Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-11729): migrate self-healing enablement from PostHog to a workflow setting (#7041)
pedrohsdb6d63c5508e0f
diff --git a/alembic/versions/2026_07_03_0333-2ac47bc1c075_add_enable_self_healing_to_workflows.py b/alembic/versions/2026_07_03_0333-2ac47bc1c075_add_enable_self_healing_to_workflows.pynew file mode 100644index 000000000..3217cbd8b--- /dev/null+++ b/alembic/versions/2026_07_03_0333-2ac47bc1c075_add_enable_self_healing_to_workflows.py@@ -0,0 +1,30 @@+"""add enable_self_healing to workflows++Revision ID: 2ac47bc1c075+Revises: ecf365563e98+Create Date: 2026-07-03T03:33:20.863940+00:00++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "2ac47bc1c075"+down_revision: Union[str, None] = "ecf365563e98"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.add_column(+ "workflows",+ sa.Column("enable_self_healing", sa.Boolean(), nullable=False, server_default=sa.false()),+ )+++def downgrade() -> None:+ op.drop_column("workflows", "enable_self_healing")diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.jsonindex adc135536..8e3352142 100644--- a/docs/api-reference/openapi.json+++ b/docs/api-reference/openapi.json@@ -10229,6 +10229,7 @@],"description": "Which vault to store this credential in. If omitted, uses the instance default. Use this to mix Skyvern-hosted and custom credentials within the same organization.","examples": [+ "skyvern","custom","azure_vault","bitwarden"@@ -24059,6 +24060,11 @@"title": "Adaptive Caching","default": false},+ "enable_self_healing": {+ "type": "boolean",+ "title": "Enable Self Healing",+ "default": false+ },"code_version": {"anyOf": [{@@ -24141,6 +24147,11 @@],"title": "Edited By"},+ "copilot_authored": {+ "type": "boolean",+ "title": "Copilot Authored",+ "default": false+ },"created_at": {"type": "string","format": "date-time",@@ -24383,6 +24394,17 @@"title": "Adaptive Caching","default": false},+ "enable_self_healing": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "title": "Enable Self Healing"+ },"code_version": {"anyOf": [{diff --git a/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsx b/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsxindex 2a7072d1b..620005e2e 100644--- a/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsx+++ b/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsx@@ -989,7 +989,7 @@ function RunWorkflowForm({<FormLabel><div className="w-72"><div className="flex items-center gap-2 text-lg">- AI Fallback (self-healing)+ AI Fallback (cached scripts)</div><h2 className="text-sm text-slate-400">If the run fails when running with code, keep this ondiff --git a/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx b/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsxindex 45da5a585..d58a131ea 100644--- a/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx+++ b/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx@@ -118,6 +118,7 @@ function getWorkflowElements(version: WorkflowVersion) {codeVersion: version.code_version ?? null,scriptCacheKey: version.cache_key,aiFallback: version.ai_fallback ?? true,+ enableSelfHealing: version.enable_self_healing ?? false,runSequentially: version.run_sequentially ?? false,sequentialKey: version.sequential_key ?? null,finallyBlockLabel: version.workflow_definition?.finally_block_label ?? null,diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex 8120192cd..d4ffcb52b 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -1350,6 +1350,7 @@ export function WorkflowCopilotChat({run_with: saveData.settings.runWith,cache_key: normalizedKey,ai_fallback: saveData.settings.aiFallback ?? true,+ enable_self_healing: saveData.settings.enableSelfHealing ?? false,code_version:saveData.settings.runWith === "code"? (saveData.settings.codeVersion ?? 2)diff --git a/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx b/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsxindex 99f73e3f2..af38ee440 100644--- a/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx+++ b/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx@@ -87,6 +87,7 @@ function Debugger() {codeVersion: workflow.code_version ?? null,scriptCacheKey: workflow.cache_key,aiFallback: workflow.ai_fallback ?? true,+ enableSelfHealing: workflow.enable_self_healing ?? false,runSequentially: workflow.run_sequentially ?? false,sequentialKey: workflow.sequential_key ?? null,finallyBlockLabel:diff --git a/skyvern-frontend/src/routes/workflows/defaultWorkflowRequest.ts b/skyvern-frontend/src/routes/workflows/defaultWorkflowRequest.tsindex 1b2189f40..908646aa6 100644--- a/skyvern-frontend/src/routes/workflows/defaultWorkflowRequest.ts+++ b/skyvern-frontend/src/routes/workflows/defaultWorkflowRequest.ts@@ -4,6 +4,7 @@ const defaultWorkflowRequest: WorkflowCreateYAMLRequest = {title: "New Agent",description: "",ai_fallback: true,+ enable_self_healing: false,code_version: 2,run_with: "agent",workflow_definition: {diff --git a/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsxindex ee328f51f..57c9c892e 100644--- a/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx@@ -87,6 +87,7 @@ function WorkflowEditor() {codeVersion: workflow.code_version ?? null,scriptCacheKey: workflow.cache_key,aiFallback: workflow.ai_fallback ?? true,+ enableSelfHealing: workflow.enable_self_healing ?? false,runSequentially: workflow.run_sequentially ?? false,sequentialKey: workflow.sequential_key ?? null,finallyBlockLabel:diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsxindex 80e60b5b7..8030d969f 100644--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx@@ -1528,6 +1528,7 @@ function Workspace({codeVersion: workflowData.code_version ?? null,scriptCacheKey: workflowData.cache_key ?? null,aiFallback: workflowData.ai_fallback ?? true,+ enableSelfHealing: workflowData.enable_self_healing ?? false,runSequentially: workflowData.run_sequentially ?? false,sequentialKey: workflowData.sequential_key ?? null,finallyBlockLabel:@@ -1805,6 +1806,7 @@ function Workspace({codeVersion: selectedVersion.code_version ?? null,scriptCacheKey: selectedVersion.cache_key,aiFallback: selectedVersion.ai_fallback ?? true,+ enableSelfHealing: selectedVersion.enable_self_healing ?? false,runSequentially: selectedVersion.run_sequentially ?? false,sequentialKey: selectedVersion.sequential_key ?? null,finallyBlockLabel:@@ -2785,6 +2787,7 @@ function Workspace({run_with: saveData.settings.runWith,cache_key: saveData.settings.scriptCacheKey,ai_fallback: saveData.settings.aiFallback,+ enable_self_healing: saveData.settings.enableSelfHealing ?? false,adaptive_caching: false,code_version:saveData.settings.runWith === "code"diff --git a/skyvern-frontend/src/routes/workflows/editor/nestedConditionalSave.test.ts b/skyvern-frontend/src/routes/workflows/editor/nestedConditionalSave.test.tsindex 0e4c1676c..0ab9aca3e 100644--- a/skyvern-frontend/src/routes/workflows/editor/nestedConditionalSave.test.ts+++ b/skyvern-frontend/src/routes/workflows/editor/nestedConditionalSave.test.ts@@ -31,6 +31,7 @@ const DEFAULT_SETTINGS: WorkflowSettings = {codeVersion: 2,scriptCacheKey: null,aiFallback: true,+ enableSelfHealing: false,runSequentially: false,sequentialKey: null,finallyBlockLabel: null,diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.test.tsxindex f4955fff5..f07738ec3 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.test.tsx@@ -58,6 +58,7 @@ const startNodeData: WorkflowStartNodeData = {codeVersion: null,scriptCacheKey: null,aiFallback: true,+ enableSelfHealing: false,runSequentially: false,sequentialKey: null,finallyBlockLabel: null,diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.test.tsxindex 31f419646..a882c0406 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.test.tsx@@ -1,5 +1,6 @@// @vitest-environment jsdom+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { cleanup, fireEvent, render, screen } from "@testing-library/react";import type { ReactNode } from "react";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";@@ -24,6 +25,7 @@ const startNodeData: WorkflowStartNodeData = {codeVersion: null,scriptCacheKey: null,aiFallback: true,+ enableSelfHealing: false,runSequentially: false,sequentialKey: null,finallyBlockLabel: null,@@ -150,7 +152,14 @@ function renderSettings(overrides: Partial<WorkflowStartNodeData> = {}) {...startNodeData,...overrides,};- return render(<WorkflowSettingsEditor blockId="start" />);+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <WorkflowSettingsEditor blockId="start" />+ </QueryClientProvider>,+ );}beforeEach(() => {diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.tsxindex 80787eca0..eb6bb47b6 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.tsx@@ -20,6 +20,7 @@ import {DialogTitle,DialogTrigger,} from "@/components/ui/dialog";+import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -33,6 +34,8 @@ import {import { Switch } from "@/components/ui/switch";import { useResetProfileMutation } from "@/routes/workflows/hooks/useResetProfileMutation";+import { useWorkflowQuery } from "@/routes/workflows/hooks/useWorkflowQuery";+import { useWorkflowStudioEnabled } from "@/hooks/useWorkflowStudioEnabled";import { placeholders } from "../../helpContent";import { useUpdate } from "../../useUpdate";@@ -86,6 +89,13 @@ function WorkflowSettingsEditorBody({const nodes = useNodes<AppNode>();const edges = useEdges();const update = useUpdate<StartNode["data"]>({ id: blockId, editable: true });+ const studioEnabled = useWorkflowStudioEnabled();+ const { data: workflow } = useWorkflowQuery({ workflowPermanentId });+ // Self-healing is restricted to copilot-authored workflows; hide the toggle+ // elsewhere so it never reads as a switch that silently does nothing.+ // copilot_authored is lineage-derived server-side — the current version's+ // created_by/edited_by get re-stamped by user saves and are not durable.+ const copilotAuthored = workflow?.copilot_authored === true;const [localWebhookUrl, setLocalWebhookUrl] = useState(data.webhookCallbackUrl,@@ -221,8 +231,8 @@ function WorkflowSettingsEditorBody({</div><div className="space-y-2"><div className="flex items-center gap-2">- <Label>AI Fallback (self-healing)</Label>- <HelpTooltip content="If a run with code fails, fallback to AI and regenerate the code." />+ <Label>AI Fallback (cached scripts)</Label>+ <HelpTooltip content="If a cached-script run fails, fall back to AI and regenerate the script." /><SwitchclassName="ml-auto"checked={data.aiFallback}@@ -230,6 +240,24 @@ function WorkflowSettingsEditorBody({/></div></div>+ {studioEnabled && copilotAuthored && (+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <Label>Code Block Self-Healing</Label>+ <Badge variant="warning" className="px-1.5 py-0.5 text-[10px]">+ Beta+ </Badge>+ <HelpTooltip content="If a code block fails on a changed page, an AI agent takes over the live browser to finish that block's goal, then the run continues." />+ <Switch+ className="ml-auto"+ checked={data.enableSelfHealing}+ onCheckedChange={(value) =>+ update({ enableSelfHealing: value })+ }+ />+ </div>+ </div>+ )}<div className="space-y-2"><div className="flex gap-2"><Label>Code Key (optional)</Label>diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/types.tsindex 4257e6ef7..2510435d6 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/types.ts+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/types.ts@@ -20,6 +20,7 @@ export type WorkflowStartNodeData = {codeVersion: number | null;scriptCacheKey: string | null;aiFallback: boolean;+ enableSelfHealing: boolean;runSequentially: boolean;sequentialKey: string | null;finallyBlockLabel: string | null;diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/WorkflowSettingsBlockForm.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/WorkflowSettingsBlockForm.tsxindex 15533b71b..8466e6b32 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/WorkflowSettingsBlockForm.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/WorkflowSettingsBlockForm.tsx@@ -34,6 +34,7 @@ function WorkflowSettingsBlockFormBody({proxyLocation: data.proxyLocation,runWith: data.runWith,aiFallback: data.aiFallback,+ enableSelfHealing: data.enableSelfHealing,scriptCacheKey: data.scriptCacheKey,runSequentially: data.runSequentially,sequentialKey: data.sequentialKey,diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsxindex 735bf381b..1588e8e1b 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx@@ -154,6 +154,7 @@ function getWorkflowElements(version: WorkflowVersion) {codeVersion: version.code_version ?? null,scriptCacheKey: version.cache_key,aiFallback: version.ai_fallback ?? true,+ enableSelfHealing: version.enable_self_healing ?? false,runSequentially: version.run_sequentially ?? false,sequentialKey: version.sequential_key ?? null,finallyBlockLabel: version.workflow_definition?.finally_block_label ?? null,diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts b/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.tsindex cd80eddca..e40c95774 100644--- a/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts@@ -60,6 +60,7 @@ const DEFAULT_SETTINGS: WorkflowSettings = {codeVersion: 2,scriptCacheKey: null,aiFallback: true,+ enableSelfHealing: false,runSequentially: false,sequentialKey: null,finallyBlockLabel: null,diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts b/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.tsindex cf565b0a0..b10f935ad 100644--- a/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts@@ -54,6 +54,7 @@ const DEFAULT_SETTINGS: WorkflowSettings = {codeVersion: 2,scriptCacheKey: null,aiFallback: true,+ enableSelfHealing: false,runSequentially: false,sequentialKey: null,finallyBlockLabel: null,diff --git a/skyvern-frontend/src/routes/workflows/editor/utils.test.ts b/skyvern-frontend/src/routes/workflows/editor/utils.test.tsindex 6a6f4f8a7..88e1d15a9 100644--- a/skyvern-frontend/src/routes/workflows/editor/utils.test.ts+++ b/skyvern-frontend/src/routes/workflows/editor/utils.test.ts@@ -41,6 +41,7 @@ const baseWorkflow = {run_with: "agent",cache_key: null,ai_fallback: true,+ enable_self_healing: false,adaptive_caching: null,code_version: null,run_sequentially: false,diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.tsindex ce73d66ee..b91e1b954 100644--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts@@ -1998,6 +1998,7 @@ function getElements(codeVersion: settings.codeVersion,scriptCacheKey: settings.scriptCacheKey,aiFallback: settings.aiFallback ?? true,+ enableSelfHealing: settings.enableSelfHealing ?? false,label: "__start_block__",showCode: false,runSequentially: settings.runSequentially,@@ -3415,6 +3416,7 @@ function getWorkflowSettings(nodes: Array<AppNode>): WorkflowSettings {codeVersion: 2,scriptCacheKey: null,aiFallback: true,+ enableSelfHealing: false,runSequentially: false,sequentialKey: null,finallyBlockLabel: null,@@ -3451,6 +3453,7 @@ function getWorkflowSettings(nodes: Array<AppNode>): WorkflowSettings {codeVersion: data.codeVersion,scriptCacheKey: data.scriptCacheKey,aiFallback: data.aiFallback,+ enableSelfHealing: data.enableSelfHealing,runSequentially: data.runSequentially,sequentialKey: data.sequentialKey,finallyBlockLabel: data.finallyBlockLabel ?? null,@@ -4543,6 +4546,7 @@ function convert(workflow: WorkflowApiResponse): WorkflowCreateYAMLRequest {code_version: workflow.code_version ?? undefined,cache_key: workflow.cache_key,ai_fallback: workflow.ai_fallback ?? undefined,+ enable_self_healing: workflow.enable_self_healing ?? undefined,run_sequentially: workflow.run_sequentially ?? undefined,sequential_key: workflow.sequential_key ?? undefined,};diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowVersionFromSaveData.ts b/skyvern-frontend/src/routes/workflows/editor/workflowVersionFromSaveData.tsindex 6e4d55a90..2c10ae4b9 100644--- a/skyvern-frontend/src/routes/workflows/editor/workflowVersionFromSaveData.ts+++ b/skyvern-frontend/src/routes/workflows/editor/workflowVersionFromSaveData.ts@@ -62,6 +62,7 @@ export function workflowVersionFromSaveData(run_with: settings.runWith,cache_key: settings.scriptCacheKey,ai_fallback: settings.aiFallback,+ enable_self_healing: settings.enableSelfHealing ?? false,adaptive_caching: workflow.adaptive_caching ?? false,code_version:settings.runWith === "code" ? (settings.codeVersion ?? 2) : null,diff --git a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowTypes.tsindex 2a4539afc..d0a5f719b 100644--- a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts@@ -675,12 +675,16 @@ export type WorkflowApiResponse = {run_with: string; // 'agent' or 'code'cache_key: string | null;ai_fallback: boolean | null;+ enable_self_healing: boolean | null;adaptive_caching: boolean | null;code_version: number | null;run_sequentially: boolean | null;sequential_key: string | null;folder_id: string | null;import_error: string | null;+ created_by?: string | null;+ edited_by?: string | null;+ copilot_authored?: boolean | null;};export type WorkflowSettings = {@@ -698,6 +702,7 @@ export type WorkflowSettings = {codeVersion: number | null;scriptCacheKey: string | null;aiFallback: boolean | null;+ enableSelfHealing: boolean | null;runSequentially: boolean;sequentialKey: string | null;finallyBlockLabel: string | null;diff --git a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.tsindex fbe0bdfe9..fd36578e5 100644--- a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts@@ -25,6 +25,7 @@ export type WorkflowCreateYAMLRequest = {run_with?: string | null;cache_key?: string | null;ai_fallback?: boolean;+ enable_self_healing?: boolean;adaptive_caching?: boolean;code_version?: number | null;run_sequentially?: boolean;diff --git a/skyvern-frontend/src/store/WorkflowHasChangesStore.ts b/skyvern-frontend/src/store/WorkflowHasChangesStore.tsindex f1430d546..ed5067a87 100644--- a/skyvern-frontend/src/store/WorkflowHasChangesStore.ts+++ b/skyvern-frontend/src/store/WorkflowHasChangesStore.ts@@ -204,6 +204,7 @@ const useWorkflowSave = (opts?: WorkflowSaveOpts) => {run_with: saveData.settings.runWith,cache_key: normalizedKey,ai_fallback: saveData.settings.aiFallback ?? true,+ enable_self_healing: saveData.settings.enableSelfHealing ?? false,code_version:saveData.settings.runWith === "code"? (saveData.settings.codeVersion ?? 2)diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 6ac2c773f..b9bf0380e 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -2920,11 +2920,12 @@ async def _translate_to_agent_result(workflow_yaml, ctx.last_workflow_yaml or ctx.workflow_yaml)try:- last_workflow = _process_workflow_yaml(+ last_workflow = await _process_workflow_yaml(workflow_id=chat_request.workflow_id,workflow_permanent_id=chat_request.workflow_permanent_id,organization_id=organization_id,workflow_yaml=workflow_yaml,+ settings_fallback_yaml=ctx.last_workflow_yaml or ctx.workflow_yaml,)last_workflow_yaml = workflow_yamlexcept (yaml.YAMLError, ValidationError, BaseWorkflowHTTPException) as e:diff --git a/skyvern/forge/sdk/copilot/tools/frontier.py b/skyvern/forge/sdk/copilot/tools/frontier.pyindex 1f0433d48..6d719c6a5 100644--- a/skyvern/forge/sdk/copilot/tools/frontier.py+++ b/skyvern/forge/sdk/copilot/tools/frontier.py@@ -9,14 +9,12 @@ from typing import Anyfrom urllib.parse import urlparseimport structlog-import yamltry:from bs4 import BeautifulSoup # type: ignore[import-not-found]except ImportError: # pragma: no cover — bs4 is a transitive dep but discovery degrades gracefully without it.BeautifulSoup = None # type: ignore[assignment, misc]from jinja2.sandbox import SandboxedEnvironment-from pydantic import ValidationErrorfrom skyvern.forge import appfrom skyvern.forge.sdk.copilot.block_goal_wrapping import wrap_workflow_block_goals@@ -31,7 +29,6 @@ from skyvern.forge.sdk.copilot.runtime import (AgentContext,)from skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yaml-from skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPExceptionfrom skyvern.forge.sdk.workflow.models.block import BlockTypeVar, get_all_blocksfrom skyvern.forge.sdk.workflow.models.parameter import (RESERVED_PARAMETER_KEYS,@@ -555,14 +552,15 @@ async def _get_prior_workflow_definition(ctx: AgentContext) -> object | None:last_yaml = getattr(ctx, "last_workflow_yaml", None)if last_yaml:try:- workflow = _process_workflow_yaml(+ workflow = await _process_workflow_yaml(workflow_id=ctx.workflow_id,workflow_permanent_id=ctx.workflow_permanent_id,organization_id=ctx.organization_id,workflow_yaml=last_yaml,)return workflow.workflow_definition- except (yaml.YAMLError, ValidationError, BaseWorkflowHTTPException):+ except Exception:+ # Prior-parse is best-effort; a settings-inherit lookup failure must not break diffs.passtry:fetched = await app.DATABASE.workflows.get_workflow_by_permanent_id(@@ -584,13 +582,14 @@ async def _get_prior_workflow(ctx: AgentContext) -> Workflow | None:last_yaml = ctx.last_workflow_yamlif last_yaml:try:- return _process_workflow_yaml(+ return await _process_workflow_yaml(workflow_id=ctx.workflow_id,workflow_permanent_id=ctx.workflow_permanent_id,organization_id=ctx.organization_id,workflow_yaml=last_yaml,)- except (yaml.YAMLError, ValidationError, BaseWorkflowHTTPException):+ except Exception:+ # Prior-parse is best-effort; a settings-inherit lookup failure must not break diffs.passtry:return await app.DATABASE.workflows.get_workflow_by_permanent_id(@@ -625,6 +624,7 @@ _CANONICAL_WORKFLOW_SETTING_FIELDS: tuple[str, ...] = ("ai_fallback","cache_key","adaptive_caching",+ "enable_self_healing","code_version","run_sequentially","sequential_key",diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex 6040b31ca..7d6f6389d 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -12,8 +12,6 @@ from typing import Any, Literalfrom urllib.parse import urlparseimport structlog-import yaml-from pydantic import ValidationErrorfrom skyvern.config import settingsfrom skyvern.forge import app@@ -110,7 +108,6 @@ from skyvern.forge.sdk.executor.factory import AsyncExecutorFactoryfrom skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yamlfrom skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotRunOutcomeUpdate, WorkflowCopilotStreamMessageTypefrom skyvern.forge.sdk.settings_manager import SettingsManager-from skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPExceptionfrom skyvern.forge.sdk.workflow.models.block import CodeBlockfrom skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatusfrom skyvern.schemas.workflows import BlockType@@ -765,20 +762,21 @@ def _workflow_has_blocks(workflow: Workflow | None) -> bool:return bool(definition.blocks)-def _workflow_from_prior_draft(ctx: CopilotContext, labels: list[str]) -> Workflow | None:+async 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 thecaller falls through to the existing not-found error."""workflow_yaml = ctx.prior_copilot_workflow_yamlif not workflow_yaml or not workflow_yaml.strip():return Nonetry:- workflow = _process_workflow_yaml(+ workflow = await _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):+ except Exception:+ # Prior-parse is best-effort; a settings-inherit lookup failure must not block the run tool.LOG.warning("Could not parse prior copilot draft for run-tool label resolution", exc_info=True)return Nonereturn workflow if _workflow_covers_labels(workflow, labels) else None@@ -1153,7 +1151,7 @@ async def _run_blocks_and_collect_debug(# a populated workflow missing a requested label still reports not-found.resolved_from_prior_draft = Falseif not _workflow_has_blocks(workflow):- prior_draft_workflow = _workflow_from_prior_draft(ctx, block_labels)+ prior_draft_workflow = await _workflow_from_prior_draft(ctx, block_labels)if prior_draft_workflow is not None:workflow = prior_draft_workflowresolved_from_prior_draft = Truediff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex 14fbcb510..8fd25df5d 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -5396,11 +5396,12 @@ async def _update_workflow(# Derive plain-language steps from each code block's code so the editor timeline# mirrors the actual code (deterministic action_type + line ranges).workflow_yaml_with_steps = await apply_derived_code_block_steps(workflow_yaml)- workflow = _process_workflow_yaml(+ workflow = await _process_workflow_yaml(workflow_id=ctx.workflow_id,workflow_permanent_id=ctx.workflow_permanent_id,organization_id=ctx.organization_id,workflow_yaml=workflow_yaml_with_steps,+ settings_fallback_yaml=prior_yaml,)_record_workflow_proxy_location_span(workflow_yaml, workflow)@@ -5432,6 +5433,7 @@ async def _update_workflow(ai_fallback=workflow.ai_fallback,cache_key=workflow.cache_key,adaptive_caching=workflow.adaptive_caching,+ enable_self_healing=workflow.enable_self_healing,code_version=workflow.code_version,run_sequentially=workflow.run_sequentially,sequential_key=workflow.sequential_key,diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.pyindex 9988a8a86..e650c2d18 100644--- a/skyvern/forge/sdk/db/models.py+++ b/skyvern/forge/sdk/db/models.py@@ -522,6 +522,7 @@ class WorkflowModel(SoftDeleteMixin, Base):ai_fallback = Column(Boolean, default=True, nullable=False, server_default=sqlalchemy.true())cache_key = Column(String, nullable=True)adaptive_caching = Column(Boolean, default=False, nullable=False, server_default=sqlalchemy.false())+ enable_self_healing = Column(Boolean, default=False, nullable=False, server_default=sqlalchemy.false())code_version = Column(Integer, nullable=True, server_default=sqlalchemy.text("2"))generate_script_on_terminal = Column(Boolean, default=False, nullable=False, server_default=sqlalchemy.false())run_sequentially = Column(Boolean, nullable=True)diff --git a/skyvern/forge/sdk/db/repositories/workflows.py b/skyvern/forge/sdk/db/repositories/workflows.pyindex da6447422..a4e1aec3c 100644--- a/skyvern/forge/sdk/db/repositories/workflows.py+++ b/skyvern/forge/sdk/db/repositories/workflows.py@@ -113,6 +113,7 @@ class WorkflowsRepository(BaseRepository):ai_fallback: bool = True,cache_key: str | None = None,adaptive_caching: bool = False,+ enable_self_healing: bool = False,code_version: int | None = None,generate_script_on_terminal: bool = False,run_sequentially: bool = False,@@ -145,6 +146,7 @@ class WorkflowsRepository(BaseRepository):ai_fallback=ai_fallback,cache_key=cache_key or DEFAULT_SCRIPT_RUN_ID,adaptive_caching=adaptive_caching,+ enable_self_healing=enable_self_healing,code_version=code_version,generate_script_on_terminal=generate_script_on_terminal,run_sequentially=run_sequentially,@@ -193,6 +195,20 @@ class WorkflowsRepository(BaseRepository):await session.execute(update_deleted_at_query)await session.commit()+ @db_operation("is_workflow_copilot_authored")+ async def is_workflow_copilot_authored(self, workflow_permanent_id: str, organization_id: str) -> bool:+ """Any version ever stamped by copilot marks the lineage. The latest row alone is not a+ durable signal: user saves re-stamp created_by/edited_by, while copilot back-stamps v1 on+ copilot-born workflows. Deleted versions still count — provenance is historical."""+ copilot_version_exists = (+ select(WorkflowModel.workflow_id)+ .filter_by(workflow_permanent_id=workflow_permanent_id, organization_id=organization_id)+ .filter(or_(WorkflowModel.created_by == "copilot", WorkflowModel.edited_by == "copilot"))+ .limit(1)+ )+ async with self.Session() as session:+ return (await session.scalar(copilot_version_exists)) is not None+@db_operation("get_workflow")async def get_workflow(self, workflow_id: str, organization_id: str | None = None) -> Workflow | None:async with self.Session() as session:@@ -663,6 +679,7 @@ class WorkflowsRepository(BaseRepository):cdp_connect_headers: dict[str, str] | None | object = _UNSET,ai_fallback: bool | None = None,adaptive_caching: bool | object = _UNSET,+ enable_self_healing: bool | object = _UNSET,run_sequentially: bool | None = None,sequential_key: str | None | object = _UNSET,created_by: str | None | object = _UNSET,@@ -721,6 +738,8 @@ class WorkflowsRepository(BaseRepository):workflow.ai_fallback = ai_fallbackif adaptive_caching is not _UNSET:workflow.adaptive_caching = cast(bool, adaptive_caching)+ if enable_self_healing is not _UNSET:+ workflow.enable_self_healing = cast(bool, enable_self_healing)if run_sequentially is not None:workflow.run_sequentially = run_sequentiallyif sequential_key is not _UNSET:@@ -976,6 +995,7 @@ class WorkflowsRepository(BaseRepository):cdp_connect_headers: dict[str, str] | None | object = _UNSET,ai_fallback: bool | None = None,adaptive_caching: bool | object = _UNSET,+ enable_self_healing: bool | object = _UNSET,run_sequentially: bool | None = None,sequential_key: str | None | object = _UNSET,created_by: str | None | object = _UNSET,@@ -1070,6 +1090,8 @@ class WorkflowsRepository(BaseRepository):workflow.ai_fallback = ai_fallbackif adaptive_caching is not _UNSET:workflow.adaptive_caching = cast(bool, adaptive_caching)+ if enable_self_healing is not _UNSET:+ workflow.enable_self_healing = cast(bool, enable_self_healing)if run_sequentially is not None:workflow.run_sequentially = run_sequentiallyif sequential_key is not _UNSET:diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.pyindex 254156985..52d771083 100644--- a/skyvern/forge/sdk/db/utils.py+++ b/skyvern/forge/sdk/db/utils.py@@ -575,6 +575,7 @@ def convert_to_workflow(ai_fallback=workflow_model.ai_fallback,cache_key=workflow_model.cache_key,adaptive_caching=workflow_model.adaptive_caching,+ enable_self_healing=workflow_model.enable_self_healing,code_version=workflow_model.code_version,generate_script_on_terminal=workflow_model.generate_script_on_terminal,run_sequentially=workflow_model.run_sequentially,diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 14fdb39eb..9b1bbfa85 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -4378,11 +4378,20 @@ async def get_workflow(if workflow_permanent_id not in await app.STORAGE.retrieve_global_workflows():raise InvalidTemplateWorkflowPermanentId(workflow_permanent_id=workflow_permanent_id)- return await app.WORKFLOW_SERVICE.get_workflow_by_permanent_id(+ workflow = await app.WORKFLOW_SERVICE.get_workflow_by_permanent_id(workflow_permanent_id=workflow_permanent_id,organization_id=None if template else current_org.organization_id,version=version,)+ if not template:+ workflow.copilot_authored = "copilot" in (+ workflow.created_by,+ workflow.edited_by,+ ) or await app.DATABASE.workflows.is_workflow_copilot_authored(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=current_org.organization_id,+ )+ return workflow@legacy_base_router.get(diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex 9d44a237e..a08bb55a1 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -19,6 +19,7 @@ from sse_starlette import EventSourceResponsefrom skyvern import analyticsfrom skyvern.config import settingsfrom skyvern.constants import DEFAULT_LOGIN_PROMPT+from skyvern.exceptions import WorkflowNotFoundfrom skyvern.forge import appfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.api.llm.api_handler import LLMAPIHandler@@ -938,6 +939,7 @@ async def _commit_staged_workflow(ai_fallback=staged_workflow.ai_fallback,cache_key=staged_workflow.cache_key,adaptive_caching=staged_workflow.adaptive_caching,+ enable_self_healing=staged_workflow.enable_self_healing,code_version=staged_workflow.code_version,run_sequentially=staged_workflow.run_sequentially,sequential_key=staged_workflow.sequential_key,@@ -975,6 +977,7 @@ async def _restore_workflow_definition(original_workflow: Workflow | None, organai_fallback=original_workflow.ai_fallback,cache_key=original_workflow.cache_key,adaptive_caching=original_workflow.adaptive_caching,+ enable_self_healing=original_workflow.enable_self_healing,code_version=original_workflow.code_version,run_sequentially=original_workflow.run_sequentially,sequential_key=original_workflow.sequential_key,@@ -1191,11 +1194,12 @@ async def copilot_call_llm()applied_workflow_yaml = llm_workflow_yamltry:- updated_workflow = _process_workflow_yaml(+ updated_workflow = await _process_workflow_yaml(workflow_id=chat_request.workflow_id,workflow_permanent_id=chat_request.workflow_permanent_id,organization_id=organization_id,workflow_yaml=llm_workflow_yaml,+ settings_fallback_yaml=chat_request.workflow_yaml,)except (yaml.YAMLError, ValidationError, BaseWorkflowHTTPException) as e:await stream.send(@@ -1218,11 +1222,12 @@ async def copilot_call_llm(),chat_request.workflow_yaml,)- updated_workflow = _process_workflow_yaml(+ updated_workflow = await _process_workflow_yaml(workflow_id=chat_request.workflow_id,workflow_permanent_id=chat_request.workflow_permanent_id,organization_id=organization_id,workflow_yaml=corrected_workflow_yaml,+ settings_fallback_yaml=chat_request.workflow_yaml,)applied_workflow_yaml = corrected_workflow_yaml@@ -1559,11 +1564,25 @@ def _normalize_copilot_yaml(workflow_yaml: str) -> WorkflowCreateYAMLRequest:return workflow_yaml_request-def _process_workflow_yaml(+def _yaml_enable_self_healing(workflow_yaml: str | None) -> bool | None:+ if not workflow_yaml:+ return None+ try:+ parsed = yaml.safe_load(workflow_yaml)+ except yaml.YAMLError:+ return None+ if not isinstance(parsed, dict):+ return None+ value = parsed.get("enable_self_healing")+ return value if isinstance(value, bool) else None+++async def _process_workflow_yaml(workflow_id: str,workflow_permanent_id: str,organization_id: str,workflow_yaml: str,+ settings_fallback_yaml: str | None = None,) -> Workflow:# Single seam every copilot YAML->Workflow conversion passes through, so code# blocks get their plain-view steps regardless of which path produced the YAML@@ -1577,6 +1596,24 @@ def _process_workflow_yaml(workflow_id=workflow_id,)+ enable_self_healing = workflow_yaml_request.enable_self_healing+ if enable_self_healing is None:+ # Copilot YAML routinely omits settings it didn't touch; omission must inherit —+ # the canonical-persist comparison would otherwise read the schema default as an+ # explicit disable. The submitted draft YAML wins over persisted state so an+ # unsaved editor toggle survives an unrelated copilot edit. A persisted-lookup+ # failure propagates: failing the save is safer than writing an implicit disable.+ enable_self_healing = _yaml_enable_self_healing(settings_fallback_yaml)+ if enable_self_healing is None:+ try:+ current_workflow = await app.WORKFLOW_SERVICE.get_workflow_by_permanent_id(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ )+ except WorkflowNotFound:+ current_workflow = None+ enable_self_healing = bool(current_workflow and current_workflow.enable_self_healing)+now = datetime.now(timezone.utc)return Workflow(workflow_id=workflow_id,@@ -1602,6 +1639,7 @@ def _process_workflow_yaml(ai_fallback=workflow_yaml_request.ai_fallback,cache_key=workflow_yaml_request.cache_key,adaptive_caching=workflow_yaml_request.adaptive_caching,+ enable_self_healing=enable_self_healing,code_version=workflow_yaml_request.code_version,run_sequentially=workflow_yaml_request.run_sequentially,sequential_key=workflow_yaml_request.sequential_key,diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 1687e1c39..40265cb81 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -96,7 +96,6 @@ from skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.db.enums import TaskTypefrom skyvern.forge.sdk.db.exceptions import NotFoundErrorfrom skyvern.forge.sdk.experimentation.llm_prompt_config import get_llm_handler_for_prompt_type-from skyvern.forge.sdk.experimentation.providers import NoOpExperimentationProviderfrom skyvern.forge.sdk.models import Step, StepStatusfrom skyvern.forge.sdk.schemas.files import FileInfofrom skyvern.forge.sdk.schemas.task_v2 import TaskV2Status@@ -278,8 +277,6 @@ TASKV2_TO_BLOCK_STATUS: dict[TaskV2Status, BlockStatus] = {TaskV2Status.timed_out: BlockStatus.timed_out,}-ENABLE_CODE_BLOCK_SELF_HEALING_FLAG = "ENABLE_CODE_BLOCK_SELF_HEALING"-TASK_TO_BLOCK_STATUS: dict[TaskStatus, BlockStatus] = {TaskStatus.completed: BlockStatus.completed,TaskStatus.terminated: BlockStatus.terminated,@@ -4006,27 +4003,33 @@ async def wrapper({default_args}):best_start = step.line_startreturn best- async def _self_heal_enabled(self, organization_id: str | None) -> bool:- # Per-org PostHog dial over the env default, mirroring the master copilot flags: the env- # default is the OSS/standalone fallback and a resolution failure degrades to it, never raising.- env_enabled = settings.ENABLE_CODE_BLOCK_SELF_HEALING- provider = app.EXPERIMENTATION_PROVIDER- if not organization_id or isinstance(provider, NoOpExperimentationProvider):- return env_enabled+ async def _self_heal_enabled(self, workflow_run_context: WorkflowRunContext) -> bool:+ # User-facing per-workflow setting, restricted to copilot-authored workflows —+ # pre-copilot code blocks must never gain agentic recovery from the toggle alone.+ # The env default stays as the OSS/standalone and local-dev override.+ if settings.ENABLE_CODE_BLOCK_SELF_HEALING:+ return True+ workflow = workflow_run_context.workflow+ if workflow is None or not workflow.enable_self_healing:+ return False+ if "copilot" in (workflow.created_by, workflow.edited_by):+ return True+ # User saves re-stamp both fields with the user id, so the current version alone is+ # not durable; fall back to lineage (copilot stamps every version it writes and+ # back-stamps v1 on copilot-born workflows). This runs inside the block's exception+ # handler — a lookup failure must fail closed, never mask the original block failure.try:- flag_enabled = await provider.is_feature_enabled_cached(- ENABLE_CODE_BLOCK_SELF_HEALING_FLAG,- organization_id,- properties={"organization_id": organization_id},+ return await app.DATABASE.workflows.is_workflow_copilot_authored(+ workflow_permanent_id=workflow.workflow_permanent_id,+ organization_id=workflow.organization_id,)- return bool(flag_enabled) or env_enabledexcept Exception:LOG.warning(- "Failed to resolve code-block self-heal flag; falling back to env default",- organization_id=organization_id,+ "Self-heal copilot-lineage lookup failed; failing closed (no heal)",+ workflow_permanent_id=workflow.workflow_permanent_id,exc_info=True,)- return env_enabled+ return Falsedef _is_healable_page_failure(self, exception: Exception, recording_page: RecordingPage) -> bool:"""Heal genuine page failures only: a recorded page call raised, or an (unmapped) Playwright@@ -4107,7 +4110,7 @@ async def wrapper({default_args}):"""Run one bounded agent mini-run on the same workflow-run browser to finish the block's goal(narrowed to the failing step when one is confidently matched). Returns a BlockResult when aheal was attempted, or None to fall through to the caller's fail-closed path."""- if not await self._self_heal_enabled(organization_id):+ if not await self._self_heal_enabled(workflow_run_context):return Noneif not self._is_healable_page_failure(exception, recording_page):return Nonediff --git a/skyvern/forge/sdk/workflow/models/workflow.py b/skyvern/forge/sdk/workflow/models/workflow.pyindex d53e63170..e14a1de57 100644--- a/skyvern/forge/sdk/workflow/models/workflow.py+++ b/skyvern/forge/sdk/workflow/models/workflow.py@@ -149,6 +149,7 @@ class Workflow(BaseModel):ai_fallback: bool = Truecache_key: str | None = Noneadaptive_caching: bool = False+ enable_self_healing: bool = Falsecode_version: int | None = Nonegenerate_script_on_terminal: bool = Falserun_sequentially: bool | None = None@@ -157,6 +158,9 @@ class Workflow(BaseModel):import_error: str | None = Nonecreated_by: str | None = Noneedited_by: str | None = None+ # Lineage-derived (any version copilot-stamped); populated by the detail GET route only —+ # user saves re-stamp created_by/edited_by, so the current version alone is not durable.+ copilot_authored: bool = False@field_validator("run_with", mode="before")@classmethoddiff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex f7b0eb1d4..32518eb16 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -4355,6 +4355,7 @@ class WorkflowService:sequential_key: str | None = None,folder_id: str | None = None,adaptive_caching: bool = False,+ enable_self_healing: bool = False,code_version: int | None = None,generate_script_on_terminal: bool = False,created_by: str | None = None,@@ -4389,6 +4390,7 @@ class WorkflowService:sequential_key=sequential_key,folder_id=folder_id,adaptive_caching=adaptive_caching,+ enable_self_healing=enable_self_healing,code_version=code_version,generate_script_on_terminal=generate_script_on_terminal,created_by=created_by,@@ -4776,6 +4778,7 @@ class WorkflowService:ai_fallback: bool | None = None,cache_key: str | None = None,adaptive_caching: bool | object = _UNSET,+ enable_self_healing: bool | object = _UNSET,code_version: int | None | object = _UNSET,run_sequentially: bool | None = None,sequential_key: str | None | object = _UNSET,@@ -4805,6 +4808,7 @@ class WorkflowService:ai_fallback=ai_fallback,cache_key=cache_key,adaptive_caching=adaptive_caching,+ enable_self_healing=enable_self_healing,code_version=code_version,run_sequentially=run_sequentially,sequential_key=sequential_key,@@ -4834,6 +4838,7 @@ class WorkflowService:ai_fallback=ai_fallback,cache_key=cache_key,adaptive_caching=adaptive_caching,+ enable_self_healing=enable_self_healing,code_version=code_version,run_sequentially=run_sequentially,sequential_key=sequential_key,@@ -6863,6 +6868,7 @@ class WorkflowService:run_sequentially=runtime_workflow.run_sequentially or False,sequential_key=runtime_workflow.sequential_key,adaptive_caching=runtime_workflow.adaptive_caching,+ enable_self_healing=runtime_workflow.enable_self_healing,generate_script_on_terminal=runtime_workflow.generate_script_on_terminal,folder_id=runtime_workflow.folder_id,is_saved_task=runtime_workflow.is_saved_task,@@ -7002,6 +7008,9 @@ class WorkflowService:sequential_key=request.sequential_key,folder_id=existing_latest_workflow.folder_id,adaptive_caching=request.adaptive_caching,+ enable_self_healing=request.enable_self_healing+ if request.enable_self_healing is not None+ else existing_latest_workflow.enable_self_healing,code_version=request.code_versionif request.code_version is not Noneelse existing_latest_workflow.code_version,@@ -7041,6 +7050,9 @@ class WorkflowService:sequential_key=request.sequential_key,folder_id=request.folder_id,adaptive_caching=request.adaptive_caching,+ enable_self_healing=request.enable_self_healing+ if request.enable_self_healing is not None+ else False,code_version=request.code_version,generate_script_on_terminal=request.generate_script_on_terminal,created_by=created_by,diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.pyindex f36d6eea6..4b98e6f88 100644--- a/skyvern/schemas/workflows.py+++ b/skyvern/schemas/workflows.py@@ -1319,6 +1319,10 @@ class WorkflowCreateYAMLRequest(BaseModel):ai_fallback: bool = Truecache_key: str | None = "default"adaptive_caching: bool = False+ # None = inherit from the existing workflow on update (mirrors code_version);+ # treated as False on first create. Prevents older clients that omit the field+ # from silently disabling self-healing on save.+ enable_self_healing: bool | None = Nonecode_version: int | None = Field(default=None, ge=1, le=2)generate_script_on_terminal: bool = Falserun_sequentially: bool = Field(default=False, title="Prevent Overlapping Runs")diff --git a/tests/unit/test_code_block_steps.py b/tests/unit/test_code_block_steps.pyindex 47f28b3f0..758ad2f3f 100644--- a/tests/unit/test_code_block_steps.py+++ b/tests/unit/test_code_block_steps.py@@ -226,7 +226,8 @@ def test_fill_prompts_noop_without_sources():assert "prompt" not in out["workflow_definition"]["blocks"][0]-def test_process_workflow_yaml_derives_code_block_steps_for_replace_path():+async def test_process_workflow_yaml_derives_code_block_steps_for_replace_path():# Regression: the inline REPLACE_WORKFLOW path (v1 and v2) builds the# frontend-facing workflow via _process_workflow_yaml without first deriving# steps, so a generated code block surfaced as "No steps yet" in the plain@@ -245,8 +246,9 @@ def test_process_workflow_yaml_derives_code_block_steps_for_replace_path():" await page.goto('https://example.com/')\n"" await page.get_by_role('link', name='login').click()\n")- wf = _process_workflow_yaml(+ wf = await _process_workflow_yaml(workflow_id="w_1",+ settings_fallback_yaml="enable_self_healing: false",workflow_permanent_id="wpid_1",organization_id="o_1",workflow_yaml=yaml_str,diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex 6893fc622..2741f525a 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -1910,7 +1910,8 @@ workflow_definition:async def fake_update_workflow(payload, ctx, allow_missing_credentials=False):captured["workflow_yaml"] = payload["workflow_yaml"]ctx.workflow_yaml = payload["workflow_yaml"]- workflow = _process_workflow_yaml(+ workflow = await _process_workflow_yaml(+ settings_fallback_yaml="enable_self_healing: false",workflow_id=ctx.workflow_id,workflow_permanent_id=ctx.workflow_permanent_id,organization_id=ctx.organization_id,@@ -2142,7 +2143,7 @@ class TestTranslateToAgentResultGating:new_wf = SimpleNamespace(name="new-from-replace")monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._process_workflow_yaml",- lambda **kwargs: new_wf,+ AsyncMock(return_value=new_wf),)ctx = _ctx(@@ -2212,7 +2213,7 @@ class TestTranslateToAgentResultGating:# Inline REPLACE_WORKFLOW bypasses _update_workflow, so it must also# reject a corrected workflow whose labels/titles still describe the# prior subject.- process_mock = MagicMock(return_value=SimpleNamespace(name="new"))+ process_mock = AsyncMock(return_value=SimpleNamespace(name="new"))monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._process_workflow_yaml", process_mock)prior_yaml = """@@ -2257,7 +2258,7 @@ workflow_definition:assert agent_result.workflow_yaml is Nonedef test_inline_replace_workflow_rejects_page_dependent_blocks_without_inspection(self, monkeypatch) -> None:- process_mock = MagicMock(return_value=SimpleNamespace(name="new"))+ process_mock = AsyncMock(return_value=SimpleNamespace(name="new"))monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._process_workflow_yaml", process_mock)submitted_yaml = """@@ -2299,7 +2300,7 @@ workflow_definition:def test_code_only_inline_replace_workflow_rejects_native_browser_block(self, monkeypatch) -> None:from skyvern.forge.sdk.copilot.output_policy import OutputPolicyVerdict- process_mock = MagicMock(return_value=SimpleNamespace(name="new"))+ process_mock = AsyncMock(return_value=SimpleNamespace(name="new"))monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._process_workflow_yaml", process_mock)monkeypatch.setattr(agent_module, "evaluate_output_policy", lambda **kwargs: OutputPolicyVerdict())@@ -3059,7 +3060,7 @@ workflow_definition:def test_inline_replace_workflow_persists_clean_agent_yaml(self, monkeypatch) -> None:captured: dict[str, str] = {}- def fake_process(**kwargs):+ async def fake_process(**kwargs):captured["yaml"] = kwargs["workflow_yaml"]return SimpleNamespace(name="new-wf")@@ -3081,7 +3082,7 @@ workflow_definition:def test_inline_replace_workflow_does_not_denormalize_resolved_goal(self, monkeypatch) -> None:captured: dict[str, str] = {}- def fake_process(**kwargs):+ async def fake_process(**kwargs):captured["yaml"] = kwargs["workflow_yaml"]return SimpleNamespace(name="new-wf")@@ -4910,7 +4911,7 @@ workflow_definition:monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml",- lambda **kwargs: workflow,+ AsyncMock(return_value=workflow),)monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.workflow_update.resolve_copilot_created_by_stamp",diff --git a/tests/unit/test_copilot_block_goal_wrapping.py b/tests/unit/test_copilot_block_goal_wrapping.pyindex 20f5e1aa0..ecaddd2ca 100644--- a/tests/unit/test_copilot_block_goal_wrapping.py+++ b/tests/unit/test_copilot_block_goal_wrapping.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport textwrapfrom types import SimpleNamespace+import pytestimport yamlfrom skyvern.constants import MINI_GOAL_TEMPLATE@@ -347,8 +348,10 @@ def test_returns_input_unchanged_when_blocks_not_list() -> None:assert out == src-def test_wrap_workflow_block_goals_wraps_runtime_copy_only() -> None:- workflow = _process_workflow_yaml(+async def test_wrap_workflow_block_goals_wraps_runtime_copy_only() -> None:+ workflow = await _process_workflow_yaml(+ settings_fallback_yaml="enable_self_healing: false",workflow_id="w_test",workflow_permanent_id="wpid_test",organization_id="o_test",@@ -373,8 +376,10 @@ def test_wrap_workflow_block_goals_wraps_runtime_copy_only() -> None:assert wrapped is not workflow-def test_wrap_workflow_block_goals_recurses_into_loop_blocks() -> None:- workflow = _process_workflow_yaml(+async def test_wrap_workflow_block_goals_recurses_into_loop_blocks() -> None:+ workflow = await _process_workflow_yaml(+ settings_fallback_yaml="enable_self_healing: false",workflow_id="w_test",workflow_permanent_id="wpid_test",organization_id="o_test",@@ -425,8 +430,10 @@ def test_wrap_workflow_block_goals_recurses_into_loop_blocks() -> None:assert wrapped_loop_blocks[1].complete_criterion == _wrapped("The item is processed.")-def test_wrap_workflow_block_goals_skips_copy_when_no_runtime_mutation_needed() -> None:- parsed_workflow = _process_workflow_yaml(+async def test_wrap_workflow_block_goals_skips_copy_when_no_runtime_mutation_needed() -> None:+ parsed_workflow = await _process_workflow_yaml(+ settings_fallback_yaml="enable_self_healing: false",workflow_id="w_test",workflow_permanent_id="wpid_test",organization_id="o_test",diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex e4d62d85e..a7bf25aa4 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -379,7 +379,7 @@ def _enable_imposition(ctx: CopilotContext) -> None:def _stub_successful_update(monkeypatch: pytest.MonkeyPatch) -> None:- def _fake_process_workflow_yaml(**_kwargs: object) -> SimpleNamespace:+ async def _fake_process_workflow_yaml(**_kwargs: object) -> SimpleNamespace:return SimpleNamespace(workflow_definition=SimpleNamespace(blocks=[SimpleNamespace(label="search_registry")]),proxy_location=None,diff --git a/tests/unit/test_copilot_session_injection.py b/tests/unit/test_copilot_session_injection.pyindex 4eeaedcf1..03ba37d96 100644--- a/tests/unit/test_copilot_session_injection.py+++ b/tests/unit/test_copilot_session_injection.py@@ -553,7 +553,7 @@ class TestUpdateWorkflowDirect:monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml",- lambda **kwargs: mock_workflow,+ AsyncMock(return_value=mock_workflow),)mock_wf_service = MagicMock()@@ -585,7 +585,7 @@ class TestUpdateWorkflowDirect:monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml",- lambda **kwargs: mock_workflow,+ AsyncMock(return_value=mock_workflow),)mock_wf_service = MagicMock()diff --git a/tests/unit/test_copilot_tools_credential_id_misbinding.py b/tests/unit/test_copilot_tools_credential_id_misbinding.pyindex bed098d1e..af0810cf1 100644--- a/tests/unit/test_copilot_tools_credential_id_misbinding.py+++ b/tests/unit/test_copilot_tools_credential_id_misbinding.py@@ -407,22 +407,24 @@ async def test_update_workflow_allows_credential_id_in_credential_parameter_slot),patch("skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml",- return_value=MagicMock(- title="Sign in",- description=None,- workflow_definition=MagicMock(),- proxy_location=None,- webhook_callback_url=None,- persist_browser_session=False,- browser_profile_id=None,- model=None,- max_screenshot_scrolls=None,- extra_http_headers=None,- run_with=None,- ai_fallback=None,- cache_key=None,- run_sequentially=None,- sequential_key=None,+ new=AsyncMock(+ return_value=MagicMock(+ title="Sign in",+ description=None,+ workflow_definition=MagicMock(),+ proxy_location=None,+ webhook_callback_url=None,+ persist_browser_session=False,+ browser_profile_id=None,+ model=None,+ max_screenshot_scrolls=None,+ extra_http_headers=None,+ run_with=None,+ ai_fallback=None,+ cache_key=None,+ run_sequentially=None,+ sequential_key=None,+ ),),),patch(diff --git a/tests/unit/test_workflow_browser_profile_id.py b/tests/unit/test_workflow_browser_profile_id.pyindex df2fdad8d..c3d0dd44c 100644--- a/tests/unit/test_workflow_browser_profile_id.py+++ b/tests/unit/test_workflow_browser_profile_id.py@@ -97,6 +97,53 @@ async def test_create_workflow_from_request_preserves_existing_max_elapsed_time_refresh_schedules_mock.assert_not_awaited()+async def test_create_workflow_from_request_preserves_enable_self_healing_when_omitted() -> None:+ service, _ = _make_workflow_update_service(+ existing_max_elapsed_time_minutes=None, existing_enable_self_healing=True+ )++ request = WorkflowCreateYAMLRequest(+ title="test",+ workflow_definition=WorkflowDefinitionYAML(parameters=[], blocks=[]),+ )++ await service.create_workflow_from_request(+ organization=cast(Any, SimpleNamespace(organization_id="org_1")),+ request=request,+ workflow_permanent_id="wpid_test",+ )++ create_workflow_mock = service.create_workflow+ assert isinstance(create_workflow_mock, AsyncMock)+ assert create_workflow_mock.await_args is not None+ assert create_workflow_mock.await_args.kwargs["enable_self_healing"] is True+++async def test_create_workflow_from_request_explicit_false_clears_enable_self_healing() -> None:+ service, _ = _make_workflow_update_service(+ existing_max_elapsed_time_minutes=None, existing_enable_self_healing=True+ )++ request = WorkflowCreateYAMLRequest(+ title="test",+ workflow_definition=WorkflowDefinitionYAML(parameters=[], blocks=[]),+ enable_self_healing=False,+ )++ await service.create_workflow_from_request(+ organization=cast(Any, SimpleNamespace(organization_id="org_1")),+ request=request,+ workflow_permanent_id="wpid_test",+ )++ create_workflow_mock = service.create_workflow+ assert isinstance(create_workflow_mock, AsyncMock)+ assert create_workflow_mock.await_args is not None+ assert create_workflow_mock.await_args.kwargs["enable_self_healing"] is False++@pytest.mark.asyncioasync def test_create_workflow_from_request_allows_explicit_null_to_clear_existing_max_elapsed_time() -> None:service, updated_workflow = _make_workflow_update_service(existing_max_elapsed_time_minutes=90)@@ -179,6 +226,7 @@ async def test_refresh_workflow_schedule_runtime_limits_reupserts_backend_schedudef _make_workflow_update_service(existing_max_elapsed_time_minutes: int | None,+ existing_enable_self_healing: bool = True,) -> tuple[WorkflowService, SimpleNamespace]:service = WorkflowService()existing_workflow = SimpleNamespace(@@ -188,6 +236,7 @@ def _make_workflow_update_service(folder_id=None,code_version=None,max_elapsed_time_minutes=existing_max_elapsed_time_minutes,+ enable_self_healing=existing_enable_self_healing,)potential_workflow = SimpleNamespace(workflow_id="wf_new")updated_workflow = SimpleNamespace(workflow_id="wf_new", workflow_permanent_id="wpid_test")diff --git a/tests/unit/test_yaml_loader_no_dates.py b/tests/unit/test_yaml_loader_no_dates.pyindex 02732c981..a25633513 100644--- a/tests/unit/test_yaml_loader_no_dates.py+++ b/tests/unit/test_yaml_loader_no_dates.py@@ -79,9 +79,11 @@ def test_safe_load_no_dates_preserves_other_implicit_types() -> None:assert parsed["a_list"] == [1, 2, 3]-def test_process_workflow_yaml_keeps_json_parameter_iso_strings() -> None:- workflow = _process_workflow_yaml(+async def test_process_workflow_yaml_keeps_json_parameter_iso_strings() -> None:+ workflow = await _process_workflow_yaml(workflow_id="wf-123",+ settings_fallback_yaml="enable_self_healing: false",workflow_permanent_id="wfp-123",organization_id="org-123",workflow_yaml="""diff --git a/tests/unit/workflow/test_code_block_escalation.py b/tests/unit/workflow/test_code_block_escalation.pyindex 14ac5beca..15f83e9c7 100644--- a/tests/unit/workflow/test_code_block_escalation.py+++ b/tests/unit/workflow/test_code_block_escalation.py@@ -51,7 +51,13 @@ def _make_code_block(steps: list[CodeBlockStep] | None = None, prompt: str | Non)-def _make_context(*, with_secret: bool = False) -> WorkflowRunContext:+def _make_context(+ *,+ with_secret: bool = False,+ enable_self_healing: bool | None = None,+ created_by: str | None = "copilot",+ edited_by: str | None = None,+) -> WorkflowRunContext:context = WorkflowRunContext(workflow_title="wf",workflow_id="w_test",@@ -62,6 +68,15 @@ def _make_context(*, with_secret: bool = False) -> WorkflowRunContext:if with_secret:context.secrets["k_secret"] = SECRET_VALUEcontext.include_secrets_in_templates = True+ if enable_self_healing is not None:+ context.workflow = SimpleNamespace(+ enable_self_healing=enable_self_healing,+ workflow_definition=None,+ created_by=created_by,+ edited_by=edited_by,+ workflow_permanent_id="wpid_test",+ organization_id="o_test",+ )return context@@ -91,6 +106,7 @@ def _install_db_fakes(organization: object | None = SimpleNamespace(organization_id="o_test", max_steps_per_run=None),downloaded_files: list[FileInfo] | None = None,extracted_information: ExtractedInformation = None,+ copilot_lineage: bool = False,) -> dict[str, Any]:created_task = _FakeTask("tsk_escalation", TaskStatus.running)updated_after_run = _FakeTask("tsk_escalation", final_status, extracted_information=extracted_information)@@ -139,6 +155,7 @@ def _install_db_fakes(monkeypatch.setattr(app.DATABASE.tasks, "create_step", AsyncMock(side_effect=_create_step))monkeypatch.setattr(app.DATABASE.tasks, "get_task", AsyncMock(side_effect=_get_task))monkeypatch.setattr(app.DATABASE.organizations, "get_organization", AsyncMock(side_effect=_get_organization))+ monkeypatch.setattr(app.DATABASE.workflows, "is_workflow_copilot_authored", AsyncMock(return_value=copilot_lineage))monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block.BaseTaskBlock.get_task_order",AsyncMock(side_effect=_get_task_order),@@ -193,57 +210,116 @@ async def _heal()[email protected](autouse=True)-def _self_heal_flag_resolves_to_env(monkeypatch: pytest.MonkeyPatch) -> None:- # Unit stub provider returns a truthy AsyncMock for every flag; pin self-heal resolution to the- # env default so per-test settings govern. PostHog-specific tests override the provider explicitly.- monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", AsyncMock(return_value=False))+async def test_everything_off_is_no_op(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", False, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(enable_self_healing=False), exc, _recording_page(exc))++ assert result is None+ assert state["execute_step_calls"] == 0@pytest.mark.asyncio-async def test_flag_off_is_no_op(monkeypatch: pytest.MonkeyPatch) -> None:+async def test_workflow_setting_enables_heal_when_env_off(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", False, raising=False)state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])exc = RuntimeError("rotted selector")- result = await _heal(block, _make_context(), exc, _recording_page(exc))+ result = await _heal(block, _make_context(enable_self_healing=True), exc, _recording_page(exc))++ assert result is not None+ assert state["execute_step_calls"] == 1+++async def test_non_copilot_workflow_never_heals_from_the_toggle(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", False, raising=False)+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")+ context = _make_context(enable_self_healing=True, created_by="[email protected]", edited_by=None)++ result = await _heal(block, context, exc, _recording_page(exc))assert result is Noneassert state["execute_step_calls"] == 0@pytest.mark.asyncio-async def test_posthog_flag_enables_heal_when_env_off(monkeypatch: pytest.MonkeyPatch) -> None:+async def test_user_saved_copilot_workflow_heals_via_lineage(monkeypatch: pytest.MonkeyPatch) -> None:+ """User saves re-stamp created_by/edited_by with the user id; the lineage scan must still+ recognize a copilot-authored workflow."""monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", False, raising=False)- fake_provider = SimpleNamespace(is_feature_enabled_cached=AsyncMock(return_value=True))- monkeypatch.setattr(app, "EXPERIMENTATION_PROVIDER", fake_provider)- state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed, copilot_lineage=True)block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])exc = RuntimeError("rotted selector")+ context = _make_context(enable_self_healing=True, created_by="[email protected]", edited_by="[email protected]")- result = await _heal(block, _make_context(), exc, _recording_page(exc))+ result = await _heal(block, context, exc, _recording_page(exc))assert result is not Noneassert state["execute_step_calls"] == 1- assert fake_provider.is_feature_enabled_cached.await_args.args[0] == "ENABLE_CODE_BLOCK_SELF_HEALING"@pytest.mark.asyncio-async def test_posthog_resolution_failure_falls_back_to_env(monkeypatch: pytest.MonkeyPatch) -> None:+async def test_lineage_lookup_failure_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:+ """The lineage scan runs inside the block's exception handler; a DB failure there must+ fail closed (no heal) instead of masking the original block failure with a new raise."""monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", False, raising=False)- fake_provider = SimpleNamespace(is_feature_enabled_cached=AsyncMock(side_effect=RuntimeError("posthog down")))- monkeypatch.setattr(app, "EXPERIMENTATION_PROVIDER", fake_provider)state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ monkeypatch.setattr(+ app.DATABASE.workflows,+ "is_workflow_copilot_authored",+ AsyncMock(side_effect=RuntimeError("db unavailable")),+ )block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])exc = RuntimeError("rotted selector")+ context = _make_context(enable_self_healing=True, created_by="[email protected]", edited_by="[email protected]")- result = await _heal(block, _make_context(), exc, _recording_page(exc))+ result = await _heal(block, context, exc, _recording_page(exc))assert result is Noneassert state["execute_step_calls"] == 0+async def test_copilot_edited_workflow_heals_from_the_toggle(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", False, raising=False)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")+ context = _make_context(enable_self_healing=True, created_by="[email protected]", edited_by="copilot")++ result = await _heal(block, context, exc, _recording_page(exc))++ assert result is not None+ assert state["execute_step_calls"] == 1++[email protected]("env_enabled", [True, False])+async def test_missing_workflow_on_context_falls_back_to_env(+ monkeypatch: pytest.MonkeyPatch, env_enabled: bool+) -> None:+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", env_enabled, raising=False)+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block(steps=[CodeBlockStep(description="download", line_start=1, line_end=1)])+ exc = RuntimeError("rotted selector")++ result = await _heal(block, _make_context(), exc, _recording_page(exc))++ assert (result is not None) is env_enabled+ assert state["execute_step_calls"] == (1 if env_enabled else 0)++# --- The spine fix: a rotted page failure heals on block.prompt even with no covering step. ---diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.pyindex 5699aa034..c8fb29672 100644--- a/tests/unit/workflow/test_code_block_recorder.py+++ b/tests/unit/workflow/test_code_block_recorder.py@@ -359,6 +359,7 @@ class FakeWorkflowRunContext:workflow_permanent_id = "wpid_test"workflow_run_id = "wr_test"browser_session_id = None+ workflow = Nonedef __init__(self, secrets: dict[str, str] | None = None) -> None:self.secrets = secrets or {}diff --git a/tests/unit/workflow/test_workflow_yaml_settings_defaults.py b/tests/unit/workflow/test_workflow_yaml_settings_defaults.pynew file mode 100644index 000000000..d4a9c7d0d--- /dev/null+++ b/tests/unit/workflow/test_workflow_yaml_settings_defaults.py@@ -0,0 +1,24 @@+"""enable_self_healing YAML semantics: omitted means inherit-on-update (None), never an+implicit disable — older clients that don't send the field must not clobber the setting."""++from skyvern.schemas.workflows import WorkflowCreateYAMLRequest, WorkflowDefinitionYAML+++def _request(**kwargs: object) -> WorkflowCreateYAMLRequest:+ return WorkflowCreateYAMLRequest(+ title="t",+ workflow_definition=WorkflowDefinitionYAML(parameters=[], blocks=[]),+ **kwargs,+ )+++def test_omitted_enable_self_healing_is_none() -> None:+ assert _request().enable_self_healing is None+++def test_explicit_false_survives() -> None:+ assert _request(enable_self_healing=False).enable_self_healing is False+++def test_explicit_true_survives() -> None:+ assert _request(enable_self_healing=True).enable_self_healing is True