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!

'How I got this' section

Blue Mouse82655506f9b8
diff --git a/backend/apps/cloud/src/ai/dto/chat.dto.ts b/backend/apps/cloud/src/ai/dto/chat.dto.ts
index ccbcb3162..827d6b23b 100644
--- a/backend/apps/cloud/src/ai/dto/chat.dto.ts
+++ b/backend/apps/cloud/src/ai/dto/chat.dto.ts
@@ -17,6 +17,31 @@ import { Type, Transform } from 'class-transformer'
const MAX_MESSAGES_PER_CHAT = 50
const MAX_MESSAGE_LENGTH = 5000
const MAX_CHAT_NAME_LENGTH = 200
+const MAX_TOOL_CALLS_PER_MESSAGE = 50
+const MAX_TOOL_NAME_LENGTH = 100
+
+class ChatMessageToolCallDto {
+ @ApiProperty({ description: 'Tool name that was invoked' })
+ @IsNotEmpty()
+ @IsString()
+ @MaxLength(MAX_TOOL_NAME_LENGTH)
+ toolName: string
+
+ @ApiProperty({
+ description: 'Arguments the tool was called with (arbitrary JSON)',
+ })
+ @IsOptional()
+ args?: unknown
+
+ @ApiProperty({
+ required: false,
+ description: 'ISO timestamp when the tool call was issued',
+ })
+ @IsOptional()
+ @IsString()
+ @MaxLength(40)
+ timestamp?: string
+}
class ChatMessageDto {
@ApiProperty({
@@ -46,6 +71,19 @@ class ChatMessageDto {
@IsString({ each: true })
@MaxLength(140, { each: true })
followUps?: string[]
+
+ @ApiProperty({
+ required: false,
+ type: [ChatMessageToolCallDto],
+ description:
+ 'Tool calls performed while producing this assistant message (used for the "How I got this" breakdown)',
+ })
+ @IsOptional()
+ @IsArray()
+ @ArrayMaxSize(MAX_TOOL_CALLS_PER_MESSAGE)
+ @ValidateNested({ each: true })
+ @Type(() => ChatMessageToolCallDto)
+ toolCalls?: ChatMessageToolCallDto[]
}
export class ChatDto {
diff --git a/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts b/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
index 9a4a7ef80..d91ba8e08 100644
--- a/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
+++ b/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
@@ -11,10 +11,17 @@ import { ApiProperty } from '@nestjs/swagger'
import { Project } from '../../project/entity/project.entity'
import { User } from '../../user/entities/user.entity'
+export interface ChatMessageToolCall {
+ toolName: string
+ args?: unknown
+ timestamp?: string
+}
+
export interface ChatMessage {
role: 'user' | 'assistant'
content: string
followUps?: string[]
+ toolCalls?: ChatMessageToolCall[]
}
@Entity('ai_chat')
diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
index 939885f5f..de7495a8d 100644
--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
@@ -52,6 +52,7 @@ import Tooltip from '~/ui/Tooltip'
import { cn } from '~/utils/generic'
import AIChart from './AIChart'
+import { formatToolCallSummary, ToolCallSummary } from './toolFormatters'
interface MessagePart {
type: 'text' | 'toolCall'
@@ -67,12 +68,19 @@ interface AIChatSummary {
updated: string
}
+interface MessageToolCall {
+ toolName: string
+ args: unknown
+ completed?: boolean
+ timestamp?: string
+}
+
interface Message {
id: string
role: 'user' | 'assistant'
content: string
reasoning?: string
- toolCalls?: Array<{ toolName: string; args: unknown; completed?: boolean }>
+ toolCalls?: MessageToolCall[]
parts?: MessagePart[]
followUps?: string[]
}
@@ -511,6 +519,148 @@ const MessageContent = ({
)
}
+const formatRelativeTimestamp = (timestamp: string, t: any): string | null => {
+ const date = new Date(timestamp)
+ if (Number.isNaN(date.getTime())) return null
+ const diffMs = Date.now() - date.getTime()
+ const diffMins = Math.floor(diffMs / 60000)
+ const diffHours = Math.floor(diffMs / 3600000)
+ const diffDays = Math.floor(diffMs / 86400000)
+
+ if (diffMins < 1) return t('project.askAi.timeFormat.justNow')
+ if (diffMins < 60)
+ return t('project.askAi.timeFormat.minutes', { count: diffMins })
+ if (diffHours < 24)
+ return t('project.askAi.timeFormat.hours', { count: diffHours })
+ if (diffDays < 7)
+ return t('project.askAi.timeFormat.days', { count: diffDays })
+ return date.toLocaleDateString(undefined, {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ })
+}
+
+const ToolCallSummaryDrawer = ({
+ toolCalls,
+}: {
+ toolCalls: MessageToolCall[]
+}) => {
+ const { t } = useTranslation('common')
+ const [isExpanded, setIsExpanded] = useState(false)
+
+ const summaries = useMemo<ToolCallSummary[]>(
+ () => toolCalls.map((tc) => formatToolCallSummary(tc.toolName, tc.args, t)),
+ [toolCalls, t],
+ )
+
+ if (toolCalls.length === 0) return null
+
+ const buttonLabel = t('project.askAi.howIGotThis', {
+ count: toolCalls.length,
+ defaultValue:
+ toolCalls.length === 1
+ ? 'How I got this · 1 step'
+ : `How I got this · ${toolCalls.length} steps`,
+ })
+
+ return (
+ <div className='mt-3'>
+ <button
+ type='button'
+ onClick={() => setIsExpanded((v) => !v)}
+ aria-expanded={isExpanded}
+ className='inline-flex items-center gap-1.5 rounded-md text-xs font-medium text-gray-500 transition-colors hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200'
+ >
+ <span>{buttonLabel}</span>
+ {isExpanded ? (
+ <CaretDownIcon className='h-3 w-3' />
+ ) : (
+ <CaretRightIcon className='h-3 w-3' />
+ )}
+ </button>
+
+ {isExpanded ? (
+ <div className='mt-2 overflow-hidden rounded-lg border border-gray-200 bg-white dark:border-slate-800 dark:bg-slate-900/40'>
+ <ol className='divide-y divide-gray-100 dark:divide-slate-800/80'>
+ {_map(summaries, (summary, idx) => {
+ const { label: toolLabel, icon: Icon } = getToolInfo(
+ summary.toolName,
+ t,
+ )
+ const timestamp = toolCalls[idx]?.timestamp
+ const relative = timestamp
+ ? formatRelativeTimestamp(timestamp, t)
+ : null
+ return (
+ <li key={idx} className='px-3 py-2.5'>
+ <div className='flex items-start gap-2.5'>
+ <span className='mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-gray-100 text-[10px] font-semibold text-gray-600 dark:bg-slate-800 dark:text-gray-300'>
+ {idx + 1}
+ </span>
+ <div className='min-w-0 flex-1'>
+ <div className='flex flex-wrap items-center gap-1.5'>
+ <Icon className='h-3.5 w-3.5 text-gray-500 dark:text-gray-400' />
+ <span className='text-xs font-medium text-gray-800 dark:text-gray-100'>
+ {toolLabel}
+ </span>
+ {relative ? (
+ <span className='text-[11px] text-gray-400 dark:text-gray-500'>
+ · {relative}
+ </span>
+ ) : null}
+ </div>
+ {summary.params.length === 0 ? (
+ <p className='mt-1 text-xs text-gray-400 italic dark:text-gray-500'>
+ {t('project.askAi.noParameters')}
+ </p>
+ ) : (
+ <dl className='mt-1.5 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs'>
+ {_map(summary.params, (param, pIdx) => (
+ <React.Fragment key={pIdx}>
+ <dt className='text-gray-500 dark:text-gray-400'>
+ {t(param.labelKey, {
+ defaultValue: param.fallbackLabel,
+ })}
+ </dt>
+ <dd className='min-w-0 text-gray-800 dark:text-gray-100'>
+ {param.entries ? (
+ <ul className='space-y-0.5'>
+ {_map(param.entries, (entry, eIdx) => (
+ <li
+ key={eIdx}
+ className='wrap-break-word'
+ >
+ {entry}
+ </li>
+ ))}
+ </ul>
+ ) : param.json ? (
+ <pre className='overflow-x-auto rounded-md bg-gray-50 p-2 font-mono text-[11px] leading-snug text-gray-700 dark:bg-slate-950/60 dark:text-gray-300'>
+ {param.json}
+ </pre>
+ ) : (
+ <span className='wrap-break-word'>
+ {param.value}
+ </span>
+ )}
+ </dd>
+ </React.Fragment>
+ ))}
+ </dl>
+ )}
+ </div>
+ </div>
+ </li>
+ )
+ })}
+ </ol>
+ </div>
+ ) : null}
+ </div>
+ )
+}
+
const AssistantMessage = ({
message,
isStreaming,
@@ -634,6 +784,10 @@ const AssistantMessage = ({
</>
)}
+ {!isStreaming && message.toolCalls && message.toolCalls.length > 0 ? (
+ <ToolCallSummaryDrawer toolCalls={message.toolCalls} />
+ ) : null}
+
{!isStreaming &&
hasContent &&
followUps &&
@@ -997,6 +1151,7 @@ interface AIChat {
role: 'user' | 'assistant'
content: string
followUps?: string[]
+ toolCalls?: MessageToolCall[]
}[]
isOwner?: boolean
branched?: boolean
@@ -1068,9 +1223,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const streamingContentRef = useRef('')
const streamingReasoningRef = useRef('')
- const streamingToolCallsRef = useRef<
- Array<{ toolName: string; args: unknown }>
- >([])
+ const streamingToolCallsRef = useRef<MessageToolCall[]>([])
const streamingPartsRef = useRef<MessagePart[]>([])
const currentTextPartRef = useRef('')
const streamingFollowUpsRef = useRef<string[] | null>(null)
@@ -1180,6 +1333,16 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
m.followUps.length > 0
? m.followUps
: undefined,
+ toolCalls:
+ m.role === 'assistant' &&
+ Array.isArray(m.toolCalls) &&
+ m.toolCalls.length > 0
+ ? m.toolCalls.map((tc) => ({
+ toolName: tc.toolName,
+ args: tc.args,
+ timestamp: tc.timestamp,
+ }))
+ : undefined,
})),
)
setCurrentChatId(chat.id)
@@ -1210,6 +1373,11 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
role: 'user' | 'assistant'
content: string
followUps?: string[]
+ toolCalls?: Array<{
+ toolName: string
+ args: unknown
+ timestamp?: string
+ }>
} = {
role: m.role,
content: m.content,
@@ -1217,6 +1385,13 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
if (m.role === 'assistant' && m.followUps && m.followUps.length > 0) {
base.followUps = m.followUps
}
+ if (m.role === 'assistant' && m.toolCalls && m.toolCalls.length > 0) {
+ base.toolCalls = m.toolCalls.map((tc) => ({
+ toolName: tc.toolName,
+ args: tc.args,
+ timestamp: tc.timestamp,
+ }))
+ }
return base
}
@@ -1476,7 +1651,11 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
},
onToolCall: (toolName, args) => {
setIsWaitingForResponse(false)
- streamingToolCallsRef.current.push({ toolName, args })
+ streamingToolCallsRef.current.push({
+ toolName,
+ args,
+ timestamp: new Date().toISOString(),
+ })
if (currentTextPartRef.current.trim()) {
streamingPartsRef.current.push({
diff --git a/web/app/pages/Project/tabs/AskAI/toolFormatters.ts b/web/app/pages/Project/tabs/AskAI/toolFormatters.ts
new file mode 100644
index 000000000..5c6ef7c55
--- /dev/null
+++ b/web/app/pages/Project/tabs/AskAI/toolFormatters.ts
@@ -0,0 +1,338 @@
+import type { TFunction } from 'i18next'
+
+import { tbPeriodPairs } from '~/lib/constants'
+
+interface ToolCallFilter {
+ column?: string
+ filter?: string
+ isExclusive?: boolean
+ isContains?: boolean
+}
+
+export interface ToolCallParam {
+ /** Locale key under project.askAi.params (with fallback) */
+ labelKey: string
+ /** Fallback label if no translation exists */
+ fallbackLabel: string
+ /** Plain string display value */
+ value?: string
+ /** Pre-formatted entries for list-style values (e.g. filters) */
+ entries?: string[]
+ /** Pretty-printed JSON for objects/arrays we don't have a special formatter for */
+ json?: string
+}
+
+export interface ToolCallSummary {
+ toolName: string
+ params: ToolCallParam[]
+}
+
+const PERIOD_KEYS = new Set([
+ '1h',
+ 'today',
+ 'yesterday',
+ '1d',
+ '7d',
+ '4w',
+ '3M',
+ '12M',
+ '24M',
+ 'all',
+])
+
+const FILTER_COLUMN_LABEL_KEYS: Record<string, string> = {
+ pg: 'project.mapping.pg',
+ cc: 'project.mapping.cc',
+ rg: 'project.mapping.rg',
+ ct: 'project.mapping.ct',
+ br: 'project.mapping.br',
+ brv: 'project.mapping.brv',
+ os: 'project.mapping.os',
+ osv: 'project.mapping.osv',
+ dv: 'project.mapping.dv',
+ ref: 'project.mapping.ref',
+ so: 'project.mapping.so',
+ me: 'project.mapping.me',
+ ca: 'project.mapping.ca',
+ te: 'project.mapping.te',
+ co: 'project.mapping.co',
+ lc: 'project.mapping.lc',
+ host: 'project.mapping.host',
+}
+
+/** Keys that may contain raw SQL or query text. We never render these. */
+const SENSITIVE_KEYS = new Set([
+ 'sql',
+ 'query',
+ 'queryText',
+ 'rawSql',
+ 'rawQuery',
+])
+
+const formatPeriod = (period: string, t: TFunction): string => {
+ if (!PERIOD_KEYS.has(period)) return period
+ const pair = tbPeriodPairs(t).find((p) => p.period === period)
+ return pair?.label ?? period
+}
+
+const formatDate = (input: string): string => {
+ const date = new Date(input)
+ if (Number.isNaN(date.getTime())) return input
+ return date.toLocaleDateString(undefined, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ })
+}
+
+const formatRange = (from: string, to: string): string => {
+ const fromDate = new Date(from)
+ const toDate = new Date(to)
+ if (Number.isNaN(fromDate.getTime()) || Number.isNaN(toDate.getTime())) {
+ return `${from} – ${to}`
+ }
+ const sameYear = fromDate.getFullYear() === toDate.getFullYear()
+ const fromOpts: Intl.DateTimeFormatOptions = sameYear
+ ? { month: 'short', day: 'numeric' }
+ : { year: 'numeric', month: 'short', day: 'numeric' }
+ const toOpts: Intl.DateTimeFormatOptions = {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ }
+ return `${fromDate.toLocaleDateString(undefined, fromOpts)} – ${toDate.toLocaleDateString(undefined, toOpts)}`
+}
+
+const formatFilter = (filter: ToolCallFilter, t: TFunction): string | null => {
+ if (!filter || typeof filter.column !== 'string' || !filter.filter) {
+ return null
+ }
+ const labelKey = FILTER_COLUMN_LABEL_KEYS[filter.column]
+ const column = labelKey
+ ? t(labelKey, { defaultValue: filter.column })
+ : filter.column
+ let operator: string
+ if (filter.isExclusive && filter.isContains) {
+ operator = t('project.askAi.params.opNotContains', {
+ defaultValue: 'does not contain',
+ })
+ } else if (filter.isExclusive) {
+ operator = '≠'
+ } else if (filter.isContains) {
+ operator = t('project.askAi.params.opContains', {
+ defaultValue: 'contains',
+ })
+ } else {
+ operator = '='
+ }
+ return `${column} ${operator} ${filter.filter}`
+}
+
+const formatDataType = (dataType: string, t: TFunction): string => {
+ const key = `project.askAi.params.dataTypes.${dataType}`
+ return t(key, { defaultValue: dataType })
+}
+
+const formatTimeBucket = (bucket: string, t: TFunction): string => {
+ const key = `project.askAi.params.timeBuckets.${bucket}`
+ return t(key, { defaultValue: bucket })
+}
+
+const formatMeasure = (measure: string, t: TFunction): string => {
+ const key = `project.askAi.params.measures.${measure}`
+ return t(key, { defaultValue: measure })
+}
+
+const isPlainObject = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value)
+
+/**
+ * Convert a single tool-call argument object into a structured, human-readable
+ * list of parameters. SQL/raw-query keys are intentionally never rendered.
+ */
+export const formatToolCallSummary = (
+ toolName: string,
+ args: unknown,
+ t: TFunction,
+): ToolCallSummary => {
+ if (!isPlainObject(args)) {
+ return { toolName, params: [] }
+ }
+
+ const params: ToolCallParam[] = []
+
+ const entries = Object.entries(args).filter(([key, value]) => {
+ if (SENSITIVE_KEYS.has(key)) return false
+ if (value === undefined || value === null) return false
+ if (typeof value === 'string' && value.trim() === '') return false
+ if (Array.isArray(value) && value.length === 0) return false
+ return true
+ })
+
+ const has = (k: string) => entries.some(([key]) => key === k)
+ const get = (k: string) => entries.find(([key]) => key === k)?.[1]
+
+ // Combined date range: from + to → single "From – To" entry
+ if (has('from') && has('to')) {
+ params.push({
+ labelKey: 'project.askAi.params.dateRange',
+ fallbackLabel: 'Date range',
+ value: formatRange(String(get('from')), String(get('to'))),
+ })
+ }
+
+ for (const [key, value] of entries) {
+ if (key === 'from' && has('to')) continue
+ if (key === 'to' && has('from')) continue
+
+ switch (key) {
+ case 'period': {
+ params.push({
+ labelKey: 'project.askAi.params.period',
+ fallbackLabel: 'Period',
+ value: formatPeriod(String(value), t),
+ })
+ break
+ }
+ case 'from': {
+ params.push({
+ labelKey: 'project.askAi.params.from',
+ fallbackLabel: 'From',
+ value: formatDate(String(value)),
+ })
+ break
+ }
+ case 'to': {
+ params.push({
+ labelKey: 'project.askAi.params.to',
+ fallbackLabel: 'To',
+ value: formatDate(String(value)),
+ })
+ break
+ }
+ case 'dataType': {
+ params.push({
+ labelKey: 'project.askAi.params.dataType',
+ fallbackLabel: 'Data type',
+ value: formatDataType(String(value), t),
+ })
+ break
+ }
+ case 'timeBucket': {
+ params.push({
+ labelKey: 'project.askAi.params.timeBucket',
+ fallbackLabel: 'Granularity',
+ value: formatTimeBucket(String(value), t),
+ })
+ break
+ }
+ case 'measure': {
+ params.push({
+ labelKey: 'project.askAi.params.measure',
+ fallbackLabel: 'Measure',
+ value: formatMeasure(String(value), t),
+ })
+ break
+ }
+ case 'filters': {
+ if (!Array.isArray(value)) break
+ const formatted = value
+ .map((f) => formatFilter(f as ToolCallFilter, t))
+ .filter((entry): entry is string => Boolean(entry))
+ if (formatted.length > 0) {
+ params.push({
+ labelKey: 'project.askAi.params.filters',
+ fallbackLabel: 'Filters',
+ entries: formatted,
+ })
+ }
+ break
+ }
+ case 'goalId':
+ case 'funnelId':
+ case 'flagId':
+ case 'experimentId': {
+ const resolved = resolveEntityName(toolName, key, String(value), t)
+ const labelKey = `project.askAi.params.${key}`
+ const fallback =
+ key === 'goalId'
+ ? 'Goal'
+ : key === 'funnelId'
+ ? 'Funnel'
+ : key === 'flagId'
+ ? 'Feature flag'
+ : 'Experiment'
+ params.push({
+ labelKey,
+ fallbackLabel: fallback,
+ value: resolved,
+ })
+ break
+ }
+ case 'country': {
+ params.push({
+ labelKey: 'project.askAi.params.country',
+ fallbackLabel: 'Country',
+ value: String(value),
+ })
+ break
+ }
+ case 'page': {
+ params.push({
+ labelKey: 'project.askAi.params.page',
+ fallbackLabel: 'Page',
+ value: String(value),
+ })
+ break
+ }
+ case 'take': {
+ params.push({
+ labelKey: 'project.askAi.params.take',
+ fallbackLabel: 'Limit',
+ value: String(value),
+ })
+ break
+ }
+ default: {
+ if (
+ typeof value === 'string' ||
+ typeof value === 'number' ||
+ typeof value === 'boolean'
+ ) {
+ params.push({
+ labelKey: `project.askAi.params.${key}`,
+ fallbackLabel: humaniseKey(key),
+ value: String(value),
+ })
+ } else {
+ params.push({
+ labelKey: `project.askAi.params.${key}`,
+ fallbackLabel: humaniseKey(key),
+ json: JSON.stringify(value, null, 2),
+ })
+ }
+ }
+ }
+ }
+
+ return { toolName, params }
+}
+
+const humaniseKey = (key: string): string => {
+ const spaced = key.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ')
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
+}
+
+/**
+ * Best-effort lookup of an entity name. Without project context, we just show
+ * the raw ID with a "(ID)" hint so users can see the call was scoped to a
+ * specific entity even when we don't yet know the friendly name.
+ */
+const resolveEntityName = (
+ _toolName: string,
+ _key: string,
+ id: string,
+ _t: TFunction,
+): string => {
+ return id
+}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 42d258548..b06f2e5b0 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -2142,6 +2142,47 @@
"getSessionsList": "Fetched recent sessions",
"getProfilesOverview": "Fetched profiles overview"
},
+ "howIGotThis_one": "How I got this · 1 step",
+ "howIGotThis_other": "How I got this · {{count}} steps",
+ "noParameters": "No parameters",
+ "params": {
+ "period": "Period",
+ "from": "From",
+ "to": "To",
+ "dateRange": "Date range",
+ "dataType": "Data type",
+ "timeBucket": "Granularity",
+ "measure": "Measure",
+ "filters": "Filters",
+ "goalId": "Goal",
+ "funnelId": "Funnel",
+ "flagId": "Feature flag",
+ "experimentId": "Experiment",
+ "country": "Country",
+ "page": "Page",
+ "take": "Limit",
+ "opContains": "contains",
+ "opNotContains": "does not contain",
+ "dataTypes": {
+ "analytics": "Traffic analytics",
+ "performance": "Performance",
+ "captcha": "CAPTCHA",
+ "errors": "Errors",
+ "customEvents": "Custom events"
+ },
+ "timeBuckets": {
+ "minute": "Minute",
+ "hour": "Hour",
+ "day": "Day",
+ "month": "Month",
+ "year": "Year"
+ },
+ "measures": {
+ "average": "Average",
+ "median": "Median",
+ "p95": "p95"
+ }
+ },
"capabilities": {
"title": "Swetrix AI can:",
"queryAnalytics": "Query analytics including pageviews, visitors, and sessions",