Corregir mensajes de conversación fix #121

This commit is contained in:
2026-02-18 08:41:59 -06:00
parent cd16b3cb4f
commit 99ed75b2eb
2 changed files with 48 additions and 27 deletions

View File

@@ -168,10 +168,8 @@ export async function getConversationByPlan(planId: string) {
.from('conversaciones_plan') .from('conversaciones_plan')
.select('*') .select('*')
.eq('plan_estudio_id', planId) .eq('plan_estudio_id', planId)
.eq('estado', 'ACTIVA') .order('creado_en', { ascending: true })
.order('creado_en', { ascending: true }) // Añade un orden para que el último sea el más nuevo
if (error) throw error if (error) throw error
return data ?? [] // Devuelve un array vacío en lugar de null para evitar el "undefined" return data ?? []
} }

View File

@@ -124,31 +124,59 @@ function RouteComponent() {
}, },
) )
useEffect(() => { useEffect(() => {
if (isLoadingHistory) return // 1. Si no hay ID o está cargando el historial, no hacemos nada
if (!activeChatId || isLoadingHistory) return
const messagesToProcess = historyMessages?.items || historyMessages const messagesFromApi = historyMessages?.items || historyMessages
if (activeChatId && Array.isArray(messagesToProcess)) { if (Array.isArray(messagesFromApi)) {
const flattened = messagesToProcess.map((msg) => { const flattened = messagesFromApi.map((msg) => {
let content = msg.content let content = msg.content
// Tu lógica de parseo existente... let suggestions: Array<any> = []
if (typeof content === 'object' && content !== null) { if (typeof content === 'object' && content !== null) {
suggestions = Object.entries(content)
.filter(([key]) => key !== 'ai-message')
.map(([key, value]) => ({
key,
label: key.replace(/_/g, ' '),
newValue: value as string,
}))
content = content['ai-message'] || JSON.stringify(content) content = content['ai-message'] || JSON.stringify(content)
} }
return { ...msg, content } // Si el content es un string que parece JSON (caso común en respuestas RAW)
else if (typeof content === 'string' && content.startsWith('{')) {
try {
const parsed = JSON.parse(content)
suggestions = Object.entries(parsed)
.filter(([key]) => key !== 'ai-message')
.map(([key, value]) => ({
key,
label: key.replace(/_/g, ' '),
newValue: value as string,
}))
content = parsed['ai-message'] || content
} catch (e) {
/* no es json */
}
}
return {
...msg,
content,
suggestions,
type: suggestions.length > 0 ? 'improvement-card' : 'text',
}
}) })
setMessages(flattened.reverse())
} else if (!activeChatId) { // Solo actualizamos si no estamos esperando la respuesta de un POST
setMessages([ // para evitar saltos visuales
{ if (!isLoading) {
id: 'welcome', setMessages(flattened.reverse())
role: 'assistant', }
content:
'¡Hola! Soy tu asistente de IA. ¿Qué campos deseas mejorar? Usa ":" para seleccionar.',
},
])
} }
}, [historyMessages, activeChatId, isLoadingHistory]) }, [historyMessages, activeChatId, isLoadingHistory, isLoading])
useEffect(() => { useEffect(() => {
// Si no hay un chat seleccionado manualmente y la API nos devuelve chats existentes // Si no hay un chat seleccionado manualmente y la API nos devuelve chats existentes
@@ -292,12 +320,7 @@ function RouteComponent() {
// Si no hay campos, enviamos el texto tal cual // Si no hay campos, enviamos el texto tal cual
if (fields.length === 0) return userInput if (fields.length === 0) return userInput
// Si hay campos, creamos un bloque de contexto superior return `Instrucción del usuario: ${userInput}`
const fieldsContext = fields
.map((f) => `[CAMPO SELECCIONADO: ${f.label}]`)
.join(' ')
return `${fieldsContext}\n\nInstrucción del usuario: ${userInput}`
} }
const handleSend = async (promptOverride?: string) => { const handleSend = async (promptOverride?: string) => {