Skip to content

Automate browser based workflows with AI

Lock the Copilot review gate's Test end-to-end menu item like Reject (SKY-17393) (#8715)

Shuchang Zheng402fc28be401
diff --git a/docs/cloud/getting-started/run-a-task.mdx b/docs/cloud/getting-started/run-a-task.mdx
index 405abfe80..22b5b0e32 100644
--- a/docs/cloud/getting-started/run-a-task.mdx
+++ b/docs/cloud/getting-started/run-a-task.mdx
@@ -33,7 +33,7 @@ Type a natural language instruction describing what you want automated. Be speci
Click the **send button** or press **Enter** to start.
-Below the prompt box, **quick-action buttons** offer pre-built examples like "Add a product to cart" or "Get an insurance quote." Click one to run it immediately or use it as a starting point.
+Below the prompt box, **example cards** offer pre-built prompts like "Apply for a job" or "Get an insurance quote." Click one to load it into the prompt box, edit it if you like, then send it.
---
diff --git a/docs/cloud/getting-started/run-your-first-task.mdx b/docs/cloud/getting-started/run-your-first-task.mdx
index fb530d5a8..106af98a4 100644
--- a/docs/cloud/getting-started/run-your-first-task.mdx
+++ b/docs/cloud/getting-started/run-your-first-task.mdx
@@ -28,7 +28,7 @@ Get the title of the #1 post on the front page for https://news.ycombinator.com
That's it. Skyvern parses the URL and figures out how to navigate the page and extract the data.
-Below the input, you'll see quick-action chips like "Add a product to cart" and "What's the top post on hackernews". Click any of these to try a pre-filled example instead.
+Below the input, you'll see example cards like "Apply for a job" and "Add a product to cart". Click one to load it into the input, edit it if you like, then send it.
<Tip>
The more specific your prompt, the better. "Get the title of the #1 post" works much better than "get some data." Include the exact fields you want, what success looks like, and any constraints.
@@ -36,10 +36,10 @@ The more specific your prompt, the better. "Get the title of the #1 post" works
## Step 2: Create and run the agent
-Click the **send button** (arrow icon to the right of the input). Skyvern generates an agent from your prompt using the default Skyvern 1.0 task engine and opens it in the agent editor. Click **Run** in the top right, confirm the parameters, then click **Run agent** to start execution.
+Click the **send button** (arrow icon in the bottom-right corner of the input). Skyvern generates an agent from your prompt using the default Skyvern 1.0 task engine and opens it in the agent editor. Click **Run** in the top right, confirm the parameters, then click **Run agent** to start execution.
<Accordion title="Optional: Advanced settings">
-Click the **gear icon** next to send to configure additional options before running:
+Click the **gear icon** below the input to configure additional options before running:
| Setting | What it does |
|---------|-------------|
diff --git a/skyvern-frontend/src/components/BrowserStream.tsx b/skyvern-frontend/src/components/BrowserStream.tsx
index ca585a876..90c5983d1 100644
--- a/skyvern-frontend/src/components/BrowserStream.tsx
+++ b/skyvern-frontend/src/components/BrowserStream.tsx
@@ -19,6 +19,7 @@ import { RecordingPill } from "@/components/RecordingPill";
import { Tip } from "@/components/Tip";
import { toast } from "@/components/ui/use-toast";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useLogging } from "@/hooks/useLogging";
import { statusIsNotFinalized } from "@/routes/tasks/types";
import { useRecordingStore } from "@/store/useRecordingStore";
import { useSettingsStore } from "@/store/SettingsStore";
@@ -250,12 +251,16 @@ function BrowserStream({
const messageReconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(
null,
);
+ const gaveUpLoggedRef = useRef(false);
+ const streamLogFieldsRef = useRef({ browserSessionId, entity, runId });
+ streamLogFieldsRef.current = { browserSessionId, entity, runId };
const isRecording = useRecordingStore((state) => state.isRecording);
const workflowPermanentId = useRecordingStore(
(state) => state.workflowPermanentId,
);
const settingsStore = useSettingsStore();
const credentialGetter = useCredentialGetter();
+ const logging = useLogging();
const getWebSocketParams = useWebSocketParams();
const isBrowserSessionAvailable =
entity !== "browserSession" || hasBrowserSession;
@@ -326,6 +331,7 @@ function BrowserStream({
setIsBrowserSessionEnded(false);
setHasGivenUp(false);
setTerminalDiagnostic(null);
+ gaveUpLoggedRef.current = false;
messageReconnectAttemptsRef.current = 0;
if (messageReconnectTimerRef.current) {
clearTimeout(messageReconnectTimerRef.current);
@@ -433,6 +439,20 @@ function BrowserStream({
if (messageReconnectAttemptsRef.current >= MESSAGE_MAX_RECONNECT_ATTEMPTS) {
setTerminalDiagnostic((prev) => prev ?? STREAM_GAVE_UP_DIAGNOSTIC);
setHasGivenUp(true);
+ if (!gaveUpLoggedRef.current) {
+ gaveUpLoggedRef.current = true;
+ logging.warn("Stream gave up", {
+ stream: "vnc",
+ browser_session_id:
+ streamLogFieldsRef.current.browserSessionId ?? null,
+ workflow_run_id:
+ streamLogFieldsRef.current.entity === "workflow"
+ ? streamLogFieldsRef.current.runId
+ : null,
+ reason: "message_reconnect_exhausted",
+ reconnect_attempts: messageReconnectAttemptsRef.current,
+ });
+ }
return;
}
@@ -444,7 +464,7 @@ function BrowserStream({
messageReconnectTimerRef.current = null;
setMessagesDisconnectedTrigger((x) => x + 1);
}, MESSAGE_RECONNECT_DELAY_MS);
- }, [isMessageConnected, isVncConnected]);
+ }, [isMessageConnected, isVncConnected, logging]);
useEffect(() => {
return () => {
@@ -585,6 +605,20 @@ function BrowserStream({
);
} else {
setHasGivenUp(true);
+ if (!gaveUpLoggedRef.current) {
+ gaveUpLoggedRef.current = true;
+ logging.warn("Stream gave up", {
+ stream: "vnc",
+ browser_session_id:
+ streamLogFieldsRef.current.browserSessionId ?? null,
+ workflow_run_id:
+ streamLogFieldsRef.current.entity === "workflow"
+ ? streamLogFieldsRef.current.runId
+ : null,
+ reason: "reconnect_exhausted",
+ reconnect_attempts: vncReconnectAttemptsRef.current,
+ });
+ }
}
onClose?.();
const clean = Boolean(e.detail?.clean);
@@ -636,6 +670,7 @@ function BrowserStream({
runId,
showStream,
vncDisconnectedTrigger, // will re-run on disconnects
+ logging,
],
);
diff --git a/skyvern-frontend/src/components/PaneErrorBoundary.test.tsx b/skyvern-frontend/src/components/PaneErrorBoundary.test.tsx
new file mode 100644
index 000000000..67d1b68c3
--- /dev/null
+++ b/skyvern-frontend/src/components/PaneErrorBoundary.test.tsx
@@ -0,0 +1,69 @@
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { PaneErrorBoundary } from "./PaneErrorBoundary";
+
+describe("PaneErrorBoundary", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("reports a crash, renders a fallback, and reloads the panel", () => {
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const error = new Error("panel crashed");
+ let shouldThrow = true;
+ const onError = vi.fn(() => {
+ shouldThrow = false;
+ });
+
+ function Child() {
+ if (shouldThrow) {
+ throw error;
+ }
+ return <div>Panel recovered</div>;
+ }
+
+ render(
+ <PaneErrorBoundary pane="editor" onError={onError}>
+ <Child />
+ </PaneErrorBoundary>,
+ );
+
+ expect(screen.getByText("This panel hit an error.")).toBeTruthy();
+ expect(onError).toHaveBeenCalledOnce();
+ expect(onError).toHaveBeenCalledWith(error, expect.any(String));
+
+ fireEvent.click(screen.getByRole("button", { name: "Reload panel" }));
+
+ expect(screen.getByText("Panel recovered")).toBeTruthy();
+ expect(onError).toHaveBeenCalledOnce();
+ });
+
+ it("renders the fallback in the fallback container", () => {
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const fallbackContainer = document.createElement("div");
+ document.body.appendChild(fallbackContainer);
+
+ function Child(): null {
+ throw new Error("panel crashed");
+ }
+
+ const view = render(
+ <PaneErrorBoundary
+ pane="copilot"
+ fallbackContainer={fallbackContainer}
+ onError={() => undefined}
+ >
+ <Child />
+ </PaneErrorBoundary>,
+ );
+
+ expect(
+ within(fallbackContainer).getByText("This panel hit an error."),
+ ).toBeTruthy();
+ expect(view.container.childElementCount).toBe(0);
+
+ view.unmount();
+ fallbackContainer.remove();
+ });
+});
diff --git a/skyvern-frontend/src/components/PaneErrorBoundary.tsx b/skyvern-frontend/src/components/PaneErrorBoundary.tsx
new file mode 100644
index 000000000..a42f621ae
--- /dev/null
+++ b/skyvern-frontend/src/components/PaneErrorBoundary.tsx
@@ -0,0 +1,59 @@
+import { Component, type ErrorInfo, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+
+import { Button } from "@/components/ui/button";
+
+type Props = {
+ pane: string;
+ onError: (error: unknown, componentStack?: string | null) => void;
+ fallbackContainer?: HTMLElement | null;
+ children: ReactNode;
+};
+
+type State = {
+ crashed: boolean;
+};
+
+class PaneErrorBoundary extends Component<Props, State> {
+ state: State = { crashed: false };
+
+ static getDerivedStateFromError(): State {
+ return { crashed: true };
+ }
+
+ componentDidCatch(error: unknown, info: ErrorInfo): void {
+ this.props.onError(error, info.componentStack);
+ }
+
+ private reload = () => {
+ this.setState({ crashed: false });
+ };
+
+ render() {
+ if (!this.state.crashed) {
+ return this.props.children;
+ }
+
+ const fallback = (
+ <div
+ aria-label={`${this.props.pane} panel error`}
+ className="flex h-full min-h-32 w-full items-center justify-center p-4"
+ >
+ <div className="flex flex-col items-center gap-3 text-center">
+ <p className="text-sm text-muted-foreground">
+ This panel hit an error.
+ </p>
+ <Button size="sm" variant="outline" onClick={this.reload}>
+ Reload panel
+ </Button>
+ </div>
+ </div>
+ );
+
+ return this.props.fallbackContainer
+ ? createPortal(fallback, this.props.fallbackContainer)
+ : fallback;
+ }
+}
+
+export { PaneErrorBoundary };
diff --git a/skyvern-frontend/src/hooks/useSpeechToText.test.ts b/skyvern-frontend/src/hooks/useSpeechToText.test.ts
index 6ac93ea49..d79348c05 100644
--- a/skyvern-frontend/src/hooks/useSpeechToText.test.ts
+++ b/skyvern-frontend/src/hooks/useSpeechToText.test.ts
@@ -300,6 +300,48 @@ describe("useSpeechToText", () => {
);
});
+ it("drops a transcript that arrives after cancel", async () => {
+ const onTranscript = vi.fn();
+ const { result } = renderHook(() =>
+ useSpeechToText({
+ getBaseText: () => "before dictation",
+ onTranscript,
+ }),
+ );
+
+ await startSpeech(() => result.current.start());
+ const recognition = MockSpeechRecognition.lastInstance;
+ act(() => result.current.cancel());
+ act(() => {
+ recognition?.emitResult("late words");
+ });
+
+ expect(result.current.isListening).toBe(false);
+ expect(onTranscript).not.toHaveBeenCalled();
+ });
+
+ it("does not start dictation when cancelled during the permission prompt", async () => {
+ let grantPermission: (stream: unknown) => void = () => {};
+ mockGetUserMedia.mockReturnValueOnce(
+ new Promise((resolve) => {
+ grantPermission = resolve;
+ }),
+ );
+ const { result } = renderHook(() =>
+ useSpeechToText({ onTranscript: vi.fn() }),
+ );
+
+ act(() => result.current.start());
+ act(() => result.current.cancel());
+ await act(async () => {
+ grantPermission({ getTracks: () => [{ stop: trackStop }] });
+ await Promise.resolve();
+ });
+
+ expect(MockSpeechRecognition.lastInstance).toBeNull();
+ expect(result.current.isListening).toBe(false);
+ });
+
it("starts from an empty base text", async () => {
const onTranscript = vi.fn();
const { result } = renderHook(() =>
diff --git a/skyvern-frontend/src/hooks/useSpeechToText.ts b/skyvern-frontend/src/hooks/useSpeechToText.ts
index 522adde7c..e2a8b95e4 100644
--- a/skyvern-frontend/src/hooks/useSpeechToText.ts
+++ b/skyvern-frontend/src/hooks/useSpeechToText.ts
@@ -146,6 +146,8 @@ export interface UseSpeechToTextResult {
start: () => void;
/** Resolves with captured audio when available; callers may ignore it. */
stop: () => Promise<Blob | null>;
+ /** Stops immediately and drops any transcript still in flight. */
+ cancel: () => void;
toggle: () => void;
takeAudioBlob: () => Blob | null;
}
@@ -222,6 +224,7 @@ export function useSpeechToText(
null,
);
const isStartingRef = useRef(false);
+ const startTokenRef = useRef(0);
const onTranscriptRef = useRef(onTranscript);
const onErrorRef = useRef(onError);
@@ -407,6 +410,16 @@ export function useSpeechToText(
teardownRecognition,
]);
+ const cancel = useCallback(() => {
+ startTokenRef.current += 1;
+ shouldKeepListeningRef.current = false;
+ isListeningRef.current = false;
+ setIsListening(false);
+ clearHearingSpeech();
+ teardownRecognition();
+ void stopAudioCapture();
+ }, [clearHearingSpeech, stopAudioCapture, teardownRecognition]);
+
const beginRecognition = useCallback(() => {
const SpeechRecognitionCtor = getSpeechRecognitionConstructor();
if (
@@ -555,12 +568,17 @@ export function useSpeechToText(
}
isStartingRef.current = true;
+ const startToken = ++startTokenRef.current;
void (async () => {
try {
await requestMicrophonePermission();
- if (!enabledRef.current || isListeningRef.current) {
+ if (
+ startToken !== startTokenRef.current ||
+ !enabledRef.current ||
+ isListeningRef.current
+ ) {
return;
}
@@ -609,6 +627,7 @@ export function useSpeechToText(
isHearingSpeech,
start,
stop,
+ cancel,
toggle,
takeAudioBlob,
};
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
index 753e3492d..4df8f34d9 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useLogging } from "@/hooks/useLogging";
import { newWssBaseUrl, getCredentialParam } from "@/util/env";
import { useCdpInput } from "@/routes/streaming/useCdpInput";
import {
@@ -141,6 +142,7 @@ function BrowserSessionStream({
useState<StreamDiagnostic>(STARTING_DIAGNOSTIC);
const [isStopped, setIsStopped] = useState(false);
const credentialGetter = useCredentialGetter();
+ const logging = useLogging();
const settingsStore = useSettingsStore();
const socketRef = useRef<WebSocket | null>(null);
@@ -164,6 +166,7 @@ function BrowserSessionStream({
const lastCommittedTokenRef = useRef<number>(0);
const reconnectAttemptsRef = useRef(0);
const streamFinishedRef = useRef(false);
+ const parseFailureLoggedRef = useRef(false);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const recordingReconnectTimerRef = useRef<ReturnType<
typeof setTimeout
@@ -448,6 +451,7 @@ function BrowserSessionStream({
hasFrameRef.current = false;
reconnectAttemptsRef.current = 0;
streamFinishedRef.current = false;
+ parseFailureLoggedRef.current = false;
streamEndedDiagnosticRef.current = null;
const clearReconnectTimer = () => {
@@ -594,6 +598,14 @@ function BrowserSessionStream({
}
} catch (e) {
console.error("Failed to parse message", e);
+ if (!parseFailureLoggedRef.current) {
+ parseFailureLoggedRef.current = true;
+ logging.warn("Stream message parse failed", {
+ stream: "cdp",
+ browser_session_id: browserSessionId,
+ workflow_run_id: null,
+ });
+ }
// The backend only sends non-JSON text to reject credentials, and
// retrying that would just burn the reconnect budget in silence.
streamFinishedRef.current = true;
@@ -676,6 +688,13 @@ function BrowserSessionStream({
setDiagnostic(
diagnosticForReconnectExhausted(BROWSER_SESSION_STREAM_SUBJECT),
);
+ logging.warn("Stream gave up", {
+ stream: "cdp",
+ browser_session_id: browserSessionId,
+ workflow_run_id: null,
+ reason: "reconnect_exhausted",
+ reconnect_attempts: reconnectAttemptsRef.current,
+ });
}
});
}
@@ -691,7 +710,7 @@ function BrowserSessionStream({
socket.close();
}
};
- }, [credentialGetter, browserSessionId, forceCdp]);
+ }, [credentialGetter, browserSessionId, forceCdp, logging]);
const isReady = streamImgSrc.length > 0;
const streamState: StreamState = isReady
diff --git a/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx b/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
index 11592e904..79e51ba87 100644
--- a/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
+++ b/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
@@ -87,8 +87,8 @@ vi.mock("@/routes/tasks/create/PromptBox", async () => {
return {
PromptBox: React.forwardRef<
{ focusAndPrefillExample: (key: string) => void },
- Record<string, never>
- >(function PromptBoxMock(_, ref) {
+ { secondaryAction?: React.ReactNode }
+ >(function PromptBoxMock({ secondaryAction }, ref) {
const [value, setValue] = React.useState("");
const textareaRef = React.useRef<HTMLTextAreaElement>(null);
React.useImperativeHandle(ref, () => ({
@@ -107,6 +107,7 @@ vi.mock("@/routes/tasks/create/PromptBox", async () => {
value={value}
onChange={(event) => setValue(event.target.value)}
/>
+ {secondaryAction}
</div>
);
}),
@@ -460,9 +461,10 @@ describe("DiscoverPage onboarding mount", () => {
it("preserves content order and mounts over seeded template data", async () => {
renderDiscover(baseState);
- const content = screen.getByTestId("discover-templates").parentElement;
+ const content =
+ screen.getByTestId("discover-templates").parentElement?.parentElement;
expect(content?.textContent).toBe(
- "Create an agentpromptSkip — start with blank canvas →templates",
+ "Create an agentpromptStart with a blank canvastemplates",
);
expect(screen.queryByText("Build your first agent")).toBeNull();
expect(screen.queryByText(/Keep going/)).toBeNull();
@@ -478,7 +480,7 @@ describe("DiscoverPage onboarding mount", () => {
);
fireEvent.click(
- screen.getByRole("button", { name: /start with blank canvas/i }),
+ screen.getByRole("button", { name: /start with a blank canvas/i }),
);
const submitted = mocks.capture.mock.calls.find(
@@ -515,7 +517,7 @@ describe("DiscoverPage onboarding mount", () => {
expect(mocks.telemetry.modalOpened).not.toHaveBeenCalled();
expect(mocks.telemetry.questionnaireShown).not.toHaveBeenCalled();
const blankCanvas = screen.getByRole("button", {
- name: /start with blank canvas/i,
+ name: /start with a blank canvas/i,
hidden: true,
});
@@ -552,7 +554,7 @@ describe("DiscoverPage onboarding mount", () => {
await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledOnce());
const dialog = screen.getByRole("dialog");
const blankCanvas = screen.getByRole("button", {
- name: /start with blank canvas/i,
+ name: /start with a blank canvas/i,
hidden: true,
});
expect(
diff --git a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
index 9db12ee50..e3d04ca77 100644
--- a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
+++ b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
@@ -14,7 +14,7 @@ import { WorkflowTemplates } from "./WorkflowTemplates";
import { useCreateWorkflowMutation } from "../workflows/hooks/useCreateWorkflowMutation";
import { Button } from "@/components/ui/button";
import { useSearchParams } from "react-router-dom";
-import { ReloadIcon } from "@radix-ui/react-icons";
+import { FilePlusIcon, ReloadIcon } from "@radix-ui/react-icons";
import { defaultWorkflowRequest } from "../workflows/defaultWorkflowRequest";
function getIntentExampleKey(
@@ -24,7 +24,7 @@ function getIntentExampleKey(
case "fill_forms":
return "contact_us_forms";
case "extract_data":
- return "hackernews";
+ return "extractIntegrationsFromGong";
case "monitor_website":
return "AAPLStockPrice";
default:
@@ -161,16 +161,14 @@ function DiscoverPage({ revamp = false, onRevampComplete }: Props = {}) {
return (
<div className="space-y-10">
<h1 className="sr-only">Create an agent</h1>
- <div className="space-y-3">
- <PromptBox
- ref={promptBoxRef}
- enableCopilotHandoff={enableCopilotHandoff}
- />
- <div className="flex justify-end">
+ <PromptBox
+ ref={promptBoxRef}
+ enableCopilotHandoff={enableCopilotHandoff}
+ secondaryAction={
<Button
variant="ghost"
size="sm"
- className="h-11 touch-manipulation text-muted-foreground hover:text-foreground"
+ 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}
onClick={() => {
createWorkflow({
@@ -179,17 +177,21 @@ function DiscoverPage({ revamp = false, onRevampComplete }: Props = {}) {
});
}}
>
- {createWorkflowMutation.isPending && (
+ {createWorkflowMutation.isPending ? (
<ReloadIcon
aria-hidden="true"
- className="mr-2 h-3 w-3 motion-safe:animate-spin motion-reduce:animate-none"
+ className="h-3 w-3 motion-safe:animate-spin motion-reduce:animate-none"
/>
+ ) : (
+ <FilePlusIcon aria-hidden="true" className="size-4" />
)}
- Skip — start with blank canvas →
+ Start with a blank canvas
</Button>
- </div>
+ }
+ />
+ <div className="mx-auto w-full max-w-[60rem] pb-8">
+ <WorkflowTemplates />
</div>
- <WorkflowTemplates />
{onboardingModal}
</div>
);
diff --git a/skyvern-frontend/src/routes/discover/WorkflowTemplateCard.tsx b/skyvern-frontend/src/routes/discover/WorkflowTemplateCard.tsx
index f49dda25a..201f15ae1 100644
--- a/skyvern-frontend/src/routes/discover/WorkflowTemplateCard.tsx
+++ b/skyvern-frontend/src/routes/discover/WorkflowTemplateCard.tsx
@@ -1,25 +1,100 @@
+import { ArrowRightIcon, FileTextIcon } from "@radix-ui/react-icons";
+import { Link } from "react-router-dom";
+import { cn } from "@/util/utils";
+import {
+ TEMPLATE_CATEGORIES,
+ splitTemplateTitle,
+ type TemplateCategory,
+} from "./templateCatalog";
+
type Props = {
title: string;
- image: string;
+ image?: string;
+ category: TemplateCategory | null;
+ popular?: boolean;
+ to: string;
onClick: () => void;
+ className?: string;
};
-function WorkflowTemplateCard({ title, image, onClick }: Props) {
+function WorkflowTemplateCard({
+ title,
+ image,
+ category,
+ popular = false,
+ to,
+ onClick,
+ className,
+}: Props) {
+ const { name, publisher } = splitTemplateTitle(title);
+ const style = category ? TEMPLATE_CATEGORIES[category] : null;
+
return (
- <div className="h-52 w-full cursor-pointer rounded-xl" onClick={onClick}>
- <div className="h-28 rounded-t-xl bg-slate-elevation1 px-6 pt-6">
- <img src={image} alt={title} className="h-full w-full object-contain" />
+ <Link
+ to={to}
+ onClick={onClick}
+ onAuxClick={(event) => {
+ if (event.button === 1) onClick();
+ }}
+ className={cn(
+ "group flex flex-col overflow-hidden rounded-2xl border border-border/70 bg-slate-elevation1 text-foreground transition-[border-color,box-shadow,transform] hover:-translate-y-0.5 hover:border-foreground/20 hover:shadow-[0_12px_32px_rgba(0,0,0,0.08)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 motion-reduce:transition-none motion-reduce:hover:translate-y-0 dark:hover:shadow-[0_12px_32px_rgba(0,0,0,0.35)]",
+ className,
+ )}
+ >
+ <div
+ className={cn(
+ "relative h-[150px] overflow-hidden md:h-44",
+ style?.stage ?? "bg-slate-elevation2",
+ )}
+ >
+ {popular ? (
+ <span className="absolute left-3 top-3 z-10 flex h-6 items-center rounded-full bg-cta px-2.5 text-[11px] font-semibold tracking-wide text-cta-foreground">
+ Most used
+ </span>
+ ) : null}
+ {image ? (
+ <img
+ src={image}
+ alt=""
+ className="absolute left-1/2 top-9 w-[220px] -translate-x-1/2 -rotate-2 rounded-[10px] shadow-[0_14px_30px_rgba(2,8,23,0.35),0_0_0_1px_rgba(148,163,184,0.18)] transition-transform duration-300 group-hover:-translate-y-1 group-hover:rotate-0 motion-reduce:transition-none md:top-10 md:w-[270px]"
+ />
+ ) : (
+ <FileTextIcon
+ aria-hidden="true"
+ className={cn(
+ "absolute left-1/2 top-1/2 size-10 -translate-x-1/2 -translate-y-1/2",
+ style?.ink ?? "text-muted-foreground",
+ )}
+ />
+ )}
</div>
- <div className="h-24 space-y-1 rounded-b-xl bg-slate-elevation2 p-3">
- <h1
- className="line-clamp-2 overflow-hidden text-ellipsis"
+ <div className="flex flex-1 flex-col gap-1.5 px-4 pb-4 pt-3.5">
+ <span
+ className={cn(
+ "text-[11px] font-semibold uppercase leading-4 tracking-wider",
+ style?.ink ?? "text-muted-foreground",
+ )}
+ >
+ {style?.label ?? "Template"}
+ </span>
+ <span
+ className="line-clamp-2 text-[15px] font-semibold leading-[21px]"
title={title}
>
- {title}
- </h1>
- <p className="text-sm text-slate-400">Template</p>
+ {name}
+ </span>
+ <span className="truncate text-[12.5px] leading-[17px] text-muted-foreground">
+ {publisher ?? "Skyvern template"}
+ </span>
+ <span className="mt-auto flex items-center gap-1.5 pt-2 text-[13px] font-medium">
+ Use template
+ <ArrowRightIcon
+ aria-hidden="true"
+ className="size-3.5 transition-transform group-hover:translate-x-0.5 motion-reduce:transition-none"
+ />
+ </span>
</div>
- </div>
+ </Link>
);
}
diff --git a/skyvern-frontend/src/routes/discover/WorkflowTemplates.test.tsx b/skyvern-frontend/src/routes/discover/WorkflowTemplates.test.tsx
new file mode 100644
index 000000000..d6065c71d
--- /dev/null
+++ b/skyvern-frontend/src/routes/discover/WorkflowTemplates.test.tsx
@@ -0,0 +1,59 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { WorkflowTemplates } from "./WorkflowTemplates";
+
+const templates = [
+ {
+ workflow_permanent_id: "wpid_a",
+ title: "State Agency - Annual Report Filing",
+ },
+ { workflow_permanent_id: "wpid_b", title: "Board - License Lookup" },
+ {
+ workflow_permanent_id: "wpid_462707285715519276",
+ title: "Invoice Downloading",
+ },
+ { workflow_permanent_id: "wpid_c", title: "County - Business Registration" },
+];
+
+vi.mock("../workflows/hooks/useGlobalWorkflowsQuery", () => ({
+ useGlobalWorkflowsQuery: () => ({ data: templates, isLoading: false }),
+}));
+vi.mock("@/hooks/useWorkflowStudioEnabled", () => ({
+ useWorkflowStudioEnabled: () => false,
+}));
+vi.mock("@/util/homeTelemetry", () => ({
+ HomeTelemetry: { templateClicked: vi.fn() },
+}));
+
+function cardTitles() {
+ return screen
+ .getAllByRole("link")
+ .map((link) => link.querySelector("[title]")?.getAttribute("title"));
+}
+
+describe("WorkflowTemplates", () => {
+ afterEach(cleanup);
+
+ it("leads with the most used template and filters by category", () => {
+ render(
+ <MemoryRouter>
+ <WorkflowTemplates />
+ </MemoryRouter>,
+ );
+
+ expect(cardTitles()[0]).toBe("Invoice Downloading");
+ expect(screen.getAllByText("Most used")).toHaveLength(1);
+ expect(screen.getAllByRole("link")[0]?.textContent).toContain("Most used");
+
+ fireEvent.click(
+ screen.getByRole("button", { name: /Government filings 2/ }),
+ );
+
+ expect(cardTitles()).toEqual([
+ "State Agency - Annual Report Filing",
+ "County - Business Registration",
+ ]);
+ });
+});
diff --git a/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx b/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx
index 9b7927637..cd783ba99 100644
--- a/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx
+++ b/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx
@@ -1,81 +1,161 @@
+import { useMemo, useState } from "react";
+import { ChevronDownIcon } from "@radix-ui/react-icons";
import { Skeleton } from "@/components/ui/skeleton";
import { useWorkflowStudioEnabled } from "@/hooks/useWorkflowStudioEnabled";
import { workflowEditorPath } from "@/routes/workflows/studioNavigation";
import { useGlobalWorkflowsQuery } from "../workflows/hooks/useGlobalWorkflowsQuery";
-import { useNavigate } from "react-router-dom";
import { WorkflowTemplateCard } from "./WorkflowTemplateCard";
import { HomeTelemetry } from "@/util/homeTelemetry";
-import testImg from "@/assets/promptBoxBg.png";
import { TEMPORARY_TEMPLATE_IMAGES } from "./TemporaryTemplateImages";
import {
- Carousel,
- CarouselContent,
- CarouselItem,
- CarouselNext,
- CarouselPrevious,
-} from "@/components/ui/carousel";
+ CATEGORY_ORDER,
+ TEMPLATE_CATEGORIES,
+ categorizeTemplate,
+ popularityRank,
+ type TemplateCategory,
+} from "./templateCatalog";
+import { cn } from "@/util/utils";
+
+const COLLAPSED_COUNT = 6;
+
+type Filter = TemplateCategory | "all";
function WorkflowTemplates() {
const { data: workflowTemplates, isLoading } = useGlobalWorkflowsQuery();
- const navigate = useNavigate();
const studioEnabled = useWorkflowStudioEnabled();
+ const [filter, setFilter] = useState<Filter>("all");
+ const [expanded, setExpanded] = useState(false);
+
+ const templates = useMemo(
+ () =>
+ (workflowTemplates ?? [])
+ .map((workflow, index) => ({
+ workflow,
+ index,
+ category: categorizeTemplate(workflow.title),
+ }))
+ .sort(
+ (a, b) =>
+ popularityRank(a.workflow.workflow_permanent_id) -
+ popularityRank(b.workflow.workflow_permanent_id) ||
+ a.index - b.index,
+ ),
+ [workflowTemplates],
+ );
if (isLoading) {
return (
- <div className="flex gap-6">
- <Skeleton className="h-48 w-56 rounded-xl" />
- <Skeleton className="h-48 w-56 rounded-xl" />
- <Skeleton className="h-48 w-56 rounded-xl" />
+ <div className="flex gap-3 overflow-hidden md:grid md:grid-cols-2 md:gap-4 lg:grid-cols-3">
+ <Skeleton className="h-80 w-64 shrink-0 rounded-2xl md:w-auto" />
+ <Skeleton className="h-80 w-64 shrink-0 rounded-2xl md:w-auto" />
+ <Skeleton className="h-80 w-64 shrink-0 rounded-2xl md:w-auto" />
</div>
);
}
- if (!workflowTemplates || workflowTemplates.length === 0) {
+ if (templates.length === 0) {
return null;
}
+ const filters = [
+ { id: "all" as const, label: "All", count: templates.length },
+ ...CATEGORY_ORDER.map((category) => ({
+ id: category,
+ label: TEMPLATE_CATEGORIES[category].filterLabel,
+ count: templates.filter((t) => t.category === category).length,
+ })).filter((option) => option.count > 0),
+ ];
+ const activeFilter = filters.some((option) => option.id === filter)
+ ? filter
+ : "all";
+ const visible = templates.filter(
+ (t) => activeFilter === "all" || t.category === activeFilter,
+ );
+ const canExpand = visible.length > COLLAPSED_COUNT;
+
return (
- <div className="space-y-5">
- <h2 className="text-xl">Explore Agents</h2>
- <Carousel
- opts={{
- align: "start",
- loop: true,
- }}
- className="w-full"
+ <section>
+ <div
+ data-hint="start-template"
+ className="mb-3.5 flex items-start justify-between gap-3 md:items-end"
>
- <CarouselContent className="-ml-6">
- {workflowTemplates.map((workflow) => (
- <CarouselItem
- key={workflow.workflow_permanent_id}
- className="basis-1/5 pl-6"
- >
- <WorkflowTemplateCard
- title={workflow.title}
- image={
- TEMPORARY_TEMPLATE_IMAGES[workflow.workflow_permanent_id] ??
- testImg
- }
+ <div className="flex flex-col gap-1">
+ <h2 className="text-lg font-semibold leading-7 tracking-tight md:text-xl">
+ Start from a template
+ </h2>
+ <p className="text-[13px] text-muted-foreground">
+ Ready-made agents you can run as they are or edit.
+ </p>
+ </div>
+ {canExpand ? (
+ <button
+ type="button"
+ aria-expanded={expanded}
+ onClick={() => setExpanded((value) => !value)}
+ className="hidden h-9 shrink-0 items-center gap-1.5 rounded-lg px-2 text-[13px] font-medium text-foreground transition-colors hover:bg-muted md:flex"
+ >
+ <ChevronDownIcon
+ aria-hidden="true"
+ className={cn("size-3.5 transition-transform", {
+ "rotate-180": expanded,
+ })}
+ />
+ {expanded ? "Show fewer" : `See all ${visible.length}`}
+ </button>
+ ) : null}
+ </div>
+ {filters.length > 2 ? (
+ <div className="-mx-4 mb-3 flex scroll-px-4 gap-2 overflow-x-auto px-4 py-1 md:mx-0 md:flex-wrap md:px-0">
+ {filters.map((option) => {
+ const active = option.id === activeFilter;
+ return (
+ <button
+ key={option.id}
+ type="button"
+ aria-pressed={active}
onClick={() => {
- HomeTelemetry.templateClicked({
- workflowPermanentId: workflow.workflow_permanent_id,
- title: workflow.title,
- });
- navigate(
- workflowEditorPath(
- workflow.workflow_permanent_id,
- studioEnabled,
- ),
- );
+ setFilter(option.id);
+ setExpanded(false);
}}
- />
- </CarouselItem>
- ))}
- </CarouselContent>
- <CarouselPrevious className="-left-4" />
- <CarouselNext className="-right-4" />
- </Carousel>
- </div>
+ className={cn(
+ "h-10 shrink-0 whitespace-nowrap rounded-full border px-3.5 text-[13px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 md:h-9",
+ active
+ ? "border-cta bg-cta text-cta-foreground"
+ : "border-border/70 text-muted-foreground hover:bg-muted hover:text-foreground",
+ )}
+ >
+ {option.label}{" "}
+ <span className="opacity-60">{option.count}</span>
+ </button>
+ );
+ })}
+ </div>
+ ) : null}
+ <div className="-mx-4 -mt-2 flex snap-x snap-mandatory scroll-px-4 gap-3 overflow-x-auto px-4 pb-2 pt-2 md:mx-0 md:mt-0 md:grid md:grid-cols-2 md:gap-4 md:overflow-visible md:px-0 md:py-0 lg:grid-cols-3">
+ {visible.map(({ workflow, category }, index) => (
+ <WorkflowTemplateCard
+ key={workflow.workflow_permanent_id}
+ title={workflow.title}
+ image={TEMPORARY_TEMPLATE_IMAGES[workflow.workflow_permanent_id]}
+ category={category}
+ popular={popularityRank(workflow.workflow_permanent_id) === 0}
+ to={workflowEditorPath(
+ workflow.workflow_permanent_id,
+ studioEnabled,
+ )}
+ onClick={() => {
+ HomeTelemetry.templateClicked({
+ workflowPermanentId: workflow.workflow_permanent_id,
+ title: workflow.title,
+ });
+ }}
+ className={cn("w-64 shrink-0 snap-start md:w-auto", {
+ "md:hidden": !expanded && index >= COLLAPSED_COUNT,
+ })}
+ />
+ ))}
+ </div>
+ </section>
);
}
diff --git a/skyvern-frontend/src/routes/discover/templateCatalog.test.ts b/skyvern-frontend/src/routes/discover/templateCatalog.test.ts
new file mode 100644
index 000000000..21defc22e
--- /dev/null
+++ b/skyvern-frontend/src/routes/discover/templateCatalog.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+import { categorizeTemplate, splitTemplateTitle } from "./templateCatalog";
+
+describe("templateCatalog", () => {
+ it.each([
+ ["Invoice Downloading", "finance"],
+ [
+ "California Secretary of State - Statement of Information CA and Out-of-State Filing",
+ "gov",
+ ],
+ ["California Employment Development Department (EDD) - DE1 Filing", "gov"],
+ ["Delaware Division of Corporations - Entity Lookup", "lookup"],
+ ["Behavior Analyst Certification Board (BACB) - Name Lookup", "lookup"],
+ ["Purchasing", "purchasing"],
+ ["County Recorder - Document Search", "lookup"],
+ ["Job Application Workflow [Staging]", "forms"],
+ ["Delaware - Certificate of Formation", null],
+ ])("categorizes %s as %s", (title, category) => {
+ expect(categorizeTemplate(title)).toBe(category);
+ });
+
+ it("leads with the task and keeps the agency as the publisher", () => {
+ expect(
+ splitTemplateTitle("Internal Revenue Service (IRS) - SS-4 Filing"),
+ ).toEqual({
+ name: "SS-4 Filing",
+ publisher: "Internal Revenue Service (IRS)",
+ });
+ expect(splitTemplateTitle("Invoice Downloading")).toEqual({
+ name: "Invoice Downloading",
+ publisher: null,
+ });
+ expect(splitTemplateTitle("Trailing - ")).toEqual({
+ name: "Trailing - ",
+ publisher: null,
+ });
+ });
+});
diff --git a/skyvern-frontend/src/routes/discover/templateCatalog.ts b/skyvern-frontend/src/routes/discover/templateCatalog.ts
new file mode 100644
index 000000000..5f313a791
--- /dev/null
+++ b/skyvern-frontend/src/routes/discover/templateCatalog.ts
@@ -0,0 +1,94 @@
+type TemplateCategory = "gov" | "lookup" | "finance" | "purchasing" | "forms";
+
+const TEMPLATE_CATEGORIES: Record<
+ TemplateCategory,
+ { label: string; filterLabel: string; stage: string; ink: string }
+> = {
+ gov: {
+ label: "Government filing",
+ filterLabel: "Government filings",
+ stage: "bg-indigo-50 dark:bg-indigo-400/15",
+ ink: "text-indigo-700 dark:text-indigo-300",
+ },
+ lookup: {
+ label: "Lookup",
+ filterLabel: "Lookups",
+ stage: "bg-teal-50 dark:bg-teal-400/15",
+ ink: "text-teal-700 dark:text-teal-300",
+ },
+ finance: {
+ label: "Finance",
+ filterLabel: "Finance",
+ stage: "bg-amber-50 dark:bg-amber-400/15",
+ ink: "text-amber-800 dark:text-amber-300",
+ },
+ purchasing: {
+ label: "Purchasing",
+ filterLabel: "Purchasing",
+ stage: "bg-rose-50 dark:bg-rose-400/15",
+ ink: "text-rose-700 dark:text-rose-300",
+ },
+ forms: {
+ label: "Form",
+ filterLabel: "Forms",
+ stage: "bg-sky-50 dark:bg-sky-400/15",
+ ink: "text-sky-700 dark:text-sky-300",
+ },
+};
+
+const CATEGORY_ORDER: Array<TemplateCategory> = [
+ "gov",
+ "lookup",
+ "finance",
+ "purchasing",
+ "forms",
+];
+
+// Most clicked first, per home.template_clicked in PostHog (Sept 2026). Each
+// entry lists the same template's ids across production and staging.
+const POPULAR_TEMPLATE_IDS: ReadonlyArray<ReadonlyArray<string>> = [
+ ["wpid_462707285715519276", "wpid_369161749055928862"],
+ ["wpid_459009284178448812"],
+ ["wpid_459004551041605070"],
+ ["wpid_459013964273286908"],
+ ["wpid_459004674259025010"],
+];
+
+function categorizeTemplate(title: string): TemplateCategory | null {
+ if (/\binvoices?\b/i.test(title)) return "finance";
+ if (/\b(purchas\w*|checkout|orders?)\b/i.test(title)) return "purchasing";
+ if (/\b(look\s?-?up|search|verif\w*)\b/i.test(title)) return "lookup";
+ if (/\b(filings?|registration|annual report|renewal)\b/i.test(title))
+ return "gov";
+ if (/\b(application|contact|forms?)\b/i.test(title)) return "forms";
+ return null;
+}
+
+/** Splits "Agency - Task" titles so the task can lead the card. */
+function splitTemplateTitle(title: string): {
+ name: string;
+ publisher: string | null;
+} {
+ const match = /\s[-–—]\s/.exec(title);
+ if (!match) return { name: title, publisher: null };
+ const publisher = title.slice(0, match.index).trim();
+ const name = title.slice(match.index + match[0].length).trim();
+ if (!name || !publisher) return { name: title, publisher: null };
+ return { name, publisher };
+}
+
+function popularityRank(workflowPermanentId: string): number {
+ const rank = POPULAR_TEMPLATE_IDS.findIndex((ids) =>
+ ids.includes(workflowPermanentId),
+ );
+ return rank === -1 ? POPULAR_TEMPLATE_IDS.length : rank;
+}
+
+export {
+ CATEGORY_ORDER,
+ TEMPLATE_CATEGORIES,
+ categorizeTemplate,
+ popularityRank,
+ splitTemplateTitle,
+};
+export type { TemplateCategory };
diff --git a/skyvern-frontend/src/routes/streaming/useCdpInput.ts b/skyvern-frontend/src/routes/streaming/useCdpInput.ts
index 70bbfde51..0ecda8598 100644
--- a/skyvern-frontend/src/routes/streaming/useCdpInput.ts
+++ b/skyvern-frontend/src/routes/streaming/useCdpInput.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useLogging } from "@/hooks/useLogging";
import { getCredentialParam } from "@/util/env";
import { useClientIdStore } from "@/store/useClientIdStore";
import {
@@ -84,6 +85,7 @@ export function useCdpInput({
const [inputReady, setInputReady] = useState(false);
const [navigateError, setNavigateError] = useState<string | null>(null);
const credentialGetter = useCredentialGetter();
+ const logging = useLogging();
const clientId = useClientIdStore((s) => s.clientId);
const inputSocketRef = useRef<WebSocket | null>(null);
@@ -94,6 +96,8 @@ export function useCdpInput({
);
const inputReconnectAttemptsRef = useRef(0);
const inputStoppedRef = useRef(false);
+ const parseFailureLoggedRef = useRef(false);
+ const gaveUpLoggedRef = useRef(false);
const inputEventCountRef = useRef(0);
const wheelAccumulatorRef = useRef<{
deltaX: number;
@@ -146,6 +150,17 @@ export function useCdpInput({
inputStoppedRef.current = false;
inputReconnectAttemptsRef.current = 0;
+ parseFailureLoggedRef.current = false;
+ gaveUpLoggedRef.current = false;
+ const streamTarget = inputWsUrl.match(
+ /\/cdp_input\/(browser_session|workflow_run)\/([^?]+)/,
+ );
+ const targetType = streamTarget?.[1];
+ const targetId = streamTarget?.[2]
+ ? decodeURIComponent(streamTarget[2])
+ : null;
+ const browserSessionId = targetType === "browser_session" ? targetId : null;
+ const workflowRunId = targetType === "workflow_run" ? targetId : null;
function connectInputWs(credentialParam: string) {
if (inputStoppedRef.current) return;
@@ -189,7 +204,14 @@ export function useCdpInput({
);
}
} catch {
- // ignore non-JSON messages
+ if (!parseFailureLoggedRef.current) {
+ parseFailureLoggedRef.current = true;
+ logging.warn("Stream message parse failed", {
+ stream: "cdp_input",
+ browser_session_id: browserSessionId,
+ workflow_run_id: workflowRunId,
+ });
+ }
}
});
ws.addEventListener("close", (event) => {
@@ -215,6 +237,16 @@ export function useCdpInput({
if (inputStoppedRef.current) return;
if (inputReconnectAttemptsRef.current >= 5) {
console.log("[cdp-input] Max reconnect attempts reached, giving up");
+ if (!gaveUpLoggedRef.current) {
+ gaveUpLoggedRef.current = true;
+ logging.warn("Stream gave up", {
+ stream: "cdp_input",
+ browser_session_id: browserSessionId,
+ workflow_run_id: workflowRunId,
+ reason: "reconnect_exhausted",
+ reconnect_attempts: inputReconnectAttemptsRef.current,
+ });
+ }
return;
}
inputReconnectAttemptsRef.current += 1;
@@ -245,7 +277,7 @@ export function useCdpInput({
}
cancelPendingMouseMove();
};
- }, [interactive, inputWsUrl, credentialGetter, clientId]);
+ }, [interactive, inputWsUrl, credentialGetter, clientId, logging]);
useEffect(() => {
userIsControllingRef.current = userIsControlling;
diff --git a/skyvern-frontend/src/routes/tasks/create/ExampleCasePill.tsx b/skyvern-frontend/src/routes/tasks/create/ExampleCasePill.tsx
index 4a39e40ef..8920cd21f 100644
--- a/skyvern-frontend/src/routes/tasks/create/ExampleCasePill.tsx
+++ b/skyvern-frontend/src/routes/tasks/create/ExampleCasePill.tsx
@@ -1,30 +1,55 @@
+import { CheckIcon } from "@radix-ui/react-icons";
import { cn } from "@/util/utils";
type Props = {
icon: React.ReactNode;
label: string;
+ hint?: string;
+ selected?: boolean;
onClick: () => void;
disabled?: boolean;
};
-function ExampleCasePill({ icon, label, onClick, disabled = false }: Props) {
+function ExampleCasePill({
+ icon,
+ label,
+ hint,
+ selected = false,
+ onClick,
+ disabled = false,
+}: Props) {
return (
- <div
+ <button
+ type="button"
+ aria-pressed={selected}
+ disabled={disabled}
+ onClick={onClick}
className={cn(
- "flex cursor-pointer gap-2 whitespace-normal rounded-sm bg-slate-elevation3 px-4 py-3 hover:bg-slate-elevation5 lg:whitespace-nowrap",
- disabled && "pointer-events-none opacity-50",
+ "flex min-h-16 w-full items-center gap-3 rounded-xl border px-3.5 py-3 text-left text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:pointer-events-none disabled:opacity-50",
+ selected
+ ? "border-indigo-600/50 bg-indigo-600/5 dark:border-indigo-300/55 dark:bg-indigo-300/[0.07]"
+ : "border-border/70 bg-slate-elevation1 hover:bg-slate-elevation2",
)}
- aria-disabled={disabled}
- onClick={() => {
- if (disabled) {
- return;
- }
- onClick();
- }}
>
- <div>{icon}</div>
- <div>{label}</div>
- </div>
+ <span
+ aria-hidden="true"
+ className="flex size-9 shrink-0 items-center justify-center rounded-[9px] bg-indigo-600/[0.08] text-indigo-600 dark:bg-indigo-300/10 dark:text-indigo-300 [&_svg]:size-[18px]"
+ >
+ {icon}
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-sm font-medium leading-5">{label}</span>
+ {hint ? (
+ <span className="truncate text-xs text-muted-foreground">{hint}</span>
+ ) : null}
+ </span>
+ {selected ? (
+ <CheckIcon
+ aria-hidden="true"
+ className="size-4 shrink-0 text-indigo-600 dark:text-indigo-300"
+ />
+ ) : null}
+ </button>
);
}
diff --git a/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx b/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
index 211232c76..30369e39c 100644
--- a/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
+++ b/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
@@ -156,11 +156,13 @@ vi.mock("./ExampleCasePill", () => ({
ExampleCasePill: ({
label,
onClick,
+ selected,
}: {
label: string;
onClick: () => void;
+ selected?: boolean;
}) => (
- <button type="button" onClick={onClick}>
+ <button type="button" aria-pressed={selected} onClick={onClick}>
{label}
</button>
),
@@ -400,9 +402,9 @@ describe("PromptBox", () => {
const textarea = screen.getByPlaceholderText("Enter your prompt...");
textarea.scrollIntoView = vi.fn();
- act(() => ref.current?.focusAndPrefillExample("hackernews"));
- expect((textarea as HTMLTextAreaElement).value).toBe(
- "Navigate to the Hacker News homepage and get the top 3 posts.",
+ act(() => ref.current?.focusAndPrefillExample("AAPLStockPrice"));
+ expect((textarea as HTMLTextAreaElement).value).toContain(
+ 'find the "AAPL" stock price',
);
expect(document.activeElement).toBe(textarea);
expect(textarea.scrollIntoView).toHaveBeenCalledWith({ block: "center" });
@@ -512,7 +514,7 @@ describe("PromptBox", () => {
expect(submitted[1]?.[1].attempt_id).not.toBe(submitted[0]?.[1].attempt_id);
});
- test("attributes a submitted example without capturing its prompt", async () => {
+ test("loads a clicked example for review and attributes it on submit without capturing its prompt", async () => {
mockPost.mockResolvedValue({
data: {
workflow_permanent_id: "wpid_example",
@@ -521,9 +523,11 @@ describe("PromptBox", () => {
});
renderPromptBox();
- fireEvent.click(
- screen.getByRole("button", { name: "Add a product to cart" }),
- );
+ const card = screen.getByRole("button", { name: "Add a product to cart" });
+ fireEvent.click(card);
+ expect(mockPost).not.toHaveBeenCalled();
+ expect(card.getAttribute("aria-pressed")).toBe("true");
+ fireEvent.click(screen.getByLabelText("submit-prompt"));
await waitFor(() => expect(mockPost).toHaveBeenCalledTimes(1));
const submitted = mockPostHogCapture.mock.calls.find(
@@ -532,6 +536,7 @@ describe("PromptBox", () => {
expect(submitted).toMatchObject({
source: "example",
example: "finditparts",
+ example_edited: false,
variant: "legacy",
});
expect(JSON.stringify(mockPostHogCapture.mock.calls)).not.toContain(
@@ -539,6 +544,28 @@ describe("PromptBox", () => {
);
});
+ test("hides run settings on the legacy home when the Copilot handoff is on", () => {
+ renderPromptBox(true);
+ expect(screen.queryByLabelText(/^Advanced settings/)).toBeNull();
+ cleanup();
+
+ renderPromptBox(false);
+ expect(screen.getByLabelText("Advanced settings")).toBeTruthy();
+ });
+
+ test("clears the selected legacy example once its prompt is edited", () => {
+ renderPromptBox();
+ const card = screen.getByRole("button", { name: "Apply for a job" });
+ fireEvent.click(card);
+ expect(card.getAttribute("aria-pressed")).toBe("true");
+
+ const textarea = screen.getByPlaceholderText(
+ "Enter your prompt...",
+ ) as HTMLTextAreaElement;
+ fireEvent.change(textarea, { target: { value: `${textarea.value} now` } });
+ expect(card.getAttribute("aria-pressed")).toBe("false");
+ });
+
test("preserves an unedited redesign example through creation outcomes", async () => {
mockPost.mockResolvedValue({
data: {
@@ -666,7 +693,7 @@ describe("PromptBox", () => {
const cases = [
["finditparts", "finditparts.com"],
["contact_us_forms", "canadahvac.com/contact-hvac-canada"],
- ["hackernews", "Hacker News homepage"],
+ ["extractIntegrationsFromGong", "Gong integrations page"],
["AAPLStockPrice", "google finance"],
] as const;
diff --git a/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx b/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
index 99bb9a267..1370118cb 100644
--- a/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
+++ b/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
@@ -8,8 +8,6 @@ import { AutoResizingTextarea } from "@/components/AutoResizingTextarea/AutoResi
import { CartIcon } from "@/components/icons/CartIcon";
import { GraphIcon } from "@/components/icons/GraphIcon";
import { InboxIcon } from "@/components/icons/InboxIcon";
-import { MessageIcon } from "@/components/icons/MessageIcon";
-import { TrophyIcon } from "@/components/icons/TrophyIcon";
import { ToastAction } from "@/components/ui/toast";
import { toast } from "@/components/ui/use-toast";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
@@ -19,11 +17,11 @@ import {
CheckIcon,
ChevronDownIcon,
Cross2Icon,
+ EnvelopeClosedIcon,
FileTextIcon,
GlobeIcon,
GearIcon,
PaperPlaneIcon,
- Pencil1Icon,
PlusIcon,
ReloadIcon,
TextAlignLeftIcon,
@@ -41,6 +39,7 @@ import { AxiosError, type AxiosResponse } from "axios";
import {
forwardRef,
type ForwardedRef,
+ type ReactNode,
useCallback,
useEffect,
useImperativeHandle,
@@ -75,65 +74,53 @@ import { useWorkflowStudioEnabled } from "@/hooks/useWorkflowStudioEnabled";
import { rememberDiscoverCopilotPrompt } from "@/routes/workflows/discoverCopilotHandoff";
import { workflowEditorPath } from "@/routes/workflows/studioNavigation";
+// Most-clicked first; the grid order is the ranking users see.
const exampleCases = [
+ {
+ key: "job_application",
+ hint: "jobs.lever.co",
+ label: "Apply for a job",
+ prompt: `Go to https://jobs.lever.co/leverdemo-8/45d39614-464a-4b62-a5cd-8683ce4fb80a/apply, fill out the job application form and apply to the job. Fill out any public burden questions if they appear in the form. Your goal is complete when the page says you've successfully applied to the job. Terminate if you are unable to apply successfully. Here's the user information: {"name":"John Doe","email":"${generateUniqueEmail()}","phone":"${generatePhoneNumber()}","resume_url":"https://writing.colostate.edu/guides/documents/resume/functionalSample.pdf","cover_letter":"Generate a compelling cover letter for me"}`,
+ icon: <InboxIcon className="size-6" />,
+ },
{
key: "finditparts",
+ hint: "finditparts.com",
label: "Add a product to cart",
prompt:
'Go to https://www.finditparts.com first. Search for the product "W01-377-8537", add it to cart and then navigate to the cart page. Your goal is COMPLETE when you\'re on the cart page and the specified product is in the cart. Extract all product quantity information from the cart page. Do not attempt to checkout.',
icon: <CartIcon className="size-6" />,
},
{
- key: "job_application",
- label: "Apply for a job",
- prompt: `Go to https://jobs.lever.co/leverdemo-8/45d39614-464a-4b62-a5cd-8683ce4fb80a/apply, fill out the job application form and apply to the job. Fill out any public burden questions if they appear in the form. Your goal is complete when the page says you've successfully applied to the job. Terminate if you are unable to apply successfully. Here's the user information: {"name":"John Doe","email":"${generateUniqueEmail()}","phone":"${generatePhoneNumber()}","resume_url":"https://writing.colostate.edu/guides/documents/resume/functionalSample.pdf","cover_letter":"Generate a compelling cover letter for me"}`,
- icon: <InboxIcon className="size-6" />,
+ key: "contact_us_forms",
+ hint: "canadahvac.com",
+ label: "Fill a contact us form",
+ prompt: `Go to https://canadahvac.com/contact-hvac-canada. Fill out the contact us form and submit it. Your goal is complete when the page says your message has been sent. Here's the user information: {"name":"John Doe","email":"[email protected]","phone":"123-456-7890","message":"Hello, I have a question about your services."}`,
+ icon: <EnvelopeClosedIcon className="size-6" />,
},
{
key: "geico",
+ hint: "geico.com",
label: "Get an insurance quote",
prompt: `Go to https://www.geico.com first. Navigate through the website until you generate an auto insurance quote. Do not generate a home insurance quote. If you're on a page showing an auto insurance quote (with premium amounts), your goal is COMPLETE. Extract all quote information in JSON format including the premium amount, the timeframe for the quote. Here's the user information: {"licensed_at_age":19,"education_level":"HIGH_SCHOOL","phone_number":"8042221111","full_name":"Chris P. Bacon","past_claim":[],"has_claims":false,"spouse_occupation":"Florist","auto_current_carrier":"None","home_commercial_uses":null,"spouse_full_name":"Amy Stake","auto_commercial_uses":null,"requires_sr22":false,"previous_address_move_date":null,"line_of_work":null,"spouse_age":"1987-12-12","auto_insurance_deadline":null,"email":"[email protected]","net_worth_numeric":1000000,"spouse_gender":"F","marital_status":"married","spouse_licensed_at_age":20,"license_number":"AAAAAAA090AA","spouse_license_number":"AAAAAAA080AA","how_much_can_you_lose":25000,"vehicles":[{"annual_mileage":10000,"commute_mileage":4000,"existing_coverages":null,"ideal_coverages":{"bodily_injury_per_incident_limit":50000,"bodily_injury_per_person_limit":25000,"collision_deductible":1000,"comprehensive_deductible":1000,"personal_injury_protection":null,"property_damage_per_incident_limit":null,"property_damage_per_person_limit":25000,"rental_reimbursement_per_incident_limit":null,"rental_reimbursement_per_person_limit":null,"roadside_assistance_limit":null,"underinsured_motorist_bodily_injury_per_incident_limit":50000,"underinsured_motorist_bodily_injury_per_person_limit":25000,"underinsured_motorist_property_limit":null},"ownership":"Owned","parked":"Garage","purpose":"commute","vehicle":{"style":"AWD 3.0 quattro TDI 4dr Sedan","model":"A8 L","price_estimate":29084,"year":2015,"make":"Audi"},"vehicle_id":null,"vin":null}],"additional_drivers":[],"home":[{"home_ownership":"owned"}],"spouse_line_of_work":"Agriculture, Forestry and Fishing","occupation":"Customer Service Representative","id":null,"gender":"M","credit_check_authorized":false,"age":"1987-11-11","license_state":"Washington","cash_on_hand":"$10000–14999","address":{"city":"HOUSTON","country":"US","state":"TX","street":"9625 GARFIELD AVE.","zip":"77082"},"spouse_education_level":"MASTERS","spouse_email":"[email protected]","spouse_added_to_auto_policy":true}`,
icon: <FileTextIcon className="size-6" />,
},
{
- key: "california_edd",
- label: "Fill out CA's online EDD",
- prompt: `Go to https://eddservices.edd.ca.gov/acctservices/AccountManagement/AccountServlet?Command=NEW_SIGN_UP. Navigate through the employer services online enrollment form. Terminate when the form is completed. Here's the needed information: {"username":"isthisreal1","password":"Password123!","first_name":"John","last_name":"Doe","pin":"1234","email":"${generateUniqueEmail()}","phone_number":"${generatePhoneNumber()}"}`,
- icon: <Pencil1Icon className="size-6" />,
- },
- {
- key: "contact_us_forms",
- label: "Fill a contact us form",
- prompt: `Go to https://canadahvac.com/contact-hvac-canada. Fill out the contact us form and submit it. Your goal is complete when the page says your message has been sent. Here's the user information: {"name":"John Doe","email":"[email protected]","phone":"123-456-7890","message":"Hello, I have a question about your services."}`,
- icon: <FileTextIcon className="size-6" />,
- },
- {
- key: "hackernews",
- label: "What's the top post on hackernews",
- prompt: "Navigate to the Hacker News homepage and get the top 3 posts.",
- icon: <MessageIcon className="size-6" />,
+ key: "extractIntegrationsFromGong",
+ hint: "gong.io",
+ label: "Extract integrations from Gong",
+ prompt:
+ "Go to https://www.gong.io first. Navigate to the 'Integrations' page on the Gong website. Extract the names and descriptions of all integrations listed on the Gong integrations page. Ensure not to click on any external links or advertisements.",
+ icon: <GearIcon className="size-6" />,
},
{
key: "AAPLStockPrice",
+ hint: "google.com/finance",
label: "Search for AAPL on Google Finance",
prompt:
'Go to google finance and find the "AAPL" stock price. COMPLETE when the search results for "AAPL" are displayed and the stock price is extracted.',
icon: <GraphIcon className="size-6" />,
},
- {
- key: "topRankedFootballTeam",
- label: "Get the top ranked football team",
- prompt:
- "Navigate to the FIFA World Ranking page and identify the top ranked football team. Extract the name of the top ranked football team from the FIFA World Ranking page.",
- icon: <TrophyIcon className="size-6" />,
- },
- {
- key: "extractIntegrationsFromGong",
- label: "Extract Integrations from Gong.io",
- prompt:
- "Go to https://www.gong.io first. Navigate to the 'Integrations' page on the Gong website. Extract the names and descriptions of all integrations listed on the Gong integrations page. Ensure not to click on any external links or advertisements.",
- icon: <GearIcon className="size-6" />,
- },
] as const;
type ExamplePromptKey = (typeof exampleCases)[number]["key"];
@@ -167,6 +154,8 @@ type PromptBoxProps = {
minimal?: boolean;
/** 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;
};
type PromptBoxHandle = {
@@ -255,6 +244,7 @@ function PromptBoxImpl(
enableCopilotHandoff = false,
minimal = false,
onAgentCreated,
+ secondaryAction,
}: PromptBoxProps,
ref: ForwardedRef<PromptBoxHandle>,
) {
@@ -302,6 +292,7 @@ function PromptBoxImpl(
const selectedExample =
exampleCases.find((example) => example.key === key) ?? exampleCases[0];
if (!prompt.trim()) {
+ cancelSpeech();
setPrompt(selectedExample.prompt);
setExampleAttribution({ id: selectedExample.key, edited: false });
}
@@ -571,6 +562,7 @@ function PromptBoxImpl(
isListening: isSpeechListening,
isHearingSpeech: isSpeechHearing,
toggle: toggleSpeech,
+ cancel: cancelSpeech,
} = useSpeechToTextField({
value: prompt,
onChange: updatePrompt,
@@ -619,106 +611,128 @@ function PromptBoxImpl(
if (!minimal) {
return (
- <div>
+ <div className="relative isolate flex flex-col items-center pb-4 pt-12 md:pt-24">
+ {/* The artwork is translucent white: it reads as shading on the dark background and is inverted for light. */}
<div
- className="rounded-sm py-[4.25rem]"
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-x-0 top-0 -z-10 h-[30rem] opacity-85 invert [mask-image:radial-gradient(closest-side,#000_35%,transparent_100%)] dark:opacity-100 dark:invert-0 md:h-[35rem]"
style={{
background: `url(${img}) 50% / cover no-repeat`,
}}
- >
- <div className="mx-auto flex min-w-44 flex-col items-center gap-7 px-8">
- <span className="text-2xl">
- What task would you like to accomplish?
- </span>
- <div className="flex w-full max-w-xl flex-col">
- <div className="flex w-full items-center gap-2 rounded-xl border border-input bg-background py-2 pr-3 text-muted-foreground shadow-sm transition-colors focus-within:border-foreground/20 focus-within:ring-2 focus-within:ring-ring/10">
- <SpeechInputButton
- isSupported={isSpeechSupported}
- isListening={isSpeechListening}
- isHearingSpeech={isSpeechHearing}
- disabled={isSubmitting}
- onToggle={() => {
- HomeTelemetry.voiceToggled();
- toggleSpeech();
- }}
- className="ml-2 h-9 w-9 border-0 bg-transparent shadow-none hover:bg-muted"
- iconClassName="h-5 w-5"
- />
- <AutoResizingTextarea
- ref={textareaRef}
- id="discover-prompt-input"
- className="min-h-0 resize-none border-0 bg-transparent px-4 py-0 leading-5 text-foreground shadow-none placeholder:text-muted-foreground hover:border-0 focus-visible:ring-0"
- value={prompt}
- onChange={(e) => updatePrompt(e.target.value)}
- placeholder="Enter your prompt..."
- />
- {!enableCopilotHandoff ? (
- <AdvancedSettingsPopover
- settings={taskRunSettings}
- onChange={setTaskRunSettings}
- open={showAdvancedSettings}
- onOpenChange={(open) => {
- HomeTelemetry.advancedSettingsToggled(open);
- setShowAdvancedSettings(open);
- }}
- tab={advancedSettingsTab}
- onTabChange={setAdvancedSettingsTab}
- />
- ) : null}
- <button
- type="button"
- aria-label="submit-prompt"
- disabled={!prompt.trim() || isSubmitting}
- className="flex items-center justify-center rounded-lg bg-cta p-2 text-cta-foreground shadow-sm transition-colors hover:bg-cta-hover disabled:pointer-events-none disabled:bg-cta/45 disabled:text-cta-foreground/65 disabled:shadow-none"
- onClick={() => {
- submitPrompt({ prompt, attribution: exampleAttribution });
- }}
- >
- {isSubmitting ? (
- <ReloadIcon className="size-4 animate-spin" />
- ) : (
- <PaperPlaneIcon
- aria-hidden="true"
- className="size-4 shrink-0"
- />
- )}
- </button>
- </div>
+ />
+ <div className="flex w-full max-w-[45rem] flex-col items-start text-left md:items-center md:text-center">
+ <span className="text-2xl font-semibold tracking-tight md:text-[1.875rem] md:leading-[2.375rem]">
+ What task would you like to accomplish?
+ </span>
+ <p className="mt-2.5 text-[15px] leading-[22px] text-muted-foreground">
+ Describe it like you would to a colleague. Skyvern opens a browser
+ and does it.
+ </p>
+ </div>
+ <div className="mt-6 flex w-full max-w-[45rem] flex-col md:mt-9">
+ <div className="flex w-full flex-col rounded-2xl border border-input bg-background text-muted-foreground shadow-[0_12px_32px_rgba(0,0,0,0.06)] transition-[border-color,box-shadow] focus-within:border-foreground/20 focus-within:shadow-[0_0_0_4px_rgba(79,70,229,0.10),0_12px_32px_rgba(0,0,0,0.06)] dark:bg-slate-elevation1 dark:shadow-[0_12px_32px_rgba(0,0,0,0.35)] dark:focus-within:shadow-[0_0_0_4px_rgba(165,180,252,0.14),0_12px_32px_rgba(0,0,0,0.35)]">
+ <AutoResizingTextarea
+ ref={textareaRef}
+ id="discover-prompt-input"
+ className="max-h-[14rem] min-h-[6rem] resize-none overflow-y-auto border-0 bg-transparent px-5 pb-1.5 pt-[18px] text-base leading-6 text-foreground shadow-none placeholder:text-muted-foreground hover:border-0 focus-visible:ring-0 md:text-[15px]"
+ value={prompt}
+ onChange={(e) => updatePrompt(e.target.value)}
+ placeholder="Enter your prompt..."
+ />
+ <div className="flex items-center gap-1 px-2.5 pb-2.5 pt-2">
+ <SpeechInputButton
+ isSupported={isSpeechSupported}
+ isListening={isSpeechListening}
+ isHearingSpeech={isSpeechHearing}
+ disabled={isSubmitting}
+ onToggle={() => {
+ HomeTelemetry.voiceToggled();
+ toggleSpeech();
+ }}
+ className="size-11 border-0 bg-transparent shadow-none hover:bg-muted md:size-9"
+ iconClassName="h-[18px] w-[18px]"
+ />
{!enableCopilotHandoff ? (
- <ChangedSettingsChips
+ <AdvancedSettingsPopover
settings={taskRunSettings}
onChange={setTaskRunSettings}
- onEdit={(tab) => {
- setAdvancedSettingsTab(tab);
- setShowAdvancedSettings(true);
+ open={showAdvancedSettings}
+ onOpenChange={(open) => {
+ HomeTelemetry.advancedSettingsToggled(open);
+ setShowAdvancedSettings(open);
}}
+ tab={advancedSettingsTab}
+ onTabChange={setAdvancedSettingsTab}
+ triggerClassName="size-11 rounded-[10px] md:size-9"
/>
) : null}
+ <button
+ type="button"
+ aria-label="submit-prompt"
+ disabled={!prompt.trim() || isSubmitting}
+ className="ml-auto flex size-11 items-center justify-center rounded-[10px] bg-cta text-cta-foreground shadow-sm transition-colors hover:bg-cta-hover disabled:pointer-events-none disabled:bg-cta/45 disabled:text-cta-foreground/65 disabled:shadow-none md:size-9"
+ onClick={() => {
+ submitPrompt({ prompt, attribution: exampleAttribution });
+ }}
+ >
+ {isSubmitting ? (
+ <ReloadIcon className="size-4 animate-spin" />
+ ) : (
+ <PaperPlaneIcon
+ aria-hidden="true"
+ className="size-4 shrink-0"
+ />
+ )}
+ </button>
</div>
</div>
+ {!enableCopilotHandoff ? (
+ <ChangedSettingsChips
+ settings={taskRunSettings}
+ onChange={setTaskRunSettings}
+ onEdit={(tab) => {
+ setAdvancedSettingsTab(tab);
+ setShowAdvancedSettings(true);
+ }}
+ />
+ ) : null}
+ {secondaryAction ? (
+ <div className="mt-3 flex md:justify-end">{secondaryAction}</div>
+ ) : null}
</div>
- <div className="flex flex-wrap justify-center gap-4 rounded-sm bg-slate-elevation1 p-4">
- {exampleCases.map((example) => {
- return (
+ <section className="mt-9 w-full max-w-[60rem] md:mt-16">
+ <div className="mb-3 flex flex-col gap-1 md:mb-3.5 md:flex-row md:items-baseline md:justify-between">
+ <h2 className="text-sm font-semibold">Try an example</h2>
+ <p className="text-[13px] text-muted-foreground">
+ Pick one to load it into the prompt, edit it, then run.
+ </p>
+ </div>
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 sm:gap-3 lg:grid-cols-3">
+ {exampleCases.map((example) => (
<ExampleCasePill
key={example.key}
icon={example.icon}
label={example.label}
+ hint={example.hint}
+ selected={
+ exampleAttribution?.id === example.key &&
+ !exampleAttribution.edited
+ }
disabled={isSubmitting}
onClick={() => {
HomeTelemetry.exampleClicked({
example: example.key,
label: example.label,
});
- submitPrompt({
- prompt: example.prompt,
- attribution: { id: example.key, edited: false },
- });
+ cancelSpeech();
+ setPrompt(example.prompt);
+ setExampleAttribution({ id: example.key, edited: false });
+ textareaRef.current?.focus();
}}
/>
- );
- })}
- </div>
+ ))}
+ </div>
+ </section>
</div>
);
}
@@ -899,6 +913,7 @@ function PromptBoxImpl(
capability: example.capability,
label: example.label,
});
+ cancelSpeech();
setPrompt(example.prompt);
setExampleAttribution({ id: example.id, edited: false });
setPromptTouched(true);
diff --git a/skyvern-frontend/src/routes/tasks/create/PromptBoxAdvancedSettings.tsx b/skyvern-frontend/src/routes/tasks/create/PromptBoxAdvancedSettings.tsx
index fe07ac9c3..65ec38eae 100644
--- a/skyvern-frontend/src/routes/tasks/create/PromptBoxAdvancedSettings.tsx
+++ b/skyvern-frontend/src/routes/tasks/create/PromptBoxAdvancedSettings.tsx
@@ -22,6 +22,7 @@ import {
} from "@/util/geoData";
import { Cross2Icon, GearIcon } from "@radix-ui/react-icons";
import { useState } from "react";
+import { cn } from "@/util/utils";
import {
DEFAULT_TASK_RUN_SETTINGS,
type SettingsTab,
@@ -264,6 +265,7 @@ type AdvancedSettingsPopoverProps = SettingsChangeProps & {
onOpenChange: (open: boolean) => void;
tab: SettingsTab;
onTabChange: (tab: SettingsTab) => void;
+ triggerClassName?: string;
};
function AdvancedSettingsPopover({
@@ -273,6 +275,7 @@ function AdvancedSettingsPopover({
onOpenChange,
tab,
onTabChange,
+ triggerClassName,
}: AdvancedSettingsPopoverProps) {
const changedCount = changedKeys(settings).length;
// KeyValueInput keeps its own rows after mount, so Reset remounts the fields.
@@ -295,7 +298,10 @@ function AdvancedSettingsPopover({
? `Advanced settings, ${changedCount} changed`
: "Advanced settings"
}
- className="relative flex items-center justify-center rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground"
+ className={cn(
+ "relative flex items-center justify-center rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground",
+ triggerClassName,
+ )}
>
<GearIcon aria-hidden="true" className="size-5 shrink-0" />
{changedCount > 0 ? (
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx b/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx
index 6334448e5..b45d8581e 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx
@@ -1383,9 +1383,7 @@ function WorkflowsFlat() {
}}
/>
- <div data-hint="start-template">
- <WorkflowTemplates />
- </div>
+ <WorkflowTemplates />
</div>
</div>
);
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx b/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx
index dca1b9086..e5d09c4af 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx
@@ -1103,9 +1103,7 @@ function WorkflowsTree() {
}}
/>
- <div data-hint="start-template">
- <WorkflowTemplates />
- </div>
+ <WorkflowTemplates />
</div>
</div>
);
diff --git a/skyvern-frontend/src/routes/workflows/copilot/AutoAcceptChip.tsx b/skyvern-frontend/src/routes/workflows/copilot/AutoAcceptChip.tsx
index b22abb9ea..c1077b00f 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/AutoAcceptChip.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/AutoAcceptChip.tsx
@@ -3,9 +3,17 @@ import { useState } from "react";
import { getClient } from "@/api/AxiosClient";
import { toast } from "@/components/ui/use-toast";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useLogging } from "@/hooks/useLogging";
+import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";
+import { getCopilotFailureLogFields } from "./copilotFailureLogFields";
type Props = {
chatId: string;
+ organizationId?: string | null;
+ captureProductEvent?: (
+ event: string,
+ properties: Record<string, unknown>,
+ ) => void;
waitForAccept: (chatId: string) => Promise<void>;
// This chat's Turn off is already running, including one started before this chip mounted.
pendingFromChat: boolean;
@@ -15,12 +23,16 @@ type Props = {
export function AutoAcceptChip({
chatId,
+ organizationId,
+ captureProductEvent,
waitForAccept,
pendingFromChat,
onPendingChange,
onTurnedOff,
}: Props) {
const credentialGetter = useCredentialGetter();
+ const logging = useLogging();
+ const workflowPermanentId = useWorkflowPermanentId();
const [pending, setPending] = useState(false);
const busy = pending || pendingFromChat;
@@ -36,14 +48,33 @@ export function AutoAcceptChip({
await client.post("/workflow/copilot/disable-auto-accept", {
workflow_copilot_chat_id: chatId,
});
+ captureProductEvent?.("copilot.auto_accept.toggled", {
+ org_id: organizationId,
+ workflow_permanent_id: workflowPermanentId,
+ enabled: false,
+ });
onTurnedOff(chatId);
} catch (error) {
console.error("Failed to turn off auto-accept:", error);
+ const waitingForAccept =
+ error instanceof Error &&
+ error.message === "Wait for the Copilot change to finish";
+ if (!waitingForAccept) {
+ const fields = getCopilotFailureLogFields(error);
+ const status = fields.http_status;
+ const clientError =
+ typeof status === "number" && status >= 400 && status < 500;
+ logging[clientError ? "warn" : "error"]("Copilot request failed", {
+ operation: "proposal_sync",
+ workflow_permanent_id: workflowPermanentId,
+ chat_id: chatId,
+ ...fields,
+ });
+ }
toast({
title: "Auto-accept is still on",
description:
- error instanceof Error &&
- error.message === "Wait for the Copilot change to finish"
+ waitingForAccept && error instanceof Error
? error.message
: "Could not turn it off. Please try again.",
variant: "destructive",
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 70573282a..419390a25 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -220,6 +220,8 @@ import { captureRecordBrowser } from "@/util/recordBrowserTelemetry";
import { useWorkflowBlockSearchStore } from "@/store/WorkflowBlockSearchStore";
import { resolveTimelineBlockJumpNodeId } from "@/routes/workflows/studio/runview/timelineBlockJump";
import { TooltipProvider } from "@/components/ui/tooltip";
+import { useLogging } from "@/hooks/useLogging";
+import { getCopilotFailureLogFields } from "./copilotFailureLogFields";
// Cap on retained per-turn snap-back snapshots. A typical session has a
// handful of turns; this ceiling guards a runaway long-running chat.
@@ -231,6 +233,18 @@ const MAX_TURN_SNAPSHOTS = 20;
// apply that never answers cannot leave that chat's gate without its Accept actions. Accept p95 is ~11s.
export const ACCEPT_SETTLE_CEILING_MS = 30_000;
+type CopilotFailureOperation =
+ | "send_stream"
+ | "history_load"
+ | "chat_load"
+ | "recovery_poll_gave_up"
+ | "cancel"
+ | "workflow_update"
+ | "proposal_sync"
+ | "queued_send"
+ | "auto_send"
+ | "resume_token";
+
const requestTokenKey = (workflowId: string) =>
`copilot-request-cancel-token:${workflowId}`;
@@ -1201,6 +1215,11 @@ export type WorkflowUpdateOptions = {
};
interface WorkflowCopilotChatProps {
+ organizationId?: string | null;
+ captureProductEvent?: (
+ event: string,
+ properties: Record<string, unknown>,
+ ) => void;
captureEditorState?: () => EditorStateSnapshot | null;
restoreEditorState?: (snapshot: EditorStateSnapshot) => RestoreResult;
onWorkflowPersisted?: (workflowPermanentId: string) => void;
@@ -1523,6 +1542,8 @@ const constrainPosition = (
};
export function WorkflowCopilotChat({
+ organizationId,
+ captureProductEvent,
onWorkflowUpdate,
captureEditorState,
restoreEditorState,
@@ -1553,6 +1574,7 @@ export function WorkflowCopilotChat({
portalTarget,
}: WorkflowCopilotChatProps = {}) {
const workflowPermanentId = useWorkflowPermanentId();
+ const logging = useLogging();
useLayoutEffect(() => {
if (workflowPermanentId)
useWorkflowTitleStore
@@ -2025,6 +2047,38 @@ export function WorkflowCopilotChat({
// Mirrors workflowCopilotChatId for async handlers that would otherwise
// close over a stale value across renders (e.g. clearProposedWorkflow).
const workflowCopilotChatIdRef = useRef<string | null>(null);
+ const logCopilotRequestFailure = useCallback(
+ (
+ operation: CopilotFailureOperation,
+ error: unknown,
+ chatId = workflowCopilotChatIdRef.current,
+ ) => {
+ const fields = getCopilotFailureLogFields(error);
+ const log =
+ typeof fields.http_status === "number" &&
+ fields.http_status >= 400 &&
+ fields.http_status < 500
+ ? logging.warn
+ : logging.error;
+ log("Copilot request failed", {
+ operation,
+ workflow_permanent_id: workflowPermanentId,
+ chat_id: chatId,
+ ...fields,
+ });
+ },
+ [logging, workflowPermanentId],
+ );
+ const captureCopilotEvent = useCallback(
+ (event: string, properties: Record<string, unknown>) => {
+ captureProductEvent?.(event, {
+ org_id: organizationId,
+ workflow_permanent_id: workflowPermanentId,
+ ...properties,
+ });
+ },
+ [captureProductEvent, organizationId, workflowPermanentId],
+ );
const turnSnapshots = useRef<Map<string, TurnSnapshot>>(new Map());
// Snapshot captured at submit time. Moved into turnSnapshots once
// turn_start lands and we know the BE-assigned turn_id.
@@ -2485,6 +2539,11 @@ export function WorkflowCopilotChat({
"Failed to send credential response:",
error instanceof Error ? error.message : String(error),
);
+ logCopilotRequestFailure(
+ "resume_token",
+ error,
+ frame.workflow_copilot_chat_id,
+ );
toast({
title: "Couldn't send your credential response",
description: "Please try again.",
@@ -2494,7 +2553,7 @@ export function WorkflowCopilotChat({
credentialResponseInFlight.current = false;
}
},
- [credentialGetter, isCopilotTurnCurrent],
+ [credentialGetter, isCopilotTurnCurrent, logCopilotRequestFailure],
);
// Terminal-mode cards have no resume_token — connect/skip is a local UI morph,
// no network call.
@@ -3410,6 +3469,11 @@ export function WorkflowCopilotChat({
return;
}
finish();
+ logCopilotRequestFailure(
+ "recovery_poll_gave_up",
+ new Error("Copilot recovery polling gave up"),
+ chatId,
+ );
if (recordingRefinementMessageId && turnId) {
reportRecordingRefinementOutcome(
reportedRefinementOutcomes.current,
@@ -3565,6 +3629,7 @@ export function WorkflowCopilotChat({
status: getErrorStatus(error),
requestId,
});
+ logCopilotRequestFailure("cancel", error, chatId);
toast({
title: "Could not cancel the Copilot turn",
description: "Copilot will keep checking for saved changes.",
@@ -4172,6 +4237,7 @@ export function WorkflowCopilotChat({
rememberRecoveryCancelTokens,
createCanonicalRecovery,
isCopilotTurnCurrent,
+ logCopilotRequestFailure,
reserveCopilotTurn,
],
);
@@ -4385,6 +4451,7 @@ export function WorkflowCopilotChat({
historyLoadedForRef.current = workflowPermanentId;
} catch (error) {
console.error("Failed to load chat:", error);
+ logCopilotRequestFailure("chat_load", error, chatId);
toast({ title: "Failed to load chat", variant: "destructive" });
} finally {
endHistoryLoad(loadSeq);
@@ -4400,6 +4467,7 @@ export function WorkflowCopilotChat({
discardQueuedPrompt,
beginHistoryLoad,
endHistoryLoad,
+ logCopilotRequestFailure,
],
);
@@ -4552,10 +4620,11 @@ export function WorkflowCopilotChat({
// editor/Workspace.tsx) shows "Update failed" itself and then re-throws so this
// boolean is honest. Toasting again would stack two failure toasts on one event.
console.error("Failed to update workflow:", updateError);
+ logCopilotRequestFailure("workflow_update", updateError);
return false;
}
},
- [onWorkflowUpdate, isCopilotTurnCurrent],
+ [onWorkflowUpdate, isCopilotTurnCurrent, logCopilotRequestFailure],
);
const restoreTurnSnapshot = useCallback(
@@ -5199,6 +5268,7 @@ export function WorkflowCopilotChat({
"Failed to resolve chat ID before applying proposal:",
resolveError,
);
+ logCopilotRequestFailure("proposal_sync", resolveError);
}
}
@@ -5293,6 +5363,11 @@ export function WorkflowCopilotChat({
}
});
onWorkflowPersisted?.(workflowPermanentId);
+ captureCopilotEvent("copilot.proposal.accepted", {
+ chat_id: chatId,
+ auto: alwaysAccept,
+ always_accept: alwaysAccept,
+ });
if (!isCopilotTurnCurrent(acceptance)) return;
// persisted=true loads as clean baseline; without it, Save would create a duplicate version.
if (
@@ -5479,6 +5554,9 @@ export function WorkflowCopilotChat({
setPendingProposalMetadata(null);
setPendingProposalRun(null);
setPendingProposalTurnId(null);
+ captureCopilotEvent("copilot.proposal.rejected", {
+ chat_id: workflowCopilotChatIdRef.current,
+ });
return true;
} finally {
if (!recovering && !pendingCanonicalRecovery.current?.acceptChatId) {
@@ -5878,6 +5956,7 @@ export function WorkflowCopilotChat({
return row;
} catch (error) {
console.error("Failed to resync pending proposal:", error);
+ logCopilotRequestFailure("proposal_sync", error, chatId);
if (
!superseded() &&
workflowCopilotChatIdRef.current === chatId &&
@@ -5888,7 +5967,7 @@ export function WorkflowCopilotChat({
}
return null;
}
- }, [applyChatRowProposal, fetchChatRow]);
+ }, [applyChatRowProposal, fetchChatRow, logCopilotRequestFailure]);
// Unlike `resyncProposalFromChatRow`, a failed read here must not raise the `reload` gate or
// overwrite the fresher proposal the terminal frame already carried.
@@ -5915,9 +5994,10 @@ export function WorkflowCopilotChat({
setPendingProposalRun(row.proposed_workflow_run);
} catch (error) {
console.error("Failed to backfill proposal run facts:", error);
+ logCopilotRequestFailure("proposal_sync", error, chatId);
}
},
- [fetchChatRow],
+ [fetchChatRow, logCopilotRequestFailure],
);
const clearProposedWorkflow = async (
@@ -5958,6 +6038,7 @@ export function WorkflowCopilotChat({
"Failed to resolve chat ID before clearing proposal:",
resolveError,
);
+ logCopilotRequestFailure("proposal_sync", resolveError);
return false;
}
}
@@ -5982,6 +6063,7 @@ export function WorkflowCopilotChat({
}
} catch (retryError) {
console.error("Retry to clear proposed workflow failed:", retryError);
+ logCopilotRequestFailure("proposal_sync", retryError, chatId);
}
}
if (status === 409) {
@@ -5989,6 +6071,7 @@ export function WorkflowCopilotChat({
return false;
}
console.error("Failed to clear proposed workflow:", error);
+ logCopilotRequestFailure("proposal_sync", error, chatId);
toast({
title: "Copilot update failed",
description: autoAcceptValue
@@ -6204,6 +6287,7 @@ export function WorkflowCopilotChat({
} catch (error) {
if (isMounted) setStartupFailed(true);
console.error("Failed to load chat history:", error);
+ logCopilotRequestFailure("history_load", error);
} finally {
if (isMounted) {
endHistoryLoad(loadSeq);
@@ -6230,6 +6314,7 @@ export function WorkflowCopilotChat({
beginHistoryLoad,
endHistoryLoad,
discardQueuedPrompt,
+ logCopilotRequestFailure,
]);
// Set by a block's "Generate" arm step so the next send scopes regeneration to that block.
@@ -6381,13 +6466,23 @@ export function WorkflowCopilotChat({
{ cancel_token: cancelToken, source } as WorkflowCopilotCancelRequest,
{ timeout: 15_000, signal: controllerAtCancel.signal },
);
+ captureCopilotEvent("copilot.turn.cancelled", {
+ chat_id: workflowCopilotChatIdRef.current,
+ });
} catch (error) {
if (!isCurrent()) return;
console.warn("Workflow copilot cancel POST failed", error);
+ logCopilotRequestFailure("cancel", error);
abortUnconfirmed(STOP_NOT_SENT_NOTICE);
}
},
- [credentialGetter, restoreQueuedPromptToComposer, isCopilotTurnCurrent],
+ [
+ captureCopilotEvent,
+ credentialGetter,
+ isCopilotTurnCurrent,
+ logCopilotRequestFailure,
+ restoreQueuedPromptToComposer,
+ ],
);
// Stream cleanup ends the Stop spinner; recovery separately confirms whether
@@ -7461,6 +7556,11 @@ export function WorkflowCopilotChat({
const giveUp = () => {
finish();
if (!isCopilotTurnCurrent(reservation)) return;
+ logCopilotRequestFailure(
+ "recovery_poll_gave_up",
+ new Error("Copilot recovery polling gave up"),
+ chatIdForRequest,
+ );
finishRecordingRefinement("failed", "connection_lost");
if (recoveryNoticeId) {
setMessages((current) =>
@@ -7750,6 +7850,10 @@ export function WorkflowCopilotChat({
}
if (response.workflow_applied === true) {
onWorkflowPersisted?.(workflowPermanentId);
+ captureCopilotEvent("copilot.proposal.accepted", {
+ chat_id: response.workflow_copilot_chat_id,
+ auto: true,
+ });
if (responseEntry) responseEntry.workflowPersisted = true;
// This turn's auto-commit already moved canonical past any earlier
// bypassed proposal — drop the stale handle so its gate cannot
@@ -7884,6 +7988,16 @@ export function WorkflowCopilotChat({
setMessages((prev) => [...prev, errorMessage]);
// Errors on no-draft turns leave the canvas alone.
const errorTurnId = payload.turn_id ?? latestTurnId.current ?? null;
+ logging.warn("Copilot server error frame", {
+ workflow_permanent_id: workflowPermanentId,
+ chat_id: streamChatId ?? workflowCopilotChatIdRef.current,
+ turn_id: errorTurnId,
+ failure_kind: "server",
+ });
+ captureCopilotEvent("copilot.turn.failed", {
+ chat_id: streamChatId ?? workflowCopilotChatIdRef.current,
+ failure_kind: "server",
+ });
const errorEntry = errorTurnId
? (turnSnapshots.current.get(errorTurnId) ?? submittedSnapshot)
: submittedSnapshot;
@@ -7953,6 +8067,11 @@ export function WorkflowCopilotChat({
});
}
requestStarted = true;
+ captureCopilotEvent("copilot.message.sent", {
+ chat_id: chatIdForRequest,
+ is_new_chat: !chatIdForRequest,
+ has_selected_block: targetBlockLabel !== null,
+ });
for (const attached of sentAttachments) {
inFlightFileIds.current.add(attached.file_id);
}
@@ -8241,6 +8360,15 @@ export function WorkflowCopilotChat({
[400, 401, 403, 404, 405, 413, 415, 422, 429].includes(error.status);
returnPossiblySavedFiles();
console.error("Failed to send message:", error);
+ logCopilotRequestFailure(
+ "send_stream",
+ error,
+ streamChatId ?? workflowCopilotChatIdRef.current,
+ );
+ captureCopilotEvent("copilot.turn.failed", {
+ chat_id: streamChatId ?? workflowCopilotChatIdRef.current,
+ failure_kind: "client_stream",
+ });
retainUnconfirmedOutcome();
if (
!definitiveRejection &&
@@ -8377,6 +8505,7 @@ export function WorkflowCopilotChat({
[
acceptUnresolved,
applyStoredNarrativeEvent,
+ captureCopilotEvent,
createCanonicalRecovery,
onWorkflowPersisted,
reserveCopilotTurn,
@@ -8402,6 +8531,8 @@ export function WorkflowCopilotChat({
isLiveBrowserReady,
liveBrowserSessionId,
loadChatInPlace,
+ logCopilotRequestFailure,
+ logging,
pendingProposalTurnId,
rememberTurnOwnedRun,
startRecordedActionsPoll,
@@ -8644,6 +8775,7 @@ export function WorkflowCopilotChat({
recording: promptToSend.recording,
}).catch((error) => {
console.error("Queued send failed:", error);
+ logCopilotRequestFailure("queued_send", error);
});
}, [
acceptUnresolved,
@@ -8656,6 +8788,7 @@ export function WorkflowCopilotChat({
queuedPrompt,
updateQueuedPrompt,
workflowPermanentId,
+ logCopilotRequestFailure,
]);
useEffect(() => {
@@ -8713,6 +8846,7 @@ export function WorkflowCopilotChat({
: {}),
}).catch((error) => {
console.error("Auto-send failed:", error);
+ logCopilotRequestFailure("auto_send", error);
});
}, [
handleSend,
@@ -8728,6 +8862,7 @@ export function WorkflowCopilotChat({
getSaveData,
workflowPermanentId,
workflowMutationLocked,
+ logCopilotRequestFailure,
]);
useEffect(() => {
@@ -8760,6 +8895,10 @@ export function WorkflowCopilotChat({
: "The copilot was not ready in time — please retype your prompt.",
variant: "destructive",
});
+ logCopilotRequestFailure(
+ "auto_send",
+ new Error("Copilot auto-send timed out"),
+ );
}, AUTO_SEND_TIMEOUT_MS);
return () => {
window.clearTimeout(timer);
@@ -8775,6 +8914,7 @@ export function WorkflowCopilotChat({
queuedPrompt,
getSaveData,
workflowMutationLocked,
+ logCopilotRequestFailure,
]);
const handleMouseDown = (e: React.MouseEvent) => {
@@ -10213,6 +10353,8 @@ export function WorkflowCopilotChat({
<AutoAcceptChip
key={workflowCopilotChatId}
chatId={workflowCopilotChatId}
+ organizationId={organizationId}
+ captureProductEvent={captureProductEvent}
pendingFromChat={turningOffThisChat}
waitForAccept={async (turnOffChatId) => {
if (
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx
index 98d38a772..d4249cc18 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx
@@ -1,7 +1,13 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it } from "vitest";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+} from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
EMPTY_NARRATIVE,
@@ -31,6 +37,7 @@ const completedBlock = {
afterEach(() => {
cleanup();
+ vi.unstubAllGlobals();
});
// Radix menus open on pointerdown, not click.
@@ -376,6 +383,50 @@ describe("ReviewGateCard — Test end-to-end recourse", () => {
expect(testRuns).toBe(1);
});
+ it("moves Reject into More actions when the row is too narrow to hold both", () => {
+ let reportWidth: (width: number) => void = () => {};
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ reportWidth = (width) =>
+ callback(
+ [{ contentRect: { width } } as ResizeObserverEntry],
+ this as unknown as ResizeObserver,
+ );
+ }
+ observe() {}
+ disconnect() {}
+ },
+ );
+ let rejects = 0;
+ render(
+ <ReviewGateCard
+ turn={turn({ proposalDisposition: "review_untested", blocks: [] })}
+ pending
+ verdict="untested"
+ actionsEnabled
+ hasProposal
+ onAccept={noop}
+ onAlwaysAccept={noop}
+ onReject={() => {
+ rejects += 1;
+ }}
+ onReview={noop}
+ onTestEndToEnd={noop}
+ />,
+ );
+
+ act(() => reportWidth(279));
+ expect(screen.queryByRole("button", { name: "Reject" })).not.toBeNull();
+
+ act(() => reportWidth(190));
+ expect(screen.queryByRole("button", { name: "Reject" })).toBeNull();
+ openMenu("More actions");
+ fireEvent.click(screen.getByRole("menuitem", { name: "Reject" }));
+ expect(rejects).toBe(1);
+ });
+
it("drops an open confirmation and locks More actions when the gate locks", () => {
const gate = (failure: "reload" | null) => (
<ReviewGateCard
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
index 924852714..154c63ca4 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
@@ -1,9 +1,10 @@
import {
ChevronDownIcon,
+ Cross2Icon,
DotsHorizontalIcon,
MagicWandIcon,
} from "@radix-ui/react-icons";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { Badge, type BadgeProps } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -87,6 +88,10 @@ const END_TO_END_REAL_ACTIONS =
const PENDING_CHANGE_LIMIT = 4;
+// Even with the compact tier, Reject beside the more menu needs ~215px; narrower rows move Reject
+// into that menu. Both dropdowns render in a portal, so this cannot be a container query.
+const FOLD_REJECT_BELOW_PX = 220;
+
// Cause-coded per the 2026-07-13 ruling on terminal states: red only for a write that
// failed, amber for one whose outcome we cannot read yet. Most Accept "failures" are a
// second click on a first click that had already saved, so amber is the honest colour.
@@ -498,6 +503,22 @@ export function ReviewGateCard({
// The confirmation replaces the row that opened it, so focus is placed by hand both ways.
const restoreFocusRef = useRef(false);
const selectingTestRef = useRef(false);
+ const [actionsRow, setActionsRow] = useState<HTMLDivElement | null>(null);
+ const [actionsRowNarrow, setActionsRowNarrow] = useState(false);
+ // Measured once before paint so a card mounting in an already-narrow pane never shows Reject unfolded.
+ useLayoutEffect(() => {
+ if (!actionsRow || typeof ResizeObserver === "undefined") {
+ return;
+ }
+ const measure = (width: number) =>
+ setActionsRowNarrow(width > 0 && width < FOLD_REJECT_BELOW_PX);
+ measure(actionsRow.getBoundingClientRect().width);
+ const observer = new ResizeObserver(([entry]) => {
+ measure(entry?.contentRect.width ?? 0);
+ });
+ observer.observe(actionsRow);
+ return () => observer.disconnect();
+ }, [actionsRow]);
useEffect(() => {
if (confirmingTest) {
runTestRef.current?.focus();
@@ -585,7 +606,7 @@ export function ReviewGateCard({
type="button"
size="sm"
onClick={onAccept}
- className={`${ACCEPT_BUTTON_CLASS} rounded-r-none`}
+ className={`${ACCEPT_BUTTON_CLASS} rounded-r-none [@container_gate-actions_(max-width:249px)]:px-2`}
>
Accept
</Button>
@@ -597,7 +618,7 @@ export function ReviewGateCard({
type="button"
size="sm"
aria-label="More accept options"
- className={`${ACCEPT_BUTTON_CLASS} w-8 rounded-l-none border-l border-black/15 px-0`}
+ className={`${ACCEPT_BUTTON_CLASS} w-8 rounded-l-none border-l border-black/15 px-0 [@container_gate-actions_(max-width:249px)]:w-6`}
>
<ChevronDownIcon className="h-4 w-4" />
</Button>
@@ -617,46 +638,58 @@ export function ReviewGateCard({
</div>
) : null;
- const moreMenu =
- canTest && !offerTestInBody ? (
- <DropdownMenu>
- <DropdownMenuTrigger asChild disabled={actionsLocked}>
- <Button
- ref={moreTriggerRef}
- type="button"
- size="sm"
- variant="outline"
- aria-label="More actions"
- className="w-8 px-0"
- >
- <DotsHorizontalIcon />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- className="w-60"
- onCloseAutoFocus={(event) => {
- if (selectingTestRef.current) {
- selectingTestRef.current = false;
- event.preventDefault();
- }
+ const hasMoreMenu = canTest && !offerTestInBody;
+ const foldRejectIntoMenu = hasMoreMenu && actionsRowNarrow;
+ const moreMenu = hasMoreMenu ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild disabled={actionsLocked}>
+ <Button
+ ref={moreTriggerRef}
+ type="button"
+ size="sm"
+ variant="outline"
+ aria-label="More actions"
+ className="w-8 px-0 [@container_gate-actions_(max-width:249px)]:w-7"
+ >
+ <DotsHorizontalIcon />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className="w-60"
+ onCloseAutoFocus={(event) => {
+ if (selectingTestRef.current) {
+ selectingTestRef.current = false;
+ event.preventDefault();
+ }
+ }}
+ >
+ {/* The menu renders outside the disabled fieldset, and a lock can land while it is open. */}
+ <DropdownMenuItem
+ disabled={actionsLocked}
+ onSelect={() => {
+ selectingTestRef.current = true;
+ setConfirmingTest(true);
}}
+ className="flex-col items-start gap-0.5 text-xs"
>
+ {testLabel}
+ <span className="text-[11px] leading-snug text-muted-foreground">
+ Runs every block together on the real site.
+ </span>
+ </DropdownMenuItem>
+ {foldRejectIntoMenu ? (
<DropdownMenuItem
- onSelect={() => {
- selectingTestRef.current = true;
- setConfirmingTest(true);
- }}
- className="flex-col items-start gap-0.5 text-xs"
+ disabled={actionsLocked}
+ onSelect={onReject}
+ className="text-xs text-red-700 focus:text-red-700 dark:text-red-400 dark:focus:text-red-400"
>
- {testLabel}
- <span className="text-[11px] leading-snug text-muted-foreground">
- Runs every block together on the real site.
- </span>
+ Reject
</DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- ) : null;
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null;
return (
<CopilotCard
@@ -789,27 +822,42 @@ export function ReviewGateCard({
</div>
</>
) : (
- <div className="flex flex-wrap items-center gap-2">
- {acceptSplit}
- <Button
- type="button"
- size="sm"
- variant="outline"
- onClick={onReview}
- >
- Review
- </Button>
- <div className="ml-auto flex items-center gap-2">
+ // Reject collapses to an icon below 300px and the controls tighten below 250px, so the
+ // row fits on one line down to ~190px; with the more menu, Reject folds into it.
+ <div
+ ref={setActionsRow}
+ className="[container-name:gate-actions] [container-type:inline-size]"
+ >
+ <div className="flex flex-wrap items-center gap-2 [@container_gate-actions_(max-width:249px)]:gap-1.5">
+ {acceptSplit}
<Button
type="button"
size="sm"
variant="outline"
- onClick={onReject}
- className={REJECT_BUTTON_CLASS}
+ onClick={onReview}
+ className="[@container_gate-actions_(max-width:249px)]:px-2"
>
- Reject
+ Review
</Button>
- {moreMenu}
+ <div className="ml-auto flex items-center gap-2 [@container_gate-actions_(max-width:249px)]:gap-1.5">
+ {foldRejectIntoMenu ? null : (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={onReject}
+ aria-label="Reject"
+ title="Reject"
+ className={`${REJECT_BUTTON_CLASS} w-8 px-0 [@container_gate-actions_(max-width:249px)]:w-7 [@container_gate-actions_(min-width:300px)]:w-auto [@container_gate-actions_(min-width:300px)]:px-3`}
+ >
+ <Cross2Icon className="[@container_gate-actions_(min-width:300px)]:hidden" />
+ <span className="hidden [@container_gate-actions_(min-width:300px)]:inline">
+ Reject
+ </span>
+ </Button>
+ )}
+ {moreMenu}
+ </div>
</div>
</div>
)}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/copilotFailureLogFields.ts b/skyvern-frontend/src/routes/workflows/copilot/copilotFailureLogFields.ts
new file mode 100644
index 000000000..a3db5fd22
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/copilotFailureLogFields.ts
@@ -0,0 +1,25 @@
+import { AxiosError } from "axios";
+
+export function getCopilotFailureLogFields(error: unknown) {
+ const isSseHttpError =
+ error instanceof Error &&
+ error.name === "SseHttpError" &&
+ "status" in error &&
+ typeof error.status === "number";
+ const isAxiosError = error instanceof AxiosError;
+
+ return {
+ error_type: error instanceof Error ? error.name : typeof error,
+ http_status: isSseHttpError
+ ? error.status
+ : isAxiosError
+ ? (error.response?.status ?? null)
+ : null,
+ ...(!isSseHttpError &&
+ !isAxiosError &&
+ error instanceof Error &&
+ !(error instanceof SyntaxError)
+ ? { error_message: error.message }
+ : {}),
+ };
+}
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index 9df07d866..829414cd4 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -31,6 +31,7 @@ import {
useRef,
useState,
MutableRefObject,
+ type ReactNode,
} from "react";
import { nanoid } from "nanoid";
import { parse as parseYAML, stringify as convertToYAML } from "yaml";
@@ -114,6 +115,8 @@ import {
DialogTrigger,
} from "@/components/ui/dialog";
import { toast } from "@/components/ui/use-toast";
+import { PaneErrorBoundary } from "@/components/PaneErrorBoundary";
+import { useLogging } from "@/hooks/useLogging";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { AffectedBlocksNotice } from "./AffectedBlocksNotice";
import { BrowserStream } from "@/components/BrowserStream";
@@ -444,6 +447,7 @@ export function useWorkspaceCopilotUpdate({
options: WorkflowUpdateOptions & { userDriven: boolean },
) => boolean | void;
}) {
+ const logging = useLogging();
return (workflowData: WorkflowVersion, options?: WorkflowUpdateOptions) => {
try {
// All Copilot-driven applies are user edits (mid-turn draft, accept,
@@ -456,6 +460,10 @@ export function useWorkspaceCopilotUpdate({
throw new Error("The editor refused the Copilot update");
} catch (error) {
console.error("Failed to parse and apply agent", error, workflowData);
+ logging.error("Copilot agent apply failed", {
+ workflow_permanent_id: workflowData.workflow_permanent_id,
+ error,
+ });
toast({
title: "Update failed",
description: "Failed to apply agent update. Please try again.",
@@ -485,6 +493,7 @@ function Workspace({
acceptedWorkflow.version > loadedWorkflow.version
? acceptedWorkflow
: loadedWorkflow;
+ const logging = useLogging();
const { blockLabel } = useParams();
const workflowPermanentId = useWorkflowPermanentId();
const { copilotPortalEl: studioCopilotPortalEl } = useStudioShellContext();
@@ -630,6 +639,11 @@ function Workspace({
// "Make a Copy"), so the YAML editor must not open or commit for them.
const isGlobalWorkflow = useIsGlobalWorkflow();
const postHog = usePostHog();
+ const captureProductEvent = useCallback(
+ (event: string, properties: Record<string, unknown>) =>
+ postHog.capture(event, properties),
+ [postHog],
+ );
const { getNodes, getEdges } = useReactFlow();
const {
nodes,
@@ -2134,6 +2148,41 @@ function Workspace({
const handleCopilotWorkflowUpdate = useWorkspaceCopilotUpdate({
applyWorkflowUpdate,
});
+ const reportStudioPaneCrash = (
+ pane: string,
+ error: unknown,
+ componentStack?: string | null,
+ ) => {
+ logging.error("Studio pane crashed", {
+ error_source: "studio_pane",
+ pane,
+ component_stack: componentStack,
+ workflow_permanent_id: workflow.workflow_permanent_id,
+ error,
+ });
+ if (typeof postHog?.captureException === "function") {
+ postHog.captureException(error, { error_source: "studio_pane", pane });
+ }
+ };
+ const withStudioPaneBoundary = (
+ pane: string,
+ children: ReactNode,
+ fallbackContainer?: HTMLElement | null,
+ ) =>
+ embedded ? (
+ <PaneErrorBoundary
+ key={`${workflow.workflow_permanent_id}:${pane}`}
+ pane={pane}
+ fallbackContainer={fallbackContainer}
+ onError={(error, componentStack) =>
+ reportStudioPaneCrash(pane, error, componentStack)
+ }
+ >
+ {children}
+ </PaneErrorBoundary>
+ ) : (
+ children
+ );
const enterYamlMode = () => {
if (isGlobalWorkflow) {
@@ -2614,31 +2663,34 @@ function Workspace({
embedded ? (
// Studio: a flex row so Agent History docks beside the comparison; the
// legacy absolute layout below assumes the old full-width editor.
- <div className="flex h-full w-full gap-3 overflow-hidden p-3">
- <div className="min-w-0 flex-1">
- <WorkflowComparisonPanel
- key={`${workflowPanelState.data.version1.workflow_id}v${workflowPanelState.data.version1.version}-${workflowPanelState.data.version2.workflow_id}v${workflowPanelState.data.version2.version}`}
- version1={workflowPanelState.data.version1}
- version2={workflowPanelState.data.version2}
- onSelectState={handleSelectState}
- mode={workflowPanelState.data.mode}
- onCopilotReviewClose={
- workflowPanelState.data.onCopilotReviewClose
- }
- onExit={embedded ? exitVersionHistory : undefined}
- />
- </div>
- {workflowPanelState.active &&
- workflowPanelState.content === "history" && (
- <div className="shrink-0">
- <WorkflowHistoryPanel
- workflowPermanentId={workflowPermanentId!}
- onCompare={handleCompareVersions}
- onClose={embedded ? exitVersionHistory : undefined}
- />
- </div>
- )}
- </div>
+ withStudioPaneBoundary(
+ "comparison",
+ <div className="flex h-full w-full gap-3 overflow-hidden p-3">
+ <div className="min-w-0 flex-1">
+ <WorkflowComparisonPanel
+ key={`${workflowPanelState.data.version1.workflow_id}v${workflowPanelState.data.version1.version}-${workflowPanelState.data.version2.workflow_id}v${workflowPanelState.data.version2.version}`}
+ version1={workflowPanelState.data.version1}
+ version2={workflowPanelState.data.version2}
+ onSelectState={handleSelectState}
+ mode={workflowPanelState.data.mode}
+ onCopilotReviewClose={
+ workflowPanelState.data.onCopilotReviewClose
+ }
+ onExit={embedded ? exitVersionHistory : undefined}
+ />
+ </div>
+ {workflowPanelState.active &&
+ workflowPanelState.content === "history" && (
+ <div className="shrink-0">
+ <WorkflowHistoryPanel
+ workflowPermanentId={workflowPermanentId!}
+ onCompare={handleCompareVersions}
+ onClose={embedded ? exitVersionHistory : undefined}
+ />
+ </div>
+ )}
+ </div>,
+ )
) : workflowPanelState.data?.showComparison &&
workflowPanelState.data?.version1 &&
workflowPanelState.data?.version2 ? (
@@ -2746,30 +2798,35 @@ function Workspace({
{...(yamlEditorActive ? { inert: "" } : {})}
>
{/* infinite canvas */}
- <FlowRenderer
- nodes={nodes}
- edges={edges}
- setNodes={setNodes}
- setEdges={setEdges}
- onNodesChange={onNodesChange}
- onEdgesChange={onEdgesChange}
- initialTitle={initialTitle}
- workflow={workflow}
- parameterBaseline={
- parameterBaselines[workflow.workflow_permanent_id]
- }
- embedded={embedded}
- paneEntryKey={embedded ? studioEntryId : undefined}
- paneLayoutKey={
- embedded
- ? `${studioPanes.join(",")}|${paneWidthsKey(studioPaneWidths)}`
- : undefined
- }
- onRequestDeleteNode={handleRequestDeleteNode}
- captureHistoryImmediately={captureWorkflowEditImmediately}
- onAddNode={addNode}
- historyApplyTrigger={historyApplyTrigger + restoreApplyTrigger}
- />
+ {withStudioPaneBoundary(
+ "editor",
+ <FlowRenderer
+ nodes={nodes}
+ edges={edges}
+ setNodes={setNodes}
+ setEdges={setEdges}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ initialTitle={initialTitle}
+ workflow={workflow}
+ parameterBaseline={
+ parameterBaselines[workflow.workflow_permanent_id]
+ }
+ embedded={embedded}
+ paneEntryKey={embedded ? studioEntryId : undefined}
+ paneLayoutKey={
+ embedded
+ ? `${studioPanes.join(",")}|${paneWidthsKey(studioPaneWidths)}`
+ : undefined
+ }
+ onRequestDeleteNode={handleRequestDeleteNode}
+ captureHistoryImmediately={captureWorkflowEditImmediately}
+ onAddNode={addNode}
+ historyApplyTrigger={
+ historyApplyTrigger + restoreApplyTrigger
+ }
+ />,
+ )}
{/* Studio hosts the toggle in the Editor pane header; legacy
anchors it under the header on /edit only (the debugger
@@ -3345,172 +3402,178 @@ function Workspace({
</div>
)}
- <WorkflowCopilotChat
- captureEditorState={captureLiveEditorState}
- restoreEditorState={restoreLiveEditorState}
- onWorkflowPersisted={(workflowPermanentId) =>
- useWorkflowHasChangesStore
- .getState()
- .recordPersistedSave(workflowPermanentId)
- }
- isOpen={embedded ? studioCopilotOpen : showBrowser && isCopilotOpen}
- docked={embedded}
- chromeless={embedded}
- portalTarget={embedded ? studioCopilotPortalEl : undefined}
- onClose={() => setIsCopilotOpen(false)}
- onMessageCountChange={setCopilotMessageCount}
- buttonRef={copilotButtonRef}
- liveBrowserSessionId={
- copilotLiveBrowserReady ? debugBrowserSessionId : null
- }
- onTurnActivityChange={setIsCopilotTurnActive}
- workflowRunId={copilotRunId({ embedded, studioRunId })}
- requiresLiveBrowser={copilotRequiresLiveBrowser}
- isLiveBrowserReady={copilotLiveBrowserReady}
- initialMessage={initialCopilotMessage ?? undefined}
- initialAttachments={routeInitialCopilotAttachments}
- initialAction={initialCopilotAction ?? undefined}
- onInitialMessageConsumed={handleInitialCopilotMessageConsumed}
- onUploadSOP={uploadSOPAtEnd}
- canUploadSOP={authoringActionAvailability.canUploadSOP}
- isUploadingSOP={sopToBlocksMutation.isPending}
- onRecordTask={startRecordingAtEnd}
- canRecordTask={authoringActionAvailability.canRecordTask}
- authoringUnavailableReason={
- authoringActionAvailability.unavailableReason
- }
- onBlockSelect={highlightBlock}
- onReviewWorkflow={async (pendingWorkflow, settle, baseline) => {
- const saveData = workflowChangesStore.getSaveData?.();
- if (!saveData) return;
-
- try {
- // While a turn streams, the draft is staged on the canvas, so the
- // live save data would compare the proposal against itself; the
- // chat's pre-submit snapshot is "Current" then. Without a snapshot
- // (reload, chat switch) nothing was staged, so the live canvas —
- // including unsaved edits — is the right baseline.
- const parseHeaders = (
- value: string | null,
- label: string,
- ): Record<string, string> | null | undefined => {
- try {
- return value ? parseHeaderJson(value) : null;
- } catch (error) {
- toast({
- title: "Error",
- description: `Invalid JSON format in ${label}: ${getJsonParseErrorDetail(
- value ?? "",
- error,
- )}`,
- variant: "destructive",
+ {withStudioPaneBoundary(
+ "copilot",
+ <WorkflowCopilotChat
+ organizationId={workflow.organization_id}
+ captureProductEvent={captureProductEvent}
+ captureEditorState={captureLiveEditorState}
+ restoreEditorState={restoreLiveEditorState}
+ onWorkflowPersisted={(workflowPermanentId) =>
+ useWorkflowHasChangesStore
+ .getState()
+ .recordPersistedSave(workflowPermanentId)
+ }
+ isOpen={embedded ? studioCopilotOpen : showBrowser && isCopilotOpen}
+ docked={embedded}
+ chromeless={embedded}
+ portalTarget={embedded ? studioCopilotPortalEl : undefined}
+ onClose={() => setIsCopilotOpen(false)}
+ onMessageCountChange={setCopilotMessageCount}
+ buttonRef={copilotButtonRef}
+ liveBrowserSessionId={
+ copilotLiveBrowserReady ? debugBrowserSessionId : null
+ }
+ onTurnActivityChange={setIsCopilotTurnActive}
+ workflowRunId={copilotRunId({ embedded, studioRunId })}
+ requiresLiveBrowser={copilotRequiresLiveBrowser}
+ isLiveBrowserReady={copilotLiveBrowserReady}
+ initialMessage={initialCopilotMessage ?? undefined}
+ initialAttachments={routeInitialCopilotAttachments}
+ initialAction={initialCopilotAction ?? undefined}
+ onInitialMessageConsumed={handleInitialCopilotMessageConsumed}
+ onUploadSOP={uploadSOPAtEnd}
+ canUploadSOP={authoringActionAvailability.canUploadSOP}
+ isUploadingSOP={sopToBlocksMutation.isPending}
+ onRecordTask={startRecordingAtEnd}
+ canRecordTask={authoringActionAvailability.canRecordTask}
+ authoringUnavailableReason={
+ authoringActionAvailability.unavailableReason
+ }
+ onBlockSelect={highlightBlock}
+ onReviewWorkflow={async (pendingWorkflow, settle, baseline) => {
+ const saveData = workflowChangesStore.getSaveData?.();
+ if (!saveData) return;
+
+ try {
+ // While a turn streams, the draft is staged on the canvas, so the
+ // live save data would compare the proposal against itself; the
+ // chat's pre-submit snapshot is "Current" then. Without a snapshot
+ // (reload, chat switch) nothing was staged, so the live canvas —
+ // including unsaved edits — is the right baseline.
+ const parseHeaders = (
+ value: string | null,
+ label: string,
+ ): Record<string, string> | null | undefined => {
+ try {
+ return value ? parseHeaderJson(value) : null;
+ } catch (error) {
+ toast({
+ title: "Error",
+ description: `Invalid JSON format in ${label}: ${getJsonParseErrorDetail(
+ value ?? "",
+ error,
+ )}`,
+ variant: "destructive",
+ });
+ return undefined;
+ }
+ };
+ let baseVersion: WorkflowVersion;
+ if (baseline) {
+ baseVersion = baseline;
+ } else {
+ const extraHttpHeaders = parseHeaders(
+ saveData.settings.extraHttpHeaders,
+ "extra http headers",
+ );
+ if (extraHttpHeaders === undefined) return;
+ const cdpConnectHeaders = parseHeaders(
+ saveData.settings.cdpConnectHeaders,
+ "cdp connect headers",
+ );
+ if (cdpConnectHeaders === undefined) return;
+ baseVersion = canvasWorkflowVersionFromSaveData(saveData, {
+ extraHttpHeaders,
+ cdpConnectHeaders,
});
- return undefined;
}
- };
- let baseVersion: WorkflowVersion;
- if (baseline) {
- baseVersion = baseline;
- } else {
- const extraHttpHeaders = parseHeaders(
- saveData.settings.extraHttpHeaders,
- "extra http headers",
- );
- if (extraHttpHeaders === undefined) return;
- const cdpConnectHeaders = parseHeaders(
- saveData.settings.cdpConnectHeaders,
- "cdp connect headers",
- );
- if (cdpConnectHeaders === undefined) return;
- baseVersion = canvasWorkflowVersionFromSaveData(saveData, {
- extraHttpHeaders,
- cdpConnectHeaders,
- });
- }
- // Both hold canvas (YAML-shaped) blocks; round-trip them through
- // the converter so they match the proposal's shape.
- const client = await getClient(credentialGetter, "sans-api-v1");
- const baseConversion =
- await client.post<WorkflowYAMLConversionResponse>(
- "/workflow/copilot/convert-yaml-to-blocks",
- {
- workflow_definition_yaml: convertToYAML({
- version: saveData.workflowDefinitionVersion,
- parameters: baseVersion.workflow_definition.parameters,
- blocks: baseVersion.workflow_definition.blocks,
- finally_block_label:
- baseVersion.workflow_definition.finally_block_label ??
- undefined,
- workflow_system_prompt:
- baseVersion.workflow_definition.workflow_system_prompt ??
- undefined,
- error_code_mapping:
- baseVersion.workflow_definition.error_code_mapping ??
- undefined,
- retry_policy:
- baseVersion.workflow_definition.retry_policy ?? null,
- }),
- workflow_id: saveData.workflow.workflow_id,
+ // Both hold canvas (YAML-shaped) blocks; round-trip them through
+ // the converter so they match the proposal's shape.
+ const client = await getClient(credentialGetter, "sans-api-v1");
+ const baseConversion =
+ await client.post<WorkflowYAMLConversionResponse>(
+ "/workflow/copilot/convert-yaml-to-blocks",
+ {
+ workflow_definition_yaml: convertToYAML({
+ version: saveData.workflowDefinitionVersion,
+ parameters: baseVersion.workflow_definition.parameters,
+ blocks: baseVersion.workflow_definition.blocks,
+ finally_block_label:
+ baseVersion.workflow_definition.finally_block_label ??
+ undefined,
+ workflow_system_prompt:
+ baseVersion.workflow_definition
+ .workflow_system_prompt ?? undefined,
+ error_code_mapping:
+ baseVersion.workflow_definition.error_code_mapping ??
+ undefined,
+ retry_policy:
+ baseVersion.workflow_definition.retry_policy ?? null,
+ }),
+ workflow_id: saveData.workflow.workflow_id,
+ },
+ );
+ const currentVersion: WorkflowVersion = {
+ ...baseVersion,
+ workflow_definition: baseConversion.data.workflow_definition,
+ };
+
+ // Approve / Reject settle through the chat so the server-side
+ // proposal is cleared (revision-checked) and the canvas updated
+ // exactly as the chat's own buttons do. A refused decision keeps the
+ // panel open; an Accept failure renders on the chat's review gate,
+ // so the panel closes to reveal it.
+ const handleCopilotReviewClose = bindCopilotReviewClose(
+ () => settle("reject"),
+ async (status) => {
+ if (status === "approve" && !(await settle("approve"))) {
+ return;
+ }
+ setWorkflowPanelState({
+ active: false,
+ content: "history",
+ data: {
+ showComparison: false,
+ version1: undefined,
+ version2: undefined,
+ },
+ });
+ setIsCopilotOpen(true);
},
);
- const currentVersion: WorkflowVersion = {
- ...baseVersion,
- workflow_definition: baseConversion.data.workflow_definition,
- };
-
- // Approve / Reject settle through the chat so the server-side
- // proposal is cleared (revision-checked) and the canvas updated
- // exactly as the chat's own buttons do. A refused decision keeps the
- // panel open; an Accept failure renders on the chat's review gate,
- // so the panel closes to reveal it.
- const handleCopilotReviewClose = bindCopilotReviewClose(
- () => settle("reject"),
- async (status) => {
- if (status === "approve" && !(await settle("approve"))) {
- return;
- }
- setWorkflowPanelState({
- active: false,
- content: "history",
- data: {
- showComparison: false,
- version1: undefined,
- version2: undefined,
- },
- });
- setIsCopilotOpen(true);
- },
- );
- // Hide chat and show comparison. The comparison renders on the
- // editor canvas, so surface the Editor pane when docked in the studio.
- setIsCopilotOpen(false);
- if (embedded) {
- openStudioPane("editor");
+ // Hide chat and show comparison. The comparison renders on the
+ // editor canvas, so surface the Editor pane when docked in the studio.
+ setIsCopilotOpen(false);
+ if (embedded) {
+ openStudioPane("editor");
+ }
+ setWorkflowPanelState({
+ active: false,
+ content: "history",
+ data: {
+ version1: currentVersion,
+ version2: pendingWorkflow,
+ showComparison: true,
+ mode: "copilot",
+ onCopilotReviewClose: handleCopilotReviewClose,
+ },
+ });
+ } catch (error) {
+ console.error("Failed to prepare agent comparison", error);
+ toast({
+ title: "Comparison failed",
+ description:
+ "Failed to prepare agent for comparison. Please try again.",
+ variant: "destructive",
+ });
}
- setWorkflowPanelState({
- active: false,
- content: "history",
- data: {
- version1: currentVersion,
- version2: pendingWorkflow,
- showComparison: true,
- mode: "copilot",
- onCopilotReviewClose: handleCopilotReviewClose,
- },
- });
- } catch (error) {
- console.error("Failed to prepare agent comparison", error);
- toast({
- title: "Comparison failed",
- description:
- "Failed to prepare agent for comparison. Please try again.",
- variant: "destructive",
- });
- }
- }}
- onWorkflowUpdate={handleCopilotWorkflowUpdate}
- />
+ }}
+ onWorkflowUpdate={handleCopilotWorkflowUpdate}
+ />,
+ studioCopilotPortalEl,
+ )}
<ConfirmDialog
open={deleteBlockDialogState.open}
onOpenChange={(open) => {
@@ -3579,12 +3642,15 @@ function Workspace({
) : null}
{/* Studio: Code mode swaps the Editor pane's content (sibling panes stay
usable); legacy keeps the original full-screen modal overlay. */}
- {yamlEditorActive ? (
- <WorkflowYamlEditor
- workflowId={workflow.workflow_permanent_id}
- variant={embedded ? "pane" : "fullscreen"}
- />
- ) : null}
+ {yamlEditorActive
+ ? withStudioPaneBoundary(
+ "yaml",
+ <WorkflowYamlEditor
+ workflowId={workflow.workflow_permanent_id}
+ variant={embedded ? "pane" : "fullscreen"}
+ />,
+ )
+ : null}
</div>
);
}
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioShell.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioShell.tsx
index 11cfb6627..b7a2ccebe 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioShell.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioShell.tsx
@@ -9,6 +9,7 @@ import {
} from "react";
import { createPortal } from "react-dom";
import { useSearchParams } from "react-router-dom";
+import { usePostHog } from "posthog-js/react";
import {
Cross2Icon,
EnterFullScreenIcon,
@@ -16,6 +17,8 @@ import {
} from "@radix-ui/react-icons";
import { CopyButton } from "@/components/CopyButton";
+import { PaneErrorBoundary } from "@/components/PaneErrorBoundary";
+import { useLogging } from "@/hooks/useLogging";
import { StreamStatusPanel } from "@/routes/streaming/StreamDiagnostics";
import {
Tooltip,
@@ -681,6 +684,26 @@ function StudioPaneDivider({
* (?panes=). The Copilot chat is portaled into its pane from Workspace.
*/
export function StudioShell(props: StudioWorkspaceProps) {
+ const [searchParams] = useSearchParams();
+ const postHog = usePostHog();
+ const openedWorkflowIds = useRef(new Set<string>());
+ const workflowPermanentId = props.workflow.workflow_permanent_id;
+
+ useEffect(() => {
+ if (openedWorkflowIds.current.has(workflowPermanentId)) return;
+ openedWorkflowIds.current.add(workflowPermanentId);
+ postHog.capture("studio.opened", {
+ org_id: props.workflow.organization_id,
+ workflow_permanent_id: workflowPermanentId,
+ via: searchParams.get("via"),
+ });
+ }, [
+ postHog,
+ props.workflow.organization_id,
+ searchParams,
+ workflowPermanentId,
+ ]);
+
return (
<StudioWorkflowDeletedContext.Provider
value={props.workflow.deleted_at ?? null}
@@ -743,6 +766,8 @@ export function EmbeddedBrowserOverlays({
function StudioStage(props: StudioWorkspaceProps) {
const [searchParams] = useSearchParams();
+ const postHog = usePostHog();
+ const logging = useLogging();
const embedded = searchParams.get("embed") === "true";
const { panes, closePane, openPane, setOpenPanes, setPanesOrder } =
useStudioPanes();
@@ -755,6 +780,22 @@ function StudioStage(props: StudioWorkspaceProps) {
} = useStudioPaneDefaults();
const runId = useStudioRunId();
const workflowDeleted = Boolean(props.workflow.deleted_at);
+ const reportPaneCrash = (
+ pane: string,
+ error: unknown,
+ componentStack?: string | null,
+ ) => {
+ logging.error("Studio pane crashed", {
+ error_source: "studio_pane",
+ pane,
+ component_stack: componentStack,
+ workflow_permanent_id: props.workflow.workflow_permanent_id,
+ error,
+ });
+ if (typeof postHog?.captureException === "function") {
+ postHog.captureException(error, { error_source: "studio_pane", pane });
+ }
+ };
const isRecording = useRecordingStore((s) => s.isRecording);
// The title store is normally seeded by the embedded Workspace's canvas,
// which never mounts for a deleted agent — seed it here instead.
@@ -874,6 +915,7 @@ function StudioStage(props: StudioWorkspaceProps) {
const shellContextValue = useMemo(
() => ({
+ organizationId: props.workflow.organization_id,
copilotPortalEl,
panelPortalEl,
setEditorStreamSlot,
@@ -881,7 +923,12 @@ function StudioStage(props: StudioWorkspaceProps) {
setRunStreamSlot,
restoreExpandedPane,
}),
- [copilotPortalEl, panelPortalEl, restoreExpandedPane],
+ [
+ copilotPortalEl,
+ panelPortalEl,
+ props.workflow.organization_id,
+ restoreExpandedPane,
+ ],
);
// The ✕ unmounts with its pane, so hand focus back to the pane's toggle.
@@ -1070,22 +1117,38 @@ function StudioStage(props: StudioWorkspaceProps) {
headerExtras={<BrowserPaneViewPills />}
headerActions={<BrowserPaneActions />}
>
- <BrowserTab />
- {embedded ? (
- <EmbeddedBrowserOverlays
- runId={runId}
- showArchivedRecording={
- searchParams.get("view") === "recording"
- }
- />
- ) : null}
+ <PaneErrorBoundary
+ key={`${props.workflow.workflow_permanent_id}:browser`}
+ pane="browser"
+ onError={(error, componentStack) =>
+ reportPaneCrash("browser", error, componentStack)
+ }
+ >
+ <BrowserTab />
+ {embedded ? (
+ <EmbeddedBrowserOverlays
+ runId={runId}
+ showArchivedRecording={
+ searchParams.get("view") === "recording"
+ }
+ />
+ ) : null}
+ </PaneErrorBoundary>
</StudioPane>
<StudioPane
{...paneProps("overview")}
headerExtras={<RunPaneViewToggles />}
headerActions={<RunPaneActions />}
>
- <RunTab />
+ <PaneErrorBoundary
+ key={`${props.workflow.workflow_permanent_id}:run`}
+ pane="run"
+ onError={(error, componentStack) =>
+ reportPaneCrash("run", error, componentStack)
+ }
+ >
+ <RunTab />
+ </PaneErrorBoundary>
</StudioPane>
{/* Dividers are the inter-pane gaps; stateless, so unlike the panes
they can re-render freely as the open list changes. */}
@@ -1129,7 +1192,15 @@ function StudioStage(props: StudioWorkspaceProps) {
className="h-0 w-0 overflow-hidden"
/>
{createPortal(
- <StudioBrowserStream visiblePanes={visiblePanes} />,
+ <PaneErrorBoundary
+ key={`${props.workflow.workflow_permanent_id}:browser_stream`}
+ pane="browser_stream"
+ onError={(error, componentStack) =>
+ reportPaneCrash("browser_stream", error, componentStack)
+ }
+ >
+ <StudioBrowserStream visiblePanes={visiblePanes} />
+ </PaneErrorBoundary>,
streamHostEl,
)}
</div>
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioShellContext.ts b/skyvern-frontend/src/routes/workflows/studio/StudioShellContext.ts
index 454a66d8f..eb0671563 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioShellContext.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioShellContext.ts
@@ -1,6 +1,7 @@
import { createContext, useContext } from "react";
type StudioShellContextValue = {
+ organizationId?: string | null;
// Left-column target Workspace portals the docked Copilot into; null when
// collapsed or when Workspace isn't embedded in the studio shell.
copilotPortalEl: HTMLElement | null;
@@ -20,6 +21,7 @@ type StudioShellContextValue = {
};
export const StudioShellContext = createContext<StudioShellContextValue>({
+ organizationId: null,
copilotPortalEl: null,
panelPortalEl: null,
setEditorStreamSlot: () => {},
diff --git a/skyvern-frontend/src/routes/workflows/studio/useStudioPanes.ts b/skyvern-frontend/src/routes/workflows/studio/useStudioPanes.ts
index b20438f5d..9b87dba87 100644
--- a/skyvern-frontend/src/routes/workflows/studio/useStudioPanes.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/useStudioPanes.ts
@@ -1,4 +1,5 @@
import { useCallback, useMemo } from "react";
+import posthog from "posthog-js";
import {
useLocation,
useNavigate,
@@ -23,6 +24,7 @@ import {
useStudioShellContext,
useStudioWorkflowDeletedAt,
} from "./StudioShellContext";
+import { useWorkflowPermanentId } from "../WorkflowPermanentIdContext";
type ApplyPanesOptions = Pick<NavigateOptions, "state"> & {
selectedBlockLabel?: string | null;
@@ -31,6 +33,7 @@ type ApplyPanesOptions = Pick<NavigateOptions, "state"> & {
export function useStudioPanes() {
const location = useLocation();
const navigate = useNavigate();
+ const workflowPermanentId = useWorkflowPermanentId();
const studioRunId = useStudioRunId();
const {
isStudio,
@@ -40,7 +43,7 @@ export function useStudioPanes() {
preserveNextEntry,
} = useStudioPaneDefaults();
const workflowDeleted = useStudioWorkflowDeletedAt() !== null;
- const { restoreExpandedPane } = useStudioShellContext();
+ const { organizationId, restoreExpandedPane } = useStudioShellContext();
const panes = useMemo(() => {
const resolved = isStudio
? [...currentPanes]
@@ -65,7 +68,20 @@ export function useStudioPanes() {
options?: ApplyPanesOptions,
) => {
restoreExpandedPane?.();
- updatePanes(compute);
+ updatePanes((current, slots) => {
+ const next = compute(current, slots);
+ if (
+ !workflowDeleted &&
+ !current.includes("copilot") &&
+ next.includes("copilot")
+ ) {
+ posthog.capture("copilot.pane.opened", {
+ org_id: organizationId,
+ workflow_permanent_id: workflowPermanentId,
+ });
+ }
+ return next;
+ });
if (
!options ||
(!("state" in options) && options.selectedBlockLabel === undefined)
@@ -95,6 +111,9 @@ export function useStudioPanes() {
[
restoreExpandedPane,
updatePanes,
+ workflowDeleted,
+ organizationId,
+ workflowPermanentId,
location.search,
location.pathname,
location.hash,
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
index c9b99d47c..35d96235a 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
@@ -3,6 +3,7 @@ import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWork
import { useEffect, useRef, useState } from "react";
import { statusIsNotFinalized } from "@/routes/tasks/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useLogging } from "@/hooks/useLogging";
import { useFirstParam } from "@/hooks/useFirstParam";
import { getCredentialParam } from "@/util/env";
import { useQueryClient } from "@tanstack/react-query";
@@ -106,14 +107,20 @@ function WorkflowRunStream({
const showStream =
alwaysShowStream || (workflowRun && statusIsNotFinalized(workflowRun));
const credentialGetter = useCredentialGetter();
+ const logging = useLogging();
const workflow = workflowRun?.workflow;
const workflowPermanentId = workflow?.workflow_permanent_id;
+ const browserSessionId = workflowRun?.browser_session_id ?? null;
+ const browserSessionIdRef = useRef(browserSessionId);
+ browserSessionIdRef.current = browserSessionId;
const queryClient = useQueryClient();
const socketRef = useRef<WebSocket | null>(null);
const hasFrameRef = useRef(false);
const reconnectAttemptsRef = useRef(0);
const streamFinishedRef = useRef(false);
+ const parseFailureLoggedRef = useRef(false);
+ const parseFailureRunIdRef = useRef<string | undefined>(undefined);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Why the stream stopped, when the server told us before closing. Survives into
// the close handler so a reconnect notice augments that reason instead of
@@ -147,6 +154,10 @@ function WorkflowRunStream({
hasFrameRef.current = false;
reconnectAttemptsRef.current = 0;
streamFinishedRef.current = false;
+ if (parseFailureRunIdRef.current !== workflowRunId) {
+ parseFailureRunIdRef.current = workflowRunId;
+ parseFailureLoggedRef.current = false;
+ }
streamEndedDiagnosticRef.current = null;
let cancelled = false;
@@ -264,6 +275,14 @@ function WorkflowRunStream({
}
} catch (e) {
console.error("Failed to parse message", e);
+ if (!parseFailureLoggedRef.current) {
+ parseFailureLoggedRef.current = true;
+ logging.warn("Stream message parse failed", {
+ stream: "run",
+ browser_session_id: browserSessionIdRef.current,
+ workflow_run_id: workflowRunId,
+ });
+ }
// The backend only sends non-JSON text to reject credentials, and
// retrying that would just burn the reconnect budget in silence.
streamFinishedRef.current = true;
@@ -337,6 +356,13 @@ function WorkflowRunStream({
setDiagnostic(
diagnosticForReconnectExhausted(WORKFLOW_RUN_STREAM_SUBJECT),
);
+ logging.warn("Stream gave up", {
+ stream: "run",
+ browser_session_id: browserSessionIdRef.current,
+ workflow_run_id: workflowRunId,
+ reason: "reconnect_exhausted",
+ reconnect_attempts: reconnectAttemptsRef.current,
+ });
}
});
}
@@ -357,6 +383,7 @@ function WorkflowRunStream({
showStream,
queryClient,
workflowPermanentId,
+ logging,
]);
const isRunningOrPaused =
diff --git a/skyvern-frontend/src/store/WorkflowHasChangesStore.ts b/skyvern-frontend/src/store/WorkflowHasChangesStore.ts
index a611156c9..9b1fcd36d 100644
--- a/skyvern-frontend/src/store/WorkflowHasChangesStore.ts
+++ b/skyvern-frontend/src/store/WorkflowHasChangesStore.ts
@@ -28,6 +28,7 @@ import { usePostHog } from "posthog-js/react";
import { getClient } from "@/api/AxiosClient";
import { toast } from "@/components/ui/use-toast";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useLogging } from "@/hooks/useLogging";
import { flushBufferedEditorEdits } from "@/hooks/useDeferredLockedEdit";
import { buildWorkflowSaveRequest } from "@/routes/workflows/editor/workflowYamlDocument";
import { YamlCommitError } from "@/routes/workflows/editor/workflowVersionFromSaveData";
@@ -276,10 +277,25 @@ export class SaveStaleError extends Error {
const WORKFLOW_SAVE_NOTICE_MS = 30_000;
+function getSaveFailureReason(
+ error: AxiosError | YamlCommitError | SaveRefusedError | SaveStaleError,
+) {
+ if (error instanceof SaveStaleError) return "stale";
+ if (error instanceof SaveRefusedError) return "refused";
+ if (!(error instanceof AxiosError)) return "other";
+ const status = error.response?.status;
+ if (status === 422) return "validation";
+ if (status === 409) return "conflict";
+ if (status === undefined) return "network";
+ if (status >= 500 && status < 600) return "server";
+ return "other";
+}
+
const useWorkflowSave = (opts?: WorkflowSaveOpts) => {
const credentialGetter = useCredentialGetter();
const queryClient = useQueryClient();
const postHog = usePostHog();
+ const logging = useLogging();
const {
getSaveData,
setHasChanges,
@@ -305,6 +321,7 @@ const useWorkflowSave = (opts?: WorkflowSaveOpts) => {
const savedRecordingIdRef = useRef<string | null>(null);
const saveWorkflowMutation = useMutation({
+ mutationKey: ["saveWorkflow"],
mutationFn: async (
override?: Partial<SaveData> & {
yamlCommit?: YamlCommitContext;
@@ -391,6 +408,7 @@ const useWorkflowSave = (opts?: WorkflowSaveOpts) => {
const yaml = convertToYAML(requestBody);
if (owner) markWorkflowSavePersisting(owner, saveData.workflow.version);
+ const requestStartedAt = Date.now();
const noticeTimer = setTimeout(() => {
if (!owner) return;
const state = useWorkflowYamlEditorStore.getState();
@@ -402,6 +420,10 @@ const useWorkflowSave = (opts?: WorkflowSaveOpts) => {
[owner.workflowPermanentId]: { ...pending, slow: true },
},
});
+ logging.warn("Workflow save slow", {
+ workflow_permanent_id: saveData.workflow.workflow_permanent_id,
+ elapsed_ms: Date.now() - requestStartedAt,
+ });
}, WORKFLOW_SAVE_NOTICE_MS);
let response;
try {
@@ -530,10 +552,15 @@ const useWorkflowSave = (opts?: WorkflowSaveOpts) => {
onMutate: (override) => {
const store = useWorkflowYamlEditorStore.getState();
const owner = override?.yamlCommit?.owner ?? store.editorOwner;
+ const saveData = getSaveData();
return {
owner,
revision: store.revision,
- workflowPermanentId: owner?.workflowPermanentId,
+ workflowPermanentId:
+ owner?.workflowPermanentId ??
+ saveData?.workflow.workflow_permanent_id,
+ organizationId: saveData?.workflow.organization_id,
+ startedAt: Date.now(),
};
},
onSuccess: (_response, override, context) => {
@@ -562,6 +589,7 @@ const useWorkflowSave = (opts?: WorkflowSaveOpts) => {
source_recording_id: savedRecordingIdRef.current ?? undefined,
block_count: saveData.blocks.length,
block_types: saveData.blocks.map((b) => b.block_type),
+ duration_ms: Math.max(0, Date.now() - context.startedAt),
});
toast({
@@ -575,6 +603,26 @@ const useWorkflowSave = (opts?: WorkflowSaveOpts) => {
override,
context,
) => {
+ const status =
+ error instanceof AxiosError ? error.response?.status : undefined;
+ const saveData = getSaveData();
+ postHog.capture("builder.workflow.save_failed", {
+ org_id: context?.organizationId ?? saveData?.workflow.organization_id,
+ workflow_permanent_id:
+ context?.workflowPermanentId ??
+ saveData?.workflow.workflow_permanent_id,
+ reason: getSaveFailureReason(error),
+ http_status: status ?? null,
+ });
+ if (status !== undefined && status >= 400 && status < 500) {
+ logging.warn("Workflow save rejected", {
+ workflow_permanent_id:
+ context?.workflowPermanentId ??
+ saveData?.workflow.workflow_permanent_id,
+ http_status: status,
+ error,
+ });
+ }
if (context?.owner && !context.owner.active) return;
if (
override?.yamlCommit &&
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index e01961cc5..763baea56 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -180,6 +180,7 @@ from skyvern.forge.sdk.db.id import generate_action_id
from skyvern.forge.sdk.experimentation.code_block_ai_fallback import code_block_ai_fallback_flag_enabled
from skyvern.forge.sdk.experimentation.llm_prompt_config import get_llm_handler_for_prompt_type
from skyvern.forge.sdk.experimentation.workflow_block_engine import workflow_block_engine_override
+from skyvern.forge.sdk.forge_log import exception_log_fields
from skyvern.forge.sdk.models import Step, StepStatus
from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.schemas.task_v2 import TaskV2, TaskV2Status
@@ -16558,6 +16559,8 @@ class PrintPageBlock(Block):
"PrintPageBlock renderer died mid-print; retrying on a replacement page",
attempts_left=attempts_left,
workflow_run_id=workflow_run_id,
+ error=str(error),
+ **exception_log_fields(error),
)
replacement = await self._await_replacement_page(
browser_state=browser_state,
@@ -16745,7 +16748,9 @@ class PrintPageBlock(Block):
error_msg = str(e)
if "pdf" in error_msg.lower() and ("not supported" in error_msg.lower() or "chromium" in error_msg.lower()):
error_msg = "PDF generation requires Chromium browser. Current browser does not support page.pdf()."
- LOG.warning("PrintPageBlock Failed to generate PDF", error=error_msg, workflow_run_id=workflow_run_id)
+ LOG.warning(
+ "PrintPageBlock Failed to generate PDF", error=error_msg, workflow_run_id=workflow_run_id, exc_info=True
+ )
return await self.build_block_result(
success=False,
failure_reason=f"Failed to generate PDF: {error_msg}",