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!

Update errors list & error view UI

Blue Mousea0e882cf91c4
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index 1bb037f92..017d55034 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -79,6 +79,7 @@ import { GetProfileDto, GetProfileSessionsDto } from './dto/get-profile.dto'
import { ErrorDto } from './dto/error.dto'
import { GetErrorsDto } from './dto/get-errors.dto'
import { GetErrorDto } from './dto/get-error.dto'
+import { GetErrorOverviewDto } from './dto/get-error-overview.dto'
import { PatchStatusDto } from './dto/patch-status.dto'
import {
customEventTransformer,
@@ -1794,6 +1795,148 @@ export class AnalyticsController {
return result
}
+ @Get('error-overview')
+ @Auth(true, true)
+ async getErrorOverview(
+ @Query() data: GetErrorOverviewDto,
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const {
+ pid,
+ period,
+ from,
+ to,
+ filters,
+ timezone = DEFAULT_TIMEZONE,
+ timeBucket,
+ options,
+ } = data
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ await this.analyticsService.checkBillingAccess(pid)
+
+ let parsedOptions: { showResolved?: boolean } = {}
+ try {
+ parsedOptions = JSON.parse(options || '{}')
+ } catch {
+ // Ignore parse errors
+ }
+
+ let newTimeBucket = timeBucket
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ 'errors',
+ )
+
+ newTimeBucket = res.timeBucket[0]
+ diff = res.diff
+ }
+
+ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
+ filters,
+ DataType.ERRORS,
+ true,
+ )
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ newTimeBucket,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ const paramsData = {
+ params: {
+ pid,
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ ...filtersParams,
+ },
+ }
+
+ return this.analyticsService.getErrorOverview(
+ pid,
+ filtersQuery,
+ paramsData,
+ safeTimezone,
+ groupFromUTC,
+ groupToUTC,
+ newTimeBucket,
+ parsedOptions.showResolved || false,
+ )
+ }
+
+ @Get('error-sessions')
+ @Auth(true, true)
+ async getErrorSessions(
+ @Query() data: GetErrorDto & { take?: number; skip?: number },
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const { pid, eid, period, from, to, timeBucket } = data
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ await this.analyticsService.checkBillingAccess(pid)
+
+ const take = this.analyticsService.getSafeNumber(data.take, 10)
+ const skip = this.analyticsService.getSafeNumber(data.skip, 0)
+
+ if (take > 50) {
+ throw new BadRequestException(
+ 'The maximum number of sessions to return is 50',
+ )
+ }
+
+ let newTimeBucket = timeBucket
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ 'errors',
+ )
+
+ newTimeBucket = res.timeBucket[0]
+ diff = res.diff
+ }
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(DEFAULT_TIMEZONE)
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ newTimeBucket,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ return this.analyticsService.getErrorAffectedSessions(
+ pid,
+ eid,
+ groupFromUTC,
+ groupToUTC,
+ take,
+ skip,
+ )
+ }
+
@Get('session')
@Auth(true, true)
async getSession(
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index b66121e66..d71d39d5c 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -2719,9 +2719,10 @@ export class AnalyticsService {
const baseQuery = `
SELECT
${selector},
- count() as count
+ count() as count,
+ uniqExact(profileId) as affectedUsers
FROM (
- SELECT pg, dv, br, os, lc, cc, rg, ct,
+ SELECT pg, dv, br, os, lc, cc, rg, ct, profileId,
${timeBucketFunc}(created) as tz_created
FROM errors
WHERE
@@ -3285,11 +3286,12 @@ export class AnalyticsService {
query_params: paramsData.params,
})
.then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())
- const { count } = this.extractCaptchaChartData(data, x)
+ const { count, affectedUsers } = this.extractErrorsChartData(data, x)
chart = {
x: this.shiftToTimezone(x, safeTimezone, format),
occurrences: count,
+ affectedUsers,
}
})(),
]
@@ -3302,6 +3304,26 @@ export class AnalyticsService {
})
}
+ extractErrorsChartData(
+ result: any[],
+ x: string[],
+ ): { count: number[]; affectedUsers: number[] } {
+ const count = Array(x.length).fill(0)
+ const affectedUsers = Array(x.length).fill(0)
+
+ for (let row = 0; row < _size(result); ++row) {
+ const dateString = this.generateDateString(result[row])
+ const index = x.indexOf(dateString)
+
+ if (index !== -1) {
+ count[index] = Number(result[row].count) || 0
+ affectedUsers[index] = Number(result[row].affectedUsers) || 0
+ }
+ }
+
+ return { count, affectedUsers }
+ }
+
extractPerformanceChartData(result, x: string[]): any {
const dns = Array(x.length).fill(0)
const tls = Array(x.length).fill(0)
@@ -4694,9 +4716,11 @@ export class AnalyticsService {
any(filename) as filename,
count(*) as count,
max(created) as last_seen,
+ count(DISTINCT profileId) as users,
+ count(DISTINCT psid) as sessions,
status.status
FROM (
- SELECT eid, name, message, filename, toTimeZone(errors.created, {timezone:String}) AS created
+ SELECT eid, name, message, filename, psid, profileId, toTimeZone(errors.created, {timezone:String}) AS created
FROM errors
WHERE pid = {pid:FixedString(12)}
AND errors.created BETWEEN {groupFrom:String} AND {groupTo:String}
@@ -4864,6 +4888,254 @@ export class AnalyticsService {
}
}
+ async getErrorOverview(
+ pid: string,
+ filtersQuery: string,
+ paramsData: any,
+ safeTimezone: string,
+ groupFrom: string,
+ groupTo: string,
+ timeBucket: string,
+ showResolved: boolean,
+ ): Promise<any> {
+ const resolvedFilter = showResolved
+ ? ''
+ : "AND (status.status = 'active' OR status.status = 'regressed' OR status.status IS NULL)"
+
+ // Get total sessions from analytics table for the time range
+ const queryTotalSessions = `
+ SELECT count(DISTINCT psid) as totalSessions
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `
+
+ // Get error stats: total errors, unique errors, affected sessions, affected users
+ const queryErrorStats = `
+ SELECT
+ count(*) as totalErrors,
+ count(DISTINCT eid) as uniqueErrors,
+ count(DISTINCT psid) as affectedSessions,
+ count(DISTINCT profileId) as affectedUsers
+ FROM errors
+ LEFT JOIN (
+ SELECT eid, argMax(status, updated) AS status
+ FROM error_statuses
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY eid
+ ) AS status ON errors.eid = status.eid
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ ${resolvedFilter}
+ `
+
+ // Get most frequent error
+ const queryMostFrequentError = `
+ SELECT
+ errors.eid as eid,
+ any(errors.name) as name,
+ any(errors.message) as message,
+ count(*) as count,
+ count(DISTINCT errors.profileId) as usersAffected,
+ max(errors.created) as lastSeen
+ FROM errors
+ LEFT JOIN (
+ SELECT eid, argMax(status, updated) AS status
+ FROM error_statuses
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY eid
+ ) AS status ON errors.eid = status.eid
+ WHERE errors.pid = {pid:FixedString(12)}
+ AND errors.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ ${resolvedFilter}
+ GROUP BY errors.eid
+ ORDER BY count DESC
+ LIMIT 1
+ `
+
+ // Get chart data with affected users - use same pattern as other chart methods
+ const timeBucketFunc =
+ timeBucketConversion[timeBucket as keyof typeof timeBucketConversion] ||
+ timeBucketConversion.day
+ const [selector, groupBy] = this.getGroupSubquery(
+ timeBucket as TimeBucketType,
+ )
+ const queryChart = `
+ SELECT
+ ${selector},
+ count(*) as count,
+ uniqExact(profileId) as affectedUsers
+ FROM (
+ SELECT
+ profileId,
+ ${timeBucketFunc}(toTimeZone(created, {timezone:String})) as tz_created
+ FROM errors
+ LEFT JOIN (
+ SELECT eid, argMax(status, updated) AS status
+ FROM error_statuses
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY eid
+ ) AS status ON errors.eid = status.eid
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ ${resolvedFilter}
+ ) as subquery
+ GROUP BY ${groupBy}
+ ORDER BY ${groupBy}
+ `
+
+ const paramsWithTimezone = {
+ ...paramsData.params,
+ timezone: safeTimezone,
+ }
+
+ const [
+ totalSessionsResult,
+ errorStatsResult,
+ mostFrequentResult,
+ chartResult,
+ ] = await Promise.all([
+ clickhouse
+ .query({
+ query: queryTotalSessions,
+ query_params: paramsData.params,
+ })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data[0]),
+ clickhouse
+ .query({
+ query: queryErrorStats,
+ query_params: paramsWithTimezone,
+ })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data[0]),
+ clickhouse
+ .query({
+ query: queryMostFrequentError,
+ query_params: paramsWithTimezone,
+ })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data[0] || null),
+ clickhouse
+ .query({
+ query: queryChart,
+ query_params: paramsWithTimezone,
+ })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data),
+ ])
+
+ // Process chart data using same pattern as extractErrorsChartData
+ const { x, format } = this.generateUTCXAxis(
+ timeBucket as TimeBucketType,
+ groupFrom,
+ groupTo,
+ )
+ const occurrences = Array(x.length).fill(0)
+ const affectedUsersChart = Array(x.length).fill(0)
+
+ for (const row of chartResult) {
+ const dateString = this.generateDateString(row)
+ const index = x.indexOf(dateString)
+ if (index !== -1) {
+ occurrences[index] = Number(row.count) || 0
+ affectedUsersChart[index] = Number(row.affectedUsers) || 0
+ }
+ }
+
+ const errorRate =
+ totalSessionsResult?.totalSessions > 0
+ ? (Number(errorStatsResult?.affectedSessions || 0) /
+ Number(totalSessionsResult.totalSessions)) *
+ 100
+ : 0
+
+ return {
+ stats: {
+ totalErrors: Number(errorStatsResult?.totalErrors || 0),
+ uniqueErrors: Number(errorStatsResult?.uniqueErrors || 0),
+ affectedSessions: Number(errorStatsResult?.affectedSessions || 0),
+ affectedUsers: Number(errorStatsResult?.affectedUsers || 0),
+ errorRate: Math.round(errorRate * 100) / 100,
+ },
+ mostFrequentError: mostFrequentResult
+ ? {
+ eid: mostFrequentResult.eid,
+ name: mostFrequentResult.name,
+ message: mostFrequentResult.message,
+ count: Number(mostFrequentResult.count),
+ usersAffected: Number(mostFrequentResult.usersAffected),
+ lastSeen: mostFrequentResult.lastSeen,
+ }
+ : null,
+ chart: {
+ x: this.shiftToTimezone(x, safeTimezone, format),
+ occurrences,
+ affectedUsers: affectedUsersChart,
+ },
+ timeBucket,
+ }
+ }
+
+ async getErrorAffectedSessions(
+ pid: string,
+ eid: string,
+ groupFrom: string,
+ groupTo: string,
+ take: number = 10,
+ skip: number = 0,
+ ): Promise<{ sessions: any[]; total: number }> {
+ const queryCount = `
+ SELECT count(DISTINCT psid) as total
+ FROM errors
+ WHERE pid = {pid:FixedString(12)}
+ AND eid = {eid:FixedString(32)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `
+
+ const querySessions = `
+ SELECT DISTINCT
+ errors.psid as psid,
+ any(errors.profileId) as profileId,
+ any(analytics.cc) as cc,
+ any(analytics.br) as br,
+ any(analytics.os) as os,
+ min(errors.created) as firstErrorAt,
+ max(errors.created) as lastErrorAt,
+ count(*) as errorCount
+ FROM errors
+ LEFT JOIN analytics ON errors.psid = analytics.psid AND errors.pid = analytics.pid
+ WHERE errors.pid = {pid:FixedString(12)}
+ AND errors.eid = {eid:FixedString(32)}
+ AND errors.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY errors.psid
+ ORDER BY lastErrorAt DESC
+ LIMIT ${take}
+ OFFSET ${skip}
+ `
+
+ const params = { pid, eid, groupFrom, groupTo }
+
+ const [countResult, sessionsResult] = await Promise.all([
+ clickhouse
+ .query({ query: queryCount, query_params: params })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data[0]),
+ clickhouse
+ .query({ query: querySessions, query_params: params })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data),
+ ])
+
+ return {
+ sessions: sessionsResult,
+ total: Number(countResult?.total || 0),
+ }
+ }
+
getErrorID(errorDTO: ErrorDto): string {
const { name, message, colno, lineno, filename } = errorDTO
diff --git a/backend/apps/cloud/src/analytics/dto/get-error-overview.dto.ts b/backend/apps/cloud/src/analytics/dto/get-error-overview.dto.ts
new file mode 100644
index 000000000..908941164
--- /dev/null
+++ b/backend/apps/cloud/src/analytics/dto/get-error-overview.dto.ts
@@ -0,0 +1,20 @@
+import { PickType, ApiProperty } from '@nestjs/swagger'
+import { GetDataDto } from './getData.dto'
+
+export class GetErrorOverviewDto extends PickType(GetDataDto, [
+ 'pid',
+ 'period',
+ 'from',
+ 'to',
+ 'filters',
+ 'timezone',
+ 'timeBucket',
+] as const) {
+ @ApiProperty({
+ example: {
+ showResolved: true,
+ },
+ description: 'Errors list options',
+ })
+ options?: string
+}
diff --git a/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts b/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts
index 4d346a6e2..389c084eb 100644
--- a/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts
+++ b/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts
@@ -13,9 +13,9 @@ import {
FeatureFlagType,
TargetingRule,
EvaluatableFeatureFlag,
-} from '../../../../../libs/shared/src/feature-flag'
+} from '../evaluation'
-// Re-export shared types for backward compatibility
+// Re-export types for backward compatibility
export { FeatureFlagType, TargetingRule, EvaluatableFeatureFlag }
@Entity()
diff --git a/backend/libs/shared/src/feature-flag/evaluation.ts b/backend/apps/cloud/src/feature-flag/evaluation.ts
similarity index 100%
rename from backend/libs/shared/src/feature-flag/evaluation.ts
rename to backend/apps/cloud/src/feature-flag/evaluation.ts
diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts b/backend/apps/cloud/src/feature-flag/feature-flag.service.ts
index 4a960e763..cf9f4a4de 100644
--- a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts
+++ b/backend/apps/cloud/src/feature-flag/feature-flag.service.ts
@@ -6,7 +6,7 @@ import { FeatureFlag } from './entity/feature-flag.entity'
import {
evaluateFlag as sharedEvaluateFlag,
evaluateFlags as sharedEvaluateFlags,
-} from '../../../../libs/shared/src/feature-flag'
+} from './evaluation'
@Injectable()
export class FeatureFlagService {
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index 7643df280..c03b5fc17 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -66,6 +66,7 @@ import { GetSessionDto } from './dto/get-session.dto'
import { ErrorDto } from './dto/error.dto'
import { GetErrorsDto } from './dto/get-errors.dto'
import { GetErrorDto } from './dto/get-error.dto'
+import { GetErrorOverviewDto } from './dto/get-error-overview.dto'
import { PatchStatusDto } from './dto/patch-status.dto'
import {
customEventTransformer,
@@ -1722,4 +1723,142 @@ export class AnalyticsController {
return result
}
+
+ @Get('error-overview')
+ @Auth(true, true)
+ async getErrorOverview(
+ @Query() data: GetErrorOverviewDto,
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const {
+ pid,
+ period,
+ from,
+ to,
+ filters,
+ timezone = DEFAULT_TIMEZONE,
+ timeBucket,
+ options,
+ } = data
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ let parsedOptions: { showResolved?: boolean } = {}
+ try {
+ parsedOptions = JSON.parse(options || '{}')
+ } catch {
+ // Ignore parse errors
+ }
+
+ let newTimeBucket = timeBucket
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ 'errors',
+ )
+
+ newTimeBucket = res.timeBucket[0]
+ diff = res.diff
+ }
+
+ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
+ filters,
+ DataType.ERRORS,
+ true,
+ )
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ newTimeBucket,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ const paramsData = {
+ params: {
+ pid,
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ ...filtersParams,
+ },
+ }
+
+ return this.analyticsService.getErrorOverview(
+ pid,
+ filtersQuery,
+ paramsData,
+ safeTimezone,
+ groupFromUTC,
+ groupToUTC,
+ newTimeBucket,
+ parsedOptions.showResolved || false,
+ )
+ }
+
+ @Get('error-sessions')
+ @Auth(true, true)
+ async getErrorSessions(
+ @Query() data: GetErrorDto & { take?: number; skip?: number },
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const { pid, eid, period, from, to, timeBucket } = data
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ const take = this.analyticsService.getSafeNumber(data.take, 10)
+ const skip = this.analyticsService.getSafeNumber(data.skip, 0)
+
+ if (take > 50) {
+ throw new BadRequestException(
+ 'The maximum number of sessions to return is 50',
+ )
+ }
+
+ let newTimeBucket = timeBucket
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ 'errors',
+ )
+
+ newTimeBucket = res.timeBucket[0]
+ diff = res.diff
+ }
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(DEFAULT_TIMEZONE)
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ newTimeBucket,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ return this.analyticsService.getErrorAffectedSessions(
+ pid,
+ eid,
+ groupFromUTC,
+ groupToUTC,
+ take,
+ skip,
+ )
+ }
}
diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.ts
index 66b754058..351eb9b38 100644
--- a/backend/apps/community/src/analytics/analytics.service.ts
+++ b/backend/apps/community/src/analytics/analytics.service.ts
@@ -2582,9 +2582,10 @@ export class AnalyticsService {
const baseQuery = `
SELECT
${selector},
- count() as count
+ count() as count,
+ uniqExact(profileId) as affectedUsers
FROM (
- SELECT pg, dv, br, os, lc, cc, rg, ct,
+ SELECT pg, dv, br, os, lc, cc, rg, ct, profileId,
${timeBucketFunc}(created) as tz_created
FROM errors
WHERE
@@ -2834,22 +2835,24 @@ export class AnalyticsService {
})
}
- extractErrorsChartData(result, x: string[]): any {
+ extractErrorsChartData(
+ result: any[],
+ x: string[],
+ ): { count: number[]; affectedUsers: number[] } {
const count = Array(x.length).fill(0)
+ const affectedUsers = Array(x.length).fill(0)
for (let row = 0; row < _size(result); ++row) {
const dateString = this.generateDateString(result[row])
-
const index = x.indexOf(dateString)
if (index !== -1) {
- count[index] = result[row].count
+ count[index] = Number(result[row].count) || 0
+ affectedUsers[index] = Number(result[row].affectedUsers) || 0
}
}
- return {
- count,
- }
+ return { count, affectedUsers }
}
generateUTCXAxis(
@@ -3079,11 +3082,12 @@ export class AnalyticsService {
query_params: paramsData.params,
})
.then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())
- const { count } = this.extractErrorsChartData(data, x)
+ const { count, affectedUsers } = this.extractErrorsChartData(data, x)
chart = {
x: this.shiftToTimezone(x, safeTimezone, format),
occurrences: count,
+ affectedUsers,
}
})(),
]
@@ -3970,9 +3974,11 @@ export class AnalyticsService {
any(filename) as filename,
count(*) as count,
max(created) as last_seen,
+ count(DISTINCT profileId) as users,
+ count(DISTINCT psid) as sessions,
status.status
FROM (
- SELECT eid, name, message, filename, toTimeZone(errors.created, {timezone:String}) AS created
+ SELECT eid, name, message, filename, psid, profileId, toTimeZone(errors.created, {timezone:String}) AS created
FROM errors
WHERE pid = {pid:FixedString(12)}
AND errors.created BETWEEN {groupFrom:String} AND {groupTo:String}
@@ -4140,6 +4146,254 @@ export class AnalyticsService {
}
}
+ async getErrorOverview(
+ pid: string,
+ filtersQuery: string,
+ paramsData: any,
+ safeTimezone: string,
+ groupFrom: string,
+ groupTo: string,
+ timeBucket: string,
+ showResolved: boolean,
+ ): Promise<any> {
+ const resolvedFilter = showResolved
+ ? ''
+ : "AND (status.status = 'active' OR status.status = 'regressed' OR status.status IS NULL)"
+
+ // Get total sessions from analytics table for the time range
+ const queryTotalSessions = `
+ SELECT count(DISTINCT psid) as totalSessions
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `
+
+ // Get error stats: total errors, unique errors, affected sessions, affected users
+ const queryErrorStats = `
+ SELECT
+ count(*) as totalErrors,
+ count(DISTINCT eid) as uniqueErrors,
+ count(DISTINCT psid) as affectedSessions,
+ count(DISTINCT profileId) as affectedUsers
+ FROM errors
+ LEFT JOIN (
+ SELECT eid, argMax(status, updated) AS status
+ FROM error_statuses
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY eid
+ ) AS status ON errors.eid = status.eid
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ ${resolvedFilter}
+ `
+
+ // Get most frequent error
+ const queryMostFrequentError = `
+ SELECT
+ errors.eid as eid,
+ any(errors.name) as name,
+ any(errors.message) as message,
+ count(*) as count,
+ count(DISTINCT errors.profileId) as usersAffected,
+ max(errors.created) as lastSeen
+ FROM errors
+ LEFT JOIN (
+ SELECT eid, argMax(status, updated) AS status
+ FROM error_statuses
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY eid
+ ) AS status ON errors.eid = status.eid
+ WHERE errors.pid = {pid:FixedString(12)}
+ AND errors.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ ${resolvedFilter}
+ GROUP BY errors.eid
+ ORDER BY count DESC
+ LIMIT 1
+ `
+
+ // Get chart data with affected users - use same pattern as other chart methods
+ const timeBucketFunc =
+ timeBucketConversion[timeBucket as keyof typeof timeBucketConversion] ||
+ timeBucketConversion.day
+ const [selector, groupBy] = this.getGroupSubquery(
+ timeBucket as TimeBucketType,
+ )
+ const queryChart = `
+ SELECT
+ ${selector},
+ count(*) as count,
+ uniqExact(profileId) as affectedUsers
+ FROM (
+ SELECT
+ profileId,
+ ${timeBucketFunc}(toTimeZone(created, {timezone:String})) as tz_created
+ FROM errors
+ LEFT JOIN (
+ SELECT eid, argMax(status, updated) AS status
+ FROM error_statuses
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY eid
+ ) AS status ON errors.eid = status.eid
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ ${resolvedFilter}
+ ) as subquery
+ GROUP BY ${groupBy}
+ ORDER BY ${groupBy}
+ `
+
+ const paramsWithTimezone = {
+ ...paramsData.params,
+ timezone: safeTimezone,
+ }
+
+ const [
+ totalSessionsResult,
+ errorStatsResult,
+ mostFrequentResult,
+ chartResult,
+ ] = await Promise.all([
+ clickhouse
+ .query({
+ query: queryTotalSessions,
+ query_params: paramsData.params,
+ })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data[0]),
+ clickhouse
+ .query({
+ query: queryErrorStats,
+ query_params: paramsWithTimezone,
+ })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data[0]),
+ clickhouse
+ .query({
+ query: queryMostFrequentError,
+ query_params: paramsWithTimezone,
+ })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data[0] || null),
+ clickhouse
+ .query({
+ query: queryChart,
+ query_params: paramsWithTimezone,
+ })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data),
+ ])
+
+ // Process chart data using same pattern as extractErrorsChartData
+ const { x, format } = this.generateUTCXAxis(
+ timeBucket as TimeBucketType,
+ groupFrom,
+ groupTo,
+ )
+ const occurrences = Array(x.length).fill(0)
+ const affectedUsersChart = Array(x.length).fill(0)
+
+ for (const row of chartResult) {
+ const dateString = this.generateDateString(row)
+ const index = x.indexOf(dateString)
+ if (index !== -1) {
+ occurrences[index] = Number(row.count) || 0
+ affectedUsersChart[index] = Number(row.affectedUsers) || 0
+ }
+ }
+
+ const errorRate =
+ totalSessionsResult?.totalSessions > 0
+ ? (Number(errorStatsResult?.affectedSessions || 0) /
+ Number(totalSessionsResult.totalSessions)) *
+ 100
+ : 0
+
+ return {
+ stats: {
+ totalErrors: Number(errorStatsResult?.totalErrors || 0),
+ uniqueErrors: Number(errorStatsResult?.uniqueErrors || 0),
+ affectedSessions: Number(errorStatsResult?.affectedSessions || 0),
+ affectedUsers: Number(errorStatsResult?.affectedUsers || 0),
+ errorRate: Math.round(errorRate * 100) / 100,
+ },
+ mostFrequentError: mostFrequentResult
+ ? {
+ eid: mostFrequentResult.eid,
+ name: mostFrequentResult.name,
+ message: mostFrequentResult.message,
+ count: Number(mostFrequentResult.count),
+ usersAffected: Number(mostFrequentResult.usersAffected),
+ lastSeen: mostFrequentResult.lastSeen,
+ }
+ : null,
+ chart: {
+ x: this.shiftToTimezone(x, safeTimezone, format),
+ occurrences,
+ affectedUsers: affectedUsersChart,
+ },
+ timeBucket,
+ }
+ }
+
+ async getErrorAffectedSessions(
+ pid: string,
+ eid: string,
+ groupFrom: string,
+ groupTo: string,
+ take: number = 10,
+ skip: number = 0,
+ ): Promise<{ sessions: any[]; total: number }> {
+ const queryCount = `
+ SELECT count(DISTINCT psid) as total
+ FROM errors
+ WHERE pid = {pid:FixedString(12)}
+ AND eid = {eid:FixedString(32)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `
+
+ const querySessions = `
+ SELECT DISTINCT
+ errors.psid as psid,
+ any(errors.profileId) as profileId,
+ any(analytics.cc) as cc,
+ any(analytics.br) as br,
+ any(analytics.os) as os,
+ min(errors.created) as firstErrorAt,
+ max(errors.created) as lastErrorAt,
+ count(*) as errorCount
+ FROM errors
+ LEFT JOIN analytics ON errors.psid = analytics.psid AND errors.pid = analytics.pid
+ WHERE errors.pid = {pid:FixedString(12)}
+ AND errors.eid = {eid:FixedString(32)}
+ AND errors.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY errors.psid
+ ORDER BY lastErrorAt DESC
+ LIMIT ${take}
+ OFFSET ${skip}
+ `
+
+ const params = { pid, eid, groupFrom, groupTo }
+
+ const [countResult, sessionsResult] = await Promise.all([
+ clickhouse
+ .query({ query: queryCount, query_params: params })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data[0]),
+ clickhouse
+ .query({ query: querySessions, query_params: params })
+ .then(resultSet => resultSet.json<any>())
+ .then(({ data }) => data),
+ ])
+
+ return {
+ sessions: sessionsResult,
+ total: Number(countResult?.total || 0),
+ }
+ }
+
getErrorID(errorDTO: ErrorDto): string {
const { name, message, colno, lineno, filename } = errorDTO
diff --git a/backend/apps/community/src/analytics/dto/get-error-overview.dto.ts b/backend/apps/community/src/analytics/dto/get-error-overview.dto.ts
new file mode 100644
index 000000000..908941164
--- /dev/null
+++ b/backend/apps/community/src/analytics/dto/get-error-overview.dto.ts
@@ -0,0 +1,20 @@
+import { PickType, ApiProperty } from '@nestjs/swagger'
+import { GetDataDto } from './getData.dto'
+
+export class GetErrorOverviewDto extends PickType(GetDataDto, [
+ 'pid',
+ 'period',
+ 'from',
+ 'to',
+ 'filters',
+ 'timezone',
+ 'timeBucket',
+] as const) {
+ @ApiProperty({
+ example: {
+ showResolved: true,
+ },
+ description: 'Errors list options',
+ })
+ options?: string
+}
diff --git a/backend/apps/community/src/feature-flag/entity/feature-flag.entity.ts b/backend/apps/community/src/feature-flag/entity/feature-flag.entity.ts
index 7c1fb4660..e640fb350 100644
--- a/backend/apps/community/src/feature-flag/entity/feature-flag.entity.ts
+++ b/backend/apps/community/src/feature-flag/entity/feature-flag.entity.ts
@@ -2,9 +2,9 @@ import {
FeatureFlagType,
TargetingRule,
EvaluatableFeatureFlag,
-} from '../../../../../libs/shared/src/feature-flag'
+} from '../evaluation'
-// Re-export shared types for backward compatibility
+// Re-export types for backward compatibility
export { FeatureFlagType, TargetingRule, EvaluatableFeatureFlag }
export interface FeatureFlag extends EvaluatableFeatureFlag {
diff --git a/backend/apps/community/src/feature-flag/evaluation.ts b/backend/apps/community/src/feature-flag/evaluation.ts
new file mode 100644
index 000000000..4af27dc9d
--- /dev/null
+++ b/backend/apps/community/src/feature-flag/evaluation.ts
@@ -0,0 +1,171 @@
+import * as crypto from 'crypto'
+
+/**
+ * Feature flag type enum
+ */
+export enum FeatureFlagType {
+ BOOLEAN = 'boolean',
+ ROLLOUT = 'rollout',
+}
+
+/**
+ * Targeting rule interface for feature flags
+ */
+export interface TargetingRule {
+ column: string // cc, dv, br, os, pg, etc.
+ filter: string // value to match
+ isExclusive: boolean // true = exclude, false = include
+}
+
+/**
+ * Minimal feature flag interface required for evaluation
+ * Both cloud (TypeORM entity) and community (ClickHouse) flags should satisfy this
+ */
+export interface EvaluatableFeatureFlag {
+ key: string
+ enabled: boolean
+ flagType: FeatureFlagType
+ rolloutPercentage: number
+ targetingRules: TargetingRule[] | null
+}
+
+/**
+ * Evaluates all feature flags for a project given visitor attributes
+ */
+export function evaluateFlags(
+ flags: EvaluatableFeatureFlag[],
+ profileId: string,
+ attributes?: Record<string, string>,
+): Record<string, boolean> {
+ const result: Record<string, boolean> = {}
+
+ for (const flag of flags) {
+ result[flag.key] = evaluateFlag(flag, profileId, attributes)
+ }
+
+ return result
+}
+
+/**
+ * Evaluates a single feature flag for a visitor
+ */
+export function evaluateFlag(
+ flag: EvaluatableFeatureFlag,
+ profileId: string,
+ attributes?: Record<string, string>,
+): boolean {
+ // If flag is disabled, always return false
+ if (!flag.enabled) {
+ return false
+ }
+
+ // Check targeting rules if any exist
+ if (flag.targetingRules && flag.targetingRules.length > 0) {
+ const matchesTargeting = matchesTargetingRules(
+ flag.targetingRules,
+ attributes,
+ )
+ if (!matchesTargeting) {
+ return false
+ }
+ }
+
+ // For boolean flags, return true if enabled and targeting matches
+ if (flag.flagType === FeatureFlagType.BOOLEAN) {
+ return true
+ }
+
+ // For rollout flags, use percentage-based rollout
+ if (flag.flagType === FeatureFlagType.ROLLOUT) {
+ return isInRolloutPercentage(flag.key, flag.rolloutPercentage, profileId)
+ }
+
+ return false
+}
+
+/**
+ * Checks if visitor attributes match the targeting rules
+ * Rules are evaluated as AND (all rules must match)
+ */
+export function matchesTargetingRules(
+ rules: TargetingRule[],
+ attributes?: Record<string, string>,
+): boolean {
+ if (!attributes) {
+ // If no attributes provided, we can't match any rules
+ // Return true to be permissive (flag will be shown)
+ return true
+ }
+
+ for (const rule of rules) {
+ const attributeValue = attributes[rule.column]
+
+ // Check if we have the attribute
+ if (attributeValue === undefined) {
+ // If attribute not provided, skip this rule (be permissive)
+ continue
+ }
+
+ const matches = matchesRule(attributeValue, rule.filter)
+
+ // If isExclusive (exclude), we want the rule to NOT match
+ // If not isExclusive (include), we want the rule to match
+ if (rule.isExclusive) {
+ // Exclude: if it matches, targeting fails
+ if (matches) {
+ return false
+ }
+ } else {
+ // Include: if it doesn't match, targeting fails
+ if (!matches) {
+ return false
+ }
+ }
+ }
+
+ return true
+}
+
+/**
+ * Checks if an attribute value matches a filter value
+ * Supports case-insensitive matching
+ */
+export function matchesRule(
+ attributeValue: string,
+ filterValue: string,
+): boolean {
+ // Case-insensitive exact match
+ return attributeValue.toLowerCase() === filterValue.toLowerCase()
+}
+
+/**
+ * Determines if a visitor is within the rollout percentage
+ * Uses consistent hashing based on flag key and profile ID
+ */
+export function isInRolloutPercentage(
+ flagKey: string,
+ percentage: number,
+ profileId: string,
+): boolean {
+ if (percentage >= 100) {
+ return true
+ }
+ if (percentage <= 0) {
+ return false
+ }
+
+ // Create a consistent hash based on flag key and profile ID
+ // Using SHA-256 for better cryptographic properties
+ const hash = crypto
+ .createHash('sha256')
+ .update(`${flagKey}:${profileId}`)
+ .digest('hex')
+
+ // Convert first 8 hex characters to a number (0 to 2^32-1)
+ const hashValue = parseInt(hash.substring(0, 8), 16)
+
+ // Normalize to 0-100 range
+ const normalizedValue = (hashValue / 0xffffffff) * 100
+
+ return normalizedValue < percentage
+}
diff --git a/backend/apps/community/src/feature-flag/feature-flag.service.ts b/backend/apps/community/src/feature-flag/feature-flag.service.ts
index b28b3a6d4..cc1d048d3 100644
--- a/backend/apps/community/src/feature-flag/feature-flag.service.ts
+++ b/backend/apps/community/src/feature-flag/feature-flag.service.ts
@@ -21,7 +21,7 @@ import { PaginationOptionsInterface } from '../common/pagination/pagination.resu
import {
evaluateFlag as sharedEvaluateFlag,
evaluateFlags as sharedEvaluateFlags,
-} from '../../../../libs/shared/src/feature-flag'
+} from './evaluation'
dayjs.extend(utc)
diff --git a/backend/libs/shared/src/feature-flag/index.ts b/backend/libs/shared/src/feature-flag/index.ts
deleted file mode 100644
index 44eba876e..000000000
--- a/backend/libs/shared/src/feature-flag/index.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-export {
- FeatureFlagType,
- TargetingRule,
- EvaluatableFeatureFlag,
- evaluateFlags,
- evaluateFlag,
- matchesTargetingRules,
- matchesRule,
- isInRolloutPercentage,
-} from './evaluation'
diff --git a/backend/libs/shared/src/index.ts b/backend/libs/shared/src/index.ts
deleted file mode 100644
index b6acb0e9e..000000000
--- a/backend/libs/shared/src/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './feature-flag'
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index fbc0971aa..0eae62da9 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -628,6 +628,7 @@ export const getSessions = (
export const getErrors = (
pid: string,
+ timeBucket: string,
period = '3d',
filters: any[] = [],
options: any = {},
@@ -640,7 +641,7 @@ export const getErrors = (
) =>
api
.get(
- `log/errors?pid=${pid}&take=${take}&skip=${skip}&period=${period}&filters=${JSON.stringify(
+ `log/errors?pid=${pid}&timeBucket=${timeBucket}&take=${take}&skip=${skip}&period=${period}&filters=${JSON.stringify(
filters,
)}&options=${JSON.stringify(options)}&from=${from}&to=${to}&timezone=${timezone}`,
{
@@ -772,6 +773,99 @@ export const getError = (
throw error.response
})
+export interface ErrorOverviewStats {
+ totalErrors: number
+ uniqueErrors: number
+ affectedSessions: number
+ affectedUsers: number
+ errorRate: number
+}
+
+export interface MostFrequentError {
+ eid: string
+ name: string
+ message: string
+ count: number
+ usersAffected: number
+ lastSeen: string
+}
+
+export interface ErrorOverviewChart {
+ x: string[]
+ occurrences: number[]
+ affectedUsers: number[]
+}
+
+export interface ErrorOverviewResponse {
+ stats: ErrorOverviewStats
+ mostFrequentError: MostFrequentError | null
+ chart: ErrorOverviewChart
+ timeBucket: string
+}
+
+export const getErrorOverview = (
+ pid: string,
+ timeBucket = 'hour',
+ period = '7d',
+ filters: any[] = [],
+ options: any = {},
+ from = '',
+ to = '',
+ timezone = '',
+ password: string | undefined = '',
+) =>
+ api
+ .get(
+ `log/error-overview?pid=${pid}&timeBucket=${timeBucket}&period=${period}&filters=${JSON.stringify(
+ filters,
+ )}&options=${JSON.stringify(options)}&from=${from}&to=${to}&timezone=${timezone}`,
+ {
+ headers: {
+ 'x-password': password,
+ },
+ },
+ )
+ .then((response): ErrorOverviewResponse => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
+ })
+
+export interface ErrorAffectedSession {
+ psid: string
+ profileId: string | null
+ cc: string | null
+ br: string | null
+ os: string | null
+ firstErrorAt: string
+ lastErrorAt: string
+ errorCount: number
+}
+
+export const getErrorSessions = (
+ pid: string,
+ eid: string,
+ timeBucket = 'hour',
+ period = '7d',
+ from = '',
+ to = '',
+ take = 10,
+ skip = 0,
+ password: string | undefined = '',
+) =>
+ api
+ .get(
+ `log/error-sessions?pid=${pid}&eid=${eid}&timeBucket=${timeBucket}&period=${period}&from=${from}&to=${to}&take=${take}&skip=${skip}`,
+ {
+ headers: {
+ 'x-password': password,
+ },
+ },
+ )
+ .then((response): { sessions: ErrorAffectedSession[]; total: number } => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
+ })
+
export const getFunnelData = (
pid: string,
period = '3d',
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index c04e8b785..3f947c77a 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -75,6 +75,8 @@ export interface SwetrixError {
count: number
last_seen: string
status: 'active' | 'regressed' | 'fixed' | 'resolved'
+ users: number
+ sessions: number
}
export interface SwetrixErrorDetails extends SwetrixError {
diff --git a/web/app/pages/Project/Errors/View/ErrorsView.tsx b/web/app/pages/Project/Errors/View/ErrorsView.tsx
new file mode 100644
index 000000000..6a913ce58
--- /dev/null
+++ b/web/app/pages/Project/Errors/View/ErrorsView.tsx
@@ -0,0 +1,601 @@
+import type { ChartOptions } from 'billboard.js'
+import { area, bar } from 'billboard.js'
+import cx from 'clsx'
+import * as d3 from 'd3'
+import dayjs from 'dayjs'
+import _isEmpty from 'lodash/isEmpty'
+import _map from 'lodash/map'
+import _size from 'lodash/size'
+import {
+ BugIcon,
+ PercentIcon,
+ UsersIcon,
+ MonitorIcon,
+ ChevronRightIcon,
+ AlertTriangleIcon,
+ UserIcon,
+} from 'lucide-react'
+import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link, useLocation } from 'react-router'
+import { ClientOnly } from 'remix-utils/client-only'
+import { toast } from 'sonner'
+
+import { getErrors, getErrorOverview, type ErrorOverviewResponse } from '~/api'
+import {
+ TimeFormat,
+ tbsFormatMapper,
+ tbsFormatMapper24h,
+ tbsFormatMapperTooltip,
+ tbsFormatMapperTooltip24h,
+ chartTypes,
+} from '~/lib/constants'
+import { SwetrixError } from '~/lib/models/Project'
+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { getFormatDate, typeNameMapping } from '~/pages/Project/View/ViewProject.helpers'
+import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import { Badge } from '~/ui/Badge'
+import BillboardChart from '~/ui/BillboardChart'
+import Loader from '~/ui/Loader'
+import LoadingBar from '~/ui/LoadingBar'
+import { Text } from '~/ui/Text'
+import Tooltip from '~/ui/Tooltip'
+import { getRelativeDateIfPossible } from '~/utils/date'
+import { nFormatter } from '~/utils/generic'
+
+import Filters from '../../View/components/Filters'
+import NoEvents from '../../View/components/NoEvents'
+
+// Calculate optimal Y axis ticks
+const calculateOptimalTicks = (data: number[], targetCount: number = 6): number[] => {
+ const validData = data.filter((n) => n !== undefined && n !== null && Number.isFinite(n))
+
+ if (validData.length === 0) {
+ return [0, 1]
+ }
+
+ const min = Math.min(...validData)
+ const max = Math.max(...validData)
+
+ if (min === max) {
+ return max === 0 ? [0, 1] : [0, max * 1.2]
+ }
+
+ const upperBound = Math.ceil(max * 1.2)
+ const roughStep = upperBound / (targetCount - 1)
+
+ let niceStep: number
+ if (roughStep <= 1) niceStep = 1
+ else if (roughStep <= 2) niceStep = 2
+ else if (roughStep <= 5) niceStep = 5
+ else if (roughStep <= 10) niceStep = 10
+ else if (roughStep <= 20) niceStep = 20
+ else if (roughStep <= 25) niceStep = 25
+ else if (roughStep <= 50) niceStep = 50
+ else {
+ const magnitude = Math.pow(10, Math.floor(Math.log10(roughStep)))
+ const normalized = roughStep / magnitude
+ if (normalized <= 2) niceStep = 2 * magnitude
+ else if (normalized <= 5) niceStep = 5 * magnitude
+ else niceStep = 10 * magnitude
+ }
+
+ const ticks: number[] = []
+ for (let i = 0; i <= upperBound; i += niceStep) {
+ ticks.push(i)
+ }
+
+ if (ticks[ticks.length - 1] < max) {
+ ticks.push(ticks[ticks.length - 1] + niceStep)
+ }
+
+ return ticks
+}
+
+// Chart settings for error trends chart
+const getErrorTrendsChartSettings = (
+ chartData: { x: string[]; occurrences: number[]; affectedUsers: number[] },
+ timeBucket: string,
+ timeFormat: string,
+ chartType: string,
+ dataNames: Record<string, string>,
+): ChartOptions => {
+ const xAxisSize = _size(chartData.x)
+
+ const columns: any[] = [
+ ['x', ..._map(chartData.x, (el) => dayjs(el).toDate())],
+ ['occurrences', ...chartData.occurrences],
+ ['affectedUsers', ...chartData.affectedUsers],
+ ]
+
+ const allYValues: number[] = [...chartData.occurrences, ...chartData.affectedUsers].filter(
+ (n) => n !== undefined && n !== null,
+ )
+
+ const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+
+ return {
+ data: {
+ x: 'x',
+ columns,
+ types: {
+ occurrences: chartType === chartTypes.line ? area() : bar(),
+ affectedUsers: chartType === chartTypes.line ? area() : bar(),
+ },
+ colors: {
+ occurrences: '#f97316', // orange-500
+ affectedUsers: '#dc2626', // red-600
+ },
+ names: dataNames,
+ },
+ grid: {
+ y: {
+ show: true,
+ },
+ },
+ transition: {
+ duration: 200,
+ },
+ resize: {
+ auto: true,
+ timer: false,
+ },
+ axis: {
+ x: {
+ clipPath: false,
+ tick: {
+ fit: true,
+ rotate: 0,
+ format:
+ // @ts-expect-error
+ timeFormat === TimeFormat['24-hour']
+ ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
+ : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ },
+ localtime: timeFormat === TimeFormat['24-hour'],
+ type: 'timeseries',
+ },
+ y: {
+ tick: {
+ format: (d: number) => nFormatter(d, 1),
+ values: optimalTicks,
+ },
+ show: true,
+ inner: true,
+ },
+ },
+ tooltip: {
+ contents: (item: any, _: any, __: any, color: any) => {
+ if (!item || _isEmpty(item) || !item[0]) {
+ return ''
+ }
+ return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-800 rounded-md ring-1 ring-black/10 px-3 py-1'>
+ <li class='font-semibold'>${
+ timeFormat === TimeFormat['24-hour']
+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
+ }</li>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ ${_map(item, (el: { id: string; name: string; value: string }) => {
+ return `
+ <li class='flex justify-between'>
+ <div class='flex justify-items-start'>
+ <div class='w-3 h-3 rounded-xs mt-1.5 mr-2' style=background-color:${color(el.id)}></div>
+ <span>${el.name}</span>
+ </div>
+ <span class='pl-4'>${el.value}</span>
+ </li>
+ `
+ }).join('')}</ul>`
+ },
+ },
+ point:
+ chartType === chartTypes.bar
+ ? {}
+ : {
+ focus: {
+ only: xAxisSize > 1,
+ },
+ pattern: ['circle'],
+ r: 2,
+ },
+ legend: {
+ item: {
+ tile: {
+ type: 'circle',
+ width: 10,
+ r: 3,
+ },
+ },
+ },
+ area: {
+ linearGradient: true,
+ },
+ bar: {
+ linearGradient: true,
+ },
+ }
+}
+
+// Stat Card Component
+interface StatCardProps {
+ icon: React.ReactNode
+ value: string | number
+ label: string
+}
+
+const StatCard = ({ icon, value, label }: StatCardProps) => (
+ <div className='relative overflow-hidden rounded-xl border border-gray-200 bg-white p-4 dark:border-slate-700 dark:bg-slate-800'>
+ <div className='pointer-events-none absolute -bottom-5 -left-5 opacity-10 [&>svg]:size-24'>{icon}</div>
+ <div className='relative'>
+ <Text as='p' size='3xl' weight='bold' className='leading-tight'>
+ {value}
+ </Text>
+ <Text as='p' size='sm' colour='secondary' className='leading-tight'>
+ {label}
+ </Text>
+ </div>
+ </div>
+)
+
+// Most Frequent Error Card
+// Error Item Component
+interface ErrorItemProps {
+ error: SwetrixError
+}
+
+const ErrorItem = ({ error }: ErrorItemProps) => {
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
+ const location = useLocation()
+
+ const lastSeen = useMemo(() => {
+ return getRelativeDateIfPossible(error.last_seen, language)
+ }, [error.last_seen, language])
+
+ const status: {
+ label: string
+ colour: 'red' | 'yellow' | 'slate'
+ } = useMemo(() => {
+ if (error.status === 'active') {
+ return {
+ label: t('error.status.active'),
+ colour: 'red',
+ }
+ }
+
+ if (error.status === 'regressed') {
+ return {
+ label: t('error.status.regressed'),
+ colour: 'yellow',
+ }
+ }
+
+ return {
+ label: t('error.status.resolved'),
+ colour: 'slate',
+ }
+ }, [error.status, t])
+
+ const params = new URLSearchParams(location.search)
+ params.set('eid', error.eid)
+
+ // Truncate long error names/messages
+ const maxNameLength = 80
+ const maxMessageLength = 150
+ const displayName = error.name.length > maxNameLength ? `${error.name.slice(0, maxNameLength)}...` : error.name
+ const displayMessage =
+ error.message && error.message.length > maxMessageLength
+ ? `${error.message.slice(0, maxMessageLength)}...`
+ : error.message
+
+ return (
+ <Link to={{ search: params.toString() }}>
+ <li className='relative mb-3 flex cursor-pointer justify-between gap-x-6 overflow-hidden rounded-xl border border-gray-200 bg-gray-50 px-4 py-4 transition-colors hover:bg-gray-200/70 sm:px-6 dark:border-slate-800/25 dark:bg-slate-800/70 dark:hover:bg-slate-700/60'>
+ <div className='flex min-w-0 gap-x-4'>
+ <div className='min-w-0 flex-auto'>
+ <div className='flex items-center gap-x-2 leading-6'>
+ <Tooltip
+ text={error.name}
+ tooltipNode={
+ <Text size='sm' weight='bold' className='pb-0.5'>
+ {displayName}
+ </Text>
+ }
+ />
+ {error.filename ? (
+ <>
+ <svg viewBox='0 0 2 2' className='h-0.5 w-0.5 flex-none self-center fill-gray-400'>
+ <circle cx={1} cy={1} r={1} />
+ </svg>
+ <Text size='xs' weight='normal' colour='muted' className='mx-1 max-w-[200px] truncate'>
+ {error.filename}
+ </Text>
+ </>
+ ) : null}
+ </div>
+ {displayMessage ? (
+ <Tooltip
+ text={error.message}
+ tooltipNode={
+ <Text as='p' size='sm' colour='muted' className='mt-1 flex leading-5'>
+ {displayMessage}
+ </Text>
+ }
+ />
+ ) : null}
+ <p className='mt-1 flex items-center gap-x-2 text-sm leading-5 text-gray-500 dark:text-gray-300'>
+ <Badge className='mr-2 sm:hidden' label={status.label} colour={status.colour} />
+ {lastSeen}
+ <svg viewBox='0 0 2 2' className='h-0.5 w-0.5 flex-none fill-gray-400 sm:hidden'>
+ <circle cx={1} cy={1} r={1} />
+ </svg>
+ <span className='sm:hidden'>
+ {t('dashboard.xOccurrences', {
+ x: error.count,
+ })}
+ </span>
+ </p>
+ <p className='mt-2 flex text-xs leading-5 text-gray-500 sm:hidden dark:text-gray-300'>
+ <span className='mr-3 flex items-center' title={t('project.affectedUsers')}>
+ <UserIcon className='mr-1 size-4' strokeWidth={1.5} /> {error.users}
+ </span>
+ <span className='flex items-center' title={t('project.affectedSessions')}>
+ <MonitorIcon className='mr-1 size-4' strokeWidth={1.5} /> {error.sessions}
+ </span>
+ </p>
+ </div>
+ </div>
+ <div className='flex shrink-0 items-center gap-x-4'>
+ <div className='hidden sm:flex sm:flex-col sm:items-end'>
+ <div className='flex items-center gap-x-3 text-sm leading-6 text-gray-900 dark:text-gray-50'>
+ <span className='flex items-center' title={t('dashboard.xOccurrences', { x: error.count })}>
+ <AlertTriangleIcon className='mr-1 size-4' strokeWidth={1.5} /> {error.count}
+ </span>
+ <span className='flex items-center' title={t('project.xAffectedUsers', { x: error.users })}>
+ <UserIcon className='mr-1 size-4' strokeWidth={1.5} /> {error.users}
+ </span>
+ <span className='flex items-center' title={t('project.xAffectedSessions', { x: error.sessions })}>
+ <MonitorIcon className='mr-1 size-4' strokeWidth={1.5} /> {error.sessions}
+ </span>
+ </div>
+ <Badge label={status.label} colour={status.colour} />
+ </div>
+ <ChevronRightIcon className='h-5 w-5 flex-none text-gray-400' />
+ </div>
+ </li>
+ </Link>
+ )
+}
+
+const ErrorsView = () => {
+ const { id } = useCurrentProject()
+ const projectPassword = useProjectPassword(id)
+ const { timeBucket, timeFormat, period, dateRange, timezone, filters } = useViewProjectContext()
+ const { t } = useTranslation('common')
+
+ const from = dateRange ? getFormatDate(dateRange[0]) : ''
+ const to = dateRange ? getFormatDate(dateRange[1]) : ''
+ const tnMapping = typeNameMapping(t)
+
+ // Overview state
+ const [overviewLoading, setOverviewLoading] = useState<boolean | null>(null)
+ const [overview, setOverview] = useState<ErrorOverviewResponse | null>(null)
+ const isMountedRef = useRef(true)
+
+ // Errors list state
+ const [errorsLoading, setErrorsLoading] = useState<boolean | null>(null)
+ const [errors, setErrors] = useState<SwetrixError[]>([])
+ const [errorsSkip, setErrorsSkip] = useState(0)
+ const [canLoadMoreErrors, setCanLoadMoreErrors] = useState(false)
+ const errorsRequestIdRef = useRef(0)
+
+ const ERRORS_TAKE = 30
+
+ // Cleanup on unmount
+ useEffect(() => {
+ isMountedRef.current = true
+ return () => {
+ isMountedRef.current = false
+ }
+ }, [])
+
+ const loadOverview = useCallback(async () => {
+ if (overviewLoading) return
+
+ setOverviewLoading(true)
+ try {
+ const result = await getErrorOverview(
+ id,
+ timeBucket,
+ period,
+ filters,
+ { showResolved: false },
+ from,
+ to,
+ timezone || '',
+ projectPassword,
+ )
+ if (isMountedRef.current) {
+ setOverview(result)
+ }
+ } catch (reason: any) {
+ console.error('[ErrorsView] Failed to load overview:', reason)
+ if (isMountedRef.current) {
+ toast.error(reason?.message || t('apiNotifications.somethingWentWrong'))
+ }
+ } finally {
+ if (isMountedRef.current) {
+ setOverviewLoading(false)
+ }
+ }
+ }, [id, timeBucket, period, filters, from, to, timezone, projectPassword, overviewLoading, t])
+
+ const loadErrors = useCallback(
+ async (forcedSkip?: number, override?: boolean) => {
+ if (errorsLoading && !override) return
+
+ const currentRequestId = ++errorsRequestIdRef.current
+ setErrorsLoading(true)
+
+ const skip = forcedSkip !== undefined ? forcedSkip : errorsSkip
+
+ try {
+ const { errors: newErrors } = await getErrors(
+ id,
+ timeBucket,
+ period,
+ filters,
+ { showResolved: false },
+ from,
+ to,
+ ERRORS_TAKE,
+ skip,
+ timezone || '',
+ projectPassword,
+ )
+
+ if (!isMountedRef.current || currentRequestId !== errorsRequestIdRef.current) return
+
+ if (skip === 0) {
+ setErrors(newErrors)
+ } else {
+ setErrors((prev) => [...prev, ...newErrors])
+ }
+
+ setErrorsSkip(skip + ERRORS_TAKE)
+ setCanLoadMoreErrors(newErrors.length >= ERRORS_TAKE)
+ } catch (reason: any) {
+ console.error('[ErrorsView] Failed to load errors:', reason)
+ if (isMountedRef.current && currentRequestId === errorsRequestIdRef.current) {
+ toast.error(reason?.message || t('apiNotifications.somethingWentWrong'))
+ }
+ } finally {
+ if (isMountedRef.current && currentRequestId === errorsRequestIdRef.current) {
+ setErrorsLoading(false)
+ }
+ }
+ },
+ [id, timeBucket, period, filters, from, to, timezone, projectPassword, errorsLoading, errorsSkip, t],
+ )
+
+ // Load data on mount and when params change
+ useEffect(() => {
+ // Don't load until we have valid context values
+ if (!id || !timeBucket || !period) return
+
+ loadOverview()
+ setErrorsSkip(0)
+ loadErrors(0, true)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [id, period, from, to, timeBucket, timezone, filters])
+
+ const chartOptions = useMemo(() => {
+ if (!overview?.chart || !overview.chart.x || overview.chart.x.length === 0) return null
+ return getErrorTrendsChartSettings(overview.chart, timeBucket, timeFormat, chartTypes.line, {
+ occurrences: t('project.totalErrors'),
+ affectedUsers: t('project.affectedUsers'),
+ })
+ }, [overview?.chart, timeBucket, timeFormat, t])
+
+ const hasErrors = !_isEmpty(errors) || overview?.stats?.totalErrors
+
+ // Initial loading state
+ if ((overviewLoading === null || overviewLoading) && !overview && _isEmpty(errors)) {
+ return <Loader />
+ }
+
+ return (
+ <div>
+ {/* Loading bar for refreshes */}
+ {overviewLoading && overview ? <LoadingBar /> : null}
+
+ {/* Filters */}
+ {hasErrors ? <Filters className='mt-0 mb-4' tnMapping={tnMapping} /> : null}
+
+ {/* No errors state */}
+ {!hasErrors && errorsLoading === false && overviewLoading === false ? <NoEvents filters={filters} /> : null}
+
+ {hasErrors ? (
+ <>
+ {/* Chart and Stats Row */}
+ <div className='flex flex-col gap-2 lg:flex-row'>
+ {/* Error Trends Chart - Left side */}
+ {chartOptions && overview?.chart ? (
+ <div className='w-full rounded-xl border border-gray-200 bg-white p-4 lg:w-[65%] dark:border-slate-700 dark:bg-slate-800'>
+ <BillboardChart options={chartOptions} className='h-[220px]' />
+ </div>
+ ) : null}
+
+ {/* Stats Grid - Right side as 2x2 */}
+ <div className='grid w-full grid-cols-2 gap-2 lg:w-[35%]'>
+ <StatCard
+ icon={<BugIcon className='text-red-600' strokeWidth={1.5} />}
+ value={nFormatter(overview?.stats?.totalErrors || 0, 1)}
+ label={t('project.totalErrors')}
+ />
+ <StatCard
+ icon={<PercentIcon className='text-orange-600' strokeWidth={1.5} />}
+ value={`${overview?.stats?.errorRate || 0}%`}
+ label={t('project.errorRate')}
+ />
+ <StatCard
+ icon={<UsersIcon className='text-blue-600' strokeWidth={1.5} />}
+ value={nFormatter(overview?.stats?.affectedUsers || 0, 1)}
+ label={t('project.affectedUsers')}
+ />
+ <StatCard
+ icon={<MonitorIcon className='text-purple-600' strokeWidth={1.5} />}
+ value={nFormatter(overview?.stats?.affectedSessions || 0, 1)}
+ label={t('project.affectedSessions')}
+ />
+ </div>
+ </div>
+
+ {/* Recent Errors List */}
+ <div className='mt-4'>
+ <Text as='h3' weight='semibold' className='mb-3'>
+ {t('project.recentErrors')}
+ </Text>
+ <ClientOnly
+ fallback={
+ <div className='bg-gray-50 dark:bg-slate-900'>
+ <Loader />
+ </div>
+ }
+ >
+ {() => (
+ <ul>
+ {_map(errors, (error) => (
+ <ErrorItem key={error.eid} error={error} />
+ ))}
+ </ul>
+ )}
+ </ClientOnly>
+
+ {/* Load more button */}
+ {canLoadMoreErrors ? (
+ <button
+ type='button'
+ title={t('project.loadMore')}
+ onClick={() => loadErrors()}
+ className={cx(
+ 'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
+ {
+ 'cursor-not-allowed opacity-50': errorsLoading,
+ },
+ )}
+ >
+ {t('project.loadMore')}
+ </button>
+ ) : null}
+ </div>
+ </>
+ ) : null}
+ </div>
+ )
+}
+
+export default ErrorsView
diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsx
index a91365954..c95cd491c 100644
--- a/web/app/pages/Project/View/ViewProject.helpers.tsx
+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx
@@ -1020,6 +1020,7 @@ const getSettingsError = (
rotateXAxis: boolean,
chartType: string,
annotations?: Annotation[],
+ dataNames?: Record<string, string>,
): ChartOptions => {
const xAxisSize = _size(chart.x)
@@ -1035,12 +1036,23 @@ const getSettingsError = (
position: 'start',
}))
- const columns = getColumns(chart, { occurrences: true })
+ // Build columns with both occurrences and affectedUsers if available
+ const columns: any[] = [['x', ..._map(chart.x, (el: string) => dayjs(el).toDate())]]
+
+ if (chart.occurrences) {
+ columns.push(['occurrences', ...chart.occurrences])
+ }
+ if (chart.affectedUsers) {
+ columns.push(['affectedUsers', ...chart.affectedUsers])
+ }
const allYValues: number[] = []
if (chart.occurrences) {
allYValues.push(...chart.occurrences.filter((n: any) => n !== undefined && n !== null))
}
+ if (chart.affectedUsers) {
+ allYValues.push(...chart.affectedUsers.filter((n: any) => n !== undefined && n !== null))
+ }
const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
@@ -1052,17 +1064,25 @@ const getSettingsError = (
regionStart = dayjs(chart.x[xAxisSize - 1]).toDate()
}
+ const types: Record<string, any> = {
+ occurrences: chartType === chartTypes.line ? area() : bar(),
+ }
+ if (chart.affectedUsers) {
+ types.affectedUsers = chartType === chartTypes.line ? area() : bar()
+ }
+
+ const colors: Record<string, string> = {
+ occurrences: '#f97316', // orange-500
+ affectedUsers: '#dc2626', // red-600
+ }
+
return {
data: {
x: 'x',
columns,
- types: {
- occurrences: chartType === chartTypes.line ? area() : bar(),
- },
- colors: {
- occurrences: '#dc2626',
- occurrencesCompare: 'rgba(220, 38, 38, 0.4)',
- },
+ types,
+ colors,
+ names: dataNames,
regions: {
occurrences: [
{
@@ -1155,7 +1175,6 @@ const getSettingsError = (
r: 3,
},
},
- hide: ['uniqueCompare', 'totalCompare', 'bounceCompare', 'sessionDurationCompare'],
},
area: {
linearGradient: true,
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 149e969cd..6aa71cccd 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -170,6 +170,7 @@ import routes from '~/utils/routes'
import { useCurrentProject, useProjectPassword } from '../../../providers/CurrentProjectProvider'
import ProjectAlertsView from '../Alerts/View'
import AskAIView from '../AskAI'
+import ErrorsView from '../Errors/View/ErrorsView'
import FeatureFlagsView from '../FeatureFlags/View'
import GoalsView from '../Goals/View'
@@ -181,7 +182,6 @@ import CustomEventsSubmenu from './components/CustomEventsSubmenu'
import CustomMetrics from './components/CustomMetrics'
import { ErrorChart } from './components/ErrorChart'
import { ErrorDetails } from './components/ErrorDetails'
-import { Errors } from './components/Errors'
import Filters from './components/Filters'
const CaptchaView = lazy(() => import('./components/CaptchaView'))
import { FunnelChart } from './components/FunnelChart'
@@ -4071,33 +4071,7 @@ const ViewProjectContent = () => {
) : null}
</>
) : null}
- {activeTab === PROJECT_TABS.errors && !activeEID ? (
- <>
- {!_isEmpty(errors) ? <Filters tnMapping={tnMapping} /> : null}
- {(errorsLoading === null || errorsLoading) && _isEmpty(errors) ? <Loader /> : null}
- {typeof errorsLoading === 'boolean' && !errorsLoading && _isEmpty(errors) ? (
- <NoEvents filters={filters} />
- ) : null}
- <Errors errors={errors} />
- {canLoadMoreErrors ? (
- <button
- type='button'
- title={t('project.loadMore')}
- onClick={() => loadErrors()}
- className={cx(
- 'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
- {
- 'cursor-not-allowed opacity-50': errorsLoading,
- hidden: errorsLoading && _isEmpty(errors),
- },
- )}
- >
- <DownloadIcon className='mr-2 h-5 w-5' strokeWidth={1.5} />
- {t('project.loadMore')}
- </button>
- ) : null}
- </>
- ) : null}
+ {activeTab === PROJECT_TABS.errors && !activeEID ? <ErrorsView /> : null}
{activeTab === PROJECT_TABS.errors && activeEID ? (
<>
<div className='mx-auto mt-2 mb-3 flex max-w-max items-center space-x-4 lg:mx-0'>
@@ -4111,7 +4085,16 @@ const ViewProjectContent = () => {
{t('project.backToErrors')}
</Link>
</div>
- {activeError?.details ? <ErrorDetails details={activeError.details} /> : null}
+ {activeError?.details ? (
+ <ErrorDetails
+ details={activeError.details}
+ period={period}
+ from={dateRange ? getFormatDate(dateRange[0]) : undefined}
+ to={dateRange ? getFormatDate(dateRange[1]) : undefined}
+ timeBucket={timeBucket}
+ projectPassword={projectPassword}
+ />
+ ) : null}
{activeError?.chart ? (
<div
onContextMenu={(e) => handleChartContextMenu(e, activeError?.chart?.x)}
diff --git a/web/app/pages/Project/View/components/ErrorChart.tsx b/web/app/pages/Project/View/components/ErrorChart.tsx
index fb35aa8fa..2dbe51a11 100644
--- a/web/app/pages/Project/View/components/ErrorChart.tsx
+++ b/web/app/pages/Project/View/components/ErrorChart.tsx
@@ -1,5 +1,6 @@
import { ChartOptions } from 'billboard.js'
import React, { useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
import { Annotation } from '~/lib/models/Project'
@@ -11,12 +12,13 @@ interface ErrorChartProps {
chart?: {
x: string[]
occurrences: number[]
+ affectedUsers?: number[]
}
timeBucket?: string
timeFormat: string
rotateXAxis: boolean
chartType: string
- dataNames: any
+ dataNames?: Record<string, string>
className?: string
annotations?: Annotation[]
}
@@ -27,13 +29,24 @@ export const ErrorChart = ({
timeFormat,
rotateXAxis,
chartType,
- dataNames,
+ dataNames: customDataNames,
className,
annotations,
}: ErrorChartProps) => {
+ const { t } = useTranslation('common')
+
+ const dataNames = useMemo(() => {
+ return (
+ customDataNames || {
+ occurrences: t('project.totalErrors'),
+ affectedUsers: t('project.affectedUsers'),
+ }
+ )
+ }, [customDataNames, t])
+
const options: ChartOptions = useMemo(() => {
- return getSettingsError(chart, timeBucket as string, timeFormat, rotateXAxis, chartType, annotations)
- }, [chart, timeBucket, timeFormat, rotateXAxis, chartType, annotations])
+ return getSettingsError(chart, timeBucket as string, timeFormat, rotateXAxis, chartType, annotations, dataNames)
+ }, [chart, timeBucket, timeFormat, rotateXAxis, chartType, annotations, dataNames])
const deps = useMemo(
() => [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames, annotations],
diff --git a/web/app/pages/Project/View/components/ErrorDetails.tsx b/web/app/pages/Project/View/components/ErrorDetails.tsx
index e22a09985..120c66af3 100644
--- a/web/app/pages/Project/View/components/ErrorDetails.tsx
+++ b/web/app/pages/Project/View/components/ErrorDetails.tsx
@@ -1,26 +1,151 @@
import { ChevronDownIcon, ChevronUpIcon, ClipboardIcon, CheckIcon } from '@heroicons/react/24/outline'
-import { useMemo, useState } from 'react'
+import _isEmpty from 'lodash/isEmpty'
+import _map from 'lodash/map'
+import { BugIcon, FileCodeIcon, CalendarIcon, HashIcon, ExternalLinkIcon } from 'lucide-react'
+import { useMemo, useState, useEffect, useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { Link, useLocation } from 'react-router'
+import { getErrorSessions, type ErrorAffectedSession } from '~/api'
+import { BROWSER_LOGO_MAP, OS_LOGO_MAP, OS_LOGO_MAP_DARK } from '~/lib/constants'
import { SwetrixErrorDetails } from '~/lib/models/Project'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import { useTheme } from '~/providers/ThemeProvider'
+import { Badge } from '~/ui/Badge'
+import Button from '~/ui/Button'
+import Loader from '~/ui/Loader'
+import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
import { getRelativeDateIfPossible } from '~/utils/date'
-import { MetricCard } from './MetricCards'
+import CCRow from './CCRow'
interface ErrorDetailsProps {
details: SwetrixErrorDetails
+ period?: string
+ from?: string
+ to?: string
+ timeBucket?: string
+ projectPassword?: string
}
-export const ErrorDetails = ({ details }: ErrorDetailsProps) => {
+// Stat Item Component
+const StatItem = ({ icon, label, value }: { icon: React.ReactNode; label: string; value: string | number }) => (
+ <div>
+ <div className='mb-0.5 flex items-center gap-1.5 text-[10px] font-medium tracking-wide text-gray-600 uppercase dark:text-gray-400'>
+ {icon}
+ {label}
+ </div>
+ <div className='text-lg font-semibold text-gray-900 dark:text-white'>{value}</div>
+ </div>
+)
+
+// Browser Icon Component
+const BrowserIcon = ({ browser }: { browser: string | null }) => {
+ if (!browser) return null
+
+ const logoUrl = BROWSER_LOGO_MAP[browser as keyof typeof BROWSER_LOGO_MAP]
+
+ if (!logoUrl) return null
+
+ return <img src={logoUrl} className='h-4 w-4' alt='' />
+}
+
+// OS Icon Component
+const OSIcon = ({ os, theme }: { os: string | null; theme: string }) => {
+ if (!os) return null
+
+ const logoPathLight = OS_LOGO_MAP[os as keyof typeof OS_LOGO_MAP]
+ const logoPathDark = OS_LOGO_MAP_DARK[os as keyof typeof OS_LOGO_MAP_DARK]
+
+ let logoPath = theme === 'dark' ? logoPathDark : logoPathLight
+ logoPath ||= logoPathLight
+
+ if (!logoPath) return null
+
+ return <img src={`/${logoPath}`} className='h-4 w-4' alt='' />
+}
+
+// Affected Session Row
+interface SessionRowProps {
+ session: ErrorAffectedSession
+}
+
+const SessionRow = ({ session }: SessionRowProps) => {
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
+ const { theme } = useTheme()
+ const location = useLocation()
+
+ const lastErrorAt = useMemo(() => {
+ return getRelativeDateIfPossible(session.lastErrorAt, language)
+ }, [session.lastErrorAt, language])
+
+ const params = new URLSearchParams(location.search)
+ params.delete('eid')
+ params.set('psid', session.psid)
+ const sessionUrl = `?${params.toString()}&tab=sessions`
+
+ return (
+ <Link
+ to={sessionUrl}
+ className='flex items-center justify-between gap-3 rounded-lg border border-gray-100 bg-gray-50 p-3 transition-colors hover:border-gray-200 hover:bg-gray-100 dark:border-slate-700/50 dark:bg-slate-800/50 dark:hover:border-slate-600 dark:hover:bg-slate-700/50'
+ >
+ <div className='flex min-w-0 items-center gap-3'>
+ <div className='flex items-center gap-1.5'>
+ {session.cc ? <CCRow size={16} cc={session.cc} language={language} /> : null}
+ <BrowserIcon browser={session.br} />
+ <OSIcon os={session.os} theme={theme} />
+ </div>
+ <div className='min-w-0'>
+ <Text size='sm' weight='medium' truncate>
+ {session.profileId || t('project.unknownUser')}
+ </Text>
+ <Text size='xs' colour='muted'>
+ {lastErrorAt} · {session.errorCount} {t('project.occurrences').toLowerCase()}
+ </Text>
+ </div>
+ </div>
+ <ExternalLinkIcon className='size-4 shrink-0 text-gray-400' strokeWidth={1.5} />
+ </Link>
+ )
+}
+
+export const ErrorDetails = ({
+ details,
+ period = '7d',
+ from = '',
+ to = '',
+ timeBucket = 'hour',
+ projectPassword,
+}: ErrorDetailsProps) => {
const {
t,
i18n: { language },
} = useTranslation('common')
+ const { id } = useCurrentProject()
const [isStackTraceExpanded, setIsStackTraceExpanded] = useState(false)
const [isCopied, setIsCopied] = useState(false)
+ // Affected sessions state
+ const [sessions, setSessions] = useState<ErrorAffectedSession[]>([])
+ const [sessionsLoading, setSessionsLoading] = useState<boolean | null>(null)
+ const [sessionsTotal, setSessionsTotal] = useState(0)
+ const [sessionsSkip, setSessionsSkip] = useState(0)
+ const isMountedRef = useRef(true)
+
+ const SESSIONS_TAKE = 5
+
+ useEffect(() => {
+ isMountedRef.current = true
+ return () => {
+ isMountedRef.current = false
+ }
+ }, [])
+
const firstSeen = useMemo(() => {
return getRelativeDateIfPossible(details.first_seen, language)
}, [details.first_seen, language])
@@ -29,6 +154,16 @@ export const ErrorDetails = ({ details }: ErrorDetailsProps) => {
return getRelativeDateIfPossible(details.last_seen, language)
}, [details.last_seen, language])
+ const status: { label: string; colour: 'red' | 'yellow' | 'slate' } = useMemo(() => {
+ if (details.status === 'active') {
+ return { label: t('error.status.active'), colour: 'red' }
+ }
+ if (details.status === 'regressed') {
+ return { label: t('error.status.regressed'), colour: 'yellow' }
+ }
+ return { label: t('error.status.resolved'), colour: 'slate' }
+ }, [details.status, t])
+
const handleCopyStackTrace = async () => {
if (!details.stackTrace) return
@@ -41,6 +176,54 @@ export const ErrorDetails = ({ details }: ErrorDetailsProps) => {
}
}
+ const loadSessions = useCallback(
+ async (reset = false) => {
+ if (sessionsLoading) return
+
+ setSessionsLoading(true)
+ const skip = reset ? 0 : sessionsSkip
+
+ try {
+ const result = await getErrorSessions(
+ id,
+ details.eid,
+ timeBucket,
+ period,
+ from,
+ to,
+ SESSIONS_TAKE,
+ skip,
+ projectPassword,
+ )
+
+ if (!isMountedRef.current) return
+
+ if (reset) {
+ setSessions(result.sessions)
+ } else {
+ setSessions((prev) => [...prev, ...result.sessions])
+ }
+ setSessionsTotal(result.total)
+ setSessionsSkip(skip + SESSIONS_TAKE)
+ } catch (reason) {
+ console.error('[ErrorDetails] Failed to load sessions:', reason)
+ } finally {
+ if (isMountedRef.current) {
+ setSessionsLoading(false)
+ }
+ }
+ },
+ [id, details.eid, timeBucket, period, from, to, projectPassword, sessionsLoading, sessionsSkip],
+ )
+
+ // Load sessions on mount
+ useEffect(() => {
+ setSessions([])
+ setSessionsSkip(0)
+ loadSessions(true)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [details.eid, period, from, to])
+
const formatStackTraceLine = (line: string) => {
const atMatch = line.match(/(\s*at\s+)([^(]+)(\s*\(([^)]+)\))?/)
const fileMatch = line.match(/([^:]+):(\d+):(\d+)/)
@@ -79,52 +262,72 @@ export const ErrorDetails = ({ details }: ErrorDetailsProps) => {
}
const stackTraceLines = details.stackTrace ? details.stackTrace.split('\n') : []
+ const canLoadMoreSessions = sessions.length < sessionsTotal
+
+ // Truncate error message for display
+ const errorTitle = details.message ? `${details.name}: ${details.message}` : details.name
+ const shouldTruncate = errorTitle.length > 120
+ const displayTitle = shouldTruncate ? `${errorTitle.slice(0, 120)}...` : errorTitle
return (
- <div className='mb-5'>
- <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>
- <div className='flex flex-col'>
- <p className='font-bold text-slate-900 max-md:text-xl md:text-2xl dark:text-gray-50'>{`${details.name}${details.message ? `: ${details.message}` : ''}`}</p>
- <p className='text-sm font-bold text-slate-800 dark:text-gray-200'>
- {t('dashboard.atFile', {
- filename: details.filename ?? 'Unknown file',
- lineno: details.lineno ?? 'N/A',
- colno: details.colno ?? 'N/A',
- })}
- </p>
+ <div className='space-y-4'>
+ {/* Header - Similar to UserDetails */}
+ <div className='flex items-start gap-4'>
+ <div className='flex size-14 shrink-0 items-center justify-center rounded-xl bg-red-100 dark:bg-red-900/30'>
+ <BugIcon className='size-7 text-red-600 dark:text-red-400' strokeWidth={1.5} />
</div>
+ <div className='min-w-0 flex-1'>
+ <div className='flex items-center gap-2'>
+ {shouldTruncate ? (
+ <Tooltip
+ text={errorTitle}
+ tooltipNode={<h2 className='text-xl font-bold text-gray-900 dark:text-white'>{displayTitle}</h2>}
+ />
+ ) : (
+ <h2 className='text-xl font-bold text-gray-900 dark:text-white'>{displayTitle}</h2>
+ )}
+ <Badge label={status.label} colour={status.colour} />
+ </div>
+ <div className='mt-1 flex flex-wrap items-center gap-x-3 gap-y-1'>
+ {details.filename ? (
+ <div className='flex items-center gap-1 text-sm text-gray-500 dark:text-gray-400'>
+ <FileCodeIcon className='size-3.5' strokeWidth={1.5} />
+ <span className='font-mono text-xs'>
+ {details.filename}
+ {details.lineno ? `:${details.lineno}` : ''}
+ {details.colno ? `:${details.colno}` : ''}
+ </span>
+ </div>
+ ) : null}
+ <code className='text-xs text-gray-400'>{details.eid}</code>
+ </div>
+ </div>
+ </div>
- <MetricCard
- classes={{
- value: 'max-md:text-xl md:text-2xl',
- label: '[&_span]:!text-slate-800 dark:[&_span]:!text-gray-200',
- }}
- label={t('dashboard.firstSeen')}
- value={details.first_seen || 'N/A'}
- valueMapper={(value) => (
- <Tooltip className='max-w-content !w-full' tooltipNode={<span>{firstSeen}</span>} text={`${value} UTC`} />
- )}
- />
-
- <MetricCard
- classes={{
- value: 'max-md:text-xl md:text-2xl',
- label: '[&_span]:!text-slate-800 dark:[&_span]:!text-gray-200',
- }}
- label={t('dashboard.lastSeen')}
- value={details.last_seen || 'N/A'}
- valueMapper={(value) => (
- <Tooltip className='max-w-content !w-full' tooltipNode={<span>{lastSeen}</span>} text={`${value} UTC`} />
- )}
- />
+ {/* Stats Card */}
+ <div className='rounded-xl border border-gray-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-800'>
+ <div className='grid grid-cols-2 gap-y-5 sm:grid-cols-3'>
+ <StatItem
+ icon={<HashIcon className='h-3.5 w-3.5' />}
+ label={t('project.occurrences')}
+ value={details.count || 0}
+ />
+ <StatItem
+ icon={<CalendarIcon className='h-3.5 w-3.5' />}
+ label={t('dashboard.firstSeen')}
+ value={firstSeen}
+ />
+ <StatItem icon={<CalendarIcon className='h-3.5 w-3.5' />} label={t('dashboard.lastSeen')} value={lastSeen} />
+ </div>
</div>
+ {/* Stack Trace */}
{details.stackTrace ? (
- <div className='mb-5'>
- <div className='mb-2 flex items-center justify-between'>
+ <div className='rounded-xl border border-gray-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-800'>
+ <div className='mb-3 flex items-center justify-between'>
<button
onClick={() => setIsStackTraceExpanded(!isStackTraceExpanded)}
- className='flex items-center py-1 text-base font-medium text-slate-900 hover:text-slate-700 dark:text-gray-50 dark:hover:text-gray-200'
+ className='flex items-center text-sm font-medium text-gray-900 hover:text-gray-700 dark:text-gray-50 dark:hover:text-gray-200'
>
{isStackTraceExpanded ? (
<ChevronUpIcon className='mr-1 size-4' />
@@ -137,16 +340,16 @@ export const ErrorDetails = ({ details }: ErrorDetailsProps) => {
{isStackTraceExpanded ? (
<button
onClick={handleCopyStackTrace}
- className='relative flex items-center rounded-md border border-gray-50/0 bg-gray-50 p-1 text-sm font-medium text-gray-700 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200'
+ className='flex items-center rounded-md border border-gray-200 px-2 py-1 text-xs font-medium text-gray-700 hover:bg-gray-50 dark:border-slate-600 dark:text-gray-200 dark:hover:bg-slate-700'
>
{isCopied ? (
<>
- <CheckIcon className='mr-1 size-4 text-green-500' />
+ <CheckIcon className='mr-1 size-3.5 text-green-500' />
{t('project.copied')}
</>
) : (
<>
- <ClipboardIcon className='mr-1 size-4' />
+ <ClipboardIcon className='mr-1 size-3.5' />
{t('project.copy')}
</>
)}
@@ -155,12 +358,12 @@ export const ErrorDetails = ({ details }: ErrorDetailsProps) => {
</div>
{isStackTraceExpanded ? (
- <div className='rounded-lg border border-gray-300 bg-white dark:border-slate-800/60 dark:bg-slate-800/25'>
- <div className='max-h-96 overflow-auto p-4'>
- <div className='space-y-1 text-sm leading-relaxed'>
+ <div className='rounded-lg border border-gray-100 bg-gray-50 dark:border-slate-700 dark:bg-slate-900/50'>
+ <div className='max-h-80 overflow-auto p-3'>
+ <div className='space-y-0.5 font-mono text-xs leading-relaxed'>
{stackTraceLines.map((line, index) => (
<div key={index} className='flex'>
- <span className='mt-0.5 mr-3 inline-block w-8 text-right text-xs text-slate-400 select-none dark:text-slate-500'>
+ <span className='mr-3 inline-block w-6 text-right text-gray-400 select-none dark:text-slate-500'>
{index + 1}
</span>
<div className='min-w-0 flex-1'>{formatStackTraceLine(line)}</div>
@@ -172,6 +375,40 @@ export const ErrorDetails = ({ details }: ErrorDetailsProps) => {
) : null}
</div>
) : null}
+
+ {/* Affected Sessions */}
+ <div className='rounded-xl border border-gray-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-800'>
+ <h3 className='mb-3 text-xs font-semibold tracking-wide text-gray-900 uppercase dark:text-gray-50'>
+ {t('project.affectedSessionsList')} {sessionsTotal > 0 ? `(${sessionsTotal})` : ''}
+ </h3>
+
+ {sessionsLoading && sessions.length === 0 ? (
+ <Loader />
+ ) : sessions.length === 0 ? (
+ <Text as='p' size='sm' colour='muted' className='py-4 text-center'>
+ {t('project.noAffectedSessions')}
+ </Text>
+ ) : (
+ <div className='space-y-2'>
+ {_map(sessions, (session) => (
+ <SessionRow key={session.psid} session={session} />
+ ))}
+
+ {canLoadMoreSessions ? (
+ <Button
+ onClick={() => loadSessions()}
+ disabled={!!sessionsLoading}
+ loading={!!sessionsLoading}
+ className='mt-3 w-full'
+ secondary
+ regular
+ >
+ {t('project.loadMore')}
+ </Button>
+ ) : null}
+ </div>
+ )}
+ </div>
</div>
)
}
diff --git a/web/app/pages/Project/View/components/Filters.tsx b/web/app/pages/Project/View/components/Filters.tsx
index 5d8973887..988d6b814 100644
--- a/web/app/pages/Project/View/components/Filters.tsx
+++ b/web/app/pages/Project/View/components/Filters.tsx
@@ -1,5 +1,4 @@
import { XMarkIcon } from '@heroicons/react/24/outline'
-import cx from 'clsx'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import _replace from 'lodash/replace'
@@ -10,7 +9,7 @@ import { memo, MouseEvent, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useSearchParams } from 'react-router'
-import { getLocaleDisplayName } from '~/utils/generic'
+import { getLocaleDisplayName, cn } from '~/utils/generic'
import countries from '~/utils/isoCountries'
import { isFilterValid } from '../utils/filters'
@@ -138,7 +137,7 @@ export const Filter = ({
return (
<span
title={truncatedFilter === displayFilter ? undefined : displayFilter}
- className={cx(
+ className={cn(
'm-1 inline-flex items-center rounded-md bg-gray-50 py-0.5 pr-1 pl-2.5 text-sm font-medium text-gray-700 dark:bg-slate-800 dark:text-gray-200',
{
'pr-2': !removable,
@@ -150,7 +149,7 @@ export const Filter = ({
{canChangeExclusive ? (
<Link
to={createToggleExclusivePath()}
- className={cx('cursor-pointer hover:underline', {
+ className={cn('cursor-pointer hover:underline', {
'cursor-wait': dataLoading,
'text-green-600 dark:text-green-400': !isExclusive && !isContains,
'text-red-600 dark:text-red-400': isExclusive && !isContains,
@@ -207,7 +206,7 @@ export const Filter = ({
{removable ? (
<Link
to={createRemoveFilterPath()}
- className={cx(
+ className={cn(
'ml-0.5 inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-gray-800 hover:bg-gray-300 hover:text-gray-900 focus:bg-gray-300 focus:text-gray-900 focus:outline-hidden dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-gray-800 dark:hover:text-gray-300 dark:focus:bg-gray-800 dark:focus:text-gray-300',
{
'cursor-wait': dataLoading,
@@ -234,9 +233,10 @@ export const Filter = ({
interface FiltersProps {
tnMapping: Record<string, string>
+ className?: string
}
-const Filters = ({ tnMapping }: FiltersProps) => {
+const Filters = ({ tnMapping, className }: FiltersProps) => {
const { dataLoading, filters } = useViewProjectContext()
const { t } = useTranslation('common')
const [searchParams] = useSearchParams()
@@ -267,7 +267,12 @@ const Filters = ({ tnMapping }: FiltersProps) => {
}
return (
- <div className='mt-3 flex items-center justify-between rounded-md border border-gray-300 bg-slate-200 p-1 dark:border-slate-800/50 dark:bg-slate-800/25'>
+ <div
+ className={cn(
+ 'mt-3 flex items-center justify-between rounded-md border border-gray-300 bg-slate-200 p-1 dark:border-slate-800/50 dark:bg-slate-800/25',
+ className,
+ )}
+ >
<div className='flex items-center'>
<FilterIcon className='box-content size-6 shrink-0 px-1 text-gray-700 dark:text-gray-200' strokeWidth={1.5} />
<div className='flex flex-wrap'>
@@ -285,7 +290,7 @@ const Filters = ({ tnMapping }: FiltersProps) => {
to={{
search: filterlessSearch,
}}
- className={cx({
+ className={cn({
'cursor-wait': dataLoading,
})}
>
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index c27c19da9..fa6e6478f 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1180,7 +1180,21 @@
"avgDuration": "Avg. duration",
"firstSeen": "First seen",
"lastSeen": "Last seen",
+ "lastSeenAt": "Last seen: {{time}}",
"activityCalendar": "Activity calendar",
+ "totalErrors": "Total Errors",
+ "errorRate": "Error Rate",
+ "affectedUsers": "Affected Users",
+ "affectedSessions": "Affected Sessions",
+ "xAffectedUsers": "{{x}} affected users",
+ "xAffectedSessions": "{{x}} affected sessions",
+ "mostFrequentError": "Most Frequent Error",
+ "critical": "Critical",
+ "usersAffected": "users affected",
+ "recentErrors": "Recent Errors",
+ "affectedSessionsList": "Affected Sessions",
+ "noAffectedSessions": "No affected sessions found",
+ "viewSession": "View session",
"topPages": "Top pages",
"locationAndDevice": "Location & Device",
"userSessions": "Sessions",