@@ -55,6 +55,9 @@ def __init__(self, agent=None):
5555 self .recent_greetings = [] # Track recent greetings to avoid repetition
5656 self .interaction_count = 0 # Track number of interactions for familiarity
5757
58+ # Goodbye coordination flag
59+ self .goodbye_pending = False # Flag to coordinate goodbye handling between user and assistant handlers
60+
5861 # Phase 4: Mutual exclusion for virtual request processing
5962 self .virtual_request_processing_lock = asyncio .Lock ()
6063 # Removed batching complexity - no longer needed
@@ -101,6 +104,8 @@ async def _exit_current_state(self):
101104 self .user_response_timer = None
102105 # Reset conversation ending flag
103106 self .ending_conversation = False
107+ # Reset goodbye coordination flag
108+ self .goodbye_pending = False
104109
105110
106111 async def _enter_new_state (self ):
@@ -235,24 +240,30 @@ async def handle_conversation_item():
235240
236241 if any (word in text_lower for word in goodbye_words ):
237242 logger .info ("🔍 DEBUG: User indicated conversation ending - goodbye detected!" )
238- # Set ending flag to prevent timer conflicts
239- self .ending_conversation = True
240-
241- # Let agent say goodbye before ending conversation
242- goodbye_response = "friendly:Thanks for chatting! Say 'hey barista' if you need me again."
243- emotion , text = self .process_emotional_response (goodbye_response )
244- await self .say_with_emotion (text , emotion )
245-
246- # Wait for goodbye to finish, then end conversation
247- await asyncio .sleep (3 ) # Give time for TTS to complete
248- await self .end_conversation ()
243+ # Set pending flag to coordinate with LLM response
244+ self .goodbye_pending = True
245+ logger .info ("🔍 DEBUG: Set goodbye_pending = True, letting LLM respond naturally" )
249246 else :
250247 logger .info (f"🔍 DEBUG: No goodbye detected in: '{ user_text } '" )
251248
252249 # Handle agent messages for timer management
253250 elif event .item .role == "assistant" :
254251 logger .info ("🔍 DEBUG: Agent message added to conversation" )
255252
253+ # Check if this is a response to a user goodbye
254+ if self .goodbye_pending :
255+ logger .info ("🔍 DEBUG: LLM responded to user goodbye - ending conversation" )
256+ self .goodbye_pending = False
257+ self .ending_conversation = True
258+
259+ # End conversation after a brief delay to let LLM response complete
260+ async def delayed_end_conversation ():
261+ await asyncio .sleep (2 ) # Brief delay for response completion
262+ await self .end_conversation ()
263+
264+ asyncio .create_task (delayed_end_conversation ())
265+ return # Skip normal timer logic since we're ending
266+
256267 # Only start new timer if we're not ending the conversation
257268 if not self .ending_conversation :
258269 # Start timer to wait for user response after agent speaks
0 commit comments