-
Notifications
You must be signed in to change notification settings - Fork 42
feat: don't close new opened tabs (#161) #169
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
78525a7
feat: don't close new opened tabs (#161)
arunpatro b2ee152
formatting, logs
miguelg719 535339d
changeset
miguelg719 a474768
fix: update mock_stagehand_client fixture to set internal page proper…
filip-michalsky bbd8289
feat: add page stability check to LivePageProxy for async operations
filip-michalsky 55800e4
Merge branch 'main' into tab-closing
filip-michalsky 29e34e2
formatting
filip-michalsky c0959a2
fix: prevent deadlock in page navigation and add page stability tests
filip-michalsky c51f8d0
consolidate original and active page to just one page
filip-michalsky d96a372
Update stagehand/context.py
miguelg719 15719dc
Update .changeset/gorilla-of-strongest-novelty.md
miguelg719 a274c02
timeouts
miguelg719 6f35684
python 3.10 or less compatibility
miguelg719 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"stagehand": patch | ||
--- | ||
|
||
Multi-tab support |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -33,6 +33,98 @@ | |
load_dotenv() | ||
|
||
|
||
class LivePageProxy: | ||
""" | ||
A proxy object that dynamically delegates all operations to the current active page. | ||
This mimics the behavior of the JavaScript Proxy in the original implementation. | ||
""" | ||
|
||
def __init__(self, stagehand_instance): | ||
# Use object.__setattr__ to avoid infinite recursion | ||
object.__setattr__(self, "_stagehand", stagehand_instance) | ||
|
||
async def _ensure_page_stability(self): | ||
"""Wait for any pending page switches to complete""" | ||
if hasattr(self._stagehand, "_page_switch_lock"): | ||
try: | ||
# Use wait_for for Python 3.10 compatibility (timeout prevents indefinite blocking) | ||
async def acquire_lock(): | ||
async with self._stagehand._page_switch_lock: | ||
pass # Just wait for any ongoing switches | ||
|
||
await asyncio.wait_for(acquire_lock(), timeout=30) | ||
except asyncio.TimeoutError: | ||
# Log the timeout and raise to let caller handle it | ||
if hasattr(self._stagehand, "logger"): | ||
self._stagehand.logger.error( | ||
"Timeout waiting for page stability lock", category="live_proxy" | ||
) | ||
raise RuntimeError from asyncio.TimeoutError( | ||
"Page stability lock timeout - possible deadlock detected" | ||
) | ||
|
||
def __getattr__(self, name): | ||
"""Delegate all attribute access to the current active page.""" | ||
stagehand = object.__getattribute__(self, "_stagehand") | ||
|
||
# Get the current page | ||
if hasattr(stagehand, "_page") and stagehand._page: | ||
page = stagehand._page | ||
else: | ||
raise RuntimeError("No active page available") | ||
|
||
# For async operations, make them wait for stability | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. block everything until page is set |
||
attr = getattr(page, name) | ||
if callable(attr) and asyncio.iscoroutinefunction(attr): | ||
# Don't wait for stability on navigation methods | ||
if name in ["goto", "reload", "go_back", "go_forward"]: | ||
return attr | ||
|
||
async def wrapped(*args, **kwargs): | ||
await self._ensure_page_stability() | ||
return await attr(*args, **kwargs) | ||
|
||
return wrapped | ||
return attr | ||
|
||
def __setattr__(self, name, value): | ||
"""Delegate all attribute setting to the current active page.""" | ||
if name.startswith("_"): | ||
# Internal attributes are set on the proxy itself | ||
object.__setattr__(self, name, value) | ||
else: | ||
stagehand = object.__getattribute__(self, "_stagehand") | ||
|
||
# Get the current page | ||
if hasattr(stagehand, "_page") and stagehand._page: | ||
page = stagehand._page | ||
else: | ||
raise RuntimeError("No active page available") | ||
|
||
# Set the attribute on the page | ||
setattr(page, name, value) | ||
|
||
def __dir__(self): | ||
"""Return attributes of the current active page.""" | ||
stagehand = object.__getattribute__(self, "_stagehand") | ||
|
||
if hasattr(stagehand, "_page") and stagehand._page: | ||
page = stagehand._page | ||
else: | ||
return [] | ||
|
||
return dir(page) | ||
|
||
def __repr__(self): | ||
"""Return representation of the current active page.""" | ||
stagehand = object.__getattribute__(self, "_stagehand") | ||
|
||
if hasattr(stagehand, "_page") and stagehand._page: | ||
return f"<LivePageProxy -> {repr(stagehand._page)}>" | ||
else: | ||
return "<LivePageProxy -> No active page>" | ||
|
||
|
||
class Stagehand: | ||
""" | ||
Main Stagehand class. | ||
|
@@ -166,7 +258,7 @@ def __init__( | |
self._browser = None | ||
self._context: Optional[BrowserContext] = None | ||
self._playwright_page: Optional[PlaywrightPage] = None | ||
self.page: Optional[StagehandPage] = None | ||
self._page: Optional[StagehandPage] = None | ||
self.context: Optional[StagehandContext] = None | ||
self.use_api = self.config.use_api | ||
self.experimental = self.config.experimental | ||
|
@@ -181,6 +273,8 @@ def __init__( | |
|
||
self._initialized = False # Flag to track if init() has run | ||
self._closed = False # Flag to track if resources have been closed | ||
self._live_page_proxy = None # Live page proxy | ||
self._page_switch_lock = asyncio.Lock() # Lock for page stability | ||
|
||
# Setup LLM client if LOCAL mode | ||
self.llm = None | ||
|
@@ -407,15 +501,15 @@ async def init(self): | |
self._browser, | ||
self._context, | ||
self.context, | ||
self.page, | ||
self._page, | ||
) = await connect_browserbase_browser( | ||
self._playwright, | ||
self.session_id, | ||
self.browserbase_api_key, | ||
self, | ||
self.logger, | ||
) | ||
self._playwright_page = self.page._page | ||
self._playwright_page = self._page._page | ||
except Exception: | ||
await self.close() | ||
raise | ||
|
@@ -427,15 +521,15 @@ async def init(self): | |
self._browser, | ||
self._context, | ||
self.context, | ||
self.page, | ||
self._page, | ||
self._local_user_data_dir_temp, | ||
) = await connect_local_browser( | ||
self._playwright, | ||
self.local_browser_launch_options, | ||
self, | ||
self.logger, | ||
) | ||
self._playwright_page = self.page._page | ||
self._playwright_page = self._page._page | ||
except Exception: | ||
await self.close() | ||
raise | ||
|
@@ -615,6 +709,33 @@ def _handle_llm_metrics( | |
|
||
self.update_metrics_from_response(function_enum, response, inference_time_ms) | ||
|
||
def _set_active_page(self, stagehand_page: StagehandPage): | ||
""" | ||
Internal method called by StagehandContext to update the active page. | ||
|
||
Args: | ||
stagehand_page: The StagehandPage to set as active | ||
""" | ||
self._page = stagehand_page | ||
|
||
@property | ||
def page(self) -> Optional[StagehandPage]: | ||
""" | ||
Get the current active page. This property returns a live proxy that | ||
always points to the currently focused page when multiple tabs are open. | ||
|
||
Returns: | ||
A LivePageProxy that delegates to the active StagehandPage or None if not initialized | ||
""" | ||
if not self._initialized: | ||
return None | ||
|
||
# Create the live page proxy if it doesn't exist | ||
if not self._live_page_proxy: | ||
self._live_page_proxy = LivePageProxy(self) | ||
|
||
return self._live_page_proxy | ||
|
||
|
||
# Bind the imported API methods to the Stagehand class | ||
Stagehand._create_session = _create_session | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
prevent race condition: