File tree Expand file tree Collapse file tree 1 file changed +28
-4
lines changed Expand file tree Collapse file tree 1 file changed +28
-4
lines changed Original file line number Diff line number Diff line change @@ -282,11 +282,35 @@ function logResponse(type: string, response: any) {
282
282
283
283
// Ensure Stagehand is initialized
284
284
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 ;
288
313
}
289
- return stagehand ;
290
314
}
291
315
292
316
function sanitizeMessage ( message : any ) : string {
You can’t perform that action at this time.
0 commit comments