Skip to content

Commit c3969c3

Browse files
authored
Merge pull request #31 from browserbase/fm/stg-208-fix-timeout
fix timeout bb session error
2 parents 7cd4b80 + a20a1ea commit c3969c3

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

stagehand/src/index.ts

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -190,11 +190,35 @@ function logResponse(type: string, response: any) {
190190

191191
// Ensure Stagehand is initialized
192192
async function ensureStagehand() {
193-
if (!stagehand) {
194-
stagehand = new Stagehand(stagehandConfig);
195-
await stagehand.init();
193+
try {
194+
if (!stagehand) {
195+
stagehand = new Stagehand(stagehandConfig);
196+
await stagehand.init();
197+
return stagehand;
198+
}
199+
200+
// Try to perform a simple operation to check if the session is still valid
201+
try {
202+
await stagehand.page.evaluate(() => document.title);
203+
return stagehand;
204+
} catch (error) {
205+
// If we get an error indicating the session is invalid, reinitialize
206+
if (error instanceof Error &&
207+
(error.message.includes('Target page, context or browser has been closed') ||
208+
error.message.includes('Session expired') ||
209+
error.message.includes('context destroyed'))) {
210+
log('Browser session expired, reinitializing Stagehand...', 'info');
211+
stagehand = new Stagehand(stagehandConfig);
212+
await stagehand.init();
213+
return stagehand;
214+
}
215+
throw error; // Re-throw if it's a different type of error
216+
}
217+
} catch (error) {
218+
const errorMsg = error instanceof Error ? error.message : String(error);
219+
log(`Failed to initialize/reinitialize Stagehand: ${errorMsg}`, 'error');
220+
throw error;
196221
}
197-
return stagehand;
198222
}
199223

200224
function sanitizeMessage(message: any): string {

0 commit comments

Comments
 (0)