Skip to content

Commit 53b46f2

Browse files
committed
fix(ai-chat reference): await Chat.messages persist in onTurnStart
The reference's onTurnStart was using chat.defer for the messages write, which is fire-and-forget. If a user refreshed the page mid-stream, getChatMessages returned [] (the deferred write hadn't landed yet), useChat hydrated with empty initialMessages, and the resumed SSE stream pushed the assistant into an empty array — the user's message vanished from the rendered conversation forever. Switch to await prisma.chat.update(...) so the write is durable before chat.agent begins streaming. Verified end-to-end against test cloud: mid-stream refresh now yields [user, assistant] with no duplication. Aligns with the Warning added to docs/ai-chat/patterns/database-persistence.mdx in the docs branch.
1 parent 5511672 commit 53b46f2

1 file changed

Lines changed: 9 additions & 6 deletions

File tree

  • references/ai-chat/src/trigger

references/ai-chat/src/trigger/chat.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -368,12 +368,15 @@ export const aiChat = chat
368368
onTurnStart: async ({ chatId, uiMessages, writer, runId }) => {
369369
warmCodeSandbox(runId);
370370
writer.write({ type: "data-turn-status", data: { status: "preparing" }, transient: true });
371-
chat.defer(
372-
prisma.chat.update({
373-
where: { id: chatId },
374-
data: { messages: uiMessages as unknown as ChatMessagesForWrite },
375-
})
376-
);
371+
// Awaited (not chat.defer) so the user message is durable before
372+
// streaming begins. A mid-stream page refresh reads from DB; if the
373+
// write is still in flight, getChatMessages returns [] and the
374+
// resumed SSE stream rebuilds an assistant-only conversation,
375+
// dropping the user message from the UI.
376+
await prisma.chat.update({
377+
where: { id: chatId },
378+
data: { messages: uiMessages as unknown as ChatMessagesForWrite },
379+
});
377380
},
378381
// #endregion
379382

0 commit comments

Comments
 (0)