Skip to content

Automate browser based workflows with AI

Keep debug browser sessions alive from editor (#6832)

Suchintand323696365c6
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index afaacfee5..ba002ded3 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -31,7 +31,7 @@ import {
useReactFlow,
Edge,
} from "@xyflow/react";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { usePostHog } from "posthog-js/react";
import { getClient } from "@/api/AxiosClient";
@@ -47,7 +47,14 @@ import {
StreamModeBadge,
StreamStatusPanel,
} from "@/routes/streaming/StreamDiagnostics";
+import { type BrowserSession as BrowserSessionData } from "@/routes/workflows/types/browserSessionTypes";
import { useCacheKeyValuesQuery } from "../hooks/useCacheKeyValuesQuery";
+import {
+ DEBUG_SESSION_EXPIRY_STATUS_REFETCH_MS,
+ DEBUG_SESSION_EXPIRY_WARNING_THRESHOLD_MS,
+ formatBrowserSessionRemainingTime,
+ getBrowserSessionRemainingMs,
+} from "../hooks/debugSessionLease";
import { useBlockScriptStore } from "@/store/BlockScriptStore";
import { useBlockSidebarWidthStore } from "@/store/BlockSidebarWidthStore";
import { useCacheKeyValueStore } from "@/store/CacheKeyValueStore";
@@ -664,6 +671,7 @@ function Workspace({
workflowPermanentId,
enabled: shouldFetchDebugSession && !!workflowPermanentId,
isRateLimited,
+ keepAliveBrowserSession: true,
});
const activeDebugSession = debugSession ?? null;
@@ -694,6 +702,28 @@ function Workspace({
hasBackendSession: Boolean(liveBrowserSessionId),
headlessTurnDrainEnabled: headlessTurnDrainEnabled || embedded,
});
+ const debugSessionExpiryWarningKeyRef = useRef<string | null>(null);
+
+ const { data: liveBrowserSession, dataUpdatedAt: liveBrowserSessionNowMs } =
+ useQuery<BrowserSessionData>({
+ queryKey: ["browserSession", liveBrowserSessionId],
+ queryFn: async () => {
+ if (!liveBrowserSessionId) {
+ throw new Error("Cannot fetch browser session without an ID");
+ }
+ const client = await getClient(credentialGetter, "sans-api-v1");
+ const response = await client.get<BrowserSessionData>(
+ `/browser_sessions/${liveBrowserSessionId}`,
+ );
+ return response.data;
+ },
+ enabled:
+ Boolean(liveBrowserSessionId) &&
+ shouldFetchDebugSession &&
+ !isRateLimited,
+ refetchInterval: DEBUG_SESSION_EXPIRY_STATUS_REFETCH_MS,
+ refetchOnWindowFocus: true,
+ });
const handleLiveBrowserReadyChange = useCallback(
(ready: boolean, sessionId: string | null) => {
@@ -704,6 +734,50 @@ function Workspace({
useBrowserLoadingFlag(shouldFetchDebugSession, readyBrowserSessionId);
+ useEffect(() => {
+ if (!liveBrowserSession || liveBrowserSession.completed_at) {
+ debugSessionExpiryWarningKeyRef.current = null;
+ return;
+ }
+
+ const remainingMs = getBrowserSessionRemainingMs(
+ liveBrowserSession,
+ liveBrowserSessionNowMs,
+ );
+ if (remainingMs !== null && remainingMs <= 0) {
+ if (debugSessionExpiryWarningKeyRef.current) {
+ toast({
+ variant: "destructive",
+ title: "Browser session expired",
+ description: "Start a new debug browser to continue.",
+ });
+ }
+ debugSessionExpiryWarningKeyRef.current = null;
+ return;
+ }
+
+ if (
+ remainingMs === null ||
+ remainingMs > DEBUG_SESSION_EXPIRY_WARNING_THRESHOLD_MS
+ ) {
+ debugSessionExpiryWarningKeyRef.current = null;
+ return;
+ }
+
+ const warningKey = `${liveBrowserSession.browser_session_id}:${liveBrowserSession.started_at}:${liveBrowserSession.timeout}`;
+ if (debugSessionExpiryWarningKeyRef.current === warningKey) {
+ return;
+ }
+
+ debugSessionExpiryWarningKeyRef.current = warningKey;
+ const remainingTime = formatBrowserSessionRemainingTime(remainingMs);
+ toast({
+ variant: "warning",
+ title: "Browser session expiring soon",
+ description: `This debug browser expires in ${remainingTime}. Skyvern renews it automatically while this view is open, but may open a replacement browser if this lease can no longer be renewed.`,
+ });
+ }, [liveBrowserSession, liveBrowserSessionNowMs]);
+
const hasLoopBlock = nodes.some((node) => node.type === "loop");
const hasHttpBlock = nodes.some((node) => node.type === "http_request");
const workflowWidth = hasHttpBlock
diff --git a/skyvern-frontend/src/routes/workflows/hooks/debugSessionLease.test.ts b/skyvern-frontend/src/routes/workflows/hooks/debugSessionLease.test.ts
new file mode 100644
index 000000000..be2f33768
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/debugSessionLease.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, test, vi } from "vitest";
+
+import {
+ DEBUG_SESSION_EXPIRY_WARNING_THRESHOLD_MS,
+ DEBUG_SESSION_RENEWAL_THRESHOLD_MS,
+ formatBrowserSessionRemainingTime,
+ getBrowserSessionExpiresAtMs,
+ getBrowserSessionRemainingMs,
+} from "./debugSessionLease";
+
+describe("debugSessionLease", () => {
+ test("calculates browser session expiry from started_at and timeout minutes", () => {
+ expect(
+ getBrowserSessionExpiresAtMs({
+ started_at: "2026-06-23T10:00:00.000Z",
+ timeout: 20,
+ }),
+ ).toBe(new Date("2026-06-23T10:20:00.000Z").getTime());
+ });
+
+ test("returns null when the session has not started or has no timeout", () => {
+ expect(
+ getBrowserSessionExpiresAtMs({ started_at: null, timeout: 20 }),
+ ).toBe(null);
+ expect(
+ getBrowserSessionExpiresAtMs({
+ started_at: "2026-06-23T10:00:00.000Z",
+ timeout: null,
+ }),
+ ).toBe(null);
+ });
+
+ test("calculates remaining time", () => {
+ expect(
+ getBrowserSessionRemainingMs(
+ {
+ started_at: "2026-06-23T10:00:00.000Z",
+ timeout: 20,
+ },
+ new Date("2026-06-23T10:17:30.000Z").getTime(),
+ ),
+ ).toBe(150_000);
+ });
+
+ test("uses Date.now by default when calculating remaining time", () => {
+ vi.useFakeTimers();
+ try {
+ vi.setSystemTime(new Date("2026-06-23T10:17:30.000Z"));
+ expect(
+ getBrowserSessionRemainingMs({
+ started_at: "2026-06-23T10:00:00.000Z",
+ timeout: 20,
+ }),
+ ).toBe(150_000);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("formats remaining time for warning copy", () => {
+ expect(formatBrowserSessionRemainingTime(59_000)).toBe(
+ "less than 1 minute",
+ );
+ expect(formatBrowserSessionRemainingTime(60_000)).toBe("1 minute");
+ expect(formatBrowserSessionRemainingTime(61_000)).toBe("1 minute");
+ expect(formatBrowserSessionRemainingTime(120_000)).toBe("2 minutes");
+ });
+
+ test("warns before the backend renewal cutoff", () => {
+ // These values intentionally mirror the backend debug-session renewal cutoff.
+ expect(DEBUG_SESSION_RENEWAL_THRESHOLD_MS).toBe(10 * 60 * 1000);
+ expect(DEBUG_SESSION_EXPIRY_WARNING_THRESHOLD_MS).toBe(12 * 60 * 1000);
+ expect(DEBUG_SESSION_EXPIRY_WARNING_THRESHOLD_MS).toBeGreaterThan(
+ DEBUG_SESSION_RENEWAL_THRESHOLD_MS,
+ );
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/hooks/debugSessionLease.ts b/skyvern-frontend/src/routes/workflows/hooks/debugSessionLease.ts
new file mode 100644
index 000000000..d67a07f4f
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/debugSessionLease.ts
@@ -0,0 +1,58 @@
+import { type BrowserSession } from "@/routes/workflows/types/browserSessionTypes";
+
+const DEBUG_SESSION_EXPIRY_STATUS_REFETCH_MS = 30 * 1000;
+// Backend renewal uses DEBUG_SESSION_TIMEOUT_THRESHOLD_MINUTES = 10.
+const DEBUG_SESSION_RENEWAL_THRESHOLD_MS = 10 * 60 * 1000;
+// Warn 2 min before the backend renewal cutoff so manual renewal can still succeed.
+const RENEWAL_WARNING_BUFFER_MS = 2 * 60 * 1000;
+const DEBUG_SESSION_EXPIRY_WARNING_THRESHOLD_MS =
+ DEBUG_SESSION_RENEWAL_THRESHOLD_MS + RENEWAL_WARNING_BUFFER_MS;
+
+function getBrowserSessionExpiresAtMs(
+ browserSession: Pick<BrowserSession, "started_at" | "timeout"> | null,
+): number | null {
+ if (!browserSession?.started_at || !browserSession.timeout) {
+ return null;
+ }
+
+ const startedAtMs = new Date(browserSession.started_at).getTime();
+ if (Number.isNaN(startedAtMs)) {
+ return null;
+ }
+
+ return startedAtMs + browserSession.timeout * 60 * 1000;
+}
+
+function getBrowserSessionRemainingMs(
+ browserSession: Pick<BrowserSession, "started_at" | "timeout"> | null,
+ nowMs: number = Date.now(),
+): number | null {
+ const expiresAtMs = getBrowserSessionExpiresAtMs(browserSession);
+ if (expiresAtMs === null) {
+ return null;
+ }
+
+ return expiresAtMs - nowMs;
+}
+
+function formatBrowserSessionRemainingTime(remainingMs: number): string {
+ const positiveRemainingMs = Math.max(0, remainingMs);
+ if (positiveRemainingMs < 60_000) {
+ return "less than 1 minute";
+ }
+
+ const remainingMinutes = Math.floor(positiveRemainingMs / 60_000);
+ if (remainingMinutes === 1) {
+ return "1 minute";
+ }
+ return `${remainingMinutes} minutes`;
+}
+
+export {
+ DEBUG_SESSION_EXPIRY_STATUS_REFETCH_MS,
+ DEBUG_SESSION_EXPIRY_WARNING_THRESHOLD_MS,
+ DEBUG_SESSION_RENEWAL_THRESHOLD_MS,
+ formatBrowserSessionRemainingTime,
+ getBrowserSessionExpiresAtMs,
+ getBrowserSessionRemainingMs,
+};
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.test.ts b/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.test.ts
new file mode 100644
index 000000000..040051797
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, test } from "vitest";
+
+import {
+ DEBUG_SESSION_ERROR_REFETCH_INTERVAL_MS,
+ DEBUG_SESSION_KEEP_ALIVE_INTERVAL_MS,
+ getDebugSessionRefetchInterval,
+} from "./useDebugSessionQuery";
+
+describe("getDebugSessionRefetchInterval", () => {
+ test("keeps debug sessions alive after a browser session exists when enabled", () => {
+ expect(
+ getDebugSessionRefetchInterval(
+ {
+ status: "success",
+ data: { browser_session_id: "pbs_123" },
+ },
+ false,
+ true,
+ ),
+ ).toBe(DEBUG_SESSION_KEEP_ALIVE_INTERVAL_MS);
+ });
+
+ test("does not keep successful debug-session reads alive by default", () => {
+ expect(
+ getDebugSessionRefetchInterval({
+ status: "success",
+ data: { browser_session_id: "pbs_123" },
+ }),
+ ).toBe(false);
+ });
+
+ test("does not poll successful responses that have no browser session yet", () => {
+ expect(
+ getDebugSessionRefetchInterval(
+ {
+ status: "success",
+ data: { browser_session_id: "" },
+ },
+ false,
+ true,
+ ),
+ ).toBe(false);
+ expect(
+ getDebugSessionRefetchInterval(
+ {
+ status: "success",
+ data: { browser_session_id: null },
+ },
+ false,
+ true,
+ ),
+ ).toBe(false);
+ });
+
+ test("uses slower polling for errors", () => {
+ expect(getDebugSessionRefetchInterval({ status: "error" })).toBe(
+ DEBUG_SESSION_ERROR_REFETCH_INTERVAL_MS,
+ );
+ });
+
+ test("does not poll while rate limited", () => {
+ expect(
+ getDebugSessionRefetchInterval(
+ {
+ status: "success",
+ data: { browser_session_id: "pbs_123" },
+ },
+ true,
+ true,
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.ts
index d85c7d6ec..9b13403a2 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionQuery.ts
@@ -3,16 +3,43 @@ import { DebugSessionApiResponse } from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { useQuery } from "@tanstack/react-query";
+const DEBUG_SESSION_KEEP_ALIVE_INTERVAL_MS = 5 * 60 * 1000;
+const DEBUG_SESSION_ERROR_REFETCH_INTERVAL_MS = 30 * 1000;
+
+type DebugSessionRefetchState = {
+ status: "pending" | "error" | "success";
+ data?: { browser_session_id?: string | null } | null;
+};
+
+function getDebugSessionRefetchInterval(
+ queryState: DebugSessionRefetchState,
+ isRateLimited = false,
+ keepAliveBrowserSession = false,
+): number | false {
+ if (isRateLimited) {
+ return false;
+ }
+ if (queryState.status === "error") {
+ return DEBUG_SESSION_ERROR_REFETCH_INTERVAL_MS;
+ }
+ if (keepAliveBrowserSession && queryState.data?.browser_session_id) {
+ return DEBUG_SESSION_KEEP_ALIVE_INTERVAL_MS;
+ }
+ return false;
+}
+
interface Opts {
workflowPermanentId?: string;
enabled?: boolean;
isRateLimited?: boolean;
+ keepAliveBrowserSession?: boolean;
}
function useDebugSessionQuery({
workflowPermanentId,
enabled,
isRateLimited,
+ keepAliveBrowserSession,
}: Opts) {
const credentialGetter = useCredentialGetter();
@@ -35,16 +62,20 @@ function useDebugSessionQuery({
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") {
- return 30000;
- }
- return false;
- },
+ refetchInterval: (query) =>
+ getDebugSessionRefetchInterval(
+ query.state,
+ isRateLimited,
+ keepAliveBrowserSession,
+ ),
+ // Keep lease renewal polling active even when the editor tab is backgrounded.
+ refetchIntervalInBackground: keepAliveBrowserSession,
});
}
-export { useDebugSessionQuery };
+export {
+ DEBUG_SESSION_ERROR_REFETCH_INTERVAL_MS,
+ DEBUG_SESSION_KEEP_ALIVE_INTERVAL_MS,
+ getDebugSessionRefetchInterval,
+ useDebugSessionQuery,
+};