:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import clsx from 'clsx'
import { IconChevronDown, IconChevronRight } from '@posthog/icons'
import { LemonButton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import { getSeriesColor } from 'lib/colors'
import { urls } from 'scenes/urls'
import { formatErrorRate, formatLLMCost, formatLLMLatency, formatTokens } from '../utils'
import { ClusterDescription } from './ClusterDescriptionComponents'
import { ClusterTraceList } from './ClusterTraceList'
import { NOISE_CLUSTER_ID } from './constants'
import { Cluster, ClusterMetrics, ClusteringLevel, TraceSummary } from './types'
interface ClusterCardProps {
cluster: Cluster
totalTraces: number
isExpanded: boolean
onToggleExpand: () => void
traceSummaries: Record<string, TraceSummary>
loadingTraces: boolean
runId: string
clusteringLevel?: ClusteringLevel
metrics?: ClusterMetrics
metricsLoading?: boolean
}
export function ClusterCard({
cluster,
totalTraces,
isExpanded,
onToggleExpand,
traceSummaries,
loadingTraces,
runId,
clusteringLevel = 'trace',
metrics,
metricsLoading,
}: ClusterCardProps): JSX.Element {
const percentage = totalTraces > 0 ? Math.round((cluster.size / totalTraces) * 100) : 0
const isOutlierCluster = cluster.cluster_id === NOISE_CLUSTER_ID
const itemLabel =
clusteringLevel === 'generation' ? 'generations' : clusteringLevel === 'evaluation' ? 'evaluations' : 'traces'
const clusterColor = isOutlierCluster ? undefined : getSeriesColor(cluster.cluster_id)
// Check if we have any metrics to show. Eval-specific metrics (passRate /
// naRate / dominantEvaluationName / dominantRuntime) count even when the
// operational metrics are all null — an eval cluster whose linked generations
// were purged still has a meaningful pass rate.
const hasMetrics =
metrics &&
(metrics.avgCost !== null ||
metrics.avgLatency !== null ||
metrics.avgTokens !== null ||
metrics.errorRate !== null ||
(metrics.passRate ?? null) !== null ||
(metrics.naRate ?? null) !== null ||
!!metrics.dominantEvaluationName ||
!!metrics.dominantRuntime ||
(metrics.avgJudgeCost ?? null) !== null)
const isEvalLevel = clusteringLevel === 'evaluation'
return (
<div
className={clsx(
'rounded-lg overflow-hidden transition-all bg-surface-primary border border-primary',
isOutlierCluster && 'border-dashed'
)}
>
{/* Card Header */}
<div
className="p-4 cursor-pointer hover:bg-surface-secondary transition-colors"
onClick={onToggleExpand}
data-attr="clusters-card-header"
>
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<div
className={clsx(
'w-2.5 h-2.5 rounded-full shrink-0',
isOutlierCluster && 'border border-dashed border-secondary'
)}
// eslint-disable-next-line react/forbid-dom-props
style={isOutlierCluster ? undefined : { backgroundColor: clusterColor }}
aria-hidden
/>
<Link
to={urls.aiObservabilityCluster(runId, cluster.cluster_id)}
className="font-semibold text-base truncate hover:underline"
onClick={(e) => e.stopPropagation()}
data-attr="clusters-card-title-link"
>
{cluster.title}
</Link>
<LemonTag type={isOutlierCluster ? 'caution' : 'muted'}>
{cluster.size} {itemLabel} ({percentage}%)
</LemonTag>
</div>
<ClusterDescription description={cluster.description} />
{/* Cluster Metrics */}
{metricsLoading && !hasMetrics && (
<div className="flex flex-row flex-wrap items-center gap-2 mt-2">
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} className="h-5 w-24 bg-border-light rounded animate-pulse" />
))}
</div>
)}
{hasMetrics && (
<div className="flex flex-row flex-wrap items-center gap-2 mt-2">
{isEvalLevel && (metrics.passRate ?? null) !== null && (
<Tooltip
title={`${Math.round(
(metrics.passRate as number) * 100
)}% of evaluations in this cluster passed`}
>
<LemonTag
type={
(metrics.passRate as number) >= 0.8
? 'success'
: (metrics.passRate as number) <= 0.2
? 'danger'
: 'warning'
}
size="small"
>
Pass rate: {Math.round((metrics.passRate as number) * 100)}%
</LemonTag>
</Tooltip>
)}
{isEvalLevel && (metrics.naRate ?? null) !== null && (metrics.naRate as number) > 0 && (
<Tooltip title="Share of evaluations where the evaluator marked the criteria as not applicable">
<LemonTag type="muted" size="small">
N/A: {Math.round((metrics.naRate as number) * 100)}%
</LemonTag>
</Tooltip>
)}
{isEvalLevel && metrics.dominantEvaluationName && (
<Tooltip title="Most common evaluator in this cluster">
<LemonTag type="muted" size="small">
Evaluator: {metrics.dominantEvaluationName}
</LemonTag>
</Tooltip>
)}
{isEvalLevel && metrics.dominantRuntime && (
<Tooltip title="Most common evaluator runtime (llm_judge = LLM-as-judge, hog = deterministic rule-based)">
<LemonTag type="muted" size="small">
Runtime: {metrics.dominantRuntime}
</LemonTag>
</Tooltip>
)}
{isEvalLevel && (metrics.avgJudgeCost ?? null) !== null && (
<Tooltip title="Average cost of running the LLM-as-judge evaluator per eval in this cluster">
<LemonTag type="muted" size="small">
Avg Judge Cost: {formatLLMCost(metrics.avgJudgeCost as number)}
</LemonTag>
</Tooltip>
)}
{metrics.avgCost !== null && (
<Tooltip
title={
isEvalLevel
? 'Average cost of the linked generation that each evaluation judged'
: `Average cost per ${clusteringLevel}`
}
>
<LemonTag type="muted" size="small">
Avg Cost: {formatLLMCost(metrics.avgCost)}
</LemonTag>
</Tooltip>
)}
{metrics.avgLatency !== null && (
<Tooltip
title={
isEvalLevel
? 'Average latency of the linked generation that each evaluation judged'
: `Average latency per ${clusteringLevel}`
}
>
<LemonTag type="muted" size="small">
Avg Latency: {formatLLMLatency(metrics.avgLatency)}
</LemonTag>
</Tooltip>
)}
{metrics.avgTokens !== null && (
<Tooltip
title={
isEvalLevel
? 'Average input + output tokens of the linked generation'
: `Average tokens (input + output) per ${clusteringLevel}`
}
>
<LemonTag type="muted" size="small">
Avg Tokens: {formatTokens(metrics.avgTokens)}
</LemonTag>
</Tooltip>
)}
{metrics.errorRate !== null && (
<Tooltip
title={`Error rate: ${metrics.errorCount} errors out of ${metrics.itemCount} ${itemLabel}`}
>
<LemonTag type={metrics.errorRate > 0 ? 'danger' : 'muted'} size="small">
Errors: {formatErrorRate(metrics.errorRate)}
</LemonTag>
</Tooltip>
)}
{!isEvalLevel && metrics.totalCost !== null && (
<Tooltip title={`Total cost across all ${itemLabel} in this cluster`}>
<LemonTag type="muted" size="small">
Total Cost: {formatLLMCost(metrics.totalCost)}
</LemonTag>
</Tooltip>
)}
</div>
)}
</div>
<LemonButton
size="small"
noPadding
icon={isExpanded ? <IconChevronDown /> : <IconChevronRight />}
onClick={(e) => {
e.stopPropagation()
onToggleExpand()
}}
/>
</div>
</div>
{/* Expanded Trace List */}
{isExpanded && (
<div className="border-t">
<ClusterTraceList
cluster={cluster}
traceSummaries={traceSummaries}
loading={loadingTraces}
clusteringLevel={clusteringLevel}
/>
<div className="p-3 border-t bg-surface-secondary">
<Link
to={urls.aiObservabilityCluster(runId, cluster.cluster_id)}
className="text-link hover:underline text-sm font-medium"
data-attr="clusters-view-all-link"
>
View all {Object.keys(cluster.traces).length} {itemLabel} →
</Link>
</div>
</div>
)}
</div>
)
}