Skip to content

Automate browser based workflows with AI

Lead repeatable agent scheduling with a date/time picker flow (#7443)

Aaron Perezcad7fc45b103
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 752e1da80..00dc9b009 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -8616,6 +8616,7 @@
"recording",
"audio",
"session_replay",
+ "eval_score",
"browser_console_log",
"skyvern_log",
"skyvern_log_raw",
@@ -10044,7 +10045,7 @@
"type": "number",
"title": "Timeout",
"description": "Timeout in milliseconds",
- "default": 5000
+ "default": 10000
}
},
"type": "object",
@@ -16816,7 +16817,7 @@
"type": "number",
"title": "Timeout",
"description": "Timeout in milliseconds",
- "default": 5000
+ "default": 10000
}
},
"type": "object",
@@ -20268,7 +20269,7 @@
"type": "number",
"title": "Timeout",
"description": "Timeout in milliseconds",
- "default": 5000
+ "default": 10000
}
},
"type": "object",
@@ -23989,7 +23990,7 @@
"type": "number",
"title": "Timeout",
"description": "Timeout in milliseconds",
- "default": 5000
+ "default": 10000
}
},
"type": "object",
diff --git a/docs/pr-screenshots/download-target-options.png b/docs/pr-screenshots/download-target-options.png
new file mode 100644
index 000000000..da56ac795
Binary files /dev/null and b/docs/pr-screenshots/download-target-options.png differ
diff --git a/docs/pr-screenshots/download-target-s3.png b/docs/pr-screenshots/download-target-s3.png
new file mode 100644
index 000000000..ddbcd244e
Binary files /dev/null and b/docs/pr-screenshots/download-target-s3.png differ
diff --git a/docs/pr-screenshots/download-target-sftp.png b/docs/pr-screenshots/download-target-sftp.png
new file mode 100644
index 000000000..c6acecd4d
Binary files /dev/null and b/docs/pr-screenshots/download-target-sftp.png differ
diff --git a/docs/pr-screenshots/download-target-website.png b/docs/pr-screenshots/download-target-website.png
new file mode 100644
index 000000000..0c585f5cc
Binary files /dev/null and b/docs/pr-screenshots/download-target-website.png differ
diff --git a/scripts/backfill_encrypt_file_block_secrets.py b/scripts/backfill_encrypt_file_block_secrets.py
new file mode 100644
index 000000000..60c9c6dce
--- /dev/null
+++ b/scripts/backfill_encrypt_file_block_secrets.py
@@ -0,0 +1,180 @@
+import argparse
+import asyncio
+import copy
+from typing import Any
+
+import structlog
+from sqlalchemy import Select, select
+from sqlalchemy.orm.attributes import flag_modified
+
+from skyvern.forge import app
+from skyvern.forge.forge_app_initializer import start_forge_app
+from skyvern.forge.sdk.db.models import WorkflowModel
+from skyvern.forge.sdk.workflow.secret_encryption import (
+ SENSITIVE_DESTINATION_FIELDS,
+ encrypt_secret_field_value,
+ encryption_available,
+)
+
+LOG = structlog.get_logger()
+BATCH_SIZE = 100
+FILE_BLOCK_TYPES = frozenset({"file_upload", "file_download"})
+LOOP_BLOCK_TYPES = frozenset({"for_loop", "while_loop"})
+
+
+async def encrypt_file_block_secrets(
+ workflow_definition: dict[str, Any], organization_id: str | None
+) -> tuple[dict[str, Any], int]:
+ transformed = copy.deepcopy(workflow_definition)
+
+ async def encrypt_blocks(blocks: Any) -> int:
+ if not isinstance(blocks, list):
+ return 0
+
+ fields_encrypted = 0
+ for block in blocks:
+ if not isinstance(block, dict):
+ continue
+
+ block_type = block.get("block_type")
+ if block_type in FILE_BLOCK_TYPES:
+ for field_name in SENSITIVE_DESTINATION_FIELDS:
+ value = block.get(field_name)
+ if not isinstance(value, str):
+ continue
+
+ encrypted_value = await encrypt_secret_field_value(
+ value, organization_id=organization_id, field_name=field_name
+ )
+ if encrypted_value != value:
+ block[field_name] = encrypted_value
+ fields_encrypted += 1
+ elif block_type in LOOP_BLOCK_TYPES:
+ fields_encrypted += await encrypt_blocks(block.get("loop_blocks"))
+
+ return fields_encrypted
+
+ fields_encrypted = await encrypt_blocks(transformed.get("blocks"))
+ return transformed, fields_encrypted
+
+
+def _contains_file_block(blocks: Any) -> bool:
+ if not isinstance(blocks, list):
+ return False
+
+ for block in blocks:
+ if not isinstance(block, dict):
+ continue
+
+ block_type = block.get("block_type")
+ if block_type in FILE_BLOCK_TYPES:
+ return True
+ if block_type in LOOP_BLOCK_TYPES and _contains_file_block(block.get("loop_blocks")):
+ return True
+
+ return False
+
+
+def _non_deleted_workflows_query(offset: int) -> Select[tuple[WorkflowModel]]:
+ return (
+ select(WorkflowModel)
+ .where(WorkflowModel.deleted_at.is_(None))
+ .order_by(WorkflowModel.workflow_permanent_id, WorkflowModel.version, WorkflowModel.workflow_id)
+ .limit(BATCH_SIZE)
+ .offset(offset)
+ )
+
+
+def _parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description="Encrypt literal secrets in stored workflow file blocks.")
+ mode = parser.add_mutually_exclusive_group()
+ mode.add_argument("--dry-run", action="store_true", dest="dry_run", help="Report changes without writing.")
+ mode.add_argument("--commit", action="store_false", dest="dry_run", help="Write encrypted values to the database.")
+ parser.set_defaults(dry_run=True)
+ return parser.parse_args()
+
+
+def _require_encryption() -> None:
+ if not encryption_available():
+ raise SystemExit(
+ "File block secret backfill requires authenticated encryption. Set ENABLE_ENCRYPTION=true and configure "
+ "ENCRYPTOR_AES_SECRET_KEY (and optionally ENCRYPTOR_AES_SALT)."
+ )
+
+
+async def main() -> None:
+ args = _parse_args()
+ _require_encryption()
+
+ workflows_scanned = 0
+ workflows_changed = 0
+ fields_encrypted = 0
+ scripts_invalidated = 0
+ invalidated: set[tuple[str, str]] = set()
+ offset = 0
+
+ LOG.info("Starting file block secret backfill", dry_run=args.dry_run, batch_size=BATCH_SIZE)
+ while True:
+ batch_invalidations: list[tuple[str, str]] = []
+ batch_keys: set[tuple[str, str]] = set()
+ async with app.DATABASE.Session() as session:
+ workflows = (await session.scalars(_non_deleted_workflows_query(offset))).all()
+ if not workflows:
+ break
+
+ workflows_scanned += len(workflows)
+ for workflow in workflows:
+ definition = workflow.workflow_definition
+ if not isinstance(definition, dict) or not _contains_file_block(definition.get("blocks")):
+ continue
+
+ transformed, encrypted_count = await encrypt_file_block_secrets(definition, workflow.organization_id)
+ if encrypted_count == 0:
+ continue
+
+ workflows_changed += 1
+ fields_encrypted += encrypted_count
+ if not args.dry_run:
+ workflow.workflow_definition = transformed
+ flag_modified(workflow, "workflow_definition")
+ session.add(workflow)
+ key = (workflow.organization_id, workflow.workflow_permanent_id)
+ if key not in invalidated and key not in batch_keys:
+ batch_invalidations.append(key)
+ batch_keys.add(key)
+
+ if not args.dry_run:
+ try:
+ # Invalidate cached scripts BEFORE committing the encrypted definitions: if a
+ # delete fails, the batch aborts and a rerun retries both. Committing first
+ # would let a failed invalidation leave stale plaintext that a rerun (seeing an
+ # already-encrypted definition) would never retry.
+ for organization_id, workflow_permanent_id in batch_invalidations:
+ if (organization_id, workflow_permanent_id) in invalidated:
+ continue
+ scripts_invalidated += await app.DATABASE.scripts.delete_workflow_scripts_by_permanent_id(
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ )
+ invalidated.add((organization_id, workflow_permanent_id))
+ await session.commit()
+ except Exception:
+ await session.rollback()
+ LOG.error("Failed to commit file block secret backfill batch", batch_offset=offset)
+ raise RuntimeError("Failed to commit file block secret backfill batch") from None
+
+ offset += len(workflows)
+
+ LOG.info(
+ "File block secret backfill complete",
+ dry_run=args.dry_run,
+ workflows_scanned=workflows_scanned,
+ workflows_changed=workflows_changed,
+ fields_encrypted=fields_encrypted,
+ scripts_invalidated=scripts_invalidated,
+ )
+
+
+if __name__ == "__main__":
+ start_forge_app()
+ asyncio.run(main())
diff --git a/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx b/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
index 350263c1c..964f5b699 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
@@ -38,6 +38,19 @@ const run: TaskRunListItem = {
trigger_type: null,
searchable_text: null,
};
+const secondRun: TaskRunListItem = {
+ ...run,
+ task_run_id: "tr_2",
+ run_id: "wr_2",
+ title: "Second Run",
+};
+const taskRun: TaskRunListItem = {
+ ...run,
+ task_run_id: "tr_3",
+ task_run_type: TaskRunType.TaskV2,
+ run_id: "tsk_1",
+ title: "Task Run",
+};
vi.mock("use-debounce", () => ({
useDebounce: <T,>(value: T): [T] => [value],
@@ -53,7 +66,7 @@ const runsQueryCalls: Array<Record<string, unknown>> = [];
vi.mock("@/hooks/useRunsQuery", () => ({
useRunsQuery: (props: Record<string, unknown>) => {
runsQueryCalls.push(props);
- return { data: [run], isFetching: false };
+ return { data: [run, secondRun, taskRun], isFetching: false };
},
}));
@@ -165,6 +178,57 @@ describe("RunHistory run tags", () => {
within(container).getByTestId("tag-chip-list").textContent,
).toContain("platform_a");
});
+
+ it("selects only workflow runs and supports shift-range bulk actions", () => {
+ render(<RunHistory />, { wrapper });
+
+ const first = screen.getByRole("checkbox", { name: "Select My Run" });
+ const second = screen.getByRole("checkbox", { name: "Select Second Run" });
+ expect(
+ screen.queryByRole("checkbox", { name: "Select Task Run" }),
+ ).toBeNull();
+
+ fireEvent.click(first.parentElement!);
+ fireEvent.click(second.parentElement!, { shiftKey: true });
+
+ expect(
+ screen.getByRole("toolbar", { name: "Bulk actions" }).textContent,
+ ).toContain("2 selected");
+
+ fireEvent.contextMenu(screen.getByRole("row", { name: /tsk_1 Task Run/ }));
+ expect(screen.queryByRole("menu")).toBeNull();
+ });
+
+ it("hides selection when workflow tagging is disabled", () => {
+ flagState.taggingEnabled = false;
+ render(<RunHistory />, { wrapper });
+
+ expect(screen.queryByLabelText(/^Select /)).toBeNull();
+ });
+
+ it("does not restore selection after the tagging flag is toggled", () => {
+ const view = render(<RunHistory />, { wrapper });
+ fireEvent.click(
+ screen.getByRole("checkbox", { name: "Select My Run" }).parentElement!,
+ );
+
+ flagState.taggingEnabled = false;
+ view.rerender(<RunHistory />);
+ flagState.taggingEnabled = true;
+ view.rerender(<RunHistory />);
+
+ expect(screen.queryByRole("toolbar", { name: "Bulk actions" })).toBeNull();
+ });
+
+ it("opens the tag context menu from a workflow-run row", async () => {
+ render(<RunHistory />, { wrapper });
+
+ const row = screen.getByRole("row", { name: /wr_1 My Run/ });
+ fireEvent.contextMenu(row);
+
+ expect(await screen.findByRole("menu")).not.toBeNull();
+ expect(row.hasAttribute("data-row-active")).toBe(true);
+ });
});
describe("RunHistory tag filter control", () => {
diff --git a/skyvern-frontend/src/routes/history/RunHistory.tsx b/skyvern-frontend/src/routes/history/RunHistory.tsx
index 4d1ad0c6c..8c45d9e9a 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.tsx
@@ -86,6 +86,13 @@ import { TagChipList } from "@/routes/workflows/components/tagging/TagChipList";
import { TagFilterControl } from "@/routes/workflows/components/tagging/TagFilterControl";
import { useRunTagFilterParam } from "@/routes/workflows/hooks/useRunTagFilterParam";
import { WORKFLOW_TAGGING_FLAG } from "@/util/featureFlags";
+import {
+ SelectionCheckboxCell,
+ SelectionHeaderCheckboxCell,
+} from "@/components/SelectionCheckbox";
+import { useRowSelection } from "@/hooks/useRowSelection";
+import { RunBulkActionBar } from "@/routes/runs/RunBulkActionBar";
+import { RunRowContextMenu } from "@/routes/runs/RunRowContextMenu";
const statusValues = new Set<string>(Object.values(Status));
function isKnownStatus(value: string): value is Status {
@@ -260,7 +267,13 @@ function RunHistory() {
const isNextDisabled =
isFetching || !nextPageRuns || nextPageRuns.length === 0;
- const runIds = useMemo(() => (runs ?? []).map((r) => r.run_id), [runs]);
+ const runIds = useMemo(
+ () =>
+ (runs ?? [])
+ .filter((run) => run.task_run_type === TaskRunType.WorkflowRun)
+ .map((run) => run.run_id),
+ [runs],
+ );
const { data: runTagsMap = {} } = useRunTagsBatchQuery(runIds, {
enabled: taggingEnabled,
});
@@ -288,6 +301,40 @@ function RunHistory() {
})),
[runTagSuggestions?.keys],
);
+ const selectableRuns = useMemo(
+ () =>
+ taggingEnabled
+ ? (runs ?? []).filter(
+ (run) => run.task_run_type === TaskRunType.WorkflowRun,
+ )
+ : [],
+ [runs, taggingEnabled],
+ );
+ const showCheckbox = selectableRuns.length > 0;
+ const columnCount = showCheckbox ? 7 : 6;
+ const {
+ selectedItems: selectedRuns,
+ isSelected,
+ allSelected,
+ someSelected,
+ indexById: selectableIndexById,
+ handleSelect,
+ toggleSelectAll,
+ clearSelection,
+ } = useRowSelection({
+ items: selectableRuns,
+ getId: (run) => run.run_id,
+ resetKey: JSON.stringify([
+ page,
+ statusFilters,
+ runTypeGroups,
+ tagsParam,
+ workflowPermanentIdFilter,
+ textSearch,
+ taggingEnabled,
+ ]),
+ anchorResetKey: itemsPerPage,
+ });
const { matchesParameter } = useKeywordSearch(debouncedSearch);
const { expandedRows, toggleExpanded: toggleParametersExpanded } =
@@ -326,7 +373,7 @@ function RunHistory() {
if (isFetching) {
return Array.from({ length: 10 }).map((_, index) => (
<TableRow key={`row-${index}`}>
- <TableCell colSpan={6}>
+ <TableCell colSpan={columnCount}>
<Skeleton className="h-4 w-full" />
</TableCell>
</TableRow>
@@ -336,7 +383,7 @@ function RunHistory() {
// Failed to load runs
if (isError) {
return (
- <TableMessageRow colSpan={6}>
+ <TableMessageRow colSpan={columnCount}>
<div className="flex items-center justify-center gap-3">
<span>Failed to load runs.</span>
<Button
@@ -355,7 +402,9 @@ function RunHistory() {
// No runs found
if (runs?.length === 0) {
- return <TableMessageRow colSpan={6}>No runs found</TableMessageRow>;
+ return (
+ <TableMessageRow colSpan={columnCount}>No runs found</TableMessageRow>
+ );
}
return runs?.map((run, index) => {
@@ -368,6 +417,9 @@ function RunHistory() {
const navPath = getRunNavigationPath(run, studioEnabled);
const triggerType = inferTriggerType(run);
const runTags = runTagsMap[run.run_id];
+ const selectableIndex = selectableIndexById.get(run.run_id) ?? -1;
+ const isRowSelected = isSelected(run.run_id);
+ const taggable = taggingEnabled && isWorkflowRun;
const titleContent =
triggerType || run.script_run || run.workflow_deleted ? (
@@ -396,87 +448,118 @@ function RunHistory() {
(run.title ?? "")
);
- return (
- <React.Fragment key={run.task_run_id}>
- <TableRow
- className="cursor-pointer"
- data-hint={index === 0 ? "run-recording" : undefined}
- onClick={(event) => {
- handleNavigate(event, navPath);
- }}
+ const mainRow = (
+ <TableRow
+ className="group/row cursor-pointer select-none"
+ data-state={isRowSelected ? "selected" : undefined}
+ data-hint={index === 0 ? "run-recording" : undefined}
+ onClick={(event) => {
+ handleNavigate(event, navPath);
+ }}
+ >
+ {showCheckbox &&
+ (taggable ? (
+ <SelectionCheckboxCell
+ index={selectableIndex}
+ checked={isRowSelected}
+ hasSelection={selectedRuns.length > 0}
+ onSelect={handleSelect}
+ ariaLabel={`Select ${run.title ?? run.run_id}`}
+ />
+ ) : (
+ <TableCell />
+ ))}
+ <TableCell className="max-w-0 truncate" title={run.run_id}>
+ <HighlightText text={run.run_id} query={textSearch} />
+ </TableCell>
+ <TableCell
+ className="max-w-0 truncate"
+ title={run.title ?? undefined}
>
- <TableCell className="max-w-0 truncate" title={run.run_id}>
- <HighlightText text={run.run_id} query={textSearch} />
- </TableCell>
- <TableCell
- className="max-w-0 truncate"
- title={run.title ?? undefined}
- >
- <div className="flex min-w-0 flex-col gap-1">
- {titleContent}
- {taggingEnabled && runTags && runTags.length > 0 ? (
- <TagChipList
- tags={runTags}
- descriptions={tagDescriptions}
- colors={tagColors}
- maxVisible={2}
- />
- ) : null}
- </div>
- </TableCell>
- <TableCell>
- {isKnownStatus(run.status) ? (
- <StatusBadge status={run.status} />
- ) : (
- <span className="text-sm text-neutral-600 dark:text-slate-400">
- {run.status}
- </span>
- )}
- </TableCell>
- <TableCell
- className="max-w-0 truncate"
- title={basicTimeFormat(run.created_at)}
- >
- {basicLocalTimeFormat(run.created_at)}
- </TableCell>
- <TableCell className="text-neutral-600 dark:text-slate-400">
- {executionTime ?? "-"}
- </TableCell>
- <TableCell>
- {isWorkflowRun ? (
- <div className="flex justify-end">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- size="icon"
- variant="ghost"
- onClick={(event) => {
- event.stopPropagation();
- toggleParametersExpanded(run.run_id);
- }}
- className={cn(
- "text-muted-foreground hover:text-foreground",
- isExpanded && "text-blue-400",
- )}
- >
- <MixerHorizontalIcon className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- {isExpanded ? "Hide Inputs" : "Show Inputs"}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
+ <div className="flex min-w-0 flex-col gap-1">
+ {titleContent}
+ {taggingEnabled && runTags && runTags.length > 0 ? (
+ <TagChipList
+ tags={runTags}
+ descriptions={tagDescriptions}
+ colors={tagColors}
+ maxVisible={2}
+ />
) : null}
- </TableCell>
- </TableRow>
+ </div>
+ </TableCell>
+ <TableCell>
+ {isKnownStatus(run.status) ? (
+ <StatusBadge status={run.status} />
+ ) : (
+ <span className="text-sm text-neutral-600 dark:text-slate-400">
+ {run.status}
+ </span>
+ )}
+ </TableCell>
+ <TableCell
+ className="max-w-0 truncate"
+ title={basicTimeFormat(run.created_at)}
+ >
+ {basicLocalTimeFormat(run.created_at)}
+ </TableCell>
+ <TableCell className="text-neutral-600 dark:text-slate-400">
+ {executionTime ?? "-"}
+ </TableCell>
+ <TableCell>
+ {isWorkflowRun ? (
+ <div className="flex justify-end">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={(event) => {
+ event.stopPropagation();
+ toggleParametersExpanded(run.run_id);
+ }}
+ className={cn(
+ "text-muted-foreground hover:text-foreground",
+ isExpanded && "text-blue-400",
+ )}
+ >
+ <MixerHorizontalIcon className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {isExpanded ? "Hide Inputs" : "Show Inputs"}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ ) : null}
+ </TableCell>
+ </TableRow>
+ );
+ return (
+ <React.Fragment key={run.task_run_id}>
+ {taggable ? (
+ <RunRowContextMenu
+ workflowRunId={run.run_id}
+ runPath={navPath}
+ currentTags={runTags ?? []}
+ tagKeys={tagFilterKeys}
+ labelSuggestions={runTagSuggestions?.labels ?? []}
+ valueSuggestionsByKey={runTagSuggestions?.valuesByKey}
+ selectedCount={selectedRuns.length}
+ onNavigate={navigate}
+ >
+ {mainRow}
+ </RunRowContextMenu>
+ ) : (
+ mainRow
+ )}
{isExpanded && run.workflow_permanent_id && (
<TableRow key={`${run.run_id}-params`}>
<TableCell
- colSpan={6}
+ colSpan={columnCount}
className="bg-slate-50 dark:bg-slate-900/50"
>
<WorkflowRunParametersInline
@@ -616,7 +699,17 @@ function RunHistory() {
<div className="overflow-hidden rounded-lg border border-border">
<Table className="sm:table-fixed">
<TableHeader>
- <TableRow>
+ <TableRow className="group/header">
+ {showCheckbox && (
+ <SelectionHeaderCheckboxCell
+ allSelected={allSelected}
+ someSelected={someSelected}
+ hasSelection={selectedRuns.length > 0}
+ onToggleAll={toggleSelectAll}
+ ariaLabel="Select all workflow runs"
+ className="w-10"
+ />
+ )}
<TableHead className="w-[20%]">Run ID</TableHead>
<TableHead className="w-[20%]">Detail</TableHead>
<TableHead className="w-[16%]">Status</TableHead>
@@ -627,6 +720,16 @@ function RunHistory() {
</TableHeader>
<TableBody>{displayTableBody()}</TableBody>
</Table>
+ {taggingEnabled && selectedRuns.length > 0 ? (
+ <RunBulkActionBar
+ selectedRunIds={selectedRuns.map((run) => run.run_id)}
+ runTagsMap={runTagsMap}
+ tagKeys={tagFilterKeys}
+ labelSuggestions={runTagSuggestions?.labels ?? []}
+ valueSuggestionsByKey={runTagSuggestions?.valuesByKey}
+ onClearSelection={clearSelection}
+ />
+ ) : null}
<div className="relative px-3 py-3">
<div className="absolute left-3 top-1/2 flex -translate-y-1/2 items-center gap-2 text-sm">
<span className="text-neutral-600 dark:text-slate-400">
diff --git a/skyvern-frontend/src/routes/runs/RunBulkActionBar.tsx b/skyvern-frontend/src/routes/runs/RunBulkActionBar.tsx
new file mode 100644
index 000000000..060c2c56e
--- /dev/null
+++ b/skyvern-frontend/src/routes/runs/RunBulkActionBar.tsx
@@ -0,0 +1,170 @@
+import { ChevronDownIcon, TokensIcon } from "@radix-ui/react-icons";
+import { useMemo, useState } from "react";
+
+import { getClient } from "@/api/AxiosClient";
+import { SelectionBar } from "@/components/SelectionBar";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuPortal,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { invalidateRunTagQueries } from "@/routes/tasks/hooks/useRunTagMutations";
+import { TagPickerCommand } from "@/routes/workflows/components/tagging/TagPickerCommand";
+import {
+ isUserWritableTagKey,
+ sortTags,
+ tagElementKey,
+ type Tag,
+ type TagKey,
+} from "@/routes/workflows/types/tagTypes";
+import { bulkResultToast } from "@/util/bulkResultToast";
+import {
+ BULK_CONCURRENCY_LIMIT,
+ runWithConcurrency,
+} from "@/util/runWithConcurrency";
+import { useQueryClient } from "@tanstack/react-query";
+
+type Props = {
+ selectedRunIds: Array<string>;
+ runTagsMap: Record<string, Array<Tag>>;
+ tagKeys: Array<TagKey>;
+ labelSuggestions: Array<string>;
+ valueSuggestionsByKey?: Map<string, Array<string>>;
+ onClearSelection: () => void;
+};
+
+function RunBulkActionBar({
+ selectedRunIds,
+ runTagsMap,
+ tagKeys,
+ labelSuggestions,
+ valueSuggestionsByKey,
+ onClearSelection,
+}: Props) {
+ const credentialGetter = useCredentialGetter();
+ const queryClient = useQueryClient();
+ const [isOperating, setIsOperating] = useState(false);
+ const [tagError, setTagError] = useState<string | null>(null);
+ const currentTags = useMemo(() => {
+ const unique = new Map<string, Tag>();
+ for (const runId of selectedRunIds) {
+ for (const tag of runTagsMap[runId] ?? []) {
+ if (isUserWritableTagKey(tag.key)) {
+ unique.set(tagElementKey(tag), tag);
+ }
+ }
+ }
+ return sortTags([...unique.values()]);
+ }, [runTagsMap, selectedRunIds]);
+
+ async function updateTags(tag: Tag, remove: boolean) {
+ if (isOperating || !isUserWritableTagKey(tag.key)) {
+ return;
+ }
+ const tagKey = tagElementKey(tag);
+ const targetIds = remove
+ ? selectedRunIds.filter((runId) =>
+ (runTagsMap[runId] ?? []).some(
+ (current) => tagElementKey(current) === tagKey,
+ ),
+ )
+ : selectedRunIds;
+ if (targetIds.length === 0) {
+ return;
+ }
+
+ setIsOperating(true);
+ try {
+ const client = await getClient(credentialGetter);
+ const data = remove
+ ? {
+ tags_to_delete: [
+ tag.key !== null ? { key: tag.key } : { value: tag.value },
+ ],
+ }
+ : { tags: [tag] };
+ const results = await runWithConcurrency(
+ targetIds.map(
+ (runId) => () => client.post(`/runs/${runId}/tags`, data),
+ ),
+ BULK_CONCURRENCY_LIMIT,
+ );
+ const succeeded = results.filter(
+ (result) => result.status === "fulfilled",
+ ).length;
+ const label = tag.key !== null ? `${tag.key}: ${tag.value}` : tag.value;
+ bulkResultToast({
+ succeeded,
+ total: targetIds.length,
+ results,
+ successTitle: (count) =>
+ remove
+ ? `Removed ${label} from ${count} run${count === 1 ? "" : "s"}.`
+ : `Tagged ${count} run${count === 1 ? "" : "s"} with ${label}.`,
+ failureTitle: (count) =>
+ `Failed to ${remove ? "remove tags from" : "tag"} ${count} run${count === 1 ? "" : "s"}.`,
+ partialTitle: (successCount, failedCount) =>
+ `${remove ? "Updated" : "Tagged"} ${successCount} run${successCount === 1 ? "" : "s"}. ${failedCount} failed.`,
+ });
+ if (succeeded > 0) {
+ invalidateRunTagQueries(queryClient);
+ }
+ } finally {
+ setIsOperating(false);
+ }
+ }
+
+ return (
+ <SelectionBar
+ count={selectedRunIds.length}
+ isOperating={isOperating}
+ onClear={onClearSelection}
+ >
+ <DropdownMenu
+ onOpenChange={(open) => {
+ if (!open) {
+ setTagError(null);
+ }
+ }}
+ >
+ <DropdownMenuTrigger asChild>
+ <Button size="sm" variant="ghost" disabled={isOperating}>
+ Actions
+ <ChevronDownIcon className="ml-1.5 h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" side="top" className="w-56">
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <TokensIcon className="mr-2 h-4 w-4" />
+ Tags
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent className="w-72 p-0">
+ <TagPickerCommand
+ tagKeys={tagKeys}
+ labelSuggestions={labelSuggestions}
+ valueSuggestionsByKey={valueSuggestionsByKey}
+ currentTags={currentTags}
+ onApply={(tag) => void updateTags(tag, false)}
+ onRemove={(tag) => void updateTags(tag, true)}
+ error={tagError}
+ onErrorChange={setTagError}
+ disabled={isOperating}
+ />
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </SelectionBar>
+ );
+}
+
+export { RunBulkActionBar };
diff --git a/skyvern-frontend/src/routes/runs/RunRowContextMenu.tsx b/skyvern-frontend/src/routes/runs/RunRowContextMenu.tsx
new file mode 100644
index 000000000..2ef513839
--- /dev/null
+++ b/skyvern-frontend/src/routes/runs/RunRowContextMenu.tsx
@@ -0,0 +1,101 @@
+import { OpenInNewWindowIcon, TokensIcon } from "@radix-ui/react-icons";
+import {
+ Children,
+ cloneElement,
+ type ReactElement,
+ type ReactNode,
+ useState,
+} from "react";
+
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuLabel,
+ ContextMenuSeparator,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+ ContextMenuTrigger,
+} from "@/components/ui/context-menu";
+import { RunTagPickerCommand } from "@/routes/tasks/components/tagging/RunTagPickerCommand";
+import type { Tag, TagKey } from "@/routes/workflows/types/tagTypes";
+import { cn } from "@/util/utils";
+
+type Props = {
+ workflowRunId: string;
+ runPath: string;
+ currentTags: Array<Tag>;
+ tagKeys: Array<TagKey>;
+ labelSuggestions: Array<string>;
+ valueSuggestionsByKey?: Map<string, Array<string>>;
+ selectedCount?: number;
+ onNavigate: (path: string) => void;
+ children: ReactNode;
+};
+
+function RunRowContextMenu({
+ workflowRunId,
+ runPath,
+ currentTags,
+ tagKeys,
+ labelSuggestions,
+ valueSuggestionsByKey,
+ selectedCount = 0,
+ onNavigate,
+ children,
+}: Props) {
+ const child = Children.only(children) as ReactElement<{
+ className?: string;
+ "data-row-active"?: string;
+ }>;
+ const isMultiSelect = selectedCount > 1;
+ const [menuOpen, setMenuOpen] = useState(false);
+
+ return (
+ <ContextMenu onOpenChange={setMenuOpen}>
+ <ContextMenuTrigger asChild>
+ {cloneElement(child, {
+ className: cn(child.props.className, "data-[row-active]:bg-muted/50"),
+ "data-row-active": menuOpen ? "" : undefined,
+ })}
+ </ContextMenuTrigger>
+ <ContextMenuContent className="w-56">
+ {isMultiSelect ? (
+ <>
+ <ContextMenuLabel className="text-xs font-normal text-muted-foreground">
+ Acts on this run only — use the Actions bar for all{" "}
+ {selectedCount}.
+ </ContextMenuLabel>
+ <ContextMenuSeparator />
+ </>
+ ) : (
+ <>
+ <ContextMenuItem onSelect={() => onNavigate(runPath)}>
+ <OpenInNewWindowIcon className="mr-2 h-4 w-4" />
+ Open run
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ </>
+ )}
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>
+ <TokensIcon className="mr-2 h-4 w-4" />
+ Tags
+ </ContextMenuSubTrigger>
+ <ContextMenuSubContent className="w-72 p-0">
+ <RunTagPickerCommand
+ workflowRunId={workflowRunId}
+ tagKeys={tagKeys}
+ labelSuggestions={labelSuggestions}
+ valueSuggestionsByKey={valueSuggestionsByKey}
+ currentTags={currentTags}
+ />
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+ </ContextMenuContent>
+ </ContextMenu>
+ );
+}
+
+export { RunRowContextMenu };
diff --git a/skyvern-frontend/src/routes/runs/RunTagActions.test.tsx b/skyvern-frontend/src/routes/runs/RunTagActions.test.tsx
new file mode 100644
index 000000000..8554f0602
--- /dev/null
+++ b/skyvern-frontend/src/routes/runs/RunTagActions.test.tsx
@@ -0,0 +1,180 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ post: vi.fn(),
+ mutate: vi.fn(),
+}));
+
+vi.mock("@/components/ui/dropdown-menu", () => {
+ const Pass = ({ children }: { children: ReactNode }) => <>{children}</>;
+ return {
+ DropdownMenu: Pass,
+ DropdownMenuContent: Pass,
+ DropdownMenuPortal: Pass,
+ DropdownMenuSub: Pass,
+ DropdownMenuSubContent: Pass,
+ DropdownMenuSubTrigger: Pass,
+ DropdownMenuTrigger: Pass,
+ };
+});
+
+vi.mock("@/components/ui/context-menu", () => {
+ const Pass = ({ children }: { children: ReactNode }) => <>{children}</>;
+ return {
+ ContextMenu: Pass,
+ ContextMenuContent: Pass,
+ ContextMenuItem: ({
+ children,
+ onSelect,
+ }: {
+ children: ReactNode;
+ onSelect?: () => void;
+ }) => <button onClick={onSelect}>{children}</button>,
+ ContextMenuLabel: Pass,
+ ContextMenuSeparator: () => null,
+ ContextMenuSub: Pass,
+ ContextMenuSubContent: Pass,
+ ContextMenuSubTrigger: Pass,
+ ContextMenuTrigger: Pass,
+ };
+});
+
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => vi.fn(),
+}));
+
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: async () => ({ post: mocks.post }),
+}));
+
+vi.mock("@/routes/tasks/hooks/useRunTagMutations", () => ({
+ invalidateRunTagQueries: vi.fn(),
+ useApplyRunTagsMutation: () => ({
+ mutate: mocks.mutate,
+ isPending: false,
+ }),
+}));
+
+vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));
+
+import { RunBulkActionBar } from "./RunBulkActionBar";
+import { RunRowContextMenu } from "./RunRowContextMenu";
+
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+vi.stubGlobal("ResizeObserver", MockResizeObserver);
+Element.prototype.scrollIntoView = () => {};
+
+function wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={new QueryClient()}>
+ {children}
+ </QueryClientProvider>
+ );
+}
+
+const runTagsMap = {
+ wr_1: [
+ { key: "env", value: "prod" },
+ { key: "skyvern.platform", value: "browser" },
+ ],
+ wr_2: [
+ { key: "env", value: "staging" },
+ { key: null, value: "urgent" },
+ ],
+};
+
+afterEach(() => {
+ vi.clearAllMocks();
+ mocks.post.mockResolvedValue({ data: {} });
+});
+
+describe("RunBulkActionBar", () => {
+ it("adds to every selected run and removes only exact-tag matches", async () => {
+ render(
+ <RunBulkActionBar
+ selectedRunIds={["wr_1", "wr_2"]}
+ runTagsMap={runTagsMap}
+ tagKeys={[]}
+ labelSuggestions={["urgent", "reviewed"]}
+ onClearSelection={vi.fn()}
+ />,
+ { wrapper },
+ );
+
+ fireEvent.click(screen.getAllByRole("option", { name: "urgent" })[0]!);
+ await waitFor(() =>
+ expect(mocks.post).toHaveBeenCalledWith("/runs/wr_2/tags", {
+ tags_to_delete: [{ value: "urgent" }],
+ }),
+ );
+ expect(mocks.post).toHaveBeenCalledTimes(1);
+
+ fireEvent.change(screen.getByPlaceholderText(/label or group/i), {
+ target: { value: "reviewed" },
+ });
+ fireEvent.click(screen.getByRole("option", { name: /Add reviewed/i }));
+ await waitFor(() => expect(mocks.post).toHaveBeenCalledTimes(3));
+ expect(mocks.post).toHaveBeenCalledWith("/runs/wr_1/tags", {
+ tags: [{ key: null, value: "reviewed" }],
+ });
+ expect(mocks.post).toHaveBeenCalledWith("/runs/wr_2/tags", {
+ tags: [{ key: null, value: "reviewed" }],
+ });
+ });
+
+ it("does not expose reserved tags for bulk removal", () => {
+ render(
+ <RunBulkActionBar
+ selectedRunIds={["wr_1", "wr_2"]}
+ runTagsMap={runTagsMap}
+ tagKeys={[]}
+ labelSuggestions={[]}
+ onClearSelection={vi.fn()}
+ />,
+ { wrapper },
+ );
+
+ expect(screen.queryByText(/skyvern\.platform/)).toBeNull();
+ });
+});
+
+describe("RunRowContextMenu", () => {
+ it("manages the clicked run and warns when a bulk selection is active", () => {
+ const onNavigate = vi.fn();
+ render(
+ <RunRowContextMenu
+ workflowRunId="wr_1"
+ runPath="/runs/wr_1"
+ currentTags={runTagsMap.wr_1}
+ tagKeys={[]}
+ labelSuggestions={[]}
+ selectedCount={2}
+ onNavigate={onNavigate}
+ >
+ <div>Run row</div>
+ </RunRowContextMenu>,
+ );
+
+ expect(screen.getByText(/Acts on this run only/)).toBeTruthy();
+ fireEvent.click(screen.getByText("env: prod"));
+
+ expect(mocks.mutate).toHaveBeenCalledWith(
+ {
+ workflowRunId: "wr_1",
+ data: { tags_to_delete: [{ key: "env" }] },
+ },
+ expect.any(Object),
+ );
+ expect(screen.queryByText(/skyvern\.platform/)).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/routes/schedules/CreateOrgScheduleDialog.tsx b/skyvern-frontend/src/routes/schedules/CreateOrgScheduleDialog.tsx
index 301491974..18889325d 100644
--- a/skyvern-frontend/src/routes/schedules/CreateOrgScheduleDialog.tsx
+++ b/skyvern-frontend/src/routes/schedules/CreateOrgScheduleDialog.tsx
@@ -19,17 +19,12 @@ import type {
Parameter,
} from "@/routes/workflows/types/workflowTypes";
import {
- CRON_PRESETS,
- cronToHumanReadable,
- formatNextRun,
getLocalTimezone,
- getNextRuns,
- getTimezones,
isValidCron,
meetsMinCronInterval,
} from "@/routes/workflows/editor/panels/schedulePanel/cronUtils";
-import { cn } from "@/util/utils";
import { useWorkflowQuery } from "@/routes/workflows/hooks/useWorkflowQuery";
+import { ScheduleConfigFields } from "@/routes/workflows/components/ScheduleConfigFields";
import { ScheduleParametersSection } from "@/routes/workflows/components/ScheduleParametersSection";
import { buildScheduleParametersPayload } from "@/routes/workflows/components/scheduleParameters";
import { useScheduleParameterState } from "@/routes/workflows/hooks/useScheduleParameterState";
@@ -51,13 +46,10 @@ function CreateOrgScheduleDialog({ open, onOpenChange }: Readonly<Props>) {
useState<WorkflowApiResponse | null>(null);
const [cronExpression, setCronExpression] = useState("0 9 * * *");
const [timezone, setTimezone] = useState(getLocalTimezone);
- const [timezoneFilter, setTimezoneFilter] = useState<string | null>(null);
const [scheduleName, setScheduleName] = useState("");
const [scheduleDescription, setScheduleDescription] = useState("");
- const allTimezones = useMemo(() => getTimezones(), []);
-
const { data: workflows = [] } = useQuery<Array<WorkflowApiResponse>>({
queryKey: ["workflows", "scheduleDialogPicker", workflowSearch],
queryFn: async () => {
@@ -127,18 +119,8 @@ function CreateOrgScheduleDialog({ open, onOpenChange }: Readonly<Props>) {
}
}, [selectedWorkflowId, workflowParameters, resetParameters]);
- const filteredTimezones = useMemo(() => {
- if (timezoneFilter === null) return allTimezones;
- if (!timezoneFilter) return allTimezones;
- const lower = timezoneFilter.toLowerCase();
- return allTimezones.filter((tz) => tz.toLowerCase().includes(lower));
- }, [timezoneFilter, allTimezones]);
-
const valid = isValidCron(cronExpression);
- const intervalTooShort = valid && !meetsMinCronInterval(cronExpression);
- const cronAccepted = valid && !intervalTooShort;
- const humanReadable = valid ? cronToHumanReadable(cronExpression) : null;
- const nextRuns = valid ? getNextRuns(cronExpression, timezone, 5) : [];
+ const cronAccepted = valid && meetsMinCronInterval(cronExpression);
function resetForm() {
setWorkflowSearch("");
@@ -146,7 +128,6 @@ function CreateOrgScheduleDialog({ open, onOpenChange }: Readonly<Props>) {
setSelectedWorkflow(null);
setCronExpression("0 9 * * *");
setTimezone(getLocalTimezone());
- setTimezoneFilter(null);
setScheduleName("");
setScheduleDescription("");
clearParameters();
@@ -275,116 +256,13 @@ function CreateOrgScheduleDialog({ open, onOpenChange }: Readonly<Props>) {
disabled={createMutation.isPending}
/>
- {/* Cron Presets */}
- <div className="space-y-2">
- <Label>Quick Presets</Label>
- <div className="flex flex-wrap gap-2">
- {CRON_PRESETS.map((preset) => (
- <Button
- key={preset.label}
- variant={
- cronExpression === preset.expression
- ? "default"
- : "secondary"
- }
- size="sm"
- onClick={() => setCronExpression(preset.expression)}
- >
- {preset.label}
- </Button>
- ))}
- </div>
- </div>
-
- {/* Custom Cron Input */}
- <div className="space-y-2">
- <Label>Cron Expression</Label>
- <Input
- value={cronExpression}
- onChange={(e) => setCronExpression(e.target.value)}
- placeholder="* * * * *"
- className={cn(
- cronExpression && !cronAccepted && "border-destructive",
- )}
- />
- {humanReadable && (
- <p className="text-sm text-slate-400">{humanReadable}</p>
- )}
- {!valid && cronExpression && (
- <p className="text-sm text-destructive">
- Invalid cron expression
- </p>
- )}
- {intervalTooShort && (
- <p className="text-sm text-destructive">
- Schedule runs must be at least 5 minutes apart.
- </p>
- )}
- </div>
-
- {/* Timezone Selector */}
- <div className="space-y-2">
- <Label>Timezone</Label>
- <Input
- value={timezoneFilter ?? timezone}
- onChange={(e) => setTimezoneFilter(e.target.value)}
- onFocus={(e) => e.currentTarget.select()}
- onBlur={() => {
- if (
- filteredTimezones.length === 1 &&
- filteredTimezones[0] !== undefined
- ) {
- setTimezone(filteredTimezones[0]);
- }
- setTimezoneFilter(null);
- }}
- placeholder="Search timezones..."
- />
- {timezoneFilter !== null && (
- <div className="max-h-40 overflow-y-auto rounded-md border border-slate-700 bg-slate-elevation3">
- {filteredTimezones.slice(0, 20).map((tz) => (
- <button
- key={tz}
- type="button"
- className={cn(
- "w-full px-3 py-1.5 text-left text-sm hover:bg-slate-700",
- tz === timezone && "bg-slate-700 text-slate-50",
- )}
- onMouseDown={(e) => {
- e.preventDefault();
- setTimezone(tz);
- setTimezoneFilter(null);
- }}
- >
- {tz}
- </button>
- ))}
- {filteredTimezones.length === 0 && (
- <div className="px-3 py-2 text-sm text-slate-500">
- No timezones found
- </div>
- )}
- </div>
- )}
- <p className="text-xs text-slate-500">Current: {timezone}</p>
- </div>
-
- {/* Next Runs Preview */}
- {nextRuns.length > 0 && (
- <div className="space-y-2">
- <Label>Next Scheduled Runs</Label>
- <div className="space-y-1 rounded-md border border-slate-700 bg-slate-elevation3 p-3">
- {nextRuns.map((run) => (
- <div
- key={run.toISOString()}
- className="text-xs text-slate-400"
- >
- {formatNextRun(run, timezone)}
- </div>
- ))}
- </div>
- </div>
- )}
+ <ScheduleConfigFields
+ cronExpression={cronExpression}
+ timezone={timezone}
+ onCronChange={setCronExpression}
+ onTimezoneChange={setTimezone}
+ disabled={createMutation.isPending}
+ />
</div>
<DialogFooter>
diff --git a/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsx b/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsx
index e9dd13fe1..f12fb7011 100644
--- a/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsx
+++ b/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsx
@@ -27,17 +27,14 @@ import {
useUpdateScheduleMutation,
} from "./useScheduleActions";
import {
- CRON_PRESETS,
cronToHumanReadable,
formatNextRun,
- getNextRuns,
- getTimezones,
isValidCron,
meetsMinCronInterval,
} from "@/routes/workflows/editor/panels/schedulePanel/cronUtils";
-import { cn } from "@/util/utils";
import { getErrorDetail } from "@/util/getErrorDetail";
import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";
+import { ScheduleConfigFields } from "@/routes/workflows/components/ScheduleConfigFields";
import { ScheduleParametersSection } from "@/routes/workflows/components/ScheduleParametersSection";
import {
buildScheduleParametersPayload,
@@ -48,8 +45,6 @@ import {
import { useScheduleParameterState } from "@/routes/workflows/hooks/useScheduleParameterState";
import type { Parameter } from "@/routes/workflows/types/workflowTypes";
-const allTimezones = getTimezones();
-
function ScheduleDetailPage() {
const navigate = useNavigate();
const location = useLocation();
@@ -78,9 +73,6 @@ function ScheduleDetailPage() {
const [editing, setEditing] = useState(false);
const [editCron, setEditCron] = useState("");
const [editTimezone, setEditTimezone] = useState("");
- // TODO - Create shared util
- const [timezoneFilter, setTimezoneFilter] = useState<string | null>(null);
-
const [editName, setEditName] = useState("");
const [editDescription, setEditDescription] = useState("");
@@ -99,19 +91,9 @@ function ScheduleDetailPage() {
data?.schedule.parameters ?? null,
);
- const filteredTimezones = useMemo(() => {
- if (timezoneFilter === null) return allTimezones;
- if (!timezoneFilter) return allTimezones;
- const lower = timezoneFilter.toLowerCase();
- return allTimezones.filter((tz) => tz.toLowerCase().includes(lower));
- }, [timezoneFilter]);
- // ! end TODO
-
const editValid = isValidCron(editCron);
const editIntervalTooShort = editValid && !meetsMinCronInterval(editCron);
const editCronAccepted = editValid && !editIntervalTooShort;
- const editHumanReadable = editValid ? cronToHumanReadable(editCron) : null;
- const editNextRuns = editValid ? getNextRuns(editCron, editTimezone, 5) : [];
if (isLoading) {
return (
@@ -142,7 +124,6 @@ function ScheduleDetailPage() {
function startEditing() {
setEditCron(schedule.cron_expression);
setEditTimezone(schedule.timezone);
- setTimezoneFilter(null);
setEditName(schedule.name ?? "");
setEditDescription(schedule.description ?? "");
resetParameters();
@@ -151,7 +132,6 @@ function ScheduleDetailPage() {
function cancelEditing() {
setEditing(false);
- setTimezoneFilter(null);
// Drop any in-progress parameter edits so they don't reappear on
// re-entry; re-seed from the stored schedule values.
resetParameters();
@@ -329,119 +309,14 @@ function ScheduleDetailPage() {
disabled={updateMutation.isPending}
/>
- {/* Cron Presets */}
- <div className="space-y-2">
- <Label className="text-xs">Quick Presets</Label>
- <div className="flex flex-wrap gap-1.5">
- {CRON_PRESETS.map((preset) => (
- <Button
- key={preset.label}
- variant={
- editCron === preset.expression ? "default" : "secondary"
- }
- size="sm"
- className="h-6 text-xs"
- onClick={() => setEditCron(preset.expression)}
- >
- {preset.label}
- </Button>
- ))}
- </div>
- </div>
-
- {/* Cron Expression */}
- <div className="space-y-1.5">
- <Label className="text-xs">Cron Expression</Label>
- <Input
- value={editCron}
- onChange={(e) => setEditCron(e.target.value)}
- placeholder="* * * * *"
- className={cn(
- "h-8 text-sm",
- editCron && !editCronAccepted && "border-destructive",
- )}
- />
- {editHumanReadable && (
- <p className="text-xs text-slate-400">{editHumanReadable}</p>
- )}
- {!editValid && editCron && (
- <p className="text-xs text-destructive">
- Invalid cron expression
- </p>
- )}
- {editIntervalTooShort && (
- <p className="text-xs text-destructive">
- Schedule runs must be at least 5 minutes apart.
- </p>
- )}
- </div>
-
- {/* Timezone */}
- <div className="space-y-1.5">
- <Label className="text-xs">Timezone</Label>
- <Input
- value={timezoneFilter ?? editTimezone}
- onChange={(e) => setTimezoneFilter(e.target.value)}
- onFocus={(e) => e.currentTarget.select()}
- onBlur={() => {
- if (
- filteredTimezones.length === 1 &&
- filteredTimezones[0] !== undefined
- ) {
- setEditTimezone(filteredTimezones[0]);
- }
- setTimezoneFilter(null);
- }}
- placeholder="Search timezones..."
- className="h-8 text-sm"
- />
- {timezoneFilter !== null && (
- <div className="max-h-32 overflow-y-auto rounded-md border border-slate-700 bg-slate-elevation3">
- {filteredTimezones.slice(0, 15).map((tz) => (
- <button
- key={tz}
- type="button"
- className={cn(
- "w-full px-3 py-1 text-left text-xs hover:bg-slate-700",
- tz === editTimezone && "bg-slate-700 text-slate-50",
- )}
- onMouseDown={(e) => {
- e.preventDefault();
- setEditTimezone(tz);
- setTimezoneFilter(null);
- }}
- >
- {tz}
- </button>
- ))}
- {filteredTimezones.length === 0 && (
- <div className="px-3 py-1.5 text-xs text-slate-500">
- No timezones found
- </div>
- )}
- </div>
- )}
- <p className="text-xs text-slate-500">
- Current: {editTimezone}
- </p>
- </div>
-
- {/* Preview next runs */}
- {editNextRuns.length > 0 && (
- <div className="space-y-1">
- <Label className="text-xs">Next Runs Preview</Label>
- <div className="space-y-0.5">
- {editNextRuns.map((run) => (
- <p
- key={run.toISOString()}
- className="text-xs text-slate-500"
- >
- {formatNextRun(run, editTimezone)}
- </p>
- ))}
- </div>
- </div>
- )}
+ <ScheduleConfigFields
+ size="compact"
+ cronExpression={editCron}
+ timezone={editTimezone}
+ onCronChange={setEditCron}
+ onTimezoneChange={setEditTimezone}
+ disabled={updateMutation.isPending}
+ />
{/* Save / Cancel */}
<div className="flex gap-2 pt-1">
diff --git a/skyvern-frontend/src/routes/tasks/components/tagging/RunTagsEditor.test.tsx b/skyvern-frontend/src/routes/tasks/components/tagging/RunTagsEditor.test.tsx
new file mode 100644
index 000000000..98eebb847
--- /dev/null
+++ b/skyvern-frontend/src/routes/tasks/components/tagging/RunTagsEditor.test.tsx
@@ -0,0 +1,114 @@
+// @vitest-environment jsdom
+
+import { fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ taggingEnabled: true,
+ mutate: vi.fn(),
+}));
+
+vi.mock("@/hooks/useFeatureFlag", () => ({
+ useFeatureFlag: () => state.taggingEnabled,
+}));
+
+vi.mock("../../hooks/useRunTagsQuery", () => ({
+ useRunTagsQuery: () => ({
+ data: [
+ { key: "env", value: "prod" },
+ { key: "skyvern.platform", value: "browser" },
+ ],
+ }),
+}));
+
+vi.mock("../../hooks/useRunTagSuggestionsQuery", () => ({
+ useRunTagSuggestionsQuery: () => ({
+ data: {
+ keys: ["env", "skyvern.platform"],
+ valuesByKey: new Map([
+ ["env", ["prod", "staging"]],
+ ["skyvern.platform", ["browser"]],
+ ]),
+ labels: ["urgent"],
+ },
+ }),
+}));
+
+vi.mock("../../hooks/useRunTagMutations", () => ({
+ useApplyRunTagsMutation: () => ({
+ mutate: state.mutate,
+ isPending: false,
+ }),
+}));
+
+vi.mock("@/routes/workflows/hooks/useTagKeysQuery", () => ({
+ useTagKeysQuery: () => ({
+ data: [{ key: "env", description: "Environment", workflow_count: 1 }],
+ }),
+}));
+
+vi.mock("@/routes/workflows/hooks/useTagValuesQuery", () => ({
+ useTagValuesQuery: () => ({ data: new Map() }),
+}));
+
+import { RunTagsEditor } from "./RunTagsEditor";
+
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+vi.stubGlobal("ResizeObserver", MockResizeObserver);
+Element.prototype.scrollIntoView = () => {};
+
+afterEach(() => {
+ state.taggingEnabled = true;
+ vi.clearAllMocks();
+});
+
+describe("RunTagsEditor", () => {
+ it("shows system tags without removal and removes user tags from their chips", () => {
+ render(<RunTagsEditor workflowRunId="wr_1" />);
+
+ expect(screen.getByText("browser")).toBeTruthy();
+ expect(
+ screen.queryByRole("button", {
+ name: "Remove skyvern.platform: browser",
+ }),
+ ).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: "Remove env: prod" }));
+
+ expect(state.mutate).toHaveBeenCalledWith({
+ workflowRunId: "wr_1",
+ data: { tags_to_delete: [{ key: "env" }] },
+ });
+ });
+
+ it("uses run suggestions for new tags", () => {
+ render(<RunTagsEditor workflowRunId="wr_1" />);
+
+ fireEvent.click(screen.getByRole("button", { name: "Manage tags" }));
+ fireEvent.change(screen.getByPlaceholderText(/label or group/i), {
+ target: { value: "urgent" },
+ });
+ fireEvent.click(screen.getByRole("option", { name: /Add urgent/i }));
+
+ expect(state.mutate).toHaveBeenCalledWith(
+ {
+ workflowRunId: "wr_1",
+ data: { tags: [{ key: null, value: "urgent" }] },
+ },
+ expect.any(Object),
+ );
+ });
+
+ it("renders nothing when workflow tagging is disabled", () => {
+ state.taggingEnabled = false;
+
+ const { container } = render(<RunTagsEditor workflowRunId="wr_1" />);
+
+ expect(container.textContent).toBe("");
+ });
+});
diff --git a/skyvern-frontend/src/routes/tasks/components/tagging/RunTagsEditor.tsx b/skyvern-frontend/src/routes/tasks/components/tagging/RunTagsEditor.tsx
new file mode 100644
index 000000000..b0b6500aa
--- /dev/null
+++ b/skyvern-frontend/src/routes/tasks/components/tagging/RunTagsEditor.tsx
@@ -0,0 +1,109 @@
+import { TokensIcon } from "@radix-ui/react-icons";
+import { useMemo } from "react";
+
+import { Button } from "@/components/ui/button";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { useFeatureFlag } from "@/hooks/useFeatureFlag";
+import { TagChipList } from "@/routes/workflows/components/tagging/TagChipList";
+import { useTagKeysQuery } from "@/routes/workflows/hooks/useTagKeysQuery";
+import { useTagValuesQuery } from "@/routes/workflows/hooks/useTagValuesQuery";
+import {
+ isUserWritableTagKey,
+ type Tag,
+} from "@/routes/workflows/types/tagTypes";
+import { WORKFLOW_TAGGING_FLAG } from "@/util/featureFlags";
+import { cn } from "@/util/utils";
+import { useApplyRunTagsMutation } from "../../hooks/useRunTagMutations";
+import { useRunTagSuggestionsQuery } from "../../hooks/useRunTagSuggestionsQuery";
+import { useRunTagsQuery } from "../../hooks/useRunTagsQuery";
+import { RunTagPickerCommand } from "./RunTagPickerCommand";
+
+type Props = {
+ workflowRunId: string | null | undefined;
+ className?: string;
+};
+
+function RunTagsEditor({ workflowRunId, className }: Props) {
+ const taggingEnabled = useFeatureFlag(WORKFLOW_TAGGING_FLAG) !== false;
+ const { data: runTags = [] } = useRunTagsQuery(workflowRunId, {
+ enabled: taggingEnabled,
+ });
+ const { data: tagKeys = [] } = useTagKeysQuery({ enabled: taggingEnabled });
+ const { data: tagColors } = useTagValuesQuery({ enabled: taggingEnabled });
+ const { data: suggestions } = useRunTagSuggestionsQuery({
+ enabled: taggingEnabled,
+ });
+ const applyRunTagsMutation = useApplyRunTagsMutation();
+ const tagDescriptions = useMemo(
+ () =>
+ new Map(
+ tagKeys.map((tagKey): [string, string | null] => [
+ tagKey.key,
+ tagKey.description,
+ ]),
+ ),
+ [tagKeys],
+ );
+ const suggestionKeys = useMemo(
+ () =>
+ (suggestions?.keys ?? []).map((key) => ({
+ key,
+ description: null,
+ workflow_count: 0,
+ })),
+ [suggestions?.keys],
+ );
+
+ if (!taggingEnabled || !workflowRunId) {
+ return null;
+ }
+
+ function removeTag(tag: Tag) {
+ if (!workflowRunId || !isUserWritableTagKey(tag.key)) {
+ return;
+ }
+ applyRunTagsMutation.mutate({
+ workflowRunId,
+ data: {
+ tags_to_delete: [
+ tag.key !== null ? { key: tag.key } : { value: tag.value },
+ ],
+ },
+ });
+ }
+
+ return (
+ <div className={cn("flex flex-wrap items-center gap-2", className)}>
+ <TagChipList
+ tags={runTags}
+ descriptions={tagDescriptions}
+ colors={tagColors}
+ maxVisible={20}
+ onRemove={removeTag}
+ />
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button size="sm" variant="secondary" aria-label="Manage tags">
+ <TokensIcon className="mr-2 h-4 w-4" />
+ Tags
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-72 p-0" align="start">
+ <RunTagPickerCommand
+ workflowRunId={workflowRunId}
+ tagKeys={suggestionKeys}
+ labelSuggestions={suggestions?.labels ?? []}
+ valueSuggestionsByKey={suggestions?.valuesByKey}
+ currentTags={runTags}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ );
+}
+
+export { RunTagsEditor };
diff --git a/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx b/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx
index 639fe85fa..f653870fa 100644
--- a/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx
+++ b/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx
@@ -1,6 +1,6 @@
import { AxiosError } from "axios";
import { getClient } from "@/api/AxiosClient";
-import { useMemo, useState } from "react";
+import { useState } from "react";
import {
RunEngine,
Status,
@@ -12,11 +12,6 @@ import { Status404 } from "@/components/Status404";
import { StatusBadge } from "@/components/StatusBadge";
import { SwitchBarNavigation } from "@/components/SwitchBarNavigation";
import { Button } from "@/components/ui/button";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover";
import {
Dialog,
DialogClose,
@@ -32,17 +27,13 @@ import { Skeleton } from "@/components/ui/skeleton";
import { toast } from "@/components/ui/use-toast";
import { useApiCredential } from "@/hooks/useApiCredential";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
-import { useFeatureFlag } from "@/hooks/useFeatureFlag";
import { CodeEditor } from "@/routes/workflows/components/CodeEditor";
-import { TagChipList } from "@/routes/workflows/components/tagging/TagChipList";
-import { useTagKeysQuery } from "@/routes/workflows/hooks/useTagKeysQuery";
-import { useTagValuesQuery } from "@/routes/workflows/hooks/useTagValuesQuery";
import { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";
import { ApiWebhookActionsMenu } from "@/components/ApiWebhookActionsMenu";
import { WebhookReplayDialog } from "@/components/WebhookReplayDialog";
import { type ApiCommandOptions } from "@/util/apiCommands";
import { buildTaskRunPayload } from "@/util/taskRunPayload";
-import { PlayIcon, ReloadIcon, TokensIcon } from "@radix-ui/react-icons";
+import { PlayIcon, ReloadIcon } from "@radix-ui/react-icons";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Link, Outlet } from "react-router-dom";
import { statusIsFinalized } from "../types";
@@ -51,11 +42,7 @@ import { useTaskQuery } from "./hooks/useTaskQuery";
import { useFirstParam } from "@/hooks/useFirstParam";
import * as env from "@/util/env";
import { TaskRunVerificationCodeForm } from "./TaskRunVerificationCodeForm";
-import { WORKFLOW_TAGGING_FLAG } from "@/util/featureFlags";
-import { useRunTagsQuery } from "../hooks/useRunTagsQuery";
-import { RunTagPickerCommand } from "../components/tagging/RunTagPickerCommand";
-
-const EMPTY_LABEL_SUGGESTIONS: Array<string> = [];
+import { RunTagsEditor } from "../components/tagging/RunTagsEditor";
function createTaskRequestObject(values: TaskApiResponse) {
return {
@@ -75,7 +62,6 @@ function TaskDetails() {
const credentialGetter = useCredentialGetter();
const queryClient = useQueryClient();
const apiCredential = useApiCredential();
- const taggingEnabled = useFeatureFlag(WORKFLOW_TAGGING_FLAG) !== false;
const {
data: task,
@@ -111,21 +97,6 @@ function TaskDetails() {
});
const workflowRunId = task?.workflow_run_id ?? null;
- const { data: runTags = [] } = useRunTagsQuery(workflowRunId, {
- enabled: taggingEnabled,
- });
- const { data: tagKeys = [] } = useTagKeysQuery({ enabled: taggingEnabled });
- const tagDescriptions = useMemo(
- () =>
- new Map(
- tagKeys.map((tagKey): [string, string | null] => [
- tagKey.key,
- tagKey.description,
- ]),
- ),
- [tagKeys],
- );
- const { data: tagColors } = useTagValuesQuery({ enabled: taggingEnabled });
const cancelTaskMutation = useMutation({
mutationFn: async () => {
@@ -248,35 +219,12 @@ function TaskDetails() {
task && <StatusBadge status={task.status} />
)}
</div>
- {taggingEnabled && runTags.length > 0 ? (
- <TagChipList
- tags={runTags}
- descriptions={tagDescriptions}
- colors={tagColors}
- maxVisible={6}
- />
+ {workflowRunId ? (
+ <RunTagsEditor workflowRunId={workflowRunId} />
) : null}
</div>
</div>
<div className="flex items-center gap-2">
- {taggingEnabled && workflowRunId ? (
- <Popover>
- <PopoverTrigger asChild>
- <Button variant="secondary">
- <TokensIcon className="mr-2 h-4 w-4" />
- Tags
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-72 p-0" align="end">
- <RunTagPickerCommand
- workflowRunId={workflowRunId}
- tagKeys={tagKeys}
- labelSuggestions={EMPTY_LABEL_SUGGESTIONS}
- currentTags={runTags}
- />
- </PopoverContent>
- </Popover>
- ) : null}
{/** API & Webhooks consolidated dropdown + controlled dialog */}
<ApiWebhookActionsMenu
getOptions={() => {
diff --git a/skyvern-frontend/src/routes/tasks/hooks/useRunTagMutations.test.tsx b/skyvern-frontend/src/routes/tasks/hooks/useRunTagMutations.test.tsx
index c8bc2ce9e..36f830051 100644
--- a/skyvern-frontend/src/routes/tasks/hooks/useRunTagMutations.test.tsx
+++ b/skyvern-frontend/src/routes/tasks/hooks/useRunTagMutations.test.tsx
@@ -75,5 +75,11 @@ describe("useRunTagMutations", () => {
});
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["runs"] });
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["tasks"] });
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ["workflowRuns"],
+ });
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ["run-tag-suggestions"],
+ });
});
});
diff --git a/skyvern-frontend/src/routes/tasks/hooks/useRunTagMutations.ts b/skyvern-frontend/src/routes/tasks/hooks/useRunTagMutations.ts
index 8e5f6373f..d611684df 100644
--- a/skyvern-frontend/src/routes/tasks/hooks/useRunTagMutations.ts
+++ b/skyvern-frontend/src/routes/tasks/hooks/useRunTagMutations.ts
@@ -6,7 +6,27 @@ import type {
RunTagsResponse,
TagApplyRequest,
} from "@/routes/workflows/types/tagTypes";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
+import {
+ type QueryClient,
+ useMutation,
+ useQueryClient,
+} from "@tanstack/react-query";
+
+const RUN_TAG_QUERY_KEYS = [
+ ["run-tags"],
+ ["run-tag-suggestions"],
+ ["tag-keys"],
+ ["tag-values"],
+ ["runs"],
+ ["workflowRuns"],
+ ["tasks"],
+] as const;
+
+function invalidateRunTagQueries(queryClient: QueryClient) {
+ for (const queryKey of RUN_TAG_QUERY_KEYS) {
+ queryClient.invalidateQueries({ queryKey });
+ }
+}
function useApplyRunTagsMutation() {
const credentialGetter = useCredentialGetter();
@@ -26,11 +46,7 @@ function useApplyRunTagsMutation() {
.then((response) => response.data);
},
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["run-tags"] });
- queryClient.invalidateQueries({ queryKey: ["tag-keys"] });
- queryClient.invalidateQueries({ queryKey: ["tag-values"] });
- queryClient.invalidateQueries({ queryKey: ["runs"] });
- queryClient.invalidateQueries({ queryKey: ["tasks"] });
+ invalidateRunTagQueries(queryClient);
},
onError: (error: unknown) => {
toast({
@@ -42,4 +58,4 @@ function useApplyRunTagsMutation() {
});
}
-export { useApplyRunTagsMutation };
+export { invalidateRunTagQueries, useApplyRunTagsMutation };
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
index 2ae87a582..0766d8141 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
@@ -8,6 +8,7 @@ import {
} from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import CloudContext from "@/store/CloudContext";
import { PageSlotsProvider } from "@/store/PageSlots";
@@ -41,6 +42,11 @@ const workflowRun: WorkflowRunApiResponse = {
workflow_run_id: "wr_1",
workflow_title: "Test Workflow",
};
+const secondWorkflowRun: WorkflowRunApiResponse = {
+ ...workflowRun,
+ title: "Second Run",
+ workflow_run_id: "wr_2",
+};
vi.mock("posthog-js/react", () => ({
useFeatureFlagEnabled: () => false,
@@ -101,7 +107,7 @@ vi.mock("./hooks/useWorkflowRunsQuery", () => ({
useWorkflowRunsQuery: (props: Record<string, unknown>) => {
workflowRunsQueryCalls.push(props);
return {
- data: [workflowRun],
+ data: [workflowRun, secondWorkflowRun],
isLoading: false,
};
},
@@ -191,24 +197,27 @@ function LocationProbe() {
}
function renderWorkflowPage(initialEntry = "/workflows/wpid_abc123") {
+ const queryClient = new QueryClient();
return render(
- <CloudContext.Provider value={true}>
- <PageSlotsProvider value={{}}>
- <MemoryRouter initialEntries={[initialEntry]}>
- <Routes>
- <Route
- path="/workflows/:workflowPermanentId"
- element={
- <>
- <WorkflowPage />
- <LocationProbe />
- </>
- }
- />
- </Routes>
- </MemoryRouter>
- </PageSlotsProvider>
- </CloudContext.Provider>,
+ <QueryClientProvider client={queryClient}>
+ <CloudContext.Provider value={true}>
+ <PageSlotsProvider value={{}}>
+ <MemoryRouter initialEntries={[initialEntry]}>
+ <Routes>
+ <Route
+ path="/workflows/:workflowPermanentId"
+ element={
+ <>
+ <WorkflowPage />
+ <LocationProbe />
+ </>
+ }
+ />
+ </Routes>
+ </MemoryRouter>
+ </PageSlotsProvider>
+ </CloudContext.Provider>
+ </QueryClientProvider>,
);
}
@@ -220,6 +229,26 @@ describe("WorkflowPage run tags", () => {
within(container).getByTestId("tag-chip-list").textContent,
).toContain("completed");
});
+
+ it("shift-selects runs and exposes bulk tag actions", () => {
+ renderWorkflowPage();
+
+ const first = screen.getByRole("checkbox", { name: "Select wr_1" });
+ const second = screen.getByRole("checkbox", { name: "Select wr_2" });
+ fireEvent.click(first.parentElement!);
+ fireEvent.click(second.parentElement!, { shiftKey: true });
+
+ expect(
+ screen.getByRole("toolbar", { name: "Bulk actions" }).textContent,
+ ).toContain("2 selected");
+ });
+
+ it("hides selection when workflow tagging is disabled", () => {
+ flagState.taggingEnabled = false;
+ renderWorkflowPage();
+
+ expect(screen.queryByLabelText(/^Select /)).toBeNull();
+ });
});
describe("WorkflowPage tag filter control", () => {
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
index 31e7d541f..e136cf0e0 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
@@ -91,6 +91,13 @@ import { usePageSlots } from "@/store/PageSlots";
import { resolveRunWindow } from "./resolveRunWindow";
import { useRunTagsBatchQuery } from "@/routes/tasks/hooks/useRunTagsBatchQuery";
import { useRunTagSuggestionsQuery } from "@/routes/tasks/hooks/useRunTagSuggestionsQuery";
+import {
+ SelectionCheckboxCell,
+ SelectionHeaderCheckboxCell,
+} from "@/components/SelectionCheckbox";
+import { useRowSelection } from "@/hooks/useRowSelection";
+import { RunBulkActionBar } from "@/routes/runs/RunBulkActionBar";
+import { RunRowContextMenu } from "@/routes/runs/RunRowContextMenu";
function WorkflowPage() {
const { workflowPermanentId } = useParams();
@@ -193,6 +200,33 @@ function WorkflowPage() {
})),
[runTagSuggestions?.keys],
);
+ const selectableRuns = taggingEnabled ? (workflowRuns ?? []) : [];
+ const showCheckbox = selectableRuns.length > 0;
+ const columnCount = showCheckbox ? 6 : 5;
+ const {
+ selectedItems: selectedRuns,
+ isSelected,
+ allSelected,
+ someSelected,
+ indexById: selectableIndexById,
+ handleSelect,
+ toggleSelectAll,
+ clearSelection,
+ } = useRowSelection({
+ items: selectableRuns,
+ getId: (run) => run.workflow_run_id,
+ resetKey: JSON.stringify([
+ page,
+ statusFilters,
+ debouncedSearch,
+ tagsParam,
+ runWindow.createdAtStart,
+ runWindow.createdAtEnd,
+ workflowPermanentId,
+ taggingEnabled,
+ ]),
+ anchorResetKey: pageSize,
+ });
const {
workflowAnalyticsPanel: WorkflowAnalyticsPanel,
@@ -347,7 +381,17 @@ function WorkflowPage() {
<div className="overflow-hidden rounded-lg border border-border">
<Table>
<TableHeader>
- <TableRow>
+ <TableRow className="group/header">
+ {showCheckbox && (
+ <SelectionHeaderCheckboxCell
+ allSelected={allSelected}
+ someSelected={someSelected}
+ hasSelection={selectedRuns.length > 0}
+ onToggleAll={toggleSelectAll}
+ ariaLabel="Select all runs"
+ className="w-10"
+ />
+ )}
<TableHead className="w-[20%]">ID</TableHead>
<TableHead className="w-[20%]">Status</TableHead>
<TableHead className="w-[20%]">Created At</TableHead>
@@ -359,9 +403,11 @@ function WorkflowPage() {
</TableHeader>
<TableBody>
{isLoading ? (
- <TableMessageRow colSpan={5}>Loading runs…</TableMessageRow>
+ <TableMessageRow colSpan={columnCount}>
+ Loading runs…
+ </TableMessageRow>
) : workflowRuns?.length === 0 ? (
- <TableMessageRow colSpan={5}>
+ <TableMessageRow colSpan={columnCount}>
No agent runs found
</TableMessageRow>
) : (
@@ -383,101 +429,132 @@ function WorkflowPage() {
);
const runTags = runTagsMap[workflowRun.workflow_run_id];
+ const selectableIndex =
+ selectableIndexById.get(workflowRun.workflow_run_id) ??
+ -1;
+ const isRowSelected = isSelected(
+ workflowRun.workflow_run_id,
+ );
+ const runPath = studioEnabled
+ ? `/agents/${workflowPermanentId}/studio?wr=${workflowRun.workflow_run_id}`
+ : legacyRunDetailPath(
+ workflowPermanentId,
+ workflowRun.workflow_run_id,
+ );
+
+ const mainRow = (
+ <TableRow
+ onClick={(event) => {
+ if (event.ctrlKey || event.metaKey) {
+ window.open(
+ window.location.origin + runPath,
+ "_blank",
+ "noopener,noreferrer",
+ );
+ return;
+ }
+ navigate(runPath);
+ }}
+ className="group/row cursor-pointer select-none"
+ data-state={isRowSelected ? "selected" : undefined}
+ >
+ {showCheckbox && (
+ <SelectionCheckboxCell
+ index={selectableIndex}
+ checked={isRowSelected}
+ hasSelection={selectedRuns.length > 0}
+ onSelect={handleSelect}
+ ariaLabel={`Select ${workflowRun.workflow_run_id}`}
+ />
+ )}
+ <TableCell className="font-mono text-xs text-muted-foreground">
+ <div className="flex flex-col gap-1">
+ {workflowRunId}
+ {taggingEnabled && runTags?.length ? (
+ <TagChipList
+ tags={runTags}
+ descriptions={tagDescriptions}
+ colors={tagColors}
+ maxVisible={2}
+ />
+ ) : null}
+ </div>
+ </TableCell>
+ <TableCell>
+ <StatusBadge status={workflowRun.status} />
+ </TableCell>
+ <TableCell
+ className="text-muted-foreground"
+ title={basicTimeFormat(workflowRun.created_at)}
+ >
+ {compactLocalDateTime(workflowRun.created_at)}
+ </TableCell>
+ <TableCell className="tabular-nums text-muted-foreground">
+ {formatExecutionTime(
+ workflowRun.started_at ?? workflowRun.created_at,
+ workflowRun.finished_at,
+ ) ?? "-"}
+ </TableCell>
+ <TableCell>
+ <div className="flex justify-end gap-2">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={(event) => {
+ event.stopPropagation();
+ toggleParametersExpanded(
+ workflowRun.workflow_run_id,
+ );
+ }}
+ className={cn(
+ isExpanded
+ ? "text-blue-700 dark:text-blue-400"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ <MixerHorizontalIcon className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {isExpanded ? "Hide Inputs" : "Show Inputs"}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </TableCell>
+ </TableRow>
+ );
return (
<React.Fragment key={workflowRun.workflow_run_id}>
- {/* Main run row */}
- <TableRow
- onClick={(event) => {
- const url = studioEnabled
- ? `/agents/${workflowPermanentId}/studio?wr=${workflowRun.workflow_run_id}`
- : legacyRunDetailPath(
- workflowPermanentId,
- workflowRun.workflow_run_id,
- );
-
- if (event.ctrlKey || event.metaKey) {
- window.open(
- window.location.origin + url,
- "_blank",
- "noopener,noreferrer",
- );
- return;
+ {taggingEnabled ? (
+ <RunRowContextMenu
+ workflowRunId={workflowRun.workflow_run_id}
+ runPath={runPath}
+ currentTags={runTags ?? []}
+ tagKeys={tagFilterKeys}
+ labelSuggestions={runTagSuggestions?.labels ?? []}
+ valueSuggestionsByKey={
+ runTagSuggestions?.valuesByKey
}
- navigate(url);
- }}
- className="cursor-pointer"
- >
- <TableCell className="font-mono text-xs text-muted-foreground">
- <div className="flex flex-col gap-1">
- {workflowRunId}
- {taggingEnabled && runTags?.length ? (
- <TagChipList
- tags={runTags}
- descriptions={tagDescriptions}
- colors={tagColors}
- maxVisible={2}
- />
- ) : null}
- </div>
- </TableCell>
- <TableCell>
- <StatusBadge status={workflowRun.status} />
- </TableCell>
- <TableCell
- className="text-muted-foreground"
- title={basicTimeFormat(workflowRun.created_at)}
+ selectedCount={selectedRuns.length}
+ onNavigate={navigate}
>
- {compactLocalDateTime(workflowRun.created_at)}
- </TableCell>
- <TableCell className="tabular-nums text-muted-foreground">
- {formatExecutionTime(
- workflowRun.started_at ??
- workflowRun.created_at,
- workflowRun.finished_at,
- ) ?? "-"}
- </TableCell>
- <TableCell>
- <div className="flex justify-end gap-2">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- size="icon"
- variant="ghost"
- onClick={(event) => {
- event.stopPropagation();
- toggleParametersExpanded(
- workflowRun.workflow_run_id,
- );
- }}
- className={cn(
- isExpanded
- ? "text-blue-700 dark:text-blue-400"
- : "text-muted-foreground hover:text-foreground",
- )}
- >
- <MixerHorizontalIcon className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- {isExpanded
- ? "Hide Inputs"
- : "Show Inputs"}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- </TableCell>
- </TableRow>
-
+ {mainRow}
+ </RunRowContextMenu>
+ ) : (
+ mainRow
+ )}
{/* Expanded parameters section */}
{isExpanded && (
<TableRow
key={`${workflowRun.workflow_run_id}-params`}
>
<TableCell
- colSpan={5}
+ colSpan={columnCount}
className="bg-slate-50 dark:bg-slate-900/50"
>
<WorkflowRunParameters
@@ -496,6 +573,18 @@ function WorkflowPage() {
)}
</TableBody>
</Table>
+ {taggingEnabled && selectedRuns.length > 0 ? (
+ <RunBulkActionBar
+ selectedRunIds={selectedRuns.map(
+ (run) => run.workflow_run_id,
+ )}
+ runTagsMap={runTagsMap}
+ tagKeys={tagFilterKeys}
+ labelSuggestions={runTagSuggestions?.labels ?? []}
+ valueSuggestionsByKey={runTagSuggestions?.valuesByKey}
+ onClearSelection={clearSelection}
+ />
+ ) : null}
<RunParametersDialog
open={openRunParams !== null}
onOpenChange={(open) => {
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx b/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx
index f6291bbc5..d3fd1403d 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx
@@ -81,6 +81,7 @@ import { FirstRunRecoveryGuidance } from "@/components/onboarding/FirstRunRecove
import { useFeatureFlagVariantKey } from "posthog-js/react";
import { EXPERIMENT } from "@/util/onboarding/experimentConfig";
import { isFirstFailedRunRecoveryEligible } from "@/util/onboarding/rolloutGating";
+import { RunTagsEditor } from "@/routes/tasks/components/tagging/RunTagsEditor";
function WorkflowRunRightColumn({
activeItem,
@@ -570,6 +571,9 @@ function WorkflowRun() {
<h2 className="text-2xl text-neutral-600 dark:text-slate-400">
{workflowRunId}
</h2>
+ {workflowRunId ? (
+ <RunTagsEditor workflowRunId={workflowRunId} />
+ ) : null}
{workflowRun &&
(workflowRun.started_at ||
workflowRun.finished_at ||
diff --git a/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.test.tsx b/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.test.tsx
new file mode 100644
index 000000000..6e6f804b0
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.test.tsx
@@ -0,0 +1,79 @@
+import { useState } from "react";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { ScheduleConfigFields } from "./ScheduleConfigFields";
+
+function Harness({ initialCron }: { initialCron: string }) {
+ const [cron, setCron] = useState(initialCron);
+ const [timezone, setTimezone] = useState("UTC");
+ return (
+ <>
+ <ScheduleConfigFields
+ cronExpression={cron}
+ timezone={timezone}
+ onCronChange={setCron}
+ onTimezoneChange={setTimezone}
+ />
+ <output data-testid="cron-out">{cron}</output>
+ </>
+ );
+}
+
+function cronOut() {
+ return screen.getByTestId("cron-out").textContent;
+}
+
+function pressed(name: string) {
+ return screen.getByRole("button", { name }).getAttribute("aria-pressed");
+}
+
+describe("ScheduleConfigFields", () => {
+ it("seeds the day-of-week chips from a weekdays cron", () => {
+ render(<Harness initialCron="0 9 * * 1-5" />);
+ for (const day of [
+ "Monday",
+ "Tuesday",
+ "Wednesday",
+ "Thursday",
+ "Friday",
+ ]) {
+ expect(pressed(day)).toBe("true");
+ }
+ for (const day of ["Sunday", "Saturday"]) {
+ expect(pressed(day)).toBe("false");
+ }
+ });
+
+ it("toggling a day updates the generated cron", () => {
+ render(<Harness initialCron="0 9 * * 1-5" />);
+ fireEvent.click(screen.getByRole("button", { name: "Saturday" }));
+ expect(cronOut()).toBe("0 9 * * 1,2,3,4,5,6");
+ });
+
+ it("keeps at least one weekly day selected", () => {
+ render(<Harness initialCron="0 9 * * 1" />);
+ fireEvent.click(screen.getByRole("button", { name: "Monday" }));
+ expect(pressed("Monday")).toBe("true");
+ expect(cronOut()).toBe("0 9 * * 1");
+ });
+
+ it("treats an unsupported expression as custom and surfaces the raw cron", () => {
+ render(<Harness initialCron="*/1 * * * *" />);
+ // Day pickers only render for a recognized weekly schedule; a custom
+ // expression hides them and drops the user into the advanced field.
+ expect(screen.queryByRole("button", { name: "Monday" })).toBeNull();
+ const input = screen.getByPlaceholderText("* * * * *") as HTMLInputElement;
+ expect(input.value).toBe("*/1 * * * *");
+ expect(screen.queryByText(/at least 5 minutes apart/i)).not.toBeNull();
+ });
+
+ it("propagates edits made in the advanced cron field", () => {
+ render(<Harness initialCron="0 9 * * *" />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /advanced \(cron expression\)/i }),
+ );
+ const input = screen.getByPlaceholderText("* * * * *");
+ fireEvent.change(input, { target: { value: "0 14 * * *" } });
+ expect(cronOut()).toBe("0 14 * * *");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.tsx b/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.tsx
new file mode 100644
index 000000000..d2b0f8d1a
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.tsx
@@ -0,0 +1,432 @@
+import { useEffect, useMemo, useState } from "react";
+import {
+ CaretSortIcon,
+ CheckIcon,
+ ChevronRightIcon,
+} from "@radix-ui/react-icons";
+import { Button } from "@/components/ui/button";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@/components/ui/collapsible";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { cn } from "@/util/utils";
+import {
+ cronToHumanReadable,
+ formatNextRun,
+ getNextRuns,
+ getTimezones,
+ isValidCron,
+ meetsMinCronInterval,
+} from "@/routes/workflows/editor/panels/schedulePanel/cronUtils";
+import {
+ DAY_OF_WEEK_OPTIONS,
+ DEFAULT_SCHEDULE_BUILDER,
+ cronToScheduleBuilder,
+ scheduleBuilderToCron,
+ scheduleBuildersEquivalent,
+ to12Hour,
+ to24Hour,
+ type ScheduleBuilderState,
+ type ScheduleFrequency,
+} from "@/routes/workflows/editor/panels/schedulePanel/scheduleBuilder";
+
+type Props = {
+ cronExpression: string;
+ timezone: string;
+ onCronChange: (cronExpression: string) => void;
+ onTimezoneChange: (timezone: string) => void;
+ size?: "default" | "compact";
+ disabled?: boolean;
+};
+
+const FREQUENCY_OPTIONS: ReadonlyArray<{
+ value: ScheduleFrequency;
+ label: string;
+}> = [
+ { value: "hourly", label: "Hourly" },
+ { value: "daily", label: "Daily" },
+ { value: "weekly", label: "Weekly" },
+ { value: "monthly", label: "Monthly" },
+];
+
+const HOUR_OPTIONS = Array.from({ length: 12 }, (_, i) => i + 1);
+const MINUTE_OPTIONS = Array.from({ length: 60 }, (_, i) => i);
+const DAY_OF_MONTH_OPTIONS = Array.from({ length: 31 }, (_, i) => i + 1);
+
+function ScheduleConfigFields({
+ cronExpression,
+ timezone,
+ onCronChange,
+ onTimezoneChange,
+ size = "default",
+ disabled = false,
+}: Readonly<Props>) {
+ const compact = size === "compact";
+ const controlClass = compact ? "h-8 text-xs" : "h-9 text-sm";
+ const labelClass = compact ? "text-xs" : undefined;
+
+ const parsed = useMemo(
+ () => cronToScheduleBuilder(cronExpression),
+ [cronExpression],
+ );
+ const isCustom = parsed === null;
+
+ const [builder, setBuilder] = useState<ScheduleBuilderState>(
+ () => parsed ?? DEFAULT_SCHEDULE_BUILDER,
+ );
+ const [advancedOpen, setAdvancedOpen] = useState(isCustom);
+ const [timezoneOpen, setTimezoneOpen] = useState(false);
+
+ // Keep the pickers in step when the cron changes externally (raw edit,
+ // dialog reset, seeding an existing schedule). Compares only the fields the
+ // frequency actually uses so a generated cron round-trip doesn't clobber
+ // unshown selections or spin a render loop.
+ useEffect(() => {
+ if (parsed && !scheduleBuildersEquivalent(parsed, builder)) {
+ setBuilder(parsed);
+ }
+ }, [parsed, builder]);
+
+ useEffect(() => {
+ if (isCustom) setAdvancedOpen(true);
+ }, [isCustom]);
+
+ const allTimezones = useMemo(() => getTimezones(), []);
+ const valid = isValidCron(cronExpression);
+ const intervalTooShort = valid && !meetsMinCronInterval(cronExpression);
+ const humanReadable = valid ? cronToHumanReadable(cronExpression) : null;
+ const nextRuns = valid ? getNextRuns(cronExpression, timezone, 5) : [];
+
+ const { hour12, meridiem } = to12Hour(builder.hour);
+
+ function commitBuilder(next: ScheduleBuilderState) {
+ setBuilder(next);
+ onCronChange(scheduleBuilderToCron(next));
+ }
+
+ function handleFrequencyChange(value: string) {
+ if (value === "custom") return;
+ const frequency = value as ScheduleFrequency;
+ const next: ScheduleBuilderState = { ...builder, frequency };
+ if (frequency === "weekly" && next.daysOfWeek.length === 0) {
+ next.daysOfWeek = [...DEFAULT_SCHEDULE_BUILDER.daysOfWeek];
+ }
+ commitBuilder(next);
+ }
+
+ function toggleDay(day: number) {
+ const has = builder.daysOfWeek.includes(day);
+ const days = has
+ ? builder.daysOfWeek.filter((d) => d !== day)
+ : [...builder.daysOfWeek, day];
+ // A weekly schedule needs at least one day; ignore removing the last one.
+ commitBuilder({ ...builder, daysOfWeek: days.length > 0 ? days : [day] });
+ }
+
+ const showTimeOfDay = builder.frequency !== "hourly";
+
+ return (
+ <div className={cn(compact ? "space-y-4" : "space-y-6")}>
+ <div className="space-y-2">
+ <Label className={labelClass}>Repeat</Label>
+ <Select
+ value={isCustom ? "custom" : builder.frequency}
+ onValueChange={handleFrequencyChange}
+ disabled={disabled}
+ >
+ <SelectTrigger className={cn("w-full", controlClass)}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {FREQUENCY_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ {isCustom && (
+ <SelectItem value="custom" disabled>
+ Custom
+ </SelectItem>
+ )}
+ </SelectContent>
+ </Select>
+ </div>
+
+ {!isCustom && builder.frequency === "hourly" && (
+ <div className="space-y-2">
+ <Label className={labelClass}>Minute past the hour</Label>
+ <Select
+ value={String(builder.minute)}
+ onValueChange={(value) =>
+ commitBuilder({ ...builder, minute: Number(value) })
+ }
+ disabled={disabled}
+ >
+ <SelectTrigger className={cn("w-24", controlClass)}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {MINUTE_OPTIONS.map((minute) => (
+ <SelectItem key={minute} value={String(minute)}>
+ :{String(minute).padStart(2, "0")}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+
+ {!isCustom && builder.frequency === "weekly" && (
+ <div className="space-y-2">
+ <Label className={labelClass}>On these days</Label>
+ <div className="flex flex-wrap gap-1.5">
+ {DAY_OF_WEEK_OPTIONS.map((day) => {
+ const selected = builder.daysOfWeek.includes(day.value);
+ return (
+ <Button
+ key={day.value}
+ type="button"
+ variant={selected ? "default" : "secondary"}
+ size="sm"
+ aria-pressed={selected}
+ aria-label={day.label}
+ className={cn("w-9 px-0", compact && "h-7")}
+ disabled={disabled}
+ onClick={() => toggleDay(day.value)}
+ >
+ {day.short}
+ </Button>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
+ {!isCustom && builder.frequency === "monthly" && (
+ <div className="space-y-2">
+ <Label className={labelClass}>On day of month</Label>
+ <Select
+ value={String(builder.dayOfMonth)}
+ onValueChange={(value) =>
+ commitBuilder({ ...builder, dayOfMonth: Number(value) })
+ }
+ disabled={disabled}
+ >
+ <SelectTrigger className={cn("w-24", controlClass)}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {DAY_OF_MONTH_OPTIONS.map((day) => (
+ <SelectItem key={day} value={String(day)}>
+ {day}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+
+ {!isCustom && showTimeOfDay && (
+ <div className="space-y-2">
+ <Label className={labelClass}>At</Label>
+ <div className="flex items-center gap-2">
+ <Select
+ value={String(hour12)}
+ onValueChange={(value) =>
+ commitBuilder({
+ ...builder,
+ hour: to24Hour(Number(value), meridiem),
+ })
+ }
+ disabled={disabled}
+ >
+ <SelectTrigger className={cn("w-20", controlClass)}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {HOUR_OPTIONS.map((hour) => (
+ <SelectItem key={hour} value={String(hour)}>
+ {hour}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <span className="text-muted-foreground">:</span>
+ <Select
+ value={String(builder.minute)}
+ onValueChange={(value) =>
+ commitBuilder({ ...builder, minute: Number(value) })
+ }
+ disabled={disabled}
+ >
+ <SelectTrigger className={cn("w-20", controlClass)}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {MINUTE_OPTIONS.map((minute) => (
+ <SelectItem key={minute} value={String(minute)}>
+ {String(minute).padStart(2, "0")}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select
+ value={meridiem}
+ onValueChange={(value) =>
+ commitBuilder({
+ ...builder,
+ hour: to24Hour(hour12, value as "AM" | "PM"),
+ })
+ }
+ disabled={disabled}
+ >
+ <SelectTrigger className={cn("w-20", controlClass)}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="AM">AM</SelectItem>
+ <SelectItem value="PM">PM</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <Label className={labelClass}>Timezone</Label>
+ <Popover open={timezoneOpen} onOpenChange={setTimezoneOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ role="combobox"
+ aria-expanded={timezoneOpen}
+ disabled={disabled}
+ className={cn("w-full justify-between font-normal", controlClass)}
+ >
+ <span className="truncate">{timezone}</span>
+ <CaretSortIcon className="ml-2 size-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ className="w-[var(--radix-popover-trigger-width)] p-0"
+ align="start"
+ >
+ <Command>
+ <CommandInput placeholder="Search timezone..." />
+ <CommandList>
+ <CommandEmpty>No timezone found.</CommandEmpty>
+ <CommandGroup>
+ {allTimezones.map((tz) => (
+ <CommandItem
+ key={tz}
+ value={tz}
+ onSelect={() => {
+ onTimezoneChange(tz);
+ setTimezoneOpen(false);
+ }}
+ >
+ <CheckIcon
+ className={cn(
+ "mr-2 size-4",
+ tz === timezone ? "opacity-100" : "opacity-0",
+ )}
+ />
+ {tz}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ </div>
+
+ {humanReadable && (
+ <p
+ className={cn(
+ "text-muted-foreground",
+ compact ? "text-xs" : "text-sm",
+ )}
+ >
+ {humanReadable}
+ </p>
+ )}
+
+ <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
+ <CollapsibleTrigger asChild>
+ <button
+ type="button"
+ className="group flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
+ >
+ <ChevronRightIcon className="size-3 transition-transform group-data-[state=open]:rotate-90" />
+ Advanced (cron expression)
+ </button>
+ </CollapsibleTrigger>
+ <CollapsibleContent className="space-y-1.5 pt-2">
+ <Input
+ value={cronExpression}
+ onChange={(e) => onCronChange(e.target.value)}
+ placeholder="* * * * *"
+ disabled={disabled}
+ className={cn(
+ controlClass,
+ cronExpression &&
+ (!valid || intervalTooShort) &&
+ "border-destructive",
+ )}
+ />
+ {!valid && cronExpression && (
+ <p className="text-xs text-destructive">Invalid cron expression</p>
+ )}
+ {intervalTooShort && (
+ <p className="text-xs text-destructive">
+ Schedule runs must be at least 5 minutes apart.
+ </p>
+ )}
+ </CollapsibleContent>
+ </Collapsible>
+
+ {nextRuns.length > 0 && (
+ <div className="space-y-2">
+ <Label className={labelClass}>Next Scheduled Runs</Label>
+ <div className="space-y-1 rounded-md border border-border bg-slate-elevation3 p-3">
+ {nextRuns.map((run) => (
+ <div
+ key={run.toISOString()}
+ className="text-xs text-muted-foreground"
+ >
+ {formatNextRun(run, timezone)}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export { ScheduleConfigFields };
diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.shape.test.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.shape.test.tsx
index 7fd3ed4b7..bab576678 100644
--- a/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.shape.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.shape.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { cleanup, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Tag } from "../../types/tagTypes";
import { buildTagColorMap } from "../../types/tagColors";
@@ -96,4 +96,26 @@ describe("TagChipList colors", () => {
expect(html).toContain("bg-green-500");
expect(screen.getByText("standalone")).toBeTruthy();
});
+
+ it("only offers removal for user-editable tags", () => {
+ const onRemove = vi.fn();
+ render(
+ <TagChipList
+ tags={[
+ { key: "env", value: "prod" },
+ { key: "skyvern.platform", value: "browser" },
+ ]}
+ onRemove={onRemove}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Remove env: prod" }));
+
+ expect(onRemove).toHaveBeenCalledWith({ key: "env", value: "prod" });
+ expect(
+ screen.queryByRole("button", {
+ name: "Remove skyvern.platform: browser",
+ }),
+ ).toBeNull();
+ });
});
diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx
index 54b276e15..04218afc5 100644
--- a/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx
+++ b/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx
@@ -8,6 +8,7 @@ import { badgeVariants } from "@/components/ui/badge-variants";
import { cn } from "@/util/utils";
import {
normalizeWorkflowTags,
+ isUserWritableTagKey,
sortTags,
tagElementKey,
type Tag,
@@ -24,6 +25,7 @@ type Props = {
colors?: TagColorMap;
maxVisible?: number;
className?: string;
+ onRemove?: (tag: Tag) => void;
};
// Generic list of tag chips with a "+N" overflow affordance. Standalone labels
@@ -34,6 +36,7 @@ function TagChipList({
colors,
maxVisible = 3,
className,
+ onRemove,
}: Props) {
// Re-validate at render time: callers feed this straight from API payloads,
// and a shape skew here previously killed the whole route via React #31.
@@ -56,6 +59,11 @@ function TagChipList({
tag.key !== null ? descriptions?.get(tag.key) : undefined
}
color={tagColorFor(colors, tag.key, tag.value)}
+ onRemove={
+ onRemove && isUserWritableTagKey(tag.key)
+ ? () => onRemove(tag)
+ : undefined
+ }
/>
))}
{hidden.length > 0 ? (
diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/TagPickerCommand.test.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/TagPickerCommand.test.tsx
index 1d34b5ecc..3dc89ad98 100644
--- a/skyvern-frontend/src/routes/workflows/components/tagging/TagPickerCommand.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/components/tagging/TagPickerCommand.test.tsx
@@ -203,4 +203,18 @@ describe("TagPickerCommand system tags", () => {
expect(screen.queryByText(/^Add /)).toBeNull();
expect(onApply).not.toHaveBeenCalled();
});
+
+ it("keeps current system tags out of the removable group", () => {
+ const onRemove = vi.fn();
+ renderPicker(vi.fn(), {
+ currentTags: [
+ { key: "skyvern.platform", value: "browser" },
+ { key: "env", value: "prod" },
+ ],
+ onRemove,
+ });
+
+ expect(screen.getByText("env: prod")).toBeTruthy();
+ expect(screen.queryByText("skyvern.platform: browser")).toBeNull();
+ });
});
diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/TagPickerCommand.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/TagPickerCommand.tsx
index 7a0afbfba..000859912 100644
--- a/skyvern-frontend/src/routes/workflows/components/tagging/TagPickerCommand.tsx
+++ b/skyvern-frontend/src/routes/workflows/components/tagging/TagPickerCommand.tsx
@@ -30,8 +30,8 @@ type Props = {
// While a bulk apply is in flight, freeze the picker so a second pick can't
// start a competing apply for the same selection.
disabled?: boolean;
- // Set for single-target pickers (workflow-row and run-tag menus) to enable
- // removal; the bulk Actions surface omits them and stays add-only.
+ // Set by pickers that support removal (single rows and the run bulk union).
+ // The agent bulk Actions surface omits these and stays add-only.
currentTags?: Array<Tag>;
onRemove?: (tag: Tag) => void;
};
diff --git a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
index 3fe5f2612..85e034633 100644
--- a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
@@ -66,6 +66,19 @@ export const helpTooltips = {
...baseHelpTooltipContent,
navigationGoal:
"Give Skyvern an objective that describes how to download the file.",
+ download_target:
+ "Choose whether to keep downloaded files in Skyvern or send them to S3, Azure Blob Storage, Google Drive, or SFTP.",
+ path: "The path of the destination folder to send the files to.",
+ prompt:
+ "Optionally describe which downloaded files should be sent (e.g. only certain file names). Leave empty to send all files.",
+ s3_bucket: "The S3 bucket to send the file to.",
+ aws_access_key_id: "The AWS access key ID to use to send the file to S3.",
+ aws_secret_access_key:
+ "The AWS secret access key to use to send the file to S3.",
+ region_name: "The AWS region",
+ azure_storage_account_name: "The Azure Storage Account Name.",
+ azure_storage_account_key: "The Azure Storage Account Key.",
+ azure_blob_container_name: "The Azure Blob Container Name.",
},
validation: baseHelpTooltipContent,
textPrompt: {
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsx
index 8205f2710..028896a62 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsx
@@ -1,10 +1,13 @@
import { useEdges, useNodes, useNodesData } from "@xyflow/react";
+import type { ReactNode } from "react";
import { BROWSER_DOWNLOAD_TIMEOUT_SECONDS } from "@/api/types";
import { RunEngineSelector } from "@/components/EngineSelector";
import { HelpTooltip } from "@/components/HelpTooltip";
import { ModelSelector } from "@/components/ModelSelector";
+import { WorkflowBlockInput } from "@/components/WorkflowBlockInput";
import { WorkflowBlockInputTextarea } from "@/components/WorkflowBlockInputTextarea";
+import { GoogleOAuthCredentialSelector } from "@/routes/workflows/components/GoogleOAuthCredentialSelector";
import {
Accordion,
AccordionContent,
@@ -13,8 +16,16 @@ import {
} from "@/components/ui/accordion";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";
+import { GOOGLE_DRIVE_REQUIRED_SCOPES } from "@/util/googleScopes";
import { ErrorCodeMappingEditor } from "../../ErrorCodeMappingEditor";
import { AI_IMPROVE_CONFIGS } from "../../constants";
@@ -42,6 +53,24 @@ const navigationGoalTooltip =
"Give Skyvern an objective that describes how to download the file.";
const navigationGoalPlaceholder = "Tell Skyvern which file to download.";
+type DestinationFieldProps = {
+ label: string;
+ help: string;
+ children: ReactNode;
+};
+
+function DestinationField({ label, help, children }: DestinationFieldProps) {
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Label className="text-sm text-slate-400">{label}</Label>
+ <HelpTooltip content={help} />
+ </div>
+ {children}
+ </div>
+ );
+}
+
function FileDownloadEditor({ blockId }: { blockId: string }) {
// Subscribe to this node's data slice. The sidebar mount lives outside the
// per-node renderer, so a useReactFlow().getNode(id) snapshot does not
@@ -77,6 +106,26 @@ function FileDownloadEditorBody({
downloadSuffix,
totpIdentifier,
totpVerificationUrl,
+ downloadTarget,
+ path,
+ prompt,
+ s3Bucket,
+ awsAccessKeyId,
+ awsSecretAccessKey,
+ regionName,
+ azureStorageAccountName,
+ azureStorageAccountKey,
+ azureBlobContainerName,
+ googleCredentialId,
+ googleDriveFolderId,
+ sftpHost,
+ sftpPort,
+ sftpUsername,
+ sftpPassword,
+ sftpPrivateKey,
+ sftpPrivateKeyPassphrase,
+ sftpRemotePath,
+ sftpHostKey,
} = data;
const nodes = useNodes<AppNode>();
@@ -97,6 +146,295 @@ function FileDownloadEditorBody({
return (
<div data-testid="file-download-block-form" className="space-y-4">
<div className="space-y-4">
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Label className="text-sm text-slate-400">Download Target</Label>
+ <HelpTooltip
+ content={helpTooltips["fileDownload"]["download_target"]}
+ />
+ </div>
+ <Select
+ value={downloadTarget}
+ onValueChange={(value) =>
+ value &&
+ update({
+ downloadTarget: value as
+ | "website"
+ | "s3"
+ | "azure"
+ | "google_drive"
+ | "sftp",
+ })
+ }
+ disabled={!editable}
+ >
+ <SelectTrigger className="nopan text-xs">
+ <SelectValue placeholder="Select download target" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="website">Website</SelectItem>
+ <SelectItem value="s3">AWS S3</SelectItem>
+ <SelectItem value="azure">Azure Blob Storage</SelectItem>
+ <SelectItem value="google_drive">Google Drive</SelectItem>
+ <SelectItem value="sftp">SFTP</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ {downloadTarget !== "website" && (
+ <DestinationField
+ label="Prompt"
+ help={helpTooltips["fileDownload"]["prompt"]}
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ prompt: value })}
+ value={prompt ?? ""}
+ placeholder={
+ 'e.g. Only send the PDF files whose names contain "invoice"'
+ }
+ className="nopan text-xs"
+ />
+ <p className="text-xs text-slate-400">
+ Optional. Leave empty to send all downloaded files.
+ </p>
+ </DestinationField>
+ )}
+
+ {downloadTarget === "s3" && (
+ <>
+ <DestinationField
+ label="AWS Access Key ID"
+ help={helpTooltips["fileDownload"]["aws_access_key_id"]}
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ awsAccessKeyId: value })}
+ value={awsAccessKeyId as string}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="AWS Secret Access Key"
+ help={helpTooltips["fileDownload"]["aws_secret_access_key"]}
+ >
+ <WorkflowBlockInput
+ nodeId={blockId}
+ type="password"
+ value={awsSecretAccessKey as string}
+ className="nopan text-xs"
+ onChange={(value) => update({ awsSecretAccessKey: value })}
+ />
+ </DestinationField>
+ <DestinationField
+ label="S3 Bucket"
+ help={helpTooltips["fileDownload"]["s3_bucket"]}
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ s3Bucket: value })}
+ value={s3Bucket as string}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="Region Name"
+ help={helpTooltips["fileDownload"]["region_name"]}
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ regionName: value })}
+ value={regionName as string}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="(Optional) Folder Path"
+ help={helpTooltips["fileDownload"]["path"]}
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ path: value })}
+ value={path as string}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ </>
+ )}
+
+ {downloadTarget === "azure" && (
+ <>
+ <DestinationField
+ label="Storage Account Name"
+ help={helpTooltips["fileDownload"]["azure_storage_account_name"]}
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ azureStorageAccountName: value })}
+ value={azureStorageAccountName as string}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="Storage Account Key"
+ help={helpTooltips["fileDownload"]["azure_storage_account_key"]}
+ >
+ <WorkflowBlockInput
+ nodeId={blockId}
+ type="password"
+ value={azureStorageAccountKey as string}
+ className="nopan text-xs"
+ onChange={(value) => update({ azureStorageAccountKey: value })}
+ />
+ </DestinationField>
+ <DestinationField
+ label="Blob Container Name"
+ help={helpTooltips["fileDownload"]["azure_blob_container_name"]}
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ azureBlobContainerName: value })}
+ value={azureBlobContainerName as string}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="(Optional) Folder Path"
+ help="Optional folder path within the blob container. Defaults to {{ workflow_run_id }} if not specified."
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ path: value })}
+ value={path as string}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ </>
+ )}
+
+ {downloadTarget === "google_drive" && (
+ <>
+ <DestinationField
+ label="Google Account"
+ help="The connected Google account used for Drive uploads."
+ >
+ <GoogleOAuthCredentialSelector
+ nodeId={blockId}
+ value={googleCredentialId ?? ""}
+ onChange={(value) => update({ googleCredentialId: value })}
+ requiredScopes={GOOGLE_DRIVE_REQUIRED_SCOPES}
+ />
+ </DestinationField>
+ <DestinationField
+ label="Google Drive Folder ID (Required)"
+ help="Required destination Google Drive folder ID. You can paste a Drive folder URL or a bare folder ID."
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ googleDriveFolderId: value })}
+ value={googleDriveFolderId ?? ""}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ </>
+ )}
+
+ {downloadTarget === "sftp" && (
+ <>
+ <DestinationField
+ label="SFTP Host"
+ help="The SFTP host to upload files to."
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ sftpHost: value })}
+ value={sftpHost ?? ""}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="Port"
+ help="Numeric only — template values are not supported. Defaults to 22 if left blank."
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) =>
+ update({ sftpPort: value.replace(/[^0-9]/g, "") })
+ }
+ value={sftpPort ?? ""}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField label="Username" help="The SFTP username.">
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ sftpUsername: value })}
+ value={sftpUsername ?? ""}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="Password"
+ help="Password auth. Leave blank if using a private key. Reference a secret parameter for security."
+ >
+ <WorkflowBlockInput
+ nodeId={blockId}
+ type="password"
+ onChange={(value) => update({ sftpPassword: value })}
+ value={sftpPassword ?? ""}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="Private Key"
+ help="PEM private key for key-based auth. Leave blank if using a password. Reference a secret parameter for security."
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ sftpPrivateKey: value })}
+ value={sftpPrivateKey ?? ""}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="Private Key Passphrase (Optional)"
+ help="Optional passphrase for the private key."
+ >
+ <WorkflowBlockInput
+ nodeId={blockId}
+ type="password"
+ onChange={(value) =>
+ update({ sftpPrivateKeyPassphrase: value })
+ }
+ value={sftpPrivateKeyPassphrase ?? ""}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="(Optional) Remote Directory"
+ help="Remote directory to upload into. Created if it does not exist. Defaults to the login directory."
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ sftpRemotePath: value })}
+ value={sftpRemotePath ?? ""}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ <DestinationField
+ label="(Optional) Host Key"
+ help="If blank, the server's host key is NOT verified and the connection can be intercepted (MITM). Pin a host key (e.g. 'ssh-ed25519 AAAA...') for untrusted networks."
+ >
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ onChange={(value) => update({ sftpHostKey: value })}
+ value={sftpHostKey ?? ""}
+ className="nopan text-xs"
+ />
+ </DestinationField>
+ </>
+ )}
+
<div className="space-y-2">
<div className="flex gap-2">
<Label className="text-xs text-tertiary-foreground">URL</Label>
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/types.ts
index 192a972a1..ef91cff08 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/types.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/types.ts
@@ -16,6 +16,27 @@ export type FileDownloadNodeData = NodeBaseData & {
engine: RunEngine | null;
disableCache: boolean;
downloadTimeout: number | null;
+ downloadTarget: "website" | "s3" | "azure" | "google_drive" | "sftp";
+ path: string;
+ prompt: string | null;
+ s3Bucket: string | null;
+ awsAccessKeyId: string | null;
+ awsSecretAccessKey: string | null;
+ regionName: string | null;
+ azureStorageAccountName: string | null;
+ azureStorageAccountKey: string | null;
+ azureBlobContainerName: string | null;
+ googleCredentialId: string | null;
+ googleDriveFolderId: string | null;
+ sftpHost: string | null;
+ sftpPort: string | null;
+ sftpUsername: string | null;
+ sftpPassword: string | null;
+ sftpPrivateKey: string | null;
+ sftpPrivateKeyPassphrase: string | null;
+ sftpRemotePath: string | null;
+ sftpHostKey: string | null;
+ continueOnEmpty: boolean;
};
export type FileDownloadNode = Node<FileDownloadNodeData, "fileDownload">;
@@ -38,6 +59,27 @@ export const fileDownloadNodeDefaultData: FileDownloadNodeData = {
engine: RunEngine.SkyvernV1,
model: null,
downloadTimeout: null,
+ downloadTarget: "website",
+ path: "{{ workflow_run_id }}",
+ prompt: null,
+ s3Bucket: null,
+ awsAccessKeyId: null,
+ awsSecretAccessKey: null,
+ regionName: null,
+ azureStorageAccountName: null,
+ azureStorageAccountKey: null,
+ azureBlobContainerName: null,
+ googleCredentialId: null,
+ googleDriveFolderId: null,
+ sftpHost: null,
+ sftpPort: null,
+ sftpUsername: null,
+ sftpPassword: null,
+ sftpPrivateKey: null,
+ sftpPrivateKeyPassphrase: null,
+ sftpRemotePath: null,
+ sftpHostKey: null,
+ continueOnEmpty: false,
ignoreWorkflowSystemPrompt: false,
} as const;
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx
index 22ed7f213..76bdefe7b 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx
@@ -12,6 +12,10 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { RunEngine } from "@/api/types";
import type { FileDownloadNode } from "../../nodes/FileDownloadNode/types";
+import type {
+ FileDownloadBlock,
+ WorkflowApiResponse,
+} from "../../../types/workflowTypes";
const mockNodes = new Map<
string,
@@ -258,6 +262,7 @@ function setFileDownloadNode(
engine: RunEngine.SkyvernV1,
model: null,
downloadTimeout: null,
+ downloadTarget: "website",
...overrides,
},
});
@@ -298,6 +303,19 @@ describe("FileDownloadBlockForm (SKY-9361)", () => {
expect(navigationGoal.value).toBe("download the latest invoice");
});
+ test("renders Download Target defaulted to Website without destination fields", () => {
+ setFileDownloadNode("d1");
+ render(<FileDownloadBlockForm blockId="d1" />);
+
+ expect(screen.getByText("Download Target")).toBeDefined();
+ expect(screen.getByText("Website")).toBeDefined();
+ expect(screen.queryByText("Prompt")).toBeNull();
+ expect(screen.queryByText("S3 Bucket")).toBeNull();
+ expect(screen.queryByText("Storage Account Name")).toBeNull();
+ expect(screen.queryByText("Google Account")).toBeNull();
+ expect(screen.queryByText("SFTP Host")).toBeNull();
+ });
+
test("editing url propagates", () => {
setFileDownloadNode("d1");
render(<FileDownloadBlockForm blockId="d1" />);
@@ -485,3 +503,73 @@ describe("FileDownloadBlockForm (SKY-9361)", () => {
expect(ok).toBe(true);
});
});
+
+describe("file download serialization", () => {
+ test("omits destination fields for website downloads in saved and exported YAML", async () => {
+ const { convert, getWorkflowBlocks } = await vi.importActual<
+ typeof import("../../workflowEditorUtils")
+ >("../../workflowEditorUtils");
+ const destinationFields = [
+ "download_target",
+ "path",
+ "prompt",
+ "continue_on_empty",
+ "s3_bucket",
+ "aws_access_key_id",
+ "aws_secret_access_key",
+ "region_name",
+ "azure_storage_account_name",
+ "azure_storage_account_key",
+ "azure_blob_container_name",
+ "google_credential_id",
+ "google_drive_folder_id",
+ "sftp_host",
+ "sftp_port",
+ "sftp_username",
+ "sftp_password",
+ "sftp_private_key",
+ "sftp_private_key_passphrase",
+ "sftp_remote_path",
+ "sftp_host_key",
+ ];
+
+ setFileDownloadNode("d1", {
+ downloadTarget: "website",
+ path: "{{ workflow_run_id }}",
+ prompt: "stale prompt",
+ s3Bucket: "stale-s3",
+ azureBlobContainerName: "stale-azure",
+ googleDriveFolderId: "stale-google",
+ sftpHost: "stale-sftp",
+ continueOnEmpty: true,
+ });
+ const node = mockNodes.get("d1") as FileDownloadNode;
+ const [savedBlock] = getWorkflowBlocks([node], []);
+
+ const apiBlock = {
+ ...savedBlock,
+ parameters: [],
+ output_parameter: {},
+ download_target: "website",
+ path: "{{ workflow_run_id }}",
+ prompt: "stale prompt",
+ s3_bucket: "stale-s3",
+ azure_blob_container_name: "stale-azure",
+ google_drive_folder_id: "stale-google",
+ sftp_host: "stale-sftp",
+ continue_on_empty: true,
+ } as unknown as FileDownloadBlock;
+ const exportedBlock = convert({
+ workflow_definition: {
+ version: 2,
+ parameters: [],
+ blocks: [apiBlock],
+ },
+ } as unknown as WorkflowApiResponse).workflow_definition.blocks[0];
+
+ for (const field of destinationFields) {
+ expect(savedBlock).not.toHaveProperty(field);
+ expect(exportedBlock).not.toHaveProperty(field);
+ }
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/CreateScheduleDialog.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/CreateScheduleDialog.tsx
index 88bcb507a..8aadd3f94 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/CreateScheduleDialog.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/CreateScheduleDialog.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -13,19 +13,15 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PlusIcon } from "@radix-ui/react-icons";
import type { Parameter } from "@/routes/workflows/types/workflowTypes";
+import { ScheduleConfigFields } from "@/routes/workflows/components/ScheduleConfigFields";
import { ScheduleParametersSection } from "@/routes/workflows/components/ScheduleParametersSection";
import { buildScheduleParametersPayload } from "@/routes/workflows/components/scheduleParameters";
import { useScheduleParameterState } from "@/routes/workflows/hooks/useScheduleParameterState";
import {
- CRON_PRESETS,
- cronToHumanReadable,
- isValidCron,
- getNextRuns,
- formatNextRun,
- getTimezones,
getLocalTimezone,
+ isValidCron,
+ meetsMinCronInterval,
} from "./cronUtils";
-import { cn } from "@/util/utils";
type Props = {
workflowParameters: ReadonlyArray<Parameter>;
@@ -48,7 +44,6 @@ function CreateScheduleDialog({
const [open, setOpen] = useState(false);
const [cronExpression, setCronExpression] = useState("0 9 * * *");
const [timezone, setTimezone] = useState(getLocalTimezone);
- const [timezoneFilter, setTimezoneFilter] = useState<string | null>(null);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const {
@@ -71,22 +66,12 @@ function CreateScheduleDialog({
}
}, [open, workflowParameters, resetParameters]);
- const allTimezones = useMemo(() => getTimezones(), []);
- const filteredTimezones = useMemo(() => {
- if (timezoneFilter === null) return allTimezones;
- if (!timezoneFilter) return allTimezones;
- const lower = timezoneFilter.toLowerCase();
- return allTimezones.filter((tz) => tz.toLowerCase().includes(lower));
- }, [allTimezones, timezoneFilter]);
-
const valid = isValidCron(cronExpression);
- const humanReadable = valid ? cronToHumanReadable(cronExpression) : null;
- const nextRuns = valid ? getNextRuns(cronExpression, timezone, 5) : [];
+ const cronAccepted = valid && meetsMinCronInterval(cronExpression);
function resetFormState() {
setCronExpression("0 9 * * *");
setTimezone(getLocalTimezone());
- setTimezoneFilter(null);
setName("");
setDescription("");
resetParameters();
@@ -94,7 +79,7 @@ function CreateScheduleDialog({
function handleSubmit() {
const parametersValid = validateParameters();
- if (!valid || !parametersValid) return;
+ if (!cronAccepted || !parametersValid) return;
const payload = buildScheduleParametersPayload(
parameters,
workflowParameters,
@@ -155,115 +140,20 @@ function CreateScheduleDialog({
disabled={isPending}
/>
- <div className="space-y-2">
- <Label>Quick Presets</Label>
- <div className="flex flex-wrap gap-2">
- {CRON_PRESETS.map((preset) => (
- <Button
- key={preset.label}
- variant={
- cronExpression === preset.expression
- ? "default"
- : "secondary"
- }
- size="sm"
- onClick={() => setCronExpression(preset.expression)}
- >
- {preset.label}
- </Button>
- ))}
- </div>
- </div>
-
- <div className="space-y-2">
- <Label>Cron Expression</Label>
- <Input
- value={cronExpression}
- onChange={(e) => setCronExpression(e.target.value)}
- placeholder="* * * * *"
- className={cn(!valid && cronExpression && "border-destructive")}
- />
- {humanReadable && (
- <p className="text-sm text-muted-foreground">{humanReadable}</p>
- )}
- {!valid && cronExpression && (
- <p className="text-sm text-destructive">
- Invalid cron expression
- </p>
- )}
- </div>
-
- <div className="space-y-2">
- <Label>Timezone</Label>
- <Input
- value={timezoneFilter ?? timezone}
- onChange={(e) => setTimezoneFilter(e.target.value)}
- onFocus={(e) => e.currentTarget.select()}
- onBlur={() => {
- if (
- filteredTimezones.length === 1 &&
- filteredTimezones[0] !== undefined
- ) {
- setTimezone(filteredTimezones[0]);
- }
- setTimezoneFilter(null);
- }}
- placeholder="Search timezones..."
- />
- {timezoneFilter !== null && (
- <div className="max-h-40 overflow-y-auto rounded-md border border-border bg-slate-elevation3">
- {filteredTimezones.slice(0, 20).map((tz) => (
- <button
- key={tz}
- type="button"
- className={cn(
- "w-full px-3 py-1.5 text-left text-sm hover:bg-muted dark:hover:bg-slate-700",
- tz === timezone &&
- "bg-muted text-foreground dark:bg-slate-700",
- )}
- onMouseDown={(e) => {
- e.preventDefault();
- setTimezone(tz);
- setTimezoneFilter(null);
- }}
- >
- {tz}
- </button>
- ))}
- {filteredTimezones.length === 0 && (
- <div className="px-3 py-2 text-sm text-muted-foreground dark:text-slate-500">
- No timezones found
- </div>
- )}
- </div>
- )}
- <p className="text-xs text-muted-foreground dark:text-slate-500">
- Current: {timezone}
- </p>
- </div>
-
- {nextRuns.length > 0 && (
- <div className="space-y-2">
- <Label>Next Scheduled Runs</Label>
- <div className="space-y-1 rounded-md border border-border bg-slate-elevation3 p-3">
- {nextRuns.map((run) => (
- <div
- key={run.toISOString()}
- className="text-xs text-muted-foreground"
- >
- {formatNextRun(run, timezone)}
- </div>
- ))}
- </div>
- </div>
- )}
+ <ScheduleConfigFields
+ cronExpression={cronExpression}
+ timezone={timezone}
+ onCronChange={setCronExpression}
+ onTimezoneChange={setTimezone}
+ disabled={isPending}
+ />
</div>
<DialogFooter>
<Button variant="secondary" onClick={() => setOpen(false)}>
Cancel
</Button>
- <Button disabled={!valid || isPending} onClick={handleSubmit}>
+ <Button disabled={!cronAccepted || isPending} onClick={handleSubmit}>
{isPending ? "Creating..." : "Create Schedule"}
</Button>
</DialogFooter>
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleBuilder.test.ts b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleBuilder.test.ts
new file mode 100644
index 000000000..fb9911503
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleBuilder.test.ts
@@ -0,0 +1,180 @@
+import { describe, expect, it } from "vitest";
+import {
+ cronToScheduleBuilder,
+ scheduleBuilderToCron,
+ scheduleBuildersEquivalent,
+ to12Hour,
+ to24Hour,
+ type ScheduleBuilderState,
+} from "./scheduleBuilder";
+
+describe("scheduleBuilderToCron", () => {
+ it("builds an hourly expression from the minute only", () => {
+ expect(
+ scheduleBuilderToCron({
+ frequency: "hourly",
+ minute: 15,
+ hour: 9,
+ daysOfWeek: [1],
+ dayOfMonth: 1,
+ }),
+ ).toBe("15 * * * *");
+ });
+
+ it("builds a daily expression", () => {
+ expect(
+ scheduleBuilderToCron({
+ frequency: "daily",
+ minute: 0,
+ hour: 9,
+ daysOfWeek: [1],
+ dayOfMonth: 1,
+ }),
+ ).toBe("0 9 * * *");
+ });
+
+ it("builds a weekly expression with a sorted, de-duplicated day list", () => {
+ expect(
+ scheduleBuilderToCron({
+ frequency: "weekly",
+ minute: 30,
+ hour: 8,
+ daysOfWeek: [5, 1, 3, 1],
+ dayOfMonth: 1,
+ }),
+ ).toBe("30 8 * * 1,3,5");
+ });
+
+ it("builds a monthly expression", () => {
+ expect(
+ scheduleBuilderToCron({
+ frequency: "monthly",
+ minute: 0,
+ hour: 9,
+ daysOfWeek: [1],
+ dayOfMonth: 15,
+ }),
+ ).toBe("0 9 15 * *");
+ });
+});
+
+describe("cronToScheduleBuilder", () => {
+ it("parses the hourly preset", () => {
+ expect(cronToScheduleBuilder("0 * * * *")).toMatchObject({
+ frequency: "hourly",
+ minute: 0,
+ });
+ });
+
+ it("parses the daily preset", () => {
+ expect(cronToScheduleBuilder("0 9 * * *")).toMatchObject({
+ frequency: "daily",
+ minute: 0,
+ hour: 9,
+ });
+ });
+
+ it("parses the weekdays preset (range form) into a day set", () => {
+ expect(cronToScheduleBuilder("0 9 * * 1-5")).toMatchObject({
+ frequency: "weekly",
+ minute: 0,
+ hour: 9,
+ daysOfWeek: [1, 2, 3, 4, 5],
+ });
+ });
+
+ it("parses a weekly preset with a single day", () => {
+ expect(cronToScheduleBuilder("0 9 * * 1")).toMatchObject({
+ frequency: "weekly",
+ daysOfWeek: [1],
+ });
+ });
+
+ it("parses a comma list and normalizes 7 to 0 (Sunday)", () => {
+ expect(cronToScheduleBuilder("0 9 * * 7,3")).toMatchObject({
+ frequency: "weekly",
+ daysOfWeek: [0, 3],
+ });
+ });
+
+ it("parses the monthly preset", () => {
+ expect(cronToScheduleBuilder("0 9 1 * *")).toMatchObject({
+ frequency: "monthly",
+ minute: 0,
+ hour: 9,
+ dayOfMonth: 1,
+ });
+ });
+
+ it("returns null for stepped/complex expressions (custom)", () => {
+ expect(cronToScheduleBuilder("*/5 * * * *")).toBeNull();
+ expect(cronToScheduleBuilder("0 9 * 1 *")).toBeNull(); // constrained month
+ expect(cronToScheduleBuilder("0 9-17 * * *")).toBeNull(); // hour range
+ expect(cronToScheduleBuilder("0 9 15 * 1")).toBeNull(); // dom AND dow
+ expect(cronToScheduleBuilder("not a cron")).toBeNull();
+ });
+
+ it("round-trips every supported preset", () => {
+ for (const expression of [
+ "0 * * * *",
+ "0 9 * * *",
+ "0 9 * * 1",
+ "0 9 1 * *",
+ ]) {
+ const builder = cronToScheduleBuilder(expression);
+ expect(builder).not.toBeNull();
+ expect(scheduleBuilderToCron(builder as ScheduleBuilderState)).toBe(
+ expression,
+ );
+ }
+ });
+});
+
+describe("time conversion", () => {
+ it("converts 24h to 12h", () => {
+ expect(to12Hour(0)).toEqual({ hour12: 12, meridiem: "AM" });
+ expect(to12Hour(9)).toEqual({ hour12: 9, meridiem: "AM" });
+ expect(to12Hour(12)).toEqual({ hour12: 12, meridiem: "PM" });
+ expect(to12Hour(23)).toEqual({ hour12: 11, meridiem: "PM" });
+ });
+
+ it("converts 12h back to 24h", () => {
+ expect(to24Hour(12, "AM")).toBe(0);
+ expect(to24Hour(9, "AM")).toBe(9);
+ expect(to24Hour(12, "PM")).toBe(12);
+ expect(to24Hour(11, "PM")).toBe(23);
+ });
+});
+
+describe("scheduleBuildersEquivalent", () => {
+ it("ignores fields not relevant to the frequency", () => {
+ const a: ScheduleBuilderState = {
+ frequency: "daily",
+ minute: 0,
+ hour: 9,
+ daysOfWeek: [3],
+ dayOfMonth: 15,
+ };
+ const b: ScheduleBuilderState = {
+ frequency: "daily",
+ minute: 0,
+ hour: 9,
+ daysOfWeek: [1],
+ dayOfMonth: 1,
+ };
+ expect(scheduleBuildersEquivalent(a, b)).toBe(true);
+ });
+
+ it("distinguishes different weekly day sets", () => {
+ const base: ScheduleBuilderState = {
+ frequency: "weekly",
+ minute: 0,
+ hour: 9,
+ daysOfWeek: [1, 2],
+ dayOfMonth: 1,
+ };
+ expect(
+ scheduleBuildersEquivalent(base, { ...base, daysOfWeek: [1, 3] }),
+ ).toBe(false);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleBuilder.ts b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleBuilder.ts
new file mode 100644
index 000000000..b14b59e14
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleBuilder.ts
@@ -0,0 +1,191 @@
+export type ScheduleFrequency = "hourly" | "daily" | "weekly" | "monthly";
+
+export type ScheduleBuilderState = {
+ frequency: ScheduleFrequency;
+ minute: number;
+ hour: number;
+ daysOfWeek: number[];
+ dayOfMonth: number;
+};
+
+export const DEFAULT_SCHEDULE_BUILDER: ScheduleBuilderState = {
+ frequency: "daily",
+ minute: 0,
+ hour: 9,
+ daysOfWeek: [1],
+ dayOfMonth: 1,
+};
+
+export const DAY_OF_WEEK_OPTIONS: ReadonlyArray<{
+ value: number;
+ short: string;
+ label: string;
+}> = [
+ { value: 0, short: "S", label: "Sunday" },
+ { value: 1, short: "M", label: "Monday" },
+ { value: 2, short: "T", label: "Tuesday" },
+ { value: 3, short: "W", label: "Wednesday" },
+ { value: 4, short: "T", label: "Thursday" },
+ { value: 5, short: "F", label: "Friday" },
+ { value: 6, short: "S", label: "Saturday" },
+];
+
+export function to12Hour(hour24: number): {
+ hour12: number;
+ meridiem: "AM" | "PM";
+} {
+ const meridiem = hour24 < 12 ? "AM" : "PM";
+ const base = hour24 % 12;
+ return { hour12: base === 0 ? 12 : base, meridiem };
+}
+
+export function to24Hour(hour12: number, meridiem: "AM" | "PM"): number {
+ if (meridiem === "AM") {
+ return hour12 === 12 ? 0 : hour12;
+ }
+ return hour12 === 12 ? 12 : hour12 + 12;
+}
+
+export function scheduleBuilderToCron(builder: ScheduleBuilderState): string {
+ const { frequency, minute, hour, daysOfWeek, dayOfMonth } = builder;
+ switch (frequency) {
+ case "hourly":
+ return `${minute} * * * *`;
+ case "daily":
+ return `${minute} ${hour} * * *`;
+ case "weekly": {
+ const days = [...new Set(daysOfWeek)].sort((a, b) => a - b);
+ const dow = days.length > 0 ? days.join(",") : "*";
+ return `${minute} ${hour} * * ${dow}`;
+ }
+ case "monthly":
+ return `${minute} ${hour} ${dayOfMonth} * *`;
+ }
+}
+
+function parseSingleInt(
+ field: string,
+ min: number,
+ max: number,
+): number | null {
+ if (!/^\d+$/.test(field)) return null;
+ const value = Number(field);
+ if (value < min || value > max) return null;
+ return value;
+}
+
+// Expands a day-of-week field (single, comma list, and/or a-b ranges; 7 -> 0)
+// into a sorted, de-duplicated set. Returns null for steps ("*/2"), "*", or any
+// token outside 0-7 so callers fall back to the raw cron ("Custom") path.
+function parseDaysOfWeek(field: string): number[] | null {
+ if (field === "*" || field.includes("/")) return null;
+ const days = new Set<number>();
+ for (const token of field.split(",")) {
+ const range = token.match(/^(\d+)-(\d+)$/);
+ if (range) {
+ const start = Number(range[1]);
+ const end = Number(range[2]);
+ if (start > end) return null;
+ for (let d = start; d <= end; d++) {
+ if (d < 0 || d > 7) return null;
+ days.add(d === 7 ? 0 : d);
+ }
+ continue;
+ }
+ if (!/^\d+$/.test(token)) return null;
+ const value = Number(token);
+ if (value < 0 || value > 7) return null;
+ days.add(value === 7 ? 0 : value);
+ }
+ if (days.size === 0) return null;
+ return [...days].sort((a, b) => a - b);
+}
+
+// Parses a cron expression into builder state when it maps cleanly onto one of
+// the supported recurrence shapes (hourly / daily / weekly / monthly). Returns
+// null for anything else so the UI keeps it as a raw "Custom" expression.
+export function cronToScheduleBuilder(
+ expression: string,
+): ScheduleBuilderState | null {
+ const parts = expression.trim().split(/\s+/);
+ if (parts.length !== 5) return null;
+ const [minuteField, hourField, domField, monthField, dowField] = parts as [
+ string,
+ string,
+ string,
+ string,
+ string,
+ ];
+ if (monthField !== "*") return null;
+
+ const minute = parseSingleInt(minuteField, 0, 59);
+ if (minute === null) return null;
+
+ if (hourField === "*" && domField === "*" && dowField === "*") {
+ return { ...DEFAULT_SCHEDULE_BUILDER, frequency: "hourly", minute };
+ }
+
+ const hour = parseSingleInt(hourField, 0, 23);
+ if (hour === null) return null;
+
+ if (domField === "*" && dowField === "*") {
+ return { ...DEFAULT_SCHEDULE_BUILDER, frequency: "daily", minute, hour };
+ }
+
+ if (domField === "*" && dowField !== "*") {
+ const daysOfWeek = parseDaysOfWeek(dowField);
+ if (!daysOfWeek) return null;
+ return {
+ ...DEFAULT_SCHEDULE_BUILDER,
+ frequency: "weekly",
+ minute,
+ hour,
+ daysOfWeek,
+ };
+ }
+
+ if (dowField === "*" && domField !== "*") {
+ const dayOfMonth = parseSingleInt(domField, 1, 31);
+ if (dayOfMonth === null) return null;
+ return {
+ ...DEFAULT_SCHEDULE_BUILDER,
+ frequency: "monthly",
+ minute,
+ hour,
+ dayOfMonth,
+ };
+ }
+
+ return null;
+}
+
+// Compares only the fields that matter for a given frequency, so re-parsing a
+// generated cron (which resets unshown fields to defaults) doesn't clobber a
+// user's earlier selections or spin a render loop.
+export function scheduleBuildersEquivalent(
+ a: ScheduleBuilderState,
+ b: ScheduleBuilderState,
+): boolean {
+ if (a.frequency !== b.frequency) return false;
+ switch (a.frequency) {
+ case "hourly":
+ return a.minute === b.minute;
+ case "daily":
+ return a.minute === b.minute && a.hour === b.hour;
+ case "weekly": {
+ if (a.minute !== b.minute || a.hour !== b.hour) return false;
+ const aDays = [...new Set(a.daysOfWeek)].sort((x, y) => x - y);
+ const bDays = [...new Set(b.daysOfWeek)].sort((x, y) => x - y);
+ return (
+ aDays.length === bDays.length &&
+ aDays.every((day, index) => day === bDays[index])
+ );
+ }
+ case "monthly":
+ return (
+ a.minute === b.minute &&
+ a.hour === b.hour &&
+ a.dayOfMonth === b.dayOfMonth
+ );
+ }
+}
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
index 17c91da72..d8299e32d 100644
--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
@@ -915,6 +915,27 @@ function convertToNode(
maxStepsOverride: block.max_steps_per_run ?? null,
engine: block.engine ?? RunEngine.SkyvernV1,
downloadTimeout: block.download_timeout ?? null, // seconds
+ downloadTarget: block.download_target ?? "website",
+ path: block.path ?? "{{ workflow_run_id }}",
+ prompt: block.prompt ?? null,
+ s3Bucket: block.s3_bucket ?? "",
+ awsAccessKeyId: block.aws_access_key_id ?? "",
+ awsSecretAccessKey: block.aws_secret_access_key ?? "",
+ regionName: block.region_name ?? "",
+ azureStorageAccountName: block.azure_storage_account_name ?? "",
+ azureStorageAccountKey: block.azure_storage_account_key ?? "",
+ azureBlobContainerName: block.azure_blob_container_name ?? "",
+ googleCredentialId: block.google_credential_id ?? "",
+ googleDriveFolderId: block.google_drive_folder_id ?? "",
+ sftpHost: block.sftp_host ?? "",
+ sftpPort: block.sftp_port != null ? String(block.sftp_port) : "",
+ sftpUsername: block.sftp_username ?? "",
+ sftpPassword: block.sftp_password ?? "",
+ sftpPrivateKey: block.sftp_private_key ?? "",
+ sftpPrivateKeyPassphrase: block.sftp_private_key_passphrase ?? "",
+ sftpRemotePath: block.sftp_remote_path ?? "",
+ sftpHostKey: block.sftp_host_key ?? "",
+ continueOnEmpty: block.continue_on_empty ?? false,
},
};
}
@@ -3069,6 +3090,44 @@ function getWorkflowBlock(
disable_cache: node.data.disableCache ?? false,
engine: node.data.engine,
download_timeout: node.data.downloadTimeout, // seconds
+ ...(node.data.downloadTarget &&
+ node.data.downloadTarget !== "website" && {
+ download_target: node.data.downloadTarget,
+ path: node.data.path,
+ prompt: node.data.prompt,
+ continue_on_empty: node.data.continueOnEmpty ?? false,
+ ...(node.data.downloadTarget === "s3" && {
+ s3_bucket: node.data.s3Bucket ?? "",
+ aws_access_key_id: node.data.awsAccessKeyId ?? "",
+ aws_secret_access_key: node.data.awsSecretAccessKey ?? "",
+ region_name: node.data.regionName ?? "",
+ }),
+ ...(node.data.downloadTarget === "azure" && {
+ azure_storage_account_name:
+ node.data.azureStorageAccountName ?? "",
+ azure_storage_account_key: node.data.azureStorageAccountKey ?? "",
+ azure_blob_container_name: node.data.azureBlobContainerName ?? "",
+ }),
+ ...(node.data.downloadTarget === "google_drive" && {
+ google_credential_id: node.data.googleCredentialId ?? "",
+ google_drive_folder_id: node.data.googleDriveFolderId ?? "",
+ }),
+ ...(node.data.downloadTarget === "sftp" && {
+ sftp_host: node.data.sftpHost ?? "",
+ sftp_port:
+ node.data.sftpPort &&
+ Number.isFinite(Number(node.data.sftpPort))
+ ? Number(node.data.sftpPort)
+ : null,
+ sftp_username: node.data.sftpUsername ?? "",
+ sftp_password: node.data.sftpPassword ?? "",
+ sftp_private_key: node.data.sftpPrivateKey ?? "",
+ sftp_private_key_passphrase:
+ node.data.sftpPrivateKeyPassphrase ?? "",
+ sftp_remote_path: node.data.sftpRemotePath ?? "",
+ sftp_host_key: node.data.sftpHostKey ?? "",
+ }),
+ }),
};
}
case "sendEmail": {
@@ -4433,6 +4492,42 @@ function convertBlocksToBlockYAML(
disable_cache: block.disable_cache ?? false,
engine: block.engine,
download_timeout: null, // seconds
+ ...(block.download_target &&
+ block.download_target !== "website" && {
+ download_target: block.download_target,
+ path: block.path,
+ prompt: block.prompt,
+ continue_on_empty: block.continue_on_empty ?? false,
+ ...(block.download_target === "s3" && {
+ s3_bucket: block.s3_bucket ?? "",
+ aws_access_key_id: block.aws_access_key_id ?? "",
+ aws_secret_access_key: block.aws_secret_access_key ?? "",
+ region_name: block.region_name ?? "",
+ }),
+ ...(block.download_target === "azure" && {
+ azure_storage_account_name:
+ block.azure_storage_account_name ?? "",
+ azure_storage_account_key:
+ block.azure_storage_account_key ?? "",
+ azure_blob_container_name:
+ block.azure_blob_container_name ?? "",
+ }),
+ ...(block.download_target === "google_drive" && {
+ google_credential_id: block.google_credential_id ?? "",
+ google_drive_folder_id: block.google_drive_folder_id ?? "",
+ }),
+ ...(block.download_target === "sftp" && {
+ sftp_host: block.sftp_host ?? "",
+ sftp_port: block.sftp_port ?? null,
+ sftp_username: block.sftp_username ?? "",
+ sftp_password: block.sftp_password ?? "",
+ sftp_private_key: block.sftp_private_key ?? "",
+ sftp_private_key_passphrase:
+ block.sftp_private_key_passphrase ?? "",
+ sftp_remote_path: block.sftp_remote_path ?? "",
+ sftp_host_key: block.sftp_host_key ?? "",
+ }),
+ }),
};
return blockYaml;
}
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.ts
new file mode 100644
index 000000000..c8a7cde33
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/useRunHealEpisodesQuery.ts
@@ -0,0 +1,53 @@
+import { useEffect, useRef } from "react";
+import { getClient } from "@/api/AxiosClient";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { statusIsNotFinalized } from "@/routes/tasks/types";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import type { RunHealEpisodesResponse } from "../types/healTypes";
+import { useWorkflowRunWithWorkflowQuery } from "./useWorkflowRunWithWorkflowQuery";
+
+type UseRunHealEpisodesQueryOptions = {
+ workflowRunId?: string;
+ enabled?: boolean;
+};
+
+function useRunHealEpisodesQuery({
+ workflowRunId,
+ enabled = true,
+}: UseRunHealEpisodesQueryOptions) {
+ const credentialGetter = useCredentialGetter();
+ const queryClient = useQueryClient();
+ const { data: workflowRun, dataUpdatedAt } = useWorkflowRunWithWorkflowQuery({
+ 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);
+ useEffect(() => {
+ if (dataUpdatedAt !== prevDataUpdatedAtRef.current && workflowRunId) {
+ queryClient.invalidateQueries({
+ queryKey: ["run-heal-episodes", workflowRunId],
+ });
+ }
+ prevDataUpdatedAtRef.current = dataUpdatedAt;
+ }, [dataUpdatedAt, workflowRunId, queryClient]);
+
+ return useQuery<RunHealEpisodesResponse>({
+ queryKey: ["run-heal-episodes", workflowRunId],
+ queryFn: async () => {
+ const client = await getClient(credentialGetter, "sans-api-v1");
+ return client
+ .get<RunHealEpisodesResponse>(`/runs/${workflowRunId}/heal_episodes`)
+ .then((response) => response.data);
+ },
+ refetchOnMount:
+ workflowRun && statusIsNotFinalized(workflowRun) ? "always" : false,
+ refetchOnWindowFocus:
+ workflowRun && statusIsNotFinalized(workflowRun) ? "always" : false,
+ enabled: Boolean(workflowRunId) && enabled,
+ });
+}
+
+export { useRunHealEpisodesQuery };
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioPaneDefaults.test.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioPaneDefaults.test.tsx
index d27aff4ae..7047dd60e 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioPaneDefaults.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioPaneDefaults.test.tsx
@@ -82,19 +82,19 @@ beforeEach(() => {
});
describe("cold-entry default panes (the four contexts)", () => {
- test("an empty agent starts on Copilot + Browser", () => {
+ test("an empty agent starts on Editor + Browser", () => {
renderStudio({ hasBlocks: false });
- expect(panesText()).toBe("copilot,browser");
+ expect(panesText()).toBe("editor,browser");
});
- test("a built agent starts on Copilot + Browser + Editor", () => {
+ test("a built agent also starts on Editor + Browser", () => {
renderStudio({ hasBlocks: true });
- expect(panesText()).toBe("copilot,browser,editor");
+ expect(panesText()).toBe("editor,browser");
});
- test("a run in the URL lands on Copilot + Browser + Overview", () => {
+ test("a run in the URL lands on Browser + Overview", () => {
renderStudio({ path: "/workflows/wpid_1/studio?wr=wr_1" });
- expect(panesText()).toBe("copilot,browser,overview");
+ expect(panesText()).toBe("browser,overview");
});
test("a block-run deep link lands on Editor + Browser + Overview", () => {
@@ -104,7 +104,7 @@ describe("cold-entry default panes (the four contexts)", () => {
test("a blocks signal that changes after mount does not reshuffle the panes", () => {
const { rerender } = renderStudio({ hasBlocks: false });
- expect(panesText()).toBe("copilot,browser");
+ expect(panesText()).toBe("editor,browser");
rerender(
<MemoryRouter initialEntries={["/workflows/wpid_1/studio"]}>
<StudioPaneDefaultsProvider hasBlocks={true}>
@@ -112,7 +112,7 @@ describe("cold-entry default panes (the four contexts)", () => {
</StudioPaneDefaultsProvider>
</MemoryRouter>,
);
- expect(panesText()).toBe("copilot,browser");
+ expect(panesText()).toBe("editor,browser");
});
test("an explicit ?panes= is never overridden by the state default", () => {
@@ -127,8 +127,8 @@ describe("cold-entry default panes (the four contexts)", () => {
test("toggling from the state default writes the default plus the change", () => {
renderStudio({ hasBlocks: false });
- fireEvent.click(screen.getByText("open-editor"));
- expect(panesText()).toBe("copilot,browser,editor");
+ fireEvent.click(screen.getByText("toggle-overview"));
+ expect(panesText()).toBe("editor,browser,overview");
});
});
@@ -233,9 +233,8 @@ describe("gesture learning — edit-class writes reach the store", () => {
test("a gesture toggle on an edit URL learns the resulting layout", () => {
renderGestureStudio();
fireEvent.click(screen.getByText("gesture-toggle-editor"));
- // default built-agent: copilot,browser,editor → toggle closes editor → copilot,browser
+ // default built-agent: editor,browser → toggle closes editor → browser
expect(useStudioShellStore.getState().paneLayouts["edit"]).toEqual([
- "copilot",
"browser",
]);
});
@@ -268,18 +267,20 @@ describe("gesture learning — edit-class writes reach the store", () => {
describe("restore from learned edit layout", () => {
test("a built agent restores the last learned edit layout", () => {
- // Pre-seed the store as if the user previously arranged their panes.
- useStudioShellStore.getState().setPaneLayout("edit", ["editor", "browser"]);
+ // Pre-seed a layout distinct from the factory default so the restore is provable.
+ useStudioShellStore.getState().setPaneLayout("edit", ["browser", "editor"]);
renderStudio({ hasBlocks: true });
- expect(panesText()).toBe("editor,browser");
+ expect(panesText()).toBe("browser,editor");
});
test("an empty agent ignores the learned layout and always shows factory default", () => {
- useStudioShellStore.getState().setPaneLayout("edit", ["editor", "browser"]);
+ useStudioShellStore
+ .getState()
+ .setPaneLayout("edit", ["overview", "browser"]);
renderStudio({ hasBlocks: false });
- expect(panesText()).toBe("copilot,browser");
+ expect(panesText()).toBe("editor,browser");
});
test("an explicit ?panes= beats the learned layout", () => {
@@ -293,7 +294,7 @@ describe("restore from learned edit layout", () => {
useStudioShellStore.getState().setPaneLayout("edit", ["editor", "browser"]);
renderStudio({ path: "/workflows/wpid_1/studio?wr=wr_1" });
- expect(panesText()).toBe("copilot,browser,overview");
+ expect(panesText()).toBe("browser,overview");
});
test("a learned layout with an unknown pane id is sanitized to known ids only", () => {
@@ -314,7 +315,7 @@ describe("restore from learned edit layout", () => {
});
renderStudio({ hasBlocks: true });
- expect(panesText()).toBe("copilot,browser,editor");
+ expect(panesText()).toBe("editor,browser");
});
test("a corrupted non-array learned layout falls back without throwing", () => {
@@ -323,6 +324,6 @@ describe("restore from learned edit layout", () => {
});
renderStudio({ hasBlocks: true });
- expect(panesText()).toBe("copilot,browser,editor");
+ expect(panesText()).toBe("editor,browser");
});
});
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioPaneDefaults.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioPaneDefaults.tsx
index 1a6e5ac17..18d8f8770 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioPaneDefaults.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioPaneDefaults.tsx
@@ -7,7 +7,7 @@ import { useStudioShellStore } from "@/store/StudioShellStore";
import { liveSearch } from "./liveSearch";
import {
- defaultPanesForWorkflowState,
+ DEFAULT_STUDIO_PANES,
fitPanesToWidth,
panesFitWidth,
resolveOpenPanes,
@@ -45,8 +45,7 @@ function sanitizeLearnedPanes(
* loaded — so the latch decides from real data, never a placeholder.
*
* Built agents restore the user's last edit-class pane arrangement; empty
- * agents always start on the factory prompt-and-watch default (deliberate
- * first-run experience).
+ * agents always start on the factory Editor + Browser default.
*/
export function StudioPaneDefaultsProvider({
hasBlocks,
@@ -57,14 +56,16 @@ export function StudioPaneDefaultsProvider({
}) {
const location = useLocation();
+ // hasBlocks gates only the learned-layout lookup, not the factory default
+ // itself — empty agents never restore a saved arrangement.
const [defaultPanes] = useState<readonly StudioPaneId[]>(() => {
if (!hasBlocks) {
- return defaultPanesForWorkflowState({ hasBlocks });
+ return [...DEFAULT_STUDIO_PANES];
}
const learnedEdit = sanitizeLearnedPanes(
useStudioShellStore.getState().paneLayouts["edit"],
);
- return learnedEdit ?? defaultPanesForWorkflowState({ hasBlocks });
+ return learnedEdit ?? [...DEFAULT_STUDIO_PANES];
});
const [learnedRunPanes] = useState<readonly StudioPaneId[] | null>(() =>
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioPaneToggles.test.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioPaneToggles.test.tsx
index 6a578dd2b..aff1286bc 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioPaneToggles.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioPaneToggles.test.tsx
@@ -66,11 +66,11 @@ describe("StudioPaneToggles structure", () => {
}
});
- test("reflects the default panes (copilot + browser) as expanded", () => {
+ test("reflects the default panes (editor + browser) as expanded", () => {
renderAt();
- expect(tab(/^Copilot/).getAttribute("aria-expanded")).toBe("true");
+ expect(tab(/^Editor/).getAttribute("aria-expanded")).toBe("true");
expect(tab(/^Browser/).getAttribute("aria-expanded")).toBe("true");
- expect(tab(/^Editor/).getAttribute("aria-expanded")).toBe("false");
+ expect(tab(/^Copilot/).getAttribute("aria-expanded")).toBe("false");
});
test("reflects an explicit ?panes= list", () => {
@@ -99,9 +99,9 @@ describe("StudioPaneToggles structure", () => {
describe("StudioPaneToggles pane toggling", () => {
test("opening a closed pane appends it in click order", () => {
renderAt();
- fireEvent.click(tab(/^Editor/));
- expect(currentPanes()).toBe("copilot,browser,editor");
- expect(tab(/^Editor/).getAttribute("aria-expanded")).toBe("true");
+ fireEvent.click(tab(/^Copilot/));
+ expect(currentPanes()).toBe("editor,browser,copilot");
+ expect(tab(/^Copilot/).getAttribute("aria-expanded")).toBe("true");
});
test("closing an open pane splices it out, keeping the rest in order", () => {
@@ -235,6 +235,6 @@ describe("StudioPaneToggles keyboard navigation", () => {
renderAt();
fireEvent.keyDown(tab(/^Copilot/), { key: "ArrowRight" });
expect(currentPanes()).toBeNull();
- expect(tab(/^Editor/).getAttribute("aria-expanded")).toBe("false");
+ expect(tab(/^Editor/).getAttribute("aria-expanded")).toBe("true");
});
});
diff --git a/skyvern-frontend/src/routes/workflows/studio/paneLayout.test.ts b/skyvern-frontend/src/routes/workflows/studio/paneLayout.test.ts
index 2c0c5ee7a..c534fca03 100644
--- a/skyvern-frontend/src/routes/workflows/studio/paneLayout.test.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/paneLayout.test.ts
@@ -9,6 +9,7 @@ import {
paneResizable,
paneWidthsKey,
STUDIO_PANE_DEFAULT_WIDTH,
+ STUDIO_TWO_PANE_SIDE_BASIS,
} from "./paneLayout";
import { STUDIO_PANE_MIN_WIDTH, type StudioPaneId } from "./panes";
@@ -92,8 +93,44 @@ describe("paneFlex", () => {
);
});
+ test("a two-pane default gives the side pane ~35% and the browser the rest", () => {
+ expect(paneFlex("editor", ["editor", "browser"], noWidths)).toBe(
+ `0 1 ${STUDIO_TWO_PANE_SIDE_BASIS}`,
+ );
+ expect(paneFlex("browser", ["editor", "browser"], noWidths)).toBe("1 1 0%");
+ expect(paneFlex("overview", ["browser", "overview"], noWidths)).toBe(
+ `0 1 ${STUDIO_TWO_PANE_SIDE_BASIS}`,
+ );
+ expect(paneFlex("browser", ["browser", "overview"], noWidths)).toBe(
+ "1 1 0%",
+ );
+ });
+
+ test("the ~35% side split holds for any greedy two-pane row, not just the factory combos", () => {
+ expect(paneFlex("editor", ["copilot", "editor"], noWidths)).toBe("1 1 0%");
+ expect(paneFlex("copilot", ["copilot", "editor"], noWidths)).toBe(
+ `0 1 ${STUDIO_TWO_PANE_SIDE_BASIS}`,
+ );
+ });
+
+ test("a third pane reverts the side panes to the fixed default", () => {
+ const panes: StudioPaneId[] = ["editor", "browser", "overview"];
+ expect(paneFlex("editor", panes, noWidths)).toBe(
+ `0 1 ${STUDIO_PANE_DEFAULT_WIDTH}px`,
+ );
+ expect(paneFlex("overview", panes, noWidths)).toBe(
+ `0 1 ${STUDIO_PANE_DEFAULT_WIDTH}px`,
+ );
+ });
+
+ test("a pinned width still wins over the two-pane default", () => {
+ expect(paneFlex("editor", ["editor", "browser"], { editor: 480 })).toBe(
+ "0 1 480px",
+ );
+ });
+
test("garbage persisted widths fall back to the default", () => {
- const panes: StudioPaneId[] = ["copilot", "browser"];
+ const panes: StudioPaneId[] = ["copilot", "browser", "editor"];
expect(paneFlex("copilot", panes, { copilot: Number.NaN })).toBe(
`0 1 ${STUDIO_PANE_DEFAULT_WIDTH}px`,
);
diff --git a/skyvern-frontend/src/routes/workflows/studio/paneLayout.ts b/skyvern-frontend/src/routes/workflows/studio/paneLayout.ts
index dccaa9eff..0b0a93881 100644
--- a/skyvern-frontend/src/routes/workflows/studio/paneLayout.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/paneLayout.ts
@@ -11,6 +11,11 @@ export type { PaneWidths };
// rest of the row.
export const STUDIO_PANE_DEFAULT_WIDTH = 300;
+// The unpinned side pane of ANY two-pane row with a greedy pane opens at this
+// share, so the greedy pane keeps ~65% — mirrors the legacy split on the
+// factory defaults (editor+browser, browser+overview).
+export const STUDIO_TWO_PANE_SIDE_BASIS = "35%";
+
// 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(
@@ -58,9 +63,14 @@ export function paneFlex(
if (pinned !== undefined) {
return `0 1 ${pinned}px`;
}
- // Without a greedy pane, unpinned panes share the free space equally.
- return greedy === undefined
- ? `1 1 ${STUDIO_PANE_DEFAULT_WIDTH}px`
+ if (greedy === undefined) {
+ // Without a greedy pane, unpinned panes share the free space equally.
+ return `1 1 ${STUDIO_PANE_DEFAULT_WIDTH}px`;
+ }
+ // Any two-pane row gives the unpinned side pane ~35% (the greedy pane keeps
+ // ~65%); 3+ panes keep the fixed default so the greedy pane isn't starved.
+ return panes.length === 2
+ ? `0 1 ${STUDIO_TWO_PANE_SIDE_BASIS}`
: `0 1 ${STUDIO_PANE_DEFAULT_WIDTH}px`;
}
diff --git a/skyvern-frontend/src/routes/workflows/studio/panes.test.ts b/skyvern-frontend/src/routes/workflows/studio/panes.test.ts
index f38469515..91b869a88 100644
--- a/skyvern-frontend/src/routes/workflows/studio/panes.test.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/panes.test.ts
@@ -7,7 +7,6 @@ import {
STUDIO_STAGE_GAP_PX,
STUDIO_STAGE_PADDING_PX,
STUDIO_PANE_MIN_WIDTH,
- defaultPanesForWorkflowState,
fitPanesToWidth,
layoutClassForSearch,
panesFitWidth,
@@ -77,16 +76,16 @@ describe("parsePanesParam", () => {
});
describe("panesFromDeepLink", () => {
- test("a run deep link opens watch-and-review: Copilot, Browser, Overview", () => {
+ test("a run deep link opens watch-and-review: Browser, Overview", () => {
expect(
panesFromDeepLink({ runId: "wr_123", active: null, blockLabel: null }),
- ).toEqual(["copilot", "browser", "overview"]);
+ ).toEqual(["browser", "overview"]);
});
test("an ?active= deep link opens the same run layout", () => {
expect(
panesFromDeepLink({ runId: null, active: "act_1", blockLabel: null }),
- ).toEqual(["copilot", "browser", "overview"]);
+ ).toEqual(["browser", "overview"]);
});
test("a block run opens iterate: Editor, Browser, Overview", () => {
@@ -108,7 +107,7 @@ describe("panesFromDeepLink", () => {
test("no deep link falls back to the default panes", () => {
expect(
panesFromDeepLink({ runId: null, active: null, blockLabel: null }),
- ).toEqual(["copilot", "browser"]);
+ ).toEqual(["editor", "browser"]);
});
test("a learned run layout restores on a bare ?wr= entry", () => {
@@ -149,7 +148,7 @@ describe("panesFromDeepLink", () => {
DEFAULT_STUDIO_PANES,
["editor", "overview"],
),
- ).toEqual(["copilot", "browser", "overview"]);
+ ).toEqual(["browser", "overview"]);
});
test("null learned layout falls back to factory run panes", () => {
@@ -159,21 +158,17 @@ describe("panesFromDeepLink", () => {
DEFAULT_STUDIO_PANES,
null,
),
- ).toEqual(["copilot", "browser", "overview"]);
+ ).toEqual(["browser", "overview"]);
});
});
describe("resolveOpenPanes", () => {
test("no params resolves to the default panes", () => {
- expect(resolveOpenPanes("")).toEqual(["copilot", "browser"]);
+ expect(resolveOpenPanes("")).toEqual(["editor", "browser"]);
});
- test("?wr= resolves to Copilot, Browser and Overview", () => {
- expect(resolveOpenPanes("?wr=wr_123")).toEqual([
- "copilot",
- "browser",
- "overview",
- ]);
+ test("?wr= resolves to Browser and Overview", () => {
+ expect(resolveOpenPanes("?wr=wr_123")).toEqual(["browser", "overview"]);
});
test("?wr= plus ?bl= resolves to Editor, Browser and Overview", () => {
@@ -185,11 +180,7 @@ describe("resolveOpenPanes", () => {
});
test("?active= resolves like a run deep link", () => {
- expect(resolveOpenPanes("?active=act_1")).toEqual([
- "copilot",
- "browser",
- "overview",
- ]);
+ expect(resolveOpenPanes("?active=act_1")).toEqual(["browser", "overview"]);
});
test("an explicit ?panes= wins over the deep-link params", () => {
@@ -212,7 +203,7 @@ describe("resolveOpenPanes", () => {
test("unrelated params do not affect the default", () => {
expect(resolveOpenPanes("?embed=true&cache-key-value=x")).toEqual([
- "copilot",
+ "editor",
"browser",
]);
});
@@ -246,23 +237,6 @@ describe("resolveOpenPanes", () => {
});
});
-describe("defaultPanesForWorkflowState", () => {
- test("an empty agent starts on prompt-and-watch: Copilot + Browser", () => {
- expect(defaultPanesForWorkflowState({ hasBlocks: false })).toEqual([
- "copilot",
- "browser",
- ]);
- });
-
- test("a built agent adds the Editor: Copilot + Browser + Editor", () => {
- expect(defaultPanesForWorkflowState({ hasBlocks: true })).toEqual([
- "copilot",
- "browser",
- "editor",
- ]);
- });
-});
-
describe("resolveOpenPanes with custom defaults", () => {
test("no params resolves to the given defaults", () => {
expect(resolveOpenPanes("", ["copilot", "editor"])).toEqual([
@@ -273,7 +247,6 @@ describe("resolveOpenPanes with custom defaults", () => {
test("deep links are unaffected by custom defaults", () => {
expect(resolveOpenPanes("?wr=wr_123", ["copilot", "editor"])).toEqual([
- "copilot",
"browser",
"overview",
]);
diff --git a/skyvern-frontend/src/routes/workflows/studio/panes.ts b/skyvern-frontend/src/routes/workflows/studio/panes.ts
index c4574afa6..ce6d45c25 100644
--- a/skyvern-frontend/src/routes/workflows/studio/panes.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/panes.ts
@@ -29,13 +29,16 @@ const STUDIO_PANE_ID_ALIASES: Record<string, StudioPaneId> = {
timeline: "overview",
};
+// Cold-entry edit-class default when no deep link or saved layout decides:
+// Editor on the left, Browser on the right — the legacy studio edit view.
export const DEFAULT_STUDIO_PANES: readonly StudioPaneId[] = [
- "copilot",
+ "editor",
"browser",
];
-// In-app run starts (full run or block ▶) append the run surfaces to whatever
-// is already open — they never rearrange or close panes.
+// The run surfaces: cold-entry run-class views open exactly these, and in-app
+// run starts (full run or block ▶) append them to whatever is already open —
+// appends never rearrange or close panes.
export const RUN_APPEND_PANES: readonly StudioPaneId[] = [
"browser",
"overview",
@@ -74,17 +77,6 @@ function isStudioPaneId(value: string): value is StudioPaneId {
return (STUDIO_PANE_IDS as readonly string[]).includes(value);
}
-// Cold-entry defaults when no deep link decides: an empty agent starts on
-// prompt-and-watch (Copilot builds, the Browser shows it work — the Editor
-// auto-appends once a build lands); a built agent adds the Editor.
-export function defaultPanesForWorkflowState(state: {
- hasBlocks: boolean;
-}): StudioPaneId[] {
- return state.hasBlocks
- ? ["copilot", "browser", "editor"]
- : [...DEFAULT_STUDIO_PANES];
-}
-
export function panesListEqual(
a: readonly StudioPaneId[],
b: readonly StudioPaneId[],
@@ -159,12 +151,12 @@ export function panesFromDeepLink(
return ["editor", "browser", "overview"];
}
if (params.runId) {
- return learnedRunPanes
- ? [...learnedRunPanes]
- : ["copilot", "browser", "overview"];
+ return learnedRunPanes ? [...learnedRunPanes] : [...RUN_APPEND_PANES];
}
if (params.active) {
- return ["copilot", "browser", "overview"];
+ // Unlike a bare ?wr=, ?active= does not restore the learned run layout — an
+ // action reference always opens the default watch-and-review surfaces.
+ return [...RUN_APPEND_PANES];
}
return [...defaultPanes];
}
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.test.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.test.tsx
index a4756ae42..f41ccc6c0 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.test.tsx
@@ -4,7 +4,19 @@ import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, test, vi } from "vitest";
vi.mock("@/components/SummarizeOutput", () => ({
- SummarizeOutput: () => null,
+ SummarizeOutput: ({
+ contextKey,
+ outputJson,
+ }: {
+ contextKey: string;
+ outputJson: string;
+ }) => (
+ <div
+ data-testid="summarize"
+ data-context-key={contextKey}
+ data-output-json={outputJson}
+ />
+ ),
}));
vi.mock("./OverviewCodeBlock", () => ({
OverviewCodeBlock: ({ value }: { value: string }) => <pre>{value}</pre>,
@@ -14,6 +26,7 @@ import { RunOutputsSection } from "./RunOutputsSection";
const baseProps = {
workflowRunId: "wr_1",
+ outputs: null,
extractedInformation: null,
files: [],
errors: [],
@@ -23,6 +36,75 @@ const baseProps = {
afterEach(cleanup);
+describe("RunOutputsSection agent run outputs", () => {
+ const outputs = {
+ extracted_information: { answer: 42 },
+ additional_output: "full-run-only",
+ };
+
+ test("renders extracted information, then agent run outputs, then files", () => {
+ render(
+ <RunOutputsSection
+ {...baseProps}
+ outputs={outputs}
+ extractedInformation={{ answer: 42 }}
+ files={[{ url: "https://x.test/y.pdf", filename: "y.pdf" }]}
+ />,
+ );
+ const labels = screen
+ .getAllByText(
+ /^(Extracted information|Agent run outputs|Downloaded files)$/,
+ )
+ .map((el) => el.textContent);
+ expect(labels).toEqual([
+ "Extracted information",
+ "Agent run outputs",
+ "Downloaded files",
+ ]);
+ // The full outputs object carries a field that is absent from extracted info.
+ expect(screen.getByText(/full-run-only/)).not.toBeNull();
+ });
+
+ test("binds the sole summarizer to the compact full outputs", () => {
+ render(
+ <RunOutputsSection
+ {...baseProps}
+ outputs={outputs}
+ extractedInformation={{ answer: 42 }}
+ />,
+ );
+ expect(screen.getAllByTestId("summarize")).toHaveLength(1);
+ const summarizer = screen.getByTestId("summarize");
+ expect(summarizer.getAttribute("data-context-key")).toBe("run:wr_1");
+ expect(summarizer.getAttribute("data-output-json")).toBe(
+ JSON.stringify(outputs),
+ );
+ });
+
+ test("shows the generated summary under agent run outputs", () => {
+ render(
+ <RunOutputsSection
+ {...baseProps}
+ outputs={outputs}
+ extractedInformation={{ answer: 42 }}
+ summary="A short summary."
+ />,
+ );
+ expect(screen.getByText("A short summary.")).not.toBeNull();
+ });
+
+ test("renders no agent run outputs section when outputs is null", () => {
+ render(
+ <RunOutputsSection
+ {...baseProps}
+ files={[{ url: "https://x.test/y.pdf", filename: "y.pdf" }]}
+ />,
+ );
+ expect(screen.queryByText("Agent run outputs")).toBeNull();
+ expect(screen.queryByTestId("summarize")).toBeNull();
+ });
+});
+
describe("RunOutputsSection task 2.0 and webhook surfaces", () => {
test("renders the webhook failure reason", () => {
render(
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.tsx
index dec5c25b8..403a3f290 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.tsx
@@ -14,6 +14,7 @@ export type RunOutputError = Record<string, unknown>;
type RunOutputsSectionProps = {
workflowRunId: string;
workflowTitle?: string | null;
+ outputs: Record<string, unknown> | null;
extractedInformation: Record<string, unknown> | null;
files: RunOutputFile[];
errors: RunOutputError[];
@@ -158,6 +159,7 @@ function RunErrorsPanel({ errors }: { errors: RunOutputError[] }) {
export function RunOutputsSection({
workflowRunId,
workflowTitle,
+ outputs,
extractedInformation,
files,
errors,
@@ -180,7 +182,8 @@ export function RunOutputsSection({
return null;
}
- const extractedJson = JSON.stringify(extractedInformation ?? {});
+ const hasAgentRunOutputs =
+ outputs !== null && Object.keys(outputs).length > 0;
return (
<div className="flex flex-col gap-5">
@@ -207,14 +210,26 @@ export function RunOutputsSection({
</div>
) : null}
{hasExtracted ? (
+ <div className="flex flex-col gap-2">
+ <span className="text-xs font-medium text-muted-foreground">
+ Extracted information
+ </span>
+ <OverviewCodeBlock
+ value={JSON.stringify(extractedInformation, null, 2)}
+ maxHeight="320px"
+ />
+ </div>
+ ) : null}
+ {hasAgentRunOutputs ? (
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">
- Extracted information
+ Agent run outputs
</span>
<SummarizeOutput
+ key={`run:${workflowRunId}`}
contextKey={`run:${workflowRunId}`}
- outputJson={extractedJson}
+ outputJson={JSON.stringify(outputs)}
workflowTitle={workflowTitle}
hasSummary={summary !== null}
onSummary={onSummary}
@@ -230,7 +245,7 @@ export function RunOutputsSection({
</div>
) : null}
<OverviewCodeBlock
- value={JSON.stringify(extractedInformation, null, 2)}
+ value={JSON.stringify(outputs, null, 2)}
maxHeight="320px"
/>
</div>
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 8b3aec2cd..10960fe90 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
@@ -47,6 +47,11 @@ vi.mock("../../workflowRun/WorkflowRunCode", () => ({
vi.mock("../../workflowRun/WorkflowRunVerificationCodeForm", () => ({
WorkflowRunVerificationCodeForm: () => null,
}));
+vi.mock("@/routes/tasks/components/tagging/RunTagsEditor", () => ({
+ RunTagsEditor: ({ workflowRunId }: { workflowRunId: string }) => (
+ <div data-testid="run-tags-editor" data-workflow-run-id={workflowRunId} />
+ ),
+}));
// Radix ScrollArea needs ResizeObserver, which jsdom doesn't provide.
vi.mock("@/components/ui/scroll-area", () => ({
ScrollArea: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
@@ -266,6 +271,13 @@ beforeEach(() => {
});
describe("RunView view toggles", () => {
+ test("renders the shared run tag editor", () => {
+ seedCompletedRun();
+ const { getByTestId } = renderRunView();
+
+ expect(getByTestId("run-tags-editor").dataset.workflowRunId).toBe("wr_1");
+ });
+
test("defaults to the Timeline view with the timeline and step detail", () => {
seedForLoopRun();
const { container } = renderRunView();
@@ -673,6 +685,24 @@ describe("RunView output signals", () => {
expect(scope.getByText("report.pdf")).not.toBeNull();
});
+ test("surfaces the full agent run outputs below extracted information", () => {
+ seedCompletedRun({
+ outputs: {
+ extracted_information: { answer: 42 },
+ additional_output: "full-run-only",
+ },
+ });
+
+ const { container } = renderRunView();
+ const scope = within(container);
+
+ // This run has outputs, so the toggle name carries the new-output suffix.
+ fireEvent.click(scope.getByRole("button", { name: /^Outputs/ }));
+
+ expect(scope.getByText("Extracted information")).not.toBeNull();
+ expect(scope.getByText("Agent run outputs")).not.toBeNull();
+ });
+
test("does not treat a user output parameter named errors as run errors", () => {
seedCompletedRun({
outputs: {
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
index 3126ceb1a..65b30d459 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
@@ -14,6 +14,7 @@ import { useRunViewStore } from "@/store/RunViewStore";
import { useStudioBrowserStore } from "@/store/useStudioBrowserStore";
import { useWorkflowBlockSearchStore } from "@/store/WorkflowBlockSearchStore";
import { isRecord } from "@/util/utils";
+import { RunTagsEditor } from "@/routes/tasks/components/tagging/RunTagsEditor";
import { useWorkflowRunTimelineQuery } from "../../hooks/useWorkflowRunTimelineQuery";
import { useWorkflowRunWithWorkflowQuery } from "../../hooks/useWorkflowRunWithWorkflowQuery";
@@ -339,6 +340,10 @@ export function RunView({
<WorkflowRunVerificationCodeForm
workflowRunId={workflowRun.workflow_run_id}
/>
+ <RunTagsEditor
+ workflowRunId={workflowRun.workflow_run_id}
+ className="shrink-0"
+ />
{provisioning ? (
<div className="flex shrink-0 items-center gap-2 rounded-md border border-border bg-slate-elevation2 px-3 py-1.5 text-xs text-muted-foreground">
@@ -468,6 +473,7 @@ export function RunView({
<RunOutputsSection
workflowRunId={workflowRun.workflow_run_id}
workflowTitle={workflowRun.workflow?.title}
+ outputs={workflowRun.outputs}
extractedInformation={extractedInformation}
files={downloadedFiles}
errors={runErrors}
diff --git a/skyvern-frontend/src/routes/workflows/types/healTypes.ts b/skyvern-frontend/src/routes/workflows/types/healTypes.ts
new file mode 100644
index 000000000..74e68fcac
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/types/healTypes.ts
@@ -0,0 +1,47 @@
+export type HealEpisodeStatus =
+ | "fired_completed"
+ | "fired_unverified"
+ | "fired_failed"
+ | "skipped";
+
+export type HealEpisodeEngine = "harness" | "floor" | "code";
+
+export type HealOutputObligation = "none" | "observed" | "vestigial" | null;
+
+export type HealEpisodeView = {
+ heal_episode_id: string;
+ workflow_permanent_id: string;
+ workflow_id: string;
+ workflow_run_id: string;
+ workflow_run_block_id: string;
+ block_label: string | null;
+ engine: HealEpisodeEngine;
+ status: HealEpisodeStatus;
+ skip_reason: string | null;
+ snapshot_available: boolean;
+ convergence_eligible: boolean;
+ parameter_binding_keys: string[];
+ exception_class: string | null;
+ failing_line: number | null;
+ matched_step_index: number | null;
+ escalation_task_id: string | null;
+ wall_clock_ms: number | null;
+ action_count: number | null;
+ output_obligation: HealOutputObligation;
+ dom_snapshot_artifact_id: string | null;
+ scout_transcript_artifact_id: string | null;
+ screenshot_artifact_id: string | null;
+ created_at: string;
+ modified_at: string;
+};
+
+export type RunHealSummary = {
+ blocks_healed: number;
+ blocks_outcome_risk: string[];
+ blocks_with_heal_attempt: number;
+};
+
+export type RunHealEpisodesResponse = {
+ episodes: HealEpisodeView[];
+ summary: RunHealSummary;
+};
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
index 5ff4f51d4..a928c9647 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
@@ -575,6 +575,27 @@ export type FileDownloadBlock = WorkflowBlockBase & {
disable_cache?: boolean;
engine: RunEngine | null;
download_timeout: number | null; // seconds
+ download_target: "website" | "s3" | "azure" | "google_drive" | "sftp";
+ path: string;
+ prompt: string | null;
+ s3_bucket: string | null;
+ region_name: string | null;
+ aws_access_key_id: string | null;
+ aws_secret_access_key: string | null;
+ azure_storage_account_name: string | null;
+ azure_storage_account_key: string | null;
+ azure_blob_container_name: string | null;
+ google_credential_id: string | null;
+ google_drive_folder_id: string | null;
+ sftp_host: string | null;
+ sftp_port: number | null;
+ sftp_username: string | null;
+ sftp_password: string | null;
+ sftp_private_key: string | null;
+ sftp_private_key_passphrase: string | null;
+ sftp_remote_path: string | null;
+ sftp_host_key: string | null;
+ continue_on_empty: boolean;
};
export type PDFParserBlock = WorkflowBlockBase & {
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
index 3cd61eab3..c806bc40b 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
@@ -304,6 +304,27 @@ export type WaitBlockYAML = BlockYAMLBase & {
export type FileDownloadBlockYAML = BlockYAMLBase & {
block_type: "file_download";
+ download_target?: "website" | "s3" | "azure" | "google_drive" | "sftp";
+ path?: string | null;
+ prompt?: string | null;
+ s3_bucket?: string | null;
+ region_name?: string | null;
+ aws_access_key_id?: string | null;
+ aws_secret_access_key?: string | null;
+ azure_storage_account_name?: string | null;
+ azure_storage_account_key?: string | null;
+ azure_blob_container_name?: string | null;
+ google_credential_id?: string | null;
+ google_drive_folder_id?: string | null;
+ sftp_host?: string | null;
+ sftp_port?: number | null;
+ sftp_username?: string | null;
+ sftp_password?: string | null;
+ sftp_private_key?: string | null;
+ sftp_private_key_passphrase?: string | null;
+ sftp_remote_path?: string | null;
+ sftp_host_key?: string | null;
+ continue_on_empty?: boolean;
url: string | null;
title?: string;
navigation_goal: string | null;
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/BlockHealPanel.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/BlockHealPanel.test.tsx
new file mode 100644
index 000000000..49bb543d3
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/BlockHealPanel.test.tsx
@@ -0,0 +1,105 @@
+// @vitest-environment jsdom
+
+import { render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { HealEpisodeView } from "../types/healTypes";
+
+function makeEpisode(overrides: Partial<HealEpisodeView>): HealEpisodeView {
+ return {
+ heal_episode_id: "he_1",
+ workflow_permanent_id: "wpid_1",
+ workflow_id: "wf_1",
+ workflow_run_id: "wr_1",
+ workflow_run_block_id: "wrb_1",
+ block_label: "Login",
+ engine: "harness",
+ status: "fired_completed",
+ skip_reason: null,
+ snapshot_available: true,
+ convergence_eligible: true,
+ parameter_binding_keys: [],
+ exception_class: null,
+ failing_line: null,
+ matched_step_index: 3,
+ escalation_task_id: null,
+ wall_clock_ms: 820,
+ action_count: 2,
+ output_obligation: "observed",
+ dom_snapshot_artifact_id: "art_dom",
+ scout_transcript_artifact_id: "art_scout",
+ screenshot_artifact_id: "art_ss",
+ created_at: "2026-01-01T00:00:00Z",
+ modified_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+const { healState } = vi.hoisted(() => ({
+ healState: { episodes: [] as Array<HealEpisodeView> },
+}));
+
+vi.mock("../hooks/useRunHealEpisodesQuery", () => ({
+ useRunHealEpisodesQuery: () => ({
+ data: {
+ episodes: healState.episodes,
+ summary: {
+ blocks_healed: 1,
+ blocks_outcome_risk: [],
+ blocks_with_heal_attempt: 1,
+ },
+ },
+ }),
+}));
+
+import { BlockHealPanel } from "./BlockHealPanel";
+
+describe("BlockHealPanel", () => {
+ beforeEach(() => {
+ healState.episodes = [makeEpisode({})];
+ });
+
+ it("renders episode status, timing, actions, and evidence chips", () => {
+ render(<BlockHealPanel workflowRunId="wr_1" workflowRunBlockId="wrb_1" />);
+
+ expect(screen.getByText("Runtime healing")).toBeDefined();
+ expect(screen.getByText("Self-healed")).toBeDefined();
+ expect(screen.getByText("primary")).toBeDefined();
+ expect(screen.getByText("820 ms")).toBeDefined();
+ expect(screen.getByText("2 actions")).toBeDefined();
+ expect(screen.getByText("DOM snapshot")).toBeDefined();
+ expect(screen.getByText("scout transcript")).toBeDefined();
+ expect(screen.getByText("screenshot")).toBeDefined();
+ expect(
+ screen.getByText(
+ "Recovered this run — your workflow version is unchanged.",
+ ),
+ ).toBeDefined();
+ });
+
+ it("does not claim recovery when the block only failed or was skipped", () => {
+ healState.episodes = [
+ makeEpisode({
+ heal_episode_id: "he_failed",
+ status: "fired_failed",
+ wall_clock_ms: 2000,
+ action_count: 5,
+ dom_snapshot_artifact_id: null,
+ scout_transcript_artifact_id: null,
+ screenshot_artifact_id: null,
+ }),
+ ];
+
+ render(<BlockHealPanel workflowRunId="wr_1" workflowRunBlockId="wrb_1" />);
+
+ expect(screen.getByText("Heal failed")).toBeDefined();
+ expect(
+ screen.getByText("Your workflow version is unchanged."),
+ ).toBeDefined();
+ expect(
+ screen.queryByText(
+ "Recovered this run — your workflow version is unchanged.",
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/BlockHealPanel.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/BlockHealPanel.tsx
new file mode 100644
index 000000000..d37110480
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/BlockHealPanel.tsx
@@ -0,0 +1,175 @@
+import { useMemo } from "react";
+import {
+ CheckCircledIcon,
+ ExclamationTriangleIcon,
+ MinusCircledIcon,
+ QuestionMarkCircledIcon,
+} from "@radix-ui/react-icons";
+
+import { useRunHealEpisodesQuery } from "../hooks/useRunHealEpisodesQuery";
+import type { HealEpisodeStatus, HealEpisodeView } from "../types/healTypes";
+import {
+ healEngineEmphasis,
+ healEngineLabel,
+ healPanelInvariant,
+ healSkipReasonLabel,
+ healStatusHue,
+ healStatusLabel,
+ type HealEmphasis,
+ type HealHue,
+} from "./healStatus";
+
+type Props = {
+ workflowRunId?: string;
+ workflowRunBlockId: string;
+};
+
+// hue = outcome, emphasis = engine (solid harness / soft-outline fallback).
+const hueClassName: Record<HealHue, Record<HealEmphasis, string>> = {
+ success: {
+ solid: "bg-success/15 text-success",
+ soft: "border border-success/40 text-success",
+ },
+ warning: {
+ solid: "bg-warning/15 text-warning",
+ soft: "border border-warning/40 text-warning",
+ },
+ orange: {
+ solid: "bg-orange-500/15 text-orange-600 dark:text-orange-400",
+ soft: "border border-orange-500/40 text-orange-600 dark:text-orange-400",
+ },
+ neutral: {
+ solid: "bg-muted text-muted-foreground",
+ soft: "border border-border text-muted-foreground",
+ },
+};
+
+const statusIcon: Record<HealEpisodeStatus, typeof CheckCircledIcon> = {
+ fired_completed: CheckCircledIcon,
+ fired_unverified: QuestionMarkCircledIcon,
+ fired_failed: ExclamationTriangleIcon,
+ skipped: MinusCircledIcon,
+};
+
+function formatDuration(wallClockMs: number | null): string {
+ if (wallClockMs === null) {
+ return "-";
+ }
+ return `${wallClockMs.toLocaleString()} ms`;
+}
+
+function formatActionCount(actionCount: number | null): string {
+ if (actionCount === null) {
+ return "-";
+ }
+ return `${actionCount.toLocaleString()} action${actionCount === 1 ? "" : "s"}`;
+}
+
+function StatusBadge({ episode }: { episode: HealEpisodeView }) {
+ const hue = healStatusHue(episode.status);
+ const emphasis = healEngineEmphasis(episode.engine);
+ const Icon = statusIcon[episode.status];
+ const label = healStatusLabel(episode.status);
+
+ return (
+ <span
+ className={`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide ${hueClassName[hue][emphasis]}`}
+ >
+ <Icon className="h-3 w-3" />
+ {label}
+ </span>
+ );
+}
+
+function EvidenceChips({ episode }: { episode: HealEpisodeView }) {
+ const chips: Array<string> = [];
+
+ if (episode.dom_snapshot_artifact_id) {
+ chips.push("DOM snapshot");
+ }
+ if (episode.scout_transcript_artifact_id) {
+ chips.push("scout transcript");
+ }
+ if (episode.screenshot_artifact_id) {
+ chips.push("screenshot");
+ }
+
+ if (chips.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className="mt-2 flex flex-wrap gap-1.5">
+ {chips.map((chip) => (
+ <span
+ key={`${episode.heal_episode_id}-${chip}`}
+ className="rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground"
+ >
+ {chip}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+function BlockHealPanel({ workflowRunId, workflowRunBlockId }: Props) {
+ const { data } = useRunHealEpisodesQuery({ workflowRunId });
+
+ const blockEpisodes = useMemo(
+ () =>
+ (data?.episodes ?? []).filter(
+ (episode) => episode.workflow_run_block_id === workflowRunBlockId,
+ ),
+ [data?.episodes, workflowRunBlockId],
+ );
+
+ if (blockEpisodes.length === 0) {
+ return null;
+ }
+
+ const blockRecovered = blockEpisodes.some(
+ (episode) =>
+ episode.status === "fired_completed" ||
+ episode.status === "fired_unverified",
+ );
+
+ return (
+ <div className="border-b border-border bg-slate-elevation1 px-3 py-3">
+ <div className="mb-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground dark:text-slate-500">
+ Runtime healing
+ </div>
+ <div className="space-y-2">
+ {blockEpisodes.map((episode) => (
+ <div
+ key={episode.heal_episode_id}
+ className="rounded border border-border bg-slate-elevation2 p-2"
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <StatusBadge episode={episode} />
+ <span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wide text-muted-foreground dark:bg-slate-700">
+ {healEngineLabel(episode.engine)}
+ </span>
+ <span className="text-[11px] text-muted-foreground">
+ {formatDuration(episode.wall_clock_ms)}
+ </span>
+ <span className="text-[11px] text-muted-foreground">
+ {formatActionCount(episode.action_count)}
+ </span>
+ </div>
+ {episode.status === "skipped" && (
+ <div className="mt-1 text-[11px] text-muted-foreground">
+ Skip reason: {healSkipReasonLabel(episode.skip_reason)}
+ </div>
+ )}
+ <EvidenceChips episode={episode} />
+ </div>
+ ))}
+ </div>
+ <p className="mt-2 text-[11px] text-muted-foreground">
+ {healPanelInvariant(blockRecovered)}
+ </p>
+ </div>
+ );
+}
+
+export { BlockHealPanel };
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/RunHealChip.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/RunHealChip.test.tsx
new file mode 100644
index 000000000..70aa8045c
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/RunHealChip.test.tsx
@@ -0,0 +1,64 @@
+// @vitest-environment jsdom
+
+import { render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { RunHealSummary } from "../types/healTypes";
+
+const { healState } = vi.hoisted(() => ({
+ healState: { summary: undefined as RunHealSummary | undefined },
+}));
+
+vi.mock("../hooks/useRunHealEpisodesQuery", () => ({
+ useRunHealEpisodesQuery: () => ({
+ data: healState.summary
+ ? { episodes: [], summary: healState.summary }
+ : undefined,
+ }),
+}));
+
+import { RunHealChip } from "./RunHealChip";
+
+describe("RunHealChip", () => {
+ beforeEach(() => {
+ healState.summary = undefined;
+ });
+
+ it("shows the healed-block count when blocks were healed", () => {
+ healState.summary = {
+ blocks_healed: 2,
+ blocks_outcome_risk: [],
+ blocks_with_heal_attempt: 2,
+ };
+
+ render(<RunHealChip workflowRunId="wr_1" />);
+
+ expect(screen.getByText("2 block(s) self-healed")).toBeDefined();
+ });
+
+ it("shows 'Self-heal attempted' with a review badge when every heal failed", () => {
+ healState.summary = {
+ blocks_healed: 0,
+ blocks_outcome_risk: ["wrb_1"],
+ blocks_with_heal_attempt: 1,
+ };
+
+ render(<RunHealChip workflowRunId="wr_1" />);
+
+ expect(screen.getByText("Self-heal attempted")).toBeDefined();
+ expect(screen.getByText("review recommended")).toBeDefined();
+ expect(screen.queryByText("0 block(s) self-healed")).toBeNull();
+ });
+
+ it("renders nothing when no block attempted a heal", () => {
+ healState.summary = {
+ blocks_healed: 0,
+ blocks_outcome_risk: [],
+ blocks_with_heal_attempt: 0,
+ };
+
+ const { container } = render(<RunHealChip workflowRunId="wr_1" />);
+
+ expect(container.firstChild).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/RunHealChip.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/RunHealChip.tsx
new file mode 100644
index 000000000..aeec35624
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/RunHealChip.tsx
@@ -0,0 +1,50 @@
+import { useRunHealEpisodesQuery } from "../hooks/useRunHealEpisodesQuery";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { healChipTooltip } from "./healStatus";
+
+type Props = {
+ workflowRunId?: string;
+};
+
+function RunHealChip({ workflowRunId }: Props) {
+ const { data } = useRunHealEpisodesQuery({ workflowRunId });
+ const summary = data?.summary;
+
+ if (!summary || summary.blocks_with_heal_attempt <= 0) {
+ return null;
+ }
+
+ const hasOutcomeRisk = summary.blocks_outcome_risk.length > 0;
+ const healed = summary.blocks_healed > 0;
+
+ return (
+ <TooltipProvider>
+ <Tooltip delayDuration={300}>
+ <TooltipTrigger asChild>
+ <div className="inline-flex items-center gap-2 rounded-md border border-border bg-slate-elevation2/80 px-2 py-1 text-[11px] text-foreground backdrop-blur-sm">
+ <span>
+ {healed
+ ? `${summary.blocks_healed} block(s) self-healed`
+ : "Self-heal attempted"}
+ </span>
+ {hasOutcomeRisk && (
+ <span className="rounded bg-warning/15 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-warning">
+ review recommended
+ </span>
+ )}
+ </div>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-[260px] text-[11px]">
+ {healChipTooltip(healed)}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
+
+export { RunHealChip };
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.test.tsx
index 8ef47a071..64b1ee89a 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.test.tsx
@@ -10,6 +10,18 @@ vi.mock("../hooks/useWorkflowRunWithWorkflowQuery", () => ({
vi.mock("../hooks/useWorkflowRunTimelineQuery", () => ({
useWorkflowRunTimelineQuery: () => ({ data: [], isLoading: false }),
}));
+vi.mock("../hooks/useRunHealEpisodesQuery", () => ({
+ useRunHealEpisodesQuery: () => ({
+ data: {
+ episodes: [],
+ summary: {
+ blocks_healed: 0,
+ blocks_outcome_risk: [],
+ blocks_with_heal_attempt: 0,
+ },
+ },
+ }),
+}));
vi.mock("./WorkflowRunHumanInteraction", () => ({
WorkflowRunHumanInteraction: () => null,
}));
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx
index 5dbf9afaa..3407a6080 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx
@@ -32,6 +32,7 @@ import { BlockDetailThought } from "./blockDetail/BlockDetailThought";
import { BlockDetailWorkflowTrigger } from "./blockDetail/BlockDetailWorkflowTrigger";
import { BlockInspector } from "./blockDetail/BlockInspector";
import { EmptyState } from "./blockDetail/EmptyState";
+import { BlockHealPanel } from "./BlockHealPanel";
import {
BlockDetailHeader,
BlockDetailHeaderSkeleton,
@@ -264,6 +265,12 @@ function WorkflowRunBlockDetail({
{resolvedBlock && (
<BlockInspector block={resolvedBlock} action={selectedAction} />
)}
+ {resolvedBlock && (
+ <BlockHealPanel
+ workflowRunId={workflowRunId ?? resolvedBlock.workflow_run_id}
+ workflowRunBlockId={resolvedBlock.workflow_run_block_id}
+ />
+ )}
{resolvedBlock && showDownloadedFiles && (
<BlockDownloadedFiles
block={resolvedBlock}
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx
index 312fb6cbf..a9ef584b3 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx
@@ -26,6 +26,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useState } from "react";
import { useBrowserStreamingMode } from "@/hooks/useRuntimeConfig";
+import { RunHealChip } from "./RunHealChip";
export type ActionItem = {
block: WorkflowRunBlock;
@@ -131,55 +132,60 @@ function WorkflowRunOverview() {
return (
<AspectRatio ratio={16 / 9}>
- {shouldShowBrowserStream && (
- <BrowserStream
- key={browserSessionId}
- browserSessionId={browserSessionId!}
- interactive={isPaused}
- showControlButtons={isPaused}
- workflow={undefined}
- onClose={handleVncClose}
- />
- )}
- {!shouldShowBrowserStream &&
- (shouldShowScreencastFallback || selection === "stream") && (
- <WorkflowRunStream
- alwaysShowStream={shouldShowScreencastFallback}
+ <div className="relative h-full w-full">
+ <div className="absolute left-2 top-2 z-20">
+ <RunHealChip workflowRunId={workflowRunId} />
+ </div>
+ {shouldShowBrowserStream && (
+ <BrowserStream
+ key={browserSessionId}
+ browserSessionId={browserSessionId!}
interactive={isPaused}
showControlButtons={isPaused}
+ workflow={undefined}
+ onClose={handleVncClose}
/>
)}
- {!isStreamActive && isAction(selection) && (
- <ActionScreenshot
- artifactId={selection.screenshot_artifact_id ?? undefined}
- index={selection.action_order ?? 0}
- stepId={selection.step_id ?? ""}
- />
- )}
- {isWorkflowRunBlock(selection) &&
- !isStreamActive &&
- (() => {
- // A container selection (loop/conditional) resolves to a descendant leaf, so read the
- // leaf's type rather than the container's so a nested code block is treated as one.
- const screenshotBlockId = resolveScreenshotBlockId(
- workflowRunTimeline,
- selection,
- activeIteration,
- );
- const screenshotBlockType =
- findTimelineBlock(workflowRunTimeline, screenshotBlockId)
- ?.block_type ?? selection.block_type;
- return (
- <WorkflowRunBlockScreenshot
- workflowRunBlockId={screenshotBlockId}
- blockType={screenshotBlockType}
- runStatus={workflowRun?.status}
+ {!shouldShowBrowserStream &&
+ (shouldShowScreencastFallback || selection === "stream") && (
+ <WorkflowRunStream
+ alwaysShowStream={shouldShowScreencastFallback}
+ interactive={isPaused}
+ showControlButtons={isPaused}
/>
- );
- })()}
- {isObserverThought(selection) && (
- <ObserverThoughtScreenshot observerThoughtId={selection.thought_id} />
- )}
+ )}
+ {!isStreamActive && isAction(selection) && (
+ <ActionScreenshot
+ artifactId={selection.screenshot_artifact_id ?? undefined}
+ index={selection.action_order ?? 0}
+ stepId={selection.step_id ?? ""}
+ />
+ )}
+ {isWorkflowRunBlock(selection) &&
+ !isStreamActive &&
+ (() => {
+ // A container selection (loop/conditional) resolves to a descendant leaf, so read the
+ // leaf's type rather than the container's so a nested code block is treated as one.
+ const screenshotBlockId = resolveScreenshotBlockId(
+ workflowRunTimeline,
+ selection,
+ activeIteration,
+ );
+ const screenshotBlockType =
+ findTimelineBlock(workflowRunTimeline, screenshotBlockId)
+ ?.block_type ?? selection.block_type;
+ return (
+ <WorkflowRunBlockScreenshot
+ workflowRunBlockId={screenshotBlockId}
+ blockType={screenshotBlockType}
+ runStatus={workflowRun?.status}
+ />
+ );
+ })()}
+ {isObserverThought(selection) && (
+ <ObserverThoughtScreenshot observerThoughtId={selection.thought_id} />
+ )}
+ </div>
</AspectRatio>
);
}
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/__tests__/healStatus.test.ts b/skyvern-frontend/src/routes/workflows/workflowRun/__tests__/healStatus.test.ts
new file mode 100644
index 000000000..10f974fba
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/__tests__/healStatus.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ healChipTooltip,
+ healEngineEmphasis,
+ healEngineLabel,
+ healPanelInvariant,
+ healSkipReasonLabel,
+ healStatusHue,
+ healStatusLabel,
+} from "../healStatus";
+
+describe("heal status helpers", () => {
+ it("maps backend status values to user-facing labels", () => {
+ expect(healStatusLabel("fired_completed")).toBe("Self-healed");
+ expect(healStatusLabel("fired_unverified")).toBe("Recovered · unverified");
+ expect(healStatusLabel("fired_failed")).toBe("Heal failed");
+ expect(healStatusLabel("skipped")).toBe("No heal");
+ });
+
+ it("reserves the success hue for completed heals only (no false green)", () => {
+ expect(healStatusHue("fired_completed")).toBe("success");
+ expect(healStatusHue("fired_unverified")).not.toBe("success");
+ expect(healStatusHue("fired_failed")).not.toBe("success");
+ expect(healStatusHue("skipped")).not.toBe("success");
+ });
+
+ it("colors a failed heal orange, never red — the run status owns red", () => {
+ expect(healStatusHue("fired_failed")).toBe("orange");
+ });
+
+ it("de-emphasizes fallback-engine (floor) recoveries vs harness", () => {
+ expect(healEngineEmphasis("harness")).toBe("solid");
+ expect(healEngineEmphasis("code")).toBe("solid");
+ expect(healEngineEmphasis("floor")).toBe("soft");
+ });
+
+ it("labels engines in human terms, not internal jargon", () => {
+ expect(healEngineLabel("harness")).toBe("primary");
+ expect(healEngineLabel("floor")).toBe("fallback");
+ expect(healEngineLabel("code")).toBe("primary");
+ });
+
+ it("maps known skip reasons to plain-language labels", () => {
+ expect(healSkipReasonLabel("capped")).toBe("Attempt limit reached");
+ expect(healSkipReasonLabel("adoption_failed")).toBe("Recovery not adopted");
+ expect(healSkipReasonLabel("credential_unavailable")).toBe(
+ "Credential unavailable",
+ );
+ expect(healSkipReasonLabel("timeout_class")).toBe("Timed out");
+ expect(healSkipReasonLabel("insecure_code")).toBe("Unsafe code blocked");
+ expect(healSkipReasonLabel("unclassifiable")).toBe("Unclassified");
+ });
+
+ it("renders a dash for a null skip reason", () => {
+ expect(healSkipReasonLabel(null)).toBe("-");
+ });
+
+ it("de-snakes unknown skip reasons so no raw enum ever renders", () => {
+ expect(healSkipReasonLabel("some_future_reason")).toBe(
+ "some future reason",
+ );
+ });
+
+ it("only claims recovery in copy when something actually recovered", () => {
+ expect(healPanelInvariant(true)).toBe(
+ "Recovered this run — your workflow version is unchanged.",
+ );
+ expect(healPanelInvariant(false)).toBe(
+ "Your workflow version is unchanged.",
+ );
+ expect(healPanelInvariant(false)).not.toContain("Recovered");
+ expect(healChipTooltip(true)).toContain("recovered this run");
+ expect(healChipTooltip(false)).toContain("attempted");
+ expect(healChipTooltip(false)).not.toContain("recovered this run");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/healStatus.ts b/skyvern-frontend/src/routes/workflows/workflowRun/healStatus.ts
new file mode 100644
index 000000000..9d787c301
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/healStatus.ts
@@ -0,0 +1,86 @@
+import type { HealEpisodeEngine, HealEpisodeStatus } from "../types/healTypes";
+
+// Hue encodes the outcome; engine (harness vs floor) is encoded by emphasis
+// (solid vs soft) so a fallback-engine recovery reads as lower-confidence
+// without mis-coloring a verified success. Red is withheld on purpose — the run
+// status owns red — so a failed heal is orange, never red.
+type HealHue = "success" | "warning" | "orange" | "neutral";
+type HealEmphasis = "solid" | "soft";
+
+const healStatusLabels: Record<HealEpisodeStatus, string> = {
+ fired_completed: "Self-healed",
+ fired_unverified: "Recovered · unverified",
+ fired_failed: "Heal failed",
+ skipped: "No heal",
+};
+
+function healStatusLabel(status: HealEpisodeStatus): string {
+ return healStatusLabels[status];
+}
+
+function healStatusHue(status: HealEpisodeStatus): HealHue {
+ switch (status) {
+ case "fired_completed":
+ return "success";
+ case "fired_unverified":
+ return "warning";
+ case "fired_failed":
+ return "orange";
+ case "skipped":
+ return "neutral";
+ }
+}
+
+// harness = the primary, instrumented engine (solid); floor = the weaker
+// fallback that only runs when the harness can't (soft/outline).
+function healEngineEmphasis(engine: HealEpisodeEngine): HealEmphasis {
+ return engine === "harness" || engine === "code" ? "solid" : "soft";
+}
+
+// Engine names are internal jargon; surface the confidence relationship
+// instead. Unknown engines de-emphasize to "fallback" (no silent confidence).
+function healEngineLabel(engine: HealEpisodeEngine): string {
+ if (engine === "harness" || engine === "code") return "primary";
+ return "fallback";
+}
+
+const healSkipReasonLabels: Record<string, string> = {
+ capped: "Attempt limit reached",
+ adoption_failed: "Recovery not adopted",
+ credential_unavailable: "Credential unavailable",
+ timeout_class: "Timed out",
+ insecure_code: "Unsafe code blocked",
+ unclassifiable: "Unclassified",
+};
+
+function healSkipReasonLabel(reason: string | null): string {
+ if (reason === null) return "-";
+ return healSkipReasonLabels[reason] ?? reason.replace(/_/g, " ");
+}
+
+// Only claim "recovered" when something actually recovered; otherwise keep just
+// the always-true "workflow version is unchanged" invariant. A "Recovered"
+// message under a Heal failed / No heal state is the false confidence this UI
+// exists to prevent.
+function healPanelInvariant(recovered: boolean): string {
+ return recovered
+ ? "Recovered this run — your workflow version is unchanged."
+ : "Your workflow version is unchanged.";
+}
+
+function healChipTooltip(healed: boolean): string {
+ return healed
+ ? "Runtime healing recovered this run. It never edits your workflow."
+ : "Runtime healing attempted a recovery this run. It never edits your workflow.";
+}
+
+export {
+ healChipTooltip,
+ healEngineEmphasis,
+ healEngineLabel,
+ healPanelInvariant,
+ healSkipReasonLabel,
+ healStatusHue,
+ healStatusLabel,
+};
+export type { HealEmphasis, HealHue };
diff --git a/skyvern/cli/core/browser_ops.py b/skyvern/cli/core/browser_ops.py
index 313b13b76..be63b1835 100644
--- a/skyvern/cli/core/browser_ops.py
+++ b/skyvern/cli/core/browser_ops.py
@@ -6,6 +6,7 @@ Session resolution and output formatting are caller responsibilities.
from __future__ import annotations
+import asyncio
import json
import os
import re
@@ -16,7 +17,7 @@ from pathlib import Path
from typing import Any, Callable, Literal
from skyvern.forge.sdk.settings_manager import SettingsManager
-from skyvern.webeye.utils.page import SkyvernFrame
+from skyvern.webeye.utils.page import JS_FUNCTION_DEFS, SkyvernFrame
from .guards import GuardError
@@ -563,10 +564,19 @@ _ROLE_TO_TAG: dict[str, str] = {
# Structural fields always kept in serialized output; display fields filtered if empty.
_ELEMENT_KEEP_ALWAYS = frozenset({"ref", "role"})
+_DOMUTILS_INTERACTABILITY_READY_JS = r"""
+() => typeof isInteractable === "function" && typeof getHoverStylesMap === "function" && typeof buildTreeFromBody === "function"
+"""
+
+# getHoverStylesMap() can await cross-origin stylesheet fetches with no abort signal; bound the
+# scan so main-page observe falls back to a11y and selected-frame observe raises a typed error.
+_DOM_SCAN_TIMEOUT_SECONDS = 30.0
+
_OBSERVE_INTERACTABLES_JS = r"""
-({ scopeSelector, includeValues }) => {
+async ({ scopeSelector, includeValues }) => {
const root = scopeSelector ? document.querySelector(scopeSelector) : document.body;
if (!root) return [];
+ let hoverStylesMap;
const esc = (value) => (window.CSS && CSS.escape ? CSS.escape(value) : String(value).replace(/[^a-zA-Z0-9_-]/g, "\\$&"));
const classes = (element) => (element.className || "").toString();
@@ -622,12 +632,6 @@ _OBSERVE_INTERACTABLES_JS = r"""
}
return parts.join(" > ");
};
- const visible = (element) => {
- if (element.tagName.toLowerCase() === "option") return element.parentElement ? visible(element.parentElement) : false;
- const style = window.getComputedStyle(element);
- const rect = element.getBoundingClientRect();
- return !element.hidden && element.getAttribute("aria-hidden") !== "true" && style?.display !== "none" && style?.visibility !== "hidden" && style?.visibility !== "collapse" && rect.width > 0 && rect.height > 0;
- };
const explicitRole = (element) => (element.getAttribute("role") || "").toLowerCase();
const nativeRole = (element) => {
const tag = element.tagName.toLowerCase();
@@ -639,7 +643,6 @@ _OBSERVE_INTERACTABLES_JS = r"""
if (tag !== "input") return "";
return { checkbox: "checkbox", radio: "radio", range: "slider", search: "searchbox" }[type] || "textbox";
};
- const widgetRoles = new Set(["button", "checkbox", "combobox", "link", "listbox", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "searchbox", "slider", "spinbutton", "switch", "tab", "textbox", "treeitem"]);
const pointer = (element) => window.getComputedStyle(element)?.cursor === "pointer";
const staticClick = (element) => element.hasAttribute("onclick") || typeof element.onclick === "function" || element.hasAttribute("jsaction");
const frameworkClick = (element) => {
@@ -650,10 +653,6 @@ _OBSERVE_INTERACTABLES_JS = r"""
return false;
}
};
- const knownClass = (element) => {
- const className = classes(element);
- return className.includes("dropdown-item") || className.includes("ui-menu-item") || className.includes("pac-item") || className.includes("rddlItem") || className === "option";
- };
const ancestorMatching = (element, predicate) => {
for (let current = element.parentElement, depth = 0; current && depth < 5; current = current.parentElement, depth += 1) {
if (predicate(current)) return current;
@@ -672,25 +671,48 @@ _OBSERVE_INTERACTABLES_JS = r"""
});
const optionLike = (element) => Boolean(text(element) && optionContainer(element) && interactiveAncestor(element));
const roleFor = (element) => explicitRole(element) || nativeRole(element) || (optionLike(element) ? "option" : "button");
- const candidate = (element) => {
- if (!visible(element) || (window.getComputedStyle(element)?.pointerEvents === "none" && !element.disabled)) return false;
- const tag = element.tagName.toLowerCase();
- return Boolean(nativeRole(element) || widgetRoles.has(explicitRole(element)) || staticClick(element) || frameworkClick(element) || knownClass(element) || pointer(element) || (tag === "div" && element.getAttribute("tabindex") === "0") || optionLike(element));
- };
-
- // querySelectorAll excludes the root itself — a scoped observe must still surface the scoped element.
- return (scopeSelector ? [root, ...root.querySelectorAll("*")] : Array.from(root.querySelectorAll("*")))
- .filter(candidate)
- .map((element) => {
- const tag = element.tagName.toLowerCase();
- const item = { role: roleFor(element), name: text(element), tag, selector: cssPath(element) };
- if (includeValues === true && !isPassword(element) && ["input", "textarea", "select", "option"].includes(tag)) {
- item.value = element.value || element.getAttribute("value") || "";
- }
- if (tag === "select") item.options = Array.from(element.options).map((option) => text(option));
- return item;
- })
- .filter((item) => item.name || item.role);
+ // The bare-option overlay must never resurface an element the production predicate rejected
+ // for being invisible, hidden, or inert — a hidden input surfaced here would leak its value
+ // through the name fallback.
+ const overlayEligible = (element) =>
+ isElementVisible(element) &&
+ !isHidden(element) &&
+ !isScriptOrStyle(element) &&
+ !(getElementComputedStyle(element)?.pointerEvents === "none" && !element.disabled && !isHoverOnlyElement(element));
+ // Overlay: bare options inside an interactive option container are driver-discoverable even
+ // though the production predicate ignores them. "Bare" is strict: anything with a native or
+ // explicit role (or a frame-family tag) gets production's FULL verdict, including its later
+ // vetoes (disabled-select options, frame exclusions) — the overlay never overrides those.
+ const overlayVetoedTags = new Set(["html", "iframe", "frame", "frameset"]);
+ const bareElement = (element) => !overlayVetoedTags.has(element.tagName.toLowerCase()) && !nativeRole(element) && !explicitRole(element);
+ const candidate = (element) => isInteractable(element, hoverStylesMap) || (bareElement(element) && overlayEligible(element) && optionLike(element));
+
+ // A later production scrape must compute hover styles at ITS OWN time: cache ownership is
+ // snapshotted in the same evaluation and restored in finally (identity-guarded). Ceiling:
+ // two FIRST-TIME builds interleaving is last-writer-wins inside getHoverStylesMap, so the
+ // loser costs one spare recompute — never a stale cache.
+ const hadHoverCache = Boolean(window.globalHoverStylesMap);
+ try {
+ hoverStylesMap = await getHoverStylesMap();
+ // querySelectorAll excludes the root itself — a scoped observe must still surface the scoped element.
+ // The scan deliberately stays light-DOM-only; shadow roots are not traversed.
+ return (scopeSelector ? [root, ...root.querySelectorAll("*")] : Array.from(root.querySelectorAll("*")))
+ .filter(candidate)
+ .map((element) => {
+ const tag = element.tagName.toLowerCase();
+ const item = { role: roleFor(element), name: text(element), tag, selector: cssPath(element) };
+ if (includeValues === true && !isPassword(element) && ["input", "textarea", "select", "option"].includes(tag)) {
+ item.value = element.value || element.getAttribute("value") || "";
+ }
+ if (tag === "select") item.options = Array.from(element.options).map((option) => text(option));
+ return item;
+ })
+ .filter((item) => item.name || item.role);
+ } finally {
+ if (!hadHoverCache && window.globalHoverStylesMap === hoverStylesMap) {
+ window.globalHoverStylesMap = undefined;
+ }
+ }
}
"""
@@ -839,6 +861,16 @@ class ObservedElement:
needs_disambiguation: bool = False
+class ObserveFrameError(RuntimeError):
+ """Failure to evaluate an observe snapshot inside the selected frame."""
+
+ def __init__(self, frame_name: str, frame_url: str, cause: Exception) -> None:
+ self.frame_name = frame_name
+ self.frame_url = frame_url
+ frame_id = frame_name or frame_url or "<unnamed>"
+ super().__init__(f"Failed to evaluate observe in frame {frame_id!r}: {cause}")
+
+
@dataclass
class ObserveResult:
url: str
@@ -876,16 +908,26 @@ async def _get_dom_observe_elements(
page: Any,
selector: str | None = None,
include_values: bool = False,
+ *,
+ frame_name: str | None = None,
+ frame_url: str | None = None,
) -> list[dict[str, Any]]:
evaluate = getattr(page, "evaluate", None)
if evaluate is None:
+ if frame_name is not None:
+ raise ObserveFrameError(frame_name, frame_url or "", RuntimeError("frame does not support evaluate"))
return []
try:
- result = await evaluate(
- _OBSERVE_INTERACTABLES_JS,
- {"scopeSelector": selector, "includeValues": include_values},
- )
- except Exception:
+ async with asyncio.timeout(_DOM_SCAN_TIMEOUT_SECONDS):
+ if await evaluate(_DOMUTILS_INTERACTABILITY_READY_JS) is not True:
+ await evaluate(JS_FUNCTION_DEFS)
+ result = await evaluate(
+ _OBSERVE_INTERACTABLES_JS,
+ {"scopeSelector": selector, "includeValues": include_values},
+ )
+ except Exception as exc:
+ if frame_name is not None:
+ raise ObserveFrameError(frame_name, frame_url or "", exc) from exc
return []
if not isinstance(result, list):
return []
@@ -960,17 +1002,51 @@ async def do_observe(
# Execute-step params arrive as untyped JSON; a string like "false" must not
# enable value capture — the opt-in counts only as a literal boolean True.
include_values = include_values is True
- accessibility = getattr(page, "accessibility", None)
- if selector and accessibility is not None:
- element_handle = await page.locator(selector).first.element_handle()
- snapshot = await accessibility.snapshot(root=element_handle)
- elif accessibility is not None:
- snapshot = await accessibility.snapshot()
- else:
+ working_frame = getattr(page, "_working_frame", None)
+ if working_frame is not None:
+ # A popup or tab change can make get_page() resolve a different page than the
+ # one the selected frame belongs to — observing that frame would report the
+ # wrong document as if it were the active page.
+ owner = getattr(working_frame, "page", None)
+ raw_page = getattr(page, "page", page)
+ if owner is not None and owner is not raw_page:
+ raise ObserveFrameError(
+ working_frame.name,
+ working_frame.url,
+ RuntimeError("frame belongs to a different page or tab"),
+ )
+ try:
+ detached = working_frame.is_detached()
+ except AttributeError:
+ detached = False
+ if detached:
+ raise ObserveFrameError(
+ working_frame.name,
+ working_frame.url,
+ RuntimeError("frame is detached"),
+ )
+ observe_target = working_frame if working_frame is not None else page
+ if working_frame is not None:
+ # Legacy page accessibility iframe roots are unreliable; DOM-only avoids cross-document merges.
snapshot = None
+ else:
+ accessibility = getattr(page, "accessibility", None)
+ if selector and accessibility is not None:
+ element_handle = await page.locator(selector).first.element_handle()
+ snapshot = await accessibility.snapshot(root=element_handle)
+ elif accessibility is not None:
+ snapshot = await accessibility.snapshot()
+ else:
+ snapshot = None
all_elements = _flatten_a11y_tree(snapshot)
- dom_elements = await _get_dom_observe_elements(page, selector, include_values)
+ dom_elements = await _get_dom_observe_elements(
+ observe_target,
+ selector,
+ include_values,
+ frame_name=working_frame.name if working_frame is not None else None,
+ frame_url=working_frame.url if working_frame is not None else None,
+ )
if interactive_only:
all_elements = [e for e in all_elements if e.get("role") in INTERACTIVE_ROLES]
@@ -1023,9 +1099,17 @@ async def do_observe(
)
)
+ if working_frame is not None:
+ try:
+ title = await working_frame.title()
+ except Exception as exc:
+ raise ObserveFrameError(working_frame.name, working_frame.url, exc) from exc
+ else:
+ title = await page.title()
+
return ObserveResult(
- url=page.url,
- title=await page.title(),
+ url=working_frame.url if working_frame is not None else page.url,
+ title=title,
elements=observed,
element_count=len(observed),
total_on_page=total,
@@ -1181,6 +1265,10 @@ async def do_execute(
wall_ms = int((time.monotonic() - t0) * 1000)
error_payload: str | dict[str, Any] = e.error if isinstance(e, ToolStepError) else str(e)
results.append(StepResult(step=i, tool=step.tool, ok=False, wall_ms=wall_ms, error=error_payload))
+ if step.tool == "observe":
+ # A failed observe means the document may have been replaced; refs from
+ # an earlier observe in this batch must not survive it.
+ ref_map = {}
if step.tool == "navigate":
nav_failed = True
if stop_on_error:
diff --git a/skyvern/cli/core/session_manager.py b/skyvern/cli/core/session_manager.py
index c73272b95..8d1493c05 100644
--- a/skyvern/cli/core/session_manager.py
+++ b/skyvern/cli/core/session_manager.py
@@ -107,12 +107,13 @@ def _identity_token(obj: Page | Frame) -> int:
return token
-def page_ref_key(page: SkyvernBrowserPage) -> tuple[int, int | None, str]:
+def page_ref_key(page: SkyvernBrowserPage) -> tuple[int, int | None, str, str | None]:
"""Identity of the document context a ref snapshot was taken from."""
return (
_identity_token(page.page),
_identity_token(page._working_frame) if page._working_frame is not None else None,
page.url,
+ page._working_frame.url if page._working_frame is not None else None,
)
@@ -165,7 +166,7 @@ def replace_session_ref_map(
session_id: str | None = None,
cdp_url: str | None = None,
generation: int | None = None,
- page_key: tuple[int, int | None, str] | None = None,
+ page_key: tuple[int, int | None, str, str | None] | None = None,
) -> bool:
"""Replace the session's ref snapshot (never merge). Returns False if discarded.
@@ -193,7 +194,7 @@ def get_session_ref(
*,
session_id: str | None = None,
cdp_url: str | None = None,
- page_key: tuple[int, int | None, str] | None = None,
+ page_key: tuple[int, int | None, str, str | None] | None = None,
) -> dict[str, Any] | None:
"""Resolve a ref, failing closed when the snapshot was bound to a different
page/frame than the one the caller is on (popup steal, external tab close,
@@ -504,17 +505,13 @@ async def get_page(
# Propagate iframe frame context from session state to the page
if state._working_frame is not None:
- # Guard against stale (detached) frame references
- detached = False
try:
detached = state._working_frame.is_detached()
except AttributeError:
- pass # frame object doesn't support is_detached (e.g., test mocks)
+ detached = False # frame object doesn't support is_detached (e.g., test mocks)
if detached:
- LOG.debug("Clearing detached _working_frame from session state")
- state._working_frame = None
- else:
- page._working_frame = state._working_frame
+ LOG.debug("Propagating detached _working_frame for explicit action failure")
+ page._working_frame = state._working_frame
return page, ctx
diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.py
index eb1aba17b..f60558419 100644
--- a/skyvern/cli/mcp_tools/browser.py
+++ b/skyvern/cli/mcp_tools/browser.py
@@ -15,6 +15,7 @@ from skyvern.cli.core.browser_ops import (
_ALLOWED_EXECUTE_TOOLS,
MAX_EXECUTE_STEPS,
ExecuteStep,
+ ObserveFrameError,
ToolStepError,
do_act,
do_execute,
@@ -2258,6 +2259,17 @@ async def skyvern_clipboard_write(
# ---------------------------------------------------------------------------
+def _observe_frame_error(error: ObserveFrameError) -> dict[str, Any]:
+ frame_id = error.frame_name or error.frame_url or "<unnamed>"
+ return make_error(
+ ErrorCode.ACTION_FAILED,
+ f"Failed to observe frame {frame_id!r}",
+ "Use skyvern_frame_list to verify the frame, skyvern_frame_main to leave it, "
+ "or switch again before retrying selector-based click/type tools",
+ details={"frame_name": error.frame_name, "frame_url": error.frame_url},
+ )
+
+
async def skyvern_observe(
selector: Annotated[
str | None,
@@ -2305,6 +2317,15 @@ async def skyvern_observe(
include_values=include_values,
)
timer.mark("sdk")
+ except ObserveFrameError as e:
+ clear_session_ref_map(session_id=ctx.session_id, cdp_url=ctx.cdp_url)
+ return make_result(
+ "skyvern_observe",
+ ok=False,
+ browser_context=ctx,
+ timing_ms=timer.timing_ms,
+ error=_observe_frame_error(e),
+ )
except Exception as e:
return make_result(
"skyvern_observe",
@@ -2386,8 +2407,8 @@ async def _dispatch_step(
ref_map: dict[str, dict[str, Any]],
session_id: str | None,
cdp_url: str | None,
- page_key: tuple[int, int | None, str] | None = None,
- on_observe_page: Callable[[tuple[int, int | None, str]], None] | None = None,
+ page_key: tuple[int, int | None, str, str | None] | None = None,
+ on_observe_page: Callable[[tuple[int, int | None, str, str | None]], None] | None = None,
) -> dict[str, Any] | None:
"""Route a step to the appropriate handler, resolving refs to selectors."""
params = dict(step.params)
@@ -2414,7 +2435,11 @@ async def _dispatch_step(
on_observe_page(page_ref_key(page))
accepted = {"selector", "interactive_only", "max_elements", "include_values"}
filtered = {k: v for k, v in params.items() if k in accepted}
- result = await _do_observe(page, **filtered)
+ try:
+ result = await _do_observe(page, **filtered)
+ except ObserveFrameError as e:
+ clear_session_ref_map(session_id=session_id, cdp_url=cdp_url)
+ raise ToolStepError(_observe_frame_error(e)) from e
return {
"elements": serialize_elements(result.elements),
"element_count": result.element_count,
@@ -2527,9 +2552,9 @@ async def skyvern_execute(
# Generation captured before each observe dispatch so a snapshot that raced
# a concurrent navigation/context switch is discarded, not committed.
observe_generation: dict[str, int] = {}
- observe_page_key: tuple[int, int | None, str] | None = None
+ observe_page_key: tuple[int, int | None, str, str | None] | None = None
- def capture_observe_page_key(page_key: tuple[int, int | None, str]) -> None:
+ def capture_observe_page_key(page_key: tuple[int, int | None, str, str | None]) -> None:
nonlocal observe_page_key
observe_page_key = page_key
diff --git a/skyvern/cli/run_commands.py b/skyvern/cli/run_commands.py
index 0c0defc0f..007fa0225 100644
--- a/skyvern/cli/run_commands.py
+++ b/skyvern/cli/run_commands.py
@@ -1,12 +1,16 @@
+import _thread
import asyncio
import atexit
import json
import logging
import os
+import select
import shutil
+import signal
import subprocess
import sys
-from typing import TYPE_CHECKING, Annotated, List, Literal, Optional
+import threading
+from typing import TYPE_CHECKING, Annotated, Any, List, Literal, Optional, cast
if TYPE_CHECKING:
from starlette.types import ASGIApp, Receive, Scope, Send
@@ -35,6 +39,14 @@ from skyvern.utils.env_paths import (
run_app = typer.Typer(help="Commands to run Skyvern services such as the API server or UI.")
_mcp_cleanup_done = False
+_mcp_cleanup_in_progress = False
+_mcp_eof_shutdown_requested = False
+_MCP_GRACEFUL_CLEANUP_TIMEOUT_SECONDS = 5.0
+_MCP_PROCESS_KILL_TIMEOUT_SECONDS = 2.0
+_MCP_NATIVE_EOF_GRACE_SECONDS = 0.25
+# The EOF watcher's os._exit(0) preempts cleanup unconditionally, so this must exceed
+# the cloud path's graceful join plus process-kill wait.
+_MCP_EOF_SHUTDOWN_TIMEOUT_SECONDS = 10.0
def _default_host() -> str:
@@ -57,31 +69,196 @@ async def _cleanup_mcp_resources() -> None:
def _cleanup_mcp_resources_blocking() -> None:
- global _mcp_cleanup_done
- if _mcp_cleanup_done:
+ global _mcp_cleanup_done, _mcp_cleanup_in_progress
+ # CPython runs signal handlers on the main thread, and all callers stay on that thread.
+ if _mcp_cleanup_done or _mcp_cleanup_in_progress:
return
+ _mcp_cleanup_in_progress = True
try:
- asyncio.run(_cleanup_mcp_resources())
+ logger = logging.getLogger(__name__)
+ try:
+ local_browser_identity = _current_local_browser_identity()
+ except Exception:
+ logger.warning("Failed to identify the local MCP browser", exc_info=True)
+ local_browser_identity = None
+ # In stdio, this main-thread read and a cleanup thread both resolve _global_session because
+ # ContextVars are not inherited. The exclusive mode means local identity cannot hide a cloud close.
+ if local_browser_identity is not None:
+ try:
+ # Playwright objects belong to mcp.run's closed loop; a fresh-loop close hangs forever.
+ # The owned profile is an anonymous mkdtemp throwaway, so clean it up directly.
+ try:
+ _kill_local_browser_process_tree(local_browser_identity[0], local_browser_identity[1])
+ finally:
+ if local_browser_identity[2] and local_browser_identity[1]:
+ shutil.rmtree(local_browser_identity[1], ignore_errors=True)
+ except Exception:
+ logger.warning("MCP local browser cleanup failed", exc_info=True)
+ else:
+ cleanup_errors: list[BaseException] = []
+
+ def run_cleanup() -> None:
+ try:
+ asyncio.run(_cleanup_mcp_resources())
+ except BaseException as exc:
+ cleanup_errors.append(exc)
+
+ cleanup_thread = threading.Thread(target=run_cleanup, name="skyvern-mcp-cleanup", daemon=True)
+ cleanup_thread.start()
+ cleanup_thread.join(_MCP_GRACEFUL_CLEANUP_TIMEOUT_SECONDS)
+ if cleanup_thread.is_alive():
+ logger.warning("MCP graceful cleanup timed out")
+ elif cleanup_errors:
+ error = cleanup_errors[0]
+ logger.warning("MCP graceful cleanup failed", exc_info=(type(error), error, error.__traceback__))
+ finally:
_mcp_cleanup_done = True
- except Exception:
- logging.getLogger(__name__).warning("MCP cleanup failed", exc_info=True)
+ _mcp_cleanup_in_progress = False
def _cleanup_mcp_resources_sync() -> None:
- """Atexit callback for MCP cleanup. Skips if an event loop is still running
- because asyncio.run() cannot be called inside a running loop. This means
- cleanup is best-effort for signal-based exits (e.g. SIGTERM) that fire atexit
- while the MCP server's loop is still alive -- the finally block in run_mcp()
- handles normal shutdown instead."""
- logger = logging.getLogger(__name__)
+ """Atexit callback for MCP cleanup."""
+ _cleanup_mcp_resources_blocking()
+
+
+def _current_local_browser_identity() -> tuple[int | None, str | None, bool] | None:
+ from skyvern.cli.core.session_manager import get_current_session # noqa: PLC0415
+
+ current = get_current_session()
+ if current.context is None or current.context.mode != "local" or current.browser is None:
+ return None
+ return (
+ current.browser.local_cdp_port,
+ current.browser.local_user_data_dir,
+ current.browser.local_user_data_dir_owned,
+ )
+
+
+def _find_local_browser_processes(port: int | None, user_data_dir: str | None) -> list[psutil.Process]:
+ if user_data_dir is None:
+ return []
+
+ processes: dict[int, psutil.Process] = {}
+ user_data_arg = f"--user-data-dir={user_data_dir}"
try:
- asyncio.get_running_loop()
- except RuntimeError:
- _cleanup_mcp_resources_blocking()
+ for process in psutil.process_iter(["pid", "cmdline"]):
+ try:
+ if user_data_arg in ((process.info or {}).get("cmdline") or []):
+ processes[process.pid] = process
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
+ pass
+ except Exception:
+ logging.getLogger(__name__).warning("Failed to inspect local browser processes", exc_info=True)
+ return list(processes.values())
+
+
+def _local_browser_process_tree(port: int | None, user_data_dir: str | None) -> list[psutil.Process]:
+ processes: dict[int, psutil.Process] = {}
+ # The Playwright node driver is Chromium's parent, not its descendant; stdin EOF reaps that driver.
+ for root in _find_local_browser_processes(port, user_data_dir):
+ processes[root.pid] = root
+ try:
+ processes.update({process.pid: process for process in root.children(recursive=True)})
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
+ pass
+ return list(processes.values())
+
+
+def _kill_local_browser_process_tree(
+ port: int | None,
+ user_data_dir: str | None,
+ *,
+ known_processes: list[psutil.Process] | None = None,
+) -> None:
+ if user_data_dir is None:
return
- logger.debug("Skipping MCP cleanup because event loop is still running")
+ processes = {process.pid: process for process in known_processes or []}
+ processes.update({process.pid: process for process in _local_browser_process_tree(port, user_data_dir)})
+
+ for process in processes.values():
+ try:
+ process.kill()
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
+ pass
+ if processes:
+ psutil.wait_procs(list(processes.values()), timeout=_MCP_PROCESS_KILL_TIMEOUT_SECONDS)
+
+
+def _watch_stdin_eof(
+ stop: threading.Event,
+ shutdown_complete: threading.Event,
+ *,
+ stdin_fd: int | None = None,
+ request_shutdown: Any | None = None,
+ force_exit: Any | None = None,
+ native_eof_grace: float = _MCP_NATIVE_EOF_GRACE_SECONDS,
+ shutdown_timeout: float = _MCP_EOF_SHUTDOWN_TIMEOUT_SECONDS,
+) -> None:
+ def request_bounded_shutdown() -> None:
+ global _mcp_eof_shutdown_requested
+ if shutdown_complete.wait(native_eof_grace) or stop.is_set():
+ return
+ _mcp_eof_shutdown_requested = True
+ (request_shutdown or _thread.interrupt_main)()
+ if shutdown_complete.wait(shutdown_timeout):
+ return
+ try:
+ local_browser_identity = _current_local_browser_identity()
+ if local_browser_identity is not None:
+ try:
+ _kill_local_browser_process_tree(local_browser_identity[0], local_browser_identity[1])
+ finally:
+ if local_browser_identity[2] and local_browser_identity[1]:
+ shutil.rmtree(local_browser_identity[1], ignore_errors=True)
+ except Exception:
+ logging.getLogger(__name__).warning("MCP EOF fallback cleanup failed", exc_info=True)
+ (force_exit or os._exit)(0)
+
+ try:
+ if hasattr(select, "poll"):
+ poller = select.poll()
+ shutdown_events = select.POLLHUP | select.POLLERR | select.POLLNVAL
+ poller.register(sys.stdin.fileno() if stdin_fd is None else stdin_fd, shutdown_events)
+ while not stop.is_set():
+ if any(event & shutdown_events for _fd, event in poller.poll(100)):
+ if not stop.is_set():
+ request_bounded_shutdown()
+ return
+ return
+
+ peek = cast(Any, sys.stdin.buffer).peek
+ while not stop.is_set(): # pragma: no cover - Windows pipe fallback
+ if not peek(1):
+ if not stop.is_set():
+ request_bounded_shutdown()
+ return
+ stop.wait(0.05)
+ except (AttributeError, OSError, ValueError):
+ logging.getLogger(__name__).warning("MCP stdin EOF watcher failed", exc_info=True)
+
+
+def _start_stdin_eof_watcher() -> tuple[threading.Event, threading.Event]:
+ stop, shutdown_complete = threading.Event(), threading.Event()
+ threading.Thread(
+ target=_watch_stdin_eof,
+ args=(stop, shutdown_complete),
+ name="skyvern-mcp-stdin-eof",
+ daemon=True,
+ ).start()
+ return stop, shutdown_complete
+
+
+def _handle_mcp_shutdown_signal(_signum: int, _frame: Any) -> None:
+ if _mcp_cleanup_in_progress:
+ return
+ try:
+ _cleanup_mcp_resources_blocking()
+ finally:
+ # Exit 0 only for the EOF watcher's synthetic SIGINT; a real SIGTERM keeps 143.
+ eof_initiated = _mcp_eof_shutdown_requested and _signum == signal.SIGINT
+ os._exit(0 if eof_initiated else 128 + _signum)
def get_pids_on_port(port: int) -> List[int]:
@@ -449,6 +626,8 @@ def run_mcp(
] = False,
) -> None:
"""Run the MCP server with configurable transport for local or remote hosting."""
+ global _mcp_eof_shutdown_requested
+ _mcp_eof_shutdown_requested = False
prepare_cli_runtime(intent=EnvIntent.CLOUD)
from skyvern.cli.core.mcp_http_auth import MCPAPIKeyMiddleware # noqa: PLC0415
from skyvern.cli.core.session_manager import set_stateless_http_mode # noqa: PLC0415
@@ -458,14 +637,18 @@ def run_mcp(
path = _normalize_mcp_path(path)
stateless_http_enabled = transport != "stdio" and stateless_http
configure_mcp_telemetry_runtime(server_mode="local_cli", transport=transport)
- # atexit covers signal-based exits (SIGTERM); finally covers normal
- # mcp.run() completion or unhandled exceptions. Both are needed because
- # atexit doesn't fire on normal return and finally doesn't fire on signals.
+ # EOF dispatches the SIGINT cleanup handler; finally covers normal returns, with atexit as the last backstop.
atexit.register(_cleanup_mcp_resources_sync)
set_stateless_http_mode(stateless_http_enabled)
set_concise_responses(not verbose)
+ eof_watcher_stop: threading.Event | None = None
+ shutdown_complete: threading.Event | None = None
+ original_signal_handlers: dict[signal.Signals, Any] = {}
try:
if transport == "stdio":
+ original_signal_handlers[signal.SIGINT] = signal.signal(signal.SIGINT, _handle_mcp_shutdown_signal)
+ original_signal_handlers[signal.SIGTERM] = signal.signal(signal.SIGTERM, _handle_mcp_shutdown_signal)
+ eof_watcher_stop, shutdown_complete = _start_stdin_eof_watcher()
mcp.run(transport="stdio")
return
@@ -482,9 +665,17 @@ def run_mcp(
stateless_http=stateless_http_enabled,
)
finally:
- set_stateless_http_mode(False)
- set_concise_responses(False)
- _cleanup_mcp_resources_blocking()
+ if eof_watcher_stop is not None:
+ eof_watcher_stop.set()
+ try:
+ set_stateless_http_mode(False)
+ set_concise_responses(False)
+ _cleanup_mcp_resources_blocking()
+ finally:
+ for handled_signal, original_handler in original_signal_handlers.items():
+ signal.signal(handled_signal, original_handler)
+ if shutdown_complete is not None:
+ shutdown_complete.set()
def _normalize_mcp_path(path: str) -> str:
diff --git a/skyvern/core/script_generations/generate_script.py b/skyvern/core/script_generations/generate_script.py
index 6aff19f2e..358547703 100644
--- a/skyvern/core/script_generations/generate_script.py
+++ b/skyvern/core/script_generations/generate_script.py
@@ -1640,6 +1640,50 @@ def _build_download_statement(
) -> cst.SimpleStatementLine:
"""Build a skyvern.download statement."""
args = __build_base_task_statement(block_title, block, data_variable_name, value_to_param=value_to_param)
+ download_target = str(block.get("download_target") or "")
+ destination_fields_by_target = {
+ "s3": ["s3_bucket", "aws_access_key_id", "aws_secret_access_key", "region_name"],
+ "azure": ["azure_storage_account_name", "azure_storage_account_key", "azure_blob_container_name"],
+ "google_drive": ["google_credential_id", "google_drive_folder_id"],
+ "sftp": [
+ "sftp_host",
+ "sftp_port",
+ "sftp_username",
+ "sftp_password",
+ "sftp_private_key",
+ "sftp_private_key_passphrase",
+ "sftp_remote_path",
+ "sftp_host_key",
+ ],
+ }
+ destination_fields = destination_fields_by_target.get(download_target)
+ if destination_fields is not None and block.get("prompt") is not None:
+ args[0] = args[0].with_changes(keyword=cst.Name("navigation_goal"))
+
+ if destination_fields is not None:
+ args.append(
+ cst.Arg(
+ keyword=cst.Name("download_target"),
+ value=_value(download_target),
+ whitespace_after_arg=cst.ParenthesizedWhitespace(
+ indent=True,
+ last_line=cst.SimpleWhitespace(INDENT),
+ ),
+ )
+ )
+ for key in [*destination_fields, "prompt", "path", "continue_on_empty"]:
+ if block.get(key) is not None:
+ args.append(
+ cst.Arg(
+ keyword=cst.Name(key),
+ value=_value(block.get(key, "")),
+ whitespace_after_arg=cst.ParenthesizedWhitespace(
+ indent=True,
+ last_line=cst.SimpleWhitespace(INDENT),
+ ),
+ )
+ )
+ _mark_last_arg_as_comma(args)
call = cst.Call(
func=cst.Attribute(value=cst.Name("skyvern"), attr=cst.Name("download")),
args=args,
diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.py
index 0fea9622e..f6d4ce814 100644
--- a/skyvern/forge/sdk/copilot/blocker_signal.py
+++ b/skyvern/forge/sdk/copilot/blocker_signal.py
@@ -196,6 +196,39 @@ def build_output_source_unobservable_blocker_signal(
)
+def build_definition_contract_unsatisfied_blocker_signal(
+ *, unresolved_parameter_keys: Iterable[str], grounding_unresolved: bool = False
+) -> CopilotToolBlockerSignal:
+ parameter_keys = sorted({str(key).strip() for key in unresolved_parameter_keys if str(key).strip()})
+ if parameter_keys:
+ key_text = ", ".join(f"`{key}`" for key in parameter_keys)
+ user_facing = (
+ f"I kept the workflow draft, but I could not safely connect the current page fields to these reusable "
+ f"inputs: {key_text}. No workflow run was started."
+ if grounding_unresolved
+ else f"I kept the workflow draft, but it cannot run because these reusable inputs are not used: "
+ f"{key_text}. Connect each input to the workflow before trying again."
+ )
+ else:
+ user_facing = (
+ "I kept the workflow draft, but it does not yet satisfy the required workflow definition. "
+ "Complete the missing definition requirements before trying again."
+ )
+ return CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text=(
+ "The exact candidate failed its definition contract before execution. Preserve the draft, stop this "
+ "turn, and explain the unresolved reusable inputs without dispatching the candidate."
+ ),
+ user_facing_reason=user_facing,
+ recovery_hint="report_blocker_to_user",
+ preserves_workflow_draft=True,
+ renders_final_reply=True,
+ internal_reason_code=DEFINITION_CONTRACT_UNSATISFIED_REASON_CODE,
+ extra={"unresolved_parameter_keys": parameter_keys, "grounding_unresolved": grounding_unresolved},
+ )
+
+
def build_llm_tool_error_payload(signal: CopilotToolBlockerSignal) -> str:
return signal.agent_steering_text
@@ -344,6 +377,7 @@ _TERMINAL_CHALLENGE_REPLACEABLE_REASON_CODES = frozenset({"tool_error_post_budge
SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE = "tool_error_synthesized_block_persistence_required"
UNCOVERED_OUTPUT_RESCOUT_STEER_REASON_CODE = "tool_error_uncovered_output_rescout_steer"
RECORDED_OUTCOME_GROUNDING_REASON_CODE = "recorded_outcome_grounding_required"
+DEFINITION_CONTRACT_UNSATISFIED_REASON_CODE = "definition_contract_unsatisfied"
SCHEMA_INCOMPATIBILITY_REASON_CODE = "schema_incompatibility"
_OUTPUT_CONTRACT_TERMINAL_REASON_CODES = frozenset(
{OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODE, OUTPUT_CONTRACT_ACTUATION_EXHAUSTED_REASON_CODE}
@@ -363,6 +397,7 @@ GENUINELY_TERMINAL_BLOCKER_REASON_CODES: frozenset[str] = frozenset(
OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODE,
OUTPUT_CONTRACT_ACTUATION_EXHAUSTED_REASON_CODE,
"advisory_dispatch_stalled",
+ DEFINITION_CONTRACT_UNSATISFIED_REASON_CODE,
"repair_ceiling_reached",
}
)
diff --git a/skyvern/forge/sdk/copilot/build_test_outcome.py b/skyvern/forge/sdk/copilot/build_test_outcome.py
index 028eceb69..ffe49946c 100644
--- a/skyvern/forge/sdk/copilot/build_test_outcome.py
+++ b/skyvern/forge/sdk/copilot/build_test_outcome.py
@@ -60,6 +60,7 @@ BuildTestOutcomeReasonCode = Literal[
"output_policy_reject",
"scout_act_observe_hollow_after_interaction",
"required_input_unbound",
+ "definition_contract_unsatisfied",
"fallback_floor_turn_unsatisfiable",
"output_source_unobservable",
"actuation_exhausted",
@@ -344,6 +345,7 @@ def _binding_frontier_facet(outcome: RecordedBuildTestOutcome) -> BindingFrontie
"sandbox_unresolved_name",
"synthesized_parameter_binding_ambiguous",
"required_input_unbound",
+ "definition_contract_unsatisfied",
}:
return "amend_in_place"
if outcome.reason_code in {"outcome_not_demonstrated", "no_meaningful_output", "runtime_missing_output_dependency"}:
@@ -465,6 +467,8 @@ def recorded_outcome_grounding_requires_current_page(ctx: object) -> bool:
requirement = getattr(ctx, "recorded_outcome_grounding_requirement", None)
if not isinstance(requirement, RecordedOutcomeGroundingRequirement) or requirement.satisfied:
return False
+ if requirement.phase == "author_time_reject":
+ return True
if isinstance(requirement.workflow_run_id, str) and requirement.workflow_run_id:
return True
evidence = getattr(ctx, "composition_page_evidence", None)
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.py
index 7502a54d3..12b06819b 100644
--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py
+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py
@@ -33,7 +33,7 @@ from skyvern.forge.sdk.copilot.output_extraction_plan import (
output_path_segments,
)
from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget
-from skyvern.forge.sdk.copilot.runtime import ScoutedInputCorrespondence
+from skyvern.forge.sdk.copilot.runtime import ScoutedFieldParameterBinding, ScoutedInputCorrespondence
from skyvern.utils.strings import escape_code_fences
LOG = structlog.get_logger()
@@ -300,6 +300,7 @@ class SynthesisDiagnostics:
# (trajectory enumerate index -> minted type_text parameter key); diagnostics-only, never serialized.
# Recovers the key for a typed field whose value was withheld from default_value (typed_value == "").
typed_param_bindings: list[tuple[int, str]] = field(default_factory=list)
+ grounded_submit_binding_fingerprints: list[str] = field(default_factory=list)
@dataclass
@@ -315,6 +316,86 @@ class SynthesizedCodeBlock:
extraction_plan_identity: str = ""
+def grounded_parameter_key_is_safe(parameter_key: str) -> bool:
+ return (
+ parameter_key.isidentifier()
+ and not keyword.iskeyword(parameter_key)
+ and not parameter_key.startswith("__")
+ and parameter_key not in _RESERVED_PARAM_NAMES
+ )
+
+
+def grounded_submit_rung_binding_fingerprint(
+ *,
+ repeated_structural_key: str,
+ source_url: str,
+ submit_selector: str,
+ submit_trajectory_index: int,
+ field_bindings: Sequence[ScoutedFieldParameterBinding],
+) -> str:
+ payload = {
+ "repeated_structural_key": repeated_structural_key,
+ "source_url": source_url,
+ "submit_selector": submit_selector,
+ "submit_trajectory_index": submit_trajectory_index,
+ "field_bindings": [
+ {
+ "parameter_key": binding["parameter_key"],
+ "field_selector": binding["field_selector"],
+ }
+ for binding in field_bindings
+ ],
+ }
+ return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+
+
+def _validated_submit_rung_binding(
+ interaction: Mapping[str, Any], trajectory_index: int
+) -> tuple[str, tuple[tuple[str, str], ...]] | None:
+ raw = interaction.get("submit_rung_binding")
+ if not isinstance(raw, Mapping) or str(interaction.get("tool_name") or "") != "click":
+ return None
+ repeated_structural_key = str(raw.get("repeated_structural_key") or "").strip()
+ fingerprint = str(raw.get("fingerprint") or "").strip()
+ raw_fields = raw.get("field_bindings")
+ if not repeated_structural_key or not fingerprint or not isinstance(raw_fields, list) or not raw_fields:
+ return None
+ fields: list[ScoutedFieldParameterBinding] = []
+ parameter_keys: set[str] = set()
+ field_selectors: set[str] = set()
+ for raw_field in raw_fields:
+ if not isinstance(raw_field, Mapping):
+ return None
+ parameter_key = str(raw_field.get("parameter_key") or "").strip()
+ field_selector = str(raw_field.get("field_selector") or "").strip()
+ if (
+ not grounded_parameter_key_is_safe(parameter_key)
+ or not field_selector
+ or parameter_key in parameter_keys
+ or field_selector in field_selectors
+ ):
+ return None
+ parameter_keys.add(parameter_key)
+ field_selectors.add(field_selector)
+ fields.append({"parameter_key": parameter_key, "field_selector": field_selector})
+ if [field["parameter_key"] for field in fields] != sorted(parameter_keys):
+ return None
+ submit_selector = str(interaction.get("selector") or "").strip()
+ source_url = str(interaction.get("source_url") or "").strip()
+ if not submit_selector or not source_url:
+ return None
+ expected = grounded_submit_rung_binding_fingerprint(
+ repeated_structural_key=repeated_structural_key,
+ source_url=source_url,
+ submit_selector=submit_selector,
+ submit_trajectory_index=trajectory_index,
+ field_bindings=fields,
+ )
+ if fingerprint != expected:
+ return None
+ return fingerprint, tuple((field["parameter_key"], field["field_selector"]) for field in fields)
+
+
@dataclass(frozen=True, slots=True)
class SynthesizedExtractionSuffix:
code: str
@@ -1216,6 +1297,9 @@ def synthesize_code_block(
typed_param_keys: dict[tuple[str, str, str, str], str] = {}
credential_param_keys: dict[str, str] = {}
used_download_vars: set[str] = set()
+ grounded_binding_count = sum(1 for interaction in trajectory if "submit_rung_binding" in interaction)
+ if grounded_binding_count > 1:
+ return None
compile_download_target = (
reached_download_target is not None
and not reached_download_target.already_registered
@@ -1233,6 +1317,8 @@ def synthesize_code_block(
anchor=reached_download_target.trajectory_anchor,
dropped_trailing_count=dropped_trailing,
)
+ if grounded_binding_count != sum(1 for interaction in trajectory if "submit_rung_binding" in interaction):
+ return None
diagnostics.retained_trajectory_indices = list(range(len(trajectory)))
input_templated_keys, input_templated_needs_month = _prescan_input_templating(trajectory)
@@ -1551,6 +1637,23 @@ def synthesize_code_block(
line_start = len(lines) + 1
if tool_name == "click":
+ captured_index = interaction.get("trajectory_index")
+ submit_trajectory_index = (
+ captured_index if isinstance(captured_index, int) and captured_index >= 0 else trajectory_index
+ )
+ if "submit_rung_binding" in interaction:
+ grounded_binding = _validated_submit_rung_binding(interaction, submit_trajectory_index)
+ if grounded_binding is None:
+ return None
+ binding_fingerprint, field_bindings = grounded_binding
+ for parameter_key, field_selector in field_bindings:
+ if parameter_key not in used_param_keys:
+ used_param_keys.add(parameter_key)
+ parameters.append({"key": parameter_key})
+ lines.append(
+ f"{action_indent}await page.locator({_py_str(field_selector)}).fill(str({parameter_key}))"
+ )
+ diagnostics.grounded_submit_binding_fingerprints.append(binding_fingerprint)
reclassify_terminal_required = (
trajectory_index == terminal_action_index
and _is_anonymous_structural_dismissal_click(interaction)
@@ -1764,6 +1867,8 @@ def synthesize_code_block(
if not lines:
return None
+ if len(diagnostics.grounded_submit_binding_fingerprints) != grounded_binding_count:
+ return None
emitted_code = "\n".join(lines)
for scout_var in _INTERNAL_SCOUT_VARS:
if not _code_uses_name(emitted_code, scout_var):
diff --git a/skyvern/forge/sdk/copilot/completion_criteria_store.py b/skyvern/forge/sdk/copilot/completion_criteria_store.py
index ad2f5556d..43f8d98e4 100644
--- a/skyvern/forge/sdk/copilot/completion_criteria_store.py
+++ b/skyvern/forge/sdk/copilot/completion_criteria_store.py
@@ -18,10 +18,12 @@ from skyvern.forge.sdk.copilot.completion_verification import (
run_plane_all_no_evidence,
)
from skyvern.forge.sdk.copilot.request_policy import (
+ REQUESTED_OUTPUT_PATH_MINT_SOURCES,
CompletionCriterion,
CriterionKind,
ExpectedOutputShape,
RequestedOutputEvidenceSource,
+ RequestedOutputPathMintSource,
TerminalActionFamily,
_canonical_bool_string,
_coerce_classification_output_key,
@@ -151,6 +153,8 @@ def criteria_to_json(criteria: tuple[CompletionCriterion, ...] | list[Completion
}
if criterion.requested_output_corroborator:
item["requested_output_corroborator"] = True
+ if criterion.requested_output_path_mint_source is not None:
+ item["requested_output_path_mint_source"] = criterion.requested_output_path_mint_source
if criterion.mint_degrade is not None:
item["mint_degrade"] = criterion.mint_degrade
if criterion.judgment_truth_condition is not None:
@@ -193,6 +197,11 @@ def criteria_from_json(raw: Any) -> tuple[CompletionCriterion, ...]:
terminal_action_family = (
family_raw if kind == "terminal_action" and family_raw in _TERMINAL_ACTION_FAMILIES else None
)
+ mint_source_raw = item.get("requested_output_path_mint_source")
+ requested_output_path_mint_source = cast(
+ RequestedOutputPathMintSource | None,
+ mint_source_raw if mint_source_raw in REQUESTED_OUTPUT_PATH_MINT_SOURCES else None,
+ )
stored_output_path = output_path.strip() if isinstance(output_path, str) and output_path.strip() else None
stored_expected_output_value = _coerce_expected_output_value(expected_output_value)
stored_expected_output_shape = cast(ExpectedOutputShape | None, expected_output_shape)
@@ -225,6 +234,7 @@ def criteria_from_json(raw: Any) -> tuple[CompletionCriterion, ...]:
expected_output_value=stored_expected_output_value,
expected_output_shape=stored_expected_output_shape,
requested_output_evidence_source=cast(RequestedOutputEvidenceSource, requested_output_evidence_source),
+ requested_output_path_mint_source=requested_output_path_mint_source,
kind=cast(CriterionKind, kind),
terminal_action_family=cast(TerminalActionFamily | None, terminal_action_family),
classification_output_key=classification_output_key,
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 0135fe753..a759dfbee 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -250,7 +250,9 @@ _SYNTHESIZED_BLOCK_PERSISTENCE_MUTATING_TOOLS = frozenset(
_SYNTHESIZED_BLOCK_REAUTHORING_TOOLS = frozenset({SYNTHESIZED_BLOCK_PERSISTENCE_TOOL, "update_workflow"})
_SYNTHESIZED_BLOCK_COMMIT_TOOLS = frozenset({"click", "press_key"})
# Evidence sources confirmable only after a run — excluded from the pre-run scout-coverage gate.
-_PRE_RUN_UNGATED_EVIDENCE_SOURCES = frozenset({"registered_output_parameter", "registered_artifact_content"})
+_PRE_RUN_UNGATED_EVIDENCE_SOURCES = frozenset(
+ {"independent_run_evidence", "registered_output_parameter", "registered_artifact_content"}
+)
# OpenAI detail=high cost per resized image. If we support other providers,
# pull from model config — this value will silently over/undercount otherwise.
# See screenshot_utils.resize_screenshot_b64 for the dimension contract this
@@ -2318,9 +2320,10 @@ def _active_completion_criteria(ctx: AgentContext) -> tuple[CompletionCriterion,
def _pre_run_gated_completion_criteria(ctx: AgentContext) -> tuple[CompletionCriterion, ...]:
"""Completion criteria whose requested output is observable before a run. A criterion whose
- evidence lives in a registered output parameter or artifact content is only confirmable
- post-run, so gating the scout window on it would demand an unsatisfiable pre-run observation.
- The persist scaffold still demands those paths at author time — that gate is SKY-11591's."""
+ evidence comes from an independent run, registered output parameter, or artifact content is
+ only confirmable post-run, so gating the scout window on it would demand an unsatisfiable
+ pre-run observation. The persist scaffold still demands those paths at author time — that gate
+ is SKY-11591's."""
return tuple(
criterion
for criterion in _active_completion_criteria(ctx)
@@ -2329,7 +2332,8 @@ def _pre_run_gated_completion_criteria(ctx: AgentContext) -> tuple[CompletionCri
def _requested_output_paths_for_ctx(ctx: AgentContext) -> set[str]:
- paths = set(requested_output_paths(_pre_run_gated_completion_criteria(ctx)))
+ pre_run_gated_paths = set(requested_output_paths(_pre_run_gated_completion_criteria(ctx)))
+ paths = set(pre_run_gated_paths)
repair_context = ctx.last_code_authoring_repair_context
if repair_context is not None:
paths.update(
@@ -2337,6 +2341,19 @@ def _requested_output_paths_for_ctx(ctx: AgentContext) -> set[str]:
for raw in repair_context.required_goal_value_paths
if isinstance(raw, str) and raw
)
+ active_criteria = _active_completion_criteria(ctx)
+ independent_run_evidence_paths = {
+ _canonical_output_path(criterion.output_path)
+ for criterion in active_criteria
+ if criterion.requested_output_evidence_source == "independent_run_evidence" and criterion.output_path
+ }
+ non_independent_evidence_paths = {
+ _canonical_output_path(criterion.output_path)
+ for criterion in active_criteria
+ if criterion.requested_output_evidence_source != "independent_run_evidence" and criterion.output_path
+ }
+ independent_only_paths = independent_run_evidence_paths - non_independent_evidence_paths
+ paths.difference_update(independent_only_paths)
return paths
@@ -2610,6 +2627,77 @@ def _request_expects_unreached_download(ctx: AgentContext) -> bool:
return any(criterion.deliverable_kind == "registered_download" for criterion in _active_completion_criteria(ctx))
+def _last_scout_credential_fill_index(trajectory: list[Any]) -> int | None:
+ # Boundary past the ENTIRE credential flow, including a runtime-only OTP/MFA fill. Keying only on
+ # username/password let an MFA step (fill totp -> verify-click) form a durable entry->commit past
+ # the boundary and falsely release the terminal-action gate on a login-only trajectory.
+ last_index: int | None = None
+ for index, item in enumerate(trajectory):
+ if isinstance(item, dict) and str(item.get("tool_name") or "").strip() == CREDENTIAL_FILL_TOOL_NAME:
+ last_index = index
+ return last_index
+
+
+def _trajectory_reaches_post_credential_commit(ctx: AgentContext) -> bool:
+ """Deterministic floor for the terminal-action release: the scout captured a durable entry followed by a
+ commit that both sit past the last live credential fill, so a bare login prefix (whose only commit is the
+ login submit) never satisfies it while a business spine continued past login does."""
+ trajectory = ctx.scout_trajectory
+ if not trajectory:
+ return False
+ credential_index = _last_scout_credential_fill_index(trajectory)
+ start = 0 if credential_index is None else credential_index + 1
+ last_entry_index: int | None = None
+ for index in range(start, len(trajectory)):
+ item = trajectory[index]
+ if isinstance(item, dict) and is_durable_fallback_entry_target(item):
+ last_entry_index = index
+ if last_entry_index is None:
+ return False
+ return any(
+ isinstance(item, dict)
+ and str(item.get("tool_name") or "") in _SYNTHESIZED_BLOCK_COMMIT_TOOLS
+ and not is_generic_entry_opener_click(item)
+ for item in trajectory[last_entry_index + 1 :]
+ )
+
+
+def reached_terminal_action_criterion_ids(ctx: AgentContext) -> set[str]:
+ """Active, non-method-mandated terminal_action criterion ids the scout has structurally reached: empty
+ until the trajectory shows a durable entry->commit past the credential flow. The method_mandated synthetic
+ durable-fill criterion is excluded so a login-only turn never self-releases through it."""
+ if not _trajectory_reaches_post_credential_commit(ctx):
+ return set()
+ return {
+ criterion.id
+ for criterion in _active_completion_criteria(ctx)
+ if criterion.kind == "terminal_action" and not criterion.method_mandated
+ }
+
+
+def record_reached_terminal_action_observation(ctx: AgentContext) -> None:
+ reached = reached_terminal_action_criterion_ids(ctx)
+ if not reached:
+ return
+ newly_observed = reached - ctx.scout_observed_terminal_criterion_ids
+ if not newly_observed:
+ return
+ ctx.scout_observed_terminal_criterion_ids.update(newly_observed)
+ LOG.info("copilot_reached_terminal_action_observed", criterion_ids=sorted(newly_observed))
+
+
+def _request_expects_unreached_terminal_action(ctx: AgentContext) -> bool:
+ # A terminal_action criterion is reached only once the scout observes its downstream page, which no
+ # pre-run page scalar evidences; a goal-reaching login prefix would otherwise read goal-complete before
+ # the scout crosses into the business spine and land the latch on a login-only trajectory.
+ for criterion in _active_completion_criteria(ctx):
+ if criterion.kind != "terminal_action" or criterion.method_mandated:
+ continue
+ if criterion.id not in ctx.scout_observed_terminal_criterion_ids:
+ return True
+ return False
+
+
def synthesized_trajectory_is_goal_complete(ctx: AgentContext) -> bool:
"""A goal-reaching trajectory with no requested-output path left uncovered; an empty requested-output set falls
through to the reach shape byte-identically, so an entry ``synthesize_code_block`` would drop never counts."""
@@ -2617,6 +2705,8 @@ def synthesized_trajectory_is_goal_complete(ctx: AgentContext) -> bool:
return False
if _request_expects_unreached_download(ctx):
return False
+ if _request_expects_unreached_terminal_action(ctx):
+ return False
scalar_paths = _requested_output_paths_for_ctx(ctx) - download_satisfied_requested_output_paths(ctx)
if scalar_paths:
plan = requested_scalar_output_extraction_plan(ctx)
diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.py
index 71fe9a4eb..37120c5dd 100644
--- a/skyvern/forge/sdk/copilot/mcp_adapter.py
+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py
@@ -84,6 +84,7 @@ _POST_HOOK_CONTEXT_ROLLBACK_FIELDS = (
"synthesized_block_offered_trajectory_len",
"synthesized_block_offered_goal_complete",
"scouted_output_covered_paths",
+ "scout_observed_terminal_criterion_ids",
"scout_observation_contract",
"requested_output_extraction_candidate",
"synthesized_block_reopened_for_output_coverage",
diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.py
index 9c3ecd9c6..6cd91ede3 100644
--- a/skyvern/forge/sdk/copilot/request_policy.py
+++ b/skyvern/forge/sdk/copilot/request_policy.py
@@ -68,6 +68,7 @@ REGISTERED_DOWNLOAD_REQUESTED_OUTPUT_PATHS = frozenset(
"output.downloaded_file_artifact_ids",
}
)
+_LONE_REGISTERED_DOWNLOAD_OUTPUT_PATH = "output.downloaded_files"
ClarificationReason = Literal[
"none",
"raw_secret",
@@ -215,6 +216,8 @@ _CRITERION_KINDS: frozenset[str] = frozenset({"outcome", "terminal_action", "val
_TERMINAL_ACTION_FAMILIES: frozenset[str] = frozenset({"request", "application", "form", "order"})
_EXPECTED_OUTPUT_SHAPES: frozenset[str] = frozenset(get_args(ExpectedOutputShape))
_REQUESTED_OUTPUT_EVIDENCE_SOURCES: frozenset[str] = frozenset(get_args(RequestedOutputEvidenceSource))
+RequestedOutputPathMintSource = Literal["classifier_default"]
+REQUESTED_OUTPUT_PATH_MINT_SOURCES: frozenset[str] = frozenset(get_args(RequestedOutputPathMintSource))
_OUTPUT_INTENT_RE = re.compile(
r"\b(?:read|capture|extract|output|return|returns|returned|include|includes|including|"
@@ -296,6 +299,7 @@ class CompletionCriterion:
expected_output_value: ExpectedOutputValue | None = None
expected_output_shape: ExpectedOutputShape | None = None
requested_output_evidence_source: RequestedOutputEvidenceSource = "runtime_output"
+ requested_output_path_mint_source: RequestedOutputPathMintSource | None = None
kind: CriterionKind = "outcome"
terminal_action_family: TerminalActionFamily | None = None
classification_output_key: str | None = None
@@ -851,6 +855,13 @@ def _parse_completion_criteria(raw: Any) -> list[CompletionCriterion]:
return []
criteria: list[CompletionCriterion] = []
seen: set[tuple[str, ...]] = set()
+ registered_download_item_count = sum(
+ 1
+ for candidate in raw
+ if isinstance(candidate, dict)
+ and _normalize_deliverable_kind(candidate.get("deliverable_kind")) == "registered_download"
+ and _coerce_criterion_kind(candidate.get("kind")) != "validation_classification"
+ )
for item in raw:
if not isinstance(item, dict):
continue
@@ -908,6 +919,22 @@ def _parse_completion_criteria(raw: Any) -> list[CompletionCriterion]:
requested_output_evidence_source = "runtime_output"
elif isinstance(expected_output_value, bool) or expected_output_shape == "goal_judgment_boolean":
requested_output_evidence_source = "independent_run_evidence"
+ requested_output_path_mint_source: RequestedOutputPathMintSource | None = None
+ if (
+ output_path is None
+ and expected_output_value is None
+ and deliverable_kind == "registered_download"
+ and kind != "validation_classification"
+ and registered_download_item_count == 1
+ ):
+ output_path = _LONE_REGISTERED_DOWNLOAD_OUTPUT_PATH
+ requested_output_path_mint_source = "classifier_default"
+ LOG.info(
+ "copilot_registered_download_requested_output_minted",
+ output_path=output_path,
+ requested_output_path_mint_source=requested_output_path_mint_source,
+ criterion_id=f"c{len(criteria)}",
+ )
key = (
contingent_on or "",
contingent_antecedent_output_path or "",
@@ -941,6 +968,7 @@ def _parse_completion_criteria(raw: Any) -> list[CompletionCriterion]:
expected_output_value=expected_output_value,
expected_output_shape=expected_output_shape,
requested_output_evidence_source=requested_output_evidence_source,
+ requested_output_path_mint_source=requested_output_path_mint_source,
kind=kind,
terminal_action_family=_coerce_terminal_action_family(item.get("terminal_action_family"), kind),
classification_output_key=classification_output_key,
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index d418d4f8a..b800b6ef4 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -185,6 +185,17 @@ class ScoutedInputCorrespondence(TypedDict):
position: int
+class ScoutedFieldParameterBinding(TypedDict):
+ parameter_key: str
+ field_selector: str
+
+
+class ScoutedSubmitRungBinding(TypedDict):
+ repeated_structural_key: str
+ fingerprint: str
+ field_bindings: list[ScoutedFieldParameterBinding]
+
+
class ScoutedInteraction(TypedDict):
tool_name: str
selector: NotRequired[str]
@@ -210,6 +221,9 @@ class ScoutedInteraction(TypedDict):
# Set when a live scout-time count()==1 probe found the captured selector matching >1 element on its
# source page; synthesis re-anchors or drops it rather than emitting a selector that strict-mode-fails.
ambiguous: NotRequired[bool]
+ # Value-free, current-page binding attached only to the exact captured submit rung on a derived trajectory.
+ # The source trajectory remains unchanged; synthesis consumes the fingerprint all-or-nothing.
+ submit_rung_binding: NotRequired[ScoutedSubmitRungBinding]
# Credential fills carry references and metadata only — never secret values.
credential_id: NotRequired[str]
credential_field: NotRequired[str]
@@ -463,6 +477,9 @@ class AgentContext:
synthesized_block_reopened_for_output_coverage: bool = False
synthesized_block_reopened_for_credential_scout: bool = False
scouted_output_covered_paths: set[str] = field(default_factory=set)
+ # Ids of active terminal_action completion criteria the scout has structurally reached past the
+ # login prefix; releases the is_goal_complete terminal-action gate mirroring reached_download_target.
+ scout_observed_terminal_criterion_ids: set[str] = field(default_factory=set)
scout_observation_contract: ScoutObservationContract | None = None
uncovered_output_rescout_context_key: str | None = None
uncovered_output_rescout_steer_key: str | None = None
diff --git a/skyvern/forge/sdk/copilot/secret_redaction.py b/skyvern/forge/sdk/copilot/secret_redaction.py
index 570d5bf82..6da4245c3 100644
--- a/skyvern/forge/sdk/copilot/secret_redaction.py
+++ b/skyvern/forge/sdk/copilot/secret_redaction.py
@@ -4,8 +4,17 @@ import re
from email_validator import EmailNotValidError, validate_email
+# The `token` keyword is guarded by negative lookbehinds so pagination cursors
+# (next_token, page_token, continuation_token, ...), which are not credentials,
+# aren't matched as secrets by either detection or redaction.
SECRET_KEYWORD_ASSIGNMENT_PATTERN = re.compile(
- r"\b(?:password|passcode|api[_ -]?key|secret|token|bearer|authorization)\s*[:=]\s*\S+", re.I
+ r"(?:^|(?<=[^A-Za-z0-9]))(?:[A-Za-z0-9]+_){0,8}"
+ r"(?:password|passcode|api[_ -]?key|secret|bearer|authorization"
+ r"|(?<!next_)(?<!prev_)(?<!previous_)(?<!page_)(?<!continuation_)(?<!cursor_)token)"
+ # Consume an optional auth scheme word so `Authorization: Bearer <token>`
+ # redacts the token, not just the scheme.
+ r"\s*[:=]\s*(?:(?:bearer|basic|token|digest)\s+)?\S+",
+ re.I,
)
RAW_SECRET_PATTERNS = (
SECRET_KEYWORD_ASSIGNMENT_PATTERN,
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index 00a2e32a7..676d22ff2 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -15,6 +15,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
from skyvern.forge.sdk.copilot.build_phase import (
advance_to_testing,
)
+from skyvern.forge.sdk.copilot.build_test_outcome import recorded_outcome_grounding_requires_current_page
from skyvern.forge.sdk.copilot.composition_evidence import (
composition_page_evidence_error as composition_page_evidence_error,
)
@@ -650,10 +651,16 @@ async def update_and_run_blocks_tool(
serialized_code_artifact_metadata = scaffolded_code_artifact_metadata
arguments["code_artifact_metadata"] = serialized_code_artifact_metadata
+ if recorded_outcome_grounding_requires_current_page(copilot_ctx):
+ loop_error = _tool_loop_error(copilot_ctx, "update_and_run_blocks", arguments)
+ if loop_error:
+ return _diagnosis_repair_tool_error(copilot_ctx, "update_and_run_blocks", loop_error)
+
metadata_contract_preflight_reject = _metadata_contract_run_preflight_reject(
copilot_ctx,
workflow_yaml,
serialized_code_artifact_metadata,
+ parameters or {},
)
if metadata_contract_preflight_reject is not None:
record_tool_step_result_for_ctx(
@@ -710,6 +717,7 @@ async def update_and_run_blocks_tool(
if scaffold_applied or envelope_imposed
else code_artifact_metadata,
"block_labels": block_labels,
+ "parameters": parameters or {},
},
copilot_ctx,
allow_missing_credentials=skip_run_after_update,
@@ -754,6 +762,29 @@ async def update_and_run_blocks_tool(
)
return json.dumps(skip_result)
+ exact_candidate_preflight_reject = _metadata_contract_run_preflight_reject(
+ copilot_ctx,
+ copilot_ctx.workflow_yaml or workflow_yaml,
+ copilot_ctx.code_artifact_metadata,
+ parameters or {},
+ enforce_untagged_declared_inputs=True,
+ )
+ if exact_candidate_preflight_reject is not None:
+ record_tool_step_result_for_ctx(
+ copilot_ctx,
+ "update_and_run_blocks",
+ arguments,
+ exact_candidate_preflight_reject,
+ )
+ _record_diagnosis_repair_contract(
+ copilot_ctx,
+ source_tool="update_and_run_blocks",
+ result=exact_candidate_preflight_reject,
+ workflow_updated=True,
+ )
+ sanitized = sanitize_tool_result_for_llm("update_and_run_blocks", exact_candidate_preflight_reject)
+ return json.dumps(sanitized)
+
# Step 2: Compute frontier and run the blocks.
new_definition = None
if copilot_ctx.last_workflow is not None:
diff --git a/skyvern/forge/sdk/copilot/tools/blockers.py b/skyvern/forge/sdk/copilot/tools/blockers.py
index 5e57355f0..dcd51ec23 100644
--- a/skyvern/forge/sdk/copilot/tools/blockers.py
+++ b/skyvern/forge/sdk/copilot/tools/blockers.py
@@ -1548,8 +1548,12 @@ def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Any
output_contract_owns_turn = (
tool_name in _OUTPUT_CONTRACT_LADDER_AUTHORING_TOOLS and output_contract_ladder_unresolved(ctx)
)
+ grounding_owns_mutation = (
+ tool_name in _RECORDED_OUTCOME_GROUNDING_MUTATION_TOOLS
+ and recorded_outcome_grounding_requires_current_page(ctx)
+ )
- if not output_contract_owns_turn:
+ if not output_contract_owns_turn and not grounding_owns_mutation:
detected = detect_failed_tool_step_loop_for_ctx(ctx, tool_name, arguments or {})
if detected is not None:
return _emit_tool_blocker_signal(
@@ -1567,6 +1571,7 @@ def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Any
isinstance(tracker, list)
and tool_name not in _CONSECUTIVE_LOOP_GUARD_EXEMPT_TOOLS
and not output_contract_owns_turn
+ and not grounding_owns_mutation
):
detected = detect_tool_loop(tracker, tool_name, arguments)
if detected is not None:
diff --git a/skyvern/forge/sdk/copilot/tools/completion.py b/skyvern/forge/sdk/copilot/tools/completion.py
index 08f834b97..1053bddd3 100644
--- a/skyvern/forge/sdk/copilot/tools/completion.py
+++ b/skyvern/forge/sdk/copilot/tools/completion.py
@@ -1,5 +1,6 @@
import time
from collections.abc import Mapping
+from dataclasses import replace
from typing import Any, Protocol
import structlog
@@ -57,7 +58,9 @@ from skyvern.forge.sdk.copilot.reached_download_target import (
derive_from_block_outputs,
)
from skyvern.forge.sdk.copilot.request_policy import (
+ REQUESTED_OUTPUT_PATH_MINT_SOURCES,
CompletionCriterion,
+ RequestedOutputPathMintSource,
_is_judgment_boolean_criterion,
is_fallback_floor_criterion,
)
@@ -94,6 +97,12 @@ _REGISTERED_ARTIFACT_OBSERVATION_LABEL = "registered_artifact_observation"
# and observation flag cannot be traversed as observed page content.
_POST_RUN_PAGE_EVIDENCE_STAMP_KEYS = frozenset({"workflow_run_id", "observed_after_workflow_run"})
_REGISTERED_DOWNLOAD_REQUESTED_OUTPUT_PATHS = frozenset(f"output.{key}" for key in REGISTERED_DOWNLOAD_OUTPUT_KEYS)
+_CLASSIFIER_DEFAULT_MINT_SOURCE: RequestedOutputPathMintSource = "classifier_default"
+if REQUESTED_OUTPUT_PATH_MINT_SOURCES != {_CLASSIFIER_DEFAULT_MINT_SOURCE}:
+ raise RuntimeError(
+ "RequestedOutputPathMintSource gained a member; the reconciled registered-download "
+ "requested-output identity carry must be revisited before this equality can stay strict."
+ )
_AUTHORED_OUTPUT_CONTRACT_CRITERION_ID_PREFIX = "__copilot_authored_output__"
_AUTHORED_OUTPUT_CONTRACT_MISSING_CRITERION_ID = "__copilot_authored_output_contract_missing"
_AUTHORED_OUTPUT_CONTRACT_MISSING_PATH = "output.__copilot_missing_authored_output_contract__"
@@ -169,6 +178,29 @@ def _registered_download_requested_output_criterion(criterion: CompletionCriteri
)
+def _is_minted_registered_download_requested_output(criterion: CompletionCriterion) -> bool:
+ return (
+ _registered_download_requested_output_criterion(criterion)
+ and criterion.requested_output_path_mint_source == _CLASSIFIER_DEFAULT_MINT_SOURCE
+ )
+
+
+def _registered_download_criterion_carrying_requested_output(*, carries_requested_output: bool) -> CompletionCriterion:
+ criterion = registered_download_completion_criterion()
+ if carries_requested_output:
+ return replace(criterion, requested_output_path_mint_source=_CLASSIFIER_DEFAULT_MINT_SOURCE)
+ return criterion
+
+
+def _minted_registered_download_requested_output_count(criteria: list[CompletionCriterion]) -> int:
+ return sum(
+ 1
+ for criterion in criteria
+ if is_registered_download_completion_criterion(criterion)
+ and criterion.requested_output_path_mint_source == _CLASSIFIER_DEFAULT_MINT_SOURCE
+ )
+
+
def _has_typed_download_signal(copilot_ctx: Any, result: dict[str, Any]) -> bool:
if _is_typed_download_target(_ctx_reached_download_target(copilot_ctx)):
return True
@@ -181,6 +213,9 @@ def _reconcile_download_completion_criterion(
copilot_ctx: Any, result: dict[str, Any], criteria: list[CompletionCriterion]
) -> list[CompletionCriterion]:
has_registered_download_evidence = _result_has_registered_download_block_output(result)
+ stripped_minted_requested_output = has_registered_download_evidence and any(
+ _is_minted_registered_download_requested_output(criterion) for criterion in criteria
+ )
reconciled = (
[criterion for criterion in criteria if not _registered_download_requested_output_criterion(criterion)]
if has_registered_download_evidence
@@ -190,7 +225,12 @@ def _reconcile_download_completion_criterion(
return reconciled
if not _has_typed_download_signal(copilot_ctx, result):
return reconciled
- return [*reconciled, registered_download_completion_criterion()]
+ return [
+ *reconciled,
+ _registered_download_criterion_carrying_requested_output(
+ carries_requested_output=stripped_minted_requested_output
+ ),
+ ]
def _completion_verification_criteria(copilot_ctx: Any) -> list[CompletionCriterion]:
@@ -1353,6 +1393,9 @@ async def _completion_verification_from_run_result(
snapshot = _build_run_evidence_snapshot(copilot_ctx, result)
run_structural_unfired_ids = structural_unfired_contingent_criterion_ids(run_criteria, snapshot)
requested_output_criteria, judgeable_run_criteria = split_requested_output_criteria(run_criteria)
+ requested_output_criteria_count = len(
+ requested_output_criteria
+ ) + _minted_registered_download_requested_output_count(run_criteria)
requested_output_verdicts = (
grade_requested_output_criteria(copilot_ctx, requested_output_criteria, snapshot)
if requested_output_criteria
@@ -1386,7 +1429,7 @@ async def _completion_verification_from_run_result(
contingent_criterion_ids=contingent_ids,
contingent_on_by_criterion_id=contingent_on_by_id,
contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
- requested_output_criteria_count=len(requested_output_criteria),
+ requested_output_criteria_count=requested_output_criteria_count,
)
if not definition_verdicts:
return None
@@ -1449,7 +1492,7 @@ async def _completion_verification_from_run_result(
contingent_criterion_ids=contingent_ids,
contingent_on_by_criterion_id=contingent_on_by_id,
contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
- requested_output_criteria_count=len(requested_output_criteria),
+ requested_output_criteria_count=requested_output_criteria_count,
)
return CompletionVerificationResult(
status="unavailable",
@@ -1480,7 +1523,7 @@ async def _completion_verification_from_run_result(
contingent_criterion_ids=contingent_ids,
contingent_on_by_criterion_id=contingent_on_by_id,
contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
- requested_output_criteria_count=len(requested_output_criteria),
+ requested_output_criteria_count=requested_output_criteria_count,
)
return CompletionVerificationResult(
status="unavailable",
@@ -1542,7 +1585,7 @@ async def _completion_verification_from_run_result(
contingent_criterion_ids=contingent_ids,
contingent_on_by_criterion_id=contingent_on_by_id,
contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
- requested_output_criteria_count=len(requested_output_criteria),
+ requested_output_criteria_count=requested_output_criteria_count,
)
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index a47fb18ec..6787cf94e 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -1063,10 +1063,22 @@ def _merge_registered_output_parameter_values_into_blocks(data: dict[str, Any])
block["extracted_data"] = {key: value}
+def _registered_output_identity_workflow(
+ *,
+ dispatch_to_worker: bool,
+ dispatch_workflow: Workflow | None,
+ runtime_workflow: Workflow,
+) -> Workflow | None:
+ if dispatch_to_worker:
+ return dispatch_workflow
+ return runtime_workflow
+
+
async def _attach_registered_output_parameter_values(
*,
workflow_run_id: str,
workflow: Workflow | None,
+ output_identity_workflow: Workflow | None = None,
data: dict[str, Any],
persisted_output_parameters: list[Any] | None = None,
) -> dict[str, Any]:
@@ -1086,7 +1098,8 @@ async def _attach_registered_output_parameter_values(
if not registered_rows:
return {}
- index_by_id, index_by_key = _workflow_output_parameter_indexes(workflow)
+ exact_output_identity = output_identity_workflow is not None
+ index_by_id, index_by_key = _workflow_output_parameter_indexes(output_identity_workflow or workflow)
persisted_key_by_id = {
output_parameter_id: key
for parameter in persisted_output_parameters or []
@@ -1100,8 +1113,15 @@ async def _attach_registered_output_parameter_values(
if not isinstance(output_parameter_id, str) or not output_parameter_id:
continue
block_info = dict(index_by_id.get(output_parameter_id, {}))
+ if exact_output_identity and not block_info:
+ LOG.info(
+ "Skipped registered output with no exact run-definition identity",
+ workflow_run_id=workflow_run_id,
+ output_parameter_id=output_parameter_id,
+ )
+ continue
output_parameter_key = block_info.get("output_parameter_key")
- if not isinstance(output_parameter_key, str) or not output_parameter_key:
+ if not exact_output_identity and (not isinstance(output_parameter_key, str) or not output_parameter_key):
output_parameter_key = persisted_key_by_id.get(output_parameter_id)
if isinstance(output_parameter_key, str):
block_info["output_parameter_key"] = output_parameter_key
@@ -2202,12 +2222,16 @@ async def _run_blocks_and_collect_debug(
if not run_ok and run and getattr(run, "failure_reason", None):
result_data["failure_reason"] = run.failure_reason
+ output_identity_workflow = _registered_output_identity_workflow(
+ dispatch_to_worker=dispatch_to_worker,
+ dispatch_workflow=dispatch_workflow,
+ runtime_workflow=runtime_workflow,
+ )
+
registered_outputs_by_label = await _attach_registered_output_parameter_values(
workflow_run_id=workflow_run.workflow_run_id,
- # Dispatched runs: the worker wrote outputs keyed by the persisted dispatch version's
- # regenerated output-parameter ids, so map against that version (not runtime_workflow,
- # which is intentionally left with the source ids). Inline runs map against runtime_workflow.
- workflow=dispatch_workflow if dispatch_workflow is not None else runtime_workflow,
+ workflow=runtime_workflow,
+ output_identity_workflow=output_identity_workflow,
data=result_data,
persisted_output_parameters=all_output_params,
)
diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.py
index 473c5c9d4..459a70ee4 100644
--- a/skyvern/forge/sdk/copilot/tools/scouting.py
+++ b/skyvern/forge/sdk/copilot/tools/scouting.py
@@ -38,6 +38,7 @@ from skyvern.forge.sdk.copilot.context import FillCarry
from skyvern.forge.sdk.copilot.enforcement import (
_RECENT_TOOL_OUTPUT_CHAR_CAP,
mint_scout_observation_contract_for_ctx,
+ record_reached_terminal_action_observation,
record_scouted_output_coverage,
register_no_progress_interaction_click,
reset_no_progress_interaction_count,
@@ -506,6 +507,7 @@ def _record_scouted_interaction(
total_scouted_interactions=len(ctx.scouted_interactions),
total_scout_trajectory=len(ctx.scout_trajectory),
)
+ record_reached_terminal_action_observation(ctx)
def _page_evidence_has_selector(value: Any, selector: str) -> bool:
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index e4400d300..9ed260568 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -9,7 +9,7 @@ import keyword
import re
import textwrap
import tokenize
-from collections.abc import Callable, Iterable, Iterator, Mapping
+from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from collections.abc import Set as AbstractSet
from dataclasses import dataclass
from dataclasses import field as dataclass_field
@@ -20,6 +20,7 @@ from urllib.parse import urlsplit
import structlog
import yaml
+from jinja2 import TemplateSyntaxError
from pydantic import AliasChoices, BaseModel, Field, ValidationError
from skyvern.forge import app
@@ -28,6 +29,7 @@ from skyvern.forge.sdk.copilot.attribution import resolve_copilot_created_by_sta
from skyvern.forge.sdk.copilot.blocker_signal import (
CREDENTIAL_SCOUT_VERIFY_REPLY,
CopilotToolBlockerSignal,
+ build_definition_contract_unsatisfied_blocker_signal,
build_output_source_unobservable_blocker_signal,
clear_terminal_evidence_on_workflow_edit,
stash_blocker_signal,
@@ -36,9 +38,11 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (
BuildTestOutcomeReasonCode,
RecordedBuildTestOutcome,
RecordedOutcomeBindingConstraint,
+ RecordedOutcomeGroundingRequirement,
_stable_hash,
authored_block_signatures_from_workflow,
authored_structure_signature_from_workflow,
+ latest_recorded_build_test_outcome_repeated,
record_build_test_outcome,
recorded_outcome_from_author_time_reject,
recorded_outcome_from_authoring_repair_context,
@@ -80,6 +84,8 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (
build_input_templated_locator,
credential_scout_gap,
freeze_requested_output_extraction_candidate,
+ grounded_parameter_key_is_safe,
+ grounded_submit_rung_binding_fingerprint,
input_correspondences_for_interaction,
locator_selector_literals,
missing_rung_text,
@@ -95,6 +101,7 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (
uncovered_required_emitted_interactions,
uncovered_rung_records,
)
+from skyvern.forge.sdk.copilot.completion_verification import grade_definition_criteria
from skyvern.forge.sdk.copilot.composition_evidence import (
SCOUT_INTERACTION_EVIDENCE_TOOL,
composition_page_evidence_error,
@@ -152,9 +159,11 @@ from skyvern.forge.sdk.copilot.reached_download_target import (
code_is_download_intent,
)
from skyvern.forge.sdk.copilot.request_policy import (
+ REQUESTED_OUTPUT_PATH_MINT_SOURCES,
CompletionCriterion,
JudgmentPredicate,
RequestedOutputEvidenceSource,
+ RequestedOutputPathMintSource,
_coerce_requested_output_evidence_source,
_is_judgment_boolean_criterion,
)
@@ -162,7 +171,9 @@ from skyvern.forge.sdk.copilot.result_evidence import loaded_result_source_produ
from skyvern.forge.sdk.copilot.runtime import (
AgentContext,
AuthorTimeGateAblationPayload,
+ ScoutedFieldParameterBinding,
ScoutedInteraction,
+ ScoutedSubmitRungBinding,
copilot_author_time_gate_log_only_enabled,
record_author_time_gate_ablation_event,
)
@@ -179,7 +190,12 @@ from skyvern.forge.sdk.copilot.turn_halt import (
stash_repair_ceiling_turn_halt,
stash_turn_halt_from_blocker_signal,
)
-from skyvern.forge.sdk.copilot.turn_ownership import TurnClaimant, claim_turn, current_turn_owner
+from skyvern.forge.sdk.copilot.turn_ownership import (
+ TurnClaimant,
+ claim_and_stash_blocker_signal,
+ claim_turn,
+ current_turn_owner,
+)
from skyvern.forge.sdk.copilot.workflow_credential_utils import (
credential_param_ids,
parse_workflow_yaml,
@@ -192,6 +208,7 @@ from skyvern.forge.sdk.workflow.models.parameter import RESERVED_PARAMETER_KEYS,
from skyvern.forge.sdk.workflow.models.workflow import Workflow
from skyvern.schemas.proxy_location import runtime_proxy_location
from skyvern.schemas.workflows import BlockType
+from skyvern.utils.templating import get_missing_variables
from ._shared import (
BLOCK_RUNNING_TOOLS,
@@ -230,6 +247,13 @@ from .guardrails import (
LOG = structlog.get_logger()
+_CLASSIFIER_DEFAULT_MINT_SOURCE: RequestedOutputPathMintSource = "classifier_default"
+if REQUESTED_OUTPUT_PATH_MINT_SOURCES != {_CLASSIFIER_DEFAULT_MINT_SOURCE}:
+ raise RuntimeError(
+ "RequestedOutputPathMintSource gained a member; the requested-output author-exclusion "
+ "must be revisited before this equality can stay strict."
+ )
+
class BlockObservationRef(BaseModel):
label: str
@@ -1659,6 +1683,8 @@ def _requested_output_child_paths(ctx: AgentContext) -> set[str]:
if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:
return set()
paths: set[str] = set()
+ # Criteria at this seam are polymorphic (typed CompletionCriterion plus lighter duck-typed
+ # shapes), so read fields via getattr — a non-model criterion must still contribute its path.
for criterion in _active_completion_criteria(ctx):
if isinstance(criterion, CompletionCriterion) and _is_judgment_boolean_criterion(criterion):
continue
@@ -1670,6 +1696,8 @@ def _requested_output_child_paths(ctx: AgentContext) -> set[str]:
continue
if getattr(criterion, "mint_degrade", None) is not None:
continue
+ if getattr(criterion, "requested_output_path_mint_source", None) == _CLASSIFIER_DEFAULT_MINT_SOURCE:
+ continue
path = _canonical_requested_output_path(getattr(criterion, "output_path", None))
if path and _output_path_has_child(path):
paths.add(path)
@@ -1702,6 +1730,601 @@ def _active_completion_criteria(ctx: AgentContext) -> list[CompletionCriterion]:
return request_policy.graded_completion_criteria()
+class _DefinitionPlaneReject(NamedTuple):
+ criterion_ids: tuple[str, ...]
+ reason_codes: tuple[str, ...]
+ unreferenced_parameter_keys: tuple[str, ...]
+
+
+def _expression_parameter_sources(expression: ast.AST, bindings: Mapping[str, set[str]]) -> set[str]:
+ if isinstance(expression, ast.Name) and isinstance(expression.ctx, ast.Load):
+ return set(bindings.get(expression.id, set()))
+ if isinstance(expression, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)):
+ local_bindings = {name: set(sources) for name, sources in bindings.items()}
+ comprehension_sources: set[str] = set()
+ for generator in expression.generators:
+ comprehension_sources.update(_expression_parameter_sources(generator.iter, local_bindings))
+ _bind_parameter_sources(generator.target, set(), local_bindings)
+ for condition in generator.ifs:
+ comprehension_sources.update(_expression_parameter_sources(condition, local_bindings))
+ if isinstance(expression, ast.DictComp):
+ comprehension_sources.update(_expression_parameter_sources(expression.key, local_bindings))
+ comprehension_sources.update(_expression_parameter_sources(expression.value, local_bindings))
+ else:
+ comprehension_sources.update(_expression_parameter_sources(expression.elt, local_bindings))
+ return comprehension_sources
+ if isinstance(expression, ast.Lambda):
+ local_bindings = {name: set(sources) for name, sources in bindings.items()}
+ for argument in (*expression.args.posonlyargs, *expression.args.args, *expression.args.kwonlyargs):
+ local_bindings[argument.arg] = set()
+ if expression.args.vararg is not None:
+ local_bindings[expression.args.vararg.arg] = set()
+ if expression.args.kwarg is not None:
+ local_bindings[expression.args.kwarg.arg] = set()
+ return _expression_parameter_sources(expression.body, local_bindings)
+ if isinstance(expression, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ return set()
+ sources: set[str] = set()
+ for child in ast.iter_child_nodes(expression):
+ sources.update(_expression_parameter_sources(child, bindings))
+ return sources
+
+
+def _awaited_parameter_sources(expression: ast.AST, bindings: Mapping[str, set[str]]) -> set[str]:
+ if isinstance(expression, ast.Await):
+ return _expression_parameter_sources(expression.value, bindings)
+ if isinstance(expression, (ast.Lambda, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ return set()
+ sources: set[str] = set()
+ for child in ast.iter_child_nodes(expression):
+ sources.update(_awaited_parameter_sources(child, bindings))
+ return sources
+
+
+def _bind_parameter_sources(target: ast.expr, sources: set[str], bindings: dict[str, set[str]]) -> None:
+ if isinstance(target, ast.Name):
+ bindings[target.id] = set(sources)
+ return
+ if isinstance(target, (ast.Tuple, ast.List)):
+ for element in target.elts:
+ _bind_parameter_sources(element, sources, bindings)
+
+
+def _merge_parameter_bindings(left: Mapping[str, set[str]], right: Mapping[str, set[str]]) -> dict[str, set[str]]:
+ return {name: set(left.get(name, set())) | set(right.get(name, set())) for name in set(left) | set(right)}
+
+
+def _loop_body_has_reachable_break(statements: Sequence[ast.stmt]) -> bool:
+ for statement in statements:
+ if isinstance(statement, ast.Break):
+ return True
+ if isinstance(
+ statement, (ast.For, ast.AsyncFor, ast.While, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
+ ):
+ if not _statements_can_fall_through([statement]):
+ return False
+ continue
+ if isinstance(statement, ast.If):
+ if isinstance(statement.test, ast.Constant):
+ selected_branch = statement.body if bool(statement.test.value) else statement.orelse
+ if _loop_body_has_reachable_break(selected_branch):
+ return True
+ elif _loop_body_has_reachable_break(statement.body) or _loop_body_has_reachable_break(statement.orelse):
+ return True
+ elif isinstance(statement, (ast.Try, ast.TryStar)):
+ if statement.finalbody:
+ if _loop_body_has_reachable_break(statement.finalbody):
+ return True
+ if not _statements_can_fall_through(statement.finalbody):
+ return False
+ branches = [statement.body, statement.orelse]
+ branches.extend(handler.body for handler in statement.handlers)
+ if any(_loop_body_has_reachable_break(branch) for branch in branches):
+ return True
+ elif isinstance(statement, (ast.With, ast.AsyncWith)) and _loop_body_has_reachable_break(statement.body):
+ return True
+ elif isinstance(statement, ast.Match) and any(
+ _loop_body_has_reachable_break(case.body) for case in statement.cases
+ ):
+ return True
+ if not _statements_can_fall_through([statement]):
+ return False
+ return False
+
+
+def _statements_can_fall_through(statements: Sequence[ast.stmt]) -> bool:
+ for statement in statements:
+ if isinstance(statement, (ast.Return, ast.Raise, ast.Break, ast.Continue)):
+ return False
+ if isinstance(statement, ast.If):
+ if isinstance(statement.test, ast.Constant):
+ selected_branch = statement.body if bool(statement.test.value) else statement.orelse
+ if not _statements_can_fall_through(selected_branch):
+ return False
+ continue
+ if statement.orelse:
+ if not _statements_can_fall_through(statement.body) and not _statements_can_fall_through(
+ statement.orelse
+ ):
+ return False
+ if (
+ isinstance(statement, ast.While)
+ and isinstance(statement.test, ast.Constant)
+ and bool(statement.test.value)
+ and not _loop_body_has_reachable_break(statement.body)
+ ):
+ return False
+ if isinstance(statement, (ast.Try, ast.TryStar)):
+ if statement.finalbody and not _statements_can_fall_through(statement.finalbody):
+ return False
+ normal_falls_through = _statements_can_fall_through(statement.body) and _statements_can_fall_through(
+ statement.orelse
+ )
+ handler_falls_through = any(_statements_can_fall_through(handler.body) for handler in statement.handlers)
+ if not normal_falls_through and not handler_falls_through:
+ return False
+ return True
+
+
+def _statement_parameter_dataflow(
+ statements: Sequence[ast.stmt], bindings: dict[str, set[str]]
+) -> tuple[set[str], dict[str, set[str]]]:
+ consumed: set[str] = set()
+ current = {name: set(sources) for name, sources in bindings.items()}
+ for statement in statements:
+ if isinstance(statement, ast.Assign):
+ consumed.update(_awaited_parameter_sources(statement.value, current))
+ sources = _expression_parameter_sources(statement.value, current)
+ for target in statement.targets:
+ _bind_parameter_sources(target, sources, current)
+ continue
+ if isinstance(statement, ast.AnnAssign):
+ value = statement.value
+ sources = _expression_parameter_sources(value, current) if value is not None else set()
+ if value is not None:
+ consumed.update(_awaited_parameter_sources(value, current))
+ _bind_parameter_sources(statement.target, sources, current)
+ continue
+ if isinstance(statement, ast.AugAssign):
+ sources = _expression_parameter_sources(statement.target, current)
+ sources.update(_expression_parameter_sources(statement.value, current))
+ consumed.update(_awaited_parameter_sources(statement.value, current))
+ _bind_parameter_sources(statement.target, sources, current)
+ continue
+ if isinstance(statement, ast.Expr):
+ consumed.update(_awaited_parameter_sources(statement.value, current))
+ continue
+ if isinstance(statement, ast.Return):
+ if statement.value is not None:
+ consumed.update(_expression_parameter_sources(statement.value, current))
+ break
+ if isinstance(statement, ast.Raise):
+ if statement.exc is not None:
+ consumed.update(_expression_parameter_sources(statement.exc, current))
+ break
+ if isinstance(statement, ast.If):
+ consumed.update(_expression_parameter_sources(statement.test, current))
+ if isinstance(statement.test, ast.Constant) and statement.test.value is False:
+ branch_consumed, branch_bindings = _statement_parameter_dataflow(statement.orelse, current)
+ consumed.update(branch_consumed)
+ current = branch_bindings
+ continue
+ if isinstance(statement.test, ast.Constant) and statement.test.value is True:
+ branch_consumed, branch_bindings = _statement_parameter_dataflow(statement.body, current)
+ consumed.update(branch_consumed)
+ current = branch_bindings
+ continue
+ body_consumed, body_bindings = _statement_parameter_dataflow(statement.body, current)
+ else_consumed, else_bindings = _statement_parameter_dataflow(statement.orelse, current)
+ consumed.update(body_consumed)
+ consumed.update(else_consumed)
+ body_falls_through = _statements_can_fall_through(statement.body)
+ else_falls_through = _statements_can_fall_through(statement.orelse)
+ if body_falls_through and else_falls_through:
+ current = _merge_parameter_bindings(body_bindings, else_bindings)
+ elif body_falls_through:
+ current = body_bindings
+ elif else_falls_through:
+ current = else_bindings
+ else:
+ break
+ continue
+ if isinstance(statement, (ast.For, ast.AsyncFor)):
+ consumed.update(_expression_parameter_sources(statement.iter, current))
+ loop_bindings = {name: set(sources) for name, sources in current.items()}
+ _bind_parameter_sources(statement.target, set(), loop_bindings)
+ body_consumed, body_bindings = _statement_parameter_dataflow(statement.body, loop_bindings)
+ else_consumed, else_bindings = _statement_parameter_dataflow(statement.orelse, current)
+ consumed.update(body_consumed)
+ consumed.update(else_consumed)
+ current = _merge_parameter_bindings(current, _merge_parameter_bindings(body_bindings, else_bindings))
+ continue
+ if isinstance(statement, ast.While):
+ consumed.update(_expression_parameter_sources(statement.test, current))
+ if isinstance(statement.test, ast.Constant) and statement.test.value is False:
+ else_consumed, current = _statement_parameter_dataflow(statement.orelse, current)
+ consumed.update(else_consumed)
+ continue
+ body_consumed, body_bindings = _statement_parameter_dataflow(statement.body, current)
+ else_consumed, else_bindings = _statement_parameter_dataflow(statement.orelse, current)
+ consumed.update(body_consumed)
+ consumed.update(else_consumed)
+ current = _merge_parameter_bindings(current, _merge_parameter_bindings(body_bindings, else_bindings))
+ continue
+ if isinstance(statement, (ast.Try, ast.TryStar)):
+ body_consumed, body_bindings = _statement_parameter_dataflow(statement.body, current)
+ consumed.update(body_consumed)
+ merged = body_bindings
+ for handler in statement.handlers:
+ handler_bindings = {name: set(sources) for name, sources in current.items()}
+ if handler.name:
+ handler_bindings[handler.name] = set()
+ handler_consumed, handler_bindings = _statement_parameter_dataflow(handler.body, handler_bindings)
+ consumed.update(handler_consumed)
+ merged = _merge_parameter_bindings(merged, handler_bindings)
+ else_consumed, else_bindings = _statement_parameter_dataflow(statement.orelse, body_bindings)
+ consumed.update(else_consumed)
+ merged = _merge_parameter_bindings(merged, else_bindings)
+ final_consumed, current = _statement_parameter_dataflow(statement.finalbody, merged)
+ consumed.update(final_consumed)
+ continue
+ if isinstance(statement, (ast.With, ast.AsyncWith)):
+ with_bindings = {name: set(sources) for name, sources in current.items()}
+ for item in statement.items:
+ consumed.update(_expression_parameter_sources(item.context_expr, current))
+ if item.optional_vars is not None:
+ _bind_parameter_sources(item.optional_vars, set(), with_bindings)
+ body_consumed, current = _statement_parameter_dataflow(statement.body, with_bindings)
+ consumed.update(body_consumed)
+ continue
+ if isinstance(statement, ast.Match):
+ consumed.update(_expression_parameter_sources(statement.subject, current))
+ merged = {name: set(sources) for name, sources in current.items()}
+ for case in statement.cases:
+ if case.guard is not None:
+ consumed.update(_expression_parameter_sources(case.guard, current))
+ case_consumed, case_bindings = _statement_parameter_dataflow(case.body, current)
+ consumed.update(case_consumed)
+ merged = _merge_parameter_bindings(merged, case_bindings)
+ current = merged
+ continue
+ if isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ function_bindings = {name: set(sources) for name, sources in current.items()}
+ for argument in (
+ *statement.args.posonlyargs,
+ *statement.args.args,
+ *statement.args.kwonlyargs,
+ ):
+ function_bindings[argument.arg] = set()
+ if statement.args.vararg is not None:
+ function_bindings[statement.args.vararg.arg] = set()
+ if statement.args.kwarg is not None:
+ function_bindings[statement.args.kwarg.arg] = set()
+ function_consumed, _ = _statement_parameter_dataflow(statement.body, function_bindings)
+ current[statement.name] = function_consumed
+ continue
+ if isinstance(statement, ast.ClassDef):
+ current[statement.name] = set()
+ continue
+ consumed.update(_expression_parameter_sources(statement, current))
+ return consumed, current
+
+
+def _code_runtime_parameter_sources(code: str, parameter_keys: set[str]) -> set[str] | None:
+ try:
+ tree = ast.parse(code)
+ except SyntaxError:
+ return None
+ initial_bindings = {key: {key} for key in parameter_keys}
+ consumed, _ = _statement_parameter_dataflow(tree.body, initial_bindings)
+ return consumed
+
+
+def _value_template_parameter_sources(value: Any, parameter_keys: set[str], depth: int = 0) -> set[str]:
+ if depth > 12:
+ return set()
+ if isinstance(value, str):
+ try:
+ return get_missing_variables(value, {}) & parameter_keys
+ except TemplateSyntaxError:
+ return set()
+ if isinstance(value, Mapping):
+ sources: set[str] = set()
+ raw_keys = value.get("parameter_keys")
+ if isinstance(raw_keys, list):
+ sources.update(key for key in raw_keys if key in parameter_keys)
+ for child in value.values():
+ sources.update(_value_template_parameter_sources(child, parameter_keys, depth + 1))
+ return sources
+ if isinstance(value, list):
+ list_sources: set[str] = set()
+ for child in value:
+ list_sources.update(_value_template_parameter_sources(child, parameter_keys, depth + 1))
+ return list_sources
+ return set()
+
+
+def _non_code_runtime_parameter_sources(parsed: Mapping[str, Any], parameter_keys: set[str]) -> set[str]:
+ definition = parsed.get("workflow_definition")
+ blocks = definition.get("blocks") if isinstance(definition, Mapping) else None
+ sources: set[str] = set()
+
+ def visit(value: Any) -> None:
+ if isinstance(value, list):
+ for child in value:
+ visit(child)
+ return
+ if not isinstance(value, Mapping):
+ return
+ is_block = "block_type" in value
+ if is_block and _enum_or_string_name(value.get("block_type")) != BlockType.CODE.value:
+ own_fields = {
+ key: child
+ for key, child in value.items()
+ if key not in {*_ORDERED_CHILD_BLOCK_LIST_KEYS, *_ORDERED_BRANCH_LIST_KEYS}
+ }
+ sources.update(_value_template_parameter_sources(own_fields, parameter_keys))
+ for key in (*_ORDERED_CHILD_BLOCK_LIST_KEYS, *_ORDERED_BRANCH_LIST_KEYS):
+ visit(value.get(key))
+
+ visit(blocks)
+ return sources
+
+
+def _workflow_runtime_parameter_sources(parsed: dict[str, Any]) -> set[str] | None:
+ parameter_keys = _declared_string_workflow_parameter_keys(parsed)
+ sources: set[str] = set()
+ for block in _workflow_code_blocks(parsed):
+ raw_parameter_keys = block.get("parameter_keys")
+ block_parameter_keys = (
+ {key for key in raw_parameter_keys if isinstance(key, str) and key}
+ if isinstance(raw_parameter_keys, list)
+ else set()
+ )
+ block_sources = _code_runtime_parameter_sources(str(block.get("code") or ""), block_parameter_keys)
+ if block_sources is None:
+ return None
+ sources.update(block_sources)
+ sources.update(_non_code_runtime_parameter_sources(parsed, parameter_keys))
+ return sources
+
+
+def _definition_plane_preflight_reject(
+ ctx: AgentContext,
+ workflow_yaml: str,
+ *,
+ enforce_untagged_declared_inputs: bool = False,
+) -> _DefinitionPlaneReject | None:
+ definition_criteria = [
+ criterion for criterion in _active_completion_criteria(ctx) if criterion.level == "definition"
+ ]
+ code_only_browser = _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ if not definition_criteria and not (code_only_browser and enforce_untagged_declared_inputs):
+ return None
+ unreferenced_parameter_keys: tuple[str, ...] = ()
+ runtime_sources: set[str] | None = None
+ if code_only_browser:
+ parsed = parse_workflow_yaml(workflow_yaml)
+ if isinstance(parsed, dict):
+ runtime_sources = _workflow_runtime_parameter_sources(parsed)
+ if runtime_sources is None:
+ return None
+ parameter_keys = _declared_string_workflow_parameter_keys(parsed)
+ unreferenced_parameter_keys = tuple(sorted(parameter_keys - runtime_sources))
+ unsatisfied = [
+ verdict
+ for verdict in grade_definition_criteria(definition_criteria, workflow_yaml)
+ if verdict.state == "unsatisfied"
+ ]
+ if runtime_sources is not None and not unreferenced_parameter_keys:
+ unsatisfied = [
+ verdict for verdict in unsatisfied if verdict.reason_code != "definition_parameters_unreferenced"
+ ]
+ if not unsatisfied and not unreferenced_parameter_keys:
+ return None
+ return _DefinitionPlaneReject(
+ criterion_ids=tuple(verdict.criterion_id for verdict in unsatisfied)
+ or tuple(criterion.id for criterion in definition_criteria),
+ reason_codes=tuple(verdict.reason_code for verdict in unsatisfied)
+ or (("definition_parameters_unreferenced",) if unreferenced_parameter_keys else ()),
+ unreferenced_parameter_keys=unreferenced_parameter_keys,
+ )
+
+
+def _definition_plane_reject_error(rejection: _DefinitionPlaneReject) -> str:
+ if rejection.unreferenced_parameter_keys:
+ keys = ", ".join(f"`{key}`" for key in rejection.unreferenced_parameter_keys)
+ return f"The submitted workflow declares reusable parameters that no block references: {keys}."
+ return "The submitted workflow does not satisfy its active definition-level requirements."
+
+
+def _record_definition_plane_reject(
+ ctx: AgentContext,
+ workflow_yaml: str,
+ rejection: _DefinitionPlaneReject,
+ *,
+ code_artifact_metadata: object = None,
+) -> None:
+ authored_signature = authored_structure_signature_from_workflow(workflow_yaml, code_artifact_metadata)
+ block_labels = sorted(_workflow_yaml_code_blocks_by_label(workflow_yaml))
+ _record_author_time_reject_outcome(
+ ctx,
+ reason_code="definition_contract_unsatisfied",
+ summary=_definition_plane_reject_error(rejection),
+ structural_payload={
+ "reason_code": "definition_contract_unsatisfied",
+ "criterion_ids": rejection.criterion_ids,
+ "definition_reason_codes": rejection.reason_codes,
+ "unreferenced_parameter_keys": rejection.unreferenced_parameter_keys,
+ "authored_structure_signature": authored_signature,
+ },
+ authored_structure_signature=authored_signature,
+ block_labels=block_labels,
+ )
+
+
+def _stash_unresolved_recorded_outcome_grounding_halt(
+ ctx: AgentContext,
+ unresolved_parameter_keys: Iterable[str],
+) -> bool:
+ requirement = ctx.recorded_outcome_grounding_requirement
+ constraint = ctx.recorded_outcome_binding_constraint
+ latest = ctx.latest_recorded_build_test_outcome
+ if (
+ not isinstance(requirement, RecordedOutcomeGroundingRequirement)
+ or requirement.phase != "author_time_reject"
+ or not requirement.satisfied
+ or not isinstance(constraint, RecordedOutcomeBindingConstraint)
+ or constraint.repeated_structural_key != requirement.structural_key
+ or not isinstance(latest, RecordedBuildTestOutcome)
+ or latest.structural_key != requirement.structural_key
+ or latest_recorded_build_test_outcome_repeated(ctx) is not True
+ ):
+ return False
+ keys = sorted(set(unresolved_parameter_keys))
+ if not keys:
+ return False
+ signal = build_definition_contract_unsatisfied_blocker_signal(
+ unresolved_parameter_keys=keys,
+ grounding_unresolved=True,
+ )
+ claim_and_stash_blocker_signal(ctx, TurnClaimant.GENUINELY_TERMINAL, signal, force_stash=True)
+ stash_turn_halt_from_blocker_signal(ctx, signal, source="recorded_outcome_regrounding")
+ LOG.info(
+ "copilot recorded outcome regrounding halted before reauthor",
+ structural_key=requirement.structural_key,
+ unresolved_parameter_keys=keys,
+ )
+ return True
+
+
+def _trajectory_with_grounded_submit_rung_binding(
+ ctx: AgentContext,
+ parsed: Mapping[str, Any],
+ runtime_parameters: Mapping[str, Any] | None,
+) -> tuple[ScoutedInteraction, ...] | None:
+ requirement = ctx.recorded_outcome_grounding_requirement
+ constraint = ctx.recorded_outcome_binding_constraint
+ if (
+ not isinstance(requirement, RecordedOutcomeGroundingRequirement)
+ or not requirement.satisfied
+ or requirement.payload is None
+ or requirement.payload.source_tool != "inspect_page_for_composition"
+ or requirement.payload.target_url != "current_page"
+ or not isinstance(constraint, RecordedOutcomeBindingConstraint)
+ or constraint.repeated_structural_key != requirement.structural_key
+ ):
+ return None
+ declared_keys = _declared_string_workflow_parameter_keys(parsed)
+ if not declared_keys or any(not grounded_parameter_key_is_safe(key) for key in declared_keys):
+ return None
+ supplied = runtime_parameters if isinstance(runtime_parameters, Mapping) else {}
+ definition = parsed.get("workflow_definition")
+ rows = definition.get("parameters") if isinstance(definition, Mapping) else None
+ defaults = (
+ {str(row.get("key") or "").strip(): row.get("default_value") for row in rows if isinstance(row, Mapping)}
+ if isinstance(rows, list)
+ else {}
+ )
+ values: dict[str, str] = {}
+ for key in sorted(declared_keys):
+ value = supplied.get(key, defaults.get(key))
+ if not isinstance(value, str) or not value:
+ return None
+ values[key] = value
+
+ evidence = ctx.composition_page_evidence
+ forms = evidence.get("forms") if isinstance(evidence, Mapping) else None
+ current_url = str(evidence.get("current_url") or "").strip() if isinstance(evidence, Mapping) else ""
+ if not isinstance(forms, list) or not current_url or requirement.payload.source_url != current_url:
+ return None
+ captured_clicks: list[tuple[int, int, str, str]] = []
+ for fallback_index, interaction in enumerate(ctx.scout_trajectory):
+ if not isinstance(interaction, Mapping) or interaction.get("tool_name") != "click":
+ continue
+ raw_index = interaction.get("trajectory_index")
+ trajectory_index = raw_index if isinstance(raw_index, int) and raw_index >= 0 else fallback_index
+ captured_clicks.append(
+ (
+ fallback_index,
+ trajectory_index,
+ str(interaction.get("selector") or "").strip(),
+ str(interaction.get("source_url") or "").strip(),
+ )
+ )
+
+ candidates: list[tuple[int, int, ScoutedSubmitRungBinding]] = []
+ for form in forms:
+ if not isinstance(form, Mapping):
+ continue
+ fields = [field for field in form.get("fields") or [] if isinstance(field, Mapping)]
+ controls = [control for control in form.get("submit_controls") or [] if isinstance(control, Mapping)]
+ submit_matches: set[tuple[int, int, str]] = set()
+ for control in controls:
+ submit_selector = str(control.get("selector") or "").strip()
+ if control.get("disabled") is True or not submit_selector:
+ continue
+ matching_clicks = [
+ click for click in captured_clicks if click[2] == submit_selector and click[3] == current_url
+ ]
+ if len(matching_clicks) == 1:
+ submit_matches.add((matching_clicks[0][0], matching_clicks[0][1], submit_selector))
+ if len(submit_matches) != 1:
+ continue
+ submit_position, submit_trajectory_index, submit_selector = next(iter(submit_matches))
+ bindings: list[ScoutedFieldParameterBinding] = []
+ used_selectors: set[str] = set()
+ for key, value in values.items():
+ matching_fields = [
+ field
+ for field in fields
+ if field.get("disabled") is not True
+ and str(field.get("selector") or "").strip()
+ and field.get("value") == value
+ ]
+ if len(matching_fields) != 1:
+ bindings = []
+ break
+ selector = str(matching_fields[0].get("selector") or "").strip()
+ if selector in used_selectors:
+ bindings = []
+ break
+ used_selectors.add(selector)
+ bindings.append({"parameter_key": key, "field_selector": selector})
+ if len(bindings) == len(values):
+ fingerprint = grounded_submit_rung_binding_fingerprint(
+ repeated_structural_key=constraint.repeated_structural_key,
+ source_url=current_url,
+ submit_selector=submit_selector,
+ submit_trajectory_index=submit_trajectory_index,
+ field_bindings=bindings,
+ )
+ candidates.append(
+ (
+ submit_position,
+ submit_trajectory_index,
+ {
+ "repeated_structural_key": constraint.repeated_structural_key,
+ "fingerprint": fingerprint,
+ "field_bindings": bindings,
+ },
+ )
+ )
+ if len(candidates) != 1:
+ return None
+ submit_position, submit_trajectory_index, submit_rung_binding = candidates[0]
+ derived = [cast(ScoutedInteraction, dict(interaction)) for interaction in ctx.scout_trajectory]
+ derived[submit_position]["submit_rung_binding"] = submit_rung_binding
+ LOG.info(
+ "copilot recorded outcome submit rung bound",
+ binding_fingerprint=submit_rung_binding["fingerprint"],
+ parameter_keys=[binding["parameter_key"] for binding in submit_rung_binding["field_bindings"]],
+ binding_count=len(submit_rung_binding["field_bindings"]),
+ submit_trajectory_index=submit_trajectory_index,
+ )
+ return tuple(derived)
+
+
def _judgment_output_paths(ctx: AgentContext) -> set[str]:
# Judgment-boolean paths are dropped from the producer's static-bind set, not moved to the
# declaration lane; declaring one would fabricate a None where the run's own judgment belongs. The
@@ -3033,6 +3656,54 @@ def _apply_metadata_contract_scaffold(
return items
+def _scaffold_metadata_from_owned_carrier_produced_output(
+ ctx: AgentContext,
+ workflow_yaml: str,
+ raw_code_artifact_metadata: object,
+) -> tuple[object, bool]:
+ if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:
+ return raw_code_artifact_metadata, False
+ if not ctx.spine_imposition_owned_attempt:
+ return raw_code_artifact_metadata, False
+ carrier_label = str(ctx.spine_imposition_carrier_label or "").strip()
+ if not carrier_label:
+ return raw_code_artifact_metadata, False
+ if carrier_label not in _missing_code_artifact_metadata_labels(workflow_yaml, ctx, raw_code_artifact_metadata):
+ return raw_code_artifact_metadata, False
+ carrier_block = _workflow_yaml_code_blocks_by_label(workflow_yaml).get(carrier_label)
+ if carrier_block is None:
+ return raw_code_artifact_metadata, False
+ produced_paths = {
+ path
+ for path in _code_block_produced_output_paths(str(carrier_block.get("code") or ""))
+ if _output_path_has_child(path)
+ } - _judgment_output_paths(ctx)
+ if not produced_paths:
+ return raw_code_artifact_metadata, False
+ schema_text = _schema_template_text_for_required_paths(produced_paths)
+ items = [
+ copy.deepcopy(item)
+ for item in _code_artifact_metadata_items(raw_code_artifact_metadata)
+ if _raw_metadata_item_mapping(item) is not None
+ ]
+ target_index: int | None = None
+ for index, raw_item in enumerate(items):
+ item = _raw_metadata_item_mapping(raw_item)
+ if item is not None and str(item.get("block_label") or "").strip() == carrier_label:
+ target_index = index
+ break
+ if target_index is None:
+ target: dict[str, Any] = {"block_label": carrier_label}
+ items.append(target)
+ else:
+ target = dict(items[target_index])
+ items[target_index] = target
+ target["block_label"] = carrier_label
+ target["artifact_id"] = _artifact_id_for_block_label(carrier_label)
+ _ensure_metadata_contract_rows(target, goal_value_paths=produced_paths, schema_text=schema_text)
+ return items, True
+
+
def _scaffold_metadata_contract_for_update(
ctx: AgentContext,
workflow_yaml: str,
@@ -3040,7 +3711,7 @@ def _scaffold_metadata_contract_for_update(
) -> tuple[object, bool]:
contract = _output_contract_required_paths_source(ctx)
if not contract.union:
- return raw_code_artifact_metadata, False
+ return _scaffold_metadata_from_owned_carrier_produced_output(ctx, workflow_yaml, raw_code_artifact_metadata)
signature = _output_contract_signature(
ctx=ctx,
workflow_yaml=workflow_yaml,
@@ -4307,13 +4978,54 @@ def _metadata_contract_run_preflight_reject(
ctx: AgentContext,
workflow_yaml: str,
raw_code_artifact_metadata: object,
+ runtime_parameters: Mapping[str, Any] | None = None,
+ *,
+ enforce_untagged_declared_inputs: bool = False,
) -> dict[str, Any] | None:
+ definition_reject = (
+ _definition_plane_preflight_reject(
+ ctx,
+ workflow_yaml,
+ enforce_untagged_declared_inputs=enforce_untagged_declared_inputs,
+ )
+ if isinstance(ctx, AgentContext)
+ else None
+ )
+ parsed = parse_workflow_yaml(workflow_yaml)
+ grounded_binding_available = (
+ isinstance(ctx, AgentContext)
+ and isinstance(parsed, Mapping)
+ and _trajectory_with_grounded_submit_rung_binding(ctx, parsed, runtime_parameters) is not None
+ )
+ if definition_reject is not None and (enforce_untagged_declared_inputs or not grounded_binding_available):
+ halted = _stash_unresolved_recorded_outcome_grounding_halt(
+ ctx,
+ definition_reject.unreferenced_parameter_keys,
+ )
+ if not halted:
+ _record_definition_plane_reject(
+ ctx,
+ workflow_yaml,
+ definition_reject,
+ code_artifact_metadata=raw_code_artifact_metadata,
+ )
+ return {
+ "ok": False,
+ "error": _definition_plane_reject_error(definition_reject),
+ "user_facing_summary": _compiled_authoring_user_summary(),
+ "data": {
+ "reason_code": "definition_contract_unsatisfied",
+ "definition_criterion_ids": list(definition_reject.criterion_ids),
+ "definition_reason_codes": list(definition_reject.reason_codes),
+ "unreferenced_parameter_keys": list(definition_reject.unreferenced_parameter_keys),
+ },
+ }
convergence_reject = _recorded_outcome_convergence_reject(
ctx,
workflow_yaml=workflow_yaml,
code_artifact_metadata=raw_code_artifact_metadata,
)
- if convergence_reject is not None:
+ if convergence_reject is not None and not grounded_binding_available:
block_labels = sorted(_workflow_yaml_code_blocks_by_label(workflow_yaml))
_record_author_time_reject_outcome(
ctx,
@@ -5452,6 +6164,7 @@ class _SynthesizedCodeImpositionResult:
scrubbed_selected_metadata_label: str | None = None
selected_extraction_metadata_disposition: SelectedExtractionMetadataDisposition = "none"
minted_parameter_keys: list[str] = dataclass_field(default_factory=list)
+ metadata_repair_contract: dict[str, object] | None = None
_SUBMITTED_LITERAL_METHODS = frozenset({"fill", "type"})
@@ -7666,7 +8379,8 @@ def _stub_with_raw_prompt_violation(ctx: AgentContext, parsed: Mapping[str, Any]
def _code_references_parameter(code: str, key: str) -> bool:
- return re.search(rf"\b{re.escape(key)}\b", code) is not None
+ sources = _code_runtime_parameter_sources(code, {key})
+ return sources is not None and key in sources
def _orphan_minted_parameter_violation(parsed: Mapping[str, Any], minted_keys: list[str]) -> str | None:
@@ -8181,13 +8895,6 @@ def _reconcile_synthesized_parameters(
parameters.append(_string_parameter_row(synthesized_default, key))
continue
- if len(non_credential_synthesized) != 1:
- add_binding_violation(
- key,
- f"Unable to bind synthesized parameter `{key}`: missing submitted workflow parameter and literal binding is ambiguous.",
- )
- continue
-
typed_length = typed_length or scout_typed_length or (typed_lengths[0] if len(typed_lengths) == 1 else None)
direct_fill_usage = _submitted_direct_fill_type_usage(submitted_code, key)
if direct_fill_usage.matched and direct_fill_usage.mismatched:
@@ -8198,6 +8905,17 @@ def _reconcile_synthesized_parameters(
"fill in the code block, or declare explicit workflow parameters/defaults for the other filled values.",
)
continue
+
+ if len(non_credential_synthesized) != 1:
+ if matched_scout is not None or direct_fill_usage.matched:
+ parameters.append(_required_string_parameter_row(key))
+ continue
+ add_binding_violation(
+ key,
+ f"Unable to bind synthesized parameter `{key}`: missing submitted workflow parameter and literal binding is ambiguous.",
+ )
+ continue
+
if direct_fill_usage.matched:
parameters.append(_required_string_parameter_row(key))
continue
@@ -8316,7 +9034,30 @@ def _split_selected_output_owner_into_browser_stages(
return []
-def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext) -> _SynthesizedCodeImpositionResult:
+def _co_computed_metadata_repair_contract(
+ ctx: AgentContext,
+ workflow_yaml: str,
+ raw_metadata: object,
+) -> dict[str, object] | None:
+ # Derive the missing-metadata block labels the same way the save-path reject does, so the repair
+ # hint names the actually-uncovered block(s) rather than the imposed carrier in a multi-block workflow.
+ missing_labels = _missing_code_artifact_metadata_labels(workflow_yaml, ctx, raw_metadata)
+ if not missing_labels:
+ return None
+ required_paths, source, reason_code = _required_child_output_paths_for_authoring(ctx)
+ return _metadata_repair_contract(
+ block_labels=missing_labels,
+ required_paths=required_paths,
+ source=source,
+ reason_code=reason_code,
+ )
+
+
+def _maybe_impose_synthesized_code_block(
+ workflow_yaml: str,
+ ctx: AgentContext,
+ runtime_parameters: Mapping[str, Any] | None = None,
+) -> _SynthesizedCodeImpositionResult:
ctx.pending_goal_complete_landing = False
ctx.pending_requested_output_extraction_candidate = None
ctx.spine_imposition_owned_attempt = False
@@ -8345,6 +9086,24 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)
parsed = parse_workflow_yaml(workflow_yaml)
if not isinstance(parsed, dict):
return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)
+ grounded_trajectory = _trajectory_with_grounded_submit_rung_binding(ctx, parsed, runtime_parameters)
+ requirement = ctx.recorded_outcome_grounding_requirement
+ constraint = ctx.recorded_outcome_binding_constraint
+ declared_keys = _declared_string_workflow_parameter_keys(parsed)
+ if (
+ grounded_trajectory is None
+ and declared_keys
+ and isinstance(requirement, RecordedOutcomeGroundingRequirement)
+ and requirement.satisfied
+ and isinstance(constraint, RecordedOutcomeBindingConstraint)
+ and constraint.repeated_structural_key == requirement.structural_key
+ and _stash_unresolved_recorded_outcome_grounding_halt(ctx, declared_keys)
+ ):
+ return _SynthesizedCodeImpositionResult(
+ workflow_yaml=workflow_yaml,
+ violations=["Unable to impose synthesized code block: current-page parameter binding is unresolved."],
+ )
+ synthesis_trajectory: Sequence[Mapping[str, Any]] = grounded_trajectory or scout_trajectory
code_blocks = _workflow_code_blocks(parsed)
prior_source, prior_yaml = _prior_yaml_source(ctx)
code_block = _select_synthesized_imposition_code_block(
@@ -8380,14 +9139,14 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)
) or requested_output_extraction_plan_changed(ctx, extraction_plan)
synthesized = (
synthesize_code_block_with_extraction(
- scout_trajectory,
+ synthesis_trajectory,
extraction_plan,
strict_selectors=True,
reached_download_target=ctx.reached_download_target,
)
if extraction_plan is not None
else synthesize_code_block(
- scout_trajectory,
+ synthesis_trajectory,
strict_selectors=True,
reached_download_target=ctx.reached_download_target,
)
@@ -8397,6 +9156,14 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)
workflow_yaml=workflow_yaml,
violations=["Unable to impose synthesized code block: scout trajectory produced no runnable code."],
)
+ if synthesized.diagnostics.grounded_submit_binding_fingerprints:
+ LOG.info(
+ "copilot recorded outcome binding consumed by synthesizer",
+ structural_key=requirement.structural_key
+ if isinstance(requirement, RecordedOutcomeGroundingRequirement)
+ else None,
+ binding_fingerprints=synthesized.diagnostics.grounded_submit_binding_fingerprints,
+ )
imposed_candidate: FrozenRequestedOutputExtractionCandidate | None = None
if extraction_plan is not None:
candidate = freeze_requested_output_extraction_candidate(synthesized, extraction_plan, source="generated")
@@ -8569,6 +9336,7 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)
violations.extend(parameter_reconciliation.violations)
if repair_context is None:
repair_context = parameter_reconciliation.repair_context
+ raw_metadata = getattr(ctx, "raw_code_artifact_metadata", None)
if violations:
persisted_calls = ctx.persisted_draft_browser_calls
if ambiguous_reject_present and ctx.update_workflow_called and persisted_calls is not None:
@@ -8580,9 +9348,9 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)
workflow_yaml=workflow_yaml,
violations=violations,
repair_context=repair_context,
+ metadata_repair_contract=_co_computed_metadata_repair_contract(ctx, workflow_yaml, raw_metadata),
)
- raw_metadata = getattr(ctx, "raw_code_artifact_metadata", None)
metadata_declares_goal_values = bool(raw_metadata) and _raw_metadata_declares_goal_values_for_block(
raw_metadata, str(code_block.get("label") or "")
)
@@ -9885,7 +10653,12 @@ async def _update_workflow(
ctx.raw_code_artifact_metadata = params.get("raw_code_artifact_metadata", params.get("code_artifact_metadata"))
# Imposition reconciles synthesized aliases/parameters before the persisted YAML contract is checked.
_enrich_scout_trajectory_input_correspondences(workflow_yaml, ctx)
- imposition = _maybe_impose_synthesized_code_block(workflow_yaml, ctx)
+ runtime_parameters = params.get("parameters")
+ imposition = _maybe_impose_synthesized_code_block(
+ workflow_yaml,
+ ctx,
+ runtime_parameters if isinstance(runtime_parameters, Mapping) else None,
+ )
# Consume the one-shot credential-scout reopen before the gate below so a fresh reject can re-arm it.
ctx.synthesized_block_reopened_for_credential_scout = False
if imposition.violations:
@@ -9915,7 +10688,10 @@ async def _update_workflow(
return reject(
error="\n".join(imposition.violations),
user_facing_summary=_compiled_authoring_user_summary(),
- data=_code_repair_progress_data(imposition.repair_context),
+ data=_code_repair_progress_data(
+ imposition.repair_context,
+ metadata_repair_contract=imposition.metadata_repair_contract,
+ ),
repair_context=imposition.repair_context,
)
workflow_yaml = imposition.workflow_yaml
@@ -9970,6 +10746,29 @@ async def _update_workflow(
user_facing_summary=_compiled_authoring_user_summary(),
data=_code_repair_progress_data(),
)
+ definition_reject = _definition_plane_preflight_reject(ctx, workflow_yaml)
+ if definition_reject is not None:
+ halted = _stash_unresolved_recorded_outcome_grounding_halt(
+ ctx,
+ definition_reject.unreferenced_parameter_keys,
+ )
+ if not halted:
+ _record_definition_plane_reject(
+ ctx,
+ workflow_yaml,
+ definition_reject,
+ code_artifact_metadata=ctx.raw_code_artifact_metadata,
+ )
+ return reject(
+ error=_definition_plane_reject_error(definition_reject),
+ user_facing_summary=_compiled_authoring_user_summary(),
+ data={
+ "reason_code": "definition_contract_unsatisfied",
+ "definition_criterion_ids": list(definition_reject.criterion_ids),
+ "definition_reason_codes": list(definition_reject.reason_codes),
+ "unreferenced_parameter_keys": list(definition_reject.unreferenced_parameter_keys),
+ },
+ )
params["workflow_yaml"] = workflow_yaml
metadata_scrubbed_by_imposition = False
if (
diff --git a/skyvern/forge/sdk/copilot/turn_halt.py b/skyvern/forge/sdk/copilot/turn_halt.py
index 3076247dd..a60372046 100644
--- a/skyvern/forge/sdk/copilot/turn_halt.py
+++ b/skyvern/forge/sdk/copilot/turn_halt.py
@@ -8,6 +8,9 @@ from typing import TYPE_CHECKING, Any
import structlog
+from skyvern.forge.sdk.copilot.blocker_signal import (
+ DEFINITION_CONTRACT_UNSATISFIED_REASON_CODE,
+)
from skyvern.forge.sdk.copilot.blocker_signal import (
GENUINELY_TERMINAL_BLOCKER_REASON_CODES as GENUINELY_TERMINAL_BLOCKER_REASON_CODES,
)
@@ -57,6 +60,7 @@ class TurnHaltKind(StrEnum):
SCHEMA_INCOMPATIBILITY = "schema_incompatibility"
OUTPUT_SOURCE_UNOBSERVABLE = "output_source_unobservable"
DELIVERED_UNVERIFIED = "delivered_unverified"
+ DEFINITION_CONTRACT_UNSATISFIED = "definition_contract_unsatisfied"
class TurnHaltVerdict(StrEnum):
@@ -94,6 +98,7 @@ _OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODES = frozenset(
ADVISORY_DISPATCH_STALLED_REASON_CODE,
}
)
+_DEFINITION_CONTRACT_UNSATISFIED_REASON_CODES = frozenset({DEFINITION_CONTRACT_UNSATISFIED_REASON_CODE})
# Halts the agent did not choose: a verified outcome may suppress these.
# ACTIVE_TERMINAL_CHALLENGE is voluntary and is deliberately excluded so a
@@ -105,6 +110,7 @@ _INVOLUNTARY_TURN_HALT_KINDS = frozenset(
TurnHaltKind.REPAIR_CEILING_REACHED,
TurnHaltKind.SCHEMA_INCOMPATIBILITY,
TurnHaltKind.OUTPUT_SOURCE_UNOBSERVABLE,
+ TurnHaltKind.DEFINITION_CONTRACT_UNSATISFIED,
}
)
_INVOLUNTARY_BLOCKER_REASON_CODES = (
@@ -112,6 +118,7 @@ _INVOLUNTARY_BLOCKER_REASON_CODES = (
| _PROBABLE_SITE_BLOCK_REASON_CODES
| _SCHEMA_INCOMPATIBILITY_REASON_CODES
| _OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODES
+ | _DEFINITION_CONTRACT_UNSATISFIED_REASON_CODES
| frozenset({REPAIR_CEILING_REASON_CODE})
)
_VERIFIED_SUPPRESSIBLE_ACTIVE_TERMINAL_REASON_CODES = frozenset({ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE})
@@ -146,6 +153,8 @@ def _kind_for_blocker_signal(signal: CopilotToolBlockerSignal) -> TurnHaltKind |
return TurnHaltKind.SCHEMA_INCOMPATIBILITY
if reason in _OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODES:
return TurnHaltKind.OUTPUT_SOURCE_UNOBSERVABLE
+ if reason in _DEFINITION_CONTRACT_UNSATISFIED_REASON_CODES:
+ return TurnHaltKind.DEFINITION_CONTRACT_UNSATISFIED
return None
diff --git a/skyvern/forge/sdk/routes/streaming/channels/exfiltration.py b/skyvern/forge/sdk/routes/streaming/channels/exfiltration.py
index c1d30d328..f324f83ba 100644
--- a/skyvern/forge/sdk/routes/streaming/channels/exfiltration.py
+++ b/skyvern/forge/sdk/routes/streaming/channels/exfiltration.py
@@ -557,8 +557,16 @@ class ExfiltrationChannel(CdpChannel):
LOG.info(f"{self.class_name} removing decoration from page.", url=page.url)
- await page.add_init_script(self.js("undecorate"))
- await page.evaluate(self.js("undecorate"))
+ # Best-effort cleanup: the page's target can close mid-recording (take-control
+ # swaps, navigations, bot-detection pages), and Playwright then raises
+ # TargetClosedError here. Swallowing it keeps teardown from crashing the whole
+ # message-channel loop, which would drop capture and yield empty recordings.
+ try:
+ await page.add_init_script(self.js("undecorate"))
+ await page.evaluate(self.js("undecorate"))
+ except Exception:
+ LOG.debug(f"{self.class_name} failed to remove decoration from page", url=page.url, exc_info=True)
+ return self
LOG.info(f"{self.class_name} decoration removed from page.", url=page.url)
diff --git a/skyvern/forge/sdk/routes/streaming/channels/message.py b/skyvern/forge/sdk/routes/streaming/channels/message.py
index e52edaf38..a8d84bf97 100644
--- a/skyvern/forge/sdk/routes/streaming/channels/message.py
+++ b/skyvern/forge/sdk/routes/streaming/channels/message.py
@@ -613,7 +613,14 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
if exfiltration_channel is not None:
ensure_live_interpretation()
- await exfiltration_channel.rearm_all_pages()
+ try:
+ await exfiltration_channel.rearm_all_pages()
+ except Exception:
+ LOG.exception(
+ f"{class_name} failed to re-arm recording capture.",
+ **message_channel.identity,
+ )
+ await send_error(message.kind, "Failed to re-arm recording capture.")
return
ensure_live_interpretation()
@@ -633,10 +640,30 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
if live_interpretation_browser_session_id:
interpretation_registry.ingest_events(live_interpretation_browser_session_id, events)
- exfiltration_channel = await ExfiltrationChannel(
+ # A dead browser target (ECONNREFUSED / 502 from connect_over_cdp) must
+ # not escape handle_data: that kills the websocket loop, the frontend
+ # reconnects and re-sends begin-exfiltration, and the recording spins
+ # in a crash-loop capturing nothing.
+ new_channel = ExfiltrationChannel(
on_event=on_event,
vnc_channel=vnc_channel,
- ).start()
+ )
+ try:
+ exfiltration_channel = await new_channel.start()
+ except Exception:
+ LOG.exception(
+ f"{class_name} failed to start recording capture.",
+ **message_channel.identity,
+ )
+ try:
+ await new_channel.stop()
+ except Exception:
+ LOG.debug(
+ f"{class_name} failed to clean up after recording capture start failure.",
+ **message_channel.identity,
+ exc_info=True,
+ )
+ await send_error(message.kind, "Failed to start recording capture.")
case MessageKind.CEDE_CONTROL:
vnc_channel = get_vnc_channel(message_channel.client_id)
@@ -724,7 +751,18 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
if exfiltration_channel is None:
return
- await exfiltration_channel.stop()
+ # Channel teardown is best-effort: a browser whose target already
+ # closed raises here, and that must never skip the interpretation
+ # flush below — losing every draft the user just recorded.
+ try:
+ await exfiltration_channel.stop()
+ except Exception:
+ # Expected race (target already closed), so warning, not error.
+ LOG.warning(
+ f"{class_name} failed to stop recording capture cleanly.",
+ **message_channel.identity,
+ exc_info=True,
+ )
exfiltration_channel = None
if live_interpretation_browser_session_id:
@@ -745,7 +783,14 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
case MessageKind.RECORDING_REARM_CAPTURE:
if exfiltration_channel is not None:
- await exfiltration_channel.rearm_all_pages()
+ try:
+ await exfiltration_channel.rearm_all_pages()
+ except Exception:
+ LOG.exception(
+ f"{class_name} failed to re-arm recording capture.",
+ **message_channel.identity,
+ )
+ await send_error(message.kind, "Failed to re-arm recording capture.")
case MessageKind.GET_BROWSER_URL:
try:
@@ -928,7 +973,15 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
await asyncio.gather(*loops, return_exceptions=True)
LOG.debug(f"{class_name} Closing the message channel stream.", **message_channel.identity)
if exfiltration_channel is not None:
- await exfiltration_channel.stop()
+ try:
+ await exfiltration_channel.stop()
+ except Exception:
+ # Expected race (target already closed), so warning, not error.
+ LOG.warning(
+ f"{class_name} failed to stop recording capture during teardown.",
+ **message_channel.identity,
+ exc_info=True,
+ )
# Live interpretation is torn down only on explicit end-exfiltration so a
# disconnect→reconnect can resume the same in-flight recording session.
await message_channel.close(reason="loop-channel-closed")
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index add311bf7..e12356601 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -6,6 +6,7 @@ import asyncio
import codecs
import copy
import csv
+import hashlib
import html
import json
import keyword
@@ -13,6 +14,7 @@ import os
import re
import shutil
import smtplib
+import socket
import textwrap
import unicodedata
import uuid
@@ -160,6 +162,11 @@ from skyvern.forge.sdk.workflow.models.parameter import (
WorkflowParameter,
WorkflowParameterType,
)
+from skyvern.forge.sdk.workflow.secret_encryption import (
+ SENSITIVE_DESTINATION_FIELDS,
+ decrypt_secret_field_value,
+ is_encrypted_secret,
+)
from skyvern.schemas.runs import RunEngine
from skyvern.schemas.self_heal import HealClassification, HealSkipReason, OutputObligation
from skyvern.schemas.workflows import (
@@ -167,6 +174,7 @@ from skyvern.schemas.workflows import (
BlockResult,
BlockStatus,
BlockType,
+ FileDownloadTarget,
FileStorageType,
FileType,
FileUploadDestination,
@@ -872,7 +880,8 @@ class Block(BaseModel, abc.ABC):
description = None
try:
block_data = self.model_dump(
- exclude={
+ exclude=SENSITIVE_DESTINATION_FIELDS
+ | {
"workflow_run_block_id",
"organization_id",
"task_id",
@@ -3715,11 +3724,20 @@ class CodeBlock(Block):
}
def generate_async_user_function(
- self, code: str, page: Page | RecordingPage, parameters: dict[str, Any] | None = None
+ self,
+ code: str,
+ page: Page | RecordingPage,
+ parameters: dict[str, Any] | None = None,
+ *,
+ workflow_run_id: str | None = None,
+ organization_id: str | None = None,
+ workflow_run_block_id: str | None = None,
) -> Callable[[], Awaitable[dict[str, Any]]]:
# SECURITY: validate before exec(). The AST check must run on the raw
# user code so it can block dunder identifiers like __capture_locals.
self.is_safe_code(code)
+ code_sha256 = hashlib.sha256(code.encode("utf-8")).hexdigest()
+ code_len = len(code)
code = textwrap.indent(textwrap.dedent(code), " ")
runtime_variables: dict[str, Callable[[], Awaitable[dict[str, Any]]]] = {}
safe_vars = self.build_safe_vars()
@@ -3741,6 +3759,19 @@ async def wrapper({default_args}):
safe_vars["__param_defaults"] = parameter_defaults
# Compile under a recognizable filename so tracebacks map back to user code lines.
compiled_code = compile(full_code, CODE_BLOCK_FILENAME, "exec")
+ inline_exec_context = skyvern_context.current()
+ LOG.info(
+ "codeblock.inline_exec_entered",
+ code_sha256=code_sha256,
+ code_len=code_len,
+ in_process=True,
+ pid=os.getpid(),
+ hostname=socket.gethostname(),
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ trace_id=inline_exec_context.request_id if inline_exec_context else None,
+ )
exec(compiled_code, safe_vars, runtime_variables) # nosemgrep
user_function = runtime_variables["wrapper"]
if not parameter_defaults:
@@ -4698,7 +4729,22 @@ async def wrapper({default_args}):
secure_code_block_result.block_result.output_parameter_value,
)
return secure_code_block_result.block_result
- user_function = self.generate_async_user_function(self.code, recording_page, parameter_values)
+ LOG.warning(
+ "codeblock.secure_runner_downgrade",
+ selection_reason="override_returned_none",
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ block_label=self.label,
+ )
+ user_function = self.generate_async_user_function(
+ self.code,
+ recording_page,
+ parameter_values,
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ workflow_run_block_id=workflow_run_block_id,
+ )
result = await self.execute_user_function_with_timeout(
user_function,
settings.CODE_BLOCK_EXECUTION_TIMEOUT_SECONDS,
@@ -5571,12 +5617,11 @@ class UploadToS3Block(Block):
)
-class FileUploadBlock(Block):
- # There is a mypy bug with Literal. Without the type: ignore, mypy will raise an error:
- # Parameter 1 of Literal[...] cannot be of type "Any"
- block_type: Literal[BlockType.FILE_UPLOAD] = BlockType.FILE_UPLOAD # type: ignore
+class UnsupportedStorageTypeError(Exception):
+ pass
- storage_type: FileStorageType = FileStorageType.S3
+
+class FileDestinationBlock(Block):
s3_bucket: str | None = None
aws_access_key_id: str | None = None
aws_secret_access_key: str | None = None
@@ -5608,11 +5653,7 @@ class FileUploadBlock(Block):
),
)
- def get_all_parameters(
- self,
- workflow_run_id: str,
- ) -> list[PARAMETER_TYPE]:
- workflow_run_context = self.get_workflow_run_context(workflow_run_id)
+ def _get_destination_parameters(self, workflow_run_context: WorkflowRunContext) -> list[PARAMETER_TYPE]:
parameters = []
if self.path and workflow_run_context.has_parameter(self.path):
@@ -5668,7 +5709,7 @@ class FileUploadBlock(Block):
return parameters
- def format_potential_template_parameters(self, workflow_run_context: WorkflowRunContext) -> None:
+ def _format_destination_template_parameters(self, workflow_run_context: WorkflowRunContext) -> None:
if self.path:
self.path = self.format_block_parameter_template_from_workflow_run_context(self.path, workflow_run_context)
@@ -5738,7 +5779,38 @@ class FileUploadBlock(Block):
self.sftp_host_key, workflow_run_context
)
- self._apply_workflow_system_prompt(workflow_run_context)
+ def _validate_destination_fields(self, storage_type: FileStorageType) -> list[str]:
+ missing_parameters = []
+ if storage_type == FileStorageType.S3:
+ if not self.s3_bucket:
+ missing_parameters.append("s3_bucket")
+ if not self.aws_access_key_id:
+ missing_parameters.append("aws_access_key_id")
+ if not self.aws_secret_access_key:
+ missing_parameters.append("aws_secret_access_key")
+ elif storage_type == FileStorageType.AZURE:
+ if not self.azure_storage_account_name or self.azure_storage_account_name == "":
+ missing_parameters.append("azure_storage_account_name")
+ if not self.azure_storage_account_key or self.azure_storage_account_key == "":
+ missing_parameters.append("azure_storage_account_key")
+ if not self.azure_blob_container_name or self.azure_blob_container_name == "":
+ missing_parameters.append("azure_blob_container_name")
+ elif storage_type == FileStorageType.GOOGLE_DRIVE:
+ if not self.google_credential_id:
+ missing_parameters.append("google_credential_id")
+ if not self.google_drive_folder_id:
+ missing_parameters.append("google_drive_folder_id")
+ elif storage_type == FileStorageType.SFTP:
+ if not self.sftp_host:
+ missing_parameters.append("sftp_host")
+ if not self.sftp_username:
+ missing_parameters.append("sftp_username")
+ if not self.sftp_password and not self.sftp_private_key:
+ missing_parameters.append("sftp_password or sftp_private_key")
+ else:
+ raise UnsupportedStorageTypeError(storage_type)
+
+ return missing_parameters
def _get_s3_uri(self, workflow_run_id: str, path: str) -> str:
folder_path = self.path or f"{workflow_run_id}"
@@ -5758,8 +5830,21 @@ class FileUploadBlock(Block):
folder_path = "/".join(segment for segment in folder_path.split("/") if segment)
return folder_path + "/" + blob_name
- def _get_azure_blob_uri(self, workflow_run_id: str, blob_name: str) -> str:
- return f"https://{self.azure_storage_account_name}.blob.core.windows.net/{self.azure_blob_container_name}/{blob_name}"
+ @staticmethod
+ def _validate_azure_storage_account_name(azure_storage_account_name: str) -> None:
+ if re.fullmatch(r"[a-z0-9]{3,24}", azure_storage_account_name) is None:
+ raise AzureConfigurationError("Azure Storage account name must match ^[a-z0-9]{3,24}$")
+
+ def _get_azure_blob_uri(
+ self,
+ workflow_run_id: str,
+ blob_name: str,
+ azure_storage_account_name: str,
+ ) -> str:
+ self._validate_azure_storage_account_name(azure_storage_account_name)
+ return (
+ f"https://{azure_storage_account_name}.blob.core.windows.net/{self.azure_blob_container_name}/{blob_name}"
+ )
def _build_s3_destination(
self,
@@ -5792,7 +5877,7 @@ class FileUploadBlock(Block):
azure_storage_account_key: str,
) -> FileUploadDestination:
blob_name = self._get_azure_blob_name(workflow_run_id, file_path)
- customer_uri = self._get_azure_blob_uri(workflow_run_id, blob_name)
+ customer_uri = self._get_azure_blob_uri(workflow_run_id, blob_name, azure_storage_account_name)
sdk_uri = f"azure://{self.azure_blob_container_name or ''}/{blob_name}"
return FileUploadDestination(
storage_type=FileStorageType.AZURE,
@@ -5848,6 +5933,187 @@ class FileUploadBlock(Block):
sftp_host_key=host_key,
)
+ @staticmethod
+ async def _resolve_sensitive_destination_credential(
+ workflow_run_context: WorkflowRunContext,
+ value: str | None,
+ field_name: str,
+ ) -> str | None:
+ if not value:
+ return None
+ if is_encrypted_secret(value):
+ return await decrypt_secret_field_value(
+ value,
+ organization_id=workflow_run_context.organization_id,
+ field_name=field_name,
+ )
+ resolved_value = workflow_run_context.get_original_secret_value_or_none(value)
+ if resolved_value is not None:
+ return resolved_value
+ return value
+
+ async def _dispatch_files_to_storage(
+ self,
+ *,
+ storage_type: FileStorageType,
+ files_to_upload: list[str],
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ organization_id: str | None,
+ workflow_run_context: WorkflowRunContext,
+ ) -> list[str]:
+ uploaded_uris: list[str] = []
+ if not files_to_upload:
+ return uploaded_uris
+ if storage_type == FileStorageType.S3:
+ actual_aws_secret_access_key = await self._resolve_sensitive_destination_credential(
+ workflow_run_context,
+ self.aws_secret_access_key,
+ "aws_secret_access_key",
+ )
+ actual_aws_access_key_id = (
+ workflow_run_context.get_original_secret_value_or_none(self.aws_access_key_id) or self.aws_access_key_id
+ )
+ if (
+ not isinstance(actual_aws_access_key_id, str)
+ or not actual_aws_access_key_id.strip()
+ or not isinstance(actual_aws_secret_access_key, str)
+ or not actual_aws_secret_access_key.strip()
+ ):
+ raise ValueError("S3 is not configured: resolved AWS credentials are empty")
+ for file_path in files_to_upload:
+ destination = self._build_s3_destination(
+ workflow_run_id=workflow_run_id,
+ file_path=file_path,
+ aws_access_key_id=actual_aws_access_key_id,
+ aws_secret_access_key=actual_aws_secret_access_key,
+ )
+ customer_uri = await app.AGENT_FUNCTION.upload_file_to_customer_storage(
+ file_path=file_path,
+ destination=destination,
+ organization_id=organization_id,
+ run_id=workflow_run_id,
+ )
+ uploaded_uris.append(customer_uri)
+ LOG.info("Uploaded file(s) to S3 customer storage", file_path=self.path)
+ elif storage_type == FileStorageType.AZURE:
+ actual_azure_storage_account_key = await self._resolve_sensitive_destination_credential(
+ workflow_run_context,
+ self.azure_storage_account_key,
+ "azure_storage_account_key",
+ )
+ resolved_azure_storage_account_name = workflow_run_context.get_original_secret_value_or_none(
+ self.azure_storage_account_name
+ )
+ actual_azure_storage_account_name = (
+ self.azure_storage_account_name
+ if resolved_azure_storage_account_name is None
+ else resolved_azure_storage_account_name
+ )
+ if (
+ not isinstance(actual_azure_storage_account_name, str)
+ or not actual_azure_storage_account_name.strip()
+ or not isinstance(actual_azure_storage_account_key, str)
+ or not actual_azure_storage_account_key.strip()
+ ):
+ raise AzureConfigurationError("Azure Storage is not configured")
+ self._validate_azure_storage_account_name(actual_azure_storage_account_name)
+
+ for file_path in files_to_upload:
+ LOG.info("Uploading file to Azure Blob Storage customer storage", file_path=file_path)
+ destination = self._build_azure_destination(
+ workflow_run_id=workflow_run_id,
+ file_path=file_path,
+ azure_storage_account_name=actual_azure_storage_account_name,
+ azure_storage_account_key=actual_azure_storage_account_key,
+ )
+ customer_uri = await app.AGENT_FUNCTION.upload_file_to_customer_storage(
+ file_path=file_path,
+ destination=destination,
+ organization_id=organization_id,
+ run_id=workflow_run_id,
+ )
+ uploaded_uris.append(customer_uri)
+ LOG.info("Uploaded file(s) to Azure Blob Storage customer storage", file_path=self.path)
+ elif storage_type == FileStorageType.GOOGLE_DRIVE:
+ org_id = organization_id or workflow_run_context.organization_id
+ if not org_id:
+ raise ValueError("organization_id is required for Google Drive uploads")
+ google_credential_id = (
+ workflow_run_context.get_original_secret_value_or_none(self.google_credential_id)
+ or self.google_credential_id
+ )
+ if not google_credential_id:
+ raise ValueError("Google credential id is required")
+
+ google_credentials = await app.AGENT_FUNCTION.get_google_workspace_credentials(
+ organization_id=org_id,
+ credential_id=google_credential_id,
+ required_scopes=list(google_oauth_service.GOOGLE_DRIVE_SCOPES),
+ )
+ if not google_credentials or not google_credentials.token:
+ raise ValueError("Google Drive credential is not connected or is missing required scopes")
+
+ folder_id = google_drive_service.extract_folder_id(self.google_drive_folder_id or "")
+ for file_path in files_to_upload:
+ LOG.info("Uploading file to Google Drive customer storage", file_path=file_path)
+ destination = self._build_google_drive_destination(
+ access_token=google_credentials.token,
+ folder_id=folder_id,
+ )
+ customer_uri = await app.AGENT_FUNCTION.upload_file_to_customer_storage(
+ file_path=file_path,
+ destination=destination,
+ organization_id=org_id,
+ run_id=workflow_run_id,
+ )
+ uploaded_uris.append(customer_uri)
+ LOG.info("Uploaded file(s) to Google Drive customer storage", file_path=self.path)
+ elif storage_type == FileStorageType.SFTP:
+ actual_sftp_password = await self._resolve_sensitive_destination_credential(
+ workflow_run_context,
+ self.sftp_password,
+ "sftp_password",
+ )
+ actual_sftp_private_key = await self._resolve_sensitive_destination_credential(
+ workflow_run_context,
+ self.sftp_private_key,
+ "sftp_private_key",
+ )
+ actual_sftp_passphrase = await self._resolve_sensitive_destination_credential(
+ workflow_run_context,
+ self.sftp_private_key_passphrase,
+ "sftp_private_key_passphrase",
+ )
+ actual_sftp_username = (
+ workflow_run_context.get_original_secret_value_or_none(self.sftp_username) or self.sftp_username
+ )
+ sftp_port = 22 if self.sftp_port is None else self.sftp_port
+ for file_path in files_to_upload:
+ destination = self._build_sftp_destination(
+ file_path=file_path,
+ host=self.sftp_host or "",
+ port=sftp_port,
+ username=actual_sftp_username or "",
+ password=actual_sftp_password,
+ private_key=actual_sftp_private_key,
+ private_key_passphrase=actual_sftp_passphrase,
+ remote_path=self.sftp_remote_path,
+ host_key=self.sftp_host_key,
+ )
+ customer_uri = await app.AGENT_FUNCTION.upload_file_to_customer_storage(
+ file_path=file_path,
+ destination=destination,
+ organization_id=organization_id,
+ run_id=workflow_run_id,
+ )
+ uploaded_uris.append(customer_uri)
+ LOG.info("Uploaded file(s) to SFTP customer storage", file_path=self.path)
+ else:
+ raise ValueError(f"Unsupported storage type: {storage_type}")
+
+ return uploaded_uris
+
@staticmethod
def _candidate_download_signal_run_ids(
*,
@@ -6153,6 +6419,24 @@ class FileUploadBlock(Block):
return registered_downloaded_files
+
+class FileUploadBlock(FileDestinationBlock):
+ # There is a mypy bug with Literal. Without the type: ignore, mypy will raise an error:
+ # Parameter 1 of Literal[...] cannot be of type "Any"
+ block_type: Literal[BlockType.FILE_UPLOAD] = BlockType.FILE_UPLOAD # type: ignore
+
+ storage_type: FileStorageType = FileStorageType.S3
+
+ def get_all_parameters(
+ self,
+ workflow_run_id: str,
+ ) -> list[PARAMETER_TYPE]:
+ return self._get_destination_parameters(self.get_workflow_run_context(workflow_run_id))
+
+ def format_potential_template_parameters(self, workflow_run_context: WorkflowRunContext) -> None:
+ self._format_destination_template_parameters(workflow_run_context)
+ self._apply_workflow_system_prompt(workflow_run_context)
+
async def execute(
self,
workflow_run_id: str,
@@ -6165,34 +6449,9 @@ class FileUploadBlock(Block):
workflow_run_context = self.get_workflow_run_context(workflow_run_id)
# get all parameters into a dictionary
# data validate before uploading
- missing_parameters = []
- if self.storage_type == FileStorageType.S3:
- if not self.s3_bucket:
- missing_parameters.append("s3_bucket")
- if not self.aws_access_key_id:
- missing_parameters.append("aws_access_key_id")
- if not self.aws_secret_access_key:
- missing_parameters.append("aws_secret_access_key")
- elif self.storage_type == FileStorageType.AZURE:
- if not self.azure_storage_account_name or self.azure_storage_account_name == "":
- missing_parameters.append("azure_storage_account_name")
- if not self.azure_storage_account_key or self.azure_storage_account_key == "":
- missing_parameters.append("azure_storage_account_key")
- if not self.azure_blob_container_name or self.azure_blob_container_name == "":
- missing_parameters.append("azure_blob_container_name")
- elif self.storage_type == FileStorageType.GOOGLE_DRIVE:
- if not self.google_credential_id:
- missing_parameters.append("google_credential_id")
- if not self.google_drive_folder_id:
- missing_parameters.append("google_drive_folder_id")
- elif self.storage_type == FileStorageType.SFTP:
- if not self.sftp_host:
- missing_parameters.append("sftp_host")
- if not self.sftp_username:
- missing_parameters.append("sftp_username")
- if not self.sftp_password and not self.sftp_private_key:
- missing_parameters.append("sftp_password or sftp_private_key")
- else:
+ try:
+ missing_parameters = self._validate_destination_fields(self.storage_type)
+ except UnsupportedStorageTypeError:
return await self.build_block_result(
success=False,
failure_reason=f"Unsupported storage type: {self.storage_type}",
@@ -6351,131 +6610,14 @@ class FileUploadBlock(Block):
organization_id=organization_id,
)
- if self.storage_type == FileStorageType.S3:
- actual_aws_access_key_id = (
- workflow_run_context.get_original_secret_value_or_none(self.aws_access_key_id)
- or self.aws_access_key_id
- )
- actual_aws_secret_access_key = (
- workflow_run_context.get_original_secret_value_or_none(self.aws_secret_access_key)
- or self.aws_secret_access_key
- )
- for file_path in files_to_upload:
- destination = self._build_s3_destination(
- workflow_run_id=workflow_run_id,
- file_path=file_path,
- aws_access_key_id=actual_aws_access_key_id,
- aws_secret_access_key=actual_aws_secret_access_key,
- )
- customer_uri = await app.AGENT_FUNCTION.upload_file_to_customer_storage(
- file_path=file_path,
- destination=destination,
- organization_id=organization_id,
- run_id=workflow_run_id,
- )
- uploaded_uris.append(customer_uri)
- LOG.info("FileUploadBlock File(s) uploaded to S3", file_path=self.path)
- elif self.storage_type == FileStorageType.AZURE:
- actual_azure_storage_account_name = (
- workflow_run_context.get_original_secret_value_or_none(self.azure_storage_account_name)
- or self.azure_storage_account_name
- )
- actual_azure_storage_account_key = (
- workflow_run_context.get_original_secret_value_or_none(self.azure_storage_account_key)
- or self.azure_storage_account_key
- )
- if actual_azure_storage_account_name is None or actual_azure_storage_account_key is None:
- raise AzureConfigurationError("Azure Storage is not configured")
-
- for file_path in files_to_upload:
- LOG.info("FileUploadBlock Uploading file to Azure Blob Storage", file_path=file_path)
- destination = self._build_azure_destination(
- workflow_run_id=workflow_run_id,
- file_path=file_path,
- azure_storage_account_name=actual_azure_storage_account_name,
- azure_storage_account_key=actual_azure_storage_account_key,
- )
- customer_uri = await app.AGENT_FUNCTION.upload_file_to_customer_storage(
- file_path=file_path,
- destination=destination,
- organization_id=organization_id,
- run_id=workflow_run_id,
- )
- uploaded_uris.append(customer_uri)
- LOG.info("FileUploadBlock File(s) uploaded to Azure Blob Storage", file_path=self.path)
- elif self.storage_type == FileStorageType.GOOGLE_DRIVE:
- org_id = organization_id or workflow_run_context.organization_id
- if not org_id:
- raise ValueError("organization_id is required for Google Drive uploads")
- google_credential_id = (
- workflow_run_context.get_original_secret_value_or_none(self.google_credential_id)
- or self.google_credential_id
- )
- if not google_credential_id:
- raise ValueError("Google credential id is required")
-
- google_credentials = await app.AGENT_FUNCTION.get_google_workspace_credentials(
- organization_id=org_id,
- credential_id=google_credential_id,
- required_scopes=list(google_oauth_service.GOOGLE_DRIVE_SCOPES),
- )
- if not google_credentials or not google_credentials.token:
- raise ValueError("Google Drive credential is not connected or is missing required scopes")
-
- folder_id = google_drive_service.extract_folder_id(self.google_drive_folder_id or "")
- for file_path in files_to_upload:
- LOG.info("FileUploadBlock Uploading file to Google Drive", file_path=file_path)
- destination = self._build_google_drive_destination(
- access_token=google_credentials.token,
- folder_id=folder_id,
- )
- customer_uri = await app.AGENT_FUNCTION.upload_file_to_customer_storage(
- file_path=file_path,
- destination=destination,
- organization_id=org_id,
- run_id=workflow_run_id,
- )
- uploaded_uris.append(customer_uri)
- LOG.info("FileUploadBlock File(s) uploaded to Google Drive", file_path=self.path)
- elif self.storage_type == FileStorageType.SFTP:
- actual_sftp_username = (
- workflow_run_context.get_original_secret_value_or_none(self.sftp_username) or self.sftp_username
- )
- actual_sftp_password = (
- workflow_run_context.get_original_secret_value_or_none(self.sftp_password) or self.sftp_password
- )
- actual_sftp_private_key = (
- workflow_run_context.get_original_secret_value_or_none(self.sftp_private_key)
- or self.sftp_private_key
- )
- actual_sftp_passphrase = (
- workflow_run_context.get_original_secret_value_or_none(self.sftp_private_key_passphrase)
- or self.sftp_private_key_passphrase
- )
- sftp_port = 22 if self.sftp_port is None else self.sftp_port
- for file_path in files_to_upload:
- destination = self._build_sftp_destination(
- file_path=file_path,
- host=self.sftp_host or "",
- port=sftp_port,
- username=actual_sftp_username or "",
- password=actual_sftp_password,
- private_key=actual_sftp_private_key,
- private_key_passphrase=actual_sftp_passphrase,
- remote_path=self.sftp_remote_path,
- host_key=self.sftp_host_key,
- )
- customer_uri = await app.AGENT_FUNCTION.upload_file_to_customer_storage(
- file_path=file_path,
- destination=destination,
- organization_id=organization_id,
- run_id=workflow_run_id,
- )
- uploaded_uris.append(customer_uri)
- LOG.info("FileUploadBlock File(s) uploaded to SFTP", file_path=self.path)
- else:
- # This case should ideally be caught by the initial validation
- raise ValueError(f"Unsupported storage type: {self.storage_type}")
+ uploaded_uris = await self._dispatch_files_to_storage(
+ storage_type=self.storage_type,
+ files_to_upload=files_to_upload,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ workflow_run_context=workflow_run_context,
+ )
except Exception as e:
LOG.exception("FileUploadBlock Failed to upload file", file_path=self.path, storage_type=self.storage_type)
@@ -8535,10 +8677,246 @@ class LoginBlock(BaseTaskBlock):
skip_saved_profile: bool = False
-class FileDownloadBlock(BaseTaskBlock):
+class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
# There is a mypy bug with Literal. Without the type: ignore, mypy will raise an error:
# Parameter 1 of Literal[...] cannot be of type "Any"
block_type: Literal[BlockType.FILE_DOWNLOAD] = BlockType.FILE_DOWNLOAD # type: ignore
+ download_target: FileDownloadTarget = FileDownloadTarget.WEBSITE
+
+ def get_all_parameters(self, workflow_run_id: str) -> list[PARAMETER_TYPE]:
+ parameters = super().get_all_parameters(workflow_run_id)
+ workflow_run_context = self.get_workflow_run_context(workflow_run_id)
+ existing_keys = {p.key for p in parameters}
+ for destination_param in self._get_destination_parameters(workflow_run_context):
+ if destination_param.key not in existing_keys:
+ parameters.append(destination_param)
+ existing_keys.add(destination_param.key)
+ return parameters
+
+ async def execute(
+ self,
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ organization_id: str | None = None,
+ browser_session_id: str | None = None,
+ **kwargs: dict,
+ ) -> BlockResult:
+ download_files_path = ""
+ baseline_unknown = False
+ pre_names: set[str] = set()
+ pre_hashes: dict[str, str] = {}
+ pre_mtimes: dict[str, int] = {}
+ colliding_normalized_names: set[str] = set()
+ if self.download_target != FileDownloadTarget.WEBSITE:
+ # Fail fast on a misconfigured destination before running the (expensive) browser
+ # download, so a missing required field does not waste a download that cannot be delivered.
+ early_storage_type = FileStorageType(self.download_target.value)
+ early_context = self.get_workflow_run_context(workflow_run_id)
+ try:
+ early_missing_parameters = self._validate_destination_fields(early_storage_type)
+ except UnsupportedStorageTypeError as e:
+ await self.record_output_parameter_value(early_context, workflow_run_id, None)
+ return await self.build_block_result(
+ success=False,
+ failure_reason=f"Failed to send downloaded file(s) to {early_storage_type}: {e}",
+ output_parameter_value=None,
+ status=BlockStatus.failed,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+ if early_missing_parameters:
+ await self.record_output_parameter_value(early_context, workflow_run_id, None)
+ return await self.build_block_result(
+ success=False,
+ failure_reason=(
+ f"Required block values are missing in the FileDownloadBlock (label: {self.label}): "
+ f"{', '.join(early_missing_parameters)}"
+ ),
+ output_parameter_value=None,
+ status=BlockStatus.failed,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+ context = skyvern_context.current()
+ run_download_id = resolve_run_download_id(context, fallback_run_id=workflow_run_id)
+ download_files_path = str(get_path_for_workflow_download_directory(run_download_id).absolute())
+ try:
+ pre_download_filenames = os.listdir(download_files_path)
+ except FileNotFoundError:
+ pre_download_filenames = []
+ except OSError:
+ baseline_unknown = True
+ pre_download_filenames = []
+ for filename in pre_download_filenames:
+ local_file = os.path.join(download_files_path, filename)
+ if not os.path.isfile(local_file):
+ continue
+ normalized_filename = unicodedata.normalize("NFC", filename)
+ if normalized_filename in pre_names:
+ colliding_normalized_names.add(normalized_filename)
+ pre_names.add(normalized_filename)
+ try:
+ pre_hashes[normalized_filename] = calculate_sha256_for_file(local_file)
+ pre_mtimes[filename] = os.stat(local_file).st_mtime_ns
+ except OSError:
+ continue
+ if baseline_unknown:
+ # Fail fast before the download: the baseline scan failed, so delivery would be
+ # refused anyway (to avoid leaking earlier files) — do not download customer data.
+ await self.record_output_parameter_value(early_context, workflow_run_id, None)
+ return await self.build_block_result(
+ success=False,
+ failure_reason=(
+ "Could not establish the pre-download baseline; refusing to deliver files to "
+ f"{early_storage_type} to avoid leaking earlier files."
+ ),
+ output_parameter_value=None,
+ status=BlockStatus.failed,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+
+ result = await super().execute(
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
+ **kwargs,
+ )
+ if self.download_target == FileDownloadTarget.WEBSITE:
+ return result
+ if not result.success:
+ return result
+
+ storage_type = FileStorageType(self.download_target.value)
+ workflow_run_context = self.get_workflow_run_context(workflow_run_id)
+ try:
+ self._format_destination_template_parameters(workflow_run_context)
+ max_file_count = (
+ MAX_UPLOAD_FILE_COUNT
+ if storage_type in {FileStorageType.S3, FileStorageType.GOOGLE_DRIVE, FileStorageType.SFTP}
+ else AZURE_BLOB_STORAGE_MAX_UPLOAD_FILE_COUNT
+ )
+ try:
+ post_download_filenames = os.listdir(download_files_path)
+ except FileNotFoundError:
+ post_download_filenames = []
+ except OSError as e:
+ # Symmetric with the pre-download baseline: a real post-download scan failure (not a
+ # missing directory) must fail closed rather than report success without delivering.
+ raise RuntimeError("Could not scan the download directory after the download completed") from e
+
+ files_to_upload: list[str] = []
+ for filename in post_download_filenames:
+ local_file = os.path.join(download_files_path, filename)
+ try:
+ if not os.path.isfile(local_file):
+ if os.path.isdir(local_file):
+ LOG.warning("FileDownloadBlock skipping directory", file=filename)
+ continue
+ normalized_filename = unicodedata.normalize("NFC", filename)
+ except OSError:
+ continue
+
+ if normalized_filename in colliding_normalized_names:
+ # Multiple byte-distinct directory entries normalized to this name at baseline,
+ # so neither content hash nor write time can be attributed to a single entry;
+ # fail closed rather than risk delivering an earlier block's file.
+ continue
+
+ if normalized_filename not in pre_names:
+ files_to_upload.append(local_file)
+ continue
+ if normalized_filename not in pre_hashes:
+ continue
+ try:
+ current_hash = calculate_sha256_for_file(local_file)
+ except OSError:
+ continue
+ if current_hash != pre_hashes[normalized_filename]:
+ files_to_upload.append(local_file)
+ continue
+ # Identical content means hashing cannot distinguish a genuine re-download
+ # from an earlier block's leftover; fall back to write time, keyed by the raw
+ # directory-entry name so Unicode-normalization-equivalent names never share a
+ # baseline. Deliver only if this block rewrote this exact entry in its own window.
+ baseline_mtime_ns = pre_mtimes.get(filename)
+ if baseline_mtime_ns is None:
+ continue
+ try:
+ current_mtime_ns = os.stat(local_file).st_mtime_ns
+ except OSError:
+ continue
+ if current_mtime_ns > baseline_mtime_ns:
+ files_to_upload.append(local_file)
+
+ if not files_to_upload:
+ return result
+
+ if len(files_to_upload) > max_file_count:
+ raise ValueError(f"Too many scoped downloaded files to upload. Max: {max_file_count}")
+
+ if files_to_upload and self.prompt and self.prompt.strip():
+ candidate_count = len(files_to_upload)
+ files_to_upload, selection_reasoning = await self._select_files_to_upload_with_prompt(
+ prompt=self.prompt,
+ files_to_upload=files_to_upload,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+ selected_count = len(files_to_upload)
+ LOG.info(
+ "FileDownloadBlock prompt selection completed",
+ block_label=self.label,
+ candidate_count=candidate_count,
+ selected_count=selected_count,
+ )
+
+ if not files_to_upload:
+ LOG.warning(
+ "FileDownloadBlock prompt selected no files; treating as no-op",
+ block_label=self.label,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ candidate_count=candidate_count,
+ selected_count=selected_count,
+ reasoning=selection_reasoning,
+ )
+ return result
+
+ uploaded_uris = await self._dispatch_files_to_storage(
+ storage_type=storage_type,
+ files_to_upload=files_to_upload,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ workflow_run_context=workflow_run_context,
+ )
+ except Exception as e:
+ LOG.exception(
+ "FileDownloadBlock failed to send downloaded file(s)",
+ block_label=self.label,
+ storage_type=storage_type,
+ )
+ await self.record_output_parameter_value(workflow_run_context, workflow_run_id, None)
+ return await self.build_block_result(
+ success=False,
+ failure_reason=f"Failed to send downloaded file(s) to {storage_type}: {e}",
+ output_parameter_value=None,
+ status=BlockStatus.failed,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+
+ LOG.info(
+ "FileDownloadBlock sent downloaded file(s) to customer storage",
+ block_label=self.label,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ storage_type=storage_type,
+ uploaded_file_count=len(uploaded_uris),
+ )
+ return result
class UrlBlock(BaseTaskBlock):
diff --git a/skyvern/forge/sdk/workflow/secret_encryption.py b/skyvern/forge/sdk/workflow/secret_encryption.py
new file mode 100644
index 000000000..a53c89bdc
--- /dev/null
+++ b/skyvern/forge/sdk/workflow/secret_encryption.py
@@ -0,0 +1,107 @@
+import base64
+import os
+from typing import Any
+
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives.ciphers.aead import AESGCM
+from cryptography.hazmat.primitives.kdf.hkdf import HKDF
+
+from skyvern.config import settings
+from skyvern.schemas.workflows import BlockType, _has_jinja_syntax
+
+SENSITIVE_DESTINATION_FIELDS: frozenset[str] = frozenset(
+ {
+ "aws_secret_access_key",
+ "azure_storage_account_key",
+ "sftp_password",
+ "sftp_private_key",
+ "sftp_private_key_passphrase",
+ }
+)
+ENCRYPTED_SECRET_PREFIX = "skyvern_enc:"
+_METHOD = "aesgcm-v1"
+_SENTINEL_PREFIX = f"{ENCRYPTED_SECRET_PREFIX}{_METHOD}:"
+_NONCE_LEN = 12
+
+
+def is_encrypted_secret(value: str | None) -> bool:
+ # Match the whole encrypted-secret namespace, not just the current method, so no sentinel
+ # (including an older method) is ever re-encrypted; decrypt still accepts only the current method.
+ return isinstance(value, str) and value.startswith(ENCRYPTED_SECRET_PREFIX)
+
+
+def encryption_available() -> bool:
+ return (
+ bool(settings.ENABLE_ENCRYPTION)
+ and bool(settings.ENCRYPTOR_AES_SECRET_KEY)
+ and settings.ENCRYPTOR_AES_SECRET_KEY != "fillmein"
+ )
+
+
+def _derive_key() -> bytes:
+ salt = settings.ENCRYPTOR_AES_SALT.encode() if settings.ENCRYPTOR_AES_SALT else None
+ hkdf = HKDF(
+ algorithm=hashes.SHA256(),
+ length=32,
+ salt=salt,
+ info=b"skyvern-file-destination-secret-aesgcm-v1",
+ )
+ return hkdf.derive(settings.ENCRYPTOR_AES_SECRET_KEY.encode())
+
+
+# AAD binds each ciphertext to its org + field so a value moved to another field or org fails to authenticate.
+def _binding_aad(organization_id: str | None, field_name: str) -> bytes:
+ return b"\x00".join((b"skyvern-file-destination-secret-v1", (organization_id or "").encode(), field_name.encode()))
+
+
+async def encrypt_secret_field_value(
+ value: str | None,
+ *,
+ organization_id: str | None,
+ field_name: str,
+) -> str | None:
+ if not value or _has_jinja_syntax(value) or is_encrypted_secret(value) or not encryption_available():
+ return value
+ nonce = os.urandom(_NONCE_LEN)
+ ciphertext = AESGCM(_derive_key()).encrypt(nonce, value.encode(), _binding_aad(organization_id, field_name))
+ return _SENTINEL_PREFIX + base64.b64encode(nonce + ciphertext).decode()
+
+
+async def decrypt_secret_field_value(value: str, *, organization_id: str | None, field_name: str) -> str:
+ if not is_encrypted_secret(value):
+ raise ValueError("Value is not an encrypted secret")
+ try:
+ raw = base64.b64decode(value[len(_SENTINEL_PREFIX) :], validate=True)
+ nonce, ciphertext = raw[:_NONCE_LEN], raw[_NONCE_LEN:]
+ if len(nonce) != _NONCE_LEN or not ciphertext:
+ raise ValueError
+ plaintext = AESGCM(_derive_key()).decrypt(nonce, ciphertext, _binding_aad(organization_id, field_name))
+ except Exception:
+ # Generic on purpose: never reveal the ciphertext/plaintext or which check failed.
+ raise ValueError("Failed to decrypt or authenticate the encrypted secret") from None
+ return plaintext.decode()
+
+
+async def encrypt_workflow_definition_secrets(definition: Any, organization_id: str | None) -> None:
+ if not encryption_available():
+ return
+
+ async def encrypt_blocks(blocks: list[Any]) -> None:
+ for block in blocks:
+ block_type = getattr(block, "block_type", None)
+ if block_type in (BlockType.FILE_UPLOAD, BlockType.FILE_DOWNLOAD):
+ for field_name in SENSITIVE_DESTINATION_FIELDS:
+ value = getattr(block, field_name, None)
+ setattr(
+ block,
+ field_name,
+ await encrypt_secret_field_value(
+ value,
+ organization_id=organization_id,
+ field_name=field_name,
+ ),
+ )
+ elif block_type in (BlockType.FOR_LOOP, BlockType.WHILE_LOOP):
+ await encrypt_blocks(getattr(block, "loop_blocks", []))
+
+ await encrypt_blocks(definition.blocks)
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 7a5d5b3cf..bb49f0acb 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -139,6 +139,7 @@ from skyvern.forge.sdk.workflow.models.workflow import (
WorkflowRunStatus,
is_adaptive_caching,
)
+from skyvern.forge.sdk.workflow.secret_encryption import encrypt_workflow_definition_secrets
from skyvern.forge.sdk.workflow.status_mapping import (
BLOCK_STATUS_MAP,
NONFINAL_BLOCK_STATUSES,
@@ -5096,6 +5097,7 @@ class WorkflowService:
edited_by: str | None = None,
) -> Workflow:
try:
+ await encrypt_workflow_definition_secrets(workflow_definition, organization_id)
return await app.DATABASE.workflows.create_workflow(
title=title,
workflow_definition=workflow_definition.model_dump(mode="json"),
@@ -5533,6 +5535,7 @@ class WorkflowService:
workflow_definition.parameters,
organization,
)
+ await encrypt_workflow_definition_secrets(workflow_definition, organization_id)
updated_workflow = await app.DATABASE.workflows.update_workflow_and_reconcile_definition_params(
workflow_id=workflow_id,
title=title,
diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
index 5b45d2f6f..2420df7d0 100644
--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py
+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
@@ -832,6 +832,27 @@ def block_yaml_to_block(
file_download_block_parameters = _resolve_block_parameters(block_yaml, parameters)
return FileDownloadBlock(
**base_kwargs,
+ download_target=block_yaml.download_target,
+ s3_bucket=block_yaml.s3_bucket,
+ aws_access_key_id=block_yaml.aws_access_key_id,
+ aws_secret_access_key=block_yaml.aws_secret_access_key,
+ region_name=block_yaml.region_name,
+ azure_storage_account_name=block_yaml.azure_storage_account_name,
+ azure_storage_account_key=block_yaml.azure_storage_account_key,
+ azure_blob_container_name=block_yaml.azure_blob_container_name,
+ google_credential_id=block_yaml.google_credential_id,
+ google_drive_folder_id=block_yaml.google_drive_folder_id,
+ sftp_host=block_yaml.sftp_host,
+ sftp_port=block_yaml.sftp_port,
+ sftp_username=block_yaml.sftp_username,
+ sftp_password=block_yaml.sftp_password,
+ sftp_private_key=block_yaml.sftp_private_key,
+ sftp_private_key_passphrase=block_yaml.sftp_private_key_passphrase,
+ sftp_remote_path=block_yaml.sftp_remote_path,
+ sftp_host_key=block_yaml.sftp_host_key,
+ path=block_yaml.path,
+ prompt=block_yaml.prompt,
+ continue_on_empty=block_yaml.continue_on_empty,
url=block_yaml.url,
title=block_yaml.title,
engine=block_yaml.engine,
diff --git a/skyvern/library/skyvern.py b/skyvern/library/skyvern.py
index 0caf73a0c..36881439b 100644
--- a/skyvern/library/skyvern.py
+++ b/skyvern/library/skyvern.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import os
import pathlib
+import shutil
import tempfile
from typing import TYPE_CHECKING, Any
@@ -21,6 +22,7 @@ from skyvern.schemas.proxy_location import ProxyLocationInput, proxy_location_to
from skyvern.schemas.run_enums import RunEngine, RunStatus
LOG = structlog.get_logger()
+_DEVTOOLS_ACTIVE_PORT_TIMEOUT_SECONDS = 2.0
if TYPE_CHECKING:
from playwright.async_api import Playwright
@@ -29,6 +31,22 @@ if TYPE_CHECKING:
from skyvern.schemas.llm import LLMConfig, LLMRouterConfig
+async def _read_devtools_active_port(user_data_dir: pathlib.Path) -> int:
+ active_port_file = user_data_dir / "DevToolsActivePort"
+ deadline = asyncio.get_running_loop().time() + _DEVTOOLS_ACTIVE_PORT_TIMEOUT_SECONDS
+ last_error: OSError | ValueError | IndexError | None = None
+ while asyncio.get_running_loop().time() < deadline:
+ try:
+ port = int(active_port_file.read_text().splitlines()[0])
+ if not 1 <= port <= 65535:
+ raise ValueError(f"invalid CDP port: {port}")
+ return port
+ except (OSError, ValueError, IndexError) as exc:
+ last_error = exc
+ await asyncio.sleep(0.01)
+ raise RuntimeError(f"Chromium did not publish a valid CDP port in {active_port_file}") from last_error
+
+
def _get_browser_session_url(browser_session: BrowserSessionResponse) -> str:
"""Return the app URL for a browser session, using the server-provided URL when available."""
if browser_session.app_url:
@@ -467,7 +485,7 @@ class Skyvern(AsyncSkyvern):
self,
*,
headless: bool = False,
- port: int = DEFAULT_CDP_PORT,
+ port: int | None = None,
args: list[str] | None = None,
user_data_dir: str | None = None,
) -> SkyvernBrowser:
@@ -478,7 +496,8 @@ class Skyvern(AsyncSkyvern):
Args:
headless: Whether to run the browser in headless mode. Defaults to False.
- port: The port number for the CDP endpoint. Defaults to DEFAULT_CDP_PORT.
+ port: The port number for the CDP endpoint. Anonymous launches use an
+ OS-assigned port; explicitly configured launches retain DEFAULT_CDP_PORT.
args: Additional command-line arguments to pass to Chromium. Defaults to None.
Example: ["--disable-blink-features=AutomationControlled", "--window-size=1920,1080"]
@@ -490,24 +509,48 @@ class Skyvern(AsyncSkyvern):
playwright = await self._get_playwright()
- if user_data_dir:
+ use_instance_defaults = user_data_dir is None and port is None
+ if use_instance_defaults:
+ user_data_path = pathlib.Path(tempfile.mkdtemp(prefix="skyvern-browser-"))
+ launch_port = 0
+ elif user_data_dir:
user_data_path = pathlib.Path(user_data_dir)
+ launch_port = port if port is not None else DEFAULT_CDP_PORT
else:
user_data_path = pathlib.Path(tempfile.gettempdir()) / "skyvern-browser"
+ launch_port = port if port is not None else DEFAULT_CDP_PORT
launch_args = [
- f"--remote-debugging-port={port}",
+ f"--remote-debugging-port={launch_port}",
]
if args:
launch_args.extend(args)
- browser_context = await playwright.chromium.launch_persistent_context(
- user_data_dir=str(user_data_path),
- headless=headless,
- args=launch_args,
+ browser_context = None
+ try:
+ browser_context = await playwright.chromium.launch_persistent_context(
+ user_data_dir=str(user_data_path),
+ headless=headless,
+ args=launch_args,
+ )
+ resolved_port = await _read_devtools_active_port(user_data_path) if use_instance_defaults else launch_port
+ except Exception:
+ try:
+ if browser_context is not None:
+ await browser_context.close()
+ finally:
+ if use_instance_defaults:
+ shutil.rmtree(user_data_path, ignore_errors=True)
+ raise
+ browser_address = f"http://localhost:{resolved_port}"
+ return SkyvernBrowser(
+ self,
+ browser_context,
+ browser_address=browser_address,
+ local_cdp_port=resolved_port,
+ local_user_data_dir=str(user_data_path),
+ local_user_data_dir_owned=use_instance_defaults,
)
- browser_address = f"http://localhost:{port}"
- return SkyvernBrowser(self, browser_context, browser_address=browser_address)
async def connect_to_browser_over_cdp(self, cdp_url: str) -> SkyvernBrowser:
"""Connect to an existing browser instance via Chrome DevTools Protocol (CDP).
diff --git a/skyvern/library/skyvern_browser.py b/skyvern/library/skyvern_browser.py
index fa57af338..870a18ff0 100644
--- a/skyvern/library/skyvern_browser.py
+++ b/skyvern/library/skyvern_browser.py
@@ -1,4 +1,5 @@
# ruff: noqa: E402
+import shutil
from typing import TYPE_CHECKING, Any
from skyvern.exceptions import require_local_extra_modules
@@ -47,6 +48,9 @@ class SkyvernBrowser(BrowserContext):
browser_session_id: str | None = None,
browser_address: str | None = None,
app_url: str | None = None,
+ local_cdp_port: int | None = None,
+ local_user_data_dir: str | None = None,
+ local_user_data_dir_owned: bool = False,
):
super().__init__(browser_context)
self._skyvern = skyvern
@@ -54,6 +58,9 @@ class SkyvernBrowser(BrowserContext):
self._browser_session_id = browser_session_id
self._browser_address = browser_address
self._app_url = app_url
+ self._local_cdp_port = local_cdp_port
+ self._local_user_data_dir = local_user_data_dir
+ self._local_user_data_dir_owned = local_user_data_dir_owned
self.workflow_run_id: None | str = None
@@ -77,6 +84,18 @@ class SkyvernBrowser(BrowserContext):
def browser_address(self) -> str | None:
return self._browser_address
+ @property
+ def local_cdp_port(self) -> int | None:
+ return self._local_cdp_port
+
+ @property
+ def local_user_data_dir(self) -> str | None:
+ return self._local_user_data_dir
+
+ @property
+ def local_user_data_dir_owned(self) -> bool:
+ return self._local_user_data_dir_owned
+
@property
def app_url(self) -> str | None:
return self._app_url
@@ -142,6 +161,8 @@ class SkyvernBrowser(BrowserContext):
```
"""
await self._browser_context.close(**kwargs)
+ if self._local_user_data_dir_owned and self._local_user_data_dir:
+ shutil.rmtree(self._local_user_data_dir, ignore_errors=True)
if self._browser_session_id:
await self._skyvern.close_browser_session(self._browser_session_id)
diff --git a/skyvern/library/skyvern_browser_page.py b/skyvern/library/skyvern_browser_page.py
index 15eebeb7a..a54992e71 100644
--- a/skyvern/library/skyvern_browser_page.py
+++ b/skyvern/library/skyvern_browser_page.py
@@ -85,7 +85,7 @@ class SkyvernBrowserPage(SkyvernPage):
raise ValueError(f"Frame index {index} out of range (0-{len(frames) - 1}).")
frame = frames[index]
- self._working_frame = frame
+ self._working_frame = None if frame is self.page.main_frame else frame
return {
"name": frame.name if frame else None,
"url": frame.url if frame else None,
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index b81937649..968662e96 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -510,6 +510,14 @@ class FileStorageType(StrEnum):
SFTP = "sftp"
+class FileDownloadTarget(StrEnum):
+ WEBSITE = "website"
+ S3 = "s3"
+ AZURE = "azure"
+ GOOGLE_DRIVE = "google_drive"
+ SFTP = "sftp"
+
+
class FileUploadDestination(BaseModel):
"""Customer-storage destination for a single file upload.
@@ -1086,6 +1094,27 @@ class HumanInteractionBlockYAML(BlockYAML):
class FileDownloadBlockYAML(BlockYAML):
block_type: Literal[BlockType.FILE_DOWNLOAD] = BlockType.FILE_DOWNLOAD # type: ignore
+ download_target: FileDownloadTarget = FileDownloadTarget.WEBSITE
+ s3_bucket: str | None = None
+ aws_access_key_id: str | None = None
+ aws_secret_access_key: str | None = None
+ region_name: str | None = None
+ azure_storage_account_name: str | None = None
+ azure_storage_account_key: str | None = None
+ azure_blob_container_name: str | None = None
+ google_credential_id: str | None = None
+ google_drive_folder_id: str | None = None
+ sftp_host: str | None = None
+ sftp_port: int | None = None
+ sftp_username: str | None = None
+ sftp_password: str | None = None
+ sftp_private_key: str | None = None
+ sftp_private_key_passphrase: str | None = None
+ sftp_remote_path: str | None = None
+ sftp_host_key: str | None = None
+ path: str | None = None
+ prompt: str | None = None
+ continue_on_empty: bool = False
navigation_goal: str
url: str | None = None
title: str = ""
diff --git a/skyvern/services/browser_recording/interpretation.py b/skyvern/services/browser_recording/interpretation.py
index 53d08572c..d1bb98962 100644
--- a/skyvern/services/browser_recording/interpretation.py
+++ b/skyvern/services/browser_recording/interpretation.py
@@ -253,9 +253,9 @@ class RecordingInterpretationSession:
self.organization_id = organization_id
self.workflow_permanent_id = workflow_permanent_id
self.on_update = on_update
- # Identifies the client-side recording attempt. A cached session is
- # reused across reconnects only when this matches; a new recording sends
- # a new id, forcing a fresh session (state machines reset from scratch).
+ # Identifies the client-side recording attempt. The registry continues an
+ # unfinished session across reconnects even when this differs (the client
+ # lost its state, e.g. page reload — SKY-12429) and adopts the new id.
self.recording_attempt_id = recording_attempt_id
self.set_deltas_enabled(deltas_enabled)
self.interpretation_session_id = str(uuid.uuid4())
diff --git a/skyvern/services/browser_recording/session_registry.py b/skyvern/services/browser_recording/session_registry.py
index 153679aa4..4a1db2321 100644
--- a/skyvern/services/browser_recording/session_registry.py
+++ b/skyvern/services/browser_recording/session_registry.py
@@ -12,6 +12,8 @@ from skyvern.services.browser_recording.types import RecordingDraftStep
LOG = structlog.get_logger(__name__)
+# Also bounds the draft-inheritance window: an unfinished session abandoned
+# without Done/Discard (tab closed, network drop) stays reusable this long.
SESSION_TTL_SECONDS = 60 * 30
@@ -32,18 +34,34 @@ class RecordingInterpretationSessionRegistry:
) -> None:
self._prune_expired_sessions()
existing = self._sessions.get(browser_session_id)
- # Reuse the cached session only for a reconnect to the SAME recording. A
- # new recording sends a different recording_attempt_id, so its events must
- # not be appended to the prior session's already-consumed state machines
- # (which would emit zero new draft steps). Clients that omit the id keep
- # the legacy reuse behavior.
+ # Reuse the cached session for any reconnect to the same unfinished
+ # recording, even under a different recording_attempt_id. The client mints
+ # the id once per recording and keeps it stable across reconnects and
+ # stream remounts, so a differing id here means the client lost its
+ # in-memory state (e.g. page reload) — wiping would drop every accumulated
+ # draft (SKY-12429). Continuing is safe: emit_snapshot resyncs the fresh
+ # client, and a completed recording never hits this branch because
+ # Done/Discard both end exfiltration, which pops the session. Deliberate
+ # trade-off: a recording abandoned WITHOUT Done/Discard reaching the
+ # backend stays inheritable for SESSION_TTL_SECONDS, so a new recording on
+ # the same browser session + workflow within that window resumes the
+ # abandoned drafts (recovery) rather than starting empty; the user can
+ # discard them, which now clears this cache.
if (
existing is not None
and existing.workflow_permanent_id == workflow_permanent_id
and existing.organization_id == organization_id
and not existing.finalized
- and (recording_attempt_id is None or existing.recording_attempt_id == recording_attempt_id)
):
+ if recording_attempt_id is not None and existing.recording_attempt_id != recording_attempt_id:
+ LOG.info(
+ "Continuing recording interpretation session under a new attempt id",
+ browser_session_id=browser_session_id,
+ previous_recording_attempt_id=existing.recording_attempt_id,
+ recording_attempt_id=recording_attempt_id,
+ accumulated_step_count=len(existing.steps),
+ )
+ existing.recording_attempt_id = recording_attempt_id
existing.on_update = on_update
existing.set_deltas_enabled(deltas_enabled)
self._last_seen[browser_session_id] = time.monotonic()
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index 1c4133693..5437d24b0 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -7,7 +7,7 @@ import json
import os
import uuid
from dataclasses import dataclass
-from datetime import datetime
+from datetime import datetime, timezone
from pathlib import Path
from typing import Any, AsyncGenerator, Callable, Sequence, cast
@@ -36,7 +36,13 @@ from skyvern.exceptions import (
)
from skyvern.forge import app
from skyvern.forge.prompts import prompt_engine
-from skyvern.forge.sdk.api.files import get_path_for_workflow_download_directory, list_files_in_directory, rename_file
+from skyvern.forge.sdk.api.files import (
+ check_downloading_files_and_wait_for_download_to_complete,
+ get_path_for_workflow_download_directory,
+ list_files_in_directory,
+ rename_file,
+ resolve_run_download_id,
+)
from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.db.enums import TaskType
@@ -53,6 +59,7 @@ from skyvern.forge.sdk.workflow.loop_download_filter import (
to_downloaded_file_signature as _to_downloaded_file_signature,
)
from skyvern.forge.sdk.workflow.models.block import (
+ CURRENT_DATE_FORMAT,
DEFAULT_MAX_LOOP_ITERATIONS,
ActionBlock,
CodeBlock,
@@ -88,7 +95,7 @@ from skyvern.schemas.scripts import (
ScriptStatus,
)
from skyvern.schemas.steps import AgentStepOutput
-from skyvern.schemas.workflows import BlockResult, BlockStatus, BlockType, FileStorageType, FileType
+from skyvern.schemas.workflows import BlockResult, BlockStatus, BlockType, FileDownloadTarget, FileStorageType, FileType
from skyvern.utils.css_selector import build_action_summaries_with_timing
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action, DecisiveAction
@@ -1985,32 +1992,180 @@ async def download(
cache_key: str | None = None,
model: dict[str, Any] | None = None,
error_code_mapping: dict[str, str] | None = None,
+ navigation_goal: str | None = None,
+ download_target: str = "website",
+ s3_bucket: str | None = None,
+ aws_access_key_id: str | None = None,
+ aws_secret_access_key: str | None = None,
+ region_name: str | None = None,
+ azure_storage_account_name: str | None = None,
+ azure_storage_account_key: str | None = None,
+ azure_blob_container_name: str | None = None,
+ google_credential_id: str | None = None,
+ google_drive_folder_id: str | None = None,
+ sftp_host: str | None = None,
+ sftp_port: int | None = None,
+ sftp_username: str | None = None,
+ sftp_password: str | None = None,
+ sftp_private_key: str | None = None,
+ sftp_private_key_passphrase: str | None = None,
+ sftp_remote_path: str | None = None,
+ sftp_host_key: str | None = None,
+ path: str | None = None,
+ continue_on_empty: bool | None = None,
) -> None:
cache_key = cache_key or label
+ navigation_prompt = navigation_goal or prompt
+ destination_prompt = prompt if navigation_goal is not None else None
+ if s3_bucket:
+ s3_bucket = _render_template_with_label(s3_bucket, cache_key)
+ if aws_access_key_id:
+ aws_access_key_id = _render_template_with_label(aws_access_key_id, cache_key)
+ if aws_secret_access_key:
+ aws_secret_access_key = _render_template_with_label(aws_secret_access_key, cache_key)
+ if region_name:
+ region_name = _render_template_with_label(region_name, cache_key)
+ if azure_storage_account_name:
+ azure_storage_account_name = _render_template_with_label(azure_storage_account_name, cache_key)
+ if azure_storage_account_key:
+ azure_storage_account_key = _render_template_with_label(azure_storage_account_key, cache_key)
+ if azure_blob_container_name:
+ azure_blob_container_name = _render_template_with_label(azure_blob_container_name, cache_key)
+ if google_credential_id:
+ google_credential_id = _render_template_with_label(google_credential_id, cache_key)
+ if google_drive_folder_id:
+ google_drive_folder_id = _render_template_with_label(google_drive_folder_id, cache_key)
+ if sftp_host:
+ sftp_host = _render_template_with_label(sftp_host, cache_key)
+ if sftp_username:
+ sftp_username = _render_template_with_label(sftp_username, cache_key)
+ if sftp_password:
+ sftp_password = _render_template_with_label(sftp_password, cache_key)
+ if sftp_private_key:
+ sftp_private_key = _render_template_with_label(sftp_private_key, cache_key)
+ if sftp_private_key_passphrase:
+ sftp_private_key_passphrase = _render_template_with_label(sftp_private_key_passphrase, cache_key)
+ if sftp_remote_path:
+ sftp_remote_path = _render_template_with_label(sftp_remote_path, cache_key)
+ if sftp_host_key:
+ sftp_host_key = _render_template_with_label(sftp_host_key, cache_key)
+ if destination_prompt:
+ destination_prompt = _render_template_with_label(destination_prompt, cache_key)
+ if path:
+ path = _render_template_with_label(path, cache_key)
+
+ resolved_download_target = FileDownloadTarget(download_target)
+ destination_block_kwargs = {
+ "download_target": resolved_download_target,
+ "s3_bucket": s3_bucket,
+ "aws_access_key_id": aws_access_key_id,
+ "aws_secret_access_key": aws_secret_access_key,
+ "region_name": region_name,
+ "azure_storage_account_name": azure_storage_account_name,
+ "azure_storage_account_key": azure_storage_account_key,
+ "azure_blob_container_name": azure_blob_container_name,
+ "google_credential_id": google_credential_id,
+ "google_drive_folder_id": google_drive_folder_id,
+ "sftp_host": sftp_host,
+ "sftp_port": sftp_port,
+ "sftp_username": sftp_username,
+ "sftp_password": sftp_password,
+ "sftp_private_key": sftp_private_key,
+ "sftp_private_key_passphrase": sftp_private_key_passphrase,
+ "sftp_remote_path": sftp_remote_path,
+ "sftp_host_key": sftp_host_key,
+ "prompt": destination_prompt,
+ "path": path,
+ "continue_on_empty": continue_on_empty if continue_on_empty is not None else False,
+ }
cached_fn = script_run_context_manager.get_cached_fn(cache_key)
context: skyvern_context.SkyvernContext | None
if cache_key and cached_fn:
# Auto-create workflow block run and task if workflow_run_id is available
workflow_run_block_id, task_id, step_id = await _create_workflow_block_run_and_task(
block_type=BlockType.FILE_DOWNLOAD,
- prompt=prompt,
+ prompt=navigation_prompt,
url=url,
label=cache_key,
model=model,
created_by="script",
)
- prompt = _render_template_with_label(prompt, cache_key)
- # set the prompt in the RunContext
+ navigation_prompt = _render_template_with_label(navigation_prompt, cache_key)
context = skyvern_context.ensure_context()
- context.prompt = prompt
+ file_download_block: FileDownloadBlock | None = None
+ storage_type: FileStorageType | None = None
+ destination_delivery_started = False
+ if resolved_download_target != FileDownloadTarget.WEBSITE:
+ file_download_block = FileDownloadBlock.model_construct(
+ label=cache_key,
+ output_parameter=None,
+ **destination_block_kwargs,
+ )
+ storage_type = FileStorageType(resolved_download_target.value)
+ missing_parameters = file_download_block._validate_destination_fields(storage_type)
+ if missing_parameters:
+ failure_reason = f"Missing download destination values: {', '.join(missing_parameters)}"
+ LOG.error(
+ "Cached download destination configuration is invalid",
+ block_label=cache_key,
+ download_target=resolved_download_target,
+ missing_parameters=missing_parameters,
+ )
+ if workflow_run_block_id:
+ await _update_workflow_block(
+ workflow_run_block_id,
+ BlockStatus.failed,
+ task_id=task_id,
+ task_status=TaskStatus.failed,
+ step_id=step_id,
+ step_status=StepStatus.failed,
+ label=cache_key,
+ failure_reason=failure_reason,
+ )
+ _clear_cached_block_overrides(cache_key)
+ # Halt the cached script: run_script does not stop on a recorded failed status, so a
+ # plain return would let later generated statements run after this misconfiguration.
+ raise ScriptTerminationException(failure_reason)
+
+ async def dispatch_to_destination(files_to_upload: list[str]) -> None:
+ if file_download_block is None or storage_type is None:
+ return
+ if destination_prompt and destination_prompt.strip():
+ files_to_upload, _ = await FileDownloadBlock._select_files_to_upload_with_prompt(
+ file_download_block,
+ prompt=destination_prompt,
+ files_to_upload=files_to_upload,
+ workflow_run_block_id=workflow_run_block_id or "",
+ organization_id=context.organization_id,
+ )
+ if files_to_upload:
+ workflow_run_context = app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context(
+ context.workflow_run_id or ""
+ )
+ await file_download_block._dispatch_files_to_storage(
+ storage_type=storage_type,
+ files_to_upload=files_to_upload,
+ workflow_run_id=context.workflow_run_id or "",
+ workflow_run_block_id=workflow_run_block_id or "",
+ organization_id=context.organization_id,
+ workflow_run_context=workflow_run_context,
+ )
+
+ # set the prompt in the RunContext
+ context.prompt = navigation_prompt
+ download_run_id = resolve_run_download_id(context, fallback_run_id=context.workflow_run_id or "") or (
+ context.workflow_run_id or ""
+ )
try:
- await _prepare_cached_block_inputs(cache_key, prompt)
+ await _prepare_cached_block_inputs(cache_key, navigation_prompt)
# Count downloaded files before running cached function so we can
# verify that the download actually produced a new file.
org_id = context.organization_id or ""
- run_id = context.workflow_run_id or ""
+ # Use the resolved download run id for storage baseline/save/verify too, so they match
+ # the directory the browser actually writes to (the inherited parent for child runs).
+ run_id = download_run_id
files_before: list = []
files_before_ok = False
try:
@@ -2028,11 +2183,30 @@ async def download(
)
# Track local files before download for renaming with download_suffix
- local_download_dir = get_path_for_workflow_download_directory(run_id)
+ local_download_dir = get_path_for_workflow_download_directory(download_run_id)
local_files_before = list_files_in_directory(local_download_dir) if local_download_dir.exists() else []
+ local_file_signatures_before: dict[str, tuple[int, int]] = {}
+ for file_path in local_files_before:
+ try:
+ file_stat = Path(file_path).stat()
+ except OSError:
+ continue
+ local_file_signatures_before[file_path] = (file_stat.st_mtime_ns, file_stat.st_size)
+ newly_downloaded_files: list[str] = []
+ replaced_downloaded_files: list[str] = []
await _run_cached_function(cached_fn)
+ # Wait for any in-flight browser downloads (including multiple concurrent CDP
+ # downloads from a single click) to finish before snapshotting, matching the agent
+ # path. Returns immediately when nothing is downloading, so the fast single-file
+ # case keeps passing without added latency.
+ await check_downloading_files_and_wait_for_download_to_complete(
+ download_dir=local_download_dir,
+ organization_id=org_id,
+ browser_session_id=context.browser_session_id,
+ )
+
# Poll local filesystem for newly downloaded files.
#
# Two download mechanisms exist with different write patterns:
@@ -2064,13 +2238,21 @@ async def download(
_now = _loop.time()
_elapsed = _now - _poll_start
_local_files_now = list_files_in_directory(local_download_dir) if local_download_dir.exists() else []
- _new_files = set(_local_files_now) - set(local_files_before)
- _new_complete = [f for f in _new_files if not f.endswith(BROWSER_DOWNLOADING_SUFFIX)]
- _new_downloading = [f for f in _new_files if f.endswith(BROWSER_DOWNLOADING_SUFFIX)]
-
- # A complete file appeared — download succeeded
- if _new_complete:
- break
+ _new_files = [file_path for file_path in _local_files_now if file_path not in local_files_before]
+ _changed_files = []
+ for file_path in _local_files_now:
+ signature_before = local_file_signatures_before.get(file_path)
+ if signature_before is None:
+ continue
+ try:
+ file_stat = Path(file_path).stat()
+ except OSError:
+ continue
+ if (file_stat.st_mtime_ns, file_stat.st_size) != signature_before:
+ _changed_files.append(file_path)
+ _download_candidates = [*_new_files, *_changed_files]
+ _new_complete = [f for f in _download_candidates if not f.endswith(BROWSER_DOWNLOADING_SUFFIX)]
+ _new_downloading = [f for f in _download_candidates if f.endswith(BROWSER_DOWNLOADING_SUFFIX)]
# A .crdownload file exists — browser-native download in progress
if _new_downloading:
@@ -2091,6 +2273,12 @@ async def download(
await asyncio.sleep(_POLL_INTERVAL)
continue
+ # A complete file appeared — download succeeded
+ if _new_complete:
+ newly_downloaded_files = _new_complete
+ replaced_downloaded_files = [f for f in _changed_files if f in _new_complete]
+ break
+
# Download was detected earlier but .crdownload disappeared without a
# complete file replacing it (cancelled/failed). Use a shorter timeout
# measured from when the file vanished, not from poll start.
@@ -2127,8 +2315,9 @@ async def download(
# This matches the agent path ordering in agent.py.
if download_suffix and local_download_dir.exists():
local_files_after = list_files_in_directory(local_download_dir)
- new_files = list(set(local_files_after) - set(local_files_before))
- for file_path in new_files:
+ files_to_rename = [file_path for file_path in newly_downloaded_files if file_path in local_files_after]
+ newly_downloaded_files = []
+ for file_path in files_to_rename:
file_extension = Path(file_path).suffix
# Skip incomplete downloads
if file_extension == BROWSER_DOWNLOADING_SUFFIX:
@@ -2141,7 +2330,8 @@ async def download(
}
desired_name = download_filename_from_suffix(download_suffix, file_extension, existing_names)
if local_basename != desired_name:
- rename_file(file_path, desired_name)
+ file_path = rename_file(file_path, desired_name)
+ newly_downloaded_files.append(file_path)
# Upload downloaded files from local filesystem to remote storage
# so that get_downloaded_files() can find them for verification.
@@ -2187,19 +2377,28 @@ async def download(
organization_id=org_id,
workflow_run_id=run_id,
)
- if len(files_after) > len(files_before):
+ if replaced_downloaded_files or len(files_after) > len(files_before):
break
if _attempt < 2:
await asyncio.sleep(2)
# Only raise if all storage calls succeeded — if any timed out, skip
# the check to avoid spurious AI fallbacks under degraded storage.
- if files_before_ok and files_after_ok and len(files_after) <= len(files_before):
+ if (
+ files_before_ok
+ and files_after_ok
+ and len(files_after) <= len(files_before)
+ and not replaced_downloaded_files
+ ):
raise Exception(
"Cached download function did not produce a new file. "
f"Files before: {len(files_before)}, after: {len(files_after)}"
)
+ if file_download_block is not None and storage_type is not None:
+ destination_delivery_started = True
+ await dispatch_to_destination(newly_downloaded_files)
+
# Update block status to completed if workflow block was created
if workflow_run_block_id:
await _update_workflow_block(
@@ -2214,11 +2413,37 @@ async def download(
await _handle_script_termination(e, "download block", workflow_run_block_id, task_id, step_id, cache_key)
raise
except Exception as e:
+ if destination_delivery_started:
+ LOG.exception("Failed to deliver cached download to destination")
+ if workflow_run_block_id:
+ await _update_workflow_block(
+ workflow_run_block_id,
+ BlockStatus.failed,
+ task_id=task_id,
+ task_status=TaskStatus.failed,
+ step_id=step_id,
+ step_status=StepStatus.failed,
+ label=cache_key,
+ failure_reason=str(e),
+ )
+ raise
+
LOG.warning("Failed to run download block. Falling back to AI run.", exc_info=True)
+ fallback_download_dir = get_path_for_workflow_download_directory(download_run_id)
+ fallback_files_before = (
+ list_files_in_directory(fallback_download_dir) if fallback_download_dir.exists() else []
+ )
+ fallback_file_signatures_before: dict[str, tuple[int, int]] = {}
+ for file_path in fallback_files_before:
+ try:
+ file_stat = Path(file_path).stat()
+ except OSError:
+ continue
+ fallback_file_signatures_before[file_path] = (file_stat.st_mtime_ns, file_stat.st_size)
await _fallback_to_ai_run(
block_type=BlockType.FILE_DOWNLOAD,
cache_key=cache_key,
- prompt=prompt,
+ prompt=navigation_prompt,
url=url,
max_steps=max_steps,
complete_on_download=complete_on_download,
@@ -2227,6 +2452,57 @@ async def download(
workflow_run_block_id=workflow_run_block_id,
error_code_mapping=error_code_mapping,
)
+ if file_download_block is not None and storage_type is not None:
+ fallback_files_after = (
+ list_files_in_directory(fallback_download_dir) if fallback_download_dir.exists() else []
+ )
+ fallback_downloaded_files = []
+ for file_path in fallback_files_after:
+ signature_before = fallback_file_signatures_before.get(file_path)
+ try:
+ file_stat = Path(file_path).stat()
+ except OSError:
+ continue
+ if signature_before is None or (file_stat.st_mtime_ns, file_stat.st_size) != signature_before:
+ fallback_downloaded_files.append(file_path)
+
+ if not fallback_downloaded_files:
+ if file_download_block.continue_on_empty:
+ return
+ failure_reason = (
+ f"AI fallback completed without a scoped local download; nothing was sent to {storage_type}."
+ )
+ if workflow_run_block_id:
+ await _update_workflow_block(
+ workflow_run_block_id,
+ BlockStatus.failed,
+ task_id=task_id,
+ task_status=TaskStatus.failed,
+ step_id=step_id,
+ step_status=StepStatus.failed,
+ label=cache_key,
+ failure_reason=failure_reason,
+ ai_fallback_triggered=True,
+ )
+ raise CachedDownloadError(failure_reason)
+
+ try:
+ await dispatch_to_destination(fallback_downloaded_files)
+ except Exception as dispatch_error:
+ LOG.exception("Failed to deliver AI fallback download to destination")
+ if workflow_run_block_id:
+ await _update_workflow_block(
+ workflow_run_block_id,
+ BlockStatus.failed,
+ task_id=task_id,
+ task_status=TaskStatus.failed,
+ step_id=step_id,
+ step_status=StepStatus.failed,
+ label=cache_key,
+ failure_reason=str(dispatch_error),
+ ai_fallback_triggered=True,
+ )
+ raise
finally:
context.prompt = None
_clear_cached_block_overrides(cache_key)
@@ -2237,7 +2513,7 @@ async def download(
output_parameter=block_validation_output.output_parameter,
url=url,
complete_on_download=complete_on_download,
- navigation_goal=prompt,
+ navigation_goal=navigation_prompt,
max_steps_per_run=max_steps,
totp_identifier=totp_identifier,
totp_verification_url=totp_url,
@@ -2245,13 +2521,18 @@ async def download(
engine=RunEngine.skyvern_v1,
model=model,
download_suffix=download_suffix,
+ **destination_block_kwargs,
)
- await file_download_block.execute_safe(
+ download_result = await file_download_block.execute_safe(
workflow_run_id=block_validation_output.workflow_run_id,
parent_workflow_run_block_id=block_validation_output.context.parent_workflow_run_block_id,
organization_id=block_validation_output.organization_id,
browser_session_id=block_validation_output.browser_session_id,
)
+ if not download_result.success:
+ # Halt the script on a failed download/delivery instead of ignoring the result, matching
+ # the cached path; otherwise later generated statements would run after the failure.
+ raise ScriptTerminationException(download_result.failure_reason or "File download block failed")
async def action(
@@ -2727,6 +3008,18 @@ def _render_template_with_label(template: str, label: str | None = None) -> str:
template_data["current_item"] = block_reference_data["current_item"]
if "current_value" in block_reference_data:
template_data["current_value"] = block_reference_data["current_value"]
+ if "workflow_title" not in template_data:
+ template_data["workflow_title"] = workflow_run_context.workflow_title
+ if "workflow_id" not in template_data:
+ template_data["workflow_id"] = workflow_run_context.workflow_id
+ if "workflow_permanent_id" not in template_data:
+ template_data["workflow_permanent_id"] = workflow_run_context.workflow_permanent_id
+ if "workflow_run_id" not in template_data:
+ template_data["workflow_run_id"] = workflow_run_context.workflow_run_id
+ if "current_date" not in template_data:
+ template_data["current_date"] = datetime.now(timezone.utc).strftime(CURRENT_DATE_FORMAT)
+ if "browser_session_id" not in template_data:
+ template_data["browser_session_id"] = workflow_run_context.browser_session_id or ""
return render_template(template, data=template_data)
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index eb4e39a3b..9f19f2ba0 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -4882,84 +4882,17 @@ def generate_totp_value_with_task(task: Task, parameter: str) -> str:
async def _did_page_respond(
incremental_scraped: IncrementalScrapePage,
- frame: Page | Frame,
- original_url: str,
skyvern_frame: SkyvernFrame | None = None,
) -> bool:
try:
if skyvern_frame:
await skyvern_frame.safe_wait_for_animation_end(caller="page_respond")
- return frame.url != original_url or (await incremental_scraped.get_incremental_elements_num()) > 0
+ return (await incremental_scraped.get_incremental_elements_num()) > 0
except Exception:
LOG.debug("Failed to check incremental elements after click", exc_info=True)
return True
-async def _click_in_javascript_and_verify(
- action: ClickAction | UploadFileAction,
- page: Page,
- skyvern_element: SkyvernElement,
- incremental_scraped: IncrementalScrapePage,
- skyvern_frame: SkyvernFrame | None,
- *,
- anchor: str,
- no_response_msg: str,
-) -> ActionResult:
- try:
- frame = skyvern_frame.get_frame() if skyvern_frame else page
- original_url = frame.url
- await skyvern_element.click_in_javascript()
- if await _did_page_respond(incremental_scraped, frame, original_url, skyvern_frame):
- return ActionSuccess()
- LOG.info(
- "Chain click: JS click did not trigger a page response",
- action=action,
- element=str(skyvern_element),
- )
- return ActionFailure(FailToClick(action.element_id, anchor=anchor, msg=no_response_msg))
- except Exception as e:
- return ActionFailure(FailToClick(action.element_id, anchor=anchor, msg=str(e)))
-
-
-async def _is_likely_sibling_control(element: SkyvernElement, timeout: int) -> bool:
- try:
- metrics = await element.get_locator().evaluate(
- """(element) => {
- const rect = element.getBoundingClientRect();
- const root = document.documentElement;
- return {
- width: rect.width,
- height: rect.height,
- viewport_width: window.innerWidth || root.clientWidth || 0,
- viewport_height: window.innerHeight || root.clientHeight || 0,
- inside_modal: Boolean(element.closest(
- 'dialog,[role="dialog" i],[role="alertdialog" i],[aria-modal="true" i]'
- )),
- };
- }""",
- timeout=timeout,
- )
- except Exception:
- LOG.debug("Failed to classify blocking sibling", exc_info=True, element_id=element.get_id())
- return False
-
- if not isinstance(metrics, dict) or metrics.get("inside_modal") is not False:
- return False
- width = metrics.get("width")
- height = metrics.get("height")
- viewport_width = metrics.get("viewport_width")
- viewport_height = metrics.get("viewport_height")
- dimensions = (width, height, viewport_width, viewport_height)
- numeric_dimensions: list[float] = []
- for value in dimensions:
- if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
- return False
- numeric_dimensions.append(float(value))
- numeric_width, numeric_height, numeric_viewport_width, numeric_viewport_height = numeric_dimensions
- # ponytail: non-modal overlays are size-gated; add style/z-index signals if smaller overlays surface.
- return numeric_width < numeric_viewport_width / 2 and numeric_height < numeric_viewport_height / 2
-
-
def _get_click_count(action: ClickAction | UploadFileAction) -> int:
if isinstance(action, ClickAction):
return action.repeat
@@ -5176,46 +5109,6 @@ async def chain_click(
)
action_results.append(ActionSuccess())
return action_results
-
- # A non-anchor click (e.g. a primary form submit) blocked by an
- # untracked overlay (a consent / opt-out / FCRA modal over the
- # control): a coordinate click would land on whatever pixel is on
- # top — the overlay's own button — so dispatch on the intended
- # element instead (element.click() fires on the target node,
- # bypassing hit-testing and never touching the overlay). This
- # needs the observer to confirm the click landed; without one we
- # fail cleanly rather than guess, like the blocker path below.
- if (
- isinstance(action, ClickAction)
- and not action.file_url
- and not action.download
- and action.x is None
- and action.y is None
- and click_count == 1
- and incremental_scraped is not None
- and skyvern_element.get_tag_name() != InteractiveElement.A
- ):
- LOG.info(
- "Chain click: click blocked by an untracked overlay; dispatching on the intended element "
- "instead of coordinate-clicking into the overlay",
- action=action,
- element=str(skyvern_element),
- locator=locator,
- )
- action_results.append(
- await _click_in_javascript_and_verify(
- action,
- page,
- skyvern_element,
- incremental_scraped,
- skyvern_frame,
- anchor="overlay_blocked",
- no_response_msg=(
- "click blocked by overlay; no page response after intended-element dispatch"
- ),
- )
- )
- return action_results
else:
# Element is visible and elementFromPoint returns the target itself,
# but Playwright's click still failed (e.g. element transiently
@@ -5259,11 +5152,9 @@ async def chain_click(
element=str(blocking_element),
locator=locator,
)
- target_handler = await skyvern_element.get_element_handler()
- if await blocking_element.is_parent_of(target_handler) or (
- await blocking_element.is_sibling_of(target_handler)
- and (incremental_scraped is None or await _is_likely_sibling_control(blocking_element, timeout))
- ):
+ if await blocking_element.is_parent_of(
+ await skyvern_element.get_element_handler()
+ ) or await blocking_element.is_sibling_of(await skyvern_element.get_element_handler()):
LOG.info(
"Chain click: element is blocked by other elements, going to click on the blocking element",
action=action,
@@ -5285,23 +5176,28 @@ async def chain_click(
# JS click dispatches directly on the DOM node, bypassing hit-testing.
LOG.info(
- "Chain click: blocker is not a safe retarget, trying JS click on original element",
+ "Chain click: blocker is not parent/sibling, trying JS click on original element",
action=action,
element=str(skyvern_element),
locator=locator,
)
- action_results.append(
- await _click_in_javascript_and_verify(
- action,
- page,
- skyvern_element,
- incremental_scraped,
- skyvern_frame,
- anchor="self_js",
- no_response_msg="no page response after click",
+ try:
+ await skyvern_element.click_in_javascript()
+ if await _did_page_respond(incremental_scraped, skyvern_frame):
+ action_results.append(ActionSuccess())
+ return action_results
+ LOG.info(
+ "Chain click: JS click did not trigger a page response",
+ action=action,
+ element=str(skyvern_element),
)
- )
- return action_results
+ action_results.append(
+ ActionFailure(FailToClick(action.element_id, anchor="self_js", msg="no page response after click"))
+ )
+ return action_results
+ except Exception as e:
+ action_results.append(ActionFailure(FailToClick(action.element_id, anchor="self_js", msg=str(e))))
+ return action_results
finally:
click_succeeded = any(isinstance(r, ActionSuccess) for r in action_results)
diff --git a/tests/unit/copilot_test_helpers.py b/tests/unit/copilot_test_helpers.py
index ed65a2849..1eb121172 100644
--- a/tests/unit/copilot_test_helpers.py
+++ b/tests/unit/copilot_test_helpers.py
@@ -175,6 +175,7 @@ def make_completion_criterion(
expected_output_value: str | None = None,
expected_output_shape: str | None = None,
requested_output_evidence_source: str = "runtime_output",
+ requested_output_path_mint_source: str | None = None,
classification_output_key: str | None = None,
expected_classification: str | bool | None = None,
requested_output_corroborator: bool = False,
@@ -194,6 +195,7 @@ def make_completion_criterion(
expected_output_value=expected_output_value,
expected_output_shape=expected_output_shape, # type: ignore[arg-type]
requested_output_evidence_source=requested_output_evidence_source, # type: ignore[arg-type]
+ requested_output_path_mint_source=requested_output_path_mint_source, # type: ignore[arg-type]
classification_output_key=classification_output_key,
expected_classification=expected_classification,
requested_output_corroborator=requested_output_corroborator,
diff --git a/tests/unit/forge/sdk/db/test_self_heal_schema.py b/tests/unit/forge/sdk/db/test_self_heal_schema.py
index 34a0b3206..8d17a4510 100644
--- a/tests/unit/forge/sdk/db/test_self_heal_schema.py
+++ b/tests/unit/forge/sdk/db/test_self_heal_schema.py
@@ -52,7 +52,7 @@ def test_heal_migration_chains_from_current_head() -> None:
script = ScriptDirectory.from_config(config)
heads = script.get_heads()
- assert heads == ["2b8e37d98d97"]
+ assert len(heads) == 1
revision = script.get_revision("2b8e37d98d97")
assert revision is not None
@@ -60,6 +60,10 @@ def test_heal_migration_chains_from_current_head() -> None:
# assert the parent resolves to a real revision instead of pinning a specific hash.
assert revision.down_revision is not None
assert script.get_revision(revision.down_revision) is not None
+ # The heal migration must be part of the single linear history, not pinned as the tip:
+ # later migrations stack on top of it.
+ ancestors = {rev.revision for rev in script.walk_revisions(base="base", head=heads[0])}
+ assert "2b8e37d98d97" in ancestors
def _episode(
diff --git a/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.py b/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.py
index cda7f3520..7295f3a80 100644
--- a/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.py
+++ b/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.py
@@ -11,6 +11,7 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
+from playwright._impl._errors import TargetClosedError
from skyvern.forge.sdk.routes.streaming.channels.exfiltration import (
ExfiltratedEventSource,
@@ -284,6 +285,36 @@ class TestExfiltrationChannelEvents:
await asyncio.sleep(0.1)
assert len(events) == 1
+ @pytest.mark.asyncio
+ async def test_stop_survives_closed_page_during_undecorate(self) -> None:
+ """SKY-12366: a closed browser target must not crash channel teardown.
+
+ In production the browser target churns mid-recording (take-control toggles,
+ navigations, bot-detection pages), so when stop() calls undecorate() on a page
+ whose target is already gone, page.add_init_script raises TargetClosedError.
+ That must be swallowed: otherwise it propagates out of stop() -> handle_data ->
+ the message-channel loop and tears down the whole recording pipeline, which is
+ what dropped users' clicks/typing and produced empty workflows.
+ """
+ channel, _ = _make_channel()
+
+ closed_page = _make_page(url="https://example.com")
+ closed_page.add_init_script = AsyncMock(
+ side_effect=TargetClosedError("Page.add_init_script: Target page, context or browser has been closed")
+ )
+
+ browser_context = MagicMock()
+ browser_context.pages = [closed_page]
+ channel.browser_context = browser_context
+
+ # Must not raise: TargetClosedError from undecorate() would otherwise escape
+ # stop() -> handle_data -> the message-channel loop.
+ result = await channel.stop()
+
+ assert result is channel
+ # The undecorate path genuinely ran and hit the closed-target error.
+ closed_page.add_init_script.assert_awaited()
+
@pytest.mark.asyncio
async def test_exfiltrate_rearms_existing_page_without_duplicate_listeners(self) -> None:
channel, _ = _make_channel()
diff --git a/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.py b/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.py
new file mode 100644
index 000000000..07aab9214
--- /dev/null
+++ b/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.py
@@ -0,0 +1,223 @@
+"""Message-channel resilience when the recorded browser target goes away (SKY-12366).
+
+Production showed two crash shapes with the same engine: a recording message handler
+touches a browser whose target is gone, the exception escapes ``handle_data``, and the
+whole websocket loop dies. The frontend auto-reconnects and re-sends the recording
+messages, producing a crash-loop with zero capture:
+
+- ``BEGIN_EXFILTRATION`` -> ``ExfiltrationChannel.start()`` -> ``connect_over_cdp`` ->
+ ``ECONNREFUSED`` / 502 (customer sessions, ~0.3s crash-loop, no drafts at all).
+- ``END_EXFILTRATION`` -> ``ExfiltrationChannel.stop()`` -> ``TargetClosedError``
+ (internal repro sessions), which also skipped the interpretation-session flush.
+
+These tests drive the real ``loop_stream_messages`` with a scripted websocket and
+assert the loop survives handler failures, surfaces them as ``MessageOutError``, and
+never skips the draft flush or the channel close.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastapi import WebSocketDisconnect
+from playwright._impl._errors import Error as PlaywrightError
+from starlette.websockets import WebSocketState
+
+from skyvern.forge.sdk.routes.streaming.channels import message as message_module
+from skyvern.forge.sdk.routes.streaming.channels.message import MessageKind, MessageOutError, loop_stream_messages
+
+PBS_ID = "pbs_123"
+WP_ID = "wpid_123"
+
+BEGIN_EXFILTRATION_DATA = {
+ "kind": MessageKind.BEGIN_EXFILTRATION.value,
+ "workflow_permanent_id": WP_ID,
+ "live_interpretation_enabled": True,
+ "recording_attempt_id": "attempt-1",
+}
+END_EXFILTRATION_DATA = {"kind": MessageKind.END_EXFILTRATION.value}
+RECORDING_REARM_CAPTURE_DATA = {"kind": MessageKind.RECORDING_REARM_CAPTURE.value}
+
+
+def _message_channel(receive_sequence: list[object]) -> MagicMock:
+ """A MessageChannel double whose websocket replays ``receive_sequence``."""
+ message_channel = MagicMock()
+ message_channel.class_name = "MessageChannel"
+ message_channel.identity = {}
+ message_channel.is_open = True
+ message_channel.client_id = "client-1"
+ message_channel.organization_id = "org_123"
+ message_channel.browser_session = MagicMock(persistent_browser_session_id=PBS_ID)
+ message_channel.websocket.receive_json = AsyncMock(side_effect=receive_sequence)
+ message_channel.websocket.client_state = WebSocketState.CONNECTED
+ # backend_to_frontend blocks on a real (empty) queue until cancelled at teardown.
+ message_channel.out_queue = asyncio.Queue()
+ message_channel.send_nowait = MagicMock()
+ message_channel.close = AsyncMock()
+ return message_channel
+
+
+def _sent_error_kinds(message_channel: MagicMock) -> list[str]:
+ kinds: list[str] = []
+ for call in message_channel.send_nowait.call_args_list:
+ for sent in call.kwargs.get("messages", []):
+ if isinstance(sent, MessageOutError):
+ kinds.append(sent.failed_kind)
+ return kinds
+
+
+def _install_recording_doubles(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ channel: object,
+) -> MagicMock:
+ """Stub the vnc registry, exfiltration channel factory, and interpretation registry."""
+ monkeypatch.setattr(message_module, "get_vnc_channel", lambda _client_id: MagicMock())
+ monkeypatch.setattr(message_module, "ExfiltrationChannel", MagicMock(return_value=channel))
+
+ registry = MagicMock()
+ registry.start_session = MagicMock()
+ registry.ingest_events = MagicMock()
+ registry.stop_session = AsyncMock(return_value=[])
+ monkeypatch.setattr(message_module, "interpretation_registry", registry)
+ return registry
+
+
+def _started_channel(*, stop_error: Exception | None = None) -> MagicMock:
+ channel = MagicMock()
+ channel.start = AsyncMock(return_value=channel)
+ channel.stop = AsyncMock(side_effect=stop_error) if stop_error else AsyncMock(return_value=channel)
+ channel.rearm_all_pages = AsyncMock()
+ return channel
+
+
+async def test_begin_exfiltration_start_failure_does_not_kill_message_loop(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A dead browser target on recording start must not tear down the websocket loop.
+
+ Mirrors the customer crash-loop: ``connect_over_cdp`` fails (ECONNREFUSED / 502),
+ and before the fix the error escaped ``handle_data`` and killed the loop, so the
+ frontend reconnected and re-sent begin-exfiltration forever.
+ """
+ channel = MagicMock()
+ channel.start = AsyncMock(
+ side_effect=PlaywrightError("BrowserType.connect_over_cdp: connect ECONNREFUSED 127.0.0.1:9222")
+ )
+ channel.stop = AsyncMock()
+
+ message_channel = _message_channel(
+ [BEGIN_EXFILTRATION_DATA, END_EXFILTRATION_DATA, WebSocketDisconnect()],
+ )
+ _install_recording_doubles(monkeypatch, channel=channel)
+
+ await loop_stream_messages(message_channel)
+
+ # The loop consumed every scripted frame instead of dying on the first one.
+ assert message_channel.websocket.receive_json.await_count == 3
+ # The failure was surfaced to the frontend rather than swallowed silently.
+ assert MessageKind.BEGIN_EXFILTRATION.value in _sent_error_kinds(message_channel)
+
+
+async def test_end_exfiltration_stop_failure_still_flushes_interpretation_session(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A failing channel stop must not skip the draft flush (message.py END_EXFILTRATION).
+
+ Mirrors the internal repro: ``stop()`` raised ``TargetClosedError`` and the
+ interpretation session was never flushed, so the recording's drafts were lost.
+ """
+ channel = _started_channel(
+ stop_error=PlaywrightError("Page.add_init_script: Target page, context or browser has been closed")
+ )
+ message_channel = _message_channel(
+ [BEGIN_EXFILTRATION_DATA, END_EXFILTRATION_DATA, WebSocketDisconnect()],
+ )
+ registry = _install_recording_doubles(monkeypatch, channel=channel)
+
+ await loop_stream_messages(message_channel)
+
+ assert message_channel.websocket.receive_json.await_count == 3
+ registry.stop_session.assert_awaited_once_with(PBS_ID)
+
+
+async def test_teardown_stop_failure_still_closes_message_channel(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A failing channel stop during loop teardown must not skip the websocket close."""
+ channel = _started_channel(stop_error=RuntimeError("browser went away mid-recording"))
+ # Disconnect while the recording is still active: teardown stops the channel.
+ message_channel = _message_channel([BEGIN_EXFILTRATION_DATA, WebSocketDisconnect()])
+ _install_recording_doubles(monkeypatch, channel=channel)
+
+ await loop_stream_messages(message_channel)
+
+ channel.stop.assert_awaited()
+ message_channel.close.assert_awaited_once()
+
+
+async def test_rearm_capture_failure_does_not_kill_message_loop(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A failing re-arm on an active recording must not tear down the websocket loop."""
+ channel = _started_channel()
+ channel.rearm_all_pages = AsyncMock(side_effect=RuntimeError("browser went away mid-recording"))
+
+ message_channel = _message_channel(
+ [BEGIN_EXFILTRATION_DATA, RECORDING_REARM_CAPTURE_DATA, END_EXFILTRATION_DATA, WebSocketDisconnect()],
+ )
+ registry = _install_recording_doubles(monkeypatch, channel=channel)
+
+ await loop_stream_messages(message_channel)
+
+ assert message_channel.websocket.receive_json.await_count == 4
+ assert MessageKind.RECORDING_REARM_CAPTURE.value in _sent_error_kinds(message_channel)
+ # The recording still finishes cleanly afterwards.
+ registry.stop_session.assert_awaited_once_with(PBS_ID)
+
+
+async def test_reconnect_rearm_failure_does_not_kill_message_loop(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A failing re-arm on a repeated begin-exfiltration (reconnect) must not kill the loop."""
+ channel = _started_channel()
+ channel.rearm_all_pages = AsyncMock(side_effect=RuntimeError("browser went away mid-recording"))
+
+ # The second begin-exfiltration hits the existing-channel branch, which re-arms.
+ message_channel = _message_channel(
+ [BEGIN_EXFILTRATION_DATA, BEGIN_EXFILTRATION_DATA, END_EXFILTRATION_DATA, WebSocketDisconnect()],
+ )
+ registry = _install_recording_doubles(monkeypatch, channel=channel)
+
+ await loop_stream_messages(message_channel)
+
+ assert message_channel.websocket.receive_json.await_count == 4
+ assert MessageKind.BEGIN_EXFILTRATION.value in _sent_error_kinds(message_channel)
+ registry.stop_session.assert_awaited_once_with(PBS_ID)
+
+
+async def test_recording_round_trip_still_works_when_target_is_healthy(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Guardrails must not change the happy path: start, stop, flush, close."""
+ channel = _started_channel()
+ message_channel = _message_channel(
+ [BEGIN_EXFILTRATION_DATA, END_EXFILTRATION_DATA, WebSocketDisconnect()],
+ )
+ registry = _install_recording_doubles(monkeypatch, channel=channel)
+
+ await loop_stream_messages(message_channel)
+
+ channel.start.assert_awaited_once()
+ channel.stop.assert_awaited_once()
+ registry.stop_session.assert_awaited_once_with(PBS_ID)
+ assert _sent_error_kinds(message_channel) == []
+ message_channel.close.assert_awaited_once()
diff --git a/tests/unit/test_backfill_encrypt_file_block_secrets.py b/tests/unit/test_backfill_encrypt_file_block_secrets.py
new file mode 100644
index 000000000..a72b42a89
--- /dev/null
+++ b/tests/unit/test_backfill_encrypt_file_block_secrets.py
@@ -0,0 +1,216 @@
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, call
+
+import pytest
+
+import scripts.backfill_encrypt_file_block_secrets as backfill
+from scripts.backfill_encrypt_file_block_secrets import _non_deleted_workflows_query, encrypt_file_block_secrets
+from skyvern.config import settings
+from skyvern.forge.sdk.db.models import WorkflowModel
+from skyvern.forge.sdk.workflow.secret_encryption import decrypt_secret_field_value, is_encrypted_secret
+
+
+def enabled_encryption(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "ENABLE_ENCRYPTION", True)
+ monkeypatch.setattr(settings, "ENCRYPTOR_AES_SECRET_KEY", "unit-test-secret-key-please-0000")
+ monkeypatch.setattr(settings, "ENCRYPTOR_AES_SALT", "unit-test-salt-000")
+
+
+class _ScalarResult:
+ def __init__(self, workflows: list[Any]) -> None:
+ self.workflows = workflows
+
+ def all(self) -> list[Any]:
+ return self.workflows
+
+
+class _FakeSession:
+ def __init__(self, workflows: list[Any], events: list[str]) -> None:
+ self.workflows = workflows
+ self.events = events
+ self.added: list[Any] = []
+ self.commit = AsyncMock(side_effect=self._record_commit)
+ self.rollback = AsyncMock()
+
+ def _record_commit(self) -> None:
+ self.events.append("commit")
+
+ async def __aenter__(self) -> "_FakeSession":
+ return self
+
+ async def __aexit__(self, *_args: Any) -> None:
+ self.events.append("exit")
+
+ async def scalars(self, _query: Any) -> _ScalarResult:
+ return _ScalarResult(self.workflows)
+
+ def add(self, workflow: Any) -> None:
+ self.added.append(workflow)
+
+
+class _FakeSessionFactory:
+ def __init__(self, batches: list[list[Any]], events: list[str]) -> None:
+ self.sessions = [_FakeSession(batch, events) for batch in batches]
+ self._remaining_sessions = iter(self.sessions)
+
+ def __call__(self) -> _FakeSession:
+ return next(self._remaining_sessions)
+
+
+def _workflow(workflow_permanent_id: str, secret: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ organization_id="o_test",
+ workflow_permanent_id=workflow_permanent_id,
+ workflow_definition={"blocks": [{"block_type": "file_download", "sftp_password": secret}]},
+ )
+
+
+def _install_fake_database(
+ monkeypatch: pytest.MonkeyPatch,
+ workflows: list[Any],
+ delete_cached_scripts: AsyncMock,
+ events: list[str],
+) -> _FakeSessionFactory:
+ session_factory = _FakeSessionFactory([workflows, []], events)
+ database = SimpleNamespace(
+ Session=session_factory,
+ scripts=SimpleNamespace(delete_workflow_scripts_by_permanent_id=delete_cached_scripts),
+ )
+ monkeypatch.setattr(backfill.app, "DATABASE", database)
+ monkeypatch.setattr(backfill, "flag_modified", lambda *_args: None)
+ return session_factory
+
+
+async def test_encrypt_file_block_secrets_transforms_literals_and_is_idempotent(
+ enabled_encryption: None,
+) -> None:
+ workflow_definition: dict[str, Any] = {
+ "blocks": [
+ {
+ "block_type": "file_upload",
+ "aws_secret_access_key": "upload-literal-secret",
+ "sftp_password": "{{ sftp_password }}",
+ },
+ {
+ "block_type": "for_loop",
+ "loop_blocks": [
+ {
+ "block_type": "file_download",
+ "azure_storage_account_key": "nested-literal-secret",
+ }
+ ],
+ },
+ {
+ "block_type": "text_prompt",
+ "sftp_password": "non-file-literal-secret",
+ },
+ ]
+ }
+
+ transformed, fields_encrypted = await encrypt_file_block_secrets(workflow_definition, "o_test")
+
+ upload = transformed["blocks"][0]
+ nested_download = transformed["blocks"][1]["loop_blocks"][0]
+ non_file = transformed["blocks"][2]
+ assert fields_encrypted == 2
+ assert is_encrypted_secret(upload["aws_secret_access_key"])
+ assert upload["sftp_password"] == "{{ sftp_password }}"
+ assert is_encrypted_secret(nested_download["azure_storage_account_key"])
+ assert (
+ await decrypt_secret_field_value(
+ upload["aws_secret_access_key"], organization_id="o_test", field_name="aws_secret_access_key"
+ )
+ == "upload-literal-secret"
+ )
+ assert (
+ await decrypt_secret_field_value(
+ nested_download["azure_storage_account_key"],
+ organization_id="o_test",
+ field_name="azure_storage_account_key",
+ )
+ == "nested-literal-secret"
+ )
+ assert non_file["sftp_password"] == "non-file-literal-secret"
+ assert workflow_definition["blocks"][0]["aws_secret_access_key"] == "upload-literal-secret"
+ assert workflow_definition["blocks"][1]["loop_blocks"][0]["azure_storage_account_key"] == ("nested-literal-secret")
+
+ rerun, rerun_fields_encrypted = await encrypt_file_block_secrets(transformed, "o_test")
+
+ assert rerun_fields_encrypted == 0
+ assert rerun == transformed
+
+
+def test_non_deleted_workflows_query_processes_all_versions_in_batches() -> None:
+ query = _non_deleted_workflows_query(offset=200)
+ compiled = str(query.compile(compile_kwargs={"literal_binds": True}))
+
+ assert "workflows.deleted_at IS NULL" in compiled
+ assert "max(" not in compiled.lower()
+ assert "group by" not in compiled.lower()
+ assert query._limit_clause is not None
+ assert query._offset_clause is not None
+ assert query._limit_clause.value == 100
+ assert query._offset_clause.value == 200
+ assert list(query._order_by_clauses) == [
+ WorkflowModel.workflow_permanent_id,
+ WorkflowModel.version,
+ WorkflowModel.workflow_id,
+ ]
+
+
+async def test_main_invalidates_cached_scripts_once_per_modified_wpid_before_commit(
+ monkeypatch: pytest.MonkeyPatch,
+ enabled_encryption: None,
+) -> None:
+ events: list[str] = []
+
+ async def record_delete(*, organization_id: str, workflow_permanent_id: str) -> int:
+ events.append(f"delete:{workflow_permanent_id}")
+ return 1
+
+ delete_cached_scripts = AsyncMock(side_effect=record_delete)
+ sessions = _install_fake_database(
+ monkeypatch,
+ [
+ _workflow("wp_one", "first-secret"),
+ _workflow("wp_one", "second-secret"),
+ _workflow("wp_two", "third-secret"),
+ ],
+ delete_cached_scripts,
+ events,
+ )
+ monkeypatch.setattr(backfill, "_parse_args", lambda: SimpleNamespace(dry_run=False))
+
+ await backfill.main()
+
+ assert delete_cached_scripts.await_args_list == [
+ call(organization_id="o_test", workflow_permanent_id="wp_one"),
+ call(organization_id="o_test", workflow_permanent_id="wp_two"),
+ ]
+ sessions.sessions[0].commit.assert_awaited_once_with()
+ assert events == ["delete:wp_one", "delete:wp_two", "commit", "exit", "exit"]
+
+
+async def test_main_dry_run_does_not_invalidate_cached_scripts(
+ monkeypatch: pytest.MonkeyPatch,
+ enabled_encryption: None,
+) -> None:
+ events: list[str] = []
+ delete_cached_scripts = AsyncMock()
+ sessions = _install_fake_database(
+ monkeypatch,
+ [_workflow("wp_dry_run", "dry-run-secret")],
+ delete_cached_scripts,
+ events,
+ )
+ monkeypatch.setattr(backfill, "_parse_args", lambda: SimpleNamespace(dry_run=True))
+
+ await backfill.main()
+
+ delete_cached_scripts.assert_not_awaited()
+ sessions.sessions[0].commit.assert_not_awaited()
diff --git a/tests/unit/test_browser_recording_interpretation.py b/tests/unit/test_browser_recording_interpretation.py
index 2dc7eaadf..ab6085a0f 100644
--- a/tests/unit/test_browser_recording_interpretation.py
+++ b/tests/unit/test_browser_recording_interpretation.py
@@ -613,7 +613,14 @@ def test_start_session_same_recording_attempt_id_reuses_session() -> None:
assert registry._sessions[PBS_ID].session_revision == 5
-def test_start_session_new_recording_attempt_id_forces_fresh_session() -> None:
+def test_start_session_new_recording_attempt_id_continues_unfinished_session() -> None:
+ """SKY-12429: a new attempt id on an unfinished recording continues it.
+
+ The client mints the attempt id per recording and keeps it stable across
+ reconnects, so a different id on the same unfinished session means the client
+ lost its in-memory state (e.g. page reload). The accumulated drafts must be
+ carried forward and resynced to the reconnecting client, not wiped.
+ """
from skyvern.services.browser_recording.session_registry import RecordingInterpretationSessionRegistry
registry = RecordingInterpretationSessionRegistry()
@@ -624,9 +631,51 @@ def test_start_session_new_recording_attempt_id_forces_fresh_session() -> None:
on_update=lambda _: None,
recording_attempt_id="attempt-1",
)
- stale = registry._sessions[PBS_ID]
- stale.session_revision = 42
- stale.steps = [
+ session = registry._sessions[PBS_ID]
+ session.session_revision = 42
+ session.steps = [
+ RecordingDraftStep(
+ step_id="step-1",
+ action_kind=ActionKind.CLICK,
+ block_type="action",
+ label="click_submit",
+ )
+ ]
+
+ resynced: list[RecordingInterpretationUpdate] = []
+ registry.start_session(
+ browser_session_id=PBS_ID,
+ organization_id=ORG_ID,
+ workflow_permanent_id=WP_ID,
+ on_update=resynced.append,
+ recording_attempt_id="attempt-2",
+ )
+
+ # Same session, drafts intact, the new attempt id adopted, and the
+ # reconnecting client resynced with the accumulated steps.
+ continued = registry._sessions[PBS_ID]
+ assert continued is session
+ assert continued.recording_attempt_id == "attempt-2"
+ assert [s.step_id for s in continued.steps] == ["step-1"]
+ assert resynced and [s.step_id for s in resynced[-1].steps] == ["step-1"]
+
+
+def test_start_session_after_finalized_recording_starts_fresh() -> None:
+ """Done/Discard finalize and pop the session; a lingering finalized session
+ must not leak its steps into the next recording."""
+ from skyvern.services.browser_recording.session_registry import RecordingInterpretationSessionRegistry
+
+ registry = RecordingInterpretationSessionRegistry()
+ registry.start_session(
+ browser_session_id=PBS_ID,
+ organization_id=ORG_ID,
+ workflow_permanent_id=WP_ID,
+ on_update=lambda _: None,
+ recording_attempt_id="attempt-1",
+ )
+ finalized = registry._sessions[PBS_ID]
+ finalized.finalized = True
+ finalized.steps = [
RecordingDraftStep(
step_id="step-1",
action_kind=ActionKind.CLICK,
@@ -643,12 +692,8 @@ def test_start_session_new_recording_attempt_id_forces_fresh_session() -> None:
recording_attempt_id="attempt-2",
)
- # A new recording gets a fresh session: not the stale object, revision reset,
- # no carried-over steps.
fresh = registry._sessions[PBS_ID]
- assert fresh is not stale
- assert fresh.recording_attempt_id == "attempt-2"
- assert fresh.session_revision == 0
+ assert fresh is not finalized
assert fresh.steps == []
@@ -743,3 +788,83 @@ async def test_resume_capture_emits_resync_snapshot(monkeypatch: pytest.MonkeyPa
assert len(updates) == 1
assert updates[0].is_snapshot is True
session.cancel()
+
+
+async def test_new_attempt_id_mid_recording_continues_session_and_keeps_drafts(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """SKY-12429: a reconnect with a new attempt id continues the same recording.
+
+ The client only presents a different recording_attempt_id for an unfinished
+ recording when it lost its in-memory state (e.g. page reload). The registry
+ must continue the populated session: resync the panel with the accumulated
+ drafts instead of blanking it, keep interpreting new events, and let the
+ finished recording build blocks from everything captured.
+ """
+ from skyvern.services.browser_recording.session_registry import RecordingInterpretationSessionRegistry
+
+ async def fake_llm(*args: object, **kwargs: object) -> dict[str, object]:
+ return {"block_label": "click_submit", "title": "Click Submit", "prompt": "Click the submit button."}
+
+ monkeypatch.setattr(app, "LLM_API_HANDLER", fake_llm)
+
+ registry = RecordingInterpretationSessionRegistry()
+ panel: list[RecordingInterpretationUpdate] = []
+
+ # Attempt 1: the user interacts and drafts accumulate.
+ registry.start_session(
+ browser_session_id=PBS_ID,
+ organization_id=ORG_ID,
+ workflow_permanent_id=WP_ID,
+ on_update=panel.append,
+ recording_attempt_id="attempt-1",
+ )
+ session_one = registry._sessions[PBS_ID]
+ registry.ingest_events(
+ PBS_ID,
+ [
+ _click_streaming_event(timestamp=1000.0, capture_seq=0, sky_id="sky-a", target_id="a"),
+ _click_streaming_event(timestamp=1010.0, capture_seq=1, sky_id="sky-b", target_id="b"),
+ ],
+ )
+ await session_one._interpret(finalized=False)
+
+ # The panel shows those drafts (full snapshot with a non-empty step list).
+ populated_snapshots = [u for u in panel if u.is_snapshot and u.steps]
+ assert populated_snapshots, "expected the panel to display the interpreted drafts"
+ accumulated_step_count = len(session_one.steps)
+ assert accumulated_step_count >= 1
+
+ # A reconnect arrives with a NEW attempt id (same browser session, not finalized).
+ panel.clear()
+ registry.start_session(
+ browser_session_id=PBS_ID,
+ organization_id=ORG_ID,
+ workflow_permanent_id=WP_ID,
+ on_update=panel.append,
+ recording_attempt_id="attempt-2",
+ )
+ session_two = registry._sessions[PBS_ID]
+
+ # The recording continues: same session, drafts intact, new attempt id adopted,
+ # and the reconnecting client immediately resynced with the accumulated steps.
+ assert session_two is session_one
+ assert len(session_two.steps) == accumulated_step_count
+ assert session_two.recording_attempt_id == "attempt-2"
+ assert panel and panel[-1].is_snapshot and len(panel[-1].steps) == accumulated_step_count
+
+ # New interactions after the reconnect keep extending the same draft list.
+ registry.ingest_events(
+ PBS_ID,
+ [_click_streaming_event(timestamp=2000.0, capture_seq=2, sky_id="sky-c", target_id="c")],
+ )
+ await session_two._interpret(finalized=False)
+ assert len(session_two.steps) > accumulated_step_count
+
+ # Finishing builds blocks from everything captured across the reconnect.
+ processor = Processor(PBS_ID, ORG_ID, WP_ID)
+ blocks = processor.drafts_to_blocks(session_two.steps)
+ assert len(blocks) == len(session_two.steps)
+
+ registry.discard_session(PBS_ID)
diff --git a/tests/unit/test_cached_download_s3_upload.py b/tests/unit/test_cached_download_s3_upload.py
index 84e157cdd..55c68641d 100644
--- a/tests/unit/test_cached_download_s3_upload.py
+++ b/tests/unit/test_cached_download_s3_upload.py
@@ -11,6 +11,8 @@ Validates that the cached download flow:
from __future__ import annotations
import asyncio
+from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -38,6 +40,8 @@ def mock_context():
ctx = MagicMock()
ctx.organization_id = "o_test_org"
ctx.workflow_run_id = "wr_test_run"
+ ctx.browser_session_id = None
+ ctx.run_id = ctx.workflow_run_id
ctx.prompt = None
return ctx
@@ -67,6 +71,9 @@ def setup(mock_context, tmp_path):
fallback_mock = AsyncMock()
update_block_mock = AsyncMock()
+ run_cached_mock = AsyncMock()
+ wait_downloads_mock = AsyncMock()
+ get_download_dir_mock = MagicMock(return_value=download_dir)
all_patches = [
patch(f"{MODULE}.app", mock_app),
@@ -79,11 +86,12 @@ def setup(mock_context, tmp_path):
patch(f"{MODULE}._render_template_with_label", side_effect=lambda p, _: p),
patch(f"{MODULE}.skyvern_context.ensure_context", return_value=mock_context),
patch(f"{MODULE}._prepare_cached_block_inputs", new_callable=AsyncMock),
- patch(f"{MODULE}._run_cached_function", new_callable=AsyncMock),
+ patch(f"{MODULE}._run_cached_function", new=run_cached_mock),
patch(f"{MODULE}._update_workflow_block", update_block_mock),
patch(f"{MODULE}._fallback_to_ai_run", fallback_mock),
patch(f"{MODULE}._clear_cached_block_overrides"),
- patch(f"{MODULE}.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch(f"{MODULE}.check_downloading_files_and_wait_for_download_to_complete", new=wait_downloads_mock),
+ patch(f"{MODULE}.get_path_for_workflow_download_directory", new=get_download_dir_mock),
patch(f"{MODULE}.list_files_in_directory", side_effect=list_side),
patch(f"{MODULE}.rename_file", rename),
]
@@ -99,6 +107,9 @@ def setup(mock_context, tmp_path):
"fallback": fallback_mock,
"update_block": update_block_mock,
"rename": rename,
+ "run_cached": run_cached_mock,
+ "wait_downloads": wait_downloads_mock,
+ "get_download_dir": get_download_dir_mock,
}
return _setup
@@ -109,6 +120,30 @@ def _cleanup(refs):
p.stop()
+def test_render_template_with_label_injects_workflow_run_id():
+ context = SimpleNamespace(workflow_run_id="wr_cached_run", script_run_parameters={}, loop_metadata=None)
+ workflow_run_context = SimpleNamespace(
+ values={},
+ workflow_title="Cached workflow",
+ workflow_id="wf_cached",
+ workflow_permanent_id="wpid_cached",
+ workflow_run_id="wr_cached_run",
+ browser_session_id=None,
+ )
+ mock_app = MagicMock()
+ mock_app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context.return_value = workflow_run_context
+
+ with (
+ patch(f"{MODULE}.app", mock_app),
+ patch(f"{MODULE}.skyvern_context.current", return_value=context),
+ ):
+ from skyvern.services.script_service import _render_template_with_label
+
+ rendered = _render_template_with_label("exports/{{ workflow_run_id }}")
+
+ assert rendered == "exports/wr_cached_run"
+
+
@pytest.mark.asyncio
async def test_cached_download_calls_save_downloaded_files(setup, tmp_path):
"""save_downloaded_files must be called so get_downloaded_files can find the file."""
@@ -131,6 +166,311 @@ async def test_cached_download_calls_save_downloaded_files(setup, tmp_path):
_cleanup(refs)
+async def test_cached_download_dispatches_only_new_files_to_destination(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ existing_file = str(download_dir / "existing.pdf")
+ downloaded_file = str(download_dir / "downloaded.pdf")
+ refs = setup(
+ get_side_effect=[[], ["downloaded.pdf"]],
+ list_files_side_effect=[[existing_file], [existing_file, downloaded_file]],
+ )
+ try:
+ from skyvern.services.script_service import FileDownloadBlock, download
+
+ with patch.object(FileDownloadBlock, "_dispatch_files_to_storage", autospec=True) as dispatch_files:
+ await download(
+ prompt="Download invoice",
+ label="test_block",
+ download_target="s3",
+ s3_bucket="bucket",
+ aws_access_key_id="access-key",
+ aws_secret_access_key="secret-key",
+ region_name="us-east-1",
+ )
+
+ file_download_block = dispatch_files.await_args.args[0]
+ assert file_download_block.download_target == "s3"
+ assert file_download_block.s3_bucket == "bucket"
+ assert file_download_block.aws_access_key_id == "access-key"
+ assert file_download_block.aws_secret_access_key == "secret-key"
+ assert file_download_block.region_name == "us-east-1"
+ dispatch_files.assert_awaited_once_with(
+ file_download_block,
+ storage_type="s3",
+ files_to_upload=[downloaded_file],
+ workflow_run_id="wr_test_run",
+ workflow_run_block_id="wrb_1",
+ organization_id="o_test_org",
+ workflow_run_context=refs["app"].WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context.return_value,
+ )
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_awaits_in_flight_downloads_before_snapshot(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ downloaded_file = str(download_dir / "downloaded.pdf")
+ refs = setup(
+ get_side_effect=[[], ["downloaded.pdf"]],
+ list_files_side_effect=[[], [downloaded_file]],
+ )
+ try:
+ from skyvern.services.script_service import FileDownloadBlock, download
+
+ async def assert_waited_before_dispatch(*_args, **_kwargs):
+ refs["wait_downloads"].assert_awaited_once_with(
+ download_dir=download_dir,
+ organization_id="o_test_org",
+ browser_session_id=None,
+ )
+
+ with patch.object(
+ FileDownloadBlock,
+ "_dispatch_files_to_storage",
+ autospec=True,
+ side_effect=assert_waited_before_dispatch,
+ ) as dispatch_files:
+ await download(
+ prompt="Download invoice",
+ label="test_block",
+ download_target="s3",
+ s3_bucket="bucket",
+ aws_access_key_id="access-key",
+ aws_secret_access_key="secret-key",
+ )
+
+ refs["wait_downloads"].assert_awaited_once_with(
+ download_dir=download_dir,
+ organization_id="o_test_org",
+ browser_session_id=None,
+ )
+ dispatch_files.assert_awaited_once()
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_uses_parent_run_id_for_download_dir(setup, mock_context, tmp_path):
+ mock_context.run_id = "wr_parent_run"
+ mock_context.workflow_run_id = "wr_child_run"
+ download_dir = tmp_path / "downloads"
+ downloaded_file = str(download_dir / "downloaded.pdf")
+ refs = setup(
+ get_side_effect=[[], ["downloaded.pdf"]],
+ list_files_side_effect=[[], [downloaded_file]],
+ )
+ try:
+ from skyvern.services.script_service import download
+
+ await download(prompt="Download invoice", label="test_block")
+
+ refs["get_download_dir"].assert_called_once_with("wr_parent_run")
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_dispatch_failure_does_not_fallback_to_ai(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ downloaded_file = str(download_dir / "downloaded.pdf")
+ refs = setup(
+ get_side_effect=[[], ["downloaded.pdf"]],
+ list_files_side_effect=[[], [downloaded_file]],
+ )
+ try:
+ from skyvern.services.script_service import FileDownloadBlock, download
+
+ with (
+ patch.object(
+ FileDownloadBlock,
+ "_dispatch_files_to_storage",
+ autospec=True,
+ side_effect=RuntimeError("destination unavailable"),
+ ) as dispatch_files,
+ pytest.raises(RuntimeError, match="destination unavailable"),
+ ):
+ await download(
+ prompt="Download invoice",
+ label="test_block",
+ download_target="s3",
+ s3_bucket="bucket",
+ aws_access_key_id="access-key",
+ aws_secret_access_key="secret-key",
+ )
+
+ dispatch_files.assert_awaited_once()
+ refs["fallback"].assert_not_awaited()
+ assert refs["update_block"].await_args.args[1].value == "failed"
+ assert refs["update_block"].await_args.kwargs["failure_reason"] == "destination unavailable"
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_ai_fallback_still_dispatches_to_destination(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ fallback_file = str(download_dir / "fallback.pdf")
+ refs = setup(
+ get_side_effect=[[]],
+ list_files_side_effect=[[], [], [fallback_file]],
+ )
+ refs["run_cached"].side_effect = RuntimeError("cached download failed")
+
+ async def create_fallback_download(**kwargs):
+ Path(fallback_file).write_bytes(b"fallback contents")
+
+ refs["fallback"].side_effect = create_fallback_download
+ try:
+ from skyvern.services.script_service import FileDownloadBlock, download
+
+ with patch.object(FileDownloadBlock, "_dispatch_files_to_storage", autospec=True) as dispatch_files:
+ await download(
+ prompt="Download invoice",
+ label="test_block",
+ download_target="s3",
+ s3_bucket="bucket",
+ aws_access_key_id="access-key",
+ aws_secret_access_key="secret-key",
+ )
+
+ refs["fallback"].assert_awaited_once()
+ dispatch_files.assert_awaited_once()
+ assert dispatch_files.await_args.kwargs["files_to_upload"] == [fallback_file]
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_website_download_never_dispatches_external_storage(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ downloaded_file = str(download_dir / "downloaded.pdf")
+ refs = setup(
+ get_side_effect=[[], ["downloaded.pdf"]],
+ list_files_side_effect=[[], [downloaded_file]],
+ )
+ try:
+ from skyvern.services.script_service import FileDownloadBlock, download
+
+ with patch.object(FileDownloadBlock, "_dispatch_files_to_storage", autospec=True) as dispatch_files:
+ await download(
+ prompt="Download invoice",
+ label="test_block",
+ download_target="website",
+ s3_bucket="stale-bucket",
+ aws_access_key_id="stale-key",
+ aws_secret_access_key="stale-secret",
+ )
+
+ dispatch_files.assert_not_awaited()
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_applies_destination_prompt_before_dispatch(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ invoice_file = str(download_dir / "invoice.pdf")
+ report_file = str(download_dir / "report.csv")
+ refs = setup(
+ get_side_effect=[[], ["invoice.pdf", "report.csv"]],
+ list_files_side_effect=[[], [invoice_file, report_file]],
+ )
+ try:
+ from skyvern.services.script_service import FileDownloadBlock, download
+
+ selected_files = AsyncMock(return_value=([invoice_file], "Only the invoice matches."))
+ with (
+ patch.object(FileDownloadBlock, "_select_files_to_upload_with_prompt", selected_files),
+ patch.object(FileDownloadBlock, "_dispatch_files_to_storage", autospec=True) as dispatch_files,
+ ):
+ await download(
+ prompt="Only upload invoice PDFs.",
+ navigation_goal="Download the invoice and report.",
+ label="test_block",
+ download_target="s3",
+ s3_bucket="bucket",
+ aws_access_key_id="access-key",
+ aws_secret_access_key="secret-key",
+ )
+
+ file_download_block = dispatch_files.await_args.args[0]
+ selected_files.assert_awaited_once_with(
+ file_download_block,
+ prompt="Only upload invoice PDFs.",
+ files_to_upload=[invoice_file, report_file],
+ workflow_run_block_id="wrb_1",
+ organization_id="o_test_org",
+ )
+ assert dispatch_files.await_args.kwargs["files_to_upload"] == [invoice_file]
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_detects_same_path_content_replacement(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ replaced_file = download_dir / "invoice.pdf"
+ replaced_file.write_bytes(b"prior block contents")
+ refs = setup(
+ get_side_effect=[[], ["invoice.pdf"]],
+ list_files_side_effect=[[str(replaced_file)], [str(replaced_file)]],
+ )
+ refs["run_cached"].side_effect = lambda _: replaced_file.write_bytes(b"this block contents")
+ try:
+ from skyvern.services.script_service import FileDownloadBlock, download
+
+ with (
+ patch(f"{MODULE}.CACHED_DOWNLOAD_NO_FILE_GRACE_SECONDS", 0),
+ patch.object(FileDownloadBlock, "_dispatch_files_to_storage", autospec=True) as dispatch_files,
+ ):
+ await download(
+ prompt="Download invoice",
+ label="test_block",
+ download_target="s3",
+ s3_bucket="bucket",
+ aws_access_key_id="access-key",
+ aws_secret_access_key="secret-key",
+ )
+
+ dispatch_files.assert_awaited_once()
+ assert dispatch_files.await_args.kwargs["files_to_upload"] == [str(replaced_file)]
+ refs["fallback"].assert_not_awaited()
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_missing_destination_halts_without_fallback(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ downloaded_file = str(download_dir / "invoice.pdf")
+ refs = setup(
+ get_side_effect=[[], ["invoice.pdf"]],
+ list_files_side_effect=[[], [downloaded_file]],
+ )
+ try:
+ from skyvern.exceptions import ScriptTerminationException
+ from skyvern.services.script_service import FileDownloadBlock, download
+
+ with patch.object(FileDownloadBlock, "_dispatch_files_to_storage", autospec=True) as dispatch_files:
+ # A misconfigured cached destination must halt the script (raise), not just return a
+ # failed status, so later generated statements do not run; and it must not download or fall back.
+ with pytest.raises(ScriptTerminationException):
+ await download(
+ prompt="Download invoice",
+ label="test_block",
+ download_target="s3",
+ aws_access_key_id="access-key",
+ aws_secret_access_key="secret-key",
+ )
+
+ dispatch_files.assert_not_awaited()
+ refs["fallback"].assert_not_awaited()
+ finally:
+ _cleanup(refs)
+
+
@pytest.mark.asyncio
async def test_rename_happens_before_s3_upload(setup, tmp_path):
"""download_suffix rename must happen BEFORE save_downloaded_files.
@@ -379,7 +719,12 @@ async def test_rename_skips_crdownload_files(setup, tmp_path):
refs = setup(
get_side_effect=[[], ["invoice.pdf"]],
# before, local verify, rename local_files_after, existing_names dedup lookup
- list_files_side_effect=[[], [incomplete, complete], [incomplete, complete], [incomplete, complete]],
+ list_files_side_effect=[
+ [incomplete],
+ [incomplete, complete],
+ [incomplete, complete],
+ [incomplete, complete],
+ ],
rename_mock=rename_mock,
)
try:
@@ -502,6 +847,53 @@ async def test_poll_waits_for_crdownload_to_complete(setup, tmp_path):
_cleanup(refs)
+async def test_cached_download_waits_for_all_files_before_dispatch(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ first_complete = str(download_dir / "a.pdf")
+ second_incomplete = str(download_dir / "b.pdf.crdownload")
+ second_complete = str(download_dir / "b.pdf")
+ refs = setup(
+ get_side_effect=[[], [first_complete, second_complete]],
+ list_files_side_effect=[
+ [],
+ [first_complete, second_incomplete],
+ [first_complete, second_complete],
+ ],
+ )
+ try:
+ from skyvern.services.script_service import FileDownloadBlock, download
+
+ async def assert_partial_state_not_settled(_delay):
+ refs["storage"].save_downloaded_files.assert_not_awaited()
+ dispatch_files.assert_not_awaited()
+ refs["update_block"].assert_not_awaited()
+
+ with (
+ patch.object(FileDownloadBlock, "_dispatch_files_to_storage", autospec=True) as dispatch_files,
+ patch(
+ f"{MODULE}.asyncio.sleep",
+ new_callable=AsyncMock,
+ side_effect=assert_partial_state_not_settled,
+ ) as sleep,
+ ):
+ await download(
+ prompt="Download reports",
+ label="test_block",
+ download_target="s3",
+ s3_bucket="bucket",
+ aws_access_key_id="access-key",
+ aws_secret_access_key="secret-key",
+ )
+
+ sleep.assert_awaited_once()
+ dispatch_files.assert_awaited_once()
+ assert dispatch_files.await_args.kwargs["files_to_upload"] == [first_complete, second_complete]
+ assert refs["update_block"].await_args.args[1].value == "completed"
+ finally:
+ _cleanup(refs)
+
+
@pytest.mark.asyncio
async def test_poll_passes_immediately_with_complete_file(setup, tmp_path):
"""When a complete file appears immediately after the cached function
diff --git a/tests/unit/test_chain_click_blocked_anchor_navigation.py b/tests/unit/test_chain_click_blocked_anchor_navigation.py
index 6e7bc384d..62d8095cd 100644
--- a/tests/unit/test_chain_click_blocked_anchor_navigation.py
+++ b/tests/unit/test_chain_click_blocked_anchor_navigation.py
@@ -9,7 +9,6 @@ fallback for the ``blocking_element is None and blocked is True`` branch only.
from __future__ import annotations
-from typing import NamedTuple
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -19,14 +18,6 @@ from skyvern.webeye.utils import dom as dom_module
from skyvern.webeye.utils.dom import InteractiveElement, SkyvernElement
-class _ChainClickRun(NamedTuple):
- results: list
- coordinate_click: AsyncMock
- try_navigate: AsyncMock
- click_in_javascript: AsyncMock
- blocking_click: AsyncMock | None
-
-
def _make_anchor_element(
href: str | None = "/target",
tag: str = InteractiveElement.A,
@@ -312,26 +303,10 @@ class TestChainClickBlockedAnchorNavigation:
action_y: int | None = None,
action_download: bool = False,
navigate_result: str | None = "https://portal.example.com/billpay",
- with_incremental: bool = False,
- page_responded: bool | None = True,
- input_type: str | None = None,
- js_click_url: str | None = None,
- blocking_is_parent: bool | None = None,
- blocking_is_sibling: bool | None = None,
- blocking_rect: dict[str, float] | None = None,
- blocking_viewport: tuple[float, float] = (1920, 1080),
- blocking_inside_modal: bool = False,
- ) -> _ChainClickRun:
- """Invoke chain_click through the ``find_blocking_element`` fallback with
- tightly-scoped stubs.
-
- ``with_incremental`` supplies an ``incremental_scraped`` observer (as the
- real ClickAction path does) and monkeypatches ``_did_page_respond`` to
- return ``page_responded`` so the intended-element JS-dispatch fallback can
- be verified. When ``blocking_is_parent``/``blocking_is_sibling`` are set,
- ``find_blocking_element`` returns a tracked blocking element with those
- relationships (Path 2); otherwise it returns ``(None, blocked)`` (Path 1).
- """
+ ) -> tuple[list, AsyncMock, AsyncMock]:
+ """Invoke chain_click through the ``blocking_element is None`` path
+ with tightly-scoped stubs. Returns (results, coordinate_click_mock,
+ try_navigate_mock)."""
from skyvern.webeye.actions import handler as handler_module
from skyvern.webeye.actions.actions import ClickAction
@@ -377,8 +352,6 @@ class TestChainClickBlockedAnchorNavigation:
return href
if name == "onclick":
return None
- if name == "type":
- return input_type
return None
elem.get_attr = AsyncMock(side_effect=_get_attr) # type: ignore[method-assign]
@@ -386,37 +359,10 @@ class TestChainClickBlockedAnchorNavigation:
elem.find_bound_label_by_attr_id = AsyncMock(return_value=None) # type: ignore[method-assign]
elem.find_bound_label_by_direct_parent = AsyncMock(return_value=None) # type: ignore[method-assign]
elem.is_visible = AsyncMock(return_value=True) # type: ignore[method-assign]
- elem.get_element_handler = AsyncMock(return_value=MagicMock()) # type: ignore[method-assign]
+ elem.find_blocking_element = AsyncMock(return_value=(None, blocked)) # type: ignore[method-assign]
elem.coordinate_click = AsyncMock(return_value=None) # type: ignore[method-assign]
elem.click_in_javascript = AsyncMock(return_value=None) # type: ignore[method-assign]
- blocking_click: AsyncMock | None = None
- if blocking_is_parent is not None or blocking_is_sibling is not None:
- blocking_element = MagicMock()
- blocking_element.get_id = MagicMock(return_value="BLK1")
- blocking_element.is_parent_of = AsyncMock(return_value=bool(blocking_is_parent))
- blocking_element.is_sibling_of = AsyncMock(return_value=bool(blocking_is_sibling))
- blocking_click = AsyncMock(return_value=None)
- blocking_locator = MagicMock()
- blocking_locator.click = blocking_click
- blocking_locator.evaluate = AsyncMock(
- return_value=(
- {
- "width": blocking_rect["width"],
- "height": blocking_rect["height"],
- "viewport_width": blocking_viewport[0],
- "viewport_height": blocking_viewport[1],
- "inside_modal": blocking_inside_modal,
- }
- if blocking_rect is not None
- else None
- )
- )
- blocking_element.get_locator = MagicMock(return_value=blocking_locator)
- elem.find_blocking_element = AsyncMock(return_value=(blocking_element, blocked)) # type: ignore[method-assign]
- else:
- elem.find_blocking_element = AsyncMock(return_value=(None, blocked)) # type: ignore[method-assign]
-
try_navigate = AsyncMock(return_value=navigate_result)
elem.try_navigate_via_href = try_navigate # type: ignore[method-assign]
@@ -424,12 +370,6 @@ class TestChainClickBlockedAnchorNavigation:
page.url = "https://portal.example.com/dashboard"
page.goto = AsyncMock(return_value=None)
page.on = MagicMock()
- if js_click_url is not None:
-
- async def _navigate_on_js_click() -> None:
- page.url = js_click_url
-
- elem.click_in_javascript = AsyncMock(side_effect=_navigate_on_js_click) # type: ignore[method-assign]
task = MagicMock()
task.organization_id = "org_test"
@@ -442,32 +382,14 @@ class TestChainClickBlockedAnchorNavigation:
y=action_y,
)
- incremental = None
- skyvern_frame = None
- if with_incremental:
- incremental = MagicMock()
- skyvern_frame = MagicMock()
- skyvern_frame.get_frame.return_value = page
- if page_responded is None:
- incremental.get_incremental_elements_num = AsyncMock(return_value=0)
- skyvern_frame.safe_wait_for_animation_end = AsyncMock(return_value=None)
- else:
- monkeypatch.setattr(
- handler_module,
- "_did_page_respond",
- AsyncMock(return_value=page_responded),
- )
-
results = await handler_module.chain_click(
task=task,
scraped_page=scraped_page,
page=page,
action=action,
skyvern_element=elem,
- incremental_scraped=incremental,
- skyvern_frame=skyvern_frame,
)
- return _ChainClickRun(results, elem.coordinate_click, try_navigate, elem.click_in_javascript, blocking_click)
+ return results, elem.coordinate_click, try_navigate
@pytest.mark.asyncio
async def test_blocked_anchor_navigates_via_href_and_skips_coordinate_click(
@@ -475,7 +397,7 @@ class TestChainClickBlockedAnchorNavigation:
) -> None:
from skyvern.webeye.actions.responses import ActionSuccess
- results, coord_click, navigate, *_ = await self._run_chain_click(
+ results, coord_click, navigate = await self._run_chain_click(
monkeypatch,
blocked=True,
tag=InteractiveElement.A,
@@ -488,7 +410,7 @@ class TestChainClickBlockedAnchorNavigation:
@pytest.mark.asyncio
async def test_blocked_non_anchor_still_uses_coordinate_click(self, monkeypatch: pytest.MonkeyPatch) -> None:
- results, coord_click, navigate, *_ = await self._run_chain_click(
+ results, coord_click, navigate = await self._run_chain_click(
monkeypatch,
blocked=True,
tag=InteractiveElement.BUTTON,
@@ -502,7 +424,7 @@ class TestChainClickBlockedAnchorNavigation:
async def test_unblocked_anchor_still_uses_coordinate_click(self, monkeypatch: pytest.MonkeyPatch) -> None:
# blocked=False = the transient-instability React re-render case; the
# coordinate fallback is safe there. We must not divert to href nav.
- results, coord_click, navigate, *_ = await self._run_chain_click(
+ results, coord_click, navigate = await self._run_chain_click(
monkeypatch,
blocked=False,
tag=InteractiveElement.A,
@@ -516,7 +438,7 @@ class TestChainClickBlockedAnchorNavigation:
async def test_blocked_anchor_with_upload_action_skips_href_navigation(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
- results, coord_click, navigate, *_ = await self._run_chain_click(
+ results, coord_click, navigate = await self._run_chain_click(
monkeypatch,
blocked=True,
tag=InteractiveElement.A,
@@ -534,7 +456,7 @@ class TestChainClickBlockedAnchorNavigation:
# JS-driven downloads (onclick builds a blob/POST) would fetch the
# wrong static resource if we diverted to ``frame.goto(href)``.
# Downloads must keep going through the normal click path.
- results, coord_click, navigate, *_ = await self._run_chain_click(
+ results, coord_click, navigate = await self._run_chain_click(
monkeypatch,
blocked=True,
tag=InteractiveElement.A,
@@ -549,7 +471,7 @@ class TestChainClickBlockedAnchorNavigation:
async def test_blocked_anchor_with_explicit_coordinates_skips_href_navigation(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
- results, coord_click, navigate, *_ = await self._run_chain_click(
+ results, coord_click, navigate = await self._run_chain_click(
monkeypatch,
blocked=True,
tag=InteractiveElement.A,
@@ -567,7 +489,7 @@ class TestChainClickBlockedAnchorNavigation:
) -> None:
# If the helper cannot resolve a safe URL (e.g. javascript:) it returns
# None; the existing coordinate fallback must still run.
- results, coord_click, navigate, *_ = await self._run_chain_click(
+ results, coord_click, navigate = await self._run_chain_click(
monkeypatch,
blocked=True,
tag=InteractiveElement.A,
@@ -579,279 +501,6 @@ class TestChainClickBlockedAnchorNavigation:
coord_click.assert_awaited_once()
-class TestChainClickOverlayBlockedSubmit:
- """A primary-submit click intercepted by a consent / opt-out / FCRA overlay
- must not be silently redirected onto the overlay. On the observer-backed
- ClickAction path (``incremental_scraped`` present), chain_click dispatches on
- the *intended* element (bypassing hit-testing) instead of coordinate-clicking
- into whatever pixel is on top, and never retargets onto a mere sibling
- overlay. Callers without an observer (custom checkbox/radio retarget) keep
- their existing coordinate-click / sibling-retarget behavior.
- """
-
- _run_chain_click = staticmethod(TestChainClickBlockedAnchorNavigation._run_chain_click)
-
- @staticmethod
- def _has_success(results: list) -> bool:
- from skyvern.webeye.actions.responses import ActionSuccess
-
- return any(isinstance(r, ActionSuccess) for r in results)
-
- @staticmethod
- def _has_failure(results: list) -> bool:
- from skyvern.webeye.actions.responses import ActionFailure
-
- return any(isinstance(r, ActionFailure) for r in results)
-
- @pytest.mark.asyncio
- async def test_untracked_overlay_dispatches_on_intended_element_not_overlay(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.BUTTON,
- href=None,
- with_incremental=True,
- page_responded=True,
- )
-
- run.click_in_javascript.assert_awaited_once()
- run.coordinate_click.assert_not_called()
- assert self._has_success(run.results)
-
- @pytest.mark.asyncio
- async def test_untracked_overlay_no_page_response_fails_clean(self, monkeypatch: pytest.MonkeyPatch) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.BUTTON,
- href=None,
- with_incremental=True,
- page_responded=False,
- )
-
- run.click_in_javascript.assert_awaited_once()
- run.coordinate_click.assert_not_called()
- assert self._has_failure(run.results)
- assert not self._has_success(run.results)
-
- @pytest.mark.asyncio
- async def test_untracked_overlay_input_submit_dispatches_on_intended_element(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.INPUT,
- href=None,
- with_incremental=True,
- page_responded=True,
- )
-
- run.click_in_javascript.assert_awaited_once()
- run.coordinate_click.assert_not_called()
- assert self._has_success(run.results)
-
- @pytest.mark.asyncio
- async def test_untracked_overlay_navigation_after_dispatch_counts_as_success(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.BUTTON,
- href=None,
- with_incremental=True,
- page_responded=None,
- js_click_url="https://portal.example.com/submitted",
- )
-
- run.click_in_javascript.assert_awaited_once()
- run.coordinate_click.assert_not_called()
- assert self._has_success(run.results)
-
- @pytest.mark.asyncio
- async def test_explicit_coordinate_click_still_coordinate_clicks_under_overlay(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- # An action with explicit x/y is a deliberate coordinate click; keep it.
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.BUTTON,
- href=None,
- with_incremental=True,
- action_x=100,
- action_y=200,
- )
-
- run.coordinate_click.assert_awaited_once()
- run.click_in_javascript.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_parent_container_blocker_still_retargets(self, monkeypatch: pytest.MonkeyPatch) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.BUTTON,
- href=None,
- with_incremental=True,
- blocking_is_parent=True,
- blocking_is_sibling=False,
- )
-
- assert run.blocking_click is not None
- run.blocking_click.assert_awaited_once()
- run.click_in_javascript.assert_not_called()
- assert self._has_success(run.results)
-
- @pytest.mark.asyncio
- async def test_sibling_overlay_with_observer_not_retargeted(self, monkeypatch: pytest.MonkeyPatch) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.BUTTON,
- href=None,
- with_incremental=True,
- page_responded=True,
- blocking_is_parent=False,
- blocking_is_sibling=True,
- )
-
- assert run.blocking_click is not None
- run.blocking_click.assert_not_called()
- run.click_in_javascript.assert_awaited_once()
- assert self._has_success(run.results)
-
- @pytest.mark.parametrize("input_type", ["checkbox", "radio"])
- @pytest.mark.asyncio
- async def test_sibling_form_control_with_observer_still_retargets(
- self, monkeypatch: pytest.MonkeyPatch, input_type: str
- ) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.INPUT,
- input_type=input_type,
- href=None,
- with_incremental=True,
- blocking_is_parent=False,
- blocking_is_sibling=True,
- blocking_rect={"x": 0, "y": 0, "width": 24, "height": 24},
- )
-
- assert run.blocking_click is not None
- run.blocking_click.assert_awaited_once()
- run.click_in_javascript.assert_not_called()
- assert self._has_success(run.results)
-
- @pytest.mark.asyncio
- async def test_small_custom_sibling_with_observer_still_retargets(self, monkeypatch: pytest.MonkeyPatch) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag="div",
- href=None,
- with_incremental=True,
- blocking_is_parent=False,
- blocking_is_sibling=True,
- blocking_rect={"x": 0, "y": 0, "width": 24, "height": 24},
- )
-
- assert run.blocking_click is not None
- run.blocking_click.assert_awaited_once()
- run.click_in_javascript.assert_not_called()
- assert self._has_success(run.results)
-
- @pytest.mark.asyncio
- async def test_full_cover_sibling_overlay_over_checkbox_is_not_retargeted(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.INPUT,
- input_type="checkbox",
- href=None,
- with_incremental=True,
- page_responded=True,
- blocking_is_parent=False,
- blocking_is_sibling=True,
- blocking_rect={"x": 0, "y": 0, "width": 1920, "height": 1080},
- )
-
- assert run.blocking_click is not None
- run.blocking_click.assert_not_called()
- run.click_in_javascript.assert_awaited_once()
- assert self._has_success(run.results)
-
- @pytest.mark.asyncio
- async def test_small_semantic_modal_sibling_over_checkbox_is_not_retargeted(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.INPUT,
- input_type="checkbox",
- href=None,
- with_incremental=True,
- page_responded=True,
- blocking_is_parent=False,
- blocking_is_sibling=True,
- blocking_rect={"x": 0, "y": 0, "width": 600, "height": 400},
- blocking_inside_modal=True,
- )
-
- assert run.blocking_click is not None
- run.blocking_click.assert_not_called()
- run.click_in_javascript.assert_awaited_once()
- assert self._has_success(run.results)
-
- @pytest.mark.asyncio
- async def test_iframe_covering_sibling_overlay_over_checkbox_is_not_retargeted(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.INPUT,
- input_type="checkbox",
- href=None,
- with_incremental=True,
- page_responded=True,
- blocking_is_parent=False,
- blocking_is_sibling=True,
- blocking_rect={"x": 0, "y": 0, "width": 800, "height": 500},
- blocking_viewport=(800, 500),
- )
-
- assert run.blocking_click is not None
- run.blocking_click.assert_not_called()
- run.click_in_javascript.assert_awaited_once()
- assert self._has_success(run.results)
-
- @pytest.mark.asyncio
- async def test_sibling_blocker_without_observer_still_retargets(self, monkeypatch: pytest.MonkeyPatch) -> None:
- # No observer = the custom checkbox/radio retarget callers; a sibling
- # decoration (e.g. a styled span over the real control) must still be
- # clicked to activate the intended control.
- run = await self._run_chain_click(
- monkeypatch,
- blocked=True,
- tag=InteractiveElement.BUTTON,
- href=None,
- with_incremental=False,
- blocking_is_parent=False,
- blocking_is_sibling=True,
- )
-
- assert run.blocking_click is not None
- run.blocking_click.assert_awaited_once()
- assert self._has_success(run.results)
-
-
def test_dom_module_exports_try_navigate_via_href() -> None:
"""Sanity check that the helper is a method on ``SkyvernElement``."""
assert hasattr(dom_module.SkyvernElement, "try_navigate_via_href")
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index 6d0d082fc..056fa5cc5 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -687,6 +687,50 @@ async def wrapper({default_args}):
return filtered_user_function
+ def test_inline_exec_emits_audit_event_with_hash_not_code(self) -> None:
+ """The inline exec path emits codeblock.inline_exec_entered with a code hash, never the code."""
+ import hashlib
+ from unittest.mock import MagicMock
+
+ from structlog.testing import capture_logs
+
+ now = datetime.now(timezone.utc)
+ output_parameter = OutputParameter(
+ parameter_type=ParameterType.OUTPUT,
+ key="audit_output",
+ description="test output",
+ output_parameter_id="op_audit",
+ workflow_id="w_test",
+ created_at=now,
+ modified_at=now,
+ )
+ secret_marker = "s3cr3t_business_logic_token"
+ code = f"x = {secret_marker!r}\nreturn {{'x': x}}"
+ block = CodeBlock(label="audit_block", code=code, output_parameter=output_parameter)
+
+ with capture_logs() as logs:
+ block.generate_async_user_function(
+ block.code,
+ MagicMock(),
+ workflow_run_id="wr-audit",
+ organization_id="org-audit",
+ workflow_run_block_id="wrb-audit",
+ )
+
+ events = [entry for entry in logs if entry.get("event") == "codeblock.inline_exec_entered"]
+ assert len(events) == 1
+ entry = events[0]
+ assert entry["code_sha256"] == hashlib.sha256(code.encode("utf-8")).hexdigest()
+ assert entry["code_len"] == len(code)
+ assert entry["in_process"] is True
+ assert isinstance(entry["pid"], int) and entry["pid"] > 0
+ assert entry["hostname"]
+ assert entry["organization_id"] == "org-audit"
+ assert entry["workflow_run_id"] == "wr-audit"
+ assert entry["workflow_run_block_id"] == "wrb-audit"
+ # SECURITY: the raw user code must never appear in the audit payload.
+ assert secret_marker not in json.dumps(entry, default=str)
+
@pytest.mark.asyncio
async def test_safe_code_runs_successfully(self) -> None:
"""Legitimate code should execute and return results."""
diff --git a/tests/unit/test_copilot_agent_blocker_renderer.py b/tests/unit/test_copilot_agent_blocker_renderer.py
index fc426d7f6..19023f4e9 100644
--- a/tests/unit/test_copilot_agent_blocker_renderer.py
+++ b/tests/unit/test_copilot_agent_blocker_renderer.py
@@ -24,6 +24,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import (
BlockerKind,
CopilotToolBlockerSignal,
RecoveryHint,
+ build_definition_contract_unsatisfied_blocker_signal,
)
from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdict
from skyvern.forge.sdk.copilot.context import AgentResult, CopilotContext
@@ -529,6 +530,21 @@ def test_turn_halt_exit_keeps_halt_signal_when_context_signal_is_cleared() -> No
assert result.user_response == signal.user_facing_reason
+def test_definition_contract_halt_renders_sorted_parameter_names_without_internal_machinery() -> None:
+ ctx = _ctx()
+ signal = build_definition_contract_unsatisfied_blocker_signal(
+ unresolved_parameter_keys=["service_address", "business_name", "contact_email"]
+ )
+ halt = TurnHalt(kind=TurnHaltKind.DEFINITION_CONTRACT_UNSATISFIED, blocker_signal=signal)
+
+ result = _build_turn_halt_exit_result(ctx, global_llm_context=None, halt=halt)
+
+ assert result.user_response == signal.user_facing_reason
+ assert result.user_response.index("business_name") < result.user_response.index("contact_email")
+ assert result.user_response.index("contact_email") < result.user_response.index("service_address")
+ assert "update_and_run_blocks" not in result.user_response
+
+
def test_turn_halt_exit_renders_code_authoring_churn_reason() -> None:
ctx = _ctx()
signal = _signal(
diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.py
index d69274f08..3c609de18 100644
--- a/tests/unit/test_copilot_code_block_persist_seam.py
+++ b/tests/unit/test_copilot_code_block_persist_seam.py
@@ -6,6 +6,8 @@ OSS-synced: only example.* / RFC-2606 placeholder targets and synthetic labels.
from __future__ import annotations
import ast
+import hashlib
+import inspect
import json
import textwrap
from types import SimpleNamespace
@@ -19,6 +21,7 @@ from skyvern.forge.sdk.copilot import agent as agent_module
from skyvern.forge.sdk.copilot import code_block_synthesis as code_block_synthesis_module
from skyvern.forge.sdk.copilot import enforcement as enforcement_module
from skyvern.forge.sdk.copilot import request_policy as request_policy_module
+from skyvern.forge.sdk.copilot import tools as tools_module
from skyvern.forge.sdk.copilot.blocker_signal import (
CREDENTIAL_SCOUT_VERIFY_REPLY,
CopilotToolBlockerSignal,
@@ -28,9 +31,11 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (
BuildTestOutcomeReasonCode,
RecordedBuildTestOutcome,
RecordedOutcomeBindingConstraint,
+ arm_recorded_outcome_grounding_requirement,
authored_block_signatures_from_workflow,
authored_structure_signature_from_workflow,
latest_recorded_build_test_outcome_repeated,
+ maybe_satisfy_recorded_outcome_grounding_requirement,
record_build_test_outcome,
recorded_outcome_from_author_time_reject,
recorded_outcome_from_authoring_repair_context,
@@ -446,6 +451,44 @@ def _single_code_block(parsed: dict[str, object]) -> dict[str, object]:
return blocks[0]
+_UNREFERENCED_DEFINITION_YAML = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: []
+ code: |
+ await page.locator("#open").click()
+ await page.locator("#submit").click()
+ """
+)
+
+
+def _definition_contract_ctx() -> CopilotContext:
+ ctx = _code_only_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ CompletionCriterion(
+ id="c0",
+ outcome=(
+ "The workflow uses business name, contact email, service address, and desired start date "
+ "as reusable inputs."
+ ),
+ level="definition",
+ output_path="workflow.parameters",
+ )
+ ]
+ )
+ return ctx
+
+
@pytest.mark.parametrize(
"code",
[
@@ -1227,6 +1270,927 @@ class TestCodeSafetySeam:
class TestCodeRepairProgressClassification:
+ def test_output_safety_clamp_byte_parity(self) -> None:
+ source = inspect.getsource(workflow_update_module._extraction_code_with_required_static_return)
+
+ assert hashlib.sha256(source.encode()).hexdigest() == (
+ "32d1a9443d6dae7e8f6367cbe52902d7aaeb270e78c0275a66648d6013f24f9d"
+ )
+
+ @pytest.mark.asyncio
+ async def test_update_workflow_rejects_unreferenced_definition_before_persistence(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _definition_contract_ctx()
+ prior_yaml = ctx.workflow_yaml
+
+ for _ in range(2):
+ result = await _update_workflow(
+ {"workflow_yaml": _UNREFERENCED_DEFINITION_YAML},
+ ctx,
+ allow_missing_credentials=True,
+ allow_static_output_uncertainty=True,
+ )
+ assert result["ok"] is False
+ assert result["data"]["reason_code"] == "definition_contract_unsatisfied"
+
+ assert ctx.workflow_yaml == prior_yaml
+ assert ctx.has_staged_proposal is False
+ assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
+ assert latest_recorded_build_test_outcome_repeated(ctx) is True
+ requirement = arm_recorded_outcome_grounding_requirement(ctx)
+ assert requirement is not None
+ assert requirement.required_target_url == "current_page"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("reason_code", ["definition_contract_unsatisfied", "metadata_reject"])
+ async def test_recut_binding_changes_candidate(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ reason_code: BuildTestOutcomeReasonCode,
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _definition_contract_ctx()
+ _enable_imposition(ctx)
+ for _ in range(2):
+ rejected = await _update_workflow({"workflow_yaml": _UNREFERENCED_DEFINITION_YAML}, ctx)
+ assert rejected["ok"] is False
+ assert arm_recorded_outcome_grounding_requirement(ctx) is not None
+ source_url = "https://example.com/utility"
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#open", "source_url": source_url, "trajectory_index": 0},
+ {"tool_name": "click", "selector": "#submit", "source_url": source_url, "trajectory_index": 1},
+ ]
+ runtime_parameters = {
+ "business_name": "Example Co",
+ "contact_email": "[email protected]",
+ "service_address": "1 Example Way",
+ "desired_start_date": "2026-08-01",
+ }
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": source_url,
+ "page_title": "Utility request",
+ "forms": [
+ {
+ "fields": [
+ {"selector": "#company", "value": runtime_parameters["business_name"]},
+ {"selector": "#email", "value": runtime_parameters["contact_email"]},
+ {"selector": "#address", "value": runtime_parameters["service_address"]},
+ {"selector": "#date", "value": runtime_parameters["desired_start_date"]},
+ ],
+ "submit_controls": [{"selector": "#submit"}],
+ }
+ ],
+ "navigation_targets": [],
+ "result_containers": [],
+ "challenge_controls": [],
+ "anti_bot_indicators": [],
+ "observed_after_workflow_run": False,
+ }
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
+ requirement = ctx.recorded_outcome_grounding_requirement
+ constraint = ctx.recorded_outcome_binding_constraint
+ assert requirement is not None
+ assert constraint is not None
+ ctx.recorded_outcome_grounding_requirement = requirement.model_copy(update={"reason_code": reason_code})
+ ctx.recorded_outcome_binding_constraint = constraint.model_copy(update={"reason_code": reason_code})
+
+ with capture_logs() as logs:
+ result = await _update_workflow(
+ {"workflow_yaml": _UNREFERENCED_DEFINITION_YAML, "parameters": runtime_parameters},
+ ctx,
+ allow_missing_credentials=True,
+ )
+
+ assert result["ok"] is True
+ bound = next(log for log in logs if log["event"] == "copilot recorded outcome submit rung bound")
+ consumed = next(
+ log for log in logs if log["event"] == "copilot recorded outcome binding consumed by synthesizer"
+ )
+ assert consumed["binding_fingerprints"] == [bound["binding_fingerprint"]]
+ assert all("submit_rung_binding" not in interaction for interaction in ctx.scout_trajectory)
+ code = str(_single_code_block(parse_workflow_yaml(ctx.workflow_yaml))["code"])
+ for selector, key in (
+ ("#company", "business_name"),
+ ("#email", "contact_email"),
+ ("#address", "service_address"),
+ ("#date", "desired_start_date"),
+ ):
+ assert f'page.locator("{selector}").fill(str({key}))' in code
+ assert code.index(f'page.locator("{selector}").fill') < code.index('page.locator("#submit").click()')
+
+ @pytest.mark.asyncio
+ async def test_public_update_and_run_consumes_regrounding_in_synthesis(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _definition_contract_ctx()
+ _enable_imposition(ctx)
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ initial_arguments = json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ }
+ )
+ for _ in range(2):
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ initial_arguments,
+ )
+ assert json.loads(result)["data"]["reason_code"] == "definition_contract_unsatisfied"
+ requirement = ctx.recorded_outcome_grounding_requirement
+ assert requirement is not None
+ assert requirement.phase == "author_time_reject"
+ source_url = "https://example.com/utility"
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#open", "source_url": source_url, "trajectory_index": 0},
+ {"tool_name": "click", "selector": "#submit", "source_url": source_url, "trajectory_index": 1},
+ ]
+ runtime_parameters = {
+ "business_name": "Example Co",
+ "contact_email": "[email protected]",
+ "service_address": "1 Example Way",
+ "desired_start_date": "2026-08-01",
+ }
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": source_url,
+ "page_title": "Utility request",
+ "forms": [
+ {
+ "fields": [
+ {"selector": "#company", "value": runtime_parameters["business_name"]},
+ {"selector": "#email", "value": runtime_parameters["contact_email"]},
+ {"selector": "#address", "value": runtime_parameters["service_address"]},
+ {"selector": "#date", "value": runtime_parameters["desired_start_date"]},
+ ],
+ "submit_controls": [{"selector": "#submit"}],
+ }
+ ],
+ "navigation_targets": [],
+ "result_containers": [],
+ "challenge_controls": [],
+ "anti_bot_indicators": [],
+ "observed_after_workflow_run": False,
+ }
+
+ async def _no_prior_definition(_ctx: CopilotContext) -> None:
+ return None
+
+ dispatched_candidates: list[str] = []
+
+ async def _run(_params: object, run_ctx: CopilotContext, **_kwargs: object) -> dict[str, object]:
+ dispatched_candidates.append(run_ctx.workflow_yaml or "")
+ return {"ok": False, "error": "stop after exact candidate"}
+
+ async def _verification(*_args: object, **_kwargs: object) -> None:
+ return None
+
+ monkeypatch.setattr(tools_module, "_get_prior_workflow_definition", _no_prior_definition)
+ monkeypatch.setattr(tools_module, "_plan_frontier", lambda *_args: (["submit_service_request"], {}, None))
+ monkeypatch.setattr(tools_module, "_frontier_run_size_error", lambda *_args: None)
+ monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", _run)
+ monkeypatch.setattr(tools_module, "_verify_and_record_run_blocks_result", _verification)
+ monkeypatch.setattr(tools_module, "_tool_visible_result_after_completion_verification", lambda _c, r, _v: r)
+ with capture_logs() as logs:
+ await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ "parameters": runtime_parameters,
+ }
+ ),
+ )
+
+ bound = next(log for log in logs if log["event"] == "copilot recorded outcome submit rung bound")
+ consumed = next(
+ log for log in logs if log["event"] == "copilot recorded outcome binding consumed by synthesizer"
+ )
+ assert consumed["binding_fingerprints"] == [bound["binding_fingerprint"]]
+ code = str(_single_code_block(parse_workflow_yaml(ctx.workflow_yaml))["code"])
+ assert 'page.locator("#company").fill(str(business_name))' in code
+ assert 'page.locator("#date").fill(str(desired_start_date))' in code
+ assert dispatched_candidates == [ctx.workflow_yaml]
+ assert workflow_update_module._definition_plane_preflight_reject(ctx, dispatched_candidates[0]) is None
+
+ @pytest.mark.asyncio
+ async def test_recut_unbindable_regrounding_halts_before_reauthor(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _definition_contract_ctx()
+ _enable_imposition(ctx)
+ for _ in range(2):
+ assert (await _update_workflow({"workflow_yaml": _UNREFERENCED_DEFINITION_YAML}, ctx))["ok"] is False
+ assert arm_recorded_outcome_grounding_requirement(ctx) is not None
+ ctx.blocker_signal = ctx.turn_halt = ctx.turn_ownership = None
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#submit", "source_url": "https://example.com/utility"}
+ ]
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": "https://example.com/utility",
+ "forms": [],
+ }
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
+ synthesize = Mock(side_effect=AssertionError("must halt before an identical re-author"))
+ monkeypatch.setattr(workflow_update_module, "synthesize_code_block_with_extraction", synthesize)
+
+ result = workflow_update_module._maybe_impose_synthesized_code_block(
+ _UNREFERENCED_DEFINITION_YAML,
+ ctx,
+ {
+ "business_name": "Example Co",
+ "contact_email": "[email protected]",
+ "service_address": "1 Example Way",
+ "desired_start_date": "2026-08-01",
+ },
+ )
+
+ assert result.workflow_yaml == _UNREFERENCED_DEFINITION_YAML
+ assert result.violations
+ synthesize.assert_not_called()
+ assert ctx.blocker_signal.extra["unresolved_parameter_keys"] == [
+ "business_name",
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+ assert "safely connect the current page fields" in ctx.blocker_signal.user_facing_reason
+
+ @pytest.mark.asyncio
+ async def test_public_update_and_run_halts_active_author_reject_before_third_identical_author(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ ctx = _definition_contract_ctx()
+ _enable_imposition(ctx)
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ arguments = json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ "parameters": {
+ "business_name": "Example Co",
+ "contact_email": "[email protected]",
+ "service_address": "1 Example Way",
+ "desired_start_date": "2026-08-01",
+ },
+ }
+ )
+ for _ in range(2):
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ arguments,
+ )
+ assert json.loads(result)["data"]["reason_code"] == "definition_contract_unsatisfied"
+ requirement = ctx.recorded_outcome_grounding_requirement
+ assert requirement is not None
+ assert requirement.phase == "author_time_reject"
+ active_structural_key = requirement.structural_key
+ ctx.blocker_signal = ctx.turn_halt = ctx.turn_ownership = None
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#submit", "source_url": "https://example.com/utility"}
+ ]
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": "https://example.com/utility",
+ "forms": [],
+ "observed_after_workflow_run": False,
+ }
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ arguments,
+ )
+
+ assert json.loads(result)["ok"] is False
+ assert ctx.latest_recorded_build_test_outcome.structural_key == active_structural_key
+ assert ctx.blocker_signal.internal_reason_code == "definition_contract_unsatisfied"
+ assert ctx.blocker_signal.extra["unresolved_parameter_keys"] == [
+ "business_name",
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+ assert ctx.turn_halt is not None
+ assert ctx.turn_halt.kind.value == "definition_contract_unsatisfied"
+
+ @pytest.mark.asyncio
+ async def test_definition_reject_stays_repairable_at_both_exact_gates(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ update_ctx = _definition_contract_ctx()
+
+ update_result = await _update_workflow({"workflow_yaml": _UNREFERENCED_DEFINITION_YAML}, update_ctx)
+
+ assert update_result["ok"] is False
+ assert update_result["data"]["unreferenced_parameter_keys"] == [
+ "business_name",
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+ assert update_ctx.blocker_signal is None
+ assert update_ctx.turn_halt is None
+
+ dispatch_ctx = _definition_contract_ctx()
+ dispatch_result = workflow_update_module._metadata_contract_run_preflight_reject(
+ dispatch_ctx,
+ _UNREFERENCED_DEFINITION_YAML,
+ [],
+ )
+
+ assert dispatch_result is not None
+ assert dispatch_result["ok"] is False
+ assert dispatch_result["data"]["reason_code"] == "definition_contract_unsatisfied"
+ assert dispatch_ctx.blocker_signal is None
+ assert dispatch_ctx.turn_halt is None
+
+ @pytest.mark.asyncio
+ async def test_public_update_and_run_definition_reject_returns_to_repair_loop(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ ctx = _definition_contract_ctx()
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ arguments = json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ }
+ )
+
+ for _ in range(2):
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ arguments,
+ )
+
+ parsed = json.loads(result)
+ assert parsed["ok"] is False
+ assert parsed["data"]["reason_code"] == "definition_contract_unsatisfied"
+ assert ctx.blocker_signal is None
+ assert ctx.turn_halt is None
+
+ assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "definition_contract_unsatisfied"
+ assert ctx.recorded_outcome_grounding_requirement is not None
+
+ third_result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ arguments,
+ )
+
+ assert json.loads(third_result)["ok"] is False
+ assert ctx.blocker_signal.internal_reason_code == "recorded_outcome_grounding_required"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("grounded_binding_available", [False, True])
+ async def test_public_update_and_run_rejects_unbound_declared_inputs_without_definition_tag(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ grounded_binding_available: bool,
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _code_only_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[CompletionCriterion(id="run", outcome="The service request is submitted.")]
+ )
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ dispatched = False
+ updated = False
+ real_update = tools_module._update_workflow
+
+ async def _observed_update(*args: object, **kwargs: object) -> dict[str, object]:
+ nonlocal updated
+ result = await real_update(*args, **kwargs)
+ updated = bool(result.get("ok"))
+ return result
+
+ async def _unexpected_dispatch(*_args: object, **_kwargs: object) -> dict[str, object]:
+ nonlocal dispatched
+ dispatched = True
+ return {"ok": True}
+
+ monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", _unexpected_dispatch)
+ monkeypatch.setattr(tools_module, "_update_workflow", _observed_update)
+ if grounded_binding_available:
+ monkeypatch.setattr(
+ workflow_update_module,
+ "_trajectory_with_grounded_submit_rung_binding",
+ lambda *_args, **_kwargs: [{"tool_name": "click", "selector": "#submit"}],
+ )
+
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ }
+ ),
+ )
+
+ parsed = json.loads(result)
+ assert parsed["ok"] is False
+ assert parsed["data"]["reason_code"] == "definition_contract_unsatisfied"
+ assert parsed["data"]["unreferenced_parameter_keys"] == [
+ "business_name",
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+ assert updated is True
+ assert dispatched is False
+
+ @pytest.mark.asyncio
+ async def test_public_initial_preflight_preserves_code_safety_precedence_for_untagged_inputs(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ ctx = _code_only_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[CompletionCriterion(id="run", outcome="The service request is submitted.")]
+ )
+ unsafe_yaml = _UNREFERENCED_DEFINITION_YAML.replace(
+ 'await page.locator("#open").click()',
+ 'import requests\n await page.locator("#open").click()',
+ )
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps({"workflow_yaml": unsafe_yaml, "block_labels": ["submit_service_request"]}),
+ )
+
+ parsed = json.loads(result)
+ assert parsed["ok"] is False
+ assert parsed.get("data", {}).get("reason_code") != "definition_contract_unsatisfied"
+ assert "sandbox safety check" in parsed["error"]
+
+ def test_recut_dispatch_controls_preserve_passing_and_zero_input_candidates(self) -> None:
+ ctx = _definition_contract_ctx()
+ ctx.output_contract_actuation_by_signature["p5-advisory"] = OutputContractAdvisoryState.GRANTED
+
+ result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, _UNREFERENCED_DEFINITION_YAML, [])
+
+ assert result is not None
+ assert result["data"]["reason_code"] == "definition_contract_unsatisfied"
+ assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
+ assert ctx.blocker_signal is None
+ assert ctx.turn_halt is None
+
+ passing_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name, contact_email, service_address, desired_start_date]
+ code: |
+ await page.locator("#company").fill(str(business_name))
+ await page.locator("#email").fill(str(contact_email))
+ await page.locator("#address").fill(str(service_address))
+ await page.locator("#date").fill(str(desired_start_date))
+ await page.locator("#submit").click()
+ """
+ )
+ passing_ctx = _definition_contract_ctx()
+ assert workflow_update_module._metadata_contract_run_preflight_reject(passing_ctx, passing_yaml, []) is None
+
+ zero_input_ctx = _code_only_ctx()
+ zero_input_ctx.request_policy = RequestPolicy(
+ completion_criteria=[CompletionCriterion(id="run", outcome="The request is submitted.")]
+ )
+ zero_input_yaml = _yaml(
+ """
+ title: Open status page
+ workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: open_status
+ parameter_keys: []
+ code: |
+ await page.goto("https://example.com/status")
+ """
+ )
+ assert (
+ workflow_update_module._metadata_contract_run_preflight_reject(zero_input_ctx, zero_input_yaml, []) is None
+ )
+
+ def test_definition_preflight_rejects_partial_parameter_references(self) -> None:
+ ctx = _definition_contract_ctx()
+ partially_referenced_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name]
+ code: |
+ await page.locator("#company").fill(str(business_name))
+ await page.locator("#submit").click()
+ """
+ )
+
+ result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, partially_referenced_yaml, [])
+
+ assert result is not None
+ assert result["data"]["unreferenced_parameter_keys"] == [
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+
+ def test_definition_preflight_ignores_parameter_names_in_comments_and_string_literals(self) -> None:
+ ctx = _definition_contract_ctx()
+ lexical_only_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name, contact_email, service_address, desired_start_date]
+ code: |
+ # contact_email and service_address are not executable references.
+ note = "desired_start_date"
+ await page.locator("#company").fill(str(business_name))
+ await page.locator("#submit").click()
+ """
+ )
+
+ result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, lexical_only_yaml, [])
+
+ assert result is not None
+ assert result["data"]["unreferenced_parameter_keys"] == [
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+
+ def test_definition_preflight_requires_live_parameter_dataflow(self) -> None:
+ ctx = _definition_contract_ctx()
+ dead_or_shadowed_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name, contact_email]
+ code: |
+ if False:
+ await page.locator("#company").fill(str(business_name))
+ contact_email = "[email protected]"
+ await page.locator("#email").fill(str(contact_email))
+ await page.locator("#submit").click()
+ """
+ )
+
+ result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, dead_or_shadowed_yaml, [])
+
+ assert result is not None
+ assert result["data"]["unreferenced_parameter_keys"] == ["business_name", "contact_email"]
+
+ def test_definition_preflight_accepts_parameter_alias_dataflow(self) -> None:
+ ctx = _definition_contract_ctx()
+ alias_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name]
+ code: |
+ company = str(business_name)
+ await page.locator("#company").fill(company)
+ await page.locator("#submit").click()
+ """
+ )
+
+ assert workflow_update_module._metadata_contract_run_preflight_reject(ctx, alias_yaml, []) is None
+
+ def test_definition_preflight_tracks_live_control_flow_dataflow(self) -> None:
+ ctx = _definition_contract_ctx()
+ control_flow_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name, contact_email]
+ code: |
+ company = business_name
+ if page.url:
+ company = company.strip()
+ else:
+ company = company.upper()
+ for selector in ["#company"]:
+ await page.locator(selector).fill(company)
+ try:
+ await page.locator("#email").fill(contact_email)
+ except Exception:
+ raise
+ """
+ )
+
+ assert workflow_update_module._metadata_contract_run_preflight_reject(ctx, control_flow_yaml, []) is None
+
+ def test_definition_preflight_drops_bindings_from_non_fallthrough_branch(self) -> None:
+ ctx = _definition_contract_ctx()
+ terminal_branch_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name]
+ code: |
+ if page.url.endswith("/done"):
+ company = business_name
+ if True:
+ return {"already_done": True}
+ else:
+ company = "fixed"
+ await page.locator("#company").fill(company)
+ """
+ )
+
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, terminal_branch_yaml)
+
+ assert result is not None
+ assert result.unreferenced_parameter_keys == ("business_name",)
+
+ @pytest.mark.parametrize(
+ "terminal_test", ["if 1:\n return {'already_done': True}", "while True:\n return {'already_done': True}"]
+ )
+ def test_definition_preflight_drops_bindings_from_constant_terminal_control(self, terminal_test: str) -> None:
+ ctx = _definition_contract_ctx()
+ indented_terminal = textwrap.indent(terminal_test, " ")
+ workflow_yaml = _yaml(
+ "title: Submit reusable service request\n"
+ "workflow_definition:\n"
+ " parameters:\n"
+ " - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}\n"
+ " blocks:\n"
+ " - block_type: code\n"
+ " label: submit_service_request\n"
+ " parameter_keys: [business_name]\n"
+ " code: |\n"
+ " if page.url.endswith('/done'):\n"
+ " company = business_name\n"
+ f"{indented_terminal}\n"
+ " else:\n"
+ " company = 'fixed'\n"
+ " await page.locator('#company').fill(company)\n"
+ )
+
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, workflow_yaml)
+
+ assert result is not None
+ assert result.unreferenced_parameter_keys == ("business_name",)
+
+ def test_definition_preflight_ignores_break_in_unreachable_constant_branch(self) -> None:
+ ctx = _definition_contract_ctx()
+ workflow_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name]
+ code: |
+ if page.url.endswith("/done"):
+ company = business_name
+ while True:
+ if False:
+ break
+ return {"already_done": True}
+ else:
+ company = "fixed"
+ await page.locator("#company").fill(company)
+ """
+ )
+
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, workflow_yaml)
+
+ assert result is not None
+ assert result.unreferenced_parameter_keys == ("business_name",)
+
+ def test_definition_preflight_ignores_break_overridden_by_terminal_finally(self) -> None:
+ ctx = _definition_contract_ctx()
+ workflow_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name]
+ code: |
+ if page.url.endswith("/done"):
+ company = business_name
+ while True:
+ try:
+ break
+ finally:
+ return {"already_done": True}
+ else:
+ company = "fixed"
+ await page.locator("#company").fill(company)
+ """
+ )
+
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, workflow_yaml)
+
+ assert result is not None
+ assert result.unreferenced_parameter_keys == ("business_name",)
+
+ @pytest.mark.parametrize(
+ ("code", "expected_unreferenced"),
+ [
+ (
+ "values = [business_name for business_name in ['fixed']]\n"
+ "await page.locator('#company').fill(values[0])",
+ ["business_name"],
+ ),
+ (
+ "async def fill_company():\n"
+ " await page.locator('#company').fill(str(business_name))\n"
+ "await fill_company()",
+ [],
+ ),
+ ],
+ )
+ def test_definition_preflight_honors_python_scopes(self, code: str, expected_unreferenced: list[str]) -> None:
+ ctx = _definition_contract_ctx()
+ indented_code = textwrap.indent(code, " ")
+ scoped_yaml = _yaml(
+ "title: Submit reusable service request\n"
+ "workflow_definition:\n"
+ " parameters:\n"
+ " - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}\n"
+ " blocks:\n"
+ " - block_type: code\n"
+ " label: submit_service_request\n"
+ " parameter_keys: [business_name]\n"
+ " code: |\n"
+ f"{indented_code}\n"
+ )
+
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, scoped_yaml)
+
+ if expected_unreferenced:
+ assert result is not None
+ assert list(result.unreferenced_parameter_keys) == expected_unreferenced
+ else:
+ assert result is None
+
+ def test_definition_preflight_counts_allowed_non_code_parameter_consumption(self) -> None:
+ ctx = _definition_contract_ctx()
+ mixed_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ blocks:
+ - block_type: navigation
+ label: open_customer
+ url: "https://example.com/customer/{{ business_name }}"
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [contact_email]
+ code: |
+ await page.locator("#email").fill(contact_email)
+ await page.locator("#submit").click()
+ """
+ )
+
+ assert workflow_update_module._metadata_contract_run_preflight_reject(ctx, mixed_yaml, []) is None
+
+ @pytest.mark.parametrize(
+ ("template", "is_consumed"),
+ [
+ ('{{ "business_name" }}', False),
+ ("{% if business_name %}/customer{% endif %}", True),
+ ],
+ )
+ def test_definition_preflight_uses_jinja_semantics(self, template: str, is_consumed: bool) -> None:
+ ctx = _definition_contract_ctx()
+ templated_yaml = _yaml(
+ f"""
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {{parameter_type: workflow, key: business_name, workflow_parameter_type: string}}
+ blocks:
+ - block_type: navigation
+ label: open_customer
+ url: {json.dumps(template)}
+ """
+ )
+
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, templated_yaml)
+
+ assert (result is None) is is_consumed
+
+ @pytest.mark.asyncio
+ async def test_definition_preflight_defers_to_repairable_syntax_error(self) -> None:
+ ctx = _definition_contract_ctx()
+ malformed_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name]
+ code: |
+ await page.locator("#company").fill(str(business_name)
+ """
+ )
+
+ result = await _update_workflow({"workflow_yaml": malformed_yaml}, ctx)
+
+ assert result["ok"] is False
+ assert "not valid Python" in result["error"]
+ assert result.get("data", {}).get("reason_code") != "definition_contract_unsatisfied"
+
+ def test_definition_preflight_is_code_first_only(self) -> None:
+ ctx = _definition_contract_ctx()
+ ctx.block_authoring_policy = BlockAuthoringPolicy.STANDARD
+ standard_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
+ blocks:
+ - block_type: task
+ label: submit_service_request
+ url: "{{business_name}}/{{contact_email}}/{{service_address}}/{{desired_start_date}}"
+ """
+ )
+
+ assert (
+ workflow_update_module._metadata_contract_run_preflight_reject(
+ ctx,
+ standard_yaml,
+ [],
+ )
+ is None
+ )
+
@pytest.mark.asyncio
async def test_code_safety_seam_reject_carries_progress_surface_kind(self) -> None:
ctx = _code_only_ctx()
@@ -13023,6 +13987,8 @@ def _auto_act_scout_ctx() -> AgentContext:
ctx.browser_session_id = None
ctx.scouted_interactions = []
ctx.scout_trajectory = []
+ ctx.scout_observed_terminal_criterion_ids = set()
+ ctx.completion_criteria_turn_state = None
ctx.discovery_mcp_server = _AutoActClickServer()
return ctx
@@ -14535,35 +15501,128 @@ class TestCredentialScoutGatePredicateCoherence:
def _trajectory(*steps: dict[str, object]) -> list[dict[str, object]]:
return list(steps)
- def _gate_ctx(self, trajectory: list[dict[str, object]]) -> CopilotContext:
- ctx = _code_only_ctx()
- ctx.scout_trajectory = trajectory
- ctx.scouted_credential_field_inventory_by_credential_id = {"cred_1": frozenset({"username", "password"})}
- return ctx
+ def _gate_ctx(self, trajectory: list[dict[str, object]]) -> CopilotContext:
+ ctx = _code_only_ctx()
+ ctx.scout_trajectory = trajectory
+ ctx.scouted_credential_field_inventory_by_credential_id = {"cred_1": frozenset({"username", "password"})}
+ return ctx
+
+ def test_predicate_complete_trajectory_passes_the_real_gate(self) -> None:
+ helper = TestCredentialScoutGapMatcher
+ trajectory = self._trajectory(
+ helper._fill("cred_1", "username", helper._PAGE_ONE),
+ helper._click(helper._PAGE_ONE),
+ helper._fill("cred_1", "password", helper._PAGE_TWO),
+ helper._click(helper._PAGE_TWO),
+ )
+ ctx = self._gate_ctx(trajectory)
+ assert enforcement_module.synthesized_trajectory_is_goal_complete(ctx) is True
+ assert workflow_update_module._credentialed_code_block_scout_gate_errors(self._TWO_FIELD_LOGIN_YAML, ctx) == []
+
+ def test_predicate_incomplete_half_login_is_also_gate_rejected(self) -> None:
+ helper = TestCredentialScoutGapMatcher
+ trajectory = self._trajectory(
+ helper._fill("cred_1", "username", helper._PAGE_ONE),
+ helper._click(helper._PAGE_ONE),
+ )
+ ctx = self._gate_ctx(trajectory)
+ assert enforcement_module.synthesized_trajectory_is_goal_complete(ctx) is False
+ errors = workflow_update_module._credentialed_code_block_scout_gate_errors(self._TWO_FIELD_LOGIN_YAML, ctx)
+ assert errors
+ assert "password" in errors[0]
+
+
+class TestTerminalActionScoutGate:
+ _BUSINESS_URL = "https://portal.example.test/business/start-service"
+
+ @staticmethod
+ def _terminal_action_criterion(*, method_mandated: bool = False) -> CompletionCriterion:
+ return CompletionCriterion(
+ id="start_service_request",
+ outcome="the business start-service request reaches its review page",
+ kind="terminal_action",
+ terminal_action_family="request",
+ method_mandated=method_mandated,
+ )
+
+ def _login_prefix_ctx(self, *criteria: CompletionCriterion) -> CopilotContext:
+ helper = TestCredentialScoutGapMatcher
+ ctx = _code_only_ctx()
+ ctx.scout_trajectory = [
+ helper._fill("cred_1", "username", helper._PAGE_ONE),
+ helper._click(helper._PAGE_ONE),
+ helper._fill("cred_1", "password", helper._PAGE_TWO),
+ helper._click(helper._PAGE_TWO),
+ ]
+ ctx.scouted_credential_field_inventory_by_credential_id = {"cred_1": frozenset({"username", "password"})}
+ ctx.completion_criteria_turn_state = SimpleNamespace(decision=SimpleNamespace(criteria=tuple(criteria)))
+ return ctx
+
+ def _business_spine(self) -> list[dict[str, object]]:
+ return [
+ {
+ "tool_name": "type_text",
+ "selector": "#service-address",
+ "source_url": self._BUSINESS_URL,
+ "role": "textbox",
+ "accessible_name": "Service Address",
+ "trajectory_index": 4,
+ },
+ {
+ "tool_name": "click",
+ "selector": "#find-address",
+ "source_url": self._BUSINESS_URL,
+ "role": "button",
+ "accessible_name": "Find Address",
+ "trajectory_index": 5,
+ },
+ ]
+
+ def test_login_prefix_with_unreached_terminal_action_is_not_goal_complete(self) -> None:
+ ctx = self._login_prefix_ctx(self._terminal_action_criterion())
+ assert enforcement_module.synthesized_trajectory_reaches_goal(ctx) is True
+ assert enforcement_module.synthesized_trajectory_is_goal_complete(ctx) is False
+
+ def test_login_is_the_whole_goal_stays_goal_complete(self) -> None:
+ ctx = self._login_prefix_ctx()
+ assert enforcement_module.synthesized_trajectory_is_goal_complete(ctx) is True
+
+ def test_method_mandated_terminal_action_criterion_does_not_gate(self) -> None:
+ ctx = self._login_prefix_ctx(self._terminal_action_criterion(method_mandated=True))
+ assert enforcement_module.synthesized_trajectory_is_goal_complete(ctx) is True
+
+ def test_scout_observed_terminal_action_releases_goal_complete(self) -> None:
+ ctx = self._login_prefix_ctx(self._terminal_action_criterion())
+ ctx.scout_observed_terminal_criterion_ids = {"start_service_request"}
+ assert enforcement_module.synthesized_trajectory_is_goal_complete(ctx) is True
- def test_predicate_complete_trajectory_passes_the_real_gate(self) -> None:
- helper = TestCredentialScoutGapMatcher
- trajectory = self._trajectory(
- helper._fill("cred_1", "username", helper._PAGE_ONE),
- helper._click(helper._PAGE_ONE),
- helper._fill("cred_1", "password", helper._PAGE_TWO),
- helper._click(helper._PAGE_TWO),
- )
- ctx = self._gate_ctx(trajectory)
+ def test_post_credential_business_spine_records_terminal_action_observation(self) -> None:
+ ctx = self._login_prefix_ctx(self._terminal_action_criterion())
+ ctx.scout_trajectory = list(ctx.scout_trajectory) + self._business_spine()
+ assert enforcement_module.reached_terminal_action_criterion_ids(ctx) == {"start_service_request"}
+ enforcement_module.record_reached_terminal_action_observation(ctx)
+ assert ctx.scout_observed_terminal_criterion_ids == {"start_service_request"}
assert enforcement_module.synthesized_trajectory_is_goal_complete(ctx) is True
- assert workflow_update_module._credentialed_code_block_scout_gate_errors(self._TWO_FIELD_LOGIN_YAML, ctx) == []
- def test_predicate_incomplete_half_login_is_also_gate_rejected(self) -> None:
+ def test_login_only_trajectory_records_no_terminal_action_observation(self) -> None:
+ ctx = self._login_prefix_ctx(self._terminal_action_criterion())
+ enforcement_module.record_reached_terminal_action_observation(ctx)
+ assert ctx.scout_observed_terminal_criterion_ids == set()
+
+ def test_mfa_login_prefix_with_unreached_terminal_action_is_not_goal_complete(self) -> None:
helper = TestCredentialScoutGapMatcher
- trajectory = self._trajectory(
- helper._fill("cred_1", "username", helper._PAGE_ONE),
- helper._click(helper._PAGE_ONE),
- )
- ctx = self._gate_ctx(trajectory)
+ ctx = self._login_prefix_ctx(self._terminal_action_criterion())
+ ctx.scout_trajectory = list(ctx.scout_trajectory) + [
+ helper._fill("cred_1", "totp", helper._PAGE_TWO),
+ helper._click(helper._PAGE_TWO),
+ ]
+ ctx.scouted_credential_field_inventory_by_credential_id = {
+ "cred_1": frozenset({"username", "password", "totp"})
+ }
+ assert enforcement_module.reached_terminal_action_criterion_ids(ctx) == set()
+ enforcement_module.record_reached_terminal_action_observation(ctx)
+ assert ctx.scout_observed_terminal_criterion_ids == set()
assert enforcement_module.synthesized_trajectory_is_goal_complete(ctx) is False
- errors = workflow_update_module._credentialed_code_block_scout_gate_errors(self._TWO_FIELD_LOGIN_YAML, ctx)
- assert errors
- assert "password" in errors[0]
class TestCredentialScoutReopenSeam:
@@ -16099,6 +17158,394 @@ def test_reconcile_scout_interaction_positional_map_skips_witness_rows() -> None
assert period is not None and period["selector"] == "#period"
+class TestSynthesizedParameterMultiFillReconciliation:
+ def _reconcile(
+ self,
+ *,
+ submitted_code: str,
+ synthesized_parameters: list[dict[str, str]],
+ scout_trajectory: list[dict[str, object]],
+ ) -> tuple[dict[str, object], object]:
+ parsed: dict[str, object] = {"workflow_definition": {"parameters": [], "blocks": []}}
+ code_block: dict[str, object] = {"label": "search_directory", "code": submitted_code}
+ reconciliation = workflow_update_module._reconcile_synthesized_parameters(
+ parsed=parsed,
+ code_block=code_block,
+ submitted_code=submitted_code,
+ synthesized_parameters=synthesized_parameters,
+ scout_trajectory=scout_trajectory,
+ )
+ return parsed, reconciliation
+
+ def test_divergent_names_auto_declare_reusable_required_rows(self) -> None:
+ parsed, reconciliation = self._reconcile(
+ submitted_code='await page.locator("#submit").click()',
+ synthesized_parameters=[
+ {"key": "address_city_county_or_zip_code"},
+ {"key": "provider_specialty"},
+ ],
+ scout_trajectory=[
+ {"tool_name": "type_text", "selector": "#location", "typed_length": 7},
+ {"tool_name": "type_text", "selector": "#specialty", "typed_length": 10},
+ ],
+ )
+
+ assert reconciliation.violations == []
+ assert reconciliation.repair_context is None
+ assert reconciliation.parameter_keys == ["address_city_county_or_zip_code", "provider_specialty"]
+ assert parsed["workflow_definition"]["parameters"] == [
+ {
+ "parameter_type": "workflow",
+ "workflow_parameter_type": "string",
+ "key": "address_city_county_or_zip_code",
+ },
+ {"parameter_type": "workflow", "workflow_parameter_type": "string", "key": "provider_specialty"},
+ ]
+
+ def test_duplicate_key_multi_fill_still_fails_closed(self) -> None:
+ parsed, reconciliation = self._reconcile(
+ submitted_code='await page.locator("#submit").click()',
+ synthesized_parameters=[
+ {"key": "address_city_county_or_zip_code"},
+ {"key": "address_city_county_or_zip_code"},
+ ],
+ scout_trajectory=[
+ {"tool_name": "type_text", "selector": "#location", "typed_length": 7},
+ {"tool_name": "type_text", "selector": "#location_again", "typed_length": 7},
+ ],
+ )
+
+ assert any("literal binding is ambiguous" in violation for violation in reconciliation.violations)
+ assert parsed["workflow_definition"]["parameters"] == []
+ assert reconciliation.repair_context is not None
+ assert reconciliation.repair_context.reason_code == "synthesized_parameter_binding_ambiguous"
+
+ @pytest.mark.asyncio
+ async def test_relaxed_multi_fill_binding_still_fails_closed_on_empty_envelope(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _code_only_ctx()
+ _enable_imposition(ctx)
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "type_text",
+ "selector": "#location",
+ "source_url": "https://example.com/directory",
+ "typed_length": 7,
+ "role": "textbox",
+ "accessible_name": "Address City County or Zip Code",
+ "trajectory_index": 0,
+ },
+ {
+ "tool_name": "type_text",
+ "selector": "#specialty",
+ "source_url": "https://example.com/directory",
+ "typed_length": 10,
+ "role": "textbox",
+ "accessible_name": "Provider Specialty",
+ "trajectory_index": 1,
+ },
+ {
+ "tool_name": "click",
+ "selector": "#search",
+ "source_url": "https://example.com/directory",
+ "role": "button",
+ "accessible_name": "Search",
+ "trajectory_index": 2,
+ },
+ ]
+ submitted = _yaml(
+ """
+ title: Directory lookup
+ workflow_definition:
+ parameters:
+ - {parameter_type: output, key: directory_result}
+ blocks:
+ - block_type: code
+ label: search_directory
+ prompt: Search the directory and return structured provider result data.
+ code: |
+ await page.locator("#location").fill("Raleigh")
+ await page.locator("#specialty").fill("Cardiology")
+ await page.locator("#search").click()
+ """
+ )
+
+ result = await _update_workflow({"workflow_yaml": submitted}, ctx)
+
+ assert result["ok"] is False
+ assert "synthesized_parameter_binding_ambiguous" not in json.dumps(result)
+ assert "must pass `code_artifact_metadata`" in result["error"]
+ assert ctx.workflow_yaml == ""
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "metadata_reject"
+
+ def _directory_output_intent_yaml(self) -> str:
+ return _yaml(
+ """
+ title: Directory lookup
+ workflow_definition:
+ parameters:
+ - {parameter_type: output, key: directory_result}
+ blocks:
+ - block_type: code
+ label: search_directory
+ prompt: Search the directory and return structured provider result data.
+ code: |
+ await page.locator("#search").click()
+ """
+ )
+
+ def test_co_computed_metadata_contract_surfaces_when_output_contract_deficient(self) -> None:
+ ctx = _code_only_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ CompletionCriterion(id="c1", outcome="return the provider npi", output_path="provider.npi")
+ ]
+ )
+
+ contract = workflow_update_module._co_computed_metadata_repair_contract(
+ ctx, self._directory_output_intent_yaml(), None
+ )
+
+ assert contract is not None
+ assert contract["block_label"] == "search_directory"
+ assert any(path == "provider.npi" for path in contract["required_goal_value_paths"])
+
+ def test_co_computed_metadata_contract_is_none_without_output_intent(self) -> None:
+ ctx = _code_only_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ CompletionCriterion(id="c1", outcome="return the provider npi", output_path="provider.npi")
+ ]
+ )
+ workflow_yaml = _yaml(
+ """
+ title: Directory lookup
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: open_directory
+ code: |
+ await page.goto("https://example.com/directory")
+ """
+ )
+
+ contract = workflow_update_module._co_computed_metadata_repair_contract(ctx, workflow_yaml, None)
+
+ assert contract is None
+
+ def test_co_computed_metadata_contract_labels_output_intent_block_in_multi_block(self) -> None:
+ # In a multi-block workflow the metadata-missing block is not necessarily the imposed carrier;
+ # the repair hint must point at the block that actually owns the output, derived from the yaml.
+ ctx = _code_only_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ CompletionCriterion(id="c1", outcome="return the provider npi", output_path="provider.npi")
+ ]
+ )
+ workflow_yaml = _yaml(
+ """
+ title: Directory lookup
+ workflow_definition:
+ parameters:
+ - {parameter_type: output, key: directory_result}
+ blocks:
+ - block_type: code
+ label: open_directory
+ code: |
+ await page.goto("https://example.com/directory")
+ - block_type: code
+ label: read_provider
+ prompt: Search the directory and return structured provider result data.
+ code: |
+ npi = (await page.locator("#npi").inner_text()).strip()
+ return {"provider": {"npi": npi}}
+ """
+ )
+
+ contract = workflow_update_module._co_computed_metadata_repair_contract(ctx, workflow_yaml, None)
+
+ assert contract is not None
+ assert contract["block_label"] == "read_provider"
+
+ def _owned_carrier_ctx(self) -> CopilotContext:
+ ctx = _code_only_ctx()
+ ctx.spine_imposition_owned_attempt = True
+ ctx.spine_imposition_carrier_label = "search_directory"
+ return ctx
+
+ def _carrier_yaml(self, code: str) -> str:
+ return _yaml(
+ f"""
+ title: Directory lookup
+ workflow_definition:
+ parameters:
+ - {{parameter_type: output, key: directory_result}}
+ blocks:
+ - block_type: code
+ label: search_directory
+ prompt: Search the directory and return structured provider result data.
+ code: |
+ {code}
+ """
+ )
+
+ def test_owned_carrier_keyed_output_forms_goal_value_paths_when_union_empty(self) -> None:
+ ctx = self._owned_carrier_ctx()
+ workflow_yaml = self._carrier_yaml(
+ 'npi = (await page.locator("#npi").inner_text()).strip()\n'
+ ' return {"provider": {"npi": npi}}'
+ )
+
+ scaffolded, scaffold_applied = workflow_update_module._scaffold_metadata_contract_for_update(
+ ctx, workflow_yaml, None
+ )
+
+ assert scaffold_applied is True
+ assert json.dumps(scaffolded).count("provider.npi") > 0
+ assert workflow_update_module._missing_code_artifact_metadata_error(workflow_yaml, ctx, scaffolded) is None
+
+ def test_owned_carrier_without_keyed_output_stays_fail_closed(self) -> None:
+ ctx = self._owned_carrier_ctx()
+ workflow_yaml = self._carrier_yaml('await page.locator("#search").click()')
+
+ scaffolded, scaffold_applied = workflow_update_module._scaffold_metadata_contract_for_update(
+ ctx, workflow_yaml, None
+ )
+
+ assert scaffold_applied is False
+ assert scaffolded is None
+ assert workflow_update_module._missing_code_artifact_metadata_error(workflow_yaml, ctx, scaffolded) is not None
+
+ def test_non_owned_carrier_does_not_form_metadata(self) -> None:
+ ctx = self._owned_carrier_ctx()
+ ctx.spine_imposition_owned_attempt = False
+ workflow_yaml = self._carrier_yaml(
+ 'npi = (await page.locator("#npi").inner_text()).strip()\n'
+ ' return {"provider": {"npi": npi}}'
+ )
+
+ scaffolded, scaffold_applied = workflow_update_module._scaffold_metadata_contract_for_update(
+ ctx, workflow_yaml, None
+ )
+
+ assert scaffold_applied is False
+ assert workflow_update_module._missing_code_artifact_metadata_error(workflow_yaml, ctx, scaffolded) is not None
+
+ def _divergent_multi_fill_scout(self) -> list[dict[str, object]]:
+ return [
+ {
+ "tool_name": "type_text",
+ "selector": "#location",
+ "source_url": "https://example.com/directory",
+ "typed_length": 7,
+ "role": "textbox",
+ "accessible_name": "Address City County or Zip Code",
+ "trajectory_index": 0,
+ },
+ {
+ "tool_name": "type_text",
+ "selector": "#specialty",
+ "source_url": "https://example.com/directory",
+ "typed_length": 10,
+ "role": "textbox",
+ "accessible_name": "Provider Specialty",
+ "trajectory_index": 1,
+ },
+ {
+ "tool_name": "click",
+ "selector": "#search",
+ "source_url": "https://example.com/directory",
+ "role": "button",
+ "accessible_name": "Search",
+ "trajectory_index": 2,
+ },
+ ]
+
+ def _divergent_multi_fill_yaml(self, *, keyed_return: bool) -> str:
+ tail = (
+ '\n npi = (await page.locator("#npi").inner_text()).strip()'
+ '\n return {"provider": {"npi": npi}}'
+ if keyed_return
+ else ""
+ )
+ return _yaml(
+ f"""
+ title: Directory lookup
+ workflow_definition:
+ parameters:
+ - {{parameter_type: output, key: directory_result}}
+ blocks:
+ - block_type: code
+ label: search_directory
+ prompt: Search the directory and return structured provider result data.
+ code: |
+ await page.locator("#location").fill("Raleigh")
+ await page.locator("#specialty").fill("Cardiology")
+ await page.locator("#search").click(){tail}
+ """
+ )
+
+ @pytest.mark.asyncio
+ async def test_two_repair_rounds_never_realternate_to_binding_reject(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _code_only_ctx()
+ _enable_imposition(ctx)
+ ctx.scout_trajectory = self._divergent_multi_fill_scout()
+
+ first = await _update_workflow({"workflow_yaml": self._divergent_multi_fill_yaml(keyed_return=False)}, ctx)
+
+ assert first["ok"] is False
+ assert "synthesized_parameter_binding_ambiguous" not in json.dumps(first)
+ assert "must pass `code_artifact_metadata`" in first["error"]
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "metadata_reject"
+
+ schema = workflow_update_module._schema_template_text_for_required_paths({"provider.npi"})
+ repaired_metadata = [
+ {
+ "block_label": "search_directory",
+ "declared_goal": "return the provider npi",
+ "claimed_outcomes": [
+ {
+ "id": "claim:search_directory",
+ "scope": "outcome",
+ "text": "return the provider npi",
+ "status": "observed_not_verified",
+ "goal_value_paths": ["provider.npi"],
+ "extraction_schema": schema,
+ }
+ ],
+ "terminal_verifier_expectations": [
+ {
+ "id": "expectation:search_directory",
+ "text": "return the provider npi",
+ "goal_value_paths": ["provider.npi"],
+ "extraction_schema": schema,
+ }
+ ],
+ }
+ ]
+
+ second = await _update_workflow(
+ {
+ "workflow_yaml": self._divergent_multi_fill_yaml(keyed_return=True),
+ "code_artifact_metadata": repaired_metadata,
+ },
+ ctx,
+ )
+
+ assert "synthesized_parameter_binding_ambiguous" not in json.dumps(second)
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.reason_code != "synthesized_parameter_binding_ambiguous"
+ # The two author-time rejects no longer alternate. This block's code fills hardcoded literals
+ # rather than the synthesized parameters, so it terminates with a single honest fail-closed
+ # reject (literal grounding is out of this ticket's plane); it does not oscillate to the ceiling.
+ assert second["ok"] is False
+
+
def _goal_reaching_freehand_ctx(*, credential: bool = False) -> CopilotContext:
ctx = _code_only_ctx()
_enable_imposition(ctx)
diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.py
index b217e2b86..4d292c1ad 100644
--- a/tests/unit/test_copilot_code_block_synthesis.py
+++ b/tests/unit/test_copilot_code_block_synthesis.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import ast
import asyncio
+import hashlib
import json
import keyword
import sys
@@ -44,6 +45,7 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (
build_synthesized_artifact_metadata,
code_contains_credential_fill,
credential_scout_gap,
+ grounded_submit_rung_binding_fingerprint,
input_correspondences_for_interaction,
is_optional_dismissal_only_trajectory,
obligation_finding_reason_code,
@@ -95,6 +97,110 @@ def _interaction(tool_name: str, **fields: Any) -> dict[str, Any]:
return {"tool_name": tool_name, **fields}
+def _submit_rung_binding(
+ interaction: dict[str, Any],
+ *,
+ trajectory_index: int,
+ fields: list[dict[str, str]],
+) -> dict[str, Any]:
+ repeated_structural_key = "recorded-p5-key"
+ return {
+ "repeated_structural_key": repeated_structural_key,
+ "field_bindings": fields,
+ "fingerprint": grounded_submit_rung_binding_fingerprint(
+ repeated_structural_key=repeated_structural_key,
+ source_url=str(interaction["source_url"]),
+ submit_selector=str(interaction["selector"]),
+ submit_trajectory_index=trajectory_index,
+ field_bindings=fields,
+ ),
+ }
+
+
+def test_grounded_submit_rung_binding_changes_candidate_and_preserves_trajectory() -> None:
+ trajectory = [
+ _interaction("click", selector="#open", source_url="https://example.com/form", trajectory_index=0),
+ _interaction("click", selector="#submit", source_url="https://example.com/form", trajectory_index=1),
+ ]
+ plain = synthesize_code_block(trajectory, strict_selectors=True)
+ fields = [
+ {"parameter_key": "company_name", "field_selector": "#company"},
+ {"parameter_key": "contact_email", "field_selector": "#email"},
+ ]
+ trajectory[1]["submit_rung_binding"] = _submit_rung_binding(trajectory[1], trajectory_index=1, fields=fields)
+ original = [dict(interaction) for interaction in trajectory]
+
+ result = synthesize_code_block(trajectory, strict_selectors=True)
+
+ assert plain is not None
+ assert result is not None
+ assert trajectory == original
+ assert hashlib.sha256(plain.code.encode()).hexdigest() == (
+ "9703bf1b2b7a0a9a2e8145f89055e20c312a3cf2d6b0dc9a34d4d325bba6361f"
+ )
+ assert result.code != plain.code
+ assert result.code.index('page.locator("#company").fill(str(company_name))') < result.code.index(
+ 'page.locator("#submit").click()'
+ )
+ assert result.code.index('page.locator("#email").fill(str(contact_email))') < result.code.index(
+ 'page.locator("#submit").click()'
+ )
+ assert {parameter["key"] for parameter in result.parameters} == {"company_name", "contact_email"}
+ assert result.diagnostics.grounded_submit_binding_fingerprints == [
+ trajectory[1]["submit_rung_binding"]["fingerprint"]
+ ]
+ assert [record["trajectory_index"] for record in result.diagnostics.emitted_interactions] == [0, 1]
+
+
+def test_grounded_submit_rung_binding_targets_exact_submit_trajectory_index() -> None:
+ trajectory = [
+ _interaction("click", selector="#submit", source_url="https://example.com/landing", trajectory_index=0),
+ _interaction("click", selector="#open", source_url="https://example.com/form", trajectory_index=1),
+ _interaction("click", selector="#submit", source_url="https://example.com/form", trajectory_index=2),
+ ]
+ fields = [{"parameter_key": "company_name", "field_selector": "#company"}]
+ trajectory[2]["submit_rung_binding"] = _submit_rung_binding(trajectory[2], trajectory_index=2, fields=fields)
+
+ result = synthesize_code_block(trajectory, strict_selectors=True)
+
+ assert result is not None
+ first_submit = result.code.index('page.locator("#submit").click()')
+ fill = result.code.index('page.locator("#company").fill(str(company_name))')
+ second_submit = result.code.rindex('page.locator("#submit").click()')
+ assert first_submit < fill < second_submit
+
+
[email protected]("mutation", ["incomplete", "leftover", "fingerprint"])
+def test_grounded_submit_rung_binding_fails_closed_on_invalid_bundle(mutation: str) -> None:
+ interaction = _interaction("click", selector="#submit", source_url="https://example.com/form", trajectory_index=0)
+ fields = [{"parameter_key": "company_name", "field_selector": "#company"}]
+ interaction["submit_rung_binding"] = _submit_rung_binding(interaction, trajectory_index=0, fields=fields)
+ trajectory = [interaction]
+ if mutation == "incomplete":
+ interaction["submit_rung_binding"]["field_bindings"] = []
+ elif mutation == "leftover":
+ trajectory.append(
+ _interaction(
+ "click",
+ selector="#second-submit",
+ source_url="https://example.com/form",
+ trajectory_index=1,
+ submit_rung_binding=_submit_rung_binding(
+ {
+ "selector": "#second-submit",
+ "source_url": "https://example.com/form",
+ },
+ trajectory_index=1,
+ fields=[{"parameter_key": "contact_email", "field_selector": "#email"}],
+ ),
+ )
+ )
+ else:
+ interaction["submit_rung_binding"]["fingerprint"] = "stale"
+
+ assert synthesize_code_block(trajectory, strict_selectors=True) is None
+
+
def _extraction_plan() -> RequestedOutputExtractionPlan:
return RequestedOutputExtractionPlan(
requested_output_paths=(
diff --git a/tests/unit/test_copilot_completion_verification.py b/tests/unit/test_copilot_completion_verification.py
index 9323edce8..157d91174 100644
--- a/tests/unit/test_copilot_completion_verification.py
+++ b/tests/unit/test_copilot_completion_verification.py
@@ -60,6 +60,7 @@ from skyvern.forge.sdk.copilot.completion_verification import (
grade_structured_record_criteria,
grade_terminal_goal_record_criteria,
grade_validation_classification_criteria,
+ is_registered_download_completion_criterion,
only_degraded_blocking,
registered_download_completion_criterion,
run_plane_all_no_evidence,
@@ -9903,6 +9904,13 @@ def test_snapshot_summarizes_registered_download_outputs() -> None:
assert "RecordingLocator" not in rendered and "Download" not in rendered and "secret" not in rendered
+_REGISTERED_DOWNLOAD_OUTPUT: dict[str, Any] = {
+ "downloaded_files": [{"filename": "statement.pdf"}],
+ "downloaded_file_urls": [],
+ "downloaded_file_artifact_ids": [],
+}
+
+
def _download_result(output: dict[str, Any]) -> dict:
return {
"ok": True,
@@ -10430,6 +10438,118 @@ def test_download_reconciliation_does_not_mutate_request_policy() -> None:
assert ctx.request_policy.completion_criteria == []
+def test_reconciliation_carries_requested_output_identity_for_minted_ask() -> None:
+ ctx = _run_ctx()
+ minted = _criterion(
+ "c_download",
+ "The finished workflow produces the downloaded file.",
+ output_path="output.downloaded_files",
+ deliverable_kind="registered_download",
+ requested_output_path_mint_source="classifier_default",
+ )
+ ctx.request_policy = RequestPolicy(completion_criteria=[minted])
+
+ reconciled = _reconcile_download_completion_criterion(ctx, _download_result(_REGISTERED_DOWNLOAD_OUTPUT), [minted])
+
+ carried = [criterion for criterion in reconciled if is_registered_download_completion_criterion(criterion)]
+ assert [criterion.output_path for criterion in reconciled] == [None]
+ assert len(carried) == 1
+ assert carried[0].requested_output_path_mint_source == "classifier_default"
+
+
+def test_reconciliation_incidental_download_stays_uncounted() -> None:
+ ctx = _run_ctx()
+ ctx.request_policy = RequestPolicy(completion_criteria=[])
+
+ reconciled = _reconcile_download_completion_criterion(ctx, _download_result(_REGISTERED_DOWNLOAD_OUTPUT), [])
+
+ carried = [criterion for criterion in reconciled if is_registered_download_completion_criterion(criterion)]
+ assert len(carried) == 1
+ assert carried[0].requested_output_path_mint_source is None
+
+
+async def test_minted_download_ask_counts_as_requested_output_and_verifies(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def fail_handler(**_: object) -> object:
+ raise AssertionError("registered download evidence must bypass the judge")
+
+ _patch_completion_handler(monkeypatch, fail_handler)
+ ctx = _run_ctx()
+ _set_workflow_labels(ctx, "download_document")
+ minted = _criterion(
+ "c_download",
+ "The finished workflow produces the downloaded file.",
+ output_path="output.downloaded_files",
+ deliverable_kind="registered_download",
+ requested_output_path_mint_source="classifier_default",
+ )
+ ctx.request_policy = RequestPolicy(completion_criteria=list(criteria_from_json(criteria_to_json([minted]))))
+
+ verification = await _maybe_run_completion_verification(
+ ctx, _download_result(_REGISTERED_DOWNLOAD_OUTPUT), time.monotonic()
+ )
+
+ assert verification is not None
+ assert verification.is_fully_satisfied() is True
+ assert verification.criterion_ids == [REGISTERED_DOWNLOAD_COMPLETION_CRITERION_ID]
+ assert verification.requested_output_criteria_count == 1
+ assert zero_requested_output_criteria_credit(verification, has_meaningful_registered_output=True) is False
+
+
+async def test_incidental_download_without_ask_stays_credit_withheld(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def fail_handler(**_: object) -> object:
+ raise AssertionError("registered download evidence must bypass the judge")
+
+ _patch_completion_handler(monkeypatch, fail_handler)
+ ctx = _run_ctx()
+ _set_workflow_labels(ctx, "download_document")
+ ctx.request_policy = RequestPolicy(completion_criteria=[])
+
+ verification = await _maybe_run_completion_verification(
+ ctx, _download_result(_REGISTERED_DOWNLOAD_OUTPUT), time.monotonic()
+ )
+
+ assert verification is not None
+ assert verification.criterion_ids == [REGISTERED_DOWNLOAD_COMPLETION_CRITERION_ID]
+ assert verification.requested_output_criteria_count == 0
+ assert zero_requested_output_criteria_credit(verification, has_meaningful_registered_output=True) is True
+
+
+async def test_predeploy_persisted_download_ask_is_undercredited_until_reminted(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def fail_handler(**_: object) -> object:
+ raise AssertionError("registered download evidence must bypass the judge")
+
+ _patch_completion_handler(monkeypatch, fail_handler)
+ ctx = _run_ctx()
+ _set_workflow_labels(ctx, "download_document")
+ minted = _criterion(
+ "c_download",
+ "The finished workflow produces the downloaded file.",
+ output_path="output.downloaded_files",
+ deliverable_kind="registered_download",
+ requested_output_path_mint_source="classifier_default",
+ )
+ predeploy_json = criteria_to_json([minted])
+ del predeploy_json[0]["requested_output_path_mint_source"]
+ ctx.request_policy = RequestPolicy(completion_criteria=list(criteria_from_json(predeploy_json)))
+
+ verification = await _maybe_run_completion_verification(
+ ctx, _download_result(_REGISTERED_DOWNLOAD_OUTPUT), time.monotonic()
+ )
+
+ assert verification is not None
+ assert verification.requested_output_criteria_count == 0
+ assert zero_requested_output_criteria_credit(verification, has_meaningful_registered_output=True) is True
+
+
def test_download_grader_requires_non_empty_registered_surface() -> None:
criteria = [registered_download_completion_criterion()]
diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.py
index a07a45778..64afac334 100644
--- a/tests/unit/test_copilot_enforcement_pruning.py
+++ b/tests/unit/test_copilot_enforcement_pruning.py
@@ -144,6 +144,7 @@ class _Ctx:
self.synthesized_goal_complete_landed = False
self.impose_synthesized_code_block = False
self.scouted_output_covered_paths: set[str] = set()
+ self.scout_observed_terminal_criterion_ids: set[str] = set()
self.scout_observation_contract: object | None = None
self.flow_evidence: list[dict[str, object]] = []
self.copilot_config: CopilotConfig | None = None
@@ -2460,6 +2461,101 @@ class TestScoutOutputCoverageGate:
assert uncovered_requested_output_paths(ctx) == set()
assert synthesized_trajectory_is_goal_complete(ctx) is True
+ def test_independent_run_evidence_is_exempt_while_runtime_output_stays_gated(self) -> None:
+ independent = CompletionCriterion(
+ id="output.login_gate_present",
+ outcome="whether a login gate blocked the target is recorded",
+ output_path="output.login_gate_present",
+ requested_output_evidence_source="independent_run_evidence",
+ )
+ runtime = _criterion("output.document_name", "the order status document name is captured")
+ ctx = self._authoring_ctx(independent, runtime)
+
+ assert uncovered_requested_output_paths(ctx) == {"output.document_name"}
+ assert synthesized_trajectory_is_goal_complete(ctx) is False
+
+ def test_independent_run_evidence_is_exempt_from_repair_context(self) -> None:
+ independent = CompletionCriterion(
+ id="output.login_gate_present",
+ outcome="whether a login gate blocked the target is recorded",
+ output_path="output.login_gate_present",
+ requested_output_evidence_source="independent_run_evidence",
+ )
+ runtime = _criterion("output.document_name", "the order status document name is captured")
+ ctx = self._authoring_ctx(independent, runtime)
+ ctx.last_code_authoring_repair_context = CodeAuthoringRepairContext(
+ block_label="extract_order",
+ reason_code="metadata_reject",
+ required_goal_value_paths=["login_gate_present", "document_name"],
+ )
+
+ assert uncovered_requested_output_paths(ctx) == {"output.document_name"}
+
+ @pytest.mark.parametrize(
+ "evidence_source",
+ ["registered_output_parameter", "registered_artifact_content"],
+ )
+ def test_registered_post_run_evidence_remains_uncovered_from_repair_context(
+ self,
+ evidence_source: str,
+ ) -> None:
+ registered = CompletionCriterion(
+ id="output.confirmation_number",
+ outcome="the confirmation number is registered after the run",
+ output_path="output.confirmation_number",
+ requested_output_evidence_source=evidence_source,
+ )
+ ctx = self._authoring_ctx(registered)
+ ctx.last_code_authoring_repair_context = CodeAuthoringRepairContext(
+ block_label="extract_order",
+ reason_code="metadata_reject",
+ required_goal_value_paths=["confirmation_number"],
+ )
+
+ assert uncovered_requested_output_paths(ctx) == {"output.confirmation_number"}
+
+ @pytest.mark.parametrize(
+ "evidence_source",
+ ["registered_output_parameter", "registered_artifact_content"],
+ )
+ def test_registered_post_run_evidence_stays_gated_when_independent_evidence_uses_same_repair_path(
+ self,
+ evidence_source: str,
+ ) -> None:
+ independent = CompletionCriterion(
+ id="independent_confirmation_number",
+ outcome="the confirmation number is confirmed by an independent run",
+ output_path="output.confirmation_number",
+ requested_output_evidence_source="independent_run_evidence",
+ )
+ registered = CompletionCriterion(
+ id="registered_confirmation_number",
+ outcome="the confirmation number is registered after the run",
+ output_path="output.confirmation_number",
+ requested_output_evidence_source=evidence_source,
+ )
+ ctx = self._authoring_ctx(independent, registered)
+ ctx.last_code_authoring_repair_context = CodeAuthoringRepairContext(
+ block_label="extract_order",
+ reason_code="metadata_reject",
+ required_goal_value_paths=["confirmation_number"],
+ )
+
+ assert uncovered_requested_output_paths(ctx) == {"output.confirmation_number"}
+
+ def test_runtime_output_stays_gated_when_independent_evidence_uses_same_path(self) -> None:
+ independent = CompletionCriterion(
+ id="independent_document_name",
+ outcome="the document name is confirmed by an independent run",
+ output_path="output.document_name",
+ requested_output_evidence_source="independent_run_evidence",
+ )
+ runtime = _criterion("output.document_name", "the order status document name is captured")
+ ctx = self._authoring_ctx(independent, runtime)
+
+ assert uncovered_requested_output_paths(ctx) == {"output.document_name"}
+ assert synthesized_trajectory_is_goal_complete(ctx) is False
+
def test_runtime_output_stays_gated_alongside_exempt_source(self) -> None:
registered = CompletionCriterion(
id="output.confirmation_number",
diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.py
index 3eedb779b..c08d310fe 100644
--- a/tests/unit/test_copilot_hooks.py
+++ b/tests/unit/test_copilot_hooks.py
@@ -1133,6 +1133,8 @@ class TestScoutedInteractionCapture:
browser_session_id=None,
scouted_interactions=[],
scout_trajectory=[],
+ scout_observed_terminal_criterion_ids=set(),
+ completion_criteria_turn_state=None,
observed_browser_urls=[],
pending_scout_source_url=source_url,
prior_fill_carry=[],
diff --git a/tests/unit/test_copilot_output_contract_actuation.py b/tests/unit/test_copilot_output_contract_actuation.py
index 96754e65b..b9a89a44f 100644
--- a/tests/unit/test_copilot_output_contract_actuation.py
+++ b/tests/unit/test_copilot_output_contract_actuation.py
@@ -1896,6 +1896,34 @@ def test_mint_degraded_output_path_leaves_observation_lane() -> None:
assert wu._output_contract_required_paths_source(ctx).union == set()
+def test_classifier_minted_download_path_excluded_from_author_coverage() -> None:
+ ctx = _antecedent_ctx(
+ CompletionCriterion(
+ id="c_download",
+ outcome="The invoice PDF is downloaded.",
+ output_path="output.downloaded_files",
+ deliverable_kind="registered_download",
+ requested_output_path_mint_source="classifier_default",
+ )
+ )
+
+ assert wu._requested_output_child_paths(ctx) == set()
+ assert wu._output_contract_required_paths_source(ctx).union == set()
+
+
+def test_non_minted_registered_download_path_still_requires_author_coverage() -> None:
+ ctx = _antecedent_ctx(
+ CompletionCriterion(
+ id="c_download",
+ outcome="The invoice PDF is downloaded.",
+ output_path="output.downloaded_files",
+ deliverable_kind="registered_download",
+ )
+ )
+
+ assert wu._requested_output_child_paths(ctx) == {"output.downloaded_files"}
+
+
def test_runtime_repair_contract_carries_declaration_lane_with_stable_signature() -> None:
ctx = _antecedent_ctx(
CompletionCriterion(
diff --git a/tests/unit/test_copilot_recorded_outcome_grounding.py b/tests/unit/test_copilot_recorded_outcome_grounding.py
index e0051ce6a..d8ae244df 100644
--- a/tests/unit/test_copilot_recorded_outcome_grounding.py
+++ b/tests/unit/test_copilot_recorded_outcome_grounding.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import json
from dataclasses import replace
from types import SimpleNamespace
@@ -7,6 +8,7 @@ import pytest
from structlog.testing import capture_logs
from skyvern.config import settings
+from skyvern.forge.sdk.copilot import tools as tools_module
from skyvern.forge.sdk.copilot.agent import _recorded_build_test_outcome_prompt
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, stash_blocker_signal
from skyvern.forge.sdk.copilot.build_test_outcome import (
@@ -633,6 +635,40 @@ def test_grounding_abstains_for_non_authoritative_or_missing_current_url_and_rec
)
+def test_author_time_churn_without_cached_url_requires_current_page_regrounding() -> None:
+ ctx = _ctx(_outcome(phase="author_time_reject", workflow_run_id=None))
+ ctx.observed_browser_urls = []
+ arm_recorded_outcome_grounding_requirement(ctx)
+
+ error = _tool_loop_error(ctx, "update_workflow", {"workflow_yaml": "workflow_definition: {blocks: []}"})
+
+ assert error is not None
+ assert ctx.blocker_signal.internal_reason_code == "recorded_outcome_grounding_required"
+
+
+async def test_update_and_run_entrypoint_regrounds_before_third_preflight(monkeypatch: pytest.MonkeyPatch) -> None:
+ ctx = _ctx(_outcome(phase="author_time_reject", workflow_run_id=None))
+ ctx.observed_browser_urls = []
+ arm_recorded_outcome_grounding_requirement(ctx)
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ monkeypatch.setattr(
+ tools_module,
+ "_metadata_contract_run_preflight_reject",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("third preflight reject")),
+ )
+
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps({"workflow_yaml": "workflow_definition: {blocks: []}", "block_labels": []}),
+ )
+
+ assert json.loads(result)["ok"] is False
+ assert ctx.blocker_signal.internal_reason_code == "recorded_outcome_grounding_required"
+ assert len(ctx.recorded_build_test_outcome_history) == 2
+
+
def test_no_run_grounding_requires_fresh_post_arm_inspect_evidence() -> None:
outcome = _outcome(phase="scout_evaluate", workflow_run_id=None, attempted_tool="evaluate")
ctx = _ctx(outcome)
@@ -734,6 +770,19 @@ def test_satisfy_binds_typed_constraint_with_frontier_facet_and_owning_blocks()
assert "frontier_facet: selector_frontier" in prompt
+def test_definition_contract_unsatisfied_binds_amend_in_place_frontier() -> None:
+ outcome = _outcome(reason_code="definition_contract_unsatisfied")
+ ctx = _ctx(outcome)
+ ctx.workflow_yaml = _OWNING_BLOCK_WORKFLOW
+ arm_recorded_outcome_grounding_requirement(ctx)
+ ctx.composition_page_evidence = _bounded_inspect_evidence()
+
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
+ constraint = ctx.recorded_outcome_binding_constraint
+ assert isinstance(constraint, RecordedOutcomeBindingConstraint)
+ assert constraint.frontier_facet == "amend_in_place"
+
+
def test_degraded_capture_binds_uncrossable_constraint() -> None:
ctx = _binding_ctx()
arm_recorded_outcome_grounding_requirement(ctx)
diff --git a/tests/unit/test_copilot_request_policy_completion_criteria.py b/tests/unit/test_copilot_request_policy_completion_criteria.py
index 9525f80c2..243521a41 100644
--- a/tests/unit/test_copilot_request_policy_completion_criteria.py
+++ b/tests/unit/test_copilot_request_policy_completion_criteria.py
@@ -1415,6 +1415,64 @@ async def test_date_qualified_download_preserves_classifier_typed_value_and_shap
assert criteria[0].expected_output_shape == "date"
+ ("raw_criteria", "expected_count"),
+ [
+ pytest.param(
+ [
+ {
+ "outcome": "The returned record includes the requested bill.",
+ "output_path": "output.downloaded_file_artifact_ids",
+ "expected_output_value": "May 2026",
+ "expected_output_shape": "date",
+ "deliverable_kind": "registered_download",
+ }
+ ],
+ 1,
+ id="typed_value_single_download_stays_pathed",
+ ),
+ pytest.param(
+ [
+ {"outcome": "The first requested download is returned.", "deliverable_kind": "registered_download"},
+ {"outcome": "The second requested download is returned.", "deliverable_kind": "registered_download"},
+ ],
+ 0,
+ id="multi_file_download_stays_pathless",
+ ),
+ pytest.param(
+ [{"outcome": "The task completes successfully."}],
+ 0,
+ id="incidental_no_ask_earns_no_requested_output",
+ ),
+ pytest.param(
+ [{"outcome": "The requested download is returned.", "deliverable_kind": "registered_download"}],
+ 1,
+ id="lone_presence_only_download_mints_requested_output",
+ ),
+ ],
+)
+def test_registered_download_shape_matrix_stays_fail_closed(
+ raw_criteria: list[dict[str, Any]], expected_count: int
+) -> None:
+ policy = RequestPolicy(completion_criteria=_parse_completion_criteria(raw_criteria))
+
+ trace = policy.to_trace_data()
+
+ assert trace["requested_output_criteria_count"] == expected_count
+ if expected_count == 0:
+ assert all(criterion.output_path is None for criterion in policy.completion_criteria)
+
+
+def test_lone_presence_only_download_defaults_downloaded_files_path() -> None:
+ criteria = _parse_completion_criteria(
+ [{"outcome": "The requested download is returned.", "deliverable_kind": "registered_download"}]
+ )
+
+ assert len(criteria) == 1
+ assert criteria[0].output_path == "output.downloaded_files"
+ assert criteria[0].expected_output_value is None
+
+
@pytest.mark.parametrize(
("criterion_kwargs", "expected"),
[
@@ -1610,6 +1668,48 @@ def test_criteria_json_rehydrates_validation_classification_without_requested_ou
assert restored[0].expected_output_shape is None
+def _minted_download_criterion() -> CompletionCriterion:
+ return _criterion(
+ "c0",
+ "The finished workflow produces the downloaded file.",
+ output_path="output.downloaded_files",
+ deliverable_kind="registered_download",
+ requested_output_path_mint_source="classifier_default",
+ )
+
+
+def test_store_round_trip_preserves_requested_output_path_mint_source() -> None:
+ criteria = (_minted_download_criterion(),)
+
+ restored = criteria_from_json(criteria_to_json(criteria))
+
+ assert restored[0].requested_output_path_mint_source == "classifier_default"
+ assert restored == criteria
+
+
+def test_criteria_from_json_without_mint_source_key_loads_none() -> None:
+ restored = criteria_from_json(
+ [
+ {
+ "id": "c0",
+ "outcome": "The finished workflow produces the downloaded file.",
+ "output_path": "output.downloaded_files",
+ "deliverable_kind": "registered_download",
+ }
+ ]
+ )
+
+ assert len(restored) == 1
+ assert restored[0].requested_output_path_mint_source is None
+
+
+def test_requested_output_path_mint_source_excluded_from_reconcile_key() -> None:
+ minted = _minted_download_criterion()
+ persisted_twin = replace(minted, requested_output_path_mint_source=None)
+
+ assert _criterion_reconcile_key(minted) == _criterion_reconcile_key(persisted_twin)
+
+
def test_request_policy_trace_exposes_requested_output_grounding_contract_without_values() -> None:
policy = RequestPolicy(
completion_criteria=[
diff --git a/tests/unit/test_copilot_request_policy_prompt.py b/tests/unit/test_copilot_request_policy_prompt.py
index d60622354..894034aee 100644
--- a/tests/unit/test_copilot_request_policy_prompt.py
+++ b/tests/unit/test_copilot_request_policy_prompt.py
@@ -269,6 +269,75 @@ class TestRawSecretBackstop:
assert "AnotherFakePass456" not in redacted
assert redacted.count("[REDACTED_SECRET]") == 2
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "access_token=abc123DEF",
+ "client_secret=xyz789",
+ "refresh_token=r_1.2.3",
+ "id_token=eyJabc.def.ghi",
+ ],
+ )
+ def test_oauth_style_underscore_prefixed_keyword_assignments_are_redacted(self, message: str) -> None:
+ redacted = redact_raw_secrets_for_prompt(message)
+ secret_value = message.split("=", 1)[1]
+
+ assert secret_value not in redacted
+ assert "[REDACTED_SECRET]" in redacted
+
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "token=abc",
+ "password: hunter2",
+ "api_key = k3y",
+ "authorization: Bearer zzz",
+ ],
+ )
+ def test_existing_keyword_assignment_cases_still_redact(self, message: str) -> None:
+ redacted = redact_raw_secrets_for_prompt(message)
+ secret_value = message.split(":", 1)[1] if ":" in message else message.split("=", 1)[1]
+
+ assert secret_value.strip() not in redacted
+ assert "[REDACTED_SECRET]" in redacted
+
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "tokenizer = Tokenizer()",
+ "password_reset_flow()",
+ "the secretary emailed me",
+ "secretariat won",
+ ],
+ )
+ def test_non_secret_text_is_not_over_redacted(self, message: str) -> None:
+ assert redact_raw_secrets_for_prompt(message) == message
+
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "next_token=abc123",
+ "continuation_token=xyz789",
+ "page_token=p_1",
+ "next_page_token=np_2",
+ ],
+ )
+ def test_pagination_cursor_tokens_are_not_over_redacted(self, message: str) -> None:
+ assert redact_raw_secrets_for_prompt(message) == message
+
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "authorization: Bearer zzz_opaque_value",
+ "Authorization: Basic dXNlcjpwYXNzd29yZA",
+ ],
+ )
+ def test_scheme_prefixed_authorization_values_are_redacted(self, message: str) -> None:
+ redacted = redact_raw_secrets_for_prompt(message)
+ opaque_value = message.split()[-1]
+ assert opaque_value not in redacted
+ assert "[REDACTED_SECRET]" in redacted
+
class TestRawSecretRefusalSentinelConsistency:
"""Transcript redaction recognizes a prior raw-secret refusal by the sentinel
diff --git a/tests/unit/test_copilot_run_output_content_gate.py b/tests/unit/test_copilot_run_output_content_gate.py
index 466de5f23..01e4d81dc 100644
--- a/tests/unit/test_copilot_run_output_content_gate.py
+++ b/tests/unit/test_copilot_run_output_content_gate.py
@@ -837,6 +837,142 @@ async def test_registered_validation_review_output_from_dict_workflow_merges_int
assert verdicts[0].evidence_ref == "block_outputs:validate_business_start_service_review"
+async def test_dispatch_version_registered_output_identity_uses_exact_draft_and_rejects_ambiguity(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def fake_get_workflow_run_output_parameters(*, workflow_run_id: str) -> list[SimpleNamespace]:
+ assert workflow_run_id == "wr_dispatch"
+ return [
+ SimpleNamespace(
+ workflow_run_id="wr_dispatch",
+ output_parameter_id="op_dispatch",
+ value={"record_number": "1234567890"},
+ ),
+ SimpleNamespace(
+ workflow_run_id="wr_dispatch",
+ output_parameter_id="op_unknown",
+ value={"record_number": "ambiguous"},
+ ),
+ ]
+
+ monkeypatch.setattr(
+ run_execution.app.DATABASE,
+ "workflow_runs",
+ SimpleNamespace(get_workflow_run_output_parameters=fake_get_workflow_run_output_parameters),
+ )
+ source_workflow = SimpleNamespace(
+ organization_id="o",
+ workflow_definition=SimpleNamespace(
+ blocks=[
+ SimpleNamespace(
+ label="extract_record",
+ block_type="CODE",
+ output_parameter=SimpleNamespace(
+ output_parameter_id="op_source",
+ key="extract_record_output",
+ ),
+ )
+ ]
+ ),
+ )
+ dispatch_workflow = SimpleNamespace(
+ organization_id="o",
+ workflow_definition=SimpleNamespace(
+ blocks=[
+ SimpleNamespace(
+ label="extract_record",
+ block_type="CODE",
+ output_parameter=SimpleNamespace(
+ output_parameter_id="op_dispatch",
+ key="extract_record_output",
+ ),
+ )
+ ]
+ ),
+ )
+ data: dict[str, Any] = {"workflow_run_id": "wr_dispatch", "blocks": []}
+
+ by_label = await _attach_registered_output_parameter_values(
+ workflow_run_id="wr_dispatch",
+ workflow=source_workflow, # type: ignore[arg-type]
+ output_identity_workflow=dispatch_workflow, # type: ignore[arg-type]
+ data=data,
+ )
+
+ assert by_label == {"extract_record": {"extract_record_output": {"record_number": "1234567890"}}}
+ assert [item["output_parameter_id"] for item in data["registered_output_parameter_values"]] == ["op_dispatch"]
+ assert data["blocks"][0]["extracted_data"] == {"extract_record_output": {"record_number": "1234567890"}}
+
+
+async def test_inline_registered_output_identity_uses_runtime_override_when_persisted_ids_differ(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def fake_get_workflow_run_output_parameters(*, workflow_run_id: str) -> list[SimpleNamespace]:
+ assert workflow_run_id == "wr_inline"
+ return [
+ SimpleNamespace(
+ workflow_run_id="wr_inline",
+ output_parameter_id="op_runtime",
+ value={"record_number": "1234567890"},
+ )
+ ]
+
+ monkeypatch.setattr(
+ run_execution.app.DATABASE,
+ "workflow_runs",
+ SimpleNamespace(get_workflow_run_output_parameters=fake_get_workflow_run_output_parameters),
+ )
+ persisted_workflow = SimpleNamespace(
+ organization_id="o",
+ workflow_definition=SimpleNamespace(
+ blocks=[
+ SimpleNamespace(
+ label="extract_record",
+ block_type="CODE",
+ output_parameter=SimpleNamespace(
+ output_parameter_id="op_persisted",
+ key="extract_record_output",
+ ),
+ )
+ ]
+ ),
+ )
+ runtime_workflow = SimpleNamespace(
+ organization_id="o",
+ workflow_definition=SimpleNamespace(
+ blocks=[
+ SimpleNamespace(
+ label="extract_record",
+ block_type="CODE",
+ output_parameter=SimpleNamespace(
+ output_parameter_id="op_runtime",
+ key="extract_record_output",
+ ),
+ )
+ ]
+ ),
+ )
+ output_identity_workflow = run_execution._registered_output_identity_workflow(
+ dispatch_to_worker=False,
+ dispatch_workflow=None,
+ runtime_workflow=runtime_workflow, # type: ignore[arg-type]
+ )
+ data: dict[str, Any] = {"workflow_run_id": "wr_inline", "blocks": []}
+
+ by_label = await _attach_registered_output_parameter_values(
+ workflow_run_id="wr_inline",
+ workflow=persisted_workflow, # type: ignore[arg-type]
+ output_identity_workflow=output_identity_workflow,
+ data=data,
+ )
+
+ assert output_identity_workflow is runtime_workflow
+ assert by_label == {"extract_record": {"extract_record_output": {"record_number": "1234567890"}}}
+ assert [item["output_parameter_id"] for item in data["registered_output_parameter_values"]] == ["op_runtime"]
+
+
def test_satisfied_completion_prevents_empty_output_suspicious_success() -> None:
result = _empty_extraction_run_result()
ctx = _ctx(result["data"]["blocks"])
diff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.py
index 86694111b..4eccab36d 100644
--- a/tests/unit/test_copilot_scout_act_observe.py
+++ b/tests/unit/test_copilot_scout_act_observe.py
@@ -131,6 +131,7 @@ def _ctx(*, server: Any = None, source_url: str | None = _SOURCE_URL) -> SimpleN
copilot_config=None,
scout_observation_contract=None,
scouted_output_covered_paths=set(),
+ scout_observed_terminal_criterion_ids=set(),
)
@@ -1613,3 +1614,97 @@ class TestScoutPageObservationSignal:
scouting_module._record_scout_page_observation(ctx, {"forms": [{"fields": [{"selector": "#name"}]}]})
assert ctx.last_scout_observation_has_password_control is False
+
+
+class TestTerminalActionObservationStampSeam:
+ _PORTAL_URL = "https://portal.example.test/login"
+ _BUSINESS_URL = "https://portal.example.test/business/start-service"
+
+ @staticmethod
+ def _terminal_action_criterion(*, method_mandated: bool = False) -> CompletionCriterion:
+ return CompletionCriterion(
+ id="start_service_request",
+ outcome="the business start-service request reaches its review page",
+ kind="terminal_action",
+ terminal_action_family="request",
+ method_mandated=method_mandated,
+ )
+
+ def _ctx_with(self, *criteria: CompletionCriterion) -> AgentContext:
+ ctx = AgentContext(
+ organization_id="o_1",
+ workflow_id="w_1",
+ workflow_permanent_id="wpid_1",
+ workflow_yaml="",
+ browser_session_id="pbs_1",
+ stream=MagicMock(),
+ )
+ ctx.completion_criteria_turn_state = SimpleNamespace(decision=SimpleNamespace(criteria=tuple(criteria)))
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "fill_credential_field",
+ "credential_id": "cred_1",
+ "credential_field": "password",
+ "selector": "#password",
+ "source_url": self._PORTAL_URL,
+ "trajectory_index": 0,
+ },
+ {
+ "tool_name": "click",
+ "selector": "input[type='submit']",
+ "source_url": self._PORTAL_URL,
+ "trajectory_index": 1,
+ },
+ {
+ "tool_name": "type_text",
+ "selector": "#service-address",
+ "source_url": self._BUSINESS_URL,
+ "role": "textbox",
+ "accessible_name": "Service Address",
+ "trajectory_index": 2,
+ },
+ ]
+ return ctx
+
+ def test_commit_past_login_stamps_terminal_action_observation(self) -> None:
+ ctx = self._ctx_with(self._terminal_action_criterion())
+ with capture_logs() as logs:
+ scouting_module._record_scouted_interaction(
+ ctx,
+ tool_name="click",
+ selector="#find-address",
+ source_url=self._BUSINESS_URL,
+ role="button",
+ accessible_name="Find Address",
+ )
+ assert ctx.scout_observed_terminal_criterion_ids == {"start_service_request"}
+ assert [log for log in logs if log["event"] == "copilot_reached_terminal_action_observed"]
+
+ def test_login_only_commit_stamps_nothing(self) -> None:
+ ctx = self._ctx_with(self._terminal_action_criterion())
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "fill_credential_field",
+ "credential_id": "cred_1",
+ "credential_field": "password",
+ "selector": "#password",
+ "source_url": self._PORTAL_URL,
+ "trajectory_index": 0,
+ },
+ ]
+ scouting_module._record_scouted_interaction(
+ ctx, tool_name="click", selector="input[type='submit']", source_url=self._PORTAL_URL
+ )
+ assert ctx.scout_observed_terminal_criterion_ids == set()
+
+ def test_method_mandated_criterion_is_not_stamped(self) -> None:
+ ctx = self._ctx_with(self._terminal_action_criterion(method_mandated=True))
+ scouting_module._record_scouted_interaction(
+ ctx,
+ tool_name="click",
+ selector="#find-address",
+ source_url=self._BUSINESS_URL,
+ role="button",
+ accessible_name="Find Address",
+ )
+ assert ctx.scout_observed_terminal_criterion_ids == set()
diff --git a/tests/unit/test_file_download_targets.py b/tests/unit/test_file_download_targets.py
new file mode 100644
index 000000000..c8482e70a
--- /dev/null
+++ b/tests/unit/test_file_download_targets.py
@@ -0,0 +1,1526 @@
+from __future__ import annotations
+
+import hashlib
+import os
+import unicodedata
+from collections.abc import Callable
+from datetime import UTC, datetime
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+from urllib.parse import urlparse
+
+import pytest
+
+from skyvern.exceptions import AzureConfigurationError
+from skyvern.forge.sdk.api.llm.api_handler_factory import LLMAPIHandlerFactory
+from skyvern.forge.sdk.services import google_oauth_service
+from skyvern.forge.sdk.workflow.models.block import BaseTaskBlock, FileDownloadBlock
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
+from skyvern.forge.sdk.workflow.workflow_definition_converter import block_yaml_to_block
+from skyvern.schemas.workflows import (
+ BlockResult,
+ BlockStatus,
+ FileDownloadBlockYAML,
+ FileDownloadTarget,
+ FileStorageType,
+)
+
+
+def _output_parameter() -> OutputParameter:
+ now = datetime.now(UTC)
+ return OutputParameter(
+ output_parameter_id="download-output-id",
+ workflow_id="workflow-id",
+ key="download_output",
+ created_at=now,
+ modified_at=now,
+ )
+
+
+def _file_download_block(download_target: FileDownloadTarget, **kwargs: object) -> FileDownloadBlock:
+ return FileDownloadBlock(
+ label="download",
+ output_parameter=_output_parameter(),
+ navigation_goal="Download the requested files.",
+ download_target=download_target,
+ **kwargs,
+ )
+
+
+def _browser_result(
+ block: FileDownloadBlock,
+ *,
+ success: bool = True,
+ downloaded_filenames: tuple[str, ...] = (),
+) -> BlockResult:
+ return BlockResult(
+ success=success,
+ output_parameter=block.output_parameter,
+ output_parameter_value={
+ "task_id": "task-id",
+ "downloaded_files": [
+ {"filename": filename, "checksum": f"checksum-{filename}"} for filename in downloaded_filenames
+ ],
+ },
+ status=BlockStatus.completed if success else BlockStatus.failed,
+ failure_reason=None if success else "Browser download failed",
+ )
+
+
+def _write_downloads(directory: Path, *names: str) -> list[Path]:
+ directory.mkdir(parents=True, exist_ok=True)
+ files = [directory / name for name in names]
+ for file in files:
+ file.write_text(file.name)
+ return files
+
+
+async def _execute_file_download(
+ block: FileDownloadBlock,
+ browser_result: BlockResult,
+ download_dir: Path,
+ *,
+ selection_result: tuple[list[str], str] | None = None,
+ upload_side_effect: BaseException | None = None,
+ secret_values: dict[str, str] | None = None,
+ downloads_during_execute: tuple[str, ...] = (),
+ during_execute: Callable[[], None] | None = None,
+) -> SimpleNamespace:
+ workflow_run_context = MagicMock()
+ workflow_run_context.organization_id = "organization-id"
+ if secret_values is None:
+ secret_values = {
+ value: value
+ for value in (
+ block.aws_secret_access_key,
+ block.azure_storage_account_key,
+ block.sftp_password,
+ block.sftp_private_key,
+ block.sftp_private_key_passphrase,
+ )
+ if value
+ }
+ workflow_run_context.get_original_secret_value_or_none.side_effect = secret_values.get
+ upload = AsyncMock(return_value="customer://uploaded-file", side_effect=upload_side_effect)
+ select_files = AsyncMock()
+ if selection_result is not None:
+ select_files.return_value = selection_result
+ recorded_output = SimpleNamespace(value=None)
+
+ async def record_output_parameter_value(
+ _workflow_context: MagicMock,
+ _workflow_id: str,
+ value: object = None,
+ ) -> None:
+ recorded_output.value = value
+
+ record_output = AsyncMock(side_effect=record_output_parameter_value)
+
+ async def execute_browser(*args: object, **kwargs: object) -> BlockResult:
+ if during_execute is None:
+ _write_downloads(download_dir, *downloads_during_execute)
+ else:
+ during_execute()
+ await block.record_output_parameter_value(
+ workflow_run_context,
+ "workflow-run-id",
+ browser_result.output_parameter_value,
+ )
+ return browser_result
+
+ with (
+ patch.object(BaseTaskBlock, "execute", new_callable=AsyncMock, side_effect=execute_browser) as browser_execute,
+ patch.object(FileDownloadBlock, "record_output_parameter_value", record_output),
+ patch.object(FileDownloadBlock, "get_workflow_run_context", return_value=workflow_run_context),
+ patch.object(FileDownloadBlock, "_format_destination_template_parameters", return_value=None),
+ patch.object(FileDownloadBlock, "_select_files_to_upload_with_prompt", select_files),
+ patch(
+ "skyvern.forge.sdk.workflow.models.block.get_path_for_workflow_download_directory",
+ return_value=download_dir,
+ ),
+ patch("skyvern.forge.sdk.workflow.models.block.skyvern_context.current", return_value=None),
+ patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
+ ):
+ mock_app.AGENT_FUNCTION.upload_file_to_customer_storage = upload
+ mock_app.AGENT_FUNCTION.get_google_workspace_credentials = AsyncMock(
+ return_value=SimpleNamespace(token="google-access-token")
+ )
+ mock_app.DATABASE.observer.update_workflow_run_block = AsyncMock()
+ result = await block.execute(
+ workflow_run_id="workflow-run-id",
+ workflow_run_block_id="workflow-run-block-id",
+ organization_id="organization-id",
+ )
+
+ return SimpleNamespace(
+ result=result,
+ browser_execute=browser_execute,
+ upload=upload,
+ select_files=select_files,
+ workflow_run_context=workflow_run_context,
+ record_output=record_output,
+ recorded_output=recorded_output,
+ get_google_workspace_credentials=mock_app.AGENT_FUNCTION.get_google_workspace_credentials,
+ )
+
+
+async def test_website_target_returns_browser_result_without_dispatch(tmp_path: Path) -> None:
+ block = _file_download_block(FileDownloadTarget.WEBSITE)
+ browser_result = _browser_result(block)
+
+ execution = await _execute_file_download(block, browser_result, tmp_path / "downloads")
+
+ assert execution.result is browser_result
+ execution.browser_execute.assert_awaited_once()
+ execution.upload.assert_not_awaited()
+
+
+async def test_sftp_target_dispatches_each_download_and_preserves_browser_result(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ downloaded_files = [download_dir / "invoice.pdf", download_dir / "report.csv"]
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_port=2222,
+ sftp_username="skyvern",
+ sftp_password="password",
+ sftp_remote_path="incoming",
+ )
+ browser_result = _browser_result(block, downloaded_filenames=("invoice.pdf", "report.csv"))
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ downloads_during_execute=("invoice.pdf", "report.csv"),
+ )
+
+ assert execution.result is browser_result
+ assert execution.result.output_parameter_value == {
+ "task_id": "task-id",
+ "downloaded_files": [
+ {"filename": "invoice.pdf", "checksum": "checksum-invoice.pdf"},
+ {"filename": "report.csv", "checksum": "checksum-report.csv"},
+ ],
+ }
+ assert execution.upload.await_count == 2
+ assert {Path(call.kwargs["file_path"]) for call in execution.upload.await_args_list} == set(downloaded_files)
+ assert all(
+ call.kwargs["destination"].storage_type == FileStorageType.SFTP for call in execution.upload.await_args_list
+ )
+
+
+async def test_prior_block_downloads_are_not_dispatched(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ _write_downloads(download_dir, "prior_block.pdf")
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block, downloaded_filenames=("this_block.pdf",))
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ downloads_during_execute=("this_block.pdf",),
+ )
+
+ execution.upload.assert_awaited_once()
+ assert Path(execution.upload.await_args.kwargs["file_path"]).name == "this_block.pdf"
+
+
+async def test_download_scope_loss_does_not_deliver_prior_block_files(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ prior_file = _write_downloads(download_dir, "prior_block.pdf")[0]
+ current_file = download_dir / "this_block.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block)
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ downloads_during_execute=(current_file.name,),
+ )
+
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(current_file)
+ assert all(call.kwargs["file_path"] != str(prior_file) for call in execution.upload.await_args_list)
+
+
+async def test_new_name_file_delivered_even_if_its_hash_fails(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ prior_file = _write_downloads(download_dir, "prior_block.pdf")[0]
+ current_file = download_dir / "this_block.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+
+ def calculate_hash(file_path: str) -> str:
+ if file_path == str(current_file):
+ raise OSError("current hash failed")
+ return hashlib.sha256(Path(file_path).read_bytes()).hexdigest()
+
+ with patch("skyvern.forge.sdk.workflow.models.block.calculate_sha256_for_file", side_effect=calculate_hash):
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block),
+ download_dir,
+ downloads_during_execute=(current_file.name,),
+ )
+
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(current_file)
+ assert all(call.kwargs["file_path"] != str(prior_file) for call in execution.upload.await_args_list)
+
+
+async def test_baseline_listdir_failure_fails_closed(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ prior_file = _write_downloads(download_dir, "prior_block.pdf")[0]
+ current_file = download_dir / "this_block.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ real_listdir = os.listdir
+ baseline_list_attempted = False
+
+ def listdir(path: os.PathLike[str] | str) -> list[str]:
+ nonlocal baseline_list_attempted
+ if not baseline_list_attempted:
+ baseline_list_attempted = True
+ raise OSError("baseline list failed")
+ return real_listdir(path)
+
+ with patch("skyvern.forge.sdk.workflow.models.block.os.listdir", side_effect=listdir):
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block),
+ download_dir,
+ downloads_during_execute=(current_file.name,),
+ )
+
+ assert baseline_list_attempted is True
+ assert execution.result.success is False
+ assert execution.result.status == BlockStatus.failed
+ assert "pre-download baseline" in (execution.result.failure_reason or "")
+ assert "sftp" in (execution.result.failure_reason or "").lower()
+ execution.upload.assert_not_awaited()
+ assert prior_file.exists()
+ # Fail fast: a failed baseline scan is rejected before the browser download runs.
+ execution.browser_execute.assert_not_awaited()
+
+
+async def test_post_download_listdir_failure_fails_closed(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ _write_downloads(download_dir, "prior_block.pdf")
+ current_file = download_dir / "this_block.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ real_listdir = os.listdir
+ post_download = False
+
+ def during_execute() -> None:
+ nonlocal post_download
+ _write_downloads(download_dir, current_file.name)
+ post_download = True
+
+ def listdir(path: os.PathLike[str] | str) -> list[str]:
+ if post_download:
+ raise OSError("post-download list failed")
+ return real_listdir(path)
+
+ with patch("skyvern.forge.sdk.workflow.models.block.os.listdir", side_effect=listdir):
+ execution = await _execute_file_download(
+ block, _browser_result(block), download_dir, during_execute=during_execute
+ )
+
+ assert post_download is True
+ assert execution.result.success is False
+ assert execution.result.status == BlockStatus.failed
+ execution.upload.assert_not_awaited()
+ assert execution.recorded_output.value is None
+
+
+async def test_unhashable_prior_file_is_not_delivered(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ prior_file = _write_downloads(download_dir, "prior_block.pdf")[0]
+ current_file = download_dir / "this_block.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ baseline_hash_failed = False
+
+ def calculate_hash(file_path: str) -> str:
+ nonlocal baseline_hash_failed
+ if file_path == str(prior_file) and not baseline_hash_failed:
+ baseline_hash_failed = True
+ raise OSError("baseline hash failed")
+ return hashlib.sha256(Path(file_path).read_bytes()).hexdigest()
+
+ with patch("skyvern.forge.sdk.workflow.models.block.calculate_sha256_for_file", side_effect=calculate_hash):
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block),
+ download_dir,
+ downloads_during_execute=(current_file.name,),
+ )
+
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(current_file)
+ assert all(call.kwargs["file_path"] != str(prior_file) for call in execution.upload.await_args_list)
+
+
+async def test_attributable_file_delivered_even_if_scope_list_incomplete(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ current_file = download_dir / "current.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("stale.pdf",)),
+ download_dir,
+ downloads_during_execute=(current_file.name,),
+ )
+
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(current_file)
+
+
+async def test_no_new_local_files_is_noop_even_if_scoped_list_nonempty(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ prior_file = _write_downloads(download_dir, "prior_block.pdf")[0]
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block, downloaded_filenames=(prior_file.name,))
+
+ execution = await _execute_file_download(block, browser_result, download_dir)
+
+ assert execution.result is browser_result
+ assert execution.result.success is True
+ execution.upload.assert_not_awaited()
+
+
+async def test_prior_files_do_not_consume_current_block_upload_limit(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ _write_downloads(download_dir, "prior.pdf")
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+
+ with patch("skyvern.forge.sdk.workflow.models.block.MAX_UPLOAD_FILE_COUNT", 1):
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("current.pdf",)),
+ download_dir,
+ downloads_during_execute=("current.pdf",),
+ )
+
+ execution.upload.assert_awaited_once()
+ assert Path(execution.upload.await_args.kwargs["file_path"]).name == "current.pdf"
+
+
+async def test_same_basename_with_wrong_checksum_never_dispatches_prior_block_file(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ prior_file = _write_downloads(download_dir, "invoice.pdf")[0]
+ prior_file.write_bytes(b"prior block contents")
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block, downloaded_filenames=("invoice.pdf",))
+ assert isinstance(browser_result.output_parameter_value, dict)
+ browser_result.output_parameter_value["downloaded_files"] = [
+ {
+ "filename": "invoice.pdf",
+ "checksum": hashlib.sha256(b"this block contents").hexdigest(),
+ }
+ ]
+
+ execution = await _execute_file_download(block, browser_result, download_dir)
+
+ execution.upload.assert_not_awaited()
+
+
+async def test_same_name_overwrite_new_content_is_delivered(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ report_file, unchanged_file = _write_downloads(download_dir, "report.pdf", "unchanged.pdf")
+ report_file.write_bytes(b"before-data")
+ unchanged_file.write_bytes(b"unchanged-data")
+ original_stat = report_file.stat()
+ new_contents = b"after-data!"
+ assert len(new_contents) == original_stat.st_size
+
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block)
+ assert isinstance(browser_result.output_parameter_value, dict)
+ browser_result.output_parameter_value["downloaded_files"] = [
+ {"filename": report_file.name, "checksum": hashlib.sha256(new_contents).hexdigest()},
+ {"filename": unchanged_file.name, "checksum": hashlib.sha256(unchanged_file.read_bytes()).hexdigest()},
+ ]
+
+ def overwrite_report() -> None:
+ report_file.write_bytes(new_contents)
+ os.utime(report_file, ns=(original_stat.st_atime_ns, original_stat.st_mtime_ns))
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ during_execute=overwrite_report,
+ )
+
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(report_file)
+ assert all(call.kwargs["file_path"] != str(unchanged_file) for call in execution.upload.await_args_list)
+
+
+async def test_same_name_identical_redownload_with_new_mtime_is_delivered(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ report_file = _write_downloads(download_dir, "report.pdf")[0]
+ report_file.write_bytes(b"same-bytes")
+ original_stat = report_file.stat()
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+
+ def overwrite_report() -> None:
+ report_file.write_bytes(b"same-bytes")
+ os.utime(report_file, ns=(original_stat.st_atime_ns, original_stat.st_mtime_ns + 1_000_000_000))
+
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block),
+ download_dir,
+ during_execute=overwrite_report,
+ )
+
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(report_file)
+
+
+async def test_same_name_identical_content_frozen_mtime_is_not_delivered(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ report_file = _write_downloads(download_dir, "report.pdf")[0]
+ report_file.write_bytes(b"same-bytes")
+ original_stat = report_file.stat()
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+
+ def overwrite_report() -> None:
+ report_file.write_bytes(b"same-bytes")
+ os.utime(report_file, ns=(original_stat.st_atime_ns, original_stat.st_mtime_ns))
+
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block),
+ download_dir,
+ during_execute=overwrite_report,
+ )
+
+ execution.upload.assert_not_awaited()
+
+
+async def test_nonempty_scoped_download_missing_locally_is_noop(tmp_path: Path) -> None:
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block, downloaded_filenames=("missing.pdf",))
+
+ execution = await _execute_file_download(block, browser_result, tmp_path / "downloads")
+
+ assert execution.result is browser_result
+ assert execution.result.success is True
+ execution.upload.assert_not_awaited()
+
+
+async def test_download_suffix_renamed_scoped_file_is_dispatched(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ renamed_file = download_dir / "quarterly-report.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ download_suffix="quarterly-report",
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block, downloaded_filenames=("quarterly-report.pdf",))
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ downloads_during_execute=("quarterly-report.pdf",),
+ )
+
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(renamed_file)
+
+
+async def test_scope_matching_normalizes_unicode_filename(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ nfc_name = "r\N{LATIN SMALL LETTER E WITH ACUTE}sume.pdf"
+ nfd_name = unicodedata.normalize("NFD", nfc_name)
+ assert nfc_name != nfd_name
+ local_file = download_dir / nfd_name
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block, downloaded_filenames=(nfc_name,))
+ assert isinstance(browser_result.output_parameter_value, dict)
+ browser_result.output_parameter_value["downloaded_files"] = [
+ {"filename": nfc_name, "checksum": hashlib.sha256(nfd_name.encode()).hexdigest()}
+ ]
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ downloads_during_execute=(nfd_name,),
+ )
+
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(local_file)
+
+
+async def test_nfc_nfd_identical_leftovers_are_not_leaked_by_mtime(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir(parents=True, exist_ok=True)
+ nfc_name = "r\N{LATIN SMALL LETTER E WITH ACUTE}sum\N{LATIN SMALL LETTER E WITH ACUTE}.pdf"
+ nfd_name = unicodedata.normalize("NFD", nfc_name)
+ assert nfc_name != nfd_name
+ nfc_file = download_dir / nfc_name
+ nfd_file = download_dir / nfd_name
+ nfc_file.write_bytes(b"identical-leftover")
+ nfd_file.write_bytes(b"identical-leftover")
+ if len(os.listdir(download_dir)) < 2:
+ pytest.skip("filesystem normalizes unicode filenames; NFC/NFD collision is not reproducible here")
+ os.utime(nfc_file, ns=(0, 1_000_000_000))
+ os.utime(nfd_file, ns=(0, 9_000_000_000))
+
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+
+ real_listdir = os.listdir
+
+ # Force the adversarial order (nfc last): a reverted normalized-key baseline would then hold
+ # nfc's smaller mtime, so nfd's larger mtime would leak. The raw-key fix must skip both.
+ def ordered_listdir(path: os.PathLike[str] | str) -> list[str]:
+ entries = real_listdir(path)
+ if set(entries) == {nfc_name, nfd_name}:
+ return [nfd_name, nfc_name]
+ return entries
+
+ with patch("skyvern.forge.sdk.workflow.models.block.os.listdir", side_effect=ordered_listdir):
+ execution = await _execute_file_download(block, _browser_result(block), download_dir)
+
+ execution.upload.assert_not_awaited()
+
+
+async def test_nfc_nfd_different_content_leftovers_are_not_leaked(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir(parents=True, exist_ok=True)
+ nfc_name = "caf\N{LATIN SMALL LETTER E WITH ACUTE}.pdf"
+ nfd_name = unicodedata.normalize("NFD", nfc_name)
+ assert nfc_name != nfd_name
+ (download_dir / nfc_name).write_bytes(b"aws-key-one")
+ (download_dir / nfd_name).write_bytes(b"totally-different")
+ if len(os.listdir(download_dir)) < 2:
+ pytest.skip("filesystem normalizes unicode filenames; NFC/NFD collision is not reproducible here")
+
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+
+ execution = await _execute_file_download(block, _browser_result(block), download_dir)
+
+ execution.upload.assert_not_awaited()
+
+
[email protected]("malformed_entry", [{}, {"filename": None}, None, "invoice.pdf"])
+async def test_malformed_scoped_download_entry_is_ignored_without_hiding_valid_file(
+ tmp_path: Path, malformed_entry: object
+) -> None:
+ download_dir = tmp_path / "downloads"
+ _write_downloads(download_dir, "prior.pdf")
+ valid_file = download_dir / "valid.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block)
+ assert isinstance(browser_result.output_parameter_value, dict)
+ browser_result.output_parameter_value["downloaded_files"] = [malformed_entry, {"filename": "valid.pdf"}]
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ downloads_during_execute=("valid.pdf",),
+ )
+
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(valid_file)
+
+
+async def test_dispatch_failure_returns_failed_result_and_clears_output(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block, downloaded_filenames=("invoice.pdf",))
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ upload_side_effect=RuntimeError("upload failed"),
+ downloads_during_execute=("invoice.pdf",),
+ )
+
+ assert execution.result.success is False
+ assert execution.result.status == BlockStatus.failed
+ assert "sftp" in (execution.result.failure_reason or "").lower()
+ assert execution.record_output.await_count == 2
+ assert execution.record_output.await_args_list[0].args[2] == browser_result.output_parameter_value
+ execution.record_output.assert_awaited_with(execution.workflow_run_context, "workflow-run-id", None)
+ assert execution.recorded_output.value is None
+
+
+async def test_empty_scope_and_empty_download_dir_is_noop(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ _write_downloads(download_dir)
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block)
+
+ execution = await _execute_file_download(block, browser_result, download_dir)
+
+ assert execution.result is browser_result
+ assert execution.result.success is True
+ execution.upload.assert_not_awaited()
+
+
+async def test_empty_scope_with_only_unchanged_prior_files_is_noop(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ _write_downloads(download_dir, "prior.pdf")
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ continue_on_empty=False,
+ )
+ browser_result = _browser_result(block)
+
+ execution = await _execute_file_download(block, browser_result, download_dir)
+
+ assert execution.result is browser_result
+ assert execution.result.success is True
+ execution.upload.assert_not_awaited()
+
+
+async def test_empty_scope_delivers_new_file_from_this_block(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ prior_file = _write_downloads(download_dir, "prior.pdf")[0]
+ current_file = download_dir / "current.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ continue_on_empty=False,
+ )
+
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block),
+ download_dir,
+ downloads_during_execute=(current_file.name,),
+ )
+
+ assert execution.result.success is True
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(current_file)
+ assert all(call.kwargs["file_path"] != str(prior_file) for call in execution.upload.await_args_list)
+
+
+async def test_pre_download_snapshot_tolerates_file_deleted_during_stat(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ vanishing_file = _write_downloads(download_dir, "vanishing.pdf")[0]
+ current_file = download_dir / "current.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ real_stat = os.stat
+ deleted = False
+
+ def delete_during_stat(path: os.PathLike[str] | str, *args: object, **kwargs: object) -> os.stat_result:
+ nonlocal deleted
+ if not deleted and os.fspath(path) == str(vanishing_file):
+ deleted = True
+ vanishing_file.unlink()
+ raise FileNotFoundError(str(vanishing_file))
+ return real_stat(path, *args, **kwargs)
+
+ with patch("skyvern.forge.sdk.workflow.models.block.os.stat", side_effect=delete_during_stat):
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=(current_file.name,)),
+ download_dir,
+ downloads_during_execute=(current_file.name,),
+ )
+
+ assert execution.result.success is True
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(current_file)
+
+
+async def test_empty_scope_with_local_files_and_continue_on_empty_is_noop(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ _write_downloads(download_dir, "prior.pdf")
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ continue_on_empty=True,
+ )
+ browser_result = _browser_result(block)
+
+ execution = await _execute_file_download(block, browser_result, download_dir)
+
+ assert execution.result is browser_result
+ assert execution.result.success is True
+ execution.upload.assert_not_awaited()
+
+
+ ("download_target", "destination_fields", "expected_storage_type"),
+ [
+ (
+ FileDownloadTarget.S3,
+ {
+ "s3_bucket": "bucket",
+ "aws_access_key_id": "access-key",
+ "aws_secret_access_key": "secret-key",
+ },
+ FileStorageType.S3,
+ ),
+ (
+ FileDownloadTarget.AZURE,
+ {
+ "azure_storage_account_name": "account",
+ "azure_storage_account_key": "account-key",
+ "azure_blob_container_name": "container",
+ },
+ FileStorageType.AZURE,
+ ),
+ (
+ FileDownloadTarget.GOOGLE_DRIVE,
+ {
+ "google_credential_id": "google-credential-id",
+ "google_drive_folder_id": "https://drive.google.com/drive/folders/folder-id",
+ },
+ FileStorageType.GOOGLE_DRIVE,
+ ),
+ ],
+ ids=["s3", "azure", "google-drive"],
+)
+async def test_external_target_dispatches_download_file(
+ tmp_path: Path,
+ download_target: FileDownloadTarget,
+ destination_fields: dict[str, object],
+ expected_storage_type: FileStorageType,
+) -> None:
+ download_dir = tmp_path / "downloads"
+ downloaded_file = download_dir / "statement.pdf"
+ block = _file_download_block(download_target, **destination_fields)
+ browser_result = _browser_result(block, downloaded_filenames=("statement.pdf",))
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ downloads_during_execute=("statement.pdf",),
+ )
+
+ assert execution.result is browser_result
+ execution.upload.assert_awaited_once()
+ assert execution.upload.await_args.kwargs["file_path"] == str(downloaded_file)
+ assert execution.upload.await_args.kwargs["destination"].storage_type == expected_storage_type
+ if download_target == FileDownloadTarget.GOOGLE_DRIVE:
+ execution.get_google_workspace_credentials.assert_awaited_once()
+
+
+async def test_s3_destination_unwraps_secret_values(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(
+ FileDownloadTarget.S3,
+ s3_bucket="bucket",
+ aws_access_key_id="{{aws_key}}",
+ aws_secret_access_key="{{aws_secret}}",
+ )
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("statement.pdf",)),
+ download_dir,
+ secret_values={"{{aws_key}}": "actual-key", "{{aws_secret}}": "actual-secret"},
+ downloads_during_execute=("statement.pdf",),
+ )
+
+ destination = execution.upload.await_args.kwargs["destination"]
+ assert destination.storage_type == FileStorageType.S3
+ assert destination.aws_access_key_id == "actual-key"
+ assert destination.aws_secret_access_key == "actual-secret"
+
+
+async def test_s3_dispatch_rejects_empty_resolved_credentials_before_upload(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ resolved_credential = "\t"
+ block = _file_download_block(
+ FileDownloadTarget.S3,
+ s3_bucket="bucket",
+ aws_access_key_id="{{aws_key}}",
+ aws_secret_access_key="{{aws_secret}}",
+ )
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("statement.pdf",)),
+ download_dir,
+ secret_values={
+ "{{aws_key}}": resolved_credential,
+ "{{aws_secret}}": resolved_credential,
+ },
+ downloads_during_execute=("statement.pdf",),
+ )
+
+ assert execution.result.success is False
+ assert "not configured" in execution.result.failure_reason
+ assert resolved_credential not in execution.result.failure_reason
+ assert execution.recorded_output.value is None
+ execution.upload.assert_not_awaited()
+
+
+async def test_azure_destination_unwraps_secret_values(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(
+ FileDownloadTarget.AZURE,
+ azure_storage_account_name="{{azure_account}}",
+ azure_storage_account_key="{{azure_key}}",
+ azure_blob_container_name="container",
+ )
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("statement.pdf",)),
+ download_dir,
+ secret_values={"{{azure_account}}": "actualaccount", "{{azure_key}}": "actual-key"},
+ downloads_during_execute=("statement.pdf",),
+ )
+
+ destination = execution.upload.await_args.kwargs["destination"]
+ assert destination.storage_type == FileStorageType.AZURE
+ assert destination.azure_storage_account_name == "actualaccount"
+ assert destination.azure_storage_account_key == "actual-key"
+ parsed_customer_uri = urlparse(destination.customer_uri)
+ assert parsed_customer_uri.scheme == "https"
+ assert parsed_customer_uri.hostname == "actualaccount.blob.core.windows.net"
+ assert parsed_customer_uri.path.startswith("/container/")
+
+
+async def test_azure_dispatch_rejects_invalid_resolved_account_name_before_building_uri(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(
+ FileDownloadTarget.AZURE,
+ azure_storage_account_name="{{azure_account}}",
+ azure_storage_account_key="{{azure_key}}",
+ azure_blob_container_name="container",
+ )
+
+ with patch.object(block, "_get_azure_blob_uri", wraps=block._get_azure_blob_uri) as get_azure_blob_uri:
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("statement.pdf",)),
+ download_dir,
+ secret_values={"{{azure_account}}": "127.0.0.1#", "{{azure_key}}": "actual-key"},
+ downloads_during_execute=("statement.pdf",),
+ )
+
+ assert execution.result.success is False
+ assert "account name" in execution.result.failure_reason
+ get_azure_blob_uri.assert_not_called()
+ execution.upload.assert_not_awaited()
+
+
+ ("resolved_account_name", "resolved_account_key"),
+ [
+ ("", "actual-key"),
+ ("actualaccount", ""),
+ (" ", "actual-key"),
+ ("actualaccount", "\t"),
+ ],
+ ids=["empty-account-name", "empty-account-key", "whitespace-account-name", "whitespace-account-key"],
+)
+async def test_azure_dispatch_rejects_empty_resolved_credentials_before_upload(
+ tmp_path: Path,
+ resolved_account_name: str,
+ resolved_account_key: str,
+) -> None:
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(
+ FileDownloadTarget.AZURE,
+ azure_storage_account_name="{{azure_account}}",
+ azure_storage_account_key="{{azure_key}}",
+ azure_blob_container_name="container",
+ )
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("statement.pdf",)),
+ download_dir,
+ secret_values={
+ "{{azure_account}}": resolved_account_name,
+ "{{azure_key}}": resolved_account_key,
+ },
+ downloads_during_execute=("statement.pdf",),
+ )
+
+ assert execution.result.success is False
+ assert "not configured" in execution.result.failure_reason
+ execution.upload.assert_not_awaited()
+
+
+async def test_azure_dispatch_without_resolved_configuration_raises_before_upload(tmp_path: Path) -> None:
+ local_file = tmp_path / "statement.pdf"
+ local_file.write_bytes(b"statement")
+ block = FileDownloadBlock.model_construct(
+ label="download",
+ output_parameter=None,
+ download_target=FileDownloadTarget.AZURE,
+ azure_storage_account_name=None,
+ azure_storage_account_key=None,
+ azure_blob_container_name="container",
+ path=None,
+ )
+ workflow_run_context = MagicMock()
+ workflow_run_context.get_original_secret_value_or_none.return_value = None
+
+ with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
+ mock_app.AGENT_FUNCTION.upload_file_to_customer_storage = AsyncMock()
+ with pytest.raises(AzureConfigurationError, match="not configured"):
+ await block._dispatch_files_to_storage(
+ storage_type=FileStorageType.AZURE,
+ files_to_upload=[str(local_file)],
+ workflow_run_id="workflow-run-id",
+ workflow_run_block_id="workflow-run-block-id",
+ organization_id="organization-id",
+ workflow_run_context=workflow_run_context,
+ )
+
+ mock_app.AGENT_FUNCTION.upload_file_to_customer_storage.assert_not_awaited()
+
+
+async def test_google_drive_unwraps_credential_id_and_requests_drive_scopes(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(
+ FileDownloadTarget.GOOGLE_DRIVE,
+ google_credential_id="{{google_credential}}",
+ google_drive_folder_id="https://drive.google.com/drive/folders/folder-id",
+ )
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("statement.pdf",)),
+ download_dir,
+ secret_values={"{{google_credential}}": "actual-google-credential"},
+ downloads_during_execute=("statement.pdf",),
+ )
+
+ execution.get_google_workspace_credentials.assert_awaited_once_with(
+ organization_id="organization-id",
+ credential_id="actual-google-credential",
+ required_scopes=list(google_oauth_service.GOOGLE_DRIVE_SCOPES),
+ )
+ destination = execution.upload.await_args.kwargs["destination"]
+ assert destination.storage_type == FileStorageType.GOOGLE_DRIVE
+ assert destination.google_access_token == "google-access-token"
+ assert destination.google_drive_folder_id == "folder-id"
+
+
+async def test_sftp_unwraps_secrets_and_defaults_port_to_22(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="{{sftp_user}}",
+ sftp_password="{{sftp_password}}",
+ sftp_private_key="{{sftp_key}}",
+ sftp_private_key_passphrase="{{sftp_passphrase}}",
+ )
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("statement.pdf",)),
+ download_dir,
+ secret_values={
+ "{{sftp_user}}": "actual-user",
+ "{{sftp_password}}": "actual-password",
+ "{{sftp_key}}": "actual-private-key",
+ "{{sftp_passphrase}}": "actual-passphrase",
+ },
+ downloads_during_execute=("statement.pdf",),
+ )
+
+ destination = execution.upload.await_args.kwargs["destination"]
+ assert destination.storage_type == FileStorageType.SFTP
+ assert destination.sftp_port == 22
+ assert destination.sftp_username == "actual-user"
+ assert destination.sftp_password == "actual-password"
+ assert destination.sftp_private_key == "actual-private-key"
+ assert destination.sftp_private_key_passphrase == "actual-passphrase"
+
+
+ ("download_target", "destination_fields", "sensitive_field", "literal_secret"),
+ [
+ (
+ FileDownloadTarget.SFTP,
+ {
+ "sftp_host": "sftp.example.com",
+ "sftp_username": "skyvern",
+ "sftp_password": "literal-sftp-password",
+ },
+ "sftp_password",
+ "literal-sftp-password",
+ ),
+ (
+ FileDownloadTarget.S3,
+ {
+ "s3_bucket": "bucket",
+ "aws_access_key_id": "access-key-id",
+ "aws_secret_access_key": "literal-aws-secret-access-key",
+ },
+ "aws_secret_access_key",
+ "literal-aws-secret-access-key",
+ ),
+ (
+ FileDownloadTarget.AZURE,
+ {
+ "azure_storage_account_name": "storageaccount",
+ "azure_storage_account_key": "literal-azure-storage-account-key",
+ "azure_blob_container_name": "container",
+ },
+ "azure_storage_account_key",
+ "literal-azure-storage-account-key",
+ ),
+ ],
+ ids=["sftp-password", "aws-secret-access-key", "azure-storage-account-key"],
+)
+async def test_literal_destination_secret_dispatches_unchanged_when_encryption_is_disabled(
+ tmp_path: Path,
+ download_target: FileDownloadTarget,
+ destination_fields: dict[str, object],
+ sensitive_field: str,
+ literal_secret: str,
+) -> None:
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(download_target, **destination_fields)
+
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("statement.pdf",)),
+ download_dir,
+ secret_values={},
+ downloads_during_execute=("statement.pdf",),
+ )
+
+ assert execution.result.success is True
+ destination = execution.upload.await_args.kwargs["destination"]
+ assert getattr(destination, sensitive_field) == literal_secret
+
+
+async def test_unset_optional_sftp_secret_fields_do_not_block_dispatch(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="{{sftp_password}}",
+ )
+
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("statement.pdf",)),
+ download_dir,
+ secret_values={"{{sftp_password}}": "resolved-sftp-password"},
+ downloads_during_execute=("statement.pdf",),
+ )
+
+ destination = execution.upload.await_args.kwargs["destination"]
+ assert destination.sftp_password == "resolved-sftp-password"
+ assert destination.sftp_private_key is None
+ assert destination.sftp_private_key_passphrase is None
+ resolver_calls = execution.workflow_run_context.get_original_secret_value_or_none.call_args_list
+ assert all(call.args[0] is not None for call in resolver_calls)
+
+
+async def test_missing_sftp_host_fails_without_dispatch(tmp_path: Path) -> None:
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block)
+
+ execution = await _execute_file_download(block, browser_result, tmp_path / "downloads")
+
+ assert execution.result.success is False
+ assert execution.result.status == BlockStatus.failed
+ assert "sftp_host" in (execution.result.failure_reason or "")
+ execution.upload.assert_not_awaited()
+ # Fail fast: a misconfigured destination is rejected before the browser download runs.
+ execution.browser_execute.assert_not_awaited()
+
+
+ ("download_target", "destination_fields", "missing_field"),
+ [
+ (FileDownloadTarget.S3, {"aws_access_key_id": "key", "aws_secret_access_key": "secret"}, "s3_bucket"),
+ (
+ FileDownloadTarget.AZURE,
+ {"azure_storage_account_name": "account", "azure_storage_account_key": "key"},
+ "azure_blob_container_name",
+ ),
+ (
+ FileDownloadTarget.GOOGLE_DRIVE,
+ {"google_credential_id": "credential"},
+ "google_drive_folder_id",
+ ),
+ (FileDownloadTarget.SFTP, {"sftp_host": "host", "sftp_username": "user"}, "sftp_password"),
+ ],
+ ids=["s3", "azure", "google-drive", "sftp"],
+)
+async def test_missing_required_destination_field_fails_without_dispatch(
+ tmp_path: Path,
+ download_target: FileDownloadTarget,
+ destination_fields: dict[str, object],
+ missing_field: str,
+) -> None:
+ block = _file_download_block(download_target, **destination_fields)
+
+ execution = await _execute_file_download(block, _browser_result(block), tmp_path / "downloads")
+
+ assert execution.result.success is False
+ assert execution.result.status == BlockStatus.failed
+ assert missing_field in (execution.result.failure_reason or "")
+ execution.upload.assert_not_awaited()
+
+
+async def test_prompt_dispatches_only_selected_downloads(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ downloaded_files = [download_dir / "invoice-1.pdf", download_dir / "invoice-2.pdf", download_dir / "report.csv"]
+ selected_files = [str(downloaded_files[0]), str(downloaded_files[1])]
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ prompt="only the invoices",
+ )
+ browser_result = _browser_result(
+ block,
+ downloaded_filenames=("invoice-1.pdf", "invoice-2.pdf", "report.csv"),
+ )
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ selection_result=(selected_files, "The invoice files match."),
+ downloads_during_execute=("invoice-1.pdf", "invoice-2.pdf", "report.csv"),
+ )
+
+ assert execution.result is browser_result
+ execution.select_files.assert_awaited_once()
+ assert set(execution.select_files.await_args.kwargs["files_to_upload"]) == {str(file) for file in downloaded_files}
+ assert execution.upload.await_count == 2
+ assert {call.kwargs["file_path"] for call in execution.upload.await_args_list} == set(selected_files)
+
+
+async def test_prompt_selector_only_receives_current_block_scope(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ prior_file = _write_downloads(download_dir, "prior.pdf")[0]
+ current_file = download_dir / "current.pdf"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ prompt="upload the requested file",
+ )
+
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block, downloaded_filenames=("current.pdf",)),
+ download_dir,
+ selection_result=([str(current_file)], "Current file matches."),
+ downloads_during_execute=("current.pdf",),
+ )
+
+ execution.select_files.assert_awaited_once()
+ assert execution.select_files.await_args.kwargs["files_to_upload"] == [str(current_file)]
+ assert str(prior_file) not in execution.select_files.await_args.kwargs["files_to_upload"]
+ assert execution.upload.await_args.kwargs["file_path"] == str(current_file)
+
+
+async def test_prompt_selector_rejects_prior_block_filename_not_in_candidates(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ prior_file, current_file = _write_downloads(download_dir, "prior.pdf", "current.pdf")
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ prompt="upload prior.pdf",
+ )
+ handler = AsyncMock(
+ return_value={"reasoning": "The user requested the prior file.", "files_to_upload": [prior_file.name]}
+ )
+
+ with (
+ patch.object(LLMAPIHandlerFactory, "get_override_llm_api_handler", return_value=handler),
+ patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
+ ):
+ mock_app.DATABASE.observer.get_workflow_run_block = AsyncMock(return_value=None)
+ with pytest.raises(ValueError, match="not candidate files"):
+ await block._select_files_to_upload_with_prompt(
+ prompt=block.prompt or "",
+ files_to_upload=[str(current_file)],
+ workflow_run_block_id="workflow-run-block-id",
+ organization_id="organization-id",
+ )
+
+
+async def test_prompt_selecting_no_downloads_is_successful_noop(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ prompt="only the invoices",
+ )
+ browser_result = _browser_result(
+ block,
+ downloaded_filenames=("invoice.pdf", "report.csv", "notes.txt"),
+ )
+
+ execution = await _execute_file_download(
+ block,
+ browser_result,
+ download_dir,
+ selection_result=([], "No files match."),
+ downloads_during_execute=("invoice.pdf", "report.csv", "notes.txt"),
+ )
+
+ assert execution.result is browser_result
+ assert execution.result.success is True
+ execution.select_files.assert_awaited_once()
+ execution.upload.assert_not_awaited()
+
+
+async def test_failed_browser_download_returns_without_dispatch(tmp_path: Path) -> None:
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ browser_result = _browser_result(block, success=False)
+
+ execution = await _execute_file_download(block, browser_result, tmp_path / "downloads")
+
+ assert execution.result is browser_result
+ execution.upload.assert_not_awaited()
+
+
+def test_file_download_yaml_conversion_preserves_destination_fields() -> None:
+ yaml_block = FileDownloadBlockYAML(
+ label="download",
+ navigation_goal="Download the requested files.",
+ download_target=FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_port=2222,
+ sftp_remote_path="incoming/reports",
+ )
+
+ block = block_yaml_to_block(yaml_block, {"download_output": _output_parameter()})
+
+ assert isinstance(block, FileDownloadBlock)
+ assert block.download_target == FileDownloadTarget.SFTP
+ assert block.sftp_host == "sftp.example.com"
+ assert block.sftp_port == 2222
+ assert block.sftp_remote_path == "incoming/reports"
+
+
+async def test_non_cached_script_download_threads_destination_into_single_block_execution() -> None:
+ validation_output = SimpleNamespace(
+ label="download",
+ output_parameter=_output_parameter(),
+ workflow_run_id="workflow-run-id",
+ organization_id="organization-id",
+ browser_session_id="browser-session-id",
+ context=SimpleNamespace(parent_workflow_run_block_id="parent-block-id"),
+ )
+
+ with (
+ patch("skyvern.services.script_service.script_run_context_manager.get_cached_fn", return_value=None),
+ patch(
+ "skyvern.services.script_service._validate_and_get_output_parameter",
+ new_callable=AsyncMock,
+ return_value=validation_output,
+ ),
+ patch.object(FileDownloadBlock, "execute_safe", autospec=True) as execute_safe,
+ ):
+ from skyvern.services.script_service import download
+
+ await download(
+ prompt="Only upload invoices.",
+ navigation_goal="Download all reports.",
+ label="download",
+ download_target="sftp",
+ sftp_host="sftp.example.com",
+ sftp_username="user",
+ sftp_password="password",
+ )
+
+ execute_safe.assert_awaited_once()
+ block = execute_safe.await_args.args[0]
+ assert block.download_target == FileDownloadTarget.SFTP
+ assert block.navigation_goal == "Download all reports."
+ assert block.prompt == "Only upload invoices."
+ assert block.sftp_host == "sftp.example.com"
+ assert block.sftp_username == "user"
+ assert block.sftp_password == "password"
+ assert execute_safe.await_args.kwargs == {
+ "workflow_run_id": "workflow-run-id",
+ "parent_workflow_run_block_id": "parent-block-id",
+ "organization_id": "organization-id",
+ "browser_session_id": "browser-session-id",
+ }
diff --git a/tests/unit/test_file_upload_prompt.py b/tests/unit/test_file_upload_prompt.py
index 821daedf5..07b570d41 100644
--- a/tests/unit/test_file_upload_prompt.py
+++ b/tests/unit/test_file_upload_prompt.py
@@ -5,6 +5,7 @@ import unicodedata
from datetime import UTC, datetime
from pathlib import Path
from types import SimpleNamespace
+from typing import cast
from unittest.mock import AsyncMock, MagicMock, patch
import libcst as cst
@@ -17,7 +18,7 @@ from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api.llm.api_handler_factory import LLMAPIHandlerFactory
from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
-from skyvern.forge.sdk.workflow.models.block import FileUploadBlock
+from skyvern.forge.sdk.workflow.models.block import FileUploadBlock, UnsupportedStorageTypeError
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
from skyvern.forge.sdk.workflow.workflow_definition_converter import block_yaml_to_block
from skyvern.schemas.workflows import BlockStatus, FileStorageType, FileUploadBlockYAML
@@ -81,10 +82,15 @@ async def _execute_file_upload(
llm_error: Exception | None = None,
formatted_prompt: str | None = None,
format_error: Exception | None = None,
+ secret_values: dict[str, str] | None = None,
) -> SimpleNamespace:
workflow_run_context = MagicMock()
workflow_run_context.organization_id = "organization-id"
- workflow_run_context.get_original_secret_value_or_none.return_value = None
+ if secret_values is None:
+ secret_values = (
+ {block.aws_secret_access_key: block.aws_secret_access_key} if block.aws_secret_access_key else {}
+ )
+ workflow_run_context.get_original_secret_value_or_none.side_effect = secret_values.get
record_output = AsyncMock()
build_result = AsyncMock(side_effect=lambda **kwargs: SimpleNamespace(**kwargs))
@@ -142,6 +148,21 @@ async def _execute_file_upload(
)
+async def test_unsupported_storage_type_returns_failed_result(tmp_path: Path) -> None:
+ block = _file_upload_block(None)
+ block.storage_type = cast(FileStorageType, "unsupported")
+
+ with pytest.raises(UnsupportedStorageTypeError):
+ block._validate_destination_fields(block.storage_type)
+
+ execution = await _execute_file_upload(block, tmp_path / "downloads")
+
+ assert execution.result.success is False
+ assert execution.result.failure_reason == "Unsupported storage type: unsupported"
+ assert execution.result.status == BlockStatus.failed
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("prompt", [None, " \n\t"], ids=["none", "whitespace"])
async def test_empty_prompt_uploads_all_files_without_llm(tmp_path: Path, prompt: str | None) -> None:
@@ -161,6 +182,37 @@ async def test_empty_prompt_uploads_all_files_without_llm(tmp_path: Path, prompt
execution.handler.assert_not_awaited()
+async def test_literal_aws_secret_access_key_dispatches_unchanged_when_encryption_is_disabled(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ _write_candidates(download_dir, names=("invoice.pdf",))
+ block = _file_upload_block(None)
+
+ execution = await _execute_file_upload(block, download_dir, secret_values={})
+
+ assert execution.result.success is True
+ destination = execution.upload.await_args.kwargs["destination"]
+ assert destination.aws_secret_access_key == block.aws_secret_access_key
+
+
+async def test_referenced_aws_secret_access_key_dispatches_resolved_value(tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ _write_candidates(download_dir, names=("invoice.pdf",))
+ block = _file_upload_block(None)
+ block.aws_secret_access_key = "{{aws_secret}}"
+
+ execution = await _execute_file_upload(
+ block,
+ download_dir,
+ secret_values={"{{aws_secret}}": "resolved-aws-secret-access-key"},
+ )
+
+ assert execution.result.success is True
+ destination = execution.upload.await_args.kwargs["destination"]
+ assert destination.aws_secret_access_key == "resolved-aws-secret-access-key"
+
+
@pytest.mark.asyncio
async def test_prompt_rendered_to_whitespace_uploads_all_files_without_llm(tmp_path: Path) -> None:
download_dir = tmp_path / "downloads"
diff --git a/tests/unit/test_iframe_mcp_e2e.py b/tests/unit/test_iframe_mcp_e2e.py
index 2f319808e..79c732e28 100644
--- a/tests/unit/test_iframe_mcp_e2e.py
+++ b/tests/unit/test_iframe_mcp_e2e.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import asyncio
from pathlib import Path
from typing import Any
+from unittest.mock import MagicMock
import pytest
import pytest_asyncio
@@ -19,7 +20,14 @@ from playwright.async_api import async_playwright
from skyvern.cli.core.result import BrowserContext
from skyvern.cli.core.session_manager import SessionState, get_current_session, set_current_session
-from skyvern.cli.mcp_tools.browser import skyvern_frame_list, skyvern_frame_main, skyvern_frame_switch
+from skyvern.cli.mcp_tools.browser import (
+ skyvern_execute,
+ skyvern_frame_list,
+ skyvern_frame_main,
+ skyvern_frame_switch,
+ skyvern_observe,
+)
+from skyvern.library.skyvern_browser_page import SkyvernBrowserPage
def _has_playwright_browser() -> bool:
@@ -46,11 +54,17 @@ MAIN_HTML = """\
<body>
<h1 id="main-heading">Main Page</h1>
<input id="main-input" type="text" value="" />
+ <button id="parent-action" type="button">Parent action</button>
<iframe id="pay-frame" name="payment" srcdoc='
<!DOCTYPE html>
<html><body>
<h2 id="frame-heading">Payment</h2>
<input id="card" type="text" value="" placeholder="Card" />
+ <button id="frame-action" type="button"
+ onclick="document.getElementById(`frame-status`).textContent = `clicked`">
+ Frame action
+ </button>
+ <div id="frame-status">idle</div>
</body></html>
'></iframe>
</body>
@@ -76,63 +90,8 @@ class _FakeBrowser:
self._browser_context = _FakeBrowserContext(page)
async def get_working_page(self) -> Any:
- # Return a lightweight wrapper that has the frame methods
- return _WrappedPage(self._page)
-
-
-class _WrappedPage:
- """Thin wrapper around Playwright Page to add frame_switch/main/list."""
-
- def __init__(self, page: Any) -> None:
- self.page = page
- self._working_frame = None
-
- @property
- def _locator_scope(self) -> Any:
- if self._working_frame is not None:
- return self._working_frame
- return self.page
-
- async def frame_switch(
- self, *, selector: str | None = None, name: str | None = None, index: int | None = None
- ) -> dict[str, Any]:
- params = sum(p is not None for p in (selector, name, index))
- if params != 1:
- raise ValueError("Exactly one of selector, name, or index is required.")
-
- frame = None
- if selector is not None:
- element = await self.page.query_selector(selector)
- if element is None:
- raise ValueError(f"Selector '{selector}' did not match any element.")
- frame = await element.content_frame()
- if frame is None:
- raise ValueError(f"Selector '{selector}' did not resolve to an iframe.")
- elif name is not None:
- frame = self.page.frame(name=name)
- if frame is None:
- raise ValueError(f"No frame found with name '{name}'.")
- elif index is not None:
- frames = self.page.frames
- if index < 0 or index >= len(frames):
- raise ValueError(f"Frame index {index} out of range.")
- frame = frames[index]
-
- self._working_frame = frame
- return {"name": frame.name if frame else None, "url": frame.url if frame else None}
-
- def frame_main(self) -> dict[str, str]:
- self._working_frame = None
- return {"status": "switched_to_main_frame"}
-
- async def frame_list(self) -> list[dict[str, Any]]:
- return [
- {"index": i, "name": f.name, "url": f.url, "is_main": f == self.page.main_frame}
- for i, f in enumerate(self.page.frames)
- ]
-
- def __getattr__(self, name: str) -> Any:
- return getattr(self.page, name)
+ # The real page wrapper, so frame routing (_locator_scope) matches production.
+ return SkyvernBrowserPage(MagicMock(), self._page)
@pytest_asyncio.fixture
@@ -228,3 +187,55 @@ async def test_mcp_frame_switch_persists_across_calls(mcp_session: SessionState)
frame = state._working_frame
heading = await frame.locator("#frame-heading").text_content()
assert heading == "Payment"
+
+
+async def test_mcp_observe_execute_ref_in_working_frame(mcp_session: SessionState) -> None:
+ await skyvern_frame_switch(selector="#pay-frame")
+
+ observe_result = await skyvern_observe()
+
+ assert observe_result["ok"] is True
+ names = {element["name"] for element in observe_result["data"]["elements"]}
+ assert "Frame action" in names
+ assert "Parent action" not in names
+ frame = mcp_session._working_frame
+ assert frame is not None
+ assert observe_result["data"]["url"] == frame.url
+ ref = next(element["ref"] for element in observe_result["data"]["elements"] if element["name"] == "Frame action")
+
+ execute_result = await skyvern_execute(steps=[{"tool": "click", "params": {"ref": ref}}])
+
+ assert execute_result["ok"] is True
+ assert await frame.locator("#frame-status").text_content() == "clicked"
+
+
+async def test_mcp_frame_main_invalidates_iframe_observe_ref(mcp_session: SessionState) -> None:
+ await skyvern_frame_switch(selector="#pay-frame")
+ observe_result = await skyvern_observe()
+ ref = next(element["ref"] for element in observe_result["data"]["elements"] if element["name"] == "Frame action")
+ frame = mcp_session._working_frame
+ assert frame is not None
+
+ await skyvern_frame_main()
+ execute_result = await skyvern_execute(steps=[{"tool": "click", "params": {"ref": ref}}])
+
+ assert execute_result["ok"] is False
+ assert "Unknown ref" in execute_result["data"]["results"][0]["error"]
+ assert await frame.locator("#frame-status").text_content() == "idle"
+
+
+async def test_iframe_navigation_invalidates_observed_ref(mcp_session: SessionState) -> None:
+ await skyvern_frame_switch(selector="#pay-frame")
+ observe_result = await skyvern_observe()
+ ref = next(element["ref"] for element in observe_result["data"]["elements"] if element["name"] == "Frame action")
+ frame = mcp_session._working_frame
+ assert frame is not None
+
+ await frame.goto("data:text/html,<button id='replacement'>Replacement action</button>")
+ execute_result = await skyvern_execute(steps=[{"tool": "click", "params": {"ref": ref}}])
+
+ assert execute_result["ok"] is False
+ assert "Unknown ref" in execute_result["data"]["results"][0]["error"]
diff --git a/tests/unit/test_iframe_support.py b/tests/unit/test_iframe_support.py
index ce73549e6..7842afc6d 100644
--- a/tests/unit/test_iframe_support.py
+++ b/tests/unit/test_iframe_support.py
@@ -237,3 +237,31 @@ class TestBrowserOps:
assert len(result) == 2
assert result[0].is_main is True
assert result[1].name == "embed"
+
+
+class TestSessionFramePropagation:
+ @pytest.mark.asyncio
+ async def test_get_page_propagates_detached_working_frame(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.cli.core import session_manager
+ from skyvern.cli.core.result import BrowserContext
+ from skyvern.cli.core.session_manager import SessionState
+ from skyvern.cli.mcp_tools import inspection
+
+ frame = MagicMock()
+ frame.is_detached.return_value = True
+ wrapper = MagicMock()
+ browser = MagicMock()
+ browser.get_working_page = AsyncMock(return_value=wrapper)
+ browser._browser_context.pages = []
+ browser._browser_context.on = MagicMock()
+ ctx = BrowserContext(mode="local")
+ state = SessionState(browser=browser, context=ctx)
+ state._working_frame = frame
+ monkeypatch.setattr(session_manager, "resolve_browser", AsyncMock(return_value=(browser, ctx)))
+ monkeypatch.setattr(session_manager, "get_current_session", lambda: state)
+ monkeypatch.setattr(inspection, "ensure_hooks_on_all_pages", MagicMock())
+
+ page, _ = await session_manager.get_page()
+
+ assert state._working_frame is frame
+ assert page._working_frame is frame
diff --git a/tests/unit/test_mcp_observe_execute.py b/tests/unit/test_mcp_observe_execute.py
index eb4b1ef41..f8cb4f1ef 100644
--- a/tests/unit/test_mcp_observe_execute.py
+++ b/tests/unit/test_mcp_observe_execute.py
@@ -2,15 +2,17 @@
from __future__ import annotations
+import asyncio
import gc
from types import SimpleNamespace
from typing import Any
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, call
import pytest
-from skyvern.cli.core import session_manager
+from skyvern.cli.core import browser_ops, session_manager
from skyvern.cli.core.browser_ops import (
+ _DOMUTILS_INTERACTABILITY_READY_JS,
_OBSERVE_INTERACTABLES_JS,
ExecuteStep,
ObserveResult,
@@ -25,6 +27,8 @@ from skyvern.cli.core.session_manager import scoped_session
from skyvern.cli.mcp_tools import browser as mcp_browser
from skyvern.cli.mcp_tools import tabs as mcp_tabs
from skyvern.client.errors import InternalServerError
+from skyvern.library.skyvern_browser_page import SkyvernBrowserPage
+from skyvern.webeye.utils.page import JS_FUNCTION_DEFS
from tests.unit._mcp_browser_fakes import make_real_wait_for_timeout, make_session_state
# ---------------------------------------------------------------------------
@@ -51,15 +55,28 @@ def _make_a11y_tree(**overrides: Any) -> dict[str, Any]:
return tree
+def _mock_dom_evaluate(result: list[dict[str, Any]], *, domutils_ready: bool = True) -> AsyncMock:
+ async def evaluate(expression: str, arg: Any = None) -> Any:
+ if expression == _DOMUTILS_INTERACTABILITY_READY_JS:
+ return domutils_ready
+ if expression == JS_FUNCTION_DEFS:
+ return None
+ return result
+
+ return AsyncMock(side_effect=evaluate)
+
+
def _make_page(a11y_tree: dict[str, Any] | None = None) -> AsyncMock:
"""Create a mock page with accessibility.snapshot()."""
page = AsyncMock()
+ page._working_frame = None
page.url = "https://example.com/login"
page.title = AsyncMock(return_value="Login Page")
tree = a11y_tree or _make_a11y_tree()
page.accessibility = SimpleNamespace(snapshot=AsyncMock(return_value=tree))
page.locator = AsyncMock()
+ page.evaluate = _mock_dom_evaluate([])
return page
@@ -72,8 +89,8 @@ def _make_values_page() -> AsyncMock:
]
)
page = _make_page(tree)
- page.evaluate = AsyncMock(
- return_value=[
+ page.evaluate = _mock_dom_evaluate(
+ [
{
"role": "textbox",
"name": "Email",
@@ -214,10 +231,47 @@ class TestDoObserve:
await do_observe(page, include_values="false") # type: ignore[arg-type]
- page.evaluate.assert_awaited_once_with(
- _OBSERVE_INTERACTABLES_JS,
- {"scopeSelector": None, "includeValues": False},
- )
+ assert page.evaluate.await_args_list == [
+ call(_DOMUTILS_INTERACTABILITY_READY_JS),
+ call(
+ _OBSERVE_INTERACTABLES_JS,
+ {"scopeSelector": None, "includeValues": False},
+ ),
+ ]
+
+ @pytest.mark.asyncio
+ async def test_dom_scan_installs_production_predicate_when_missing(self) -> None:
+ page = _make_page()
+ page.evaluate = _mock_dom_evaluate([], domutils_ready=False)
+
+ await do_observe(page)
+
+ assert page.evaluate.await_args_list == [
+ call(_DOMUTILS_INTERACTABILITY_READY_JS),
+ call(JS_FUNCTION_DEFS),
+ call(
+ _OBSERVE_INTERACTABLES_JS,
+ {"scopeSelector": None, "includeValues": False},
+ ),
+ ]
+
+ @pytest.mark.asyncio
+ async def test_dom_scan_times_out_fail_closed(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ page = _make_page(_make_a11y_tree(children=[{"role": "button", "name": "Go"}]))
+
+ async def never_settles(expression: str, arg: Any = None) -> Any:
+ await asyncio.sleep(3600)
+
+ page.evaluate = AsyncMock(side_effect=never_settles)
+ monkeypatch.setattr("skyvern.cli.core.browser_ops._DOM_SCAN_TIMEOUT_SECONDS", 0.05)
+
+ result = await do_observe(page)
+
+ assert [element.name for element in result.elements] == ["Go"]
+
+ def test_dom_scan_keeps_sky_11953_password_guards(self) -> None:
+ assert '(isPassword(element) ? "" : element.value)' in _OBSERVE_INTERACTABLES_JS
+ assert "includeValues === true && !isPassword(element)" in _OBSERVE_INTERACTABLES_JS
@pytest.mark.asyncio
async def test_max_elements_cap(self) -> None:
@@ -254,6 +308,136 @@ class TestDoObserve:
page.accessibility.snapshot.assert_awaited_once_with(root=mock_handle)
assert result.element_count == 1
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("selector", [None, "#frame-form"])
+ async def test_working_frame_uses_dom_only_and_reports_frame_url(
+ self,
+ selector: str | None,
+ ) -> None:
+ main_tree = _make_a11y_tree(children=[{"role": "button", "name": "Parent action"}])
+ page = _make_page(main_tree)
+ locator = MagicMock()
+ locator.first.element_handle = AsyncMock(return_value=MagicMock())
+ page.locator = MagicMock(return_value=locator)
+
+ frame = SimpleNamespace(
+ name="payment",
+ url="https://example.com/payment-frame",
+ title=AsyncMock(return_value="Payment Frame"),
+ evaluate=_mock_dom_evaluate(
+ [
+ {
+ "role": "button",
+ "name": "Frame action",
+ "tag": "button",
+ "selector": "#frame-action",
+ }
+ ],
+ domutils_ready=False,
+ ),
+ )
+ page._working_frame = frame
+
+ result = await do_observe(page, selector=selector)
+
+ assert frame.evaluate.await_args_list == [
+ call(_DOMUTILS_INTERACTABILITY_READY_JS),
+ call(JS_FUNCTION_DEFS),
+ call(
+ _OBSERVE_INTERACTABLES_JS,
+ {"scopeSelector": selector, "includeValues": False},
+ ),
+ ]
+ page.evaluate.assert_not_awaited()
+ page.accessibility.snapshot.assert_not_awaited()
+ assert {element.name for element in result.elements} == {"Frame action"}
+ assert result.url == frame.url
+ assert result.title == "Payment Frame"
+ frame.title.assert_awaited_once()
+ page.title.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_detached_working_frame_raises_before_evaluate(self) -> None:
+ page = _make_page()
+ frame = SimpleNamespace(
+ name="payment",
+ url="https://example.com/payment-frame",
+ is_detached=lambda: True,
+ evaluate=AsyncMock(),
+ )
+ page._working_frame = frame
+
+ with pytest.raises(browser_ops.ObserveFrameError) as exc_info:
+ await do_observe(page)
+
+ assert exc_info.value.frame_name == frame.name
+ assert exc_info.value.frame_url == frame.url
+ frame.evaluate.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_frame_switch_index_zero_uses_main_frame_accessibility_snapshot(self) -> None:
+ main_frame = SimpleNamespace(name="", url="https://example.com/login")
+ raw_page = SimpleNamespace(frames=[main_frame], main_frame=main_frame)
+ snapshot = AsyncMock(return_value=_make_a11y_tree(children=[{"role": "button", "name": "Main"}]))
+ page = SimpleNamespace(
+ page=raw_page,
+ _working_frame=SimpleNamespace(),
+ url=main_frame.url,
+ title=AsyncMock(return_value="Main Page"),
+ accessibility=SimpleNamespace(snapshot=snapshot),
+ evaluate=_mock_dom_evaluate([]),
+ )
+
+ switched = await SkyvernBrowserPage.frame_switch(page, index=0)
+ observed = await do_observe(page)
+
+ assert switched["url"] == main_frame.url
+ assert page._working_frame is None
+ snapshot.assert_awaited_once_with()
+ assert {element.name for element in observed.elements} == {"Main"}
+
+ @pytest.mark.asyncio
+ async def test_working_frame_evaluate_failure_raises_typed_error(self) -> None:
+ page = _make_page()
+ page.evaluate = AsyncMock(return_value=[])
+ page.accessibility = None
+ page._working_frame = SimpleNamespace(
+ name="payment",
+ url="https://example.com/payment-frame",
+ evaluate=AsyncMock(side_effect=RuntimeError("Execution context was destroyed")),
+ )
+
+ with pytest.raises(browser_ops.ObserveFrameError) as exc_info:
+ await do_observe(page)
+
+ error = str(exc_info.value)
+ assert page._working_frame.name in error
+
+ @pytest.mark.asyncio
+ async def test_working_frame_on_different_page_raises_typed_error(self) -> None:
+ page = _make_page()
+ page.page = object()
+ page._working_frame = SimpleNamespace(
+ name="payment",
+ url="https://example.com/payment-frame",
+ page=object(),
+ evaluate=AsyncMock(return_value=[]),
+ )
+
+ with pytest.raises(browser_ops.ObserveFrameError) as exc_info:
+ await do_observe(page)
+
+ assert "different page" in str(exc_info.value)
+
+ @pytest.mark.asyncio
+ async def test_main_frame_evaluate_failure_remains_best_effort(self) -> None:
+ page = _make_page()
+ page.evaluate = AsyncMock(side_effect=RuntimeError("Execution context was destroyed"))
+
+ result = await do_observe(page)
+
+ assert "Sign In" in {element.name for element in result.elements}
+
@pytest.mark.asyncio
async def test_combobox_options(self) -> None:
tree = _make_a11y_tree(
@@ -278,8 +462,8 @@ class TestDoObserve:
@pytest.mark.asyncio
async def test_dom_interactables_are_merged_with_selectors(self) -> None:
page = _make_page(_make_a11y_tree(children=[{"role": "textbox", "name": "City", "value": ""}]))
- page.evaluate = AsyncMock(
- return_value=[
+ page.evaluate = _mock_dom_evaluate(
+ [
{
"role": "option",
"name": "Lakewood",
@@ -301,8 +485,8 @@ class TestDoObserve:
page = SimpleNamespace(
url="https://example.com/form",
title=AsyncMock(return_value="Form"),
- evaluate=AsyncMock(
- return_value=[
+ evaluate=_mock_dom_evaluate(
+ [
{
"role": "option",
"name": "Music",
@@ -335,8 +519,8 @@ class TestDoObserve:
]
)
page = _make_page(tree)
- page.evaluate = AsyncMock(
- return_value=[
+ page.evaluate = _mock_dom_evaluate(
+ [
{
"role": "option",
"name": "East",
@@ -372,8 +556,8 @@ class TestDoObserve:
]
)
page = _make_page(tree)
- page.evaluate = AsyncMock(
- return_value=[
+ page.evaluate = _mock_dom_evaluate(
+ [
{
"role": "option",
"name": "North",
@@ -405,8 +589,8 @@ class TestDoObserve:
]
)
page = _make_page(tree)
- page.evaluate = AsyncMock(
- return_value=[
+ page.evaluate = _mock_dom_evaluate(
+ [
{"role": "combobox", "name": "Dup", "tag": "select", "selector": "#dup3"},
]
)
@@ -552,6 +736,29 @@ class TestDoExecute:
assert result.error_step is None
assert call_log == ["navigate", "click"]
+ @pytest.mark.asyncio
+ async def test_failed_observe_clears_batch_local_refs(self) -> None:
+ seen_ref_maps: list[dict[str, Any]] = []
+
+ async def dispatch(step: ExecuteStep, ref_map: dict) -> dict[str, Any] | None:
+ if step.tool == "click":
+ seen_ref_maps.append(dict(ref_map))
+ return None
+ if step.params.get("fail"):
+ raise RuntimeError("frame lost")
+ return {"elements": [{"ref": "e0", "role": "button", "name": "X", "tag": "button", "selector": "#x"}]}
+
+ steps = [
+ ExecuteStep(tool="observe", params={}),
+ ExecuteStep(tool="observe", params={"fail": True}),
+ ExecuteStep(tool="click", params={"ref": "e0"}),
+ ]
+ result = await do_execute(dispatch, steps, stop_on_error=False)
+
+ assert result.results[0].ok is True
+ assert result.results[1].ok is False
+ assert seen_ref_maps == [{}]
+
@pytest.mark.asyncio
async def test_stop_on_error_true(self) -> None:
async def dispatch(step: ExecuteStep, ref_map: dict) -> dict[str, Any] | None:
@@ -781,6 +988,37 @@ class TestSkyvernObserveMCP:
result = await mcp_browser.skyvern_observe()
assert result["ok"] is False
+ @pytest.mark.asyncio
+ async def test_non_evaluable_working_frame_returns_structured_error(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ page = _make_page()
+ page.evaluate = AsyncMock(return_value=[])
+ page.accessibility = None
+ frame = SimpleNamespace(
+ name="payment",
+ url="https://example.com/payment-frame",
+ evaluate=AsyncMock(side_effect=RuntimeError("Execution context was destroyed")),
+ )
+ page._working_frame = frame
+ ctx = BrowserContext(mode="local")
+ state = make_session_state(context=ctx)
+ state._observed_refs = {"page_key": (1, 2, "old", "old-frame"), "refs": {"e0": {"ref": "e0"}}}
+ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
+
+ async with scoped_session(state):
+ result = await mcp_browser.skyvern_observe()
+
+ assert result["ok"] is False
+ error = result["error"]
+ assert error["code"] == mcp_browser.ErrorCode.ACTION_FAILED
+ assert error["details"]["frame_name"] == frame.name
+ assert error["details"]["frame_url"] == frame.url
+ assert frame.name in error["message"] or frame.url in error["message"]
+ assert any(action in error["hint"] for action in ("skyvern_frame_main", "skyvern_frame_list", "selector"))
+ assert state._observed_refs == {}
+
# ---------------------------------------------------------------------------
# MCP tool tests: skyvern_execute
@@ -880,6 +1118,35 @@ class TestSkyvernExecuteMCP:
assert result["ok"] is True
observe.assert_awaited_once_with(page, include_values=True)
+ @pytest.mark.asyncio
+ async def test_execute_observe_returns_structured_frame_error_and_clears_refs(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ page = _make_page()
+ frame = SimpleNamespace(
+ name="payment",
+ url="https://example.com/payment-frame",
+ is_detached=lambda: True,
+ evaluate=AsyncMock(),
+ )
+ page._working_frame = frame
+ ctx = BrowserContext(mode="local")
+ state = make_session_state(context=ctx)
+ state._observed_refs = {"page_key": (1, 2, "old", "old-frame"), "refs": {"e0": {"ref": "e0"}}}
+ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
+
+ async with scoped_session(state):
+ result = await mcp_browser.skyvern_execute(steps=[{"tool": "observe", "params": {}}])
+
+ error = result["data"]["results"][0]["error"]
+ assert result["ok"] is False
+ assert error["code"] == mcp_browser.ErrorCode.ACTION_FAILED
+ assert error["details"] == {"frame_name": frame.name, "frame_url": frame.url}
+ assert "skyvern_frame_main" in error["hint"]
+ assert state._observed_refs == {}
+ frame.evaluate.assert_not_awaited()
+
@pytest.mark.asyncio
async def test_execute_resolves_ref_from_prior_observe(self, monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_page()
@@ -975,6 +1242,47 @@ class TestSkyvernExecuteMCP:
)
click.assert_not_awaited()
+ @pytest.mark.asyncio
+ async def test_iframe_ref_is_stale_after_frame_navigation(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ page = _make_page()
+ frame = SimpleNamespace(
+ name="payment",
+ url="https://example.com/payment-frame",
+ title=AsyncMock(return_value="Payment"),
+ evaluate=_mock_dom_evaluate(
+ [
+ {
+ "role": "button",
+ "name": "Frame action",
+ "tag": "button",
+ "selector": "#frame-action",
+ }
+ ]
+ ),
+ )
+
+ async def goto(url: str) -> None:
+ frame.url = url
+
+ frame.goto = AsyncMock(side_effect=goto)
+ page._working_frame = frame
+ ctx = BrowserContext(mode="local")
+ state = make_session_state(context=ctx)
+ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
+ click = AsyncMock(return_value={"ok": True, "data": None})
+ monkeypatch.setattr(mcp_browser, "skyvern_click", click)
+
+ async with scoped_session(state):
+ observed = await mcp_browser.skyvern_observe()
+ ref = observed["data"]["elements"][0]["ref"]
+ await frame.goto("https://example.com/replacement-frame")
+ result = await mcp_browser.skyvern_execute(steps=[{"tool": "click", "params": {"ref": ref}}])
+
+ assert result["data"]["results"][0]["error"] == (
+ f"Unknown ref '{ref}' — call observe first or check ref exists"
+ )
+ click.assert_not_awaited()
+
@pytest.mark.asyncio
async def test_execute_does_not_resolve_ref_from_different_session(self, monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_page()
@@ -1403,8 +1711,8 @@ class TestSkyvernExecuteMCP:
url="https://example.com/form",
title=AsyncMock(return_value="Form"),
accessibility=None,
- evaluate=AsyncMock(
- return_value=[
+ evaluate=_mock_dom_evaluate(
+ [
{
"role": "option",
"name": "East",
diff --git a/tests/unit/test_quickstart_command.py b/tests/unit/test_quickstart_command.py
index 3d5a87b66..113e43e13 100644
--- a/tests/unit/test_quickstart_command.py
+++ b/tests/unit/test_quickstart_command.py
@@ -261,6 +261,8 @@ def test_run_mcp_prepares_cloud_env_before_starting_mcp(tmp_path, monkeypatch) -
monkeypatch.delenv(key, raising=False)
monkeypatch.setattr(_cli_bootstrap, "_RUNTIME_LOGGING_CONFIGURED", False)
monkeypatch.setattr(run_commands.atexit, "register", lambda _: None)
+ eof_event = types.SimpleNamespace(set=lambda: None)
+ monkeypatch.setattr(run_commands, "_start_stdin_eof_watcher", lambda: (eof_event, eof_event))
monkeypatch.setattr(run_commands, "_cleanup_mcp_resources_blocking", lambda: events.append("cleanup"))
monkeypatch.setitem(sys.modules, "skyvern.forge.sdk.forge_log", fake_forge_log)
monkeypatch.setitem(sys.modules, "skyvern.cli.core.mcp_http_auth", fake_auth)
diff --git a/tests/unit/test_record_browser_teardown_integration.py b/tests/unit/test_record_browser_teardown_integration.py
new file mode 100644
index 000000000..1b845c153
--- /dev/null
+++ b/tests/unit/test_record_browser_teardown_integration.py
@@ -0,0 +1,115 @@
+"""Integration coverage for Record Browser teardown when the browser target closes.
+
+Reproduces SKY-12366 across the components that ``message.py`` wires together on
+``END_EXFILTRATION``: the exfiltration channel is stopped (message.py:727) and then
+the live interpretation session is flushed (message.py:731). When the page target has
+already closed (take-control swaps, navigations, bot-detection pages), the channel's
+``undecorate`` used to raise ``TargetClosedError`` out of ``stop()`` — so the flush
+never ran, the accumulated drafts were lost, and the recording produced no blocks.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from playwright._impl._errors import TargetClosedError
+
+from skyvern.forge import app
+from skyvern.forge.sdk.routes.streaming.channels.exfiltration import ExfiltratedEvent as StreamingExfiltratedEvent
+from skyvern.forge.sdk.routes.streaming.channels.exfiltration import (
+ ExfiltratedEventSource as StreamingExfiltratedEventSource,
+)
+from skyvern.forge.sdk.routes.streaming.channels.exfiltration import (
+ ExfiltrationChannel,
+)
+from skyvern.services.browser_recording.service import Processor
+from skyvern.services.browser_recording.session_registry import RecordingInterpretationSessionRegistry
+
+ORG_ID = "org_123"
+PBS_ID = "pbs_123"
+WP_ID = "wpid_123"
+
+
+def _click_event(*, capture_seq: int, sky_id: str, target_id: str) -> StreamingExfiltratedEvent:
+ return StreamingExfiltratedEvent(
+ event_name="user_interaction",
+ source=StreamingExfiltratedEventSource.CONSOLE,
+ timestamp=1000.0 + capture_seq,
+ capture_seq=capture_seq,
+ params={
+ "type": "click",
+ "url": "https://example.com",
+ "timestamp": 1000.0 + capture_seq,
+ "target": {"tagName": "BUTTON", "id": target_id, "text": ["Submit"], "skyId": sky_id},
+ "mousePosition": {"xp": 0.5, "yp": 0.5},
+ "activeElement": {"tagName": "BUTTON"},
+ "window": {"height": 800, "width": 1200, "scrollX": 0, "scrollY": 0},
+ },
+ )
+
+
+def _vnc_channel() -> MagicMock:
+ vnc_channel = MagicMock()
+ vnc_channel.browser_session = MagicMock(
+ browser_address="http://localhost:9222",
+ persistent_browser_session_id=PBS_ID,
+ )
+ vnc_channel.identity = {"client_id": "client-1", "browser_session_id": PBS_ID}
+ return vnc_channel
+
+
+def _channel_with_closed_page() -> ExfiltrationChannel:
+ """An exfiltration channel whose only page's target is already closed."""
+ channel = ExfiltrationChannel(on_event=lambda _messages: None, vnc_channel=_vnc_channel())
+
+ closed_page = MagicMock()
+ closed_page.url = "https://example.com"
+ closed_page.remove_listener = MagicMock()
+ closed_page.evaluate = AsyncMock()
+ closed_page.add_init_script = AsyncMock(
+ side_effect=TargetClosedError("Page.add_init_script: Target page, context or browser has been closed")
+ )
+
+ browser_context = MagicMock()
+ browser_context.pages = [closed_page]
+ channel.browser_context = browser_context
+ return channel
+
+
+async def test_end_exfiltration_on_closed_target_preserves_drafts_into_blocks(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def fake_llm(*args: object, **kwargs: object) -> dict[str, object]:
+ return {"block_label": "click_submit", "title": "Click Submit", "prompt": "Click the submit button."}
+
+ monkeypatch.setattr(app, "LLM_API_HANDLER", fake_llm)
+
+ # A live recording that has accumulated drafts (what the user sees in the panel).
+ registry = RecordingInterpretationSessionRegistry()
+ registry.start_session(
+ browser_session_id=PBS_ID,
+ organization_id=ORG_ID,
+ workflow_permanent_id=WP_ID,
+ on_update=lambda _update: None,
+ recording_attempt_id="attempt-1",
+ )
+ session = registry._sessions[PBS_ID]
+ registry.ingest_events(
+ PBS_ID,
+ [
+ _click_event(capture_seq=0, sky_id="sky-a", target_id="a"),
+ _click_event(capture_seq=1, sky_id="sky-b", target_id="b"),
+ ],
+ )
+ await session._interpret(finalized=False)
+ assert session.steps, "precondition: the recording accumulated drafts"
+
+ # Replay the END_EXFILTRATION handler sequence against a closed browser target.
+ channel = _channel_with_closed_page()
+ await channel.stop() # message.py:727 — must not raise on a closed target
+ drafts = await registry.stop_session(PBS_ID) # message.py:731 — only reached if stop() didn't crash
+
+ # The drafts survived teardown and convert into real workflow blocks.
+ assert drafts, "teardown dropped the recorded drafts"
+ blocks = Processor(PBS_ID, ORG_ID, WP_ID).drafts_to_blocks(drafts)
+ assert blocks, "surviving drafts did not produce workflow blocks"
diff --git a/tests/unit/test_run_commands_cleanup.py b/tests/unit/test_run_commands_cleanup.py
index 7b2323b1f..db91d0838 100644
--- a/tests/unit/test_run_commands_cleanup.py
+++ b/tests/unit/test_run_commands_cleanup.py
@@ -1,6 +1,7 @@
from __future__ import annotations
-import asyncio
+import threading
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, call
import pytest
@@ -11,6 +12,8 @@ from skyvern.cli import run_commands
@pytest.fixture(autouse=True)
def _reset_cleanup_state() -> None:
run_commands._mcp_cleanup_done = False
+ run_commands._mcp_cleanup_in_progress = False
+ run_commands._mcp_eof_shutdown_requested = False
@pytest.mark.asyncio
@@ -49,29 +52,55 @@ async def test_cleanup_mcp_resources_closes_auth_db_on_skyvern_close_error(monke
close_auth_db.assert_awaited_once()
-def test_cleanup_mcp_resources_sync_runs_without_running_loop(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_cleanup_mcp_resources_sync_skips_threaded_cleanup_for_local_browser(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
cleanup = AsyncMock()
+ fallback = MagicMock()
+ rmtree = MagicMock()
+ thread = MagicMock()
monkeypatch.setattr(run_commands, "_cleanup_mcp_resources", cleanup)
+ monkeypatch.setattr(
+ run_commands,
+ "_current_local_browser_identity",
+ lambda: (40101, "/tmp/skyvern-browser-owned", True),
+ )
+ monkeypatch.setattr(run_commands, "_kill_local_browser_process_tree", fallback)
+ monkeypatch.setattr(run_commands.shutil, "rmtree", rmtree)
+ monkeypatch.setattr(run_commands.threading, "Thread", thread)
run_commands._cleanup_mcp_resources_sync()
- cleanup.assert_awaited_once()
+ cleanup.assert_not_awaited()
+ thread.assert_not_called()
+ fallback.assert_called_once_with(40101, "/tmp/skyvern-browser-owned")
+ rmtree.assert_called_once_with("/tmp/skyvern-browser-owned", ignore_errors=True)
assert run_commands._mcp_cleanup_done is True
-async def test_cleanup_mcp_resources_sync_skips_when_loop_running(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_cleanup_mcp_resources_sync_keeps_threaded_graceful_cleanup_without_local_browser(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class RecordingThread(threading.Thread):
+ joined_with: float | None = None
+
+ def join(self, timeout: float | None = None) -> None:
+ type(self).joined_with = timeout
+ super().join(timeout)
+
cleanup = AsyncMock()
monkeypatch.setattr(run_commands, "_cleanup_mcp_resources", cleanup)
+ monkeypatch.setattr(run_commands, "_current_local_browser_identity", lambda: None)
+ monkeypatch.setattr(run_commands.threading, "Thread", RecordingThread)
run_commands._cleanup_mcp_resources_sync()
- await asyncio.sleep(0)
- cleanup.assert_not_awaited()
- assert run_commands._mcp_cleanup_done is False
+ cleanup.assert_awaited_once()
+ assert RecordingThread.joined_with == run_commands._MCP_GRACEFUL_CLEANUP_TIMEOUT_SECONDS == 5.0
+ assert run_commands._mcp_cleanup_done is True
-def test_cleanup_mcp_resources_sync_keeps_retry_possible_on_task_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_cleanup_mcp_resources_sync_suppresses_task_failure(monkeypatch: pytest.MonkeyPatch) -> None:
async def failing_cleanup() -> None:
raise RuntimeError("cleanup failed")
@@ -79,27 +108,252 @@ def test_cleanup_mcp_resources_sync_keeps_retry_possible_on_task_failure(monkeyp
run_commands._cleanup_mcp_resources_sync()
- assert run_commands._mcp_cleanup_done is False
+ assert run_commands._mcp_cleanup_done is True
-def test_run_mcp_calls_blocking_cleanup_in_finally(monkeypatch: pytest.MonkeyPatch) -> None:
- cleanup_blocking = MagicMock()
+def test_cleanup_mcp_resources_blocking_ignores_reentrant_call(monkeypatch: pytest.MonkeyPatch) -> None:
+ cleanup = AsyncMock()
+
+ def identify() -> None:
+ assert run_commands._mcp_cleanup_in_progress is True
+ run_commands._cleanup_mcp_resources_blocking()
+ return None
+
+ identify = MagicMock(side_effect=identify)
+ monkeypatch.setattr(run_commands, "_cleanup_mcp_resources", cleanup)
+ monkeypatch.setattr(run_commands, "_current_local_browser_identity", identify)
+
+ run_commands._cleanup_mcp_resources_blocking()
+
+ identify.assert_called_once_with()
+ cleanup.assert_awaited_once_with()
+
+
+def test_cleanup_mcp_resources_sync_preserves_explicit_user_data_dir(monkeypatch: pytest.MonkeyPatch) -> None:
+ cleanup = AsyncMock()
+ fallback = MagicMock()
+ rmtree = MagicMock()
+ monkeypatch.setattr(run_commands, "_cleanup_mcp_resources", cleanup)
+ monkeypatch.setattr(
+ run_commands,
+ "_current_local_browser_identity",
+ lambda: (40101, "/tmp/skyvern-browser-explicit", False),
+ )
+ monkeypatch.setattr(run_commands, "_kill_local_browser_process_tree", fallback)
+ monkeypatch.setattr(run_commands.shutil, "rmtree", rmtree)
+
+ run_commands._cleanup_mcp_resources_sync()
+
+ cleanup.assert_not_awaited()
+ fallback.assert_called_once_with(40101, "/tmp/skyvern-browser-explicit")
+ rmtree.assert_not_called()
+
+
+def test_stdin_eof_watcher_allows_native_clean_return(monkeypatch: pytest.MonkeyPatch) -> None:
+ poller = MagicMock()
+ poller.poll.return_value = [(123, run_commands.select.POLLHUP)]
+ monkeypatch.setattr(run_commands.select, "poll", lambda: poller)
+ request_shutdown, force_exit = MagicMock(), MagicMock()
+ stop = MagicMock(**{"is_set.side_effect": [False, False, True]})
+
+ run_commands._watch_stdin_eof(
+ stop,
+ MagicMock(**{"wait.return_value": False}),
+ stdin_fd=123,
+ request_shutdown=request_shutdown,
+ force_exit=force_exit,
+ )
+
+ request_shutdown.assert_not_called()
+ force_exit.assert_not_called()
+
+
+def test_stdin_eof_watcher_force_exits_after_bounded_local_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
+ poller = MagicMock()
+ poller.poll.return_value = [(123, run_commands.select.POLLHUP)]
+ monkeypatch.setattr(run_commands.select, "poll", lambda: poller)
+ monkeypatch.setattr(run_commands, "_current_local_browser_identity", lambda: (40101, "/tmp/owned", True))
+ fallback, force_exit = MagicMock(), MagicMock()
+ rmtree = MagicMock()
+ monkeypatch.setattr(run_commands, "_kill_local_browser_process_tree", fallback)
+ monkeypatch.setattr(run_commands.shutil, "rmtree", rmtree)
+
+ run_commands._watch_stdin_eof(
+ threading.Event(),
+ threading.Event(),
+ stdin_fd=123,
+ request_shutdown=MagicMock(),
+ force_exit=force_exit,
+ native_eof_grace=0,
+ shutdown_timeout=0,
+ )
+
+ fallback.assert_called_once_with(40101, "/tmp/owned")
+ rmtree.assert_called_once_with("/tmp/owned", ignore_errors=True)
+ force_exit.assert_called_once_with(0)
+ assert run_commands._mcp_eof_shutdown_requested is True
+
+
+def test_local_browser_process_matching_is_scoped_to_instance(monkeypatch: pytest.MonkeyPatch) -> None:
+ unreadable = SimpleNamespace(pid=10, info=None)
+ matching_dir = SimpleNamespace(pid=11, info={"cmdline": ["chrome", "--user-data-dir=/tmp/owned"]})
+ unrelated = SimpleNamespace(pid=12, info={"cmdline": ["chrome", "--user-data-dir=/tmp/other"]})
+ get_pids_on_port = MagicMock(side_effect=AssertionError("port-only matching is unsafe"))
+ monkeypatch.setattr(run_commands, "get_pids_on_port", get_pids_on_port)
+ monkeypatch.setattr(run_commands.psutil, "process_iter", lambda _attrs: [unreadable, matching_dir, unrelated])
+
+ assert {process.pid for process in run_commands._find_local_browser_processes(40101, "/tmp/owned")} == {11}
+ assert run_commands._find_local_browser_processes(40101, None) == []
+ get_pids_on_port.assert_not_called()
+
+
+def test_mcp_eof_shutdown_ceiling_exceeds_worst_case_cleanup() -> None:
+ # The EOF watcher's os._exit(0) preempts cleanup unconditionally, so this must cover the cloud path.
+ assert run_commands._MCP_EOF_SHUTDOWN_TIMEOUT_SECONDS > (
+ run_commands._MCP_GRACEFUL_CLEANUP_TIMEOUT_SECONDS + run_commands._MCP_PROCESS_KILL_TIMEOUT_SECONDS
+ )
+
+
+def test_local_browser_fallback_kills_only_matching_process_tree(monkeypatch: pytest.MonkeyPatch) -> None:
+ child = MagicMock(pid=20)
+ root = MagicMock(pid=10)
+ captured_before_graceful_close = MagicMock(pid=30)
+ root.children.return_value = [child]
+ monkeypatch.setattr(run_commands, "_find_local_browser_processes", lambda _port, _dir: [root])
+ wait_procs = MagicMock(return_value=([], []))
+ monkeypatch.setattr(run_commands.psutil, "wait_procs", wait_procs)
+
+ run_commands._kill_local_browser_process_tree(
+ 40101, "/tmp/skyvern-browser-owned", known_processes=[captured_before_graceful_close]
+ )
+
+ root.kill.assert_called_once_with()
+ child.kill.assert_called_once_with()
+ captured_before_graceful_close.kill.assert_called_once_with()
+ wait_procs.assert_called_once()
+
+
+ ("signum", "eof_shutdown", "expected_exit_code"),
+ [
+ ("SIGTERM", False, 143),
+ ("SIGTERM", True, 143),
+ ("SIGINT", False, 130),
+ ("SIGINT", True, 0),
+ ],
+)
+def test_mcp_shutdown_signal_uses_source_specific_exit_code(
+ monkeypatch: pytest.MonkeyPatch,
+ signum: str,
+ eof_shutdown: bool,
+ expected_exit_code: int,
+) -> None:
+ cleanup, force_exit = MagicMock(), MagicMock()
+ run_commands._mcp_eof_shutdown_requested = eof_shutdown
+ monkeypatch.setattr(run_commands, "_cleanup_mcp_resources_blocking", cleanup)
+ monkeypatch.setattr(run_commands.os, "_exit", force_exit)
+
+ run_commands._handle_mcp_shutdown_signal(getattr(run_commands.signal, signum), None)
+
+ cleanup.assert_called_once_with()
+ force_exit.assert_called_once_with(expected_exit_code)
+
+
+def test_mcp_shutdown_signal_exits_even_when_cleanup_raises(monkeypatch: pytest.MonkeyPatch) -> None:
+ force_exit = MagicMock()
+ run_commands._mcp_eof_shutdown_requested = False
+ monkeypatch.setattr(
+ run_commands, "_cleanup_mcp_resources_blocking", MagicMock(side_effect=RuntimeError("cleanup blew up"))
+ )
+ monkeypatch.setattr(run_commands.os, "_exit", force_exit)
+
+ with pytest.raises(RuntimeError, match="cleanup blew up"):
+ run_commands._handle_mcp_shutdown_signal(run_commands.signal.SIGTERM, None)
+
+ force_exit.assert_called_once_with(143)
+
+
+def test_mcp_shutdown_signal_does_not_exit_during_cleanup(monkeypatch: pytest.MonkeyPatch) -> None:
+ cleanup, force_exit = MagicMock(), MagicMock()
+ run_commands._mcp_cleanup_in_progress = True
+ monkeypatch.setattr(run_commands, "_cleanup_mcp_resources_blocking", cleanup)
+ monkeypatch.setattr(run_commands.os, "_exit", force_exit)
+
+ run_commands._handle_mcp_shutdown_signal(run_commands.signal.SIGINT, None)
+
+ cleanup.assert_not_called()
+ force_exit.assert_not_called()
+
+
+def test_run_mcp_sigterm_calls_blocking_cleanup_in_finally(monkeypatch: pytest.MonkeyPatch) -> None:
+ cleanup_blocking, force_exit = MagicMock(), MagicMock(side_effect=KeyboardInterrupt)
register = MagicMock()
- run = MagicMock(side_effect=RuntimeError("boom"))
+ signal_install = MagicMock(return_value=run_commands.signal.SIG_DFL)
+ run = MagicMock(side_effect=lambda **_kwargs: run_commands._handle_mcp_shutdown_signal(15, None))
set_stateless = MagicMock()
+ eof_event = MagicMock()
monkeypatch.setattr(run_commands, "_cleanup_mcp_resources_blocking", cleanup_blocking)
+ monkeypatch.setattr(run_commands, "_start_stdin_eof_watcher", lambda: (eof_event, eof_event))
+ monkeypatch.setattr(run_commands.os, "_exit", force_exit)
+ monkeypatch.setattr(run_commands.signal, "signal", signal_install)
monkeypatch.setattr(run_commands.atexit, "register", register)
monkeypatch.setattr("skyvern.cli.mcp_tools.mcp.run", run)
monkeypatch.setattr("skyvern.cli.core.session_manager.set_stateless_http_mode", set_stateless)
- with pytest.raises(RuntimeError, match="boom"):
+ with pytest.raises(KeyboardInterrupt):
run_commands.run_mcp()
register.assert_called_once_with(run_commands._cleanup_mcp_resources_sync)
+ assert call(run_commands.signal.SIGTERM, run_commands._handle_mcp_shutdown_signal) in signal_install.call_args_list
run.assert_called_once_with(transport="stdio")
set_stateless.assert_has_calls([call(False), call(False)])
- cleanup_blocking.assert_called_once()
+ assert cleanup_blocking.call_count == 2 and force_exit.call_args == call(143)
+
+
+def test_run_mcp_restores_signal_handlers_after_cleanup(monkeypatch: pytest.MonkeyPatch) -> None:
+ events: list[str] = []
+ originals = {run_commands.signal.SIGINT: object(), run_commands.signal.SIGTERM: object()}
+
+ def install_signal_handler(handled_signal: run_commands.signal.Signals, handler: object) -> object:
+ if handler is run_commands._handle_mcp_shutdown_signal:
+ return originals[handled_signal]
+ events.append("restore")
+ return handler
+
+ monkeypatch.setattr(run_commands.signal, "signal", install_signal_handler)
+ monkeypatch.setattr(run_commands, "_start_stdin_eof_watcher", lambda: (MagicMock(), MagicMock()))
+ monkeypatch.setattr(run_commands, "_cleanup_mcp_resources_blocking", lambda: events.append("cleanup"))
+ monkeypatch.setattr(run_commands.atexit, "register", MagicMock())
+ monkeypatch.setattr("skyvern.cli.mcp_tools.mcp.run", MagicMock())
+
+ run_commands.run_mcp()
+
+ assert events == ["cleanup", "restore", "restore"]
+
+
+def test_run_mcp_stdin_eof_invokes_blocking_cleanup(monkeypatch: pytest.MonkeyPatch) -> None:
+ cleanup_blocking = MagicMock()
+ request_shutdown, force_exit = MagicMock(), MagicMock()
+ eof_detected = threading.Event()
+ poller = MagicMock()
+ poller.poll.side_effect = lambda _timeout: (eof_detected.set(), [(123, run_commands.select.POLLHUP)])[1]
+
+ def return_on_eof(**_kwargs: object) -> None:
+ assert eof_detected.wait(1)
+
+ monkeypatch.setattr(run_commands, "_cleanup_mcp_resources_blocking", cleanup_blocking)
+ monkeypatch.setattr(run_commands._thread, "interrupt_main", request_shutdown)
+ monkeypatch.setattr(run_commands.os, "_exit", force_exit)
+ monkeypatch.setattr(run_commands.select, "poll", lambda: poller)
+ monkeypatch.setattr(run_commands.atexit, "register", MagicMock())
+ monkeypatch.setattr("skyvern.cli.mcp_tools.mcp.run", return_on_eof)
+
+ run_commands.run_mcp()
+
+ cleanup_blocking.assert_called_once_with()
+ request_shutdown.assert_not_called()
+ force_exit.assert_not_called()
def test_run_mcp_http_transport_wires_auth_middleware(monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/tests/unit/test_script_skyvern_page.py b/tests/unit/test_script_skyvern_page.py
index 481238eb1..e3059dcc3 100644
--- a/tests/unit/test_script_skyvern_page.py
+++ b/tests/unit/test_script_skyvern_page.py
@@ -11,7 +11,7 @@ import inspect
import re
import time
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, call, patch
import pytest
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
@@ -2172,6 +2172,10 @@ async def test_direct_fill_dispatch_failure_does_not_regress_fill(mock_scraped_p
# =============================================================================
# Tests for selector fallback prep opt-out — SKY-12096
+#
+# Patching skyvern_page.asyncio.sleep rebinds the GLOBAL asyncio.sleep, so the mock also
+# records sleeps from coroutines running on other threads' event loops. Assert on locator
+# behavior or on this path's own sleep values — never on bare await_args.
# =============================================================================
@@ -2193,7 +2197,7 @@ async def test_selector_fallback_default_runs_element_prep(mock_scraped_page, mo
assert ("wait_for", "attached") in locator.calls
assert ("wait_for", "visible") in locator.calls
assert ("scroll_into_view_if_needed", None) in locator.calls
- assert sleep.await_args is not None
+ assert call(0.15) in sleep.await_args_list
@pytest.mark.asyncio
@@ -2215,9 +2219,9 @@ async def test_selector_fallback_prep_opt_out_uses_playwright_actionability(
result = await skyvern_page.type("#target", "Noor", _skip_element_prep=True)
assert result in ("#target", "Noor")
- assert not any(call[0] == "wait_for" for call in locator.calls)
+ assert not any(recorded[0] == "wait_for" for recorded in locator.calls)
assert ("scroll_into_view_if_needed", None) not in locator.calls
- assert sleep.await_args is None
+ assert call(0.15) not in sleep.await_args_list
@pytest.mark.asyncio
@@ -2225,11 +2229,12 @@ async def test_selector_click_prep_opt_out_preserves_direct_timeout_failure(mock
locator = _RecordingLocator(click_error=PlaywrightTimeoutError("Timeout 5000ms exceeded."))
skyvern_page = _skyvern_page_with_locator(mock_ai, locator)
- with patch("skyvern.core.script_generations.skyvern_page.asyncio.sleep", new_callable=AsyncMock) as sleep:
+ with patch("skyvern.core.script_generations.skyvern_page.asyncio.sleep", new_callable=AsyncMock):
with pytest.raises(PlaywrightTimeoutError):
await skyvern_page.click("#target", _skip_element_prep=True, timeout=5000)
- assert sleep.await_args is None
+ # A single click means the escape-dismiss retry never ran.
+ assert [recorded for recorded in locator.calls if recorded[0] == "click"] == [("click", None)]
@pytest.mark.asyncio
@@ -2239,8 +2244,12 @@ async def test_selector_click_prep_opt_out_keeps_escape_retry_for_interception(m
)
skyvern_page = _skyvern_page_with_locator(mock_ai, locator)
- with patch("skyvern.core.script_generations.skyvern_page.asyncio.sleep", new_callable=AsyncMock) as sleep:
+ with patch("skyvern.core.script_generations.skyvern_page.asyncio.sleep", new_callable=AsyncMock):
with pytest.raises(PlaywrightTimeoutError):
await skyvern_page.click("#target", _skip_element_prep=True, timeout=5000)
- assert sleep.await_args is not None
+ # The second click is the retry after dismissing the intercepting overlay.
+ assert [recorded for recorded in locator.calls if recorded[0] == "click"] == [
+ ("click", None),
+ ("click", None),
+ ]
diff --git a/tests/unit/test_sdk_run_metadata.py b/tests/unit/test_sdk_run_metadata.py
index 902bdc8f5..84c0e4f88 100644
--- a/tests/unit/test_sdk_run_metadata.py
+++ b/tests/unit/test_sdk_run_metadata.py
@@ -1,5 +1,6 @@
import json
from datetime import UTC, datetime
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -8,9 +9,14 @@ import pytest
from skyvern.client import AsyncSkyvern, Skyvern
from skyvern.client.types.workflow_run_request_output import WorkflowRunRequestOutput as WorkflowRunRequest
+from skyvern.library.constants import DEFAULT_CDP_PORT
from skyvern.library.skyvern import Skyvern as LibrarySkyvern
+def _make_browser(_client: object, _context: object, **kwargs: object) -> SimpleNamespace:
+ return SimpleNamespace(**kwargs)
+
+
def test_workflow_run_request_accepts_run_metadata() -> None:
request = WorkflowRunRequest(workflow_id="wpid_123", run_metadata={"customer": "acme"})
@@ -46,6 +52,146 @@ async def test_launch_cloud_browser_sends_browser_profile_id(monkeypatch: pytest
connect_to_session.assert_awaited_once_with(browser_session)
+async def test_skyvern_launch_local_browser_uses_unique_anonymous_instance_defaults(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ client = LibrarySkyvern(base_url="https://api.example.test", api_key="test-key")
+ assigned_ports = iter((40101, 40102))
+
+ async def launch_persistent_context(**kwargs: object) -> object:
+ user_data_dir = Path(str(kwargs["user_data_dir"]))
+ (user_data_dir / "DevToolsActivePort").write_text(f"{next(assigned_ports)}\n/devtools/browser/test\n")
+ return object()
+
+ launch = AsyncMock(side_effect=launch_persistent_context)
+ playwright = SimpleNamespace(chromium=SimpleNamespace(launch_persistent_context=launch))
+ monkeypatch.setattr(client, "_get_playwright", AsyncMock(return_value=playwright))
+ monkeypatch.setattr("skyvern.library.skyvern.tempfile.gettempdir", lambda: str(tmp_path))
+ instance_dirs = iter((tmp_path / "skyvern-browser-one", tmp_path / "skyvern-browser-two"))
+
+ def make_instance_dir(*, prefix: str) -> str:
+ assert prefix == "skyvern-browser-"
+ path = next(instance_dirs)
+ path.mkdir()
+ return str(path)
+
+ monkeypatch.setattr("skyvern.library.skyvern.tempfile.mkdtemp", make_instance_dir)
+ monkeypatch.setattr("skyvern.library.skyvern_browser.SkyvernBrowser", _make_browser)
+
+ first = await client.launch_local_browser(headless=True)
+ second = await client.launch_local_browser(headless=True)
+
+ first_call, second_call = launch.await_args_list
+ first_dir = Path(first_call.kwargs["user_data_dir"])
+ second_dir = Path(second_call.kwargs["user_data_dir"])
+ assert first_dir != second_dir
+ assert [call.kwargs["args"] for call in (first_call, second_call)] == [["--remote-debugging-port=0"]] * 2
+ assert first.browser_address == "http://localhost:40101"
+ assert second.browser_address == "http://localhost:40102"
+ assert first.local_cdp_port == 40101
+ assert second.local_cdp_port == 40102
+ assert first.local_user_data_dir == str(first_dir)
+ assert second.local_user_data_dir == str(second_dir)
+ assert first.local_user_data_dir_owned is True
+ assert second.local_user_data_dir_owned is True
+
+
+ ("launch_kwargs", "expected_dir", "expected_port"),
+ [
+ ({"user_data_dir": "custom-profile"}, Path("custom-profile"), DEFAULT_CDP_PORT),
+ ({"port": 9333}, Path("skyvern-browser"), 9333),
+ ({"user_data_dir": "custom-profile", "port": 9333}, Path("custom-profile"), 9333),
+ ],
+)
+async def test_skyvern_launch_local_browser_preserves_explicit_config_defaults(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ launch_kwargs: dict[str, object],
+ expected_dir: Path,
+ expected_port: int,
+) -> None:
+ client = LibrarySkyvern(base_url="https://api.example.test", api_key="test-key")
+ launch = AsyncMock(return_value=object())
+ playwright = SimpleNamespace(chromium=SimpleNamespace(launch_persistent_context=launch))
+ monkeypatch.setattr(client, "_get_playwright", AsyncMock(return_value=playwright))
+ monkeypatch.setattr("skyvern.library.skyvern.tempfile.gettempdir", lambda: str(tmp_path))
+ monkeypatch.setattr("skyvern.library.skyvern_browser.SkyvernBrowser", _make_browser)
+
+ browser = await client.launch_local_browser(**launch_kwargs) # type: ignore[arg-type]
+
+ call_kwargs = launch.await_args.kwargs
+ resolved_expected_dir = expected_dir if launch_kwargs.get("user_data_dir") else tmp_path / expected_dir
+ assert call_kwargs == {
+ "user_data_dir": str(resolved_expected_dir),
+ "headless": False,
+ "args": [f"--remote-debugging-port={expected_port}"],
+ }
+ assert browser.browser_address == f"http://localhost:{expected_port}"
+ assert browser.local_cdp_port == expected_port
+ assert browser.local_user_data_dir == str(resolved_expected_dir)
+ assert browser.local_user_data_dir_owned is False
+
+
[email protected]("failure_stage", ["launch", "port_read"])
+async def test_skyvern_launch_local_browser_removes_owned_dir_on_setup_failure(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ failure_stage: str,
+) -> None:
+ client = LibrarySkyvern(base_url="https://api.example.test", api_key="test-key")
+ browser_context = SimpleNamespace(close=AsyncMock())
+ launch_fails = failure_stage == "launch"
+ launch = AsyncMock(
+ side_effect=RuntimeError("chromium failed to start") if launch_fails else None,
+ return_value=None if launch_fails else browser_context,
+ )
+ playwright = SimpleNamespace(chromium=SimpleNamespace(launch_persistent_context=launch))
+ user_data_dir = tmp_path / "skyvern-browser-failed"
+ user_data_dir.mkdir()
+
+ monkeypatch.setattr(client, "_get_playwright", AsyncMock(return_value=playwright))
+ monkeypatch.setattr("skyvern.library.skyvern.tempfile.gettempdir", lambda: str(tmp_path))
+ monkeypatch.setattr("skyvern.library.skyvern.tempfile.mkdtemp", lambda *, prefix: str(user_data_dir))
+ monkeypatch.setattr(
+ "skyvern.library.skyvern._read_devtools_active_port",
+ AsyncMock(side_effect=RuntimeError("missing port")),
+ )
+
+ with pytest.raises(RuntimeError, match="chromium failed to start" if launch_fails else "missing port"):
+ await client.launch_local_browser()
+
+ if launch_fails:
+ browser_context.close.assert_not_awaited()
+ else:
+ browser_context.close.assert_awaited_once_with()
+ assert not user_data_dir.exists()
+
+
[email protected]("owned", [True, False])
+async def test_skyvern_browser_close_removes_only_owned_user_data_dir(tmp_path: Path, owned: bool) -> None:
+ from skyvern.library.skyvern_browser import SkyvernBrowser
+
+ user_data_dir = tmp_path / ("owned" if owned else "explicit")
+ user_data_dir.mkdir()
+ browser_context = SimpleNamespace(close=AsyncMock())
+ browser = object.__new__(SkyvernBrowser)
+ object.__setattr__(browser, "_browser_context", browser_context)
+ object.__setattr__(browser, "_browser_session_id", None)
+ object.__setattr__(browser, "_local_user_data_dir", str(user_data_dir))
+ object.__setattr__(browser, "_local_user_data_dir_owned", owned)
+
+ await browser.close()
+
+ browser_context.close.assert_awaited_once_with()
+ assert user_data_dir.exists() is not owned
+
+
def test_run_workflow_sends_run_metadata() -> None:
captured_bodies: list[dict[str, object]] = []
diff --git a/tests/unit/test_secret_encryption.py b/tests/unit/test_secret_encryption.py
new file mode 100644
index 000000000..8c588ac7b
--- /dev/null
+++ b/tests/unit/test_secret_encryption.py
@@ -0,0 +1,146 @@
+from types import SimpleNamespace
+
+import pytest
+
+from skyvern.config import settings
+from skyvern.forge.sdk.workflow.secret_encryption import (
+ ENCRYPTED_SECRET_PREFIX,
+ decrypt_secret_field_value,
+ encrypt_secret_field_value,
+ encrypt_workflow_definition_secrets,
+ is_encrypted_secret,
+)
+from skyvern.schemas.workflows import BlockType
+
+
+def enabled_encryption(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "ENABLE_ENCRYPTION", True)
+ monkeypatch.setattr(settings, "ENCRYPTOR_AES_SECRET_KEY", "unit-test-secret-key-please-0000")
+ monkeypatch.setattr(settings, "ENCRYPTOR_AES_SALT", "unit-test-salt-000")
+
+
+def disabled_encryption(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "ENABLE_ENCRYPTION", False)
+ monkeypatch.setattr(settings, "ENCRYPTOR_AES_SECRET_KEY", "unit-test-secret-key-please-0000")
+ monkeypatch.setattr(settings, "ENCRYPTOR_AES_SALT", "unit-test-salt-000")
+
+
+async def test_encrypt_secret_field_value_preserves_non_encryptable_values(enabled_encryption: None) -> None:
+ jinja_value = "{{ secret_parameter }}"
+ encrypted_value = f"{ENCRYPTED_SECRET_PREFIX}aesgcm-v1:existing"
+
+ assert (
+ await encrypt_secret_field_value(jinja_value, organization_id="o_a", field_name="sftp_password") == jinja_value
+ )
+ assert (
+ await encrypt_secret_field_value(encrypted_value, organization_id="o_a", field_name="sftp_password")
+ == encrypted_value
+ )
+
+
+async def test_encrypt_secret_field_value_is_disabled(disabled_encryption: None) -> None:
+ plaintext = "disabled-test-value"
+
+ assert await encrypt_secret_field_value(plaintext, organization_id="o_a", field_name="sftp_password") == plaintext
+
+
+async def test_encrypt_secret_field_value_encrypts_literal(enabled_encryption: None) -> None:
+ plaintext = "literal-test-value"
+
+ encrypted = await encrypt_secret_field_value(plaintext, organization_id="o_a", field_name="sftp_password")
+
+ assert encrypted is not None
+ assert is_encrypted_secret(encrypted)
+ assert encrypted.startswith(f"{ENCRYPTED_SECRET_PREFIX}aesgcm-v1:")
+ assert plaintext not in encrypted
+
+
+async def test_decrypt_secret_field_value_round_trips(enabled_encryption: None) -> None:
+ plaintext = "round-trip-test-value"
+ encrypted = await encrypt_secret_field_value(plaintext, organization_id="o_a", field_name="sftp_password")
+
+ assert encrypted is not None
+ assert await decrypt_secret_field_value(encrypted, organization_id="o_a", field_name="sftp_password") == plaintext
+
+
+async def test_encrypted_secret_cannot_move_to_another_field(enabled_encryption: None) -> None:
+ plaintext = "field-binding-test-value"
+ encrypted = await encrypt_secret_field_value(
+ plaintext,
+ organization_id="o_a",
+ field_name="aws_secret_access_key",
+ )
+ assert encrypted is not None
+
+ with pytest.raises(ValueError) as exc_info:
+ await decrypt_secret_field_value(encrypted, organization_id="o_a", field_name="sftp_password")
+
+ error = str(exc_info.value)
+ assert plaintext not in error
+ assert encrypted not in error
+
+
+async def test_encrypted_secret_cannot_move_to_another_organization(enabled_encryption: None) -> None:
+ plaintext = "organization-binding-test-value"
+ encrypted = await encrypt_secret_field_value(
+ plaintext,
+ organization_id="o_a",
+ field_name="aws_secret_access_key",
+ )
+ assert encrypted is not None
+
+ with pytest.raises(ValueError) as exc_info:
+ await decrypt_secret_field_value(encrypted, organization_id="o_b", field_name="aws_secret_access_key")
+
+ error = str(exc_info.value)
+ assert plaintext not in error
+ assert encrypted not in error
+
+
+async def test_encrypt_workflow_definition_secrets_recurses_and_binds_fields(enabled_encryption: None) -> None:
+ upload = SimpleNamespace(
+ block_type=BlockType.FILE_UPLOAD,
+ aws_secret_access_key="upload-test-value",
+ azure_storage_account_key=None,
+ sftp_password="{{ sftp_password }}",
+ sftp_private_key=None,
+ sftp_private_key_passphrase=None,
+ )
+ nested_download = SimpleNamespace(
+ block_type=BlockType.FILE_DOWNLOAD,
+ aws_secret_access_key=None,
+ azure_storage_account_key=None,
+ sftp_password="nested-test-value",
+ sftp_private_key=None,
+ sftp_private_key_passphrase=None,
+ )
+ loop = SimpleNamespace(block_type=BlockType.FOR_LOOP, loop_blocks=[nested_download])
+ non_file = SimpleNamespace(block_type=object(), sftp_password="unchanged-test-value")
+ definition = SimpleNamespace(blocks=[upload, loop, non_file])
+
+ await encrypt_workflow_definition_secrets(definition, organization_id="o_x")
+
+ assert is_encrypted_secret(upload.aws_secret_access_key)
+ assert upload.sftp_password == "{{ sftp_password }}"
+ assert is_encrypted_secret(nested_download.sftp_password)
+ assert non_file.sftp_password == "unchanged-test-value"
+
+ with pytest.raises(ValueError) as exc_info:
+ await decrypt_secret_field_value(
+ nested_download.sftp_password,
+ organization_id="o_x",
+ field_name="aws_secret_access_key",
+ )
+
+ error = str(exc_info.value)
+ assert "nested-test-value" not in error
+ assert nested_download.sftp_password not in error
diff --git a/tests/unit/test_sftp_upload.py b/tests/unit/test_sftp_upload.py
index 7de6f7ba5..482f396cd 100644
--- a/tests/unit/test_sftp_upload.py
+++ b/tests/unit/test_sftp_upload.py
@@ -3,7 +3,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import libcst as cst
import pytest
-from skyvern.core.script_generations.generate_script import _build_file_upload_statement
+from skyvern.core.script_generations.generate_script import _build_download_statement, _build_file_upload_statement
from skyvern.exceptions import BlockedHost
from skyvern.forge.agent_functions import AgentFunction
from skyvern.forge.sdk.services import sftp_service
@@ -280,6 +280,112 @@ def test_generated_script_emits_sftp_fields():
assert "sftp_port=2222" in compact
+ ("download_target", "destination_fields"),
+ [
+ (
+ "sftp",
+ {
+ "sftp_host": "h",
+ "sftp_port": 2222,
+ "sftp_username": "u",
+ "sftp_password": "pw",
+ "sftp_private_key": "PEM",
+ "sftp_private_key_passphrase": "secret",
+ "sftp_remote_path": "/incoming",
+ "sftp_host_key": "ssh-ed25519 AAAA",
+ },
+ ),
+ (
+ "s3",
+ {
+ "s3_bucket": "bucket",
+ "aws_access_key_id": "access-key",
+ "aws_secret_access_key": "secret-key",
+ "region_name": "us-east-1",
+ },
+ ),
+ (
+ "azure",
+ {
+ "azure_storage_account_name": "account",
+ "azure_storage_account_key": "account-key",
+ "azure_blob_container_name": "container",
+ "path": "reports",
+ },
+ ),
+ (
+ "google_drive",
+ {
+ "google_credential_id": "credential-id",
+ "google_drive_folder_id": "folder-id",
+ },
+ ),
+ ],
+)
+def test_generated_download_script_emits_destination_fields(download_target, destination_fields):
+ block = {
+ "block_type": "file_download",
+ "label": "download",
+ "navigation_goal": "Download the file",
+ "download_target": download_target,
+ **destination_fields,
+ }
+
+ compact = cst.Module(body=[_build_download_statement("download", block)]).code.replace(" ", "").replace("\n", "")
+
+ assert f"download_target='{download_target}'" in compact
+ for field, value in destination_fields.items():
+ assert f"{field}={value!r}".replace(" ", "") in compact
+
+
+def test_generated_website_download_with_stale_prompt_keeps_required_navigation_prompt():
+ block = {
+ "block_type": "file_download",
+ "label": "download",
+ "navigation_goal": "Download the file",
+ "download_target": "website",
+ "s3_bucket": "stale-bucket",
+ "aws_access_key_id": "stale-key",
+ "aws_secret_access_key": "stale-secret",
+ "prompt": "stale selection prompt",
+ "path": "stale-path",
+ "continue_on_empty": False,
+ }
+
+ compact = cst.Module(body=[_build_download_statement("download", block)]).code.replace(" ", "").replace("\n", "")
+
+ assert "prompt='Downloadthefile'" in compact
+ assert "navigation_goal=" not in compact
+ assert "download_target=" not in compact
+ assert "s3_bucket=" not in compact
+ assert "aws_access_key_id=" not in compact
+ assert "aws_secret_access_key=" not in compact
+ assert "path=" not in compact
+ assert "continue_on_empty=" not in compact
+
+
+def test_generated_external_download_omits_other_targets_stale_secrets():
+ block = {
+ "block_type": "file_download",
+ "label": "download",
+ "navigation_goal": "Download the file",
+ "download_target": "s3",
+ "s3_bucket": "bucket",
+ "aws_access_key_id": "access-key",
+ "aws_secret_access_key": "secret-key",
+ "sftp_password": "stale-sftp-password",
+ "azure_storage_account_key": "stale-azure-key",
+ }
+
+ compact = cst.Module(body=[_build_download_statement("download", block)]).code.replace(" ", "").replace("\n", "")
+
+ assert "download_target='s3'" in compact
+ assert "s3_bucket='bucket'" in compact
+ assert "sftp_password=" not in compact
+ assert "azure_storage_account_key=" not in compact
+
+
def test_generated_script_omits_absent_sftp_fields():
block = {
"label": "sftp_upload",