🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
enhance: browser_som_screenshot (#3059)
Puzhen Zhang1408c25d11f4
diff --git a/camel/toolkits/hybrid_browser_toolkit/config_loader.py b/camel/toolkits/hybrid_browser_toolkit/config_loader.pyindex aed2a9156..e8a6130be 100644--- a/camel/toolkits/hybrid_browser_toolkit/config_loader.py+++ b/camel/toolkits/hybrid_browser_toolkit/config_loader.py@@ -44,6 +44,9 @@ class BrowserConfig:connect_over_cdp: bool = Falsecdp_url: Optional[str] = None+ # Full visual mode configuration+ full_visual_mode: bool = False+@dataclassclass ToolkitConfig:@@ -116,6 +119,8 @@ class ConfigLoader:toolkit_kwargs["session_id"] = valueelif key == "enabledTools":toolkit_kwargs["enabled_tools"] = value+ elif key == "fullVisualMode":+ browser_kwargs["full_visual_mode"] = valuebrowser_config = BrowserConfig(**browser_kwargs)toolkit_config = ToolkitConfig(**toolkit_kwargs)@@ -146,6 +151,7 @@ class ConfigLoader:"viewport_limit": self.browser_config.viewport_limit,"connectOverCdp": self.browser_config.connect_over_cdp,"cdpUrl": self.browser_config.cdp_url,+ "fullVisualMode": self.browser_config.full_visual_mode,}def get_timeout_config(self) -> Dict[str, Optional[int]]:diff --git a/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.py b/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.pyindex afcad3054..c7ab9cccf 100644--- a/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.py+++ b/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.py@@ -50,6 +50,7 @@ class HybridBrowserToolkit(BaseToolkit):viewport_limit: bool = False,connect_over_cdp: bool = False,cdp_url: Optional[str] = None,+ full_visual_mode: bool = False,**kwargs: Any,) -> Any:r"""Create a HybridBrowserToolkit instance with the specified mode.@@ -98,6 +99,11 @@ class HybridBrowserToolkit(BaseToolkit):cdp_url (Optional[str]): WebSocket endpoint URL for CDPconnection. Required when connect_over_cdp is True.Defaults to None. (Only supported in TypeScript mode)+ full_visual_mode (bool): When True, browser actions like click,+ browser_open, visit_page, etc. will return 'full visual mode'+ as snapshot instead of actual page content. The+ browser_get_page_snapshot method will still return the actual+ snapshot. Defaults to False.**kwargs: Additional keyword arguments passed to theimplementation.@@ -129,6 +135,7 @@ class HybridBrowserToolkit(BaseToolkit):viewport_limit=viewport_limit,connect_over_cdp=connect_over_cdp,cdp_url=cdp_url,+ full_visual_mode=full_visual_mode,**kwargs,)elif mode == "python":diff --git a/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit_ts.py b/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit_ts.pyindex 870d83262..4761cecb7 100644--- a/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit_ts.py+++ b/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit_ts.py@@ -98,6 +98,7 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):viewport_limit: bool = False,connect_over_cdp: bool = False,cdp_url: Optional[str] = None,+ full_visual_mode: bool = False,) -> None:r"""Initialize the HybridBrowserToolkit.@@ -143,6 +144,9 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):cdp_url (Optional[str]): WebSocket endpoint URL for CDPconnection (e.g., 'ws://localhost:9222/devtools/browser/...').Required when connect_over_cdp is True. Defaults to None.+ full_visual_mode (bool): When True, browser actions like click,+ browser_open, visit_page, etc. will not return snapshots.+ Defaults to False."""super().__init__()RegisteredAgentToolkit.__init__(self)@@ -167,6 +171,7 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):enabled_tools=enabled_tools,connect_over_cdp=connect_over_cdp,cdp_url=cdp_url,+ full_visual_mode=full_visual_mode,)# Legacy attribute access for backward compatibility@@ -182,6 +187,7 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):self._default_start_url = browser_config.default_start_urlself._session_id = toolkit_config.session_id or "default"self._viewport_limit = browser_config.viewport_limit+ self._full_visual_mode = browser_config.full_visual_mode# Store timeout configuration for backward compatibilityself._default_timeout = browser_config.default_timeout@@ -648,22 +654,29 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):# Add tab informationtab_info = await ws_wrapper.get_tab_info()- result.update(- {- "tabs": tab_info,- "current_tab": next(- (- i- for i, tab in enumerate(tab_info)- if tab.get("is_current")- ),- 0,++ response = {+ "result": result.get("result", ""),+ "snapshot": result.get("snapshot", ""),+ "tabs": tab_info,+ "current_tab": next(+ (+ i+ for i, tab in enumerate(tab_info)+ if tab.get("is_current")),- "total_tabs": len(tab_info),- }- )+ 0,+ ),+ "total_tabs": len(tab_info),+ }- return result+ if "newTabId" in result:+ response["newTabId"] = result["newTabId"]++ if "timing" in result:+ response["timing"] = result["timing"]++ return responseexcept Exception as e:logger.error(f"Failed to click element: {e}")return {@@ -1377,6 +1390,8 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):screenshot_timeout=self._screenshot_timeout,page_stability_timeout=self._page_stability_timeout,dom_content_loaded_timeout=self._dom_content_loaded_timeout,+ viewport_limit=self._viewport_limit,+ full_visual_mode=self._full_visual_mode,)def get_tools(self) -> List[FunctionTool]:diff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.tsindex 62d720232..a73abb71d 100644--- a/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts@@ -59,14 +59,30 @@ export class HybridBrowserSession {const contexts = this.browser.contexts();if (contexts.length > 0) {this.context = contexts[0];++ // Apply stealth headers to existing context if configured+ // Note: userAgent cannot be changed on an existing context+ if (stealthConfig.enabled) {+ if (stealthConfig.extraHTTPHeaders) {+ await this.context.setExtraHTTPHeaders(stealthConfig.extraHTTPHeaders);+ }+ if (stealthConfig.userAgent) {+ console.warn('[HybridBrowserSession] Cannot apply userAgent to existing context. Consider creating a new context if userAgent customization is required.');+ }+ }} else {const contextOptions: any = {viewport: browserConfig.viewport};- // Apply stealth headers if configured- if (stealthConfig.enabled && stealthConfig.extraHTTPHeaders) {- contextOptions.extraHTTPHeaders = stealthConfig.extraHTTPHeaders;+ // Apply stealth headers and UA if configured+ if (stealthConfig.enabled) {+ if (stealthConfig.extraHTTPHeaders) {+ contextOptions.extraHTTPHeaders = stealthConfig.extraHTTPHeaders;+ }+ if (stealthConfig.userAgent) {+ contextOptions.userAgent = stealthConfig.userAgent;+ }}this.context = await this.browser.newContext(contextOptions);@@ -105,13 +121,18 @@ export class HybridBrowserSession {if (stealthConfig.enabled) {launchOptions.args = stealthConfig.args || [];- // Apply stealth user agent if configured+ // Apply stealth user agent/headers if configuredif (stealthConfig.userAgent) {launchOptions.userAgent = stealthConfig.userAgent;}+ if (stealthConfig.extraHTTPHeaders) {+ launchOptions.extraHTTPHeaders = stealthConfig.extraHTTPHeaders;+ }}if (browserConfig.userDataDir) {+ // Ensure viewport is honored in persistent context+ launchOptions.viewport = browserConfig.viewport;this.context = await chromium.launchPersistentContext(browserConfig.userDataDir,launchOptions@@ -129,9 +150,14 @@ export class HybridBrowserSession {viewport: browserConfig.viewport};- // Apply stealth headers if configured- if (stealthConfig.enabled && stealthConfig.extraHTTPHeaders) {- contextOptions.extraHTTPHeaders = stealthConfig.extraHTTPHeaders;+ // Apply stealth headers and UA if configured+ if (stealthConfig.enabled) {+ if (stealthConfig.extraHTTPHeaders) {+ contextOptions.extraHTTPHeaders = stealthConfig.extraHTTPHeaders;+ }+ if (stealthConfig.userAgent) {+ contextOptions.userAgent = stealthConfig.userAgent;+ }}this.context = await this.browser.newContext(contextOptions);@@ -173,26 +199,10 @@ export class HybridBrowserSession {async getCurrentPage(): Promise<Page> {if (!this.currentTabId || !this.pages.has(this.currentTabId)) {- // In CDP mode, try to create a new page if none exists+ // In CDP mode, we cannot create new pagesconst browserConfig = this.configLoader.getBrowserConfig();- if (browserConfig.connectOverCdp && this.context) {- console.log('[CDP] No active page found, attempting to create new page...');- try {- const newPage = await this.context.newPage();- const newTabId = this.generateTabId();- this.registerNewPage(newTabId, newPage);- this.currentTabId = newTabId;-- // Set page timeouts- newPage.setDefaultNavigationTimeout(browserConfig.navigationTimeout);- newPage.setDefaultTimeout(browserConfig.navigationTimeout);-- console.log(`[CDP] Created new page with tab ID: ${newTabId}`);- return newPage;- } catch (error) {- console.error('[CDP] Failed to create new page:', error);- throw new Error('No active page available and failed to create new page in CDP mode');- }+ if (browserConfig.connectOverCdp) {+ throw new Error('No active page available in CDP mode; frontend must pre-create blank tabs.');}throw new Error('No active page available');}@@ -235,6 +245,36 @@ export class HybridBrowserSession {return this.getSnapshotForAINative(includeCoordinates, viewportLimit);}+ private parseElementFromSnapshot(snapshotText: string, ref: string): { role?: string; text?: string } {+ const lines = snapshotText.split('\n');+ for (const line of lines) {+ if (line.includes(`[ref=${ref}]`)) {+ const typeMatch = line.match(/^\s*-?\s*([\w-]+)/);+ const role = typeMatch ? typeMatch[1] : undefined;+ const textMatch = line.match(/"([^"]*)"/);+ const text = textMatch ? textMatch[1] : undefined;+ return { role, text };+ }+ }+ return {};+ }++ private buildSnapshotIndex(snapshotText: string): Map<string, { role?: string; text?: string }> {+ const index = new Map<string, { role?: string; text?: string }>();+ const refRe = /\[ref=([^\]]+)\]/i;+ for (const line of snapshotText.split('\n')) {+ const m = line.match(refRe);+ if (!m) continue;+ const ref = m[1];+ const roleMatch = line.match(/^\s*-?\s*([a-z0-9_-]+)/i);+ const role = roleMatch ? roleMatch[1].toLowerCase() : undefined;+ const textMatch = line.match(/"([^"]*)"/);+ const text = textMatch ? textMatch[1] : undefined;+ index.set(ref, { role, text });+ }+ return index;+ }+private async getSnapshotForAINative(includeCoordinates = false, viewportLimit = false): Promise<SnapshotResult & { timing: DetailedTiming }> {const startTime = Date.now();const page = await this.getCurrentPage();@@ -257,6 +297,17 @@ export class HybridBrowserSession {const mappingStart = Date.now();const playwrightMapping: Record<string, any> = {};+ // Parse element info in a single pass+ const snapshotIndex = this.buildSnapshotIndex(snapshotText);+ for (const ref of refs) {+ const elementInfo = snapshotIndex.get(ref) || {};+ playwrightMapping[ref] = {+ ref,+ role: elementInfo.role || 'unknown',+ text: elementInfo.text || '',+ };+ }+if (includeCoordinates) {// Get coordinates for each ref using aria-ref selectorfor (const ref of refs) {@@ -270,8 +321,9 @@ export class HybridBrowserSession {const boundingBox = await element.boundingBox();if (boundingBox) {+ // Add coordinates to existing element infoplaywrightMapping[ref] = {- ref,+ ...playwrightMapping[ref],coordinates: {x: Math.round(boundingBox.x),y: Math.round(boundingBox.y),@@ -388,7 +440,6 @@ export class HybridBrowserSession {if (shouldOpenNewTab) {// Handle new tab opening-// If it's a link that doesn't naturally open in new tab, force itif (isNavigableLink && !naturallyOpensNewTab) {await element.evaluate((el, blankTarget) => {@@ -803,6 +854,55 @@ export class HybridBrowserSession {}}+ /**+ * Wait for DOM to stop changing for a specified duration+ */+ private async waitForDOMStability(page: Page, maxWaitTime: number = 500): Promise<void> {+ const startTime = Date.now();+ const stabilityThreshold = 100; // Consider stable if no changes for 100ms+ let lastChangeTime = Date.now();++ try {+ // Monitor DOM changes+ await page.evaluate(() => {+ let changeCount = 0;+ (window as any).__domStabilityCheck = { changeCount: 0, lastChange: Date.now() };++ const observer = new MutationObserver(() => {+ (window as any).__domStabilityCheck.changeCount++;+ (window as any).__domStabilityCheck.lastChange = Date.now();+ });++ observer.observe(document.body, {+ childList: true,+ subtree: true,+ attributes: true,+ characterData: true+ });++ (window as any).__domStabilityObserver = observer;+ });++ // Wait until no changes for stabilityThreshold or timeout+ await page.waitForFunction(+ (threshold) => {+ const check = (window as any).__domStabilityCheck;+ return check && (Date.now() - check.lastChange) > threshold;+ },+ stabilityThreshold,+ { timeout: Math.max(0, maxWaitTime) }+ ).catch(() => {});+ } finally {+ // Cleanup+ await page.evaluate(() => {+ const observer = (window as any).__domStabilityObserver;+ if (observer) observer.disconnect();+ delete (window as any).__domStabilityObserver;+ delete (window as any).__domStabilityCheck;+ }).catch(() => {});+ }+ }+private async waitForPageStability(page: Page): Promise<{ domContentLoadedTime: number; networkIdleTime: number }> {let domContentLoadedTime = 0;let networkIdleTime = 0;@@ -1132,12 +1232,12 @@ export class HybridBrowserSession {const filtered: Record<string, SnapshotElement> = {};- // Apply viewport filtering with scroll position adjustment- const browserConfig = this.configLoader.getBrowserConfig();- const adjustedScrollPos = {- x: scrollPos.x * browserConfig.scrollPositionScale,- y: scrollPos.y * browserConfig.scrollPositionScale- };+ // Apply viewport filtering+ // boundingBox() returns viewport-relative coordinates, so we don't need to add scroll offsets+ const viewportLeft = 0;+ const viewportTop = 0;+ const viewportRight = viewport.width;+ const viewportBottom = viewport.height;for (const [ref, element] of Object.entries(elements)) {// If element has no coordinates, include it (fallback)@@ -1148,14 +1248,9 @@ export class HybridBrowserSession {const { x, y, width, height } = element.coordinates;- // Calculate viewport bounds using adjusted scroll position- const viewportLeft = adjustedScrollPos.x;- const viewportTop = adjustedScrollPos.y;- const viewportRight = adjustedScrollPos.x + viewport.width;- const viewportBottom = adjustedScrollPos.y + viewport.height;-// Check if element is visible in current viewport// Element is visible if it overlaps with viewport bounds+ // Since boundingBox() coords are viewport-relative, we compare directlyconst isVisible = (x < viewportRight && // Left edge is before viewport righty < viewportBottom && // Top edge is before viewport bottomdiff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/config-loader.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/config-loader.tsindex f92d120d1..dfecf0d4e 100644--- a/camel/toolkits/hybrid_browser_toolkit/ts/src/config-loader.ts+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/config-loader.ts@@ -79,6 +79,7 @@ export interface WebSocketConfig {browser_log_to_file: boolean;session_id?: string;viewport_limit: boolean;+ fullVisualMode?: boolean;}// Default stealth configuration@@ -212,6 +213,7 @@ export class ConfigLoader {if (config.browser_log_to_file !== undefined) wsConfig.browser_log_to_file = config.browser_log_to_file;if (config.session_id !== undefined) wsConfig.session_id = config.session_id;if (config.viewport_limit !== undefined) wsConfig.viewport_limit = config.viewport_limit;+ if (config.fullVisualMode !== undefined) wsConfig.fullVisualMode = config.fullVisualMode;// CDP connection optionsif (config.connectOverCdp !== undefined) browserConfig.connectOverCdp = config.connectOverCdp;diff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/hybrid-browser-toolkit.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/hybrid-browser-toolkit.tsindex 4c627b359..3ca3b7e79 100644--- a/camel/toolkits/hybrid_browser_toolkit/ts/src/hybrid-browser-toolkit.ts+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/hybrid-browser-toolkit.ts@@ -2,18 +2,22 @@ import {HybridBrowserSession} from './browser-session';import {ActionResult, BrowserAction, BrowserToolkitConfig, SnapshotResult, TabInfo, VisualMarkResult} from './types';import {ConfigLoader} from './config-loader';import {ConsoleMessage} from 'playwright';+import {SomScreenshotInjected} from './som-screenshot-injected';+import {filterClickableByHierarchy} from './snapshot-parser';export class HybridBrowserToolkit {private session: HybridBrowserSession;private config: BrowserToolkitConfig;private configLoader: ConfigLoader;private viewportLimit: boolean;+ private fullVisualMode: boolean;constructor(config: BrowserToolkitConfig = {}) {this.configLoader = ConfigLoader.fromPythonConfig(config);this.config = config; // Store original config for backward compatibilitythis.session = new HybridBrowserSession(this.configLoader.getBrowserConfig()); // Pass processed configthis.viewportLimit = this.configLoader.getWebSocketConfig().viewport_limit;+ this.fullVisualMode = this.configLoader.getWebSocketConfig().fullVisualMode || false;}async openBrowser(startUrl?: string): Promise<ActionResult> {@@ -26,7 +30,7 @@ export class HybridBrowserToolkit {const result = await this.session.visitPage(url);const snapshotStart = Date.now();- const snapshot = await this.getPageSnapshot(this.viewportLimit);+ const snapshot = await this.getSnapshotForAction(this.viewportLimit);const snapshotTime = Date.now() - snapshotStart;const totalTime = Date.now() - startTime;@@ -83,7 +87,7 @@ export class HybridBrowserToolkit {if (result.success) {const snapshotStart = Date.now();- response.snapshot = await this.getPageSnapshot(this.viewportLimit);+ response.snapshot = await this.getSnapshotForAction(this.viewportLimit);const snapshotTime = Date.now() - snapshotStart;if (result.timing) {@@ -119,6 +123,7 @@ export class HybridBrowserToolkit {async getPageSnapshot(viewportLimit: boolean = false): Promise<string> {try {+ // Always return real snapshot when explicitly called// If viewport limiting is enabled, we need coordinates for filteringconst snapshotResult = await this.session.getSnapshotForAI(viewportLimit, viewportLimit);return snapshotResult.snapshot;@@ -126,6 +131,14 @@ export class HybridBrowserToolkit {return `Error capturing snapshot: ${error}`;}}++ // Internal method for getting snapshot in actions (respects fullVisualMode)+ private async getSnapshotForAction(viewportLimit: boolean = false): Promise<string> {+ if (this.fullVisualMode) {+ return 'full visual mode';+ }+ return this.getPageSnapshot(viewportLimit);+ }async getSnapshotForAI(): Promise<SnapshotResult> {@@ -134,35 +147,34 @@ export class HybridBrowserToolkit {async getSomScreenshot(): Promise<VisualMarkResult & { timing: any }> {const startTime = Date.now();+ console.log('[HybridBrowserToolkit] Starting getSomScreenshot...');try {- const screenshotResult = await this.session.takeScreenshot();- const snapshotResult = await this.session.getSnapshotForAI(true); // Include coordinates for SOM_mark-- // Add visual marks using improved method- const markingStart = Date.now();- const markedImageBuffer = await this.addVisualMarksOptimized(screenshotResult.buffer, snapshotResult);- const markingTime = Date.now() - markingStart;+ // Get page and snapshot data+ const page = await this.session.getCurrentPage();+ const snapshotResult = await this.session.getSnapshotForAI(true); // Include coordinates- const base64Image = markedImageBuffer.toString('base64');- const dataUrl = `data:image/png;base64,${base64Image}`;+ // Parse clickable elements from snapshot text+ const clickableElements = this.parseClickableElements(snapshotResult.snapshot);+ console.log(`[HybridBrowserToolkit] Found ${clickableElements.size} clickable elements`);- const totalTime = Date.now() - startTime;+ // Apply hierarchy-based filtering+ const filteredElements = filterClickableByHierarchy(snapshotResult.snapshot, clickableElements);+ console.log(`[HybridBrowserToolkit] After filtering: ${filteredElements.size} elements remain`);++ // Use injected SOM-screenshot method without export path+ const result = await SomScreenshotInjected.captureOptimized(+ page,+ snapshotResult,+ filteredElements,+ undefined // No export path - don't generate files+ );- // Count elements with coordinates- const elementsWithCoords = Object.values(snapshotResult.elements).filter(el => el.coordinates).length;+ // Add snapshot timing info to result+ result.timing.snapshot_time_ms = snapshotResult.timing.snapshot_time_ms;+ result.timing.coordinate_enrichment_time_ms = snapshotResult.timing.coordinate_enrichment_time_ms;- return {- text: `Visual webpage screenshot captured with ${Object.keys(snapshotResult.elements).length} interactive elements (${elementsWithCoords} marked visually)`,- images: [dataUrl],- timing: {- total_time_ms: totalTime,- screenshot_time_ms: screenshotResult.timing.screenshot_time_ms,- snapshot_time_ms: snapshotResult.timing.snapshot_time_ms,- coordinate_enrichment_time_ms: snapshotResult.timing.coordinate_enrichment_time_ms,- visual_marking_time_ms: markingTime,- },- };+ return result;} catch (error) {const totalTime = Date.now() - startTime;return {@@ -179,132 +191,6 @@ export class HybridBrowserToolkit {}}- private async addVisualMarksOptimized(screenshotBuffer: Buffer, snapshotResult: SnapshotResult): Promise<Buffer> {- try {-- // Check if we have any elements with coordinates- const elementsWithCoords = Object.entries(snapshotResult.elements)- .filter(([ref, element]) => element.coordinates);-- if (elementsWithCoords.length === 0) {- return screenshotBuffer;- }-- // Parse clickable elements from snapshot text- const clickableElements = this.parseClickableElements(snapshotResult.snapshot);-- // Use sharp for image processing- const sharp = require('sharp');- const page = await this.session.getCurrentPage();- let viewport = page.viewportSize();-- // In CDP mode, viewportSize might be null, get it from window dimensions- if (!viewport) {- const windowSize = await page.evaluate(() => ({- width: window.innerWidth,- height: window.innerHeight- }));- viewport = windowSize;- }-- // Get device pixel ratio to handle high DPI screens- const dpr = await page.evaluate(() => window.devicePixelRatio) || 1;-- // Get actual screenshot dimensions- const metadata = await sharp(screenshotBuffer).metadata();- const screenshotWidth = metadata.width || viewport.width;- const screenshotHeight = metadata.height || viewport.height;-- // Calculate scaling factor between CSS pixels and screenshot pixels- const scaleX = screenshotWidth / viewport.width;- const scaleY = screenshotHeight / viewport.height;-- // Debug logging for CDP mode- if (process.env.HYBRID_BROWSER_DEBUG === '1') {- console.log('[CDP Debug] Viewport size:', viewport);- console.log('[CDP Debug] Device pixel ratio:', dpr);- console.log('[CDP Debug] Screenshot dimensions:', { width: screenshotWidth, height: screenshotHeight });- console.log('[CDP Debug] Scale factors:', { scaleX, scaleY });- console.log('[CDP Debug] Elements with coordinates:', elementsWithCoords.length);- elementsWithCoords.slice(0, 3).forEach(([ref, element]) => {- console.log(`[CDP Debug] Element ${ref}:`, element.coordinates);- });- }-- // Filter elements visible in viewport- const visibleElements = elementsWithCoords.filter(([ref, element]) => {- const coords = element.coordinates!;- return coords.x < viewport.width &&- coords.y < viewport.height &&- coords.x + coords.width > 0 &&- coords.y + coords.height > 0;- });-- // Remove overlapped elements (only keep topmost)- const nonOverlappedElements = this.removeOverlappedElements(visibleElements);-- // Create SVG overlay with all the marks- const marks = nonOverlappedElements.map(([ref, element]) => {- const coords = element.coordinates!;- const isClickable = clickableElements.has(ref);-- // Scale coordinates from CSS pixels to screenshot pixels- const x = Math.max(0, coords.x * scaleX);- const y = Math.max(0, coords.y * scaleY);- const width = coords.width * scaleX;- const height = coords.height * scaleY;-- // Clamp to screenshot bounds- const clampedWidth = Math.min(width, screenshotWidth - x);- const clampedHeight = Math.min(height, screenshotHeight - y);-- // Position text to be visible even if element is partially cut off- const textX = Math.max(2, Math.min(x + 2, screenshotWidth - 40));- const textY = Math.max(14, Math.min(y + 14, screenshotHeight - 4));-- // Different colors for clickable vs non-clickable elements- const colors = isClickable ? {- fill: 'rgba(0, 150, 255, 0.15)', // Blue for clickable- stroke: '#0096FF',- textFill: '#0096FF'- } : {- fill: 'rgba(255, 107, 107, 0.1)', // Red for non-clickable- stroke: '#FF6B6B',- textFill: '#FF6B6B'- };-- return `- <rect x="${x}" y="${y}" width="${clampedWidth}" height="${clampedHeight}"- fill="${colors.fill}" stroke="${colors.stroke}" stroke-width="2" rx="2"/>- <text x="${textX}" y="${textY}" font-family="Arial, sans-serif"- font-size="12" fill="${colors.textFill}" font-weight="bold">${ref}</text>- `;- }).join('');-- const svgOverlay = `- <svg width="${screenshotWidth}" height="${screenshotHeight}" xmlns="http://www.w3.org/2000/svg">- ${marks}- </svg>- `;-- // Composite the overlay onto the screenshot- const markedImageBuffer = await sharp(screenshotBuffer)- .composite([{- input: Buffer.from(svgOverlay),- top: 0,- left: 0- }])- .png()- .toBuffer();-- return markedImageBuffer;-- } catch (error) {- // Error adding visual marks, falling back to original screenshot- // Return original screenshot if marking fails- return screenshotBuffer;- }- }/*** Parse clickable elements from snapshot text@@ -314,8 +200,8 @@ export class HybridBrowserToolkit {const lines = snapshotText.split('\n');for (const line of lines) {- // Look for lines containing [cursor=pointer] and extract ref- if (line.includes('[cursor=pointer]')) {+ // Look for lines containing [cursor=pointer] or [active] and extract ref+ if (line.includes('[cursor=pointer]') || line.includes('[active]')) {const refMatch = line.match(/\[ref=([^\]]+)\]/);if (refMatch) {clickableElements.add(refMatch[1]);@@ -326,56 +212,6 @@ export class HybridBrowserToolkit {return clickableElements;}- /**- * Remove overlapped elements, keeping only the topmost (last in DOM order)- */- private removeOverlappedElements(elements: Array<[string, any]>): Array<[string, any]> {- const result: Array<[string, any]> = [];-- for (let i = 0; i < elements.length; i++) {- const [refA, elementA] = elements[i];- const coordsA = elementA.coordinates!;- let isOverlapped = false;-- // Check if this element is completely overlapped by any later element- for (let j = i + 1; j < elements.length; j++) {- const [refB, elementB] = elements[j];- const coordsB = elementB.coordinates!;-- // Check if element A is completely covered by element B- if (this.isCompletelyOverlapped(coordsA, coordsB)) {- isOverlapped = true;- break;- }- }-- if (!isOverlapped) {- result.push(elements[i]);- }- }-- return result;- }-- /**- * Check if element A is completely overlapped by element B- */- private isCompletelyOverlapped(- coordsA: { x: number; y: number; width: number; height: number },- coordsB: { x: number; y: number; width: number; height: number }- ): boolean {- // A is completely overlapped by B if:- // B's left edge is <= A's left edge AND- // B's top edge is <= A's top edge AND- // B's right edge is >= A's right edge AND- // B's bottom edge is >= A's bottom edge- return (- coordsB.x <= coordsA.x &&- coordsB.y <= coordsA.y &&- coordsB.x + coordsB.width >= coordsA.x + coordsA.width &&- coordsB.y + coordsB.height >= coordsA.y + coordsA.height- );- }private async executeActionWithSnapshot(action: BrowserAction): Promise<any> {const result = await this.session.executeAction(action);@@ -472,7 +308,7 @@ export class HybridBrowserToolkit {const navigationTime = Date.now() - navigationStart;const snapshotStart = Date.now();- const snapshot = await this.getPageSnapshot(this.viewportLimit);+ const snapshot = await this.getSnapshotForAction(this.viewportLimit);const snapshotTime = Date.now() - snapshotStart;const totalTime = Date.now() - startTime;@@ -512,7 +348,7 @@ export class HybridBrowserToolkit {const navigationTime = Date.now() - navigationStart;const snapshotStart = Date.now();- const snapshot = await this.getPageSnapshot(this.viewportLimit);+ const snapshot = await this.getSnapshotForAction(this.viewportLimit);const snapshotTime = Date.now() - snapshotStart;const totalTime = Date.now() - startTime;@@ -584,7 +420,7 @@ export class HybridBrowserToolkit {return {success: true,message: `Closed tab ${tabId}`,- snapshot: await this.getPageSnapshot(this.viewportLimit),+ snapshot: await this.getSnapshotForAction(this.viewportLimit),};} else {return {@@ -649,7 +485,7 @@ export class HybridBrowserToolkit {const { result, logs } = evalResult;const snapshotStart = Date.now();- const snapshot = await this.getPageSnapshot(this.viewportLimit);+ const snapshot = await this.getSnapshotForAction(this.viewportLimit);const snapshotTime = Date.now() - snapshotStart;const totalTime = Date.now() - startTime;diff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/parent-child-filter.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/parent-child-filter.tsnew file mode 100644index 000000000..776782635--- /dev/null+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/parent-child-filter.ts@@ -0,0 +1,226 @@+/**+ * Parent-child filtering logic for SOM-labels+ * Filters out child elements that are contained within propagating parent elements+ */++export interface ElementInfo {+ ref: string;+ coordinates?: {+ x: number;+ y: number;+ width: number;+ height: number;+ };+ role?: string;+ type?: string;+ tagName?: string;+ attributes?: Record<string, any>;+ text?: string;+}++// Elements that propagate bounds to their children+const PROPAGATING_ELEMENTS = [+ { tag: 'a', role: null },+ { tag: 'button', role: null },+ { tag: 'div', role: 'button' },+ { tag: 'div', role: 'combobox' },+ { tag: 'span', role: 'button' },+ { tag: 'span', role: 'combobox' },+ { tag: 'input', role: 'combobox' },+];++const CONTAINMENT_THRESHOLD = 0.99; // 99% containment required++/**+ * Check if element is a propagating element+ */+function isPropagatingElement(element: ElementInfo): boolean {+ const tagName = element.tagName || element.type || '';+ const tag = tagName.toLowerCase();+ const role = element.role || element.attributes?.role || null;++ // For generic elements with cursor=pointer, we need to be more selective+ // Only treat them as propagating if they don't have text content+ // (text-containing generics are usually labels, not containers)+ if ((tag === 'generic' || element.type === 'generic') &&+ element.attributes?.['cursor'] === 'pointer') {+ // If element has direct text content, it's likely a label, not a container+ if (element.text && element.text.trim()) {+ return false;+ }+ // If no text, it might be a container+ return true;+ }++ for (const pattern of PROPAGATING_ELEMENTS) {+ if (pattern.tag === tag) {+ if (pattern.role === null || pattern.role === role) {+ return true;+ }+ }+ }+ return false;+}++/**+ * Check if child bounds are contained within parent bounds+ */+function isContained(+ childBounds: { x: number; y: number; width: number; height: number },+ parentBounds: { x: number; y: number; width: number; height: number },+ threshold: number+): boolean {+ // Calculate intersection+ const xOverlap = Math.max(0,+ Math.min(childBounds.x + childBounds.width, parentBounds.x + parentBounds.width) -+ Math.max(childBounds.x, parentBounds.x)+ );+ const yOverlap = Math.max(0,+ Math.min(childBounds.y + childBounds.height, parentBounds.y + parentBounds.height) -+ Math.max(childBounds.y, parentBounds.y)+ );++ const intersectionArea = xOverlap * yOverlap;+ const childArea = childBounds.width * childBounds.height;++ if (childArea === 0) return false;++ return (intersectionArea / childArea) >= threshold;+}++/**+ * Check if child element should be filtered out+ */+function shouldFilterChild(childEl: ElementInfo, parentEl: ElementInfo): boolean {+ // Never filter if parent is not a propagating element+ if (!isPropagatingElement(parentEl)) {+ return false;+ }++ // Never filter if elements don't have coordinates+ if (!childEl.coordinates || !parentEl.coordinates) {+ return false;+ }++ // Check containment+ if (!isContained(childEl.coordinates, parentEl.coordinates, CONTAINMENT_THRESHOLD)) {+ return false;+ }++ const childTag = (childEl.tagName || childEl.type || '').toLowerCase();+ const childRole = childEl.role || childEl.attributes?.role || null;++ // Exception rules - never filter these:++ // 1. Form elements (need individual interaction)+ if (['input', 'select', 'textarea', 'label'].includes(childTag)) {+ return false;+ }++ // 2. Child is also a propagating element (might have stopPropagation)+ if (isPropagatingElement(childEl)) {+ return false;+ }++ // 3. Has onclick handler+ if (childEl.attributes?.onclick) {+ return false;+ }++ // 4. Has meaningful aria-label+ if (childEl.attributes?.['aria-label']?.trim()) {+ return false;+ }++ // 5. Has interactive role+ if (['button', 'link', 'checkbox', 'radio', 'tab', 'menuitem'].includes(childRole || '')) {+ return false;+ }++ // Default: filter this child+ return true;+}++/**+ * Filter clickable elements based on parent-child relationships+ * @param elements - Map of all elements with their info+ * @param clickableRefs - Set of refs that are clickable+ * @returns Filtered set of element refs and debug info+ */+export function filterParentChildElements(+ elements: Record<string, ElementInfo>,+ clickableRefs: Set<string>+): {+ filteredElements: Set<string>;+ debugInfo: any[];+} {+ const elementRefs = Array.from(clickableRefs);+ const filteredElements = new Set<string>(elementRefs);+ const debugInfo: any[] = [];++ console.log(`[Parent-Child Filter] Analyzing ${elementRefs.length} clickable elements`);++ // Check each pair of elements for parent-child filtering+ for (let i = 0; i < elementRefs.length; i++) {+ const parentRef = elementRefs[i];+ const parentEl = elements[parentRef];++ if (!parentEl?.coordinates) continue;++ const isParentPropagating = isPropagatingElement(parentEl);++ for (let j = 0; j < elementRefs.length; j++) {+ if (i === j) continue;++ const childRef = elementRefs[j];+ const childEl = elements[childRef];++ if (!childEl?.coordinates) continue;++ // Debug parent-child relationships when enabled+ const DEBUG_PARENT_CHILD = process.env.DEBUG_PARENT_CHILD === 'true';+ if (DEBUG_PARENT_CHILD) {+ const shouldFilter = shouldFilterChild(childEl, parentEl);+ console.log(`\n[Debug] Checking ${parentRef} -> ${childRef}:`);+ console.log(`Parent:`, {+ ref: parentRef,+ type: parentEl.type || parentEl.tagName,+ role: parentEl.role,+ coords: parentEl.coordinates,+ isPropagating: isParentPropagating+ });+ console.log(`Child:`, {+ ref: childRef,+ type: childEl.type || childEl.tagName,+ role: childEl.role,+ coords: childEl.coordinates+ });+ console.log(`Should filter? ${shouldFilter}`);+ }++ if (shouldFilterChild(childEl, parentEl)) {+ filteredElements.delete(childRef);++ debugInfo.push({+ type: 'filtered',+ childRef,+ parentRef,+ reason: 'Contained within propagating parent',+ parentType: parentEl.type || parentEl.tagName,+ childType: childEl.type || childEl.tagName,+ parentRole: parentEl.role,+ childRole: childEl.role,+ containment: isContained(childEl.coordinates, parentEl.coordinates, CONTAINMENT_THRESHOLD)+ });+ }+ }+ }++ const filteredCount = elementRefs.length - filteredElements.size;+ console.log(`[Parent-Child Filter] Filtered out ${filteredCount} child elements`);++ return {+ filteredElements,+ debugInfo+ };+}\ No newline at end of filediff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/snapshot-parser.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/snapshot-parser.tsnew file mode 100644index 000000000..8fdb3a09e--- /dev/null+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/snapshot-parser.ts@@ -0,0 +1,231 @@+/**+ * Parse snapshot text to extract parent-child relationships+ */++export interface SnapshotNode {+ ref: string;+ type: string;+ text?: string;+ attributes: Record<string, string>;+ children: string[]; // refs of child elements+ parent?: string; // ref of parent element+}++export function parseSnapshotHierarchy(snapshotText: string): Map<string, SnapshotNode> {+ const nodes = new Map<string, SnapshotNode>();+ const lines = snapshotText.split('\n');++ // Stack to track parent elements at each indentation level+ const parentStack: { ref: string; indent: number }[] = [];++ for (const line of lines) {+ if (!line.trim()) continue;++ // Calculate indentation+ const indent = line.length - line.trimStart().length;++ // Extract element info using regex+ // Support both lines with : (have children) and without : (leaf nodes)+ // Also support quoted lines like - 'button "text" [ref=...]'+ // Also support escaped quotes in text+ // Also support attributes before [ref=...]+ // Extract type and optional label (before any [..] blocks)+ const headerMatch = line.match(/^\s*(?:-\s*)?'?([a-z0-9_-]+)(?:\s+"((?:[^"\\]|\\.)*)")?/i);+ if (!headerMatch) continue;+ const [, typeRaw, label] = headerMatch;+ const type = (typeRaw || 'unknown');++ // Extract mandatory ref+ const refMatch = line.match(/\[ref=([^\]]+)\]/i);+ if (!refMatch) continue;+ const ref = refMatch[1];++ // Parse all bracketed attributes except the [ref=...] block+ const attrs: Record<string, string> = {};+ for (const block of line.matchAll(/\[([^\]]+)\]/g)) {+ const content = block[1];+ if (/^ref=/i.test(content)) continue;+ const attrMatches = content.matchAll(/([a-z0-9_-]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\s\]]+)))?/gi);+ for (const m of attrMatches) {+ const key = m[1].toLowerCase();+ const val = m[2] ?? m[3] ?? m[4] ?? 'true';+ attrs[key] = val;+ }+ }++ // Update parent stack based on indentation+ while (parentStack.length > 0 && parentStack[parentStack.length - 1].indent >= indent) {+ parentStack.pop();+ }++ // Create node+ const node: SnapshotNode = {+ ref,+ type: type.toLowerCase(),+ text: label || '',+ attributes: attrs,+ children: [],+ parent: parentStack.length > 0 ? parentStack[parentStack.length - 1].ref : undefined+ };++ // Add to parent's children if has parent+ if (node.parent && nodes.has(node.parent)) {+ nodes.get(node.parent)!.children.push(ref);+ }++ // Add to nodes map+ nodes.set(ref, node);++ // Add to parent stack+ parentStack.push({ ref, indent });+ }++ return nodes;+}++/**+ * Find clickable elements that should be filtered based on DOM hierarchy+ */+export function filterClickableByHierarchy(+ snapshotText: string,+ clickableElements: Set<string>+): Set<string> {+ const hierarchy = parseSnapshotHierarchy(snapshotText);+ const filtered = new Set<string>(clickableElements);+ const debugInfo: any[] = [];++ // Debug clickable elements when enabled+ const DEBUG_SNAPSHOT_PARSER = process.env.DEBUG_SNAPSHOT_PARSER === 'true';+ if (DEBUG_SNAPSHOT_PARSER) {+ clickableElements.forEach(ref => {+ const node = hierarchy.get(ref);+ if (node) {+ console.log(`[Debug] ${ref} type: ${node.type}, parent: ${node.parent || 'none'}`);+ } else {+ console.log(`[Debug] ${ref} NOT FOUND in hierarchy!`);+ }+ });+ }++ // First pass: identify parent-child relationships where both are clickable+ const parentChildPairs: Array<{parent: string, child: string, parentType: string, childType: string}> = [];++ for (const childRef of clickableElements) {+ const childNode = hierarchy.get(childRef);+ if (!childNode || !childNode.parent) continue;++ const parentRef = childNode.parent;+ if (clickableElements.has(parentRef)) {+ const parentNode = hierarchy.get(parentRef);+ if (parentNode) {+ parentChildPairs.push({+ parent: parentRef,+ child: childRef,+ parentType: parentNode.type.toLowerCase(),+ childType: childNode.type.toLowerCase()+ });++ // Debug specific pairs+ if ((parentRef === 'e296' && childRef === 'e297') ||+ (parentRef === 'e361' && childRef === 'e363') ||+ (parentRef === 'e371' && childRef === 'e373') ||+ (parentRef === 'e344' && childRef === 'e346') ||+ (parentRef === 'e348' && childRef === 'e350')) {+ console.log(`[Debug] Found pair: ${parentRef} (${parentNode.type}) -> ${childRef} (${childNode.type})`);+ }+ }+ }+ }++ // Decide which elements to filter based on parent-child relationships+ for (const pair of parentChildPairs) {+ const { parent, child, parentType, childType } = pair;++ // Rules for what to filter:+ // 1. link > img: filter img (keep link)+ // 2. button > generic: filter generic (keep button)+ // 3. generic > button: filter generic (keep button)+ // 4. link > generic: filter generic (keep link)+ // 5. generic > generic: filter child (keep parent)+ // 6. generic > unknown: filter child (keep parent)++ if ((parentType === 'link' && childType === 'img') ||+ (parentType === 'button' && childType === 'generic') ||+ (parentType === 'link' && childType === 'generic') ||+ (parentType === 'generic' && childType === 'generic') ||+ (parentType === 'generic' && childType === 'unknown')) {+ // Filter child+ filtered.delete(child);+ console.log(`[Hierarchy Filter] Filtered ${child} (${childType}) - keeping parent ${parent} (${parentType})`);+ } else if (parentType === 'generic' && childType === 'button') {+ // Special case: filter parent generic, keep child button+ filtered.delete(parent);+ console.log(`[Hierarchy Filter] Filtered ${parent} (${parentType}) - keeping child ${child} (${childType})`);+ }+ }++ // Original logic for nested hierarchies (keep for deep nesting)+ for (const childRef of clickableElements) {+ if (!filtered.has(childRef)) continue; // Already filtered++ const childNode = hierarchy.get(childRef);+ if (!childNode || !childNode.parent) continue;++ // Check if any ancestor is a propagating element+ let currentParent: string | undefined = childNode.parent;+ while (currentParent) {+ if (clickableElements.has(currentParent) && filtered.has(currentParent)) {+ const parentNode = hierarchy.get(currentParent);+ if (parentNode) {+ // Check if parent is a propagating element+ const parentType = parentNode.type.toLowerCase();+ const isPropagating = ['button', 'link', 'a'].includes(parentType) ||+ (parentType === 'generic' && parentNode.attributes.cursor === 'pointer' && !parentNode.text);++ if (isPropagating) {+ // Filter child elements that should be contained within propagating parents+ const childType = childNode.type.toLowerCase();++ // Filter these types of children:+ // 1. Generic elements with cursor=pointer+ // 2. Images within links/buttons+ // 3. Text elements (span, generic without specific role)+ const shouldFilter =+ (childType === 'generic' && childNode.attributes.cursor === 'pointer') ||+ childType === 'img' ||+ childType === 'span' ||+ (childType === 'generic' && !childNode.attributes.role);++ if (shouldFilter) {+ filtered.delete(childRef);+ console.log(`[Hierarchy Filter] Filtered ${childRef} (${childType}) contained in ${currentParent} (${parentType})`);+ break;+ }+ }+ }+ }+ // Move up the hierarchy+ const nextParent = hierarchy.get(currentParent);+ currentParent = nextParent?.parent;+ }+ }++ // Additional pass: if a generic parent contains only one button child, filter the parent+ for (const ref of Array.from(filtered)) {+ const node = hierarchy.get(ref);+ if (!node || node.type.toLowerCase() !== 'generic') continue;++ // Check if this generic has exactly one clickable child that's a button+ const clickableChildren = node.children.filter(childRef =>+ filtered.has(childRef) && hierarchy.get(childRef)?.type.toLowerCase() === 'button'+ );++ if (clickableChildren.length === 1) {+ // This generic wraps a single button - filter it out+ filtered.delete(ref);+ console.log(`[Hierarchy Filter] Filtered ${ref} (generic wrapper around button ${clickableChildren[0]})`);+ }+ }++ return filtered;+}\ No newline at end of filediff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/som-screenshot-injected.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/som-screenshot-injected.tsnew file mode 100644index 000000000..eaf318741--- /dev/null+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/som-screenshot-injected.ts@@ -0,0 +1,543 @@+/**+ * Alternative implementation of SOM-screenshot using JS injection+ * This avoids CDP resolution issues by rendering labels directly in the page+ */++import { Page } from 'playwright';+import { SnapshotResult, VisualMarkResult } from './types';+import { writeFile } from 'fs/promises';++export class SomScreenshotInjected {+ /**+ * Take a screenshot with SOM-labels injected into the page+ * This approach uses a single script injection for better performance+ */+ static async captureOptimized(+ page: Page,+ snapshotResult: SnapshotResult,+ clickableElements: Set<string>,+ exportPath?: string+ ): Promise<VisualMarkResult & { timing: any }> {+ const startTime = Date.now();++ try {+ // Use the already filtered clickableElements directly+ const filterStartTime = Date.now();+ const filterTime = Date.now() - filterStartTime;+ console.log(`Using pre-filtered clickable elements: ${clickableElements.size} elements`);++ // Prepare element geometry data for export+ const elementGeometry: any[] = [];+ // Inject and capture in one go+ // Collect visibility debug info+ const visibilityDebugInfo: any[] = [];++ const result = await page.evaluate(async (data) => {+ const { elements, clickable, filterDebugInfo } = data;+ const markedElements: any[] = [];++ // Debug info collector - include filter debug info+ const debugInfo: any[] = [...filterDebugInfo];++ // Helper function to check element visibility based on coordinates+ function checkElementVisibilityByCoords(+ coords: { x: number, y: number, width: number, height: number },+ ref: string,+ elementInfo: any+ ): 'visible' | 'partial' | 'hidden' {+ // Skip if element is outside viewport+ if (coords.y + coords.height < 0 || coords.y > window.innerHeight ||+ coords.x + coords.width < 0 || coords.x > window.innerWidth) {+ return 'hidden';+ }++ // Simple approach: just check the center point+ // If center is visible and shows our element (or its child), consider it visible+ const centerX = coords.x + coords.width * 0.5;+ const centerY = coords.y + coords.height * 0.5;++ try {+ const elementsAtCenter = document.elementsFromPoint(centerX, centerY);+ if (!elementsAtCenter || elementsAtCenter.length === 0) {+ return 'hidden';+ }++ // Find our target element in the stack+ let targetFound = false;+ let targetIsTopmost = false;++ for (let i = 0; i < elementsAtCenter.length; i++) {+ const elem = elementsAtCenter[i];+ const rect = elem.getBoundingClientRect();++ // Check if this element matches our expected bounds (within tolerance)+ if (Math.abs(rect.left - coords.x) < 5 &&+ Math.abs(rect.top - coords.y) < 5 &&+ Math.abs(rect.width - coords.width) < 10 &&+ Math.abs(rect.height - coords.height) < 10) {+ targetFound = true;+ targetIsTopmost = (i === 0);++ // If target is topmost, it's definitely visible+ if (targetIsTopmost) {+ return 'visible';+ }++ // If not topmost, check if the topmost element is a child of our target+ const topmostElem = elementsAtCenter[0];+ if (elem.contains(topmostElem)) {+ // Topmost is our child - element is visible+ return 'visible';+ }++ // Otherwise, we're obscured+ return 'hidden';+ }+ }++ // If we didn't find our target element at all+ if (!targetFound) {+ // Special handling for composite widgets+ const topElement = elementsAtCenter[0];+ const tagName = topElement.tagName.toUpperCase();++ // Get element role/type for better decision making+ const elementRole = elementInfo?.role || '';+ const elementTagName = elementInfo?.tagName || '';++ // Only apply special handling for form controls that are part of composite widgets+ if (['SELECT', 'INPUT', 'TEXTAREA', 'BUTTON'].includes(tagName)) {+ const isFormRelatedElement = ['combobox', 'select', 'textbox', 'searchbox', 'spinbutton'].includes(elementRole) ||+ ['SELECT', 'INPUT', 'TEXTAREA', 'BUTTON', 'OPTION'].includes(elementTagName.toUpperCase());++ // Check if the form control approximately matches our area+ const rect = topElement.getBoundingClientRect();+ const overlap = Math.min(rect.right, coords.x + coords.width) - Math.max(rect.left, coords.x) > 0 &&+ Math.min(rect.bottom, coords.y + coords.height) - Math.max(rect.top, coords.y) > 0;++ if (overlap && isFormRelatedElement) {+ // Check for specific composite widget patterns+ // For combobox with search input (like Amazon search)+ if (elementRole === 'combobox' && tagName === 'INPUT') {+ // This is likely a search box with category selector - mark as visible+ return 'visible';+ }++ // For button/generic elements covered by INPUT with exact same bounds+ // This usually indicates the INPUT is the actual interactive element for the button+ if ((elementRole === 'button' || elementRole === 'generic') && tagName === 'INPUT') {+ const rectMatch = Math.abs(rect.left - coords.x) < 2 &&+ Math.abs(rect.top - coords.y) < 2 &&+ Math.abs(rect.width - coords.width) < 2 &&+ Math.abs(rect.height - coords.height) < 2;+ if (rectMatch) {+ // The INPUT is the actual interactive element for this button+ return 'visible';+ }+ }++ // For other form-related elements, only mark as visible if they share similar positioning+ // (i.e., they're likely part of the same widget)+ const sizeDiff = Math.abs(rect.width - coords.width) + Math.abs(rect.height - coords.height);+ if (sizeDiff < 50) { // Tolerance for size difference+ return 'visible';+ }+ }+ }++ return 'hidden';+ }++ return 'partial';++ } catch (e) {+ // Fallback: use simple elementFromPoint check+ const elem = document.elementFromPoint(centerX, centerY);+ if (!elem) return 'hidden';++ const rect = elem.getBoundingClientRect();+ // Check if the element at center matches our bounds+ if (Math.abs(rect.left - coords.x) < 5 &&+ Math.abs(rect.top - coords.y) < 5) {+ return 'visible';+ }+ return 'partial';+ }+ }+++ // Create overlay+ const overlay = document.createElement('div');+ overlay.id = 'camel-som-overlay-temp'; // Set ID immediately for cleanup+ overlay.style.cssText = `+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ pointer-events: none;+ z-index: 2147483647;+ `;++ // Check visibility for each element using coordinates+ const elementStates = new Map<string, 'visible' | 'partial' | 'hidden'>();++ Object.entries(elements).forEach(([ref, element]: [string, any]) => {+ if (element.coordinates && clickable.includes(ref)) {+ const visibility = checkElementVisibilityByCoords(element.coordinates, ref, element);+ elementStates.set(ref, visibility);++ // Add debug info+ const centerX = element.coordinates.x + element.coordinates.width * 0.5;+ const centerY = element.coordinates.y + element.coordinates.height * 0.5;++ try {+ const elementsAtCenter = document.elementsFromPoint(centerX, centerY);+ const topmostElement = elementsAtCenter[0];++ debugInfo.push({+ ref,+ coords: element.coordinates,+ centerPoint: { x: centerX, y: centerY },+ visibilityResult: visibility,+ elementRole: element.role || 'unknown',+ elementTagName: element.tagName || '',+ topmostElement: topmostElement ? {+ tagName: topmostElement.tagName,+ className: topmostElement.className,+ id: topmostElement.id+ } : null,+ elementsAtCenterCount: elementsAtCenter.length+ });+ } catch (e) {+ debugInfo.push({+ ref,+ coords: element.coordinates,+ visibilityResult: visibility,+ elementRole: element.role || 'unknown',+ elementTagName: element.tagName || '',+ error: 'Failed to get elements at center'+ });+ }+ }+ });++ // Track label positions to avoid overlap+ const labelPositions: Array<{x: number, y: number, width: number, height: number, ref: string}> = [];++ // Helper to check if two rectangles overlap+ function rectsOverlap(r1: any, r2: any): boolean {+ return !(r1.x + r1.width < r2.x ||+ r2.x + r2.width < r1.x ||+ r1.y + r1.height < r2.y ||+ r2.y + r2.height < r1.y);+ }++ // Helper to find non-overlapping position for label+ function findLabelPosition(element: any, labelWidth: number, labelHeight: number): {x: number, y: number} {+ const { x, y, width, height } = element.coordinates;+ const isSmallElement = height < 70;+ const margin = 2; // Space between label and element++ // Try different positions in order of preference+ const positions = [];++ if (isSmallElement) {+ // For small elements, try outside positions+ // 1. Above element+ positions.push({ x: x - 2, y: y - labelHeight - margin });+ // 2. Below element+ positions.push({ x: x - 2, y: y + height + margin });+ // 3. Left of element+ positions.push({ x: x - labelWidth - margin, y: y });+ // 4. Right of element+ positions.push({ x: x + width + margin, y: y });+ } else {+ // For large elements, inside top-left+ positions.push({ x: x + 4, y: y + 4 });+ }++ // Check each position+ for (const pos of positions) {+ // Adjust for viewport boundaries+ const adjustedPos = { ...pos };++ // Keep within viewport+ adjustedPos.x = Math.max(0, Math.min(adjustedPos.x, window.innerWidth - labelWidth));+ adjustedPos.y = Math.max(0, Math.min(adjustedPos.y, window.innerHeight - labelHeight));++ // Check for overlaps with existing labels+ const testRect = { x: adjustedPos.x, y: adjustedPos.y, width: labelWidth, height: labelHeight };+ let hasOverlap = false;++ for (const existing of labelPositions) {+ if (rectsOverlap(testRect, existing)) {+ hasOverlap = true;+ break;+ }+ }++ if (!hasOverlap) {+ return adjustedPos;+ }+ }++ // If all positions overlap, try to find space by offsetting+ // Try positions around the element in a spiral pattern+ const offsets = [+ { dx: 0, dy: -labelHeight - margin - 20 }, // Further above+ { dx: 0, dy: height + margin + 20 }, // Further below+ { dx: -labelWidth - margin - 20, dy: 0 }, // Further left+ { dx: width + margin + 20, dy: 0 }, // Further right+ { dx: -labelWidth - margin, dy: -labelHeight - margin }, // Top-left+ { dx: width + margin, dy: -labelHeight - margin }, // Top-right+ { dx: -labelWidth - margin, dy: height + margin }, // Bottom-left+ { dx: width + margin, dy: height + margin }, // Bottom-right+ ];++ for (const offset of offsets) {+ const pos = {+ x: Math.max(0, Math.min(x + offset.dx, window.innerWidth - labelWidth)),+ y: Math.max(0, Math.min(y + offset.dy, window.innerHeight - labelHeight))+ };++ const testRect = { x: pos.x, y: pos.y, width: labelWidth, height: labelHeight };+ let hasOverlap = false;++ for (const existing of labelPositions) {+ if (rectsOverlap(testRect, existing)) {+ hasOverlap = true;+ break;+ }+ }++ if (!hasOverlap) {+ return pos;+ }+ }++ // Fallback: use original logic but ensure within viewport+ if (isSmallElement) {+ const fallbackY = y >= 25 ? y - 25 : y + height + 2;+ return {+ x: Math.max(0, Math.min(x - 2, window.innerWidth - labelWidth)),+ y: Math.max(0, Math.min(fallbackY, window.innerHeight - labelHeight))+ };+ } else {+ return { x: x + 4, y: y + 4 };+ }+ }++ // Add labels and collect geometry data (only for filtered elements)+ Object.entries(elements).forEach(([ref, element]: [string, any]) => {+ if (element.coordinates && clickable.includes(ref)) {+ const state = elementStates.get(ref);++ // Skip completely hidden elements+ if (state === 'hidden') return;+ const label = document.createElement('div');+ const { x, y, width, height } = element.coordinates;++ label.style.cssText = `+ position: absolute;+ left: ${x}px;+ top: ${y}px;+ width: ${width}px;+ height: ${height}px;+ border: 2px ${state === 'partial' ? 'dashed' : 'solid'} #FF0066;+ border-radius: 4px;+ box-shadow: 0 2px 8px rgba(0,0,0,0.3);+ `;++ // Add ref number with smart positioning+ const refLabel = document.createElement('div');+ refLabel.textContent = ref;++ // Create temporary label to measure its size+ refLabel.style.cssText = `+ position: absolute;+ visibility: hidden;+ background: #FF0066;+ color: white;+ font: bold 12px Arial, sans-serif;+ padding: 2px 6px;+ border-radius: 2px;+ min-width: 20px;+ text-align: center;+ white-space: nowrap;+ `;+ document.body.appendChild(refLabel);+ const labelWidth = refLabel.offsetWidth;+ const labelHeight = refLabel.offsetHeight;+ document.body.removeChild(refLabel);++ // Find non-overlapping position+ const labelPos = findLabelPosition(element, labelWidth, labelHeight);++ // Apply final position+ refLabel.style.cssText = `+ position: absolute;+ left: ${labelPos.x - x}px;+ top: ${labelPos.y - y}px;+ background: #FF0066;+ color: white;+ font: bold 12px Arial, sans-serif;+ padding: 2px 6px;+ border-radius: 2px;+ min-width: 20px;+ text-align: center;+ box-shadow: 0 2px 4px rgba(0,0,0,0.2);+ opacity: ${state === 'partial' ? '0.8' : '1'};+ z-index: 1;+ white-space: nowrap;+ `;++ // Track this label position+ labelPositions.push({+ x: labelPos.x,+ y: labelPos.y,+ width: labelWidth,+ height: labelHeight,+ ref: ref+ });++ label.appendChild(refLabel);+ overlay.appendChild(label);++ // Collect geometry data+ markedElements.push({+ ref,+ x,+ y,+ width,+ height,+ center: {+ x: x + width / 2,+ y: y + height / 2+ },+ area: width * height,+ type: element.role || 'unknown',+ text: element.text || '',+ attributes: element.attributes || {},+ tagName: element.tagName || '',+ isFiltered: false+ });+ }+ });++ document.body.appendChild(overlay);++ // Force repaint+ await new Promise(resolve => requestAnimationFrame(resolve));++ return {+ overlayId: overlay.id, // Use the ID that was set earlier+ elementCount: overlay.children.length,+ markedElements,+ debugInfo+ };+ }, {+ elements: snapshotResult.elements,+ clickable: Array.from(clickableElements),+ filterDebugInfo: []+ });++ // Take screenshot+ const screenshotBuffer = await page.screenshot({+ fullPage: false,+ type: 'png'+ });++ // Keep the overlay visible for 1 second before cleanup+ await page.waitForTimeout(1000);++ // Clean up+ await page.evaluate((overlayId) => {+ const overlay = document.getElementById(overlayId);+ if (overlay) overlay.remove();+ }, result.overlayId);++ // Export element geometry if path is provided+ if (exportPath && result.markedElements) {+ try {+ const pageUrl = page.url();+ const timestamp = new Date().toISOString();+ const exportData = {+ timestamp,+ url: pageUrl,+ viewport: await page.viewportSize(),+ elements: result.markedElements,+ summary: {+ totalElements: result.markedElements.length,+ byType: result.markedElements.reduce((acc: any, el: any) => {+ acc[el.type] = (acc[el.type] || 0) + 1;+ return acc;+ }, {}),+ averageSize: {+ width: result.markedElements.reduce((sum: number, el: any) => sum + el.width, 0) / result.markedElements.length,+ height: result.markedElements.reduce((sum: number, el: any) => sum + el.height, 0) / result.markedElements.length+ }+ }+ };++ if (typeof writeFile !== 'undefined') {+ await writeFile(exportPath, JSON.stringify(exportData, null, 2));+ console.log(`Element geometry exported to: ${exportPath}`);+ }++ // Also save visibility debug info+ if (result.debugInfo) {+ const debugPath = exportPath.replace('.json', '-visibility-debug.json');++ const debugData = {+ timestamp,+ url: pageUrl,+ totalElements: result.debugInfo.length,+ summary: {+ visible: result.debugInfo.filter((d: any) => d.visibilityResult === 'visible').length,+ partial: result.debugInfo.filter((d: any) => d.visibilityResult === 'partial').length,+ hidden: result.debugInfo.filter((d: any) => d.visibilityResult === 'hidden').length+ },+ elements: result.debugInfo.sort((a: any, b: any) => {+ // Sort by visibility status: hidden first, then partial, then visible+ const order: any = { hidden: 0, partial: 1, visible: 2 };+ return order[a.visibilityResult] - order[b.visibilityResult];+ })+ };++ if (typeof writeFile !== 'undefined') {+ await writeFile(debugPath, JSON.stringify(debugData, null, 2));+ console.log(`Visibility debug info exported to: ${debugPath}`);+ }+ }+ } catch (error) {+ console.error('Failed to export element geometry:', error);+ }+ }++ const base64Image = screenshotBuffer.toString('base64');+ const dataUrl = `data:image/png;base64,${base64Image}`;++ return {+ text: `Visual webpage screenshot captured with ${result.elementCount} interactive elements marked`,+ images: [dataUrl],+ timing: {+ total_time_ms: Date.now() - startTime,+ screenshot_time_ms: Date.now() - startTime - 1100, // Approximate screenshot time (excluding 1s wait)+ snapshot_time_ms: 0, // Will be filled by caller+ coordinate_enrichment_time_ms: 0, // Will be filled by caller+ visual_marking_time_ms: 1100, // Injection, rendering and 1s display time+ injection_method: 'optimized',+ elements_count: result.elementCount,+ display_duration_ms: 1000, // Time the overlay is kept visible+ parent_child_filter_time_ms: filterTime,+ filtered_count: 0 // Filtering is done before this method is called+ }+ };++ } catch (error) {+ console.error('SOM screenshot injection error:', error);+ throw error;+ }+ }+}\ No newline at end of filediff --git a/camel/toolkits/hybrid_browser_toolkit/ts/websocket-server.js b/camel/toolkits/hybrid_browser_toolkit/ts/websocket-server.jsindex 327338f8e..a9fbf4cc6 100644--- a/camel/toolkits/hybrid_browser_toolkit/ts/websocket-server.js+++ b/camel/toolkits/hybrid_browser_toolkit/ts/websocket-server.js@@ -141,9 +141,13 @@ class WebSocketBrowserServer {if (!this.toolkit) throw new Error('Toolkit not initialized');return await this.toolkit.getPageSnapshot(params.viewport_limit);- case 'get_snapshot_for_ai':+ case 'get_snapshot_for_ai': {if (!this.toolkit) throw new Error('Toolkit not initialized');- return await this.toolkit.getSnapshotForAI();+ // Support includeCoordinates and viewportLimit parameters+ const includeCoordinates = Boolean(params.includeCoordinates);+ const viewportLimit = Boolean(params.viewportLimit);+ return await this.toolkit.session.getSnapshotForAI(includeCoordinates, viewportLimit);+ }case 'get_som_screenshot': {if (!this.toolkit) throw new Error('Toolkit not initialized');@@ -225,8 +229,10 @@ class WebSocketBrowserServer {if (!this.toolkit) throw new Error('Toolkit not initialized');return await this.toolkit.waitUser(params.timeout);- case 'shutdown':+ case 'shutdown': {console.log('Shutting down server...');++ // Close browser firstif (this.toolkit) {try {await this.toolkit.closeBrowser();@@ -234,10 +240,37 @@ class WebSocketBrowserServer {console.error('Error closing browser:', error);}}++ // Return response immediately+ const shutdownResponse = { message: 'Server shutting down' };++ // Schedule server shutdown after a short delay to ensure response is sentsetTimeout(() => {- process.exit(0);- }, 1000);- return { message: 'Server shutting down' };+ // Close the WebSocket server properly+ if (this.server) {+ this.server.close((err) => {+ if (err) {+ console.error('Error closing server:', err);+ } else {+ console.log('WebSocket server closed successfully');+ }+ console.log('Exiting process...');+ process.exit(0);+ });++ // Fallback timeout in case server close hangs+ setTimeout(() => {+ console.log('Server close timeout, forcing exit...');+ process.exit(0);+ }, 5000); // 5 second fallback+ } else {+ console.log('No server to close, exiting...');+ process.exit(0);+ }+ }, 100); // Delay to ensure response is sent++ return shutdownResponse;+ }default:throw new Error(`Unknown command: ${command}`);diff --git a/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py b/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.pyindex bea5b6169..733d515de 100644--- a/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py+++ b/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py@@ -13,6 +13,7 @@# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import asyncio+import contextlibimport datetimeimport jsonimport os@@ -115,6 +116,7 @@ class WebSocketBrowserWrapper:self._pending_responses: Dict[str, asyncio.Future[Dict[str, Any]]] = {} # Message ID -> Future+ self._server_ready_future = None # Future to track server ready state# Logging configurationself.browser_log_to_file = (config or {}).get(@@ -123,8 +125,11 @@ class WebSocketBrowserWrapper:self.session_id = (config or {}).get('session_id', 'default')self.log_file_path: Optional[str] = Noneself.log_buffer: List[Dict[str, Any]] = []+ self.ts_log_file_path: Optional[str] = None+ self.ts_log_file = None # File handle for TypeScript logs+ self._log_reader_task = None # Task for reading and logging stdout- # Set up log file if needed+ # Set up log files if neededif self.browser_log_to_file:log_dir = "browser_log"os.makedirs(log_dir, exist_ok=True)@@ -133,6 +138,11 @@ class WebSocketBrowserWrapper:log_dir,f"hybrid_browser_toolkit_ws_{timestamp}_{self.session_id}.log",)+ # Add TypeScript console log file+ self.ts_log_file_path = os.path.join(+ log_dir,+ f"typescript_console_{timestamp}_{self.session_id}.log",+ )async def __aenter__(self):"""Async context manager entry."""@@ -207,36 +217,53 @@ class WebSocketBrowserWrapper:['node', 'websocket-server.js'],cwd=self.ts_dir,stdout=subprocess.PIPE,- stderr=subprocess.PIPE,+ stderr=subprocess.STDOUT, # Redirect stderr to stdouttext=True,+ bufsize=1, # Line buffered+ )++ # Create a future to wait for server ready (before starting log reader)+ self._server_ready_future = asyncio.get_running_loop().create_future()++ # Start log reader task immediately after process starts+ self._log_reader_task = asyncio.create_task(+ self._read_and_log_output())+ if self.browser_log_to_file and self.ts_log_file_path:+ logger.info(+ f"TypeScript console logs will be written to: "+ f"{self.ts_log_file_path}"+ )+# Wait for server to output the portserver_ready = Falsetimeout = 10 # 10 seconds timeout- start_time = time.time()-- while not server_ready and time.time() - start_time < timeout:- if self.process.poll() is not None:- # Process died- stderr = self.process.stderr.read()- raise RuntimeError(- f"WebSocket server failed to start: {stderr}"- )- try:- line = self.process.stdout.readline()- if line.startswith('SERVER_READY:'):- self.server_port = int(line.split(':')[1].strip())- server_ready = True- logger.info(- f"WebSocket server ready on port {self.server_port}"- )- except (ValueError, IndexError):- continue+ # Wait for the server to be ready+ try:+ await asyncio.wait_for(self._server_ready_future, timeout=timeout)+ server_ready = True+ except asyncio.TimeoutError:+ server_ready = Falseif not server_ready:- self.process.kill()+ with contextlib.suppress(ProcessLookupError, Exception):+ self.process.kill()+ with contextlib.suppress(Exception):+ # Ensure the process fully exits+ self.process.wait(timeout=2)+ # Cancel and await the log reader task+ if self._log_reader_task and not self._log_reader_task.done():+ self._log_reader_task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await self._log_reader_task+ # Close TS log file if open+ if getattr(self, 'ts_log_file', None):+ with contextlib.suppress(Exception):+ self.ts_log_file.close()+ self.ts_log_file = None+ self.process = Noneraise RuntimeError("WebSocket server failed to start within timeout")@@ -251,7 +278,19 @@ class WebSocketBrowserWrapper:)logger.info("Connected to WebSocket server")except Exception as e:- self.process.kill()+ with contextlib.suppress(ProcessLookupError, Exception):+ self.process.kill()+ with contextlib.suppress(Exception):+ self.process.wait(timeout=2)+ if self._log_reader_task and not self._log_reader_task.done():+ self._log_reader_task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await self._log_reader_task+ if getattr(self, 'ts_log_file', None):+ with contextlib.suppress(Exception):+ self.ts_log_file.close()+ self.ts_log_file = None+ self.process = Noneraise RuntimeError(f"Failed to connect to WebSocket server: {e}") from e@@ -264,34 +303,59 @@ class WebSocketBrowserWrapper:async def stop(self):"""Stop the WebSocket connection and server."""- # Cancel the receiver task- if self._receive_task and not self._receive_task.done():- self._receive_task.cancel()- try:- await self._receive_task- except asyncio.CancelledError:- pass-+ # First, send shutdown command while receive task is still runningif self.websocket:- try:- await self._send_command('shutdown', {})+ with contextlib.suppress(asyncio.TimeoutError, Exception):+ # Send shutdown command with a short timeout+ await asyncio.wait_for(+ self._send_command('shutdown', {}),+ timeout=2.0, # 2 second timeout for shutdown+ )+ # Note: TimeoutError is expected as server may close+ # before responding++ # Close websocket connection+ with contextlib.suppress(Exception):await self.websocket.close()- except Exception as e:- logger.warning(f"Error during websocket shutdown: {e}")- finally:- self.websocket = None+ self.websocket = None+ # Gracefully stop the Node process before cancelling the log readerif self.process:try:- self.process.terminate()- self.process.wait(timeout=5)+ # give the process a short grace period to exit after shutdown+ self.process.wait(timeout=2)except subprocess.TimeoutExpired:- self.process.kill()- self.process.wait()+ try:+ self.process.terminate()+ self.process.wait(timeout=3)+ except subprocess.TimeoutExpired:+ with contextlib.suppress(ProcessLookupError, Exception):+ self.process.kill()+ self.process.wait()+ except Exception as e:+ logger.warning(f"Error terminating process: {e}")except Exception as e:- logger.warning(f"Error terminating process: {e}")- finally:- self.process = None+ logger.warning(f"Error waiting for process: {e}")++ # Now cancel background tasks (reader won't block on readline)+ tasks_to_cancel = [+ ('_receive_task', self._receive_task),+ ('_log_reader_task', self._log_reader_task),+ ]+ for _, task in tasks_to_cancel:+ if task and not task.done():+ task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await task++ # Close TS log file if open+ if getattr(self, 'ts_log_file', None):+ with contextlib.suppress(Exception):+ self.ts_log_file.close()+ self.ts_log_file = None++ # Ensure process handle cleared+ self.process = Noneasync def _log_action(self,@@ -383,8 +447,9 @@ class WebSocketBrowserWrapper:# Check if connection is still alivetry:- # Send a ping to check connection- await self.websocket.ping()+ # Send a ping and wait for the corresponding pong (bounded wait)+ pong_waiter = await self.websocket.ping()+ await asyncio.wait_for(pong_waiter, timeout=5.0)except Exception as e:logger.warning(f"WebSocket ping failed: {e}")self.websocket = None@@ -403,7 +468,8 @@ class WebSocketBrowserWrapper:message = {'id': message_id, 'command': command, 'params': params}# Create a future for this message- future: asyncio.Future[Dict[str, Any]] = asyncio.Future()+ loop = asyncio.get_running_loop()+ future: asyncio.Future[Dict[str, Any]] = loop.create_future()self._pending_responses[message_id] = futuretry:@@ -681,3 +747,73 @@ class WebSocketBrowserWrapper:'wait_user', {'timeout': timeout_sec})return response++ async def _read_and_log_output(self):+ """Read stdout from Node.js process & handle SERVER_READY + logging."""+ if not self.process:+ return++ try:+ with contextlib.ExitStack() as stack:+ if self.ts_log_file_path:+ self.ts_log_file = stack.enter_context(+ open(self.ts_log_file_path, 'w', encoding='utf-8')+ )+ self.ts_log_file.write(+ f"TypeScript Console Log - Started at "+ f"{time.strftime('%Y-%m-%d %H:%M:%S')}\n"+ )+ self.ts_log_file.write("=" * 80 + "\n")+ self.ts_log_file.flush()++ while self.process and self.process.poll() is None:+ try:+ line = (+ await asyncio.get_running_loop().run_in_executor(+ None, self.process.stdout.readline+ )+ )+ if not line: # EOF+ break++ # Check for SERVER_READY message+ if line.startswith('SERVER_READY:'):+ try:+ self.server_port = int(+ line.split(':', 1)[1].strip()+ )+ logger.info(+ f"WebSocket server ready on port "+ f"{self.server_port}"+ )+ if (+ self._server_ready_future+ and not self._server_ready_future.done()+ ):+ self._server_ready_future.set_result(True)+ except (ValueError, IndexError) as e:+ logger.error(+ f"Failed to parse SERVER_READY: {e}"+ )++ # Write all output to log file+ if self.ts_log_file:+ timestamp = time.strftime('%H:%M:%S')+ self.ts_log_file.write(f"[{timestamp}] {line}")+ self.ts_log_file.flush()++ except Exception as e:+ logger.warning(f"Error reading stdout: {e}")+ break++ # Footer if we had a file+ if self.ts_log_file:+ self.ts_log_file.write("\n" + "=" * 80 + "\n")+ self.ts_log_file.write(+ f"TypeScript Console Log - Ended at "+ f"{time.strftime('%Y-%m-%d %H:%M:%S')}\n"+ )+ # ExitStack closes file; clear handle+ self.ts_log_file = None+ except Exception as e:+ logger.warning(f"Error in _read_and_log_output: {e}")diff --git a/examples/toolkits/hybrid_browser_toolkit_example.py b/examples/toolkits/hybrid_browser_toolkit_example.pyindex fbacb511c..28b7a3d62 100644--- a/examples/toolkits/hybrid_browser_toolkit_example.py+++ b/examples/toolkits/hybrid_browser_toolkit_example.py@@ -13,11 +13,10 @@# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import asyncioimport logging-import osfrom camel.agents import ChatAgentfrom camel.models import ModelFactory-from camel.toolkits import FileWriteToolkit, HybridBrowserToolkit+from camel.toolkits import HybridBrowserToolkitfrom camel.types import ModelPlatformType, ModelTypelogging.basicConfig(@@ -69,10 +68,10 @@ custom_tools = ["browser_switch_tab","browser_enter",# "browser_get_som_screenshot", # remove it to achieve faster operation- "browser_press_key",- "browser_console_view",- "browser_console_exec",- "browser_mouse_drag",+ # "browser_press_key",+ # "browser_console_view",+ # "browser_console_exec",+ # "browser_mouse_drag",]web_toolkit_custom = HybridBrowserToolkit(@@ -81,23 +80,14 @@ web_toolkit_custom = HybridBrowserToolkit(enabled_tools=custom_tools,browser_log_to_file=True, # generate detailed log file in ./browser_logstealth=True, # Using stealth mode during browser operation- mode="python",+ viewport_limit=True,# Limit snapshot to current viewport to reduce context)print(f"Custom tools: {web_toolkit_custom.enabled_tools}")-output_dir = "./file_write_outputs"-os.makedirs(output_dir, exist_ok=True)--# Initialize the FileWriteToolkit with the output directory-file_toolkit = FileWriteToolkit(working_directory=output_dir)--# Get the tools from the toolkit-tools_list = file_toolkit.get_tools()-# Use the custom toolkit for the actual taskagent = ChatAgent(model=model_backend,- tools=[*web_toolkit_custom.get_tools(), *file_toolkit.get_tools()],+ tools=[*web_toolkit_custom.get_tools()],toolkits_to_register_agent=[web_toolkit_custom],max_iteration=10,)@@ -107,8 +97,7 @@ Use Google Search to search for news in Munich today, and click on relevantwebsites to get the news and write it in markdown.I mean you need to browse multiple websites. After visiting each website,-write the news in markdown, then return to the Google search results page-and click on other websites.+return to the Google search results page and click on other websites.Use enter to confirm search or input.If you see a cookie page, click accept all.@@ -116,12 +105,18 @@ If you see a cookie page, click accept all.async def main() -> None:- response = await agent.astep(TASK_PROMPT)- print("Task:", TASK_PROMPT)- print(f"Using user data directory: {USER_DATA_DIR}")- print(f"Enabled tools: {web_toolkit_custom.enabled_tools}")- print("\nResponse from agent:")- print(response.msgs[0].content if response.msgs else "<no response>")+ try:+ response = await agent.astep(TASK_PROMPT)+ print("Task:", TASK_PROMPT)+ print(f"Using user data directory: {USER_DATA_DIR}")+ print(f"Enabled tools: {web_toolkit_custom.enabled_tools}")+ print("\nResponse from agent:")+ print(response.msgs[0].content if response.msgs else "<no response>")+ finally:+ # Ensure browser is closed properly+ print("\nClosing browser...")+ await web_toolkit_custom.browser_close()+ print("Browser closed successfully.")if __name__ == "__main__":