Skip to content

Commit a20a1ea

Browse files
fix timeout bb session error
1 parent 331e646 commit a20a1ea

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
@@ -282,11 +282,35 @@ function logResponse(type: string, response: any) {
282282

283283
// Ensure Stagehand is initialized
284284
async function ensureStagehand() {
285-
if (!stagehand) {
286-
stagehand = new Stagehand(stagehandConfig);
287-
await stagehand.init();
285+
try {
286+
if (!stagehand) {
287+
stagehand = new Stagehand(stagehandConfig);
288+
await stagehand.init();
289+
return stagehand;
290+
}
291+
292+
// Try to perform a simple operation to check if the session is still valid
293+
try {
294+
await stagehand.page.evaluate(() => document.title);
295+
return stagehand;
296+
} catch (error) {
297+
// If we get an error indicating the session is invalid, reinitialize
298+
if (error instanceof Error &&
299+
(error.message.includes('Target page, context or browser has been closed') ||
300+
error.message.includes('Session expired') ||
301+
error.message.includes('context destroyed'))) {
302+
log('Browser session expired, reinitializing Stagehand...', 'info');
303+
stagehand = new Stagehand(stagehandConfig);
304+
await stagehand.init();
305+
return stagehand;
306+
}
307+
throw error; // Re-throw if it's a different type of error
308+
}
309+
} catch (error) {
310+
const errorMsg = error instanceof Error ? error.message : String(error);
311+
log(`Failed to initialize/reinitialize Stagehand: ${errorMsg}`, 'error');
312+
throw error;
288313
}
289-
return stagehand;
290314
}
291315

292316
function sanitizeMessage(message: any): string {

0 commit comments

Comments
 (0)