Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🐛 fix: Prevent Crash on Duplicate Message ID (#6392)

Odrec77884c14aa71
diff --git a/api/models/Message.js b/api/models/Message.js
index e651b20ad0..58068813ef 100644
--- a/api/models/Message.js
+++ b/api/models/Message.js
@@ -71,7 +71,42 @@ async function saveMessage(req, params, metadata) {
} catch (err) {
logger.error('Error saving message:', err);
logger.info(`---\`saveMessage\` context: ${metadata?.context}`);
- throw err;
+
+ // Check if this is a duplicate key error (MongoDB error code 11000)
+ if (err.code === 11000 && err.message.includes('duplicate key error')) {
+ // Log the duplicate key error but don't crash the application
+ logger.warn(`Duplicate messageId detected: ${params.messageId}. Continuing execution.`);
+
+ try {
+ // Try to find the existing message with this ID
+ const existingMessage = await Message.findOne({
+ messageId: params.messageId,
+ user: req.user.id,
+ });
+
+ // If we found it, return it
+ if (existingMessage) {
+ return existingMessage.toObject();
+ }
+
+ // If we can't find it (unlikely but possible in race conditions)
+ return {
+ ...params,
+ messageId: params.messageId,
+ user: req.user.id,
+ };
+ } catch (findError) {
+ // If the findOne also fails, log it but don't crash
+ logger.warn(`Could not retrieve existing message with ID ${params.messageId}: ${findError.message}`);
+ return {
+ ...params,
+ messageId: params.messageId,
+ user: req.user.id,
+ };
+ }
+ }
+
+ throw err; // Re-throw other errors
}
}