Skip to content

Automate browser based workflows with AI

Show Upload an SOP and Demonstrate task cards under the Home prompt box (SKY-18697) (#9011)

Shuchang Zheng957faa988a94
diff --git a/skyvern-frontend/src/components/StartFromCards.tsx b/skyvern-frontend/src/components/StartFromCards.tsx
new file mode 100644
index 000000000..1015dc657
--- /dev/null
+++ b/skyvern-frontend/src/components/StartFromCards.tsx
@@ -0,0 +1,139 @@
+import { UploadIcon } from "@radix-ui/react-icons";
+import { useRef } from "react";
+
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { toast } from "@/components/ui/use-toast";
+import { ControlTooltip } from "@/routes/workflows/studio/ControlTooltip";
+import { cn } from "@/util/utils";
+
+type UploadSopAction = {
+ onFile: (file: File) => void;
+ disabled?: boolean;
+ /** Replaces the default hint, e.g. with the reason the action is unavailable. */
+ tooltip?: string;
+};
+
+type RecordTaskAction = {
+ onSelect: () => void;
+ disabled?: boolean;
+ tooltip?: string;
+};
+
+type StartFromCardsProps = {
+ uploadSOP: UploadSopAction;
+ recordTask: RecordTaskAction;
+ className?: string;
+ labelClassName?: string;
+ /** Column rule for the host: the Copilot pane uses a container query, Home a breakpoint. */
+ gridClassName?: string;
+};
+
+const UPLOAD_SOP_HINT = "Attach a procedure PDF for Copilot to build from";
+const RECORD_TASK_HINT =
+ "Skyvern records your clicks, typing, and navigation, then turns them into workflow steps";
+
+const cardClassName =
+ "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";
+const iconBoxClassName =
+ "flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-slate-elevation2";
+
+function StartFromCards({
+ uploadSOP,
+ recordTask,
+ className,
+ labelClassName,
+ gridClassName,
+}: StartFromCardsProps) {
+ const sopFileInputRef = useRef<HTMLInputElement>(null);
+ const uploadDisabled = Boolean(uploadSOP.disabled);
+ const recordDisabled = Boolean(recordTask.disabled);
+
+ return (
+ <div className={className}>
+ <p className={cn("text-xs text-muted-foreground/80", labelClassName)}>
+ Or start from
+ </p>
+ <TooltipProvider>
+ <div className={cn("mt-2 grid grid-cols-1 gap-2", gridClassName)}>
+ <ControlTooltip
+ content={uploadSOP.tooltip ?? UPLOAD_SOP_HINT}
+ blocked={uploadDisabled}
+ side="top"
+ wrapperClassName="min-w-0 w-full"
+ >
+ <button
+ type="button"
+ aria-label="Upload an SOP"
+ className={cardClassName}
+ disabled={uploadDisabled}
+ onClick={() => sopFileInputRef.current?.click()}
+ >
+ <span className={iconBoxClassName}>
+ <UploadIcon className="h-4 w-4" />
+ </span>
+ <span className="min-w-0">
+ <span className="block text-sm font-medium text-foreground">
+ Upload an SOP
+ </span>
+ <span className="mt-0.5 block text-xs leading-snug text-muted-foreground">
+ A PDF of the procedure
+ </span>
+ </span>
+ </button>
+ </ControlTooltip>
+ <ControlTooltip
+ content={recordTask.tooltip ?? RECORD_TASK_HINT}
+ blocked={recordDisabled}
+ side="top"
+ wrapperClassName="min-w-0 w-full"
+ >
+ <button
+ type="button"
+ aria-label="Demonstrate task"
+ className={cardClassName}
+ disabled={recordDisabled}
+ onClick={recordTask.onSelect}
+ >
+ <span className={iconBoxClassName}>
+ <span className="h-2.5 w-2.5 rounded-full bg-red-500" />
+ </span>
+ <span className="min-w-0">
+ <span className="block text-sm font-medium text-foreground">
+ Demonstrate task
+ </span>
+ <span className="mt-0.5 block text-xs leading-snug text-muted-foreground">
+ Show Copilot how in the browser
+ </span>
+ </span>
+ </button>
+ </ControlTooltip>
+ </div>
+ </TooltipProvider>
+ <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;
+ // Reset first: picking the same file twice in a row fires no change event otherwise.
+ event.target.value = "";
+ if (uploadDisabled) return;
+ if (!file.name.toLowerCase().endsWith(".pdf")) {
+ toast({
+ variant: "destructive",
+ title: "Invalid file type",
+ description: "Please select a PDF file",
+ });
+ return;
+ }
+ uploadSOP.onFile(file);
+ }}
+ />
+ </div>
+ );
+}
+
+export { StartFromCards };
diff --git a/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx b/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
index 89a2b80ea..8549c1df9 100644
--- a/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
+++ b/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
@@ -86,7 +86,11 @@ vi.mock("@/routes/tasks/create/PromptBox", async () => {
{
focusAndPrefillExample: (key: string | null, fallback: string) => void;
},
- { secondaryAction?: React.ReactNode }
+ {
+ secondaryAction?:
+ | React.ReactNode
+ | ((state: { busy: boolean }) => React.ReactNode);
+ }
>(function PromptBoxMock({ secondaryAction }, ref) {
const [value, setValue] = React.useState("");
const textareaRef = React.useRef<HTMLTextAreaElement>(null);
@@ -106,7 +110,9 @@ vi.mock("@/routes/tasks/create/PromptBox", async () => {
value={value}
onChange={(event) => setValue(event.target.value)}
/>
- {secondaryAction}
+ {typeof secondaryAction === "function"
+ ? secondaryAction({ busy: false })
+ : secondaryAction}
</div>
);
}),
diff --git a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
index 5155f239c..583aa89bc 100644
--- a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
+++ b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
@@ -173,12 +173,12 @@ function DiscoverPage({ revamp = false, onRevampComplete }: Props = {}) {
ref={promptBoxRef}
enableCopilotHandoff={enableCopilotHandoff}
handoffFlagLoading={copilotHandoffFlag === undefined}
- secondaryAction={
- <Button
- variant="ghost"
- size="sm"
- className="h-11 w-full touch-manipulation gap-2 border border-border/70 text-muted-foreground hover:text-foreground md:h-10 md:w-auto md:border-0"
- disabled={createWorkflowMutation.isPending}
+ siblingBusy={createWorkflowMutation.isPending}
+ secondaryAction={({ busy }) => (
+ <button
+ type="button"
+ className="relative inline-flex touch-manipulation items-center gap-1.5 rounded px-1 py-0.5 text-xs text-muted-foreground transition-colors before:absolute before:-inset-y-3 before:inset-x-0 before:content-[''] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 md:before:hidden"
+ disabled={createWorkflowMutation.isPending || busy}
onClick={() => {
createWorkflow({
...defaultWorkflowRequest,
@@ -189,14 +189,14 @@ function DiscoverPage({ revamp = false, onRevampComplete }: Props = {}) {
{createWorkflowMutation.isPending ? (
<ReloadIcon
aria-hidden="true"
- className="h-3 w-3 motion-safe:animate-spin motion-reduce:animate-none"
+ className="size-3.5 motion-safe:animate-spin motion-reduce:animate-none"
/>
) : (
- <FilePlusIcon aria-hidden="true" className="size-4" />
+ <FilePlusIcon aria-hidden="true" className="size-3.5" />
)}
Start with a blank canvas
- </Button>
- }
+ </button>
+ )}
/>
<div className="mx-auto w-full max-w-[60rem] pb-8">
<WorkflowTemplates />
diff --git a/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx b/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
index 7111cdc26..139c1b692 100644
--- a/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
+++ b/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
@@ -24,6 +24,7 @@ import { toast } from "@/components/ui/use-toast";
import { UserContext } from "@/store/UserContext";
import { Link } from "react-router-dom";
+import { takeSopHandoffFile } from "@/routes/workflows/sopHandoff";
import { PromptBox, type PromptBoxHandle } from "./PromptBox";
import {
PREWARM_DISPATCH_WAIT_TIMEOUT_MS,
@@ -202,6 +203,7 @@ function renderPromptBox(
ref?: Ref<PromptBoxHandle>,
minimal = false,
handoffFlagLoading = false,
+ siblingBusy = false,
) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
@@ -219,6 +221,7 @@ function renderPromptBox(
enableCopilotHandoff={enableCopilotHandoff}
minimal={minimal}
handoffFlagLoading={handoffFlagLoading}
+ siblingBusy={siblingBusy}
/>
</QueryClientProvider>
</UserContext.Provider>,
@@ -934,36 +937,120 @@ describe("PromptBox", () => {
]);
});
- test("drops only the example's sample resume when switching to an example without one", async () => {
+ test("drops the example's sample resume when switching to an example without one", async () => {
vi.stubGlobal(
"fetch",
vi.fn(() =>
Promise.resolve(new Response(new Blob(["%PDF"]), { status: 200 })),
),
);
- mockPost
- .mockResolvedValueOnce({ data: { file_id: "file_user" } })
- .mockResolvedValueOnce({ data: { file_id: "file_example" } });
+ mockPost.mockResolvedValueOnce({ data: { file_id: "file_example" } });
renderPromptBox(true);
- fireEvent.change(screen.getByLabelText("Upload document"), {
- target: {
- files: [
- new File(["%PDF"], "sample-resume.pdf", { type: "application/pdf" }),
- ],
+ fireEvent.click(screen.getByRole("button", { name: "Apply for a job" }));
+ await screen.findByText("sample-resume.pdf");
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "Add a product to cart" }),
+ );
+ await waitFor(() =>
+ expect(screen.queryByText("sample-resume.pdf")).toBeNull(),
+ );
+ });
+
+ test("Upload an SOP creates a blank agent and hands the PDF to the editor once", async () => {
+ mockPost.mockResolvedValue({
+ data: {
+ workflow_permanent_id: "wpid_sop",
+ workflow_definition: { blocks: [] },
},
});
- await screen.findByText("sample-resume.pdf");
- fireEvent.click(screen.getByRole("button", { name: "Apply for a job" }));
+ const pdf = new File(["%PDF"], "procedure.pdf", {
+ type: "application/pdf",
+ });
+
+ renderPromptBox(true);
+ expect(screen.queryByLabelText("Add files and more")).toBeNull();
+ fireEvent.change(screen.getByLabelText("Choose an SOP PDF"), {
+ target: { files: [pdf] },
+ });
+
await waitFor(() =>
- expect(screen.getAllByText("sample-resume.pdf")).toHaveLength(2),
+ expect(mockNavigate).toHaveBeenCalledWith(
+ "/agents/wpid_sop/studio?sop=1",
+ ),
);
+ expect(mockPost).toHaveBeenCalledTimes(1);
+ expect(mockPost.mock.calls[0]![0]).toBe("/workflows");
+ expect(mockPost.mock.calls[0]![1]).toContain("title: New Agent");
+ expect(takeSopHandoffFile("wpid_sop")).toBe(pdf);
+ expect(takeSopHandoffFile("wpid_sop")).toBeNull();
+ expect(mockPostHogCapture).toHaveBeenCalledWith(
+ "home.upload_sop_selected",
+ expect.any(Object),
+ );
+ });
- fireEvent.click(
- screen.getByRole("button", { name: "Add a product to cart" }),
+ test("rejects a non-PDF SOP without creating an agent", () => {
+ renderPromptBox(true);
+ fireEvent.change(screen.getByLabelText("Choose an SOP PDF"), {
+ target: {
+ files: [new File(["steps"], "procedure.txt", { type: "text/plain" })],
+ },
+ });
+
+ expect(toast).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Invalid file type" }),
+ );
+ expect(mockPost).not.toHaveBeenCalled();
+ expect(mockNavigate).not.toHaveBeenCalled();
+ });
+
+ test("start cards wait while the blank-canvas link is creating an agent", () => {
+ renderPromptBox(true, undefined, false, false, true);
+ expect(
+ (screen.getByLabelText("Upload an SOP") as HTMLButtonElement).disabled,
+ ).toBe(true);
+ expect(
+ (screen.getByLabelText("Demonstrate task") as HTMLButtonElement).disabled,
+ ).toBe(true);
+ });
+
+ test("rejects an oversized SOP before creating an agent", () => {
+ const big = new File(["%PDF"], "huge.pdf", { type: "application/pdf" });
+ Object.defineProperty(big, "size", { value: 31 * 1024 * 1024 });
+ renderPromptBox(true);
+ fireEvent.change(screen.getByLabelText("Choose an SOP PDF"), {
+ target: { files: [big] },
+ });
+
+ expect(toast).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "File too large" }),
);
+ expect(mockPost).not.toHaveBeenCalled();
+ expect(mockNavigate).not.toHaveBeenCalled();
+ });
+
+ test("Demonstrate task creates a blank agent and opens the editor recording", async () => {
+ mockPost.mockResolvedValue({
+ data: {
+ workflow_permanent_id: "wpid_demo",
+ workflow_definition: { blocks: [] },
+ },
+ });
+
+ renderPromptBox(true);
+ fireEvent.click(screen.getByRole("button", { name: "Demonstrate task" }));
+
await waitFor(() =>
- expect(screen.getAllByText("sample-resume.pdf")).toHaveLength(1),
+ expect(mockNavigate).toHaveBeenCalledWith(
+ "/agents/wpid_demo/studio?record=1",
+ ),
+ );
+ expect(mockPost.mock.calls[0]![1]).toContain("title: Demonstrated Agent");
+ expect(mockPostHogCapture).toHaveBeenCalledWith(
+ "home.record_task_selected",
+ expect.any(Object),
);
});
diff --git a/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx b/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
index 2b352a44c..066cd4ce3 100644
--- a/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
+++ b/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
@@ -9,6 +9,7 @@ import { GraphIcon } from "@/components/icons/GraphIcon";
import { InboxIcon } from "@/components/icons/InboxIcon";
import { ToastAction } from "@/components/ui/toast";
import { toast } from "@/components/ui/use-toast";
+import { ATTACHMENT_SIZE_LIMIT_BYTES } from "@/routes/workflows/copilot/attachmentLimits";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";
import { useBrowserSessionPrewarm } from "./useBrowserSessionPrewarm";
@@ -39,6 +40,9 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { StartFromCards } from "@/components/StartFromCards";
+import { defaultWorkflowRequest } from "@/routes/workflows/defaultWorkflowRequest";
+import { rememberSopHandoffFile } from "@/routes/workflows/sopHandoff";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError, type AxiosResponse } from "axios";
import {
@@ -192,7 +196,9 @@ type PromptBoxProps = {
/** Fires once an agent has been created from this prompt box. */
onAgentCreated?: () => void;
/** Rendered under the prompt input in the full (non-minimal) layout. */
- secondaryAction?: ReactNode;
+ secondaryAction?: ReactNode | ((state: { busy: boolean }) => ReactNode);
+ /** True while a sibling creation path (the blank-canvas link) is posting, so the cards wait for it. */
+ siblingBusy?: boolean;
};
type PromptBoxHandle = {
@@ -280,6 +286,7 @@ function PromptBoxImpl(
minimal = false,
onAgentCreated,
secondaryAction,
+ siblingBusy = false,
}: PromptBoxProps,
ref: ForwardedRef<PromptBoxHandle>,
) {
@@ -324,6 +331,9 @@ function PromptBoxImpl(
// react-query isPending only flips on the next render, so a same-frame
// double-click can slip past it; the ref is the synchronous guard.
const submitInFlightRef = useRef(false);
+ // Synchronous guard for the start cards: a second activation before the pending state renders
+ // would create a second agent.
+ const cardStartRef = useRef(false);
const updatePrompt = useCallback((value: string) => {
setPrompt(value);
@@ -443,37 +453,59 @@ function PromptBoxImpl(
return prompt;
};
- const recordTaskMutation = useMutation({
- mutationFn: async () => {
- const client = await getClient(credentialGetter);
- const yaml = convertToYAML(
- buildBlankWorkflowRequest("Demonstrated Agent"),
- );
- const result = await client.post<string, AxiosResponse<unknown>>(
- "/workflows",
- yaml,
- { headers: { "Content-Type": "text/plain" } },
+ const createBlankWorkflow = async (title: string) => {
+ const client = await getClient(credentialGetter);
+ const yaml = convertToYAML(buildBlankWorkflowRequest(title));
+ const result = await client.post<string, AxiosResponse<unknown>>(
+ "/workflows",
+ yaml,
+ { headers: { "Content-Type": "text/plain" } },
+ );
+ if (!hasWorkflowShape(result.data)) {
+ throw new Error(
+ `workflow create returned an unexpected response shape (${describeResponseEnvelope(result)})`,
);
- if (!hasWorkflowShape(result.data)) {
- throw new Error(
- `workflow create returned an unexpected response shape (${describeResponseEnvelope(result)})`,
- );
- }
- return result.data;
+ }
+ return result.data;
+ };
+
+ const openCreatedWorkflow = (
+ workflow: WorkflowApiResponse,
+ search: string,
+ ) => {
+ onAgentCreated?.();
+ queryClient.invalidateQueries({ queryKey: ["workflows"] });
+ navigate(
+ workflowEditorPath(workflow.workflow_permanent_id, studioEnabled, search),
+ );
+ };
+
+ const recordTaskMutation = useMutation({
+ mutationFn: () => createBlankWorkflow("Demonstrated Agent"),
+ onSuccess: (workflow) => openCreatedWorkflow(workflow, "?record=1"),
+ onError: (error: AxiosError) => {
+ showCreateErrorToast("Could not start demonstration", error);
},
- onSuccess: (workflow) => {
- onAgentCreated?.();
- queryClient.invalidateQueries({ queryKey: ["workflows"] });
- navigate(
- workflowEditorPath(
- workflow.workflow_permanent_id,
- studioEnabled,
- "?record=1",
- ),
- );
+ onSettled: () => {
+ cardStartRef.current = false;
+ },
+ });
+
+ // The editor stages the PDF in Copilot once it opens (`?sop=1`), the same path as the Copilot card.
+ const startFromSopMutation = useMutation({
+ mutationFn: async (file: File) => ({
+ file,
+ workflow: await createBlankWorkflow(defaultWorkflowRequest.title),
+ }),
+ onSuccess: ({ file, workflow }) => {
+ rememberSopHandoffFile(workflow.workflow_permanent_id, file);
+ openCreatedWorkflow(workflow, "?sop=1");
},
onError: (error: AxiosError) => {
- showCreateErrorToast("Could not start demonstration", error);
+ showCreateErrorToast("Could not start from the SOP", error);
+ },
+ onSettled: () => {
+ cardStartRef.current = false;
},
});
@@ -666,7 +698,9 @@ function PromptBoxImpl(
generateWorkflowMutation.isPending ||
handoffWorkflowMutation.isPending ||
uploadDocumentMutation.isPending ||
- recordTaskMutation.isPending;
+ recordTaskMutation.isPending ||
+ startFromSopMutation.isPending;
+ const cardsBusy = isSubmitting || siblingBusy;
const {
isSupported: isSpeechSupported,
@@ -764,6 +798,7 @@ function PromptBoxImpl(
</div>
) : null;
+ // Only the redesigned (minimal) home still offers the "+" menu; the hero shows the cards instead.
const fileInput = (
<input
ref={fileInputRef}
@@ -873,12 +908,6 @@ function PromptBoxImpl(
<div className="px-5">{attachmentChips}</div>
) : null}
<div className="flex items-center gap-1.5 px-2.5 pb-2.5 pt-2">
- {!hideFlagControls && enableCopilotHandoff ? (
- <>
- {renderAddMenu("size-11 md:size-9")}
- {fileInput}
- </>
- ) : null}
{!hideFlagControls ? (
<SpeechInputButton
isSupported={isSpeechSupported}
@@ -935,8 +964,43 @@ function PromptBoxImpl(
}}
/>
) : null}
+ <StartFromCards
+ className="mt-3.5"
+ labelClassName="text-left"
+ gridClassName="md:grid-cols-2"
+ uploadSOP={{
+ onFile: (file) => {
+ if (cardStartRef.current || cardsBusy) return;
+ if (file.size > ATTACHMENT_SIZE_LIMIT_BYTES) {
+ toast({
+ variant: "destructive",
+ title: "File too large",
+ description: `${file.name} exceeds the 30MB limit.`,
+ });
+ return;
+ }
+ cardStartRef.current = true;
+ HomeTelemetry.uploadSopSelected();
+ startFromSopMutation.mutate(file);
+ },
+ disabled: cardsBusy,
+ }}
+ recordTask={{
+ onSelect: () => {
+ if (cardStartRef.current || cardsBusy) return;
+ cardStartRef.current = true;
+ HomeTelemetry.recordTaskSelected();
+ recordTaskMutation.mutate();
+ },
+ disabled: cardsBusy,
+ }}
+ />
{secondaryAction ? (
- <div className="mt-3 flex md:justify-end">{secondaryAction}</div>
+ <div className="mt-2.5 flex justify-start md:justify-center">
+ {typeof secondaryAction === "function"
+ ? secondaryAction({ busy: isSubmitting })
+ : secondaryAction}
+ </div>
) : null}
</div>
<section className="mt-9 w-full max-w-[60rem] md:mt-16">
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
index 9728c6d59..ded347645 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
@@ -298,7 +298,7 @@ async function attachSpreadsheet(
file = new File(["row_id,url\n"], filename),
) {
const input = document.querySelector(
- 'input[accept*=".pdf"]',
+ 'input[type="file"][accept*=".csv"]',
) as HTMLInputElement;
if (!input) throw new Error("composer has no attachment input");
await act(async () => {
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index d3c0f4b92..ea72c3ff8 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -3,6 +3,7 @@ import type {
EditorStateSnapshot,
RestoreResult,
} from "../editor/editorStateSnapshot";
+import { ATTACHMENT_SIZE_LIMIT_BYTES } from "./attachmentLimits";
import { flushBufferedEditorEdits } from "@/hooks/useDeferredLockedEdit";
import { hashKey } from "@tanstack/react-query";
import {
@@ -25,6 +26,7 @@ import {
} from "@/store/WorkflowYamlEditorStore";
import { ArtifactDownloadLink } from "@/components/ArtifactDownloadLink";
import { Button } from "@/components/ui/button";
+import { StartFromCards } from "@/components/StartFromCards";
import {
Fragment,
useState,
@@ -58,7 +60,6 @@ import {
ChevronDownIcon,
ArrowUpIcon,
FileIcon,
- UploadIcon,
PlusIcon,
PauseIcon,
ExclamationTriangleIcon,
@@ -791,8 +792,6 @@ const ATTACHMENT_EXTENSIONS = [
...VIDEO_ATTACHMENT_EXTENSIONS,
] as const;
const ATTACHMENT_ACCEPT = ATTACHMENT_EXTENSIONS.join(",");
-// Mirrors the server's MAX_UPLOAD_FILE_SIZE.
-const ATTACHMENT_SIZE_LIMIT_BYTES = 30 * 1024 * 1024;
// Mirrors MAX_ATTACHED_FILES_PER_MESSAGE on the chat request.
const ATTACHMENT_COUNT_LIMIT = 20;
@@ -1803,7 +1802,6 @@ export function WorkflowCopilotChat({
(outstandingAccept?.snapshot as CanonicalRecovery | undefined)
?.unattributedClaim === true;
const initialHandoffMessageId = `initial-copilot-message-${workflowPermanentId ?? "pending"}`;
- const sopFileInputRef = useRef<HTMLInputElement>(null);
// Set when a file is staged while the composer is hidden or not yet mounted.
const focusComposerWhenShownRef = useRef(false);
const recordingAuthoringActive = useRecordingStore(
@@ -11239,49 +11237,22 @@ export function WorkflowCopilotChat({
</p>
</div>
- <div className="[container-name:copilot-actions] [container-type:inline-size]">
- <p className="text-xs text-muted-foreground/80">
- Or start from
- </p>
- <div className="mt-2 grid grid-cols-1 gap-2 [@container_copilot-actions_(min-width:440px)]:grid-cols-2">
- <TooltipProvider>
- <ControlTooltip
- content={
- attachDisabledReason ??
- "Attach a procedure PDF for Copilot to build from"
- }
- blocked={attachDisabledReason !== null}
- 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={attachDisabledReason !== null}
- 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">
- Upload an SOP
- </span>
- <span className="mt-0.5 block text-xs leading-snug text-muted-foreground">
- A PDF of the procedure
- </span>
- </span>
- </button>
- </ControlTooltip>
- </TooltipProvider>
- <DemonstrateTaskButton
- disabled={recordTaskDisabled}
- disabledReason={recordTaskUnavailableReason}
- onClick={startRecordTask}
- />
- </div>
- </div>
+ <StartFromCards
+ className="[container-name:copilot-actions] [container-type:inline-size]"
+ gridClassName="[@container_copilot-actions_(min-width:440px)]:grid-cols-2"
+ uploadSOP={{
+ onFile: (file) => stageSopFile(file, sopAttachmentDraft()),
+ disabled: attachDisabledReason !== null,
+ tooltip: attachDisabledReason ?? undefined,
+ }}
+ recordTask={{
+ onSelect: startRecordTask,
+ disabled: recordTaskDisabled,
+ tooltip: recordTaskDisabled
+ ? recordTaskUnavailableReason
+ : undefined,
+ }}
+ />
</div>
) : null}
<ConvoAggregatePill
@@ -12534,18 +12505,6 @@ 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];
- event.target.value = "";
- if (file) stageSopFile(file, sopAttachmentDraft());
- }}
- />
{/* As tall as one textarea line box, so the controls center on the last line as the textarea grows. */}
<div className="flex h-10 shrink-0 items-center gap-1.5">
<button
diff --git a/skyvern-frontend/src/routes/workflows/copilot/attachmentLimits.ts b/skyvern-frontend/src/routes/workflows/copilot/attachmentLimits.ts
new file mode 100644
index 000000000..bcab3e1ef
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/attachmentLimits.ts
@@ -0,0 +1,2 @@
+// Mirrors the server's MAX_UPLOAD_FILE_SIZE.
+export const ATTACHMENT_SIZE_LIMIT_BYTES = 30 * 1024 * 1024;
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index ae28b2198..90380f21e 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -57,6 +57,7 @@ import {
useSearchParams,
} from "react-router-dom";
import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";
+import { takeSopHandoffFile } from "@/routes/workflows/sopHandoff";
import { useReactFlow, Edge } from "@xyflow/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { usePostHog } from "posthog-js/react";
@@ -264,6 +265,8 @@ import {
demonstrationInsertionFromNodes,
resolveAppendInsertionPoint,
resolveWorkspaceAuthoringActionAvailability,
+ sopAttachmentDraft,
+ stageSopFile,
} from "./workspaceAuthoringActions";
import { paneWidthsKey } from "../studio/paneLayout";
import { useStudioPanes } from "../studio/useStudioPanes";
@@ -1916,6 +1919,54 @@ function Workspace({
authoringBlocked,
startRecordingAtEnd,
]);
+ // `/discover`'s "Upload an SOP" lands here with ?sop=1; stage the PDF in Copilot once its
+ // composer can take a file.
+ const sopHandoffRequested = searchParams.get("sop") === "1";
+ const sopHandoffHandledRef = useRef(false);
+ // A boolean, not the function: the chat re-registers the stager whenever its callbacks change,
+ // and subscribing to the identity would re-render this component into a loop.
+ const copilotCanStageAttachment = useCopilotActionStore(
+ (state) => state.stageAttachment !== null,
+ );
+ useEffect(() => {
+ if (
+ !sopHandoffRequested ||
+ sopHandoffHandledRef.current ||
+ !copilotCanStageAttachment
+ ) {
+ return;
+ }
+ // Deferred past the mount commit: an upload started inside it is detached from its
+ // observer by StrictMode's simulated remount and reports pending forever.
+ const timer = window.setTimeout(() => {
+ sopHandoffHandledRef.current = true;
+ const file = takeSopHandoffFile(workflow.workflow_permanent_id);
+ if (file) stageSopFile(file, sopAttachmentDraft());
+ else
+ toast({
+ variant: "destructive",
+ title: "SOP not received",
+ description:
+ "The PDF did not reach the editor. Use Upload an SOP in the Copilot panel to try again.",
+ });
+ // After staging: opening the Copilot pane navigates with the current URL, which would
+ // put the marker back if it ran after this rewrite.
+ setRecordSearchParams(
+ (current) => {
+ const next = new URLSearchParams(current);
+ next.delete("sop");
+ return next;
+ },
+ { replace: true },
+ );
+ }, 0);
+ return () => window.clearTimeout(timer);
+ }, [
+ sopHandoffRequested,
+ copilotCanStageAttachment,
+ setRecordSearchParams,
+ workflow.workflow_permanent_id,
+ ]);
useEffect(() => {
if (!embedded) {
return;
diff --git a/skyvern-frontend/src/routes/workflows/sopHandoff.test.ts b/skyvern-frontend/src/routes/workflows/sopHandoff.test.ts
new file mode 100644
index 000000000..5ff8636c0
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/sopHandoff.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, test } from "vitest";
+
+import { rememberSopHandoffFile, takeSopHandoffFile } from "./sopHandoff";
+
+describe("sopHandoff", () => {
+ test("hands the file to its own workflow exactly once", () => {
+ const file = new File(["%PDF"], "procedure.pdf");
+ rememberSopHandoffFile("wpid_a", file);
+
+ expect(takeSopHandoffFile("wpid_b")).toBeNull();
+ expect(takeSopHandoffFile("wpid_a")).toBe(file);
+ expect(takeSopHandoffFile("wpid_a")).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/sopHandoff.ts b/skyvern-frontend/src/routes/workflows/sopHandoff.ts
new file mode 100644
index 000000000..01dc3a2cc
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/sopHandoff.ts
@@ -0,0 +1,21 @@
+type PendingSop = { workflowPermanentId: string; file: File };
+
+// Home hands the chosen PDF to the editor in memory: a File fits neither the URL nor
+// sessionStorage, and the editor consumes it exactly once, like `?record=1`.
+let pendingSop: PendingSop | null = null;
+
+export function rememberSopHandoffFile(
+ workflowPermanentId: string,
+ file: File,
+): void {
+ pendingSop = { workflowPermanentId, file };
+}
+
+export function takeSopHandoffFile(workflowPermanentId: string): File | null {
+ if (!pendingSop || pendingSop.workflowPermanentId !== workflowPermanentId) {
+ return null;
+ }
+ const { file } = pendingSop;
+ pendingSop = null;
+ return file;
+}
diff --git a/skyvern-frontend/src/util/homeTelemetry.ts b/skyvern-frontend/src/util/homeTelemetry.ts
index 0fa33a86e..03e622ec1 100644
--- a/skyvern-frontend/src/util/homeTelemetry.ts
+++ b/skyvern-frontend/src/util/homeTelemetry.ts
@@ -120,6 +120,7 @@ export const HomeTelemetry = {
uploadDocumentSelected: () => capture("upload_document_selected"),
uploadDocumentFinished: (ok: boolean) =>
capture("upload_document_finished", { ok }),
+ uploadSopSelected: () => capture("upload_sop_selected"),
recordTaskSelected: () => capture("record_task_selected"),
voiceToggled: () => capture("voice_toggled"),
skipToBlankCanvasClicked: (attempt: AgentCreationAttempt) =>
diff --git a/tests/conftest.py b/tests/conftest.py
index 387a03444..8d4430f48 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -17,6 +17,7 @@ import structlog
from _pytest.monkeypatch import NOTSET, derive_importpath
from structlog._config import BoundLoggerLazyProxy
+from skyvern.cli.core import action_log
from skyvern.config import settings
from skyvern.forge import app, forge_app_initializer, request_logging
from skyvern.forge.sdk.core import organization_age_cache
@@ -90,6 +91,13 @@ def _url_validation_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(settings, "ENABLE_URL_VALIDATION", True)
[email protected](autouse=True)
+def _no_action_log_delivery(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The shared MCP action-log worker posts each cloud-session tool call to SKYVERN_BASE_URL, the public API by
+ default. Tests that exercise delivery build their own ActionLogWorker."""
+ monkeypatch.setattr(action_log.action_log_worker, "_send_batch", AsyncMock())
+
+
LOOP_OWNER = ("skyvern/forge/agent.py", "_execute_task_v3")
# The loop's own contract tests call it directly by design.
LOOP_OWNER_EXEMPT_TEST_FILES = frozenset({"test_taskv3_engine.py"})
diff --git a/tests/unit/forge/sdk/copilot/test_browser_code_tool.py b/tests/unit/forge/sdk/copilot/test_browser_code_tool.py
index e0719ba7c..9a71e9ebf 100644
--- a/tests/unit/forge/sdk/copilot/test_browser_code_tool.py
+++ b/tests/unit/forge/sdk/copilot/test_browser_code_tool.py
@@ -844,7 +844,8 @@ async def test_fresh_namespace_rebinds_to_the_current_browser_before_resetting(
ctx = make_copilot_context()
ctx.browser_session_id = "pbs_replacement"
order: list[str] = []
- session = MagicMock(session_id="browser_code_session", page=object())
+ # No confirmed tab, so frame staging stops before it resolves the browser through the API.
+ session = MagicMock(session_id="browser_code_session", page=object(), confirmed_page=None)
async def reset_namespace() -> None:
order.append("reset")
@@ -893,7 +894,7 @@ async def test_fresh_namespace_does_not_reset_a_session_opened_for_a_replacement
ctx = make_copilot_context()
ctx.browser_session_id = "pbs_replacement"
old_session = MagicMock(session_id="old_browser_code_session")
- replacement_session = MagicMock(session_id="replacement_browser_code_session")
+ replacement_session = MagicMock(session_id="replacement_browser_code_session", confirmed_page=None)
replacement_session.reset_namespace = AsyncMock()
ctx.browser_code_host.session = old_session
diff --git a/tests/unit/test_api_handler_factory.py b/tests/unit/test_api_handler_factory.py
index 09b155247..9dfd52c89 100644
--- a/tests/unit/test_api_handler_factory.py
+++ b/tests/unit/test_api_handler_factory.py
@@ -182,6 +182,7 @@ async def test_custom_llm_http_clients_do_not_follow_redirects(
@pytest.mark.parametrize("request_error", [None, RuntimeError("provider failed")], ids=["success", "failure"])
@pytest.mark.asyncio
[email protected]("public_dns")
async def test_custom_openrouter_client_is_scoped_to_request(
monkeypatch: pytest.MonkeyPatch, request_error: Exception | None
) -> None:
@@ -344,6 +345,7 @@ async def test_hard_deadline_surfaces_as_retryable_from_the_public_call(monkeypa
@pytest.mark.asyncio
[email protected]("public_dns")
async def test_hard_deadline_on_a_custom_openrouter_client_closes_it(monkeypatch: pytest.MonkeyPatch) -> None:
async def _hang(**kwargs: Any) -> Any:
await asyncio.sleep(60)
@@ -502,6 +504,7 @@ def _litellm_rate_limit_error() -> Exception:
"make_rate_limit_error", [_openai_rate_limit_error, _litellm_rate_limit_error], ids=["openai", "litellm"]
)
@pytest.mark.asyncio
[email protected]("public_dns")
async def test_a_rate_limited_custom_client_call_is_retryable(
monkeypatch: pytest.MonkeyPatch, make_rate_limit_error: Any
) -> None:
diff --git a/tests/unit/test_iframe_support.py b/tests/unit/test_iframe_support.py
index 9a1082ab9..824bba8f6 100644
--- a/tests/unit/test_iframe_support.py
+++ b/tests/unit/test_iframe_support.py
@@ -60,6 +60,7 @@ class TestMCPFrameTools:
assert result["error"]["code"] == mcp_browser.ErrorCode.NO_ACTIVE_BROWSER
@pytest.mark.asyncio
+ @pytest.mark.usefixtures("public_dns")
async def test_navigate_clears_working_frame(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""skyvern_navigate must clear _working_frame to prevent stale frame references."""
from skyvern.cli.core.session_manager import SessionState
@@ -85,6 +86,7 @@ class TestMCPFrameTools:
assert state._working_frame is None
@pytest.mark.asyncio
+ @pytest.mark.usefixtures("public_dns")
async def test_navigate_clears_frame_on_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Frame state must be cleared even when navigation fails (partial load may destroy iframes)."""
from skyvern.cli.core.session_manager import SessionState
diff --git a/tests/unit/test_mcp_argument_validation.py b/tests/unit/test_mcp_argument_validation.py
index 203661d87..76fbed8eb 100644
--- a/tests/unit/test_mcp_argument_validation.py
+++ b/tests/unit/test_mcp_argument_validation.py
@@ -207,6 +207,7 @@ def test_csv_list_repair_leaves_excessive_item_count_for_other_validation() -> N
@pytest.mark.asyncio
[email protected]("public_dns")
async def test_navigate_sub_1000_timeout_is_treated_as_seconds_and_converted_to_milliseconds(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -244,6 +245,7 @@ async def test_navigate_fractional_seconds_stay_unchanged_when_rescaling_is_stil
@pytest.mark.asyncio
[email protected]("public_dns")
async def test_navigate_timeout_at_millisecond_threshold_is_not_scaled(monkeypatch: pytest.MonkeyPatch) -> None:
navigate = _mock_navigation(monkeypatch)
diff --git a/tests/unit/test_mcp_observe_execute.py b/tests/unit/test_mcp_observe_execute.py
index b7c5567d7..fc50a0144 100644
--- a/tests/unit/test_mcp_observe_execute.py
+++ b/tests/unit/test_mcp_observe_execute.py
@@ -1537,6 +1537,7 @@ class TestSkyvernExecuteMCP:
assert mcp_browser.skyvern_click.call_args.kwargs["selector"] == 'role=button[name="Current"]'
@pytest.mark.asyncio
+ @pytest.mark.usefixtures("public_dns")
async def test_navigate_clears_session_refs(self, monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_page()
ctx = BrowserContext(mode="cloud_session", session_id="pbs_navigate_refs")
@@ -1560,6 +1561,7 @@ class TestSkyvernExecuteMCP:
)
@pytest.mark.asyncio
+ @pytest.mark.usefixtures("public_dns")
async def test_navigate_clears_batch_refs(self, monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_page()
ctx = BrowserContext(mode="cloud_session", session_id="pbs_batch_navigate_refs")
@@ -1780,6 +1782,7 @@ class TestSkyvernExecuteMCP:
assert result.error_step is None
@pytest.mark.asyncio
+ @pytest.mark.usefixtures("public_dns")
async def test_observe_started_during_navigation_is_discarded(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""A generation captured while navigation is in flight must not commit after it completes."""
page = _make_page()
@@ -1900,6 +1903,7 @@ class TestSkyvernExecuteMCP:
click.assert_not_awaited()
@pytest.mark.asyncio
+ @pytest.mark.usefixtures("public_dns")
async def test_failed_navigation_still_invalidates_midflight_observe(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""A navigation that raises can still have replaced the document — mid-flight commits must die."""
page = _make_page()
diff --git a/tests/unit/test_mcp_session_lifecycle.py b/tests/unit/test_mcp_session_lifecycle.py
index 9b2f6137f..e793a13ee 100644
--- a/tests/unit/test_mcp_session_lifecycle.py
+++ b/tests/unit/test_mcp_session_lifecycle.py
@@ -2196,7 +2196,9 @@ async def test_session_close_without_id_closes_cloud_session_via_api_first(
)
fake_skyvern = MagicMock()
+ fake_skyvern.get_browser_session = AsyncMock(side_effect=RuntimeError("recording data unavailable"))
monkeypatch.setattr(session_manager, "get_skyvern", lambda: fake_skyvern)
+ monkeypatch.setattr(mcp_session, "get_skyvern", lambda: fake_skyvern)
async def _api_close(skyvern: object, session_id: str) -> SessionCloseResult:
call_order.append("api_close")
@@ -2236,7 +2238,9 @@ async def test_session_close_without_id_is_best_effort_when_api_close_fails(
)
fake_skyvern = MagicMock()
+ fake_skyvern.get_browser_session = AsyncMock(side_effect=RuntimeError("recording data unavailable"))
monkeypatch.setattr(session_manager, "get_skyvern", lambda: fake_skyvern)
+ monkeypatch.setattr(mcp_session, "get_skyvern", lambda: fake_skyvern)
do_session_close = AsyncMock(side_effect=ConnectionError("API close failed"))
monkeypatch.setattr("skyvern.cli.core.session_ops.do_session_close", do_session_close)