Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

feat(pixel): let preview inspection start on another page of the snapshot (#8297)

Mike Bradleyeb83e43ebd45
diff --git a/ods/extensions/services/pixel-agent/COMPLETION-RELIABILITY.md b/ods/extensions/services/pixel-agent/COMPLETION-RELIABILITY.md
index e4badb051..f1be5e0e4 100644
--- a/ods/extensions/services/pixel-agent/COMPLETION-RELIABILITY.md
+++ b/ods/extensions/services/pixel-agent/COMPLETION-RELIABILITY.md
@@ -269,7 +269,9 @@ descendants (an `aria-hidden` icon or chevron, a hidden alternate label, a
`display: none` badge) never turn a correct name into a missing one; a hidden
control keeps its hidden-inclusive name. The latest receipt bound to the current
snapshot decides, whether its steps passed or failed or it came back incomplete
-for an untested show/hide change (its `details.receipt`, below). That holds
+for an untested show/hide change (its `details.receipt`, below). Only an
+entry-page receipt counts: one of another page (`page`) lists that page's
+controls, which can neither show nor rule out the entry page's. That holds
whatever `error` the harness attaches to the `after_tool_call` event: OpenClaw
2026.6.33 sets one on every error result of a direct call (tower2's transport),
and a thrown call has no receipt to bind. "Named exactly" compares
diff --git a/ods/extensions/services/pixel-agent/host/Dockerfile.inspection b/ods/extensions/services/pixel-agent/host/Dockerfile.inspection
index 9babd401c..d0b673746 100644
--- a/ods/extensions/services/pixel-agent/host/Dockerfile.inspection
+++ b/ods/extensions/services/pixel-agent/host/Dockerfile.inspection
@@ -20,6 +20,7 @@ LABEL org.osmantic.ods.component="pixel-preview-inspection" \
org.osmantic.ods.inspection.download="snapshot-download-v1" \
org.osmantic.ods.inspection.press="trusted-key-press-v1" \
org.osmantic.ods.inspection.paint="element-paint-v1" \
+ org.osmantic.ods.inspection.page="snapshot-page-v1" \
org.osmantic.ods.inspection.screenshot="viewport-screenshot-v1" \
org.osmantic.ods.inspection.playwright="1.62.0"
USER 65534:65534
diff --git a/ods/extensions/services/pixel-agent/host/preview-inspection-protocol.md b/ods/extensions/services/pixel-agent/host/preview-inspection-protocol.md
index 3b84c3a03..9078ea081 100644
--- a/ods/extensions/services/pixel-agent/host/preview-inspection-protocol.md
+++ b/ods/extensions/services/pixel-agent/host/preview-inspection-protocol.md
@@ -8,7 +8,9 @@ socket or browser authority.
## Request
The plugin sends one JSON object with `schemaVersion: 1`, `action: "inspect"`,
-`siteId`, the full snapshot `sha256`, `viewport: {width, height}`, and `steps`.
+`siteId`, the full snapshot `sha256`, `viewport: {width, height}`, and `steps`,
+plus an optional `page` that names the page of the same snapshot to start on
+instead of its entry page (see "Page" below).
Each step has `action` (`assert-visible`, `assert-hidden`, `assert-text`,
`click`, `select-option`, `fill`, `download`, `press`, or `assert-painted`)
and `locator`. `assert-text` adds `expectedText`; `select-option` and `fill`
@@ -148,14 +150,14 @@ visible. Publication is byte-only and renders nothing, so the capsule reports
the painted palette with every receipt it builds.
After the step context is closed and its receipt is final, the capsule loads
-the same snapshot once more in a separate context of the same browser: a fixed
-1280x720 desktop viewport, default (light) color scheme, device scale 0.25.
-It uses the same loopback server, request guard, navigation limit, and popup,
-download and websocket blocking, and registers no page-error listener. It
-waits 100 ms after `load`, takes a 320x180 PNG screenshot of the viewport (one
-device pixel per 4x4 CSS pixels) and decodes it with the standard library. The
-page as first loaded is captured, never the state left by the inspected
-clicks, and never hover or focus styles.
+the same page of the snapshot once more in a separate context of the same
+browser: a fixed 1280x720 desktop viewport, default (light) color scheme,
+device scale 0.25. It uses the same loopback server, request guard, navigation
+limit, and popup, download and websocket blocking, and registers no page-error
+listener. It waits 100 ms after `load`, takes a 320x180 PNG screenshot of the
+viewport (one device pixel per 4x4 CSS pixels) and decodes it with the
+standard library. The page as first loaded is captured, never the state left
+by the inspected clicks, and never hover or focus styles.
Each pixel's exact color goes to one fixed bucket. A color with chroma under
26/255 is neutral and named by HSL lightness: `black` (<0.13), `dark gray`
@@ -236,7 +238,8 @@ quoted evidence copy; when an exact role/name locator matched nothing and a
control of that role shows the locator's name as its text (or differs only in
letter case), the locator feedback states the actual name and what supplied it.
The plugin checks owner-requested control names against them (see
-`COMPLETION-RELIABILITY.md`). A host keeps producing receipts without
+`COMPLETION-RELIABILITY.md`), from entry-page receipts only: a `page` receipt
+lists another page's controls. A host keeps producing receipts without
`controls` until the installer rebuilds the inspection image.
## Host custody and isolation
@@ -275,8 +278,12 @@ read-only root, UID/GID 65534, all capabilities dropped, no-new-privileges,
256 MiB temporary filesystem. No host mounts, sockets, credentials, or host
URLs enter it. The only stdin is the validated plan and base64 immutable file
map. The loopback server reproduces production iframe sandbox, CSP, MIME/UTF-8,
-and CORS/security headers. Foreign requests, extra navigation, popups, and
-downloads are blocked; service workers are disabled.
+and CORS/security headers. The request guard admits at most two navigations,
+the fixed wrapper document and the one page it frames: the site entry
+(`/<siteId>/`) or the requested `page`. Only an explicit download step adds
+one, to its own snapshot file. Foreign requests, any other navigation (a link
+to another page of the same snapshot included), popups, and downloads are
+blocked; service workers are disabled.
The runner permits at most 45 seconds and 32 KiB of receipt output, plus one
bounded JPEG when the request directs a viewport screenshot (see "Viewport
@@ -606,6 +613,73 @@ schema, the Python/JavaScript scope, bounds and plan hash, capsule summaries as
receipts, forged paint evidence, feedback, the unchanged-fingerprint note and
the evidence policy.
+## Page
+
+An inspection loads one page: without `page`, the snapshot's entry page,
+exactly as before. A multi-page site ("a three-page bakery site: home, menu and
+contact") needs its other pages checked too, so a request may name one. `page`
+is the path of a published `.html` file relative to the site root, such as
+`menu.html` or `about/team.html`, or a folder ending in `/` for that folder's
+`index.html` (`blog/` is `blog/index.html`), the rule by which the capsule's
+loopback server resolves URL paths (`snapshot_file`).
+
+`page`, with a trailing `/` read as `/index.html`, must be a name the snapshot's
+file map can hold (`snapshot_name`, shared with `validate_bundle`): at most 512
+characters and 12 segments of at most 128 ASCII letters, digits, `.`, `_`, `-`,
+`[` and `]`, ending in `.html`. That excludes a leading `/`, `\`, NUL and other
+control characters, `.` and `..` segments, empty segments, a scheme, query or
+fragment, percent-encoding, hidden names (a leading `.`, which the publisher
+skips) and the reserved `__ods_` and `__pycache__` names. The plugin applies
+the same rules (`workspace-preview-inspect.mjs`), but only the immutable file
+map shows whether that file exists. The broker binds `page` to it after reading
+the snapshot and before any browser runs; a page that names no file of it
+returns a bound `page_not_found` failure. The capsule checks it again in
+`validate_bundle`. The publisher-side export never sees `page`, since it reads
+the whole snapshot either way, so an older export helper keeps working.
+
+`page` changes only where the inspection starts. The wrapper document frames
+`/<siteId>/` plus the URL-quoted page instead of `/<siteId>/`, and the request
+guard admits that page as the one entry navigation in place of the site entry,
+which is then refused like any other navigation. Links between pages are not
+followed: a click or key that navigates to another page is blocked, recorded in
+`blockedRequests` and fails the receipt, exactly as before. Asset requests,
+popups, downloads, the CSP, the iframe sandbox and every capsule isolation
+property above are unchanged. A download step's `path` stays relative to the
+site root, and the rendered palette is captured from the same page.
+
+`page` is part of the plan, so `planSha256` binds it; a request without it
+validates and hashes exactly as before, and `schemaVersion` stays 1. Every
+receipt of a page plan, passed or failed, carries the same `page`, and its
+scope ends `Only the requested page of this snapshot was loaded; links between
+pages were not followed.` Receipts of plans without `page` carry neither. The
+broker and the plugin reject a receipt whose `page` differs from the
+request's, and the tool names the page in its result (`Preview inspection of
+page "menu.html" passed.`). A passing page plan counts as browser evidence for
+its snapshot like any other inspection, while owner-requested control names are
+checked against entry-page receipts only (see "Load-time control names"). An
+untested show/hide change gets corrective steps on the same page, without the
+entry page's outline.
+
+The immutable capsule must advertise
+`org.osmantic.ods.inspection.page=snapshot-page-v1`. The broker checks it
+before reading the snapshot, and the installer requires it, as for paint. An
+older image returns a bound `unsupported_capability` failure without executing
+the plan, and the tool asks to inspect the entry page without `page` until the
+inspector is updated; deploy plugin, broker and rebuilt capsule together.
+
+`test_preview_inspection_page.py` covers the page rules, unchanged legacy
+hashes and scope, the file-map binding, the broker's label check, its
+`page_not_found` refusal before any capsule runs, the export without `page` on
+both transports and the receipt binding; through a scripted browser it loads
+the wrapper from the capsule's loopback server and checks its `src`, the
+guard's one entry navigation, a blocked click-through to a sibling page, the
+receipt and the palette. With the opt-in Chromium or image settings above it
+also checks every page of a small multi-page site and a link that is not
+followed. `inspection_page.test.mjs` checks the plugin rules, hash, scope and
+failure receipt against Python's, the schema and description, receipt binding,
+the not-found, unsupported, passing and blocked results, the evidence policy
+and the corrective steps.
+
## Viewport screenshot
A model that ODS declares able to read images can look at its own published
diff --git a/ods/extensions/services/pixel-agent/host/preview_inspection.py b/ods/extensions/services/pixel-agent/host/preview_inspection.py
index a7a84b8a6..2fc02f7b9 100644
--- a/ods/extensions/services/pixel-agent/host/preview_inspection.py
+++ b/ods/extensions/services/pixel-agent/host/preview_inspection.py
@@ -22,11 +22,13 @@ from preview_inspection_protocol import (
MAX_REQUEST_FRAME,
MAX_RESULT,
MAX_SCREENSHOT_RESULT,
+ MissingPage,
SELECT_CAPABILITY,
FILL_CAPABILITY,
DOWNLOAD_CAPABILITY,
PRESS_CAPABILITY,
PAINT_CAPABILITY,
+ PAGE_CAPABILITY,
SCREENSHOT_CAPABILITY,
canonical,
exact,
@@ -308,6 +310,13 @@ def inspect_request(request, config, cancelled=None):
b'', timeout=5, limit=128, cancelled=cancelled)
if capability.decode().strip() != PAINT_CAPABILITY:
return failure('unsupported_capability', request)
+ if 'page' in request:
+ capability = bounded_process(
+ [*docker_prefix(config), 'image', 'inspect', '--format',
+ '{{index .Config.Labels "org.osmantic.ods.inspection.page"}}', config['imageId']],
+ b'', timeout=5, limit=128, cancelled=cancelled)
+ if capability.decode().strip() != PAGE_CAPABILITY:
+ return failure('unsupported_capability', request)
# The snapshot and its export never carry the screenshot directive, so an
# older publisher-side export helper keeps working and the bundle binds the
# plan alone. An image without the label still runs the plan; only the
@@ -321,8 +330,13 @@ def inspect_request(request, config, cancelled=None):
b'', timeout=5, limit=128, cancelled=cancelled)
if capability.decode().strip() != SCREENSHOT_CAPABILITY:
directive, omitted = None, {"status": "omitted", "reason": "capability_missing"}
+ # The export reads the whole snapshot, so it never sees the page either and
+ # an older export helper keeps working. The page is bound to that
+ # snapshot's file map here, before any browser runs; one that names no
+ # file of the snapshot is refused.
+ snapshot = {key: value for key, value in plan.items() if key != "page"}
if config["transport"] == "local":
- bundle = snapshot_bundle(config["snapshotRoot"], plan, config["ownerUid"])
+ bundle = snapshot_bundle(config["snapshotRoot"], snapshot, config["ownerUid"])
else:
raw = bounded_process(
[
@@ -334,15 +348,21 @@ def inspect_request(request, config, cancelled=None):
"/source/preview_inspection.py",
"export",
],
- canonical(plan),
+ canonical(snapshot),
timeout=15,
limit=MAX_BUNDLE,
cancelled=cancelled,
)
bundle = strict_json(raw)
bound, _files = validate_bundle(bundle)
- if bound != plan:
+ if bound != snapshot:
raise Invalid("snapshot mismatch")
+ if "page" in plan:
+ bundle = {**bundle, "request": plan}
+ try:
+ validate_bundle(bundle)
+ except MissingPage:
+ return failure("page_not_found", request)
if directive is not None:
bundle = {**bundle, "request": {**plan, "screenshot": directive}}
name = "ods-preview-inspection-" + uuid.uuid4().hex
@@ -365,6 +385,7 @@ def inspect_request(request, config, cancelled=None):
or result.get("siteId") != request["siteId"]
or result.get("sha256") != request["sha256"]
or result.get("planSha256") != plan_hash(request)
+ or result.get("page") != request.get("page")
or result.get("status") not in ("passed", "failed")
or result.get("scope") != inspection_scope(request)
or len(canonical(result)) > MAX_RESULT
diff --git a/ods/extensions/services/pixel-agent/host/preview_inspection_capsule.py b/ods/extensions/services/pixel-agent/host/preview_inspection_capsule.py
index 85c5435df..f74c99c5e 100644
--- a/ods/extensions/services/pixel-agent/host/preview_inspection_capsule.py
+++ b/ods/extensions/services/pixel-agent/host/preview_inspection_capsule.py
@@ -983,12 +983,18 @@ def capture_screenshot(cdp, page, request, started):
return omitted_screenshot("too_large")
-def wrapper_document(prefix):
+def entry_path(prefix, request):
+ """URL path of the page an inspection starts on: the site entry, or the
+ requested page, which validate_bundle bound to a file of this snapshot."""
+ return prefix + urllib.parse.quote(request.get("page", ""))
+
+
+def wrapper_document(entry):
# Fixed and script-free: page script exceptions therefore come only from
# the sandboxed preview frame or a frame the preview itself created.
return (
f"<!doctype html><style>html,body{{margin:0;height:100%;overflow:hidden}}iframe{{border:0;width:100%;height:100%}}</style>"
- f'<iframe name="inspection" sandbox="{SANDBOX}" src="{prefix}"></iframe>'
+ f'<iframe name="inspection" sandbox="{SANDBOX}" src="{entry}"></iframe>'
).encode()
@@ -1109,10 +1115,11 @@ def snapshot_file(path, prefix, files):
return name if name in files else None
-def guard_requests(context, page, origin, prefix, blocked, download=None, download_urls=(), *, files=()):
+def guard_requests(context, page, origin, prefix, blocked, download=None, download_urls=(), *, files=(), entry):
"""Allow only GETs of the wrapper and this site's files from the loopback
- server, and at most the wrapper and site-entry navigations. Everything
- else, popups, downloads and websockets are recorded (bounded) and stopped."""
+ server, and at most the wrapper and entry navigations; `entry` is the URL
+ path of the page the wrapper frames (entry_path). Everything else, popups,
+ downloads and websockets are recorded (bounded) and stopped."""
navigation_count = 0
def route_handler(route):
@@ -1133,7 +1140,7 @@ def guard_requests(context, page, origin, prefix, blocked, download=None, downlo
navigation_count += 1
safe = (
safe
- and ((navigation_count <= 2 and req.url in (origin + "/__ods_inspection__.html", origin + prefix))
+ and ((navigation_count <= 2 and req.url in (origin + "/__ods_inspection__.html", origin + entry))
or (download is not None and download.active and req.method == 'GET' and req.url == download.url))
)
if safe:
@@ -1180,8 +1187,9 @@ def guard_requests(context, page, origin, prefix, blocked, download=None, downlo
)
-def capture_palette(browser, origin, prefix, files=()):
- """Rendered colors of a fresh load at the fixed desktop viewport, or None.
+def capture_palette(browser, origin, prefix, files=(), *, entry):
+ """Rendered colors of a fresh load of the inspected page (`entry`) at the
+ fixed desktop viewport, or None.
Its own context: the step context and its page-error listener never see
this load, and a request blocked here voids only the palette."""
@@ -1195,14 +1203,14 @@ def capture_palette(browser, origin, prefix, files=()):
try:
page = context.new_page()
page.set_default_timeout(PALETTE_TIMEOUT_MS)
- guard_requests(context, page, origin, prefix, blocked, files=files)
+ guard_requests(context, page, origin, prefix, blocked, files=files, entry=entry)
page.goto(
origin + "/__ods_inspection__.html",
wait_until="load",
timeout=PALETTE_TIMEOUT_MS,
)
frame = page.frame(name="inspection")
- if frame is None or frame.url != origin + prefix:
+ if frame is None or frame.url != origin + entry:
return None
page.wait_for_timeout(PALETTE_SETTLE_MS)
image = page.screenshot(type="png", scale="device", timeout=PALETTE_TIMEOUT_MS)
@@ -1243,6 +1251,7 @@ def run_browser(bundle, playwright_factory=None):
started = time.monotonic()
request, files = validate_bundle(bundle)
prefix = "/" + request["siteId"] + "/"
+ entry = entry_path(prefix, request)
blocked = []
page_errors = PageErrors()
@@ -1256,7 +1265,7 @@ def run_browser(bundle, playwright_factory=None):
path = urllib.parse.urlsplit(self.path).path
name = ''
if path == "/__ods_inspection__.html":
- body = wrapper_document(prefix)
+ body = wrapper_document(entry)
mime = "text/html"
elif (name := snapshot_file(path, prefix, files)) is not None:
body = files[name]
@@ -1327,7 +1336,7 @@ def run_browser(bundle, playwright_factory=None):
page.set_default_timeout(2000)
download = SnapshotDownload(browser, context, page, blocked) if request['steps'][-1]['action'] == 'download' else None
download_urls = {origin + prefix + name for name in files if name.lower().endswith(('.pdf', '.zip'))}
- guard_requests(context, page, origin, prefix, blocked, download, download_urls, files=files)
+ guard_requests(context, page, origin, prefix, blocked, download, download_urls, files=files, entry=entry)
# Registered before navigation so startup exceptions are included.
# Page-scoped (not context-wide): blocked popups are never recorded.
page.on("pageerror", page_errors.record)
@@ -1337,7 +1346,7 @@ def run_browser(bundle, playwright_factory=None):
if blocked:
raise BlockedRequest()
frame = page.frame(name="inspection")
- if frame is None or frame.url != origin + prefix:
+ if frame is None or frame.url != origin + entry:
raise Invalid("preview frame unavailable")
# Isolated world prevents author JS overriding querySelector,
# getComputedStyle, checkVisibility, or receipt construction.
@@ -1762,6 +1771,9 @@ def run_browser(bundle, playwright_factory=None):
"siteId": request["siteId"],
"sha256": request["sha256"],
"planSha256": plan_hash(request),
+ # A page plan's receipt names its page; the entry page's never
+ # carries one, as before.
+ **({"page": request["page"]} if "page" in request else {}),
"viewport": request["viewport"],
"steps": results,
"diagnostics": diagnostics,
@@ -1775,7 +1787,7 @@ def run_browser(bundle, playwright_factory=None):
palette = None
if time.monotonic() - started < PALETTE_START_BUDGET_S:
try:
- palette = capture_palette(browser, origin, prefix, files)
+ palette = capture_palette(browser, origin, prefix, files, entry=entry)
except Exception:
pass
if palette:
diff --git a/ods/extensions/services/pixel-agent/host/preview_inspection_protocol.py b/ods/extensions/services/pixel-agent/host/preview_inspection_protocol.py
index 9fcc44528..c0003124e 100644
--- a/ods/extensions/services/pixel-agent/host/preview_inspection_protocol.py
+++ b/ods/extensions/services/pixel-agent/host/preview_inspection_protocol.py
@@ -51,6 +51,12 @@ PAINT_SCOPE = " Pixel paint was checked only for explicit assert-painted steps,
# only of fill. workspace-preview-inspect.mjs mirrors both exactly.
STEP_SCOPE = "Only the listed steps were tested, each only as stated here. CSS layout visibility, normalized visible-text assertions and click dispatches do not test pixel paint; no step tests occlusion, clipping, a full accessibility audit, or overall functionality."
PRESS_FILL_SCOPE = " Native non-sensitive text and number fields were filled only with explicit synthetic values; number constraint flags are observations, not a claim of form validity. Fill sends no key events and does not submit forms."
+# An optional `page` starts the inspection on another page of the same
+# snapshot instead of its entry page. Page plans run only on a capsule labelled
+# for them, and their receipts name the page. workspace-preview-inspect.mjs
+# mirrors the scope and the page rules exactly.
+PAGE_CAPABILITY = "snapshot-page-v1"
+PAGE_SCOPE = " Only the requested page of this snapshot was loaded; links between pages were not followed."
# One viewport screenshot after the steps, only when the plugin asks for it
# (a model that accepts images). The directive sits beside the plan, never in
# it: plan_hash, scope and every receipt field stay those of the plan alone.
@@ -76,13 +82,18 @@ def inspection_scope(request):
scope += (PRESS_FILL_SCOPE if pressed else FILL_SCOPE) if any(s['action'] == 'fill' for s in request['steps']) else ''
scope += PRESS_SCOPE if pressed else ''
scope += PAINT_SCOPE if any(s['action'] == 'assert-painted' for s in request['steps']) else ''
- return scope + (DOWNLOAD_SCOPE if request['steps'][-1]['action'] == 'download' else '')
+ scope += DOWNLOAD_SCOPE if request['steps'][-1]['action'] == 'download' else ''
+ return scope + (PAGE_SCOPE if 'page' in request else '')
class Invalid(ValueError):
pass
+class MissingPage(Invalid):
+ """The requested page is not a file of this immutable snapshot."""
+
+
def read_only_wsl_docker(binary, info):
"""Verify Desktop's immutable ISO despite its CLI/directory 0775 modes."""
binary = Path(binary)
@@ -281,11 +292,39 @@ def printable(value, chars, size):
)
+def snapshot_name(name):
+ """A file path an immutable snapshot may hold: relative POSIX segments of
+ ASCII name characters, so no hidden (leading ".") or reserved names."""
+ return (
+ isinstance(name, str)
+ and len(name) <= 512
+ and len(name.split("/")) <= 12
+ and all(
+ re.fullmatch(r"(?!__ods_)[A-Za-z0-9_\[][A-Za-z0-9._\[\]-]{0,127}", p)
+ and p not in (".", "..", "__pycache__")
+ for p in name.split("/")
+ )
+ )
+
+
+def page_file(page):
+ """The snapshot file a page names. A trailing "/" names that folder's
+ index.html, as preview_inspection_capsule.snapshot_file serves it."""
+ return page + "index.html" if page.endswith("/") else page
+
+
def validate_request(value):
keys = ("schemaVersion", "action", "siteId", "sha256", "viewport", "steps")
- exact(value, (*keys, "screenshot") if isinstance(value, dict) and "screenshot" in value else keys)
+ optional = tuple(key for key in ("page", "screenshot") if isinstance(value, dict) and key in value)
+ exact(value, (*keys, *optional))
if "screenshot" in value:
validate_screenshot_directive(value["screenshot"])
+ if "page" in value and (
+ not isinstance(value["page"], str)
+ or not snapshot_name(page_file(value["page"]))
+ or not page_file(value["page"]).endswith(".html")
+ ):
+ raise Invalid("invalid page")
if (
type(value["schemaVersion"]) is not int
or value["schemaVersion"] != 1
@@ -382,17 +421,7 @@ def validate_bundle(bundle):
for entry in files:
exact(entry, ("path", "base64"))
name = entry["path"]
- if (
- not isinstance(name, str)
- or len(name) > 512
- or len(name.split("/")) > 12
- or name <= previous
- or any(
- not re.fullmatch(r"(?!__ods_)[A-Za-z0-9_\[][A-Za-z0-9._\[\]-]{0,127}", p)
- or p in (".", "..", "__pycache__")
- for p in name.split("/")
- )
- ):
+ if not snapshot_name(name) or name <= previous:
raise Invalid("invalid file path")
if (
not isinstance(entry["base64"], str)
@@ -416,6 +445,8 @@ def validate_bundle(bundle):
result[name], previous = data, name
if "index.html" not in result or digest.hexdigest() != request["sha256"]:
raise Invalid("snapshot mismatch")
+ if "page" in request and page_file(request["page"]) not in result:
+ raise MissingPage("page not in snapshot")
download = request['steps'][-1]
if download['action'] == 'download':
data = result.get(download['path'])
@@ -435,6 +466,7 @@ def failure(code, request=None):
"siteId": request["siteId"],
"sha256": request["sha256"],
"planSha256": plan_hash(request),
+ **({"page": request["page"]} if "page" in request else {}),
}
if request
else {}
diff --git a/ods/extensions/services/pixel-agent/plugin/agent-skills.mjs b/ods/extensions/services/pixel-agent/plugin/agent-skills.mjs
index 9d140a164..4ec36c827 100644
--- a/ods/extensions/services/pixel-agent/plugin/agent-skills.mjs
+++ b/ods/extensions/services/pixel-agent/plugin/agent-skills.mjs
@@ -30,7 +30,7 @@ Preserve files/framework; read before edit/apply_patch. Use write for authored c
Workspace execution is not host installation. Use workdir, not shell directory chains. After timeouts, observe the same exec handle; never duplicate it. Parallelize independent actions only.
For source maps/copies, use the final executed files, parse maps back and check required keys/values. Compare decoded/raw bytes, including trailing newlines; filenames are not contents. For requested logs, capture real process stdout/stderr as bytes, save and display them, and retain exit status. Never handwrite a transcript after a failed command. Regenerate dependent artifacts after source changes; finish comparisons before publishing.
For CLI work, run documented arguments on real files; inspect exit status, stdout, stderr and artifacts; imports or calls to main do not verify its entry point. Derive normal/rejected cases from requested keys, paths and corrections. Distinguish ordinary file endings from malformed records. Retain and fix matching failures; never replace them with easier cases or normalize forbidden values. Preserve inputs and protected tests.
-For new projects without a destination, use a descriptive Playground folder; keep existing locations. Sandbox servers are not browser-accessible. For publication, run the framework's real build and publish its output directory containing index.html with pixel_ods_workspace_preview. Never handwrite dist files. Preview URLs have a site prefix: use relative asset URLs (for Vite, --base=./; Next static export assetPrefix:"."). Verify nested routes too. Preserve the framework; index.html may exist only in build output. Verify scripts/styles load and the application boots at the exact published URL; exercise requested controls with an available browser. Share its verified URL. HTTP readback alone does not prove behavior. Changes after publication require a new snapshot.
+For new projects without a destination, use a descriptive Playground folder; keep existing locations. Sandbox servers are not browser-accessible. For publication, run the framework's real build and publish its output directory containing index.html with pixel_ods_workspace_preview. Never handwrite dist files. Preview URLs have a site prefix: use relative asset URLs (for Vite, --base=./; Next static export assetPrefix:"."). Verify nested routes too (inspector page). Preserve the framework; index.html may exist only in build output. Verify scripts/styles load and the application boots at the exact published URL; exercise requested controls with an available browser. Share its verified URL. HTTP readback alone does not prove behavior. Changes after publication require a new snapshot.
${NAMED_ITEM_CONTRACT}
${PREVIEW_RUNTIME_CONTRACT}`,
research: `Research and source evidence
@@ -45,7 +45,7 @@ Preserve work across compaction/interruption. Recover requirements via pixel_ods
Report evidence limits: compilation, imports, HTTP readback and project behavior are distinct checks. State untested OS/GPU/model combinations; plans, submitted jobs and model narrative do not prove completion.
In the Docker sandbox, node (no npm) checks JavaScript offline: run node --check on each script; test pure logic with node --test and explicit test files from the project directory, or with a small harness script that stubs document, window and the canvas 2D context (for example, count save/restore balance per frame); time hot loops with performance.now over many frames, once before and once after an edit. A harness prints what it measured and exits 1 only when a check fails; a node run that exits 1 with output is a test result to fix, not a tool failure. Wrap long harnesses in timeout 60; never start servers or put loopback URLs in commands. A node result does not replace publication and inspection.
${PREVIEW_RUNTIME_CONTRACT}
-Test startup and pointer/keyboard controls (inspector click/press, then assert results; assert-painted for canvas) at the exact published URL, including saving when storage is unavailable. Inspect browser errors and continued work after failed saves; HTTP 200 or a test outside the preview sandbox cannot establish this. Report unavailable verification. The inspector starts at the entry page with no navigation/reload; report cross-reload persistence unverified. Simulated reloads and sibling pages are not persistence evidence.`,
+Test startup and pointer/keyboard controls (inspector click/press, then assert results; assert-painted for canvas) at the exact published URL, including saving when storage is unavailable. Inspect browser errors and continued work after failed saves; HTTP 200 or a test outside the preview sandbox cannot establish this. Report unavailable verification. The inspector opens the entry page (or page) with no navigation/reload; report cross-reload persistence unverified. Simulated reloads and sibling pages are not persistence evidence.`,
});
export function createAgentSkillTool() {
diff --git a/ods/extensions/services/pixel-agent/plugin/preview-interaction-assurance.mjs b/ods/extensions/services/pixel-agent/plugin/preview-interaction-assurance.mjs
index be1d7f101..3a7452803 100644
--- a/ods/extensions/services/pixel-agent/plugin/preview-interaction-assurance.mjs
+++ b/ods/extensions/services/pixel-agent/plugin/preview-interaction-assurance.mjs
@@ -151,11 +151,13 @@ export function boundInspectionPageErrors(params, result, preview) {
// capsule receipt passed): they are observed before any step runs, so a
// failed step or a missing transition does not void them. `controls` is
// undefined when the receipt carries none (an older capsule or a transport
-// failure). Never interaction evidence.
+// failure). Never interaction evidence. Only the entry page's names count:
+// a receipt of another page (`page`) lists that page's buttons and links,
+// which can neither show nor rule out a control of the entry page.
export function boundInspectionControls(params, result, preview) {
try {
- const {receipt} = boundReceipt(params, result, preview, {incomplete: true}) ?? {};
- return receipt ? Object.freeze({siteId: receipt.siteId, sha256: receipt.sha256,
+ const {request, receipt} = boundReceipt(params, result, preview, {incomplete: true}) ?? {};
+ return receipt && request.page === undefined ? Object.freeze({siteId: receipt.siteId, sha256: receipt.sha256,
controls: inspectionControls(receipt)}) : undefined;
} catch { return undefined; }
}
diff --git a/ods/extensions/services/pixel-agent/plugin/workspace-preview-inspect.mjs b/ods/extensions/services/pixel-agent/plugin/workspace-preview-inspect.mjs
index 9dcd10341..3e70742e9 100644
--- a/ods/extensions/services/pixel-agent/plugin/workspace-preview-inspect.mjs
+++ b/ods/extensions/services/pixel-agent/plugin/workspace-preview-inspect.mjs
@@ -27,6 +27,18 @@ export const MAX_PAINT_SIDE = 256, MAX_PAINT_COLORS = 4, MAX_PAINT_DISTINCT_COLO
// only of fill. Exactly preview_inspection_protocol.py STEP_SCOPE and PRESS_FILL_SCOPE.
export const STEP_INSPECTION_SCOPE = 'Only the listed steps were tested, each only as stated here. CSS layout visibility, normalized visible-text assertions and click dispatches do not test pixel paint; no step tests occlusion, clipping, a full accessibility audit, or overall functionality.';
export const PRESS_FILL_INSPECTION_SCOPE = ' Native non-sensitive text and number fields were filled only with explicit synthetic values; number constraint flags are observations, not a claim of form validity. Fill sends no key events and does not submit forms.';
+// An optional page starts the inspection on another page of the same snapshot
+// instead of its entry page; links between pages are still not followed. Page
+// plans run only on a capsule labelled for them, and their receipts name the
+// page. The rules are exactly preview_inspection_protocol.py PAGE_SCOPE,
+// snapshot_name and page_file: a snapshot file name (relative ASCII segments,
+// none hidden or reserved) ending in .html, where a trailing / names that
+// folder's index.html. Whether that file exists only the host can tell.
+export const PAGE_INSPECTION_SCOPE = ' Only the requested page of this snapshot was loaded; links between pages were not followed.';
+const SNAPSHOT_SEGMENT = /^(?!__ods_)(?!__pycache__$)[A-Za-z0-9_\[][A-Za-z0-9._\[\]-]{0,127}$/;
+export const pageFile = page => page.endsWith('/') ? page + 'index.html' : page;
+const pageValid = page => typeof page === 'string' && pageFile(page).length <= 512 && pageFile(page).split('/').length <= 12 &&
+ pageFile(page).split('/').every(part => SNAPSHOT_SEGMENT.test(part)) && pageFile(page).endsWith('.html');
const LEGACY_INSPECTION_SCOPE = 'Only the listed CSS layout visibility assertions and click dispatches were tested; not pixel paint, occlusion, clipping, a full accessibility audit, or overall functionality.';
const SOCKET = '/run/ods-pixel-inspection/control.sock';
const HELPER = '/usr/local/libexec/ods-pixel-services/helpers/preview_inspection.py';
@@ -58,8 +70,10 @@ const fillPlan = request => request.steps.some(s=>s.action==='fill');
const downloadPlan = request => request.steps.at(-1)?.action==='download';
const pressPlan = request => request.steps.some(s=>s.action==='press');
const paintPlan = request => request.steps.some(s=>s.action==='assert-painted');
+const pagePlan = request => request.page !== undefined;
const requestScope = request => (pressPlan(request)||paintPlan(request)?STEP_INSPECTION_SCOPE:INSPECTION_SCOPE) + (selectionPlan(request)?SELECT_OPTION_INSPECTION_SCOPE:'') +
- (fillPlan(request)?(pressPlan(request)?PRESS_FILL_INSPECTION_SCOPE:FILL_INSPECTION_SCOPE):'') + (pressPlan(request)?PRESS_INSPECTION_SCOPE:'') + (paintPlan(request)?PAINT_INSPECTION_SCOPE:'') + (downloadPlan(request)?DOWNLOAD_INSPECTION_SCOPE:'');
+ (fillPlan(request)?(pressPlan(request)?PRESS_FILL_INSPECTION_SCOPE:FILL_INSPECTION_SCOPE):'') + (pressPlan(request)?PRESS_INSPECTION_SCOPE:'') + (paintPlan(request)?PAINT_INSPECTION_SCOPE:'') + (downloadPlan(request)?DOWNLOAD_INSPECTION_SCOPE:'') +
+ (pagePlan(request)?PAGE_INSPECTION_SCOPE:'');
const downloadKeys = ['path','expectedBytes','expectedSha256'];
// holdMs is optional; the capsule holds the key 100 ms when it is absent.
const pressKeys = s => ['key',...(Object.hasOwn(s,'holdMs')?['holdMs']:[])];
@@ -184,8 +198,12 @@ function nearlyOneColorNote(result) {
step.paint.dominant.percent >= NEARLY_ONE_COLOR_PERCENT);
return step ? ` Note: step ${step.index+1} (assert-painted) passed, but ${step.paint.dominant.percent}% of that element's box is one color (${step.paint.dominant.hex}). If it should show a scene, sprites or a map, it is probably still blank apart from small details: check what the render path draws last over the frame, and assert visible state with assert-text.` : '';
}
+const PAGE_NOT_FOUND = "The requested page is not a file of this published snapshot, so nothing was loaded and no step ran. page names one published .html file relative to the site root, such as menu.html or about/team.html, or a folder ending in / for its index.html: copy it from the publication receipt's published paths, or omit page for the entry page. If the owner asked for that page and it is missing, add it, republish and inspect the new snapshot. Requested behavior remains unverified.";
+const PAGE_UNSUPPORTED = 'This installed inspector cannot start on another page (page). Update the ODS inspector and its capsule together. Until then it inspects only the entry page: omit page for that page, keep the published pages unchanged and report the other pages as unverified.';
function transitionCoverageFeedback(request, result) {
- if (result.errorCode === 'request_blocked' || result.blockedRequests?.some(kind => kind === 'network' || kind === 'navigation')) return 'The inspection guard blocked a page operation. Check project requests and navigation; keep assets relative to the published output and navigation within that snapshot; root-absolute asset paths such as /_next/ may leave its site prefix. Inspect the project build configuration, rebuild and republish if needed. Do not broaden network access, rewrite host routes, or change permissions to bypass this boundary. Requested behavior remains unverified; this result does not establish that the inspection runtime is unavailable.';
+ if (result.errorCode === 'page_not_found') return PAGE_NOT_FOUND;
+ if (result.errorCode === 'request_blocked' || result.blockedRequests?.some(kind => kind === 'network' || kind === 'navigation')) return 'The inspection guard blocked a page operation. Check project requests and navigation; keep assets relative to the published output and navigation within that snapshot; root-absolute asset paths such as /_next/ may leave its site prefix. The inspector never follows a link to another page: inspect that page with page instead of clicking the link. Inspect the project build configuration, rebuild and republish if needed. Do not broaden network access, rewrite host routes, or change permissions to bypass this boundary. Requested behavior remains unverified; this result does not establish that the inspection runtime is unavailable.';
+ if (result.errorCode === 'unsupported_capability' && pagePlan(request)) return PAGE_UNSUPPORTED;
if (result.errorCode === 'unsupported_capability') return paintPlan(request) ? (pressPlan(request)
? 'This installed inspector does not support every check in this plan: element paint checks (assert-painted) and trusted key presses need a current inspector. Update the ODS inspector and its capsule together. Keep the published page unchanged; rendering and keyboard behavior remain unverified.'
: 'This installed inspector does not support element paint checks (assert-painted). Update the ODS inspector and its capsule together. Keep the published page unchanged; rendering remains unverified.') : pressPlan(request) ? 'This installed inspector does not support trusted key presses. Update the ODS inspector and its capsule together. Keep the published page unchanged; keyboard behavior remains unverified.' : fillPlan(request) ? 'This installed inspector does not support native text/number-field filling. Update the ODS inspector and its capsule together. Keep the published interface unchanged; form behavior remains unverified.' : downloadPlan(request) ? 'This installed inspector does not support snapshot download verification. Update the ODS inspector and its capsule together. Keep the published interface unchanged; download behavior remains unverified.' : 'This installed inspector does not support native select-option. Update the ODS inspector and its capsule together. Keep the published select unchanged; selection behavior remains unverified.';
@@ -264,18 +282,20 @@ function transitionCoverageFeedback(request, result) {
// state qualifiers removed, as the published element's id when it has one,
// checked against the published outline; else the owner-named heading. The
// requirement comes from the run guard, bound to this exact call; without it
-// the result is unchanged.
+// the result is unchanged. A page plan's corrective steps stay on its page,
+// and the outline, which is of the entry page, does not describe that page.
export const TRANSITION_UNTESTED = 'transition_untested';
export function transitionCorrection(request, requirement) {
const clickAt = request.steps.findIndex(step => step.action === 'click');
const control = clickAt >= 0 ? request.steps[clickAt].locator
: requirement?.control ? {role: requirement.control.role, name: requirement.control.name, exact: true} : undefined;
- const chosen = chooseTransitionTarget(request, {control, outline: requirement?.outline, phrase: requirement?.target});
+ const chosen = chooseTransitionTarget(request, {control, outline: pagePlan(request) ? undefined : requirement?.outline,
+ phrase: requirement?.target});
const [first, last] = requirement?.initiallyHidden === false ? ['assert-visible', 'assert-hidden'] : ['assert-hidden', 'assert-visible'];
let args;
if (control && chosen) {
try {
- args = {siteId: request.siteId, sha256: request.sha256, viewport: request.viewport,
+ args = {siteId: request.siteId, sha256: request.sha256, ...(pagePlan(request) ? {page: request.page} : {}), viewport: request.viewport,
steps: [{action: first, locator: chosen.locator}, {action: 'click', locator: control}, {action: last, locator: chosen.locator}]};
normalizeWorkspacePreviewInspectionParams(args);
} catch { args = undefined; }
@@ -355,12 +375,13 @@ export function renderedColorsLine(renderedColors) {
'. Colors under 1% of the view and hover/focus-only styles are not listed.';
}
const INPUT_HINTS = new Map([
- ['invalid preview inspection fields','Provide only siteId, sha256, viewport and steps.'],
+ ['invalid preview inspection fields','Provide only siteId, sha256, viewport, steps and, optionally, page.'],
+ ['invalid preview inspection page','page names one published .html page of the same snapshot, relative to the site root (for example menu.html or about/team.html), or a folder ending in / for its index.html. No leading / or URL, no ./ or ../ segments, hidden names, query or fragment. Omit page for the entry page.'],
['invalid preview inspection digest','sha256 must be the full 64-character lowercase snapshot digest from the publication receipt; never the shortened site suffix or a file digest.'],
['invalid preview inspection snapshot binding','siteId does not match the snapshot sha256. Copy both from the same latest publication receipt; do not use entrySha256 or invent a digest.'],
['invalid preview inspection viewport','viewport must contain integer width and height from 240 to 1920.'],
['invalid preview inspection steps','Provide 1 to 12 supported steps per inspection.'],
- ['unsupported inspection navigation','path is allowed only for a final download assertion. The inspector opens the published snapshot entry page and has no navigation or reload action. Verify supported in-page interactions and report cross-reload persistence as unverified; do not simulate a reload or use sibling test pages as persistence evidence.'],
+ ['unsupported inspection navigation','path is allowed only for a final download assertion. The inspector opens one page of the published snapshot, the entry page unless the top-level page names another, and has no navigation or reload action. Verify supported in-page interactions and report cross-reload persistence as unverified; do not simulate a reload or use sibling test pages as persistence evidence.'],
['invalid inspection step','Each step needs action and locator; assert-text additionally requires expectedText (normalized visible text, 1 to 256 characters); select-option or fill requires value (exact option value or synthetic text, 0 to 256 printable characters); download must be last and requires path, expectedBytes and expectedSha256 for one existing snapshot PDF/ZIP up to 4 MiB; press requires key (ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Space, Enter, Escape, Tab, one lowercase letter a-z or one digit 0-9; no modifiers, chords or text) and accepts holdMs (integer 0 to 1000 milliseconds, default 100); assert-painted takes only action and locator.'],
['missing expectedText','assert-text needs expectedText: the exact visible text the element should show after the earlier steps (normalized, 1 to 256 characters). To check only that it is shown, use assert-visible.'],
['missing value','select-option and fill need value: the exact option value, or synthetic text of 0 to 256 printable characters.'],
@@ -411,10 +432,12 @@ function inspectionStepProblem(step,index,count) {
// (preview_inspection_protocol.py); the plan hash and receipt bind that form.
const protocolLocator = l => Object.hasOwn(l,'selector') ? {selector:l.selector} : {role:l.role,name:l.name,exact:true};
export function normalizeWorkspacePreviewInspectionParams(params) {
- if(!exact(params,['siteId','sha256','viewport','steps'])) throw Error('invalid preview inspection fields');
+ const pageKey = params && typeof params==='object' && Object.hasOwn(params,'page') ? ['page'] : [];
+ if(!exact(params,['siteId','sha256','viewport','steps',...pageKey])) throw Error('invalid preview inspection fields');
if(typeof params.sha256!=='string'||!/^[a-f0-9]{64}$/.test(params.sha256)) throw Error('invalid preview inspection digest');
if(params.siteId!==`site-${params.sha256.slice(0,24)}`) throw Error('invalid preview inspection snapshot binding');
if(!exact(params.viewport,['width','height']) || Object.values(params.viewport).some(v=>!Number.isSafeInteger(v)||v<240||v>1920)) throw Error('invalid preview inspection viewport');
+ if(pageKey.length && !pageValid(params.page)) throw Error('invalid preview inspection page');
if(!Array.isArray(params.steps)||params.steps.length<1||params.steps.length>12) throw Error('invalid preview inspection steps');
const problems=[];
for(const [index,step] of params.steps.entries()) {
@@ -442,16 +465,18 @@ function stateValid(s, text=false, select=false, fill=false) {
return exact(s,['count','visible','display','visibility','opacity','hidden','hiddenUntilFound','rectCount',...(text?['text']:[]),...(select?['selection']:[]),...(fill?['input']:[])]) && (!fill || inputValid(s.input)) && (!select || selectionValid(s.selection)) && (!text || (exact(s.text,['actual','truncated']) && typeof s.text.actual==='string' && (s.text.actual==='' || printable(s.text.actual,256)) && typeof s.text.truncated==='boolean')) && s.count===1 && ['visible','hidden','hiddenUntilFound'].every(k=>typeof s[k]==='boolean') && ['display','visibility','opacity'].every(k=>printable(s[k],64)) && Number.isSafeInteger(s.rectCount)&&s.rectCount>=0&&s.rectCount<=100000;
}
export function validateWorkspacePreviewInspectionReceipt(value, request) {
- const validScope=value?.scope===requestScope(request) || (!selectionPlan(request) && !fillPlan(request) && !downloadPlan(request) && !pressPlan(request) && !paintPlan(request) && value?.scope===LEGACY_INSPECTION_SCOPE && !request.steps.some(step=>step.action==='assert-text'));
- if(!value || value.schemaVersion!==1 || value.kind!==INSPECTION_KIND || !['passed','failed'].includes(value.status) || value.siteId!==request.siteId || value.sha256!==request.sha256 || value.planSha256!==inspectionPlanHash(request) || !validScope) throw Error('invalid inspection binding');
+ const validScope=value?.scope===requestScope(request) || (!selectionPlan(request) && !fillPlan(request) && !downloadPlan(request) && !pressPlan(request) && !paintPlan(request) && !pagePlan(request) && value?.scope===LEGACY_INSPECTION_SCOPE && !request.steps.some(step=>step.action==='assert-text'));
+ // Every receipt of a page plan names that page; an entry-page receipt never names one.
+ if(!value || value.schemaVersion!==1 || value.kind!==INSPECTION_KIND || !['passed','failed'].includes(value.status) || value.siteId!==request.siteId || value.sha256!==request.sha256 || value.planSha256!==inspectionPlanHash(request) || value.page!==request.page || !validScope) throw Error('invalid inspection binding');
+ const pageKey=pagePlan(request)?['page']:[];
if(value.errorCode!==undefined) {
- if(!exact(value,['schemaVersion','kind','status','errorCode','siteId','sha256','planSha256','scope'])||value.status!=='failed'||!['unavailable','output_limit','timeout','cancelled','unsupported_capability','request_blocked'].includes(value.errorCode)) throw Error('invalid inspection failure');
+ if(!exact(value,['schemaVersion','kind','status','errorCode','siteId','sha256','planSha256',...pageKey,'scope'])||value.status!=='failed'||!['unavailable','output_limit','timeout','cancelled','unsupported_capability','request_blocked',...(pageKey.length?['page_not_found']:[])].includes(value.errorCode)) throw Error('invalid inspection failure');
return value;
}
// pageErrors, renderedColors and controls are optional: absent when none
// was observed or captured, or when an older capsule produced the receipt.
// Present, each must be exactly bounded.
- if(!exact(value,['schemaVersion','kind','status','siteId','sha256','planSha256','viewport','steps','diagnostics','blockedRequests',...(value.pageErrors===undefined?[]:['pageErrors']),...(value.renderedColors===undefined?[]:['renderedColors']),...(value.controls===undefined?[]:['controls']),'scope']) || (value.pageErrors!==undefined&&!pageErrorsValid(value.pageErrors)) || (value.renderedColors!==undefined&&!renderedColorsValid(value.renderedColors)) || (value.controls!==undefined&&!controlsValid(value.controls)) || canonical(value.viewport)!==canonical(request.viewport)||!Array.isArray(value.steps)||value.steps.length<1||value.steps.length>request.steps.length||!diagnosticsValid(value.diagnostics)||!Array.isArray(value.blockedRequests)||value.blockedRequests.length>32||value.blockedRequests.some(v=>!['navigation','network','popup','download','websocket'].includes(v))) throw Error('invalid inspection receipt');
+ if(!exact(value,['schemaVersion','kind','status','siteId','sha256','planSha256',...pageKey,'viewport','steps','diagnostics','blockedRequests',...(value.pageErrors===undefined?[]:['pageErrors']),...(value.renderedColors===undefined?[]:['renderedColors']),...(value.controls===undefined?[]:['controls']),'scope']) || (value.pageErrors!==undefined&&!pageErrorsValid(value.pageErrors)) || (value.renderedColors!==undefined&&!renderedColorsValid(value.renderedColors)) || (value.controls!==undefined&&!controlsValid(value.controls)) || canonical(value.viewport)!==canonical(request.viewport)||!Array.isArray(value.steps)||value.steps.length<1||value.steps.length>request.steps.length||!diagnosticsValid(value.diagnostics)||!Array.isArray(value.blockedRequests)||value.blockedRequests.length>32||value.blockedRequests.some(v=>!['navigation','network','popup','download','websocket'].includes(v))) throw Error('invalid inspection receipt');
value.steps.forEach((step,i)=>{
const textStep=step.action==='assert-text', selectStep=step.action==='select-option', fillStep=step.action==='fill', downloadStep=step.action==='download', pressStep=step.action==='press', paintStep=step.action==='assert-painted', textKeys=textStep?['expectedText']:(selectStep||fillStep)?['value']:downloadStep?downloadKeys:pressStep?pressKeys(request.steps[i]):[];
if(textStep && step.expectedText!==request.steps[i].expectedText) throw Error('invalid text binding');
@@ -544,8 +569,8 @@ export function createWorkspacePreviewInspectTool({request,transport='unix',tran
if(!['unix','native'].includes(transport))throw Error('invalid inspection transport');
request??=transport==='unix'?unixRequest:nativeRequest;
return {name:'pixel_ods_workspace_preview_inspect',
- description:'Inspect an already published owned snapshot using bounded CSS or exact accessible role/name locators. Pass its exact siteId and sha256 from publication. Each step accepts action and locator. assert-text also requires expectedText: the exact visible innerText after whitespace is collapsed and trimmed, 1 to 256 characters. This reads rendered text, not the value of an input field. For counters or status labels, use assert-text before and after clicking (for example 0, click Somar, 1, click Zerar, 0). For a visible editable native text/search/number input or textarea, use fill with value (0 to 256 printable characters), then click and assert the resulting text. Use synthetic test data only, never passwords, credentials or personal/payment data. Password/file/email and other input types, sensitive autocomplete fields, readonly/disabled fields and contenteditable are unsupported. For number fields use finite decimal or exponent strings with a dot separator, or empty to clear; do not use commas, NaN or Infinity. Min/max/step-invalid values are allowed for negative tests: boolean constraint flags report them without declaring the form valid. Fill emits input/change events without key events and does not submit forms. For keyboard controls such as a canvas game, use press with key: ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Space, Enter, Escape, Tab, one lowercase letter or one digit (no modifiers or text). Its locator is the rendered element that receives the keys, such as the game canvas, its container, the page body or a button; press focuses the preview page and that element, then sends real keydown/keyup events, which also reach window and document listeners. Optional holdMs (0 to 1000, default 100) keeps the key down, since many games read held keys once per animation frame. Press refuses text fields; use fill for those. Several presses may run in a row (for example Space to start, then ArrowRight), but follow the last one with assert-text, assert-visible/assert-hidden or assert-painted on the visible result; a key press alone proves no result. A start click needs its own assertion before the first press (for example click Start, assert-visible on the game screen or assert-painted on its canvas, then press): a click followed directly by a press does not count as behavior evidence. To check that a canvas game, chart or other drawing renders at all, use assert-painted (action and locator only) on the rendered element that draws, after the presses or start click that begin it (it can be that click\'s assertion): it captures that element\'s on-screen content box, inside the viewport and any rounded corners and including anything covering it, and passes when the box shows at least two colors within the observation window. One color fails as uniform_paint, for example a blank or black canvas. It reports only bounded color statistics and a fingerprint, never an image, and it is not image recognition: a background without its sprites still passes, so also assert visible state such as a score with assert-text. Two assert-painted steps of one element around a press show whether its paint changed. For a visible enabled native single-select, use select-option with value set to one exact option value (empty is allowed), then assert the dependent text. Do not add buttons merely because a test needs to select an option. Custom comboboxes and multiple selects are not supported. To verify delivery bytes use one final download step with path (a snapshot-relative PDF or ZIP), expectedBytes (1 to 4194304) and expectedSha256 (full SHA-256 of that file). The snapshot must already contain exactly those bytes. The download step performs the click itself. Do not precede it with an ordinary click on the download control; use any visibility/text assertions followed directly by download. This captures exactly one download privately inside the capsule; it does not download to the user computer or validate PDF quality or ZIP contents. Blob/data URLs, external URLs and additional downloads are unsupported. Ordinary click steps still cancel downloads; a blocked download is unverified, not a website failure. This runs the real page script in Chromium; test visible UI effects with fill, click, press and behavior assertions. Script, style and head metadata elements are normally not rendered; their visibility says nothing about whether page JavaScript executed. Do not replace the real page script with a reimplementation in another language. A locator is {selector:"#actual-id"} or {role:"button",name:"Exact source name"}; role/name always match the exact accessible name, so exact:true is optional and exact:false is invalid. Immediately after publication, check each requested interaction with an initial state assertion, the relevant click or press, then an explicit postcondition assertion matching the requested behavior. For downloads, the final download action supplies both the click and byte verification; omit a separate click. Read actual selectors and state changes from the source; do not guess them. Do not wait until finalization. Each locator must match exactly one element. Exact role/name locators match rendered elements; assert-hidden also matches hidden ones, so one role/name can be asserted hidden, clicked into view, then asserted visible. Visibility assertions test CSS layout visibility, not pixel paint, occlusion or clipping. The result also lists the rendered colors of the page by area at a desktop view as first loaded; use them to confirm a requested color change is actually visible. A click alone proves no behavioral result. Rendered hidden attributes are diagnostic; intentional CSS overrides are not automatically errors. Uncaught page script errors are reported and leave interactions unverified. When ODS declares the selected model able to read images, the result also carries one JPEG screenshot (about one megapixel at most, at most 3 per run) of the whole preview viewport, taken after the steps that ran: look at it before saying how the page looks. Otherwise the result says why it has none. Unavailable inspection is unverified, never success. No URLs or JavaScript accepted.',
- parameters:{type:'object',additionalProperties:false,required:['siteId','sha256','viewport','steps'],properties:{siteId:{type:'string',pattern:'^site-[a-f0-9]{24}$'},sha256:{type:'string',pattern:'^[a-f0-9]{64}$',description:'Full snapshot sha256 from the same publication receipt; not entrySha256 or a site suffix.'},viewport:{type:'object',additionalProperties:false,required:['width','height'],properties:{width:{type:'integer',minimum:240,maximum:1920},height:{type:'integer',minimum:240,maximum:1920}}},steps:{type:'array',minItems:1,maxItems:12,items:{type:'object',additionalProperties:false,required:['action','locator'],properties:{action:{type:'string',enum:['assert-visible','assert-hidden','assert-text','click','select-option','fill','download','press','assert-painted']},key:{type:'string',enum:[...PRESS_KEYS],description:'Required only for press; one unmodified key.'},holdMs:{type:'integer',minimum:0,maximum:MAX_PRESS_HOLD_MS,description:'Optional for press; milliseconds the key stays down (default 100).'},path:{type:'string',maxLength:512,description:'Required only for a single final download step; exact existing snapshot-relative PDF or ZIP path.'},expectedBytes:{type:'integer',minimum:1,maximum:4194304,description:'Required only for download; byte length of the existing snapshot file.'},expectedSha256:{type:'string',pattern:'^[a-f0-9]{64}$',description:'Required only for download; SHA-256 of the existing snapshot file, not the full snapshot hash.'},value:{type:'string',maxLength:256,description:'Required only for select-option or fill; exact option value or synthetic printable field text, including empty string.'},expectedText:{type:'string',minLength:1,maxLength:256,description:'Required only for assert-text; exact normalized visible text.'},locator:{oneOf:[{type:'object',additionalProperties:false,required:['selector'],properties:{selector:{type:'string',minLength:1,maxLength:256},exact:{const:true}}},{type:'object',additionalProperties:false,required:['role','name'],properties:{role:{type:'string',enum:[...roles]},name:{type:'string',minLength:1,maxLength:120},exact:{const:true}}}]}}}}}},
+ description:'Inspect an already published owned snapshot using bounded CSS or exact accessible role/name locators. Pass its exact siteId and sha256 from publication. It opens the entry page; to check another page of the same snapshot, pass page: its published .html path from the site root, such as menu.html or about/team.html (a folder ending in / means its index.html). Links between pages are not followed: inspect each page with its own call. Each step accepts action and locator. assert-text also requires expectedText: the exact visible innerText after whitespace is collapsed and trimmed, 1 to 256 characters. This reads rendered text, not the value of an input field. For counters or status labels, use assert-text before and after clicking (for example 0, click Somar, 1, click Zerar, 0). For a visible editable native text/search/number input or textarea, use fill with value (0 to 256 printable characters), then click and assert the resulting text. Use synthetic test data only, never passwords, credentials or personal/payment data. Password/file/email and other input types, sensitive autocomplete fields, readonly/disabled fields and contenteditable are unsupported. For number fields use finite decimal or exponent strings with a dot separator, or empty to clear; do not use commas, NaN or Infinity. Min/max/step-invalid values are allowed for negative tests: boolean constraint flags report them without declaring the form valid. Fill emits input/change events without key events and does not submit forms. For keyboard controls such as a canvas game, use press with key: ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Space, Enter, Escape, Tab, one lowercase letter or one digit (no modifiers or text). Its locator is the rendered element that receives the keys, such as the game canvas, its container, the page body or a button; press focuses the preview page and that element, then sends real keydown/keyup events, which also reach window and document listeners. Optional holdMs (0 to 1000, default 100) keeps the key down, since many games read held keys once per animation frame. Press refuses text fields; use fill for those. Several presses may run in a row (for example Space to start, then ArrowRight), but follow the last one with assert-text, assert-visible/assert-hidden or assert-painted on the visible result; a key press alone proves no result. A start click needs its own assertion before the first press (for example click Start, assert-visible on the game screen or assert-painted on its canvas, then press): a click followed directly by a press does not count as behavior evidence. To check that a canvas game, chart or other drawing renders at all, use assert-painted (action and locator only) on the rendered element that draws, after the presses or start click that begin it (it can be that click\'s assertion): it captures that element\'s on-screen content box, inside the viewport and any rounded corners and including anything covering it, and passes when the box shows at least two colors within the observation window. One color fails as uniform_paint, for example a blank or black canvas. It reports only bounded color statistics and a fingerprint, never an image, and it is not image recognition: a background without its sprites still passes, so also assert visible state such as a score with assert-text. Two assert-painted steps of one element around a press show whether its paint changed. For a visible enabled native single-select, use select-option with value set to one exact option value (empty is allowed), then assert the dependent text. Do not add buttons merely because a test needs to select an option. Custom comboboxes and multiple selects are not supported. To verify delivery bytes use one final download step with path (a snapshot-relative PDF or ZIP), expectedBytes (1 to 4194304) and expectedSha256 (full SHA-256 of that file). The snapshot must already contain exactly those bytes. The download step performs the click itself. Do not precede it with an ordinary click on the download control; use any visibility/text assertions followed directly by download. This captures exactly one download privately inside the capsule; it does not download to the user computer or validate PDF quality or ZIP contents. Blob/data URLs, external URLs and additional downloads are unsupported. Ordinary click steps still cancel downloads; a blocked download is unverified, not a website failure. This runs the real page script in Chromium; test visible UI effects with fill, click, press and behavior assertions. Script, style and head metadata elements are normally not rendered; their visibility says nothing about whether page JavaScript executed. Do not replace the real page script with a reimplementation in another language. A locator is {selector:"#actual-id"} or {role:"button",name:"Exact source name"}; role/name always match the exact accessible name, so exact:true is optional and exact:false is invalid. Immediately after publication, check each requested interaction with an initial state assertion, the relevant click or press, then an explicit postcondition assertion matching the requested behavior. For downloads, the final download action supplies both the click and byte verification; omit a separate click. Read actual selectors and state changes from the source; do not guess them. Do not wait until finalization. Each locator must match exactly one element. Exact role/name locators match rendered elements; assert-hidden also matches hidden ones, so one role/name can be asserted hidden, clicked into view, then asserted visible. Visibility assertions test CSS layout visibility, not pixel paint, occlusion or clipping. The result also lists the rendered colors of the page by area at a desktop view as first loaded; use them to confirm a requested color change is actually visible. A click alone proves no behavioral result. Rendered hidden attributes are diagnostic; intentional CSS overrides are not automatically errors. Uncaught page script errors are reported and leave interactions unverified. When ODS declares the selected model able to read images, the result also carries one JPEG screenshot (about one megapixel at most, at most 3 per run) of the whole preview viewport, taken after the steps that ran: look at it before saying how the page looks. Otherwise the result says why it has none. Unavailable inspection is unverified, never success. No URLs or JavaScript accepted.',
+ parameters:{type:'object',additionalProperties:false,required:['siteId','sha256','viewport','steps'],properties:{siteId:{type:'string',pattern:'^site-[a-f0-9]{24}$'},sha256:{type:'string',pattern:'^[a-f0-9]{64}$',description:'Full snapshot sha256 from the same publication receipt; not entrySha256 or a site suffix.'},page:{type:'string',minLength:1,maxLength:512,description:'Optional; the published .html page of this snapshot to open instead of the entry page, relative to the site root (menu.html, or blog/ for blog/index.html). Omit for the entry page.'},viewport:{type:'object',additionalProperties:false,required:['width','height'],properties:{width:{type:'integer',minimum:240,maximum:1920},height:{type:'integer',minimum:240,maximum:1920}}},steps:{type:'array',minItems:1,maxItems:12,items:{type:'object',additionalProperties:false,required:['action','locator'],properties:{action:{type:'string',enum:['assert-visible','assert-hidden','assert-text','click','select-option','fill','download','press','assert-painted']},key:{type:'string',enum:[...PRESS_KEYS],description:'Required only for press; one unmodified key.'},holdMs:{type:'integer',minimum:0,maximum:MAX_PRESS_HOLD_MS,description:'Optional for press; milliseconds the key stays down (default 100).'},path:{type:'string',maxLength:512,description:'Required only for a single final download step; exact existing snapshot-relative PDF or ZIP path.'},expectedBytes:{type:'integer',minimum:1,maximum:4194304,description:'Required only for download; byte length of the existing snapshot file.'},expectedSha256:{type:'string',pattern:'^[a-f0-9]{64}$',description:'Required only for download; SHA-256 of the existing snapshot file, not the full snapshot hash.'},value:{type:'string',maxLength:256,description:'Required only for select-option or fill; exact option value or synthetic printable field text, including empty string.'},expectedText:{type:'string',minLength:1,maxLength:256,description:'Required only for assert-text; exact normalized visible text.'},locator:{oneOf:[{type:'object',additionalProperties:false,required:['selector'],properties:{selector:{type:'string',minLength:1,maxLength:256},exact:{const:true}}},{type:'object',additionalProperties:false,required:['role','name'],properties:{role:{type:'string',enum:[...roles]},name:{type:'string',minLength:1,maxLength:120},exact:{const:true}}}]}}}}}},
execute:async(toolCallId,params,signal)=>{
let normalized;
// Bad model arguments are not evidence that the installed broker is down.
@@ -578,10 +603,12 @@ export function createWorkspacePreviewInspectTool({request,transport='unix',tran
try { requirement=transitionRequirement(toolCallId,params); } catch { requirement=undefined; }
}
// Quote page text once, labelled; the evidence copy keeps only the count.
+ // A page plan's result names its page, as its receipt does.
+ const inspection=`Preview inspection${result.page===undefined?'':` of page ${JSON.stringify(result.page)}`}`;
const summary=pageErrors
- ? `Preview inspection ${result.status==='passed'?'steps passed, but':'failed, and'} ${pageErrorFeedback(pageErrors)}`
+ ? `${inspection} ${result.status==='passed'?'steps passed, but':'failed, and'} ${pageErrorFeedback(pageErrors)}`
: requirement ? transitionIncompleteFeedback(normalized, requirement)
- : `Preview inspection ${result.status}. ${transitionCoverageFeedback(normalized, result)}${unchangedPaintNote(result)}${nearlyOneColorNote(result)}${renderedHiddenNote(result)}`;
+ : `${inspection} ${result.status}. ${transitionCoverageFeedback(normalized, result)}${unchangedPaintNote(result)}${nearlyOneColorNote(result)}${renderedHiddenNote(result)}`;
// The palette is stated once, as its fixed line; the evidence copy omits
// it and the load-time control names (used only for locator feedback).
const {renderedColors,controls,...rest}=result;
diff --git a/ods/extensions/services/pixel-agent/tests/agent-skills.test.mjs b/ods/extensions/services/pixel-agent/tests/agent-skills.test.mjs
index 471db1d76..745893b54 100644
--- a/ods/extensions/services/pixel-agent/tests/agent-skills.test.mjs
+++ b/ods/extensions/services/pixel-agent/tests/agent-skills.test.mjs
@@ -75,6 +75,15 @@ test('verification guide keeps scratch work in a hidden project folder that neve
assert.doesNotMatch(guide, /mktemp -d or tempfile\.mkdtemp in the project;/);
});
+// A multi-page site ("home, menu and contact") needs its other pages checked:
+// the inspector's page opens one, and still never navigates or reloads.
+test('guides point to the inspector page field for other pages without promising navigation', () => {
+ assert.match(AGENT_SKILLS.workspace, /Verify nested routes too \(inspector page\)\./);
+ assert.match(AGENT_SKILLS.verification, /The inspector opens the entry page \(or page\) with no navigation\/reload; report cross-reload persistence unverified\./);
+ assert.match(AGENT_SKILLS.verification, /Simulated reloads and sibling pages are not persistence evidence\./);
+ assert.doesNotMatch(AGENT_SKILLS.verification, /starts at the entry page/);
+});
+
// Elf of Doom on the RTX Spark: without a runtime the model could only read its
// canvas game, so a save() leak and a per-hit freeze survived many turns.
test('verification guide shows offline node checks for browser JavaScript, scoped to the sandbox', () => {
diff --git a/ods/extensions/services/pixel-agent/tests/inspection_page.test.mjs b/ods/extensions/services/pixel-agent/tests/inspection_page.test.mjs
new file mode 100644
index 000000000..96c9bbcb9
--- /dev/null
+++ b/ods/extensions/services/pixel-agent/tests/inspection_page.test.mjs
@@ -0,0 +1,214 @@
+// An optional page starts an inspection on another page of the same published
+// snapshot ("a three-page bakery site: home, menu and contact"). It grants no
+// new permission: links between pages are still not followed, and every
+// receipt of a page plan names its page.
+import assert from 'node:assert/strict';
+import {test} from 'node:test';
+import {spawnSync} from 'node:child_process';
+import {fileURLToPath} from 'node:url';
+import {createWorkspacePreviewInspectTool,normalizeWorkspacePreviewInspectionParams as normalize,validateWorkspacePreviewInspectionReceipt as validate,
+ inspectionPlanHash,pageFile,transitionCorrection,INSPECTION_KIND,INSPECTION_SCOPE,PAGE_INSPECTION_SCOPE,PRESS_INSPECTION_SCOPE,
+ STEP_INSPECTION_SCOPE} from '../plugin/workspace-preview-inspect.mjs';
+import {boundInspectionControls,boundRenderedPreviewInspection,boundVisibilityInspection} from '../plugin/preview-interaction-assurance.mjs';
+
+const preview={siteId:'site-'+'a'.repeat(24),sha256:'a'.repeat(64)};
+const visible=selector=>({action:'assert-visible',locator:{selector}});
+const press={action:'press',locator:{selector:'#game'},key:'Space'};
+const params=(page,...steps)=>({...preview,...(page===undefined?{}:{page}),viewport:{width:800,height:600},steps:steps.length?steps:[visible('h1')]});
+const state=shown=>({count:1,visible:shown,display:shown?'block':'none',visibility:'visible',opacity:'1',hidden:!shown,hiddenUntilFound:false,rectCount:shown?1:0});
+const CONTROLS={count:1,items:[{role:'button',name:'Show specials',visible:true,source:'content'}]};
+// The scope of these plans: the press base for press plans, and the page suffix for page plans.
+const scopeOf=request=>(request.steps.some(s=>s.action==='press')?STEP_INSPECTION_SCOPE+PRESS_INSPECTION_SCOPE:INSPECTION_SCOPE)+
+ (request.page===undefined?'':PAGE_INSPECTION_SCOPE);
+function receipt(request,extra={}) {
+ return {schemaVersion:1,kind:INSPECTION_KIND,status:'passed',siteId:request.siteId,sha256:request.sha256,planSha256:inspectionPlanHash(request),
+ ...(request.page===undefined?{}:{page:request.page}),viewport:request.viewport,
+ steps:request.steps.map((s,index)=>({index,...s,stable:true,status:'passed',before:state(s.action!=='assert-hidden'),...(s.action==='click'?{after:state(true)}:{})})),
+ diagnostics:{renderedHiddenAttributeCount:0,hiddenUntilFoundCount:0},blockedRequests:[],scope:scopeOf(request),...extra};
+}
+const failure=(request,errorCode)=>({schemaVersion:1,kind:INSPECTION_KIND,status:'failed',errorCode,siteId:request.siteId,sha256:request.sha256,
+ planSha256:inspectionPlanHash(request),...(request.page===undefined?{}:{page:request.page}),scope:scopeOf(request)});
+const run=async(plan,answer)=>createWorkspacePreviewInspectTool({request:async request=>answer(request)}).execute('page',plan);
+
+// Published pages of a site, and nested ones: a trailing / names that
+// folder's index.html, as the capsule's loopback server serves it. At most
+// 512 characters, 12 segments and 128 characters per segment, as the snapshot.
+const LONG=`${'x'.repeat(120)}/`.repeat(4);
+const GOOD=['menu.html','about/team.html','about/','index.html','[slug].html','_not-found.html','v1.2/notes.html',
+ 'a/b/c/d/e/f/g/h/i/j/k/x.html','x/'.repeat(11),'x'.repeat(123)+'.html',LONG+'x'.repeat(23)+'.html'];
+// Traversal, absolute paths, URLs, queries, fragments, hidden or reserved
+// names, other file types, empty segments and the bounds.
+const BAD=['','/','//','/menu.html','\\menu.html','menu\\x.html','menu\u0000.html','../menu.html','about/../menu.html','./menu.html','about/./team.html',
+ 'about//team.html','http://example.invalid/menu.html','//example.invalid/menu.html','file:menu.html','menu.html?x=1','menu.html#top','.hidden.html',
+ 'about/.secret.html','.well-known/','menu','menu.htm','menu.HTML','menu.html.bak','style.css','about','about/team','%2e%2e/menu.html','men u.html',
+ 'ménu.html','menu.html\n','__ods_view__.html','__pycache__/x.html','-menu.html','x'.repeat(124)+'.html','a/'.repeat(12)+'x.html','x/'.repeat(12),
+ LONG+'x'.repeat(24)+'.html'];
+
+test('page accepts published .html paths of the snapshot and refuses every other form',async()=>{
+ for(const page of GOOD) assert.equal(normalize(params(page)).page,page,page);
+ assert.equal(Object.hasOwn(normalize(params()),'page'),false,'the entry page is not written into the plan');
+ let calls=0;
+ const tool=createWorkspacePreviewInspectTool({request:async()=>{calls++;throw Error('must not execute');}});
+ for(const page of [...BAD,null,undefined,1,true,['menu.html'],{path:'menu.html'}]) {
+ assert.throws(()=>normalize({...params(),page}),/invalid preview inspection page/,JSON.stringify(page));
+ const result=await tool.execute('bad-page',{...params(),page});
+ assert.equal(result.details.errorCode,'invalid_request',JSON.stringify(page));
+ assert.match(result.content[0].text,/page names one published \.html page of the same snapshot/);
+ assert.match(result.content[0].text,/Omit page for the entry page/);
+ }
+ const marker='PRIVATE_PAGE_DO_NOT_REPEAT';
+ assert.ok(!(await tool.execute('marker',{...params(),page:`../${marker}.html`})).content[0].text.includes(marker),'the value is never reflected');
+ assert.equal(calls,0,'an invalid page never reaches the inspector');
+ // Exactly one optional top-level field; nothing else is loosened.
+ for(const extra of [{url:'http://localhost/menu.html'},{pages:['menu.html']},{path:'menu.html'}]) {
+ assert.throws(()=>normalize({...params('menu.html'),...extra}),/invalid preview inspection fields/);
+ }
+ assert.equal(pageFile('about/'),'about/index.html');
+ assert.equal(pageFile('menu.html'),'menu.html');
+});
+
+test('existing plans hash exactly as before and a page is part of the plan',()=>{
+ // The plan of tests/test-preview-inspection.mjs, whose hash matches Python's canonical contract.
+ const legacy={...preview,viewport:{width:375,height:812},steps:[{action:'assert-hidden',locator:{selector:'#card'}},
+ {action:'click',locator:{role:'button',name:'Mostrar próximos eventos',exact:true}},visible('#card')]};
+ assert.equal(inspectionPlanHash(normalize(legacy)),'156ae762e4eb8cbec17063823bfb5a61705c2917251da8cdff43af2c9ffbc06c');
+ assert.deepEqual(Object.keys(normalize(legacy)).sort(),['action','schemaVersion','sha256','siteId','steps','viewport']);
+ const paged=normalize({...legacy,page:'menu.html'});
+ assert.notEqual(inspectionPlanHash(paged),inspectionPlanHash(normalize(legacy)));
+ assert.notEqual(inspectionPlanHash(paged),inspectionPlanHash(normalize({...legacy,page:'contact.html'})));
+});
+
+// The capsule protocol in Python decides what the broker accepts and hashes.
+function python(requests) {
+ const script='import json,sys\nsys.path.insert(0,sys.argv[1])\nimport preview_inspection_protocol as p\n'+
+ 'out={"scope":p.PAGE_SCOPE,"capability":p.PAGE_CAPABILITY,"requests":[]}\n'+
+ 'for r in json.load(sys.stdin):\n'+
+ ' try: p.validate_request(r); out["requests"].append({"valid":True,"hash":p.plan_hash(r),"scope":p.inspection_scope(r),'+
+ '"file":p.page_file(r["page"]) if "page" in r else None,"failure":p.failure("page_not_found",r)})\n'+
+ ' except p.Invalid: out["requests"].append({"valid":False})\n'+
+ 'print(json.dumps(out))\n';
+ const result=spawnSync(process.platform==='win32'?'python':'python3',['-c',script,fileURLToPath(new URL('../host',import.meta.url))],
+ {input:JSON.stringify(requests),encoding:'utf8',windowsHide:true});
+ assert.equal(result.status,0,result.stderr);
+ return JSON.parse(result.stdout);
+}
+
+test('the plugin mirrors the Python page rules, scope, failure receipt and plan hash',()=>{
+ const samples=[params(),params(undefined,press),params('menu.html',press),...GOOD.map(page=>params(page)),...BAD.map(page=>params(page)),
+ {...params(),page:null},{...params(),page:7}];
+ const py=python(samples.map(sample=>({schemaVersion:1,action:'inspect',...sample})));
+ assert.equal(py.scope,PAGE_INSPECTION_SCOPE);
+ assert.equal(py.capability,'snapshot-page-v1');
+ samples.forEach((sample,i)=>{
+ let request;
+ try { request=normalize(sample); } catch { request=undefined; }
+ assert.equal(py.requests[i].valid,request!==undefined,JSON.stringify(sample.page));
+ if(!request) return;
+ assert.equal(py.requests[i].hash,inspectionPlanHash(request));
+ assert.equal(py.requests[i].scope,validate(failure(request,'unavailable'),request).scope);
+ assert.equal(py.requests[i].file,request.page===undefined?null:pageFile(request.page));
+ // The host's bound failure for a missing page validates here only for a page plan.
+ if(request.page!==undefined) assert.deepEqual(validate(py.requests[i].failure,request),py.requests[i].failure);
+ else assert.throws(()=>validate(py.requests[i].failure,request));
+ });
+});
+
+test('the schema offers page as one optional bounded string, and the description says links are not followed',()=>{
+ const {parameters,description}=createWorkspacePreviewInspectTool({request:async()=>{}});
+ assert.deepEqual(parameters.required,['siteId','sha256','viewport','steps']);
+ const {page}=parameters.properties;
+ assert.deepEqual([page.type,page.minLength,page.maxLength,page.pattern],['string',1,512,undefined]);
+ assert.match(page.description,/Omit for the entry page/);
+ assert.match(description,/It opens the entry page; to check another page of the same snapshot, pass page: its published \.html path from the site root/);
+ assert.match(description,/Links between pages are not followed: inspect each page with its own call\./);
+});
+
+test('every receipt of a page plan names that page, and an entry-page receipt never does',()=>{
+ const request=normalize(params('menu.html',visible('#specials'))),good=receipt(request);
+ assert.equal(validate(good,request).page,'menu.html');
+ const entry=normalize(params(undefined,visible('#specials')));
+ assert.equal(validate(receipt(entry),entry).page,undefined);
+ for(const change of [r=>{delete r.page;},r=>r.page='contact.html',r=>r.page='menu.html/',r=>r.scope=INSPECTION_SCOPE,
+ r=>r.scope='Only the listed CSS layout visibility assertions and click dispatches were tested; not pixel paint, occlusion, clipping, a full accessibility audit, or overall functionality.']) {
+ const forged=structuredClone(good);change(forged);
+ assert.throws(()=>validate(forged,request),undefined,JSON.stringify(forged));
+ }
+ assert.throws(()=>validate({...receipt(entry),page:'index.html'},entry),'an entry-page receipt names no page');
+ assert.throws(()=>validate(receipt(request),entry),'a page receipt never stands for the entry page');
+ // Bound failures name the page too; page_not_found exists only for a page plan.
+ for(const code of ['page_not_found','unavailable','unsupported_capability','request_blocked']) assert.equal(validate(failure(request,code),request).errorCode,code);
+ const unnamed=failure(request,'unavailable');delete unnamed.page;
+ assert.throws(()=>validate(unnamed,request));
+ assert.throws(()=>validate(failure(entry,'page_not_found'),entry));
+ assert.throws(()=>validate({...failure(entry,'unavailable'),page:'menu.html'},entry));
+});
+
+test('a page that names no file of the snapshot is reported as not found, never unavailable or passed',async()=>{
+ const result=await run(params('menu.html'),request=>failure(request,'page_not_found'));
+ assert.equal(result.isError,true);
+ assert.equal(result.details.errorCode,'page_not_found');
+ assert.equal(result.details.page,'menu.html');
+ const text=result.content[0].text;
+ assert.match(text,/^Preview inspection of page "menu\.html" failed\. The requested page is not a file of this published snapshot, so nothing was loaded and no step ran\./);
+ assert.match(text,/copy it from the publication receipt's published paths, or omit page for the entry page/);
+ assert.match(text,/add it, republish and inspect the new snapshot/);
+ assert.match(text,/Requested behavior remains unverified/);
+ assert.doesNotMatch(text,/unavailable or invalid|guard blocked/);
+});
+
+test('an inspector without page support says so and points to the entry page',async()=>{
+ const result=await run(params('menu.html',press),request=>failure(request,'unsupported_capability'));
+ assert.equal(result.details.errorCode,'unsupported_capability');
+ assert.match(result.content[0].text,/cannot start on another page \(page\)\. Update the ODS inspector and its capsule together/);
+ assert.match(result.content[0].text,/omit page for that page, keep the published pages unchanged and report the other pages as unverified/);
+ const entry=await run(params(undefined,press),request=>failure(request,'unsupported_capability'));
+ assert.match(entry.content[0].text,/does not support trusted key presses/,'entry-page plans keep their own message');
+ assert.doesNotMatch(entry.content[0].text,/another page/);
+});
+
+test('a passing page plan names its page and counts as browser evidence for the snapshot',async()=>{
+ const steps=[{action:'assert-hidden',locator:{selector:'#specials'}},{action:'click',locator:{selector:'#show'}},visible('#specials')];
+ const plan=params('menu.html',...steps);
+ const result=await run(plan,request=>receipt(request,{controls:CONTROLS}));
+ assert.equal(result.isError,undefined);
+ assert.equal(result.details.page,'menu.html');
+ assert.match(result.content[0].text,/^Preview inspection of page "menu\.html" passed\. These steps tested opposite visibility states/);
+ assert.ok(result.content[0].text.includes(PAGE_INSPECTION_SCOPE));
+ assert.match(result.content[0].text,/"page":"menu\.html"/,'the evidence copy names the page');
+ assert.ok(boundRenderedPreviewInspection(plan,result,preview));
+ assert.deepEqual(boundVisibilityInspection(plan,result,preview),{...preview,planSha256:result.details.planSha256});
+ // Load-time control names of another page cannot show or rule out the
+ // owner's control on the entry page; the entry page's own still count.
+ assert.equal(boundInspectionControls(plan,result,preview),undefined);
+ const entryPlan=params(undefined,...steps);
+ const entry=await run(entryPlan,request=>receipt(request,{controls:CONTROLS}));
+ assert.match(entry.content[0].text,/^Preview inspection passed\./,'the entry page keeps its wording');
+ assert.deepEqual(boundInspectionControls(entryPlan,entry,preview).controls,CONTROLS);
+});
+
+test('a click-through to another page stays a blocked navigation',async()=>{
+ const plan=params('menu.html',{action:'click',locator:{selector:'#to-contact'}},visible('h1'));
+ const result=await run(plan,request=>({...receipt(request),status:'failed',blockedRequests:['navigation'],
+ steps:[{index:0,...request.steps[0],before:state(true),stable:true,status:'failed',errorCode:'click_failed'}]}));
+ assert.equal(result.isError,true);
+ assert.match(result.content[0].text,/^Preview inspection of page "menu\.html" failed\. The inspection guard blocked a page operation\./);
+ assert.match(result.content[0].text,/The inspector never follows a link to another page: inspect that page with page instead of clicking the link\./);
+ assert.match(result.content[0].text,/Do not broaden network access/);
+ assert.equal(boundRenderedPreviewInspection(plan,result,preview),undefined);
+});
+
+test('an untested show/hide correction stays on the inspected page and ignores the entry-page outline',()=>{
+ // The entry page's outline: its .card has the id specials.
+ const outline={elements:[{tag:'section',parent:-1,id:'specials',classes:['card','hidden']}],stateClasses:['hidden']};
+ const steps=[{action:'assert-hidden',locator:{selector:'.card.hidden'}},{action:'click',locator:{selector:'#show'}}];
+ const entry=transitionCorrection(normalize(params(undefined,...steps)),{outline,initiallyHidden:true});
+ assert.equal(entry.basis,'id');
+ assert.equal(entry.args.page,undefined);
+ assert.deepEqual(entry.args.steps[0].locator,{selector:'#specials'});
+ const paged=transitionCorrection(normalize(params('menu.html',...steps)),{outline,initiallyHidden:true});
+ assert.equal(paged.basis,'unverified');
+ assert.equal(paged.args.page,'menu.html');
+ assert.deepEqual(paged.args.steps.map(step=>[step.action,step.locator]),
+ [['assert-hidden',{selector:'.card'}],['click',{selector:'#show'}],['assert-visible',{selector:'.card'}]]);
+ assert.equal(normalize(paged.args).page,'menu.html','the ready-to-send args are a valid page plan');
+});
diff --git a/ods/extensions/services/pixel-agent/tests/preview_inspection_input_recovery.test.mjs b/ods/extensions/services/pixel-agent/tests/preview_inspection_input_recovery.test.mjs
index 7d0b445c3..96a904c85 100644
--- a/ods/extensions/services/pixel-agent/tests/preview_inspection_input_recovery.test.mjs
+++ b/ods/extensions/services/pixel-agent/tests/preview_inspection_input_recovery.test.mjs
@@ -207,6 +207,7 @@ test('non-download paths explain navigation limits without transport or value di
assert.match(result.content[0].text,/steps\[1\]\.path/);
assert.match(result.content[0].text,/path is allowed only for a final download assertion/);
assert.match(result.content[0].text,/no navigation or reload action/);
+ assert.match(result.content[0].text,/the entry page unless the top-level page names another/);
assert.match(result.content[0].text,/cross-reload persistence as unverified/);
assert.ok(!result.content[0].text.includes(marker));
assert.ok(!result.content[0].text.includes('sibling-test.html'));
diff --git a/ods/installers/lib/pixel-preview-inspection.py b/ods/installers/lib/pixel-preview-inspection.py
index e037cf7c3..f306ac6a3 100644
--- a/ods/installers/lib/pixel-preview-inspection.py
+++ b/ods/installers/lib/pixel-preview-inspection.py
@@ -167,6 +167,7 @@ def validate_image(image, image_id):
or labels.get("org.osmantic.ods.inspection.select") != "native-single-select-v1"
or labels.get("org.osmantic.ods.inspection.press") != "trusted-key-press-v1"
or labels.get("org.osmantic.ods.inspection.paint") != "element-paint-v1"
+ or labels.get("org.osmantic.ods.inspection.page") != "snapshot-page-v1"
or labels.get("org.osmantic.ods.inspection.screenshot") != "viewport-screenshot-v1"
or labels.get("org.osmantic.ods.inspection.playwright") != "1.62.0"
):
diff --git a/ods/tests/test_preview_inspection.py b/ods/tests/test_preview_inspection.py
index 7282954a7..f23b4ff55 100644
--- a/ods/tests/test_preview_inspection.py
+++ b/ods/tests/test_preview_inspection.py
@@ -574,7 +574,7 @@ class SnapshotAssetGuardTests(unittest.TestCase):
origin = 'http://127.0.0.1:4321'
prefix = '/site-' + 'a' * 24 + '/'
blocked = []
- capsule.guard_requests(context, context, origin, prefix, blocked, files=files)
+ capsule.guard_requests(context, context, origin, prefix, blocked, files=files, entry=prefix)
for path, method, nav, expected in [
('/_next/app/%5Bslug%5D/page.js', 'GET', False, 'continued'),
('/_next/app/%5Bslug%5D/page.js', 'POST', False, 'aborted'),
diff --git a/ods/tests/test_preview_inspection_distribution.py b/ods/tests/test_preview_inspection_distribution.py
index 51b8152c4..ffbe8c5a0 100644
--- a/ods/tests/test_preview_inspection_distribution.py
+++ b/ods/tests/test_preview_inspection_distribution.py
@@ -318,6 +318,7 @@ def image():
"org.osmantic.ods.inspection.select": "native-single-select-v1",
"org.osmantic.ods.inspection.press": "trusted-key-press-v1",
"org.osmantic.ods.inspection.paint": "element-paint-v1",
+ "org.osmantic.ods.inspection.page": "snapshot-page-v1",
"org.osmantic.ods.inspection.screenshot": "viewport-screenshot-v1",
"org.osmantic.ods.inspection.playwright": "1.62.0",
},
@@ -347,7 +348,7 @@ def test_config_rejects_ambient_authority(field, value):
@pytest.mark.parametrize(
- "fault", ["id", "os", "architecture", "user", "entrypoint", "label", "select", "fill", "press", "paint", "screenshot"]
+ "fault", ["id", "os", "architecture", "user", "entrypoint", "label", "select", "fill", "press", "paint", "page", "screenshot"]
)
def test_image_contract_is_exact(monkeypatch, fault):
monkeypatch.setattr(module.platform, "machine", lambda: "x86_64")
@@ -368,6 +369,8 @@ def test_image_contract_is_exact(monkeypatch, fault):
del value[0]["Config"]["Labels"]["org.osmantic.ods.inspection.press"]
elif fault == "paint":
del value[0]["Config"]["Labels"]["org.osmantic.ods.inspection.paint"]
+ elif fault == "page":
+ del value[0]["Config"]["Labels"]["org.osmantic.ods.inspection.page"]
elif fault == "screenshot":
del value[0]["Config"]["Labels"]["org.osmantic.ods.inspection.screenshot"]
else:
diff --git a/ods/tests/test_preview_inspection_page.py b/ods/tests/test_preview_inspection_page.py
new file mode 100644
index 000000000..626fbeb9d
--- /dev/null
+++ b/ods/tests/test_preview_inspection_page.py
@@ -0,0 +1,366 @@
+"""A page of the same snapshot to start on: no new permission, every receipt names it."""
+import os
+import re
+import unittest
+import urllib.request
+from unittest.mock import patch
+
+import test_preview_inspection as harness
+from test_preview_inspection_blocked import execute_real
+
+bundle, protocol, broker, capsule = harness.bundle, harness.protocol, harness.broker, harness.capsule
+step, Route, PaletteDouble, ScriptedBrowser = harness.step, harness.Route, harness.PaletteDouble, harness.ScriptedBrowser
+
+# A three-page bakery site with nested pages, as an owner asks for one.
+SITE = {
+ "index.html": b'<h1>Crumb &amp; Co</h1><a id="to-menu" href="menu.html">Menu</a> <a href="contact.html">Contact</a>',
+ "menu.html": b'<h1>Menu</h1><p id="bread">Sourdough</p><a id="to-contact" href="contact.html">Contact</a>',
+ "contact.html": b'<h1>Contact</h1><p id="phone">555 0100</p>',
+ "about/index.html": b'<h1>About</h1><link rel="stylesheet" href="../style.css">',
+ "about/team.html": b'<h1>Team</h1>',
+ "[slug].html": b'<h1>Post</h1>',
+ "style.css": b"h1{color:#7a4b2a}",
+}
+LONG = ("x" * 120 + "/") * 4
+GOOD = ("menu.html", "about/team.html", "about/", "index.html", "[slug].html", "_not-found.html", "v1.2/notes.html",
+ "a/b/c/d/e/f/g/h/i/j/k/x.html", "x/" * 11, "x" * 123 + ".html", LONG + "x" * 23 + ".html")
+# Exactly the rejected pages of inspection_page.test.mjs.
+BAD = ("", "/", "//", "/menu.html", "\\menu.html", "menu\\x.html", "menu\x00.html", "../menu.html", "about/../menu.html",
+ "./menu.html", "about/./team.html", "about//team.html", "http://example.invalid/menu.html", "//example.invalid/menu.html",
+ "file:menu.html", "menu.html?x=1", "menu.html#top", ".hidden.html", "about/.secret.html", ".well-known/", "menu",
+ "menu.htm", "menu.HTML", "menu.html.bak", "style.css", "about", "about/team", "%2e%2e/menu.html", "men u.html",
+ "ménu.html", "menu.html\n", "__ods_view__.html", "__pycache__/x.html", "-menu.html", "x" * 124 + ".html",
+ "a/" * 12 + "x.html", "x/" * 12, LONG + "x" * 24 + ".html", None, 7, ["menu.html"])
+# The plan of tests/test-preview-inspection.mjs. LEGACY_HASH is its plan_hash
+# on main before page existed, and the plugin's hash of it.
+LEGACY = {"schemaVersion": 1, "action": "inspect", "siteId": "site-" + "a" * 24, "sha256": "a" * 64,
+ "viewport": {"width": 375, "height": 812},
+ "steps": [{"action": "assert-hidden", "locator": {"selector": "#card"}},
+ {"action": "click", "locator": {"role": "button", "name": "Mostrar próximos eventos", "exact": True}},
+ {"action": "assert-visible", "locator": {"selector": "#card"}}]}
+LEGACY_HASH = "156ae762e4eb8cbec17063823bfb5a61705c2917251da8cdff43af2c9ffbc06c"
+DIRECTIVE = {"maxSide": 1200, "maxPixels": 1048576, "maxBytes": 131072}
+
+
+def site(page=None, steps=None):
+ data = bundle("", steps or [step("assert-visible", "h1")], files=SITE)
+ if page is not None:
+ data["request"]["page"] = page
+ return data
+
+
+def config(**extra):
+ return {"ownerUid": os.getuid(), "docker": "/usr/bin/docker", "transport": "local",
+ "snapshotRoot": "/unused", "imageId": "sha256:" + "a" * 64, **extra}
+
+
+def passed(request):
+ """A passed capsule receipt for this request, as the broker relays it."""
+ return {"schemaVersion": 1, "kind": protocol.KIND, "status": "passed", "siteId": request["siteId"],
+ "sha256": request["sha256"], "planSha256": protocol.plan_hash(request),
+ **({"page": request["page"]} if "page" in request else {}), "viewport": request["viewport"],
+ "steps": [], "diagnostics": {}, "blockedRequests": [], "scope": protocol.inspection_scope(request)}
+
+
+class PageProtocol(unittest.TestCase):
+ def test_existing_requests_validate_and_hash_exactly_as_before(self):
+ self.assertEqual(protocol.validate_request(dict(LEGACY)), LEGACY)
+ self.assertEqual(protocol.plan_hash(LEGACY), LEGACY_HASH)
+ self.assertEqual(protocol.plan_hash({**LEGACY, "screenshot": DIRECTIVE}), LEGACY_HASH)
+ self.assertEqual(protocol.inspection_scope(LEGACY), protocol.SCOPE)
+ self.assertEqual(set(protocol.failure("unavailable", LEGACY)),
+ {"schemaVersion", "kind", "status", "errorCode", "siteId", "sha256", "planSha256", "scope"})
+ # A page is part of the plan; the screenshot directive still is not.
+ paged = {**LEGACY, "page": "menu.html"}
+ self.assertNotEqual(protocol.plan_hash(paged), LEGACY_HASH)
+ self.assertEqual(protocol.plan_hash({**paged, "screenshot": DIRECTIVE}), protocol.plan_hash(paged))
+ protocol.validate_request({**paged, "screenshot": DIRECTIVE})
+ # One optional field more; nothing else is loosened.
+ for extra in ({"pages": ["menu.html"]}, {"url": "http://localhost/menu.html"}, {"path": "menu.html"}):
+ with self.subTest(extra=extra), self.assertRaises(protocol.Invalid):
+ protocol.validate_request({**paged, **extra})
+
+ def test_a_page_is_a_relative_published_html_path(self):
+ for page in GOOD:
+ with self.subTest(page=page):
+ self.assertEqual(protocol.validate_request({**LEGACY, "page": page})["page"], page)
+ self.assertEqual(protocol.page_file("about/"), "about/index.html")
+ self.assertEqual(protocol.page_file("menu.html"), "menu.html")
+ for page in BAD:
+ with self.subTest(page=page), self.assertRaisesRegex(protocol.Invalid, "invalid page"):
+ protocol.validate_request({**LEGACY, "page": page})
+
+ def test_the_page_must_be_a_file_of_the_snapshot(self):
+ for page in ("menu.html", "about/team.html", "about/", "index.html", "[slug].html"):
+ with self.subTest(page=page):
+ request, files = protocol.validate_bundle(site(page))
+ self.assertEqual(request["page"], page)
+ self.assertIn(protocol.page_file(page), files)
+ for page in ("missing.html", "about/missing.html", "contact/", "Menu.html", "blog/"):
+ with self.subTest(page=page), self.assertRaises(protocol.MissingPage):
+ protocol.validate_bundle(site(page))
+ self.assertTrue(issubclass(protocol.MissingPage, protocol.Invalid))
+
+ def test_the_scope_and_failures_of_a_page_plan_name_the_page(self):
+ request = site("menu.html")["request"]
+ self.assertEqual(protocol.inspection_scope(request), protocol.SCOPE + protocol.PAGE_SCOPE)
+ self.assertIn("links between pages were not followed", protocol.PAGE_SCOPE)
+ self.assertNotIn(protocol.PAGE_SCOPE, protocol.inspection_scope(site()["request"]))
+ failed = protocol.failure("page_not_found", request)
+ self.assertEqual((failed["page"], failed["planSha256"]), ("menu.html", protocol.plan_hash(request)))
+
+
+class PageBroker(unittest.TestCase):
+ def test_an_image_without_the_label_is_refused_before_reading_the_snapshot(self):
+ request = site("menu.html")["request"]
+ for label in (b"", b"<no value>\n", b"snapshot-page-v0\n"):
+ with self.subTest(label=label), patch.object(broker, "bounded_process", return_value=label) as process, \
+ patch.object(broker, "snapshot_bundle") as snapshot:
+ result = broker.inspect_request(request, config())
+ self.assertEqual(result, protocol.failure("unsupported_capability", request))
+ self.assertEqual(result["page"], "menu.html")
+ self.assertEqual(process.call_count, 1)
+ self.assertIn("org.osmantic.ods.inspection.page", str(process.call_args))
+ snapshot.assert_not_called()
+
+ def test_plans_without_a_page_never_ask_for_the_label(self):
+ class Reached(Exception):
+ pass
+ with patch.object(broker, "bounded_process") as process, \
+ patch.object(broker, "snapshot_bundle", side_effect=Reached), self.assertRaises(Reached):
+ broker.inspect_request(site()["request"], config())
+ process.assert_not_called()
+
+ def run_broker(self, request, settings, snapshot):
+ """The broker with a page-labelled image: its result, the request the
+ snapshot export saw and the bundle the capsule received."""
+ seen = {}
+
+ def process(argv, body, **_kwargs):
+ if "inspect" in argv:
+ return b"snapshot-page-v1\n"
+ if "exec" in argv:
+ seen["export"] = protocol.strict_json(body)
+ return protocol.canonical(snapshot)
+ if "run" in argv:
+ seen["capsule"] = protocol.strict_json(body)
+ return protocol.canonical(passed(seen["capsule"]["request"]))
+ return b""
+
+ def local(_root, exported, _owner):
+ seen["export"] = exported
+ return snapshot
+
+ with patch.object(broker, "bounded_process", side_effect=process), \
+ patch.object(broker, "snapshot_bundle", side_effect=local):
+ return broker.inspect_request(request, settings), seen
+
+ def test_the_export_never_sees_the_page_and_the_capsule_gets_it_bound(self):
+ data = site()
+ request = {**data["request"], "page": "menu.html"}
+ native = config(transport="docker-desktop", docker="/Applications/Docker.app/Contents/Resources/bin/docker",
+ dockerSocket="/Users/owner/.docker/run/docker.sock", snapshotRoot="/previews")
+ for settings in (config(), native):
+ with self.subTest(transport=settings["transport"]):
+ result, seen = self.run_broker(request, settings, data)
+ # An older publisher-side export helper keeps working.
+ self.assertEqual(seen["export"], data["request"])
+ self.assertEqual(seen["capsule"], {**data, "request": request})
+ self.assertEqual((result["status"], result["page"]), ("passed", "menu.html"))
+
+ def test_a_page_outside_the_snapshot_is_refused_before_any_browser_runs(self):
+ data = site()
+ for page in ("missing.html", "about/missing.html", "contact/", "Menu.html"):
+ request = {**data["request"], "page": page}
+ with self.subTest(page=page):
+ result, seen = self.run_broker(request, config(), data)
+ self.assertEqual(result, protocol.failure("page_not_found", request))
+ self.assertNotIn("capsule", seen)
+
+ def test_a_receipt_must_name_exactly_the_requested_page(self):
+ data = site()
+ cases = [({**data["request"], "page": "menu.html"}, None), ({**data["request"], "page": "menu.html"}, "contact.html"),
+ (data["request"], "index.html")]
+ for request, named in cases:
+ receipt = {key: value for key, value in passed(request).items() if key != "page"}
+ if named is not None:
+ receipt["page"] = named
+ with self.subTest(page=request.get("page"), named=named), \
+ patch.object(broker, "bounded_process", side_effect=lambda argv, *_a, receipt=receipt, **_k:
+ b"snapshot-page-v1\n" if "inspect" in argv else protocol.canonical(receipt) if "run" in argv else b""), \
+ patch.object(broker, "snapshot_bundle", return_value=data), \
+ self.assertRaisesRegex(protocol.Invalid, "invalid capsule receipt"):
+ broker.inspect_request(request, config())
+
+
+class PageBrowser(ScriptedBrowser):
+ """The scripted browser of test_preview_inspection.py, loading the wrapper
+ the capsule's own loopback server serves: each navigation goes through the
+ installed request guard and only an admitted one loads. `click_to` is a
+ sibling page that a click navigates to, as a link would."""
+
+ def __init__(self, click_to=None, **kwargs):
+ super().__init__(**kwargs)
+ self.click_to, self.routes, self.wrapper, self.served, self.url = click_to, [], None, None, None
+ self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+
+ def route(self, _pattern, handler):
+ self.guard = handler
+
+ def navigate(self, url):
+ route = Route(url, navigation=True)
+ self.guard(route)
+ self.routes.append(route)
+ return route.outcome == "continued"
+
+ def goto(self, url, **_):
+ self.calls.append("goto")
+ self.origin = url.split("/__ods_inspection__.html")[0]
+ if self.navigate(url):
+ with self.opener.open(url, timeout=5) as response:
+ self.wrapper = response.read().decode()
+ src = self.origin + re.search(r'src="([^"]*)"', self.wrapper).group(1)
+ if self.navigate(src):
+ with self.opener.open(src, timeout=5) as response:
+ self.served = response.read()
+ self.url = src
+ self.emit(self.load_errors)
+
+ def click(self, **_):
+ if self.click_to:
+ self.navigate(self.origin + "/" + self.site + "/" + self.click_to)
+ super().click()
+
+
+class PagePalette(PaletteDouble):
+ """The palette load of a page plan, whose wrapper frames that page."""
+
+ def __init__(self, image, page):
+ super().__init__(image)
+ self.page = page
+
+ def goto(self, url, **kwargs):
+ self.during_load = [("/" + self.site + "/" + self.page, True)]
+ super().goto(url, **kwargs)
+ self.url = self.origin + "/" + self.site + "/" + self.page
+
+
+class PageCapsule(unittest.TestCase):
+ PREFIX = "/site-" + "a" * 24 + "/"
+
+ def run_scripted(self, browser, data):
+ browser.site = data["request"]["siteId"]
+ return capsule.run_browser(data, playwright_factory=browser)
+
+ def test_the_wrapper_frames_the_requested_page(self):
+ prefix = self.PREFIX
+ for page, src in (("menu.html", prefix + "menu.html"), ("about/", prefix + "about/"),
+ ("[slug].html", prefix + "%5Bslug%5D.html"), (None, prefix)):
+ entry = capsule.entry_path(prefix, {} if page is None else {"page": page})
+ document = capsule.wrapper_document(entry).decode()
+ with self.subTest(page=page):
+ self.assertEqual(entry, src)
+ self.assertIn(f'src="{src}"', document)
+ self.assertNotIn("<script", document.lower())
+ self.assertIn('sandbox="' + protocol.SANDBOX + '"', document)
+ # The served URL is exactly the file validate_bundle bound.
+ self.assertEqual(capsule.snapshot_file(entry, prefix, SITE), "index.html" if page is None else protocol.page_file(page))
+
+ def test_the_guard_admits_the_requested_page_as_the_one_entry_navigation(self):
+ origin, prefix = "http://127.0.0.1:4321", self.PREFIX
+
+ def guarded(entry):
+ context, blocked = PaletteDouble(b""), []
+ capsule.guard_requests(context, context, origin, prefix, blocked, files=SITE, entry=entry)
+
+ def go(path, navigation=True):
+ route = Route(origin + path, navigation)
+ context.guard(route)
+ return route.outcome
+ return go, blocked
+
+ go, blocked = guarded(prefix + "menu.html")
+ self.assertEqual([go("/__ods_inspection__.html"), go(prefix + "menu.html"), go(prefix + "style.css", False)],
+ ["continued", "continued", "continued"])
+ # A click-through to a sibling page is one more navigation: blocked.
+ self.assertEqual(go(prefix + "contact.html"), "aborted")
+ self.assertEqual(blocked, ["navigation"])
+ # The page replaces the site entry; no other page loads in its place.
+ for path in (prefix, prefix + "index.html", prefix + "contact.html", prefix + "menu.html?x=1"):
+ go, blocked = guarded(prefix + "menu.html")
+ go("/__ods_inspection__.html")
+ with self.subTest(path=path):
+ self.assertEqual(go(path), "aborted")
+ self.assertEqual(blocked, ["navigation"])
+ # Without a page the site entry stays the one entry navigation.
+ go, _ = guarded(prefix)
+ self.assertEqual([go("/__ods_inspection__.html"), go(prefix)], ["continued", "continued"])
+ go, _ = guarded(prefix)
+ go("/__ods_inspection__.html")
+ self.assertEqual(go(prefix + "menu.html"), "aborted")
+
+ def test_a_page_plan_loads_that_page_and_its_receipt_names_it(self):
+ browser = PageBrowser()
+ data = site("menu.html", [step("assert-visible", "#bread")])
+ result = self.run_scripted(browser, data)
+ self.assertEqual(result["status"], "passed", result)
+ self.assertEqual(result["page"], "menu.html")
+ self.assertEqual(result["planSha256"], protocol.plan_hash(data["request"]))
+ self.assertEqual(result["scope"], protocol.SCOPE + protocol.PAGE_SCOPE)
+ # The loopback server's wrapper framed menu.html, and the guard admitted it.
+ self.assertIn('src="/' + browser.site + '/menu.html"', browser.wrapper)
+ self.assertEqual([route.outcome for route in browser.routes], ["continued", "continued"])
+ self.assertEqual(browser.served, SITE["menu.html"])
+ # Without a page the receipt keeps exactly its former shape.
+ entry = PageBrowser()
+ result = self.run_scripted(entry, site(None, [step("assert-visible", "h1")]))
+ self.assertEqual(set(result), {"schemaVersion", "kind", "status", "siteId", "sha256", "planSha256", "viewport",
+ "steps", "diagnostics", "blockedRequests", "scope"})
+ self.assertEqual(result["scope"], protocol.SCOPE)
+ self.assertIn('src="/' + entry.site + '/"', entry.wrapper)
+ self.assertEqual(entry.served, SITE["index.html"])
+
+ def test_a_click_through_to_a_sibling_page_is_blocked(self):
+ browser = PageBrowser(click_to="contact.html")
+ result = self.run_scripted(browser, site("menu.html", [step("click", "#to-contact"), step("assert-visible", "h1")]))
+ self.assertEqual(result["status"], "failed", result)
+ self.assertEqual(result["blockedRequests"], ["navigation"])
+ self.assertEqual([(item["action"], item["errorCode"]) for item in result["steps"]], [("click", "click_failed")])
+ self.assertEqual(result["page"], "menu.html")
+ self.assertEqual([route.outcome for route in browser.routes], ["continued", "continued", "aborted"])
+
+ def test_the_palette_is_captured_from_the_same_page(self):
+ palette = PagePalette(harness.PaletteCaptureTests.GREEN, "menu.html")
+ result = self.run_scripted(PageBrowser(palette=palette), site("menu.html"))
+ self.assertEqual(result["status"], "passed", result)
+ self.assertIn("renderedColors", result)
+ self.assertEqual([route.outcome for route in palette.routes], ["continued", "continued"])
+
+
[email protected](os.environ.get("ODS_PREVIEW_BROWSER_TESTS") == "1" or os.environ.get("ODS_INSPECTION_TEST_IMAGE"),
+ "requires isolated real browser")
+class RealPages(unittest.TestCase):
+ def text(self, selector, value):
+ return {"action": "assert-text", "locator": {"selector": selector}, "expectedText": value}
+
+ def test_a_three_page_site_is_checked_page_by_page(self):
+ for page, selector, value in (("menu.html", "#bread", "Sourdough"), ("contact.html", "#phone", "555 0100"),
+ ("about/", "h1", "About"), ("about/team.html", "h1", "Team"), ("[slug].html", "h1", "Post")):
+ with self.subTest(page=page):
+ result = execute_real(site(page, [self.text(selector, value)]))
+ self.assertEqual(result["status"], "passed", result)
+ self.assertEqual(result["page"], page)
+ self.assertEqual(result["blockedRequests"], [])
+ entry = execute_real(site(None, [self.text("h1", "Crumb & Co")]))
+ self.assertEqual(entry["status"], "passed", entry)
+ self.assertNotIn("page", entry)
+
+ def test_links_between_pages_are_not_followed(self):
+ result = execute_real(site("menu.html", [step("click", "#to-contact"), self.text("h1", "Contact")]))
+ self.assertEqual(result["status"], "failed", result)
+ self.assertIn("navigation", result["blockedRequests"])
+ self.assertEqual(result["page"], "menu.html")
+
+
+if __name__ == "__main__":
+ unittest.main()