Skip to content

Automate browser based workflows with AI

Show saved logins at the Copilot credential checkpoint, not just create-new (SKY-15784) (#8563)

Andrew Neilson345ff6083601
diff --git a/skyvern-frontend/src/components/RecordingPill.tsx b/skyvern-frontend/src/components/RecordingPill.tsx
index caced38a5..f1eba0d5a 100644
--- a/skyvern-frontend/src/components/RecordingPill.tsx
+++ b/skyvern-frontend/src/components/RecordingPill.tsx
@@ -62,7 +62,11 @@ export function RecordingPill() {
"opacity-50": finishRequested,
})}
/>
- {finishRequested ? "FINISHING" : paused ? "PAUSED" : "REC"}{" "}
+ {finishRequested
+ ? "CREATING STEPS"
+ : paused
+ ? "TASK PAUSED"
+ : "RECORDING TASK"}{" "}
{formatRecordingClock(elapsedSeconds)}
<span className={paused ? "text-amber-400/80" : "text-red-400/80"}>
·
diff --git a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts
index b3dac8863..b2186f85b 100644
--- a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts
+++ b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts
@@ -187,10 +187,10 @@ const useProcessRecordingMutation = ({
}
toast({
variant: "success",
- title: evidence ? "Recorded steps added" : "Recording processed",
+ title: evidence ? "Workflow steps captured" : "Workflow steps added",
description: evidence
? "Copilot is refining the workflow now. Follow its progress in the Copilot pane."
- : "The recording has been successfully processed.",
+ : "Skyvern turned your browser demonstration into workflow steps.",
});
onSuccess?.({ recordingId, blocks, parameters: parameters });
@@ -217,8 +217,9 @@ const useProcessRecordingMutation = ({
toast({
variant: "warning",
- title: "Recording Processed (No Blocks)",
- description: "No blocks could be created from the recording.",
+ title: "No workflow steps created",
+ description:
+ "Skyvern couldn't turn this task recording into workflow steps.",
});
},
onError: (error) => {
@@ -233,9 +234,9 @@ const useProcessRecordingMutation = ({
recordingStore.reset();
toast({
variant: "warning",
- title: "Nothing was recorded",
+ title: "No task captured",
description:
- "Interact with the live browser (clicks, typing, navigation), then stop recording again to generate blocks.",
+ "Complete the task in the browser. Skyvern captures your clicks, typing, and navigation, then turns them into workflow steps.",
});
return;
}
@@ -247,7 +248,7 @@ const useProcessRecordingMutation = ({
toast({
variant: "destructive",
- title: "Error Processing Recording",
+ title: "Couldn't create workflow steps",
description: error instanceof Error ? error.message : String(error),
});
},
diff --git a/skyvern-frontend/src/routes/workflows/copilot/RecordingRefinementProgressCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/RecordingRefinementProgressCard.tsx
index 86c61a840..9181942ea 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/RecordingRefinementProgressCard.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/RecordingRefinementProgressCard.tsx
@@ -54,9 +54,8 @@ function RecordingRefinementProgressCard({
return () => window.clearInterval(timer);
}, [startedAtMs, working]);
- const actionLabel = `${actionCount} recorded action${actionCount === 1 ? "" : "s"}`;
const title = working
- ? `Turning ${actionLabel} into a workflow`
+ ? "Turning your task demonstration into a workflow"
: status === "complete"
? awaitingReview
? "Workflow ready to review"
@@ -103,7 +102,7 @@ function RecordingRefinementProgressCard({
</div>
<div className="mt-0.5 text-[11.5px] leading-relaxed text-muted-foreground">
{working
- ? "Copilot is reviewing the recording and preparing changes for you to review."
+ ? `Copilot is reviewing ${actionCount} captured interaction${actionCount === 1 ? "" : "s"} and preparing changes for you to review.`
: status === "complete"
? awaitingReview
? "Review the changes below, then save when you’re ready."
@@ -124,8 +123,8 @@ function RecordingRefinementProgressCard({
</div>
<div className="ml-9 mt-3 flex flex-col gap-2 border-l border-border/70 pl-3">
- <CompletedStep>Recording saved</CompletedStep>
- <CompletedStep>Recorded actions prepared</CompletedStep>
+ <CompletedStep>Task recording saved</CompletedStep>
+ <CompletedStep>Browser interactions prepared</CompletedStep>
<div
className={`flex items-center gap-2 text-xs ${
failed ? "text-red-600 dark:text-red-400" : "text-foreground"
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx
index b9602dc13..bdcafeb02 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx
@@ -599,16 +599,21 @@ describe("WorkflowCopilotChat — build follow", () => {
expect(focusBlock).not.toHaveBeenCalled();
});
- it("never fights the recording overlay", async () => {
+ it("blocks Copilot submission while the recording overlay owns authoring", async () => {
useRecordingStore.setState({ isRecording: true });
try {
await renderChat(makeDockedProps());
- await submit("build it");
- streamCalls[0]!.onMessage(
- blockProgressFrame({ block_label: "login", status: "running" }),
- );
+ expect(
+ (screen.getByRole("textbox") as HTMLTextAreaElement).disabled,
+ ).toBe(true);
+ const sendButton = screen.getByRole("button", {
+ name: "Send disabled — finish the current authoring action",
+ }) as HTMLButtonElement;
+ expect(sendButton.disabled).toBe(true);
+ fireEvent.click(sendButton);
+ expect(postStreaming).not.toHaveBeenCalled();
expect(focusBlock).not.toHaveBeenCalled();
} finally {
useRecordingStore.setState({ isRecording: false });
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
index 9fe2d3539..25fbebf4b 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
@@ -8,6 +8,7 @@ import {
} from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useCopilotActionStore } from "@/store/useCopilotActionStore";
+import { useRecordingStore } from "@/store/useRecordingStore";
import { COPILOT_WORKING_VERBS } from "./workingVerbs";
import { FeatureFlagContext } from "@/hooks/useFeatureFlag";
@@ -194,6 +195,11 @@ beforeEach(() => {
streamCalls.length = 0;
postStreaming.mockClear();
cancelPost.mockClear();
+ useRecordingStore.setState({
+ isRecording: false,
+ finishRequested: false,
+ isCommitting: false,
+ });
useCopilotActionStore.setState({
pendingBuild: null,
generatingBlockLabel: null,
@@ -208,6 +214,11 @@ beforeEach(() => {
});
afterEach(() => {
+ useRecordingStore.setState({
+ isRecording: false,
+ finishRequested: false,
+ isCommitting: false,
+ });
cleanup();
});
@@ -274,6 +285,9 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {
expect(postStreaming).toHaveBeenCalledTimes(1);
await deliverFirstFrame();
+ await act(async () => {
+ useRecordingStore.setState({ isRecording: true });
+ });
const button = screen.getByRole("button", { name: "Stop" });
expect(screen.getByTestId("copilot-stop-orbit").className).not.toContain(
"paused",
@@ -295,6 +309,7 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {
"/workflow/copilot/cancel",
expect.anything(),
);
+ useRecordingStore.setState({ isRecording: false });
});
it("arms stop on the first streamed frame even when that frame carries no turn id", async () => {
@@ -472,6 +487,100 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {
expect(ta.parentElement?.className).toContain("focus-within");
});
+ it("starts SOP upload and task recording from the empty state", async () => {
+ const onUploadSOP = vi.fn();
+ const onRecordTask = vi.fn();
+
+ render(
+ <FeatureFlagContext.Provider value={() => false}>
+ <WorkflowCopilotChat
+ onUploadSOP={onUploadSOP}
+ onRecordTask={onRecordTask}
+ canRecordTask
+ />
+ </FeatureFlagContext.Provider>,
+ );
+
+ await waitFor(() =>
+ expect(screen.getByText("Start a new chat")).toBeTruthy(),
+ );
+ expect(screen.getByText("Upload an SOP")).toBeTruthy();
+ expect(screen.getByText("Record task")).toBeTruthy();
+ const actionLayout = screen.getByRole("button", {
+ name: "Upload an SOP",
+ }).parentElement?.parentElement;
+ expect(actionLayout?.className).toContain("grid-cols-1");
+ expect(actionLayout?.className).toContain(
+ "[@container_copilot-actions_(min-width:440px)]:grid-cols-2",
+ );
+ expect(
+ screen.getByText(
+ "Complete the task in the browser. Skyvern captures the browser view and your clicks, typing, and navigation, then turns them into workflow steps.",
+ ),
+ ).toBeTruthy();
+
+ const file = new File(["procedure"], "procedure.pdf", {
+ type: "application/pdf",
+ });
+ fireEvent.change(screen.getByLabelText("Choose an SOP PDF"), {
+ target: { files: [file] },
+ });
+ expect(onUploadSOP).toHaveBeenCalledWith(file);
+
+ fireEvent.click(screen.getByRole("button", { name: "Record task" }));
+ expect(onRecordTask).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not allow SOP upload and task recording at the same time", async () => {
+ const onUploadSOP = vi.fn();
+ const onRecordTask = vi.fn();
+ const { rerender } = render(
+ <FeatureFlagContext.Provider value={() => false}>
+ <WorkflowCopilotChat
+ onUploadSOP={onUploadSOP}
+ canUploadSOP
+ onRecordTask={onRecordTask}
+ canRecordTask
+ isUploadingSOP
+ />
+ </FeatureFlagContext.Provider>,
+ );
+
+ await waitFor(() =>
+ expect(screen.getByText("Uploading SOP…")).toBeTruthy(),
+ );
+ const recordTaskButton = screen.getByRole("button", {
+ name: "Record task",
+ });
+ expect(recordTaskButton.hasAttribute("disabled")).toBe(true);
+ expect(recordTaskButton.parentElement?.getAttribute("tabindex")).toBe("0");
+ expect((textarea() as HTMLTextAreaElement).disabled).toBe(true);
+ expect(
+ (
+ screen.getByRole("button", {
+ name: "Send disabled — finish the current authoring action",
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+
+ rerender(
+ <FeatureFlagContext.Provider value={() => false}>
+ <WorkflowCopilotChat
+ onUploadSOP={onUploadSOP}
+ canUploadSOP={false}
+ onRecordTask={onRecordTask}
+ canRecordTask
+ />
+ </FeatureFlagContext.Provider>,
+ );
+
+ const uploadSOPButton = screen.getByRole("button", {
+ name: "Upload an SOP",
+ });
+ expect(uploadSOPButton.hasAttribute("disabled")).toBe(true);
+ expect(uploadSOPButton.parentElement?.getAttribute("tabindex")).toBe("0");
+ });
+
it("places the mic and send inside the container, with the mic to the right of the input", async () => {
await renderChat({ codeBlockMode: true });
const ta = textarea();
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx
index 2ff0523f3..2ecee4c35 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx
@@ -654,12 +654,20 @@ describe("WorkflowCopilotChat — credential card wiring", () => {
fireEvent.click(screen.getByRole("button", { name: "Skip for now" }));
});
await waitFor(() => expect(credentialResponsePosts()).toHaveLength(1));
- expect(credentialResponsePosts()[0]![1]).toMatchObject({
+ const skipBody = credentialResponsePosts()[0]![1] as Record<
+ string,
+ unknown
+ >;
+ expect(skipBody).toMatchObject({
turn_id: "turn-1",
workflow_copilot_chat_id: "chat-1",
resume_token: "rt-abc",
action: "skip",
});
+ expect(skipBody.credential_id).toBeUndefined();
+ expect(await screen.findByText(/Credential setup skipped/)).toBeTruthy();
+ expect(screen.queryByText(/Credential '.*' added/)).toBeNull();
+ expect(screen.queryByText(/Credential added/)).toBeNull();
});
it("connect with an existing matched credential POSTs the credential_id", async () => {
@@ -685,10 +693,25 @@ describe("WorkflowCopilotChat — credential card wiring", () => {
fireEvent.click(useButton);
});
await waitFor(() => expect(credentialResponsePosts()).toHaveLength(1));
- expect(credentialResponsePosts()[0]![1]).toMatchObject({
+ const pickBody = credentialResponsePosts()[0]![1] as Record<
+ string,
+ unknown
+ >;
+ expect(pickBody).toMatchObject({
+ turn_id: "turn-1",
+ workflow_copilot_chat_id: "chat-1",
+ resume_token: "rt-abc",
action: "connected",
credential_id: "cred-hn",
});
+ expect(Object.keys(pickBody).sort()).toEqual([
+ "action",
+ "credential_id",
+ "resume_token",
+ "turn_id",
+ "workflow_copilot_chat_id",
+ ]);
+ expect(postStreaming).toHaveBeenCalledTimes(1);
// Receipt keeps the credential name after the turn goes terminal.
await act(async () => {
streamCalls[0]!.onMessage({
@@ -781,6 +804,47 @@ describe("WorkflowCopilotChat — credential card wiring", () => {
expect(postStreaming).toHaveBeenCalledTimes(1);
});
+ it("sends one resume POST when a second pick races the first", async () => {
+ let releaseFirstPost = () => {};
+ sansApiPost.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ releaseFirstPost = () => resolve({});
+ }),
+ );
+ credentialsData.current = [
+ { credential_id: "cred-first", name: "first", tested_url: null },
+ { credential_id: "cred-second", name: "second", tested_url: null },
+ ];
+ 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(await screen.findByRole("combobox"));
+ });
+ await act(async () => {
+ fireEvent.click(await screen.findByRole("button", { name: "first" }));
+ });
+ await act(async () => {
+ fireEvent.click(await screen.findByRole("combobox"));
+ });
+ await act(async () => {
+ fireEvent.click(await screen.findByRole("button", { name: "second" }));
+ });
+ expect(credentialResponsePosts()).toHaveLength(1);
+ expect(credentialResponsePosts()[0]![1]).toMatchObject({
+ credential_id: "cred-first",
+ });
+ await act(async () => {
+ releaseFirstPost();
+ });
+ expect(credentialResponsePosts()).toHaveLength(1);
+ });
+
it("keeps the card actionable, toasts, and never logs the raw error (resume_token leak) when the resume POST fails", async () => {
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
// AxiosError-shaped: config.data carries the one-time resume_token.
@@ -826,10 +890,12 @@ describe("WorkflowCopilotChat — credential card wiring", () => {
await waitFor(() =>
expect(credentialsGets().length).toBeGreaterThanOrEqual(1),
);
- // Failed fetch → no picker (null, not a cached []); the Connect-credential CTA remains so the
- // user can still create one, and the pause stays answerable.
expect(
- await screen.findByRole("button", { name: "Connect credential" }),
+ await screen.findByText(/Couldn't load your saved logins/),
+ ).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
+ expect(
+ screen.getByRole("button", { name: "Connect credential" }),
).toBeTruthy();
expect(screen.queryByText("Use existing…")).toBeNull();
errSpy.mockRestore();
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx
index a3d742105..11f5611b9 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx
@@ -337,10 +337,10 @@ describe("WorkflowCopilotChat — run grounding bridge", () => {
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
expect(
- screen.getByText("Turning 2 recorded actions into a workflow"),
+ screen.getByText("Turning your task demonstration into a workflow"),
).toBeTruthy();
- expect(screen.getByText("Recording saved")).toBeTruthy();
- expect(screen.getByText("Recorded actions prepared")).toBeTruthy();
+ expect(screen.getByText("Task recording saved")).toBeTruthy();
+ expect(screen.getByText("Browser interactions prepared")).toBeTruthy();
expect(screen.getByText("Refining the workflow…")).toBeTruthy();
await act(async () => {
@@ -354,7 +354,7 @@ describe("WorkflowCopilotChat — run grounding bridge", () => {
});
expect(
- screen.getByText("Turning 2 recorded actions into a workflow"),
+ screen.getByText("Turning your task demonstration into a workflow"),
).toBeTruthy();
await act(async () => {
@@ -405,7 +405,7 @@ describe("WorkflowCopilotChat — run grounding bridge", () => {
});
expect(
- screen.getByText("Turning 1 recorded action into a workflow"),
+ screen.getByText("Turning your task demonstration into a workflow"),
).toBeTruthy();
expect(screen.queryByText("Workflow refinement stopped")).toBeNull();
@@ -436,7 +436,7 @@ describe("WorkflowCopilotChat — run grounding bridge", () => {
});
expect(
- screen.getByText("Turning 1 recorded action into a workflow"),
+ screen.getByText("Turning your task demonstration into a workflow"),
).toBeTruthy();
expect(screen.queryByText("Workflow ready to review")).toBeNull();
@@ -530,7 +530,7 @@ describe("WorkflowCopilotChat — run grounding bridge", () => {
);
expect(
- screen.getByText("Turning 1 recorded action into a workflow"),
+ screen.getByText("Turning your task demonstration into a workflow"),
).toBeTruthy();
expect(
screen.getByText(
@@ -966,7 +966,7 @@ describe("WorkflowCopilotChat — run grounding bridge", () => {
await vi.advanceTimersByTimeAsync(2_000);
});
expect(
- screen.getByText("Turning 2 recorded actions into a workflow"),
+ screen.getByText("Turning your task demonstration into a workflow"),
).toBeTruthy();
Object.assign(historyResponse.data, {
@@ -1021,7 +1021,7 @@ describe("WorkflowCopilotChat — run grounding bridge", () => {
streamCalls[0]?.reject(new Error("stream disconnected"));
});
expect(
- screen.getByText("Turning 1 recorded action into a workflow"),
+ screen.getByText("Turning your task demonstration into a workflow"),
).toBeTruthy();
await act(async () => {
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 9fe6c6510..a58a31d50 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -23,6 +23,7 @@ import {
ArrowUpIcon,
Pencil1Icon,
FileIcon,
+ UploadIcon,
PlusIcon,
ExclamationTriangleIcon,
} from "@radix-ui/react-icons";
@@ -899,6 +900,12 @@ interface WorkflowCopilotChatProps {
initialMessage?: string;
initialAction?: CopilotProductAction;
onInitialMessageConsumed?: () => void;
+ onUploadSOP?: (file: File) => void;
+ canUploadSOP?: boolean;
+ isUploadingSOP?: boolean;
+ onRecordTask?: () => void;
+ canRecordTask?: boolean;
+ authoringUnavailableReason?: string | null;
// Render as a docked panel (no float/drag/resize) instead of a floating window.
docked?: boolean;
// Render frameless — no border, background, or title; the header keeps only
@@ -999,10 +1006,21 @@ export function WorkflowCopilotChat({
initialMessage,
initialAction,
onInitialMessageConsumed,
+ onUploadSOP,
+ canUploadSOP = true,
+ isUploadingSOP = false,
+ onRecordTask,
+ canRecordTask = false,
+ authoringUnavailableReason,
docked = false,
chromeless = false,
portalTarget,
}: WorkflowCopilotChatProps = {}) {
+ const sopFileInputRef = useRef<HTMLInputElement>(null);
+ const recordingAuthoringActive = useRecordingStore(
+ (state) => state.isRecording || state.finishRequested || state.isCommitting,
+ );
+ const authoringInProgress = isUploadingSOP || recordingAuthoringActive;
const codeBlockModeFlag = useFeatureFlag("WORKFLOW_COPILOT_CODE_BLOCK_MODE");
const codeBlockAccessFlag = useFeatureFlag("CODE_BLOCK_ACCESS");
const codeBlockModeEnabled =
@@ -3570,6 +3588,7 @@ export function WorkflowCopilotChat({
const handleSend = useCallback(
async (messageOverride?: string, options: SendOptions = {}) => {
+ if (authoringInProgress) return;
const candidate = messageOverride ?? inputValue;
const pendingQuestion = questionInteractions.find(
(item) => item.status === "pending",
@@ -4850,6 +4869,7 @@ export function WorkflowCopilotChat({
applyStoredNarrativeEvent,
applyWorkflowUpdate,
armStop,
+ authoringInProgress,
autoAccept,
codeBlockModeEnabled,
codeBlockRequestOverride,
@@ -5022,7 +5042,7 @@ export function WorkflowCopilotChat({
};
useEffect(() => {
- if (!queuedPrompt || hasPendingQuestion) {
+ if (!queuedPrompt || hasPendingQuestion || authoringInProgress) {
return;
}
// isLoading (reactive state) is the in-flight signal here so the effect
@@ -5082,6 +5102,7 @@ export function WorkflowCopilotChat({
console.error("Queued send failed:", error);
});
}, [
+ authoringInProgress,
codeBlockModeEnabled,
codeBlockRequestOverride,
handleSend,
@@ -5436,26 +5457,29 @@ export function WorkflowCopilotChat({
);
const showsStopGlyph =
isStopping || (turnObservablyRunning && !hasComposerText);
+ const authoringBlocksComposerAction = authoringInProgress && !showsStopGlyph;
// Sent, no frame yet: the control reports the wait rather than an action, and
// cancelSend's own guard is what makes a press in this window issue no cancel.
const turnPendingFirstFrame =
isLoading && !turnObservablyRunning && narrative.terminal === null;
const morphButtonPending = turnPendingFirstFrame && !hasComposerText;
- const morphButtonLabel = isStopping
- ? "Stopping…"
- : waitingOnQueueOnly
- ? "Send disabled — waiting for live browser"
- : morphButtonPending
- ? "Starting…"
- : queuedPrompt && hasComposerText
- ? "Replace queued message"
- : !turnObservablyRunning
- ? isLoading
- ? "Queue for next turn"
- : "Send"
- : hasComposerText
- ? "Queue for next turn"
- : "Stop";
+ const morphButtonLabel = authoringBlocksComposerAction
+ ? "Send disabled — finish the current authoring action"
+ : isStopping
+ ? "Stopping…"
+ : waitingOnQueueOnly
+ ? "Send disabled — waiting for live browser"
+ : morphButtonPending
+ ? "Starting…"
+ : queuedPrompt && hasComposerText
+ ? "Replace queued message"
+ : !turnObservablyRunning
+ ? isLoading
+ ? "Queue for next turn"
+ : "Send"
+ : hasComposerText
+ ? "Queue for next turn"
+ : "Stop";
// Shared between the composer treatments so the two Build implementations
// never drift.
const modeMenuItems = (
@@ -5517,6 +5541,9 @@ export function WorkflowCopilotChat({
/>
);
+ const uploadSOPDisabled = !onUploadSOP || !canUploadSOP || isUploadingSOP;
+ const recordTaskDisabled = !onRecordTask || !canRecordTask || isUploadingSOP;
+
const content = (
<div
className={
@@ -5599,24 +5626,110 @@ export function WorkflowCopilotChat({
<div ref={scrollRef} className="h-full overflow-y-auto p-4">
<div className="space-y-3">
{!isLoadingHistory && messages.length === 0 && !isLoading ? (
- <div className="rounded-lg border border-border bg-slate-elevation2 p-4 text-sm text-muted-foreground">
- <p className="font-semibold text-foreground">
- Start a new chat
- </p>
- <p className="mt-2 text-muted-foreground">
- Ask the copilot to draft or edit your agent. Provide a goal,
- the target site, and any credentials it should use.
- </p>
- <p className="mt-2 text-muted-foreground">
- Example: "Build an agent to find the top post on hackernews
- today"
- </p>
- {/* The only in-product pointer to this: the newer composer
- placeholder dropped the "or paste recorded steps" clause, so
- without it here the affordance is undiscoverable. */}
- <p className="mt-2 text-muted-foreground">
- Already recorded this with another agent? Copy that workflow's
- prompt text and paste it here.
+ <div className="flex flex-col gap-5 rounded-lg border border-border bg-slate-elevation2 p-5 text-sm text-muted-foreground">
+ <div>
+ <p className="text-base font-semibold text-foreground">
+ Start a new chat
+ </p>
+ <p className="mt-2 leading-relaxed text-muted-foreground">
+ Ask Copilot to draft or edit your agent. Provide a goal, the
+ target site, and any credentials it should use.
+ </p>
+ <p className="mt-3 border-l-2 border-border bg-slate-elevation3 px-3 py-2 text-xs leading-relaxed text-muted-foreground">
+ Example: “Build an agent to find the top post on Hacker News
+ today.”
+ </p>
+ </div>
+
+ <div className="[container-name:copilot-actions] [container-type:inline-size]">
+ <p className="font-semibold text-foreground">
+ Or start from an existing process
+ </p>
+ <p className="mt-1 text-xs leading-relaxed text-muted-foreground">
+ Give Copilot the source material instead of describing it
+ from scratch.
+ </p>
+ <div className="mt-3 grid grid-cols-1 gap-2 [@container_copilot-actions_(min-width:440px)]:grid-cols-2">
+ <TooltipProvider>
+ <ControlTooltip
+ content={
+ uploadSOPDisabled
+ ? (authoringUnavailableReason ??
+ "SOP upload is not available right now")
+ : "Upload a procedure as a PDF"
+ }
+ blocked={uploadSOPDisabled}
+ side="top"
+ wrapperClassName="min-w-0 w-full"
+ >
+ <button
+ type="button"
+ aria-label="Upload an SOP"
+ className="flex w-full min-w-0 items-center gap-3 rounded-lg border border-border bg-slate-elevation3 p-3 text-left transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
+ disabled={uploadSOPDisabled}
+ onClick={() => sopFileInputRef.current?.click()}
+ >
+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-slate-elevation2">
+ <UploadIcon className="h-4 w-4" />
+ </span>
+ <span className="min-w-0">
+ <span className="block font-medium text-foreground">
+ {isUploadingSOP
+ ? "Uploading SOP…"
+ : "Upload an SOP"}
+ </span>
+ <span className="mt-0.5 block text-xs leading-snug text-muted-foreground">
+ Turn an existing procedure into workflow steps.
+ </span>
+ </span>
+ </button>
+ </ControlTooltip>
+ </TooltipProvider>
+ <TooltipProvider>
+ <ControlTooltip
+ content={
+ recordTaskDisabled
+ ? (authoringUnavailableReason ??
+ "Record task is available when the browser is ready")
+ : "Demonstrate the task in the browser"
+ }
+ blocked={recordTaskDisabled}
+ side="top"
+ wrapperClassName="min-w-0 w-full"
+ >
+ <button
+ type="button"
+ aria-label="Record task"
+ className="flex w-full min-w-0 items-center gap-3 rounded-lg border border-red-500/45 bg-red-500/[0.06] p-3 text-left transition-colors hover:bg-red-500/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
+ disabled={recordTaskDisabled}
+ onClick={onRecordTask}
+ >
+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-red-500/40 bg-red-500/10">
+ <span className="h-2.5 w-2.5 rounded-full bg-red-500" />
+ </span>
+ <span className="min-w-0">
+ <span className="block font-medium text-foreground">
+ Record task
+ </span>
+ <span className="mt-0.5 block text-xs leading-snug text-muted-foreground">
+ Demonstrate it in the browser and create workflow
+ steps.
+ </span>
+ </span>
+ </button>
+ </ControlTooltip>
+ </TooltipProvider>
+ </div>
+ <p className="mt-3 text-xs leading-relaxed text-muted-foreground">
+ Complete the task in the browser. Skyvern captures the
+ browser view and your clicks, typing, and navigation, then
+ turns them into workflow steps.
+ </p>
+ </div>
+
+ <p className="text-xs leading-relaxed text-muted-foreground">
+ Already recorded this with another agent? Copy that
+ workflow&apos;s prompt text and paste it here.
</p>
</div>
) : null}
@@ -6330,6 +6443,7 @@ export function WorkflowCopilotChat({
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={handleKeyPress}
+ disabled={authoringInProgress}
rows={1}
className="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"
style={{
@@ -6350,16 +6464,40 @@ export function WorkflowCopilotChat({
if (file) void uploadAttachment(file);
}}
/>
+ <input
+ ref={sopFileInputRef}
+ type="file"
+ accept=".pdf,application/pdf"
+ aria-label="Choose an SOP PDF"
+ className="hidden"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+ if (!file.name.toLowerCase().endsWith(".pdf")) {
+ toast({
+ variant: "destructive",
+ title: "Invalid file type",
+ description: "Please select a PDF file",
+ });
+ event.target.value = "";
+ return;
+ }
+ onUploadSOP?.(file);
+ event.target.value = "";
+ }}
+ />
<button
type="button"
onClick={() => attachmentInputRef.current?.click()}
// An answer to a pending question is sent through the question flow, which carries
// no files, so offering the control here would stage a file nothing can send.
- disabled={hasPendingQuestion}
+ disabled={hasPendingQuestion || authoringInProgress}
title={
- hasPendingQuestion
- ? "Answer the pending question before attaching a file"
- : "Attach a file"
+ authoringInProgress
+ ? "Finish the current authoring action before attaching a file"
+ : hasPendingQuestion
+ ? "Answer the pending question before attaching a file"
+ : "Attach a file"
}
aria-label="Attach a file"
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground transition hover:bg-accent hover:text-accent-foreground"
@@ -6370,6 +6508,7 @@ export function WorkflowCopilotChat({
isSupported={isSpeechSupported}
isListening={isSpeechListening}
isHearingSpeech={isSpeechHearing}
+ disabled={authoringInProgress && !isSpeechListening}
onToggle={toggleSpeech}
className="h-8 w-8 rounded-full border-0 bg-transparent"
iconClassName="h-3.5 w-3.5"
@@ -6377,11 +6516,15 @@ export function WorkflowCopilotChat({
<TooltipProvider>
<ControlTooltip
content={morphButtonLabel}
- blocked={waitingOnQueueOnly}
+ blocked={waitingOnQueueOnly || authoringBlocksComposerAction}
>
<button
type="button"
- disabled={waitingOnQueueOnly || isStopping}
+ disabled={
+ waitingOnQueueOnly ||
+ isStopping ||
+ authoringBlocksComposerAction
+ }
aria-busy={isStopping}
onClick={() =>
turnObservablyRunning && !hasComposerText
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts
index 0d8666010..c672163d0 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts
@@ -66,6 +66,15 @@ export const CREDENTIAL_REQUIRED_FRAME_MINIMAL: CredentialRequiredFrame = {
reason: "workflow_credential_inputs_unbound",
};
+// The shape a raw-secret ask actually reaches the card with: the supplied name was replaced by
+// the redaction upstream, so no ask text and no candidate ids survive to pin a suggestion.
+export const CREDENTIAL_REQUIRED_FRAME_REDACTED_ASK: CredentialRequiredFrame =
+ buildCredentialRequiredFrame({
+ reason: "raw_secret",
+ message: undefined,
+ credential_refs: undefined,
+ });
+
export const RESOLVED_OUTCOME_CONNECTED: CredentialPauseHistorical = {
outcome: "connected",
credentialId: "cred_hn",
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx
index 050373259..31583170d 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx
@@ -13,6 +13,7 @@ import {
CREDENTIAL_REQUIRED_FRAME_BY_REASON,
CREDENTIAL_REQUIRED_FRAME_MINIMAL,
CREDENTIAL_REQUIRED_FRAME_NO_MESSAGE,
+ CREDENTIAL_REQUIRED_FRAME_REDACTED_ASK,
RESOLVED_OUTCOME_CONNECTED,
RESOLVED_OUTCOME_CONNECTED_UNNAMED,
RESOLVED_OUTCOME_SKIPPED,
@@ -26,7 +27,7 @@ import {
type CredentialRequiredReason,
} from "./CredentialCard";
-const { getClientMock, credsData, credsFail } = vi.hoisted(() => {
+const { getClientMock, credsData, credsFail, clientGet } = vi.hoisted(() => {
const data = {
current: [] as Array<{
credential_id: string;
@@ -36,17 +37,29 @@ const { getClientMock, credsData, credsFail } = vi.hoisted(() => {
}>,
};
const fail = { current: false };
- const get = vi.fn((path: string) =>
- path === "/credentials"
- ? fail.current
- ? Promise.reject(new Error("network"))
- : Promise.resolve({ data: data.current })
- : Promise.resolve({ data: {} }),
+ // Stands in for the route's `search` param (case-insensitive across name and username) so a test
+ // can prove the picker's box reaches the server rather than filtering the fetched page.
+ const get = vi.fn(
+ (path: string, config?: { params?: { search?: string } }) => {
+ if (path !== "/credentials") return Promise.resolve({ data: {} });
+ if (fail.current) return Promise.reject(new Error("network"));
+ const term = config?.params?.search?.toLowerCase();
+ return Promise.resolve({
+ data: term
+ ? data.current.filter((credential) =>
+ `${credential.name} ${credential.credential?.username ?? ""}`
+ .toLowerCase()
+ .includes(term),
+ )
+ : data.current,
+ });
+ },
);
return {
getClientMock: vi.fn(() => Promise.resolve({ get })),
credsData: data,
credsFail: fail,
+ clientGet: get,
};
});
@@ -58,7 +71,22 @@ vi.mock("@/hooks/useCredentialGetter", () => ({
// Radix Popover + cmdk misbehave in jsdom (portals, pointer capture); stub them to plain wrappers so
// the picker's items render inline and are directly clickable, mirroring the Select mock below.
vi.mock("@/components/ui/popover", () => ({
- Popover: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ // Exposes onOpenChange as a clickable close, since the real dismissal is a Radix pointer gesture
+ // jsdom cannot perform. Nothing else about the card reads it.
+ Popover: ({
+ children,
+ onOpenChange,
+ }: {
+ children?: ReactNode;
+ onOpenChange?: (open: boolean) => void;
+ }) => (
+ <div>
+ <button type="button" onClick={() => onOpenChange?.(false)}>
+ close-popover
+ </button>
+ {children}
+ </div>
+ ),
PopoverTrigger: ({ children }: { children?: ReactNode }) => (
<div>{children}</div>
),
@@ -68,8 +96,20 @@ vi.mock("@/components/ui/popover", () => ({
}));
vi.mock("@/components/ui/command", () => ({
Command: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- CommandInput: ({ placeholder }: { placeholder?: string }) => (
- <input placeholder={placeholder} />
+ CommandInput: ({
+ placeholder,
+ value,
+ onValueChange,
+ }: {
+ placeholder?: string;
+ value?: string;
+ onValueChange?: (value: string) => void;
+ }) => (
+ <input
+ placeholder={placeholder}
+ value={value}
+ onChange={(event) => onValueChange?.(event.target.value)}
+ />
),
CommandList: ({ children }: { children?: ReactNode }) => (
<div>{children}</div>
@@ -325,7 +365,8 @@ describe("CredentialCard terminal org-credential picker", () => {
expect(onConnect).toHaveBeenCalledWith("cred_hn", "HN login");
});
- it("degrades to the Connect-credential CTA only when the org has no credentials", async () => {
+ it("says the list is loading while the fetch is in flight, CTA still usable", () => {
+ credsData.current = [{ credential_id: "cred_a", name: "Login A" }];
render(
<CredentialCard
frame={buildCredentialRequiredFrame()}
@@ -334,28 +375,169 @@ describe("CredentialCard terminal org-credential picker", () => {
onSkip={vi.fn()}
/>,
);
- await waitFor(() => expect(getClientMock).toHaveBeenCalled());
+ expect(screen.getByRole("status").textContent).toContain(
+ "Loading saved logins",
+ );
+ expect(screen.queryByRole("button", { name: "Login A" })).toBeNull();
+ expect(
+ screen
+ .getByRole("button", { name: "Connect credential" })
+ .hasAttribute("disabled"),
+ ).toBe(false);
+ });
+
+ it("leaves the announcement to a surrounding live region instead of nesting one", () => {
+ credsData.current = [{ credential_id: "cred_a", name: "Login A" }];
+ render(
+ <div role="status" aria-live="polite" data-testid="chat-live-region">
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />
+ </div>,
+ );
+ expect(screen.getByText(/Loading saved logins/)).toBeTruthy();
+ expect(screen.getAllByRole("status")).toHaveLength(1);
+ expect(screen.getByRole("status").dataset.testid).toBe("chat-live-region");
+ });
+
+ it("keeps its own live region for an inline pause restored outside the chat's", async () => {
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ credsFail.current = true;
+ // A pause restored after a reload renders beside, not inside, the chat's live region.
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ const liveRegion = screen.getByRole("status");
+ await waitFor(() =>
+ expect(liveRegion.textContent).toBe("Couldn't load your saved logins."),
+ );
+ expect(screen.getByRole("status")).toBe(liveRegion);
+ errSpy.mockRestore();
+ });
+
+ it("shows an empty org as empty — no error, no loading text, creation still offered", async () => {
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="terminal"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ await waitFor(() =>
+ expect(screen.getByRole("status").textContent).toBe(""),
+ );
expect(
screen.getByRole("button", { name: "Connect credential" }),
).toBeTruthy();
expect(screen.queryByRole("combobox")).toBeNull();
+ expect(screen.queryByText(/Couldn't load your saved logins/)).toBeNull();
});
- it("degrades to the CTA when the fetch fails, without caching an empty list", async () => {
+ it("shows a failed fetch as failed, and Retry recovers to a usable picker", async () => {
+ const onConnect = vi.fn();
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
credsFail.current = true;
render(
<CredentialCard
frame={buildCredentialRequiredFrame()}
mode="terminal"
- onConnect={vi.fn()}
+ onConnect={onConnect}
onSkip={vi.fn()}
/>,
);
- await waitFor(() => expect(getClientMock).toHaveBeenCalled());
+ // Captured before the fetch settles: a live region is only announced when it was already in the
+ // tree when its text changed, so the failure must land in this same element.
+ const liveRegion = screen.getByRole("status");
+ expect(
+ await screen.findByText(/Couldn't load your saved logins/, {
+ selector: ":not(.sr-only)",
+ }),
+ ).toBeTruthy();
+ expect(screen.getByRole("status")).toBe(liveRegion);
+ expect(liveRegion.textContent).toBe("Couldn't load your saved logins.");
expect(
screen.getByRole("button", { name: "Connect credential" }),
).toBeTruthy();
expect(screen.queryByRole("combobox")).toBeNull();
+ // The AxiosError-shaped rejection serializes credentials into console output otherwise.
+ const logged = errSpy.mock.calls.find((call) =>
+ String(call[0]).includes("Failed to load credentials"),
+ );
+ expect(typeof logged![1]).toBe("string");
+ errSpy.mockRestore();
+
+ credsFail.current = false;
+ credsData.current = [
+ { credential_id: "cred_recovered", name: "Recovered" },
+ ];
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Recovered" }));
+ expect(onConnect).toHaveBeenCalledWith("cred_recovered", "Recovered");
+ expect(screen.queryByText(/Couldn't load your saved logins/)).toBeNull();
+ });
+
+ it("disables Retry once the inline pause has expired", async () => {
+ credsFail.current = true;
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame({
+ expires_at: new Date(Date.now() - 1000).toISOString(),
+ })}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ const retry = await screen.findByRole("button", { name: "Retry" });
+ expect(retry.hasAttribute("disabled")).toBe(true);
+ expect(
+ screen
+ .getByRole("button", { name: "Connect credential" })
+ .hasAttribute("disabled"),
+ ).toBe(true);
+ });
+
+ it("offers an explicitly listed credential even when the ask carries no candidate ids", async () => {
+ const onConnect = vi.fn();
+ credsData.current = [
+ { credential_id: "cred_listed", name: "Listed login" },
+ ];
+ render(
+ <CredentialCard
+ frame={CREDENTIAL_REQUIRED_FRAME_REDACTED_ASK}
+ mode="inline-pause"
+ onConnect={onConnect}
+ onSkip={vi.fn()}
+ />,
+ );
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Listed login" }),
+ );
+ expect(onConnect).toHaveBeenCalledWith("cred_listed", "Listed login");
+ });
+
+ it("never picks a sole credential on the user's behalf", async () => {
+ const onConnect = vi.fn();
+ credsData.current = [{ credential_id: "cred_only", name: "Only login" }];
+ render(
+ <CredentialCard
+ frame={CREDENTIAL_REQUIRED_FRAME_REDACTED_ASK}
+ mode="inline-pause"
+ onConnect={onConnect}
+ onSkip={vi.fn()}
+ />,
+ );
+ await screen.findByRole("button", { name: "Only login" });
+ expect(onConnect).not.toHaveBeenCalled();
});
it("does not fetch for a terminal receipt (resolved outcome)", () => {
@@ -427,6 +609,324 @@ describe("CredentialCard terminal org-credential picker", () => {
expect(await screen.findByText("New login")).toBeTruthy();
});
+ it("keeps a loaded picker when a re-fetch fails instead of falling back to create-only", async () => {
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ credsData.current = [{ credential_id: "cred_kept", name: "Kept login" }];
+ const { rerender } = render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ reloadKey={0}
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(await screen.findByText("Kept login")).toBeTruthy();
+
+ credsFail.current = true;
+ rerender(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ reloadKey={1}
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ await waitFor(() =>
+ expect(
+ errSpy.mock.calls.some((call) =>
+ String(call[0]).includes("Failed to load credentials"),
+ ),
+ ).toBe(true),
+ );
+ expect(screen.getByText("Kept login")).toBeTruthy();
+ expect(screen.queryByText(/Couldn't load your saved logins/)).toBeNull();
+ errSpy.mockRestore();
+ });
+
+ it("searches the server rather than the fetched page, so a login past the page cap is reachable", async () => {
+ credsData.current = [{ credential_id: "cred_page1", name: "On page one" }];
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(await screen.findByText("On page one")).toBeTruthy();
+
+ // Stands for a credential the org owns beyond the 100 the unpaginated fetch returns: it is
+ // absent from the rendered page and only a server-side search can surface it.
+ credsData.current = [
+ { credential_id: "cred_beyond", name: "Beyond the cap" },
+ ];
+ fireEvent.change(screen.getByPlaceholderText("Search credentials..."), {
+ target: { value: "beyond" },
+ });
+ expect(await screen.findByText("Beyond the cap")).toBeTruthy();
+ expect(clientGet).toHaveBeenCalledWith(
+ "/credentials",
+ expect.objectContaining({
+ params: expect.objectContaining({ search: "beyond" }),
+ }),
+ );
+ });
+
+ it("caps the search box at the route's limit, so the rows never answer a hidden prefix", async () => {
+ credsData.current = [{ credential_id: "cred_a", name: "Acme login" }];
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(await screen.findByText("Acme login")).toBeTruthy();
+
+ // The route caps search at 200 characters, so an unclamped paste 422s into a failure whose
+ // Retry re-sends the same rejected term and can never succeed. Clamping only the request would
+ // instead leave the box showing 250 characters while the rows answered the first 200 — with
+ // local filtering off, those rows read as matching the whole visible term.
+ const box = screen.getByPlaceholderText(
+ "Search credentials...",
+ ) as HTMLInputElement;
+ fireEvent.change(box, { target: { value: "z".repeat(250) } });
+ expect(box.value).toHaveLength(200);
+ await waitFor(() =>
+ expect(
+ clientGet.mock.calls.some(
+ (call) =>
+ (call[1] as { params?: { search?: string } })?.params?.search
+ ?.length === 200,
+ ),
+ ).toBe(true),
+ );
+ expect(
+ clientGet.mock.calls.every(
+ (call) =>
+ ((call[1] as { params?: { search?: string } })?.params?.search ?? "")
+ .length <= 200,
+ ),
+ ).toBe(true);
+
+ // The route counts code points, and an emoji is two UTF-16 units. Clamping by units would keep
+ // half of it, which Axios cannot URL-encode, so the search would fail on every Retry.
+ const atLimit = "a".repeat(199) + "😀";
+ fireEvent.change(box, { target: { value: `${atLimit}b` } });
+ expect(box.value).toBe(atLimit);
+ expect(Array.from(box.value)).toHaveLength(200);
+ });
+
+ it("says when a full page of matches hides the rest instead of reading as the complete set", async () => {
+ credsData.current = Array.from({ length: 100 }, (_unused, index) => ({
+ credential_id: `cred_${index}`,
+ name: `Login ${index}`,
+ }));
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(await screen.findByText("Login 0")).toBeTruthy();
+ expect(screen.getByText(/Showing the first 100/)).toBeTruthy();
+
+ credsData.current = credsData.current.slice(0, 99);
+ fireEvent.change(screen.getByPlaceholderText("Search credentials..."), {
+ target: { value: "Login" },
+ });
+ await waitFor(() =>
+ expect(screen.queryByText(/Showing the first 100/)).toBeNull(),
+ );
+ });
+
+ it("drops a zero-match term when the popover closes, so the add-credential route comes back", async () => {
+ credsData.current = [
+ { credential_id: "cred_other", name: "Other login" },
+ { credential_id: "cred_work", name: "Work login" },
+ ];
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="auto-bound"
+ autoBound={{ credentialId: "cred_work", name: "Work login" }}
+ canChange
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(
+ await screen.findByRole("button", { name: "Other login" }),
+ ).toBeTruthy();
+ fireEvent.change(screen.getByPlaceholderText("Search credentials..."), {
+ target: { value: "nothing-matches-this" },
+ });
+ expect(await screen.findByText("No credentials found.")).toBeTruthy();
+
+ // A term left behind keeps the card in search mode over an empty result, which on this receipt
+ // hides both the remaining logins and the only route to the add-credential modal and Retry.
+ fireEvent.click(screen.getByRole("button", { name: "close-popover" }));
+ expect(
+ await screen.findByRole("button", { name: "Other login" }),
+ ).toBeTruthy();
+ expect(
+ (screen.getByPlaceholderText("Search credentials...") as HTMLInputElement)
+ .value,
+ ).toBe("");
+ });
+
+ it("keeps the picker in place while a cleared search reloads, and offers Retry if that reload fails", async () => {
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ credsData.current = [
+ { credential_id: "cred_acme", name: "Acme login" },
+ { credential_id: "cred_other", name: "Other login" },
+ ];
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ const box = await screen.findByPlaceholderText("Search credentials...");
+ fireEvent.change(box, { target: { value: "acme" } });
+ expect(await screen.findByText("Acme login")).toBeTruthy();
+
+ // Erasing the term searches for the empty one. The picker must not vanish mid-edit while that
+ // reload is in flight, which would close the dropdown and drop focus.
+ credsFail.current = true;
+ fireEvent.change(box, { target: { value: "" } });
+ expect(screen.getByPlaceholderText("Search credentials...")).toBeTruthy();
+
+ // A failed reset leaves the rows answering "acme" while the box is empty, so it has to say so
+ // and stay recoverable — otherwise the picker never returns and creation is the only option.
+ expect(
+ await screen.findByText(/Couldn't run that search/, {
+ selector: ":not(.sr-only)",
+ }),
+ ).toBeTruthy();
+ expect(screen.getByPlaceholderText("Search credentials...")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Acme login" })).toBeNull();
+
+ credsFail.current = false;
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ expect(await screen.findByText("Other login")).toBeTruthy();
+ expect(screen.getByText("Acme login")).toBeTruthy();
+ expect(screen.queryByText(/Couldn't run that search/)).toBeNull();
+ errSpy.mockRestore();
+ });
+
+ it("trims the term before searching, so padding neither misses a match nor empties the list", async () => {
+ credsData.current = [{ credential_id: "cred_acme", name: "Acme login" }];
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(await screen.findByText("Acme login")).toBeTruthy();
+
+ // The route builds its ILIKE pattern from the literal value, so an untrimmed " Acme " would
+ // match nothing despite the credential existing.
+ const box = screen.getByPlaceholderText("Search credentials...");
+ fireEvent.change(box, { target: { value: " Acme " } });
+ expect(await screen.findByText("Acme login")).toBeTruthy();
+ expect(clientGet).toHaveBeenCalledWith(
+ "/credentials",
+ expect.objectContaining({
+ params: expect.objectContaining({ search: "Acme" }),
+ }),
+ );
+
+ // An all-space term is no term: it must not be sent as a pattern that matches almost nothing.
+ fireEvent.change(box, { target: { value: " " } });
+ expect(await screen.findByText("Acme login")).toBeTruthy();
+ expect(clientGet).not.toHaveBeenCalledWith(
+ "/credentials",
+ expect.objectContaining({
+ params: expect.objectContaining({ search: " " }),
+ }),
+ );
+ });
+
+ it("offers nothing to pick while a typed search is still in flight", async () => {
+ const onConnect = vi.fn();
+ credsData.current = [{ credential_id: "cred_other", name: "Other login" }];
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={onConnect}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(await screen.findByText("Other login")).toBeTruthy();
+
+ // Typing leaves the previous rows on hand until the debounce and the request complete. While
+ // that is true they answer a different term, and cmdk highlights the first row, so Enter would
+ // resume the turn with a login the user never searched for.
+ fireEvent.change(screen.getByPlaceholderText("Search credentials..."), {
+ target: { value: "acme" },
+ });
+ expect(screen.getByText("Searching…")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Other login" })).toBeNull();
+ expect(onConnect).not.toHaveBeenCalled();
+
+ credsData.current = [{ credential_id: "cred_acme", name: "Acme login" }];
+ fireEvent.click(await screen.findByRole("button", { name: "Acme login" }));
+ expect(onConnect).toHaveBeenCalledWith("cred_acme", "Acme login");
+ expect(screen.queryByText("Searching…")).toBeNull();
+ });
+
+ it("withdraws the previous rows when a search fails, rather than offering them as its result", async () => {
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ credsData.current = [{ credential_id: "cred_stale", name: "Earlier row" }];
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(await screen.findByText("Earlier row")).toBeTruthy();
+ const liveRegion = screen.getByRole("status");
+
+ credsFail.current = true;
+ fireEvent.change(screen.getByPlaceholderText("Search credentials..."), {
+ target: { value: "acme" },
+ });
+ expect(
+ await screen.findByText(/Couldn't run that search/, {
+ selector: ":not(.sr-only)",
+ }),
+ ).toBeTruthy();
+ // The visible notice renders in the portaled popover, outside any live region, so focus in the
+ // search box would otherwise hear nothing. The card's own region, mounted earlier, carries it.
+ expect(screen.getByRole("status")).toBe(liveRegion);
+ expect(liveRegion.textContent).toBe("Couldn't run that search.");
+ // The earlier row answered a different query, so it is no longer offered — nothing selectable
+ // can submit a login the user did not search for. The term stays put and retryable.
+ expect(screen.queryByText("Earlier row")).toBeNull();
+ expect(screen.queryByText("No credentials found.")).toBeNull();
+ expect(screen.getByPlaceholderText("Search credentials...")).toBeTruthy();
+
+ credsFail.current = false;
+ credsData.current = [{ credential_id: "cred_acme", name: "Acme login" }];
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ expect(await screen.findByText("Acme login")).toBeTruthy();
+ expect(screen.queryByText(/Couldn't run that search/)).toBeNull();
+ errSpy.mockRestore();
+ });
+
it("pins the frame's credential_refs under a Suggested group, full list still complete", async () => {
credsData.current = [
{ credential_id: "cred_sug", name: "Suggested login" },
@@ -995,8 +1495,6 @@ describe("CredentialCard auto-bound receipt", () => {
it("keeps Change reachable when the credential list fails to load", async () => {
const onConnect = vi.fn();
- // A transient /credentials failure leaves the list null; Change must not vanish (alternates may
- // exist) — it falls back to the add-credential path so the auto-bound pick stays correctable.
credsFail.current = true;
render(
<CredentialCard
@@ -1012,4 +1510,67 @@ describe("CredentialCard auto-bound receipt", () => {
fireEvent.click(await screen.findByRole("button", { name: "Change" }));
expect(onConnect).toHaveBeenCalledWith(undefined);
});
+
+ it("says a failed load once when the receipt sits inside the chat's live region", async () => {
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ credsFail.current = true;
+ // The chat renders this receipt inside each message's role="status" wrapper, which already
+ // announces the visible sentence; a hidden copy would make it heard twice.
+ render(
+ <div role="status" aria-live="polite">
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="auto-bound"
+ autoBound={{ credentialId: "cred_work", name: "Work login" }}
+ canChange
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />
+ </div>,
+ );
+ await screen.findByRole("button", { name: "Retry" });
+ expect(
+ screen.getAllByText("Couldn't load your other saved logins."),
+ ).toHaveLength(1);
+ expect(screen.getAllByRole("status")).toHaveLength(1);
+ errSpy.mockRestore();
+ });
+
+ it("recovers the Change picker from a failed list fetch via Retry", async () => {
+ const onConnect = vi.fn();
+ credsFail.current = true;
+ credsData.current = [
+ { credential_id: "cred_other", name: "Other login" },
+ { credential_id: "cred_work", name: "Work login" },
+ ];
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="auto-bound"
+ autoBound={{ credentialId: "cred_work", name: "Work login" }}
+ canChange
+ onConnect={onConnect}
+ onSkip={vi.fn()}
+ />,
+ );
+ // Captured before the fetch settles, so the announcement must change this element's text rather
+ // than arrive in a freshly mounted one that screen readers would not announce.
+ const liveRegion = screen.getByRole("status");
+ expect(liveRegion.textContent).toBe("");
+ const retry = await screen.findByRole("button", { name: "Retry" });
+ expect(
+ screen.getByText("Couldn't load your other saved logins.", {
+ selector: ":not(.sr-only)",
+ }),
+ ).toBeTruthy();
+ expect(screen.getByRole("status")).toBe(liveRegion);
+ expect(liveRegion.textContent).toBe(
+ "Couldn't load your other saved logins.",
+ );
+ credsFail.current = false;
+ fireEvent.click(retry);
+ fireEvent.click(await screen.findByRole("button", { name: "Change" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Other login" }));
+ expect(onConnect).toHaveBeenCalledWith("cred_other", "Other login");
+ });
});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx
index 0be763e12..aa71b4623 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx
@@ -1,9 +1,10 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import {
ChevronDownIcon,
Cross2Icon,
LockClosedIcon,
} from "@radix-ui/react-icons";
+import { useDebounce } from "use-debounce";
import { getClient } from "@/api/AxiosClient";
import { isPasswordCredential, type CredentialApiResponse } from "@/api/types";
@@ -70,6 +71,13 @@ interface PickerCredential {
secondary?: string;
}
+type OrgCredentialList =
+ | { status: "loading" }
+ | { status: "error" }
+ // forSearch is the term these rows answer, so the picker can tell whether they still answer the
+ // one in the box. Offering rows fetched for an earlier term lets Enter submit an unrelated login.
+ | { status: "ready"; credentials: PickerCredential[]; forSearch: string };
+
export interface CredentialCardProps {
frame: CredentialRequiredFrame;
mode: CredentialCardMode;
@@ -117,6 +125,28 @@ export const CREDENTIAL_WHY_LINE_BY_REASON: Record<
"You held off on this earlier — connect a credential now so the workflow can sign in when it runs.",
};
+// Mirrors the credentials route: it caps `search` at 200 characters and pages at 100. A longer term
+// is rejected outright, leaving a Retry that can never succeed.
+const CREDENTIAL_SEARCH_MAX = 200;
+const CREDENTIAL_PAGE_SIZE = 100;
+
+// The box itself is capped, not just the term sent to the route: searching a silent prefix of a
+// longer visible term offers rows that its hidden characters exclude. Counted in code points, as
+// the route's length check is; slicing UTF-16 units can halve an emoji, which Axios cannot encode.
+function clampSearch(term: string): string {
+ return Array.from(term).slice(0, CREDENTIAL_SEARCH_MAX).join("");
+}
+
+// Applied to both the request and every comparison against it — trimming one side only would leave
+// forSearch and the live term permanently unequal on a padded query.
+function normalizeSearch(term: string): string {
+ return term.trim();
+}
+
+const LIVE_REGION_SELECTOR =
+ '[aria-live]:not([aria-live="off"]), [role="status"], [role="log"], [role="alert"]';
+const SEARCH_FAILED_ANNOUNCEMENT = "Couldn't run that search.";
+
const SKIP_COPY =
"Credential setup skipped — test run may stop at the login step";
const TIMEOUT_COPY =
@@ -206,6 +236,12 @@ function CredentialPicker({
suggestedIds,
disabled,
onPick,
+ search,
+ onSearchChange,
+ searchFailed,
+ searchPending,
+ resultsTruncated,
+ onRetrySearch,
triggerLabel = "Use existing…",
triggerClassName = "h-6 w-[200px] justify-between px-3 text-xs font-normal",
// Popover content matches the trigger width by default; a content-width trigger (e.g. "Change")
@@ -218,6 +254,18 @@ function CredentialPicker({
suggestedIds?: string[];
disabled?: boolean;
onPick: (credentialId: string, name: string) => void;
+ // The org list is one unpaginated page, so searching it reaches the server and cmdk's own filter
+ // is off: it would re-filter a server result on a narrower field set and hide matched rows.
+ search: string;
+ onSearchChange: (search: string) => void;
+ // The rows below are the previous query's result when a search fails, so the list says so instead
+ // of letting them stand as the answer.
+ searchFailed: boolean;
+ // True while the rows on hand answer an earlier term than the one in the box.
+ searchPending: boolean;
+ // The response filled a whole page, so there may be more matches than are listed.
+ resultsTruncated: boolean;
+ onRetrySearch: () => void;
triggerLabel?: string;
triggerClassName?: string;
contentClassName?: string;
@@ -250,7 +298,18 @@ function CredentialPicker({
</CommandItem>
);
return (
- <Popover open={open && !disabled} onOpenChange={setOpen}>
+ <Popover
+ open={open && !disabled}
+ onOpenChange={(nextOpen) => {
+ setOpen(nextOpen);
+ // Closing drops the term, as CredentialCombobox does. A zero-match term left behind keeps
+ // the card in search mode, and on the auto-bound receipt that hides its only route to
+ // adding a credential.
+ if (!nextOpen) {
+ onSearchChange("");
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
type="button"
@@ -265,10 +324,37 @@ function CredentialPicker({
</Button>
</PopoverTrigger>
<PopoverContent className={`${contentClassName} p-0`} align="start">
- <Command>
- <CommandInput placeholder="Search credentials..." />
+ <Command shouldFilter={false}>
+ <CommandInput
+ placeholder="Search credentials..."
+ value={search}
+ onValueChange={onSearchChange}
+ />
<CommandList>
- <CommandEmpty>No credentials found.</CommandEmpty>
+ {searchFailed ? (
+ <div className="px-2 py-1.5 text-[11px] leading-relaxed text-muted-foreground">
+ Couldn&apos;t run that search.{" "}
+ <button
+ type="button"
+ onClick={onRetrySearch}
+ className="font-medium text-foreground underline"
+ >
+ Retry
+ </button>
+ </div>
+ ) : searchPending ? (
+ <div className="px-2 py-1.5 text-[11px] text-muted-foreground">
+ Searching…
+ </div>
+ ) : (
+ <CommandEmpty>No credentials found.</CommandEmpty>
+ )}
+ {resultsTruncated && !searchPending && !searchFailed ? (
+ <div className="px-2 py-1.5 text-[11px] leading-relaxed text-muted-foreground">
+ Showing the first {CREDENTIAL_PAGE_SIZE}. Narrow the search if
+ yours isn&apos;t listed.
+ </div>
+ ) : null}
{suggested.length > 0 ? (
// Copilot's suggestion(s) pinned first; cmdk highlights the first item, so one Enter
// accepts it. The full org list stays below to override.
@@ -311,17 +397,38 @@ export function CredentialCard({
const disabled = countdownActive && expired;
const credentialGetter = useCredentialGetter();
- const [orgCredentials, setOrgCredentials] = useState<
- PickerCredential[] | null
- >(null);
+ const [orgCredentials, setOrgCredentials] = useState<OrgCredentialList>({
+ status: "loading",
+ });
+ const [retryKey, setRetryKey] = useState(0);
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search, 300);
+ // The route builds its ILIKE pattern from the literal value, so " Acme " matches no credential
+ // named "Acme" and an all-space term matches almost nothing. Trimmed once here and used for the
+ // request, the fetch dependency and forSearch alike, matching CredentialCombobox.
+ const searchTerm = normalizeSearch(debouncedSearch);
+ // Which term's fetch failed, rather than a bare "a search failed": clearing the box searches for
+ // the empty term, and a boolean keyed on a non-empty term reads that failure as no failure, which
+ // leaves the rows permanently out of step with the box and the picker gone with no way back.
+ const [failedSearch, setFailedSearch] = useState<string | null>(null);
+ // Read from the page rather than inferred from `mode`: an inline pause restored after a reload
+ // renders outside the chat's live region, so the mode alone cannot say whether one surrounds us.
+ const rootRef = useRef<HTMLDivElement>(null);
+ const [insideLiveRegion, setInsideLiveRegion] = useState(false);
+ useLayoutEffect(() => {
+ setInsideLiveRegion(
+ Boolean(rootRef.current?.parentElement?.closest(LIVE_REGION_SELECTOR)),
+ );
+ }, []);
const fetchGeneration = useRef(0);
// Any credential ask (terminal or inline-pause) lists every org login credential so the user can
// pick or create. credential_type=password since the card only ever asks for a sign-in; the API
// returns them most-recent-first (created_at desc), used as-is. Direct getClient fetch, not
// useCredentialsQuery: the copilot chat's test harness has no QueryClientProvider. Re-fetches when
// the parent bumps reloadKey (a credential was just created) so the new one appears in the picker.
- // page_size 100 with no pagination — a >100-credential org shows only the 100 most-recent; older
- // ones are reachable only by creating a new credential. Add the route's `search` param if that bites.
+ // page_size 100 with no pagination, so the picker's search goes to the route's `search` param
+ // rather than filtering the page locally: a >100-credential org would otherwise get a confident
+ // empty result for a login it owns.
const isAsk = !resolvedOutcome;
// An auto-bound receipt only needs the org list when its Change affordance is live; a read-only
// scrollback receipt must not each fire its own 100-credential fetch.
@@ -335,29 +442,89 @@ export function CredentialCard({
try {
const client = await getClient(credentialGetter);
const res = await client.get<CredentialApiResponse[]>("/credentials", {
- params: { page: 1, page_size: 100, credential_type: "password" },
+ params: {
+ page: 1,
+ page_size: CREDENTIAL_PAGE_SIZE,
+ credential_type: "password",
+ ...(searchTerm ? { search: searchTerm } : {}),
+ },
});
if (fetchGeneration.current !== generation) return;
- setOrgCredentials(
- (Array.isArray(res.data) ? res.data : []).map((credential) => ({
- credentialId: credential.credential_id,
- name: credential.name,
- secondary:
- credential.credential &&
- isPasswordCredential(credential.credential)
- ? credential.credential.username
- : undefined,
- })),
- );
+ setFailedSearch(null);
+ setOrgCredentials({
+ status: "ready",
+ forSearch: searchTerm,
+ credentials: (Array.isArray(res.data) ? res.data : []).map(
+ (credential) => ({
+ credentialId: credential.credential_id,
+ name: credential.name,
+ secondary:
+ credential.credential &&
+ isPasswordCredential(credential.credential)
+ ? credential.credential.username
+ : undefined,
+ }),
+ ),
+ });
} catch (error) {
- // Leave the list null so the picker degrades to the Connect-credential CTA; null keeps
- // not-loaded distinct from a genuinely empty org.
if (fetchGeneration.current === generation) {
- console.error("Failed to load credentials:", error);
+ // A failed re-fetch (reloadKey bumped, canChange flipped, a search) must keep a list the
+ // user can already pick from; only a fetch with nothing to show becomes the error state.
+ setOrgCredentials((current) =>
+ current.status === "ready" ? current : { status: "error" },
+ );
+ setFailedSearch(searchTerm);
+ // Log only the message: an AxiosError serializes its request config into the console.
+ console.error(
+ "Failed to load credentials:",
+ error instanceof Error ? error.message : String(error),
+ );
}
}
})();
- }, [needsCredentialList, reloadKey, credentialGetter]);
+ }, [needsCredentialList, reloadKey, retryKey, searchTerm, credentialGetter]);
+
+ const retryCredentialList = () => {
+ setOrgCredentials({ status: "loading" });
+ setRetryKey((key) => key + 1);
+ };
+ // Re-runs the current term without dropping to "loading": that would unmount the picker the user
+ // is typing in, along with the term itself.
+ const retrySearch = () => setRetryKey((key) => key + 1);
+ const changeSearch = (term: string) => setSearch(clampSearch(term));
+
+ // The picker offers only rows that answer the term now in the box. A row fetched for an earlier
+ // term is offered neither while the next request is in flight (cmdk highlights the first row, so
+ // Enter would submit an unrelated login) nor after a failed one.
+ const readyList =
+ orgCredentials.status === "ready" ? orgCredentials.credentials : [];
+ const searchPending =
+ orgCredentials.status === "ready" &&
+ orgCredentials.forSearch !== normalizeSearch(search);
+ // Only while the box still holds the failed term (typing past it is a new search, not a standing
+ // complaint about an abandoned one) AND the rows do not already answer it: a re-fetch that failed
+ // over rows already matching the box left nothing stale, so it stays a log line.
+ const searchFailed =
+ searchPending &&
+ failedSearch !== null &&
+ failedSearch === normalizeSearch(search);
+ const pickable = searchPending ? [] : readyList;
+ // A full page means the route had more to give, so the list says so rather than reading as the
+ // complete set of matches.
+ const resultsTruncated = pickable.length >= CREDENTIAL_PAGE_SIZE;
+ // Mounted whenever the picker is mid-search, not only when it has rows: unmounting on an empty
+ // interim result closes the dropdown and drops the user's focus mid-edit.
+ const pickerEngaged = Boolean(search) || searchPending || searchFailed;
+ const retryButton = (
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={retryCredentialList}
+ className="rounded-md border border-border px-2 py-1 text-xs font-medium text-foreground hover:bg-accent disabled:pointer-events-none disabled:opacity-50"
+ >
+ Retry
+ </button>
+ );
if (resolvedOutcome) {
switch (resolvedOutcome.outcome) {
@@ -401,13 +568,16 @@ export function CredentialCard({
if (mode === "auto-bound" && autoBound) {
// Change re-picks only OTHER credentials (re-picking the bound one fires a redundant continuation).
- // When none are pickable yet — list still loading, fetch failed, or the bound one is the org's only
- // credential — fall back to adding a new credential so a correction is always reachable.
- const others = (orgCredentials ?? []).filter(
+ // When none are pickable — still loading, or the bound one is the org's only credential — fall back
+ // to adding a new credential; a failed fetch also offers Retry so other saved logins stay reachable.
+ const others = pickable.filter(
(credential) => credential.credentialId !== autoBound.credentialId,
);
return (
- <div className="rounded-lg border border-border bg-slate-elevation2 p-3">
+ <div
+ ref={rootRef}
+ className="rounded-lg border border-border bg-slate-elevation2 p-3"
+ >
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2 text-xs font-semibold text-foreground">
<span aria-hidden="true">🔑</span>
@@ -416,10 +586,18 @@ export function CredentialCard({
</span>
</div>
{canChange ? (
- others.length > 0 ? (
+ // An active search stays mounted on zero results: unmounting the picker would discard
+ // the term the user is still typing and read as "you own nothing by that name".
+ others.length > 0 || pickerEngaged ? (
<CredentialPicker
credentials={others}
onPick={(credentialId, name) => onConnect(credentialId, name)}
+ search={search}
+ onSearchChange={changeSearch}
+ searchFailed={searchFailed}
+ searchPending={searchPending}
+ resultsTruncated={resultsTruncated}
+ onRetrySearch={retrySearch}
triggerLabel="Change"
triggerClassName="h-6 gap-1 px-2 text-xs font-medium"
contentClassName="w-[240px]"
@@ -441,6 +619,29 @@ export function CredentialCard({
? "Auto-selected to sign in on your behalf — Change it if this isn't right."
: "Auto-selected to sign in on your behalf."}
</p>
+ {canChange && orgCredentials.status === "error" ? (
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <span className="text-xs text-muted-foreground">
+ Couldn&apos;t load your other saved logins.
+ </span>
+ {retryButton}
+ </div>
+ ) : null}
+ {/* Mounted for the card's lifetime so only its text changes: a live region that appears
+ already holding its text is read as ordinary new content and never announced. It carries
+ the search failure too, whose visible text sits in a portaled popover no region reaches. */}
+ <span
+ className="sr-only"
+ role={insideLiveRegion ? undefined : "status"}
+ >
+ {searchFailed
+ ? SEARCH_FAILED_ANNOUNCEMENT
+ : !insideLiveRegion &&
+ canChange &&
+ orgCredentials.status === "error"
+ ? "Couldn't load your other saved logins."
+ : ""}
+ </span>
</div>
);
}
@@ -448,7 +649,7 @@ export function CredentialCard({
const site = siteFromLoginPageUrls(frame.login_page_urls);
return (
- <div>
+ <div ref={rootRef}>
{frame.message ? (
<p className="text-sm leading-relaxed text-foreground">
{frame.message}
@@ -510,14 +711,52 @@ export function CredentialCard({
>
Connect credential
</button>
- {orgCredentials && orgCredentials.length > 0 ? (
+ {orgCredentials.status === "ready" &&
+ (pickable.length > 0 || pickerEngaged) ? (
<CredentialPicker
- credentials={orgCredentials}
+ credentials={pickable}
suggestedIds={frame.credential_refs}
disabled={disabled}
onPick={(credentialId, name) => onConnect(credentialId, name)}
+ search={search}
+ onSearchChange={changeSearch}
+ searchFailed={searchFailed}
+ searchPending={searchPending}
+ resultsTruncated={resultsTruncated}
+ onRetrySearch={retrySearch}
/>
) : null}
+ {orgCredentials.status === "loading" ? (
+ <span className="text-xs text-muted-foreground">
+ Loading saved logins…
+ </span>
+ ) : null}
+ {orgCredentials.status === "error" ? (
+ <>
+ <span className="text-xs text-muted-foreground">
+ Couldn&apos;t load your saved logins.
+ </span>
+ {retryButton}
+ </>
+ ) : null}
+ {/* Mounted for the card's lifetime so only its text changes: a live region that appears
+ already holding its text is read as ordinary new content and never announced. Inside
+ an outer live region it takes no role and repeats nothing that region already
+ contains, only the search failure, whose visible text sits in a portaled popover. */}
+ <span
+ className="sr-only"
+ role={insideLiveRegion ? undefined : "status"}
+ >
+ {searchFailed
+ ? SEARCH_FAILED_ANNOUNCEMENT
+ : insideLiveRegion
+ ? ""
+ : orgCredentials.status === "loading"
+ ? "Loading saved logins…"
+ : orgCredentials.status === "error"
+ ? "Couldn't load your saved logins."
+ : ""}
+ </span>
</div>
</div>
</div>
diff --git a/skyvern-frontend/src/routes/workflows/editor/WorkflowAdderBusy.tsx b/skyvern-frontend/src/routes/workflows/editor/WorkflowAdderBusy.tsx
index fb7433b71..5fd9d8684 100644
--- a/skyvern-frontend/src/routes/workflows/editor/WorkflowAdderBusy.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/WorkflowAdderBusy.tsx
@@ -201,7 +201,7 @@ function WorkflowAdderBusy({
<TooltipContent>
<p>
{operation === "recording"
- ? "Stop recording & generate blocks"
+ ? "Stop & generate workflow steps"
: operation === "uploading"
? "Converting SOP... (click to cancel)"
: "Processing..."}
@@ -232,7 +232,7 @@ function WorkflowAdderBusy({
<p>
{eventCount === 0
? "No events yet — click and type in the live browser"
- : "Events captured in this recording"}
+ : "Interactions captured for this task"}
</p>
</TooltipContent>
</Tooltip>
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index a819cc912..d8eac3dca 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -71,6 +71,8 @@ import { useBlockScriptStore } from "@/store/BlockScriptStore";
import { useBlockSidebarWidthStore } from "@/store/BlockSidebarWidthStore";
import { useCacheKeyValueStore } from "@/store/CacheKeyValueStore";
import { useRecordingStore } from "@/store/useRecordingStore";
+import { useRecordedBlocksStore } from "@/store/RecordedBlocksStore";
+import { useWorkflowSettingsStore } from "@/store/WorkflowSettingsStore";
import { useStudioShellStore } from "@/store/StudioShellStore";
import { useCopilotActionStore } from "@/store/useCopilotActionStore";
import { useShowAllCodeStore } from "@/store/ShowAllCodeStore";
@@ -199,6 +201,12 @@ import {
import { useStudioShellContext } from "../studio/StudioShellContext";
import { StudioShellPanelPortal } from "../studio/StudioShellPanelPortal";
import { useRecordingLauncherStore } from "@/store/useRecordingLauncherStore";
+import { useSopToBlocksMutation } from "../hooks/useSopToBlocksMutation";
+import {
+ applySopResultAtCurrentAppend,
+ resolveAppendInsertionPoint,
+ resolveWorkspaceAuthoringActionAvailability,
+} from "./workspaceAuthoringActions";
import { paneWidthsKey } from "../studio/paneLayout";
import { useStudioPanes } from "../studio/useStudioPanes";
import { WorkflowCopilotButton } from "../copilot/WorkflowCopilotButton";
@@ -629,6 +637,9 @@ function Workspace({
const [isCopilotTurnActive, setIsCopilotTurnActive] = useState(false);
const blockScriptStore = useBlockScriptStore();
const recordingStore = useRecordingStore();
+ const finallyBlockLabel = useWorkflowSettingsStore(
+ (state) => state.finallyBlockLabel,
+ );
const cacheKey = workflow?.cache_key ?? "";
// Block delete confirmation dialog state
@@ -1450,21 +1461,47 @@ function Workspace({
// Stable action ref (vs the whole-store `recordingStore` object, which gets a
// new reference on every store write and would re-register the launcher).
const setIsRecording = useRecordingStore((s) => s.setIsRecording);
- const startRecordingAtEnd = useCallback(() => {
- const currentNodes = getNodes() as Array<AppNode>;
- const currentEdges = getEdges();
- const trailingAdder = currentNodes.find(
- (node) => node.type === "nodeAdder" && !node.parentId,
+ const setRecordedBlocks = useRecordedBlocksStore((s) => s.setRecordedBlocks);
+ const getAppendInsertionPoint = useCallback(() => {
+ return resolveAppendInsertionPoint(
+ getNodes() as Array<AppNode>,
+ getEdges(),
);
- const incomingEdge = trailingAdder
- ? currentEdges.find((edge) => edge.target === trailingAdder.id)
- : undefined;
+ }, [getEdges, getNodes]);
+ const sopToBlocksMutation = useSopToBlocksMutation({
+ onSuccess: (result) => {
+ applySopResultAtCurrentAppend({
+ result,
+ getNodes: () => getNodes() as Array<AppNode>,
+ getEdges,
+ setRecordedBlocks,
+ });
+ },
+ });
+ const authoringActionAvailability =
+ resolveWorkspaceAuthoringActionAvailability({
+ browserReady: copilotLiveBrowserReady,
+ isGlobalWorkflow,
+ isWorkflowDeleted: Boolean(workflow.deleted_at),
+ hasActiveRun: Boolean(viewerState?.active_run_session_id),
+ isComparing: Boolean(workflowPanelState.data?.showComparison),
+ isEditingYaml: yamlEditorActive,
+ hasFinallyBlock: Boolean(finallyBlockLabel),
+ isRecording:
+ recordingStore.isRecording ||
+ recordingStore.finishRequested ||
+ recordingStore.isCommitting,
+ isUploadingSOP: sopToBlocksMutation.isPending,
+ });
+ const startRecordingAtEnd = useCallback(() => {
+ if (!authoringActionAvailability.canRecordTask) return;
+ const insertionPoint = getAppendInsertionPoint();
setWorkflowPanelState({
active: false,
content: "nodeLibrary",
data: {
- previous: incomingEdge?.source ?? null,
- next: trailingAdder?.id ?? null,
+ previous: insertionPoint.previous,
+ next: insertionPoint.next,
parent: undefined,
connectingEdgeType: "default",
},
@@ -1474,20 +1511,34 @@ function Workspace({
browserSessionId: debugBrowserSessionId,
});
}, [
- getNodes,
- getEdges,
+ getAppendInsertionPoint,
setWorkflowPanelState,
setIsRecording,
workflowPermanentId,
debugBrowserSessionId,
+ authoringActionAvailability.canRecordTask,
]);
+ const uploadSOPAtEnd = useCallback(
+ (file: File) => {
+ if (!authoringActionAvailability.canUploadSOP) return;
+ sopToBlocksMutation.mutate(file);
+ },
+ [authoringActionAvailability.canUploadSOP, sopToBlocksMutation],
+ );
useEffect(() => {
if (!embedded) {
return;
}
- setStartRecordingAtEnd(startRecordingAtEnd);
+ setStartRecordingAtEnd(
+ authoringActionAvailability.canRecordTask ? startRecordingAtEnd : null,
+ );
return () => setStartRecordingAtEnd(null);
- }, [embedded, startRecordingAtEnd, setStartRecordingAtEnd]);
+ }, [
+ authoringActionAvailability.canRecordTask,
+ embedded,
+ startRecordingAtEnd,
+ setStartRecordingAtEnd,
+ ]);
// Listen for conditional branch changes to trigger re-layout
useEffect(() => {
@@ -2963,6 +3014,14 @@ function Workspace({
initialMessage={initialCopilotMessage ?? undefined}
initialAction={initialCopilotAction ?? undefined}
onInitialMessageConsumed={handleInitialCopilotMessageConsumed}
+ onUploadSOP={uploadSOPAtEnd}
+ canUploadSOP={authoringActionAvailability.canUploadSOP}
+ isUploadingSOP={sopToBlocksMutation.isPending}
+ onRecordTask={startRecordingAtEnd}
+ canRecordTask={authoringActionAvailability.canRecordTask}
+ authoringUnavailableReason={
+ authoringActionAvailability.unavailableReason
+ }
onBlockSelect={(blockLabel) => {
const matches = (node: AppNode) =>
(node.data as { label?: string } | undefined)?.label === blockLabel;
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeActionMenu.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeActionMenu.tsx
index 853be001f..a9c8c6065 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeActionMenu.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeActionMenu.tsx
@@ -43,14 +43,14 @@ function NodeActionMenu({
const isRecording = recordingStore.isRecording;
const deleteGated = isRecording || isCanvasLocked;
const deleteGateReason = isRecording
- ? "Stop recording to delete blocks"
+ ? "Finish recording the task to delete blocks"
: isCanvasLocked
? "Unlock canvas to delete blocks"
: null;
const duplicateGated =
isRecording || isCanvasLocked || Boolean(duplicateDisabledReason);
const duplicateGateReason = isRecording
- ? "Stop recording to duplicate blocks"
+ ? "Finish recording the task to duplicate blocks"
: isCanvasLocked
? "Unlock canvas to duplicate blocks"
: duplicateDisabledReason;
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx
index cef34de37..255b4502c 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx
@@ -195,9 +195,7 @@ describe("NodeAdderNode", () => {
fireEvent.mouseEnter(busyControl!);
expect(screen.getAllByText("Processing...").length).toBeGreaterThan(0);
- expect(
- screen.queryAllByText("Stop recording & generate blocks"),
- ).toHaveLength(0);
+ expect(screen.queryAllByText("Stop & generate workflow")).toHaveLength(0);
fireEvent.click(busyControl!.firstElementChild!);
expect(useRecordingStore.getState()).toMatchObject({
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.tsx
index e15a57e4c..120a0a7ae 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.tsx
@@ -142,7 +142,7 @@ function NodeAdderNode({ id, parentId }: NodeProps<NodeAdderNode>) {
: isBlockedByFinally
? "Finally block must run last - choose a position above it"
: !isBusy && recordingStore.isRecording
- ? "Stop recording to add a block"
+ ? "Finish recording the task to add a block"
: null;
const updateWorkflowPanelState = (
diff --git a/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.test.tsx b/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.test.tsx
index bf3a6cd80..12686583f 100644
--- a/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.test.tsx
@@ -119,10 +119,16 @@ describe("RecordingPanel", () => {
cleanup();
});
- it("uses task language while recording", () => {
+ it("explains what Record task captures and what Skyvern creates", () => {
render(<RecordingPanel browserSessionId="pbs_123" />);
expect(screen.getByText("Recording task")).toBeTruthy();
+ expect(
+ screen.getByText(
+ "Complete the task in the browser. Skyvern captures the browser view and your clicks, typing, and navigation, then turns them into workflow steps.",
+ ),
+ ).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Done" })).toBeTruthy();
});
it("keeps Done disabled and never calls process_recording while the browser session id has not resolved", () => {
diff --git a/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.tsx
index 0907b856e..db2bcbec3 100644
--- a/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.tsx
@@ -527,7 +527,7 @@ function RecordingPanel({ browserSessionId }: Props) {
const showInterpretationFallbackNote =
!interpretationEnabled && exposedEventCount > 0;
const headerTitle = isFinishing
- ? "Finishing recording"
+ ? "Creating workflow steps"
: manualCapturePaused
? "Recording paused"
: "Recording task";
@@ -568,9 +568,9 @@ function RecordingPanel({ browserSessionId }: Props) {
</>
) : (
<>
- Interact with the browser.
- <br />
- Your clicks, typing and navigation will appear here as blocks.
+ Complete the task in the browser. Skyvern captures the browser
+ view and your clicks, typing, and navigation, then turns them
+ into workflow steps.
</>
)}
</div>
@@ -640,8 +640,8 @@ function RecordingPanel({ browserSessionId }: Props) {
{showInterpretationFallbackNote && (
<div className="px-3 py-2 text-[11px] leading-relaxed text-muted-foreground">
{exposedEventCount} interaction
- {exposedEventCount === 1 ? "" : "s"} captured — blocks will be
- generated when you finish.
+ {exposedEventCount === 1 ? "" : "s"} captured — workflow steps will
+ be generated when you choose Done.
</div>
)}
<div ref={feedEndRef} />
@@ -649,8 +649,8 @@ function RecordingPanel({ browserSessionId }: Props) {
{insertionPointMissing && (
<div className="flex-none border-t px-3.5 py-2 text-[11px] leading-relaxed text-red-700 dark:text-red-400">
- Could not determine where to insert recorded blocks. Discard and start
- recording from the workflow editor again.
+ Could not determine where to insert workflow steps. Discard and choose
+ Record task from the workflow editor again.
</div>
)}
@@ -659,7 +659,11 @@ function RecordingPanel({ browserSessionId }: Props) {
<Button
variant="outline"
size="icon"
- title={manualCapturePaused ? "Resume capture" : "Pause capture"}
+ title={
+ manualCapturePaused
+ ? "Resume recording task"
+ : "Pause recording task"
+ }
className="h-8 w-8"
disabled={isCommitting || isFinishing}
onClick={() =>
@@ -677,7 +681,7 @@ function RecordingPanel({ browserSessionId }: Props) {
<Button
variant="outline"
size="icon"
- title="Discard recording"
+ title="Discard task recording"
className="h-8 w-8 hover:border-red-500/40 hover:text-red-700 dark:hover:text-red-400"
disabled={isCommitting}
onClick={onDiscardClick}
@@ -695,7 +699,11 @@ function RecordingPanel({ browserSessionId }: Props) {
onClick={onDoneClick}
>
<CheckIcon className="mr-1.5 h-4 w-4" />
- {mutationIsError ? "Retry" : isFinishing ? "Processing…" : "Done"}
+ {mutationIsError
+ ? "Retry"
+ : isFinishing
+ ? "Creating workflow…"
+ : "Done"}
</Button>
</div>
@@ -703,14 +711,14 @@ function RecordingPanel({ browserSessionId }: Props) {
<Dialog open onOpenChange={setConfirmDiscardOpen}>
<DialogContent>
<DialogHeader>
- <DialogTitle>Discard recording?</DialogTitle>
+ <DialogTitle>Discard task recording?</DialogTitle>
<DialogDescription>
{visibleSteps.length > 0
- ? `You have ${visibleSteps.length} recorded block${
+ ? `You have ${visibleSteps.length} captured workflow step${
visibleSteps.length === 1 ? "" : "s"
} that will be lost if you discard.`
- : "Your recorded interactions will be lost if you discard."}{" "}
- Are you sure you want to discard the recording?
+ : "Your captured browser interactions will be lost if you discard."}{" "}
+ Are you sure you want to discard this task recording?
</DialogDescription>
</DialogHeader>
<DialogFooter>
@@ -718,10 +726,10 @@ function RecordingPanel({ browserSessionId }: Props) {
variant="outline"
onClick={() => setConfirmDiscardOpen(false)}
>
- Keep recording
+ Keep recording task
</Button>
<Button variant="destructive" onClick={discard}>
- Discard recording
+ Discard
</Button>
</DialogFooter>
</DialogContent>
diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/dragModeGate.test.ts b/skyvern-frontend/src/routes/workflows/editor/sortable/dragModeGate.test.ts
index 177136f54..2cb7d8b68 100644
--- a/skyvern-frontend/src/routes/workflows/editor/sortable/dragModeGate.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/dragModeGate.test.ts
@@ -32,7 +32,7 @@ describe("getDragGateReason (SKY-9061)", () => {
test("returns the recording hint when recording is on", () => {
expect(
getDragGateReason({ isRecording: true, isCanvasLocked: false }),
- ).toBe("Stop recording to reorder blocks");
+ ).toBe("Finish recording the task to reorder blocks");
});
test("returns the canvas-lock hint when only canvas is locked", () => {
@@ -43,7 +43,7 @@ describe("getDragGateReason (SKY-9061)", () => {
test("prefers recording hint when both gates are active", () => {
expect(getDragGateReason({ isRecording: true, isCanvasLocked: true })).toBe(
- "Stop recording to reorder blocks",
+ "Finish recording the task to reorder blocks",
);
});
});
diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/dragModeGate.ts b/skyvern-frontend/src/routes/workflows/editor/sortable/dragModeGate.ts
index ebad81bf8..a685236ad 100644
--- a/skyvern-frontend/src/routes/workflows/editor/sortable/dragModeGate.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/dragModeGate.ts
@@ -30,7 +30,7 @@ export function getDragGateReason({
isRecording,
isCanvasLocked,
}: DragModeGateInputs): string | null {
- if (isRecording) return "Stop recording to reorder blocks";
+ if (isRecording) return "Finish recording the task to reorder blocks";
if (isCanvasLocked) return "Unlock canvas to reorder blocks";
return null;
}
diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/dropBlockedToast.test.ts b/skyvern-frontend/src/routes/workflows/editor/sortable/dropBlockedToast.test.ts
index 559c6cfc1..9509dd16e 100644
--- a/skyvern-frontend/src/routes/workflows/editor/sortable/dropBlockedToast.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/dropBlockedToast.test.ts
@@ -64,7 +64,9 @@ describe("formatDropBlockedToast (SKY-9062)", () => {
kind: "drag-mode",
});
expect(content.title).toContain("recording");
- expect(content.description).toBe("Stop recording to reorder blocks.");
+ expect(content.description).toBe(
+ "Finish recording the task to reorder blocks.",
+ );
expect(content.details).toEqual([]);
});
});
diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/dropBlockedToast.tsx b/skyvern-frontend/src/routes/workflows/editor/sortable/dropBlockedToast.tsx
index 75abdb054..17e28feb9 100644
--- a/skyvern-frontend/src/routes/workflows/editor/sortable/dropBlockedToast.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/dropBlockedToast.tsx
@@ -85,8 +85,8 @@ export function formatDropBlockedToast(
}
case "drag-mode": {
return {
- title: "Can't reorder: recording is active",
- description: "Stop recording to reorder blocks.",
+ title: "Can't reorder: task recording is active",
+ description: "Finish recording the task to reorder blocks.",
details: [],
};
}
diff --git a/skyvern-frontend/src/routes/workflows/editor/workspaceAuthoringActions.test.ts b/skyvern-frontend/src/routes/workflows/editor/workspaceAuthoringActions.test.ts
new file mode 100644
index 000000000..b4d2437d6
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/workspaceAuthoringActions.test.ts
@@ -0,0 +1,174 @@
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ applySopResultAtCurrentAppend,
+ resolveWorkspaceAuthoringActionAvailability,
+} from "./workspaceAuthoringActions";
+
+describe("workspace authoring actions", () => {
+ it("applies an SOP at the current workflow tail when conversion finishes", () => {
+ let nodes = [
+ { id: "a", type: "task" },
+ { id: "adder", type: "nodeAdder" },
+ ];
+ let edges = [{ source: "a", target: "adder" }];
+ const setRecordedBlocks = vi.fn();
+ const result = { blocks: [], parameters: [] };
+
+ const applyResult = () =>
+ applySopResultAtCurrentAppend({
+ result,
+ getNodes: () => nodes,
+ getEdges: () => edges,
+ setRecordedBlocks,
+ });
+
+ nodes = [
+ { id: "a", type: "task" },
+ { id: "b", type: "task" },
+ { id: "adder", type: "nodeAdder" },
+ ];
+ edges = [
+ { source: "a", target: "b" },
+ { source: "b", target: "adder" },
+ ];
+ applyResult();
+
+ expect(setRecordedBlocks).toHaveBeenCalledWith(result, {
+ previous: "b",
+ next: "adder",
+ parent: undefined,
+ connectingEdgeType: "default",
+ });
+ });
+
+ it("makes SOP upload and task recording mutually exclusive", () => {
+ expect(
+ resolveWorkspaceAuthoringActionAvailability({
+ browserReady: true,
+ isGlobalWorkflow: false,
+ isWorkflowDeleted: false,
+ hasActiveRun: false,
+ isComparing: false,
+ isEditingYaml: false,
+ hasFinallyBlock: false,
+ isRecording: false,
+ isUploadingSOP: true,
+ }),
+ ).toMatchObject({ canUploadSOP: false, canRecordTask: false });
+
+ expect(
+ resolveWorkspaceAuthoringActionAvailability({
+ browserReady: true,
+ isGlobalWorkflow: false,
+ isWorkflowDeleted: false,
+ hasActiveRun: false,
+ isComparing: false,
+ isEditingYaml: false,
+ hasFinallyBlock: false,
+ isRecording: true,
+ isUploadingSOP: false,
+ }),
+ ).toMatchObject({ canUploadSOP: false, canRecordTask: false });
+ });
+
+ it("blocks append-only actions on global workflows and after a finally block", () => {
+ const base = {
+ browserReady: true,
+ isWorkflowDeleted: false,
+ hasActiveRun: false,
+ isComparing: false,
+ isEditingYaml: false,
+ isRecording: false,
+ isUploadingSOP: false,
+ };
+
+ expect(
+ resolveWorkspaceAuthoringActionAvailability({
+ ...base,
+ isGlobalWorkflow: true,
+ hasFinallyBlock: false,
+ }),
+ ).toMatchObject({
+ canUploadSOP: false,
+ canRecordTask: false,
+ unavailableReason: "Make a copy to edit this agent",
+ });
+
+ expect(
+ resolveWorkspaceAuthoringActionAvailability({
+ ...base,
+ isGlobalWorkflow: false,
+ hasFinallyBlock: true,
+ }),
+ ).toMatchObject({
+ canUploadSOP: false,
+ canRecordTask: false,
+ unavailableReason:
+ "The finally block must remain last. Add steps above it in the editor.",
+ });
+ });
+
+ it("blocks deleted workflows and recording against an active run browser", () => {
+ const base = {
+ browserReady: true,
+ isGlobalWorkflow: false,
+ hasFinallyBlock: false,
+ isComparing: false,
+ isEditingYaml: false,
+ isRecording: false,
+ isUploadingSOP: false,
+ };
+
+ expect(
+ resolveWorkspaceAuthoringActionAvailability({
+ ...base,
+ isWorkflowDeleted: true,
+ hasActiveRun: false,
+ }),
+ ).toEqual({
+ canUploadSOP: false,
+ canRecordTask: false,
+ unavailableReason: "This agent is deleted and view-only",
+ });
+
+ expect(
+ resolveWorkspaceAuthoringActionAvailability({
+ ...base,
+ isWorkflowDeleted: false,
+ hasActiveRun: true,
+ }),
+ ).toEqual({
+ canUploadSOP: true,
+ canRecordTask: false,
+ unavailableReason: "Stop the active run before recording a task",
+ });
+
+ expect(
+ resolveWorkspaceAuthoringActionAvailability({
+ ...base,
+ isWorkflowDeleted: false,
+ hasActiveRun: false,
+ isComparing: true,
+ }),
+ ).toEqual({
+ canUploadSOP: false,
+ canRecordTask: false,
+ unavailableReason: "Exit history comparison to edit this agent",
+ });
+
+ expect(
+ resolveWorkspaceAuthoringActionAvailability({
+ ...base,
+ isWorkflowDeleted: false,
+ hasActiveRun: false,
+ isComparing: false,
+ isEditingYaml: true,
+ }),
+ ).toEqual({
+ canUploadSOP: false,
+ canRecordTask: false,
+ unavailableReason: "Switch to Visual mode before adding workflow steps",
+ });
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/workspaceAuthoringActions.ts b/skyvern-frontend/src/routes/workflows/editor/workspaceAuthoringActions.ts
new file mode 100644
index 000000000..eaf389417
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/workspaceAuthoringActions.ts
@@ -0,0 +1,110 @@
+import type { WorkflowBlock, WorkflowParameter } from "../types/workflowTypes";
+import type { InsertionPoint } from "@/store/RecordedBlocksStore";
+
+type WorkflowNodeLike = {
+ id: string;
+ type?: string;
+ parentId?: string;
+};
+
+type WorkflowEdgeLike = {
+ source: string;
+ target: string;
+};
+
+type SopResult = {
+ blocks: Array<WorkflowBlock>;
+ parameters: Array<WorkflowParameter>;
+};
+
+function resolveAppendInsertionPoint(
+ nodes: Array<WorkflowNodeLike>,
+ edges: Array<WorkflowEdgeLike>,
+): InsertionPoint {
+ const trailingAdder = nodes.find(
+ (node) => node.type === "nodeAdder" && !node.parentId,
+ );
+ const incomingEdge = trailingAdder
+ ? edges.find((edge) => edge.target === trailingAdder.id)
+ : undefined;
+
+ return {
+ previous: incomingEdge?.source ?? null,
+ next: trailingAdder?.id ?? null,
+ parent: undefined,
+ connectingEdgeType: "default",
+ };
+}
+
+function applySopResultAtCurrentAppend({
+ result,
+ getNodes,
+ getEdges,
+ setRecordedBlocks,
+}: {
+ result: SopResult;
+ getNodes: () => Array<WorkflowNodeLike>;
+ getEdges: () => Array<WorkflowEdgeLike>;
+ setRecordedBlocks: (
+ result: SopResult,
+ insertionPoint: InsertionPoint,
+ ) => void;
+}) {
+ setRecordedBlocks(
+ result,
+ resolveAppendInsertionPoint(getNodes(), getEdges()),
+ );
+}
+
+function resolveWorkspaceAuthoringActionAvailability({
+ browserReady,
+ isGlobalWorkflow,
+ isWorkflowDeleted,
+ hasActiveRun,
+ isComparing,
+ isEditingYaml,
+ hasFinallyBlock,
+ isRecording,
+ isUploadingSOP,
+}: {
+ browserReady: boolean;
+ isGlobalWorkflow: boolean;
+ isWorkflowDeleted: boolean;
+ hasActiveRun: boolean;
+ isComparing: boolean;
+ isEditingYaml: boolean;
+ hasFinallyBlock: boolean;
+ isRecording: boolean;
+ isUploadingSOP: boolean;
+}) {
+ const unavailableReason = isWorkflowDeleted
+ ? "This agent is deleted and view-only"
+ : isComparing
+ ? "Exit history comparison to edit this agent"
+ : isEditingYaml
+ ? "Switch to Visual mode before adding workflow steps"
+ : isGlobalWorkflow
+ ? "Make a copy to edit this agent"
+ : hasFinallyBlock
+ ? "The finally block must remain last. Add steps above it in the editor."
+ : isRecording
+ ? "Finish recording the current task first"
+ : isUploadingSOP
+ ? "Wait for the SOP upload to finish"
+ : null;
+ const recordUnavailableReason =
+ unavailableReason ??
+ (hasActiveRun ? "Stop the active run before recording a task" : null);
+
+ return {
+ canUploadSOP: unavailableReason === null,
+ canRecordTask: recordUnavailableReason === null && browserReady,
+ unavailableReason: recordUnavailableReason,
+ };
+}
+
+export {
+ applySopResultAtCurrentAppend,
+ resolveAppendInsertionPoint,
+ resolveWorkspaceAuthoringActionAvailability,
+};
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useSopToBlocksMutation.ts b/skyvern-frontend/src/routes/workflows/hooks/useSopToBlocksMutation.ts
index 09cf572d3..cc58acaf5 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useSopToBlocksMutation.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useSopToBlocksMutation.ts
@@ -44,7 +44,7 @@ function useSopToBlocksMutation({ onSuccess }: UseSopToBlocksMutationOptions) {
toast({
variant: "success",
title: "SOP converted",
- description: `Generated ${result.blocks.length} block${result.blocks.length === 1 ? "" : "s"}`,
+ description: `Generated ${result.blocks.length} workflow step${result.blocks.length === 1 ? "" : "s"}`,
});
onSuccess?.(result);
},
diff --git a/skyvern/forge/sdk/workflow/context_manager.py b/skyvern/forge/sdk/workflow/context_manager.py
index 04a813295..a07b48160 100644
--- a/skyvern/forge/sdk/workflow/context_manager.py
+++ b/skyvern/forge/sdk/workflow/context_manager.py
@@ -781,7 +781,10 @@ class WorkflowRunContext:
result = result.replace(secret, mask)
return result
elif isinstance(data, dict):
- return {k: self.mask_secrets_in_data(v, mask) for k, v in data.items()}
+ # Keys are masked as well as values: authored code is free to build {code: True}, and a
+ # key carrying a secret is as readable in stored output as a value carrying one. Two keys
+ # that both mask to the same string collapse into one entry, which is preferred to leaking.
+ return {self.mask_secrets_in_data(k, mask): self.mask_secrets_in_data(v, mask) for k, v in data.items()}
elif isinstance(data, list):
return [self.mask_secrets_in_data(item, mask) for item in data]
return data
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recorder.py b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
index 19bbf66a0..4b8332d28 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recorder.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
@@ -980,7 +980,7 @@ def json_safe_recorder_output(value: Any) -> Any:
A leaked proxy is a generated-code defect with no meaningful serializable value, so it collapses
to a type marker rather than its selector: a selector is only a lossy display fragment and can
- embed a resolved credential, which mask_secrets_in_data does not scrub out of a dict key."""
+ embed a resolved credential, and this runs before any masking."""
if isinstance(value, (RecordingLocator, RecordingKeyboard, RecordingPage)):
return f"<{type(value).__name__}>"
if isinstance(value, dict):
diff --git a/tests/unit/test_non_secret_credential_fields.py b/tests/unit/test_non_secret_credential_fields.py
index 7208630c1..04b4d1768 100644
--- a/tests/unit/test_non_secret_credential_fields.py
+++ b/tests/unit/test_non_secret_credential_fields.py
@@ -117,6 +117,14 @@ def test_standalone_short_secret_leaf_still_masks() -> None:
assert context.mask_secrets_in_data(["587"]) == ["*****"]
+def test_secret_used_as_a_dict_key_masks() -> None:
+ context = _context_with_secrets(otp="778899")
+
+ assert context.mask_secrets_in_data({"778899": True}) == {"*****": True}
+ assert context.mask_secrets_in_data([{"778899": {"seen": "778899"}}]) == [{"*****": {"seen": "*****"}}]
+ assert context.mask_secrets_in_data({1: "ok", None: "ok"}) == {1: "ok", None: "ok"}
+
+
def test_four_char_year_masks_only_as_whole_value() -> None:
context = _context_with_secrets(card_exp_year="2030")
payload = {"due": "2030-01-15", "note": "renews in 2030"}
diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.py
index e3e8f70df..07c6041e2 100644
--- a/tests/unit/workflow/test_code_block_recorder.py
+++ b/tests/unit/workflow/test_code_block_recorder.py
@@ -2225,8 +2225,8 @@ def test_json_safe_recorder_output_normalizes_leaked_locator_used_as_key() -> No
def test_json_safe_recorder_output_never_leaks_a_secret_bearing_selector() -> None:
- """A resolved credential can end up in a locator selector; mask_secrets_in_data scrubs dict
- values, not keys, so the marker must not carry the selector at all — as a value or a key."""
+ """A resolved credential can end up in a locator selector, and this runs before any masking, so
+ the marker must not carry the selector at all — as a value or a key."""
secret = "s3cr3t-token"
recorder = _Recorder(None)
as_value = RecordingLocator(FakeLocator(), recorder, f"text={secret}")