Skip to content

Automate browser based workflows with AI

Copilot: carry code artifact metadata (verifier-neutral) (#6439)

Andrew Neilsonee1334c14d6a
diff --git a/skyvern-frontend/src/routes/credentials/CredentialItem.tsx b/skyvern-frontend/src/routes/credentials/CredentialItem.tsx
index e24ff48db..8d5de44d2 100644
--- a/skyvern-frontend/src/routes/credentials/CredentialItem.tsx
+++ b/skyvern-frontend/src/routes/credentials/CredentialItem.tsx
@@ -6,6 +6,7 @@ import {
} from "@/api/types";
import { useState } from "react";
import {
+ ExclamationTriangleIcon,
ExternalLinkIcon,
Pencil1Icon,
ReloadIcon,
@@ -43,6 +44,23 @@ function CredentialItem({ credential, onStartBackgroundTest }: Props) {
);
const credentialData = credential.credential;
const modalType = credentialTypeToModalType(credential.credential_type);
+ // Offer re-save for any credential that already has a saved profile, not only ones
+ // flagged with the save-session intent.
+ const canResaveSession = Boolean(
+ credential.save_browser_session_intent || credential.browser_profile_id,
+ );
+ const handleResaveSession = () => {
+ if (credential.tested_url && onStartBackgroundTest) {
+ onStartBackgroundTest(
+ credential.credential_id,
+ credential.tested_url,
+ credential.user_context ?? undefined,
+ );
+ } else {
+ // No URL on record to test against — fall back to the editor where it's entered.
+ setEditModalOpen(true);
+ }
+ };
const getTotpTypeDisplay = (totpType: string) => {
switch (totpType) {
case "authenticator":
@@ -174,6 +192,21 @@ function CredentialItem({ credential, onStartBackgroundTest }: Props) {
)}
</div>
)}
+ {canResaveSession && !credential.browser_profile_id && !activeTest && (
+ <div className="flex items-center gap-1 text-xs">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="flex items-center text-red-400">
+ <ExclamationTriangleIcon className="size-4" />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Browser session was not saved</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <span className="text-red-400">Not saved</span>
+ </div>
+ )}
</div>
{credentialDetails}
<div className="ml-auto flex gap-1">
@@ -190,6 +223,33 @@ function CredentialItem({ credential, onStartBackgroundTest }: Props) {
<TooltipContent>Assign to Folder</TooltipContent>
</Tooltip>
</TooltipProvider>
+ {canResaveSession && (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size="icon"
+ variant="tertiary"
+ className="h-8 w-9"
+ disabled={Boolean(activeTest)}
+ onClick={handleResaveSession}
+ aria-label={
+ credential.browser_profile_id
+ ? "Refresh saved session"
+ : "Retry saving session"
+ }
+ >
+ <ReloadIcon className="size-5" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {credential.browser_profile_id
+ ? "Refresh saved session"
+ : "Retry saving session"}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx
index 09807d5f9..481de52b5 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx
@@ -10,8 +10,11 @@ import {
TurnNarrativeState,
} from "./narrativeState";
-const completedBlock = (label: string): BlockState => ({
- workflowRunBlockId: `wrb_${label}`,
+const completedBlock = (
+ label: string,
+ workflowRunBlockId = `wrb_${label}`,
+): BlockState => ({
+ workflowRunBlockId,
label,
blockType: "navigation",
state: "completed",
@@ -21,6 +24,14 @@ const completedBlock = (label: string): BlockState => ({
endedAt: "2026-05-30T00:00:10Z",
});
+const failedBlock = (
+ label: string,
+ workflowRunBlockId = `wrb_failed_${label}`,
+): BlockState => ({
+ ...completedBlock(label, workflowRunBlockId),
+ state: "failed",
+});
+
const terminalBuildTurn = (): TurnNarrativeState => ({
...EMPTY_NARRATIVE,
turnId: "turn-1",
@@ -145,4 +156,26 @@ describe("NarrativeView collapse default", () => {
expect(screen.getByRole("button", { name: "Collapse turn" })).toBeTruthy();
expect(screen.queryByText(HEADLINE)).toBeNull();
});
+
+ it("summarizes the latest retry attempt for duplicate block labels", () => {
+ render(
+ <NarrativeView
+ turn={{
+ ...terminalBuildTurn(),
+ blocks: [
+ completedBlock("open_site", "wrb_open_first"),
+ failedBlock("add_to_cart", "wrb_add_first"),
+ completedBlock("open_site", "wrb_open_retry"),
+ completedBlock("add_to_cart", "wrb_add_retry"),
+ completedBlock("confirm_cart", "wrb_confirm_retry"),
+ ],
+ }}
+ />,
+ );
+
+ expect(screen.getByText(HEADLINE)).toBeTruthy();
+ expect(screen.queryByText("Run halted")).toBeNull();
+ expect(screen.queryByText("Halted")).toBeNull();
+ expect(screen.getAllByText("add_to_cart")).toHaveLength(1);
+ });
});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
index 2eadbd767..b64bf9363 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
@@ -425,6 +425,14 @@ interface TurnSummary {
isStoppedWithDraft: boolean;
}
+function latestBlocksByLabel(blocks: BlockState[]): BlockState[] {
+ const latest = new Map<string, BlockState>();
+ for (const block of blocks) {
+ latest.set(block.label, block);
+ }
+ return Array.from(latest.values());
+}
+
function asksUserForInput(turn: TurnNarrativeState): boolean {
if (turn.responseType === "ASK_QUESTION") {
return true;
@@ -442,8 +450,9 @@ function asksUserForInput(turn: TurnNarrativeState): boolean {
}
function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {
+ const rollupBlocks = latestBlocksByLabel(turn.blocks);
const isFail =
- turn.terminal === "error" || turn.blocks.some((b) => b.state === "failed");
+ turn.terminal === "error" || rollupBlocks.some((b) => b.state === "failed");
const mode = effectiveMode(turn);
const needsInput = asksUserForInput(turn);
const isQA =
@@ -490,8 +499,8 @@ function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {
const turnElapsed = formatElapsed(turn.startedAt, turn.endedAt);
if (turnElapsed) stats.push(turnElapsed);
if (!isQA) {
- const ok = turn.blocks.filter((b) => b.state === "completed").length;
- const failed = turn.blocks.filter((b) => b.state === "failed").length;
+ const ok = rollupBlocks.filter((b) => b.state === "completed").length;
+ const failed = rollupBlocks.filter((b) => b.state === "failed").length;
const newBlocks = hasEdited ? 0 : (turn.draft?.blockCount ?? 0);
if (ok) stats.push(`${ok} block${ok === 1 ? "" : "s"} ran`);
if (newBlocks) stats.push(`${newBlocks} new`);
@@ -592,8 +601,9 @@ interface RollupCardProps {
function RollupCard({ turn, summary, onExpand }: RollupCardProps) {
const closing =
turn.narrativeSummary?.trim() || turn.terminalMessage?.trim() || "";
- const completed = turn.blocks.filter((b) => b.state === "completed");
- const failed = turn.blocks.filter((b) => b.state === "failed");
+ const rollupBlocks = latestBlocksByLabel(turn.blocks);
+ const completed = rollupBlocks.filter((b) => b.state === "completed");
+ const failed = rollupBlocks.filter((b) => b.state === "failed");
const showCommit = !summary.isQA && completed.length > 0;
return (
diff --git a/skyvern-frontend/src/routes/workflows/editor/collapse/scheduleCollapseRelayout.test.ts b/skyvern-frontend/src/routes/workflows/editor/collapse/scheduleCollapseRelayout.test.ts
new file mode 100644
index 000000000..b6e4531cb
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/collapse/scheduleCollapseRelayout.test.ts
@@ -0,0 +1,110 @@
+// @vitest-environment jsdom
+
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { scheduleCollapseRelayout } from "./scheduleCollapseRelayout";
+
+const EVENT = "conditional-header-resized" as const;
+
+// Manual rAF queue so the two-frame deferral is driven explicitly instead of
+// racing real timers. Handles are monotonic ids (never reused) so a cancel
+// targets exactly the frame it was issued for.
+let rafCallbacks: Map<number, FrameRequestCallback>;
+let nextRafHandle: number;
+
+function flushFrame() {
+ const callbacks = rafCallbacks;
+ rafCallbacks = new Map();
+ callbacks.forEach((cb) => cb(performance.now()));
+}
+
+beforeEach(() => {
+ rafCallbacks = new Map();
+ nextRafHandle = 1;
+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
+ const handle = nextRafHandle++;
+ rafCallbacks.set(handle, cb);
+ return handle;
+ });
+ vi.spyOn(window, "cancelAnimationFrame").mockImplementation((handle) => {
+ rafCallbacks.delete(handle);
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function listenOnce() {
+ const handler = vi.fn();
+ window.addEventListener(EVENT, handler);
+ return {
+ handler,
+ cleanup: () => window.removeEventListener(EVENT, handler),
+ };
+}
+
+describe("scheduleCollapseRelayout", () => {
+ test("expanding dispatches the re-layout event synchronously", () => {
+ const { handler, cleanup } = listenOnce();
+ scheduleCollapseRelayout(EVENT, true, false);
+ expect(handler).toHaveBeenCalledTimes(1);
+ cleanup();
+ });
+
+ test("collapsing dispatches only after two animation frames", () => {
+ const { handler, cleanup } = listenOnce();
+ scheduleCollapseRelayout(EVENT, false, true);
+
+ expect(handler).not.toHaveBeenCalled();
+ flushFrame();
+ expect(handler).not.toHaveBeenCalled();
+ flushFrame();
+ expect(handler).toHaveBeenCalledTimes(1);
+ cleanup();
+ });
+
+ test("the collapse cleanup cancels a still-pending dispatch", () => {
+ const { handler, cleanup } = listenOnce();
+ const dispose = scheduleCollapseRelayout(EVENT, false, true);
+
+ flushFrame(); // first frame scheduled the second
+ dispose(); // unmount / effect re-run before the second frame fires
+ flushFrame();
+
+ expect(handler).not.toHaveBeenCalled();
+ cleanup();
+ });
+
+ test("disposing before the first frame fires cancels the outer frame and never dispatches", () => {
+ const { handler, cleanup } = listenOnce();
+ const dispose = scheduleCollapseRelayout(EVENT, false, true);
+
+ dispose(); // unmount before either frame runs
+ flushFrame();
+ flushFrame();
+
+ expect(handler).not.toHaveBeenCalled();
+ cleanup();
+ });
+
+ test("initial mount in the collapsed state does not dispatch", () => {
+ const { handler, cleanup } = listenOnce();
+ scheduleCollapseRelayout(EVENT, null, true);
+
+ flushFrame();
+ flushFrame();
+ expect(handler).not.toHaveBeenCalled();
+ cleanup();
+ });
+
+ test("a no-op re-render (still expanded) does not dispatch", () => {
+ const { handler, cleanup } = listenOnce();
+ scheduleCollapseRelayout(EVENT, false, false);
+
+ flushFrame();
+ flushFrame();
+ expect(handler).not.toHaveBeenCalled();
+ cleanup();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/collapse/scheduleCollapseRelayout.ts b/skyvern-frontend/src/routes/workflows/editor/collapse/scheduleCollapseRelayout.ts
new file mode 100644
index 000000000..f495ab7ee
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/collapse/scheduleCollapseRelayout.ts
@@ -0,0 +1,44 @@
+// A container block (loop / conditional) drives a canvas re-layout whenever
+// its collapse state flips, because its rendered height changes and every
+// block below it must re-stack. The two transitions need different timing:
+//
+// - Expanding: children become visible again and the layout recomputes the
+// container height from them, so a synchronous dispatch is enough.
+// - Collapsing: the container shrinks to its header card and React Flow
+// re-measures that smaller height asynchronously. Dispatching synchronously
+// would re-run layout against the stale (expanded) height, leaving the
+// block below stranded at the container's old Y. Wait two animation frames
+// for the new measurement to land before dispatching.
+//
+// Returns a cleanup that cancels any frames still pending when the effect
+// re-runs or the node unmounts.
+export function scheduleCollapseRelayout(
+ eventName: "conditional-header-resized" | "loop-header-resized",
+ prevIsCollapsed: boolean | null,
+ isCollapsed: boolean,
+): () => void {
+ const wasCollapsed = prevIsCollapsed === true;
+ const wasExpanded = prevIsCollapsed === false;
+
+ if (wasCollapsed && !isCollapsed) {
+ window.dispatchEvent(new Event(eventName));
+ return () => {};
+ }
+
+ if (wasExpanded && isCollapsed) {
+ let innerFrame: number | null = null;
+ const outerFrame = requestAnimationFrame(() => {
+ innerFrame = requestAnimationFrame(() => {
+ window.dispatchEvent(new Event(eventName));
+ });
+ });
+ return () => {
+ cancelAnimationFrame(outerFrame);
+ if (innerFrame !== null) {
+ cancelAnimationFrame(innerFrame);
+ }
+ };
+ }
+
+ return () => {};
+}
diff --git a/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.test.tsx b/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.test.tsx
index b37fbbb90..1f0e6f5de 100644
--- a/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.test.tsx
@@ -102,7 +102,9 @@ describe("EdgeWithAddButton", () => {
cleanup();
});
- it("keeps the loop as parent and inherits branch context for nested-loop edge inserts", () => {
+ it("keeps the loop as parent without branch context for nested-loop edge inserts", () => {
+ // SKY-10719: a block inside a loop is a plain loop child even when the loop
+ // lives in a conditional; keep the loop as parent with no branch context.
useNodesMock.mockReturnValue([
{
id: "conditional",
@@ -138,19 +140,17 @@ describe("EdgeWithAddButton", () => {
fireEvent.click(screen.getByRole("button"));
- expect(useWorkflowPanelStore.getState().workflowPanelState).toMatchObject({
+ const state = useWorkflowPanelStore.getState().workflowPanelState;
+ expect(state).toMatchObject({
active: true,
content: "nodeLibrary",
data: {
- branchContext: {
- branchId: "branch-a",
- conditionalNodeId: "conditional",
- },
next: "target",
parent: "loop",
previous: "source",
},
});
+ expect(state.data?.branchContext).toBeUndefined();
});
it("does not branch-scope the post-merge edge after a top-level conditional", () => {
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/ConditionalNode/ConditionalNode.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/ConditionalNode/ConditionalNode.tsx
index f197a0d92..d8ee8ecd7 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/ConditionalNode/ConditionalNode.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/ConditionalNode/ConditionalNode.tsx
@@ -13,6 +13,7 @@ import { cn } from "@/util/utils";
import { NodeHeader } from "../components/NodeHeader";
import { AppNode } from "..";
import { applyDescendantCollapseVisibility } from "../../collapse/applyDescendantCollapseVisibility";
+import { scheduleCollapseRelayout } from "../../collapse/scheduleCollapseRelayout";
import { useCollapseContext } from "../../collapse/CollapseContext";
import {
isBlockCollapsedAt,
@@ -104,7 +105,7 @@ function ConditionalNodeComponent({ id, data }: NodeProps<ConditionalNode>) {
prevIsCollapsed.current = false;
return;
}
- const wasCollapsed = prevIsCollapsed.current === true;
+ const previousIsCollapsed = prevIsCollapsed.current;
prevIsCollapsed.current = isCollapsed;
setNodes((prev) => {
const collapsedSet = useNodeCollapseStore.getState().collapsed;
@@ -113,9 +114,11 @@ function ConditionalNodeComponent({ id, data }: NodeProps<ConditionalNode>) {
isBlockCollapsedAt(collapsedSet, wpid, label),
);
});
- if (wasCollapsed && !isCollapsed) {
- window.dispatchEvent(new Event("conditional-header-resized"));
- }
+ return scheduleCollapseRelayout(
+ "conditional-header-resized",
+ previousIsCollapsed,
+ isCollapsed,
+ );
}, [id, isCollapsed, setNodes, workflowPermanentId]);
if (!node) {
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/LoopNode/LoopNode.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/LoopNode/LoopNode.tsx
index f8a26f019..72a02aa18 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/LoopNode/LoopNode.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/LoopNode/LoopNode.tsx
@@ -16,6 +16,7 @@ import { cn } from "@/util/utils";
import { AppNode } from "..";
import { applyDescendantCollapseVisibility } from "../../collapse/applyDescendantCollapseVisibility";
+import { scheduleCollapseRelayout } from "../../collapse/scheduleCollapseRelayout";
import { useCollapseContext } from "../../collapse/CollapseContext";
import {
isBlockCollapsedAt,
@@ -92,7 +93,7 @@ function LoopNode({ id, data }: NodeProps<LoopNode>) {
prevIsCollapsed.current = false;
return;
}
- const wasCollapsed = prevIsCollapsed.current === true;
+ const previousIsCollapsed = prevIsCollapsed.current;
prevIsCollapsed.current = isCollapsed;
setNodes((prev) => {
const collapsedSet = useNodeCollapseStore.getState().collapsed;
@@ -105,10 +106,13 @@ function LoopNode({ id, data }: NodeProps<LoopNode>) {
// marginy even if debouncedLayoutForDimensions already ran with stale
// data before the header's ResizeObserver had a chance to update
// _headerHeight. The handler has a built-in 10ms delay that lets the
- // ResizeObserver win the race.
- if (wasCollapsed && !isCollapsed) {
- window.dispatchEvent(new Event("loop-header-resized"));
- }
+ // ResizeObserver win the race. Collapsing fires the same re-layout, but
+ // deferred two frames so React Flow has re-measured the shorter card.
+ return scheduleCollapseRelayout(
+ "loop-header-resized",
+ previousIsCollapsed,
+ isCollapsed,
+ );
}, [id, isCollapsed, setNodes, workflowPermanentId]);
const furthestDownChild: Node | null = children.reduce(
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx
index aa62611b5..0e200bb3d 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx
@@ -97,7 +97,9 @@ describe("NodeAdderNode", () => {
cleanup();
});
- it("keeps the loop as parent and inherits branch context when adding the first block in a nested loop", () => {
+ it("keeps the loop as parent without branch context when adding the first block in a nested loop", () => {
+ // SKY-10719: adding a block into a loop nested in a conditional keeps the
+ // loop as parent with no branch context (loop children are not branch members).
const edges: Array<Edge> = [
{
id: "edge",
@@ -142,18 +144,16 @@ describe("NodeAdderNode", () => {
fireEvent.click(screen.getByTestId("node-adder-button"));
- expect(useWorkflowPanelStore.getState().workflowPanelState).toMatchObject({
+ const state = useWorkflowPanelStore.getState().workflowPanelState;
+ expect(state).toMatchObject({
active: true,
content: "nodeLibrary",
data: {
- branchContext: {
- branchId: "branch-a",
- conditionalNodeId: "conditional",
- },
next: "adder",
parent: "loop",
previous: "start",
},
});
+ expect(state.data?.branchContext).toBeUndefined();
});
});
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.test.ts b/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.test.ts
index 1e906d661..80b5899a7 100644
--- a/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.test.ts
@@ -101,7 +101,9 @@ describe("findBranchContextForInsertion", () => {
).toEqual(branch);
});
- it("climbs to a parent loop when an empty nested loop inserts from its start node", () => {
+ it("does not inherit branch context when inserting into a loop nested in a conditional (from its start node)", () => {
+ // SKY-10719: a loop is a container boundary; an insert inside it must not
+ // inherit the loop's own membership in the outer conditional.
expect(
findBranchContextForInsertion(
[
@@ -127,6 +129,78 @@ describe("findBranchContextForInsertion", () => {
"start",
"loop",
),
+ ).toBeUndefined();
+ });
+
+ it("does not inherit branch context when inserting between two blocks inside a loop nested in a conditional", () => {
+ // SKY-10719: walking up from a loop child reaches the loop, whose branch
+ // membership belongs to the loop, not to blocks inside it.
+ expect(
+ findBranchContextForInsertion(
+ [
+ {
+ id: "conditional-node",
+ type: "conditional",
+ data: {
+ activeBranchId: "branch-a",
+ branches: [{ id: "branch-a" }, { id: "branch-b" }],
+ label: "conditional",
+ mergeLabel: null,
+ },
+ },
+ {
+ id: "loop",
+ parentId: "conditional-node",
+ type: "loop",
+ data: {
+ conditionalBranchId: "branch-a",
+ conditionalLabel: "conditional",
+ conditionalMergeLabel: null,
+ conditionalNodeId: "conditional-node",
+ label: "block_loop",
+ },
+ },
+ { id: "block-8", parentId: "loop", type: "codeBlock", data: {} },
+ { id: "block-14", parentId: "loop", type: "codeBlock", data: {} },
+ ],
+ "block-8",
+ "loop",
+ ),
+ ).toBeUndefined();
+ });
+
+ it("still inherits branch context when inserting a sibling after a loop inside a conditional", () => {
+ // The loop's own membership is correct when the loop itself is the insertion
+ // point; the boundary only applies when stepping INTO the loop from a child.
+ expect(
+ findBranchContextForInsertion(
+ [
+ {
+ id: "conditional-node",
+ type: "conditional",
+ data: {
+ activeBranchId: "branch-a",
+ branches: [{ id: "branch-a" }],
+ label: "conditional",
+ mergeLabel: null,
+ },
+ },
+ {
+ id: "loop",
+ parentId: "conditional-node",
+ type: "loop",
+ data: {
+ conditionalBranchId: "branch-a",
+ conditionalLabel: "conditional",
+ conditionalMergeLabel: null,
+ conditionalNodeId: "conditional-node",
+ label: "block_loop",
+ },
+ },
+ ],
+ "loop",
+ "conditional-node",
+ ),
).toEqual(branch);
});
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.ts b/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.ts
index 645e27e57..2977f964e 100644
--- a/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.ts
@@ -96,15 +96,21 @@ export function findBranchContextForInsertion(
// active branch. Check the container context first so the inner branch
// wins and the inserted block is not orphaned under the outer conditional
// (SKY-10460).
- const treatConditionalAsContainer =
- includeStartingConditional || !isStartingNode;
- if (treatConditionalAsContainer) {
+ const treatAsContainer = includeStartingConditional || !isStartingNode;
+ if (treatAsContainer) {
const conditionalBranchContext = branchContextFromConditionalNode(node);
if (conditionalBranchContext) {
return conditionalBranchContext;
}
}
+ // A loop is a container boundary: its children carry no conditional
+ // metadata, so stepping into a loop must not inherit its branch
+ // membership, else the inserted block drops out of the loop scope (SKY-10719).
+ if (treatAsContainer && node.type === "loop") {
+ return undefined;
+ }
+
const nodeBranchContext = branchContextFromNodeData(
node.data as Partial<NodeBaseData> | undefined,
);
diff --git a/skyvern/forge/sdk/artifact/storage/local.py b/skyvern/forge/sdk/artifact/storage/local.py
index 63a7210c0..c7630986d 100644
--- a/skyvern/forge/sdk/artifact/storage/local.py
+++ b/skyvern/forge/sdk/artifact/storage/local.py
@@ -189,14 +189,11 @@ class LocalStorage(BaseStorage):
return None
def _drop_stale_session_sidecar(self, source_directory: Path, stored_folder_path: Path) -> None:
- # These stores overlay onto an existing dir. persist_session_cookies removes the sidecar at the
- # source when a session ends with no session cookies; without this the old sidecar survives in the
- # destination and a dead session gets re-injected on the next reuse.
+ # These stores overlay onto an existing dir, so a sidecar dropped at the source (session ended
+ # with no session cookies) must also be cleared in the destination, else a dead session reinjects.
if (source_directory / SESSION_COOKIES_FILENAME).exists():
return
- stale_sidecar = stored_folder_path / SESSION_COOKIES_FILENAME
- if stale_sidecar.exists():
- stale_sidecar.unlink(missing_ok=True)
+ (stored_folder_path / SESSION_COOKIES_FILENAME).unlink(missing_ok=True)
def _copy_directory_best_effort(self, source_directory: Path, stored_folder_path: Path) -> None:
# Source may be a live browser profile. Skip only transient runtime files: ones that vanish
@@ -294,6 +291,11 @@ class LocalStorage(BaseStorage):
source_directory = Path(directory).resolve()
if source_directory == stored_folder_path:
return
+ # True overwrite: drop any prior contents so a re-save can't leave stale cookies or
+ # localStorage from the old session mixed into the refreshed profile. Let errors surface
+ # rather than silently merging onto a half-deleted directory.
+ if stored_folder_path.exists():
+ shutil.rmtree(stored_folder_path)
self._create_directories_if_not_exists(stored_folder_path)
LOG.info(
"Storing browser profile locally",
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index a77b56c0d..624a9d135 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -6,7 +6,7 @@ import asyncio
import inspect
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, AsyncIterator, Awaitable, cast
+from typing import TYPE_CHECKING, Any, AsyncIterator, Awaitable, TypeAlias, cast
import structlog
@@ -47,6 +47,10 @@ _SESSION_CLEANUP_TIMEOUT_SECONDS = 5.0
_BROWSER_BOOT_WAIT_SECONDS = 30.0
_BROWSER_BOOT_POLL_INTERVAL_SECONDS = 0.25
_FINAL_BROWSER_SESSION_STATUSES: frozenset[str] = frozenset({"completed", "failed", "timeout"})
+CodeArtifactMetadataValue: TypeAlias = (
+ str | int | float | bool | None | list["CodeArtifactMetadataValue"] | dict[str, "CodeArtifactMetadataValue"]
+)
+CodeArtifactMetadataPayload: TypeAlias = dict[str, CodeArtifactMetadataValue]
def _playwright_private_impl(browser_context: object) -> object | None:
@@ -194,7 +198,11 @@ class AgentContext:
block_observation_refs: dict[str, int] = field(default_factory=dict)
# Raw tool input for block_observation_refs, retained only for diagnostics
# when normalization drops malformed entries before composition validation.
- raw_block_observation_refs: Any | None = None
+ raw_block_observation_refs: object | None = None
+ # Block-label keyed metadata describing authored code artifacts. This layer
+ # only normalizes and carries the metadata; sufficiency checks live elsewhere.
+ code_artifact_metadata: dict[str, CodeArtifactMetadataPayload] = field(default_factory=dict)
+ raw_code_artifact_metadata: object | None = None
# Hydrated at turn start from StructuredContext.observed_acted_pages; lets the
# composition gate credit a page observed on a prior turn when this turn's
# flow_evidence does not cover it (closes the spent-inspection-budget
diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.py
index 0c2155313..357c447b0 100644
--- a/skyvern/forge/sdk/copilot/tools.py
+++ b/skyvern/forge/sdk/copilot/tools.py
@@ -25,7 +25,7 @@ except ImportError: # pragma: no cover — bs4 is a transitive dep but discover
BeautifulSoup = None # type: ignore[assignment, misc]
from agents.run_context import RunContextWrapper
from jinja2.sandbox import SandboxedEnvironment
-from pydantic import BaseModel, Field, ValidationError
+from pydantic import AliasChoices, BaseModel, Field, ValidationError
from skyvern.config import settings
from skyvern.forge import app
@@ -2210,6 +2210,284 @@ class BlockObservationRef(BaseModel):
observation_step: Annotated[int, Field(ge=0)]
+ArtifactEvidenceStatus = Literal["satisfied", "missing", "diagnostic_only", "observed_not_verified"]
+
+
+class CodeArtifactClaimedOutcome(BaseModel):
+ id: str
+ scope: str
+ text: str
+ status: ArtifactEvidenceStatus
+ depends_on: list[str] = Field(default_factory=list)
+ covered_criteria: list[str] = Field(default_factory=list)
+ criteria_ids: list[str] = Field(default_factory=list)
+ evidence_refs: list[str] = Field(default_factory=list)
+ observation_refs: list[str] = Field(default_factory=list)
+ required_tokens: list[str] = Field(default_factory=list)
+ entities: list[str] = Field(default_factory=list)
+
+
+class CodeArtifactPageDependency(BaseModel):
+ id: str
+ scope: str
+ status: ArtifactEvidenceStatus
+ url_hint: str | None = None
+ page_state_hint: str | None = None
+ required_affordances: list[str] = Field(default_factory=list)
+ required_outcomes: list[str] = Field(default_factory=list)
+ evidence_refs: list[str] = Field(default_factory=list, description="Dependency-scoped evidence_ref ids.")
+ observation_refs: list[str] = Field(default_factory=list, description="Dependency-scoped observation_ref ids.")
+
+
+class CodeArtifactCompletionCriterion(BaseModel):
+ id: str
+ text: str
+ level: Literal["terminal", "outcome", "prefix", "method"]
+ outcome: str | None = None
+ terminal: bool | None = None
+
+
+class CodeArtifactScopedRef(BaseModel):
+ claim_id: str | None = None
+ dependency_id: str | None = None
+ criterion_id: str | None = None
+ evidence_ref: str | None = None
+ observation_ref: str | None = None
+ status: ArtifactEvidenceStatus = Field(validation_alias=AliasChoices("status", "evidence_status"))
+ source_tool: str | None = None
+ observation_step: Annotated[int, Field(ge=0)] | None = None
+ run_sample_id: str | None = None
+ current_url: str | None = None
+ source_label: str | None = None
+ checkpoint_next_mode: Literal["advance", "stop"] | None = None
+
+
+class CodeArtifactTerminalVerifierExpectation(BaseModel):
+ id: str
+ text: str
+ criteria_ids: list[str] = Field(default_factory=list)
+ claimed_outcome_ids: list[str] = Field(default_factory=list)
+
+
+class CodeArtifactExplorationObservation(BaseModel):
+ id: str
+ text: str
+ status: Literal["observed_not_verified"] = Field(
+ default="observed_not_verified",
+ validation_alias=AliasChoices("status", "evidence_status"),
+ )
+ observation_ref: str | None = None
+ source_tool: str | None = None
+ observation_step: Annotated[int, Field(ge=0)] | None = None
+ current_url: str | None = None
+ source_label: str | None = None
+ checkpoint_next_mode: Literal["stop"] | None = None
+
+
+class CodeArtifactMetadata(BaseModel):
+ artifact_id: str | None = None
+ block_label: str | None = None
+ block_id: str | None = None
+ declared_goal: str
+ claimed_outcomes: list[CodeArtifactClaimedOutcome] = Field(default_factory=list)
+ page_dependencies: list[CodeArtifactPageDependency] = Field(default_factory=list)
+ completion_criteria: list[CodeArtifactCompletionCriterion] = Field(default_factory=list)
+ evidence_refs: list[CodeArtifactScopedRef] = Field(default_factory=list)
+ observation_refs: list[CodeArtifactScopedRef] = Field(default_factory=list)
+ terminal_verifier_expectations: list[CodeArtifactTerminalVerifierExpectation] = Field(default_factory=list)
+ exploration_observations: list[CodeArtifactExplorationObservation] = Field(default_factory=list)
+
+
+_CODE_ARTIFACT_REQUIRED_LIST_FIELDS = (
+ "claimed_outcomes",
+ "page_dependencies",
+ "completion_criteria",
+ "terminal_verifier_expectations",
+)
+
+
+def _code_artifact_metadata_as_tool_argument(
+ metadata: list[CodeArtifactMetadata] | None,
+) -> list[dict[str, Any]]:
+ if not metadata:
+ return []
+ return [item.model_dump(mode="json", exclude_none=True) for item in metadata]
+
+
+def _normalize_code_artifact_metadata(
+ raw_metadata: Any,
+ workflow_yaml: str,
+) -> tuple[dict[str, dict[str, Any]], str | None]:
+ if raw_metadata in (None, [], {}):
+ return {}, None
+ items = _code_artifact_metadata_items(raw_metadata)
+ code_blocks = _workflow_yaml_code_blocks_by_label(workflow_yaml)
+ normalized: dict[str, dict[str, Any]] = {}
+ for raw_item in items:
+ try:
+ metadata = (
+ raw_item
+ if isinstance(raw_item, CodeArtifactMetadata)
+ else CodeArtifactMetadata.model_validate(raw_item)
+ )
+ except ValidationError as exc:
+ return {}, f"Artifact metadata is malformed: {exc}"
+ dumped = metadata.model_dump(mode="json", exclude_none=True)
+ label = str(dumped.get("block_label") or "").strip()
+ if not label:
+ return {}, "Artifact metadata requires a non-empty `block_label` for each artifact."
+ if label not in code_blocks:
+ return {}, (
+ f"Artifact metadata for `{label}` does not reference an existing code block label. "
+ "Attach metadata only to authored code blocks."
+ )
+ if label in normalized:
+ return {}, f"Artifact metadata contains duplicate entries for `{label}`."
+ dumped["block_label"] = label
+ artifact_id = str(dumped.get("artifact_id") or "").strip()
+ if artifact_id and not artifact_id.startswith("code_artifact:"):
+ return {}, f"Artifact metadata for `{label}` requires `artifact_id` to start with `code_artifact:`."
+ dumped["artifact_id"] = artifact_id or _artifact_id_for_block_label(label)
+ block_id = str(
+ dumped.get("block_id") or code_blocks[label].get("block_id") or code_blocks[label].get("id") or ""
+ ).strip()
+ if block_id:
+ dumped["block_id"] = block_id
+ declared_goal = str(dumped.get("declared_goal") or "").strip()
+ if not declared_goal:
+ return {}, f"Artifact metadata for `{label}` requires a non-empty `declared_goal`."
+ for field_name in _CODE_ARTIFACT_REQUIRED_LIST_FIELDS:
+ value = dumped.get(field_name)
+ if not isinstance(value, list) or not value:
+ return {}, f"Artifact metadata for `{label}` requires non-empty `{field_name}`."
+ if not dumped.get("evidence_refs") and not dumped.get("observation_refs"):
+ return {}, f"Artifact metadata for `{label}` requires `evidence_refs` or `observation_refs`."
+ validation_error = _code_artifact_metadata_shape_error(label, dumped)
+ if validation_error is not None:
+ return {}, validation_error
+ normalized[label] = dumped
+ return normalized, None
+
+
+def _code_artifact_metadata_items(raw_metadata: Any) -> list[Any]:
+ if isinstance(raw_metadata, Mapping):
+ items: list[Any] = []
+ for block_label, value in raw_metadata.items():
+ if isinstance(value, Mapping) and "block_label" not in value:
+ items.append({"block_label": block_label, **value})
+ else:
+ items.append(value)
+ return items
+ if isinstance(raw_metadata, list):
+ return raw_metadata
+ return [raw_metadata]
+
+
+def _workflow_yaml_code_blocks_by_label(workflow_yaml: str | None) -> dict[str, Mapping[str, Any]]:
+ blocks: dict[str, Mapping[str, Any]] = {}
+ for label, block in _workflow_yaml_blocks_by_label(workflow_yaml).items():
+ if _enum_or_string_name(block.get("block_type")) == BlockType.CODE.value:
+ blocks[label] = block
+ return blocks
+
+
+def _artifact_id_for_block_label(label: str) -> str:
+ fragment = re.sub(r"[^A-Za-z0-9_.-]+", "_", label).strip("_") or "artifact"
+ return f"code_artifact:{fragment}"
+
+
+def _code_artifact_metadata_shape_error(label: str, artifact: Mapping[str, Any]) -> str | None:
+ for field_name, ref_key in (("evidence_refs", "evidence_ref"), ("observation_refs", "observation_ref")):
+ for index, ref in enumerate(_artifact_rows(artifact.get(field_name))):
+ if not str(ref.get(ref_key) or "").strip():
+ return f"Artifact metadata for `{label}` `{field_name}` entry {index} requires `{ref_key}`."
+ if not any(str(ref.get(key) or "").strip() for key in ("claim_id", "dependency_id", "criterion_id")):
+ return f"Artifact metadata for `{label}` `{field_name}` entry {index} requires a scoped id."
+ status = str(ref.get("status") or "").strip()
+ if ref.get("checkpoint_next_mode") == "advance" and status != "diagnostic_only":
+ return (
+ f"Artifact metadata for `{label}` `{field_name}` entry {index} has "
+ "`checkpoint_next_mode=advance`; it must stay `diagnostic_only`."
+ )
+ if ref.get("checkpoint_next_mode") == "stop" and status not in {"observed_not_verified", "diagnostic_only"}:
+ return (
+ f"Artifact metadata for `{label}` `{field_name}` entry {index} has "
+ "`checkpoint_next_mode=stop`; it must remain `observed_not_verified` or `diagnostic_only`."
+ )
+ if status != "missing" and not str(ref.get("source_tool") or "").strip():
+ return f"Artifact metadata for `{label}` `{field_name}` entry {index} requires `source_tool`."
+
+ for index, claim in enumerate(_artifact_rows(artifact.get("claimed_outcomes"))):
+ claim_id = str(claim.get("id") or "").strip()
+ if not _artifact_string_list(claim.get("depends_on")):
+ return f"Artifact metadata claim `{claim_id or index}` for `{label}` requires `depends_on`."
+ claim_criteria = _artifact_string_list(claim.get("covered_criteria")) or _artifact_string_list(
+ claim.get("criteria_ids")
+ )
+ if not claim_criteria:
+ return f"Artifact metadata claim `{claim_id}` for `{label}` requires covered criterion ids."
+ claim_evidence_refs = _artifact_string_list(claim.get("evidence_refs"))
+ claim_observation_refs = _artifact_string_list(claim.get("observation_refs"))
+ if claim.get("status") == "satisfied" and not claim_evidence_refs:
+ return (
+ f"Artifact metadata claim `{claim_id}` for `{label}` is `satisfied` but has no "
+ "claim-scoped `evidence_refs`."
+ )
+ if claim.get("status") != "missing" and not claim_evidence_refs and not claim_observation_refs:
+ return (
+ f"Artifact metadata claim `{claim_id}` for `{label}` requires claim-scoped "
+ "`evidence_refs` or `observation_refs` unless status is `missing`."
+ )
+
+ for dependency in _artifact_rows(artifact.get("page_dependencies")):
+ dependency_id = str(dependency.get("id") or "").strip()
+ dependency_evidence_refs = _artifact_string_list(dependency.get("evidence_refs"))
+ dependency_observation_refs = _artifact_string_list(dependency.get("observation_refs"))
+ if dependency.get("status") == "satisfied" and not dependency_evidence_refs:
+ return (
+ f"Artifact metadata dependency `{dependency_id}` for `{label}` is `satisfied` but has no "
+ "dependency-scoped `evidence_refs`."
+ )
+ if dependency.get("status") != "missing" and not dependency_evidence_refs and not dependency_observation_refs:
+ return (
+ f"Artifact metadata dependency `{dependency_id}` for `{label}` requires scoped "
+ "`evidence_refs` or `observation_refs` unless status is `missing`."
+ )
+
+ for index, expectation in enumerate(_artifact_rows(artifact.get("terminal_verifier_expectations"))):
+ expectation_id = str(expectation.get("id") or "").strip()
+ if not _artifact_string_list(expectation.get("criteria_ids")) and not _artifact_string_list(
+ expectation.get("claimed_outcome_ids")
+ ):
+ return (
+ f"Artifact metadata terminal verifier expectation `{expectation_id or index}` for `{label}` "
+ "requires `criteria_ids` or `claimed_outcome_ids`."
+ )
+
+ for index, observation in enumerate(_artifact_rows(artifact.get("exploration_observations"))):
+ if observation.get("status") != "observed_not_verified":
+ return (
+ f"Artifact metadata for `{label}` exploration observation {index} must be marked "
+ "`observed_not_verified` until authored execution and terminal verification pass."
+ )
+ if observation.get("checkpoint_next_mode") == "advance":
+ return (
+ f"Artifact metadata for `{label}` exploration observation {index} cannot carry "
+ "`checkpoint_next_mode=advance`; record that as `diagnostic_only` evidence instead."
+ )
+ return None
+
+
+def _artifact_rows(value: Any) -> list[Mapping[str, Any]]:
+ return [row for row in value if isinstance(row, Mapping)] if isinstance(value, list) else []
+
+
+def _artifact_string_list(value: Any) -> list[str]:
+ if not isinstance(value, list):
+ return []
+ return [str(item).strip() for item in value if str(item).strip()]
+
+
async def _update_workflow(
params: dict[str, Any],
ctx: AgentContext,
@@ -2225,6 +2503,17 @@ async def _update_workflow(
# gate below consumes these refs, so they must be visible before validation.
ctx.raw_block_observation_refs = params.get("raw_block_observation_refs", params.get("block_observation_refs"))
ctx.block_observation_refs = normalize_block_observation_refs(params.get("block_observation_refs"))
+ ctx.raw_code_artifact_metadata = params.get("raw_code_artifact_metadata", params.get("code_artifact_metadata"))
+ code_artifact_metadata, code_artifact_metadata_error = _normalize_code_artifact_metadata(
+ params.get("code_artifact_metadata"),
+ workflow_yaml,
+ )
+ if code_artifact_metadata_error is not None:
+ return {"ok": False, "error": code_artifact_metadata_error}
+ if code_artifact_metadata:
+ ctx.code_artifact_metadata = code_artifact_metadata
+ ctx.workflow_verification_evidence.code_artifact_metadata = code_artifact_metadata
+ params["code_artifact_metadata"] = code_artifact_metadata
if allow_missing_credentials is None:
allow_missing_credentials = getattr(ctx, "allow_untested_workflow_draft", False) is True
if not allow_missing_credentials:
@@ -6722,6 +7011,7 @@ async def update_workflow_tool(
ctx: RunContextWrapper,
workflow_yaml: str,
block_observation_refs: list[BlockObservationRef] | None = None,
+ code_artifact_metadata: list[CodeArtifactMetadata] | None = None,
) -> str:
"""Validate and update the workflow YAML definition.
Provide the complete workflow YAML as a string.
@@ -6740,10 +7030,18 @@ async def update_workflow_tool(
`block_observation_refs` entries with each block label and the
`observation_step` returned by inspect_page_for_composition for the page
that block acts on.
+ For authored code blocks, include `code_artifact_metadata` rows describing
+ declared goals, claimed outcomes, page dependencies, criteria, evidence
+ refs, observation refs, and terminal verifier expectations.
"""
copilot_ctx = ctx.context
+ serialized_code_artifact_metadata = _code_artifact_metadata_as_tool_argument(code_artifact_metadata)
normalized_block_observation_refs = normalize_block_observation_refs(block_observation_refs)
- arguments = {"workflow_yaml": workflow_yaml, "block_observation_refs": normalized_block_observation_refs}
+ arguments = {
+ "workflow_yaml": workflow_yaml,
+ "block_observation_refs": normalized_block_observation_refs,
+ "code_artifact_metadata": serialized_code_artifact_metadata,
+ }
loop_error = _tool_loop_error(copilot_ctx, "update_workflow", arguments)
if loop_error:
return json.dumps({"ok": False, "error": loop_error})
@@ -6798,7 +7096,11 @@ async def update_workflow_tool(
prior_definition = await _get_prior_workflow_definition(copilot_ctx)
with copilot_span("update_workflow", data={"yaml_length": len(workflow_yaml)}):
result = await _update_workflow(
- {**arguments, "raw_block_observation_refs": block_observation_refs},
+ {
+ **arguments,
+ "raw_block_observation_refs": block_observation_refs,
+ "raw_code_artifact_metadata": code_artifact_metadata,
+ },
copilot_ctx,
allow_missing_credentials=getattr(copilot_ctx, "allow_untested_workflow_draft", False) is True,
)
@@ -7038,6 +7340,7 @@ async def update_and_run_blocks_tool(
workflow_yaml: str,
block_labels: list[str],
block_observation_refs: list[BlockObservationRef] | None = None,
+ code_artifact_metadata: list[CodeArtifactMetadata] | None = None,
parameters: dict[str, Any] | None = None,
) -> Any:
"""Update the workflow YAML and immediately run the specified blocks in one step.
@@ -7080,6 +7383,9 @@ async def update_and_run_blocks_tool(
`block_observation_refs` entries with each block label and the
`observation_step` returned by inspect_page_for_composition or evaluate for
the page that block acts on.
+ For authored code blocks, include `code_artifact_metadata` rows describing
+ declared goals, claimed outcomes, page dependencies, criteria, evidence
+ refs, observation refs, and terminal verifier expectations.
When inspected evidence shows an anti-bot challenge gating a disabled
submit/search control, account for challenge resolution before submit;
do not compose a click against a control observed as disabled.
@@ -7087,11 +7393,13 @@ async def update_and_run_blocks_tool(
copilot_ctx = ctx.context
copilot_ctx.completion_verification_result = None
handler_start = time.monotonic()
+ serialized_code_artifact_metadata = _code_artifact_metadata_as_tool_argument(code_artifact_metadata)
normalized_block_observation_refs = normalize_block_observation_refs(block_observation_refs)
arguments = {
"workflow_yaml": workflow_yaml,
"block_labels": block_labels,
"block_observation_refs": normalized_block_observation_refs,
+ "code_artifact_metadata": serialized_code_artifact_metadata,
"parameters": parameters or {},
}
skip_run_after_update = _request_policy_allows_update_and_skip_run(copilot_ctx, "update_and_run_blocks")
@@ -7138,6 +7446,8 @@ async def update_and_run_blocks_tool(
"workflow_yaml": workflow_yaml,
"block_observation_refs": normalized_block_observation_refs,
"raw_block_observation_refs": block_observation_refs,
+ "code_artifact_metadata": serialized_code_artifact_metadata,
+ "raw_code_artifact_metadata": code_artifact_metadata,
},
copilot_ctx,
allow_missing_credentials=skip_run_after_update,
diff --git a/skyvern/forge/sdk/copilot/verification_evidence.py b/skyvern/forge/sdk/copilot/verification_evidence.py
index a5d0b4570..849479b3b 100644
--- a/skyvern/forge/sdk/copilot/verification_evidence.py
+++ b/skyvern/forge/sdk/copilot/verification_evidence.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
+from typing import Any
def _dedupe(values: list[str]) -> list[str]:
@@ -26,6 +27,7 @@ class WorkflowVerificationEvidence:
unverified_block_labels: list[str] = field(default_factory=list)
failed_block_labels: list[str] = field(default_factory=list)
failure_reason: str | None = None
+ code_artifact_metadata: dict[str, dict[str, Any]] = field(default_factory=dict)
def merge_verified_blocks(self, labels: list[str]) -> None:
self.block_verified = _dedupe([*self.block_verified, *labels])
@@ -51,6 +53,7 @@ class WorkflowVerificationEvidence:
or self.unverified_block_labels
or self.failed_block_labels
or self.failure_reason
+ or self.code_artifact_metadata
)
def to_trace_data(self) -> dict[str, bool | int]:
@@ -70,6 +73,7 @@ class WorkflowVerificationEvidence:
"unverified_block_count": len(self.unverified_block_labels),
"failed_block_count": len(self.failed_block_labels),
"has_failure_reason": bool(self.failure_reason),
+ "code_artifact_metadata_count": len(self.code_artifact_metadata),
}
def render_prompt_block(self) -> str:
diff --git a/skyvern/forge/sdk/db/repositories/browser_sessions.py b/skyvern/forge/sdk/db/repositories/browser_sessions.py
index 52e800dff..dd5dd2c30 100644
--- a/skyvern/forge/sdk/db/repositories/browser_sessions.py
+++ b/skyvern/forge/sdk/db/repositories/browser_sessions.py
@@ -148,6 +148,21 @@ class BrowserSessionsRepository(BaseRepository):
await session.refresh(browser_profile)
return BrowserProfile.model_validate(browser_profile)
+ @db_operation("touch_browser_profile")
+ async def touch_browser_profile(self, profile_id: str, organization_id: str) -> None:
+ async with self.Session() as session:
+ query = (
+ select(BrowserProfileModel)
+ .filter_by(browser_profile_id=profile_id)
+ .filter_by(organization_id=organization_id)
+ .filter(BrowserProfileModel.deleted_at.is_(None))
+ )
+ browser_profile = (await session.scalars(query)).first()
+ if not browser_profile:
+ raise BrowserProfileNotFound(profile_id=profile_id, organization_id=organization_id)
+ browser_profile.modified_at = naive_utc_now()
+ await session.commit()
+
@db_operation("get_active_persistent_browser_sessions")
async def get_active_persistent_browser_sessions(
self,
diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.py
index 894989bb1..2aa3a37c5 100644
--- a/skyvern/forge/sdk/routes/credentials.py
+++ b/skyvern/forge/sdk/routes/credentials.py
@@ -27,7 +27,6 @@ exact threat the vault architecture is designed to prevent.
import asyncio
import json
-from datetime import datetime
from typing import Annotated
import structlog
@@ -38,6 +37,7 @@ from skyvern.exceptions import HttpException as SkyvernHttpException
from skyvern.exceptions import SkyvernHTTPException
from skyvern.forge import app
from skyvern.forge.sdk.core.aiohttp_helper import aiohttp_request
+from skyvern.forge.sdk.db.datetime_utils import naive_utc_now, to_naive_utc
from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
from skyvern.forge.sdk.db.models import CredentialFolderModel
from skyvern.forge.sdk.executor.factory import AsyncExecutorFactory
@@ -105,7 +105,10 @@ from skyvern.schemas.credential_folders import (
UpdateCredentialFolderRequest,
)
from skyvern.schemas.workflows import (
+ BLOCK_YAML_TYPES,
LoginBlockYAML,
+ UrlBlockYAML,
+ ValidationBlockYAML,
WorkflowCreateYAMLRequest,
WorkflowDefinitionYAML,
WorkflowParameterYAML,
@@ -426,6 +429,50 @@ def _build_navigation_goal(base_prompt: str, user_context: str | None) -> str:
)
+SESSION_VALIDATION_COMPLETE_CRITERION = (
+ "The user is logged in: the page shows authenticated content such as a dashboard, "
+ "account/profile menu, or user-specific data, and there is NO sign-in page or "
+ "username/password login form visible."
+)
+
+SESSION_VALIDATION_TERMINATE_CRITERION = (
+ "Terminate if a sign-in/login page or a username/password login form is visible, "
+ "or the page indicates the user is logged out or the session has expired. This means "
+ "the browser session is not authenticated and must not be saved."
+)
+
+
+def _build_login_test_blocks(
+ *,
+ url: str,
+ navigation_goal: str,
+ parameter_key: str,
+ totp_identifier: str | None,
+) -> list[BLOCK_YAML_TYPES]:
+ # Re-navigate after login so validation runs on a freshly fetched page, not a stale cached one.
+ blocks: list[BLOCK_YAML_TYPES] = [
+ LoginBlockYAML(
+ label="login",
+ title="login",
+ url=url,
+ navigation_goal=navigation_goal,
+ terminate_criterion=LOGIN_TEST_TERMINATE_CRITERION,
+ max_steps_per_run=None,
+ parameter_keys=[parameter_key],
+ totp_verification_url=None,
+ totp_identifier=totp_identifier,
+ skip_saved_profile=True,
+ ),
+ UrlBlockYAML(label="verify_navigate", url=url),
+ ValidationBlockYAML(
+ label="verify_session",
+ complete_criterion=SESSION_VALIDATION_COMPLETE_CRITERION,
+ terminate_criterion=SESSION_VALIDATION_TERMINATE_CRITERION,
+ ),
+ ]
+ return blocks
+
+
@base_router.patch(
"/credentials/{credential_id}",
response_model=CredentialResponse,
@@ -728,7 +775,6 @@ async def test_credential(
navigation_goal = _build_navigation_goal(base_prompt, data.user_context)
parameter_key = "credential"
- label = "login"
yaml_parameters = [
WorkflowParameterYAML(
@@ -739,21 +785,14 @@ async def test_credential(
)
]
- login_block_yaml = LoginBlockYAML(
- label=label,
- title=label,
- url=data.url,
- navigation_goal=navigation_goal,
- terminate_criterion=LOGIN_TEST_TERMINATE_CRITERION,
- max_steps_per_run=None,
- parameter_keys=[parameter_key],
- totp_verification_url=None,
- totp_identifier=credential.totp_identifier,
- )
-
workflow_definition_yaml = WorkflowDefinitionYAML(
parameters=yaml_parameters,
- blocks=[login_block_yaml],
+ blocks=_build_login_test_blocks(
+ url=data.url,
+ navigation_goal=navigation_goal,
+ parameter_key=parameter_key,
+ totp_identifier=credential.totp_identifier,
+ ),
)
workflow_create_request = WorkflowCreateYAMLRequest(
@@ -770,9 +809,10 @@ async def test_credential(
request=workflow_create_request,
)
- run_request = WorkflowRequestBody(
- browser_profile_id=existing_browser_profile_id,
- )
+ # Boot fresh (don't seed the saved profile): a reused profile is loaded read-only and the
+ # refreshed session would never persist. A fresh login persists via the normal session path,
+ # which the saver then writes onto existing_browser_profile_id.
+ run_request = WorkflowRequestBody()
workflow_run = await app.WORKFLOW_SERVICE.setup_workflow_run(
request_id=None,
@@ -814,6 +854,7 @@ async def test_credential(
organization_id=organization_id,
credential_name=credential.name,
test_url=data.url,
+ existing_browser_profile_id=existing_browser_profile_id,
)
)
_background_tasks.add(task)
@@ -963,18 +1004,29 @@ async def get_test_credential_status(
elif status == WorkflowRunStatus.canceled:
failure_reason = "The login test was canceled."
- # Only a real failure once the background task has had time to finish; grace must
- # exceed its session-persist wait plus headroom, else mid-polls misread.
+ # The saver runs after the run reaches `completed`, and on a re-save it overwrites an
+ # already-linked profile in place — so a present id is not by itself proof this run's
+ # session was stored. Confirm via the profile's modified_at; until then withhold the id so
+ # the client keeps polling, and only surface failure once the saver's retry budget is spent.
_PROFILE_GRACE_PERIOD_SECONDS = _SESSION_PERSIST_MAX_WAIT_SECONDS + _PROFILE_GRACE_PERIOD_HEADROOM_SECONDS
- if (
- status == WorkflowRunStatus.completed
- and not browser_profile_id
- and workflow_run.finished_at
- and (datetime.utcnow() - workflow_run.finished_at).total_seconds() > _PROFILE_GRACE_PERIOD_SECONDS
- ):
- browser_profile_failure_reason = (
- "Login succeeded but the browser profile could not be saved. Please try testing again."
- )
+ if status == WorkflowRunStatus.completed and workflow_run.finished_at:
+ workflow = await app.DATABASE.workflows.get_workflow(workflow_run.workflow_id, organization_id)
+ # Only a save-enabled test has a saver; a plain login test must not report a save failure.
+ if workflow and workflow.persist_browser_session:
+ save_persisted = False
+ if browser_profile_id:
+ profile = await app.DATABASE.browser_sessions.get_browser_profile(
+ profile_id=browser_profile_id, organization_id=organization_id
+ )
+ saved_at = to_naive_utc(profile.modified_at) if profile else None
+ run_finished_at = to_naive_utc(workflow_run.finished_at)
+ save_persisted = bool(saved_at and run_finished_at and saved_at >= run_finished_at)
+ if not save_persisted:
+ browser_profile_id = None
+ if (naive_utc_now() - workflow_run.finished_at).total_seconds() > _PROFILE_GRACE_PERIOD_SECONDS:
+ browser_profile_failure_reason = (
+ "Login succeeded but the browser profile could not be saved. Please try testing again."
+ )
return TestCredentialStatusResponse(
credential_id=credential_id,
@@ -1070,9 +1122,10 @@ async def _create_browser_profile_after_workflow(
organization_id: str,
credential_name: str,
test_url: str,
+ existing_browser_profile_id: str | None = None,
) -> None:
- """Background task that polls the workflow run status and creates a browser
- profile from the persisted session when the run completes successfully."""
+ """Poll the run and persist the captured session on success: a re-save overwrites
+ ``existing_browser_profile_id`` in place, otherwise a new profile is created and linked."""
max_polls = 120 # ~10 minutes at 5s intervals
poll_interval = 5
@@ -1153,34 +1206,54 @@ async def _create_browser_profile_after_workflow(
)
return
- # Create the browser profile in DB
- profile_name = f"Profile - {credential_name} ({credential_id})"
- profile = await app.DATABASE.browser_sessions.create_browser_profile(
- organization_id=organization_id,
- name=profile_name,
- description=f"Browser profile from credential test for {credential_name}",
- )
+ # Re-save overwrites the existing profile in place so references to its id keep
+ # working; a first-time save (or a since-deleted profile) creates a new one.
+ target_profile_id = existing_browser_profile_id
+ reused_existing = False
+ if target_profile_id:
+ existing_profile = await app.DATABASE.browser_sessions.get_browser_profile(
+ profile_id=target_profile_id,
+ organization_id=organization_id,
+ )
+ reused_existing = existing_profile is not None
+ if not reused_existing:
+ target_profile_id = None
- # Copy session data to the browser profile storage location
+ if not target_profile_id:
+ profile = await app.DATABASE.browser_sessions.create_browser_profile(
+ organization_id=organization_id,
+ name=f"Profile - {credential_name} ({credential_id})",
+ description=f"Browser profile from credential test for {credential_name}",
+ )
+ target_profile_id = profile.browser_profile_id
+
+ # Overwrites in place when reusing an existing id.
await app.STORAGE.store_browser_profile(
organization_id=organization_id,
- profile_id=profile.browser_profile_id,
+ profile_id=target_profile_id,
directory=session_dir,
)
+ if reused_existing:
+ # Bump modified_at so the status poll can tell this run's re-save actually landed.
+ await app.DATABASE.browser_sessions.touch_browser_profile(
+ profile_id=target_profile_id,
+ organization_id=organization_id,
+ )
- # Link browser profile to credential
+ # Link browser profile to credential (refreshes tested_url; id unchanged on re-save).
await app.DATABASE.credentials.update_credential(
credential_id=credential_id,
organization_id=organization_id,
- browser_profile_id=profile.browser_profile_id,
+ browser_profile_id=target_profile_id,
tested_url=test_url,
)
LOG.info(
- "Browser profile created from credential test",
+ "Browser profile saved from credential test",
credential_id=credential_id,
- browser_profile_id=profile.browser_profile_id,
+ browser_profile_id=target_profile_id,
workflow_run_id=workflow_run_id,
+ overwrote_existing=target_profile_id == existing_browser_profile_id,
)
return
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 71a90cf0f..420db8714 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -5877,6 +5877,10 @@ class LoginBlock(BaseTaskBlock):
# Parameter 1 of Literal[...] cannot be of type "Any"
block_type: Literal[BlockType.LOGIN] = BlockType.LOGIN # type: ignore
+ # Opt out of reusing the credential's saved browser profile so the run logs in fresh and
+ # the captured session persists via the normal path (a reused profile is loaded read-only).
+ skip_saved_profile: bool = False
+
class FileDownloadBlock(BaseTaskBlock):
# There is a mypy bug with Literal. Without the type: ignore, mypy will raise an error:
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 12bd7d926..63df3dcfa 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -84,6 +84,7 @@ from skyvern.forge.sdk.workflow.models.block import (
ExtractionBlock,
FileParserBlock,
ForLoopBlock,
+ LoginBlock,
NavigationBlock,
PDFParserBlock,
TaskV2Block,
@@ -159,6 +160,7 @@ from skyvern.utils.css_selector import build_action_summaries_with_timing # sha
from skyvern.utils.secret_headers import merge_masked_headers
from skyvern.utils.url_validators import validate_url as validate_url_with_blocked_host_check
from skyvern.webeye.browser_state import BrowserState
+from skyvern.webeye.session_cookies import persist_session_cookies
LOG = structlog.get_logger()
@@ -3315,6 +3317,10 @@ class WorkflowService:
) -> str | None:
"""Inspect the block-level parameters and return the browser_profile_id
from the credential parameter bound to this specific block."""
+ # A credential re-save logs in fresh so the new session persists via the normal path,
+ # so it must not reuse (and boot read-only from) the credential's saved profile.
+ if isinstance(block, LoginBlock) and block.skip_saved_profile:
+ return None
params = block.parameters
# Pre-fetch run parameters once (used by WorkflowParameter/CREDENTIAL_ID style).
@@ -5697,6 +5703,13 @@ class WorkflowService:
and not workflow_run.browser_profile_id
):
if workflow_run.status == WorkflowRunStatus.completed:
+ if not close_browser_on_completion:
+ # Browser stays alive here, so close()'s cookie snapshot never ran; capture
+ # session cookies now or they're missing from the archived profile on reuse.
+ await persist_session_cookies(
+ browser_state.browser_context,
+ browser_state.browser_artifacts.browser_session_dir,
+ )
await app.STORAGE.store_browser_session(
workflow_run.organization_id,
workflow.workflow_permanent_id,
diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
index 4e5c4af26..839e8de21 100644
--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py
+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
@@ -697,6 +697,7 @@ def block_yaml_to_block(
complete_criterion=block_yaml.complete_criterion,
terminate_criterion=block_yaml.terminate_criterion,
complete_verification=block_yaml.complete_verification,
+ skip_saved_profile=block_yaml.skip_saved_profile,
)
elif block_yaml.block_type == BlockType.WAIT:
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index 04ae3d1b5..2993be28e 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -1005,6 +1005,7 @@ class LoginBlockYAML(BlockYAML):
complete_criterion: str | None = None
terminate_criterion: str | None = None
complete_verification: bool = True
+ skip_saved_profile: bool = False
class WaitBlockYAML(BlockYAML):
diff --git a/skyvern/webeye/default_persistent_sessions_manager.py b/skyvern/webeye/default_persistent_sessions_manager.py
index e09c3722f..01ab9e779 100644
--- a/skyvern/webeye/default_persistent_sessions_manager.py
+++ b/skyvern/webeye/default_persistent_sessions_manager.py
@@ -459,8 +459,8 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):
# Export session profile before closing (so it can be used to create browser profiles)
browser_artifacts = browser_session.browser_state.browser_artifacts
if browser_artifacts and browser_artifacts.browser_session_dir:
- # Load-bearing: write the sidecar before store_browser_profile copies the dir; close()
- # also persists but runs after the export, too late for this path.
+ # Snapshot session cookies before store_browser_profile copies the dir; the later
+ # close() persist runs after this export, too late to land in the archive.
await persist_session_cookies(
browser_session.browser_state.browser_context, browser_artifacts.browser_session_dir
)
diff --git a/skyvern/webeye/real_browser_manager.py b/skyvern/webeye/real_browser_manager.py
index a2b89fb20..247309222 100644
--- a/skyvern/webeye/real_browser_manager.py
+++ b/skyvern/webeye/real_browser_manager.py
@@ -15,6 +15,7 @@ from skyvern.webeye.browser_factory import BrowserContextFactory
from skyvern.webeye.browser_manager import BrowserManager
from skyvern.webeye.browser_state import BrowserState
from skyvern.webeye.real_browser_state import RealBrowserState
+from skyvern.webeye.session_cookies import persist_session_cookies
from skyvern.webeye.video_utils import finalize_webm
LOG = structlog.get_logger()
@@ -462,7 +463,12 @@ class RealBrowserManager(BrowserManager):
LOG.info("Stopped tracing", trace_path=trace_path)
if streams_active:
- # Defer close until the last stream disconnects
+ # Defer close until the last stream disconnects. Persist session cookies first: the
+ # deferred close() runs after store_browser_session archives the dir, too late for it.
+ await persist_session_cookies(
+ browser_state_to_close.browser_context,
+ browser_state_to_close.browser_artifacts.browser_session_dir,
+ )
LOG.info(
"Deferring browser close — active CDP streams",
workflow_run_id=workflow_run_id,
diff --git a/skyvern/webeye/session_cookies.py b/skyvern/webeye/session_cookies.py
index 5b6836b91..6bf6fe144 100644
--- a/skyvern/webeye/session_cookies.py
+++ b/skyvern/webeye/session_cookies.py
@@ -62,9 +62,10 @@ async def restore_session_cookies(browser_context: BrowserContext | None, user_d
return
with open(path) as f:
cookies = json.load(f)
- # Re-filter so a sidecar written before this filter existed (full cookie set) still narrows.
+ # Re-filter (old sidecars hold the full cookie set) and pin expires to -1: patchright reports
+ # session cookies as expires 0, which add_cookies reads as the Unix epoch (expired) and drops.
sanitized = [
- {k: v for k, v in cookie.items() if k in _ALLOWED_COOKIE_KEYS}
+ {**{k: v for k, v in cookie.items() if k in _ALLOWED_COOKIE_KEYS}, "expires": -1}
for cookie in cookies
if cookie.get("expires", -1) in _SESSION_COOKIE_EXPIRES
]
diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.py
index 1d62a346a..18dbf96cb 100644
--- a/tests/unit/test_copilot_output_policy.py
+++ b/tests/unit/test_copilot_output_policy.py
@@ -83,6 +83,62 @@ workflow_definition:
"""
+def _code_artifact_metadata(label: str = "open_results") -> list[dict[str, object]]:
+ return [
+ {
+ "block_label": label,
+ "declared_goal": "Open the result page.",
+ "claimed_outcomes": [
+ {
+ "id": "claim:open_results",
+ "scope": "sufficient_for_prefix_validation",
+ "text": "The result page is reachable.",
+ "status": "satisfied",
+ "depends_on": ["dep:result_link"],
+ "criteria_ids": ["criterion:result_page_reached"],
+ "evidence_refs": ["evidence:result_link"],
+ }
+ ],
+ "page_dependencies": [
+ {
+ "id": "dep:result_link",
+ "scope": "current_page_state",
+ "status": "satisfied",
+ "evidence_refs": ["evidence:result_link"],
+ }
+ ],
+ "completion_criteria": [
+ {
+ "id": "criterion:result_page_reached",
+ "text": "The result page is visible after authored execution.",
+ "level": "terminal",
+ }
+ ],
+ "evidence_refs": [
+ {
+ "evidence_ref": "evidence:result_link",
+ "claim_id": "claim:open_results",
+ "dependency_id": "dep:result_link",
+ "criterion_id": "criterion:result_page_reached",
+ "status": "satisfied",
+ "source_tool": "inspect_page_for_composition",
+ "observation_step": 1,
+ }
+ ],
+ "observation_refs": [],
+ "terminal_verifier_expectations": [
+ {
+ "id": "verify:result_page_reached",
+ "text": "Verify the result page is visible.",
+ "criteria_ids": ["criterion:result_page_reached"],
+ "claimed_outcome_ids": ["claim:open_results"],
+ }
+ ],
+ "exploration_observations": [],
+ }
+ ]
+
+
def _inline_conditional_workflow_yaml(*, url: str = "https://login.example.test/login") -> str:
return f"""
workflow_definition:
@@ -1345,6 +1401,7 @@ workflow_definition:
{"label": "open_results", "observation_step": 0},
{"label": "read_results", "observation_step": 1},
],
+ "code_artifact_metadata": _code_artifact_metadata(),
"parameters": {},
}
),
@@ -1360,6 +1417,14 @@ workflow_definition:
{"label": "open_results", "observation_step": 0},
{"label": "read_results", "observation_step": 1},
]
+ assert captured["payload"]["code_artifact_metadata"][0]["block_label"] == "open_results"
+ assert captured["payload"]["code_artifact_metadata"][0]["claimed_outcomes"][0]["id"] == "claim:open_results"
+ assert (
+ captured["payload"]["code_artifact_metadata"][0]["evidence_refs"][0]["evidence_ref"] == "evidence:result_link"
+ )
+ assert [
+ item.model_dump(mode="json", exclude_none=True) for item in captured["payload"]["raw_code_artifact_metadata"]
+ ] == captured["payload"]["code_artifact_metadata"]
assert ctx.block_observation_refs == {}
diff --git a/tests/unit/test_credential_test_blocks.py b/tests/unit/test_credential_test_blocks.py
new file mode 100644
index 000000000..79e52f7b2
--- /dev/null
+++ b/tests/unit/test_credential_test_blocks.py
@@ -0,0 +1,32 @@
+from skyvern.forge.sdk.routes.credentials import (
+ SESSION_VALIDATION_COMPLETE_CRITERION,
+ SESSION_VALIDATION_TERMINATE_CRITERION,
+ _build_login_test_blocks,
+)
+from skyvern.schemas.workflows import LoginBlockYAML, UrlBlockYAML, ValidationBlockYAML
+
+
+def test_build_login_test_blocks_logs_in_then_revisits_and_validates() -> None:
+ blocks = _build_login_test_blocks(
+ url="https://example.com/login",
+ navigation_goal="log in with the credential",
+ parameter_key="credential",
+ totp_identifier="[email protected]",
+ )
+
+ assert [type(b) for b in blocks] == [LoginBlockYAML, UrlBlockYAML, ValidationBlockYAML]
+
+ login, revisit, validate = blocks
+ assert login.url == "https://example.com/login"
+ assert login.parameter_keys == ["credential"]
+ assert login.totp_identifier == "[email protected]"
+ # Re-save must log in fresh so the captured session persists (and can overwrite the profile).
+ assert login.skip_saved_profile is True
+ # A fresh re-navigation before validating defeats a stale "already logged in" page.
+ assert revisit.url == "https://example.com/login"
+ assert validate.complete_criterion == SESSION_VALIDATION_COMPLETE_CRITERION
+ assert validate.terminate_criterion == SESSION_VALIDATION_TERMINATE_CRITERION
+
+ labels = [b.label for b in blocks]
+ assert labels == ["login", "verify_navigate", "verify_session"]
+ assert all(label.isidentifier() for label in labels)
diff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.py
index a7e09c179..9a830060a 100644
--- a/tests/unit/test_real_browser_manager.py
+++ b/tests/unit/test_real_browser_manager.py
@@ -490,3 +490,31 @@ async def test_popup_video_listener_timeout_url_error_safe() -> None:
await handler(page)
assert len(artifacts.video_artifacts) == 0
+
+
+async def test_cleanup_persists_session_cookies_when_close_deferred_for_streams(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Active CDP streams defer the browser close, so cleanup must snapshot session cookies before
+ store_browser_session archives the dir — the deferred close runs too late."""
+ manager = RealBrowserManager()
+ browser_state = MagicMock()
+ browser_state.browser_artifacts.traces_dir = None
+ browser_state.browser_artifacts.browser_session_dir = "/tmp/fake_profile"
+ browser_state.close = AsyncMock()
+ manager.pages["wfr_streamed"] = browser_state
+
+ persist_mock = AsyncMock()
+ monkeypatch.setattr("skyvern.webeye.real_browser_manager.persist_session_cookies", persist_mock)
+ # streaming is a namespace package; patch the module object so resolution does not depend on the
+ # parent binding the submodule, which varies with import order across the suite.
+ from skyvern.forge.sdk.routes.streaming import registries as streaming_registries
+
+ monkeypatch.setattr(streaming_registries, "stream_ref_active", lambda wrid: True)
+ monkeypatch.setattr(streaming_registries, "set_deferred_close_params", lambda *a, **k: None)
+
+ await manager.cleanup_for_workflow_run("wfr_streamed", task_ids=[], close_browser_on_completion=True)
+
+ persist_mock.assert_awaited_once_with(browser_state.browser_context, "/tmp/fake_profile")
+ browser_state.close.assert_not_awaited()
diff --git a/tests/unit/test_workflow_service_profile_writeback.py b/tests/unit/test_workflow_service_profile_writeback.py
index a26fc1444..e25edef3b 100644
--- a/tests/unit/test_workflow_service_profile_writeback.py
+++ b/tests/unit/test_workflow_service_profile_writeback.py
@@ -105,3 +105,59 @@ async def test_profile_not_persisted_on_non_completed_run(
await svc.clean_up_workflow(workflow=workflow, workflow_run=workflow_run, need_call_webhook=False)
store_mock.assert_not_awaited()
+
+
+async def test_session_cookies_persisted_before_store_when_browser_stays_alive(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Remote-browser / existing-session runs keep the browser alive, so close() never persists the
+ sidecar; clean_up_workflow must snapshot session cookies before archiving the profile."""
+ from skyvern.forge.sdk.workflow import service as service_module
+ from skyvern.forge.sdk.workflow.service import WorkflowService
+
+ workflow = _make_workflow(persist=True)
+ workflow_run = _make_workflow_run(WorkflowRunStatus.completed)
+ workflow_run.browser_address = "ws://remote-browser"
+ browser_state = _make_browser_state()
+ store_mock = _patch_clean_up_deps(monkeypatch, browser_state)
+
+ order: list[str] = []
+ persist_mock = AsyncMock(side_effect=lambda *a, **k: order.append("persist"))
+ store_mock.side_effect = lambda *a, **k: order.append("store")
+ monkeypatch.setattr(service_module, "persist_session_cookies", persist_mock)
+
+ svc = WorkflowService()
+ monkeypatch.setattr(svc, "persist_video_data", AsyncMock())
+ monkeypatch.setattr(svc, "get_tasks_by_workflow_run_id", AsyncMock(return_value=[]))
+
+ await svc.clean_up_workflow(workflow=workflow, workflow_run=workflow_run, need_call_webhook=False)
+
+ persist_mock.assert_awaited_once_with(browser_state.browser_context, "/tmp/fake_profile")
+ assert order == ["persist", "store"]
+
+
+async def test_session_cookies_not_double_persisted_when_browser_closed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """When the browser closes on completion, close() already wrote the sidecar — clean_up_workflow
+ must not persist again."""
+ from skyvern.forge.sdk.workflow import service as service_module
+ from skyvern.forge.sdk.workflow.service import WorkflowService
+
+ workflow = _make_workflow(persist=True)
+ workflow_run = _make_workflow_run(WorkflowRunStatus.completed)
+ browser_state = _make_browser_state()
+ _patch_clean_up_deps(monkeypatch, browser_state)
+
+ persist_mock = AsyncMock()
+ monkeypatch.setattr(service_module, "persist_session_cookies", persist_mock)
+
+ svc = WorkflowService()
+ monkeypatch.setattr(svc, "persist_video_data", AsyncMock())
+ monkeypatch.setattr(svc, "get_tasks_by_workflow_run_id", AsyncMock(return_value=[]))
+
+ await svc.clean_up_workflow(workflow=workflow, workflow_run=workflow_run, need_call_webhook=False)
+
+ persist_mock.assert_not_awaited()