@@ -421,6 +421,9 @@ export function useChat({
421421 return ;
422422 }
423423
424+ // Prevent duplicate session creation on rerenders while streaming
425+ connectionStatus . current = 'connecting' ;
426+
424427 // Start new code generation using API client
425428 const response = await apiClient . createAgentSession ( {
426429 query : userQuery ,
@@ -487,6 +490,10 @@ export function useChat({
487490 setIsGeneratingBlueprint ( false ) ;
488491 sendMessage ( createAIMessage ( 'main' , 'Blueprint generation complete. Now starting the code generation...' , true ) ) ;
489492
493+ if ( ! result . websocketUrl || ! result . agentId ) {
494+ throw new Error ( 'Failed to initialize agent session' ) ;
495+ }
496+
490497 // Connect to WebSocket
491498 logger . debug ( 'connecting to ws with created id' ) ;
492499 connectWithRetry ( result . websocketUrl ) ;
@@ -498,6 +505,9 @@ export function useChat({
498505 description : userQuery ,
499506 } ) ;
500507 } else if ( connectionStatus . current === 'idle' ) {
508+ // Prevent duplicate connect calls on rerenders
509+ connectionStatus . current = 'connecting' ;
510+
501511 setIsBootstrapping ( false ) ;
502512 // Show starting message with thinking indicator
503513 setMessages ( ( ) => [
@@ -516,12 +526,18 @@ export function useChat({
516526 setChatId ( urlChatId ) ;
517527
518528
529+ if ( ! response . data . websocketUrl ) {
530+ throw new Error ( 'Missing websocketUrl for existing agent' ) ;
531+ }
532+
519533 logger . debug ( 'connecting from init for existing chatId' ) ;
520534 connectWithRetry ( response . data . websocketUrl , {
521535 disableGenerate : true , // We'll handle generation resume in the WebSocket open handler
522536 } ) ;
523537 }
524538 } catch ( error ) {
539+ // Allow retry on failure
540+ connectionStatus . current = 'idle' ;
525541 logger . error ( 'Error initializing code generation:' , error ) ;
526542 if ( error instanceof RateLimitExceededError ) {
527543 const rateLimitMessage = handleRateLimitError ( error . details , onDebugMessage ) ;
0 commit comments