Skip to content

Automate browser based workflows with AI

feat(SKY-9304): hand off /discover prompt to workflow copilot chat (#5723)

Andrew Neilson3a157801a911
diff --git a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
index 5a29b4e51..9d79e9b94 100644
--- a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
+++ b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
@@ -1,10 +1,14 @@
+import { useFeatureFlag } from "@/hooks/useFeatureFlag";
import { PromptBox } from "../tasks/create/PromptBox";
import { WorkflowTemplates } from "./WorkflowTemplates";
function DiscoverPage() {
+ const enableCopilotHandoff =
+ useFeatureFlag("ENABLE_DISCOVER_COPILOT_HANDOFF") === true;
+
return (
<div className="space-y-10">
- <PromptBox />
+ <PromptBox enableCopilotHandoff={enableCopilotHandoff} />
<WorkflowTemplates />
</div>
);
diff --git a/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx b/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
index 76d63f656..03c23d6be 100644
--- a/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
+++ b/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
@@ -1,5 +1,7 @@
import { getClient } from "@/api/AxiosClient";
import { Createv2TaskRequest, ProxyLocation } from "@/api/types";
+import { stringify as convertToYAML } from "yaml";
+import { WorkflowCreateYAMLRequest } from "@/routes/workflows/types/workflowYamlTypes";
import img from "@/assets/promptBoxBg.png";
import { AutoResizingTextarea } from "@/components/AutoResizingTextarea/AutoResizingTextarea";
import { CartIcon } from "@/components/icons/CartIcon";
@@ -34,7 +36,7 @@ import {
} from "@radix-ui/react-icons";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
-import { useState } from "react";
+import { useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
generatePhoneNumber,
@@ -111,7 +113,35 @@ const exampleCases = [
},
];
-function PromptBox() {
+type PromptBoxProps = {
+ enableCopilotHandoff?: boolean;
+};
+
+const HANDOFF_TITLE_MAX_LEN = 80;
+
+function deriveHandoffTitle(prompt: string): string {
+ const collapsed = prompt.replace(/\s+/g, " ").trim();
+ if (!collapsed) return "New Workflow";
+ if (collapsed.length <= HANDOFF_TITLE_MAX_LEN) return collapsed;
+ return `${collapsed.slice(0, HANDOFF_TITLE_MAX_LEN - 1).trimEnd()}…`;
+}
+
+function buildBlankWorkflowRequest(title: string): WorkflowCreateYAMLRequest {
+ return {
+ title,
+ description: "",
+ ai_fallback: true,
+ code_version: 2,
+ run_with: "code",
+ workflow_definition: {
+ version: 2,
+ blocks: [],
+ parameters: [],
+ },
+ };
+}
+
+function PromptBox({ enableCopilotHandoff = false }: PromptBoxProps) {
const navigate = useNavigate();
const [prompt, setPrompt] = useState<string>("");
const [selectValue, setSelectValue] = useState<"v1" | "v2" | "v2-code">(
@@ -139,6 +169,9 @@ function PromptBox() {
const [extraHttpHeaders, setExtraHttpHeaders] = useState<string | null>(null);
const { setAutoplay } = useAutoplayStore();
const [promptImprovalIsPending, setPromptImprovalIsPending] = useState(false);
+ // 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);
const generateWorkflowMutation = useMutation({
mutationFn: async ({
@@ -228,8 +261,68 @@ function PromptBox() {
description: error.message,
});
},
+ onSettled: () => {
+ submitInFlightRef.current = false;
+ },
});
+ const handoffWorkflowMutation = useMutation({
+ mutationFn: async ({ prompt }: { prompt: string }) => {
+ const client = await getClient(credentialGetter);
+ const yaml = convertToYAML(
+ buildBlankWorkflowRequest(deriveHandoffTitle(prompt)),
+ );
+ const result = await client.post<string, { data: WorkflowApiResponse }>(
+ "/workflows",
+ yaml,
+ {
+ headers: {
+ "Content-Type": "text/plain",
+ },
+ },
+ );
+ return { data: result.data, prompt };
+ },
+ onSuccess: ({ data: workflow, prompt }) => {
+ queryClient.invalidateQueries({ queryKey: ["workflows"] });
+ queryClient.invalidateQueries({ queryKey: ["folders"] });
+ navigate(`/workflows/${workflow.workflow_permanent_id}/build`, {
+ state: { copilotMessage: prompt },
+ });
+ },
+ onError: (error: AxiosError) => {
+ toast({
+ variant: "destructive",
+ title: "Error creating workflow",
+ description: error.message,
+ });
+ },
+ onSettled: () => {
+ submitInFlightRef.current = false;
+ },
+ });
+
+ const isSubmitting =
+ generateWorkflowMutation.isPending || handoffWorkflowMutation.isPending;
+
+ const submitPrompt = ({
+ prompt,
+ legacyVersion,
+ }: {
+ prompt: string;
+ legacyVersion: "v1" | "v2" | "v2-code";
+ }) => {
+ if (submitInFlightRef.current || isSubmitting) {
+ return;
+ }
+ submitInFlightRef.current = true;
+ if (enableCopilotHandoff) {
+ handoffWorkflowMutation.mutate({ prompt });
+ return;
+ }
+ generateWorkflowMutation.mutate({ prompt, version: legacyVersion });
+ };
+
return (
<div>
<div
@@ -335,29 +428,28 @@ function PromptBox() {
size="large"
useCase="new_workflow"
/>
- <div className="flex items-center">
- <GearIcon
- className="size-6 cursor-pointer"
- onClick={() => {
- setShowAdvancedSettings((value) => !value);
- }}
- />
- </div>
+ {!enableCopilotHandoff ? (
+ <div className="flex items-center">
+ <GearIcon
+ className="size-6 cursor-pointer"
+ onClick={() => {
+ setShowAdvancedSettings((value) => !value);
+ }}
+ />
+ </div>
+ ) : null}
<div
className={cn("flex items-center", {
"pointer-events-none opacity-20": !prompt.trim(),
})}
>
- {generateWorkflowMutation.isPending ? (
+ {isSubmitting ? (
<ReloadIcon className="size-6 animate-spin" />
) : (
<PaperPlaneIcon
className="size-6 cursor-pointer"
- onClick={async () => {
- generateWorkflowMutation.mutate({
- prompt,
- version: selectValue,
- });
+ onClick={() => {
+ submitPrompt({ prompt, legacyVersion: selectValue });
}}
/>
)}
@@ -574,9 +666,9 @@ function PromptBox() {
icon={example.icon}
label={example.label}
onClick={() => {
- generateWorkflowMutation.mutate({
+ submitPrompt({
prompt: example.prompt,
- version: "v2",
+ legacyVersion: "v2",
});
}}
/>
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 7ff936ea3..1e8efa5bd 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -122,8 +122,12 @@ interface WorkflowCopilotChatProps {
onMessageCountChange?: (count: number) => void;
buttonRef?: React.RefObject<HTMLButtonElement>;
liveBrowserSessionId?: string | null;
+ initialMessage?: string;
+ onInitialMessageConsumed?: () => void;
}
+const AUTO_SEND_TIMEOUT_MS = 5000;
+
const DEFAULT_WINDOW_WIDTH = 600;
const DEFAULT_WINDOW_HEIGHT = 400;
const MIN_WINDOW_WIDTH = 300;
@@ -174,6 +178,8 @@ export function WorkflowCopilotChat({
onMessageCountChange,
buttonRef,
liveBrowserSessionId,
+ initialMessage,
+ onInitialMessageConsumed,
}: WorkflowCopilotChatProps = {}) {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [proposedWorkflow, setProposedWorkflow] =
@@ -228,6 +234,19 @@ export function WorkflowCopilotChat({
const { getSaveData } = useWorkflowHasChangesStore();
const hasInitializedPosition = useRef(false);
const hasScrolledOnLoad = useRef(false);
+ const hasAutoSentRef = useRef(false);
+ // Reset on initialMessage change so a re-arrival of the prop (without a
+ // remount) can fire auto-send again.
+ useEffect(() => {
+ hasAutoSentRef.current = false;
+ }, [initialMessage]);
+ const onInitialMessageConsumedRef = useRef(onInitialMessageConsumed);
+ useEffect(() => {
+ onInitialMessageConsumedRef.current = onInitialMessageConsumed;
+ }, [onInitialMessageConsumed]);
+ // Pinned per workflow so dep-change re-fires can't clobber locally-pushed
+ // messages, and so auto-send has a synchronous "history loaded" gate.
+ const historyLoadedForRef = useRef<string | null>(null);
const scrollToBottom = (behavior: ScrollBehavior) => {
messagesEndRef.current?.scrollIntoView({ behavior });
@@ -459,6 +478,11 @@ export function WorkflowCopilotChat({
setWorkflowCopilotChatId(null);
setProposedWorkflow(null);
setAutoAccept(false);
+ historyLoadedForRef.current = null;
+ return;
+ }
+
+ if (historyLoadedForRef.current === workflowPermanentId) {
return;
}
@@ -490,6 +514,7 @@ export function WorkflowCopilotChat({
setWorkflowCopilotChatId(response.data.workflow_copilot_chat_id);
setProposedWorkflow(response.data.proposed_workflow ?? null);
setAutoAccept(response.data.auto_accept ?? false);
+ historyLoadedForRef.current = workflowPermanentId;
} catch (error) {
console.error("Failed to load chat history:", error);
} finally {
@@ -533,8 +558,9 @@ export function WorkflowCopilotChat({
streamingAbortController.current?.abort();
};
- const handleSend = async () => {
- if (!inputValue.trim() || isLoading) return;
+ const handleSend = async (messageOverride?: string) => {
+ const candidate = messageOverride ?? inputValue;
+ if (!candidate.trim() || isLoading) return;
if (!workflowPermanentId) {
toast({
title: "Missing workflow",
@@ -548,14 +574,16 @@ export function WorkflowCopilotChat({
const userMessage: ChatMessage = {
id: userMessageId,
sender: "user",
- content: inputValue,
+ content: candidate,
};
pendingMessageId.current = userMessageId;
setMessages((prev) => [...prev, userMessage]);
setProposedWorkflow(null);
- const messageContent = inputValue;
- setInputValue("");
+ const messageContent = candidate;
+ if (messageOverride === undefined) {
+ setInputValue("");
+ }
setIsLoading(true);
setProcessingStatus("Starting...");
setLatestNarration("");
@@ -783,6 +811,69 @@ export function WorkflowCopilotChat({
}
};
+ useEffect(() => {
+ if (!initialMessage || hasAutoSentRef.current) {
+ return;
+ }
+ if (isLoadingHistory || isLoading || !workflowPermanentId) {
+ return;
+ }
+ // Synchronous gate: isLoadingHistory state is stale in this effect's
+ // closure when both effects run in the same commit.
+ if (historyLoadedForRef.current !== workflowPermanentId) {
+ return;
+ }
+ const saveData = getSaveData();
+ if (
+ !saveData?.workflow.workflow_id ||
+ saveData.workflow.workflow_permanent_id !== workflowPermanentId
+ ) {
+ return;
+ }
+ // Trip the guard before any await so the 5s timeout cannot toast over
+ // an in-flight send.
+ hasAutoSentRef.current = true;
+ onInitialMessageConsumedRef.current?.();
+ handleSend(initialMessage).catch((error) => {
+ console.error("Auto-send failed:", error);
+ });
+ // handleSend omitted: a new reference each render would re-fire the effect.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ initialMessage,
+ isLoadingHistory,
+ isLoading,
+ workflowPermanentId,
+ getSaveData,
+ ]);
+
+ useEffect(() => {
+ if (!initialMessage || hasAutoSentRef.current) {
+ return;
+ }
+ if (isLoadingHistory) {
+ return;
+ }
+ const saveData = getSaveData();
+ if (!saveData?.workflow.workflow_id) {
+ return;
+ }
+ const timer = window.setTimeout(() => {
+ if (hasAutoSentRef.current) return;
+ hasAutoSentRef.current = true;
+ onInitialMessageConsumedRef.current?.();
+ toast({
+ title: "Could not auto-send message",
+ description:
+ "The copilot was not ready in time — please retype your prompt.",
+ variant: "destructive",
+ });
+ }, AUTO_SEND_TIMEOUT_MS);
+ return () => {
+ window.clearTimeout(timer);
+ };
+ }, [initialMessage, isLoadingHistory, getSaveData]);
+
const handleMouseDown = (e: React.MouseEvent) => {
setIsDragging(true);
setDragStart({
@@ -1099,7 +1190,7 @@ export function WorkflowCopilotChat({
}}
/>
<button
- onClick={handleSend}
+ onClick={() => handleSend()}
disabled={isLoading}
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
>
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index dea85db40..1eea34d41 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -18,7 +18,12 @@ import {
PlayIcon,
ReloadIcon,
} from "@radix-ui/react-icons";
-import { useParams, useSearchParams } from "react-router-dom";
+import {
+ useLocation,
+ useNavigate,
+ useParams,
+ useSearchParams,
+} from "react-router-dom";
import {
useEdgesState,
useNodesState,
@@ -236,6 +241,20 @@ function Workspace({
workflow,
}: Props) {
const { blockLabel, workflowPermanentId } = useParams();
+ const location = useLocation();
+ const navigate = useNavigate();
+ const locationState = location.state as { copilotMessage?: unknown } | null;
+ const initialCopilotMessage =
+ typeof locationState?.copilotMessage === "string"
+ ? locationState.copilotMessage
+ : null;
+ const handleInitialCopilotMessageConsumed = useCallback(() => {
+ if (!initialCopilotMessage) return;
+ navigate(location.pathname + location.search, {
+ replace: true,
+ state: null,
+ });
+ }, [initialCopilotMessage, location.pathname, location.search, navigate]);
const [searchParams, setSearchParams] = useSearchParams();
const cacheKeyValueParam = searchParams.get("cache-key-value");
const [timelineMode, setTimelineMode] = useState("wide");
@@ -263,7 +282,7 @@ function Workspace({
const [openCycleBrowserDialogue, setOpenCycleBrowserDialogue] =
useState(false);
const [isCopilotOpen, setIsCopilotOpen] = useState(
- () => !initialNodes.some(isWorkflowBlockNode),
+ () => !!initialCopilotMessage || !initialNodes.some(isWorkflowBlockNode),
);
const [copilotMessageCount, setCopilotMessageCount] = useState(0);
const copilotButtonRef = useRef<HTMLButtonElement>(null);
@@ -565,7 +584,10 @@ function Workspace({
if (activeDebugSession) {
const pbsId = activeDebugSession.browser_session_id;
if (pbsId) {
- window.open(`${location.origin}/browser-session/${pbsId}`, "_blank");
+ window.open(
+ `${window.location.origin}/browser-session/${pbsId}`,
+ "_blank",
+ );
}
}
};
@@ -2012,6 +2034,8 @@ function Workspace({
onMessageCountChange={setCopilotMessageCount}
buttonRef={copilotButtonRef}
liveBrowserSessionId={activeDebugSession?.browser_session_id ?? null}
+ initialMessage={initialCopilotMessage ?? undefined}
+ onInitialMessageConsumed={handleInitialCopilotMessageConsumed}
onReviewWorkflow={async (pendingWorkflow, clearPending) => {
const saveData = workflowChangesStore.getSaveData?.();
if (!saveData) return;