Skip to content

An AI-powered search engine with a generative UI

test: fix TypeScript types and formatting in chat tests

Yoshiki Miura21935f742404
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index a1465f3e..c424a834 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -1,10 +1,10 @@
import { cookies } from 'next/headers'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
-import { perfLog, perfTime } from '@/lib/utils/perf-logging'
-import { resetAllCounters } from '@/lib/utils/perf-tracking'
import { createChatStreamResponse } from '@/lib/streaming/create-chat-stream-response'
import { Model } from '@/lib/types/models'
+import { perfLog, perfTime } from '@/lib/utils/perf-logging'
+import { resetAllCounters } from '@/lib/utils/perf-tracking'
import { isProviderEnabled } from '@/lib/utils/registry'
export const maxDuration = 30
@@ -19,15 +19,17 @@ const DEFAULT_MODEL: Model = {
export async function POST(req: Request) {
const startTime = performance.now()
const abortSignal = req.signal
-
+
// Reset counters for new request
resetAllCounters()
try {
const body = await req.json()
const { message, chatId, trigger, messageId, isNewChat } = body
-
- perfLog(`API Route - Start: chatId=${chatId}, trigger=${trigger}, isNewChat=${isNewChat}`)
+
+ perfLog(
+ `API Route - Start: chatId=${chatId}, trigger=${trigger}, isNewChat=${isNewChat}`
+ )
// Handle different triggers
if (trigger === 'regenerate-assistant-message') {
@@ -48,7 +50,7 @@ export async function POST(req: Request) {
const referer = req.headers.get('referer')
const isSharePage = referer?.includes('/share/')
-
+
const authStart = performance.now()
const userId = await getCurrentUserId()
perfTime('Auth completed', authStart)
@@ -102,14 +104,14 @@ export async function POST(req: Request) {
abortSignal,
isNewChat
})
-
+
const totalTime = performance.now() - startTime
perfLog(`Total API route time: ${totalTime.toFixed(2)}ms`)
perfLog(`=== Summary ===`)
perfLog(`Chat Type: ${isNewChat ? 'NEW' : 'EXISTING'}`)
perfLog(`Total Time: ${totalTime.toFixed(2)}ms`)
perfLog(`================`)
-
+
return response
} catch (error) {
console.error('API route error:', error)
diff --git a/lib/actions/__tests__/chat.test.ts b/lib/actions/__tests__/chat.test.ts
index 0075cc4a..c315835d 100644
--- a/lib/actions/__tests__/chat.test.ts
+++ b/lib/actions/__tests__/chat.test.ts
@@ -1,4 +1,5 @@
import { revalidateTag } from 'next/cache'
+
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { generateChatTitle } from '@/lib/agents/title-generator'
@@ -56,7 +57,7 @@ describe('Chat Actions', () => {
})
it('should return empty array for unauthenticated user', async () => {
- vi.mocked(getCurrentUserId).mockResolvedValue(null)
+ vi.mocked(getCurrentUserId).mockResolvedValue(undefined)
const result = await getChats()
@@ -91,7 +92,7 @@ describe('Chat Actions', () => {
})
it('should return empty result for unauthenticated user', async () => {
- vi.mocked(getCurrentUserId).mockResolvedValue(null)
+ vi.mocked(getCurrentUserId).mockResolvedValue(undefined)
const result = await getChatsPage()
@@ -214,7 +215,6 @@ describe('Chat Actions', () => {
const message: UIMessage = {
id: 'msg-1',
role: 'user',
- content: 'Hello',
parts: [{ type: 'text', text: 'Hello' }]
}
const mockChat: Chat = {
@@ -229,7 +229,8 @@ describe('Chat Actions', () => {
chatId: mockChat.id,
role: 'user',
metadata: {},
- createdAt: new Date()
+ createdAt: new Date(),
+ updatedAt: null
}
vi.mocked(getCurrentUserId).mockResolvedValue(userId)
@@ -244,12 +245,11 @@ describe('Chat Actions', () => {
})
it('should throw error for unauthenticated user', async () => {
- vi.mocked(getCurrentUserId).mockResolvedValue(null)
+ vi.mocked(getCurrentUserId).mockResolvedValue(undefined)
const message: UIMessage = {
id: 'msg-1',
role: 'user',
- content: 'Hello',
parts: []
}
@@ -267,7 +267,6 @@ describe('Chat Actions', () => {
const message: UIMessage = {
id: 'msg-1',
role: 'user',
- content: 'Hello',
parts: [{ type: 'text', text: 'Hello' }]
}
const mockResult = {
@@ -283,7 +282,8 @@ describe('Chat Actions', () => {
chatId,
role: 'user' as const,
metadata: {},
- createdAt: new Date()
+ createdAt: new Date(),
+ updatedAt: null
}
}
@@ -305,11 +305,11 @@ describe('Chat Actions', () => {
chatId,
chatTitle: title,
userId,
- message: expect.objectContaining({
+ message: {
id: 'msg-1',
role: 'user',
- content: 'Hello'
- })
+ parts: [{ type: 'text', text: 'Hello' }]
+ }
})
expect(revalidateTag).toHaveBeenCalledWith(`chat-${chatId}`)
expect(revalidateTag).toHaveBeenCalledWith('chat')
@@ -323,7 +323,6 @@ describe('Chat Actions', () => {
const message: UIMessage = {
id: 'msg-1',
role: 'assistant',
- content: 'Response',
parts: []
}
const mockMessage: Message = {
@@ -331,7 +330,8 @@ describe('Chat Actions', () => {
chatId,
role: 'assistant',
metadata: {},
- createdAt: new Date()
+ createdAt: new Date(),
+ updatedAt: null
}
vi.mocked(dbActions.upsertMessage).mockResolvedValue(mockMessage)
@@ -351,16 +351,17 @@ describe('Chat Actions', () => {
const chatId = 'chat-123'
const userId = 'user-123'
const message: UIMessage = {
+ id: '', // Empty string will trigger ID generation
role: 'user',
- content: 'Hello',
parts: []
}
const mockMessage: Message = {
- id: expect.any(String),
+ id: 'generated-id',
chatId,
role: 'user',
metadata: {},
- createdAt: new Date()
+ createdAt: new Date(),
+ updatedAt: null
}
vi.mocked(dbActions.upsertMessage).mockResolvedValue(mockMessage)
@@ -392,7 +393,7 @@ describe('Chat Actions', () => {
})
it('should return error for unauthenticated user', async () => {
- vi.mocked(getCurrentUserId).mockResolvedValue(null)
+ vi.mocked(getCurrentUserId).mockResolvedValue(undefined)
const result = await deleteChat('chat-123')
@@ -514,7 +515,7 @@ describe('Chat Actions', () => {
})
it('should return null for unauthenticated user', async () => {
- vi.mocked(getCurrentUserId).mockResolvedValue(null)
+ vi.mocked(getCurrentUserId).mockResolvedValue(undefined)
const result = await shareChat('chat-123')
@@ -559,7 +560,6 @@ describe('Chat Actions', () => {
const message: UIMessage = {
id: 'msg-1',
role: 'user',
- content: 'Hello, how are you?',
parts: [{ type: 'text', text: 'Hello, how are you?' }]
}
const modelId = 'gpt-4'
@@ -599,7 +599,6 @@ describe('Chat Actions', () => {
const message: UIMessage = {
id: 'msg-1',
role: 'user',
- content: 'Hello',
parts: []
}
@@ -616,4 +615,4 @@ describe('Chat Actions', () => {
expect(dbActions.updateChatTitle).not.toHaveBeenCalled()
})
})
-})
\ No newline at end of file
+})
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
index 7d1feb35..ee3a5127 100644
--- a/lib/actions/chat.ts
+++ b/lib/actions/chat.ts
@@ -146,7 +146,6 @@ export async function createChatWithFirstMessage(
return result
}
-
/**
* Upsert a message to a chat
* @param userId - Required but not used for access check (assumes already authorized)
@@ -171,7 +170,6 @@ export async function upsertMessage(
return dbMessage
}
-
/**
* Delete a chat
*/
diff --git a/lib/db/actions.ts b/lib/db/actions.ts
index f7207e79..23bb3554 100644
--- a/lib/db/actions.ts
+++ b/lib/db/actions.ts
@@ -9,12 +9,12 @@ import {
mapUIMessagePartsToDBParts,
mapUIMessageToDBMessage
} from '@/lib/utils/message-mapping'
+import { perfLog, perfTime } from '@/lib/utils/perf-logging'
+import { incrementDbOperationCount } from '@/lib/utils/perf-tracking'
import type { Chat, Message } from './schema'
import { chats, generateId, messages, parts } from './schema'
import { db } from '.'
-import { perfLog, perfTime } from '@/lib/utils/perf-logging'
-import { incrementDbOperationCount } from '@/lib/utils/perf-tracking'
/**
* Create a new chat
@@ -375,11 +375,17 @@ export async function createChatWithFirstMessageTransaction({
// 2. Save message
const dbMessage = mapUIMessageToDBMessage({ ...message, chatId })
- const [savedMessage] = await tx.insert(messages).values(dbMessage).returning()
+ const [savedMessage] = await tx
+ .insert(messages)
+ .values(dbMessage)
+ .returning()
// 3. Save parts if they exist
if (message.parts && message.parts.length > 0) {
- const partsData = mapUIMessagePartsToDBParts(message.parts, savedMessage.id)
+ const partsData = mapUIMessagePartsToDBParts(
+ message.parts,
+ savedMessage.id
+ )
if (partsData.length > 0) {
await tx.insert(parts).values(partsData)
}
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 59fa69d9..49ae647a 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -14,13 +14,13 @@ import { isTracingEnabled } from '@/lib/utils/telemetry'
import { loadChat } from '../actions/chat'
import { generateChatTitle } from '../agents/title-generator'
-import { perfLog, perfTime } from '../utils/perf-logging'
import {
getMaxAllowedTokens,
shouldTruncateMessages,
truncateMessages
} from '../utils/context-window'
import { getTextFromParts } from '../utils/message-utils'
+import { perfLog, perfTime } from '../utils/perf-logging'
import { filterReasoningParts } from './helpers/filter-reasoning-parts'
import { handleStreamFinish } from './helpers/handle-stream-finish'
@@ -34,8 +34,16 @@ const DEFAULT_CHAT_TITLE = 'Untitled'
export async function createChatStreamResponse(
config: BaseStreamConfig
): Promise<Response> {
- const { message, model, chatId, userId, trigger, messageId, abortSignal, isNewChat } =
- config
+ const {
+ message,
+ model,
+ chatId,
+ userId,
+ trigger,
+ messageId,
+ abortSignal,
+ isNewChat
+ } = config
const modelId = `${model.providerId}:${model.id}`
// Verify that chatId is provided
diff --git a/lib/streaming/helpers/prepare-messages.ts b/lib/streaming/helpers/prepare-messages.ts
index d2f2d698..253ff624 100644
--- a/lib/streaming/helpers/prepare-messages.ts
+++ b/lib/streaming/helpers/prepare-messages.ts
@@ -87,7 +87,12 @@ export async function prepareMessages(
// Use createChatWithFirstMessage for atomic operation
const createStart = performance.now()
const { createChatWithFirstMessage } = await import('@/lib/actions/chat')
- await createChatWithFirstMessage(chatId, messageWithId, userId, DEFAULT_CHAT_TITLE)
+ await createChatWithFirstMessage(
+ chatId,
+ messageWithId,
+ userId,
+ DEFAULT_CHAT_TITLE
+ )
perfTime('createChatWithFirstMessage completed', createStart)
perfTime('prepareMessages - Total', startTime)
return [messageWithId]
diff --git a/lib/utils/perf-logging.ts b/lib/utils/perf-logging.ts
index 4fd83b02..c7c64708 100644
--- a/lib/utils/perf-logging.ts
+++ b/lib/utils/perf-logging.ts
@@ -10,6 +10,8 @@ export function perfLog(message: string) {
export function perfTime(label: string, startTime: number) {
if (isPerfLoggingEnabled) {
- console.log(`[PERF] ${label}: ${(performance.now() - startTime).toFixed(2)}ms`)
+ console.log(
+ `[PERF] ${label}: ${(performance.now() - startTime).toFixed(2)}ms`
+ )
}
-}
\ No newline at end of file
+}
diff --git a/lib/utils/perf-tracking.ts b/lib/utils/perf-tracking.ts
index a605db83..cf3e89e1 100644
--- a/lib/utils/perf-tracking.ts
+++ b/lib/utils/perf-tracking.ts
@@ -24,4 +24,4 @@ export function incrementDbOperationCount() {
export function resetAllCounters() {
authCallCount = 0
dbOperationCount = 0
-}
\ No newline at end of file
+}