fix(browser): multi-thread browser instance bug

This commit is contained in:
zhayujie
2026-03-30 00:57:19 +08:00
parent e4f9697d06
commit fa149cf4aa
2 changed files with 13 additions and 2 deletions

View File

@@ -10,6 +10,7 @@ import os
import sys import sys
import re import re
import uuid import uuid
import threading
from typing import Optional, Dict, Any, List from typing import Optional, Dict, Any, List
from common.log import logger from common.log import logger
@@ -206,13 +207,21 @@ class BrowserService:
self._page: Optional[Page] = None self._page: Optional[Page] = None
self._headless: Optional[bool] = None self._headless: Optional[bool] = None
self._screenshot_dir: Optional[str] = None self._screenshot_dir: Optional[str] = None
self._owner_thread: Optional[int] = None
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# Lifecycle # Lifecycle
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def _ensure_browser(self): def _ensure_browser(self):
"""Lazily launch browser on first use.""" """Lazily launch browser on first use. Re-launch if called from a different thread."""
current_thread = threading.current_thread().ident
# Playwright sync API is single-threaded; if called from a different thread, restart
if self._owner_thread and self._owner_thread != current_thread and self._playwright:
logger.info("[Browser] Thread changed, restarting browser instance")
self.close()
if self._page and not self._page.is_closed(): if self._page and not self._page.is_closed():
return return
@@ -248,6 +257,7 @@ class BrowserService:
), ),
) )
self._page = self._context.new_page() self._page = self._context.new_page()
self._owner_thread = current_thread
logger.info("[Browser] Browser ready") logger.info("[Browser] Browser ready")
@property @property
@@ -276,6 +286,7 @@ class BrowserService:
self._context = None self._context = None
self._browser = None self._browser = None
self._playwright = None self._playwright = None
self._owner_thread = None
logger.info("[Browser] Browser closed") logger.info("[Browser] Browser closed")
# ------------------------------------------------------------------ # ------------------------------------------------------------------

View File

@@ -22,7 +22,7 @@ CowAgent 支持灵活切换多种模型,能处理文本、语音、图片、
<CardGroup cols={2}> <CardGroup cols={2}>
<Card title="复杂任务规划" icon="brain" href="/intro/architecture"> <Card title="复杂任务规划" icon="brain" href="/intro/architecture">
能够理解复杂任务并自主规划执行,持续思考和调用工具直到完成目标,支持通过工具操作访问文件、终端、浏览器、定时任务等系统资源 能够理解复杂任务并自主规划执行,持续思考和调用各类工具和技能直到完成目标
</Card> </Card>
<Card title="长期记忆" icon="database" href="/memory"> <Card title="长期记忆" icon="database" href="/memory">
自动将对话记忆持久化至本地文件和数据库中,包括全局记忆和天级记忆,支持关键词及向量检索。 自动将对话记忆持久化至本地文件和数据库中,包括全局记忆和天级记忆,支持关键词及向量检索。