ralph: story-6 Playwright screenshot skill for OpenRCT2 web

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Mike LiuandClaude Opus 4.6 committed 2026-02-25 00:19:29 +00:00
1 parent a826e2f6f7
commit b19fea3209
4 files changed
+201 -1

No files matched your search

+1 -1
View File
@@ -49,7 +49,7 @@
"title": "Playwright screenshot skill for OpenRCT2 web",
"description": "Create scripts/reskin/screenshot_game.py — a Playwright script that:\n1. Starts the OpenRCT2 web server (scripts/serve-emscripten.py) pointing at a directory containing the built wasm output\n2. Launches headless Chromium with SharedArrayBuffer support (args: --enable-features=SharedArrayBuffer)\n3. Navigates to index.html, waits for the canvas to appear (selector: canvas#canvas with display != none)\n4. Waits for the game to load (the #loadingWebassembly element gets removed when loading completes — wait for it to be detached)\n5. Takes a screenshot and saves to a specified output path\n6. Shuts down browser and server\n\nCLI: python3 screenshot_game.py --serve-dir <dir> --output <path.png> [--port 8000] [--wait-seconds 10]\n\nUse playwright.sync_api (Python sync API). The server needs COOP/COEP headers (serve-emscripten.py handles this).\n\nIMPORTANT: The script must handle the case where no wasm build exists gracefully — print a clear error message and exit 1. Do NOT try to build the wasm.\n\nTest: Create scripts/reskin/test_screenshot_game.py with at least 2 tests:\n- test_server_starts_and_stops: verify the COOP/COEP server can start on a temp dir and respond to requests\n- test_missing_serve_dir: verify graceful error when dir doesn't exist\n\nDo NOT test the full Playwright flow in unit tests (requires wasm build). The integration test is manual.",
"verify": "cd /workspace/OpenRCT2-Web && python3 -m pytest scripts/reskin/test_screenshot_game.py -v",
"status": "pending",
"status": "passed",
"retries": 0
},
{
+13
View File
@@ -57,3 +57,16 @@ Created scripts/reskin/test_reskin.py with 6 tests — all pass.
Verification passed: pytest scripts/reskin/test_reskin.py -v (6/6 passed) + --list-categories (6 categories).
Status: PASSED
Status: PASSED
--- Iteration 6 | story-6 | 2026-02-25 00:18:04 ---
Created scripts/reskin/screenshot_game.py — Playwright screenshot script for OpenRCT2 web.
Features: COOP/COEP server (reuses pattern from serve-emscripten.py), headless Chromium with
SharedArrayBuffer support, waits for canvas#canvas visible + #loadingWebassembly detached,
graceful error on missing serve dir.
CLI: --serve-dir, --output, --port, --wait-seconds.
Created scripts/reskin/test_screenshot_game.py with 2 tests:
- test_server_starts_and_stops: verifies COOP/COEP headers and content serving
- test_missing_serve_dir: verifies exit 1 with clear error message
Note: had to pip install playwright (browsers were pre-installed at /root/.cache/ms-playwright/).
Verification passed: pytest scripts/reskin/test_screenshot_game.py -v (2/2 passed).
Status: PASSED
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""Take a screenshot of the OpenRCT2 web game using Playwright.
Starts a local COOP/COEP server, launches headless Chromium, waits for
the game canvas to appear and loading to finish, then captures a screenshot.
Usage:
python3 screenshot_game.py --serve-dir build/www --output screenshot.png
python3 screenshot_game.py --serve-dir build/www --output screenshot.png --port 9000 --wait-seconds 15
"""
import argparse
import os
import sys
import threading
import time
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
class COOPCOEPHandler(SimpleHTTPRequestHandler):
"""HTTP handler that adds Cross-Origin Isolation headers."""
def end_headers(self):
self.send_header("Cross-Origin-Opener-Policy", "same-origin")
self.send_header("Cross-Origin-Embedder-Policy", "require-corp")
self.send_header("Cross-Origin-Resource-Policy", "cross-origin")
super().end_headers()
def log_message(self, format, *args):
"""Suppress request logging to keep output clean."""
pass
def start_server(directory, host="127.0.0.1", port=8000):
"""Start a COOP/COEP HTTP server in a background thread.
Returns (server, thread) so the caller can shut it down.
"""
handler = partial(COOPCOEPHandler, directory=directory)
server = ThreadingHTTPServer((host, port), handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
return server, thread
def take_screenshot(port=8000, output_path="screenshot.png", wait_seconds=10):
"""Launch headless Chromium and screenshot the OpenRCT2 game.
Requires playwright to be installed with Chromium browser.
"""
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(
headless=True,
args=["--enable-features=SharedArrayBuffer"],
)
page = browser.new_page(viewport={"width": 1280, "height": 720})
url = f"http://127.0.0.1:{port}/index.html"
page.goto(url, wait_until="domcontentloaded")
# Wait for the canvas to become visible
page.wait_for_selector(
"canvas#canvas",
state="visible",
timeout=wait_seconds * 1000,
)
# Wait for loading to finish — #loadingWebassembly is removed when done
try:
page.wait_for_selector(
"#loadingWebassembly",
state="detached",
timeout=wait_seconds * 1000,
)
except Exception:
# If the element never existed or was already gone, that's fine
pass
# Give the game a moment to render a frame
time.sleep(2)
page.screenshot(path=output_path, full_page=False)
print(f"Screenshot saved to {output_path}")
browser.close()
def main():
parser = argparse.ArgumentParser(
description="Take a screenshot of the OpenRCT2 web game"
)
parser.add_argument(
"--serve-dir", required=True,
help="Directory containing the built wasm output (index.html etc.)"
)
parser.add_argument(
"--output", required=True,
help="Output path for the screenshot PNG"
)
parser.add_argument(
"--port", type=int, default=8000,
help="Port for the local server (default: 8000)"
)
parser.add_argument(
"--wait-seconds", type=int, default=10,
help="Max seconds to wait for game to load (default: 10)"
)
args = parser.parse_args()
# Validate serve dir exists
if not os.path.isdir(args.serve_dir):
print(f"ERROR: serve directory does not exist: {args.serve_dir}")
sys.exit(1)
# Start server
server, thread = start_server(args.serve_dir, port=args.port)
print(f"Server started on http://127.0.0.1:{args.port}")
try:
take_screenshot(
port=args.port,
output_path=args.output,
wait_seconds=args.wait_seconds,
)
finally:
server.shutdown()
print("Server stopped.")
if __name__ == "__main__":
main()
+53
View File
@@ -0,0 +1,53 @@
"""Tests for screenshot_game.py (server and error handling only).
Does NOT test the full Playwright flow — that requires a wasm build.
"""
import os
import sys
import tempfile
import time
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from screenshot_game import start_server
def test_server_starts_and_stops():
"""Verify the COOP/COEP server can start, serve, and stop cleanly."""
with tempfile.TemporaryDirectory() as d:
# Create a minimal index.html to serve
with open(os.path.join(d, "index.html"), "w") as f:
f.write("<html><body>test</body></html>")
server, thread = start_server(d, host="127.0.0.1", port=18765)
try:
# Give server a moment to start
time.sleep(0.2)
# Fetch the page
resp = urllib.request.urlopen("http://127.0.0.1:18765/index.html")
body = resp.read().decode()
assert "test" in body
# Verify COOP/COEP headers
coop = resp.headers.get("Cross-Origin-Opener-Policy")
coep = resp.headers.get("Cross-Origin-Embedder-Policy")
assert coop == "same-origin"
assert coep == "require-corp"
finally:
server.shutdown()
def test_missing_serve_dir():
"""Verify graceful error when serve directory doesn't exist."""
import subprocess
result = subprocess.run(
[sys.executable, os.path.join(os.path.dirname(__file__), "screenshot_game.py"),
"--serve-dir", "/nonexistent/path/abc123",
"--output", "/tmp/test.png"],
capture_output=True, text=True,
)
assert result.returncode == 1
assert "does not exist" in result.stderr or "does not exist" in result.stdout