Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Show unsaved workflow changes and change summaries in Studio (SKY-12442) (#7513)
Celal Zamanoğlu68d138fb0233
diff --git a/skyvern-frontend/src/routes/workflows/editor/FlowRenderer.tsx b/skyvern-frontend/src/routes/workflows/editor/FlowRenderer.tsxindex 8d35b96c4..c21ebcdd0 100644--- a/skyvern-frontend/src/routes/workflows/editor/FlowRenderer.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/FlowRenderer.tsx@@ -22,11 +22,13 @@ import {import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";import {commitYamlDraft,+ subscribeToYamlDraftChanges,useWorkflowYamlEditorStore,} from "@/store/WorkflowYamlEditorStore";import { useWorkflowParametersStore } from "@/store/WorkflowParametersStore";import { useWorkflowSettingsStore } from "@/store/WorkflowSettingsStore";import { useWorkflowTitleStore } from "@/store/WorkflowTitleStore";+import { useWorkflowSnapshotStore } from "@/store/WorkflowSnapshotStore";import { ReloadIcon } from "@radix-ui/react-icons";import {DndContext,@@ -140,6 +142,8 @@ import {upgradeWorkflowDefinitionToVersionTwo,getWorkflowErrors,} from "./workflowEditorUtils";+import { summarizeWorkflowChanges } from "./workflowChangesSummary";+import { WorkflowChangesList } from "./WorkflowChangesList";import {createDimensionConvergenceState,processDimensionChanges,@@ -199,6 +203,13 @@ import { duplicateBlockBelow } from "./workflowDuplicate";// only needs to cover synchronous mount-time effects.const INITIAL_LOAD_SETTLE_MS = 500;+// Max gap between a user gesture and the draft change it caused for that change+// to count as a user edit (vs. post-load materialization like login autofill).+// Biased large so a real edit is never misread as materialization; the cost is+// that an autofill landing within this window of a gesture can still read as a+// phantom (the broad autofill-on-mount case is tracked as a follow-up).+const USER_EDIT_GESTURE_WINDOW_MS = 250;+function convertToParametersYAML(parameters: ParametersState,): Array<@@ -743,6 +754,25 @@ function FlowRenderer({const blockerRef = useRef(blocker);blockerRef.current = blocker;+ // Studio-only: list what changed inside the leave/run unsaved-changes modal.+ // Memoized on the blocked state so it runs once when the modal opens (the+ // canvas is behind the modal and can't be edited). Legacy /edit keeps the+ // modal unchanged (embedded gate).+ const isNavBlocked = blocker.state === "blocked";+ const unsavedChangeSummary = useMemo(() => {+ if (!embedded || !isNavBlocked) {+ return [];+ }+ try {+ const saveData = useWorkflowHasChangesStore.getState().getSaveData();+ const snapshot = useWorkflowSnapshotStore.getState().snapshot;+ return saveData ? summarizeWorkflowChanges(saveData, snapshot) : [];+ } catch (error) {+ console.error("Failed to summarize workflow changes", error);+ return [];+ }+ }, [embedded, isNavBlocked]);+const doLayout = useCallback((nodes: Array<AppNode>, edges: Array<Edge>) => {const layoutedElements = layout(nodes, edges, targettedBlockLabel);@@ -973,6 +1003,102 @@ function FlowRenderer({};}, [nodes, edges, parameters, title, workflow]);+ // Studio unsaved-changes baseline: freeze a clean snapshot at the+ // first user interaction after a load/save, so post-load canvas+ // materialization (e.g. a login-block credential autofill, which flips+ // hasChanges without a user gesture) is absorbed into the baseline instead of+ // reading as a user edit. Clear it when the workflow returns to clean, and+ // keep the dot's contentDirty flag in sync with the draft. Studio-only.+ const hasChangesFlag = workflowChangesStore.hasChanges;+ useEffect(() => {+ if (!embedded || readOnly || hasChangesFlag) {+ return;+ }+ useWorkflowSnapshotStore.getState().clearSnapshot();+ }, [embedded, readOnly, hasChangesFlag]);++ // Timestamp of the last discrete user gesture. The dirtiness effect below uses+ // it to tell a user edit (change lands within a gesture window) from post-load+ // materialization (a change with no preceding gesture), so autofill after an+ // early interaction is absorbed into the baseline rather than shown as an edit.+ const lastUserGestureAtRef = useRef(0);+ // A held pointer means a drag may be in progress: the graph re-serializes per+ // frame but its content can't change until the drop, so the dirtiness effect+ // skips the per-frame diff while this is set (it settles at pointerup).+ const pointerDownRef = useRef(false);+ useEffect(() => {+ if (!embedded || readOnly) {+ return;+ }+ const captureBaseline = () => {+ if (useWorkflowSnapshotStore.getState().snapshot === null) {+ useWorkflowSnapshotStore.getState().captureSnapshot();+ }+ };+ const markGesture = () => {+ lastUserGestureAtRef.current = Date.now();+ };+ const onPointerDown = () => {+ pointerDownRef.current = true;+ markGesture();+ captureBaseline();+ };+ const onPointerUp = () => {+ pointerDownRef.current = false;+ markGesture();+ };+ const onKeyDown = () => {+ markGesture();+ captureBaseline();+ };+ document.addEventListener("pointerdown", onPointerDown, true);+ document.addEventListener("pointerup", onPointerUp, true);+ document.addEventListener("pointercancel", onPointerUp, true);+ document.addEventListener("keydown", onKeyDown, true);+ return () => {+ document.removeEventListener("pointerdown", onPointerDown, true);+ document.removeEventListener("pointerup", onPointerUp, true);+ document.removeEventListener("pointercancel", onPointerUp, true);+ document.removeEventListener("keydown", onKeyDown, true);+ };+ }, [embedded, readOnly]);++ // Debounced for user edits: constructSaveData changes per-frame during a node+ // drag, and recomputing dirtiness serializes the whole graph — coalesce to+ // once the draft settles (the dot updating a moment late is imperceptible).+ const scheduleUserDirtyRefresh = useDebouncedCallback(() => {+ useWorkflowSnapshotStore.getState().noteDraftChange(true);+ }, 200);+ useEffect(() => {+ if (!embedded || readOnly) {+ return;+ }+ const userDriven =+ Date.now() - lastUserGestureAtRef.current <= USER_EDIT_GESTURE_WINDOW_MS;+ if (userDriven) {+ scheduleUserDirtyRefresh();+ } else if (!pointerDownRef.current) {+ // Post-load materialization (e.g. login autofill) is a one-off — resolve+ // it promptly so the baseline absorbs it before the dot or the summary can+ // flash a phantom edit. Skipped while a pointer is held so a long node+ // drag doesn't re-serialize the whole graph every frame; a drag settles at+ // pointerup, where the drop's constructSaveData change re-runs this.+ useWorkflowSnapshotStore.getState().noteDraftChange(false);+ }+ }, [embedded, readOnly, constructSaveData, scheduleUserDirtyRefresh]);+ // A Code-editor edit changes only the YAML draft, so constructSaveData is+ // unchanged and the effect above never fires for it. The editor's keystrokes+ // also don't reach the canvas gesture window that effect classifies on, and+ // the draft only ever changes via user typing — so refresh as a user edit+ // directly. Routing through that classification would read the edit as+ // materialization and absorb it into the baseline, leaving the dot dark.+ useEffect(() => {+ if (!embedded || readOnly) {+ return;+ }+ return subscribeToYamlDraftChanges(scheduleUserDirtyRefresh);+ }, [embedded, readOnly, scheduleUserDirtyRefresh]);+useEffect(() => {if (readOnly) {// Comparison canvases mount FlowRenderer twice and must not stomp the@@ -2054,6 +2180,7 @@ function FlowRenderer({before leaving?</DialogDescription></DialogHeader>+ <WorkflowChangesList changes={unsavedChangeSummary} /><DialogFooter><Buttonvariant="secondary"diff --git a/skyvern-frontend/src/routes/workflows/editor/WorkflowChangesList.tsx b/skyvern-frontend/src/routes/workflows/editor/WorkflowChangesList.tsxnew file mode 100644index 000000000..b00b004fc--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/WorkflowChangesList.tsx@@ -0,0 +1,30 @@+import { cn } from "@/util/utils";++function WorkflowChangesList({+ changes,+ className,+}: {+ changes: Array<string>;+ className?: string;+}) {+ if (changes.length === 0) {+ return null;+ }+ return (+ <ul+ className={cn(+ "max-h-48 space-y-1.5 overflow-y-auto rounded-md border border-border bg-slate-elevation3 p-3 text-sm text-foreground",+ className,+ )}+ >+ {changes.map((change, index) => (+ <li key={index} className="flex gap-2">+ <span className="select-none text-muted-foreground">•</span>+ <span className="min-w-0 break-words">{change}</span>+ </li>+ ))}+ </ul>+ );+}++export { WorkflowChangesList };diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsxindex a5fbefd57..79e9712ee 100644--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx@@ -110,6 +110,7 @@ import {type WorkflowSaveData,} from "@/store/WorkflowHasChangesStore";import { useWorkflowParametersStore } from "@/store/WorkflowParametersStore";+import { useWorkflowSnapshotStore } from "@/store/WorkflowSnapshotStore";import { useWorkflowTitleStore } from "@/store/WorkflowTitleStore";import { getCode, getOrderedBlockLabels } from "@/routes/workflows/utils";import { copyText } from "@/util/copyText";@@ -945,6 +946,10 @@ function Workspace({useWorkflowPanelStore.getState().setSelectedBlockId(initialSelectedBlockId);useShowAllCodeStore.getState().reset();useSidebarSaveStateStore.getState().reset();+ // Drop A's unsaved-changes baseline on an A→B same-instance route swap;+ // a carried snapshot would diff B's graph against A's and surface phantom+ // "edited" lines. clearSnapshot resets contentDirty + userHasEdited too.+ useWorkflowSnapshotStore.getState().clearSnapshot();cacheKeyInitWpidRef.current = null;setReadyBrowserSessionId(null);if (workflowPermanentId) {@@ -1573,7 +1578,7 @@ function Workspace({const applyWorkflowUpdate = (workflowData: WorkflowVersion,- options?: { persisted?: boolean },+ options?: { persisted?: boolean; userDriven?: boolean },) => {const settings: WorkflowSettings = {proxyLocation: workflowData.proxy_location ?? ProxyLocation.Residential,@@ -1638,6 +1643,11 @@ function Workspace({}} else {workflowChangesStore.setHasChanges(true);+ if (options?.userDriven) {+ // A Copilot build has no canvas gesture but is user-driven; mark it so+ // the dot/summary surface it instead of the baseline absorbing it.+ useWorkflowSnapshotStore.getState().markUserEdit();+ }}};@@ -2949,7 +2959,7 @@ function Workspace({const handleCopilotReviewClose = (status: CopilotReviewStatus) => {if (status === "approve") {try {- applyWorkflowUpdate(pendingWorkflow);+ applyWorkflowUpdate(pendingWorkflow, { userDriven: true });} catch (error) {console.error("Failed to apply copilot agent",@@ -3012,7 +3022,10 @@ function Workspace({}}onWorkflowUpdate={(workflowData, options) => {try {- applyWorkflowUpdate(workflowData, options);+ // All Copilot-driven applies are user edits (mid-turn draft, accept,+ // snap-back); only version-restore/load call applyWorkflowUpdate+ // without this and stay a clean baseline.+ applyWorkflowUpdate(workflowData, { ...options, userDriven: true });const { fire, nextState } = shouldAutoOpenEditor(editorAutoOpenStateRef.current,{diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowChangesSummary.test.ts b/skyvern-frontend/src/routes/workflows/editor/workflowChangesSummary.test.tsnew file mode 100644index 000000000..82e47e4cb--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/workflowChangesSummary.test.ts@@ -0,0 +1,454 @@+import { afterEach, describe, expect, it } from "vitest";+import { stringify as toYaml } from "yaml";++import type { BlockYAML } from "@/routes/workflows/types/workflowYamlTypes";+import type { WorkflowSaveData } from "@/store/WorkflowHasChangesStore";+import { useWorkflowYamlEditorStore } from "@/store/WorkflowYamlEditorStore";++import {+ isDraftDirty,+ snapshotOf,+ summarizeBlockChanges,+ summarizeWorkflowChanges,+} from "./workflowChangesSummary";++const block = (label: string, extra: Record<string, unknown> = {}): BlockYAML =>+ ({ label, block_type: "task", ...extra }) as unknown as BlockYAML;++type SaveOver = {+ title?: string;+ blocks?: Array<BlockYAML>;+ parameters?: Array<+ Record<string, unknown> & { key: string; parameter_type: string }+ >;+ settings?: Record<string, unknown>;+};++const saveData = (over: SaveOver = {}): WorkflowSaveData =>+ ({+ title: over.title ?? "T",+ blocks: over.blocks ?? [],+ parameters: over.parameters ?? [],+ settings: over.settings ?? { proxyLocation: "RESIDENTIAL" },+ workflow: {+ title: "T",+ workflow_definition: { version: 2, blocks: [], parameters: [] },+ },+ }) as unknown as WorkflowSaveData;++describe("summarizeBlockChanges", () => {+ it("returns nothing when blocks are identical (no phantom edits)", () => {+ const blocks = [block("a", { url: "https://x" }), block("b")];+ expect(summarizeBlockChanges(blocks, blocks)).toEqual([]);+ });++ it("ignores cosmetic empty-value and key-order differences", () => {+ const baseline = [+ block("a", { url: "https://x", navigation_goal: null, data_schema: [] }),+ ];+ const draft = [block("a", { navigation_goal: "", url: "https://x" })];+ expect(summarizeBlockChanges(baseline, draft)).toEqual([]);+ });++ it("detects an added block with its type", () => {+ expect(+ summarizeBlockChanges(+ [block("a")],+ [block("a"), block("b", { block_type: "for_loop" })],+ ),+ ).toEqual([`Added for loop block "b"`]);+ });++ it("detects a removed block", () => {+ expect(+ summarizeBlockChanges([block("a"), block("b")], [block("a")]),+ ).toEqual([`Removed block "b"`]);+ });++ it("detects an edited block from a field change", () => {+ expect(+ summarizeBlockChanges(+ [block("a", { url: "https://x" })],+ [block("a", { url: "https://y" })],+ ),+ ).toEqual([`Edited block "a"`]);+ });++ it("detects a pure rename (same content, new label)", () => {+ expect(+ summarizeBlockChanges(+ [block("old", { url: "https://x" })],+ [block("new", { url: "https://x" })],+ ),+ ).toEqual([`Renamed block "old" to "new"`]);+ });++ it("keeps remove + add when a rename also changes content", () => {+ const out = summarizeBlockChanges(+ [block("old", { url: "https://x" })],+ [block("new", { url: "https://y" })],+ );+ expect(out).toContain(`Added task block "new"`);+ expect(out).toContain(`Removed block "old"`);+ expect(out).not.toContain(`Renamed block "old" to "new"`);+ });++ it("renames a loop container without flagging its unchanged children", () => {+ const loop = (label: string): BlockYAML =>+ ({+ label,+ block_type: "for_loop",+ loop_blocks: [block("child", { url: "https://x" })],+ }) as unknown as BlockYAML;+ // Renaming the container must not report its byte-identical child as+ // removed + added (the ancestor-label cascade bug).+ expect(summarizeBlockChanges([loop("loop1")], [loop("loop2")])).toEqual([+ `Renamed block "loop1" to "loop2"`,+ ]);+ });++ it("detects a rename of a nested loop child", () => {+ const loop = (childLabel: string): BlockYAML =>+ ({+ label: "loop",+ block_type: "for_loop",+ loop_blocks: [block(childLabel, { url: "https://x" })],+ }) as unknown as BlockYAML;+ expect(summarizeBlockChanges([loop("a")], [loop("b")])).toEqual([+ `Renamed block "a" to "b"`,+ ]);+ });++ it("flags only the edited loop child, not its container", () => {+ const container = (childUrl: string): BlockYAML =>+ ({+ label: "loop",+ block_type: "for_loop",+ loop_blocks: [block("child", { url: childUrl })],+ }) as unknown as BlockYAML;+ expect(+ summarizeBlockChanges([container("https://x")], [container("https://y")]),+ ).toEqual([`Edited block "child"`]);+ });++ it("tracks a loop child that shares a label with its container", () => {+ const loopWith = (children: Array<BlockYAML>): BlockYAML =>+ ({+ label: "dup",+ block_type: "for_loop",+ loop_blocks: children,+ }) as unknown as BlockYAML;+ // A global-label map would let the child overwrite the container and+ // misreport this as an edit; nesting-path keys keep them distinct.+ expect(+ summarizeBlockChanges(+ [loopWith([block("dup", { code: "x" })])],+ [loopWith([])],+ ),+ ).toEqual([`Removed block "dup"`]);+ });+});++describe("summarizeWorkflowChanges (snapshot baseline)", () => {+ it("returns [] when there is no snapshot yet (no user edit since load)", () => {+ expect(+ summarizeWorkflowChanges(saveData({ blocks: [block("a")] }), null),+ ).toEqual([]);+ });++ // The QA repro: a freshly loaded "Skyvern Page Checker" with a login block+ // whose credential goal the canvas auto-materialized on open. The baseline is+ // captured from the same live draft, so it lists nothing — no phantom+ // "Edited block block_1". Covers a login block with a credential parameter.+ it("lists nothing for a fresh load, including an autofilled login block", () => {+ const data = saveData({+ title: "Skyvern Page Checker",+ blocks: [+ block("start", { url: "https://example.com" }),+ block("block_1", {+ block_type: "login",+ parameter_keys: ["credentials"],+ navigation_goal: "log in using the provided context",+ }),+ ],+ parameters: [{ key: "credentials", parameter_type: "credential" }],+ });+ expect(summarizeWorkflowChanges(data, snapshotOf(data))).toEqual([]);+ });++ it("detects a real block edit against the snapshot", () => {+ const base = snapshotOf(saveData({ blocks: [block("a", { url: "x" })] }));+ expect(+ summarizeWorkflowChanges(+ saveData({ blocks: [block("a", { url: "y" })] }),+ base,+ ),+ ).toEqual([`Edited block "a"`]);+ });++ it("reports a workflow rename", () => {+ const base = snapshotOf(saveData({ title: "Old" }));+ expect(+ summarizeWorkflowChanges(saveData({ title: "New" }), base),+ ).toContain(`Renamed workflow to "New"`);+ });++ it("reports added/removed workflow parameters and ignores secrets", () => {+ const base = snapshotOf(+ saveData({+ parameters: [+ { key: "kept", parameter_type: "workflow" },+ { key: "gone", parameter_type: "workflow" },+ ],+ }),+ );+ const out = summarizeWorkflowChanges(+ saveData({+ parameters: [+ { key: "kept", parameter_type: "workflow" },+ { key: "added", parameter_type: "workflow" },+ { key: "secret", parameter_type: "aws_secret" },+ ],+ }),+ base,+ );+ expect(out).toContain(`Added parameter "added"`);+ expect(out).toContain(`Removed parameter "gone"`);+ expect(out).not.toContain(`Added parameter "secret"`);+ });++ const wfParam = (over: Record<string, unknown> = {}) => ({+ key: "param_x",+ parameter_type: "workflow",+ workflow_parameter_type: "string",+ ...over,+ });++ it("flags a default-value change as an edited parameter", () => {+ const base = snapshotOf(saveData({ parameters: [wfParam()] }));+ expect(+ summarizeWorkflowChanges(+ saveData({ parameters: [wfParam({ default_value: "y" })] }),+ base,+ ),+ ).toEqual([`Edited parameter "param_x"`]);+ });++ it("flags a description-only change as an edited parameter", () => {+ const base = snapshotOf(+ saveData({ parameters: [wfParam({ description: "a" })] }),+ );+ expect(+ summarizeWorkflowChanges(+ saveData({ parameters: [wfParam({ description: "b" })] }),+ base,+ ),+ ).toEqual([`Edited parameter "param_x"`]);+ });++ it("emits one line per edited parameter even when several fields change", () => {+ const base = snapshotOf(+ saveData({+ parameters: [wfParam({ default_value: "y", description: "a" })],+ }),+ );+ expect(+ summarizeWorkflowChanges(+ saveData({+ parameters: [+ wfParam({+ default_value: "z",+ description: "b",+ workflow_parameter_type: "integer",+ }),+ ],+ }),+ base,+ ),+ ).toEqual([`Edited parameter "param_x"`]);+ });++ it("emits nothing when a parameter is unchanged (no false positive)", () => {+ const data = saveData({+ parameters: [wfParam({ default_value: "y", description: "d" })],+ });+ expect(summarizeWorkflowChanges(data, snapshotOf(data))).toEqual([]);+ });++ it("names a proxy-location change instead of the generic bucket", () => {+ const base = snapshotOf(+ saveData({ settings: { proxyLocation: "RESIDENTIAL" } }),+ );+ expect(+ summarizeWorkflowChanges(+ saveData({ settings: { proxyLocation: "US-CA" } }),+ base,+ ),+ ).toEqual(["Changed proxy location"]);+ });++ it("names a boolean setting toggle", () => {+ const base = snapshotOf(+ saveData({ settings: { persistBrowserSession: false } }),+ );+ expect(+ summarizeWorkflowChanges(+ saveData({ settings: { persistBrowserSession: true } }),+ base,+ ),+ ).toEqual(["Toggled persist browser session"]);+ });++ it("groups a browser-profile change into one line", () => {+ const base = snapshotOf(+ saveData({+ settings: { browserProfileId: "p1", browserProfileKey: "k1" },+ }),+ );+ expect(+ summarizeWorkflowChanges(+ saveData({+ settings: { browserProfileId: "p2", browserProfileKey: "k2" },+ }),+ base,+ ),+ ).toEqual(["Changed browser profile"]);+ });++ it("groups sequential-run settings into one line", () => {+ const base = snapshotOf(+ saveData({ settings: { runSequentially: false, sequentialKey: null } }),+ );+ expect(+ summarizeWorkflowChanges(+ saveData({ settings: { runSequentially: true, sequentialKey: "k" } }),+ base,+ ),+ ).toEqual(["Changed sequential run settings"]);+ });++ it("emits nothing when a fully-populated settings object is unchanged", () => {+ const settings = {+ proxyLocation: "RESIDENTIAL",+ webhookCallbackUrl: "https://h",+ persistBrowserSession: true,+ pinSavedSessionIp: false,+ browserProfileId: "p",+ browserProfileKey: "k",+ model: null,+ maxScreenshotScrolls: 3,+ maxElapsedTimeMinutes: 10,+ extraHttpHeaders: '{"a":"b"}',+ cdpConnectHeaders: null,+ runWith: "code",+ codeVersion: 2,+ scriptCacheKey: "c",+ aiFallback: true,+ enableSelfHealing: false,+ runSequentially: true,+ sequentialKey: "s",+ finallyBlockLabel: "f",+ workflowSystemPrompt: "prompt",+ errorCodeMapping: { e: "m" },+ };+ const data = saveData({ settings });+ expect(summarizeWorkflowChanges(data, snapshotOf(data))).toEqual([]);+ });++ it("names every edit in a kitchen-sink change with no generic bucket", () => {+ const base = snapshotOf(+ saveData({+ title: "Old",+ blocks: [block("a", { url: "https://x" })],+ parameters: [wfParam({ default_value: "1" })],+ settings: { proxyLocation: "RESIDENTIAL", model: null },+ }),+ );+ const out = summarizeWorkflowChanges(+ saveData({+ title: "New",+ blocks: [block("a", { url: "https://y" })],+ parameters: [wfParam({ default_value: "2" })],+ settings: { proxyLocation: "US-CA", model: { modelName: "gpt" } },+ }),+ base,+ );+ expect(out).toContain(`Renamed workflow to "New"`);+ expect(out).toContain(`Edited block "a"`);+ expect(out).toContain(`Edited parameter "param_x"`);+ expect(out).toContain("Changed proxy location");+ expect(out).toContain("Changed model");+ expect(out).not.toContain("Other workflow changes");+ });++ it("uses the generic bucket only for a change no summarizer covers", () => {+ // A non-workflow (credential) parameter edit that doesn't also touch a+ // block is deliberately not itemized, so it falls to the catch-all.+ const base = snapshotOf(+ saveData({+ parameters: [+ { key: "c", parameter_type: "credential", credential_id: "a" },+ ],+ }),+ );+ expect(+ summarizeWorkflowChanges(+ saveData({+ parameters: [+ { key: "c", parameter_type: "credential", credential_id: "b" },+ ],+ }),+ base,+ ),+ ).toEqual(["Other workflow changes"]);+ });+});++describe("isDraftDirty", () => {+ it("is false with no snapshot", () => {+ expect(isDraftDirty(saveData({ blocks: [block("a")] }), null)).toBe(false);+ });++ it("is false when the draft matches the snapshot", () => {+ const data = saveData({ blocks: [block("a", { url: "x" })] });+ expect(isDraftDirty(data, snapshotOf(data))).toBe(false);+ });++ it("is true when a block changed", () => {+ const base = snapshotOf(saveData({ blocks: [block("a", { url: "x" })] }));+ expect(+ isDraftDirty(saveData({ blocks: [block("a", { url: "y" })] }), base),+ ).toBe(true);+ });+});++describe("summarizeWorkflowChanges YAML draft path", () => {+ afterEach(() => {+ useWorkflowYamlEditorStore.setState({+ active: false,+ draft: "",+ entrySnapshot: "",+ });+ });++ it("diffs the parsed YAML draft against the snapshot", () => {+ const canvas = saveData({+ blocks: [block("a", { block_type: "code", code: "# a" })],+ });+ const snap = snapshotOf(canvas); // captured while the YAML editor is closed+ useWorkflowYamlEditorStore.setState({+ active: true,+ entrySnapshot: toYaml({ parameters: [], blocks: canvas.blocks }),+ draft: toYaml({+ parameters: [],+ blocks: [+ ...canvas.blocks,+ { label: "b", block_type: "code", code: "# b" },+ ],+ }),+ });+ expect(summarizeWorkflowChanges(canvas, snap)).toContain(+ `Added code block "b"`,+ );+ });+});diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowChangesSummary.ts b/skyvern-frontend/src/routes/workflows/editor/workflowChangesSummary.tsnew file mode 100644index 000000000..ea1cd6d63--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/workflowChangesSummary.ts@@ -0,0 +1,338 @@+import { parse } from "yaml";++import type {+ WorkflowSettings,+ WorkflowParameter,+} from "@/routes/workflows/types/workflowTypes";+import type {+ BlockYAML,+ ParameterYAML,+} from "@/routes/workflows/types/workflowYamlTypes";+import type { WorkflowSaveData } from "@/store/WorkflowHasChangesStore";+import {+ isWorkflowYamlDirty,+ useWorkflowYamlEditorStore,+} from "@/store/WorkflowYamlEditorStore";++// A frozen copy of the editable draft, taken at a clean baseline (see+// WorkflowSnapshotStore). Diffed against the live draft to describe unsaved+// edits. Both sides come from the SAME nodes->YAML serializer, so content the+// canvas materialized post-load (e.g. a login-block credential autofill) is+// present on both sides and never reads as a phantom edit.+export type WorkflowSnapshot = {+ blocks: Array<BlockYAML>;+ parameters: Array<ParameterYAML | WorkflowParameter>;+ settings: WorkflowSettings;+ title: string;+};++// Recursively sort object keys and drop empty values (null / "" / [] / {}) so+// two serializations of the same content compare equal despite cosmetic+// key-order or empty-value differences.+function canonicalize(value: unknown): unknown {+ if (Array.isArray(value)) {+ const items = value.map(canonicalize).filter((item) => item !== undefined);+ return items.length > 0 ? items : undefined;+ }+ if (value !== null && typeof value === "object") {+ const out: Record<string, unknown> = {};+ for (const key of Object.keys(value as Record<string, unknown>).sort()) {+ const canon = canonicalize((value as Record<string, unknown>)[key]);+ if (canon !== undefined) {+ out[key] = canon;+ }+ }+ return Object.keys(out).length > 0 ? out : undefined;+ }+ if (value === null || value === "") {+ return undefined;+ }+ return value;+}++function canonicalKey(value: unknown): string {+ return JSON.stringify(canonicalize(value));+}++type LoopBlock = BlockYAML & { loop_blocks?: Array<BlockYAML> };++// A block's own content, excluding its label (so a rename can be matched) and+// its loop_blocks (children are diffed separately, so a child edit flags only+// the child, not its container).+function ownFingerprint(block: BlockYAML): string {+ const { label, loop_blocks, ...self } = block as LoopBlock;+ void label;+ void loop_blocks;+ return canonicalKey(self);+}++// A block's whole subtree excluding only its label — used to pair a removed+// block with an added one as a rename only when everything but the label matches.+function subtreeFingerprint(block: BlockYAML): string {+ const { label, ...self } = block as LoopBlock;+ void label;+ return canonicalKey(self);+}++function loopChildren(block: BlockYAML): Array<BlockYAML> {+ const children = (block as LoopBlock).loop_blocks;+ return Array.isArray(children) ? children : [];+}++function blockNoun(blockType: string): string {+ return blockType.split("_").join(" ");+}++// Diff one nesting level, recursing into matched/renamed loop containers. Labels+// are unique per level (not globally), so each level is keyed by label and+// renames are paired by identical subtree content. Recursing per level keeps a+// container rename from flagging its unchanged children — a child's identity+// never encodes an ancestor's label.+export function summarizeBlockChanges(+ baseline: Array<BlockYAML>,+ draft: Array<BlockYAML>,+): Array<string> {+ const baseByLabel = new Map(baseline.map((b) => [b.label, b] as const));+ const draftByLabel = new Map(draft.map((b) => [b.label, b] as const));+ const edited: Array<string> = [];+ const childChanges: Array<string> = [];+ const addedBlocks: Array<BlockYAML> = [];+ const removedBlocks: Array<BlockYAML> = [];++ for (const draftBlock of draft) {+ const baseBlock = baseByLabel.get(draftBlock.label);+ if (!baseBlock) {+ addedBlocks.push(draftBlock);+ continue;+ }+ if (ownFingerprint(baseBlock) !== ownFingerprint(draftBlock)) {+ edited.push(`Edited block "${draftBlock.label}"`);+ }+ childChanges.push(+ ...summarizeBlockChanges(+ loopChildren(baseBlock),+ loopChildren(draftBlock),+ ),+ );+ }+ for (const baseBlock of baseline) {+ if (!draftByLabel.has(baseBlock.label)) {+ removedBlocks.push(baseBlock);+ }+ }++ // A removed block whose whole subtree (label aside) matches an added one is a+ // rename; when the content also changed, the subtrees differ and it stays a+ // remove + add.+ const renamed: Array<string> = [];+ const takenAdded = new Set<number>();+ const removedLines: Array<string> = [];+ for (const rem of removedBlocks) {+ const matchIdx = addedBlocks.findIndex(+ (a, idx) =>+ !takenAdded.has(idx) &&+ subtreeFingerprint(a) === subtreeFingerprint(rem),+ );+ const match = matchIdx >= 0 ? addedBlocks[matchIdx] : undefined;+ if (match) {+ takenAdded.add(matchIdx);+ renamed.push(`Renamed block "${rem.label}" to "${match.label}"`);+ } else {+ removedLines.push(`Removed block "${rem.label}"`);+ }+ }+ const addedLines = addedBlocks+ .filter((_, idx) => !takenAdded.has(idx))+ .map((a) => `Added ${blockNoun(a.block_type)} block "${a.label}"`);++ return [+ ...addedLines,+ ...renamed,+ ...edited,+ ...childChanges,+ ...removedLines,+ ];+}++// Only workflow-type parameters are user-managed; aws_secret / echo / email+// secrets are synthesized at save time and would read as phantom changes.+type ParameterLike = { key: string; parameter_type: string };++function summarizeParameterChanges(+ baseline: Array<ParameterLike>,+ draft: Array<ParameterLike>,+): Array<string> {+ const isWorkflowParam = (p: ParameterLike) => p.parameter_type === "workflow";+ const baseMap = new Map(+ baseline.filter(isWorkflowParam).map((p) => [p.key, p] as const),+ );+ const draftMap = new Map(+ draft.filter(isWorkflowParam).map((p) => [p.key, p] as const),+ );+ const changes: Array<string> = [];+ // Match by key and fingerprint the whole parameter (default value,+ // description, type…) so any field edit reads as one "Edited parameter" line,+ // mirroring the block grammar. One entry per key even if several fields change.+ for (const [key, param] of draftMap) {+ const base = baseMap.get(key);+ if (!base) {+ changes.push(`Added parameter "${key}"`);+ } else if (canonicalKey(param) !== canonicalKey(base)) {+ changes.push(`Edited parameter "${key}"`);+ }+ }+ for (const key of baseMap.keys()) {+ if (!draftMap.has(key)) {+ changes.push(`Removed parameter "${key}"`);+ }+ }+ return changes;+}++// Every user-editable workflow setting maps to a specific, value-free line so a+// settings change is named rather than falling to the generic bucket. Grouped+// pairs (browser profile, sequential runs) read as one line. TOTP and other+// workflow-object fields are not diffed here — they live outside the snapshot.+const SETTINGS_LABELS: Array<{+ fields: Array<keyof WorkflowSettings>;+ label: string;+}> = [+ { fields: ["proxyLocation"], label: "Changed proxy location" },+ { fields: ["webhookCallbackUrl"], label: "Changed webhook callback URL" },+ {+ fields: ["persistBrowserSession"],+ label: "Toggled persist browser session",+ },+ { fields: ["pinSavedSessionIp"], label: "Toggled pinned session IP" },+ {+ fields: ["browserProfileId", "browserProfileKey"],+ label: "Changed browser profile",+ },+ { fields: ["model"], label: "Changed model" },+ { fields: ["maxScreenshotScrolls"], label: "Changed max screenshot scrolls" },+ { fields: ["maxElapsedTimeMinutes"], label: "Changed max run time" },+ { fields: ["extraHttpHeaders"], label: "Changed extra HTTP headers" },+ { fields: ["cdpConnectHeaders"], label: "Changed CDP connect headers" },+ { fields: ["runWith"], label: "Changed run mode" },+ { fields: ["codeVersion"], label: "Changed code version" },+ { fields: ["scriptCacheKey"], label: "Changed script cache key" },+ { fields: ["aiFallback"], label: "Toggled AI fallback" },+ { fields: ["enableSelfHealing"], label: "Toggled self-healing" },+ {+ fields: ["runSequentially", "sequentialKey"],+ label: "Changed sequential run settings",+ },+ { fields: ["finallyBlockLabel"], label: "Changed finally block" },+ { fields: ["workflowSystemPrompt"], label: "Changed workflow system prompt" },+ { fields: ["errorCodeMapping"], label: "Changed error handling" },+];++function summarizeSettingsChanges(+ baseline: WorkflowSettings | null,+ draft: WorkflowSettings | null,+): Array<string> {+ if (!baseline || !draft) {+ return [];+ }+ const changes: Array<string> = [];+ for (const { fields, label } of SETTINGS_LABELS) {+ const changed = fields.some(+ (field) => canonicalKey(baseline[field]) !== canonicalKey(draft[field]),+ );+ if (changed) {+ changes.push(label);+ }+ }+ return changes;+}++// While the Code/YAML editor is open with uncommitted edits, the canvas graph+// (saveData) lags the draft, and the actual save commits the YAML draft. Parse+// the YAML draft so YAML-only edits are reflected. Malformed YAML mid-typing+// falls back to the canvas.+function effectiveDraft(saveData: WorkflowSaveData): WorkflowSnapshot {+ let blocks = saveData.blocks;+ let parameters: WorkflowSnapshot["parameters"] = saveData.parameters;+ const yamlState = useWorkflowYamlEditorStore.getState();+ if (yamlState.active && isWorkflowYamlDirty(yamlState)) {+ try {+ const parsed = parse(yamlState.draft) as {+ blocks?: Array<BlockYAML>;+ parameters?: Array<ParameterYAML>;+ } | null;+ if (parsed && Array.isArray(parsed.blocks)) {+ blocks = parsed.blocks;+ if (Array.isArray(parsed.parameters)) {+ parameters = parsed.parameters;+ }+ }+ } catch {+ // fall through to the canvas draft+ }+ }+ // Only user-editable content is diffed. workflowDefinitionVersion (bumped by+ // the save-time v2 upgrade) and other workflow-object fields are excluded so+ // non-user churn can never surface as a change.+ return {+ blocks,+ parameters,+ settings: saveData.settings,+ title: saveData.title,+ };+}++// The clean-baseline snapshot, frozen at the first user edit after a load or+// save (see WorkflowSnapshotStore). Same extraction as the diff, so a fresh+// load compares equal.+export function snapshotOf(saveData: WorkflowSaveData): WorkflowSnapshot {+ return effectiveDraft(saveData);+}++export function isDraftDirty(+ saveData: WorkflowSaveData,+ snapshot: WorkflowSnapshot | null,+): boolean {+ if (!snapshot) {+ return false;+ }+ return canonicalKey(effectiveDraft(saveData)) !== canonicalKey(snapshot);+}++/**+ * Human-readable summary of the unsaved edits between the live draft and the+ * clean-baseline `snapshot`. Returns [] when there is no snapshot yet (no user+ * edit since the last load/save) or the draft matches it, so a freshly loaded+ * workflow — even one the canvas auto-materialized on open — lists nothing.+ * Covers the workflow rename, block add/edit/remove/rename, workflow-parameter+ * add/edit/remove, and every workflow setting. A pure block reorder reads as an+ * "Edited block" (its linkage fields changed) — a deliberate ceiling. The+ * generic "Other workflow changes" line is a catch-all for anything no specific+ * summarizer covers (a future schema field, or a non-workflow-parameter edit+ * that isn't already reflected as a block edit).+ */+export function summarizeWorkflowChanges(+ saveData: WorkflowSaveData,+ snapshot: WorkflowSnapshot | null,+): Array<string> {+ if (!snapshot) {+ return [];+ }+ const draft = effectiveDraft(saveData);+ const changes: Array<string> = [];+ if (draft.title !== snapshot.title) {+ changes.push(`Renamed workflow to "${draft.title}"`);+ }+ changes.push(...summarizeBlockChanges(snapshot.blocks, draft.blocks));+ changes.push(+ ...summarizeParameterChanges(+ snapshot.parameters as Array<ParameterLike>,+ draft.parameters as Array<ParameterLike>,+ ),+ );+ changes.push(...summarizeSettingsChanges(snapshot.settings, draft.settings));++ if (changes.length === 0 && isDraftDirty(saveData, snapshot)) {+ changes.push("Other workflow changes");+ }+ return changes;+}diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.test.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.test.tsxindex b321654d3..3a04599f7 100644--- a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.test.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.test.tsx@@ -8,19 +8,35 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { ProxyLocation, Status } from "@/api/types";import { TooltipProvider } from "@/components/ui/tooltip";-const { workflowRunQueryMock } = vi.hoisted(() => ({+const { workflowRunQueryMock, saveWorkflowSpy } = vi.hoisted(() => ({workflowRunQueryMock: vi.fn(),+ saveWorkflowSpy: vi.fn(() => Promise.resolve()),}));vi.mock("../hooks/useWorkflowRunWithWorkflowQuery", () => ({useWorkflowRunWithWorkflowQuery: () => workflowRunQueryMock(),}));+vi.mock("../editor/hooks/useSaveWorkflow", () => ({+ useSaveWorkflow: () => saveWorkflowSpy,+}));vi.mock("@/api/AxiosClient", () => ({ getClient: vi.fn() }));vi.mock("@/hooks/useCredentialGetter", () => ({useCredentialGetter: () => vi.fn(),}));-import { RunStopButton } from "./StudioTopBar";+import { stringify as toYaml } from "yaml";++import type { BlockYAML } from "@/routes/workflows/types/workflowYamlTypes";+import { snapshotOf } from "@/routes/workflows/editor/workflowChangesSummary";+import { useRecordingStore } from "@/store/useRecordingStore";+import {+ useWorkflowHasChangesStore,+ type WorkflowSaveData,+} from "@/store/WorkflowHasChangesStore";+import { useWorkflowSnapshotStore } from "@/store/WorkflowSnapshotStore";+import { useWorkflowYamlEditorStore } from "@/store/WorkflowYamlEditorStore";++import { RunStopButton, SaveButton } from "./StudioTopBar";function LocationProbe() {const location = useLocation();@@ -245,3 +261,116 @@ describe("RunStopButton stopOnly (global workflows)", () => {expect(screen.queryByRole("button")).toBeNull();});});++const block = (label: string, extra: Record<string, unknown> = {}): BlockYAML =>+ ({ label, block_type: "task", ...extra }) as unknown as BlockYAML;++const saveData = (blocks: Array<BlockYAML>): WorkflowSaveData =>+ ({+ title: "T",+ blocks,+ parameters: [],+ settings: { proxyLocation: "RESIDENTIAL" },+ workflow: {+ title: "T",+ workflow_definition: { version: 2, blocks: [], parameters: [] },+ },+ }) as unknown as WorkflowSaveData;++function renderSaveButton() {+ return render(+ <TooltipProvider delayDuration={0}>+ <SaveButton />+ </TooltipProvider>,+ );+}++// The confirmation is gated on live dirtiness computed in the click handler, not+// on the debounced canvas-only `contentDirty` dot — so a YAML edit or an+// edit-then-save inside the debounce window still shows the "Saving Changes"+// list. Each case here has `contentDirty` stale-false to exercise that gap.+describe("SaveButton confirmation gating", () => {+ afterEach(() => {+ useWorkflowSnapshotStore.getState().clearSnapshot();+ useWorkflowHasChangesStore.setState({+ getSaveData: () => null,+ saveIsPending: false,+ });+ useWorkflowYamlEditorStore.setState({+ active: false,+ draft: "",+ entrySnapshot: "",+ });+ useRecordingStore.setState({ isRecording: false });+ });++ test("confirms a dirty draft even when contentDirty is stale-false", () => {+ const clean = saveData([block("a", { url: "x" })]);+ const dirty = saveData([block("a", { url: "y" })]);+ useWorkflowHasChangesStore.setState({+ getSaveData: () => dirty,+ saveIsPending: false,+ });+ useWorkflowSnapshotStore.setState({+ snapshot: snapshotOf(clean),+ contentDirty: false,+ userHasEdited: false,+ });++ renderSaveButton();+ fireEvent.click(screen.getByRole("button", { name: "Save workflow" }));++ expect(screen.queryByText("Saving Changes")).not.toBeNull();+ expect(saveWorkflowSpy).not.toHaveBeenCalled();+ });++ test("saves directly with no confirmation when the draft matches the baseline", () => {+ const clean = saveData([block("a", { url: "x" })]);+ useWorkflowHasChangesStore.setState({+ getSaveData: () => clean,+ saveIsPending: false,+ });+ useWorkflowSnapshotStore.setState({+ snapshot: snapshotOf(clean),+ contentDirty: false,+ userHasEdited: false,+ });++ renderSaveButton();+ fireEvent.click(screen.getByRole("button", { name: "Save workflow" }));++ expect(screen.queryByText("Saving Changes")).toBeNull();+ expect(saveWorkflowSpy).toHaveBeenCalledTimes(1);+ });++ test("confirms an uncommitted YAML-draft edit the canvas hasn't caught up to", () => {+ const canvas = saveData([block("a", { block_type: "code", code: "# a" })]);+ // Baseline and canvas agree; the edit lives only in the YAML draft.+ useWorkflowHasChangesStore.setState({+ getSaveData: () => canvas,+ saveIsPending: false,+ });+ useWorkflowSnapshotStore.setState({+ snapshot: snapshotOf(canvas),+ contentDirty: false,+ userHasEdited: false,+ });+ useWorkflowYamlEditorStore.setState({+ active: true,+ entrySnapshot: toYaml({ parameters: [], blocks: canvas.blocks }),+ draft: toYaml({+ parameters: [],+ blocks: [+ ...canvas.blocks,+ { label: "b", block_type: "code", code: "# b" },+ ],+ }),+ });++ renderSaveButton();+ fireEvent.click(screen.getByRole("button", { name: "Save workflow" }));++ expect(screen.queryByText("Saving Changes")).not.toBeNull();+ expect(saveWorkflowSpy).not.toHaveBeenCalled();+ });+});diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsxindex 9abe8b25e..32c257074 100644--- a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx@@ -1,4 +1,4 @@-import { type ReactNode } from "react";+import { type ReactNode, useMemo, useState } from "react";import { AxiosError } from "axios";import {CalendarIcon,@@ -27,6 +27,7 @@ import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { useRecordingStore } from "@/store/useRecordingStore";import { useWorkflowHasChangesStore } from "@/store/WorkflowHasChangesStore";import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";+import { useWorkflowSnapshotStore } from "@/store/WorkflowSnapshotStore";import { useWorkflowTitleStore } from "@/store/WorkflowTitleStore";import { statusIsFinalized } from "@/routes/tasks/types";import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";@@ -35,6 +36,11 @@ import { cn } from "@/util/utils";import { EditableNodeTitle } from "../editor/nodes/components/EditableNodeTitle";import { EditorOverflowMenu } from "../editor/header/EditorOverflowMenu";import { MakeACopyButton } from "../editor/MakeACopyButton";+import { WorkflowChangesList } from "../editor/WorkflowChangesList";+import {+ isDraftDirty,+ summarizeWorkflowChanges,+} from "../editor/workflowChangesSummary";import { useSaveWorkflow } from "../editor/hooks/useSaveWorkflow";import { useToggleHistoryPanel } from "../editor/hooks/useToggleHistoryPanel";import { useIsGlobalWorkflow } from "../hooks/useIsGlobalWorkflow";@@ -68,27 +74,114 @@ function TitleSection({ editable = true }: { editable?: boolean }) {);}-function SaveButton() {+export function SaveButton() {const saving = useWorkflowHasChangesStore((s) => s.saveIsPending);+ const getSaveData = useWorkflowHasChangesStore((s) => s.getSaveData);+ // contentDirty reflects real user edits vs the clean baseline snapshot, so+ // post-load canvas materialization (login autofill) doesn't light the dot.+ // It's debounced, so the click handler recomputes dirtiness synchronously+ // instead of gating on it (see onClick).+ const contentDirty = useWorkflowSnapshotStore((s) => s.contentDirty);+ const snapshot = useWorkflowSnapshotStore((s) => s.snapshot);const isRecording = useRecordingStore((s) => s.isRecording);const onSave = useSaveWorkflow();+ const [confirmOpen, setConfirmOpen] = useState(false);++ // Compute once when the confirm dialog opens; the canvas is behind the modal+ // and can't be edited while it's up, so the summary stays valid.+ const changes = useMemo(() => {+ if (!confirmOpen) {+ return [];+ }+ try {+ const saveData = getSaveData();+ return saveData ? summarizeWorkflowChanges(saveData, snapshot) : [];+ } catch (error) {+ console.error("Failed to summarize workflow changes", error);+ return [];+ }+ }, [confirmOpen, getSaveData, snapshot]);+return (- <ControlTooltip content="Save workflow" blocked={isRecording}>- <Button- variant="outline"- size="icon"- className="h-8 w-8 border-border bg-transparent shadow-none"- disabled={isRecording}- onClick={() => void onSave()}- aria-label="Save workflow"- >- {saving ? (- <ReloadIcon className="size-4 animate-spin" />- ) : (- <SaveIcon className="size-4" />- )}- </Button>- </ControlTooltip>+ <>+ <ControlTooltip content="Save workflow" blocked={isRecording}>+ <Button+ variant="outline"+ size="icon"+ className="relative h-8 w-8 border-border bg-transparent shadow-none"+ disabled={isRecording}+ onClick={() => {+ // Recompute dirtiness synchronously from the same source as the+ // summary (incl. the YAML draft). contentDirty is debounced and+ // canvas-only, so gating the confirmation on it would skip it for a+ // YAML edit or an edit-then-save inside the debounce window.+ let dirty = false;+ try {+ const saveData = getSaveData();+ dirty = saveData ? isDraftDirty(saveData, snapshot) : false;+ } catch (error) {+ console.error("Failed to check workflow changes", error);+ }+ // onSave rejects on a failed save (already toasted by its onError);+ // swallow so it isn't an unhandled rejection.+ if (dirty) {+ setConfirmOpen(true);+ } else {+ void onSave().catch(() => {});+ }+ }}+ aria-label={+ contentDirty ? "Save workflow (unsaved changes)" : "Save workflow"+ }+ >+ {saving ? (+ <ReloadIcon className="size-4 animate-spin" />+ ) : (+ <SaveIcon className="size-4" />+ )}+ {contentDirty && !saving && (+ <span+ aria-hidden+ className="absolute -right-0.5 -top-0.5 size-1.5 rounded-full bg-primary"+ />+ )}+ </Button>+ </ControlTooltip>+ <Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Saving Changes</DialogTitle>+ <DialogDescription>+ The changes below are going to be saved:+ </DialogDescription>+ </DialogHeader>+ <WorkflowChangesList changes={changes} />+ <DialogFooter>+ <DialogClose asChild>+ <Button variant="secondary">Cancel</Button>+ </DialogClose>+ <Button+ disabled={saving}+ onClick={() => {+ // Close only on success; a failed save (already toasted by+ // onSave's onError) keeps the list open for retry, so swallow+ // the rejection rather than leaving it unhandled.+ void onSave()+ .then(() => {+ if (!useWorkflowHasChangesStore.getState().hasChanges) {+ setConfirmOpen(false);+ }+ })+ .catch(() => {});+ }}+ >+ {saving && <ReloadIcon className="mr-2 size-4 animate-spin" />}+ Save changes+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>);}diff --git a/skyvern-frontend/src/store/WorkflowSnapshotStore.test.ts b/skyvern-frontend/src/store/WorkflowSnapshotStore.test.tsnew file mode 100644index 000000000..054ee2bb4--- /dev/null+++ b/skyvern-frontend/src/store/WorkflowSnapshotStore.test.ts@@ -0,0 +1,300 @@+// @vitest-environment jsdom++import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { stringify as toYaml } from "yaml";++import type { BlockYAML } from "@/routes/workflows/types/workflowYamlTypes";+import { isDraftDirty } from "@/routes/workflows/editor/workflowChangesSummary";+import {+ subscribeToYamlDraftChanges,+ useWorkflowYamlEditorStore,+} from "@/store/WorkflowYamlEditorStore";++import {+ useWorkflowHasChangesStore,+ type WorkflowSaveData,+} from "./WorkflowHasChangesStore";+import { useWorkflowSnapshotStore } from "./WorkflowSnapshotStore";++const block = (label: string, extra: Record<string, unknown> = {}): BlockYAML =>+ ({ label, block_type: "task", ...extra }) as unknown as BlockYAML;++const saveData = (blocks: Array<BlockYAML>): WorkflowSaveData =>+ ({+ title: "T",+ blocks,+ parameters: [],+ settings: { proxyLocation: "RESIDENTIAL" },+ workflow: {+ title: "T",+ workflow_definition: { version: 2, blocks: [], parameters: [] },+ },+ }) as unknown as WorkflowSaveData;++/** Point getSaveData at a fresh draft — the store reads it live on each call. */+function setDraft(blocks: Array<BlockYAML>) {+ useWorkflowHasChangesStore.setState({ getSaveData: () => saveData(blocks) });+}++beforeEach(() => {+ useWorkflowSnapshotStore.getState().clearSnapshot();+});++afterEach(() => {+ useWorkflowSnapshotStore.getState().clearSnapshot();+ useWorkflowHasChangesStore.setState({ getSaveData: () => null });+ useWorkflowYamlEditorStore.setState({+ active: false,+ draft: "",+ entrySnapshot: "",+ });+});++describe("WorkflowSnapshotStore lifecycle", () => {+ it("captureSnapshot freezes the current draft and starts clean", () => {+ setDraft([block("a", { url: "x" })]);+ useWorkflowSnapshotStore.getState().captureSnapshot();+ const state = useWorkflowSnapshotStore.getState();+ expect(state.snapshot).not.toBeNull();+ expect(state.contentDirty).toBe(false);+ expect(state.userHasEdited).toBe(false);+ });++ it("clearSnapshot drops the baseline and resets the flags", () => {+ setDraft([block("a")]);+ useWorkflowSnapshotStore.getState().captureSnapshot();+ useWorkflowSnapshotStore.getState().noteDraftChange(true);+ useWorkflowSnapshotStore.getState().clearSnapshot();+ const state = useWorkflowSnapshotStore.getState();+ expect(state.snapshot).toBeNull();+ expect(state.contentDirty).toBe(false);+ expect(state.userHasEdited).toBe(false);+ });++ it("is a no-op with no baseline yet (nothing to diff against)", () => {+ setDraft([block("a")]);+ useWorkflowSnapshotStore.getState().noteDraftChange(true);+ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(false);+ expect(useWorkflowSnapshotStore.getState().snapshot).toBeNull();+ });+});++describe("WorkflowSnapshotStore dirty-refresh (user edits)", () => {+ it("flags a canvas edit against the baseline", () => {+ setDraft([block("a", { url: "x" })]);+ useWorkflowSnapshotStore.getState().captureSnapshot();++ setDraft([block("a", { url: "y" })]);+ useWorkflowSnapshotStore.getState().noteDraftChange(true);++ const state = useWorkflowSnapshotStore.getState();+ expect(state.contentDirty).toBe(true);+ expect(state.userHasEdited).toBe(true);+ });++ it("flags a YAML-draft edit against the baseline", () => {+ const canvas = [block("a", { block_type: "code", code: "# a" })];+ setDraft(canvas);+ // Baseline captured while the YAML editor is closed.+ useWorkflowSnapshotStore.getState().captureSnapshot();++ useWorkflowYamlEditorStore.setState({+ active: true,+ entrySnapshot: toYaml({ parameters: [], blocks: canvas }),+ draft: toYaml({+ parameters: [],+ blocks: [...canvas, { label: "b", block_type: "code", code: "# b" }],+ }),+ });+ useWorkflowSnapshotStore.getState().noteDraftChange(true);++ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(true);+ });++ it("clears dirtiness when a user edit is reverted", () => {+ setDraft([block("a", { url: "x" })]);+ useWorkflowSnapshotStore.getState().captureSnapshot();++ setDraft([block("a", { url: "y" })]);+ useWorkflowSnapshotStore.getState().noteDraftChange(true);+ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(true);++ setDraft([block("a", { url: "x" })]);+ useWorkflowSnapshotStore.getState().noteDraftChange(true);+ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(false);+ });+});++describe("WorkflowSnapshotStore YAML-draft trigger", () => {+ const canvas = [block("a", { block_type: "code", code: "# a" })];+ const dirtyDraft = () =>+ toYaml({+ parameters: [],+ blocks: [...canvas, { label: "b", block_type: "code", code: "# b" }],+ });++ // The canvas dirtiness effect keys off constructSaveData, which a Code-editor+ // edit never changes — so without the draft subscription the dot stays off on+ // a YAML-only edit. This wires the trigger as FlowRenderer does: a YAML draft+ // change refreshes as a *user-driven* edit (noteDraftChange(true)).+ it("lights contentDirty when a YAML-only edit diverges from the baseline", () => {+ setDraft(canvas);+ useWorkflowSnapshotStore.getState().captureSnapshot(); // clean baseline+ useWorkflowYamlEditorStore+ .getState()+ .open(toYaml({ parameters: [], blocks: canvas }));++ const unsub = subscribeToYamlDraftChanges(() =>+ useWorkflowSnapshotStore.getState().noteDraftChange(true),+ );+ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(false);++ useWorkflowYamlEditorStore.getState().setDraft(dirtyDraft());+ unsub();++ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(true);+ });++ // Regression: the code editor's keystrokes never reach the canvas gesture+ // window, so classifying a YAML draft change by gesture proximity reads it as+ // non-user materialization and ABSORBS it into the baseline — dot stays dark.+ // The subscription must refresh as user-driven; this pins the failure mode.+ it("absorbs the edit (dot dark) if a YAML change is refreshed as non-user", () => {+ setDraft(canvas);+ useWorkflowSnapshotStore.getState().captureSnapshot();+ useWorkflowYamlEditorStore+ .getState()+ .open(toYaml({ parameters: [], blocks: canvas }));++ const unsub = subscribeToYamlDraftChanges(() =>+ useWorkflowSnapshotStore.getState().noteDraftChange(false),+ );+ useWorkflowYamlEditorStore.getState().setDraft(dirtyDraft());+ unsub();++ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(false);+ });+});++describe("WorkflowSnapshotStore cross-workflow reset (A→B same instance)", () => {+ // Workspace can be reused across workflows without remounting (A/build →+ // B/build), so its per-workflow reset effect must clear the baseline — a+ // carried snapshot diffs B's graph against A's and phantoms an "edited" line.+ it("a carried baseline phantoms the next workflow; clearSnapshot prevents it", () => {+ setDraft([block("a", { url: "wfA" })]);+ useWorkflowSnapshotStore.getState().captureSnapshot(); // baseline = workflow A++ setDraft([block("b", { url: "wfB" })]); // A→B nav: getSaveData now returns B+ const carried = useWorkflowSnapshotStore.getState().snapshot;+ expect(isDraftDirty(saveData([block("b", { url: "wfB" })]), carried)).toBe(+ true,+ ); // phantom without a reset++ useWorkflowSnapshotStore.getState().clearSnapshot(); // the per-workflow reset+ expect(useWorkflowSnapshotStore.getState().snapshot).toBeNull();+ expect(isDraftDirty(saveData([block("b", { url: "wfB" })]), null)).toBe(+ false,+ );+ });+});++describe("WorkflowSnapshotStore absorbs pre-first-edit materialization", () => {+ // The early-interaction phantom: a bare interaction freezes the baseline, then+ // login-credential autofill resolves and mutates the canvas. That change is+ // not user-driven and no user edit has happened, so it is absorbed into the+ // baseline instead of surfacing as a phantom "Edited" block.+ it("re-baselines a non-user change before any user edit (no phantom)", () => {+ setDraft([block("login", { navigation_goal: "" })]);+ useWorkflowSnapshotStore.getState().captureSnapshot();++ // Autofill writes the login goal — a change with no preceding gesture.+ setDraft([block("login", { navigation_goal: "log in with the context" })]);+ useWorkflowSnapshotStore.getState().noteDraftChange(false);++ const state = useWorkflowSnapshotStore.getState();+ expect(state.contentDirty).toBe(false);+ // The baseline moved to include the autofill, so the current draft is clean.+ expect(+ isDraftDirty(+ saveData([+ block("login", { navigation_goal: "log in with the context" }),+ ]),+ state.snapshot,+ ),+ ).toBe(false);+ });++ it("a user-driven change with no content diff still absorbs a later autofill", () => {+ // Selecting/dragging a node recomputes the graph (userDriven) without+ // changing content — it must not count as an edit, or a subsequent autofill+ // would surface as a phantom.+ setDraft([block("a", { url: "x" })]);+ useWorkflowSnapshotStore.getState().captureSnapshot();++ useWorkflowSnapshotStore.getState().noteDraftChange(true); // same draft+ expect(useWorkflowSnapshotStore.getState().userHasEdited).toBe(false);+ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(false);++ setDraft([+ block("a", { url: "x" }),+ block("b", { block_type: "login", navigation_goal: "log in" }),+ ]);+ useWorkflowSnapshotStore.getState().noteDraftChange(false);+ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(false);+ });++ it("does NOT absorb a non-user change once the user has edited", () => {+ setDraft([block("a", { url: "x" })]);+ useWorkflowSnapshotStore.getState().captureSnapshot();++ // A genuine user edit freezes the baseline.+ setDraft([block("a", { url: "y" })]);+ useWorkflowSnapshotStore.getState().noteDraftChange(true);+ expect(useWorkflowSnapshotStore.getState().userHasEdited).toBe(true);++ // A later non-user change is NOT absorbed — it surfaces (documented ceiling).+ setDraft([+ block("a", { url: "y" }),+ block("b", { block_type: "login", navigation_goal: "log in" }),+ ]);+ useWorkflowSnapshotStore.getState().noteDraftChange(false);+ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(true);+ });+});++describe("WorkflowSnapshotStore markUserEdit (Copilot / gesture-less edits)", () => {+ // A Copilot build lands async, outside the gesture window, so its change would+ // be classified non-user-driven. markUserEdit is the source-level signal that+ // keeps it from being absorbed, so the dot lights and the summary itemizes it.+ it("surfaces a later non-user change instead of absorbing it", () => {+ setDraft([block("a", { url: "x" })]);+ useWorkflowSnapshotStore.getState().captureSnapshot();++ useWorkflowSnapshotStore.getState().markUserEdit();+ expect(useWorkflowSnapshotStore.getState().userHasEdited).toBe(true);++ // Copilot mutates the canvas (no gesture) — must surface, not be absorbed.+ setDraft([+ block("a", { url: "x" }),+ block("b", { block_type: "code", code: "# copilot" }),+ ]);+ useWorkflowSnapshotStore.getState().noteDraftChange(false);+ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(true);+ });++ it("captures a pre-change baseline when a Copilot build is the first edit", () => {+ // No gesture yet → snapshot is null. markUserEdit freezes the current+ // (pre-Copilot) draft so the build diffs against it.+ expect(useWorkflowSnapshotStore.getState().snapshot).toBeNull();+ setDraft([block("a", { url: "x" })]);+ useWorkflowSnapshotStore.getState().markUserEdit();+ expect(useWorkflowSnapshotStore.getState().snapshot).not.toBeNull();++ setDraft([+ block("a", { url: "x" }),+ block("b", { block_type: "code", code: "# copilot" }),+ ]);+ useWorkflowSnapshotStore.getState().noteDraftChange(false);+ expect(useWorkflowSnapshotStore.getState().contentDirty).toBe(true);+ });+});diff --git a/skyvern-frontend/src/store/WorkflowSnapshotStore.ts b/skyvern-frontend/src/store/WorkflowSnapshotStore.tsnew file mode 100644index 000000000..9edba0e61--- /dev/null+++ b/skyvern-frontend/src/store/WorkflowSnapshotStore.ts@@ -0,0 +1,80 @@+import { create } from "zustand";++import {+ isDraftDirty,+ snapshotOf,+ type WorkflowSnapshot,+} from "@/routes/workflows/editor/workflowChangesSummary";++import { useWorkflowHasChangesStore } from "./WorkflowHasChangesStore";++// The clean-baseline snapshot for the unsaved-changes indicator + summary.+// Frozen at the first user edit after a load/save (so post-load canvas+// materialization — e.g. login-block credential autofill — is absorbed into the+// baseline instead of reading as a user edit), and cleared when the workflow+// returns to a clean state. `contentDirty` drives the studio save-button dot.+// `userHasEdited` gates whether a later non-user change is absorbed or surfaced.+type WorkflowSnapshotStore = {+ snapshot: WorkflowSnapshot | null;+ contentDirty: boolean;+ userHasEdited: boolean;+ captureSnapshot: () => void;+ clearSnapshot: () => void;+ // Record a draft change. `userDriven` = the change followed a user gesture+ // (edit) vs. arrived on its own (post-load materialization).+ noteDraftChange: (userDriven: boolean) => void;+ // Mark the workflow user-edited for a change that has no canvas gesture but is+ // still user-driven — a Copilot build. Keeps the next draft change from being+ // absorbed as materialization; captures a baseline first if none exists yet.+ markUserEdit: () => void;+};++export const useWorkflowSnapshotStore = create<WorkflowSnapshotStore>(+ (set) => ({+ snapshot: null,+ contentDirty: false,+ userHasEdited: false,+ captureSnapshot: () => {+ const saveData = useWorkflowHasChangesStore.getState().getSaveData();+ set({+ snapshot: saveData ? snapshotOf(saveData) : null,+ contentDirty: false,+ userHasEdited: false,+ });+ },+ clearSnapshot: () =>+ set({ snapshot: null, contentDirty: false, userHasEdited: false }),+ noteDraftChange: (userDriven) =>+ set((state) => {+ const saveData = useWorkflowHasChangesStore.getState().getSaveData();+ if (!saveData || state.snapshot === null) {+ return { contentDirty: false };+ }+ const dirty = isDraftDirty(saveData, state.snapshot);+ // A change that diverges the draft before the first user edit and isn't+ // user-driven is post-load materialization (e.g. a login credential+ // autofill resolving after an early interaction). Absorb it into the+ // baseline instead of surfacing a phantom edit; the broad+ // autofill-on-mount case is tracked separately.+ if (!state.userHasEdited && !userDriven && dirty) {+ return { snapshot: snapshotOf(saveData), contentDirty: false };+ }+ // Only a user-driven change that actually diverges the draft counts as+ // the first edit — a bare selection/drag recomputes the graph without+ // changing content and must not freeze the baseline against a later+ // materialization.+ const userHasEdited = state.userHasEdited || (userDriven && dirty);+ return { userHasEdited, contentDirty: dirty };+ }),+ markUserEdit: () =>+ set((state) => {+ const saveData = useWorkflowHasChangesStore.getState().getSaveData();+ // Capture the pre-change state as the baseline if there isn't one yet+ // (e.g. a Copilot build before any manual edit), so the incoming change+ // diffs against it rather than being absorbed.+ const snapshot =+ state.snapshot ?? (saveData ? snapshotOf(saveData) : null);+ return { snapshot, userHasEdited: true };+ }),+ }),+);diff --git a/skyvern-frontend/src/store/WorkflowYamlEditorStore.test.ts b/skyvern-frontend/src/store/WorkflowYamlEditorStore.test.tsindex b4cdcc116..b12af1775 100644--- a/skyvern-frontend/src/store/WorkflowYamlEditorStore.test.ts+++ b/skyvern-frontend/src/store/WorkflowYamlEditorStore.test.ts@@ -1,7 +1,8 @@-import { beforeEach, describe, expect, test } from "vitest";+import { beforeEach, describe, expect, test, vi } from "vitest";import {isWorkflowYamlDirty,+ subscribeToYamlDraftChanges,useWorkflowYamlEditorStore,} from "./WorkflowYamlEditorStore";@@ -55,3 +56,44 @@ describe("WorkflowYamlEditorStore", () => {expect(state.commit).toBe(commit);});});++describe("subscribeToYamlDraftChanges", () => {+ beforeEach(() => {+ useWorkflowYamlEditorStore.getState().close();+ });++ test("fires on a draft edit while the editor is active", () => {+ useWorkflowYamlEditorStore.getState().open("blocks: []");+ const onChange = vi.fn();+ const unsub = subscribeToYamlDraftChanges(onChange);+ useWorkflowYamlEditorStore.getState().setDraft("blocks: [a]");+ unsub();+ expect(onChange).toHaveBeenCalledTimes(1);+ });++ test("does not fire while the editor is inactive", () => {+ const onChange = vi.fn();+ const unsub = subscribeToYamlDraftChanges(onChange);+ // active=false; setDraft still mutates the field, but the guard skips it.+ useWorkflowYamlEditorStore.getState().setDraft("blocks: [a]");+ unsub();+ expect(onChange).not.toHaveBeenCalled();+ });++ test("does not fire when the draft is unchanged (error-only update)", () => {+ useWorkflowYamlEditorStore.getState().open("a: 1");+ const onChange = vi.fn();+ const unsub = subscribeToYamlDraftChanges(onChange);+ useWorkflowYamlEditorStore.getState().setError("could not parse");+ unsub();+ expect(onChange).not.toHaveBeenCalled();+ });++ test("stops firing after unsubscribe", () => {+ useWorkflowYamlEditorStore.getState().open("blocks: []");+ const onChange = vi.fn();+ subscribeToYamlDraftChanges(onChange)();+ useWorkflowYamlEditorStore.getState().setDraft("blocks: [a]");+ expect(onChange).not.toHaveBeenCalled();+ });+});diff --git a/skyvern-frontend/src/store/WorkflowYamlEditorStore.ts b/skyvern-frontend/src/store/WorkflowYamlEditorStore.tsindex 0b74cd8b4..31c55b103 100644--- a/skyvern-frontend/src/store/WorkflowYamlEditorStore.ts+++ b/skyvern-frontend/src/store/WorkflowYamlEditorStore.ts@@ -67,6 +67,17 @@ export function isWorkflowYamlDirty(state: {return state.draft !== state.entrySnapshot;}+// Fire `onChange` when the editable YAML draft changes while the Code editor is+// active. A draft edit doesn't touch the canvas, so canvas-derived effects miss+// it; subscribing to the draft lets them re-sync. Returns an unsubscribe.+export function subscribeToYamlDraftChanges(onChange: () => void): () => void {+ return useWorkflowYamlEditorStore.subscribe((state, prev) => {+ if (state.active && state.draft !== prev.draft) {+ onChange();+ }+ });+}+// Shared entry point for the commit-on-switch flow used by the overlay's Visual// toggle, the top-bar save, and the nav-blocker "Save changes" dialog. Guards// against a re-entrant commit and toggles the committing flag around it.