@@ -2,6 +2,7 @@ import { Page, BrowserContext } from "@browserbasehq/stagehand";
22import type { Config } from "../config.d.ts" ;
33import type { Cookie } from "playwright-core" ;
44import { createStagehandInstance } from "./stagehandStore.js" ;
5+ import { clearScreenshotsForSession } from "./mcp/resources.js" ;
56import type { BrowserSession } from "./types/types.js" ;
67
78// Global state for managing browser sessions
@@ -131,6 +132,21 @@ export async function createNewBrowserSession(
131132 ) ;
132133 setActiveSessionId ( defaultSessionId ) ;
133134 }
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+ }
134150 } ) ;
135151
136152 // Add cookies to the context if they are provided in the config
@@ -192,6 +208,20 @@ async function closeBrowserGracefully(
192208 process . stderr . write (
193209 `[SessionManager] Successfully closed Stagehand and browser for session: ${ sessionIdToLog } \n` ,
194210 ) ;
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+ }
195225 } catch ( closeError ) {
196226 process . stderr . write (
197227 `[SessionManager] WARN - Error closing Stagehand for session ${ sessionIdToLog } : ${
@@ -335,6 +365,17 @@ export async function cleanupSession(sessionId: string): Promise<void> {
335365 // Remove from browsers map
336366 browsers . delete ( sessionId ) ;
337367
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+
338379 // Clear default session reference if this was the default
339380 if ( sessionId === defaultSessionId && defaultBrowserSession ) {
340381 defaultBrowserSession = null ;
0 commit comments