diff --git a/src/main/browserbase.ts b/src/main/browserbase.ts index 4f21e38..948f0f7 100644 --- a/src/main/browserbase.ts +++ b/src/main/browserbase.ts @@ -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; @@ -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 { - 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 */ @@ -187,13 +183,13 @@ export class BrowserbaseClient { ); } - private async fetchSession(sessionId: string): Promise { + private async fetchSession(sessionId: string, timeoutMs?: number): Promise { 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})`); @@ -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 { + private async fetchDebugInfo(sessionId: string, timeoutMs?: number): Promise { 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})`); @@ -230,7 +226,7 @@ export class BrowserbaseClient { return await response.json() as BrowserbaseDebugInfo; } - private async toReadySession(session: BrowserbaseApiSession): Promise { + private async toReadySession(session: BrowserbaseApiSession, timeoutMs?: number): Promise { if (session.status !== "RUNNING") { throw new Error( `Browserbase session ${session.id} is ${session.status}; connection details are not available yet` @@ -238,7 +234,7 @@ export class BrowserbaseClient { } // 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, @@ -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(); @@ -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); } /** @@ -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 { + async getDebugUrl(sessionId: string, timeoutMs?: number): Promise { 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 || @@ -511,16 +512,20 @@ export class BrowserbaseClient { timeoutMs: number = this.getDefaultReadyTimeoutMs(), pollIntervalMs: number = this.getDefaultReadyPollIntervalMs() ): Promise { + 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)) { diff --git a/src/main/index.ts b/src/main/index.ts index c33384b..3edb4e7 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -23,6 +23,8 @@ import { AutomationServer, getAutomationServerPort, isAutomationServerEnabled } let mainWindow: BrowserWindow | null = null; let resizeTimeout: ReturnType | null = null; let automationServer: AutomationServer | null = null; +let quitting = false; +let cleanupComplete = false; // Window state persistence interface WindowState { @@ -312,6 +314,7 @@ function createApplicationMenu(): void { } async function createWindow(): Promise { + if (quitting) return; const windowState = loadWindowState(); // Create the browser window with Chrome-like appearance @@ -370,23 +373,28 @@ async function createWindow(): Promise { // 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 @@ -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 diff --git a/src/main/session.ts b/src/main/session.ts index 3964fb7..688dc2a 100644 --- a/src/main/session.ts +++ b/src/main/session.ts @@ -40,17 +40,22 @@ export class SessionManager { private session: BrowserbaseSession | null = null; private browser: Browser | null = null; private context: BrowserContext | null = null; - private cdpSession: CDPSession | null = null; private mainWindow: BrowserWindow | null = null; private tabs: TabInfo[] = []; - private pageCdpSessions = new WeakMap(); + private pageCdpSessions = new WeakMap>(); private currentUrl: string = ""; private activeTabIndex: number = 0; private reconnectAttempts = 0; private maxReconnectAttempts = 3; - private isConnecting = false; - - setMainWindow(window: BrowserWindow): void { + private initializing: Promise | null = null; + private connecting: Promise | null = null; + private cleaningUp: Promise | null = null; + private reconnectTimer: ReturnType | null = null; + private shuttingDown = false; + private permanentlyClosed = false; + private generation = 0; + + setMainWindow(window: BrowserWindow | null): void { this.mainWindow = window; } @@ -81,8 +86,7 @@ export class SessionManager { private async applyViewportToPage(page: Page, width: number, height: number): Promise { try { - // Always create a new CDP session for the specific page - const cdp = await page.context().newCDPSession(page); + const cdp = await this.getCdpSessionForPage(page); const deviceScaleFactor = process.platform === "darwin" ? 2 : 1; @@ -111,6 +115,32 @@ export class SessionManager { } async initialize(): Promise { + if (this.permanentlyClosed) throw new Error("Application is shutting down"); + if (this.cleaningUp) await this.cleaningUp; + if (this.permanentlyClosed) throw new Error("Application is shutting down"); + if (this.initializing) return this.initializing; + if (this.session) { + const session = this.session; + if (!this.browser?.isConnected()) await this.connectToBrowser(); + if (this.shuttingDown || this.session !== session) throw new Error("Session is closing"); + // A reloaded renderer has fresh UI state even when the cloud session is reused. + this.notifyTabsUpdated(); + this.notifyUrlChanged(this.currentUrl); + return session; + } + + this.shuttingDown = false; + const generation = this.generation; + const initializing = this.initializeSession(generation); + this.initializing = initializing; + try { + return await initializing; + } finally { + if (this.initializing === initializing) this.initializing = null; + } + } + + private async initializeSession(generation: number): Promise { try { // Calculate viewport size based on window content area // Chrome UI elements: tab bar (36px), nav bar (40px) = 76px total @@ -142,10 +172,9 @@ export class SessionManager { // Create a Browserbase session with viewport matching our window. // BrowserbaseClient waits until the remote browser is RUNNING before // returning connection URLs when async/deferred scheduling is enabled. - const scaleFactor = this.mainWindow?.webContents.getZoomFactor() || 1; const deviceScaleFactor = process.platform === 'darwin' ? 2 : 1; - this.session = await this.getBrowserbaseClient().createSession({ + const session = await this.getBrowserbaseClient().createSession({ browserSettings: { viewport: { width: viewportWidth, @@ -154,82 +183,80 @@ export class SessionManager { deviceScaleFactor, }, }); + if (this.shuttingDown || generation !== this.generation) { + await this.getBrowserbaseClient().stopSession(session.id); + throw new Error("Session startup cancelled"); + } + this.session = session; console.log(`Using deviceScaleFactor: ${deviceScaleFactor}`); console.log("Browserbase session created:", this.session.id); // Connect to the remote browser via CDP await this.connectToBrowser(); + if (this.shuttingDown || generation !== this.generation) { + throw new Error("Session startup cancelled"); + } - return this.session; + // A failed start page should not discard an otherwise usable browser. + const defaultUrl = process.env.BROWSERBASE_DEFAULT_URL || "https://www.google.com"; + try { + await this.navigateTo(defaultUrl); + } catch (error) { + console.warn("Could not load the start page:", safeError(error).message); + } + if (this.shuttingDown || generation !== this.generation) { + throw new Error("Session startup cancelled"); + } + return session; } catch (error) { + await this.releaseResources(); console.error("Failed to initialize session:", safeError(error).message); - this.notifyError(safeError(error)); + if (!this.shuttingDown) this.notifyError(safeError(error)); throw safeError(error); } } private async connectToBrowser(): Promise { - if (!this.session) { - throw new Error("No session available"); - } + if (this.connecting) return this.connecting; + if (!this.session || this.shuttingDown) throw new Error("No session available"); - if (this.isConnecting) { - console.log("Already connecting, skipping..."); - return; + const connecting = this.openBrowserConnection(this.session, this.generation); + this.connecting = connecting; + try { + await connecting; + } finally { + if (this.connecting === connecting) this.connecting = null; } + } - this.isConnecting = true; + private async openBrowserConnection(session: BrowserbaseSession, generation: number): Promise { + console.log("Connecting to remote browser via CDP..."); + const browser = await chromium.connectOverCDP(session.connectUrl, { timeout: 30000 }); + if (this.shuttingDown || generation !== this.generation || this.session !== session) { + await browser.close(); + throw new Error("Browser connection cancelled"); + } + this.browser = browser; + this.pageCdpSessions = new WeakMap(); try { - // Connect to the remote browser using Playwright with timeout - console.log("Connecting to remote browser via CDP..."); - this.browser = await chromium.connectOverCDP(this.session.connectUrl, { - timeout: 30000, - }); - console.log("Connected to remote browser via CDP"); - - // Get the default context - const contexts = this.browser.contexts(); - this.context = contexts[0] || await this.browser.newContext(); - - // Get all pages (tabs) - const pages = this.context.pages(); - if (pages.length === 0) { - await this.context.newPage(); - } - - // Set up CDP session for advanced control - const page = this.context.pages()[0]; - try { - this.cdpSession = await page.context().newCDPSession(page); - } catch (cdpError) { - console.warn("Could not create CDP session:", safeError(cdpError).message); - // Continue without CDP session - basic functionality still works - } - - // Set up event listeners + this.context = browser.contexts()[0] || await browser.newContext(); + if (this.context.pages().length === 0) await this.context.newPage(); await this.setupEventListeners(this.context); - - // Initial tab sync await this.syncTabs(); - - // Navigate to default URL - const defaultUrl = process.env.BROWSERBASE_DEFAULT_URL || "https://www.google.com"; - await this.navigateTo(defaultUrl); - - // Apply viewport override via CDP to match actual window size - console.log(`[Viewport] Applying initial viewport: ${this.currentViewportWidth}x${this.currentViewportHeight}`); await this.applyViewportToAllPages(); - + console.log("Connected to remote browser via CDP"); } catch (error) { - console.error("Failed to connect to browser:", safeError(error).message); + if (this.browser === browser) { + this.browser = null; + this.context = null; + } + await browser.close().catch(() => {}); throw safeError(error); - } finally { - this.isConnecting = false; } } - private async setupEventListeners(context: any): Promise { + private async setupEventListeners(context: BrowserContext): Promise { // Helper to setup page listeners const setupPageListeners = (page: Page) => { page.on("close", async () => { @@ -271,8 +298,13 @@ export class SessionManager { }); // Listen for browser disconnect - this.browser?.on("disconnected", () => { + const browser = this.browser; + browser?.on("disconnected", () => { + if (this.shuttingDown || this.browser !== browser) return; console.log("Browser disconnected"); + this.browser = null; + this.context = null; + this.pageCdpSessions = new WeakMap(); this.handleDisconnect(); }); } @@ -347,7 +379,7 @@ export class SessionManager { private async getTargetIdForPage(page: Page): Promise { try { - const cdp = await page.context().newCDPSession(page); + const cdp = await this.getCdpSessionForPage(page); const targetInfo = await cdp.send("Target.getTargetInfo") as { targetInfo?: { targetId?: string } }; return targetInfo.targetInfo?.targetId || null; } catch (error) { @@ -359,8 +391,11 @@ export class SessionManager { private async getCdpSessionForPage(page: Page): Promise { let cdp = this.pageCdpSessions.get(page); if (!cdp) { - cdp = await page.context().newCDPSession(page); + cdp = page.context().newCDPSession(page); this.pageCdpSessions.set(page, cdp); + cdp.catch(() => { + if (this.pageCdpSessions.get(page) === cdp) this.pageCdpSessions.delete(page); + }); } return cdp; } @@ -653,22 +688,26 @@ export class SessionManager { } private handleDisconnect(): void { - if (this.reconnectAttempts < this.maxReconnectAttempts) { - this.reconnectAttempts++; - console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})`); - - setTimeout(async () => { - try { - await this.connectToBrowser(); - this.reconnectAttempts = 0; - } catch (error) { - console.error("Reconnection failed:", safeError(error).message); - this.handleDisconnect(); - } - }, 2000); - } else { + if (this.shuttingDown || !this.session || this.reconnectTimer) return; + if (this.reconnectAttempts >= this.maxReconnectAttempts) { this.notifyDisconnected(); + return; } + + this.reconnectAttempts++; + const generation = this.generation; + console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})`); + this.reconnectTimer = setTimeout(async () => { + this.reconnectTimer = null; + if (this.shuttingDown || generation !== this.generation) return; + try { + await this.connectToBrowser(); + this.reconnectAttempts = 0; + } catch (error) { + console.error("Reconnection failed:", safeError(error).message); + this.handleDisconnect(); + } + }, 2000); } private notifyTabsUpdated(): void { @@ -708,21 +747,58 @@ export class SessionManager { } } + async shutdown(): Promise { + this.permanentlyClosed = true; + await this.cleanup(); + } + async cleanup(): Promise { + if (this.cleaningUp) return this.cleaningUp; + this.shuttingDown = true; + this.generation++; + if (this.reconnectTimer) clearTimeout(this.reconnectTimer); + this.reconnectTimer = null; + + const cleanup = (async () => { + // Close an existing connection now, interrupting any pending navigation. + const releasing = this.releaseResources(); + // A create/connect already in flight must settle so late resources are released too. + await this.initializing?.catch(() => {}); + await this.connecting?.catch(() => {}); + await releasing; + await this.releaseResources(); + })(); + this.cleaningUp = cleanup; try { - if (this.browser) { - await this.browser.close(); - this.browser = null; - } + await cleanup; + } finally { + if (this.cleaningUp === cleanup) this.cleaningUp = null; + } + } - if (this.session) { - await this.getBrowserbaseClient().stopSession(this.session.id); - this.session = null; - } - } catch (error) { - console.error("Cleanup failed:", safeError(error).message); + private async releaseResources(): Promise { + const browser = this.browser; + const session = this.session; + // Clear ownership before close emits 'disconnected'. + this.browser = null; + this.context = null; + this.session = null; + this.tabs = []; + this.currentUrl = ""; + this.activeTabIndex = 0; + this.reconnectAttempts = 0; + this.pageCdpSessions = new WeakMap(); + + // Failure to close the transport must not skip the remote release request. + const results = await Promise.allSettled([ + browser?.close(), + session ? this.getBrowserbaseClient().stopSession(session.id) : undefined, + ]); + for (const result of results) { + if (result.status === "rejected") console.error("Cleanup failed:", safeError(result.reason).message); } } + } export const sessionManager = new SessionManager(); diff --git a/tests/browserbase-lifecycle.test.cjs b/tests/browserbase-lifecycle.test.cjs new file mode 100644 index 0000000..507233d --- /dev/null +++ b/tests/browserbase-lifecycle.test.cjs @@ -0,0 +1,79 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { BrowserbaseClient } = require('../dist/main/browserbase'); + +function client(t) { + const previous = process.env.BROWSERBASE_API_KEY; + process.env.BROWSERBASE_API_KEY = 'synthetic-api-key'; + t.after(() => { if (previous === undefined) delete process.env.BROWSERBASE_API_KEY; else process.env.BROWSERBASE_API_KEY = previous; }); + return new BrowserbaseClient(); +} + +for (const status of [429, 500, 503]) { + test(`creation does not retry a non-idempotent POST after HTTP ${status}`, async (t) => { + const bb = client(t); + const fetch = t.mock.method(globalThis, 'fetch', async () => new Response('', { status })); + await assert.rejects(bb.createSession()); + assert.equal(fetch.mock.callCount(), 1); + }); +} + +test('creation does not retry after the response is lost', async (t) => { + const bb = client(t); + const fetch = t.mock.method(globalThis, 'fetch', async () => { throw new Error('synthetic network failure'); }); + await assert.rejects(bb.createSession(), /synthetic network failure/); + assert.equal(fetch.mock.callCount(), 1); +}); + +test('retryable reads retain the last HTTP response and do not sleep after the final attempt', async (t) => { + const bb = client(t); + const delays = []; + bb.sleep = async (ms) => delays.push(ms); + const fetch = t.mock.method(globalThis, 'fetch', async () => new Response('', { status: 503 })); + await assert.rejects(bb.getSession('synthetic-session'), /HTTP 503/); + assert.equal(fetch.mock.callCount(), 3); + assert.equal(delays.length, 2); +}); + +test('failed deferred startup releases its cloud session before rejecting', async (t) => { + const bb = client(t); + const requests = []; + t.mock.method(globalThis, 'fetch', async (url, options) => { + requests.push([url, options.method, options.body]); + if (url.endsWith('/sessions')) return Response.json({ id: 'synthetic-session', status: 'PENDING' }); + if (options.method === 'GET') return Response.json({ id: 'synthetic-session', status: 'ERROR' }); + return Response.json({ status: 'COMPLETED' }); + }); + await assert.rejects(bb.createSession(), /Session failed with status: ERROR/); + assert.equal(requests.length, 3); + assert.deepEqual(JSON.parse(requests[2][2]), { status: 'REQUEST_RELEASE' }); +}); + +test('readiness deadline aborts a stalled status request and still releases the session', async (t) => { + const bb = client(t); + // AbortSignal.timeout is unref'ed; keep this synthetic test alive until it fires. + const keepAlive = setTimeout(() => {}, 1000); + t.after(() => clearTimeout(keepAlive)); + let released = false; + let aborted = false; + t.mock.method(globalThis, 'fetch', async (url, options) => { + if (url.endsWith('/sessions')) return Response.json({ id: 'synthetic-session', status: 'PENDING' }); + if (options.method === 'GET') return new Promise((resolve, reject) => { + options.signal.addEventListener('abort', () => { aborted = true; reject(options.signal.reason); }); + }); + released = true; + return Response.json({ status: 'COMPLETED' }); + }); + const started = Date.now(); + await assert.rejects(bb.createSession({ readyTimeoutMs: 30 })); + assert.ok(Date.now() - started < 500); + assert.equal(aborted, true); + assert.equal(released, true); +}); + +test('readiness rejects invalid time limits instead of polling indefinitely', async (t) => { + const bb = client(t); + for (const timeout of [Infinity, NaN, 0, -1]) { + await assert.rejects(bb.waitForSessionReady('synthetic-session', timeout), /positive finite/); + } +}); diff --git a/tests/session-lifecycle.test.cjs b/tests/session-lifecycle.test.cjs new file mode 100644 index 0000000..6e2dddd --- /dev/null +++ b/tests/session-lifecycle.test.cjs @@ -0,0 +1,165 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { EventEmitter } = require('node:events'); +const { chromium } = require('playwright-core'); +const { SessionManager } = require('../dist/main/session'); + +function deferred() { + let resolve, reject; + const promise = new Promise((a, b) => { resolve = a; reject = b; }); + return { promise, resolve, reject }; +} + +function fixture(t) { + const remote = { id: 'synthetic-session', status: 'RUNNING', connectUrl: 'wss://example.com', debugUrl: 'https://example.com/live' }; + const context = new EventEmitter(); + const page = new EventEmitter(); + let url = 'about:blank'; + const navigations = []; + page.url = () => url; + page.title = async () => 'Synthetic page'; + page.context = () => context; + page.goto = async (next) => { url = next; navigations.push(next); }; + context.pages = () => [page]; + let cdpCount = 0; + context.newCDPSession = async () => { + cdpCount++; + return { send: async () => ({ targetInfo: { targetId: 'synthetic-target' } }) }; + }; + const browser = new EventEmitter(); + let connected = true; + browser.contexts = () => [context]; + browser.isConnected = () => connected; + browser.close = async () => { connected = false; browser.emit('disconnected'); }; + const connects = t.mock.method(chromium, 'connectOverCDP', async () => { connected = true; return browser; }); + const released = []; + const client = { createSession: async () => remote, stopSession: async (id) => released.push(id) }; + const manager = new SessionManager(); + manager.browserbaseClient = client; + return { manager, client, browser, page, context, remote, connects, released, navigations, cdpCount: () => cdpCount }; +} + +test('concurrent initialization and renderer reload reuse one cloud session', async (t) => { + const f = fixture(t); + const gate = deferred(); + const create = t.mock.method(f.client, 'createSession', () => gate.promise); + const first = f.manager.initialize(); + const second = f.manager.initialize(); + gate.resolve(f.remote); + assert.deepEqual(await Promise.all([first, second]), [f.remote, f.remote]); + assert.equal(await f.manager.initialize(), f.remote); + assert.equal(create.mock.callCount(), 1); + assert.equal(f.connects.mock.callCount(), 1); + await f.manager.cleanup(); +}); + +test('cleanup cancels a startup and releases a session returned after the window closes', async (t) => { + const f = fixture(t); + const gate = deferred(); + f.client.createSession = () => gate.promise; + const initialized = f.manager.initialize(); + const rejected = assert.rejects(initialized, /cancelled/); + const cleanup = f.manager.cleanup(); + gate.resolve(f.remote); + await Promise.all([cleanup, rejected]); + assert.deepEqual(f.released, ['synthetic-session']); + assert.equal(f.connects.mock.callCount(), 0); + assert.equal(f.manager.getSessionId(), ''); +}); + +test('cleanup releases the cloud session even when closing the transport fails', async (t) => { + const f = fixture(t); + await f.manager.initialize(); + f.browser.close = async () => { throw new Error('synthetic close failure'); }; + await Promise.all([f.manager.cleanup(), f.manager.cleanup()]); + assert.deepEqual(f.released, ['synthetic-session']); + assert.equal(f.manager.getSessionId(), ''); + assert.deepEqual(f.manager.getTabs(), []); +}); + +test('intentional cleanup does not schedule a reconnect', async (t) => { + const f = fixture(t); + await f.manager.initialize(); + await f.manager.cleanup(); + assert.equal(f.manager.reconnectTimer, null); + assert.equal(f.manager.reconnectAttempts, 0); + assert.equal(f.connects.mock.callCount(), 1); +}); + +test('failed CDP connection releases the newly created remote session', async (t) => { + const f = fixture(t); + f.connects.mock.mockImplementation(async () => { throw new Error('synthetic connection failure'); }); + await assert.rejects(f.manager.initialize(), /synthetic connection failure/); + assert.deepEqual(f.released, ['synthetic-session']); + assert.equal(f.manager.getSessionId(), ''); +}); + +test('reconnect preserves navigation and cleanup cancels its retry timer', async (t) => { + const f = fixture(t); + await f.manager.initialize(); + await f.manager.navigateTo('https://example.com/keep-this-page'); + t.mock.timers.enable({ apis: ['setTimeout'] }); + f.browser.emit('disconnected'); + t.mock.timers.tick(2000); + await new Promise(setImmediate); + assert.equal(f.connects.mock.callCount(), 2); + assert.equal(f.page.url(), 'https://example.com/keep-this-page'); + assert.equal(f.navigations.length, 2); + f.browser.emit('disconnected'); + await f.manager.cleanup(); + t.mock.timers.tick(10000); + await new Promise(setImmediate); + assert.equal(f.connects.mock.callCount(), 2); +}); + +test('viewport changes and target lookup share the page CDP connection', async (t) => { + const f = fixture(t); + await f.manager.initialize(); + await Promise.all(Array.from({ length: 20 }, (_, i) => f.manager.updateViewport(800 + i, 600))); + assert.equal(await f.manager.getTargetIdForPage(f.page), 'synthetic-target'); + assert.equal(f.cdpCount(), 1); + await f.manager.cleanup(); +}); + +test('a failed start page keeps a connected session usable', async (t) => { + const f = fixture(t); + f.page.goto = async () => { throw new Error('synthetic navigation failure'); }; + assert.equal(await f.manager.initialize(), f.remote); + assert.equal(f.manager.getSessionId(), 'synthetic-session'); + assert.deepEqual(f.released, []); + await f.manager.cleanup(); +}); + + +test('final shutdown prevents initialization already waiting for window cleanup', async (t) => { + const f = fixture(t); + const created = t.mock.method(f.client, 'createSession', async () => f.remote); + await f.manager.initialize(); + const release = deferred(); + f.client.stopSession = () => release.promise; + const cleanup = f.manager.cleanup(); + const reopened = f.manager.initialize(); + const rejected = assert.rejects(reopened, /Application is shutting down/); + const shutdown = f.manager.shutdown(); + release.resolve(); + await Promise.all([cleanup, shutdown, rejected]); + await assert.rejects(f.manager.initialize(), /Application is shutting down/); + assert.equal(created.mock.callCount(), 1); +}); + + +test('renderer reload receives the existing tabs and address without creating a new session', async (t) => { + const f = fixture(t); + await f.manager.initialize(); + await f.manager.navigateTo('https://example.com/existing-page'); + const sent = []; + f.manager.setMainWindow({ isDestroyed: () => false, webContents: { send: (...args) => sent.push(args) } }); + const { IPC_CHANNELS } = require('../dist/shared/types'); + assert.equal(await f.manager.initialize(), f.remote); + assert.deepEqual(sent, [ + [IPC_CHANNELS.TABS_UPDATED, f.manager.getTabs()], + [IPC_CHANNELS.URL_CHANGED, 'https://example.com/existing-page'], + ]); + assert.equal(f.connects.mock.callCount(), 1); + await f.manager.cleanup(); +});