Skip to content

📈 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!

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.ts
index 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.messages
chat.messages = data.messages
- // Update name if not manually set and we have a new first user message
if (!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 name
const firstUserMessage = messages.find(m => m.role === 'user')
if (firstUserMessage) {
const content = firstUserMessage.content.trim()
- // Truncate to reasonable length
return 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 null
const queryBuilder = this.aiChatRepository
diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.ts
index 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 status
const ip = getIPFromHeaders(headers) || 'unknown'
if (uid) {
await checkRateLimit(
@@ -88,7 +86,6 @@ export class AiController {
)
}
- // Check if OpenRouter API key is configured
if (!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 access
const project = await this.projectService.getFullProject(pid)
if (_isEmpty(project)) {
@@ -105,7 +101,6 @@ export class AiController {
this.projectService.allowedToView(project, uid)
- // Check billing status
if (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 headers
res.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 messages
const 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 AI
const 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 gracefully
let hasContent = false
let toolCallCount = 0
let toolResultCount = 0
@@ -182,7 +172,6 @@ export class AiController {
} else if (part.type === 'tool-call') {
hasContent = true
toolCallCount++
- // Send tool call info for UI feedback
res.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 available
res.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 continue
res.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 notice
if (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 event
res.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 error
if (!res.headersSent) {
throw new HttpException(
'Failed to process AI request',
@@ -308,7 +289,6 @@ export class AiController {
)
}
- // If streaming already started, send error event
res.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 status
const 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 status
const 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 status
const 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 chats
if (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 status
const 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 status
const 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 status
const 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.tsx
index 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 details
import SessionsView from '../tabs/Sessions/SessionsView'
import TrafficView from '../tabs/Traffic/TrafficView'
@@ -100,7 +99,6 @@ import {
} from './ViewProject.helpers'
interface ViewProjectContextType {
- // States
timezone: string
dateRange: Date[] | null
isLoading: boolean
@@ -124,7 +122,6 @@ interface ViewProjectContextType {
funnelsRefreshTrigger: number
profilesRefreshTrigger: number
- // Comparison state
isActiveCompare: boolean
dateRangeCompare: Date[] | null
activePeriodCompare: string
@@ -136,27 +133,22 @@ interface ViewProjectContextType {
periodPairsCompare: { label: string; period: string }[]
setPeriodPairsCompare: (value: { label: string; period: string }[]) => void
- // Chart state
chartType: keyof typeof chartTypes
setChartTypeOnClick: (type: keyof typeof chartTypes) => void
rotateXAxis: boolean
- // Zoom state
onMainChartZoom: (domain: [Date, Date] | null) => void
shouldEnableZoom: boolean
- // Filter functions
getFilterLink: (column: string, value: string | null) => LinkProps['to']
getVersionFilterLink: (parent: string | null, version: string | null, panelType: 'br' | 'os') => string
- // Functions
updatePeriod: (newPeriod: { period: Period; label?: string }) => void
updateTimebucket: (newTimebucket: TimeBucket) => void
setShowFiltersSearch: (value: boolean) => void
resetDateRange: () => void
refreshStats: (isManual?: boolean) => Promise<void>
- // Refs
refCalendar: React.RefObject<any>
refCalendarCompare: React.RefObject<any>
}
@@ -185,7 +177,6 @@ const defaultViewProjectContext: ViewProjectContextType = {
funnelsRefreshTrigger: 0,
profilesRefreshTrigger: 0,
- // Comparison state defaults
isActiveCompare: false,
dateRangeCompare: null,
activePeriodCompare: '',
@@ -197,16 +188,13 @@ const defaultViewProjectContext: ViewProjectContextType = {
periodPairsCompare: [],
setPeriodPairsCompare: () => {},
- // Chart state defaults
chartType: chartTypes.line,
setChartTypeOnClick: () => {},
rotateXAxis: false,
- // Zoom state defaults
onMainChartZoom: () => {},
shouldEnableZoom: true,
- // Filter functions defaults
getFilterLink: () => ({ search: '' }) as LinkProps['to'],
getVersionFilterLink: () => '',
@@ -928,13 +916,11 @@ const ViewProjectContent = () => {
updatePeriod(pair)
})
- // Mobile sidebar handlers
const openMobileSidebar = useCallback(() => setIsMobileSidebarOpen(true), [])
const closeMobileSidebar = useCallback(() => setIsMobileSidebarOpen(false), [])
const contextValue = useMemo(
() => ({
- // States
timezone,
dateRange,
isLoading: authLoading,
@@ -958,7 +944,6 @@ const ViewProjectContent = () => {
funnelsRefreshTrigger,
profilesRefreshTrigger,
- // Comparison state
isActiveCompare,
dateRangeCompare,
activePeriodCompare,
@@ -970,27 +955,22 @@ const ViewProjectContent = () => {
periodPairsCompare,
setPeriodPairsCompare,
- // Chart state
chartType,
setChartTypeOnClick,
rotateXAxis,
- // Zoom state
onMainChartZoom,
shouldEnableZoom,
- // Filter functions
getFilterLink,
getVersionFilterLink,
- // Functions
updatePeriod,
updateTimebucket,
setShowFiltersSearch,
resetDateRange,
refreshStats,
- // Refs
refCalendar,
refCalendarCompare,
}),
@@ -1044,7 +1024,6 @@ const ViewProjectContent = () => {
],
)
- // Show password modal over a skeleton dashboard when password is required
if (isPasswordRequired) {
return (
<>
diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
index 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 objects
const 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 braces
let braceCount = 0
let endIndex = -1
@@ -92,7 +90,6 @@ const parseCharts = (content: string): { text: string; charts: any[] } => {
}
if (endIndex === -1) {
- // No matching brace found, skip this occurrence
searchIndex = startIndex + chartStartPattern.length
continue
}
@@ -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 text
text = text.substring(0, startIndex) + text.substring(endIndex + 1)
- // Don't advance searchIndex since we removed content
continue
}
} catch {
- // Not valid JSON, skip this occurrence
+ // Invalid JSON, skip
}
searchIndex = startIndex + chartStartPattern.length