:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): refresh of the notebook experiments node. (#57848)
Rodrigo Iloro7d0ea9756784
diff --git a/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx b/frontend/src/scenes/experiments/ExperimentView/Exposures.tsxindex 1c1f4b1a7f0e..8711caab6621 100644--- a/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx@@ -58,7 +58,7 @@ function buildExposureDatasets(timeseries: ExperimentExposureTimeSeries[]): {return { labels, datasets }}-function MicroChart({ exposures }: MicroChartProps): JSX.Element | null {+export function MicroChart({ exposures }: MicroChartProps): JSX.Element | null {const { canvasRef } = useChart({getConfig: () => {if (!exposures?.timeseries?.length) {diff --git a/frontend/src/scenes/experiments/components/ResultsTag.tsx b/frontend/src/scenes/experiments/components/ResultsTag.tsxnew file mode 100644index 000000000000..6f6a683d4db0--- /dev/null+++ b/frontend/src/scenes/experiments/components/ResultsTag.tsx@@ -0,0 +1,13 @@+import { LemonTag } from '@posthog/lemon-ui'++export interface ResultsTagProps {+ isSignificant: boolean+}++export function ResultsTag({ isSignificant }: ResultsTagProps): JSX.Element {+ return (+ <LemonTag type={isSignificant ? 'success' : 'primary'}>+ <b className="uppercase">{isSignificant ? 'Significant' : 'Not significant'}</b>+ </LemonTag>+ )+}diff --git a/frontend/src/scenes/experiments/notebook/ExperimentStatItem.tsx b/frontend/src/scenes/experiments/notebook/ExperimentStatItem.tsxnew file mode 100644index 000000000000..dd1f8f514046--- /dev/null+++ b/frontend/src/scenes/experiments/notebook/ExperimentStatItem.tsx@@ -0,0 +1,24 @@+import { LemonSkeleton } from '@posthog/lemon-ui'++export interface ExperimentStatItemProps {+ label: string+ value: string | number+ loading?: boolean+ chart?: React.ReactNode+}++export function ExperimentStatItem({ label, value, loading, chart }: ExperimentStatItemProps): JSX.Element {+ return (+ <div className="flex flex-col gap-0.5">+ <span className="text-xs text-muted">{label}</span>+ <div className="flex items-center gap-1.5">+ {loading ? (+ <LemonSkeleton className="w-12 h-4" />+ ) : (+ <span className="font-semibold text-sm">{value}</span>+ )}+ {chart}+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/experiments/notebook/NotebookCompactTable.tsx b/frontend/src/scenes/experiments/notebook/NotebookCompactTable.tsxnew file mode 100644index 000000000000..8ae85ad1ddd9--- /dev/null+++ b/frontend/src/scenes/experiments/notebook/NotebookCompactTable.tsx@@ -0,0 +1,79 @@+import { LemonTable, LemonTableColumns } from '@posthog/lemon-ui'++import {+ ExperimentMetric,+ isExperimentMeanMetric,+ isExperimentRatioMetric,+ NewExperimentQueryResponse,+} from '~/queries/schema/schema-general'+import { VariantTag } from '~/scenes/experiments/ExperimentView/components'+import {+ ExperimentVariantResult,+ formatChanceToWinForGoal,+ formatDeltaPercent,+ formatMetricValue,+ isBayesianResult,+} from '~/scenes/experiments/MetricsView/shared/utils'++type NotebookCompactTableProps = {+ result: NewExperimentQueryResponse+ metric: ExperimentMetric+}++type TableRow = ExperimentVariantResult & { key: string; isBaseline: boolean }++export function NotebookCompactTable({ result, metric }: NotebookCompactTableProps): JSX.Element {+ const goal = 'goal' in metric ? metric.goal : undefined++ const columns: LemonTableColumns<TableRow> = [+ {+ key: 'variant',+ title: 'Variant',+ render: (_, item) => <VariantTag variantKey={item.key} />,+ },+ {+ key: 'value',+ title: isExperimentMeanMetric(metric) ? 'Mean' : isExperimentRatioMetric(metric) ? 'Ratio' : 'Conversion',+ render: (_, item) => {+ const value = formatMetricValue(item, metric)+ const delta = item.isBaseline ? null : formatDeltaPercent(item)++ return (+ <div className="flex flex-col">+ <span className="font-semibold">{value}</span>+ {delta && (+ <span+ className={`text-xs ${+ delta.startsWith('+') ? 'text-success' : delta.startsWith('-') ? 'text-danger' : ''+ }`}+ >+ {delta}+ </span>+ )}+ {item.isBaseline && <span className="text-xs text-muted">Baseline</span>}+ </div>+ )+ },+ },+ {+ key: 'win_probability',+ title: 'Win prob.',+ render: (_, item) => {+ if (item.isBaseline) {+ return <span className="text-muted">—</span>+ }+ if (!isBayesianResult(item)) {+ return <span className="text-muted">—</span>+ }+ return <span className="font-semibold">{formatChanceToWinForGoal(item, goal)}</span>+ },+ },+ ]++ const dataSource: TableRow[] = [+ ...(result.baseline ? [{ ...result.baseline, key: 'control', isBaseline: true } as TableRow] : []),+ ...(result.variant_results?.map((v) => ({ ...v, isBaseline: false }) as TableRow) || []),+ ]++ return <LemonTable columns={columns} dataSource={dataSource} size="small" />+}diff --git a/frontend/src/scenes/experiments/notebook/NotebookExperimentComponent.tsx b/frontend/src/scenes/experiments/notebook/NotebookExperimentComponent.tsxnew file mode 100644index 000000000000..a1bcfb9b0511--- /dev/null+++ b/frontend/src/scenes/experiments/notebook/NotebookExperimentComponent.tsx@@ -0,0 +1,247 @@+import { BindLogic, useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { IconFlask } from '@posthog/icons'+import { LemonBanner, LemonDivider, LemonSkeleton } from '@posthog/lemon-ui'++import { NotFound } from 'lib/components/NotFound'+import { dayjs } from 'lib/dayjs'+import { humanFriendlyDiff, humanFriendlyNumber } from 'lib/utils'++import {+ CachedNewExperimentQueryResponse,+ ExperimentExposureQueryResponse,+ ExperimentMetric,+} from '~/queries/schema/schema-general'+import { ResultsTag } from '~/scenes/experiments/components/ResultsTag'+import { experimentLogic } from '~/scenes/experiments/experimentLogic'+import { getExperimentStatus } from '~/scenes/experiments/experimentsLogic'+import { StatusTag } from '~/scenes/experiments/ExperimentView/components'+import { MicroChart } from '~/scenes/experiments/ExperimentView/Exposures'+import { getChanceToWin, isBayesianResult } from '~/scenes/experiments/MetricsView/shared/utils'+import { isLegacyExperiment } from '~/scenes/experiments/utils'++import { ExperimentStatItem } from './ExperimentStatItem'+import { NotebookCompactTable } from './NotebookCompactTable'+import { NotebookWinningVariantSummary } from './NotebookWinningVariantSummary'++export interface NotebookExperimentComponentProps {+ id: number+ expanded: boolean+}++function formatDuration(startDate: string | null | undefined, endDate: string | null | undefined): string {+ if (!startDate) {+ return 'Not started'+ }+ const start = dayjs(startDate)+ const end = endDate ? dayjs(endDate) : dayjs()+ return humanFriendlyDiff(start, end)+}++function formatTotalExposures(exposures: ExperimentExposureQueryResponse | null): string {+ if (!exposures?.total_exposures) {+ return '0'+ }+ const total = Object.values(exposures.total_exposures).reduce((a, b) => a + b, 0)+ return humanFriendlyNumber(total)+}++interface MetricWithResult {+ metric: ExperimentMetric+ result: CachedNewExperimentQueryResponse+ index: number+ maxChanceToWin: number+ isSignificant: boolean+}++function findMostSignificantMetric(+ metrics: ExperimentMetric[] | undefined,+ results: CachedNewExperimentQueryResponse[] | undefined+): MetricWithResult | null {+ if (!metrics?.length || !results?.length) {+ return null+ }++ const metricsWithResults = metrics+ .map((metric, index) => {+ const result = results[index]+ if (!result?.variant_results?.length) {+ return null+ }++ const goal = 'goal' in metric ? metric.goal : undefined+ const isSignificant = result.variant_results.some((v) => v.significant)+ const maxChanceToWin = result.variant_results+ .filter(isBayesianResult)+ .map((v) => getChanceToWin(v, goal) ?? 0)+ .reduce((max, ctw) => Math.max(max, ctw), 0)++ return { metric, result, index, maxChanceToWin, isSignificant }+ })+ .filter((m): m is MetricWithResult => m !== null)++ if (metricsWithResults.length === 0) {+ return null+ }++ return metricsWithResults.reduce((best, current) => {+ if (current.isSignificant && !best.isSignificant) {+ return current+ }+ if (current.isSignificant === best.isSignificant && current.maxChanceToWin > best.maxChanceToWin) {+ return current+ }+ return best+ })+}++export function NotebookExperimentComponent({ id, expanded }: NotebookExperimentComponentProps): JSX.Element {+ const {+ experiment,+ experimentLoading,+ experimentMissing,+ isExperimentDraft,+ isExperimentLaunched,+ primaryMetricsResults,+ primaryMetricsResultsLoading,+ exposures,+ exposuresLoading,+ variants,+ } = useValues(experimentLogic({ experimentId: id }))++ const { loadExperiment, loadExposures } = useActions(experimentLogic({ experimentId: id }))++ useEffect(() => {+ loadExperiment()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [id])++ useEffect(() => {+ if (isExperimentLaunched && experiment && !isLegacyExperiment(experiment)) {+ loadExposures()+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isExperimentLaunched, experiment])++ if (experimentMissing) {+ return <NotFound object="experiment" />+ }++ const isLegacy = experiment && isLegacyExperiment(experiment)+ const status = experiment ? getExperimentStatus(experiment) : null+ const hasResults = primaryMetricsResults?.length > 0 && primaryMetricsResults[0]++ // Find the most significant primary metric to display+ const bestMetric = findMostSignificantMetric(+ experiment?.metrics as ExperimentMetric[] | undefined,+ primaryMetricsResults+ )+ const totalPrimaryMetrics = experiment?.metrics?.length || 0++ return (+ <div>+ <BindLogic logic={experimentLogic} props={{ experimentId: id }}>+ {/* Header */}+ <div className="flex items-center gap-2 p-3">+ <IconFlask className="text-lg shrink-0" />+ {experimentLoading ? (+ <LemonSkeleton className="h-6 flex-1" />+ ) : (+ <>+ <span className="flex-1 font-semibold truncate">{experiment.name}</span>+ {status && <StatusTag status={status} />}+ {isExperimentLaunched && hasResults && !isLegacy && bestMetric && (+ <ResultsTag isSignificant={bestMetric.isSignificant} />+ )}+ </>+ )}+ </div>++ {/* Expanded Content */}+ {expanded && !experimentLoading && (+ <>+ <LemonDivider className="my-0" />++ {/* Description */}+ {experiment.description && (+ <div className="px-3 pt-3 pb-1 text-sm">{experiment.description}</div>+ )}++ {/* Legacy experiment warning */}+ {isLegacy && (+ <div className="p-3">+ <LemonBanner type="warning">+ <div>+ <strong>Legacy experiment</strong>+ </div>+ <div>+ This experiment uses legacy metrics. Results are only available in the full+ experiment view.+ </div>+ </LemonBanner>+ </div>+ )}++ {/* Draft state */}+ {isExperimentDraft && !isLegacy && (+ <div className="p-3">+ <div className="text-sm text-muted mb-2">+ Experiment is in draft. Launch to start collecting data.+ </div>+ <div className="flex gap-4 text-sm text-muted">+ <span>{variants.length} variants</span>+ <span>{experiment.metrics?.length || 0} metrics</span>+ </div>+ </div>+ )}++ {/* Launched state with new metrics */}+ {isExperimentLaunched && !isLegacy && (+ <div className="p-3 space-y-3">+ {/* Stats row */}+ <div className="flex gap-6">+ <ExperimentStatItem+ label="Duration"+ value={formatDuration(experiment.start_date, experiment.end_date)}+ />+ <ExperimentStatItem+ label="Exposures"+ value={formatTotalExposures(exposures)}+ loading={exposuresLoading}+ chart={exposures ? <MicroChart exposures={exposures} /> : undefined}+ />+ <ExperimentStatItem label="Variants" value={variants.length} />+ </div>++ {/* Primary metric results - show most significant metric */}+ {primaryMetricsResultsLoading ? (+ <div className="space-y-2">+ <LemonSkeleton className="h-4 w-48" />+ <LemonSkeleton className="h-24 w-full" />+ </div>+ ) : bestMetric ? (+ <>+ {totalPrimaryMetrics > 1 && (+ <div className="text-xs text-muted mb-1">+ Showing most significant of {totalPrimaryMetrics} metrics+ {bestMetric.metric.name && `: ${bestMetric.metric.name}`}+ </div>+ )}+ <NotebookWinningVariantSummary+ result={bestMetric.result}+ metric={bestMetric.metric}+ />+ <NotebookCompactTable result={bestMetric.result} metric={bestMetric.metric} />+ </>+ ) : (+ <div className="text-sm text-muted">Collecting data...</div>+ )}+ </div>+ )}+ </>+ )}+ </BindLogic>+ </div>+ )+}diff --git a/frontend/src/scenes/experiments/notebook/NotebookWinningVariantSummary.tsx b/frontend/src/scenes/experiments/notebook/NotebookWinningVariantSummary.tsxnew file mode 100644index 000000000000..be8c97b45e7d--- /dev/null+++ b/frontend/src/scenes/experiments/notebook/NotebookWinningVariantSummary.tsx@@ -0,0 +1,66 @@+import { ExperimentMetric, NewExperimentQueryResponse } from '~/queries/schema/schema-general'++import { VariantTag } from '../ExperimentView/components'+import {+ ExperimentVariantResult,+ formatChanceToWinForGoal,+ getChanceToWin,+ isBayesianResult,+} from '../MetricsView/shared/utils'++type NotebookWinningVariantSummaryProps = {+ result: NewExperimentQueryResponse+ metric: ExperimentMetric+}++function getWinningVariant(+ result: NewExperimentQueryResponse,+ goal: 'increase' | 'decrease' | undefined+): { variantKey: string; chanceToWin: number } | null {+ if (!result.variant_results?.length) {+ return null+ }++ const winner = result.variant_results+ .filter(isBayesianResult)+ .map((variant) => ({+ variant,+ chanceToWin: getChanceToWin(variant, goal) ?? -1,+ }))+ .reduce<{ variant: ExperimentVariantResult; chanceToWin: number } | null>(+ (best, current) => (current.chanceToWin > (best?.chanceToWin ?? -1) ? current : best),+ null+ )++ if (!winner || winner.chanceToWin <= 0) {+ return null+ }++ return {+ variantKey: winner.variant.key,+ chanceToWin: winner.chanceToWin,+ }+}++export function NotebookWinningVariantSummary({ result, metric }: NotebookWinningVariantSummaryProps): JSX.Element {+ const goal = 'goal' in metric ? metric.goal : undefined+ const winning = getWinningVariant(result, goal)++ if (!winning) {+ return <div className="text-sm text-muted">Collecting data...</div>+ }++ const formattedChance = formatChanceToWinForGoal(+ result.variant_results.find((v) => v.key === winning.variantKey) as ExperimentVariantResult,+ goal+ )++ return (+ <div className="text-sm flex items-center gap-1 flex-wrap">+ <VariantTag variantKey={winning.variantKey} />+ <span>is winning with</span>+ <span className="font-semibold">{formattedChance}</span>+ <span>probability</span>+ </div>+ )+}diff --git a/frontend/src/scenes/experiments/notebook/index.ts b/frontend/src/scenes/experiments/notebook/index.tsnew file mode 100644index 000000000000..45aae0fd1126--- /dev/null+++ b/frontend/src/scenes/experiments/notebook/index.ts@@ -0,0 +1 @@+export { NotebookExperimentComponent } from './NotebookExperimentComponent'diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeExperiment.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeExperiment.tsxindex 072056b097de..414bde269fc2 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeExperiment.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeExperiment.tsx@@ -1,84 +1,18 @@-import { BindLogic, useActions, useValues } from 'kea'-import { useEffect } from 'react'+import { useValues } from 'kea'-import { IconFlag, IconFlask } from '@posthog/icons'-import { LemonDivider } from '@posthog/lemon-ui'+import { NotebookExperimentComponent } from '~/scenes/experiments/notebook'+import { createPostHogWidgetNode } from '~/scenes/notebooks/Nodes/NodeWrapper'+import { type NotebookNodeProps, NotebookNodeType } from '~/scenes/notebooks/types'+import { urls } from '~/scenes/urls'-import { NotFound } from 'lib/components/NotFound'-import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'-import { experimentLogic } from 'scenes/experiments/experimentLogic'-import { getExperimentStatus } from 'scenes/experiments/experimentsLogic'-import { StatusTag } from 'scenes/experiments/ExperimentView/components'-import { Info } from 'scenes/experiments/ExperimentView/Info'-import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'-import { urls } from 'scenes/urls'--import { NotebookNodeProps, NotebookNodeType } from '../types'-import { buildFlagContent } from './NotebookNodeFlag'import { notebookNodeLogic } from './notebookNodeLogic'import { INTEGER_REGEX_MATCH_GROUPS, OPTIONAL_PROJECT_NON_CAPTURE_GROUP } from './utils'const Component = ({ attributes }: NotebookNodeProps<NotebookNodeExperimentAttributes>): JSX.Element => {const { id } = attributes- const { experiment, experimentLoading, experimentMissing } = useValues(experimentLogic({ experimentId: id }))- const { loadExperiment } = useActions(experimentLogic({ experimentId: id }))const { expanded } = useValues(notebookNodeLogic)- const { insertAfter, setActions } = useActions(notebookNodeLogic)-- useEffect(() => {- setActions([- {- text: 'View feature flag',- icon: <IconFlag />,- onClick: () => insertAfter(buildFlagContent(experiment.feature_flag?.id || 'new')),- },- ])-- loadExperiment()-- // oxlint-disable-next-line exhaustive-deps- }, [id])-- if (experimentMissing) {- return <NotFound object="experiment" />- }-- return (- <div>- <BindLogic logic={experimentLogic} props={{ experimentId: id }}>- <div className="flex items-center gap-2 p-3">- <IconFlask className="text-lg" />- {experimentLoading ? (- <LemonSkeleton className="h-6 flex-1" />- ) : (- <>- <span className="flex-1 font-semibold truncate">{experiment.name}</span>- <StatusTag status={getExperimentStatus(experiment)} />- </>- )}- </div>- {expanded ? (- <>- {experiment.description && (- <>- <LemonDivider className="my-0" />- <span className="p-2">{experiment.description}</span>- </>- )}- {!experiment.start_date && (- <>- <LemonDivider className="my-0" />- <div className="p-2">- <Info />- </div>- </>- )}- </>- ) : null}- </BindLogic>- </div>- )+ return <NotebookExperimentComponent id={id} expanded={expanded} />}type NotebookNodeExperimentAttributes = {