Skip to content

Automate browser based workflows with AI

feat(SKY-12136): g2 unified review gate behind copilot_ux_v1 (#7273)

Celal Zamanoğlu8d60808001cc
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
index ec93b6b3e..259487e10 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
@@ -900,6 +900,105 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
});
});
+describe("computeTurnSummary — uxV1 disposition-first reorder (SKY-12136)", () => {
+ it("a pending untested draft outranks a non-build responseKind (old: Question)", () => {
+ const turn = buildTurn({
+ responseKind: "clarify",
+ draft: draft3,
+ proposalDisposition: "review_untested",
+ });
+ expect(computeTurnSummary(turn).headline).toBe("Question");
+ const summary = computeTurnSummary(turn, { uxV1: true });
+ expect(summary.headline).toBe("Draft needs review");
+ expect(summary.accent).toBe("qa");
+ expect(summary.glyph).toBe("!");
+ });
+
+ it("a pending tested draft outranks a non-build responseKind too", () => {
+ const summary = computeTurnSummary(
+ buildTurn({
+ responseKind: "clarify",
+ draft: draft3,
+ proposalDisposition: "review_tested",
+ }),
+ { uxV1: true },
+ );
+ expect(summary.headline).toBe("Workflow ready for review");
+ expect(summary.accent).toBe("qa");
+ expect(summary.glyph).toBe("!");
+ });
+
+ it("fallback chain: an untested draft outranks needsInput text when responseKind is null", () => {
+ const turn = buildTurn({
+ draft: draft3,
+ proposalDisposition: "review_untested",
+ terminalMessage: "Could you provide the login details?",
+ });
+ expect(turn.responseKind).toBeNull();
+ expect(computeTurnSummary(turn).headline).toBe("Question");
+ const summary = computeTurnSummary(turn, { uxV1: true });
+ expect(summary.headline).toBe("Draft needs review");
+ });
+
+ it("old payload (hydrated, no responseKind) still gets the uxV1 draft-review reorder", () => {
+ const turn = hydrateNarrativeFromPayload(
+ reproClarifyPayload({ proposalDisposition: "review_untested" }),
+ )!;
+ expect(turn.responseKind).toBeNull();
+ const summary = computeTurnSummary(turn, { uxV1: true });
+ expect(summary.headline).toBe("Draft needs review");
+ });
+
+ it("renames the pure-ask clarify headline to Needs your input", () => {
+ const summary = computeTurnSummary(
+ buildTurn({ responseKind: "clarify", verifiedSuccess: false }),
+ { uxV1: true },
+ );
+ expect(summary.headline).toBe("Needs your input");
+ expect(summary.accent).toBe("qa");
+ expect(summary.glyph).toBe("✦");
+ });
+
+ it.each([
+ ["refuse", "Declined"],
+ ["diagnose", "Answered"],
+ ] as const)(
+ "leaves %s as %s under uxV1 — only the clarify/Question case renames",
+ (kind, headline) => {
+ const summary = computeTurnSummary(
+ buildTurn({ responseKind: kind, verifiedSuccess: false }),
+ { uxV1: true },
+ );
+ expect(summary.headline).toBe(headline);
+ expect(summary.accent).toBe("qa");
+ },
+ );
+
+ it("isStoppedWithDraft keeps absolute precedence under uxV1 too", () => {
+ const summary = computeTurnSummary(
+ buildTurn({
+ cancelled: true,
+ draft: draft3,
+ proposalDisposition: "review_untested",
+ responseKind: "build",
+ verifiedSuccess: true,
+ }),
+ { uxV1: true },
+ );
+ expect(summary.headline).toBe("Stopped with a draft");
+ expect(summary.accent).toBe("qa");
+ });
+
+ it("uxV1 fallback needsInput still renders Needs your input when no draft is pending", () => {
+ const turn = buildTurn({
+ terminalMessage: "Could you provide the login details?",
+ });
+ expect(computeTurnSummary(turn).headline).toBe("Question");
+ const summary = computeTurnSummary(turn, { uxV1: true });
+ expect(summary.headline).toBe("Needs your input");
+ });
+});
+
describe("hydrateHistoryNarrative — persisted turn_outcome graft", () => {
it("grafts clarify from the adjacent turn_outcome onto a pre-fix payload", () => {
const turn = hydrateHistoryNarrative(reproClarifyPayload(), {
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
index bca738c8b..745137fcd 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
@@ -787,10 +787,18 @@ function DetailView({ turn, onCollapse, onBlockSelect }: DetailViewProps) {
interface NarrativeViewProps {
turn: TurnNarrativeState;
onBlockSelect?: (blockLabel: string) => void;
+ uxV1?: boolean;
}
-export function NarrativeView({ turn, onBlockSelect }: NarrativeViewProps) {
- const summary = useMemo(() => computeTurnSummary(turn), [turn]);
+export function NarrativeView({
+ turn,
+ onBlockSelect,
+ uxV1,
+}: NarrativeViewProps) {
+ const summary = useMemo(
+ () => computeTurnSummary(turn, { uxV1 }),
+ [turn, uxV1],
+ );
const isInFlight = turn.terminal === null;
const isComplete = !isInFlight;
const [userRolled, setUserRolled] = useState<boolean | null>(null);
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 0f4bef355..c50844b8c 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
@@ -100,7 +100,9 @@ vi.mock("react-router-dom", async (importOriginal) => {
});
vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: () => true,
+ // "copilot_ux_v1" stays off — this file's fixtures pin today's headline
+ // strings, not the disposition-first reorder behind that flag.
+ useFeatureFlagEnabled: (flag: string) => flag !== "copilot_ux_v1",
}));
const saveData = {
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx
new file mode 100644
index 000000000..3123edc49
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx
@@ -0,0 +1,506 @@
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { COPILOT_UX_V1_FLAG } from "@/util/featureFlags";
+
+import type { WorkflowCopilotStreamResponseUpdate } from "./workflowCopilotTypes";
+
+type StreamBody = {
+ message: string;
+ keep_pending_proposal?: boolean;
+};
+type StreamCall = {
+ body: StreamBody;
+ onMessage: (payload: unknown) => boolean;
+ resolve: () => void;
+ reject: (error: unknown) => void;
+};
+
+const {
+ streamCalls,
+ postStreaming,
+ cancelPost,
+ historyGet,
+ historyResponse,
+ flagMap,
+} = vi.hoisted(() => {
+ const calls: StreamCall[] = [];
+ const post = vi.fn().mockResolvedValue({});
+ const streaming = vi.fn(
+ (
+ _path: string,
+ body: StreamBody,
+ onMessage: (payload: unknown) => boolean,
+ ) =>
+ new Promise<void>((resolve, reject) => {
+ calls.push({ body, onMessage, resolve, reject });
+ }),
+ );
+ const history = {
+ data: {
+ workflow_copilot_chat_id: "chat-1" as string | null,
+ chat_history: [] as unknown[],
+ proposed_workflow: null as Record<string, unknown> | null,
+ auto_accept: false,
+ },
+ };
+ const get = vi.fn().mockImplementation(() => Promise.resolve(history));
+ return {
+ streamCalls: calls,
+ postStreaming: streaming,
+ cancelPost: post,
+ historyGet: get,
+ historyResponse: history,
+ flagMap: { current: {} as Record<string, boolean> },
+ };
+});
+
+vi.mock("@/api/sse", () => ({
+ getSseClient: vi.fn().mockResolvedValue({ postStreaming }),
+}));
+
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: vi.fn().mockResolvedValue({
+ get: historyGet,
+ post: cancelPost,
+ }),
+}));
+
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => null,
+}));
+
+vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));
+
+vi.mock("react-router-dom", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react-router-dom")>();
+ return {
+ ...actual,
+ useParams: () => ({
+ workflowPermanentId: "wpid_1",
+ workflowRunId: undefined,
+ }),
+ useSearchParams: () => [new URLSearchParams(), vi.fn()],
+ };
+});
+
+vi.mock("posthog-js/react", () => ({
+ useFeatureFlagEnabled: (flag: string) => flagMap.current[flag] ?? false,
+}));
+
+const saveData = {
+ title: "Test WF",
+ workflow: {
+ workflow_id: "wf_1",
+ workflow_permanent_id: "wpid_1",
+ description: "",
+ totp_verification_url: null,
+ is_saved_task: false,
+ status: "published",
+ },
+ settings: {
+ proxyLocation: null,
+ webhookCallbackUrl: null,
+ persistBrowserSession: false,
+ pinSavedSessionIp: false,
+ browserProfileId: null,
+ browserProfileKey: null,
+ model: null,
+ maxScreenshotScrolls: null,
+ extraHttpHeaders: null,
+ runWith: "agent",
+ scriptCacheKey: "",
+ aiFallback: true,
+ codeVersion: 2,
+ runSequentially: false,
+ sequentialKey: null,
+ },
+ parameters: [],
+ blocks: [],
+ workflowDefinitionVersion: 1,
+};
+
+vi.mock("@/store/WorkflowHasChangesStore", () => ({
+ useWorkflowHasChangesStore: () => ({ getSaveData: () => saveData }),
+}));
+
+// Unrelated to this file's tests; the real hook needs a QueryClientProvider
+// this harness doesn't set up.
+vi.mock("@/routes/workflows/hooks/useWorkflowRunQuery", () => ({
+ useWorkflowRunQuery: () => ({ data: undefined }),
+}));
+
+import { WorkflowCopilotChat } from "./WorkflowCopilotChat";
+
+async function renderChat(props: { docked?: boolean } = {}) {
+ // docked renders via a portal; without a target it intentionally renders null.
+ const portalTarget = props.docked ? document.body : undefined;
+ const view = render(
+ <WorkflowCopilotChat
+ docked={props.docked ?? false}
+ portalTarget={portalTarget}
+ />,
+ );
+ await waitFor(() =>
+ expect(screen.getByPlaceholderText(/Message Skyvern Copilot/)).toBeTruthy(),
+ );
+ return view;
+}
+
+function textarea(): HTMLTextAreaElement {
+ return screen.getByRole("textbox") as HTMLTextAreaElement;
+}
+
+async function submit(value: string) {
+ fireEvent.change(textarea(), { target: { value } });
+ await act(async () => {
+ fireEvent.keyDown(textarea(), { key: "Enter" });
+ });
+}
+
+const proposedWorkflowPayload = (
+ overrides: Record<string, unknown> = {},
+): Record<string, unknown> => ({
+ workflow_id: "wf_proposed",
+ title: "Draft workflow",
+ _copilot_unvalidated: true,
+ ...overrides,
+});
+
+const proposalNarrativePayload = (
+ overrides: Record<string, unknown> = {},
+): Record<string, unknown> => ({
+ turnId: "turn-1",
+ turnIndex: 0,
+ mode: "build",
+ responseType: "REPLY",
+ cancelled: false,
+ proposalDisposition: "review_untested",
+ designStarted: true,
+ designEnded: true,
+ draft: {
+ blockCount: 1,
+ blockLabels: ["extract_titles"],
+ summary: null,
+ },
+ blocks: [
+ {
+ workflowRunBlockId: "wrb_extract_titles",
+ label: "extract_titles",
+ blockType: "task",
+ state: "completed",
+ lastSeenIteration: 0,
+ activity: [],
+ startedAt: null,
+ endedAt: null,
+ },
+ ],
+ terminal: "response",
+ terminalMessage: "Here is a draft workflow for you to review.",
+ narrativeSummary: "Here is a draft workflow for you to review.",
+ priorBlockCount: 0,
+ designActivity: [],
+ startedAt: "2026-07-09T00:00:00Z",
+ endedAt: "2026-07-09T00:00:05Z",
+ ...overrides,
+});
+
+const proposalResponse = (
+ message: string,
+ overrides: Partial<WorkflowCopilotStreamResponseUpdate> &
+ Record<string, unknown> = {},
+): WorkflowCopilotStreamResponseUpdate =>
+ ({
+ type: "response",
+ workflow_copilot_chat_id: "chat-1",
+ message,
+ updated_workflow: proposedWorkflowPayload(),
+ response_time: "2026-07-09T00:00:05Z",
+ proposal_disposition: "review_untested",
+ turn_id: "turn-1",
+ narrative_payload: proposalNarrativePayload(),
+ ...overrides,
+ }) as WorkflowCopilotStreamResponseUpdate;
+
+const plainReplyResponse = (
+ message: string,
+ overrides: Partial<WorkflowCopilotStreamResponseUpdate> &
+ Record<string, unknown> = {},
+): WorkflowCopilotStreamResponseUpdate =>
+ ({
+ type: "response",
+ workflow_copilot_chat_id: "chat-1",
+ message,
+ updated_workflow: null,
+ response_time: "2026-07-09T00:00:10Z",
+ proposal_disposition: "no_proposal",
+ turn_id: "turn-2",
+ narrative_payload: {
+ ...proposalNarrativePayload(),
+ turnId: "turn-2",
+ turnIndex: 1,
+ draft: null,
+ proposalDisposition: "no_proposal",
+ terminalMessage: message,
+ narrativeSummary: message,
+ },
+ ...overrides,
+ }) as WorkflowCopilotStreamResponseUpdate;
+
+beforeEach(() => {
+ HTMLElement.prototype.scrollIntoView = vi.fn();
+ HTMLElement.prototype.scrollTo = vi.fn();
+ streamCalls.length = 0;
+ postStreaming.mockClear();
+ cancelPost.mockClear();
+ cancelPost.mockResolvedValue({});
+ historyGet.mockClear();
+ flagMap.current = {};
+ historyResponse.data = {
+ workflow_copilot_chat_id: "chat-1",
+ chat_history: [],
+ proposed_workflow: null,
+ auto_accept: false,
+ };
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe("WorkflowCopilotChat — g2 review gate (flag-on, SKY-12136)", () => {
+ it("does not send keep_pending_proposal on a chat's first message (nothing pending yet)", async () => {
+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
+ await renderChat();
+
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+
+ expect(streamCalls[0]!.body.keep_pending_proposal).toBe(false);
+ });
+
+ it("restores an actionable gate via the chip after a bypassed proposal (old code: buttons vanish forever)", async () => {
+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
+ await renderChat();
+
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ streamCalls[0]!.onMessage(proposalResponse("Draft ready."));
+ streamCalls[0]!.resolve();
+ });
+
+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Always accept" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Review" })).toBeTruthy();
+
+ // Bypass: send a follow-up instead of acting on the gate.
+ historyResponse.data.proposed_workflow = proposedWorkflowPayload();
+ await submit("also grab the story scores");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));
+
+ // keep_pending_proposal must ride along on the bypassing request.
+ expect(streamCalls[1]!.body.keep_pending_proposal).toBe(true);
+ // Mid-flight: the gate's own actions are not accessible while loading.
+ expect(screen.queryByRole("button", { name: "Accept" })).toBeNull();
+ expect(screen.getByText("1 proposal pending · Review")).toBeTruthy();
+
+ // Turn 2 ends with no new proposal; resync picks the row back up.
+ await act(async () => {
+ streamCalls[1]!.onMessage(
+ plainReplyResponse("I'll fold that into the draft above."),
+ );
+ streamCalls[1]!.resolve();
+ });
+ await waitFor(() => expect(historyGet).toHaveBeenCalled());
+
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy(),
+ );
+ // The gate's owning turn is still not the last message, so the chip
+ // (and its jump-back affordance) stays up even once actions re-enable.
+ const chip = screen.getByText("1 proposal pending · Review");
+ await act(async () => {
+ fireEvent.click(chip);
+ });
+ expect(HTMLElement.prototype.scrollIntoView).toHaveBeenCalled();
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Accept" }));
+ });
+ await waitFor(() =>
+ expect(cancelPost).toHaveBeenCalledWith(
+ "/workflow/copilot/apply-proposed-workflow",
+ expect.objectContaining({ workflow_copilot_chat_id: "chat-1" }),
+ ),
+ );
+ });
+
+ it("shows the Untested pill on hydration of an old payload lacking proposalDisposition", async () => {
+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
+ historyResponse.data.proposed_workflow = proposedWorkflowPayload({
+ _copilot_unvalidated: true,
+ });
+ historyResponse.data.chat_history = [
+ {
+ sender: "ai",
+ content: "Here is a draft.",
+ created_at: "2026-07-09T00:00:05Z",
+ narrative_payload: null,
+ turn_outcome: null,
+ },
+ ];
+ await renderChat();
+
+ await waitFor(() => expect(screen.getByText("Untested")).toBeTruthy());
+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();
+ });
+
+ it("renders a legacy (no-narrative) pending turn as pill + footer, no changes body", async () => {
+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
+ historyResponse.data.proposed_workflow = proposedWorkflowPayload({
+ _copilot_unvalidated: true,
+ });
+ historyResponse.data.chat_history = [
+ {
+ sender: "ai",
+ content: "Here is a draft.",
+ created_at: "2026-07-09T00:00:05Z",
+ narrative_payload: null,
+ turn_outcome: null,
+ },
+ ];
+ await renderChat();
+
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy(),
+ );
+ expect(screen.getByText("Proposed changes")).toBeTruthy();
+ expect(screen.queryByText("Added")).toBeNull();
+ expect(screen.queryByText("Removed")).toBeNull();
+ // No narrative turn id to derive an owning turn from — the chip would be
+ // a dead no-op affordance here, not a working jump-back.
+ expect(screen.queryByText("1 proposal pending · Review")).toBeNull();
+ });
+
+ it("clears a stale bypassed gate when a later turn auto-applies (stale Accept can't reapply over the newer canvas)", async () => {
+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
+ await renderChat();
+
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ streamCalls[0]!.onMessage(proposalResponse("Draft ready."));
+ streamCalls[0]!.resolve();
+ });
+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();
+
+ // Bypass: this follow-up comes back auto-applied instead of another gate.
+ await submit("actually just fix the typo directly");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));
+ expect(streamCalls[1]!.body.keep_pending_proposal).toBe(true);
+
+ await act(async () => {
+ streamCalls[1]!.onMessage(
+ proposalResponse("Fixed and applied.", {
+ proposal_disposition: "auto_applicable",
+ workflow_applied: true,
+ turn_id: "turn-2",
+ narrative_payload: proposalNarrativePayload({
+ turnId: "turn-2",
+ turnIndex: 1,
+ proposalDisposition: "auto_applicable",
+ terminalMessage: "Fixed and applied.",
+ narrativeSummary: "Fixed and applied.",
+ }),
+ }),
+ );
+ streamCalls[1]!.resolve();
+ });
+
+ await waitFor(() =>
+ expect(screen.queryByRole("button", { name: "Accept" })).toBeNull(),
+ );
+ expect(screen.queryByText("1 proposal pending · Review")).toBeNull();
+ });
+
+ it("clears the proposal and shows a discarded receipt on a late Reject", async () => {
+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
+ await renderChat();
+
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ streamCalls[0]!.onMessage(proposalResponse("Draft ready."));
+ streamCalls[0]!.resolve();
+ });
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy(),
+ );
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Reject" }));
+ });
+
+ await waitFor(() =>
+ expect(cancelPost).toHaveBeenCalledWith(
+ "/workflow/copilot/clear-proposed-workflow",
+ expect.objectContaining({ workflow_copilot_chat_id: "chat-1" }),
+ ),
+ );
+ expect(
+ screen.getByText("Discarded — canvas reverted to the previous version"),
+ ).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Reject" })).toBeNull();
+ });
+});
+
+describe("WorkflowCopilotChat — flag-off parity (SKY-12136)", () => {
+ it("renders today's two green pills + Review + solid Reject with no chip, and never sends keep_pending_proposal", async () => {
+ await renderChat({ docked: true });
+
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ streamCalls[0]!.onMessage(proposalResponse("Draft ready."));
+ streamCalls[0]!.resolve();
+ });
+
+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Always accept" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Review" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
+ expect(screen.queryByText(/proposal pending/)).toBeNull();
+ expect(screen.queryByText("Untested")).toBeNull();
+ expect(streamCalls[0]!.body.keep_pending_proposal).toBe(false);
+
+ // docked -> today's DiffCard also renders alongside the raw button row.
+ expect(screen.getByText("Proposed changes")).toBeTruthy();
+ });
+
+ it("nulls the proposal on the next send, matching today's orphaning behavior", async () => {
+ await renderChat();
+
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ streamCalls[0]!.onMessage(proposalResponse("Draft ready."));
+ streamCalls[0]!.resolve();
+ });
+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();
+
+ await submit("also grab the story scores");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));
+
+ expect(streamCalls[1]!.body.keep_pending_proposal).toBe(false);
+ expect(screen.queryByRole("button", { name: "Accept" })).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 1349b4126..f38e38f9e 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -66,6 +66,7 @@ import { NarrativeView } from "./NarrativeView";
import { useRunLifecycleAnnouncements } from "./useRunLifecycleAnnouncements";
import { DiffCard, shouldShowDiffCard } from "./cards/DiffCard";
import { FixCard, shouldShowFixCard } from "./cards/FixCard";
+import { ReviewGateCard, getReviewGateVerdict } from "./cards/ReviewGateCard";
import {
CopilotBlockActionsEvent,
EMPTY_NARRATIVE,
@@ -327,6 +328,20 @@ const findLastTurnIndex = (messages: ChatMessage[]): number => {
return -1;
};
+// Locates the message owning a bypassed pending proposal so its gate keeps
+// rendering actionable controls even after later turns push it up the thread.
+const findLastIndexOfTurn = (
+ messages: ChatMessage[],
+ turnId: string,
+): number => {
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ if (messages[index]?.narrative?.turnId === turnId) {
+ return index;
+ }
+ }
+ return -1;
+};
+
type QueuedPrompt = {
id: string;
content: string;
@@ -592,11 +607,24 @@ export function WorkflowCopilotChat({
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [proposedWorkflow, setProposedWorkflow] =
useState<WorkflowApiResponse | null>(null);
+ // Owning turn of the current proposedWorkflow. Kept alongside it (never
+ // merged into one object) so the gate can re-attach to its owning message.
+ const [pendingProposalTurnId, setPendingProposalTurnId] = useState<
+ string | null
+ >(null);
+ // Transient ring highlight on the gate the pending-proposal chip just
+ // scrolled to; cleared after the flash window.
+ const [gateFlashTurnId, setGateFlashTurnId] = useState<string | null>(null);
// Turn IDs the user explicitly rejected. This is client-local because reject
// only reverts the local canvas; the backend proposalDisposition stays fixed.
const [rejectedTurnIds, setRejectedTurnIds] = useState<Set<string>>(
new Set(),
);
+ // Mirror of rejectedTurnIds for manual Accept, session-local (no server
+ // record of a non-auto-applied accept).
+ const [acceptedTurnIds, setAcceptedTurnIds] = useState<Set<string>>(
+ new Set(),
+ );
const [autoAccept, setAutoAccept] = useState<boolean>(false);
const [inputValue, setInputValue] = useState("");
const dismissPasteSkillHint = usePasteSkillHintStore((s) => s.dismiss);
@@ -632,6 +660,7 @@ export function WorkflowCopilotChat({
const pendingMessageId = useRef<string | null>(null);
const pendingCancelToken = useRef<string | null>(null);
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
// the cancel POST and the watcher firing, so the frontend must remember it.
const cancelInFlightController = useRef<AbortController | null>(null);
@@ -662,6 +691,10 @@ export function WorkflowCopilotChat({
clearTimeout(cancelSafetyTimer.current);
cancelSafetyTimer.current = null;
}
+ if (gateFlashTimer.current !== null) {
+ clearTimeout(gateFlashTimer.current);
+ gateFlashTimer.current = null;
+ }
};
}, []);
const [size, setSize] = useState({
@@ -880,8 +913,10 @@ export function WorkflowCopilotChat({
updateQueuedPrompt(null);
setWorkflowCopilotChatId(null);
setProposedWorkflow(null);
+ setPendingProposalTurnId(null);
setAutoAccept(false);
setRejectedTurnIds(new Set());
+ setAcceptedTurnIds(new Set());
setNarrative(EMPTY_NARRATIVE);
turnSnapshots.current.clear();
pendingSubmitSnapshot.current = null;
@@ -917,10 +952,10 @@ export function WorkflowCopilotChat({
return hydrated;
})(),
}));
- const pendingProposalTurnId = data.proposed_workflow
+ const restoredPendingProposalTurnId = data.proposed_workflow
? getLatestDiffCardTurnId(historyMessages)
: null;
- latestTurnId.current = pendingProposalTurnId;
+ latestTurnId.current = restoredPendingProposalTurnId;
// History never carries run_lifecycle lines (local-only); carry them
// forward only for the mount-race caller, not an explicit chat switch.
setMessages((prev) => [
@@ -931,6 +966,9 @@ export function WorkflowCopilotChat({
]);
setWorkflowCopilotChatId(data.workflow_copilot_chat_id);
setProposedWorkflow(data.proposed_workflow ?? null);
+ setPendingProposalTurnId(
+ data.proposed_workflow ? restoredPendingProposalTurnId : null,
+ );
setAutoAccept(data.auto_accept ?? false);
},
// Only stable state setters are referenced, so the callback never needs to change.
@@ -943,6 +981,7 @@ export function WorkflowCopilotChat({
setIsLoadingHistory(true);
updateQueuedPrompt(null);
setRejectedTurnIds(new Set());
+ setAcceptedTurnIds(new Set());
setNarrative(EMPTY_NARRATIVE);
turnSnapshots.current.clear();
pendingSubmitSnapshot.current = null;
@@ -1039,6 +1078,15 @@ export function WorkflowCopilotChat({
[onWorkflowUpdate],
);
+ // Records the accepted turn (for the "Applied changes" relabel) before
+ // clearing the pending-gate handle, shared by all three accept outcomes.
+ const markProposalAccepted = () => {
+ if (pendingProposalTurnId) {
+ setAcceptedTurnIds((prev) => new Set(prev).add(pendingProposalTurnId));
+ }
+ setPendingProposalTurnId(null);
+ };
+
const handleAcceptWorkflow = async (
workflow: WorkflowApiResponse,
alwaysAccept: boolean = false,
@@ -1060,6 +1108,7 @@ export function WorkflowCopilotChat({
if (!applyWorkflowUpdate(workflow, { applied: true })) {
return;
}
+ markProposalAccepted();
setProposedWorkflow(null);
if (alwaysAccept) {
setAutoAccept(true);
@@ -1083,6 +1132,7 @@ export function WorkflowCopilotChat({
) {
return;
}
+ markProposalAccepted();
setProposedWorkflow(null);
if (alwaysAccept) {
setAutoAccept(true);
@@ -1104,6 +1154,7 @@ export function WorkflowCopilotChat({
});
return;
}
+ markProposalAccepted();
setProposedWorkflow(null);
if (alwaysAccept) {
setAutoAccept(true);
@@ -1116,7 +1167,10 @@ export function WorkflowCopilotChat({
// The staged proposal was rendered onto the canvas mid-turn (via
// WORKFLOW_DRAFT). Reject must revert the canvas to the pre-submit
// canvas state captured client-side at submit time.
- const turnId = latestTurnId.current ?? getLatestDiffCardTurnId(messages);
+ const turnId =
+ pendingProposalTurnId ??
+ latestTurnId.current ??
+ getLatestDiffCardTurnId(messages);
const entry = turnId ? turnSnapshots.current.get(turnId) : null;
if (entry?.snapshot) {
applyWorkflowUpdate(entry.snapshot);
@@ -1125,6 +1179,7 @@ export function WorkflowCopilotChat({
setRejectedTurnIds((prev) => new Set(prev).add(turnId));
}
setProposedWorkflow(null);
+ setPendingProposalTurnId(null);
void clearProposedWorkflow(false);
};
@@ -1180,6 +1235,32 @@ export function WorkflowCopilotChat({
[credentialGetter, workflowPermanentId],
);
+ // A follow-up turn that ends without a new draft no longer nulls a bypassed
+ // proposal client-side (flag-on); re-fetch the chat row instead, since the
+ // backend (keep_pending_proposal) may have kept it alive server-side.
+ // useCallback-stable: handleSend depends on it and is itself a dependency
+ // of other effects, so a churning identity here would cascade into them.
+ const resyncProposalFromChatRow = useCallback(async (): Promise<void> => {
+ const chatId = workflowCopilotChatIdRef.current?.trim();
+ if (!chatId) {
+ return;
+ }
+ try {
+ const client = await getClient(credentialGetter, "sans-api-v1");
+ const response = await client.get<WorkflowCopilotChatHistoryResponse>(
+ "/workflow/copilot/chat-history",
+ { params: { workflow_copilot_chat_id: chatId } },
+ );
+ const nextProposal = response.data.proposed_workflow ?? null;
+ setProposedWorkflow(nextProposal);
+ if (!nextProposal) {
+ setPendingProposalTurnId(null);
+ }
+ } catch (error) {
+ console.error("Failed to resync pending proposal:", error);
+ }
+ }, [credentialGetter]);
+
const clearProposedWorkflow = async (autoAcceptValue: boolean) => {
const clearProposalByChatId = async (chatId: string) => {
const client = await getClient(credentialGetter, "sans-api-v1");
@@ -1236,7 +1317,10 @@ export function WorkflowCopilotChat({
};
const handleReviewWorkflow = (workflow: WorkflowApiResponse) => {
- onReviewWorkflow?.(workflow, () => setProposedWorkflow(null));
+ onReviewWorkflow?.(workflow, () => {
+ setProposedWorkflow(null);
+ setPendingProposalTurnId(null);
+ });
};
useEffect(() => {
@@ -1251,6 +1335,7 @@ export function WorkflowCopilotChat({
updateQueuedPrompt(null);
setWorkflowCopilotChatId(null);
setProposedWorkflow(null);
+ setPendingProposalTurnId(null);
setAutoAccept(false);
setNarrative(EMPTY_NARRATIVE);
historyLoadedForRef.current = null;
@@ -1457,7 +1542,10 @@ export function WorkflowCopilotChat({
{ id: queuedId, sender: "user", content: candidate },
]);
}
- setProposedWorkflow(null);
+ if (!copilotUxV1Enabled) {
+ setProposedWorkflow(null);
+ setPendingProposalTurnId(null);
+ }
if (messageOverride === undefined) {
setInputValue("");
}
@@ -1493,7 +1581,10 @@ export function WorkflowCopilotChat({
if (!options.queuedMessageId) {
setMessages((prev) => [...prev, userMessage]);
}
- setProposedWorkflow(null);
+ if (!copilotUxV1Enabled) {
+ setProposedWorkflow(null);
+ setPendingProposalTurnId(null);
+ }
const messageContent = candidate;
if (messageOverride === undefined && !options.queuedMessageId) {
setInputValue("");
@@ -1688,8 +1779,14 @@ export function WorkflowCopilotChat({
)
) {
applyWorkflowUpdate(response.updated_workflow, { applied: true });
+ // This turn's auto-commit already moved canonical past any earlier
+ // bypassed proposal — drop the stale handle so its gate cannot
+ // reapply an outdated draft over what was just committed.
+ setProposedWorkflow(null);
+ setPendingProposalTurnId(null);
} else if (response.updated_workflow) {
setProposedWorkflow(response.updated_workflow);
+ setPendingProposalTurnId(responseTurnId);
} else if (
// Cancel/error terminal on a turn that produced staged content →
// snap canvas back to the pre-submit client snapshot.
@@ -1699,11 +1796,18 @@ export function WorkflowCopilotChat({
) {
applyWorkflowUpdate(responseEntry.snapshot);
setProposedWorkflow(null);
+ setPendingProposalTurnId(null);
+ } else if (copilotUxV1Enabled && pendingProposalTurnId) {
+ // No new draft this turn, but a bypassed proposal is still
+ // pending: re-fetch instead of nulling, since the backend (given
+ // keep_pending_proposal) may have kept it alive for a late Accept.
+ void resyncProposalFromChatRow();
} else {
// Informational reply OR proposal pending review. For
// proposals, the Accept/Reject card is the user's next gate;
// canvas keeps the staged content until the user acts.
setProposedWorkflow(response.updated_workflow ?? null);
+ setPendingProposalTurnId(null);
}
};
@@ -1734,6 +1838,7 @@ export function WorkflowCopilotChat({
if (errorEntry?.hadStagedDraft && errorEntry?.snapshot) {
applyWorkflowUpdate(errorEntry.snapshot);
setProposedWorkflow(null);
+ setPendingProposalTurnId(null);
}
};
@@ -1764,6 +1869,8 @@ export function WorkflowCopilotChat({
cancel_token: cancelToken,
target_block_label: targetBlockLabel,
fix_origin: fixOrigin,
+ keep_pending_proposal:
+ copilotUxV1Enabled && Boolean(pendingProposalTurnId),
} as WorkflowCopilotChatRequest,
(payload) => {
switch (payload.type) {
@@ -1877,6 +1984,7 @@ export function WorkflowCopilotChat({
codeBlockModeEnabled,
codeBlockRequestOverride,
composerMode,
+ copilotUxV1Enabled,
copilotV2Enabled,
credentialGetter,
getSaveData,
@@ -1886,7 +1994,9 @@ export function WorkflowCopilotChat({
isLiveBrowserReady,
liveBrowserSessionId,
maybeFetchRecordedActions,
+ pendingProposalTurnId,
requiresLiveBrowser,
+ resyncProposalFromChatRow,
stopSpeech,
takeSpeechAudioBlob,
updateQueuedPrompt,
@@ -2280,6 +2390,15 @@ export function WorkflowCopilotChat({
: "Listening…"
: browserStatusText;
const lastTurnIndex = findLastTurnIndex(messages);
+ // A bypassed proposal's gate stays attached to its owning turn (not
+ // necessarily the last message) so a chip can jump back to it.
+ const gateOwnerIndex = pendingProposalTurnId
+ ? findLastIndexOfTurn(messages, pendingProposalTurnId)
+ : -1;
+ const gateIndex = gateOwnerIndex >= 0 ? gateOwnerIndex : lastTurnIndex;
+ // Mid-turn Accept would be clobbered by the in-flight turn's terminal
+ // restore, so gate actions wait for idle.
+ const gateActionable = Boolean(proposedWorkflow) && !isLoading;
const content = (
<div
@@ -2402,8 +2521,13 @@ export function WorkflowCopilotChat({
// subsequent turns. The Accept/Reject controls render only on
// the latest message AND while the proposal is pending review.
if (message.sender === "ai" && message.narrative) {
+ const turnId = message.narrative.turnId;
const showProposalActions =
isLastMessage && Boolean(proposedWorkflow);
+ const showReviewGate =
+ copilotUxV1Enabled &&
+ (shouldShowDiffCard(message.narrative) ||
+ (turnId !== null && turnId === pendingProposalTurnId));
return (
<div
key={message.id}
@@ -2414,50 +2538,93 @@ export function WorkflowCopilotChat({
<NarrativeView
turn={message.narrative}
onBlockSelect={onBlockSelect}
+ uxV1={copilotUxV1Enabled}
/>
- {showProposalActions && proposedWorkflow ? (
- <div className="flex flex-wrap gap-2 pl-1">
- <button
- type="button"
- onClick={() => handleReviewWorkflow(proposedWorkflow)}
- className="rounded border border-cta/60 bg-cta/10 px-3 py-1 text-xs text-foreground hover:bg-cta/20"
- >
- Review
- </button>
- <button
- type="button"
- onClick={() => handleAcceptWorkflow(proposedWorkflow)}
- className="rounded bg-success px-3 py-1 text-xs text-success-foreground hover:bg-success/90"
- >
- Accept
- </button>
- <button
- type="button"
- onClick={() =>
- handleAcceptWorkflow(proposedWorkflow, true)
- }
- className="rounded bg-success px-3 py-1 text-xs text-success-foreground hover:bg-success/80"
- >
- Always accept
- </button>
- <button
- type="button"
- onClick={handleRejectWorkflow}
- className="rounded bg-destructive px-3 py-1 text-xs text-destructive-foreground hover:bg-destructive/90"
- >
- Reject
- </button>
- </div>
- ) : null}
- {docked && shouldShowDiffCard(message.narrative) ? (
- <DiffCard
- pendingProposal={showProposalActions}
- rejected={
- message.narrative.turnId !== null &&
- rejectedTurnIds.has(message.narrative.turnId)
- }
+ {showReviewGate ? (
+ <ReviewGateCard
turn={message.narrative}
+ pending={
+ index === gateIndex && Boolean(proposedWorkflow)
+ }
+ verdict={getReviewGateVerdict(
+ message.narrative,
+ proposedWorkflow,
+ )}
+ settled={
+ turnId && acceptedTurnIds.has(turnId)
+ ? "accepted"
+ : turnId && rejectedTurnIds.has(turnId)
+ ? "rejected"
+ : null
+ }
+ actionsEnabled={gateActionable}
+ onAccept={() =>
+ proposedWorkflow &&
+ handleAcceptWorkflow(proposedWorkflow)
+ }
+ onAlwaysAccept={() =>
+ proposedWorkflow &&
+ handleAcceptWorkflow(proposedWorkflow, true)
+ }
+ onReject={handleRejectWorkflow}
+ onReview={() =>
+ proposedWorkflow &&
+ handleReviewWorkflow(proposedWorkflow)
+ }
+ gateId={turnId ? `copilot-gate-${turnId}` : undefined}
+ flash={turnId !== null && turnId === gateFlashTurnId}
/>
+ ) : !copilotUxV1Enabled ? (
+ <>
+ {showProposalActions && proposedWorkflow ? (
+ <div className="flex flex-wrap gap-2 pl-1">
+ <button
+ type="button"
+ onClick={() =>
+ handleReviewWorkflow(proposedWorkflow)
+ }
+ className="rounded border border-cta/60 bg-cta/10 px-3 py-1 text-xs text-foreground hover:bg-cta/20"
+ >
+ Review
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ handleAcceptWorkflow(proposedWorkflow)
+ }
+ className="rounded bg-success px-3 py-1 text-xs text-success-foreground hover:bg-success/90"
+ >
+ Accept
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ handleAcceptWorkflow(proposedWorkflow, true)
+ }
+ className="rounded bg-success px-3 py-1 text-xs text-success-foreground hover:bg-success/80"
+ >
+ Always accept
+ </button>
+ <button
+ type="button"
+ onClick={handleRejectWorkflow}
+ className="rounded bg-destructive px-3 py-1 text-xs text-destructive-foreground hover:bg-destructive/90"
+ >
+ Reject
+ </button>
+ </div>
+ ) : null}
+ {docked && shouldShowDiffCard(message.narrative) ? (
+ <DiffCard
+ pendingProposal={showProposalActions}
+ rejected={
+ message.narrative.turnId !== null &&
+ rejectedTurnIds.has(message.narrative.turnId)
+ }
+ turn={message.narrative}
+ />
+ ) : null}
+ </>
) : null}
{docked &&
isLastMessage &&
@@ -2475,6 +2642,8 @@ export function WorkflowCopilotChat({
);
}
const showProposedPanel = isLastMessage && proposedWorkflow;
+ const isGateOwnerOrLast =
+ index === gateIndex && Boolean(proposedWorkflow);
return (
<MessageItem
key={message.id}
@@ -2485,7 +2654,30 @@ export function WorkflowCopilotChat({
<ReloadIcon className="h-3 w-3 animate-spin" />
<span>{queuedPromptWaitingStatus}</span>
</div>
- ) : showProposedPanel ? (
+ ) : copilotUxV1Enabled && isGateOwnerOrLast ? (
+ <ReviewGateCard
+ pending
+ verdict={getReviewGateVerdict(
+ undefined,
+ proposedWorkflow,
+ )}
+ settled={null}
+ actionsEnabled={gateActionable}
+ onAccept={() =>
+ proposedWorkflow &&
+ handleAcceptWorkflow(proposedWorkflow)
+ }
+ onAlwaysAccept={() =>
+ proposedWorkflow &&
+ handleAcceptWorkflow(proposedWorkflow, true)
+ }
+ onReject={handleRejectWorkflow}
+ onReview={() =>
+ proposedWorkflow &&
+ handleReviewWorkflow(proposedWorkflow)
+ }
+ />
+ ) : !copilotUxV1Enabled && showProposedPanel ? (
<>
<button
type="button"
@@ -2534,7 +2726,11 @@ export function WorkflowCopilotChat({
role="status"
aria-live="polite"
>
- <NarrativeView turn={narrative} onBlockSelect={onBlockSelect} />
+ <NarrativeView
+ turn={narrative}
+ onBlockSelect={onBlockSelect}
+ uxV1={copilotUxV1Enabled}
+ />
</div>
)}
</div>
@@ -2553,6 +2749,32 @@ export function WorkflowCopilotChat({
{/* Input */}
<div className="border-t border-border p-3">
+ {copilotUxV1Enabled &&
+ proposedWorkflow &&
+ pendingProposalTurnId &&
+ (gateOwnerIndex !== lastTurnIndex || isLoading) ? (
+ <button
+ type="button"
+ onClick={() => {
+ if (!pendingProposalTurnId) return;
+ document
+ .getElementById(`copilot-gate-${pendingProposalTurnId}`)
+ ?.scrollIntoView({ behavior: "smooth", block: "center" });
+ if (gateFlashTimer.current !== null) {
+ clearTimeout(gateFlashTimer.current);
+ }
+ setGateFlashTurnId(pendingProposalTurnId);
+ gateFlashTimer.current = setTimeout(() => {
+ setGateFlashTurnId(null);
+ gateFlashTimer.current = null;
+ }, 1100);
+ }}
+ className="mb-2 flex items-center gap-1.5 rounded-full border border-border px-2.5 py-1 text-[10.5px] text-muted-foreground hover:bg-slate-elevation3"
+ >
+ <span className="h-1.5 w-1.5 rounded-full bg-sky-400" />1 proposal
+ pending · Review
+ </button>
+ ) : null}
{inputStatusText ? (
<div
className="mb-2 text-xs text-muted-foreground"
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/DiffCard.test.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/DiffCard.test.ts
index 4d3934775..d6075cb96 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/DiffCard.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/DiffCard.test.ts
@@ -79,4 +79,28 @@ describe("getDiffCardTitle", () => {
),
).toBe("Added browser step");
});
+
+ it("labels a manually accepted review_tested draft as applied changes", () => {
+ expect(
+ getDiffCardTitle(turn({ proposalDisposition: "review_tested" }), {
+ accepted: true,
+ }),
+ ).toBe("Applied changes");
+ });
+
+ it("still lets a backend-supplied summary win over accepted", () => {
+ expect(
+ getDiffCardTitle(
+ turn({
+ proposalDisposition: "review_tested",
+ draft: {
+ blockCount: 1,
+ blockLabels: ["block_1"],
+ summary: "Added browser step",
+ },
+ }),
+ { accepted: true },
+ ),
+ ).toBe("Added browser step");
+ });
});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.ts
new file mode 100644
index 000000000..7c2c5c97a
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+
+import { EMPTY_NARRATIVE, type TurnNarrativeState } from "../narrativeState";
+import { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";
+import { getReviewGateVerdict } from "./ReviewGateCard";
+
+const turn = (
+ overrides: Partial<TurnNarrativeState> = {},
+): TurnNarrativeState => ({
+ ...EMPTY_NARRATIVE,
+ turnId: "turn-1",
+ turnIndex: 0,
+ mode: "build",
+ designStarted: true,
+ designEnded: true,
+ draft: {
+ blockCount: 1,
+ blockLabels: ["block_1"],
+ summary: null,
+ },
+ proposalDisposition: "review_untested",
+ terminal: "response",
+ ...overrides,
+});
+
+describe("getReviewGateVerdict", () => {
+ it("treats review_tested as tested", () => {
+ expect(
+ getReviewGateVerdict(
+ turn({ proposalDisposition: "review_tested" }),
+ null,
+ ),
+ ).toBe("tested");
+ });
+
+ it("treats auto_applicable as tested — the backend only assigns this disposition to verified changes", () => {
+ expect(
+ getReviewGateVerdict(
+ turn({ proposalDisposition: "auto_applicable" }),
+ null,
+ ),
+ ).toBe("tested");
+ });
+
+ it("treats review_untested as untested", () => {
+ expect(
+ getReviewGateVerdict(
+ turn({ proposalDisposition: "review_untested" }),
+ null,
+ ),
+ ).toBe("untested");
+ });
+
+ it("falls back to the legacy _copilot_unvalidated marker when the turn has no disposition", () => {
+ const legacyProposal = {
+ _copilot_unvalidated: true,
+ } as unknown as WorkflowApiResponse;
+ expect(
+ getReviewGateVerdict(turn({ proposalDisposition: null }), legacyProposal),
+ ).toBe("untested");
+ });
+
+ it("falls back to tested for a legacy proposal without the unvalidated marker", () => {
+ const legacyProposal = {} as unknown as WorkflowApiResponse;
+ expect(
+ getReviewGateVerdict(turn({ proposalDisposition: null }), legacyProposal),
+ ).toBe("tested");
+ });
+
+ it("returns null with no disposition and no proposal", () => {
+ expect(
+ getReviewGateVerdict(turn({ proposalDisposition: null }), null),
+ ).toBe(null);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
new file mode 100644
index 000000000..6e14dac87
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
@@ -0,0 +1,197 @@
+import { MagicWandIcon } from "@radix-ui/react-icons";
+
+import { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";
+
+import { TurnNarrativeState } from "../narrativeState";
+import { getDiffCardTitle } from "./diffCardTitle";
+
+export type ReviewGateVerdict = "tested" | "untested" | null;
+export type ReviewGateSettled = "accepted" | "rejected" | null;
+
+// The backend stashes this marker on chat.proposed_workflow only for
+// review_untested proposals; it's absent from the typed WorkflowApiResponse
+// shape because it never round-trips through a real workflow save.
+type LegacyProposedWorkflow = WorkflowApiResponse & {
+ _copilot_unvalidated?: boolean;
+};
+
+// eslint-disable-next-line react-refresh/only-export-components
+export function getReviewGateVerdict(
+ turn: TurnNarrativeState | undefined,
+ proposedWorkflow: WorkflowApiResponse | null,
+): ReviewGateVerdict {
+ if (
+ turn?.proposalDisposition === "review_tested" ||
+ turn?.proposalDisposition === "auto_applicable"
+ ) {
+ return "tested";
+ }
+ if (turn?.proposalDisposition) {
+ return "untested";
+ }
+ if (!proposedWorkflow) {
+ return null;
+ }
+ const legacy = proposedWorkflow as LegacyProposedWorkflow;
+ return legacy._copilot_unvalidated ? "untested" : "tested";
+}
+
+const VERDICT_PILL_CLASSES: Record<"tested" | "untested", string> = {
+ tested: "border-emerald-500/30 bg-emerald-500/15 text-emerald-300",
+ untested: "border-sky-500/30 bg-sky-500/15 text-sky-300",
+};
+
+const VERDICT_PILL_LABELS: Record<"tested" | "untested", string> = {
+ tested: "Tested",
+ untested: "Untested",
+};
+
+interface ReviewGateCardProps {
+ turn?: TurnNarrativeState;
+ pending: boolean;
+ verdict: ReviewGateVerdict;
+ settled?: ReviewGateSettled;
+ actionsEnabled: boolean;
+ onAccept: () => void;
+ onAlwaysAccept: () => void;
+ onReject: () => void;
+ onReview: () => void;
+ gateId?: string;
+ // Transient highlight when the pending-proposal chip scrolls to this gate.
+ flash?: boolean;
+}
+
+export function ReviewGateCard({
+ turn,
+ pending,
+ verdict,
+ settled = null,
+ actionsEnabled,
+ onAccept,
+ onAlwaysAccept,
+ onReject,
+ onReview,
+ gateId,
+ flash = false,
+}: ReviewGateCardProps) {
+ const draft = turn?.draft ?? null;
+ const rejected = settled === "rejected";
+ const accepted = settled === "accepted";
+ const itemClassName = rejected
+ ? "ml-2 text-xs text-slate-500 line-through opacity-60"
+ : "ml-2 text-xs text-foreground";
+ const priorLabels = new Set(
+ (turn?.blocks ?? [])
+ .filter((block) => block.state === "drafted")
+ .map((block) => block.label),
+ );
+ const removed = draft
+ ? [...priorLabels].filter((label) => !draft.blockLabels.includes(label))
+ : [];
+ const title = turn
+ ? getDiffCardTitle(turn, { pendingProposal: pending, rejected, accepted })
+ : "Proposed changes";
+
+ return (
+ <div
+ id={gateId}
+ className={`overflow-hidden rounded-[10px] border border-border bg-slate-elevation2 ${
+ flash ? "ring-2 ring-sky-400/60 [transition:box-shadow_1.1s]" : ""
+ }`}
+ >
+ <div className="flex items-center gap-2 px-3 pt-3 text-xs font-semibold text-foreground">
+ <MagicWandIcon className="h-3.5 w-3.5" />
+ {title}
+ {pending && verdict ? (
+ <span
+ className={`ml-auto rounded-full border px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ${VERDICT_PILL_CLASSES[verdict]}`}
+ >
+ {VERDICT_PILL_LABELS[verdict]}
+ </span>
+ ) : null}
+ </div>
+ {draft ? (
+ <div className="px-3 pb-3">
+ {draft.blockLabels.length > 0 ? (
+ <div className="mt-2">
+ <div className="text-[10px] font-bold uppercase tracking-wide text-success">
+ Added
+ </div>
+ {draft.blockLabels.map((label) => (
+ <div key={label} className={itemClassName}>
+ + {label}
+ </div>
+ ))}
+ </div>
+ ) : null}
+ {removed.length > 0 ? (
+ <div className="mt-2">
+ <div className="text-[10px] font-bold uppercase tracking-wide text-destructive">
+ Removed
+ </div>
+ {removed.map((label) => (
+ <div key={label} className={itemClassName}>
+ - {label}
+ </div>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ {pending && actionsEnabled ? (
+ <div className="flex flex-wrap gap-2 border-t border-border/55 bg-slate-elevation1/55 px-3 py-2">
+ <button
+ type="button"
+ onClick={onReview}
+ className="rounded-md border border-border px-3 py-1.5 text-xs text-slate-200 hover:bg-slate-elevation4"
+ >
+ Review
+ </button>
+ <button
+ type="button"
+ onClick={onAccept}
+ className="rounded-md bg-success px-3 py-1.5 text-xs font-semibold text-success-foreground hover:opacity-90"
+ >
+ Accept
+ </button>
+ <button
+ type="button"
+ onClick={onAlwaysAccept}
+ className="rounded-md px-3 py-1.5 text-xs text-slate-400 hover:bg-slate-elevation4 hover:text-slate-200"
+ >
+ Always accept
+ </button>
+ <button
+ type="button"
+ onClick={onReject}
+ className="rounded-md px-3 py-1.5 text-xs text-red-300 hover:bg-red-500/10 hover:text-red-400"
+ >
+ Reject
+ </button>
+ </div>
+ ) : null}
+ {settled ? (
+ <div
+ className={`flex items-center gap-2 border-l-2 px-3 py-2 text-xs ${
+ accepted
+ ? "border-l-success text-slate-200"
+ : "border-l-slate-600 text-slate-400"
+ }`}
+ >
+ <span
+ className={`flex h-[18px] w-[18px] shrink-0 items-center justify-center rounded text-[11px] ${
+ accepted
+ ? "bg-emerald-500/15 text-emerald-400"
+ : "bg-slate-elevation4 text-slate-400"
+ }`}
+ >
+ {accepted ? "✓" : "↺"}
+ </span>
+ {accepted
+ ? "Accepted — saved as a new workflow version"
+ : "Discarded — canvas reverted to the previous version"}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/diffCardTitle.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/diffCardTitle.ts
index 80c98e91b..0763fdc3b 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/diffCardTitle.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/diffCardTitle.ts
@@ -3,17 +3,26 @@ import { TurnNarrativeState } from "../narrativeState";
type DiffCardTitleOptions = {
pendingProposal?: boolean;
rejected?: boolean;
+ accepted?: boolean;
};
export function getDiffCardTitle(
turn: TurnNarrativeState,
- { pendingProposal = false, rejected = false }: DiffCardTitleOptions = {},
+ {
+ pendingProposal = false,
+ rejected = false,
+ accepted = false,
+ }: DiffCardTitleOptions = {},
): string {
const summary = turn.draft?.summary?.trim();
if (summary) {
return summary;
}
+ if (accepted) {
+ return "Applied changes";
+ }
+
// "Applied changes" requires the backend's explicit auto-applied signal.
// Everything else - pending review, a rejected auto-applicable draft, or a
// null/unknown disposition from a forward-compatible backend - defaults to
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index d6dbe814c..10738d7e5 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -932,8 +932,17 @@ function adjudicatedSummaryParts(
hasDrafts: boolean;
hasCleanCompletedBuild: boolean;
},
+ uxV1 = false,
): AdjudicatedParts | null {
if (turn.responseKind === null) return null;
+ // Disposition-first (rule A): a pending draft review outranks why the turn
+ // ended, regardless of responseKind (including non-build/clarify turns).
+ if (uxV1 && flags.needsUntestedProposalReview) {
+ return { headline: "Draft needs review", accent: "qa", glyph: "!" };
+ }
+ if (uxV1 && flags.needsTestedProposalReview) {
+ return { headline: "Workflow ready for review", accent: "qa", glyph: "!" };
+ }
if (turn.responseKind !== "build") {
return {
headline:
@@ -941,7 +950,9 @@ function adjudicatedSummaryParts(
? "Declined"
: turn.responseKind === "diagnose"
? "Answered"
- : "Question",
+ : uxV1
+ ? "Needs your input"
+ : "Question",
accent: "qa",
glyph: "✦",
};
@@ -982,7 +993,11 @@ function adjudicatedSummaryParts(
return { headline: "Completed the run", accent: "ok", glyph: "✓" };
}
-export function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {
+export function computeTurnSummary(
+ turn: TurnNarrativeState,
+ opts: { uxV1?: boolean } = {},
+): TurnSummary {
+ const uxV1 = opts.uxV1 ?? false;
const rollupBlocks = latestBlocksByLabel(turn.blocks);
const isFail =
turn.terminal === "error" || rollupBlocks.some((b) => b.state === "failed");
@@ -1014,13 +1029,17 @@ export function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {
const adjudicated =
isStoppedWithDraft || isFail
? null
- : adjudicatedSummaryParts(turn, {
- needsUntestedProposalReview,
- needsTestedProposalReview,
- hasEdited,
- hasDrafts,
- hasCleanCompletedBuild,
- });
+ : adjudicatedSummaryParts(
+ turn,
+ {
+ needsUntestedProposalReview,
+ needsTestedProposalReview,
+ hasEdited,
+ hasDrafts,
+ hasCleanCompletedBuild,
+ },
+ uxV1,
+ );
const headline = adjudicated
? adjudicated.headline
@@ -1028,23 +1047,41 @@ export function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {
? "Stopped with a draft"
: isFail
? "Run halted"
- : needsInput
- ? "Question"
- : needsUntestedProposalReview
+ : uxV1
+ ? needsUntestedProposalReview
? "Draft needs review"
: needsTestedProposalReview
? "Workflow ready for review"
- : isQA
- ? mode === "refuse"
- ? "Declined"
- : mode === "clarify"
- ? "Question"
- : "Answered"
- : hasEdited
- ? "Applied edits and re-tested"
- : hasDrafts
- ? "Built and tested the workflow"
- : "Completed the run";
+ : needsInput
+ ? "Needs your input"
+ : isQA
+ ? mode === "refuse"
+ ? "Declined"
+ : mode === "clarify"
+ ? "Needs your input"
+ : "Answered"
+ : hasEdited
+ ? "Applied edits and re-tested"
+ : hasDrafts
+ ? "Built and tested the workflow"
+ : "Completed the run"
+ : needsInput
+ ? "Question"
+ : needsUntestedProposalReview
+ ? "Draft needs review"
+ : needsTestedProposalReview
+ ? "Workflow ready for review"
+ : isQA
+ ? mode === "refuse"
+ ? "Declined"
+ : mode === "clarify"
+ ? "Question"
+ : "Answered"
+ : hasEdited
+ ? "Applied edits and re-tested"
+ : hasDrafts
+ ? "Built and tested the workflow"
+ : "Completed the run";
const stats: string[] = [];
const turnElapsed = formatElapsed(turn.startedAt, turn.endedAt);
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index 19b57a014..467fc0bd4 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -44,6 +44,7 @@ export interface WorkflowCopilotChatRequest {
cancel_token?: string;
target_block_label?: string | null;
fix_origin?: boolean;
+ keep_pending_proposal?: boolean;
}
export interface WorkflowCopilotCancelRequest {