Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat: persist workflow studio block selection in URL (#6969)
Aaron Perezebb6f8f43cea
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsxindex e9b24497b..8f436facf 100644--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx@@ -108,6 +108,10 @@ import { cn } from "@/util/utils";import { FlowRenderer, type FlowRendererProps } from "./FlowRenderer";import { useCacheKeyValueUrlSync } from "./hooks/useCacheKeyValueUrlSync";+import {+ getInitialSelectedBlockId,+ useSelectedBlockUrlSync,+} from "./hooks/useSelectedBlockUrlSync";import { useSaveWorkflow } from "./hooks/useSaveWorkflow";import { useWorkspaceMountInitialization } from "./hooks/useWorkspaceMountInitialization";import { useWorkflowHistory } from "./hooks/useWorkflowHistory";@@ -850,11 +854,14 @@ function Workspace({const cacheKeyInitWpidRef = useRef<string | null>(null);useEffect(() => {// Studio defaults the selection to the start node on open (legacy keeps it- // empty); fires only on workflow change, so tab-switch selection persists.- const startNodeId = embedded- ? (initialNodes.find((node) => node.type === "start")?.id ?? null)- : null;- useWorkflowPanelStore.getState().setSelectedBlockId(startNodeId);+ // empty), unless the URL asks for a specific block; fires only on workflow+ // change, so tab-switch selection persists.+ const initialSelectedBlockId = getInitialSelectedBlockId({+ enabled: embedded,+ nodes: initialNodes,+ searchParams,+ });+ useWorkflowPanelStore.getState().setSelectedBlockId(initialSelectedBlockId);// The collapse flag is a module-level store, so it survives an in-session// A→B workflow nav; re-collapse here so every workflow opens to the rail.if (embedded) {@@ -948,6 +955,11 @@ function Workspace({});useCacheKeyValueUrlSync(cacheKeyInitWpidRef.current === workflowPermanentId);+ useSelectedBlockUrlSync({+ enabled: embedded,+ nodes,+ getNodes: getNodes as () => Array<AppNode>,+ });// Centralized function to manage comparison and panel statesconst clearComparisonViewAndShowFreshIfActive = useCallback(diff --git a/skyvern-frontend/src/routes/workflows/editor/hooks/useSelectedBlockUrlSync.test.tsx b/skyvern-frontend/src/routes/workflows/editor/hooks/useSelectedBlockUrlSync.test.tsxnew file mode 100644index 000000000..226913f0b--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/hooks/useSelectedBlockUrlSync.test.tsx@@ -0,0 +1,170 @@+// @vitest-environment jsdom++import type { ReactNode } from "react";+import { act, renderHook, waitFor } from "@testing-library/react";+import { MemoryRouter, useLocation, useNavigate } from "react-router-dom";+import { beforeEach, describe, expect, test } from "vitest";++import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";++import type { AppNode } from "../nodes";+import {+ getInitialSelectedBlockId,+ SELECTED_BLOCK_SEARCH_PARAM,+ useSelectedBlockUrlSync,+} from "./useSelectedBlockUrlSync";++const startNode = {+ id: "start-node",+ type: "start",+ data: { label: "__start_block__" },+} as AppNode;++const loginNode = {+ id: "login-node",+ type: "task",+ data: { label: "Login" },+} as AppNode;++const checkoutNode = {+ id: "checkout-node",+ type: "codeBlock",+ data: { label: "Checkout step" },+} as AppNode;++const nodes = [startNode, loginNode, checkoutNode];++function makeWrapper(initialEntry: string) {+ return ({ children }: { children: ReactNode }) => (+ <MemoryRouter initialEntries={[initialEntry]}>{children}</MemoryRouter>+ );+}++function useTestHarness(enabled = true) {+ useSelectedBlockUrlSync({ enabled, nodes });+ return useLocation();+}++function useTestHarnessWithNavigate(enabled = true) {+ useSelectedBlockUrlSync({ enabled, nodes });+ return { location: useLocation(), navigate: useNavigate() };+}++beforeEach(() => {+ useWorkflowPanelStore.getState().setSelectedBlockId(null);+});++describe("getInitialSelectedBlockId", () => {+ test("restores the matching workflow block in studio", () => {+ const searchParams = new URLSearchParams();+ searchParams.set(SELECTED_BLOCK_SEARCH_PARAM, "Login");++ expect(+ getInitialSelectedBlockId({ enabled: true, nodes, searchParams }),+ ).toBe("login-node");+ });++ test("falls back to the start node when the URL block is gone", () => {+ const searchParams = new URLSearchParams();+ searchParams.set(SELECTED_BLOCK_SEARCH_PARAM, "Removed block");++ expect(+ getInitialSelectedBlockId({ enabled: true, nodes, searchParams }),+ ).toBe("start-node");+ });++ test("keeps legacy editor selection empty", () => {+ const searchParams = new URLSearchParams();+ searchParams.set(SELECTED_BLOCK_SEARCH_PARAM, "Login");++ expect(+ getInitialSelectedBlockId({ enabled: false, nodes, searchParams }),+ ).toBeNull();+ });+});++describe("useSelectedBlockUrlSync", () => {+ test("restores selectedBlockId from the selected-block search param", async () => {+ useWorkflowPanelStore.getState().setSelectedBlockId("start-node");++ const { result } = renderHook(() => useTestHarness(), {+ wrapper: makeWrapper("/workflows/wpid_abc/studio?selected-block=Login"),+ });++ await waitFor(() => {+ expect(useWorkflowPanelStore.getState().selectedBlockId).toBe(+ "login-node",+ );+ });+ expect(result.current.search).toBe("?selected-block=Login");+ });++ test("mirrors block selection to the URL without dropping existing params", async () => {+ const { result } = renderHook(() => useTestHarness(), {+ wrapper: makeWrapper("/workflows/wpid_abc/studio?wr=run_1"),+ });++ act(() => {+ useWorkflowPanelStore.getState().setSelectedBlockId("checkout-node");+ });++ await waitFor(() => {+ expect(result.current.search).toBe(+ "?wr=run_1&selected-block=Checkout+step",+ );+ });+ });++ test("removes the selected-block param when the selected block is missing", async () => {+ const { result } = renderHook(() => useTestHarness(), {+ wrapper: makeWrapper(+ "/workflows/wpid_abc/studio?selected-block=Removed+block",+ ),+ });++ await waitFor(() => {+ expect(result.current.search).toBe("");+ });+ expect(useWorkflowPanelStore.getState().selectedBlockId).toBe("start-node");+ });++ test("clears a stale selected-block param instead of re-writing the previous selection", async () => {+ const { result } = renderHook(() => useTestHarnessWithNavigate(), {+ wrapper: makeWrapper("/workflows/wpid_abc/studio?selected-block=Login"),+ });++ await waitFor(() => {+ expect(useWorkflowPanelStore.getState().selectedBlockId).toBe(+ "login-node",+ );+ });++ act(() => {+ result.current.navigate(+ "/workflows/wpid_abc/studio?selected-block=Removed+block",+ );+ });++ await waitFor(() => {+ expect(result.current.location.search).toBe("");+ });+ // The param must stay cleared: selectedBlockId has to actually move off+ // "login-node", otherwise the mirror effect writes "Login" right back.+ expect(useWorkflowPanelStore.getState().selectedBlockId).toBe("start-node");+ expect(result.current.location.search).toBe("");+ });++ test("does not touch the URL outside the embedded studio", async () => {+ const { result } = renderHook(() => useTestHarness(false), {+ wrapper: makeWrapper("/workflows/wpid_abc/edit"),+ });++ act(() => {+ useWorkflowPanelStore.getState().setSelectedBlockId("login-node");+ });++ await waitFor(() => {+ expect(result.current.search).toBe("");+ });+ });+});diff --git a/skyvern-frontend/src/routes/workflows/editor/hooks/useSelectedBlockUrlSync.ts b/skyvern-frontend/src/routes/workflows/editor/hooks/useSelectedBlockUrlSync.tsnew file mode 100644index 000000000..f24e22912--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/hooks/useSelectedBlockUrlSync.ts@@ -0,0 +1,171 @@+import { useCallback, useEffect, useRef } from "react";+import { useSearchParams } from "react-router-dom";++import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";++import { type AppNode, isWorkflowBlockNode } from "../nodes";++export const SELECTED_BLOCK_SEARCH_PARAM = "selected-block";++function getStartNodeId(nodes: Array<AppNode>): string | null {+ return nodes.find((node) => node.type === "start")?.id ?? null;+}++// The URL key is the block's label, not its stable node id: renaming a block+// mid-session orphans any in-flight deep link, so a stale label falls back to+// the start node instead of resolving to the renamed block.+function getWorkflowBlockNodeIdByLabel(+ nodes: Array<AppNode>,+ blockLabel: string,+): string | null {+ return (+ nodes.find(+ (node) => isWorkflowBlockNode(node) && node.data.label === blockLabel,+ )?.id ?? null+ );+}++function getWorkflowBlockLabelByNodeId(+ nodes: Array<AppNode>,+ nodeId: string | null,+): string | null {+ if (nodeId === null) {+ return null;+ }++ const node = nodes.find((candidate) => candidate.id === nodeId);+ if (!node || !isWorkflowBlockNode(node)) {+ return null;+ }++ return node.data.label;+}++export function getInitialSelectedBlockId({+ enabled,+ nodes,+ searchParams,+}: {+ enabled: boolean;+ nodes: Array<AppNode>;+ searchParams: URLSearchParams;+}): string | null {+ if (!enabled) {+ return null;+ }++ const selectedBlockLabel = searchParams.get(SELECTED_BLOCK_SEARCH_PARAM);+ if (!selectedBlockLabel) {+ return getStartNodeId(nodes);+ }++ return (+ getWorkflowBlockNodeIdByLabel(nodes, selectedBlockLabel) ??+ getStartNodeId(nodes)+ );+}++type UseSelectedBlockUrlSyncOptions = {+ enabled: boolean;+ nodes: Array<AppNode>;+ getNodes?: () => Array<AppNode>;+};++export function useSelectedBlockUrlSync({+ enabled,+ nodes,+ getNodes,+}: UseSelectedBlockUrlSyncOptions): void {+ const [searchParams, setSearchParams] = useSearchParams();+ const selectedBlockId = useWorkflowPanelStore((s) => s.selectedBlockId);+ const setSelectedBlockId = useWorkflowPanelStore((s) => s.setSelectedBlockId);+ const suppressNextSelectionMirrorRef = useRef(false);+ const selectedBlockLabelParam = searchParams.get(SELECTED_BLOCK_SEARCH_PARAM);++ const getCurrentNodes = useCallback(() => {+ const latestNodes = getNodes?.();+ return latestNodes && latestNodes.length > 0 ? latestNodes : nodes;+ }, [getNodes, nodes]);++ useEffect(() => {+ if (!enabled || !selectedBlockLabelParam) {+ return;+ }++ const currentNodes = getCurrentNodes();+ const matchedNodeId = getWorkflowBlockNodeIdByLabel(+ currentNodes,+ selectedBlockLabelParam,+ );+ if (!matchedNodeId) {+ setSearchParams(+ (prev) => {+ const next = new URLSearchParams(prev);+ next.delete(SELECTED_BLOCK_SEARCH_PARAM);+ return next;+ },+ { replace: true },+ );+ }++ // Must actually move selectedBlockId off the stale block, not just skip+ // this mirror cycle: leaving it pointed at the old (still valid)+ // selection means the very next mirror run recomputes that block's+ // label and writes it straight back into the just-cleared URL.+ const targetNodeId = matchedNodeId ?? getStartNodeId(currentNodes);+ const currentSelectedBlockId =+ useWorkflowPanelStore.getState().selectedBlockId;+ if (currentSelectedBlockId !== targetNodeId) {+ suppressNextSelectionMirrorRef.current = true;+ setSelectedBlockId(targetNodeId);+ }+ }, [+ enabled,+ getCurrentNodes,+ selectedBlockLabelParam,+ setSearchParams,+ setSelectedBlockId,+ ]);++ useEffect(() => {+ if (!enabled) {+ return;+ }++ // Relies on the URL->store effect above running first each render and+ // setting this flag when it moves selectedBlockId; if the two effects+ // are ever reordered, this suppression stops working.+ if (suppressNextSelectionMirrorRef.current) {+ suppressNextSelectionMirrorRef.current = false;+ return;+ }++ const selectedBlockLabel = getWorkflowBlockLabelByNodeId(+ getCurrentNodes(),+ selectedBlockId,+ );+ const currentUrlLabel = searchParams.get(SELECTED_BLOCK_SEARCH_PARAM);+ if (currentUrlLabel === selectedBlockLabel) {+ return;+ }++ setSearchParams(+ (prev) => {+ const next = new URLSearchParams(prev);+ if (selectedBlockLabel) {+ next.set(SELECTED_BLOCK_SEARCH_PARAM, selectedBlockLabel);+ } else {+ next.delete(SELECTED_BLOCK_SEARCH_PARAM);+ }+ return next;+ },+ { replace: true },+ );+ }, [+ enabled,+ getCurrentNodes,+ searchParams,+ selectedBlockId,+ setSearchParams,+ ]);+}