@@ -2,6 +2,7 @@ import { Page, BrowserContext } from "@browserbasehq/stagehand";
2
2
import type { Config } from "../config.d.ts" ;
3
3
import type { Cookie } from "playwright-core" ;
4
4
import { createStagehandInstance } from "./stagehandStore.js" ;
5
+ import { clearScreenshotsForSession } from "./mcp/resources.js" ;
5
6
import type { BrowserSession } from "./types/types.js" ;
6
7
7
8
// Global state for managing browser sessions
@@ -131,6 +132,21 @@ export async function createNewBrowserSession(
131
132
) ;
132
133
setActiveSessionId ( defaultSessionId ) ;
133
134
}
135
+
136
+ // Purge any screenshots associated with both internal and Browserbase IDs
137
+ try {
138
+ clearScreenshotsForSession ( newSessionId ) ;
139
+ const bbId = browserbaseSessionId ;
140
+ if ( bbId ) {
141
+ clearScreenshotsForSession ( bbId ) ;
142
+ }
143
+ } catch ( err ) {
144
+ process . stderr . write (
145
+ `[SessionManager] WARN - Failed to clear screenshots on disconnect for ${ newSessionId } : ${
146
+ err instanceof Error ? err . message : String ( err )
147
+ } \n`,
148
+ ) ;
149
+ }
134
150
} ) ;
135
151
136
152
// Add cookies to the context if they are provided in the config
@@ -192,6 +208,20 @@ async function closeBrowserGracefully(
192
208
process . stderr . write (
193
209
`[SessionManager] Successfully closed Stagehand and browser for session: ${ sessionIdToLog } \n` ,
194
210
) ;
211
+ // After close, purge any screenshots associated with both internal and Browserbase IDs
212
+ try {
213
+ clearScreenshotsForSession ( sessionIdToLog ) ;
214
+ const bbId = session ?. stagehand ?. browserbaseSessionID ;
215
+ if ( bbId ) {
216
+ clearScreenshotsForSession ( bbId ) ;
217
+ }
218
+ } catch ( err ) {
219
+ process . stderr . write (
220
+ `[SessionManager] WARN - Failed to clear screenshots after close for ${ sessionIdToLog } : ${
221
+ err instanceof Error ? err . message : String ( err )
222
+ } \n`,
223
+ ) ;
224
+ }
195
225
} catch ( closeError ) {
196
226
process . stderr . write (
197
227
`[SessionManager] WARN - Error closing Stagehand for session ${ sessionIdToLog } : ${
@@ -335,6 +365,17 @@ export async function cleanupSession(sessionId: string): Promise<void> {
335
365
// Remove from browsers map
336
366
browsers . delete ( sessionId ) ;
337
367
368
+ // Always purge screenshots for this (internal) session id
369
+ try {
370
+ clearScreenshotsForSession ( sessionId ) ;
371
+ } catch ( err ) {
372
+ process . stderr . write (
373
+ `[SessionManager] WARN - Failed to clear screenshots during cleanup for ${ sessionId } : ${
374
+ err instanceof Error ? err . message : String ( err )
375
+ } \n`,
376
+ ) ;
377
+ }
378
+
338
379
// Clear default session reference if this was the default
339
380
if ( sessionId === defaultSessionId && defaultBrowserSession ) {
340
381
defaultBrowserSession = null ;
0 commit comments