An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Fix conversationTurn double-count (#873)
Yoshiki Miurac17e1d09d9ab
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex 2e500d70..918aef0c 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -8,6 +8,7 @@ import {trackChatEvent} from '@/lib/analytics'import { getCurrentUserId } from '@/lib/auth/get-current-user'+import { generateId } from '@/lib/db/schema'import { checkAndEnforceAdaptiveLimit } from '@/lib/rate-limit/adaptive-limit'import { checkAndEnforceOverallChatLimit } from '@/lib/rate-limit/chat-limits'import { checkAndEnforceGuestLimit } from '@/lib/rate-limit/guest-limit'@@ -39,6 +40,11 @@ export async function POST(req: Request) {const body = await req.json()const { message, messages, chatId, trigger, messageId, isNewChat } = body+ // Normalize the message id up front so persistence and analytics agree on it.+ if (message && !message.id) {+ message.id = generateId()+ }+perfLog(`API Route - Start: chatId=${chatId}, trigger=${trigger}, isNewChat=${isNewChat}`)@@ -191,8 +197,10 @@ export async function POST(req: Request) {if (!isNewChat && !isGuest) {const chat = await loadChat(chatId, userId)if (chat?.messages) {- // Add 1 to account for the current message being sent- conversationTurn = calculateConversationTurn(chat.messages) + 1+ conversationTurn = calculateConversationTurn(+ chat.messages,+ message?.id+ )}}diff --git a/lib/analytics/__tests__/utils.test.ts b/lib/analytics/__tests__/utils.test.tsindex 134d0c21..ce8c11d8 100644--- a/lib/analytics/__tests__/utils.test.ts+++ b/lib/analytics/__tests__/utils.test.ts@@ -1,6 +1,17 @@+import type { UIMessage } from 'ai'import { describe, expect, it } from 'vitest'-import { deriveQueryShape } from '@/lib/analytics/utils'+import {+ calculateConversationTurn,+ deriveQueryShape+} from '@/lib/analytics/utils'++const userMsg = (id: string): UIMessage => ({ id, role: 'user', parts: [] })+const assistantMsg = (id: string): UIMessage => ({+ id,+ role: 'assistant',+ parts: []+})describe('deriveQueryShape', () => {it('buckets query length and never returns raw text', () => {@@ -22,3 +33,26 @@ describe('deriveQueryShape', () => {expect(deriveQueryShape('12345').lang).toBe('other')})})++describe('calculateConversationTurn', () => {+ const history = [userMsg('u1'), assistantMsg('a1')]++ it('counts the current message once when history excludes it (stale cache)', () => {+ expect(calculateConversationTurn(history, 'u2')).toBe(2)+ })++ it('counts the current message once when history already includes it', () => {+ const fresh = [...history, userMsg('u2')]+ expect(calculateConversationTurn(fresh, 'u2')).toBe(2)+ })++ it('returns at least 1', () => {+ expect(calculateConversationTurn([], 'u1')).toBe(1)+ expect(calculateConversationTurn([])).toBe(1)+ })++ it('counts existing user messages without a current id (regenerate)', () => {+ const fresh = [...history, userMsg('u2')]+ expect(calculateConversationTurn(fresh)).toBe(2)+ })+})diff --git a/lib/analytics/utils.ts b/lib/analytics/utils.tsindex 26c34eb0..cb397777 100644--- a/lib/analytics/utils.ts+++ b/lib/analytics/utils.ts@@ -32,25 +32,22 @@ export function deriveQueryShape(text: string): QueryShape {}/**- * Calculate the conversation turn number from message history+ * Calculate the conversation turn number (1-indexed) for the message being sent.*- * The turn number represents how many user messages have been sent,- * which indicates the follow-up count (1 = initial message, 2+ = follow-ups)+ * Counts distinct user messages by id. `currentMessageId` is included so the+ * result is stable whether or not the history (which may be cached) already+ * contains the message being sent.*- * @param messages - Array of UI messages from the conversation- * @returns Turn number (1-indexed)- *- * @example- * ```typescript- * const messages = [- * { role: 'user', parts: [...] },- * { role: 'assistant', parts: [...] },- * { role: 'user', parts: [...] }- * ]- * calculateConversationTurn(messages) // Returns 2- * ```+ * @param messages - User/assistant messages from the conversation+ * @param currentMessageId - Id of the message being sent, if any*/-export function calculateConversationTurn(messages: UIMessage[]): number {- const userMessageCount = messages.filter(msg => msg.role === 'user').length- return Math.max(1, userMessageCount)+export function calculateConversationTurn(+ messages: UIMessage[],+ currentMessageId?: string+): number {+ const userIds = new Set(+ messages.filter(msg => msg.role === 'user').map(msg => msg.id)+ )+ if (currentMessageId) userIds.add(currentMessageId)+ return Math.max(1, userIds.size)}