Skip to content

Automate browser based workflows with AI

fix(SKY-11252): contain block library drawer (#6721)

Aaron Perez8206da4f5058
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index 8a4fa1b8a..62b882b8c 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -354,7 +354,9 @@ function Workspace({
? frozenSidebarOpenRef.current
: blockSidebarOpen
: false;
- const blockSidebarWidth = useBlockSidebarWidthStore((s) => s.width);
+ const renderedBlockSidebarWidth = useBlockSidebarWidthStore(
+ (s) => s.renderedWidth,
+ );
const handleOnSave = useSaveWorkflow();
const postHog = usePostHog();
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
@@ -1418,7 +1420,7 @@ function Workspace({
className="relative h-full w-full"
style={
{
- [BLOCK_SIDEBAR_WIDTH_VAR]: `${blockSidebarWidth}px`,
+ [BLOCK_SIDEBAR_WIDTH_VAR]: `${renderedBlockSidebarWidth}px`,
} as React.CSSProperties
}
>
diff --git a/skyvern-frontend/src/routes/workflows/editor/blockSidebar.test.ts b/skyvern-frontend/src/routes/workflows/editor/blockSidebar.test.ts
index 0efce1a4f..d4dc139af 100644
--- a/skyvern-frontend/src/routes/workflows/editor/blockSidebar.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/blockSidebar.test.ts
@@ -1,4 +1,6 @@
-import { describe, expect, test } from "vitest";
+// @vitest-environment jsdom
+
+import { afterEach, describe, expect, test } from "vitest";
import {
isBlockSidebarOpen,
@@ -6,8 +8,14 @@ import {
HEADER_RIGHT_INSET_OPEN,
BLOCK_SIDEBAR_WIDTH_VAR,
BLOCK_SIDEBAR_RIGHT_GAP,
+ getBlockSidebarGutterPx,
+ getContainedBlockSidebarWidth,
} from "./blockSidebar";
+afterEach(() => {
+ document.documentElement.style.fontSize = "";
+});
+
describe("isBlockSidebarOpen", () => {
test("returns true when in edit mode with a selected block", () => {
expect(isBlockSidebarOpen("edit", "block-123")).toBe(true);
@@ -54,3 +62,22 @@ describe("right-inset class constants", () => {
expect(BLOCK_SIDEBAR_RIGHT_GAP).toBe("1.5rem");
});
});
+
+describe("getContainedBlockSidebarWidth", () => {
+ test("returns the requested numeric width when the editor shell is unmeasured", () => {
+ expect(getContainedBlockSidebarWidth(640, null)).toBe(640);
+ });
+
+ test("clamps to the editor shell gutter when measured", () => {
+ expect(getContainedBlockSidebarWidth(640, 500)).toBe(452);
+ });
+
+ test("derives the gutter from the document root font size", () => {
+ document.documentElement.style.fontSize = "20px";
+
+ const gutterPx = getBlockSidebarGutterPx(document.documentElement);
+
+ expect(gutterPx).toBe(60);
+ expect(getContainedBlockSidebarWidth(640, 500, gutterPx)).toBe(440);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/blockSidebar.ts b/skyvern-frontend/src/routes/workflows/editor/blockSidebar.ts
index c6a0ac59a..c151e78db 100644
--- a/skyvern-frontend/src/routes/workflows/editor/blockSidebar.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/blockSidebar.ts
@@ -2,11 +2,58 @@ import type { WorkflowEditorMode } from "./hooks/useWorkflowEditorMode";
export const BLOCK_SIDEBAR_WIDTH_VAR = "--block-sidebar-w";
export const BLOCK_SIDEBAR_RIGHT_GAP = "1.5rem";
+export const BLOCK_SIDEBAR_HORIZONTAL_GUTTER = "3rem";
+const DEFAULT_ROOT_FONT_SIZE_PX = 16;
export const HEADER_RIGHT_INSET_CLOSED = "right-6";
export const HEADER_RIGHT_INSET_OPEN =
"right-[calc(var(--block-sidebar-w)+3rem)]";
+function parseRemValue(value: string): number | null {
+ if (!value.endsWith("rem")) {
+ return null;
+ }
+
+ const rem = Number.parseFloat(value);
+ return Number.isFinite(rem) && rem > 0 ? rem : null;
+}
+
+export function getBlockSidebarGutterPx(element: HTMLElement | null): number {
+ const rem = parseRemValue(BLOCK_SIDEBAR_HORIZONTAL_GUTTER) ?? 3;
+ // The CSS inset uses rems; derive the numeric Resizable gutter from the
+ // active root font size so browser/user scaling keeps both paths in sync.
+ const ownerDocument =
+ element?.ownerDocument ??
+ (typeof document === "undefined" ? null : document);
+ const rootFontSize = ownerDocument?.defaultView?.getComputedStyle(
+ ownerDocument.documentElement,
+ ).fontSize;
+ const rootFontSizePx = Number.parseFloat(rootFontSize ?? "");
+
+ return (
+ rem *
+ (Number.isFinite(rootFontSizePx)
+ ? rootFontSizePx
+ : DEFAULT_ROOT_FONT_SIZE_PX)
+ );
+}
+
+export function getContainedBlockSidebarWidth(
+ widthPx: number,
+ containerWidthPx: number | null,
+ gutterPx: number = getBlockSidebarGutterPx(null),
+): number {
+ const roundedWidth = Math.max(0, Math.round(widthPx));
+ if (containerWidthPx === null || containerWidthPx <= 0) {
+ return roundedWidth;
+ }
+
+ // Parent shell clips overflow, so keep persisted widths contained before
+ // they reach re-resizable (which only supports numeric px constraints).
+ const containedMaxWidth = Math.max(0, containerWidthPx - gutterPx);
+ return Math.min(roundedWidth, containedMaxWidth);
+}
+
export function isBlockSidebarOpen(
mode: WorkflowEditorMode,
selectedBlockId: string | null,
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.test.tsx
index dc782fd49..afd464050 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.test.tsx
@@ -77,10 +77,15 @@ vi.mock("@xyflow/react", async () => {
});
import { useSidebarSaveStateStore } from "@/store/SidebarSaveStateStore";
+import {
+ BLOCK_SIDEBAR_WIDTH_MAX,
+ useBlockSidebarWidthStore,
+} from "@/store/BlockSidebarWidthStore";
import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";
import { BLOCK_FORMS, type WorkflowBlockNodeType } from "./BlockConfigForm";
import { BlockConfigSidebar } from "./BlockConfigSidebar";
+import { getContainedBlockSidebarWidth } from "../blockSidebar";
// EditableNodeTitle (used by the editable block title) measures truncation
// via ResizeObserver, which jsdom does not implement. Stubbed per-test in
@@ -112,6 +117,11 @@ const StubFormForBlockType: (
beforeEach(() => {
vi.stubGlobal("ResizeObserver", ResizeObserverStub);
useWorkflowPanelStore.getState().setSelectedBlockId(null);
+ useWorkflowPanelStore.getState().setWorkflowPanelState({
+ active: false,
+ content: "parameters",
+ });
+ useBlockSidebarWidthStore.getState().reset();
for (const key of BLOCK_FORM_KEYS) {
BLOCK_FORMS[key] = StubFormForBlockType(key);
}
@@ -262,6 +272,95 @@ describe("BlockConfigSidebar mode gating (SKY-9361)", () => {
});
});
+describe("BlockConfigSidebar block library layout (contained drawer)", () => {
+ test("constrains the persisted sidebar width to the editor canvas gutter with numeric resize bounds", () => {
+ const getBoundingClientRect = vi
+ .spyOn(HTMLElement.prototype, "getBoundingClientRect")
+ .mockImplementation(function (this: HTMLElement) {
+ if (this.dataset.testid === "editor-shell") {
+ return {
+ width: 500,
+ height: 800,
+ top: 0,
+ right: 500,
+ bottom: 800,
+ left: 0,
+ x: 0,
+ y: 0,
+ toJSON: () => {},
+ };
+ }
+
+ return {
+ width: 0,
+ height: 0,
+ top: 0,
+ right: 0,
+ bottom: 0,
+ left: 0,
+ x: 0,
+ y: 0,
+ toJSON: () => {},
+ };
+ });
+
+ try {
+ act(() => {
+ useBlockSidebarWidthStore.getState().setWidth(BLOCK_SIDEBAR_WIDTH_MAX);
+ useWorkflowPanelStore.getState().setWorkflowPanelState({
+ active: true,
+ content: "nodeLibrary",
+ });
+ });
+
+ render(
+ <MemoryRouter initialEntries={["/workflows/wpid_abc/edit"]}>
+ <div data-testid="editor-shell">
+ <BlockConfigSidebar />
+ </div>
+ </MemoryRouter>,
+ );
+
+ const sidebarRoot = screen.getByTestId(
+ "block-config-sidebar",
+ ).parentElement;
+
+ expect(getContainedBlockSidebarWidth(BLOCK_SIDEBAR_WIDTH_MAX, 500)).toBe(
+ 452,
+ );
+ expect(sidebarRoot?.style.width).toBe("452px");
+ expect(sidebarRoot?.style.minWidth).toBe("320px");
+ expect(sidebarRoot?.style.maxWidth).toBe("452px");
+ expect(sidebarRoot?.style.cssText).not.toContain("min(");
+ expect(useBlockSidebarWidthStore.getState().renderedWidth).toBe(452);
+ } finally {
+ getBoundingClientRect.mockRestore();
+ }
+ });
+
+ test("lets block-library item labels shrink inside the bounded drawer", () => {
+ act(() => {
+ useWorkflowPanelStore.getState().setWorkflowPanelState({
+ active: true,
+ content: "nodeLibrary",
+ });
+ });
+
+ render(
+ <MemoryRouter initialEntries={["/workflows/wpid_abc/edit"]}>
+ <BlockConfigSidebar />
+ </MemoryRouter>,
+ );
+
+ const item = screen.getByTestId("block-library-item-login");
+ const title = screen.getByText("Login Block");
+
+ expect(item.className).toContain("min-w-0");
+ expect(title.parentElement?.className).toContain("min-w-0");
+ expect(title.className).toContain("min-w-0");
+ });
+});
+
describe("BlockConfigSidebar block title editing (SKY-10255)", () => {
beforeEach(() => {
mockLabelChangeHandler.mockClear();
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx
index 7eb0d7513..6e1acce28 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx
@@ -1,7 +1,7 @@
import { Cross2Icon, GearIcon, PlusIcon } from "@radix-ui/react-icons";
import { useNodesData, useReactFlow } from "@xyflow/react";
import { Resizable } from "re-resizable";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import {
BLOCK_SIDEBAR_WIDTH_MAX,
@@ -22,6 +22,10 @@ import { isStartNode } from "../nodes/StartNode/types";
import { WorkflowBlockIcon } from "../nodes/WorkflowBlockIcon";
import { workflowBlockTitle } from "../nodes/types";
import { WorkflowBlockType } from "../../types/workflowTypes";
+import {
+ getBlockSidebarGutterPx,
+ getContainedBlockSidebarWidth,
+} from "../blockSidebar";
import { BlockConfigForm } from "./BlockConfigForm";
import { useHasInteractedThisSession } from "./useHasInteractedThisSession";
import { WorkflowNodeLibraryPanel } from "./WorkflowNodeLibraryPanel";
@@ -77,6 +81,19 @@ function getBlockTypeFromNode(node: AppNode): WorkflowBlockType | null {
const FOOTER_TICK_INTERVAL_MS = 10_000;
+function measureElementWidth(element: HTMLElement): number | null {
+ const boundingWidth = element.getBoundingClientRect().width;
+ if (boundingWidth > 0) {
+ return boundingWidth;
+ }
+
+ if (element.offsetWidth > 0) {
+ return element.offsetWidth;
+ }
+
+ return null;
+}
+
function formatUpdatedAgo(updatedAt: number, now: number): string {
const elapsedSec = Math.max(0, Math.floor((now - updatedAt) / 1000));
if (elapsedSec < 60) {
@@ -271,7 +288,7 @@ function BlockLibrarySidebarBody({
<Cross2Icon className="h-4 w-4" />
</button>
</header>
- <div className="flex-1 overflow-hidden px-5 py-4">
+ <div className="flex min-h-0 flex-1 overflow-hidden px-5 py-4">
<WorkflowNodeLibraryPanel onNodeClick={onAddNode} />
</div>
</>
@@ -283,8 +300,14 @@ type BlockConfigSidebarProps = {
};
function BlockConfigSidebar({ onAddNode }: BlockConfigSidebarProps) {
+ const resizableRef = useRef<Resizable | null>(null);
+ const [editorShellMetrics, setEditorShellMetrics] = useState(() => ({
+ gutterPx: getBlockSidebarGutterPx(null),
+ width: null as number | null,
+ }));
const width = useBlockSidebarWidthStore((s) => s.width);
const setWidth = useBlockSidebarWidthStore((s) => s.setWidth);
+ const setRenderedWidth = useBlockSidebarWidthStore((s) => s.setRenderedWidth);
const mode = useWorkflowEditorMode();
const selectedBlockId = useWorkflowPanelStore(
(state) => state.selectedBlockId,
@@ -299,6 +322,20 @@ function BlockConfigSidebar({ onAddNode }: BlockConfigSidebarProps) {
(state) => state.closeWorkflowPanel,
);
const flushPendingCommit = usePendingCommitsStore((state) => state.flush);
+ const containedWidth = getContainedBlockSidebarWidth(
+ width,
+ editorShellMetrics.width,
+ editorShellMetrics.gutterPx,
+ );
+ const containedMaxWidth = getContainedBlockSidebarWidth(
+ BLOCK_SIDEBAR_WIDTH_MAX,
+ editorShellMetrics.width,
+ editorShellMetrics.gutterPx,
+ );
+ const containedMinWidth = Math.min(
+ BLOCK_SIDEBAR_WIDTH_MIN,
+ containedMaxWidth,
+ );
// Auto-commit on block switch. When `selectedBlockId` flips
// from A → B, flush any pending commit registered by the dispatcher
@@ -317,6 +354,62 @@ function BlockConfigSidebar({ onAddNode }: BlockConfigSidebarProps) {
const showLibrary =
workflowPanelState.active && workflowPanelState.content === "nodeLibrary";
+ const sidebarVisible =
+ showLibrary || (mode !== "build" && selectedBlockId !== null);
+
+ useLayoutEffect(() => {
+ if (!sidebarVisible) {
+ setEditorShellMetrics({
+ gutterPx: getBlockSidebarGutterPx(null),
+ width: null,
+ });
+ return;
+ }
+
+ const parentElement = resizableRef.current?.resizable?.parentElement;
+ if (parentElement === undefined || parentElement === null) {
+ setEditorShellMetrics({
+ gutterPx: getBlockSidebarGutterPx(null),
+ width: null,
+ });
+ return;
+ }
+
+ const updateEditorShellMetrics = () => {
+ setEditorShellMetrics({
+ gutterPx: getBlockSidebarGutterPx(parentElement),
+ width: measureElementWidth(parentElement),
+ });
+ };
+
+ updateEditorShellMetrics();
+
+ if (typeof ResizeObserver === "undefined") {
+ if (typeof window === "undefined") {
+ return;
+ }
+
+ window.addEventListener("resize", updateEditorShellMetrics);
+ return () => {
+ window.removeEventListener("resize", updateEditorShellMetrics);
+ };
+ }
+
+ const resizeObserver = new ResizeObserver(updateEditorShellMetrics);
+ resizeObserver.observe(parentElement);
+
+ return () => {
+ resizeObserver.disconnect();
+ };
+ }, [sidebarVisible]);
+
+ useLayoutEffect(() => {
+ if (!sidebarVisible) {
+ return;
+ }
+
+ setRenderedWidth(containedWidth);
+ }, [containedWidth, setRenderedWidth, sidebarVisible]);
// In build mode the block-config form is unavailable, but the node library
// must still render so users can insert blocks from the canvas.
@@ -330,12 +423,13 @@ function BlockConfigSidebar({ onAddNode }: BlockConfigSidebarProps) {
return (
<Resizable
- size={{ width, height: "auto" }}
- minWidth={BLOCK_SIDEBAR_WIDTH_MIN}
- maxWidth={BLOCK_SIDEBAR_WIDTH_MAX}
+ ref={resizableRef}
+ size={{ width: containedWidth, height: "auto" }}
+ minWidth={containedMinWidth}
+ maxWidth={containedMaxWidth}
enable={{ left: true }}
- onResizeStop={(_e, _dir, _ref, delta) => {
- setWidth(width + delta.width);
+ onResizeStop={(_e, _dir, ref) => {
+ setWidth(ref.offsetWidth);
}}
handleClasses={{ left: "block-sidebar-resize-handle" }}
handleStyles={{
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx
index 2e25e4057..0a5303eba 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx
@@ -373,7 +373,7 @@ function WorkflowNodeLibraryPanel({ onNodeClick }: Props) {
});
return (
- <div className="flex h-full flex-col gap-4">
+ <div className="flex h-full min-h-0 min-w-0 flex-col gap-4">
<div className="relative">
<div className="absolute left-0 top-0 flex size-9 items-center justify-center">
<MagnifyingGlassIcon className="size-5" />
@@ -390,15 +390,18 @@ function WorkflowNodeLibraryPanel({ onNodeClick }: Props) {
tabIndex={0}
/>
</div>
- <ScrollArea className="h-full flex-1">
- <ScrollAreaViewport className="h-full">
+ <ScrollArea className="min-h-0 min-w-0 flex-1">
+ {/* Radix wraps viewport children in a display:table div by default;
+ override it so narrow sidebar rows can shrink instead of widening the
+ clipped editor shell. */}
+ <ScrollAreaViewport className="h-full w-full [&>div]:!block [&>div]:!overflow-x-hidden">
<div className="space-y-2">
{filteredItems.length > 0 ? (
filteredItems.map((item) => (
<div
key={item.nodeType}
data-testid={`block-library-item-${item.nodeType}`}
- className="flex cursor-pointer items-center justify-between rounded-sm bg-slate-elevation4 p-4 hover:bg-slate-elevation5"
+ className="flex min-w-0 cursor-pointer items-center justify-between rounded-sm bg-slate-elevation4 p-4 hover:bg-slate-elevation5"
onClick={() => {
onNodeClick({
nodeType: item.nodeType,
@@ -413,15 +416,15 @@ function WorkflowNodeLibraryPanel({ onNodeClick }: Props) {
closeWorkflowPanel();
}}
>
- <div className="flex gap-2">
+ <div className="flex min-w-0 gap-2">
<div className="flex h-[2.75rem] w-[2.75rem] shrink-0 items-center justify-center rounded border border-slate-600">
{item.icon}
</div>
- <div className="flex flex-col gap-1">
- <span className="max-w-64 truncate text-base">
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="min-w-0 truncate text-base">
{item.title}
</span>
- <span className="text-xs text-slate-600 dark:text-slate-400">
+ <span className="min-w-0 truncate text-xs text-slate-600 dark:text-slate-400">
{item.description}
</span>
</div>
diff --git a/skyvern-frontend/src/store/BlockSidebarWidthStore.test.ts b/skyvern-frontend/src/store/BlockSidebarWidthStore.test.ts
index d3972e9a3..fc1416fcc 100644
--- a/skyvern-frontend/src/store/BlockSidebarWidthStore.test.ts
+++ b/skyvern-frontend/src/store/BlockSidebarWidthStore.test.ts
@@ -20,6 +20,9 @@ describe("BlockSidebarWidthStore", () => {
expect(useBlockSidebarWidthStore.getState().width).toBe(
BLOCK_SIDEBAR_WIDTH_DEFAULT,
);
+ expect(useBlockSidebarWidthStore.getState().renderedWidth).toBe(
+ BLOCK_SIDEBAR_WIDTH_DEFAULT,
+ );
});
test("setWidth clamps to [MIN, MAX]", () => {
@@ -43,6 +46,15 @@ describe("BlockSidebarWidthStore", () => {
expect(JSON.parse(raw!)).toMatchObject({ state: { width: 420 } });
});
+ test("setRenderedWidth tracks the measured width without persisting it", () => {
+ useBlockSidebarWidthStore.getState().setRenderedWidth(452);
+
+ expect(useBlockSidebarWidthStore.getState().renderedWidth).toBe(452);
+ const raw = localStorage.getItem(BLOCK_SIDEBAR_WIDTH_STORAGE_KEY);
+ expect(raw).not.toBeNull();
+ expect(JSON.parse(raw!).state).not.toHaveProperty("renderedWidth");
+ });
+
test("reset returns width to default and clears persistence", () => {
const store = useBlockSidebarWidthStore.getState();
store.setWidth(420);
@@ -50,6 +62,9 @@ describe("BlockSidebarWidthStore", () => {
expect(useBlockSidebarWidthStore.getState().width).toBe(
BLOCK_SIDEBAR_WIDTH_DEFAULT,
);
+ expect(useBlockSidebarWidthStore.getState().renderedWidth).toBe(
+ BLOCK_SIDEBAR_WIDTH_DEFAULT,
+ );
});
test("constants form a sane range", () => {
diff --git a/skyvern-frontend/src/store/BlockSidebarWidthStore.ts b/skyvern-frontend/src/store/BlockSidebarWidthStore.ts
index 125e7318d..8b4b57f0c 100644
--- a/skyvern-frontend/src/store/BlockSidebarWidthStore.ts
+++ b/skyvern-frontend/src/store/BlockSidebarWidthStore.ts
@@ -8,7 +8,9 @@ export const BLOCK_SIDEBAR_WIDTH_STORAGE_KEY = "skyvern.blockSidebarWidth";
type BlockSidebarWidthStore = {
width: number;
+ renderedWidth: number;
setWidth: (next: number) => void;
+ setRenderedWidth: (next: number) => void;
reset: () => void;
};
@@ -20,12 +22,24 @@ function clamp(n: number): number {
);
}
+function normalizeRenderedWidth(n: number): number {
+ if (!Number.isFinite(n)) return BLOCK_SIDEBAR_WIDTH_DEFAULT;
+ return Math.max(0, n);
+}
+
const useBlockSidebarWidthStore = create<BlockSidebarWidthStore>()(
persist(
(set) => ({
width: BLOCK_SIDEBAR_WIDTH_DEFAULT,
+ renderedWidth: BLOCK_SIDEBAR_WIDTH_DEFAULT,
setWidth: (next) => set({ width: clamp(next) }),
- reset: () => set({ width: BLOCK_SIDEBAR_WIDTH_DEFAULT }),
+ setRenderedWidth: (next) =>
+ set({ renderedWidth: normalizeRenderedWidth(next) }),
+ reset: () =>
+ set({
+ width: BLOCK_SIDEBAR_WIDTH_DEFAULT,
+ renderedWidth: BLOCK_SIDEBAR_WIDTH_DEFAULT,
+ }),
}),
{
name: BLOCK_SIDEBAR_WIDTH_STORAGE_KEY,
diff --git a/skyvern/cli/commands/browser.py b/skyvern/cli/commands/browser.py
index 8a413178b..37a57748d 100644
--- a/skyvern/cli/commands/browser.py
+++ b/skyvern/cli/commands/browser.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import json
import subprocess
+import sys
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
@@ -251,7 +252,20 @@ def session_close(
skyvern = get_skyvern()
result = await do_session_close(skyvern, connection.session_id)
clear_state()
- return {"session_id": result.session_id, "closed": result.closed}
+
+ # Best-effort fetch of recording data after close
+ recording_data: dict = {}
+ try:
+ resolved = await skyvern.get_browser_session(connection.session_id)
+ recording_data = {
+ "app_url": resolved.app_url,
+ "recordings": [{"url": r.url, "filename": r.filename} for r in (resolved.recordings or [])],
+ "downloaded_files": [{"url": f.url, "filename": f.filename} for f in (resolved.downloaded_files or [])],
+ }
+ except Exception:
+ pass
+
+ return {"session_id": result.session_id, "closed": result.closed, **recording_data}
try:
data = asyncio.run(_run())
@@ -343,6 +357,8 @@ def session_get(
resolved = await skyvern.get_browser_session(session)
state = load_state()
is_current = bool(state and state.mode == "cloud" and state.session_id == session)
+ recordings = [{"url": r.url, "filename": r.filename} for r in (resolved.recordings or [])]
+ downloaded_files = [{"url": f.url, "filename": f.filename} for f in (resolved.downloaded_files or [])]
return {
"session_id": resolved.browser_session_id,
"status": resolved.status,
@@ -351,6 +367,9 @@ def session_get(
"timeout": resolved.timeout,
"runnable_id": resolved.runnable_id,
"is_current": is_current,
+ "app_url": resolved.app_url,
+ "recordings": recordings,
+ "downloaded_files": downloaded_files,
}
try:
@@ -2286,3 +2305,122 @@ def clipboard_write_cmd(
except Exception as e:
capture_cli_tool_call("skyvern_clipboard_write", ok=False, error=e)
output_error(str(e), json_mode=json_output)
+
+
+# ---------------------------------------------------------------------------
+# QA command — single-prompt QA with recording
+# ---------------------------------------------------------------------------
+
+
+@browser_app.command("qa")
+def qa(
+ prompt: str = typer.Argument(..., help="Natural language QA task to perform."),
+ url: str | None = typer.Option(None, help="URL to navigate to before running."),
+ timeout: int = typer.Option(15, help="Session timeout in minutes."),
+ max_steps: int | None = typer.Option(None, "--max-steps", min=1, help="Maximum number of agent steps."),
+ task_timeout: int = typer.Option(180, "--task-timeout", min=10, max=1800, help="Task timeout in seconds."),
+ proxy: str | None = typer.Option(None, help="Proxy location (e.g. RESIDENTIAL)."),
+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
+) -> None:
+ """Run a single-prompt QA task with automatic session management and recording.
+
+ Creates a cloud browser session, runs the task, fetches the recording, and
+ closes the session. Returns the result along with recording URLs.
+
+ \b
+ Examples:
+ skyvern browser qa "Go to https://example.com and verify the homepage loads"
+ skyvern browser qa "Log in and check the dashboard" --url https://app.example.com
+ """
+
+ async def _run() -> dict[str, Any]:
+ skyvern_client = get_skyvern()
+
+ # 1. Create cloud session
+ _browser, session_result = await do_session_create(
+ skyvern_client,
+ timeout=timeout,
+ proxy_location=proxy,
+ )
+ session_id = session_result.session_id
+
+ try:
+ # 2. Run task via MCP tool (reuses existing implementation)
+ task_result = await tool_run_task(
+ prompt=prompt,
+ session_id=session_id,
+ url=url,
+ max_steps=max_steps,
+ timeout_seconds=task_timeout,
+ )
+
+ # 3. Fetch session details for recording
+ recording_data: dict[str, Any] = {}
+ if session_id:
+ try:
+ session_details = await skyvern_client.get_browser_session(session_id)
+ recording_data = {
+ "app_url": session_details.app_url,
+ "recordings": [
+ {"url": r.url, "filename": r.filename} for r in (session_details.recordings or [])
+ ],
+ }
+ except Exception:
+ pass
+
+ # 4. Build QA report
+ task_data = task_result.get("data", {}) if task_result.get("ok") else {}
+ qa_result: dict[str, Any] = {
+ "session_id": session_id,
+ "status": task_data.get("status", "failed") if task_data else "failed",
+ "prompt": prompt,
+ "output": task_data.get("output") if task_data else None,
+ "failure_reason": task_data.get("failure_reason") if task_data else None,
+ **recording_data,
+ }
+
+ if not task_result.get("ok"):
+ err = task_result.get("error", {})
+ qa_result["error"] = err.get("message", "Task failed")
+
+ return qa_result
+
+ finally:
+ # 5. Always close session
+ if session_id:
+ try:
+ await do_session_close(skyvern_client, session_id)
+ except Exception:
+ pass
+
+ try:
+ data = asyncio.run(_run())
+
+ if json_output:
+ json.dump(data, sys.stdout, indent=2, default=str)
+ sys.stdout.write("\n")
+ return
+
+ # Human-readable output
+ status = data.get("status", "unknown")
+ status_color = "green" if status == "completed" else "red"
+ console.print(f"\n[bold]QA Session:[/bold] {data.get('session_id', 'N/A')}")
+ console.print(f"[bold]Status:[/bold] [{status_color}]{status.upper()}[/{status_color}]")
+
+ if data.get("app_url"):
+ console.print(f"\n[bold]Watch recording:[/bold] [cyan]{data['app_url']}[/cyan]")
+ if data.get("recordings"):
+ for rec in data["recordings"]:
+ console.print(f"[bold]Download recording:[/bold] [cyan]{rec['url']}[/cyan]")
+
+ if data.get("output"):
+ console.print(f"\n[bold]Result:[/bold] {data['output']}")
+ if data.get("failure_reason"):
+ console.print(f"\n[bold red]Failure:[/bold red] {data['failure_reason']}")
+ if data.get("error"):
+ console.print(f"\n[bold red]Error:[/bold red] {data['error']}")
+
+ console.print()
+
+ except Exception as e:
+ output_error(str(e), hint="Check your API key, prompt, and network connection.", json_mode=json_output)
diff --git a/skyvern/cli/mcp_tools/prompts.py b/skyvern/cli/mcp_tools/prompts.py
index 1cd443a73..e050a4646 100644
--- a/skyvern/cli/mcp_tools/prompts.py
+++ b/skyvern/cli/mcp_tools/prompts.py
@@ -932,6 +932,38 @@ HTTP requests and deterministic response checks over browser-based inference.
| Component doesn't render | Capture screenshot and specific UI error |
| API returns unexpected 5xx | Save request/response evidence and report the regression |
+## Session Recording
+
+Before closing, fetch the session recording so you can include it in the QA report.
+
+### Via MCP tools
+
+```text
+skyvern_browser_session_get(session_id="pbs_xxx")
+→ Returns app_url (watch in browser) and recordings (download URLs)
+```
+
+Or simply close — `skyvern_browser_session_close()` now returns recording data too:
+
+```text
+skyvern_browser_session_close()
+→ { session_id, closed, app_url, recordings: [{url, filename}], downloaded_files: [{url, filename}] }
+```
+
+### Via CLI
+
+```bash
+skyvern browser session get --session pbs_xxx --json
+# → { "app_url": "https://...", "recordings": [...] }
+
+skyvern browser session close --session pbs_xxx --json
+# → { "session_id": "pbs_xxx", "closed": true, "app_url": "https://...", "recordings": [...] }
+```
+
+Include in the QA report:
+- **Watch recording**: the `app_url` value
+- **Download recording**: the first entry in `recordings[].url`
+
## Session Cleanup
Always close browser sessions when done:
diff --git a/skyvern/cli/mcp_tools/session.py b/skyvern/cli/mcp_tools/session.py
index 6ce43e3dc..62c2e783b 100644
--- a/skyvern/cli/mcp_tools/session.py
+++ b/skyvern/cli/mcp_tools/session.py
@@ -183,11 +183,29 @@ async def skyvern_browser_session_create(
)
+async def _fetch_session_recording_data(skyvern: Any, sid: str | None) -> dict[str, Any]:
+ """Best-effort fetch of recording data from a closed session."""
+ if not sid:
+ return {}
+ try:
+ session = await skyvern.get_browser_session(sid)
+ recordings = [{"url": r.url, "filename": r.filename} for r in (session.recordings or [])]
+ downloaded_files = [{"url": f.url, "filename": f.filename} for f in (session.downloaded_files or [])]
+ return {
+ "app_url": session.app_url,
+ "recordings": recordings,
+ "downloaded_files": downloaded_files,
+ }
+ except Exception:
+ return {}
+
+
async def skyvern_browser_session_close(
session_id: Annotated[str | None, Field(description="Session ID to close (uses current if not specified)")] = None,
) -> dict[str, Any]:
"""Close a browser session when you're done. Frees cloud resources.
+ Returns session_id, closed status, plus app_url and recording URLs for the session.
Closes the specified session or the current active session.
"""
current = get_current_session()
@@ -230,9 +248,10 @@ async def skyvern_browser_session_close(
raise RuntimeError("Expected session close result after successful close operation")
timer.mark("sdk")
+ recording_data = await _fetch_session_recording_data(skyvern, session_id)
return make_result(
"skyvern_browser_session_close",
- data={"session_id": result.session_id, "closed": result.closed},
+ data={"session_id": result.session_id, "closed": result.closed, **recording_data},
timing_ms=timer.timing_ms,
)
@@ -260,9 +279,11 @@ async def skyvern_browser_session_close(
error=make_error(ErrorCode.SDK_ERROR, str(e), "Failed to close session"),
)
+ skyvern = get_skyvern()
+ recording_data = await _fetch_session_recording_data(skyvern, closed_id)
return make_result(
"skyvern_browser_session_close",
- data={"session_id": closed_id, "closed": True},
+ data={"session_id": closed_id, "closed": True, **recording_data},
timing_ms=timer.timing_ms,
)
@@ -340,6 +361,9 @@ async def skyvern_browser_session_get(
current = get_current_session()
is_current = current.context and current.context.session_id == session_id
+ recordings = [{"url": r.url, "filename": r.filename} for r in (session.recordings or [])]
+ downloaded_files = [{"url": f.url, "filename": f.filename} for f in (session.downloaded_files or [])]
+
return make_result(
"skyvern_browser_session_get",
browser_context=BrowserContext(mode="cloud_session", session_id=session_id) if is_current else None,
@@ -351,6 +375,9 @@ async def skyvern_browser_session_get(
"timeout": session.timeout,
"runnable_id": session.runnable_id,
"is_current": is_current,
+ "app_url": session.app_url,
+ "recordings": recordings,
+ "downloaded_files": downloaded_files,
},
timing_ms=timer.timing_ms,
)
diff --git a/skyvern/cli/skills/qa/SKILL.md b/skyvern/cli/skills/qa/SKILL.md
index e2071209e..8265bb01b 100644
--- a/skyvern/cli/skills/qa/SKILL.md
+++ b/skyvern/cli/skills/qa/SKILL.md
@@ -438,6 +438,38 @@ other reviewers.
| Component does not render | Capture screenshot and specific UI error |
| API returns unexpected 5xx | Save request/response evidence and report the regression |
+## Session Recording
+
+Before closing, fetch the session recording so you can include it in the QA report.
+
+### Via MCP tools
+
+```text
+skyvern_browser_session_get(session_id="pbs_xxx")
+→ Returns app_url (watch in browser) and recordings (download URLs)
+```
+
+Or simply close — `skyvern_browser_session_close()` now returns recording data too:
+
+```text
+skyvern_browser_session_close()
+→ { session_id, closed, app_url, recordings: [{url, filename}], downloaded_files: [{url, filename}] }
+```
+
+### Via CLI
+
+```bash
+skyvern browser session get --session pbs_xxx --json
+# → { "app_url": "https://...", "recordings": [...] }
+
+skyvern browser session close --session pbs_xxx --json
+# → { "session_id": "pbs_xxx", "closed": true, "app_url": "https://...", "recordings": [...] }
+```
+
+Include in the QA report:
+- **Watch recording**: the `app_url` value
+- **Download recording**: the first entry in `recordings[].url`
+
## Session Cleanup
Always close browser sessions when done:
diff --git a/skyvern/library/skyvern.py b/skyvern/library/skyvern.py
index 7dae02d78..dbd018427 100644
--- a/skyvern/library/skyvern.py
+++ b/skyvern/library/skyvern.py
@@ -29,8 +29,11 @@ if TYPE_CHECKING:
from skyvern.schemas.llm import LLMConfig, LLMRouterConfig
-def _get_browser_session_url(browser_session_id: str) -> str:
- return f"https://app.skyvern.com/browser-session/{browser_session_id}"
+def _get_browser_session_url(browser_session: BrowserSessionResponse) -> str:
+ """Return the app URL for a browser session, using the server-provided URL when available."""
+ if browser_session.app_url:
+ return browser_session.app_url
+ return f"https://app.skyvern.com/browser-session/{browser_session.browser_session_id}"
class Skyvern(AsyncSkyvern):
@@ -539,7 +542,7 @@ class Skyvern(AsyncSkyvern):
if self._environment == SkyvernEnvironment.CLOUD:
LOG.info(
"Connecting to existing cloud browser session",
- url=_get_browser_session_url(browser_session.browser_session_id),
+ url=_get_browser_session_url(browser_session),
)
else:
LOG.info(
@@ -579,7 +582,7 @@ class Skyvern(AsyncSkyvern):
if self._environment == SkyvernEnvironment.CLOUD:
LOG.info(
"Launched new cloud browser session",
- url=_get_browser_session_url(browser_session.browser_session_id),
+ url=_get_browser_session_url(browser_session),
)
else:
LOG.info("Launched new cloud browser session", browser_session_id=browser_session.browser_session_id)
@@ -623,7 +626,7 @@ class Skyvern(AsyncSkyvern):
if self._environment == SkyvernEnvironment.CLOUD:
LOG.info(
"Launched new cloud browser session",
- url=_get_browser_session_url(browser_session.browser_session_id),
+ url=_get_browser_session_url(browser_session),
)
else:
LOG.info("Launched new cloud browser session", browser_session_id=browser_session.browser_session_id)
@@ -631,7 +634,7 @@ class Skyvern(AsyncSkyvern):
if self._environment == SkyvernEnvironment.CLOUD:
LOG.info(
"Reusing existing cloud browser session",
- url=_get_browser_session_url(browser_session.browser_session_id),
+ url=_get_browser_session_url(browser_session),
)
else:
LOG.info(
diff --git a/tests/unit/test_cli_commands.py b/tests/unit/test_cli_commands.py
index db94b4ce6..3334621c6 100644
--- a/tests/unit/test_cli_commands.py
+++ b/tests/unit/test_cli_commands.py
@@ -186,6 +186,9 @@ class TestBrowserCommands:
completed_at=None,
timeout=60,
runnable_id=None,
+ app_url="https://app.skyvern.com/browser-session/pbs_123",
+ recordings=[],
+ downloaded_files=[],
)
skyvern = SimpleNamespace(get_browser_session=AsyncMock(return_value=session_obj))
monkeypatch.setattr(browser_cmd, "get_skyvern", lambda: skyvern)