diff --git a/backend/src/routes/chat.js b/backend/src/routes/chat.js index 3698ecd..aede4a9 100644 --- a/backend/src/routes/chat.js +++ b/backend/src/routes/chat.js @@ -23,6 +23,10 @@ router.post("/", async (req, res) => { } const currentChatId = session.id; + // Persist the user message BEFORE streaming so it is included in the AI + // context (the model must see the current question) and survives even if + // the AI call fails. + await addMessage(currentChatId, "user", text.trim()); const chatMessages = await getMessages(currentChatId); res.setHeader("Content-Type", "text/event-stream"); res.setHeader("Cache-Control", "no-cache"); @@ -50,7 +54,6 @@ router.post("/", async (req, res) => { ); res.write(`data: ${JSON.stringify({ type: "done" })}\n\n`); - await addMessage(currentChatId, "user", text.trim()); await addMessage(currentChatId, "assistant", assistantText); } catch (err) { console.error("Chat error:", err.message);