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): redesign the online evals overview page (#122070)

Bernat Torres716c77069998
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b57ca7644cd5..591c507de034 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8900,6 +8900,58 @@ snapshots:
hash: v1.k794b7964.1cd199ebfc3ecf7f75c065b7f670778fed080997c6afb56bac02e49b49637c96.nFRmsF5CaYLyxKdaRS0UtS6ba8esGKqBv6MPu7HwOBo
scenes-app-ai-observability-evaluation-explanation--system-one-zero-probability--light:
hash: v1.k794b7964.f56325c23a185f032b8e7c331463345ea780e4e1b9a85f44a2f560869f06afa4.KcU1H2opmRuSoQcBHacqKya9WVvI5GATsFn_lgLD8rM
+ scenes-app-ai-observability-evaluations-overview--directory-open--dark:
+ hash: v1.k794b7964.cb88d8783a0c7ab63525f13c5aafbdddcb35a5448c12a774c8465122228257d5.vVBMLgF2jQd6tJ_DlQjocyXVoe4XtpNjDKGijdEz8oU
+ scenes-app-ai-observability-evaluations-overview--directory-open--light:
+ hash: v1.k794b7964.c9ec46ad37a56b9b6452a26a91c958b57896de6a10f176c7a17bb379068a6b1c.BqQx9mi7aDofnP8isJ9I4NDv5e7N0bXfqDgs0X0g1ZE
+ scenes-app-ai-observability-evaluations-overview--drawer-categories--dark:
+ hash: v1.k794b7964.4cabff23a255eb480b2552eaed88a2b4246810bcfff9395dfca593acc8fe9edd.sQaiXQclGUKel63G3sDb5trGxWS7mYXJmwP11Zxb_-g
+ scenes-app-ai-observability-evaluations-overview--drawer-categories--light:
+ hash: v1.k794b7964.fbf879ba63125470a86901970419cfa3c201288ad3253258c125cf15efd4a40f.U5VPkQF1GmH7Q7fxWkcutAXXaFnlDuwrN9HGi7dCBg8
+ scenes-app-ai-observability-evaluations-overview--drawer-empty-disabled--dark:
+ hash: v1.k794b7964.447a7751495e5a6bcd17385767bcba2b8bdc81f02d53eecad34d73cacd840580.kbEQMyBlAG71PNTjmErbPj4RwbEn2yk54Fkbii-hw44
+ scenes-app-ai-observability-evaluations-overview--drawer-empty-disabled--light:
+ hash: v1.k794b7964.6f140231f4a4b29734b368a4e593a74d19f3b1725cd84353c722be4515a616d8.qUumzeREHGY6StfR8u2U_y5amFAOD0Nv9cXA4p7uLGk
+ scenes-app-ai-observability-evaluations-overview--drawer-empty-enabled--dark:
+ hash: v1.k794b7964.73805cdb88f1006a914063e81575b7e6d335833df06a44c60cc060b41953c5f9.JZEVhh4lYjNn81V9Sc_9CAr3V0_n2Jy5XtnF-v2WeXM
+ scenes-app-ai-observability-evaluations-overview--drawer-empty-enabled--light:
+ hash: v1.k794b7964.f255b69ad63c46b41655c948366d0d64ef44d53f4000342cc58cb8fccd81b91d.H3lcZdE7MgJCvzIVyKBKrViKTx761pOjLJFaPtXVrOI
+ scenes-app-ai-observability-evaluations-overview--drawer-empty-errored--dark:
+ hash: v1.k794b7964.6db2d2de62e9a61caab066053e25b39b40965df38585d350c19f4dad835da44d.a82YqeR5UYL40v85fGps9eUhtsW6sfKTa5srO9pk5J4
+ scenes-app-ai-observability-evaluations-overview--drawer-empty-errored--light:
+ hash: v1.k794b7964.46ebd323b280383d83502730d0693a7637241c7fe071f470983d0d3c341fd41e.ndXSeiqebpcyhHkc5ui4BJMPkUOxC54H3cc29cFcj90
+ scenes-app-ai-observability-evaluations-overview--drawer-pass-rate--dark:
+ hash: v1.k794b7964.c59641eacce51ec3bc0f654e544e11b9b734d4c91343ed43cbd529c1c01e6b0f.skJafCWiaK6Ntu5ozzs0KEGD_AMTu1vs-KnRqM2zIb4
+ scenes-app-ai-observability-evaluations-overview--drawer-pass-rate--light:
+ hash: v1.k794b7964.b872bfa48645d18ab2f8b5b32cacc3607b165d47c19352eef6e9b995416412b3.YvpSYQnvFB58Z3r1lXMdmvXwdyF5tvHsZAzoFhANG1o
+ scenes-app-ai-observability-evaluations-overview--drawer-score--dark:
+ hash: v1.k794b7964.a724067d973d728e4b200a0c48086adacf1f7dc563fd0d22d4538e659f5ab176.av1tQF4dnvpQuyV--VENrB9aGQaI7hAEAZEtcRvlYC8
+ scenes-app-ai-observability-evaluations-overview--drawer-score--light:
+ hash: v1.k794b7964.62e77593a1b70279196c11f65882695bd9d78ce5eb4f9aa510094b6d36915442.4fO10Nj_BEMedqqz-9w52lt2gISZlv-NOr5kPFDoGWk
+ scenes-app-ai-observability-evaluations-overview--drawer-sentiment--dark:
+ hash: v1.k794b7964.277ece705e647f0f0228dd7b5349fecfee655ac017388cb7598951b69b2af3d0.R855kqaimlHKt0diuffMtmhXH1tpVDlaGQAppq4F0xI
+ scenes-app-ai-observability-evaluations-overview--drawer-sentiment--light:
+ hash: v1.k794b7964.14f497fb2a77a4c3a3729471356d3f912b83badaab94679dc6ffcc6343ffac56.RY7t5NdEAfI5m-7NfVTZ1ArAus8L-uDDJtxq8E9SdUc
+ scenes-app-ai-observability-evaluations-overview--many-evaluations--dark:
+ hash: v1.k794b7964.fbcbaae66d5a2c77d8e77dbdc3e9f7992a2008b2a3864938104978f40e4321eb.ifYIp5Fu1sF7_XEVmb1VDKiooJj5K60HOLWb9MIhL3Y
+ scenes-app-ai-observability-evaluations-overview--many-evaluations--light:
+ hash: v1.k794b7964.95c1dd456bde8b6ec7a2f6dfc408bb0f82d3fc5f5bb65c476b8c3750a09e678a.CMP5LgTTvQOCzCsOTs1Y3qzuM_-t2aOW3hVxTCBKt1g
+ scenes-app-ai-observability-evaluations-overview--many-evaluations-with-directories--dark:
+ hash: v1.k794b7964.f9d1904e16fbb8b91b95db6da6fc18d0fcc815d90e5424e45da5c7ae0fc5afde.0lSsJ4kSoHKIjCu3DrPW0JQN2osfjyqAFps5ZpK9mNM
+ scenes-app-ai-observability-evaluations-overview--many-evaluations-with-directories--light:
+ hash: v1.k794b7964.c3825d792e81b5625958f0760e3399c490d6ac3350cb19b0362c13d015239c8b.IH6TyFEKE4zDPgKXQ0enT0Yc9iYjeQdokOA9EuOxcxQ
+ scenes-app-ai-observability-evaluations-overview--nothing-graded--dark:
+ hash: v1.k794b7964.bd7288f40aa7d8977501f22bcc98d7c01b703f3be982002010f0bca198837aa7.wbuna3fvctXcy8flwdNVoGKD9v6wR7iEb-NUn-Cgn_Q
+ scenes-app-ai-observability-evaluations-overview--nothing-graded--light:
+ hash: v1.k794b7964.2870efedd0db26c0b9ece8d9cce6b927b9ba0cb730478ae13a3b031bec7190b5.-bnKQwjXhvGM60fQxX92vygvdm1Vwbb-luGqFzroNOs
+ scenes-app-ai-observability-evaluations-overview--rate-limited--dark:
+ hash: v1.k794b7964.e8aa37a66dc03651a6633b7e997672b8abf80f42a8efe8df7f9a685af6321f4a.iraGLjZfIqSCcP-vxVIYB22Fe31a7f4ScQi6rcGnB3g
+ scenes-app-ai-observability-evaluations-overview--rate-limited--light:
+ hash: v1.k794b7964.db4495726f9c49b37dbe0fc0d388c4de8cc2a807f265554d2d40b22a361a59b5.kcY7HlDaxjApOhHIujs93_5fTT2Gt0VFQYl3PxORgYs
+ scenes-app-ai-observability-evaluations-overview--two-evaluations--dark:
+ hash: v1.k794b7964.01f4f76c91fed6f85af93311a8efc739f91cacd64bd338810c8e5f16a79414e2.LcTqRRMA_gix5MSAsWEebZ4StIvkzJRfDYPxiCoCLxA
+ scenes-app-ai-observability-evaluations-overview--two-evaluations--light:
+ hash: v1.k794b7964.aabf120a9d267deae68e65135f81d73b102c3fc3dcbb1044dab4ce464f07412d.Zrk0PAAQjMkhQJ-GUIXCZa2zGLsYAKTCVqGlVfcikc0
scenes-app-ai-observability-image-preview--failed-image--dark:
hash: v1.k794b7964.e4f4b0993222ae8f8a3f0e59e4c0528312f13a1e358df37e53d4331b4dacbae5.oDWA2N3BGPuGJvd9voAvMpM2rCR7tfrLjEwDqJT6MYk
scenes-app-ai-observability-image-preview--failed-image--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 81e940ff35fe..bee805b73f2a 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -252,6 +252,7 @@ export const FEATURE_FLAGS = {
// Temporary feature flags, still WIP, should be removed eventually
ADVANCE_MARKETING_ANALYTICS_SETTINGS: 'advance-marketing-analytics-settings', // owner: @jabahamondes #team-web-analytics
+ AI_OBSERVABILITY_EVALUATIONS_OVERVIEW: 'ai-observability-evaluations-overview', // owner: #team-ai-observability
AI_OBSERVABILITY_OFFLINE_EVALUATIONS: 'ai-observability-offline-evaluations', // owner: #team-ai-observability
AI_OBSERVABILITY_TRACE_REDESIGN: 'ai-observability-trace-redesign', // owner: #team-ai-observability, gates the redesigned trace view
/** Alert edit modal: check history chart + chart/table toggle (table remains when off). */
diff --git a/products/ai_observability/frontend/AIObservabilityReloadAction.tsx b/products/ai_observability/frontend/AIObservabilityReloadAction.tsx
index 3aa1884af2a0..21eaf2673656 100644
--- a/products/ai_observability/frontend/AIObservabilityReloadAction.tsx
+++ b/products/ai_observability/frontend/AIObservabilityReloadAction.tsx
@@ -17,6 +17,7 @@ import { AI_OBSERVABILITY_DATA_COLLECTION_NODE_ID, aiObservabilitySharedLogic }
import { EVALUATION_METRICS_COLLECTION_ID } from './evaluations/components/EvaluationMetrics'
import { evaluationMetricsLogic } from './evaluations/evaluationMetricsLogic'
import { llmEvaluationsLogic } from './evaluations/llmEvaluationsLogic'
+import { evaluationsOverviewLogic } from './evaluations/overview/evaluationsOverviewLogic'
import { aiObservabilityDashboardLogic } from './tabs/aiObservabilityDashboardLogic'
import { aiObservabilitySessionsViewLogic } from './tabs/aiObservabilitySessionsViewLogic'
@@ -55,7 +56,6 @@ export function AIObservabilityReloadAction(): JSX.Element {
const { reloadAll: reloadEvaluationMetrics } = useActions(
dataNodeCollectionLogic({ key: EVALUATION_METRICS_COLLECTION_ID })
)
- const { refreshMetrics: refreshEvaluationMetrics } = useActions(evaluationMetricsLogic)
const { loadEvaluations } = useActions(llmEvaluationsLogic)
const { sessionsLoading } = useValues(aiObservabilitySessionsViewLogic)
const { loadSessions } = useActions(aiObservabilitySessionsViewLogic)
@@ -67,9 +67,11 @@ export function AIObservabilityReloadAction(): JSX.Element {
if (activeTab === 'dashboard') {
triggerDashboardRefresh()
} else if (activeTab === 'evaluations') {
- // Refresh evaluations list and metrics
+ // Refresh evaluations list and metrics. Only the view on screen has its logic mounted, and mounting the
+ // other one from here would start its queries for nothing.
loadEvaluations()
- refreshEvaluationMetrics()
+ evaluationMetricsLogic.findMounted()?.actions.refreshMetrics()
+ evaluationsOverviewLogic.findMounted()?.actions.reloadOverview()
reloadEvaluationMetrics()
} else if (activeTab === 'sessions') {
// The sessions list is a custom loader, not part of the data-node collection reloadAll() drives.
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
index 986bb4f5e47d..f2b64c487c03 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
@@ -61,6 +61,8 @@ import { EvaluationStats, evaluationMetricsLogic } from './evaluationMetricsLogi
import { EvaluationsTabs } from './EvaluationsTabs'
import { EvaluationTemplatesEmptyState } from './EvaluationTemplates'
import { llmEvaluationsLogic } from './llmEvaluationsLogic'
+import { EvaluationResultsTable } from './overview/EvaluationResultsTable'
+import { EvaluationsOverview } from './overview/EvaluationsOverview'
import { statusReasonLabel } from './statusDisplay'
import { EvaluationConfig } from './types'
@@ -133,13 +135,42 @@ function EvaluationDescription({ description }: { description: string }): JSX.El
)
}
+/** The table without the overview. It alone reads the metrics, so the overview never runs their queries. */
+function EvaluationsWithMetricsTable({
+ columns,
+ displayedEvaluations,
+ loading,
+}: {
+ columns: LemonTableColumns<EvaluationConfig>
+ displayedEvaluations: EvaluationConfig[]
+ loading: boolean
+}): JSX.Element {
+ const { evaluationsWithMetrics } = useValues(evaluationMetricsLogic)
+ const displayedIds = new Set(displayedEvaluations.map((evaluation) => evaluation.id))
+
+ return (
+ <LemonTable
+ columns={columns}
+ dataSource={evaluationsWithMetrics.filter((evaluation: EvaluationConfig) =>
+ displayedIds.has(evaluation.id)
+ )}
+ loading={loading}
+ rowKey="id"
+ pagination={{
+ pageSize: 50,
+ }}
+ nouns={['evaluation', 'evaluations']}
+ />
+ )
+}
+
function AIObservabilityEvaluationsContent(): JSX.Element {
const evaluationsLogic = llmEvaluationsLogic()
- const metricsLogic = evaluationMetricsLogic()
const {
evaluations,
displayedEvaluations,
evaluationsLoading,
+ evaluationsLoadFailed,
evaluationsFilter,
showDisabledEvaluations,
dateFilter,
@@ -170,7 +201,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
selectDirectory,
deleteEvaluation,
} = useActions(evaluationsLogic)
- const { evaluationsWithMetrics } = useValues(metricsLogic)
+ const overviewEnabled = useFeatureFlag('AI_OBSERVABILITY_EVALUATIONS_OVERVIEW')
const { push } = useActions(router)
const { searchParams } = useValues(router)
const evaluationUrl = (id: string): string => combineUrl(urls.aiObservabilityEvaluation(id), searchParams).url
@@ -182,9 +213,6 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
evaluation.user_access_level ?? undefined
)
- const filteredEvaluationsWithMetrics = evaluationsWithMetrics.filter((evaluation: EvaluationConfig) =>
- displayedEvaluations.some((filtered) => filtered.id === evaluation.id)
- )
const directoryById = new Map(evaluationDirectories.map((directory) => [directory.id, directory]))
const columns: LemonTableColumns<EvaluationConfig> = [
@@ -553,7 +581,9 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
},
]
+ // A failed list is not an empty project. The overview still loads, and in a directory it shows a retry.
const showEmptyState =
+ !(overviewEnabled && evaluationsLoadFailed) &&
!evaluationsLoading &&
!evaluationDirectoriesLoading &&
evaluations.length === 0 &&
@@ -603,7 +633,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
- {!selectedDirectoryId && (
+ {!selectedDirectoryId && !overviewEnabled && (
<AccessControlAction
resourceType={AccessControlResourceType.Evaluation}
minAccessLevel={AccessControlLevel.Editor}
@@ -639,33 +669,41 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
<EvaluationTemplatesEmptyState />
) : (
<>
- <DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />
+ {overviewEnabled ? (
+ <EvaluationsOverview />
+ ) : (
+ <>
+ <DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />
- <EvaluationMetrics />
+ <EvaluationMetrics />
+ </>
+ )}
- <div className="flex flex-wrap items-center gap-2">
- <LemonInput
- type="search"
- placeholder="Search online evals..."
- value={evaluationsFilter}
- data-attr="evaluations-search-input"
- onChange={setEvaluationsFilter}
- prefix={<IconSearch />}
- className="max-w-sm"
- />
- <LemonButton
- type="secondary"
- active={!showDisabledEvaluations}
- icon={showDisabledEvaluations ? <IconEye /> : <IconHide />}
- onClick={() => setShowDisabledEvaluations(!showDisabledEvaluations)}
- data-attr="toggle-show-disabled-evaluations"
- tooltip={showDisabledEvaluations ? 'Hide disabled evals' : 'Show disabled evals'}
- >
- {showDisabledEvaluations ? 'Hide disabled' : 'Show disabled'}
- </LemonButton>
- </div>
+ {!overviewEnabled && (
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonInput
+ type="search"
+ placeholder="Search online evals..."
+ value={evaluationsFilter}
+ data-attr="evaluations-search-input"
+ onChange={setEvaluationsFilter}
+ prefix={<IconSearch />}
+ className="max-w-sm"
+ />
+ <LemonButton
+ type="secondary"
+ active={!showDisabledEvaluations}
+ icon={showDisabledEvaluations ? <IconEye /> : <IconHide />}
+ onClick={() => setShowDisabledEvaluations(!showDisabledEvaluations)}
+ data-attr="toggle-show-disabled-evaluations"
+ tooltip={showDisabledEvaluations ? 'Hide disabled evals' : 'Show disabled evals'}
+ >
+ {showDisabledEvaluations ? 'Hide disabled' : 'Show disabled'}
+ </LemonButton>
+ </div>
+ )}
- {!evaluationsFilter && !selectedDirectoryId && (
+ {!overviewEnabled && !evaluationsFilter && !selectedDirectoryId && (
<LemonTable
columns={directoryColumns}
dataSource={evaluationDirectories}
@@ -675,16 +713,15 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
/>
)}
- <LemonTable
- columns={columns}
- dataSource={filteredEvaluationsWithMetrics}
- loading={evaluationsLoading || evaluationDirectoriesLoading}
- rowKey="id"
- pagination={{
- pageSize: 50,
- }}
- nouns={['evaluation', 'evaluations']}
- />
+ {overviewEnabled ? (
+ <EvaluationResultsTable />
+ ) : (
+ <EvaluationsWithMetricsTable
+ columns={columns}
+ displayedEvaluations={displayedEvaluations}
+ loading={evaluationsLoading || evaluationDirectoriesLoading}
+ />
+ )}
</>
)}
@@ -723,17 +760,28 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
)
}
+/**
+ * Binding mounts the metrics for the scene's lifetime. Attaching them to llmEvaluationsLogic instead would hold both
+ * mounted, so the list would never reload on the next visit. The overview never shows them, so it skips their queries.
+ */
+function LegacyMetricsBinding({ bound, children }: { bound: boolean; children: React.ReactNode }): JSX.Element {
+ return bound ? (
+ <BindLogic logic={evaluationMetricsLogic} props={{}}>
+ {children}
+ </BindLogic>
+ ) : (
+ <>{children}</>
+ )
+}
+
export function AIObservabilityEvaluationsScene(): JSX.Element {
useMountedLogic(llmEvaluationsLogic())
- // Mount for this component's lifetime rather than attaching to llmEvaluationsLogic:
- // evaluationMetricsLogic connects to it, so attaching leaves the two holding each
- // other mounted, and the list never reloads on the next visit to this scene.
- useMountedLogic(evaluationMetricsLogic())
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
+ const overviewEnabled = useFeatureFlag('AI_OBSERVABILITY_EVALUATIONS_OVERVIEW')
return (
<BindLogic logic={llmEvaluationsLogic} props={{}}>
- <BindLogic logic={evaluationMetricsLogic} props={{}}>
+ <LegacyMetricsBinding bound={!overviewEnabled}>
<SceneContent>
<SceneTitleSection
name="Evaluations"
@@ -770,7 +818,7 @@ export function AIObservabilityEvaluationsScene(): JSX.Element {
<AIObservabilityEvaluationsContent />
</EvaluationsTabs>
</SceneContent>
- </BindLogic>
+ </LegacyMetricsBinding>
</BindLogic>
)
}
diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
index 702865128b8a..1f80407c754a 100644
--- a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
@@ -120,6 +120,78 @@ function buildEvaluationBreakdownExpression(evaluations: EvaluationConfig[]): st
return `multiIf(${conditionsAndLabels.join(', ')}, toString(properties.$ai_evaluation_id))`
}
+/** Pass rate over time with one line per evaluation, or null when none of them has a pass rate. */
+export function buildEvaluationPassRateTrendsQuery(
+ evaluations: EvaluationConfig[],
+ dateFilter: { dateFrom: string | null; dateTo: string | null },
+ intervalOverride?: 'hour' | 'day'
+): TrendsQuery | null {
+ const enabledEvaluations = evaluations
+ .filter((evaluation) => evaluation.enabled && !evaluation.deleted && hasPassRate(evaluation))
+ .slice(0, MAX_EVALUATION_CHART_SERIES)
+
+ if (enabledEvaluations.length === 0) {
+ return null
+ }
+
+ const dateFrom = dateFilter.dateFrom || '-7d'
+ const dateTo = dateFilter.dateTo || null
+ const interval = intervalOverride ?? getIntervalFromDateRange(dateFrom)
+ const numericEvaluations = enabledEvaluations.filter((evaluation) => evaluation.output_type === 'numeric')
+ let passedExpression = evaluationPassedHogQLForMany(
+ enabledEvaluations.filter(evaluationIsDetector).map((evaluation) => evaluation.id)
+ )
+ let gradedExpression = EVALUATION_BOOLEAN_GRADED_HOGQL
+ if (numericEvaluations.length > 0) {
+ const numericCases = numericEvaluations.flatMap((evaluation) => [
+ `properties.$ai_evaluation_id = ${escapeHogQLString(evaluation.id)}`,
+ numericEvaluationPassedHogQL(evaluation),
+ ])
+ const numericIds = numericEvaluations.map((evaluation) => escapeHogQLString(evaluation.id)).join(', ')
+ passedExpression = `multiIf(${numericCases.join(', ')}, ${passedExpression})`
+ gradedExpression = `if(properties.$ai_evaluation_id IN (${numericIds}), ${EVALUATION_NUMERIC_GRADED_HOGQL}, ${EVALUATION_BOOLEAN_GRADED_HOGQL})`
+ }
+
+ if (enabledEvaluations.some((evaluation) => evaluation.output_type === 'categorical')) {
+ passedExpression = `if(properties.$ai_evaluation_result_type = 'categorical', ${categoricalEvaluationsPassedHogQL(enabledEvaluations)}, ${passedExpression})`
+ gradedExpression = `if(properties.$ai_evaluation_result_type = 'categorical', ${EVALUATION_CATEGORICAL_GRADED_HOGQL}, ${gradedExpression})`
+ }
+
+ return {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: '$ai_evaluation',
+ math: HogQLMathType.HogQL,
+ math_hogql: evaluationPassRateHogQL(passedExpression, gradedExpression),
+ properties: [
+ {
+ key: '$ai_evaluation_id',
+ value: enabledEvaluations.map((evaluation) => evaluation.id),
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ ],
+ },
+ ],
+ breakdownFilter: {
+ breakdown: buildEvaluationBreakdownExpression(enabledEvaluations),
+ breakdown_type: 'hogql',
+ breakdown_limit: MAX_EVALUATION_CHART_SERIES,
+ breakdown_hide_other_aggregation: true,
+ },
+ trendsFilter: {
+ display: ChartDisplayType.ActionsLineGraph,
+ },
+ dateRange: {
+ date_from: dateFrom,
+ date_to: dateTo,
+ },
+ interval,
+ }
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface evaluationMetricsLogicValues {
dateFilter: {
@@ -407,76 +479,7 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
(
evaluationsForMetrics: EvaluationConfig[],
dateFilter: { dateFrom: string | null; dateTo: string | null }
- ): TrendsQuery | null => {
- const enabledEvaluations = evaluationsForMetrics
- .filter((evaluation) => evaluation.enabled && !evaluation.deleted && hasPassRate(evaluation))
- .slice(0, MAX_EVALUATION_CHART_SERIES)
-
- if (enabledEvaluations.length === 0) {
- return null
- }
-
- const dateFrom = dateFilter.dateFrom || '-7d'
- const dateTo = dateFilter.dateTo || null
- const interval = getIntervalFromDateRange(dateFrom)
- const numericEvaluations = enabledEvaluations.filter(
- (evaluation) => evaluation.output_type === 'numeric'
- )
- let passedExpression = evaluationPassedHogQLForMany(
- enabledEvaluations.filter(evaluationIsDetector).map((evaluation) => evaluation.id)
- )
- let gradedExpression = EVALUATION_BOOLEAN_GRADED_HOGQL
- if (numericEvaluations.length > 0) {
- const numericCases = numericEvaluations.flatMap((evaluation) => [
- `properties.$ai_evaluation_id = ${escapeHogQLString(evaluation.id)}`,
- numericEvaluationPassedHogQL(evaluation),
- ])
- const numericIds = numericEvaluations
- .map((evaluation) => escapeHogQLString(evaluation.id))
- .join(', ')
- passedExpression = `multiIf(${numericCases.join(', ')}, ${passedExpression})`
- gradedExpression = `if(properties.$ai_evaluation_id IN (${numericIds}), ${EVALUATION_NUMERIC_GRADED_HOGQL}, ${EVALUATION_BOOLEAN_GRADED_HOGQL})`
- }
-
- if (enabledEvaluations.some((evaluation) => evaluation.output_type === 'categorical')) {
- passedExpression = `if(properties.$ai_evaluation_result_type = 'categorical', ${categoricalEvaluationsPassedHogQL(enabledEvaluations)}, ${passedExpression})`
- gradedExpression = `if(properties.$ai_evaluation_result_type = 'categorical', ${EVALUATION_CATEGORICAL_GRADED_HOGQL}, ${gradedExpression})`
- }
-
- return {
- kind: NodeKind.TrendsQuery,
- series: [
- {
- kind: NodeKind.EventsNode,
- event: '$ai_evaluation',
- math: HogQLMathType.HogQL,
- math_hogql: evaluationPassRateHogQL(passedExpression, gradedExpression),
- properties: [
- {
- key: '$ai_evaluation_id',
- value: enabledEvaluations.map((evaluation) => evaluation.id),
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- },
- ],
- },
- ],
- breakdownFilter: {
- breakdown: buildEvaluationBreakdownExpression(enabledEvaluations),
- breakdown_type: 'hogql',
- breakdown_limit: MAX_EVALUATION_CHART_SERIES,
- breakdown_hide_other_aggregation: true,
- },
- trendsFilter: {
- display: ChartDisplayType.ActionsLineGraph,
- },
- dateRange: {
- date_from: dateFrom,
- date_to: dateTo,
- },
- interval,
- }
- },
+ ): TrendsQuery | null => buildEvaluationPassRateTrendsQuery(evaluationsForMetrics, dateFilter),
],
}),
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index ae6c0fa469b1..a85df921f56c 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -59,6 +59,7 @@ import { EvaluationBackTarget, getEvaluationBackTarget } from './evaluationNavig
import { evaluationReportLogic, persistReportDraft } from './evaluationReportLogic'
import { getHogEvalExample } from './hogEvalExamples'
import { llmEvaluationsLogic } from './llmEvaluationsLogic'
+import { markEvaluationsOverviewStale } from './overview/evaluationsOverviewLogic'
import { EvaluationTemplateKey, defaultEvaluationTemplates } from './templates'
import type {
EvaluationConditionSet,
@@ -1426,6 +1427,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
// The list and the self-driving table read from llmEvaluationsLogic, which only
// fetches on mount. Refresh it here so they show the eval we just saved.
llmEvaluationsLogic.findMounted()?.actions.loadEvaluations()
+ markEvaluationsOverviewStale()
if (isNew) {
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.SetUpLlmEvaluation)
// Saving navigates away, so the offer to cover past data travels with the user.
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
index d4fd0465c09f..effcca602db9 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
@@ -1,6 +1,8 @@
import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -377,6 +379,22 @@ describe('llmEvaluationsLogic', () => {
})
})
+ describe('default date range', () => {
+ it.each([
+ { flagOn: true, dateFrom: undefined, expected: '-7d' },
+ { flagOn: false, dateFrom: undefined, expected: '-24h' },
+ { flagOn: true, dateFrom: '-30d', expected: '-30d' },
+ ])('flag on $flagOn with date_from $dateFrom starts at $expected', async ({ flagOn, dateFrom, expected }) => {
+ const flag = FEATURE_FLAGS.AI_OBSERVABILITY_EVALUATIONS_OVERVIEW
+ featureFlagLogic.actions.setFeatureFlags(flagOn ? [flag] : [], { [flag]: flagOn })
+
+ router.actions.push(combineUrl(urls.aiObservabilityEvaluations(), { date_from: dateFrom }).url)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.dateFilter.dateFrom).toEqual(expected)
+ })
+ })
+
describe('detectorEvaluationIds', () => {
it('lists only evaluations whose true result is a failure', async () => {
await expectLogic(logic, () => {
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
index 0e2fdc68132b..61d3c269e605 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
@@ -14,7 +14,9 @@ import {
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
+import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -35,6 +37,8 @@ import { listAllEvaluations, patchEvaluation } from './evaluationsApi'
import { EvaluationConfig } from './types'
const INITIAL_DATE_FROM = '-24h' as string | null
+// The overview compares each day with the previous period, which a 24 hour range is too short to show.
+const OVERVIEW_INITIAL_DATE_FROM = '-7d'
const INITIAL_DATE_TO = null as string | null
export type LLMEvaluationsLogicProps = Record<string, never>
@@ -47,6 +51,7 @@ export interface EvaluationDirectoryEditor {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface llmEvaluationsLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
activeProviderKey: LLMProviderKey | null | undefined // llmProviderKeysLogic
providerKeys: LLMProviderKey[] // llmProviderKeysLogic
searchParams: Record<string, any> // router
@@ -55,6 +60,7 @@ export interface llmEvaluationsLogicValues {
dateFrom: string | null
dateTo: string | null
}
+ defaultDateFrom: string | null
deletingDirectoryId: string | null
detectorEvaluationIds: string[]
directoryEditor: EvaluationDirectoryEditor | null
@@ -206,6 +212,7 @@ export interface llmEvaluationsLogicMeta {
evaluationsFilter: string,
showDisabledEvaluations: boolean
) => EvaluationConfig[]
+ defaultDateFrom: (featureFlags: FeatureFlagsSet) => string | null
selectedDirectoryId: (searchParams: Record<string, any>) => string | null
selectedDirectory: (
evaluationDirectories: EvaluationDirectoryApi[],
@@ -237,7 +244,14 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
path(['products', 'ai_observability', 'evaluations', 'llmEvaluationsLogic']),
props({} as LLMEvaluationsLogicProps),
connect(() => ({
- values: [llmProviderKeysLogic, ['providerKeys', 'activeProviderKey'], router, ['searchParams']],
+ values: [
+ llmProviderKeysLogic,
+ ['providerKeys', 'activeProviderKey'],
+ router,
+ ['searchParams'],
+ featureFlagLogic,
+ ['featureFlags'],
+ ],
actions: [llmProviderKeysLogic, ['loadProviderKeys']],
})),
@@ -585,6 +599,13 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
)
},
],
+ defaultDateFrom: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): string | null =>
+ featureFlags[FEATURE_FLAGS.AI_OBSERVABILITY_EVALUATIONS_OVERVIEW]
+ ? OVERVIEW_INITIAL_DATE_FROM
+ : INITIAL_DATE_FROM,
+ ],
selectedDirectoryId: [
(s) => [s.searchParams],
(searchParams: Record<string, unknown>): string | null =>
@@ -652,7 +673,7 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
return
}
- const dateFrom = (searchParams.date_from as string | null) || INITIAL_DATE_FROM
+ const dateFrom = (searchParams.date_from as string | null) || values.defaultDateFrom
const dateTo = (searchParams.date_to as string | null) || INITIAL_DATE_TO
if (dateFrom !== values.dateFilter.dateFrom || dateTo !== values.dateFilter.dateTo) {
@@ -661,12 +682,12 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
},
})),
- trackedActionToUrl(() => ({
+ trackedActionToUrl(({ values }) => ({
setDates: ({ dateFrom, dateTo }) => [
urls.aiObservabilityEvaluations(),
{
...router.values.searchParams,
- date_from: dateFrom === INITIAL_DATE_FROM ? undefined : dateFrom || undefined,
+ date_from: dateFrom === values.defaultDateFrom ? undefined : dateFrom || undefined,
date_to: dateTo || undefined,
},
],
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationCategoryShares.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationCategoryShares.tsx
new file mode 100644
index 000000000000..6b351e0c2e5b
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationCategoryShares.tsx
@@ -0,0 +1,62 @@
+import { useMemo } from 'react'
+
+import { BarList } from '@posthog/quill-charts'
+import type { Series } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import type { CategoriesSummaryApi, SentimentSummaryApi } from '../../generated/api.schemas'
+
+export function EvaluationCategoryShares({
+ summary,
+ gradedCount,
+}: {
+ summary: CategoriesSummaryApi | SentimentSummaryApi
+ gradedCount: number
+}): JSX.Element {
+ const theme = useChartTheme()
+
+ const series = useMemo<Series[]>(() => {
+ if (summary.kind === 'sentiment') {
+ return [
+ { key: 'negative', label: 'Negative', data: [summary.negative], color: getColorVar('danger') },
+ { key: 'neutral', label: 'Neutral', data: [summary.neutral], color: getColorVar('muted') },
+ { key: 'positive', label: 'Positive', data: [summary.positive], color: getColorVar('success') },
+ ]
+ }
+ const rows: Series[] = summary.categories.map((category) => ({
+ key: category.key,
+ label: category.label,
+ data: [category.count],
+ }))
+ if (summary.multiple) {
+ rows.push({
+ key: '__none',
+ label: 'No categories',
+ data: [summary.noCategoriesCount],
+ color: getColorVar('muted'),
+ })
+ }
+ return rows
+ }, [summary])
+
+ return (
+ <div className="flex flex-col gap-2">
+ <BarList
+ series={series}
+ theme={theme}
+ total={gradedCount}
+ valueFormatter={(value) =>
+ `${humanFriendlyNumber(value)} · ${gradedCount > 0 ? Math.round((value / gradedCount) * 100) : 0}%`
+ }
+ />
+ {summary.kind === 'categories' && summary.multiple && (
+ <div className="text-xs text-secondary">
+ One result can carry several labels, so shares can add up to more than 100%.
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationChartEmptyState.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationChartEmptyState.tsx
new file mode 100644
index 000000000000..283dd29ff8bb
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationChartEmptyState.tsx
@@ -0,0 +1,84 @@
+import { useValues } from 'kea'
+
+import { IconPlay, IconPlus } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { AccessControlAction } from 'lib/components/AccessControlAction'
+import { urls } from 'scenes/urls'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+// Placeholder lines in chart coordinates. They hint at what the chart will show, without real data.
+const GHOST_LINES = [
+ 'M0 40 C 80 34, 160 46, 240 38 S 400 30, 480 42 S 640 36, 800 40',
+ 'M0 90 C 80 96, 160 84, 240 92 S 400 104, 480 96 S 640 88, 800 100',
+ 'M0 140 C 80 132, 160 148, 240 150 S 400 138, 480 152 S 640 160, 800 156',
+]
+
+export function EvaluationChartEmptyState({ pausedRows }: { pausedRows: EvaluationResultApi[] }): JSX.Element {
+ const { evaluationUrl } = useValues(evaluationsOverviewLogic)
+ // A single paused evaluation is the obvious one to resume. With several, the list below lets people choose.
+ const onlyPaused = pausedRows.length === 1 ? pausedRows[0] : null
+ return (
+ <div className="relative h-96 rounded border-2 border-dotted border-secondary overflow-hidden">
+ <svg
+ viewBox="0 0 800 200"
+ preserveAspectRatio="none"
+ className="absolute inset-0 w-full h-full text-[var(--color-border-primary)]"
+ aria-hidden
+ >
+ {GHOST_LINES.map((path) => (
+ <path
+ key={path}
+ d={path}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={3}
+ vectorEffect="non-scaling-stroke"
+ />
+ ))}
+ </svg>
+ <div className="relative h-full flex items-center justify-center px-4">
+ {/* A solid card keeps the placeholder lines from running through the text. */}
+ <div className="flex flex-col items-center gap-3 text-center rounded-lg border bg-surface-primary px-6 py-6">
+ <div className="font-semibold text-base">No results in this range</div>
+ <div className="text-secondary max-w-md">
+ {onlyPaused
+ ? 'Turn your evaluation back on, or create a new one, to see results here.'
+ : pausedRows.length > 1
+ ? 'Turn an evaluation in the list below back on, or create a new one, to see results here.'
+ : 'Create an evaluation to see results here.'}
+ </div>
+ <div className="flex flex-wrap justify-center gap-2">
+ {onlyPaused && (
+ <LemonButton
+ type="primary"
+ icon={<IconPlay />}
+ to={evaluationUrl(onlyPaused.id)}
+ data-attr="evaluation-overview-empty-resume"
+ >
+ Turn it back on
+ </LemonButton>
+ )}
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Evaluation}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ type={onlyPaused ? 'secondary' : 'primary'}
+ icon={<IconPlus />}
+ to={urls.aiObservabilityEvaluationTemplates()}
+ data-attr="evaluation-overview-empty-create"
+ >
+ Create an evaluation
+ </LemonButton>
+ </AccessControlAction>
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationCompareItem.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationCompareItem.tsx
new file mode 100644
index 000000000000..384b40f2adae
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationCompareItem.tsx
@@ -0,0 +1,84 @@
+import { useValues } from 'kea'
+
+import { IconArrowRight } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { compactHeadline, describeAttention, isChartable, lastResultDay } from './evaluationOverviewDisplay'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+const ATTENTION_CLASSES: Record<string, string> = {
+ errored: 'text-danger',
+ worse: 'text-warning-dark',
+ silent: 'text-secondary',
+}
+
+function caption(row: EvaluationResultApi, timezone: string): string {
+ const attention = describeAttention(row, timezone)
+ if (attention) {
+ return attention
+ }
+ if (row.gradedCount > 0) {
+ return compactHeadline(row)
+ }
+ if (row.enabled) {
+ return 'No results in this range'
+ }
+ const day = lastResultDay(row, timezone)
+ return day ? `Paused, last result ${day}` : 'Paused'
+}
+
+export function EvaluationCompareItem({
+ row,
+ color,
+ onToggle,
+}: {
+ row: EvaluationResultApi
+ color: string | undefined
+ onToggle: () => void
+}): JSX.Element {
+ const { timezone, evaluationUrl: urlOf } = useValues(evaluationsOverviewLogic)
+ // Without a line to draw, the row opens the evaluation instead.
+ const chartable = isChartable(row)
+ const [reason] = row.attentionReasons
+ const evaluationUrl = urlOf(row.id)
+ return (
+ <li className="flex items-center gap-1">
+ <LemonButton
+ size="small"
+ className="flex-1 min-w-0"
+ active={!!color}
+ onClick={chartable ? onToggle : undefined}
+ to={chartable ? undefined : evaluationUrl}
+ tooltip={chartable ? (color ? 'Hide from the chart' : 'Show on the chart') : 'Open the evaluation'}
+ data-attr={reason ? `evaluation-overview-compare-${reason}` : 'evaluation-overview-compare'}
+ >
+ <span className="flex items-start gap-2 min-w-0 font-normal">
+ <span
+ className={cn(
+ 'mt-1.5 inline-block size-2.5 shrink-0 rounded-full',
+ !color && (chartable ? 'border-2 border-muted' : 'border-2 border-dashed border-muted')
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={color ? { backgroundColor: color } : undefined}
+ />
+ <span className="flex flex-col min-w-0">
+ <span className="font-semibold truncate">{row.name}</span>
+ <span className={cn('text-xs', (reason && ATTENTION_CLASSES[reason]) || 'text-secondary')}>
+ {caption(row, timezone)}
+ </span>
+ </span>
+ </span>
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ icon={<IconArrowRight />}
+ tooltip="Open the evaluation"
+ to={evaluationUrl}
+ data-attr="evaluation-overview-compare-open"
+ />
+ </li>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationCompareList.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationCompareList.tsx
new file mode 100644
index 000000000000..7685eeb7c535
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationCompareList.tsx
@@ -0,0 +1,34 @@
+import { useActions, useValues } from 'kea'
+
+import { EvaluationCompareItem } from './EvaluationCompareItem'
+import { EvaluationCreateSlot } from './EvaluationCreateSlot'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+/**
+ * Every evaluation with results, as the chart's legend and picker in one. The ones that need attention come
+ * first with a colored caption saying why, so no heading is needed to set them apart.
+ */
+export function EvaluationCompareList({ colors }: { colors: Map<string, string> }): JSX.Element {
+ const { compareListRows, few } = useValues(evaluationsOverviewLogic)
+ const { toggleCompared } = useActions(evaluationsOverviewLogic)
+
+ return (
+ <ul className="flex flex-col gap-0.5 max-h-96 overflow-y-auto pr-1">
+ {compareListRows.map((row) => (
+ <EvaluationCompareItem
+ key={row.id}
+ row={row}
+ color={colors.get(row.id)}
+ onToggle={() => toggleCompared(row.id)}
+ />
+ ))}
+ {few && (
+ // Leaves the arrow column empty, so the slot lines up with the rows above it.
+ <li className="flex items-center gap-1 mt-1">
+ <EvaluationCreateSlot className="flex-1" />
+ <span aria-hidden className="w-6 shrink-0" />
+ </li>
+ )}
+ </ul>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationCreateSlot.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationCreateSlot.tsx
new file mode 100644
index 000000000000..053f185c7e1a
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationCreateSlot.tsx
@@ -0,0 +1,23 @@
+import { IconPlus } from '@posthog/icons'
+import { Link } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+import { urls } from 'scenes/urls'
+
+/** A dotted slot to add an evaluation, for teams that only run a few. */
+export function EvaluationCreateSlot({ className }: { className?: string }): JSX.Element {
+ return (
+ <Link
+ to={urls.aiObservabilityEvaluationTemplates()}
+ subtle
+ className={cn(
+ 'flex items-center justify-center gap-1.5 rounded px-3 py-2 text-sm font-medium text-secondary hover:text-primary border-2 border-dotted border-secondary hover:border-accent',
+ className
+ )}
+ data-attr="evaluation-overview-create-slot"
+ >
+ <IconPlus />
+ <span>Create evaluation</span>
+ </Link>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationDirectoryTile.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationDirectoryTile.tsx
new file mode 100644
index 000000000000..7827b6aece55
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationDirectoryTile.tsx
@@ -0,0 +1,91 @@
+import { useActions, useValues } from 'kea'
+
+import { IconEllipsis, IconFolder } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonMenu } from '@posthog/lemon-ui'
+
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { cn } from 'lib/utils/css-classes'
+import { pluralize } from 'lib/utils/strings'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import { llmEvaluationsLogic } from '../llmEvaluationsLogic'
+import { type DirectoryTile, evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+export function EvaluationDirectoryTile({ tile, selected }: { tile: DirectoryTile; selected: boolean }): JSX.Element {
+ const { deletingDirectoryId } = useValues(llmEvaluationsLogic)
+ const { openRenameDirectory, deleteDirectory, selectDirectory } = useActions(llmEvaluationsLogic)
+ const { openDirectory } = useActions(evaluationsOverviewLogic)
+ const { directory, evaluationCount, needAttentionCount } = tile
+ const editorReason = getAccessControlDisabledReason(AccessControlResourceType.Evaluation, AccessControlLevel.Editor)
+ const deleting = deletingDirectoryId === directory.id
+
+ return (
+ <div
+ className={cn(
+ 'relative flex items-center rounded-lg border transition-colors motion-reduce:transition-none',
+ selected
+ ? 'border-accent bg-accent-highlight-secondary'
+ : 'border-primary bg-surface-primary hover:border-accent'
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => (selected ? selectDirectory(null) : openDirectory(directory.id))}
+ aria-pressed={selected}
+ className="flex flex-1 min-w-0 items-center gap-3 px-3 py-2 pr-9 text-left cursor-pointer rounded-lg"
+ data-attr="evaluation-overview-directory-tile"
+ >
+ <span className="flex size-8 shrink-0 items-center justify-center rounded text-lg bg-accent-highlight-secondary text-accent">
+ <IconFolder />
+ </span>
+ <span className="flex flex-col min-w-0">
+ <span className="font-semibold truncate">{directory.name}</span>
+ <span className="text-xs text-secondary truncate">
+ <span>{pluralize(evaluationCount, 'evaluation')}</span>
+ {needAttentionCount ? (
+ <span className="text-danger">{` · ${needAttentionCount} need attention`}</span>
+ ) : null}
+ </span>
+ </span>
+ </button>
+ <div className="absolute right-1 top-1/2 -translate-y-1/2">
+ <LemonMenu
+ items={[
+ {
+ label: 'Rename',
+ onClick: () => openRenameDirectory(directory),
+ disabledReason: editorReason,
+ 'data-attr': 'evaluation-overview-directory-rename',
+ },
+ {
+ label: 'Delete',
+ status: 'danger',
+ disabledReason: editorReason ?? (deleting ? 'Deleting the directory' : undefined),
+ 'data-attr': 'evaluation-overview-directory-delete',
+ onClick: () =>
+ LemonDialog.open({
+ title: `Delete ${directory.name}?`,
+ description: `${pluralize(evaluationCount, 'evaluation')} will move to the top level.`,
+ primaryButton: {
+ children: 'Delete directory',
+ status: 'danger',
+ onClick: () => deleteDirectory(directory.id),
+ },
+ secondaryButton: { children: 'Cancel' },
+ }),
+ },
+ ]}
+ >
+ <LemonButton
+ size="xsmall"
+ icon={<IconEllipsis />}
+ loading={deleting}
+ tooltip="Directory actions"
+ data-attr="evaluation-overview-directory-more"
+ />
+ </LemonMenu>
+ </div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationDirectoryTiles.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationDirectoryTiles.tsx
new file mode 100644
index 000000000000..2bf9d1328194
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationDirectoryTiles.tsx
@@ -0,0 +1,51 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPlus } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import { llmEvaluationsLogic } from '../llmEvaluationsLogic'
+import { EvaluationDirectoryTile } from './EvaluationDirectoryTile'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+/** Directories as compact tiles, like a file browser, so a long list of them still fits in a couple of rows. */
+export function EvaluationDirectoryTiles(): JSX.Element | null {
+ const { directoryTiles, selectedDirectoryId } = useValues(evaluationsOverviewLogic)
+ const { openCreateDirectory } = useActions(llmEvaluationsLogic)
+ const editorReason = getAccessControlDisabledReason(AccessControlResourceType.Evaluation, AccessControlLevel.Editor)
+
+ // Few teams use directories, so the tiles only appear once a team has made one.
+ if (directoryTiles.length === 0) {
+ return null
+ }
+ return (
+ <div className="@container">
+ <div className="grid gap-2 grid-cols-1 @min-[30rem]:grid-cols-2 @3xl:grid-cols-3 @5xl:grid-cols-4 @7xl:grid-cols-6">
+ {directoryTiles.map((tile) => (
+ <EvaluationDirectoryTile
+ key={tile.directory.id}
+ tile={tile}
+ selected={tile.directory.id === selectedDirectoryId}
+ />
+ ))}
+ <Tooltip title={editorReason}>
+ <button
+ type="button"
+ onClick={() => openCreateDirectory()}
+ disabled={!!editorReason}
+ className="flex items-center gap-3 rounded-lg border-2 border-dotted border-secondary px-3 py-2 text-left text-secondary enabled:hover:text-primary enabled:hover:border-accent enabled:cursor-pointer disabled:opacity-60"
+ data-attr="create-evaluation-directory-button"
+ >
+ <span className="flex size-8 shrink-0 items-center justify-center rounded text-lg">
+ <IconPlus />
+ </span>
+ <span className="font-semibold">New directory</span>
+ </button>
+ </Tooltip>
+ </div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationDrawerEmptyState.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationDrawerEmptyState.tsx
new file mode 100644
index 000000000000..b99007b14d52
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationDrawerEmptyState.tsx
@@ -0,0 +1,154 @@
+import { useActions, useValues } from 'kea'
+
+import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass'
+import { IconCalendar, IconGear, IconClockRewind, IconPlay } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { urls } from 'scenes/urls'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { llmEvaluationsLogic } from '../llmEvaluationsLogic'
+import { statusReasonLabel, statusReasonRecoveryLabel } from '../statusDisplay'
+import type { EvaluationStatusReason } from '../types'
+import { evaluationResultDrawerLogic } from './evaluationResultDrawerLogic'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+const HedgehogSearching = pngHoggie(magnifyingGlassPng)
+
+/** The range the "Widen the range" action switches to, and the length below which it offers to. */
+const WIDER_RANGE = '-30d'
+const WIDER_RANGE_DAYS = 30
+
+/** What the drawer shows when an evaluation graded nothing in the range, with the next steps for its state. */
+export function EvaluationDrawerEmptyState({ row }: { row: EvaluationResultApi }): JSX.Element {
+ const { configById, togglingIds, interval, periodLength, evaluationUrl } = useValues(evaluationsOverviewLogic)
+ const { canEnableEvaluation } = useValues(llmEvaluationsLogic)
+ const { toggleEvaluationEnabled, setDates } = useActions(llmEvaluationsLogic)
+ const { trackEmptyStateAction } = useActions(evaluationResultDrawerLogic)
+ const config = configById.get(row.id)
+ const errored = row.attentionReasons.includes('errored')
+ const enabled = config?.enabled ?? row.enabled
+ const reason = row.statusReason as EvaluationStatusReason | null
+ const editorReason = getAccessControlDisabledReason(
+ AccessControlResourceType.Evaluation,
+ AccessControlLevel.Editor,
+ config?.user_access_level ?? undefined
+ )
+ const state = errored ? 'errored' : enabled ? 'enabled' : 'disabled'
+
+ const title = errored ? statusReasonLabel(reason) : 'Nothing graded in this range'
+ const explanation = errored
+ ? statusReasonRecoveryLabel(reason)
+ : enabled
+ ? 'No generations matched its triggers in this range.'
+ : "It's turned off, so new generations aren't scored."
+
+ const runOnPastData = (
+ <LemonButton
+ type="secondary"
+ icon={<IconClockRewind />}
+ to={evaluationUrl(row.id, { evaluation_tab: 'backfills' })}
+ onClick={() => trackEmptyStateAction('run_on_past_data', state)}
+ disabledReason={editorReason}
+ data-attr="evaluation-overview-drawer-empty-backfill"
+ >
+ Run on past data
+ </LemonButton>
+ )
+
+ return (
+ <div className="flex flex-col items-center justify-center gap-3 text-center py-12 px-4">
+ <HedgehogSearching className="w-28 h-28" />
+ <h3 className="mb-0 text-lg font-semibold">{title}</h3>
+ <p className="mb-0 text-secondary max-w-md">{explanation}</p>
+ <div className="flex flex-wrap justify-center gap-2 pt-1">
+ {errored ? (
+ <>
+ {reason?.startsWith('provider_key') ? (
+ <LemonButton
+ type="primary"
+ icon={<IconGear />}
+ to={urls.settings('project-ai-observability', 'ai-observability-byok')}
+ onClick={() => trackEmptyStateAction('fix_in_settings', state)}
+ data-attr="evaluation-overview-drawer-empty-settings"
+ >
+ Fix in settings
+ </LemonButton>
+ ) : (
+ <LemonButton
+ type="primary"
+ to={evaluationUrl(row.id, { evaluation_tab: 'configuration' })}
+ onClick={() => trackEmptyStateAction('fix_evaluation', state)}
+ disabledReason={editorReason}
+ data-attr="evaluation-overview-drawer-empty-fix"
+ >
+ Fix the evaluation
+ </LemonButton>
+ )}
+ <LemonButton
+ type="secondary"
+ to={evaluationUrl(row.id)}
+ onClick={() => trackEmptyStateAction('open_evaluation', state)}
+ data-attr="evaluation-overview-drawer-empty-open"
+ >
+ Open evaluation
+ </LemonButton>
+ </>
+ ) : !enabled ? (
+ <>
+ {config && (
+ <LemonButton
+ type="primary"
+ icon={<IconPlay />}
+ onClick={() => {
+ trackEmptyStateAction('turn_on', state)
+ toggleEvaluationEnabled(config.id)
+ }}
+ loading={togglingIds.includes(config.id)}
+ disabledReason={
+ editorReason ??
+ (canEnableEvaluation(config)
+ ? undefined
+ : 'Add a provider API key to enable this evaluation.')
+ }
+ data-attr="evaluation-overview-drawer-empty-turn-on"
+ >
+ Turn it back on
+ </LemonButton>
+ )}
+ {runOnPastData}
+ </>
+ ) : (
+ <>
+ <LemonButton
+ type="primary"
+ to={evaluationUrl(row.id, { evaluation_tab: 'configuration' })}
+ onClick={() => trackEmptyStateAction('check_triggers', state)}
+ data-attr="evaluation-overview-drawer-empty-triggers"
+ >
+ Check the triggers
+ </LemonButton>
+ {(interval === 'hour' || periodLength < WIDER_RANGE_DAYS) && (
+ <LemonButton
+ type="secondary"
+ icon={<IconCalendar />}
+ onClick={() => {
+ trackEmptyStateAction('widen_range', state)
+ setDates(WIDER_RANGE, null)
+ }}
+ data-attr="evaluation-overview-drawer-empty-widen"
+ >
+ Widen the range
+ </LemonButton>
+ )}
+ {runOnPastData}
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationFailingExamples.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationFailingExamples.tsx
new file mode 100644
index 000000000000..365455951907
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationFailingExamples.tsx
@@ -0,0 +1,39 @@
+import { Link } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { cn } from 'lib/utils/css-classes'
+import { urls } from 'scenes/urls'
+
+import type { EvaluationRunApi } from '../../generated/api.schemas'
+
+export function EvaluationFailingExamples({ failures }: { failures: EvaluationRunApi[] }): JSX.Element {
+ return (
+ <ul className="flex flex-col gap-3">
+ {failures.map((failure, index) => (
+ <li key={`${failure.timestamp}-${index}`} className="flex items-start justify-between gap-2 min-w-0">
+ <div className="flex flex-col gap-0.5 min-w-0">
+ <span className={cn('text-sm line-clamp-3', !failure.reasoning && 'text-secondary')}>
+ {failure.reasoning ?? 'No reasoning was recorded for this result.'}
+ </span>
+ {/* noStyles drops the dotted underline, which read as a second separator under each item. */}
+ <TZLabel time={failure.timestamp} noStyles className="text-xs text-secondary" />
+ </div>
+ {failure.traceId && (
+ <Link
+ // The result is recorded after the trace ends, and the trace view reads a timestamp as
+ // the trace's earliest event, so passing it would hide the trace.
+ to={urls.aiObservabilityTrace(
+ failure.traceId,
+ failure.targetEventId ? { event: failure.targetEventId } : undefined
+ )}
+ className="text-xs shrink-0"
+ data-attr="evaluation-overview-drawer-trace"
+ >
+ View trace
+ </Link>
+ )}
+ </li>
+ ))}
+ </ul>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationOverviewMetricChart.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationOverviewMetricChart.tsx
new file mode 100644
index 000000000000..5f500b0ba0d4
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationOverviewMetricChart.tsx
@@ -0,0 +1,46 @@
+import { useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { TimeSeriesLineChart } from '@posthog/quill-charts'
+import type { Series, TimeSeriesLineChartConfig } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+
+import { hourTick } from './evaluationOverviewDisplay'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+export function EvaluationOverviewMetricChart({
+ label,
+ labels,
+ values,
+ color,
+ percentage = false,
+}: {
+ label: string
+ labels: string[]
+ values: number[]
+ color?: string
+ percentage?: boolean
+}): JSX.Element {
+ const theme = useChartTheme()
+ const { timezone, interval } = useValues(evaluationsOverviewLogic)
+ const series = useMemo<Series[]>(
+ () => [{ key: 'metric', label, data: values, color, points: { radius: 3 } }],
+ [label, values, color]
+ )
+ const config = useMemo<TimeSeriesLineChartConfig>(
+ () => ({
+ xAxis: { timezone, interval, ...(interval === 'hour' ? { tickFormatter: hourTick } : {}) },
+ yAxis: percentage ? { format: 'percentage', showGrid: true } : { showGrid: true, decimalPlaces: 0 },
+ showCrosshair: true,
+ // Straight segments, because a curve invents values between buckets and overshoots on sparse ones.
+ curve: 'linear',
+ }),
+ [percentage, timezone, interval]
+ )
+ return (
+ <div className="h-64 min-w-0 flex flex-col">
+ <TimeSeriesLineChart series={series} labels={labels} theme={theme} config={config} />
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationOverviewResults.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationOverviewResults.tsx
new file mode 100644
index 000000000000..b920101774f7
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationOverviewResults.tsx
@@ -0,0 +1,143 @@
+import { useActions, useValues } from 'kea'
+
+import { IconGraph } from '@posthog/icons'
+import { LemonButton, LemonSegmentedButton, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { getColorVar } from 'lib/colors'
+
+import { type BucketInterval, toChartValues } from './evaluationOverviewDisplay'
+import { EvaluationOverviewMetricChart } from './EvaluationOverviewMetricChart'
+import { EvaluationPassRateOverview } from './EvaluationPassRateOverview'
+import { EvaluationRankedBars } from './EvaluationRankedBars'
+import { type OverviewMetric, type OverviewView, evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+import { EvaluationStatusGrid } from './EvaluationStatusGrid'
+
+function viewTitle(view: OverviewView, metric: OverviewMetric, interval: BucketInterval): string {
+ switch (view) {
+ case 'over_time':
+ return metric === 'pass_rate'
+ ? 'Results over time'
+ : metric === 'graded'
+ ? `Graded results each ${interval}`
+ : 'Negative sentiment over time'
+ case 'by_bucket':
+ return `Each evaluation, ${interval} by ${interval}`
+ case 'ranked':
+ return 'Each evaluation, ranked'
+ }
+}
+
+function viewSubtitle(view: OverviewView, interval: BucketInterval): string {
+ switch (view) {
+ case 'over_time':
+ return 'Pick evaluations in the list to compare them.'
+ case 'by_bucket':
+ return `Every evaluation, most unusual ${interval}s first. Hover a${interval === 'hour' ? 'n' : ''} ${interval} for details.`
+ case 'ranked':
+ return 'Lowest first, on a scale where higher is better. Click a row to open it.'
+ }
+}
+
+function viewOptions(interval: BucketInterval): { value: OverviewView; label: string; 'data-attr': string }[] {
+ return [
+ { value: 'over_time', label: 'Over time', 'data-attr': 'evaluation-overview-view-over-time' },
+ {
+ value: 'by_bucket',
+ label: interval === 'hour' ? 'Hour by hour' : 'Day by day',
+ 'data-attr': 'evaluation-overview-view-by-bucket',
+ },
+ { value: 'ranked', label: 'Ranked', 'data-attr': 'evaluation-overview-view-ranked' },
+ ]
+}
+
+function ResultsBody(): JSX.Element {
+ const { view, metric, overview, buckets, sentimentRow, ranked } = useValues(evaluationsOverviewLogic)
+
+ if (view === 'by_bucket') {
+ return <EvaluationStatusGrid />
+ }
+ if (view === 'ranked') {
+ return (
+ <div className="flex flex-col gap-6">
+ {ranked.results.length > 0 && (
+ <EvaluationRankedBars labelHeader="Evaluation" valueHeader="Result" items={ranked.results} />
+ )}
+ {ranked.labels.length > 0 && (
+ <EvaluationRankedBars
+ labelHeader="Labels"
+ valueHeader="Tracked label"
+ fullScale
+ items={ranked.labels}
+ />
+ )}
+ </div>
+ )
+ }
+ if (metric === 'graded') {
+ return (
+ <EvaluationOverviewMetricChart
+ label="Graded results"
+ labels={buckets}
+ values={overview?.totals.gradedTrend ?? []}
+ />
+ )
+ }
+ if (metric === 'sentiment' && sentimentRow) {
+ return (
+ <EvaluationOverviewMetricChart
+ label="Negative share"
+ labels={buckets}
+ values={toChartValues(sentimentRow.trend.values)}
+ color={getColorVar('danger')}
+ percentage
+ />
+ )
+ }
+ return <EvaluationPassRateOverview />
+}
+
+/** One results card with a view picker, so the page shows a single chart at a time. */
+export function EvaluationOverviewResults(): JSX.Element {
+ const { view, metric, overview, overviewLoading, request, nothingGraded, exploreUrl, interval } =
+ useValues(evaluationsOverviewLogic)
+ const { setView, clickExplore } = useActions(evaluationsOverviewLogic)
+ const loading = (overviewLoading || !request.ready) && !overview
+
+ return (
+ <div className="border rounded bg-surface-primary flex flex-col min-w-0">
+ <div className="flex flex-wrap items-center justify-between gap-2 px-4 py-3 border-b">
+ <div className="flex flex-col min-w-0">
+ <h3 className="mb-0 text-base font-semibold">{viewTitle(view, metric, interval)}</h3>
+ {!loading && !nothingGraded && (view !== 'over_time' || metric === 'pass_rate') && (
+ <span className="text-xs text-secondary">{viewSubtitle(view, interval)}</span>
+ )}
+ </div>
+ {!loading && !nothingGraded && (
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ {/* Explore only works on the pass rate chart. It sits left of the view picker, so the picker
+ keeps its place when Explore comes and goes. */}
+ {exploreUrl && view === 'over_time' && metric === 'pass_rate' && (
+ <LemonButton
+ size="small"
+ icon={<IconGraph />}
+ to={exploreUrl}
+ onClick={clickExplore}
+ tooltip="Open the pass rates as an insight, with one line per evaluation, to change filters or break them down"
+ data-attr="evaluation-overview-explore"
+ >
+ Explore
+ </LemonButton>
+ )}
+ <LemonSegmentedButton
+ size="small"
+ value={view}
+ onChange={setView}
+ options={viewOptions(interval)}
+ />
+ </div>
+ )}
+ </div>
+ <div className="p-4">{loading ? <LemonSkeleton className="h-96 w-full" /> : <ResultsBody />}</div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationOverviewTiles.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationOverviewTiles.tsx
new file mode 100644
index 000000000000..8c26f4f2884e
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationOverviewTiles.tsx
@@ -0,0 +1,172 @@
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
+import {
+ AnalyticsMetricCard,
+ type AnalyticsMetricCardProps,
+} from 'lib/components/AnalyticsMetricCard/AnalyticsMetricCard'
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
+
+import { formatBucket, formatPercent, formatPoints, toChartValues } from './evaluationOverviewDisplay'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+/**
+ * A metric card that keeps its shape when there is nothing to show: a dash, an empty sparkline area and the
+ * empty message as its caption, so the row of cards reads the same with or without data.
+ */
+function Tile({ buckets, ...props }: AnalyticsMetricCardProps & { buckets: string[] }): JSX.Element {
+ if (props.value != null && Number.isFinite(props.value)) {
+ const format = props.formatValue
+ // Hovering a bucket without results would otherwise print "NaN%".
+ return (
+ <AnalyticsMetricCard
+ {...props}
+ formatValue={(value) => (Number.isFinite(value) ? (format ? format(value) : String(value)) : '-')}
+ />
+ )
+ }
+ return (
+ <AnalyticsMetricCard
+ {...props}
+ value={NaN}
+ formatValue={() => '-'}
+ data={buckets.map(() => NaN)}
+ labels={buckets}
+ subtitle={undefined}
+ restingSubtitle={props.emptyMessage}
+ showChange={false}
+ change={null}
+ />
+ )
+}
+
+function percentChange(current: number, previous: number): number | null {
+ return previous > 0 ? ((current - previous) / previous) * 100 : null
+}
+
+export function EvaluationOverviewTiles(): JSX.Element {
+ const theme = useChartTheme()
+ const {
+ overview,
+ overviewLoading,
+ request,
+ buckets,
+ interval,
+ periodLength,
+ rows,
+ metric,
+ attentionCounts,
+ sentimentRow,
+ measuredPassRateRows: counted,
+ } = useValues(evaluationsOverviewLogic)
+ const { selectCard } = useActions(evaluationsOverviewLogic)
+ // Volume going up or down is not good or bad on its own, so its pill stays neutral.
+ const neutral = useMemo(() => ({ background: 'transparent', foreground: getColorVar('muted') }), [])
+
+ const loading = (overviewLoading || !request.ready) && !overview
+ const passRates = overview?.passRateOverview
+ const totals = overview?.totals
+ const medianChange = passRates?.medianComparison
+ ? passRates.medianComparison.current - passRates.medianComparison.previous
+ : null
+ const gradedChange = totals?.gradedComparison
+ ? percentChange(totals.gradedComparison.current, totals.gradedComparison.previous)
+ : null
+ const sentiment = totals?.sentiment
+ const hasSentimentEvaluation = rows.some((row) => row.summary.kind === 'sentiment')
+ const shared = {
+ theme,
+ formatLabel: (label: string) => formatBucket(label, interval),
+ sparklineHeight: 36,
+ buckets,
+ labels: buckets,
+ loading,
+ }
+
+ return (
+ <div className={cn('grid gap-3 grid-cols-2', hasSentimentEvaluation ? '@4xl:grid-cols-4' : '@3xl:grid-cols-3')}>
+ <Tile
+ {...shared}
+ title="Needs attention"
+ value={overview ? attentionCounts.any : undefined}
+ formatValue={(value) => String(Math.round(value))}
+ showChange={false}
+ restingSubtitle={`of ${pluralize(rows.length, 'evaluation')}`}
+ // Clicking scrolls to the list instead of selecting a chart, so the card is never shown as selected.
+ selected={false}
+ // The shared card grows its header to push a sparkline down. Without one, that would push the count
+ // to the bottom, out of line with the cards next to it.
+ className="[&>button>div>div:first-child]:flex-none"
+ onClick={() => selectCard('attention')}
+ ariaLabel="Show the evaluations list"
+ dataAttr="evaluation-overview-card-attention"
+ />
+ <Tile
+ {...shared}
+ title="Pass rate"
+ value={passRates?.median ?? undefined}
+ formatValue={formatPercent}
+ data={toChartValues(passRates?.medianTrend ?? [])}
+ change={medianChange !== null ? { value: medianChange } : null}
+ formatChange={formatPoints}
+ goodDirection="up"
+ changeTooltip="Change in the median against the previous period, for evaluations with results in both"
+ restingSubtitle={counted.length === 1 ? counted[0].name : `Median of ${counted.length} evaluations`}
+ // Entries without a median all have too few graded results to count.
+ emptyMessage={
+ passRates?.entries.length
+ ? 'Too few graded results yet'
+ : 'No evaluation with a pass rate has results yet'
+ }
+ selected={metric === 'pass_rate'}
+ onClick={() => selectCard('pass_rate')}
+ ariaLabel="Show pass rate over time"
+ dataAttr="evaluation-overview-card-pass-rate"
+ />
+ <Tile
+ {...shared}
+ title="Graded results"
+ value={totals && totals.graded > 0 ? totals.graded : undefined}
+ formatValue={humanFriendlyNumber}
+ emptyMessage="No graded results in this range"
+ data={totals?.gradedTrend ?? []}
+ change={gradedChange !== null ? { value: gradedChange } : null}
+ positiveColor={neutral}
+ negativeColor={neutral}
+ changeTooltip="Change against the previous period, for evaluations with results in both"
+ restingSubtitle={`In ${pluralize(periodLength, interval)}`}
+ selected={metric === 'graded'}
+ onClick={() => selectCard('graded')}
+ ariaLabel="Show graded results over time"
+ dataAttr="evaluation-overview-card-graded"
+ />
+ {hasSentimentEvaluation && (
+ <Tile
+ {...shared}
+ title="Negative sentiment"
+ value={sentiment?.negativeShare}
+ formatValue={(value) => `${Math.round(value)}%`}
+ data={toChartValues(sentimentRow?.trend.values ?? [])}
+ change={
+ sentiment && sentiment.previousShare !== null
+ ? { value: sentiment.negativeShare - sentiment.previousShare }
+ : null
+ }
+ formatChange={formatPoints}
+ goodDirection="down"
+ changeTooltip="Change in the share of negative user messages against the previous period"
+ restingSubtitle="of last user messages"
+ emptyMessage="No messages classified in this range"
+ selected={metric === 'sentiment'}
+ onClick={() => selectCard('sentiment')}
+ ariaLabel="Show negative sentiment over time"
+ dataAttr="evaluation-overview-card-sentiment"
+ />
+ )}
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationPassRateCompareChart.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationPassRateCompareChart.tsx
new file mode 100644
index 000000000000..3550b35783c1
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationPassRateCompareChart.tsx
@@ -0,0 +1,111 @@
+import { useValues } from 'kea'
+import { Fragment, useMemo } from 'react'
+
+import { TimeSeriesLineChart, TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'
+import type { Series, TimeSeriesLineChartConfig, TooltipContext } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import { bucketHeadline, formatBucket, hourTick, percentTrend, toChartValues } from './evaluationOverviewDisplay'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+const MEDIAN_KEY = '__median'
+
+export function EvaluationPassRateCompareChart({ colors }: { colors: Map<string, string> }): JSX.Element {
+ const theme = useChartTheme()
+ const {
+ overview,
+ measuredPassRateRows: measured,
+ compareListRows,
+ buckets,
+ timezone,
+ interval,
+ } = useValues(evaluationsOverviewLogic)
+
+ // Only the picked evaluations draw, so every line on the chart is one the list shows as picked.
+ const drawn = useMemo(
+ () => ({ measuredCount: measured.length, picked: compareListRows.filter((row) => colors.has(row.id)) }),
+ [measured, compareListRows, colors]
+ )
+
+ const medianTrend = useMemo(() => toChartValues(overview?.passRateOverview.medianTrend ?? []), [overview])
+
+ const series = useMemo<Series[]>(() => {
+ return [
+ ...drawn.picked.map((row) => ({
+ key: row.id,
+ label: row.name,
+ data: percentTrend(row),
+ color: colors.get(row.id),
+ points: { radius: 2.5 },
+ })),
+ // A median of one evaluation is that evaluation, so the extra line would only hide it.
+ ...(drawn.measuredCount > 1
+ ? [
+ {
+ key: MEDIAN_KEY,
+ label: 'Median pass rate',
+ data: medianTrend,
+ color: getColorVar('color-text-primary'),
+ stroke: { pattern: [6, 4] },
+ },
+ ]
+ : []),
+ ]
+ }, [drawn, colors, medianTrend])
+
+ const config = useMemo<TimeSeriesLineChartConfig>(() => {
+ // The median covers every measured evaluation, not only the picked ones, so it can sit below all of them.
+ const finite = series.flatMap((entry) => entry.data).filter(Number.isFinite)
+ const floor = finite.length > 0 ? Math.max(0, Math.floor((Math.min(...finite) - 5) / 10) * 10) : 0
+ return {
+ xAxis: { timezone, interval, ...(interval === 'hour' ? { tickFormatter: hourTick } : {}) },
+ yAxis: { format: 'percentage', showGrid: true },
+ // Straight segments, because a curve invents values between buckets and overshoots on sparse ones.
+ curve: 'linear',
+ valueDomain: { min: floor, max: 100 },
+ showCrosshair: true,
+ }
+ }, [series, timezone, interval])
+
+ const tooltip = (ctx: TooltipContext): JSX.Element => {
+ const median = medianTrend[ctx.dataIndex]
+ const picked = drawn.picked.filter((row) => row.trend.values[ctx.dataIndex] !== null)
+ return (
+ <TooltipSurface>
+ <div className="font-semibold mb-1">{formatBucket(String(ctx.label), interval)}</div>
+ <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-0.5">
+ {picked.map((row) => (
+ <Fragment key={row.id}>
+ <span className="flex items-center gap-2 min-w-0">
+ <TooltipSwatch color={colors.get(row.id) ?? ''} />
+ <span className="truncate max-w-72">{row.name}</span>
+ </span>
+ {/* The value stays short, so the name gets the rest of the tooltip's fixed width. */}
+ <span className="text-right whitespace-nowrap tabular-nums">
+ <strong>{bucketHeadline(row, ctx.dataIndex)}</strong>
+ <span className="text-secondary">{` · ${humanFriendlyNumber(row.trend.volume[ctx.dataIndex] ?? 0)}`}</span>
+ </span>
+ </Fragment>
+ ))}
+ {drawn.measuredCount > 1 && Number.isFinite(median) && (
+ <>
+ <span className="mt-1 pt-1 border-t border-current/25">Median pass rate</span>
+ <strong className="mt-1 pt-1 border-t border-current/25 text-right whitespace-nowrap tabular-nums">
+ {`${median.toFixed(1)}%`}
+ </strong>
+ </>
+ )}
+ </div>
+ </TooltipSurface>
+ )
+ }
+
+ return (
+ <div className="h-96 min-w-0 flex flex-col">
+ <TimeSeriesLineChart series={series} labels={buckets} theme={theme} config={config} tooltip={tooltip} />
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationPassRateOverview.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationPassRateOverview.tsx
new file mode 100644
index 000000000000..8ea6f2f1173f
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationPassRateOverview.tsx
@@ -0,0 +1,34 @@
+import { useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { useChartTheme } from 'lib/charts/hooks'
+
+import { EvaluationChartEmptyState } from './EvaluationChartEmptyState'
+import { EvaluationCompareList } from './EvaluationCompareList'
+import { EvaluationPassRateCompareChart } from './EvaluationPassRateCompareChart'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+export function EvaluationPassRateOverview(): JSX.Element {
+ const theme = useChartTheme()
+ const { chartedIds, nothingGraded, rows } = useValues(evaluationsOverviewLogic)
+ const colors = useMemo(() => {
+ const palette = theme.colors.slice(1)
+ return new Map(chartedIds.map((id, index) => [id, palette[index % palette.length]]))
+ }, [chartedIds, theme])
+
+ // With nothing graded the layout stays the same: the list shows why each one is empty, the chart what fills it.
+ return (
+ <div className="flex flex-col gap-4 min-w-0 @3xl:flex-row">
+ <div className="@3xl:w-72 shrink-0">
+ <EvaluationCompareList colors={colors} />
+ </div>
+ <div className="flex-1 min-w-0 flex flex-col gap-2">
+ {nothingGraded ? (
+ <EvaluationChartEmptyState pausedRows={rows.filter((row) => !row.enabled)} />
+ ) : (
+ <EvaluationPassRateCompareChart colors={colors} />
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationPausedNotice.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationPausedNotice.tsx
new file mode 100644
index 000000000000..dbc43168acb5
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationPausedNotice.tsx
@@ -0,0 +1,53 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPause, IconPlay } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { llmEvaluationsLogic } from '../llmEvaluationsLogic'
+import { lastResultDay } from './evaluationOverviewDisplay'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+/** Turning an evaluation off is a normal choice, so this offers the way back without pressing it. */
+export function EvaluationPausedNotice({ row }: { row: EvaluationResultApi }): JSX.Element {
+ const { configById, togglingIds, timezone } = useValues(evaluationsOverviewLogic)
+ const { canEnableEvaluation } = useValues(llmEvaluationsLogic)
+ const { toggleEvaluationEnabled } = useActions(llmEvaluationsLogic)
+ const config = configById.get(row.id)
+ const day = lastResultDay(row, timezone)
+
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-3 border rounded bg-surface-primary px-4 py-3">
+ <div className="flex items-center gap-2 text-secondary">
+ <IconPause className="shrink-0" />
+ <span>
+ {`Paused. New generations aren't scored while it's off.${day ? ` Last result ${day}.` : ''}`}
+ </span>
+ </div>
+ {config && (
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconPlay />}
+ onClick={() => toggleEvaluationEnabled(config.id)}
+ loading={togglingIds.includes(config.id)}
+ disabledReason={
+ getAccessControlDisabledReason(
+ AccessControlResourceType.Evaluation,
+ AccessControlLevel.Editor,
+ config.user_access_level ?? undefined
+ ) ??
+ (canEnableEvaluation(config) ? undefined : 'Add a provider API key to enable this evaluation.')
+ }
+ data-attr="evaluation-overview-drawer-resume"
+ >
+ Turn back on
+ </LemonButton>
+ )}
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationRankedBars.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationRankedBars.tsx
new file mode 100644
index 000000000000..00b33c824607
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationRankedBars.tsx
@@ -0,0 +1,100 @@
+import { useValues } from 'kea'
+
+import { Link, Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import type { ResultChangeApi } from '../../generated/api.schemas'
+import { compactHeadline, formatPercent, formatPoints, resultHeadline } from './evaluationOverviewDisplay'
+import { type RankedRow, evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+function formatChange(change: ResultChangeApi): string {
+ return change.unit === 'pp'
+ ? formatPoints(change.value)
+ : `${change.value > 0 ? '+' : ''}${change.value.toFixed(2)} points`
+}
+
+export function EvaluationRankedBars({
+ items,
+ labelHeader,
+ valueHeader = 'Pass rate',
+ fullScale = false,
+}: {
+ items: RankedRow[]
+ labelHeader: string
+ valueHeader?: string
+ /** Draw on 0-100% instead of zooming in, for results with no shared meaning to compare closely. */
+ fullScale?: boolean
+}): JSX.Element {
+ const { evaluationUrl } = useValues(evaluationsOverviewLogic)
+ // Worst first, with results too sparse to rely on kept at the bottom and out of the scale.
+ const sorted = [...items].sort((a, b) => Number(a.row.lowEvidence) - Number(b.row.lowEvidence) || a.rate - b.rate)
+ const lowest = Math.min(100, ...sorted.filter((item) => !item.row.lowEvidence).map((item) => item.rate))
+ // Start the scale just under the lowest value, so differences between high rates stay visible.
+ const start = fullScale ? 0 : Math.max(0, Math.floor((lowest - 5) / 10) * 10)
+ const position = (rate: number): string => `${Math.max(0, ((rate - start) / (100 - start)) * 100)}%`
+
+ return (
+ <div className="flex flex-col text-sm">
+ <div className="flex items-center gap-3 text-xs text-secondary pb-1 border-b">
+ <span className="w-28 @2xl:w-44 shrink-0">{labelHeader}</span>
+ <span className="flex-1 flex justify-between">
+ <span>{`${start}%`}</span>
+ <span>100%</span>
+ </span>
+ <span className="w-28 @2xl:w-60 shrink-0 text-right">{valueHeader}</span>
+ </div>
+ {sorted.map(({ row, rate }) => {
+ // The bar sits on the shared scale, and the label says the result in its own terms.
+ const valueLabel =
+ row.summary.kind === 'pass_rate'
+ ? formatPercent(rate)
+ : row.summary.kind === 'score'
+ ? resultHeadline(row)
+ : compactHeadline(row)
+ const change = row.change ? formatChange(row.change) : null
+ return (
+ <Tooltip
+ key={row.id}
+ title={
+ <>
+ <div className="font-semibold">{row.name}</div>
+ <div>{`${row.summary.kind === 'pass_rate' ? `${valueLabel} passed` : valueLabel}, ${humanFriendlyNumber(row.gradedCount)} graded`}</div>
+ {change !== null && <div>{`${change} against the previous period`}</div>}
+ {row.lowEvidence && <div>Too few results to rely on</div>}
+ </>
+ }
+ >
+ <Link
+ to={evaluationUrl(row.id)}
+ subtle
+ className="flex items-center gap-3 py-1 rounded text-primary hover:bg-surface-secondary"
+ data-attr="evaluation-overview-ranked-bar"
+ >
+ <span className="w-28 @2xl:w-44 shrink-0 truncate text-left">{row.name}</span>
+ <span className="relative flex-1 min-w-8 h-2.5 rounded-sm bg-surface-secondary">
+ <span
+ className={cn(
+ 'absolute inset-y-0 left-0 rounded-sm bg-muted',
+ row.lowEvidence && 'opacity-40'
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: position(rate) }}
+ />
+ </span>
+ <span className="w-28 @2xl:w-60 shrink-0 text-right tabular-nums whitespace-nowrap truncate">
+ <span className={cn('font-semibold', row.lowEvidence && 'text-secondary')}>
+ {valueLabel}
+ </span>
+ <span className="hidden @2xl:inline text-xs text-secondary ml-1">
+ {change ?? `${humanFriendlyNumber(row.gradedCount)} graded`}
+ </span>
+ </span>
+ </Link>
+ </Tooltip>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultActions.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultActions.tsx
new file mode 100644
index 000000000000..a69da85bf303
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultActions.tsx
@@ -0,0 +1,123 @@
+import { useActions, useValues } from 'kea'
+
+import { IconEllipsis, IconFolder, IconPause, IconPencil, IconPlay, IconTrash, IconWarning } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonMenu } from '@posthog/lemon-ui'
+
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import { llmEvaluationsLogic } from '../llmEvaluationsLogic'
+import type { EvaluationConfig } from '../types'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+export function EvaluationResultActions({ config }: { config: EvaluationConfig }): JSX.Element {
+ const { evaluationDirectories, movingEvaluationId, canEnableEvaluation } = useValues(llmEvaluationsLogic)
+ const { toggleEvaluationEnabled, moveEvaluation, deleteEvaluation } = useActions(llmEvaluationsLogic)
+ const { togglingIds, evaluationUrl } = useValues(evaluationsOverviewLogic)
+ const { trackTableAction } = useActions(evaluationsOverviewLogic)
+ const editorReason = getAccessControlDisabledReason(
+ AccessControlResourceType.Evaluation,
+ AccessControlLevel.Editor,
+ config.user_access_level ?? undefined
+ )
+ const moving = movingEvaluationId === config.id
+ const toggling = togglingIds.includes(config.id)
+ const errored = config.status === 'error'
+ const blocked = !config.enabled && !canEnableEvaluation(config)
+
+ return (
+ <div className="flex gap-1">
+ <LemonButton
+ size="small"
+ icon={<IconPencil />}
+ tooltip="Edit"
+ to={evaluationUrl(config.id)}
+ onClick={() => trackTableAction('edit')}
+ disabledReason={editorReason}
+ data-attr="evaluation-overview-table-edit"
+ />
+ <LemonMenu
+ items={[
+ {
+ items: [
+ errored
+ ? {
+ label: 'Open to fix',
+ icon: <IconWarning />,
+ to: evaluationUrl(config.id),
+ 'data-attr': 'evaluation-overview-table-fix',
+ }
+ : {
+ label: config.enabled ? 'Disable' : 'Enable',
+ icon: config.enabled ? <IconPause /> : <IconPlay />,
+ onClick: () => toggleEvaluationEnabled(config.id),
+ disabledReason:
+ editorReason ??
+ (toggling
+ ? 'Saving the change'
+ : blocked
+ ? 'Add a provider API key to enable this evaluation.'
+ : undefined),
+ 'data-attr': 'evaluation-overview-table-toggle',
+ },
+ {
+ label: 'Move to directory',
+ icon: <IconFolder />,
+ disabledReason: editorReason ?? (moving ? 'Moving the evaluation' : undefined),
+ items: [
+ {
+ label: 'Top level',
+ onClick: () => moveEvaluation(config.id, null),
+ disabledReason: config.directory_id ? undefined : 'Evaluation is already here',
+ },
+ ...evaluationDirectories.map((directory) => ({
+ label: directory.name,
+ onClick: () => moveEvaluation(config.id, directory.id),
+ disabledReason:
+ config.directory_id === directory.id
+ ? 'Evaluation is already here'
+ : undefined,
+ })),
+ ],
+ },
+ ],
+ },
+ // A separate section draws a divider, which keeps the destructive action apart.
+ {
+ items: [
+ {
+ label: 'Delete',
+ icon: <IconTrash />,
+ status: 'danger',
+ disabledReason: editorReason,
+ 'data-attr': 'evaluation-overview-table-delete',
+ onClick: () =>
+ LemonDialog.open({
+ title: `Delete ${config.name}?`,
+ description: 'Are you sure you want to delete this evaluation?',
+ primaryButton: {
+ children: 'Delete',
+ type: 'primary',
+ status: 'danger',
+ 'data-attr': 'confirm-delete-evaluation',
+ onClick: () => deleteEvaluation(config.id),
+ },
+ secondaryButton: { children: 'Cancel', type: 'secondary' },
+ }),
+ },
+ ],
+ },
+ ]}
+ >
+ <LemonButton
+ size="small"
+ icon={<IconEllipsis />}
+ loading={moving || toggling}
+ tooltip="More actions"
+ data-attr="evaluation-overview-table-more"
+ />
+ </LemonMenu>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultCell.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultCell.tsx
new file mode 100644
index 000000000000..a1f278bf1246
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultCell.tsx
@@ -0,0 +1,33 @@
+import { useValues } from 'kea'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { lastResultDay, resultEvidence, resultHeadline } from './evaluationOverviewDisplay'
+import { EvaluationResultChange } from './EvaluationResultChange'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+export function EvaluationResultCell({ row }: { row: EvaluationResultApi }): JSX.Element {
+ const { timezone } = useValues(evaluationsOverviewLogic)
+ if (row.gradedCount === 0) {
+ const day = lastResultDay(row, timezone)
+ return <div className="text-secondary">{day ? `No results since ${day}` : 'No results in this range'}</div>
+ }
+ const content = (
+ <div className={cn('min-w-0', row.lowEvidence && 'opacity-60')}>
+ <div className="text-sm @3xl:text-base font-semibold">{resultHeadline(row)}</div>
+ <div className="text-xs text-secondary">{resultEvidence(row)}</div>
+ {/* The trend column hides on a narrow table, so the change shows here instead. */}
+ <div className="text-xs mt-0.5 @min-[32.5rem]:hidden">
+ <EvaluationResultChange row={row} />
+ </div>
+ </div>
+ )
+ return row.lowEvidence ? (
+ <Tooltip title="Too few graded results to rely on, so this result can swing a lot.">{content}</Tooltip>
+ ) : (
+ content
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultChange.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultChange.tsx
new file mode 100644
index 000000000000..55455becc3f7
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultChange.tsx
@@ -0,0 +1,35 @@
+import { IconArrowRightDown, IconArrowUpRight } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+
+export function EvaluationResultChange({ row }: { row: EvaluationResultApi }): JSX.Element {
+ const { change } = row
+ if (!change) {
+ const reason =
+ row.gradedCount === 0
+ ? 'No graded results in this range.'
+ : row.lowEvidence
+ ? 'Too few graded results to compare.'
+ : row.previousGradedCount
+ ? 'Too few graded results in the previous period to compare.'
+ : 'No results in the previous period.'
+ return (
+ <Tooltip title={reason}>
+ <span className="text-secondary">-</span>
+ </Tooltip>
+ )
+ }
+ // A change is not good or bad on its own, so it stays neutral. The attention tags say when it is worse.
+ const Icon = change.value > 0 ? IconArrowUpRight : change.value < 0 ? IconArrowRightDown : null
+ const magnitude = Math.abs(change.value).toFixed(change.unit === 'points' ? 2 : 1)
+ return (
+ <Tooltip title="Change against the previous period of the same length.">
+ <span className="inline-flex items-center gap-0.5 whitespace-nowrap">
+ {Icon && <Icon className="text-secondary" />}
+ <span>{`${magnitude} ${change.unit}`}</span>
+ {change.subject && <span className="text-secondary">{` ${change.subject}`}</span>}
+ </span>
+ </Tooltip>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultDetails.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultDetails.tsx
new file mode 100644
index 000000000000..0b999f1b5525
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultDetails.tsx
@@ -0,0 +1,46 @@
+import { useActions } from 'kea'
+
+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { RATE_LIMITED_MESSAGE } from './evaluationOverviewDisplay'
+import { type DetailsLoad, type EvaluationDetails, evaluationResultDrawerLogic } from './evaluationResultDrawerLogic'
+
+export function EvaluationResultDetails({
+ evaluationId,
+ load,
+ children,
+}: {
+ evaluationId: string
+ load: DetailsLoad | null
+ children: (details: EvaluationDetails) => JSX.Element
+}): JSX.Element {
+ const { loadDetails } = useActions(evaluationResultDrawerLogic)
+
+ if (load?.status === 'ready') {
+ return children(load.details)
+ }
+ if (load?.status === 'error') {
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-2 text-sm">
+ <span className="text-secondary">
+ {load.failure === 'rate_limited' ? RATE_LIMITED_MESSAGE : "Couldn't load these results."}
+ </span>
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={() => loadDetails(evaluationId, 'open')}
+ data-attr="evaluation-overview-drawer-retry"
+ >
+ Try again
+ </LemonButton>
+ </div>
+ )
+ }
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonSkeleton className="h-4 w-full" />
+ <LemonSkeleton className="h-4 w-3/4" />
+ <LemonSkeleton className="h-4 w-1/2" />
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultDrawer.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultDrawer.tsx
new file mode 100644
index 000000000000..945655f27e1e
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultDrawer.tsx
@@ -0,0 +1,44 @@
+import { useActions, useValues } from 'kea'
+
+import { IconArrowRight } from '@posthog/icons'
+import { LemonButton, LemonDrawer } from '@posthog/lemon-ui'
+
+import { evaluationResultDrawerLogic } from './evaluationResultDrawerLogic'
+import { EvaluationResultExpanded } from './EvaluationResultExpanded'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+/** One evaluation's results in a drawer, so the table keeps its place. */
+export function EvaluationResultDrawer(): JSX.Element {
+ const { openRow } = useValues(evaluationResultDrawerLogic)
+ const { closeDrawer } = useActions(evaluationResultDrawerLogic)
+ const { evaluationUrl } = useValues(evaluationsOverviewLogic)
+
+ return (
+ <LemonDrawer
+ isOpen={!!openRow}
+ onClose={closeDrawer}
+ // The padding keeps a long name clear of the button next to the close button.
+ title={<span className="block pr-40">{openRow?.name ?? 'Evaluation'}</span>}
+ width={960}
+ data-attr="evaluation-overview-drawer"
+ description={
+ openRow ? (
+ // The drawer's close button sits at the top right, so this sits just left of it.
+ <div className="absolute top-3 right-14">
+ <LemonButton
+ type="secondary"
+ size="small"
+ sideIcon={<IconArrowRight />}
+ to={evaluationUrl(openRow.id)}
+ data-attr="evaluation-overview-drawer-open"
+ >
+ Open evaluation
+ </LemonButton>
+ </div>
+ ) : null
+ }
+ >
+ {openRow ? <EvaluationResultExpanded row={openRow} /> : null}
+ </LemonDrawer>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultExpanded.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultExpanded.tsx
new file mode 100644
index 000000000000..d7570f48caf2
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultExpanded.tsx
@@ -0,0 +1,106 @@
+import { useValues } from 'kea'
+
+import { LemonBanner, Link } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { EvaluationCategoryShares } from './EvaluationCategoryShares'
+import { EvaluationDrawerEmptyState } from './EvaluationDrawerEmptyState'
+import { EvaluationFailingExamples } from './EvaluationFailingExamples'
+import { describeAttention } from './evaluationOverviewDisplay'
+import { EvaluationPausedNotice } from './EvaluationPausedNotice'
+import { EvaluationResultDetails } from './EvaluationResultDetails'
+import { evaluationResultDrawerLogic } from './evaluationResultDrawerLogic'
+import { EvaluationResultOutcomes } from './EvaluationResultOutcomes'
+import { EvaluationResultTrendChart } from './EvaluationResultTrendChart'
+import { EvaluationScoreHistogram } from './EvaluationScoreHistogram'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+function Card({
+ title,
+ className,
+ children,
+}: {
+ title: string
+ className?: string
+ children: React.ReactNode
+}): JSX.Element {
+ return (
+ <section className={cn('border rounded bg-surface-primary p-3 flex flex-col gap-2 min-w-0', className)}>
+ <h4 className="mb-0 text-sm font-semibold">{title}</h4>
+ {children}
+ </section>
+ )
+}
+
+export function EvaluationResultExpanded({ row }: { row: EvaluationResultApi }): JSX.Element {
+ const { configById, timezone, evaluationUrl } = useValues(evaluationsOverviewLogic)
+ const { openDetails } = useValues(evaluationResultDrawerLogic)
+ const { summary } = row
+ const errored = row.attentionReasons.includes('errored')
+ const enabled = configById.get(row.id)?.enabled ?? row.enabled
+ const hasScore = summary.kind === 'score' || (summary.kind === 'pass_rate' && row.outputType === 'numeric')
+
+ const notice = errored ? (
+ <LemonBanner type="error">
+ <span>{`${describeAttention(row, timezone)}. `}</span>
+ <Link to={evaluationUrl(row.id)}>Open the evaluation to fix it.</Link>
+ </LemonBanner>
+ ) : !enabled ? (
+ <EvaluationPausedNotice row={row} />
+ ) : null
+
+ if (row.gradedCount === 0) {
+ return <EvaluationDrawerEmptyState row={row} />
+ }
+
+ return (
+ <div className="@container flex flex-col gap-3">
+ {notice}
+ <div className="grid gap-3 grid-cols-1 @2xl:grid-cols-2">
+ <Card title="Over time" className="@2xl:col-span-2">
+ <EvaluationResultTrendChart row={row} />
+ </Card>
+ {summary.kind === 'pass_rate' && (
+ <Card title="Outcomes">
+ <EvaluationResultOutcomes row={row} summary={summary} />
+ </Card>
+ )}
+ {(summary.kind === 'categories' || summary.kind === 'sentiment') && (
+ <Card title={summary.kind === 'sentiment' ? 'Sentiment split' : 'Labels'}>
+ <EvaluationCategoryShares summary={summary} gradedCount={row.gradedCount} />
+ </Card>
+ )}
+ {hasScore && (
+ <Card title="Score distribution">
+ <EvaluationResultDetails evaluationId={row.id} load={openDetails}>
+ {(details) =>
+ details.scoreDistribution ? (
+ <EvaluationScoreHistogram histogram={details.scoreDistribution} />
+ ) : (
+ <div className="text-sm text-secondary">
+ Set score bounds on the evaluation to see how scores spread.
+ </div>
+ )
+ }
+ </EvaluationResultDetails>
+ </Card>
+ )}
+ {summary.kind === 'pass_rate' && (
+ <Card title="Recent failing examples">
+ <EvaluationResultDetails evaluationId={row.id} load={openDetails}>
+ {(details) =>
+ details.recentFailures && details.recentFailures.length > 0 ? (
+ <EvaluationFailingExamples failures={details.recentFailures} />
+ ) : (
+ <div className="text-sm text-secondary">No failed runs in this range.</div>
+ )
+ }
+ </EvaluationResultDetails>
+ </Card>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultMiniChart.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultMiniChart.tsx
new file mode 100644
index 000000000000..3043695a0782
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultMiniChart.tsx
@@ -0,0 +1,73 @@
+import { useMemo } from 'react'
+
+import { ProportionBar, Sparkline } from '@posthog/quill-charts'
+import type { Series } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { toChartValues } from './evaluationOverviewDisplay'
+
+const SENTIMENT_COLORS = { positive: 'success', neutral: 'muted', negative: 'danger' } as const
+
+// Fit the line to its own range so the shape shows. The number next to it carries the magnitude.
+function paddedDomain(values: number[]): { min: number; max: number } | undefined {
+ const finite = values.filter(Number.isFinite)
+ if (finite.length === 0) {
+ return undefined
+ }
+ const low = Math.min(...finite)
+ const high = Math.max(...finite)
+ const padding = high > low ? (high - low) * 0.2 : Math.max(Math.abs(high) * 0.05, 1)
+ return { min: low - padding, max: high + padding }
+}
+
+export function EvaluationResultMiniChart({
+ row,
+ buckets,
+}: {
+ row: EvaluationResultApi
+ buckets: string[]
+}): JSX.Element {
+ const theme = useChartTheme()
+ const { summary } = row
+
+ const parts = useMemo<Series[] | null>(() => {
+ if (summary.kind === 'sentiment') {
+ return (['positive', 'neutral', 'negative'] as const).map((key) => ({
+ key,
+ label: key[0].toUpperCase() + key.slice(1),
+ data: [summary[key]],
+ color: getColorVar(SENTIMENT_COLORS[key]),
+ }))
+ }
+ // Labels on a multiple-selection result overlap, so a part-of-whole bar would mislead.
+ if (summary.kind === 'categories' && !summary.multiple) {
+ return summary.categories.map((category) => ({
+ key: category.key,
+ label: category.label,
+ data: [category.count],
+ }))
+ }
+ return null
+ }, [summary])
+ const values = useMemo(() => toChartValues(row.trend.values), [row])
+
+ if (parts) {
+ return (
+ <div className="h-7 flex flex-col justify-center">
+ <ProportionBar
+ series={parts}
+ theme={theme}
+ config={{ barHeight: 8, barCornerRadius: 2, legend: { show: false } }}
+ />
+ </div>
+ )
+ }
+ return (
+ <div className="h-7">
+ <Sparkline data={values} labels={buckets} theme={theme} height={28} valueDomain={paddedDomain(values)} />
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultNameCell.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultNameCell.tsx
new file mode 100644
index 000000000000..5430acc9a3c8
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultNameCell.tsx
@@ -0,0 +1,84 @@
+import { useActions, useValues } from 'kea'
+
+import { IconFolder } from '@posthog/icons'
+import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { getUnhealthyProviderKey, providerKeyStateIssueDescription } from '../../settings/providerKeyStateUtils'
+import { evaluationTypeUsesProviderKey } from '../evaluationCapabilities'
+import { llmEvaluationsLogic } from '../llmEvaluationsLogic'
+import { ATTENTION_LABELS, describeAttention, methodLabel, outputTypeLabel } from './evaluationOverviewDisplay'
+import { evaluationResultDrawerLogic } from './evaluationResultDrawerLogic'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+export function EvaluationResultNameCell({ row }: { row: EvaluationResultApi }): JSX.Element {
+ const { configById, timezone } = useValues(evaluationsOverviewLogic)
+ const { providerKeys } = useValues(llmEvaluationsLogic)
+ const { openDrawer, prefetchDetails } = useActions(evaluationResultDrawerLogic)
+ const config = configById.get(row.id)
+ const keyIssue =
+ config?.enabled && evaluationTypeUsesProviderKey(config.evaluation_type)
+ ? getUnhealthyProviderKey(providerKeys, config.model_configuration?.provider_key_id)
+ : null
+ const type = outputTypeLabel(row)
+
+ return (
+ <div className="flex flex-col gap-1 py-1 min-w-0">
+ <Link
+ onClick={() => openDrawer(row.id)}
+ onMouseEnter={() => prefetchDetails(row.id)}
+ className="font-semibold break-words"
+ data-attr="evaluation-overview-table-name"
+ >
+ {row.name}
+ </Link>
+ <div className="flex flex-wrap items-center gap-1">
+ {row.directoryName && (
+ <span className="inline-flex items-center gap-0.5 text-xs text-secondary mr-1">
+ <IconFolder />
+ <span>{row.directoryName}</span>
+ </span>
+ )}
+ <LemonTag size="small">{methodLabel(row)}</LemonTag>
+ {type && <LemonTag size="small">{type}</LemonTag>}
+ {!(config?.enabled ?? row.enabled) && !row.attentionReasons.includes('errored') && (
+ <LemonTag size="small" type="muted">
+ Disabled
+ </LemonTag>
+ )}
+ {row.attentionReasons.map((reason) =>
+ reason === 'errored' ? (
+ <Tooltip
+ key={reason}
+ title={`${describeAttention(row, timezone)}. Open the evaluation to fix it.`}
+ >
+ <LemonTag size="small" type="danger">
+ {ATTENTION_LABELS[reason]}
+ </LemonTag>
+ </Tooltip>
+ ) : (
+ <LemonTag key={reason} size="small" type="warning">
+ {ATTENTION_LABELS[reason]}
+ </LemonTag>
+ )
+ )}
+ {keyIssue && (
+ <Tooltip
+ title={`Paused because API key ${keyIssue.name} ${providerKeyStateIssueDescription(keyIssue.state)}. Open settings to fix.`}
+ >
+ <Link
+ to={urls.settings('project-ai-observability', 'ai-observability-byok')}
+ data-attr="evaluation-overview-table-key-issue"
+ >
+ <LemonTag size="small" type="warning">
+ Key issue
+ </LemonTag>
+ </Link>
+ </Tooltip>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultOutcomes.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultOutcomes.tsx
new file mode 100644
index 000000000000..3963e99a944b
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultOutcomes.tsx
@@ -0,0 +1,66 @@
+import { useMemo } from 'react'
+
+import { ProportionBar } from '@posthog/quill-charts'
+import type { Series } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import type { EvaluationResultApi, PassRateSummaryApi } from '../../generated/api.schemas'
+import { formatPercent } from './evaluationOverviewDisplay'
+
+export function EvaluationResultOutcomes({
+ row,
+ summary,
+}: {
+ row: EvaluationResultApi
+ summary: PassRateSummaryApi
+}): JSX.Element {
+ const theme = useChartTheme()
+ const series = useMemo<Series[]>(
+ () => [
+ { key: 'passed', label: 'Passed', data: [summary.passed], color: getColorVar('success') },
+ { key: 'failed', label: 'Failed', data: [summary.failed], color: getColorVar('danger') },
+ ],
+ [summary]
+ )
+ const total = summary.passed + summary.failed
+ const outside = (
+ [
+ ['N/A', row.notApplicableCount],
+ ['skipped', row.skippedCount],
+ ] as [string, number][]
+ ).filter(([, count]) => count > 0)
+
+ return (
+ <>
+ {/* The bar's own legend sits in a scroll box a few pixels too short for its row, which shows an empty
+ scrollbar where scrollbars always show, so this card draws the legend itself. */}
+ <ProportionBar
+ series={series}
+ theme={theme}
+ config={{ barHeight: 12, barCornerRadius: 3, legend: { show: false } }}
+ />
+ <div className="flex flex-wrap gap-x-3 gap-y-1 text-xs">
+ {series.map((part) => (
+ <span key={part.key} className="inline-flex items-center gap-1.5">
+ <span
+ aria-hidden
+ className="inline-block size-2.5 rounded-sm shrink-0"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ backgroundColor: part.color }}
+ />
+ <span>{part.label}</span>
+ <span className="text-secondary tabular-nums">{`${formatPercent(total > 0 ? (part.data[0] / total) * 100 : NaN)} · ${humanFriendlyNumber(part.data[0])}`}</span>
+ </span>
+ ))}
+ </div>
+ <div className="text-xs text-secondary">
+ {outside.length > 0
+ ? `Not in the rate: ${outside.map(([label, count]) => `${humanFriendlyNumber(count)} ${label}`).join(' · ')}`
+ : 'Every graded run counts toward the rate.'}
+ </div>
+ </>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultTrendCell.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultTrendCell.tsx
new file mode 100644
index 000000000000..241a0204660e
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultTrendCell.tsx
@@ -0,0 +1,23 @@
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { EvaluationResultChange } from './EvaluationResultChange'
+import { EvaluationResultMiniChart } from './EvaluationResultMiniChart'
+
+export function EvaluationResultTrendCell({
+ row,
+ buckets,
+}: {
+ row: EvaluationResultApi
+ buckets: string[]
+}): JSX.Element | null {
+ if (row.gradedCount === 0) {
+ return null
+ }
+ return (
+ <div className="w-32 @3xl:w-44 flex flex-col gap-1">
+ <div className="text-xs">
+ <EvaluationResultChange row={row} />
+ </div>
+ <EvaluationResultMiniChart row={row} buckets={buckets} />
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultTrendChart.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultTrendChart.tsx
new file mode 100644
index 000000000000..e0e647e8b7b9
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultTrendChart.tsx
@@ -0,0 +1,138 @@
+import { useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { TimeSeriesComboChart, TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'
+import type { Series, TimeSeriesComboChartConfig, TooltipContext } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { formatBucket, hourTick, toChartValues, trackedCategory } from './evaluationOverviewDisplay'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+const VOLUME_KEY = 'volume'
+const VOLUME_CEILING_KEY = 'volume-ceiling'
+/** Volume bars use at most this share of the plot height, so they read as context behind the line. */
+const VOLUME_HEIGHT_SHARE = 1 / 4
+
+const HEADLINE_LABELS: Record<EvaluationResultApi['summary']['kind'], string> = {
+ pass_rate: 'Pass rate',
+ score: 'Mean score',
+ sentiment: 'Negative share',
+ categories: 'Share with the tracked label',
+}
+
+/** Canvas colors cannot read CSS variables, so resolve the token and add transparency. */
+function withAlpha(color: string, alpha: number): string {
+ const hex = color.startsWith('#') && color.length === 7 ? color : null
+ return hex
+ ? `${hex}${Math.round(alpha * 255)
+ .toString(16)
+ .padStart(2, '0')}`
+ : color
+}
+
+export function EvaluationResultTrendChart({ row }: { row: EvaluationResultApi }): JSX.Element {
+ const theme = useChartTheme()
+ const { buckets, timezone, interval } = useValues(evaluationsOverviewLogic)
+ const { summary, trend } = row
+ const isScore = summary.kind === 'score'
+ const label = trackedCategory(row)?.label ?? HEADLINE_LABELS[summary.kind]
+ const values = useMemo(() => toChartValues(trend.values), [trend])
+
+ const series = useMemo<Series[]>(() => {
+ return [
+ {
+ key: VOLUME_KEY,
+ label: 'Graded',
+ data: trend.volume,
+ type: 'bar',
+ yAxisId: VOLUME_KEY,
+ color: withAlpha(getColorVar('muted'), 0.3),
+ },
+ // The combo chart ignores axis bounds, so an invisible line at the ceiling stretches the volume axis
+ // and keeps the real bars in the bottom part of the plot.
+ {
+ key: VOLUME_CEILING_KEY,
+ label: '',
+ data: trend.volume.map(() => Math.max(1, ...trend.volume) / VOLUME_HEIGHT_SHARE),
+ type: 'line',
+ yAxisId: VOLUME_KEY,
+ color: 'transparent',
+ visibility: { tooltip: false, total: false, valueLabel: false },
+ },
+ {
+ key: 'headline',
+ label,
+ // NaN leaves a gap, so a bucket with no graded results never reads as a measured 0%.
+ data: values,
+ type: 'line',
+ color: theme.colors[0],
+ points: { radius: 3 },
+ },
+ ]
+ }, [trend, values, label, theme])
+
+ const config = useMemo<TimeSeriesComboChartConfig>(() => {
+ const finite = values.filter(Number.isFinite)
+ // Zoom in when every point sits high, and let the axis labels say so.
+ const floor = finite.length > 0 ? Math.max(0, Math.floor((Math.min(...finite) - 10) / 10) * 10) : 0
+ const scale = summary.kind === 'score' ? summary.score?.scale : null
+ return {
+ xAxis: { timezone, interval, ...(interval === 'hour' ? { tickFormatter: hourTick } : {}) },
+ // Straight segments, because a curve invents values between buckets and overshoots on sparse ones.
+ curve: 'linear',
+ yAxis: [
+ isScore
+ ? { id: 'left', showGrid: true, decimalPlaces: 2 }
+ : { id: 'left', showGrid: true, format: 'percentage' },
+ { id: VOLUME_KEY, position: 'right', hide: true },
+ ],
+ valueDomain: isScore ? (scale ? { min: scale.min, max: scale.max } : undefined) : { min: floor, max: 100 },
+ }
+ }, [isScore, summary, values, timezone, interval])
+
+ const tooltip = (ctx: TooltipContext): JSX.Element => {
+ const value = values[ctx.dataIndex]
+ const line = ctx.seriesData.find((entry) => entry.series.key === 'headline')
+ return (
+ <TooltipSurface>
+ <div className="font-semibold">{formatBucket(String(ctx.label), interval)}</div>
+ {Number.isFinite(value) ? (
+ <div className="flex items-center gap-2 mt-1">
+ {line && <TooltipSwatch color={line.color} />}
+ <span>{label}</span>
+ <strong className="ml-auto tabular-nums">
+ {isScore ? value.toFixed(2) : `${value.toFixed(1)}%`}
+ </strong>
+ </div>
+ ) : (
+ <div className="mt-1 opacity-70">No graded results</div>
+ )}
+ <div className="flex items-center gap-2 opacity-70">
+ <span>Graded results</span>
+ <span className="ml-auto tabular-nums">
+ {humanFriendlyNumber(trend.volume[ctx.dataIndex] ?? 0)}
+ </span>
+ </div>
+ </TooltipSurface>
+ )
+ }
+
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="h-56 min-w-0 flex flex-col">
+ <TimeSeriesComboChart
+ series={series}
+ labels={buckets}
+ theme={theme}
+ config={config}
+ tooltip={tooltip}
+ />
+ </div>
+ <div className="text-xs text-secondary">{`Shaded bars show how many results were graded each ${interval}.`}</div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationResultsTable.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationResultsTable.tsx
new file mode 100644
index 000000000000..ee7ff886c864
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationResultsTable.tsx
@@ -0,0 +1,164 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPlus, IconSearch } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonSelect, LemonTable } from '@posthog/lemon-ui'
+
+import { AccessControlAction } from 'lib/components/AccessControlAction'
+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import type { EvaluationResultApi } from '../../generated/api.schemas'
+import { llmEvaluationsLogic } from '../llmEvaluationsLogic'
+import { EvaluationCreateSlot } from './EvaluationCreateSlot'
+import { EvaluationDirectoryTiles } from './EvaluationDirectoryTiles'
+import { ATTENTION_LABELS } from './evaluationOverviewDisplay'
+import { EvaluationResultActions } from './EvaluationResultActions'
+import { EvaluationResultCell } from './EvaluationResultCell'
+import { EvaluationResultDrawer } from './EvaluationResultDrawer'
+import { EvaluationResultNameCell } from './EvaluationResultNameCell'
+import { EvaluationResultTrendCell } from './EvaluationResultTrendCell'
+import { type AttentionFilter, OVERVIEW_LIST_ANCHOR_ID, evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+const FILTER_OPTIONS: { value: AttentionFilter; label: string }[] = [
+ { value: null, label: 'All' },
+ { value: 'any', label: 'Needs attention' },
+ ...(['errored', 'silent', 'worse'] as const).map((reason) => ({ value: reason, label: ATTENTION_LABELS[reason] })),
+]
+
+export function EvaluationResultsTable(): JSX.Element {
+ const {
+ tableRows,
+ rows,
+ buckets,
+ search,
+ attentionFilter,
+ attentionCounts,
+ configById,
+ few,
+ overviewLoading,
+ overviewFailure,
+ directoryTiles,
+ } = useValues(evaluationsOverviewLogic)
+ const { setSearch, setAttentionFilter } = useActions(evaluationsOverviewLogic)
+ const { openCreateDirectory } = useActions(llmEvaluationsLogic)
+
+ const columns: LemonTableColumns<EvaluationResultApi> = [
+ {
+ title: 'Evaluation',
+ key: 'name',
+ render: (_, row) => <EvaluationResultNameCell row={row} />,
+ sorter: (a, b) => a.name.localeCompare(b.name),
+ },
+ {
+ title: 'Result',
+ key: 'result',
+ render: (_, row) => <EvaluationResultCell row={row} />,
+ // Sorts by how many results were graded, since results of different types share no scale.
+ sorter: (a, b) => a.gradedCount - b.gradedCount,
+ },
+ {
+ title: 'Trend',
+ key: 'trend',
+ // Under about 520px the change moves under the result instead.
+ className: 'hidden @min-[32.5rem]:table-cell',
+ tooltip: 'Change against the previous period of the same length, and the trend within this range',
+ width: 0,
+ render: (_, row) => <EvaluationResultTrendCell row={row} buckets={buckets} />,
+ },
+ {
+ title: 'Created by',
+ key: 'created_by',
+ className: 'hidden @min-[40rem]:table-cell',
+ width: 0,
+ align: 'center',
+ render: (_, row) => {
+ const user = configById.get(row.id)?.created_by
+ return user ? (
+ <ProfilePicture user={user} size="md" title={user.first_name || user.email} />
+ ) : row.createdBy ? (
+ <ProfilePicture name={row.createdBy} size="md" title={row.createdBy} />
+ ) : (
+ <span className="text-secondary">-</span>
+ )
+ },
+ },
+ {
+ key: 'actions',
+ width: 0,
+ render: (_, row) => {
+ const config = configById.get(row.id)
+ return config ? <EvaluationResultActions config={config} /> : null
+ },
+ },
+ ]
+
+ return (
+ <div id={OVERVIEW_LIST_ANCHOR_ID} className="@container flex flex-col gap-3 scroll-mt-4">
+ <EvaluationDirectoryTiles />
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonInput
+ type="search"
+ size="small"
+ className="flex-1 min-w-48"
+ prefix={<IconSearch />}
+ placeholder="Search evaluations"
+ value={search}
+ onChange={setSearch}
+ data-attr="evaluation-overview-table-search"
+ />
+ {directoryTiles.length === 0 && (
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Evaluation}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ size="small"
+ icon={<IconPlus />}
+ onClick={() => openCreateDirectory()}
+ data-attr="create-evaluation-directory-button"
+ >
+ New directory
+ </LemonButton>
+ </AccessControlAction>
+ )}
+ <LemonSelect
+ size="small"
+ value={attentionFilter}
+ onChange={setAttentionFilter}
+ options={FILTER_OPTIONS.map(({ value, label }) => ({
+ value,
+ label: `${label} (${attentionCounts[value ?? 'all'] ?? 0})`,
+ }))}
+ data-attr="evaluation-overview-table-filter"
+ />
+ </div>
+ <LemonTable
+ columns={columns}
+ dataSource={tableRows}
+ loading={overviewLoading}
+ rowKey="id"
+ // Each row draws a trend chart, so a long list renders one page at a time.
+ pagination={{ pageSize: 50 }}
+ nouns={['evaluation', 'evaluations']}
+ footer={
+ few && (
+ <div className="p-2">
+ <EvaluationCreateSlot className="w-full py-3" />
+ </div>
+ )
+ }
+ emptyState={
+ overviewFailure
+ ? "Results didn't load. Try again above."
+ : attentionFilter || search
+ ? 'No evaluations match this search or filter.'
+ : 'No evaluations in this scope yet.'
+ }
+ />
+ <div className="text-xs text-secondary">{`Showing ${tableRows.length} of ${rows.length} evaluations`}</div>
+ <EvaluationResultDrawer />
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationScopePicker.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationScopePicker.tsx
new file mode 100644
index 000000000000..51f0bf2ec220
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationScopePicker.tsx
@@ -0,0 +1,72 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconSearch } from '@posthog/icons'
+import { LemonButton, LemonCheckbox, LemonDropdown, LemonInput } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+/** Picks which evaluations the overview shows. A button like the date range, so the header controls line up. */
+export function EvaluationScopePicker(): JSX.Element {
+ const { scopeEvaluations, pickedIds } = useValues(evaluationsOverviewLogic)
+ const { setPickedIds } = useActions(evaluationsOverviewLogic)
+ const [search, setSearch] = useState('')
+ const matching = scopeEvaluations.filter((evaluation) =>
+ evaluation.name.toLowerCase().includes(search.toLowerCase())
+ )
+ const toggle = (id: string): void =>
+ setPickedIds(pickedIds.includes(id) ? pickedIds.filter((current) => current !== id) : [...pickedIds, id])
+
+ return (
+ <LemonDropdown
+ closeOnClickInside={false}
+ overlay={
+ <div className="flex flex-col gap-1 w-72 max-h-96">
+ <LemonInput
+ type="search"
+ size="small"
+ autoFocus
+ prefix={<IconSearch />}
+ placeholder="Search evaluations"
+ value={search}
+ onChange={setSearch}
+ />
+ <div className="flex flex-col overflow-y-auto">
+ {matching.length === 0 ? (
+ <div className="px-2 py-1 text-secondary">No evaluations match this search</div>
+ ) : (
+ matching.map((evaluation) => (
+ <LemonCheckbox
+ key={evaluation.id}
+ fullWidth
+ size="small"
+ className="px-2 py-1"
+ checked={pickedIds.includes(evaluation.id)}
+ onChange={() => toggle(evaluation.id)}
+ label={evaluation.name}
+ />
+ ))
+ )}
+ </div>
+ {pickedIds.length > 0 && (
+ <LemonButton
+ size="small"
+ fullWidth
+ center
+ onClick={() => setPickedIds([])}
+ data-attr="evaluation-overview-scope-clear"
+ >
+ Show all evaluations
+ </LemonButton>
+ )}
+ </div>
+ }
+ >
+ <LemonButton type="secondary" size="small" data-attr="evaluation-overview-scope-picker">
+ {pickedIds.length === 0 ? 'All evaluations' : pluralize(pickedIds.length, 'evaluation')}
+ </LemonButton>
+ </LemonDropdown>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationScoreHistogram.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationScoreHistogram.tsx
new file mode 100644
index 000000000000..ed7eb0913eec
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationScoreHistogram.tsx
@@ -0,0 +1,27 @@
+import { useMemo } from 'react'
+
+import { BarChart } from '@posthog/quill-charts'
+import type { Series } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+
+import type { ScoreHistogramApi } from '../../generated/api.schemas'
+
+export function EvaluationScoreHistogram({ histogram }: { histogram: ScoreHistogramApi }): JSX.Element {
+ const theme = useChartTheme()
+ const labels = useMemo(() => histogram.buckets.map((bucket) => bucket.label), [histogram])
+ const series = useMemo<Series[]>(
+ () => [{ key: 'results', label: 'Results', data: histogram.buckets.map((bucket) => bucket.count) }],
+ [histogram]
+ )
+ return (
+ <div className="h-48 min-w-0 flex flex-col">
+ <BarChart
+ series={series}
+ labels={labels}
+ theme={theme}
+ config={{ showGrid: true, barCornerRadius: 2, xAxisLabel: 'Score', yAxisLabel: 'Results' }}
+ />
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationStatusGrid.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationStatusGrid.tsx
new file mode 100644
index 000000000000..25678636472f
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationStatusGrid.tsx
@@ -0,0 +1,188 @@
+import { useValues } from 'kea'
+import { type MouseEvent, useEffect, useMemo, useRef, useState } from 'react'
+
+import { Link, Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { BucketStatusEnumApi, EvaluationResultApi } from '../../generated/api.schemas'
+import { compactHeadline, describeBucket, formatBucket } from './evaluationOverviewDisplay'
+import { evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+/** Below this many graded results the backend never marks a bucket unusual, so the cell is greyed as unreliable. */
+const LOW_EVIDENCE_BUCKET_VOLUME = 30
+
+const STATUS_CLASSES: Record<BucketStatusEnumApi, string> = {
+ dip: 'bg-warning border-transparent',
+ normal: 'bg-muted opacity-40 border-transparent',
+ none: 'border-dashed border-primary',
+}
+
+const STATUS_LABELS: Record<BucketStatusEnumApi, string> = {
+ dip: 'Unusual for this evaluation',
+ normal: 'In line with its usual results',
+ none: 'No graded results',
+}
+
+const LOW_EVIDENCE_CLASSES = 'bg-muted opacity-15 border-transparent'
+
+const LEGEND_ORDER: BucketStatusEnumApi[] = ['dip', 'normal', 'none']
+
+interface HoveredCell {
+ row: number
+ index: number
+ /** The cell's box relative to the grid, where the shared tooltip anchors. */
+ box: { left: number; top: number; width: number; height: number }
+}
+
+function isLowEvidence(row: EvaluationResultApi, index: number): boolean {
+ return row.bucketStatus[index] === 'normal' && (row.trend.volume[index] ?? 0) < LOW_EVIDENCE_BUCKET_VOLUME
+}
+
+export function EvaluationStatusGrid(): JSX.Element {
+ const { statusGridRows, buckets, interval, evaluationUrl } = useValues(evaluationsOverviewLogic)
+ // One tooltip follows the pointer, because a tooltip per cell makes a large grid slow to render.
+ const [hovered, setHovered] = useState<HoveredCell | null>(null)
+ const gridRef = useRef<HTMLDivElement>(null)
+ const labels = useMemo(() => buckets.map((bucket) => formatBucket(bucket, interval)), [buckets, interval])
+
+ // A tooltip held open with `visible` loses its own Escape and scroll dismissal, so the grid restores both. Both
+ // listen in the capture phase, because Base UI stops Escape before it bubbles to the window.
+ useEffect(() => {
+ if (!hovered) {
+ return
+ }
+ const dismiss = (): void => setHovered(null)
+ const onKeyDown = (event: KeyboardEvent): void => {
+ if (event.key === 'Escape') {
+ dismiss()
+ }
+ }
+ window.addEventListener('keydown', onKeyDown, true)
+ window.addEventListener('scroll', dismiss, true)
+ return () => {
+ window.removeEventListener('keydown', onKeyDown, true)
+ window.removeEventListener('scroll', dismiss, true)
+ }
+ }, [hovered])
+
+ // Memoized so that moving the pointer renders only the tooltip, not every cell.
+ const rows = useMemo(
+ () =>
+ statusGridRows.map((row, rowIndex) => (
+ <div key={row.id} className={cn('flex items-center gap-3', row.lowEvidence && 'opacity-60')}>
+ <Link
+ to={evaluationUrl(row.id)}
+ subtle
+ className="w-28 @2xl:w-48 shrink-0 truncate text-primary"
+ data-attr="evaluation-overview-status-grid-name"
+ >
+ {row.name}
+ </Link>
+ <span className="flex-1 min-w-0 flex gap-0.5">
+ {row.bucketStatus.map((status, index) => (
+ <span
+ key={buckets[index] ?? index}
+ data-row={rowIndex}
+ data-index={index}
+ aria-label={`${row.name}, ${labels[index]}: ${STATUS_LABELS[status]}`}
+ className={cn(
+ 'h-5 flex-1 min-w-0 rounded-sm border',
+ isLowEvidence(row, index) ? LOW_EVIDENCE_CLASSES : STATUS_CLASSES[status]
+ )}
+ />
+ ))}
+ </span>
+ <span className="w-24 @2xl:w-28 shrink-0 text-right tabular-nums truncate font-semibold">
+ {row.gradedCount === 0 ? (row.enabled ? 'No results' : 'Disabled') : compactHeadline(row)}
+ </span>
+ </div>
+ )),
+ [statusGridRows, buckets, labels, evaluationUrl]
+ )
+
+ const hover = (event: MouseEvent<HTMLDivElement>): void => {
+ const cell = (event.target as HTMLElement).closest<HTMLElement>('[data-row]')
+ const grid = gridRef.current
+ if (!cell || !grid) {
+ setHovered(null)
+ return
+ }
+ const row = Number(cell.dataset.row)
+ const index = Number(cell.dataset.index)
+ if (hovered?.row === row && hovered.index === index) {
+ return
+ }
+ const cellBox = cell.getBoundingClientRect()
+ const gridBox = grid.getBoundingClientRect()
+ setHovered({
+ row,
+ index,
+ box: {
+ left: cellBox.left - gridBox.left,
+ top: cellBox.top - gridBox.top,
+ width: cellBox.width,
+ height: cellBox.height,
+ },
+ })
+ }
+
+ const hoveredRow = hovered ? statusGridRows[hovered.row] : undefined
+
+ return (
+ <div className="flex flex-col gap-1 text-sm">
+ <div className="flex items-center gap-3 text-xs text-secondary">
+ <span className="w-28 @2xl:w-48 shrink-0" />
+ <span className="flex-1 flex justify-between">
+ <span>{buckets.length ? formatBucket(buckets[0], interval, 'MMM D') : ''}</span>
+ <span>{buckets.length ? formatBucket(buckets[buckets.length - 1], interval, 'MMM D') : ''}</span>
+ </span>
+ <span className="w-24 @2xl:w-28 shrink-0 text-right">Result</span>
+ </div>
+ <div
+ ref={gridRef}
+ className="relative flex flex-col gap-1"
+ onMouseOver={hover}
+ onMouseLeave={() => setHovered(null)}
+ >
+ {rows}
+ {hovered && hoveredRow && (
+ <Tooltip
+ // A new anchor per cell, because the tooltip does not follow an anchor that moves.
+ key={`${hovered.row}-${hovered.index}`}
+ visible
+ title={
+ <>
+ <div className="font-semibold">{`${hoveredRow.name}, ${labels[hovered.index]}`}</div>
+ <div>{describeBucket(hoveredRow, hovered.index)}</div>
+ <div>
+ {isLowEvidence(hoveredRow, hovered.index)
+ ? 'Too few results to compare'
+ : STATUS_LABELS[hoveredRow.bucketStatus[hovered.index]]}
+ </div>
+ </>
+ }
+ >
+ <span
+ className="absolute pointer-events-none"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={hovered.box}
+ />
+ </Tooltip>
+ )}
+ </div>
+ <div className="flex flex-wrap gap-x-4 gap-y-1 pt-2 text-xs text-secondary">
+ {LEGEND_ORDER.map((status) => (
+ <span key={status} className="inline-flex items-center gap-1.5">
+ <span className={cn('inline-block size-3 rounded-sm border', STATUS_CLASSES[status])} />
+ <span>{STATUS_LABELS[status]}</span>
+ </span>
+ ))}
+ <span className="inline-flex items-center gap-1.5">
+ <span className={cn('inline-block size-3 rounded-sm border', LOW_EVIDENCE_CLASSES)} />
+ <span>Too few results to compare</span>
+ </span>
+ </div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationsOverview.stories.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationsOverview.stories.tsx
new file mode 100644
index 000000000000..3b02a1798c85
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationsOverview.stories.tsx
@@ -0,0 +1,431 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { within } from '@testing-library/dom'
+import userEvent from '@testing-library/user-event'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+import { toPaginatedResponse } from '~/mocks/handlers'
+
+import type {
+ EvaluationApi,
+ EvaluationResultApi,
+ EvaluationRunsApi,
+ EvaluationsOverviewApi,
+ PassRateOverviewEntryApi,
+ ScoreHistogramApi,
+} from '../../generated/api.schemas'
+
+const DAYS = Array.from({ length: 14 }, (_, index) => `2026-10-${String(7 + index).padStart(2, '0')}T00:00:00+00:00`)
+
+/** A smooth, repeatable daily series around `base`, so stories render the same every time. */
+function wave(base: number, swing: number, phase: number): number[] {
+ return DAYS.map((_, index) => Math.round((base + swing * Math.sin(index / 2 + phase)) * 10) / 10)
+}
+
+function volume(perDay: number): number[] {
+ return DAYS.map((_, index) => perDay + ((index * 7) % 5) * Math.round(perDay / 10))
+}
+
+function sum(values: number[]): number {
+ return values.reduce((total, value) => total + value, 0)
+}
+
+function uuid(index: number): string {
+ return `0b1e0000-0000-4000-8000-${index.toString(16).padStart(12, '0')}`
+}
+
+type ResultOverrides = Partial<EvaluationResultApi> & Pick<EvaluationResultApi, 'id' | 'name' | 'summary'>
+
+function result(overrides: ResultOverrides): EvaluationResultApi {
+ return {
+ directoryName: null,
+ evaluationType: 'llm_judge',
+ outputType: 'boolean',
+ enabled: true,
+ statusReason: null,
+ createdBy: 'Ada Example',
+ gradedCount: 0,
+ previousGradedCount: null,
+ notApplicableCount: 0,
+ skippedCount: 0,
+ lastRunAt: '2026-10-20T09:00:00Z',
+ trend: { values: DAYS.map(() => null), volume: DAYS.map(() => 0) },
+ change: null,
+ lowEvidence: false,
+ attentionReasons: [],
+ bucketStatus: DAYS.map(() => 'none'),
+ trackedCategory: null,
+ ...overrides,
+ }
+}
+
+function passRateResult(
+ id: string,
+ name: string,
+ rate: number,
+ previous: number | null,
+ perDay: number,
+ swing = 2
+): EvaluationResultApi {
+ const values = wave(rate, swing, id.length)
+ const daily = volume(perDay)
+ const graded = sum(daily)
+ const passed = Math.round((graded * rate) / 100)
+ const change = previous === null ? null : Math.round((rate - previous) * 10) / 10
+ return result({
+ id,
+ name,
+ gradedCount: graded,
+ previousGradedCount: previous === null ? null : Math.round(graded * 0.94),
+ summary: {
+ kind: 'pass_rate',
+ passed,
+ failed: graded - passed,
+ previous:
+ previous === null
+ ? null
+ : {
+ passed: Math.round((graded * previous) / 100),
+ failed: graded - Math.round((graded * previous) / 100),
+ },
+ score: null,
+ },
+ trend: { values, volume: daily },
+ change: change === null ? null : { value: change, unit: 'pp', subject: null },
+ lowEvidence: graded < 30,
+ attentionReasons: change !== null && change <= -2 ? ['worse'] : [],
+ bucketStatus: values.map((value) => (previous !== null && value <= previous - 3 ? 'dip' : 'normal')),
+ })
+}
+
+const HELPFULNESS = passRateResult(uuid(1), 'Helpfulness', 91.4, 92.0, 140)
+const GROUNDEDNESS = passRateResult(uuid(2), 'Answer is grounded in context', 78.2, 86.5, 90, 4)
+const TONE = passRateResult(uuid(3), 'Polite tone', 97.1, 96.4, 60, 1)
+const NEW_CHECK = passRateResult(uuid(4), 'Refuses off-topic requests', 70, null, 1)
+
+const SENTIMENT_VALUES = wave(14, 3, 1)
+const SENTIMENT = result({
+ id: uuid(5),
+ name: 'User sentiment',
+ evaluationType: 'sentiment',
+ outputType: 'sentiment',
+ gradedCount: 3640,
+ previousGradedCount: 3410,
+ summary: { kind: 'sentiment', positive: 1820, neutral: 1310, negative: 510, previousNegativeShare: 12.1 },
+ trend: { values: SENTIMENT_VALUES, volume: volume(250) },
+ change: { value: 1.9, unit: 'pp', subject: 'negative' },
+ bucketStatus: SENTIMENT_VALUES.map((value) => (value >= 15.1 ? 'dip' : 'normal')),
+})
+
+const INTENT = result({
+ id: uuid(6),
+ name: 'Request intent',
+ outputType: 'categorical',
+ gradedCount: 1960,
+ previousGradedCount: 1880,
+ summary: {
+ kind: 'categories',
+ multiple: false,
+ categories: [
+ { key: 'billing', label: 'Billing', count: 820, previousShare: 38.2 },
+ { key: 'bug', label: 'Bug report', count: 640, previousShare: 36.9 },
+ { key: 'other', label: 'Other', count: 500, previousShare: 24.9 },
+ ],
+ noCategoriesCount: 0,
+ },
+ trend: { values: wave(41.8, 2, 2), volume: volume(140) },
+ change: { value: 3.6, unit: 'pp', subject: 'Billing' },
+ bucketStatus: DAYS.map((_, index) => (index === 9 ? 'dip' : 'normal')),
+ trackedCategory: 'billing',
+})
+
+const SCORE = result({
+ id: uuid(7),
+ name: 'Answer completeness',
+ outputType: 'numeric',
+ gradedCount: 1120,
+ previousGradedCount: 1050,
+ summary: { kind: 'score', score: { mean: 3.8, scale: { min: 1, max: 5 } }, previousMean: 3.9 },
+ trend: { values: wave(3.8, 0.15, 3), volume: volume(80) },
+ change: { value: -0.1, unit: 'points', subject: null },
+ bucketStatus: DAYS.map(() => 'normal'),
+})
+
+const ERRORED = result({
+ id: uuid(8),
+ name: 'Cites a source',
+ enabled: false,
+ statusReason: 'provider_key_quota_exceeded',
+ lastRunAt: '2026-10-12T14:00:00Z',
+ summary: { kind: 'pass_rate', passed: 0, failed: 0, previous: null, score: null },
+ attentionReasons: ['errored'],
+})
+
+const SILENT = result({
+ id: uuid(9),
+ name: 'Mentions pricing correctly',
+ lastRunAt: '2026-10-03T08:00:00Z',
+ summary: { kind: 'pass_rate', passed: 0, failed: 0, previous: null, score: null },
+ attentionReasons: ['silent'],
+})
+
+const PAUSED = result({
+ id: uuid(10),
+ name: 'Hallucination check',
+ enabled: false,
+ lastRunAt: '2026-09-28T08:00:00Z',
+ summary: { kind: 'pass_rate', passed: 0, failed: 0, previous: null, score: null },
+})
+
+function median(values: number[]): number | null {
+ if (values.length === 0) {
+ return null
+ }
+ const sorted = [...values].sort((a, b) => a - b)
+ const middle = Math.floor(sorted.length / 2)
+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2
+}
+
+function rateOf(row: EvaluationResultApi): number {
+ return row.summary.kind === 'pass_rate' ? (row.summary.passed / row.gradedCount) * 100 : NaN
+}
+
+function previousRateOf(row: EvaluationResultApi): number | null {
+ const previous = row.summary.kind === 'pass_rate' ? row.summary.previous : null
+ return previous ? (previous.passed / (previous.passed + previous.failed)) * 100 : null
+}
+
+/** Totals built from the rows, the way the backend builds them, so the cards agree with the chart. */
+function overview(evaluations: EvaluationResultApi[]): EvaluationsOverviewApi {
+ const active = evaluations.filter((row) => row.enabled)
+ const passRates = active.filter((row) => row.summary.kind === 'pass_rate' && row.gradedCount > 0)
+ const measured = passRates.filter((row) => !row.lowEvidence)
+ const compared = measured.filter((row) => previousRateOf(row) !== null)
+ const both = active.filter((row) => row.gradedCount > 0 && row.previousGradedCount !== null)
+ const entries: PassRateOverviewEntryApi[] = passRates
+ .map((row) => ({ evaluationId: row.id, rate: rateOf(row), lowEvidence: row.lowEvidence }))
+ .sort((a, b) => a.rate - b.rate)
+ const currentMedian = median(compared.map(rateOf))
+ const previousMedian = median(compared.map((row) => previousRateOf(row) ?? 0))
+ const sentiment = active.find((row) => row.summary.kind === 'sentiment' && row.gradedCount > 0)
+ return {
+ start: DAYS[0],
+ end: '2026-10-21T00:00:00+00:00',
+ previousStart: '2026-09-23T00:00:00+00:00',
+ previousEnd: DAYS[0],
+ interval: 'day',
+ buckets: DAYS,
+ evaluations,
+ totals: {
+ graded: sum(active.map((row) => row.gradedCount)),
+ gradedComparison:
+ both.length > 0
+ ? {
+ current: sum(both.map((row) => row.gradedCount)),
+ previous: sum(both.map((row) => row.previousGradedCount ?? 0)),
+ }
+ : null,
+ gradedTrend: DAYS.map((_, index) => sum(active.map((row) => row.trend.volume[index]))),
+ sentiment:
+ sentiment && sentiment.summary.kind === 'sentiment'
+ ? {
+ evaluationId: sentiment.id,
+ negativeShare: (sentiment.summary.negative / sentiment.gradedCount) * 100,
+ previousShare: sentiment.summary.previousNegativeShare,
+ }
+ : null,
+ },
+ passRateOverview: {
+ entries,
+ median: median(measured.map(rateOf)),
+ medianComparison:
+ currentMedian !== null && previousMedian !== null
+ ? { current: currentMedian, previous: previousMedian }
+ : null,
+ medianTrend: measured.length
+ ? DAYS.map((_, index) =>
+ median(measured.map((row) => row.trend.values[index]).filter((value) => value !== null))
+ )
+ : [],
+ },
+ }
+}
+
+const SUPPORT_DIRECTORY = {
+ id: '0b1ed100-0000-4000-8000-000000000001',
+ name: 'Support bot',
+ created_at: '2026-09-01T10:00:00Z',
+ updated_at: null,
+ created_by: null,
+ evaluation_count: 2,
+}
+
+const SEARCH_DIRECTORY = {
+ ...SUPPORT_DIRECTORY,
+ id: '0b1ed100-0000-4000-8000-000000000002',
+ name: 'Search assistant',
+ evaluation_count: 3,
+}
+
+const DIRECTORIES = [SUPPORT_DIRECTORY, SEARCH_DIRECTORY]
+
+/** The list entry the scene's table and scope picker read, for one overview row. */
+function listEntry(row: EvaluationResultApi): EvaluationApi {
+ return {
+ id: row.id,
+ name: row.name,
+ description: '',
+ directory_id: DIRECTORIES.find((directory) => directory.name === row.directoryName)?.id ?? null,
+ enabled: row.enabled,
+ status: row.statusReason ? 'error' : row.enabled ? 'active' : 'paused',
+ status_reason: row.statusReason as EvaluationApi['status_reason'],
+ status_reason_detail: null,
+ evaluation_type: row.evaluationType as EvaluationApi['evaluation_type'],
+ evaluation_config:
+ row.evaluationType === 'sentiment' ? {} : { prompt: `Check this response for: ${row.name.toLowerCase()}` },
+ output_type: row.outputType as EvaluationApi['output_type'],
+ output_config:
+ row.outputType === 'categorical'
+ ? { options: [{ key: 'billing', label: 'Billing' }] }
+ : row.outputType === 'numeric'
+ ? { min: 1, max: 5 }
+ : {},
+ conditions: [],
+ target: row.evaluationType === 'sentiment' ? 'trace' : 'generation',
+ model_configuration: null,
+ created_at: '2026-09-01T10:00:00Z',
+ updated_at: '2026-10-01T10:00:00Z',
+ created_by: null,
+ deleted: false,
+ user_access_level: 'editor',
+ }
+}
+
+const FAILURES: Record<string, string[]> = {
+ [GROUNDEDNESS.id]: [
+ 'The answer promises a full-year refund. The retrieved policy only allows refunds within 30 days.',
+ 'No retrieved document mentions an export schedule, so the stated time is not supported.',
+ 'The reply names a plan tier that does not appear in the provided pricing context.',
+ ],
+}
+
+/** Invented failing runs for one evaluation, newest first, matching the shape the runs endpoint returns. */
+function failingRuns(id: string): EvaluationRunsApi {
+ return {
+ results: (FAILURES[id] ?? []).map((reasoning, index) => ({
+ timestamp: `2026-10-19T0${9 - index}:12:00Z`,
+ outcome: 'failed',
+ reasoning,
+ targetEventId: `0b1ee000-0000-4000-8000-00000000000${index}`,
+ traceId: `trace-example-${index}`,
+ })),
+ }
+}
+
+const SCORE_HISTOGRAM: ScoreHistogramApi = {
+ scale: { min: 1, max: 5 },
+ buckets: [
+ { label: '1', count: 40 },
+ { label: '2', count: 96 },
+ { label: '3', count: 210 },
+ { label: '4', count: 452 },
+ { label: '5', count: 322 },
+ ],
+}
+
+function scene(rows: EvaluationResultApi[], { rateLimited = false } = {}): ReturnType<typeof mswDecorator> {
+ return mswDecorator({
+ get: {
+ '/api/projects/:team_id/evaluations/': toPaginatedResponse(rows.map(listEntry)),
+ '/api/projects/:team_id/evaluations/overview/': ({ request }) => {
+ if (rateLimited) {
+ return [429, { type: 'throttled_error', detail: 'Too many queries are running.' }]
+ }
+ const ids = new URL(request.url).searchParams.get('evaluation_ids')?.split(',')
+ return [200, overview(ids ? rows.filter((row) => ids.includes(row.id)) : rows)]
+ },
+ '/api/projects/:team_id/evaluations/:id/runs/': ({ params }) => [200, failingRuns(String(params.id))],
+ '/api/projects/:team_id/evaluations/:id/score_distribution/': SCORE_HISTOGRAM,
+ '/api/projects/:team_id/evaluation_directories/': DIRECTORIES.filter((directory) =>
+ rows.some((row) => row.directoryName === directory.name)
+ ),
+ '/api/environments/:team_id/llm_analytics/provider_keys/': toPaginatedResponse([]),
+ '/api/projects/:team_id/llm_analytics/provider_keys/': toPaginatedResponse([]),
+ '/api/environments/:team_id/llm_analytics/evaluation_config/': { active_provider_key: null },
+ },
+ post: {
+ '/api/environments/:team_id/query/': { results: [] },
+ '/api/projects/:team_id/query/': { results: [] },
+ },
+ })
+}
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/AI observability/Evaluations overview',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2026-10-20',
+ pageUrl: urls.aiObservabilityEvaluations(),
+ featureFlags: [FEATURE_FLAGS.AI_OBSERVABILITY_EVALUATIONS_OVERVIEW],
+ testOptions: { waitForLoadersToDisappear: true },
+ },
+}
+export default meta
+type Story = StoryObj<{}>
+
+const MANY = [HELPFULNESS, GROUNDEDNESS, TONE, NEW_CHECK, SENTIMENT, INTENT, SCORE, ERRORED, SILENT, PAUSED]
+
+export const ManyEvaluations: Story = { decorators: [scene(MANY)] }
+
+function openDrawer(name: string): Story['play'] {
+ return async ({ canvasElement }) => {
+ const selector = '[data-attr="evaluation-overview-table-name"]'
+ await userEvent.click(await within(canvasElement).findByText(name, { selector }))
+ }
+}
+
+const IN_DIRECTORIES = [
+ { ...HELPFULNESS, directoryName: SUPPORT_DIRECTORY.name },
+ { ...GROUNDEDNESS, directoryName: SUPPORT_DIRECTORY.name },
+ { ...TONE, directoryName: SEARCH_DIRECTORY.name },
+ { ...INTENT, directoryName: SEARCH_DIRECTORY.name },
+ { ...ERRORED, directoryName: SEARCH_DIRECTORY.name },
+ NEW_CHECK,
+ SENTIMENT,
+ SCORE,
+ SILENT,
+ PAUSED,
+]
+
+export const ManyEvaluationsWithDirectories: Story = { decorators: [scene(IN_DIRECTORIES)] }
+
+export const DirectoryOpen: Story = {
+ parameters: { pageUrl: `${urls.aiObservabilityEvaluations()}?directory=${SEARCH_DIRECTORY.id}` },
+ decorators: [scene(IN_DIRECTORIES)],
+}
+
+export const DrawerPassRate: Story = { decorators: [scene(MANY)], play: openDrawer(GROUNDEDNESS.name) }
+
+export const DrawerScore: Story = { decorators: [scene(MANY)], play: openDrawer(SCORE.name) }
+
+export const DrawerCategories: Story = { decorators: [scene(MANY)], play: openDrawer(INTENT.name) }
+
+export const DrawerSentiment: Story = { decorators: [scene(MANY)], play: openDrawer(SENTIMENT.name) }
+
+export const DrawerEmptyEnabled: Story = { decorators: [scene(MANY)], play: openDrawer(SILENT.name) }
+
+export const DrawerEmptyDisabled: Story = { decorators: [scene(MANY)], play: openDrawer(PAUSED.name) }
+
+export const DrawerEmptyErrored: Story = { decorators: [scene(MANY)], play: openDrawer(ERRORED.name) }
+
+export const RateLimited: Story = { decorators: [scene(MANY, { rateLimited: true })] }
+
+// Most teams run one or two evaluations, so the page has to hold up with very little in it.
+export const TwoEvaluations: Story = { decorators: [scene([GROUNDEDNESS, TONE])] }
+
+export const NothingGraded: Story = { decorators: [scene([SILENT, PAUSED])] }
diff --git a/products/ai_observability/frontend/evaluations/overview/EvaluationsOverview.tsx b/products/ai_observability/frontend/evaluations/overview/EvaluationsOverview.tsx
new file mode 100644
index 000000000000..546848886890
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/EvaluationsOverview.tsx
@@ -0,0 +1,77 @@
+import { useActions, useValues } from 'kea'
+
+import { IconFolder, IconX } from '@posthog/icons'
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+
+import { RATE_LIMITED_MESSAGE } from './evaluationOverviewDisplay'
+import { EvaluationOverviewResults } from './EvaluationOverviewResults'
+import { EvaluationOverviewTiles } from './EvaluationOverviewTiles'
+import { EvaluationScopePicker } from './EvaluationScopePicker'
+import { OVERVIEW_DATE_OPTIONS, evaluationsOverviewLogic } from './evaluationsOverviewLogic'
+
+export function EvaluationsOverview(): JSX.Element {
+ const { dateFilter, request, overviewFailure, selectedDirectory, evaluationListFailed } =
+ useValues(evaluationsOverviewLogic)
+ const { setDates, selectDirectory, retryOverview } = useActions(evaluationsOverviewLogic)
+
+ return (
+ <div className="@container flex flex-col gap-4">
+ <div className="flex flex-wrap items-center gap-2">
+ {selectedDirectory && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconFolder />}
+ sideIcon={<IconX />}
+ onClick={() => selectDirectory(null)}
+ tooltip="Show every directory"
+ data-attr="evaluation-overview-scope-directory-clear"
+ >
+ {selectedDirectory.name}
+ </LemonButton>
+ )}
+ <EvaluationScopePicker />
+ <DateFilter
+ dateFrom={dateFilter.dateFrom}
+ dateTo={dateFilter.dateTo}
+ onChange={setDates}
+ dateOptions={OVERVIEW_DATE_OPTIONS}
+ allowedRollingDateOptions={['hours', 'days', 'weeks', 'months']}
+ />
+ </div>
+ {request.notice ? (
+ <LemonBanner type="info">{request.notice}</LemonBanner>
+ ) : overviewFailure ? (
+ <LemonBanner
+ type={overviewFailure === 'rate_limited' ? 'warning' : 'error'}
+ action={{
+ children: 'Try again',
+ onClick: () => retryOverview(),
+ 'data-attr': 'evaluation-overview-retry',
+ }}
+ >
+ {overviewFailure === 'rate_limited' ? RATE_LIMITED_MESSAGE : "Couldn't load evaluation results."}
+ </LemonBanner>
+ ) : (
+ <>
+ {evaluationListFailed && (
+ <LemonBanner
+ type="warning"
+ action={{
+ children: 'Try again',
+ onClick: () => retryOverview(),
+ 'data-attr': 'evaluation-overview-list-retry',
+ }}
+ >
+ Couldn't load the evaluation list, so editing evaluations and picking them is unavailable.
+ </LemonBanner>
+ )}
+ <EvaluationOverviewTiles />
+ <EvaluationOverviewResults />
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/evaluationOverviewDisplay.ts b/products/ai_observability/frontend/evaluations/overview/evaluationOverviewDisplay.ts
new file mode 100644
index 000000000000..efb20a2278b8
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/evaluationOverviewDisplay.ts
@@ -0,0 +1,239 @@
+import { dayjs } from 'lib/dayjs'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import type { AttentionReasonsEnumApi, CategoryCountApi, EvaluationResultApi } from '../../generated/api.schemas'
+import { statusReasonLabel } from '../statusDisplay'
+import type { EvaluationStatusReason } from '../types'
+
+export const RATE_LIMITED_MESSAGE = 'Too many requests, try again in a moment.'
+
+export function formatPercent(value: number): string {
+ return Number.isFinite(value) ? `${value.toFixed(1)}%` : '-'
+}
+
+export function formatPoints(value: number): string {
+ return Number.isFinite(value) ? `${value > 0 ? '+' : ''}${value.toFixed(1)} pp` : '-'
+}
+
+export type BucketInterval = 'hour' | 'day'
+
+/**
+ * A bucket start for tooltips, read from its own text. Buckets carry the project's offset, so reading the date and
+ * time off the string shows project time whatever the viewer's timezone is. The ends of an axis pass the short
+ * "MMM D" format, for example "Oct 22" or "Oct 22, 14:00".
+ */
+export function formatBucket(label: string, interval: BucketInterval, dayFormat: string = 'ddd, MMM D'): string {
+ const day = dayjs(label.slice(0, 10)).format(dayFormat)
+ return interval === 'hour' ? `${day}, ${label.slice(11, 16)}` : day
+}
+
+/** Charts take NaN for a missing point, where the API sends null. */
+export function toChartValues(values: (number | null)[]): number[] {
+ return values.map((value) => (value === null ? NaN : value))
+}
+
+function share(part: number, whole: number): number {
+ return whole > 0 ? (part / whole) * 100 : NaN
+}
+
+/** The category a categorical row's trend follows. Labels can repeat, so it is found by key. */
+export function trackedCategory(row: EvaluationResultApi): CategoryCountApi | undefined {
+ return row.summary.kind === 'categories'
+ ? row.summary.categories.find((entry) => entry.key === row.trackedCategory)
+ : undefined
+}
+
+export function passRate(row: EvaluationResultApi): number {
+ const { summary } = row
+ return summary.kind === 'pass_rate' ? share(summary.passed, summary.passed + summary.failed) : NaN
+}
+
+/**
+ * A row's period result on a 0-100 scale, so every evaluation type can share one axis. Pass rates, negative
+ * sentiment and label shares are already percentages. Scores become their position on the configured scale.
+ */
+export function percentValue(row: EvaluationResultApi): number {
+ const { summary } = row
+ switch (summary.kind) {
+ case 'pass_rate':
+ return passRate(row)
+ case 'sentiment':
+ return share(summary.negative, summary.positive + summary.neutral + summary.negative)
+ case 'categories': {
+ const category = trackedCategory(row)
+ return category ? share(category.count, row.gradedCount) : NaN
+ }
+ case 'score':
+ return summary.score?.scale
+ ? share(summary.score.mean - summary.score.scale.min, summary.score.scale.max - summary.score.scale.min)
+ : NaN
+ }
+}
+
+/** The same 0-100 scale as `percentValue`, for each day of the trend. */
+export function percentTrend(row: EvaluationResultApi): number[] {
+ const values = toChartValues(row.trend.values)
+ const { summary } = row
+ if (summary.kind !== 'score') {
+ return values
+ }
+ const scale = summary.score?.scale
+ return values.map((value) => (scale ? share(value - scale.min, scale.max - scale.min) : NaN))
+}
+
+/** A result without words, for example "92.5%", "18% negative", "Billing 42%" or "Mean 0.71". */
+function headline(row: EvaluationResultApi, value: number): string {
+ if (!Number.isFinite(value)) {
+ return '-'
+ }
+ switch (row.summary.kind) {
+ case 'pass_rate':
+ return formatPercent(value)
+ case 'score':
+ return `Mean ${value.toFixed(2)}`
+ case 'sentiment':
+ return `${Math.round(value)}% negative`
+ case 'categories':
+ return `${trackedCategory(row)?.label} ${Math.round(value)}%`
+ }
+}
+
+/** Short result for lists and legends. Scores show their mean, the rest their share. */
+export function compactHeadline(row: EvaluationResultApi): string {
+ return headline(row, row.summary.kind === 'score' ? (row.summary.score?.mean ?? NaN) : percentValue(row))
+}
+
+/** One bucket's result without words, for the compact compare tooltip. */
+export function bucketHeadline(row: EvaluationResultApi, index: number): string | null {
+ const value = row.trend.values[index]
+ return value == null ? null : headline(row, value)
+}
+
+/** What one bucket means for this row, for tooltips, for example "82.1% passed, 140 graded". */
+export function describeBucket(row: EvaluationResultApi, index: number): string {
+ const value = row.trend.values[index]
+ if (value == null) {
+ return 'No graded results'
+ }
+ const { kind } = row.summary
+ const result =
+ kind === 'pass_rate'
+ ? `${formatPercent(value)} passed`
+ : kind === 'categories'
+ ? `${trackedCategory(row)?.label} on ${Math.round(value)}%`
+ : headline(row, value)
+ return `${result}, ${row.trend.volume[index] ?? 0} ${kind === 'pass_rate' || kind === 'score' ? 'graded' : 'classified'}`
+}
+
+/** The day of the latest graded run in the project's timezone, which the chart's buckets also use. */
+export function lastResultDay(row: EvaluationResultApi, timezone: string): string | null {
+ return row.lastRunAt ? dayjs(row.lastRunAt).tz(timezone).format('MMM D') : null
+}
+
+export function describeAttention(row: EvaluationResultApi, timezone: string): string | null {
+ const [reason] = row.attentionReasons
+ switch (reason) {
+ case 'errored':
+ return statusReasonLabel(row.statusReason as EvaluationStatusReason | null)
+ case 'silent': {
+ // The read starts at the previous period, so a missing last run means nothing in that window, not never.
+ const day = lastResultDay(row, timezone)
+ return day ? `Enabled, but no results since ${day}` : 'Enabled, but no results in this range'
+ }
+ case 'worse': {
+ const rate = percentValue(row)
+ const change = row.change?.value ?? NaN
+ return row.summary.kind === 'sentiment'
+ ? `Negative share rose ${Math.abs(change).toFixed(1)} pp to ${Math.round(rate)}%`
+ : `Fell ${Math.abs(change).toFixed(1)} pp, from ${formatPercent(rate - change)} to ${formatPercent(rate)}`
+ }
+ default:
+ return null
+ }
+}
+
+export const ATTENTION_LABELS: Record<AttentionReasonsEnumApi, string> = {
+ errored: 'Errored',
+ silent: 'No recent results',
+ worse: 'Worse than before',
+}
+
+const METHOD_LABELS: Record<string, string> = {
+ llm_judge: 'LLM judge',
+ hog: 'Hog',
+ sentiment: 'Sentiment',
+}
+
+export function methodLabel(row: EvaluationResultApi): string {
+ return METHOD_LABELS[row.evaluationType] ?? row.evaluationType
+}
+
+export function outputTypeLabel(row: EvaluationResultApi): string | null {
+ const { summary } = row
+ switch (summary.kind) {
+ case 'pass_rate':
+ return row.outputType === 'numeric'
+ ? 'Numeric'
+ : row.outputType === 'categorical'
+ ? 'Categorical'
+ : 'Boolean'
+ case 'score':
+ return 'Numeric'
+ case 'categories':
+ return summary.multiple ? 'Multiple labels' : 'Single label'
+ case 'sentiment':
+ return null
+ }
+}
+
+/** The result in words, for the table, for example "92.5% passed" or "Billing 42% · Bug report 33%". */
+export function resultHeadline(row: EvaluationResultApi): string {
+ const { summary } = row
+ switch (summary.kind) {
+ case 'pass_rate':
+ return `${formatPercent(passRate(row))} passed`
+ case 'score':
+ return summary.score
+ ? `Mean ${summary.score.mean.toFixed(2)}${summary.score.scale ? ` on ${summary.score.scale.min}-${summary.score.scale.max}` : ''}`
+ : '-'
+ case 'categories':
+ return summary.categories
+ .slice(0, 2)
+ .map((category) => `${category.label} ${Math.round(share(category.count, row.gradedCount))}%`)
+ .join(' · ')
+ case 'sentiment':
+ return compactHeadline(row)
+ }
+}
+
+export function resultEvidence(row: EvaluationResultApi): string {
+ const { summary } = row
+ const parts =
+ summary.kind === 'pass_rate'
+ ? [`${humanFriendlyNumber(summary.passed)} / ${humanFriendlyNumber(row.gradedCount)} graded`]
+ : [`${humanFriendlyNumber(row.gradedCount)} ${summary.kind === 'score' ? 'graded' : 'classified'}`]
+ if (row.notApplicableCount > 0) {
+ parts.push(`${humanFriendlyNumber(row.notApplicableCount)} N/A`)
+ }
+ return parts.join(' · ')
+}
+
+/** Whether the row has at least one day the compare chart can draw. */
+export function isChartable(row: EvaluationResultApi): boolean {
+ return row.gradedCount > 0 && percentTrend(row).some(Number.isFinite)
+}
+
+/** Hourly axes label every third hour, so midnight always gets a tick. */
+const HOUR_TICK_STEP = 3
+
+/**
+ * Axis ticks for hourly buckets: the time every few hours, and the date at midnight so a range across two days
+ * says where the second one starts. Read from the bucket text, which carries the project's offset.
+ */
+export function hourTick(label: string): string | null {
+ const hour = Number(label.slice(11, 13))
+ if (hour % HOUR_TICK_STEP !== 0) {
+ return null
+ }
+ return hour === 0 ? dayjs(label.slice(0, 10)).format('MMM D') : label.slice(11, 16)
+}
diff --git a/products/ai_observability/frontend/evaluations/overview/evaluationResultDrawerLogic.ts b/products/ai_observability/frontend/evaluations/overview/evaluationResultDrawerLogic.ts
new file mode 100644
index 000000000000..d6ea3a3ecf2e
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/evaluationResultDrawerLogic.ts
@@ -0,0 +1,270 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { evaluationsRunsRetrieve, evaluationsScoreDistributionRetrieve } from '../../generated/api'
+import type {
+ EvaluationResultApi,
+ EvaluationRunApi,
+ EvaluationsOverviewApi,
+ ScoreHistogramApi,
+} from '../../generated/api.schemas'
+import {
+ type OverviewFailure,
+ type OverviewRequest,
+ evaluationsOverviewLogic,
+ failureOf,
+} from './evaluationsOverviewLogic'
+
+/** How long the pointer rests on a row name before its details are read. */
+const PREFETCH_DELAY_MS = 75
+const RECENT_FAILURES_LIMIT = 5
+
+/** Each part is null when the evaluation has none: failures need a passing rule, the histogram a score scale. */
+export interface EvaluationDetails {
+ recentFailures: EvaluationRunApi[] | null
+ scoreDistribution: ScoreHistogramApi | null
+}
+
+export type DetailsTrigger = 'open' | 'prefetch'
+export type DetailsLoad =
+ | { status: 'loading' }
+ | { status: 'ready'; details: EvaluationDetails }
+ | { status: 'error'; failure: OverviewFailure }
+
+function detailsKey(evaluationId: string, request: OverviewRequest): string {
+ return `${evaluationId}/${request.params.date_from}/${request.params.date_to}`
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface evaluationResultDrawerLogicValues {
+ currentTeamId: number | null // evaluationsOverviewLogic
+ request: OverviewRequest // evaluationsOverviewLogic
+ rowsById: Map<string, EvaluationResultApi> // evaluationsOverviewLogic
+ details: Record<string, DetailsLoad>
+ openDetails: DetailsLoad | null
+ openEvaluationId: string | null
+ openRow: EvaluationResultApi | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface evaluationResultDrawerLogicActions {
+ loadOverviewSuccess: (
+ overview: EvaluationsOverviewApi | null,
+ payload?: void | undefined
+ ) => {
+ overview: EvaluationsOverviewApi | null
+ payload?: void | undefined
+ } // evaluationsOverviewLogic
+ reloadOverview: () => {
+ value: true
+ } // evaluationsOverviewLogic
+ closeDrawer: () => {
+ value: true
+ }
+ detailsLoaded: (
+ key: string,
+ load: DetailsLoad
+ ) => {
+ key: string
+ load: DetailsLoad
+ }
+ detailsRequested: (
+ key: string,
+ evaluationId: string
+ ) => {
+ evaluationId: string
+ key: string
+ }
+ loadDetails: (
+ evaluationId: string,
+ trigger: DetailsTrigger
+ ) => {
+ evaluationId: string
+ trigger: DetailsTrigger
+ }
+ openDrawer: (evaluationId: string) => {
+ evaluationId: string
+ }
+ prefetchDetails: (evaluationId: string) => {
+ evaluationId: string
+ }
+ resetDetails: () => {
+ value: true
+ }
+ trackEmptyStateAction: (
+ action: string,
+ state: string
+ ) => {
+ action: string
+ state: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface evaluationResultDrawerLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ openRow: (
+ openEvaluationId: string | null,
+ rowsById: Map<string, EvaluationResultApi>
+ ) => EvaluationResultApi | null
+ openDetails: (
+ openEvaluationId: string | null,
+ details: Record<string, DetailsLoad>,
+ request: OverviewRequest
+ ) => DetailsLoad | null
+ }
+}
+
+export type evaluationResultDrawerLogicType = MakeLogicType<
+ evaluationResultDrawerLogicValues,
+ evaluationResultDrawerLogicActions,
+ Record<string, any>,
+ evaluationResultDrawerLogicMeta
+>
+
+export const evaluationResultDrawerLogic = kea<evaluationResultDrawerLogicType>([
+ path(['products', 'ai_observability', 'frontend', 'evaluations', 'overview', 'evaluationResultDrawerLogic']),
+ connect(() => ({
+ values: [evaluationsOverviewLogic, ['request', 'currentTeamId', 'rowsById']],
+ actions: [evaluationsOverviewLogic, ['loadOverviewSuccess', 'reloadOverview']],
+ })),
+ actions({
+ openDrawer: (evaluationId: string) => ({ evaluationId }),
+ closeDrawer: true,
+ trackEmptyStateAction: (action: string, state: string) => ({ action, state }),
+ prefetchDetails: (evaluationId: string) => ({ evaluationId }),
+ loadDetails: (evaluationId: string, trigger: DetailsTrigger) => ({ evaluationId, trigger }),
+ detailsRequested: (key: string, evaluationId: string) => ({ key, evaluationId }),
+ detailsLoaded: (key: string, load: DetailsLoad) => ({ key, load }),
+ resetDetails: true,
+ }),
+ reducers({
+ openEvaluationId: [
+ null as string | null,
+ {
+ openDrawer: (_, { evaluationId }) => evaluationId,
+ closeDrawer: () => null,
+ },
+ ],
+ // Keyed by evaluation and period, so reopening a drawer for the same range shows it at once.
+ details: [
+ {} as Record<string, DetailsLoad>,
+ {
+ detailsRequested: (state, { key }) => ({ ...state, [key]: { status: 'loading' } }),
+ detailsLoaded: (state, { key, load }) => ({ ...state, [key]: load }),
+ resetDetails: () => ({}),
+ },
+ ],
+ }),
+ selectors({
+ openRow: [
+ (s) => [s.openEvaluationId, s.rowsById],
+ (openEvaluationId: string | null, rowsById: Map<string, EvaluationResultApi>): EvaluationResultApi | null =>
+ (openEvaluationId && rowsById.get(openEvaluationId)) || null,
+ ],
+ openDetails: [
+ (s) => [s.openEvaluationId, s.details, s.request],
+ (
+ openEvaluationId: string | null,
+ details: Record<string, DetailsLoad>,
+ request: OverviewRequest
+ ): DetailsLoad | null =>
+ openEvaluationId ? (details[detailsKey(openEvaluationId, request)] ?? null) : null,
+ ],
+ }),
+ // pinned: every analytics event name and property in these listeners, because renaming one breaks dashboards.
+ listeners(({ actions, values, cache }) => ({
+ // A new period or scope can arrive while the drawer stays open, for example through browser Back. Its rows
+ // are current only once the overview loads, which the graded check in `loadDetails` needs.
+ loadOverviewSuccess: () => {
+ if (values.openEvaluationId) {
+ actions.loadDetails(values.openEvaluationId, 'open')
+ }
+ },
+ // A refresh keeps the period, so the key alone would keep showing details from before it.
+ reloadOverview: () => {
+ // The backend caches details for a few minutes, so a period read before the refresh skips that cache next.
+ cache.refreshKeys = new Set([...(cache.refreshKeys ?? []), ...Object.keys(values.details)])
+ // A read still in flight started before the refresh, so its response must not land as current.
+ cache.generation = (cache.generation ?? 0) + 1
+ actions.resetDetails()
+ },
+ trackEmptyStateAction: ({ action, state }) => {
+ posthog.capture('llma evaluation overview drawer empty action', { action, state })
+ },
+ openDrawer: ({ evaluationId }) => {
+ const row = values.rowsById.get(evaluationId)
+ posthog.capture('llma evaluation overview drawer opened', {
+ summary_kind: row?.summary.kind,
+ prefetched: values.details[detailsKey(evaluationId, values.request)]?.status === 'ready',
+ })
+ actions.loadDetails(evaluationId, 'open')
+ },
+ prefetchDetails: async ({ evaluationId }, breakpoint) => {
+ // A pointer crossing the table on its way elsewhere moves on before this, and the next row cancels it.
+ await breakpoint(PREFETCH_DELAY_MS)
+ actions.loadDetails(evaluationId, 'prefetch')
+ },
+ loadDetails: ({ evaluationId, trigger }) => {
+ const key = detailsKey(evaluationId, values.request)
+ const current = values.details[key]
+ // A failed read retries only when someone opens the drawer.
+ if (current && (current.status !== 'error' || trigger === 'prefetch')) {
+ return
+ }
+ // Without its row, for example after a failed refresh, the read would not know which endpoints apply. The next
+ // overview that lands loads the open drawer again. Nothing graded shows a notice that needs no details.
+ const row = values.rowsById.get(evaluationId)
+ if (!row || row.gradedCount === 0) {
+ return
+ }
+ if (trigger === 'prefetch') {
+ // Each read holds one of the organization's query slots, so a sweep down the table must not start
+ // one read per row it crosses.
+ if (cache.prefetchingKey) {
+ return
+ }
+ cache.prefetchingKey = key
+ }
+ actions.detailsRequested(key, evaluationId)
+ },
+ detailsRequested: async ({ key, evaluationId }) => {
+ const { date_from, date_to } = values.request.params
+ const refresh = cache.refreshKeys?.has(key) === true
+ const generation = cache.generation ?? 0
+ const projectId = String(values.currentTeamId)
+ const params = { date_from, date_to, ...(refresh ? { refresh: true } : {}) }
+ // Each endpoint rejects an evaluation it does not apply to, so the row decides which ones to read.
+ const summary = values.rowsById.get(evaluationId)?.summary
+ const scale = summary && 'score' in summary ? summary.score?.scale : null
+ const load = await Promise.all([
+ summary?.kind === 'pass_rate'
+ ? evaluationsRunsRetrieve(projectId, evaluationId, {
+ ...params,
+ outcome: 'failed',
+ limit: RECENT_FAILURES_LIMIT,
+ }).then((runs) => runs.results)
+ : null,
+ scale && scale.min < scale.max
+ ? evaluationsScoreDistributionRetrieve(projectId, evaluationId, params)
+ : null,
+ ]).then(
+ ([recentFailures, scoreDistribution]): DetailsLoad => ({
+ status: 'ready',
+ details: { recentFailures, scoreDistribution },
+ }),
+ (error: unknown): DetailsLoad => ({ status: 'error', failure: failureOf(error) })
+ )
+ if (cache.prefetchingKey === key) {
+ cache.prefetchingKey = null
+ }
+ if (generation === (cache.generation ?? 0)) {
+ // A failed read keeps the key, so the retry skips the cache too.
+ if (load.status === 'ready') {
+ cache.refreshKeys?.delete(key)
+ }
+ actions.detailsLoaded(key, load)
+ }
+ },
+ })),
+])
diff --git a/products/ai_observability/frontend/evaluations/overview/evaluationsOverviewLogic.test.ts b/products/ai_observability/frontend/evaluations/overview/evaluationsOverviewLogic.test.ts
new file mode 100644
index 000000000000..a2306a5dbcb0
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/evaluationsOverviewLogic.test.ts
@@ -0,0 +1,676 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { dayjs } from 'lib/dayjs'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type { EvaluationApi, EvaluationResultApi } from '../../generated/api.schemas'
+import { llmEvaluationsLogic } from '../llmEvaluationsLogic'
+import { evaluationResultDrawerLogic } from './evaluationResultDrawerLogic'
+import {
+ evaluationsOverviewLogic,
+ markEvaluationsOverviewStale,
+ resetEvaluationsOverviewStale,
+} from './evaluationsOverviewLogic'
+
+const EMPTY_OVERVIEW = {
+ start: '2026-10-01T00:00:00+00:00',
+ end: '2026-10-15T00:00:00+00:00',
+ previousStart: '2026-09-17T00:00:00+00:00',
+ previousEnd: '2026-10-01T00:00:00+00:00',
+ interval: 'day',
+ buckets: [],
+ evaluations: [],
+ totals: { graded: 0, gradedComparison: null, gradedTrend: [], sentiment: null },
+ passRateOverview: {
+ entries: [],
+ median: null,
+ medianComparison: null,
+ medianTrend: [],
+ },
+}
+
+const evaluation = (id: string, directoryId: string | null): Partial<EvaluationApi> => ({
+ id,
+ name: `Evaluation ${id}`,
+ directory_id: directoryId,
+ enabled: true,
+ status: 'active',
+ status_reason: null,
+ status_reason_detail: null,
+ evaluation_type: 'llm_judge',
+ evaluation_config: { prompt: 'Prompt' },
+ output_type: 'boolean',
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+})
+
+const row = (id: string, outputType: string, summary: EvaluationResultApi['summary']): EvaluationResultApi => ({
+ id,
+ name: `Evaluation ${id}`,
+ directoryName: null,
+ evaluationType: 'llm_judge',
+ outputType,
+ enabled: true,
+ statusReason: null,
+ createdBy: null,
+ gradedCount: 10,
+ previousGradedCount: null,
+ notApplicableCount: 0,
+ skippedCount: 0,
+ lastRunAt: null,
+ summary,
+ trend: { values: [], volume: [] },
+ change: null,
+ lowEvidence: false,
+ attentionReasons: [],
+ bucketStatus: [],
+ trackedCategory: null,
+})
+
+const SCALE = { min: 0, max: 10 }
+const ROWS = [
+ row('eval-a', 'boolean', { kind: 'pass_rate', passed: 8, failed: 2, previous: null, score: null }),
+ row('eval-b', 'numeric', {
+ kind: 'pass_rate',
+ passed: 8,
+ failed: 2,
+ previous: null,
+ score: { mean: 7, scale: SCALE },
+ }),
+ row('eval-c', 'numeric', { kind: 'score', score: { mean: 7, scale: SCALE }, previousMean: null }),
+ row('eval-d', 'numeric', { kind: 'score', score: { mean: 7, scale: null }, previousMean: null }),
+ row('eval-e', 'categorical', { kind: 'categories', multiple: false, categories: [], noCategoriesCount: 0 }),
+]
+const PASS_RATE = { kind: 'pass_rate', passed: 40, failed: 10, previous: null, score: null } as const
+const SENTIMENT = { kind: 'sentiment', positive: 10, neutral: 10, negative: 30, previousNegativeShare: 40 } as const
+const attentionRow = (
+ id: string,
+ reason: EvaluationResultApi['attentionReasons'][number] | null,
+ summary: EvaluationResultApi['summary'],
+ change: number | null
+): EvaluationResultApi => ({
+ ...row(id, 'boolean', summary),
+ gradedCount: reason === 'errored' || reason === 'silent' ? 0 : 50,
+ trend: { values: [50], volume: [50] },
+ change: change === null ? null : { value: change, unit: 'pp', subject: null },
+ attentionReasons: reason ? [reason] : [],
+})
+// A falling pass rate and a rising negative share are both worse, so the sentiment row is the worst regression.
+const ATTENTION_ROWS = [
+ attentionRow('healthy', null, PASS_RATE, 1),
+ attentionRow('silent', 'silent', PASS_RATE, null),
+ attentionRow('worse-5', 'worse', PASS_RATE, -5),
+ attentionRow('worse-sentiment', 'worse', SENTIMENT, 20),
+ attentionRow('worse-12', 'worse', PASS_RATE, -12),
+ attentionRow('worse-8', 'worse', PASS_RATE, -8),
+ attentionRow('errored', 'errored', PASS_RATE, null),
+]
+
+const HISTOGRAM = { scale: SCALE, buckets: [{ label: '7', count: 10 }] }
+
+const PERIOD = 'date_from=2026-10-01&date_to=2026-10-14'
+
+/** The clock the tests read. Only Date is faked, so kea breakpoints and network mocks keep real timers. */
+const NOW = '2026-10-22T10:30:15Z'
+
+/** A rolling range in hours as the request sends it: exact instants up to the current minute. */
+function lastHours(hours: number): string {
+ const end = dayjs.utc(NOW).startOf('minute')
+ const instant = (value: dayjs.Dayjs): string => value.format('YYYY-MM-DDTHH:mm:ss[Z]')
+ return `date_from=${instant(end.subtract(hours, 'hour'))}&date_to=${instant(end)}`
+}
+
+/** A details read as `<endpoint> <id> <query>`, without the period every read sends. */
+function detailRequest(endpoint: string, id: string, url: string): string {
+ const params = new URL(url).searchParams
+ params.delete('date_from')
+ params.delete('date_to')
+ return `${endpoint} ${id} ${params.toString()}`.trim()
+}
+
+const FAILURES_QUERY = 'outcome=failed&limit=5'
+
+describe('evaluationsOverviewLogic', () => {
+ let requests: URLSearchParams[]
+ /** Statuses the next overview reads fail with, one per read. */
+ let overviewFailures: number[]
+ let detailRequests: string[]
+ let logic: ReturnType<typeof evaluationsOverviewLogic.build>
+
+ beforeEach(async () => {
+ resetEvaluationsOverviewStale()
+ jest.useFakeTimers({
+ now: new Date(NOW),
+ doNotFake: [
+ 'hrtime',
+ 'nextTick',
+ 'performance',
+ 'queueMicrotask',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'requestIdleCallback',
+ 'cancelIdleCallback',
+ 'setImmediate',
+ 'clearImmediate',
+ 'setInterval',
+ 'clearInterval',
+ 'setTimeout',
+ 'clearTimeout',
+ ],
+ })
+ requests = []
+ overviewFailures = []
+ detailRequests = []
+ useMocks({
+ get: {
+ '/api/environments/:teamId/llm_analytics/provider_keys/': { results: [] },
+ '/api/projects/:teamId/evaluations/': {
+ count: 3,
+ next: null,
+ results: [evaluation('eval-a', null), evaluation('eval-b', 'dir-1'), evaluation('eval-c', 'dir-1')],
+ },
+ '/api/projects/:teamId/evaluation_directories/': [],
+ '/api/projects/:teamId/evaluations/:id/runs/': ({ params, request }) => {
+ detailRequests.push(detailRequest('runs', params.id as string, request.url))
+ return [200, { results: [] }]
+ },
+ '/api/projects/:teamId/evaluations/:id/score_distribution/': ({ params, request }) => {
+ detailRequests.push(detailRequest('score_distribution', params.id as string, request.url))
+ return [200, HISTOGRAM]
+ },
+ '/api/projects/:teamId/evaluations/overview/': ({ request }) => {
+ const params = new URL(request.url).searchParams
+ requests.push(params)
+ const failure = overviewFailures.shift()
+ if (failure) {
+ return [failure, {}]
+ }
+ // The backend buckets a day or two by hour.
+ const oneDay = params.get('date_from') === params.get('date_to')
+ return [200, { ...EMPTY_OVERVIEW, evaluations: ROWS, interval: oneDay ? 'hour' : 'day' }]
+ },
+ },
+ })
+ initKeaTests()
+ llmEvaluationsLogic.mount()
+ llmEvaluationsLogic.actions.setDates('2026-10-01', '2026-10-14')
+ logic = evaluationsOverviewLogic()
+ logic.mount()
+ await expectLogic(llmEvaluationsLogic).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
+ requests = []
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ test.each([
+ {
+ name: 'scope change sends the picked evaluations',
+ act: () => logic.actions.setPickedIds(['eval-a']),
+ expected: [`${PERIOD}&evaluation_ids=eval-a`],
+ },
+ {
+ name: 'several scope picks in a row read once',
+ act: () => {
+ logic.actions.setPickedIds(['eval-a'])
+ logic.actions.setPickedIds(['eval-a', 'eval-b'])
+ },
+ expected: [`${PERIOD}&evaluation_ids=eval-a,eval-b`],
+ },
+ {
+ name: 'date change sends the new period',
+ act: () => llmEvaluationsLogic.actions.setDates('2026-09-01', '2026-09-30'),
+ expected: ['date_from=2026-09-01&date_to=2026-09-30'],
+ },
+ {
+ name: 'last 7 days sends the 7 whole days ending today',
+ act: () => llmEvaluationsLogic.actions.setDates('-7d', null),
+ expected: ['date_from=2026-10-16&date_to=2026-10-22'],
+ },
+ {
+ name: 'last 2 weeks sends the 14 whole days ending today',
+ act: () => llmEvaluationsLogic.actions.setDates('-2w', null),
+ expected: ['date_from=2026-10-09&date_to=2026-10-22'],
+ },
+ {
+ name: 'last 90 days fits the backend limit',
+ act: () => llmEvaluationsLogic.actions.setDates('-90d', null),
+ expected: ['date_from=2026-07-25&date_to=2026-10-22'],
+ },
+ {
+ // Clocks fall back on November 1, so these 90 days are 2161 hours long.
+ name: '90 days across a daylight saving change fit the backend limit',
+ act: () => {
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...teamLogic.values.currentTeam!,
+ timezone: 'America/New_York',
+ })
+ llmEvaluationsLogic.actions.setDates('2026-08-05', '2026-11-02')
+ },
+ expected: ['date_from=2026-08-05&date_to=2026-11-02'],
+ },
+ {
+ name: 'last 24 hours sends exact instants',
+ act: () => llmEvaluationsLogic.actions.setDates('-24h', null),
+ expected: [lastHours(24)],
+ },
+ {
+ name: 'exact instants an evaluation links back with stay exact',
+ act: () => llmEvaluationsLogic.actions.setDates('2026-10-21T10:30:00Z', '2026-10-22T10:30:00Z'),
+ expected: [lastHours(24)],
+ },
+ {
+ name: 'this month sends whole days from its first day',
+ act: () => llmEvaluationsLogic.actions.setDates('mStart', null),
+ expected: ['date_from=2026-10-01&date_to=2026-10-22'],
+ },
+ {
+ name: 'yesterday sends that whole day',
+ act: () => llmEvaluationsLogic.actions.setDates('-1dStart', '-1dEnd'),
+ expected: ['date_from=2026-10-21&date_to=2026-10-21'],
+ },
+ {
+ name: 'last week starts on the first day of the project week',
+ act: () => {
+ teamLogic.actions.loadCurrentTeamSuccess({ ...teamLogic.values.currentTeam!, week_start_day: 1 })
+ llmEvaluationsLogic.actions.setDates('-1wStart', '-1wEnd')
+ },
+ expected: ['date_from=2026-10-12&date_to=2026-10-18'],
+ },
+ {
+ name: 'a period the backend refuses is not requested',
+ act: () => llmEvaluationsLogic.actions.setDates('2026-01-01', '2026-09-30'),
+ expected: [],
+ },
+ {
+ name: 'opening a directory sends only its evaluations',
+ act: () => llmEvaluationsLogic.actions.selectDirectory('dir-1'),
+ expected: [`${PERIOD}&evaluation_ids=eval-b,eval-c`],
+ },
+ {
+ name: 'a pick inside a directory narrows it',
+ act: () => {
+ llmEvaluationsLogic.actions.selectDirectory('dir-1')
+ logic.actions.setPickedIds(['eval-c'])
+ },
+ expected: [`${PERIOD}&evaluation_ids=eval-b,eval-c`, `${PERIOD}&evaluation_ids=eval-c`],
+ },
+ {
+ name: 'several edits in a row reload once past the cache',
+ act: () => {
+ llmEvaluationsLogic.actions.moveEvaluationSuccess('eval-a', 'dir-1')
+ llmEvaluationsLogic.actions.toggleEvaluationEnabledSuccess('eval-b')
+ },
+ expected: [`${PERIOD}&refresh=true`],
+ },
+ {
+ name: 'a change inside a directory skips the cache for all evaluations too',
+ act: async () => {
+ llmEvaluationsLogic.actions.selectDirectory('dir-1')
+ await expectLogic(logic).toFinishAllListeners()
+ llmEvaluationsLogic.actions.toggleEvaluationEnabledSuccess('eval-b')
+ await expectLogic(logic).toFinishAllListeners()
+ llmEvaluationsLogic.actions.selectDirectory(null)
+ },
+ expected: [
+ `${PERIOD}&evaluation_ids=eval-b,eval-c`,
+ `${PERIOD}&evaluation_ids=eval-b,eval-c&refresh=true`,
+ `${PERIOD}&refresh=true`,
+ ],
+ },
+ {
+ name: 'undo reloads past the cache',
+ act: () => llmEvaluationsLogic.actions.restoreEvaluationSuccess(evaluation('eval-d', null) as any),
+ expected: [`${PERIOD}&refresh=true`],
+ },
+ {
+ name: 'reload skips the cache',
+ act: () => logic.actions.reloadOverview(),
+ expected: [`${PERIOD}&refresh=true`],
+ },
+ {
+ name: 'a retry after a failed reload still skips the cache',
+ act: async () => {
+ overviewFailures = [429]
+ logic.actions.reloadOverview()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.retryOverview()
+ },
+ expected: [`${PERIOD}&refresh=true`, `${PERIOD}&refresh=true`],
+ },
+ {
+ name: 'returning after a save in the editor skips the cache',
+ act: () => {
+ logic.unmount()
+ markEvaluationsOverviewStale()
+ logic.mount()
+ },
+ expected: [`${PERIOD}&refresh=true`],
+ },
+ {
+ name: 'after a save in the editor, a retry after a failed read still skips the cache',
+ act: async () => {
+ logic.unmount()
+ markEvaluationsOverviewStale()
+ overviewFailures = [500]
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.retryOverview()
+ },
+ expected: [`${PERIOD}&refresh=true`, `${PERIOD}&refresh=true`],
+ },
+ {
+ name: 'after a save in a directory, leaving the directory skips the cache too',
+ act: () => {
+ llmEvaluationsLogic.actions.selectDirectory('dir-1')
+ logic.unmount()
+ markEvaluationsOverviewStale()
+ logic.mount()
+ llmEvaluationsLogic.actions.selectDirectory(null)
+ },
+ expected: [
+ `${PERIOD}&evaluation_ids=eval-b,eval-c`,
+ `${PERIOD}&evaluation_ids=eval-b,eval-c&refresh=true`,
+ `${PERIOD}&refresh=true`,
+ ],
+ },
+ {
+ name: 'browser back from a directory drops the picks made in it',
+ act: () => {
+ llmEvaluationsLogic.actions.selectDirectory('dir-1')
+ logic.actions.setPickedIds(['eval-c'])
+ router.actions.push(router.values.location.pathname, {
+ ...router.values.searchParams,
+ directory: undefined,
+ })
+ },
+ expected: [`${PERIOD}&evaluation_ids=eval-b,eval-c`, PERIOD],
+ },
+ ])('$name', async ({ act, expected }) => {
+ await act()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(requests.map((params) => decodeURIComponent(params.toString()))).toEqual(expected)
+ })
+
+ it('reads an evaluation once when the pointer rests on its name twice', async () => {
+ const drawerLogic = evaluationResultDrawerLogic()
+ drawerLogic.mount()
+
+ drawerLogic.actions.prefetchDetails('eval-b')
+ await expectLogic(drawerLogic).toFinishAllListeners()
+ drawerLogic.actions.prefetchDetails('eval-b')
+ await expectLogic(drawerLogic).toFinishAllListeners()
+
+ expect(detailRequests).toEqual([`runs eval-b ${FAILURES_QUERY}`, 'score_distribution eval-b'])
+ expect(drawerLogic.values.details).toMatchObject({
+ 'eval-b/2026-10-01/2026-10-14': { status: 'ready' },
+ })
+ })
+
+ it('loads the open drawer again when the period changes under it', async () => {
+ const drawerLogic = evaluationResultDrawerLogic()
+ drawerLogic.mount()
+ drawerLogic.actions.openDrawer('eval-b')
+ await expectLogic(drawerLogic).toFinishAllListeners()
+
+ llmEvaluationsLogic.actions.setDates('2026-09-01', '2026-09-30')
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(drawerLogic).toFinishAllListeners()
+
+ expect(detailRequests).toEqual([
+ `runs eval-b ${FAILURES_QUERY}`,
+ 'score_distribution eval-b',
+ `runs eval-b ${FAILURES_QUERY}`,
+ 'score_distribution eval-b',
+ ])
+ expect(drawerLogic.values.openDetails).toMatchObject({ status: 'ready' })
+ })
+
+ test.each([
+ { dateFrom: '-14d', dateTo: null, expected: '"date_from":"2026-10-09","date_to":"2026-10-22"' },
+ // Hourly buckets read a date-only end as midnight, which would drop the whole day.
+ {
+ dateFrom: '-1dStart',
+ dateTo: '-1dEnd',
+ expected: '"date_from":"2026-10-21","date_to":"2026-10-21T23:59:59"',
+ },
+ ])(
+ 'opens the same period in Explore as the overview shows from $dateFrom',
+ async ({ dateFrom, dateTo, expected }) => {
+ llmEvaluationsLogic.actions.setDates(dateFrom, dateTo)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(decodeURIComponent(logic.values.exploreUrl ?? '')).toContain(expected)
+ }
+ )
+
+ it('reloads an open directory after the list it waits for comes back', async () => {
+ llmEvaluationsLogic.actions.selectDirectory('dir-1')
+ await expectLogic(logic).toFinishAllListeners()
+ requests = []
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ capture.mockClear()
+
+ // The header Refresh reloads the list first, so the directory's evaluations are briefly unknown.
+ llmEvaluationsLogic.actions.loadEvaluations()
+ logic.actions.reloadOverview()
+ await expectLogic(llmEvaluationsLogic).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(requests.map((params) => decodeURIComponent(params.toString()))).toEqual([
+ `${PERIOD}&evaluation_ids=eval-b,eval-c&refresh=true`,
+ ])
+ expect(logic.values.overview).not.toBeNull()
+ expect(capture.mock.calls.filter(([event]) => event === 'llma evaluation overview loaded')).toHaveLength(1)
+ })
+
+ const DIRECTORY_RELOAD = `${PERIOD}&evaluation_ids=eval-b,eval-c&refresh=true`
+ test.each([
+ {
+ name: 'an open directory waits for fails to reload',
+ directory: 'dir-1',
+ listFirst: true,
+ failedReads: [],
+ retriedReads: [DIRECTORY_RELOAD],
+ },
+ {
+ name: 'an open directory waits for fails on the first load',
+ directory: 'dir-1',
+ listFirst: false,
+ failedReads: [],
+ retriedReads: [DIRECTORY_RELOAD],
+ },
+ // The results still load, so only the list loads again.
+ {
+ name: 'fails at the top level',
+ directory: null,
+ listFirst: true,
+ failedReads: [`${PERIOD}&refresh=true`],
+ retriedReads: [],
+ },
+ ])('offers a retry when the list $name', async ({ directory, listFirst, failedReads, retriedReads }) => {
+ llmEvaluationsLogic.actions.selectDirectory(directory)
+ await expectLogic(logic).toFinishAllListeners()
+ if (!listFirst) {
+ llmEvaluationsLogic.actions.loadEvaluationsSuccess([])
+ }
+ useMocks({ get: { '/api/projects/:teamId/evaluations/': () => [500, {}] } })
+ requests = []
+
+ llmEvaluationsLogic.actions.loadEvaluations()
+ logic.actions.reloadOverview()
+ await expectLogic(llmEvaluationsLogic).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(requests.map((params) => decodeURIComponent(params.toString()))).toEqual(failedReads)
+ expect(logic.values.request.notice).toBeNull()
+ expect([logic.values.overviewFailure, logic.values.evaluationListFailed]).toEqual(
+ directory ? ['failed', false] : [null, true]
+ )
+ requests = []
+
+ useMocks({
+ get: {
+ '/api/projects/:teamId/evaluations/': {
+ count: 2,
+ next: null,
+ results: [evaluation('eval-b', 'dir-1'), evaluation('eval-c', 'dir-1')],
+ },
+ },
+ })
+ logic.actions.retryOverview()
+ await expectLogic(llmEvaluationsLogic).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(requests.map((params) => decodeURIComponent(params.toString()))).toEqual(retriedReads)
+ expect(logic.values.evaluationListFailed).toBe(false)
+ expect([...logic.values.configById.keys()]).toEqual(['eval-b', 'eval-c'])
+ })
+
+ test.each([
+ {
+ selector: 'tableRows' as const,
+ expected: ['errored', 'worse-sentiment', 'worse-12', 'worse-8', 'worse-5', 'silent', 'healthy'],
+ },
+ { selector: 'chartedIds' as const, expected: ['worse-sentiment', 'worse-12', 'worse-8'] },
+ ])('puts the worst regression first in $selector', async ({ selector, expected }) => {
+ useMocks({
+ get: {
+ '/api/projects/:teamId/evaluations/overview/': () => [
+ 200,
+ { ...EMPTY_OVERVIEW, buckets: ['2026-10-01'], evaluations: ATTENTION_ROWS },
+ ],
+ },
+ })
+ logic.actions.reloadOverview()
+ await expectLogic(logic).toFinishAllListeners()
+
+ const ids = logic.values[selector].map((item) => (typeof item === 'string' ? item : item.id))
+ expect(ids).toEqual(expected)
+ })
+
+ // The evaluation page reads "-7d" as 8 days, so links send the days the overview counted.
+ test.each([
+ { dateFrom: '-7d', expected: 'date_from=2026-10-16&date_to=2026-10-22' },
+ { dateFrom: '-24h', expected: lastHours(24) },
+ ])('links to an evaluation with the period the overview shows for $dateFrom', async ({ dateFrom, expected }) => {
+ llmEvaluationsLogic.actions.selectDirectory('dir-1')
+ llmEvaluationsLogic.actions.setDates(dateFrom, null)
+ await expectLogic(logic).toFinishAllListeners()
+
+ const url = logic.values.evaluationUrl('eval-a', { evaluation_tab: 'backfills' })
+ expect(Object.fromEntries(new URLSearchParams(url.split('?')[1]))).toEqual({
+ ...Object.fromEntries(new URLSearchParams(expected)),
+ directory: 'dir-1',
+ evaluation_tab: 'backfills',
+ })
+ })
+
+ it('moves a rolling period up to the present on reload', async () => {
+ llmEvaluationsLogic.actions.setDates('-24h', null)
+ await expectLogic(logic).toFinishAllListeners()
+ jest.setSystemTime(dayjs.utc(NOW).add(10, 'minute').toDate())
+
+ logic.actions.reloadOverview()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(requests.map((params) => params.get('date_to'))).toEqual([
+ '2026-10-22T10:30:00Z',
+ '2026-10-22T10:40:00Z',
+ ])
+ })
+
+ test.each([
+ { name: 'after the first read lands', settleFirst: true, reloadFails: false },
+ { name: 'while the first read is still in flight', settleFirst: false, reloadFails: false },
+ // The failed reload clears the rows, so the drawer must wait for the retry instead of caching empty details.
+ { name: 'once a retry follows a failed reload', settleFirst: true, reloadFails: true },
+ ])('reads the open drawer again past the cache on reload $name', async ({ settleFirst, reloadFails }) => {
+ const drawerLogic = evaluationResultDrawerLogic()
+ drawerLogic.mount()
+ drawerLogic.actions.openDrawer('eval-b')
+ if (settleFirst) {
+ await expectLogic(drawerLogic).toFinishAllListeners()
+ }
+
+ overviewFailures = reloadFails ? [500] : []
+ logic.actions.reloadOverview()
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(drawerLogic).toFinishAllListeners()
+ if (reloadFails) {
+ logic.actions.retryOverview()
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(drawerLogic).toFinishAllListeners()
+ }
+
+ expect(detailRequests).toEqual([
+ `runs eval-b ${FAILURES_QUERY}`,
+ 'score_distribution eval-b',
+ `runs eval-b refresh=true&${FAILURES_QUERY}`,
+ 'score_distribution eval-b refresh=true',
+ ])
+ expect(drawerLogic.values.openDetails).toMatchObject({ status: 'ready' })
+ })
+
+ test.each([
+ {
+ kind: 'boolean pass rate',
+ id: 'eval-a',
+ expected: [`runs eval-a ${FAILURES_QUERY}`],
+ details: { recentFailures: [], scoreDistribution: null },
+ },
+ {
+ kind: 'numeric pass rate',
+ id: 'eval-b',
+ expected: [`runs eval-b ${FAILURES_QUERY}`, 'score_distribution eval-b'],
+ details: { recentFailures: [], scoreDistribution: HISTOGRAM },
+ },
+ {
+ kind: 'score',
+ id: 'eval-c',
+ expected: ['score_distribution eval-c'],
+ details: { recentFailures: null, scoreDistribution: HISTOGRAM },
+ },
+ {
+ kind: 'score without bounds',
+ id: 'eval-d',
+ expected: [],
+ details: { recentFailures: null, scoreDistribution: null },
+ },
+ {
+ kind: 'categorical',
+ id: 'eval-e',
+ expected: [],
+ details: { recentFailures: null, scoreDistribution: null },
+ },
+ ])('reads only the details a $kind evaluation has', async ({ id, expected, details }) => {
+ const drawerLogic = evaluationResultDrawerLogic()
+ drawerLogic.mount()
+
+ drawerLogic.actions.openDrawer(id)
+ await expectLogic(drawerLogic).toFinishAllListeners()
+
+ expect(detailRequests).toEqual(expected)
+ expect(drawerLogic.values.openDetails).toEqual({ status: 'ready', details })
+ })
+
+ it('shows the details as failed when either read fails', async () => {
+ useMocks({ get: { '/api/projects/:teamId/evaluations/:id/score_distribution/': () => [500, {}] } })
+ const drawerLogic = evaluationResultDrawerLogic()
+ drawerLogic.mount()
+
+ drawerLogic.actions.openDrawer('eval-b')
+ await expectLogic(drawerLogic).toFinishAllListeners()
+
+ expect(drawerLogic.values.openDetails).toEqual({ status: 'error', failure: 'failed' })
+ })
+})
diff --git a/products/ai_observability/frontend/evaluations/overview/evaluationsOverviewLogic.ts b/products/ai_observability/frontend/evaluations/overview/evaluationsOverviewLogic.ts
new file mode 100644
index 000000000000..20a436d11038
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/overview/evaluationsOverviewLogic.ts
@@ -0,0 +1,1203 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { combineUrl, router } from 'kea-router'
+import type { LocationChangedPayload } from 'kea-router/lib/types'
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api'
+import { dayjs } from 'lib/dayjs'
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { dateMapping, dateStringToComponents, dateStringToDayJs, startOfWeek } from 'lib/utils/dateFilters'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
+import { AccessControlLevel, AccessControlResourceType, type DateMappingOption } from '~/types'
+
+import { evaluationsOverviewRetrieve } from '../../generated/api'
+import type {
+ AttentionReasonsEnumApi,
+ EvaluationDirectoryApi,
+ EvaluationResultApi,
+ EvaluationsOverviewApi,
+ EvaluationsOverviewRetrieveParams,
+} from '../../generated/api.schemas'
+import { buildEvaluationPassRateTrendsQuery } from '../evaluationMetricsLogic'
+import { llmEvaluationsLogic } from '../llmEvaluationsLogic'
+import type { EvaluationDirectoryEditor } from '../llmEvaluationsLogic'
+import type { EvaluationConfig } from '../types'
+import { type BucketInterval, isChartable, percentValue } from './evaluationOverviewDisplay'
+
+export type OverviewView = 'over_time' | 'by_bucket' | 'ranked'
+export type OverviewMetric = 'pass_rate' | 'graded' | 'sentiment'
+export type OverviewCard = OverviewMetric | 'attention'
+export type AttentionFilter = 'any' | AttentionReasonsEnumApi | null
+export type OverviewFailure = 'rate_limited' | 'failed'
+export type TableAction = 'edit' | 'enable' | 'disable' | 'move' | 'delete'
+export type DirectoryAction = 'rename' | 'delete'
+
+export interface DirectoryTile {
+ directory: EvaluationDirectoryApi
+ evaluationCount: number
+ /** Null until an overview read has covered the directory's evaluations. */
+ needAttentionCount: number | null
+}
+
+/** Several edits in a row, such as a few moves, reload the overview once. */
+const REFRESH_AFTER_CHANGE_MS = 500
+/** Several scope picks in a row, such as ticking a few evaluations, read the overview once. */
+const SCOPE_CHANGE_DEBOUNCE_MS = 300
+
+/** At or below this many evaluations, the page keeps a way to create another in view. */
+const FEW_EVALUATIONS_MAX = 3
+/** The backend rejects a longer period. */
+const OVERVIEW_MAX_DAYS = 90
+/** How many evaluations the chart picks on its first render. People can pick more. */
+const DEFAULT_COMPARED = 3
+/** The anchor the "Needs attention" card scrolls to, right above the evaluations table. */
+export const OVERVIEW_LIST_ANCHOR_ID = 'evaluations-overview-list'
+
+/** A rolling relative start such as "-24h", "-14d" or "-3w", without a Start or End clip. */
+const ROLLING_RANGE = /^-(\d+)([hdwmqy])$/
+const ROLLING_UNITS = { h: 'hour', d: 'day', w: 'week', m: 'month', q: 'quarter', y: 'year' } as const
+/** An exact UTC instant, the format the overview sends an hourly period in. */
+const INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/
+
+/** The date presets the overview can show: everything up to its maximum period. */
+export const OVERVIEW_DATE_OPTIONS: DateMappingOption[] = dateMapping.filter((option) => {
+ const [value = ''] = option.values
+ const days = /^-(\d+)d$/.exec(value)?.[1]
+ return value !== 'all' && !(days && Number(days) > OVERVIEW_MAX_DAYS)
+})
+
+/** How long the backend caches an overview response. */
+const BACKEND_CACHE_MS = 5 * 60 * 1000
+
+/**
+ * When an evaluation last changed, on this page or elsewhere such as a save in the editor. The backend caches each
+ * scope's results and a change does not alter their cache keys, so every scope read within the cache lifetime skips
+ * that cache once, not only the scope on screen.
+ */
+let lastChangeAt: number | null = null
+const refreshedSinceChange = new Set<string>()
+
+function markEveryScopeStale(): void {
+ lastChangeAt = Date.now()
+ refreshedSinceChange.clear()
+}
+
+export function markEvaluationsOverviewStale(): void {
+ markEveryScopeStale()
+ evaluationsOverviewLogic.findMounted()?.actions.reloadOverview()
+}
+
+export function resetEvaluationsOverviewStale(): void {
+ lastChangeAt = null
+ refreshedSinceChange.clear()
+}
+
+function needsRefreshAfterChange(requestKey: string): boolean {
+ if (lastChangeAt === null || Date.now() - lastChangeAt > BACKEND_CACHE_MS) {
+ return false
+ }
+ return !refreshedSinceChange.has(requestKey)
+}
+
+export interface OverviewPeriod {
+ dateFrom: string
+ dateTo: string
+ /** Length of the period, to check it against the backend's maximum: calendar days for whole days, real time
+ * for instants, as the backend counts them. */
+ days: number
+}
+
+function toInstant(value: dayjs.Dayjs): string {
+ return value.utc().format('YYYY-MM-DDTHH:mm:ss[Z]')
+}
+
+/** Like `dateStringToDayJs`, but a week clip such as "-1wStart" follows the project's first day of the week. */
+function resolveDate(value: string, timezone: string, weekStartDay: number): dayjs.Dayjs | null {
+ const components = dateStringToComponents(value)
+ if (components?.unit !== 'week' || !components.clip) {
+ return dateStringToDayJs(value, timezone)
+ }
+ const day = dateStringToDayJs(value.replace(/(Start|End)$/, ''), timezone)
+ const weekStart = day && startOfWeek(day, weekStartDay)
+ return weekStart && (components.clip === 'Start' ? weekStart : weekStart.add(6, 'day'))
+}
+
+/**
+ * The period to request for the date control's values. A rolling range in hours, like "-24h", is sent as exact
+ * instants up to now. Everything else is sent as whole days in the project's timezone, which the backend counts
+ * inclusively, so "Last 7 days" is the 7 days ending today. Null when the control has no start.
+ */
+export function overviewPeriod(
+ dateFilter: { dateFrom: string | null; dateTo: string | null },
+ timezone: string,
+ now: dayjs.Dayjs,
+ weekStartDay: number = 0
+): OverviewPeriod | null {
+ if (!dateFilter.dateFrom || dateFilter.dateFrom === 'all') {
+ return null
+ }
+ // An hourly period comes back as exact instants from an evaluation page, and whole days would widen it.
+ if (INSTANT.test(dateFilter.dateFrom) && dateFilter.dateTo && INSTANT.test(dateFilter.dateTo)) {
+ const [start, end] = [dayjs.utc(dateFilter.dateFrom), dayjs.utc(dateFilter.dateTo)]
+ return { dateFrom: dateFilter.dateFrom, dateTo: dateFilter.dateTo, days: end.diff(start, 'day', true) }
+ }
+ const rolling = ROLLING_RANGE.exec(dateFilter.dateFrom)
+ if (rolling && !dateFilter.dateTo) {
+ const unit = ROLLING_UNITS[rolling[2] as keyof typeof ROLLING_UNITS]
+ if (unit === 'hour') {
+ // Whole minutes keep the request, and so the backend's cache key, stable within a minute.
+ const end = now.startOf('minute')
+ const start = end.subtract(Number(rolling[1]), unit)
+ return { dateFrom: toInstant(start), dateTo: toInstant(end), days: end.diff(start, 'day', true) }
+ }
+ // The backend counts today as one of the days, so the range starts one day after the same day N units ago.
+ const today = now.tz(timezone).startOf('day')
+ const start = today.subtract(Number(rolling[1]), unit).add(1, 'day')
+ return wholeDays(start, today)
+ }
+ const start = resolveDate(dateFilter.dateFrom, timezone, weekStartDay)
+ const end = (dateFilter.dateTo ? resolveDate(dateFilter.dateTo, timezone, weekStartDay) : null) ?? now.tz(timezone)
+ if (!start) {
+ return null
+ }
+ return wholeDays(start, end)
+}
+
+function wholeDays(start: dayjs.Dayjs, end: dayjs.Dayjs): OverviewPeriod {
+ const dateFrom = start.format('YYYY-MM-DD')
+ const dateTo = end.format('YYYY-MM-DD')
+ // Counted on UTC dates, because a local day across a daylight saving change is 23 or 25 hours long.
+ return { dateFrom, dateTo, days: dayjs.utc(dateTo).diff(dayjs.utc(dateFrom), 'day') + 1 }
+}
+
+function matchesAttention(row: EvaluationResultApi, filter: AttentionFilter): boolean {
+ if (filter === null) {
+ return true
+ }
+ return filter === 'any' ? row.attentionReasons.length > 0 : row.attentionReasons.includes(filter)
+}
+
+// Display order only. A worse result comes before a silent one, because a quality drop is the finding people come
+// for, and evaluations that never ran would otherwise push it below the fold.
+const ATTENTION_ORDER: Record<AttentionReasonsEnumApi, number> = { errored: 0, worse: 1, silent: 2 }
+
+function attentionRank(row: EvaluationResultApi): number {
+ return Math.min(Number.POSITIVE_INFINITY, ...row.attentionReasons.map((reason) => ATTENTION_ORDER[reason]))
+}
+
+/**
+ * How much worse a row got, larger is worse. A pass rate gets worse as it falls, and sentiment gets worse as its
+ * negative share rises.
+ */
+function worsening(row: EvaluationResultApi): number {
+ const change = row.change?.value ?? 0
+ return row.summary.kind === 'sentiment' ? change : -change
+}
+
+/** Most urgent first: by reason, then the biggest worsening within a reason. */
+function compareUrgency(a: EvaluationResultApi, b: EvaluationResultApi): number {
+ return attentionRank(a) - attentionRank(b) || worsening(b) - worsening(a)
+}
+
+/** Rows that ask for attention first, most urgent first, then the rest as the backend sent them. */
+function attentionFirst(rows: EvaluationResultApi[]): EvaluationResultApi[] {
+ return rows
+ .map((row, index) => ({ row, index }))
+ .sort((a, b) => compareUrgency(a.row, b.row) || a.index - b.index)
+ .map(({ row }) => row)
+}
+
+/**
+ * The table's default order: attention first, most urgent first, then running evaluations by graded volume, then
+ * disabled ones and ones without results.
+ */
+function tableOrder(rows: EvaluationResultApi[]): EvaluationResultApi[] {
+ const group = (row: EvaluationResultApi): number =>
+ row.attentionReasons.length > 0 ? attentionRank(row) : !row.enabled || row.gradedCount === 0 ? 4 : 3
+ return [...rows].sort(
+ (a, b) =>
+ group(a) - group(b) ||
+ (group(a) === ATTENTION_ORDER.worse ? worsening(b) - worsening(a) : 0) ||
+ b.gradedCount - a.gradedCount
+ )
+}
+
+function dipCount(row: EvaluationResultApi): number {
+ return row.bucketStatus.filter((status) => status === 'dip').length
+}
+
+/** Pass rates sort weakest first. Other types have no shared scale, so they sort after them. */
+function gridSortRate(row: EvaluationResultApi): number {
+ const rate = percentValue(row)
+ return row.summary.kind === 'pass_rate' && Number.isFinite(rate) ? rate : 100
+}
+
+/** Rate limiting has its own message, because waiting fixes it. */
+export function failureOf(error: unknown): OverviewFailure {
+ return error instanceof ApiError && error.status === 429 ? 'rate_limited' : 'failed'
+}
+
+export interface OverviewRequest {
+ params: EvaluationsOverviewRetrieveParams
+ /** False when the request would be refused or would not match what the page shows. */
+ ready: boolean
+ /** Why nothing is requested, for the page to show in place of results. */
+ notice: string | null
+}
+
+export interface RankedRow {
+ row: EvaluationResultApi
+ rate: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface evaluationsOverviewLogicValues {
+ dateFilter: {
+ dateFrom: string | null
+ dateTo: string | null
+ } // llmEvaluationsLogic
+ directoryEditor: EvaluationDirectoryEditor | null // llmEvaluationsLogic
+ evaluationDirectories: EvaluationDirectoryApi[] // llmEvaluationsLogic
+ evaluations: EvaluationConfig[] // llmEvaluationsLogic
+ evaluationsLoadFailed: boolean // llmEvaluationsLogic
+ evaluationsSettled: boolean // llmEvaluationsLogic
+ selectedDirectory: EvaluationDirectoryApi | null // llmEvaluationsLogic
+ selectedDirectoryId: string | null // llmEvaluationsLogic
+ searchParams: Record<string, any> // router
+ currentTeamId: number | null // teamLogic
+ timezone: string // teamLogic
+ weekStartDay: number // teamLogic
+ attentionById: Record<string, boolean>
+ attentionCounts: Record<string, number>
+ attentionFilter: AttentionFilter
+ buckets: string[]
+ chartedIds: string[]
+ chosenMetric: OverviewMetric
+ compareListRows: EvaluationResultApi[]
+ comparedIds: string[] | null
+ configById: Map<string, EvaluationConfig>
+ directoryTiles: DirectoryTile[]
+ evaluationListFailed: boolean
+ evaluationUrl: (id: string, params?: Record<string, string>) => string
+ exploreUrl: string | null
+ few: boolean
+ interval: BucketInterval
+ measuredPassRateRows: EvaluationResultApi[]
+ metric: OverviewMetric
+ nothingGraded: boolean
+ overview: EvaluationsOverviewApi | null
+ overviewFailure: OverviewFailure | null
+ overviewLoading: boolean
+ periodLength: number
+ periodNow: number
+ pickedIds: string[]
+ ranked: {
+ labels: RankedRow[]
+ results: RankedRow[]
+ }
+ request: OverviewRequest
+ rows: EvaluationResultApi[]
+ rowsById: Map<string, EvaluationResultApi>
+ scopeEvaluations: EvaluationConfig[]
+ scopedIds: string[] | null
+ search: string
+ sentimentRow: EvaluationResultApi | null
+ statusGridRows: EvaluationResultApi[]
+ tableRows: EvaluationResultApi[]
+ togglingIds: string[]
+ view: OverviewView
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface evaluationsOverviewLogicActions {
+ deleteDirectory: (id: string) => {
+ id: string
+ } // llmEvaluationsLogic
+ deleteDirectorySuccess: (id: string) => {
+ id: string
+ } // llmEvaluationsLogic
+ deleteEvaluation: (id: string) => {
+ id: string
+ } // llmEvaluationsLogic
+ deleteEvaluationSuccess: (id: string) => {
+ id: string
+ } // llmEvaluationsLogic
+ loadEvaluations: () => {
+ value: true
+ } // llmEvaluationsLogic
+ loadEvaluationsFailure: () => {
+ value: true
+ } // llmEvaluationsLogic
+ loadEvaluationsSuccess: (evaluations: EvaluationConfig[]) => {
+ evaluations: EvaluationConfig[]
+ } // llmEvaluationsLogic
+ moveEvaluation: (
+ id: string,
+ directoryId: string | null
+ ) => {
+ directoryId: string | null
+ id: string
+ } // llmEvaluationsLogic
+ moveEvaluationSuccess: (
+ id: string,
+ directoryId: string | null
+ ) => {
+ directoryId: string | null
+ id: string
+ } // llmEvaluationsLogic
+ restoreEvaluationSuccess: (evaluation: EvaluationConfig) => {
+ evaluation: EvaluationConfig
+ } // llmEvaluationsLogic
+ selectDirectory: (directoryId: string | null) => {
+ directoryId: string | null
+ } // llmEvaluationsLogic
+ setDates: (
+ dateFrom: string | null,
+ dateTo: string | null
+ ) => {
+ dateFrom: string | null
+ dateTo: string | null
+ } // llmEvaluationsLogic
+ submitDirectory: () => {
+ value: true
+ } // llmEvaluationsLogic
+ submitDirectorySuccess: () => {
+ value: true
+ } // llmEvaluationsLogic
+ toggleEvaluationEnabled: (id: string) => {
+ id: string
+ } // llmEvaluationsLogic
+ toggleEvaluationEnabledFailure: (
+ id: string,
+ error: string
+ ) => {
+ error: string
+ id: string
+ } // llmEvaluationsLogic
+ toggleEvaluationEnabledSuccess: (id: string) => {
+ id: string
+ } // llmEvaluationsLogic
+ locationChanged: ({
+ method,
+ pathname,
+ search,
+ searchParams,
+ hash,
+ hashParams,
+ initial,
+ url,
+ routerState,
+ }: LocationChangedPayload) => {
+ hash: string
+ hashParams: Record<string, any>
+ initial: boolean
+ method: 'POP' | 'PUSH' | 'REPLACE'
+ pathname: string
+ routerState: Record<string, any>
+ search: string
+ searchParams: Record<string, any>
+ url: string
+ } // router
+ clickExplore: () => {
+ value: true
+ }
+ loadOverview: (_: void) => void
+ loadOverviewFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadOverviewSuccess: (
+ overview: EvaluationsOverviewApi | null,
+ payload?: void
+ ) => {
+ overview: EvaluationsOverviewApi | null
+ payload?: void
+ }
+ openDirectory: (directoryId: string) => {
+ directoryId: string
+ }
+ refreshAfterChange: () => {
+ value: true
+ }
+ reloadOverview: () => {
+ value: true
+ }
+ resetPicks: () => {
+ value: true
+ }
+ retryOverview: () => {
+ value: true
+ }
+ selectCard: (card: OverviewCard) => {
+ card: OverviewCard
+ }
+ setAttentionFilter: (filter: AttentionFilter) => {
+ filter: AttentionFilter
+ }
+ setComparedIds: (ids: string[]) => {
+ ids: string[]
+ }
+ setOverviewFailure: (failure: OverviewFailure) => {
+ failure: OverviewFailure
+ }
+ setPickedIds: (ids: string[]) => {
+ ids: string[]
+ }
+ setSearch: (search: string) => {
+ search: string
+ }
+ setView: (view: OverviewView) => {
+ view: OverviewView
+ }
+ toggleCompared: (id: string) => {
+ id: string
+ }
+ trackDirectoryAction: (action: DirectoryAction) => {
+ action: DirectoryAction
+ }
+ trackTableAction: (action: TableAction) => {
+ action: TableAction
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface evaluationsOverviewLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ scopeEvaluations: (evaluations: EvaluationConfig[], selectedDirectoryId: string | null) => EvaluationConfig[]
+ scopedIds: (
+ scopeEvaluations: EvaluationConfig[],
+ pickedIds: string[],
+ selectedDirectoryId: string | null
+ ) => string[] | null
+ request: (
+ dateFilter: {
+ dateFrom: string | null
+ dateTo: string | null
+ },
+ timezone: string,
+ weekStartDay: number,
+ scopedIds: string[] | null,
+ selectedDirectoryId: string | null,
+ evaluationsSettled: boolean,
+ evaluationsLoadFailed: boolean,
+ periodNow: number
+ ) => OverviewRequest
+ rows: (overview: EvaluationsOverviewApi | null) => EvaluationResultApi[]
+ buckets: (overview: EvaluationsOverviewApi | null) => string[]
+ interval: (overview: EvaluationsOverviewApi | null) => BucketInterval
+ periodLength: (overview: EvaluationsOverviewApi | null) => number
+ rowsById: (rows: EvaluationResultApi[]) => Map<string, EvaluationResultApi>
+ few: (evaluations: EvaluationConfig[]) => boolean
+ nothingGraded: (rows: EvaluationResultApi[]) => boolean
+ sentimentRow: (
+ overview: EvaluationsOverviewApi | null,
+ rowsById: Map<string, EvaluationResultApi>
+ ) => EvaluationResultApi | null
+ metric: (chosenMetric: OverviewMetric, sentimentRow: EvaluationResultApi | null) => OverviewMetric
+ compareListRows: (rows: EvaluationResultApi[], nothingGraded: boolean) => EvaluationResultApi[]
+ measuredPassRateRows: (
+ overview: EvaluationsOverviewApi | null,
+ rowsById: Map<string, EvaluationResultApi>
+ ) => EvaluationResultApi[]
+ chartedIds: (comparedIds: string[] | null, compareListRows: EvaluationResultApi[]) => string[]
+ statusGridRows: (rows: EvaluationResultApi[]) => EvaluationResultApi[]
+ ranked: (
+ overview: EvaluationsOverviewApi | null,
+ rows: EvaluationResultApi[],
+ rowsById: Map<string, EvaluationResultApi>
+ ) => {
+ labels: RankedRow[]
+ results: RankedRow[]
+ }
+ configById: (evaluations: EvaluationConfig[]) => Map<string, EvaluationConfig>
+ attentionCounts: (rows: EvaluationResultApi[]) => Record<string, number>
+ directoryTiles: (
+ evaluationDirectories: EvaluationDirectoryApi[],
+ evaluations: EvaluationConfig[],
+ attentionById: Record<string, boolean>
+ ) => DirectoryTile[]
+ tableRows: (
+ rows: EvaluationResultApi[],
+ search: string,
+ attentionFilter: AttentionFilter
+ ) => EvaluationResultApi[]
+ evaluationUrl: (
+ searchParams: Record<string, any>,
+ request: OverviewRequest
+ ) => (id: string, params?: Record<string, string>) => string
+ exploreUrl: (
+ evaluations: EvaluationConfig[],
+ scopedIds: string[] | null,
+ request: OverviewRequest,
+ interval: BucketInterval
+ ) => string | null
+ evaluationListFailed: (
+ evaluationsLoadFailed: boolean,
+ overviewFailure: OverviewFailure | null,
+ request: OverviewRequest
+ ) => boolean
+ }
+}
+
+export type evaluationsOverviewLogicType = MakeLogicType<
+ evaluationsOverviewLogicValues,
+ evaluationsOverviewLogicActions,
+ Record<string, any>,
+ evaluationsOverviewLogicMeta
+>
+
+export const evaluationsOverviewLogic = kea<evaluationsOverviewLogicType>([
+ path(['products', 'ai_observability', 'frontend', 'evaluations', 'overview', 'evaluationsOverviewLogic']),
+ connect(() => ({
+ values: [
+ teamLogic,
+ ['currentTeamId', 'timezone', 'weekStartDay'],
+ router,
+ ['searchParams'],
+ llmEvaluationsLogic,
+ [
+ 'dateFilter',
+ 'evaluations',
+ 'evaluationsSettled',
+ 'evaluationsLoadFailed',
+ 'selectedDirectoryId',
+ 'selectedDirectory',
+ 'evaluationDirectories',
+ 'directoryEditor',
+ ],
+ ],
+ actions: [
+ llmEvaluationsLogic,
+ [
+ 'setDates',
+ 'selectDirectory',
+ 'loadEvaluations',
+ 'loadEvaluationsSuccess',
+ 'loadEvaluationsFailure',
+ 'toggleEvaluationEnabled',
+ 'toggleEvaluationEnabledSuccess',
+ 'toggleEvaluationEnabledFailure',
+ 'moveEvaluation',
+ 'deleteEvaluation',
+ 'moveEvaluationSuccess',
+ 'deleteEvaluationSuccess',
+ 'restoreEvaluationSuccess',
+ 'submitDirectory',
+ 'submitDirectorySuccess',
+ 'deleteDirectory',
+ 'deleteDirectorySuccess',
+ ],
+ router,
+ ['locationChanged'],
+ ],
+ })),
+ actions({
+ setPickedIds: (ids: string[]) => ({ ids }),
+ setView: (view: OverviewView) => ({ view }),
+ selectCard: (card: OverviewCard) => ({ card }),
+ toggleCompared: (id: string) => ({ id }),
+ setComparedIds: (ids: string[]) => ({ ids }),
+ clickExplore: true,
+ setSearch: (search: string) => ({ search }),
+ setAttentionFilter: (filter: AttentionFilter) => ({ filter }),
+ trackTableAction: (action: TableAction) => ({ action }),
+ setOverviewFailure: (failure: OverviewFailure) => ({ failure }),
+ refreshAfterChange: true,
+ reloadOverview: true,
+ retryOverview: true,
+ resetPicks: true,
+ openDirectory: (directoryId: string) => ({ directoryId }),
+ trackDirectoryAction: (action: DirectoryAction) => ({ action }),
+ }),
+ loaders(({ actions, values, cache }) => ({
+ overview: [
+ null as EvaluationsOverviewApi | null,
+ {
+ loadOverview: async (_: void, breakpoint) => {
+ if (!values.currentTeamId || !values.request.ready) {
+ // A refresh can land while the list reloads. The results stay on screen, and a cleared key lets
+ // the load after the list arrives run, with the refresh still pending.
+ cache.requestKey = null
+ // A directory waits for its list. A failed list never arrives, so the page shows its retry instead.
+ if (values.evaluationsLoadFailed) {
+ actions.setOverviewFailure('failed')
+ }
+ return values.request.notice ? null : values.overview
+ }
+ const requestKey = JSON.stringify(values.request)
+ cache.requestKey = requestKey
+ const refresh = needsRefreshAfterChange(requestKey) || cache.forceRefresh === true
+ const requestedAt = performance.now()
+ let overview: EvaluationsOverviewApi
+ try {
+ overview = await evaluationsOverviewRetrieve(String(values.currentTeamId), {
+ ...values.request.params,
+ ...(refresh ? { refresh: true } : {}),
+ })
+ } catch (error) {
+ breakpoint()
+ // The page shows its own failure state with a retry, so the loader's generic toast is skipped.
+ actions.setOverviewFailure(failureOf(error))
+ return null
+ }
+ // Drops a response that a newer scope or date change has superseded.
+ breakpoint()
+ // Only a response that lands consumes the refresh, so a retry after a failure skips the cache too.
+ if (refresh) {
+ refreshedSinceChange.add(requestKey)
+ cache.forceRefresh = false
+ }
+ // pinned: the event name and its properties, because renaming one breaks dashboards.
+ posthog.capture('llma evaluation overview loaded', {
+ load_ms: Math.round(performance.now() - requestedAt),
+ evaluation_count: overview.evaluations.length,
+ buckets: overview.buckets.length,
+ interval: overview.interval,
+ })
+ return overview
+ },
+ },
+ ],
+ })),
+ reducers({
+ // The instant a rolling period ends at. The request selector reads no clock, so a reload or a new scope or
+ // range moves this forward to cover what arrived since. Zero until then reads the clock once.
+ periodNow: [
+ 0,
+ {
+ reloadOverview: () => Date.now(),
+ setDates: () => Date.now(),
+ selectDirectory: () => Date.now(),
+ setPickedIds: () => Date.now(),
+ resetPicks: () => Date.now(),
+ },
+ ],
+ // Picks belong to the directory they were made in, so opening another one starts from all of its evaluations.
+ pickedIds: [
+ [] as string[],
+ {
+ setPickedIds: (_, { ids }) => ids,
+ selectDirectory: () => [],
+ resetPicks: () => [],
+ deleteEvaluationSuccess: (state, { id }) => state.filter((picked) => picked !== id),
+ },
+ ],
+ view: [
+ 'over_time' as OverviewView,
+ {
+ setView: (_, { view }) => view,
+ // A charted card swaps the over time chart, so it shows that view.
+ selectCard: (state, { card }) => (card === 'attention' ? state : 'over_time'),
+ },
+ ],
+ chosenMetric: [
+ 'pass_rate' as OverviewMetric,
+ { selectCard: (state, { card }) => (card === 'attention' ? state : card) },
+ ],
+ // Null keeps the default picks, so they follow the data until someone picks by hand.
+ comparedIds: [
+ null as string[] | null,
+ {
+ setPickedIds: () => null,
+ selectDirectory: () => null,
+ resetPicks: () => null,
+ setComparedIds: (_, { ids }) => ids,
+ },
+ ],
+ overviewFailure: [
+ null as OverviewFailure | null,
+ {
+ loadOverview: () => null,
+ setOverviewFailure: (_, { failure }) => failure,
+ },
+ ],
+ search: ['', { setSearch: (_, { search }) => search }],
+ // Whether each evaluation needed attention in the latest read that covered it, so directory tiles keep
+ // their counts while one directory scopes the overview.
+ attentionById: [
+ {} as Record<string, boolean>,
+ {
+ setDates: () => ({}),
+ loadOverviewSuccess: (state, { overview }) =>
+ overview
+ ? {
+ ...state,
+ ...Object.fromEntries(
+ overview.evaluations.map((row) => [row.id, row.attentionReasons.length > 0])
+ ),
+ }
+ : state,
+ },
+ ],
+ attentionFilter: [
+ null as AttentionFilter,
+ {
+ setAttentionFilter: (_, { filter }) => filter,
+ selectCard: (state, { card }) => (card === 'attention' ? 'any' : state),
+ },
+ ],
+ // The enable switch has no in-flight state of its own, so the table tracks it to block a second click.
+ togglingIds: [
+ [] as string[],
+ {
+ toggleEvaluationEnabled: (state, { id }) => [...state, id],
+ toggleEvaluationEnabledSuccess: (state, { id }) => state.filter((other) => other !== id),
+ toggleEvaluationEnabledFailure: (state, { id }) => state.filter((other) => other !== id),
+ },
+ ],
+ }),
+ selectors({
+ scopeEvaluations: [
+ (s) => [s.evaluations, s.selectedDirectoryId],
+ (evaluations: EvaluationConfig[], selectedDirectoryId: string | null): EvaluationConfig[] =>
+ selectedDirectoryId
+ ? evaluations.filter((evaluation) => evaluation.directory_id === selectedDirectoryId)
+ : evaluations,
+ ],
+ // Null covers every evaluation the user can see.
+ scopedIds: [
+ (s) => [s.scopeEvaluations, s.pickedIds, s.selectedDirectoryId],
+ (
+ scopeEvaluations: EvaluationConfig[],
+ pickedIds: string[],
+ selectedDirectoryId: string | null
+ ): string[] | null => {
+ const inScope = new Set(scopeEvaluations.map((evaluation) => evaluation.id))
+ const picked = selectedDirectoryId ? pickedIds.filter((id) => inScope.has(id)) : pickedIds
+ if (picked.length > 0) {
+ return picked
+ }
+ return selectedDirectoryId ? [...inScope] : null
+ },
+ ],
+ request: [
+ (s) => [
+ s.dateFilter,
+ s.timezone,
+ s.weekStartDay,
+ s.scopedIds,
+ s.selectedDirectoryId,
+ s.evaluationsSettled,
+ s.evaluationsLoadFailed,
+ s.periodNow,
+ ],
+ (
+ dateFilter: {
+ dateFrom: string | null
+ dateTo: string | null
+ },
+ timezone: string,
+ weekStartDay: number,
+ scopedIds: string[] | null,
+ selectedDirectoryId: string | null,
+ evaluationsSettled: boolean,
+ evaluationsLoadFailed: boolean,
+ periodNow: number
+ ): OverviewRequest => {
+ const period = overviewPeriod(
+ dateFilter,
+ timezone,
+ periodNow ? dayjs(periodNow) : dayjs(),
+ weekStartDay
+ )
+ const params: EvaluationsOverviewRetrieveParams = {
+ date_from: period?.dateFrom,
+ date_to: period?.dateTo,
+ evaluation_ids: scopedIds ?? undefined,
+ }
+ // Without a start the backend falls back to its default period, which the date control would not show.
+ if (!period || period.days > OVERVIEW_MAX_DAYS) {
+ return {
+ params,
+ ready: false,
+ notice: `Pick a range of ${OVERVIEW_MAX_DAYS} days or less to see results here.`,
+ }
+ }
+ // A directory's evaluations are only known once the list has loaded. A failed list is not an empty one.
+ if (selectedDirectoryId && (!evaluationsSettled || evaluationsLoadFailed)) {
+ return { params, ready: false, notice: null }
+ }
+ // An empty id list would mean every evaluation, not none.
+ if (scopedIds?.length === 0) {
+ return { params, ready: false, notice: 'This directory has no evaluations yet.' }
+ }
+ return { params, ready: true, notice: null }
+ },
+ ],
+ rows: [
+ (s) => [s.overview],
+ (overview: EvaluationsOverviewApi | null): EvaluationResultApi[] => overview?.evaluations ?? [],
+ ],
+ buckets: [(s) => [s.overview], (overview: EvaluationsOverviewApi | null): string[] => overview?.buckets ?? []],
+ interval: [
+ (s) => [s.overview],
+ (overview: EvaluationsOverviewApi | null): BucketInterval => overview?.interval ?? 'day',
+ ],
+ // The period's length in the interval's unit, for captions. Buckets can start before the period, so their
+ // count can be one more than this.
+ periodLength: [
+ (s) => [s.overview],
+ (overview: EvaluationsOverviewApi | null): number =>
+ overview
+ ? Math.round(
+ dayjs(overview.end).diff(
+ dayjs(overview.start),
+ overview.interval === 'hour' ? 'hour' : 'day',
+ true
+ )
+ )
+ : 0,
+ ],
+ rowsById: [
+ (s) => [s.rows],
+ (rows: EvaluationResultApi[]): Map<string, EvaluationResultApi> =>
+ new Map(rows.map((row) => [row.id, row])),
+ ],
+ few: [
+ (s) => [s.evaluations],
+ // The create slot is a nudge, so people who can't create evaluations don't see it.
+ (evaluations: EvaluationConfig[]): boolean =>
+ evaluations.length <= FEW_EVALUATIONS_MAX &&
+ !getAccessControlDisabledReason(AccessControlResourceType.Evaluation, AccessControlLevel.Editor),
+ ],
+ nothingGraded: [
+ (s) => [s.rows],
+ (rows: EvaluationResultApi[]): boolean => rows.every((row) => row.gradedCount === 0),
+ ],
+ sentimentRow: [
+ (s) => [s.overview, s.rowsById],
+ (
+ overview: EvaluationsOverviewApi | null,
+ rowsById: Map<string, EvaluationResultApi>
+ ): EvaluationResultApi | null => {
+ const id = overview?.totals.sentiment?.evaluationId
+ return (id && rowsById.get(id)) || null
+ },
+ ],
+ // A scope or period without sentiment results falls back to pass rates, so the chart never mixes the two.
+ metric: [
+ (s) => [s.chosenMetric, s.sentimentRow],
+ (chosenMetric: OverviewMetric, sentimentRow: EvaluationResultApi | null): OverviewMetric =>
+ chosenMetric === 'sentiment' && !sentimentRow ? 'pass_rate' : chosenMetric,
+ ],
+ compareListRows: [
+ (s) => [s.rows, s.nothingGraded],
+ (rows: EvaluationResultApi[], nothingGraded: boolean): EvaluationResultApi[] => {
+ const listed = nothingGraded
+ ? rows
+ : rows.filter((row) => row.attentionReasons.length > 0 || (row.enabled && row.gradedCount > 0))
+ // Rows with a line to draw come first, so evaluations that never ran do not push them down.
+ return [
+ ...attentionFirst(listed.filter(isChartable)),
+ ...attentionFirst(listed.filter((row) => !isChartable(row))),
+ ]
+ },
+ ],
+ // Pass rates with enough results to rely on, the ones the median and the chart's background lines use.
+ measuredPassRateRows: [
+ (s) => [s.overview, s.rowsById],
+ (
+ overview: EvaluationsOverviewApi | null,
+ rowsById: Map<string, EvaluationResultApi>
+ ): EvaluationResultApi[] =>
+ (overview?.passRateOverview.entries ?? []).flatMap((entry) => {
+ const row = !entry.lowEvidence && rowsById.get(entry.evaluationId)
+ return row ? [row] : []
+ }),
+ ],
+ chartedIds: [
+ (s) => [s.comparedIds, s.compareListRows],
+ (comparedIds: string[] | null, compareListRows: EvaluationResultApi[]): string[] => {
+ if (comparedIds) {
+ return comparedIds
+ }
+ const chartable = compareListRows.filter(isChartable)
+ const urgent = chartable.filter((row) => row.attentionReasons.length > 0).sort(compareUrgency)
+ const picked = urgent.length > 0 ? urgent : chartable.sort((a, b) => b.gradedCount - a.gradedCount)
+ return picked.slice(0, DEFAULT_COMPARED).map((row) => row.id)
+ },
+ ],
+ // Evaluations with the most unusual days come first. Ones without results go last.
+ statusGridRows: [
+ (s) => [s.rows],
+ (rows: EvaluationResultApi[]): EvaluationResultApi[] =>
+ [...rows].sort(
+ (a, b) =>
+ Number(a.gradedCount === 0) - Number(b.gradedCount === 0) ||
+ dipCount(b) - dipCount(a) ||
+ gridSortRate(a) - gridSortRate(b)
+ ),
+ ],
+ ranked: [
+ (s) => [s.overview, s.rows, s.rowsById],
+ (
+ overview: EvaluationsOverviewApi | null,
+ rows: EvaluationResultApi[],
+ rowsById: Map<string, EvaluationResultApi>
+ ): { results: RankedRow[]; labels: RankedRow[] } => {
+ const rank = (kinds: string[], rate: (row: EvaluationResultApi) => number): RankedRow[] =>
+ rows
+ .filter((row) => row.enabled && row.gradedCount > 0 && kinds.includes(row.summary.kind))
+ .map((row) => ({ row, rate: rate(row) }))
+ .filter((item) => Number.isFinite(item.rate))
+ return {
+ // Results with a better and a worse direction, on one scale where higher is better: pass rates as
+ // they are, sentiment as the share that is not negative, and scores as their position on the scale.
+ results: [
+ ...(overview?.passRateOverview.entries ?? []).flatMap((entry) => {
+ const row = rowsById.get(entry.evaluationId)
+ return row ? [{ row, rate: entry.rate }] : []
+ }),
+ ...rank(['sentiment', 'score'], (row) =>
+ row.summary.kind === 'sentiment' ? 100 - percentValue(row) : percentValue(row)
+ ),
+ ],
+ // Labels without a passing rule have no better or worse, so they rank on their own.
+ labels: rank(['categories'], percentValue),
+ }
+ },
+ ],
+ configById: [
+ (s) => [s.evaluations],
+ (evaluations: EvaluationConfig[]): Map<string, EvaluationConfig> =>
+ new Map(evaluations.map((evaluation) => [evaluation.id, evaluation])),
+ ],
+ attentionCounts: [
+ (s) => [s.rows],
+ (rows: EvaluationResultApi[]): Record<string, number> =>
+ Object.fromEntries(
+ (['all', 'any', 'errored', 'silent', 'worse'] as const).map((filter) => [
+ filter,
+ rows.filter((row) => matchesAttention(row, filter === 'all' ? null : filter)).length,
+ ])
+ ),
+ ],
+ directoryTiles: [
+ (s) => [s.evaluationDirectories, s.evaluations, s.attentionById],
+ (
+ directories: EvaluationDirectoryApi[],
+ evaluations: EvaluationConfig[],
+ attentionById: Record<string, boolean>
+ ): DirectoryTile[] =>
+ directories.map((directory) => {
+ const members = evaluations.filter((evaluation) => evaluation.directory_id === directory.id)
+ const known = members.every((evaluation) => evaluation.id in attentionById)
+ return {
+ directory,
+ evaluationCount: members.length,
+ needAttentionCount: known
+ ? members.filter((evaluation) => attentionById[evaluation.id]).length
+ : null,
+ }
+ }),
+ ],
+ tableRows: [
+ (s) => [s.rows, s.search, s.attentionFilter],
+ (rows: EvaluationResultApi[], search: string, attentionFilter: AttentionFilter): EvaluationResultApi[] => {
+ const query = search.trim().toLowerCase()
+ const matching = rows.filter(
+ (row) => matchesAttention(row, attentionFilter) && row.name.toLowerCase().includes(query)
+ )
+ return tableOrder(matching)
+ },
+ ],
+ // Links keep the page's search params, so an evaluation returns to this directory. They carry the period the
+ // overview resolved, because the evaluation page reads a relative range such as "-7d" with one more day.
+ evaluationUrl: [
+ (s) => [s.searchParams, s.request],
+ (
+ searchParams: Record<string, any>,
+ request: OverviewRequest
+ ): ((id: string, params?: Record<string, string>) => string) => {
+ const { date_from, date_to } = request.params
+ const period = date_from && date_to ? { date_from, date_to } : {}
+ return (id, params = {}) =>
+ combineUrl(urls.aiObservabilityEvaluation(id), { ...searchParams, ...period, ...params }).url
+ },
+ ],
+ exploreUrl: [
+ (s) => [s.evaluations, s.scopedIds, s.request, s.interval],
+ (
+ evaluations: EvaluationConfig[],
+ scopedIds: string[] | null,
+ request: OverviewRequest,
+ interval: BucketInterval
+ ): string | null => {
+ if (!request.ready) {
+ return null
+ }
+ const scoped = scopedIds
+ ? evaluations.filter((evaluation) => scopedIds.includes(evaluation.id))
+ : evaluations
+ const { date_from = null, date_to = null } = request.params
+ // Trends reads a date-only end as that day's midnight when it buckets by hour, so the day gets an end.
+ const dateTo =
+ interval === 'hour' && date_to && /^\d{4}-\d{2}-\d{2}$/.test(date_to)
+ ? `${date_to}T23:59:59`
+ : date_to
+ // The period and interval the overview resolved, so the insight covers what the chart it opens from shows.
+ const source = buildEvaluationPassRateTrendsQuery(scoped, { dateFrom: date_from, dateTo }, interval)
+ if (!source) {
+ return null
+ }
+ const query: InsightVizNode = { kind: NodeKind.InsightVizNode, source }
+ return urls.insightNew({ query })
+ },
+ ],
+ // Results can load without the list, but row actions and the scope picker need it. When the results fail
+ // too, their own banner retries both.
+ evaluationListFailed: [
+ (s) => [s.evaluationsLoadFailed, s.overviewFailure, s.request],
+ (
+ evaluationsLoadFailed: boolean,
+ overviewFailure: OverviewFailure | null,
+ request: OverviewRequest
+ ): boolean => evaluationsLoadFailed && !overviewFailure && !request.notice,
+ ],
+ }),
+ listeners(({ actions, values, cache }) => {
+ // Scope and dates reach this logic through several actions and the URL, so one change can arrive twice.
+ const refresh = (): void => {
+ const key = JSON.stringify(values.request)
+ if (key !== cache.requestKey) {
+ cache.requestKey = key
+ actions.loadOverview()
+ }
+ }
+ // pinned: every analytics event name and property in these listeners, because renaming one breaks dashboards.
+ return {
+ setPickedIds: async ({ ids }, breakpoint) => {
+ posthog.capture('llma evaluation overview scope changed', {
+ evaluation_count: ids.length,
+ directory_scoped: values.selectedDirectoryId !== null,
+ trigger: 'picker',
+ })
+ await breakpoint(SCOPE_CHANGE_DEBOUNCE_MS)
+ refresh()
+ },
+ selectDirectory: ({ directoryId }) => {
+ posthog.capture('llma evaluation overview scope changed', {
+ evaluation_count: values.scopedIds?.length ?? values.evaluations.length,
+ directory_scoped: directoryId !== null,
+ trigger: 'directory',
+ })
+ refresh()
+ },
+ setDates: refresh,
+ locationChanged: () => {
+ // Browser back and forward change the directory without `selectDirectory`, so picks reset here too.
+ if (values.selectedDirectoryId !== cache.directoryId) {
+ cache.directoryId = values.selectedDirectoryId
+ actions.resetPicks()
+ }
+ refresh()
+ },
+ loadEvaluationsSuccess: refresh,
+ loadEvaluationsFailure: () => {
+ // A load that waited for the list has no list to resume with, so the page shows its retry.
+ if (cache.requestKey === null) {
+ actions.setOverviewFailure('failed')
+ }
+ },
+ setView: ({ view }) => {
+ posthog.capture('llma evaluation overview view changed', { view })
+ },
+ selectCard: ({ card }) => {
+ posthog.capture('llma evaluation overview card clicked', { card })
+ if (card === 'attention') {
+ posthog.capture('llma evaluation overview attention filter changed', {
+ filter: 'any',
+ trigger: 'card',
+ })
+ document
+ .getElementById(OVERVIEW_LIST_ANCHOR_ID)
+ ?.scrollIntoView({ behavior: 'smooth', block: 'start' })
+ }
+ },
+ toggleCompared: ({ id }) => {
+ const current = values.chartedIds
+ actions.setComparedIds(
+ current.includes(id) ? current.filter((other) => other !== id) : [...current, id]
+ )
+ },
+ setAttentionFilter: ({ filter }) => {
+ posthog.capture('llma evaluation overview attention filter changed', {
+ filter: filter ?? 'all',
+ trigger: 'table',
+ })
+ },
+ trackTableAction: ({ action }) => {
+ posthog.capture('llma evaluation overview table action used', { action })
+ },
+ toggleEvaluationEnabled: ({ id }) => {
+ actions.trackTableAction(values.configById.get(id)?.enabled ? 'disable' : 'enable')
+ },
+ moveEvaluation: () => actions.trackTableAction('move'),
+ toggleEvaluationEnabledSuccess: () => actions.refreshAfterChange(),
+ moveEvaluationSuccess: () => actions.refreshAfterChange(),
+ deleteEvaluationSuccess: () => actions.refreshAfterChange(),
+ deleteDirectorySuccess: () => actions.refreshAfterChange(),
+ restoreEvaluationSuccess: () => actions.refreshAfterChange(),
+ refreshAfterChange: async (_, breakpoint) => {
+ markEveryScopeStale()
+ await breakpoint(REFRESH_AFTER_CHANGE_MS)
+ actions.reloadOverview()
+ },
+ reloadOverview: () => {
+ cache.forceRefresh = true
+ actions.loadOverview()
+ },
+ retryOverview: () => {
+ // A directory's overview waits for its list, so a failed list reloads too. Its success resumes the load.
+ if (values.evaluationsLoadFailed) {
+ actions.loadEvaluations()
+ }
+ // A failed list alone leaves the results current, so they load again only when they failed.
+ if (values.overviewFailure) {
+ actions.loadOverview()
+ }
+ },
+ openDirectory: ({ directoryId }) => {
+ posthog.capture('llma evaluation overview directory opened', {
+ evaluation_count: values.evaluations.filter((evaluation) => evaluation.directory_id === directoryId)
+ .length,
+ })
+ actions.selectDirectory(directoryId)
+ },
+ submitDirectory: () => {
+ cache.directoryEditorMode = values.directoryEditor?.mode ?? null
+ },
+ submitDirectorySuccess: () => {
+ if (cache.directoryEditorMode === 'create') {
+ posthog.capture('llma evaluation overview directory created')
+ } else if (cache.directoryEditorMode === 'rename') {
+ actions.trackDirectoryAction('rename')
+ // Rows carry their directory's name, which the request key does not change with.
+ actions.refreshAfterChange()
+ }
+ },
+ deleteDirectory: () => actions.trackDirectoryAction('delete'),
+ trackDirectoryAction: ({ action }) => {
+ posthog.capture('llma evaluation overview directory action', { action })
+ },
+ deleteEvaluation: () => actions.trackTableAction('delete'),
+ clickExplore: () => {
+ posthog.capture('llma evaluation overview explore clicked', {
+ evaluation_count: values.rows.length,
+ })
+ },
+ }
+ }),
+ afterMount(({ actions, values, cache }) => {
+ cache.directoryId = values.selectedDirectoryId
+ cache.requestKey = JSON.stringify(values.request)
+ actions.loadOverview()
+ }),
+])