@@ -195,6 +195,8 @@ export class SandboxClient {
195195 this . attemptAutoReconnect ( ) ;
196196 }
197197 } else if ( state === "CONNECTED" ) {
198+ // Reset keep-alive failures on successful connection
199+ this . keepAliveFailures = 0 ;
198200 if ( this . shouldKeepAlive ) {
199201 this . keepActiveWhileConnected ( true ) ;
200202 }
@@ -389,6 +391,8 @@ export class SandboxClient {
389391 private keepAliveInterval : NodeJS . Timeout | null = null ;
390392 private shouldKeepAlive = false ;
391393 private isExplicitlyDisconnected = false ;
394+ private keepAliveFailures = 0 ;
395+ private maxKeepAliveFailures = 3 ;
392396 /**
393397 * If enabled, we will keep the sandbox from hibernating as long as the SDK is connected to it.
394398 */
@@ -399,9 +403,31 @@ export class SandboxClient {
399403 if ( enabled ) {
400404 if ( ! this . keepAliveInterval ) {
401405 this . keepAliveInterval = setInterval ( ( ) => {
402- this . agentClient . system . update ( ) . catch ( ( error ) => {
403- console . warn ( "Unable to keep active while connected" , error ) ;
404- } ) ;
406+ this . agentClient . system . update ( )
407+ . then ( ( ) => {
408+ // Reset failure count on success
409+ this . keepAliveFailures = 0 ;
410+ } )
411+ . catch ( ( error ) => {
412+ this . keepAliveFailures ++ ;
413+ console . warn ( `Keep-alive failed (${ this . keepAliveFailures } /${ this . maxKeepAliveFailures } ):` , error ) ;
414+
415+ // If we've hit max failures, stop aggressive keep-alive to prevent connection thrashing
416+ if ( this . keepAliveFailures >= this . maxKeepAliveFailures ) {
417+ console . warn ( "Max keep-alive failures reached, reducing frequency to prevent connection issues" ) ;
418+ if ( this . keepAliveInterval ) {
419+ clearInterval ( this . keepAliveInterval ) ;
420+ this . keepAliveInterval = null ;
421+ }
422+ // Restart with longer interval after failures
423+ setTimeout ( ( ) => {
424+ if ( this . shouldKeepAlive && ! this . keepAliveInterval ) {
425+ this . keepActiveWhileConnected ( true ) ;
426+ this . keepAliveFailures = 0 ; // Reset for retry
427+ }
428+ } , 60000 ) ; // Wait 1 minute before retrying
429+ }
430+ } ) ;
405431 } , 1000 * 10 ) ;
406432 }
407433 } else {
0 commit comments