Skip to content

Automate browser based workflows with AI

SKY-15406: Record which gesture cancelled a copilot turn, and stop asserting the user did it (#8431)

Andrew Neilsone90c6b18b9c7
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
index 3087b1570..43c569df1 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
@@ -1939,7 +1939,8 @@ describe("a real cancel's backend payload still renders neutrally", () => {
},
],
terminal: "error",
- terminalMessage: "Cancelled by user.",
+ terminalMessage:
+ "Stopped. 1 block ran this turn. No workflow draft from this turn was preserved.",
narrativeSummary: null,
cancelled: true,
priorBlockCount: null,
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
index a42c8638a..9e6b59620 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
@@ -7,6 +7,7 @@ import {
waitFor,
} from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useCopilotActionStore } from "@/store/useCopilotActionStore";
import { COPILOT_WORKING_VERBS } from "./workingVerbs";
import {
@@ -180,12 +181,31 @@ async function submit(value: string) {
});
}
+async function deliverFirstFrame() {
+ const call = streamCalls[streamCalls.length - 1];
+ if (!call) throw new Error("no pending stream to open");
+ await act(async () => {
+ call.onMessage({
+ type: "turn_start",
+ turn_id: "turn-1",
+ turn_index: 0,
+ mode: "build",
+ timestamp: "2026-05-25T00:00:00Z",
+ });
+ });
+}
+
beforeEach(() => {
HTMLElement.prototype.scrollIntoView = vi.fn();
HTMLElement.prototype.scrollTo = vi.fn();
streamCalls.length = 0;
postStreaming.mockClear();
cancelPost.mockClear();
+ useCopilotActionStore.setState({
+ pendingBuild: null,
+ generatingBlockLabel: null,
+ cancelNonce: 0,
+ });
historyResponse.data = {
workflow_copilot_chat_id: null,
chat_history: [],
@@ -249,6 +269,18 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ // Sent but not yet streaming: the control stays pressable, and the cancel
+ // chokepoint - not a disabled attribute - is what issues nothing.
+ const pending = screen.getByRole("button", { name: "Starting…" });
+ expect(pending.hasAttribute("disabled")).toBe(false);
+ expect(pending.getAttribute("aria-busy")).not.toBe("true");
+ await act(async () => {
+ fireEvent.click(pending);
+ });
+ expect(cancelPost).not.toHaveBeenCalled();
+ expect(postStreaming).toHaveBeenCalledTimes(1);
+ await deliverFirstFrame();
+
const button = screen.getByRole("button", { name: "Stop" });
expect(screen.getByTestId("copilot-stop-orbit").className).not.toContain(
"paused",
@@ -272,6 +304,89 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {
);
});
+ it("arms stop on the first streamed frame even when that frame carries no turn id", async () => {
+ await renderChat({ copilotV2: true, codeBlockMode: true });
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+
+ const call = streamCalls[streamCalls.length - 1];
+ if (!call) throw new Error("no pending stream to open");
+ await act(async () => {
+ call.onMessage({ type: "condensing" });
+ });
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Stop" }));
+ });
+ await waitFor(() => expect(cancelPost).toHaveBeenCalledTimes(1));
+ });
+
+ it("re-arms stop once a turn has streamed nothing for the arming window", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ await renderChat({ copilotV2: true, codeBlockMode: true });
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ expect(screen.getByRole("button", { name: "Starting…" })).toBeTruthy();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(20_000);
+ });
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Stop" }));
+ });
+ await waitFor(() => expect(cancelPost).toHaveBeenCalledTimes(1));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("cancels a block-level stop before the first frame, when Stop itself would not", async () => {
+ // The arming gate exists so a fast double-click on Send is not "send, then cancel".
+ // A block's own cancel is a deliberate gesture, so it must not go dead during that
+ // window — a turn hanging before its first frame is when someone reaches for it.
+ await renderChat({ copilotV2: true, codeBlockMode: true });
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+
+ await act(async () => {
+ useCopilotActionStore.getState().requestCancel();
+ });
+ await waitFor(() => expect(cancelPost).toHaveBeenCalledTimes(1));
+ expect(cancelPost).toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ expect.objectContaining({ source: "stop_button" }),
+ );
+ });
+
+ it("hands a queued prompt back to the composer rather than letting the stop auto-fire it", async () => {
+ await renderChat({ copilotV2: true, codeBlockMode: true });
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+
+ fireEvent.change(textarea(), {
+ target: { value: "also grab the story scores" },
+ });
+ await act(async () => {
+ fireEvent.click(
+ screen.getByRole("button", { name: "Queue for next turn" }),
+ );
+ });
+ expect(textarea().value).toBe("");
+
+ await act(async () => {
+ useCopilotActionStore.getState().requestCancel();
+ });
+
+ // The stop lands, and the queued follow-up is handed back rather than auto-firing.
+ await waitFor(() => expect(cancelPost).toHaveBeenCalledTimes(1));
+ expect(postStreaming).toHaveBeenCalledTimes(1);
+ await waitFor(() =>
+ expect(textarea().value).toBe("also grab the story scores"),
+ );
+ });
+
it("flips back to a queueing send when typing mid-run, and queues on click", async () => {
await renderChat({ copilotV2: true, codeBlockMode: true });
await submit("build me a workflow");
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
index be25e071f..02c4595e7 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
@@ -251,6 +251,16 @@ async function submit(value: string) {
});
}
+// Deliver the first SSE frame of the newest pending stream, which is what arms
+// the stop control.
+async function deliverFirstFrame() {
+ const call = streamCalls[streamCalls.length - 1];
+ if (!call) throw new Error("no pending stream to open");
+ await act(async () => {
+ call.onMessage(turnStart());
+ });
+}
+
// Drive the oldest pending stream to a clean terminal frame.
async function completeOldestStream(message: string) {
const call = streamCalls.find((c) => c.body.message !== undefined);
@@ -347,6 +357,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await deliverFirstFrame();
expect(textarea().disabled).toBe(false);
expect(screen.getByRole("button", { name: "Cancel run" })).toBeTruthy();
@@ -356,6 +367,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await deliverFirstFrame();
expect(
screen.getByText(
@@ -417,6 +429,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
await renderChat();
await submit("first message");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await deliverFirstFrame();
await submit("second message");
@@ -444,15 +457,22 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
expect(screen.getAllByText("second message")).toHaveLength(1);
});
- it("Escape edits the queued message first, preserving the active run", async () => {
+ it("Escape in the composer edits the queued message, preserving the active run", async () => {
await renderChat();
await submit("first message");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await deliverFirstFrame();
await submit("second message");
+ const ambientEscape = vi.fn();
+ window.addEventListener("keydown", ambientEscape);
await act(async () => {
- fireEvent.keyDown(window, { key: "Escape" });
+ fireEvent.keyDown(textarea(), { key: "Escape" });
});
+ window.removeEventListener("keydown", ambientEscape);
+
+ // Consumed at the composer, so sibling window/document Escape listeners never see it.
+ expect(ambientEscape).not.toHaveBeenCalled();
// Queued text returns to the input; the run was not cancelled.
expect(textarea().value).toBe("second message");
@@ -461,6 +481,186 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
expect(screen.getByRole("button", { name: "Cancel run" })).toBeTruthy();
});
+ it("an IME Escape in the composer does not discard the queued message", async () => {
+ // Dismissing a conversion candidate is not abandoning the follow-up. The composer
+ // handler consumes Escape before the window guard can see it, so it has to make the
+ // composition check itself — otherwise the queued text is dropped with no bubble
+ // and no text, because the half-composed input wins the restore tiebreak.
+ await renderChat();
+ await submit("first message");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await deliverFirstFrame();
+ await submit("second message");
+
+ fireEvent.change(textarea(), { target: { value: "にほんご" } });
+ await act(async () => {
+ fireEvent.keyDown(textarea(), { key: "Escape", isComposing: true });
+ });
+
+ // The queued message survives, and the composition text is left alone.
+ expect(textarea().value).toBe("にほんご");
+ expect(screen.getAllByText("second message").length).toBeGreaterThan(0);
+ expect(cancelPost).not.toHaveBeenCalled();
+ });
+
+ it("an Escape pressed during IME composition never cancels the turn", async () => {
+ await renderChat();
+ await submit("first message");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await deliverFirstFrame();
+
+ const outside = document.createElement("button");
+ document.body.appendChild(outside);
+ outside.focus();
+ expect(document.activeElement).toBe(outside);
+
+ // Dismissing a conversion candidate, not stopping the turn.
+ await act(async () => {
+ fireEvent.keyDown(window, { key: "Escape", isComposing: true });
+ fireEvent.keyDown(outside, { key: "Escape", isComposing: true });
+ });
+
+ expect(cancelPost).not.toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ expect.anything(),
+ );
+ expect(screen.getByRole("button", { name: "Cancel run" })).toBeTruthy();
+ outside.remove();
+ });
+
+ it("Escape outside the composer stops the turn and records the gesture", async () => {
+ await renderChat();
+ await submit("first message");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await deliverFirstFrame();
+
+ const outside = document.createElement("button");
+ document.body.appendChild(outside);
+ outside.focus();
+
+ await act(async () => {
+ fireEvent.keyDown(window, { key: "Escape" });
+ });
+
+ expect(cancelPost).toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ expect.objectContaining({
+ cancel_token: expect.any(String),
+ source: "escape_key",
+ }),
+ );
+ outside.remove();
+ });
+
+ it("the stop control does not cancel before the turn's first frame arrives", async () => {
+ await renderChat();
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+
+ // Sent, but no SSE frame has been delivered to the reducer yet: the control is
+ // mounted and pressable, so a click on it is the negative arm.
+ const pending = screen.getByRole("button", { name: "Starting…" });
+ expect(pending.hasAttribute("disabled")).toBe(false);
+ expect(pending.getAttribute("aria-busy")).not.toBe("true");
+ await act(async () => {
+ fireEvent.click(pending);
+ });
+ expect(cancelPost).not.toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ expect.anything(),
+ );
+
+ await deliverFirstFrame();
+
+ const stop = screen.getByRole("button", { name: "Cancel run" });
+ await act(async () => {
+ fireEvent.click(stop);
+ });
+
+ expect(cancelPost).toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ expect.objectContaining({
+ cancel_token: expect.any(String),
+ source: "stop_button",
+ }),
+ );
+ });
+
+ it("arms the visible stop shortly after send even when no frame ever streams", async () => {
+ // The gate exists for the second click of a double-tap, not to leave the control a
+ // user reaches for dead while a turn hangs before its first frame.
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ await renderChat();
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Starting…" }));
+ });
+ expect(cancelPost).not.toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ expect.anything(),
+ );
+
+ // Past the double-tap window, with no frame delivered at any point.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(600);
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Cancel run" }));
+ });
+ expect(cancelPost).toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ expect.objectContaining({ source: "stop_button" }),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("does not let a stalled turn's arming deadline arm the turn its queued prompt drains into", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ await renderChat();
+ await submit("first message");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await submit("second message");
+
+ // Stop just short of the first turn's arming deadline, hand over to the turn its
+ // queued prompt drains into, then cross that deadline: it belongs to the turn that
+ // scheduled it and must not arm the one now running.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ await completeOldestStream("first done");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(200);
+ });
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Starting…" }));
+ });
+ expect(cancelPost).not.toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ expect.anything(),
+ );
+
+ await deliverFirstFrame();
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Cancel run" }));
+ });
+ expect(cancelPost).toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ expect.anything(),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("clears the queued block-build target on cancel so it cannot leak into the next message", async () => {
await renderChat();
await submit("first message");
@@ -477,7 +677,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
// Cancel the queued block-build before it sends.
await act(async () => {
- fireEvent.keyDown(window, { key: "Escape" });
+ fireEvent.keyDown(textarea(), { key: "Escape" });
});
// Finish the original turn and send an unrelated follow-up.
@@ -741,7 +941,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
await act(async () => {
call.onMessage(turnStart());
call.onMessage({
- ...terminalResponse("Cancelled by user."),
+ ...terminalResponse("Stopped. 0 blocks ran this turn."),
proposal_disposition: "no_proposal",
cancelled: true,
});
@@ -1428,6 +1628,7 @@ describe("WorkflowCopilotChat — a stop never replays a queued message", () =>
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await deliverFirstFrame();
await submit("also add a login step");
expect(screen.getAllByText("also add a login step")).toHaveLength(1);
@@ -1447,6 +1648,7 @@ describe("WorkflowCopilotChat — a stop never replays a queued message", () =>
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await deliverFirstFrame();
const stop = screen.getByRole("button", { name: /Cancel run/ });
expect(stop.hasAttribute("disabled")).toBe(false);
@@ -1493,6 +1695,7 @@ describe("WorkflowCopilotChat — the composer stays usable while a prompt is pa
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await deliverFirstFrame();
await submit("queued answer");
// Half-typed replacement, never submitted.
fireEvent.change(textarea(), {
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index ff649c464..a7aee1c61 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -39,6 +39,7 @@ import { toast } from "@/components/ui/use-toast";
import { getSseClient } from "@/api/sse";
import {
WorkflowCopilotCancelRequest,
+ WorkflowCopilotCancelSource,
WorkflowCopilotChatHistoryResponse,
WorkflowCopilotDesignEndUpdate,
WorkflowCopilotDesignStartUpdate,
@@ -192,6 +193,20 @@ function collectTimelineBlockActions(
const ASK_GLYPH = "\u275D\uFE0E";
const BUILD_GLYPH = "\uD83D\uDC09";
+// What the arming gate is actually for: the second click of a double-tap on Send, which
+// lands on the morphed control a moment later. That is a sub-second gesture, so the
+// window is sized to it — long enough to swallow the stray click, short enough that the
+// visible Stop is not dead while a turn hangs. The first frame arms sooner and clears it.
+const STOP_ARM_DOUBLE_TAP_MS = 500;
+
+const STOP_UNCONFIRMED_NOTICE =
+ "I sent the stop, but couldn't confirm what this turn recorded. Reload to see the turn's own report.";
+
+// The request itself failed, so the stop never reached the backend and the turn may
+// still be running. Saying "I sent the stop" here would claim something that did not happen.
+const STOP_NOT_SENT_NOTICE =
+ "I couldn't send the stop. Reload to see what this turn recorded.";
+
const STOP_ORBIT_GRADIENT =
"conic-gradient(from 0deg, rgba(120,170,255,.08) 0deg, rgba(120,170,255,.08) 120deg, rgba(150,195,255,.55) 250deg, #dbeaff 330deg, rgba(120,170,255,.08) 360deg)";
@@ -308,8 +323,8 @@ export interface ChatMessage {
// so the per-block cards persist as the user scrolls back through past
// turns. Live in-flight narrative is rendered separately at the bottom.
narrative?: TurnNarrativeState;
- // FE-synthetic run status line (never persisted, never sent to the LLM).
- kind?: "run_lifecycle";
+ // FE-synthetic rows (never persisted, never sent to the LLM).
+ kind?: "run_lifecycle" | "status_notice";
}
function connectedAccountSelectionReceipt(
@@ -746,6 +761,7 @@ export function WorkflowCopilotChat({
// A stop is a round trip to the backend; without this the control stays
// live-looking and users press it repeatedly.
const [isStopping, setIsStopping] = useState(false);
+ const [stopArmed, setStopArmed] = useState(false);
useTurnActivityChange(isLoading, onTurnActivityChange);
const [queuedPrompt, setQueuedPrompt] = useState<QueuedPrompt | null>(null);
const [narrative, setNarrative] =
@@ -836,6 +852,16 @@ export function WorkflowCopilotChat({
} | null>(null);
const pendingMessageId = useRef<string | null>(null);
const pendingCancelToken = useRef<string | null>(null);
+ // Read by cancelSend, which must not re-create on every render of the arming signal.
+ const turnObservablyRunningRef = useRef(false);
+ const stopArmTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const armStop = useCallback(() => {
+ if (stopArmTimer.current !== null) {
+ clearTimeout(stopArmTimer.current);
+ stopArmTimer.current = null;
+ }
+ setStopArmed(true);
+ }, []);
const cancelSafetyTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const gateFlashTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Backend cancel watcher polls Redis: a turn can complete normally between
@@ -891,6 +917,10 @@ export function WorkflowCopilotChat({
clearTimeout(cancelSafetyTimer.current);
cancelSafetyTimer.current = null;
}
+ if (stopArmTimer.current !== null) {
+ clearTimeout(stopArmTimer.current);
+ stopArmTimer.current = null;
+ }
if (gateFlashTimer.current !== null) {
clearTimeout(gateFlashTimer.current);
gateFlashTimer.current = null;
@@ -1928,66 +1958,82 @@ export function WorkflowCopilotChat({
});
}, [adjustTextareaHeight, updateQueuedPrompt]);
- const cancelSend = useCallback(async () => {
- // A stop must never let a queued message auto-fire. Hand its text back to
- // the composer synchronously, before isLoading flips and the drain effect
- // would otherwise send it as a fresh turn.
- restoreQueuedPromptToComposer();
+ const cancelSend = useCallback(
+ async (
+ source: WorkflowCopilotCancelSource,
+ // A stop control must not fire before the turn is observably running, or a fast
+ // double-click on Send is "send, then cancel". The deliberate gestures -- Escape,
+ // and a block's own cancel -- are exempt, so a turn that hangs before its first
+ // frame is still stoppable rather than leaving every path dead for that window.
+ { requireArmed = true }: { requireArmed?: boolean } = {},
+ ) => {
+ // A stop must never let a queued message auto-fire. Hand its text back to
+ // the composer synchronously, before isLoading flips and the drain effect
+ // would otherwise send it as a fresh turn.
+ restoreQueuedPromptToComposer();
- // Capture upfront so the 15s timer below can't latch onto a next turn's controller.
- const controllerAtCancel = streamingAbortController.current;
- if (!controllerAtCancel) return;
+ if (requireArmed && !turnObservablyRunningRef.current) return;
- const cancelToken = pendingCancelToken.current;
- pendingCancelToken.current = null;
- // After the token check, not before: a turn that already finished has no
- // token, and claiming "Stopping…" for a cancel that never goes out would
- // rely on the isLoading reset as its only way back.
- if (!cancelToken) return;
+ // Capture upfront so the 15s timer below can't latch onto a next turn's controller.
+ const controllerAtCancel = streamingAbortController.current;
+ if (!controllerAtCancel) return;
- setIsStopping(true);
+ const cancelToken = pendingCancelToken.current;
+ pendingCancelToken.current = null;
+ // After the token check, not before: a turn that already finished has no
+ // token, and claiming "Stopping…" for a cancel that never goes out would
+ // rely on the isLoading reset as its only way back.
+ if (!cancelToken) return;
- cancelInFlightController.current = controllerAtCancel;
+ setIsStopping(true);
- const appendCancelledBubble = () => {
- setMessages((prev) => [
- ...prev,
- {
- id: `${Date.now()}-cancel`,
- sender: "ai",
- content: "Cancelled by user.",
- timestamp: new Date().toISOString(),
- },
- ]);
- // Otherwise the bubble freezes mid-state next to the Cancelled message.
- setNarrative(EMPTY_NARRATIVE);
- };
+ cancelInFlightController.current = controllerAtCancel;
- try {
- const client = await getClient(credentialGetter, "sans-api-v1");
- await client.post<void>("/workflow/copilot/cancel", {
- cancel_token: cancelToken,
- } as WorkflowCopilotCancelRequest);
- // Safety net: if the SSE channel never resolves, surface a fallback
- // bubble and abort so handleSend's finally clears "Cancelling...".
- if (cancelSafetyTimer.current !== null) {
- clearTimeout(cancelSafetyTimer.current);
- }
- cancelSafetyTimer.current = setTimeout(() => {
- cancelSafetyTimer.current = null;
- if (streamingAbortController.current !== controllerAtCancel) return;
- appendCancelledBubble();
+ // The backend is still running when this fires, so it cannot report what the
+ // turn recorded; the persisted row stays authoritative on reload.
+ const appendStopUnconfirmedNotice = (content: string) => {
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: `${Date.now()}-cancel`,
+ sender: "ai",
+ content,
+ timestamp: new Date().toISOString(),
+ kind: "status_notice",
+ },
+ ]);
+ // Otherwise the working bubble freezes mid-state next to the notice.
+ setNarrative(EMPTY_NARRATIVE);
+ };
+
+ try {
+ const client = await getClient(credentialGetter, "sans-api-v1");
+ await client.post<void>("/workflow/copilot/cancel", {
+ cancel_token: cancelToken,
+ source,
+ } as WorkflowCopilotCancelRequest);
+ // Safety net: if the SSE channel never resolves, surface a fallback
+ // bubble and abort so handleSend's finally clears "Cancelling...".
+ if (cancelSafetyTimer.current !== null) {
+ clearTimeout(cancelSafetyTimer.current);
+ }
+ cancelSafetyTimer.current = setTimeout(() => {
+ cancelSafetyTimer.current = null;
+ if (streamingAbortController.current !== controllerAtCancel) return;
+ appendStopUnconfirmedNotice(STOP_UNCONFIRMED_NOTICE);
+ controllerAtCancel.abort();
+ }, 15_000);
+ } catch (error) {
+ // 503 (Redis disabled) or network failure: client-side abort still
+ // gives the user immediate feedback; the backend will run to
+ // completion in that environment. Log so we can spot it in dev.
+ console.warn("Workflow copilot cancel POST failed", error);
controllerAtCancel.abort();
- }, 15_000);
- } catch (error) {
- // 503 (Redis disabled) or network failure: client-side abort still
- // gives the user immediate feedback; the backend will run to
- // completion in that environment. Log so we can spot it in dev.
- console.warn("Workflow copilot cancel POST failed", error);
- controllerAtCancel.abort();
- appendCancelledBubble();
- }
- }, [credentialGetter, restoreQueuedPromptToComposer]);
+ appendStopUnconfirmedNotice(STOP_NOT_SENT_NOTICE);
+ }
+ },
+ [credentialGetter, restoreQueuedPromptToComposer],
+ );
// The turn ending is the one signal that a stop actually landed — it covers
// the normal path, the 15s safety-timer abort, and the failed-POST abort.
@@ -2002,12 +2048,17 @@ export function WorkflowCopilotChat({
if (event.key !== "Escape" || !isOpen) {
return;
}
+ // Dismissing an IME conversion candidate fires Escape with isComposing
+ // set; the user is editing text, not stopping their turn.
+ if (event.isComposing) {
+ return;
+ }
if (queuedPrompt) {
restoreQueuedPromptToComposer();
return;
}
if (isLoading) {
- cancelSend();
+ cancelSend("escape_key", { requireArmed: false });
}
};
@@ -2172,6 +2223,18 @@ export function WorkflowCopilotChat({
streamingAbortController.current?.abort();
streamingAbortController.current = abortController;
+ setStopArmed(false);
+ if (stopArmTimer.current !== null) {
+ clearTimeout(stopArmTimer.current);
+ }
+ stopArmTimer.current = setTimeout(() => {
+ stopArmTimer.current = null;
+ // A queued prompt can drain into a next turn before this fires; only the
+ // turn that scheduled it may arm.
+ if (streamingAbortController.current !== abortController) return;
+ setStopArmed(true);
+ }, STOP_ARM_DOUBLE_TAP_MS);
+
try {
const saveData = getSaveData();
const workflowId = saveData?.workflow.workflow_id;
@@ -2490,6 +2553,11 @@ export function WorkflowCopilotChat({
supports_credential_pause: true,
} as WorkflowCopilotChatRequest,
(payload) => {
+ // Same identity check the fallback timer makes: a frame buffered from an
+ // aborted stream must not arm the turn that replaced it.
+ if (streamingAbortController.current === abortController) {
+ armStop();
+ }
switch (payload.type) {
case "processing_update":
handleProcessingUpdate(payload);
@@ -2654,6 +2722,11 @@ export function WorkflowCopilotChat({
clearTimeout(cancelSafetyTimer.current);
cancelSafetyTimer.current = null;
}
+ if (stopArmTimer.current !== null) {
+ clearTimeout(stopArmTimer.current);
+ stopArmTimer.current = null;
+ }
+ setStopArmed(false);
pendingMessageId.current = null;
pendingCancelToken.current = null;
// Backstop: roll back a continuation that didn't genuinely complete —
@@ -2671,6 +2744,7 @@ export function WorkflowCopilotChat({
[
applyStoredNarrativeEvent,
applyWorkflowUpdate,
+ armStop,
autoAccept,
codeBlockModeEnabled,
codeBlockRequestOverride,
@@ -2821,11 +2895,23 @@ export function WorkflowCopilotChat({
);
return;
}
- void cancelSend();
+ void cancelSend("stop_button", { requireArmed: false });
}
}, [blockCancelNonce, cancelSend, updateQueuedPrompt]);
const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ // Escape and Enter both mean something to an IME mid-composition: dismissing a
+ // conversion candidate and committing one. React's synthetic event does not carry
+ // isComposing, so the native one is what can be asked.
+ if (e.nativeEvent.isComposing) {
+ return;
+ }
+ if (e.key === "Escape" && queuedPrompt) {
+ e.preventDefault();
+ e.stopPropagation();
+ restoreQueuedPromptToComposer();
+ return;
+ }
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
@@ -3132,6 +3218,20 @@ export function WorkflowCopilotChat({
[messages],
);
+ // Stoppable between the turn's first streamed frame and its terminal one; isLoading
+ // alone is true from send. Issuing a cancel clears the token, so isStopping holds it.
+ const turnObservablyRunning =
+ isStopping ||
+ (isLoading &&
+ stopArmed &&
+ narrative.terminal === null &&
+ pendingCancelToken.current !== null);
+ // A render-phase write would let a discarded pass latch, and a passive effect
+ // would leave Stop painted armed while cancelSend still reads false.
+ useLayoutEffect(() => {
+ turnObservablyRunningRef.current = turnObservablyRunning;
+ }, [turnObservablyRunning]);
+
if (!isOpen) {
return null;
}
@@ -3187,18 +3287,33 @@ export function WorkflowCopilotChat({
queuedPrompt.reason === "live_browser" &&
!messages.some((message) => message.id === queuedPrompt.id),
);
- const showsStopGlyph = isStopping || (isLoading && !hasComposerText);
+ const showsStopGlyph =
+ isStopping || (turnObservablyRunning && !hasComposerText);
+ // Sent, no frame yet: the control reports the wait rather than an action, and
+ // cancelSend's own guard is what makes a press in this window issue no cancel.
+ const turnPendingFirstFrame =
+ isLoading && !turnObservablyRunning && narrative.terminal === null;
+ const morphButtonPending = turnPendingFirstFrame && !hasComposerText;
+ const legacyCancelLabel = turnPendingFirstFrame
+ ? "Starting…"
+ : isStopping
+ ? "Stopping…"
+ : "Cancel run";
const morphButtonLabel = isStopping
? "Stopping…"
: waitingOnQueueOnly
? "Send disabled — waiting for live browser"
- : queuedPrompt && hasComposerText
- ? "Replace queued message"
- : !isLoading
- ? "Send"
- : hasComposerText
- ? "Queue for next turn"
- : "Stop";
+ : morphButtonPending
+ ? "Starting…"
+ : queuedPrompt && hasComposerText
+ ? "Replace queued message"
+ : !turnObservablyRunning
+ ? isLoading
+ ? "Queue for next turn"
+ : "Send"
+ : hasComposerText
+ ? "Queue for next turn"
+ : "Stop";
// Shared between the legacy fused split-button and the S4 mode pill so the
// three options never drift between the two composer treatments.
const modeMenuItems = (
@@ -3396,6 +3511,13 @@ export function WorkflowCopilotChat({
/>
);
}
+ if (message.kind === "status_notice") {
+ return (
+ <div key={message.id} role="status" aria-live="polite">
+ <MessageItem message={message} />
+ </div>
+ );
+ }
// Per-message frozen narrative. When an AI message carries a
// frozen narrative, render the narrative card stack in place
// of the legacy text bubble so the per-block cards survive
@@ -3890,7 +4012,9 @@ export function WorkflowCopilotChat({
disabled={waitingOnQueueOnly || isStopping}
aria-busy={isStopping}
onClick={() =>
- isLoading && !hasComposerText ? cancelSend() : handleSend()
+ turnObservablyRunning && !hasComposerText
+ ? cancelSend("stop_button")
+ : handleSend()
}
aria-label={morphButtonLabel}
className={cn(
@@ -3942,13 +4066,13 @@ export function WorkflowCopilotChat({
Edit queued
</button>
<button
- onClick={cancelSend}
+ onClick={() => cancelSend("stop_button")}
disabled={isStopping}
aria-busy={isStopping}
- title={isStopping ? "Stopping…" : "Cancel run"}
+ title={legacyCancelLabel}
className="flex h-10 items-center justify-center rounded-lg bg-destructive px-3 text-sm font-medium text-destructive-foreground hover:bg-destructive/90 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
>
- {isStopping ? "Stopping…" : "Cancel run"}
+ {legacyCancelLabel}
</button>
</>
) : isLoading ? (
@@ -3963,13 +4087,13 @@ export function WorkflowCopilotChat({
</button>
<button
type="button"
- onClick={cancelSend}
+ onClick={() => cancelSend("stop_button")}
disabled={isStopping}
aria-busy={isStopping}
- title={isStopping ? "Stopping…" : "Cancel run"}
+ title={legacyCancelLabel}
className="flex h-10 items-center justify-center rounded-lg bg-destructive px-3 text-sm font-medium text-destructive-foreground hover:bg-destructive/90 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
>
- {isStopping ? "Stopping…" : "Cancel run"}
+ {legacyCancelLabel}
</button>
</>
) : queuedPrompt ? (
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts
index 28dc3b7a0..a137f0b68 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts
@@ -399,6 +399,7 @@ describe("hydrateNarrativeFromPayload — outcome", () => {
expect(withEnvelope.terminalEnvelope).toEqual({
runVerdict: "not_demonstrated",
runDisplayReason: "Checkout never reached confirmation.",
+ runOutcomeRole: null,
connectFailure: null,
});
@@ -412,6 +413,7 @@ describe("hydrateNarrativeFromPayload — outcome", () => {
expect(malformed.terminalEnvelope).toEqual({
runVerdict: null,
runDisplayReason: null,
+ runOutcomeRole: null,
connectFailure: null,
});
@@ -518,6 +520,25 @@ describe("notConfirmedOutcome — envelope-first", () => {
expect(outcome).toBeNull();
});
+ it("an interim run-start envelope does not suppress the recorded not-confirmed outcome", () => {
+ const outcome = notConfirmedOutcome({
+ ...base,
+ terminalEnvelope: {
+ runVerdict: "not_evaluated",
+ runDisplayReason: null,
+ runOutcomeRole: "interim_build_test",
+ },
+ lastRunOutcome: {
+ verdict: "not_demonstrated",
+ displayReason: "The earlier run never reached the dashboard.",
+ },
+ });
+ expect(outcome).toEqual({
+ verdict: "not_demonstrated",
+ displayReason: "The earlier run never reached the dashboard.",
+ });
+ });
+
it("envelope without a run verdict falls back to the legacy inference", () => {
const outcome = notConfirmedOutcome({
...base,
@@ -650,6 +671,31 @@ describe("canonical turn facts — card, pill and prose over one bundle", () =>
expect(card.isFail).toBe(false);
});
+ it("makes no completion claim when a stop left the run start unresolved", () => {
+ const recorded = bundles[CLEAN_RECORDED_TURN] as unknown as {
+ turnFacts: Record<string, unknown>;
+ };
+ const turn = hydrateNarrativeFromPayload({
+ ...(bundles[CLEAN_RECORDED_TURN] as unknown as Record<string, unknown>),
+ turnFacts: {
+ ...recorded.turnFacts,
+ runId: "wr_1",
+ runCompleted: null,
+ blocksRunThisTurn: null,
+ evaluationState: null,
+ ranCleanOnCurrentSource: false,
+ },
+ });
+ if (!turn) throw new Error("fixture did not hydrate");
+ const card = computeTurnSummary(turn);
+
+ expect(turn.turnFacts?.runCompleted).toBeNull();
+ expect(card.stats).toContain("1/1 ran on current source");
+ expect(card.stats).not.toContain("run completed");
+ expect(card.stats).not.toContain("run did not complete");
+ expect(getReviewGateVerdict(turn, null)).toBe("untested");
+ });
+
it("withholds success from a fully covered turn whose recorded run failed", () => {
const recorded = bundles[CLEAN_RECORDED_TURN] as unknown as {
blocks: Array<Record<string, unknown>>;
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index 8e710938e..5b918a532 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -168,6 +168,8 @@ function isBuildTestConnectFailureState(
export interface TerminalEnvelopeFacts {
runVerdict: BlockOutcome | null;
runDisplayReason: string | null;
+ // Absent on envelopes persisted before the role was carried.
+ runOutcomeRole?: RunOutcomeRole | null;
connectFailure?: {
state: BuildTestConnectFailureState;
retryAction: "test_end_to_end";
@@ -257,6 +259,7 @@ export function parseTerminalEnvelope(
browserSessionId: text("browser_session_id"),
};
})();
+ const role = obj.run_outcome_role;
return {
runVerdict:
v === "demonstrated" || v === "not_demonstrated" || v === "not_evaluated"
@@ -266,6 +269,12 @@ export function parseTerminalEnvelope(
typeof obj.run_display_reason === "string"
? obj.run_display_reason
: null,
+ runOutcomeRole:
+ role === "recorded" ||
+ role === "adjudicated" ||
+ role === "interim_build_test"
+ ? role
+ : null,
connectFailure,
};
}
@@ -1889,7 +1898,11 @@ export function notConfirmedOutcome(
// verdict; the pointer/block inference below only covers rows persisted
// before the envelope existed (or envelopes from run-less turns).
const envelope = turn.terminalEnvelope;
- if (envelope !== null && envelope.runVerdict !== null) {
+ if (
+ envelope !== null &&
+ envelope.runVerdict !== null &&
+ !isInterimOutcome(envelope.runOutcomeRole ?? undefined)
+ ) {
return envelope.runVerdict === "not_demonstrated"
? {
verdict: "not_demonstrated",
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index 358b344ac..95522d526 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -61,8 +61,11 @@ export interface WorkflowCopilotChatRequest {
supports_credential_pause?: boolean;
}
+export type WorkflowCopilotCancelSource = "escape_key" | "stop_button" | "api";
+
export interface WorkflowCopilotCancelRequest {
cancel_token: string;
+ source: WorkflowCopilotCancelSource;
}
export interface WorkflowCopilotChatHistoryMessage {
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index c482f1520..466a7e847 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -181,12 +181,17 @@ from skyvern.forge.sdk.copilot.streaming_adapter import (
maybe_emit_design_end,
)
from skyvern.forge.sdk.copilot.terminal_envelope import (
+ MINIMAL_CANCEL_STOP,
+ TESTED_DRAFT_PRESERVED,
+ UNTESTED_DRAFT_PRESERVED,
InterruptedTurnFacts,
TerminalCause,
TerminalOutcomeEnvelope,
assemble_terminal_envelope,
+ is_interim_run_outcome,
reason_in_reply_shadow,
render_terminal_message,
+ run_start_unresolved,
select_run_outcome_anchor,
)
from skyvern.forge.sdk.copilot.todo_list import todo_list_prompt
@@ -1480,6 +1485,13 @@ def _terminal_envelope_run_outcomes(ctx: CopilotContext) -> list[RecordedRunOutc
return [recorded] if isinstance(recorded, RecordedRunOutcome) else []
+def _blocks_run_this_turn(ctx: CopilotContext) -> int | None:
+ """None while a started run has no recorded result: an unresolved run's block count is unknown, not zero."""
+ if run_start_unresolved(_terminal_envelope_run_outcomes(ctx)):
+ return None
+ return len(ctx.executed_block_labels)
+
+
def _terminal_halt_fields(ctx: CopilotContext) -> tuple[str | None, str | None]:
halt = getattr(ctx, "turn_halt", None)
if not isinstance(halt, TurnHalt):
@@ -1526,14 +1538,16 @@ def _draft_ran_on_current_source(
facts: NarrativeTurnFacts, unresolved_failure: UnresolvedRuntimeFailure | None
) -> bool:
"""A tested draft claims full current-source coverage and a lifecycle that contradicts nothing:
- a halted turn, an unfinished or unconfirmed run, or an open block failure each disqualify it.
- ``runCompleted`` is None when no run is anchored to this turn, leaving the source-bound receipts
- as the only claim."""
+ a halted turn, an unfinished, unresolved or unconfirmed run, or an open block failure each
+ disqualify it. ``runCompleted`` is None both when no run is anchored to this turn and when a
+ started run never resolved, so only the former leaves the source-bound receipts as the claim."""
authored = facts.get("authoredBlockCount")
if not facts["factsAvailable"] or not authored or facts.get("matchingSourceBlockCount") != authored:
return False
if facts["terminalCause"] is not None or unresolved_failure is not None:
return False
+ if facts["runId"] is not None and facts["runCompleted"] is None:
+ return False
return facts["runCompleted"] is not False and facts["evaluationState"] != "not_demonstrated"
@@ -1573,9 +1587,12 @@ def _turn_fact_bundle(
unresolved_failure: UnresolvedRuntimeFailure | None = None,
) -> NarrativeTurnFacts:
run_id = run_outcome.workflow_run_id if run_outcome is not None else None
+ # A run start with no result behind it names a run without adjudicating one, so the
+ # evaluation slot stays empty while the lifecycle keeps the outcome's own unfinished state.
+ resolved_outcome = None if is_interim_run_outcome(run_outcome) else run_outcome
facts: NarrativeTurnFacts = {
"factsAvailable": review is not None,
- "evaluationState": run_outcome.verdict if run_outcome is not None else None,
+ "evaluationState": resolved_outcome.verdict if resolved_outcome is not None else None,
"runId": (run_id.strip() or None) if isinstance(run_id, str) else None,
"runCompleted": run_outcome.run_completed if run_outcome is not None else None,
"terminalCause": terminal_cause,
@@ -1600,7 +1617,7 @@ def _turn_facts_for_context(
review,
select_run_outcome_anchor(_terminal_envelope_run_outcomes(ctx)),
_terminal_cause_for_context(ctx),
- len(ctx.executed_block_labels),
+ _blocks_run_this_turn(ctx),
# The proposal these facts describe, not the turn-start persisted workflow. The terminal
# seam asks whether the workflow the user can run today still carries the failure and is
# right to read persistence; this pill claims the draft ran clean, so a failure the draft
@@ -1651,7 +1668,7 @@ def _assemble_terminal_envelope_safe(
response_type: str,
verified: bool,
workflow_applied: bool,
- proposal_disposition: str | None,
+ proposal_disposition: ProposalDisposition | None,
run_outcomes: Sequence[RecordedRunOutcome],
blocker_reason: str | None,
halt_kind: str | None,
@@ -1777,7 +1794,9 @@ def _make_agent_result(
response_type = kwargs.get("response_type", "REPLY")
response_type_value = response_type if isinstance(response_type, str) else "REPLY"
raw_disposition = kwargs.get("proposal_disposition")
- proposal_disposition: str | None = raw_disposition if isinstance(raw_disposition, str) else None
+ proposal_disposition: ProposalDisposition | None = (
+ raw_disposition if raw_disposition in get_args(ProposalDisposition) else None
+ )
if turn_facts is not None and proposal_disposition == "review_tested" and not turn_facts["ranCleanOnCurrentSource"]:
proposal_disposition = "review_untested"
kwargs["proposal_disposition"] = proposal_disposition
@@ -1901,7 +1920,7 @@ def _make_agent_result(
response_type=response_type_value,
verified=bool(outcome_fully_verified(ctx)),
workflow_applied=False,
- proposal_disposition=proposal_disposition if isinstance(proposal_disposition, str) else None,
+ proposal_disposition=proposal_disposition,
run_outcomes=_terminal_envelope_run_outcomes(ctx),
blocker_reason=blocker_reason,
halt_kind=halt_kind,
@@ -1910,7 +1929,7 @@ def _make_agent_result(
workflow_attempted=ctx.has_genuine_workflow_attempt(),
final_message=str(kwargs.get("user_response") or ""),
terminal_cause=terminal_cause,
- blocks_run_this_turn=len(ctx.executed_block_labels),
+ blocks_run_this_turn=_blocks_run_this_turn(ctx),
failed_operation=failed_operation,
connect_failure=connect_failure,
proposal_present=result_carries_workflow,
@@ -2465,12 +2484,10 @@ _RAW_SECRET_LEAK_REFUSAL = (
f"credential ID beginning with cred_. {RAW_SECRET_REFUSAL_SENTINEL}."
)
_SAVED_DRAFT_OUTPUT_POLICY_SUFFIX = "I only blocked the chat reply; the workflow draft is still saved."
-_CANCEL_REPLY_DEFAULT = "Cancelled by user."
-_CANCEL_REPLY_UNVALIDATED = (
- "Cancelled. I have a draft workflow you can keep — accept it to save "
- "(note: it hasn't been verified end-to-end), or discard."
-)
-_CANCEL_REPLY_TESTED = "Cancelled. I have a tested draft for you. Accept it to save, or discard."
+_CANCEL_REPLY_DEFAULT = MINIMAL_CANCEL_STOP
+_CANCEL_REPLY_ACCEPT_OR_DISCARD = "Accept it to save, or discard."
+_CANCEL_REPLY_UNVALIDATED = f"{MINIMAL_CANCEL_STOP} {UNTESTED_DRAFT_PRESERVED} {_CANCEL_REPLY_ACCEPT_OR_DISCARD}"
+_CANCEL_REPLY_TESTED = f"{MINIMAL_CANCEL_STOP} {TESTED_DRAFT_PRESERVED} {_CANCEL_REPLY_ACCEPT_OR_DISCARD}"
_UNBACKED_WORKFLOW_DELIVERY_REPLY = (
"I wasn't able to produce a workflow proposal in this turn, and I couldn't identify which details were missing "
"from this turn. Please retry with the target site, page, or workflow requirement."
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index cdc2ba1ad..921989976 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -724,7 +724,7 @@ class AgentResult:
resolved_model: str | None = None
# Set when the agent absorbed an asyncio cancellation initiated by an
# explicit user Stop. Lets the route route to a cancel-specific
- # persistence path (rollback + ``Cancelled by user.`` chat row) without
+ # persistence path (rollback + stop-report chat row) without
# losing ``workflow_was_persisted`` the way a re-raise would.
cancelled: bool = False
# Facts the route needs to persist an interruption record; the route sees the
diff --git a/skyvern/forge/sdk/copilot/terminal_envelope.py b/skyvern/forge/sdk/copilot/terminal_envelope.py
index 3dc390f6f..96453b435 100644
--- a/skyvern/forge/sdk/copilot/terminal_envelope.py
+++ b/skyvern/forge/sdk/copilot/terminal_envelope.py
@@ -8,8 +8,10 @@ from pydantic import BaseModel, model_validator
from skyvern.forge.sdk.copilot.blocker_signal import assert_clean_user_facing_text
from skyvern.forge.sdk.copilot.build_test_connect_failure import BuildTestConnectFailure
from skyvern.forge.sdk.copilot.build_test_outcome import BuildTestFailedOperation
-from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
+from skyvern.forge.sdk.copilot.context import ProposalDisposition
+from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome, RunOutcomeRole
from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt
+from skyvern.forge.sdk.schemas.copilot_turn_outcome import CopilotCancelSource
TerminalNextState = Literal["completed", "proposal_pending", "awaiting_user_input", "stopped"]
TerminalResponseKind = Literal["question", "update", "answer", "stopped"]
@@ -26,6 +28,16 @@ _REVIEW_PROPOSAL_DISPOSITIONS = frozenset({"review_untested", "review_tested"})
_SHADOW_REASON_TRAILING_PUNCTUATION = ".,;:!?"
MINIMAL_HONEST_STOP = "I stopped without confirming the goal was met."
+MINIMAL_CANCEL_STOP = "Stopped."
+_INTERIM_RUN_OUTCOME_ROLE: RunOutcomeRole = "interim_build_test"
+TESTED_DRAFT_PRESERVED = "The tested draft from this turn was preserved for review."
+UNTESTED_DRAFT_PRESERVED = "The untested draft from this turn was preserved for review."
+_NO_DRAFT_PRESERVED = "No workflow draft from this turn was preserved."
+_CANCEL_DRAFT_DISPOSITIONS = (TESTED_DRAFT_PRESERVED, UNTESTED_DRAFT_PRESERVED, _NO_DRAFT_PRESERVED)
+# Only a Stop click is unambiguously the user asking. An Escape may be ambient, so it
+# keeps the plain opening rather than claiming an intent the request cannot establish.
+CANCEL_STOP_AT_USER_REQUEST = "Stopped at your request."
+_CANONICAL_ROLLED_BACK = "The saved workflow was rolled back to its state before this turn."
INTERRUPTED_TERMINAL_REASON = "interrupted"
INTERRUPTED_TERMINAL_HEADLINE = "This turn was interrupted before it could finish."
@@ -56,6 +68,9 @@ class TerminalOutcomeEnvelope(BaseModel):
run_id: str | None = None
run_completed: bool | None = None
blocks_run_this_turn: int | None = None
+ # ``interim_build_test`` marks a run start with no result behind it, which no
+ # surface may read as a resolved outcome.
+ run_outcome_role: RunOutcomeRole | None = None
run_display_reason: str | None = None
run_output_report: str | None = None
blocker_reason: str | None = None
@@ -67,7 +82,12 @@ class TerminalOutcomeEnvelope(BaseModel):
failed_operation: BuildTestFailedOperation | None = None
connect_failure: BuildTestConnectFailure | None = None
proposal_present: bool = False
+ proposal_disposition: ProposalDisposition | None = None
+ canonical_rolled_back: bool = False
interruption: InterruptedTurnFacts | None = None
+ # None when the client named no gesture, so the report stays silent rather
+ # than naming one the request never carried.
+ cancel_source: CopilotCancelSource | None = None
rendered_from_envelope: bool = False
envelope_version: int = 1
@@ -84,7 +104,7 @@ def assemble_terminal_envelope(
response_type: str,
verified: bool,
workflow_applied: bool,
- proposal_disposition: str | None,
+ proposal_disposition: ProposalDisposition | None,
run_outcomes: Sequence[RecordedRunOutcome],
blocker_reason: str | None,
halt_kind: str | None,
@@ -99,6 +119,8 @@ def assemble_terminal_envelope(
interruption: InterruptedTurnFacts | None = None,
) -> TerminalOutcomeEnvelope | None:
run_outcome = select_run_outcome_anchor(run_outcomes)
+ run_outcome_role = run_outcome.role if run_outcome is not None else None
+ run_resolved = run_outcome is not None and not is_interim_run_outcome(run_outcome)
run_verdict = run_outcome.verdict if run_outcome is not None else None
run_id = _clean_text(run_outcome.workflow_run_id) if run_outcome is not None else None
# Lifecycle and identity come from the same archived outcome, which a workflow edit
@@ -121,7 +143,7 @@ def assemble_terminal_envelope(
next_state=next_state,
workflow_mutated=workflow_mutated,
workflow_attempted=workflow_attempted,
- explicit_stop=bool(run_outcome or blocker_reason or halt_kind or terminal_cause),
+ explicit_stop=bool(run_resolved or blocker_reason or halt_kind or terminal_cause),
)
if failed_operation is not None:
if not user_action_required:
@@ -145,6 +167,7 @@ def assemble_terminal_envelope(
run_id=run_id,
run_completed=run_completed,
blocks_run_this_turn=blocks_run_this_turn,
+ run_outcome_role=run_outcome_role,
run_display_reason=run_display_reason,
run_output_report=run_output_report,
blocker_reason=_clean_text(blocker_reason),
@@ -156,6 +179,7 @@ def assemble_terminal_envelope(
failed_operation=failed_operation,
connect_failure=connect_failure,
proposal_present=proposal_present,
+ proposal_disposition=proposal_disposition,
interruption=interruption,
)
@@ -308,12 +332,32 @@ def render_terminal_message(envelope: TerminalOutcomeEnvelope, agent_message: st
return _append_sentence(message, output_report), True
return message, True
+ # A stop reports what the turn recorded regardless of derived state: a cancel that
+ # preserved a draft derives ``proposal_pending`` and never reaches the branch below.
+ if cancelled:
+ # This branch renders twice on a stop that also carries a failed operation or a
+ # connect failure, so every clause is appended only when it is not already there.
+ message = agent_message.strip() or MINIMAL_CANCEL_STOP
+ # Replace only the opening sentence, so a stop that also preserved a draft keeps
+ # the rest of its seed reply instead of losing the upgrade to a longer prefix.
+ if envelope.cancel_source == "stop_button" and message.startswith(MINIMAL_CANCEL_STOP):
+ message = CANCEL_STOP_AT_USER_REQUEST + message[len(MINIMAL_CANCEL_STOP) :]
+ for sentence in _recorded_run_facts(envelope):
+ if not _text_contains(message, sentence):
+ message = _append_sentence(message, sentence)
+ if not any(_text_contains(message, sentence) for sentence in _CANCEL_DRAFT_DISPOSITIONS):
+ message = _append_sentence(message, _cancel_draft_disposition(envelope))
+ if envelope.canonical_rolled_back and not _text_contains(message, _CANONICAL_ROLLED_BACK):
+ message = _append_sentence(message, _CANONICAL_ROLLED_BACK)
+ if envelope.run_display_reason and not _text_contains(message, envelope.run_display_reason):
+ message = _append_labeled_sentence(message, label="Reason", text=envelope.run_display_reason)
+ if output_report and not _text_contains(message, output_report):
+ message = _append_sentence(message, output_report)
+ return message, message != agent_message
+
# A plain reply with no concrete workflow/run/blocker evidence is an answer
# even though next_state remains "stopped"; only stopped-kind turns carry the
# recorded facts.
- if cancelled:
- return agent_message, False
-
if envelope.next_state != "stopped" or envelope.response_kind != "stopped":
if output_report and not _text_contains(agent_message, output_report):
return _append_sentence(agent_message, output_report), True
@@ -346,6 +390,8 @@ def _recorded_run_facts(envelope: TerminalOutcomeEnvelope) -> list[str]:
ran = envelope.blocks_run_this_turn
if ran is not None:
facts.append(f"{ran} block{'' if ran == 1 else 's'} ran this turn.")
+ elif envelope.run_id is not None:
+ facts.append("A run was started, and how many of its blocks ran was not confirmed.")
# The completion clause rides on the recorded lifecycle fact, never on the
# verdict: an unevaluated outcome says nothing about whether the run finished.
lifecycle = "The recorded run completed, and its" if envelope.run_completed else "The recorded run's"
@@ -356,25 +402,60 @@ def _recorded_run_facts(envelope: TerminalOutcomeEnvelope) -> list[str]:
return facts
+def _cancel_draft_disposition(envelope: TerminalOutcomeEnvelope) -> str:
+ """Reads the disposition the seed reply was chosen from, so the two cannot disagree."""
+ if not envelope.proposal_present:
+ return _NO_DRAFT_PRESERVED
+ if envelope.proposal_disposition == "review_tested":
+ return TESTED_DRAFT_PRESERVED
+ return UNTESTED_DRAFT_PRESERVED
+
+
+def is_interim_run_outcome(outcome: RecordedRunOutcome | None) -> bool:
+ """A run start with no result behind it, which no surface may read as a resolved outcome."""
+ return outcome is not None and outcome.role == _INTERIM_RUN_OUTCOME_ROLE
+
+
+def interim_run_start_outcome(workflow_run_id: str) -> RecordedRunOutcome:
+ """The run-start record a mid-run stop reads: a run exists, its lifecycle and blocks are unresolved."""
+ return RecordedRunOutcome(
+ verdict="not_evaluated",
+ workflow_run_id=workflow_run_id,
+ run_completed=None,
+ role=_INTERIM_RUN_OUTCOME_ROLE,
+ )
+
+
def select_run_outcome_anchor(run_outcomes: Sequence[RecordedRunOutcome]) -> RecordedRunOutcome | None:
- final_outcomes = [outcome for outcome in run_outcomes if outcome.verdict in _FINAL_RUN_VERDICTS]
+ # The terminal describes the last run the turn touched, and a result supersedes that run's
+ # own start whatever its verdict — including the ``demonstrated`` one no anchor reports.
+ resolved_run_ids = {
+ outcome.workflow_run_id
+ for outcome in run_outcomes
+ if outcome.workflow_run_id is not None and not is_interim_run_outcome(outcome)
+ }
+ live_outcomes = [
+ outcome
+ for outcome in run_outcomes
+ if not (is_interim_run_outcome(outcome) and outcome.workflow_run_id in resolved_run_ids)
+ ]
+ final_outcomes = [outcome for outcome in live_outcomes if outcome.verdict in _FINAL_RUN_VERDICTS]
if not final_outcomes:
return None
- # The terminal reports the run record in order. An interim event is not a terminal
- # run when a recorded run exists; otherwise the latest interim event is the only
- # run fact available.
- recorded = [outcome for outcome in final_outcomes if outcome.role != "interim_build_test"]
- if recorded:
- return recorded[-1]
return final_outcomes[-1]
+def run_start_unresolved(run_outcomes: Sequence[RecordedRunOutcome]) -> bool:
+ """True when the outcome the terminal anchors on is a run start with no result behind it."""
+ return is_interim_run_outcome(select_run_outcome_anchor(run_outcomes))
+
+
def _derive_next_state(
*,
user_action_required: bool,
verified: bool,
workflow_applied: bool,
- proposal_disposition: str | None,
+ proposal_disposition: ProposalDisposition | None,
) -> TerminalNextState:
if user_action_required:
return "awaiting_user_input"
@@ -422,10 +503,8 @@ def reason_in_reply_shadow(run_display_reason: str | None, final_message: str) -
return bool(normalized_reason and normalized_reply and normalized_reason in normalized_reply)
-def _proposal_requires_review(proposal_disposition: str | None) -> bool:
- if not isinstance(proposal_disposition, str):
- return False
- return proposal_disposition.strip().lower() in _REVIEW_PROPOSAL_DISPOSITIONS
+def _proposal_requires_review(proposal_disposition: ProposalDisposition | None) -> bool:
+ return proposal_disposition in _REVIEW_PROPOSAL_DISPOSITIONS
def _clean_text(value: str | None) -> str | None:
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 82f3331b3..4957d0e3d 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -155,6 +155,7 @@ from skyvern.forge.sdk.copilot.secret_scrub import (
register_secret_scrub_values_from_structure,
scrub_secrets_from_structure,
)
+from skyvern.forge.sdk.copilot.terminal_envelope import interim_run_start_outcome, is_interim_run_outcome
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
from skyvern.forge.sdk.copilot.turn_halt import stash_turn_halt_from_blocker_signal
from skyvern.forge.sdk.copilot.workflow_yaml import _process_workflow_yaml, runner_code_block_associations
@@ -661,6 +662,16 @@ def _forget_browser_position(ctx: CopilotContext) -> None:
ctx.verified_prefix_terminal_label = None
+def _forget_interim_run_start(ctx: CopilotContext, workflow_run_id: str) -> None:
+ """Drop the run-start record when submission unwound, so no terminal reports a run that never ran."""
+ outcomes = ctx.terminal_envelope_run_outcomes
+ outcomes[:] = [
+ outcome
+ for outcome in outcomes
+ if not (is_interim_run_outcome(outcome) and outcome.workflow_run_id == workflow_run_id)
+ ]
+
+
def _block_end_urls_by_label(run_block_rows: list[WorkflowRunBlock]) -> dict[str, str]:
"""Page each labelled block ended on, chronologically, from worker-persisted run rows."""
end_urls: dict[str, str] = {}
@@ -2927,6 +2938,10 @@ async def _run_blocks_and_collect_debug(
run_task: asyncio.Task | None = None
sensitive_run_custody_lock: asyncio.Lock | None = None
sensitive_run_session_id: str | None = None
+ interim_run_id: str | None = None
+ # Set only where the run may already be executing, so an unwind before either executor call
+ # can still retract the run-start record.
+ run_submission_attempted = False
try:
workflow_run = await workflow_service.prepare_workflow(
workflow_id=ctx.workflow_permanent_id,
@@ -2969,6 +2984,10 @@ async def _run_blocks_and_collect_debug(
# cancellation exits leave by paths a success-only reset never reaches.
_forget_browser_position(ctx)
+ # A run that never returns a result must not read as zero blocks at the terminal;
+ # the tool-return record supersedes this one.
+ interim_run_id = workflow_run.workflow_run_id
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome(interim_run_id))
await _send_run_started_update(ctx, workflow_run.workflow_run_id)
if dispatch_to_worker:
@@ -2976,6 +2995,7 @@ async def _run_blocks_and_collect_debug(
# snapshot version, so the worker resolves the exact wrapped definition via
# run.workflow_id — no workflow_override crosses the wire. block_labels/block_outputs
# and the shared browser session reproduce the frontier re-run on the worker.
+ run_submission_attempted = True
await AsyncExecutorFactory.get_executor().execute_workflow(
request=None,
background_tasks=None,
@@ -3014,6 +3034,7 @@ async def _run_blocks_and_collect_debug(
frontier_start_label=frontier_start_label,
)
if inline_fence_failure is not None:
+ _forget_interim_run_start(ctx, workflow_run.workflow_run_id)
await app.WORKFLOW_SERVICE.mark_workflow_run_as_failed_if_not_final(
workflow_run_id=workflow_run.workflow_run_id,
failure_reason=inline_fence_failure["error"],
@@ -3025,6 +3046,7 @@ async def _run_blocks_and_collect_debug(
organization_id=ctx.organization_id,
)
+ run_submission_attempted = True
run_task = asyncio.create_task(
app.WORKFLOW_SERVICE.execute_workflow(
workflow_run_id=workflow_run.workflow_run_id,
@@ -3053,6 +3075,8 @@ async def _run_blocks_and_collect_debug(
if sensitive_run_session_id is not None:
release_sensitive_origin_run_lease(ctx, workflow_run_id=workflow_run.workflow_run_id)
sensitive_run_custody_lock.release()
+ if interim_run_id is not None and not run_submission_attempted:
+ _forget_interim_run_start(ctx, interim_run_id)
raise
active_run_association: ActiveRunSessionAssociation | None = None
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.py
index 59082d8d8..72f62fcda 100644
--- a/skyvern/forge/sdk/routes/workflow_copilot.py
+++ b/skyvern/forge/sdk/routes/workflow_copilot.py
@@ -9,7 +9,7 @@ from copy import deepcopy
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Any, Iterator
+from typing import Any, Iterator, cast, get_args
from urllib.parse import urlparse
import structlog
@@ -57,6 +57,7 @@ from skyvern.forge.sdk.copilot.review_gate import parse_execution_receipts, seri
from skyvern.forge.sdk.copilot.runtime import close_browser_session_quietly
from skyvern.forge.sdk.copilot.terminal_envelope import (
INTERRUPTED_TERMINAL_REASON,
+ MINIMAL_CANCEL_STOP,
InterruptedTurnFacts,
TerminalOutcomeEnvelope,
finalize_applied_state,
@@ -81,6 +82,7 @@ from skyvern.forge.sdk.routes.routers import base_router
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcome
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.workflow_copilot import (
+ CopilotCancelSource,
CopilotFailureKind,
CopilotPendingTurn,
WorkflowCopilotApplyProposedWorkflowRequest,
@@ -362,18 +364,31 @@ def _copilot_idempotency_digest(
return hmac.new(settings.SECRET_KEY.encode(), scoped_value, hashlib.sha256).hexdigest()
+def _coerce_cancel_source(flag: str | bytes | None) -> CopilotCancelSource | None:
+ """Read the cancel source out of the flag value the cancel route wrote.
+
+ Rows written before the source existed hold ``"1"``, which names no gesture.
+ """
+ if isinstance(flag, bytes):
+ flag = flag.decode(errors="replace")
+ if flag in get_args(CopilotCancelSource):
+ return cast(CopilotCancelSource, flag)
+ return None
+
+
async def _watch_for_cancel(
cache: Any,
organization_id: str,
cancel_token: str,
handler_task: asyncio.Task,
observed: list[bool],
+ observed_source: list[CopilotCancelSource | None] | None = None,
) -> None:
"""Cancel ``handler_task`` when the matching Redis flag flips truthy.
Sets ``observed[0] = True`` before issuing the cancel so the handler's
``except CancelledError`` block can tell a user cancel apart from
- server shutdown — only the user path writes a ``Cancelled by user.`` row.
+ server shutdown — only the user path writes a stop-report row.
"""
key = _copilot_cancel_key(organization_id, cancel_token)
while not handler_task.done():
@@ -384,12 +399,16 @@ async def _watch_for_cancel(
LOG.debug("Copilot cancel-watcher get failed; will retry", exc_info=True)
continue
if flag:
+ source = _coerce_cancel_source(flag)
LOG.info(
"Copilot cancel signal observed; cancelling handler task",
cancel_token=cancel_token,
organization_id=organization_id,
+ cancel_source=source,
)
observed[0] = True
+ if observed_source is not None:
+ observed_source[0] = source
handler_task.cancel()
return
@@ -601,6 +620,29 @@ def _with_rendered_terminal_text(
return payload
+def _log_terminal_render_decision(
+ envelope: TerminalOutcomeEnvelope,
+ *,
+ flag_enabled: bool,
+ replaced: bool,
+ cancelled: bool,
+ product_action: str | None,
+) -> None:
+ # The envelope's own log fields are stamped pre-render, so this is the only
+ # signal that witnesses the render decision in prod.
+ LOG.info(
+ "copilot_terminal_render_decision",
+ flag_enabled=flag_enabled,
+ product_action=product_action,
+ cancelled=cancelled,
+ replaced=replaced,
+ run_verdict=envelope.run_verdict,
+ next_state=envelope.next_state,
+ response_kind=envelope.response_kind,
+ reason_present=bool(envelope.run_display_reason),
+ )
+
+
def _build_recoverable_route_agent_result(
error: BaseException,
*,
@@ -935,6 +977,7 @@ async def _persist_cancel_turn(
prior_global_llm_context: str | None = None,
user_row_already_persisted: bool = False,
record_as_interrupted: bool = False,
+ cancel_source: CopilotCancelSource | None = None,
) -> None:
"""Persist a cancelled turn and emit a terminal SSE response frame.
@@ -947,10 +990,12 @@ async def _persist_cancel_turn(
turn as interrupted, for a cancellation no user asked for.
"""
turn_outcome: TurnOutcome | None
+ narrative_summary: str | None
+ narrative_payload: TurnNarrativePayload | None
workflow_applied = False
canonical_rolled_back = False
if agent_result is None:
- user_response = "Cancelled by user."
+ user_response = MINIMAL_CANCEL_STOP
updated_workflow = None
updated_global_llm_context = prior_global_llm_context
total_tokens = None
@@ -962,11 +1007,33 @@ async def _persist_cancel_turn(
reason_code=USER_CANCELLED_TERMINAL_REASON,
terminal_reason=USER_CANCELLED_TERMINAL_REASON,
copilot_turn_id=turn_id,
+ cancel_source=cancel_source,
)
response_turn_id = turn_id
- narrative_summary = None
- narrative_payload = None
- terminal_envelope = None
+ # Nothing was dispatched before the agent started, so zero is a recorded fact here
+ # rather than the absent count the mid-run path reports, and no draft is this turn's.
+ terminal_envelope_model = TerminalOutcomeEnvelope(
+ next_state="stopped",
+ verified=False,
+ response_kind="stopped",
+ blocks_run_this_turn=0,
+ cancel_source=cancel_source,
+ )
+ should_render_terminal_from_envelope = await asyncio.shield(
+ app.AGENT_FUNCTION.should_render_copilot_terminal_from_envelope(organization_id)
+ )
+ terminal_envelope_model = terminal_envelope_model.model_copy(update={"rendered_from_envelope": True})
+ user_response, replaced = render_terminal_message(terminal_envelope_model, user_response, cancelled=True)
+ terminal_envelope = terminal_envelope_model.model_dump(mode="json")
+ _log_terminal_render_decision(
+ terminal_envelope_model,
+ flag_enabled=should_render_terminal_from_envelope,
+ replaced=replaced,
+ cancelled=True,
+ product_action=None,
+ )
+ narrative_summary = user_response
+ narrative_payload = _make_error_narrative_payload(turn_id, None, user_response)
if chat.proposed_workflow is not None and not keep_pending_proposal:
await asyncio.shield(_clear_proposed_workflow(chat))
else:
@@ -1008,6 +1075,8 @@ async def _persist_cancel_turn(
resolved_model = agent_result.resolved_model
output_policy_diagnostics = agent_result.output_policy_diagnostics
turn_outcome = agent_result.turn_outcome
+ if turn_outcome is not None and cancel_source is not None:
+ turn_outcome = turn_outcome.model_copy(update={"cancel_source": cancel_source})
response_turn_id = turn_id or agent_result.turn_id
narrative_summary = agent_result.narrative_summary
narrative_payload = agent_result.narrative_payload
@@ -1022,14 +1091,27 @@ async def _persist_cancel_turn(
terminal_envelope = None
else:
terminal_envelope_model, terminal_envelope = terminal_envelope_result
- # Cancelled turns keep the agent text (render_terminal_message
- # passes them through), so only the flag marker is stamped here.
+ terminal_envelope_model = terminal_envelope_model.model_copy(
+ update={"canonical_rolled_back": canonical_rolled_back, "cancel_source": cancel_source}
+ )
# Shielded like the persistence writes above: a cancel landing on
# this await must not skip the chat-row persistence that follows.
- if await asyncio.shield(app.AGENT_FUNCTION.should_render_copilot_terminal_from_envelope(organization_id)):
- terminal_envelope = terminal_envelope_model.model_copy(
- update={"rendered_from_envelope": True}
- ).model_dump(mode="json")
+ should_render_terminal_from_envelope = await asyncio.shield(
+ app.AGENT_FUNCTION.should_render_copilot_terminal_from_envelope(organization_id)
+ )
+ terminal_envelope_model = terminal_envelope_model.model_copy(update={"rendered_from_envelope": True})
+ user_response, replaced = render_terminal_message(terminal_envelope_model, user_response, cancelled=True)
+ terminal_envelope = terminal_envelope_model.model_dump(mode="json")
+ if replaced:
+ narrative_payload = _with_rendered_terminal_text(narrative_payload, rendered_message=user_response)
+ narrative_summary = user_response
+ _log_terminal_render_decision(
+ terminal_envelope_model,
+ flag_enabled=should_render_terminal_from_envelope,
+ replaced=replaced,
+ cancelled=True,
+ product_action=None,
+ )
if record_as_interrupted:
facts = _interruption_facts(
@@ -1045,8 +1127,11 @@ async def _persist_cancel_turn(
prior_turn_outcome=turn_outcome,
)
terminal_envelope = interrupted_terminal_envelope(facts).model_dump(mode="json")
+ # Hydration prefers narrativeSummary, so a cancel-rendered summary left in place
+ # would outlive the reply it was rendered for.
+ narrative_summary = user_response
narrative_payload = (
- {**narrative_payload, "terminalMessage": user_response}
+ {**narrative_payload, "terminalMessage": user_response, "narrativeSummary": user_response}
if narrative_payload is not None
else _make_error_narrative_payload(turn_id or response_turn_id, None, user_response)
)
@@ -1197,8 +1282,8 @@ async def _finalise_normal_turn(
)
replaced = False
if should_render_terminal_from_envelope and chat_request.product_action != "test_end_to_end":
- # rendered_from_envelope means "flag on, envelope is display
- # authority" for the FE — not that this turn's text was replaced.
+ # rendered_from_envelope means the envelope is display authority for the FE, not
+ # that this turn's text was replaced.
terminal_envelope_model = terminal_envelope_model.model_copy(update={"rendered_from_envelope": True})
user_response, replaced = render_terminal_message(
terminal_envelope_model,
@@ -1214,17 +1299,12 @@ async def _finalise_normal_turn(
# The frame-level summary is preferred by the FE over the
# message on hydration, so it must carry the rendered text too.
narrative_summary = user_response
- # The envelope's own log fields are stamped pre-render, so this is the
- # only signal that witnesses the render decision in prod.
- LOG.info(
- "copilot_terminal_render_decision",
+ _log_terminal_render_decision(
+ terminal_envelope_model,
flag_enabled=should_render_terminal_from_envelope,
- product_action=chat_request.product_action,
replaced=replaced,
- run_verdict=terminal_envelope_model.run_verdict,
- next_state=terminal_envelope_model.next_state,
- response_kind=terminal_envelope_model.response_kind,
- reason_present=bool(terminal_envelope_model.run_display_reason),
+ cancelled=False,
+ product_action=chat_request.product_action,
)
narrative_payload = _with_terminal_narrative_metadata(
narrative_payload,
@@ -2014,8 +2094,11 @@ async def _new_copilot_chat_post(
# The watcher sets [0] = True before issuing handler_task.cancel() so the
# except CancelledError block can distinguish a user-driven cancel from
# operational cancels (server shutdown / deploy drain) and only persist
- # a "Cancelled by user." chat row in the user case.
+ # a stop-report chat row in the user case.
user_cancel_observed: list[bool] = [False]
+ # Which gesture asked for it, when the client said; None for a legacy
+ # client or a cancel that named no source.
+ user_cancel_source: list[CopilotCancelSource | None] = [None]
try:
await stream.send(
@@ -2179,6 +2262,7 @@ async def _new_copilot_chat_post(
chat_request.cancel_token,
handler_task,
user_cancel_observed,
+ user_cancel_source,
)
)
@@ -2295,6 +2379,7 @@ async def _new_copilot_chat_post(
keep_pending_proposal=chat_request.keep_pending_proposal,
user_row_already_persisted=turn_started,
record_as_interrupted=not user_cancel_observed[0],
+ cancel_source=user_cancel_source[0],
)
terminal_frame_emitted = True
capture_code_mode_opt_out_after_persist()
@@ -2302,6 +2387,7 @@ async def _new_copilot_chat_post(
"Workflow copilot v2 turn cancelled",
workflow_copilot_chat_id=chat_request.workflow_copilot_chat_id,
user_cancel_observed=user_cancel_observed[0],
+ cancel_source=user_cancel_source[0],
)
return
@@ -2379,17 +2465,19 @@ async def _new_copilot_chat_post(
keep_pending_proposal=chat_request.keep_pending_proposal,
prior_global_llm_context=global_llm_context,
user_row_already_persisted=turn_started,
+ cancel_source=user_cancel_source[0],
)
)
terminal_frame_emitted = True
LOG.info(
"Workflow copilot v2 cancelled by user during pre-agent setup",
workflow_copilot_chat_id=chat_request.workflow_copilot_chat_id,
+ cancel_source=user_cancel_source[0],
)
return
else:
# Operational cancel (worker shutdown, deploy drain). Don't manufacture
- # a "Cancelled by user." chat row — chat history should not record an
+ # a stop-report chat row — chat history should not record an
# operational cancel as user intent. When finalisation already started,
# its shielded write owns this turn's row and wins; if it dies before
# committing, the pending turn is left for reconcile-on-read to recover.
@@ -3052,7 +3140,8 @@ async def workflow_copilot_cancel(
)
await cache.set(
_copilot_cancel_key(organization.organization_id, cancel_request.cancel_token),
- "1",
+ # A client too old to name its gesture still has to set a truthy flag.
+ cancel_request.source or "1",
ex=COPILOT_CANCEL_TTL,
)
diff --git a/skyvern/forge/sdk/schemas/copilot_turn_outcome.py b/skyvern/forge/sdk/schemas/copilot_turn_outcome.py
index 69ca35bef..6964b248b 100644
--- a/skyvern/forge/sdk/schemas/copilot_turn_outcome.py
+++ b/skyvern/forge/sdk/schemas/copilot_turn_outcome.py
@@ -72,6 +72,9 @@ class ConnectedAccountChoiceReference(BaseModel):
connection_id: str
+CopilotCancelSource = Literal["escape_key", "stop_button", "api"]
+
+
class TurnOutcome(BaseModel):
# extra="ignore" so a rolling deploy that adds a new TurnOutcome field
# does not make older readers silently treat freshly-written rows as None.
@@ -84,6 +87,9 @@ class TurnOutcome(BaseModel):
normalized_reply_signature: str = ""
tool_calls: list[str] = Field(default_factory=list)
terminal_reason: str | None = None
+ # Sits beside terminal_reason so cancel volume groups by gesture in the same
+ # query that finds the cancels. None when the request named no source.
+ cancel_source: CopilotCancelSource | None = None
blocked_signatures: list[str] = Field(default_factory=list)
copilot_effective_mode: Literal["ask", "build", "code"] | None = None
copilot_code_available: bool = False
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index 0d35effca..2f84013ad 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -8,7 +8,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator
from skyvern.forge.sdk.copilot.code_write_diff import CodeWriteDiff
from skyvern.forge.sdk.copilot.context import ProposalDisposition, ResponseType, TurnNarrativePayload
from skyvern.forge.sdk.copilot.run_outcome import RunOutcomeReasonCode, RunOutcomeRole, RunOutcomeVerdict
-from skyvern.forge.sdk.schemas.copilot_turn_outcome import TurnOutcome
+from skyvern.forge.sdk.schemas.copilot_turn_outcome import CopilotCancelSource, TurnOutcome
class CopilotPendingTurn(BaseModel):
@@ -192,6 +192,14 @@ class WorkflowCopilotChatRequest(BaseModel):
class WorkflowCopilotCancelRequest(BaseModel):
cancel_token: str = Field(..., description="The cancel_token sent on the original /chat-post request")
+ source: CopilotCancelSource | None = Field(
+ default=None,
+ description=(
+ "Which gesture asked for the cancel, so cancel volume is attributable by source. "
+ "Absent from a client too old to send it, which is recorded as unattributed rather "
+ "than as an API caller."
+ ),
+ )
class WorkflowCopilotCredentialResponseRequest(BaseModel):
diff --git a/tests/unit/test_copilot_agent_blocker_renderer.py b/tests/unit/test_copilot_agent_blocker_renderer.py
index b8885bede..8daad2721 100644
--- a/tests/unit/test_copilot_agent_blocker_renderer.py
+++ b/tests/unit/test_copilot_agent_blocker_renderer.py
@@ -33,6 +33,7 @@ from skyvern.forge.sdk.copilot.output_policy import (
from skyvern.forge.sdk.copilot.request_policy import LivePageResolutionRecord, RequestPolicy
from skyvern.forge.sdk.copilot.review_gate import workflow_block_fingerprints
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
+from skyvern.forge.sdk.copilot.terminal_envelope import MINIMAL_CANCEL_STOP
from skyvern.forge.sdk.copilot.turn_halt import TurnHalt, TurnHaltKind
from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ConnectedAccountChoice, ResponseKind, TurnOutcome
@@ -635,7 +636,7 @@ def test_shim_over_a_cancelled_turn_keeps_the_stop_label() -> None:
ctx = _ctx()
ctx.blocker_signal = _signal()
result = AgentResult(
- user_response="Cancelled by user.",
+ user_response=MINIMAL_CANCEL_STOP,
updated_workflow=None,
global_llm_context=None,
cancelled=True,
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 2658d2e34..3e38e1913 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -85,6 +85,7 @@ from skyvern.forge.sdk.copilot.request_policy import (
from skyvern.forge.sdk.copilot.request_slots import PROMPT_NAME as REQUEST_SLOTS_PROMPT_NAME
from skyvern.forge.sdk.copilot.review_gate import workflow_block_fingerprints
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
+from skyvern.forge.sdk.copilot.terminal_envelope import interim_run_start_outcome
from skyvern.forge.sdk.copilot.tools import _run_blocks_and_collect_debug
from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
from skyvern.forge.sdk.copilot.tools.completion import (
@@ -6525,6 +6526,24 @@ workflow_definition:
assert rendered["facts"]["evaluationState"] == "not_demonstrated"
assert rendered["disposition"] == "review_untested"
+ def test_an_unresolved_run_start_over_full_coverage_drops_the_tested_pill(self) -> None:
+ staged = self._two_block_yaml()
+ ctx = _ctx(persisted_workflow_yaml=staged)
+ ctx.executed_block_fingerprints = {
+ label: set(fingerprints) for label, fingerprints in workflow_block_fingerprints(staged).items()
+ }
+ ctx.executed_block_labels = {"sign_in", "read_metric"}
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_unresolved"))
+
+ rendered = self._render(ctx, staged)
+
+ assert rendered["facts"]["matchingSourceBlockCount"] == 2
+ assert rendered["facts"]["blocksRunThisTurn"] is None
+ assert rendered["facts"]["runCompleted"] is None
+ assert rendered["facts"]["evaluationState"] is None
+ assert rendered["facts"]["ranCleanOnCurrentSource"] is False
+ assert rendered["disposition"] == "review_untested"
+
def test_an_edited_block_is_no_longer_counted_against_its_stale_receipt(self) -> None:
tested = self._two_block_yaml()
staged = self._two_block_yaml("Read it twice")
@@ -6672,7 +6691,7 @@ workflow_definition:
terminal_reason="max_turns",
)
- assert "tested draft" not in result.user_response
+ assert result.user_response != tested_reply
assert result.user_response == unvalidated_reply
assert result.proposal_disposition == "review_untested"
diff --git a/tests/unit/test_copilot_terminal_envelope.py b/tests/unit/test_copilot_terminal_envelope.py
index 31482123c..48d46101c 100644
--- a/tests/unit/test_copilot_terminal_envelope.py
+++ b/tests/unit/test_copilot_terminal_envelope.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+import asyncio
import time
+from dataclasses import replace
from datetime import UTC, datetime
from types import SimpleNamespace
from typing import Any
@@ -11,6 +13,7 @@ import structlog.testing
from skyvern.exceptions import get_user_facing_exception_message
from skyvern.forge.sdk.copilot import agent as agent_module
+from skyvern.forge.sdk.copilot.agent import _CANCEL_REPLY_UNVALIDATED
from skyvern.forge.sdk.copilot.blocker_signal import (
CopilotToolBlockerSignal,
)
@@ -21,27 +24,41 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (
RecordedBuildTestOutcome,
)
from skyvern.forge.sdk.copilot.config import CopilotConfig
+from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
from skyvern.forge.sdk.copilot.secret_scrub import clear_session_scrub_values, register_secret_scrub_value
from skyvern.forge.sdk.copilot.terminal_envelope import (
+ CANCEL_STOP_AT_USER_REQUEST,
INTERRUPTED_TERMINAL_HEADLINE,
+ MINIMAL_CANCEL_STOP,
MINIMAL_HONEST_STOP,
+ UNTESTED_DRAFT_PRESERVED,
InterruptedTurnFacts,
TerminalOutcomeEnvelope,
assemble_terminal_envelope,
finalize_applied_state,
+ interim_run_start_outcome,
+ is_interim_run_outcome,
reason_in_reply_shadow,
render_terminal_message,
+ run_start_unresolved,
+ select_run_outcome_anchor,
)
from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
from skyvern.forge.sdk.copilot.tools.run_execution import (
+ _commit_run_blocks_record,
+ _forget_interim_run_start,
_record_run_blocks_result,
_stamp_run_side_connect_failure,
_stash_recorded_run_outcome,
)
from skyvern.forge.sdk.copilot.tools.workflow_update import _record_workflow_update_result
from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession
-from tests.unit.copilot_test_helpers import make_copilot_ctx
+from tests.unit.copilot_test_helpers import (
+ HANDBACK_WORKFLOW_YAML,
+ install_run_blocks_harness,
+ make_copilot_ctx,
+)
RUN_SIDE_SHARED_REASON = get_user_facing_exception_message(
Exception("connect_over_cdp failed: WebSocket error: connection closed")
@@ -560,48 +577,52 @@ def test_anchor_uses_the_latest_final_run_fact() -> None:
assert envelope.run_display_reason == "A later run completed."
-def _interim_outcome(verdict: str, display_reason: str | None = None) -> RecordedRunOutcome:
- return RecordedRunOutcome(verdict=verdict, display_reason=display_reason, role="interim_build_test")
+def test_a_run_start_is_recognised_as_interim_by_its_role_alone() -> None:
+ # The role is the whole marker, so a surface cannot be fooled into reading a run start
+ # as resolved by any lifecycle or verdict value carried alongside it.
+ start = interim_run_start_outcome("wr_1")
+ assert start.run_completed is None
+ assert is_interim_run_outcome(start)
+ assert is_interim_run_outcome(replace(start, run_completed=False, verdict="not_demonstrated"))
+ assert not is_interim_run_outcome(RecordedRunOutcome(verdict="not_evaluated", workflow_run_id="wr_1"))
-def test_run_anchor_ignores_interim_not_demonstrated_when_recorded_run_follows() -> None:
- envelope = _assemble(
- run_outcomes=[
- _interim_outcome("not_demonstrated", "The scout has not produced the goal yet."),
- _run_outcome("not_evaluated", "The later run completed."),
- ]
- )
-
- assert envelope.run_verdict == "not_evaluated"
- assert envelope.run_display_reason == "The later run completed."
-
-def test_run_anchor_keeps_interim_amber_when_no_adjudicated_outcome() -> None:
- # Repair ceiling: the loop stops after a suspicious-success run without ever
- # producing an adjudicated outcome, so the interim not_demonstrated is the turn's
- # honest terminal verdict and must still anchor amber.
+def test_a_result_for_the_same_run_supersedes_that_runs_own_start() -> None:
envelope = _assemble(
run_outcomes=[
- _interim_outcome("not_demonstrated", "The run completed but did not demonstrate the goal."),
+ interim_run_start_outcome("wr_1"),
+ RecordedRunOutcome(
+ verdict="not_demonstrated",
+ workflow_run_id="wr_1",
+ display_reason="The extraction returned no value.",
+ run_completed=True,
+ ),
]
)
+ assert envelope.run_outcome_role == "recorded"
assert envelope.run_verdict == "not_demonstrated"
- assert envelope.run_display_reason == "The run completed but did not demonstrate the goal."
+ assert envelope.run_display_reason == "The extraction returned no value."
+ assert envelope.run_completed is True
-def test_run_anchor_prefers_adjudicated_not_demonstrated_over_earlier_interim() -> None:
- # A genuine adjudicated failure on the completed workflow anchors amber even when an
- # earlier interim run also went not_demonstrated.
- envelope = _assemble(
- run_outcomes=[
- _interim_outcome("not_demonstrated", "Interim scout, still building."),
- _run_outcome("not_demonstrated", "The extraction returned no value."),
- ]
- )
+def test_an_unresolved_run_start_leaves_every_lifecycle_facet_unknown() -> None:
+ envelope = _assemble(run_outcomes=[interim_run_start_outcome("wr_1")], blocks_run_this_turn=None)
- assert envelope.run_verdict == "not_demonstrated"
- assert envelope.run_display_reason == "The extraction returned no value."
+ assert envelope.run_outcome_role == "interim_build_test"
+ assert envelope.run_id == "wr_1"
+ assert envelope.run_completed is None
+ assert envelope.blocks_run_this_turn is None
+ assert envelope.run_display_reason is None
+ assert envelope.run_output_report is None
+ assert envelope.run_verdict == "not_evaluated"
+
+ message, _ = render_terminal_message(envelope, MINIMAL_CANCEL_STOP, cancelled=True)
+
+ assert "A run was started, and how many of its blocks ran was not confirmed." in message
+ assert "The recorded run's outcome was not evaluated." in message
+ assert "completed" not in message
@pytest.mark.parametrize(
@@ -610,7 +631,7 @@ def test_run_anchor_prefers_adjudicated_not_demonstrated_over_earlier_interim()
("ASK_QUESTION", False, False, "no_proposal", "awaiting_user_input"),
("REPLY", True, True, "no_proposal", "completed"),
("REPLY", False, False, "review_tested", "proposal_pending"),
- ("REPLY", False, False, "review_required", "stopped"),
+ ("REPLY", False, False, "review_untested", "proposal_pending"),
("REPLY", True, False, "auto_applicable", "stopped"),
],
)
@@ -1029,27 +1050,177 @@ def test_render_terminal_message_omits_unsafe_recorded_output_report() -> None:
assert replaced is False
- ("next_state", "cancelled"),
- [
- ("completed", False),
- ("proposal_pending", False),
- ("awaiting_user_input", False),
- ("stopped", True),
- ],
-)
-def test_render_terminal_message_passthrough_for_non_stopped_or_cancelled(next_state: str, cancelled: bool) -> None:
[email protected]("next_state", ["completed", "proposal_pending", "awaiting_user_input"])
+def test_render_terminal_message_passthrough_for_non_stopped(next_state: str) -> None:
envelope = TerminalOutcomeEnvelope(
next_state=next_state, verified=False, run_verdict="not_demonstrated", response_kind="stopped"
)
message = "keep-agent-message"
- rendered, replaced = render_terminal_message(envelope, message, cancelled=cancelled)
+ rendered, replaced = render_terminal_message(envelope, message, cancelled=False)
assert rendered == message
assert replaced is False
[email protected]("next_state", ["stopped", "proposal_pending"])
+def test_render_terminal_message_cancelled_reports_recorded_facts_in_any_state(next_state: str) -> None:
+ envelope = TerminalOutcomeEnvelope(
+ next_state=next_state,
+ verified=False,
+ run_verdict="not_demonstrated",
+ response_kind="stopped",
+ blocks_run_this_turn=2,
+ proposal_present=next_state == "proposal_pending",
+ )
+
+ rendered, replaced = render_terminal_message(envelope, "keep-agent-message", cancelled=True)
+
+ assert rendered.startswith("keep-agent-message")
+ assert "2 blocks ran this turn." in rendered
+ assert "outcome did not confirm the goal was met." in rendered
+ assert replaced is True
+
+
+def test_render_terminal_message_cancelled_mid_run_reports_unknown_never_zero() -> None:
+ envelope = TerminalOutcomeEnvelope(
+ next_state="stopped",
+ verified=False,
+ response_kind="stopped",
+ blocks_run_this_turn=None,
+ run_id="wr_1",
+ run_verdict="not_evaluated",
+ )
+
+ rendered, _ = render_terminal_message(envelope, MINIMAL_CANCEL_STOP, cancelled=True)
+
+ assert "A run was started, and how many of its blocks ran was not confirmed." in rendered
+ assert "0 blocks ran" not in rendered
+
+
+def test_render_terminal_message_cancelled_names_a_tested_draft_from_the_seed_disposition() -> None:
+ envelope = TerminalOutcomeEnvelope(
+ next_state="proposal_pending",
+ verified=False,
+ response_kind="update",
+ blocks_run_this_turn=0,
+ proposal_present=True,
+ proposal_disposition="review_tested",
+ )
+ seed = "Stopped. The tested draft from this turn was preserved for review."
+
+ rendered, _ = render_terminal_message(envelope, seed, cancelled=True)
+
+ assert rendered.count("The tested draft from this turn was preserved for review.") == 1
+ assert "untested draft" not in rendered
+
+
+def test_render_terminal_message_cancelled_never_ships_two_draft_dispositions() -> None:
+ # The seed reply and the envelope disagree; one bubble still carries one disposition.
+ envelope = TerminalOutcomeEnvelope(
+ next_state="proposal_pending",
+ verified=True,
+ response_kind="update",
+ blocks_run_this_turn=0,
+ proposal_present=True,
+ proposal_disposition="review_untested",
+ )
+ seed = "Stopped. The tested draft from this turn was preserved for review."
+
+ rendered, _ = render_terminal_message(envelope, seed, cancelled=True)
+
+ assert rendered.count("draft from this turn was preserved for review.") == 1
+
+
+def test_render_terminal_message_cancelled_is_stable_across_a_second_render() -> None:
+ envelope = TerminalOutcomeEnvelope(
+ next_state="stopped",
+ verified=False,
+ response_kind="stopped",
+ run_verdict="not_demonstrated",
+ run_display_reason="The sign-in never reached the dashboard.",
+ blocks_run_this_turn=2,
+ proposal_present=True,
+ proposal_disposition="review_untested",
+ canonical_rolled_back=True,
+ failed_operation=BuildTestFailedOperation(kind="browser_operation_failed"),
+ )
+
+ first, _ = render_terminal_message(envelope, "keep-agent-message", cancelled=True)
+ second, replaced = render_terminal_message(envelope, first, cancelled=True)
+
+ assert second == first
+ assert replaced is False
+ assert first.count("2 blocks ran this turn.") == 1
+ assert first.count("The saved workflow was rolled back to its state before this turn.") == 1
+
+
+def test_cancelled_render_appends_to_agent_text_even_with_a_failure_recorded() -> None:
+ """Every replacing branch is guarded ``not cancelled``, which is why the stop report ships ungated."""
+ envelope = TerminalOutcomeEnvelope(
+ next_state="stopped",
+ verified=False,
+ response_kind="stopped",
+ blocks_run_this_turn=2,
+ terminal_cause="cdp_connect_failed",
+ connect_failure=BuildTestConnectFailure(state="cdp_connect_failed", browser_session_id="pbs_1"),
+ failed_operation=BuildTestFailedOperation(kind="browser_operation_failed"),
+ )
+
+ rendered, replaced = render_terminal_message(envelope, "keep-agent-message", cancelled=True)
+
+ assert rendered.startswith("keep-agent-message")
+ assert "Build testing stopped with browser connection state" not in rendered
+ assert "I stopped after a browser operation failed" not in rendered
+ assert "2 blocks ran this turn." in rendered
+ assert replaced is True
+
+
+def test_render_terminal_message_cancelled_names_the_rollback() -> None:
+ envelope = TerminalOutcomeEnvelope(
+ next_state="stopped",
+ verified=False,
+ response_kind="stopped",
+ blocks_run_this_turn=1,
+ canonical_rolled_back=True,
+ )
+
+ rendered, _ = render_terminal_message(envelope, MINIMAL_CANCEL_STOP, cancelled=True)
+
+ assert "The saved workflow was rolled back to its state before this turn." in rendered
+
+
+def test_an_unresolved_run_start_is_not_an_explicit_stop() -> None:
+ envelope = _assemble(
+ workflow_attempted=False,
+ run_outcomes=[interim_run_start_outcome("wr_1")],
+ )
+
+ assert envelope.run_outcome_role == "interim_build_test"
+ assert envelope.response_kind == "answer"
+
+
+def test_a_resolved_run_outcome_still_reports_an_explicit_stop() -> None:
+ envelope = _assemble(
+ workflow_attempted=False,
+ run_outcomes=[RecordedRunOutcome(verdict="not_evaluated", workflow_run_id="wr_1")],
+ )
+
+ assert envelope.run_outcome_role == "recorded"
+ assert envelope.response_kind == "stopped"
+
+
+def test_an_unresolved_run_start_leaves_the_turn_facts_evaluation_empty() -> None:
+ ctx = make_copilot_ctx()
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_1"))
+
+ facts = agent_module._turn_facts_for_context(ctx, None, None)
+
+ assert facts["runId"] == "wr_1"
+ assert facts["evaluationState"] is None
+ assert facts["runCompleted"] is None
+
+
def test_render_terminal_message_keeps_answer_kind_replies_on_stopped_state() -> None:
# Diagnose/refuse turns end next_state="stopped" with response_kind="answer";
# their specific reply text is the deliverable and must survive flag-on.
@@ -1128,10 +1299,10 @@ def test_render_terminal_message_held_draft_unreplaced_without_deadline_cause()
def test_render_terminal_message_cancelled_turn_ignores_deadline_cause() -> None:
envelope = _assemble(proposal_disposition="auto_applicable", terminal_cause="deadline_expired")
- rendered, replaced = render_terminal_message(envelope, "cancelled-text", cancelled=True)
+ rendered, _ = render_terminal_message(envelope, "cancelled-text", cancelled=True)
- assert rendered == "cancelled-text"
- assert replaced is False
+ assert rendered.startswith("cancelled-text")
+ assert "time limit" not in rendered
def test_render_terminal_message_completed_turn_is_not_stamped_by_deadline_cause() -> None:
@@ -1368,3 +1539,187 @@ def test_run_lifecycle_and_run_id_name_the_same_archived_outcome() -> None:
assert halted.run_id == "wr_2"
assert halted.run_completed is False
+
+
+def test_blocks_run_this_turn_is_absent_while_a_started_run_has_no_result() -> None:
+ ctx = make_copilot_ctx()
+ ctx.executed_block_labels = set()
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_1"))
+
+ assert agent_module._blocks_run_this_turn(ctx) is None
+
+
+def test_blocks_run_this_turn_reports_the_count_once_the_run_result_lands() -> None:
+ ctx = make_copilot_ctx()
+ ctx.executed_block_labels = {"sign_in", "extract"}
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_1"))
+ _stash_recorded_run_outcome(ctx, RecordedRunOutcome(verdict="not_evaluated", workflow_run_id="wr_1"))
+
+ assert agent_module._blocks_run_this_turn(ctx) == 2
+
+
+def test_an_unwound_run_start_is_dropped_and_a_recorded_outcome_is_kept() -> None:
+ ctx = make_copilot_ctx()
+ _stash_recorded_run_outcome(ctx, RecordedRunOutcome(verdict="not_evaluated", workflow_run_id="wr_1"))
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_2"))
+
+ _forget_interim_run_start(ctx, "wr_2")
+
+ assert [outcome.workflow_run_id for outcome in ctx.terminal_envelope_run_outcomes] == ["wr_1"]
+ assert agent_module._blocks_run_this_turn(ctx) == 0
+
+
+def test_one_stop_report_reads_its_verdict_and_block_count_from_the_same_run() -> None:
+ ctx = make_copilot_ctx()
+ ctx.executed_block_labels = {"sign_in", "extract"}
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_a"))
+ _stash_recorded_run_outcome(ctx, RecordedRunOutcome(verdict="not_demonstrated", workflow_run_id="wr_a"))
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_b"))
+
+ anchor = select_run_outcome_anchor(ctx.terminal_envelope_run_outcomes)
+
+ assert anchor is not None
+ assert anchor.workflow_run_id == "wr_b"
+ assert run_start_unresolved(ctx.terminal_envelope_run_outcomes)
+ assert agent_module._blocks_run_this_turn(ctx) is None
+
+
+def test_a_run_started_after_a_demonstrated_run_reports_the_new_run_unresolved() -> None:
+ ctx = make_copilot_ctx()
+ ctx.executed_block_labels = {"sign_in", "extract"}
+ _stash_recorded_run_outcome(ctx, RecordedRunOutcome(verdict="demonstrated", workflow_run_id="wr_a"))
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_b"))
+
+ anchor = select_run_outcome_anchor(ctx.terminal_envelope_run_outcomes)
+
+ assert anchor is not None
+ assert anchor.workflow_run_id == "wr_b"
+ assert run_start_unresolved(ctx.terminal_envelope_run_outcomes)
+ assert agent_module._blocks_run_this_turn(ctx) is None
+
+
+def test_a_run_that_demonstrated_the_goal_reports_its_real_block_count() -> None:
+ ctx = make_copilot_ctx()
+ ctx.executed_block_labels = {"sign_in"}
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_1"))
+ _stash_recorded_run_outcome(ctx, RecordedRunOutcome(verdict="demonstrated", workflow_run_id="wr_1"))
+
+ assert agent_module._blocks_run_this_turn(ctx) == 1
+
+
+def test_a_run_that_lost_its_browser_session_supersedes_its_own_run_start() -> None:
+ ctx = make_copilot_ctx()
+ ctx.executed_block_labels = set()
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_run_side"))
+
+ _commit_run_blocks_record(ctx, _run_side_failed_result(reason_code="browser_session_closed"))
+
+ assert not run_start_unresolved(ctx.terminal_envelope_run_outcomes)
+ assert agent_module._blocks_run_this_turn(ctx) == 0
+
+
+def test_a_stop_on_a_run_that_lost_its_browser_session_never_says_the_count_was_unconfirmed() -> None:
+ ctx = make_copilot_ctx()
+ ctx.executed_block_labels = set()
+ ctx.terminal_envelope_run_outcomes.append(interim_run_start_outcome("wr_run_side"))
+ _commit_run_blocks_record(ctx, _run_side_failed_result(reason_code="browser_session_closed"))
+
+ envelope = TerminalOutcomeEnvelope(
+ next_state="stopped",
+ verified=False,
+ response_kind="stopped",
+ blocks_run_this_turn=agent_module._blocks_run_this_turn(ctx),
+ run_id="wr_run_side",
+ run_verdict="not_evaluated",
+ )
+ rendered, _ = render_terminal_message(envelope, MINIMAL_CANCEL_STOP, cancelled=True)
+
+ assert "how many of its blocks ran was not confirmed" not in rendered
+ assert "0 blocks ran this turn." in rendered
+
+
+def test_blocks_run_this_turn_reports_zero_when_no_run_was_started() -> None:
+ ctx = make_copilot_ctx()
+ ctx.executed_block_labels = set()
+
+ assert agent_module._blocks_run_this_turn(ctx) == 0
+
+
+async def _run_blocks_cancelling_at(monkeypatch: pytest.MonkeyPatch, *, cancel_at: str | None) -> CopilotContext:
+ harness = await install_run_blocks_harness(
+ monkeypatch,
+ workflow_yaml=HANDBACK_WORKFLOW_YAML,
+ polled_status="running",
+ dispatch_to_worker=cancel_at is None,
+ )
+ ctx = make_copilot_ctx(browser_session_id="pbs_chat")
+ ctx.staged_workflow = harness["workflow"]
+ ctx.frontier_resume_session_id = "pbs_run"
+
+ async def _cancel(*_args: Any, **_kwargs: Any) -> None:
+ raise asyncio.CancelledError
+
+ if cancel_at is None:
+ harness["worker_execute"].side_effect = _cancel
+ else:
+ monkeypatch.setattr(run_execution_module, cancel_at, _cancel)
+ with pytest.raises(asyncio.CancelledError):
+ await run_execution_module._run_blocks_and_collect_debug(
+ {"block_labels": ["extract_heading"], "parameters": {}}, ctx
+ )
+ return ctx
+
+
+async def test_a_cancel_before_the_inline_run_starts_leaves_no_run_start_record(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = await _run_blocks_cancelling_at(monkeypatch, cancel_at="initialize_skyvern_state_file")
+
+ assert ctx.terminal_envelope_run_outcomes == []
+ assert agent_module._blocks_run_this_turn(ctx) == 0
+
+
+async def test_a_cancel_once_the_run_is_submitted_keeps_its_unresolved_run_start(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = await _run_blocks_cancelling_at(monkeypatch, cancel_at=None)
+
+ assert [outcome.role for outcome in ctx.terminal_envelope_run_outcomes] == ["interim_build_test"]
+ assert agent_module._blocks_run_this_turn(ctx) is None
+
+
+def test_only_a_stop_click_is_reported_as_the_user_asking() -> None:
+ """A Stop click is the user asking; an ambient Escape is the very thing this
+ ticket says the product cannot attribute, so it must not claim their intent."""
+
+ def render(source: str | None) -> str:
+ envelope = TerminalOutcomeEnvelope(
+ next_state="stopped",
+ verified=False,
+ response_kind="stopped",
+ blocks_run_this_turn=0,
+ cancel_source=source,
+ )
+ return render_terminal_message(envelope, MINIMAL_CANCEL_STOP, cancelled=True)[0]
+
+ assert render("stop_button").startswith(CANCEL_STOP_AT_USER_REQUEST)
+ for unattributed in ("escape_key", "api", None):
+ assert render(unattributed).startswith(MINIMAL_CANCEL_STOP)
+ assert "your request" not in render(unattributed)
+
+ # The ordinary build stop preserves a draft, so its seed reply is longer than the
+ # bare opening; the upgrade has to replace that opening rather than skip the turn.
+ with_draft = TerminalOutcomeEnvelope(
+ next_state="stopped",
+ verified=False,
+ response_kind="stopped",
+ blocks_run_this_turn=0,
+ cancel_source="stop_button",
+ proposal_present=True,
+ proposal_disposition="review_untested",
+ )
+ drafted = render_terminal_message(with_draft, _CANCEL_REPLY_UNVALIDATED, cancelled=True)[0]
+ assert drafted.startswith(CANCEL_STOP_AT_USER_REQUEST)
+ assert UNTESTED_DRAFT_PRESERVED in drafted
diff --git a/tests/unit/test_workflow_copilot_cancel.py b/tests/unit/test_workflow_copilot_cancel.py
index 9ba1631b0..871d499de 100644
--- a/tests/unit/test_workflow_copilot_cancel.py
+++ b/tests/unit/test_workflow_copilot_cancel.py
@@ -10,12 +10,12 @@ Covers:
``CopilotContext.workflow_persisted`` (so the route's rollback decision has
the same source of truth on cancel as it does on success).
- The route's success-path branch on ``agent_result.cancelled`` runs the
- cancel-specific persistence (rollback + user msg + ``Cancelled by user.``
+ cancel-specific persistence (rollback + user msg + stop-report
AI msg + RESPONSE frame) and skips proposal persistence when there is no WIP.
- ``/workflow/copilot/cancel`` returns 503 when the Redis cache is absent and
204 + the expected key/TTL when it is present.
- A cancel nobody asked for (``task.cancel()`` without ``user_cancel_observed[0]``
- set) is recorded as an interrupted turn, never as a ``Cancelled by user.`` chat row.
+ set) is recorded as an interrupted turn, never as a stop-report chat row.
"""
from __future__ import annotations
@@ -33,19 +33,21 @@ from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.sdk.copilot.agent import _build_exit_result
from skyvern.forge.sdk.copilot.context import AgentResult, CopilotContext, StructuredContext
-from skyvern.forge.sdk.copilot.terminal_envelope import INTERRUPTED_TERMINAL_REASON
+from skyvern.forge.sdk.copilot.terminal_envelope import INTERRUPTED_TERMINAL_REASON, MINIMAL_CANCEL_STOP
from skyvern.forge.sdk.routes.workflow_copilot import (
COPILOT_CANCEL_TTL,
USER_CANCELLED_TERMINAL_REASON,
_assistant_row_exists_for_turn,
+ _coerce_cancel_source,
_copilot_cancel_key,
+ _make_error_narrative_payload,
_persist_cancel_turn,
_persist_proposed_workflow_state,
_watch_for_cancel,
workflow_copilot_cancel,
workflow_copilot_chat_post,
)
-from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind
+from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcome
from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotCancelRequest,
WorkflowCopilotChatRequest,
@@ -147,12 +149,12 @@ def test_build_exit_result_cancelled_round_trips_workflow_persisted() -> None:
)
ctx.workflow_persisted = True
- result = _build_exit_result(ctx, "Cancelled by user.", None, cancelled=True)
+ result = _build_exit_result(ctx, MINIMAL_CANCEL_STOP, None, cancelled=True)
assert isinstance(result, AgentResult)
assert result.cancelled is True
assert result.workflow_was_persisted is True
- assert result.user_response == "Cancelled by user."
+ assert result.user_response == MINIMAL_CANCEL_STOP
def test_build_exit_result_default_cancelled_false() -> None:
@@ -253,8 +255,11 @@ async def _drive_cancel_route(
cancel_token: str,
handler_task: Any,
observed: list[bool],
+ observed_source: list[str | None] | None = None,
) -> Any:
observed[0] = True
+ if observed_source is not None:
+ observed_source[0] = "stop_button"
return asyncio.sleep(0)
monkeypatch.setattr(app._inst, "CACHE", _FakeCache(), raising=False)
@@ -300,7 +305,7 @@ async def test_route_cancel_branch_persists_user_and_cancelled_messages(
chat = _make_chat(auto_accept=False)
original_workflow = _make_original_workflow()
agent_result = SimpleNamespace(
- user_response="Cancelled by user.",
+ user_response=MINIMAL_CANCEL_STOP,
updated_workflow=None,
global_llm_context=None,
workflow_yaml=None,
@@ -327,7 +332,7 @@ async def test_route_cancel_branch_persists_user_and_cancelled_messages(
"[Message unavailable because safety screening did not complete]"
)
- assert "Cancelled by user." in contents
+ assert MINIMAL_CANCEL_STOP in contents
# No proposed_workflow update when the cancelled result has no WIP.
workflow_params.update_workflow_copilot_chat.assert_not_awaited()
@@ -335,7 +340,7 @@ async def test_route_cancel_branch_persists_user_and_cancelled_messages(
p for p in sent_payloads if getattr(p, "type", None) == WorkflowCopilotStreamMessageType.RESPONSE
]
assert len(response_frames) == 1
- assert response_frames[0].message == "Cancelled by user."
+ assert response_frames[0].message == MINIMAL_CANCEL_STOP
assert response_frames[0].updated_workflow is None
assert response_frames[0].cancelled is True
@@ -351,7 +356,7 @@ async def test_route_cancel_branch_records_an_unrequested_cancel_as_interrupted(
chat = _make_chat(auto_accept=False)
original_workflow = _make_original_workflow()
agent_result = SimpleNamespace(
- user_response="Cancelled by user.",
+ user_response=MINIMAL_CANCEL_STOP,
updated_workflow=None,
global_llm_context=None,
workflow_yaml=None,
@@ -369,7 +374,7 @@ async def test_route_cancel_branch_records_an_unrequested_cancel_as_interrupted(
)
written = workflow_params.create_workflow_copilot_chat_message.await_args_list[-1].kwargs
- assert "Cancelled by user." not in written["content"]
+ assert MINIMAL_CANCEL_STOP not in written["content"]
assert "interrupted" in written["content"].lower()
assert "iteration 2" in written["content"]
assert "were not saved to the workflow" in written["content"]
@@ -387,6 +392,94 @@ async def test_route_cancel_branch_records_an_unrequested_cancel_as_interrupted(
assert "interrupted" in response_frames[0].message.lower()
+async def test_cancel_reply_reports_recorded_run_state_with_the_render_flag_off(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION,
+ "should_render_copilot_terminal_from_envelope",
+ AsyncMock(return_value=False),
+ )
+ chat = _make_chat(auto_accept=False)
+ original_workflow = _make_original_workflow()
+ agent_result = SimpleNamespace(
+ user_response=MINIMAL_CANCEL_STOP,
+ updated_workflow=None,
+ global_llm_context=None,
+ workflow_yaml=None,
+ workflow_was_persisted=True,
+ clear_proposed_workflow=False,
+ resolved_model=None,
+ cancelled=True,
+ total_tokens=None,
+ response_type="REPLY",
+ turn_outcome=None,
+ narrative_summary=MINIMAL_CANCEL_STOP,
+ narrative_payload=_make_error_narrative_payload(None, 0, MINIMAL_CANCEL_STOP),
+ terminal_envelope={
+ "next_state": "stopped",
+ "verified": False,
+ "response_kind": "stopped",
+ "blocks_run_this_turn": 3,
+ },
+ )
+ _, workflow_params, sent_payloads = await _drive_cancel_route(monkeypatch, chat, original_workflow, agent_result)
+
+ written = workflow_params.create_workflow_copilot_chat_message.await_args_list[-1].kwargs
+ assert written["content"] != MINIMAL_CANCEL_STOP
+ assert "3 blocks ran this turn" in written["content"]
+ assert written["narrative_payload"]["terminalEnvelope"]["rendered_from_envelope"] is True
+ frame = next(p for p in sent_payloads if getattr(p, "type", None) == WorkflowCopilotStreamMessageType.RESPONSE)
+ assert frame.message == written["content"]
+
+
+async def test_interrupted_record_replaces_the_cancel_rendered_narrative_summary(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION,
+ "should_render_copilot_terminal_from_envelope",
+ AsyncMock(return_value=True),
+ )
+ chat = _make_chat(auto_accept=False)
+ original_workflow = _make_original_workflow()
+ agent_result = SimpleNamespace(
+ user_response=MINIMAL_CANCEL_STOP,
+ updated_workflow=None,
+ global_llm_context=None,
+ workflow_yaml=None,
+ workflow_was_persisted=True,
+ clear_proposed_workflow=False,
+ resolved_model=None,
+ cancelled=True,
+ cancellation_iteration=2,
+ total_tokens=None,
+ response_type="REPLY",
+ turn_outcome=None,
+ narrative_summary=MINIMAL_CANCEL_STOP,
+ narrative_payload=_make_error_narrative_payload(None, 0, MINIMAL_CANCEL_STOP),
+ terminal_envelope={
+ "next_state": "stopped",
+ "verified": False,
+ "response_kind": "stopped",
+ "blocks_run_this_turn": 0,
+ },
+ )
+ _, workflow_params, sent_payloads = await _drive_cancel_route(
+ monkeypatch, chat, original_workflow, agent_result, user_cancel=False
+ )
+
+ frame = next(p for p in sent_payloads if getattr(p, "type", None) == WorkflowCopilotStreamMessageType.RESPONSE)
+ assert "interrupted" in frame.message.lower()
+ assert frame.narrative_summary == frame.message
+ assert frame.narrative_payload["narrativeSummary"] == frame.message
+ assert "0 blocks ran" not in frame.narrative_summary
+ written = workflow_params.create_workflow_copilot_chat_message.await_args_list[-1].kwargs
+ assert written["narrative_payload"]["narrativeSummary"] == written["content"]
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("disposition", "expect_unvalidated_marker", "title", "user_response"),
@@ -504,7 +597,7 @@ async def test_route_cancel_clears_stale_proposed_workflow_when_no_wip(
)
original_workflow = _make_original_workflow()
agent_result = SimpleNamespace(
- user_response="Cancelled by user.",
+ user_response=MINIMAL_CANCEL_STOP,
updated_workflow=None,
global_llm_context=None,
workflow_yaml=None,
@@ -538,7 +631,7 @@ async def test_route_cancel_keeps_stale_proposed_workflow_when_no_wip_and_keep_p
)
original_workflow = _make_original_workflow()
agent_result = SimpleNamespace(
- user_response="Cancelled by user.",
+ user_response=MINIMAL_CANCEL_STOP,
updated_workflow=None,
global_llm_context=None,
workflow_yaml=None,
@@ -570,7 +663,7 @@ async def test_route_cancel_explicit_clear_overrides_keep_pending(
)
original_workflow = _make_original_workflow()
agent_result = SimpleNamespace(
- user_response="Cancelled by user.",
+ user_response=MINIMAL_CANCEL_STOP,
updated_workflow=None,
global_llm_context=None,
workflow_yaml=None,
@@ -605,7 +698,7 @@ async def test_route_cancel_clears_stale_proposal_when_rollback_itself_fails(
)
original_workflow = _make_original_workflow()
agent_result = SimpleNamespace(
- user_response="Cancelled by user.",
+ user_response=MINIMAL_CANCEL_STOP,
updated_workflow=None,
global_llm_context=None,
workflow_yaml=None,
@@ -643,7 +736,7 @@ async def test_route_cancel_clears_stale_proposal_when_rollback_itself_fails(
async def test_pre_agent_cancel_clears_stale_proposed_workflow() -> None:
"""Pre-agent cancel (agent_result=None) must clear any stale proposal.
- Without this, reload reattaches the old card to the new "Cancelled by user." message.
+ Without this, reload reattaches the old card to the new stop-report message.
"""
chat = SimpleNamespace(
organization_id="org-1",
@@ -747,6 +840,49 @@ async def test_pre_agent_cancel_keeps_stale_proposed_workflow_when_keep_pending(
workflow_params.update_workflow_copilot_chat.assert_not_awaited()
+async def test_pre_agent_cancel_reports_recorded_run_state_with_the_render_flag_off(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A cancel has no model-authored reply to protect, so the stop report is not behind the rollout flag."""
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION,
+ "should_render_copilot_terminal_from_envelope",
+ AsyncMock(return_value=False),
+ )
+ chat = SimpleNamespace(
+ organization_id="org-1",
+ workflow_copilot_chat_id="chat-1",
+ proposed_workflow=None,
+ auto_accept=False,
+ )
+ workflow_params = SimpleNamespace(
+ update_workflow_copilot_chat=AsyncMock(),
+ create_workflow_copilot_chat_message=AsyncMock(
+ return_value=SimpleNamespace(created_at=datetime(2026, 4, 27, tzinfo=timezone.utc))
+ ),
+ )
+ app.DATABASE.workflow_params = workflow_params
+
+ stream = MagicMock()
+ stream.send = AsyncMock(return_value=True)
+
+ await _persist_cancel_turn(
+ stream=stream,
+ chat=chat,
+ organization_id="org-1",
+ original_workflow=None,
+ user_message="please update",
+ agent_result=None,
+ )
+
+ written = workflow_params.create_workflow_copilot_chat_message.await_args_list[-1].kwargs
+ assert written["content"] != MINIMAL_CANCEL_STOP
+ assert "0 blocks ran this turn." in written["content"]
+ assert "No workflow draft from this turn was preserved." in written["content"]
+ assert written["narrative_payload"]["narrativeSummary"] == written["content"]
+
+
@pytest.mark.asyncio
async def test_timeout_wip_result_streams_normal_response_frame(
monkeypatch: pytest.MonkeyPatch,
@@ -824,7 +960,7 @@ async def test_timeout_wip_result_streams_normal_response_frame(
error_frames = [p for p in sent_payloads if getattr(p, "type", None) == WorkflowCopilotStreamMessageType.ERROR]
assert error_frames == []
contents = [c.kwargs.get("content") for c in workflow_params.create_workflow_copilot_chat_message.await_args_list]
- assert "Cancelled by user." not in contents
+ assert MINIMAL_CANCEL_STOP not in contents
@pytest.mark.asyncio
@@ -983,20 +1119,75 @@ async def test_cancel_endpoint_204_writes_redis_flag(monkeypatch: pytest.MonkeyP
organization = SimpleNamespace(organization_id="org-1")
result = await workflow_copilot_cancel(
- WorkflowCopilotCancelRequest(cancel_token="tok_abc"),
+ WorkflowCopilotCancelRequest(cancel_token="tok_abc", source="escape_key"),
organization=organization,
)
assert result is None # 204 No Content
+ # The flag value is the gesture, so the watcher can attribute the cancel.
expected_key = _copilot_cancel_key("org-1", "tok_abc")
- assert cache.store[expected_key] == "1"
+ assert cache.store[expected_key] == "escape_key"
assert len(cache.set_calls) == 1
key, value, ex = cache.set_calls[0]
- assert (key, value) == (expected_key, "1")
+ assert (key, value) == (expected_key, "escape_key")
assert isinstance(ex, timedelta)
assert ex == COPILOT_CANCEL_TTL
+ "flag, expected",
+ [
+ ("escape_key", "escape_key"),
+ ("stop_button", "stop_button"),
+ ("api", "api"),
+ (b"escape_key", "escape_key"),
+ # Written before the source existed: truthy, but names no gesture.
+ ("1", None),
+ ("something_else", None),
+ ],
+)
+def test_cancel_source_is_read_only_from_a_recognised_gesture(flag: str | bytes, expected: str | None) -> None:
+ assert _coerce_cancel_source(flag) == expected
+
+
+def test_the_gesture_is_recorded_beside_the_terminal_reason_on_the_turn() -> None:
+ """AC1: attributing cancels must not need a second column or a JSON blob.
+
+ ``turn_outcome`` is what the 120h RCA grouped by, so the source lives there
+ next to ``terminal_reason`` rather than only inside the narrative payload.
+ """
+ outcome = TurnOutcome(
+ response_kind=ResponseKind.RECOVER,
+ terminal_reason=USER_CANCELLED_TERMINAL_REASON,
+ cancel_source="escape_key",
+ )
+
+ persisted = outcome.model_dump(mode="json")
+ assert persisted["terminal_reason"] == USER_CANCELLED_TERMINAL_REASON
+ assert persisted["cancel_source"] == "escape_key"
+ # A turn whose request named no gesture reads as unattributed, never as a guess.
+ assert TurnOutcome(response_kind=ResponseKind.RECOVER).cancel_source is None
+
+
+async def test_watcher_reports_the_gesture_the_cancel_named() -> None:
+ cache = _FakeCache()
+ key = _copilot_cancel_key("org-1", "tok_abc")
+ cache.store[key] = "escape_key"
+ observed: list[bool] = [False]
+ observed_source: list[str | None] = [None]
+
+ async def never_finishes() -> None:
+ await asyncio.sleep(30)
+
+ handler_task = asyncio.create_task(never_finishes())
+ await _watch_for_cancel(cache, "org-1", "tok_abc", handler_task, observed, observed_source)
+
+ assert observed[0] is True
+ assert observed_source[0] == "escape_key"
+ assert handler_task.cancelled() or handler_task.cancelling()
+
+
# ---------------------------------------------------------------------------
# Operational cancel disambiguation
# ---------------------------------------------------------------------------
@@ -1035,7 +1226,6 @@ async def test_operational_cancel_records_the_turn_as_interrupted_and_still_re_r
async def fake_llm_handler(*args: object, **kwargs: object) -> None:
del args, kwargs
- return None
monkeypatch.setattr(
"skyvern.forge.sdk.routes.workflow_copilot.resolve_main_copilot_handler",
@@ -1089,7 +1279,7 @@ async def test_operational_cancel_records_the_turn_as_interrupted_and_still_re_r
insert_calls = workflow_params.create_workflow_copilot_chat_message.await_args_list
contents = [c.kwargs.get("content") for c in insert_calls]
- assert "Cancelled by user." not in contents
+ assert MINIMAL_CANCEL_STOP not in contents
interrupted = [content for content in contents if content and "interrupted" in content.lower()]
assert len(interrupted) == 1
assert "wpid-1" in interrupted[0]
diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.py
index 10ba23e04..d5e5ac7c0 100644
--- a/tests/unit/test_workflow_copilot_route.py
+++ b/tests/unit/test_workflow_copilot_route.py
@@ -39,6 +39,7 @@ from skyvern.forge.sdk.copilot.enforcement import TOTAL_TIMEOUT_SECONDS
from skyvern.forge.sdk.copilot.terminal_envelope import (
INTERRUPTED_TERMINAL_MESSAGE,
INTERRUPTED_TERMINAL_REASON,
+ MINIMAL_CANCEL_STOP,
InterruptedTurnFacts,
TerminalOutcomeEnvelope,
assemble_terminal_envelope,
@@ -140,7 +141,7 @@ def _terminal_payload(
workflow_applied: bool,
workflow_mutated: bool = True,
workflow_attempted: bool = True,
- blocks_run_this_turn: int = 0,
+ blocks_run_this_turn: int | None = 0,
) -> dict[str, Any]:
envelope = assemble_terminal_envelope(
response_type="REPLY",
@@ -664,7 +665,7 @@ async def test_cancel_turn_finalizes_terminal_envelope_to_non_completed_state(
)
original_workflow = SimpleNamespace(workflow_id="wf-canonical")
agent_result = AgentResult(
- user_response="Cancelled by user.",
+ user_response=MINIMAL_CANCEL_STOP,
updated_workflow=None,
global_llm_context=None,
response_type="REPLY",
@@ -716,7 +717,7 @@ async def _persist_cancel_and_read_row(
)
original_workflow = SimpleNamespace(workflow_id="wf-canonical", version=7)
agent_result = AgentResult(
- user_response="Cancelled by user.",
+ user_response=MINIMAL_CANCEL_STOP,
updated_workflow=None,
global_llm_context=None,
response_type="REPLY",
@@ -778,7 +779,8 @@ async def test_a_user_stop_is_still_recorded_as_the_users_own_cancel(
) -> None:
content, payload = await _persist_cancel_and_read_row(monkeypatch, record_as_interrupted=False)
- assert content == "Cancelled by user."
+ assert "Cancelled by user." not in content
+ assert content.startswith("Stopped.")
assert payload["terminalEnvelope"].get("interruption") is None
@@ -1143,7 +1145,7 @@ async def test_terminal_envelope_finalization_failure_omits_envelope(
updated_workflow = MagicMock()
updated_workflow.model_dump.return_value = {"workflow_id": "wf-draft"}
agent_result = AgentResult(
- user_response="done" if finalizer == "normal" else "Cancelled by user.",
+ user_response="done" if finalizer == "normal" else MINIMAL_CANCEL_STOP,
updated_workflow=updated_workflow if finalizer == "normal" else None,
global_llm_context=None,
response_type="REPLY",
@@ -1283,7 +1285,7 @@ async def test_terminal_envelope_finalization_failure_flag_on_fails_closed_to_le
@pytest.mark.asyncio
-async def test_cancel_turn_agent_result_flag_on_marks_envelope_but_keeps_message(
+async def test_cancel_turn_agent_result_flag_on_persists_the_rendered_stop_report(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
@@ -1299,14 +1301,14 @@ async def test_cancel_turn_agent_result_flag_on_marks_envelope_but_keeps_message
)
original_workflow = SimpleNamespace(workflow_id="wf-canonical")
agent_result = AgentResult(
- user_response="Cancelled by user.",
+ user_response=MINIMAL_CANCEL_STOP,
updated_workflow=None,
global_llm_context=None,
response_type="REPLY",
proposal_disposition="auto_applicable",
cancelled=True,
narrative_payload=_narrative_payload(),
- terminal_envelope=_terminal_payload(verified=True, workflow_applied=True),
+ terminal_envelope=_terminal_payload(verified=True, workflow_applied=True, blocks_run_this_turn=3),
)
_, workflow_params = setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)
stream = MagicMock(send=AsyncMock(return_value=True))
@@ -1322,18 +1324,22 @@ async def test_cancel_turn_agent_result_flag_on_marks_envelope_but_keeps_message
response_frame = stream.send.await_args.args[0]
assert isinstance(response_frame, WorkflowCopilotStreamResponseUpdate)
- assert response_frame.message == "Cancelled by user."
+ assert "Cancelled by user." not in response_frame.message
+ assert "3 blocks ran this turn." in response_frame.message
assert response_frame.terminal_envelope is not None
assert response_frame.terminal_envelope["rendered_from_envelope"] is True
persisted_writes = workflow_params.create_workflow_copilot_chat_message.await_args_list
- assert persisted_writes[-1].kwargs["content"] == "Cancelled by user."
+ # The reload leg reads this row, so it must carry the same report the frame did.
+ assert persisted_writes[-1].kwargs["content"] == response_frame.message
persisted_payload = persisted_writes[-1].kwargs["narrative_payload"]
assert persisted_payload is not None
+ assert persisted_payload["terminalMessage"] == response_frame.message
+ assert persisted_payload["narrativeSummary"] == response_frame.message
assert persisted_payload["terminalEnvelope"]["rendered_from_envelope"] is True
@pytest.mark.asyncio
-async def test_pre_agent_cancel_path_keeps_literal_cancelled_by_user(monkeypatch: pytest.MonkeyPatch) -> None:
+async def test_pre_agent_cancel_path_reports_that_nothing_was_dispatched(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
app.AGENT_FUNCTION,
"should_render_copilot_terminal_from_envelope",
@@ -1360,10 +1366,12 @@ async def test_pre_agent_cancel_path_keeps_literal_cancelled_by_user(monkeypatch
response_frame = stream.send.await_args.args[0]
assert isinstance(response_frame, WorkflowCopilotStreamResponseUpdate)
- assert response_frame.message == "Cancelled by user."
- assert response_frame.terminal_envelope is None
+ assert "Cancelled by user." not in response_frame.message
+ assert "0 blocks ran this turn." in response_frame.message
+ assert response_frame.terminal_envelope is not None
+ assert response_frame.terminal_envelope["blocks_run_this_turn"] == 0
persisted_writes = workflow_params.create_workflow_copilot_chat_message.await_args_list
- assert persisted_writes[-1].kwargs["content"] == "Cancelled by user."
+ assert persisted_writes[-1].kwargs["content"] == response_frame.message
@pytest.mark.asyncio