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!

fix lint

Blue Mouse4b59806a0b15
diff --git a/backend/apps/cloud/src/ai/ai-chat.service.ts b/backend/apps/cloud/src/ai/ai-chat.service.ts
index c6aeaa05c..37a29e4c1 100644
--- a/backend/apps/cloud/src/ai/ai-chat.service.ts
+++ b/backend/apps/cloud/src/ai/ai-chat.service.ts
@@ -131,4 +131,20 @@ export class AiChatService {
return queryBuilder.getOne()
}
+
+ /**
+ * Verify that a chat belongs to a project (without checking user ownership).
+ * Used for shared chat links where anyone who can view the project can access the chat.
+ */
+ async verifyProjectAccess(
+ chatId: string,
+ projectId: string,
+ ): Promise<AiChat | null> {
+ return this.aiChatRepository.findOne({
+ where: {
+ id: chatId,
+ project: { id: projectId },
+ },
+ })
+ }
}
diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.ts
index 299cba99b..368fa76a7 100644
--- a/backend/apps/cloud/src/ai/ai.controller.ts
+++ b/backend/apps/cloud/src/ai/ai.controller.ts
@@ -115,10 +115,19 @@ export class AiController {
// 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
+ let textDeltaCount = 0
try {
for await (const part of result.fullStream) {
+ this.logger.debug(
+ { pid, partType: part.type },
+ 'AI stream part received',
+ )
+
if (part.type === 'text-delta') {
hasContent = true
+ textDeltaCount++
res.write(
`data: ${JSON.stringify({ type: 'text', content: part.textDelta })}\n\n`,
)
@@ -128,6 +137,7 @@ export class AiController {
)
} else if (part.type === 'tool-call') {
hasContent = true
+ toolCallCount++
// Send tool call info for UI feedback
res.write(
`data: ${JSON.stringify({
@@ -141,6 +151,7 @@ export class AiController {
'AI tool call',
)
} 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'
@@ -177,8 +188,38 @@ export class AiController {
res.write(
`data: ${JSON.stringify({ type: 'error', content: 'A temporary error occurred, continuing...' })}\n\n`,
)
+ } else if (part.type === 'finish') {
+ this.logger.log(
+ {
+ pid,
+ finishReason: (part as any).finishReason,
+ usage: (part as any).usage,
+ },
+ 'AI stream finish event',
+ )
+ } else if (part.type === 'step-finish') {
+ this.logger.log(
+ {
+ pid,
+ stepType: (part as any).stepType,
+ finishReason: (part as any).finishReason,
+ isContinued: (part as any).isContinued,
+ },
+ 'AI stream step-finish event',
+ )
}
}
+
+ this.logger.log(
+ {
+ pid,
+ toolCallCount,
+ toolResultCount,
+ textDeltaCount,
+ hasContent,
+ },
+ 'AI stream completed - summary',
+ )
} catch (streamError) {
// Handle errors thrown during stream iteration (e.g., malformed provider responses)
this.logger.error(
@@ -316,9 +357,12 @@ 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)
- const chat = await this.aiChatService.verifyAccess(chatId, pid, uid)
+ // For shared chat links, only verify the chat belongs to the project
+ // Users who can view the project can access any chat in that project
+ const chat = await this.aiChatService.verifyProjectAccess(chatId, pid)
if (!chat) {
throw new NotFoundException('Chat not found')
diff --git a/backend/apps/cloud/src/ai/ai.service.ts b/backend/apps/cloud/src/ai/ai.service.ts
index b01a5d3e5..75a862595 100644
--- a/backend/apps/cloud/src/ai/ai.service.ts
+++ b/backend/apps/cloud/src/ai/ai.service.ts
@@ -170,12 +170,20 @@ Guidelines:
6. Round percentages and large numbers for readability
7. Explain trends and provide actionable insights when relevant
8. If no data is available for the requested period, say so clearly instead of making up data
+9. If user asks technical questions, like how to set up a tracking script, or use the platform, refer them to the documentation at https://docs.swetrix.com/
To include a chart in your response, use this exact JSON format on its own line:
+
+For time-series charts (line, bar, area):
{"type":"chart","chartType":"line","title":"Chart Title","data":{"x":["2024-01-01","2024-01-02"],"pageviews":[100,150],"visitors":[80,120]}}
-Supported chart types: "line", "bar", "area"
-The data object should have "x" for x-axis labels and named arrays for each series.`
+For pie/donut charts (showing proportions):
+{"type":"chart","chartType":"pie","title":"Device Distribution","data":{"labels":["Desktop","Mobile","Tablet"],"values":[650,280,70]}}
+{"type":"chart","chartType":"donut","title":"Traffic Sources","data":{"labels":["Organic","Direct","Referral"],"values":[450,300,150]}}
+
+Supported chart types: "line", "bar", "area", "pie", "donut"
+- For line/bar/area: data object should have "x" for x-axis labels and named arrays for each series
+- For pie/donut: data object should have "labels" array and "values" array (use raw numbers, not percentages)`
}
private buildTools(project: Project, timezone: string) {
@@ -183,8 +191,10 @@ The data object should have "x" for x-axis labels and named arrays for each seri
getProjectInfo: tool({
description:
'Get basic information about the current project including name, settings, and available funnels/goals',
- parameters: z.object({}),
- execute: async () => {
+ parameters: z.object({
+ // Empty object schema - no parameters needed
+ }),
+ execute: async (_params: Record<string, never>) => {
this.logger.log({ pid: project.id }, 'Tool: getProjectInfo called')
try {
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index d7f967d8f..36cdd9a0f 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -1810,12 +1810,12 @@ export const getGSCKeywords = (
})
// AI Chat API with SSE streaming
-export interface AIChatMessage {
+interface AIChatMessage {
role: 'user' | 'assistant'
content: string
}
-export interface AIStreamCallbacks {
+interface AIStreamCallbacks {
onText: (chunk: string) => void
onToolCall?: (toolName: string, args: unknown) => void
onToolResult?: (toolName: string, result: unknown) => void
@@ -1913,7 +1913,7 @@ export interface AIChatSummary {
updated: string
}
-export interface AIChat extends AIChatSummary {
+interface AIChat extends AIChatSummary {
messages: AIChatMessage[]
}
diff --git a/web/app/pages/Project/AskAI/AIChart.tsx b/web/app/pages/Project/AskAI/AIChart.tsx
index 494f17b23..14e33d2cb 100644
--- a/web/app/pages/Project/AskAI/AIChart.tsx
+++ b/web/app/pages/Project/AskAI/AIChart.tsx
@@ -1,11 +1,10 @@
import type { ChartOptions } from 'billboard.js'
import { line, area, bar, spline, pie, donut } from 'billboard.js'
import dayjs from 'dayjs'
+import _filter from 'lodash/filter'
import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _map from 'lodash/map'
-import _size from 'lodash/size'
-import _filter from 'lodash/filter'
import React, { useMemo } from 'react'
import BillboardChart from '~/ui/BillboardChart'
@@ -320,7 +319,7 @@ const AIChart: React.FC<AIChartProps> = ({ chart }) => {
return (
<div className='rounded-lg border border-gray-200 bg-white p-3 dark:border-slate-600 dark:bg-slate-800'>
- {chart.title && <h4 className='mb-2 text-sm font-medium text-gray-700 dark:text-gray-300'>{chart.title}</h4>}
+ {chart.title ? <h4 className='mb-2 text-sm font-medium text-gray-700 dark:text-gray-300'>{chart.title}</h4> : null}
<div className={isPieDonut ? 'h-[280px] w-full' : 'h-[200px] w-full'}>
<BillboardChart options={chartOptions} className='h-full w-full' />
</div>