An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: implement Vercel AI SDK v5 persistence pattern
Yoshiki Miura5465c0284f48
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex 93a68426..dcdf8463 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -23,7 +23,7 @@ export async function POST(req: Request) {// Handle different triggerslet message-+if (trigger === 'regenerate-assistant-message') {// For regeneration, we'll fetch the messages from DB and use the last user message// This will be handled in createChatStreamResponse@@ -31,7 +31,7 @@ export async function POST(req: Request) {} else {// Get the last message from the messages array (the new user message)message = messages?.[messages.length - 1]-+if (!message) {return new Response('No message provided', {status: 400,diff --git a/app/page.tsx b/app/page.tsxindex d58b1801..7cb53da5 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -1,10 +1,10 @@import { getModels } from '@/lib/config/models'-import { generateUUID } from '@/lib/utils'+import { generateId } from '@/lib/db/schema'import { Chat } from '@/components/chat'export default async function Page() {- const id = generateUUID()+ const id = generateId()const models = await getModels()return <Chat id={id} models={models} />}diff --git a/components/chat.tsx b/components/chat.tsxindex 0c10ab94..e99664ae 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -8,10 +8,11 @@ import { toast } from 'sonner'import { z } from 'zod'import { deleteTrailingMessages } from '@/lib/actions/chat-db'+import { generateId } from '@/lib/db/schema'import { UploadedFile } from '@/lib/types'import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'import { Model } from '@/lib/types/models'-import { cn, generateUUID } from '@/lib/utils'+import { cn } from '@/lib/utils'import { useFileDropzone } from '@/hooks/use-file-dropzone'@@ -51,9 +52,10 @@ export function Chat({regenerate,addToolResult} = useChat({+ id, // use the provided chatIdtransport: new DefaultChatTransport({api: '/api/chat',- prepareSendMessagesRequest: ({ id, messages, trigger, messageId }) => {+ prepareSendMessagesRequest: ({ messages, trigger, messageId }) => {switch (trigger) {case 'regenerate-assistant-message':// Only send messageId, not message data@@ -61,8 +63,8 @@ export function Chat({body: {trigger: 'regenerate-assistant-message',chatId: id,- messageId,- },+ messageId+ }}case 'submit-user-message':@@ -73,8 +75,8 @@ export function Chat({trigger: 'submit-user-message',chatId: id,messages: [messages[messages.length - 1]],- messageId,- },+ messageId+ }}}}@@ -88,24 +90,13 @@ export function Chat({toast.error(`Error in chat: ${error.message}`)},experimental_throttle: 100,- generateId: generateUUID+ generateId})const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {setInput(e.target.value)}- const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {- e.preventDefault()- if (input.trim()) {- sendMessage({- role: 'user' as const,- parts: [{ type: 'text', text: input }]- })- setInput('')- }- }-// Convert messages array to sections arrayconst sections = useMemo<ChatSection[]>(() => {const result: ChatSection[] = []@@ -216,7 +207,7 @@ export function Chat({: prevMessagesconst newUIMessage: UIMessage = {- id: generateUUID(),+ id: generateId(),role: 'user',parts: [{ type: 'text', text: newContentText }]}@@ -286,7 +277,7 @@ export function Chat({)const newResentUserMessage: UIMessage = {- id: generateUUID(),+ id: generateId(),role: 'user',parts: [{ type: 'text', text: contentToResend }]}diff --git a/drizzle/0002_add_related_questions_columns.sql b/drizzle/0002_add_related_questions_columns.sqlnew file mode 100644index 00000000..6114b25c--- /dev/null+++ b/drizzle/0002_add_related_questions_columns.sql@@ -0,0 +1,3 @@+-- Add columns for relatedQuestions tool+ALTER TABLE parts ADD COLUMN tool_related_questions_input json;+ALTER TABLE parts ADD COLUMN tool_related_questions_output json;\ No newline at end of filediff --git a/drizzle/meta/0001_snapshot.json b/drizzle/meta/0001_snapshot.jsonindex 487a1769..5e04af1a 100644--- a/drizzle/meta/0001_snapshot.json+++ b/drizzle/meta/0001_snapshot.json@@ -122,12 +122,8 @@"name": "messages_chat_id_chats_id_fk","tableFrom": "messages","tableTo": "chats",- "columnsFrom": [- "chat_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["chat_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -403,12 +399,8 @@"name": "parts_message_id_messages_id_fk","tableFrom": "parts","tableTo": "messages",- "columnsFrom": [- "message_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["message_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -452,4 +444,4 @@"schemas": {},"tables": {}}-}\ No newline at end of file+}diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.jsonnew file mode 100644index 00000000..4c9d178b--- /dev/null+++ b/drizzle/meta/0002_snapshot.json@@ -0,0 +1,540 @@+{+ "id": "00000000-0000-0000-0000-000000000002",+ "prevId": "00000000-0000-0000-0000-000000000001",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.chats": {+ "name": "chats",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "default": ""+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": ""+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "default": ""+ },+ "visibility": {+ "name": "visibility",+ "type": "visibility_type",+ "typeSchema": "public",+ "primaryKey": false,+ "notNull": false,+ "default": "'private'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chats_user_id_idx": {+ "name": "chats_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chats_created_at_idx": {+ "name": "chats_created_at_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.messages": {+ "name": "messages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "default": ""+ },+ "chat_id": {+ "name": "chat_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "default": ""+ },+ "role": {+ "name": "role",+ "type": "message_role",+ "typeSchema": "public",+ "primaryKey": false,+ "notNull": true,+ "default": ""+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "messages_chat_id_idx": {+ "name": "messages_chat_id_idx",+ "columns": [+ {+ "expression": "chat_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_created_at_idx": {+ "name": "messages_created_at_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "messages_chat_id_fkey": {+ "name": "messages_chat_id_fkey",+ "tableFrom": "messages",+ "tableTo": "chats",+ "columnsFrom": ["chat_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.parts": {+ "name": "parts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "default": ""+ },+ "message_id": {+ "name": "message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true,+ "default": ""+ },+ "type": {+ "name": "type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true,+ "default": ""+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": ""+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "reasoning_text": {+ "name": "reasoning_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "file_media_type": {+ "name": "file_media_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "file_filename": {+ "name": "file_filename",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "file_url": {+ "name": "file_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "source_url_source_id": {+ "name": "source_url_source_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "source_url_url": {+ "name": "source_url_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "source_url_title": {+ "name": "source_url_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "source_document_source_id": {+ "name": "source_document_source_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "source_document_media_type": {+ "name": "source_document_media_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "source_document_title": {+ "name": "source_document_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "source_document_filename": {+ "name": "source_document_filename",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "source_document_url": {+ "name": "source_document_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "source_document_snippet": {+ "name": "source_document_snippet",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_call_id": {+ "name": "tool_call_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_name": {+ "name": "tool_name",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_args": {+ "name": "tool_args",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "result": {+ "name": "result",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "is_error": {+ "name": "is_error",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "tool_tool_call_id": {+ "name": "tool_tool_call_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_state": {+ "name": "tool_state",+ "type": "tool_state",+ "typeSchema": "public",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_error_text": {+ "name": "tool_error_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_search_input": {+ "name": "tool_search_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_search_output": {+ "name": "tool_search_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_retrieve_input": {+ "name": "tool_retrieve_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_retrieve_output": {+ "name": "tool_retrieve_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_question_input": {+ "name": "tool_question_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_question_output": {+ "name": "tool_question_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_video_search_input": {+ "name": "tool_video_search_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_video_search_output": {+ "name": "tool_video_search_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_related_questions_input": {+ "name": "tool_related_questions_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_related_questions_output": {+ "name": "tool_related_questions_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_mcp_input": {+ "name": "tool_mcp_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "tool_mcp_output": {+ "name": "tool_mcp_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "data_prefix": {+ "name": "data_prefix",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "data_content": {+ "name": "data_content",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "data_id": {+ "name": "data_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false,+ "default": ""+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "parts_message_id_idx": {+ "name": "parts_message_id_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "parts_message_id_fkey": {+ "name": "parts_message_id_fkey",+ "tableFrom": "parts",+ "tableTo": "messages",+ "columnsFrom": ["message_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {+ "public.message_role": {+ "name": "message_role",+ "schema": "public",+ "values": ["user", "assistant", "system", "data"]+ },+ "public.tool_state": {+ "name": "tool_state",+ "schema": "public",+ "values": [+ "input-streaming",+ "input-available",+ "output-available",+ "output-error"+ ]+ },+ "public.visibility_type": {+ "name": "visibility_type",+ "schema": "public",+ "values": ["public", "private"]+ }+ },+ "schemas": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex 9e010182..7ac7826f 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -15,6 +15,13 @@"when": 1753524626533,"tag": "0001_busy_katie_power","breakpoints": true+ },+ {+ "idx": 2,+ "version": "7",+ "when": 1753525000000,+ "tag": "0002_add_related_questions_columns",+ "breakpoints": true}]-}\ No newline at end of file+}diff --git a/lib/actions/chat.ts b/lib/actions/chat.tsindex e7b4fd29..f87af00c 100644--- a/lib/actions/chat.ts+++ b/lib/actions/chat.ts@@ -1,6 +1,6 @@'use server'-import { revalidateTag, unstable_cache } from 'next/cache'+import { revalidateTag } from 'next/cache'import { getCurrentUserId } from '@/lib/auth/get-current-user'import * as dbActions from '@/lib/db/actions'@@ -21,9 +21,9 @@ export async function getChats() {}/**- * Get a single chat with caching+ * Get a chat with messages (no cache)*/-const getChatUncached = async function (+export async function getChat(chatId: string,requestingUserId?: string): Promise<(Chat & { messages: UIMessage[] }) | null> {@@ -36,26 +36,31 @@ const getChatUncached = async function (return { ...chat, messages }}-// Create a cached version for each chatId-const createCachedGetChat = (chatId: string) =>- unstable_cache(- (id: string, userId?: string) => getChatUncached(id, userId),- [`chat-${chatId}`],- {- revalidate: 300, // 5 minutes cache- tags: [`chat-${chatId}`, 'chat']- }- )-/**- * Get a chat with messages (cached)+ * Create a new chat*/-export async function getChat(- chatId: string,- requestingUserId?: string-): Promise<(Chat & { messages: UIMessage[] }) | null> {- const cachedGetChat = createCachedGetChat(chatId)- return cachedGetChat(chatId, requestingUserId)+export async function createChat(id?: string, title?: string): Promise<Chat> {+ const userId = await getCurrentUserId()+ if (!userId) {+ throw new Error('User not authenticated')+ }++ const chatId = id || generateId()+ const chatTitle = title || 'New Chat'++ // Create chat+ const chat = await dbActions.createChat({+ id: chatId,+ title: chatTitle.substring(0, 255),+ userId,+ visibility: 'private'+ })++ // Revalidate cache+ revalidateTag(`chat-${chatId}`)+ revalidateTag('chat')++ return chat}/**@@ -74,7 +79,8 @@ export async function createChatAndSaveMessage(const messageId = message.id || generateId()// Extract title from message if not provided- const chatTitle = title || getTextFromParts(message.parts as any[]) || 'New Chat'+ const chatTitle =+ title || getTextFromParts(message.parts as any[]) || 'New Chat'// Create chatconst chat = await dbActions.createChat({@@ -138,7 +144,7 @@ export async function deleteChat(chatId: string) {}const result = await dbActions.deleteChat(chatId, userId)-+if (result.success) {revalidateTag(`chat-${chatId}`)revalidateTag('chat')@@ -157,7 +163,7 @@ export async function clearChats() {}const chats = await dbActions.getChats(userId)-+for (const chat of chats) {await dbActions.deleteChat(chat.id, userId)}@@ -169,10 +175,7 @@ export async function clearChats() {/*** Delete messages after a specific message*/-export async function deleteMessagesAfter(- chatId: string,- messageId: string-) {+export async function deleteMessagesAfter(chatId: string, messageId: string) {const userId = await getCurrentUserId()if (!userId) {return { error: 'User not authenticated' }@@ -185,9 +188,9 @@ export async function deleteMessagesAfter(}const result = await dbActions.deleteMessagesAfter(chatId, messageId)-+revalidateTag(`chat-${chatId}`)-+return { success: true, count: result.count }}@@ -200,8 +203,12 @@ export async function shareChat(chatId: string) {return null}- const updatedChat = await dbActions.updateChatVisibility(chatId, userId, 'public')-+ const updatedChat = await dbActions.updateChatVisibility(+ chatId,+ userId,+ 'public'+ )+if (updatedChat) {revalidateTag(`chat-${chatId}`)}@@ -228,8 +235,8 @@ export async function deleteMessagesFromIndex(}const result = await dbActions.deleteMessagesFromIndex(chatId, messageId)-+revalidateTag(`chat-${chatId}`)-+return { success: true, count: result.count }-}\ No newline at end of file+}diff --git a/lib/db/actions.ts b/lib/db/actions.tsindex e1ddf151..071fc834 100644--- a/lib/db/actions.ts+++ b/lib/db/actions.ts@@ -1,16 +1,17 @@'use server'-import { and, asc, desc,eq, gt, inArray } from 'drizzle-orm'+import { and, asc, desc, eq, gt, inArray } from 'drizzle-orm'import type { UIMessage } from '@/lib/types/ai'import type { PersistableUIMessage } from '@/lib/types/message-persistence'-import {- buildUIMessageFromDB,- mapUIMessagePartsToDBParts,- mapUIMessageToDBMessage} from '@/lib/utils/message-mapping'+import {+ buildUIMessageFromDB,+ mapUIMessagePartsToDBParts,+ mapUIMessageToDBMessage+} from '@/lib/utils/message-mapping'import type { Chat, Message } from './schema'-import { chats, generateId,messages, parts } from './schema'+import { chats, generateId, messages, parts } from './schema'import { db } from '.'/**@@ -75,7 +76,7 @@ export async function getChat(export async function upsertMessage(message: PersistableUIMessage & { chatId: string }): Promise<Message> {- return await db.transaction(async (tx) => {+ return await db.transaction(async tx => {// 1. Insert or update the messageconst messageData = mapUIMessageToDBMessage(message)const [dbMessage] = await tx@@ -83,7 +84,7 @@ export async function upsertMessage(.values(messageData).onConflictDoUpdate({target: messages.id,- set: { role: messageData.role },+ set: { role: messageData.role }}).returning()@@ -111,10 +112,10 @@ export async function loadChat(chatId: string): Promise<UIMessage[]> {where: eq(messages.chatId, chatId),with: {parts: {- orderBy: [asc(parts.order)],- },+ orderBy: [asc(parts.order)]+ }},- orderBy: [asc(messages.createdAt)],+ orderBy: [asc(messages.createdAt)]})// Convert to UI format@@ -151,7 +152,7 @@ export async function deleteMessagesAfter()const messageIds = messagesToDelete.map(m => m.id)-+if (messageIds.length > 0) {// Delete messages (parts will be cascade deleted)await db.delete(messages).where(inArray(messages.id, messageIds))@@ -176,7 +177,7 @@ export async function deleteMessagesFromIndex(// Find the index of the target messageconst messageIndex = allMessages.findIndex(m => m.id === messageId)-+if (messageIndex === -1) {return { count: 0 }}@@ -247,4 +248,20 @@ export async function updateChatVisibility(.returning()return updatedChat-}\ No newline at end of file+}++/**+ * Update chat title+ */+export async function updateChatTitle(+ chatId: string,+ title: string+): Promise<Chat | null> {+ const [updatedChat] = await db+ .update(chats)+ .set({ title })+ .where(eq(chats.id, chatId))+ .returning()++ return updatedChat || null+}diff --git a/lib/db/index.ts b/lib/db/index.tsindex dc27af9e..1e0f9d9d 100644--- a/lib/db/index.ts+++ b/lib/db/index.ts@@ -17,8 +17,8 @@ const client = postgres(connectionString, {max: 20 // Max 20 connections})-export const db = drizzle(client, {- schema: { ...schema, ...relations }+export const db = drizzle(client, {+ schema: { ...schema, ...relations }})// Helper type for all tablesdiff --git a/lib/db/relations.ts b/lib/db/relations.tsindex 67a8705a..9fc2e953 100644--- a/lib/db/relations.ts+++ b/lib/db/relations.ts@@ -3,20 +3,20 @@ import { relations } from 'drizzle-orm'import { chats, messages, parts } from './schema'export const chatsRelations = relations(chats, ({ many }) => ({- messages: many(messages),+ messages: many(messages)}))export const messagesRelations = relations(messages, ({ one, many }) => ({chat: one(chats, {fields: [messages.chatId],- references: [chats.id],+ references: [chats.id]}),- parts: many(parts),+ parts: many(parts)}))export const partsRelations = relations(parts, ({ one }) => ({message: one(messages, {fields: [parts.messageId],- references: [messages.id],- }),-}))\ No newline at end of file+ references: [messages.id]+ })+}))diff --git a/lib/db/schema.ts b/lib/db/schema.tsindex 2f48b555..c95c5174 100644--- a/lib/db/schema.ts+++ b/lib/db/schema.ts@@ -8,7 +8,8 @@ import {pgTable,text,timestamp,- varchar} from 'drizzle-orm/pg-core'+ varchar+} from 'drizzle-orm/pg-core'// ID generation functionexport const generateId = () => createId()@@ -17,7 +18,9 @@ export const generateId = () => createId()export const chats = pgTable('chats',{- id: varchar('id').primaryKey().$defaultFn(() => generateId()),+ id: varchar('id')+ .primaryKey()+ .$defaultFn(() => generateId()),createdAt: timestamp('created_at', { mode: 'string', withTimezone: true }).notNull().defaultNow(),@@ -43,7 +46,9 @@ export type Chat = InferSelectModel<typeof chats>export const messages = pgTable('messages',{- id: varchar('id').primaryKey().$defaultFn(() => generateId()),+ id: varchar('id')+ .primaryKey()+ .$defaultFn(() => generateId()),chatId: varchar('chat_id').notNull().references(() => chats.id, { onDelete: 'cascade' }),@@ -54,7 +59,10 @@ export const messages = pgTable(},table => ({chatIdIdx: index('messages_chat_id_idx').on(table.chatId),- chatIdCreatedAtIdx: index('messages_chat_id_created_at_idx').on(table.chatId, table.createdAt),+ chatIdCreatedAtIdx: index('messages_chat_id_created_at_idx').on(+ table.chatId,+ table.createdAt+ ),enableRls: true}))@@ -65,42 +73,50 @@ export type Message = InferSelectModel<typeof messages>export const parts = pgTable('parts',{- id: varchar('id').primaryKey().$defaultFn(() => generateId()),+ id: varchar('id')+ .primaryKey()+ .$defaultFn(() => generateId()),messageId: varchar('message_id').notNull().references(() => messages.id, { onDelete: 'cascade' }),order: integer('order').notNull(),type: varchar('type', { length: 256 }).notNull(),-+// Text partstext_text: text('text_text'),-+// Reasoning partsreasoning_text: text('reasoning_text'),-+// File partsfile_mediaType: varchar('file_media_type', { length: 256 }),file_filename: varchar('file_filename', { length: 1024 }),file_url: text('file_url'),-+// Source URL partssource_url_sourceId: varchar('source_url_source_id', { length: 256 }),source_url_url: text('source_url_url'),source_url_title: text('source_url_title'),-+// Source document parts- source_document_sourceId: varchar('source_document_source_id', { length: 256 }),- source_document_mediaType: varchar('source_document_media_type', { length: 256 }),+ source_document_sourceId: varchar('source_document_source_id', {+ length: 256+ }),+ source_document_mediaType: varchar('source_document_media_type', {+ length: 256+ }),source_document_title: text('source_document_title'),- source_document_filename: varchar('source_document_filename', { length: 1024 }),+ source_document_filename: varchar('source_document_filename', {+ length: 1024+ }),source_document_url: text('source_document_url'),source_document_snippet: text('source_document_snippet'),-+// Tool parts (generic)tool_toolCallId: varchar('tool_tool_call_id', { length: 256 }),tool_state: varchar('tool_state', { length: 256 }),tool_errorText: text('tool_error_text'),-+// Tool-specific columns (all Morphic tools)tool_search_input: json('tool_search_input').$type<any>(),tool_search_output: json('tool_search_output').$type<any>(),@@ -110,17 +126,23 @@ export const parts = pgTable(tool_question_output: json('tool_question_output').$type<any>(),tool_videoSearch_input: json('tool_video_search_input').$type<any>(),tool_videoSearch_output: json('tool_video_search_output').$type<any>(),+ tool_relatedQuestions_input: json(+ 'tool_related_questions_input'+ ).$type<any>(),+ tool_relatedQuestions_output: json(+ 'tool_related_questions_output'+ ).$type<any>(),tool_mcp_input: json('tool_mcp_input').$type<any>(),tool_mcp_output: json('tool_mcp_output').$type<any>(),-+// Data parts (generic support)data_prefix: varchar('data_prefix', { length: 256 }),data_content: json('data_content').$type<any>(),data_id: varchar('data_id', { length: 256 }),-+// Provider metadataproviderMetadata: json('provider_metadata').$type<Record<string, any>>(),-+createdAt: timestamp('created_at', { mode: 'string', withTimezone: true }).notNull().defaultNow()@@ -128,17 +150,35 @@ export const parts = pgTable(table => ({// IndexesmessageIdIdx: index('parts_message_id_idx').on(table.messageId),- messageIdOrderIdx: index('parts_message_id_order_idx').on(table.messageId, table.order),+ messageIdOrderIdx: index('parts_message_id_order_idx').on(+ table.messageId,+ table.order+ ),enableRls: true,-+// Constraints- textTextRequired: check('text_text_required', sql`(type != 'text' OR text_text IS NOT NULL)`),- reasoningTextRequired: check('reasoning_text_required', sql`(type != 'reasoning' OR reasoning_text IS NOT NULL)`),- fileFieldsRequired: check('file_fields_required', sql`(type != 'file' OR (file_media_type IS NOT NULL AND file_filename IS NOT NULL AND file_url IS NOT NULL))`),- toolStateValid: check('tool_state_valid', sql`(tool_state IS NULL OR tool_state IN ('input-streaming', 'input-available', 'output-available', 'output-error'))`),- toolFieldsRequired: check('tool_fields_required', sql`(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))`)+ textTextRequired: check(+ 'text_text_required',+ sql`(type != 'text' OR text_text IS NOT NULL)`+ ),+ reasoningTextRequired: check(+ 'reasoning_text_required',+ sql`(type != 'reasoning' OR reasoning_text IS NOT NULL)`+ ),+ fileFieldsRequired: check(+ 'file_fields_required',+ sql`(type != 'file' OR (file_media_type IS NOT NULL AND file_filename IS NOT NULL AND file_url IS NOT NULL))`+ ),+ toolStateValid: check(+ 'tool_state_valid',+ sql`(tool_state IS NULL OR tool_state IN ('input-streaming', 'input-available', 'output-available', 'output-error'))`+ ),+ toolFieldsRequired: check(+ 'tool_fields_required',+ sql`(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))`+ )}))export type Part = InferSelectModel<typeof parts>-export type NewPart = typeof parts.$inferInsert\ No newline at end of file+export type NewPart = typeof parts.$inferInsertdiff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.tsindex a4ea9277..3f31b196 100644--- a/lib/streaming/create-chat-stream-response.ts+++ b/lib/streaming/create-chat-stream-response.ts@@ -8,7 +8,12 @@ import {import { researcher } from '@/lib/agents/researcher'-import { createChatAndSaveMessage, deleteMessagesFromIndex,getChat as getChatAction, saveMessage } from '../actions/chat'+import {+ createChat,+ deleteMessagesFromIndex,+ getChat as getChatAction,+ saveMessage+} from '../actions/chat'import { generateRelatedQuestions } from '../agents/generate-related-questions'import { generateChatTitle } from '../agents/title-generator'import { generateId } from '../db/schema'@@ -19,68 +24,66 @@ import { BaseStreamConfig } from './types'export async function createChatStreamResponse(config: BaseStreamConfig): Promise<Response> {- const { message, model, chatId, searchMode, userId, trigger, messageId } = config+ const { message, model, chatId, searchMode, userId, trigger, messageId } =+ configconst modelId = `${model.providerId}:${model.id}`- // Fetch chat data for authorization check before stream creation- const chatForAuth = await getChatAction(chatId, userId)+ // Verify that chatId is provided+ if (!chatId) {+ return new Response('Chat ID is required', {+ status: 400,+ statusText: 'Bad Request'+ })+ }++ // Fetch chat data for authorization check+ const chat = await getChatAction(chatId, userId)- // Authorization check: if chat exists and does not belong to the user- if (chatForAuth && chatForAuth.userId !== userId) {+ // Authorization check: if chat exists, it must belong to the user+ if (chat && chat.userId !== userId) {return new Response('You are not allowed to access this chat', {status: 403,statusText: 'Forbidden'})}- // If authorized or it's a new chat, proceed to create the stream+ // Create the streamconst stream = createUIMessageStream({execute: async ({ writer }: { writer: UIMessageStreamWriter }) => {try {let messagesToModel: UIMessage[]-+if (trigger === 'regenerate-assistant-message' && messageId) {// Handle regeneration- if (!chatForAuth) {- throw new Error('Chat not found for regeneration')- }-// Delete messages from the specified messageId onwardsawait deleteMessagesFromIndex(chatId, messageId)-+// Get updated messagesconst updatedChat = await getChatAction(chatId, userId)if (!updatedChat || !updatedChat.messages.length) {throw new Error('No messages to regenerate')}-+messagesToModel = updatedChat.messages} else {// Handle normal message submissionif (!message) {throw new Error('No message provided')}-- // Ensure message has an ID++ // Save the messageconst messageWithId = {...message,id: message.id || generateId()}- // Use chatForAuth (from outer scope) to decide new/existing path- if (!chatForAuth) {- // New chat- const userContent = getTextFromParts(message.parts)- const title = await generateChatTitle({- userMessageContent: userContent,- modelId- })- await createChatAndSaveMessage(messageWithId, title)- } else {- // Existing chat, and user is authorized (auth check done outside)- await saveMessage(chatId, messageWithId)+ // If chat doesn't exist, create it with a temporary title+ if (!chat) {+ await createChat(chatId, 'New Chat')}+ await saveMessage(chatId, messageWithId)+// Get all messages including the one just savedconst updatedChat = await getChatAction(chatId, userId)messagesToModel = updatedChat?.messages || [messageWithId]@@ -136,34 +139,36 @@ export async function createChatStreamResponse(writer.merge(relatedQuestionsResult.toUIMessageStream({sendStart: false,- onFinish: ({ responseMessage }) => {+ onFinish: async ({ responseMessage }) => {relatedQuestionsMessage = responseMessage- }- })- )- // Save the complete message after both agents finish- relatedQuestionsResult.response- .then(async () => {- // Merge and save both messages- if (researchMessage && relatedQuestionsMessage) {- const mergedMessage = mergeUIMessages(- researchMessage,- relatedQuestionsMessage- )- await saveMessage(chatId, mergedMessage)- } else if (researchMessage) {- // Save research message only if related questions failed- await saveMessage(chatId, researchMessage)- }- })- .catch(async error => {- console.error('Related questions error:', error)- // Save research message even if related questions fail- if (researchMessage) {- await saveMessage(chatId, researchMessage)+ // Save the complete message after both agents finish+ // Merge and save both messages+ if (researchMessage && relatedQuestionsMessage) {+ const mergedMessage = mergeUIMessages(+ researchMessage,+ relatedQuestionsMessage+ )+ await saveMessage(chatId, mergedMessage)+ } else if (researchMessage) {+ // Save research message only if related questions failed+ await saveMessage(chatId, researchMessage)+ }++ // Generate proper title after conversation starts+ if (!chat && message) {+ const userContent = getTextFromParts(message.parts)+ const title = await generateChatTitle({+ userMessageContent: userContent,+ modelId+ })+ // Update chat title+ const { updateChatTitle } = await import('../db/actions')+ await updateChatTitle(chatId, title)+ }}})+ )} catch (error) {console.error('Error generating related questions:', error)}diff --git a/lib/types/message-persistence.ts b/lib/types/message-persistence.tsindex fc32e3ff..caacf37c 100644--- a/lib/types/message-persistence.ts+++ b/lib/types/message-persistence.ts@@ -19,7 +19,11 @@ export type DBMessagePart = typeof parts.$inferInsertexport type DBMessagePartSelect = typeof parts.$inferSelect// Tool states-export type ToolState = 'input-streaming' | 'input-available' | 'output-available' | 'output-error'+export type ToolState =+ | 'input-streaming'+ | 'input-available'+ | 'output-available'+ | 'output-error'// MCP tool type definitionsexport type MCPToolInput = {@@ -52,4 +56,4 @@ export type DBMessage = {export type PersistableUIMessage = UIMessage & {id: stringchatId?: string-}\ No newline at end of file+}diff --git a/lib/utils/message-mapping.ts b/lib/utils/message-mapping.tsindex ec2c4e6c..8e0197cb 100644--- a/lib/utils/message-mapping.ts+++ b/lib/utils/message-mapping.ts@@ -1,17 +1,54 @@+import { generateId } from '@/lib/db/schema'import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'-import type { DBMessagePart, DBMessagePartSelect, ToolState } from '@/lib/types/message-persistence'+import type {+ DBMessagePart,+ DBMessagePartSelect,+ ToolState+} from '@/lib/types/message-persistence'// Define local types for message parts that are compatible with the AI SDKtype TextUIPart = { type: 'text'; text: string; providerMetadata?: any }-type ReasoningUIPart = { type: 'reasoning'; text: string; providerMetadata?: any }-type FileUIPart = { type: 'file'; mediaType: string; filename?: string; url: string }-type SourceUrlUIPart = { type: 'source-url'; sourceId: string; url: string; title: string } // title is required-type SourceDocumentUIPart = { type: 'source-document'; sourceId: string; mediaType: string; title: string; filename: string; url: string; snippet: string } // all fields required-type ToolCallPart = { type: 'tool-call'; toolCallId: string; toolName: string; args: any }-type ToolResultPart = { type: 'tool-result'; toolCallId: string; result: any; isError?: boolean }+type ReasoningUIPart = {+ type: 'reasoning'+ text: string+ providerMetadata?: any+}+type FileUIPart = {+ type: 'file'+ mediaType: string+ filename?: string+ url: string+}+type SourceUrlUIPart = {+ type: 'source-url'+ sourceId: string+ url: string+ title: string+} // title is required+type SourceDocumentUIPart = {+ type: 'source-document'+ sourceId: string+ mediaType: string+ title: string+ filename: string+ url: string+ snippet: string+} // all fields required+type ToolCallPart = {+ type: 'tool-call'+ toolCallId: string+ toolName: string+ args: any+}+type ToolResultPart = {+ type: 'tool-result'+ toolCallId: string+ result: any+ isError?: boolean+}type DataPart = { type: string; [key: string]: any }-type UIMessagePart =+type UIMessagePart =| TextUIPart| ReasoningUIPart| FileUIPart@@ -32,21 +69,21 @@ export function mapUIMessagePartsToDBParts(const basePart = {messageId,order: index,- type: part.type,+ type: part.type}switch (part.type) {case 'text':return {...basePart,- text_text: part.text,+ text_text: part.text}case 'reasoning':return {...basePart,reasoning_text: part.text,- providerMetadata: part.providerMetadata,+ providerMetadata: part.providerMetadata}case 'file':@@ -54,7 +91,7 @@ export function mapUIMessagePartsToDBParts(...basePart,file_mediaType: part.mediaType,file_filename: part.filename,- file_url: part.url,+ file_url: part.url}case 'source-url':@@ -62,7 +99,7 @@ export function mapUIMessagePartsToDBParts(...basePart,source_url_sourceId: part.sourceId,source_url_url: part.url,- source_url_title: part.title,+ source_url_title: part.title}case 'source-document':@@ -73,33 +110,73 @@ export function mapUIMessagePartsToDBParts(source_document_title: part.title,source_document_filename: part.filename,source_document_url: part.url,- source_document_snippet: part.snippet,+ source_document_snippet: part.snippet}// Tool partscase 'tool-call':const toolName = getToolNameFromType(part.toolName)const toolInputColumn = `tool_${toolName}_input` as keyof DBMessagePart-+return {...basePart,type: `tool-${toolName}`,tool_toolCallId: part.toolCallId,tool_state: 'input-available' as ToolState,- [toolInputColumn]: part.args,+ [toolInputColumn]: part.args}case 'tool-result':- const resultToolName = getToolNameFromCallId(part.toolCallId, messageParts)- const toolOutputColumn = `tool_${resultToolName}_output` as keyof DBMessagePart-+ const resultToolName = getToolNameFromCallId(+ part.toolCallId,+ messageParts+ )+ const toolOutputColumn =+ `tool_${resultToolName}_output` as keyof DBMessagePart+return {...basePart,type: `tool-${resultToolName}`,tool_toolCallId: part.toolCallId,- tool_state: part.isError ? 'output-error' : 'output-available' as ToolState,+ tool_state: part.isError+ ? 'output-error'+ : ('output-available' as ToolState),tool_errorText: part.isError ? String(part.result) : undefined,- [toolOutputColumn]: !part.isError ? part.result : undefined,+ [toolOutputColumn]: !part.isError ? part.result : undefined+ }++ // Step parts (for UI tracking)+ case 'step-start':+ case 'step-result':+ case 'step-continue':+ case 'step-finish':+ return {+ ...basePart,+ type: part.type,+ data_prefix: part.type,+ data_content: part+ }++ // Tool-specific parts that are not tool-call or tool-result+ case 'tool-search':+ case 'tool-retrieve':+ case 'tool-question':+ case 'tool-videoSearch':+ case 'tool-relatedQuestions':+ // These are tool parts with state tracking+ const toolPartName = part.type.replace('tool-', '') // Remove 'tool-' prefix+ const inputColumn = `tool_${toolPartName}_input` as keyof DBMessagePart+ const outputColumn =+ `tool_${toolPartName}_output` as keyof DBMessagePart++ return {+ ...basePart,+ type: part.type,+ tool_toolCallId: (part as any).toolCallId || generateId(),+ tool_state: (part as any).state || ('input-available' as ToolState),+ tool_errorText: (part as any).errorText,+ [inputColumn]: (part as any).input,+ [outputColumn]: (part as any).output}// Data parts@@ -110,7 +187,7 @@ export function mapUIMessagePartsToDBParts(...basePart,data_prefix: dataType,data_content: (part as any).data || part,- data_id: (part as any).id,+ data_id: (part as any).id}}@@ -118,7 +195,7 @@ export function mapUIMessagePartsToDBParts(return {...basePart,data_prefix: part.type,- data_content: part,+ data_content: part}}})@@ -127,19 +204,21 @@ export function mapUIMessagePartsToDBParts(/*** Convert DB message parts to UI format*/-export function mapDBPartToUIMessagePart(part: DBMessagePartSelect): UIMessagePart {+export function mapDBPartToUIMessagePart(+ part: DBMessagePartSelect+): UIMessagePart {switch (part.type) {case 'text':return {type: 'text',- text: part.text_text!,+ text: part.text_text!}case 'reasoning':return {type: 'reasoning',text: part.reasoning_text!,- providerMetadata: part.providerMetadata,+ providerMetadata: part.providerMetadata}case 'file':@@ -147,7 +226,7 @@ export function mapDBPartToUIMessagePart(part: DBMessagePartSelect): UIMessagePatype: 'file',mediaType: part.file_mediaType!,filename: part.file_filename!,- url: part.file_url!,+ url: part.file_url!}case 'source-url':@@ -155,7 +234,7 @@ export function mapDBPartToUIMessagePart(part: DBMessagePartSelect): UIMessagePatype: 'source-url',sourceId: part.source_url_sourceId!,url: part.source_url_url!,- title: part.source_url_title || '', // Provide default empty string+ title: part.source_url_title || '' // Provide default empty string}case 'source-document':@@ -166,23 +245,48 @@ export function mapDBPartToUIMessagePart(part: DBMessagePartSelect): UIMessagePatitle: part.source_document_title || '', // Provide defaultsfilename: part.source_document_filename || '',url: part.source_document_url || '',- snippet: part.source_document_snippet || '',+ snippet: part.source_document_snippet || ''}default:// Tool partsif (part.type.startsWith('tool-')) {const toolName = part.type.substring(5) // Remove 'tool-' prefix- const inputColumn = `tool_${toolName}_input` as keyof DBMessagePartSelect- const outputColumn = `tool_${toolName}_output` as keyof DBMessagePartSelect+ const inputColumn =+ `tool_${toolName}_input` as keyof DBMessagePartSelect+ const outputColumn =+ `tool_${toolName}_output` as keyof DBMessagePartSelect- // Determine if this is a tool-call or tool-result based on state- if (part.tool_state === 'input-available' || part.tool_state === 'input-streaming') {+ // Special handling for tool parts that maintain their type+ if (+ [+ 'search',+ 'retrieve',+ 'question',+ 'videoSearch',+ 'relatedQuestions'+ ].includes(toolName)+ ) {+ return {+ type: part.type as any,+ toolCallId: part.tool_toolCallId!,+ state: part.tool_state!,+ input: part[inputColumn],+ output: part[outputColumn],+ errorText: part.tool_errorText+ }+ }++ // Standard tool-call/tool-result pattern+ if (+ part.tool_state === 'input-available' ||+ part.tool_state === 'input-streaming'+ ) {return {type: 'tool-call',toolCallId: part.tool_toolCallId!,toolName: getOriginalToolName(toolName),- args: part[inputColumn] as any,+ args: part[inputColumn] as any}} else {// output-available or output-error@@ -190,9 +294,10 @@ export function mapDBPartToUIMessagePart(part: DBMessagePartSelect): UIMessagePatype: 'tool-result',toolCallId: part.tool_toolCallId!,isError: part.tool_state === 'output-error',- result: part.tool_state === 'output-error'- ? part.tool_errorText- : part[outputColumn],+ result:+ part.tool_state === 'output-error'+ ? part.tool_errorText+ : part[outputColumn]}}}@@ -202,7 +307,7 @@ export function mapDBPartToUIMessagePart(part: DBMessagePartSelect): UIMessagePareturn {type: `data-${part.data_prefix}`,...(part.data_content as any),- ...(part.data_id ? { id: part.data_id } : {}),+ ...(part.data_id ? { id: part.data_id } : {})}}@@ -217,12 +322,13 @@ export function mapDBPartToUIMessagePart(part: DBMessagePartSelect): UIMessagePafunction getToolNameFromType(toolName: string): string {// Map original tool names to DB column namesconst toolNameMap: Record<string, string> = {- 'search': 'search',- 'retrieve': 'retrieve',- 'askQuestion': 'question',- 'question': 'question',- 'videoSearch': 'videoSearch',+ search: 'search',+ retrieve: 'retrieve',+ askQuestion: 'question',+ question: 'question',+ videoSearch: 'videoSearch','video-search': 'videoSearch',+ relatedQuestions: 'relatedQuestions'}// For MCP tools@@ -236,7 +342,10 @@ function getToolNameFromType(toolName: string): string {/*** Get tool name from tool-result*/-function getToolNameFromCallId(toolCallId: string, allParts: UIMessagePart[]): string {+function getToolNameFromCallId(+ toolCallId: string,+ allParts: UIMessagePart[]+): string {// Find tool-call part with the same toolCallIdconst toolCallPart = allParts.find(part => part.type === 'tool-call' && part.toolCallId === toolCallId@@ -255,11 +364,11 @@ function getToolNameFromCallId(toolCallId: string, allParts: UIMessagePart[]): s*/function getOriginalToolName(dbToolName: string): string {const reverseMap: Record<string, string> = {- 'search': 'search',- 'retrieve': 'retrieve',- 'question': 'askQuestion',- 'videoSearch': 'videoSearch',- 'mcp': 'mcp', // For MCP, the actual tool name is included in the input+ search: 'search',+ retrieve: 'retrieve',+ question: 'askQuestion',+ videoSearch: 'videoSearch',+ mcp: 'mcp' // For MCP, the actual tool name is included in the input}return reverseMap[dbToolName] || dbToolName@@ -278,7 +387,7 @@ export function mapUIMessageToDBMessage(return {id: message.id,chatId: message.chatId,- role: message.role,+ role: message.role}}@@ -297,6 +406,8 @@ export function buildUIMessageFromDB(id: dbMessage.id,role: dbMessage.role as 'user' | 'assistant',parts: dbParts.map(mapDBPartToUIMessagePart) as UIMessage['parts'],- metadata: dbMessage.createdAt ? { createdAt: new Date(dbMessage.createdAt) } : undefined,+ metadata: dbMessage.createdAt+ ? { createdAt: new Date(dbMessage.createdAt) }+ : undefined}-}\ No newline at end of file+}