Skip to content

Editorial diagram design for Claude Code, Codex, GitHub Copilot, Cursor, Factory Droid, Qoder, and Pi. 45 diagram types. Self-contained HTML + SVG. No shadows. No Mermaid slop.

fix(export): bound the rasterize wait so proxied networks don't hang (#183)

PISIT KOOLPLUKPOL5294f7decaa9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4b99a54..167215f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -438,6 +438,23 @@ jobs:
playwright install --with-deps chromium
python -c "import importlib.metadata as m; print('playwright', m.version('playwright'))"
+ # The export snippet's browser contract, enforced where Playwright and
+ # Chromium are already installed (stalled load, normal load, and
+ # non-timeout errors propagating must all hold).
+ - name: Verify export snippet stalled-load fallback
+ if: always() && matrix.os == 'ubuntu-latest' && matrix.python-version == '3.12'
+ id: export_wait
+ shell: bash
+ run: |
+ # Playwright is installed on this leg, so a SKIP means the browser
+ # contract silently went unverified -- treat it as a failure.
+ out="$(python scripts/test-export-wait.py)"
+ echo "$out"
+ case "$out" in
+ SKIP:*) echo "::error::export-wait tests skipped despite Playwright being installed" && exit 1 ;;
+ esac
+ echo "$out" | grep -q "All export-wait cases passed"
+
# The checks before the sweep: a broken linter must not be able to report
# a clean repository.
- name: Verify render linter checks
@@ -527,3 +544,4 @@ jobs:
echo "| Primitive Icons & Documentation | ${{ steps.icons.outcome == 'success' && '✅ Passed' || (steps.icons.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARY
echo "| Render Linter Self-Test | ${{ steps.render_selftest.outcome == 'success' && '✅ Passed' || (steps.render_selftest.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARY
echo "| Rendered Layout (paint oracle) | ${{ steps.render.outcome == 'success' && '✅ Passed' || (steps.render.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARY
+ echo "| Export Snippet Stalled-Load Fallback | ${{ steps.export_wait.outcome == 'success' && '✅ Passed' || (steps.export_wait.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARY
diff --git a/.maintainer-policy.json b/.maintainer-policy.json
index 55cee75..6afd3f4 100644
--- a/.maintainer-policy.json
+++ b/.maintainer-policy.json
@@ -100,6 +100,7 @@
"python3 scripts/test-verify-beeswarm.py",
"python3 scripts/verify-skin-polarity.py --all",
"python3 scripts/test-verify-skin-polarity.py",
+ "python3 scripts/test-export-wait.py",
"python3 scripts/test-verify-heatmap.py",
"python3 scripts/verify-heatmap.py --all",
"python3 scripts/build-icons.py && git diff --ignore-space-at-eol --exit-code -- skills/diagram-design/assets/icons.html skills/diagram-design/references/primitive-icons.md"
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 44bf79a..1d0bf9c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -56,6 +56,7 @@ Every validation gate below must pass before a PR is ready. They also run automa
| Every shipped motion template/example | `python3 scripts/verify-motion.py --shipped` |
| Docs/routing sync (description hooks, gallery, README tree, reference links and style-guide anchors, strict-bundler support paths, command/prompt surfaces, font-link parity, template title fallback order, SKILL.md split routing) | `python3 scripts/verify-docs-sync.py && python3 scripts/test-verify-docs-sync.py` |
| Canonical README screenshots match their example HTML sources and recorded PNG digests | `python3 scripts/verify-screenshot-freshness.py` |
+| Export snippet's stalled-webfont fallback (window.stop on timeout, warning, normal load) | `python3 scripts/test-export-wait.py` (requires Playwright; skips without it) |
| Screenshot freshness checker behaves (CRLF checkout, real source drift, raw PNG digests) | `python3 scripts/test-verify-screenshot-freshness.py` |
| README WebP previews match their PNGs, manifest, dimensions, and full-size links | `python3 scripts/test-build-readme-thumbs.py && python3 scripts/build-readme-thumbs.py --check` (requires `Pillow==12.1.1`) |
| Packaged output self-check behaves (pass + adversarial cases) | `python3 scripts/test-self-check.py` |
@@ -173,7 +174,8 @@ python3 scripts/test-plugin-package.py \
&& python3 scripts/verify-beeswarm.py --all \
&& python3 scripts/test-verify-beeswarm.py \
&& python3 scripts/verify-skin-polarity.py --all \
- && python3 scripts/test-verify-skin-polarity.py
+ && python3 scripts/test-verify-skin-polarity.py \
+ && python3 scripts/test-export-wait.py
```
### If a gate fails
diff --git a/scripts/test-export-wait.py b/scripts/test-export-wait.py
new file mode 100644
index 0000000..9484510
--- /dev/null
+++ b/scripts/test-export-wait.py
@@ -0,0 +1,268 @@
+#!/usr/bin/env python3
+"""Deterministic tests for the export snippet's stalled-load fallback.
+
+Drives the exact python snippet shipped in
+skills/diagram-design/references/export.md against local fixtures:
+
+- a stalled stylesheet request is cancelled with window.stop(), the snippet
+ warns about fallback typography, and capture completes quickly;
+- a normal load captures cleanly with no warning;
+- non-timeout errors are not swallowed by the fallback.
+
+Requires Playwright (and its Chromium); skips otherwise, matching the export
+procedure's own detection step.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import io
+import re
+import sys
+import tempfile
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+EXPORT_DOC = ROOT / "skills/diagram-design/references/export.md"
+
+# Fast-but-deterministic substitutes for the snippet's production waits.
+FAST_IDLE_TIMEOUT = "timeout=1500"
+FAST_SETTLE = "wait_for_timeout(150)"
+STALL_HOLD_SECONDS = 30 # must outlast the test's networkidle timeout
+WARNING_ANCHOR = "fallback typography"
+# The full fallback (fast timeout + settle + capture) must stay far below the
+# production path's 15s networkidle + 4s settle budget.
+FALLBACK_BUDGET_SECONDS = 15.0
+
+
+RASTERIZE_HEADING = re.compile(r"^### Rasterize\b.*$", re.M)
+NEXT_HEADING = re.compile(r"^#{1,3} ", re.M)
+PYTHON_FENCE = re.compile(r"^( *)```python[ \t]*\n(.*?)^\1```[ \t]*$", re.M | re.S)
+
+
+def select_rasterize_block(text: str) -> str:
+ """Return the python block under the Rasterize heading.
+
+ export.md carries other python blocks (the SVG color normalization, for
+ one), so the snippet is located by its section and by the code it runs,
+ never by counting blocks in the whole file.
+ """
+ heading = RASTERIZE_HEADING.search(text)
+ if heading is None:
+ raise AssertionError(f"{EXPORT_DOC.name} has no '### Rasterize' section")
+ section = text[heading.end():]
+ following = NEXT_HEADING.search(section)
+ if following is not None:
+ section = section[: following.start()]
+ blocks = [
+ "\n".join(line[len(indent):] for line in body.splitlines()) + "\n"
+ for indent, body in PYTHON_FENCE.findall(section)
+ ]
+ if len(blocks) != 1:
+ raise AssertionError(
+ "expected exactly one python block in the Rasterize section of "
+ f"{EXPORT_DOC.name}, found {len(blocks)}"
+ )
+ if "sync_playwright" not in blocks[0]:
+ raise AssertionError(
+ "the Rasterize section's python block does not use sync_playwright"
+ )
+ return blocks[0]
+
+
+def require_block_selection() -> None:
+ """The selector must ignore python blocks outside the Rasterize section."""
+ rasterize = (
+ "### Rasterize\n\nRun this:\n\n```python\n"
+ "from playwright.sync_api import sync_playwright\nprint('rasterize')\n"
+ "```\n\nAfter the block.\n"
+ )
+ other = " ```python\n import re\n svg = re.sub('a', 'b', 'a')\n ```\n"
+ doc = (
+ "# Export\n\n## SVG export procedure\n\n4. Normalize colors:\n\n"
+ f"{other}\n## PNG export procedure\n\n{rasterize}\n"
+ "### Output naming\n\n```python\nprint('later block')\n```\n"
+ )
+ selected = select_rasterize_block(doc)
+ if "print('rasterize')" not in selected or "re.sub" in selected or "later block" in selected:
+ raise AssertionError(f"selector picked the wrong python block:\n{selected}")
+ try:
+ select_rasterize_block(doc.replace("### Rasterize", "### Capture"))
+ except AssertionError:
+ pass
+ else:
+ raise AssertionError("selector accepted a doc with no Rasterize section")
+ print("OK: snippet selector finds the Rasterize block among other python blocks")
+
+
+def load_snippet() -> str:
+ snippet = select_rasterize_block(EXPORT_DOC.read_text(encoding="utf-8"))
+ for anchor in (
+ "except PlaywrightTimeoutError:",
+ 'page.evaluate("window.stop()")',
+ WARNING_ANCHOR,
+ "timeout=15000",
+ ):
+ if anchor not in snippet:
+ raise AssertionError(
+ f"export snippet is missing required anchor {anchor!r}"
+ )
+ if "except Exception" in snippet or re.search(r"except\s*:", snippet):
+ raise AssertionError(
+ "export snippet must not swallow non-timeout errors with a "
+ "broad or bare except"
+ )
+ return snippet
+
+
+class _StallHandler(BaseHTTPRequestHandler):
+ """Serves nothing: holds /stall* requests open so the load never settles."""
+
+ def do_GET(self) -> None: # noqa: N802 - stdlib naming
+ if self.path.startswith("/stall"):
+ time.sleep(STALL_HOLD_SECONDS)
+ self.send_error(500)
+ return
+ self.send_error(404)
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+
+def start_stall_server() -> ThreadingHTTPServer:
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _StallHandler)
+ server.daemon_threads = True
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ return server
+
+
+def run_snippet(snippet: str, src: Path, out: Path) -> str:
+ """Exec the doc snippet with the given argv; return captured stderr."""
+ stderr = io.StringIO()
+ old_argv, old_stderr = sys.argv, sys.stderr
+ sys.argv = ["export", str(src), str(out)]
+ try:
+ with contextlib.redirect_stderr(stderr):
+ exec(compile(snippet, str(EXPORT_DOC), "exec"), {"__name__": "export_snippet"})
+ finally:
+ sys.argv, sys.stderr = old_argv, old_stderr
+ return stderr.getvalue()
+
+
+def require_png(out: Path, name: str) -> None:
+ if not out.exists() or out.stat().st_size == 0:
+ raise AssertionError(f"{name}: expected a non-empty screenshot at {out}")
+
+
+def require_stalled_fallback(snippet: str, tmp: Path) -> None:
+ fast = snippet.replace("timeout=15000", FAST_IDLE_TIMEOUT).replace(
+ "wait_for_timeout(4000)", FAST_SETTLE
+ )
+ if fast == snippet:
+ raise AssertionError("could not shorten the snippet's production waits for the test")
+
+ server = start_stall_server()
+ try:
+ port = server.server_address[1]
+ src = tmp / "stall-fixture.html"
+ src.write_text(
+ "<!doctype html>\n<html>\n<head>\n<meta charset='utf-8'>\n"
+ f"<link rel='stylesheet' href='http://127.0.0.1:{port}/stall.css'>\n"
+ "</head>\n<body>\n"
+ "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 400 240' "
+ "width='400' height='240' role='img' aria-labelledby='stall-title'>\n"
+ "<title id='stall-title'>Stall fixture diagram</title>\n"
+ "<rect width='400' height='240' fill='#ffffff'/>\n"
+ "<text x='200' y='124' text-anchor='middle' font-family='sans-serif' "
+ "font-size='24' fill='#111111'>stall fixture</text>\n"
+ "</svg>\n</body>\n</html>\n",
+ encoding="utf-8",
+ )
+ out = tmp / "stall-fixture.png"
+
+ started = time.monotonic()
+ stderr = run_snippet(fast, src, out)
+ elapsed = time.monotonic() - started
+
+ require_png(out, "stalled-fallback")
+ if WARNING_ANCHOR not in stderr:
+ raise AssertionError(
+ f"stalled-fallback: expected a {WARNING_ANCHOR!r} warning on stderr\n{stderr}"
+ )
+ if elapsed > FALLBACK_BUDGET_SECONDS:
+ raise AssertionError(
+ f"stalled-fallback: capture took {elapsed:.1f}s, over the "
+ f"{FALLBACK_BUDGET_SECONDS:.0f}s budget - window.stop() did not "
+ "release the stalled load"
+ )
+ print(
+ f"OK: stalled stylesheet cancels via window.stop(), warns, "
+ f"and captures in {elapsed:.1f}s"
+ )
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+def require_normal_load(snippet: str, tmp: Path) -> None:
+ src = tmp / "normal-fixture.html"
+ src.write_text(
+ "<!doctype html>\n<html>\n<head>\n<meta charset='utf-8'>\n</head>\n<body>\n"
+ "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 400 240' "
+ "width='400' height='240' role='img' aria-labelledby='normal-title'>\n"
+ "<title id='normal-title'>Normal fixture diagram</title>\n"
+ "<rect width='400' height='240' fill='#ffffff'/>\n"
+ "<text x='200' y='124' text-anchor='middle' font-family='sans-serif' "
+ "font-size='24' fill='#111111'>normal fixture</text>\n"
+ "</svg>\n</body>\n</html>\n",
+ encoding="utf-8",
+ )
+ out = tmp / "normal-fixture.png"
+
+ stderr = run_snippet(snippet, src, out)
+
+ require_png(out, "normal-load")
+ if WARNING_ANCHOR in stderr:
+ raise AssertionError(f"normal-load: fallback warning fired unexpectedly\n{stderr}")
+ print("OK: normal load captures with no fallback warning")
+
+
+def require_other_errors_propagate(snippet: str, tmp: Path) -> None:
+ missing = tmp / "does-not-exist.html"
+ out = tmp / "never.png"
+ try:
+ run_snippet(snippet, missing, out)
+ except Exception as exc:
+ if type(exc).__name__ == "TimeoutError":
+ raise AssertionError(
+ "missing-source: goto failure surfaced as a TimeoutError; "
+ "the fallback caught the wrong error class"
+ )
+ print(f"OK: non-timeout failure propagates ({type(exc).__name__})")
+ return
+ raise AssertionError("missing-source: expected goto on a missing file to raise")
+
+
+def main() -> int:
+ try:
+ import playwright # noqa: F401
+ except ImportError:
+ print("SKIP: playwright is not installed; export snippet tests skipped")
+ return 0
+
+ require_block_selection()
+ snippet = load_snippet()
+ with tempfile.TemporaryDirectory(prefix="diagram-export-wait-") as raw_tmp:
+ tmp = Path(raw_tmp)
+ require_stalled_fallback(snippet, tmp)
+ require_normal_load(snippet, tmp)
+ require_other_errors_propagate(snippet, tmp)
+ print("All export-wait cases passed.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/diagram-design/references/export.md b/skills/diagram-design/references/export.md
index d92af04..aaa00a8 100644
--- a/skills/diagram-design/references/export.md
+++ b/skills/diagram-design/references/export.md
@@ -114,7 +114,7 @@ Don't auto-install. The user asked for one feature, not a system change.
Write the snippet below to a temp file and run it with `python <tmp.py> <src.html> <out.png>`:
```python
-from playwright.sync_api import sync_playwright
+from playwright.sync_api import TimeoutError as PlaywrightTimeoutError, sync_playwright
import sys, pathlib
src, out = sys.argv[1], sys.argv[2]
@@ -123,8 +123,15 @@ scale = int(sys.argv[3]) if len(sys.argv) > 3 else 2
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(device_scale_factor=scale)
- page.goto(f"file://{pathlib.Path(src).resolve()}")
- page.wait_for_load_state("networkidle")
+ page.goto(f"file://{pathlib.Path(src).resolve()}", wait_until="domcontentloaded")
+ try:
+ page.wait_for_load_state("networkidle", timeout=15000)
+ except PlaywrightTimeoutError:
+ # proxied networks may stall webfont subrequests past any deadline;
+ # cancel the outstanding load so the capture below can't block on it again
+ page.evaluate("window.stop()")
+ page.wait_for_timeout(4000)
+ print("warning: webfont request stalled - captured with fallback typography; the PNG may not match the intended fonts", file=sys.stderr)
svg = page.locator("svg").first
# Release every clipping ancestor (local scroller, overflow:hidden chrome)
# so an SVG wider than its frame is captured whole.
@@ -133,6 +140,8 @@ with sync_playwright() as p:
browser.close()
```
+If the `networkidle` wait times out (a stalled font or stylesheet behind a proxy), the snippet cancels the outstanding load with `window.stop()` and captures with fallback typography, printing a warning to stderr — pass that warning on to the user. Any other error propagates and fails the export normally.
+
Default `device_scale_factor=2` for crisp output. Accept `1` for compact assets or `3` for print/retina hero use, passed as a third CLI arg.
The overflow release matters for the wide presets. `min-width` equals the viewBox width (see [`output-spec.md`](output-spec.md)), so a `doc-wide` or `slide-16x9` SVG is 1280px inside a 1200px frame, and its `.diagram-container` scroller clips the last 80px on screen. The screenshot covers the SVG's box but not what an ancestor clipped, so without the release the PNG comes out full size with a blank right edge. This is the screen-side counterpart of the templates' `@media print` rule.