Skip to content

Automate browser based workflows with AI

Add browser controls to CDP streams (#6229)

Suchintan5a6c2f083caf
diff --git a/docs/assets/pr/cdp-browser-controls.png b/docs/assets/pr/cdp-browser-controls.png
new file mode 100644
index 000000000..84458e623
Binary files /dev/null and b/docs/assets/pr/cdp-browser-controls.png differ
diff --git a/skyvern-frontend/src/components/BrowserStream.tsx b/skyvern-frontend/src/components/BrowserStream.tsx
index 5eb5b0355..37cf6334f 100644
--- a/skyvern-frontend/src/components/BrowserStream.tsx
+++ b/skyvern-frontend/src/components/BrowserStream.tsx
@@ -4,7 +4,7 @@
import _RFB from "@novnc/novnc/lib/rfb.js";
type RFB = _RFB;
const RFB = (_RFB as typeof _RFB & { default?: typeof _RFB }).default ?? _RFB;
-import { ExitIcon, HandIcon, InfoCircledIcon } from "@radix-ui/react-icons";
+import { InfoCircledIcon } from "@radix-ui/react-icons";
import { useEffect, useState, useRef, useCallback } from "react";
import { useQuery } from "@tanstack/react-query";
@@ -826,33 +826,40 @@ function BrowserStream({
{isReady && isVisible && (
<div className="overlay z-10 flex items-center justify-center overflow-hidden">
{showControlButtons && (
- <div className="control-buttons pointer-events-none relative flex h-full w-full items-center justify-center">
+ <div className="control-buttons pointer-events-none relative flex h-full w-full items-center justify-center bg-[radial-gradient(circle_at_center,rgba(15,23,42,0.22)_0%,rgba(15,23,42,0.12)_18%,transparent_42%)]">
<Button
+ aria-label="Take control of this browser session"
onClick={() => {
setUserIsControlling(true);
}}
- className={cn("control-button pointer-events-auto border", {
- hide: userIsControlling,
- })}
- size="sm"
+ className={cn(
+ "control-button group pointer-events-auto h-10 rounded-full border border-white/15 bg-slate-950/90 px-5 text-sm font-semibold text-white shadow-xl shadow-slate-950/25 ring-1 ring-slate-950/10 backdrop-blur-sm transition duration-200 ease-out hover:-translate-y-0.5 hover:bg-slate-900 hover:shadow-2xl focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 motion-reduce:transition-none motion-reduce:hover:translate-y-0",
+ {
+ hide: userIsControlling,
+ },
+ )}
>
- <HandIcon className="mr-2 h-4 w-4" />
- take control
+ Take the wheel
+ <span
+ aria-hidden="true"
+ className="ml-2 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none"
+ >
+ →
+ </span>
</Button>
<Button
+ aria-label="Stop controlling this browser session"
onClick={() => {
setUserIsControlling(false);
}}
className={cn(
- "control-button pointer-events-auto absolute bottom-0 border",
+ "control-button pointer-events-auto absolute bottom-0 h-9 rounded-full border border-white/15 bg-slate-950/90 px-4 text-sm font-semibold text-white shadow-xl shadow-slate-950/25 ring-1 ring-slate-950/10 backdrop-blur-sm transition duration-200 ease-out hover:-translate-y-0.5 hover:bg-slate-900 focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 motion-reduce:transition-none motion-reduce:hover:translate-y-0",
{
hide: !userIsControlling,
},
)}
- size="sm"
>
- <ExitIcon className="mr-2 h-4 w-4" />
- stop controlling
+ Release control
</Button>
</div>
)}
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
index bfbb84b1c..b487d8a8d 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
@@ -109,8 +109,10 @@ function BrowserSessionStream({
userIsControlling,
setUserIsControlling,
inputReady,
+ browserCommandError,
containerRef,
handlers,
+ browserControls,
} = useCdpInput({
inputWsUrl,
interactive,
@@ -236,9 +238,11 @@ function BrowserSessionStream({
userIsControlling={userIsControlling}
setUserIsControlling={setUserIsControlling}
inputReady={inputReady}
+ browserCommandError={interactive ? browserCommandError : null}
containerRef={containerRef}
showControlButtons={showControlButtons}
handlers={handlers}
+ browserControls={interactive ? browserControls : undefined}
currentUrl={currentUrl}
/>
);
diff --git a/skyvern-frontend/src/routes/streaming/InteractiveStreamView.tsx b/skyvern-frontend/src/routes/streaming/InteractiveStreamView.tsx
index b99bf31eb..bfc65860a 100644
--- a/skyvern-frontend/src/routes/streaming/InteractiveStreamView.tsx
+++ b/skyvern-frontend/src/routes/streaming/InteractiveStreamView.tsx
@@ -1,7 +1,13 @@
-import type { RefObject } from "react";
-import { GlobeIcon } from "@radix-ui/react-icons";
+import { useEffect, useState, type FormEvent, type RefObject } from "react";
+import {
+ ArrowLeftIcon,
+ ArrowRightIcon,
+ GlobeIcon,
+ ReloadIcon,
+} from "@radix-ui/react-icons";
import { ZoomableImage } from "@/components/ZoomableImage";
import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
import { cn } from "@/util/utils";
interface InteractiveStreamViewProps {
@@ -11,6 +17,7 @@ interface InteractiveStreamViewProps {
userIsControlling: boolean;
setUserIsControlling: (v: boolean) => void;
inputReady: boolean;
+ browserCommandError?: string | null;
containerRef: RefObject<HTMLDivElement>;
showControlButtons: boolean;
handlers: {
@@ -20,14 +27,99 @@ interface InteractiveStreamViewProps {
handleKeyDown: (e: React.KeyboardEvent) => void;
handleKeyUp: (e: React.KeyboardEvent) => void;
};
+ browserControls?: {
+ navigate: (url: string) => void;
+ reload: () => void;
+ goBack: () => void;
+ goForward: () => void;
+ };
currentUrl?: string;
}
-function UrlBar({ url }: { url: string }) {
+function UrlBar({
+ url,
+ inputReady,
+ browserCommandError,
+ browserControls,
+}: {
+ url: string;
+ inputReady: boolean;
+ browserCommandError?: string | null;
+ browserControls?: InteractiveStreamViewProps["browserControls"];
+}) {
+ const [draftUrl, setDraftUrl] = useState(url);
+ const controlsEnabled = inputReady && Boolean(browserControls);
+
+ useEffect(() => {
+ setDraftUrl(url);
+ }, [url]);
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault();
+ e.stopPropagation();
+ browserControls?.navigate(draftUrl);
+ }
+
return (
- <div className="flex h-8 w-full items-center gap-2 rounded-t-md bg-slate-800 px-3 text-xs text-slate-300">
- <GlobeIcon className="h-3 w-3 flex-shrink-0 text-slate-400" />
- <span className="truncate">{url}</span>
+ <div
+ className="flex h-8 w-full items-center gap-1 rounded-t-md bg-slate-800 px-2 text-xs text-slate-300"
+ onKeyDown={(e) => e.stopPropagation()}
+ onKeyUp={(e) => e.stopPropagation()}
+ onMouseDown={(e) => e.stopPropagation()}
+ onMouseUp={(e) => e.stopPropagation()}
+ >
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6 flex-shrink-0 text-slate-300 hover:bg-slate-700 hover:text-white"
+ disabled={!controlsEnabled}
+ aria-label="Go back"
+ title="Go back"
+ onClick={() => browserControls?.goBack()}
+ >
+ <ArrowLeftIcon className="h-3.5 w-3.5" />
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6 flex-shrink-0 text-slate-300 hover:bg-slate-700 hover:text-white"
+ disabled={!controlsEnabled}
+ aria-label="Go forward"
+ title="Go forward"
+ onClick={() => browserControls?.goForward()}
+ >
+ <ArrowRightIcon className="h-3.5 w-3.5" />
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6 flex-shrink-0 text-slate-300 hover:bg-slate-700 hover:text-white"
+ disabled={!controlsEnabled}
+ aria-label="Reload"
+ title="Reload"
+ onClick={() => browserControls?.reload()}
+ >
+ <ReloadIcon className="h-3.5 w-3.5" />
+ </Button>
+ <form className="min-w-0 flex-1" onSubmit={handleSubmit}>
+ <div className="relative">
+ <GlobeIcon className="pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-slate-400" />
+ <Input
+ value={draftUrl}
+ disabled={!controlsEnabled}
+ aria-label="Current browser URL"
+ title={browserCommandError || draftUrl}
+ onChange={(e) => setDraftUrl(e.target.value)}
+ className={cn(
+ "h-6 rounded border-slate-700 bg-slate-900 py-0 pl-7 pr-2 text-xs text-slate-200 shadow-none focus-visible:ring-slate-500",
+ browserCommandError ? "border-red-500 text-red-200" : "",
+ )}
+ />
+ </div>
+ </form>
</div>
);
}
@@ -39,12 +131,15 @@ function InteractiveStreamView({
userIsControlling,
setUserIsControlling,
inputReady,
+ browserCommandError,
containerRef,
showControlButtons,
handlers,
+ browserControls,
currentUrl,
}: InteractiveStreamViewProps) {
const imgDataUrl = `data:image/${streamFormat};base64,${streamImgSrc}`;
+ const showUrlBar = Boolean(currentUrl) || Boolean(browserControls);
if (interactive) {
return (
@@ -55,27 +150,45 @@ function InteractiveStreamView({
onKeyDown={handlers.handleKeyDown}
onKeyUp={handlers.handleKeyUp}
>
- {currentUrl && <UrlBar url={currentUrl} />}
+ {showUrlBar && (
+ <UrlBar
+ url={currentUrl ?? ""}
+ inputReady={inputReady}
+ browserCommandError={browserCommandError}
+ browserControls={browserControls}
+ />
+ )}
{showControlButtons && !userIsControlling && inputReady && (
- <div className="absolute inset-0 z-10 flex items-center justify-center">
- <Button onClick={() => setUserIsControlling(true)}>
- take control
+ <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-[radial-gradient(circle_at_center,rgba(15,23,42,0.22)_0%,rgba(15,23,42,0.12)_18%,transparent_42%)]">
+ <Button
+ aria-label="Take control of this browser session"
+ className="group pointer-events-auto h-10 rounded-full border border-white/15 bg-slate-950/90 px-5 text-sm font-semibold text-white shadow-xl shadow-slate-950/25 ring-1 ring-slate-950/10 backdrop-blur-sm transition duration-200 ease-out hover:-translate-y-0.5 hover:bg-slate-900 hover:shadow-2xl focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 motion-reduce:transition-none motion-reduce:hover:translate-y-0"
+ onClick={() => setUserIsControlling(true)}
+ >
+ Take the wheel
+ <span
+ aria-hidden="true"
+ className="ml-2 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none"
+ >
+ →
+ </span>
</Button>
</div>
)}
{showControlButtons && userIsControlling && (
<Button
- className="absolute bottom-2 left-1/2 z-10 -translate-x-1/2"
+ aria-label="Stop controlling this browser session"
+ className="absolute bottom-2 left-1/2 z-10 h-9 -translate-x-1/2 rounded-full border border-white/15 bg-slate-950/90 px-4 text-sm font-semibold text-white shadow-xl shadow-slate-950/25 ring-1 ring-slate-950/10 backdrop-blur-sm transition duration-200 ease-out hover:-translate-x-1/2 hover:-translate-y-0.5 hover:bg-slate-900 focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 motion-reduce:transition-none motion-reduce:hover:-translate-x-1/2 motion-reduce:hover:translate-y-0"
onClick={() => setUserIsControlling(false)}
>
- stop controlling
+ Release control
</Button>
)}
<img
src={imgDataUrl}
className={cn(
"w-full rounded-md object-contain",
- currentUrl ? "h-[calc(100%-2rem)]" : "h-full",
+ showUrlBar ? "h-[calc(100%-2rem)] rounded-t-none" : "h-full",
{ "cursor-default": userIsControlling },
)}
onMouseDown={handlers.handleMouseDown}
@@ -90,11 +203,18 @@ function InteractiveStreamView({
return (
<div className="h-full w-full">
- {currentUrl && <UrlBar url={currentUrl} />}
+ {showUrlBar && (
+ <UrlBar
+ url={currentUrl ?? ""}
+ inputReady={inputReady}
+ browserCommandError={browserCommandError}
+ browserControls={browserControls}
+ />
+ )}
<ZoomableImage
src={imgDataUrl}
className={
- currentUrl ? "h-[calc(100%-2rem)] rounded-b-md" : "rounded-md"
+ showUrlBar ? "h-[calc(100%-2rem)] rounded-b-md" : "rounded-md"
}
/>
</div>
diff --git a/skyvern-frontend/src/routes/streaming/cdpInputUtils.test.ts b/skyvern-frontend/src/routes/streaming/cdpInputUtils.test.ts
new file mode 100644
index 000000000..427109320
--- /dev/null
+++ b/skyvern-frontend/src/routes/streaming/cdpInputUtils.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, test } from "vitest";
+import { buildKeyDownPayload, buildKeyUpPayload } from "./cdpInputUtils";
+
+function makeKeyboardEvent(
+ key: string,
+ code: string,
+ modifiers: Partial<KeyboardEvent> = {},
+): KeyboardEvent {
+ return new KeyboardEvent("keydown", {
+ key,
+ code,
+ altKey: Boolean(modifiers.altKey),
+ ctrlKey: Boolean(modifiers.ctrlKey),
+ metaKey: Boolean(modifiers.metaKey),
+ shiftKey: Boolean(modifiers.shiftKey),
+ });
+}
+
+describe("CDP keyboard payloads", () => {
+ test("sends non-printable keys as rawKeyDown with a Windows virtual key code", () => {
+ expect(buildKeyDownPayload(makeKeyboardEvent("Enter", "Enter"))).toEqual({
+ type: "keyEvent",
+ eventType: "rawKeyDown",
+ key: "Enter",
+ code: "Enter",
+ windowsVirtualKeyCode: 13,
+ modifiers: 0,
+ });
+
+ expect(
+ buildKeyDownPayload(makeKeyboardEvent("ArrowLeft", "ArrowLeft")),
+ ).toMatchObject({
+ eventType: "rawKeyDown",
+ windowsVirtualKeyCode: 37,
+ });
+ });
+
+ test("includes the Windows virtual key code on keyUp for non-printable keys", () => {
+ expect(
+ buildKeyUpPayload(makeKeyboardEvent("Backspace", "Backspace")),
+ ).toEqual({
+ type: "keyEvent",
+ eventType: "keyUp",
+ key: "Backspace",
+ code: "Backspace",
+ windowsVirtualKeyCode: 8,
+ modifiers: 0,
+ });
+ });
+
+ test("keeps printable characters as keyDown with text", () => {
+ expect(buildKeyDownPayload(makeKeyboardEvent("a", "KeyA"))).toEqual({
+ type: "keyEvent",
+ eventType: "keyDown",
+ key: "a",
+ code: "KeyA",
+ text: "a",
+ windowsVirtualKeyCode: 65,
+ modifiers: 0,
+ });
+ });
+
+ test("keeps unmapped multi-character keys as keyDown", () => {
+ expect(buildKeyDownPayload(makeKeyboardEvent("Dead", "Quote"))).toEqual({
+ type: "keyEvent",
+ eventType: "keyDown",
+ key: "Dead",
+ code: "Quote",
+ modifiers: 0,
+ });
+ });
+
+ test("preserves modifier bitmask", () => {
+ expect(
+ buildKeyDownPayload(
+ makeKeyboardEvent("Tab", "Tab", { ctrlKey: true, shiftKey: true }),
+ ),
+ ).toMatchObject({
+ modifiers: 10,
+ windowsVirtualKeyCode: 9,
+ });
+ });
+});
diff --git a/skyvern-frontend/src/routes/streaming/cdpInputUtils.ts b/skyvern-frontend/src/routes/streaming/cdpInputUtils.ts
index 9937da288..8c2552d0a 100644
--- a/skyvern-frontend/src/routes/streaming/cdpInputUtils.ts
+++ b/skyvern-frontend/src/routes/streaming/cdpInputUtils.ts
@@ -15,6 +15,102 @@ export function getModifiers(
return m;
}
+const WINDOWS_VIRTUAL_KEY_CODES: Record<string, number> = {
+ Backspace: 8,
+ Tab: 9,
+ Enter: 13,
+ Shift: 16,
+ Control: 17,
+ Alt: 18,
+ Pause: 19,
+ CapsLock: 20,
+ Escape: 27,
+ " ": 32,
+ PageUp: 33,
+ PageDown: 34,
+ End: 35,
+ Home: 36,
+ ArrowLeft: 37,
+ ArrowUp: 38,
+ ArrowRight: 39,
+ ArrowDown: 40,
+ Insert: 45,
+ Delete: 46,
+ Meta: 91,
+ ContextMenu: 93,
+ F1: 112,
+ F2: 113,
+ F3: 114,
+ F4: 115,
+ F5: 116,
+ F6: 117,
+ F7: 118,
+ F8: 119,
+ F9: 120,
+ F10: 121,
+ F11: 122,
+ F12: 123,
+ NumLock: 144,
+ ScrollLock: 145,
+};
+
+export type CdpKeyEventPayload = {
+ type: "keyEvent";
+ eventType: "keyDown" | "keyUp" | "rawKeyDown";
+ key: string;
+ code: string;
+ modifiers: number;
+ text?: string;
+ windowsVirtualKeyCode?: number;
+};
+
+type KeyboardEventLike = Pick<
+ KeyboardEvent,
+ "altKey" | "code" | "ctrlKey" | "key" | "metaKey" | "shiftKey"
+>;
+
+function windowsVirtualKeyCodeForKey(key: string): number | undefined {
+ if (/^[a-z]$/i.test(key)) {
+ return key.toUpperCase().charCodeAt(0);
+ }
+ if (/^[0-9]$/.test(key)) {
+ return key.charCodeAt(0);
+ }
+ return WINDOWS_VIRTUAL_KEY_CODES[key];
+}
+
+export function buildKeyDownPayload(e: KeyboardEventLike): CdpKeyEventPayload {
+ const windowsVirtualKeyCode = windowsVirtualKeyCodeForKey(e.key);
+ const isPrintableSingleCharacter = e.key.length === 1;
+ const eventType =
+ !isPrintableSingleCharacter && windowsVirtualKeyCode !== undefined
+ ? "rawKeyDown"
+ : "keyDown";
+
+ return {
+ type: "keyEvent",
+ eventType,
+ key: e.key,
+ code: e.code,
+ ...(isPrintableSingleCharacter ? { text: e.key } : {}),
+ ...(windowsVirtualKeyCode !== undefined ? { windowsVirtualKeyCode } : {}),
+ modifiers: getModifiers(e),
+ };
+}
+
+export function buildKeyUpPayload(e: KeyboardEventLike): CdpKeyEventPayload {
+ const windowsVirtualKeyCode = windowsVirtualKeyCodeForKey(e.key);
+
+ return {
+ type: "keyEvent",
+ eventType: "keyUp",
+ key: e.key,
+ code: e.code,
+ ...(windowsVirtualKeyCode !== undefined ? { windowsVirtualKeyCode } : {}),
+ modifiers: getModifiers(e),
+ };
+}
+
/**
* Map pixel coordinates from a rendered image back to viewport coordinates,
* accounting for object-contain letterboxing.
diff --git a/skyvern-frontend/src/routes/streaming/useCdpInput.ts b/skyvern-frontend/src/routes/streaming/useCdpInput.ts
index 72f7119d7..3664b23d1 100644
--- a/skyvern-frontend/src/routes/streaming/useCdpInput.ts
+++ b/skyvern-frontend/src/routes/streaming/useCdpInput.ts
@@ -4,6 +4,8 @@ import { getCredentialParam } from "@/util/env";
import { useClientIdStore } from "@/store/useClientIdStore";
import {
mouseButtonName,
+ buildKeyDownPayload,
+ buildKeyUpPayload,
getModifiers,
mapCoordinates,
mapMouseCoordinates,
@@ -22,6 +24,7 @@ interface UseCdpInputReturn {
userIsControlling: boolean;
setUserIsControlling: (v: boolean) => void;
inputReady: boolean;
+ browserCommandError: string | null;
containerRef: React.RefObject<HTMLDivElement>;
handlers: {
handleMouseDown: (e: React.MouseEvent<HTMLImageElement>) => void;
@@ -30,6 +33,12 @@ interface UseCdpInputReturn {
handleKeyDown: (e: React.KeyboardEvent) => void;
handleKeyUp: (e: React.KeyboardEvent) => void;
};
+ browserControls: {
+ navigate: (url: string) => void;
+ reload: () => void;
+ goBack: () => void;
+ goForward: () => void;
+ };
}
export function useCdpInput({
@@ -40,6 +49,9 @@ export function useCdpInput({
}: UseCdpInputOptions): UseCdpInputReturn {
const [userIsControlling, setUserIsControlling] = useState(false);
const [inputReady, setInputReady] = useState(false);
+ const [browserCommandError, setBrowserCommandError] = useState<string | null>(
+ null,
+ );
const credentialGetter = useCredentialGetter();
const clientId = useClientIdStore((s) => s.clientId);
@@ -93,6 +105,8 @@ export function useCdpInput({
if (userIsControllingRef.current) {
ws.send(JSON.stringify({ kind: "take-control" }));
}
+ } else if (msg.kind === "browserCommandResult") {
+ setBrowserCommandError(msg.ok ? null : String(msg.error || ""));
}
} catch {
// ignore non-JSON messages
@@ -237,6 +251,44 @@ export function useCdpInput({
ws.send(JSON.stringify(payload));
}, []);
+ const sendBrowserCommand = useCallback((payload: Record<string, unknown>) => {
+ const ws = inputSocketRef.current;
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
+ setBrowserCommandError("Browser controls are not connected.");
+ return;
+ }
+ setBrowserCommandError(null);
+ ws.send(JSON.stringify({ type: "browserCommand", ...payload }));
+ }, []);
+
+ const navigate = useCallback(
+ (rawUrl: string) => {
+ const url = rawUrl.trim();
+ if (!url) {
+ setBrowserCommandError("URL must not be empty.");
+ return;
+ }
+ if (url.toLowerCase().startsWith("chrome://")) {
+ setBrowserCommandError("chrome:// URLs are not allowed.");
+ return;
+ }
+ sendBrowserCommand({ command: "navigate", url });
+ },
+ [sendBrowserCommand],
+ );
+
+ const reload = useCallback(() => {
+ sendBrowserCommand({ command: "reload" });
+ }, [sendBrowserCommand]);
+
+ const goBack = useCallback(() => {
+ sendBrowserCommand({ command: "goBack" });
+ }, [sendBrowserCommand]);
+
+ const goForward = useCallback(() => {
+ sendBrowserCommand({ command: "goForward" });
+ }, [sendBrowserCommand]);
+
const handleMouseDown = useCallback(
(e: React.MouseEvent<HTMLImageElement>) => {
if (!interactive || !userIsControlling) return;
@@ -316,14 +368,7 @@ export function useCdpInput({
(e: React.KeyboardEvent) => {
if (!interactive || !userIsControlling) return;
e.preventDefault();
- sendInputEvent({
- type: "keyEvent",
- eventType: "keyDown",
- key: e.key,
- code: e.code,
- text: e.key.length === 1 ? e.key : "",
- modifiers: getModifiers(e),
- });
+ sendInputEvent(buildKeyDownPayload(e.nativeEvent));
},
[interactive, userIsControlling, sendInputEvent],
);
@@ -332,13 +377,7 @@ export function useCdpInput({
(e: React.KeyboardEvent) => {
if (!interactive || !userIsControlling) return;
e.preventDefault();
- sendInputEvent({
- type: "keyEvent",
- eventType: "keyUp",
- key: e.key,
- code: e.code,
- modifiers: getModifiers(e),
- });
+ sendInputEvent(buildKeyUpPayload(e.nativeEvent));
},
[interactive, userIsControlling, sendInputEvent],
);
@@ -347,6 +386,7 @@ export function useCdpInput({
userIsControlling,
setUserIsControlling,
inputReady,
+ browserCommandError,
containerRef,
handlers: {
handleMouseDown,
@@ -355,5 +395,11 @@ export function useCdpInput({
handleKeyDown,
handleKeyUp,
},
+ browserControls: {
+ navigate,
+ reload,
+ goBack,
+ goForward,
+ },
};
}
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
index 78e6a0ca5..ded4e53f0 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
@@ -22,6 +22,7 @@ type StreamMessage = {
format?: string;
viewport_width?: number;
viewport_height?: number;
+ url?: string;
};
const STARTING_DIAGNOSTIC: StreamDiagnostic = {
@@ -93,6 +94,7 @@ function WorkflowRunStream({
const [streamFormat, setStreamFormat] = useState<string>("png");
const [viewportWidth, setViewportWidth] = useState(1280);
const [viewportHeight, setViewportHeight] = useState(720);
+ const [currentUrl, setCurrentUrl] = useState("");
const [diagnostic, setDiagnostic] =
useState<StreamDiagnostic>(STARTING_DIAGNOSTIC);
const showStream =
@@ -114,8 +116,10 @@ function WorkflowRunStream({
userIsControlling,
setUserIsControlling,
inputReady,
+ browserCommandError,
containerRef,
handlers,
+ browserControls,
} = useCdpInput({
inputWsUrl,
interactive,
@@ -128,6 +132,7 @@ function WorkflowRunStream({
return;
}
setDiagnostic(STARTING_DIAGNOSTIC);
+ setCurrentUrl("");
hasFrameRef.current = false;
let cancelled = false;
@@ -167,6 +172,9 @@ function WorkflowRunStream({
if (message.viewport_height) {
setViewportHeight(message.viewport_height);
}
+ if (message.url !== undefined) {
+ setCurrentUrl(message.url);
+ }
if (!message.screenshot && message.status) {
setDiagnostic(diagnosticForStatus(message.status));
}
@@ -289,9 +297,12 @@ function WorkflowRunStream({
userIsControlling={userIsControlling}
setUserIsControlling={setUserIsControlling}
inputReady={inputReady}
+ browserCommandError={interactive ? browserCommandError : null}
containerRef={containerRef}
showControlButtons={showControlButtons}
handlers={handlers}
+ browserControls={interactive ? browserControls : undefined}
+ currentUrl={currentUrl}
/>
);
}
diff --git a/skyvern/forge/sdk/routes/streaming/cdp_input.py b/skyvern/forge/sdk/routes/streaming/cdp_input.py
index 772967d6e..5c0f7d3d0 100644
--- a/skyvern/forge/sdk/routes/streaming/cdp_input.py
+++ b/skyvern/forge/sdk/routes/streaming/cdp_input.py
@@ -5,14 +5,17 @@ CDP input channel for interactive browser control via Chrome DevTools Protocol.
import asyncio
import dataclasses
import json
+import re
import time
import typing as t
+from urllib.parse import urlparse
import structlog
from fastapi import WebSocket, WebSocketDisconnect
-from playwright.async_api import CDPSession
+from playwright.async_api import CDPSession, Page
from websockets.exceptions import ConnectionClosedError, ConnectionClosedOK
+from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.sdk.routes.routers import base_router, legacy_base_router
from skyvern.forge.sdk.routes.streaming.auth import auth, require_client_id
@@ -37,6 +40,8 @@ _MAX_KEY_LEN = 32
_MAX_CODE_LEN = 32
_MODIFIER_MASK = 0xF
_MAX_VK_CODE = 0xFE
+_MAX_NAVIGATION_URL_LEN = 2048
+_BARE_HOST_PORT_RE = re.compile(r"^[A-Za-z0-9.-]+:\d+(?:[/?#].*)?$")
@dataclasses.dataclass
@@ -196,10 +201,86 @@ async def _dispatch_event(
)
+def _normalize_navigation_url(raw_url: str) -> str:
+ candidate = raw_url.strip()
+ if not candidate:
+ raise ValueError("URL must not be empty")
+ if len(candidate) > _MAX_NAVIGATION_URL_LEN:
+ raise ValueError("URL is too long")
+ if candidate.lower().startswith("chrome://"):
+ raise ValueError("chrome:// URLs are not allowed")
+ if candidate.startswith("//"):
+ raise ValueError("URL must include an explicit http(s) scheme or host")
+ if _BARE_HOST_PORT_RE.match(candidate):
+ return f"http://{candidate}"
+
+ parsed = urlparse(candidate)
+ if parsed.scheme in ("http", "https"):
+ return candidate
+ if parsed.scheme:
+ raise ValueError(f"refusing to navigate to non-http(s) scheme: {parsed.scheme}")
+ return f"https://{candidate}"
+
+
+async def _dispatch_browser_command(
+ websocket: WebSocket,
+ page: Page,
+ msg: dict,
+ log_id_key: str,
+ log_id_value: str,
+) -> None:
+ command = msg.get("command")
+ try:
+ if command == "reload":
+ await page.reload(wait_until="domcontentloaded", timeout=settings.BROWSER_ACTION_TIMEOUT_MS)
+ elif command == "goBack":
+ await page.go_back(wait_until="domcontentloaded", timeout=settings.BROWSER_ACTION_TIMEOUT_MS)
+ elif command == "goForward":
+ await page.go_forward(wait_until="domcontentloaded", timeout=settings.BROWSER_ACTION_TIMEOUT_MS)
+ elif command == "navigate":
+ raw_url = msg.get("url")
+ if not isinstance(raw_url, str):
+ raise ValueError("URL must be a string")
+ await page.goto(
+ _normalize_navigation_url(raw_url),
+ wait_until="domcontentloaded",
+ timeout=settings.BROWSER_ACTION_TIMEOUT_MS,
+ )
+ else:
+ raise ValueError("unsupported browser command")
+ except Exception as exc:
+ LOG.warning(
+ "CDP input: browser command failed",
+ **{log_id_key: log_id_value},
+ command=command,
+ error=str(exc),
+ )
+ await websocket.send_json(
+ {
+ "kind": "browserCommandResult",
+ "ok": False,
+ "command": command,
+ "error": str(exc),
+ "url": page.url,
+ }
+ )
+ return
+
+ await websocket.send_json(
+ {
+ "kind": "browserCommandResult",
+ "ok": True,
+ "command": command,
+ "url": page.url,
+ }
+ )
+
+
async def _run_input_loop(
websocket: WebSocket,
channel: CdpInputChannel,
cdp_session: CDPSession,
+ page: Page,
log_id_key: str,
log_id_value: str,
) -> None:
@@ -226,6 +307,9 @@ async def _run_input_loop(
channel.interactor = "agent"
LOG.info("CDP input: cede-control received", **{log_id_key: log_id_value}, client_id=channel.client_id)
continue
+ if kind == "browserCommand":
+ await _dispatch_browser_command(websocket, page, msg, log_id_key, log_id_value)
+ continue
if channel.interactor != "user":
if dropped_log_count < 5:
@@ -314,7 +398,7 @@ async def cdp_input_stream(
LOG.info("CDP input channel ready", workflow_run_id=workflow_run_id, client_id=client_id)
await websocket.send_json({"kind": "ready"})
- await _run_input_loop(websocket, channel, cdp_session, "workflow_run_id", workflow_run_id)
+ await _run_input_loop(websocket, channel, cdp_session, page, "workflow_run_id", workflow_run_id)
except ConnectionClosedOK:
LOG.info("CDP input: WS closed cleanly", workflow_run_id=workflow_run_id)
@@ -390,7 +474,7 @@ async def cdp_input_browser_session_stream(
LOG.info("CDP input channel ready", browser_session_id=browser_session_id, client_id=client_id)
await websocket.send_json({"kind": "ready"})
- await _run_input_loop(websocket, channel, cdp_session, "browser_session_id", browser_session_id)
+ await _run_input_loop(websocket, channel, cdp_session, page, "browser_session_id", browser_session_id)
except ConnectionClosedOK:
LOG.info("CDP input: WS closed cleanly", browser_session_id=browser_session_id)