Feat: Ajustes y Preparación Docker

This commit is contained in:
2025-11-20 12:39:23 -03:00
parent c94936d56e
commit 1e85b2ed86
11 changed files with 317 additions and 56 deletions

View File

@@ -150,4 +150,40 @@ opacity: 0.8;
.context-indicator span {
font-weight: bold;
}
}
/* --- INICIO DE LA ANIMACIÓN DE "ESCRIBIENDO" --- */
.typing-indicator {
display: flex;
align-items: center;
padding: 2px 0; /* Espacio vertical para que no se pegue a los bordes */
}
.typing-indicator span {
height: 8px;
width: 8px;
background-color: #999;
border-radius: 50%;
display: inline-block;
margin: 0 2px;
animation: typing-bounce 1.4s infinite;
}
/* Aplicamos un pequeño retardo a cada punto para crear el efecto de onda */
.typing-indicator span:nth-child(2) {
animation-delay: 0.2s;
}
.typing-indicator span:nth-child(3) {
animation-delay: 0.4s;
}
@keyframes typing-bounce {
0%, 80%, 100% {
transform: scale(0);
}
40% {
transform: scale(0.75);
}
}

View File

@@ -11,8 +11,9 @@ interface Message {
}
const MAX_CHARS = 200;
// Constante para la clave del localStorage
// Constantes para la clave del localStorage
const CHAT_HISTORY_KEY = 'chatbot-history';
const CHAT_CONTEXT_KEY = 'chatbot-active-article';
const Chatbot: React.FC = () => {
const [isOpen, setIsOpen] = useState(false);
@@ -33,8 +34,22 @@ const Chatbot: React.FC = () => {
const [inputValue, setInputValue] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isStreaming, setIsStreaming] = useState(false);
const messagesEndRef = useRef<null | HTMLDivElement>(null);
const [activeArticleUrl, setActiveArticleUrl] = useState<string | null>(null);
const [activeArticle, setActiveArticle] = useState<{ url: string; title: string; } | null>(() => {
try {
// 1. Intentamos obtener el contexto del artículo guardado.
const savedContext = localStorage.getItem(CHAT_CONTEXT_KEY);
if (savedContext) {
// 2. Si existe, lo parseamos y lo usamos como estado inicial.
return JSON.parse(savedContext);
}
} catch (error) {
console.error("No se pudo cargar el contexto del artículo desde localStorage:", error);
}
// 3. Si no hay nada guardado o hay un error, el estado inicial es null.
return null;
});
// Añadimos un useEffect para guardar los mensajes.
useEffect(() => {
@@ -46,6 +61,19 @@ const Chatbot: React.FC = () => {
}
}, [messages]);
useEffect(() => {
try {
if (activeArticle) {
// Si hay un artículo activo, lo guardamos en localStorage.
localStorage.setItem(CHAT_CONTEXT_KEY, JSON.stringify(activeArticle));
} else {
// Si el artículo activo es null, lo eliminamos de localStorage para mantenerlo limpio.
localStorage.removeItem(CHAT_CONTEXT_KEY);
}
} catch (error) {
console.error("No se pudo guardar el contexto del artículo en localStorage:", error);
}
}, [activeArticle]); // Wste efecto se ejecuta cada vez que 'activeArticle' cambia.
useEffect(() => {
// Solo intentamos hacer scroll si la ventana del chat está abierta.
@@ -73,15 +101,15 @@ const Chatbot: React.FC = () => {
setMessages(prev => [...prev, userMessage]);
const messageToSend = inputValue;
setInputValue('');
setIsLoading(true);
const botMessagePlaceholder: Message = { text: '', sender: 'bot' };
setMessages(prev => [...prev, botMessagePlaceholder]);
// Inicia el estado de carga, pero aún no el de streaming
setIsLoading(true);
setIsStreaming(false);
try {
const requestBody = {
message: messageToSend,
contextUrl: activeArticleUrl
contextUrl: activeArticle ? activeArticle.url : null
};
const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/chat/stream-message`, {
@@ -98,52 +126,67 @@ const Chatbot: React.FC = () => {
const decoder = new TextDecoder();
const readStream = async () => {
let fullReply = '';
let fullReplyRaw = '';
let isFirstChunk = true;
while (true) {
const { done, value } = await reader.read();
if (done) {
let finalCleanText = '';
// ... (La lógica de `if (done)` no cambia)
try {
const parsedArray = JSON.parse(fullReply.replace(/,$/, '') + ']');
finalCleanText = Array.isArray(parsedArray) ? parsedArray.join('') : fullReply;
const responseArray = JSON.parse(fullReplyRaw);
let intent = 'Homepage';
let messageChunks = [];
if (Array.isArray(responseArray) && responseArray.length > 0) {
if (typeof responseArray[0] === 'string' && responseArray[0].startsWith('INTENT::')) {
intent = responseArray[0].split('::')[1];
messageChunks = responseArray.slice(1);
} else {
messageChunks = responseArray;
}
}
const finalCleanText = messageChunks.join('');
const linkRegex = /\[(.*?)\]\((https?:\/\/[^\s]+)\)/;
const match = finalCleanText.match(linkRegex);
if (match && match[1] && match[2]) {
setActiveArticle({ title: match[1], url: match[2] });
} else if (intent === 'Database' || intent === 'Homepage') {
setActiveArticle(null);
}
} catch (e) {
finalCleanText = fullReply.replace(/^\["|"]$|","/g, '');
console.error("Error al procesar la respuesta final del stream:", e, "Contenido crudo:", fullReplyRaw);
setActiveArticle(null);
}
const linkRegex = /\[.*?\]\((https?:\/\/[^\s]+)\)/;
const match = finalCleanText.match(linkRegex);
// --- INICIO DE LA CORRECCIÓN ---
// Si encontramos un nuevo enlace, actualizamos el contexto.
// Si NO encontramos un enlace, ya no hacemos nada, permitiendo que el contexto anterior persista.
if (match && match[1]) {
console.log("Noticia activa establecida:", match[1]);
setActiveArticleUrl(match[1]);
}
// HEMOS ELIMINADO EL BLOQUE "ELSE" QUE RESETEABA EL CONTEXTO.
// --- FIN DE LA CORRECCIÓN ---
break;
}
// ... (el resto del bucle while sigue exactamente igual)
const chunk = decoder.decode(value);
fullReply += chunk;
fullReplyRaw += chunk;
let cleanText = '';
let cleanTextForDisplay = '';
try {
const parsedArray = JSON.parse(fullReply.replace(/,$/, '') + ']');
cleanText = Array.isArray(parsedArray) ? parsedArray.join('') : fullReply;
const parsedArray = JSON.parse(fullReplyRaw.replace(/,$/, '') + ']');
const displayChunks = parsedArray[0] && parsedArray[0].startsWith('INTENT::')
? parsedArray.slice(1)
: parsedArray;
cleanTextForDisplay = displayChunks.join('');
} catch (e) {
cleanText = fullReply.replace(/^\["|"]$|","/g, '');
cleanTextForDisplay = fullReplyRaw.replace(/^\["INTENT::.*?","|\["|"]$|","/g, '');
}
setMessages(prev => {
const lastMessage = prev[prev.length - 1];
const updatedLastMessage = { ...lastMessage, text: cleanText };
return [...prev.slice(0, -1), updatedLastMessage];
});
if (isFirstChunk) {
// En el primer chunk, activamos el flag de streaming
setIsStreaming(true);
setMessages(prev => [...prev, { text: cleanTextForDisplay, sender: 'bot' }]);
isFirstChunk = false;
} else {
setMessages(prev => {
const updatedMessages = [...prev];
updatedMessages[updatedMessages.length - 1].text = cleanTextForDisplay;
return updatedMessages;
});
}
}
};
@@ -152,15 +195,11 @@ const Chatbot: React.FC = () => {
} catch (error) {
console.error("Error al conectar con la API de streaming:", error);
const errorText = error instanceof Error ? error.message : 'Lo siento, no pude conectarme.';
setMessages(prev => {
const lastMessage = prev[prev.length - 1];
const updatedLastMessage = { ...lastMessage, text: errorText };
return [...prev.slice(0, -1), updatedLastMessage];
});
setMessages(prev => [...prev, { text: errorText, sender: 'bot' }]);
} finally {
// Al final, reseteamos ambos estados
setIsLoading(false);
setIsStreaming(false);
}
};
@@ -176,7 +215,7 @@ const Chatbot: React.FC = () => {
<span>Asistente Virtual - El Día</span>
<button className="close-button" onClick={toggleChat}>&times;</button>
</div>
<div className="messages-container">
<div className={`messages-container ${isLoading ? 'is-loading' : ''}`}>
{messages.map((msg, index) => (
<div key={index} className={`message ${msg.sender}`}>
<ReactMarkdown rehypePlugins={[rehypeSanitize]}>
@@ -184,11 +223,23 @@ const Chatbot: React.FC = () => {
</ReactMarkdown>
</div>
))}
{isLoading && !isStreaming && (
<div className="message bot">
<div className="typing-indicator">
<span></span>
<span></span>
<span></span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
{activeArticleUrl && (
{activeArticle && (
<div className="context-indicator">
Hablando sobre: <span>Noticia actual</span>
Hablando sobre:
<a href={activeArticle.url} target="_blank" rel="noopener noreferrer">
{activeArticle.title}
</a>
</div>
)}
<form className="input-form" onSubmit={handleSendMessage}>