Skip to content

Automate browser based workflows with AI

fix(SKY-12102): key copilot code-block synthesis on captured control-state (#7254)

Andrew Neilson0b0fce76e757
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.py
index 567a0d1de..301d2bb94 100644
--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py
+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py
@@ -31,6 +31,7 @@ _ENTRY_RESUME_AFTER_AUTH_VAR = "_scout_entry_resume_after_auth"
_ENTRY_RESUME_TARGET_VAR = "_scout_entry_resume_target"
_ENTRY_OPENER_VAR = "_scout_entry_opener"
_OPTIONAL_DISMISSAL_VAR = "_scout_optional_dismissal"
+_READONLY_DEFERRED_VAR = "_scout_readonly_actual"
_ENTRY_LOCATOR_VARS = (_ENTRY_TARGET_VAR, _ENTRY_RESUME_TARGET_VAR, _ENTRY_OPENER_VAR)
_INTERNAL_SCOUT_VARS = (
_ENTRY_TARGET_VAR,
@@ -39,6 +40,7 @@ _INTERNAL_SCOUT_VARS = (
_ENTRY_RESUME_TARGET_VAR,
_ENTRY_OPENER_VAR,
_OPTIONAL_DISMISSAL_VAR,
+ _READONLY_DEFERRED_VAR,
)
# Base name for the download var bound by `async with page.expect_download() as <name>:`.
@@ -801,9 +803,11 @@ def synthesize_code_block(
lines.append(f"{_INDENT * 3}pass")
elif entry_post_auth_resume_index:
lines.append(f"{_INDENT}if not {_ENTRY_RESUME_AFTER_AUTH_VAR}:")
+ lines.append(f"{_INDENT * 2}pass")
append_step(f"Open {entry_url}", "goto_url", line_start)
emitted = 0
+ deferred_readonly_assertions: list[tuple[int, str, str, str]] = []
def action_indent_for(trajectory_index: int) -> str:
if entry_replay_condition_active:
@@ -911,8 +915,30 @@ def synthesize_code_block(
if typed_identity is not None:
typed_param_keys[typed_identity] = param_key
diagnostics.typed_param_bindings.append((trajectory_index, param_key))
- lines.append(f"{action_indent}await {locator}.fill(str({param_key}))")
- append_step(f"Type into {_step_target(interaction)}", "input_text", line_start)
+ readonly_or_disabled = bool(interaction.get("control_readonly")) or bool(
+ interaction.get("control_disabled")
+ )
+ if readonly_or_disabled and bool(interaction.get("control_value_satisfied")):
+ verify_target = _step_target(interaction)
+ lines.append(f"{action_indent}try:")
+ lines.append(f"{action_indent}{_INDENT}{_READONLY_DEFERRED_VAR} = await {locator}.input_value()")
+ lines.append(f"{action_indent}except Exception:")
+ lines.append(f"{action_indent}{_INDENT}{_READONLY_DEFERRED_VAR} = None")
+ lines.append(
+ f"{action_indent}if {_READONLY_DEFERRED_VAR} is not None "
+ f"and {_READONLY_DEFERRED_VAR} != str({param_key}):"
+ )
+ lines.append(
+ f"{action_indent}{_INDENT}print("
+ f"{_py_str(f'{verify_target}: read-only value ')} + repr({_READONLY_DEFERRED_VAR})"
+ f" + {_py_str(' does not match expected ')} + repr(str({param_key})))"
+ )
+ append_step(f"Verify {verify_target}", "input_text", line_start)
+ elif readonly_or_disabled:
+ deferred_readonly_assertions.append((trajectory_index, locator, param_key, _step_target(interaction)))
+ else:
+ lines.append(f"{action_indent}await {locator}.fill(str({param_key}))")
+ append_step(f"Type into {_step_target(interaction)}", "input_text", line_start)
elif tool_name == CREDENTIAL_FILL_TOOL_NAME:
credential_id = str(interaction.get("credential_id") or "").strip()
credential_field = str(interaction.get("credential_field") or "").strip()
@@ -954,9 +980,57 @@ def synthesize_code_block(
continue
emitted += 1
- if entry_replay_condition_active and emitted == 0 and not entry_post_auth_resume_index:
+ if (
+ entry_replay_condition_active
+ and (emitted - len(deferred_readonly_assertions)) == 0
+ and (not entry_post_auth_resume_index)
+ ):
lines.append(f"{_INDENT * 2}pass")
+ if deferred_readonly_assertions:
+ deferred_base = _INDENT
+ if entry_replay_condition_active:
+ lines.append(f"{_INDENT}if not {_ENTRY_REUSED_VAR}:")
+ deferred_base = _INDENT * 2
+
+ def emit_deferred_readonly_assertion(indent: str, locator_expr: str, param_ref: str, target: str) -> None:
+ line_start = len(lines) + 1
+ lines.append(f"{indent}try:")
+ lines.append(f"{indent}{_INDENT}{_READONLY_DEFERRED_VAR} = await {locator_expr}.input_value()")
+ lines.append(f"{indent}except Exception:")
+ lines.append(f"{indent}{_INDENT}{_READONLY_DEFERRED_VAR} = None")
+ lines.append(f"{indent}if {_READONLY_DEFERRED_VAR} == {_py_str('')}:")
+ lines.append(
+ f"{indent}{_INDENT}raise AssertionError("
+ f"{_py_str(f'{target} was not set to the required value by an earlier step')})"
+ )
+ lines.append(
+ f"{indent}elif {_READONLY_DEFERRED_VAR} is not None and {_READONLY_DEFERRED_VAR} != str({param_ref}):"
+ )
+ lines.append(
+ f"{indent}{_INDENT}print("
+ f"{_py_str(f'{target}: read-only value ')} + repr({_READONLY_DEFERRED_VAR})"
+ f" + {_py_str(' does not match expected ')} + repr(str({param_ref})))"
+ )
+ append_step(f"Verify {target}", "input_text", line_start)
+
+ for deferred_index, deferred_locator, deferred_param_key, deferred_target in deferred_readonly_assertions:
+ if entry_post_auth_resume_index and deferred_index < entry_post_auth_resume_index:
+ continue
+ emit_deferred_readonly_assertion(deferred_base, deferred_locator, deferred_param_key, deferred_target)
+
+ pre_resume_deferred = [
+ entry
+ for entry in deferred_readonly_assertions
+ if entry_post_auth_resume_index and entry[0] < entry_post_auth_resume_index
+ ]
+ if pre_resume_deferred:
+ lines.append(f"{deferred_base}if not {_ENTRY_RESUME_AFTER_AUTH_VAR}:")
+ for _, deferred_locator, deferred_param_key, deferred_target in pre_resume_deferred:
+ emit_deferred_readonly_assertion(
+ deferred_base + _INDENT, deferred_locator, deferred_param_key, deferred_target
+ )
+
if compile_download_target and reached_download_target is not None:
# The download affordance is observed in nav_targets, not necessarily a trajectory click, so the
# download is an appended terminal step compiled from the typed target — never an in-place click upgrade.
diff --git a/skyvern/forge/sdk/copilot/composition_browser_expressions.py b/skyvern/forge/sdk/copilot/composition_browser_expressions.py
index c70caab6e..843393c45 100644
--- a/skyvern/forge/sdk/copilot/composition_browser_expressions.py
+++ b/skyvern/forge/sdk/copilot/composition_browser_expressions.py
@@ -108,6 +108,34 @@ def selector_match_count_expression(css_selector: str) -> str:
return f"(() => {{ try {{ return document.querySelectorAll({sel}).length; }} catch (e) {{ return -1; }}}})()"
+# Read only the readonly/disabled control-state booleans for a CSS or XPath selector; never reads the
+# element's value. An unresolvable selector or non-CSS/XPath engine returns null (UNKNOWN editability).
+def scout_control_state_expression(selector: str) -> str:
+ sel = json.dumps(selector)
+ return (
+ "(() => {"
+ f" const sel = {sel};"
+ " let el = null;"
+ " try {"
+ " if (/^\\s*(xpath=|\\(?\\/)/.test(sel)) {"
+ " const x = sel.replace(/^\\s*xpath=/, '');"
+ " const r = document.evaluate(x, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);"
+ " el = r ? r.singleNodeValue : null;"
+ " } else {"
+ " el = document.querySelector(sel);"
+ " }"
+ " } catch (e) { return null; }"
+ " if (!el) return null;"
+ " const attrOf = (k) => (el.getAttribute && el.getAttribute(k)) || '';"
+ " const readonly = el.readOnly === true || (el.hasAttribute && el.hasAttribute('readonly'))"
+ " || attrOf('aria-readonly').toLowerCase() === 'true';"
+ " const disabled = el.disabled === true || (el.hasAttribute && el.hasAttribute('disabled'))"
+ " || attrOf('aria-disabled').toLowerCase() === 'true';"
+ " return { readonly: !!readonly, disabled: !!disabled };"
+ "})()"
+ )
+
+
COMPOSITION_VISUAL_OBSTRUCTION_CANDIDATES_EXPRESSION = (
"(() => {"
" const body = document.body; if (!body) return [];"
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 91c8f1e27..1250b4cab 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -162,6 +162,9 @@ class FillCarry(BaseModel):
typed_length: int = 0
typed_value: str = ""
value: str = ""
+ control_readonly: bool | None = None
+ control_disabled: bool | None = None
+ control_value_satisfied: bool | None = None
credential_id: str = ""
credential_field: str = ""
@@ -240,6 +243,7 @@ class StructuredContext(BaseModel):
payload["loaded_result_targets"] = [
_sanitized_loaded_result_target_payload(target) for target in self.loaded_result_targets
]
+ payload["fill_carry"] = [carry.model_dump(mode="json", exclude_none=True) for carry in self.fill_carry]
return json.dumps(payload, indent=2)
@classmethod
@@ -408,6 +412,10 @@ def _carry_int(value: FillCarryPrimitive) -> int:
return parsed if parsed > 0 else 0
+def _carry_bool(value: FillCarryPrimitive) -> bool | None:
+ return value if isinstance(value, bool) else None
+
+
def _fill_carry_from_scout_trajectory(trajectory: Sequence[Mapping[str, FillCarryPrimitive]]) -> list[FillCarry]:
carry: list[FillCarry] = []
for interaction in trajectory:
@@ -429,6 +437,9 @@ def _fill_carry_from_scout_trajectory(trajectory: Sequence[Mapping[str, FillCarr
accessible_name=accessible_name,
typed_length=typed_length,
typed_value=_carry_text(interaction.get("typed_value")),
+ control_readonly=_carry_bool(interaction.get("control_readonly")),
+ control_disabled=_carry_bool(interaction.get("control_disabled")),
+ control_value_satisfied=_carry_bool(interaction.get("control_value_satisfied")),
)
)
elif tool_name == "select_option":
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 063d1b804..584787c72 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -187,6 +187,10 @@ class ScoutedInteraction(TypedDict):
raw_typed_value: NotRequired[str]
role: NotRequired[str]
accessible_name: NotRequired[str]
+ # Captured for the type_text lane only; absent on credential fills (secret-leak boundary).
+ control_readonly: NotRequired[bool]
+ control_disabled: NotRequired[bool]
+ control_value_satisfied: NotRequired[bool]
trajectory_index: NotRequired[int]
carried: NotRequired[bool]
# Credential fills carry references and metadata only — never secret values.
@@ -343,7 +347,7 @@ class AgentContext:
# flow_evidence does not cover it (closes the spent-inspection-budget
# deadlock). Each item: {url, had_bounded_schema, reached_via}.
prior_observed_acted_pages: list[dict[str, Any]] = field(default_factory=list)
- prior_fill_carry: list[dict[str, str | int]] = field(default_factory=list)
+ prior_fill_carry: list[dict[str, str | int | bool | None]] = field(default_factory=list)
fill_carry_rebound_done: bool = False
post_budget_page_inspection_required: bool = False
post_budget_page_inspection_url: str | None = None
diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
index 65b8dfb2c..3aac217da 100644
--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
@@ -14,6 +14,7 @@ from skyvern.forge.sdk.copilot.build_phase import (
BuildPhase,
advance_to_composing,
)
+from skyvern.forge.sdk.copilot.composition_browser_expressions import scout_control_state_expression
from skyvern.forge.sdk.copilot.config import (
BlockAuthoringPolicy,
download_scout_act_required_for_policy,
@@ -593,11 +594,72 @@ async def _attach_reperception_targets_on_non_advancing_click(
_TYPE_READBACK_SETTLE_SECONDS = 0.3
+async def _read_scout_field_value(ctx: AgentContext, selector: str) -> str | None:
+ """Read a field's current value through the discovery MCP surface, or None when unavailable."""
+ server = getattr(ctx, "discovery_mcp_server", None)
+ if server is None:
+ return None
+ try:
+ readback = await asyncio.wait_for(
+ server.call_internal_tool("skyvern_get_value", {"selector": selector}),
+ timeout=_DISCOVERY_PER_CALL_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ LOG.debug("scout field-value read failed; leaving the value unread", exc_info=True)
+ return None
+ if not isinstance(readback, dict) or not readback.get("ok"):
+ return None
+ value = (readback.get("data") or {}).get("value")
+ return value if isinstance(value, str) else None
+
+
+_XPATH_SELECTOR_RE = re.compile(r"^\s*(?:xpath=|\(?/)")
+_ENGINE_PREFIXED_SELECTOR_RE = re.compile(r"^\s*[A-Za-z][\w-]*=")
+
+
+def _selector_supports_control_state_probe(selector: str) -> bool:
+ """Only bare CSS and XPath resolve inside the probe expression. A Playwright-engine selector
+ (``role=``, ``text=``, or a ``>>`` chain) would throw in-page and cost a round-trip to learn nothing.
+ """
+ if _XPATH_SELECTOR_RE.match(selector):
+ return True
+ return ">>" not in selector and not _ENGINE_PREFIXED_SELECTOR_RE.match(selector)
+
+
+async def _probe_scout_control_state(ctx: AgentContext, selector: str) -> tuple[bool | None, bool | None]:
+ """Return (readonly, disabled) booleans for a captured type_text target, either None when the control
+ state cannot be resolved (unavailable surface, unresolvable/non-CSS-or-XPath selector). No raw field
+ value crosses this boundary — the evaluate reads attributes only.
+ """
+ if not isinstance(selector, str) or not selector.strip():
+ return None, None
+ if not _selector_supports_control_state_probe(selector):
+ return None, None
+ server = getattr(ctx, "discovery_mcp_server", None)
+ if server is None:
+ return None, None
+ try:
+ result = await asyncio.wait_for(
+ server.call_internal_tool("skyvern_evaluate", {"expression": scout_control_state_expression(selector)}),
+ timeout=_DISCOVERY_PER_CALL_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ LOG.debug("scout control-state probe failed; treating editability as unknown", exc_info=True)
+ return None, None
+ if not isinstance(result, dict) or not result.get("ok"):
+ return None, None
+ state = (result.get("data") or {}).get("result")
+ if not isinstance(state, dict):
+ return None, None
+ return bool(state.get("readonly")), bool(state.get("disabled"))
+
+
async def _verify_scout_type_landed(
ctx: AgentContext,
*,
selector: str,
typed_length: Any,
+ prefetched_value: str | None = None,
) -> dict[str, Any] | None:
"""Confirm a non-empty type actually entered the field, else return a failure.
@@ -613,29 +675,15 @@ async def _verify_scout_type_landed(
return None
if not isinstance(typed_length, int) or typed_length <= 0:
return None
- server = getattr(ctx, "discovery_mcp_server", None)
- if server is None:
+ if getattr(ctx, "discovery_mcp_server", None) is None:
return None
- async def _read_back() -> Any:
- try:
- readback = await asyncio.wait_for(
- server.call_internal_tool("skyvern_get_value", {"selector": selector}),
- timeout=_DISCOVERY_PER_CALL_TIMEOUT_SECONDS,
- )
- except Exception:
- LOG.debug("scout type-landed read-back failed; leaving the type result unverified", exc_info=True)
- return None
- if not isinstance(readback, dict) or not readback.get("ok"):
- return None
- return (readback.get("data") or {}).get("value")
-
- value = await _read_back()
+ value = prefetched_value if prefetched_value is not None else await _read_scout_field_value(ctx, selector)
if isinstance(value, str) and value.strip() == "":
# A controlled/React input can mirror its value asynchronously, so a first read may be
# transiently empty; settle briefly and re-read once before declaring the type lost.
await asyncio.sleep(_TYPE_READBACK_SETTLE_SECONDS)
- value = await _read_back()
+ value = await _read_scout_field_value(ctx, selector)
if isinstance(value, str) and value.strip() == "":
return {
"ok": False,
@@ -668,8 +716,18 @@ async def _type_text_post_hook(
"typed_length": typed_length,
"url": url,
}
- landing_failure = await _verify_scout_type_landed(ctx, selector=selector, typed_length=typed_length)
- if landing_failure is not None:
+ has_landing_probe = (
+ isinstance(selector, str) and bool(selector.strip()) and isinstance(typed_length, int) and typed_length > 0
+ )
+ field_value = await _read_scout_field_value(ctx, selector) if has_landing_probe else None
+ control_readonly, control_disabled = (
+ await _probe_scout_control_state(ctx, selector) if has_landing_probe else (None, None)
+ )
+ is_readonly_or_disabled = bool(control_readonly) or bool(control_disabled)
+ landing_failure = await _verify_scout_type_landed(
+ ctx, selector=selector, typed_length=typed_length, prefetched_value=field_value
+ )
+ if landing_failure is not None and not is_readonly_or_disabled:
return landing_failure
_mark_pending_browser_interaction_observation(ctx, tool_name="type_text", url=url)
role, accessible_name = await _resolve_scout_role_name(ctx, selector)
@@ -690,6 +748,16 @@ async def _type_text_post_hook(
else None
)
raw_typed_value = pending_typed_value if value_landed and isinstance(pending_typed_value, str) else ""
+ if is_readonly_or_disabled and isinstance(pending_typed_value, str):
+ settled_value = field_value
+ if settled_value is not None and settled_value != pending_typed_value:
+ await asyncio.sleep(_TYPE_READBACK_SETTLE_SECONDS)
+ settled_value = await _read_scout_field_value(ctx, selector)
+ control_value_satisfied: bool | None = (
+ settled_value == pending_typed_value if settled_value is not None else None
+ )
+ else:
+ control_value_satisfied = None
_record_scouted_interaction(
ctx,
tool_name="type_text",
@@ -700,6 +768,9 @@ async def _type_text_post_hook(
raw_typed_value=raw_typed_value,
role=role,
accessible_name=accessible_name,
+ control_readonly=control_readonly,
+ control_disabled=control_disabled,
+ control_value_satisfied=control_value_satisfied,
)
observation_step, page_evidence = await _register_scout_interaction_observation(
ctx, tool_name="type_text", selector=selector, source_url=source_url, url=url
diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.py
index 9d5f7d7eb..5e70639fe 100644
--- a/skyvern/forge/sdk/copilot/tools/scouting.py
+++ b/skyvern/forge/sdk/copilot/tools/scouting.py
@@ -319,6 +319,9 @@ def _record_scouted_interaction(
typed_length: int = 0,
role: str = "",
accessible_name: str = "",
+ control_readonly: bool | None = None,
+ control_disabled: bool | None = None,
+ control_value_satisfied: bool | None = None,
credential_id: str = "",
credential_field: str = "",
credential_name: str = "",
@@ -347,6 +350,13 @@ def _record_scouted_interaction(
artifact["role"] = role
if accessible_name:
artifact["accessible_name"] = accessible_name
+ if tool_name == "type_text":
+ if control_readonly is not None:
+ artifact["control_readonly"] = control_readonly
+ if control_disabled is not None:
+ artifact["control_disabled"] = control_disabled
+ if control_value_satisfied is not None:
+ artifact["control_value_satisfied"] = control_value_satisfied
if credential_id:
artifact["credential_id"] = credential_id
if credential_field:
@@ -455,8 +465,15 @@ def _fill_carry_to_interaction(carry: FillCarry, trajectory_index: int) -> Scout
interaction["accessible_name"] = carry.accessible_name
if carry.typed_length:
interaction["typed_length"] = carry.typed_length
- if carry.tool_name == "type_text" and carry.typed_value:
- interaction["typed_value"] = carry.typed_value
+ if carry.tool_name == "type_text":
+ if carry.typed_value:
+ interaction["typed_value"] = carry.typed_value
+ if carry.control_readonly is not None:
+ interaction["control_readonly"] = carry.control_readonly
+ if carry.control_disabled is not None:
+ interaction["control_disabled"] = carry.control_disabled
+ if carry.control_value_satisfied is not None:
+ interaction["control_value_satisfied"] = carry.control_value_satisfied
elif carry.tool_name == "select_option" and carry.value:
interaction["value"] = carry.value
elif carry.tool_name == "fill_credential_field":
diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.py
index a93b71576..0c929e2dd 100644
--- a/tests/unit/test_copilot_code_block_synthesis.py
+++ b/tests/unit/test_copilot_code_block_synthesis.py
@@ -18,7 +18,11 @@ from skyvern.forge.sdk.copilot.code_block_preflight import preflight_code_block
from skyvern.forge.sdk.copilot.code_block_security import author_time_code_security_errors
from skyvern.forge.sdk.copilot.code_block_synthesis import (
_DOWNLOAD_VAR_BASE,
+ _ENTRY_RESUME_AFTER_AUTH_VAR,
+ _ENTRY_REUSED_VAR,
+ _INDENT,
_MAX_STEPS,
+ _READONLY_DEFERRED_VAR,
_SYNTHESIZED_BLOCK_LABEL,
CREDENTIAL_FILL_TOOL_NAME,
_get_by_role_expr,
@@ -29,8 +33,14 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (
render_synthesized_offer_text,
synthesize_code_block,
)
+from skyvern.forge.sdk.copilot.context import (
+ FillCarry,
+ StructuredContext,
+ _fill_carry_from_scout_trajectory,
+)
from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget
from skyvern.forge.sdk.copilot.tools import _normalize_code_artifact_metadata
+from skyvern.forge.sdk.copilot.tools.scouting import _fill_carry_to_interaction
from skyvern.forge.sdk.copilot.tools.workflow_update import _code_block_safety_errors
from skyvern.forge.sdk.workflow.models.block import CodeBlock, CodeBlockStep
@@ -2258,3 +2268,307 @@ class TestDownloadRungSynthesis:
result = synthesize_code_block([_nav_click()])
assert result is not None
assert "expect_download" not in result.code
+
+
+def _readonly_type(**overrides: Any) -> dict[str, Any]:
+ base = _interaction(
+ "type_text",
+ selector="#electric-date",
+ source_url="https://example.com/service",
+ typed_length=10,
+ role="textbox",
+ accessible_name="Start date",
+ )
+ base.update(overrides)
+ return base
+
+
+def _deferred_conditional_snippet(code: str) -> str:
+ lines = code.splitlines()
+ start = next(i for i, ln in enumerate(lines) if f"if {_READONLY_DEFERRED_VAR} == " in ln)
+ return textwrap.dedent("\n".join(lines[start : start + 4]))
+
+
+def _guarded_deferred_snippet(code: str, guard_var: str) -> str:
+ lines = code.splitlines()
+ cond = [i for i, ln in enumerate(lines) if f"if {_READONLY_DEFERRED_VAR} == " in ln][-1]
+ guard = max(i for i in range(cond) if lines[i].strip() == f"if not {guard_var}:")
+ body = textwrap.dedent("\n".join(lines[cond : cond + 4]))
+ return lines[guard].strip() + "\n" + textwrap.indent(body, _INDENT)
+
+
+class TestReadonlyControlStateSynthesis:
+ def test_readonly_holding_value_emits_nonraising_verify_not_fill(self) -> None:
+ result = synthesize_code_block([_readonly_type(control_readonly=True, control_value_satisfied=True)])
+ assert result is not None
+ assert ".fill(str(start_date))" not in result.code
+ assert 'await page.locator("#electric-date").input_value()' in result.code
+ assert "!= str(start_date)" in result.code
+ assert "raise AssertionError" not in result.code
+ assert "print(" in result.code
+ assert result.parameters == [{"key": "start_date"}]
+ ast.parse("async def _block(page):\n" + result.code)
+
+ def test_disabled_holding_value_emits_verify_not_fill(self) -> None:
+ result = synthesize_code_block([_readonly_type(control_disabled=True, control_value_satisfied=True)])
+ assert result is not None
+ assert ".fill(str(" not in result.code
+ assert ".input_value()" in result.code
+
+ def test_readonly_needing_value_defers_assertion_after_later_picker(self) -> None:
+ trajectory = [
+ _readonly_type(control_readonly=True, control_value_satisfied=False),
+ _interaction(
+ "click",
+ selector="#date-picker-next",
+ source_url="https://example.com/service",
+ role="button",
+ accessible_name="Next",
+ ),
+ ]
+ result = synthesize_code_block(trajectory)
+ assert result is not None
+ code = result.code
+ assert ".fill(str(start_date))" not in code
+ assert "raise AssertionError" in code
+ assert code.index('await page.locator("#date-picker-next").click()') < code.index("raise AssertionError")
+ assert code.index(f"{_READONLY_DEFERRED_VAR} = await") > code.index(".click()")
+ ast.parse("async def _block(page):\n" + code)
+
+ def test_readonly_needing_value_still_asserts_without_actuator(self) -> None:
+ result = synthesize_code_block([_readonly_type(control_readonly=True, control_value_satisfied=False)])
+ assert result is not None
+ assert "raise AssertionError" in result.code
+ assert ".fill(str(" not in result.code
+ ast.parse("async def _block(page):\n" + result.code)
+
+ def test_post_auth_resume_header_always_carries_a_body(self) -> None:
+ # The resume-only entry header (elif entry_post_auth_resume_index) gets a guarding `pass` so that a
+ # pre-resume body reduced to deferring readonly actions never compiles to an empty block (SKY-12102).
+ trajectory = [
+ _interaction(
+ CREDENTIAL_FILL_TOOL_NAME,
+ selector="#user",
+ source_url="https://example.com/service",
+ credential_id="cred_1",
+ credential_name="mock_login",
+ credential_field="username",
+ ),
+ _interaction("click", selector="#signin", source_url="https://example.com/service"),
+ _readonly_type(control_readonly=True, control_value_satisfied=False),
+ _interaction("click", selector="#statement", source_url="https://example.com/service"),
+ ]
+ result = synthesize_code_block(trajectory)
+ assert result is not None
+ lines = result.code.splitlines()
+ header_index = lines.index(" if not _scout_entry_resume_after_auth:")
+ assert lines[header_index + 1] == f"{_INDENT * 2}pass"
+ ast.parse("async def _block(page):\n" + result.code)
+
+ def test_deferred_assertion_short_circuits_with_replayed_trajectory_on_reuse(self) -> None:
+ trajectory = [
+ _readonly_type(control_readonly=True, control_value_satisfied=False),
+ _interaction(
+ "click",
+ selector="#date-picker-next",
+ source_url="https://example.com/service",
+ role="button",
+ accessible_name="Next",
+ ),
+ ]
+ result = synthesize_code_block(trajectory, reached_download_target=_download_target())
+ assert result is not None
+ lines = result.code.splitlines()
+ guard = next(ln for ln in lines if ln.strip() == f"if not {_ENTRY_REUSED_VAR}:")
+ guard_indent = len(guard) - len(guard.lstrip())
+ read_idx = next(i for i, ln in enumerate(lines) if f"{_READONLY_DEFERRED_VAR} = await" in ln)
+ deferred_try = max(i for i in range(read_idx) if lines[i].strip() == "try:")
+ assert (len(lines[deferred_try]) - len(lines[deferred_try].lstrip())) > guard_indent
+ raise_line = next(ln for ln in lines if "raise AssertionError" in ln)
+ assert (len(raise_line) - len(raise_line.lstrip())) > guard_indent
+ ast.parse("async def _block(page):\n" + result.code)
+
+ def test_unknown_editability_falls_through_to_fill(self) -> None:
+ result = synthesize_code_block([_readonly_type()])
+ assert result is not None
+ assert 'await page.locator("#electric-date").fill(str(start_date))' in result.code
+ assert ".input_value()" not in result.code
+ assert "raise AssertionError" not in result.code
+
+ def test_editable_control_state_falls_through_to_fill(self) -> None:
+ result = synthesize_code_block([_readonly_type(control_readonly=False, control_disabled=False)])
+ assert result is not None
+ assert "fill(str(start_date))" in result.code
+ assert ".input_value()" not in result.code
+
+ def test_deferred_verify_var_is_cleaned_up_not_leaked_as_output(self) -> None:
+ result = synthesize_code_block([_readonly_type(control_readonly=True, control_value_satisfied=False)])
+ assert result is not None
+ assert f"del {_READONLY_DEFERRED_VAR}" in result.code
+
+ def test_readonly_verify_matches_fill_param_registration(self) -> None:
+ readonly = synthesize_code_block(
+ [_readonly_type(control_readonly=True, control_value_satisfied=True, typed_value="example-value")]
+ )
+ editable = synthesize_code_block([_readonly_type(typed_value="example-value")])
+ assert readonly is not None and editable is not None
+ assert readonly.parameters == editable.parameters
+
+ def test_deferred_empty_read_raises_honest_fail(self) -> None:
+ result = synthesize_code_block([_readonly_type(control_readonly=True, control_value_satisfied=False)])
+ assert result is not None
+ snippet = _deferred_conditional_snippet(result.code)
+ with pytest.raises(AssertionError):
+ exec(snippet, {"_scout_readonly_actual": "", "start_date": "06/22/2026"})
+
+ def test_deferred_reformatted_nonempty_read_prints_not_raises(self, capsys: pytest.CaptureFixture[str]) -> None:
+ result = synthesize_code_block([_readonly_type(control_readonly=True, control_value_satisfied=False)])
+ assert result is not None
+ snippet = _deferred_conditional_snippet(result.code)
+ exec(snippet, {"_scout_readonly_actual": "2026-06-22", "start_date": "06/22/2026"})
+ assert "does not match expected" in capsys.readouterr().out
+
+ def test_deferred_matching_nonempty_read_neither_raises_nor_prints(
+ self, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ result = synthesize_code_block([_readonly_type(control_readonly=True, control_value_satisfied=False)])
+ assert result is not None
+ snippet = _deferred_conditional_snippet(result.code)
+ exec(snippet, {"_scout_readonly_actual": "06/22/2026", "start_date": "06/22/2026"})
+ assert capsys.readouterr().out == ""
+
+ def test_deferred_unreadable_none_read_is_silent(self, capsys: pytest.CaptureFixture[str]) -> None:
+ result = synthesize_code_block([_readonly_type(control_readonly=True, control_value_satisfied=False)])
+ assert result is not None
+ snippet = _deferred_conditional_snippet(result.code)
+ exec(snippet, {"_scout_readonly_actual": None, "start_date": "06/22/2026"})
+ assert capsys.readouterr().out == ""
+
+ def test_resume_gating_partitions_pre_and_post_resume_deferred_assertions(self) -> None:
+ trajectory = [
+ _readonly_type(control_readonly=True, control_value_satisfied=False, selector="#account-id"),
+ _interaction(
+ CREDENTIAL_FILL_TOOL_NAME,
+ selector="#user",
+ source_url="https://example.com/login",
+ credential_id="cred_123",
+ credential_name="mock_portal_login",
+ credential_field="username",
+ ),
+ _interaction("click", selector="#signinBtn", source_url="https://example.com/login"),
+ _interaction("click", selector="#current-statement-row", source_url="https://example.com/bills"),
+ _readonly_type(
+ control_readonly=True,
+ control_value_satisfied=False,
+ selector="#post-field",
+ source_url="https://example.com/bills",
+ ),
+ ]
+ result = synthesize_code_block(trajectory)
+ assert result is not None
+ lines = result.code.splitlines()
+ pre_read = next(i for i, ln in enumerate(lines) if "#account-id" in ln and ".input_value()" in ln)
+ post_read = next(i for i, ln in enumerate(lines) if "#post-field" in ln and ".input_value()" in ln)
+ guard = next(
+ i
+ for i, ln in enumerate(lines)
+ if ln == f"{_INDENT}if not {_ENTRY_RESUME_AFTER_AUTH_VAR}:" and i > post_read
+ )
+ assert post_read < guard < pre_read
+ guard_indent = len(lines[guard]) - len(lines[guard].lstrip())
+ assert (len(lines[pre_read]) - len(lines[pre_read].lstrip())) > guard_indent
+ ast.parse("async def _block(page):\n" + result.code)
+
+ def test_resume_and_reuse_gates_short_circuit_deferred_assertion_at_runtime(
+ self, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ resume = synthesize_code_block(
+ [
+ _readonly_type(control_readonly=True, control_value_satisfied=False, selector="#account-id"),
+ _interaction(
+ CREDENTIAL_FILL_TOOL_NAME,
+ selector="#user",
+ source_url="https://example.com/login",
+ credential_id="cred_123",
+ credential_name="mock_portal_login",
+ credential_field="username",
+ ),
+ _interaction("click", selector="#signinBtn", source_url="https://example.com/login"),
+ _interaction("click", selector="#current-statement-row", source_url="https://example.com/bills"),
+ _readonly_type(
+ control_readonly=True,
+ control_value_satisfied=False,
+ selector="#post-field",
+ source_url="https://example.com/bills",
+ ),
+ ]
+ )
+ assert resume is not None
+ pre_resume = _guarded_deferred_snippet(resume.code, _ENTRY_RESUME_AFTER_AUTH_VAR)
+ post_resume = _deferred_conditional_snippet(resume.code)
+
+ exec(
+ pre_resume,
+ {_ENTRY_RESUME_AFTER_AUTH_VAR: True, _READONLY_DEFERRED_VAR: "2026-06-22", "start_date": "06/22/2026"},
+ )
+ assert capsys.readouterr().out == ""
+ with pytest.raises(AssertionError):
+ exec(pre_resume, {_ENTRY_RESUME_AFTER_AUTH_VAR: False, _READONLY_DEFERRED_VAR: ""})
+ with pytest.raises(AssertionError):
+ exec(post_resume, {_ENTRY_RESUME_AFTER_AUTH_VAR: True, _READONLY_DEFERRED_VAR: ""})
+
+ reuse = synthesize_code_block(
+ [
+ _readonly_type(control_readonly=True, control_value_satisfied=False),
+ _interaction(
+ "click",
+ selector="#date-picker-next",
+ source_url="https://example.com/service",
+ role="button",
+ accessible_name="Next",
+ ),
+ ],
+ reached_download_target=_download_target(),
+ )
+ assert reuse is not None
+ reuse_gated = _guarded_deferred_snippet(reuse.code, _ENTRY_REUSED_VAR)
+ exec(reuse_gated, {_ENTRY_REUSED_VAR: True, _READONLY_DEFERRED_VAR: "2026-06-22", "start_date": "06/22/2026"})
+ assert capsys.readouterr().out == ""
+ with pytest.raises(AssertionError):
+ exec(reuse_gated, {_ENTRY_REUSED_VAR: False, _READONLY_DEFERRED_VAR: ""})
+
+
+class TestReadonlyControlStateCarry:
+ def test_fill_carry_roundtrip_preserves_control_state_for_type_text(self) -> None:
+ interaction = _readonly_type(control_readonly=True, control_value_satisfied=True)
+ carry = _fill_carry_from_scout_trajectory([interaction])
+ assert len(carry) == 1
+ assert carry[0].control_readonly is True
+ assert carry[0].control_value_satisfied is True
+ rebound = _fill_carry_to_interaction(carry[0], trajectory_index=0)
+ assert rebound["control_readonly"] is True
+ assert rebound["control_value_satisfied"] is True
+ result = synthesize_code_block([rebound])
+ assert result is not None
+ assert ".fill(str(" not in result.code
+ assert ".input_value()" in result.code
+
+ def test_credential_carry_persists_no_control_state_keys(self) -> None:
+ credential_carry = FillCarry(
+ source_url="https://example.com/login",
+ selector="#password",
+ tool_name="fill_credential_field",
+ credential_id="cred_example",
+ credential_field="password",
+ )
+ persisted = StructuredContext(fill_carry=[credential_carry]).to_json_str()
+ assert "control_readonly" not in persisted
+ assert "control_disabled" not in persisted
+ assert "control_value_satisfied" not in persisted
+
+ def test_type_text_carry_persists_control_value_satisfied_bool(self) -> None:
+ interaction = _readonly_type(control_readonly=True, control_value_satisfied=False)
+ carry = _fill_carry_from_scout_trajectory([interaction])
+ persisted = StructuredContext(fill_carry=carry).to_json_str()
+ assert '"control_readonly": true' in persisted
+ assert '"control_value_satisfied": false' in persisted
diff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.py
index ff6a93c01..6f063d4d3 100644
--- a/tests/unit/test_copilot_scout_act_observe.py
+++ b/tests/unit/test_copilot_scout_act_observe.py
@@ -815,11 +815,36 @@ class TestActObserveToolGate:
ctx,
)
- server.call_internal_tool.assert_not_awaited()
+ awaited_tools = [call.args[0] for call in server.call_internal_tool.await_args_list]
+ assert awaited_tools == ["skyvern_get_value"]
assert result["ok"] is True
assert "page" not in result["data"]
assert ctx.flow_evidence[0]["had_bounded_schema"] is False
+ @pytest.mark.asyncio
+ async def test_bare_css_selector_probes_control_state(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.forge.sdk.copilot import tools as tools_module
+
+ async def passes(*_args: object, **_kwargs: object) -> None:
+ return None
+
+ monkeypatch.setattr(tools_module.mcp_hooks, "_verify_scout_type_landed", passes)
+ server = _server_returning(_bounded_extractor_payload())
+ ctx = _ctx(server=server, source_url=_SOURCE_URL)
+
+ await tools_module._type_text_post_hook(
+ {"ok": True, "data": {"selector": "#electricDate", "text_length": 10}},
+ {"browser_context": {"url": _LANDING_URL, "title": "Results"}},
+ ctx,
+ )
+
+ probed = [
+ call
+ for call in server.call_internal_tool.await_args_list
+ if call.args and call.args[0] == "skyvern_evaluate" and "readonly" in call.args[1]["expression"]
+ ]
+ assert len(probed) == 1
+
def _np_ctx(*, server: Any = None, counter: int = 0) -> SimpleNamespace:
ctx = _ctx(server=server)