mirror of
https://github.com/escalante29/WealthySmart.git
synced 2026-07-17 12:48:47 +02:00
Assistant: hydrate the persisted thread in the UI
- Asistente.tsx pins threadId "main" on CopilotChat (an explicit stable id stops the per-mount message wipe), runs a hydration pass on page load — an empty-messages run makes MAF replay the stored snapshot as MESSAGES_SNAPSHOT with no LLM call — and sends the Inicio ask-box question only after hydration so every normal run carries the full client-known history. "Nueva conversación" clears the stored thread behind a ConfirmDialog. - server.ts: the BFF no longer injects context into empty-messages requests (that would defeat MAF's hydration trigger), and the snapshot reconciliation passes hydration replays through untouched and treats ids the client already sent as history rather than duplicates. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import {
|
||||
CopilotChat,
|
||||
@@ -7,10 +7,17 @@ import {
|
||||
useCopilotKit,
|
||||
} from "@copilotkit/react-core/v2";
|
||||
import { useCopilotAction } from "@copilotkit/react-core";
|
||||
import { Sparkles } from "lucide-react";
|
||||
import { MessageSquarePlus, Sparkles } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import ConfirmDialog from "@/components/ConfirmDialog";
|
||||
import { PageHeader } from '@/components/page-header';
|
||||
import { SpendingSummaryCard, type SpendingSummaryArgs } from "@/components/chat/ChatCards";
|
||||
|
||||
// Single persistent conversation: the backend snapshot store keys on this
|
||||
// same id (backend/app/api/v1/endpoints/chat.py). An explicit, stable
|
||||
// threadId also stops CopilotChat from wiping messages on remount.
|
||||
const CHAT_THREAD_ID = "main";
|
||||
|
||||
const STATIC_SUGGESTIONS = {
|
||||
available: "before-first-message" as const,
|
||||
suggestions: [
|
||||
@@ -24,28 +31,66 @@ const STATIC_SUGGESTIONS = {
|
||||
export default function Asistente() {
|
||||
useConfigureSuggestions(STATIC_SUGGESTIONS);
|
||||
|
||||
// A question typed on the Inicio dashboard arrives via router state:
|
||||
// append it as a user message and run the agent once.
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { agent } = useAgent({ agentId: "wealthysmart" });
|
||||
const { copilotkit } = useCopilotKit();
|
||||
const sentRef = useRef(false);
|
||||
const [confirmClear, setConfirmClear] = useState(false);
|
||||
const [clearing, setClearing] = useState(false);
|
||||
|
||||
// Boot sequence, once per page load: hydrate the persisted thread, then
|
||||
// send any question that arrived from the Inicio ask-box via router state.
|
||||
// Order matters — hydration first keeps the invariant that every normal
|
||||
// run's input carries the full client-known history (the BFF's snapshot
|
||||
// reconciliation relies on it).
|
||||
const bootRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!agent || bootRef.current) return;
|
||||
bootRef.current = true;
|
||||
const ask = (location.state as { ask?: string } | null)?.ask;
|
||||
if (!ask || sentRef.current || !agent) return;
|
||||
sentRef.current = true;
|
||||
// Clear the state so back/refresh doesn't re-send the question.
|
||||
navigate(location.pathname, { replace: true, state: null });
|
||||
agent.addMessage({
|
||||
id: crypto.randomUUID(),
|
||||
role: "user",
|
||||
content: ask,
|
||||
});
|
||||
void copilotkit.runAgent({ agent });
|
||||
if (ask) {
|
||||
// Clear the state so back/refresh doesn't re-send the question.
|
||||
navigate(location.pathname, { replace: true, state: null });
|
||||
}
|
||||
void (async () => {
|
||||
agent.threadId = CHAT_THREAD_ID;
|
||||
if (agent.messages.length === 0) {
|
||||
// Empty-messages run = MAF's hydration trigger: replays the stored
|
||||
// snapshot as MESSAGES_SNAPSHOT without invoking the LLM.
|
||||
try {
|
||||
await copilotkit.runAgent({ agent });
|
||||
} catch (err) {
|
||||
console.error("[asistente] thread hydration failed:", err);
|
||||
}
|
||||
}
|
||||
if (ask) {
|
||||
agent.addMessage({
|
||||
id: crypto.randomUUID(),
|
||||
role: "user",
|
||||
content: ask,
|
||||
});
|
||||
void copilotkit.runAgent({ agent });
|
||||
}
|
||||
})();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [agent]);
|
||||
|
||||
const clearThread = async () => {
|
||||
setClearing(true);
|
||||
try {
|
||||
await fetch("/api/v1/chat/thread", {
|
||||
method: "DELETE",
|
||||
credentials: "include",
|
||||
});
|
||||
agent?.setMessages([]);
|
||||
setConfirmClear(false);
|
||||
} catch (err) {
|
||||
console.error("[asistente] clear thread failed:", err);
|
||||
} finally {
|
||||
setClearing(false);
|
||||
}
|
||||
};
|
||||
|
||||
useCopilotAction({
|
||||
name: "render_spending_summary",
|
||||
description:
|
||||
@@ -92,12 +137,35 @@ export default function Asistente() {
|
||||
icon={Sparkles}
|
||||
title="Asistente"
|
||||
subtitle="Pregúntale a WealthySmart sobre tus finanzas."
|
||||
actions={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setConfirmClear(true)}
|
||||
disabled={!agent || agent.messages.length === 0}
|
||||
>
|
||||
<MessageSquarePlus />
|
||||
Nueva conversación
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{confirmClear && (
|
||||
<ConfirmDialog
|
||||
title="¿Nueva conversación?"
|
||||
message="Se borrará el historial del chat guardado. Esta acción no se puede deshacer."
|
||||
confirmLabel="Borrar historial"
|
||||
onConfirm={clearThread}
|
||||
onCancel={() => setConfirmClear(false)}
|
||||
loading={clearing}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex-1 min-h-0 rounded-xl border border-border overflow-hidden bg-card">
|
||||
<CopilotChat
|
||||
className="h-full"
|
||||
threadId={CHAT_THREAD_ID}
|
||||
labels={{
|
||||
modalHeaderTitle: "WealthySmart",
|
||||
welcomeMessageText: "¿Qué quieres saber sobre tus finanzas?",
|
||||
|
||||
Reference in New Issue
Block a user