Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
Fix Dockerfile.dev, make browser manager robust to the browser closing
Dillon DuPont3f0ed2c20309
diff --git a/libs/python/computer-server/computer_server/browser.py b/libs/python/computer-server/computer_server/browser.pyindex 3d0a4c69cd..bd0f3f7e18 100644--- a/libs/python/computer-server/computer_server/browser.py+++ b/libs/python/computer-server/computer_server/browser.py@@ -9,7 +9,7 @@ import osfrom typing import Any, Dict, Optionaltry:- from playwright.async_api import async_playwright, Browser, BrowserContext, Page+ from playwright.async_api import Browser, BrowserContext, Page, async_playwrightexcept ImportError:async_playwright = NoneBrowser = None@@ -122,14 +122,57 @@ class BrowserManager:except Exception as e:logger.error(f"Failed to initialize browser: {e}")import traceback+logger.error(traceback.format_exc())# Don't raise - return error in execute_command insteadself._initialization_error = str(e)raise+ async def _execute_command_impl(self, cmd: str, params: Dict[str, Any]) -> Dict[str, Any]:+ """Internal implementation of command execution."""+ if cmd == "visit_url":+ url = params.get("url")+ if not url:+ return {"success": False, "error": "url parameter is required"}+ await self.page.goto(url, wait_until="domcontentloaded", timeout=30000)+ return {"success": True, "url": self.page.url}++ elif cmd == "click":+ x = params.get("x")+ y = params.get("y")+ if x is None or y is None:+ return {"success": False, "error": "x and y parameters are required"}+ await self.page.mouse.click(x, y)+ return {"success": True}++ elif cmd == "type":+ text = params.get("text")+ if text is None:+ return {"success": False, "error": "text parameter is required"}+ await self.page.keyboard.type(text)+ return {"success": True}++ elif cmd == "scroll":+ delta_x = params.get("delta_x", 0)+ delta_y = params.get("delta_y", 0)+ await self.page.mouse.wheel(delta_x, delta_y)+ return {"success": True}++ elif cmd == "web_search":+ query = params.get("query")+ if not query:+ return {"success": False, "error": "query parameter is required"}+ # Navigate to Google search+ search_url = f"https://www.google.com/search?q={query}"+ await self.page.goto(search_url, wait_until="domcontentloaded", timeout=30000)+ return {"success": True, "url": self.page.url}++ else:+ return {"success": False, "error": f"Unknown command: {cmd}"}+async def execute_command(self, cmd: str, params: Dict[str, Any]) -> Dict[str, Any]:"""- Execute a browser command.+ Execute a browser command with automatic recovery.Args:cmd: Command name (visit_url, click, type, scroll, web_search)@@ -138,57 +181,88 @@ class BrowserManager:Returns:Result dictionary with success status and any data"""- try:- await self._ensure_initialized()- except Exception as e:- error_msg = getattr(self, '_initialization_error', None) or str(e)- logger.error(f"Browser initialization failed: {error_msg}")- return {- "success": False,- "error": f"Browser initialization failed: {error_msg}. "- f"Make sure Playwright and Firefox are installed, and DISPLAY is set correctly."- }-- # Ensure browser is still initialized (in case it was manually closed)- # This will automatically reinitialize if the browser was closed- await self._ensure_initialized()-- # Check if page is still valid- page_valid = False- try:- if self.page is not None:- # Try to access page.url to check if it's still valid- _ = self.page.url- page_valid = True- except Exception as e:- logger.warning(f"Page is invalid: {e}, will get a new page...")- self.page = None-- # Get a valid page if we don't have one- if not page_valid or self.page is None:+ max_retries = 2+ for attempt in range(max_retries):try:- pages = self.context.pages- if pages:- # Find first non-closed page- for p in pages:+ await self._ensure_initialized()+ except Exception as e:+ error_msg = getattr(self, "_initialization_error", None) or str(e)+ logger.error(f"Browser initialization failed: {error_msg}")+ return {+ "success": False,+ "error": f"Browser initialization failed: {error_msg}. "+ f"Make sure Playwright and Firefox are installed, and DISPLAY is set correctly.",+ }++ # Check if page is still valid and get a new one if needed+ page_valid = False+ try:+ if self.page is not None and not self.page.is_closed():+ # Try to access page.url to check if it's still valid+ _ = self.page.url+ page_valid = True+ except Exception as e:+ logger.warning(f"Page is invalid: {e}, will get a new page...")+ self.page = None++ # Get a valid page if we don't have one+ if not page_valid or self.page is None:+ try:+ if self.context:+ pages = self.context.pages+ if pages:+ # Find first non-closed page+ for p in pages:+ try:+ if not p.is_closed():+ self.page = p+ logger.info("Reusing existing open page")+ page_valid = True+ break+ except Exception:+ continue++ # If no valid page found, create a new one+ if not page_valid:+ self.page = await self.context.new_page()+ logger.info("Created new page")+ except Exception as e:+ logger.error(f"Failed to get new page: {e}, browser may be closed")+ # Browser was closed - force reinitialization+ self._initialized = False+ self.context = None+ self.page = None+ if self.playwright:try:- if not p.is_closed():- self.page = p- logger.info("Reusing existing open page")- page_valid = True- break+ await self.playwright.stop()except Exception:- continue-- # If no valid page found, create a new one- if not page_valid:- self.page = await self.context.new_page()- logger.info("Created new page")+ pass+ self.playwright = None++ # If this isn't the last attempt, continue to retry+ if attempt < max_retries - 1:+ logger.info("Browser was closed, retrying with fresh initialization...")+ continue+ else:+ return {+ "success": False,+ "error": f"Browser was closed and cannot be recovered: {e}",+ }++ # Try to execute the command+ try:+ return await self._execute_command_impl(cmd, params)except Exception as e:- logger.error(f"Failed to get new page: {e}, browser may be closed")- # Browser was closed - reinitialize it- try:- logger.info("Browser was closed manually, reinitializing...")+ error_str = str(e)+ logger.error(f"Error executing command {cmd}: {e}")++ # Check if this is a "browser/page/context closed" error+ if any(keyword in error_str.lower() for keyword in ["closed", "target", "context"]):+ logger.warning(+ f"Browser/page was closed during command execution (attempt {attempt + 1}/{max_retries})"+ )++ # Force reinitializationself._initialized = Falseself.context = Noneself.page = None@@ -198,80 +272,25 @@ class BrowserManager:except Exception:passself.playwright = None-- # Reinitialize- await self._ensure_initialized()- # Get or create a page- pages = self.context.pages- if pages:- self.page = pages[0]++ # If this isn't the last attempt, retry+ if attempt < max_retries - 1:+ logger.info("Retrying command after browser reinitialization...")+ continueelse:- self.page = await self.context.new_page()- logger.info("Browser reopened successfully after manual closure")- except Exception as reinit_error:- logger.error(f"Failed to reinitialize browser: {reinit_error}")+ return {+ "success": False,+ "error": f"Command failed after {max_retries} attempts: {error_str}",+ }+ else:+ # Not a browser closed error, return immediatelyimport traceback+logger.error(traceback.format_exc())- return {"success": False, "error": f"Browser was closed and cannot be recovered: {reinit_error}"}-- try:- if cmd == "visit_url":- url = params.get("url")- if not url:- return {"success": False, "error": "url parameter is required"}- await self.page.goto(url, wait_until="domcontentloaded", timeout=30000)- return {"success": True, "url": self.page.url}-- elif cmd == "click":- x = params.get("x")- y = params.get("y")- if x is None or y is None:- return {"success": False, "error": "x and y parameters are required"}- await self.page.mouse.click(x, y)- return {"success": True}-- elif cmd == "type":- text = params.get("text")- if text is None:- return {"success": False, "error": "text parameter is required"}- await self.page.keyboard.type(text)- return {"success": True}-- elif cmd == "scroll":- delta_x = params.get("delta_x", 0)- delta_y = params.get("delta_y", 0)- await self.page.mouse.wheel(delta_x, delta_y)- return {"success": True}-- elif cmd == "web_search":- query = params.get("query")- if not query:- return {"success": False, "error": "query parameter is required"}- # Navigate to Google search- search_url = f"https://www.google.com/search?q={query}"- await self.page.goto(search_url, wait_until="domcontentloaded", timeout=30000)- return {"success": True, "url": self.page.url}-- else:- return {"success": False, "error": f"Unknown command: {cmd}"}-- except Exception as e:- logger.error(f"Error executing command {cmd}: {e}")- import traceback- logger.error(traceback.format_exc())- # If page was closed due to error, try to recover- if "closed" in str(e).lower() and self.context:- try:- pages = self.context.pages- if pages:- self.page = pages[0]- logger.info("Recovered page after error")- else:- self.page = await self.context.new_page()- logger.info("Created new page after error")- except Exception as recover_error:- logger.error(f"Failed to recover page: {recover_error}")- return {"success": False, "error": str(e)}+ return {"success": False, "error": error_str}++ # Should never reach here, but just in case+ return {"success": False, "error": "Command failed after all retries"}async def close(self):"""Close the browser and cleanup resources."""@@ -305,4 +324,3 @@ def get_browser_manager() -> BrowserManager:if _browser_manager is None:_browser_manager = BrowserManager()return _browser_manager-diff --git a/libs/xfce/Development.md b/libs/xfce/Development.mdindex 4bc12c813a..b67199e834 100644--- a/libs/xfce/Development.md+++ b/libs/xfce/Development.md@@ -11,6 +11,14 @@ docker build -f Dockerfile.dev -t cua-xfce:dev ..The build context is set to the parent directory to allow copying the local `computer-server` source.+## Tagging the Image++To tag the dev image as latest:++```bash+docker tag cua-xfce:dev cua-xfce:latest+```+## Running the Development Container```bashdiff --git a/libs/xfce/Dockerfile.dev b/libs/xfce/Dockerfile.devindex 12036a0cec..c24efaf9d7 100644--- a/libs/xfce/Dockerfile.dev+++ b/libs/xfce/Dockerfile.dev@@ -105,7 +105,7 @@ RUN mkdir -p /home/cua/.cache && \chown -R cua:cua /home/cua/.cache# Copy local computer-server source and install it-COPY ../python/computer-server /tmp/computer-server+COPY python/computer-server /tmp/computer-serverRUN python3.12 -m pip install /tmp/computer-server && \rm -rf /tmp/computer-server@@ -117,8 +117,8 @@ RUN python3.12 -m pip install playwright && \RUN chown -R cua:cua /home/cua/.cache# Copy startup scripts-COPY src/supervisor/ /etc/supervisor/conf.d/-COPY src/scripts/ /usr/local/bin/+COPY xfce/src/supervisor/ /etc/supervisor/conf.d/+COPY xfce/src/scripts/ /usr/local/bin/# Make scripts executableRUN chmod +x /usr/local/bin/*.sh@@ -135,9 +135,9 @@ RUN mkdir -p $HOME/.vncRUN mkdir -p $HOME/.config/xfce4/xfconf/xfce-perchannel-xml $HOME/.config/xfce4 $HOME/.config/autostart# Copy XFCE config to disable browser launching and welcome screens-COPY --chown=cua:cua src/xfce-config/helpers.rc $HOME/.config/xfce4/helpers.rc-COPY --chown=cua:cua src/xfce-config/xfce4-session.xml $HOME/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-session.xml-COPY --chown=cua:cua src/xfce-config/xfce4-power-manager.xml $HOME/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml+COPY --chown=cua:cua xfce/src/xfce-config/helpers.rc $HOME/.config/xfce4/helpers.rc+COPY --chown=cua:cua xfce/src/xfce-config/xfce4-session.xml $HOME/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-session.xml+COPY --chown=cua:cua xfce/src/xfce-config/xfce4-power-manager.xml $HOME/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml# Disable autostart for screensaver, lock screen, and power managerRUN echo "[Desktop Entry]\nHidden=true" > $HOME/.config/autostart/xfce4-tips-autostart.desktop && \