An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Track chat_message_sent for guests (#874)
Yoshiki Miurac312f894e8ca
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex 918aef0c..a52fb041 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -39,6 +39,7 @@ export async function POST(req: Request) {try {const body = await req.json()const { message, messages, chatId, trigger, messageId, isNewChat } = body+ const analyticsId: unknown = body.analyticsId// Normalize the message id up front so persistence and analytics agree on it.if (message && !message.id) {@@ -191,40 +192,48 @@ export async function POST(req: Request) {// Calculate conversation turn by loading chat history;(async () => {try {- let conversationTurn = 1 // Default for new chats+ // Attribute to the authenticated user id, or the client-provided+ // PostHog distinct id for guests (so it merges with their client events).+ const distinctId =+ userId ?? (typeof analyticsId === 'string' ? analyticsId : undefined)+ if (!distinctId) return- // For existing chats, load history and calculate turn number- if (!isNewChat && !isGuest) {- const chat = await loadChat(chatId, userId)- if (chat?.messages) {- conversationTurn = calculateConversationTurn(- chat.messages,- message?.id- )+ let conversationTurn = 1 // Default for new chats+ if (!isNewChat) {+ if (!isGuest && userId) {+ const chat = await loadChat(chatId, userId)+ if (chat?.messages) {+ conversationTurn = calculateConversationTurn(+ chat.messages,+ message?.id+ )+ }+ } else if (isGuest && Array.isArray(messages)) {+ conversationTurn = calculateConversationTurn(messages, message?.id)}}- if (!isGuest && userId) {- const resolvedTrigger =- (trigger as 'submit-message' | 'regenerate-message') ??- 'submit-message'- const queryShape =- resolvedTrigger === 'submit-message' && message?.parts- ? deriveQueryShape(getTextFromParts(message.parts))- : undefined-- await trackChatEvent({- searchMode,- conversationTurn,- isNewChat: isNewChat ?? false,- trigger: resolvedTrigger,- chatId,- userId,- providerId: selectedModel.providerId,- modelId: selectedModel.id,- queryShape- })- }+ const resolvedTrigger =+ (trigger as 'submit-message' | 'regenerate-message') ??+ 'submit-message'+ const queryShape =+ resolvedTrigger === 'submit-message' && message?.parts+ ? deriveQueryShape(getTextFromParts(message.parts))+ : undefined++ await trackChatEvent({+ searchMode,+ conversationTurn,+ isNewChat: isNewChat ?? false,+ trigger: resolvedTrigger,+ chatId,+ distinctId,+ isGuest,+ userId: userId ?? undefined,+ providerId: selectedModel.providerId,+ modelId: selectedModel.id,+ queryShape+ })} catch (error) {// Log error but don't throw - analytics should never break the appconsole.error('Analytics tracking failed:', error)diff --git a/components/chat.tsx b/components/chat.tsxindex 0d687406..e20cdac0 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -8,7 +8,7 @@ import { DefaultChatTransport } from 'ai'import { toast } from 'sonner'import { summarizeGenui } from '@/lib/analytics/genui-summary'-import { captureClient } from '@/lib/analytics/posthog-client'+import { captureClient, getDistinctId } from '@/lib/analytics/posthog-client'import { ChatProvider } from '@/lib/contexts/chat-context'import { generateId } from '@/lib/db/schema'import {@@ -149,6 +149,7 @@ export function Chat({trigger, // Use AI SDK's default trigger value directlychatId: chatId,messageId,+ analyticsId: getDistinctId(),...(isGuest ? { messages } : {}),message:trigger === 'regenerate-message' &&diff --git a/components/posthog-provider.tsx b/components/posthog-provider.tsxindex aadf3ecb..df19abd3 100644--- a/components/posthog-provider.tsx+++ b/components/posthog-provider.tsx@@ -7,6 +7,7 @@ import {captureClient,identify,initPostHog,+ isIdentified,reset} from '@/lib/analytics/posthog-client'@@ -24,7 +25,9 @@ export function PostHogProvider({useEffect(() => {if (userId) {identify(userId)- } else {+ } else if (isIdentified()) {+ // Only reset on an actual logout, not on every guest mount, so a guest+ // keeps a stable distinct id (persisted in localStorage) across loads.reset()}}, [userId])diff --git a/lib/analytics/posthog-client.ts b/lib/analytics/posthog-client.tsindex f028d3fa..40506087 100644--- a/lib/analytics/posthog-client.ts+++ b/lib/analytics/posthog-client.ts@@ -30,11 +30,26 @@ export function initPostHog(): void {initialized = true}+export function getDistinctId(): string | undefined {+ if (!clientKey()) return undefined+ // Self-initialize so the id is available regardless of effect ordering+ // (a child auto-send effect can run before the provider's init effect).+ initPostHog()+ return posthog.get_distinct_id?.()+}+export function identify(distinctId: string): void {if (!clientKey()) returnposthog.identify(distinctId)}+/** Whether PostHog currently holds an identified (logged-in) distinct id. */+export function isIdentified(): boolean {+ if (!clientKey()) return false+ initPostHog()+ return posthog.get_property?.('$user_state') === 'identified'+}+export function reset(): void {if (!clientKey()) returnposthog.reset()@@ -45,6 +60,7 @@ export function captureClient(properties?: Record<string, unknown>): void {if (!clientKey()) return+ initPostHog()posthog.capture(event, properties)}diff --git a/lib/analytics/track-chat-event.ts b/lib/analytics/track-chat-event.tsindex 77f586da..7877576b 100644--- a/lib/analytics/track-chat-event.ts+++ b/lib/analytics/track-chat-event.ts@@ -8,14 +8,13 @@ import type { ChatEventData } from './types'* only the derived query shape is included.*/export async function trackChatEvent(data: ChatEventData): Promise<void> {- const { userId, queryShape, ...rest } = data+ const { distinctId, queryShape, ...rest } = dataawait capture({event: 'chat_message_sent',- distinctId: userId,+ distinctId,properties: {...rest,- userId,...queryShape}})diff --git a/lib/analytics/types.ts b/lib/analytics/types.tsindex 4328d9bb..af64f649 100644--- a/lib/analytics/types.ts+++ b/lib/analytics/types.ts@@ -33,8 +33,12 @@ export interface ChatEventData {trigger: 'submit-message' | 'regenerate-message'/** Chat session ID (CUID2 - safe for tracking) */chatId: string- /** User ID (Supabase UUID - pseudonymized identifier) */- userId: string+ /** PostHog distinct id to attribute the event to (user id or guest id) */+ distinctId: string+ /** Whether the sender is a guest (unauthenticated) */+ isGuest: boolean+ /** User ID (Supabase UUID) - present only for authenticated users */+ userId?: string/** Provider identifier used for the chat */providerId: string/** Model identifier used for the chat */