Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Let Copilot read large pages after a saved-login run, and say when a result is withheld (SKY-17346) (#8742)
Andrew Neilson539dc5d14e86
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowRunTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowRunTypes.tsindex 6b117859b..eb3832039 100644--- a/skyvern-frontend/src/routes/workflows/types/workflowRunTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/workflowRunTypes.ts@@ -283,7 +283,8 @@ export type BranchEvaluation = {branch_index: number;criteria_type: "jinja2_template" | "prompt" | null;original_expression: string | null;- rendered_expression: string | null;+ // The backend drops this key on every branch that did not match.+ rendered_expression?: string | null;result: boolean | null;is_matched: boolean;is_default: boolean;@@ -294,6 +295,7 @@ export type BranchEvaluation = {export type ConditionalBlockOutput = {evaluations?: Array<BranchEvaluation>;matched_branch_index?: number | null;+ evaluation_error?: string | null;};export function hasEvaluations(diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsxindex df7364439..109b9040a 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx@@ -317,6 +317,72 @@ describe("WorkflowRunTimelineBlockItem", () => {expect(screen.queryByText("0 actions")).toBeNull();});+ it("flags a completed conditional that routed on an evaluation error, and only that one", () => {+ const error =+ "Workflow branch evaluation context is too large to process safely. Reduce the workflow input or prior block output size, then retry.";+ const promptBranch = {+ branch_id: "b_prompt",+ branch_index: 0,+ criteria_type: "prompt",+ original_expression: "user selected premium plan",+ result: false,+ is_matched: false,+ is_default: false,+ next_block_label: "premium",+ error: null,+ };+ const defaultBranch = {+ branch_id: "b_default",+ branch_index: 1,+ criteria_type: null,+ original_expression: null,+ rendered_expression: null,+ result: null,+ is_matched: true,+ is_default: true,+ next_block_label: "fallback_block",+ error: null,+ };+ const evaluated = buildBlock({+ workflow_run_block_id: "wrb_cond",+ block_type: "conditional",+ label: "check_plan",+ status: Status.Completed,+ executed_branch_id: "b_default",+ executed_branch_next_block: "fallback_block",+ output: {+ branch_taken: "fallback_block",+ evaluations: [promptBranch, defaultBranch],+ },+ });+ const errored = buildBlock({+ ...evaluated,+ output: {+ branch_taken: "fallback_block",+ evaluations: [{ ...promptBranch, result: null, error }, defaultBranch],+ evaluation_error: error,+ },+ });+ const renderRow = (block: WorkflowRunBlock) => (+ <WorkflowRunTimelineBlockItem+ activeItem={null}+ block={block}+ subItems={[]}+ onActionClick={noop}+ onBlockItemClick={noop}+ />+ );++ const { rerender } = render(renderRow(evaluated));+ expect(screen.queryByText("evaluation error")).toBeNull();++ rerender(renderRow(errored));+ const flag = screen.getByText("evaluation error");+ expect(flag.getAttribute("title")).toContain(error);+ // The block still reports completed; the flag sits beside that status.+ expect(screen.getByRole("img", { name: "completed" })).toBeDefined();+ });+it("renders action rows under a code block and lets the user select an action", () => {const onActionClick = vi.fn();const block = buildBlock({diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsxindex 2912e9b71..3c9f975c2 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx@@ -51,6 +51,7 @@ import {import { ThoughtCard } from "./ThoughtCard";import {aggregateIterationStatus,+ getConditionalEvaluationError,type SkippedBranchMetadata,type UnexecutedDefinedBlock,} from "./workflowTimelineUtils";@@ -1118,6 +1119,7 @@ function WorkflowRunTimelineBlockItem({const blockName = block.label ?? blockTypeTitle;const descriptor = getTimelineDescriptor(block);const resultSummary = getWebSearchResultSummary(block);+ const evaluationError = getConditionalEvaluationError(block);const showsActionRows = hasActions;// Code blocks without recorded actions fall back to their definition step// outline so the timeline still reflects what the block was meant to do.@@ -1364,6 +1366,14 @@ function WorkflowRunTimelineBlockItem({{TIMELINE_DESCRIPTOR_SEPARATOR} {resultSummary}</span>)}+ {evaluationError && (+ <span+ className="shrink-0 rounded bg-warning/15 px-1 text-[10px] text-warning"+ title={`${evaluationError.summary}\n${evaluationError.message}`}+ >+ evaluation error+ </span>+ )}{isFinallyBlock && (<span className="shrink-0 rounded bg-amber-500/80 px-1 text-[9px] font-medium text-black">finallydiff --git a/skyvern-frontend/src/routes/workflows/workflowRun/blockDetail/BlockDetailConditional.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/blockDetail/BlockDetailConditional.test.tsxindex dd19fc3fc..6f8d6bc6f 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/blockDetail/BlockDetailConditional.test.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/blockDetail/BlockDetailConditional.test.tsx@@ -5,11 +5,14 @@ vi.mock("@/hooks/useCredentialGetter", () => ({useCredentialGetter: () => null,}));-import { cleanup, render, screen } from "@testing-library/react";+import { cleanup, render, screen, within } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { Status } from "@/api/types";-import type { WorkflowRunBlock } from "../../types/workflowRunTypes";+import type {+ BranchEvaluation,+ WorkflowRunBlock,+} from "../../types/workflowRunTypes";import { BlockDetailConditional } from "./BlockDetailConditional";function buildConditional(@@ -48,6 +51,22 @@ function buildConditional(};}+function evaluation(+ overrides: Partial<BranchEvaluation> & { branch_id: string },+): BranchEvaluation {+ return {+ branch_index: 0,+ criteria_type: "jinja2_template",+ original_expression: null,+ result: null,+ is_matched: false,+ is_default: false,+ next_block_label: null,+ error: null,+ ...overrides,+ };+}+afterEach(() => {cleanup();});@@ -148,15 +167,22 @@ describe("BlockDetailConditional", () => {});it("falls back to the legacy executed_branch_expression rendering when no evaluations array", () => {+ // The shape a conditional evaluated from cached code writes.const block = buildConditional({executed_branch_id: "b_match",executed_branch_expression: "{{ x == 1 }}",executed_branch_result: true,+ output: {+ branch_taken: "next",+ branch_index: 0,+ next_block_label: "next",+ },});render(<BlockDetailConditional block={block} />);- expect(screen.getByText(/evaluation/i)).toBeDefined();+ expect(screen.getByText(/^evaluation$/i)).toBeDefined();expect(screen.getByText("{{ x == 1 }}")).toBeDefined();+ expect(screen.queryByText(/could not be evaluated/i)).toBeNull();});it("renders valid JSON rendered branch values with the JSON explorer", () => {@@ -201,6 +227,179 @@ describe("BlockDetailConditional", () => {expect(screen.getByText(/no conditions matched/i)).toBeDefined();});+ it("says a condition could not be evaluated and the default branch was taken, though the block completed", () => {+ const error =+ "Failed to evaluate natural language branches: Branch evaluation failed: LLM exploded";+ const block = buildConditional({+ status: Status.Completed,+ executed_branch_id: "b_default",+ executed_branch_next_block: "fallback_block",+ output: {+ branch_taken: "fallback_block",+ evaluations: [+ evaluation({+ branch_id: "b_prompt",+ criteria_type: "prompt",+ original_expression: "user selected premium plan",+ next_block_label: "premium",+ error,+ }),+ evaluation({+ branch_id: "b_default",+ is_default: true,+ is_matched: true,+ criteria_type: null,+ next_block_label: "fallback_block",+ }),+ ],+ evaluation_error: error,+ },+ });++ render(<BlockDetailConditional block={block} />);++ const notice = screen.getByText(/could not be evaluated/i);+ expect(notice.textContent).toMatch(/default branch/i);+ // The reason is stated once: the branch does not repeat what the notice says.+ expect(screen.getAllByText(error)).toHaveLength(1);+ const erroredRow = screen+ .getByText("user selected premium plan")+ .closest("li")!;+ expect(within(erroredRow).getByText("error")).toBeDefined();+ expect(screen.getByText("fallback_block")).toBeDefined();+ });++ it("marks an errored branch differently from one that evaluated false, and shows an error the notice does not state", () => {+ const promptError =+ "Failed to evaluate natural language branches: Branch evaluation failed: LLM exploded";+ const jinjaError =+ "Failed to format Jinja style parameter '{{ total > }}'. Reason: unexpected 'end of print statement'. <img src=x onerror=alert(1)>";+ const block = buildConditional({+ executed_branch_id: "b_default",+ executed_branch_next_block: "fallback_block",+ output: {+ evaluations: [+ evaluation({+ branch_id: "b_false",+ original_expression: "{{ total > 100 }}",+ result: false,+ next_block_label: "big_order",+ }),+ evaluation({+ branch_id: "b_prompt",+ criteria_type: "prompt",+ original_expression: "the page shows an invoice",+ next_block_label: "invoice",+ error: promptError,+ }),+ evaluation({+ branch_id: "b_jinja_error",+ original_expression: "{{ total > }}",+ next_block_label: "other",+ error: jinjaError,+ }),+ evaluation({+ branch_id: "b_default",+ is_default: true,+ is_matched: true,+ criteria_type: null,+ next_block_label: "fallback_block",+ }),+ ],+ evaluation_error: promptError,+ },+ });++ const { container } = render(<BlockDetailConditional block={block} />);++ const falseRow = screen.getByText("{{ total > 100 }}").closest("li")!;+ expect(within(falseRow).getByText("false")).toBeDefined();+ expect(within(falseRow).queryByText("error")).toBeNull();++ const jinjaRow = screen.getByText("{{ total > }}").closest("li")!;+ expect(within(jinjaRow).getByText("error")).toBeDefined();+ expect(within(jinjaRow).queryByText("false")).toBeNull();+ // Rendered as text: the markup in the message stays a string.+ expect(within(jinjaRow).getByText(jinjaError)).toBeDefined();+ expect(container.querySelector("img")).toBeNull();++ const promptRow = screen+ .getByText("the page shows an invoice")+ .closest("li")!;+ expect(within(promptRow).getByText("error")).toBeDefined();+ expect(screen.getAllByText(promptError)).toHaveLength(1);+ });++ it("does not claim the default branch was taken when a later branch matched after the error", () => {+ const branchError =+ "Failed to format Jinja style parameter '{{ total > }}'. Reason: unexpected 'end of print statement'.";+ const block = buildConditional({+ executed_branch_id: "b_true",+ executed_branch_expression: "{{ total > 10 }}",+ executed_branch_result: true,+ executed_branch_next_block: "big_order",+ output: {+ evaluations: [+ evaluation({+ branch_id: "b_error",+ original_expression: "{{ total > }}",+ next_block_label: "invoice",+ error: branchError,+ }),+ evaluation({+ branch_id: "b_true",+ original_expression: "{{ total > 10 }}",+ rendered_expression: "12 > 10",+ result: true,+ is_matched: true,+ next_block_label: "big_order",+ }),+ ],+ evaluation_error: `Failed to evaluate branch 0 for route_document: ${branchError}`,+ },+ });++ render(<BlockDetailConditional block={block} />);++ const notice = screen.getByText(/could not be evaluated/i);+ expect(notice.textContent).not.toMatch(/default branch/i);+ expect(+ screen.getByText(+ `Failed to evaluate branch 0 for route_document: ${branchError}`,+ ),+ ).toBeDefined();+ });++ it("renders no evaluation-error notice or error marker when the output carries no error", () => {+ const block = buildConditional({+ executed_branch_id: "b_true",+ output: {+ evaluations: [+ evaluation({+ branch_id: "b_true",+ original_expression: "{{ count > 3 }}",+ rendered_expression: "5 > 3",+ result: true,+ is_matched: true,+ next_block_label: "notify_team",+ }),+ evaluation({+ branch_id: "b_default",+ is_default: true,+ criteria_type: null,+ next_block_label: "fallback",+ }),+ ],+ },+ });++ render(<BlockDetailConditional block={block} />);++ expect(screen.getByText("notify_team")).toBeDefined();+ expect(screen.queryByText(/could not be evaluated/i)).toBeNull();+ expect(screen.queryByText("error")).toBeNull();+ });+it("renders no evaluation/branches section before the conditional has resolved a branch", () => {const block = buildConditional({status: Status.Running,diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/blockDetail/BlockDetailConditional.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/blockDetail/BlockDetailConditional.tsxindex e3b60d00f..b0c9b0167 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/blockDetail/BlockDetailConditional.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/blockDetail/BlockDetailConditional.tsx@@ -1,3 +1,5 @@+import { ExclamationTriangleIcon } from "@radix-ui/react-icons";+import { cn } from "@/util/utils";import {@@ -5,6 +7,10 @@ import {hasEvaluations,type WorkflowRunBlock,} from "../../types/workflowRunTypes";+import {+ type ConditionalEvaluationError,+ getConditionalEvaluationError,+} from "../workflowTimelineUtils";import { JsonExplorer } from "./BlockInspector";import { Section } from "./shared";@@ -26,8 +32,9 @@ function tryParseJson(value: string): unknown | null {* One branch as a keyword-led rule line: `if` / `else if` / `else` in a muted* gutter carries the order, the condition follows in regular type (mono only* for a template expression), and the outcome sits at the end — `false` for a- * condition that did not hold, the destination for the branch that ran. The- * branch that ran is the one emphasized row; no glyph, no tint.+ * condition that did not hold, `error` for one that could not be evaluated,+ * the destination for the branch that ran. The branch that ran is the one+ * emphasized row; no glyph, no tint.*/function BranchRow({keyword,@@ -45,7 +52,8 @@ function BranchRow({mono?: boolean;outcome?:| { kind: "next"; label: string }- | { kind: "result"; value: boolean };+ | { kind: "result"; value: boolean }+ | { kind: "error" };children?: React.ReactNode;}) {return (@@ -82,6 +90,8 @@ function BranchRow({<span className="shrink-0 font-mono text-muted-foreground/70">{outcome.value ? "true" : "false"}</span>+ ) : outcome?.kind === "error" ? (+ <span className="shrink-0 font-mono text-warning">error</span>) : null}</div>{children ? <div className="pl-[3.25rem]">{children}</div> : null}@@ -97,18 +107,24 @@ function keywordFor(index: number, isDefault: boolean): string {function EvaluationRow({evaluation,index,+ statedError,}: {evaluation: BranchEvaluation;index: number;+ // The message the notice above the list already shows in full.+ statedError: string | null;}) {const keyword = keywordFor(index, evaluation.is_default);+ const error = evaluation.error || null;const outcome = evaluation.is_matched? evaluation.next_block_label? ({ kind: "next", label: evaluation.next_block_label } as const): undefined- : evaluation.result === null- ? undefined- : ({ kind: "result", value: evaluation.result } as const);+ : error+ ? ({ kind: "error" } as const)+ : evaluation.result === null+ ? undefined+ : ({ kind: "result", value: evaluation.result } as const);if (evaluation.is_default) {return (<BranchRow@@ -150,7 +166,36 @@ function EvaluationRow({template={rendered ? original : null}mono={mono}outcome={outcome}- />+ >+ {error && !statedError?.includes(error) ? (+ <p className="whitespace-pre-wrap break-words text-xs text-muted-foreground">+ {error}+ </p>+ ) : null}+ </BranchRow>+ );+}++// Amber, not the red failure box: the block completed, and the status owns red.+function EvaluationErrorNotice({+ summary,+ message,+}: ConditionalEvaluationError) {+ return (+ <div className="space-y-1.5 duration-200 animate-in fade-in slide-in-from-top-2">+ <div className="text-[11px] font-medium uppercase tracking-wide text-warning">+ Evaluation error+ </div>+ <div className="flex items-start gap-2.5 rounded-md border border-warning/40 bg-warning/5 p-3 text-xs leading-relaxed text-foreground dark:bg-warning/10">+ <ExclamationTriangleIcon className="mt-0.5 h-4 w-4 shrink-0 text-warning" />+ <div className="min-w-0 flex-1 space-y-1">+ <p>{summary}</p>+ <p className="whitespace-pre-wrap break-words text-muted-foreground">+ {message}+ </p>+ </div>+ </div>+ </div>);}@@ -163,9 +208,11 @@ function BlockDetailConditional({ block }: Props) {// resolved a branch. Before that (Created/Queued/Running), claiming a// result — especially the "executed default branch" fallback — is wrong.const hasExecutedBranch = Boolean(block.executed_branch_id);+ const evaluationError = getConditionalEvaluationError(block);return (<div className="space-y-4 px-3 py-3 empty:hidden">+ {evaluationError ? <EvaluationErrorNotice {...evaluationError} /> : null}{hasExecutedBranch && evaluations && evaluations.length > 0 ? (<Section title="Branches"><ul className="divide-y divide-border/50">@@ -174,6 +221,7 @@ function BlockDetailConditional({ block }: Props) {key={evaluation.branch_id || index}evaluation={evaluation}index={index}+ statedError={evaluationError?.message ?? null}/>))}</ul>diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts b/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.tsindex 169d4bcb7..e93cdb966 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts+++ b/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts@@ -311,7 +311,7 @@ const DENIAL_TEMPLATES: Record<string, CodeBlockFailureTemplate> = {kind: "limit",title: "The block held too many browser objects",guidance:- "This block used more live browser objects in a single run than the per-run limit allows. Every query_selector or element_handle result, .all() on a filtered, get_by_* or frame-rooted locator, and each locator passed as an argument holds one object for the rest of the run. Read rows through page.locator(...), .nth() and .all() chains instead, which hold none, or split the work across several runs.",+ "This block used more live browser objects in a single run than the per-run limit allows. Every query_selector or element_handle result, .all() on a filtered, get_by_* or frame-rooted locator, and each locator passed as an argument holds one object until it is released with dispose() or the run ends. Read rows through page.locator(...), .nth() and .all() chains instead, which hold none, release each temporary object with dispose() in a finally block, or split the work across several runs.",recovery: "fix",},"codeblock.page_operation_broker.BlockedEgressError": {diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.ts b/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.tsindex ecb80065c..e95564baf 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.ts+++ b/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.ts@@ -140,6 +140,34 @@ type BranchOutcome = {notTakenTargets: Array<SkippedBranchMetadata>;};+type ConditionalEvaluationError = {+ summary: string;+ message: string;+};++// The block still reports completed when this is set: the backend routed+// despite a branch it could not evaluate. Absent on cached-code and older runs.+function getConditionalEvaluationError(+ block: WorkflowRunBlock,+): ConditionalEvaluationError | null {+ if (block.block_type !== "conditional" || !hasEvaluations(block.output)) {+ return null;+ }+ const { evaluation_error: message, evaluations = [] } = block.output;+ if (!message) {+ return null;+ }+ const tookDefaultBranch = evaluations.some(+ (evaluation) => evaluation.is_matched && evaluation.is_default,+ );+ return {+ summary: tookDefaultBranch+ ? "A condition could not be evaluated, so the default branch was taken."+ : "A condition could not be evaluated. The branch that ran was chosen without it.",+ message,+ };+}+function collectExecutedConditionals(timelineItems: Array<WorkflowRunTimelineItem>,): Array<WorkflowRunBlock> {@@ -855,10 +883,12 @@ export {findThoughtsForBlock,findTimelineBlock,flattenTimelineChronologically,+ getConditionalEvaluationError,parseActiveIterationParam,resolveScreenshotBlockId,};export type {+ ConditionalEvaluationError,SkippedBranchMetadata,UnexecutedBlockReason,UnexecutedDefinedBlock,diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 986fb1c6e..5e9710461 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -1279,7 +1279,14 @@ class AgentFunction:under them; OSS has no runner, so its budget is unknown rather than unlimited."""return None- def redact_codeblock_parameter_values(self, value: Any, parameters: dict[str, Any]) -> Any:+ def redact_codeblock_parameter_values(+ self,+ value: Any,+ parameters: dict[str, Any],+ *,+ max_disclosure_chars: int | None = None,+ max_disclosure_nodes: int | None = None,+ ) -> Any:"""Cloud overrides this with the runner's canonical parameter scrubber."""return valuediff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.pyindex 101451cb8..278eaf383 100644--- a/skyvern/forge/sdk/copilot/mcp_adapter.py+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py@@ -32,6 +32,7 @@ from playwright.async_api import Browser, BrowserContextfrom skyvern.cli.core.client import reset_api_key_override, set_api_key_overridefrom skyvern.cli.core.session_manager import request_session_scope+from skyvern.cli.mcp_tools.response import MCP_MAX_RESPONSE_CHARSfrom skyvern.forge import appfrom skyvern.forge.agent_functions import CopilotCandidateNetworkHopfrom skyvern.forge.sdk.copilot.blocker_signal import (@@ -159,7 +160,11 @@ class _BrowserCallOutcome:return deepcopy(self._raw_result_payload)def with_raw_result(self, raw_result: dict[str, Any]) -> _BrowserCallOutcome:- return replace(self, _raw_result_payload=_copy_browser_result(raw_result))+ outcome = replace(self, _raw_result_payload=_copy_browser_result(raw_result))+ return outcome.as_redaction_withheld() if is_redaction_withheld(raw_result) else outcome++ def as_redaction_withheld(self) -> _BrowserCallOutcome:+ return replace(self, ok=False, payload_omitted=True, error_kind=self.error_kind or "tool")@dataclass(frozen=True)@@ -748,6 +753,62 @@ def _mapping_at(value: Any, path: tuple[str, ...]) -> dict[str, Any] | None:return value if isinstance(value, dict) else None+_REDACTION_WITHHELD_KEY = "redaction_withheld"+_RedactionWithheldReason = Literal["redaction_budget", "redaction_unavailable"]+++def is_redaction_withheld(result: object) -> bool:+ data = result.get("data") if isinstance(result, dict) else None+ return isinstance(data, dict) and isinstance(data.get(_REDACTION_WITHHELD_KEY), dict)+++def _original_chars(result: Any) -> int | None:+ if is_redaction_withheld(result):+ inherited = result["data"][_REDACTION_WITHHELD_KEY].get("original_chars")+ return inherited if type(inherited) is int else None+ try:+ return len(json.dumps(result, default=str, ensure_ascii=False))+ except (TypeError, ValueError, RecursionError):+ return None+++def _redaction_withheld_result(+ ctx: AgentContext, result: Any, *, tool_name: str | None, failure: _RedactionWithheldReason+) -> dict[str, Any]:+ original_chars = _original_chars(result)+ rewithheld = is_redaction_withheld(result)+ if rewithheld:+ inherited_budget = result["data"][_REDACTION_WITHHELD_KEY].get("reason") == "redaction_budget"+ failure = "redaction_budget" if inherited_budget else "redaction_unavailable"+ # An inherited size can be missing because it was dropped as a registered value, not because it was small.+ over_budget = original_chars > MCP_MAX_RESPONSE_CHARS if original_chars is not None else rewithheld+ reason: _RedactionWithheldReason = (+ "redaction_budget" if failure == "redaction_budget" and over_budget else "redaction_unavailable"+ )+ # A size equal to a registered value would disclose it, so the size is only reported when it scrubs to itself.+ if original_chars is not None:+ probe = {"original_chars": original_chars, "text": str(original_chars)}+ if _scrub_model_facing_tool_result(ctx, probe) != probe:+ original_chars = None+ if not rewithheld:+ LOG.warning(+ "copilot_model_facing_result_withheld",+ tool_name=tool_name,+ reason=reason,+ original_chars=original_chars,+ active_parameter_sets=len(_active_parameter_sets(ctx)),+ )+ withheld: dict[str, Any] = {"reason": reason}+ if original_chars is not None:+ withheld["original_chars"] = original_chars+ if reason == "redaction_budget":+ size = f" ({original_chars} characters)" if original_chars is not None else ""+ error = f"Result withheld, too large to redact{size}."+ else:+ error = "Result withheld: it could not be redacted safely."+ return {"ok": False, "error": error, "data": {_REDACTION_WITHHELD_KEY: withheld}}++def scrub_model_facing_tool_result(ctx: AgentContext, result: Any, *, tool_name: str | None = None) -> dict[str, Any]:driver_codes = {path: code@@ -756,9 +817,8 @@ def scrub_model_facing_tool_result(ctx: AgentContext, result: Any, *, tool_name:is not None}scrubbed = _scrub_model_facing_tool_result(ctx, result)- # An empty result is the fail-closed answer; writing a code into it would read as a successful call.- if not scrubbed:- return scrubbed+ if not isinstance(scrubbed, dict):+ return _redaction_withheld_result(ctx, result, tool_name=tool_name, failure=scrubbed)for path, code in driver_codes.items():parent = _mapping_at(scrubbed, path)if parent is not None:@@ -766,15 +826,27 @@ def scrub_model_facing_tool_result(ctx: AgentContext, result: Any, *, tool_name:return scrubbed-def _scrub_model_facing_tool_result(ctx: AgentContext, result: Any) -> dict[str, Any]:+def _scrub_model_facing_tool_result(ctx: AgentContext, result: Any) -> dict[str, Any] | _RedactionWithheldReason:scrubbed_secrets = scrub_secrets_from_structure(ctx, result)if not isinstance(scrubbed_secrets, dict) or not _mapping_keys_preserved(result, scrubbed_secrets):- return {}+ return "redaction_unavailable"scrubbed = scrubbed_secretsfor parameter_set in _active_parameter_sets(ctx):- candidate = app.AGENT_FUNCTION.redact_codeblock_parameter_values(scrubbed, parameter_set)- if not isinstance(candidate, dict) or not _mapping_keys_preserved(scrubbed, candidate):- return {}+ candidate = app.AGENT_FUNCTION.redact_codeblock_parameter_values(+ scrubbed,+ parameter_set,+ max_disclosure_chars=MCP_MAX_RESPONSE_CHARS,+ max_disclosure_nodes=MCP_MAX_RESPONSE_CHARS,+ )+ if not isinstance(candidate, dict):+ # The redactor returns the same non-dict for a blown budget and for a parameter set it refuses,+ # so ask it about an empty input to tell the two apart.+ refuses_parameters = not isinstance(+ app.AGENT_FUNCTION.redact_codeblock_parameter_values({}, parameter_set), dict+ )+ return "redaction_unavailable" if refuses_parameters else "redaction_budget"+ if not _mapping_keys_preserved(scrubbed, candidate):+ return "redaction_unavailable"if type(scrubbed.get("ok")) is bool:candidate["ok"] = scrubbed["ok"]scrubbed = candidate@@ -1995,6 +2067,8 @@ class SkyvernOverlayMCPServer(MCPServer):if isinstance(copilot_result, dict):await _stamp_page_state(copilot_result)copilot_result = scrub_model_facing_tool_result(copilot_ctx, copilot_result, tool_name=mcp_name)+ if browser_outcome is not None and is_redaction_withheld(copilot_result):+ browser_outcome = browser_outcome.as_redaction_withheld()def _commit_evidence() -> None:if browser_outcome is not None:diff --git a/skyvern/forge/sdk/copilot/tools/_shared.py b/skyvern/forge/sdk/copilot/tools/_shared.pyindex c465c2e73..9e3d280ef 100644--- a/skyvern/forge/sdk/copilot/tools/_shared.py+++ b/skyvern/forge/sdk/copilot/tools/_shared.py@@ -40,7 +40,11 @@ from skyvern.forge.sdk.copilot.enforcement import (_requested_output_labels_by_path,proxy_hop_failure_reason,)-from skyvern.forge.sdk.copilot.mcp_adapter import _browser_session_error_disposition, _browser_session_loss_result+from skyvern.forge.sdk.copilot.mcp_adapter import (+ _browser_session_error_disposition,+ _browser_session_loss_result,+ is_redaction_withheld,+)from skyvern.forge.sdk.copilot.nav_attribution import proxy_owns_nav_codesfrom skyvern.forge.sdk.copilot.runtime import (SENSITIVE_ORIGIN_ACTIVE_RUN_PAGE_ERROR,@@ -1000,6 +1004,8 @@ async def _composition_get_structured_evidence_result(f"and {type(exc).__name__} carried no message")if outcome is not None and outcome.payload_omitted:+ if is_redaction_withheld(result):+ return None, f"structured page evidence was withheld: {result.get('error')}"return None, "structured page evidence was omitted at the MCP boundary"if not result.get("ok"):LOG.warning(diff --git a/skyvern/forge/sdk/copilot/tools/browser_code.py b/skyvern/forge/sdk/copilot/tools/browser_code.pyindex 9a9be1991..5858ac983 100644--- a/skyvern/forge/sdk/copilot/tools/browser_code.py+++ b/skyvern/forge/sdk/copilot/tools/browser_code.py@@ -43,6 +43,7 @@ from skyvern.forge.sdk.copilot.mcp_adapter import (_browser_session_loss_result,_prepare_browser_session_for_dispatch,_record_browser_call_outcome,+ is_redaction_withheld,scrub_model_facing_tool_result,)from skyvern.forge.sdk.copilot.runtime import (@@ -531,7 +532,7 @@ async def run_browser_code(else result)scrubbed = scrub_model_facing_tool_result(copilot_ctx, result_to_scrub)- if retained_reference is not None and scrubbed:+ if retained_reference is not None and scrubbed and not is_redaction_withheld(scrubbed):# This server-generated capability is not derived from credential data. Scrubbing a coincidental# secret substring would corrupt the lookup key and make exact-source promotion impossible.scrubbed["executed_source_reference"] = retained_referencediff --git a/skyvern/forge/sdk/copilot/tools/composition_capture.py b/skyvern/forge/sdk/copilot/tools/composition_capture.pyindex 14deab6f8..d716f8363 100644--- a/skyvern/forge/sdk/copilot/tools/composition_capture.py+++ b/skyvern/forge/sdk/copilot/tools/composition_capture.py@@ -107,6 +107,7 @@ from .mcp_hooks import _bind_login_credential_for_observed_url, _record_scouted_from .scouting import (_clear_pending_browser_interaction_observation,_consume_pending_browser_interaction_observation,+ _evidence_list_len,_mark_post_run_page_observed,)@@ -1097,6 +1098,7 @@ def store_post_run_page_evidence(run_browser_session_id=run_browser_session_id,matched=source_browser_session_id == run_browser_session_id,granted=stamped.get("observed_after_workflow_run") is True,+ key_value_relation_count=_evidence_list_len(stamped, "key_value_relations"),)if current_url and not stamped.get("current_url"):stamped["current_url"] = current_urldiff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex be1f259ab..8c9ba0368 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -2444,15 +2444,26 @@ async def _fetch_dispatched_terminal_page_evidence(return Noneif artifact_bytes.startswith(_ZIP_MAGIC_PREFIXES):return None+ # Cut before redaction: a registered value whose first 1-7 characters land on the cut is not caught, because+ # the redactor only recognises a dangling prefix of 8 or more characters.raw_html = artifact_bytes.decode("utf-8", errors="ignore")[:_MAX_POST_RUN_PAGE_HTML_CHARS]scrubbed_html = (app.AGENT_FUNCTION.redact_codeblock_parameter_values(- raw_html, _mutable_redaction_value(artifact_redaction_parameters)+ raw_html,+ _mutable_redaction_value(artifact_redaction_parameters),+ max_disclosure_chars=_MAX_POST_RUN_PAGE_HTML_CHARS,)if artifact_redaction_parameterselse raw_html)if not isinstance(scrubbed_html, str) or not scrubbed_html:+ # The HTML is cut to the budget before redaction, so a refusal here is never about size. The size is not+ # logged because the refused parameters cannot vouch that it differs from a registered value.+ LOG.warning(+ "copilot_model_facing_result_withheld",+ tool_name="post_run_page_html",+ reason="redaction_unavailable",+ )return Nonetry:evidence = await asyncio.wait_for(diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 7d2cad764..d5a9cdfef 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -345,6 +345,7 @@ from skyvern.services.webhook_delivery import (from skyvern.services.workflow_script_service import ( # noqa: F401 -- re-exported; several tests import it from this moduleBLOCK_TYPES_THAT_SHOULD_BE_CACHED,create_script_version_from_review,+ engine_only_loop_child_types,is_block_type_cacheable,)from skyvern.utils.contained_effects import contained_effect@@ -8859,8 +8860,10 @@ class WorkflowService:# bypassing _execute_single_block. Recursively walk all nesting levels# so deeply nested blocks (e.g., file_download inside a double-nested# loop) get cached functions generated.+ # Skip engine-only loops: their script never runs, so queueing an unexecuted branch child regenerates every run.if (isinstance(block, (ForLoopBlock, WhileLoopBlock))+ and is_block_type_cacheable(block)and (is_adaptive_caching(workflow, workflow_run) or is_script_run)and workflow_run_block_result.status in cacheable_statuses):@@ -8921,6 +8924,7 @@ class WorkflowService:in_cache=block.label in script_blocks_by_label,disable_cache=block.disable_cache,requires_agent=block_requires_agent,+ engine_only_child_types=sorted(child_type.value for child_type in engine_only_loop_child_types(block)),)fallback_episode_id: str | None = Nonediff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.pyindex d7a97cc1c..05a5f2cd0 100644--- a/skyvern/forge/taskv3/tools.py+++ b/skyvern/forge/taskv3/tools.py@@ -636,8 +636,8 @@ class _TypeaheadPick(NamedTuple):clicked: booldeclared: boolnote: str | None = None- # How many rows the widget DECLARED beyond the ones it rendered, so a refusal can tell "nothing on- # this list is it" from "nothing on the part of it we could read".+ # How many rows the widget DECLARED beyond the ones it rendered (-1: its total is unknown), so a refusal+ # can tell "nothing on this list is it" from "nothing on the part of it we could read".overflow: int = 0# Whether the commit surface already vouched for the chosen label BEFORE the pick click — such a# surface proves nothing about the commit and must not vouch for it downstream either.@@ -794,6 +794,23 @@ def _lone_duplicate_candidate(rows: list[dict[str, Any]]) -> int | None:return n if isinstance(n, int) else None+def _rows_declare_more(rows: list[dict[str, Any]], *, partial: bool = False, count: int | None = None) -> bool:+ # `partial` (the scroller runs past the rendered rows) is passed only for a single window's read; a+ # walk that covered the scroller's whole extent has measured that itself and passes the rows it walked+ # as `count`, since its `rows` are keyed by label.+ return (+ partial+ or any(o.get("setsize_unknown") for o in rows)+ or max((int(o.get("setsize") or 0) for o in rows), default=0) > (len(rows) if count is None else count)+ )+++def _lead_clause(text: str) -> str:+ # The leading clause the anchor-lead read compares, split the way its JS splits it.+ norm = " ".join(text.split()).lower()+ return re.split(r"\s*[,;|(]\s*|\s+[-\u2013\u2014]\s+", norm)[0].strip()++def _prefix_tokens(s: str) -> list[str]:# Fold commas and apostrophes so a short value token-prefix-matches a punctuated label ("Yes" → "Yes, I# consent"). A slash is left intact so a combined "Yes/No" option is not prefix-matched by "Yes".@@ -2162,11 +2179,28 @@ _FIND_SUGGESTION_JS = (}return { count: n, options, declared: false };}- pool.sort((a, b) => b.score - a.score || a.h - b.h);- const best = pool[0];+ // An empty-state row is never the winner: one the widget disables, or one that echoes the typed+ // query back inside quotation marks ('No results for "x"'), which is how a list quotes the user's input.+ const QUOTES = '"\'\u201c\u201d\u2018\u2019\u00ab\u00bb\u201e';+ const typedNorm = String(args.value || '').replace(/\s+/g, ' ').trim().toLowerCase();+ const emptyState = (n) => {+ if (composedClosest(n, '[aria-disabled="true"]')) return true;+ const t = (n.innerText || '').replace(/\s+/g, ' ').trim().toLowerCase();+ const at = typedNorm ? t.indexOf(typedNorm) : -1;+ return at > 0 && QUOTES.includes(t[at - 1]) && QUOTES.includes(t[at + typedNorm.length] || '');+ };+ const live = pool.filter((c) => !emptyState(c.el));+ // The exact row the widget will not take still names the answer, so no lesser row may stand in for it.+ const barred = pool.find((c) => c.exactRow && emptyState(c.el));+ if (barred && !live.some((c) => c.exactRow)) {+ return { count: 1, options: [], declared: false, barredExact: (barred.el.innerText || '').trim().slice(0, 60) };+ }+ if (!live.length) return null;+ live.sort((a, b) => b.score - a.score || a.h - b.h);+ const best = live[0];// Two leading-clause matches for a short value ("No, ..." and "No - ...") with no exact row are// ambiguous: geometry must not decide an answer, so refuse and let the caller report the options.- if (exact !== null && !best.exactRow && pool.length > 1 && pool[1].score === best.score) return null;+ if (exact !== null && !best.exactRow && live.length > 1 && live[1].score === best.score) return null;// Refuse to tag a multi-row CONTAINER even when it is the only match (its score came from different// rows' text combined, and clicking it would land on an arbitrary middle row). A real suggestion is a// single row: its visible child elements, if any, sit on one line (inline sub-parts), not stacked rows.@@ -2441,45 +2475,6 @@ _FIND_CATEGORIES_JS = (}""")-# Tier-1 semantic commit read (SKY-15322): ONE shape-invariant probe consulted before the shape-# heuristics below. Decisive-ACCEPT-only — it answers {committed: true} or {committed: false}-# ("unknown"), never a decisive negative, so an unresolvable widget always falls to the heuristics-# unchanged. Every accept rests on a signal the tool did NOT author: raw value equality is NOT one-# (the tool typed the intended string itself, so it holds on every dead click — the equal-value-# impostor pair proves no black-box read can split that case).-# Tier-1 semantic commit read (SKY-15322): the narrowed solid core. ONE decisive-accept rule —-# the value TRANSFORM on a real form control: the widget rewrote what the tool typed into the-# intended value (raw equality is never evidence; the tool authored the typed string). Everything-# else is unknown by contract and falls to the shape heuristics unchanged: native selects (their own-# tool verifies by value; selection state alone carries no click causality), contenteditable anchors-# (three review rounds showed their text state cannot carry commit causality — completion, previews-# and blur-expansion are all indistinguishable from selection at the DOM level), and ARIA selection-# state (four distinct false-accept shapes across temporal, wiring, polarity and cross-root-# dimensions — retired to a later phase rather than guarded a fifth time).-_SEMANTIC_COMMIT_STATE_JS = (- r"""(arg) => {"""- + _PIERCED_QUERY_JS- + r"""- const nrm = (s) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().toLowerCase();- const want = nrm(arg.intended);- if (!want) return { committed: false };- let el = null;- try { el = pQS(arg.sel); } catch (e) { el = null; }- if (!el && arg.el && arg.el.isConnected) el = arg.el;- if (!el) return { committed: false };- if (el.tagName === 'SELECT') return { committed: false };- if (el.isContentEditable) return { committed: false };- // The typed baseline must have been READ from the element by the caller and is opt-in- // (typedTrusted !== true reads as untrusted), so a caller that forgets the key fails SAFE.- if (arg.typedTrusted !== true) return { committed: false };- const cur = el.value;- if (nrm(cur) === want && nrm(arg.typed) !== want) {- return { committed: true, via: 'value-transform', value: String(cur || '').trim() };- }- return { committed: false };-}"""-)-# A field's own committed-value surface: React-Select / styled combobox widgets move a commit OUT of# the filter input into a single-value node or chip beside it (clearing the input), so reading el.value# misses it. Reads only once the widget reports closed (aria-expanded=false) — a still-open list@@ -2492,12 +2487,17 @@ _SEMANTIC_COMMIT_STATE_JS = (# `ownCommittedSurface` is the display form (D1's short-surface read, observe/D3): one node's text or# aria, joined across several surfaces (multi-value chips) with ", "._OWN_COMMITTED_SURFACE_FN_JS = r"""- const ownWidgetClosed = (el) => {+ // `popupOpen`, when a caller passes it, lets a widget that exposes no aria-expanded at all read as+ // closed once its own popup is gone.+ const ownWidgetClosed = (el, popupOpen) => {const expandedEl = el.getAttribute('aria-expanded') != null ? el : el.closest('[aria-expanded]');- return (expandedEl ? expandedEl.getAttribute('aria-expanded') : null) === 'false';+ const exp = expandedEl ? expandedEl.getAttribute('aria-expanded') : null;+ if (exp === 'false') return true;+ return exp == null && typeof popupOpen === 'function' && !popupOpen(el);};- const ownCommittedSurfaces = (el) => {- if (!ownWidgetClosed(el)) return [];+ // `anyState` reads the nodes even while the list is open, for a baseline that may only over-count.+ const ownCommittedSurfaces = (el, popupOpen, anyState) => {+ if (!anyState && !ownWidgetClosed(el, popupOpen)) return [];const TRIGGER = "[role=combobox],[aria-haspopup=listbox],[aria-haspopup=menu],button[aria-expanded],input[role=combobox],select";const SURFACE = "[class*='single-value'],[class*='singleValue'],[class*='multi-value__label'],[role=option][aria-selected=true],.chip,.pill,[class*='token']";const VALUE_NODE = "[class*='single-value'],[class*='singleValue'],[class*='multi-value__label']";@@ -2740,8 +2740,16 @@ _VERIFY_COMMIT_JS = (// container — a re-render that merely replaces row nodes strips the row tags but keeps the// container, and must not read as a commit; suggListOpen). Exact equality with the CHOSEN label only.if (!args.liveOffer && args.suggTagged && !args.suggListOpen && cur && eqi(cur, chosen) && tagsGone) return cur;- } else if (cur && (cur !== typed || listClosed) && (toks(cur).size === 0 || overlaps(cur, chosen) || overlaps(cur, typed))) {- return cur;+ } else if (cur) {+ // The tool typed `typed` itself, so a value that is only that text back (whole, or with nothing beyond it+ // that names the chosen row) counts only once the list closed, and a value relates to the pick through+ // the chosen row, never through the typed query.+ const fold = (s) => String(s).replace(/\s+/g, ' ').trim().toLowerCase();+ const c = fold(chosen), inner = fold(cur).slice(c.length + 2, -1);+ const namesChosen = fold(cur) === c || (fold(cur).startsWith(c + ' (') && fold(cur).endsWith(')') && !!inner && !/[()]/.test(inner));+ const echo = !!typed && (fold(cur) === fold(typed) || (fold(cur).includes(fold(typed)) && !namesChosen+ && !overlaps(fold(cur).replace(fold(typed), ' '), chosen)));+ if ((!echo || listClosed) && (toks(cur).size === 0 || overlaps(cur, chosen))) return cur;}const cont = el.closest('div,li,fieldset');if (cont) {@@ -2752,13 +2760,15 @@ _VERIFY_COMMIT_JS = (for (const h of cont.querySelectorAll('input[type=hidden]')) {const v = (h.value || '').trim();if (!v || isOtherRow(v)) continue;+ // A hidden copy of the typed query that was already there before the click is the tool's own text.+ if (typed && preHidden.has(v) && (eqi(v, typed) || overlaps(v, typed))) continue;if (eqi(v, chosen)) return v;if (args.noSuggestionList) {const declaredHidden = Array.isArray(args.chosenValues) ? args.chosenValues : [];if ((overlaps(v, chosen) || declaredHidden.some((d) => eqi(d, v))) && !preHidden.has(v)) return v;continue;}- if (overlaps(v, chosen) || eqi(v, typed) || overlaps(v, typed)) return v;+ if (overlaps(v, chosen)) return v;}}// React-Select / styled combobox: on commit the value moves OUT of the filter input into a@@ -2889,6 +2899,255 @@ _OWN_FIELD_SCOPES_FN_JS = r"""};"""+# The hidden-input values _VERIFY_COMMIT_JS would read for this field, in the same div/li/fieldset scope.+_HIDDEN_VALUES_JS = (+ "el => { const c = el.closest('div,li,fieldset'); if (!c) return []; "+ "return Array.from(c.querySelectorAll('input[type=hidden]')).map((h) => (h.value || '').trim()).filter(Boolean); }"+)++# What the field ITSELF shows as committed, read only from sources it owns: its own label or+# aria-labelledby text past the caption, a removable chip in its single-field container, its own anchor+# text once its own popup is gone, or a painted value node. A neighbour's label, a row still offered in+# a list, and the raw text of the field's own input never count. Returns the source name, or ''.+_FIELD_OWN_STATE_FN_JS = r"""+ const OFFER_SEL = '[role="listbox"],[role="menu"],[role="tree"],[role="grid"],[role="option"],[role="menuitem"],[data-tv3-sugglist],[data-tv3-sugg],[data-tv3-menu]';+ const ownNrm = (s) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().toLowerCase();+ const ownPopupOpen = (el) => {+ const exp = el.getAttribute('aria-expanded') != null ? el : el.closest('[aria-expanded]');+ if (exp && exp.getAttribute('aria-expanded') === 'true') return true;+ return fieldOwnPopup(el, true) !== null;+ };+ const offered = (n) => { try { return composedClosest(n, OFFER_SEL) !== null; } catch (e) { return true; } };+ const textRuns = (root, el) => {+ const runs = [];+ const walk = (n, depth) => {+ if (depth > 6) return;+ for (const c of n.childNodes) {+ if (runs.length > 8) return;+ if (c.nodeType === 3) {+ const t = ownNrm(c.nodeValue);+ if (t) runs.push(t);+ continue;+ }+ if (c.nodeType !== 1 || c === el) continue;+ let skip = true;+ try {+ skip = c.matches('input,select,textarea,button,[role="button"],script,style,svg') || c.matches(OFFER_SEL) || !visible(c);+ } catch (e) { skip = true; }+ if (!skip) walk(c, depth + 1);+ }+ };+ walk(root, 0);+ return runs;+ };+ // The value a label shows is its LAST text run, after a caption that differs from it ("Country" / "Canada").+ const ownLabelHolds = (el, want) => {+ const labels = [];+ try { for (const l of (el.labels || [])) labels.push(l); } catch (e) { /* not a labelable element */ }+ const root = el.getRootNode();+ for (const id of String(el.getAttribute('aria-labelledby') || '').split(/\s+/)) {+ let t = null;+ try { t = id && root.getElementById ? root.getElementById(id) : null; } catch (e) { t = null; }+ if (t && t !== el && !pContains(t, el) && labels.indexOf(t) === -1) labels.push(t);+ }+ for (const l of labels) {+ if (offered(l) || !visible(l)) continue;+ const runs = textRuns(l, el);+ if (runs.length >= 2 && runs[runs.length - 1] === want && runs[0] !== want) return true;+ }+ return false;+ };+ // A chip is removable: it nests a control, or its name offers removal ("White Dismiss"). A button that+ // merely names an option ("Choose Canada", a quick pick) is an offer, not a commit.+ const CHIP_SEL = 'button,[role="button"],[class*="chip" i],[class*="pill" i],[class*="token" i],[class*="multi-value" i],[class*="multiValue" i]';+ const REMOVAL_RE = /\b(?:remove|dismiss|delete|clear|deselect|unselect)\b|^[x\u00d7\u2715\u2716\u2a2f]$/;+ // The chip's branch under the scope it shares with the field holds no caption of its own: a sibling+ // group's chips sit under that group's caption ("Countries lived in"), which a field-less group cannot+ // otherwise be told apart by.+ const captionFree = (scope, c) => {+ let branch = c;+ while (branch && scopeUp(branch) !== scope) branch = scopeUp(branch);+ if (!branch || branch.nodeType !== 1 || branch === c) return true;+ const runs = [];+ const walk = (n, depth) => {+ if (depth > 6 || runs.length) return;+ for (const k of n.childNodes) {+ if (k.nodeType === 3) { if (ownNrm(k.nodeValue)) { runs.push(k); return; } continue; }+ if (k.nodeType !== 1) continue;+ let skip = true;+ try { skip = k.matches(CHIP_SEL) || k.matches('script,style,svg') || !visible(k); } catch (e) { skip = true; }+ if (!skip) walk(k, depth + 1);+ }+ };+ walk(branch, 0);+ return runs.length === 0;+ };+ const idRefs = (el, attr) => {+ const root = el.getRootNode();+ const out = [];+ for (const id of String(el.getAttribute(attr) || '').split(/\s+/)) {+ let t = null;+ try { t = id && root.getElementById ? root.getElementById(id) : null; } catch (e) { t = null; }+ if (t) out.push(t);+ }+ return out;+ };+ // Proof that a chip is the field's own: the field describes it through ARIA, or it shares the field's+ // innermost container with nothing else there that carries text (other than the field's own label) and+ // no labelled group between it and that container.+ const chipProvablyOwned = (el, c) => {+ if (idRefs(el, 'aria-describedby').some((t) => pContains(t, c))) return true;+ const scope = ownFieldScopes(el).find((s) => pContains(s, c));+ if (!scope) return false;+ for (let n = scopeUp(c); n && n !== scope; n = scopeUp(n)) {+ if (n.nodeType !== 1) continue;+ if (n.tagName === 'FIELDSET' || n.hasAttribute('aria-label') || n.hasAttribute('aria-labelledby')) return false;+ }+ const own = idRefs(el, 'aria-labelledby');+ try { for (const l of (el.labels || [])) own.push(l); } catch (e) { /* not a labelable element */ }+ let text = false;+ const walk = (n, depth) => {+ if (depth > 8 || text) return;+ for (const k of n.childNodes) {+ if (k.nodeType === 3) { if (ownNrm(k.nodeValue)) { text = true; return; } continue; }+ if (k.nodeType !== 1 || k === el) continue;+ let skip = true;+ try { skip = own.includes(k) || k.matches(CHIP_SEL) || k.matches('input,select,textarea,script,style,svg') || !visible(k); } catch (e) { skip = true; }+ if (!skip) walk(k, depth + 1);+ }+ };+ walk(scope, 0);+ return !text;+ };+ // `strict` (the pre-act no-op) keeps only chips whose ownership is provable.+ const ownChipLabels = (el, strict) => {+ const found = [];+ for (const scope of ownFieldScopes(el)) {+ for (const c of scope.querySelectorAll(CHIP_SEL)) {+ if (found.some((f) => f.node === c) || excludedFor(el, c) || offered(c) || !visible(c)) continue;+ if (c.matches('[aria-selected],[aria-pressed],[aria-checked],[aria-expanded],[type="submit" i]')) continue;+ const runs = textRuns(c, el);+ if (!runs.length) continue;+ const aria = ownNrm(c.getAttribute('aria-label'));+ let removable = runs.slice(1).some((t) => REMOVAL_RE.test(t)) || (!!aria && aria !== runs[0] && REMOVAL_RE.test(aria));+ try { removable = removable || c.querySelector('button,[role="button"]') !== null; } catch (e) { /* keep */ }+ if (!removable || !captionFree(scope, c) || (strict && !chipProvablyOwned(el, c))) continue;+ found.push({ node: c, label: runs.filter((t) => !REMOVAL_RE.test(t)).join(' ') });+ }+ }+ return found.filter((f) => !found.some((o) => o !== f && f.node.contains(o.node))).map((f) => f.label);+ };+ const anchorHolds = (el, want, anyState) => {+ if (['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName) || el.isContentEditable) return false;+ if (!anyState && ownPopupOpen(el)) return false;+ if (textRuns(el, el).join(' ') === want) return true;+ const head = ownNrm(el.getAttribute('aria-label')).split('|')[0];+ return !!head && (head.includes(':') ? head.slice(head.indexOf(':') + 1).trim() : head) === want;+ };+ // An anchor may show only the committed row's leading clause ("Riverton" for "Riverton, North+ // Province"). That counts only as a CHANGE from the anchor's own text before its list opened, and only+ // when no other option the list showed shares that clause (`leadUnique`).+ const anchorShowsLead = (el, want, pre) => {+ if (['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName) || el.isContentEditable || ownPopupOpen(el)) return false;+ const lead = want.split(/\s*[,;|(]\s*|\s+[-\u2013\u2014]\s+/)[0].trim();+ if (!lead || lead === want || ownNrm(el.textContent) === ownNrm(pre)) return false;+ return textRuns(el, el).join(' ') === lead;+ };+ // Every source that shows `want`. `anyState` ignores whether the list is open: a pre-click baseline+ // read that way can only over-count, which only withholds an accept.+ const fieldOwnSources = (el, want, anyState) => {+ const out = [];+ if (!want) return out;+ if (ownLabelHolds(el, want)) out.push('label');+ if (ownChipLabels(el).includes(want)) out.push('chip');+ if (anchorHolds(el, want, anyState)) out.push('anchor');+ const surfaces = ownCommittedSurfaces(el, ownPopupOpen, anyState);+ if (surfaces.some((s) => s.displayed && (ownNrm(s.text) === want || ownNrm(s.aria) === want))) out.push('value-node');+ return out;+ };+"""++# Tier-1 semantic commit read (SKY-15322), decisive-ACCEPT-only: {committed: true} or {committed: false}+# ("unknown"), never a decisive negative, so an unresolvable widget falls to the shape heuristics+# unchanged. It accepts on the field's own committed state (fieldOwnSources, after a click: only a source the+# `baseline` read taken before the click did not show) or on a value TRANSFORM (the widget rewrote the text the+# tool typed into the intended value); raw value equality is never evidence, since the tool authored the text.+# Native selects and contenteditable anchors stay unknown (their state carries no click causality), and+# ARIA selection state is never read: an offered row can carry it.+_SEMANTIC_COMMIT_STATE_JS = (+ r"""(arg) => {"""+ + _PIERCED_QUERY_JS+ + _ROW_SEMANTICS_JS+ + _OWN_FIELD_SCOPES_FN_JS+ + _OWN_COMMITTED_SURFACE_FN_JS+ + _FIELD_OWN_STATE_FN_JS+ + r"""+ const nrm = (s) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().toLowerCase();+ const want = nrm(arg.intended);+ let el = null;+ try { el = pQS(arg.sel); } catch (e) { el = null; }+ if (!el && arg.el && arg.el.isConnected) el = arg.el;+ if (arg.snapshot === true) {+ // The field's committed state as raw parts, for a caller that asks whether ANY of it changed:+ // its own value, its container's hidden values, and its own aria-label and text (\u0001-joined).+ if (!el) return null;+ const hiddenValues = """+ + _HIDDEN_VALUES_JS+ + r""";+ return [+ el.isContentEditable ? (el.textContent || '') : (el.value || ''),+ hiddenValues(el).join(', '),+ nrm(el.getAttribute('aria-label')) + '\u0001' + nrm(el.textContent),+ ];+ }+ if (arg.baseline === true) {+ if (!el || !want) return null;+ return fieldOwnSources(el, want, true);+ }+ if (!el || !want) return { committed: false };+ if (el.tagName === 'SELECT') return { committed: false };+ if (el.isContentEditable) return { committed: false };+ // After a click, a source counts only when it did not already show the value before the click; an+ // unread baseline withholds every source.+ const preHeld = Array.isArray(arg.preHeld) ? arg.preHeld : null;+ let via = '';+ if (preHeld !== null) {+ try { via = fieldOwnSources(el, want, false).find((s) => !preHeld.includes(s)) || ''; } catch (e) { via = ''; }+ }+ if (via) return { committed: true, via: via, value: String(arg.intended).trim() };+ let lead = false;+ try {+ lead = typeof arg.preAnchor === 'string' && arg.leadUnique === true && anchorShowsLead(el, want, arg.preAnchor);+ } catch (e) { lead = false; }+ if (lead) return { committed: true, via: 'anchor-lead', value: String(arg.intended).trim() };+ // The typed baseline must have been READ from the element by the caller and is opt-in+ // (typedTrusted !== true reads as untrusted), so a caller that forgets the key fails SAFE.+ if (arg.typedTrusted !== true) return { committed: false };+ const cur = el.value;+ if (nrm(cur) === want && nrm(arg.typed) !== want) {+ return { committed: true, via: 'value-transform', value: String(cur || '').trim() };+ }+ return { committed: false };+}"""+)++# The labels of the removable chips the field's own container holds; null when unreadable.+_OWN_CHIPS_JS = (+ r"""(arg) => {"""+ + _PIERCED_QUERY_JS+ + _ROW_SEMANTICS_JS+ + _OWN_FIELD_SCOPES_FN_JS+ + _OWN_COMMITTED_SURFACE_FN_JS+ + _FIELD_OWN_STATE_FN_JS+ + r"""+ const el = pQS(arg.sel) || (arg.el && arg.el.isConnected ? arg.el : null);+ if (!el) return null;+ // A popup the field declares is its list, whatever its role; while it is on screen no chip counts as held.+ if (arg.strict === true && declaredTargets(el).some((t) => !pContains(t, el) && visible(t))) return null;+ return ownChipLabels(el, arg.strict === true);+}"""+)+# Whether the field's own widget container shows `chosen` as a committed-selection surface: a pill /# selected-item row (its leading aria-label clause or leaf text IS the label), or a bare label node the# widget renders beside a field that commits an opaque id into its value.@@ -3202,12 +3461,6 @@ _MENU_ROW_VALUES_JS = (}""")-# The hidden-input values _VERIFY_COMMIT_JS would read for this field, in the same div/li/fieldset scope.-_HIDDEN_VALUES_JS = (- "el => { const c = el.closest('div,li,fieldset'); if (!c) return []; "- "return Array.from(c.querySelectorAll('input[type=hidden]')).map((h) => (h.value || '').trim()).filter(Boolean); }"-)-# Why a reaction probe's answer about this selector may not carry a claim. `unprobeable` -- in-page# CSS cannot even parse it (Playwright syntax like `css=`, `>> nth=`, `:visible`, `text=`).# `component` -- it lives inside a component. The probes DO pierce open shadow roots, so this no@@ -6852,33 +7105,50 @@ _MENU_SCROLLER_STEP_JS = (}""")-# Whether the anchor (or its nearest aria-expanded ancestor) currently reports an OPEN list. Used to-# gate the "close a stray open list" Escape: sending Escape with no menu open would bubble to and close-# a surrounding dialog, so we only send it once a menu is confirmed open.-_MENU_OPEN_JS = (+# Whether a DECLARED field's own list is still open: its aria-expanded=true, OR the popup+# the field declares (fieldOwnPopup, from _ROW_SEMANTICS_JS) is still rendered. A widget that re-searches+# on the value it just wrote back can leave rows on screen with aria-expanded never having flipped.+_TYPEAHEAD_LIST_OPEN_JS = (r"""(arg) => {"""+ _PIERCED_QUERY_JS+ + _ROW_SEMANTICS_JS+ r"""- const el = pQS(arg.sel) || (arg.el && arg.el.isConnected ? arg.el : null);+ const el = (arg.sel ? pQS(arg.sel) : null) || (arg.el && arg.el.isConnected ? arg.el : null);if (!el) return false;const exp = el.getAttribute('aria-expanded') != null ? el : el.closest('[aria-expanded]');- return !!(exp && exp.getAttribute('aria-expanded') === 'true');+ if (exp && exp.getAttribute('aria-expanded') === 'true') return true;+ return !!fieldOwnPopup(el, true);}""")-# Whether a DECLARED field's own list is still open: _MENU_OPEN_JS's aria-expanded check, OR the popup-# the field declares (fieldOwnPopup, from _ROW_SEMANTICS_JS) is still rendered. A widget that re-searches-# on the value it just wrote back can leave rows on screen with aria-expanded never having flipped.-_TYPEAHEAD_LIST_OPEN_JS = (+# Whether the field's own list is KNOWN closed: aria-expanded="false" on the field or its owning combobox, or a+# declared popup that exists and is not rendered. No declared state is unknown, never closed.+_OWN_LIST_CLOSED_JS = (+ r"""(arg) => {"""+ + _PIERCED_QUERY_JS+ + _ROW_SEMANTICS_JS+ + r"""+ const el = (arg.sel ? pQS(arg.sel) : null) || (arg.el && arg.el.isConnected ? arg.el : null);+ if (!el || fieldOwnPopup(el, true)) return false;+ const owner = el.getAttribute('aria-expanded') != null ? el : composedClosest(el, '[role="combobox"][aria-expanded]');+ if (owner) return owner.getAttribute('aria-expanded') === 'false';+ const popups = declaredTargets(el).filter((t) => !pContains(t, el));+ const shown = (t) => { const r = t.getBoundingClientRect(); return r.width > 0 && r.height > 0; };+ return popups.length > 0 && !popups.some(shown);+}"""+)++# Whether the field declares its list's state: aria-expanded, a declared popup, or a declared popup id that+# resolves to nothing (the list is unmounted). Without one, an open list reads the same as a closed one.+_LIST_STATE_DECLARED_JS = (r"""(arg) => {"""+ _PIERCED_QUERY_JS+ _ROW_SEMANTICS_JS+ r"""const el = (arg.sel ? pQS(arg.sel) : null) || (arg.el && arg.el.isConnected ? arg.el : null);if (!el) return false;- const exp = el.getAttribute('aria-expanded') != null ? el : el.closest('[aria-expanded]');- if (exp && exp.getAttribute('aria-expanded') === 'true') return true;- return !!fieldOwnPopup(el, true);+ const declares = !!(el.getAttribute('aria-controls') || el.getAttribute('aria-owns'));+ return el.closest('[aria-expanded]') !== null || !!fieldOwnPopup(el, false) || (declares && !declaredTargets(el).length);}""")@@ -13611,7 +13881,15 @@ def build_browser_tools(return [str(t) for t in raw if isinstance(t, str)] if isinstance(raw, list) else Noneasync def _semantic_commit_read(- page: Any, selector: str, intended: str, typed: str, *, typed_trusted: bool+ page: Any,+ selector: str,+ intended: str,+ typed: str,+ *,+ typed_trusted: bool,+ pre_held: list[str] | None = None,+ pre_anchor: str | None = None,+ lead_unique: bool = False,) -> str | None:# Decisive-accept-only: the committed value when the semantic probe proves the commit, else# None ("unknown") — the caller's shape heuristics run unchanged on None, so this tier can@@ -13624,6 +13902,9 @@ def build_browser_tools("intended": intended,"typed": typed,"typedTrusted": typed_trusted,+ "preHeld": pre_held,+ "preAnchor": pre_anchor,+ "leadUnique": lead_unique,},)except Exception:@@ -13633,6 +13914,41 @@ def build_browser_tools(return str(read.get("value")).strip()return None+ async def _field_already_holds(page: Any, selector: str, value: str) -> bool:+ # Only a toggle field, one showing its values as removable chips that a re-click would remove, skips a+ # held value, and only with its own list known closed; every other field acts and verifies the click.+ if not settings.TASK_V3_SEMANTIC_COMMIT_VERIFY:+ return False+ await input_dispatch.approach(page, selector)+ try:+ if not await page.evaluate(_OWN_LIST_CLOSED_JS, await _probe_arg(page, selector)):+ return False+ except Exception:+ return False+ chips = await _own_chip_labels(page, selector, strict=True)+ return _exact_tier_key(value) in {_exact_tier_key(c) for c in chips or []}++ async def _field_own_baseline(page: Any, selector: str, value: str) -> list[str] | None:+ # Which of the field's own sources show `value` just before a click; None when unread.+ try:+ read = await page.evaluate(+ _SEMANTIC_COMMIT_STATE_JS,+ {**(await _probe_arg(page, selector)), "intended": value, "baseline": True},+ )+ except Exception:+ return None+ return [str(v) for v in read if isinstance(v, str)] if isinstance(read, list) else None++ async def _own_chip_labels(page: Any, selector: str, strict: bool = False) -> list[str] | None:+ try:+ chips = await page.evaluate(_OWN_CHIPS_JS, {**(await _probe_arg(page, selector)), "strict": strict})+ except Exception:+ return None+ return [str(c) for c in chips if isinstance(c, str)] if isinstance(chips, list) else None++ async def _holds_own_chips(page: Any, selector: str) -> bool:+ return bool(await _own_chip_labels(page, selector))+async def _settled_commit_read(page: Any, selector: str, verify_args: dict[str, Any], chosen: str, pre_surface_hit: bool) -> tuple[str, bool]:@@ -13643,6 +13959,8 @@ def build_browser_tools(readable = Falsecommitted = ""counted = False+ pre_held = verify_args.get("preHeld")+ pre_anchor = verify_args.get("preAnchorClosed")for attempt in range(4):if attempt:await asyncio.sleep(0.7)@@ -13681,6 +13999,9 @@ def build_browser_tools(chosen,str(verify_args.get("typed") or ""),typed_trusted=verify_args.get("typedTrusted") is True,+ pre_held=pre_held if isinstance(pre_held, list) else None,+ pre_anchor=pre_anchor.split("\u0001")[-1] if isinstance(pre_anchor, str) else None,+ lead_unique=verify_args.get("leadUnique") is True,)if semantic is not None:if semantic_commit_stats is not None:@@ -13887,8 +14208,8 @@ def build_browser_tools(# tagged. Where nothing declares one, the finder already reduced the reaction to a single# winner and there is nothing left to choose between — except under a reduced query, whose# rows answer a broader question than the caller asked. The 4th value is the declared- # aria-setsize when it exceeds the rendered row count (0 otherwise), reported in the refusal- # note so the model knows to name the option's full label rather than retry blindly.+ # aria-setsize when it exceeds the rendered row count, -1 when the rows declare their total+ # unknown, 0 otherwise; the refusal note reports it so the model names the full label.tagged = [o for o in (found.get("options") or []) if isinstance(o, dict) and isinstance(o.get("n"), int)]if not tagged:return bool(found.get("declared")), [], None, 0@@ -13901,7 +14222,9 @@ def build_browser_tools(# the list would hide a genuinely truncated one.declared_rendered = [o for o in rows if o.get("n") not in bare_ns]declared_size = max((int(o.get("setsize") or 0) for o in declared_rendered), default=0)- overflow = declared_size if declared_rendered and declared_size > len(declared_rendered) else 0+ overflow = 0+ if _rows_declare_more(declared_rendered):+ overflow = declared_size if declared_size > len(declared_rendered) else -1idx = _pick(rows)if idx is None and overflow == 0:# No exact-label winner over the complete rendered list — but "several rows" may be@@ -13978,11 +14301,19 @@ def build_browser_tools()if found is None:return _TypeaheadPick(None, None, False, None, clicked=False, declared=False)+ barred = found.get("barredExact")+ if isinstance(barred, str):+ verdict = ToolResult.error(+ f"the exact option {_model_text(barred, 60)!r} in {selector}'s list is disabled, so it cannot be selected "+ "— the field is NOT filled; no other option was picked in its place"+ )+ return _TypeaheadPick(None, None, False, None, clicked=False, declared=False, verdict=verdict)declared_rows, rows, idx, overflow = judged if judged is not None else await _resolve(found)stamp = f'[data-tv3-sugg="{idx}"]'if idx is None:+ declares = "its total unknown" if overflow < 0 else f"{overflow} rows"note = (- f"the list declares {overflow} rows and only {len(rows)} are rendered — type the option's full label"+ f"the list declares {declares} and only {len(rows)} are rendered — type the option's full label"if declared_rows and overflowelse None)@@ -14017,6 +14348,7 @@ def build_browser_tools(pre_value = pre_value_read if pre_value_read is not None else valueclicked = Falsepre_surface_hit = await _surface_confirms(page, selector, best_txt)+ pre_held = await _field_own_baseline(page, selector, best_txt)try:await page.evaluate(_STAMP_SUGG_LIST_JS, {"attr": "sugg", "n": idx})except Exception:@@ -14050,6 +14382,7 @@ def build_browser_tools(from_focus = bool(info.get("fromFocus"))declared = [str(v) for v in (info.get("declared") or []) if isinstance(v, str)]pre_surface_hit = await _surface_confirms(page, selector, best_txt)+ pre_held = await _field_own_baseline(page, selector, best_txt)try:await page.evaluate(_STAMP_SUGG_LIST_JS, {"attr": "sugg", "n": idx})except Exception:@@ -14099,6 +14432,7 @@ def build_browser_tools(if _exact_tier_key(text) != _exact_tier_key(best_txt)],"nestedRows": _rows_nested_in(idx, rows),+ "preHeld": pre_held,},best_txt,pre_surface_hit,@@ -14422,7 +14756,9 @@ def build_browser_tools(# Only a field the click could not reach can misroute its keys, and only that path restores.# A checked click leaves the page untagged and pays nothing.collateral.extend(await _capture_collateral(page, selector))- await input_dispatch.clear(page, selector, timeout=_ACTION_TIMEOUT_MS)+ # Clearing an empty multi-value input sends Delete, which removes the field's last chip.+ if not (pre_value == "" and await _holds_own_chips(page, selector)):+ await input_dispatch.clear(page, selector, timeout=_ACTION_TIMEOUT_MS)await input_dispatch.type_keys(page, selector, typed, delay=15, timeout=_typing_timeout_ms(typed), secret=secret, replace=True)@@ -15791,6 +16127,10 @@ def build_browser_tools(return _covered_error(exc.selector, exc.occluder)except _FieldNotEditable as exc:return _not_editable_error(exc)+ if pick.verdict is not None:+ # Nothing was picked either way, so the typed query comes back out and its list closes.+ await _restore_pre_type_value(page, selector, pre_value, [text])+ return pick.verdictif reach != "click":# focus() without a click cannot show the field took the keystrokes: a segmented control# may move the caret to a sibling segment or drop the keys. So only a read-back that holds@@ -15974,7 +16314,13 @@ def build_browser_tools(return Falseasync def _open_observe_pick(- page: Any, selector: str, value: str, *, close_open_menu: bool = False, search: str | None = None+ page: Any,+ selector: str,+ value: str,+ *,+ close_open_menu: bool = False,+ search: str | None = None,+ pre_checked: bool = False,) -> ToolResult:# Commit a click-to-open single-select in ONE call: open the list, enumerate the option rows the# click rendered (v3's own _FIND_MENU_JS tags them data-tv3-menu="N"), deterministically pick the@@ -15983,14 +16329,16 @@ def build_browser_tools(# and a non-typeable button/div anchor both land here. When no deterministic match is found the# tool returns a truthful did-not-commit AND the observed options, so the model resolves a# genuinely unexpected widget by sight (look()/act-by-mark) — never a blind text-LLM guess.+ if not pre_checked and await _field_already_holds(page, selector, value):+ return _already_held_result(selector, value)if close_open_menu:# A prior keystroke attempt may have opened this widget's list; close it so the pre-snapshot# captures the CLOSED page and _FIND_MENU_JS counts only rows THIS open-click renders. Escape- # is sent ONLY once a menu is confirmed open (aria-expanded=true) — a stray Escape with nothing- # open would bubble to and close a surrounding dialog, discarding the form. If the widget does- # not expose aria-expanded, we skip Escape and let the reopen self-heal below handle a toggle.+ # is sent ONLY once the field's own list is confirmed open (aria-expanded=true, or its declared+ # popup rendered) — a stray Escape with nothing open would bubble to and close a surrounding+ # dialog, discarding the form. An undeclared list is left to the reopen self-heal below.try:- menu_open = bool(await page.evaluate(_MENU_OPEN_JS, await _probe_arg(page, selector)))+ menu_open = bool(await page.evaluate(_TYPEAHEAD_LIST_OPEN_JS, await _probe_arg(page, selector)))except Exception:menu_open = Falseif menu_open:@@ -15999,6 +16347,17 @@ def build_browser_tools(await asyncio.sleep(0.1)except Exception:pass+ # The anchor's text with its list closed: an open list can change it, so a baseline read later would+ # let the anchor's return to its closed text pass for a commit.+ pre_anchor_closed: str | None = None+ try:+ probe_closed = await _probe_arg(page, selector)+ if await page.evaluate(_LIST_STATE_DECLARED_JS, probe_closed) and not await page.evaluate(+ _TYPEAHEAD_LIST_OPEN_JS, probe_closed+ ):+ pre_anchor_closed = str(await page.evaluate(_ANCHOR_SURFACE_JS, probe_closed) or "")+ except Exception:+ pre_anchor_closed = Noneasync def _open_and_enumerate() -> tuple[dict[str, Any] | None, ToolResult | None]:await input_dispatch.approach(page, selector)@@ -16126,12 +16485,13 @@ def build_browser_tools()walked_twins = False+ walked_twin_rows = 0walk_complete = Falsewalk_unproven: dict[str, Any] | None = Nonewalk_seen: list[dict[str, Any]] = []async def _scroll_search_menu_option() -> tuple[int | None, str | None, list[dict[str, Any]], bool]:- nonlocal walked_twins, walk_complete, walk_unproven, walk_seen+ nonlocal walked_twins, walked_twin_rows, walk_complete, walk_unproven, walk_seenunproven: str | None = None# A virtualised listbox only ever holds a window of rows in the DOM, so `value` may sit# outside what we already read. Drive the scroller `_FIND_MENU_JS` tagged, re-enumerating@@ -16229,14 +16589,14 @@ def build_browser_tools(hit = _match_menu_option(value, [{"n": k, "text": t} for k, t in enumerate(texts)])return texts[hit] if hit is not None else None- def _walked_rows() -> int:+ def _rows_of(key: str) -> int:# Rows, not labels: a label seen at tops more than 3px apart is that many rows.- total = 0- for key in {_exact_tier_key(t) for t in seen}:- ps = sorted(seen_pos.get(key, []))- at = 1 + sum(1 for a, b in zip(ps, ps[1:]) if b - a > 3) if ps else 1- total += max(at, sum(1 for t in seen if _exact_tier_key(t) == key))- return total+ ps = sorted(seen_pos.get(key, []))+ at = 1 + sum(1 for a, b in zip(ps, ps[1:]) if b - a > 3) if ps else 1+ return max(at, sum(1 for t in seen if _exact_tier_key(t) == key))++ def _walked_rows() -> int:+ return sum(_rows_of(key) for key in {_exact_tier_key(t) for t in seen})def _row_n(current: list[dict[str, Any]], text: str) -> int | None:fresh = next((o for o in current if str(o.get("text") or "") == text and not o.get("nav")), None)@@ -16332,10 +16692,16 @@ def build_browser_tools(# the exact row a prefix hit stands in for, may sit in what was not seen.covered = reached_end and _rows_cover_extent()walked_twins = want in ambiguous- declared = max((int(o.get("setsize") or 0) for o in seen.values()), default=0)+ walked_twin_rows = _rows_of(want) if walked_twins else 0# A text-less option still counts against the declared size (it may be a placeholder whose row is still# loading); only a declared separator is filler, and it counts neither there nor as a gap in the extent.- walk_complete = covered and not size_unknown and not unknown_seen and declared <= _walked_rows()+ walk_complete = (+ covered+ and not size_unknown+ and not unknown_seen+ and not _rows_declare_more(list(seen.values()), count=_walked_rows())+ )+ walk_seen = [o for o in seen.values() if not o.get("nav")]named = _value_contenders(value, [t for t, o in seen.items() if not o.get("nav")])for text in (hit_text, deferred if _match_seen() == deferred else None):if text is None:@@ -16377,7 +16743,6 @@ def build_browser_tools(# A walk that reached the end but left gaps is reported as cut short: its rows are not the# whole list, so the definitive no-match/ambiguity verdicts do not apply.definitive = reached_end and (_is_ambiguous(hit_text) if hit_text is not None else _rows_cover_extent())- walk_seen = [o for o in seen.values() if not o.get("nav")]return None, None, (list(seen.values()) if definitive else current), definitive# collapse_duplicates only here: `options` is the COMPLETE, non-overflowed list this call just@@ -16454,26 +16819,16 @@ def build_browser_tools()async def _committed() -> list[str | None]:- # The field's own value, its container's hidden values and its label, each None when unread.- probe = await _probe_arg(page, selector)- state: list[str | None] = []+ # The field's own value, its container's hidden values, its aria-label and text; None when unread.try:- own = await page.eval_on_selector(- selector, "el => (el.isContentEditable ? (el.textContent || '') : (el.value || ''))"+ read = await page.evaluate(+ _SEMANTIC_COMMIT_STATE_JS, {**(await _probe_arg(page, selector)), "snapshot": True})- state.append(str(own or ""))- except Exception:- state.append(None)- try:- hidden = await page.eval_on_selector(selector, _HIDDEN_VALUES_JS)- state.append(", ".join(str(v) for v in hidden) if isinstance(hidden, list) else None)except Exception:- state.append(None)- try:- state.append(str(await page.evaluate(_ANCHOR_SURFACE_JS, probe) or ""))- except Exception:- state.append(None)- return state+ read = None+ if not isinstance(read, list) or len(read) != 3:+ return [None, None, None]+ return [part if isinstance(part, str) else None for part in read]before = await _committed()@@ -16519,10 +16874,8 @@ def build_browser_tools(read_now = [o for o in raw or [] if isinstance(o, dict) and isinstance(o.get("n"), int)]# Same completeness signals as the unfiltered read: a declared aria-setsize past the rows, or a# scroller whose extent runs past them. `_commit_gate` commits no row from an incomplete read.- complete = (- max((int(o.get("setsize") or 0) for o in read_now), default=0) <= len(read_now)- and not any(o.get("setsize_unknown") for o in read_now)- and not (isinstance(tagged, dict) and tagged.get("partial"))+ complete = not _rows_declare_more(+ read_now, partial=isinstance(tagged, dict) and bool(tagged.get("partial")))fresh = int(tagged.get("fresh") or 0) if isinstance(tagged, dict) else 0return sorted((o for o in read_now if not o.get("nav")), key=_n_order), complete, fresh@@ -16694,12 +17047,14 @@ def build_browser_tools(# Only two visible rows that ARE the value make the filter pointless; a longer row that merely starts# with it says nothing about whether the exact one sits past the window.exact_twins = walked_twins or sum(1 for t in contenders if _exact_tier_key(t) == want_key) >= 2+ filtered_pick = Falseif idx is None and not walk_complete and not exact_twins:popup_pick = await _popup_filter_pick()if isinstance(popup_pick, ToolResult):return popup_pickif popup_pick is not None:idx, options = popup_pick+ filtered_pick = Trueif idx is None:# Match over the FULL list above, but bound the error PAYLOAD: enumerate at most 15 rows,# each ≤60 chars, so a miss on a 250-option country list does not ship a 15KB tool message.@@ -16707,7 +17062,15 @@ def build_browser_tools(if walk_unproven is not None and len(contenders) < 2 and not exact_twins:return _unproven_row_error(value, selector, str(walk_unproven["why"]), walk_unproven)if scanned_all:- if len(contenders) >= 2 or exact_twins or (contenders and walk_complete):+ if exact_twins:+ shared = next((t for t in contenders if _exact_tier_key(t) == want_key), value)+ n_twins = max(2, walked_twin_rows, sum(1 for t in contenders if _exact_tier_key(t) == want_key))+ return ToolResult.error(+ f"{value!r} is ambiguous in {selector}'s list — {n_twins} options share the exact label "+ f"{_model_text(shared, 60)!r}; the field is NOT filled — look() at the list and click the right one by "+ 'its [data-tv3-menu="N"] selector'+ )+ if len(contenders) >= 2 or (contenders and walk_complete):return _ambiguous_error()if contenders:only = _model_text(contenders[0], 60)@@ -16813,7 +17176,7 @@ def build_browser_tools(# that multi-selects, declared or not. Leave it; close the list the way the widget closes# itself.try:- if await page.evaluate(_MENU_OPEN_JS, probe):+ if await page.evaluate(_TYPEAHEAD_LIST_OPEN_JS, probe):await input_dispatch.press(_current_page(), None, "Escape")except Exception:pass@@ -16826,6 +17189,14 @@ def build_browser_tools(except Exception:chosen_values = []pre_surface_hit = await _surface_confirms(page, selector, matched)+ pre_held = await _field_own_baseline(page, selector, matched)+ # A leading clause names the row only when the whole list was read and no other row shares it.+ lead = _lead_clause(matched)+ lead_unique = (+ not filtered_pick+ and (not overflowed or walk_complete)+ and sum(1 for o in evidence_rows if _lead_clause(str(o.get("text") or "")) == lead) == 1+ )try:await page.evaluate(_STAMP_SUGG_LIST_JS, {"attr": "menu", "n": idx})except Exception:@@ -16851,6 +17222,9 @@ def build_browser_tools("typedTrusted": typed_trusted,"preHidden": pre_hidden,"preSurface": pre_surface,+ "preHeld": pre_held,+ "preAnchorClosed": pre_anchor_closed,+ "leadUnique": lead_unique,},matched,pre_surface_hit,@@ -16873,6 +17247,9 @@ def build_browser_tools(return ToolResult.error(f"clicked {matched!r} but {selector} did not commit a value")return ToolResult.error(f"clicked {matched!r} but {selector} did not commit a value")+ def _already_held_result(selector: str, value: str) -> ToolResult:+ return ToolResult.ok(f"{value!r} was already selected for {selector}; left it as is")+def _surface_holds(matched: str, surface: str, value: str) -> bool:def norm(t: str) -> str:return " ".join(t.split()).casefold()@@ -16979,6 +17356,9 @@ def build_browser_tools(return ToolResult.error(f"selected suggestion {opt_txt!r} but {selector} did not commit a value")return ToolResult.error(f"selected suggestion {opt_txt!r} but {selector} did not commit a value")+ if await _field_already_holds(page, selector, value):+ return _already_held_result(selector, value)+if live_offer is not None:live_pick = await _commit_typeahead(page, selector, value, rounds=0, pre_own=await _own_surface_text(page, selector), live_offer=live_offer@@ -17051,6 +17431,9 @@ def build_browser_tools(rung_pick = await _commit_typeahead(page, selector, value, rounds=4, exact_only=True, probe=rung, pre_own=pre_own)+ if rung_pick.verdict is not None:+ await _restore_pre_type_value(page, selector, pre_value, typed_queries)+ return rung_pick.verdictif rung_pick.suggestion is not None:return await _typeahead_verdict_result(rung_pick.suggestion,@@ -17298,7 +17681,9 @@ def build_browser_tools(data={"release_own_list": True},)# The focus-click of the type attempt may have opened this widget's list, so close it first.- opened = await _open_observe_pick(page, selector, value, close_open_menu=True, search=search)+ opened = await _open_observe_pick(+ page, selector, value, close_open_menu=True, search=search, pre_checked=True+ )if restore_on_refusal and opened.status != "ok":await _restore_pre_type_value(page, selector, pre_value, typed_queries)return opened@@ -17326,7 +17711,7 @@ def build_browser_tools(await _restore_pre_type_value(page, selector, pre_value, typed_queries)return verdict# A non-typeable anchor (a button/div that only opens a list on click): open, observe, pick.- return await _open_observe_pick(page, selector, value, search=search)+ return await _open_observe_pick(page, selector, value, search=search, pre_checked=True)async def select_option(args: dict[str, Any]) -> ToolResult:page, error = await _resolve_page()diff --git a/skyvern/services/workflow_script_service.py b/skyvern/services/workflow_script_service.pyindex d2ff9bfa0..4211cca19 100644--- a/skyvern/services/workflow_script_service.py+++ b/skyvern/services/workflow_script_service.py@@ -60,17 +60,21 @@ BLOCK_TYPES_THAT_SHOULD_BE_CACHED = {# Loop children that must always run through the engine: codegen emits them as a# no-op comment, so a cached loop would silently skip them.-_ENGINE_ONLY_LOOP_CHILD_TYPES = {BlockType.WEB_SEARCH, BlockType.TERMINATE}+_ENGINE_ONLY_LOOP_CHILD_TYPES = {BlockType.WEB_SEARCH, BlockType.TERMINATE, BlockType.CONDITIONAL}-def _contains_engine_only_child(block: Any) -> bool:+def engine_only_loop_child_types(block: Any) -> set[BlockType]:+ """Engine-only block types nested at any depth inside a loop; empty for any other block."""block_type = block.get("block_type") if isinstance(block, dict) else getattr(block, "block_type", None)- if block_type in _ENGINE_ONLY_LOOP_CHILD_TYPES:- return True- if block_type in {BlockType.FOR_LOOP, BlockType.WHILE_LOOP}:- children = block.get("loop_blocks", []) if isinstance(block, dict) else block.loop_blocks- return any(_contains_engine_only_child(child) for child in children)- return False+ if block_type not in {BlockType.FOR_LOOP, BlockType.WHILE_LOOP}:+ return set()+ found: set[BlockType] = set()+ for child in block.get("loop_blocks", []) if isinstance(block, dict) else block.loop_blocks:+ child_type = child.get("block_type") if isinstance(child, dict) else getattr(child, "block_type", None)+ if child_type in _ENGINE_ONLY_LOOP_CHILD_TYPES:+ found.add(BlockType(child_type))+ found |= engine_only_loop_child_types(child)+ return founddef is_block_type_cacheable(block: Any) -> bool:@@ -80,7 +84,8 @@ def is_block_type_cacheable(block: Any) -> bool:block with export enabled is excluded: the generated script's cached replayfunction only carries prompt/schema/url/model (see _build_extract_statement), soa cached run would silently skip the Parquet export while still reporting- success (SKY-15396).+ success (SKY-15396). A loop holding an engine-only child (_ENGINE_ONLY_LOOP_CHILD_TYPES)+ is excluded for the same reason: loop codegen emits every child in list order.Accepts either a Block model instance or its dict/model_dump form, matching thetwo shapes callers hold across script generation and workflow execution.@@ -88,7 +93,7 @@ def is_block_type_cacheable(block: Any) -> bool:block_type = block.get("block_type") if isinstance(block, dict) else getattr(block, "block_type", None)if block_type not in BLOCK_TYPES_THAT_SHOULD_BE_CACHED:return False- if block_type in {BlockType.FOR_LOOP, BlockType.WHILE_LOOP} and _contains_engine_only_child(block):+ if engine_only_loop_child_types(block):return Falseif block_type == BlockType.EXTRACTION:export_enabled = (diff --git a/tests/unit/copilot_test_helpers.py b/tests/unit/copilot_test_helpers.pyindex 1a7dbe6e9..8ad50b4fb 100644--- a/tests/unit/copilot_test_helpers.py+++ b/tests/unit/copilot_test_helpers.py@@ -819,7 +819,7 @@ def redact_parameter_values(monkeypatch: pytest.MonkeyPatch, ctx: AgentContext,"""Give ``ctx`` code-block parameters and a redactor that replaces each of their values with ``[redacted]``."""ctx.codeblock_redaction_parameters = parameters- def redact(value: Any, active: dict[str, Any]) -> Any:+ def redact(value: Any, active: dict[str, Any], **_budget: object) -> Any:if isinstance(value, str):for secret in active.values():value = value.replace(secret, "[redacted]")diff --git a/tests/unit/forge/sdk/copilot/test_browser_code_tool.py b/tests/unit/forge/sdk/copilot/test_browser_code_tool.pyindex c773a71c7..d7a5639b2 100644--- a/tests/unit/forge/sdk/copilot/test_browser_code_tool.py+++ b/tests/unit/forge/sdk/copilot/test_browser_code_tool.py@@ -2118,7 +2118,9 @@ async def test_a_tainted_page_withholds_its_location_from_browser_code_page_stat@pytest.mark.asyncio@pytest.mark.parametrize("code", [pytest.param(" ", id="refused"), pytest.param("1", id="ran-with-source-reference")])-async def test_a_browser_code_result_the_scrub_empties_stays_empty(monkeypatch: pytest.MonkeyPatch, code: str) -> None:+async def test_a_browser_code_result_the_scrub_cannot_redact_is_withheld(+ monkeypatch: pytest.MonkeyPatch, code: str+) -> None:_patch_cell_runtime(monkeypatch)ctx = make_copilot_context()ctx.browser_session_id = "pbs_scrub_emptied"@@ -2129,4 +2131,6 @@ async def test_a_browser_code_result_the_scrub_empties_stays_empty(monkeypatch:finally:clear_session_scrub_values(ctx.browser_session_id)- assert result == {}+ assert mcp_adapter.is_redaction_withheld(result) and result["ok"] is False+ assert result["data"]["redaction_withheld"]["reason"] == "redaction_unavailable"+ assert set(result) == {"page_state", "ok", "error", "data"}diff --git a/tests/unit/test_copilot_mcp_adapter.py b/tests/unit/test_copilot_mcp_adapter.pyindex 066115ede..f68da31f8 100644--- a/tests/unit/test_copilot_mcp_adapter.py+++ b/tests/unit/test_copilot_mcp_adapter.py@@ -56,6 +56,7 @@ from skyvern.forge.sdk.copilot.secret_scrub import ()from skyvern.forge.sdk.copilot.tools import NATIVE_TOOLS, mcp_hooksfrom skyvern.forge.sdk.copilot.tools import scouting as scouting_module+from skyvern.forge.sdk.copilot.tools._shared import _composition_get_structured_evidence_resultfrom skyvern.forge.sdk.copilot.tools.mcp_hooks import _build_skyvern_mcp_overlays, get_skyvern_mcp_alias_mapfrom skyvern.forge.sdk.copilot.turn_origin import TurnOriginfrom skyvern.webeye.persistent_sessions_manager import (@@ -99,7 +100,7 @@ def test_scrub_tool_result_redacts_encoded_matching_origin_values(monkeypatch: pencoded = quote(secret, safe="")seen_parameters: list[dict[str, Any]] = []- def redact(value: Any, parameters: dict[str, Any]) -> Any:+ def redact(value: Any, parameters: dict[str, Any], **_budget: object) -> Any:seen_parameters.append(parameters)def walk(node: Any) -> Any:@@ -160,12 +161,63 @@ def test_a_driver_navigation_code_survives_a_scrubbed_value_that_spells_part_of_rescrubbed = mcp_adapter.scrub_model_facing_tool_result(ctx, flattened, tool_name="skyvern_navigate")assert rescrubbed["nav_error_code"] == flattened["nav_error_code"]- # A scrub that fails closed stays empty: a code written into it would turn a failed call into a success.register_secret_scrub_value(ctx, "target")fail_closed = mcp_adapter.scrub_model_facing_tool_result(ctx, {**flattened, "target": {"page": 0}}, tool_name="skyvern_navigate")- assert fail_closed == {}+ assert mcp_adapter.is_redaction_withheld(fail_closed) and fail_closed["ok"] is False+ assert "nav_error_code" not in fail_closed and "ERR_TUNNEL" not in str(fail_closed)++[email protected]("size_is_registered", [False, True])+def test_a_withheld_result_keeps_its_disposition_across_rescrubs_and_logs_once(size_is_registered: bool) -> None:+ ctx = make_copilot_ctx()+ register_secret_scrub_value(ctx, "data")+ raw = {"ok": True, "data": {"result": "signed-in page text"}}+ size = len(json.dumps(raw, ensure_ascii=False))+ if size_is_registered:+ register_secret_scrub_value(ctx, str(size))+ outcome = mcp_adapter._browser_call_outcome_from_mapping(+ raw_tool_name="skyvern_evaluate", source_browser_session_id=None, raw_result=raw+ )++ with capture_logs() as logs:+ first = mcp_adapter.scrub_model_facing_tool_result(ctx, raw, tool_name="skyvern_evaluate")+ withheld_outcome = outcome.with_raw_result(first)+ projected = mcp_adapter._project_browser_call_outcome(withheld_outcome, display_tool_name="evaluate")+ second = mcp_adapter.scrub_model_facing_tool_result(ctx, projected, tool_name="skyvern_evaluate")++ assert first == second and mcp_adapter.is_redaction_withheld(second)+ assert (withheld_outcome.ok, withheld_outcome.payload_omitted, withheld_outcome.error_kind) == (False, True, "tool")+ assert "signed-in page text" not in json.dumps([first, projected, second])+ assert (str(size) in json.dumps(second)) is not size_is_registered+ assert [log["event"] for log in logs if log["event"] == "copilot_model_facing_result_withheld"] == [+ "copilot_model_facing_result_withheld"+ ]++[email protected]("_stub_browser_session")+async def test_structured_evidence_reports_a_withheld_read_by_its_reason() -> None:+ ctx = make_copilot_ctx(browser_session_id="pbs_withheld_evidence")+ register_secret_scrub_value(ctx, "data")+ ctx.discovery_mcp_server = _make_server(+ ctx,+ {"ok": True, "data": {"result": json.dumps({"text": "signed-in page text"})}},+ SchemaOverlay(requires_browser=True),+ alias_map={"evaluate": "skyvern_evaluate"},+ )+ try:+ evidence, error = await _composition_get_structured_evidence_result(+ ctx, inspected_url="https://example.test/", current_url="https://example.test/"+ )+ finally:+ clear_session_scrub_values(ctx.browser_session_id)++ assert evidence is None+ assert error is not None and error.startswith("structured page evidence was withheld: Result withheld")+ assert "could not be redacted safely" in error and "too large" not in error+ assert "returned an error" not in error and "signed-in" not in error@pytest.mark.parametrize(@@ -213,7 +265,7 @@ def test_the_model_facing_scrub_reads_the_run_parameters_before_restoring_a_code"""A redaction parameter never registered with the exact-value scrubber is still redacted, so therestore has to consult it too or it hands back what the parameter pass was hiding."""- def redact(value: object, parameters: dict[str, object]) -> object:+ def redact(value: object, parameters: dict[str, object], **_budget: object) -> object:secret = str(next(iter(parameters.values())))def walk(node: object) -> object:@@ -3616,7 +3668,7 @@ class TestPageStateOnBrowserResults:@skip_no_browser@pytest.mark.asyncio- async def test_a_result_the_scrub_empties_stays_an_error(self, monkeypatch: pytest.MonkeyPatch) -> None:+ async def test_a_result_the_scrub_withholds_stays_an_error(self, monkeypatch: pytest.MonkeyPatch) -> None:ctx = make_copilot_ctx(browser_session_id="pbs_scrub_emptied")register_secret_scrub_value(ctx, "error")try:@@ -3628,4 +3680,4 @@ class TestPageStateOnBrowserResults:clear_session_scrub_values(ctx.browser_session_id)assert result.isError is True- assert result.content == []+ assert "redaction_withheld" in result.content[0].text and "timed out" not in result.content[0].textdiff --git a/tests/unit/test_copilot_non_retriable_nav.py b/tests/unit/test_copilot_non_retriable_nav.pyindex e08732a1d..2edf9d80c 100644--- a/tests/unit/test_copilot_non_retriable_nav.py+++ b/tests/unit/test_copilot_non_retriable_nav.py@@ -1599,7 +1599,7 @@ def test_a_driver_code_survives_the_code_block_result_scrub() -> None:"""The heal path masks the whole block result before the run result is assembled."""- def redact(value: object, parameters: dict[str, object]) -> object:+ def redact(value: object, parameters: dict[str, object], **_budget: object) -> object:secret = str(next(iter(parameters.values())))def walk(node: object) -> object:@@ -1920,7 +1920,7 @@ def test_a_parameter_walk_that_runs_out_leaves_every_code_to_the_mask(monkeypatcfor _ in range(block_module._PARAMETER_STRING_WALK_LIMIT):deep = {"next": deep}- def redact(value: object, parameters: dict[str, object]) -> object:+ def redact(value: object, parameters: dict[str, object], **_budget: object) -> object:if isinstance(value, list):return ["[redacted]" for _ in value]return valuediff --git a/tests/unit/test_copilot_positive_evidence_carriers.py b/tests/unit/test_copilot_positive_evidence_carriers.pyindex 6f359bcd9..0c03a6341 100644--- a/tests/unit/test_copilot_positive_evidence_carriers.py+++ b/tests/unit/test_copilot_positive_evidence_carriers.py@@ -606,7 +606,7 @@ async def test_nonsensitive_origin_parameters_still_scrub_dispatched_terminal_ht_stub_app(monkeypatch, artifacts, {"art_parameter": html.encode()})seen_parameters: list[object] = []- def redact(value: object, parameters: object) -> object:+ def redact(value: object, parameters: object, **_budget: object) -> object:seen_parameters.append(parameters)return value.replace(parameter_value, "[REDACTED]") if isinstance(value, str) else value@@ -1324,7 +1324,7 @@ async def test_dispatched_fetch_scrubs_persisted_terminal_html_before_parsing(_stub_app(monkeypatch, artifacts, {"art_secret": html.encode()})seen: list[object] = []- def scrub(value: object, redaction_parameters: object) -> object:+ def scrub(value: object, redaction_parameters: object, **_budget: object) -> object:seen.append(value)assert redaction_parameters == {"password": secret}return value.replace(secret, "[REDACTED]") if isinstance(value, str) else valuediff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.pyindex a106a211d..21e207fa7 100644--- a/tests/unit/test_copilot_scout_act_observe.py+++ b/tests/unit/test_copilot_scout_act_observe.py@@ -498,7 +498,7 @@ async def test_failed_click_wrapper_reuses_registered_and_codeblock_redaction_bopage_payload["page_title"] = f"Account for {credential_secret}"page_payload["forms"][0]["submit_controls"][0]["text"] = f"Continue with {credential_secret} and {parameter_secret}"- def redact_codeblock_parameters(value: Any, parameters: dict[str, Any]) -> Any:+ def redact_codeblock_parameters(value: Any, parameters: dict[str, Any], **_budget: object) -> Any:assert parameters == {"account": parameter_secret}return value.replace(parameter_secret, "[REDACTED_PARAMETER]") if isinstance(value, str) else valuediff --git a/tests/unit/test_forloop_script_generation.py b/tests/unit/test_forloop_script_generation.pyindex 30fae30fd..1096cb74d 100644--- a/tests/unit/test_forloop_script_generation.py+++ b/tests/unit/test_forloop_script_generation.py@@ -21,6 +21,7 @@ from skyvern.core.script_generations.transform_workflow_run import ()from skyvern.forge.sdk.workflow.service import BLOCK_TYPES_THAT_SHOULD_BE_CACHEDfrom skyvern.schemas.workflows import BlockType+from skyvern.services.workflow_script_service import is_block_type_cacheableclass TestForLoopInCacheableBlocks:@@ -464,6 +465,44 @@ class TestForLoopScriptExecution:# Should have values = '' (empty string), not Noneassert "values = ''" in code or 'values = ""' in code+ def test_loop_holding_a_conditional_is_not_cacheable(self) -> None:+ """Loop codegen emits every child in list order, so a cached loop would run both branches."""+ forloop_block = {+ "block_type": "for_loop",+ "label": "loop_1",+ "loop_variable_reference": "rows",+ "loop_blocks": [+ {+ "block_type": "conditional",+ "label": "cond_1",+ "branch_conditions": [+ {+ "criteria": {"criteria_type": "jinja2_template", "expression": "{{ current_value.ok }}"},+ "next_block_label": "branch_a_http",+ },+ {"is_default": True, "next_block_label": "branch_b_http"},+ ],+ },+ {+ "block_type": "http_request",+ "label": "branch_a_http",+ "method": "GET",+ "url": "https://example.com/a",+ },+ {+ "block_type": "http_request",+ "label": "branch_b_http",+ "method": "GET",+ "url": "https://example.com/b",+ },+ ],+ }++ loop_code = cst.Module(body=[_build_for_loop_statement("loop_1", forloop_block)]).code++ assert "branch_a_http" in loop_code and "branch_b_http" in loop_code+ assert is_block_type_cacheable(forloop_block) is False+class TestForLoopScriptCompilation:"""Test that generated scripts with ForLoop blocks compile without SyntaxError.diff --git a/tests/unit/test_pending_script_promotion.py b/tests/unit/test_pending_script_promotion.pyindex 6a527e8cc..6122779ca 100644--- a/tests/unit/test_pending_script_promotion.py+++ b/tests/unit/test_pending_script_promotion.py@@ -132,14 +132,34 @@ class TestIsBlockTypeCacheable:assert workflow_script_service.is_block_type_cacheable(non_cacheable) is False@pytest.mark.parametrize("loop_type", [BlockType.FOR_LOOP, BlockType.WHILE_LOOP])- def test_loop_containing_a_terminate_block_is_not_cacheable(self, loop_type: BlockType) -> None:- terminate = {"label": "stop", "block_type": BlockType.TERMINATE, "reason": "missing"}+ @pytest.mark.parametrize(+ "engine_only_child",+ [+ {"label": "stop", "block_type": BlockType.TERMINATE, "reason": "missing"},+ {"label": "search", "block_type": BlockType.WEB_SEARCH, "query": "q"},+ {+ "label": "route",+ "block_type": BlockType.CONDITIONAL,+ "branch_conditions": [+ {"criteria": {"expression": "{{ current_value }}"}, "next_block_label": "fill"},+ {"is_default": True, "next_block_label": None},+ ],+ },+ ],+ ids=["terminate", "web_search", "conditional"],+ )+ def test_loop_containing_an_engine_only_block_is_not_cacheable(+ self, loop_type: BlockType, engine_only_child: dict+ ) -> None:task = {"label": "fill", "block_type": BlockType.TASK}- direct = {"label": "outer", "block_type": loop_type, "loop_blocks": [task, terminate]}+ direct = {"label": "outer", "block_type": loop_type, "loop_blocks": [task, engine_only_child]}nested = {"label": "outer","block_type": loop_type,- "loop_blocks": [task, {"label": "inner", "block_type": BlockType.FOR_LOOP, "loop_blocks": [terminate]}],+ "loop_blocks": [+ task,+ {"label": "inner", "block_type": BlockType.FOR_LOOP, "loop_blocks": [engine_only_child]},+ ],}plain = {"label": "outer", "block_type": loop_type, "loop_blocks": [task]}diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.pyindex 45664ed4d..4a847abd4 100644--- a/tests/unit/test_taskv3_tools.py+++ b/tests/unit/test_taskv3_tools.py@@ -24696,6 +24696,35 @@ async def test_observe_marks_button_listbox_anchor_as_combobox() -> None:assert "[autocomplete→use select_combobox]" in line, line+@_skip_no_browser+async def test_select_combobox_does_not_take_a_shared_lead_clause_the_walk_saw_as_the_committed_row() -> None:+ # The walk passes "Riverton, South Province" before it finds "Riverton, Riverdale County" far down the list;+ # the widget then commits the sibling and shows only "Riverton". That clause names two walked rows.+ places = [(f"Place {i:02d}", f"+{i}") for i in range(30)]+ places[2] = ("Riverton, South Province", "+2")+ places[-1] = ("Riverton, Riverdale County", "+29")+ misroute = """+<script>+(function () {+ var btn = document.getElementById('cc');+ new MutationObserver(function () {+ var label = btn.getAttribute('aria-label') || '';+ if (label.indexOf('Riverdale County') < 0) return;+ btn.setAttribute('aria-label', 'Select country calling code: Riverton, South Province');+ btn.textContent = 'Riverton';+ }).observe(btn, { attributes: true, attributeFilter: ['aria-label'] });+})();+</script>+</body>"""+ async with _content_page(_cc_widget_html(places, 0).replace("</body>", misroute)) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "select_combobox").handler({"selector": "#cc", "value": "Riverton, Riverdale County"})+ label = await page.eval_on_selector("#cc", "el => el.getAttribute('aria-label')")+ assert label.endswith("South Province"), label+ assert r.status != "ok", r.content++@_skip_no_browser@pytest.mark.asyncioasync def test_select_combobox_commits_in_window_row_of_virtualized_button_listbox() -> None:@@ -25870,6 +25899,561 @@ async def _run_generated_popup_shape(browser: Any, shape: dict[str, str]) -> lisreturn [f"{shape}: {f} -- {r.content[:300]}" for f in failures]+_COMMIT_STATE_VOCAB = ["Canada", "Cape Verde", "Chile", "China", "Colombia", "Denmark", "France"]+++def _generated_commit_state_widget_html(shape: dict[str, str]) -> str:+ # One field in a form beside an unrelated input, a SIBLING field with its own label, and an empty block+ # below the field. `path` is a typeahead input or a click-to-open anchor; `surface` is where a commit shows+ # (the input's value, a painted single-value node, a removable chip button, the label's own value line, or+ # the anchor's text). `extra` pre-holds the value, writes the pick into the sibling instead, renders a+ # dependent sub-form below the field on commit, answers an absent value with an echo row, starts with+ # another chip, or multi-selects so the list stays open. `quickpick` puts inert suggestion buttons naming the+ # options beside the field, `neighbour_chips` a sibling chip group with no field control of its own, and+ # `filter_popup_dead` a list whose row click is dead and re-renders the list with its own filter box+ # (`_split` also splits each row's text across a checkbox and highlight markup; `_inline` does that in a+ # list laid out in the page's flow; `_div_inline` renders it as roleless divs with no checkbox). `mirror`+ # copies each keystroke into a hidden input beside the field. `held_open` holds the value with the+ # field's list already open, and `controlled_chip_popup` opens it before the call as a roleless list the field+ # names in aria-controls (`_bare`: names nowhere), each row shaped like a chip with its own dismiss control.+ # `disabled_exact` greys out the exact row beside a longer one, `toggle_async` deselects a held chip a beat after the click, and+ # `short_open_text` / `short_misroute` show only a leading clause that several options share.+ # The widget's committed truth is body[data-committed].+ return f"""+<!doctype html><html><body style="margin:0">+<form id="f" onsubmit="return false" style="position:relative;padding:20px">+ <input id="x-name" type="text" style="width:200px;height:24px">+ <div id="grp" style="position:relative;margin-top:10px">+ <label id="lbl" for="fld">Country<span id="lbl-val" style="display:block"></span></label>+ <div id="ctl" style="display:flex;gap:4px;align-items:center;min-height:30px">+ <span id="chips"></span><span id="sv" class="select__single-value"></span>+ <span id="anchor-slot"></span>+ </div>+ </div>+ <div id="dep"></div>+ <div id="sib" style="margin-top:260px">+ <label id="sib-lbl" for="sib-in">Other country<span id="sib-val" style="display:block"></span></label>+ <span id="sib-chips"></span><input id="sib-in" type="text" style="width:200px;height:24px">+ </div>+</form>+<script>+(function () {{+ var S = {json.dumps(shape)}, VOCAB = {json.dumps(_COMMIT_STATE_VOCAB)};+ var TYPE = S.path === 'typeahead', DECL = S.declared === 'yes', EXP = S.aria === 'expanded';+ var MULTI = S.surface === 'chip' || S.extra === 'left_open';+ var OPEN_TEXT = '';+ // The short_* extras show only the committed row's leading clause on the anchor ("Riverton").+ var SHORT = S.extra.indexOf('short') === 0, shown = S.extra === 'short_unchanged' ? 'Riverton' : 'Make a selection';+ if (SHORT) VOCAB = ['Riverdale, North Province', 'Riverton, Riverdale County', 'Rivers, South Province'];+ if (S.extra.indexOf('short_open_text') === 0) VOCAB = ['Riverdale, North Province', 'Riverton, Riverdale County'];+ if (S.extra === 'short_misroute') VOCAB = ['Riverton, Riverdale County', 'Riverton, South Province'];+ if (S.extra.indexOf('disabled_exact') === 0) VOCAB = ['Canada', S.near, 'Chile'];+ var DEAD_POPUP = S.extra.indexOf('filter_popup_dead') === 0;+ var slot = document.getElementById('anchor-slot'), grp = document.getElementById('grp');+ var chips = document.getElementById('chips'), sv = document.getElementById('sv');+ var lblVal = document.getElementById('lbl-val'), list = null, field, cbLabel = null, truth = [];+ window.__rowClicks = 0;+ window.__escapes = 0;+ if (TYPE) {{+ field = document.createElement('input');+ field.type = 'text';+ field.autocomplete = 'off';+ field.style.cssText = 'width:200px;height:24px';+ }} else {{+ field = document.createElement('div');+ field.tabIndex = 0;+ field.style.cssText = 'width:250px;height:30px;border:1px solid #999';+ cbLabel = document.createElement('span');+ cbLabel.textContent = 'Make a selection';+ field.appendChild(cbLabel);+ }}+ field.id = 'fld';+ field.setAttribute('role', 'combobox');+ if (TYPE) field.setAttribute('aria-autocomplete', 'list');+ var CHIP_ROWS = S.extra.indexOf('controlled_chip_popup') === 0;+ if (DECL || S.extra === 'controlled_chip_popup') field.setAttribute('aria-controls', 'fld-list');+ if (EXP) field.setAttribute('aria-expanded', 'false');+ slot.appendChild(field);+ function counted(el) {{+ el.setAttribute('data-inputs', '0');+ el.addEventListener('input', function () {{+ el.setAttribute('data-inputs', String(Number(el.getAttribute('data-inputs')) + 1));+ }});+ }}+ ['x-name', 'sib-in'].forEach(function (id) {{ counted(document.getElementById(id)); }});+ if (TYPE) counted(field);+ if (S.mirror === 'yes') {{+ var mirror = document.createElement('input');+ mirror.type = 'hidden';+ document.getElementById('ctl').appendChild(mirror);+ field.addEventListener('input', function () {{ mirror.value = field.value; }});+ }}+ function sync() {{ document.body.setAttribute('data-committed', truth.join('|')); }}+ function chip(host, name) {{+ if (S.extra === 'rs_held') {{+ var mv = document.createElement('div');+ mv.className = 'select__multi-value';+ mv.innerHTML = '<div class="select__multi-value__label">' + name + '</div><div role="button" aria-label="Remove '+ + name + '" class="select__multi-value__remove"><svg width="8" height="8"><rect width="8" height="8"></rect></svg></div>';+ host.appendChild(mv);+ return;+ }}+ var b = document.createElement('button');+ b.type = 'button';+ b.className = 'tag-btn';+ var words = S.extra === 'split_chip' ? name.split(' ') : [name];+ b.appendChild(document.createTextNode(words[0]));+ if (words.length > 1) {{ var rest = document.createElement('span'); rest.textContent = ' ' + words.slice(1).join(' '); b.appendChild(rest); }}+ var sr = document.createElement('span');+ sr.style.cssText = 'position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)';+ sr.textContent = 'Dismiss';+ b.appendChild(sr);+ host.appendChild(b);+ }}+ function paint() {{+ if (S.surface === 'chip') {{ chips.innerHTML = ''; truth.forEach(function (n) {{ chip(chips, n); }}); }}+ if (S.surface === 'single') sv.textContent = truth[0] || '';+ if (S.surface === 'label') lblVal.textContent = truth[0] || '';+ if (!TYPE) cbLabel.textContent = (MULTI ? truth.length + ' selected' : SHORT ? shown : (truth[0] || 'Make a selection')) + OPEN_TEXT;+ sync();+ }}+ function close() {{+ if (list) {{ list.remove(); list = null; }}+ if (OPEN_TEXT || S.extra === 'preview_open') {{ OPEN_TEXT = ''; paint(); }}+ if (EXP) field.setAttribute('aria-expanded', 'false');+ }}+ function commit(name) {{+ window.__rowClicks++;+ if (DEAD_POPUP) {{+ setTimeout(function () {{ if (list) {{ list.remove(); list = null; render(field.value.trim().toLowerCase()); }} }}, 50);+ return;+ }}+ if (S.extra.indexOf('short_open_text') === 0) {{ close(); return; }}+ if (S.extra === 'short_misroute') {{ truth = ['Riverton, South Province']; shown = 'Riverton'; paint(); close(); return; }}+ if (S.extra === 'toggle_async') {{+ if (TYPE) field.value = '';+ close();+ setTimeout(function () {{ var at = truth.indexOf(name); if (at >= 0) truth.splice(at, 1); else truth.push(name); paint(); }}, 900);+ return;+ }}+ if (SHORT) {{+ if (S.extra === 'short') {{ truth = [name]; shown = name.split(',')[0]; }}+ if (S.extra === 'short_wrong') shown = 'Riverdale';+ if (S.extra === 'short_placeholder') shown = 'Select\u2026';+ if (S.extra === 'short_sibling') document.getElementById('sib-cb').textContent = name.split(',')[0];+ paint();+ close();+ return;+ }}+ if (S.extra === 'sibling') {{+ document.getElementById('sib-val').textContent = name;+ document.getElementById('sib-in').value = name;+ chip(document.getElementById('sib-chips'), name);+ if (TYPE) field.value = '';+ close();+ return;+ }}+ if (MULTI) {{+ var at = truth.indexOf(name);+ if (at >= 0) truth.splice(at, 1); else truth.push(name);+ }} else {{+ truth = [name];+ }}+ if (TYPE) field.value = S.surface !== 'value' ? '' : S.extra === 'decorated_open' ? name + ' (CA)' : name;+ paint();+ if (S.extra === 'dependent') {{+ document.getElementById('dep').innerHTML =+ '<div style="padding:4px"><label for="dep-in">Postal code</label><input id="dep-in" type="text"></div>';+ }}+ if (S.extra !== 'left_open' && S.extra !== 'decorated_open') close();+ else if (list) render('');+ }}+ function row(name, echo) {{+ var DIVS = DECL || S.extra === 'filter_popup_dead_div_inline';+ var r = document.createElement(DIVS ? 'div' : 'li');+ if (DECL) r.setAttribute('role', 'option');+ if (DECL || S.extra === 'left_open') r.setAttribute('aria-selected', truth.indexOf(name) >= 0 ? 'true' : 'false');+ r.style.cssText = 'height:24px;cursor:pointer';+ if (echo === 'disabled') {{ r.setAttribute('aria-disabled', 'true'); r.textContent = 'No results for ' + name; }}+ else if (echo) r.textContent = 'No results found for\\u00a0"' + name + '"';+ else if (S.extra === 'filter_popup_dead_div_inline') r.innerHTML = '<b>' + name.slice(0, 3) + '</b>' + name.slice(3);+ else if (CHIP_ROWS) {{+ r.className = 'chip';+ r.innerHTML = name + '<button type="button" aria-label="Dismiss" style="width:12px;height:12px"></button>';+ }}+ else if (S.extra.indexOf('filter_popup_dead_') === 0) {{+ r.innerHTML = '<input type="checkbox"><span><b>' + name.slice(0, 3) + '</b>' + name.slice(3) + '</span>';+ }} else r.textContent = name;+ var greyed = S.extra.indexOf('disabled_exact') === 0 && name === S.target;+ if (greyed) r.setAttribute('aria-disabled', 'true');+ r.addEventListener('click', function () {{+ if (greyed) return;+ if (echo) {{ document.body.setAttribute('data-echo-clicked', '1'); return; }}+ commit(name);+ }});+ return r;+ }}+ function render(q) {{+ if (!list) {{+ list = document.createElement(DECL || S.extra === 'filter_popup_dead_div_inline' ? 'div' : 'ul');+ list.id = 'fld-list';+ if (DECL) list.setAttribute('role', 'listbox');+ if (S.extra === 'left_open') list.setAttribute('aria-multiselectable', 'true');+ list.style.cssText = S.extra === 'filter_popup_dead_inline' || S.extra === 'filter_popup_dead_div_inline'+ ? 'list-style:none;margin:0;padding:0;width:260px;background:#fff'+ : 'list-style:none;margin:0;padding:0;position:absolute;left:0;top:64px;width:260px;background:#fff;z-index:5';+ grp.appendChild(list);+ if (EXP) field.setAttribute('aria-expanded', 'true');+ if (S.extra.indexOf('short_open_text') === 0) {{ OPEN_TEXT = ' (choose below)'; paint(); }}+ if (S.extra === 'preview_open') cbLabel.textContent = S.target;+ }}+ list.innerHTML = '';+ if (DEAD_POPUP) {{+ var filter = document.createElement('input');+ filter.placeholder = 'Filter';+ list.appendChild(filter);+ }}+ var hits = VOCAB.filter(function (n) {{ return (!q || n.toLowerCase().indexOf(q) === 0); }});+ // A fuzzy search answers the query with every near spelling it knows.+ if (q && S.near) hits = VOCAB.slice(0, 2);+ if (q && !hits.length && S.extra === 'echo') list.appendChild(row(field.value.trim(), S.echo));+ hits.forEach(function (n) {{ list.appendChild(row(n, '')); }});+ }}+ if (S.extra === 'held' || S.extra === 'held_open' || S.extra === 'left_open' || S.extra === 'toggle_async') {{+ truth = [S.target];+ }}+ if (S.extra === 'disabled_exact_held' || S.extra === 'rs_held') truth = [S.target];+ if (S.extra.indexOf('short_open_text') === 0) {{ truth = ['Riverton, South Province']; shown = 'Riverton'; }}+ if (S.extra === 'split_chip') truth = ['Canada East'];+ if (S.extra === 'preview_open') truth = ['Chile'];+ if (S.extra === 'prior_chip') truth = ['Chile'];+ if (S.extra === 'held_raw') field.value = S.target;+ if (SHORT) {{+ var sibCb = document.createElement('div');+ sibCb.id = 'sib-cb';+ sibCb.setAttribute('role', 'combobox');+ sibCb.textContent = 'Make a selection';+ document.getElementById('sib').appendChild(sibCb);+ }}+ if (S.extra === 'quickpick') {{+ var picks = document.createElement('span');+ VOCAB.slice(0, 2).forEach(function (n) {{+ var q = document.createElement('button');+ q.type = 'button';+ q.setAttribute('aria-label', 'Choose ' + n);+ q.textContent = n;+ picks.appendChild(q);+ }});+ document.getElementById('ctl').appendChild(picks);+ }}+ if (S.extra === 'caption_chip' || S.extra === 'group_chip') {{+ var removable = '<span class="chip">' + S.target + '<button type="button" aria-label="Remove"><svg width="8" height="8">'+ + '<rect width="8" height="8"></rect></svg></button></span>';+ var held = document.createElement(S.extra === 'caption_chip' ? 'span' : 'div');+ if (S.extra === 'caption_chip') held.innerHTML = '<span>Countries lived in</span>' + removable;+ else {{ held.setAttribute('role', 'group'); held.setAttribute('aria-label', 'Countries lived in'); held.innerHTML = removable; }}+ var ctl = document.getElementById('ctl');+ if (S.extra === 'caption_chip') while (held.firstChild) ctl.insertBefore(held.firstChild, slot);+ else ctl.insertBefore(held, slot);+ }}+ if (S.extra === 'neighbour_chips') {{+ var other = document.createElement('div');+ other.innerHTML = '<span>Countries lived in</span><span class="chip">' + S.target+ + '<button type="button" aria-label="Remove"><svg width="8" height="8"><rect width="8" height="8"></rect></svg>'+ + '</button></span><button type="button">Add</button>';+ grp.insertBefore(other, grp.firstChild);+ }}+ paint();+ if (TYPE) {{+ field.addEventListener('input', function () {{+ var q = field.value.trim().toLowerCase();+ if (!q) {{ close(); return; }}+ render(q);+ }});+ field.addEventListener('keydown', function (e) {{+ if ((e.key === 'Backspace' || e.key === 'Delete') && field.value === '' && MULTI && truth.length) {{+ truth.pop();+ paint();+ }}+ }});+ }} else {{+ field.addEventListener('click', function () {{ if (list) close(); else render(''); }});+ }}+ document.addEventListener('keydown', function (e) {{ if (e.key === 'Escape') {{ window.__escapes++; close(); }} }});+ if (S.extra === 'label_hint') lblVal.innerHTML = 'e.g. <b>' + S.target + '</b>';+ if (S.extra === 'held_open' || S.extra === 'short_open_text_open' || S.extra === 'preview_open' || CHIP_ROWS) render('');+}})();+</script>+</body></html>+"""+++def _generated_commit_state_shapes() -> list[dict[str, str]]:+ def shape(+ path: str,+ surface: str,+ aria: str,+ declared: str,+ extra: str,+ echo: str = "",+ tool: str = "select_combobox",+ near: str = "",+ mirror: str = "no",+ ) -> dict[str, str]:+ return {+ "family": "commit_state",+ "tool": tool,+ "near": near,+ "mirror": mirror,+ "path": path,+ "surface": surface,+ "aria": aria,+ "declared": declared,+ "extra": extra,+ "echo": echo,+ # A quoted echo shares only its inner words with the query, so the target has one.+ "target": "Riverton, Riverdale County"+ if extra.startswith("short")+ else {"quoted": "Lost City Atlantis", "disabled": "Atlantis"}.get(echo, "Canada"),+ }++ arias = ("expanded", "none")+ typed = ("value", "single", "chip", "label")+ shapes = [shape("typeahead", s, a, d, "none") for s in typed for a in arias for d in ("yes", "no")]+ shapes += [shape("typeahead", s, a, "yes", "held") for s in ("single", "chip", "label") for a in arias]+ shapes += [shape("typeahead", "value", a, d, "held_raw") for a in arias for d in ("yes", "no")]+ shapes += [shape("typeahead", s, "none", d, "sibling") for s in ("single", "chip", "label") for d in ("yes", "no")]+ shapes += [shape("typeahead", s, a, "no", "dependent") for s in ("value", "single", "label") for a in arias]+ shapes += [shape("typeahead", "value", a, "no", "echo", e) for a in arias for e in ("quoted", "disabled")]+ shapes += [shape("typeahead", "chip", a, d, "prior_chip") for a in arias for d in ("yes", "no")]+ shapes += [shape("click", "anchor", a, "yes", x) for a in arias for x in ("none", "held", "left_open")]+ shapes += [shape("click", "anchor", "none", "yes", x) for x in ("sibling", "dependent")]+ shapes += [shape("click", "anchor", a, "no", "held") for a in arias]+ shapes += [shape("typeahead", s, "none", d, "quickpick") for s in ("value", "single") for d in ("yes", "no")]+ shapes += [shape("typeahead", "value", "none", d, "neighbour_chips") for d in ("yes", "no")]+ shapes += [shape("click", "anchor", "none", "yes", x) for x in ("quickpick", "neighbour_chips")]+ # A removable chip beside the field that another field's caption or labelled group owns, and a held+ # React-Select-style chip that is the field's own.+ shapes += [+ shape("typeahead", s, "none", d, x)+ for x in ("caption_chip", "group_chip")+ for s in ("value", "single")+ for d in ("yes", "no")+ ]+ shapes += [shape("click", "anchor", "none", "yes", x) for x in ("caption_chip", "group_chip")]+ shapes += [shape("typeahead", "chip", a, d, "rs_held") for a in arias for d in ("yes", "no")]+ shapes += [shape("typeahead", "value", a, d, "filter_popup_dead") for a in arias for d in ("yes", "no")]+ shorts = ("short", "short_wrong", "short_unchanged", "short_sibling", "short_placeholder")+ shapes += [shape("click", "anchor", a, "yes", x) for a in arias for x in shorts]+ for tool in ("select_combobox", "type"):+ for x in ("filter_popup_dead_split", "filter_popup_dead_inline"):+ shapes += [shape("typeahead", "value", a, d, x, tool=tool) for a in arias for d in ("yes", "no")]+ # The exact row is greyed out beside a row one prefix, stem or extra word away from it.+ for near in ("Canada East", "Canadian", "Canad", "Upper Canada Region"):+ shapes += [shape("typeahead", "value", a, "no", "disabled_exact", tool=tool, near=near) for a in arias]+ shapes += [shape("typeahead", "chip", a, "no", "disabled_exact_held", tool=tool, near=near) for a in arias]+ shapes += [shape("typeahead", "chip", a, d, "toggle_async", tool="type") for a in arias for d in ("yes", "no")]+ shapes += [shape("typeahead", "chip", a, d, "none", tool="type") for a in arias for d in ("yes", "no")]+ shapes += [shape("click", "anchor", a, "yes", x) for a in arias for x in ("short_open_text", "short_misroute")]+ # A dead click that re-renders the popup, whatever its rows look like, with the typed query also copied+ # into a hidden input; and the real commits beside them, with and without a dependent sub-form.+ dead = ("filter_popup_dead", "filter_popup_dead_split", "filter_popup_dead_inline", "filter_popup_dead_div_inline")+ for tool in ("select_combobox", "type"):+ shapes += [+ shape("typeahead", "value", a, d, "filter_popup_dead_div_inline", tool=tool)+ for a in arias+ for d in ("yes", "no")+ ]+ shapes += [+ shape("typeahead", "value", a, d, x, tool=tool, mirror="yes")+ for x in dead+ for a in arias+ for d in ("yes", "no")+ ]+ shapes += [+ shape("typeahead", "value", a, "no", x, tool=tool, mirror="yes")+ for x in ("none", "dependent")+ for a in arias+ ]+ shapes += [+ shape("typeahead", s, a, d, "held_open")+ for s in ("chip", "label")+ for a, d in (("expanded", "no"), ("none", "yes"), ("expanded", "yes"))+ ]+ shapes += [shape("click", "anchor", a, "yes", "held_open") for a in arias]+ # A label hint naming the value beside an empty field, a held chip whose text only starts with it, and an+ # already-open list whose open state nothing declares.+ shapes += [+ shape("typeahead", s, a, d, "label_hint") for s in ("value", "single") for a in arias for d in ("yes", "no")+ ]+ shapes += [shape("typeahead", "chip", a, d, "split_chip") for a in arias for d in ("yes", "no")]+ shapes += [shape("click", "anchor", "none", "no", "short_open_text_open")]+ # An open list whose anchor previews the highlighted row, and a commit that writes the row's text plus a+ # code while its list stays on screen.+ shapes += [shape("click", "anchor", a, d, "preview_open") for a in arias for d in ("yes", "no")]+ shapes += [shape("typeahead", "value", a, "yes", "decorated_open") for a in arias]+ shapes += [+ shape("typeahead", "value", "none", "no", x) for x in ("controlled_chip_popup", "controlled_chip_popup_bare")+ ]+ return shapes+++async def _run_generated_commit_state_shape(browser: Any, shape: dict[str, str]) -> list[str]:+ target = shape["target"]+ context = await browser.new_context(viewport={"width": 1024, "height": 900})+ try:+ page = await context.new_page()+ await page.set_content(_generated_commit_state_widget_html(shape))+ tools = build_browser_tools(_fixed_page_provider(page))+ if shape["tool"] == "type":+ r = await _tool(tools, "type").handler({"selector": "#fld", "text": target})+ await asyncio.sleep(1.2)+ else:+ r = await _tool(tools, "select_combobox").handler({"selector": "#fld", "value": target})+ state = await page.evaluate(+ """() => ({+ committed: document.body.getAttribute('data-committed') || '',+ rowClicks: window.__rowClicks,+ escapes: window.__escapes,+ fieldInputs: Number(document.getElementById('fld').getAttribute('data-inputs') || 0),+ echoClicked: document.body.hasAttribute('data-echo-clicked'),+ listShown: !!document.getElementById('fld-list'),+ outside: ['x-name', 'sib-in'].map((id) => [id, document.getElementById(id).getAttribute('data-inputs')]),+ xName: document.getElementById('x-name').value,+ })"""+ )+ finally:+ await context.close()+ held = [v for v in state["committed"].split("|") if v]+ before = {+ "held": [target],+ "held_open": [target],+ "left_open": [target],+ "prior_chip": ["Chile"],+ "disabled_exact_held": [target],+ "rs_held": [target],+ "toggle_async": [target],+ "short_open_text": ["Riverton, South Province"],+ "short_open_text_open": ["Riverton, South Province"],+ "split_chip": ["Canada East"],+ }.get(shape["extra"], [])+ failures = []+ if r.status == "ok" and target not in held:+ failures.append(f"(a) ok but the field holds {held!r}")+ # `short_misroute` is the widget committing another row than the one clicked; only (a) judges it.+ misroute = shape["extra"] == "short_misroute"+ if not misroute and r.status != "ok" and held != before and not all(v in r.content for v in held):+ failures.append(f"(b) field changed to {held!r} unnamed")+ failures += [f"(c) outside #{i} inputs={n}" for i, n in state["outside"] if n != "0"]+ if state["xName"]:+ failures.append("(c) outside #x-name holds text")+ # Only a toggle field (its values shown as removable chips) with its list known closed (aria-expanded="false")+ # skips a held value. A single-value field re-picks it and may then be refused when the click changes nothing it+ # shows; an anchor that already showed the value in an open list's preview cannot vouch for the click either. A+ # held chip whose list is open or undeclared is clicked too, and the click that removes it is reported as not+ # committed.+ single_held = shape["extra"] in ("held", "held_open") and shape["surface"] != "chip"+ open_toggle = shape["surface"] == "chip" and (+ shape["extra"] == "held_open" or (shape["extra"] in ("held", "rs_held") and shape["aria"] != "expanded")+ )+ weak_held = single_held or shape["extra"] == "preview_open"+ # A click-to-open list marks the held row aria-selected, which main already reads as selected.+ if shape["extra"] == "held" and single_held and shape["path"] == "typeahead" and not state["rowClicks"]:+ failures.append("(l) a single-value field skipped the re-pick")+ if open_toggle and not state["rowClicks"]:+ failures.append("(l) a held chip with its list open or undeclared was not re-picked")+ if (+ shape["extra"] in ("held", "left_open", "rs_held")+ and not single_held+ and not open_toggle+ and (state["rowClicks"] or state["fieldInputs"])+ ):+ failures.append(f"(f) re-pick acted: {state['rowClicks']} row clicks, {state['fieldInputs']} inputs")+ if shape["extra"] == "held" and not single_held and not open_toggle and state["escapes"]:+ failures.append(f"(k) pressed Escape {state['escapes']} times on a held field with no list open")+ # A type() click on a held chip's row toggles it off; this row judges only what the tool reported.+ if shape["extra"] != "toggle_async" and not open_toggle and any(v not in held for v in before):+ failures.append(f"(g) a value the field held before was removed: {held!r}")+ if not misroute and any(v not in before and v != target for v in held):+ failures.append(f"(j) committed a row other than the target: {held!r}")+ if state["echoClicked"]:+ failures.append("(h) clicked the empty-state row that echoes the query")+ if r.status == "ok" and state["listShown"]:+ failures.append("(i) ok but the field's own list was left open")+ # A plain input that shows only the text the tool typed has no committed state of its own, and once the+ # page renders anything new beside it that cannot be told from a dead click, so it is refused.+ echo_beside_new_content = shape["extra"] == "dependent" and shape["surface"] == "value"+ expects_ok = shape["extra"] in ("short",) or not (+ open_toggle+ or shape["extra"] in ("sibling", "echo", "disabled_exact", "toggle_async", "disabled_exact_held")+ or shape["extra"].startswith(("short", "filter_popup_dead"))+ or echo_beside_new_content+ )+ if expects_ok and not weak_held and r.status != "ok":+ failures.append("coverage: expected a commit")+ if not expects_ok and r.status == "ok" and shape["extra"] not in ("toggle_async", "disabled_exact_held"):+ failures.append("reported ok for a pick the field never took")+ return [f"{shape}: {f} -- {r.content[:300]}" for f in failures]+++@_skip_no_browser+async def test_select_combobox_holds_nothing_on_a_label_hint_or_a_partial_chip() -> None:+ """The pre-act "already holds" no-op applies only to a toggle field with its list known closed: a label hint, an+ open list's anchor preview, a chip that only starts with the value, a held single value, or a chip-shaped row of+ an open roleless popup, declared or not, does not skip the fill, while an exact chip on a closed field still does.+ A list whose open state nothing declares never lends its anchor text as the pre-click baseline. A commit that+ writes the chosen row plus a code counts with its list still open; the typed text left behind by a dead click+ does not."""+ from playwright.async_api import async_playwright # noqa: PLC0415++ shapes = [+ s+ for s in _generated_commit_state_shapes()+ if s["extra"]+ in (+ "label_hint",+ "split_chip",+ "short_open_text_open",+ "preview_open",+ "decorated_open",+ "controlled_chip_popup",+ "controlled_chip_popup_bare",+ )+ or (s["extra"] == "held" and s["surface"] in ("single", "chip"))+ or (s["extra"] == "filter_popup_dead" and s["tool"] == "select_combobox")+ ]+ async with async_playwright() as pw:+ browser = await pw.chromium.launch(headless=True, args=["--use-mock-keychain", "--password-store=basic"])+ try:+ results = await asyncio.gather(*(_run_generated_commit_state_shape(browser, s) for s in shapes))+ finally:+ await browser.close()+ failures = [f for r in results for f in r]+ assert len(shapes) == 33+ assert not failures, "\n".join(failures)+++@_skip_no_browser+async def test_select_combobox_acts_past_a_chip_it_cannot_prove_is_its_own() -> None:+ """A removable chip under another field's caption or labelled group, laid out in the field's own wrapper, does+ not make a re-pick a no-op: the field is filled and verified. A React-Select-style chip the field owns still is+ when the field declares its list closed."""+ from playwright.async_api import async_playwright # noqa: PLC0415++ shapes = [s for s in _generated_commit_state_shapes() if s["extra"] in ("caption_chip", "group_chip", "rs_held")]+ async with async_playwright() as pw:+ browser = await pw.chromium.launch(headless=True, args=["--use-mock-keychain", "--password-store=basic"])+ try:+ results = await asyncio.gather(*(_run_generated_commit_state_shape(browser, s) for s in shapes))+ finally:+ await browser.close()+ failures = [f for r in results for f in r]+ assert len(shapes) == 14+ assert not failures, "\n".join(failures)++@_skip_no_browser@pytest.mark.asyncioasync def test_select_combobox_popup_filter_property_over_generated_widget_shapes() -> None:@@ -25882,10 +26466,15 @@ async def test_select_combobox_popup_filter_property_over_generated_widget_shapereceived input; (d) a changed field is never called NOT filled; (e) the refusal claims the list's searchbox answered only when a filter box was typed into. A field behind a key sink that swallows keys must stayunchanged: the first typed character never lands there, so nothing more is typed.++ The commit-state shapes judge a commit by what the field itself holds. Beyond (a)-(c): (f) re-picking a+ chip a toggle field holds with its list known closed neither types nor clicks, while (l) a single-value field re-picks;+ (g) nothing the field held before is removed; (h) an empty-state row echoing the query is never clicked; (i) an+ ok leaves the field's own list closed."""from playwright.async_api import async_playwright # noqa: PLC0415- shapes = _generated_popup_shapes()+ shapes = _generated_popup_shapes() + _generated_commit_state_shapes()gate = asyncio.Semaphore(6)async with async_playwright() as pw:browser = await pw.chromium.launch(headless=True, args=["--use-mock-keychain", "--password-store=basic"])@@ -25893,13 +26482,15 @@ async def test_select_combobox_popup_filter_property_over_generated_widget_shapeasync def _one(shape: dict[str, str]) -> list[str]:async with gate:+ if shape.get("family") == "commit_state":+ return await _run_generated_commit_state_shape(browser, shape)return await _run_generated_popup_shape(browser, shape)results = await asyncio.gather(*(_one(s) for s in shapes))finally:await browser.close()failures = [f for r in results for f in r]- assert len(shapes) >= 101+ assert len(shapes) >= 295assert not failures, "\n".join(failures)@@ -29427,6 +30018,66 @@ async def test_select_combobox_does_not_toggle_off_an_already_selected_multi_selassert label == "Countries: Germany", label+@_skip_no_browser[email protected]("closed_by", ["aria_expanded_false", "hidden_declared_popup"])+async def test_select_combobox_leaves_a_held_chip_only_when_its_list_is_known_closed(closed_by: str) -> None:+ # A held chip is left as is only when the field's own list is known closed: aria-expanded="false" on the field,+ # or the popup it declares exists and is hidden.+ aria = "expanded" if closed_by == "aria_expanded_false" else "none"+ shape = next(+ s+ for s in _generated_commit_state_shapes()+ if (s["path"], s["extra"], s["surface"], s["aria"], s["declared"]) == ("typeahead", "held", "chip", aria, "yes")+ )+ html = _generated_commit_state_widget_html(shape)+ if closed_by == "hidden_declared_popup":+ html = html.replace('<div id="dep">', '<div id="fld-list" role="listbox" hidden></div><div id="dep">', 1)+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "select_combobox").handler({"selector": "#fld", "value": shape["target"]})+ state = await page.evaluate(+ "() => [document.body.getAttribute('data-committed'), window.__rowClicks,"+ " Number(document.getElementById('fld').getAttribute('data-inputs'))]"+ )+ assert r.status == "ok" and "already selected" in r.content, r.content+ assert state == [shape["target"], 0, 0], state+++@_skip_no_browser+async def test_select_combobox_already_held_chip_inside_an_expanded_accordion() -> None:+ # The held field sits in an expanded accordion that collapses on any Escape. Nothing declares the field's own list+ # closed, so the re-pick acts as on main; it reports only what the field holds and leaves the accordion open.+ shape = next(+ s+ for s in _generated_commit_state_shapes()+ if (s["path"], s["extra"], s["surface"], s["aria"], s["declared"])+ == ("typeahead", "held", "chip", "none", "yes")+ )+ html = _generated_commit_state_widget_html(shape)+ html = html.replace('<div id="grp"', '<div id="acc" role="region" aria-expanded="true"><div id="grp"', 1)+ html = html.replace('<div id="dep">', '</div><div id="dep">', 1)+ html = html.replace(+ "</body>",+ "<script>window.__docEscapes = 0; document.addEventListener('keydown', function (e) { if (e.key === 'Escape') "+ "{ window.__docEscapes++; document.getElementById('acc').setAttribute('aria-expanded', 'false'); } }, true);"+ "</script></body>",+ 1,+ )+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "select_combobox").handler({"selector": "#fld", "value": shape["target"]})+ state = await page.evaluate(+ "() => [document.body.getAttribute('data-committed'), window.__docEscapes, window.__rowClicks,"+ " document.getElementById('acc').getAttribute('aria-expanded')]"+ )+ committed, escapes, row_clicks, acc_expanded = state+ assert "already selected" not in r.content and row_clicks == 1, (r.content, state)+ assert r.status != "ok" or committed == shape["target"], (r.content, state)+ assert escapes == 0 and acc_expanded == "true", state++@_skip_no_browser@pytest.mark.asyncioasync def test_select_combobox_verifies_a_comma_bearing_label_off_the_trigger() -> None:@@ -36480,6 +37131,8 @@ async def test_click_toggle_probe_matches_the_toggle_state_observe_prints() -> Nassert await probe({"selector": "#loose"}) is True+_CC_COUNTRIES_NO_EXACT_US = [c for c in _CC_COUNTRIES if c[0] != "United States"]+_TEXT_DELTA_HEADER = "page newly shows (since your previous tool call): "_TEXT_DELTA_HEADER_RE = re.compile(r"page newly shows \((?:since your previous tool call|over your last \d+ tool calls)\): "@@ -36680,6 +37333,45 @@ def _m4_generated_cases(seed: int, draws: int) -> list[tuple[str, str, str, str]return cases # type: ignore[return-value]+@_skip_no_browser+ ("setsize_js", "commits"),+ [+ pytest.param("'-1'", False, id="unknown_every_row"),+ pytest.param("(i < 38 || i > 42) ? '-1' : ''", False, id="unknown_off_open_window"),+ pytest.param(f"'{len(_CC_COUNTRIES_NO_EXACT_US)}'", True, id="declared_total_equals_rows"),+ ],+)+async def test_select_combobox_prefix_hit_after_a_full_walk_obeys_the_walked_rows_setsize(+ setsize_js: str, commits: bool+) -> None:+ # aria-setsize="-1" on ANY walked row says the rows are not the whole list, so the lone prefix row+ # "United States Minor Outlying Islands" must not commit for "United States" -- including when the open+ # window (rows 38..42) declares no size. A declared total equal to the rows walked is complete: it commits.+ html = _cc_widget_html(_CC_COUNTRIES_NO_EXACT_US, _CC_CURRENT_INDEX)+ marked = html.replace(+ "'\" id=\"item-' + i + '\"",+ "'\"' + (("+ + setsize_js+ + ") ? ' aria-setsize=\"' + ("+ + setsize_js+ + ") + '\"' : '') + ' id=\"item-' + i + '\"",+ )+ assert marked != html+ async with _content_page(marked) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ pre_label = await page.eval_on_selector("#cc", "el => el.getAttribute('aria-label')")+ r = await _tool(tools, "select_combobox").handler({"selector": "#cc", "value": "United States"})+ label = await page.eval_on_selector("#cc", "el => el.getAttribute('aria-label')")+ if commits:+ assert r.status == "ok", r.content+ assert label.endswith("United States Minor Outlying Islands"), label+ else:+ assert r.status == "error", r.content+ assert label == pre_label, label++@_skip_no_browser@pytest.mark.asyncioasync def test_text_delta_reports_each_inserted_line_exactly_once_in_the_first_result_after_it_rendered(@@ -37379,6 +38071,34 @@ async def test_child_frame_text_past_the_char_bound_is_refused_in_the_frame(monkassert taskv3_loop._TEXT_DELTA.get() == (0.0, None, 0, True, "over_bound", 0)+@_skip_no_browser+ ("setsize", "commits"),+ [+ pytest.param(None, True, id="no_setsize_collapses"),+ pytest.param("-1", False, id="total_unknown_refuses"),+ ],+)+async def test_select_combobox_collapses_twice_rendered_suggestion_only_over_a_complete_list(+ setsize: str | None, commits: bool+) -> None:+ # Two identical rows are one candidate rendered twice only when they are the whole list; rows declaring+ # aria-setsize="-1" are never the whole list, so a same-label option may sit unrendered.+ attrs = [{"aria-setsize": setsize}, {"aria-setsize": setsize}] if setsize else None+ async with _content_page(_duplicate_suggestion_html(_DUPLICATE_STREET_ROWS, attrs=attrs)) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "select_combobox").handler({"selector": "#addr", "value": "123 Maple Court"})+ clicked_index = await page.evaluate("() => window.__clicked_row_index")+ if commits:+ assert r.status == "ok", r.content+ assert clicked_index == 0, clicked_index+ else:+ assert r.status == "error", r.content+ assert clicked_index is None, clicked_index+ assert "declares its total unknown" in r.content, r.content++@_skip_no_browser@pytest.mark.asyncioasync def test_a_refused_call_neither_reports_nor_reads_so_the_next_call_reports_across_it() -> None:@@ -37911,6 +38631,22 @@ async def test_an_action_on_a_working_tab_reopened_after_loss_reports_what_it_shassert _delta_lines(result) == ["Row loaded"], result.content+@_skip_no_browser+async def test_select_combobox_names_exact_twins_the_walk_saw_and_routes_to_a_click() -> None:+ # The walk sees two "Congo" rows at different positions; text alone cannot separate them, so the error+ # must say so and route to a click rather than ask for a fuller text that does not exist.+ items = [("Congo", "CG-1"), *_POPUP_SEARCH_STATES[:19], ("Congo", "CG-2"), *_POPUP_SEARCH_STATES[19:30]]+ html = _popup_search_combobox_html(items=items, setsize=True, filtered_window=1, values=True)+ async with _content_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "select_combobox").handler({"selector": "#state", "value": "Congo"})+ assert r.status == "error", r.content+ assert "2 options share the exact label 'Congo'" in r.content, r.content+ assert "look()" in r.content and "data-tv3-menu" in r.content, r.content+ assert await page.eval_on_selector("#state-value", "el => el.value") == "", r.content++@_skip_no_browser@pytest.mark.asyncioasync def test_the_pending_read_that_finds_a_document_past_the_bound_is_timed_and_not_counted_as_a_skip(diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.pyindex ddee6889b..c4b730d1b 100644--- a/tests/unit/workflow/test_code_block_recorder.py+++ b/tests/unit/workflow/test_code_block_recorder.py@@ -3064,7 +3064,7 @@ async def test_inline_timeout_snapshot_masks_before_bounding_and_uses_exact_locamonkeypatch.setattr(block_module.app,"AGENT_FUNCTION",- SimpleNamespace(redact_codeblock_parameter_values=lambda value, _parameters: value),+ SimpleNamespace(redact_codeblock_parameter_values=lambda value, _parameters, **_budget: value),)context = SimpleNamespace(mask_secrets_in_data=lambda value: value.replace(secret, "*****"))block = _make_code_block("pass")diff --git a/tests/unit/workflow/test_execute_single_block_phases.py b/tests/unit/workflow/test_execute_single_block_phases.pyindex 4c81b937f..c12950377 100644--- a/tests/unit/workflow/test_execute_single_block_phases.py+++ b/tests/unit/workflow/test_execute_single_block_phases.py@@ -17,6 +17,7 @@ from typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest+from structlog.testing import capture_logsfrom skyvern.forge import appfrom skyvern.forge.sdk.db.enums import BrowserSeedSource@@ -130,7 +131,7 @@ def _script_block(label: str, run_signature: str, requires_agent: bool = False))-def _completed_result(block: NavigationBlock | LoginBlock | ConditionalBlock) -> BlockResult:+def _completed_result(block: NavigationBlock | LoginBlock | ConditionalBlock | ForLoopBlock) -> BlockResult:return BlockResult(success=True,output_parameter=block.output_parameter,@@ -141,7 +142,7 @@ def _completed_result(block: NavigationBlock | LoginBlock | ConditionalBlock) ->async def _run_single_block(service: WorkflowService,- block: NavigationBlock | LoginBlock | ConditionalBlock,+ block: NavigationBlock | LoginBlock | ConditionalBlock | ForLoopBlock,*,workflow: MagicMock | None = None,workflow_run: MagicMock | None = None,@@ -758,6 +759,72 @@ async def test_script_success_skips_agent_execution(monkeypatch: pytest.MonkeyPaassert should_stop is False+def _loop_holding_a_conditional() -> ForLoopBlock:+ conditional = ConditionalBlock(+ label="cond",+ output_parameter=_output_parameter("cond_output"),+ branch_conditions=[+ BranchCondition(criteria=JinjaBranchCriteria(expression="{{ current_value }}"), next_block_label="nav_a"),+ BranchCondition(is_default=True, next_block_label="nav_b"),+ ],+ )+ return ForLoopBlock(+ label="loop",+ output_parameter=_output_parameter("loop_output"),+ loop_blocks=[conditional, _navigation_block("nav_a"), _navigation_block("nav_b")],+ )+++async def _run_cached_loop_holding_a_conditional(monkeypatch: pytest.MonkeyPatch) -> tuple[list[str], AsyncMock, set]:+ """Script run of a loop whose script and executed branch are already cached; nav_b never ran."""+ block = _loop_holding_a_conditional()+ script_calls: list[str] = []+ execute_safe = AsyncMock(return_value=_completed_result(block))+ monkeypatch.setattr(ForLoopBlock, "execute_safe", execute_safe)+ # Only reached if the cached script runs and fails; stubbed so that regression fails on the assertions.+ monkeypatch.setattr(WorkflowService, "mark_workflow_run_as_failed_if_not_final", AsyncMock())++ _, blocks_to_update, _, _, _ = await _run_single_block(+ WorkflowService(),+ block,+ workflow_run=_workflow_run(ai_fallback=False),+ is_script_run=True,+ script_blocks_by_label={+ "loop": _script_block("loop", "record_dispatch()"),+ "nav_a": _script_block("nav_a", "record_dispatch()"),+ },+ loaded_script_module=SimpleNamespace(record_dispatch=lambda: script_calls.append("called")),+ )+ return script_calls, execute_safe, blocks_to_update+++async def test_cached_loop_holding_a_conditional_runs_through_the_engine(monkeypatch: pytest.MonkeyPatch) -> None:+ script_calls, execute_safe, _ = await _run_cached_loop_holding_a_conditional(monkeypatch)++ assert script_calls == []+ execute_safe.assert_awaited_once()+++async def test_engine_only_loop_logs_which_child_kept_it_off_the_cache(monkeypatch: pytest.MonkeyPatch) -> None:+ with capture_logs() as logs:+ await _run_cached_loop_holding_a_conditional(monkeypatch)++ [mode_resolved] = [log for log in logs if log["event"] == "Block execution mode resolved"]+ assert mode_resolved["execution_mode"] == "ai"+ assert mode_resolved["engine_only_child_types"] == ["conditional"]+++async def test_engine_only_loop_does_not_queue_its_children_for_regeneration(monkeypatch: pytest.MonkeyPatch) -> None:+ # nav_b sits on a branch that did not run, so codegen has no actions to mint it from:+ # queueing it would regenerate the script on every run.+ _, _, blocks_to_update = await _run_cached_loop_holding_a_conditional(monkeypatch)++ assert blocks_to_update == set()++@pytest.mark.asyncioasync def test_conditional_block_returns_branch_metadata(monkeypatch: pytest.MonkeyPatch) -> None:service = WorkflowService()