Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-12081): author-time reject for unresolvable freehand copilot selectors + idempotent login (#7419)
Andrew Neilsond438273d1e49
diff --git a/skyvern-frontend/package-lock.json b/skyvern-frontend/package-lock.jsonindex c8d3954bf..5e6133942 100644--- a/skyvern-frontend/package-lock.json+++ b/skyvern-frontend/package-lock.json@@ -41,6 +41,7 @@"@radix-ui/react-tooltip": "^1.0.7","@radix-ui/react-visually-hidden": "^1.1.0","@tanstack/react-query": "^5.28.6",+ "@uiw/codemirror-theme-tokyo-night-day": "^4.23.0","@uiw/codemirror-theme-tokyo-night-storm": "^4.23.0","@uiw/react-codemirror": "^4.23.0","@xyflow/react": "^12.1.1",@@ -3900,6 +3901,18 @@"@codemirror/view": ">=6.0.0"}},+ "node_modules/@uiw/codemirror-theme-tokyo-night-day": {+ "version": "4.25.9",+ "resolved": "https://registry.npmjs.org/@uiw/codemirror-theme-tokyo-night-day/-/codemirror-theme-tokyo-night-day-4.25.9.tgz",+ "integrity": "sha512-1ziFletBO6tfRtX4FVWij1wYIf95uYi54dgnMz5CXe4A4u710rJ3uS3C4ijlnclRbwHjNTqtrMWNuicKDBMsPg==",+ "license": "MIT",+ "dependencies": {+ "@uiw/codemirror-themes": "4.25.9"+ },+ "funding": {+ "url": "https://jaywcjlove.github.io/#/sponsor"+ }+ },"node_modules/@uiw/codemirror-theme-tokyo-night-storm": {"version": "4.25.9","resolved": "https://registry.npmjs.org/@uiw/codemirror-theme-tokyo-night-storm/-/codemirror-theme-tokyo-night-storm-4.25.9.tgz",diff --git a/skyvern-frontend/package.json b/skyvern-frontend/package.jsonindex 75e1ca0d2..428662025 100644--- a/skyvern-frontend/package.json+++ b/skyvern-frontend/package.json@@ -52,6 +52,7 @@"@radix-ui/react-tooltip": "^1.0.7","@radix-ui/react-visually-hidden": "^1.1.0","@tanstack/react-query": "^5.28.6",+ "@uiw/codemirror-theme-tokyo-night-day": "^4.23.0","@uiw/codemirror-theme-tokyo-night-storm": "^4.23.0","@uiw/react-codemirror": "^4.23.0","@xyflow/react": "^12.1.1",diff --git a/skyvern-frontend/src/routes/workflows/components/BlockCodeEditor.tsx b/skyvern-frontend/src/routes/workflows/components/BlockCodeEditor.tsxindex ca0b02144..485f771d3 100644--- a/skyvern-frontend/src/routes/workflows/components/BlockCodeEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/components/BlockCodeEditor.tsx@@ -122,7 +122,7 @@ function BlockCodeEditor({/></div>) : (- <div className="flex h-full w-full items-center justify-center bg-slate-950 text-slate-100">+ <div className="flex h-full w-full items-center justify-center bg-muted text-muted-foreground dark:bg-slate-950 dark:text-slate-100">No script defined</div>)}diff --git a/skyvern-frontend/src/routes/workflows/components/BlockOutputs.tsx b/skyvern-frontend/src/routes/workflows/components/BlockOutputs.tsxindex a49bbc00a..8061a0fb2 100644--- a/skyvern-frontend/src/routes/workflows/components/BlockOutputs.tsx+++ b/skyvern-frontend/src/routes/workflows/components/BlockOutputs.tsx@@ -134,7 +134,7 @@ function BlockOutputs({/></>) : (- <div className="flex h-full w-full flex-1 items-center justify-center bg-slate-950 text-slate-100">+ <div className="flex h-full w-full flex-1 items-center justify-center bg-muted text-muted-foreground dark:bg-slate-950 dark:text-slate-100">No output defined</div>)}diff --git a/skyvern-frontend/src/routes/workflows/components/CodeEditor.test.tsx b/skyvern-frontend/src/routes/workflows/components/CodeEditor.test.tsxindex 00433366b..c00d3d18c 100644--- a/skyvern-frontend/src/routes/workflows/components/CodeEditor.test.tsx+++ b/skyvern-frontend/src/routes/workflows/components/CodeEditor.test.tsx@@ -9,10 +9,16 @@ type CmMockProps = {onChange?: unknown;onBlur?: unknown;value?: string;+ theme?: unknown;};const cmMockCalls: CmMockProps[] = [];+const themeModeMock = vi.hoisted(() => vi.fn());+vi.mock("@/components/useThemeAsDarkOrLight", () => ({+ useThemeAsDarkOrLight: () => themeModeMock(),+}));+vi.mock("@uiw/react-codemirror", async (importOriginal) => {const actual = await importOriginal<typeof import("@uiw/react-codemirror")>();return {@@ -26,9 +32,12 @@ vi.mock("@uiw/react-codemirror", async (importOriginal) => {beforeEach(() => {cmMockCalls.length = 0;+ themeModeMock.mockReturnValue("dark");});import { CodeEditor } from "./CodeEditor";+import { tokyoNightStorm } from "@uiw/codemirror-theme-tokyo-night-storm";+import { tokyoNightDay } from "@uiw/codemirror-theme-tokyo-night-day";// Drive the IntersectionObserver mock so we can flip visibility deterministically.let observerCallback: IntersectionObserverCallback | null = null;@@ -156,3 +165,27 @@ describe("CodeEditor callback identity (SKY-9051)", () => {expect(finalOnUpdate).toBe(initialOnUpdate);});});++describe("CodeEditor theme (SKY-12414)", () => {+ function mountAndReadTheme() {+ render(<CodeEditor value="print('hi')" language="python" />);+ observerCallback!(+ [{ isIntersecting: true } as IntersectionObserverEntry],+ {} as IntersectionObserver,+ );+ return waitFor(() => {+ expect(cmMockCalls.length).toBeGreaterThan(0);+ return cmMockCalls[cmMockCalls.length - 1]!.theme;+ });+ }++ test("uses the light Tokyo Night Day theme in light mode", async () => {+ themeModeMock.mockReturnValue("light");+ expect(await mountAndReadTheme()).toBe(tokyoNightDay);+ });++ test("uses the dark Tokyo Night Storm theme in dark mode", async () => {+ themeModeMock.mockReturnValue("dark");+ expect(await mountAndReadTheme()).toBe(tokyoNightStorm);+ });+});diff --git a/skyvern-frontend/src/routes/workflows/components/CodeEditor.tsx b/skyvern-frontend/src/routes/workflows/components/CodeEditor.tsxindex 9d5802561..0edeb5901 100644--- a/skyvern-frontend/src/routes/workflows/components/CodeEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/components/CodeEditor.tsx@@ -5,8 +5,10 @@ import { python } from "@codemirror/lang-python";import { html } from "@codemirror/lang-html";import { yaml } from "@codemirror/lang-yaml";import { tokyoNightStorm } from "@uiw/codemirror-theme-tokyo-night-storm";+import { tokyoNightDay } from "@uiw/codemirror-theme-tokyo-night-day";import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import { cn } from "@/util/utils";+import { useThemeAsDarkOrLight } from "@/components/useThemeAsDarkOrLight";import { useDebouncedCallback } from "use-debounce";import {@@ -85,6 +87,7 @@ function CodeEditorImpl({// the editor and the oversized-document guard never read `.length` of// undefined.const safeValue = value ?? "";+ const themeMode = useThemeAsDarkOrLight();const viewRef = useRef<EditorView | null>(null);const [internalValue, setInternalValue] = useState(safeValue);const latestValueRef = useRef(safeValue);@@ -277,7 +280,7 @@ function CodeEditorImpl({value={internalValue}onChange={handleChange}extensions={extensions}- theme={tokyoNightStorm}+ theme={themeMode === "dark" ? tokyoNightStorm : tokyoNightDay}minHeight={minHeight}maxHeight={maxHeight}readOnly={readOnly}diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsxindex bce78e98c..54851ed84 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx@@ -341,3 +341,53 @@ describe("NarrativeView — phase checklist (SKY-11970)", () => {expect(screen.queryByText("Block 1")).toBeNull();});});++describe("NarrativeView — narrator content condensing (SKY-11971)", () => {+ const retriedBlockActivity: ActivityEntry[] = [+ activityEntry({+ id: "tc-x1",+ kind: "tool_call",+ toolName: "extract",+ displayLabel: "Extracting",+ }),+ activityEntry({+ id: "tr-x1",+ kind: "tool_result",+ toolName: "extract",+ success: false,+ text: "no results found",+ }),+ activityEntry({+ id: "tc-x2",+ kind: "tool_call",+ toolName: "extract",+ displayLabel: "Extracting",+ }),+ activityEntry({+ id: "tr-x2",+ kind: "tool_result",+ toolName: "extract",+ success: true,+ text: "top 5 titles + links",+ }),+ ];++ const retriedTurn = (): TurnNarrativeState => ({+ ...testActiveTurn(),+ blocks: [runningBlock({ activity: retriedBlockActivity })],+ });++ it("checklist (uxV1): folds the block's failed-then-retried tool activity into one row with an attempt count", () => {+ render(<NarrativeView turn={retriedTurn()} uxV1 />);+ expect(screen.queryByText("no results found")).toBeNull();+ expect(screen.getByText("top 5 titles + links")).toBeTruthy();+ expect(screen.getByText(/2 attempts/)).toBeTruthy();+ });++ it("legacy (uxV1 absent): renders every raw call/result row unfolded, exactly as before", () => {+ render(<NarrativeView turn={retriedTurn()} />);+ expect(screen.getByText("no results found")).toBeTruthy();+ expect(screen.getByText("top 5 titles + links")).toBeTruthy();+ expect(screen.queryByText(/attempts/)).toBeNull();+ });+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.tsindex 259487e10..80ec5c75e 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts@@ -1,11 +1,13 @@import { describe, expect, it } from "vitest";import {+ ActivityEntry,BlockState,EMPTY_NARRATIVE,TurnNarrativeState,applyNarrativeEvent,computeTurnSummary,+ condenseActivityEntries,effectiveMode,hydrateHistoryNarrative,hydrateNarrativeFromPayload,@@ -14,9 +16,11 @@ import {WorkflowCopilotBlockProgressUpdate,WorkflowCopilotDesignEndUpdate,WorkflowCopilotDesignStartUpdate,+ WorkflowCopilotNarrationUpdate,WorkflowCopilotStreamErrorUpdate,WorkflowCopilotStreamResponseUpdate,WorkflowCopilotToolCallUpdate,+ WorkflowCopilotToolResultUpdate,WorkflowCopilotTurnStartUpdate,WorkflowCopilotWorkflowDraftUpdate,} from "./workflowCopilotTypes";@@ -77,6 +81,28 @@ const toolCall = (...overrides,});+const toolResult = (+ overrides: Partial<WorkflowCopilotToolResultUpdate> = {},+): WorkflowCopilotToolResultUpdate => ({+ type: "tool_result",+ tool_name: "update_and_run_blocks",+ success: true,+ summary: "Testing workflow successful",+ iteration: 0,+ tool_call_id: "call-1",+ ...overrides,+});++const narration = (+ overrides: Partial<WorkflowCopilotNarrationUpdate> = {},+): WorkflowCopilotNarrationUpdate => ({+ type: "narration",+ narration: "Reading the page…",+ iteration: 0,+ timestamp: "2026-05-25T00:00:04Z",+ ...overrides,+});+const response = (overrides: Partial<WorkflowCopilotStreamResponseUpdate> = {},): WorkflowCopilotStreamResponseUpdate => ({@@ -352,6 +378,247 @@ describe("applyNarrativeEvent — activity", () => {});});+describe("condenseActivityEntries", () => {+ function reduceEvents(events: Parameters<typeof applyNarrativeEvent>[1][]) {+ return events.reduce(+ (state: TurnNarrativeState, event) => applyNarrativeEvent(state, event),+ EMPTY_NARRATIVE,+ );+ }++ it("folds a resolved tool_call/tool_result pair into one row (no leftover calling… chatter)", () => {+ const s = reduceEvents([+ toolCall({ tool_call_id: "call-1", tool_name: "evaluate" }),+ toolResult({+ tool_call_id: "call-1",+ tool_name: "evaluate",+ success: true,+ }),+ ]);+ const condensed = condenseActivityEntries(s.designActivity);+ expect(condensed).toHaveLength(1);+ expect(condensed[0]).toMatchObject({ kind: "tool_result", success: true });+ });++ it("REGRESSION PIN: substitutes the humanized tool name for the backend's bare 'OK' fallback (celal QA catch)", () => {+ // A tool with no dedicated backend summary falls back to a literal+ // "OK" — condensing already removed the "<tool> · calling…" row that+ // used to give it context, so a bare "OK" reads as meaningless.+ const s = reduceEvents([+ toolCall({ tool_call_id: "call-1", tool_name: "evaluate" }),+ toolResult({+ tool_call_id: "call-1",+ tool_name: "evaluate",+ summary: "OK",+ }),+ ]);+ const condensed = condenseActivityEntries(s.designActivity);+ expect(condensed).toHaveLength(1);+ expect(condensed[0]?.text).toBe("Inspecting page");+ expect(condensed[0]?.text).not.toBe("OK");+ });++ it("leaves a real (non-fallback) backend summary untouched, even if a mapped tool", () => {+ const s = reduceEvents([+ toolCall({ tool_call_id: "call-1", tool_name: "evaluate" }),+ toolResult({+ tool_call_id: "call-1",+ tool_name: "evaluate",+ summary: "Evaluated JavaScript — returned a string",+ }),+ ]);+ const condensed = condenseActivityEntries(s.designActivity);+ expect(condensed[0]?.text).toBe("Evaluated JavaScript — returned a string");+ });++ it("folds a failed attempt then a retry into one row, terminal outcome only", () => {+ const s = reduceEvents([+ toolCall({ tool_call_id: "call-1", tool_name: "extract" }),+ toolResult({+ tool_call_id: "call-1",+ tool_name: "extract",+ success: false,+ summary: "no results",+ }),+ toolCall({ tool_call_id: "call-2", tool_name: "extract" }),+ toolResult({+ tool_call_id: "call-2",+ tool_name: "extract",+ success: true,+ summary: "top 5 titles",+ }),+ ]);+ const condensed = condenseActivityEntries(s.designActivity);+ expect(condensed).toHaveLength(1);+ expect(condensed[0]).toMatchObject({+ success: true,+ attempts: 2,+ text: "top 5 titles",+ });+ });++ it("folds a 3-attempt retry chain into one row with attempts=3", () => {+ const s = reduceEvents([+ toolCall({ tool_call_id: "c1", tool_name: "extract" }),+ toolResult({ tool_call_id: "c1", tool_name: "extract", success: false }),+ toolCall({ tool_call_id: "c2", tool_name: "extract" }),+ toolResult({ tool_call_id: "c2", tool_name: "extract", success: false }),+ toolCall({ tool_call_id: "c3", tool_name: "extract" }),+ toolResult({ tool_call_id: "c3", tool_name: "extract", success: true }),+ ]);+ const condensed = condenseActivityEntries(s.designActivity);+ expect(condensed).toHaveLength(1);+ expect(condensed[0]).toMatchObject({ success: true, attempts: 3 });+ });++ it("folds a retry across a narration sitting between two attempts (narration never breaks the fold)", () => {+ // Array position can't reliably tell "narration between attempts" from+ // "narration mid-flight during the retry itself" (see the regression+ // pin below, where the same ordered shape arises from a genuinely+ // different case) — so narration is never treated as a fold-breaking+ // gap, full stop.+ const s = reduceEvents([+ toolCall({ tool_call_id: "c1", tool_name: "extract" }),+ toolResult({ tool_call_id: "c1", tool_name: "extract", success: false }),+ narration(),+ toolCall({ tool_call_id: "c2", tool_name: "extract" }),+ toolResult({ tool_call_id: "c2", tool_name: "extract", success: true }),+ ]);+ const condensed = condenseActivityEntries(s.designActivity);+ // Narration arrived before the merged (2nd-attempt) result, so the+ // fold keeps that order — narration first, not stranded after a row+ // whose content is chronologically later than it.+ expect(condensed.map((e) => e.kind)).toEqual(["narration", "tool_result"]);+ expect(condensed[1]).toMatchObject({ success: true, attempts: 2 });+ });++ it("REGRESSION PIN: folds a retry when the narration fires mid-flight during the RETRY itself (Codex catch)", () => {+ // Ordering fix (pass 1) puts this narration in the identical array+ // position as narration genuinely between two attempts — attempt 1's+ // clean result already sits before attempt 2's call, so the retry's+ // own mid-flight narration lands right after it either way. Only a+ // narration-agnostic fold (last TOOL row, not literal adjacency)+ // survives this case.+ const s = reduceEvents([+ toolCall({ tool_call_id: "c1", tool_name: "extract" }),+ toolResult({ tool_call_id: "c1", tool_name: "extract", success: false }),+ toolCall({ tool_call_id: "c2", tool_name: "extract" }),+ narration(),+ toolResult({ tool_call_id: "c2", tool_name: "extract", success: true }),+ ]);+ const condensed = condenseActivityEntries(s.designActivity);+ // The merge must not leave the (chronologically later) result parked+ // at attempt 1's old position, ahead of narration that streamed+ // before it arrived.+ expect(condensed.map((e) => e.kind)).toEqual(["narration", "tool_result"]);+ expect(condensed[1]).toMatchObject({ success: true, attempts: 2 });+ });++ it("REGRESSION PIN: folds a retry even when the narration fires mid-flight, during the FIRST attempt (reviewer catch)", () => {+ // The narrator can emit a progress narration while a call is still+ // pending. Pairing (pass 1) then places attempt 1's result at attempt+ // 1's call position, ahead of that narration — which used to make the+ // narration look like it sat BETWEEN the two attempts and break the+ // fold, even though nothing genuinely interrupted the retry.+ const s = reduceEvents([+ toolCall({ tool_call_id: "c1", tool_name: "extract" }),+ narration(),+ toolResult({ tool_call_id: "c1", tool_name: "extract", success: false }),+ toolCall({ tool_call_id: "c2", tool_name: "extract" }),+ toolResult({ tool_call_id: "c2", tool_name: "extract", success: true }),+ ]);+ const condensed = condenseActivityEntries(s.designActivity);+ expect(condensed.map((e) => e.kind)).toEqual(["narration", "tool_result"]);+ expect(condensed[1]).toMatchObject({ success: true, attempts: 2 });+ });++ it("does not fold two consecutive different-tool results", () => {+ const s = reduceEvents([+ toolCall({ tool_call_id: "c1", tool_name: "navigate_browser" }),+ toolResult({+ tool_call_id: "c1",+ tool_name: "navigate_browser",+ success: false,+ }),+ toolCall({ tool_call_id: "c2", tool_name: "evaluate" }),+ toolResult({ tool_call_id: "c2", tool_name: "evaluate", success: true }),+ ]);+ const condensed = condenseActivityEntries(s.designActivity);+ expect(condensed).toHaveLength(2);+ });++ it("keeps an orphaned tool_result (its call was evicted) as its own row instead of dropping it", () => {+ const entries: ActivityEntry[] = [+ {+ kind: "tool_result",+ text: "done",+ iteration: 0,+ toolName: "evaluate",+ success: true,+ id: "tr-orphan-1",+ },+ ];+ expect(condenseActivityEntries(entries)).toEqual(entries);+ });++ it("REGRESSION PIN: still pairs a call/result whose sliced tool_call_id is an empty string (Claude catch)", () => {+ // toolCallIdOf returns "" (falsy but defined) for an id like "tc-" —+ // a truthiness check would treat that as "no id" and never pair it,+ // inconsistent with hasPendingToolCall's unconditional `?? ""`.+ const entries: ActivityEntry[] = [+ {+ kind: "tool_call",+ text: "Extracting…",+ iteration: 0,+ toolName: "extract",+ id: "tc-",+ },+ {+ kind: "tool_result",+ text: "done",+ iteration: 0,+ toolName: "extract",+ success: true,+ id: "tr-",+ },+ ];+ expect(condenseActivityEntries(entries)).toHaveLength(1);+ });++ it("an orphaned same-tool result immediately after a failed attempt still folds as its retry outcome", () => {+ const s = reduceEvents([+ toolCall({ tool_call_id: "c1", tool_name: "extract" }),+ toolResult({ tool_call_id: "c1", tool_name: "extract", success: false }),+ ]);+ const orphan: ActivityEntry = {+ kind: "tool_result",+ text: "top 5 titles + links",+ iteration: 1,+ toolName: "extract",+ success: true,+ id: "tr-evicted-call-2",+ };+ const condensed = condenseActivityEntries([...s.designActivity, orphan]);+ expect(condensed).toHaveLength(1);+ expect(condensed[0]).toMatchObject({+ success: true,+ attempts: 2,+ text: "top 5 titles + links",+ });+ });++ it("leaves a still-pending retry visible, tagged with the attempt count", () => {+ const s = reduceEvents([+ toolCall({ tool_call_id: "c1", tool_name: "extract" }),+ toolResult({ tool_call_id: "c1", tool_name: "extract", success: false }),+ toolCall({ tool_call_id: "c2", tool_name: "extract" }),+ ]);+ const condensed = condenseActivityEntries(s.designActivity);+ expect(condensed).toHaveLength(1);+ expect(condensed[0]).toMatchObject({ kind: "tool_call", attempts: 2 });+ });+});+describe("applyNarrativeEvent — terminal", () => {it("response closes designEnded and uses narrative_summary when present", () => {let s = applyNarrativeEvent(EMPTY_NARRATIVE, designStart());diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsxindex fe5515715..8341f6906 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx@@ -15,6 +15,7 @@ import {TurnNarrativeState,TurnSummary,computeTurnSummary,+ condenseActivityEntries,effectiveMode,formatElapsed,isBlockOk,@@ -173,6 +174,16 @@ function FSubRow({);}+function AttemptsBadge({ attempts }: { attempts?: number }) {+ if (!attempts || attempts <= 1) return null;+ return (+ <span className="text-muted-foreground dark:text-slate-500">+ {" "}+ · ↻ {attempts} attempts+ </span>+ );+}+function ActivityRow({ entry }: { entry: ActivityEntry }) {if (entry.kind === "narration") {return (@@ -196,6 +207,7 @@ function ActivityRow({ entry }: { entry: ActivityEntry }) {{" "}· calling…</span>+ <AttemptsBadge attempts={entry.attempts} /></FSubRow>);}@@ -218,6 +230,7 @@ function ActivityRow({ entry }: { entry: ActivityEntry }) {>{entry.text}</span>+ <AttemptsBadge attempts={entry.attempts} /></FSubRow>);}@@ -733,6 +746,14 @@ function FPhaseChecklist({uxV1,}: FPhaseChecklistProps) {const rows = useMemo(() => derivePhases(turn), [turn]);+ const condensedBlocks = useMemo(+ () =>+ turn.blocks.map((b) => ({+ ...b,+ activity: condenseActivityEntries(b.activity),+ })),+ [turn.blocks],+ );const [openPhases, setOpenPhases] = useState<Set<CopilotPhaseId>>(() => new Set(),);@@ -853,7 +874,7 @@ function FPhaseChecklist({{row.entries.map((entry) => (<ActivityRow key={entry.id} entry={entry} />))}- {turn.blocks.map((b) => (+ {condensedBlocks.map((b) => (<FBlockRunkey={b.workflowRunBlockId || b.label}block={b}diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsxindex a46eb739f..d44f58448 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx@@ -165,7 +165,11 @@ function chatUi() {async function renderChat() {const view = render(chatUi());await waitFor(() =>- expect(screen.getByPlaceholderText(/Message Skyvern Copilot/)).toBeTruthy(),+ expect(+ screen.getByPlaceholderText(+ /Message Skyvern Copilot|Ask Copilot to build/,+ ),+ ).toBeTruthy(),);return view;}diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsxindex 29c1bcf48..e3d32b821 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx@@ -317,6 +317,34 @@ describe("WorkflowCopilotChat — S4 composer, copilot_ux_v1 on", () => {screen.queryByText("Prompt queued. Waiting for live browser..."),).toBeNull();});++ it("embeds the input: idle placeholder matches the mock, textarea borderless inside a focus-within container", async () => {+ await renderChat({ copilotV2: true, codeBlockMode: true });+ const ta = textarea();++ expect(ta.getAttribute("placeholder")).toBe(+ "Ask Copilot to build or change your workflow…",+ );+ // Border + focus ring moved off the textarea onto the wrapping container.+ expect(ta.className).not.toContain("border-input");+ expect(ta.parentElement?.className).toContain("focus-within");+ });++ it("places the mic and send inside the container, with the mic to the right of the input", async () => {+ await renderChat({ copilotV2: true, codeBlockMode: true });+ const ta = textarea();+ const container = ta.parentElement as HTMLElement;+ const mic = screen.getByRole("button", { name: "Dictate message" });+ const send = screen.getByRole("button", { name: "Send" });++ expect(container.contains(mic)).toBe(true);+ expect(container.contains(send)).toBe(true);+ // Embedded on the right: the mic now follows the textarea in DOM order+ // (it sits before it in the legacy flat row).+ expect(+ ta.compareDocumentPosition(mic) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ });});describe("WorkflowCopilotChat — S4 composer, copilot_ux_v1 off (parity)", () => {@@ -341,4 +369,20 @@ describe("WorkflowCopilotChat — S4 composer, copilot_ux_v1 off (parity)", () =screen.queryByRole("button", { name: "Cancel queued message" }),).toBeNull();});++ it("keeps the legacy flat row: bordered textarea, legacy placeholder, mic before the input", async () => {+ mockCopilotUxV1Enabled.mockReturnValue(false);+ await renderChat({ copilotV2: true, codeBlockMode: true });+ const ta = textarea();+ const mic = screen.getByRole("button", { name: "Dictate message" });++ expect(ta.getAttribute("placeholder")).toBe(+ "Message Skyvern Copilot, or paste recorded steps…",+ );+ expect(ta.className).toContain("border-input");+ // Legacy layout: the mic sits before the textarea, outside any embedded container.+ expect(+ ta.compareDocumentPosition(mic) & Node.DOCUMENT_POSITION_PRECEDING,+ ).toBeTruthy();+ });});diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsxnew file mode 100644index 000000000..aa75a801c--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx@@ -0,0 +1,594 @@+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { COPILOT_UX_V1_FLAG } from "@/util/featureFlags";++import type { WorkflowCopilotCredentialRequiredUpdate } from "./workflowCopilotTypes";++type StreamBody = {+ message: string;+ supports_credential_pause?: boolean;+};+type StreamCall = {+ body: StreamBody;+ onMessage: (payload: unknown) => boolean;+ resolve: () => void;+ reject: (error: unknown) => void;+};++const {+ streamCalls,+ postStreaming,+ apiPost,+ sansApiPost,+ getClientMock,+ apiGet,+ historyResponse,+ credentialsData,+ credsFail,+ modalOverrideType,+ toastFn,+ flagMap,+} = vi.hoisted(() => {+ const calls: StreamCall[] = [];+ const streaming = vi.fn(+ (+ _path: string,+ body: StreamBody,+ onMessage: (payload: unknown) => boolean,+ ) =>+ new Promise<void>((resolve, reject) => {+ calls.push({ body, onMessage, resolve, reject });+ }),+ );+ const history = {+ data: {+ workflow_copilot_chat_id: "chat-1" as string | null,+ chat_history: [] as unknown[],+ proposed_workflow: null as Record<string, unknown> | null,+ auto_accept: false,+ },+ };+ const creds = {+ current: [] as Array<{+ credential_id: string;+ name: string;+ tested_url: string | null;+ }>,+ };+ const post = vi.fn().mockResolvedValue({});+ const sansPost = vi.fn().mockResolvedValue({});+ const fail = { current: false };+ const get = vi.fn().mockImplementation((path: string) => {+ if (path === "/credentials") {+ return fail.current+ ? Promise.reject(new Error("network"))+ : Promise.resolve({ data: creds.current });+ }+ return Promise.resolve(history);+ });+ // Route post by API version: copilot routes (credential-response) must use+ // the sans-api-v1 client (base_router), not the default /api/v1 client.+ const getClientFn = vi.fn((_cg: unknown, version?: string) =>+ Promise.resolve({+ get,+ post: version === "sans-api-v1" ? sansPost : post,+ }),+ );+ return {+ streamCalls: calls,+ postStreaming: streaming,+ apiPost: post,+ sansApiPost: sansPost,+ getClientMock: getClientFn,+ apiGet: get,+ historyResponse: history,+ credentialsData: creds,+ credsFail: fail,+ modalOverrideType: { current: undefined as string | undefined },+ toastFn: vi.fn(),+ flagMap: { current: {} as Record<string, boolean> },+ };+});++vi.mock("@/api/sse", () => ({+ getSseClient: vi.fn().mockResolvedValue({ postStreaming }),+}));++vi.mock("@/api/AxiosClient", () => ({+ getClient: getClientMock,+}));++vi.mock("@/hooks/useCredentialGetter", () => ({+ useCredentialGetter: () => null,+}));++vi.mock("@/components/ui/use-toast", () => ({ toast: toastFn }));++// The real modal pulls react-query; a stub is enough to prove the connect →+// modal → onCredentialCreated wiring.+vi.mock("@/routes/credentials/CredentialsModal", () => ({+ CredentialsModal: ({+ isOpen,+ onCredentialCreated,+ overrideType,+ }: {+ isOpen?: boolean;+ onCredentialCreated?: (id: string) => void;+ overrideType?: string;+ }) => {+ modalOverrideType.current = overrideType;+ return isOpen ? (+ <button+ type="button"+ data-testid="mock-create-credential"+ onClick={() => onCredentialCreated?.("new-cred-1")}+ >+ create credential+ </button>+ ) : null;+ },+}));++vi.mock("react-router-dom", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react-router-dom")>();+ return {+ ...actual,+ useParams: () => ({+ workflowPermanentId: "wpid_1",+ workflowRunId: undefined,+ }),+ useSearchParams: () => [new URLSearchParams(), vi.fn()],+ };+});++vi.mock("posthog-js/react", () => ({+ useFeatureFlagEnabled: (flag: string) => flagMap.current[flag] ?? false,+}));++const saveData = {+ title: "Test WF",+ workflow: {+ workflow_id: "wf_1",+ workflow_permanent_id: "wpid_1",+ description: "",+ totp_verification_url: null,+ is_saved_task: false,+ status: "published",+ },+ settings: {+ proxyLocation: null,+ webhookCallbackUrl: null,+ persistBrowserSession: false,+ pinSavedSessionIp: false,+ browserProfileId: null,+ browserProfileKey: null,+ model: null,+ maxScreenshotScrolls: null,+ extraHttpHeaders: null,+ runWith: "agent",+ scriptCacheKey: "",+ aiFallback: true,+ codeVersion: 2,+ runSequentially: false,+ sequentialKey: null,+ },+ parameters: [],+ blocks: [],+ workflowDefinitionVersion: 1,+};++vi.mock("@/store/WorkflowHasChangesStore", () => ({+ useWorkflowHasChangesStore: () => ({ getSaveData: () => saveData }),+}));++vi.mock("@/routes/workflows/hooks/useWorkflowRunQuery", () => ({+ useWorkflowRunQuery: () => ({ data: undefined }),+}));++import { WorkflowCopilotChat } from "./WorkflowCopilotChat";++async function renderChat() {+ const view = render(<WorkflowCopilotChat docked={false} />);+ await waitFor(() =>+ expect(screen.getByPlaceholderText(/Message Skyvern Copilot/)).toBeTruthy(),+ );+ return view;+}++function textarea(): HTMLTextAreaElement {+ return screen.getByRole("textbox") as HTMLTextAreaElement;+}++async function submit(value: string) {+ fireEvent.change(textarea(), { target: { value } });+ await act(async () => {+ fireEvent.keyDown(textarea(), { key: "Enter" });+ });+}++const turnStart = (turnId = "turn-1") => ({+ type: "turn_start",+ turn_id: turnId,+ turn_index: 0,+ mode: "build",+ timestamp: "2026-07-13T00:00:00Z",+});++const credentialFrame = (+ overrides: Partial<WorkflowCopilotCredentialRequiredUpdate> = {},+): WorkflowCopilotCredentialRequiredUpdate => ({+ type: "credential_required",+ turn_id: "turn-1",+ workflow_copilot_chat_id: "chat-1",+ resume_token: "rt-abc",+ reason: "workflow_credential_inputs_unbound",+ message: "",+ login_page_urls: ["https://news.ycombinator.com/login"],+ credential_refs: [],+ timeout_seconds: 300,+ // Future relative to the real clock so the inline countdown isn't expired+ // (an expired card disables its buttons).+ expires_at: new Date(Date.now() + 300_000).toISOString(),+ timestamp: new Date().toISOString(),+ ...overrides,+});++const terminalPromptResponse = (turnId = "turn-9") => ({+ type: "response",+ workflow_copilot_chat_id: "chat-1",+ message: "Connect a credential to continue.",+ updated_workflow: null,+ response_time: "2026-07-13T00:00:05Z",+ proposal_disposition: "no_proposal",+ turn_id: turnId,+ narrative_payload: {+ turnId,+ turnIndex: 0,+ mode: "build",+ responseType: "REPLY",+ terminal: "response",+ terminalMessage: "Connect a credential to continue.",+ narrativeSummary: "Connect a credential to continue.",+ startedAt: "2026-07-13T00:00:00Z",+ endedAt: "2026-07-13T00:00:05Z",+ credentialPrompt: { reason: "credential_name_unresolved" },+ },+});++// A pause that engaged but never sent a frame — no card should render.+const terminalDeclinedResponse = (turnId = "turn-7") => ({+ type: "response",+ workflow_copilot_chat_id: "chat-1",+ message: "Let me know which credential to use.",+ updated_workflow: null,+ response_time: "2026-07-13T00:00:05Z",+ proposal_disposition: "no_proposal",+ turn_id: turnId,+ narrative_payload: {+ turnId,+ turnIndex: 0,+ mode: "build",+ responseType: "REPLY",+ terminal: "response",+ terminalMessage: "Let me know which credential to use.",+ narrativeSummary: "Let me know which credential to use.",+ startedAt: "2026-07-13T00:00:00Z",+ endedAt: "2026-07-13T00:00:05Z",+ credentialPrompt: { reason: "credential_name_unresolved" },+ credentialPause: { outcome: "declined" },+ },+});++const errorFrame = (turnId = "turn-1") => ({+ type: "error",+ error: "The turn failed.",+ turn_id: turnId,+});++function credentialResponsePosts() {+ return sansApiPost.mock.calls.filter(+ (call) => call[0] === "/workflow/copilot/credential-response",+ );+}++function credentialsGets() {+ return apiGet.mock.calls.filter((call) => call[0] === "/credentials");+}++beforeEach(() => {+ HTMLElement.prototype.scrollIntoView = vi.fn();+ HTMLElement.prototype.scrollTo = vi.fn();+ streamCalls.length = 0;+ postStreaming.mockClear();+ apiPost.mockClear();+ apiPost.mockResolvedValue({});+ sansApiPost.mockClear();+ sansApiPost.mockResolvedValue({});+ apiGet.mockClear();+ toastFn.mockClear();+ credentialsData.current = [];+ credsFail.current = false;+ modalOverrideType.current = undefined;+ flagMap.current = {};+ historyResponse.data = {+ workflow_copilot_chat_id: "chat-1",+ chat_history: [],+ proposed_workflow: null,+ auto_accept: false,+ };+});++afterEach(() => {+ cleanup();+});++describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {+ it("sends supports_credential_pause on the request", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ expect(streamCalls[0]!.body.supports_credential_pause).toBe(true);+ });++ it("renders the inline-pause card when a credential_required frame arrives", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart());+ streamCalls[0]!.onMessage(credentialFrame());+ });+ expect(+ screen.getByText(/Copilot needs to sign in to news\.ycombinator\.com/),+ ).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Connect credential" }),+ ).toBeTruthy();+ });++ it("skip POSTs a credential-response with action skip", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart());+ streamCalls[0]!.onMessage(credentialFrame());+ });+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Skip for now" }));+ });+ await waitFor(() => expect(credentialResponsePosts()).toHaveLength(1));+ expect(credentialResponsePosts()[0]![1]).toMatchObject({+ turn_id: "turn-1",+ workflow_copilot_chat_id: "chat-1",+ resume_token: "rt-abc",+ action: "skip",+ });+ });++ it("connect with an existing matched credential POSTs the credential_id", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ credentialsData.current = [+ {+ credential_id: "cred-hn",+ name: "HN Login",+ tested_url: "https://news.ycombinator.com/login",+ },+ ];+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart());+ streamCalls[0]!.onMessage(credentialFrame());+ });+ const useButton = await screen.findByRole("button", {+ name: /Use 'HN Login'/,+ });+ await act(async () => {+ fireEvent.click(useButton);+ });+ await waitFor(() => expect(credentialResponsePosts()).toHaveLength(1));+ expect(credentialResponsePosts()[0]![1]).toMatchObject({+ action: "connected",+ credential_id: "cred-hn",+ });+ // Receipt keeps the credential name after the turn goes terminal.+ await act(async () => {+ streamCalls[0]!.onMessage({+ type: "response",+ workflow_copilot_chat_id: "chat-1",+ message: "Connected. Continuing.",+ updated_workflow: null,+ response_time: "2026-07-13T00:00:06Z",+ proposal_disposition: "no_proposal",+ turn_id: "turn-1",+ narrative_payload: {+ turnId: "turn-1",+ turnIndex: 0,+ mode: "build",+ responseType: "REPLY",+ terminal: "response",+ terminalMessage: "Connected. Continuing.",+ startedAt: "2026-07-13T00:00:00Z",+ endedAt: "2026-07-13T00:00:06Z",+ credentialPause: { outcome: "connected", credentialId: "cred-hn" },+ },+ });+ streamCalls[0]!.resolve();+ });+ expect(await screen.findByText(/Credential 'HN Login' added/)).toBeTruthy();+ });++ it("connect CTA opens the modal, then a created credential POSTs connected", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart());+ streamCalls[0]!.onMessage(credentialFrame());+ });+ await act(async () => {+ fireEvent.click(+ screen.getByRole("button", { name: "Connect credential" }),+ );+ });+ const createBtn = await screen.findByTestId("mock-create-credential");+ // A sign-in pause forces the password credential form regardless of any+ // lingering ?type= param.+ expect(modalOverrideType.current).toBe("password");+ await act(async () => {+ fireEvent.click(createBtn);+ });+ await waitFor(() => expect(credentialResponsePosts()).toHaveLength(1));+ expect(credentialResponsePosts()[0]![1]).toMatchObject({+ action: "connected",+ credential_id: "new-cred-1",+ });+ });++ it("keeps the card actionable, toasts, and never logs the raw error (resume_token leak) when the resume POST fails", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ // AxiosError-shaped: config.data carries the one-time resume_token.+ sansApiPost.mockRejectedValueOnce(+ Object.assign(new Error("Request failed with status code 404"), {+ config: { data: JSON.stringify({ resume_token: "rt-secret" }) },+ }),+ );+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart());+ streamCalls[0]!.onMessage(credentialFrame());+ });+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Skip for now" }));+ });+ await waitFor(() => expect(toastFn).toHaveBeenCalled());+ // Still actionable for a retry.+ expect(+ screen.getByRole("button", { name: "Connect credential" }),+ ).toBeTruthy();+ const logged = errSpy.mock.calls.find((call) =>+ String(call[0]).includes("Failed to send credential response"),+ );+ expect(logged).toBeTruthy();+ expect(typeof logged![1]).toBe("string");+ expect(JSON.stringify(logged)).not.toContain("rt-secret");+ errSpy.mockRestore();+ });++ it("retries the credentials fetch on a later pause after a transient failure (no poisoned cache)", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ credsFail.current = true;+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart("turn-a"));+ streamCalls[0]!.onMessage(credentialFrame({ turn_id: "turn-a" }));+ });+ await waitFor(() =>+ expect(credentialsGets().length).toBeGreaterThanOrEqual(1),+ );+ const afterFailure = credentialsGets().length;+ // A later pause frame must trigger a fresh fetch — caching [] on failure+ // would have left credentialsList non-null and blocked all retries.+ credsFail.current = false;+ await act(async () => {+ streamCalls[0]!.onMessage(credentialFrame({ turn_id: "turn-b" }));+ });+ await waitFor(() =>+ expect(credentialsGets().length).toBeGreaterThan(afterFailure),+ );+ errSpy.mockRestore();+ });++ it("renders no card when the pause resolved to declined (frame never shown)", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ await renderChat();+ await submit("use my saved login");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart("turn-7"));+ streamCalls[0]!.onMessage(terminalDeclinedResponse("turn-7"));+ streamCalls[0]!.resolve();+ });+ expect(screen.queryByText(/Copilot needs to sign in to/)).toBeNull();+ expect(+ screen.queryByRole("button", { name: "Connect credential" }),+ ).toBeNull();+ });++ it("terminal-mode connect/skip never hits the network", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ await renderChat();+ await submit("who am I signing in as?");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart("turn-9"));+ streamCalls[0]!.onMessage(terminalPromptResponse("turn-9"));+ streamCalls[0]!.resolve();+ });+ expect(+ screen.getByText(/Copilot needs to sign in to the site/),+ ).toBeTruthy();+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Skip for now" }));+ });+ expect(credentialResponsePosts()).toHaveLength(0);+ });++ it("clears the pause card on a terminal error — no dead actionable card", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart());+ streamCalls[0]!.onMessage(credentialFrame());+ });+ expect(+ screen.getByRole("button", { name: "Connect credential" }),+ ).toBeTruthy();+ await act(async () => {+ streamCalls[0]!.onMessage(errorFrame());+ streamCalls[0]!.resolve();+ });+ expect(+ screen.queryByRole("button", { name: "Connect credential" }),+ ).toBeNull();+ expect(screen.queryByRole("button", { name: "Skip for now" })).toBeNull();+ });+});++describe("WorkflowCopilotChat — credential card (flag off parity)", () => {+ it("omits supports_credential_pause and renders no card even if a frame arrives", async () => {+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ expect(streamCalls[0]!.body.supports_credential_pause).toBeUndefined();+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart());+ streamCalls[0]!.onMessage(credentialFrame());+ });+ expect(+ screen.queryByRole("button", { name: "Connect credential" }),+ ).toBeNull();+ });+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsxindex f1fe22ff2..00feae3c1 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx@@ -164,7 +164,11 @@ function chatUi(props: ChatProps) {async function renderChat(props: ChatProps = {}) {const view = render(chatUi(props));await waitFor(() =>- expect(screen.getByPlaceholderText(/Message Skyvern Copilot/)).toBeTruthy(),+ expect(+ screen.getByPlaceholderText(+ /Message Skyvern Copilot|Ask Copilot to build/,+ ),+ ).toBeTruthy(),);return view;}diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runLifecycle.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runLifecycle.test.tsxindex ffc21a397..6022ab220 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runLifecycle.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runLifecycle.test.tsx@@ -192,7 +192,11 @@ function makeDockedProps(props: ChatProps = {}): ChatProps {async function renderChat(props: ChatProps = {}) {const view = render(chatUi(props));await waitFor(() =>- expect(screen.getByPlaceholderText(/Message Skyvern Copilot/)).toBeTruthy(),+ expect(+ screen.getByPlaceholderText(+ /Message Skyvern Copilot|Ask Copilot to build/,+ ),+ ).toBeTruthy(),);return view;}diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex a2a33e96d..1a21ea789 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -8,8 +8,15 @@ import {memo,} from "react";import { getClient } from "@/api/AxiosClient";-import { ActionsApiResponse, getReadableActionType } from "@/api/types";+import {+ ActionsApiResponse,+ CredentialApiResponse,+ getReadableActionType,+} from "@/api/types";import { useCredentialGetter } from "@/hooks/useCredentialGetter";+import { CredentialsModal } from "@/routes/credentials/CredentialsModal";+import { CredentialModalTypes } from "@/routes/credentials/useCredentialModalState";+import { getHostname } from "@/util/getHostname";import { useParams } from "react-router-dom";import {ReloadIcon,@@ -49,6 +56,7 @@ import {WorkflowCopilotRunOutcomeUpdate,WorkflowCopilotTurnStartUpdate,WorkflowCopilotWorkflowDraftUpdate,+ WorkflowCopilotCredentialRequiredUpdate,WorkflowCopilotChatSender,WorkflowCopilotChatRequest,WorkflowCopilotChatSummary,@@ -71,6 +79,13 @@ import { ConfirmCard, shouldShowConfirmCard } from "./cards/ConfirmCard";import { DiffCard, shouldShowDiffCard } from "./cards/DiffCard";import { FixCard, shouldShowFixCard } from "./cards/FixCard";import { ReviewGateCard, getReviewGateVerdict } from "./cards/ReviewGateCard";+import {+ CredentialCard,+ type CredentialRequiredFrame,+ type CredentialRequiredReason,+ type CredentialPauseHistorical,+ type MatchingCredential,+} from "./cards/CredentialCard";import {CopilotBlockActionsEvent,EMPTY_NARRATIVE,@@ -377,7 +392,74 @@ type WorkflowCopilotSsePayload =| WorkflowCopilotTurnStartUpdate| WorkflowCopilotDesignStartUpdate| WorkflowCopilotDesignEndUpdate- | WorkflowCopilotWorkflowDraftUpdate;+ | WorkflowCopilotWorkflowDraftUpdate+ | WorkflowCopilotCredentialRequiredUpdate;++// The live pause frame is a structural superset of the card's frame; only+// reason needs narrowing (the card tolerates unknown tokens either way).+function liveFrameToCardFrame(+ frame: WorkflowCopilotCredentialRequiredUpdate,+): CredentialRequiredFrame {+ return { ...frame, reason: frame.reason as CredentialRequiredReason };+}++// Terminal-mode synthetic frame from the sparse narrative_payload signals.+// credentialPause wins over credentialPrompt so a paused-then-resolved turn+// shows one resolved card, not a receipt stacked with a fresh actionable+// prompt (the timeout/dedup case). "declined" → no card was ever shown.+function credentialCardFrameFor(+ turn: TurnNarrativeState,+): CredentialRequiredFrame | null {+ if (turn.credentialPause) {+ if (turn.credentialPause.outcome === "declined") return null;+ return {+ type: "credential_required",+ reason: (turn.credentialPrompt?.reason ??+ "workflow_credential_inputs_unbound") as CredentialRequiredReason,+ };+ }+ if (turn.credentialPrompt) {+ return {+ type: "credential_required",+ reason: turn.credentialPrompt.reason as CredentialRequiredReason,+ };+ }+ return null;+}++function historicalCredentialOutcome(+ turn: TurnNarrativeState,+): CredentialPauseHistorical | undefined {+ const pause = turn.credentialPause;+ if (!pause || pause.outcome === "declined") return undefined;+ return {+ outcome: pause.outcome,+ credentialId: pause.credentialId ?? undefined,+ };+}++type CredentialResolution = CredentialPauseHistorical & { name?: string };++// Append a resolution keyed by turn, capping the map with oldest-eviction like+// the sibling per-turn maps (turnSnapshots/turnOwnedRunIds). delete-then-set+// re-inserts an existing turn as newest so an active turn isn't evicted.+function withCappedResolution(+ prev: Record<string, CredentialResolution>,+ turnId: string,+ value: CredentialResolution,+): Record<string, CredentialResolution> {+ const next = { ...prev };+ delete next[turnId];+ next[turnId] = value;+ const keys = Object.keys(next);+ for (const key of keys.slice(+ 0,+ Math.max(0, keys.length - MAX_TURN_SNAPSHOTS),+ )) {+ delete next[key];+ }+ return next;+}const formatChatTimestamp = (value: string) => {let normalizedValue = value.replace(/\.(\d{3})\d*/, ".$1");@@ -694,6 +776,33 @@ export function WorkflowCopilotChat({[],);const [isLoadingHistory, setIsLoadingHistory] = useState(false);+ // Active mid-build credential pause frame for the in-flight turn. Cleared at+ // turn_start and at every terminal so a dead resume_token can never render.+ const [livePauseFrame, setLivePauseFrame] =+ useState<WorkflowCopilotCredentialRequiredUpdate | null>(null);+ // Local credential-card resolutions keyed by turn_id: live pauses after a+ // successful resume POST, and terminal-mode connect/skip (which never POST).+ // name is captured at connect so the receipt keeps showing it after the turn+ // goes terminal and the live frame (and its matching list) is gone.+ const [credentialResolutions, setCredentialResolutions] = useState<+ Record<string, CredentialResolution>+ >({});+ const [credentialModalOpen, setCredentialModalOpen] = useState(false);+ // Credentials list for matching a live pause against stored credentials.+ // Fetched lazily (only once a pause frame arrives — the only path carrying+ // login_page_urls to match against), so a chat with no pause never fetches.+ const [credentialsList, setCredentialsList] = useState<+ CredentialApiResponse[] | null+ >(null);+ const credentialsFetchInFlight = useRef(false);+ // Routes the add-credential modal's onCredentialCreated back to the card that+ // opened it: a live frame (POST resume) or a terminal turn (local resolve).+ const pendingCredentialConnect = useRef<{+ frame: WorkflowCopilotCredentialRequiredUpdate | null;+ turnId: string;+ } | null>(null);+ // Single-flight guard for the resume POST against a double-click.+ const credentialResponseInFlight = useRef(false);const streamingAbortController = useRef<AbortController | null>(null);// Synchronous in-flight gate. State (isLoading) lags a render behind, so a// rapid double-submit would run a stale closure and start a second stream;@@ -858,6 +967,141 @@ export function WorkflowCopilotChat({workflowPermanentId,],);+ // Fetch the stored credentials once a pause is live. ponytail: page_size 100,+ // no pagination — a >100-credential org may miss a match and fall back to the+ // Connect CTA. Add pagination if that shows up. Setting credentialsList back+ // to null (after a modal create) re-runs this to pick up the new credential.+ useEffect(() => {+ if (+ !copilotUxV1Enabled ||+ !livePauseFrame ||+ credentialsList !== null ||+ credentialsFetchInFlight.current+ ) {+ return;+ }+ credentialsFetchInFlight.current = true;+ void (async () => {+ try {+ const client = await getClient(credentialGetter);+ const res = await client.get<CredentialApiResponse[]>("/credentials", {+ params: { page: 1, page_size: 100 },+ });+ setCredentialsList(Array.isArray(res.data) ? res.data : []);+ } catch (error) {+ // Leave credentialsList null so a later pause frame retries; caching []+ // here would disable matching for the whole mounted session.+ console.error("Failed to load credentials:", error);+ } finally {+ credentialsFetchInFlight.current = false;+ }+ })();+ }, [copilotUxV1Enabled, livePauseFrame, credentialsList, credentialGetter]);+ const liveMatchingCredentials = useMemo<MatchingCredential[]>(() => {+ if (!livePauseFrame) return [];+ const hosts = livePauseFrame.login_page_urls+ .map(getHostname)+ .filter((host): host is string => host !== null);+ if (hosts.length === 0) return [];+ return (credentialsList ?? [])+ .filter((credential) => {+ const host = credential.tested_url+ ? getHostname(credential.tested_url)+ : null;+ return host !== null && hosts.includes(host);+ })+ .map((credential) => ({+ credentialId: credential.credential_id,+ name: credential.name,+ }));+ }, [livePauseFrame, credentialsList]);+ const respondToCredentialPause = useCallback(+ async (+ frame: WorkflowCopilotCredentialRequiredUpdate,+ action: "connected" | "skip",+ credentialId?: string,+ ) => {+ if (credentialResponseInFlight.current) return;+ credentialResponseInFlight.current = true;+ try {+ // Copilot routes live on base_router (no /api/v1 prefix), like cancel.+ const client = await getClient(credentialGetter, "sans-api-v1");+ await client.post("/workflow/copilot/credential-response", {+ turn_id: frame.turn_id,+ workflow_copilot_chat_id: frame.workflow_copilot_chat_id,+ resume_token: frame.resume_token,+ action,+ credential_id: action === "connected" ? credentialId : undefined,+ });+ const name = liveMatchingCredentials.find(+ (candidate) => candidate.credentialId === credentialId,+ )?.name;+ setCredentialResolutions((prev) =>+ withCappedResolution(+ prev,+ frame.turn_id,+ action === "connected"+ ? { outcome: "connected", credentialId, name }+ : { outcome: "skipped" },+ ),+ );+ } catch (error) {+ // Log only the message: the AxiosError serializes config.data, which+ // carries the one-time resume_token, into the console otherwise.+ console.error(+ "Failed to send credential response:",+ error instanceof Error ? error.message : String(error),+ );+ toast({+ title: "Couldn't send your credential response",+ description: "Please try again.",+ variant: "destructive",+ });+ } finally {+ credentialResponseInFlight.current = false;+ }+ },+ [credentialGetter, liveMatchingCredentials],+ );+ // Terminal-mode cards have no resume_token — connect/skip is a local UI morph,+ // no network call.+ const resolveTerminalCredential = useCallback(+ (turnId: string, action: "connected" | "skip", credentialId?: string) => {+ setCredentialResolutions((prev) =>+ withCappedResolution(+ prev,+ turnId,+ action === "connected"+ ? { outcome: "connected", credentialId }+ : { outcome: "skipped" },+ ),+ );+ },+ [],+ );+ const openCredentialModal = useCallback(+ (frame: WorkflowCopilotCredentialRequiredUpdate | null, turnId: string) => {+ pendingCredentialConnect.current = { frame, turnId };+ setCredentialModalOpen(true);+ },+ [],+ );+ const handleCredentialCreated = useCallback(+ (credentialId: string) => {+ const ctx = pendingCredentialConnect.current;+ pendingCredentialConnect.current = null;+ setCredentialModalOpen(false);+ // Re-fetch so the new credential's name resolves in the receipt.+ setCredentialsList(null);+ if (!ctx) return;+ if (ctx.frame) {+ void respondToCredentialPause(ctx.frame, "connected", credentialId);+ } else {+ resolveTerminalCredential(ctx.turnId, "connected", credentialId);+ }+ },+ [respondToCredentialPause, resolveTerminalCredential],+ );// Explore/Draft boundary is unobservable (the LLM writes code with no// frames emitted); after DRAFTING_GAP_MS of silence with no pending block// run, assume Draft has started. Re-arms per narrative update; the reducer@@ -1806,6 +2050,9 @@ export function WorkflowCopilotChat({) => {// Stream completed; a Cancel click after this point should no-op.pendingCancelToken.current = null;+ // Turn is terminal — the in-flight pause card (if any) unmounts with+ // the live bubble; drop its now-dead resume_token too.+ setLivePauseFrame(null);setWorkflowCopilotChatId(response.workflow_copilot_chat_id);// freeze the current narrative state into the AI message@@ -1890,6 +2137,9 @@ export function WorkflowCopilotChat({errorNarrative?: TurnNarrativeState,) => {pendingCancelToken.current = null;+ // A terminal error carries no credentialPause payload, so the dead+ // frame must be cleared explicitly or its card would stay actionable.+ setLivePauseFrame(null);const liveNarrative = errorNarrative ?? narrativeRef.current;const frozenNarrative: TurnNarrativeState | undefined =errorNarrative ??@@ -1945,6 +2195,9 @@ export function WorkflowCopilotChat({fix_origin: fixOrigin,keep_pending_proposal:copilotUxV1Enabled && Boolean(pendingProposalTurnId),+ // Only opt in behind the flag; flag-off omits the field entirely so+ // the request stays byte-identical to legacy.+ ...(copilotUxV1Enabled && { supports_credential_pause: true }),} as WorkflowCopilotChatRequest,(payload) => {switch (payload.type) {@@ -1972,7 +2225,12 @@ export function WorkflowCopilotChat({}maybeFetchRecordedActions(payload);return false;+ case "credential_required":+ setLivePauseFrame(payload);+ return false;case "turn_start": {+ // A new turn can't carry the prior turn's dead resume_token.+ setLivePauseFrame(null);// Move the pre-submit canvas snapshot into the per-turn// map keyed by the BE-assigned turn_id; cap the map so a// long-running chat does not retain every turn's snapshot.@@ -2043,6 +2301,7 @@ export function WorkflowCopilotChat({// A thrown stream never emits a terminal narrative event, so clear the// bubble or its Working/elapsed indicator would tick forever.setNarrative(EMPTY_NARRATIVE);+ setLivePauseFrame(null);} finally {if (streamingAbortController.current === abortController) {streamingAbortController.current = null;@@ -2829,6 +3088,49 @@ export function WorkflowCopilotChat({}/>) : null}+ {(() => {+ if (!copilotUxV1Enabled || turnId === null) return null;+ const credFrame = credentialCardFrameFor(+ message.narrative,+ );+ if (!credFrame) return null;+ // Terminal frames carry no login_page_urls, so there's+ // nothing to match against — the only name we can show is+ // one captured locally when this turn's pause connected.+ const localResolution = credentialResolutions[turnId];+ const receiptName =+ localResolution?.name && localResolution.credentialId+ ? [+ {+ credentialId: localResolution.credentialId,+ name: localResolution.name,+ },+ ]+ : undefined;+ return (+ <CredentialCard+ frame={credFrame}+ mode="terminal"+ matchingCredentials={receiptName}+ resolvedOutcome={+ localResolution ??+ historicalCredentialOutcome(message.narrative)+ }+ onConnect={(credentialId) =>+ credentialId+ ? resolveTerminalCredential(+ turnId,+ "connected",+ credentialId,+ )+ : openCredentialModal(null, turnId)+ }+ onSkip={() =>+ resolveTerminalCredential(turnId, "skip")+ }+ />+ );+ })()}</div>);}@@ -2928,6 +3230,33 @@ export function WorkflowCopilotChat({onBlockSelect={onBlockSelect}uxV1={copilotUxV1Enabled}/>+ {copilotUxV1Enabled &&+ livePauseFrame &&+ livePauseFrame.turn_id === narrative.turnId ? (+ <CredentialCard+ frame={liveFrameToCardFrame(livePauseFrame)}+ mode="inline-pause"+ matchingCredentials={liveMatchingCredentials}+ resolvedOutcome={+ credentialResolutions[livePauseFrame.turn_id]+ }+ onConnect={(credentialId) =>+ credentialId+ ? void respondToCredentialPause(+ livePauseFrame,+ "connected",+ credentialId,+ )+ : openCredentialModal(+ livePauseFrame,+ livePauseFrame.turn_id,+ )+ }+ onSkip={() =>+ void respondToCredentialPause(livePauseFrame, "skip")+ }+ />+ ) : null}</div>)}</div>@@ -3035,22 +3364,23 @@ export function WorkflowCopilotChat({{inputStatusText}</div>) : null}- <div className="flex items-end gap-2">- <SpeechInputButton- isSupported={isSpeechSupported}- isListening={isSpeechListening}- isHearingSpeech={isSpeechHearing}- disabled={inputDisabled}- onToggle={toggleSpeech}- className={- copilotUxV1Enabled && copilotV2Enabled- ? "h-8 w-8 rounded-full border-0 bg-transparent"- : "h-10 w-10 rounded-lg"- }- iconClassName={- copilotUxV1Enabled && copilotV2Enabled ? "h-3.5 w-3.5" : undefined- }- />+ <div+ className={+ copilotUxV1Enabled && copilotV2Enabled+ ? "flex items-end gap-1.5 rounded-lg border border-input bg-slate-elevation2 py-1.5 pl-3 pr-2.5 transition-colors focus-within:border-ring"+ : "flex items-end gap-2"+ }+ >+ {copilotUxV1Enabled && copilotV2Enabled ? null : (+ <SpeechInputButton+ isSupported={isSpeechSupported}+ isListening={isSpeechListening}+ isHearingSpeech={isSpeechHearing}+ disabled={inputDisabled}+ onToggle={toggleSpeech}+ className="h-10 w-10 rounded-lg"+ />+ )}<textarearef={setTextareaRef}placeholder={@@ -3060,7 +3390,9 @@ export function WorkflowCopilotChat({? "Type a message to send next…": isWaitingForLiveBrowser? "Type a prompt to send when ready..."- : "Message Skyvern Copilot, or paste recorded steps…"+ : copilotUxV1Enabled && copilotV2Enabled+ ? "Ask Copilot to build or change your workflow…"+ : "Message Skyvern Copilot, or paste recorded steps…"}value={inputValue}onChange={(e) => setInputValue(e.target.value)}@@ -3068,13 +3400,28 @@ export function WorkflowCopilotChat({onKeyDown={handleKeyPress}disabled={inputDisabled}rows={1}- className="min-h-10 flex-1 resize-none rounded-lg border border-input bg-slate-elevation2 px-3 py-2 text-sm leading-6 text-foreground placeholder:truncate placeholder:text-muted-foreground focus:border-ring focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"+ className={+ copilotUxV1Enabled && copilotV2Enabled+ ? "min-h-10 flex-1 resize-none border-0 bg-transparent py-2 text-sm leading-6 text-foreground placeholder:truncate placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"+ : "min-h-10 flex-1 resize-none rounded-lg border border-input bg-slate-elevation2 px-3 py-2 text-sm leading-6 text-foreground placeholder:truncate placeholder:text-muted-foreground focus:border-ring focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"+ }style={{minHeight: "40px",maxHeight: "150px",overflowY: "hidden",}}/>+ {copilotUxV1Enabled && copilotV2Enabled ? (+ <SpeechInputButton+ isSupported={isSpeechSupported}+ isListening={isSpeechListening}+ isHearingSpeech={isSpeechHearing}+ disabled={inputDisabled}+ onToggle={toggleSpeech}+ className="h-8 w-8 rounded-full border-0 bg-transparent"+ iconClassName="h-3.5 w-3.5"+ />+ ) : null}{copilotUxV1Enabled && copilotV2Enabled ? (<TooltipProvider><ControlTooltip@@ -3252,6 +3599,21 @@ export function WorkflowCopilotChat({/></>)}+ {/* Mounted only while open: CredentialsModal pulls react-query at mount,+ so keeping it mounted-but-closed would tax every render for nothing. */}+ {copilotUxV1Enabled && credentialModalOpen ? (+ <CredentialsModal+ isOpen+ // A sign-in pause always needs a password credential; force the form+ // so a lingering ?type=credit-card/secret param can't open the wrong one.+ overrideType={CredentialModalTypes.PASSWORD}+ onOpenChange={(open) => {+ setCredentialModalOpen(open);+ if (!open) pendingCredentialConnect.current = null;+ }}+ onCredentialCreated={handleCredentialCreated}+ />+ ) : null}</div>);diff --git a/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.test.ts b/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.test.tsindex 00e87c8b1..7b61e0fbd 100644--- a/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.test.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.test.ts@@ -102,6 +102,84 @@ describe("derivePhases — bucket split", () => {});});+describe("derivePhases — condenses each phase's entries (SKY-11971)", () => {+ it("folds a failed-then-retried tool_call/tool_result pair in the explore bucket into one row", () => {+ const t = turn({+ designActivity: [+ entry({+ id: "tc-1",+ kind: "tool_call",+ toolName: "evaluate",+ }),+ entry({+ id: "tr-1",+ kind: "tool_result",+ toolName: "evaluate",+ success: false,+ }),+ entry({+ id: "tc-2",+ kind: "tool_call",+ toolName: "evaluate",+ }),+ entry({+ id: "tr-2",+ kind: "tool_result",+ toolName: "evaluate",+ success: true,+ }),+ ],+ });+ const rows = derivePhases(t);+ const exploreEntries = phase(rows, "explore").entries;+ expect(exploreEntries).toHaveLength(1);+ expect(exploreEntries[0]).toMatchObject({+ id: "tr-2",+ success: true,+ attempts: 2,+ });+ });++ it("REGRESSION PIN: the explore 'N steps' stub matches the condensed row count, not the raw event count (Claude catch)", () => {+ const t = turn({+ terminal: "response",+ designActivity: [+ entry({ id: "tc-1", kind: "tool_call", toolName: "evaluate" }),+ entry({+ id: "tr-1",+ kind: "tool_result",+ toolName: "evaluate",+ success: false,+ }),+ entry({ id: "tc-2", kind: "tool_call", toolName: "evaluate" }),+ entry({+ id: "tr-2",+ kind: "tool_result",+ toolName: "evaluate",+ success: true,+ }),+ ],+ });+ const rows = derivePhases(t);+ expect(phase(rows, "explore").entries).toHaveLength(1);+ expect(phase(rows, "explore").stub).toBe("1 step");+ });++ it("leaves the earlier bucket-routing test's un-paired hand-rolled ids unaffected", () => {+ // Regression pin: short test ids ("1"/"2"/"3"/"4") don't collide with+ // the tc-/tr- correlation convention, so condensing is a no-op there.+ const t = turn({+ designActivity: [+ entry({ id: "1", kind: "tool_call", toolName: "navigate_browser" }),+ entry({ id: "2", kind: "tool_call", toolName: "update_workflow" }),+ ],+ designEnded: true,+ });+ const rows = derivePhases(t);+ expect(phase(rows, "draft").entries.map((e) => e.id)).toEqual(["2"]);+ });+});+describe("derivePhases — live progression", () => {it("explore is active before any authoring activity", () => {const t = turn({diff --git a/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.ts b/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.tsindex c06634fa0..12cc62ef1 100644--- a/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.ts@@ -10,9 +10,11 @@ import {BlockState,RUN_TOOLS,TurnNarrativeState,+ condenseActivityEntries,formatElapsed,latestBlocksByLabel,parseUtcIsoMs,+ toolCallIdOf,} from "./narrativeState";export { AUTHORING_TOOLS, RUN_TOOLS };@@ -61,9 +63,9 @@ function hasPendingToolCall(designActivity: ActivityEntry[]): boolean {const pending = new Set<string>();for (const entry of designActivity) {if (entry.kind === "tool_call") {- pending.add(entry.id.slice(3)); // "tc-<tool_call_id>"+ pending.add(toolCallIdOf(entry) ?? "");} else if (entry.kind === "tool_result") {- pending.delete(entry.id.slice(3)); // "tr-<tool_call_id>"+ pending.delete(toolCallIdOf(entry) ?? "");}}return pending.size > 0;@@ -266,13 +268,26 @@ export function derivePhases(turn: TurnNarrativeState): PhaseRowModel[] {return "done";}+ // Condensed for display only — stubFor/redrafting/activitySeq above all+ // read the raw explore/draftEntries/test closures, not this map.+ const entriesFor: Record<CopilotPhaseId, ActivityEntry[]> = {+ explore: condenseActivityEntries(explore),+ draft: condenseActivityEntries(draftEntries),+ test: condenseActivityEntries(test),+ done: [],+ };+function stubFor(id: CopilotPhaseId, status: PhaseStatus): string | null {if (id === "done") return null;if (id === "explore") {if (status !== "done" && status !== "fail" && status !== "stopped") {return null;}- const n = explore.filter((e) => e.kind === "tool_call").length;+ // Condensed count, not raw: a folded retry now renders as one row,+ // so the stub must match what expanding the row actually shows.+ const n = entriesFor.explore.filter(+ (e) => e.toolName !== undefined,+ ).length;return n > 0 ? pluralize(n, "step") : null;}if (id === "draft") {@@ -282,6 +297,10 @@ export function derivePhases(turn: TurnNarrativeState): PhaseRowModel[] {if (!turn.draft) return null;const base = pluralize(turn.draft.blockCount, "block");if (!isTerminal) return base;+ // Intentionally a raw authoring-attempt count, not a rendered-row+ // count: it spans update_workflow (draft bucket) AND+ // update_and_run_blocks (test bucket), so there's no single+ // condensed bucket to count against the way the explore stub does.const drafts = countAuthoringToolCalls(turn.designActivity);return drafts >= 2 ? `${base} · ${drafts} drafts` : base;}@@ -303,13 +322,6 @@ export function derivePhases(turn: TurnNarrativeState): PhaseRowModel[] {: pluralize(latestBlocks.length, "block");}- const entriesFor: Record<CopilotPhaseId, ActivityEntry[]> = {- explore,- draft: draftEntries,- test,- done: [],- };-return (["explore", "draft", "test", "done"] as const).map((id) => {const status = statusFor(id);return {diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.credentialPause.test.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.credentialPause.test.tsnew file mode 100644index 000000000..04263b06f--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.credentialPause.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it } from "vitest";++import {+ applyNarrativeEvent,+ EMPTY_NARRATIVE,+ hydrateNarrativeFromPayload,+ parseCredentialPause,+ parseCredentialPrompt,+} from "./narrativeState";+import type {+ WorkflowCopilotStreamErrorUpdate,+ WorkflowCopilotStreamResponseUpdate,+} from "./workflowCopilotTypes";++const basePayload = (+ overrides: Record<string, unknown> = {},+): Record<string, unknown> => ({+ turnId: "turn-1",+ turnIndex: 0,+ mode: "build",+ responseType: "REPLY",+ terminal: "response",+ startedAt: "2026-07-13T00:00:00Z",+ endedAt: "2026-07-13T00:00:05Z",+ ...overrides,+});++describe("parseCredentialPrompt", () => {+ it("keeps any non-empty reason string (card tolerates unknown tokens)", () => {+ expect(parseCredentialPrompt({ reason: "raw_secret" })).toEqual({+ reason: "raw_secret",+ });+ expect(parseCredentialPrompt({ reason: "a_future_reason" })).toEqual({+ reason: "a_future_reason",+ });+ });++ it("rejects malformed shapes", () => {+ expect(parseCredentialPrompt(null)).toBeNull();+ expect(parseCredentialPrompt("raw_secret")).toBeNull();+ expect(parseCredentialPrompt({})).toBeNull();+ expect(parseCredentialPrompt({ reason: "" })).toBeNull();+ expect(parseCredentialPrompt({ reason: 3 })).toBeNull();+ });+});++describe("parseCredentialPause", () => {+ it("accepts the four real outcomes and defaults credentialId to null", () => {+ expect(+ parseCredentialPause({ outcome: "connected", credentialId: "c1" }),+ ).toEqual({ outcome: "connected", credentialId: "c1" });+ expect(parseCredentialPause({ outcome: "skipped" })).toEqual({+ outcome: "skipped",+ credentialId: null,+ });+ expect(parseCredentialPause({ outcome: "timeout" })).toEqual({+ outcome: "timeout",+ credentialId: null,+ });+ expect(parseCredentialPause({ outcome: "declined" })).toEqual({+ outcome: "declined",+ credentialId: null,+ });+ });++ it("rejects unknown or malformed outcomes so the renderer can't crash", () => {+ expect(parseCredentialPause(null)).toBeNull();+ expect(parseCredentialPause({ outcome: "exploded" })).toBeNull();+ expect(parseCredentialPause({})).toBeNull();+ });+});++describe("hydrateNarrativeFromPayload — credential signals", () => {+ it("defaults both signals to null when absent", () => {+ expect(EMPTY_NARRATIVE.credentialPrompt).toBeNull();+ expect(EMPTY_NARRATIVE.credentialPause).toBeNull();+ const hydrated = hydrateNarrativeFromPayload(basePayload());+ expect(hydrated?.credentialPrompt).toBeNull();+ expect(hydrated?.credentialPause).toBeNull();+ });++ it("hydrates credentialPrompt from the narrative payload", () => {+ const hydrated = hydrateNarrativeFromPayload(+ basePayload({+ credentialPrompt: { reason: "credential_name_unresolved" },+ }),+ );+ expect(hydrated?.credentialPrompt).toEqual({+ reason: "credential_name_unresolved",+ });+ });++ it("hydrates a resolved credentialPause", () => {+ const hydrated = hydrateNarrativeFromPayload(+ basePayload({+ credentialPause: { outcome: "connected", credentialId: "cred-9" },+ }),+ );+ expect(hydrated?.credentialPause).toEqual({+ outcome: "connected",+ credentialId: "cred-9",+ });+ });++ it("carries both signals through the terminal response reducer (reload path)", () => {+ const response: WorkflowCopilotStreamResponseUpdate = {+ type: "response",+ workflow_copilot_chat_id: "chat-1",+ message: "Connect a credential to continue.",+ updated_workflow: null,+ response_time: "2026-07-13T00:00:05Z",+ proposal_disposition: "no_proposal",+ turn_id: "turn-1",+ narrative_payload: basePayload({+ credentialPrompt: { reason: "workflow_credential_inputs_unbound" },+ credentialPause: { outcome: "timeout", credentialId: null },+ }),+ } as WorkflowCopilotStreamResponseUpdate;+ const next = applyNarrativeEvent(EMPTY_NARRATIVE, response);+ expect(next.credentialPrompt).toEqual({+ reason: "workflow_credential_inputs_unbound",+ });+ expect(next.credentialPause).toEqual({+ outcome: "timeout",+ credentialId: null,+ });+ });++ it("leaves the signals null on a terminal error (no credential payload)", () => {+ const error: WorkflowCopilotStreamErrorUpdate = {+ type: "error",+ error: "Something went wrong.",+ turn_id: "turn-1",+ };+ const live = hydrateNarrativeFromPayload(basePayload({ terminal: null }))!;+ const next = applyNarrativeEvent(live, error);+ expect(next.credentialPrompt).toBeNull();+ expect(next.credentialPause).toBeNull();+ });+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.tsindex 857b05647..4a7cd09c3 100644--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts@@ -127,6 +127,9 @@ export interface ActivityEntry {success?: boolean;// Stable per-event id used as React key.id: string;+ // Consecutive same-tool retries folded into this row by+ // condenseActivityEntries. Unset outside that transform.+ attempts?: number;}// Closed vocabulary of the backend TurnOutcome.response_kind enum. Unknown@@ -200,6 +203,15 @@ export interface TurnNarrativeState {displayReason: string | null;activitySeqAtVerdict: number;} | null;+ // Terminal-mode credential ask, from the credentialPrompt narrative signal.+ // reason is kept as a raw string — the card tolerates unknown tokens.+ credentialPrompt: { reason: string } | null;+ // Resolved pause outcome, from the credentialPause narrative signal.+ // "declined" means the pause engaged but never sent a frame, so no card.+ credentialPause: {+ outcome: "connected" | "skipped" | "timeout" | "declined";+ credentialId: string | null;+ } | null;}export const EMPTY_NARRATIVE: TurnNarrativeState = Object.freeze({@@ -227,6 +239,8 @@ export const EMPTY_NARRATIVE: TurnNarrativeState = Object.freeze({authoringCount: 0,activitySeq: 0,lastRunOutcome: null,+ credentialPrompt: null,+ credentialPause: null,}) as TurnNarrativeState;// Caps to keep long-running narrations from unbounded growth (and to keep@@ -256,6 +270,34 @@ export function parseResponseKind(value: unknown): TurnResponseKind | null {: null;}+export function parseCredentialPrompt(+ value: unknown,+): TurnNarrativeState["credentialPrompt"] {+ if (!value || typeof value !== "object") return null;+ const reason = (value as Record<string, unknown>).reason;+ return typeof reason === "string" && reason.length > 0 ? { reason } : null;+}++export function parseCredentialPause(+ value: unknown,+): TurnNarrativeState["credentialPause"] {+ if (!value || typeof value !== "object") return null;+ const o = value as Record<string, unknown>;+ const outcome = o.outcome;+ if (+ outcome !== "connected" &&+ outcome !== "skipped" &&+ outcome !== "timeout" &&+ outcome !== "declined"+ ) {+ return null;+ }+ return {+ outcome,+ credentialId: typeof o.credentialId === "string" ? o.credentialId : null,+ };+}+// Tool calls that write the workflow definition. update_workflow only// validates/saves the draft; update_and_run_blocks also runs it, so it's// the one AUTHORING_TOOLS member that's also a RUN_TOOLS member (its@@ -345,6 +387,129 @@ function buildActivityFromNarration(};}+// Shared "tc-<tool_call_id>" / "tr-<tool_call_id>" id-parsing convention —+// also used by copilotPhases.ts's hasPendingToolCall.+export function toolCallIdOf(entry: ActivityEntry): string | undefined {+ return entry.kind === "tool_call" || entry.kind === "tool_result"+ ? entry.id.slice(3)+ : undefined;+}++// Folds each tool_call/tool_result pair into one row (pending while+// unresolved, replaced by its result once it lands) so a single tool+// invocation never renders as two chatter lines, then folds a run of+// same-tool retries into the last attempt's row with an attempt count —+// only the terminal outcome of a retry chain ever shows red, intermediate+// failed attempts stay quiet.+//+// Chronology, not just row count: a call is only replaced IN PLACE when+// nothing else streamed while it was pending. If a narration arrived first+// (the narrator can emit mid-flight progress on a slow call), replacing in+// place would render the result ahead of a narration that genuinely came+// earlier — so the stale pending row is dropped instead and the result+// lands at its own later, true position.+//+// The retry fold below deliberately ignores narration rows entirely for+// adjacency (tracks the last TOOL row, not literal array adjacency).+// Array position alone can't reliably tell "narration mid-flight during+// this attempt" from "narration genuinely between two attempts" once a+// retry's own narration is involved — a mid-flight narration during+// attempt 2 lands in the exact same ordered position as one that arrived+// between attempt 1 and attempt 2. Since there's no per-entry signal to+// disambiguate the two, narration never breaks a retry fold, full stop.+// Folding itself follows the same drop-and-reinsert rule as pairing above:+// the earlier attempt's row is removed rather than overwritten in place,+// so a narration that streamed before the later attempt's result still+// reads as arriving before it, not after.+//+// Known tradeoff: toolName is the only correlation signal available here+// (no argument/target identity on the wire), so two independent same-tool+// calls where only the first fails will also fold into one falsely-labeled+// "retry" row. Accepted for this content-classification pass.+//+// A tool without a dedicated backend summary falls back to a bare "OK"+// (summarize_tool_result in output_utils.py). That used to sit right below+// its own "<tool name> · calling…" row, so the tool name was still visible+// above it; condensing removes that row, leaving an unlabeled "OK" with no+// context. Substitute the humanized tool name only for that exact literal+// — a real backend summary always passes through untouched.+const UNMAPPED_TOOL_RESULT_FALLBACK = "OK";++function withHumanizedFallback(entry: ActivityEntry): ActivityEntry {+ if (+ entry.kind !== "tool_result" ||+ entry.text !== UNMAPPED_TOOL_RESULT_FALLBACK+ ) {+ return entry;+ }+ return {+ ...entry,+ text: entry.displayLabel ?? toolActivityDisplayLabel(entry.toolName),+ };+}++export function condenseActivityEntries(+ entries: ActivityEntry[],+): ActivityEntry[] {+ const callIndexById = new Map<string, number>();+ const paired: (ActivityEntry | null)[] = [];+ for (const entry of entries) {+ if (entry.kind === "tool_call") {+ const id = toolCallIdOf(entry);+ const idx = paired.push(entry) - 1;+ if (id !== undefined) callIndexById.set(id, idx);+ continue;+ }+ if (entry.kind === "tool_result") {+ const id = toolCallIdOf(entry);+ const idx = id !== undefined ? callIndexById.get(id) : undefined;+ if (idx !== undefined) {+ callIndexById.delete(id!);+ if (idx === paired.length - 1) {+ paired[idx] = entry;+ } else {+ paired[idx] = null;+ paired.push(entry);+ }+ } else {+ // Its tool_call was evicted past the activity cap — keep the+ // result visible rather than silently dropping it.+ paired.push(entry);+ }+ continue;+ }+ paired.push(entry);+ }+ const ordered = paired.filter((e): e is ActivityEntry => e !== null);++ const condensed: (ActivityEntry | null)[] = [];+ let lastToolIdx = -1;+ for (const entry of ordered) {+ const prevTool = lastToolIdx >= 0 ? condensed[lastToolIdx] : undefined;+ if (+ prevTool &&+ entry.toolName !== undefined &&+ prevTool.toolName === entry.toolName &&+ prevTool.success === false+ ) {+ condensed[lastToolIdx] = null;+ lastToolIdx =+ condensed.push({+ ...entry,+ attempts: (prevTool.attempts ?? 1) + 1,+ }) - 1;+ continue;+ }+ const idx = condensed.push(entry) - 1;+ if (entry.toolName !== undefined) {+ lastToolIdx = idx;+ }+ }+ return condensed+ .filter((e): e is ActivityEntry => e !== null)+ .map(withHumanizedFallback);+}+function appendCapped<T>(arr: T[], entry: T, cap: number): T[] {const next = [...arr, entry];return next.length > cap ? next.slice(next.length - cap) : next;@@ -944,6 +1109,8 @@ export function hydrateNarrativeFromPayload(: null,endedAt:typeof payload.endedAt === "string" ? (payload.endedAt as string) : null,+ credentialPrompt: parseCredentialPrompt(payload.credentialPrompt),+ credentialPause: parseCredentialPause(payload.credentialPause),};}diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.tsindex 467fc0bd4..10aaa797c 100644--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts@@ -45,6 +45,9 @@ export interface WorkflowCopilotChatRequest {target_block_label?: string | null;fix_origin?: boolean;keep_pending_proposal?: boolean;+ // Opt-in: only clients that can render the credential_required frame set+ // this, so the backend never pauses a turn a client would silently drop.+ supports_credential_pause?: boolean;}export interface WorkflowCopilotCancelRequest {@@ -107,7 +110,8 @@ export type WorkflowCopilotStreamMessageType =| "turn_start"| "design_start"| "design_end"- | "workflow_draft";+ | "workflow_draft"+ | "credential_required";export interface WorkflowCopilotProcessingUpdate {type: "processing_update";@@ -174,6 +178,23 @@ export interface WorkflowCopilotWorkflowDraftUpdate {workflow?: WorkflowApiResponse | null;}+// Mid-build pause frame: the turn stays open (SSE alive) while the client+// surfaces a credential card. reason stays a raw string here — CredentialCard+// tolerates unknown reason tokens, so a newer backend can't break the wiring.+export interface WorkflowCopilotCredentialRequiredUpdate {+ type: "credential_required";+ turn_id: string;+ workflow_copilot_chat_id: string;+ resume_token: string;+ reason: string;+ message: string;+ login_page_urls: string[];+ credential_refs: string[];+ timeout_seconds: number;+ expires_at: string;+ timestamp: string;+}+export interface WorkflowCopilotToolCallUpdate {type: "tool_call";tool_name: string;diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/ScriptDiffViewer.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/ScriptDiffViewer.tsxindex 427078417..656b5ed46 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/ScriptDiffViewer.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/ScriptDiffViewer.tsx@@ -4,6 +4,8 @@ import { EditorState } from "@codemirror/state";import { python } from "@codemirror/lang-python";import { unifiedMergeView } from "@codemirror/merge";import { tokyoNightStorm } from "@uiw/codemirror-theme-tokyo-night-storm";+import { tokyoNightDay } from "@uiw/codemirror-theme-tokyo-night-day";+import { useThemeAsDarkOrLight } from "@/components/useThemeAsDarkOrLight";function ScriptDiffViewer({original,@@ -14,6 +16,7 @@ function ScriptDiffViewer({}) {const containerRef = useRef<HTMLDivElement>(null);const viewRef = useRef<EditorView | null>(null);+ const themeMode = useThemeAsDarkOrLight();useEffect(() => {if (!containerRef.current) return;@@ -32,7 +35,7 @@ function ScriptDiffViewer({EditorState.readOnly.of(true),lineNumbers(),python(),- tokyoNightStorm,+ themeMode === "dark" ? tokyoNightStorm : tokyoNightDay,unifiedMergeView({original,highlightChanges: true,@@ -54,7 +57,7 @@ function ScriptDiffViewer({view.destroy();viewRef.current = null;};- }, [original, modified]);+ }, [original, modified, themeMode]);return <div ref={containerRef} />;}diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.pyindex 282b0cadb..7502a54d3 100644--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py@@ -81,7 +81,15 @@ _CREDENTIAL_FIELD_ACCESS_RE = re.compile(r"\b(?P<parameter>[A-Za-z_][A-Za-z0-9_]*)\.(?:(?P<field>username|password|totp)\b|(?P<otp_method>otp)\s*\()")_CODE_SUBMIT_ACTION_RE = re.compile(r"\.(?:click|press)\s*\(")-_SCOUT_SUBMIT_TOOL_NAMES = frozenset({"click", "press_key"})+++def _is_submit_interaction(interaction: Mapping[str, Any]) -> bool:+ """A submit is a click, or an Enter keypress; other keys (Tab between fields) are not submits, so+ both the synthesis submit boundary and the persist-time credential-scout gate share one definition."""+ tool_name = str(interaction.get("tool_name") or "").strip()+ if tool_name == "click":+ return True+ return tool_name == "press_key" and str(interaction.get("key") or "").strip() == "Enter"class CredentialFieldAccess(NamedTuple):@@ -127,7 +135,7 @@ def first_matched_post_fill_submit_index(for index, interaction in enumerate(trajectory):if index <= latest_fill_index:continue- if str(interaction.get("tool_name") or "").strip() not in _SCOUT_SUBMIT_TOOL_NAMES:+ if not _is_submit_interaction(interaction):continuesource_url = str(interaction.get("source_url") or "").strip()if matched_source_urls and source_url not in matched_source_urls:@@ -819,6 +827,7 @@ def _locator_expr(selector = str(interaction.get("selector") or "").strip()role = str(interaction.get("role") or "").strip()name = str(interaction.get("accessible_name") or "").strip()+ scout_ambiguous = bool(interaction.get("ambiguous"))templated = _maybe_input_templated_locator(interaction, diagnostics=diagnostics, trajectory_index=trajectory_index)if templated is not None:@@ -838,7 +847,7 @@ def _locator_expr(return ""parsed_strict = _parse_role_name(selector)ambiguous_role = parsed_strict is not None and not parsed_strict[1]- if ambiguous_role or _is_bare_ambiguous_selector(selector):+ if ambiguous_role or scout_ambiguous or _is_bare_ambiguous_selector(selector):if role and name:expr = _get_by_role_expr_strict(role, name)if diagnostics is not None:@@ -895,6 +904,20 @@ def _locator_expr(if _is_positional_selector(selector):notes.append(f"low-confidence locator: positional selector {selector!r} with no role/name to anchor on")return f"page.locator({_py_str(selector)})"+ if scout_ambiguous and role and name:+ return _get_by_role_expr(role, name)+ if scout_ambiguous:+ notes.append(f"disambiguated a scout-ambiguous {selector!r} selector to .first from scout document order")+ if diagnostics is not None:+ diagnostics.locator_provenance.append(+ {+ "trajectory_index": trajectory_index if trajectory_index is not None else -1,+ "selector": selector,+ "emitted_literal": selector,+ "source": "first_fallback",+ }+ )+ return f"page.locator({_py_str(selector)}).first"if _is_bare_ambiguous_selector(selector):if role and name:return _get_by_role_expr(role, name)@@ -1138,7 +1161,7 @@ def _post_auth_resume_locator(trajectory: Sequence[Mapping[str, Any]], *, strictsubmit_index = -1for index in range(last_credential_index + 1, len(trajectory)):- if str(trajectory[index].get("tool_name") or "") == "click":+ if _is_submit_interaction(trajectory[index]):submit_index = indexbreakif submit_index < 0:@@ -1271,6 +1294,7 @@ def synthesize_code_block(entry_replay_condition_active = Falseentry_replay_start_index = 0entry_post_auth_resume_index = 0+ login_only_presence_guard_active = Falsefor index, interaction in enumerate(trajectory):candidate = str(interaction.get("source_url") or "").strip()if candidate:@@ -1339,6 +1363,22 @@ def synthesize_code_block(entry_recovery_clicks.append((recovery_index, recovery_locator))if entry_recovery_clicks:notes.append("entry fallback replays a generic opener only when the durable target stays hidden")+ login_only_presence_guard_active = bool(+ entry_target+ and not entry_replay_condition_active+ and not entry_post_auth_resume_index+ and not entry_replay_start_index+ and not entry_recovery_clicks+ and any(+ str(interaction.get("tool_name") or "") == CREDENTIAL_FILL_TOOL_NAME+ and str(interaction.get("credential_field") or "").strip() in _CREDENTIAL_FIELDS+ for interaction in entry_trajectory+ )+ )+ if login_only_presence_guard_active:+ notes.append(+ "login rung fills only when the credential form is present, so an authenticated replay skips it"+ )line_start = len(lines) + 1if entry_target:if entry_replay_condition_active:@@ -1402,7 +1442,7 @@ def synthesize_code_block(lane="entry_recovery",)lines.append(f'{_INDENT * recovery_indent}await {_ENTRY_TARGET_VAR}.wait_for(state="visible")')- else:+ elif not login_only_presence_guard_active:lines.append(f'{_INDENT * post_goto_indent}await {_ENTRY_TARGET_VAR}.wait_for(state="visible")')else:lines.append(@@ -1417,6 +1457,8 @@ def synthesize_code_block(elif entry_post_auth_resume_index:lines.append(f"{_INDENT}if not {_ENTRY_RESUME_AFTER_AUTH_VAR}:")lines.append(f"{_INDENT * 2}pass")+ if login_only_presence_guard_active:+ lines.append(f"{_INDENT}if await {_ENTRY_TARGET_VAR}.count() == 1:")append_step(f"Open {entry_url}", "goto_url", line_start)emitted = 0@@ -1430,6 +1472,8 @@ def synthesize_code_block(return _INDENT * 2if entry_post_auth_resume_index and trajectory_index < entry_post_auth_resume_index:return _INDENT * 2+ if login_only_presence_guard_active:+ return _INDENT * 2return _INDENTfor trajectory_index, interaction in enumerate(trajectory):@@ -1635,6 +1679,9 @@ def synthesize_code_block():lines.append(f"{_INDENT * 2}pass")+ if login_only_presence_guard_active and (emitted - len(deferred_readonly_assertions)) == 0:+ lines.append(f"{_INDENT * 2}pass")+if deferred_readonly_assertions:deferred_base = _INDENTif entry_replay_condition_active:diff --git a/skyvern/forge/sdk/copilot/composition_browser_expressions.py b/skyvern/forge/sdk/copilot/composition_browser_expressions.pyindex 4dc714420..208dcab73 100644--- a/skyvern/forge/sdk/copilot/composition_browser_expressions.py+++ b/skyvern/forge/sdk/copilot/composition_browser_expressions.py@@ -46,61 +46,123 @@ COMPOSITION_STRIPPED_HTML_EXPRESSION = ()+_JS_TEXT_HELPER = "const text = (v) => String(v == null ? '' : v).replace(/\\s+/g, ' ').trim();"++_JS_IS_EDITABLE_HELPER = (+ "const isEditable = (node) => {"+ " const tag = (node.tagName || '').toLowerCase();"+ " if (tag === 'input' || tag === 'textarea' || tag === 'select') return true;"+ " return node.isContentEditable === true;"+ "};"+)++_JS_IMPLICIT_ROLE_HELPER = (+ "const implicitRole = (node) => {"+ " const tag = (node.tagName || '').toLowerCase();"+ " const type = (node.getAttribute('type') || '').toLowerCase();"+ " if (tag === 'a' && node.hasAttribute('href')) return 'link';"+ " if (tag === 'button') return 'button';"+ " if (tag === 'select') return 'combobox';"+ " if (tag === 'textarea') return 'textbox';"+ " if (tag === 'input') {"+ " if (['button', 'submit', 'reset'].includes(type)) return 'button';"+ " if (type === 'checkbox') return 'checkbox';"+ " if (type === 'radio') return 'radio';"+ " if (['text', 'search', 'email', 'tel', 'url', 'password', ''].includes(type)) return 'textbox';"+ " }"+ " if (/^h[1-6]$/.test(tag)) return 'heading';"+ " return '';"+ "};"+)++# ARIA roles whose accessible name is computed from the element's own text content (ARIA name-from-content).+# Editable roles (textbox/combobox/searchbox/spinbutton/listbox) are deliberately absent so a typed-into+# control never leaks its value as an accessible name.+_JS_NAME_FROM_CONTENT_ROLES = (+ "const nameFromContentRoles = new Set(["+ "'button', 'link', 'checkbox', 'radio', 'heading', 'tab', 'menuitem', "+ "'menuitemcheckbox', 'menuitemradio', 'option', 'switch', 'treeitem', "+ "'cell', 'gridcell', 'columnheader', 'rowheader', 'row', 'tooltip'"+ "]);"+)++_JS_ACCESSIBLE_NAME_HELPER = (+ "const accessibleName = (node, role) => {"+ " const aria = text(node.getAttribute('aria-label'));"+ " if (aria) return aria;"+ " const labelledby = node.getAttribute('aria-labelledby');"+ " if (labelledby) {"+ " const parts = labelledby.split(/\\s+/).map((id) => {"+ " const ref = document.getElementById(id);"+ " return ref ? text(ref.textContent) : '';"+ " }).filter(Boolean);"+ " if (parts.length) return text(parts.join(' '));"+ " }"+ " const id = node.getAttribute('id');"+ " if (id) {"+ " let lab = null;"+ " try { lab = document.querySelector('label[for=\"' + (window.CSS && CSS.escape ? CSS.escape(id) : id) + '\"]'); } catch (e) { lab = null; }"+ " if (lab) { const t = text(lab.textContent); if (t) return t; }"+ " }"+ " const parentLabel = node.closest ? node.closest('label') : null;"+ " if (parentLabel) { const t = text(parentLabel.textContent); if (t) return t; }"+ " const title = text(node.getAttribute('title'));"+ " if (title) return title;"+ " const placeholder = text(node.getAttribute('placeholder'));"+ " if (placeholder) return placeholder;"+ " if (role && nameFromContentRoles.has(role) && !isEditable(node)) {"+ " const content = text(node.textContent);"+ " if (content) return content;"+ " }"+ " return '';"+ "};"+)++# Given a CSS selector, return the element's ARIA role and accessible name so the code-block-# synthesizer has a get_by_role fallback anchor for a positional/unstable captured selector. The-# name is read only from true label sources, never the element's own textContent/value.+# synthesizer has a get_by_role fallback anchor for a positional/unstable captured selector. The name+# follows the ARIA algorithm: label sources first, then name-from-content for content-named roles only.def scout_accessible_role_name_expression(css_selector: str) -> str:sel = json.dumps(css_selector)return ("(() => {"f" const el = document.querySelector({sel});"" if (!el) return null;"- " const text = (v) => String(v == null ? '' : v).replace(/\\s+/g, ' ').trim();"- " const implicitRole = (node) => {"- " const tag = (node.tagName || '').toLowerCase();"- " const type = (node.getAttribute('type') || '').toLowerCase();"- " if (tag === 'a' && node.hasAttribute('href')) return 'link';"- " if (tag === 'button') return 'button';"- " if (tag === 'select') return 'combobox';"- " if (tag === 'textarea') return 'textbox';"- " if (tag === 'input') {"- " if (['button', 'submit', 'reset'].includes(type)) return 'button';"- " if (type === 'checkbox') return 'checkbox';"- " if (type === 'radio') return 'radio';"- " if (['text', 'search', 'email', 'tel', 'url', 'password', ''].includes(type)) return 'textbox';"- " }"- " if (/^h[1-6]$/.test(tag)) return 'heading';"- " return '';"- " };"- " const accessibleName = (node) => {"- " const aria = text(node.getAttribute('aria-label'));"- " if (aria) return aria;"- " const labelledby = node.getAttribute('aria-labelledby');"- " if (labelledby) {"- " const parts = labelledby.split(/\\s+/).map((id) => {"- " const ref = document.getElementById(id);"- " return ref ? text(ref.textContent) : '';"- " }).filter(Boolean);"- " if (parts.length) return text(parts.join(' '));"- " }"- " const id = node.getAttribute('id');"- " if (id) {"- " let lab = null;"- " try { lab = document.querySelector('label[for=\"' + (window.CSS && CSS.escape ? CSS.escape(id) : id) + '\"]'); } catch (e) { lab = null; }"- " if (lab) { const t = text(lab.textContent); if (t) return t; }"- " }"- " const parentLabel = node.closest ? node.closest('label') : null;"- " if (parentLabel) { const t = text(parentLabel.textContent); if (t) return t; }"- # textContent/value are never name sources: for a typed-into textbox/contenteditable- # they would leak the raw typed value as accessible_name.- " const title = text(node.getAttribute('title'));"- " if (title) return title;"- " const placeholder = text(node.getAttribute('placeholder'));"- " if (placeholder) return placeholder;"- " return '';"- " };"+ f" {_JS_TEXT_HELPER}"+ f" {_JS_IS_EDITABLE_HELPER}"+ f" {_JS_IMPLICIT_ROLE_HELPER}"+ f" {_JS_NAME_FROM_CONTENT_ROLES}"+ f" {_JS_ACCESSIBLE_NAME_HELPER}"" const role = text(el.getAttribute('role')) || implicitRole(el);"- " return { role: role, accessible_name: accessibleName(el) };"+ " return { role: role, accessible_name: accessibleName(el, role) };"+ "})()"+ )+++# Count elements whose computed ARIA role and accessible name exactly match, so a scout-ambiguous+# selector's get_by_role(role, name, exact=True) re-anchor is only trusted when it resolves uniquely.+def role_name_match_count_expression(role: str, name: str) -> str:+ target_role = json.dumps(role)+ target_name = json.dumps(name)+ return (+ "(() => {"+ " try {"+ f" {_JS_TEXT_HELPER}"+ f" {_JS_IS_EDITABLE_HELPER}"+ f" {_JS_IMPLICIT_ROLE_HELPER}"+ f" {_JS_NAME_FROM_CONTENT_ROLES}"+ f" {_JS_ACCESSIBLE_NAME_HELPER}"+ f" const targetRole = {target_role};"+ f" const targetName = {target_name};"+ " let count = 0;"+ " const nodes = document.querySelectorAll('*');"+ " for (const el of nodes) {"+ " const role = text(el.getAttribute('role')) || implicitRole(el);"+ " if (role !== targetRole) continue;"+ " if (accessibleName(el, role) === targetName) { count++; if (count > 1) break; }"+ " }"+ " return count;"+ " } catch (e) { return -1; }""})()")diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.pyindex 6f9d58828..71fe9a4eb 100644--- a/skyvern/forge/sdk/copilot/mcp_adapter.py+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py@@ -63,6 +63,8 @@ _POST_HOOK_CONTEXT_ROLLBACK_FIELDS = ("pending_scout_source_url","pending_scout_typed_value","pending_scout_role_name",+ "pending_scout_ambiguous",+ "pending_scout_reanchor","post_budget_page_inspection_required","post_budget_page_inspection_url","post_budget_page_inspection_run_id",diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex b2f0bfbb9..d418d4f8a 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -207,6 +207,9 @@ class ScoutedInteraction(TypedDict):control_value_satisfied: NotRequired[bool]trajectory_index: NotRequired[int]carried: NotRequired[bool]+ # 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]# Credential fills carry references and metadata only — never secret values.credential_id: NotRequired[str]credential_field: NotRequired[str]@@ -453,6 +456,9 @@ class AgentContext:# Imposition answered this persist attempt on a goal-complete trajectory, so the persist-seam under-build# guard (the fallback for a non-rewriting imposition) must not also answer for it.spine_imposition_owned_attempt: bool = False+ # Label of the code block the imposition attempt owns this call (carrier), including on no-op early+ # returns. The freehand persist-seam surface leg exempts exactly this label and gates its siblings.+ spine_imposition_carrier_label: str | None = Nonesynthesized_block_reopened_after_failed_run: bool = Falsesynthesized_block_reopened_for_output_coverage: bool = Falsesynthesized_block_reopened_for_credential_scout: bool = False@@ -483,6 +489,13 @@ class AgentContext:# Selector of an in-flight click, captured pre-dispatch so a failed/timed-out click can gate a# settle re-perception on whether that selector still resolves to a live element.pending_scout_click_selector: str | None = None+ # (selector, ambiguous) verdict from a pre-dispatch live count probe, applied to the recorded+ # interaction only when the post-action resolved selector matches the probed one.+ pending_scout_ambiguous: tuple[str, bool] | None = None+ # (selector, role, accessible_name) captured pre-dispatch for an ambiguous selector only when the+ # get_by_role(role, name, exact=True) re-anchor resolves to exactly one live element on the source+ # page; a non-unique or nameless ambiguous selector leaves this None so synthesis drops the interaction.+ pending_scout_reanchor: tuple[str, str, str] | None = None# Exact secret strings filled into the live browser this turn (passwords,# call-time-minted OTP codes). Page-readback tool results are exact-string# scrubbed against this set before being recorded or returned to the model.diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.pyindex 33a743cd3..00a2e32a7 100644--- a/skyvern/forge/sdk/copilot/tools/__init__.py+++ b/skyvern/forge/sdk/copilot/tools/__init__.py@@ -224,6 +224,7 @@ from .run_execution import _watchdog_exit_allows_terminal_promotion as _watchdogfrom .run_execution import _watchdog_user_failure_reason as _watchdog_user_failure_reasonfrom .scouting import _MAX_SCOUTED_INTERACTIONS as _MAX_SCOUTED_INTERACTIONSfrom .scouting import _capture_accessible_role_name as _capture_accessible_role_name+from .scouting import _capture_scout_ambiguity as _capture_scout_ambiguityfrom .scouting import _capture_scout_role_name as _capture_scout_role_namefrom .scouting import _capture_scout_source_url as _capture_scout_source_urlfrom .scouting import _clear_pending_browser_interaction_observation as _clear_pending_browser_interaction_observation@@ -234,6 +235,7 @@ from .scouting import _consume_scout_source_url as _consume_scout_source_urlfrom .scouting import _mark_page_inspected as _mark_page_inspectedfrom .scouting import _mark_pending_browser_interaction_observation as _mark_pending_browser_interaction_observationfrom .scouting import _mark_post_run_page_observed as _mark_post_run_page_observed+from .scouting import _prenav_ambiguity_for_selector as _prenav_ambiguity_for_selectorfrom .scouting import _prenav_role_name_for_selector as _prenav_role_name_for_selectorfrom .scouting import _record_scouted_interaction as _record_scouted_interactionfrom .scouting import _register_scout_interaction_observation as _register_scout_interaction_observationdiff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.pyindex 98982108e..f5575cd6a 100644--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py@@ -46,6 +46,7 @@ from .scouting import (_PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS,_actionable_targets_for_result,_attach_scout_page_summary,+ _capture_scout_ambiguity,_capture_scout_role_name,_capture_scout_source_url,_clear_pending_browser_interaction_observation,@@ -54,6 +55,7 @@ from .scouting import (_mark_page_inspected,_mark_pending_browser_interaction_observation,_maybe_attach_reached_download_target,+ _prenav_ambiguity_for_selector,_prenav_role_name_for_selector,_record_scouted_interaction,_register_scout_interaction_observation,@@ -301,6 +303,7 @@ async def _click_pre_hook(# cannot leave a prior click's stash for this click's post-hook to consume.ctx.pending_scout_role_name = Nonectx.pending_scout_click_selector = None+ ctx.pending_scout_ambiguous = Noneawait _capture_scout_source_url(ctx)deterministic_result = _strip_intent_for_code_only_selector_action(params, ctx, tool_name="click")if deterministic_result is not None:@@ -324,6 +327,7 @@ async def _click_pre_hook(),}await _capture_scout_role_name(ctx, selector)+ await _capture_scout_ambiguity(ctx, selector)return None@@ -359,8 +363,13 @@ async def _select_option_pre_hook(params: dict[str, Any],ctx: AgentContext,) -> dict[str, Any] | None:+ ctx.pending_scout_ambiguous = None+ ctx.pending_scout_reanchor = Noneawait _capture_scout_source_url(ctx)- return _strip_intent_for_code_only_selector_action(params, ctx, tool_name="select_option")+ result = _strip_intent_for_code_only_selector_action(params, ctx, tool_name="select_option")+ if result is None:+ await _capture_scout_ambiguity(ctx, params.get("selector", ""))+ return resultasync def _press_key_pre_hook(@@ -423,6 +432,10 @@ async def _click_post_hook(source_url = _consume_scout_source_url(ctx)pending_role_name = ctx.pending_scout_role_namectx.pending_scout_role_name = None+ pending_ambiguous = ctx.pending_scout_ambiguous+ ctx.pending_scout_ambiguous = None+ pending_reanchor = ctx.pending_scout_reanchor+ ctx.pending_scout_reanchor = Noneattempted_selector = ctx.pending_scout_click_selectorctx.pending_scout_click_selector = Noneif result.get("ok") and result.get("data"):@@ -439,6 +452,9 @@ async def _click_post_hook(role, accessible_name = await _resolve_scout_role_name(ctx, selector, allow_browser_read=not navigated)if navigated and not (role and accessible_name):role, accessible_name = _prenav_role_name_for_selector(pending_role_name, selector)+ ambiguous = _prenav_ambiguity_for_selector(pending_ambiguous, selector)+ if ambiguous:+ role, accessible_name = _prenav_role_name_for_selector(pending_reanchor, selector)result["data"]["effective_target"] = _effective_target_text(selector, role, accessible_name)_record_scouted_interaction(ctx,@@ -447,6 +463,7 @@ async def _click_post_hook(source_url=source_url,role=role,accessible_name=accessible_name,+ ambiguous=ambiguous,)observation_step, page_evidence = await _register_scout_interaction_observation(ctx, tool_name="click", selector=selector, source_url=source_url, url=url@@ -852,6 +869,10 @@ async def _select_option_post_hook() -> dict[str, Any]:_clear_pending_browser_interaction_observation(ctx)source_url = _consume_scout_source_url(ctx)+ pending_ambiguous = ctx.pending_scout_ambiguous+ ctx.pending_scout_ambiguous = None+ pending_reanchor = ctx.pending_scout_reanchor+ ctx.pending_scout_reanchor = Noneif result.get("ok") and result.get("data"):data = result["data"]selector = _selector_from_tool_data(data)@@ -863,6 +884,9 @@ async def _select_option_post_hook("url": url,}role, accessible_name = await _resolve_scout_role_name(ctx, selector)+ ambiguous = _prenav_ambiguity_for_selector(pending_ambiguous, selector)+ if ambiguous:+ role, accessible_name = _prenav_role_name_for_selector(pending_reanchor, selector)_record_scouted_interaction(ctx,tool_name="select_option",@@ -871,6 +895,7 @@ async def _select_option_post_hook(value=data.get("value", ""),role=role,accessible_name=accessible_name,+ ambiguous=ambiguous,)observation_step, page_evidence = await _register_scout_interaction_observation(ctx, tool_name="select_option", selector=selector, source_url=source_url, url=urldiff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.pyindex aeed99331..473c5c9d4 100644--- a/skyvern/forge/sdk/copilot/tools/scouting.py+++ b/skyvern/forge/sdk/copilot/tools/scouting.py@@ -18,6 +18,9 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (recorded_outcome_from_loaded_result_evidence,recorded_outcome_from_scout_act_observe_hollow,)+from skyvern.forge.sdk.copilot.composition_browser_expressions import (+ role_name_match_count_expression as _role_name_match_count_expression,+)from skyvern.forge.sdk.copilot.composition_browser_expressions import (scout_accessible_role_name_expression as _scout_accessible_role_name_expression,)@@ -251,6 +254,35 @@ async def _selector_live_match_count(return value+async def _role_name_match_count(+ ctx: AgentContext, role: str, name: str, *, timeout_seconds: float = _PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS+) -> int | None:+ """Live count of elements whose computed ARIA role and accessible name exactly match, or None when+ the page read is unavailable; lets the ambiguity guard tell a uniquely-resolvable re-anchor apart from+ a name-degenerate one before trusting get_by_role(role, name, exact=True)."""+ if not role or not name:+ return None+ server = getattr(ctx, "discovery_mcp_server", None)+ if server is None or timeout_seconds <= 0:+ return None+ try:+ result = await asyncio.wait_for(+ server.call_internal_tool(+ "skyvern_evaluate",+ {"expression": _role_name_match_count_expression(role, name)},+ ),+ timeout=timeout_seconds,+ )+ except Exception:+ return None+ if not isinstance(result, dict) or not result.get("ok"):+ return None+ value = (result.get("data") or {}).get("result")+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ return None+ return value++async def _capture_scout_role_name(ctx: AgentContext, selector: str | None) -> None:"""Stash (selector, role, accessible_name) before an in-flight click that may navigate.@@ -287,6 +319,43 @@ def _prenav_role_name_for_selector(pending: tuple[str, str, str] | None, selectoreturn role, name+async def _capture_scout_ambiguity(ctx: AgentContext, selector: str | None) -> None:+ """Stash whether a click/select selector is ambiguous (>1 match) on its source page, read before the+ action dispatches so the count reflects the source rather than a post-navigation landing; a captured+ (role, name) re-anchor is kept only when get_by_role(role, name, exact=True) resolves uniquely, so a+ name-degenerate selector fails closed to the scout-the-step drop instead of a strict-mode failure."""+ ctx.pending_scout_ambiguous = None+ ctx.pending_scout_reanchor = None+ selector = _selector_text(selector)+ if not selector:+ return+ count = await _selector_live_match_count(ctx, selector)+ if count is None or count <= 1:+ return+ ctx.pending_scout_ambiguous = (selector, True)+ captured = await _capture_accessible_role_name(+ ctx, selector, timeout_seconds=_PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS+ )+ if captured is None:+ return+ role, name = captured+ if not role or not name:+ return+ if await _role_name_match_count(ctx, role, name) == 1:+ ctx.pending_scout_reanchor = (selector, role, name)+++def _prenav_ambiguity_for_selector(pending: tuple[str, bool] | None, selector: str) -> bool:+ """Return the stashed ambiguity verdict only when the recorded selector matches the probed one, so a+ navigating click's verdict is never applied to a different element."""+ if pending is None:+ return False+ stashed_selector, ambiguous = pending+ if stashed_selector != _selector_text(selector):+ return False+ return ambiguous++async def _resolve_scout_role_name(ctx: AgentContext, selector: str | None, *, allow_browser_read: bool = True) -> tuple[str, str]:@@ -362,6 +431,7 @@ def _record_scouted_interaction(credential_id: str = "",credential_field: str = "",credential_name: str = "",+ ambiguous: bool = False,) -> None:selector = _selector_text(selector)# press_key may be page-level, so it is recorded by key even with no selector; other tools require one.@@ -406,6 +476,8 @@ def _record_scouted_interaction(artifact["credential_field"] = credential_fieldif credential_name:artifact["credential_name"] = credential_name+ if ambiguous:+ artifact["ambiguous"] = Trueinteractions = [itemfor item in ctx.scouted_interactionsdiff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex 867637ed7..e4400d300 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -10,6 +10,7 @@ import reimport textwrapimport tokenizefrom collections.abc import Callable, Iterable, Iterator, Mapping+from collections.abc import Set as AbstractSetfrom dataclasses import dataclassfrom dataclasses import field as dataclass_fieldfrom dataclasses import replace@@ -54,6 +55,7 @@ from skyvern.forge.sdk.copilot.code_block_security import CodeBlockSecurityErrorfrom skyvern.forge.sdk.copilot.code_block_steps import apply_derived_code_block_steps, fill_code_block_prompts_in_yamlfrom skyvern.forge.sdk.copilot.code_block_synthesis import (_CODE_SUBMIT_ACTION_RE,+ _CREDENTIAL_FIELDS,_INTERNAL_SCOUT_VARS,_SYNTHESIZED_BLOCK_LABEL,CREDENTIAL_FILL_TOOL_NAME,@@ -6129,6 +6131,32 @@ def _direct_locator_receiver_signature(node: ast.AST) -> str | None:return None+# page.get_by_label(...) is a durable locator factory strict synthesis never emits, so it is scanned+# as a durable mutation receiver only to route it through the admissibility contract, never to admit it.+_DURABLE_NON_SYNTHESIZED_FACTORY_METHODS = frozenset({"get_by_label"})+++def _durable_non_synthesized_receiver_signature(node: ast.AST) -> str | None:+ receiver = _locator_receiver_for_signature(node)+ if (+ isinstance(receiver, ast.Call)+ and isinstance(receiver.func, ast.Attribute)+ and receiver.func.attr in _DURABLE_NON_SYNTHESIZED_FACTORY_METHODS+ and isinstance(receiver.func.value, ast.Name)+ and receiver.func.value.id == "page"+ ):+ return _call_name(receiver)+ return None+++def _receiver_is_durable_non_synthesized_factory(receiver: str) -> bool:+ try:+ node = ast.parse(receiver, mode="eval").body+ except SyntaxError:+ return False+ return _durable_non_synthesized_receiver_signature(node) is not None++def _direct_page_method_signature(node: ast.AST) -> str | None:if not isinstance(node, ast.Name) or node.id != "page":return None@@ -6149,7 +6177,9 @@ def _browser_mutation_signature_for_call(node: ast.Call) -> _BrowserMutationSignif not isinstance(func, ast.Attribute):return Noneif func.attr in _LOCATOR_MUTATION_METHODS:- receiver = _direct_locator_receiver_signature(func.value)+ receiver = _direct_locator_receiver_signature(func.value) or _durable_non_synthesized_receiver_signature(+ func.value+ )if receiver is not None:return _BrowserMutationSignature(func.attr, receiver, ast.dump(node, include_attributes=False))return None@@ -6276,6 +6306,8 @@ def _browser_expression_kind(node: ast.AST, bindings: _BrowserBindings) -> _Browreturn _BrowserExpressionKind.LOCATORif _direct_locator_receiver_signature(node) is not None:return _BrowserExpressionKind.LOCATOR+ if _durable_non_synthesized_receiver_signature(node) is not None:+ return _BrowserExpressionKind.LOCATORif isinstance(node, ast.Attribute) and node.attr in {"first", "last"}:if _browser_expression_kind(node.value, bindings) == _BrowserExpressionKind.LOCATOR:return _BrowserExpressionKind.LOCATOR@@ -6591,11 +6623,18 @@ def _whole_trajectory_browser_surface_violations(synthesized_code: str,prior_yaml: str | None = None,synthesized_diagnostics: SynthesisDiagnostics | None = None,+ admit_on_receiver: bool = False,+ restrict_to_durable_factory: bool = False,) -> _BrowserSurfaceValidation:violations: list[str] = []provenance: list[_BrowserSurfaceRejectionProvenance] = []scouted_mutations, _, _ = _browser_surface_for_code(synthesized_code)scouted_signatures = set(scouted_mutations)+ # Freehand admission is selector-resolvability, so a block that replays a scouted locator with a+ # different literal argument stays admissible; imposition siblings keep the stricter full-call match.+ admitted_receivers = {+ (mutation.method, normalized_locator_expr(mutation.receiver)) for mutation in scouted_mutations+ }for block in code_blocks:if block is selected_code_block:continue@@ -6604,7 +6643,21 @@ def _whole_trajectory_browser_surface_violations(label = _code_block_label(block)block_code = str(block.get("code") or "")block_mutations, _, block_ambiguous = _browser_surface_for_code(block_code)- unscouted_mutations = [mutation for mutation in block_mutations if mutation not in scouted_signatures]+ if admit_on_receiver:+ unscouted_mutations = [+ mutation+ for mutation in block_mutations+ if mutation.receiver != "page"+ and (mutation.method, normalized_locator_expr(mutation.receiver)) not in admitted_receivers+ ]+ else:+ unscouted_mutations = [mutation for mutation in block_mutations if mutation not in scouted_signatures]+ if restrict_to_durable_factory:+ unscouted_mutations = [+ mutation+ for mutation in unscouted_mutations+ if _receiver_is_durable_non_synthesized_factory(mutation.receiver)+ ]if unscouted_mutations:action_text = ", ".join(f"{mutation.receiver}.{mutation.method}" for mutation in sorted(unscouted_mutations)@@ -6624,7 +6677,7 @@ def _whole_trajectory_browser_surface_violations(f"Unable to impose synthesized code block: `{label}` contains unscouted browser action(s): "f"{action_text}.{_provenance_suffix_text(block_provenance)}")- if block_ambiguous:+ if block_ambiguous and not restrict_to_durable_factory:ambiguous_provenance = [_ambiguous_browser_action_provenance(action, site="whole_trajectory", block_label=label)for action in block_ambiguous@@ -6870,6 +6923,197 @@ def _persist_seam_spine_under_build_result()+_FREEHAND_UNRESOLVABLE_SELECTOR_REASON_CODE = "freehand_unresolvable_selector"+_FREEHAND_UNGUARDED_CREDENTIAL_REASON_CODE = "freehand_unguarded_credential_fill"+++def _workflow_credential_parameter_keys(parsed: Mapping[str, Any]) -> set[str]:+ workflow_definition = parsed.get("workflow_definition")+ parameters = workflow_definition.get("parameters") if isinstance(workflow_definition, dict) else None+ if not isinstance(parameters, list):+ return set()+ keys: set[str] = set()+ for parameter in parameters:+ if not isinstance(parameter, Mapping) or not _is_credential_parameter(parameter):+ continue+ key = str(parameter.get("key") or "").strip()+ if key:+ keys.add(key)+ return keys+++def _credential_field_fill_argument(arg: ast.AST, credential_parameter_keys: AbstractSet[str]) -> bool:+ if (+ isinstance(arg, ast.Attribute)+ and arg.attr in _CREDENTIAL_FIELDS+ and isinstance(arg.value, ast.Name)+ and arg.value.id in credential_parameter_keys+ ):+ return True+ target = arg.value if isinstance(arg, ast.Await) else arg+ return (+ isinstance(target, ast.Call)+ and isinstance(target.func, ast.Attribute)+ and target.func.attr == "otp"+ and isinstance(target.func.value, ast.Name)+ and target.func.value.id in credential_parameter_keys+ )+++def _is_credential_field_fill_call(node: ast.AST, credential_parameter_keys: AbstractSet[str]) -> bool:+ return (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "fill"+ and bool(node.args)+ and _credential_field_fill_argument(node.args[0], credential_parameter_keys)+ )+++def _is_presence_guard_test(test: ast.AST) -> bool:+ for node in ast.walk(test):+ if isinstance(node, ast.Attribute) and node.attr in {"count", "is_visible"}:+ return True+ if isinstance(node, ast.Name) and node.id in _INTERNAL_SCOUT_VARS:+ return True+ return False+++def _credential_fill_is_presence_guarded(node: ast.AST, parents: Mapping[int, ast.AST]) -> bool:+ current: ast.AST = node+ while id(current) in parents:+ parent = parents[id(current)]+ if (+ isinstance(parent, ast.If)+ and any(current is stmt for stmt in parent.body)+ and _is_presence_guard_test(parent.test)+ ):+ return True+ current = parent+ return False+++def _block_has_unguarded_credential_fill(code: str, credential_parameter_keys: AbstractSet[str]) -> bool:+ if not credential_parameter_keys:+ return False+ tree = _wrapped_code_ast(code)+ if tree is None:+ return False+ parents: dict[int, ast.AST] = {}+ for node in ast.walk(tree):+ for child in ast.iter_child_nodes(node):+ parents[id(child)] = node+ return any(+ _is_credential_field_fill_call(node, credential_parameter_keys)+ and not _credential_fill_is_presence_guarded(node, parents)+ for node in ast.walk(tree)+ )+++def _freehand_surface_reject(+ workflow_yaml: str, code_blocks: list[dict[str, Any]], validation: _BrowserSurfaceValidation+) -> _SynthesizedCodeImpositionResult:+ first = validation.provenance[0] if validation.provenance else None+ repair_context = CodeAuthoringRepairContext(+ block_label=first.block_label if first is not None else _code_block_label(code_blocks[0]),+ reason_code=_FREEHAND_UNRESOLVABLE_SELECTOR_REASON_CODE,+ selector=first.nearest_selector if first is not None else None,+ )+ return _SynthesizedCodeImpositionResult(+ workflow_yaml=workflow_yaml,+ violations=validation.violations,+ repair_context=repair_context,+ )+++def _persist_seam_freehand_surface_result(+ workflow_yaml: str, ctx: AgentContext+) -> _SynthesizedCodeImpositionResult | None:+ # Imposition validates only the spine it rewrites; this leg closes the persist lanes where a changed+ # freehand browser block never reached that surface gate, applying the same admissibility to siblings.+ if not ctx.impose_synthesized_code_block:+ return None+ if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:+ return None+ scout_trajectory = ctx.scout_trajectory+ if not scout_trajectory:+ return None+ if not str(scout_trajectory[0].get("source_url") or "").strip():+ return None+ parsed = parse_workflow_yaml(workflow_yaml)+ if not isinstance(parsed, dict):+ return None+ code_blocks = _workflow_code_blocks(parsed)+ if not code_blocks:+ return None+ _, prior_yaml = _prior_yaml_source(ctx)+ carrier_label = ctx.spine_imposition_carrier_label+ exempt_block = (+ next((block for block in code_blocks if _code_block_label(block) == carrier_label), None)+ if carrier_label+ else None+ )+ credential_parameter_keys = _workflow_credential_parameter_keys(parsed)+ for block in code_blocks:+ if block is exempt_block:+ continue+ if prior_yaml is not None and not _submitted_code_block_changed(block, prior_yaml):+ continue+ if not _block_has_unguarded_credential_fill(str(block.get("code") or ""), credential_parameter_keys):+ continue+ label = _code_block_label(block)+ LOG.info("copilot_freehand_unguarded_credential_fill", block_label=label)+ violation = (+ f"Unable to persist code block: `{label}` fills a credential field without a presence guard, so it "+ "re-fills and times out when the workflow replays on an already-authenticated page. Reuse the "+ "synthesized entry rung, which fills only when the login form is still present."+ )+ return _SynthesizedCodeImpositionResult(+ workflow_yaml=workflow_yaml,+ violations=[violation],+ repair_context=CodeAuthoringRepairContext(+ block_label=label, reason_code=_FREEHAND_UNGUARDED_CREDENTIAL_REASON_CODE+ ),+ )+ synthesized = synthesize_code_block(+ scout_trajectory, strict_selectors=True, reached_download_target=ctx.reached_download_target+ )+ synthesized_code = "" if synthesized is None else (synthesized.interaction_code or synthesized.code)+ synthesized_diagnostics = None if synthesized is None else synthesized.diagnostics+ sentinel_selected: dict[str, Any] = {}+ selected_code_block = exempt_block if exempt_block is not None else sentinel_selected+ # get_by_label is never a synthesized selector, so an unresolvable one is rejected regardless of whether+ # the scout reached its goal; a fragment scout still fails this class closed to the scout-the-step route.+ factory_validation = _whole_trajectory_browser_surface_violations(+ code_blocks=code_blocks,+ selected_code_block=selected_code_block,+ submitted_selected_code="",+ synthesized_code=synthesized_code,+ prior_yaml=prior_yaml,+ synthesized_diagnostics=synthesized_diagnostics,+ admit_on_receiver=True,+ restrict_to_durable_factory=True,+ )+ if factory_validation.violations:+ return _freehand_surface_reject(workflow_yaml, code_blocks, factory_validation)+ # The full synthesized spine is an authoritative admissibility reference only when the scout captured a+ # durable entry through a commit; a fragment scout would false-reject legitimate multi-block authoring.+ if synthesized is None or not synthesized_trajectory_reaches_goal(ctx):+ return None+ validation = _whole_trajectory_browser_surface_violations(+ code_blocks=code_blocks,+ selected_code_block=selected_code_block,+ submitted_selected_code="",+ synthesized_code=synthesized_code,+ prior_yaml=prior_yaml,+ synthesized_diagnostics=synthesized_diagnostics,+ admit_on_receiver=True,+ )+ if not validation.violations:+ return None+ return _freehand_surface_reject(workflow_yaml, code_blocks, validation)++def _workflow_yaml_browser_call_pairs(workflow_yaml: str) -> list[tuple[str, str]]:parsed = parse_workflow_yaml(workflow_yaml)if not isinstance(parsed, dict):@@ -8076,6 +8320,7 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)ctx.pending_goal_complete_landing = Falsectx.pending_requested_output_extraction_candidate = Nonectx.spine_imposition_owned_attempt = False+ ctx.spine_imposition_carrier_label = Noneif not getattr(ctx, "impose_synthesized_code_block", False):return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:@@ -8114,6 +8359,7 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)LOG.info("copilot_spine_imposition_no_carrier", code_block_count=len(code_blocks))return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)submitted_code = str(code_block.get("code") or "")+ ctx.spine_imposition_carrier_label = _code_block_label(code_block)owns_spine = reaches_goalctx.spine_imposition_owned_attempt = owns_spine@@ -9685,6 +9931,17 @@ async def _update_workflow(repair_context=seam_under_build.repair_context,record_repair_context_outcome=False,)+ freehand_surface = _persist_seam_freehand_surface_result(workflow_yaml, ctx)+ if freehand_surface is not None:+ _set_code_authoring_repair_context(ctx, freehand_surface.repair_context)+ _record_code_authoring_guardrail_reject(ctx)+ return reject(+ error="\n".join(freehand_surface.violations),+ user_facing_summary=_compiled_authoring_user_summary(),+ data=_code_repair_progress_data(freehand_surface.repair_context),+ repair_context=freehand_surface.repair_context,+ record_repair_context_outcome=False,+ )stripped_sandbox_imports: list[str] = []if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:workflow_yaml, stripped_sandbox_imports = _strip_redundant_sandbox_imports_in_yaml(workflow_yaml)diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex 368b8050a..d69274f08 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -16097,3 +16097,200 @@ def test_reconcile_scout_interaction_positional_map_skips_witness_rows() -> None)assert account is not None and account["selector"] == "#account"assert period is not None and period["selector"] == "#period"+++def _goal_reaching_freehand_ctx(*, credential: bool = False) -> CopilotContext:+ ctx = _code_only_ctx()+ _enable_imposition(ctx)+ if credential:+ ctx.scout_trajectory = [+ {+ "tool_name": "fill_credential_field",+ "selector": "#username",+ "source_url": "https://example.com/login",+ "credential_id": "cred_1",+ "credential_name": "portal",+ "credential_field": "username",+ "trajectory_index": 0,+ },+ {+ "tool_name": "click",+ "selector": "#signin",+ "source_url": "https://example.com/login",+ "role": "button",+ "accessible_name": "Sign In",+ "trajectory_index": 1,+ },+ ]+ else:+ ctx.scout_trajectory = [+ {+ "tool_name": "type_text",+ "selector": "#search",+ "source_url": "https://example.com/find",+ "typed_length": 5,+ "role": "textbox",+ "accessible_name": "Search",+ "trajectory_index": 0,+ },+ {+ "tool_name": "click",+ "selector": "button",+ "source_url": "https://example.com/find",+ "role": "button",+ "accessible_name": "Sign In",+ "trajectory_index": 1,+ },+ ]+ return ctx+++def _freehand_block_yaml(code: str, *, label: str = "find_address", parameters: str = "") -> str:+ indented = "\n".join(f" {line}" for line in code.splitlines())+ return (+ "title: t\n"+ "workflow_definition:\n"+ f"{parameters}"+ " blocks:\n"+ " - block_type: code\n"+ f" label: {label}\n"+ " code: |\n"+ f"{indented}\n"+ )+++class TestFreehandSurfacePersistSeam:+ def test_get_by_label_unassociated_shape_rejected_with_scout_route(self) -> None:+ code = (+ 'await page.locator("#search").fill("x")\n'+ 'await page.get_by_role("button", name="Sign In", exact=True).click()\n'+ 'await page.get_by_label("State").select_option("CA")'+ )+ result = workflow_update_module._persist_seam_freehand_surface_result(+ _freehand_block_yaml(code), _goal_reaching_freehand_ctx()+ )+ assert result is not None+ assert result.repair_context is not None+ assert result.repair_context.reason_code == "freehand_unresolvable_selector"+ assert "get_by_label" in result.violations[0]+ assert "never_captured" in result.violations[0]++ def test_attribute_selector_button_shape_rejected(self) -> None:+ code = (+ 'await page.locator("#search").fill("x")\n'+ "await page.locator(\"button[data-action='orderDocuments']\").click()"+ )+ result = workflow_update_module._persist_seam_freehand_surface_result(+ _freehand_block_yaml(code), _goal_reaching_freehand_ctx()+ )+ assert result is not None+ assert "orderDocuments" in result.violations[0]++ def test_strict_synthesis_parity_rejects_bare_locator_when_emitted_literal_is_role_form(self) -> None:+ code = 'await page.locator("#search").fill("x")\nawait page.locator("button").click()'+ result = workflow_update_module._persist_seam_freehand_surface_result(+ _freehand_block_yaml(code), _goal_reaching_freehand_ctx()+ )+ assert result is not None+ assert "page.locator('button')" in result.violations[0]++ def test_receiver_matching_literal_fill_is_admitted(self) -> None:+ code = (+ 'await page.locator("#search").fill("hardcoded")\n'+ 'await page.get_by_role("button", name="Sign In", exact=True).click()'+ )+ result = workflow_update_module._persist_seam_freehand_surface_result(+ _freehand_block_yaml(code), _goal_reaching_freehand_ctx()+ )+ assert result is None++ def test_selectorless_navigation_block_is_not_gated(self) -> None:+ code = 'await page.goto("https://example.com/find")\nawait page.reload()'+ result = workflow_update_module._persist_seam_freehand_surface_result(+ _freehand_block_yaml(code, label="nav"), _goal_reaching_freehand_ctx()+ )+ assert result is None++ def _fragment_scout_ctx(self) -> CopilotContext:+ ctx = _goal_reaching_freehand_ctx()+ ctx.scout_trajectory = [+ {+ "tool_name": "type_text",+ "selector": "#search",+ "source_url": "https://example.com/find",+ "role": "textbox",+ "accessible_name": "Search",+ "trajectory_index": 0,+ }+ ]+ assert enforcement_module.synthesized_trajectory_reaches_goal(ctx) is False+ return ctx++ def test_fragment_scout_rejects_ungrounded_get_by_label(self) -> None:+ ctx = self._fragment_scout_ctx()+ code = 'await page.get_by_label("State").select_option("CA")'+ result = workflow_update_module._persist_seam_freehand_surface_result(_freehand_block_yaml(code), ctx)+ assert result is not None+ assert result.repair_context is not None+ assert result.repair_context.reason_code == "freehand_unresolvable_selector"+ assert "get_by_label" in result.violations[0]++ def test_fragment_scout_admits_reused_scouted_receiver(self) -> None:+ ctx = self._fragment_scout_ctx()+ code = 'await page.locator("#search").fill("x")'+ result = workflow_update_module._persist_seam_freehand_surface_result(_freehand_block_yaml(code), ctx)+ assert result is None++ def test_fragment_scout_admits_not_yet_scouted_get_by_role(self) -> None:+ ctx = self._fragment_scout_ctx()+ code = 'await page.get_by_role("button", name="Continue", exact=True).click()'+ result = workflow_update_module._persist_seam_freehand_surface_result(_freehand_block_yaml(code), ctx)+ assert result is None++ def test_unguarded_credential_fill_routes_to_guarded_entry_rung(self) -> None:+ parameters = " parameters:\n - {parameter_type: credential, key: portal}\n"+ code = 'await page.locator("#password").fill(portal.password)'+ result = workflow_update_module._persist_seam_freehand_surface_result(+ _freehand_block_yaml(code, parameters=parameters), _goal_reaching_freehand_ctx(credential=True)+ )+ assert result is not None+ assert result.repair_context is not None+ assert result.repair_context.reason_code == "freehand_unguarded_credential_fill"++ def test_fragment_scout_rejects_unguarded_credential_fill(self) -> None:+ ctx = _goal_reaching_freehand_ctx(credential=True)+ ctx.scout_trajectory = ctx.scout_trajectory[:1]+ assert enforcement_module.synthesized_trajectory_reaches_goal(ctx) is False+ parameters = " parameters:\n - {parameter_type: credential, key: portal}\n"+ code = 'await page.locator("#password").fill(portal.password)'+ result = workflow_update_module._persist_seam_freehand_surface_result(+ _freehand_block_yaml(code, parameters=parameters), ctx+ )+ assert result is not None+ assert result.repair_context is not None+ assert result.repair_context.reason_code == "freehand_unguarded_credential_fill"++ def test_presence_guarded_credential_fill_is_admitted(self) -> None:+ parameters = " parameters:\n - {parameter_type: credential, key: portal}\n"+ code = (+ '_scout_entry_target = page.locator("#username")\n'+ "if await _scout_entry_target.count() == 1:\n"+ ' await page.locator("#username").fill(portal.username)'+ )+ result = workflow_update_module._persist_seam_freehand_surface_result(+ _freehand_block_yaml(code, parameters=parameters), _goal_reaching_freehand_ctx(credential=True)+ )+ assert result is None++ def test_non_credential_attribute_fill_is_not_flagged_as_credential(self) -> None:+ parameters = " parameters:\n - {parameter_type: credential, key: portal}\n"+ code = 'await page.locator("#search").fill(profile.email)'+ assert workflow_update_module._block_has_unguarded_credential_fill(code, {"portal"}) is False+ _ = parameters++ def test_reaches_goal_gate_off_returns_none_without_imposition(self) -> None:+ ctx = _goal_reaching_freehand_ctx()+ ctx.impose_synthesized_code_block = False+ code = 'await page.get_by_label("State").select_option("CA")'+ result = workflow_update_module._persist_seam_freehand_surface_result(_freehand_block_yaml(code), ctx)+ assert result is Nonediff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex 71f0912a9..b217e2b86 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -6,6 +6,7 @@ OSS-synced: only example.* / RFC-2606 placeholder targets.from __future__ import annotationsimport ast+import asyncioimport jsonimport keywordimport sys@@ -21,6 +22,7 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (_DOWNLOAD_VAR_BASE,_ENTRY_RESUME_AFTER_AUTH_VAR,_ENTRY_REUSED_VAR,+ _ENTRY_TARGET_VAR,_INDENT,_MAX_STEPS,_READONLY_DEFERRED_VAR,@@ -37,9 +39,11 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (SynthesisDiagnostics,_get_by_role_expr,_get_by_role_expr_strict,+ _is_submit_interaction,build_input_templated_locator,build_synthesized_artifact_metadata,code_contains_credential_fill,+ credential_scout_gap,input_correspondences_for_interaction,is_optional_dismissal_only_trajectory,obligation_finding_reason_code,@@ -483,6 +487,56 @@ class TestLocatorSynthesis:]assert dropped+ def test_attribute_selector_emitted_verbatim_when_not_scout_ambiguous(self) -> None:+ trajectory = [+ _interaction("click", selector="#open", source_url="https://example.com/home"),+ _interaction(+ "click",+ selector="button[data-action='orderDocuments']",+ source_url="https://example.com/portal",+ role="button",+ accessible_name="Order Documents",+ ),+ ]+ result = synthesize_code_block(trajectory, strict_selectors=True)+ assert result is not None+ assert "button[data-action='orderDocuments']" in result.code++ def test_strict_reanchors_scout_ambiguous_attribute_selector(self) -> None:+ trajectory = [+ _interaction("click", selector="#open", source_url="https://example.com/home"),+ _interaction(+ "click",+ selector="button[data-action='orderDocuments']",+ source_url="https://example.com/portal",+ role="button",+ accessible_name="Order Documents",+ ambiguous=True,+ ),+ ]+ result = synthesize_code_block(trajectory, strict_selectors=True)+ assert result is not None+ assert "data-action" not in result.code+ assert 'await page.get_by_role("button", name="Order Documents", exact=True).click()' in result.code++ def test_strict_drops_scout_ambiguous_attribute_selector_without_role_name(self) -> None:+ trajectory = [+ _interaction("click", selector="#open", source_url="https://example.com/home"),+ _interaction(+ "click",+ selector="button[data-action='businessToggle']",+ source_url="https://example.com/portal",+ ambiguous=True,+ ),+ ]+ result = synthesize_code_block(trajectory, strict_selectors=True)+ assert result is not None+ assert "data-action" not in result.code+ dropped = [+ d for d in result.diagnostics.dropped_interactions if d.get("reason_code") == "ambiguous_bare_selector"+ ]+ assert dropped+def test_strict_imposed_refuses_bare_role_no_name(self) -> None:trajectory = [_interaction("click", selector="#open-login", source_url="https://example.com/home"),@@ -3592,3 +3646,156 @@ def test_synthesize_input_purity() -> None:synthesize_code_block(list(trajectory), strict_selectors=False)synthesize_code_block(list(trajectory), strict_selectors=True)assert trajectory == snapshot+++def _credential_fill(**overrides: Any) -> dict[str, Any]:+ fields = {+ "selector": "#username",+ "source_url": "https://example.com/login",+ "credential_id": "cred_1",+ "credential_name": "portal",+ "credential_field": "username",+ "typed_length": 8,+ }+ fields.update(overrides)+ return _interaction(CREDENTIAL_FILL_TOOL_NAME, **fields)+++class _FakeLocator:+ def __init__(self, page: _FakePage, selector: str) -> None:+ self._page = page+ self._selector = selector++ async def count(self) -> int:+ return self._page.counts.get(self._selector, 0)++ async def wait_for(self, *, state: str, timeout: float | None = None) -> None:+ if self._page.counts.get(self._selector, 0) < 1:+ raise TimeoutError(f"{self._selector} not visible")++ async def fill(self, value: object) -> None:+ if self._page.counts.get(self._selector, 0) != 1:+ raise AssertionError(+ f"strict-mode fill on {self._selector} with count {self._page.counts.get(self._selector, 0)}"+ )+ self._page.filled.append(self._selector)++ async def click(self) -> None:+ self._page.clicked.append(self._selector)++ async def press(self, key: str) -> None:+ self._page.pressed.append((self._selector, key))+++class _FakePage:+ def __init__(self, counts: dict[str, int]) -> None:+ self.counts = counts+ self.filled: list[str] = []+ self.clicked: list[str] = []+ self.pressed: list[tuple[str, str]] = []+ self.goto_calls: list[str] = []++ def locator(self, selector: str) -> _FakeLocator:+ return _FakeLocator(self, selector)++ async def goto(self, url: str, *, wait_until: str | None = None) -> None:+ self.goto_calls.append(url)++ async def wait_for_load_state(self, state: str) -> None:+ return None+++def _run_synthesized_block(code: str, page: _FakePage, portal: object) -> None:+ namespace: dict[str, Any] = {}+ exec("async def _block(page, portal):\n" + code, namespace)+ asyncio.run(namespace["_block"](page, portal))+++class TestLoginOnlyPresenceGuardSynthesis:+ def _login_only_trajectory(self, *, submit: dict[str, Any]) -> list[dict[str, Any]]:+ return [+ _credential_fill(selector="#username", credential_field="username"),+ _credential_fill(selector="#password", credential_field="password"),+ submit,+ ]++ def test_click_submit_wraps_whole_prefix_in_count_guard(self) -> None:+ traj = self._login_only_trajectory(+ submit=_interaction("click", selector="#login-btn", source_url="https://example.com/login")+ )+ result = synthesize_code_block(traj, strict_selectors=True)+ assert result is not None+ assert f"if await {_ENTRY_TARGET_VAR}.count() == 1:" in result.code+ guard_line = next(i for i, ln in enumerate(result.code.splitlines()) if ".count() == 1:" in ln)+ body = result.code.splitlines()[guard_line + 1 : guard_line + 5]+ assert any(".fill(portal.username)" in ln for ln in body)+ assert any(".fill(portal.password)" in ln for ln in body)+ assert any('page.locator("#login-btn").click()' in ln for ln in body)+ assert all(ln.startswith(_INDENT * 2) for ln in body)++ def test_enter_submit_is_recognized_and_guarded(self) -> None:+ traj = self._login_only_trajectory(+ submit=_interaction("press_key", selector="#password", key="Enter", source_url="https://example.com/login")+ )+ result = synthesize_code_block(traj, strict_selectors=True)+ assert result is not None+ assert f"if await {_ENTRY_TARGET_VAR}.count() == 1:" in result.code+ assert ' await page.locator("#password").press("Enter")' in result.code++ def test_present_state_runs_full_login(self) -> None:+ traj = self._login_only_trajectory(+ submit=_interaction("click", selector="#login-btn", source_url="https://example.com/login")+ )+ result = synthesize_code_block(traj, strict_selectors=True)+ assert result is not None+ page = _FakePage({"#username": 1, "#password": 1, "#login-btn": 1})+ _run_synthesized_block(result.code, page, SimpleNamespace(username="u", password="p"))+ assert page.filled == ["#username", "#password"]+ assert page.clicked == ["#login-btn"]++ def test_absent_state_skips_login_without_timeout(self) -> None:+ traj = self._login_only_trajectory(+ submit=_interaction("click", selector="#login-btn", source_url="https://example.com/login")+ )+ result = synthesize_code_block(traj, strict_selectors=True)+ assert result is not None+ page = _FakePage({})+ _run_synthesized_block(result.code, page, SimpleNamespace(username="u", password="p"))+ assert page.filled == []+ assert page.clicked == []+ assert page.goto_calls == ["https://example.com/login"]++ def test_multiple_match_state_does_not_strict_mode_fail(self) -> None:+ traj = self._login_only_trajectory(+ submit=_interaction("click", selector="#login-btn", source_url="https://example.com/login")+ )+ result = synthesize_code_block(traj, strict_selectors=True)+ assert result is not None+ page = _FakePage({"#username": 2, "#password": 2, "#login-btn": 2})+ _run_synthesized_block(result.code, page, SimpleNamespace(username="u", password="p"))+ assert page.filled == []+ assert page.clicked == []+++class TestSharedSubmitPredicate:+ def test_click_and_enter_are_submits_but_tab_is_not(self) -> None:+ assert _is_submit_interaction({"tool_name": "click"}) is True+ assert _is_submit_interaction({"tool_name": "press_key", "key": "Enter"}) is True+ assert _is_submit_interaction({"tool_name": "press_key", "key": "Tab"}) is False+ assert _is_submit_interaction({"tool_name": "type_text"}) is False++ def test_tab_only_post_fill_reports_missing_submit(self) -> None:+ trajectory = [+ _credential_fill(selector="#username", credential_field="username"),+ _interaction("press_key", selector="#username", key="Tab", source_url="https://example.com/login"),+ ]+ gap = credential_scout_gap(trajectory, [(frozenset({"cred_1"}), frozenset({"username"}))], requires_submit=True)+ assert gap.missing_submit is True++ def test_enter_post_fill_satisfies_submit(self) -> None:+ trajectory = [+ _credential_fill(selector="#username", credential_field="username"),+ _interaction("press_key", selector="#username", key="Enter", source_url="https://example.com/login"),+ ]+ gap = credential_scout_gap(trajectory, [(frozenset({"cred_1"}), frozenset({"username"}))], requires_submit=True)+ assert gap.missing_submit is Falsediff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.pyindex b46062361..3eedb779b 100644--- a/tests/unit/test_copilot_hooks.py+++ b/tests/unit/test_copilot_hooks.py@@ -18,7 +18,12 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import synthesize_code_blockfrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicyfrom skyvern.forge.sdk.copilot.enforcement import CopilotGoalSatisfiedfrom skyvern.forge.sdk.copilot.hooks import CopilotRunHooks-from skyvern.forge.sdk.copilot.tools import _click_post_hook, _click_pre_hook+from skyvern.forge.sdk.copilot.tools import (+ _capture_scout_ambiguity,+ _click_post_hook,+ _click_pre_hook,+ _prenav_ambiguity_for_selector,+)from skyvern.forge.sdk.copilot.turn_halt import CopilotTurnHalt, turn_halt_from_blocker_signal@@ -1029,6 +1034,8 @@ class TestBrowserInteractionObservationHooks:pending_scout_typed_value=None,pending_scout_role_name=None,pending_scout_click_selector=None,+ pending_scout_ambiguous=None,+ pending_scout_reanchor=None,discovery_mcp_server=None,scouted_interactions=[],scout_trajectory=[],@@ -1063,6 +1070,8 @@ class TestBrowserInteractionObservationHooks:pending_scout_typed_value=None,pending_scout_role_name=None,pending_scout_click_selector=None,+ pending_scout_ambiguous=None,+ pending_scout_reanchor=None,discovery_mcp_server=None,scouted_interactions=[],scout_trajectory=[],@@ -1118,6 +1127,8 @@ class TestScoutedInteractionCapture:pending_scout_typed_value=None,pending_scout_role_name=None,pending_scout_click_selector=None,+ pending_scout_ambiguous=None,+ pending_scout_reanchor=None,discovery_mcp_server=None,browser_session_id=None,scouted_interactions=[],@@ -1457,6 +1468,116 @@ class TestScoutedInteractionCapture:assert entry["evidence"]["interaction_selector"] == "#sort"assert result["data"]["observation_step"] == entry["step"]+ def _ctx_with_count(self, count: int) -> SimpleNamespace:+ server = SimpleNamespace()+ server.call_internal_tool = AsyncMock(return_value={"ok": True, "data": {"result": count}})+ ctx = self._ctx(source_url="https://example.com/portal")+ ctx.discovery_mcp_server = server+ return ctx++ @pytest.mark.asyncio+ async def test_capture_scout_ambiguity_marks_multi_match_selector(self) -> None:+ ctx = self._ctx_with_count(3)+ await _capture_scout_ambiguity(ctx, "button[data-action='orderDocuments']")+ assert ctx.pending_scout_ambiguous == ("button[data-action='orderDocuments']", True)++ @pytest.mark.asyncio+ async def test_capture_scout_ambiguity_does_not_mark_unique_selector(self) -> None:+ ctx = self._ctx_with_count(1)+ await _capture_scout_ambiguity(ctx, "#unique")+ assert ctx.pending_scout_ambiguous is None++ @pytest.mark.asyncio+ async def test_click_cycle_records_scout_ambiguous_multi_match(self) -> None:+ ctx = self._ctx_with_count(2)+ await _click_pre_hook({"selector": "button[data-action='orderDocuments']"}, ctx)+ await _click_post_hook(+ {"ok": True, "data": {"selector": "button[data-action='orderDocuments']"}},+ {"browser_context": {"url": "https://example.com/portal", "title": "Portal"}},+ ctx,+ )+ assert ctx.scouted_interactions[-1].get("ambiguous") is True++ def _ctx_with_scripted_reads(+ self, *, selector_count: int, role_name: tuple[str, str], match_count: int+ ) -> SimpleNamespace:+ async def call(_tool: str, args: dict[str, Any]) -> dict[str, Any]:+ expression = args["expression"]+ if "accessible_name:" in expression:+ role, name = role_name+ return {"ok": True, "data": {"result": {"role": role, "accessible_name": name}}}+ if "targetRole" in expression:+ return {"ok": True, "data": {"result": match_count}}+ return {"ok": True, "data": {"result": selector_count}}++ server = SimpleNamespace()+ server.call_internal_tool = AsyncMock(side_effect=call)+ ctx = self._ctx(source_url="https://example.com/portal")+ ctx.discovery_mcp_server = server+ return ctx++ @pytest.mark.asyncio+ async def test_capture_scout_ambiguity_stashes_unique_reanchor(self) -> None:+ ctx = self._ctx_with_scripted_reads(+ selector_count=2, role_name=("button", "I AM A BUSINESS CUSTOMER"), match_count=1+ )+ await _capture_scout_ambiguity(ctx, "button[data-action='businessToggle']")+ assert ctx.pending_scout_ambiguous == ("button[data-action='businessToggle']", True)+ assert ctx.pending_scout_reanchor == (+ "button[data-action='businessToggle']",+ "button",+ "I AM A BUSINESS CUSTOMER",+ )++ @pytest.mark.asyncio+ async def test_capture_scout_ambiguity_withholds_name_degenerate_reanchor(self) -> None:+ ctx = self._ctx_with_scripted_reads(selector_count=2, role_name=("button", "Toggle"), match_count=2)+ await _capture_scout_ambiguity(ctx, "button[data-action='businessToggle']")+ assert ctx.pending_scout_ambiguous == ("button[data-action='businessToggle']", True)+ assert ctx.pending_scout_reanchor is None++ @pytest.mark.asyncio+ async def test_capture_scout_ambiguity_withholds_nameless_reanchor(self) -> None:+ ctx = self._ctx_with_scripted_reads(selector_count=2, role_name=("button", ""), match_count=1)+ await _capture_scout_ambiguity(ctx, "button[data-action='businessToggle']")+ assert ctx.pending_scout_ambiguous == ("button[data-action='businessToggle']", True)+ assert ctx.pending_scout_reanchor is None++ @pytest.mark.asyncio+ async def test_ambiguous_click_records_validated_reanchor_role_name(self) -> None:+ ctx = self._ctx_with_scripted_reads(+ selector_count=2, role_name=("button", "I AM A BUSINESS CUSTOMER"), match_count=1+ )+ await _click_pre_hook({"selector": "button[data-action='businessToggle']"}, ctx)+ await _click_post_hook(+ {"ok": True, "data": {"selector": "button[data-action='businessToggle']"}},+ {"browser_context": {"url": "https://example.com/portal", "title": "Portal"}},+ ctx,+ )+ recorded = ctx.scouted_interactions[-1]+ assert recorded.get("ambiguous") is True+ assert recorded.get("role") == "button"+ assert recorded.get("accessible_name") == "I AM A BUSINESS CUSTOMER"++ @pytest.mark.asyncio+ async def test_ambiguous_click_without_unique_reanchor_records_no_role_name(self) -> None:+ ctx = self._ctx_with_scripted_reads(selector_count=2, role_name=("button", "Toggle"), match_count=2)+ await _click_pre_hook({"selector": "button[data-action='businessToggle']"}, ctx)+ await _click_post_hook(+ {"ok": True, "data": {"selector": "button[data-action='businessToggle']"}},+ {"browser_context": {"url": "https://example.com/portal", "title": "Portal"}},+ ctx,+ )+ recorded = ctx.scouted_interactions[-1]+ assert recorded.get("ambiguous") is True+ assert "role" not in recorded+ assert "accessible_name" not in recorded++ def test_prenav_ambiguity_ignores_mismatched_selector(self) -> None:+ assert _prenav_ambiguity_for_selector(("button", True), "a") is False+ assert _prenav_ambiguity_for_selector(("button", True), "button") is True+ assert _prenav_ambiguity_for_selector(None, "button") is False+@pytest.mark.asyncioasync def test_intent_click_uses_resolved_selector_when_raw_selector_is_none(self) -> None:from skyvern.forge.sdk.copilot.tools import _click_post_hookdiff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.pyindex 32a0fc141..86694111b 100644--- a/tests/unit/test_copilot_scout_act_observe.py+++ b/tests/unit/test_copilot_scout_act_observe.py@@ -117,6 +117,8 @@ def _ctx(*, server: Any = None, source_url: str | None = _SOURCE_URL) -> SimpleNpending_scout_typed_value=None,pending_scout_role_name=None,pending_scout_click_selector=None,+ pending_scout_ambiguous=None,+ pending_scout_reanchor=None,discovery_mcp_server=server,scouted_interactions=[],scout_trajectory=[],