Skip to content

: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.

feat(aio): render cluster scatter plots with quill charts (#86243)

Sam Pennington6d9eb6230985
diff --git a/products/ai_observability/frontend/clusters/ClusterDetailScatterPlot.tsx b/products/ai_observability/frontend/clusters/ClusterDetailScatterPlot.tsx
index 0b303207c3cd..2e5ffcf7702b 100644
--- a/products/ai_observability/frontend/clusters/ClusterDetailScatterPlot.tsx
+++ b/products/ai_observability/frontend/clusters/ClusterDetailScatterPlot.tsx
@@ -1,240 +1,64 @@
import { useValues } from 'kea'
-import { router } from 'kea-router'
-import { useEffect } from 'react'
+import { useEffect, useMemo, useState } from 'react'
-import { Chart } from 'lib/Chart'
-import { useChart } from 'lib/hooks/useChart'
-import { urls } from 'scenes/urls'
+import { ScatterChart } from '@posthog/quill-charts'
+import type { ScatterAreaSelection, ScatterChartConfig, ScatterPointDatum } from '@posthog/quill-charts'
-import { clusterDetailLogic } from './clusterDetailLogic'
-import { isCentroidDataset } from './constants'
-import { formatEvalTitle } from './traceSummaryLoader'
-
-interface ScatterPoint {
- x: number
- y: number
- traceId?: string
- generationId?: string
- timestamp?: string
-}
+import { useChartTheme } from 'lib/charts/hooks'
-export function ClusterDetailScatterPlot(): JSX.Element {
- const { cluster, traceSummaries, scatterPlotDatasets, clusteringLevel } = useValues(clusterDetailLogic)
+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
- const handleClick = (
- _event: MouseEvent,
- elements: { datasetIndex: number; index: number }[],
- chart: Chart<'scatter'>
- ): void => {
- if (elements.length === 0) {
- return
- }
+import { clusterDetailLogic } from './clusterDetailLogic'
+import { navigateToClusterItem } from './clusterScatter'
+import type { ClusterScatterMeta } from './clusterScatter'
+import { ClusterDetailTooltip } from './ClusterScatterTooltip'
- const element = elements[0]
- const dataset = chart.data?.datasets?.[element.datasetIndex]
- if (!dataset || isCentroidDataset(dataset)) {
- return
- }
+const handleChartError = makeChartErrorHandler('ai-cluster-detail-scatter')
- const point = dataset.data?.[element.index] as ScatterPoint | undefined
- if (!point) {
- return
- }
+export function ClusterDetailScatterPlot(): JSX.Element {
+ const { cluster, traceSummaries, scatterPlotSeries, clusteringLevel } = useValues(clusterDetailLogic)
+ const theme = useChartTheme()
+ const [zoom, setZoom] = useState<ScatterAreaSelection | null>(null)
+
+ // Drop a pinned zoom when the data changes — a stale domain from the previous UMAP space would
+ // drop the new points and render the plot blank until reset.
+ useEffect(() => setZoom(null), [scatterPlotSeries])
+
+ const config = useMemo<ScatterChartConfig<ClusterScatterMeta>>(
+ () => ({
+ xAxis: { hide: true, domain: zoom?.x },
+ yAxis: { hide: true, domain: zoom?.y },
+ tooltip: { placement: 'cursor' },
+ }),
+ [zoom]
+ )
- if (clusteringLevel === 'evaluation') {
- // For eval points, point.traceId is the backend's eval-uuid fallback
- // when the metadata join couldn't resolve — routing to /traces/<eval_uuid>
- // 404s. Use the loaded summary's real traceId instead; if it hasn't
- // loaded yet we just no-op (the list below shows "Loading...").
- const summary = point.generationId ? traceSummaries[point.generationId] : undefined
- const resolvedTraceId = summary?.traceId
- if (!resolvedTraceId) {
- return
- }
- router.actions.push(
- urls.aiObservabilityTrace(resolvedTraceId, {
- tab: 'summary',
- ...(point.generationId ? { event: point.generationId } : {}),
- ...(point.timestamp ? { timestamp: point.timestamp } : {}),
- })
- )
+ const handlePointClick = (point: ScatterPointDatum<ClusterScatterMeta>): void => {
+ if (point.meta?.isCentroid || !point.meta) {
return
}
-
- if (point.traceId) {
- router.actions.push(
- urls.aiObservabilityTrace(point.traceId, {
- tab: 'summary',
- // For generation-level, highlight the specific generation
- ...(clusteringLevel === 'generation' && point.generationId ? { event: point.generationId } : {}),
- // timestamp is the trace's first_timestamp for both levels
- ...(point.timestamp ? { timestamp: point.timestamp } : {}),
- })
- )
- }
+ navigateToClusterItem(point.meta, clusteringLevel, traceSummaries)
}
- const { canvasRef, chartRef } = useChart<'scatter'>({
- getConfig: () => {
- if (!cluster || scatterPlotDatasets.length === 0) {
- return null
- }
-
- return {
- type: 'scatter',
- data: { datasets: scatterPlotDatasets },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- // Chart.js onClick type is complex; cast through unknown for type safety
- onClick: handleClick as unknown as undefined,
- onHover: (event, elements, chart) => {
- const canvas = event.native?.target as HTMLCanvasElement | undefined
- if (!canvas) {
- return
- }
- if (elements.length === 0) {
- canvas.style.cursor = 'default'
- return
- }
- const element = elements[0]
- const dataset = chart?.data?.datasets?.[element.datasetIndex]
- if (isCentroidDataset(dataset)) {
- canvas.style.cursor = 'default'
- return
- }
- // Eval points are only clickable once their summary has loaded —
- // otherwise point.traceId is the backend's eval-uuid fallback
- // and the click would 404. Mirror the logic in handleClick.
- if (clusteringLevel === 'evaluation') {
- const point = dataset?.data?.[element.index] as ScatterPoint | undefined
- const summary = point?.generationId ? traceSummaries[point.generationId] : undefined
- canvas.style.cursor = summary?.traceId ? 'pointer' : 'default'
- return
- }
- canvas.style.cursor = 'pointer'
- },
- plugins: {
- legend: {
- display: false,
- },
- zoom: {
- zoom: {
- drag: {
- enabled: true,
- backgroundColor: 'rgba(100, 100, 100, 0.3)',
- borderColor: 'rgba(100, 100, 100, 0.8)',
- borderWidth: 1,
- },
- mode: 'xy',
- },
- },
- tooltip: {
- bodyFont: {
- weight: 'normal',
- },
- footerFont: {
- weight: 'normal',
- style: 'italic',
- },
- callbacks: {
- title: (context) => {
- const isCentroid = isCentroidDataset(context[0]?.dataset)
- if (isCentroid) {
- return 'Cluster centroid'
- }
- return cluster.title
- },
- label: (context) => {
- const isCentroid = isCentroidDataset(context.dataset)
- if (isCentroid) {
- return 'Center of this cluster'
- }
-
- const point = context.raw as ScatterPoint
- // For evaluation-level, the cluster item id (= eval uuid) is
- // carried in generationId; traceId is the parent trace being
- // judged, which doesn't key into the summary map.
- // For generation-level, summaries are keyed by generation_id.
- // For trace-level, summaries are keyed by trace_id.
- const summaryKey =
- clusteringLevel === 'generation' || clusteringLevel === 'evaluation'
- ? point.generationId
- : point.traceId
- if (summaryKey) {
- const summary = traceSummaries[summaryKey]
- if (clusteringLevel === 'evaluation') {
- const formatted = formatEvalTitle(summary, 140)
- if (formatted) {
- return formatted
- }
- } else if (summary?.title) {
- return summary.title
- }
- }
- if (point.traceId) {
- return clusteringLevel === 'generation'
- ? `Generation ${(point.generationId || point.traceId).slice(0, 8)}...`
- : clusteringLevel === 'evaluation'
- ? `Evaluation ${(point.generationId || point.traceId).slice(0, 8)}...`
- : `Trace ${point.traceId.slice(0, 8)}...`
- }
- return undefined
- },
- footer: (context) => {
- const isCentroid = isCentroidDataset(context[0]?.dataset)
- if (isCentroid) {
- return ''
- }
- const point = context[0]?.raw as ScatterPoint
- if (point?.traceId) {
- return clusteringLevel === 'generation' || clusteringLevel === 'evaluation'
- ? 'click to view generation'
- : 'click to view trace'
- }
- return ''
- },
- },
- },
- },
- scales: {
- x: {
- type: 'linear',
- position: 'bottom',
- display: false,
- },
- y: {
- type: 'linear',
- display: false,
- },
- },
- },
- }
- },
- deps: [scatterPlotDatasets, traceSummaries, cluster],
- })
-
- // Reset zoom on double-click
- useEffect(() => {
- const canvas = canvasRef.current
- if (!canvas) {
- return
- }
-
- const handleDoubleClick = (): void => {
- if (chartRef.current) {
- // resetZoom is added by chartjs-plugin-zoom at runtime
- ;(chartRef.current as unknown as { resetZoom: () => void }).resetZoom()
- }
- }
-
- canvas.addEventListener('dblclick', handleDoubleClick)
- return () => canvas.removeEventListener('dblclick', handleDoubleClick)
- }, [canvasRef, chartRef])
-
return (
- <div className="h-64">
- <canvas ref={canvasRef} />
+ <div className="h-64 flex flex-col" onDoubleClick={() => setZoom(null)}>
+ <ScatterChart
+ series={scatterPlotSeries}
+ theme={theme}
+ config={config}
+ dataAttr="ai-cluster-detail-scatter"
+ onPointClick={handlePointClick}
+ onAreaSelect={setZoom}
+ onError={handleChartError}
+ tooltip={({ point }) => (
+ <ClusterDetailTooltip
+ point={point}
+ cluster={cluster}
+ clusteringLevel={clusteringLevel}
+ traceSummaries={traceSummaries}
+ />
+ )}
+ />
</div>
)
}
diff --git a/products/ai_observability/frontend/clusters/ClusterScatterPlot.stories.tsx b/products/ai_observability/frontend/clusters/ClusterScatterPlot.stories.tsx
new file mode 100644
index 000000000000..e76766178071
--- /dev/null
+++ b/products/ai_observability/frontend/clusters/ClusterScatterPlot.stories.tsx
@@ -0,0 +1,91 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import { ClusterScatterPlot } from './ClusterScatterPlot'
+import { clustersLogic } from './clustersLogic'
+import { NOISE_CLUSTER_ID } from './constants'
+import { Cluster, ClusterItemInfo, ClusteringRun } from './types'
+
+// Deterministic ring of points around a centroid — random coordinates would churn the snapshot.
+function makeTraces(clusterId: number, cx: number, cy: number, count: number): Record<string, ClusterItemInfo> {
+ const traces: Record<string, ClusterItemInfo> = {}
+ for (let i = 0; i < count; i++) {
+ const angle = (i / count) * Math.PI * 2
+ const radius = 0.4 + (i % 5) * 0.12
+ const id = `c${clusterId}-t${i}`
+ traces[id] = {
+ distance_to_centroid: radius,
+ rank: i,
+ x: cx + Math.cos(angle) * radius,
+ y: cy + Math.sin(angle) * radius,
+ timestamp: '2026-08-01T10:00:00Z',
+ trace_id: id,
+ }
+ }
+ return traces
+}
+
+function makeCluster(clusterId: number, title: string, cx: number, cy: number, count: number): Cluster {
+ return {
+ cluster_id: clusterId,
+ size: count,
+ title,
+ description: '',
+ traces: makeTraces(clusterId, cx, cy, count),
+ centroid: [],
+ centroid_x: cx,
+ centroid_y: cy,
+ }
+}
+
+const run: ClusteringRun = {
+ runId: '2_trace_20260801_120000',
+ windowStart: '2026-07-25T00:00:00Z',
+ windowEnd: '2026-08-01T00:00:00Z',
+ totalItemsAnalyzed: 120,
+ timestamp: '2026-08-01T12:00:00Z',
+ level: 'trace',
+ clusters: [
+ makeCluster(0, 'Refund requests', -2, 1.5, 28),
+ makeCluster(1, 'Password resets', 2, 2, 24),
+ makeCluster(2, 'Billing questions', 1.5, -2, 22),
+ makeCluster(NOISE_CLUSTER_ID, 'Outliers', -3, -2.5, 10),
+ ],
+}
+
+const meta: Meta<typeof ClusterScatterPlot> = {
+ title: 'Scenes-App/AI observability/ClusterScatterPlot',
+ component: ClusterScatterPlot,
+ // Excluded from visual-regression snapshots: it mounts clustersLogic (and its on-mount query
+ // loaders), which doesn't settle within the runner's screenshot timeout under CI load. It still
+ // renders the real chart in interactive Storybook for inspection.
+ tags: ['test-skip'],
+ parameters: {
+ layout: 'padded',
+ },
+ render: () => {
+ // The runs list loader fires on mount; keep it empty so the seeded run below is what renders.
+ useStorybookMocks({
+ post: {
+ '/api/environments/:team_id/query/': () => [200, { results: [] }],
+ },
+ })
+ useOnMountEffect(() => {
+ clustersLogic.mount()
+ clustersLogic.actions.loadClusteringRunSuccess(run)
+ })
+ return (
+ <div className="max-w-3xl">
+ <ClusterScatterPlot />
+ </div>
+ )
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof ClusterScatterPlot>
+
+export const Overview: Story = {}
diff --git a/products/ai_observability/frontend/clusters/ClusterScatterPlot.tsx b/products/ai_observability/frontend/clusters/ClusterScatterPlot.tsx
index d8591bfa2f4e..4fcd6264d136 100644
--- a/products/ai_observability/frontend/clusters/ClusterScatterPlot.tsx
+++ b/products/ai_observability/frontend/clusters/ClusterScatterPlot.tsx
@@ -1,251 +1,75 @@
import { useValues } from 'kea'
import { router } from 'kea-router'
-import { useEffect } from 'react'
+import { useEffect, useMemo, useState } from 'react'
-import { Chart } from 'lib/Chart'
-import { useChart } from 'lib/hooks/useChart'
+import { ScatterChart } from '@posthog/quill-charts'
+import type { ScatterAreaSelection, ScatterChartConfig, ScatterPointDatum } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
import { urls } from 'scenes/urls'
-import { clustersLogic } from './clustersLogic'
-import { isCentroidDataset } from './constants'
-import { formatEvalTitle } from './traceSummaryLoader'
-import { TraceSummary } from './types'
+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
-interface ScatterPoint {
- x: number
- y: number
- traceId?: string
- generationId?: string
- clusterId?: number
- timestamp?: string
-}
+import { navigateToClusterItem } from './clusterScatter'
+import type { ClusterScatterMeta } from './clusterScatter'
+import { ClusterOverviewTooltip } from './ClusterScatterTooltip'
+import { clustersLogic } from './clustersLogic'
-interface ClusterScatterPlotProps {
- traceSummaries: Record<string, TraceSummary>
-}
+const handleChartError = makeChartErrorHandler('ai-clusters-scatter')
-export function ClusterScatterPlot({ traceSummaries }: ClusterScatterPlotProps): JSX.Element {
- const { scatterPlotDatasets, traceToClusterTitle, sortedClusters, effectiveRunId, clusteringLevel } =
+export function ClusterScatterPlot(): JSX.Element {
+ const { scatterPlotSeries, sortedClusters, effectiveRunId, clusteringLevel, traceSummaries } =
useValues(clustersLogic)
+ const theme = useChartTheme()
+ const [zoom, setZoom] = useState<ScatterAreaSelection | null>(null)
+
+ // Drop a pinned zoom when the data changes (run switch or filter) — a stale domain from the
+ // previous run's UMAP space would drop the new points and render the plot blank until reset.
+ useEffect(() => setZoom(null), [scatterPlotSeries])
+
+ const config = useMemo<ScatterChartConfig<ClusterScatterMeta>>(
+ () => ({
+ xAxis: { hide: true, domain: zoom?.x },
+ yAxis: { hide: true, domain: zoom?.y },
+ tooltip: { placement: 'cursor' },
+ }),
+ [zoom]
+ )
- const handleClick = (
- _event: MouseEvent,
- elements: { datasetIndex: number; index: number }[],
- chart: Chart<'scatter'>
- ): void => {
- if (elements.length === 0) {
- return
- }
-
- const element = elements[0]
- const dataset = chart.data?.datasets?.[element.datasetIndex]
- if (!dataset) {
- return
- }
-
- const point = dataset.data?.[element.index] as ScatterPoint | undefined
-
- // Navigate to cluster page for centroid clicks
- if (isCentroidDataset(dataset)) {
- if (point?.clusterId !== undefined && effectiveRunId) {
- router.actions.push(urls.aiObservabilityCluster(effectiveRunId, point.clusterId))
- }
- return
- }
-
- if (!point) {
- return
- }
-
- if (clusteringLevel === 'evaluation') {
- // Eval point.traceId is the backend's eval-uuid fallback when
- // metadata wasn't resolved; routing there 404s. Use summary.traceId
- // instead; no-op until the summary loads.
- const summary = point.generationId ? traceSummaries[point.generationId] : undefined
- const resolvedTraceId = summary?.traceId
- if (!resolvedTraceId) {
- return
+ const handlePointClick = (point: ScatterPointDatum<ClusterScatterMeta>): void => {
+ if (point.meta?.isCentroid) {
+ if (point.meta.clusterId !== undefined && effectiveRunId) {
+ router.actions.push(urls.aiObservabilityCluster(effectiveRunId, point.meta.clusterId))
}
- router.actions.push(
- urls.aiObservabilityTrace(resolvedTraceId, {
- tab: 'summary',
- ...(point.generationId ? { event: point.generationId } : {}),
- ...(point.timestamp ? { timestamp: point.timestamp } : {}),
- })
- )
return
}
-
- // Navigate to trace page for trace/generation clicks
- if (point.traceId) {
- router.actions.push(
- urls.aiObservabilityTrace(point.traceId, {
- tab: 'summary',
- // For generation-level, highlight the specific generation
- ...(clusteringLevel === 'generation' && point.generationId ? { event: point.generationId } : {}),
- // timestamp is now the trace's first_timestamp for both levels
- ...(point.timestamp ? { timestamp: point.timestamp } : {}),
- })
- )
+ if (point.meta) {
+ navigateToClusterItem(point.meta, clusteringLevel, traceSummaries)
}
}
- const { canvasRef, chartRef } = useChart<'scatter'>({
- getConfig: () => {
- if (scatterPlotDatasets.length === 0) {
- return null
- }
-
- return {
- type: 'scatter',
- data: { datasets: scatterPlotDatasets },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- // Chart.js onClick type is complex; cast through unknown for type safety
- onClick: handleClick as unknown as undefined,
- onHover: (event, elements, chart) => {
- const canvas = event.native?.target as HTMLCanvasElement | undefined
- if (!canvas) {
- return
- }
- if (elements.length === 0) {
- canvas.style.cursor = 'default'
- return
- }
- // Eval points are only clickable once their summary has loaded —
- // otherwise the click would route to /traces/<eval_uuid> and 404.
- if (clusteringLevel === 'evaluation') {
- const element = elements[0]
- const dataset = chart?.data?.datasets?.[element.datasetIndex]
- if (isCentroidDataset(dataset)) {
- canvas.style.cursor = 'pointer'
- return
- }
- const point = dataset?.data?.[element.index] as ScatterPoint | undefined
- const summary = point?.generationId ? traceSummaries[point.generationId] : undefined
- canvas.style.cursor = summary?.traceId ? 'pointer' : 'default'
- return
- }
- canvas.style.cursor = 'pointer'
- },
- plugins: {
- legend: {
- display: false,
- },
- zoom: {
- zoom: {
- drag: {
- enabled: true,
- backgroundColor: 'rgba(100, 100, 100, 0.3)',
- borderColor: 'rgba(100, 100, 100, 0.8)',
- borderWidth: 1,
- },
- mode: 'xy',
- },
- },
- tooltip: {
- bodyFont: {
- weight: 'normal',
- },
- footerFont: {
- weight: 'normal',
- style: 'italic',
- },
- callbacks: {
- title: (context) => {
- const datasetLabel = context[0]?.dataset?.label || ''
- return datasetLabel.replace(' (centroid)', '')
- },
- label: (context) => {
- const isCentroid = isCentroidDataset(context.dataset)
- if (isCentroid) {
- return 'Cluster centroid'
- }
-
- const point = context.raw as ScatterPoint
- // For evaluation-level, the cluster item id (= eval uuid) is
- // carried in generationId; traceId is the parent trace being
- // judged, which doesn't key into the summary map.
- // For generation-level, summaries are keyed by generation_id.
- // For trace-level, summaries are keyed by trace_id.
- const summaryKey =
- clusteringLevel === 'generation' || clusteringLevel === 'evaluation'
- ? point.generationId
- : point.traceId
- if (summaryKey) {
- const summary = traceSummaries[summaryKey]
- if (clusteringLevel === 'evaluation') {
- const formatted = formatEvalTitle(summary, 140)
- if (formatted) {
- return formatted
- }
- } else if (summary?.title) {
- return summary.title
- }
- }
-
- return undefined
- },
- footer: (context) => {
- const isCentroid = isCentroidDataset(context[0]?.dataset)
- if (isCentroid) {
- return 'click to view cluster'
- }
-
- const point = context[0]?.raw as ScatterPoint
- if (point?.traceId) {
- return clusteringLevel === 'generation' || clusteringLevel === 'evaluation'
- ? 'click to view generation'
- : 'click to view trace'
- }
- return ''
- },
- },
- },
- },
- scales: {
- x: {
- type: 'linear',
- position: 'bottom',
- display: false,
- },
- y: {
- type: 'linear',
- display: false,
- },
- },
- },
- }
- },
- deps: [scatterPlotDatasets, traceSummaries, traceToClusterTitle],
- })
-
- // Reset zoom on double-click
- useEffect(() => {
- const canvas = canvasRef.current
- if (!canvas) {
- return
- }
-
- const handleDoubleClick = (): void => {
- if (chartRef.current) {
- // resetZoom is added by chartjs-plugin-zoom at runtime
- ;(chartRef.current as unknown as { resetZoom: () => void }).resetZoom()
- }
- }
-
- canvas.addEventListener('dblclick', handleDoubleClick)
- return () => canvas.removeEventListener('dblclick', handleDoubleClick)
- }, [canvasRef, chartRef])
-
if (sortedClusters.length === 0) {
return <div className="text-muted text-center py-8">No cluster data available for visualization</div>
}
return (
- <div className="h-80">
- <canvas ref={canvasRef} />
+ <div className="h-80 flex flex-col" onDoubleClick={() => setZoom(null)}>
+ <ScatterChart
+ series={scatterPlotSeries}
+ theme={theme}
+ config={config}
+ dataAttr="ai-clusters-scatter"
+ onPointClick={handlePointClick}
+ onAreaSelect={setZoom}
+ onError={handleChartError}
+ tooltip={({ point }) => (
+ <ClusterOverviewTooltip
+ point={point}
+ clusteringLevel={clusteringLevel}
+ traceSummaries={traceSummaries}
+ />
+ )}
+ />
</div>
)
}
diff --git a/products/ai_observability/frontend/clusters/ClusterScatterTooltip.tsx b/products/ai_observability/frontend/clusters/ClusterScatterTooltip.tsx
new file mode 100644
index 000000000000..2a8bddd2ff4f
--- /dev/null
+++ b/products/ai_observability/frontend/clusters/ClusterScatterTooltip.tsx
@@ -0,0 +1,86 @@
+import { TooltipFooter, TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'
+import type { ScatterPointDatum } from '@posthog/quill-charts'
+
+import { clusterItemFooter, clusterItemLabel, fallbackItemLabel } from './clusterScatter'
+import type { ClusterScatterMeta } from './clusterScatter'
+import type { Cluster, ClusteringLevel, TraceSummary } from './types'
+
+function TooltipShell({
+ color,
+ title,
+ subtitle,
+ footer,
+}: {
+ color: string
+ title: string
+ subtitle?: string
+ footer?: string
+}): JSX.Element {
+ return (
+ <TooltipSurface>
+ <div className="flex items-center gap-2 min-w-0 font-semibold">
+ <TooltipSwatch color={color} />
+ <span className="truncate">{title}</span>
+ </div>
+ {subtitle ? <div className="opacity-60">{subtitle}</div> : null}
+ {footer ? <TooltipFooter>{footer}</TooltipFooter> : null}
+ </TooltipSurface>
+ )
+}
+
+export function ClusterDetailTooltip({
+ point,
+ cluster,
+ clusteringLevel,
+ traceSummaries,
+}: {
+ point: ScatterPointDatum<ClusterScatterMeta>
+ cluster: Cluster | null
+ clusteringLevel: ClusteringLevel
+ traceSummaries: Record<string, TraceSummary>
+}): JSX.Element {
+ const meta = point.meta ?? {}
+ if (meta.isCentroid) {
+ return <TooltipShell color={point.color} title="Cluster centroid" subtitle="Center of this cluster" />
+ }
+ return (
+ <TooltipShell
+ color={point.color}
+ title={cluster?.title ?? point.seriesLabel}
+ subtitle={
+ clusterItemLabel(meta, clusteringLevel, traceSummaries) ?? fallbackItemLabel(meta, clusteringLevel)
+ }
+ footer={clusterItemFooter(meta, clusteringLevel)}
+ />
+ )
+}
+
+export function ClusterOverviewTooltip({
+ point,
+ clusteringLevel,
+ traceSummaries,
+}: {
+ point: ScatterPointDatum<ClusterScatterMeta>
+ clusteringLevel: ClusteringLevel
+ traceSummaries: Record<string, TraceSummary>
+}): JSX.Element {
+ const meta = point.meta ?? {}
+ if (meta.isCentroid) {
+ return (
+ <TooltipShell
+ color={point.color}
+ title={point.seriesLabel.replace(' (centroid)', '')}
+ subtitle="Cluster centroid"
+ footer="click to view cluster"
+ />
+ )
+ }
+ return (
+ <TooltipShell
+ color={point.color}
+ title={point.seriesLabel}
+ subtitle={clusterItemLabel(meta, clusteringLevel, traceSummaries)}
+ footer={clusterItemFooter(meta, clusteringLevel)}
+ />
+ )
+}
diff --git a/products/ai_observability/frontend/clusters/ClustersView.tsx b/products/ai_observability/frontend/clusters/ClustersView.tsx
index 124e4ac26005..c853864559d4 100644
--- a/products/ai_observability/frontend/clusters/ClustersView.tsx
+++ b/products/ai_observability/frontend/clusters/ClustersView.tsx
@@ -294,7 +294,7 @@ export function ClustersView(): JSX.Element {
</div>
{isScatterPlotExpanded && (
<div className="border-t p-4">
- <ClusterScatterPlot traceSummaries={traceSummaries} />
+ <ClusterScatterPlot />
<div className="flex items-center justify-between mt-2">
<span className="text-xs text-muted">Drag to zoom &middot; Double-click to reset</span>
<Tooltip
diff --git a/products/ai_observability/frontend/clusters/clusterDetailLogic.test.ts b/products/ai_observability/frontend/clusters/clusterDetailLogic.test.ts
index b9ffd0beedeb..20715d1e3e63 100644
--- a/products/ai_observability/frontend/clusters/clusterDetailLogic.test.ts
+++ b/products/ai_observability/frontend/clusters/clusterDetailLogic.test.ts
@@ -199,12 +199,12 @@ describe('clusterDetailLogic', () => {
})
})
- describe('scatterPlotDatasets', () => {
+ describe('scatterPlotSeries', () => {
it('returns empty array when no cluster', () => {
- expect(logic.values.scatterPlotDatasets).toEqual([])
+ expect(logic.values.scatterPlotSeries).toEqual([])
})
- it('returns datasets with trace points and centroid for regular cluster', async () => {
+ it('returns item points and centroid for regular cluster', async () => {
logic.actions.loadClusterDataSuccess({
cluster: mockCluster,
runTimestamp: '2025-01-05T00:00:00Z',
@@ -213,22 +213,23 @@ describe('clusterDetailLogic', () => {
clusteringLevel: 'trace',
})
- const datasets = logic.values.scatterPlotDatasets
- expect(datasets).toHaveLength(2) // trace points + centroid
+ const series = logic.values.scatterPlotSeries
+ expect(series).toHaveLength(2) // item points + centroid
- // First dataset is trace points
- expect(datasets[0].label).toBe('Test Cluster')
- expect(datasets[0].data).toHaveLength(3)
- expect(datasets[0].pointStyle).toBe('circle')
+ // First series is item points
+ expect(series[0].label).toBe('Test Cluster')
+ expect(series[0].points).toHaveLength(3)
+ expect(series[0].shape).toBe('circle')
- // Second dataset is centroid
- expect(datasets[1].label).toBe('Centroid')
- expect(datasets[1].data).toHaveLength(1)
- expect(datasets[1].data[0].x).toBe(mockCluster.centroid_x)
- expect(datasets[1].data[0].y).toBe(mockCluster.centroid_y)
+ // Second series is the centroid
+ expect(series[1].label).toBe('Centroid')
+ expect(series[1].points).toHaveLength(1)
+ expect(series[1].points[0].x).toBe(mockCluster.centroid_x)
+ expect(series[1].points[0].y).toBe(mockCluster.centroid_y)
+ expect(series[1].points[0].meta).toMatchObject({ isCentroid: true })
})
- it('returns datasets without centroid for outlier cluster', async () => {
+ it('returns items without centroid for outlier cluster', async () => {
logic.actions.loadClusterDataSuccess({
cluster: mockOutlierCluster,
runTimestamp: '2025-01-05T00:00:00Z',
@@ -237,10 +238,10 @@ describe('clusterDetailLogic', () => {
clusteringLevel: 'trace',
})
- const datasets = logic.values.scatterPlotDatasets
- expect(datasets).toHaveLength(1) // only trace points, no centroid
+ const series = logic.values.scatterPlotSeries
+ expect(series).toHaveLength(1) // only item points, no centroid
- expect(datasets[0].pointStyle).toBe('crossRot')
+ expect(series[0].shape).toBe('cross')
})
})
diff --git a/products/ai_observability/frontend/clusters/clusterDetailLogic.ts b/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
index b607ef228d8f..95ca348ece03 100644
--- a/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
+++ b/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
@@ -17,6 +17,7 @@ import type { ProductIntentProperties } from '../../../../frontend/src/lib/utils
import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
import type { ApplyUrlStatePayload } from '../aiObservabilitySharedLogic'
import { loadClusterMetrics } from './clusterMetricsLoader'
+import type { ClusterScatterSeries } from './clusterScatter'
import {
FILTER_QUERY_MAX_ROWS,
AI_OBSERVABILITY_CLUSTER_SCENE_TAG,
@@ -56,17 +57,6 @@ export interface ClusterData {
clusteringLevel: ClusteringLevel
}
-export interface ScatterDataset {
- label: string
- data: Array<{ x: number; y: number; traceId?: string; generationId?: string; timestamp?: string }>
- backgroundColor: string
- borderColor: string
- borderWidth: number
- pointRadius: number
- pointHoverRadius: number
- pointStyle?: 'circle' | 'crossRot'
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface clusterDetailLogicValues {
propertyFilters: AnyPropertyFilter[] // aiObservabilitySharedLogic
@@ -86,7 +76,7 @@ export interface clusterDetailLogicValues {
paginatedTraceIds: string[]
paginatedTracesWithSummaries: TraceWithSummary[]
runTimestamp: string
- scatterPlotDatasets: ScatterDataset[]
+ scatterPlotSeries: ClusterScatterSeries[]
sortedTraceIds: string[]
totalPages: number
totalTraces: number
@@ -188,7 +178,7 @@ export interface clusterDetailLogicMeta {
windowEnd: (clusterData: ClusterData | null) => string
clusteringLevel: (clusterData: ClusterData | null) => ClusteringLevel
isOutlierCluster: (cluster: Cluster | null) => boolean
- scatterPlotDatasets: (cluster: Cluster | null, isOutlierCluster: boolean) => ScatterDataset[]
+ scatterPlotSeries: (cluster: Cluster | null, isOutlierCluster: boolean) => ClusterScatterSeries[]
sortedTraceIds: (cluster: Cluster | null, filteredItemIds: Set<string> | null) => string[]
totalTraces: (sortedTraceIds: string[]) => number
unfilteredTotalTraces: (cluster: Cluster | null) => number
@@ -475,49 +465,43 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([
(cluster: Cluster | null): boolean => cluster?.cluster_id === NOISE_CLUSTER_ID,
],
- scatterPlotDatasets: [
+ scatterPlotSeries: [
(s) => [s.cluster, s.isOutlierCluster],
- (cluster: Cluster | null, isOutlier: boolean): ScatterDataset[] => {
+ (cluster: Cluster | null, isOutlier: boolean): ClusterScatterSeries[] => {
if (!cluster) {
return []
}
const color = isOutlier ? OUTLIER_COLOR : getSeriesColor(cluster.cluster_id)
- const tracePoints = Object.entries(cluster.traces).map(([itemKey, traceInfo]) => ({
- x: traceInfo.x,
- y: traceInfo.y,
- // Use explicit trace_id/generation_id from backend if available
- // Fall back to itemKey for backwards compatibility
- traceId: traceInfo.trace_id || itemKey,
- generationId: traceInfo.generation_id,
- timestamp: traceInfo.timestamp,
- }))
-
- const result: ScatterDataset[] = [
+ const result: ClusterScatterSeries[] = [
{
+ key: 'items',
label: cluster.title,
- data: tracePoints,
- backgroundColor: `${color}80`,
- borderColor: color,
- borderWidth: 1,
+ color,
pointRadius: 5,
- pointHoverRadius: 7,
- pointStyle: isOutlier ? 'crossRot' : 'circle',
+ shape: isOutlier ? 'cross' : 'circle',
+ points: Object.entries(cluster.traces).map(([itemKey, traceInfo]) => ({
+ x: traceInfo.x,
+ y: traceInfo.y,
+ meta: {
+ traceId: traceInfo.trace_id || itemKey,
+ generationId: traceInfo.generation_id,
+ timestamp: traceInfo.timestamp,
+ },
+ })),
},
]
// Add centroid marker for non-outlier clusters
if (!isOutlier) {
result.push({
+ key: 'centroid',
label: 'Centroid',
- data: [{ x: cluster.centroid_x, y: cluster.centroid_y }],
- backgroundColor: `${color}40`,
- borderColor: color,
- borderWidth: 2,
+ color,
pointRadius: 10,
- pointHoverRadius: 12,
- pointStyle: 'circle',
+ shape: 'circle',
+ points: [{ x: cluster.centroid_x, y: cluster.centroid_y, meta: { isCentroid: true } }],
})
}
diff --git a/products/ai_observability/frontend/clusters/clusterScatter.test.ts b/products/ai_observability/frontend/clusters/clusterScatter.test.ts
new file mode 100644
index 000000000000..58a114ad208a
--- /dev/null
+++ b/products/ai_observability/frontend/clusters/clusterScatter.test.ts
@@ -0,0 +1,37 @@
+import { clusterItemLabel } from './clusterScatter'
+import type { ClusterScatterMeta } from './clusterScatter'
+import { TraceSummary } from './types'
+
+const summary = (overrides: Partial<TraceSummary>): TraceSummary => ({
+ traceId: 'trace-1',
+ title: 'Untitled',
+ flowDiagram: '',
+ bullets: '',
+ interestingNotes: '',
+ timestamp: '2025-01-05T10:00:00Z',
+ ...overrides,
+})
+
+describe('clusterScatter', () => {
+ describe('clusterItemLabel', () => {
+ const meta: ClusterScatterMeta = { traceId: 'trace-1', generationId: 'gen-1' }
+
+ it.each([
+ ['trace', 'trace-1', 'Trace title'],
+ ['generation', 'gen-1', 'Generation title'],
+ ] as const)('reads %s summaries by the id navigation uses', (level, key, title) => {
+ expect(clusterItemLabel(meta, level, { [key]: summary({ title }) })).toBe(title)
+ })
+
+ it('returns nothing when the summary is keyed by the other id', () => {
+ expect(clusterItemLabel(meta, 'trace', { 'gen-1': summary({ title: 'x' }) })).toBeUndefined()
+ expect(clusterItemLabel(meta, 'generation', { 'trace-1': summary({ title: 'x' }) })).toBeUndefined()
+ })
+
+ it('strips the verdict suffix for evaluation summaries, keyed by generationId', () => {
+ expect(clusterItemLabel(meta, 'evaluation', { 'gen-1': summary({ title: 'Accuracy: PASS' }) })).toBe(
+ 'Accuracy'
+ )
+ })
+ })
+})
diff --git a/products/ai_observability/frontend/clusters/clusterScatter.ts b/products/ai_observability/frontend/clusters/clusterScatter.ts
new file mode 100644
index 000000000000..c6bf9b3963dc
--- /dev/null
+++ b/products/ai_observability/frontend/clusters/clusterScatter.ts
@@ -0,0 +1,97 @@
+import { router } from 'kea-router'
+
+import type { ScatterSeries } from '@posthog/quill-charts'
+
+import { urls } from 'scenes/urls'
+
+import { formatEvalTitle } from './traceSummaryLoader'
+import type { ClusteringLevel, TraceSummary } from './types'
+
+/** Per-point data carried through quill's scatter `meta`, handed back on hover and click. */
+export interface ClusterScatterMeta {
+ traceId?: string
+ generationId?: string
+ timestamp?: string
+ clusterId?: number
+ isCentroid?: boolean
+}
+
+export type ClusterScatterSeries = ScatterSeries<ClusterScatterMeta>
+
+/** Routes a clicked item point (trace / generation / evaluation) to its trace page. Shared by the
+ * overview and single-cluster plots, which navigate identically for non-centroid points. */
+export function navigateToClusterItem(
+ meta: ClusterScatterMeta,
+ clusteringLevel: ClusteringLevel,
+ traceSummaries: Record<string, TraceSummary>
+): void {
+ if (clusteringLevel === 'evaluation') {
+ // point.traceId is the backend's eval-uuid fallback when metadata didn't resolve; routing
+ // there 404s. Use the loaded summary's real traceId; no-op until it loads.
+ const resolvedTraceId = meta.generationId ? traceSummaries[meta.generationId]?.traceId : undefined
+ if (!resolvedTraceId) {
+ return
+ }
+ router.actions.push(
+ urls.aiObservabilityTrace(resolvedTraceId, {
+ tab: 'summary',
+ ...(meta.generationId ? { event: meta.generationId } : {}),
+ ...(meta.timestamp ? { timestamp: meta.timestamp } : {}),
+ })
+ )
+ return
+ }
+
+ if (meta.traceId) {
+ router.actions.push(
+ urls.aiObservabilityTrace(meta.traceId, {
+ tab: 'summary',
+ ...(clusteringLevel === 'generation' && meta.generationId ? { event: meta.generationId } : {}),
+ ...(meta.timestamp ? { timestamp: meta.timestamp } : {}),
+ })
+ )
+ }
+}
+
+/** Tooltip body line for an item point: the trace/eval summary title once it has loaded. */
+export function clusterItemLabel(
+ meta: ClusterScatterMeta,
+ clusteringLevel: ClusteringLevel,
+ traceSummaries: Record<string, TraceSummary>
+): string | undefined {
+ // Evaluation/generation summaries are keyed by generation_id; trace summaries by trace_id.
+ const summaryKey =
+ clusteringLevel === 'generation' || clusteringLevel === 'evaluation' ? meta.generationId : meta.traceId
+ if (!summaryKey) {
+ return undefined
+ }
+ const summary = traceSummaries[summaryKey]
+ if (clusteringLevel === 'evaluation') {
+ return formatEvalTitle(summary, 140) || undefined
+ }
+ return summary?.title || undefined
+}
+
+export function clusterItemFooter(meta: ClusterScatterMeta, clusteringLevel: ClusteringLevel): string {
+ if (!meta.traceId) {
+ return ''
+ }
+ return clusteringLevel === 'generation' || clusteringLevel === 'evaluation'
+ ? 'click to view generation'
+ : 'click to view trace'
+}
+
+/** Placeholder body line shown until the item's summary loads: a shortened id. */
+export function fallbackItemLabel(meta: ClusterScatterMeta, clusteringLevel: ClusteringLevel): string | undefined {
+ if (!meta.traceId) {
+ return undefined
+ }
+ const id = (meta.generationId || meta.traceId).slice(0, 8)
+ if (clusteringLevel === 'generation') {
+ return `Generation ${id}...`
+ }
+ if (clusteringLevel === 'evaluation') {
+ return `Evaluation ${id}...`
+ }
+ return `Trace ${meta.traceId.slice(0, 8)}...`
+}
diff --git a/products/ai_observability/frontend/clusters/clustersLogic.test.ts b/products/ai_observability/frontend/clusters/clustersLogic.test.ts
index 2f901d035b3b..1eb9eaae06f2 100644
--- a/products/ai_observability/frontend/clusters/clustersLogic.test.ts
+++ b/products/ai_observability/frontend/clusters/clustersLogic.test.ts
@@ -341,8 +341,8 @@ describe('clustersLogic', () => {
})
})
- describe('traceToClusterTitle', () => {
- it('maps trace IDs to cluster titles', async () => {
+ describe('scatterPlotSeries', () => {
+ it('creates item and centroid series for regular clusters', async () => {
const mockRun: ClusteringRun = {
runId: 'test-run',
windowStart: '2025-01-01T00:00:00Z',
@@ -355,60 +355,16 @@ describe('clustersLogic', () => {
logic.actions.loadClusteringRunSuccess(mockRun)
- const mapping = logic.values.traceToClusterTitle
- expect(mapping['trace-1']).toBe('Cluster A')
- expect(mapping['trace-2']).toBe('Cluster A')
- expect(mapping['trace-3']).toBe('Cluster B')
- })
-
- it('uses default title when cluster title is empty', async () => {
- const clusterWithoutTitle: Cluster = {
- ...mockCluster1,
- title: '',
- }
+ const series = logic.values.scatterPlotSeries
+ // 2 item series + 2 centroid series
+ expect(series.length).toBe(4)
- const mockRun: ClusteringRun = {
- runId: 'test-run',
- windowStart: '2025-01-01T00:00:00Z',
- windowEnd: '2025-01-08T00:00:00Z',
- totalItemsAnalyzed: 10,
- clusters: [clusterWithoutTitle],
- timestamp: '2025-01-08T00:00:00Z',
- clusteringParams: undefined,
- }
-
- logic.actions.loadClusteringRunSuccess(mockRun)
-
- const mapping = logic.values.traceToClusterTitle
- expect(mapping['trace-1']).toBe('Cluster 0')
+ const itemSeries = series.filter((d) => !d.label.includes('(centroid)'))
+ expect(itemSeries.length).toBe(2)
+ expect(itemSeries[0].shape).toBe('circle')
})
- })
- describe('scatterPlotDatasets', () => {
- it('creates datasets for regular clusters', async () => {
- const mockRun: ClusteringRun = {
- runId: 'test-run',
- windowStart: '2025-01-01T00:00:00Z',
- windowEnd: '2025-01-08T00:00:00Z',
- totalItemsAnalyzed: 15,
- clusters: [mockCluster1, mockCluster2],
- timestamp: '2025-01-08T00:00:00Z',
- clusteringParams: undefined,
- }
-
- logic.actions.loadClusteringRunSuccess(mockRun)
-
- const datasets = logic.values.scatterPlotDatasets
- // 2 trace datasets + 2 centroid datasets
- expect(datasets.length).toBe(4)
-
- // Verify trace datasets have correct structure
- const traceDatasets = datasets.filter((d) => !d.label.includes('(centroid)'))
- expect(traceDatasets.length).toBe(2)
- expect(traceDatasets[0].pointStyle).toBe('circle')
- })
-
- it('uses crossRot style for outlier cluster', async () => {
+ it('uses cross shape for outlier cluster', async () => {
const mockRun: ClusteringRun = {
runId: 'test-run',
windowStart: '2025-01-01T00:00:00Z',
@@ -421,11 +377,10 @@ describe('clustersLogic', () => {
logic.actions.loadClusteringRunSuccess(mockRun)
- const datasets = logic.values.scatterPlotDatasets
- const outlierDataset = datasets.find((d) => d.label === 'Outliers')
+ const series = logic.values.scatterPlotSeries
+ const outlierSeries = series.find((d) => d.label === 'Outliers')
- expect(outlierDataset).toBeTruthy()
- expect(outlierDataset?.pointStyle).toBe('crossRot')
+ expect(outlierSeries).toMatchObject({ shape: 'cross' })
})
it('does not create centroid marker for outlier cluster', async () => {
@@ -441,15 +396,15 @@ describe('clustersLogic', () => {
logic.actions.loadClusteringRunSuccess(mockRun)
- const datasets = logic.values.scatterPlotDatasets
- const centroidDatasets = datasets.filter((d) => d.label.includes('(centroid)'))
+ const series = logic.values.scatterPlotSeries
+ const centroidSeries = series.filter((d) => d.label.includes('(centroid)'))
// Only one centroid for regular cluster, none for outliers
- expect(centroidDatasets.length).toBe(1)
- expect(centroidDatasets[0].label).toBe('Cluster A (centroid)')
+ expect(centroidSeries.length).toBe(1)
+ expect(centroidSeries[0].label).toBe('Cluster A (centroid)')
})
- it('includes trace metadata in data points', async () => {
+ it('carries trace metadata into item points', async () => {
const mockRun: ClusteringRun = {
runId: 'test-run',
windowStart: '2025-01-01T00:00:00Z',
@@ -462,14 +417,14 @@ describe('clustersLogic', () => {
logic.actions.loadClusteringRunSuccess(mockRun)
- const datasets = logic.values.scatterPlotDatasets
- const traceDataset = datasets.find((d) => d.label === 'Cluster A')
+ const series = logic.values.scatterPlotSeries
+ const itemSeries = series.find((d) => d.label === 'Cluster A')
- expect(traceDataset?.data[0]).toMatchObject({
- x: 0.0,
- y: 0.0,
- traceId: 'trace-1',
- timestamp: '2025-01-05T10:00:00Z',
+ expect(itemSeries).toMatchObject({
+ points: [
+ { x: 0.0, y: 0.0, meta: { traceId: 'trace-1', timestamp: '2025-01-05T10:00:00Z' } },
+ { x: 0.1, y: 0.1, meta: { traceId: 'trace-2', timestamp: '2025-01-05T11:00:00Z' } },
+ ],
})
})
})
diff --git a/products/ai_observability/frontend/clusters/clustersLogic.ts b/products/ai_observability/frontend/clusters/clustersLogic.ts
index 2e6a4773401e..33f4733d734f 100644
--- a/products/ai_observability/frontend/clusters/clustersLogic.ts
+++ b/products/ai_observability/frontend/clusters/clustersLogic.ts
@@ -17,6 +17,7 @@ import { AnyPropertyFilter, Breadcrumb, PropertyFilterType, PropertyOperator } f
import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
import type { ApplyUrlStatePayload } from '../aiObservabilitySharedLogic'
import { loadClusterMetrics } from './clusterMetricsLoader'
+import type { ClusterScatterSeries } from './clusterScatter'
import {
FILTER_QUERY_MAX_ROWS,
AI_OBSERVABILITY_CLUSTERS_SCENE_TAG,
@@ -58,34 +59,6 @@ function eventNameForLevel(
return '$ai_trace_clusters'
}
-export interface ScatterDataset {
- label: string
- data: Array<{
- x: number
- y: number
- traceId?: string
- generationId?: string
- clusterId?: number
- timestamp?: string
- }>
- backgroundColor: string
- borderColor: string
- borderWidth: number
- pointRadius: number
- pointHoverRadius: number
- pointStyle?:
- | 'circle'
- | 'cross'
- | 'crossRot'
- | 'dash'
- | 'line'
- | 'rect'
- | 'rectRounded'
- | 'rectRot'
- | 'star'
- | 'triangle'
-}
-
export type ClustersLogicProps = Record<string, never>
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -122,13 +95,12 @@ export interface clustersLogicValues {
propertyFilteredItemIds: Set<string> | null
propertyFilteredItemIdsLoading: boolean
propertyFiltersActive: boolean
- scatterPlotDatasets: ScatterDataset[]
+ scatterPlotSeries: ClusterScatterSeries[]
selectedRunId: string | null
sortedClusters: Cluster[]
totalItemCount: number
traceSummaries: Record<string, TraceSummary>
traceSummariesLoading: boolean
- traceToClusterTitle: Record<string, string>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -287,8 +259,7 @@ export interface clustersLogicMeta {
filteredItemCount: (filteredSortedClusters: Cluster[]) => number
totalItemCount: (sortedClusters: Cluster[]) => number
isClusterExpanded: (expandedClusterIds: Set<number>) => (clusterId: number) => boolean
- traceToClusterTitle: (sortedClusters: Cluster[]) => Record<string, string>
- scatterPlotDatasets: (filteredSortedClusters: Cluster[]) => ScatterDataset[]
+ scatterPlotSeries: (filteredSortedClusters: Cluster[]) => ClusterScatterSeries[]
}
}
@@ -835,25 +806,11 @@ export const clustersLogic = kea<clustersLogicType>([
expandedIds.has(clusterId),
],
- traceToClusterTitle: [
- (s) => [s.sortedClusters],
- (clusters: Cluster[]): Record<string, string> => {
- const map: Record<string, string> = {}
- for (const cluster of clusters) {
- const clusterTitle = cluster.title || `Cluster ${cluster.cluster_id}`
- for (const traceId of Object.keys(cluster.traces)) {
- map[traceId] = clusterTitle
- }
- }
- return map
- },
- ],
-
- scatterPlotDatasets: [
+ scatterPlotSeries: [
(s) => [s.filteredSortedClusters],
- (clusters: Cluster[]): ScatterDataset[] => {
- const itemDatasets: ScatterDataset[] = []
- const centroidDatasets: ScatterDataset[] = []
+ (clusters: Cluster[]): ClusterScatterSeries[] => {
+ const itemSeries: ClusterScatterSeries[] = []
+ const centroidSeries: ClusterScatterSeries[] = []
for (const cluster of clusters) {
const isOutlier = cluster.cluster_id === NOISE_CLUSTER_ID
@@ -861,40 +818,43 @@ export const clustersLogic = kea<clustersLogicType>([
const label = cluster.title || `Cluster ${cluster.cluster_id}`
// Item points (traces or generations)
- itemDatasets.push({
+ itemSeries.push({
+ key: `cluster-${cluster.cluster_id}`,
label,
- data: Object.entries(cluster.traces).map(([itemKey, itemInfo]) => ({
+ color,
+ pointRadius: 4,
+ shape: isOutlier ? 'cross' : 'circle', // X shape for outliers
+ points: Object.entries(cluster.traces).map(([itemKey, itemInfo]) => ({
x: itemInfo.x,
y: itemInfo.y,
- // Use explicit trace_id/generation_id from backend if available
- // Fall back to itemKey for backwards compatibility
- traceId: itemInfo.trace_id || itemKey,
- generationId: itemInfo.generation_id,
- timestamp: itemInfo.timestamp,
+ meta: {
+ traceId: itemInfo.trace_id || itemKey,
+ generationId: itemInfo.generation_id,
+ timestamp: itemInfo.timestamp,
+ },
})),
- backgroundColor: `${color}80`,
- borderColor: color,
- borderWidth: 1,
- pointRadius: isOutlier ? 4 : 4,
- pointHoverRadius: isOutlier ? 6 : 6,
- pointStyle: isOutlier ? 'crossRot' : 'circle', // X shape for outliers
})
// Centroid marker (skip for outliers - they don't have a real centroid)
if (!isOutlier) {
- centroidDatasets.push({
+ centroidSeries.push({
+ key: `centroid-${cluster.cluster_id}`,
label: `${label} (centroid)`,
- data: [{ x: cluster.centroid_x, y: cluster.centroid_y, clusterId: cluster.cluster_id }],
- backgroundColor: `${color}40`,
- borderColor: color,
- borderWidth: 2,
+ color,
pointRadius: 8,
- pointHoverRadius: 10,
+ shape: 'circle',
+ points: [
+ {
+ x: cluster.centroid_x,
+ y: cluster.centroid_y,
+ meta: { clusterId: cluster.cluster_id, isCentroid: true },
+ },
+ ],
})
}
}
- return [...itemDatasets, ...centroidDatasets]
+ return [...itemSeries, ...centroidSeries]
},
],
}),
diff --git a/products/ai_observability/frontend/clusters/constants.ts b/products/ai_observability/frontend/clusters/constants.ts
index ae4534aba50f..14c3b6fd0f53 100644
--- a/products/ai_observability/frontend/clusters/constants.ts
+++ b/products/ai_observability/frontend/clusters/constants.ts
@@ -37,22 +37,3 @@ export const SAFE_ID_RE = /^[a-f0-9-]+$/i
// this are silently truncated server-side, so post-hoc property-filter queries against the
// full set of cluster items must either fit under the cap or fall back to "no filtering".
export const FILTER_QUERY_MAX_ROWS = 50000
-
-/**
- * Centroid detection for chart.js scatter datasets.
- *
- * Two label shapes exist:
- * - Overview plot (ClusterScatterPlot): per-cluster label with "(centroid)" suffix,
- * e.g. "Auth failures (centroid)" — so one cluster's points and centroid stay visually paired.
- * - Single-cluster detail plot (ClusterDetailScatterPlot): just "Centroid" since the dataset
- * only holds one cluster's worth of data.
- *
- * Centralising keeps tooltip/click suppression in sync across both views.
- */
-export function isCentroidDataset(dataset: { label?: string } | undefined | null): boolean {
- const label = dataset?.label
- if (!label) {
- return false
- }
- return label === 'Centroid' || label.includes('(centroid)')
-}