Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-12378): prefill run inputs when re-running from a viewed run in Studio (#7388)
Celal Zamanoğlu868a5474b06b
diff --git a/skyvern-frontend/src/routes/workflows/studio/RunTab.test.tsx b/skyvern-frontend/src/routes/workflows/studio/RunTab.test.tsxindex 46dd61433..e70ec4a0f 100644--- a/skyvern-frontend/src/routes/workflows/studio/RunTab.test.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/RunTab.test.tsx@@ -1,16 +1,24 @@// @vitest-environment jsdom-import { cleanup, render, screen } from "@testing-library/react";-import { MemoryRouter } from "react-router-dom";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { ProxyLocation, Status } from "@/api/types";import { RunTab } from "./RunTab";-const { runsQueryMock } = vi.hoisted(() => ({ runsQueryMock: vi.fn() }));+const { runsQueryMock, workflowRunQueryMock } = vi.hoisted(() => ({+ runsQueryMock: vi.fn(),+ workflowRunQueryMock: vi.fn(),+}));vi.mock("../hooks/useWorkflowRunsQuery", () => ({useWorkflowRunsQuery: () => runsQueryMock(),}));+vi.mock("../hooks/useWorkflowRunWithWorkflowQuery", () => ({+ useWorkflowRunWithWorkflowQuery: (options?: { workflowRunId?: string }) =>+ workflowRunQueryMock(options),+}));vi.mock("./runview/RunView", () => ({RunView: (props: { onRetry?: () => void; runIdPending?: boolean }) => (@@ -18,19 +26,74 @@ vi.mock("./runview/RunView", () => ({data-testid="runview"data-has-retry={props.onRetry ? "yes" : "no"}data-run-id-pending={props.runIdPending ? "yes" : "no"}- />+ >+ {props.onRetry ? (+ <button type="button" onClick={props.onRetry}>+ Retry as-is+ </button>+ ) : null}+ </div>),}));-afterEach(cleanup);-beforeEach(() => runsQueryMock.mockReturnValue({ data: [], isPending: false }));+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});+beforeEach(() => {+ runsQueryMock.mockReturnValue({ data: [], isPending: false });+ workflowRunQueryMock.mockReturnValue({ data: undefined });+});++function mockWorkflowRun(overrides: Record<string, unknown> = {}) {+ workflowRunQueryMock.mockReturnValue({+ data: {+ workflow_run_id: "run_1",+ status: Status.Failed,+ parameters: { query: "status report", payload: ["alpha"] },+ proxy_location: ProxyLocation.ResidentialDE,+ webhook_callback_url: "https://example.com/webhook",+ max_screenshot_scrolls: 8,+ run_with: "code",+ browser_profile_id: "profile_synthetic",+ task_v2: null,+ workflow: { deleted_at: null },+ ...overrides,+ },+ });+}++function LocationProbe() {+ const location = useLocation();+ return (+ <>+ <div data-testid="location">{location.pathname}</div>+ <div data-testid="location-state">+ {JSON.stringify(location.state ?? null)}+ </div>+ </>+ );+}++function locationState() {+ return JSON.parse(screen.getByTestId("location-state").textContent ?? "null");+}// useStudioRunId reads ?wr= from the router, so the MemoryRouter URL drives it// (and ?bl=, which RunTab reads directly) — no hook mock needed.function renderAt(path: string) {return render(<MemoryRouter initialEntries={[path]}>- <RunTab />+ <Routes>+ <Route+ path="/workflows/:workflowPermanentId/studio"+ element={<RunTab />}+ />+ <Route+ path="/agents/:workflowPermanentId/run"+ element={<LocationProbe />}+ />+ </Routes></MemoryRouter>,);}@@ -51,6 +114,62 @@ describe("RunTab block-scoped retry", () => {});});+describe("RunTab retry navigation", () => {+ test("an explicit failed workflow run retries with the legacy state", () => {+ mockWorkflowRun();+ renderAt("/workflows/wpid_abc/studio?wr=run_1");++ fireEvent.click(screen.getByRole("button", { name: "Retry as-is" }));++ expect(screen.getByTestId("location").textContent).toBe(+ "/agents/wpid_abc/run",+ );+ expect(locationState()).toEqual({+ data: { query: "status report", payload: ["alpha"] },+ proxyLocation: ProxyLocation.ResidentialDE,+ webhookCallbackUrl: "https://example.com/webhook",+ maxScreenshotScrolls: 8,+ runWith: "code",+ browserProfileId: "profile_synthetic",+ });+ });++ test("the latest-run fallback retries the inspected run with state", () => {+ runsQueryMock.mockReturnValue({+ data: [{ workflow_run_id: "run_latest" }],+ isPending: false,+ });+ mockWorkflowRun({ workflow_run_id: "run_latest" });+ renderAt("/workflows/wpid_abc/studio");++ fireEvent.click(screen.getByRole("button", { name: "Retry as-is" }));++ expect(workflowRunQueryMock).toHaveBeenCalledWith({+ workflowRunId: "run_latest",+ });+ expect(locationState()).toEqual({+ data: { query: "status report", payload: ["alpha"] },+ proxyLocation: ProxyLocation.ResidentialDE,+ webhookCallbackUrl: "https://example.com/webhook",+ maxScreenshotScrolls: 8,+ runWith: "code",+ browserProfileId: "profile_synthetic",+ });+ });++ test("a task run keeps the existing state-less retry", () => {+ mockWorkflowRun({ task_v2: { task_id: "task_synthetic" } });+ renderAt("/workflows/wpid_abc/studio?wr=run_1");++ fireEvent.click(screen.getByRole("button", { name: "Retry as-is" }));++ expect(screen.getByTestId("location").textContent).toBe(+ "/agents/wpid_abc/run",+ );+ expect(locationState()).toBeNull();+ });+});+describe("RunTab run-id resolution", () => {test("marks the run id pending while the recent-runs query is loading", () => {runsQueryMock.mockReturnValue({ data: undefined, isPending: true });diff --git a/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx b/skyvern-frontend/src/routes/workflows/studio/RunTab.tsxindex aea9dac33..504de30c5 100644--- a/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx@@ -1,5 +1,8 @@import { useNavigate, useParams, useSearchParams } from "react-router-dom";+import { statusIsFinalized } from "@/routes/tasks/types";+import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";+import { getRerunNavigationState } from "../utils";import { RunView } from "./runview/RunView";import { useStudioInspectedRun } from "./useStudioInspectedRun";import { useStudioPanes } from "./useStudioPanes";@@ -16,12 +19,28 @@ export function RunTab() {const { workflowPermanentId } = useParams();const { openPane } = useStudioPanes();const { runId, pending } = useStudioInspectedRun();+ const { data: workflowRun } = useWorkflowRunWithWorkflowQuery(+ runId ? { workflowRunId: runId } : undefined,+ );// Fix (Copilot) and Retry both mutate/rerun the workflow — gone with the// source agent, so the CTAs go too (the run stays viewable).const workflowDeleted = useStudioWorkflowDeletedAt() !== null;// ?bl= marks a block-scoped run; "Retry as-is" would rerun the whole workflow,// so suppress that CTA for block runs (the block is rerun from the editor).const isBlockRun = searchParams.has("bl");+ const retryRun = () => {+ const path = `/agents/${workflowPermanentId}/run`;+ if (+ workflowRun &&+ workflowRun.workflow_run_id === runId &&+ statusIsFinalized(workflowRun) &&+ workflowRun.task_v2 === null+ ) {+ navigate(path, { state: getRerunNavigationState(workflowRun) });+ return;+ }+ navigate(path);+ };return (<RunView@@ -40,13 +59,7 @@ export function RunTab() {});}}- onRetry={- isBlockRun || workflowDeleted- ? undefined- : // The post-start navigate resets the layout to the run mapping,- // so the form round-trip carries nothing.- () => navigate(`/agents/${workflowPermanentId}/run`)- }+ onRetry={isBlockRun || workflowDeleted ? undefined : retryRun}/>);}diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.test.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.test.tsxindex 522070c9c..b321654d3 100644--- a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.test.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.test.tsx@@ -5,7 +5,7 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react";import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";-import { Status } from "@/api/types";+import { ProxyLocation, Status } from "@/api/types";import { TooltipProvider } from "@/components/ui/tooltip";const { workflowRunQueryMock } = vi.hoisted(() => ({@@ -25,10 +25,15 @@ import { RunStopButton } from "./StudioTopBar";function LocationProbe() {const location = useLocation();return (- <div data-testid="location">- {location.pathname}- {location.search}- </div>+ <>+ <div data-testid="location">+ {location.pathname}+ {location.search}+ </div>+ <div data-testid="location-state">+ {JSON.stringify(location.state ?? null)}+ </div>+ </>);}@@ -56,12 +61,28 @@ function renderAt(path: string, element = <RunStopButton />) {);}-function mockRun(status: Status) {+function mockRun(status: Status, overrides: Record<string, unknown> = {}) {workflowRunQueryMock.mockReturnValue({- data: { workflow_run_id: "wr_1", status },+ data: {+ workflow_run_id: "wr_1",+ status,+ parameters: { query: "status report", payload: ["alpha"] },+ proxy_location: ProxyLocation.ResidentialDE,+ webhook_callback_url: "https://example.com/webhook",+ max_screenshot_scrolls: 8,+ run_with: "code",+ browser_profile_id: "profile_synthetic",+ task_v2: null,+ workflow: { deleted_at: null },+ ...overrides,+ },});}+function locationState() {+ return JSON.parse(screen.getByTestId("location-state").textContent ?? "null");+}+afterEach(() => {cleanup();vi.clearAllMocks();@@ -83,11 +104,10 @@ describe("RunStopButton concurrency with a live block run", () => {expect(screen.queryByTestId("location")).toBeNull();fireEvent.click(screen.getByRole("button", { name: "Start full run" }));- // The form carries nothing: the post-start navigation resets the layout- // to the run mapping (copilot, browser, overview).expect(screen.getByTestId("location").textContent).toBe("/agents/wpid_1/run",);+ expect(locationState()).toBeNull();});test("the confirm can be declined without navigating", () => {@@ -106,23 +126,81 @@ describe("RunStopButton concurrency with a live block run", () => {expect(screen.queryByRole("button", { name: /Run/ })).toBeNull();});- test("an idle workflow starts a run directly, with no confirm", () => {+ test("a finalized workflow run reruns with the legacy navigation state", () => {mockRun(Status.Completed);renderAt("/workflows/wpid_1/studio?wr=wr_1");- fireEvent.click(screen.getByRole("button", { name: /Run/ }));+ fireEvent.click(screen.getByRole("button", { name: "Re-run agent" }));expect(screen.queryByText("Start a full run?")).toBeNull();expect(screen.getByTestId("location").textContent).toBe("/agents/wpid_1/run",);+ expect(locationState()).toEqual({+ data: { query: "status report", payload: ["alpha"] },+ proxyLocation: ProxyLocation.ResidentialDE,+ webhookCallbackUrl: "https://example.com/webhook",+ maxScreenshotScrolls: 8,+ runWith: "code",+ browserProfileId: "profile_synthetic",+ });+ });++ test("no focused run starts fresh", () => {+ workflowRunQueryMock.mockReturnValue({ data: undefined });+ renderAt("/workflows/wpid_1/studio");++ fireEvent.click(screen.getByRole("button", { name: "Run agent" }));++ expect(screen.getByTestId("location").textContent).toBe(+ "/agents/wpid_1/run",+ );+ expect(locationState()).toBeNull();+ });++ test("a stale prior run (id mismatches the URL) does not seed a rerun", () => {+ // keepPreviousData can surface the previously focused run after the URL run+ // clears/changes; its id no longer matches, so the button stays fresh.+ mockRun(Status.Completed, { workflow_run_id: "wr_previous" });+ renderAt("/workflows/wpid_1/studio?wr=wr_1");++ fireEvent.click(screen.getByRole("button", { name: "Run agent" }));++ expect(screen.getByTestId("location").textContent).toBe(+ "/agents/wpid_1/run",+ );+ expect(locationState()).toBeNull();+ });++ test("a finalized block run starts a fresh full run", () => {+ mockRun(Status.Completed);+ renderAt("/workflows/wpid_1/studio?wr=wr_1&bl=Block%201");++ fireEvent.click(screen.getByRole("button", { name: "Run agent" }));++ expect(screen.getByTestId("location").textContent).toBe(+ "/agents/wpid_1/run",+ );+ expect(locationState()).toBeNull();+ });++ test("a finalized task run starts fresh", () => {+ mockRun(Status.Failed, { task_v2: { task_id: "task_synthetic" } });+ renderAt("/workflows/wpid_1/studio?wr=wr_1");++ fireEvent.click(screen.getByRole("button", { name: "Run agent" }));++ expect(screen.getByTestId("location").textContent).toBe(+ "/agents/wpid_1/run",+ );+ expect(locationState()).toBeNull();});test("an editor-open layout is NOT carried into the run form (full runs reset)", () => {mockRun(Status.Completed);renderAt("/workflows/wpid_1/studio?wr=wr_1&panes=editor,copilot");- fireEvent.click(screen.getByRole("button", { name: /Run/ }));+ fireEvent.click(screen.getByRole("button", { name: "Re-run agent" }));expect(screen.getByTestId("location").textContent).toBe("/agents/wpid_1/run",diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsxindex e61e7e2ea..9abe8b25e 100644--- a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx@@ -28,6 +28,7 @@ import { useRecordingStore } from "@/store/useRecordingStore";import { useWorkflowHasChangesStore } from "@/store/WorkflowHasChangesStore";import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";import { useWorkflowTitleStore } from "@/store/WorkflowTitleStore";+import { statusIsFinalized } from "@/routes/tasks/types";import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";import { cn } from "@/util/utils";@@ -38,6 +39,7 @@ import { useSaveWorkflow } from "../editor/hooks/useSaveWorkflow";import { useToggleHistoryPanel } from "../editor/hooks/useToggleHistoryPanel";import { useIsGlobalWorkflow } from "../hooks/useIsGlobalWorkflow";import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";+import { getRerunNavigationState } from "../utils";import { runOutcomeFromStatus } from "./runProjections";import { ControlTooltip } from "./ControlTooltip";import { PaneHeaderDivider } from "./PaneHeaderDivider";@@ -151,6 +153,16 @@ export function RunStopButton({ stopOnly = false }: { stopOnly?: boolean }) {// ?bl= marks the URL run as a block run; a full run can start alongside it// (they execute concurrently), so Run stays available next to Stop.const isBlockRun = searchParams.has("bl");+ const rerunEligible = Boolean(+ workflowRun &&+ // keepPreviousData can surface a prior run after the focused run clears/changes;+ // only treat it as the focused run when its id matches the URL.+ workflowRun.workflow_run_id === runId &&+ statusIsFinalized(workflowRun) &&+ workflowRun.task_v2 === null &&+ !isBlockRun &&+ !workflowRun.workflow?.deleted_at,+ );const cancelRun = useMutation({mutationFn: async () => {@@ -182,12 +194,14 @@ export function RunStopButton({ stopOnly = false }: { stopOnly?: boolean }) {// ?panes= rides through the run form so the post-start navigate restores// this exact layout (plus the run surfaces appended) instead of remapping.- const startFullRun = () =>- navigate(- // The post-start navigate resets the layout to the run mapping, so the- // form round-trip carries nothing.- `/agents/${workflowPermanentId}/run`,- );+ const startFullRun = () => {+ const path = `/agents/${workflowPermanentId}/run`;+ if (rerunEligible && workflowRun) {+ navigate(path, { state: getRerunNavigationState(workflowRun) });+ return;+ }+ navigate(path);+ };if (running && activeRunId) {const stopDialog = (@@ -276,7 +290,8 @@ export function RunStopButton({ stopOnly = false }: { stopOnly?: boolean }) {disabled={isRecording}onClick={startFullRun}>- <PlayIcon className="mr-2 size-4" /> Run agent+ <PlayIcon className="mr-2 size-4" />+ {rerunEligible ? "Re-run agent" : "Run agent"}</Button>);}diff --git a/skyvern-frontend/src/routes/workflows/utils.test.ts b/skyvern-frontend/src/routes/workflows/utils.test.tsindex 43d4dad16..6b11e6c06 100644--- a/skyvern-frontend/src/routes/workflows/utils.test.ts+++ b/skyvern-frontend/src/routes/workflows/utils.test.ts@@ -1,11 +1,97 @@import { describe, expect, it } from "vitest";import {+ ProxyLocation,+ type WorkflowRunStatusApiResponseWithWorkflow,+} from "@/api/types";+import type { WorkflowParameter } from "./types/workflowTypes";+import {+ getInitialValues,+ getRerunNavigationState,normalizeJsonParameterFormValue,parseJsonWorkflowParameterValue,validateJsonWorkflowParameterValue,} from "./utils";+function buildWorkflowRun(+ overrides: Partial<WorkflowRunStatusApiResponseWithWorkflow> = {},+): WorkflowRunStatusApiResponseWithWorkflow {+ return {+ parameters: { query: "status report", payload: ["alpha"] },+ proxy_location: ProxyLocation.ResidentialDE,+ webhook_callback_url: "https://example.com/webhook",+ max_screenshot_scrolls: 8,+ run_with: "code",+ browser_profile_id: "profile_synthetic",+ extra_http_headers: { "X-Test": "synthetic" },+ ...overrides,+ } as WorkflowRunStatusApiResponseWithWorkflow;+}++describe("getRerunNavigationState", () => {+ it("maps exactly the six legacy rerun fields", () => {+ const state = getRerunNavigationState(buildWorkflowRun());++ expect(state).toEqual({+ data: { query: "status report", payload: ["alpha"] },+ proxyLocation: ProxyLocation.ResidentialDE,+ webhookCallbackUrl: "https://example.com/webhook",+ maxScreenshotScrolls: 8,+ runWith: "code",+ browserProfileId: "profile_synthetic",+ });+ expect(state).not.toHaveProperty("extraHttpHeaders");+ expect(state).not.toHaveProperty("cdpConnectHeaders");+ expect(state).not.toHaveProperty("cdpAddress");+ });++ it("matches the legacy nullish fallbacks", () => {+ const workflowRun = {+ parameters: null,+ proxy_location: null,+ webhook_callback_url: null,+ max_screenshot_scrolls: null,+ run_with: null,+ browser_profile_id: null,+ } as unknown as WorkflowRunStatusApiResponseWithWorkflow;++ expect(getRerunNavigationState(workflowRun)).toEqual({+ data: {},+ proxyLocation: ProxyLocation.Residential,+ webhookCallbackUrl: "",+ maxScreenshotScrolls: null,+ runWith: "agent",+ browserProfileId: null,+ });+ });++ it("flows rerun data through initial values with JSON normalization", () => {+ const state = getRerunNavigationState(buildWorkflowRun());+ const workflowParameters = [+ {+ parameter_type: "workflow",+ key: "query",+ workflow_parameter_type: "string",+ },+ {+ parameter_type: "workflow",+ key: "payload",+ workflow_parameter_type: "json",+ },+ ] as WorkflowParameter[];++ expect(+ getInitialValues(+ { state } as Parameters<typeof getInitialValues>[0],+ workflowParameters,+ ),+ ).toEqual({+ query: "status report",+ payload: '[\n "alpha"\n]',+ });+ });+});+describe("parseJsonWorkflowParameterValue", () => {it("parses a JSON array string", () => {expect(parseJsonWorkflowParameterValue('["1002763917"]')).toEqual([diff --git a/skyvern-frontend/src/routes/workflows/utils.ts b/skyvern-frontend/src/routes/workflows/utils.tsindex 503362cd3..a57755f8a 100644--- a/skyvern-frontend/src/routes/workflows/utils.ts+++ b/skyvern-frontend/src/routes/workflows/utils.ts@@ -1,9 +1,26 @@import { useLocation } from "react-router-dom";+import {+ ProxyLocation,+ type WorkflowRunStatusApiResponseWithWorkflow,+} from "@/api/types";import type { Parameter, WorkflowParameter } from "./types/workflowTypes";import { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";type Location = ReturnType<typeof useLocation>;+export function getRerunNavigationState(+ workflowRun: WorkflowRunStatusApiResponseWithWorkflow,+) {+ return {+ data: workflowRun.parameters ?? {},+ proxyLocation: workflowRun.proxy_location ?? ProxyLocation.Residential,+ webhookCallbackUrl: workflowRun.webhook_callback_url ?? "",+ maxScreenshotScrolls: workflowRun.max_screenshot_scrolls ?? null,+ runWith: workflowRun.run_with ?? "agent",+ browserProfileId: workflowRun.browser_profile_id ?? null,+ };+}+/*** Keep JSON workflow parameters as editable strings in react-hook-form state.* Parsed arrays/objects from API re-runs are stringified so CodeEditor state