Skip to content

Automate browser based workflows with AI

Add workflow retry policy settings and attempt-aware run views (SKY-15802) (#8558)

Shuchang Zhengcf65e535bb7f
diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.ts
index dad701c89..ae91df9fc 100644
--- a/skyvern-frontend/src/api/types.ts
+++ b/skyvern-frontend/src/api/types.ts
@@ -804,6 +804,26 @@ export type DebugLoginBlockCompatibilityResponse = {
reason: "pbs_no_profile" | "pbs_different_profile" | null;
};
+export type WorkflowRunAttempt = {
+ attempt_number: number;
+ status: Status;
+ failure_reason: string | null;
+ error_codes: Array<string>;
+ started_at: string | null;
+ finished_at: string | null;
+ retry_decision: string | null;
+ decision_reason: string | null;
+ next_attempt_at: string | null;
+ webhook_sent_at: string | null;
+};
+
+export type WorkflowRunRetryFields = {
+ attempt?: number;
+ retry_pending?: boolean;
+ next_attempt_at?: string | null;
+ attempts?: Array<WorkflowRunAttempt>;
+};
+
export type WorkflowRunApiResponse = {
created_at: string;
failure_reason: string | null;
@@ -825,7 +845,10 @@ export type WorkflowRunApiResponse = {
workflow_run_id: string;
workflow_title: string | null;
retried_from_workflow_run_id?: string | null;
-};
+} & Pick<
+ WorkflowRunRetryFields,
+ "attempt" | "retry_pending" | "next_attempt_at"
+>;
export const TaskRunType = {
TaskV1: "task_v1",
@@ -853,7 +876,10 @@ export type TaskRunListItem = {
script_run: boolean;
trigger_type?: TriggerType | null;
searchable_text: string | null;
-};
+} & Pick<
+ WorkflowRunRetryFields,
+ "attempt" | "retry_pending" | "next_attempt_at"
+>;
export type WorkflowRunStatusApiResponse = {
workflow_id: string;
@@ -896,7 +922,7 @@ export type WorkflowRunStatusApiResponse = {
verification_code_polling_started_at?: string | null;
retried_from_workflow_run_id?: string | null;
retried_by_workflow_run_id?: string | null;
-};
+} & WorkflowRunRetryFields;
export type WorkflowRunStatusApiResponseWithWorkflow = {
workflow_id: string;
@@ -940,7 +966,7 @@ export type WorkflowRunStatusApiResponseWithWorkflow = {
verification_code_polling_started_at?: string | null;
retried_from_workflow_run_id?: string | null;
retried_by_workflow_run_id?: string | null;
-};
+} & WorkflowRunRetryFields;
export type TaskGenerationApiResponse = {
suggested_title: string | null;
diff --git a/skyvern-frontend/src/components/ApiWebhookActionsMenu.tsx b/skyvern-frontend/src/components/ApiWebhookActionsMenu.tsx
index 2c11e1bcf..d653ad36b 100644
--- a/skyvern-frontend/src/components/ApiWebhookActionsMenu.tsx
+++ b/skyvern-frontend/src/components/ApiWebhookActionsMenu.tsx
@@ -25,6 +25,7 @@ type ApiWebhookActionsMenuProps = {
getOptions: () => ApiCommandOptions;
runId?: string;
webhookDisabled?: boolean;
+ disabledReason?: string;
onTestWebhook: () => void;
size?: "default" | "sm";
// Single element forwarded to the trigger via Radix `asChild`; when set,
@@ -37,6 +38,7 @@ type ApiWebhookActionsMenuProps = {
export function ApiWebhookActionsMenu({
getOptions,
webhookDisabled = false,
+ disabledReason,
onTestWebhook,
size = "default",
trigger,
@@ -105,7 +107,12 @@ export function ApiWebhookActionsMenu({
setTimeout(() => onTestWebhook(), 0);
}}
>
- Test Webhook
+ <span>Test Webhook</span>
+ {webhookDisabled && disabledReason ? (
+ <span className="ml-2 text-xs text-muted-foreground">
+ {disabledReason}
+ </span>
+ ) : null}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
diff --git a/skyvern-frontend/src/components/WorkflowRunAttemptChip.tsx b/skyvern-frontend/src/components/WorkflowRunAttemptChip.tsx
new file mode 100644
index 000000000..d607c8fac
--- /dev/null
+++ b/skyvern-frontend/src/components/WorkflowRunAttemptChip.tsx
@@ -0,0 +1,49 @@
+import { UpdateIcon } from "@radix-ui/react-icons";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { basicLocalTimeFormat } from "@/util/timeFormat";
+import { cn } from "@/util/utils";
+
+type Props = {
+ attempt?: number;
+ retryPending?: boolean;
+ nextAttemptAt?: string | null;
+ className?: string;
+};
+
+export function WorkflowRunAttemptChip({
+ attempt = 1,
+ retryPending = false,
+ nextAttemptAt,
+ className,
+}: Props) {
+ if (attempt === 1 && !retryPending) return null;
+ const label = retryPending ? "Retry pending" : `Attempt ${attempt}`;
+ const description = retryPending
+ ? `Attempt ${attempt} ended. Next attempt ${nextAttemptAt ? `at ${basicLocalTimeFormat(nextAttemptAt)}` : "soon"}`
+ : label;
+ return (
+ <TooltipProvider delayDuration={200}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span
+ role="img"
+ aria-label={description}
+ className={cn(
+ "inline-flex shrink-0 items-center gap-1 rounded-md text-xs text-blue-400 outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ className,
+ )}
+ >
+ <UpdateIcon className="size-3.5" />
+ {label}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{description}</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
diff --git a/skyvern-frontend/src/routes/history/RunHistory.test.tsx b/skyvern-frontend/src/routes/history/RunHistory.test.tsx
index bb4180a00..60667e5d2 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.test.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.test.tsx
@@ -369,3 +369,12 @@ describe("RunHistory inputs during filtering", () => {
);
});
});
+
+describe("RunHistory refetch policy", () => {
+ it("leaves filtered list refreshes to the existing query policy", () => {
+ renderRunHistory();
+ expect(runsQueryCalls.length).toBeGreaterThan(0);
+ for (const options of runsQueryCalls)
+ expect(options.refetchInterval).toBeUndefined();
+ });
+});
diff --git a/skyvern-frontend/src/routes/history/RunHistory.tsx b/skyvern-frontend/src/routes/history/RunHistory.tsx
index 61b3a4af6..d478c0c86 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.tsx
@@ -20,6 +20,7 @@ import {
WorkflowRunStatusApiResponse,
} from "@/api/types";
import { StatusBadge } from "@/components/StatusBadge";
+import { WorkflowRunAttemptChip } from "@/components/WorkflowRunAttemptChip";
import { StatusFilterDropdown } from "@/components/StatusFilterDropdown";
import { AgentFilterDropdown } from "@/components/AgentFilterDropdown";
import {
@@ -490,7 +491,7 @@ function RunHistory() {
</div>
</TableCell>
<TableCell>
- <div className="flex items-center gap-1.5">
+ <div className="flex flex-wrap items-center gap-1.5">
{isKnownStatus(run.status) ? (
<StatusBadge status={run.status} />
) : (
@@ -498,6 +499,11 @@ function RunHistory() {
{run.status}
</span>
)}
+ <WorkflowRunAttemptChip
+ attempt={run.attempt}
+ retryPending={run.retry_pending}
+ nextAttemptAt={run.next_attempt_at}
+ />
<RunOutcomeRiskMarker
outcomeRisk={
(runHealMap[run.run_id]?.blocks_outcome_risk?.length ?? 0) > 0
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
index 7b4f6eef7..1ad20de3c 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
@@ -440,3 +440,10 @@ describe("Past Runs list state in the URL", () => {
expect(locationSearch(container)).not.toContain("status=");
});
});
+
+it("refetches the history on mount without adding list polling", () => {
+ renderWorkflowPage();
+ const options = mockWorkflowRunsQuery.mock.lastCall?.[0];
+ expect(options.refetchOnMount).toBe("always");
+ expect(options.refetchInterval).toBeUndefined();
+});
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
index 2243f609f..591197f63 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
@@ -10,6 +10,7 @@ import {
import { Tip } from "@/components/Tip";
import { WorkflowRunStatusApiResponse } from "@/api/types";
import { StatusBadge } from "@/components/StatusBadge";
+import { WorkflowRunAttemptChip } from "@/components/WorkflowRunAttemptChip";
import { CredentialFallbackRetryBadge } from "@/components/CredentialFallbackRetryBadge";
import { StatusFilterDropdown } from "@/components/StatusFilterDropdown";
import { Button } from "@/components/ui/button";
@@ -520,6 +521,11 @@ function WorkflowPage() {
<TableCell>
<div className="flex items-center gap-2">
<StatusBadge status={workflowRun.status} />
+ <WorkflowRunAttemptChip
+ attempt={workflowRun.attempt}
+ retryPending={workflowRun.retry_pending}
+ nextAttemptAt={workflowRun.next_attempt_at}
+ />
<CredentialFallbackRetryBadge
retriedFromWorkflowRunId={
workflowRun.retried_from_workflow_run_id
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx b/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx
index 853c2eda2..293dfa8d6 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx
@@ -1,9 +1,18 @@
+import { useRunCompletionToast } from "./workflowRun/useRunCompletionToast";
+import { claimRunCompletionNotice } from "@/routes/workflows/workflowRun/runCompletionNotices";
+import {
+ getRunAttempt,
+ runIsRetryWaiting,
+ runIsCancellable,
+ runIsLogicallyFinal,
+} from "@/routes/workflows/workflowRun/runRetryState";
import { AxiosError } from "axios";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { getClient } from "@/api/AxiosClient";
import { ProxyLocation, Status } from "@/api/types";
import { FailureCategoryBadge } from "@/components/FailureCategoryBadge";
import { StatusBadge } from "@/components/StatusBadge";
+import { WorkflowRunAttemptChip } from "@/components/WorkflowRunAttemptChip";
import { CredentialFallbackRetryBadge } from "@/components/CredentialFallbackRetryBadge";
import {
SwitchBarNavigation,
@@ -48,7 +57,6 @@ import {
runOverviewScreenshotLocation,
runViewTabBasePath,
} from "@/routes/runs/runViewTabBasePath";
-import { statusIsCancellable, statusIsFinalized } from "../tasks/types";
import { useWorkflowRunWithWorkflowQuery } from "./hooks/useWorkflowRunWithWorkflowQuery";
import { useRefreshOnboardingOnRunCompletion } from "./hooks/useRefreshOnboardingOnRunCompletion";
import { ResizableTimelineSplit } from "./workflowRun/ResizableTimelineSplit";
@@ -56,6 +64,7 @@ import { WorkflowRunBlockDetail } from "./workflowRun/WorkflowRunBlockDetail";
import { WorkflowRunTimeline } from "./workflowRun/WorkflowRunTimeline";
import { useWorkflowRunTimelineQuery } from "./hooks/useWorkflowRunTimelineQuery";
import {
+ filterTimelineToAttempt,
findActiveItem,
parseActiveIterationParam,
} from "./workflowRun/workflowTimelineUtils";
@@ -199,6 +208,7 @@ function WorkflowRun() {
} = useWorkflowRunWithWorkflowQuery();
useRefreshOnboardingOnRunCompletion(workflowRun);
+ useRunCompletionToast(workflowRunIsPlaceholder ? undefined : workflowRun);
const recoveryGuidanceRetry = getRecoveryGuidanceRetryNavigation(
location.state,
);
@@ -234,7 +244,7 @@ function WorkflowRun() {
const workflowPermanentId =
workflowPermanentIdParam ?? workflow?.workflow_permanent_id;
const cacheKey = workflow?.cache_key ?? "";
- const isFinalized = workflowRun ? statusIsFinalized(workflowRun) : null;
+ const isFinalized = workflowRun ? runIsLogicallyFinal(workflowRun) : null;
const isWorkflowDeleted = Boolean(workflow?.deleted_at);
const [hasPublishedCode, setHasPublishedCode] = useState(false);
@@ -301,11 +311,15 @@ function WorkflowRun() {
queryClient.invalidateQueries({
queryKey: ["workflowRun", workflowPermanentId, workflowRunId],
});
- toast({
- variant: "success",
- title: "Agent Canceled",
- description: "The agent has been successfully canceled.",
- });
+ if (workflowRunId) {
+ claimRunCompletionNotice(workflowRunId, () => {
+ toast({
+ variant: "success",
+ title: "Agent Canceled",
+ description: "The agent has been successfully canceled.",
+ });
+ });
+ }
},
onError: (error) => {
toast({
@@ -318,9 +332,10 @@ function WorkflowRun() {
const statusUnavailable = Boolean(error);
const workflowRunIsCancellable =
- !statusUnavailable && workflowRun && statusIsCancellable(workflowRun);
+ !statusUnavailable && workflowRun && runIsCancellable(workflowRun);
- const workflowRunIsFinalized = workflowRun && statusIsFinalized(workflowRun);
+ const workflowRunIsFinalized =
+ workflowRun && runIsLogicallyFinal(workflowRun);
const { data: fallbackEpisodes } = useFallbackEpisodesQuery({
workflowPermanentId,
@@ -329,8 +344,13 @@ function WorkflowRun() {
});
const finallyBlockLabel =
workflow?.workflow_definition?.finally_block_label ?? null;
- const selection = findActiveItem(
+ const currentAttemptTimeline = filterTimelineToAttempt(
workflowRunTimeline ?? [],
+ workflowRun?.attempts ?? [],
+ getRunAttempt(workflowRun ?? {}),
+ );
+ const selection = findActiveItem(
+ active === null ? currentAttemptTimeline : (workflowRunTimeline ?? []),
active,
!!workflowRunIsFinalized,
finallyBlockLabel,
@@ -365,7 +385,7 @@ function WorkflowRun() {
const codeFailure = findRunCodeBlockFailure(
failureReason,
- workflowRunTimeline,
+ currentAttemptTimeline,
finallyBlockLabel,
);
@@ -377,7 +397,7 @@ function WorkflowRun() {
"font-mono text-sm text-neutral-600 hover:text-neutral-950 hover:underline hover:underline-offset-2 dark:text-slate-400 dark:hover:text-slate-200";
const finallyBlockInTimeline = finallyBlockLabel
- ? workflowRunTimeline?.find(
+ ? currentAttemptTimeline.find(
(item) => isBlockItem(item) && item.block.label === finallyBlockLabel,
)
: null;
@@ -662,6 +682,11 @@ function WorkflowRun() {
) : workflowRun && !statusUnavailable ? (
<div className="mt-[0.27rem] flex items-center gap-2">
<StatusBadge status={workflowRun?.status} />
+ <WorkflowRunAttemptChip
+ attempt={workflowRun.attempt}
+ retryPending={workflowRun.retry_pending}
+ nextAttemptAt={workflowRun.next_attempt_at}
+ />
<CredentialFallbackRetryBadge
retriedFromWorkflowRunId={
workflowRun.retried_from_workflow_run_id
@@ -769,6 +794,11 @@ function WorkflowRun() {
headers,
} satisfies ApiCommandOptions;
}}
+ disabledReason={
+ workflowRun && runIsRetryWaiting(workflowRun)
+ ? "Unavailable while a retry is pending"
+ : undefined
+ }
webhookDisabled={
workflowRunIsLoading || !workflowRunIsFinalized
}
@@ -851,6 +881,7 @@ function WorkflowRun() {
{WorkflowRunMilestoneCard &&
workflowRun &&
!workflowRunIsPlaceholder &&
+ runIsLogicallyFinal(workflowRun) &&
workflowRun.status === Status.Completed ? (
<WorkflowRunMilestoneCard
workflowRunId={workflowRun.workflow_run_id}
@@ -937,7 +968,7 @@ function WorkflowRun() {
<SwitchBarNavigation options={switchBarOptions} />
{workflowRun && (
<WorkflowRunStatusAlert
- status={workflowRun.status}
+ run={workflowRun}
title={workflow?.title}
visible={!statusUnavailable && !isFinalized}
/>
diff --git a/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx b/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx
index c9b606442..ca3b9e0c9 100644
--- a/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx
+++ b/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx
@@ -128,6 +128,7 @@ function getWorkflowElements(version: WorkflowVersion) {
workflowSystemPrompt:
version.workflow_definition?.workflow_system_prompt ?? null,
errorCodeMapping: version.workflow_definition?.error_code_mapping ?? null,
+ retryPolicy: version.workflow_definition?.retry_policy ?? null,
};
return getElements(
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 00499635a..e3e0d406c 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -3719,6 +3719,7 @@ export function WorkflowCopilotChat({
version: saveData.workflowDefinitionVersion,
parameters: saveData.parameters,
blocks: saveData.blocks,
+ retry_policy: saveData.settings.retryPolicy ?? null,
},
is_saved_task: saveData.workflow.is_saved_task,
status: saveData.workflow.status,
@@ -3748,6 +3749,7 @@ export function WorkflowCopilotChat({
...saveData.workflow.workflow_definition,
parameters: saveData.parameters,
blocks: saveData.blocks,
+ retry_policy: saveData.settings.retryPolicy ?? null,
},
} as WorkflowApiResponse;
}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/useRunLifecycleAnnouncements.ts b/skyvern-frontend/src/routes/workflows/copilot/useRunLifecycleAnnouncements.ts
index 068bf0fc7..71a2f7015 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/useRunLifecycleAnnouncements.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/useRunLifecycleAnnouncements.ts
@@ -1,8 +1,9 @@
+import { runIsLogicallyFinal } from "@/routes/workflows/workflowRun/runRetryState";
import { useEffect, useRef } from "react";
import { useSearchParams } from "react-router-dom";
import { Status, WorkflowRunStatusApiResponse } from "@/api/types";
-import { statusIsAFailureType, statusIsFinalized } from "@/routes/tasks/types";
+import { statusIsAFailureType } from "@/routes/tasks/types";
import { formatElapsedSeconds, isRecord } from "@/util/utils";
import { useWorkflowRunQuery } from "../hooks/useWorkflowRunQuery";
@@ -145,7 +146,7 @@ export function useRunLifecycleAnnouncements({
entry.terminal = true;
return;
}
- const finalized = statusIsFinalized({ status: data.status });
+ const finalized = runIsLogicallyFinal(data);
// A not-yet-claimed run seen mid-turn may still turn out to be the turn's
// own (its run_outcome hasn't landed yet), so hold its lines until the turn
// ends instead of leaking a start line the turn would also narrate. Record
diff --git a/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx b/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx
index 47d4ae411..debfd9019 100644
--- a/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx
+++ b/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx
@@ -98,6 +98,7 @@ function Debugger() {
workflowSystemPrompt:
workflow.workflow_definition?.workflow_system_prompt ?? null,
errorCodeMapping: workflow.workflow_definition?.error_code_mapping ?? null,
+ retryPolicy: workflow.workflow_definition?.retry_policy ?? null,
};
const elements = getElements(blocksToRender, settings, true);
diff --git a/skyvern-frontend/src/routes/workflows/debugger/DebuggerRunTimeline.tsx b/skyvern-frontend/src/routes/workflows/debugger/DebuggerRunTimeline.tsx
index 333e535f7..3b0e4a058 100644
--- a/skyvern-frontend/src/routes/workflows/debugger/DebuggerRunTimeline.tsx
+++ b/skyvern-frontend/src/routes/workflows/debugger/DebuggerRunTimeline.tsx
@@ -2,7 +2,11 @@ import { useMemo } from "react";
import { ScrollArea, ScrollAreaViewport } from "@/components/ui/scroll-area";
import { Skeleton } from "@/components/ui/skeleton";
-import { statusIsFinalized } from "@/routes/tasks/types";
+import {
+ getRunAttempt,
+ runIsExecuting,
+} from "@/routes/workflows/workflowRun/runRetryState";
+import { filterTimelineToAttempt } from "@/routes/workflows/workflowRun/workflowTimelineUtils";
import { cn } from "@/util/utils";
import { useWorkflowRunQuery } from "../hooks/useWorkflowRunQuery";
import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";
@@ -62,12 +66,17 @@ function DebuggerRunTimeline({
return null;
}
- const workflowRunIsFinalized = statusIsFinalized(workflowRun);
+ const attemptIsExecuting = runIsExecuting(workflowRun);
+ const currentAttemptTimeline = filterTimelineToAttempt(
+ workflowRunTimeline,
+ workflowRun.attempts ?? [],
+ getRunAttempt(workflowRun),
+ );
- const numberOfActions = countActionsInTimeline(workflowRunTimeline);
+ const numberOfActions = countActionsInTimeline(currentAttemptTimeline);
const firstActionOrThoughtIsPending =
- !workflowRunIsFinalized && workflowRunTimeline.length === 0;
+ attemptIsExecuting && currentAttemptTimeline.length === 0;
return (
<div
@@ -96,20 +105,20 @@ function DebuggerRunTimeline({
<ScrollArea>
<ScrollAreaViewport className="h-full w-full">
<div className="w-full space-y-4">
- {workflowRunIsFinalized && workflowRunTimeline.length === 0 && (
+ {!attemptIsExecuting && currentAttemptTimeline.length === 0 && (
<div>Workflow timeline is empty</div>
)}
- {!workflowRunIsFinalized && workflowRunTimeline.length === 0 && (
+ {attemptIsExecuting && currentAttemptTimeline.length === 0 && (
<div className="flex h-full w-full items-center justify-center">
Formulating actions...
</div>
)}
- {workflowRunTimeline?.map((timelineItem, i) => {
+ {currentAttemptTimeline.map((timelineItem, i) => {
if (isBlockItem(timelineItem)) {
return (
<div
className={cn({
- "animate-pulse": !workflowRunIsFinalized && i === 0,
+ "animate-pulse": attemptIsExecuting && i === 0,
})}
key={timelineItem.block.workflow_run_block_id}
>
@@ -130,7 +139,7 @@ function DebuggerRunTimeline({
return (
<div
className={cn({
- "animate-pulse": !workflowRunIsFinalized && i === 0,
+ "animate-pulse": attemptIsExecuting && i === 0,
})}
key={timelineItem.thought.thought_id}
>
diff --git a/skyvern-frontend/src/routes/workflows/debugger/DebuggerRunTimelineMinimal.tsx b/skyvern-frontend/src/routes/workflows/debugger/DebuggerRunTimelineMinimal.tsx
index 8b60fdf6c..1837d9f53 100644
--- a/skyvern-frontend/src/routes/workflows/debugger/DebuggerRunTimelineMinimal.tsx
+++ b/skyvern-frontend/src/routes/workflows/debugger/DebuggerRunTimelineMinimal.tsx
@@ -1,6 +1,10 @@
import { ScrollArea, ScrollAreaViewport } from "@/components/ui/scroll-area";
import { Skeleton } from "@/components/ui/skeleton";
-import { statusIsFinalized } from "@/routes/tasks/types";
+import {
+ getRunAttempt,
+ runIsExecuting,
+} from "@/routes/workflows/workflowRun/runRetryState";
+import { filterTimelineToAttempt } from "@/routes/workflows/workflowRun/workflowTimelineUtils";
import { useWorkflowRunQuery } from "../hooks/useWorkflowRunQuery";
import { useWorkflowRunTimelineQuery } from "../hooks/useWorkflowRunTimelineQuery";
import { isBlockItem, isThoughtItem } from "../types/workflowRunTypes";
@@ -26,11 +30,16 @@ function DebuggerRunTimelineMinimal() {
return null;
}
- const workflowRunIsFinalized = statusIsFinalized(workflowRun);
+ const attemptIsExecuting = runIsExecuting(workflowRun);
+ const currentAttemptTimeline = filterTimelineToAttempt(
+ workflowRunTimeline,
+ workflowRun.attempts ?? [],
+ getRunAttempt(workflowRun),
+ );
return (
<div className="h-full w-full">
- {!workflowRunIsFinalized && workflowRunTimeline.length === 0 && (
+ {attemptIsExecuting && currentAttemptTimeline.length === 0 && (
<Skeleton className="vertical-line-gradient-soft flex h-full min-h-[30rem] w-full items-center justify-center overflow-visible">
{/* rotate this by 90 degrees */}
<div
@@ -44,16 +53,16 @@ function DebuggerRunTimelineMinimal() {
<ScrollArea className="h-full w-full">
<ScrollAreaViewport className="h-full w-full">
<div className="flex w-full flex-col items-center justify-center gap-4 pt-2">
- {workflowRunIsFinalized && workflowRunTimeline.length === 0 && (
+ {!attemptIsExecuting && currentAttemptTimeline.length === 0 && (
<div>-</div>
)}
- {workflowRunTimeline?.map((timelineItem, i) => {
+ {currentAttemptTimeline.map((timelineItem, i) => {
if (isBlockItem(timelineItem)) {
return (
<div
key={timelineItem.block.workflow_run_block_id}
className={cn({
- "animate-pulse": !workflowRunIsFinalized && i === 0,
+ "animate-pulse": attemptIsExecuting && i === 0,
})}
>
<WorkflowRunTimelineBlockItemMinimal
@@ -68,7 +77,7 @@ function DebuggerRunTimelineMinimal() {
<div
key={timelineItem.thought.thought_id}
className={cn({
- "animate-pulse": !workflowRunIsFinalized && i === 0,
+ "animate-pulse": attemptIsExecuting && i === 0,
})}
>
<ThoughtCardMinimal
diff --git a/skyvern-frontend/src/routes/workflows/debugger/recentActivity/useRecentActivity.ts b/skyvern-frontend/src/routes/workflows/debugger/recentActivity/useRecentActivity.ts
index 951de6b14..ae06728b1 100644
--- a/skyvern-frontend/src/routes/workflows/debugger/recentActivity/useRecentActivity.ts
+++ b/skyvern-frontend/src/routes/workflows/debugger/recentActivity/useRecentActivity.ts
@@ -3,7 +3,7 @@ import { useNavigate, useParams } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "@/components/ui/use-toast";
-import { statusIsFinalized } from "@/routes/tasks/types";
+import { runIsLogicallyFinal } from "@/routes/workflows/workflowRun/runRetryState";
import { useWorkflowRunQuery } from "@/routes/workflows/hooks/useWorkflowRunQuery";
import { toDate } from "@/util/utils";
@@ -51,7 +51,7 @@ export function useRecentActivity(): RecentActivity {
debugSessionId: debugSession?.debug_session_id,
});
- const isFinalized = workflowRun ? statusIsFinalized(workflowRun) : null;
+ const isFinalized = workflowRun ? runIsLogicallyFinal(workflowRun) : null;
const isWorkflowRunning = isFinalized !== null && !isFinalized;
const runs = useMemo(
diff --git a/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.test.tsx b/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.test.tsx
index efaa995ed..0f7aa9bec 100644
--- a/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.test.tsx
@@ -2,10 +2,15 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cleanup, render, screen } from "@testing-library/react";
+import { ReactFlowProvider } from "@xyflow/react";
+import { useEffect, type ReactNode } from "react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { Status } from "@/api/types";
+import { WorkflowEditor } from "./WorkflowEditor";
+import { Workspace } from "./Workspace";
+import type { FlowRendererProps } from "./FlowRenderer";
const { workflowQueryMock, runQueryMock, runsQueryMock } = vi.hoisted(() => ({
workflowQueryMock: vi.fn(),
@@ -28,6 +33,55 @@ vi.mock("../hooks/useWorkflowRunWithWorkflowQuery", () => ({
vi.mock("../hooks/useWorkflowRunsQuery", () => ({
useWorkflowRunsQuery: () => runsQueryMock(),
}));
+vi.mock("../hooks/useWorkflowRunQuery", () => ({
+ useWorkflowRunQuery: () => runQueryMock(),
+}));
+vi.mock("../hooks/useBlockScriptsQuery", () => ({
+ useBlockScriptsQuery: () => ({ data: undefined }),
+}));
+vi.mock("../hooks/useCacheKeyValuesQuery", () => ({
+ useCacheKeyValuesQuery: () => ({ data: undefined, isLoading: false }),
+}));
+vi.mock("../hooks/useDebugSessionQuery", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../hooks/useDebugSessionQuery")>()),
+ useDebugSessionQuery: () => ({ data: undefined }),
+}));
+vi.mock("../hooks/useActiveRunSessionQuery", () => ({
+ useActiveRunSessionQuery: () => ({
+ data: { active_run_session_id: "pbs_run" },
+ }),
+}));
+vi.mock("@/hooks/useRuntimeConfig", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/hooks/useRuntimeConfig")>()),
+ useStreamTransport: () => ({ streamTransport: "vnc" }),
+}));
+vi.mock("./FlowRenderer", () => ({
+ FlowRenderer: ({ onLayoutPhaseChange }: FlowRendererProps) => {
+ useEffect(() => {
+ onLayoutPhaseChange?.("ready");
+ }, [onLayoutPhaseChange]);
+ return null;
+ },
+}));
+vi.mock("@/components/BrowserStream", () => ({
+ BrowserStream: ({ isExecuting }: { isExecuting: boolean }) => (
+ <div data-testid="browser-stream" data-executing={isExecuting} />
+ ),
+}));
+vi.mock("@/components/Splitter", () => ({
+ Splitter: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+vi.mock("./WorkflowHeader", () => ({ WorkflowHeader: () => null }));
+vi.mock("../copilot/WorkflowCopilotChat", () => ({
+ WorkflowCopilotChat: () => null,
+}));
+vi.mock("../debugger/DebuggerRun", () => ({ DebuggerRun: () => null }));
+vi.mock("../debugger/DebuggerRunMinimal", () => ({
+ DebuggerRunMinimal: () => null,
+}));
+vi.mock("../debugger/recentActivity/RecentActivityRunSelector", () => ({
+ RecentActivityRunSelector: () => null,
+}));
// Pane bodies own their data wiring (tested in their own suites); the shell
// contract under test is which of them mount and how the chrome degrades.
vi.mock("../studio/EditorTab", () => ({
@@ -53,8 +107,6 @@ vi.mock("@/components/onboarding/ProductTour", () => ({
ProductTour: () => null,
}));
-import { WorkflowEditor } from "./WorkflowEditor";
-
const deletedWorkflow = {
workflow_permanent_id: "wpid_del",
title: "Deleted agent",
@@ -104,7 +156,10 @@ function renderStudioAt(path: string) {
);
}
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
beforeEach(() => {
vi.clearAllMocks();
@@ -212,3 +267,60 @@ describe("WorkflowEditor deleted-agent run fallback", () => {
).toBe(false);
});
});
+
+test("the editor browser stops indicating execution during a retry wait and resumes for the next attempt", () => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ disconnect() {}
+ },
+ );
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const editor = () => (
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={["/agents/wpid_live/edit?wr=wr_1"]}>
+ <Routes>
+ <Route
+ path="/agents/:workflowPermanentId/edit"
+ element={
+ <ReactFlowProvider>
+ <Workspace
+ initialNodes={[]}
+ initialEdges={[]}
+ initialTitle="Live agent"
+ workflow={liveWorkflow}
+ showBrowser
+ />
+ </ReactFlowProvider>
+ }
+ />
+ </Routes>
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+ runQueryMock.mockReturnValue({
+ data: {
+ workflow_run_id: "wr_1",
+ status: Status.Failed,
+ retry_pending: true,
+ },
+ });
+ const view = render(editor());
+ expect(
+ screen.getByTestId("browser-stream").getAttribute("data-executing"),
+ ).toBe("false");
+
+ runQueryMock.mockReturnValue({
+ data: { workflow_run_id: "wr_1", status: Status.Running, attempt: 2 },
+ });
+ view.rerender(editor());
+ expect(
+ screen.getByTestId("browser-stream").getAttribute("data-executing"),
+ ).toBe("true");
+ view.unmount();
+ queryClient.clear();
+ vi.unstubAllGlobals();
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx
index f8b93fda1..23a8cea45 100644
--- a/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx
@@ -126,6 +126,7 @@ function WorkflowEditor() {
workflowSystemPrompt:
workflow.workflow_definition?.workflow_system_prompt ?? null,
errorCodeMapping: workflow.workflow_definition?.error_code_mapping ?? null,
+ retryPolicy: workflow.workflow_definition?.retry_policy ?? null,
};
const elements = getElements(
diff --git a/skyvern-frontend/src/routes/workflows/editor/WorkflowHeader.tsx b/skyvern-frontend/src/routes/workflows/editor/WorkflowHeader.tsx
index 90aa0cb0b..534589d44 100644
--- a/skyvern-frontend/src/routes/workflows/editor/WorkflowHeader.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/WorkflowHeader.tsx
@@ -1,3 +1,4 @@
+import { runIsLogicallyActive } from "@/routes/workflows/workflowRun/runRetryState";
import {
CalendarIcon,
ChevronDownIcon,
@@ -19,7 +20,7 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
-import { statusIsRunningOrQueued } from "@/routes/tasks/types";
+
import { useGlobalWorkflowsQuery } from "../hooks/useGlobalWorkflowsQuery";
import { useIsGlobalWorkflow } from "../hooks/useIsGlobalWorkflow";
import { MakeACopyButton } from "./MakeACopyButton";
@@ -65,7 +66,7 @@ function BrowserModeButton() {
const recordingStore = useRecordingStore();
const { data: workflowRun } = useWorkflowRunQuery();
const workflowRunIsRunningOrQueued = Boolean(
- workflowRun && statusIsRunningOrQueued(workflowRun),
+ workflowRun && runIsLogicallyActive(workflowRun),
);
const handleClick = () => {
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index f2465f806..7a4d4111c 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -102,7 +102,10 @@ import { AffectedBlocksNotice } from "./AffectedBlocksNotice";
import { BrowserStream } from "@/components/BrowserStream";
import { RecordingPanel } from "@/routes/workflows/editor/recording/RecordingPanel";
import { useApplyRecordedBlocks } from "@/routes/workflows/editor/recording/useApplyRecordedBlocks";
-import { statusIsFinalized } from "@/routes/tasks/types.ts";
+import {
+ runIsLogicallyFinal,
+ runIsExecuting,
+} from "@/routes/workflows/workflowRun/runRetryState";
import { CodeEditor } from "@/routes/workflows/components/CodeEditor";
import { DebuggerRun } from "@/routes/workflows/debugger/DebuggerRun";
import { DebuggerRunMinimal } from "@/routes/workflows/debugger/DebuggerRunMinimal";
@@ -572,7 +575,7 @@ function Workspace({
const { getNodes, getEdges } = useReactFlow();
const { data: workflowRun } = useWorkflowRunQuery();
const studioRunId = useStudioRunId();
- const isFinalized = workflowRun ? statusIsFinalized(workflowRun) : false;
+ const isFinalized = workflowRun ? runIsLogicallyFinal(workflowRun) : false;
const [openCycleBrowserDialogue, setOpenCycleBrowserDialogue] =
useState(false);
@@ -1729,6 +1732,7 @@ function Workspace({
workflowData.workflow_definition?.workflow_system_prompt ?? null,
errorCodeMapping:
workflowData.workflow_definition?.error_code_mapping ?? null,
+ retryPolicy: workflowData.workflow_definition?.retry_policy ?? null,
};
const elements = getElements(
@@ -1924,6 +1928,7 @@ function Workspace({
finally_block_label: finallyBlockLabel,
workflow_system_prompt: saveData.settings.workflowSystemPrompt ?? null,
error_code_mapping: saveData.settings.errorCodeMapping ?? null,
+ retry_policy: saveData.settings.retryPolicy ?? null,
};
const version = workflowVersionFromSaveData(saveData, definition, {
extraHttpHeaders,
@@ -2070,6 +2075,7 @@ function Workspace({
selectedVersion.workflow_definition?.workflow_system_prompt ?? null,
errorCodeMapping:
selectedVersion.workflow_definition?.error_code_mapping ?? null,
+ retryPolicy: selectedVersion.workflow_definition?.retry_policy ?? null,
};
const elements = getElements(
@@ -2692,7 +2698,9 @@ function Workspace({
// debug session owns the recording reset.
resetRecordingOnUnmount={false}
resizeTrigger={windowResizeTrigger}
- isExecuting={!!workflowRun && !isFinalized}
+ isExecuting={
+ !!workflowRun && runIsExecuting(workflowRun)
+ }
onReadyChange={handleLiveBrowserReadyChange}
/>
) : (
@@ -2979,6 +2987,7 @@ function Workspace({
version: saveData.workflowDefinitionVersion,
parameters: saveData.parameters,
blocks: saveData.blocks,
+ retry_policy: saveData.settings.retryPolicy ?? null,
finally_block_label:
saveData.settings.finallyBlockLabel ?? undefined,
workflow_system_prompt:
diff --git a/skyvern-frontend/src/routes/workflows/editor/header/EditorOverflowMenu.tsx b/skyvern-frontend/src/routes/workflows/editor/header/EditorOverflowMenu.tsx
index db061e0c7..f757537ef 100644
--- a/skyvern-frontend/src/routes/workflows/editor/header/EditorOverflowMenu.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/header/EditorOverflowMenu.tsx
@@ -1,3 +1,4 @@
+import { runIsLogicallyActive } from "@/routes/workflows/workflowRun/runRetryState";
import {
CounterClockwiseClockIcon,
DotsHorizontalIcon,
@@ -24,7 +25,7 @@ import {
} from "@/components/ui/tooltip";
import { toast } from "@/components/ui/use-toast";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
-import { statusIsRunningOrQueued } from "@/routes/tasks/types";
+
import { useWorkflowQuery } from "@/routes/workflows/hooks/useWorkflowQuery";
import { useWorkflowRunQuery } from "@/routes/workflows/hooks/useWorkflowRunQuery";
import { useProductTourStore } from "@/store/ProductTourStore";
@@ -68,7 +69,7 @@ export function EditorOverflowMenu({
const enterYamlMode = useWorkflowYamlEditorStore((s) => s.enterYamlMode);
const workflowRunIsRunningOrQueued = Boolean(
- workflowRun && statusIsRunningOrQueued(workflowRun),
+ workflowRun && runIsLogicallyActive(workflowRun),
);
const templateMutation = useMutation({
diff --git a/skyvern-frontend/src/routes/workflows/editor/hooks/useIsGeneratingCode.ts b/skyvern-frontend/src/routes/workflows/editor/hooks/useIsGeneratingCode.ts
index 56dc2ffb3..adbfada9e 100644
--- a/skyvern-frontend/src/routes/workflows/editor/hooks/useIsGeneratingCode.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/hooks/useIsGeneratingCode.ts
@@ -1,4 +1,5 @@
-import { statusIsFinalized } from "@/routes/tasks/types";
+import { runIsLogicallyFinal } from "@/routes/workflows/workflowRun/runRetryState";
+
import { useBlockScriptsQuery } from "@/routes/workflows/hooks/useBlockScriptsQuery";
import { useWorkflowQuery } from "@/routes/workflows/hooks/useWorkflowQuery";
import { useWorkflowRunQuery } from "@/routes/workflows/hooks/useWorkflowRunQuery";
@@ -26,7 +27,7 @@ export function useIsGeneratingCode(params: Params): boolean {
});
const { data: workflow } = useWorkflowQuery({ workflowPermanentId });
- const isFinalized = workflowRun ? statusIsFinalized(workflowRun) : false;
+ const isFinalized = workflowRun ? runIsLogicallyFinal(workflowRun) : false;
const publishedLabelCount = Object.keys(
blockScriptsPublished?.blocks ?? {},
).length;
diff --git a/skyvern-frontend/src/routes/workflows/editor/nestedConditionalSave.test.ts b/skyvern-frontend/src/routes/workflows/editor/nestedConditionalSave.test.ts
index bc0efb1be..7e57f3a61 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nestedConditionalSave.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nestedConditionalSave.test.ts
@@ -49,6 +49,7 @@ const DEFAULT_SETTINGS: WorkflowSettings = {
finallyBlockLabel: null,
workflowSystemPrompt: null,
errorCodeMapping: null,
+ retryPolicy: null,
};
function op(label: string): OutputParameter {
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.test.tsx
index 05e8daf82..a77fdfe9e 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.test.tsx
@@ -173,6 +173,7 @@ function startNode(
finallyBlockLabel: null,
workflowSystemPrompt: null,
errorCodeMapping: null,
+ retryPolicy: null,
label: "__start_block__",
showCode: false,
...overrides,
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/ErrorCodeChipInput.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/ErrorCodeChipInput.tsx
new file mode 100644
index 000000000..0f018699a
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/ErrorCodeChipInput.tsx
@@ -0,0 +1,136 @@
+import { useId, useState } from "react";
+import { Cross2Icon, ChevronDownIcon } from "@radix-ui/react-icons";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import { TemplateModeToggle } from "@/routes/workflows/components/TemplateModeToggle";
+
+type Props = {
+ value: Array<string>;
+ onChange: (codes: Array<string>) => void;
+ knownErrorCodes: Array<string>;
+ readOnly: boolean;
+};
+
+export function ErrorCodeChipInput({
+ value,
+ onChange,
+ knownErrorCodes,
+ readOnly,
+}: Props) {
+ const id = useId();
+ const [custom, setCustom] = useState(false);
+ const [draft, setDraft] = useState("");
+ const [open, setOpen] = useState(false);
+ const available = knownErrorCodes.filter((code) => !value.includes(code));
+ function addCode(raw: string) {
+ const code = raw.trim();
+ if (!readOnly && code && !value.includes(code)) onChange([...value, code]);
+ setDraft("");
+ }
+ return (
+ <fieldset disabled={readOnly} className="min-w-0 space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ <Label htmlFor={id}>Error codes</Label>
+ <TemplateModeToggle
+ pressed={custom}
+ pickerTitle="Choose an error code"
+ onToggle={setCustom}
+ />
+ </div>
+ {value.length > 0 && (
+ <div className="flex flex-wrap gap-1">
+ {value.map((code) => (
+ <Badge key={code} variant="secondary" className="max-w-full gap-1">
+ <span className="break-all">{code}</span>
+ <button
+ type="button"
+ aria-label={`Remove error code ${code}`}
+ disabled={readOnly}
+ onClick={() => onChange(value.filter((item) => item !== code))}
+ >
+ <Cross2Icon className="size-3" />
+ </button>
+ </Badge>
+ ))}
+ </div>
+ )}
+ {custom ? (
+ <Input
+ id={id}
+ value={draft}
+ disabled={readOnly}
+ placeholder={value.length ? "Enter an error code" : "Any error code"}
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={() => addCode(draft)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ addCode(draft);
+ }
+ }}
+ />
+ ) : (
+ <Popover open={open && !readOnly} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ id={id}
+ type="button"
+ variant="outline"
+ disabled={readOnly}
+ role="combobox"
+ aria-expanded={open}
+ className="w-full justify-between text-xs"
+ >
+ {value.length ? "Add an error code" : "Any error code"}
+ <ChevronDownIcon className="ml-2 size-4 shrink-0" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ className="w-[--radix-popover-trigger-width] p-0"
+ align="start"
+ >
+ <Command>
+ <CommandInput placeholder="Search error codes" />
+ <CommandList>
+ <CommandEmpty>
+ {knownErrorCodes.length
+ ? "No error codes available."
+ : "No error codes are defined in this workflow yet."}
+ </CommandEmpty>
+ <CommandGroup>
+ {available.map((code) => (
+ <CommandItem
+ key={code}
+ value={code}
+ onSelect={() => {
+ addCode(code);
+ setOpen(false);
+ }}
+ >
+ {code}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ )}
+ </fieldset>
+ );
+}
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/RetryPolicyEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/RetryPolicyEditor.tsx
new file mode 100644
index 000000000..0cd85e439
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/RetryPolicyEditor.tsx
@@ -0,0 +1,262 @@
+import { useId, useState } from "react";
+import { Cross2Icon, PlusIcon } from "@radix-ui/react-icons";
+import { HelpTooltip } from "@/components/HelpTooltip";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import type {
+ WorkflowRetryPolicy,
+ WorkflowRetryStatus,
+ WorkflowRetryWebhookMode,
+} from "@/routes/workflows/types/workflowTypes";
+import { ErrorCodeChipInput } from "./ErrorCodeChipInput";
+import { clampRetryInteger, normalizeRetryPolicy } from "./retryPolicyUtils";
+
+const statuses = [
+ { value: "failed", label: "Failed" },
+ { value: "terminated", label: "Terminated" },
+ { value: "timed_out", label: "Timed out" },
+ { value: "completed", label: "Completed" },
+] as const;
+
+type Props = {
+ value: WorkflowRetryPolicy | null;
+ onChange: (policy: WorkflowRetryPolicy | null) => void;
+ knownErrorCodes: Array<string>;
+ readOnly: boolean;
+};
+
+export function RetryPolicyEditor({
+ value,
+ onChange,
+ knownErrorCodes,
+ readOnly,
+}: Props) {
+ const id = useId();
+ const [maxRetriesDraft, setMaxRetriesDraft] = useState<string | null>(null);
+ const [delayDraft, setDelayDraft] = useState<string | null>(null);
+ const unusedStatuses = statuses.filter(
+ (status) => !value?.retry_on.some((rule) => rule.status === status.value),
+ );
+ function update(policy: WorkflowRetryPolicy | null) {
+ if (!readOnly) onChange(normalizeRetryPolicy(policy));
+ }
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Label htmlFor={`${id}-enabled`}>Automatic retry</Label>
+ <HelpTooltip content="Retries restart the workflow from the beginning. All attempts share one workflow run ID. Each attempt uses credits." />
+ <Switch
+ id={`${id}-enabled`}
+ className="ml-auto"
+ disabled={readOnly}
+ checked={value !== null}
+ onCheckedChange={(enabled) => {
+ setMaxRetriesDraft(null);
+ setDelayDraft(null);
+ update(
+ enabled
+ ? {
+ max_retries: 1,
+ delay_seconds: 0,
+ webhook_on_retry: "final_only",
+ retry_on: [{ status: "failed" }],
+ }
+ : null,
+ );
+ }}
+ />
+ </div>
+ {value && (
+ <div className="flex flex-col gap-4 rounded-md bg-slate-elevation4 p-4">
+ {value.retry_on.map((rule, index) => (
+ <div
+ key={index}
+ className="space-y-2 rounded-md bg-slate-elevation5 p-3"
+ >
+ <div className="flex items-end gap-2">
+ <div className="min-w-0 flex-1 space-y-2">
+ <Label htmlFor={`${id}-status-${index}`}>Status</Label>
+ <Select
+ value={rule.status}
+ disabled={readOnly}
+ onValueChange={(status) =>
+ update({
+ ...value,
+ retry_on: value.retry_on.map((item, i) =>
+ i === index
+ ? { ...item, status: status as WorkflowRetryStatus }
+ : item,
+ ),
+ })
+ }
+ >
+ <SelectTrigger id={`${id}-status-${index}`}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {rule.status === "canceled" && (
+ <SelectItem value="canceled">
+ Canceled (never retried)
+ </SelectItem>
+ )}
+ {statuses
+ .filter(
+ (status) =>
+ status.value === rule.status ||
+ unusedStatuses.includes(status),
+ )
+ .map((status) => (
+ <SelectItem key={status.value} value={status.value}>
+ {status.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={`Remove ${rule.status} condition`}
+ disabled={readOnly || value.retry_on.length === 1}
+ onClick={() =>
+ update({
+ ...value,
+ retry_on: value.retry_on.filter((_, i) => i !== index),
+ })
+ }
+ >
+ <Cross2Icon className="size-4" />
+ </Button>
+ </div>
+ <ErrorCodeChipInput
+ value={rule.error_codes ?? []}
+ knownErrorCodes={knownErrorCodes}
+ readOnly={readOnly}
+ onChange={(codes) =>
+ update({
+ ...value,
+ retry_on: value.retry_on.map((item, i) =>
+ i === index ? { ...item, error_codes: codes } : item,
+ ),
+ })
+ }
+ />
+ </div>
+ ))}
+ <Button
+ type="button"
+ variant="secondary"
+ disabled={readOnly || unusedStatuses.length === 0}
+ onClick={() => {
+ const status = unusedStatuses[0]?.value;
+ if (status)
+ update({ ...value, retry_on: [...value.retry_on, { status }] });
+ }}
+ >
+ <PlusIcon className="mr-2 size-4" />
+ Add condition
+ </Button>
+ <div className="space-y-2">
+ <Label htmlFor={`${id}-max`}>Maximum retries</Label>
+ <Input
+ id={`${id}-max`}
+ type="number"
+ min={1}
+ max={5}
+ step={1}
+ disabled={readOnly}
+ value={maxRetriesDraft ?? value.max_retries}
+ onChange={(event) => {
+ const text = event.target.value;
+ setMaxRetriesDraft(text);
+ if (text.trim() !== "" && Number.isFinite(Number(text))) {
+ update({
+ ...value,
+ max_retries: clampRetryInteger(text, 1, 5, 1),
+ });
+ }
+ }}
+ onBlur={(event) => {
+ setMaxRetriesDraft(null);
+ update({
+ ...value,
+ max_retries: clampRetryInteger(event.target.value, 1, 5, 1),
+ });
+ }}
+ />
+ <p className="text-xs text-muted-foreground">
+ Total attempts = retries + 1
+ </p>
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor={`${id}-delay`}>
+ Delay between attempts (seconds)
+ </Label>
+ <Input
+ id={`${id}-delay`}
+ type="number"
+ min={0}
+ max={3600}
+ step={1}
+ disabled={readOnly}
+ value={delayDraft ?? value.delay_seconds}
+ onChange={(event) => {
+ const text = event.target.value;
+ setDelayDraft(text);
+ if (text.trim() !== "" && Number.isFinite(Number(text))) {
+ update({
+ ...value,
+ delay_seconds: clampRetryInteger(text, 0, 3600, 0),
+ });
+ }
+ }}
+ onBlur={(event) => {
+ setDelayDraft(null);
+ update({
+ ...value,
+ delay_seconds: clampRetryInteger(
+ event.target.value,
+ 0,
+ 3600,
+ 0,
+ ),
+ });
+ }}
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor={`${id}-webhook`}>Retry webhook</Label>
+ <Select
+ value={value.webhook_on_retry}
+ disabled={readOnly}
+ onValueChange={(mode) =>
+ update({
+ ...value,
+ webhook_on_retry: mode as WorkflowRetryWebhookMode,
+ })
+ }
+ >
+ <SelectTrigger id={`${id}-webhook`}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="final_only">Final attempt only</SelectItem>
+ <SelectItem value="every_attempt">Every attempt</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.test.tsx
index 765d5db90..a22f17b10 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.test.tsx
@@ -70,6 +70,7 @@ const startNodeData: WorkflowStartNodeData = {
finallyBlockLabel: null,
workflowSystemPrompt: null,
errorCodeMapping: null,
+ retryPolicy: null,
label: "__start_block__",
showCode: false,
};
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.test.tsx
index 4e5f90985..b37ae903b 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.test.tsx
@@ -5,6 +5,7 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { RetryPolicyEditor } from "./RetryPolicyEditor";
import type { WorkflowStartNodeData } from "./types";
const mockUpdateNodeData = vi.fn();
@@ -34,6 +35,7 @@ const startNodeData: WorkflowStartNodeData = {
finallyBlockLabel: null,
workflowSystemPrompt: null,
errorCodeMapping: null,
+ retryPolicy: null,
label: "__start_block__",
showCode: false,
};
@@ -53,7 +55,7 @@ vi.mock("@xyflow/react", async () => {
data: nodeData,
}
: null,
- useNodes: () => [],
+ useNodes: () => [{ id: "start", type: "start", data: nodeData }],
useEdges: () => [],
useReactFlow: () => ({
updateNodeData: mockUpdateNodeData,
@@ -311,3 +313,134 @@ describe("WorkflowSettingsEditor mask secrets setting", () => {
});
});
});
+
+describe("WorkflowSettingsEditor retry policy", () => {
+ test("enables, edits, and disables automatic retry", () => {
+ let view = renderSettings({
+ retryPolicy: null,
+ errorCodeMapping: { E_RETRY: "Retryable failure" },
+ });
+
+ function applyUpdate(retryPolicy: WorkflowStartNodeData["retryPolicy"]) {
+ expect(mockUpdateNodeData).toHaveBeenCalledExactlyOnceWith("start", {
+ retryPolicy,
+ });
+ nodeData = { ...nodeData, ...mockUpdateNodeData.mock.calls[0]![1] };
+ mockUpdateNodeData.mockClear();
+ view.unmount();
+ view = renderSettings(nodeData);
+ }
+
+ fireEvent.click(screen.getByRole("switch", { name: "Automatic retry" }));
+ const defaultPolicy: NonNullable<WorkflowStartNodeData["retryPolicy"]> = {
+ max_retries: 1,
+ delay_seconds: 0,
+ webhook_on_retry: "final_only",
+ retry_on: [{ status: "failed" }],
+ };
+ applyUpdate(defaultPolicy);
+
+ const maxRetries = screen.getByLabelText(
+ "Maximum retries",
+ ) as HTMLInputElement;
+ fireEvent.change(maxRetries, { target: { value: "" } });
+ expect(mockUpdateNodeData).not.toHaveBeenCalled();
+ expect(maxRetries.value).toBe("");
+ fireEvent.change(maxRetries, { target: { value: "9" } });
+ applyUpdate({ ...defaultPolicy, max_retries: 5 });
+
+ fireEvent.change(screen.getByLabelText("Maximum retries"), {
+ target: { value: "" },
+ });
+ fireEvent.blur(screen.getByLabelText("Maximum retries"));
+ applyUpdate(defaultPolicy);
+
+ fireEvent.change(screen.getByLabelText("Maximum retries"), {
+ target: { value: "2" },
+ });
+ applyUpdate({ ...defaultPolicy, max_retries: 2 });
+
+ fireEvent.change(
+ screen.getByLabelText("Delay between attempts (seconds)"),
+ {
+ target: { value: "5" },
+ },
+ );
+ const configuredPolicy = {
+ ...defaultPolicy,
+ max_retries: 2,
+ delay_seconds: 5,
+ };
+ applyUpdate(configuredPolicy);
+
+ fireEvent.change(
+ screen.getByLabelText("Delay between attempts (seconds)"),
+ {
+ target: { value: "" },
+ },
+ );
+ fireEvent.blur(screen.getByLabelText("Delay between attempts (seconds)"));
+ applyUpdate({ ...configuredPolicy, delay_seconds: 0 });
+ fireEvent.change(
+ screen.getByLabelText("Delay between attempts (seconds)"),
+ {
+ target: { value: "5" },
+ },
+ );
+ applyUpdate(configuredPolicy);
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "Enter a custom value" }),
+ );
+ fireEvent.change(screen.getByLabelText("Error codes"), {
+ target: { value: "E_RETRY" },
+ });
+ fireEvent.keyDown(screen.getByLabelText("Error codes"), { key: "Enter" });
+ applyUpdate({
+ ...configuredPolicy,
+ retry_on: [{ status: "failed", error_codes: ["E_RETRY"] }],
+ });
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "Enter a custom value" }),
+ );
+ fireEvent.change(screen.getByLabelText("Error codes"), {
+ target: { value: "E_CUSTOM" },
+ });
+ fireEvent.keyDown(screen.getByLabelText("Error codes"), { key: "Enter" });
+ applyUpdate({
+ ...configuredPolicy,
+ retry_on: [{ status: "failed", error_codes: ["E_RETRY", "E_CUSTOM"] }],
+ });
+
+ fireEvent.click(screen.getByRole("switch", { name: "Automatic retry" }));
+ applyUpdate(null);
+ expect(screen.queryByLabelText("Maximum retries")).toBeNull();
+ });
+});
+
+test("changing a retry status preserves the custom error-code draft", () => {
+ const policy = {
+ max_retries: 1,
+ delay_seconds: 0,
+ webhook_on_retry: "final_only" as const,
+ retry_on: [{ status: "failed" as const }],
+ };
+ const view = (status: "failed" | "terminated") => (
+ <RetryPolicyEditor
+ value={{ ...policy, retry_on: [{ status }] }}
+ onChange={() => {}}
+ knownErrorCodes={[]}
+ readOnly={false}
+ />
+ );
+ const { rerender } = render(view("failed"));
+ fireEvent.click(screen.getByRole("button", { name: "Enter a custom value" }));
+ fireEvent.change(screen.getByLabelText("Error codes"), {
+ target: { value: "E_DRAFT" },
+ });
+ rerender(view("terminated"));
+ expect((screen.getByLabelText("Error codes") as HTMLInputElement).value).toBe(
+ "E_DRAFT",
+ );
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.tsx
index f51514da8..1dbaf79cb 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/WorkflowSettingsEditor.tsx
@@ -1,3 +1,6 @@
+import { useWorkflowScopeReadOnly } from "../../WorkflowScopeContext";
+import { RetryPolicyEditor } from "./RetryPolicyEditor";
+import { collectKnownErrorCodes } from "./retryPolicyUtils";
import { ReloadIcon } from "@radix-ui/react-icons";
import { useEdges, useNodes, useNodesData } from "@xyflow/react";
import { useEffect, useMemo, useRef, useState } from "react";
@@ -97,6 +100,8 @@ function WorkflowSettingsEditorBody({
}) {
const workflowPermanentId = useWorkflowPermanentId();
const nodes = useNodes<AppNode>();
+ const readOnly = useWorkflowScopeReadOnly();
+ const knownErrorCodes = useMemo(() => collectKnownErrorCodes(nodes), [nodes]);
const edges = useEdges();
const update = useUpdate<StartNode["data"]>({ id: blockId, editable: true });
const studioEnabled = useWorkflowStudioEnabled();
@@ -150,6 +155,12 @@ function WorkflowSettingsEditorBody({
return (
<div data-testid="workflow-settings-block-form" className="space-y-4">
+ <RetryPolicyEditor
+ value={data.retryPolicy ?? null}
+ onChange={(retryPolicy) => update({ retryPolicy })}
+ knownErrorCodes={knownErrorCodes}
+ readOnly={readOnly || !data.editable}
+ />
<div className="space-y-2">
<div className="flex gap-2">
<Label>Model</Label>
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/retryPolicyUtils.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/retryPolicyUtils.ts
new file mode 100644
index 000000000..b5407f0ef
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/retryPolicyUtils.ts
@@ -0,0 +1,54 @@
+import type { WorkflowRetryPolicy } from "@/routes/workflows/types/workflowTypes";
+
+export function clampRetryInteger(
+ value: string | number,
+ min: number,
+ max: number,
+ fallback: number,
+): number {
+ const number =
+ typeof value === "string" && value.trim() === "" ? NaN : Number(value);
+ return Number.isFinite(number)
+ ? Math.min(max, Math.max(min, Math.trunc(number)))
+ : fallback;
+}
+
+export function normalizeRetryPolicy(
+ policy: WorkflowRetryPolicy | null | undefined,
+): WorkflowRetryPolicy | null {
+ if (!policy) return null;
+ return {
+ max_retries: clampRetryInteger(policy.max_retries, 1, 5, 1),
+ delay_seconds: clampRetryInteger(policy.delay_seconds, 0, 3600, 0),
+ webhook_on_retry: policy.webhook_on_retry,
+ retry_on: policy.retry_on.map(({ status, error_codes }) => {
+ const codes = [
+ ...new Set(
+ (error_codes ?? []).map((code) => code.trim()).filter(Boolean),
+ ),
+ ];
+ return codes.length ? { status, error_codes: codes } : { status };
+ }),
+ };
+}
+
+export function collectKnownErrorCodes(
+ nodes: ReadonlyArray<{ data: Record<string, unknown> }>,
+): Array<string> {
+ const codes = new Set<string>();
+ for (const node of nodes) {
+ let mapping: unknown = node.data.errorCodeMapping;
+ if (typeof mapping === "string") {
+ try {
+ mapping = JSON.parse(mapping) as unknown;
+ } catch {
+ continue;
+ }
+ }
+ if (mapping === null || typeof mapping !== "object") continue;
+ const prototype: unknown = Object.getPrototypeOf(mapping);
+ if (prototype !== Object.prototype && prototype !== null) continue;
+ for (const code of Object.keys(mapping)) codes.add(code);
+ }
+ return [...codes].sort();
+}
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/types.ts
index 8998b3cd4..df7bd104f 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/types.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/types.ts
@@ -1,10 +1,14 @@
import { ProxyLocation } from "@/api/types";
import type { Node } from "@xyflow/react";
import { AppNode } from "..";
-import { WorkflowModel } from "@/routes/workflows/types/workflowTypes";
+import {
+ WorkflowModel,
+ WorkflowRetryPolicy,
+} from "@/routes/workflows/types/workflowTypes";
export type WorkflowStartNodeData = {
withWorkflowSettings: true;
+ retryPolicy: WorkflowRetryPolicy | null;
webhookCallbackUrl: string;
proxyLocation: ProxyLocation;
persistBrowserSession: boolean;
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.test.tsx
index e8b304d4a..c1721c23a 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.test.tsx
@@ -178,3 +178,22 @@ describe("NodeHeader block controls vs a retained run payload (SKY-15507)", () =
expect(blockActionsAreInert()).toBe(false);
});
});
+
+test("a paused block run leaves per-block controls idle", () => {
+ queryClient.setQueryData(["workflowRun", "wf-test", "wr_paused"], {
+ workflow_run_id: "wr_paused",
+ status: Status.Paused,
+ });
+ renderNodeHeader(
+ { blockLabel: "block_1" },
+ { isDebugMode: true, blockRunsEnabled: false },
+ "/agents/wf-test/build?wr=wr_paused&bl=block_1",
+ );
+ expect(
+ screen
+ .getByRole("button", { name: "Block actions" })
+ .closest(".pointer-events-none"),
+ ).toBeNull();
+ expect(screen.getByRole("button", { name: "Run this block" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Stop this block" })).toBeNull();
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx
index d33eda8b8..85e2a0cb5 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx
@@ -1,3 +1,6 @@
+import { runIsRetryWaiting } from "@/routes/workflows/workflowRun/runRetryState";
+import { claimRunCompletionNotice } from "@/routes/workflows/workflowRun/runCompletionNotices";
+import { useRunCompletionToast } from "@/routes/workflows/workflowRun/useRunCompletionToast";
import { AxiosError } from "axios";
import {
ChevronDownIcon,
@@ -75,11 +78,7 @@ import {
} from "@/store/WorkflowSettingsStore";
import { getJsonParseErrorDetail } from "@/util/jsonParseError";
import { cn, formatDate, toDate } from "@/util/utils";
-import {
- statusIsAFailureType,
- statusIsFinalized,
- statusIsRunningOrQueued,
-} from "@/routes/tasks/types";
+import { statusIsRunningOrQueued } from "@/routes/tasks/types";
import {
Tooltip,
@@ -293,7 +292,10 @@ function NodeHeader({
// switch — that changes the query key while the run id stays the same.
const runStateIsLive = !statusUnavailable && !isPlaceholderData;
const workflowRunIsRunningOrQueued =
- runStateIsLive && workflowRun && statusIsRunningOrQueued(workflowRun);
+ runStateIsLive &&
+ workflowRun &&
+ (statusIsRunningOrQueued(workflowRun) || runIsRetryWaiting(workflowRun));
+ useRunCompletionToast(runStateIsLive ? workflowRun : undefined);
const { isRateLimited } = useBrowserSessionRateLimit(workflowPermanentId);
const { data: debugSession } = useDebugSessionQuery({
workflowPermanentId,
@@ -376,41 +378,6 @@ function NodeHeader({
}
});
- useEffect(() => {
- if (
- !workflowRun ||
- !workflowPermanentId ||
- !activeWorkflowRunId ||
- // Only block-scoped runs toast per block; full runs report via the run
- // surfaces (?wr= without ?bl=).
- targetBlockLabel === undefined
- ) {
- return;
- }
-
- if (statusIsFinalized(workflowRun)) {
- if (statusIsAFailureType(workflowRun)) {
- toast({
- variant: "destructive",
- title: `Agent Block ${targetBlockLabel}: ${workflowRun.status}`,
- description: `Reason: ${workflowRun.failure_reason}`,
- });
- } else if (statusIsFinalized(workflowRun)) {
- toast({
- variant: "success",
- title: `Agent Block ${targetBlockLabel}: ${workflowRun.status}`,
- });
- }
- }
- }, [
- queryClient,
- targetBlockLabel,
- navigate,
- workflowPermanentId,
- workflowRun,
- activeWorkflowRunId,
- ]);
-
const runBlock = useMutation({
mutationFn: async (opts?: {
codeGen: boolean;
@@ -661,11 +628,15 @@ function NodeHeader({
debugSessionId: debugSession?.debug_session_id,
browserSessionId: debugSession?.browser_session_id,
});
- toast({
- variant: "success",
- title: "Agent Canceled",
- description: "The agent has been successfully canceled.",
- });
+ if (activeWorkflowRunId) {
+ claimRunCompletionNotice(activeWorkflowRunId, () => {
+ toast({
+ variant: "success",
+ title: "Agent Canceled",
+ description: "The agent has been successfully canceled.",
+ });
+ });
+ }
},
onError: (error: AxiosError) => {
const detail = (error.response?.data as { detail?: string })?.detail;
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/WorkflowSettingsBlockForm.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/WorkflowSettingsBlockForm.tsx
index 71d812aa4..a4209a192 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/WorkflowSettingsBlockForm.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/WorkflowSettingsBlockForm.tsx
@@ -49,6 +49,7 @@ function WorkflowSettingsBlockFormBody({
maxElapsedTimeMinutes: data.maxElapsedTimeMinutes,
finallyBlockLabel: data.finallyBlockLabel,
workflowSystemPrompt: data.workflowSystemPrompt,
+ retryPolicy: data.retryPolicy,
};
}, [data]);
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx
index 0cf0fe394..196357ecb 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx
@@ -169,6 +169,7 @@ function getWorkflowElements(version: WorkflowVersion) {
workflowSystemPrompt:
version.workflow_definition?.workflow_system_prompt ?? null,
errorCodeMapping: version.workflow_definition?.error_code_mapping ?? null,
+ retryPolicy: version.workflow_definition?.retry_policy ?? null,
};
// Deep clone the blocks to ensure complete isolation from main editor
diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts b/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts
index 1f37cb28b..ca2748432 100644
--- a/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts
@@ -69,6 +69,7 @@ const DEFAULT_SETTINGS: WorkflowSettings = {
finallyBlockLabel: null,
workflowSystemPrompt: null,
errorCodeMapping: null,
+ retryPolicy: null,
};
function makeOutputParameter(label: string): OutputParameter {
diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts b/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts
index 33b3a0341..d9cfae9e2 100644
--- a/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts
@@ -67,6 +67,7 @@ const DEFAULT_SETTINGS: WorkflowSettings = {
finallyBlockLabel: null,
workflowSystemPrompt: null,
errorCodeMapping: null,
+ retryPolicy: null,
};
function makeOutputParameter(label: string): OutputParameter {
diff --git a/skyvern-frontend/src/routes/workflows/editor/undefinedParametersGuard.test.ts b/skyvern-frontend/src/routes/workflows/editor/undefinedParametersGuard.test.ts
index dce05e40f..ccfd06a12 100644
--- a/skyvern-frontend/src/routes/workflows/editor/undefinedParametersGuard.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/undefinedParametersGuard.test.ts
@@ -35,6 +35,7 @@ const DEFAULT_SETTINGS: WorkflowSettings = {
finallyBlockLabel: null,
workflowSystemPrompt: null,
errorCodeMapping: null,
+ retryPolicy: null,
};
describe("getElements is robust to blocks with undefined parameters", () => {
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowChangesSummary.ts b/skyvern-frontend/src/routes/workflows/editor/workflowChangesSummary.ts
index b4fa9079b..a5b6c12f3 100644
--- a/skyvern-frontend/src/routes/workflows/editor/workflowChangesSummary.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowChangesSummary.ts
@@ -230,6 +230,7 @@ const SETTINGS_LABELS: Array<{
{ fields: ["finallyBlockLabel"], label: "Changed finally block" },
{ fields: ["workflowSystemPrompt"], label: "Changed workflow system prompt" },
{ fields: ["errorCodeMapping"], label: "Changed error handling" },
+ { fields: ["retryPolicy"], label: "Automatic retry" },
];
function summarizeSettingsChanges(
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
index 6eab0f867..fef878f00 100644
--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
@@ -1,3 +1,4 @@
+import { normalizeRetryPolicy } from "./nodes/StartNode/retryPolicyUtils";
import Dagre from "@dagrejs/dagre";
import { type Node, Edge } from "@xyflow/react";
import { nanoid } from "nanoid";
@@ -2202,6 +2203,7 @@ function getElements(
finallyBlockLabel: settings.finallyBlockLabel ?? null,
workflowSystemPrompt: settings.workflowSystemPrompt ?? null,
errorCodeMapping: settings.errorCodeMapping ?? null,
+ retryPolicy: normalizeRetryPolicy(settings.retryPolicy),
}),
);
@@ -3794,6 +3796,7 @@ function getWorkflowSettings(nodes: Array<AppNode>): WorkflowSettings {
finallyBlockLabel: null,
workflowSystemPrompt: null,
errorCodeMapping: null,
+ retryPolicy: null,
};
const startNodes = nodes.filter(isStartNode);
const startNodeWithWorkflowSettings = startNodes.find(
@@ -3834,6 +3837,7 @@ function getWorkflowSettings(nodes: Array<AppNode>): WorkflowSettings {
finallyBlockLabel: data.finallyBlockLabel ?? null,
workflowSystemPrompt: data.workflowSystemPrompt ?? null,
errorCodeMapping: data.errorCodeMapping ?? null,
+ retryPolicy: normalizeRetryPolicy(data.retryPolicy),
};
}
return defaultSettings;
@@ -5088,6 +5092,9 @@ function convert(workflow: WorkflowApiResponse): WorkflowCreateYAMLRequest {
version: workflowDefinitionVersion,
parameters: convertParametersToParameterYAML(userParameters),
blocks: convertBlocksToBlockYAML(workflow.workflow_definition.blocks),
+ retry_policy: normalizeRetryPolicy(
+ workflow.workflow_definition.retry_policy,
+ ),
finally_block_label: workflow.workflow_definition.finally_block_label,
workflow_system_prompt:
workflow.workflow_definition.workflow_system_prompt,
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.ts b/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.ts
index 9dea1fdc4..673ec2ecc 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.ts
@@ -1,10 +1,14 @@
+import { runIsLogicallyFinal } from "@/routes/workflows/workflowRun/runRetryState";
import { useEffect, useRef } from "react";
import { useQueryClient } from "@tanstack/react-query";
-import { Status } from "@/api/types";
-import { statusIsFinalized } from "@/routes/tasks/types";
+import { Status, WorkflowRunRetryFields } from "@/api/types";
+
import type { OnboardingStateResponse } from "@/store/onboarding/types";
-type RunLike = { workflow_run_id: string; status: Status };
+type RunLike = {
+ workflow_run_id: string;
+ status: Status;
+} & WorkflowRunRetryFields;
// The backend stamps first_run_at only when a run reaches a final status, so
// refresh onboarding once per finalized run. Failed runs share one delayed
@@ -27,7 +31,7 @@ function useRefreshOnboardingOnRunCompletion(
);
useEffect(() => {
- if (!workflowRun || !statusIsFinalized(workflowRun)) {
+ if (!workflowRun || !runIsLogicallyFinal(workflowRun)) {
return;
}
const runId = workflowRun.workflow_run_id;
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.test.tsx b/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.test.tsx
index 0a5e14aa0..c6828c3d4 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.test.tsx
@@ -1,14 +1,23 @@
// @vitest-environment jsdom
import type { ReactNode } from "react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { renderHook, waitFor } from "@testing-library/react";
+import {
+ focusManager,
+ QueryClient,
+ QueryClientProvider,
+} from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
const { mockGet, mockGetClient, runState } = vi.hoisted(() => ({
mockGet: vi.fn(),
mockGetClient: vi.fn(),
- runState: { status: "running" },
+ runState: {
+ status: "running",
+ retry_pending: false,
+ attempt: 1,
+ dataUpdatedAt: 0,
+ },
}));
vi.mock("@/api/AxiosClient", () => ({ getClient: mockGetClient }));
@@ -19,9 +28,11 @@ vi.mock("./useWorkflowRunWithWorkflowQuery", () => ({
useWorkflowRunWithWorkflowQuery: () => ({
data: {
status: runState.status,
+ attempt: runState.attempt,
+ retry_pending: runState.retry_pending,
workflow: { workflow_permanent_id: "wpid_1" },
},
- dataUpdatedAt: 0,
+ dataUpdatedAt: runState.dataUpdatedAt,
}),
}));
@@ -30,6 +41,10 @@ import { useRunHealEpisodesQuery } from "./useRunHealEpisodesQuery";
afterEach(() => {
vi.clearAllMocks();
runState.status = "running";
+ runState.retry_pending = false;
+ runState.attempt = 1;
+ runState.dataUpdatedAt = 0;
+ focusManager.setFocused(undefined);
});
describe("useRunHealEpisodesQuery", () => {
@@ -106,3 +121,117 @@ describe("useRunHealEpisodesQuery", () => {
);
});
});
+
+it("refreshes execution updates but retains episodes through retry-wait polls, focus, and remount", async () => {
+ const initial = { episodes: [{ workflow_run_block_id: "wrb_initial" }] };
+ const duringExecution = {
+ episodes: [{ workflow_run_block_id: "wrb_executing" }],
+ };
+ const finished = { episodes: [{ workflow_run_block_id: "wrb_finished" }] };
+ const nextAttempt = { episodes: [{ workflow_run_block_id: "wrb_next" }] };
+ let serverData = initial;
+ mockGet.mockImplementation(async () => ({ data: serverData }));
+ mockGetClient.mockResolvedValue({ get: mockGet });
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ function wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ }
+ const useEpisodes = () => useRunHealEpisodesQuery({ workflowRunId: "wr_1" });
+ const mounted = renderHook(useEpisodes, { wrapper });
+ await waitFor(() => expect(mounted.result.current.data).toEqual(initial));
+
+ serverData = duringExecution;
+ runState.dataUpdatedAt++;
+ mounted.rerender();
+ await waitFor(() =>
+ expect(mounted.result.current.data).toEqual(duringExecution),
+ );
+
+ serverData = finished;
+ runState.status = "failed";
+ runState.retry_pending = true;
+ runState.dataUpdatedAt++;
+ mounted.rerender();
+ await waitFor(() => expect(mounted.result.current.data).toEqual(finished));
+
+ serverData = nextAttempt;
+ for (let tick = 0; tick < 3; tick++) {
+ await act(async () => {
+ runState.dataUpdatedAt++;
+ mounted.rerender();
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(mounted.result.current.data).toEqual(finished);
+ expect(
+ queryClient.getQueryState([
+ "run-heal-episodes",
+ "wr_1",
+ "failed",
+ 1,
+ true,
+ ])?.isInvalidated,
+ ).toBe(false);
+ }
+ await act(async () => {
+ focusManager.setFocused(false);
+ focusManager.setFocused(true);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(mounted.result.current.data).toEqual(finished);
+ mounted.unmount();
+ const remounted = renderHook(useEpisodes, { wrapper });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(remounted.result.current.data).toEqual(finished);
+
+ runState.status = "running";
+ runState.retry_pending = false;
+ runState.dataUpdatedAt++;
+ remounted.rerender();
+ await waitFor(() =>
+ expect(remounted.result.current.data).toEqual(nextAttempt),
+ );
+ remounted.unmount();
+ queryClient.clear();
+});
+
+it("re-reads consecutive failed attempts without showing the previous attempt's episodes", async () => {
+ runState.status = "failed";
+ const first = { episodes: [{ workflow_run_block_id: "wrb_attempt_1" }] };
+ const second = { episodes: [{ workflow_run_block_id: "wrb_attempt_2" }] };
+ mockGet.mockResolvedValue({ data: first });
+ mockGetClient.mockResolvedValue({ get: mockGet });
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ const { result, rerender, unmount } = renderHook(
+ () => useRunHealEpisodesQuery({ workflowRunId: "wr_fail_twice" }),
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.data).toEqual(first));
+ let finish: (value: { data: typeof second }) => void = () => {};
+ mockGet.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ runState.attempt = 2;
+ rerender();
+ await waitFor(() => expect(result.current.isFetching).toBe(true));
+ expect(result.current.data).toBeUndefined();
+ await act(async () => finish({ data: second }));
+ await waitFor(() => expect(result.current.data).toEqual(second));
+ unmount();
+ client.clear();
+});
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.ts
index bd8c538bf..d3718ecd8 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.ts
@@ -1,7 +1,10 @@
import { useEffect, useRef } from "react";
import { getClient } from "@/api/AxiosClient";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
-import { statusIsNotFinalized } from "@/routes/tasks/types";
+import {
+ getRunAttempt,
+ runIsExecuting,
+} from "@/routes/workflows/workflowRun/runRetryState";
import {
keepPreviousData,
useQuery,
@@ -25,24 +28,45 @@ function useRunHealEpisodesQuery({
workflowRunId,
});
- // Follow the workflow-run query's polling: while a run is active it refetches
- // (~5s), so invalidate heal episodes on each update — a self-heal recorded
- // mid-run then surfaces without needing a remount or window refocus.
- const prevDataUpdatedAtRef = useRef<number>(dataUpdatedAt);
+ const executing = Boolean(workflowRun && runIsExecuting(workflowRun));
+ const attempt = workflowRun ? getRunAttempt(workflowRun) : 1;
+ const previousRunUpdateRef = useRef({
+ workflowRunId,
+ dataUpdatedAt,
+ executing,
+ });
useEffect(() => {
- if (dataUpdatedAt !== prevDataUpdatedAtRef.current && workflowRunId) {
+ const previous = previousRunUpdateRef.current;
+ // Include the stop transition so the final heal episode is fetched, but
+ // ignore status polls that only confirm a retry wait.
+ if (
+ dataUpdatedAt !== previous.dataUpdatedAt &&
+ workflowRunId &&
+ (executing ||
+ (previous.workflowRunId === workflowRunId && previous.executing))
+ ) {
queryClient.invalidateQueries({
queryKey: ["run-heal-episodes", workflowRunId],
});
}
- prevDataUpdatedAtRef.current = dataUpdatedAt;
- }, [dataUpdatedAt, workflowRunId, queryClient]);
+ previousRunUpdateRef.current = {
+ workflowRunId,
+ dataUpdatedAt,
+ executing,
+ };
+ }, [dataUpdatedAt, workflowRunId, executing, queryClient]);
return useQuery<RunHealEpisodesResponse>({
// Same reason the run timeline carries its status: the invalidation above only fires while the
// run query is still polling, so a reader that unmounts mid-run and comes back after the run
// finished would otherwise be served the episodes as of the unmount.
- queryKey: ["run-heal-episodes", workflowRunId, workflowRun?.status],
+ queryKey: [
+ "run-heal-episodes",
+ workflowRunId,
+ workflowRun?.status,
+ attempt,
+ workflowRun?.retry_pending,
+ ],
queryFn: async () => {
const client = await getClient(credentialGetter, "sans-api-v1");
return client
@@ -51,11 +75,14 @@ function useRunHealEpisodesQuery({
},
// The status swap lands on an uncached key, and both readers render null on absent data — so
// without this the heal chip and the block heal panel blink out as the run finishes.
- placeholderData: keepPreviousData,
- refetchOnMount:
- workflowRun && statusIsNotFinalized(workflowRun) ? "always" : false,
- refetchOnWindowFocus:
- workflowRun && statusIsNotFinalized(workflowRun) ? "always" : false,
+ placeholderData: (previousData, previousQuery) =>
+ previousQuery &&
+ previousQuery.queryKey[1] === workflowRunId &&
+ previousQuery.queryKey[3] === attempt
+ ? keepPreviousData(previousData)
+ : undefined,
+ refetchOnMount: executing ? "always" : false,
+ refetchOnWindowFocus: executing ? "always" : false,
enabled: Boolean(workflowRunId) && enabled,
});
}
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx
index c45dbd2f4..ff5c47bf1 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx
@@ -4,11 +4,18 @@ import {
QueryClientProvider,
QueryObserver,
} from "@tanstack/react-query";
-import { cleanup, render, renderHook, waitFor } from "@testing-library/react";
+import {
+ act,
+ cleanup,
+ render,
+ renderHook,
+ waitFor,
+} from "@testing-library/react";
import { type ReactNode } from "react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { toast } from "@/components/ui/use-toast";
import { Status } from "@/api/types";
import { retryTransientNetworkFailures } from "@/api/QueryClient";
import { TooltipProvider } from "@/components/ui/tooltip";
@@ -25,6 +32,8 @@ import {
} from "./useWorkflowRunQuery";
import { useWorkflowRunWithWorkflowQuery } from "./useWorkflowRunWithWorkflowQuery";
+vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));
+
const { getClientMock } = vi.hoisted(() => ({ getClientMock: vi.fn() }));
vi.mock("@/api/AxiosClient", async (importOriginal) => ({
@@ -362,3 +371,27 @@ describe("studio consumers of a retained run payload", () => {
expect(container.textContent).toBe("");
});
});
+
+test("Studio completion toast waits for cancel to revoke a pending retry and fires once", async () => {
+ const client = makeClient();
+ const id = "wr_cancel_wait";
+ const run = {
+ ...buildRun(id, Status.Failed),
+ retry_pending: true,
+ next_attempt_at: "2026-09-09T12:00:00Z",
+ };
+ client.setQueryData(["workflowRun", id], run);
+ const { rerender } = renderHook(() => useStudioRunSignals(), {
+ wrapper: harness(client, `/agents/wpid_1/studio?wr=${id}`),
+ });
+ expect(toast).not.toHaveBeenCalled();
+ act(() => {
+ client.setQueryData(["workflowRun", id], { ...run, retry_pending: false });
+ });
+ await waitFor(() => expect(toast).toHaveBeenCalledTimes(1));
+ rerender();
+ expect(toast).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Run Failed" }),
+ );
+ expect(toast).toHaveBeenCalledTimes(1);
+});
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts
index 4caa54c25..97e0f6a3f 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts
@@ -1,12 +1,14 @@
+import { runIsLogicallyActive } from "@/routes/workflows/workflowRun/runRetryState";
import { useCallback } from "react";
import { getClient } from "@/api/AxiosClient";
-import { Status, WorkflowRunStatusApiResponse } from "@/api/types";
+import {
+ Status,
+ WorkflowRunRetryFields,
+ WorkflowRunStatusApiResponse,
+} from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { useFirstParam } from "@/hooks/useFirstParam";
-import {
- statusIsNotFinalized,
- statusIsRunningOrQueued,
-} from "@/routes/tasks/types";
+
import {
DefaultError,
keepPreviousData,
@@ -33,14 +35,14 @@ const RUN_STATUS_OUTAGE_RETRY_INTERVAL_MS = 30000;
// fetchFailureCount, which query-core resets at the start of every fetch.
function getRunStatusRefetchInterval(state: {
status: "pending" | "error" | "success";
- data?: { status: Status };
+ data?: { status: Status } & WorkflowRunRetryFields;
dataUpdatedAt: number;
errorUpdatedAt: number;
}): number | false {
if (!state.data) {
return false;
}
- if (!statusIsNotFinalized(state.data)) {
+ if (!runIsLogicallyActive(state.data)) {
return false;
}
if (
@@ -110,13 +112,13 @@ function useWorkflowRunQuery(options?: { workflowRunId: string | undefined }) {
if (!query.state.data) {
return false;
}
- return statusIsRunningOrQueued(query.state.data) ? "always" : false;
+ return runIsLogicallyActive(query.state.data) ? "always" : false;
},
refetchOnWindowFocus: (query) => {
if (!query.state.data) {
return false;
}
- return statusIsRunningOrQueued(query.state.data);
+ return runIsLogicallyActive(query.state.data);
},
enabled: !!globalWorkflows && !!workflowPermanentId && !!workflowRunId,
});
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.test.tsx b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.test.tsx
index 6b43f61b5..d6340fa48 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.test.tsx
@@ -12,7 +12,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
const { mockGet, mockGetClient, runState } = vi.hoisted(() => ({
mockGet: vi.fn(),
mockGetClient: vi.fn(),
- runState: { status: "completed" },
+ runState: { status: "completed", attempt: 1, retry_pending: false },
}));
vi.mock("@/api/AxiosClient", () => ({
@@ -30,7 +30,7 @@ vi.mock("./useGlobalWorkflowsQuery", () => ({
vi.mock("./useWorkflowRunWithWorkflowQuery", () => ({
useWorkflowRunWithWorkflowQuery: () => ({
data: {
- status: runState.status,
+ ...runState,
workflow: { workflow_permanent_id: "wpid_1" },
},
dataUpdatedAt: 0,
@@ -56,9 +56,44 @@ afterEach(() => {
vi.useRealTimers();
focusManager.setFocused(undefined);
runState.status = "completed";
+ runState.attempt = 1;
+ runState.retry_pending = false;
});
describe("useWorkflowRunTimelineQuery", () => {
+ it("stops polling during a retry delay and fetches the next attempt", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ focusManager.setFocused(true);
+ runState.status = "failed";
+ runState.retry_pending = true;
+ mockGet.mockResolvedValue({ data: [] });
+ mockGetClient.mockResolvedValue({ get: mockGet });
+
+ const { result, rerender } = renderHook(
+ () => useWorkflowRunTimelineQuery(),
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ const readsBeforeDelay = mockGet.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(3 * RUNNING_TIMELINE_REFETCH_INTERVAL_MS);
+ expect(mockGet).toHaveBeenCalledTimes(readsBeforeDelay);
+
+ runState.status = "queued";
+ runState.attempt = 2;
+ runState.retry_pending = false;
+ rerender();
+ await waitFor(() =>
+ expect(mockGet.mock.calls.length).toBeGreaterThan(readsBeforeDelay),
+ );
+
+ runState.status = "running";
+ rerender();
+ await waitFor(() => expect(result.current.isFetching).toBe(false));
+ const readsBeforePolling = mockGet.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(3 * RUNNING_TIMELINE_REFETCH_INTERVAL_MS);
+ expect(mockGet.mock.calls.length).toBeGreaterThan(readsBeforePolling);
+ });
+
it("returns the timeline when the response is an array", async () => {
mockGet.mockResolvedValue({ data: [] });
mockGetClient.mockResolvedValue({ get: mockGet });
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.ts
index 89a7b3505..d750c5dd3 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.ts
@@ -1,7 +1,8 @@
+import { runIsLogicallyActive } from "@/routes/workflows/workflowRun/runRetryState";
import { getClient } from "@/api/AxiosClient";
import { Status } from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
-import { statusIsNotFinalized } from "@/routes/tasks/types";
+
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { WorkflowRunTimelineItem } from "../types/workflowRunTypes";
import { useWorkflowRunWithWorkflowQuery } from "./useWorkflowRunWithWorkflowQuery";
@@ -31,7 +32,7 @@ function useWorkflowRunTimelineQuery(options?: {
const { data: workflowRun } = useWorkflowRunWithWorkflowQuery(options);
const workflow = workflowRun?.workflow;
const workflowPermanentId = workflow?.workflow_permanent_id;
- const runIsLive = !!workflowRun && statusIsNotFinalized(workflowRun);
+ const runIsLive = !!workflowRun && runIsLogicallyActive(workflowRun);
// Only a running run writes timeline rows. Created, queued and paused are live but idle, and a
// paused run waits on a human for as long as that takes.
const runIsWriting = workflowRun?.status === Status.Running;
@@ -49,6 +50,8 @@ function useWorkflowRunTimelineQuery(options?: {
workflowPermanentId,
workflowRunId,
workflowRun?.status,
+ workflowRun?.attempt,
+ workflowRun?.retry_pending,
],
activeOrgQueryKeyScope,
),
@@ -81,7 +84,7 @@ function useWorkflowRunTimelineQuery(options?: {
if (query.state.status === "error") {
return false;
}
- return runIsLive ? RUNNING_TIMELINE_REFETCH_INTERVAL_MS : false;
+ return runIsWriting ? RUNNING_TIMELINE_REFETCH_INTERVAL_MS : false;
},
// The interval otherwise pauses while the window is unfocused, and a run watched from another
// window keeps writing blocks the whole time. Scoped to a running run so a backgrounded tab
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts
index c063554e3..65930ce01 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts
@@ -1,8 +1,9 @@
+import { runIsLogicallyActive } from "@/routes/workflows/workflowRun/runRetryState";
import { useCallback } from "react";
import { getClient } from "@/api/AxiosClient";
import { WorkflowRunStatusApiResponseWithWorkflow } from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
-import { statusIsRunningOrQueued } from "@/routes/tasks/types";
+
import {
DefaultError,
keepPreviousData,
@@ -64,13 +65,13 @@ function useWorkflowRunWithWorkflowQuery(options?: {
if (!query.state.data) {
return false;
}
- return statusIsRunningOrQueued(query.state.data) ? "always" : false;
+ return runIsLogicallyActive(query.state.data) ? "always" : false;
},
refetchOnWindowFocus: (query) => {
if (!query.state.data) {
return false;
}
- return statusIsRunningOrQueued(query.state.data);
+ return runIsLogicallyActive(query.state.data);
},
enabled: (options?.enabled ?? true) && !!workflowRunId,
});
diff --git a/skyvern-frontend/src/routes/workflows/studio/BlockStatusBar.test.tsx b/skyvern-frontend/src/routes/workflows/studio/BlockStatusBar.test.tsx
index 673c51f73..0a55f9703 100644
--- a/skyvern-frontend/src/routes/workflows/studio/BlockStatusBar.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/BlockStatusBar.test.tsx
@@ -9,6 +9,7 @@ import { BlockStatusBar } from "./BlockStatusBar";
const mocks = vi.hoisted(() => ({
timeline: undefined as unknown,
+ run: undefined as unknown,
isPlaceholderData: false,
}));
@@ -19,6 +20,10 @@ vi.mock("../hooks/useWorkflowRunTimelineQuery", () => ({
}),
}));
+vi.mock("../hooks/useWorkflowRunWithWorkflowQuery", () => ({
+ useWorkflowRunWithWorkflowQuery: () => ({ data: mocks.run }),
+}));
+
function seedRunningBlock() {
mocks.timeline = [
{
@@ -49,6 +54,7 @@ function renderBar() {
afterEach(() => {
cleanup();
mocks.timeline = undefined;
+ mocks.run = undefined;
mocks.isPlaceholderData = false;
});
@@ -70,3 +76,10 @@ describe("BlockStatusBar", () => {
expect(container.textContent).toContain("Running");
});
});
+
+it("does not show an attempt-1 block once attempt 2 starts", () => {
+ seedRunningBlock();
+ mocks.run = { workflow_run_id: "wr_2", status: Status.Running, attempt: 2 };
+ const { container } = renderBar();
+ expect(container.textContent).toBe("");
+});
diff --git a/skyvern-frontend/src/routes/workflows/studio/BlockStatusBar.tsx b/skyvern-frontend/src/routes/workflows/studio/BlockStatusBar.tsx
index 626f705b0..b2513e9f1 100644
--- a/skyvern-frontend/src/routes/workflows/studio/BlockStatusBar.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/BlockStatusBar.tsx
@@ -5,6 +5,9 @@ import {
} from "@radix-ui/react-icons";
import { useWorkflowRunTimelineQuery } from "../hooks/useWorkflowRunTimelineQuery";
import { buildBlockStatusMap, runOutcomeFromStatus } from "./runProjections";
+import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";
+import { getRunAttempt } from "../workflowRun/runRetryState";
+import { filterTimelineToAttempt } from "../workflowRun/workflowTimelineUtils";
import { useStudioRunId } from "./useStudioRunId";
/**
@@ -20,12 +23,27 @@ export function BlockStatusBar({ blockLabel }: { blockLabel: string }) {
const { data: retainedTimeline, isPlaceholderData: timelineIsPlaceholder } =
useWorkflowRunTimelineQuery(runId ? { workflowRunId: runId } : undefined);
const timeline = timelineIsPlaceholder ? undefined : retainedTimeline;
- const statusMap = useMemo(() => buildBlockStatusMap(timeline), [timeline]);
+ const { data: workflowRun } = useWorkflowRunWithWorkflowQuery({
+ workflowRunId: runId ?? undefined,
+ });
+ const statusMap = useMemo(
+ () =>
+ buildBlockStatusMap(
+ timeline
+ ? filterTimelineToAttempt(
+ timeline,
+ workflowRun?.attempts ?? [],
+ getRunAttempt(workflowRun ?? {}),
+ )
+ : undefined,
+ ),
+ [timeline, workflowRun],
+ );
const state = statusMap[blockLabel];
if (!state || !state.status) {
return null;
}
- const outcome = runOutcomeFromStatus(state.status);
+ const outcome = runOutcomeFromStatus({ status: state.status });
if (outcome === "running") {
return (
diff --git a/skyvern-frontend/src/routes/workflows/studio/BrowserTab.test.tsx b/skyvern-frontend/src/routes/workflows/studio/BrowserTab.test.tsx
index bd42ecb88..1e4ebb433 100644
--- a/skyvern-frontend/src/routes/workflows/studio/BrowserTab.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/BrowserTab.test.tsx
@@ -32,6 +32,11 @@ const mocks = vi.hoisted(() => ({
timeline: undefined as unknown,
debugSession: undefined as unknown,
runs: [] as Array<{ workflow_run_id: string }>,
+ realScreenshot: false,
+}));
+
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: async () => ({ get: async () => ({ data: [] }) }),
}));
vi.mock("../hooks/useWorkflowRunWithWorkflowQuery", () => ({
@@ -64,8 +69,15 @@ vi.mock("@/routes/streaming/StreamDiagnostics", () => ({
StreamModeBadge: ({ mode }: { mode: string }) => (
<span data-testid="stream-mode-badge">{mode}</span>
),
- StreamStatusPanel: ({ diagnostic }: { diagnostic: { title: string } }) => (
- <div data-testid="stream-status">{diagnostic.title}</div>
+ StreamStatusPanel: ({
+ diagnostic,
+ }: {
+ diagnostic: { title: string; detail?: string };
+ }) => (
+ <div data-testid="stream-status">
+ <span>{diagnostic.title}</span>
+ <span>{diagnostic.detail}</span>
+ </div>
),
}));
vi.mock("./runview/HeroRecording", () => ({
@@ -73,14 +85,21 @@ vi.mock("./runview/HeroRecording", () => ({
<div data-testid="hero-recording" data-count={recordingUrls.length} />
),
}));
-vi.mock("./runview/HeroScreenshot", () => ({
- HeroScreenshot: ({ selection }: { selection: unknown }) => (
- <div
- data-testid="hero-screenshot"
- data-selection={JSON.stringify(selection)}
- />
- ),
-}));
+vi.mock("./runview/HeroScreenshot", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("./runview/HeroScreenshot")>();
+ return {
+ HeroScreenshot: (props: Parameters<typeof actual.HeroScreenshot>[0]) =>
+ mocks.realScreenshot ? (
+ <actual.HeroScreenshot {...props} />
+ ) : (
+ <div
+ data-testid="hero-screenshot"
+ data-selection={JSON.stringify(props.selection)}
+ />
+ ),
+ };
+});
vi.mock("./runview/RunLiveStream", () => ({
RunLiveStream: (props: {
workflowRunId: string;
@@ -194,7 +213,7 @@ function seedRun({
function renderBrowserPane(initialPath: string) {
const setBrowserStreamSlot = vi.fn();
const queryClient = new QueryClient();
- const view = render(
+ const pane = () => (
<QueryClientProvider client={queryClient}>
<TooltipProvider delayDuration={0}>
<StudioShellContext.Provider
@@ -224,9 +243,15 @@ function renderBrowserPane(initialPath: string) {
</MemoryRouter>
</StudioShellContext.Provider>
</TooltipProvider>
- </QueryClientProvider>,
+ </QueryClientProvider>
);
- return { ...view, setBrowserStreamSlot };
+ const view = render(pane());
+ return {
+ ...view,
+ setBrowserStreamSlot,
+ queryClient,
+ rerenderPane: () => view.rerender(pane()),
+ };
}
const STUDIO_PATH = "/workflows/wpid_test/studio?panes=copilot,browser";
@@ -240,6 +265,7 @@ beforeEach(() => {
mocks.timeline = undefined;
mocks.debugSession = undefined;
mocks.runs = [];
+ mocks.realScreenshot = false;
});
afterEach(() => {
@@ -247,6 +273,109 @@ afterEach(() => {
});
describe("BrowserTab view machine", () => {
+ it("keeps Live selected during a retry wait and pauses artifact polling until execution resumes", () => {
+ mocks.realScreenshot = true;
+ seedRun({ status: Status.Running });
+ const block = buildBlock({
+ actions: [buildAction({ screenshot_artifact_id: null })],
+ });
+ mocks.timeline = [buildBlockItem(block)];
+ const { queryClient, rerenderPane } = renderBrowserPane(
+ `${STUDIO_PATH}&wr=wr_1`,
+ );
+ const expectLive = () =>
+ expect(
+ screen
+ .getByRole("button", { name: "Live" })
+ .getAttribute("aria-pressed"),
+ ).toBe("true");
+ const expectArtifactPolling = (interval: number | false) => {
+ const queries = queryClient
+ .getQueryCache()
+ .getAll()
+ .filter(
+ (query) => query.queryKey[query.queryKey.length - 1] === "artifacts",
+ );
+ expect(queries).toHaveLength(3);
+ for (const query of queries) {
+ expect(query.observers[0]?.options.refetchInterval).toBe(interval);
+ }
+ expect(
+ queries.find((query) => query.queryKey[0] === "step")?.observers[0]
+ ?.options.enabled,
+ ).toBe(true);
+ };
+
+ expectLive();
+ mocks.workflowRun = Object.assign({}, mocks.workflowRun, {
+ status: Status.Failed,
+ retry_pending: true,
+ });
+ rerenderPane();
+ expectLive();
+ expect(
+ screen.getByText("The browser reconnects when the next attempt starts."),
+ ).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Screenshots" }));
+ expectArtifactPolling(false);
+ fireEvent.click(screen.getByRole("button", { name: "Live" }));
+
+ mocks.workflowRun = Object.assign({}, mocks.workflowRun, {
+ status: Status.Running,
+ retry_pending: false,
+ attempt: 2,
+ });
+ mocks.timeline = [{ ...buildBlockItem(block), attempt: 2 }];
+ rerenderPane();
+ expectLive();
+ expect(screen.getByTestId("run-live-stream")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Screenshots" }));
+ expectArtifactPolling(5000);
+ });
+
+ it("keeps historical screenshots and recordings accessible during a retry wait", () => {
+ seedRun({ status: Status.Completed, recordingUrl: "https://r.test/1.mp4" });
+ mocks.workflowRun = Object.assign({}, mocks.workflowRun, {
+ retry_pending: true,
+ attempt: 2,
+ });
+ mocks.timeline = [
+ {
+ ...buildBlockItem(
+ buildBlock({ workflow_run_block_id: "wrb_historical" }),
+ ),
+ attempt: 1,
+ },
+ ];
+ renderBrowserPane(`${STUDIO_PATH}&wr=wr_1&active=wrb_historical`);
+
+ const retryMessage = "The browser reconnects when the next attempt starts.";
+ expect(screen.queryByText(retryMessage)).toBeNull();
+ expect(
+ JSON.parse(
+ screen.getByTestId("hero-screenshot").getAttribute("data-selection") ??
+ "{}",
+ ),
+ ).toEqual({
+ kind: "block",
+ workflowRunBlockId: "wrb_historical",
+ blockType: "task",
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: "Recording" }));
+ expect(screen.getByTestId("hero-recording")).toBeTruthy();
+ expect(screen.queryByText(retryMessage)).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: "Screenshots" }));
+ expect(screen.getByTestId("hero-screenshot")).toBeTruthy();
+ expect(screen.queryByText(retryMessage)).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: "Live" }));
+ expect(screen.getByText(retryMessage)).toBeTruthy();
+ expect(screen.queryByTestId("run-live-stream")).toBeNull();
+ });
+
it("shows the live debug stream slot with no run history", () => {
mocks.debugSession = { browser_session_id: "pbs_test" };
renderBrowserPane(STUDIO_PATH);
@@ -614,3 +743,18 @@ describe("stream-mode badge dev gating", () => {
expect(screen.queryByTestId("stream-mode-badge")).toBeNull();
});
});
+
+it.each([false, true])(
+ "keeps the shared browser visible during a retry wait (recording=%s)",
+ (recording) => {
+ seedRun({ status: Status.Failed, browserSessionId: "pbs_test" });
+ mocks.workflowRun = Object.assign({}, mocks.workflowRun, {
+ retry_pending: true,
+ });
+ mocks.debugSession = { browser_session_id: "pbs_test" };
+ useRecordingStore.setState({ isRecording: recording });
+ renderBrowserPane(recording ? `${STUDIO_PATH}&wr=wr_1` : STUDIO_PATH);
+ expect(screen.getByTestId("browser-pane-stream-slot")).toBeTruthy();
+ expect(screen.queryByText("Retry pending")).toBeNull();
+ },
+);
diff --git a/skyvern-frontend/src/routes/workflows/studio/BrowserTab.tsx b/skyvern-frontend/src/routes/workflows/studio/BrowserTab.tsx
index f794aed10..6379b1fb2 100644
--- a/skyvern-frontend/src/routes/workflows/studio/BrowserTab.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/BrowserTab.tsx
@@ -1,3 +1,4 @@
+import { runIsRetryWaiting } from "../workflowRun/runRetryState";
import { useCallback } from "react";
import { ClockIcon } from "@radix-ui/react-icons";
import { usePostHog } from "posthog-js/react";
@@ -31,7 +32,7 @@ export function BrowserTab() {
const {
workflowRun,
- running,
+ executing,
provisioning,
isPaused,
recordingUrls,
@@ -62,7 +63,15 @@ export function BrowserTab() {
<div className="relative flex h-full min-h-0 w-full items-center justify-center overflow-hidden bg-slate-950">
{view === "live" ? (
showRunStream ? (
- provisioning ? (
+ workflowRun && runIsRetryWaiting(workflowRun) ? (
+ <StreamStatusPanel
+ diagnostic={{
+ title: "Retry pending",
+ detail: "The browser reconnects when the next attempt starts.",
+ pending: true,
+ }}
+ />
+ ) : provisioning ? (
// Mounting the stream while the run is still queued opens a
// socket the backend never feeds; wait until it actually runs.
<StreamStatusPanel
@@ -75,6 +84,7 @@ export function BrowserTab() {
) : (
<RunLiveStream
workflowRunId={runId}
+ run={workflowRun}
browserSessionId={workflowRun?.browser_session_id ?? null}
interactive={isPaused}
/>
@@ -122,7 +132,7 @@ export function BrowserTab() {
/>
)
) : heroSelection ? (
- <HeroScreenshot selection={heroSelection} running={running} />
+ <HeroScreenshot selection={heroSelection} running={executing} />
) : visuals.finalized ? (
<StreamStatusPanel
diagnostic={{
diff --git a/skyvern-frontend/src/routes/workflows/studio/PastRunsList.test.tsx b/skyvern-frontend/src/routes/workflows/studio/PastRunsList.test.tsx
index d6b328984..3b4f98f72 100644
--- a/skyvern-frontend/src/routes/workflows/studio/PastRunsList.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/PastRunsList.test.tsx
@@ -283,3 +283,11 @@ describe("searchWithRunSwitched", () => {
expect(params.get("panes")).toBe("browser");
});
});
+
+test("the attempt chip adds no tab stop inside its run row", () => {
+ mocks.runs = [makeRun({ attempt: 2 })];
+ renderList();
+ const chip = screen.getByText("Attempt 2");
+ expect(chip.hasAttribute("tabindex")).toBe(false);
+ expect(chip.closest("button")).toBeTruthy();
+});
diff --git a/skyvern-frontend/src/routes/workflows/studio/PastRunsList.tsx b/skyvern-frontend/src/routes/workflows/studio/PastRunsList.tsx
index bcc493b5e..9a186db59 100644
--- a/skyvern-frontend/src/routes/workflows/studio/PastRunsList.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/PastRunsList.tsx
@@ -3,6 +3,7 @@ import { Link } from "react-router-dom";
import { TriggerType } from "@/api/types";
import { StatusBadge } from "@/components/StatusBadge";
+import { WorkflowRunAttemptChip } from "@/components/WorkflowRunAttemptChip";
import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";
import { cn, handleInfiniteScroll } from "@/util/utils";
@@ -135,6 +136,11 @@ export function PastRunsList({
status={run.status}
className="shrink-0 md:w-auto"
/>
+ <WorkflowRunAttemptChip
+ attempt={run.attempt}
+ retryPending={run.retry_pending}
+ nextAttemptAt={run.next_attempt_at}
+ />
<span className="flex min-w-0 flex-1 flex-col">
{/* Runs in this list all belong to one workflow, so the
title never varies — when it ran is what tells them
diff --git a/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx b/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx
index e814a557a..28a0642d4 100644
--- a/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx
@@ -1,7 +1,6 @@
+import { runIsLogicallyFinal } from "@/routes/workflows/workflowRun/runRetryState";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";
-
-import { statusIsFinalized } from "@/routes/tasks/types";
import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";
import { getRerunNavigationState } from "../utils";
import { RunView } from "./runview/RunView";
@@ -32,7 +31,7 @@ export function RunTab() {
const retryPath = `/agents/${workflowPermanentId}/run`;
const retryState =
workflowRun &&
- statusIsFinalized(workflowRun) &&
+ runIsLogicallyFinal(workflowRun) &&
workflowRun.task_v2 === null
? getRerunNavigationState(workflowRun)
: undefined;
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioBrowserStream.test.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioBrowserStream.test.tsx
index b41079476..9db3ab70f 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioBrowserStream.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioBrowserStream.test.tsx
@@ -9,6 +9,7 @@ import { useRecordingStore } from "@/store/useRecordingStore";
import { useStudioBrowserStore } from "@/store/useStudioBrowserStore";
import { StudioBrowserStream } from "./StudioBrowserStream";
+import { type StudioPaneId } from "./panes";
import { useStudioPanes } from "./useStudioPanes";
const runtimeConfigMock = vi.hoisted(() => ({
@@ -105,7 +106,10 @@ function OpenBrowserPaneButton() {
}
// The browser pane's visibility comes from ?panes= in the URL.
-function renderStudioBrowserStream(initialPath: string) {
+function renderStudioBrowserStream(
+ initialPath: string,
+ visiblePanes?: readonly StudioPaneId[],
+) {
return render(
<MemoryRouter initialEntries={[initialPath]}>
<Routes>
@@ -113,7 +117,7 @@ function renderStudioBrowserStream(initialPath: string) {
path="/workflows/:workflowPermanentId/studio"
element={
<>
- <StudioBrowserStream />
+ <StudioBrowserStream visiblePanes={visiblePanes} />
<OpenBrowserPaneButton />
</>
}
@@ -312,6 +316,14 @@ describe("StudioBrowserStream block-run co-drive", () => {
expect(screen.queryByRole("status")).toBeNull();
});
+ it("withdraws control when fullscreen hides an otherwise open Browser pane", () => {
+ mockWorkflowRun(Status.Running, "pbs_test");
+ renderStudioBrowserStream(BLOCK_RUN_OPEN_PATH, ["editor"]);
+
+ expect(controlButtonsAttr("emit vnc frame")).toBe("no");
+ expect(screen.queryByRole("status")).toBeNull();
+ });
+
it("shows no sharing pill during a recording (the recorder is driving)", () => {
useRecordingStore.setState({ isRecording: true });
mockWorkflowRun(Status.Running, "pbs_test");
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioBrowserStream.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioBrowserStream.tsx
index 7ee10f5ac..fdac51923 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioBrowserStream.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioBrowserStream.tsx
@@ -4,6 +4,7 @@ import { useRecordingStore } from "@/store/useRecordingStore";
import { useStudioBrowserStore } from "@/store/useStudioBrowserStore";
import { StreamPresenter } from "./StreamPresenter";
+import { type StudioPaneId } from "./panes";
import { useBrowserPaneView } from "./useBrowserPaneView";
import { useExecutingBlockRun } from "./useExecutingBlockRun";
import { useStudioPanes } from "./useStudioPanes";
@@ -12,9 +13,14 @@ import { useStudioPanes } from "./useStudioPanes";
* The studio's single live-browser stream, portaled into a host node re-parented
* between the open panes so the socket persists instead of re-booting.
*/
-export function StudioBrowserStream() {
+export function StudioBrowserStream({
+ visiblePanes,
+}: {
+ visiblePanes?: readonly StudioPaneId[];
+}) {
const { panes } = useStudioPanes();
- const browserPaneOpen = panes.includes("browser");
+ const renderedPanes = visiblePanes ?? panes;
+ const browserPaneOpen = renderedPanes.includes("browser");
const isRecording = useRecordingStore((s) => s.isRecording);
const resetRecording = useRecordingStore((s) => s.reset);
const reloadNonce = useStudioBrowserStore((s) => s.reloadNonce);
@@ -87,7 +93,7 @@ export function StudioBrowserStream() {
// header already shows the timer + step count — an on-stream REC pill
// would duplicate it. Closing that pane brings the pill back on either
// transport (VNC renders it in BrowserStream, CDP in StreamPresenter).
- hideRecordingIndicator={panes.includes("copilot")}
+ hideRecordingIndicator={renderedPanes.includes("copilot")}
onUrlChange={handleUrlChange}
onActivity={handleActivity}
/>
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioPaneToggles.test.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioPaneToggles.test.tsx
index 02bdf171f..160ce756b 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioPaneToggles.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioPaneToggles.test.tsx
@@ -4,6 +4,7 @@ import {
cleanup,
fireEvent,
render,
+ renderHook,
screen,
waitFor,
} from "@testing-library/react";
@@ -21,7 +22,27 @@ import { WorkflowPermanentIdContext } from "@/routes/workflows/WorkflowPermanent
import { useStudioBrowserStore } from "@/store/useStudioBrowserStore";
import { useStudioShellStore } from "@/store/StudioShellStore";
+import { useStudioRunSignals } from "./useStudioRunSignals";
import { StudioPaneToggles } from "./StudioPaneToggles";
+import { claimRunCompletionNotice } from "../workflowRun/runCompletionNotices";
+
+test("completion claims retain the 500 most recently used run IDs", () => {
+ const runIds = Array.from(
+ { length: 501 },
+ (_, index) => `wr_bounded_${index}`,
+ );
+ const shown: string[] = [];
+ const claim = (id: string) =>
+ claimRunCompletionNotice(id, () => {
+ shown.push(id);
+ });
+ for (const id of runIds.slice(0, 500)) claim(id);
+ expect(claim(runIds[0]!)).toBe(false);
+ expect(claim(runIds[500]!)).toBe(true);
+ expect(claim(runIds[0]!)).toBe(false);
+ expect(claim(runIds[1]!)).toBe(true);
+ expect(shown).toEqual([...runIds, runIds[1]]);
+});
const { runsQueryMock, runWithWorkflowMock, infiniteRunsMock, copyTextMock } =
vi.hoisted(() => ({
@@ -54,7 +75,8 @@ function infiniteRuns(runs: Array<Record<string, unknown>>) {
}
vi.mock("../hooks/useWorkflowRunWithWorkflowQuery", () => ({
- useWorkflowRunWithWorkflowQuery: () => runWithWorkflowMock(),
+ useWorkflowRunWithWorkflowQuery: (options: { workflowRunId?: string }) =>
+ runWithWorkflowMock(options),
}));
// Radix Popover positioning observes the anchor; jsdom has no ResizeObserver.
@@ -269,12 +291,15 @@ describe("StudioPaneToggles run tab label", () => {
expect(screen.queryByRole("button", { name: "Copy run link" })).toBeNull();
});
- test("names the latest run when the URL names none", () => {
+ test("keeps Past Runs uninspected when the URL names none", () => {
runsQueryMock.mockReturnValue({
data: [{ workflow_run_id: "wr_late", status: Status.Completed }],
});
renderAt();
- expect(tab(/^View Run: wr_late/)).toBeTruthy();
+ expect(tab(/^Past Runs/)).toBeTruthy();
+ expect(runWithWorkflowMock.mock.lastCall?.[0]).toEqual({
+ workflowRunId: undefined,
+ });
});
test("reads 'Past Runs' while no run exists to inspect", () => {
@@ -397,8 +422,8 @@ describe("StudioPaneToggles run selector", () => {
describe("StudioPaneToggles run-status dot", () => {
test("shows a status-colored dot with a status icon for a finalized run", () => {
- runsQueryMock.mockReturnValue({ data: [{ status: Status.Completed }] });
- renderAt();
+ runWithWorkflowMock.mockReturnValue({ data: { status: Status.Completed } });
+ renderAt("/workflows/wpid_abc/studio?wr=wr_tab");
const dot = runsTab().querySelector(
"span.absolute.-right-1",
) as HTMLElement | null;
@@ -408,20 +433,20 @@ describe("StudioPaneToggles run-status dot", () => {
});
test("uses a different icon per finalized status (not color-only)", () => {
- runsQueryMock.mockReturnValue({
- data: [{ workflow_run_id: "wr_tab", status: Status.Failed }],
+ runWithWorkflowMock.mockReturnValue({
+ data: { workflow_run_id: "wr_tab", status: Status.Failed },
});
- const { unmount } = renderAt();
+ const { unmount } = renderAt("/workflows/wpid_abc/studio?wr=wr_tab");
const failedIcon = runsTab().querySelector(
"span.absolute.-right-1 svg",
)?.outerHTML;
unmount();
cleanup();
- runsQueryMock.mockReturnValue({
- data: [{ workflow_run_id: "wr_tab", status: Status.Canceled }],
+ runWithWorkflowMock.mockReturnValue({
+ data: { workflow_run_id: "wr_tab", status: Status.Canceled },
});
- renderAt();
+ renderAt("/workflows/wpid_abc/studio?wr=wr_tab");
const canceledIcon = runsTab().querySelector(
"span.absolute.-right-1 svg",
)?.outerHTML;
@@ -432,27 +457,27 @@ describe("StudioPaneToggles run-status dot", () => {
});
test("includes the finalized run status in the run tab accessible name", () => {
- runsQueryMock.mockReturnValue({
- data: [{ workflow_run_id: "wr_tab", status: Status.TimedOut }],
+ runWithWorkflowMock.mockReturnValue({
+ data: { workflow_run_id: "wr_tab", status: Status.TimedOut },
});
- renderAt();
+ renderAt("/workflows/wpid_abc/studio?wr=wr_tab");
expect(
screen.getByRole("button", { name: "View Run: wr_tab, timed out" }),
).toBeTruthy();
});
test("omits the dot while the run is still in flight", () => {
- runsQueryMock.mockReturnValue({ data: [{ status: Status.Running }] });
- renderAt();
+ runWithWorkflowMock.mockReturnValue({ data: { status: Status.Running } });
+ renderAt("/workflows/wpid_abc/studio?wr=wr_tab");
expect(runsTab().querySelector("span.absolute.-right-1")).toBeNull();
});
test("tooltips the run status even with labels expanded (no hidden xl:inline gate)", async () => {
- runsQueryMock.mockReturnValue({
- data: [{ workflow_run_id: "wr_tip", status: Status.Failed }],
+ runWithWorkflowMock.mockReturnValue({
+ data: { workflow_run_id: "wr_tip", status: Status.Failed },
});
- renderAt();
- fireEvent.focus(tab(/^View Run: wr_tip/));
+ renderAt("/workflows/wpid_abc/studio?wr=wr_tab");
+ fireEvent.focus(tab(/^View Run: wr_tab/));
const tooltip = await screen.findByRole("tooltip");
expect(tooltip.textContent).toContain("failed");
});
@@ -558,3 +583,35 @@ describe("StudioPaneToggles keyboard navigation", () => {
expect(tab(/^Editor/).getAttribute("aria-expanded")).toBe("true");
});
});
+
+test("an uninspected latest run never consumes its completion notice", () => {
+ const runId = "wr_uninspected";
+ const run = { workflow_run_id: runId, status: Status.Running };
+ runsQueryMock.mockReturnValue({ data: [run] });
+ runWithWorkflowMock.mockReturnValue({ data: run });
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <MemoryRouter>
+ <WorkflowPermanentIdContext.Provider value="wpid_abc">
+ {children}
+ </WorkflowPermanentIdContext.Provider>
+ </MemoryRouter>
+ );
+ const { result, rerender } = renderHook(useStudioRunSignals, { wrapper });
+ expect(result.current.runId).toBeUndefined();
+ expect(result.current.runStatus).toBeNull();
+ runWithWorkflowMock.mockReturnValue({
+ data: { ...run, status: Status.Completed },
+ });
+ rerender();
+ expect(result.current.runStatus).toBeNull();
+ expect(runWithWorkflowMock.mock.lastCall?.[0]).toEqual({
+ workflowRunId: undefined,
+ });
+ const displayed: string[] = [];
+ expect(
+ claimRunCompletionNotice(runId, () => {
+ displayed.push("shown on the run's page");
+ }),
+ ).toBe(true);
+ expect(displayed).toEqual(["shown on the run's page"]);
+});
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioShell.test.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioShell.test.tsx
index c97ad744c..44beee2d5 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioShell.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioShell.test.tsx
@@ -8,8 +8,26 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { type StudioPaneId } from "./panes";
import { paneAccessibleName } from "./paneMeta";
+import { paneExpansionKeyframes } from "./paneLayout";
import { StudioPane } from "./StudioShell";
+describe("paneExpansionKeyframes", () => {
+ test("grows from the pane's current bounds into its final bounds", () => {
+ expect(
+ paneExpansionKeyframes(
+ { left: 260, top: 100, width: 300, height: 500 },
+ { left: 20, top: 40, width: 1000, height: 600 },
+ ),
+ ).toEqual([
+ {
+ transform: "translate(240px, 60px) scale(0.3, 0.8333333333333334)",
+ transformOrigin: "top left",
+ },
+ { transform: "none", transformOrigin: "top left" },
+ ]);
+ });
+});
+
vi.mock("@/util/copyText", () => ({ copyText: vi.fn() }));
const mockedCopyText = vi.mocked(copyText);
@@ -25,10 +43,25 @@ describe("StudioPane header", () => {
id = "copilot",
runId,
headerActions,
+ expanded = false,
+ expansionTransitioning = false,
+ onToggleExpanded = vi.fn(),
+ transitionFromBounds,
+ onTransitionEnd,
}: {
id?: StudioPaneId;
runId?: string;
headerActions?: ReactNode;
+ expanded?: boolean;
+ expansionTransitioning?: boolean;
+ onToggleExpanded?: () => void;
+ transitionFromBounds?: {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ };
+ onTransitionEnd?: () => void;
} = {}) => {
const reorder = {
draggingId: null,
@@ -48,6 +81,11 @@ describe("StudioPane header", () => {
flex={undefined}
reorder={reorder}
onClose={vi.fn()}
+ expanded={expanded}
+ expansionTransitioning={expansionTransitioning}
+ onToggleExpanded={onToggleExpanded}
+ transitionFromBounds={transitionFromBounds}
+ onTransitionEnd={onTransitionEnd}
headerActions={headerActions}
>
<div>content</div>
@@ -70,6 +108,9 @@ describe("StudioPane header", () => {
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ Reflect.deleteProperty(HTMLElement.prototype, "animate");
});
test("gives each pane a clear two-pixel outline", () => {
@@ -79,6 +120,123 @@ describe("StudioPane header", () => {
expect(pane.className).toContain("border-border");
});
+ test("expands a pane to the full studio stage from its header", () => {
+ const onToggleExpanded = vi.fn();
+ const { pane } = renderPane({ onToggleExpanded });
+ const expand = screen.getByRole("button", {
+ name: "Expand Copilot pane",
+ });
+
+ expect(expand.getAttribute("aria-pressed")).toBe("false");
+ fireEvent.click(expand);
+
+ expect(onToggleExpanded).toHaveBeenCalledTimes(1);
+ expect(pane.className).not.toContain("absolute");
+ });
+
+ test("restores an expanded pane to the multi-pane layout", () => {
+ const onToggleExpanded = vi.fn();
+ const { pane } = renderPane({ expanded: true, onToggleExpanded });
+ const restore = screen.getByRole("button", {
+ name: "Restore Copilot pane",
+ });
+
+ expect(restore.getAttribute("aria-pressed")).toBe("true");
+ expect(pane.className).toContain("absolute");
+ expect(pane.className).toContain("inset-3");
+ fireEvent.click(restore);
+
+ expect(onToggleExpanded).toHaveBeenCalledTimes(1);
+ });
+
+ test("prevents another fullscreen toggle during the transition", () => {
+ const onToggleExpanded = vi.fn();
+ renderPane({ expansionTransitioning: true, onToggleExpanded });
+ const expand = screen.getByRole("button", {
+ name: "Expand Copilot pane",
+ });
+
+ expect(expand.getAttribute("aria-disabled")).toBe("true");
+ expect((expand as HTMLButtonElement).disabled).toBe(false);
+ fireEvent.click(expand);
+ expect(onToggleExpanded).not.toHaveBeenCalled();
+ });
+
+ test("animates from the measured pane bounds over 200ms", () => {
+ const animation = {
+ cancel: vi.fn(),
+ onfinish: null,
+ } as unknown as Animation;
+ const animate = vi.fn(() => animation);
+ Object.defineProperty(HTMLElement.prototype, "animate", {
+ configurable: true,
+ value: animate,
+ });
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({
+ left: 20,
+ top: 40,
+ width: 1000,
+ height: 600,
+ } as DOMRect);
+ const onTransitionEnd = vi.fn();
+
+ renderPane({
+ transitionFromBounds: {
+ left: 260,
+ top: 100,
+ width: 300,
+ height: 500,
+ },
+ onTransitionEnd,
+ });
+
+ expect(animate).toHaveBeenCalledWith(
+ paneExpansionKeyframes(
+ { left: 260, top: 100, width: 300, height: 500 },
+ { left: 20, top: 40, width: 1000, height: 600 },
+ ),
+ {
+ duration: 200,
+ easing: "cubic-bezier(0.22, 1, 0.36, 1)",
+ fill: "both",
+ },
+ );
+ animation.onfinish?.(new Event("finish") as AnimationPlaybackEvent);
+ expect(onTransitionEnd).toHaveBeenCalledTimes(1);
+ });
+
+ test("finishes immediately when reduced motion is preferred", () => {
+ const animate = vi.fn();
+ Object.defineProperty(HTMLElement.prototype, "animate", {
+ configurable: true,
+ value: animate,
+ });
+ vi.stubGlobal(
+ "matchMedia",
+ vi.fn(() => ({ matches: true })),
+ );
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({
+ left: 20,
+ top: 40,
+ width: 1000,
+ height: 600,
+ } as DOMRect);
+ const onTransitionEnd = vi.fn();
+
+ renderPane({
+ transitionFromBounds: {
+ left: 260,
+ top: 100,
+ width: 300,
+ height: 500,
+ },
+ onTransitionEnd,
+ });
+
+ expect(animate).not.toHaveBeenCalled();
+ expect(onTransitionEnd).toHaveBeenCalledTimes(1);
+ });
+
test("dragstart sets the drag payload synchronously but engages reorder on a later task", () => {
const { reorder, header } = renderPane();
const dt = dataTransfer();
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioShell.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioShell.tsx
index 1eddfdca7..546626eea 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioShell.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioShell.tsx
@@ -1,4 +1,5 @@
import {
+ useCallback,
useEffect,
useLayoutEffect,
useMemo,
@@ -8,7 +9,11 @@ import {
} from "react";
import { createPortal } from "react-dom";
import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";
-import { Cross2Icon } from "@radix-ui/react-icons";
+import {
+ Cross2Icon,
+ EnterFullScreenIcon,
+ ExitFullScreenIcon,
+} from "@radix-ui/react-icons";
import { CopyButton } from "@/components/CopyButton";
import {
@@ -48,8 +53,10 @@ import {
clampResizeDelta,
movePaneBy,
movePaneTo,
+ paneExpansionKeyframes,
paneFlex,
paneResizable,
+ type PaneBounds,
type PaneWidths,
} from "./paneLayout";
import { STUDIO_PANE_META, paneAccessibleName, paneLabel } from "./paneMeta";
@@ -141,6 +148,11 @@ export function StudioPane({
flex,
reorder,
onClose,
+ expanded,
+ expansionTransitioning = false,
+ onToggleExpanded,
+ transitionFromBounds = null,
+ onTransitionEnd,
headerExtras,
headerActions,
iconBadge,
@@ -154,6 +166,11 @@ export function StudioPane({
flex: string | undefined;
reorder: PaneReorder;
onClose: () => void;
+ expanded: boolean;
+ expansionTransitioning?: boolean;
+ onToggleExpanded: () => void;
+ transitionFromBounds?: PaneBounds | null;
+ onTransitionEnd?: () => void;
// Rendered after the pane label (badges, view pills).
headerExtras?: ReactNode;
// Rendered right-aligned, before the close button.
@@ -168,9 +185,46 @@ export function StudioPane({
// drag hint, and close control take the stable accessible name so a run
// switch never renames them for screen readers.
const accessibleLabel = paneAccessibleName(id);
+ const paneRef = useRef<HTMLElement>(null);
const headerRef = useRef<HTMLDivElement>(null);
+ const onTransitionEndRef = useRef(onTransitionEnd);
+ onTransitionEndRef.current = onTransitionEnd;
const hasChrome = headerExtras != null || headerActions != null;
const [compact, setCompact] = useState(false);
+ useLayoutEffect(() => {
+ const pane = paneRef.current;
+ if (!pane || transitionFromBounds === null) {
+ return;
+ }
+
+ const finalBounds = pane.getBoundingClientRect();
+ const reducedMotion =
+ typeof window.matchMedia === "function" &&
+ window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+ if (
+ reducedMotion ||
+ typeof pane.animate !== "function" ||
+ finalBounds.width === 0 ||
+ finalBounds.height === 0
+ ) {
+ onTransitionEndRef.current?.();
+ return;
+ }
+
+ const animation = pane.animate(
+ paneExpansionKeyframes(transitionFromBounds, finalBounds),
+ {
+ duration: 200,
+ easing: "cubic-bezier(0.22, 1, 0.36, 1)",
+ fill: "both",
+ },
+ );
+ animation.onfinish = () => onTransitionEndRef.current?.();
+ return () => {
+ animation.onfinish = null;
+ animation.cancel();
+ };
+ }, [transitionFromBounds]);
// Layout effect + an immediate measure so a narrow pane never paints one
// frame of full-width labels before the observer's first callback.
useLayoutEffect(() => {
@@ -220,12 +274,16 @@ export function StudioPane({
return (
<section
+ ref={paneRef}
id={studioPanelId(id)}
role="region"
aria-label={accessibleLabel}
style={{ order, minWidth: STUDIO_PANE_MIN_WIDTH[id], flex }}
className={cn(
"relative min-h-0 flex-col overflow-hidden rounded-lg border-2 border-border bg-slate-elevation1",
+ expanded && "absolute inset-3 z-30",
+ transitionFromBounds !== null &&
+ "pointer-events-none z-30 will-change-transform",
open
? "flex duration-200 motion-safe:animate-in motion-safe:fade-in"
: "hidden",
@@ -314,6 +372,31 @@ export function StudioPane({
</div>
) : null}
</StudioPaneCompactContext.Provider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={() => {
+ if (!expansionTransitioning) {
+ onToggleExpanded();
+ }
+ }}
+ aria-disabled={expansionTransitioning}
+ aria-label={`${expanded ? "Restore" : "Expand"} ${accessibleLabel} pane`}
+ aria-pressed={expanded}
+ className={PANE_HEADER_ICON_BUTTON_CLASS}
+ >
+ {expanded ? (
+ <ExitFullScreenIcon className="size-3.5" />
+ ) : (
+ <EnterFullScreenIcon className="size-3.5" />
+ )}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ {expanded ? "Restore pane" : "Expand to full screen"}
+ </TooltipContent>
+ </Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<button
@@ -639,6 +722,14 @@ function StudioStage(props: StudioWorkspaceProps) {
const [draggingPaneId, setDraggingPaneId] = useState<StudioPaneId | null>(
null,
);
+ const [expandedPaneId, setExpandedPaneId] = useState<StudioPaneId | null>(
+ null,
+ );
+ const [paneTransition, setPaneTransition] = useState<{
+ id: StudioPaneId;
+ fromBounds: PaneBounds;
+ } | null>(null);
+ const previousPanesRef = useRef(panes);
const [copilotPortalEl, setCopilotPortalEl] = useState<HTMLElement | null>(
null,
);
@@ -661,9 +752,47 @@ function StudioStage(props: StudioWorkspaceProps) {
null,
);
- const browserOpen = panes.includes("browser");
- const editorOpen = panes.includes("editor");
- const overviewOpen = panes.includes("overview");
+ const activeExpandedPaneId =
+ expandedPaneId !== null && panes.includes(expandedPaneId)
+ ? expandedPaneId
+ : null;
+ // Keep the surrounding layout mounted while the active pane grows over it.
+ // Once the pane covers the stage, hiding the panes underneath is invisible.
+ const visiblePanes =
+ activeExpandedPaneId && paneTransition === null
+ ? [activeExpandedPaneId]
+ : panes;
+ const browserOpen = visiblePanes.includes("browser");
+ const editorOpen = visiblePanes.includes("editor");
+ const overviewOpen = visiblePanes.includes("overview");
+
+ const toggleExpandedPane = (id: StudioPaneId) => {
+ const pane = document.getElementById(studioPanelId(id));
+ if (pane) {
+ const { left, top, width, height } = pane.getBoundingClientRect();
+ if (width > 0 && height > 0) {
+ setPaneTransition({
+ id,
+ fromBounds: { left, top, width, height },
+ });
+ }
+ }
+ setExpandedPaneId((current) => (current === id ? null : id));
+ };
+
+ const restoreExpandedPane = useCallback(() => {
+ setExpandedPaneId(null);
+ setPaneTransition(null);
+ }, []);
+
+ useEffect(() => {
+ const previousPanes = previousPanesRef.current;
+ previousPanesRef.current = panes;
+ if (expandedPaneId !== null && !panesListEqual(previousPanes, panes)) {
+ setExpandedPaneId(null);
+ setPaneTransition(null);
+ }
+ }, [expandedPaneId, panes]);
// Move the persistent stream node into the highest-priority open surface:
// Browser pane > Overview pane with a live block run (runStreamSlot registers
@@ -701,12 +830,15 @@ function StudioStage(props: StudioWorkspaceProps) {
setEditorStreamSlot,
setBrowserStreamSlot,
setRunStreamSlot,
+ restoreExpandedPane,
}),
- [copilotPortalEl, panelPortalEl],
+ [copilotPortalEl, panelPortalEl, restoreExpandedPane],
);
// The ✕ unmounts with its pane, so hand focus back to the pane's toggle.
const closeWithFocus = (id: StudioPaneId) => {
+ setExpandedPaneId((current) => (current === id ? null : current));
+ setPaneTransition((current) => (current?.id === id ? null : current));
closePane(id, { learn: true });
document.getElementById(studioTabId(id))?.focus();
};
@@ -742,29 +874,39 @@ function StudioStage(props: StudioWorkspaceProps) {
const wasRecording = prevIsRecordingRef.current;
const wasProcessing = prevProcessingRef.current;
if (processingRecording && !wasProcessing) {
+ restoreExpandedPane();
openPane("editor");
} else if (isRecording && !wasRecording) {
// Recording or finalizing → live browser + drafts.
+ restoreExpandedPane();
openPane("copilot");
openPane("browser");
} else if (!isRecording && wasRecording && !processingRecording) {
// Recording ended (commit or discard) → back to the canvas.
+ restoreExpandedPane();
openPane("editor");
}
prevIsRecordingRef.current = isRecording;
prevProcessingRef.current = processingRecording;
- }, [isRecording, processingRecording, openPane]);
+ }, [isRecording, processingRecording, openPane, restoreExpandedPane]);
const paneProps = (id: StudioPaneId) => {
const index = panes.indexOf(id);
return {
id,
runId,
- open: index >= 0,
+ open: index >= 0 && visiblePanes.includes(id),
// Panes take even slots and the dividers between them take odd slots.
order: index >= 0 ? index * 2 : undefined,
flex: index >= 0 ? paneFlex(id, panes, paneWidths) : undefined,
onClose: () => closeWithFocus(id),
+ expanded: activeExpandedPaneId === id,
+ expansionTransitioning: paneTransition !== null,
+ onToggleExpanded: () => toggleExpandedPane(id),
+ transitionFromBounds:
+ paneTransition?.id === id ? paneTransition.fromBounds : null,
+ onTransitionEnd: () =>
+ setPaneTransition((current) => (current?.id === id ? null : current)),
reorder: {
draggingId: draggingPaneId,
placement:
@@ -865,17 +1007,21 @@ function StudioStage(props: StudioWorkspaceProps) {
</StudioPane>
{/* Dividers are the inter-pane gaps; stateless, so unlike the panes
they can re-render freely as the open list changes. */}
- {panes.slice(1).map((rightId, index) => (
- <StudioPaneDivider
- key={`${panes[index]}:${rightId}`}
- leftId={panes[index]!}
- rightId={rightId}
- order={index * 2 + 1}
- panes={panes}
- onCommit={setPaneWidths}
- onReset={resetPaneWidths}
- />
- ))}
+ {activeExpandedPaneId === null || paneTransition !== null
+ ? panes
+ .slice(1)
+ .map((rightId, index) => (
+ <StudioPaneDivider
+ key={`${panes[index]}:${rightId}`}
+ leftId={panes[index]!}
+ rightId={rightId}
+ order={index * 2 + 1}
+ panes={panes}
+ onCommit={setPaneWidths}
+ onReset={resetPaneWidths}
+ />
+ ))
+ : null}
{panes.length === 0 ? <StudioStageLauncher /> : null}
<StudioCoachMark />
<StudioWorkflowPanels />
@@ -900,7 +1046,10 @@ function StudioStage(props: StudioWorkspaceProps) {
aria-hidden
className="h-0 w-0 overflow-hidden"
/>
- {createPortal(<StudioBrowserStream />, streamHostEl)}
+ {createPortal(
+ <StudioBrowserStream visiblePanes={visiblePanes} />,
+ streamHostEl,
+ )}
</div>
</TooltipProvider>
</StudioShellContext.Provider>
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioShellContext.ts b/skyvern-frontend/src/routes/workflows/studio/StudioShellContext.ts
index 0f2b0ada2..454a66d8f 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioShellContext.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioShellContext.ts
@@ -14,6 +14,9 @@ type StudioShellContextValue = {
// The Overview pane registers this for a block run, so the debug-session stream shows
// there too (same node, view-only); null for a full run keeps it parked.
setRunStreamSlot: (el: HTMLElement | null) => void;
+ // Pane actions from nested controls leave fullscreen before applying their
+ // own layout change, including when the requested pane is already open.
+ restoreExpandedPane?: () => void;
};
export const StudioShellContext = createContext<StudioShellContextValue>({
@@ -22,6 +25,7 @@ export const StudioShellContext = createContext<StudioShellContextValue>({
setEditorStreamSlot: () => {},
setBrowserStreamSlot: () => {},
setRunStreamSlot: () => {},
+ restoreExpandedPane: () => {},
});
export function useStudioShellContext(): StudioShellContextValue {
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx
index 6ff30c8fa..70fd493e3 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx
@@ -1,3 +1,8 @@
+import { claimRunCompletionNotice } from "@/routes/workflows/workflowRun/runCompletionNotices";
+import {
+ runIsCancellable,
+ runIsLogicallyFinal,
+} from "@/routes/workflows/workflowRun/runRetryState";
import { type ReactNode, useMemo, useState } from "react";
import { AxiosError } from "axios";
import {
@@ -33,7 +38,7 @@ import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";
import { useWorkflowParametersStore } from "@/store/WorkflowParametersStore";
import { useWorkflowSnapshotStore } from "@/store/WorkflowSnapshotStore";
import { useWorkflowTitleStore } from "@/store/WorkflowTitleStore";
-import { statusIsFinalized } from "@/routes/tasks/types";
+
import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";
import { cn } from "@/util/utils";
@@ -51,7 +56,6 @@ 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";
import { StudioPaneToggles } from "./StudioPaneToggles";
@@ -316,14 +320,13 @@ export function RunStopButton({ stopOnly = false }: { stopOnly?: boolean }) {
const workflowRun = isPlaceholderData ? undefined : retainedRun;
const activeRunId = workflowRun?.workflow_run_id;
const running =
- !statusUnavailable &&
- runOutcomeFromStatus(workflowRun?.status) === "running";
+ !statusUnavailable && Boolean(workflowRun && runIsCancellable(workflowRun));
// ?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 &&
- statusIsFinalized(workflowRun) &&
+ runIsLogicallyFinal(workflowRun) &&
workflowRun.task_v2 === null &&
!isBlockRun &&
!workflowRun.workflow?.deleted_at,
@@ -342,11 +345,15 @@ export function RunStopButton({ stopOnly = false }: { stopOnly?: boolean }) {
queryKey: ["workflowRun", workflowPermanentId, activeRunId],
});
queryClient.invalidateQueries({ queryKey: ["workflowRuns"] });
- toast({
- variant: "success",
- title: "Run canceled",
- description: "The agent run has been canceled.",
- });
+ if (activeRunId) {
+ claimRunCompletionNotice(activeRunId, () => {
+ toast({
+ variant: "success",
+ title: "Run canceled",
+ description: "The agent run has been canceled.",
+ });
+ });
+ }
},
onError: (error: AxiosError) => {
toast({
diff --git a/skyvern-frontend/src/routes/workflows/studio/paneLayout.ts b/skyvern-frontend/src/routes/workflows/studio/paneLayout.ts
index 0b0a93881..902f06e9b 100644
--- a/skyvern-frontend/src/routes/workflows/studio/paneLayout.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/paneLayout.ts
@@ -16,6 +16,21 @@ export const STUDIO_PANE_DEFAULT_WIDTH = 300;
// factory defaults (editor+browser, browser+overview).
export const STUDIO_TWO_PANE_SIDE_BASIS = "35%";
+export type PaneBounds = Pick<DOMRect, "left" | "top" | "width" | "height">;
+
+export function paneExpansionKeyframes(
+ from: PaneBounds,
+ to: PaneBounds,
+): Keyframe[] {
+ return [
+ {
+ transform: `translate(${from.left - to.left}px, ${from.top - to.top}px) scale(${from.width / to.width}, ${from.height / to.height})`,
+ transformOrigin: "top left",
+ },
+ { transform: "none", transformOrigin: "top left" },
+ ];
+}
+
// The browser is the best consumer of free space; the canvas takes over when
// the browser is closed. With neither open, every open pane flexes equally.
export function greedyPaneOf(
diff --git a/skyvern-frontend/src/routes/workflows/studio/runProjections.test.ts b/skyvern-frontend/src/routes/workflows/studio/runProjections.test.ts
index 003b27036..1c510cf73 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runProjections.test.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/runProjections.test.ts
@@ -1,3 +1,8 @@
+import {
+ runIsCancellable,
+ runIsExecuting,
+ runIsLogicallyActive,
+} from "../workflowRun/runRetryState";
import { describe, expect, test } from "vitest";
import {
@@ -101,21 +106,21 @@ describe("runOutcomeFromStatus", () => {
});
test("running for in-flight statuses", () => {
- expect(runOutcomeFromStatus(Status.Created)).toBe("running");
- expect(runOutcomeFromStatus(Status.Queued)).toBe("running");
- expect(runOutcomeFromStatus(Status.Running)).toBe("running");
- expect(runOutcomeFromStatus(Status.Paused)).toBe("running");
+ expect(runOutcomeFromStatus({ status: Status.Created })).toBe("running");
+ expect(runOutcomeFromStatus({ status: Status.Queued })).toBe("running");
+ expect(runOutcomeFromStatus({ status: Status.Running })).toBe("running");
+ expect(runOutcomeFromStatus({ status: Status.Paused })).toBe("running");
});
test("success only for completed", () => {
- expect(runOutcomeFromStatus(Status.Completed)).toBe("success");
+ expect(runOutcomeFromStatus({ status: Status.Completed })).toBe("success");
});
test("failed for failure types and canceled", () => {
- expect(runOutcomeFromStatus(Status.Failed)).toBe("failed");
- expect(runOutcomeFromStatus(Status.Terminated)).toBe("failed");
- expect(runOutcomeFromStatus(Status.TimedOut)).toBe("failed");
- expect(runOutcomeFromStatus(Status.Canceled)).toBe("failed");
+ expect(runOutcomeFromStatus({ status: Status.Failed })).toBe("failed");
+ expect(runOutcomeFromStatus({ status: Status.Terminated })).toBe("failed");
+ expect(runOutcomeFromStatus({ status: Status.TimedOut })).toBe("failed");
+ expect(runOutcomeFromStatus({ status: Status.Canceled })).toBe("failed");
});
});
@@ -123,18 +128,26 @@ describe("finalizedRunStatus", () => {
test("null while there is no status or the run is in-flight", () => {
expect(finalizedRunStatus(null)).toBeNull();
expect(finalizedRunStatus(undefined)).toBeNull();
- expect(finalizedRunStatus(Status.Created)).toBeNull();
- expect(finalizedRunStatus(Status.Queued)).toBeNull();
- expect(finalizedRunStatus(Status.Running)).toBeNull();
- expect(finalizedRunStatus(Status.Paused)).toBeNull();
+ expect(finalizedRunStatus({ status: Status.Created })).toBeNull();
+ expect(finalizedRunStatus({ status: Status.Queued })).toBeNull();
+ expect(finalizedRunStatus({ status: Status.Running })).toBeNull();
+ expect(finalizedRunStatus({ status: Status.Paused })).toBeNull();
});
test("preserves the real terminal status instead of collapsing it", () => {
- expect(finalizedRunStatus(Status.Completed)).toBe(Status.Completed);
- expect(finalizedRunStatus(Status.Failed)).toBe(Status.Failed);
- expect(finalizedRunStatus(Status.Terminated)).toBe(Status.Terminated);
- expect(finalizedRunStatus(Status.TimedOut)).toBe(Status.TimedOut);
- expect(finalizedRunStatus(Status.Canceled)).toBe(Status.Canceled);
+ expect(finalizedRunStatus({ status: Status.Completed })).toBe(
+ Status.Completed,
+ );
+ expect(finalizedRunStatus({ status: Status.Failed })).toBe(Status.Failed);
+ expect(finalizedRunStatus({ status: Status.Terminated })).toBe(
+ Status.Terminated,
+ );
+ expect(finalizedRunStatus({ status: Status.TimedOut })).toBe(
+ Status.TimedOut,
+ );
+ expect(finalizedRunStatus({ status: Status.Canceled })).toBe(
+ Status.Canceled,
+ );
});
});
@@ -689,6 +702,16 @@ describe("formatRunTimesTooltip", () => {
});
});
+test("created and paused runs remain active and cancellable", () => {
+ for (const status of [Status.Created, Status.Paused]) {
+ const run = { status };
+ expect(runIsLogicallyActive(run)).toBe(true);
+ expect(runIsCancellable(run)).toBe(true);
+ expect(runOutcomeFromStatus(run)).toBe("running");
+ expect(finalizedRunStatus(run)).toBeNull();
+ }
+});
+
describe("actionLabel", () => {
// Task V3 stamps every action's description with its tool call, so a description-first fallback
// labelled every v3 frame with machine syntax instead of what the agent said it was doing.
@@ -724,3 +747,9 @@ describe("actionLabel", () => {
).toBe("Open the billing page");
});
});
+
+test.each(Object.values(Status))("execution semantics for %s", (status) => {
+ const executing = status === Status.Running || status === Status.Queued;
+ expect(runIsExecuting({ status })).toBe(executing);
+ expect(runIsExecuting({ status, retry_pending: true })).toBe(executing);
+});
diff --git a/skyvern-frontend/src/routes/workflows/studio/runProjections.ts b/skyvern-frontend/src/routes/workflows/studio/runProjections.ts
index 5cec2f19c..e339cd6bb 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runProjections.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/runProjections.ts
@@ -4,8 +4,9 @@ import {
ReadableActionTypes,
Status,
WorkflowRunStatusApiResponseWithWorkflow,
+ WorkflowRunRetryFields,
} from "@/api/types";
-import { statusIsAFailureType, statusIsFinalized } from "@/routes/tasks/types";
+import { statusIsAFailureType } from "@/routes/tasks/types";
import {
isBlockItem,
WorkflowRunBlock,
@@ -13,6 +14,10 @@ import {
} from "@/routes/workflows/types/workflowRunTypes";
import { taskV3CallText } from "@/routes/workflows/workflowBlockUtils";
import { flattenTimelineChronologically } from "@/routes/workflows/workflowRun/workflowTimelineUtils";
+import {
+ runIsLogicallyFinal,
+ runIsLogicallyActive,
+} from "../workflowRun/runRetryState";
import { isRecord } from "@/util/utils";
import { basicLocalTimeFormat, normalizeUtcTimestamp } from "@/util/timeFormat";
@@ -59,7 +64,7 @@ export function formatElapsed(
export function formatRunTimesTooltip(
workflowRun: WorkflowRunStatusApiResponseWithWorkflow,
): string {
- const finalized = statusIsFinalized(workflowRun);
+ const finalized = runIsLogicallyFinal(workflowRun);
return [
workflowRun.created_at
? `Created ${basicLocalTimeFormat(workflowRun.created_at)}`
@@ -79,15 +84,16 @@ export function formatRunTimesTooltip(
}
export function runOutcomeFromStatus(
- status: Status | null | undefined,
+ run: ({ status: Status } & WorkflowRunRetryFields) | null | undefined,
): RunOutcome {
- if (!status) {
+ if (!run) {
return "idle";
}
- if (status === Status.Completed) {
+ if (runIsLogicallyActive(run)) return "running";
+ if (run.status === Status.Completed) {
return "success";
}
- if (statusIsAFailureType({ status }) || status === Status.Canceled) {
+ if (statusIsAFailureType(run) || run.status === Status.Canceled) {
return "failed";
}
return "running";
@@ -95,12 +101,12 @@ export function runOutcomeFromStatus(
// Null while the run is in-flight; the tab shows only the terminal status.
export function finalizedRunStatus(
- status: Status | null | undefined,
+ run: ({ status: Status } & WorkflowRunRetryFields) | null | undefined,
): Status | null {
- if (status == null) {
+ if (run == null) {
return null;
}
- return statusIsFinalized({ status }) ? status : null;
+ return runIsLogicallyFinal(run) ? run.status : null;
}
type RunOutputSignals = Pick<
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunFailurePresentation.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunFailurePresentation.tsx
index 430b0f7ee..3a798eeda 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunFailurePresentation.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunFailurePresentation.tsx
@@ -5,6 +5,8 @@ import {
ReloadIcon,
} from "@radix-ui/react-icons";
+import { type WorkflowRunStatusApiResponseWithWorkflow } from "@/api/types";
+import { runIsRetryWaiting } from "@/routes/workflows/workflowRun/runRetryState";
import { Button } from "@/components/ui/button";
// Fix leads when it is offered; Retry is the primary only when it stands alone.
export function FailureRecoveryActions({
@@ -57,6 +59,7 @@ export function FailureTips({ tips }: { tips: Array<string> }) {
// The strip's second line. The block name is the jump; the full
// reason rides the headline's title so nothing else is said at run level.
export function RunFailureLine({
+ workflowRun,
blockLabel,
headline,
detail,
@@ -64,6 +67,7 @@ export function RunFailureLine({
tips,
children,
}: {
+ workflowRun?: WorkflowRunStatusApiResponseWithWorkflow;
blockLabel: string | null;
headline: string;
detail: string | null;
@@ -71,6 +75,13 @@ export function RunFailureLine({
tips: Array<string>;
children: ReactNode;
}) {
+ if (workflowRun && runIsRetryWaiting(workflowRun)) {
+ return (
+ <div className="shrink-0 text-xs text-muted-foreground">
+ Retry pending. Skyvern will run this workflow again.
+ </div>
+ );
+ }
return (
<div
data-testid="run-failure-line"
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunLiveStream.test.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunLiveStream.test.tsx
index b8f838f96..d6262be45 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunLiveStream.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunLiveStream.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { cleanup, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, test, vi } from "vitest";
let transport: string | undefined = "cdp";
@@ -10,7 +10,9 @@ vi.mock("@/hooks/useRuntimeConfig", () => ({
}));
vi.mock("@/components/BrowserStream", () => ({
- BrowserStream: () => <div data-testid="vnc-stream" />,
+ BrowserStream: ({ onClose }: { onClose: () => void }) => (
+ <button data-testid="vnc-stream" onClick={onClose} />
+ ),
}));
vi.mock("@/routes/browserSessions/BrowserSessionStream", () => ({
@@ -63,3 +65,55 @@ describe("RunLiveStream", () => {
expect(screen.queryByTestId("run-stream")).not.toBeNull();
});
});
+
+test("remounts the whole transport chooser when an attempt changes without a wait frame", () => {
+ transport = "vnc";
+ const run = {
+ workflow_run_id: "wr_attempt",
+ status: "running" as const,
+ attempt: 1,
+ };
+ const { rerender } = render(
+ <RunLiveStream
+ workflowRunId={run.workflow_run_id}
+ run={run}
+ browserSessionId="pbs_same"
+ interactive={false}
+ />,
+ );
+ fireEvent.click(screen.getByTestId("vnc-stream"));
+ expect(screen.queryByTestId("session-stream")).not.toBeNull();
+ rerender(
+ <RunLiveStream
+ workflowRunId={run.workflow_run_id}
+ run={{ ...run, attempt: 2 }}
+ browserSessionId="pbs_same"
+ interactive={false}
+ />,
+ );
+ expect(screen.queryByTestId("vnc-stream")).not.toBeNull();
+ expect(screen.queryByTestId("session-stream")).toBeNull();
+});
+
+test("shows retry waits through the theme-aware status panel", () => {
+ render(
+ <RunLiveStream
+ workflowRunId="wr_wait"
+ run={{
+ workflow_run_id: "wr_wait",
+ status: "failed",
+ retry_pending: true,
+ }}
+ browserSessionId={null}
+ interactive={false}
+ />,
+ );
+ const panel = screen.getByRole("status");
+ expect(panel.textContent).toContain("Retry pending");
+ expect(panel.textContent).toContain(
+ "The browser reconnects when the next attempt starts.",
+ );
+ expect(panel.className).toContain("bg-white");
+ expect(panel.className).toContain("text-neutral-600");
+ expect(screen.queryByTestId("run-stream")).toBeNull();
+});
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunLiveStream.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunLiveStream.tsx
index e5da6c301..7c0ddb49a 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunLiveStream.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunLiveStream.tsx
@@ -1,3 +1,9 @@
+import { StreamStatusPanel } from "@/routes/streaming/StreamDiagnostics";
+import type { Status, WorkflowRunRetryFields } from "@/api/types";
+import {
+ getRunAttemptKey,
+ runIsRetryWaiting,
+} from "../../workflowRun/runRetryState";
import { useEffect, useState } from "react";
import { BrowserStream } from "@/components/BrowserStream";
@@ -8,6 +14,7 @@ import { WorkflowRunStream } from "../../workflowRun/WorkflowRunStream";
type RunLiveStreamProps = {
workflowRunId: string;
+ run?: { workflow_run_id: string; status: Status } & WorkflowRunRetryFields;
browserSessionId: string | null;
interactive: boolean;
// Live page URL from the CDP frames; the VNC path doesn't surface one yet.
@@ -18,7 +25,27 @@ type RunLiveStreamProps = {
* Live browser for a workflow run, mirroring WorkflowRunOverview: VNC keyed by the
* browser session, with the session's CDP screencast when VNC is wrong or closes early.
*/
-export function RunLiveStream({
+export function RunLiveStream(props: RunLiveStreamProps) {
+ if (props.run && runIsRetryWaiting(props.run)) {
+ return (
+ <StreamStatusPanel
+ diagnostic={{
+ title: "Retry pending",
+ detail: "The browser reconnects when the next attempt starts.",
+ pending: true,
+ }}
+ />
+ );
+ }
+ return (
+ <RunLiveStreamTransport
+ key={props.run ? getRunAttemptKey(props.run) : props.workflowRunId}
+ {...props}
+ />
+ );
+}
+
+function RunLiveStreamTransport({
workflowRunId,
browserSessionId,
interactive,
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunPaneHeader.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunPaneHeader.tsx
index 611a0cc04..de82e842e 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunPaneHeader.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunPaneHeader.tsx
@@ -1,3 +1,8 @@
+import {
+ runIsRetryWaiting,
+ runIsExecuting,
+ runIsLogicallyFinal,
+} from "@/routes/workflows/workflowRun/runRetryState";
import { useCallback, useState } from "react";
import {
ActivityLogIcon,
@@ -25,7 +30,7 @@ import {
} from "@/components/ui/tooltip";
import { useApiCredential } from "@/hooks/useApiCredential";
import { Status } from "@/api/types";
-import { statusIsFinalized } from "@/routes/tasks/types";
+
import { useRunViewStore } from "@/store/RunViewStore";
import { useRunPaneViewStore } from "@/store/useRunPaneViewStore";
import { useStudioBrowserStore } from "@/store/useStudioBrowserStore";
@@ -36,7 +41,6 @@ import { cn } from "@/util/utils";
import { useIsGeneratingCode } from "../../editor/hooks/useIsGeneratingCode";
import { constructCacheKeyValue } from "../../editor/utils";
import { useWorkflowRunWithWorkflowQuery } from "../../hooks/useWorkflowRunWithWorkflowQuery";
-import { runOutcomeFromStatus } from "../runProjections";
import { studioPanelId } from "../constants";
import { useStudioPaneCompact } from "../StudioShellContext";
import { useStudioInspectedRun } from "../useStudioInspectedRun";
@@ -98,11 +102,11 @@ export function RunPaneViewToggles() {
if (!workflowRun) {
return null;
}
- const outcome = runOutcomeFromStatus(workflowRun.status);
const provisioning =
workflowRun.status === Status.Created ||
workflowRun.status === Status.Queued;
- const showLive = !statusUnavailable && outcome === "running" && !provisioning;
+ const showLive =
+ !statusUnavailable && runIsExecuting(workflowRun) && !provisioning;
return (
<>
@@ -230,7 +234,7 @@ export function RunPaneActions() {
if (workflowRun.workflow?.deleted_at) {
return null;
}
- const finalized = statusIsFinalized(workflowRun);
+ const finalized = runIsLogicallyFinal(workflowRun);
return (
<>
<ApiWebhookActionsMenu
@@ -273,6 +277,11 @@ export function RunPaneActions() {
headers,
} satisfies ApiCommandOptions;
}}
+ disabledReason={
+ workflowRun && runIsRetryWaiting(workflowRun)
+ ? "Unavailable while a retry is pending"
+ : undefined
+ }
webhookDisabled={!finalized}
onTestWebhook={() => setReplayOpen(true)}
/>
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunSummaryStrip.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunSummaryStrip.tsx
index 7bed6ff8b..9191640f7 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunSummaryStrip.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunSummaryStrip.tsx
@@ -8,7 +8,8 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
-import { statusIsFinalized } from "@/routes/tasks/types";
+import { runIsLogicallyFinal } from "@/routes/workflows/workflowRun/runRetryState";
+import { WorkflowRunAttemptChip } from "@/components/WorkflowRunAttemptChip";
import { type WorkflowRunTimelineItem } from "@/routes/workflows/types/workflowRunTypes";
import { TimelineRunCounts } from "@/routes/workflows/workflowRun/WorkflowRunTimeline";
import { compactLocalDateTime } from "@/util/timeFormat";
@@ -39,7 +40,7 @@ export function RunSummaryStrip({
statusUnavailable = false,
trailing,
}: RunSummaryStripProps) {
- const finalized = statusIsFinalized(workflowRun);
+ const finalized = runIsLogicallyFinal(workflowRun);
const ranFor =
finalized && workflowRun.started_at && workflowRun.finished_at
? formatElapsed(workflowRun.started_at, workflowRun.finished_at)
@@ -62,6 +63,13 @@ export function RunSummaryStrip({
{!statusUnavailable ? (
<StatusBadge status={workflowRun.status} collapsible />
) : null}
+ {!statusUnavailable ? (
+ <WorkflowRunAttemptChip
+ attempt={workflowRun.attempt}
+ retryPending={workflowRun.retry_pending}
+ nextAttemptAt={workflowRun.next_attempt_at}
+ />
+ ) : null}
{!statusUnavailable && workflowRun.failure_category?.length ? (
<FailureCategoryBadge
failureCategory={workflowRun.failure_category}
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
index f37bac72a..eedd2adc4 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
@@ -408,6 +408,26 @@ beforeEach(() => {
});
describe("RunView view toggles", () => {
+ test("mounts the completion milestone only after a pending retry is final", () => {
+ seedCompletedRun({ retry_pending: true });
+ const MilestoneCard = vi.fn(() => <div data-testid="milestone-card" />);
+ const overview = renderRunView({}, "/?panes=overview", false, undefined, {
+ workflowRunMilestoneCard: MilestoneCard,
+ });
+
+ expect(MilestoneCard).not.toHaveBeenCalled();
+ expect(overview.queryByTestId("milestone-card")).toBeNull();
+ expect(
+ overview.queryByRole("button", {
+ name: "Watch live in the Browser pane",
+ }),
+ ).toBeNull();
+
+ seedCompletedRun({ retry_pending: false });
+ overview.rerenderRunView();
+ expect(overview.queryByTestId("milestone-card")).not.toBeNull();
+ });
+
test("mounts the milestone slot throughout Overview but not the editor", () => {
seedCompletedRun();
const MilestoneCard = vi.fn(() => <div data-testid="milestone-card" />);
@@ -1703,6 +1723,47 @@ describe("RunView timeline → editor jump", () => {
useWorkflowBlockSearchStore.getState().registerHandle(null);
});
+ test("clicking a historical block keeps its ID when the canvas mirrors its label", () => {
+ const label = "jump-target-block";
+ seedRunWithBlock(label);
+ mocks.workflowRun = { ...(mocks.workflowRun as object), attempt: 2 };
+ mocks.timeline = [
+ {
+ ...buildBlockItem(
+ buildBlock({ workflow_run_block_id: "wrb_historical", label }),
+ ),
+ attempt: 1,
+ },
+ {
+ ...buildBlockItem(
+ buildBlock({ workflow_run_block_id: "wrb_current", label }),
+ ),
+ attempt: 2,
+ },
+ ];
+ registerHandle();
+ const { container, getByRole } = renderRunView(
+ {},
+ "/?wr=wr_1&panes=editor,overview&active=wrb_current",
+ false,
+ <SelectBlockOnCanvas label={label} />,
+ );
+ fireEvent.click(getByRole("button", { name: "Search blocks" }));
+ expect(
+ screen.getAllByRole("option").map((option) => option.textContent),
+ ).toEqual(["#1jump-target-block"]);
+ fireEvent.keyDown(screen.getByPlaceholderText("Search blocks…"), {
+ key: "Escape",
+ });
+ const historicalGroup = getByRole("button", { name: /Attempt 1/ });
+ expect(historicalGroup.getAttribute("aria-expanded")).toBe("false");
+ fireEvent.click(historicalGroup);
+ clickBlock(container);
+ expect(useRunViewStore.getState().pinnedFrameId).toBe("wrb_historical");
+ fireEvent.click(getByRole("button", { name: `canvas: select ${label}` }));
+ expect(useRunViewStore.getState().pinnedFrameId).toBe("wrb_historical");
+ });
+
test("clicking a timeline block jumps the editor when the editor pane is open", () => {
seedRunWithBlock("jump-target-block");
const focusBlock = registerHandle();
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
index f78584fd8..7b4c5f4e0 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
@@ -1,3 +1,8 @@
+import {
+ getRunAttempt,
+ runIsLogicallyFinal,
+ runIsRetryWaiting,
+} from "@/routes/workflows/workflowRun/runRetryState";
import { useEffect, useMemo, useRef, useState } from "react";
import { MagnifyingGlassIcon } from "@radix-ui/react-icons";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
@@ -16,7 +21,7 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
-import { statusIsFinalized } from "@/routes/tasks/types";
+
import {
SELECTED_BLOCK_SEARCH_PARAM,
SYSTEM_BLOCK_FOCUS_PARAM,
@@ -43,6 +48,7 @@ import { pickDownloadedFileFilename } from "../../workflowRun/blockDownloadedFil
import {
buildBlockOrderIndex,
collectTimelineSearchTargets,
+ filterTimelineToAttempt,
findActiveItem,
flattenTimelineChronologically,
type TimelineSearchTarget,
@@ -178,7 +184,8 @@ function TimelineBlockSearch({
{targets.map((target) => (
<CommandItem
key={target.block.workflow_run_block_id}
- value={target.label}
+ value={target.block.workflow_run_block_id}
+ keywords={[target.label]}
onSelect={() => {
onJump(target);
closeAndReset();
@@ -231,6 +238,17 @@ export function RunView({
// the previous run's timeline on both a switch and a clear.
const timeline =
!workflowRunId || timelineIsPlaceholder ? undefined : retainedTimeline;
+ const currentTimeline = useMemo(
+ () =>
+ timeline
+ ? filterTimelineToAttempt(
+ timeline,
+ workflowRun?.attempts ?? [],
+ getRunAttempt(workflowRun ?? {}),
+ )
+ : undefined,
+ [timeline, workflowRun],
+ );
const pinnedFrameId = useRunViewStore((s) => s.pinnedFrameId);
const activeIteration = useRunViewStore((s) => s.activeIteration);
const pinFrame = useRunViewStore((s) => s.pinFrame);
@@ -327,19 +345,22 @@ export function RunView({
);
}, [runPaneOpen, workflowRunId, pathRunId, navigate]);
- const frames = useMemo(() => buildFilmstrip(timeline), [timeline]);
+ const frames = useMemo(
+ () => buildFilmstrip(currentTimeline),
+ [currentTimeline],
+ );
const searchTargets = useMemo(
() =>
- timeline
+ currentTimeline
? collectTimelineSearchTargets(
- flattenTimelineChronologically(timeline),
- buildBlockOrderIndex(timeline),
+ flattenTimelineChronologically(currentTimeline),
+ buildBlockOrderIndex(currentTimeline),
)
: [],
- [timeline],
+ [currentTimeline],
);
- const outcome = runOutcomeFromStatus(workflowRun?.status);
+ const outcome = runOutcomeFromStatus(workflowRun);
// A user-canceled run isn't a failure — don't show the "run failed" CTA.
const canceled = workflowRun?.status === Status.Canceled;
// While a run switch is still serving the previous payload, this status belongs to the old run
@@ -350,26 +371,28 @@ export function RunView({
outcome === "failed" &&
!canceled;
const finalized =
- !statusUnavailable && workflowRun ? statusIsFinalized(workflowRun) : false;
+ !statusUnavailable && workflowRun
+ ? runIsLogicallyFinal(workflowRun)
+ : false;
useLiveClock(Boolean(workflowRun) && !finalized && !statusUnavailable);
const finallyBlockLabel =
workflowRun?.workflow?.workflow_definition?.finally_block_label ?? null;
const landingSelectionId = useMemo(
- () => resolveLandingSelectionId(frames, timeline, finalized),
- [frames, timeline, finalized],
+ () => resolveLandingSelectionId(frames, currentTimeline, finalized),
+ [frames, currentTimeline, finalized],
);
const codeFailure = useMemo(
() =>
findRunCodeBlockFailure(
workflowRun?.failure_reason,
- timeline,
+ currentTimeline,
finallyBlockLabel,
),
- [workflowRun?.failure_reason, timeline, finallyBlockLabel],
+ [workflowRun?.failure_reason, currentTimeline, finallyBlockLabel],
);
const failedBlock = useMemo(
- () => failingBlock(timeline, finallyBlockLabel),
- [timeline, finallyBlockLabel],
+ () => failingBlock(currentTimeline, finallyBlockLabel),
+ [currentTimeline, finallyBlockLabel],
);
const failureBlockId =
codeFailure?.workflowRunBlockId ??
@@ -399,7 +422,7 @@ export function RunView({
if (runIsPlaceholder || timelineIsPlaceholder) {
return;
}
- if (!statusIsFinalized(workflowRun)) {
+ if (!runIsLogicallyFinal(workflowRun)) {
// Still running: leave the one-shot open so the terminal transition of
// a watched run lands the same last-item pin as a cold open.
watchedLiveRunRef.current = workflowRunId;
@@ -506,8 +529,13 @@ export function RunView({
: landingSelectionId;
const activeItem = useMemo(
() =>
- findActiveItem(timeline ?? [], selectedId, finalized, finallyBlockLabel),
- [timeline, selectedId, finalized, finallyBlockLabel],
+ findActiveItem(
+ (selectedId ? timeline : currentTimeline) ?? [],
+ selectedId,
+ finalized,
+ finallyBlockLabel,
+ ),
+ [timeline, currentTimeline, selectedId, finalized, finallyBlockLabel],
);
// Selecting a block on the editor canvas moves the run selection onto it, so
@@ -527,7 +555,7 @@ export function RunView({
return;
}
syncedBlockLabelRef.current = selectedBlockLabel;
- const blockId = resolveEditorSelectionPin({
+ const selection = {
editorOpen: studioPanes.includes("editor"),
runPaneOpen,
finalized,
@@ -536,6 +564,12 @@ export function RunView({
selectedBlockLabel,
systemFocusLabel: searchParamsRef.current.get(SYSTEM_BLOCK_FOCUS_PARAM),
pinnedFrameId: useRunViewStore.getState().pinnedFrameId,
+ };
+ // An explicit historical ID wins over the current attempt's same-label block.
+ if (resolveEditorSelectionPin(selection) === null) return;
+ const blockId = resolveEditorSelectionPin({
+ ...selection,
+ timeline: currentTimeline,
});
if (blockId) {
pinFrame(blockId);
@@ -543,6 +577,7 @@ export function RunView({
}, [
selectedBlockLabel,
timeline,
+ currentTimeline,
studioPanes,
runPaneOpen,
finalized,
@@ -733,6 +768,7 @@ export function RunView({
{WorkflowRunMilestoneCard &&
runPaneOpen &&
!runIsPlaceholder &&
+ runIsLogicallyFinal(workflowRun) &&
workflowRun.status === Status.Completed ? (
<WorkflowRunMilestoneCard
workflowRunId={workflowRun.workflow_run_id}
@@ -744,7 +780,7 @@ export function RunView({
<div className="flex min-h-0 flex-1 flex-col gap-2">
<RunSummaryStrip
workflowRun={workflowRun}
- timeline={timeline}
+ timeline={currentTimeline}
liveElapsed={statusUnavailable ? null : liveElapsed}
statusUnavailable={statusUnavailable}
trailing={
@@ -754,8 +790,9 @@ export function RunView({
/>
}
/>
- {failed ? (
+ {failed || runIsRetryWaiting(workflowRun) ? (
<RunFailureLine
+ workflowRun={workflowRun}
blockLabel={failedBlock?.label ?? null}
headline={failureHeadline}
detail={failureDetail}
@@ -800,7 +837,11 @@ export function RunView({
<WorkflowRunBlockDetail
activeItem={activeItem}
activeIteration={activeIteration}
- timeline={timeline ?? []}
+ timeline={
+ (pinnedFrameId && pinnedFrameId !== "stream"
+ ? timeline
+ : currentTimeline) ?? []
+ }
timelineReady={Boolean(timeline)}
showDownloadedFiles
workflowRunId={workflowRunId}
diff --git a/skyvern-frontend/src/routes/workflows/studio/useRunVisuals.test.tsx b/skyvern-frontend/src/routes/workflows/studio/useRunVisuals.test.tsx
index fc113d8bf..017455752 100644
--- a/skyvern-frontend/src/routes/workflows/studio/useRunVisuals.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/useRunVisuals.test.tsx
@@ -13,6 +13,7 @@ import type {
WorkflowRunTimelineItem,
} from "../types/workflowRunTypes";
import { useRunVisuals } from "./useRunVisuals";
+import { resolveBrowserPaneView } from "./browserPaneView";
const { mocks, getClientMock } = vi.hoisted(() => ({
mocks: {
@@ -161,6 +162,50 @@ afterEach(() => {
beforeEach(() => useRunViewStore.getState().reset());
describe("useRunVisuals loop-iteration threading", () => {
+ test("keeps the auto browser pane live across a retry delay until the run is final", () => {
+ seedLoopRun();
+ mocks.workflowRun = { status: Status.Running };
+ const { result, rerender } = renderHook(
+ () => {
+ const visuals = useRunVisuals("wr_1");
+ return {
+ ...visuals,
+ view: resolveBrowserPaneView({
+ intent: "auto",
+ recording: false,
+ scrubbing: visuals.scrubbing,
+ inspectingRun: true,
+ blockRunInDebugSession: false,
+ systemFocused: false,
+ running: visuals.running,
+ hasRecording: visuals.recordingUrls.length > 0,
+ failed: visuals.failed,
+ }),
+ };
+ },
+ { wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
+ );
+
+ expect(result.current.view).toBe("live");
+
+ mocks.workflowRun = { status: Status.Failed, retry_pending: true };
+ rerender();
+ expect(result.current.view).toBe("live");
+ expect(result.current.running).toBe(true);
+ expect(result.current.finalized).toBe(false);
+
+ mocks.workflowRun = { status: Status.Running, attempt: 2 };
+ rerender();
+ expect(result.current.running).toBe(true);
+ expect(result.current.view).toBe("live");
+
+ mocks.workflowRun = { status: Status.Failed, attempt: 2 };
+ rerender();
+ expect(result.current.running).toBe(false);
+ expect(result.current.finalized).toBe(true);
+ expect(result.current.view).toBe("screenshots");
+ });
+
test("resolves a selected container without an iteration to its first leaf", () => {
seedLoopRun();
const { result } = renderHook(() => useRunVisuals("wr_1"), { wrapper });
diff --git a/skyvern-frontend/src/routes/workflows/studio/useRunVisuals.ts b/skyvern-frontend/src/routes/workflows/studio/useRunVisuals.ts
index f1ea3b0e2..d46eaf37c 100644
--- a/skyvern-frontend/src/routes/workflows/studio/useRunVisuals.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/useRunVisuals.ts
@@ -1,8 +1,14 @@
+import {
+ getRunAttempt,
+ runIsLogicallyActive,
+ runIsLogicallyFinal,
+ runIsExecuting,
+} from "@/routes/workflows/workflowRun/runRetryState";
import { useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { Status, WorkflowRunStatusApiResponseWithWorkflow } from "@/api/types";
-import { statusIsFinalized } from "@/routes/tasks/types";
+
import {
isAction,
isObserverThought,
@@ -15,6 +21,7 @@ import { useWorkflowRunTimelineQuery } from "../hooks/useWorkflowRunTimelineQuer
import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";
import { getRecordingUrls } from "../workflowRun/recordingUrls";
import {
+ filterTimelineToAttempt,
findActiveItem,
findTimelineBlock,
resolveScreenshotBlockId,
@@ -30,6 +37,7 @@ export type RunVisuals = {
workflowRun: WorkflowRunStatusApiResponseWithWorkflow | undefined;
timeline: WorkflowRunTimelineItem[] | undefined;
running: boolean;
+ executing: boolean;
failed: boolean;
finalized: boolean;
provisioning: boolean;
@@ -70,18 +78,30 @@ export function useRunVisuals(workflowRunId: string | undefined): RunVisuals {
// the previous run's timeline on both a switch and a clear.
const timeline =
!workflowRunId || timelineIsPlaceholder ? undefined : retainedTimeline;
+ const currentTimeline = useMemo(
+ () =>
+ timeline
+ ? filterTimelineToAttempt(
+ timeline,
+ workflowRun?.attempts ?? [],
+ getRunAttempt(workflowRun ?? {}),
+ )
+ : undefined,
+ [timeline, workflowRun],
+ );
const [searchParams] = useSearchParams();
const activeParam = searchParams.get("active");
// The Overview pane's loop-iteration selection isn't in the URL; read it from the
// shared store so a selected iteration's screenshot resolves here too.
const activeIteration = useRunViewStore((s) => s.activeIteration);
- const outcome = runOutcomeFromStatus(workflowRun?.status);
- const running = outcome === "running";
+ const outcome = runOutcomeFromStatus(workflowRun);
+ const running = Boolean(workflowRun && runIsLogicallyActive(workflowRun));
+ const executing = Boolean(workflowRun && runIsExecuting(workflowRun));
// A user-canceled run isn't a failure — its replay defaults like a success.
const canceled = workflowRun?.status === Status.Canceled;
const failed = outcome === "failed" && !canceled;
- const finalized = workflowRun ? statusIsFinalized(workflowRun) : false;
+ const finalized = workflowRun ? runIsLogicallyFinal(workflowRun) : false;
const provisioning =
workflowRun?.status === Status.Created ||
workflowRun?.status === Status.Queued;
@@ -92,11 +112,14 @@ export function useRunVisuals(workflowRunId: string | undefined): RunVisuals {
[workflowRun],
);
- const frames = useMemo(() => buildFilmstrip(timeline), [timeline]);
+ const frames = useMemo(
+ () => buildFilmstrip(currentTimeline),
+ [currentTimeline],
+ );
const scrubbing = activeParam != null && activeParam !== "stream";
const landingSelectionId = useMemo(
- () => resolveLandingSelectionId(frames, timeline, finalized),
- [frames, timeline, finalized],
+ () => resolveLandingSelectionId(frames, currentTimeline, finalized),
+ [frames, currentTimeline, finalized],
);
const selectedFrameId = scrubbing ? activeParam : landingSelectionId;
const finallyBlockLabel =
@@ -104,12 +127,12 @@ export function useRunVisuals(workflowRunId: string | undefined): RunVisuals {
const activeItem = useMemo(
() =>
findActiveItem(
- timeline ?? [],
+ (selectedFrameId ? timeline : currentTimeline) ?? [],
selectedFrameId,
finalized,
finallyBlockLabel,
),
- [timeline, selectedFrameId, finalized, finallyBlockLabel],
+ [timeline, currentTimeline, selectedFrameId, finalized, finallyBlockLabel],
);
const heroSelection = useMemo<HeroSelection | null>(() => {
@@ -159,6 +182,7 @@ export function useRunVisuals(workflowRunId: string | undefined): RunVisuals {
workflowRun,
timeline,
running,
+ executing,
failed,
finalized,
provisioning,
diff --git a/skyvern-frontend/src/routes/workflows/studio/useStudioPanes.ts b/skyvern-frontend/src/routes/workflows/studio/useStudioPanes.ts
index ad8ca50f4..98b709d22 100644
--- a/skyvern-frontend/src/routes/workflows/studio/useStudioPanes.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/useStudioPanes.ts
@@ -26,7 +26,10 @@ import {
import { SELECTED_BLOCK_SEARCH_PARAM } from "../editor/hooks/useSelectedBlockUrlSync";
import { useStudioPaneDefaults } from "./StudioPaneDefaultsContext";
import { useStudioRunId } from "./useStudioRunId";
-import { useStudioWorkflowDeletedAt } from "./StudioShellContext";
+import {
+ useStudioShellContext,
+ useStudioWorkflowDeletedAt,
+} from "./StudioShellContext";
type ApplyPanesOptions = Pick<NavigateOptions, "state"> & {
// When true the resulting pane list is stored as the learned default for this
@@ -89,6 +92,7 @@ export function useStudioPanes() {
const { defaultPanes, clamp, notePaneWrite, learnedRunPanes } =
useStudioPaneDefaults();
const workflowDeleted = useStudioWorkflowDeletedAt() !== null;
+ const { restoreExpandedPane } = useStudioShellContext();
const present = useCallback(
(resolved: StudioPaneId[]): StudioPaneId[] => {
@@ -159,6 +163,7 @@ export function useStudioPanes() {
options?: ApplyPanesOptions,
writeKind: PaneWriteKind = "normal",
) => {
+ restoreExpandedPane?.();
const search = liveSearch(location.search);
const resolvedSearch = searchWithRunReference(search, studioRunId);
const context = copilotContextForSearch(resolvedSearch);
@@ -317,6 +322,7 @@ export function useStudioPanes() {
navigate,
notePaneWrite,
present,
+ restoreExpandedPane,
setCopilotSelection,
setPaneLayout,
workflowDeleted,
diff --git a/skyvern-frontend/src/routes/workflows/studio/useStudioPanesOrder.test.tsx b/skyvern-frontend/src/routes/workflows/studio/useStudioPanesOrder.test.tsx
index f145ee2aa..c501d51a7 100644
--- a/skyvern-frontend/src/routes/workflows/studio/useStudioPanesOrder.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/useStudioPanesOrder.test.tsx
@@ -8,11 +8,12 @@ import {
useLocation,
useNavigate,
} from "react-router-dom";
-import { beforeEach, describe, expect, test } from "vitest";
+import { beforeEach, describe, expect, test, vi } from "vitest";
import { useStudioShellStore } from "@/store/StudioShellStore";
import { type StudioPaneId } from "./panes";
+import { StudioShellContext } from "./StudioShellContext";
import { useStudioPanes } from "./useStudioPanes";
beforeEach(() => {
@@ -54,6 +55,7 @@ function CopilotMemoryProbe() {
<button onClick={() => togglePane("copilot")}>toggle-copilot</button>
<button onClick={() => togglePane("browser")}>toggle-browser</button>
<button onClick={() => togglePane("editor")}>toggle-editor</button>
+ <button onClick={() => openPane("browser")}>open-browser</button>
<button
onClick={() =>
openPane("copilot", {
@@ -92,6 +94,31 @@ function renderCopilotMemory(entry: string) {
}
describe("useStudioPanes Copilot context memory", () => {
+ test("restores an expanded pane before a nested pane action, even when the target is already open", () => {
+ const restoreExpandedPane = vi.fn();
+ render(
+ <StudioShellContext.Provider
+ value={{
+ copilotPortalEl: null,
+ panelPortalEl: null,
+ setEditorStreamSlot: vi.fn(),
+ setBrowserStreamSlot: vi.fn(),
+ setRunStreamSlot: vi.fn(),
+ restoreExpandedPane,
+ }}
+ >
+ <MemoryRouter initialEntries={["/studio?panes=editor,browser"]}>
+ <CopilotMemoryProbe />
+ </MemoryRouter>
+ </StudioShellContext.Provider>,
+ );
+
+ fireEvent.click(screen.getByText("open-browser"));
+
+ expect(restoreExpandedPane).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId("panes").textContent).toBe("editor,browser");
+ });
+
test("restores independent Studio and past-run selections without changing the URL", () => {
const studioAddress =
"/studio?via=blank&panes=copilot,editor,browser#proof";
diff --git a/skyvern-frontend/src/routes/workflows/studio/useStudioRunSignals.ts b/skyvern-frontend/src/routes/workflows/studio/useStudioRunSignals.ts
index b823f9487..b68ec6f13 100644
--- a/skyvern-frontend/src/routes/workflows/studio/useStudioRunSignals.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/useStudioRunSignals.ts
@@ -1,5 +1,5 @@
+import { useRunCompletionToast } from "../workflowRun/useRunCompletionToast";
import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";
-
import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";
import { useWorkflowRunsQuery } from "../hooks/useWorkflowRunsQuery";
import { finalizedRunStatus } from "./runProjections";
@@ -8,28 +8,28 @@ import { useStudioRunId } from "./useStudioRunId";
/**
* The run facts the shell keys UI off: Run-tab gating, the toggle status dot
* and label, and the first-visit pane default. `runId` is the inspected run —
- * the URL's run or the latest-run fallback — so the tab's label and status dot
+ * the URL's explicit run — so the tab's label and status dot
* always describe the same run. `knownHasRuns` stays undefined until the runs
* page-1 probe has data, so callers can tell "no runs" from "not loaded".
*/
export function useStudioRunSignals() {
const urlRunId = useStudioRunId();
const workflowPermanentId = useWorkflowPermanentId();
- const { data: urlRun } = useWorkflowRunWithWorkflowQuery({
- workflowRunId: urlRunId,
- });
const { data: runs } = useWorkflowRunsQuery({
workflowPermanentId,
page: 1,
pageSize: 1,
});
+ const runId = urlRunId;
+ const { data: urlRun } = useWorkflowRunWithWorkflowQuery({
+ workflowRunId: runId,
+ });
+ useRunCompletionToast(runId ? urlRun : undefined);
const knownHasRuns = runs === undefined ? undefined : runs.length > 0;
return {
hasRun: Boolean(urlRunId) || knownHasRuns === true,
- runId: urlRunId ?? runs?.[0]?.workflow_run_id,
- runStatus: finalizedRunStatus(
- urlRunId ? urlRun?.status : runs?.[0]?.status,
- ),
+ runId,
+ runStatus: finalizedRunStatus(runId ? urlRun : undefined),
knownHasRuns,
};
}
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowRunTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowRunTypes.ts
index 0ef8af240..6b117859b 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowRunTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowRunTypes.ts
@@ -26,6 +26,7 @@ export type ObserverThought = {
};
export type WorkflowRunBlock = {
+ attempt_number?: number | null;
workflow_run_block_id: string;
workflow_run_id: string;
parent_workflow_run_block_id: string | null;
@@ -86,6 +87,7 @@ export function isWorkflowRunLoopContainerBlock(block: {
}
export type WorkflowRunTimelineBlockItem = {
+ attempt?: number;
type: "block";
block: WorkflowRunBlock;
children: Array<WorkflowRunTimelineItem>;
@@ -95,6 +97,7 @@ export type WorkflowRunTimelineBlockItem = {
};
export type WorkflowRunTimelineThoughtItem = {
+ attempt?: number;
type: "thought";
block: null;
children: Array<WorkflowRunTimelineItem>;
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
index 55d279e27..84aa48d85 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
@@ -729,7 +729,26 @@ export type SplitPdfBlock = WorkflowBlockBase & {
parameters: Array<WorkflowParameter>;
};
+export type WorkflowRetryStatus =
+ | "completed"
+ | "failed"
+ | "terminated"
+ | "canceled"
+ | "timed_out";
+export type WorkflowRetryRule = {
+ status: WorkflowRetryStatus;
+ error_codes?: Array<string> | null;
+};
+export type WorkflowRetryWebhookMode = "final_only" | "every_attempt";
+export type WorkflowRetryPolicy = {
+ max_retries: number;
+ delay_seconds: number;
+ webhook_on_retry: WorkflowRetryWebhookMode;
+ retry_on: Array<WorkflowRetryRule>;
+};
+
export type WorkflowDefinition = {
+ retry_policy?: WorkflowRetryPolicy | null;
version?: number | null;
parameters: Array<Parameter>;
blocks: Array<WorkflowBlock>;
@@ -783,6 +802,7 @@ export type WorkflowApiResponse = {
};
export type WorkflowSettings = {
+ retryPolicy: WorkflowRetryPolicy | null;
proxyLocation: ProxyLocation | null;
webhookCallbackUrl: string | null;
persistBrowserSession: boolean;
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
index d2136f492..d6f9fd3de 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
@@ -6,6 +6,7 @@ import {
EmailBodyFormat,
WorkflowBlockType,
WorkflowModel,
+ WorkflowRetryPolicy,
} from "./workflowTypes";
export type WorkflowCreateYAMLRequest = {
@@ -41,6 +42,7 @@ export type WorkflowCreateYAMLRequest = {
};
export type WorkflowDefinitionYAML = {
+ retry_policy?: WorkflowRetryPolicy | null;
version?: number | null;
parameters: Array<ParameterYAML>;
blocks: Array<BlockYAML>;
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx
index 480ed25a2..947d17369 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx
@@ -2,7 +2,7 @@ import type { ActionsApiResponse } from "@/api/types";
import { useMemo } from "react";
import { FileIcon } from "@radix-ui/react-icons";
import { ArtifactDownloadLink } from "@/components/ArtifactDownloadLink";
-import { statusIsFinalized } from "@/routes/tasks/types";
+import { runIsLogicallyFinal } from "@/routes/workflows/workflowRun/runRetryState";
import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";
import {
isAction,
@@ -255,8 +255,7 @@ function WorkflowRunBlockDetail({
block={resolvedBlock}
iterationOverride={effectiveIteration}
runFinalized={
- Boolean(workflowRun) &&
- statusIsFinalized({ status: workflowRun!.status })
+ Boolean(workflowRun) && runIsLogicallyFinal(workflowRun!)
}
/>
</>
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsx
index 4436afc72..dc563be47 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsx
@@ -1,5 +1,5 @@
import { getClient } from "@/api/AxiosClient";
-import { ArtifactApiResponse, Status } from "@/api/types";
+import { ArtifactApiResponse } from "@/api/types";
import { ZoomableImage } from "@/components/ZoomableImage";
import { useArtifactImageSrc } from "@/hooks/useArtifactImageSrc";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
@@ -8,20 +8,19 @@ import {
SCREENSHOT_PANEL_CLASS,
StreamStatusPanel,
} from "@/routes/streaming/StreamDiagnostics";
-import { statusIsNotFinalized } from "@/routes/tasks/types";
import { apiPathPrefix } from "@/util/env";
import { isBlockScreenshot, selectBlockScreenshot } from "./blockScreenshot";
type Props = {
workflowRunBlockId: string;
blockType?: string;
- runStatus?: Status;
+ running?: boolean;
};
function WorkflowRunBlockScreenshot({
workflowRunBlockId,
blockType,
- runStatus,
+ running,
}: Props) {
const credentialGetter = useCredentialGetter();
@@ -40,8 +39,8 @@ function WorkflowRunBlockScreenshot({
// action screenshots land after its pre-execution LLM screenshot). Once finalized, stop:
// no further screenshots are captured, including for promptless code blocks that never
// produce one. Status unknown -> poll until any screenshot appears.
- if (runStatus !== undefined) {
- return statusIsNotFinalized({ status: runStatus }) ? 5000 : false;
+ if (running !== undefined) {
+ return running ? 5000 : false;
}
return query.state.data?.some(isBlockScreenshot) ? false : 5000;
},
@@ -63,10 +62,7 @@ function WorkflowRunBlockScreenshot({
);
}
- const runIsActive =
- runStatus !== undefined && statusIsNotFinalized({ status: runStatus });
-
- if (!screenshot && runIsActive) {
+ if (!screenshot && running) {
return (
<StreamStatusPanel
className={SCREENSHOT_PANEL_CLASS}
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunCode.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunCode.tsx
index 3453196bf..9c5a22c5f 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunCode.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunCode.tsx
@@ -1,3 +1,4 @@
+import { runIsLogicallyFinal } from "@/routes/workflows/workflowRun/runRetryState";
import { useCallback, useEffect, useRef, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
@@ -11,7 +12,7 @@ import {
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { HelpTooltip } from "@/components/HelpTooltip";
-import { statusIsFinalized } from "@/routes/tasks/types";
+
import { CodeEditor } from "@/routes/workflows/components/CodeEditor";
import { useBlockScriptsQuery } from "@/routes/workflows/hooks/useBlockScriptsQuery";
import { useCacheKeyValuesQuery } from "@/routes/workflows/hooks/useCacheKeyValuesQuery";
@@ -92,7 +93,7 @@ function WorkflowRunCode(props?: Props) {
page: 1,
workflowPermanentId,
});
- const isFinalized = workflowRun ? statusIsFinalized(workflowRun) : null;
+ const isFinalized = workflowRun ? runIsLogicallyFinal(workflowRun) : null;
const parameters = workflowRun?.parameters;
const [hasPublishedCode, setHasPublishedCode] = useState(false);
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOutput.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOutput.test.tsx
index d3219d02c..61c998e3d 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOutput.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOutput.test.tsx
@@ -1,16 +1,13 @@
// @vitest-environment jsdom
-vi.mock("@/api/AxiosClient", () => ({ getClient: vi.fn() }));
-vi.mock("@/hooks/useCredentialGetter", () => ({
- useCredentialGetter: () => null,
-}));
-
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cleanup, render, screen } from "@testing-library/react";
import { type ReactNode } from "react";
import { MemoryRouter } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Status } from "@/api/types";
+import { WorkflowRun } from "../WorkflowRun";
import type {
WorkflowRunBlock,
WorkflowRunTimelineBlockItem,
@@ -18,12 +15,16 @@ import type {
import { WorkflowRunOutput } from "./WorkflowRunOutput";
const mocks = vi.hoisted(() => ({
- activeItem: null as unknown,
workflowRun: null as unknown,
timeline: [] as unknown,
timelineIsPlaceholder: false,
}));
+vi.mock("@/api/AxiosClient", () => ({ getClient: vi.fn() }));
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => null,
+}));
+
vi.mock("../hooks/useWorkflowRunWithWorkflowQuery", () => ({
useWorkflowRunWithWorkflowQuery: () => ({
data: mocks.workflowRun,
@@ -39,10 +40,6 @@ vi.mock("../hooks/useWorkflowRunTimelineQuery", () => ({
}),
}));
-vi.mock("./useActiveWorkflowRunItem", () => ({
- useActiveWorkflowRunItem: () => [mocks.activeItem, vi.fn()],
-}));
-
vi.mock("../components/CodeEditor", () => ({
CodeEditor: ({ value }: { value: string }) => (
<pre data-testid="code-editor">{value}</pre>
@@ -60,6 +57,34 @@ vi.mock("@/components/ui/scroll-area", () => ({
),
}));
+vi.mock("@/hooks/useApiCredential", () => ({
+ useApiCredential: () => null,
+}));
+vi.mock("@/hooks/useWorkflowStudioEnabled", () => ({
+ useWorkflowStudioEnabled: () => false,
+}));
+vi.mock("../hooks/useCacheKeyValuesQuery", () => ({
+ useCacheKeyValuesQuery: () => ({ data: undefined }),
+}));
+vi.mock("../hooks/useBlockScriptsQuery", () => ({
+ useBlockScriptsQuery: () => ({ data: undefined }),
+}));
+vi.mock("../hooks/useFallbackEpisodesQuery", () => ({
+ useFallbackEpisodesQuery: () => ({ data: undefined }),
+}));
+vi.mock("../hooks/useRefreshOnboardingOnRunCompletion", () => ({
+ useRefreshOnboardingOnRunCompletion: () => undefined,
+}));
+vi.mock("./useRunCompletionToast", () => ({
+ useRunCompletionToast: () => undefined,
+}));
+vi.mock("./WorkflowRunTimeline", () => ({
+ WorkflowRunTimeline: () => null,
+}));
+vi.mock("./WorkflowRunBlockDetail", () => ({
+ WorkflowRunBlockDetail: () => null,
+}));
+
function buildBlock(
overrides: Partial<WorkflowRunBlock> = {},
): WorkflowRunBlock {
@@ -108,7 +133,6 @@ function buildBlockItem(block: WorkflowRunBlock): WorkflowRunTimelineBlockItem {
}
function renderWorkflowRunOutput(activeBlock: WorkflowRunBlock) {
- mocks.activeItem = activeBlock;
mocks.timeline = [buildBlockItem(activeBlock)];
mocks.workflowRun = {
workflow_run_id: activeBlock.workflow_run_id,
@@ -119,14 +143,17 @@ function renderWorkflowRunOutput(activeBlock: WorkflowRunBlock) {
};
return render(
- <MemoryRouter initialEntries={["/runs/demo?active=wrb_code"]}>
+ <MemoryRouter
+ initialEntries={[
+ `/runs/demo?active=${activeBlock.workflow_run_block_id}`,
+ ]}
+ >
<WorkflowRunOutput />
</MemoryRouter>,
);
}
beforeEach(() => {
- mocks.activeItem = null;
mocks.workflowRun = null;
mocks.timeline = [];
mocks.timelineIsPlaceholder = false;
@@ -137,6 +164,62 @@ afterEach(() => {
});
describe("WorkflowRunOutput", () => {
+ it.each([
+ { active: "", hasCurrentBlocks: true, expected: '"current output"' },
+ { active: "", hasCurrentBlocks: false, expected: null },
+ {
+ active: "?active=wrb_cleanup_1",
+ hasCurrentBlocks: true,
+ expected: '"historical output"',
+ },
+ ])(
+ "scopes default output to the current attempt ($active, $hasCurrentBlocks)",
+ ({ active, hasCurrentBlocks, expected }) => {
+ const historical = {
+ ...buildBlockItem(
+ buildBlock({
+ workflow_run_block_id: "wrb_cleanup_1",
+ label: "cleanup",
+ block_type: "code",
+ output: { extracted_information: "historical output" },
+ }),
+ ),
+ attempt: 1,
+ };
+ const current = {
+ ...buildBlockItem(
+ buildBlock({
+ workflow_run_block_id: "wrb_cleanup_2",
+ label: "cleanup",
+ block_type: "code",
+ output: { extracted_information: "current output" },
+ }),
+ ),
+ attempt: 2,
+ };
+ mocks.timeline = hasCurrentBlocks ? [historical, current] : [historical];
+ mocks.workflowRun = {
+ workflow_run_id: "wr_default",
+ status: Status.Completed,
+ attempt: 2,
+ workflow: { workflow_definition: { finally_block_label: "cleanup" } },
+ };
+
+ render(
+ <MemoryRouter initialEntries={[`/runs/wr_default${active}`]}>
+ <WorkflowRunOutput />
+ </MemoryRouter>,
+ );
+
+ expect(
+ screen
+ .queryAllByTestId("code-editor")
+ .map((editor) => editor.textContent)
+ .filter(Boolean),
+ ).toEqual(expected ? [expected] : []);
+ },
+ );
+
it("renders code block extracted information without the raw output wrapper", () => {
const block = buildBlock({
workflow_run_block_id: "wrb_code",
@@ -193,3 +276,79 @@ describe("WorkflowRunOutput with a retained timeline", () => {
expect(screen.queryByText('"ord_123"')).toBeNull();
});
});
+
+describe("legacy WorkflowRun failure card", () => {
+ it("uses the final attempt's code details and finally-block outcome", () => {
+ const reason = "CodeBlock failed with ValueError at line 8";
+ const body = buildBlock({
+ block_type: "code",
+ label: "body",
+ status: Status.Failed,
+ failure_reason: reason,
+ });
+ const finallyBlock = buildBlock({ label: "cleanup" });
+ mocks.workflowRun = {
+ workflow_run_id: "wr_retry",
+ status: Status.Failed,
+ attempt: 2,
+ failure_reason: reason,
+ task_v2: null,
+ workflow: {
+ title: "Retry workflow",
+ workflow_permanent_id: "wpid_retry",
+ workflow_definition: { blocks: [], finally_block_label: "cleanup" },
+ },
+ };
+ mocks.timeline = [
+ {
+ ...buildBlockItem({
+ ...body,
+ workflow_run_block_id: "wrb_body_1",
+ error_codes: ["runner_unavailable"],
+ }),
+ attempt: 1,
+ },
+ {
+ ...buildBlockItem({
+ ...finallyBlock,
+ workflow_run_block_id: "wrb_cleanup_1",
+ status: Status.Completed,
+ }),
+ attempt: 1,
+ },
+ {
+ ...buildBlockItem({
+ ...body,
+ workflow_run_block_id: "wrb_body_2",
+ error_codes: ["user_code_error"],
+ }),
+ attempt: 2,
+ },
+ {
+ ...buildBlockItem({
+ ...finallyBlock,
+ workflow_run_block_id: "wrb_cleanup_2",
+ status: Status.Failed,
+ }),
+ attempt: 2,
+ },
+ ];
+
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <MemoryRouter initialEntries={["/runs/wr_retry?embed=true"]}>
+ <WorkflowRun />
+ </MemoryRouter>
+ </QueryClientProvider>,
+ );
+
+ expect(
+ screen.getByText('"Execute on any outcome" block (cleanup) failed.'),
+ ).toBeDefined();
+ expect(
+ screen.getByText("The block's code raised ValueError"),
+ ).toBeDefined();
+ expect(screen.queryByText(/completed successfully/)).toBeNull();
+ expect(screen.queryByText("runner_unavailable")).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx
index d27452e4e..97cb5cb6f 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx
@@ -1,9 +1,16 @@
+import {
+ getRunAttempt,
+ getRunAttemptKey,
+ runIsRetryWaiting,
+ runIsExecuting,
+ runIsLogicallyFinal,
+} from "@/routes/workflows/workflowRun/runRetryState";
+import { statusIsNotFinalized } from "@/routes/tasks/types";
import { ActionsApiResponse, Status as WorkflowRunStatus } from "@/api/types";
import { BrowserStream } from "@/components/BrowserStream";
import { AspectRatio } from "@/components/ui/aspect-ratio";
import { BrowserSessionStream } from "@/routes/browserSessions/BrowserSessionStream";
import { ActionScreenshot } from "@/routes/tasks/detail/ActionScreenshot";
-import { statusIsFinalized } from "@/routes/tasks/types";
import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";
import { useWorkflowRunTimelineQuery } from "../hooks/useWorkflowRunTimelineQuery";
import {
@@ -18,6 +25,7 @@ import { WorkflowRunBlockScreenshot } from "./WorkflowRunBlockScreenshot";
import { WorkflowRunStream } from "./WorkflowRunStream";
import { useSearchParams } from "react-router-dom";
import {
+ filterTimelineToAttempt,
findActiveItem,
findTimelineBlock,
parseActiveIterationParam,
@@ -43,6 +51,15 @@ export type WorkflowRunOverviewActiveElement =
| null;
function WorkflowRunOverview() {
+ const { data: workflowRun } = useWorkflowRunWithWorkflowQuery();
+ return (
+ <WorkflowRunOverviewAttempt
+ key={workflowRun ? getRunAttemptKey(workflowRun) : "loading"}
+ />
+ );
+}
+
+function WorkflowRunOverviewAttempt() {
const [searchParams] = useSearchParams();
const active = searchParams.get("active");
const iterationParam = searchParams.get("iteration");
@@ -99,15 +116,32 @@ function WorkflowRunOverview() {
return null;
}
+ const retryWaiting = runIsRetryWaiting(workflowRun);
+ if (retryWaiting && (active === null || active === "stream")) {
+ return (
+ <AspectRatio ratio={16 / 9}>
+ <div className="flex h-full items-center justify-center">
+ Retry pending. The browser reconnects when the next attempt starts.
+ </div>
+ </AspectRatio>
+ );
+ }
+
if (typeof workflowRunTimeline === "undefined") {
return null;
}
- const workflowRunIsFinalized = statusIsFinalized(workflowRun);
+ const workflowRunIsFinalized = runIsLogicallyFinal(workflowRun);
const finallyBlockLabel =
workflowRun.workflow?.workflow_definition?.finally_block_label ?? null;
const selection = findActiveItem(
- workflowRunTimeline,
+ active === null
+ ? filterTimelineToAttempt(
+ workflowRunTimeline,
+ workflowRun?.attempts ?? [],
+ getRunAttempt(workflowRun),
+ )
+ : workflowRunTimeline,
active,
workflowRunIsFinalized,
finallyBlockLabel,
@@ -118,7 +152,7 @@ function WorkflowRunOverview() {
const wantsVncStream = !!(
browserSessionId &&
- !workflowRunIsFinalized &&
+ (runIsExecuting(workflowRun) || isPaused) &&
(selection === "stream" ||
(isWorkflowRunBlock(selection) &&
selection.block_type === "human_interaction"))
@@ -195,7 +229,7 @@ function WorkflowRunOverview() {
<WorkflowRunBlockScreenshot
workflowRunBlockId={screenshotBlockId}
blockType={screenshotBlockType}
- runStatus={workflowRun?.status}
+ running={statusIsNotFinalized(workflowRun)}
/>
);
})()}
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStatusAlert.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStatusAlert.tsx
index 493bac313..aa128e995 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStatusAlert.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStatusAlert.tsx
@@ -8,7 +8,11 @@ import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { HelpTooltip } from "@/components/HelpTooltip";
-import { type Status as WorkflowRunStatus } from "@/api/types";
+import {
+ type Status as WorkflowRunStatus,
+ type WorkflowRunRetryFields,
+} from "@/api/types";
+import { runIsRetryWaiting } from "./runRetryState";
const deadStatuses = [
"canceled",
@@ -25,12 +29,13 @@ type LiveStatus = (typeof liveStatuses)[number];
type WatchableStatus = EndingStatus | LiveStatus;
interface Props {
- status: WorkflowRunStatus;
+ run: { status: WorkflowRunStatus } & WorkflowRunRetryFields;
title?: string;
visible: boolean;
}
-function WorkflowRunStatusAlert({ status, title, visible }: Props) {
+function WorkflowRunStatusAlert({ run, title, visible }: Props) {
+ const { status, retry_pending } = run;
const [notifyIsOpen, setNotifyIsOpen] = useState(false);
const [statusesWatched, setStatusesWatched] = useState<Set<WatchableStatus>>(
new Set(),
@@ -85,6 +90,7 @@ function WorkflowRunStatusAlert({ status, title, visible }: Props) {
}, [notifyIsOpen]);
useEffect(() => {
+ if (runIsRetryWaiting(run)) return;
if (!hasRequestedNotification) {
return;
}
@@ -125,7 +131,7 @@ function WorkflowRunStatusAlert({ status, title, visible }: Props) {
);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [status]);
+ }, [status, retry_pending]);
function askForPermissions() {
if (hasRequestedNotification) {
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
index f0284c803..3e5e976fa 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
@@ -5,7 +5,6 @@ import { statusIsNotFinalized } from "@/routes/tasks/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { useFirstParam } from "@/hooks/useFirstParam";
import { getCredentialParam } from "@/util/env";
-import { toast } from "@/components/ui/use-toast";
import { useQueryClient } from "@tanstack/react-query";
import { useCdpInput } from "@/routes/streaming/useCdpInput";
import { InteractiveStreamView } from "@/routes/streaming/InteractiveStreamView";
@@ -253,22 +252,6 @@ function WorkflowRunStream({
queryClient.invalidateQueries({
queryKey: ["runs"],
});
- if (
- message.status === "failed" ||
- message.status === "terminated"
- ) {
- toast({
- title: "Run Failed",
- description: "The agent run has failed.",
- variant: "destructive",
- });
- } else if (message.status === "completed") {
- toast({
- title: "Run Completed",
- description: "The agent run has been completed.",
- variant: "success",
- });
- }
}
} catch (e) {
console.error("Failed to parse message", e);
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.test.tsx
index 8245b44f3..88b50c935 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.test.tsx
@@ -19,6 +19,8 @@ import {
vi,
} from "vitest";
import { type ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MemoryRouter } from "react-router-dom";
import { Status } from "@/api/types";
import type {
@@ -27,8 +29,13 @@ import type {
WorkflowRunTimelineItem,
} from "../types/workflowRunTypes";
import type { WorkflowBlock } from "../types/workflowTypes";
-import type { WorkflowRunOverviewActiveElement } from "./WorkflowRunOverview";
+import {
+ WorkflowRunOverview,
+ type WorkflowRunOverviewActiveElement,
+} from "./WorkflowRunOverview";
import { WorkflowRunTimeline } from "./WorkflowRunTimeline";
+import { DebuggerRunTimeline } from "../debugger/DebuggerRunTimeline";
+import { DebuggerRunTimelineMinimal } from "../debugger/DebuggerRunTimelineMinimal";
const mocks = vi.hoisted(() => ({
workflowRun: undefined as unknown,
@@ -37,6 +44,10 @@ const mocks = vi.hoisted(() => ({
timelineQuery: vi.fn(),
}));
+vi.mock("../hooks/useWorkflowRunQuery", () => ({
+ useWorkflowRunQuery: () => ({ data: mocks.workflowRun, isLoading: false }),
+}));
+
vi.mock("../hooks/useWorkflowRunWithWorkflowQuery", () => ({
useWorkflowRunWithWorkflowQuery: () => ({
data: mocks.workflowRun,
@@ -50,6 +61,16 @@ vi.mock("../hooks/useWorkflowRunTimelineQuery", () => ({
return { data: mocks.timeline, isLoading: false };
},
}));
+vi.mock("@/hooks/useRuntimeConfig", () => ({
+ useStreamTransport: () => ({ streamTransport: "cdp" }),
+}));
+vi.mock("./RunHealChip", () => ({ RunHealChip: () => null }));
+vi.mock("./RunReliabilityUplink", () => ({ RunReliabilityUplink: () => null }));
+vi.mock("./WorkflowRunBlockScreenshot", () => ({
+ WorkflowRunBlockScreenshot: ({ running }: { running: boolean }) => (
+ <div data-testid="block-screenshot" data-polling={running} />
+ ),
+}));
// Radix ScrollArea needs ResizeObserver, which jsdom doesn't provide.
vi.mock("@/components/ui/scroll-area", () => ({
ScrollArea: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
@@ -191,6 +212,177 @@ afterEach(() => {
});
describe("WorkflowRunTimeline", () => {
+ it("opens the selected attempt and preserves manual expansion across retries", () => {
+ const workflowRun = {
+ workflow_run_id: "wr_default",
+ status: Status.Running,
+ attempt: 2,
+ workflow: { workflow_definition: { blocks: [] } },
+ };
+ const historicalBlock = buildBlock({
+ workflow_run_block_id: "wrb_historical",
+ label: "historical_block",
+ });
+ mocks.workflowRun = workflowRun;
+ const timeline = [{ ...buildBlockItem(historicalBlock), attempt: 1 }];
+ mocks.timeline = timeline;
+ const view = (activeItem: WorkflowRunOverviewActiveElement) => (
+ <WorkflowRunTimeline
+ workflowRunId="wr_default"
+ activeItem={activeItem}
+ onLiveStreamSelected={noop}
+ onActionItemSelected={noop}
+ onBlockItemSelected={noop}
+ onThoughtItemSelected={noop}
+ onIterationSelected={noop}
+ />
+ );
+ const { rerender } = render(view(historicalBlock));
+ const historicalGroup = () =>
+ screen.getByRole("button", { name: /Attempt 1$/ });
+ expect(historicalGroup().getAttribute("aria-expanded")).toBe("true");
+ expect(screen.getByText("historical_block").closest("[hidden]")).toBeNull();
+ expect(
+ screen
+ .getByRole("button", { name: /Attempt 2/ })
+ .getAttribute("aria-expanded"),
+ ).toBe("true");
+
+ mocks.workflowRun = { ...workflowRun, attempt: 3 };
+ mocks.timeline = [
+ ...timeline,
+ {
+ ...buildBlockItem(buildBlock({ workflow_run_block_id: "wrb_current" })),
+ attempt: 3,
+ },
+ ];
+ rerender(view({ ...historicalBlock }));
+ expect(historicalGroup().getAttribute("aria-expanded")).toBe("true");
+ fireEvent.click(historicalGroup());
+ rerender(view({ ...historicalBlock }));
+ expect(historicalGroup().getAttribute("aria-expanded")).toBe("false");
+ expect(screen.queryByText("historical_block")).toBeNull();
+
+ fireEvent.click(historicalGroup());
+ rerender(view(null));
+ mocks.workflowRun = { ...workflowRun, attempt: 4 };
+ rerender(view(null));
+ expect(historicalGroup().getAttribute("aria-expanded")).toBe("true");
+ expect(screen.getByText("historical_block").closest("[hidden]")).toBeNull();
+ expect(
+ screen
+ .getByRole("button", { name: /Attempt 3$/ })
+ .getAttribute("aria-expanded"),
+ ).toBe("false");
+ expect(
+ screen
+ .getByRole("button", { name: /Attempt 4/ })
+ .getAttribute("aria-expanded"),
+ ).toBe("true");
+ });
+
+ it("restarts block numbering in each attempt", () => {
+ mocks.workflowRun = {
+ workflow_run_id: "wr_default",
+ status: Status.Completed,
+ attempt: 2,
+ workflow: { workflow_definition: { blocks: [] } },
+ };
+ mocks.timeline = [1, 2].map((attempt) => ({
+ ...buildBlockItem(
+ buildBlock({
+ workflow_run_block_id: `wrb_attempt_${attempt}`,
+ label: `attempt_${attempt}_block`,
+ created_at: `2026-01-01T00:0${attempt}:00Z`,
+ }),
+ ),
+ attempt,
+ }));
+
+ renderTimeline(null);
+ fireEvent.click(screen.getByRole("button", { name: /Attempt 1$/ }));
+
+ for (const attempt of [1, 2]) {
+ const row = screen
+ .getByText(`attempt_${attempt}_block`)
+ .closest("button")!;
+ expect(within(row).getByText("#1")).toBeDefined();
+ }
+ });
+
+ it("hides the Live control during a retry wait and restores it for the next attempt", () => {
+ const workflowRun = {
+ workflow_run_id: "wr_1",
+ status: Status.Failed,
+ attempt: 1,
+ retry_pending: true,
+ total_steps: 0,
+ credits_used: 0,
+ cached_credits_used: 0,
+ workflow: {
+ workflow_definition: { blocks: [], finally_block_label: null },
+ },
+ };
+ mocks.workflowRun = workflowRun;
+ mocks.timeline = [];
+ const view = () => (
+ <WorkflowRunTimeline
+ workflowRunId="wr_1"
+ activeItem={null}
+ onLiveStreamSelected={noop}
+ onActionItemSelected={noop}
+ onBlockItemSelected={noop}
+ onThoughtItemSelected={noop}
+ onIterationSelected={noop}
+ />
+ );
+ const { rerender } = render(view());
+ const liveControl = {
+ name: "Jump to the live stream of the running workflow",
+ };
+ expect(screen.queryByRole("button", liveControl)).toBeNull();
+
+ mocks.workflowRun = {
+ ...workflowRun,
+ status: Status.Running,
+ attempt: 2,
+ retry_pending: false,
+ };
+ rerender(view());
+ expect(screen.getByRole("button", liveControl)).toBeDefined();
+ });
+
+ it("stops overview artifact polling during a retry delay and resumes for the next attempt", () => {
+ mocks.workflowRun = {
+ workflow_run_id: "wr_1",
+ status: Status.Failed,
+ retry_pending: true,
+ };
+ mocks.timeline = [buildBlockItem(buildBlock())];
+ const client = new QueryClient();
+ const view = () => (
+ <QueryClientProvider client={client}>
+ <MemoryRouter initialEntries={["/?active=wrb_default"]}>
+ <WorkflowRunOverview />
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+ const { rerender } = render(view());
+
+ expect(screen.getByTestId("block-screenshot").dataset.polling).toBe(
+ "false",
+ );
+
+ mocks.workflowRun = {
+ workflow_run_id: "wr_1",
+ status: Status.Running,
+ attempt: 2,
+ };
+ rerender(view());
+ expect(screen.getByTestId("block-screenshot").dataset.polling).toBe("true");
+ client.clear();
+ });
+
it("does not offer a live stream from an unavailable status payload", () => {
mocks.workflowRun = {
status: Status.Running,
@@ -719,3 +911,90 @@ describe("timeline run resolution", () => {
});
});
});
+
+it("shows debugger execution indicators only between retry waits in both timeline variants", () => {
+ const run: { status: Status; retry_pending: boolean; attempt: number } = {
+ status: Status.Running,
+ retry_pending: false,
+ attempt: 1,
+ };
+ mocks.workflowRun = run;
+ mocks.timeline = [];
+ const view = () => (
+ <>
+ <DebuggerRunTimeline
+ activeItem={null}
+ onObserverThoughtCardSelected={noop}
+ onActionItemSelected={noop}
+ onBlockItemSelected={noop}
+ />
+ <DebuggerRunTimelineMinimal />
+ </>
+ );
+ const { container, rerender } = render(view());
+ expect(screen.getAllByText(/formulating actions/i)).toHaveLength(2);
+ expect(container.querySelector(".animate-pulse")).not.toBeNull();
+
+ run.status = Status.Failed;
+ run.retry_pending = true;
+ rerender(view());
+ expect(screen.queryAllByText(/formulating actions/i)).toHaveLength(0);
+ expect(screen.getByText("Workflow timeline is empty")).toBeTruthy();
+ expect(screen.getByText("-")).toBeTruthy();
+ expect(container.querySelector(".animate-pulse")).toBeNull();
+
+ mocks.timeline = [buildBlockItem(buildBlock({ label: "finished_attempt" }))];
+ rerender(view());
+ expect(screen.getByText("finished_attempt")).toBeTruthy();
+ expect(container.querySelector(".animate-pulse")).toBeNull();
+
+ run.status = Status.Running;
+ run.retry_pending = false;
+ run.attempt = 2;
+ rerender(view());
+ expect(screen.getAllByText(/formulating actions/i)).toHaveLength(2);
+ expect(screen.queryByText("finished_attempt")).toBeNull();
+ mocks.timeline = [{ ...buildBlockItem(buildBlock()), attempt: 2 }];
+ rerender(view());
+ expect(screen.queryAllByText(/formulating actions/i)).toHaveLength(0);
+ expect(container.querySelectorAll(".animate-pulse")).toHaveLength(2);
+});
+
+it.each([1, 2])(
+ "does not formulate actions during attempt %s's retry wait",
+ (attempt) => {
+ mocks.workflowRun = {
+ workflow_run_id: "wr_empty",
+ status: Status.Failed,
+ retry_pending: true,
+ attempt,
+ };
+ mocks.timeline = [];
+ renderTimeline(null);
+ expect(screen.queryByText("Formulating actions...")).toBeNull();
+ },
+);
+
+it.each([
+ ["user_code_error", "The block's code raised an error"],
+ ["E_CUSTOM", "E_CUSTOM"],
+])("labels attempt errors for %s", (code, label) => {
+ mocks.workflowRun = {
+ workflow_run_id: "wr_errors",
+ status: Status.Failed,
+ attempt: 2,
+ attempts: [
+ { attempt_number: 1, status: Status.Failed, error_codes: [code] },
+ ],
+ };
+ mocks.timeline = [];
+ renderTimeline(null);
+ expect(
+ screen.getByRole("button", {
+ name: new RegExp(`Attempt 1.*failed.*${label}`),
+ }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole("button", { name: /Attempt 2.*failed/ }),
+ ).toBeTruthy();
+});
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.tsx
index 150b92a53..56c137d48 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.tsx
@@ -1,3 +1,4 @@
+import { formatCodeBlockErrorCode } from "./codeBlockFailure";
import { ScrollArea, ScrollAreaViewport } from "@/components/ui/scroll-area";
import { Skeleton } from "@/components/ui/skeleton";
import {
@@ -7,18 +8,31 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { type WorkflowRunStatusApiResponseWithWorkflow } from "@/api/types";
-import { statusIsFinalized, statusIsNotFinalized } from "@/routes/tasks/types";
+import {
+ getRunAttempt,
+ runIsExecuting,
+ runIsLogicallyFinal,
+ runIsRetryWaiting,
+} from "./runRetryState";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@/components/ui/collapsible";
+import { formatElapsed } from "../studio/runProjections";
import { cn } from "@/util/utils";
import { DotFilledIcon } from "@radix-ui/react-icons";
-import { useEffect, useMemo, useRef } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";
import { useWorkflowRunTimelineQuery } from "../hooks/useWorkflowRunTimelineQuery";
import {
countActionsInTimeline,
countCompletedTopLevelBlocks,
+ isAction,
isBlockItem,
isObserverThought,
isThoughtItem,
+ isWorkflowRunBlock,
ObserverThought,
WorkflowRunBlock,
WorkflowRunTimelineItem,
@@ -29,12 +43,16 @@ import {
} from "./WorkflowRunOverview";
import { ThoughtCard } from "./ThoughtCard";
import {
+ StatusDot,
type SkippedBranchGroup,
WorkflowRunTimelineBlockItem,
} from "./WorkflowRunTimelineBlockItem";
import { WorkflowRunTimelineUnexecutedBlockItem } from "./WorkflowRunTimelineUnexecutedBlockItem";
import { buildCodeStepsByLabel } from "../workflowBlockUtils";
import {
+ groupTimelineByAttempt,
+ filterTimelineToAttempt,
+ findActiveItem,
buildBlockOrderIndex,
classifyUnexecutedDefinedBlocks,
flattenTimelineChronologically,
@@ -162,14 +180,79 @@ function WorkflowRunTimeline({
const { data: workflowRunTimeline, isLoading: workflowRunTimelineIsLoading } =
useWorkflowRunTimelineQuery({ workflowRunId });
+ const currentAttempt = getRunAttempt(workflowRun ?? {});
+ const groups = useMemo(
+ () =>
+ groupTimelineByAttempt(
+ workflowRunTimeline ?? [],
+ workflowRun?.attempts ?? [],
+ currentAttempt,
+ ).map((group) => ({
+ ...group,
+ blockOrder: buildBlockOrderIndex(group.items),
+ })),
+ [workflowRunTimeline, workflowRun?.attempts, currentAttempt],
+ );
+ const currentTimeline = useMemo(
+ () =>
+ filterTimelineToAttempt(
+ workflowRunTimeline ?? [],
+ workflowRun?.attempts ?? [],
+ currentAttempt,
+ ),
+ [workflowRunTimeline, workflowRun?.attempts, currentAttempt],
+ );
+ const activeItemId = isWorkflowRunBlock(activeItem)
+ ? activeItem.workflow_run_block_id
+ : isObserverThought(activeItem)
+ ? activeItem.thought_id
+ : isAction(activeItem)
+ ? activeItem.action_id
+ : null;
+ const activeAttempt = useMemo(
+ () =>
+ activeItemId === null
+ ? undefined
+ : groups.find((group) =>
+ findActiveItem(group.items, activeItemId, false),
+ )?.attemptNumber,
+ [activeItemId, groups],
+ );
+ const [expansion, setExpansion] = useState(() => ({
+ workflowRunId,
+ attempt: currentAttempt,
+ activeItemId,
+ activeAttempt,
+ overrides: new Map<number, boolean>(),
+ }));
+ if (
+ expansion.workflowRunId !== workflowRunId ||
+ expansion.attempt !== currentAttempt ||
+ expansion.activeItemId !== activeItemId ||
+ expansion.activeAttempt !== activeAttempt
+ ) {
+ const overrides =
+ expansion.workflowRunId === workflowRunId
+ ? new Map(expansion.overrides)
+ : new Map<number, boolean>();
+ if (expansion.attempt !== currentAttempt) {
+ overrides.delete(currentAttempt);
+ }
+ if (activeAttempt !== undefined) {
+ overrides.delete(activeAttempt);
+ }
+ setExpansion({
+ workflowRunId,
+ attempt: currentAttempt,
+ activeItemId,
+ activeAttempt,
+ overrides,
+ });
+ }
const displayTimeline = useMemo(
() => flattenTimelineChronologically(workflowRunTimeline ?? []),
[workflowRunTimeline],
);
- const blockOrder = useMemo(
- () => buildBlockOrderIndex(workflowRunTimeline ?? []),
- [workflowRunTimeline],
- );
const codeStepsByLabel = useMemo(
() =>
buildCodeStepsByLabel(
@@ -177,12 +260,10 @@ function WorkflowRunTimeline({
),
[workflowRun],
);
- const workflowRunIsNotFinalized =
- workflowRun && !statusUnavailable
- ? statusIsNotFinalized(workflowRun)
- : false;
+ const workflowRunIsExecuting =
+ workflowRun && !statusUnavailable ? runIsExecuting(workflowRun) : false;
const workflowRunIsFinalized = workflowRun
- ? statusIsFinalized(workflowRun)
+ ? runIsLogicallyFinal(workflowRun)
: false;
const definedBlocks = useMemo(
() => workflowRun?.workflow?.workflow_definition?.blocks ?? [],
@@ -191,12 +272,9 @@ function WorkflowRunTimeline({
const unexecutedBlocks = useMemo(
() =>
workflowRunIsFinalized
- ? classifyUnexecutedDefinedBlocks(
- definedBlocks,
- workflowRunTimeline ?? [],
- )
+ ? classifyUnexecutedDefinedBlocks(definedBlocks, currentTimeline)
: [],
- [definedBlocks, workflowRunIsFinalized, workflowRunTimeline],
+ [definedBlocks, workflowRunIsFinalized, currentTimeline],
);
const { skippedBranchBlocksByConditionalId, trailingUnexecutedBlocks } =
useMemo(() => {
@@ -281,6 +359,79 @@ function WorkflowRunTimeline({
const finallyBlockLabel =
workflowRun.workflow?.workflow_definition?.finally_block_label ?? null;
+ const showAttemptGroups = groups.length > 1 || currentAttempt > 1;
+ const unexecutedRows = trailingUnexecutedBlocks.map(({ block, reason }) => (
+ <WorkflowRunTimelineUnexecutedBlockItem
+ key={`unexecuted-${block.label}`}
+ block={block}
+ reason={reason}
+ />
+ ));
+ const renderTimelineItem = (
+ timelineItem: WorkflowRunTimelineItem,
+ blockOrder: ReadonlyMap<string, number> | undefined,
+ ) => {
+ const itemId = isBlockItem(timelineItem)
+ ? timelineItem.block.workflow_run_block_id
+ : isThoughtItem(timelineItem)
+ ? timelineItem.thought.thought_id
+ : null;
+ const isNew =
+ itemId !== null &&
+ !isInitialRenderRef.current &&
+ !knownItemIdsRef.current.has(itemId);
+
+ if (isBlockItem(timelineItem)) {
+ return (
+ <div
+ key={timelineItem.block.workflow_run_block_id}
+ className={cn({
+ "duration-300 animate-in fade-in slide-in-from-top-3": isNew,
+ })}
+ >
+ <WorkflowRunTimelineBlockItem
+ subItems={timelineItem.children}
+ activeItem={activeItem}
+ activeIteration={activeIteration}
+ block={timelineItem.block}
+ blockOrder={blockOrder}
+ codeStepsByLabel={codeStepsByLabel}
+ skippedBranchBlocksByConditionalId={
+ skippedBranchBlocksByConditionalId
+ }
+ onActionClick={onActionItemSelected}
+ onBlockItemClick={onBlockItemSelected}
+ onIterationClick={onIterationSelected}
+ onThoughtClick={onThoughtItemSelected}
+ finallyBlockLabel={finallyBlockLabel}
+ workflowRunIsFinalized={workflowRunIsFinalized}
+ />
+ </div>
+ );
+ }
+ if (isThoughtItem(timelineItem)) {
+ return (
+ <div
+ key={timelineItem.thought.thought_id}
+ className={cn(
+ "py-1",
+ isNew && "duration-300 animate-in fade-in slide-in-from-top-3",
+ )}
+ >
+ <ThoughtCard
+ active={
+ isObserverThought(activeItem) &&
+ activeItem.thought_id === timelineItem.thought.thought_id
+ }
+ onClick={onThoughtItemSelected}
+ thought={timelineItem.thought}
+ />
+ </div>
+ );
+ }
+ return null;
+ };
+
return (
<div
className={cn(
@@ -295,7 +446,7 @@ function WorkflowRunTimeline({
Timeline
</span>
<div className="min-w-0 flex-1" />
- {workflowRunIsNotFinalized && (
+ {workflowRunIsExecuting && (
<button
type="button"
onClick={onLiveStreamSelected}
@@ -319,7 +470,7 @@ function WorkflowRunTimeline({
<div className="flex shrink-0 flex-wrap items-center gap-x-3 gap-y-1 border-b border-border px-3 py-1.5 text-xs">
<TimelineRunCounts
workflowRun={workflowRun}
- timeline={workflowRunTimeline}
+ timeline={currentTimeline}
/>
</div>
</>
@@ -327,85 +478,92 @@ function WorkflowRunTimeline({
<ScrollArea className="min-h-0 flex-1">
<ScrollAreaViewport className="h-full max-h-full [&>div]:!block [&>div]:!overflow-x-hidden">
<div className="p-2">
- {workflowRunIsNotFinalized && workflowRunTimeline.length === 0 && (
- <div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
- Formulating actions...
- </div>
- )}
- {workflowRunIsFinalized && workflowRunTimeline.length === 0 && (
- <div>Workflow timeline is empty</div>
- )}
- {displayTimeline.map((timelineItem) => {
- const itemId = isBlockItem(timelineItem)
- ? timelineItem.block.workflow_run_block_id
- : isThoughtItem(timelineItem)
- ? timelineItem.thought.thought_id
- : null;
- const isNew =
- itemId !== null &&
- !isInitialRenderRef.current &&
- !knownItemIdsRef.current.has(itemId);
-
- if (isBlockItem(timelineItem)) {
- return (
- <div
- key={timelineItem.block.workflow_run_block_id}
- className={cn({
- "duration-300 animate-in fade-in slide-in-from-top-3":
- isNew,
- })}
- >
- <WorkflowRunTimelineBlockItem
- subItems={timelineItem.children}
- activeItem={activeItem}
- activeIteration={activeIteration}
- block={timelineItem.block}
- blockOrder={blockOrder}
- codeStepsByLabel={codeStepsByLabel}
- skippedBranchBlocksByConditionalId={
- skippedBranchBlocksByConditionalId
+ {!showAttemptGroups &&
+ workflowRunIsExecuting &&
+ workflowRunTimeline.length === 0 && (
+ <div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
+ Formulating actions...
+ </div>
+ )}
+ {!showAttemptGroups &&
+ workflowRunIsFinalized &&
+ workflowRunTimeline.length === 0 && (
+ <div>Workflow timeline is empty</div>
+ )}
+ {showAttemptGroups
+ ? groups.map((group) => {
+ const status =
+ group.summary?.status ??
+ (group.isCurrent ? workflowRun.status : null);
+ return (
+ <Collapsible
+ key={group.attemptNumber}
+ open={
+ expansion.overrides.get(group.attemptNumber) ??
+ (group.isCurrent ||
+ group.attemptNumber === activeAttempt)
}
- onActionClick={onActionItemSelected}
- onBlockItemClick={onBlockItemSelected}
- onIterationClick={onIterationSelected}
- onThoughtClick={onThoughtItemSelected}
- finallyBlockLabel={finallyBlockLabel}
- workflowRunIsFinalized={workflowRunIsFinalized}
- />
- </div>
- );
- }
- if (isThoughtItem(timelineItem)) {
- return (
- <div
- key={timelineItem.thought.thought_id}
- className={cn(
- "py-1",
- isNew &&
- "duration-300 animate-in fade-in slide-in-from-top-3",
- )}
- >
- <ThoughtCard
- active={
- isObserverThought(activeItem) &&
- activeItem.thought_id ===
- timelineItem.thought.thought_id
+ onOpenChange={(open) =>
+ setExpansion((previous) => {
+ const overrides = new Map(previous.overrides);
+ overrides.set(group.attemptNumber, open);
+ return { ...previous, overrides };
+ })
}
- onClick={onThoughtItemSelected}
- thought={timelineItem.thought}
- />
- </div>
- );
- }
- return null;
- })}
- {trailingUnexecutedBlocks.map(({ block, reason }) => (
- <WorkflowRunTimelineUnexecutedBlockItem
- key={`unexecuted-${block.label}`}
- block={block}
- reason={reason}
- />
- ))}
+ >
+ <CollapsibleTrigger className="flex w-full items-center gap-2 rounded px-2 py-2 text-left text-xs hover:bg-muted focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">
+ <StatusDot
+ status={status}
+ isFinalized={
+ !group.isCurrent || workflowRunIsFinalized
+ }
+ />
+ <span className="font-medium">
+ Attempt {group.attemptNumber}
+ </span>
+ {status ? (
+ <span>{status.replace("_", " ")}</span>
+ ) : null}
+ {group.isCurrent && runIsRetryWaiting(workflowRun) ? (
+ <span>Retry pending</span>
+ ) : null}
+ {group.summary?.error_codes[0] ? (
+ <span>
+ {formatCodeBlockErrorCode(
+ group.summary.error_codes[0],
+ )}
+ </span>
+ ) : null}
+ {group.summary?.started_at ? (
+ <span className="ml-auto tabular-nums text-muted-foreground">
+ {formatElapsed(
+ group.summary.started_at,
+ group.summary.finished_at,
+ )}
+ </span>
+ ) : null}
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ {group.items.length === 0 &&
+ (group.isCurrent && workflowRunIsExecuting ? (
+ <div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
+ Formulating actions...
+ </div>
+ ) : (
+ <div>Workflow timeline is empty</div>
+ ))}
+ {flattenTimelineChronologically(group.items).map(
+ (item) => renderTimelineItem(item, group.blockOrder),
+ )}
+ {group.isCurrent ? unexecutedRows : null}
+ </CollapsibleContent>
+ </Collapsible>
+ );
+ })
+ : displayTimeline.map((item) =>
+ renderTimelineItem(item, groups[0]?.blockOrder),
+ )}
+ {!showAttemptGroups ? unexecutedRows : null}
</div>
</ScrollAreaViewport>
</ScrollArea>
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts b/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts
index e2efa006d..e4d593ae4 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts
@@ -489,3 +489,9 @@ export function findRunCodeBlockFailure(
? null
: { ...failure, workflowRunBlockId: culprit.workflow_run_block_id };
}
+
+export function formatCodeBlockErrorCode(code: string): string {
+ return Object.prototype.hasOwnProperty.call(FAILURE_TEMPLATES, code)
+ ? FAILURE_TEMPLATES[code]!.title
+ : code;
+}
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/runCompletionNotices.ts b/skyvern-frontend/src/routes/workflows/workflowRun/runCompletionNotices.ts
new file mode 100644
index 000000000..04567f203
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/runCompletionNotices.ts
@@ -0,0 +1,26 @@
+/**
+ * useRunCompletionToast owns final-state notices on every surface and selects
+ * block-specific copy before claiming. Cancellation handlers claim their own
+ * confirmation. No caller may mark a run separately from displaying its notice.
+ * Claims refresh recency; the last 500 run IDs survive remounts and navigation.
+ */
+const MAX_NOTIFIED_RUN_IDS = 500;
+const notifiedRunIds = new Set<string>();
+
+export function claimRunCompletionNotice(
+ runId: string,
+ showNotice: () => void,
+): boolean {
+ if (notifiedRunIds.has(runId)) {
+ notifiedRunIds.delete(runId);
+ notifiedRunIds.add(runId);
+ return false;
+ }
+ showNotice();
+ notifiedRunIds.add(runId);
+ if (notifiedRunIds.size > MAX_NOTIFIED_RUN_IDS) {
+ const oldestRunId = notifiedRunIds.values().next().value;
+ if (oldestRunId !== undefined) notifiedRunIds.delete(oldestRunId);
+ }
+ return true;
+}
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/runRetryState.ts b/skyvern-frontend/src/routes/workflows/workflowRun/runRetryState.ts
new file mode 100644
index 000000000..e731bcd01
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/runRetryState.ts
@@ -0,0 +1,69 @@
+import type {
+ Status,
+ WorkflowRunAttempt,
+ WorkflowRunRetryFields,
+} from "@/api/types";
+import {
+ statusIsCancellable,
+ statusIsFinalized,
+ statusIsNotFinalized,
+ statusIsRunningOrQueued,
+} from "@/routes/tasks/types";
+import type { WorkflowRunTimelineItem } from "../types/workflowRunTypes";
+import { normalizeUtcTimestamp } from "@/util/timeFormat";
+
+type RunLike = { status: Status } & WorkflowRunRetryFields;
+
+export function getRunAttempt(run: WorkflowRunRetryFields): number {
+ return run.attempt ?? 1;
+}
+export function runIsLogicallyFinal(run: RunLike): boolean {
+ return statusIsFinalized(run) && !run.retry_pending;
+}
+export function runIsLogicallyActive(run: RunLike): boolean {
+ return statusIsNotFinalized(run) || !!run.retry_pending;
+}
+export function runIsRetryWaiting(run: RunLike): boolean {
+ return statusIsFinalized(run) && !!run.retry_pending;
+}
+/**
+ * Queued and running attempts execute. Created has not entered the execution
+ * queue yet; paused, skipped, and retry-waiting runs are idle.
+ */
+export function runIsExecuting(run: RunLike): boolean {
+ return statusIsRunningOrQueued(run) && !runIsRetryWaiting(run);
+}
+export function runIsCancellable(run: RunLike): boolean {
+ return statusIsCancellable(run) || runIsRetryWaiting(run);
+}
+export function getRunAttemptKey(
+ run: { workflow_run_id: string } & WorkflowRunRetryFields,
+): string {
+ return `${run.workflow_run_id}:${getRunAttempt(run)}`;
+}
+export function resolveTimelineItemAttempt(
+ item: WorkflowRunTimelineItem,
+ attempts: Array<WorkflowRunAttempt>,
+): number {
+ const explicitAttempt = item.attempt ?? item.block?.attempt_number;
+ if (explicitAttempt != null && explicitAttempt > 1) return explicitAttempt;
+ // Nested Task V2 items carry the child run's attempt 1, even when their
+ // enclosing run is retrying. Only that ambiguous default uses parent windows.
+ if (attempts.length > 1) {
+ const createdAt =
+ item.block?.created_at ?? item.thought?.created_at ?? item.created_at;
+ const created = Date.parse(normalizeUtcTimestamp(createdAt));
+ for (let index = 0; index < attempts.length; index++) {
+ const attempt = attempts[index]!;
+ const next = attempts[index + 1];
+ const start = attempt.started_at
+ ? Date.parse(normalizeUtcTimestamp(attempt.started_at))
+ : NaN;
+ const end = next?.started_at
+ ? Date.parse(normalizeUtcTimestamp(next.started_at))
+ : Infinity;
+ if (created >= start && created < end) return attempt.attempt_number;
+ }
+ }
+ return 1;
+}
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/useActiveWorkflowRunItem.ts b/skyvern-frontend/src/routes/workflows/workflowRun/useActiveWorkflowRunItem.ts
index d16e094de..222f9bd45 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/useActiveWorkflowRunItem.ts
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/useActiveWorkflowRunItem.ts
@@ -1,8 +1,14 @@
import { useSearchParams } from "react-router-dom";
import { useWorkflowRunTimelineQuery } from "../hooks/useWorkflowRunTimelineQuery";
import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";
-import { statusIsFinalized } from "@/routes/tasks/types";
-import { findActiveItem } from "./workflowTimelineUtils";
+import {
+ getRunAttempt,
+ runIsLogicallyFinal,
+} from "@/routes/workflows/workflowRun/runRetryState";
+import {
+ filterTimelineToAttempt,
+ findActiveItem,
+} from "./workflowTimelineUtils";
import { WorkflowRunOverviewActiveElement } from "./WorkflowRunOverview";
function useActiveWorkflowRunItem(): [
@@ -17,12 +23,17 @@ function useActiveWorkflowRunItem(): [
const { data: workflowRunTimeline } = useWorkflowRunTimelineQuery();
const workflowRunIsFinalized =
- workflowRunWithWorkflow && statusIsFinalized(workflowRunWithWorkflow);
+ workflowRunWithWorkflow && runIsLogicallyFinal(workflowRunWithWorkflow);
const finallyBlockLabel =
workflowRunWithWorkflow?.workflow?.workflow_definition
?.finally_block_label ?? null;
- const activeItem = findActiveItem(
+ const currentAttemptTimeline = filterTimelineToAttempt(
workflowRunTimeline ?? [],
+ workflowRunWithWorkflow?.attempts ?? [],
+ getRunAttempt(workflowRunWithWorkflow ?? {}),
+ );
+ const activeItem = findActiveItem(
+ active === null ? currentAttemptTimeline : (workflowRunTimeline ?? []),
active,
!!workflowRunIsFinalized,
finallyBlockLabel,
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/useRunCompletionToast.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/useRunCompletionToast.test.tsx
new file mode 100644
index 000000000..34a3f0d49
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/useRunCompletionToast.test.tsx
@@ -0,0 +1,67 @@
+// @vitest-environment jsdom
+
+import { cleanup, renderHook } from "@testing-library/react";
+import { afterEach, expect, test } from "vitest";
+import { MemoryRouter } from "react-router-dom";
+import type { ReactNode } from "react";
+import { Status } from "@/api/types";
+import { useToast } from "@/components/ui/use-toast";
+import { claimRunCompletionNotice } from "./runCompletionNotices";
+import { useRunCompletionToast } from "./useRunCompletionToast";
+
+afterEach(cleanup);
+
+test("block-specific completion wins across observers and never toasts twice", () => {
+ const run = {
+ workflow_run_id: "wr_block_notice",
+ status: Status.Running,
+ retry_pending: false,
+ failure_reason: "Step failed",
+ };
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter initialEntries={["/studio?wr=wr_block_notice&bl=step_1"]}>
+ {children}
+ </MemoryRouter>
+ );
+ const { result, rerender } = renderHook(
+ ({ status, retry_pending }) => {
+ const state = useToast();
+ useRunCompletionToast({ ...run, status, retry_pending });
+ useRunCompletionToast({ ...run, status, retry_pending });
+ return state.toasts;
+ },
+ {
+ wrapper,
+ initialProps: { status: Status.Running as Status, retry_pending: false },
+ },
+ );
+ const previousId = result.current[0]?.id;
+ rerender({ status: Status.Failed, retry_pending: true });
+ expect(result.current[0]?.id).toBe(previousId);
+ rerender({ status: Status.Failed, retry_pending: false });
+ expect(result.current[0]?.title).toBe("Agent Block step_1: failed");
+ expect(result.current[0]?.description).toBe("Reason: Step failed");
+ const noticeId = result.current[0]?.id;
+ rerender({ status: Status.Failed, retry_pending: false });
+ expect(result.current[0]?.id).toBe(noticeId);
+ expect(
+ claimRunCompletionNotice(run.workflow_run_id, () => {
+ throw new Error("Duplicate notice");
+ }),
+ ).toBe(false);
+});
+
+test("a failed display does not consume the run's notice", () => {
+ expect(() =>
+ claimRunCompletionNotice("wr_notice_failure", () => {
+ throw new Error("Display failed");
+ }),
+ ).toThrow("Display failed");
+ const displayed: string[] = [];
+ expect(
+ claimRunCompletionNotice("wr_notice_failure", () => {
+ displayed.push("shown");
+ }),
+ ).toBe(true);
+ expect(displayed).toEqual(["shown"]);
+});
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/useRunCompletionToast.ts b/skyvern-frontend/src/routes/workflows/workflowRun/useRunCompletionToast.ts
new file mode 100644
index 000000000..94a543cbc
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/useRunCompletionToast.ts
@@ -0,0 +1,63 @@
+import type { Status, WorkflowRunRetryFields } from "@/api/types";
+import { toast } from "@/components/ui/use-toast";
+import { statusIsAFailureType } from "@/routes/tasks/types";
+import { useEffect, useRef } from "react";
+import { useBlockRunTarget } from "../editor/hooks/useBlockRunTarget";
+import { claimRunCompletionNotice } from "./runCompletionNotices";
+import { runIsLogicallyActive, runIsLogicallyFinal } from "./runRetryState";
+
+type RunLike = {
+ workflow_run_id: string;
+ status: Status;
+ failure_reason?: string | null;
+} & WorkflowRunRetryFields;
+
+export function useRunCompletionToast(run: RunLike | null | undefined) {
+ const { workflowRunId, blockLabel } = useBlockRunTarget();
+ const observedActiveRunIds = useRef(new Set<string>());
+ useEffect(() => {
+ if (!run) return;
+ const runId = run.workflow_run_id;
+ if (runIsLogicallyActive(run)) {
+ observedActiveRunIds.current.add(runId);
+ return;
+ }
+ if (!runIsLogicallyFinal(run) || !observedActiveRunIds.current.has(runId))
+ return;
+
+ claimRunCompletionNotice(runId, () => {
+ if (workflowRunId === runId && blockLabel !== undefined) {
+ const failed = statusIsAFailureType(run);
+ toast({
+ title: `Agent Block ${blockLabel}: ${run.status}`,
+ description: failed ? `Reason: ${run.failure_reason}` : undefined,
+ variant: failed ? "destructive" : "success",
+ });
+ } else if (run.status === "failed" || run.status === "terminated") {
+ toast({
+ title: "Run Failed",
+ description: "The agent run has failed.",
+ variant: "destructive",
+ });
+ } else if (run.status === "timed_out") {
+ toast({
+ title: "Run Timed Out",
+ description: "The agent run has timed out.",
+ variant: "destructive",
+ });
+ } else if (run.status === "canceled") {
+ toast({
+ title: "Run Canceled",
+ description: "The agent run has been canceled.",
+ variant: "destructive",
+ });
+ } else if (run.status === "completed") {
+ toast({
+ title: "Run Completed",
+ description: "The agent run has been completed.",
+ variant: "success",
+ });
+ }
+ });
+ }, [run, workflowRunId, blockLabel]);
+}
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.test.ts b/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.test.ts
index 84730ae81..fc97bb707 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.test.ts
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "vitest";
-import { Status } from "@/api/types";
+import { Status, type WorkflowRunAttempt } from "@/api/types";
import {
countActionsInTimeline,
type ObserverThought,
@@ -10,6 +10,8 @@ import {
} from "../types/workflowRunTypes";
import type { WorkflowBlock } from "../types/workflowTypes";
import {
+ groupTimelineByAttempt,
+ filterTimelineToAttempt,
aggregateIterationStatus,
classifyUnexecutedDefinedBlocks,
findActiveItem,
@@ -305,6 +307,15 @@ describe("findLastExecutedBlock", () => {
});
describe("findActiveItem default selection", () => {
+ test("ignores previous-attempt blocks for the default but resolves explicit history", () => {
+ const previousBlock = buildBlock({ workflow_run_block_id: "wrb_attempt1" });
+ const timeline = [{ ...buildBlockItem(previousBlock), attempt: 1 }];
+ const currentTimeline = filterTimelineToAttempt(timeline, [], 2);
+
+ expect(findActiveItem(currentTimeline, null, true)).toBeNull();
+ expect(findActiveItem(timeline, "wrb_attempt1", true)).toBe(previousBlock);
+ });
+
test("returns 'stream' when no active param and the run is still in progress", () => {
const timeline = [buildBlockItem(buildBlock({ status: Status.Running }))];
expect(findActiveItem(timeline, null, false)).toBe("stream");
@@ -1146,3 +1157,51 @@ describe("resolveScreenshotBlockId", () => {
expect(resolveScreenshotBlockId(timeline, loop, 99)).toBe("wrb_iter1_leaf");
});
});
+
+test("keeps blocks tagged with attempt_number when attempt summaries are absent", () => {
+ const item = buildBlockItem(buildBlock({ attempt_number: 2 }));
+
+ expect(filterTimelineToAttempt([item], [], 2)).toEqual([item]);
+});
+
+test("attributes nested-run roots to their parent attempt window and keeps children together", () => {
+ const attempts: Array<WorkflowRunAttempt> = [1, 2].map((attempt) => ({
+ attempt_number: attempt,
+ status: Status.Completed,
+ started_at: `2026-01-01T00:0${attempt - 1}:00Z`,
+ finished_at: null,
+ failure_reason: null,
+ error_codes: [],
+ retry_decision: null,
+ decision_reason: null,
+ next_attempt_at: null,
+ webhook_sent_at: null,
+ }));
+ const child = buildBlockItem(buildBlock({ workflow_run_block_id: "child" }));
+ const nested = {
+ ...buildBlockItem(
+ buildBlock({
+ workflow_run_block_id: "nested",
+ attempt_number: null,
+ created_at: "2026-01-01T00:01:05Z",
+ }),
+ [child],
+ ),
+ attempt: 1,
+ };
+ const groups = groupTimelineByAttempt([nested], attempts, 2);
+ expect(
+ groups.map((group) => [
+ group.attemptNumber,
+ group.items.length,
+ group.isCurrent,
+ ]),
+ ).toEqual([
+ [1, 0, false],
+ [2, 1, true],
+ ]);
+ expect(groups[1]?.summary).toBe(attempts[1]);
+ expect(groups[1]?.items[0]).toBe(nested);
+ expect(groups[1]?.items[0]?.children).toEqual([child]);
+ expect(filterTimelineToAttempt([nested], attempts, 2)).toEqual([nested]);
+});
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.ts b/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.ts
index 0e7249096..ecb80065c 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.ts
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/workflowTimelineUtils.ts
@@ -1,4 +1,4 @@
-import { Status } from "@/api/types";
+import { Status, type WorkflowRunAttempt } from "@/api/types";
import { statusIsFinalized } from "@/routes/tasks/types";
import {
findUnexecutedDefinedBlocks,
@@ -12,6 +12,52 @@ import {
import { BranchCondition, WorkflowBlock } from "../types/workflowTypes";
import { WorkflowRunOverviewActiveElement } from "./WorkflowRunOverview";
+import { resolveTimelineItemAttempt } from "./runRetryState";
+
+export function groupTimelineByAttempt(
+ items: Array<WorkflowRunTimelineItem>,
+ attempts: Array<WorkflowRunAttempt>,
+ currentAttempt: number,
+): Array<{
+ attemptNumber: number;
+ items: Array<WorkflowRunTimelineItem>;
+ summary: WorkflowRunAttempt | null;
+ isCurrent: boolean;
+}> {
+ const itemsByAttempt = new Map<number, Array<WorkflowRunTimelineItem>>();
+ for (const item of items) {
+ const attempt = resolveTimelineItemAttempt(item, attempts);
+ const group = itemsByAttempt.get(attempt) ?? [];
+ group.push(item);
+ itemsByAttempt.set(attempt, group);
+ }
+ const numbers = new Set([
+ ...attempts.map((attempt) => attempt.attempt_number),
+ ...itemsByAttempt.keys(),
+ currentAttempt,
+ ]);
+ return [...numbers]
+ .sort((a, b) => a - b)
+ .map((attemptNumber) => ({
+ attemptNumber,
+ items: itemsByAttempt.get(attemptNumber) ?? [],
+ summary:
+ attempts.find((attempt) => attempt.attempt_number === attemptNumber) ??
+ null,
+ isCurrent: attemptNumber === currentAttempt,
+ }));
+}
+
+export function filterTimelineToAttempt(
+ items: Array<WorkflowRunTimelineItem>,
+ attempts: Array<WorkflowRunAttempt>,
+ attempt: number,
+): Array<WorkflowRunTimelineItem> {
+ return items.filter(
+ (item) => resolveTimelineItemAttempt(item, attempts) === attempt,
+ );
+}
+
const containerBlockTypes = new Set(["for_loop", "while_loop", "conditional"]);
function parseActiveIterationParam(value: string | null): number | null {
diff --git a/skyvern-frontend/src/store/WorkflowHasChangesStore.ts b/skyvern-frontend/src/store/WorkflowHasChangesStore.ts
index 92116a63e..e2fed4aae 100644
--- a/skyvern-frontend/src/store/WorkflowHasChangesStore.ts
+++ b/skyvern-frontend/src/store/WorkflowHasChangesStore.ts
@@ -287,6 +287,7 @@ const useWorkflowSave = (opts?: WorkflowSaveOpts) => {
workflow_system_prompt:
saveData.settings.workflowSystemPrompt ?? undefined,
error_code_mapping: saveData.settings.errorCodeMapping ?? undefined,
+ retry_policy: saveData.settings.retryPolicy ?? null,
},
is_saved_task: saveData.workflow.is_saved_task,
status: opts?.status ?? saveData.workflow.status,
diff --git a/skyvern-frontend/src/store/useRecordingStore.test.ts b/skyvern-frontend/src/store/useRecordingStore.test.ts
index 372f86a79..6344793fe 100644
--- a/skyvern-frontend/src/store/useRecordingStore.test.ts
+++ b/skyvern-frontend/src/store/useRecordingStore.test.ts
@@ -174,6 +174,23 @@ describe("commit safety and resets", () => {
expect(store().optimisticSteps).toHaveLength(1);
});
+ it("falls back to raw events when interpretation produced no draft steps", () => {
+ store().setIsRecording(true);
+ store().applyInterpretationUpdate(update("s1", 1, [], { finalized: true }));
+
+ expect(store().getFinalDraftSteps()).toBeNull();
+ });
+
+ it("preserves an intentionally empty draft after the user deletes every step", () => {
+ store().setIsRecording(true);
+ store().applyInterpretationUpdate(
+ update("s1", 1, [draft("s1-0", "click")], { finalized: true }),
+ );
+ store().deleteDraftStep("s1-0");
+
+ expect(store().getFinalDraftSteps()).toEqual([]);
+ });
+
it("reset() and starting a new recording zero optimistic state", () => {
store().setIsRecording(true);
store().addOptimisticStep(opt());
diff --git a/skyvern-frontend/src/store/useRecordingStore.ts b/skyvern-frontend/src/store/useRecordingStore.ts
index 6f87a5c80..cbe163288 100644
--- a/skyvern-frontend/src/store/useRecordingStore.ts
+++ b/skyvern-frontend/src/store/useRecordingStore.ts
@@ -313,8 +313,9 @@ interface RecordingStore {
setIsCommitting: (isCommitting: boolean) => void;
/**
* Draft steps to commit: snapshot minus user deletions, with user edits
- * applied. Null when live interpretation never produced a revision (caller
- * should fall back to raw event processing).
+ * applied. Null when live interpretation produced no draft steps (caller
+ * should fall back to raw event processing). An empty array is reserved for
+ * the intentional case where the user deleted every generated draft.
*/
getFinalDraftSteps: () => Array<RecordingDraftStep> | null;
/**
@@ -661,7 +662,7 @@ export const useRecordingStore = create<RecordingStore>((set, get) => ({
getFinalDraftSteps: () => {
const state = get();
- if (state.sessionRevision === 0) {
+ if (state.sessionRevision === 0 || state.draftSteps.length === 0) {
return null;
}
return applyDraftStepOverlays(
diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.py
index 9b86ae728..3b9168bd0 100644
--- a/tests/unit/test_workflow_copilot_route.py
+++ b/tests/unit/test_workflow_copilot_route.py
@@ -2356,6 +2356,98 @@ async def test_route_error_after_staged_commit_clears_stale_proposal_despite_kee
)
+ "newer_candidate_lands_during_commit",
+ [False, True],
+ ids=["assistant-row-write-fails", "candidate-superseded-then-assistant-row-write-fails"],
+)
+async def test_route_error_after_auto_accept_commit_keeps_the_committed_workflow(
+ monkeypatch: pytest.MonkeyPatch,
+ newer_candidate_lands_during_commit: bool,
+ api_key_request: MagicMock,
+ copilot_stream: MagicMock,
+ organization: SimpleNamespace,
+) -> None:
+ """Recovery after a successful auto-accept commit must not restore the pre-turn workflow over
+ it. A newer candidate landing during the commit discards this turn's proposal, so recovery
+ then sees a result that no longer carries the draft it committed."""
+ captured = install_fake_create(monkeypatch)
+ chat = SimpleNamespace(
+ workflow_copilot_chat_id="chat-1",
+ workflow_permanent_id="wpid-1",
+ organization_id="org-1",
+ proposed_workflow=None,
+ auto_accept=True,
+ )
+ original_workflow = _make_copilot_workflow("Saved workflow", _NOW)
+ committed = _make_copilot_workflow("Committed draft", _NOW)
+ agent_result = AgentResult(
+ user_response="done",
+ updated_workflow=committed,
+ global_llm_context=None,
+ workflow_yaml="title: Committed draft",
+ proposal_disposition="auto_applicable",
+ has_staged_proposal=True,
+ staged_workflow=committed,
+ narrative_payload=_narrative_payload(),
+ )
+ real_restore = workflow_copilot_route._restore_workflow_definition
+ _, workflow_params = setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)
+ monkeypatch.setattr(workflow_copilot_route, "_restore_workflow_definition", real_restore)
+ workflow_params.clear_workflow_copilot_candidate = AsyncMock()
+
+ def candidate(owner_turn_id: str) -> dict[str, Any]:
+ return {
+ "_copilot_yaml": "title: Committed draft",
+ COPILOT_PROPOSAL_METADATA_KEY: {
+ "owner_turn_id": owner_turn_id,
+ "revision": 1,
+ "canonical_fingerprint": "fp",
+ "disposition": "review_tested",
+ },
+ }
+
+ if newer_candidate_lands_during_commit:
+ agent_result.proposal_owner_turn_id = "turn-this"
+ agent_result.proposal_revision = 1
+
+ async def run_agent_publishing_candidate(*args: object, **kwargs: object) -> AgentResult:
+ chat.proposed_workflow = candidate("turn-this")
+ return agent_result
+
+ monkeypatch.setattr(workflow_copilot_route, "run_copilot_agent", run_agent_publishing_candidate)
+
+ canonical: dict[str, str] = {original_workflow.workflow_id: original_workflow.title}
+
+ async def update_workflow_definition(**kwargs: Any) -> None:
+ canonical[kwargs["workflow_id"]] = kwargs["title"]
+ if newer_candidate_lands_during_commit and kwargs["title"] == committed.title:
+ chat.proposed_workflow = candidate("turn-newer")
+
+ monkeypatch.setattr(app, "WORKFLOW_SERVICE", SimpleNamespace(update_workflow_definition=update_workflow_definition))
+
+ first_assistant_write_failure = [RuntimeError("assistant row write failed")]
+ assistant_rows: list[dict[str, Any]] = []
+
+ async def create_message(**kwargs: Any) -> SimpleNamespace:
+ if kwargs["sender"] == WorkflowCopilotChatSender.AI:
+ if first_assistant_write_failure:
+ raise first_assistant_write_failure.pop()
+ assistant_rows.append(kwargs)
+ return SimpleNamespace(created_at=_NOW)
+
+ workflow_params.create_workflow_copilot_chat_message = AsyncMock(side_effect=create_message)
+
+ await workflow_copilot_chat_post(api_key_request, _make_chat_request(), organization)
+ handler = captured["handler"]
+ assert callable(handler)
+ await handler(copilot_stream)
+
+ assert [row["turn_outcome"].response_kind for row in assistant_rows] == [ResponseKind.RECOVER]
+ assert canonical == {original_workflow.workflow_id: committed.title}
+
+
@pytest.mark.asyncio
async def test_finalise_normal_turn_clears_stale_proposal_when_rollback_itself_fails(
monkeypatch: pytest.MonkeyPatch,