📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Remove bullshit comments
Blue Mousea5cf78318411
diff --git a/backend/apps/cloud/src/ai/ai-chat.service.ts b/backend/apps/cloud/src/ai/ai-chat.service.tsindex 7a4056ec2..f2253bbbd 100644--- a/backend/apps/cloud/src/ai/ai-chat.service.ts+++ b/backend/apps/cloud/src/ai/ai-chat.service.ts@@ -23,8 +23,6 @@ export class AiChatService {userId: string | null,limit: number = 5,): Promise<AiChat[]> {- // Do not return stored chats to unauthenticated users.- // (Public project analytics may be viewable, but chats contain user prompts and context.)if (!userId) {return []}@@ -45,7 +43,6 @@ export class AiChatService {skip: number = 0,take: number = 20,): Promise<{ chats: AiChat[]; total: number }> {- // Do not return stored chats to unauthenticated users.if (!userId) {return { chats: [], total: 0 }}@@ -87,7 +84,6 @@ export class AiChatService {if (data.messages) {const previousMessages = chat.messageschat.messages = data.messages- // Update name if not manually set and we have a new first user messageif (!chat.name || chat.name === this.generateChatName(previousMessages)) {chat.name = this.generateChatName(data.messages)}@@ -105,11 +101,9 @@ export class AiChatService {}private generateChatName(messages: ChatMessage[]): string {- // Use the first user message as the chat nameconst firstUserMessage = messages.find(m => m.role === 'user')if (firstUserMessage) {const content = firstUserMessage.content.trim()- // Truncate to reasonable lengthreturn content.length > 100 ? content.slice(0, 97) + '...' : content}return 'New conversation'@@ -120,7 +114,6 @@ export class AiChatService {projectId: string,userId: string | null,): Promise<AiChat | null> {- // Explicitly require authentication for user-scoped access checks.if (!userId) return nullconst queryBuilder = this.aiChatRepositorydiff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.tsindex 08e5c92f0..d91ff94f0 100644--- a/backend/apps/cloud/src/ai/ai.controller.ts+++ b/backend/apps/cloud/src/ai/ai.controller.ts@@ -38,13 +38,12 @@ import {} from './dto/chat.dto'import { trackCustom } from '../common/analytics'-// Rate limit constants for AI endpoints-const AI_CHAT_RATE_LIMIT = 50 // requests per hour for authenticated users-const AI_CHAT_RATE_LIMIT_UNAUTH = 20 // requests per hour for unauthenticated users-const AI_CHAT_RATE_LIMIT_TIMEOUT = 3600 // 1 hour+const AI_CHAT_RATE_LIMIT = 50+const AI_CHAT_RATE_LIMIT_UNAUTH = 20+const AI_CHAT_RATE_LIMIT_TIMEOUT = 3600-const AI_READ_RATE_LIMIT = 200 // requests per hour for read operations-const AI_READ_RATE_LIMIT_UNAUTH = 50 // requests per hour for unauthenticated users+const AI_READ_RATE_LIMIT = 200+const AI_READ_RATE_LIMIT_UNAUTH = 50@ApiTags('AI')@Controller(['ai', 'v1/ai'])@@ -70,7 +69,6 @@ export class AiController {) {this.logger.log({ uid, pid }, 'POST /ai/:pid/chat')- // Apply rate limiting based on authentication statusconst ip = getIPFromHeaders(headers) || 'unknown'if (uid) {await checkRateLimit(@@ -88,7 +86,6 @@ export class AiController {)}- // Check if OpenRouter API key is configuredif (!process.env.OPENROUTER_API_KEY) {throw new HttpException('AI features are not configured. Please set OPENROUTER_API_KEY.',@@ -96,7 +93,6 @@ export class AiController {)}- // Get and validate project accessconst project = await this.projectService.getFullProject(pid)if (_isEmpty(project)) {@@ -105,7 +101,6 @@ export class AiController {this.projectService.allowedToView(project, uid)- // Check billing statusif (project.admin?.dashboardBlockReason) {throw new ForbiddenException('The account that owns this project is currently suspended due to a billing issue.',@@ -113,7 +108,6 @@ export class AiController {}try {- // Set up SSE headersres.setHeader('Content-Type', 'text/event-stream')res.setHeader('Cache-Control', 'no-cache')res.setHeader('Connection', 'keep-alive')@@ -125,7 +119,6 @@ export class AiController {clientClosed = true})- // Convert messages to CoreMessage format, filtering out empty messagesconst messages = chatDto.messages.filter(m => m.content && m.content.trim().length > 0).map(m => ({@@ -145,15 +138,12 @@ export class AiController {'Starting AI chat stream',)- // Get streaming response from AIconst result = await this.aiService.chat(project,messages,chatDto.timezone || 'UTC',)- // Stream the full response including tool calls and reasoning- // Wrap in try-catch to handle provider errors gracefullylet hasContent = falselet toolCallCount = 0let toolResultCount = 0@@ -182,7 +172,6 @@ export class AiController {} else if (part.type === 'tool-call') {hasContent = truetoolCallCount++- // Send tool call info for UI feedbackres.write(`data: ${JSON.stringify({type: 'tool-call',@@ -196,7 +185,6 @@ export class AiController {)} else if (part.type === 'tool-result') {toolResultCount++- // Send tool result for transparency (limit result size to avoid huge payloads)const resultPreview =typeof part.result === 'object'? JSON.stringify(part.result).slice(0, 1000)@@ -218,17 +206,14 @@ export class AiController {)} else if (part.type === 'reasoning') {hasContent = true- // Stream reasoning/thinking tokens if availableres.write(`data: ${JSON.stringify({ type: 'reasoning', content: part.textDelta })}\n\n`,)} else if (part.type === 'error') {- // Handle errors during streaming (emitted by AI SDK)this.logger.error({ error: part.error, pid, uid },'Error event during AI stream',)- // Don't end the stream on error events - the provider may continueres.write(`data: ${JSON.stringify({ type: 'error', content: 'A temporary error occurred, continuing...' })}\n\n`,)@@ -274,13 +259,11 @@ export class AiController {'AI stream completed - summary',)} catch (streamError) {- // Handle errors thrown during stream iteration (e.g., malformed provider responses)this.logger.error({ error: streamError, pid, uid },'Exception during AI stream iteration',)- // If we already have some content, send what we have with an error noticeif (hasContent) {res.write(`data: ${JSON.stringify({ type: 'error', content: 'The response was interrupted due to a provider error.' })}\n\n`,@@ -292,7 +275,6 @@ export class AiController {}}- // Send done eventres.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`)res.end()@@ -300,7 +282,6 @@ export class AiController {} catch (error) {this.logger.error({ error, pid, uid }, 'Error in AI chat')- // If headers not sent yet, throw errorif (!res.headersSent) {throw new HttpException('Failed to process AI request',@@ -308,7 +289,6 @@ export class AiController {)}- // If streaming already started, send error eventres.write(`data: ${JSON.stringify({ type: 'error', content: 'An error occurred while processing your request' })}\n\n`,)@@ -329,7 +309,6 @@ export class AiController {) {this.logger.log({ uid, pid }, 'GET /ai/:pid/chats')- // Apply rate limiting based on authentication statusconst ip = getIPFromHeaders(headers) || 'unknown'if (uid) {await checkRateLimit(@@ -387,7 +366,6 @@ export class AiController {) {this.logger.log({ uid, pid }, 'GET /ai/:pid/chats/all')- // Apply rate limiting based on authentication statusconst ip = getIPFromHeaders(headers) || 'unknown'if (uid) {await checkRateLimit(@@ -449,7 +427,6 @@ export class AiController {) {this.logger.log({ uid, pid, chatId }, 'GET /ai/:pid/chats/:chatId')- // Apply rate limiting based on authentication statusconst ip = getIPFromHeaders(headers) || 'unknown'if (uid) {await checkRateLimit(@@ -473,16 +450,10 @@ export class AiController {throw new NotFoundException('Project not found')}- // Check if user is allowed to view the project (includes public projects)this.projectService.allowedToView(project, uid)let chat- // For public projects:- // - unauthenticated users may access only anonymously-owned chats (userId IS NULL) by ID- // - authenticated users may access their own chats (plus shared anonymous chats)- // For private projects:- // - authenticated users may access only their own chatsif (project.public) {if (!uid) {chat = await this.aiChatService.verifyPublicChatAccess(chatId, pid)@@ -519,7 +490,6 @@ export class AiController {) {this.logger.log({ uid, pid }, 'POST /ai/:pid/chats')- // Apply rate limiting based on authentication statusconst ip = getIPFromHeaders(headers) || 'unknown'if (uid) {await checkRateLimit(@@ -579,7 +549,6 @@ export class AiController {) {this.logger.log({ uid, pid, chatId }, 'POST /ai/:pid/chats/:chatId')- // Apply rate limiting based on authentication statusconst ip = getIPFromHeaders(headers) || 'unknown'if (uid) {await checkRateLimit(@@ -605,7 +574,6 @@ export class AiController {this.projectService.allowedToView(project, uid)- // Updates require authentication and chat ownership.const existingChat = await this.aiChatService.verifyOwnerAccess(chatId,pid,@@ -647,7 +615,6 @@ export class AiController {) {this.logger.log({ uid, pid, chatId }, 'DELETE /ai/:pid/chats/:chatId')- // Apply rate limiting based on authentication statusconst ip = getIPFromHeaders(headers) || 'unknown'if (uid) {await checkRateLimit(@@ -673,7 +640,6 @@ export class AiController {this.projectService.allowedToView(project, uid)- // Deletes require authentication and chat ownership.const existingChat = await this.aiChatService.verifyOwnerAccess(chatId,pid,diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex 1032d6858..6da942c22 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -76,7 +76,6 @@ import FunnelsView from '../tabs/Funnels/FunnelsView'import GoalsView from '../tabs/Goals/GoalsView'import PerformanceView from '../tabs/Performance/PerformanceView'import ProfilesView from '../tabs/Profiles/ProfilesView'-// Revenue dashboard removed - revenue data is displayed in TrafficView, Pageflow, and Profile detailsimport SessionsView from '../tabs/Sessions/SessionsView'import TrafficView from '../tabs/Traffic/TrafficView'@@ -100,7 +99,6 @@ import {} from './ViewProject.helpers'interface ViewProjectContextType {- // Statestimezone: stringdateRange: Date[] | nullisLoading: boolean@@ -124,7 +122,6 @@ interface ViewProjectContextType {funnelsRefreshTrigger: numberprofilesRefreshTrigger: number- // Comparison stateisActiveCompare: booleandateRangeCompare: Date[] | nullactivePeriodCompare: string@@ -136,27 +133,22 @@ interface ViewProjectContextType {periodPairsCompare: { label: string; period: string }[]setPeriodPairsCompare: (value: { label: string; period: string }[]) => void- // Chart statechartType: keyof typeof chartTypessetChartTypeOnClick: (type: keyof typeof chartTypes) => voidrotateXAxis: boolean- // Zoom stateonMainChartZoom: (domain: [Date, Date] | null) => voidshouldEnableZoom: boolean- // Filter functionsgetFilterLink: (column: string, value: string | null) => LinkProps['to']getVersionFilterLink: (parent: string | null, version: string | null, panelType: 'br' | 'os') => string- // FunctionsupdatePeriod: (newPeriod: { period: Period; label?: string }) => voidupdateTimebucket: (newTimebucket: TimeBucket) => voidsetShowFiltersSearch: (value: boolean) => voidresetDateRange: () => voidrefreshStats: (isManual?: boolean) => Promise<void>- // RefsrefCalendar: React.RefObject<any>refCalendarCompare: React.RefObject<any>}@@ -185,7 +177,6 @@ const defaultViewProjectContext: ViewProjectContextType = {funnelsRefreshTrigger: 0,profilesRefreshTrigger: 0,- // Comparison state defaultsisActiveCompare: false,dateRangeCompare: null,activePeriodCompare: '',@@ -197,16 +188,13 @@ const defaultViewProjectContext: ViewProjectContextType = {periodPairsCompare: [],setPeriodPairsCompare: () => {},- // Chart state defaultschartType: chartTypes.line,setChartTypeOnClick: () => {},rotateXAxis: false,- // Zoom state defaultsonMainChartZoom: () => {},shouldEnableZoom: true,- // Filter functions defaultsgetFilterLink: () => ({ search: '' }) as LinkProps['to'],getVersionFilterLink: () => '',@@ -928,13 +916,11 @@ const ViewProjectContent = () => {updatePeriod(pair)})- // Mobile sidebar handlersconst openMobileSidebar = useCallback(() => setIsMobileSidebarOpen(true), [])const closeMobileSidebar = useCallback(() => setIsMobileSidebarOpen(false), [])const contextValue = useMemo(() => ({- // Statestimezone,dateRange,isLoading: authLoading,@@ -958,7 +944,6 @@ const ViewProjectContent = () => {funnelsRefreshTrigger,profilesRefreshTrigger,- // Comparison stateisActiveCompare,dateRangeCompare,activePeriodCompare,@@ -970,27 +955,22 @@ const ViewProjectContent = () => {periodPairsCompare,setPeriodPairsCompare,- // Chart statechartType,setChartTypeOnClick,rotateXAxis,- // Zoom stateonMainChartZoom,shouldEnableZoom,- // Filter functionsgetFilterLink,getVersionFilterLink,- // FunctionsupdatePeriod,updateTimebucket,setShowFiltersSearch,resetDateRange,refreshStats,- // RefsrefCalendar,refCalendarCompare,}),@@ -1044,7 +1024,6 @@ const ViewProjectContent = () => {],)- // Show password modal over a skeleton dashboard when password is requiredif (isPasswordRequired) {return (<>diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsxindex 1d2de0b72..53f1fd462 100644--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx@@ -67,7 +67,6 @@ const parseCharts = (content: string): { text: string; charts: any[] } => {const charts: any[] = []let text = content- // Find all occurrences of {"type":"chart" and extract full JSON objectsconst chartStartPattern = '{"type":"chart"'let searchIndex = 0@@ -75,7 +74,6 @@ const parseCharts = (content: string): { text: string; charts: any[] } => {const startIndex = text.indexOf(chartStartPattern, searchIndex)if (startIndex === -1) break- // Find the matching closing brace by counting braceslet braceCount = 0let endIndex = -1@@ -92,7 +90,6 @@ const parseCharts = (content: string): { text: string; charts: any[] } => {}if (endIndex === -1) {- // No matching brace found, skip this occurrencesearchIndex = startIndex + chartStartPattern.lengthcontinue}@@ -103,13 +100,11 @@ const parseCharts = (content: string): { text: string; charts: any[] } => {const chartData = JSON.parse(jsonString)if (chartData.type === 'chart') {charts.push(chartData)- // Remove the chart JSON from texttext = text.substring(0, startIndex) + text.substring(endIndex + 1)- // Don't advance searchIndex since we removed contentcontinue}} catch {- // Not valid JSON, skip this occurrence+ // Invalid JSON, skip}searchIndex = startIndex + chartStartPattern.length