diff --git a/packages/flow/openadapt_flow/runtime/identity_vlm.py b/packages/flow/openadapt_flow/runtime/identity_vlm.py index ebad05e1fc..dd6a0e79d8 100644 --- a/packages/flow/openadapt_flow/runtime/identity_vlm.py +++ b/packages/flow/openadapt_flow/runtime/identity_vlm.py @@ -21,12 +21,228 @@ from __future__ import annotations import tempfile +from dataclasses import dataclass +from enum import Enum from pathlib import Path from typing import Any, Optional +from openadapt_flow.ir import Region +from openadapt_flow.runtime.grounder import component_may_egress +from openadapt_flow.runtime.remote_vlm import ( + _MAX_MODEL_IMAGE_DIM, + IdentityVerdict, + extract_roi_crop, + gold_crop_for_model, +) + DEFAULT_MODEL = "mlx-community/Qwen3-VL-4B-Instruct-4bit" +class VetoVerdict(str, Enum): + """Unified veto-only verdict for local and remote VLM guards. + + * ``PASS`` -- confident affirmative match/state; fail-to-veto ONLY. + NEVER overrides a failed deterministic check. + * ``VETO`` -- explicit mismatch or violated state; halts execution. + * ``ABSTAIN`` -- uncertain, unreachable, timeout, exception, or malformed + output; halts execution. + """ + + PASS = "pass" + VETO = "veto" + ABSTAIN = "abstain" + + +@dataclass(frozen=True) +class VetoDecision: + """Outcome of a single veto-only VLM guard check.""" + + verdict: VetoVerdict + reason: str = "" + used_gold_crop: bool = False + + @property + def should_halt(self) -> bool: + """True for ``VETO`` and ``ABSTAIN``; False only for ``PASS``.""" + return self.verdict is not VetoVerdict.PASS + + def apply_to_deterministic(self, deterministic_passed: bool) -> bool: + """Combine with a deterministic check under strict veto-only semantics. + + ``VETO`` / ``ABSTAIN`` always halt (return ``False``). ``PASS`` lets a + passing deterministic check stand, and NEVER overrides a failing + deterministic check. + """ + return bool(deterministic_passed) and not self.should_halt + + +class VetoOnlyVLMGuard: + """Unified veto-only guard over local (MLX) or remote VLM backends. + + Enforces two invariants across identity and state checks: + + 1. **Strict veto-only semantics**: ``VETO`` and ``ABSTAIN`` (including any + transport error, model exception, or unrecognized answer) halt; ``PASS`` + only declines to veto and never overrides deterministic checks. + 2. **GOLD ROI cropping**: when full-frame screenshots exceed ``max_dim`` + (1024px) and a target/alert ``roi`` is provided, the guard extracts + native-resolution ROI crops (or GOLD global+local composites) within the + ``max_dim`` budget instead of uniformly downscaling away small text. + """ + + def __init__( + self, + *, + identity_vlm: Optional[Any] = None, + state_verifier: Optional[Any] = None, + max_dim: int = _MAX_MODEL_IMAGE_DIM, + ) -> None: + self._identity_vlm = identity_vlm + self._state_verifier = state_verifier + self._max_dim = max_dim + + @property + def MAY_EGRESS(self) -> bool: + """Propagate screenshot-egress classification from wrapped backends.""" + return component_may_egress(self._identity_vlm) or component_may_egress( + self._state_verifier + ) + + def check_identity( + self, + recorded_png: bytes, + live_png: bytes, + *, + roi: Optional[Region] = None, + ) -> VetoDecision: + """Run a veto-only identity comparison, applying symmetric ROI cropping if ``roi`` is set.""" + if self._identity_vlm is None: + return VetoDecision(VetoVerdict.ABSTAIN, reason="no_identity_backend") + + used_gold = False + rec_sent = recorded_png + live_sent = live_png + if roi is not None: + rec_crop = extract_roi_crop(recorded_png, roi, max_dim=self._max_dim) + live_crop = extract_roi_crop(live_png, roi, max_dim=self._max_dim) + if rec_crop is None or live_crop is None: + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="identity_roi_unavailable", + used_gold_crop=False, + ) + rec_sent = rec_crop + live_sent = live_crop + used_gold = True + + try: + compare_fn = getattr(self._identity_vlm, "compare", None) + if callable(compare_fn): + raw = compare_fn(rec_sent, live_sent) + if raw is IdentityVerdict.VERIFY: + return VetoDecision(VetoVerdict.PASS, used_gold_crop=used_gold) + if raw is IdentityVerdict.MISMATCH: + return VetoDecision( + VetoVerdict.VETO, + reason="identity_mismatch", + used_gold_crop=used_gold, + ) + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="identity_abstain", + used_gold_crop=used_gold, + ) + + same_fn = getattr(self._identity_vlm, "same_or_different", None) + if callable(same_fn): + ans = same_fn(rec_sent, live_sent) + if ans == "same": + return VetoDecision(VetoVerdict.PASS, used_gold_crop=used_gold) + if ans == "different": + return VetoDecision( + VetoVerdict.VETO, + reason="identity_different", + used_gold_crop=used_gold, + ) + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="identity_unrecognized", + used_gold_crop=used_gold, + ) + except Exception as exc: + return VetoDecision( + VetoVerdict.ABSTAIN, + reason=f"identity_error:{type(exc).__name__}", + used_gold_crop=used_gold, + ) + + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="unsupported_identity_backend", + used_gold_crop=used_gold, + ) + + def check_state( + self, + screenshot: bytes, + expected_state: str, + *, + roi: Optional[Region] = None, + ) -> VetoDecision: + """Run a veto-only state check, applying GOLD cropping when ``roi`` is set.""" + if self._state_verifier is None: + return VetoDecision(VetoVerdict.ABSTAIN, reason="no_state_backend") + + used_gold = False + sent = screenshot + if roi is not None: + gold = gold_crop_for_model(screenshot, roi=roi, max_dim=self._max_dim) + if gold.used_gold: + sent = gold.composite_png + used_gold = True + + try: + verify_fn = getattr(self._state_verifier, "verify", None) + if not callable(verify_fn): + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="unsupported_state_backend", + used_gold_crop=used_gold, + ) + raw = verify_fn(sent, expected_state) + except Exception as exc: + return VetoDecision( + VetoVerdict.ABSTAIN, + reason=f"state_error:{type(exc).__name__}", + used_gold_crop=used_gold, + ) + + if raw == "yes": + return VetoDecision(VetoVerdict.PASS, used_gold_crop=used_gold) + if raw == "no": + return VetoDecision( + VetoVerdict.VETO, + reason="state_not_held", + used_gold_crop=used_gold, + ) + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="state_uncertain", + used_gold_crop=used_gold, + ) + + def same_or_different( + self, + recorded_png: bytes, + live_png: bytes, + *, + roi: Optional[Region] = None, + ) -> str: + """Satisfy the ``IdentityVLM`` protocol: ``"same"`` iff ``PASS``, else ``"different"``.""" + decision = self.check_identity(recorded_png, live_png, roi=roi) + return "same" if decision.verdict is VetoVerdict.PASS else "different" + + class MLXIdentityVLM: """Local MLX VLM used as a veto-only same/different identity comparator. diff --git a/packages/flow/openadapt_flow/runtime/remote_vlm.py b/packages/flow/openadapt_flow/runtime/remote_vlm.py index 6d88c415fb..ee36316c30 100644 --- a/packages/flow/openadapt_flow/runtime/remote_vlm.py +++ b/packages/flow/openadapt_flow/runtime/remote_vlm.py @@ -18,6 +18,7 @@ from __future__ import annotations import base64 +import math import os from dataclasses import dataclass from enum import Enum @@ -64,6 +65,10 @@ def _b64(png: bytes) -> str: # but never useful). Full-frame screenshots are downscaled below this before # they cross the wire; identity crops are already small and are left untouched. _MAX_MODEL_IMAGE_DIM = 1024 +_GOLD_DIVIDER_PX = 4 +_GOLD_DIVIDER_RGB = (48, 48, 48) +_GOLD_DEFAULT_PAD_RATIO = 0.15 +_GOLD_MIN_PAD_PX = 16 def _downscale_for_model( @@ -96,6 +101,234 @@ def _downscale_for_model( return png, 1.0 +def _png_dimensions(png: bytes) -> Optional[tuple[int, int]]: + """Return ``(width, height)`` for decodable image bytes, or ``None``.""" + try: + from io import BytesIO + + from PIL import Image + + with Image.open(BytesIO(png)) as img: + w, h = img.size + return (int(w), int(h)) if w > 0 and h > 0 else None + except Exception: + return None + + +def extract_roi_crop( + png: bytes, + roi: Region, + max_dim: int = _MAX_MODEL_IMAGE_DIM, + *, + pad_ratio: float = _GOLD_DEFAULT_PAD_RATIO, + min_pad_px: int = _GOLD_MIN_PAD_PX, +) -> Optional[bytes]: + """Extract a padded ROI crop bounded by ``max_dim``, or ``None`` if invalid. + + Unlike :func:`gold_crop_for_model`, this always crops to ``roi`` regardless + of whether the source frame exceeds ``max_dim`` so callers comparing two + frames (e.g. identity checks) never pair a cropped ROI with an uncropped + full screenshot. + """ + if max_dim <= 0: + return None + try: + from io import BytesIO + + from PIL import Image + + img = Image.open(BytesIO(png)).convert("RGB") + w, h = img.size + rx, ry, rw, rh = roi + if rw <= 0 or rh <= 0: + return None + x0 = int(rx) + y0 = int(ry) + x1 = int(rx + rw) + y1 = int(ry + rh) + # Require the entire requested subject region to be visible inside the + # image; a partly clipped ROI would omit part of the identifier on one + # side while forwarding a nonempty crop. + if x0 < 0 or y0 < 0 or x1 > w or y1 > h: + return None + + pad_x = max(min_pad_px, round((x1 - x0) * pad_ratio)) + pad_y = max(min_pad_px, round((y1 - y0) * pad_ratio)) + cx0 = max(0, x0 - pad_x) + cy0 = max(0, y0 - pad_y) + cx1 = min(w, x1 + pad_x) + cy1 = min(h, y1 + pad_y) + + crop = img.crop((cx0, cy0, cx1, cy1)) + cw, ch = crop.size + if max(cw, ch) > max_dim: + local_scale = max_dim / max(cw, ch) + crop = crop.resize( + (max(1, round(cw * local_scale)), max(1, round(ch * local_scale))), + Image.Resampling.LANCZOS, + ) + buf = BytesIO() + crop.save(buf, format="PNG") + return buf.getvalue() + except Exception: + return None + + +@dataclass(frozen=True) +class GoldCropResult: + """Deterministic Global-to-Local (GOLD) view of a screenshot within ``max_dim``. + + * ``global_png`` -- downscaled full frame (``max(w, h) <= max_dim``) + * ``global_scale`` -- scale factor of ``global_png`` (``<= 1.0``) + * ``local_png`` -- high-resolution ROI crop extracted from the original + unscaled frame (``max(w, h) <= max_dim``) + * ``local_scale`` -- scale factor of ``local_png`` relative to original + pixels (``1.0`` whenever the padded ROI fits inside ``max_dim``) + * ``local_origin`` -- ``(crop_x, crop_y)`` top-left of the padded ROI in + original full-frame pixel coordinates + * ``composite_png`` -- single-image GOLD composite (global overview stacked + above the high-resolution local ROI crop, bounded by ``max_dim`` on both + axes) for single-image VLM endpoints + * ``used_gold`` -- ``True`` iff the original frame exceeded ``max_dim`` + and a valid ROI preserved higher pixel resolution than uniform downscaling + """ + + global_png: bytes + global_scale: float + local_png: bytes + local_scale: float + local_origin: tuple[int, int] + composite_png: bytes + used_gold: bool + + +def gold_crop_for_model( + png: bytes, + roi: Optional[Region] = None, + max_dim: int = _MAX_MODEL_IMAGE_DIM, + *, + pad_ratio: float = _GOLD_DEFAULT_PAD_RATIO, + min_pad_px: int = _GOLD_MIN_PAD_PX, +) -> GoldCropResult: + """Build a deterministic Global-to-Local (GOLD) view within ``max_dim``. + + When ``roi`` is ``None``, empty/out-of-bounds, or the screenshot already + fits inside ``max_dim``, this falls back cleanly to + :func:`_downscale_for_model` with ``used_gold=False`` (zero behavior + change for existing callers). + + When ``max(w, h) > max_dim`` and a valid ``roi = (x, y, w, h)`` is given, + the target/alert region is cropped directly from the original unscaled + screenshot with deterministic padding so small text and banners retain + native 1:1 resolution (or the highest scale that fits ``max_dim``), paired + with a global overview frame inside a single ``<= max_dim`` composite. + """ + global_png, global_scale = _downscale_for_model(png, max_dim=max_dim) + fallback = GoldCropResult( + global_png=global_png, + global_scale=global_scale, + local_png=global_png, + local_scale=global_scale, + local_origin=(0, 0), + composite_png=global_png, + used_gold=False, + ) + if roi is None or max_dim <= _GOLD_DIVIDER_PX + 2: + return fallback + + try: + from io import BytesIO + + from PIL import Image + + img = Image.open(BytesIO(png)).convert("RGB") + w, h = img.size + if max(w, h) <= max_dim: + return fallback + + rx, ry, rw, rh = roi + if rw <= 0 or rh <= 0: + return fallback + x0 = max(0, min(w, int(rx))) + y0 = max(0, min(h, int(ry))) + x1 = max(0, min(w, int(rx + rw))) + y1 = max(0, min(h, int(ry + rh))) + if x1 <= x0 or y1 <= y0: + return fallback + + pad_x = max(min_pad_px, round((x1 - x0) * pad_ratio)) + pad_y = max(min_pad_px, round((y1 - y0) * pad_ratio)) + cx0 = max(0, x0 - pad_x) + cy0 = max(0, y0 - pad_y) + cx1 = min(w, x1 + pad_x) + cy1 = min(h, y1 + pad_y) + + crop = img.crop((cx0, cy0, cx1, cy1)) + cw, ch = crop.size + if max(cw, ch) > max_dim: + local_scale = max_dim / max(cw, ch) + local_img = crop.resize( + (max(1, round(cw * local_scale)), max(1, round(ch * local_scale))), + Image.Resampling.LANCZOS, + ) + else: + local_scale = 1.0 + local_img = crop + + local_buf = BytesIO() + local_img.save(local_buf, format="PNG") + local_png = local_buf.getvalue() + + # Build the single-image GOLD composite inside (max_dim x max_dim). + # Preserve native local crop resolution up to 2/3 of the vertical budget + # and fit the global overview in the remaining height. + avail_h = max_dim - _GOLD_DIVIDER_PX + local_max_h = min(local_img.height, max(1, (avail_h * 2) // 3)) + if local_img.height > local_max_h or local_img.width > max_dim: + comp_local_scale = min( + max_dim / local_img.width, local_max_h / local_img.height + ) + local_panel = local_img.resize( + ( + max(1, round(local_img.width * comp_local_scale)), + max(1, round(local_img.height * comp_local_scale)), + ), + Image.Resampling.LANCZOS, + ) + else: + local_panel = local_img + + global_max_h = max(1, avail_h - local_panel.height) + comp_global_scale = min(max_dim / w, global_max_h / h) + global_panel = img.resize( + ( + max(1, round(w * comp_global_scale)), + max(1, round(h * comp_global_scale)), + ), + Image.Resampling.LANCZOS, + ) + + comp_w = max(global_panel.width, local_panel.width) + comp_h = global_panel.height + _GOLD_DIVIDER_PX + local_panel.height + canvas = Image.new("RGB", (comp_w, comp_h), _GOLD_DIVIDER_RGB) + canvas.paste(global_panel, (0, 0)) + canvas.paste(local_panel, (0, global_panel.height + _GOLD_DIVIDER_PX)) + comp_buf = BytesIO() + canvas.save(comp_buf, format="PNG") + + return GoldCropResult( + global_png=global_png, + global_scale=global_scale, + local_png=local_png, + local_scale=local_scale, + local_origin=(cx0, cy0), + composite_png=comp_buf.getvalue(), + used_gold=local_scale > global_scale, + ) + except Exception: + return fallback + + class RemoteVLMClient: """Thin HTTP client for the VLM service. Never raises on transport failure. @@ -235,8 +468,41 @@ def locate( screen_png: bytes, intent: str, ocr_text: Optional[str] = None, + roi: Optional[Region] = None, ) -> Optional[GrounderMatch]: + if roi is not None: + gold = gold_crop_for_model(screen_png, roi=roi) + if gold.used_gold: + match = self._ground_and_map( + gold.local_png, + intent, + ocr_text, + scale=gold.local_scale, + origin=gold.local_origin, + ) + if match is not None: + return match + # Local ROI had no proposal: fall back deterministically to the + # global downscaled frame so a drifted target can still be found. + return self._ground_and_map( + gold.global_png, + intent, + ocr_text, + scale=gold.global_scale, + origin=(0, 0), + ) sent, scale = _downscale_for_model(screen_png) + return self._ground_and_map(sent, intent, ocr_text, scale=scale, origin=(0, 0)) + + def _ground_and_map( + self, + sent: bytes, + intent: str, + ocr_text: Optional[str], + *, + scale: float, + origin: tuple[int, int], + ) -> Optional[GrounderMatch]: data = self._client.ground(sent, intent, ocr_text) if data is None: return None # SAFE: service down => no proposal @@ -244,11 +510,30 @@ def locate( if not point or not isinstance(point, (list, tuple)) or len(point) != 2: return None x, y = point - if not isinstance(x, (int, float)) or not isinstance(y, (int, float)): + if ( + isinstance(x, bool) + or isinstance(y, bool) + or not isinstance(x, (int, float)) + or not isinstance(y, (int, float)) + or not math.isfinite(x) + or not math.isfinite(y) + ): + return None + # Validate coordinates against the actual image submitted to the model + # before translating back to full-frame pixel space; if dimensions + # cannot be established or the point falls outside the observed image, + # treat it as a miss (local retries globally; global returns None). + dims = _png_dimensions(sent) + if dims is None: return None - # The model saw a downscaled frame; map the proposal back to the - # original screenshot's pixel space before anything acts on it. - px, py = int(round(x / scale)), int(round(y / scale)) + sent_w, sent_h = dims + if x < 0 or y < 0 or x >= sent_w or y >= sent_h: + return None + # The model saw a downscaled or ROI-cropped frame; map the proposal back + # to the original screenshot's pixel space before anything acts on it. + ox, oy = origin + px = ox + int(round(x / scale)) + py = oy + int(round(y / scale)) region: Region = ( max(0, px - _REGION_HALF_W), max(0, py - _REGION_HALF_H), @@ -277,10 +562,20 @@ class RemoteStateVerifier: def __init__(self, client: RemoteVLMClient) -> None: self._client = client - def verify(self, screenshot: bytes, expected_state: str) -> str: - # Downscale below the model's image ceiling; there are no coordinates - # to map back for a yes/no/uncertain verdict. - sent, _scale = _downscale_for_model(screenshot) + def verify( + self, + screenshot: bytes, + expected_state: str, + roi: Optional[Region] = None, + ) -> str: + # Downscale below the model's image ceiling; when an ROI is supplied on + # a >1024px frame, send a GOLD composite (global overview + native-res + # local crop) within the same 1024px budget. + if roi is not None: + gold = gold_crop_for_model(screenshot, roi=roi) + sent = gold.composite_png if gold.used_gold else gold.global_png + else: + sent, _scale = _downscale_for_model(screenshot) data = self._client.verify_state(sent, expected_state) if data is None: return "uncertain" # SAFE: service down => unproven => halt @@ -289,9 +584,14 @@ def verify(self, screenshot: bytes, expected_state: str) -> str: return holds return "uncertain" - def holds(self, screenshot: bytes, expected_state: str) -> bool: + def holds( + self, + screenshot: bytes, + expected_state: str, + roi: Optional[Region] = None, + ) -> bool: """Convenience: True ONLY on a confident 'yes' (uncertain/no => False).""" - return self.verify(screenshot, expected_state) == "yes" + return self.verify(screenshot, expected_state, roi=roi) == "yes" @dataclass diff --git a/packages/flow/tests/test_local_vlm_gold_crop.py b/packages/flow/tests/test_local_vlm_gold_crop.py new file mode 100644 index 0000000000..8e33c0661a --- /dev/null +++ b/packages/flow/tests/test_local_vlm_gold_crop.py @@ -0,0 +1,500 @@ +"""Tests for Global-to-Local (GOLD) ROI cropping and VetoOnlyVLMGuard. + +Proves: +1. Zero behavior regression when ``roi`` is omitted or frames fit ``<= 1024px``. +2. Improved pixel-fidelity preservation on ``> 1024px`` synthetic frames within + the ``<= 1024px`` model ceiling, plus deterministic coordinate round-trips. +3. Strict veto-only semantics: ``VETO`` and ``ABSTAIN`` always halt; ``PASS`` + never overrides a failed deterministic check. +""" + +from __future__ import annotations + +import io +from typing import Optional + +import pytest +from PIL import Image, ImageDraw + +from openadapt_flow.runtime.grounder import component_may_egress +from openadapt_flow.runtime.identity import IdentityVLM +from openadapt_flow.runtime.identity_vlm import ( + VetoDecision, + VetoOnlyVLMGuard, + VetoVerdict, +) +from openadapt_flow.runtime.remote_vlm import ( + _MAX_MODEL_IMAGE_DIM, + IdentityVerdict, + RemoteGrounder, + RemoteIdentityVLM, + RemoteStateVerifier, + RemoteVLMClient, + _downscale_for_model, + gold_crop_for_model, +) +from openadapt_flow.runtime.replayer import EgressNotPermitted, Replayer + + +def _dims(png: bytes) -> tuple[int, int]: + return Image.open(io.BytesIO(png)).size + + +def _make_synthetic_banner_frame( + w: int = 2560, + h: int = 1440, + roi: tuple[int, int, int, int] = (900, 80, 320, 64), +) -> bytes: + """Create a >1024px frame with crisp alternating 2px vertical bars in ``roi``. + + Uniformly downscaling 2560 -> 1024 (0.4x) blurs 2px stripes into grey, + whereas a native-resolution GOLD ROI crop preserves full black/white contrast. + """ + img = Image.new("RGB", (w, h), (235, 235, 235)) + draw = ImageDraw.Draw(img) + rx, ry, rw, rh = roi + # Distinct red border around the alert banner region + draw.rectangle( + [rx, ry, rx + rw - 1, ry + rh - 1], fill=(255, 255, 255), outline=(220, 30, 30) + ) + # High-frequency 2px vertical bars inside the banner (proxy for small crisp text) + for x in range(rx + 8, rx + rw - 8, 4): + draw.rectangle([x, ry + 12, x + 1, ry + rh - 12], fill=(0, 0, 0)) + buf = io.BytesIO() + img.save(buf, format="PNG") + return buf.getvalue() + + +class _StubClient: + def __init__(self, *, ground_responses=None, state=None): + self._ground_responses = list(ground_responses or []) + self._state = state + self.ground_calls: list[tuple[tuple[int, int], str]] = [] + self.state_calls: list[tuple[tuple[int, int], str]] = [] + self.last_state_png: Optional[bytes] = None + + def ground(self, png, intent, ocr_text=None): + self.ground_calls.append((_dims(png), intent)) + if self._ground_responses: + return self._ground_responses.pop(0) + return None + + def verify_state(self, png, expected): + self.state_calls.append((_dims(png), expected)) + self.last_state_png = png + return self._state + + +# -------------------------------------------------------------------------- +# 1. Zero behavior regression +# -------------------------------------------------------------------------- + + +def test_gold_crop_no_roi_matches_downscale_exactly(): + frame = _make_synthetic_banner_frame(2560, 1440) + expected_png, expected_scale = _downscale_for_model(frame) + res = gold_crop_for_model(frame, roi=None) + assert res.used_gold is False + assert res.global_png == expected_png + assert res.local_png == expected_png + assert res.composite_png == expected_png + assert res.global_scale == expected_scale + assert res.local_scale == expected_scale + assert res.local_origin == (0, 0) + + +def test_gold_crop_small_frame_is_untouched(): + frame = _make_synthetic_banner_frame(800, 600, roi=(100, 50, 200, 60)) + res = gold_crop_for_model(frame, roi=(100, 50, 200, 60)) + assert res.used_gold is False + assert res.global_png == frame + assert res.composite_png == frame + assert res.global_scale == 1.0 + assert res.local_scale == 1.0 + + +@pytest.mark.parametrize( + "bad_roi", + [ + (0, 0, 0, 50), + (0, 0, 50, -10), + (5000, 5000, 100, 100), + ], +) +def test_gold_crop_invalid_roi_falls_back_cleanly(bad_roi): + frame = _make_synthetic_banner_frame(2048, 1200) + res = gold_crop_for_model(frame, roi=bad_roi) + assert res.used_gold is False + assert max(_dims(res.composite_png)) == _MAX_MODEL_IMAGE_DIM + + +def test_gold_crop_malformed_bytes_fail_safe(): + res = gold_crop_for_model(b"not-a-png", roi=(10, 10, 100, 50)) + assert res.used_gold is False + assert res.composite_png == b"not-a-png" + assert res.global_scale == 1.0 + + +# -------------------------------------------------------------------------- +# 2. Improved crop preservation on >1024px frames within the 1024px budget +# -------------------------------------------------------------------------- + + +def test_gold_crop_preserves_native_resolution_and_high_frequency_detail(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + res = gold_crop_for_model(frame, roi=roi) + + assert res.used_gold is True + assert res.global_scale == pytest.approx(1024 / 2560) + assert res.local_scale == 1.0 + assert res.local_scale > res.global_scale + + # Every output stays strictly inside the 1024px model ceiling on both axes. + assert max(_dims(res.global_png)) <= _MAX_MODEL_IMAGE_DIM + assert max(_dims(res.local_png)) <= _MAX_MODEL_IMAGE_DIM + assert max(_dims(res.composite_png)) <= _MAX_MODEL_IMAGE_DIM + + # Verify high-frequency stripe contrast is preserved in local_png (black=0, white=255) + # whereas uniform global downscaling smears the stripes. + local_im = Image.open(io.BytesIO(res.local_png)).convert("L") + local_extrema = local_im.getextrema() + assert local_extrema == (0, 255) + + global_im = Image.open(io.BytesIO(res.global_png)).convert("L") + rx, ry, rw, rh = roi + gs = res.global_scale + global_banner = global_im.crop( + ( + int(rx * gs) + 4, + int(ry * gs) + 4, + int((rx + rw) * gs) - 4, + int((ry + rh) * gs) - 4, + ) + ) + g_lo, g_hi = global_banner.getextrema() + assert (g_hi - g_lo) < 255 # downscaled banner lost full black-white contrast + + +def test_gold_crop_oversized_roi_stays_within_budget_and_beats_global(): + frame = _make_synthetic_banner_frame(3200, 2400, roi=(400, 300, 1400, 900)) + res = gold_crop_for_model(frame, roi=(400, 300, 1400, 900)) + assert res.used_gold is True + assert max(_dims(res.local_png)) == _MAX_MODEL_IMAGE_DIM + assert max(_dims(res.composite_png)) <= _MAX_MODEL_IMAGE_DIM + assert res.local_scale > res.global_scale + + +def test_remote_grounder_gold_crop_maps_local_point_to_original_frame(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + expected = gold_crop_for_model(frame, roi=roi) + ox, oy = expected.local_origin + + stub = _StubClient(ground_responses=[{"point": [100, 40], "confidence": 0.92}]) + grounder = RemoteGrounder(stub) + match = grounder.locate(frame, "Dismiss alert", roi=roi) + + assert len(stub.ground_calls) == 1 + assert stub.ground_calls[0][0] == _dims(expected.local_png) + assert match is not None + assert match.point == (ox + 100, oy + 40) + assert match.confidence == pytest.approx(0.92) + + +def test_remote_grounder_gold_crop_falls_back_to_global_when_local_misses(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + + # Local ROI returns null; global pass finds target at (500, 200) in 1024x576 frame. + stub = _StubClient( + ground_responses=[ + {"point": None}, + {"point": [500, 200], "confidence": 0.85}, + ] + ) + grounder = RemoteGrounder(stub) + match = grounder.locate(frame, "Submit button", roi=roi) + + assert len(stub.ground_calls) == 2 + assert stub.ground_calls[1][0] == (1024, 576) + assert match is not None + assert match.point == (round(500 / (1024 / 2560)), round(200 / (1024 / 2560))) + + +def test_remote_state_verifier_uses_gold_composite_within_budget(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + stub = _StubClient(state={"holds": "yes"}) + verifier = RemoteStateVerifier(stub) + + assert verifier.verify(frame, "error banner visible", roi=roi) == "yes" + assert len(stub.state_calls) == 1 + sent_w, sent_h = stub.state_calls[0][0] + assert max(sent_w, sent_h) <= _MAX_MODEL_IMAGE_DIM + # Composite is taller than plain 1024x576 global downscale because it appends the ROI crop. + assert sent_h > 576 + + +# -------------------------------------------------------------------------- +# 3. Unified Veto-Only Local VLM Guard semantics +# -------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("det_passed", "verdict", "expected"), + [ + (True, VetoVerdict.PASS, True), + (True, VetoVerdict.VETO, False), + (True, VetoVerdict.ABSTAIN, False), + # PASS must NEVER override a failed deterministic check. + (False, VetoVerdict.PASS, False), + (False, VetoVerdict.VETO, False), + (False, VetoVerdict.ABSTAIN, False), + ], +) +def test_veto_decision_strict_veto_only_truth_table(det_passed, verdict, expected): + decision = VetoDecision(verdict=verdict) + assert decision.should_halt is (verdict is not VetoVerdict.PASS) + assert decision.apply_to_deterministic(det_passed) is expected + + +class _FakeRemoteIdentity: + def __init__(self, verdict: IdentityVerdict): + self.verdict = verdict + self.seen_dims: list[tuple[tuple[int, int], tuple[int, int]]] = [] + + def compare(self, crop_a: bytes, crop_b: bytes) -> IdentityVerdict: + self.seen_dims.append((_dims(crop_a), _dims(crop_b))) + return self.verdict + + +class _FakeLocalIdentity: + def __init__(self, answer: str): + self.answer = answer + + def same_or_different(self, recorded_png: bytes, live_png: bytes) -> str: + return self.answer + + +class _ExplodingBackend: + def compare(self, crop_a: bytes, crop_b: bytes): + raise RuntimeError("backend crashed") + + def verify(self, screenshot: bytes, expected_state: str): + raise RuntimeError("backend crashed") + + +def test_guard_satisfies_identity_vlm_protocol(): + guard = VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("same")) + assert isinstance(guard, IdentityVLM) + + +def test_guard_identity_uses_gold_crop_and_maps_verdicts(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + + remote_ok = _FakeRemoteIdentity(IdentityVerdict.VERIFY) + guard_ok = VetoOnlyVLMGuard(identity_vlm=remote_ok) + dec_ok = guard_ok.check_identity(frame, frame, roi=roi) + assert dec_ok.verdict is VetoVerdict.PASS + assert dec_ok.should_halt is False + assert dec_ok.used_gold_crop is True + assert max(remote_ok.seen_dims[0][0]) <= _MAX_MODEL_IMAGE_DIM + assert remote_ok.seen_dims[0][0][0] < 1024 # cropped ROI, not full 1024px frame + assert guard_ok.same_or_different(frame, frame, roi=roi) == "same" + + guard_mismatch = VetoOnlyVLMGuard( + identity_vlm=_FakeRemoteIdentity(IdentityVerdict.MISMATCH) + ) + dec_veto = guard_mismatch.check_identity(frame, frame, roi=roi) + assert dec_veto.verdict is VetoVerdict.VETO + assert dec_veto.should_halt is True + assert guard_mismatch.same_or_different(frame, frame, roi=roi) == "different" + + guard_abstain = VetoOnlyVLMGuard( + identity_vlm=_FakeRemoteIdentity(IdentityVerdict.ABSTAIN) + ) + dec_abs = guard_abstain.check_identity(frame, frame, roi=roi) + assert dec_abs.verdict is VetoVerdict.ABSTAIN + assert dec_abs.should_halt is True + assert guard_abstain.same_or_different(frame, frame, roi=roi) == "different" + + +def test_guard_local_identity_and_exceptions_fail_safe_to_halt(): + frame = _make_synthetic_banner_frame(800, 600) + + assert ( + VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("same")) + .check_identity(frame, frame) + .verdict + is VetoVerdict.PASS + ) + assert ( + VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("different")) + .check_identity(frame, frame) + .verdict + is VetoVerdict.VETO + ) + assert ( + VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("maybe")) + .check_identity(frame, frame) + .verdict + is VetoVerdict.ABSTAIN + ) + + exploding = VetoOnlyVLMGuard( + identity_vlm=_ExplodingBackend(), state_verifier=_ExplodingBackend() + ) + id_dec = exploding.check_identity(frame, frame) + st_dec = exploding.check_state(frame, "saved") + assert id_dec.verdict is VetoVerdict.ABSTAIN and id_dec.should_halt is True + assert st_dec.verdict is VetoVerdict.ABSTAIN and st_dec.should_halt is True + + empty = VetoOnlyVLMGuard() + assert empty.check_identity(frame, frame).verdict is VetoVerdict.ABSTAIN + assert empty.check_state(frame, "saved").verdict is VetoVerdict.ABSTAIN + + +def test_guard_state_check_uses_gold_composite_and_veto_only_semantics(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + + for raw, expected_verdict in [ + ("yes", VetoVerdict.PASS), + ("no", VetoVerdict.VETO), + ("uncertain", VetoVerdict.ABSTAIN), + ]: + stub = _StubClient(state={"holds": raw}) + guard = VetoOnlyVLMGuard(state_verifier=RemoteStateVerifier(stub)) + dec = guard.check_state(frame, "alert visible", roi=roi) + assert dec.verdict is expected_verdict + assert dec.used_gold_crop is True + assert max(stub.state_calls[0][0]) <= _MAX_MODEL_IMAGE_DIM + + +# -------------------------------------------------------------------------- +# 4. Review regressions: egress propagation, bounds checks, symmetric ROI +# -------------------------------------------------------------------------- + + +def test_guard_propagates_egress_classification_to_replayer(): + remote_client = RemoteVLMClient("http://127.0.0.1:9") + remote_id_guard = VetoOnlyVLMGuard(identity_vlm=RemoteIdentityVLM(remote_client)) + remote_state_guard = VetoOnlyVLMGuard( + state_verifier=RemoteStateVerifier(remote_client) + ) + local_guard = VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("same")) + + assert component_may_egress(remote_id_guard) is True + assert component_may_egress(remote_state_guard) is True + assert component_may_egress(local_guard) is False + + # Replayer refuses a wrapped remote comparator without explicit opt-in. + with pytest.raises(EgressNotPermitted): + Replayer(backend=object(), vision=object(), identity_vlm=remote_id_guard) + + # With opt-in, Replayer wires it and sets the egress report flag. + replayer_remote = Replayer( + backend=object(), + vision=object(), + identity_vlm=remote_id_guard, + allow_model_grounding=True, + ) + assert replayer_remote._screenshots_may_leave_box is True + + # Purely local guard requires no opt-in and does not set the egress flag. + replayer_local = Replayer( + backend=object(), vision=object(), identity_vlm=local_guard + ) + assert replayer_local._screenshots_may_leave_box is False + + +@pytest.mark.parametrize( + "bad_point", + [ + [-1, 20], + [999, 20], + [20, 999], + [float("nan"), 20], + [float("inf"), 20], + [True, 20], + ], +) +def test_remote_grounder_rejects_out_of_bounds_local_and_falls_back_to_global( + bad_point, +): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + + # Invalid local point must NOT be translated; must trigger global fallback. + stub = _StubClient( + ground_responses=[ + {"point": bad_point, "confidence": 0.99}, + {"point": [500, 200], "confidence": 0.85}, + ] + ) + match = RemoteGrounder(stub).locate(frame, "Submit", roi=roi) + assert len(stub.ground_calls) == 2 + assert match is not None + assert match.point == (round(500 / (1024 / 2560)), round(200 / (1024 / 2560))) + + # Invalid global point must return None (no proposal). + stub_global_bad = _StubClient( + ground_responses=[ + {"point": bad_point, "confidence": 0.99}, + {"point": [2000, 2000], "confidence": 0.99}, + ] + ) + assert RemoteGrounder(stub_global_bad).locate(frame, "Submit", roi=roi) is None + + +def test_guard_identity_crops_both_frames_symmetrically_or_abstains(): + roi = (200, 80, 320, 64) + large_frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + small_frame = _make_synthetic_banner_frame(1024, 768, roi=roi) + + # Mixed sizes (one >1024px, one <=1024px): BOTH sides must get ROI crops, + # never a crop paired with an uncropped full screenshot. + backend = _FakeRemoteIdentity(IdentityVerdict.VERIFY) + guard = VetoOnlyVLMGuard(identity_vlm=backend) + dec = guard.check_identity(large_frame, small_frame, roi=roi) + assert dec.verdict is VetoVerdict.PASS + assert dec.used_gold_crop is True + assert len(backend.seen_dims) == 1 + rec_dims, live_dims = backend.seen_dims[0] + assert rec_dims == live_dims + assert rec_dims[0] < 1024 and rec_dims[1] < 768 + + # ROI partially clipped on the smaller frame (x=900..1220 exceeds 1024): + # must ABSTAIN without invoking the backend rather than comparing a partial + # crop against a full crop. + clipped_roi = (900, 80, 320, 64) + backend_clipped = _FakeRemoteIdentity(IdentityVerdict.VERIFY) + dec_clipped = VetoOnlyVLMGuard(identity_vlm=backend_clipped).check_identity( + large_frame, small_frame, roi=clipped_roi + ) + assert dec_clipped.verdict is VetoVerdict.ABSTAIN + assert dec_clipped.reason == "identity_roi_unavailable" + assert dec_clipped.should_halt is True + assert backend_clipped.seen_dims == [] + + # ROI outside the smaller frame: must ABSTAIN without invoking the backend. + oob_roi = (1500, 80, 320, 64) + backend_oob = _FakeRemoteIdentity(IdentityVerdict.VERIFY) + dec_oob = VetoOnlyVLMGuard(identity_vlm=backend_oob).check_identity( + large_frame, small_frame, roi=oob_roi + ) + assert dec_oob.verdict is VetoVerdict.ABSTAIN + assert dec_oob.reason == "identity_roi_unavailable" + assert dec_oob.should_halt is True + assert backend_oob.seen_dims == [] + + # Malformed bytes on one side: must ABSTAIN without invoking the backend. + backend_bad = _FakeRemoteIdentity(IdentityVerdict.VERIFY) + dec_bad = VetoOnlyVLMGuard(identity_vlm=backend_bad).check_identity( + large_frame, b"not-a-png", roi=roi + ) + assert dec_bad.verdict is VetoVerdict.ABSTAIN + assert dec_bad.should_halt is True + assert backend_bad.seen_dims == [] diff --git a/packages/flow/tests/test_remote_vlm.py b/packages/flow/tests/test_remote_vlm.py index 3bc16395d2..db0198cb88 100644 --- a/packages/flow/tests/test_remote_vlm.py +++ b/packages/flow/tests/test_remote_vlm.py @@ -7,8 +7,11 @@ from __future__ import annotations +import io + import httpx import pytest +from PIL import Image from openadapt_flow.runtime.grounder import Grounder, GrounderMatch from openadapt_flow.runtime.remote_vlm import ( @@ -19,7 +22,13 @@ RemoteVLMClient, ) -PNG = b"\x89PNG\r\n\x1a\n" # bytes need not be a real PNG for the client layer +PNG = b"\x89PNG\r\n\x1a\n" # unreadable stub header for transport-failure tests + + +def _valid_png(w: int = 200, h: int = 100) -> bytes: + buf = io.BytesIO() + Image.new("RGB", (w, h), (220, 220, 220)).save(buf, format="PNG") + return buf.getvalue() # --- happy path (baseline: clients pass through good answers) --------------- @@ -54,11 +63,23 @@ def test_grounder_pass_through_point(monkeypatch): ), ) g = RemoteGrounder(RemoteVLMClient("http://x", token="t")) - m = g.locate(PNG, "Save button") + m = g.locate(_valid_png(200, 100), "Save button") assert isinstance(m, GrounderMatch) assert m.point == (120, 45) +def test_grounder_refuses_unreadable_image_bytes(monkeypatch): + monkeypatch.setattr( + httpx, + "post", + lambda url, **kw: httpx.Response( + 200, json={"point": [120, 45], "confidence": 0.9} + ), + ) + g = RemoteGrounder(RemoteVLMClient("http://x", token="t")) + assert g.locate(PNG, "Save button") is None + + def test_remote_grounder_satisfies_protocol(): g = RemoteGrounder(RemoteVLMClient("http://x")) assert isinstance(g, Grounder) diff --git a/packages/flow/tests/test_wire_remote_vlm.py b/packages/flow/tests/test_wire_remote_vlm.py index beff66bab7..f58cfa03b1 100644 --- a/packages/flow/tests/test_wire_remote_vlm.py +++ b/packages/flow/tests/test_wire_remote_vlm.py @@ -112,8 +112,14 @@ def test_grounder_outage_returns_no_proposal(): def test_grounder_proposes_a_point_when_reachable(): + import io + + from PIL import Image + + buf = io.BytesIO() + Image.new("RGB", (200, 100), (220, 220, 220)).save(buf, format="PNG") g = RemoteGrounder(_StubClient(ground={"point": [120, 44], "confidence": 0.9})) - m = g.locate(b"png", "click Save", None) + m = g.locate(buf.getvalue(), "click Save", None) assert m is not None and m.point == (120, 44)