To address the issue of code snippets containing characters that interfere with Markdown or HTML rendering (such as <, >, or backticks) spilling out of message bubbles, you can implement a dual-layer encoding strategy. This approach ensures that the UI remains intact by escaping problematic characters when displaying the code, while maintaining the original code content for communication with the AI.
Here's a comprehensive solution that accommodates your current architecture and future extensions:
1. Escape Code Content When Embedding in Message Text
When you embed code snippets within the message text using <code> tags, it's essential to escape the code content to prevent HTML parsing issues. This ensures that characters like < and > within the code don't break the HTML structure of your message bubbles.
Modify addCodeAttachment in ChatInterface.js to Escape codeContent:
const addCodeAttachment = ({
codeContent,
fileName = "untitled",
notes = "",
}) => {
const escapedFileName = escapeHtml(fileName);
const escapedNotes = escapeHtml(notes);
const escapedCodeContent = escapeHtml(codeContent); // Escape codeContent
const codeTag = `<code fileName="${escapedFileName}" notes="${escapedNotes}">${escapedCodeContent}</code>`;
setMessage((prev) => prev + codeTag);
};
2. Ensure Proper Unescaping When Extracting Code Attachments
When extracting code attachments from the message text (e.g., in the Message component), make sure to unescape the code content so that the AI receives the original code without HTML entities.
Update extractCodeAttachments in Message.js:
const extractCodeAttachments = useCallback((text) => {
const codeRegex =
/<code(?:\s+fileName="([^"]*)")?(?:\s+notes="([^"]*)")?>([\s\S]*?)<\/code>/g;
let match;
const attachments = [];
while ((match = codeRegex.exec(text)) !== null) {
attachments.push({
fileName: match[1] || "Untitled",
notes: match[2] || "",
codeContent: unescapeHtml(match[3]), // Unescape codeContent
});
}
return attachments;
}, []);
3. Reconstruct the Message Before Sending to the AI
Before sending the message to the AI, reconstruct the message by replacing the escaped <code> tags with their unescaped counterparts. This ensures that the AI receives the raw code content without any HTML escaping.
Implement reconstructMessageForAI in ChatInterface.js:
Add a utility function to reconstruct the message:
/**
* Reconstructs the message by unescaping codeContent within <code> tags.
*
* @param {string} message - The original message text with escaped code attachments.
* @returns {string} - The reconstructed message with raw code content.
*/
const reconstructMessageForAI = (message) => {
return message.replace(/<code\s+fileName="([^"]*)"\s+notes="([^"]*)">([\s\S]*?)<\/code>/g, (match, fileName, notes, codeContent) => {
// Do not escape codeContent when sending to AI
return `<code fileName="${fileName}" notes="${notes}">${unescapeHtml(codeContent)}</code>`;
});
};
Modify the handleSend Function to Use the Reconstructed Message:
const handleSend = useCallback(async () => {
if (!message.trim() || !currentChatId || !selectedModelId) return;
// Retrieve the system prompt from the current chat
const systemPrompt = currentChat.systemPrompt || "";
// Combine the system prompt with the user message
const fullMessage = systemPrompt ? `${systemPrompt}\n${message}` : message;
// Reconstruct the message for AI by unescaping codeContent
const aiMessage = reconstructMessageForAI(fullMessage);
const userMessage = { sender: "user", text: aiMessage };
addMessage(currentChatId, userMessage);
setMessage("");
scrollToBottom();
// Set typing indicator
setIsTyping(true);
try {
const response = await fetch(
`${process.env.REACT_APP_BACKEND_URL}/api/chat`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: aiMessage, // Send the reconstructed message
model_id: selectedModelId,
}),
}
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(
errorData.detail || "Failed to get response from the server."
);
}
const data = await response.json();
const responseText = data.response;
const responseModelId = data.model_id;
const botMessage = {
sender: "bot",
text: responseText,
model_id: responseModelId,
};
addMessage(currentChatId, botMessage);
scrollToBottom();
} catch (error) {
console.error("Error:", error);
const errorMessage = {
sender: "bot",
text: "Sorry, something went wrong. Please try again.",
};
addMessage(currentChatId, errorMessage);
scrollToBottom();
} finally {
// Remove typing indicator
setIsTyping(false);
}
}, [message, currentChatId, selectedModelId, addMessage, currentChat]);
4. Enhance the Bubble System for Future Extensions
To accommodate various types of bubbles (e.g., instructions, errors, documentation), consider generalizing your bubble tagging system. Use a type attribute to distinguish different bubble types within your custom tags. This makes it easier to parse and render different bubble types uniformly.
Example Enhanced addCodeAttachment:
const addCodeAttachment = ({
codeContent,
fileName = "untitled",
notes = "",
}) => {
const escapedFileName = escapeHtml(fileName);
const escapedNotes = escapeHtml(notes);
const escapedCodeContent = escapeHtml(codeContent);
const codeTag = `<attachment type="code" fileName="${escapedFileName}" notes="${escapedNotes}">${escapedCodeContent}</attachment>`;
setMessage((prev) => prev + codeTag);
};
Update extractCodeAttachments to Handle Multiple Types in Message.js:
const extractAttachments = useCallback((text) => {
const attachmentRegex =
/<attachment\s+type="([^"]*)"(?:\s+fileName="([^"]*)")?(?:\s+notes="([^"]*)")?>([\s\S]*?)<\/attachment>/g;
let match;
const attachments = [];
while ((match = attachmentRegex.exec(text)) !== null) {
const [_, type, fileName, notes, content] = match;
attachments.push({
type,
fileName: fileName || "Untitled",
notes: notes || "",
content: type === "code" ? unescapeHtml(content) : content,
});
}
return attachments;
}, []);
Adjust the Message Component to Render Different Attachment Types:
<div className="mt-2 flex flex-wrap">
{attachments.map((attachment, index) => {
switch (attachment.type) {
case "code":
return (
<CodeAttachmentBubble
key={index}
attachment={attachment}
onEdit={() => handleEdit(attachment)}
onDelete={() => handleDelete(attachment)}
/>
);
// Add cases for other attachment types like 'instruction', 'error', etc.
default:
return null;
}
})}
</div>
5. Ensure Security and Prevent XSS Attacks
While escaping code content prevents your UI from breaking, it's also crucial for security to prevent Cross-Site Scripting (XSS) attacks. Ensure that all user-provided content is appropriately sanitized before rendering.
Review and Enhance escapeHtml Utility:
/**
* Escapes HTML special characters in a string to prevent XSS attacks.
*
* @param {string} unsafe - The string to be escaped.
* @returns {string} - The escaped string safe for insertion into HTML.
*/
export const escapeHtml = (unsafe) => {
if (typeof unsafe !== 'string') {
console.warn('escapeHtml received non-string:', unsafe);
unsafe = String(unsafe);
}
const entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '=',
};
return unsafe.replace(/[&<>"'`=\/]/g, (char) => entityMap[char]);
};
6. Comprehensive Example
Bringing it all together, here's how your key components can integrate these changes:
ChatInterface.js:
import React, { /* ... */ } from "react";
// ...other imports
function ChatInterface() {
// ...existing state and context
// Modify addCodeAttachment to escape codeContent
const addCodeAttachment = ({
codeContent,
fileName = "untitled",
notes = "",
}) => {
const escapedFileName = escapeHtml(fileName);
const escapedNotes = escapeHtml(notes);
const escapedCodeContent = escapeHtml(codeContent); // Escape codeContent
const codeTag = `<code fileName="${escapedFileName}" notes="${escapedNotes}">${escapedCodeContent}</code>`;
setMessage((prev) => prev + codeTag);
};
// ...existing handlers
// Implement reconstructMessageForAI
const reconstructMessageForAI = (message) => {
return message.replace(/<code\s+fileName="([^"]*)"\s+notes="([^"]*)">([\s\S]*?)<\/code>/g, (match, fileName, notes, codeContent) => {
return `<code fileName="${fileName}" notes="${notes}">${unescapeHtml(codeContent)}</code>`;
});
};
// Modify handleSend to use aiMessage
const handleSend = useCallback(async () => {
if (!message.trim() || !currentChatId || !selectedModelId) return;
const systemPrompt = currentChat.systemPrompt || "";
const fullMessage = systemPrompt ? `${systemPrompt}\n${message}` : message;
const aiMessage = reconstructMessageForAI(fullMessage);
const userMessage = { sender: "user", text: aiMessage };
addMessage(currentChatId, userMessage);
setMessage("");
scrollToBottom();
setIsTyping(true);
try {
const response = await fetch(
`${process.env.REACT_APP_BACKEND_URL}/api/chat`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: aiMessage,
model_id: selectedModelId,
}),
}
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(
errorData.detail || "Failed to get response from the server."
);
}
const data = await response.json();
const responseText = data.response;
const responseModelId = data.model_id;
const botMessage = {
sender: "bot",
text: responseText,
model_id: responseModelId,
};
addMessage(currentChatId, botMessage);
scrollToBottom();
} catch (error) {
console.error("Error:", error);
const errorMessage = {
sender: "bot",
text: "Sorry, something went wrong. Please try again.",
};
addMessage(currentChatId, errorMessage);
scrollToBottom();
} finally {
setIsTyping(false);
}
}, [message, currentChatId, selectedModelId, addMessage, currentChat]);
// ...rest of the component
}
export default ChatInterface;
Message.js:
import React, { /* ... */ } from "react";
// ...other imports
function Message({ chatId, messageIndex, sender, text, model_id }) {
// ...existing state and context
const extractAttachments = useCallback((text) => {
const attachmentRegex =
/<attachment\s+type="([^"]*)"(?:\s+fileName="([^"]*)")?(?:\s+notes="([^"]*)")?>([\s\S]*?)<\/attachment>/g;
let match;
const attachments = [];
while ((match = attachmentRegex.exec(text)) !== null) {
const [_, type, fileName, notes, content] = match;
attachments.push({
type,
fileName: fileName || "Untitled",
notes: notes || "",
content: type === "code" ? unescapeHtml(content) : content,
});
}
return attachments;
}, []);
const attachments = extractAttachments(text);
const cleanedText = text.replace(
/<attachment\s+type="code"(?:\s+fileName="[^"]*")?(?:\s+notes="[^"]*")?>[\s\S]*?<\/attachment>/g,
""
);
// ...existing handlers
return (
<>
<div
className={`mb-4 flex ${
sender === "user" ? "justify-end" : "justify-start"
}`}
>
<div
className={`max-w-xs md:max-w-md lg:max-w-5xl p-5 rounded-xl ${
sender === "user"
? "bg-zinc-950 text-white"
: "bg-gray-200 dark:bg-[#282828] text-gray-800 dark:text-gray-200"
}`}
role={sender === "user" ? "article" : "document"}
aria-label={`${sender === "user" ? "User" : "Bot"} message`}
>
{sender === "bot" && modelName && (
<div className="mb-2 text-sm text-gray-500 dark:text-gray-400">
<strong>Model:</strong> {modelName}
</div>
)}
<MarkdownRenderer text={cleanedText} />
<div className="mt-2 flex flex-wrap">
{attachments.map((attachment, index) => {
switch (attachment.type) {
case "code":
return (
<CodeAttachmentBubble
key={index}
attachment={attachment}
onEdit={() => handleEdit(attachment)}
onDelete={() => handleDelete(attachment)}
/>
);
// Handle other attachment types here
default:
return null;
}
})}
</div>
{/* ...existing copy button */}
</div>
</div>
{/* ...existing modals */}
</>
);
}
export default Message;
7. Benefits of This Approach
-
UI Stability: Escaping codeContent prevents special characters from breaking the HTML structure of your message bubbles.
-
AI Integrity: By reconstructing the message before sending, the AI receives the original, unescaped code, ensuring accurate processing.
-
Scalability: Generalizing the attachment tags with a type attribute allows you to easily add more bubble types in the future without overhauling the system.
-
Security: Proper escaping mitigates the risk of XSS attacks by ensuring that any user-provided content is safely handled.
8. Final Considerations
-
Testing: Thoroughly test the entire flow by adding various code snippets, including those with complex HTML or Markdown characters, to ensure that both the UI and AI receive and render the content correctly.
-
Error Handling: Enhance error handling to catch and manage any issues that arise during the escaping and unescaping processes.
-
Performance: Monitor any performance implications, especially if messages become large or contain numerous attachments.
By implementing the above strategy, you can ensure that your AI assistant interface handles code attachments robustly, maintaining both UI integrity and AI communication fidelity.