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
43 changes: 23 additions & 20 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { IPC_CHANNELS } from "../shared/types";
import { getConfigSearchPaths, loadEnvironmentConfig } from "./config";
import { AutomationServer, getAutomationServerPort, isAutomationServerEnabled } from "./automation";
import { secureWindow } from "./security";
import { parseViewport } from "./viewport";

let mainWindow: BrowserWindow | null = null;
let resizeTimeout: ReturnType<typeof setTimeout> | null = null;
Expand Down Expand Up @@ -345,23 +346,14 @@ async function createWindow(): Promise<void> {
mainWindow.maximize();
}

// Save window state on resize/move
// The renderer reports the actual live-view size, including toolbars and zoom.
mainWindow.on("resize", () => {
if (mainWindow) {
saveWindowState(mainWindow);
// Debounce viewport updates to avoid too many CDP calls during drag
if (resizeTimeout) {
clearTimeout(resizeTimeout);
}
resizeTimeout = setTimeout(() => {
if (mainWindow) {
const bounds = mainWindow.getContentBounds();
const chromeUIHeight = 76; // Tab bar (36px) + nav bar (40px)
const viewportHeight = Math.max(400, bounds.height - chromeUIHeight);
sessionManager.updateViewport(bounds.width, viewportHeight);
}
}, 150); // 150ms debounce
}
const window = mainWindow;
if (resizeTimeout) clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => {
resizeTimeout = null;
if (window && !window.isDestroyed()) saveWindowState(window);
}, 100);
});
mainWindow.on("move", () => mainWindow && saveWindowState(mainWindow));
mainWindow.on("close", () => mainWindow && saveWindowState(mainWindow));
Expand All @@ -373,17 +365,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
mainWindow.webContents.on("did-finish-load", async () => {
// Keep this callback tied to its window while initialization is in flight.
const window = mainWindow;
const isCurrentWindow = () => !window.isDestroyed() && mainWindow === window;
window.webContents.on("did-finish-load", async () => {
if (!isCurrentWindow()) return;
console.log("Renderer loaded, initializing Browserbase session...");

try {
// Measure before provisioning so the initial remote surface matches the guest.
const viewport = parseViewport(await window.webContents.executeJavaScript(`(() => {
const rect = document.getElementById("live-view-frame")?.getBoundingClientRect();
return rect ? { width: Math.round(rect.width), height: Math.round(rect.height) } : null;
})()`));
if (!isCurrentWindow()) return;
if (viewport) await sessionManager.updateViewport(viewport.width, viewport.height);
if (!isCurrentWindow()) return;
const bbSession = await sessionManager.initialize();
console.log("Session initialized, sending SESSION_CREATED event");
mainWindow?.webContents.send(IPC_CHANNELS.SESSION_CREATED, bbSession.id);
if (isCurrentWindow()) 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 (isCurrentWindow()) window.webContents.send(IPC_CHANNELS.SESSION_ERROR, (error as Error).message);
}
});

Expand Down
9 changes: 9 additions & 0 deletions src/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import { ipcMain, BrowserWindow, IpcMainEvent, IpcMainInvokeEvent } from "electr
import { IPC_CHANNELS, ScrollInputEvent } from "../shared/types";
import { sessionManager } from "./session";
import { isTrustedRenderer } from "./security";
import { ViewportUpdater } from "./viewport";

let viewportUpdater: ViewportUpdater | null = null;

function isAcceleratedScrollEnabled(): boolean {
const value = process.env.BROWSERBASE_ACCELERATED_SCROLL;
Expand Down Expand Up @@ -44,6 +47,10 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
});
};

viewportUpdater?.dispose();
viewportUpdater = new ViewportUpdater(({ width, height }) => sessionManager.updateViewport(width, height));
on(IPC_CHANNELS.VIEWPORT_CHANGED, (_event, viewport: unknown) => viewportUpdater?.push(viewport));

// Navigation handlers
handle(IPC_CHANNELS.NAVIGATE_TO, async (_event, url: string) => {
try {
Expand Down Expand Up @@ -189,6 +196,8 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
* memory leaks and ensure clean shutdown.
*/
export function removeIpcHandlers(): void {
viewportUpdater?.dispose();
viewportUpdater = null;
const channels = Object.values(IPC_CHANNELS);
channels.forEach((channel) => {
ipcMain.removeHandler(channel);
Expand Down
4 changes: 4 additions & 0 deletions src/main/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ contextBridge.exposeInMainWorld("electronAPI", {
dispatchScroll: (scrollEvent: import("../shared/types").ScrollInputEvent) =>
ipcRenderer.send(IPC_CHANNELS.INPUT_SCROLL, scrollEvent),

updateViewport: (width: number, height: number) =>
ipcRenderer.send(IPC_CHANNELS.VIEWPORT_CHANGED, { width, height }),

// Tabs
newTab: () => ipcRenderer.invoke(IPC_CHANNELS.TAB_NEW),
closeTab: (tabId: string) => ipcRenderer.invoke(IPC_CHANNELS.TAB_CLOSE, tabId),
Expand Down Expand Up @@ -142,6 +145,7 @@ declare global {
navigateHome: () => Promise<{ success: boolean; error?: string }>;
isAcceleratedScrollEnabled: () => Promise<boolean>;
dispatchScroll: (scrollEvent: import("../shared/types").ScrollInputEvent) => void;
updateViewport: (width: number, height: number) => void;
newTab: () => Promise<{ success: boolean; error?: string }>;
closeTab: (tabId: string) => Promise<{ success: boolean; error?: string }>;
switchTab: (tabId: string) => Promise<{ success: boolean; error?: string }>;
Expand Down
30 changes: 3 additions & 27 deletions src/main/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,37 +111,13 @@ export class SessionManager {

async initialize(): Promise<BrowserbaseSession> {
try {
// Calculate viewport size based on window content area
// Chrome UI elements: tab bar (36px), nav bar (40px) = 76px total
const windowBounds = this.mainWindow?.getContentBounds();
const chromeUIHeight = 76; // 36 (tab bar) + 40 (nav bar)

// Use actual window size, with reasonable defaults
const defaultWidth = 1440;
const defaultHeight = 900;

const contentWidth = windowBounds?.width || defaultWidth;
const contentHeight = windowBounds
? Math.max(400, windowBounds.height - chromeUIHeight)
: defaultHeight - chromeUIHeight;

// Store for later use with new tabs
this.currentViewportWidth = contentWidth;
this.currentViewportHeight = contentHeight;

// For session creation, use larger viewport to avoid issues - we'll override with CDP later
const viewportWidth = Math.max(2560, contentWidth);
const viewportHeight = Math.max(1440, contentHeight);

console.log("Window content bounds:", windowBounds);
console.log(`Chrome UI height: ${chromeUIHeight}px`);
console.log(`Actual viewport to use: ${contentWidth}x${contentHeight}`);
console.log(`Creating session with initial viewport: ${viewportWidth}x${viewportHeight} (will override with CDP)`);
// The renderer supplies measured content dimensions before initialization.
const viewportWidth = this.currentViewportWidth;
const viewportHeight = this.currentViewportHeight;

// 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({
Expand Down
53 changes: 53 additions & 0 deletions src/main/viewport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { ViewportConfig } from "../shared/types";

/** Reject hidden elements, malformed IPC values, and unreasonably large surfaces. */
export function parseViewport(value: unknown): ViewportConfig | null {
if (!value || typeof value !== "object") return null;
const { width, height } = value as Partial<ViewportConfig>;
if (typeof width !== "number" || typeof height !== "number" ||
!Number.isInteger(width) || !Number.isInteger(height) ||
width < 1 || height < 1 || width > 8192 || height > 8192) return null;
return { width, height };
}

/** Coalesce resize bursts and serialize CDP updates so the newest size wins. */
export class ViewportUpdater {
private pending: ViewportConfig | null = null;
private timer: ReturnType<typeof setTimeout> | null = null;
private applying = false;
private disposed = false;

constructor(private update: (viewport: ViewportConfig) => Promise<void>, private delayMs = 100) {}

push(value: unknown): void {
const viewport = parseViewport(value);
if (!viewport || this.disposed) return;
this.pending = viewport;
if (!this.timer && !this.applying) {
this.timer = setTimeout(() => { void this.flush(); }, this.delayMs);
}
}

private async flush(): Promise<void> {
this.timer = null;
const viewport = this.pending;
this.pending = null;
if (!viewport || this.disposed) return;
this.applying = true;
try {
await this.update(viewport);
} catch {
console.error("Failed to update the remote viewport");
} finally {
this.applying = false;
if (this.pending && !this.disposed) this.push(this.pending);
}
}

dispose(): void {
this.disposed = true;
this.pending = null;
if (this.timer) clearTimeout(this.timer);
this.timer = null;
}
}
22 changes: 22 additions & 0 deletions src/renderer/components/ContentArea.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export class ContentArea {
private isLoaded: boolean = false;
private loadTimeout: ReturnType<typeof setTimeout> | null = null;
private acceleratedScrollEnabled: boolean = false;
private resizeObserver: ResizeObserver | null = null;
private viewportTimeout: ReturnType<typeof setTimeout> | null = null;

constructor() {
console.log("[ContentArea] Initializing...");
Expand All @@ -19,10 +21,30 @@ export class ContentArea {
});

this.setupEventListeners();
this.observeViewport();
void this.loadInputSettings();
console.log("[ContentArea] Initialized successfully");
}

private observeViewport(): void {
if (!this.debugView) return;
this.resizeObserver = new ResizeObserver(() => {
if (this.viewportTimeout) return;
this.viewportTimeout = setTimeout(() => {
this.viewportTimeout = null;
const rect = this.debugView?.getBoundingClientRect();
if (rect && rect.width > 0 && rect.height > 0) {
window.electronAPI.updateViewport(Math.round(rect.width), Math.round(rect.height));
}
}, 100);
});
this.resizeObserver.observe(this.debugView);
window.addEventListener("beforeunload", () => {
this.resizeObserver?.disconnect();
if (this.viewportTimeout) clearTimeout(this.viewportTimeout);
}, { once: true });
}

private async loadInputSettings(): Promise<void> {
try {
this.acceleratedScrollEnabled = await window.electronAPI.isAcceleratedScrollEnabled();
Expand Down
1 change: 1 addition & 0 deletions src/shared/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ export const IPC_CHANNELS = {

// Input forwarding
INPUT_SCROLL: "input:scroll",
VIEWPORT_CHANGED: "viewport:changed",
GET_ACCELERATED_SCROLL_ENABLED: "input:get-accelerated-scroll-enabled",

// Tab management
Expand Down
78 changes: 78 additions & 0 deletions tests/electron-startup.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Run after npm run build: electron tests/electron-startup.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { app, BrowserWindow } = require('electron');
const { sessionManager } = require('../dist/main/session');
const config = require('../dist/main/config');
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-startup-test-'));
app.setPath('userData', profile);
// Exercise macOS's persistent app lifecycle on every test host.
Object.defineProperty(process, 'platform', { value: 'darwin' });
process.env.BROWSERBASE_API_KEY = 'synthetic-test-key';
delete process.env.BROWSERBASE_AUTOMATION_SERVER;
config.loadEnvironmentConfig = () => [];
let stage = 'measurement';
let releaseMeasurement;
let releaseViewport;
let measured = false;
let initialized = 0;
sessionManager.initialize = async () => { initialized++; return { id: 'synthetic-session' }; };
sessionManager.cleanup = async () => {};
sessionManager.getDebugUrl = () => '';
sessionManager.updateViewport = async () => {
if (stage === 'viewport' && measured && !releaseViewport) {
await new Promise(resolve => { releaseViewport = resolve; });
}
};
app.on('web-contents-created', (_event, contents) => {
const execute = contents.executeJavaScript.bind(contents);
contents.executeJavaScript = (code, ...args) => {
if (code.includes('const rect = document.getElementById("live-view-frame")')) {
measured = true;
if (stage === 'measurement') return new Promise(resolve => { releaseMeasurement = resolve; });
}
return execute(code, ...args);
};
});
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(check) {
for (let i = 0; i < 100; i++) { if (await check()) return; await delay(20); }
throw new Error('Timed out waiting for window startup');
}
const timeout = setTimeout(() => { console.error('Startup test timed out'); app.exit(1); }, 15000);
app.whenReady().then(async () => {
let passed = false;
try {
await until(() => releaseMeasurement);
BrowserWindow.getAllWindows()[0].close();
await until(() => BrowserWindow.getAllWindows().length === 0);
releaseMeasurement({ width: 800, height: 520 });
await delay(100);
assert.equal(initialized, 0, 'a closed window cannot start a session after measurement');

stage = 'viewport'; measured = false;
app.emit('activate');
await until(() => releaseViewport);
BrowserWindow.getAllWindows()[0].close();
await until(() => BrowserWindow.getAllWindows().length === 0);
releaseViewport();
await delay(100);
assert.equal(initialized, 0, 'a closed window cannot start a session after a viewport update');

stage = 'ready';
app.emit('activate');
await until(() => initialized === 1);
assert.equal(BrowserWindow.getAllWindows().length, 1);
console.log('PASS: stale measurement and viewport updates cannot initialize a closed window; reopening starts normally');
passed = true;
} catch (error) { console.error(error); }
finally {
clearTimeout(timeout);
for (const window of BrowserWindow.getAllWindows()) window.destroy();
fs.rmSync(profile, { recursive: true, force: true });
app.exit(passed ? 0 : 1);
}
});
require('../dist/main/index');
Loading