From 70aaff0fc6373b6dcc06effdfe35f7ab5d1cda7d Mon Sep 17 00:00:00 2001 From: Shrey Pandya <3813908+shrey150@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:58:39 +0000 Subject: [PATCH 1/2] fix: keep tab selection and live view tied to stable targets --- src/main/browserbase.ts | 11 +- src/main/session.ts | 259 +++++++++++++++--------------------- src/shared/types.ts | 2 +- tests/session-tabs.test.cjs | 117 ++++++++++++++++ 4 files changed, 232 insertions(+), 157 deletions(-) create mode 100644 tests/session-tabs.test.cjs diff --git a/src/main/browserbase.ts b/src/main/browserbase.ts index 948f0f7..87dfe2c 100644 --- a/src/main/browserbase.ts +++ b/src/main/browserbase.ts @@ -393,15 +393,16 @@ export class BrowserbaseClient { async getDebugUrlForPage( sessionId: string, pageUrl: string, - options: { fallbackToPrimary?: boolean } = {} + options: { fallbackToPrimary?: boolean; timeoutMs?: number } = {} ): Promise { try { - const debugInfo = await this.fetchDebugInfo(sessionId); + const debugInfo = await this.fetchDebugInfo(sessionId, options.timeoutMs); // Find the page by URL match if (debugInfo.pages) { - const matchingPage = debugInfo.pages.find(p => p.url === pageUrl); + const matches = debugInfo.pages.filter(p => p.url === pageUrl); + const matchingPage = matches.length === 1 ? matches[0] : undefined; if (matchingPage) { const debugUrl = this.getDebugUrlFromPage(matchingPage); if (debugUrl) { @@ -436,9 +437,9 @@ export class BrowserbaseClient { * @param targetId - The CDP target ID for the page * @returns The debug URL for the page, or null if not found */ - async getDebugUrlForTarget(sessionId: string, targetId: string): Promise { + async getDebugUrlForTarget(sessionId: string, targetId: string, timeoutMs?: number): Promise { try { - const debugInfo = await this.fetchDebugInfo(sessionId); + const debugInfo = await this.fetchDebugInfo(sessionId, timeoutMs); const matchingPage = debugInfo.pages?.find((page) => page.id === targetId); if (!matchingPage) { diff --git a/src/main/session.ts b/src/main/session.ts index 688dc2a..81685bf 100644 --- a/src/main/session.ts +++ b/src/main/session.ts @@ -44,7 +44,12 @@ export class SessionManager { private tabs: TabInfo[] = []; private pageCdpSessions = new WeakMap>(); private currentUrl: string = ""; - private activeTabIndex: number = 0; + private activePage: Page | null = null; + private pageIds = new WeakMap(); + private pageTargetIds = new WeakMap(); + private nextTabId = 0; + private tabSyncRevision = 0; + private selectionRevision = 0; private reconnectAttempts = 0; private maxReconnectAttempts = 3; private initializing: Promise | null = null; @@ -260,15 +265,21 @@ export class SessionManager { // Helper to setup page listeners const setupPageListeners = (page: Page) => { page.on("close", async () => { - console.log("Page closed"); + if (this.context !== context) return; + const wasActive = this.activePage === page; + if (wasActive) { + const index = this.tabs.findIndex((tab) => tab.id === this.getPageId(page)); + this.activePage = context.pages()[Math.max(0, index - 1)] || null; + this.selectionRevision++; + } await this.syncTabs(); + if (wasActive && this.activePage) await this.updateActiveDebugUrl(this.activePage); }); // Listen for URL changes page.on("framenavigated", async (frame: any) => { - if (frame === page.mainFrame()) { + if (this.context === context && frame === page.mainFrame()) { await this.syncTabs(); - this.notifyUrlChanged(page.url()); } }); @@ -288,6 +299,7 @@ export class SessionManager { // Listen for new pages (tabs) context.on("page", async (page: Page) => { console.log("New page created"); + if (this.context !== context) return; setupPageListeners(page); await this.syncTabs(); }); @@ -309,50 +321,46 @@ export class SessionManager { }); } + private getPageId(page: Page): string { + let id = this.pageIds.get(page); + if (!id) { + id = `tab-${this.nextTabId++}`; + this.pageIds.set(page, id); + } + return id; + } + private async syncTabs(): Promise { - if (!this.browser || !this.context) return; + const context = this.context; + if (!this.browser || !context) return; + const revision = ++this.tabSyncRevision; + const pages = context.pages(); + const previousTarget = this.tabs.find((tab) => tab.active)?.targetId; try { - const pages = this.context.pages(); - - // Ensure activeTabIndex is valid - if (this.activeTabIndex >= pages.length) { - this.activeTabIndex = Math.max(0, pages.length - 1); - } - - this.tabs = await Promise.all( - pages.map(async (page, index) => { - let title = ""; - let url = ""; - - try { - title = await page.title(); - url = page.url(); - } catch { - // Page might be loading - } - - return { - id: `tab-${index}`, - targetId: `target-${index}`, - title: title || "New Tab", - url: url || "about:blank", - active: index === this.activeTabIndex, - favicon: this.getFaviconUrl(url), - }; - }) - ); - - // Update current URL from active tab - if (pages[this.activeTabIndex]) { - try { - this.currentUrl = pages[this.activeTabIndex].url(); - } catch { - // Page might be loading - } + const tabs = await Promise.all(pages.map(async (page) => { + let title = ""; + try { title = await page.title(); } catch { /* The page may be navigating or closed. */ } + const url = page.url(); + return { + id: this.getPageId(page), + targetId: await this.getTargetIdForPage(page) || "", + title: title || "New Tab", + url: url || "about:blank", + active: false, + favicon: this.getFaviconUrl(url), + }; + })); + if (this.context !== context || revision !== this.tabSyncRevision) return; + if (pages.length !== context.pages().length || pages.some((page, i) => context.pages()[i] !== page)) return; + + if (!this.activePage || !pages.includes(this.activePage)) { + const previousIndex = previousTarget ? tabs.findIndex((tab) => tab.targetId === previousTarget) : -1; + this.activePage = pages[Math.max(0, previousIndex)] || null; } - + this.tabs = tabs.map((tab, i) => ({ ...tab, active: pages[i] === this.activePage })); this.notifyTabsUpdated(); + this.notifyUrlChanged(this.activePage?.url() || ""); } catch (error) { console.error("Failed to sync tabs:", safeError(error).message); } @@ -370,7 +378,7 @@ export class SessionManager { private getActivePage(): Page | null { if (!this.context) return null; const pages = this.context.pages(); - return pages[this.activeTabIndex] || pages[0] || null; + return this.activePage && pages.includes(this.activePage) ? this.activePage : pages[0] || null; } private sleep(ms: number): Promise { @@ -378,10 +386,14 @@ export class SessionManager { } private async getTargetIdForPage(page: Page): Promise { + const cached = this.pageTargetIds.get(page); + if (cached) return cached; try { const cdp = await this.getCdpSessionForPage(page); const targetInfo = await cdp.send("Target.getTargetInfo") as { targetInfo?: { targetId?: string } }; - return targetInfo.targetInfo?.targetId || null; + const targetId = targetInfo.targetInfo?.targetId || null; + if (targetId) this.pageTargetIds.set(page, targetId); + return targetId; } catch (error) { console.warn("Failed to read page target ID:", safeError(error).message); return null; @@ -412,7 +424,8 @@ export class SessionManager { private async waitForDebugUrlForPage( page: Page, timeoutMs: number = 5000, - pollIntervalMs: number = 150 + pollIntervalMs: number = 150, + selectionRevision: number = this.selectionRevision ): Promise { if (!this.session) { return null; @@ -422,16 +435,21 @@ export class SessionManager { const targetId = await this.getTargetIdForPage(page); const startedAt = Date.now(); - while (Date.now() - startedAt <= timeoutMs) { + while (Date.now() - startedAt < timeoutMs) { + if (this.session?.id !== sessionId || this.getActivePage() !== page || selectionRevision !== this.selectionRevision) return null; let debugUrl: string | null = null; if (targetId) { - debugUrl = await this.getBrowserbaseClient().getDebugUrlForTarget(sessionId, targetId); + debugUrl = await this.getBrowserbaseClient().getDebugUrlForTarget( + sessionId, targetId, Math.max(1, timeoutMs - (Date.now() - startedAt)) + ); } - if (!debugUrl && (!targetId || page.url() !== "about:blank")) { + // Never match by URL when we know the target: multiple tabs can share a URL. + if (!debugUrl && !targetId) { debugUrl = await this.getBrowserbaseClient().getDebugUrlForPage(sessionId, page.url(), { fallbackToPrimary: false, + timeoutMs: Math.max(1, timeoutMs - (Date.now() - startedAt)), }); } @@ -469,7 +487,6 @@ export class SessionManager { const activePage = this.getActivePage(); if (activePage) { await activePage.goto(url, { waitUntil: "domcontentloaded", timeout: 60000 }); - this.currentUrl = url; await this.syncTabs(); } } catch (error) { @@ -533,124 +550,60 @@ export class SessionManager { } } - async newTab(): Promise { - if (!this.context) return; - - try { - const newPage = await this.context.newPage(); - const pages = this.context.pages(); - this.activeTabIndex = pages.indexOf(newPage); - - // Apply viewport to the new tab - console.log(`[Viewport] Applying viewport to new tab: ${this.currentViewportWidth}x${this.currentViewportHeight}`); - await this.applyViewportToPage(newPage, this.currentViewportWidth, this.currentViewportHeight); - - this.notifyDebugUrlLoading(); - await this.syncTabs(); + private async updateActiveDebugUrl(page: Page, revision = this.selectionRevision): Promise { + const debugUrl = await this.waitForDebugUrlForPage(page, 3000, 150, revision); + if (!debugUrl || this.getActivePage() !== page || revision !== this.selectionRevision || !this.session) return false; + this.session.debugUrl = debugUrl; + this.notifyDebugUrlChanged(debugUrl); + return true; + } - let newDebugUrl = await this.waitForDebugUrlForPage(newPage, 3000); - if (newDebugUrl) { - this.notifyDebugUrlChanged(newDebugUrl); - } else { - console.warn("Timed out waiting for debug URL for new page before navigation"); - } + private async activatePage(page: Page): Promise { + const revision = ++this.selectionRevision; + this.activePage = page; + this.notifyDebugUrlLoading(); + this.notifyUrlChanged(page.url()); + await page.bringToFront(); + if (this.getActivePage() !== page || revision !== this.selectionRevision) return false; + await this.applyViewportToPage(page, this.currentViewportWidth, this.currentViewportHeight); + await this.syncTabs(); + return this.updateActiveDebugUrl(page, revision); + } - // Navigate to Google like the initial tab + async newTab(): Promise { + const context = this.context; + if (!context) return; + try { + const page = await context.newPage(); + if (this.context !== context) return; + const updated = await this.activatePage(page); + const revision = this.selectionRevision; const defaultUrl = process.env.BROWSERBASE_DEFAULT_URL || "https://www.google.com"; - await newPage.goto(defaultUrl, { waitUntil: "domcontentloaded", timeout: 60000 }); - + await page.goto(defaultUrl, { waitUntil: "domcontentloaded", timeout: 60000 }); await this.syncTabs(); - - if (!newDebugUrl) { - newDebugUrl = await this.waitForDebugUrlForPage(newPage, 3000); - if (newDebugUrl) { - this.notifyDebugUrlChanged(newDebugUrl); - } else { - console.warn("Timed out waiting for debug URL for new page after navigation"); - } - } + if (!updated && this.getActivePage() === page) await this.updateActiveDebugUrl(page, revision); } catch (error) { console.error("New tab failed:", safeError(error).message); } } async closeTab(tabId: string): Promise { - if (!this.context) return; - + const pages = this.context?.pages(); + const page = pages?.find((candidate) => this.getPageId(candidate) === tabId); + if (!pages || !page || pages.length <= 1) return; try { - const tabIndex = parseInt(tabId.replace("tab-", ""), 10); - const pages = this.context.pages(); - - if (pages[tabIndex] && pages.length > 1) { - await pages[tabIndex].close(); - - // Adjust active tab if necessary - if (tabIndex <= this.activeTabIndex) { - this.activeTabIndex = Math.max(0, this.activeTabIndex - 1); - } - - await this.syncTabs(); - - // Update debug URL for the new active tab - if (this.session) { - const sessionId = this.session.id; - const remainingPages = this.context.pages(); - const activePage = remainingPages[this.activeTabIndex]; - if (activePage) { - setTimeout(async () => { - try { - const pageUrl = activePage.url(); - const newDebugUrl = await this.getBrowserbaseClient().getDebugUrlForPage(sessionId, pageUrl); - if (newDebugUrl) { - this.notifyDebugUrlChanged(newDebugUrl); - } - } catch (e) { - console.error("Failed to get debug URL after close:", safeError(e).message); - } - }, 300); - } - } - } + await page.close(); + await this.syncTabs(); } catch (error) { console.error("Close tab failed:", safeError(error).message); } } async switchTab(tabId: string): Promise { - if (!this.context) return; - + const page = this.context?.pages().find((candidate) => this.getPageId(candidate) === tabId); + if (!page) return; try { - const tabIndex = parseInt(tabId.replace("tab-", ""), 10); - const pages = this.context.pages(); - - if (pages[tabIndex]) { - await pages[tabIndex].bringToFront(); - this.activeTabIndex = tabIndex; - this.notifyDebugUrlLoading(); - - // Update URL to match new active tab - try { - this.currentUrl = pages[tabIndex].url(); - this.notifyUrlChanged(this.currentUrl); - } catch { - // Page might be loading - } - - // Get the updated debug URL for this specific page and notify renderer - if (this.session && pages[tabIndex]) { - try { - const pageUrl = pages[tabIndex].url(); - const newDebugUrl = await this.getBrowserbaseClient().getDebugUrlForPage(this.session.id, pageUrl); - if (newDebugUrl) { - this.notifyDebugUrlChanged(newDebugUrl); - } - } catch (e) { - console.error("Failed to get debug URL for page:", safeError(e).message); - } - } - - await this.syncTabs(); - } + await this.activatePage(page); } catch (error) { console.error("Switch tab failed:", safeError(error).message); } @@ -785,7 +738,11 @@ export class SessionManager { this.session = null; this.tabs = []; this.currentUrl = ""; - this.activeTabIndex = 0; + this.activePage = null; + this.pageIds = new WeakMap(); + this.pageTargetIds = new WeakMap(); + this.tabSyncRevision++; + this.selectionRevision++; this.reconnectAttempts = 0; this.pageCdpSessions = new WeakMap(); diff --git a/src/shared/types.ts b/src/shared/types.ts index 8e60102..3d8fd3c 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -68,7 +68,7 @@ export interface SessionConfig { * Synchronized from Playwright pages and sent to the renderer for UI updates. */ export interface TabInfo { - /** Unique tab identifier (format: "tab-{index}") */ + /** Stable tab identifier (format: "tab-{number}") */ id: string; /** CDP target ID for the page */ targetId: string; diff --git a/tests/session-tabs.test.cjs b/tests/session-tabs.test.cjs new file mode 100644 index 0000000..a3bfa89 --- /dev/null +++ b/tests/session-tabs.test.cjs @@ -0,0 +1,117 @@ +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'); +const { IPC_CHANNELS } = require('../dist/shared/types'); + +function deferred() { + let resolve; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +async function fixture(t) { + const context = new EventEmitter(); + const pages = []; + for (let i = 0; i < 3; i++) { + const page = new EventEmitter(); + const frame = {}; + page.target = `target-${i}`; + page.currentUrl = 'https://example.com/same-url'; + page.url = () => page.currentUrl; + page.title = async () => page.target; + page.context = () => context; + page.mainFrame = () => frame; + page.bringToFront = async () => {}; + page.goto = async (url) => { page.currentUrl = url; }; + page.close = async () => { pages.splice(pages.indexOf(page), 1); page.emit('close'); }; + pages.push(page); + } + context.pages = () => [...pages]; + context.newCDPSession = async (page) => ({ send: async (method) => method === 'Target.getTargetInfo' ? { targetInfo: { targetId: page.target } } : {} }); + const browser = new EventEmitter(); + browser.contexts = () => [context]; + browser.isConnected = () => true; + browser.close = async () => {}; + t.mock.method(chromium, 'connectOverCDP', async () => browser); + const manager = new SessionManager(); + const lookups = []; + const client = { + createSession: async () => ({ id: 'synthetic-session', status: 'RUNNING', connectUrl: 'wss://example.com', debugUrl: 'https://example.com/target-0' }), + stopSession: async () => {}, + getDebugUrlForTarget: async (_, target) => { lookups.push(target); return `https://example.com/${target}`; }, + getDebugUrlForPage: async () => { throw new Error('URL matching must not be used when the target is known'); }, + }; + manager.browserbaseClient = client; + const events = []; + manager.setMainWindow({ isDestroyed: () => false, getContentBounds: () => ({ width: 800, height: 600 }), webContents: { getZoomFactor: () => 1, send: (...args) => events.push(args) } }); + await manager.initialize(); + pages[0].currentUrl = pages[1].currentUrl; + t.after(() => manager.cleanup()); + return { manager, pages, context, client, events, lookups }; +} + +test('duplicate-URL tabs select their exact CDP target and persist the active debug URL', async (t) => { + const f = await fixture(t); + const second = f.manager.getTabs()[1]; + await f.manager.switchTab(second.id); + assert.deepEqual(f.lookups, ['target-1']); + assert.equal(f.manager.getDebugUrl(), 'https://example.com/target-1'); + assert.equal(f.manager.getAutomationInfo().debugUrl, 'https://example.com/target-1'); + assert.equal(f.manager.getTabs().find((tab) => tab.active).targetId, 'target-1'); +}); + +test('closing an earlier tab preserves active page identity and stable tab IDs', async (t) => { + const f = await fixture(t); + const [first, second, third] = f.manager.getTabs(); + await f.manager.switchTab(third.id); + await f.manager.closeTab(first.id); + assert.deepEqual(f.manager.getTabs().map((tab) => tab.id), [second.id, third.id]); + assert.equal(f.manager.getTabs().find((tab) => tab.active).id, third.id); + await f.manager.closeTab(first.id); // A stale click must not close the next tab. + assert.equal(f.pages.length, 2); +}); + +test('background navigation never replaces the active address bar', async (t) => { + const f = await fixture(t); + await f.manager.switchTab(f.manager.getTabs()[1].id); + f.events.length = 0; + f.pages[2].currentUrl = 'https://example.com/background'; + f.pages[2].emit('framenavigated', f.pages[2].mainFrame()); + await new Promise(setImmediate); + const addresses = f.events.filter(([channel]) => channel === IPC_CHANNELS.URL_CHANGED).map(([, url]) => url); + assert.deepEqual(addresses, ['https://example.com/same-url']); + assert.equal(f.manager.getCurrentUrl(), 'https://example.com/same-url'); +}); + +test('a late live-view response cannot overwrite the more recent tab selection', async (t) => { + const f = await fixture(t); + const gate = deferred(); + const requested = deferred(); + f.client.getDebugUrlForTarget = async (_, target) => { + if (target === 'target-1') { requested.resolve(); return gate.promise; } + return `https://example.com/${target}`; + }; + const second = f.manager.switchTab(f.manager.getTabs()[1].id); + await requested.promise; + await f.manager.switchTab(f.manager.getTabs()[2].id); + gate.resolve('https://example.com/target-1'); + await second; + assert.equal(f.manager.getDebugUrl(), 'https://example.com/target-2'); + const debugChanges = f.events.filter(([channel]) => channel === IPC_CHANNELS.DEBUG_URL_CHANGED).map(([, url]) => url); + assert.deepEqual(debugChanges, ['https://example.com/target-2']); +}); + +test('a slow old tab sync cannot resurrect a closed page', async (t) => { + const f = await fixture(t); + const gate = deferred(); + const original = f.pages[0]; + original.title = () => gate.promise; + const oldSync = f.manager.syncTabs(); + await f.manager.closeTab(f.manager.getTabs()[0].id); + gate.resolve('Removed tab'); + await oldSync; + assert.equal(f.manager.getTabs().length, 2); + assert.ok(f.manager.getTabs().every((tab) => tab.targetId !== original.target)); +}); From 9a7ba64aefd9bfe9b9dfdbe623175416a213d69c Mon Sep 17 00:00:00 2001 From: Shrey Pandya <3813908+shrey150@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:00:11 +0000 Subject: [PATCH 2/2] fix: finish tab loading failures and await current tab state --- src/main/session.ts | 17 ++++++++++++++- tests/session-tabs.test.cjs | 43 +++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/src/main/session.ts b/src/main/session.ts index 81685bf..afe9f97 100644 --- a/src/main/session.ts +++ b/src/main/session.ts @@ -49,6 +49,7 @@ export class SessionManager { private pageTargetIds = new WeakMap(); private nextTabId = 0; private tabSyncRevision = 0; + private tabSyncPromise: Promise | null = null; private selectionRevision = 0; private reconnectAttempts = 0; private maxReconnectAttempts = 3; @@ -331,6 +332,16 @@ export class SessionManager { } private async syncTabs(): Promise { + let pending = this.synchronizeTabs(); + this.tabSyncPromise = pending; + do { + await pending; + if (this.tabSyncPromise === pending) return; + pending = this.tabSyncPromise!; + } while (pending); + } + + private async synchronizeTabs(): Promise { const context = this.context; if (!this.browser || !context) return; const revision = ++this.tabSyncRevision; @@ -552,7 +563,11 @@ export class SessionManager { private async updateActiveDebugUrl(page: Page, revision = this.selectionRevision): Promise { const debugUrl = await this.waitForDebugUrlForPage(page, 3000, 150, revision); - if (!debugUrl || this.getActivePage() !== page || revision !== this.selectionRevision || !this.session) return false; + if (this.getActivePage() !== page || revision !== this.selectionRevision || !this.session) return false; + if (!debugUrl) { + this.notifyError(new Error("Live view is unavailable for this tab. Select the tab again to retry.")); + return false; + } this.session.debugUrl = debugUrl; this.notifyDebugUrlChanged(debugUrl); return true; diff --git a/tests/session-tabs.test.cjs b/tests/session-tabs.test.cjs index a3bfa89..fb22da3 100644 --- a/tests/session-tabs.test.cjs +++ b/tests/session-tabs.test.cjs @@ -115,3 +115,46 @@ test('a slow old tab sync cannot resurrect a closed page', async (t) => { assert.equal(f.manager.getTabs().length, 2); assert.ok(f.manager.getTabs().every((tab) => tab.targetId !== original.target)); }); + + +test('a missing live-view target ends loading with an error for the current selection', async (t) => { + const f = await fixture(t); + f.manager.waitForDebugUrlForPage = async () => null; + await f.manager.switchTab(f.manager.getTabs()[1].id); + const errors = f.events.filter(([channel]) => channel === IPC_CHANNELS.SESSION_ERROR); + assert.equal(errors.length, 1); + assert.match(errors[0][1], /Select the tab again to retry/); +}); + +test('a timed out lookup for a previous tab does not show an error over the active tab', async (t) => { + const f = await fixture(t); + const gate = deferred(); + const requested = deferred(); + f.manager.waitForDebugUrlForPage = async (page) => { + if (page.target === 'target-1') { requested.resolve(); return gate.promise; } + return `https://example.com/${page.target}`; + }; + const second = f.manager.switchTab(f.manager.getTabs()[1].id); + await requested.promise; + await f.manager.switchTab(f.manager.getTabs()[2].id); + gate.resolve(null); + await second; + assert.equal(f.events.filter(([channel]) => channel === IPC_CHANNELS.SESSION_ERROR).length, 0); +}); + +test('tab operations await the newer sync when their own snapshot is superseded', async (t) => { + const f = await fixture(t); + const first = deferred(); + const second = deferred(); + let calls = 0; + f.pages[0].title = () => (++calls === 1 ? first.promise : second.promise); + let returned = false; + const oldSync = f.manager.syncTabs().then(() => { returned = true; }); + const newSync = f.manager.syncTabs(); + first.resolve('Old title'); + await new Promise(setImmediate); + assert.equal(returned, false); + second.resolve('Current title'); + await Promise.all([oldSync, newSync]); + assert.equal(f.manager.getTabs()[0].title, 'Current title'); +});