Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 52 additions & 47 deletions src/main/browserbase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ const MAX_RETRIES = 3;
/** Base delay in milliseconds between retry attempts (uses exponential backoff) */
const RETRY_DELAY_MS = 1000;

/** Total deadline for an API operation, including retries and response bodies. */
const REQUEST_TIMEOUT_MS = 30000;

/** Default maximum time to wait for a deferred session to become RUNNING */
const DEFAULT_SESSION_READY_TIMEOUT_MS = 120000;

Expand Down Expand Up @@ -117,41 +120,34 @@ export class BrowserbaseClient {
private async fetchWithRetry(
url: string,
options: RequestInit,
retries: number = MAX_RETRIES
retries: number = MAX_RETRIES,
timeoutMs: number = REQUEST_TIMEOUT_MS
): Promise<Response> {
let lastError: Error | null = null;
const deadline = Date.now() + timeoutMs;
let lastError = new Error("Browserbase request timed out");

for (let attempt = 0; attempt < retries; attempt++) {
const remainingMs = deadline - Date.now();
if (remainingMs <= 0) throw lastError;
try {
const response = await fetch(url, options);

// Don't retry client errors (4xx) except for rate limiting (429)
if (response.status >= 400 && response.status < 500 && response.status !== 429) {
return response;
}

// Retry server errors (5xx) and rate limiting (429)
if (response.ok) {
return response;
}

if (response.status === 429 || response.status >= 500) {
const delay = RETRY_DELAY_MS * Math.pow(2, attempt);
console.log(`Request failed with ${response.status}, retrying in ${delay}ms...`);
await this.sleep(delay);
continue;
}

return response;
const signal = AbortSignal.timeout(Math.ceil(remainingMs));
const response = await fetch(url, { ...options, signal });
const retryable = response.status === 429 || response.status >= 500;
if (!retryable || attempt === retries - 1) return response;
await response.body?.cancel();
lastError = new Error(`Browserbase request failed (HTTP ${response.status})`);
} catch (error) {
lastError = safeError(error);
const delay = RETRY_DELAY_MS * Math.pow(2, attempt);
console.log(`Request failed: ${safeError(error).message}, retrying in ${delay}ms...`);
await this.sleep(delay);
if (attempt === retries - 1 || Date.now() >= deadline) throw lastError;
}

const delay = Math.min(RETRY_DELAY_MS * Math.pow(2, attempt), deadline - Date.now());
if (delay <= 0) throw lastError;
console.log(`Retrying Browserbase request in ${delay}ms...`);
await this.sleep(delay);
}

throw lastError || new Error("Request failed after retries");
throw lastError;
}

/** Utility function to pause execution for a specified duration */
Expand Down Expand Up @@ -187,13 +183,13 @@ export class BrowserbaseClient {
);
}

private async fetchSession(sessionId: string): Promise<BrowserbaseApiSession> {
private async fetchSession(sessionId: string, timeoutMs?: number): Promise<BrowserbaseApiSession> {
const response = await this.fetchWithRetry(`${BROWSERBASE_API_URL}/sessions/${sessionId}`, {
method: "GET",
headers: {
"x-bb-api-key": this.apiKey,
},
});
}, MAX_RETRIES, timeoutMs);

if (!response.ok) {
throw new Error(`Failed to get Browserbase session (HTTP ${response.status})`);
Expand All @@ -215,13 +211,13 @@ export class BrowserbaseClient {
return `https://www.browserbase.com/devtools-fullscreen/inspector.html?wss=connect.browserbase.com&apiKey=${this.apiKey}&sessionId=${sessionId}`;
}

private async fetchDebugInfo(sessionId: string): Promise<BrowserbaseDebugInfo> {
private async fetchDebugInfo(sessionId: string, timeoutMs?: number): Promise<BrowserbaseDebugInfo> {
const response = await this.fetchWithRetry(`${BROWSERBASE_API_URL}/sessions/${sessionId}/debug`, {
method: "GET",
headers: {
"x-bb-api-key": this.apiKey,
},
});
}, MAX_RETRIES, timeoutMs);

if (!response.ok) {
throw new Error(`Failed to get Browserbase debug info (HTTP ${response.status})`);
Expand All @@ -230,15 +226,15 @@ export class BrowserbaseClient {
return await response.json() as BrowserbaseDebugInfo;
}

private async toReadySession(session: BrowserbaseApiSession): Promise<BrowserbaseSession> {
private async toReadySession(session: BrowserbaseApiSession, timeoutMs?: number): Promise<BrowserbaseSession> {
if (session.status !== "RUNNING") {
throw new Error(
`Browserbase session ${session.id} is ${session.status}; connection details are not available yet`
);
}

// Get the debug/live view URL from the debug endpoint once the browser is running.
const debugUrl = await this.getDebugUrl(session.id);
const debugUrl = await this.getDebugUrl(session.id, timeoutMs);

return {
id: session.id,
Expand Down Expand Up @@ -311,7 +307,7 @@ export class BrowserbaseClient {
method: "POST",
headers,
body: JSON.stringify(requestBody),
});
}, 1); // Creation is not idempotent: a lost response must not create another session.

let response = await post();

Expand Down Expand Up @@ -343,16 +339,21 @@ export class BrowserbaseClient {
const session = (await response.json()) as BrowserbaseApiSession;
console.log("Browserbase session created with status:", session.status);

if (session.status === "PENDING") {
console.log(`Browserbase session ${session.id} is pending; polling until RUNNING...`);
return await this.waitForSessionReady(
session.id,
config?.readyTimeoutMs,
config?.readyPollIntervalMs
);
try {
if (session.status === "PENDING") {
console.log(`Browserbase session ${session.id} is pending; polling until RUNNING...`);
return await this.waitForSessionReady(
session.id,
config?.readyTimeoutMs,
config?.readyPollIntervalMs
);
}
return await this.toReadySession(session);
} catch (error) {
// The caller cannot release a session until creation returns its ID.
await this.stopSession(session.id);
throw safeError(error);
}

return await this.toReadySession(session);
}

/**
Expand All @@ -364,9 +365,9 @@ export class BrowserbaseClient {
* @param sessionId - The session ID to get the debug URL for
* @returns The debug URL for iframe embedding
*/
async getDebugUrl(sessionId: string): Promise<string> {
async getDebugUrl(sessionId: string, timeoutMs?: number): Promise<string> {
try {
const debugInfo = await this.fetchDebugInfo(sessionId);
const debugInfo = await this.fetchDebugInfo(sessionId, timeoutMs);

// Use debuggerFullscreenUrl for the embedded view, hide navbar since we have our own
const baseUrl = debugInfo.debuggerFullscreenUrl || debugInfo.debuggerUrl ||
Expand Down Expand Up @@ -511,16 +512,20 @@ export class BrowserbaseClient {
timeoutMs: number = this.getDefaultReadyTimeoutMs(),
pollIntervalMs: number = this.getDefaultReadyPollIntervalMs()
): Promise<BrowserbaseSession> {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || !Number.isFinite(pollIntervalMs) || pollIntervalMs <= 0) {
throw new Error("Session readiness timeout and poll interval must be positive finite numbers");
}
const startTime = Date.now();
let lastStatus: BrowserbaseSessionStatus = "UNKNOWN";

while (Date.now() - startTime <= timeoutMs) {
const session = await this.fetchSession(sessionId);
while (Date.now() - startTime < timeoutMs) {
const remainingBeforeFetch = timeoutMs - (Date.now() - startTime);
const session = await this.fetchSession(sessionId, Math.min(REQUEST_TIMEOUT_MS, remainingBeforeFetch));
lastStatus = session.status;

if (session.status === "RUNNING") {
console.log(`Browserbase session ${sessionId} is RUNNING`);
return await this.toReadySession(session);
return await this.toReadySession(session, Math.max(1, timeoutMs - (Date.now() - startTime)));
}

if (TERMINAL_SESSION_STATUSES.has(session.status)) {
Expand Down
44 changes: 30 additions & 14 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { AutomationServer, getAutomationServerPort, isAutomationServerEnabled }
let mainWindow: BrowserWindow | null = null;
let resizeTimeout: ReturnType<typeof setTimeout> | null = null;
let automationServer: AutomationServer | null = null;
let quitting = false;
let cleanupComplete = false;

// Window state persistence
interface WindowState {
Expand Down Expand Up @@ -312,6 +314,7 @@ function createApplicationMenu(): void {
}

async function createWindow(): Promise<void> {
if (quitting) return;
const windowState = loadWindowState();

// Create the browser window with Chrome-like appearance
Expand Down Expand Up @@ -370,23 +373,28 @@ async function createWindow(): Promise<void> {
// Load the renderer HTML
mainWindow.loadFile(path.join(__dirname, "../renderer/index.html"));

// Wait for renderer to be ready before initializing session
// Keep this callback tied to its window while initialization is in flight.
const window = mainWindow;
mainWindow.webContents.on("did-finish-load", async () => {
if (quitting) return;
console.log("Renderer loaded, initializing Browserbase session...");

try {
const bbSession = await sessionManager.initialize();
console.log("Session initialized, sending SESSION_CREATED event");
mainWindow?.webContents.send(IPC_CHANNELS.SESSION_CREATED, bbSession.id);
if (!quitting && !window.isDestroyed()) window.webContents.send(IPC_CHANNELS.SESSION_CREATED, bbSession.id);
} catch (error) {
console.error("Failed to initialize Browserbase session:", error);
mainWindow?.webContents.send(IPC_CHANNELS.SESSION_ERROR, (error as Error).message);
if (!window.isDestroyed()) window.webContents.send(IPC_CHANNELS.SESSION_ERROR, (error as Error).message);
}
});

// Handle window close
mainWindow.on("closed", () => {
if (resizeTimeout) clearTimeout(resizeTimeout);
resizeTimeout = null;
mainWindow = null;
sessionManager.setMainWindow(null);
});

// Open DevTools in development
Expand Down Expand Up @@ -446,25 +454,33 @@ app.whenReady().then(async () => {
});

app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
if (!quitting && BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});

app.on("window-all-closed", async () => {
// Clean up Browserbase session
await sessionManager.cleanup();
app.on("window-all-closed", () => {
// Remove old handlers immediately so a macOS activation can register new ones.
removeIpcHandlers();

if (process.platform !== "darwin") {
app.quit();
}
void sessionManager.cleanup().then(() => {
if (process.platform !== "darwin" && BrowserWindow.getAllWindows().length === 0) {
app.quit();
}
});
});

app.on("will-quit", async () => {
await automationServer?.stop();
await sessionManager.cleanup();
app.on("before-quit", (event) => {
if (cleanupComplete) return;
// Electron does not wait for async lifecycle listeners on its own.
event.preventDefault();
if (quitting) return;
quitting = true;
if (resizeTimeout) clearTimeout(resizeTimeout);
void Promise.allSettled([automationServer?.stop(), sessionManager.shutdown()]).finally(() => {
cleanupComplete = true;
app.quit();
});
});

// Handle uncaught exceptions
Expand Down
Loading