Skip to content

Automate browser based workflows with AI

Rate limit browser session refresh in debug UI (#SKY-7514) (#5152)

Celal Zamanoğlu7722d1f7360e
diff --git a/skyvern-frontend/src/routes/workflows/debugger/DebuggerBlockRuns.tsx b/skyvern-frontend/src/routes/workflows/debugger/DebuggerBlockRuns.tsx
index 1dd5598bd..fb2f9e1ef 100644
--- a/skyvern-frontend/src/routes/workflows/debugger/DebuggerBlockRuns.tsx
+++ b/skyvern-frontend/src/routes/workflows/debugger/DebuggerBlockRuns.tsx
@@ -12,6 +12,7 @@ import { statusIsFinalized } from "@/routes/tasks/types";
import { useWorkflowRunQuery } from "@/routes/workflows/hooks/useWorkflowRunQuery";
import { cn, formatMs, toDate } from "@/util/utils";
+import { useBrowserSessionRateLimit } from "../hooks/useBrowserSessionRateLimit";
import { useDebugSessionQuery } from "../hooks/useDebugSessionQuery";
import { useWorkflowQuery } from "../hooks/useWorkflowQuery";
import {
@@ -29,8 +30,10 @@ function DebuggerBlockRuns() {
const { data: workflow } = useWorkflowQuery({
workflowPermanentId,
});
+ const { isRateLimited } = useBrowserSessionRateLimit(workflowPermanentId);
const { data: debugSession } = useDebugSessionQuery({
workflowPermanentId,
+ isRateLimited,
});
const { data: debugSessionRuns } = useDebugSessionRunsQuery({
debugSessionId: debugSession?.debug_session_id,
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index a8f8ce984..0480ce557 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -31,6 +31,7 @@ import { getClient } from "@/api/AxiosClient";
import { DebugSessionApiResponse } from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { useMountEffect } from "@/hooks/useMountEffect";
+import { useBrowserSessionRateLimit } from "../hooks/useBrowserSessionRateLimit";
import { useDebugSessionQuery } from "../hooks/useDebugSessionQuery";
import { useBlockScriptsQuery } from "@/routes/workflows/hooks/useBlockScriptsQuery";
import { WorkflowRunStream } from "@/routes/workflows/workflowRun/WorkflowRunStream";
@@ -117,6 +118,9 @@ const Constants = {
NewBrowserCooldown: 30000,
} as const;
+// How long to poll before recording one rate-limit attempt (60s)
+const POLL_ATTEMPT_THRESHOLD_MS = 60_000;
+
type Props = Pick<FlowRendererProps, "initialTitle" | "workflow"> & {
initialNodes: Array<AppNode>;
initialEdges: Array<Edge>;
@@ -458,9 +462,13 @@ function Workspace({
workflowPermanentId,
});
+ const { isRateLimited, recordAttempt, resetOnSuccess } =
+ useBrowserSessionRateLimit(workflowPermanentId);
+
const { data: debugSession } = useDebugSessionQuery({
workflowPermanentId,
enabled: shouldFetchDebugSession && !!workflowPermanentId,
+ isRateLimited,
});
const setCollapsed = useSidebarStore((state) => {
@@ -623,6 +631,7 @@ function Workspace({
onSuccess: (response) => {
const newDebugSession = response.data;
setActiveDebugSession(newDebugSession);
+ resetOnSuccess();
queryClient.invalidateQueries({
queryKey: ["debugSession", workflowPermanentId],
@@ -637,6 +646,8 @@ function Workspace({
afterCycleBrowser();
},
onError: (error: AxiosError) => {
+ recordAttempt();
+
toast({
variant: "destructive",
title: "Failed to cycle browser",
@@ -677,23 +688,44 @@ function Workspace({
const intervalRef = useRef<NodeJS.Timeout | null>(null);
const powerButtonTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ const pollingStartRef = useRef<number | null>(null);
+ // Polling loop: invalidate the debug-session query on an interval while
+ // we're waiting for a browser session. Records a rate-limit attempt after
+ // sustained polling without success.
useEffect(() => {
if (
(!debugSession || !debugSession.browser_session_id) &&
shouldFetchDebugSession &&
- workflowPermanentId
+ workflowPermanentId &&
+ !isRateLimited
) {
+ if (!pollingStartRef.current) {
+ pollingStartRef.current = Date.now();
+ }
+
intervalRef.current = setInterval(() => {
+ // After sustained polling without success, record one attempt
+ if (
+ pollingStartRef.current &&
+ Date.now() - pollingStartRef.current >= POLL_ATTEMPT_THRESHOLD_MS
+ ) {
+ recordAttempt();
+ pollingStartRef.current = Date.now();
+ }
+
queryClient.invalidateQueries({
queryKey: ["debugSession", workflowPermanentId],
});
- }, 2000);
+ }, 5000);
} else {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
+ // Reset polling timer so it doesn't carry a stale timestamp into the
+ // next polling cycle (e.g. after a rate-limit window expires).
+ pollingStartRef.current = null;
if (debugSession) {
setActiveDebugSession(debugSession);
@@ -705,7 +737,23 @@ function Workspace({
clearInterval(intervalRef.current);
}
};
- }, [debugSession, shouldFetchDebugSession, workflowPermanentId, queryClient]);
+ }, [
+ debugSession,
+ shouldFetchDebugSession,
+ workflowPermanentId,
+ queryClient,
+ isRateLimited,
+ recordAttempt,
+ ]);
+
+ // Reset rate-limit state when a browser session is successfully acquired.
+ // Separated from the polling effect to avoid a circular dependency where
+ // resetOnSuccess is both called inside and listed as a dependency.
+ useEffect(() => {
+ if (debugSession?.browser_session_id) {
+ resetOnSuccess();
+ }
+ }, [debugSession?.browser_session_id, resetOnSuccess]);
useEffect(() => {
const splitLeft = dom.splitLeft.current;
@@ -1607,18 +1655,46 @@ function Workspace({
{(!activeDebugSession ||
activeDebugSession.vnc_streaming_supported) && (
<div className="skyvern-vnc-browser flex h-full w-[calc(100%_-_6rem)] flex-1 flex-col items-center justify-center">
- <div key={reloadKey} className="w-full flex-1">
- <BrowserStream
- exfiltrate={recordingStore.isRecording}
- interactive={true}
- browserSessionId={
- activeDebugSession?.browser_session_id
- }
- showControlButtons={true}
- resizeTrigger={windowResizeTrigger}
- isExecuting={!!workflowRun && !isFinalized}
- />
- </div>
+ {isRateLimited ? (
+ <div
+ data-testid="browser-rate-limit-message"
+ className="flex w-full flex-1 items-center justify-center"
+ >
+ <div className="flex max-w-md flex-col items-center justify-center gap-4 rounded-md border border-slate-700 bg-slate-900 p-8 text-center">
+ <p className="text-sm text-slate-300">
+ Failed to load a browser. We have a high demand for
+ browsers right now. The browser will become
+ available again automatically in ~30 minutes. If the
+ issue persists, please contact support.
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ resetOnSuccess();
+ queryClient.invalidateQueries({
+ queryKey: ["debugSession", workflowPermanentId],
+ });
+ }}
+ >
+ Try again
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div key={reloadKey} className="w-full flex-1">
+ <BrowserStream
+ exfiltrate={recordingStore.isRecording}
+ interactive={true}
+ browserSessionId={
+ activeDebugSession?.browser_session_id
+ }
+ showControlButtons={true}
+ resizeTrigger={windowResizeTrigger}
+ isExecuting={!!workflowRun && !isFinalized}
+ />
+ </div>
+ )}
<footer className="flex h-[2rem] w-full items-center justify-start gap-4">
<WorkflowCopilotButton
ref={copilotButtonRef}
@@ -1636,10 +1712,12 @@ function Workspace({
"mr-16": !blockLabel,
})}
>
- {!recordingStore.isRecording && showPowerButton && (
- <PowerButton onClick={() => cycle()} />
- )}
- {!recordingStore.isRecording && (
+ {!recordingStore.isRecording &&
+ showPowerButton &&
+ !isRateLimited && (
+ <PowerButton onClick={() => cycle()} />
+ )}
+ {!recordingStore.isRecording && !isRateLimited && (
<ReloadButton
isReloading={isReloading}
onClick={() => reload()}
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx
index de8bffd8c..350fac1ea 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx
@@ -18,6 +18,7 @@ import { useNodeLabelChangeHandler } from "@/routes/workflows/hooks/useLabelChan
import { useRequestDeleteNodeCallback } from "@/routes/workflows/hooks/useRequestDeleteNodeCallback";
import { useTransmuteNodeCallback } from "@/routes/workflows/hooks/useTransmuteNodeCallback";
import { useToggleScriptForNodeCallback } from "@/routes/workflows/hooks/useToggleScriptForNodeCallback";
+import { useBrowserSessionRateLimit } from "@/routes/workflows/hooks/useBrowserSessionRateLimit";
import { useDebugSessionQuery } from "@/routes/workflows/hooks/useDebugSessionQuery";
import { useWorkflowQuery } from "@/routes/workflows/hooks/useWorkflowQuery";
import { useWorkflowRunQuery } from "@/routes/workflows/hooks/useWorkflowRunQuery";
@@ -204,8 +205,10 @@ function NodeHeader({
const { data: workflowRun } = useWorkflowRunQuery();
const workflowRunIsRunningOrQueued =
workflowRun && statusIsRunningOrQueued(workflowRun);
+ const { isRateLimited } = useBrowserSessionRateLimit(workflowPermanentId);
const { data: debugSession } = useDebugSessionQuery({
workflowPermanentId,
+ isRateLimited,
});
const { data: workflow } = useWorkflowQuery({
workflowPermanentId,
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useBrowserSessionRateLimit.ts b/skyvern-frontend/src/routes/workflows/hooks/useBrowserSessionRateLimit.ts
new file mode 100644
index 000000000..7a02fed90
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/useBrowserSessionRateLimit.ts
@@ -0,0 +1,147 @@
+import { useCallback, useEffect, useMemo } from "react";
+import { create } from "zustand";
+
+const MAX_ATTEMPTS = 2;
+const WINDOW_MS = 30 * 60 * 1000; // 30 minutes
+const STORAGE_KEY_PREFIX = "skyvern:debug-session-rate-limit";
+
+interface RateLimitState {
+ isRateLimited: boolean;
+ recordAttempt: () => void;
+ resetOnSuccess: () => void;
+}
+
+function getStorageKey(workflowPermanentId: string): string {
+ return `${STORAGE_KEY_PREFIX}:${workflowPermanentId}`;
+}
+
+function getAttempts(workflowPermanentId: string): number[] {
+ try {
+ const key = getStorageKey(workflowPermanentId);
+ const raw = localStorage.getItem(key);
+ if (!raw) return [];
+ const attempts: number[] = JSON.parse(raw);
+ if (!Array.isArray(attempts)) return [];
+ const now = Date.now();
+ return attempts.filter((t) => now - t < WINDOW_MS);
+ } catch {
+ return [];
+ }
+}
+
+function saveAttempts(workflowPermanentId: string, attempts: number[]): void {
+ try {
+ const key = getStorageKey(workflowPermanentId);
+ localStorage.setItem(key, JSON.stringify(attempts));
+ } catch {
+ // Ignore storage errors (e.g. private browsing, quota exceeded)
+ }
+}
+
+// Shared zustand store so all hook instances see the same state.
+// Keyed by workflowPermanentId so each workflow has independent rate limiting.
+interface RateLimitStore {
+ attemptsByWorkflow: Record<string, number[]>;
+ setAttempts: (wpid: string, attempts: number[]) => void;
+}
+
+const useRateLimitStore = create<RateLimitStore>((set) => ({
+ attemptsByWorkflow: {},
+ setAttempts: (wpid, attempts) =>
+ set((state) => ({
+ attemptsByWorkflow: { ...state.attemptsByWorkflow, [wpid]: attempts },
+ })),
+}));
+
+// Track active expiry timers per workflow to avoid duplicates
+const expiryTimers: Record<string, NodeJS.Timeout> = {};
+
+function useBrowserSessionRateLimit(
+ workflowPermanentId: string | undefined,
+): RateLimitState {
+ const storeAttempts = useRateLimitStore((state) =>
+ workflowPermanentId
+ ? state.attemptsByWorkflow[workflowPermanentId] ?? null
+ : null,
+ );
+ const setAttempts = useRateLimitStore((state) => state.setAttempts);
+
+ // Initialize store from localStorage on first mount for this workflow
+ const attempts = useMemo(
+ () =>
+ storeAttempts ??
+ (workflowPermanentId ? getAttempts(workflowPermanentId) : []),
+ [storeAttempts, workflowPermanentId],
+ );
+
+ // Sync localStorage into the store on first access
+ useEffect(() => {
+ if (workflowPermanentId && storeAttempts === null) {
+ const fromStorage = getAttempts(workflowPermanentId);
+ setAttempts(workflowPermanentId, fromStorage);
+ }
+ }, [workflowPermanentId, storeAttempts, setAttempts]);
+
+ // Schedule a re-render when the rate limit expires
+ useEffect(() => {
+ if (attempts.length < MAX_ATTEMPTS || !workflowPermanentId) return;
+
+ // Only one timer per workflow across all hook instances
+ if (expiryTimers[workflowPermanentId]) return;
+
+ const oldest = Math.min(...attempts);
+ const expiresAt = oldest + WINDOW_MS;
+ const now = Date.now();
+ const delay = expiresAt - now;
+
+ if (delay <= 0) {
+ const fresh = getAttempts(workflowPermanentId);
+ setAttempts(workflowPermanentId, fresh);
+ return;
+ }
+
+ expiryTimers[workflowPermanentId] = setTimeout(() => {
+ delete expiryTimers[workflowPermanentId];
+ const fresh = getAttempts(workflowPermanentId);
+ setAttempts(workflowPermanentId, fresh);
+ }, delay + 100);
+
+ // No cleanup: the timer must survive component unmounts (e.g. a NodeHeader
+ // being deleted) so auto-recovery still fires for remaining instances.
+ }, [attempts, workflowPermanentId, setAttempts]);
+
+ const isRateLimited = attempts.length >= MAX_ATTEMPTS;
+
+ const recordAttempt = useCallback(() => {
+ if (!workflowPermanentId) return;
+ const current = getAttempts(workflowPermanentId);
+ const updated = [...current, Date.now()].slice(-MAX_ATTEMPTS);
+ saveAttempts(workflowPermanentId, updated);
+ setAttempts(workflowPermanentId, updated);
+ }, [workflowPermanentId, setAttempts]);
+
+ const resetOnSuccess = useCallback(() => {
+ if (!workflowPermanentId) return;
+ // Guard: skip if already cleared (avoids redundant localStorage writes
+ // when multiple success paths call this, e.g. cycleBrowser.onSuccess +
+ // the dedicated useEffect that watches debugSession.browser_session_id).
+ const current = getAttempts(workflowPermanentId);
+ if (current.length === 0) return;
+ saveAttempts(workflowPermanentId, []);
+ setAttempts(workflowPermanentId, []);
+ // Clear the expiry timer so a new one can be scheduled if the user
+ // gets rate-limited again (e.g. after clicking "Try again").
+ if (expiryTimers[workflowPermanentId]) {
+ clearTimeout(expiryTimers[workflowPermanentId]);
+ delete expiryTimers[workflowPermanentId];
+ }
+ }, [workflowPermanentId, setAttempts]);
+
+ return {
+ isRateLimited,
+ recordAttempt,
+ resetOnSuccess,
+ };
+}
+
+export { useBrowserSessionRateLimit };
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.ts
index 00cbe4787..d85c7d6ec 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.ts
@@ -6,11 +6,21 @@ import { useQuery } from "@tanstack/react-query";
interface Opts {
workflowPermanentId?: string;
enabled?: boolean;
+ isRateLimited?: boolean;
}
-function useDebugSessionQuery({ workflowPermanentId, enabled }: Opts) {
+function useDebugSessionQuery({
+ workflowPermanentId,
+ enabled,
+ isRateLimited,
+}: Opts) {
const credentialGetter = useCredentialGetter();
+ const baseEnabled =
+ enabled !== undefined
+ ? enabled && !!workflowPermanentId
+ : !!workflowPermanentId;
+
return useQuery<DebugSessionApiResponse>({
queryKey: ["debugSession", workflowPermanentId],
queryFn: async () => {
@@ -19,16 +29,14 @@ function useDebugSessionQuery({ workflowPermanentId, enabled }: Opts) {
.get(`/debug-session/${workflowPermanentId}`)
.then((response) => response.data);
},
- enabled:
- enabled !== undefined
- ? enabled && !!workflowPermanentId
- : !!workflowPermanentId,
+ enabled: baseEnabled && !isRateLimited,
// Reduce polling frequency on errors
retry: 3,
retryDelay: 10000,
refetchOnWindowFocus: false,
// Don't keep retrying if in error state
refetchInterval: (query) => {
+ if (isRateLimited) return false;
// If query is in error state, poll much less frequently (30s)
// Otherwise don't auto-refetch
if (query.state.status === "error") {