(
sessionId: string,
config: Config,
createIfMissing: boolean = true,
)
| 355 | |
| 356 | // Get a specific session by ID |
| 357 | async getSession( |
| 358 | sessionId: string, |
| 359 | config: Config, |
| 360 | createIfMissing: boolean = true, |
| 361 | ): Promise<BrowserSession | null> { |
| 362 | if (sessionId === this.defaultSessionId && createIfMissing) { |
| 363 | try { |
| 364 | return await this.ensureDefaultSessionInternal(config); |
| 365 | } catch { |
| 366 | process.stderr.write( |
| 367 | `[SessionManager] Failed to get default session due to error in ensureDefaultSessionInternal for ${sessionId}. See previous messages for details.\n`, |
| 368 | ); |
| 369 | return null; |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | // For non-default sessions |
| 374 | process.stderr.write(`[SessionManager] Getting session: ${sessionId}\n`); |
| 375 | const sessionObj = this.browsers.get(sessionId); |
| 376 | |
| 377 | if (!sessionObj) { |
| 378 | process.stderr.write( |
| 379 | `[SessionManager] WARN - Session not found in map: ${sessionId}\n`, |
| 380 | ); |
| 381 | return null; |
| 382 | } |
| 383 | |
| 384 | try { |
| 385 | const pages = sessionObj.stagehand.context.pages(); |
| 386 | if (!pages || pages.length === 0) { |
| 387 | throw new Error("No pages available"); |
| 388 | } |
| 389 | } catch { |
| 390 | process.stderr.write( |
| 391 | `[SessionManager] WARN - Found session ${sessionId} is stale, removing.\n`, |
| 392 | ); |
| 393 | await this.closeBrowserGracefully(sessionObj, sessionId); |
| 394 | this.browsers.delete(sessionId); |
| 395 | if (this.activeSessionId === sessionId) { |
| 396 | process.stderr.write( |
| 397 | `[SessionManager] WARN - Invalidated active session ${sessionId}, resetting to default.\n`, |
| 398 | ); |
| 399 | this.setActiveSessionId(this.defaultSessionId); |
| 400 | } |
| 401 | return null; |
| 402 | } |
| 403 | |
| 404 | // Session appears valid, make it active |
| 405 | this.setActiveSessionId(sessionId); |
| 406 | process.stderr.write( |
| 407 | `[SessionManager] Using valid session: ${sessionId}\n`, |
| 408 | ); |
| 409 | return sessionObj; |
| 410 | } |
| 411 | |
| 412 | /** |
| 413 | * Clean up a session by closing the browser and removing it from tracking. |
no test coverage detected