Skip to content

Automate browser based workflows with AI

fix(SKY-11012): resolve run-only re-test against the turn's workflow_yaml (#6589)

Andrew Neilsoneaf4ec621191
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2
index f039ca032..c8c538df7 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2
@@ -28,6 +28,14 @@ USER WORKFLOW CHANGES SINCE LAST COPILOT TURN:
```
{% endif %}
+{% if runnable_draft_summary is defined and runnable_draft_summary %}
+RUNNABLE UNCOMMITTED DRAFT (not on the canvas):
+
+```
+{{ runnable_draft_summary }}
+```
+{% endif %}
+
PREVIOUS CONTEXT:
{% if chat_history %}
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 88f32a6d9..1e2d80ccc 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -606,6 +606,7 @@ def _build_user_context(
user_message: str,
request_policy_summary: str = "",
user_workflow_change_summary: str = "",
+ runnable_draft_summary: str = "",
repeated_reply_warning: str = "",
) -> str:
"""Render untrusted context into the user message with code fencing.
@@ -629,6 +630,7 @@ def _build_user_context(
request_policy_summary=escape_code_fences(redact_raw_secrets_for_prompt(request_policy_summary)),
user_message=escape_code_fences(redact_raw_secrets_for_prompt(user_message)),
user_workflow_change_summary=escape_code_fences(user_workflow_change_summary or ""),
+ runnable_draft_summary=escape_code_fences(runnable_draft_summary or ""),
repeated_reply_warning=escape_code_fences(repeated_reply_warning or ""),
)
@@ -3036,6 +3038,7 @@ async def _run_copilot_turn_impl(
turn_id=turn_id,
turn_index=turn_index,
prior_block_count=prior_block_count,
+ prior_copilot_workflow_yaml=prior_copilot_workflow_yaml,
block_authoring_policy=copilot_config.block_authoring_policy,
impose_synthesized_code_block=copilot_config.impose_synthesized_code_block,
)
@@ -3202,10 +3205,13 @@ async def _run_copilot_turn_impl(
)
user_workflow_change_summary = ""
+ runnable_draft_summary = ""
repeated_reply_warning = ""
if isinstance(ctx.turn_context_packet, TurnContextPacket):
if ctx.turn_context_packet.workflow_change_context is not None:
user_workflow_change_summary = ctx.turn_context_packet.workflow_change_context.rendered_summary
+ if ctx.turn_context_packet.runnable_draft_context is not None:
+ runnable_draft_summary = ctx.turn_context_packet.runnable_draft_context.rendered_summary
if ctx.turn_context_packet.repeated_reply_context is not None:
repeated_reply_warning = ctx.turn_context_packet.repeated_reply_context.rendered_summary
@@ -3216,6 +3222,7 @@ async def _run_copilot_turn_impl(
debug_run_info_text=redact_raw_secrets_for_prompt(debug_run_info_text),
user_message=agent_user_message,
user_workflow_change_summary=user_workflow_change_summary,
+ runnable_draft_summary=runnable_draft_summary,
repeated_reply_warning=repeated_reply_warning,
)
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 4a8dc93ab..e2c22c8ae 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -545,6 +545,8 @@ class CopilotContext(AgentContext):
staged_workflow_yaml: str | None = None
staged_workflow: Workflow | None = None
has_staged_proposal: bool = False
+ # Prior turn's uncommitted draft; carries blocks even when the request body and canonical row are empty.
+ prior_copilot_workflow_yaml: str | None = None
# Set when ``_update_workflow`` wrote canonical mid-turn (param / top-level
# settings changes); terminal handlers roll back on non-auto-accept.
canonical_was_persisted_due_to_param_change: bool = False
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 931d3f1c1..f84bbf1d8 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -207,6 +207,8 @@ class AgentContext:
staged_workflow_yaml: str | None = None
staged_workflow: Any | None = None
has_staged_proposal: bool = False
+ # Prior turn's uncommitted draft; carries blocks even when the request body and canonical row are empty.
+ prior_copilot_workflow_yaml: str | None = None
canonical_was_persisted_due_to_param_change: bool = False
allow_untested_workflow_draft: bool = False
request_policy: RequestPolicy | None = None
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 6f7b3ea60..1897a6d0d 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -12,6 +12,8 @@ from typing import Any, Literal
from urllib.parse import urlparse
import structlog
+import yaml
+from pydantic import ValidationError
from skyvern.forge import app
from skyvern.forge.sdk.artifact.models import ArtifactType
@@ -57,9 +59,11 @@ from skyvern.forge.sdk.copilot.runtime import (
)
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
from skyvern.forge.sdk.copilot.turn_halt import stash_turn_halt_from_blocker_signal
+from skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yaml
from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotRunOutcomeUpdate, WorkflowCopilotStreamMessageType
from skyvern.forge.sdk.settings_manager import SettingsManager
-from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunStatus
+from skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException
+from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatus
from skyvern.schemas.workflows import BlockType
from skyvern.webeye.navigation import is_skip_inner_retry_error
from skyvern.webeye.utils.page import SkyvernFrame
@@ -614,6 +618,38 @@ def _watchdog_user_facing_summary(
return "The run ended before recording a trustworthy terminal status."
+def _workflow_covers_labels(workflow: Workflow | None, labels: list[str]) -> bool:
+ return workflow is not None and all(workflow.get_output_parameter(label) for label in labels)
+
+
+def _workflow_has_blocks(workflow: Workflow | None) -> bool:
+ if workflow is None:
+ return False
+ definition = workflow.workflow_definition
+ if isinstance(definition, dict):
+ return bool(definition.get("blocks"))
+ return bool(definition.blocks)
+
+
+def _workflow_from_prior_draft(ctx: CopilotContext, labels: list[str]) -> Workflow | None:
+ """Returns None on empty/malformed yaml or when it still misses a label, so the
+ caller falls through to the existing not-found error."""
+ workflow_yaml = ctx.prior_copilot_workflow_yaml
+ if not workflow_yaml or not workflow_yaml.strip():
+ return None
+ try:
+ workflow = _process_workflow_yaml(
+ workflow_id=ctx.workflow_id,
+ workflow_permanent_id=ctx.workflow_permanent_id,
+ organization_id=ctx.organization_id,
+ workflow_yaml=workflow_yaml,
+ )
+ except (yaml.YAMLError, ValidationError, BaseWorkflowHTTPException):
+ LOG.warning("Could not parse prior copilot draft for run-tool label resolution", exc_info=True)
+ return None
+ return workflow if _workflow_covers_labels(workflow, labels) else None
+
+
async def _run_blocks_and_collect_debug(
params: dict[str, Any],
ctx: CopilotContext,
@@ -651,6 +687,14 @@ async def _run_blocks_and_collect_debug(
workflow_permanent_id=ctx.workflow_permanent_id,
organization_id=ctx.organization_id,
)
+ # Only an empty workflow borrows the uncommitted prior draft (ctx.prior_copilot_workflow_yaml);
+ # a populated workflow missing a requested label still reports not-found.
+ resolved_from_prior_draft = False
+ if not _workflow_has_blocks(workflow):
+ prior_draft_workflow = _workflow_from_prior_draft(ctx, block_labels)
+ if prior_draft_workflow is not None:
+ workflow = prior_draft_workflow
+ resolved_from_prior_draft = True
if not workflow:
return {"ok": False, "error": f"Workflow not found: {ctx.workflow_permanent_id}"}
@@ -702,7 +746,12 @@ async def _run_blocks_and_collect_debug(
# Short-circuit before a wasted workflow execution when the definition
# JSON has drifted from the persisted parameter rows that runtime reads.
- invariant_error = _parameter_binding_invariant_error(workflow, all_workflow_params, all_output_params)
+ # Skipped for the prior-draft fallback: its in-memory params differ from the rolled-back canonical rows by design.
+ invariant_error = (
+ None
+ if resolved_from_prior_draft
+ else _parameter_binding_invariant_error(workflow, all_workflow_params, all_output_params)
+ )
if invariant_error is not None:
summary, missing_persisted, missing_from_definition = invariant_error
return {
diff --git a/skyvern/forge/sdk/copilot/turn_context.py b/skyvern/forge/sdk/copilot/turn_context.py
index 856f75258..3a5f2575a 100644
--- a/skyvern/forge/sdk/copilot/turn_context.py
+++ b/skyvern/forge/sdk/copilot/turn_context.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from typing import Any, Literal
import structlog
+import yaml
from pydantic import BaseModel, ConfigDict, Field
from skyvern.forge.sdk.copilot.repeated_reply_summary import RepeatedReplyKind, summarize_repeated_replies
@@ -15,6 +16,7 @@ from skyvern.forge.sdk.copilot.turn_intent import RequiredContextKey, TurnIntent
from skyvern.forge.sdk.copilot.workflow_change_summary import WorkflowChangeKind, summarize_user_workflow_change
from skyvern.forge.sdk.schemas.credentials import Credential
from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatHistoryMessage, WorkflowCopilotChatSender
+from skyvern.utils.yaml_loader import safe_load_no_dates
LOG = structlog.get_logger()
@@ -54,6 +56,11 @@ class WorkflowChangeContext(BaseModel):
structural_diff_unavailable: bool = False
+class RunnableDraftContext(BaseModel):
+ rendered_summary: str
+ block_labels: list[str] = Field(default_factory=list)
+
+
class RepeatedReplyContext(BaseModel):
kind: RepeatedReplyKind
rendered_summary: str
@@ -101,6 +108,7 @@ class TurnContextPacket(BaseModel):
workflow_context: WorkflowContext | None = None
proposal_context: ProposalContext | None = None
workflow_change_context: WorkflowChangeContext | None = None
+ runnable_draft_context: RunnableDraftContext | None = None
transcript_context: TranscriptContext
run_context: RunContext | None = None
credential_context: CredentialContext | None = None
@@ -113,6 +121,7 @@ class TurnContextPacket(BaseModel):
"workflow_context",
"proposal_context",
"workflow_change_context",
+ "runnable_draft_context",
"run_context",
"credential_context",
"docs_context",
@@ -159,6 +168,28 @@ def _bounded_text(value: str, char_budget: int) -> tuple[str, int, bool]:
return redacted[: char_budget - len(suffix)].rstrip() + suffix, original_chars, True
+def _top_level_block_labels(workflow_yaml: str) -> list[str]:
+ try:
+ parsed = safe_load_no_dates(workflow_yaml)
+ except yaml.YAMLError:
+ return []
+ if not isinstance(parsed, dict):
+ return []
+ definition = parsed.get("workflow_definition")
+ if not isinstance(definition, dict):
+ return []
+ blocks = definition.get("blocks")
+ if not isinstance(blocks, list):
+ return []
+ labels: list[str] = []
+ for block in blocks:
+ if isinstance(block, dict):
+ label = block.get("label")
+ if isinstance(label, str) and label:
+ labels.append(label)
+ return labels
+
+
def _latest_assistant_turn(chat_history: list[WorkflowCopilotChatHistoryMessage]) -> str:
for message in reversed(chat_history):
if message.sender == WorkflowCopilotChatSender.AI and (message.content or "").strip():
@@ -206,6 +237,7 @@ class TurnContextAssembler:
workflow_context: WorkflowContext | None = None
proposal_context: ProposalContext | None = None
workflow_change_context: WorkflowChangeContext | None = None
+ runnable_draft_context: RunnableDraftContext | None = None
run_context: RunContext | None = None
credential_context: CredentialContext | None = None
docs_context: DocsContext | None = None
@@ -275,6 +307,8 @@ class TurnContextAssembler:
structural_diff_unavailable=change_summary.structural_diff_unavailable,
)
+ runnable_draft_context = self._runnable_draft_context(inputs)
+
if self._should_include_run_context(inputs.turn_intent, required):
if inputs.debug_run_info_text.strip():
summary, original_chars, truncated = _bounded_text(inputs.debug_run_info_text, self.run_char_budget)
@@ -323,6 +357,7 @@ class TurnContextAssembler:
workflow_context=workflow_context,
proposal_context=proposal_context,
workflow_change_context=workflow_change_context,
+ runnable_draft_context=runnable_draft_context,
transcript_context=transcript_context,
run_context=run_context,
credential_context=credential_context,
@@ -346,6 +381,23 @@ class TurnContextAssembler:
intent.mode in _WORKFLOW_MODES and intent.authority.may_update_workflow
)
+ def _runnable_draft_context(self, inputs: TurnContextInputs) -> RunnableDraftContext | None:
+ if not inputs.turn_intent.authority.may_run_blocks:
+ return None
+ if _top_level_block_labels(inputs.workflow_yaml):
+ return None
+ labels = _top_level_block_labels(inputs.prior_workflow_yaml)
+ if not labels:
+ return None
+ labels_csv = ", ".join(labels)
+ summary = (
+ "A prior turn proposed a workflow draft that was never committed to the canvas, so the"
+ " CURRENT WORKFLOW YAML above is empty. The user is asking to run/re-test that draft. To"
+ " run it, call run_blocks_and_collect_debug with these block labels: "
+ f"{labels_csv}. Do not call update_and_run_blocks and do not ask the user to rebuild it."
+ )
+ return RunnableDraftContext(rendered_summary=summary, block_labels=labels)
+
def _should_include_run_context(self, intent: TurnIntent, required: set[RequiredContextKey]) -> bool:
if intent.mode == TurnIntentMode.DOCS_ANSWER:
return False