Spaces:
Running

axeronis commited on
Commit
464c219
·
1 Parent(s): dba971d

fix: post-generation check - abort if new messages arrived during AI generation

Browse files
Files changed (1) hide show
  1. backend/app/api/webhook.py +24 -0
backend/app/api/webhook.py CHANGED
@@ -1194,6 +1194,30 @@ async def process_ai_response_background(
1194
  conversation_history=conversation_history
1195
  )
1196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1197
  # --- BOOKING INTERCEPTION START ---
1198
  import re
1199
  from datetime import datetime
 
1194
  conversation_history=conversation_history
1195
  )
1196
 
1197
+ # POST-GENERATION CHECK: Did new messages arrive during AI generation?
1198
+ # If yes, abort sending - the newer message's task will handle response
1199
+ post_gen_stmt = select(Message).where(
1200
+ Message.conversation_id == conversation_id,
1201
+ Message.sender_type == "user"
1202
+ ).order_by(Message.created_at.desc()).limit(1)
1203
+
1204
+ post_gen_result = await session.execute(post_gen_stmt)
1205
+ post_gen_latest = post_gen_result.scalar_one_or_none()
1206
+
1207
+ if post_gen_latest and post_gen_latest.id != user_message_id:
1208
+ # New message arrived DURING generation - abort!
1209
+ logger.info(
1210
+ "⏭️ Post-generation abort: New message arrived during AI generation",
1211
+ original_msg_id=str(user_message_id),
1212
+ new_msg_id=str(post_gen_latest.id),
1213
+ conversation_id=str(conversation_id)
1214
+ )
1215
+ # Reset lead status
1216
+ lead.processing_status = "idle"
1217
+ session.add(lead)
1218
+ await session.commit()
1219
+ return # Exit - let the newer message's background task respond
1220
+
1221
  # --- BOOKING INTERCEPTION START ---
1222
  import re
1223
  from datetime import datetime