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 @@ -190,11 +190,35 @@ function logResponse(type: string, response: any) {
190
190
191
191
// Ensure Stagehand is initialized
192
192
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 ;
196
221
}
197
- return stagehand ;
198
222
}
199
223
200
224
function sanitizeMessage ( message : any ) : string {
You can’t perform that action at this time.
0 commit comments