Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

fix review suggestions

Blue Mouse3845f1f1eff2
diff --git a/backend/apps/cloud/src/experiment/bayesian.ts b/backend/apps/cloud/src/experiment/bayesian.ts
index 580cc9f1b..9fee80f76 100644
--- a/backend/apps/cloud/src/experiment/bayesian.ts
+++ b/backend/apps/cloud/src/experiment/bayesian.ts
@@ -129,34 +129,50 @@ export function calculateBayesianProbabilities(
return new Map()
}
- if (variants.length === 1) {
- return new Map([[variants[0].key, 1]])
+ // Sanitize simulations: ensure it's a positive integer to avoid division by zero and invalid seeds
+ simulations = Math.max(1, Math.floor(simulations))
+
+ // Sanitize variant data: clamp exposures and conversions to valid ranges
+ const sanitizedVariants = variants.map(v => {
+ const exposures = Math.max(0, Math.floor(v.exposures))
+ const conversions = Math.min(
+ Math.max(0, Math.floor(v.conversions)),
+ exposures,
+ )
+ return { key: v.key, exposures, conversions }
+ })
+
+ if (sanitizedVariants.length === 1) {
+ return new Map([[sanitizedVariants[0].key, 1]])
}
- // Check if we have any data at all
- const totalExposures = variants.reduce((sum, v) => sum + v.exposures, 0)
+ // Check if we have any data at all (recompute from sanitized values)
+ const totalExposures = sanitizedVariants.reduce(
+ (sum, v) => sum + v.exposures,
+ 0,
+ )
if (totalExposures === 0) {
// No data yet - equal probability for all variants
- const prob = 1 / variants.length
- return new Map(variants.map(v => [v.key, prob]))
+ const prob = 1 / sanitizedVariants.length
+ return new Map(sanitizedVariants.map(v => [v.key, prob]))
}
// Count wins for each variant
const wins = new Map<string, number>()
- for (const v of variants) {
+ for (const v of sanitizedVariants) {
wins.set(v.key, 0)
}
// Use deterministic PRNG so the same input always produces the same output.
// This prevents slight "drift" between the table value and the last chart point.
- const random = mulberry32(seedFromVariants(variants, simulations))
+ const random = mulberry32(seedFromVariants(sanitizedVariants, simulations))
// Run Monte Carlo simulation
for (let i = 0; i < simulations; i++) {
let bestRate = -1
let bestKey = ''
- for (const variant of variants) {
+ for (const variant of sanitizedVariants) {
// Calculate Beta distribution parameters
// alpha = conversions + 1 (prior success)
// beta = exposures - conversions + 1 (prior failure)
diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts
index ba9838a49..19092b29c 100644
--- a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts
+++ b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts
@@ -334,9 +334,13 @@ export class FeatureFlagController {
for (const experiment of experiments) {
if (experiment.variants && experiment.variants.length > 0) {
+ // Sort variants by key to ensure stable ordering regardless of DB query order
+ const sortedVariants = [...experiment.variants].sort((a, b) =>
+ a.key.localeCompare(b.key),
+ )
const variantKey = getExperimentVariant(
experiment.id,
- experiment.variants.map(v => ({
+ sortedVariants.map(v => ({
key: v.key,
rolloutPercentage: v.rolloutPercentage,
})),
diff --git a/backend/apps/cloud/src/goal/goal.controller.ts b/backend/apps/cloud/src/goal/goal.controller.ts
index 17506f690..070cd8a7a 100644
--- a/backend/apps/cloud/src/goal/goal.controller.ts
+++ b/backend/apps/cloud/src/goal/goal.controller.ts
@@ -101,9 +101,10 @@ export class GoalController {
@Param('projectId') projectId: string,
@Query('take', new ParseIntPipe({ optional: true })) take?: number,
@Query('skip', new ParseIntPipe({ optional: true })) skip?: number,
+ @Query('search') search?: string,
) {
this.logger.log(
- { userId, projectId, take, skip },
+ { userId, projectId, take, skip, search },
'GET /goal/project/:projectId',
)
@@ -119,6 +120,7 @@ export class GoalController {
{ take, skip },
{ project: { id: projectId } },
['project'],
+ search,
)
// @ts-expect-error
diff --git a/backend/apps/cloud/src/goal/goal.service.ts b/backend/apps/cloud/src/goal/goal.service.ts
index 4a95c3d15..8a677eef8 100644
--- a/backend/apps/cloud/src/goal/goal.service.ts
+++ b/backend/apps/cloud/src/goal/goal.service.ts
@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
-import { FindManyOptions, FindOneOptions, Repository } from 'typeorm'
+import { FindManyOptions, FindOneOptions, Repository, ILike } from 'typeorm'
import { Pagination, PaginationOptionsInterface } from '../common/pagination'
import { Goal } from './entity/goal.entity'
@@ -15,11 +15,23 @@ export class GoalService {
options: PaginationOptionsInterface,
where: FindManyOptions<Goal>['where'],
relations?: Array<string>,
+ search?: string,
): Promise<Pagination<Goal>> {
+ let finalWhere: FindManyOptions<Goal>['where'] = where
+
+ if (search && search.trim()) {
+ const searchPattern = `%${search.trim()}%`
+ // Use array of where conditions for OR with the base where conditions
+ finalWhere = [
+ { ...where, name: ILike(searchPattern) },
+ { ...where, value: ILike(searchPattern) },
+ ]
+ }
+
const [results, total] = await this.goalsRepository.findAndCount({
take: options.take || 100,
skip: options.skip || 0,
- where,
+ where: finalWhere,
order: {
name: 'ASC',
},
diff --git a/backend/apps/community/src/goal/goal.controller.ts b/backend/apps/community/src/goal/goal.controller.ts
index 3dfdd556c..6f7c3406c 100644
--- a/backend/apps/community/src/goal/goal.controller.ts
+++ b/backend/apps/community/src/goal/goal.controller.ts
@@ -83,9 +83,10 @@ export class GoalController {
@Param('projectId') projectId: string,
@Query('take', new ParseIntPipe({ optional: true })) take?: number,
@Query('skip', new ParseIntPipe({ optional: true })) skip?: number,
+ @Query('search') search?: string,
) {
this.logger.log(
- { userId, projectId, take, skip },
+ { userId, projectId, take, skip, search },
'GET /goal/project/:projectId',
)
@@ -97,7 +98,11 @@ export class GoalController {
this.projectService.allowedToView(project, userId)
- const result = await this.goalService.paginate({ take, skip }, projectId)
+ const result = await this.goalService.paginate(
+ { take, skip },
+ projectId,
+ search,
+ )
return {
...result,
diff --git a/backend/apps/community/src/goal/goal.service.ts b/backend/apps/community/src/goal/goal.service.ts
index 5dd1250b3..498b4679e 100644
--- a/backend/apps/community/src/goal/goal.service.ts
+++ b/backend/apps/community/src/goal/goal.service.ts
@@ -117,19 +117,30 @@ export class GoalService {
async paginate(
options: PaginationOptionsInterface,
projectId: string,
+ search?: string,
): Promise<Pagination<Goal>> {
const take = options.take || 100
const skip = options.skip || 0
+ let searchCondition = ''
+ const queryParams: Record<string, any> = { projectId, take, skip }
+
+ if (search && search.trim()) {
+ searchCondition = `AND (name ILIKE concat('%', {search:String}, '%') OR value ILIKE concat('%', {search:String}, '%'))`
+ queryParams.search = search.trim()
+ }
+
const countQuery = `
SELECT count() as total
FROM goal
WHERE projectId = {projectId:FixedString(12)}
+ ${searchCondition}
`
const dataQuery = `
SELECT * FROM goal
WHERE projectId = {projectId:FixedString(12)}
+ ${searchCondition}
ORDER BY name ASC
LIMIT {take:UInt32} OFFSET {skip:UInt32}
`
@@ -138,13 +149,13 @@ export class GoalService {
clickhouse
.query({
query: countQuery,
- query_params: { projectId },
+ query_params: queryParams,
})
.then(resultSet => resultSet.json<{ total: number }>()),
clickhouse
.query({
query: dataQuery,
- query_params: { projectId, take, skip },
+ query_params: queryParams,
})
.then(resultSet => resultSet.json<ClickhouseGoal>()),
])
diff --git a/backend/migrations/mysql/2025_12_11_experiments.sql b/backend/migrations/mysql/2025_12_11_experiments.sql
index d7552b584..34b1305d2 100644
--- a/backend/migrations/mysql/2025_12_11_experiments.sql
+++ b/backend/migrations/mysql/2025_12_11_experiments.sql
@@ -37,5 +37,5 @@ CREATE TABLE IF NOT EXISTS `experiment_variant` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Add experimentId to feature_flag table for linking
-ALTER TABLE `feature_flag` ADD COLUMN IF NOT EXISTS `experimentId` varchar(36) DEFAULT NULL;
+ALTER TABLE `feature_flag` ADD COLUMN `experimentId` varchar(36) DEFAULT NULL;
ALTER TABLE `feature_flag` ADD KEY `FK_feature_flag_experiment` (`experimentId`);
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index 656c06d17..0ad67fb69 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -1257,9 +1257,18 @@ export interface GoalChartData {
export const DEFAULT_GOALS_TAKE = 20
-export const getProjectGoals = (projectId: string, take: number = DEFAULT_GOALS_TAKE, skip = 0) =>
- api
- .get(`/goal/project/${projectId}?take=${take}&skip=${skip}`)
+export const getProjectGoals = (projectId: string, take: number = DEFAULT_GOALS_TAKE, skip = 0, search?: string) => {
+ const params = new URLSearchParams({
+ take: String(take),
+ skip: String(skip),
+ })
+
+ if (search?.trim()) {
+ params.append('search', search.trim())
+ }
+
+ return api
+ .get(`/goal/project/${projectId}?${params.toString()}`)
.then(
(
response,
@@ -1271,6 +1280,7 @@ export const getProjectGoals = (projectId: string, take: number = DEFAULT_GOALS_
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
+}
export const getGoal = (goalId: string) =>
api
diff --git a/web/app/pages/Project/Experiments/View/ExperimentsView.tsx b/web/app/pages/Project/Experiments/View/ExperimentsView.tsx
index b8888b5c5..d0587be0e 100644
--- a/web/app/pages/Project/Experiments/View/ExperimentsView.tsx
+++ b/web/app/pages/Project/Experiments/View/ExperimentsView.tsx
@@ -319,8 +319,10 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
return
}
isLoadingRef.current = true
- // Only show loading state if requested and we don't have existing data
- if (showLoading) {
+
+ // Only toggle global loading UI when we don't already have cached data
+ const didShowLoading = showLoading && (!experiments || experiments.length === 0)
+ if (didShowLoading) {
setIsLoading(true)
}
@@ -329,6 +331,7 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
if (isMountedRef.current) {
setExperiments(result.results)
setTotal(result.total)
+ setError(null) // Clear any previous error on success
}
} catch (reason: any) {
if (isMountedRef.current) {
@@ -336,7 +339,7 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
}
} finally {
isLoadingRef.current = false
- if (isMountedRef.current) {
+ if (isMountedRef.current && didShowLoading) {
setIsLoading(false)
}
}
diff --git a/web/app/pages/Project/Goals/View/GoalsView.tsx b/web/app/pages/Project/Goals/View/GoalsView.tsx
index 9a2bf97b0..4bb05db05 100644
--- a/web/app/pages/Project/Goals/View/GoalsView.tsx
+++ b/web/app/pages/Project/Goals/View/GoalsView.tsx
@@ -4,6 +4,7 @@ import { area, bar } from 'billboard.js'
import cx from 'clsx'
import * as d3 from 'd3'
import dayjs from 'dayjs'
+import _debounce from 'lodash/debounce'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import _size from 'lodash/size'
@@ -17,7 +18,7 @@ import {
MousePointerClickIcon,
ChevronDownIcon,
} from 'lucide-react'
-import { useState, useEffect, useMemo, useRef } from 'react'
+import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
import { toast } from 'sonner'
@@ -441,6 +442,7 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
const [page, setPage] = useState(1)
const [error, setError] = useState<string | null>(null)
const [filterQuery, setFilterQuery] = useState('')
+ const [debouncedSearch, setDebouncedSearch] = useState('')
// Expanded goal state
const [expandedGoalId, setExpandedGoalId] = useState<string | null>(null)
@@ -461,15 +463,25 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
const pageAmount = Math.ceil(total / DEFAULT_GOALS_TAKE)
- const filteredGoals = useMemo(() => {
- if (!filterQuery.trim()) return goals
- const query = filterQuery.toLowerCase()
- return goals.filter(
- (goal) => goal.name.toLowerCase().includes(query) || (goal.value && goal.value.toLowerCase().includes(query)),
- )
- }, [goals, filterQuery])
+ // Debounced search handler
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const debouncedSetSearch = useCallback(
+ _debounce((value: string) => {
+ setDebouncedSearch(value)
+ setPage(1) // Reset to first page when search changes
+ }, 300),
+ [],
+ )
+
+ // Update debounced search when filterQuery changes
+ useEffect(() => {
+ debouncedSetSearch(filterQuery)
+ return () => {
+ debouncedSetSearch.cancel()
+ }
+ }, [filterQuery, debouncedSetSearch])
- const loadGoals = async (take: number, skip: number) => {
+ const loadGoals = async (take: number, skip: number, search?: string) => {
if (isLoadingRef.current) {
return
}
@@ -477,7 +489,7 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
setIsLoading(true)
try {
- const result = await getProjectGoals(id, take, skip)
+ const result = await getProjectGoals(id, take, skip, search)
if (isMountedRef.current) {
setGoals(result.results)
setTotal(result.total)
@@ -547,9 +559,9 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
}
useEffect(() => {
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE)
+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [page])
+ }, [page, debouncedSearch])
useEffect(() => {
// Load stats for all goals when goals change or date range changes
@@ -572,7 +584,7 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
// Refresh goals data when refresh button is clicked
useEffect(() => {
if (goalsRefreshTrigger > 0) {
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE)
+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
// Clear cached chart data for non-expanded goals, silently refresh expanded goal
if (expandedGoalId) {
// Keep only the expanded goal's data while we fetch fresh data
@@ -603,7 +615,7 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
}
const handleModalSuccess = () => {
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE)
+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
}
const handleDeleteGoal = async (goalId: string) => {
@@ -611,7 +623,7 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
await deleteGoalApi(goalId)
toast.success(t('goals.deleted'))
// Reload goals
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE)
+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
} catch (reason: any) {
toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))
}
@@ -709,7 +721,7 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
{/* Goals list */}
<ul className='mt-4'>
- {_map(filteredGoals, (goal) => (
+ {_map(goals, (goal) => (
<GoalRow
key={goal.id}
goal={goal}
@@ -727,14 +739,14 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
))}
</ul>
- {filteredGoals.length === 0 && filterQuery ? (
+ {goals.length === 0 && debouncedSearch ? (
<p className='py-8 text-center text-sm text-gray-500 dark:text-gray-400'>
{t('goals.noGoalsMatchFilter')}
</p>
) : null}
</>
)}
- {pageAmount > 1 && !filterQuery ? (
+ {pageAmount > 1 ? (
<Pagination
className='mt-4'
page={page}
diff --git a/web/app/pages/Project/View/components/CaptchaView.tsx b/web/app/pages/Project/View/components/CaptchaView.tsx
index c7fc21bf4..40704c83a 100644
--- a/web/app/pages/Project/View/components/CaptchaView.tsx
+++ b/web/app/pages/Project/View/components/CaptchaView.tsx
@@ -177,7 +177,7 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
const hasExistingData = chartData !== null || !_isEmpty(panelsData.types)
// Show waiting state if project has no captcha data yet
- if (!project?.isCaptchaDataExists) {
+ if (!_isEmpty(project) && !project?.isCaptchaDataExists) {
return <WaitingForAnEvent />
}