I'm making an AI assistant interface website, and I've noticed an issue with my code attachment feature. If the code I paste into the attachment has characters that are the same as those used in Markdown or HTML (eg. or backticks) then the code will spill out of the bubble. How can I fix this WITHOUT sending sanitized code to the AI or showing the user's code as a bunch of escaped special characters. Bear in mind, I plan on introducing an extended bubble system at some point incorporating more than just code bubbles: instructions, errors, documentation and even custom ones, as all these bubbles are meant to do is encase some text in tags for the AI to understand, such as (though some bubbles like code do have additional information like file name). If it makes sense, perhaps it would be good to introduce that now?
import React, {
useState,
useContext,
useRef,
useEffect,
useCallback,
} from "react";
import { ChatContext } from "../context/ChatContext";
import Message from "./Message";
import CodeModal from "./CodeModal";
import InlineCodeEditor from "./InlineCodeEditor";
import { escapeHtml } from "../utils/escapeHtml";
import { unescapeHtml } from "../utils/unescapeHtml"; // Import unescapeHtml
/**
Component representing the chat interface where users can send messages and receive responses.
@returns {JSX.Element} The ChatInterface component.
*/
function ChatInterface() {
const {
chats,
currentChatId,
addMessage,
updateChat,
selectedModelId,
models,
} = useContext(ChatContext);
// Use a more robust selector if possible to prevent regex issues
const regex = new RegExp(
<code\\s+fileName="${escapeHtml( currentEditingCode.fileName )}"\\s+notes="${escapeHtml( currentEditingCode.notes )}">([\\s\\S]*?)<\\/code>
);
Sends the user's message to the backend and handles the response.
*/
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;
const userMessage = { sender: "user", text: fullMessage };
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: fullMessage, // Send the full message with <code> tags intact
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);
}
Toggles the visibility of the system prompt textarea.
*/
const toggleSystemPrompt = useCallback(() => {
setIsSystemPromptOpen((prev) => !prev);
}, []);
// Remove unused useState: codeAttachments
if (!currentChat) {
return (
No active chat. Please start a new chat.
);
}
Handles keydown events, specifically for Enter and Shift+Enter.
@param {object} e - The event object.
*/
const handleKeyDown = useCallback((e) => {
if (e.key === 'Enter') {
if (e.shiftKey) {
// Allow Shift+Enter to insert a newline
// Let the event propagate naturally
} else {
// Prevent default behavior and emit a custom event or handle sending the message
// Here, you might want to trigger the send action if needed
// For InlineCodeEditor, we'll allow the parent to handle message sending
// by not preventing default here
}
}
}, []);
/**
Handles paste events by stripping formatting and inserting plain text.
@param {object} e - The event object.
*/
const handlePaste = useCallback((e) => {
e.preventDefault();
const text = e.clipboardData.getData('text/plain');
document.execCommand('insertText', false, text);
}, []);
/**
Handles clicks on code bubbles to initiate editing.
@param {string} id - The unique identifier of the chat to delete.
*/
const deleteChat = (id) => {
setChats((prevChats) => prevChats.filter((chat) => chat.id !== id));
// If the deleted chat was the current one, reset currentChatId
if (id === currentChatId) {
setCurrentChatId(null);
}
};
@param {object} model - The model object to add.
*/
const addModel = (model) => {
setModels((prev) => [...prev, model]);
};
/**
Removes an AI model by its ID.
@param {string} modelId - The unique identifier of the model to remove.
*/
const removeModel = (modelId) => {
setModels((prev) => prev.filter((model) => model.id !== modelId));
// If the removed model was selected, select the first available model or null
if (selectedModelId === modelId) {
const remainingModels = models.filter((model) => model.id !== modelId);
setSelectedModelId(remainingModels.length > 0 ? remainingModels[0].id : null);
}
};
import React, { createContext, useState, useCallback } from 'react';
/**
Context for managing the code-related sidebar, including visibility and current code content.
*/
export const CodeContext = createContext();
/**
Provider component that encapsulates code-related state and functions.
@param {React.ReactNode} children - Child components that consume the context.
@returns {JSX.Element} - The CodeContext provider wrapping children.
*/
export const CodeProvider = ({ children }) => {
// Indicates whether the code sidebar is open
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
// Holds the current code attachment details
const [currentCode, setCurrentCode] = useState(null);
/**
Displays the code sidebar with the provided code attachment.
@param {object} codeAttachment - The code data to display in the sidebar.
*/
const showCode = useCallback((codeAttachment) => {
setCurrentCode(codeAttachment);
setIsSidebarOpen(true);
}, []);
/**
Hides the code sidebar and clears the current code content.
*/
const hideCode = useCallback(() => {
setIsSidebarOpen(false);
setCurrentCode(null);
}, []);
@returns {string} - The unescaped HTML string.
*/
export const unescapeHtml = (unsafe) => {
const doc = new DOMParser().parseFromString(unsafe, "text/html");
return doc.documentElement.textContent;
};
import { escapeHtml } from './escapeHtml';
/**
Generates an HTML string for a code bubble with given details.
@param {string} fileName - Name of the file.
@param {string} [notes=''] - Optional notes or annotations.
@param {string} [codeContent=''] - The code content to be associated.
@returns {string} - The HTML string representing the code bubble.
*/
export const renderCodeBubble = (fileName, notes = '', codeContent = '') => {
// Safely escape all dynamic content to prevent XSS
const safeFileName = escapeHtml(fileName || 'Untitled');
const safeNotes = escapeHtml(notes);
const safeCodeContent = escapeHtml(codeContent); // Changed from encodeURIComponent to escapeHtml
return <span class="inline-flex items-center bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-300 px-3 py-1 rounded-full mr-2 mb-2 code-bubble cursor-pointer" data-filename="${safeFileName}" data-notes="${safeNotes}" data-codecontent="${safeCodeContent}" <!-- Removed encoding --> > ${safeFileName} </span> \u200B <!-- Zero-width space to ensure cursor moves after the bubble --> ;
};
The issue you're facing with the code input spilling out of the bubble due to characters being interpreted as HTML or Markdown can be resolved by adopting a few strategies while still maintaining the integrity of the user's code.
1. Change HTML Escape Handling for Code
Instead of treating the code as regular text which gets rendered as HTML and could be misinterpreted, consider wrapping the inserted code in a dedicated container that escapes the special characters for display purposes only, without altering the underlying data that you send or store. Here's how you can do it:
Step 1: Modify the Code Attachment Function
In the addCodeAttachment, you will want to use a different way of displaying the code content. Use a tag to indicate that this content should be treated as raw text.
When rendering the code attachments in the MarkdownRenderer or any part that needs to display code, you will need to adjust the way you access the code content. Parse the CDATA section accordingly when you're rendering or extracting the code.
For your extractCodeAttachments function in the Message.js file, adjust it like this:
Now, in your rendering logic in MarkdownRenderer, ensure that the code within the CDATA section is displayed correctly without being interpreted as HTML.
Step 4: Ensure CDATA Is Handled Properly
When you're rendering these attachments, you will want to handle the CDATA section distinctly, ensuring that when the code content is displayed it doesn't get processed as HTML.
2. Introduce a More Robust Bubble Format
To further future-proof your design with multiple types of bubbles, consider expanding the concept of the bubble to accept various attributes. Here’s a conceptual approach to doing this:
<code fileName="example.js" notes="This function does X." type="code"><![CDATA[// JavaScript content here]]></code>
3. Handling Various Bubbles
In the InlineCodeEditor, you might want to create a specific handler that understands different bubble types. For example, create a rendering and input handler that automatically organizes different bubble types:
const renderBubble = (attrs, content) => {
switch (attrs.type) {
case 'code':
return renderCodeBubble(attrs.fileName, attrs.notes, content);
case 'documentation':
return renderDocumentationBubble(attrs.title, content);
// Add more cases as necessary
default:
return ""; // or some default handling
}
};
4. Summary
These changes aimed at using CDATA sections for code content while constructing the raw HTML safely. Make sure any user-input code is preserved and displayed properly, without being affected by browser parsing. By implementing a more sophisticated bubble rendering and handling system, you will also be equipped for your extended bubble requirements in the future.
Feel free to reach out if you need further assistance implementing this or expanding the feature set!