Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(streaming): support VNC address bar paste (#6812)
Suchintande730d4b57b8
diff --git a/skyvern-frontend/src/components/BrowserStream.test.tsx b/skyvern-frontend/src/components/BrowserStream.test.tsxnew file mode 100644index 000000000..28547c010--- /dev/null+++ b/skyvern-frontend/src/components/BrowserStream.test.tsx@@ -0,0 +1,194 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { BrowserStream } from "./BrowserStream";++const mocks = vi.hoisted(() => {+ type RfbListener = (event: { detail?: unknown }) => void;++ const rfbInstances: Array<{+ clipboardPasteFrom: ReturnType<typeof vi.fn>;+ sendKey: ReturnType<typeof vi.fn>;+ disconnect: ReturnType<typeof vi.fn>;+ }> = [];+ const apiGet = vi.fn(async () => ({+ data: {+ browser_session_id: "pbs_test",+ status: "running",+ browser_address: "ws://browser.test",+ started_at: "2026-01-01T00:00:00Z",+ completed_at: null,+ },+ }));++ class MockRFB {+ scaleViewport = false;+ clipboardPasteFrom = vi.fn();+ sendKey = vi.fn();+ disconnect = vi.fn();++ private listeners: Record<string, RfbListener[]> = {};++ constructor(target: HTMLElement) {+ rfbInstances.push(this);+ target.appendChild(document.createElement("canvas"));+ queueMicrotask(() => this.emit("connect"));+ }++ addEventListener(type: string, listener: RfbListener) {+ this.listeners[type] = [...(this.listeners[type] ?? []), listener];+ }++ removeEventListener(type: string, listener: RfbListener) {+ this.listeners[type] = (this.listeners[type] ?? []).filter(+ (candidate) => candidate !== listener,+ );+ }++ private emit(type: string, detail?: unknown) {+ for (const listener of this.listeners[type] ?? []) {+ listener({ detail });+ }+ }+ }++ class MockWebSocket {+ onopen: ((event: Event) => void) | null = null;+ onmessage: ((event: MessageEvent) => void) | null = null;+ onclose: ((event: CloseEvent) => void) | null = null;+ send = vi.fn();+ close = vi.fn();++ constructor() {+ queueMicrotask(() => this.onopen?.(new Event("open")));+ }+ }++ const settingsStore = {+ setBrowserSessionId: vi.fn(),+ setIsUsingABrowser: vi.fn(),+ };++ const recordingStore = {+ add: vi.fn(),+ compressedChunks: [],+ getEventCount: vi.fn(() => 0),+ getSecondsRecording: vi.fn(() => 0),+ isRecording: false,+ pendingEvents: [],+ reset: vi.fn(),+ setIsRecording: vi.fn(),+ };++ return {+ MockRFB,+ MockWebSocket,+ apiGet,+ rfbInstances,+ recordingStore,+ settingsStore,+ };+});++vi.mock("@novnc/novnc/lib/rfb.js", () => ({+ default: mocks.MockRFB,+}));++vi.mock("@/api/AxiosClient", () => ({+ getClient: vi.fn(async () => ({ get: mocks.apiGet })),+}));++vi.mock("@/hooks/useCredentialGetter", () => ({+ useCredentialGetter: () => async () => null,+}));++vi.mock("@/store/useClientIdStore", () => ({+ useClientIdStore: (selector: (state: { clientId: string }) => unknown) =>+ selector({ clientId: "client-test" }),+}));++vi.mock("@/store/SettingsStore", () => ({+ useSettingsStore: () => mocks.settingsStore,+}));++vi.mock("@/store/useRecordingStore", () => ({+ useRecordingStore: () => mocks.recordingStore,+}));++function renderBrowserStream() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ });++ return render(+ <QueryClientProvider client={queryClient}>+ <BrowserStream+ browserSessionId="pbs_test"+ interactive={false}+ showControlButtons={true}+ />+ </QueryClientProvider>,+ );+}++describe("BrowserStream", () => {+ beforeEach(() => {+ Object.defineProperty(globalThis, "WebSocket", {+ configurable: true,+ value: mocks.MockWebSocket,+ });+ Object.defineProperty(window, "WebSocket", {+ configurable: true,+ value: mocks.MockWebSocket,+ });+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: {+ readText: vi.fn(async () => "https://example.test"),+ },+ });+ });++ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ mocks.rfbInstances.length = 0;+ });++ it("supports VNC paste after taking control of a browser session stream", async () => {+ const { container } = renderBrowserStream();+ const takeControlButton = await screen.findByRole("button", {+ name: /take control/i,+ });+ const stream = container.querySelector(".browser-stream");++ expect(stream).toBeInstanceOf(HTMLElement);+ expect(mocks.rfbInstances).toHaveLength(1);++ fireEvent.keyDown(stream!, { ctrlKey: true, key: "v" });+ expect(mocks.rfbInstances[0]?.clipboardPasteFrom).not.toHaveBeenCalled();++ fireEvent.click(takeControlButton);+ fireEvent.keyDown(stream!, { ctrlKey: true, key: "v" });++ await waitFor(() => {+ expect(mocks.rfbInstances[0]?.clipboardPasteFrom).toHaveBeenCalledWith(+ "https://example.test",+ );+ });+ await waitFor(() => {+ expect(mocks.rfbInstances[0]?.sendKey).toHaveBeenCalledTimes(4);+ });+ });+});diff --git a/skyvern-frontend/src/components/BrowserStream.tsx b/skyvern-frontend/src/components/BrowserStream.tsxindex 7773cb83f..21cd49c40 100644--- a/skyvern-frontend/src/components/BrowserStream.tsx+++ b/skyvern-frontend/src/components/BrowserStream.tsx@@ -43,6 +43,7 @@ import {StreamStatusPanel,type StreamDiagnostic,} from "@/routes/streaming/StreamDiagnostics";+import { handleVncClipboardPasteShortcut } from "@/components/browserStreamClipboard";import "./browser-stream.css";@@ -216,6 +217,7 @@ function BrowserStream({setCanvasContainer(node);}, []);const rfbRef = useRef<RFB | null>(null);+ const userCanSendVncInputRef = useRef(false);const observerRef = useRef<MutationObserver | null>(null);const clientId = useClientIdStore((state) => state.clientId);const recordingStore = useRecordingStore();@@ -633,6 +635,32 @@ function BrowserStream({}}, [interactive]);+ const theUserIsControlling =+ userIsControlling || (interactive && !showControlButtons);++ useEffect(() => {+ userCanSendVncInputRef.current = theUserIsControlling;+ }, [theUserIsControlling]);++ useEffect(() => {+ if (!canvasContainer) {+ return;+ }++ const handleKeyDown = (event: KeyboardEvent) => {+ if (!userCanSendVncInputRef.current) {+ return;+ }++ void handleVncClipboardPasteShortcut(event, rfbRef.current);+ };++ canvasContainer.addEventListener("keydown", handleKeyDown, true);+ return () => {+ canvasContainer.removeEventListener("keydown", handleKeyDown, true);+ };+ }, [canvasContainer]);+// effect to ensure the recordingStore is reset when the component unmountsuseEffect(() => {return () => {@@ -767,7 +795,7 @@ function BrowserStream({toast({title: "Pasting Into Browser",description:- "Pasting your current clipboard text into the web page. NOTE: copy-paste only works in the web page - not in the browser (like the address bar).",+ "Pasting your current clipboard text into the browser.",});const response: MessageOutAskForClipboardResponse = {@@ -791,8 +819,7 @@ function BrowserStream({if (success) {toast({title: "Copied to Clipboard",- description:- "The text has been copied to your clipboard. NOTE: copy-paste only works in the web page - not in the browser (like the address bar).",+ description: "The text has been copied to your clipboard.",});} else {toast({@@ -825,8 +852,6 @@ function BrowserStream({}};- const theUserIsControlling =- userIsControlling || (interactive && !showControlButtons);const streamDiagnostic: StreamDiagnostic =!showStream || !runId? {diff --git a/skyvern-frontend/src/components/browserStreamClipboard.test.ts b/skyvern-frontend/src/components/browserStreamClipboard.test.tsnew file mode 100644index 000000000..17b4b7c02--- /dev/null+++ b/skyvern-frontend/src/components/browserStreamClipboard.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it, vi } from "vitest";++import {+ handleVncClipboardPasteShortcut,+ isClipboardPasteShortcut,+ sendVncPasteShortcut,+ type PasteShortcutEvent,+ type VncClipboardRfb,+} from "./browserStreamClipboard";++function pasteEvent(overrides: Partial<PasteShortcutEvent> = {}) {+ return {+ altKey: false,+ ctrlKey: true,+ key: "v",+ metaKey: false,+ preventDefault: vi.fn(),+ shiftKey: false,+ stopImmediatePropagation: vi.fn(),+ stopPropagation: vi.fn(),+ ...overrides,+ } satisfies PasteShortcutEvent;+}++function rfbMock() {+ return {+ clipboardPasteFrom: vi.fn(),+ sendKey: vi.fn(),+ } satisfies VncClipboardRfb;+}++describe("browserStreamClipboard", () => {+ it("detects Ctrl+V and Cmd+V paste shortcuts", () => {+ expect(isClipboardPasteShortcut(pasteEvent({ ctrlKey: true }))).toBe(true);+ expect(+ isClipboardPasteShortcut(pasteEvent({ ctrlKey: false, metaKey: true })),+ ).toBe(true);+ });++ it("ignores non-paste shortcuts", () => {+ expect(isClipboardPasteShortcut(pasteEvent({ ctrlKey: false }))).toBe(+ false,+ );+ expect(isClipboardPasteShortcut(pasteEvent({ altKey: true }))).toBe(false);+ expect(isClipboardPasteShortcut(pasteEvent({ shiftKey: true }))).toBe(true);+ expect(isClipboardPasteShortcut(pasteEvent({ key: "c" }))).toBe(false);+ });++ it("sends a remote Ctrl+V sequence", () => {+ const rfb = rfbMock();++ sendVncPasteShortcut(rfb);++ expect(rfb.sendKey).toHaveBeenNthCalledWith(1, 0xffe3, "ControlLeft", true);+ expect(rfb.sendKey).toHaveBeenNthCalledWith(2, 0x0076, "KeyV", true);+ expect(rfb.sendKey).toHaveBeenNthCalledWith(3, 0x0076, "KeyV", false);+ expect(rfb.sendKey).toHaveBeenNthCalledWith(+ 4,+ 0xffe3,+ "ControlLeft",+ false,+ );+ });++ it("syncs local clipboard text to VNC before sending paste", async () => {+ const event = pasteEvent();+ const rfb = rfbMock();++ await handleVncClipboardPasteShortcut(+ event,+ rfb,+ async () => "https://example.test",+ 0,+ );++ expect(event.preventDefault).toHaveBeenCalledOnce();+ expect(event.stopPropagation).toHaveBeenCalledOnce();+ expect(event.stopImmediatePropagation).toHaveBeenCalledOnce();+ expect(rfb.clipboardPasteFrom).toHaveBeenCalledWith("https://example.test");+ expect(rfb.sendKey).toHaveBeenCalledTimes(4);+ });++ it("does not send stale VNC clipboard contents when browser clipboard read fails", async () => {+ const event = pasteEvent();+ const rfb = rfbMock();++ await expect(+ handleVncClipboardPasteShortcut(+ event,+ rfb,+ async () => {+ throw new Error("denied");+ },+ 0,+ ),+ ).resolves.toBe(true);++ expect(event.preventDefault).toHaveBeenCalledOnce();+ expect(rfb.clipboardPasteFrom).not.toHaveBeenCalled();+ expect(rfb.sendKey).not.toHaveBeenCalled();+ });++ it("does not intercept non-paste keys", async () => {+ const event = pasteEvent({ key: "x" });+ const rfb = rfbMock();++ await expect(+ handleVncClipboardPasteShortcut(event, rfb, async () => "ignored"),+ ).resolves.toBe(false);++ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(rfb.clipboardPasteFrom).not.toHaveBeenCalled();+ expect(rfb.sendKey).not.toHaveBeenCalled();+ });+});diff --git a/skyvern-frontend/src/components/browserStreamClipboard.ts b/skyvern-frontend/src/components/browserStreamClipboard.tsnew file mode 100644index 000000000..4c77479ed--- /dev/null+++ b/skyvern-frontend/src/components/browserStreamClipboard.ts@@ -0,0 +1,76 @@+export interface VncClipboardRfb {+ clipboardPasteFrom(text: string): void;+ sendKey(keysym: number, code: string, down?: boolean): void;+}++export type PasteShortcutEvent = Pick<+ KeyboardEvent,+ | "altKey"+ | "ctrlKey"+ | "key"+ | "metaKey"+ | "preventDefault"+ | "shiftKey"+ | "stopImmediatePropagation"+ | "stopPropagation"+>;++const VNC_CONTROL_LEFT_KEYSYM = 0xffe3;+const VNC_V_KEYSYM = 0x0076;+const DEFAULT_VNC_CLIPBOARD_SYNC_DELAY_MS = 50;++function sleep(ms: number) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function isClipboardPasteShortcut(event: PasteShortcutEvent) {+ // Ctrl+Shift+V is paste-without-formatting in many browser inputs. We only+ // exclude Alt-based shortcuts to match the backend RFB paste detection.+ return (+ (event.ctrlKey || event.metaKey) &&+ !event.altKey &&+ event.key.toLowerCase() === "v"+ );+}++function sendVncPasteShortcut(rfb: VncClipboardRfb) {+ rfb.sendKey(VNC_CONTROL_LEFT_KEYSYM, "ControlLeft", true);+ rfb.sendKey(VNC_V_KEYSYM, "KeyV", true);+ rfb.sendKey(VNC_V_KEYSYM, "KeyV", false);+ rfb.sendKey(VNC_CONTROL_LEFT_KEYSYM, "ControlLeft", false);+}++async function handleVncClipboardPasteShortcut(+ event: PasteShortcutEvent,+ rfb: VncClipboardRfb | null,+ readClipboardText = () => navigator.clipboard.readText(),+ syncDelayMs = DEFAULT_VNC_CLIPBOARD_SYNC_DELAY_MS,+) {+ if (!rfb || !isClipboardPasteShortcut(event)) {+ return false;+ }++ event.preventDefault();+ event.stopPropagation();+ event.stopImmediatePropagation();++ try {+ const text = await readClipboardText();+ rfb.clipboardPasteFrom(text);+ if (syncDelayMs > 0) {+ await sleep(syncDelayMs);+ }+ } catch (err) {+ console.error("Failed to sync clipboard contents to VNC:", err);+ return true;+ }++ sendVncPasteShortcut(rfb);+ return true;+}++export {+ handleVncClipboardPasteShortcut,+ isClipboardPasteShortcut,+ sendVncPasteShortcut,+};diff --git a/skyvern-frontend/src/novnc.d.ts b/skyvern-frontend/src/novnc.d.tsindex 68706d6ee..813f4cc5d 100644--- a/skyvern-frontend/src/novnc.d.ts+++ b/skyvern-frontend/src/novnc.d.ts@@ -33,7 +33,9 @@ declare module "@novnc/novnc/lib/rfb.js" {addEventListener(event: string, listener: (e: RfbEvent) => void): void;removeEventListener(event: string, listener: (e: RfbEvent) => void): void;+ clipboardPasteFrom(text: string): void;disconnect(): void;+ sendKey(keysym: number, code: string, down?: boolean): void;viewportChange(): void;}}diff --git a/skyvern/forge/sdk/routes/streaming/channels/vnc.py b/skyvern/forge/sdk/routes/streaming/channels/vnc.pyindex 809887bb7..fa447e201 100644--- a/skyvern/forge/sdk/routes/streaming/channels/vnc.py+++ b/skyvern/forge/sdk/routes/streaming/channels/vnc.py@@ -18,6 +18,7 @@ Channel data:import asyncioimport dataclasses+import timeimport typing as tfrom enum import IntEnumfrom urllib.parse import urlparse@@ -70,6 +71,10 @@ Loops = list[asyncio.Task] # aka "queue-less actors"; or "programs"class MessageType(IntEnum):Keyboard = 4Mouse = 5+ ClientCutText = 6+++REMOTE_CLIPBOARD_SYNC_PASTE_GRACE_SECONDS = 2.0class Keys:@@ -162,6 +167,7 @@ class VncChannel:browser_session: AddressablePersistentBrowserSession | None = Nonekey_state: KeyState = dataclasses.field(default_factory=KeyState)+ remote_clipboard_synced_at: float | None = Nonetask: Task | None = Noneworkflow_run: WorkflowRun | None = None@@ -239,6 +245,14 @@ class VncChannel:elif data == Keys.Up.Cmd:self.key_state.cmd_is_down = False+ def mark_remote_clipboard_synced(self) -> None:+ self.remote_clipboard_synced_at = time.monotonic()++ def remote_clipboard_was_recently_synced(self) -> bool:+ if self.remote_clipboard_synced_at is None:+ return False+ return time.monotonic() - self.remote_clipboard_synced_at <= REMOTE_CLIPBOARD_SYNC_PASTE_GRACE_SECONDS+async def copy_text(vnc_channel: VncChannel) -> None:class_name = vnc_channel.class_name@@ -384,12 +398,18 @@ async def loop_stream_vnc(vnc_channel: VncChannel) -> None:if vnc_channel.key_state.is_copy(data):await copy_text(vnc_channel)- if vnc_channel.key_state.is_paste(data):+ if (+ vnc_channel.key_state.is_paste(data)+ and not vnc_channel.remote_clipboard_was_recently_synced()+ ):await ask_for_clipboard(vnc_channel)if vnc_channel.key_state.is_forbidden(data):continue+ if message_type == MessageType.ClientCutText.value:+ vnc_channel.mark_remote_clipboard_synced()+# prevent right-mouse-button clicks for "security" reasonsif message_type == MessageType.Mouse.value:if Mouse.Up.Right(data):diff --git a/tests/unit/forge/sdk/routes/streaming/test_vnc_clipboard.py b/tests/unit/forge/sdk/routes/streaming/test_vnc_clipboard.pynew file mode 100644index 000000000..6ba8dd0e4--- /dev/null+++ b/tests/unit/forge/sdk/routes/streaming/test_vnc_clipboard.py@@ -0,0 +1,56 @@+from __future__ import annotations++import pytest++from skyvern.forge.sdk.routes.streaming.channels import vnc as vnc_module+from skyvern.forge.sdk.routes.streaming.channels.vnc import (+ REMOTE_CLIPBOARD_SYNC_PASTE_GRACE_SECONDS,+ MessageType,+ VncChannel,+)+++def make_vnc_channel() -> VncChannel:+ channel = object.__new__(VncChannel)+ channel.remote_clipboard_synced_at = None+ return channel+++def test_client_cut_text_message_type_matches_rfb_protocol() -> None:+ assert MessageType.ClientCutText.value == 6+++def test_remote_clipboard_recently_synced_guard(monkeypatch: pytest.MonkeyPatch) -> None:+ channel = make_vnc_channel()++ monkeypatch.setattr(vnc_module.time, "monotonic", lambda: 10.0)+ channel.mark_remote_clipboard_synced()++ monkeypatch.setattr(+ vnc_module.time,+ "monotonic",+ lambda: 10.0 + REMOTE_CLIPBOARD_SYNC_PASTE_GRACE_SECONDS - 0.1,+ )++ assert channel.remote_clipboard_was_recently_synced() is True+++def test_remote_clipboard_sync_guard_expires(monkeypatch: pytest.MonkeyPatch) -> None:+ channel = make_vnc_channel()++ monkeypatch.setattr(vnc_module.time, "monotonic", lambda: 10.0)+ channel.mark_remote_clipboard_synced()++ monkeypatch.setattr(+ vnc_module.time,+ "monotonic",+ lambda: 10.0 + REMOTE_CLIPBOARD_SYNC_PASTE_GRACE_SECONDS + 0.1,+ )++ assert channel.remote_clipboard_was_recently_synced() is False+++def test_remote_clipboard_sync_guard_defaults_to_false() -> None:+ channel = make_vnc_channel()++ assert channel.remote_clipboard_was_recently_synced() is False