diff --git a/app.py b/app.py index 2dafa7c..ae4b7bf 100644 --- a/app.py +++ b/app.py @@ -85,101 +85,93 @@ async def run_browser_task(task_id: str, task: str, max_steps: int, model: str): import urllib.request import sys - print(f"[{task_id}] Starting Chrome with Remote Debugging on port {REMOTE_DEBUGGING_PORT}...") - - # Список возможных путей к Chrome - chrome_exe = None - possible_paths = [ - "/root/.cache/ms-playwright/chromium-1208/chrome-linux64/chrome", - "/root/.cache/ms-playwright/chromium-*/chrome-linux64/chrome", - "/ms-playwright/*/chrome-linux/chrome", - "/usr/bin/google-chrome", - "/usr/bin/chromium", - "/usr/bin/chromium-browser", - ] - - for path_pattern in possible_paths: - matches = glob.glob(path_pattern) - if matches: - chrome_exe = matches[0] - break - - if not chrome_exe: - # Попробуем найти через shutil - import shutil - chrome_exe = shutil.which("google-chrome") or shutil.which("chromium") or shutil.which("chromium-browser") - - if not chrome_exe: - raise RuntimeError(f"Chrome not found. Please ensure playwright browsers are installed.") - - print(f"[{task_id}] Using Chrome executable: {chrome_exe}") - - # Создаем уникальную директорию для профиля (чтобы избежать блокировки) - import uuid - unique_id = str(uuid.uuid4())[:8] - user_data_dir = f"/tmp/browser-data-{unique_id}" - os.makedirs(user_data_dir, exist_ok=True) - - # Запускаем Chrome с remote debugging - chrome_cmd = [ - chrome_exe, - f"--remote-debugging-port={REMOTE_DEBUGGING_PORT}", - f"--remote-debugging-address=0.0.0.0", - f"--user-data-dir={user_data_dir}", - "--no-first-run", - "--no-default-browser-check", - "--disable-extensions", - "--disable-gpu", - "--no-sandbox", - "--disable-dev-shm-usage", - "--headless", - "about:blank" - ] - - print(f"[{task_id}] Executing command: {' '.join(chrome_cmd)}") - - # Запускаем процесс - process = subprocess.Popen( - chrome_cmd, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True - ) - - # Ждем пока Chrome запустится и CDP будет готов - cdp_ready = False cdp_url = f"http://127.0.0.1:{REMOTE_DEBUGGING_PORT}" - for i in range(30): # Ждем до 30 секунд - await asyncio.sleep(1) + # 1. Проверяем, не запущен ли уже Chrome с CDP + print(f"[{task_id}] Checking if Chrome is already running with CDP at {cdp_url}...") + chrome_already_running = False + try: + response = urllib.request.urlopen(f"{cdp_url}/json/version", timeout=2) + if response.status == 200: + print(f"[{task_id}] Chrome is already running, connecting to existing instance.") + chrome_already_running = True + except Exception: + print(f"[{task_id}] Chrome not detected at {cdp_url}. Starting new instance...") + + if not chrome_already_running: + # Список возможных путей к Chrome + chrome_exe = None + possible_paths = [ + "/root/.cache/ms-playwright/chromium-1208/chrome-linux64/chrome", + "/root/.cache/ms-playwright/chromium-*/chrome-linux64/chrome", + "/ms-playwright/*/chrome-linux/chrome", + "/usr/bin/google-chrome", + "/usr/bin/chromium", + "/usr/bin/chromium-browser", + ] - # Проверяем, не упал ли процесс - if process.poll() is not None: - stdout, stderr = process.communicate() - raise RuntimeError( - f"Chrome process exited unexpectedly with code {process.returncode}.\n" - f"STDOUT: {stdout}\n" - f"STDERR: {stderr}" - ) - - try: - response = urllib.request.urlopen(f"{cdp_url}/json/version", timeout=2) - if response.status == 200: - cdp_ready = True - print(f"[{task_id}] CDP is ready at {cdp_url}") + for path_pattern in possible_paths: + matches = glob.glob(path_pattern) + if matches: + chrome_exe = matches[0] break - except Exception: - if i % 5 == 0: - print(f"[{task_id}] Waiting for CDP at {cdp_url}... (attempt {i})") - - if not cdp_ready: - # Получаем логи Chrome - stdout, stderr = process.communicate(timeout=5) - raise RuntimeError( - f"Chrome started but CDP not ready after 30s at {cdp_url}.\n" - f"STDOUT: {stdout}\n" - f"STDERR: {stderr}" + + if not chrome_exe: + import shutil + chrome_exe = shutil.which("google-chrome") or shutil.which("chromium") or shutil.which("chromium-browser") + + if not chrome_exe: + raise RuntimeError(f"Chrome not found. Please ensure playwright browsers are installed.") + + print(f"[{task_id}] Using Chrome executable: {chrome_exe}") + + # Используем постоянную директорию для сохранения сессий (логинов) + user_data_dir = "/app/browser-data/main_profile" + os.makedirs(user_data_dir, exist_ok=True) + + # Запускаем Chrome с remote debugging + chrome_cmd = [ + chrome_exe, + f"--remote-debugging-port={REMOTE_DEBUGGING_PORT}", + f"--remote-debugging-address=0.0.0.0", + f"--user-data-dir={user_data_dir}", + "--remote-allow-origins=*", + "--no-first-run", + "--no-default-browser-check", + "--disable-extensions", + "--disable-gpu", + "--no-sandbox", + "--disable-dev-shm-usage", + "--headless", + "about:blank" + ] + + print(f"[{task_id}] Executing command: {' '.join(chrome_cmd)}") + + # Запускаем процесс (без блокировки, в фоне) + subprocess.Popen( + chrome_cmd, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True ) + + # Ждем пока Chrome запустится и CDP будет готов + cdp_ready = False + for i in range(30): # Ждем до 30 секунд + await asyncio.sleep(1) + try: + response = urllib.request.urlopen(f"{cdp_url}/json/version", timeout=2) + if response.status == 200: + cdp_ready = True + print(f"[{task_id}] CDP is ready at {cdp_url}") + break + except Exception: + if i % 5 == 0: + print(f"[{task_id}] Waiting for CDP at {cdp_url}... (attempt {i})") + + if not cdp_ready: + raise RuntimeError(f"Failed to start Chrome or CDP not ready after 30s at {cdp_url}") # Подключаемся через CDP from browser_use import BrowserConfig