Skip to content

Automate browser based workflows with AI

Skip same-process sandboxed iframes when clearing session storage on raw-CDP (SKY-16341) (#8592)

Andrew Neilsonedb26e152991
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 9ce62d794..ce49039e0 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -11313,17 +11313,6 @@
},
"CodeBlockStep": {
"properties": {
- "title": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "Title"
- },
"description": {
"anyOf": [
{
@@ -11367,17 +11356,6 @@
},
"CodeBlockStepYAML": {
"properties": {
- "title": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "Title"
- },
"description": {
"anyOf": [
{
@@ -11529,7 +11507,7 @@
}
],
"title": "Steps",
- "description": "Plain-language step outline mapped to code line ranges; derived from the code when omitted"
+ "description": "Plain-language step outline mapped to code line ranges; always rebuilt from the code on save, so any value sent is ignored"
}
},
"type": "object",
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockEditor.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockEditor.test.tsx
index 856e2923b..5e932173c 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockEditor.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockEditor.test.tsx
@@ -596,12 +596,12 @@ describe("CodeBlockEditor for a block without a goal", () => {
expect(screen.getByText(/No steps yet/)).toBeTruthy();
});
- test("opens on the steps when a goal-less block carries an outline", () => {
+ test("opens on the code even when a goal-less block carries derived steps", () => {
node.data = { ...baseData, steps: codeFirstData.steps! };
renderEditor();
- expect(screen.getByText("Open the page")).toBeTruthy();
- expect(screen.queryByTestId("code-editor")).toBeNull();
+ expect(screen.getByTestId("code-editor")).toBeTruthy();
+ expect(screen.queryByTitle("Open the page")).toBeNull();
});
test("treats a block missing the goal field entirely the same as null", () => {
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockEditor.tsx
index 6cbccb1a7..cef70b07a 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockEditor.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockEditor.tsx
@@ -69,10 +69,9 @@ function CodeBlockEditorBody({
const update = useUpdate<CodeBlockNodeData>({ id: blockId, editable });
const scopeReadOnly = useWorkflowScopeReadOnly();
const steps = data.steps ?? [];
- // A block with neither a goal nor a generated outline is hand-written, so open
- // it on its code rather than on an empty Steps card.
+ // Steps are derived from any saved code, so only a goal marks a block as code-first.
const [view, setView] = useState<CodeBlockView>(
- data.prompt == null && steps.length === 0 ? "code" : "plain",
+ data.prompt == null ? "code" : "plain",
);
const [stepsOpen, setStepsOpen] = useState(true);
const [activeStepIndex, setActiveStepIndex] = useState<number | null>(null);
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockNode.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockNode.tsx
index 773131365..1f8b52bb2 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockNode.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockNode.tsx
@@ -20,10 +20,7 @@ function CodeBlockNode({ id, data }: NodeProps<CodeBlockNode>) {
const { data: workflowRun } = useWorkflowRunQuery();
const recordingStore = useRecordingStore();
const { open } = useCollapseContext();
- const blockTitle = getCodeBlockTitle({
- prompt: data.prompt,
- steps: data.steps,
- });
+ const blockTitle = getCodeBlockTitle({ prompt: data.prompt });
const workflowRunIsRunningOrQueued =
workflowRun && statusIsRunningOrQueued(workflowRun);
const thisBlockIsTargetted =
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockPlainCard.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockPlainCard.test.tsx
index b3f061d37..717d99107 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockPlainCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/CodeBlockNode/CodeBlockPlainCard.test.tsx
@@ -29,7 +29,7 @@ describe("CodeBlockPlainCard", () => {
it("uses a singular label for a single step", () => {
render(
<CodeBlockPlainCard
- steps={[{ action_type: "extract", title: "Summarize the page" }]}
+ steps={[{ action_type: "extract", description: "Summarize the page" }]}
/>,
);
@@ -79,7 +79,7 @@ describe("CodeBlockPlainCard", () => {
expect(screen.getByText("Go Forward")).toBeDefined();
});
- it("falls back to the readable action type for the step text when title and description are absent", () => {
+ it("falls back to the readable action type for the step text when the description is absent", () => {
const steps: Array<CodeBlockStep> = [
{ action_type: "extract", line_start: 1, line_end: 1 },
];
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/types.test.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/types.test.ts
index bdd4bf6cd..a005e823a 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/types.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/types.test.ts
@@ -3,35 +3,22 @@ import { describe, expect, it } from "vitest";
import { CODE_BLOCK_TITLE_MAX_LENGTH, getCodeBlockTitle } from "./types";
describe("getCodeBlockTitle", () => {
- it("prefers a normalized prompt over the first step title", () => {
+ it("uses the normalized prompt", () => {
expect(
getCodeBlockTitle({
prompt: " Collect\ninvoice details ",
- steps: [{ title: "Run a script" }],
}),
).toBe("Collect invoice details");
});
- it("falls back to the first step title and then Code", () => {
- expect(
- getCodeBlockTitle({
- prompt: null,
- steps: [{ title: "Summarize the page" }],
- }),
- ).toBe("Summarize the page");
-
- expect(
- getCodeBlockTitle({
- prompt: " ",
- steps: [{ title: null }],
- }),
- ).toBe("Code");
+ it("falls back to Code without a prompt", () => {
+ expect(getCodeBlockTitle({ prompt: null })).toBe("Code");
+ expect(getCodeBlockTitle({ prompt: " " })).toBe("Code");
});
it("truncates long titles", () => {
const title = getCodeBlockTitle({
prompt: "a".repeat(CODE_BLOCK_TITLE_MAX_LENGTH + 20),
- steps: null,
});
expect(title).toHaveLength(CODE_BLOCK_TITLE_MAX_LENGTH);
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts
index d59b9f530..fb940a917 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts
@@ -62,9 +62,7 @@ function truncateTitle(value: string): string {
export function getCodeBlockTitle(source: CodeBlockTitleSource): string {
return truncateTitle(
- normalizeTitle(source.prompt) ??
- normalizeTitle(source.steps?.[0]?.title) ??
- CODE_BLOCK_FALLBACK_TITLE,
+ normalizeTitle(source.prompt) ?? CODE_BLOCK_FALLBACK_TITLE,
);
}
diff --git a/skyvern-frontend/src/routes/workflows/types/scriptTypes.ts b/skyvern-frontend/src/routes/workflows/types/scriptTypes.ts
index 0b99630a4..527222773 100644
--- a/skyvern-frontend/src/routes/workflows/types/scriptTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/scriptTypes.ts
@@ -1,8 +1,5 @@
-import type { CodeBlockStep } from "./workflowTypes";
-
export type CodeBlockTitleSource = {
prompt?: string | null;
- steps?: Array<Pick<CodeBlockStep, "title">> | null;
};
export type ScriptBlocksResponse = {
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
index b3964c493..951e5a0b5 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
@@ -394,7 +394,6 @@ export type WhileLoopBlock = WorkflowBlockBase & {
};
export type CodeBlockStep = {
- title?: string | null;
description?: string | null;
action_type: string;
line_start?: number | null;
diff --git a/skyvern-frontend/src/routes/workflows/workflowBlockUtils.test.ts b/skyvern-frontend/src/routes/workflows/workflowBlockUtils.test.ts
index aa71a56c7..73140ecfa 100644
--- a/skyvern-frontend/src/routes/workflows/workflowBlockUtils.test.ts
+++ b/skyvern-frontend/src/routes/workflows/workflowBlockUtils.test.ts
@@ -49,7 +49,12 @@ function forLoop(
describe("buildCodeStepsByLabel", () => {
it("maps code block labels to their step outline", () => {
const steps: Array<CodeBlockStep> = [
- { action_type: "goto", title: "Open page", line_start: 1, line_end: 1 },
+ {
+ action_type: "goto",
+ description: "Open page",
+ line_start: 1,
+ line_end: 1,
+ },
];
const map = buildCodeStepsByLabel([codeBlock("run_script", steps)]);
expect(map.get("run_script")).toEqual(steps);
@@ -156,17 +161,7 @@ describe("visitWorkflowBlocks", () => {
});
describe("getCodeStepPlainText", () => {
- it("prefers the step title", () => {
- expect(
- getCodeStepPlainText({
- action_type: "extract",
- title: "Extract the product details",
- description: "page.extract",
- }),
- ).toBe("Extract the product details");
- });
-
- it("falls back to the description when there is no title", () => {
+ it("uses the description", () => {
expect(
getCodeStepPlainText({
action_type: "click",
@@ -175,7 +170,7 @@ describe("getCodeStepPlainText", () => {
).toBe("Click submit");
});
- it("humanizes the action type when title and description are absent", () => {
+ it("humanizes the action type when the description is absent", () => {
expect(getCodeStepPlainText({ action_type: "extract" })).toBe(
"Extract Data",
);
@@ -184,12 +179,11 @@ describe("getCodeStepPlainText", () => {
);
});
- it("ignores blank title and description", () => {
+ it("ignores a blank description", () => {
expect(
getCodeStepPlainText({
action_type: "extract",
- title: " ",
- description: "",
+ description: " ",
}),
).toBe("Extract Data");
});
@@ -197,9 +191,14 @@ describe("getCodeStepPlainText", () => {
describe("findCodeStepForLine", () => {
const steps: Array<CodeBlockStep> = [
- { action_type: "goto", title: "Open page", line_start: 1, line_end: 1 },
- { action_type: "click", title: "Submit", line_start: 3, line_end: 6 },
- { action_type: "extract", title: "No line position" },
+ {
+ action_type: "goto",
+ description: "Open page",
+ line_start: 1,
+ line_end: 1,
+ },
+ { action_type: "click", description: "Submit", line_start: 3, line_end: 6 },
+ { action_type: "extract", description: "No line position" },
];
it("returns null when the action carries no code line", () => {
@@ -207,19 +206,29 @@ describe("findCodeStepForLine", () => {
});
it("matches a step by exact line_start", () => {
- expect(findCodeStepForLine(steps, 1)?.title).toBe("Open page");
+ expect(findCodeStepForLine(steps, 1)?.description).toBe("Open page");
});
it("matches a step by range containment when no exact line_start matches", () => {
- expect(findCodeStepForLine(steps, 4)?.title).toBe("Submit");
+ expect(findCodeStepForLine(steps, 4)?.description).toBe("Submit");
});
it("prefers an exact line_start over a containing range", () => {
const overlapping: Array<CodeBlockStep> = [
- { action_type: "click", title: "Range", line_start: 1, line_end: 5 },
- { action_type: "extract", title: "Exact", line_start: 3, line_end: 3 },
+ {
+ action_type: "click",
+ description: "Range",
+ line_start: 1,
+ line_end: 5,
+ },
+ {
+ action_type: "extract",
+ description: "Exact",
+ line_start: 3,
+ line_end: 3,
+ },
];
- expect(findCodeStepForLine(overlapping, 3)?.title).toBe("Exact");
+ expect(findCodeStepForLine(overlapping, 3)?.description).toBe("Exact");
});
it("returns null when no step covers the line", () => {
diff --git a/skyvern-frontend/src/routes/workflows/workflowBlockUtils.ts b/skyvern-frontend/src/routes/workflows/workflowBlockUtils.ts
index 457ec5c66..ab23e2672 100644
--- a/skyvern-frontend/src/routes/workflows/workflowBlockUtils.ts
+++ b/skyvern-frontend/src/routes/workflows/workflowBlockUtils.ts
@@ -106,15 +106,10 @@ export function buildCodeStepsByLabel(
}
/**
- * Plain-English text for a code-block step: prefer the generated title, then
- * the description, and only humanize the raw action type when neither is
- * present.
+ * Plain-English text for a code-block step: the description, and only
+ * humanize the raw action type when it is absent.
*/
export function getCodeStepPlainText(step: CodeBlockStep): string {
- const title = step.title?.trim();
- if (title) {
- return title;
- }
const description = step.description?.trim();
if (description) {
return description;
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx
index 62277d82e..f449812ff 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx
@@ -904,7 +904,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
const steps: Array<CodeBlockStep> = [
{
action_type: "goto",
- title: "Open the homepage",
+ description: "Open the homepage",
line_start: 1,
line_end: 1,
},
@@ -946,7 +946,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
actions: [],
});
const steps: Array<CodeBlockStep> = [
- { action_type: "execute_js", title: "Run a script" },
+ { action_type: "execute_js", description: "Run a script" },
];
render(
@@ -975,7 +975,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
actions: [],
});
const steps: Array<CodeBlockStep> = [
- { action_type: "execute_js", title: "Summarize the page" },
+ { action_type: "execute_js", description: "Summarize the page" },
];
render(
@@ -1055,7 +1055,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
actions: [],
});
const steps: Array<CodeBlockStep> = [
- { action_type: "goto", title: "Open the homepage", line_start: 1 },
+ { action_type: "goto", description: "Open the homepage", line_start: 1 },
];
render(
@@ -1106,12 +1106,16 @@ describe("WorkflowRunTimelineBlockItem", () => {
] as unknown as WorkflowRunBlock["actions"],
});
const steps: Array<CodeBlockStep> = [
- { action_type: "goto_url", title: "Open the homepage", line_start: 1 },
- { action_type: "click", title: "Submit the form", line_start: 3 },
- { action_type: "extract", title: "Read the result", line_start: 5 },
+ {
+ action_type: "goto_url",
+ description: "Open the homepage",
+ line_start: 1,
+ },
+ { action_type: "click", description: "Submit the form", line_start: 3 },
+ { action_type: "extract", description: "Read the result", line_start: 5 },
{
action_type: "execute_js",
- title: "Summarize the page",
+ description: "Summarize the page",
line_start: 7,
line_end: 8,
},
@@ -1168,8 +1172,8 @@ describe("WorkflowRunTimelineBlockItem", () => {
] as unknown as WorkflowRunBlock["actions"],
});
const steps: Array<CodeBlockStep> = [
- { action_type: "goto", title: "Open the homepage", line_start: 1 },
- { action_type: "click", title: "Submit the form", line_start: 3 },
+ { action_type: "goto", description: "Open the homepage", line_start: 1 },
+ { action_type: "click", description: "Submit the form", line_start: 3 },
];
render(
@@ -1208,8 +1212,12 @@ describe("WorkflowRunTimelineBlockItem", () => {
] as unknown as WorkflowRunBlock["actions"],
});
const steps: Array<CodeBlockStep> = [
- { action_type: "extract", title: "Has a line position", line_start: 5 },
- { action_type: "execute_js", title: "No line position" },
+ {
+ action_type: "extract",
+ description: "Has a line position",
+ line_start: 5,
+ },
+ { action_type: "execute_js", description: "No line position" },
];
render(
@@ -1248,7 +1256,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
] as unknown as WorkflowRunBlock["actions"],
});
const steps: Array<CodeBlockStep> = [
- { action_type: "extract", title: "A later step", line_start: 5 },
+ { action_type: "extract", description: "A later step", line_start: 5 },
];
render(
@@ -1286,8 +1294,8 @@ describe("WorkflowRunTimelineBlockItem", () => {
] as unknown as WorkflowRunBlock["actions"],
});
const steps: Array<CodeBlockStep> = [
- { action_type: "goto", title: "Open the homepage", line_start: 1 },
- { action_type: "extract", title: "Read the result", line_start: 5 },
+ { action_type: "goto", description: "Open the homepage", line_start: 1 },
+ { action_type: "extract", description: "Read the result", line_start: 5 },
];
render(
@@ -1325,7 +1333,10 @@ describe("WorkflowRunTimelineBlockItem", () => {
] as unknown as WorkflowRunBlock["actions"],
});
const steps: Array<CodeBlockStep> = [
- { action_type: "goto", title: "Outline step that should be hidden" },
+ {
+ action_type: "goto",
+ description: "Outline step that should be hidden",
+ },
];
render(
@@ -1367,7 +1378,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
const steps: Array<CodeBlockStep> = [
{
action_type: "extract",
- title: "Extract the product details",
+ description: "Extract the product details",
line_start: 12,
line_end: 12,
},
@@ -1415,7 +1426,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
const steps: Array<CodeBlockStep> = [
{
action_type: "click",
- title: "Submit the application",
+ description: "Submit the application",
line_start: 3,
line_end: 6,
},
@@ -1457,7 +1468,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
const steps: Array<CodeBlockStep> = [
{
action_type: "extract",
- title: "A step on another line",
+ description: "A step on another line",
line_start: 1,
},
];
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx
index e85485097..5aa1244b4 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx
@@ -739,9 +739,7 @@ function TimelineCodeStepRows({
<div className="space-y-1 py-1">
{steps.map((step, index) => {
const lines = formatCodeStepLines(step);
- const summary =
- normalizeInlineText(step.title) ??
- normalizeInlineText(step.description);
+ const summary = normalizeInlineText(step.description);
return (
<div key={index} className="flex min-h-[24px] items-stretch text-xs">
@@ -810,9 +808,7 @@ function TimelineSkippedStepRows({
<div className="space-y-1 pb-1">
{steps.map((step, index) => {
const lines = formatCodeStepLines(step);
- const summary =
- normalizeInlineText(step.title) ??
- normalizeInlineText(step.description);
+ const summary = normalizeInlineText(step.description);
return (
<div
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/blockInfo/CodeBlockParameters.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/blockInfo/CodeBlockParameters.tsx
index 90b72c5ce..528368ad8 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/blockInfo/CodeBlockParameters.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/blockInfo/CodeBlockParameters.tsx
@@ -127,7 +127,7 @@ function CodeBlockParameters({
{step.action_type}
</span>
<span className="min-w-0 flex-1 truncate text-tertiary-foreground">
- {step.title ?? step.description}
+ {step.description}
</span>
{step.line_start != null ? (
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground dark:text-slate-500">
diff --git a/skyvern/cli/mcp_tools/workflow.py b/skyvern/cli/mcp_tools/workflow.py
index 1a91f63e6..248ee3ba4 100644
--- a/skyvern/cli/mcp_tools/workflow.py
+++ b/skyvern/cli/mcp_tools/workflow.py
@@ -721,10 +721,9 @@ def _inject_code_block_prompt_defaults(definition: str, fmt: str, existing_code_
def _inject_code_block_derived_steps(definition: str, fmt: str) -> str:
- """Fill `steps` from `code` on code-first blocks (non-null prompt) that carry none, using the
- copilot's own deterministic derivation. Legacy blocks (null/absent prompt) and explicit steps
- (even an empty outline) are left untouched, so this composes with the prompt-default injection's
- migration guarantees; `steps: null` is the workflow-get shape for "no steps yet" and derives."""
+ """Rebuild `steps` from `code` on code-first blocks (non-null prompt), discarding any submitted steps.
+ Legacy blocks (null/absent prompt) are left untouched, so this composes with the prompt-default
+ injection's migration guarantees."""
raw, parsed_format = _load_definition_dict(definition, fmt)
if raw is None or parsed_format is None:
return definition
@@ -735,13 +734,13 @@ def _inject_code_block_derived_steps(definition: str, fmt: str) -> str:
changed = False
for block in _iter_blocks_flat(blocks):
- if block.get("block_type") != "code" or block.get("prompt") is None or block.get("steps") is not None:
+ if block.get("block_type") != "code" or block.get("prompt") is None:
continue
code = block.get("code")
if not isinstance(code, str):
continue
- derived = derive_code_block_steps(code, block.get("prompt"))
- if derived:
+ derived = derive_code_block_steps(code)
+ if (derived or block.get("steps")) and block.get("steps") != derived:
block["steps"] = derived
changed = True
@@ -1735,7 +1734,7 @@ async def skyvern_workflow_create(
Pass run_with="code" to opt into cached script execution. Blocks share a browser session automatically.
Give every code block a `prompt`: its plain-language goal, shown as the block's Goal in the
editor. Code blocks that omit `prompt` are defaulted to prompt="" so they render the current
- code block editor experience, and their `steps` outline is derived from the code when omitted.
+ code block editor experience. A code block's `steps` outline is always rebuilt from its code, so do not send one.
Leave optional toggles and overrides unset unless the user explicitly asks for them. This
applies to workflow-level fields (persist_browser_session, pin_saved_session_ip, extra_http_headers,
diff --git a/skyvern/forge/sdk/copilot/code_block_steps.py b/skyvern/forge/sdk/copilot/code_block_steps.py
index 58e59e90d..4f55ddab6 100644
--- a/skyvern/forge/sdk/copilot/code_block_steps.py
+++ b/skyvern/forge/sdk/copilot/code_block_steps.py
@@ -5,11 +5,13 @@ import re
import textwrap
from dataclasses import dataclass, replace
from typing import Any, Iterator
+from urllib.parse import urlsplit
import structlog
import yaml
from skyvern.forge.sdk.copilot.code_block_synthesis import _RESERVED_PARAM_NAMES
+from skyvern.utils.templating import mask_jinja_control_blocks, strip_jinja_control_blocks
LOG = structlog.get_logger()
@@ -91,21 +93,39 @@ class CodeActionSpan:
first_arg: str | None # source of the first call arg, if any
prompt: str | None # natural-language `prompt` argument value, if a string literal
loop_var: str | None # name of the enclosing for-loop target, if the call is inside one
+ store_name: str | None = None # where a read's value is stored: assigned variable, appended list, or dict key
+ element_name: str | None = None # visible name from get_by_role(name=...)/get_by_label/get_by_text
+ goto_name: str | None = None
+ goto_literal: str | None = None # the string constant goto_name is bound to, when bound exactly once
def analyze_code_actions(code: str) -> list[CodeActionSpan]:
"""Find browser-action calls in `code` and map each to an action_type + exact line range."""
if not code or not code.strip():
return []
- try:
- tree = ast.parse(code)
- except SyntaxError:
+ tree: ast.Module | None = None
+ # Stripping keeps Python that shares a line with a tag; commenting is the fallback for tag bodies that are not Python.
+ for mask in (strip_jinja_control_blocks, mask_jinja_control_blocks):
+ try:
+ tree = ast.parse(mask(code))
+ break
+ # CPython's parser reports source nested too deeply as MemoryError, not RecursionError.
+ except (SyntaxError, ValueError, RecursionError, MemoryError):
+ continue
+ if tree is None:
return []
parents: dict[ast.AST, ast.AST] = {}
+ parent_fields: dict[ast.AST, str] = {}
for parent in ast.walk(tree):
- for child in ast.iter_child_nodes(parent):
- parents[child] = parent
+ for field, value in ast.iter_fields(parent):
+ for child in value if isinstance(value, list) else [value]:
+ if isinstance(child, ast.AST):
+ parents[child] = parent
+ parent_fields[child] = field
+ bindings: dict[str, list[ast.AST]] | None = None
+ store_names: dict[ast.AST, str | None] = {}
+ loop_vars: dict[ast.AST, str | None] = {}
spans: list[CodeActionSpan] = []
for node in ast.walk(tree):
@@ -120,6 +140,14 @@ def analyze_code_actions(code: str) -> list[CodeActionSpan]:
action_type = _METHOD_ACTION_TYPES.get(method) or _READ_METHODS.get(method)
if action_type is None:
continue
+ goto_url = _goto_url_node(call, method)
+ goto_arg = goto_url if isinstance(goto_url, ast.Name) else None
+ first_arg = call.args[0] if call.args else goto_url
+ goto_literal = None
+ if goto_arg is not None:
+ if bindings is None:
+ bindings = _name_bindings(tree)
+ goto_literal = _same_body_string_binding(node, goto_arg, bindings, parents, parent_fields)
spans.append(
CodeActionSpan(
action_type=action_type,
@@ -127,9 +155,13 @@ def analyze_code_actions(code: str) -> list[CodeActionSpan]:
line_end=getattr(node, "end_lineno", None) or node.lineno,
method=method,
receiver=_safe_unparse(call.func.value),
- first_arg=_safe_unparse(call.args[0]) if call.args else None,
+ first_arg=_safe_unparse(first_arg) if first_arg is not None else None,
prompt=_prompt_literal(call, method),
- loop_var=_enclosing_loop_var(node, parents),
+ loop_var=_enclosing_loop_var(node, parents, loop_vars),
+ store_name=_store_name(node, parents, store_names) if action_type == "extract" else None,
+ element_name=_element_name(call.func.value) if action_type == "extract" else None,
+ goto_name=goto_arg.id if goto_arg else None,
+ goto_literal=goto_literal,
)
)
spans.sort(key=lambda s: (s.line_start, s.line_end))
@@ -150,6 +182,158 @@ def _prompt_literal(call: ast.Call, method: str) -> str | None:
return None
+def _goto_url_node(call: ast.Call, method: str) -> ast.expr | None:
+ if method != "goto":
+ return None
+ if call.args:
+ return call.args[0]
+ return next((keyword.value for keyword in call.keywords if keyword.arg == "url"), None)
+
+
+_PASS_UP = object()
+
+
+def _store_name(node: ast.AST, parents: dict[ast.AST, ast.AST], cache: dict[ast.AST, str | None]) -> str | None:
+ """Where the enclosing statement stores a read's value, or None for any use that could borrow an unrelated name.
+
+ Memoized per node, so reads sharing one long expression (a chain of `+`) walk it once in total."""
+ visited: list[ast.AST] = []
+ current = node
+ while current not in cache:
+ visited.append(current)
+ outcome = _stored_in(parents.get(current), current)
+ if outcome is _PASS_UP:
+ current = parents[current]
+ continue
+ cache[current] = outcome if isinstance(outcome, str) else None
+ result = cache[current]
+ for seen in visited:
+ cache[seen] = result
+ return result
+
+
+def _stored_in(parent: ast.AST | None, current: ast.AST) -> object:
+ """The name `parent` stores `current` in, None when there is none, or _PASS_UP to keep walking up."""
+ if parent is None:
+ return None
+ if isinstance(parent, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
+ targets = parent.targets if isinstance(parent, ast.Assign) else [parent.target]
+ if parent.value is current and len(targets) == 1 and isinstance(targets[0], ast.Name):
+ return targets[0].id
+ return None
+ if isinstance(parent, ast.Dict):
+ key = next((key for key, value in zip(parent.keys, parent.values) if value is current), None)
+ return _constant_str(key) if key is not None else None
+ if isinstance(parent, ast.Call):
+ if parent.func is current:
+ return _PASS_UP
+ func = parent.func
+ if (
+ current in parent.args
+ and isinstance(func, ast.Attribute)
+ and func.attr == "append"
+ and isinstance(func.value, ast.Name)
+ ):
+ return func.value.id
+ return None
+ if isinstance(parent, (ast.Attribute, ast.Subscript)) and parent.value is current:
+ return _PASS_UP
+ if isinstance(parent, (ast.BinOp, ast.BoolOp, ast.UnaryOp)):
+ return _PASS_UP
+ return None
+
+
+def _element_name(receiver: ast.AST) -> str | None:
+ """The nearest visible element name cited by a get_by_role/get_by_label/get_by_text call in the receiver chain."""
+ node: ast.AST | None = receiver
+ while node is not None:
+ if isinstance(node, ast.Call):
+ func = node.func
+ if isinstance(func, ast.Attribute) and func.attr in ("get_by_role", "get_by_label", "get_by_text"):
+ for keyword in node.keywords:
+ if keyword.arg == "name" or (keyword.arg == "text" and func.attr != "get_by_role"):
+ return _constant_str(keyword.value)
+ if func.attr != "get_by_role" and node.args:
+ return _constant_str(node.args[0])
+ return None
+ node = func
+ elif isinstance(node, (ast.Attribute, ast.Subscript)):
+ node = node.value
+ else:
+ node = None
+ return None
+
+
+def _name_bindings(tree: ast.AST) -> dict[str, list[ast.AST]]:
+ bindings: dict[str, list[ast.AST]] = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Name) and not isinstance(node.ctx, ast.Load):
+ names = [node.id]
+ elif isinstance(node, ast.arg):
+ names = [node.arg]
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ names = [node.name]
+ elif isinstance(node, ast.alias):
+ names = [node.asname or node.name.split(".")[0]]
+ elif isinstance(node, (ast.Global, ast.Nonlocal)):
+ names = list(node.names)
+ elif isinstance(node, (ast.ExceptHandler, ast.MatchAs, ast.MatchStar)) and node.name:
+ names = [node.name]
+ elif isinstance(node, ast.MatchMapping) and node.rest:
+ names = [node.rest]
+ else:
+ continue
+ for name in names:
+ bindings.setdefault(name, []).append(node)
+ return bindings
+
+
+def _same_body_string_binding(
+ goto: ast.AST,
+ name: ast.Name,
+ bindings: dict[str, list[ast.AST]],
+ parents: dict[ast.AST, ast.AST],
+ parent_fields: dict[ast.AST, str],
+) -> str | None:
+ """The address `name` holds, when its only binding is `name = "<str>"` earlier in the goto's own statement body."""
+ if len(bindings.get(name.id, [])) != 1:
+ return None
+ assignment = parents.get(bindings[name.id][0])
+ if not isinstance(assignment, ast.Assign) or len(assignment.targets) != 1:
+ return None
+ statement = goto
+ while not isinstance(statement, ast.stmt):
+ statement = parents[statement]
+ if (
+ parents.get(assignment) is not parents.get(statement)
+ or parent_fields.get(assignment) != parent_fields.get(statement)
+ or assignment.lineno >= statement.lineno
+ ):
+ return None
+ return _address_without_secrets(_constant_str(assignment.value))
+
+
+def _address_without_secrets(value: str | None) -> str | None:
+ """The literal unchanged when it is a plain http(s) address, else None so the label names the variable instead.
+
+ Credentials, a query, a fragment, or a template placeholder never reach a label."""
+ if not value or "{{" in value:
+ return None
+ try:
+ parts = urlsplit(value)
+ plain = (
+ parts.scheme in ("http", "https")
+ and bool(parts.hostname)
+ and "@" not in parts.netloc
+ and not parts.query
+ and not parts.fragment
+ and (parts.port is None or parts.port > 0)
+ )
+ except ValueError:
+ return None
+ return value if plain else None
+
+
def _constant_str(node: ast.AST) -> str | None:
"""The decoded value of a string-literal AST node, else None (e.g. a variable or f-string)."""
if isinstance(node, ast.Constant) and isinstance(node.value, str):
@@ -157,14 +341,23 @@ def _constant_str(node: ast.AST) -> str | None:
return None
-def _enclosing_loop_var(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> str | None:
- """Name of the nearest enclosing for-loop's target, when it is a plain variable."""
+def _enclosing_loop_var(node: ast.AST, parents: dict[ast.AST, ast.AST], cache: dict[ast.AST, str | None]) -> str | None:
+ """Name of the nearest enclosing for-loop's target, when it is a plain variable (memoized per ancestor)."""
+ visited: list[ast.AST] = []
current = parents.get(node)
+ result: str | None = None
while current is not None:
+ if current in cache:
+ result = cache[current]
+ break
+ visited.append(current)
if isinstance(current, (ast.For, ast.AsyncFor)) and isinstance(current.target, ast.Name):
- return current.target.id
+ result = current.target.id
+ break
current = parents.get(current)
- return None
+ for seen in visited:
+ cache[seen] = result
+ return result
def _safe_unparse(node: ast.AST) -> str:
@@ -222,8 +415,19 @@ def _describe(span: CodeActionSpan) -> str:
# a repeated generic "Open the page". Inside a loop it opens each iterated item.
if span.loop_var:
return f"Open each {_humanize_identifier(span.loop_var)}"
+ if span.goto_literal:
+ return f"Open {span.goto_literal}"
+ if span.goto_name:
+ return f"Open the {_humanize_identifier(span.goto_name)}"
return "Open the linked page"
if span.action_type == "extract":
+ store = _humanize_identifier(span.store_name) if span.store_name else None
+ if store and span.element_name:
+ return f'Extract {store} from "{span.element_name}"'
+ if store:
+ return f"Extract {store}"
+ if span.element_name:
+ return f'Extract "{span.element_name}"'
return "Extract information from the page"
if span.action_type == "click":
return f"Click {_target_label(span.receiver, span.first_arg)}"
@@ -268,18 +472,23 @@ def _describe(span: CodeActionSpan) -> str:
def _consolidate_read_spans(spans: list[CodeActionSpan]) -> list[CodeActionSpan]:
- """Merge adjacent raw DOM reads into one extract span."""
+ """Merge adjacent raw DOM reads that carry the same label into one extract span."""
consolidated: list[CodeActionSpan] = []
for span in spans:
prev = consolidated[-1] if consolidated else None
- if span.method in _READ_METHODS and prev is not None and prev.method in _READ_METHODS:
+ if (
+ span.method in _READ_METHODS
+ and prev is not None
+ and prev.method in _READ_METHODS
+ and _describe(prev) == _describe(span)
+ ):
consolidated[-1] = replace(prev, line_end=max(prev.line_end, span.line_end))
continue
consolidated.append(span)
return consolidated
-def derive_code_block_steps(code: str, goal: str | None = None) -> list[dict[str, Any]]:
+def derive_code_block_steps(code: str) -> list[dict[str, Any]]:
"""Derive the ordered plain-language steps for a code block from its code (deterministic)."""
return [
{
@@ -305,10 +514,7 @@ def _iter_code_block_dicts(node: Any) -> Iterator[dict[str, Any]]:
def derive_code_block_steps_in_yaml(workflow_yaml: str) -> str:
- """Return workflow_yaml with each code block's `steps` filled from its `code` when absent.
-
- Deterministic and sync: a block that already carries steps is left untouched, so this
- can run on the shared YAML->Workflow seam without clobbering steps produced upstream."""
+ """Return workflow_yaml with each code block's `steps` rebuilt from its `code`, discarding any it carried."""
try:
data = yaml.safe_load(workflow_yaml)
except yaml.YAMLError:
@@ -318,10 +524,10 @@ def derive_code_block_steps_in_yaml(workflow_yaml: str) -> str:
changed = False
for block in _iter_code_block_dicts(data):
- if block.get("steps"):
- continue
- block["steps"] = derive_code_block_steps(block["code"], block.get("prompt"))
- changed = True
+ derived = derive_code_block_steps(block["code"])
+ if block.get("steps") != derived:
+ block["steps"] = derived
+ changed = True
if not changed:
return workflow_yaml
@@ -417,25 +623,6 @@ def fill_code_block_error_code_mappings_in_yaml(workflow_yaml: str, *, prior_yam
return yaml.safe_dump(data, sort_keys=False)
-async def apply_derived_code_block_steps(workflow_yaml: str) -> str:
- """Return workflow_yaml with each code block's `steps` recomputed from its `code`."""
- try:
- data = yaml.safe_load(workflow_yaml)
- except yaml.YAMLError:
- return workflow_yaml
- if not isinstance(data, (dict, list)):
- return workflow_yaml
-
- changed = False
- for block in _iter_code_block_dicts(data):
- block["steps"] = derive_code_block_steps(block["code"], block.get("prompt"))
- changed = True
-
- if not changed:
- return workflow_yaml
- return yaml.safe_dump(data, sort_keys=False)
-
-
def _declared_parameter_keys(data: Any) -> set[str]:
definition = data.get("workflow_definition") if isinstance(data, dict) else None
parameters = definition.get("parameters") if isinstance(definition, dict) else None
diff --git a/skyvern/forge/sdk/copilot/review_gate.py b/skyvern/forge/sdk/copilot/review_gate.py
index 9d26c5a4a..a79873c2c 100644
--- a/skyvern/forge/sdk/copilot/review_gate.py
+++ b/skyvern/forge/sdk/copilot/review_gate.py
@@ -8,7 +8,6 @@ from typing import Any, Literal
from jinja2 import Environment, nodes
from typing_extensions import NotRequired, TypedDict
-from skyvern.forge.sdk.copilot.code_block_steps import derive_code_block_steps_in_yaml
from skyvern.forge.sdk.copilot.data_write_defaults import DATA_WRITE_BLOCK_TYPES
from skyvern.forge.sdk.copilot.workflow_credential_utils import parse_workflow_yaml, workflow_blocks
from skyvern.forge.sdk.services import google_drive_service
@@ -196,8 +195,18 @@ DESTINATION_ADAPTERS: dict[str, DestinationAdapter] = {
}
+def _without_code_steps(value: Any) -> Any:
+ """Drop code-derived `steps` at every nesting depth; they are a projection of `code`, not execution identity."""
+ if isinstance(value, dict):
+ is_code = _block_type(value) == BlockType.CODE.value
+ return {key: _without_code_steps(item) for key, item in value.items() if not (is_code and key == "steps")}
+ if isinstance(value, list):
+ return [_without_code_steps(item) for item in value]
+ return value
+
+
def _comparison_value(block: Mapping[str, Any]) -> dict[str, Any]:
- return {key: value for key, value in block.items() if key not in _IGNORED_COMPARISON_KEYS}
+ return {key: value for key, value in _without_code_steps(block).items() if key not in _IGNORED_COMPARISON_KEYS}
def _workflow_execution_inputs(parsed: Mapping[str, Any]) -> dict[str, Any]:
@@ -230,7 +239,9 @@ def _block_fingerprint(block: Mapping[str, Any], workflow_execution_inputs: Mapp
# Ignore only the indexed block's own label. Nested labels and control-flow
# links remain part of the exact version that a run exercised.
value = {
- "block": {key: item for key, item in block.items() if key not in _IGNORED_FINGERPRINT_KEYS},
+ "block": {
+ key: item for key, item in _without_code_steps(block).items() if key not in _IGNORED_FINGERPRINT_KEYS
+ },
"workflowExecutionInputs": workflow_execution_inputs,
}
serialized = json.dumps(value, sort_keys=True, default=str, separators=(",", ":"))
@@ -258,7 +269,7 @@ def _next_common_label(
def workflow_block_fingerprints(workflow_yaml: str) -> dict[str, set[str]]:
if not isinstance(workflow_yaml, str):
return {}
- parsed = parse_workflow_yaml(derive_code_block_steps_in_yaml(workflow_yaml))
+ parsed = parse_workflow_yaml(workflow_yaml)
if not isinstance(parsed, dict):
return {}
indexed = _labeled_blocks(parsed)
@@ -333,8 +344,8 @@ def build_review_projection(
) -> NarrativeReviewProjection | None:
if not isinstance(persisted_workflow_yaml, str) or not isinstance(staged_workflow_yaml, str):
return None
- persisted = parse_workflow_yaml(derive_code_block_steps_in_yaml(persisted_workflow_yaml))
- staged = parse_workflow_yaml(derive_code_block_steps_in_yaml(staged_workflow_yaml))
+ persisted = parse_workflow_yaml(persisted_workflow_yaml)
+ staged = parse_workflow_yaml(staged_workflow_yaml)
if not isinstance(persisted, dict) or not isinstance(staged, dict):
return None
persisted_index = _labeled_blocks(persisted)
diff --git a/skyvern/forge/sdk/workflow/exceptions.py b/skyvern/forge/sdk/workflow/exceptions.py
index db2187eef..cba672a0d 100644
--- a/skyvern/forge/sdk/workflow/exceptions.py
+++ b/skyvern/forge/sdk/workflow/exceptions.py
@@ -184,14 +184,6 @@ class WorkflowDefinitionHasUndefinedParameters(WorkflowDefinitionValidationExcep
)
-class InvalidCodeBlockStep(WorkflowDefinitionValidationException):
- def __init__(self, block_label: str, step_index: int, detail: str) -> None:
- super().__init__(
- f"Invalid step at index {step_index} in code block '{block_label}': {detail}",
- status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
- )
-
-
class CodeBlockTemplateSyntaxError(WorkflowDefinitionValidationException):
def __init__(self, block_label: str, original: BaseException) -> None:
self.block_label = block_label
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index f5c2a7e23..a1464e2fc 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -4586,7 +4586,6 @@ class Credential(SimpleNamespace):
class CodeBlockStep(BaseModel):
- title: str | None = None
description: str | None = None
action_type: ActionType = ActionType.NULL_ACTION
line_start: int | None = None
@@ -5451,12 +5450,12 @@ async def _dom_storage_session(context: BrowserContext, open_page: Page, frame:
_FRAME_STORAGE_REACHABLE_PROBE = (
- "(() => { try { sessionStorage.length; return 'reachable'; } catch (error) { return 'unreachable'; } })()"
+ "() => { try { sessionStorage.length; return 'reachable'; } catch (error) { return 'unreachable'; } }"
)
-async def _frame_storage_is_unreachable(session: CDPSession) -> bool:
- """Whether the frame behind this session can reach web storage at all.
+async def _frame_storage_is_unreachable(target: Page | Frame) -> bool:
+ """Whether this frame's own document can reach web storage at all.
A sandboxed or otherwise opaque frame has no storage area to address and nothing that outlives its
document, so a clear that cannot find one has found nothing to clear. Asked only after the clear
@@ -5464,14 +5463,12 @@ async def _frame_storage_is_unreachable(session: CDPSession) -> bool:
it can address, so a real addressing failure still surfaces.
"""
try:
- answer = await session.send(
- "Runtime.evaluate", {"expression": _FRAME_STORAGE_REACHABLE_PROBE, "returnByValue": True}
- )
+ answer = await target.evaluate(_FRAME_STORAGE_REACHABLE_PROBE)
except Exception as exc:
if not _is_browser_refusal(exc):
raise
return False
- return answer.get("result", {}).get("value") == "unreachable"
+ return answer == "unreachable"
async def _cleared_session_storage(context: BrowserContext, open_page: Page, frame: Frame, origin: str) -> bool:
@@ -5486,9 +5483,9 @@ async def _cleared_session_storage(context: BrowserContext, open_page: Page, fra
await frame_session.send("DOMStorage.clear", {"storageId": {"securityOrigin": origin, "isLocalStorage": False}})
return True
except Exception as exc:
- # Only a frame holding a session of its own can be asked about its own storage, and a frame
- # with nothing to clear is exactly that kind: it is opaque, so it has a target.
- if not _is_browser_refusal(exc) or not (is_own_session and await _frame_storage_is_unreachable(frame_session)):
+ # The frame is asked rather than its session: an engine can hand a frame sharing the page's
+ # renderer a session on the page's target, which answers for the page.
+ if not _is_browser_refusal(exc) or not (is_own_session and await _frame_storage_is_unreachable(frame)):
raise
return False
finally:
@@ -5514,7 +5511,7 @@ async def _cleared_inherited_session_storage(context: BrowserContext, open_page:
# A frame with no storage key is one on an opaque origin, which has no storage area to
# clear -- and which answers the probe as such. Any other refusal, a timeout among them,
# would otherwise pass for a tab with nothing to clear and leave its session behind.
- if not _is_browser_refusal(exc) or not await _frame_storage_is_unreachable(session):
+ if not _is_browser_refusal(exc) or not await _frame_storage_is_unreachable(open_page):
raise
return ""
storage_key = answer.get("storageKey")
@@ -6627,22 +6624,16 @@ async def wrapper({default_args}):
return None
def _static_url_from_goal(self) -> str:
- # The goal is human free text (prompt + step descriptions), not code, so a URL regex is
- # appropriate here (unlike the AST-only code scan). This is the authored destination the
- # heal should reach when the block's own navigation rotted. Returns the first well-formed
- # absolute http(s) URL, else "".
- texts = [self.prompt or ""]
- if self.steps:
- texts.extend(step.description or "" for step in self.steps)
- for text in texts:
- match = re.search(r"https?://[^\s'\"<>)\]]+", text)
- if not match:
- continue
- candidate = match.group(0).rstrip(".,;")
- parsed = urlparse(candidate)
- if parsed.scheme in {"http", "https"} and parsed.netloc:
- return candidate
- return ""
+ # The prompt is human free text, not code, so a URL regex is appropriate here (unlike the
+ # AST-only code scan). Step descriptions are derived from the code, so an address there is
+ # the code's own possibly-rotted goto, never an authored destination. Returns the first
+ # well-formed absolute http(s) URL, else "".
+ match = re.search(r"https?://[^\s'\"<>)\]]+", self.prompt or "")
+ if not match:
+ return ""
+ candidate = match.group(0).rstrip(".,;")
+ parsed = urlparse(candidate)
+ return candidate if parsed.scheme in {"http", "https"} and parsed.netloc else ""
def _derive_escalation_navigation_url(self, failing_line: int, recording_page: RecordingPage) -> str:
code_lines = self.code.splitlines()
diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
index a5e4ac5d0..fe9917c27 100644
--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py
+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
@@ -3,7 +3,6 @@ from datetime import UTC, datetime
from typing import Any, cast
import structlog
-from pydantic import ValidationError
from skyvern.config import settings
from skyvern.constants import DEFAULT_LOGIN_PROMPT
@@ -22,7 +21,6 @@ from skyvern.forge.sdk.db.id import (
)
from skyvern.forge.sdk.workflow.exceptions import (
ContextParameterSourceNotDefined,
- InvalidCodeBlockStep,
InvalidWaitBlockTime,
InvalidWorkflowDefinition,
WorkflowDefinitionHasDuplicateBlockLabels,
@@ -409,64 +407,6 @@ def _build_block_kwargs(
}
-def _code_block_step_span_issue(step: CodeBlockStep, code_line_count: int) -> str | None:
- """Return why a step's line span is malformed, or None when it is well-formed: a well-formed span
- is empty, a lone 1-based line_start, or a 1-based line_start <= line_end with both bounds within
- the code's line count (a lone line_end has no anchor for the editor to render from)."""
- line_start = step.line_start
- line_end = step.line_end
- if line_end is not None and line_start is None:
- return "line_end is set without line_start"
- for bound_name, bound in (("line_start", line_start), ("line_end", line_end)):
- if bound is None:
- continue
- if bound < 1:
- return f"{bound_name} must be >= 1, got {bound}"
- if bound > code_line_count:
- return f"{bound_name} ({bound}) exceeds the code length ({code_line_count} line(s))"
- if line_start is not None and line_end is not None and line_start > line_end:
- return f"line_start ({line_start}) must be <= line_end ({line_end})"
- return None
-
-
-def _reconcile_code_block_step_spans(
- *,
- block_label: str,
- steps: list[CodeBlockStep],
- code: str,
-) -> list[CodeBlockStep]:
- """Repair malformed step spans against the code-derived spans instead of rejecting the save.
-
- Step spans are display-only line references the editor and run timeline render. A non-copilot
- save path (the copilot re-derives) can persist a stale or model-mangled span, e.g. a code edit
- that shortens the block below a step's line_end. Snap an invalid span to the synthesized span at
- the same position, or drop it to null when the code yields no step there; well-formed spans and
- all other fields are kept untouched."""
- code_line_count = len(code.splitlines())
- issues = [_code_block_step_span_issue(step, code_line_count) for step in steps]
- if not any(issues):
- return steps
- derived = derive_code_block_steps(code)
- reconciled: list[CodeBlockStep] = []
- for step_index, (step, issue) in enumerate(zip(steps, issues)):
- if issue is None:
- reconciled.append(step)
- continue
- derived_step = derived[step_index] if step_index < len(derived) else None
- repaired_start = derived_step["line_start"] if derived_step else None
- repaired_end = derived_step["line_end"] if derived_step else None
- LOG.info(
- "Reconciled malformed code-block step span",
- block_label=block_label,
- step_index=step_index,
- issue=issue,
- line_start=repaired_start,
- line_end=repaired_end,
- )
- reconciled.append(step.model_copy(update={"line_start": repaired_start, "line_end": repaired_end}))
- return reconciled
-
-
def block_yaml_to_block(
block_yaml: BLOCK_YAML_TYPES,
parameters: dict[str, PARAMETER_TYPE],
@@ -594,33 +534,13 @@ def block_yaml_to_block(
branch_conditions=branch_conditions,
)
elif block_yaml.block_type == BlockType.CODE:
- code_block_steps: list[CodeBlockStep] | None = None
- if block_yaml.steps:
- code_block_steps = []
- for step_index, step_yaml in enumerate(block_yaml.steps):
- try:
- step = CodeBlockStep(**step_yaml.model_dump())
- except ValidationError as exc:
- first_error = exc.errors()[0]
- field = ".".join(str(part) for part in first_error["loc"])
- raise InvalidCodeBlockStep(
- block_label=block_yaml.label,
- step_index=step_index,
- detail=f"{field}: {first_error['msg']}",
- ) from exc
- code_block_steps.append(step)
- code_block_steps = _reconcile_code_block_step_spans(
- block_label=block_yaml.label,
- steps=code_block_steps,
- code=block_yaml.code,
- )
return CodeBlock(
**base_kwargs,
code=block_yaml.code,
parameters=_resolve_block_parameters(block_yaml, parameters),
error_code_mapping=block_yaml.error_code_mapping,
prompt=block_yaml.prompt,
- steps=code_block_steps,
+ steps=[CodeBlockStep(**step) for step in derive_code_block_steps(block_yaml.code)] or None,
)
elif block_yaml.block_type == BlockType.TEXT_PROMPT:
return TextPromptBlock(
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index 840e8c25f..beaec4545 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -1,7 +1,6 @@
import abc
import ast
import functools
-import re
import textwrap
import unicodedata
from dataclasses import dataclass, field
@@ -9,7 +8,16 @@ from enum import StrEnum
from typing import Annotated, Any, Literal, Protocol, TypeVar
import structlog
-from pydantic import BaseModel, Field, StrictInt, field_serializer, field_validator, model_validator
+from pydantic import (
+ BaseModel,
+ Field,
+ StrictInt,
+ TypeAdapter,
+ ValidationError,
+ field_serializer,
+ field_validator,
+ model_validator,
+)
from skyvern.config import settings
from skyvern.constants import ERROR_CODE_REASONING_MAX_LENGTH
@@ -28,7 +36,7 @@ from skyvern.schemas.emails import EmailBodyFormat
from skyvern.schemas.runs import GeoTarget, ProxyLocation, RunEngine, normalize_browser_type
from skyvern.utils.secret_headers import mask_header_values
from skyvern.utils.strings import sanitize_identifier
-from skyvern.utils.templating import replace_jinja_reference
+from skyvern.utils.templating import mask_jinja_control_blocks, replace_jinja_reference
LOG = structlog.get_logger()
@@ -906,7 +914,6 @@ class ConditionalBlockYAML(BlockYAML):
class CodeBlockStepYAML(BaseModel):
- title: str | None = None
description: str | None = None
# str (not ActionType) so this module does not import skyvern.webeye; the converter coerces to the enum.
action_type: str = "null_action"
@@ -997,12 +1004,7 @@ def _validate_code_block_error_code_mapping(mapping: Any) -> None:
def _direct_code_block_error_code_raises(code: str) -> set[tuple[int, str]]:
- sanitized = re.sub(
- r"\{%.*?%\}",
- lambda match: "\n".join("# __JINJA_BLOCK__" for _ in range(match.group().count("\n") + 1)),
- textwrap.dedent(code),
- flags=re.DOTALL,
- )
+ sanitized = mask_jinja_control_blocks(textwrap.dedent(code))
try:
tree = ast.parse(sanitized)
except SyntaxError as exc:
@@ -1082,7 +1084,7 @@ class CodeBlockYAML(BlockYAML):
)
steps: list[CodeBlockStepYAML] | None = Field(
default=None,
- description="Plain-language step outline mapped to code line ranges; derived from the code when omitted",
+ description="Plain-language step outline mapped to code line ranges; always rebuilt from the code on save, so any value sent is ignored",
)
@model_validator(mode="before")
@@ -1097,9 +1099,18 @@ class CodeBlockYAML(BlockYAML):
)
if isinstance(data, dict):
_validate_code_block_error_code_mapping(data.get("error_code_mapping"))
+ # Saves rebuild steps from the code, so malformed submitted steps must not reject valid code.
+ if data.get("steps") is not None:
+ try:
+ _CODE_BLOCK_STEPS_ADAPTER.validate_python(data["steps"])
+ except ValidationError:
+ data = {**data, "steps": None}
return data
+_CODE_BLOCK_STEPS_ADAPTER = TypeAdapter(list[CodeBlockStepYAML])
+
+
class TextPromptBlockYAML(BlockYAML):
# There is a mypy bug with Literal. Without the type: ignore, mypy will raise an error:
# Parameter 1 of Literal[...] cannot be of type "Any"
diff --git a/skyvern/utils/templating.py b/skyvern/utils/templating.py
index 349c2ca4b..bae0f4366 100644
--- a/skyvern/utils/templating.py
+++ b/skyvern/utils/templating.py
@@ -1,7 +1,7 @@
import json
import keyword
import re
-from typing import Any
+from typing import Any, Callable
from jinja2 import StrictUndefined, UndefinedError, meta, nodes
from jinja2.sandbox import SandboxedEnvironment
@@ -11,6 +11,55 @@ class Constants:
MissingVariablePattern = var_pattern = r"\{\{\s*([a-zA-Z_][a-zA-Z0-9_.\[\]'\"]*)\s*\}\}"
+_JINJA_TAG_CLOSERS = {"{%": "%}", "{#": "#}"}
+
+
+def _jinja_tag_spans(code: str) -> list[tuple[int, int]]:
+ """Leftmost non-overlapping `{% ... %}` / `{# ... #}` spans, found in one forward pass.
+
+ Once an opener has no closer after it, no later opener of that kind can close either, so that kind
+ is dropped; a regex search would instead rescan to the end from every later opener (quadratic)."""
+ spans: list[tuple[int, int]] = []
+ next_opener = {opener: code.find(opener) for opener in _JINJA_TAG_CLOSERS}
+ position = 0
+ while True:
+ for opener, index in list(next_opener.items()):
+ if index != -1 and index < position:
+ next_opener[opener] = code.find(opener, position)
+ open_kinds = {opener: index for opener, index in next_opener.items() if index != -1}
+ if not open_kinds:
+ return spans
+ opener = min(open_kinds, key=open_kinds.__getitem__)
+ start = open_kinds[opener]
+ end = code.find(_JINJA_TAG_CLOSERS[opener], start + len(opener))
+ if end == -1:
+ del next_opener[opener]
+ continue
+ position = end + len(_JINJA_TAG_CLOSERS[opener])
+ spans.append((start, position))
+
+
+def _replace_jinja_tags(code: str, replacement: Callable[[str], str]) -> str:
+ parts: list[str] = []
+ cursor = 0
+ for start, end in _jinja_tag_spans(code):
+ parts.append(code[cursor:start])
+ parts.append(replacement(code[start:end]))
+ cursor = end
+ parts.append(code[cursor:])
+ return "".join(parts)
+
+
+def mask_jinja_control_blocks(code: str) -> str:
+ """Replace each `{% ... %}` block and `{# ... #}` comment in Python source with comment lines, keeping every line number."""
+ return _replace_jinja_tags(code, lambda tag: "\n".join("# __JINJA_BLOCK__" for _ in range(tag.count("\n") + 1)))
+
+
+def strip_jinja_control_blocks(code: str) -> str:
+ """Remove each `{% ... %}` block and `{# ... #}` comment from Python source, keeping its newlines so line numbers hold."""
+ return _replace_jinja_tags(code, lambda tag: "\n" * tag.count("\n"))
+
+
def replace_jinja_reference(text: str, old_key: str, new_key: str) -> str:
"""Replaces jinja-style references in a string.
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index bfccf78fc..b6669a2c0 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -674,17 +674,26 @@ class FakeClearingBrowserContext:
# Storage key the browser reports for a tab whose URL names no origin, as it does for a
# window opened on about:blank. A tab absent from this list has an opaque origin and none.
self.inherited_storage_keys: list[tuple[object, str]] = []
+ # (frame, page) pairs whose frame session is attached to the page's target, as raw-CDP attaches
+ # a same-process frame, so protocol calls on it answer for the page's document.
+ self.frames_attached_to_page_target: list[tuple[object, object]] = []
async def clear_cookies(self) -> None:
self.clear_cookies_calls += 1
if self.clear_cookies_error is not None:
raise self.clear_cookies_error
+ async def _probe_storage(self, document: object) -> str:
+ return "unreachable" if document in self.frames_without_storage else "reachable"
+
async def new_cdp_session(self, page: object) -> FakeCdpSession:
+ if not hasattr(page, "evaluate"):
+ page.evaluate = lambda expression, document=page: self._probe_storage(document) # type: ignore[attr-defined]
if page in self.frames_without_own_session:
raise PlaywrightError("This frame does not have a separate CDP session")
+ answering = next((held for frame, held in self.frames_attached_to_page_target if frame is page), page)
session = FakeCdpSession(
- storage_reachable=page not in self.frames_without_storage,
+ storage_reachable=answering not in self.frames_without_storage,
origins_refusing_clear=tuple(self.origins_refusing_clear),
origins_failing_unexpectedly=tuple(self.origins_failing_unexpectedly),
refuses_clear=page in self.frames_refusing_clear,
diff --git a/tests/unit/copilot/test_review_gate.py b/tests/unit/copilot/test_review_gate.py
index 9b1eccec5..800d92d4b 100644
--- a/tests/unit/copilot/test_review_gate.py
+++ b/tests/unit/copilot/test_review_gate.py
@@ -1,6 +1,10 @@
from __future__ import annotations
import json
+import textwrap
+from collections.abc import Callable
+
+import pytest
from skyvern.forge.sdk.copilot.code_block_steps import derive_code_block_steps_in_yaml
from skyvern.forge.sdk.copilot.data_write_defaults import DATA_WRITE_BLOCK_TYPES
@@ -269,6 +273,54 @@ def test_missing_code_steps_are_canonicalized_before_execution_fingerprinting()
assert workflow_block_fingerprints(without_steps) == workflow_block_fingerprints(accepted_shape)
+_READ_PRICE_BLOCK = """- block_type: code
+ label: read_price
+ code: |-
+ price = await page.locator('.price').inner_text()
+"""
+_OLD_WORDING_STEPS = """ steps:
+ - description: Extract information from the page
+ action_type: extract
+ line_start: 1
+"""
+_NEW_WORDING_STEPS = """ steps:
+ - description: Extract price
+ action_type: extract
+ line_start: 1
+ line_end: 1
+"""
+
+
+def _top_level(block: str) -> str:
+ return _workflow(textwrap.indent(block, " "))
+
+
+def _inside_loop(block: str) -> str:
+ loop = "- block_type: for_loop\n label: loop\n loop_over_parameter_key: items\n loop_blocks:\n"
+ return _workflow(textwrap.indent(loop + textwrap.indent(block, " "), " "))
+
+
[email protected]("wrap", [_top_level, _inside_loop])
+def test_tested_block_fingerprint_ignores_code_steps_at_every_depth(wrap: Callable[[str], str]) -> None:
+ old = wrap(_READ_PRICE_BLOCK + _OLD_WORDING_STEPS)
+ new = wrap(_READ_PRICE_BLOCK + _NEW_WORDING_STEPS)
+
+ assert workflow_block_fingerprints(old) == workflow_block_fingerprints(new)
+
+
[email protected]("wrap", [_top_level, _inside_loop])
+def test_projection_treats_old_wording_steps_as_unchanged(wrap: Callable[[str], str]) -> None:
+ persisted = wrap(_READ_PRICE_BLOCK + _OLD_WORDING_STEPS)
+ staged = wrap(_READ_PRICE_BLOCK)
+
+ projection = build_review_projection(persisted, staged, workflow_block_fingerprints(persisted))
+
+ assert projection is not None
+ assert [(block["change"], block["coverage"]) for block in projection["blocks"]] == [
+ ("unchanged", "current_source")
+ ] * len(projection["blocks"])
+
+
def test_projection_retains_every_tested_version_when_a_block_reverts() -> None:
version_a = _workflow(""" - block_type: task
label: step
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index b63d57c81..b0d753f4f 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -14,7 +14,7 @@ from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from datetime import UTC, datetime, timezone
from types import SimpleNamespace
-from unittest.mock import ANY, AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
from playwright.async_api import Error as PlaywrightError
@@ -3188,17 +3188,28 @@ class TestClearBrowserDataHelperBinding:
@pytest.mark.asyncio
@pytest.mark.parametrize(
- ("has_own_session", "reaches_storage", "skipped"),
+ ("has_own_session", "reaches_storage", "on_page_target", "skipped"),
[
- (True, False, True),
- (True, True, False),
- (False, False, False),
+ (True, False, False, True),
+ (True, True, False, False),
+ (False, False, False, False),
+ (True, False, True, True),
+ ],
+ ids=[
+ "sandboxed_frame",
+ "real_defect",
+ "same_process_frame_cannot_be_classified",
+ "sandboxed_frame_whose_session_is_on_the_page_target",
],
- ids=["sandboxed_frame", "real_defect", "same_process_frame_cannot_be_classified"],
)
@pytest.mark.parametrize("refusal_error", [PlaywrightError, CdpError], ids=["playwright", "raw_cdp"])
async def test_a_frame_whose_clear_fails_is_skipped_only_when_it_reports_no_storage_of_its_own(
- self, has_own_session: bool, reaches_storage: bool, skipped: bool, refusal_error: type[BaseException]
+ self,
+ has_own_session: bool,
+ reaches_storage: bool,
+ on_page_target: bool,
+ skipped: bool,
+ refusal_error: type[BaseException],
) -> None:
# A sandboxed iframe has no storage area to address, so a clear that cannot find one found
# nothing to clear and the block carries on. A frame that CAN reach storage is an addressing
@@ -3221,6 +3232,8 @@ class TestClearBrowserDataHelperBinding:
context.frames_without_storage = [page]
elif not reaches_storage:
context.frames_without_storage = [embedded]
+ if on_page_target:
+ context.frames_attached_to_page_target = [(embedded, page)]
user_function = self._block().generate_async_user_function(
'await clear_browser_data(page)\nreturn {"cleared": True}\n',
@@ -3334,7 +3347,6 @@ class TestClearBrowserDataHelperBinding:
[
("Page.getFrameTree", None),
("Storage.getStorageKeyForFrame", {"frameId": "frame-of-this-session"}),
- ("Runtime.evaluate", ANY),
],
),
]
diff --git a/tests/unit/test_code_block_steps.py b/tests/unit/test_code_block_steps.py
index a467d3dc9..bebb0e7d2 100644
--- a/tests/unit/test_code_block_steps.py
+++ b/tests/unit/test_code_block_steps.py
@@ -1,11 +1,11 @@
import textwrap
+import timeit
import pytest
import yaml
from skyvern.forge.sdk.copilot.code_block_steps import (
analyze_code_actions,
- apply_derived_code_block_steps,
bind_referenced_parameters_in_yaml,
derive_code_block_steps,
derive_code_block_steps_in_yaml,
@@ -126,8 +126,7 @@ def test_derive_steps_empty_code_is_empty():
assert derive_code_block_steps("x = 1\n") == []
-async def test_apply_sets_steps_on_code_blocks_and_leaves_others_untouched():
+def test_derive_in_yaml_sets_steps_on_code_blocks_and_leaves_others_untouched():
src = {
"workflow_definition": {
"blocks": [
@@ -151,7 +150,7 @@ async def test_apply_sets_steps_on_code_blocks_and_leaves_others_untouched():
]
}
}
- out = yaml.safe_load(await apply_derived_code_block_steps(yaml.safe_dump(src)))
+ out = yaml.safe_load(derive_code_block_steps_in_yaml(yaml.safe_dump(src)))
blocks = out["workflow_definition"]["blocks"]
assert blocks[0]["steps"] == [
{"description": "Open https://x.com/", "action_type": "goto_url", "line_start": 2, "line_end": 2}
@@ -160,11 +159,6 @@ async def test_apply_sets_steps_on_code_blocks_and_leaves_others_untouched():
assert blocks[2]["loop_blocks"][0]["steps"][0]["action_type"] == "click" # nested code block annotated
-async def test_apply_is_noop_on_unparseable_yaml():
- assert await apply_derived_code_block_steps("::not yaml::") == "::not yaml::"
-
-
def test_derive_in_yaml_fills_steps_when_absent():
src = (
"workflow_definition:\n"
@@ -180,10 +174,8 @@ def test_derive_in_yaml_fills_steps_when_absent():
assert [s["action_type"] for s in steps] == ["goto_url", "click"]
-def test_derive_in_yaml_preserves_existing_steps():
- # An LLM-refined steps list must survive untouched; deterministic derivation
- # is a fallback only when steps are absent.
- refined = [{"description": "Open the homepage", "action_type": "goto_url", "line_start": 1, "line_end": 1}]
+def test_derive_in_yaml_rebuilds_stale_steps_from_code():
+ stale = [{"description": "Open the homepage", "action_type": "click", "line_start": 4, "line_end": 9}]
src = {
"workflow_definition": {
"blocks": [
@@ -191,13 +183,15 @@ def test_derive_in_yaml_preserves_existing_steps():
"block_type": "code",
"label": "block_1",
"code": "await page.goto('https://x.com/')\n",
- "steps": refined,
+ "steps": stale,
}
]
}
}
out = yaml.safe_load(derive_code_block_steps_in_yaml(yaml.safe_dump(src)))
- assert out["workflow_definition"]["blocks"][0]["steps"] == refined
+ assert out["workflow_definition"]["blocks"][0]["steps"] == [
+ {"description": "Open https://x.com/", "action_type": "goto_url", "line_start": 1, "line_end": 1}
+ ]
def test_derive_in_yaml_noop_on_unparseable():
@@ -411,27 +405,6 @@ async def test_process_workflow_yaml_binds_a_parameter_the_code_names():
assert [parameter.key for parameter in block.parameters] == ["site_login"]
-async def test_apply_derived_steps_on_copilot_yaml_shape():
- # Mirrors the _copilot_yaml payload that apply-proposed-workflow reads from
- # the stashed proposal. Steps must be populated so manual-accept persists them.
- copilot_yaml = (
- "title: Search\n"
- "workflow_definition:\n"
- " blocks:\n"
- " - block_type: code\n"
- " label: do_search\n"
- " code: |\n"
- " await page.goto('https://example.com/')\n"
- " await page.get_by_label('Query').fill(str(query))\n"
- )
- enriched = yaml.safe_load(await apply_derived_code_block_steps(copilot_yaml))
- steps = enriched["workflow_definition"]["blocks"][0]["steps"]
- assert len(steps) == 2
- assert steps[0]["action_type"] == "goto_url"
- assert steps[1]["action_type"] == "input_text"
-
-
def test_multiline_call_span_covers_all_lines():
code = "async def run(page):\n await page.get_by_label('Email').fill(\n str(email)\n )\n"
spans = analyze_code_actions(code)
@@ -483,11 +456,186 @@ def test_page_extract_is_not_a_code_block_step():
assert derive_code_block_steps(code) == []
-def test_goto_with_non_literal_url_outside_a_loop_describes_a_linked_page():
- code = "async def run(page, target_url):\n await page.goto(target_url)\n"
+def test_goto_on_a_parameter_names_the_variable():
+ code = "async def run(page, product_url):\n await page.goto(product_url)\n"
steps = derive_code_block_steps(code)
assert steps[0]["action_type"] == "goto_url"
- assert steps[0]["description"] == "Open the linked page"
+ assert steps[0]["description"] == "Open the product url"
+
+
+ ("code", "description"),
+ [
+ ("await page.goto(url='https://example.com/a')\n", "Open https://example.com/a"),
+ ("async def run(page, product_url):\n await page.goto(url=product_url)\n", "Open the product url"),
+ ("url = 'https://example.com/a'\nawait page.goto(url=url, wait_until='load')\n", "Open https://example.com/a"),
+ ],
+)
+def test_goto_with_url_keyword_is_labeled_like_the_positional_form(code, description):
+ assert derive_code_block_steps(code)[0]["description"] == description
+
+
+def test_goto_on_a_variable_bound_once_to_an_address_shows_the_address():
+ code = "async def run(page):\n url = 'https://example.com/a'\n await page.goto(url)\n"
+ assert derive_code_block_steps(code)[0]["description"] == "Open https://example.com/a"
+
+
+ "code",
+ [
+ (
+ "async def run(page):\n url = 'https://example.com/a'\n"
+ " url = 'https://example.com/b'\n await page.goto(url)\n"
+ ),
+ "async def run(page, url='https://example.com/a'):\n await page.goto(url)\n",
+ "async def run(page):\n url = 'https://example.com/a'\n url += '/b'\n await page.goto(url)\n",
+ "async def run(page):\n await page.goto(url)\n url = 'https://example.com/a'\n",
+ "async def run(page):\n url = build('https://example.com/a')\n await page.goto(url)\n",
+ "async def run(page, flag):\n if flag:\n url = 'https://example.com/a'\n await page.goto(url)\n",
+ "def helper():\n url = 'https://example.com/a'\n\nasync def run(page):\n await page.goto(url)\n",
+ ],
+)
+def test_goto_on_a_variable_without_a_single_fixed_address_names_the_variable(code):
+ assert derive_code_block_steps(code)[0]["description"] == "Open the url"
+
+
+def test_goto_address_shows_a_plain_http_address_unchanged():
+ code = "url = 'https://example.com:8443/a/b'\nawait page.goto(url)\n"
+ assert derive_code_block_steps(code)[0]["description"] == "Open https://example.com:8443/a/b"
+
+
+ "address",
+ [
+ "https://user:[email protected]/a",
+ "admin:[email protected]/login",
+ "{{ start_url }}",
+ "https://example.com/{{ path }}",
+ "https://example.com/a?token=abc",
+ "https://example.com/a#frag",
+ "ftp://example.com/a",
+ "https://example.com:99999/a",
+ ],
+)
+def test_goto_address_that_is_not_a_plain_http_address_names_the_variable(address):
+ code = f"url = {address!r}\nawait page.goto(url)\n"
+ assert derive_code_block_steps(code)[0]["description"] == "Open the url"
+
+
+def _derive_seconds(code: str) -> float:
+ # timeit pauses the garbage collector, and the best of three drops scheduler noise on shared CI runners.
+ return min(timeit.repeat(lambda: derive_code_block_steps(code), number=1, repeat=3))
+
+
+def test_many_gotos_on_variables_derive_in_linear_time():
+ def gotos(count: int) -> str:
+ return "".join(f"url_{i} = 'https://example.com/{i}'\nawait page.goto(url_{i})\n" for i in range(count))
+
+ assert derive_code_block_steps(gotos(2000))[-1]["description"] == "Open https://example.com/1999"
+ # Quadratic growth makes 4x the gotos take ~16x as long; linear stays near 4x.
+ assert _derive_seconds(gotos(2000)) < 8 * _derive_seconds(gotos(500))
+
+
+def test_unclosed_template_openers_derive_in_linear_time():
+ def commented(count: int) -> str:
+ return "await page.goto('https://example.com/a')\n" + "x = 1 # {# note {% here\n" * count
+
+ assert derive_code_block_steps(commented(2000))[0]["description"] == "Open https://example.com/a"
+ # Quadratic growth makes 4x the lines take ~16x as long; linear stays near 4x.
+ assert _derive_seconds(commented(2000)) < 8 * _derive_seconds(commented(500))
+
+
+def test_reads_chained_in_one_expression_derive_in_linear_time():
+ def chained(count: int) -> str:
+ return "total = " + " + ".join(f"await page.locator('#p{i}').inner_text()" for i in range(count)) + "\n"
+
+ # Python 3.11's parser rejects much longer chains, which would return [] and pass vacuously.
+ assert derive_code_block_steps(chained(2000))[0]["description"] == "Extract total"
+ # Quadratic growth makes 4x the reads take ~16x as long; linear stays near 4x.
+ assert _derive_seconds(chained(2000)) < 8 * _derive_seconds(chained(500))
+
+
+def test_code_too_deep_for_the_parser_derives_no_steps():
+ assert derive_code_block_steps("x = " + "-" * 200000 + "1\n") == []
+
+
+def test_goto_on_a_loop_variable_keeps_the_open_each_wording():
+ code = (
+ "async def run(page):\n url = 'https://example.com/a'\n for url in urls:\n await page.goto(url)\n"
+ )
+ assert derive_code_block_steps(code)[0]["description"] == "Open each url"
+
+
+def test_goto_on_an_expression_keeps_the_vague_wording():
+ code = "async def run(page):\n await page.goto(links[0])\n"
+ assert derive_code_block_steps(code)[0]["description"] == "Open the linked page"
+
+
+ "code, expected",
+ [
+ ("price = await page.locator('.p').inner_text()\n", "Extract price"),
+ ("price = (await page.locator('.p').inner_text()).strip()\n", "Extract price"),
+ ("status = (await page.locator('.s').text_content() or '').strip()\n", "Extract status"),
+ ("first_link = (await page.locator('a').all_text_contents())[0]\n", "Extract first link"),
+ ("price = await page.get_by_role('cell', name='Price').inner_text()\n", 'Extract price from "Price"'),
+ ("await page.get_by_label('Price').inner_text()\n", 'Extract "Price"'),
+ ("await page.get_by_label(text='Price').inner_text()\n", 'Extract "Price"'),
+ ("total = await page.get_by_text(text='Total').inner_text()\n", 'Extract total from "Total"'),
+ ("results.append(await page.locator('.row').inner_text())\n", "Extract results"),
+ ("row = {'title': await page.locator('.t').inner_text()}\n", "Extract title"),
+ ],
+)
+def test_read_is_named_from_where_the_code_stores_it_or_the_element_it_cites(code, expected):
+ assert [s["description"] for s in derive_code_block_steps(code)] == [expected]
+
+
+def test_template_control_blocks_keep_steps_and_their_line_numbers():
+ code = "{% if enabled %}\nawait page.goto('https://example.com/a')\n{% endif %}\nprice = await page.locator('.p').inner_text()\n"
+ assert [(s["description"], s["line_start"]) for s in derive_code_block_steps(code)] == [
+ ("Open https://example.com/a", 2),
+ ("Extract price", 4),
+ ]
+
+
+def test_template_comment_does_not_cost_the_block_its_steps():
+ code = "{# optional note #}\nprice = await page.locator('.p').inner_text()\n"
+ assert [(s["description"], s["line_start"]) for s in derive_code_block_steps(code)] == [("Extract price", 2)]
+
+
+ ("code", "line"),
+ [
+ ("{% if enabled %}await page.goto('https://example.com/a'){% endif %}\n", 1),
+ ("{# note #}await page.goto('https://example.com/a')\n", 1),
+ ("{% set x =\n 1 %}\nawait page.goto('https://example.com/a')\n", 3),
+ ("{% if f %}value = 1{% else %}value = 2{% endif %}\nawait page.goto('https://example.com/a')\n", 2),
+ ],
+)
+def test_python_sharing_a_line_with_a_template_tag_keeps_its_step(code, line):
+ assert [(s["description"], s["line_start"]) for s in derive_code_block_steps(code)] == [
+ ("Open https://example.com/a", line)
+ ]
+
+
+ "code",
+ [
+ "if await page.locator('.price-box').inner_text():\n pass\n",
+ "async def run(page):\n return await page.locator('.price-box').inner_text()\n",
+ "price = parse(await page.locator('.price-box').inner_text())\n",
+ "await page.locator('.price-box').inner_text()\n",
+ ],
+)
+def test_read_without_a_name_in_the_code_keeps_the_vague_wording(code):
+ assert [s["description"] for s in derive_code_block_steps(code)] == ["Extract information from the page"]
+
+
+def test_fill_value_bound_to_a_literal_never_appears_in_the_label():
+ code = "async def run(page):\n v = 'secret'\n await page.fill('#x', v)\n await page.type('#y', v)\n"
+ descriptions = [s["description"] for s in derive_code_block_steps(code)]
+ assert descriptions == ["Type into the element", "Type into the element"]
+ assert not any("secret" in d for d in descriptions)
def test_prompt_kwarg_is_preferred_as_step_copy_for_interactions():
@@ -529,23 +677,39 @@ def test_raw_dom_reads_surface_as_an_extraction_step_not_just_navigation():
" results.append({'title': title, 'href': href})\n"
)
steps = derive_code_block_steps(code)
- assert [s["action_type"] for s in steps] == ["goto_url", "extract"]
- assert steps[1]["description"] == "Extract information from the page"
+ assert [(s["action_type"], s["description"]) for s in steps] == [
+ ("goto_url", "Open https://example.com/"),
+ ("extract", "Extract title"),
+ ("extract", "Extract href"),
+ ]
-def test_consecutive_dom_reads_collapse_into_one_extraction_step():
- # A scrape reads many fields; surfacing one step per read is noise. Collapse a
- # run of adjacent reads into a single step spanning their combined line range.
+def test_consecutive_unnamed_dom_reads_collapse_into_one_extraction_step():
code = (
"async def run(page):\n"
- " a = await page.locator('#a').text_content()\n"
- " b = await page.locator('#b').inner_text()\n"
- " c = await page.locator('#c').get_attribute('value')\n"
+ " await page.locator('#a').text_content()\n"
+ " await page.locator('#b').inner_text()\n"
+ " await page.locator('#c').get_attribute('value')\n"
)
steps = derive_code_block_steps(code)
- assert [s["action_type"] for s in steps] == ["extract"]
- assert steps[0]["line_start"] == 2
- assert steps[0]["line_end"] == 4
+ assert [(s["description"], s["line_start"], s["line_end"]) for s in steps] == [
+ ("Extract information from the page", 2, 4)
+ ]
+
+
+def test_consecutive_reads_with_different_names_stay_separate_steps():
+ code = (
+ "async def run(page):\n"
+ " heading = await page.locator('h1').inner_text()\n"
+ " price = (\n"
+ " await page.locator('.price').inner_text()\n"
+ " ).strip()\n"
+ )
+ steps = derive_code_block_steps(code)
+ assert [(s["description"], s["line_start"], s["line_end"]) for s in steps] == [
+ ("Extract heading", 2, 2),
+ ("Extract price", 4, 4),
+ ]
def test_dom_reads_separated_by_an_action_are_distinct_steps():
diff --git a/tests/unit/test_mcp_legacy_manifest.py b/tests/unit/test_mcp_legacy_manifest.py
index c2c034b72..88b441bcf 100644
--- a/tests/unit/test_mcp_legacy_manifest.py
+++ b/tests/unit/test_mcp_legacy_manifest.py
@@ -126,7 +126,9 @@ LEGACY_TOOL_MANIFEST_DIGESTS = {
"skyvern_wait": "7f9b8d8d39762eaa2c2962ab3b1e4b997454d9a1039ee2fee1b5aaa07019786a",
"skyvern_wait_for_either_state": "b4b127498f91a7d9e1536d11a8993cb9d1cbf7b1557f9bec832afaa127ea1613",
"skyvern_workflow_cancel": "0ee1a599421c3a116bf09906613574807b7f0a4e7f72b6a79adf6cfb84edb3d1",
- "skyvern_workflow_create": "42dd751b5ba7607a6be052093eea1d986b03e14c02525b9741618865db666189",
+ # Re-frozen for SKY-16333: the description said a code block's `steps` outline is "derived from the code
+ # when omitted"; steps are now always rebuilt on save. Description text only; the schema is unchanged.
+ "skyvern_workflow_create": "f9062f485a05cc359f0a818ebe09b047a5b03aebc29024999188ba413e4bf692",
"skyvern_workflow_delete": "4b8b6574f78122c5d6bf8ee12f5b3cedeb83832d08462445889259cfd0c8b861",
"skyvern_workflow_get": "b9340c5d1cfa0db49431d4e914c0879f15e458d4c6d4879de0d0de653de842da",
"skyvern_workflow_list": "3b651992b2f20e020305fe308e0b1cde38d330e4dc3ee243887efaa212a2516a",
diff --git a/tests/unit/test_mcp_workflow_create_defaults.py b/tests/unit/test_mcp_workflow_create_defaults.py
index be2780776..c12a352ba 100644
--- a/tests/unit/test_mcp_workflow_create_defaults.py
+++ b/tests/unit/test_mcp_workflow_create_defaults.py
@@ -385,22 +385,18 @@ def test_code_block_steps_not_derived_without_prompt() -> None:
assert result == definition
-def test_code_block_explicit_steps_preserved() -> None:
- explicit = [{"description": "Author step", "action_type": "click", "line_start": 1, "line_end": 1}]
- definition = _code_workflow_json(
- [{"block_type": "code", "label": "step1", "code": _ACTION_CODE, "prompt": "", "steps": explicit}]
- )
- result = _inject_code_block_derived_steps(definition, "json")
- assert json.loads(result)["workflow_definition"]["blocks"][0]["steps"] == explicit
-
-
-def test_code_block_explicit_empty_steps_preserved() -> None:
- """An explicitly-supplied `steps: []` is an authored empty outline, not absence."""
+ "submitted",
+ [[{"description": "Author step", "action_type": "click", "line_start": 9, "line_end": 9}], []],
+ ids=["stale_outline", "empty_outline"],
+)
+def test_code_block_submitted_steps_are_rebuilt_from_code(submitted: list[dict[str, object]]) -> None:
definition = _code_workflow_json(
- [{"block_type": "code", "label": "step1", "code": _ACTION_CODE, "prompt": "", "steps": []}]
+ [{"block_type": "code", "label": "step1", "code": _ACTION_CODE, "prompt": "", "steps": submitted}]
)
result = _inject_code_block_derived_steps(definition, "json")
- assert json.loads(result)["workflow_definition"]["blocks"][0]["steps"] == []
+ steps = json.loads(result)["workflow_definition"]["blocks"][0]["steps"]
+ assert [step["action_type"] for step in steps] == ["goto_url", "click"]
def test_code_block_null_steps_derived() -> None:
diff --git a/tests/unit/test_workflow_persist_code_only.py b/tests/unit/test_workflow_persist_code_only.py
index fd1bce59b..43fd545a0 100644
--- a/tests/unit/test_workflow_persist_code_only.py
+++ b/tests/unit/test_workflow_persist_code_only.py
@@ -465,13 +465,20 @@ async def test_workflow_create_code_only_false_preserves_yaml_bytes(
format_name: str,
) -> None:
request_mock = _patch_skyvern_http(monkeypatch)
- # prompt and steps supplied explicitly: omitted values are now defaulted/derived (new code
- # block experience), which intentionally rewrites the definition.
+ # prompt and steps supplied as the code already derives them: omitted or stale values are
+ # defaulted/rebuilt (new code block experience), which intentionally rewrites the definition.
definition = _workflow_definition(
[
_code_block(
prompt="",
- steps=[{"description": "Open the page", "action_type": "goto_url", "line_start": 1, "line_end": 1}],
+ steps=[
+ {
+ "description": "Open https://example.com",
+ "action_type": "goto_url",
+ "line_start": 1,
+ "line_end": 1,
+ }
+ ],
)
],
proxy_location="RESIDENTIAL",
diff --git a/tests/unit/workflow/test_code_block_escalation.py b/tests/unit/workflow/test_code_block_escalation.py
index e0129abd1..524fe75e1 100644
--- a/tests/unit/workflow/test_code_block_escalation.py
+++ b/tests/unit/workflow/test_code_block_escalation.py
@@ -1315,6 +1315,18 @@ def test_steps_alone_never_manufacture_a_heal_goal(prompt: str | None) -> None:
assert block._compose_heal_goal(workflow_run_context=context, failing_line=1) == ""
+def test_failing_goto_heals_toward_its_own_url_not_an_address_in_the_step_outline() -> None:
+ block = _make_code_block(
+ code="await page.goto('https://example.com/a')\nawait page.goto('https://example.com/b')\n",
+ steps=[
+ CodeBlockStep(description="Open https://example.com/a", line_start=1, line_end=1),
+ CodeBlockStep(description="Open https://example.com/b", line_start=2, line_end=2),
+ ],
+ )
+
+ assert block._derive_escalation_navigation_url(2, _recording_page(None)) == "https://example.com/b"
+
+
def test_an_authored_goal_is_still_narrowed_by_its_matched_step() -> None:
block = _make_code_block(
steps=[CodeBlockStep(description="click the export button", line_start=1, line_end=1)],
diff --git a/tests/unit/workflow/test_code_block_schema.py b/tests/unit/workflow/test_code_block_schema.py
index f6902fdd6..e641dd65e 100644
--- a/tests/unit/workflow/test_code_block_schema.py
+++ b/tests/unit/workflow/test_code_block_schema.py
@@ -4,12 +4,12 @@ from unittest.mock import MagicMock
import pytest
from pydantic import ValidationError
+from skyvern.forge.sdk.copilot.code_block_steps import derive_code_block_steps
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
-from skyvern.forge.sdk.workflow.exceptions import WorkflowDefinitionValidationException
from skyvern.forge.sdk.workflow.models.block import CodeBlock, CodeBlockStep, ErrorCode
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
from skyvern.forge.sdk.workflow.models.workflow import WorkflowDefinition
-from skyvern.forge.sdk.workflow.workflow_definition_converter import _code_block_step_span_issue, block_yaml_to_block
+from skyvern.forge.sdk.workflow.workflow_definition_converter import block_yaml_to_block
from skyvern.schemas.workflows import CodeBlockYAML, WorkflowDefinitionYAML, _direct_code_block_error_code_raises
from skyvern.webeye.actions.action_types import ActionType
@@ -459,148 +459,6 @@ def test_error_code_manifest_accepts_normal_punctuation_and_backticks() -> None:
)
-def test_converter_coerces_step_action_type_to_enum() -> None:
- block_yaml = CodeBlockYAML(
- label="code_1",
- code="x = 1",
- steps=[
- {"description": "Open the page", "action_type": "goto_url"},
- {"description": "No explicit action type"},
- ],
- )
- block = block_yaml_to_block(block_yaml, {"code_1_output": _output_parameter()})
- assert isinstance(block, CodeBlock)
- assert block.steps is not None
- assert block.steps[0].action_type is ActionType.GOTO_URL
- assert block.steps[1].action_type is ActionType.NULL_ACTION
-
-
-def test_converter_rejects_invalid_step_action_type_with_block_context() -> None:
- block_yaml = CodeBlockYAML(
- label="code_1",
- code="x = 1",
- steps=[
- {"description": "Open the page", "action_type": "goto_url"},
- {"description": "Bad step", "action_type": "not_a_real_action"},
- ],
- )
- with pytest.raises(WorkflowDefinitionValidationException) as exc_info:
- block_yaml_to_block(block_yaml, {"code_1_output": _output_parameter()})
- message = str(exc_info.value)
- assert "code_1" in message
- assert "index 1" in message
- assert "action_type" in message
-
-
-def _convert_with_steps(code: str, steps: list[dict]) -> CodeBlock:
- block_yaml = CodeBlockYAML(label="code_1", code=code, steps=steps)
- block = block_yaml_to_block(block_yaml, {"code_1_output": _output_parameter()})
- assert isinstance(block, CodeBlock)
- return block
-
-
-def test_converter_accepts_valid_line_spans() -> None:
- block = _convert_with_steps(
- "a = 1\nb = 2\nc = 3",
- [
- {"description": "first", "action_type": "goto_url", "line_start": 1, "line_end": 2},
- {"description": "second", "action_type": "click", "line_start": 3, "line_end": 3},
- ],
- )
- assert block.steps is not None
- assert (block.steps[0].line_start, block.steps[0].line_end) == (1, 2)
- assert (block.steps[1].line_start, block.steps[1].line_end) == (3, 3)
-
-
-def test_converter_accepts_steps_without_line_spans() -> None:
- block = _convert_with_steps(
- "x = 1",
- [
- {"description": "no span", "action_type": "goto_url"},
- {"description": "still no span", "action_type": "extract"},
- ],
- )
- assert block.steps is not None
- assert block.steps[0].line_start is None and block.steps[0].line_end is None
-
-
-def test_converter_accepts_line_start_only_step() -> None:
- block = _convert_with_steps(
- "a = 1\nb = 2",
- [{"description": "lone start", "action_type": "click", "line_start": 2}],
- )
- assert block.steps is not None
- assert block.steps[0].line_start == 2 and block.steps[0].line_end is None
-
-
- "line_start, line_end, code_line_count, expect_issue",
- [
- (1, 2, 3, False),
- (2, None, 3, False),
- (None, None, 3, False),
- (None, 2, 3, True),
- (3, 2, 3, True),
- (0, 1, 3, True),
- (1, -2, 3, True),
- (1, 4, 3, True),
- (5, None, 3, True),
- ],
-)
-def test_code_block_step_span_issue(
- line_start: int | None, line_end: int | None, code_line_count: int, expect_issue: bool
-) -> None:
- step = CodeBlockStep(line_start=line_start, line_end=line_end)
- assert (_code_block_step_span_issue(step, code_line_count) is not None) == expect_issue
-
-
-def test_converter_snaps_out_of_range_span_to_synthesized_span() -> None:
- # Line 1 (x = 1) is not an action; the click is the only synthesized step, on line 2.
- block = _convert_with_steps(
- "x = 1\nawait page.click('#go')",
- [{"description": "click go", "action_type": "click", "line_start": 1, "line_end": 99}],
- )
- assert block.steps is not None
- # Snapped to the synthesized span (2, 2) rather than clamped to (1, 2).
- assert (block.steps[0].line_start, block.steps[0].line_end) == (2, 2)
- assert block.steps[0].description == "click go"
-
-
- "step",
- [
- {"description": "lone end", "action_type": "click", "line_end": 2},
- {"description": "inverted", "action_type": "click", "line_start": 3, "line_end": 2},
- {"description": "zero", "action_type": "click", "line_start": 0, "line_end": 1},
- {"description": "negative", "action_type": "click", "line_start": 1, "line_end": -2},
- {"description": "beyond end", "action_type": "click", "line_start": 1, "line_end": 9},
- {"description": "lone start beyond end", "action_type": "click", "line_start": 5},
- ],
-)
-def test_converter_drops_unrepairable_span_to_null(step: dict) -> None:
- # Action-less code has no synthesized step to snap to, so an invalid span is dropped to
- # null (the step survives as display-only metadata) instead of 422-ing the whole save.
- block = _convert_with_steps("a = 1\nb = 2\nc = 3", [step])
- assert block.steps is not None
- assert block.steps[0].line_start is None and block.steps[0].line_end is None
- assert block.steps[0].description == step["description"]
-
-
-def test_converter_preserves_valid_span_and_repairs_invalid_neighbor() -> None:
- block = _convert_with_steps(
- "await page.goto('https://example.com')\nawait page.click('#go')",
- [
- {"description": "open", "action_type": "goto_url", "line_start": 1, "line_end": 1},
- {"description": "click", "action_type": "click", "line_start": 2, "line_end": 50},
- ],
- )
- assert block.steps is not None
- # A valid span is left untouched; only the invalid neighbor is reconciled.
- assert (block.steps[0].line_start, block.steps[0].line_end) == (1, 1)
- assert (block.steps[1].line_start, block.steps[1].line_end) == (2, 2)
- assert block.steps[1].action_type is ActionType.CLICK
-
-
def test_code_block_model_roundtrip() -> None:
block = CodeBlock(
label="code_1",
@@ -643,3 +501,29 @@ def test_format_potential_template_parameters_renders_prompt() -> None:
assert block.code == "x = 1"
assert block.prompt == "Open https://example.com"
+
+
+def test_save_path_rebuilds_steps_from_code_and_discards_a_handed_in_list() -> None:
+ code = "await page.goto('https://example.com/')\nprice = await page.locator('.price').inner_text()\n"
+ block_yaml = CodeBlockYAML(
+ label="code_1",
+ code=code,
+ steps=[
+ {"description": "Click submit", "action_type": "click", "line_start": 1, "line_end": 2},
+ {"description": "Stale step", "action_type": "extract", "line_start": 2, "line_end": 2},
+ ],
+ )
+ block = block_yaml_to_block(block_yaml, {"code_1_output": _output_parameter()})
+ assert isinstance(block, CodeBlock)
+ assert block.steps is not None
+ assert [step.model_dump(mode="json") for step in block.steps] == derive_code_block_steps(code)
+ assert [step.description for step in block.steps] == ["Open https://example.com/", "Extract price"]
+
+
[email protected]("steps", [[{"line_start": "unknown"}], ["not a step"], "not a list"])
+def test_save_path_accepts_code_carrying_malformed_steps(steps: object) -> None:
+ code = "await page.goto('https://example.com/')\n"
+ block_yaml = CodeBlockYAML.model_validate({"label": "code_1", "code": code, "steps": steps})
+ block = block_yaml_to_block(block_yaml, {"code_1_output": _output_parameter()})
+ assert isinstance(block, CodeBlock)
+ assert [step.description for step in block.steps or []] == ["Open https://example.com/"]