Skip to content

Automate browser based workflows with AI

fix: resolve Code 2.0 script UI issues (SKY-8444–8448) (#5143)

pedrohsdb8ff61021018a
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowScriptDetailPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowScriptDetailPage.tsx
index acf93e732..f64e8d1c4 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowScriptDetailPage.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowScriptDetailPage.tsx
@@ -21,13 +21,14 @@ import {
DrawingPinFilledIcon,
DrawingPinIcon,
} from "@radix-ui/react-icons";
-import { Link, useParams } from "react-router-dom";
+import { Link, useParams, useSearchParams } from "react-router-dom";
import { CodeEditor } from "./components/CodeEditor";
import { usePinScriptMutation } from "./hooks/usePinScriptMutation";
import { useScriptRunsQuery } from "./hooks/useScriptRunsQuery";
import { useScriptVersionCodeQuery } from "./hooks/useScriptVersionCodeQuery";
import { useScriptVersionsQuery } from "./hooks/useScriptVersionsQuery";
import { useWorkflowScriptsQuery } from "./hooks/useWorkflowScriptsQuery";
+import { ScriptFixInput } from "./workflowRun/ScriptFixInput";
const statusVariant: Record<string, "default" | "secondary" | "destructive"> = {
completed: "default",
@@ -90,21 +91,28 @@ function StatusDistribution({
function WorkflowScriptDetailPage() {
const { workflowPermanentId, scriptId } = useParams();
+ const [searchParams] = useSearchParams();
+ const requestedVersion = searchParams.get("version");
const { data: versions, isLoading: versionsLoading } = useScriptVersionsQuery(
{ scriptId },
);
const latestVersion = versions?.versions?.[0]?.version;
+ // If a specific version was requested via query param, use it; otherwise latest
+ const activeVersion =
+ requestedVersion != null ? Number(requestedVersion) : latestVersion;
+ const isLatest = activeVersion === latestVersion;
const { data: codeData, isLoading: codeLoading } = useScriptVersionCodeQuery({
scriptId,
- version: latestVersion,
+ version: activeVersion,
});
const { data: runsData, isLoading: runsLoading } = useScriptRunsQuery({
scriptId,
pageSize: 50,
+ version: activeVersion,
});
const { data: scriptsData } = useWorkflowScriptsQuery({
@@ -121,10 +129,17 @@ function WorkflowScriptDetailPage() {
});
const mainScript = codeData?.main_script ?? "";
- const latestVersionInfo = versions?.versions?.[0];
+ const activeVersionInfo = versions?.versions?.find(
+ (v) => v.version === activeVersion,
+ );
+ const newerCount = versions?.versions
+ ? versions.versions.filter((v) => v.version > (activeVersion ?? 0)).length
+ : 0;
const runs = runsData?.runs ?? [];
const statusCounts = runsData?.status_counts ?? {};
const totalCount = runsData?.total_count ?? 0;
+ const successRate =
+ totalCount > 0 ? (statusCounts["completed"] ?? 0) / totalCount : null;
const MAX_RUNS_SHOWN = 50;
if (!workflowPermanentId || !scriptId) return null;
@@ -196,38 +211,78 @@ function WorkflowScriptDetailPage() {
<div className="grid grid-cols-4 gap-4">
<div className="rounded-md border p-4">
- <p className="text-sm text-muted-foreground">Latest Version</p>
- <p className="text-2xl font-semibold">
- {versionsLoading ? (
- <Skeleton className="h-8 w-12" />
- ) : (
- `v${latestVersion ?? "?"}`
+ <p className="text-sm text-muted-foreground">Viewing Revision</p>
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center gap-2">
+ <p className="text-2xl font-semibold">
+ {versionsLoading ? (
+ <Skeleton className="h-8 w-12" />
+ ) : (
+ `#${activeVersion ?? "?"}`
+ )}
+ </p>
+ {!versionsLoading && activeVersion != null && (
+ <Badge
+ variant="secondary"
+ className={
+ isLatest
+ ? "text-xs"
+ : "border-amber-500/30 bg-amber-500/10 text-xs text-amber-500"
+ }
+ >
+ {isLatest ? "Latest" : `${newerCount} newer`}
+ </Badge>
+ )}
+ </div>
+ {!versionsLoading && activeVersionInfo && (
+ <p className="font-mono text-xs text-muted-foreground">
+ {activeVersionInfo.script_revision_id}
+ </p>
)}
- </p>
+ </div>
</div>
<div className="rounded-md border p-4">
- <p className="text-sm text-muted-foreground">Total Versions</p>
+ <p className="text-sm text-muted-foreground">Revision History</p>
<p className="text-2xl font-semibold">
{versionsLoading ? (
<Skeleton className="h-8 w-12" />
) : (
- versions?.versions?.length ?? 0
+ <>
+ {versions?.versions
+ ? versions.versions.filter(
+ (v) => v.version < (activeVersion ?? 0),
+ ).length
+ : 0}{" "}
+ <span className="text-sm font-normal text-muted-foreground">
+ prior
+ </span>
+ </>
)}
</p>
</div>
<div className="rounded-md border p-4">
- <p className="text-sm text-muted-foreground">Total Runs</p>
+ <p className="text-sm text-muted-foreground">Runs (this revision)</p>
<p className="text-2xl font-semibold">
{runsLoading ? <Skeleton className="h-8 w-12" /> : totalCount}
</p>
</div>
<div className="rounded-md border p-4">
- <p className="text-sm text-muted-foreground">Completion Rate</p>
+ <p className="text-sm text-muted-foreground">Success Rate</p>
<p className="text-2xl font-semibold">
{runsLoading ? (
<Skeleton className="h-8 w-12" />
- ) : totalCount > 0 ? (
- `${Math.round(((statusCounts["completed"] ?? 0) / totalCount) * 100)}%`
+ ) : successRate != null ? (
+ <span
+ className={
+ successRate >= 0.8
+ ? "text-green-500"
+ : successRate >= 0.5
+ ? "text-yellow-500"
+ : "text-red-500"
+ }
+ >
+ {Math.round(successRate * 100)}%
+ </span>
) : (
"N/A"
)}
@@ -248,15 +303,25 @@ function WorkflowScriptDetailPage() {
</div>
<div className="space-y-3">
- <h2 className="text-lg font-semibold">Script Code</h2>
- {!codeLoading && !versionsLoading && latestVersionInfo?.run_id && (
+ <div className="flex items-center justify-between gap-4">
+ <h2 className="whitespace-nowrap text-lg font-semibold">
+ Script Code
+ </h2>
+ {workflowPermanentId && mainScript && (
+ <ScriptFixInput
+ workflowPermanentId={workflowPermanentId}
+ workflowRunId={activeVersionInfo?.run_id ?? undefined}
+ />
+ )}
+ </div>
+ {!codeLoading && !versionsLoading && activeVersionInfo?.run_id && (
<p className="text-sm text-muted-foreground">
- v{latestVersion} created on run{" "}
+ Revision #{activeVersion} created on run{" "}
<Link
- to={`/workflows/${workflowPermanentId}/${latestVersionInfo.run_id}/code`}
+ to={`/workflows/${workflowPermanentId}/${activeVersionInfo.run_id}/code`}
className="font-mono text-blue-400 hover:underline"
>
- {latestVersionInfo.run_id}
+ {activeVersionInfo.run_id}
</Link>
</p>
)}
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowScriptsPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowScriptsPage.tsx
index 5cbccf9b4..b93acf33e 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowScriptsPage.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowScriptsPage.tsx
@@ -29,6 +29,8 @@ import { toast } from "@/components/ui/use-toast";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";
import {
+ ChevronDownIcon,
+ ChevronRightIcon,
DrawingPinFilledIcon,
DrawingPinIcon,
FileTextIcon,
@@ -39,15 +41,16 @@ import {
} from "@radix-ui/react-icons";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { type AxiosError } from "axios";
-import { useState } from "react";
+import { Fragment, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { usePinScriptMutation } from "./hooks/usePinScriptMutation";
+import { useScriptVersionsQuery } from "./hooks/useScriptVersionsQuery";
import { useWorkflowQuery } from "./hooks/useWorkflowQuery";
import { useWorkflowScriptsQuery } from "./hooks/useWorkflowScriptsQuery";
import { WorkflowActions } from "./WorkflowActions";
import type { WorkflowScriptSummary } from "./types/scriptTypes";
-const TABLE_COL_COUNT = 7;
+const TABLE_COL_COUNT = 6;
function PinButton({
workflowPermanentId,
@@ -252,8 +255,6 @@ function ScriptsTableRows({
scripts: WorkflowScriptSummary[];
workflowPermanentId: string;
}) {
- const navigate = useNavigate();
-
if (isLoading) {
return (
<TableRow>
@@ -299,53 +300,182 @@ function ScriptsTableRows({
}
return scripts.map((script) => (
- <TableRow
+ <ScriptRow
key={script.script_id}
- className="cursor-pointer"
- onClick={() =>
- navigate(
- `/workflows/${workflowPermanentId}/scripts/${script.script_id}`,
- )
- }
- >
- <TableCell className="w-10">
- <PinButton workflowPermanentId={workflowPermanentId} script={script} />
- </TableCell>
- <TableCell className="font-mono text-sm">
- {script.cache_key_value || "(default)"}
- </TableCell>
- <TableCell>v{script.latest_version}</TableCell>
- <TableCell>{script.total_runs}</TableCell>
- <TableCell>
- {script.success_rate != null ? (
- <span
- className={
- script.success_rate >= 0.8
- ? "text-green-500"
- : script.success_rate >= 0.5
- ? "text-yellow-500"
- : "text-red-500"
- }
- >
- {Math.round(script.success_rate * 100)}%
- </span>
- ) : (
- <span className="text-muted-foreground">-</span>
- )}
- </TableCell>
- <TableCell title={basicTimeFormat(script.modified_at)}>
- {basicLocalTimeFormat(script.modified_at)}
- </TableCell>
- <TableCell>
- <DeleteScriptButton
- workflowPermanentId={workflowPermanentId}
- script={script}
- />
- </TableCell>
- </TableRow>
+ script={script}
+ workflowPermanentId={workflowPermanentId}
+ />
));
}
+function ScriptRow({
+ script,
+ workflowPermanentId,
+}: {
+ script: WorkflowScriptSummary;
+ workflowPermanentId: string;
+}) {
+ const [expanded, setExpanded] = useState(false);
+ const navigate = useNavigate();
+ const hasRevisions = script.version_count > 1;
+
+ const { data: versions, isLoading: versionsLoading } = useScriptVersionsQuery(
+ {
+ scriptId: expanded ? script.script_id : undefined,
+ },
+ );
+
+ // Group versions by run_id — each sub-row = one run that modified the script.
+ // versions is ordered DESC (newest first).
+ const runGroups: {
+ run_id: string | null;
+ count: number;
+ latest_at: string;
+ latest_version: number;
+ is_initial: boolean;
+ }[] = [];
+ if (versions?.versions) {
+ const vList = [...versions.versions].reverse(); // chronological order
+ const seen = new Map<string, number>();
+ for (const v of vList) {
+ const key = v.run_id ?? `__none_${v.version}`;
+ const existing = seen.get(key);
+ if (existing !== undefined && runGroups[existing]) {
+ runGroups[existing].count += 1;
+ runGroups[existing].latest_version = v.version;
+ } else {
+ seen.set(key, runGroups.length);
+ runGroups.push({
+ run_id: v.run_id,
+ count: 1,
+ latest_at: v.created_at,
+ latest_version: v.version,
+ is_initial: runGroups.length === 0,
+ });
+ }
+ }
+ runGroups.reverse(); // newest first for display
+ }
+
+ return (
+ <Fragment>
+ <TableRow
+ className="cursor-pointer"
+ onClick={() => {
+ if (hasRevisions) {
+ setExpanded(!expanded);
+ } else {
+ navigate(
+ `/workflows/${workflowPermanentId}/scripts/${script.script_id}`,
+ );
+ }
+ }}
+ >
+ <TableCell className="w-8">
+ {hasRevisions ? (
+ expanded ? (
+ <ChevronDownIcon className="size-4 text-muted-foreground" />
+ ) : (
+ <ChevronRightIcon className="size-4 text-muted-foreground" />
+ )
+ ) : null}
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <PinButton
+ workflowPermanentId={workflowPermanentId}
+ script={script}
+ />
+ <div className="flex flex-col gap-0.5">
+ <Link
+ to={`/workflows/${workflowPermanentId}/scripts/${script.script_id}`}
+ className="font-mono text-sm text-blue-400 hover:underline"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {script.cache_key_value || "(default)"}
+ </Link>
+ <span className="font-mono text-xs text-muted-foreground">
+ {script.script_id}
+ </span>
+ </div>
+ </div>
+ </TableCell>
+ <TableCell>{script.version_count}</TableCell>
+ <TableCell>{script.total_runs}</TableCell>
+ <TableCell title={basicTimeFormat(script.modified_at)}>
+ {basicLocalTimeFormat(script.modified_at)}
+ </TableCell>
+ <TableCell>
+ <DeleteScriptButton
+ workflowPermanentId={workflowPermanentId}
+ script={script}
+ />
+ </TableCell>
+ </TableRow>
+ {expanded && (
+ <>
+ {versionsLoading ? (
+ <TableRow>
+ <TableCell colSpan={TABLE_COL_COUNT}>
+ <Skeleton className="mx-8 h-5 w-3/4" />
+ </TableCell>
+ </TableRow>
+ ) : (
+ runGroups.map((group) => (
+ <TableRow
+ key={group.run_id ?? `no-run-v${group.latest_version}`}
+ className="cursor-pointer bg-muted/30 hover:bg-muted/50"
+ onClick={() =>
+ navigate(
+ `/workflows/${workflowPermanentId}/scripts/${script.script_id}?version=${group.latest_version}`,
+ )
+ }
+ >
+ <TableCell />
+ <TableCell className="pl-8 text-sm">
+ {group.run_id ? (
+ <Link
+ to={`/workflows/${workflowPermanentId}/${group.run_id}/code`}
+ className="font-mono text-xs text-blue-400 hover:underline"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {group.run_id}
+ </Link>
+ ) : (
+ <span className="text-xs text-muted-foreground">-</span>
+ )}
+ </TableCell>
+ <TableCell className="text-xs">
+ {group.is_initial ? (
+ <span className="text-muted-foreground">
+ Initial script
+ </span>
+ ) : (
+ <>
+ {group.count}{" "}
+ <span className="text-muted-foreground">
+ {group.count === 1 ? "correction" : "corrections"}
+ </span>
+ </>
+ )}
+ </TableCell>
+ <TableCell />
+ <TableCell
+ className="text-xs"
+ title={basicTimeFormat(group.latest_at)}
+ >
+ {basicLocalTimeFormat(group.latest_at)}
+ </TableCell>
+ <TableCell />
+ </TableRow>
+ ))
+ )}
+ </>
+ )}
+ </Fragment>
+ );
+}
+
function WorkflowScriptsPage() {
const { workflowPermanentId } = useParams();
const navigate = useNavigate();
@@ -379,8 +509,15 @@ function WorkflowScriptsPage() {
</>
) : (
<>
- <h1 className="text-lg font-semibold">{workflow?.title}</h1>
- <h2 className="text-sm">{workflowPermanentId}</h2>
+ <Link
+ to={`/workflows/${workflowPermanentId}/runs`}
+ className="text-lg font-semibold hover:text-blue-400 hover:underline"
+ >
+ {workflow?.title}
+ </Link>
+ <h2 className="text-sm text-muted-foreground">
+ {workflowPermanentId}
+ </h2>
</>
)}
</div>
@@ -424,11 +561,10 @@ function WorkflowScriptsPage() {
<Table>
<TableHeader>
<TableRow>
- <TableHead className="w-10" />
+ <TableHead className="w-8" />
<TableHead>Cache Key Value</TableHead>
- <TableHead>Version</TableHead>
- <TableHead>Total Runs</TableHead>
- <TableHead>Success Rate</TableHead>
+ <TableHead>Total Revisions</TableHead>
+ <TableHead>Runs</TableHead>
<TableHead>Last Updated</TableHead>
<TableHead className="w-12" />
</TableRow>
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useScriptRunsQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useScriptRunsQuery.ts
index 1a3bcc46f..5ea5d7fa3 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useScriptRunsQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useScriptRunsQuery.ts
@@ -6,17 +6,22 @@ import type { ScriptRunsResponse } from "../types/scriptTypes";
type Props = {
scriptId?: string;
pageSize?: number;
+ version?: number;
};
-function useScriptRunsQuery({ scriptId, pageSize = 50 }: Props) {
+function useScriptRunsQuery({ scriptId, pageSize = 50, version }: Props) {
const credentialGetter = useCredentialGetter();
return useQuery<ScriptRunsResponse>({
- queryKey: ["script-runs", scriptId, pageSize],
+ queryKey: ["script-runs", scriptId, pageSize, version],
queryFn: async () => {
const client = await getClient(credentialGetter, "sans-api-v1");
+ const params = new URLSearchParams({ page_size: String(pageSize) });
+ if (version !== undefined) {
+ params.set("version", String(version));
+ }
return client
- .get(`/scripts/${scriptId}/runs?page_size=${pageSize}`)
+ .get(`/scripts/${scriptId}/runs?${params}`)
.then((r) => r.data);
},
enabled: !!scriptId,
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunCode.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunCode.tsx
index 96f682f4f..ee67a23fc 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunCode.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunCode.tsx
@@ -282,7 +282,26 @@ function WorkflowRunCode(props?: Props) {
);
}
- const hasVersions = versions.length > 1;
+ // Compute "used" vs "generated" versions for this run
+ const workflowRunId = workflowRun?.workflow_run_id;
+ const generatedByThisRun = versions.filter(
+ (v) => v.run_id != null && v.run_id === workflowRunId,
+ );
+ const generatedVersion =
+ generatedByThisRun.length > 0
+ ? Math.max(...generatedByThisRun.map((v) => v.version))
+ : currentVersion;
+ const earliestGeneratedVersion =
+ generatedByThisRun.length > 0
+ ? Math.min(...generatedByThisRun.map((v) => v.version))
+ : null;
+ const usedVersion =
+ earliestGeneratedVersion != null
+ ? versions.find(
+ (v) =>
+ v.version < earliestGeneratedVersion && v.run_id !== workflowRunId,
+ )?.version ?? null
+ : null;
// Edit button shown when not in edit mode and there's a script to edit
const editButton =
@@ -322,51 +341,49 @@ function WorkflowRunCode(props?: Props) {
</div>
) : null;
- // Version selector — badge when single version, dropdown when multiple
- const versionSelector = !versionsFetched ? null : hasVersions ? (
- <Select
- value={String(selectedVersion ?? currentVersion ?? "")}
- onValueChange={(v: string) => setSelectedVersion(Number(v))}
- disabled={isEditing}
- >
- <SelectTrigger className="h-7 w-auto min-w-[5rem] gap-1.5 rounded-full border-slate-700 px-2.5 text-xs">
- <SelectValue placeholder="Version" />
- </SelectTrigger>
- <SelectContent>
- {versions.map((v) => {
- const isRunVersion = v.version === currentVersion;
- const isLatest = v.version === versions[0]?.version;
- return (
- <SelectItem key={v.version} value={String(v.version)}>
- <span className="flex items-center gap-1.5">
- <span
- className={cn({
- "font-semibold text-emerald-400": isRunVersion,
- })}
- >
- v{v.version}
- </span>
- {isRunVersion && (
- <span className="rounded-sm bg-emerald-900/50 px-1 py-0.5 text-[10px] leading-none text-emerald-300">
- this run
- </span>
- )}
- {isLatest && !isRunVersion && (
- <span className="rounded-sm bg-blue-900/50 px-1 py-0.5 text-[10px] leading-none text-blue-300">
- latest
- </span>
- )}
- </span>
- </SelectItem>
- );
- })}
- </SelectContent>
- </Select>
- ) : currentVersion != null ? (
- <span className="rounded-full border border-slate-700 px-2.5 py-1 text-xs text-slate-400">
- v{currentVersion}
- </span>
- ) : null;
+ // Version selector — "Used → Generated" chips instead of dropdown
+ const activeChipVersion = selectedVersion ?? generatedVersion;
+
+ const versionSelector = !versionsFetched ? null : (
+ <div className="flex items-center gap-1">
+ {usedVersion != null && (
+ <>
+ <button
+ type="button"
+ className={cn(
+ "rounded-full border px-2.5 py-1 text-xs transition-colors",
+ activeChipVersion === usedVersion
+ ? "border-blue-500 bg-blue-500/20 text-blue-300"
+ : "border-slate-700 text-slate-400 hover:border-slate-500",
+ )}
+ onClick={() => setSelectedVersion(usedVersion)}
+ disabled={isEditing}
+ >
+ Used: #{usedVersion}
+ </button>
+ <span className="text-xs text-slate-600">→</span>
+ </>
+ )}
+ {generatedVersion != null && (
+ <button
+ type="button"
+ className={cn(
+ "rounded-full border px-2.5 py-1 text-xs transition-colors",
+ activeChipVersion === generatedVersion || selectedVersion === null
+ ? "border-emerald-500 bg-emerald-500/20 text-emerald-300"
+ : "border-slate-700 text-slate-400 hover:border-slate-500",
+ )}
+ onClick={() => setSelectedVersion(null)}
+ disabled={isEditing}
+ >
+ Generated: #{generatedVersion}
+ {usedVersion == null && (
+ <span className="ml-1 text-[10px] text-slate-500">(initial)</span>
+ )}
+ </button>
+ )}
+ </div>
+ );
if (!showCacheKeyValueSelector || !cacheKey || cacheKey === "") {
return (
diff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.py
index 41be4b113..abe7865be 100644
--- a/skyvern/forge/sdk/db/agent_db.py
+++ b/skyvern/forge/sdk/db/agent_db.py
@@ -6456,6 +6456,10 @@ class AgentDB(BaseAlchemyDB):
)
if statuses:
query = query.filter(WorkflowScriptModel.status.in_(statuses))
+ # A single run can create multiple workflow_script entries (one per
+ # revision cycle). Return the latest one so callers see the final
+ # version produced by the run.
+ query = query.order_by(WorkflowScriptModel.created_at.desc())
workflow_script_model = (await session.scalars(query)).first()
return WorkflowScript.model_validate(workflow_script_model) if workflow_script_model else None
@@ -6493,6 +6497,9 @@ class AgentDB(BaseAlchemyDB):
if workflow_run_id:
query = query.where(WorkflowScriptModel.workflow_run_id == workflow_run_id)
+ # Pin to the script version that existed when this run's
+ # workflow_script entry was created, not the latest version.
+ query = query.where(ScriptModel.created_at <= WorkflowScriptModel.created_at)
if cache_key is not None:
query = query.where(WorkflowScriptModel.cache_key == cache_key)
@@ -6521,7 +6528,7 @@ class AgentDB(BaseAlchemyDB):
try:
async with self.Session() as session:
query = (
- select(func.count())
+ select(func.count(distinct(WorkflowScriptModel.cache_key_value)))
.select_from(WorkflowScriptModel)
.filter_by(organization_id=organization_id)
.filter_by(workflow_permanent_id=workflow_permanent_id)
@@ -6553,7 +6560,7 @@ class AgentDB(BaseAlchemyDB):
try:
async with self.Session() as session:
query = (
- select(WorkflowScriptModel.cache_key_value)
+ select(distinct(WorkflowScriptModel.cache_key_value))
.order_by(WorkflowScriptModel.cache_key_value.asc())
.filter_by(organization_id=organization_id)
.filter_by(workflow_permanent_id=workflow_permanent_id)
@@ -6696,8 +6703,9 @@ class AgentDB(BaseAlchemyDB):
total_count is derived from the status_counts GROUP BY, and status_counts is a
GROUP BY aggregation of statuses across all runs.
- If created_after/created_before are provided, filters runs to those that started
- within the time window (used for version-scoped queries).
+ If created_after/created_before are provided, filters by the workflow_script
+ entry's created_at (not the run's created_at), scoping to the version that
+ was active in that time window.
"""
try:
async with self.Session() as session:
@@ -6709,15 +6717,22 @@ class AgentDB(BaseAlchemyDB):
.filter(WorkflowScriptModel.workflow_run_id.isnot(None))
)
+ # Time-window filters scope by workflow_script creation time,
+ # which aligns with the script version that was created/used.
+ if created_after is not None:
+ run_ids_subquery = run_ids_subquery.filter(
+ WorkflowScriptModel.created_at >= created_after,
+ )
+ if created_before is not None:
+ run_ids_subquery = run_ids_subquery.filter(
+ WorkflowScriptModel.created_at < created_before,
+ )
+
# Base filter for workflow runs
base_filters = [
WorkflowRunModel.workflow_run_id.in_(run_ids_subquery),
WorkflowRunModel.organization_id == organization_id,
]
- if created_after is not None:
- base_filters.append(WorkflowRunModel.created_at >= created_after)
- if created_before is not None:
- base_filters.append(WorkflowRunModel.created_at < created_before)
# Count statuses via GROUP BY (also gives us total_count)
status_query = (
diff --git a/skyvern/forge/sdk/routes/scripts.py b/skyvern/forge/sdk/routes/scripts.py
index 6441eaf3e..9dbd897cd 100644
--- a/skyvern/forge/sdk/routes/scripts.py
+++ b/skyvern/forge/sdk/routes/scripts.py
@@ -723,7 +723,35 @@ async def get_workflow_script_blocks(
if not workflow_run:
workflow_run_id = None
else:
- # find the published script if any and return that
+ # Try to find the script version pinned to this specific run first.
+ # get_workflow_script() always resolves the latest version for a
+ # cache_key_value, but the Code tab should show the version that was
+ # active when this run executed (SKY-8448).
+ workflow_script = await app.DATABASE.get_workflow_script(
+ organization_id=current_org.organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ workflow_run_id=workflow_run_id,
+ statuses=[ScriptStatus.published],
+ )
+ if workflow_script:
+ published_script = await workflow_script_service.get_workflow_script_by_cache_key_value(
+ organization_id=current_org.organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ cache_key_value=workflow_script.cache_key_value,
+ workflow_run_id=workflow_run_id,
+ statuses=[ScriptStatus.published],
+ )
+ if published_script:
+ return await get_script_blocks_response(
+ script_revision_id=published_script.script_revision_id,
+ organization_id=current_org.organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ include_main_script=include_main_script,
+ script_id=published_script.script_id,
+ version=published_script.version,
+ )
+
+ # Fall back to latest version (for runs without a workflow_script entry)
published_script, _ = await workflow_script_service.get_workflow_script(
workflow=workflow,
workflow_run=workflow_run,
@@ -945,6 +973,7 @@ async def list_workflow_scripts(
async def get_script_runs(
script_id: str = Path(..., description="The script ID"),
page_size: int = Query(50, ge=1, le=100),
+ version: int | None = Query(None, description="Filter runs to a specific script version"),
current_org: Organization = Depends(org_auth_service.get_current_org),
) -> ScriptRunsResponse:
"""Get workflow runs associated with a specific script, with status counts."""
@@ -955,10 +984,34 @@ async def get_script_runs(
if not script:
raise HTTPException(status_code=404, detail="Script not found")
+ created_after = None
+ created_before = None
+
+ if version is not None:
+ # Get all versions to determine the time window for this version
+ all_versions = await app.DATABASE.get_script_versions(
+ script_id=script_id,
+ organization_id=organization_id,
+ )
+ # versions is ordered by version DESC
+ version_found = False
+ for i, v in enumerate(all_versions):
+ if v.version == version:
+ created_after = v.created_at
+ # Next higher version (i-1 in DESC order) sets the upper bound
+ if i > 0:
+ created_before = all_versions[i - 1].created_at
+ version_found = True
+ break
+ if not version_found:
+ raise HTTPException(status_code=404, detail=f"Script version {version} not found")
+
runs, total_count, status_counts = await app.DATABASE.get_workflow_runs_for_script(
organization_id=organization_id,
script_id=script_id,
page_size=page_size,
+ created_after=created_after,
+ created_before=created_before,
)
return ScriptRunsResponse(