Skip to content

An AI-powered search engine with a generative UI

fix: address Copilot code review comments

Yoshiki Miuracae2b827ceaf
diff --git a/lib/actions/chat-db.ts b/lib/actions/chat-db.ts
index dffa3a5a..cdb3ce42 100644
--- a/lib/actions/chat-db.ts
+++ b/lib/actions/chat-db.ts
@@ -9,6 +9,9 @@ import * as chatDb from '@/lib/db/chat'
import { type Chat as DBChat, type Message as DBMessage } from '@/lib/db/schema' // Import DB schema types
import { getTextFromParts } from '@/lib/utils/message-utils' // Corrected import path
+// Constants
+const DEFAULT_CHAT_TITLE = 'New Chat'
+
// Get all chats for a user
export async function getChats(userId: string) {
return chatDb.getChats(userId)
@@ -211,7 +214,7 @@ export async function saveChatMessage(
if (!existingChat) {
// Use userMessage.parts for title generation
const messageTextForTitle = getTextFromParts(userMessage.parts as any[])
- const chatTitle = title || messageTextForTitle || 'New Chat'
+ const chatTitle = title || messageTextForTitle || DEFAULT_CHAT_TITLE
const chatDataForDb: Partial<DBChat> = {
id: chatId,
title: chatTitle.substring(0, 255),
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
index f87af00c..782ac50f 100644
--- a/lib/actions/chat.ts
+++ b/lib/actions/chat.ts
@@ -9,6 +9,9 @@ import { generateId } from '@/lib/db/schema'
import type { UIMessage } from '@/lib/types/ai'
import { getTextFromParts } from '@/lib/utils/message-utils'
+// Constants
+const DEFAULT_CHAT_TITLE = 'New Chat'
+
/**
* Get all chats for the current user
*/
@@ -46,7 +49,7 @@ export async function createChat(id?: string, title?: string): Promise<Chat> {
}
const chatId = id || generateId()
- const chatTitle = title || 'New Chat'
+ const chatTitle = title || DEFAULT_CHAT_TITLE
// Create chat
const chat = await dbActions.createChat({
@@ -80,7 +83,7 @@ export async function createChatAndSaveMessage(
// Extract title from message if not provided
const chatTitle =
- title || getTextFromParts(message.parts as any[]) || 'New Chat'
+ title || getTextFromParts(message.parts as any[]) || DEFAULT_CHAT_TITLE
// Create chat
const chat = await dbActions.createChat({
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 53a17009..4033295d 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -11,6 +11,12 @@ import {
varchar
} from 'drizzle-orm/pg-core'
+// Constants
+const ID_LENGTH = 191
+const USER_ID_LENGTH = 255
+const VARCHAR_LENGTH = 256
+const FILENAME_LENGTH = 1024
+
// ID generation function
export const generateId = () => createId()
@@ -18,14 +24,14 @@ export const generateId = () => createId()
export const chats = pgTable(
'chats',
{
- id: varchar('id', { length: 191 })
+ id: varchar('id', { length: ID_LENGTH })
.primaryKey()
.$defaultFn(() => generateId()),
createdAt: timestamp('created_at').notNull().defaultNow(),
title: text('title').notNull(),
- userId: varchar('user_id', { length: 255 }).notNull(),
+ userId: varchar('user_id', { length: USER_ID_LENGTH }).notNull(),
visibility: varchar('visibility', {
- length: 256,
+ length: VARCHAR_LENGTH,
enum: ['public', 'private']
})
.notNull()
@@ -44,13 +50,13 @@ export type Chat = InferSelectModel<typeof chats>
export const messages = pgTable(
'messages',
{
- id: varchar('id', { length: 191 })
+ id: varchar('id', { length: ID_LENGTH })
.primaryKey()
.$defaultFn(() => generateId()),
- chatId: varchar('chat_id', { length: 191 })
+ chatId: varchar('chat_id', { length: ID_LENGTH })
.notNull()
.references(() => chats.id, { onDelete: 'cascade' }),
- role: varchar('role', { length: 256 }).notNull(),
+ role: varchar('role', { length: VARCHAR_LENGTH }).notNull(),
createdAt: timestamp('created_at').notNull().defaultNow()
},
table => ({
@@ -69,14 +75,14 @@ export type Message = InferSelectModel<typeof messages>
export const parts = pgTable(
'parts',
{
- id: varchar('id', { length: 191 })
+ id: varchar('id', { length: ID_LENGTH })
.primaryKey()
.$defaultFn(() => generateId()),
- messageId: varchar('message_id', { length: 191 })
+ messageId: varchar('message_id', { length: ID_LENGTH })
.notNull()
.references(() => messages.id, { onDelete: 'cascade' }),
order: integer('order').notNull(),
- type: varchar('type', { length: 256 }).notNull(),
+ type: varchar('type', { length: VARCHAR_LENGTH }).notNull(),
// Text parts
text_text: text('text_text'),
@@ -85,32 +91,34 @@ export const parts = pgTable(
reasoning_text: text('reasoning_text'),
// File parts
- file_mediaType: varchar('file_media_type', { length: 256 }),
- file_filename: varchar('file_filename', { length: 1024 }),
+ file_mediaType: varchar('file_media_type', { length: VARCHAR_LENGTH }),
+ file_filename: varchar('file_filename', { length: FILENAME_LENGTH }),
file_url: text('file_url'),
// Source URL parts
- source_url_sourceId: varchar('source_url_source_id', { length: 256 }),
+ source_url_sourceId: varchar('source_url_source_id', {
+ length: VARCHAR_LENGTH
+ }),
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
+ length: VARCHAR_LENGTH
}),
source_document_mediaType: varchar('source_document_media_type', {
- length: 256
+ length: VARCHAR_LENGTH
}),
source_document_title: text('source_document_title'),
source_document_filename: varchar('source_document_filename', {
- length: 1024
+ length: FILENAME_LENGTH
}),
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_toolCallId: varchar('tool_tool_call_id', { length: VARCHAR_LENGTH }),
+ tool_state: varchar('tool_state', { length: VARCHAR_LENGTH }),
tool_errorText: text('tool_error_text'),
// Tool-specific columns (all Morphic tools)
@@ -132,9 +140,9 @@ export const parts = pgTable(
tool_mcp_output: json('tool_mcp_output').$type<any>(),
// Data parts (generic support)
- data_prefix: varchar('data_prefix', { length: 256 }),
+ data_prefix: varchar('data_prefix', { length: VARCHAR_LENGTH }),
data_content: json('data_content').$type<any>(),
- data_id: varchar('data_id', { length: 256 }),
+ data_id: varchar('data_id', { length: VARCHAR_LENGTH }),
// Provider metadata
providerMetadata: json('provider_metadata').$type<Record<string, any>>(),
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 3f31b196..065a0ddc 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -21,6 +21,9 @@ import { getTextFromParts, mergeUIMessages } from '../utils/message-utils'
import { BaseStreamConfig } from './types'
+// Constants
+const DEFAULT_CHAT_TITLE = 'New Chat'
+
export async function createChatStreamResponse(
config: BaseStreamConfig
): Promise<Response> {
@@ -79,7 +82,7 @@ export async function createChatStreamResponse(
// If chat doesn't exist, create it with a temporary title
if (!chat) {
- await createChat(chatId, 'New Chat')
+ await createChat(chatId, DEFAULT_CHAT_TITLE)
}
await saveMessage(chatId, messageWithId)
diff --git a/lib/utils/message-mapping.ts b/lib/utils/message-mapping.ts
index c2c4cbd0..6792a62e 100644
--- a/lib/utils/message-mapping.ts
+++ b/lib/utils/message-mapping.ts
@@ -58,6 +58,43 @@ type UIMessagePart =
| ToolResultPart
| DataPart
+// Type guards
+function isToolCallPart(part: any): part is ToolCallPart {
+ return (
+ part.type === 'tool-call' &&
+ typeof part.toolCallId === 'string' &&
+ typeof part.toolName === 'string' &&
+ part.args !== undefined
+ )
+}
+
+function isToolResultPart(part: any): part is ToolResultPart {
+ return (
+ part.type === 'tool-result' &&
+ typeof part.toolCallId === 'string' &&
+ part.result !== undefined
+ )
+}
+
+// Type for tool-specific parts with extended properties
+type ExtendedToolPart = {
+ type: string
+ toolCallId?: string
+ state?: ToolState
+ errorText?: string
+ input?: any
+ output?: any
+}
+
+function isExtendedToolPart(part: any): part is ExtendedToolPart {
+ return (
+ typeof part === 'object' &&
+ part !== null &&
+ typeof part.type === 'string' &&
+ part.type.startsWith('tool-')
+ )
+}
+
/**
* Convert UI message parts to DB format
*/
@@ -115,6 +152,11 @@ export function mapUIMessagePartsToDBParts(
// Tool parts
case 'tool-call':
+ // Type guard ensures part has the required properties
+ if (!isToolCallPart(part)) {
+ console.error('Invalid tool-call part:', part)
+ return null
+ }
const toolName = getToolNameFromType(part.toolName)
const toolInputColumn = `tool_${toolName}_input` as keyof DBMessagePart
@@ -159,6 +201,10 @@ export function mapUIMessagePartsToDBParts(
case 'tool-videoSearch':
case 'tool-relatedQuestions':
// These are tool parts with state tracking
+ if (!isExtendedToolPart(part)) {
+ console.error('Invalid extended tool part:', part)
+ return null
+ }
const toolPartName = part.type.replace('tool-', '') // Remove 'tool-' prefix
const inputColumn = `tool_${toolPartName}_input` as keyof DBMessagePart
const outputColumn =
@@ -167,11 +213,11 @@ export function mapUIMessagePartsToDBParts(
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
+ tool_toolCallId: part.toolCallId || generateId(),
+ tool_state: part.state || ('input-available' as ToolState),
+ tool_errorText: part.errorText,
+ [inputColumn]: part.input,
+ [outputColumn]: part.output
}
// Data parts
@@ -181,8 +227,8 @@ export function mapUIMessagePartsToDBParts(
return {
...basePart,
data_prefix: dataType,
- data_content: (part as any).data || part,
- data_id: (part as any).id
+ data_content: 'data' in part ? part.data : part,
+ data_id: 'id' in part ? part.id : undefined
}
}
@@ -211,38 +257,38 @@ export function mapDBPartToUIMessagePart(
case 'text':
return {
type: 'text',
- text: part.text_text!
+ text: part.text_text || ''
}
case 'reasoning':
return {
type: 'reasoning',
- text: part.reasoning_text!,
+ text: part.reasoning_text || '',
providerMetadata: part.providerMetadata
}
case 'file':
return {
type: 'file',
- mediaType: part.file_mediaType!,
- filename: part.file_filename!,
- url: part.file_url!
+ mediaType: part.file_mediaType || '',
+ filename: part.file_filename || '',
+ url: part.file_url || ''
}
case 'source-url':
return {
type: 'source-url',
- sourceId: part.source_url_sourceId!,
- url: part.source_url_url!,
- title: part.source_url_title || '' // Provide default empty string
+ sourceId: part.source_url_sourceId || '',
+ url: part.source_url_url || '',
+ title: part.source_url_title || ''
}
case 'source-document':
return {
type: 'source-document',
- sourceId: part.source_document_sourceId!,
- mediaType: part.source_document_mediaType!,
- title: part.source_document_title || '', // Provide defaults
+ sourceId: part.source_document_sourceId || '',
+ mediaType: part.source_document_mediaType || '',
+ title: part.source_document_title || '',
filename: part.source_document_filename || '',
url: part.source_document_url || '',
snippet: part.source_document_snippet || ''
@@ -269,8 +315,8 @@ export function mapDBPartToUIMessagePart(
) {
return {
type: part.type as any,
- toolCallId: part.tool_toolCallId!,
- state: part.tool_state!,
+ toolCallId: part.tool_toolCallId || '',
+ state: part.tool_state || 'input-available',
input: part[inputColumn],
output: part[outputColumn],
errorText: part.tool_errorText
@@ -284,7 +330,7 @@ export function mapDBPartToUIMessagePart(
) {
return {
type: 'tool-call',
- toolCallId: part.tool_toolCallId!,
+ toolCallId: part.tool_toolCallId || '',
toolName: getOriginalToolName(toolName),
args: part[inputColumn] as any
}
@@ -292,7 +338,7 @@ export function mapDBPartToUIMessagePart(
// output-available or output-error
return {
type: 'tool-result',
- toolCallId: part.tool_toolCallId!,
+ toolCallId: part.tool_toolCallId || '',
isError: part.tool_state === 'output-error',
result:
part.tool_state === 'output-error'