Skip to content

Commit b2ee152

Browse files
committed
formatting, logs
1 parent 78525a7 commit b2ee152

File tree

3 files changed

+52
-71
lines changed

3 files changed

+52
-71
lines changed

stagehand/browser.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -237,9 +237,6 @@ async def connect_local_browser(
237237

238238
# Apply stealth scripts
239239
await apply_stealth_scripts(context, logger)
240-
241-
# Initialize StagehandContext
242-
stagehand_context = await StagehandContext.init(context, stagehand_instance)
243240

244241
# Get the initial page (usually one is created by default)
245242
if context.pages:

stagehand/context.py

Lines changed: 20 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ async def get_stagehand_page(self, pw_page: Page) -> StagehandPage:
4242
return await self.create_stagehand_page(pw_page)
4343
stagehand_page = self.page_map[pw_page]
4444
# Update active page when getting a page
45-
self.set_active_page(stagehand_page)
45+
# self.set_active_page(stagehand_page)
4646
return stagehand_page
4747

4848
async def get_stagehand_pages(self) -> list:
@@ -60,13 +60,11 @@ def set_active_page(self, stagehand_page: StagehandPage):
6060
if hasattr(self.stagehand, "_set_active_page"):
6161
self.stagehand._set_active_page(stagehand_page)
6262
self.stagehand.logger.debug(
63-
f"Set active page to: {stagehand_page.url}",
64-
category="context"
63+
f"Set active page to: {stagehand_page.url}", category="context"
6564
)
6665
else:
6766
self.stagehand.logger.debug(
68-
"Stagehand does not have _set_active_page method",
69-
category="context"
67+
"Stagehand does not have _set_active_page method", category="context"
7068
)
7169

7270
def get_active_page(self) -> StagehandPage:
@@ -77,74 +75,61 @@ async def init(cls, context: BrowserContext, stagehand):
7775
stagehand.logger.debug("StagehandContext.init() called", category="context")
7876
instance = cls(context, stagehand)
7977
# Pre-initialize StagehandPages for any existing pages
80-
stagehand.logger.debug(f"Found {len(instance._context.pages)} existing pages", category="context")
78+
stagehand.logger.debug(
79+
f"Found {len(instance._context.pages)} existing pages", category="context"
80+
)
8181
for pw_page in instance._context.pages:
8282
await instance.create_stagehand_page(pw_page)
8383
if instance._context.pages:
8484
first_page = instance._context.pages[0]
8585
stagehand_page = await instance.get_stagehand_page(first_page)
8686
instance.set_active_page(stagehand_page)
87-
87+
8888
# Add event listener for new pages (popups, new tabs from window.open, etc.)
8989
def handle_page_event(pw_page):
90-
instance.stagehand.logger.debug(
91-
f"Page event fired for URL: {pw_page.url}",
92-
category="context"
93-
)
9490
instance._handle_new_page(pw_page)
95-
96-
instance.stagehand.logger.debug(
97-
f"Setting up page event listener on context (ID: {id(context)})",
98-
category="context"
99-
)
91+
10092
context.on("page", handle_page_event)
101-
instance.stagehand.logger.debug(
102-
"Page event listener setup complete",
103-
category="context"
104-
)
105-
93+
10694
return instance
107-
95+
10896
def _handle_new_page(self, pw_page: Page):
10997
"""
11098
Handle new pages created by the browser (popups, window.open, etc.).
11199
This runs synchronously in the event handler context.
112100
"""
101+
113102
async def _async_handle():
114103
try:
115104
self.stagehand.logger.debug(
116105
f"Creating StagehandPage for new page with URL: {pw_page.url}",
117-
category="context"
106+
category="context",
118107
)
119108
stagehand_page = await self.create_stagehand_page(pw_page)
120109
self.set_active_page(stagehand_page)
121-
self.stagehand.logger.log(
122-
"New page detected and initialized",
123-
level=2,
124-
category="context",
125-
auxiliary={"url": {"value": pw_page.url, "type": "string"}}
110+
self.stagehand.logger.debug(
111+
"New page detected and initialized", category="context"
126112
)
127113
except Exception as e:
128114
self.stagehand.logger.error(
129-
f"Failed to initialize new page: {str(e)}",
130-
category="context"
115+
f"Failed to initialize new page: {str(e)}", category="context"
131116
)
132117
import traceback
118+
133119
self.stagehand.logger.error(
134-
f"Traceback: {traceback.format_exc()}",
135-
category="context"
120+
f"Traceback: {traceback.format_exc()}", category="context"
136121
)
137-
122+
138123
# Schedule the async work
139124
import asyncio
125+
140126
try:
141127
loop = asyncio.get_running_loop()
142128
loop.create_task(_async_handle())
143129
except RuntimeError:
144130
# No event loop running, which shouldn't happen in normal operation
145131
self.stagehand.logger.error(
146-
"No event loop available to handle new page",
147-
category="context"
132+
"No event loop available to handle new page", category="context"
148133
)
149134

150135
def __getattr__(self, name):

stagehand/main.py

Lines changed: 32 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -38,71 +38,71 @@ class LivePageProxy:
3838
A proxy object that dynamically delegates all operations to the current active page.
3939
This mimics the behavior of the JavaScript Proxy in the original implementation.
4040
"""
41-
41+
4242
def __init__(self, stagehand_instance):
4343
# Use object.__setattr__ to avoid infinite recursion
44-
object.__setattr__(self, '_stagehand', stagehand_instance)
45-
44+
object.__setattr__(self, "_stagehand", stagehand_instance)
45+
4646
def __getattr__(self, name):
4747
"""Delegate all attribute access to the current active page."""
48-
stagehand = object.__getattribute__(self, '_stagehand')
49-
48+
stagehand = object.__getattribute__(self, "_stagehand")
49+
5050
# Get the current active page
51-
if hasattr(stagehand, '_active_page') and stagehand._active_page:
51+
if hasattr(stagehand, "_active_page") and stagehand._active_page:
5252
active_page = stagehand._active_page
53-
elif hasattr(stagehand, '_original_page') and stagehand._original_page:
53+
elif hasattr(stagehand, "_original_page") and stagehand._original_page:
5454
active_page = stagehand._original_page
5555
else:
5656
raise RuntimeError("No active page available")
57-
57+
5858
# Get the attribute from the active page
5959
attr = getattr(active_page, name)
60-
60+
6161
# If it's a method, bind it to the active page
6262
if callable(attr):
6363
return attr
64-
64+
6565
return attr
66-
66+
6767
def __setattr__(self, name, value):
6868
"""Delegate all attribute setting to the current active page."""
69-
if name.startswith('_'):
69+
if name.startswith("_"):
7070
# Internal attributes are set on the proxy itself
7171
object.__setattr__(self, name, value)
7272
else:
73-
stagehand = object.__getattribute__(self, '_stagehand')
74-
73+
stagehand = object.__getattribute__(self, "_stagehand")
74+
7575
# Get the current active page
76-
if hasattr(stagehand, '_active_page') and stagehand._active_page:
76+
if hasattr(stagehand, "_active_page") and stagehand._active_page:
7777
active_page = stagehand._active_page
78-
elif hasattr(stagehand, '_original_page') and stagehand._original_page:
78+
elif hasattr(stagehand, "_original_page") and stagehand._original_page:
7979
active_page = stagehand._original_page
8080
else:
8181
raise RuntimeError("No active page available")
82-
82+
8383
# Set the attribute on the active page
8484
setattr(active_page, name, value)
85-
85+
8686
def __dir__(self):
8787
"""Return attributes of the current active page."""
88-
stagehand = object.__getattribute__(self, '_stagehand')
89-
90-
if hasattr(stagehand, '_active_page') and stagehand._active_page:
88+
stagehand = object.__getattribute__(self, "_stagehand")
89+
90+
if hasattr(stagehand, "_active_page") and stagehand._active_page:
9191
active_page = stagehand._active_page
92-
elif hasattr(stagehand, '_original_page') and stagehand._original_page:
92+
elif hasattr(stagehand, "_original_page") and stagehand._original_page:
9393
active_page = stagehand._original_page
9494
else:
9595
return []
96-
96+
9797
return dir(active_page)
98-
98+
9999
def __repr__(self):
100100
"""Return representation of the current active page."""
101-
stagehand = object.__getattribute__(self, '_stagehand')
102-
103-
if hasattr(stagehand, '_active_page') and stagehand._active_page:
101+
stagehand = object.__getattribute__(self, "_stagehand")
102+
103+
if hasattr(stagehand, "_active_page") and stagehand._active_page:
104104
return f"<LivePageProxy -> {repr(stagehand._active_page)}>"
105-
elif hasattr(stagehand, '_original_page') and stagehand._original_page:
105+
elif hasattr(stagehand, "_original_page") and stagehand._original_page:
106106
return f"<LivePageProxy -> {repr(stagehand._original_page)}>"
107107
else:
108108
return "<LivePageProxy -> No active page>"
@@ -705,29 +705,28 @@ def _handle_llm_metrics(
705705
def _set_active_page(self, stagehand_page: StagehandPage):
706706
"""
707707
Internal method called by StagehandContext to update the active page.
708-
708+
709709
Args:
710710
stagehand_page: The StagehandPage to set as active
711711
"""
712712
self._active_page = stagehand_page
713713

714-
715714
@property
716715
def page(self) -> Optional[StagehandPage]:
717716
"""
718717
Get the current active page. This property returns a live proxy that
719718
always points to the currently focused page when multiple tabs are open.
720-
719+
721720
Returns:
722721
A LivePageProxy that delegates to the active StagehandPage or None if not initialized
723722
"""
724723
if not self._initialized:
725724
return None
726-
725+
727726
# Create the live page proxy if it doesn't exist
728727
if not self._live_page_proxy:
729728
self._live_page_proxy = LivePageProxy(self)
730-
729+
731730
return self._live_page_proxy
732731

733732

0 commit comments

Comments
 (0)