Skip to content

Automate browser based workflows with AI

feat(SKY-11580): force diagnose-first on the Fix-with-Copilot path (#6932)

pedrohsdbbb0ecbae3037
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx
index bad2188b6..4c0eff527 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx
@@ -16,6 +16,7 @@ import {
type StreamBody = {
message: string;
workflow_run_id?: string | null;
+ fix_origin?: boolean;
};
type StreamCall = {
body: StreamBody;
@@ -123,19 +124,33 @@ vi.mock("@/store/WorkflowHasChangesStore", () => ({
import { WorkflowCopilotChat } from "./WorkflowCopilotChat";
-async function renderChat(props: { workflowRunId?: string | null } = {}) {
- const booleanFlags: Record<string, boolean> = {
- ENABLE_WORKFLOW_COPILOT_V2: true,
- WORKFLOW_COPILOT_CODE_BLOCK_MODE: false,
- CODE_BLOCK_ACCESS: false,
- };
- const view = render(
- <FeatureFlagContext.Provider value={(name) => booleanFlags[name]}>
+const BOOLEAN_FLAGS: Record<string, boolean> = {
+ ENABLE_WORKFLOW_COPILOT_V2: true,
+ WORKFLOW_COPILOT_CODE_BLOCK_MODE: false,
+ CODE_BLOCK_ACCESS: false,
+};
+
+type ChatProps = {
+ workflowRunId?: string | null;
+ initialMessage?: string;
+ initialMessageFixOrigin?: boolean;
+ requiresLiveBrowser?: boolean;
+ isLiveBrowserReady?: boolean;
+ liveBrowserSessionId?: string | null;
+};
+
+function chatUi(props: ChatProps) {
+ return (
+ <FeatureFlagContext.Provider value={(name) => BOOLEAN_FLAGS[name]}>
<FeatureFlagValueContext.Provider value={() => undefined}>
<WorkflowCopilotChat {...props} />
</FeatureFlagValueContext.Provider>
- </FeatureFlagContext.Provider>,
+ </FeatureFlagContext.Provider>
);
+}
+
+async function renderChat(props: ChatProps = {}) {
+ const view = render(chatUi(props));
await waitFor(() =>
expect(screen.getByPlaceholderText(/Message Skyvern Copilot/)).toBeTruthy(),
);
@@ -204,3 +219,138 @@ describe("WorkflowCopilotChat — run grounding bridge", () => {
expect(streamCalls[0]?.body.workflow_run_id).toBe("wr_route");
});
});
+
+describe("WorkflowCopilotChat — fix-origin signal", () => {
+ it("auto-sends fix_origin:true when the seed originates from Fix with Copilot", async () => {
+ await renderChat({
+ workflowRunId: "wr_1",
+ initialMessage:
+ "Diagnose why this run failed, then fix the workflow so it succeeds.",
+ initialMessageFixOrigin: true,
+ });
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+
+ expect(streamCalls[0]?.body.fix_origin).toBe(true);
+ expect(streamCalls[0]?.body.workflow_run_id).toBe("wr_1");
+ });
+
+ it("does not set fix_origin for a seed that is not a fix origin", async () => {
+ await renderChat({
+ workflowRunId: "wr_1",
+ initialMessage: "Build a workflow that scrapes prices.",
+ initialMessageFixOrigin: false,
+ });
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+
+ expect(streamCalls[0]?.body.fix_origin).toBe(false);
+ });
+
+ it("does not set fix_origin for a normal typed turn", async () => {
+ await renderChat({ workflowRunId: "wr_1" });
+ await submit("this run failed, fix it");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+
+ expect(streamCalls[0]?.body.fix_origin).toBe(false);
+ });
+
+ it("clears the fix-origin signal when a queued fix seed is cancelled (no leak to the next turn)", async () => {
+ const view = render(
+ chatUi({
+ workflowRunId: "wr_1",
+ requiresLiveBrowser: true,
+ isLiveBrowserReady: false,
+ initialMessage: "Diagnose why this run failed, then fix it.",
+ initialMessageFixOrigin: true,
+ }),
+ );
+ // Live browser not ready: the fix seed queues (a user bubble appears) instead of sending.
+ await waitFor(() =>
+ expect(screen.getByText(/Diagnose why this run failed/i)).toBeTruthy(),
+ );
+ expect(postStreaming).not.toHaveBeenCalled();
+
+ // Cancel the queued prompt (Escape), then let the live browser become ready.
+ await act(async () => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ });
+ view.rerender(
+ chatUi({
+ workflowRunId: "wr_1",
+ requiresLiveBrowser: true,
+ isLiveBrowserReady: true,
+ }),
+ );
+
+ // A normal typed turn after the cancel must not inherit the cancelled fix-origin signal.
+ await submit("add a step that downloads the invoice");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ expect(streamCalls[0]?.body.fix_origin).toBe(false);
+ });
+
+ it("clears the fix-origin signal when a queued fix seed is discarded by New chat (no leak to the next turn)", async () => {
+ const view = render(
+ chatUi({
+ workflowRunId: "wr_1",
+ requiresLiveBrowser: true,
+ isLiveBrowserReady: false,
+ initialMessage: "Diagnose why this run failed, then fix it.",
+ initialMessageFixOrigin: true,
+ }),
+ );
+ // Live browser not ready: the fix seed queues (a user bubble appears) instead of sending.
+ await waitFor(() =>
+ expect(screen.getByText(/Diagnose why this run failed/i)).toBeTruthy(),
+ );
+ expect(postStreaming).not.toHaveBeenCalled();
+
+ // Discard the queued fix seed via "New chat", then let the live browser become ready.
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: /New chat/i }));
+ });
+ view.rerender(
+ chatUi({
+ workflowRunId: "wr_1",
+ requiresLiveBrowser: true,
+ isLiveBrowserReady: true,
+ }),
+ );
+
+ // A normal typed turn after New chat must not inherit the discarded fix-origin signal.
+ await submit("add a step that downloads the invoice");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ expect(streamCalls[0]?.body.fix_origin).toBe(false);
+ });
+
+ it("preserves fix_origin when a queued fix seed drains after the live browser connects", async () => {
+ const view = render(
+ chatUi({
+ workflowRunId: "wr_1",
+ requiresLiveBrowser: true,
+ isLiveBrowserReady: false,
+ initialMessage: "Diagnose why this run failed, then fix it.",
+ initialMessageFixOrigin: true,
+ }),
+ );
+ // Live browser not ready: the fix seed queues instead of sending.
+ await waitFor(() =>
+ expect(screen.getByText(/Diagnose why this run failed/i)).toBeTruthy(),
+ );
+ expect(postStreaming).not.toHaveBeenCalled();
+
+ // Browser connects (session id present): the queued fix seed drains and
+ // must still carry fix_origin. initialMessage is dropped so this is a pure
+ // drain of the already-queued prompt, not a fresh seed.
+ await act(async () => {
+ view.rerender(
+ chatUi({
+ workflowRunId: "wr_1",
+ requiresLiveBrowser: true,
+ isLiveBrowserReady: true,
+ liveBrowserSessionId: "bs_1",
+ }),
+ );
+ });
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ expect(streamCalls[0]?.body.fix_origin).toBe(true);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index c855edea0..1a43a30cf 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -251,6 +251,9 @@ type QueuedPrompt = {
content: string;
reason: QueuedPromptReason;
audioBlob?: Blob | null;
+ // The one-shot fix-origin signal travels with the prompt it was seeded for, so
+ // discarding the queue (new chat, history load, agent switch) drops it too.
+ fixOrigin?: boolean;
};
type SendOptions = {
@@ -340,6 +343,8 @@ interface WorkflowCopilotChatProps {
requiresLiveBrowser?: boolean;
isLiveBrowserReady?: boolean;
initialMessage?: string;
+ // Sent as fix_origin only on the initial turn; does not propagate to subsequent turns.
+ initialMessageFixOrigin?: boolean;
onInitialMessageConsumed?: () => void;
// Render as a docked panel (no float/drag/resize) instead of a floating window.
docked?: boolean;
@@ -416,6 +421,7 @@ export function WorkflowCopilotChat({
requiresLiveBrowser = false,
isLiveBrowserReady = false,
initialMessage,
+ initialMessageFixOrigin,
onInitialMessageConsumed,
docked = false,
onCollapse,
@@ -1111,8 +1117,11 @@ export function WorkflowCopilotChat({
}
updateQueuedPrompt(null);
- // Discard the queued block-build's target so it can't leak into the next normal message.
+ // Drop the queued block-build target so it doesn't leak into the next message.
+ // The fix-origin signal rode on the discarded prompt; clear the ref too in case
+ // a future path set it without queuing.
blockBuildTargetLabelRef.current = null;
+ fixOriginPendingRef.current = false;
setMessages((prev) =>
prev.filter((message) => message.id !== queuedPrompt.id),
);
@@ -1145,6 +1154,7 @@ export function WorkflowCopilotChat({
// Set by a block's "Generate" arm step so the next send scopes regeneration to that block.
const blockBuildTargetLabelRef = useRef<string | null>(null);
+ const fixOriginPendingRef = useRef(false);
// True only while a block-build turn is actually in flight (not a turn it queued behind).
const blockGenInFlightRef = useRef(false);
@@ -1185,11 +1195,18 @@ export function WorkflowCopilotChat({
const reason: QueuedPromptReason =
action === "queue_working" ? "working" : "live_browser";
const queuedId = options.queuedMessageId ?? crypto.randomUUID();
+ // Move the pending fix-origin signal off the bare ref and onto the
+ // queued prompt so a discard of the queue (new chat, history load)
+ // can't leave it set to leak into the next, unrelated turn. The drain
+ // restores it onto the ref before re-entering handleSend.
+ const queuedFixOrigin = fixOriginPendingRef.current;
+ fixOriginPendingRef.current = false;
updateQueuedPrompt({
id: queuedId,
content: candidate,
reason,
audioBlob: messageAudioBlob,
+ fixOrigin: queuedFixOrigin,
});
// First queue adds the user bubble; a re-queue (a working drain that
// then had to wait for the browser) reuses the existing bubble.
@@ -1476,6 +1493,10 @@ export function WorkflowCopilotChat({
}
};
+ // Consume the one-shot fix-origin signal before any awaitable send step so a pre-stream
+ // failure (e.g. getSseClient throwing) can't leave it set to leak into the next turn.
+ const fixOrigin = fixOriginPendingRef.current;
+ fixOriginPendingRef.current = false;
const client = await getSseClient(credentialGetter);
const targetBlockLabel = blockBuildTargetLabelRef.current;
blockBuildTargetLabelRef.current = null;
@@ -1498,6 +1519,7 @@ export function WorkflowCopilotChat({
isBuild && codeBlockModeEnabled ? codeBlockRequestOverride : null,
cancel_token: cancelToken,
target_block_label: targetBlockLabel,
+ fix_origin: fixOrigin,
} as WorkflowCopilotChatRequest,
(payload) => {
switch (payload.type) {
@@ -1741,6 +1763,9 @@ export function WorkflowCopilotChat({
// prompt that still needs the browser re-queues under the same id and
// drains via the live_browser path once the session arrives.
updateQueuedPrompt(null);
+ // Restore the fix-origin signal the prompt carried so the drained turn
+ // sends it; a re-queue (working → live_browser) re-captures it off the ref.
+ fixOriginPendingRef.current = promptToSend.fixOrigin ?? false;
handleSend(promptToSend.content, {
queuedMessageId: promptToSend.id,
skipQueue: drainAction === "drain_skip_queue",
@@ -1781,12 +1806,16 @@ export function WorkflowCopilotChat({
// live browser isn't ready yet.
hasAutoSentRef.current = true;
onInitialMessageConsumedRef.current?.();
+ if (initialMessageFixOrigin) {
+ fixOriginPendingRef.current = true;
+ }
handleSend(initialMessage).catch((error) => {
console.error("Auto-send failed:", error);
});
}, [
handleSend,
initialMessage,
+ initialMessageFixOrigin,
isLoading,
isLoadingHistory,
queuedPrompt,
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index db0285b0a..19b57a014 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -43,6 +43,7 @@ export interface WorkflowCopilotChatRequest {
code_block?: boolean | null;
cancel_token?: string;
target_block_label?: string | null;
+ fix_origin?: boolean;
}
export interface WorkflowCopilotCancelRequest {
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index 3f92480a7..4dc059c4a 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -340,11 +340,15 @@ function Workspace({
: 0;
const location = useLocation();
const navigate = useNavigate();
- const locationState = location.state as { copilotMessage?: unknown } | null;
+ const locationState = location.state as {
+ copilotMessage?: unknown;
+ copilotFixOrigin?: unknown;
+ } | null;
const initialCopilotMessage =
typeof locationState?.copilotMessage === "string"
? locationState.copilotMessage
: null;
+ const initialCopilotFixOrigin = locationState?.copilotFixOrigin === true;
const handleInitialCopilotMessageConsumed = useCallback(() => {
if (!initialCopilotMessage) return;
navigate(location.pathname + location.search, {
@@ -2373,6 +2377,7 @@ function Workspace({
requiresLiveBrowser={copilotRequiresLiveBrowser}
isLiveBrowserReady={copilotLiveBrowserReady}
initialMessage={initialCopilotMessage ?? undefined}
+ initialMessageFixOrigin={initialCopilotFixOrigin}
onInitialMessageConsumed={handleInitialCopilotMessageConsumed}
onBlockSelect={(blockLabel) => {
const matches = (node: AppNode) =>
diff --git a/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx b/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx
index 3031fff7f..884f5f8f6 100644
--- a/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx
@@ -42,7 +42,7 @@ export function RunTab() {
// Seed via location.state (Workspace reads it as the copilot's initialMessage);
// replace so Fix adds no Back-able entry and the message can't re-fire on Back.
navigate(`${location.pathname}${location.search}`, {
- state: { copilotMessage: seedMessage },
+ state: { copilotMessage: seedMessage, copilotFixOrigin: true },
replace: true,
});
setCopilotCollapsed(false);
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index be437fdfa..763735732 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -262,6 +262,7 @@ class RequestPolicyGuardrailInputs:
workflow_permanent_id: str | None = None
workflow_run_id: str | None = None
browser_session_id: str | None = None
+ fix_origin: bool = False
stored_completion_criteria: StoredCriteriaSnapshot | None = None
@@ -456,6 +457,7 @@ def _store_request_policy_on_context(
workflow_run_id=policy_inputs.workflow_run_id,
browser_session_id=policy_inputs.browser_session_id,
classifier_result=turn_intent_classifier_result,
+ fix_origin=policy_inputs.fix_origin,
)
@@ -3780,6 +3782,7 @@ async def _run_copilot_turn_impl(
workflow_permanent_id=chat_request.workflow_permanent_id,
workflow_run_id=getattr(chat_request, "workflow_run_id", None),
browser_session_id=getattr(chat_request, "browser_session_id", None),
+ fix_origin=getattr(chat_request, "fix_origin", False),
stored_completion_criteria=stored_completion_criteria,
)
request_policy_guardrails = _build_copilot_input_guardrails(
diff --git a/skyvern/forge/sdk/copilot/turn_intent.py b/skyvern/forge/sdk/copilot/turn_intent.py
index e6eb7a607..7cc3f3e01 100644
--- a/skyvern/forge/sdk/copilot/turn_intent.py
+++ b/skyvern/forge/sdk/copilot/turn_intent.py
@@ -110,6 +110,7 @@ class TurnIntentReasonCode(StrEnum):
RAW_SECRET_REFUSAL = "raw_secret_refusal"
USER_NON_PROGRESS = "user_non_progress"
RECOVERY_FROM_RUN_CONTEXT = "recovery_from_run_context"
+ FIX_ORIGIN_DIAGNOSE = "fix_origin_diagnose"
LLM_CLASSIFIER = "llm_classifier"
LOW_CONFIDENCE_CLARIFICATION = "low_confidence_clarification"
TARGET_ENTITY_RESOLVED = "target_entity_resolved"
@@ -754,6 +755,7 @@ def build_turn_intent(
workflow_run_id: str | None = None,
browser_session_id: str | None = None,
classifier_result: TurnIntentClassifierResult | None = None,
+ fix_origin: bool = False,
) -> TurnIntent:
has_workflow = bool((workflow_yaml or "").strip())
has_prior_context = bool((global_llm_context or "").strip())
@@ -865,6 +867,14 @@ def build_turn_intent(
reason_codes.append(TurnIntentReasonCode.LLM_CLASSIFIER)
reason_codes.extend(classification.reason_codes)
+ # Runs before the LOW_CONFIDENCE / MISSING_EDIT_TARGET downgrades: a CLARIFY here is only a request-policy
+ # clarification (already set) that, like REFUSE, still wins; a confident/would-be-downgraded edit becomes DIAGNOSE.
+ if fix_origin and has_prior_run_signal and mode not in (TurnIntentMode.REFUSE, TurnIntentMode.CLARIFY):
+ mode = TurnIntentMode.DIAGNOSE
+ expected_output = TurnIntentExpectedOutput.RUN_RESULT
+ target_entities.pop("workflow_change", None)
+ reason_codes.append(TurnIntentReasonCode.FIX_ORIGIN_DIAGNOSE)
+
if (
classification is not None
and mode in _MUTATING_CLASSIFIER_MODES
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index 49d8acc18..da7efafac 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -115,6 +115,15 @@ class WorkflowCopilotChatRequest(BaseModel):
"other block unchanged. Used by the block-level Generate action."
),
)
+ fix_origin: bool = Field(
+ False,
+ description=(
+ "True when the turn originates from the 'Fix with Copilot' action on a failed run. Routes the "
+ "run-grounded turn to diagnose-first (DIAGNOSE, no write authority) instead of a direct rewrite. "
+ "Only takes effect when a run signal (workflow_run_id or prior run context) is present; "
+ "otherwise it is a no-op."
+ ),
+ )
class WorkflowCopilotCancelRequest(BaseModel):
diff --git a/tests/unit/test_copilot_turn_intent.py b/tests/unit/test_copilot_turn_intent.py
index c7af1a772..af109c52f 100644
--- a/tests/unit/test_copilot_turn_intent.py
+++ b/tests/unit/test_copilot_turn_intent.py
@@ -410,6 +410,172 @@ def test_build_turn_intent_allows_clear_workflow_change_edit_classification() ->
assert intent.target_entities["workflow_change"] == ["add_invoice_download_step"]
+def test_build_turn_intent_fix_origin_forces_diagnose_over_classifier_edit() -> None:
+ intent = build_turn_intent(
+ user_message="Diagnose why this run failed, then fix the workflow so it succeeds.",
+ workflow_yaml=(
+ "title: Existing\nworkflow_definition:\n blocks:\n - block_type: code\n label: find_top_country\n"
+ ),
+ chat_history=[],
+ global_llm_context="",
+ request_policy=RequestPolicy(),
+ workflow_run_id="wr_123",
+ classifier_result=_classification(
+ TurnIntentMode.EDIT,
+ confidence=0.93,
+ target_entities={"workflow_change": ["fix_find_top_country"]},
+ ),
+ fix_origin=True,
+ )
+
+ assert intent.mode == TurnIntentMode.DIAGNOSE
+ assert intent.authority.may_update_workflow is False
+ assert intent.authority.may_read_run_context is True
+ assert TurnIntentReasonCode.FIX_ORIGIN_DIAGNOSE in intent.reason_codes
+ # The DIAGNOSE force drops the classifier's edit target (mirrors the CLARIFY force) but keeps the run.
+ assert "workflow_change" not in intent.target_entities
+ assert intent.target_entities.get("run") == ["wr_123"]
+
+
+def test_build_turn_intent_fix_origin_forces_diagnose_over_classifier_build() -> None:
+ intent = build_turn_intent(
+ user_message="Diagnose why this run failed, then fix the workflow so it succeeds.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
+ chat_history=[],
+ global_llm_context="",
+ request_policy=RequestPolicy(),
+ workflow_run_id="wr_123",
+ classifier_result=_classification(TurnIntentMode.BUILD, confidence=0.9),
+ fix_origin=True,
+ )
+
+ assert intent.mode == TurnIntentMode.DIAGNOSE
+ assert intent.authority.may_update_workflow is False
+ assert TurnIntentReasonCode.FIX_ORIGIN_DIAGNOSE in intent.reason_codes
+
+
+def test_build_turn_intent_fix_origin_yields_to_raw_secret_refusal() -> None:
+ policy = RequestPolicy(
+ credential_input_kind="raw_secret",
+ raw_secret_detected=True,
+ clarification_question="Store the credential in the Credentials UI.",
+ )
+ intent = build_turn_intent(
+ user_message="Fix the run; the password is hunter2.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
+ chat_history=[],
+ global_llm_context="",
+ request_policy=policy,
+ workflow_run_id="wr_123",
+ classifier_result=_classification(TurnIntentMode.EDIT, target_entities={"workflow_change": ["x"]}),
+ fix_origin=True,
+ )
+
+ assert intent.mode == TurnIntentMode.REFUSE
+ assert TurnIntentReasonCode.FIX_ORIGIN_DIAGNOSE not in intent.reason_codes
+
+
+def test_build_turn_intent_fix_origin_without_run_signal_does_not_force_diagnose() -> None:
+ intent = build_turn_intent(
+ user_message="Add a step that downloads the invoice PDF.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
+ chat_history=[],
+ global_llm_context="",
+ request_policy=RequestPolicy(allow_run_blocks=False),
+ classifier_result=_classification(
+ TurnIntentMode.EDIT,
+ confidence=0.82,
+ target_entities={"workflow_change": ["add_invoice_download_step"]},
+ ),
+ fix_origin=True,
+ )
+
+ assert intent.mode == TurnIntentMode.EDIT
+ assert TurnIntentReasonCode.FIX_ORIGIN_DIAGNOSE not in intent.reason_codes
+
+
+def test_build_turn_intent_without_fix_origin_keeps_classifier_edit_on_run() -> None:
+ intent = build_turn_intent(
+ user_message="Add a step that downloads the invoice PDF.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
+ chat_history=[],
+ global_llm_context="",
+ request_policy=RequestPolicy(allow_run_blocks=False),
+ workflow_run_id="wr_123",
+ classifier_result=_classification(
+ TurnIntentMode.EDIT,
+ confidence=0.82,
+ target_entities={"workflow_change": ["add_invoice_download_step"]},
+ ),
+ )
+
+ assert intent.mode == TurnIntentMode.EDIT
+ assert intent.authority.may_update_workflow is True
+ assert TurnIntentReasonCode.FIX_ORIGIN_DIAGNOSE not in intent.reason_codes
+
+
+def test_build_turn_intent_fix_origin_overrides_low_confidence_clarify() -> None:
+ # A low-confidence classifier EDIT would normally degrade to CLARIFY; an explicit Fix click must
+ # still diagnose-first rather than ask "what change should I make?".
+ intent = build_turn_intent(
+ user_message="Diagnose why this run failed, then fix it.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
+ chat_history=[],
+ global_llm_context="",
+ request_policy=RequestPolicy(),
+ workflow_run_id="wr_123",
+ classifier_result=_classification(TurnIntentMode.EDIT, confidence=0.35),
+ fix_origin=True,
+ )
+
+ assert intent.mode == TurnIntentMode.DIAGNOSE
+ assert intent.authority.may_update_workflow is False
+ assert TurnIntentReasonCode.FIX_ORIGIN_DIAGNOSE in intent.reason_codes
+ assert TurnIntentReasonCode.LOW_CONFIDENCE_CLARIFICATION not in intent.reason_codes
+
+
+def test_build_turn_intent_fix_origin_overrides_missing_edit_target_clarify() -> None:
+ # A confident EDIT with no specific change target would normally degrade to CLARIFY (MISSING_EDIT_TARGET);
+ # an explicit Fix click must diagnose-first instead, and the workflow_change pop is a no-op (no entry).
+ intent = build_turn_intent(
+ user_message="Fix the workflow so this run succeeds.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
+ chat_history=[],
+ global_llm_context="",
+ request_policy=RequestPolicy(),
+ workflow_run_id="wr_123",
+ classifier_result=_classification(TurnIntentMode.EDIT, confidence=0.9),
+ fix_origin=True,
+ )
+
+ assert intent.mode == TurnIntentMode.DIAGNOSE
+ assert intent.authority.may_update_workflow is False
+ assert TurnIntentReasonCode.FIX_ORIGIN_DIAGNOSE in intent.reason_codes
+ assert TurnIntentReasonCode.MISSING_EDIT_TARGET not in intent.reason_codes
+ assert "workflow_change" not in intent.target_entities
+
+
+def test_build_turn_intent_fix_origin_yields_to_request_policy_clarify() -> None:
+ # A genuine clarification request (request policy) still wins over the fix-origin diagnose force.
+ policy = RequestPolicy(
+ user_response_policy="ask_clarification",
+ clarification_question="Which run should I diagnose?",
+ )
+ intent = build_turn_intent(
+ user_message="Fix this run.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
+ chat_history=[],
+ global_llm_context="",
+ request_policy=policy,
+ workflow_run_id="wr_123",
+ classifier_result=_classification(TurnIntentMode.EDIT),
+ fix_origin=True,
+ )
+
+ assert intent.mode == TurnIntentMode.CLARIFY
+ assert TurnIntentReasonCode.FIX_ORIGIN_DIAGNOSE not in intent.reason_codes
+
+
@pytest.mark.parametrize(
("block_ref", "expected_label"),
[