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(desktop): show experiment results in artifacts (#90183)

Shy Alter5b88a7527968
diff --git a/products/desktop/packages/api-client/src/evidence-previews.test.ts b/products/desktop/packages/api-client/src/evidence-previews.test.ts
index be938e05eb19..ac81902b7438 100644
--- a/products/desktop/packages/api-client/src/evidence-previews.test.ts
+++ b/products/desktop/packages/api-client/src/evidence-previews.test.ts
@@ -16,6 +16,7 @@ import {
shapeEvaluationPreview,
shapeEventDefinitionPreview,
shapeExperimentPreview,
+ shapeExperimentResults,
shapeFlagPreview,
shapePersonPreview,
shapeRecordingPreview,
@@ -27,6 +28,257 @@ import type { Schemas } from "./generated";
// The shapers only read the fields they show; build minimal inputs and cast.
describe("evidence preview shaping", () => {
+ const experimentWithMetrics = (
+ overrides: Partial<Schemas.Experiment> = {},
+ ): Schemas.Experiment =>
+ ({
+ id: 1234,
+ name: "Checkout prompt",
+ feature_flag_key: "checkout-prompt",
+ feature_flag: { id: 3, key: "checkout-prompt" },
+ start_date: "2026-01-01T00:00:00Z",
+ metrics: [
+ {
+ kind: "ExperimentMetric",
+ uuid: "primary-1",
+ name: "Checkout conversion",
+ metric_type: "funnel",
+ },
+ ],
+ metrics_secondary: [
+ {
+ kind: "ExperimentMetric",
+ uuid: "secondary-1",
+ name: "Orders per user",
+ metric_type: "mean",
+ },
+ ],
+ saved_metrics: [],
+ ...overrides,
+ }) as unknown as Schemas.Experiment;
+
+ const exposureResponse = {
+ kind: "ExperimentExposureQuery",
+ timeseries: [],
+ total_exposures: { control: 1050, test: 1020 },
+ date_range: { date_from: "2026-01-01", date_to: null },
+ } as Schemas.ExperimentExposureQueryResponse;
+
+ const readyMetricResponse = {
+ kind: "ExperimentQuery",
+ baseline: {
+ key: "control",
+ number_of_samples: 1000,
+ sum: 100,
+ sum_squares: 100,
+ },
+ variant_results: [
+ {
+ key: "test",
+ method: "frequentist",
+ number_of_samples: 1000,
+ sum: 125,
+ sum_squares: 125,
+ confidence_interval: [0.05, 0.45],
+ p_value: 0.02,
+ significant: true,
+ },
+ ],
+ significance_code: "significant",
+ is_cached: true,
+ last_refresh: new Date().toISOString(),
+ } as unknown as Schemas.ExperimentQueryResponse;
+
+ it("shapes running experiment results with primary and secondary metrics", () => {
+ const results = shapeExperimentResults(
+ experimentWithMetrics(),
+ exposureResponse,
+ [{ response: readyMetricResponse }],
+ [{ response: readyMetricResponse }],
+ );
+
+ expect(results.state).toBe("ready");
+ expect(results.primaryMetrics[0]).toMatchObject({
+ name: "Checkout conversion",
+ metricType: "primary",
+ outcomeLabel: "Conversions",
+ state: "ready",
+ bestVariant: {
+ key: "test",
+ uplift: "+25.0%",
+ significance: "significant",
+ isImprovement: true,
+ },
+ variants: [
+ {
+ key: "control",
+ outcome: "100 · 10.0%",
+ sampleContext: "1K samples · 1.1K exposed",
+ uplift: null,
+ upliftDirection: null,
+ isImprovement: null,
+ },
+ {
+ key: "test",
+ outcome: "125 · 12.5%",
+ sampleContext: "1K samples · 1K exposed",
+ uplift: "+25.0%",
+ upliftDirection: "positive",
+ isImprovement: true,
+ interval: "+5.00% to +45.0%",
+ pValue: "0.020",
+ significance: "significant",
+ },
+ ],
+ });
+ expect(results.secondaryMetrics[0]).toMatchObject({
+ name: "Orders per user",
+ metricType: "secondary",
+ });
+ });
+
+ it("selects the strongest variant using a decrease metric's goal", () => {
+ const experiment = experimentWithMetrics({
+ metrics: [
+ {
+ kind: "ExperimentMetric",
+ uuid: "primary-1",
+ name: "Support requests",
+ metric_type: "mean",
+ goal: "decrease",
+ },
+ ],
+ metrics_secondary: [],
+ } as unknown as Partial<Schemas.Experiment>);
+ const response = {
+ ...readyMetricResponse,
+ baseline: {
+ key: "control",
+ number_of_samples: 100,
+ sum: 100,
+ sum_squares: 100,
+ },
+ variant_results: [
+ {
+ key: "fewer-requests",
+ number_of_samples: 100,
+ sum: 80,
+ sum_squares: 80,
+ significant: true,
+ },
+ {
+ key: "more-requests",
+ number_of_samples: 100,
+ sum: 120,
+ sum_squares: 120,
+ significant: true,
+ },
+ ],
+ } as unknown as Schemas.ExperimentQueryResponse;
+
+ const results = shapeExperimentResults(
+ experiment,
+ exposureResponse,
+ [{ response }],
+ [],
+ );
+
+ expect(results.primaryMetrics[0].bestVariant).toMatchObject({
+ key: "fewer-requests",
+ uplift: "-20.0%",
+ isImprovement: true,
+ });
+ });
+
+ it("keeps a draft experiment distinct from missing results", () => {
+ const results = shapeExperimentResults(
+ experimentWithMetrics({ start_date: null }),
+ null,
+ [],
+ [],
+ );
+
+ expect(results.state).toBe("draft");
+ expect(results.primaryMetrics).toHaveLength(1);
+ expect(results.primaryMetrics[0].state).toBe("insufficient_data");
+ expect(results.secondaryMetrics).toHaveLength(1);
+ });
+
+ it("marks an old cached result as stale while the experiment is running", () => {
+ const oldResponse = {
+ ...readyMetricResponse,
+ last_refresh: "2020-01-01T00:00:00Z",
+ } as unknown as Schemas.ExperimentQueryResponse;
+ const results = shapeExperimentResults(
+ experimentWithMetrics(),
+ exposureResponse,
+ [{ response: oldResponse }],
+ [{ response: oldResponse }],
+ );
+
+ expect(results.stale).toBe(true);
+ expect(results.lastRefresh).toBe("2020-01-01T00:00:00Z");
+ });
+
+ it("does not mark final completed results as stale", () => {
+ const oldResponse = {
+ ...readyMetricResponse,
+ last_refresh: "2025-01-01T00:00:00Z",
+ } as unknown as Schemas.ExperimentQueryResponse;
+ const results = shapeExperimentResults(
+ experimentWithMetrics({ end_date: "2026-01-15T00:00:00Z" }),
+ exposureResponse,
+ [{ response: oldResponse }],
+ [{ response: oldResponse }],
+ );
+
+ expect(results.state).toBe("ready");
+ expect(results.stale).toBe(false);
+ });
+
+ it("preserves a failed metric query in its configured position", () => {
+ const results = shapeExperimentResults(
+ experimentWithMetrics(),
+ exposureResponse,
+ [{ response: null }],
+ [{ response: readyMetricResponse }],
+ );
+
+ expect(results.state).toBe("error");
+ expect(results.primaryMetrics[0]).toMatchObject({
+ name: "Checkout conversion",
+ state: "error",
+ error: "Couldn't calculate this metric.",
+ });
+ expect(results.secondaryMetrics[0].state).toBe("ready");
+ });
+
+ it("shows outcomes while marking low-exposure results as insufficient", () => {
+ const insufficientResponse = {
+ ...readyMetricResponse,
+ significance_code: "not_enough_exposure",
+ significant: false,
+ } as unknown as Schemas.ExperimentQueryResponse;
+ const results = shapeExperimentResults(
+ experimentWithMetrics(),
+ exposureResponse,
+ [{ response: insufficientResponse }],
+ [{ response: insufficientResponse }],
+ );
+
+ expect(results.state).toBe("insufficient_data");
+ expect(results.primaryMetrics[0]).toMatchObject({
+ state: "insufficient_data",
+ variants: [
+ expect.any(Object),
+ expect.objectContaining({
+ outcome: "125 · 12.5%",
+ significance: "insufficient_data",
+ }),
+ ],
+ });
+ });
+
it("keys the flag preview by key and carries the numeric id for links", () => {
const preview = shapeFlagPreview({
id: 42,
diff --git a/products/desktop/packages/api-client/src/evidence-previews.ts b/products/desktop/packages/api-client/src/evidence-previews.ts
index 111acd8737b9..65daa29a932d 100644
--- a/products/desktop/packages/api-client/src/evidence-previews.ts
+++ b/products/desktop/packages/api-client/src/evidence-previews.ts
@@ -18,6 +18,57 @@ export interface EvidenceDetailSection {
fields: EvidenceDetailField[];
}
+export type ExperimentResultState =
+ | "ready"
+ | "draft"
+ | "error"
+ | "insufficient_data";
+
+export interface ExperimentVariantResultPresentation {
+ key: string;
+ isControl: boolean;
+ outcome: string;
+ sampleContext: string;
+ uplift: string | null;
+ upliftValue: number | null;
+ intervalBounds: [number, number] | null;
+ upliftDirection: "positive" | "negative" | null;
+ isImprovement: boolean | null;
+ interval: string | null;
+ pValue: string | null;
+ chanceToWin: string | null;
+ significance: "significant" | "not_significant" | "insufficient_data" | null;
+}
+
+export interface ExperimentMetricResultPresentation {
+ id: string;
+ name: string;
+ metricType: "primary" | "secondary";
+ state: "ready" | "error" | "insufficient_data";
+ error: string | null;
+ outcomeLabel: string;
+ axisRange: number | null;
+ bestVariant: {
+ key: string;
+ uplift: string;
+ significance: ExperimentVariantResultPresentation["significance"];
+ isImprovement: boolean | null;
+ } | null;
+ variants: ExperimentVariantResultPresentation[];
+}
+
+export interface ExperimentResultsPresentation {
+ state: ExperimentResultState;
+ stale: boolean;
+ lastRefresh: string | null;
+ primaryMetrics: ExperimentMetricResultPresentation[];
+ secondaryMetrics: ExperimentMetricResultPresentation[];
+}
+
+export interface ExperimentMetricQueryResult {
+ response: Schemas.ExperimentQueryResponse | null;
+}
+
export interface EvidencePreview {
/** The object's name in PostHog. */
title: string;
@@ -55,6 +106,7 @@ export interface EvidencePreview {
render: "line" | "bar";
};
sections?: EvidenceDetailSection[];
+ experimentResults?: ExperimentResultsPresentation;
/**
* A dashboard's tiles, each resolvable to a live insight chart, so a full
* page can render the metrics themselves rather than describe them.
@@ -443,6 +495,438 @@ export function shapeExperimentPreview(
};
}
+interface ExperimentMetricDefinition {
+ query: unknown;
+ id: string;
+ name: string;
+ metricType: "primary" | "secondary";
+ valueType: string | null;
+ goal: string | null;
+}
+
+function metricName(metric: QueryRecord, index: number): string {
+ const directName = conciseValue(metric.name);
+ if (directName) return directName;
+ for (const field of [
+ "source",
+ "completion_event",
+ "start_event",
+ "numerator",
+ ]) {
+ const source = metric[field];
+ if (isRecord(source)) {
+ const eventName = conciseValue(source.event) ?? conciseValue(source.name);
+ if (eventName) return eventName;
+ }
+ }
+ return `Metric ${index + 1}`;
+}
+
+function metricUuid(metric: QueryRecord, fallback: string): string {
+ return conciseValue(metric.uuid) ?? fallback;
+}
+
+function orderedMetricDefinitions(
+ experiment: Schemas.Experiment,
+ metricType: "primary" | "secondary",
+): ExperimentMetricDefinition[] {
+ const inlineMetrics = ((metricType === "primary"
+ ? experiment.metrics
+ : experiment.metrics_secondary) ?? []) as unknown[];
+ const definitions: ExperimentMetricDefinition[] = inlineMetrics.flatMap(
+ (metric, index) =>
+ isRecord(metric)
+ ? [
+ {
+ query: metric,
+ id: metricUuid(metric, `${metricType}-${index}`),
+ name: metricName(metric, index),
+ metricType,
+ valueType: conciseValue(metric.metric_type),
+ goal: conciseValue(metric.goal),
+ },
+ ]
+ : [],
+ );
+
+ for (const savedMetric of experiment.saved_metrics ?? []) {
+ const metadata = isRecord(savedMetric.metadata) ? savedMetric.metadata : {};
+ if (metadata.type !== metricType || !isRecord(savedMetric.query)) continue;
+ definitions.push({
+ query: savedMetric.query,
+ id: metricUuid(
+ savedMetric.query,
+ `${metricType}-saved-${savedMetric.saved_metric}`,
+ ),
+ name:
+ savedMetric.name || metricName(savedMetric.query, definitions.length),
+ metricType,
+ valueType: conciseValue(savedMetric.query.metric_type),
+ goal: conciseValue(savedMetric.query.goal),
+ });
+ }
+
+ const experimentRecord = experiment as unknown as QueryRecord;
+ const orderKey =
+ metricType === "primary"
+ ? "primary_metrics_ordered_uuids"
+ : "secondary_metrics_ordered_uuids";
+ const orderedUuids = Array.isArray(experimentRecord[orderKey])
+ ? (experimentRecord[orderKey] as unknown[]).filter(
+ (uuid): uuid is string => typeof uuid === "string",
+ )
+ : [];
+ if (orderedUuids.length === 0) return definitions;
+ const position = new Map(orderedUuids.map((uuid, index) => [uuid, index]));
+ return definitions
+ .map((definition, index) => ({ definition, index }))
+ .sort(
+ (left, right) =>
+ (position.get(left.definition.id) ?? orderedUuids.length + left.index) -
+ (position.get(right.definition.id) ??
+ orderedUuids.length + right.index),
+ )
+ .map(({ definition }) => definition);
+}
+
+export function experimentMetricQueries(
+ experiment: Schemas.Experiment,
+ metricType: "primary" | "secondary",
+): unknown[] {
+ return orderedMetricDefinitions(experiment, metricType).map(
+ (definition) => definition.query,
+ );
+}
+
+function formatPercent(value: number, includeSign = false): string {
+ const percentage = value * 100;
+ const sign = includeSign && percentage > 0 ? "+" : "";
+ return `${sign}${Math.abs(percentage) >= 10 ? percentage.toFixed(1) : percentage.toFixed(2)}%`;
+}
+
+function formatPValue(value: number): string {
+ return value < 0.001 ? "< 0.001" : value.toFixed(3);
+}
+
+function validInterval(value: unknown): [number, number] | null {
+ if (!Array.isArray(value) || value.length !== 2) return null;
+ const lower = cellNumber(value[0]);
+ const upper = cellNumber(value[1]);
+ return lower === null || upper === null ? null : [lower, upper];
+}
+
+function outcomeValue(
+ stats: Schemas.ExperimentStatsBaseValidated,
+ valueType: string | null,
+): { label: string; comparable: number | null; display: string } {
+ const samples = stats.number_of_samples;
+ const mean = samples > 0 ? stats.sum / samples : null;
+ if (valueType === "funnel" || valueType === "retention") {
+ return {
+ label: valueType === "retention" ? "Retained" : "Conversions",
+ comparable: mean,
+ display: `${compactCount(stats.sum)} · ${mean === null ? "No rate" : formatPercent(mean)}`,
+ };
+ }
+ if (valueType === "ratio") {
+ const denominator = cellNumber(stats.denominator_sum);
+ const ratio =
+ denominator && denominator !== 0 ? stats.sum / denominator : null;
+ return {
+ label: "Ratio",
+ comparable: ratio,
+ display: `${compactCount(stats.sum)} numerator · ${ratio === null ? "No ratio" : ratio.toFixed(2)}`,
+ };
+ }
+ return {
+ label: "Outcome",
+ comparable: mean,
+ display: `${compactCount(stats.sum)} total · ${mean === null ? "No mean" : `${compactCount(mean)} per sample`}`,
+ };
+}
+
+function hasInsufficientData(
+ response: Schemas.ExperimentQueryResponse,
+ stats: Schemas.ExperimentStatsBaseValidated[],
+): boolean {
+ if (response.significance_code === "not_enough_exposure") return true;
+ return stats.some((entry) =>
+ (entry.validation_failures ?? []).some(
+ (failure) =>
+ failure === "not-enough-exposures" ||
+ failure === "not-enough-metric-data",
+ ),
+ );
+}
+
+const MIN_AXIS_RANGE = 0.05;
+const MAX_AXIS_RANGE = 1.5;
+
+function deltaAxisRange(
+ rows: ExperimentVariantResultPresentation[],
+): number | null {
+ const bounds = rows.flatMap((row) =>
+ row.intervalBounds ? row.intervalBounds.map(Math.abs) : [],
+ );
+ if (bounds.length === 0) return null;
+ return Math.min(MAX_AXIS_RANGE, Math.max(MIN_AXIS_RANGE, ...bounds));
+}
+
+function shapeMetricResult(
+ definition: ExperimentMetricDefinition,
+ queryResult: ExperimentMetricQueryResult | undefined,
+ exposures: Record<string, number>,
+ experimentStarted: boolean,
+): ExperimentMetricResultPresentation {
+ const response = queryResult?.response;
+ if (!experimentStarted) {
+ return {
+ id: definition.id,
+ name: definition.name,
+ metricType: definition.metricType,
+ state: "insufficient_data",
+ error: null,
+ outcomeLabel: "Outcome",
+ axisRange: null,
+ bestVariant: null,
+ variants: [],
+ };
+ }
+ if (!response) {
+ return {
+ id: definition.id,
+ name: definition.name,
+ metricType: definition.metricType,
+ state: "error",
+ error: "Couldn't calculate this metric.",
+ outcomeLabel: "Outcome",
+ axisRange: null,
+ bestVariant: null,
+ variants: [],
+ };
+ }
+
+ const baseline = response.baseline;
+ const variants = response.variant_results ?? [];
+ if (!baseline || variants.length === 0) {
+ return {
+ id: definition.id,
+ name: definition.name,
+ metricType: definition.metricType,
+ state: "insufficient_data",
+ error: null,
+ outcomeLabel: "Outcome",
+ axisRange: null,
+ bestVariant: null,
+ variants: [],
+ };
+ }
+
+ const baselineOutcome = outcomeValue(baseline, definition.valueType);
+ const allStats = [baseline, ...variants];
+ const insufficient = hasInsufficientData(response, allStats);
+ const upliftedRows: Array<{
+ row: ExperimentVariantResultPresentation;
+ value: number;
+ }> = [];
+ const rows = allStats.map((stats, index) => {
+ const outcome = outcomeValue(stats, definition.valueType);
+ const isControl = index === 0;
+ const statsRecord = stats as unknown as QueryRecord;
+ const interval = validInterval(
+ statsRecord.confidence_interval ??
+ statsRecord.credible_interval ??
+ response.credible_intervals?.[stats.key],
+ );
+ const pValue = cellNumber(
+ statsRecord.p_value ?? (variants.length === 1 ? response.p_value : null),
+ );
+ const chanceToWin = cellNumber(
+ statsRecord.chance_to_win ?? response.probability?.[stats.key],
+ );
+ const significantValue =
+ typeof statsRecord.significant === "boolean"
+ ? statsRecord.significant
+ : variants.length === 1 && typeof response.significant === "boolean"
+ ? response.significant
+ : null;
+ const uplift =
+ !isControl &&
+ outcome.comparable !== null &&
+ baselineOutcome.comparable !== null &&
+ baselineOutcome.comparable !== 0
+ ? outcome.comparable / baselineOutcome.comparable - 1
+ : null;
+ const builtRow: ExperimentVariantResultPresentation = {
+ key: stats.key,
+ isControl,
+ outcome: outcome.display,
+ sampleContext: [
+ `${compactCount(stats.number_of_samples)} samples`,
+ typeof exposures[stats.key] === "number"
+ ? `${compactCount(exposures[stats.key])} exposed`
+ : null,
+ ]
+ .filter(Boolean)
+ .join(" · "),
+ uplift: isControl || uplift === null ? null : formatPercent(uplift, true),
+ upliftValue: isControl ? null : uplift,
+ intervalBounds:
+ isControl || !interval ? null : [interval[0], interval[1]],
+ upliftDirection:
+ uplift === null || uplift === 0
+ ? null
+ : uplift > 0
+ ? ("positive" as const)
+ : ("negative" as const),
+ isImprovement:
+ uplift === null || uplift === 0
+ ? null
+ : definition.goal === "decrease"
+ ? uplift < 0
+ : uplift > 0,
+ interval:
+ isControl || !interval
+ ? null
+ : `${formatPercent(interval[0], true)} to ${formatPercent(interval[1], true)}`,
+ pValue: isControl || pValue === null ? null : formatPValue(pValue),
+ chanceToWin:
+ isControl || chanceToWin === null ? null : formatPercent(chanceToWin),
+ significance: isControl
+ ? null
+ : insufficient
+ ? ("insufficient_data" as const)
+ : significantValue === null
+ ? null
+ : significantValue
+ ? ("significant" as const)
+ : ("not_significant" as const),
+ };
+ if (uplift !== null) {
+ upliftedRows.push({ row: builtRow, value: uplift });
+ }
+ return builtRow;
+ });
+ const best = upliftedRows.reduce<{
+ row: ExperimentVariantResultPresentation;
+ value: number;
+ } | null>((leader, entry) => {
+ if (!leader) return entry;
+ const isBetter =
+ definition.goal === "decrease"
+ ? entry.value < leader.value
+ : entry.value > leader.value;
+ return isBetter ? entry : leader;
+ }, null);
+
+ return {
+ id: definition.id,
+ name: definition.name,
+ metricType: definition.metricType,
+ state: insufficient ? "insufficient_data" : "ready",
+ error: null,
+ outcomeLabel: baselineOutcome.label,
+ axisRange: deltaAxisRange(rows),
+ bestVariant: best
+ ? {
+ key: best.row.key,
+ uplift: formatPercent(best.value, true),
+ significance: best.row.significance,
+ isImprovement: best.row.isImprovement,
+ }
+ : null,
+ variants: rows,
+ };
+}
+
+export function shapeExperimentExposureChart(
+ response: Schemas.ExperimentExposureQueryResponse | null,
+): EvidencePreview["chart"] {
+ if (!response) return undefined;
+ const rows = response.timeseries.flatMap((series) =>
+ series.days.map((day, index) => [
+ day,
+ series.variant,
+ series.exposure_counts[index] ?? 0,
+ ]),
+ );
+ const pivot = pivotDailyGroups(rows);
+ if (!pivot) return undefined;
+ return {
+ title:
+ pivot.omittedGroups > 0
+ ? `Daily exposures by variant (top ${pivot.series.length} of ${pivot.series.length + pivot.omittedGroups})`
+ : "Daily exposures by variant",
+ labels: pivot.labels,
+ series: pivot.series,
+ render: "bar",
+ };
+}
+
+export function shapeExperimentResults(
+ experiment: Schemas.Experiment,
+ exposuresResponse: Schemas.ExperimentExposureQueryResponse | null,
+ primaryResults: ExperimentMetricQueryResult[],
+ secondaryResults: ExperimentMetricQueryResult[],
+): ExperimentResultsPresentation {
+ const primaryMetrics = orderedMetricDefinitions(experiment, "primary").map(
+ (definition, index) =>
+ shapeMetricResult(
+ definition,
+ primaryResults[index],
+ exposuresResponse?.total_exposures ?? {},
+ !!experiment.start_date,
+ ),
+ );
+ const secondaryMetrics = orderedMetricDefinitions(
+ experiment,
+ "secondary",
+ ).map((definition, index) =>
+ shapeMetricResult(
+ definition,
+ secondaryResults[index],
+ exposuresResponse?.total_exposures ?? {},
+ !!experiment.start_date,
+ ),
+ );
+ const metrics = [...primaryMetrics, ...secondaryMetrics];
+ const responses = [...primaryResults, ...secondaryResults]
+ .map((result) => result.response as unknown as QueryRecord | null)
+ .filter((response): response is QueryRecord => response !== null);
+ const refreshTimes = responses.flatMap((response) => {
+ const lastRefresh = conciseValue(response.last_refresh);
+ return lastRefresh ? [lastRefresh] : [];
+ });
+ const staleRefreshTimes = experiment.end_date
+ ? []
+ : responses.flatMap((response) => {
+ const lastRefresh = conciseValue(response.last_refresh);
+ if (response.is_cached !== true || !lastRefresh) return [];
+ const refreshedAt = new Date(lastRefresh).getTime();
+ return Number.isFinite(refreshedAt) &&
+ Date.now() - refreshedAt > 24 * 60 * 60 * 1000
+ ? [lastRefresh]
+ : [];
+ });
+ const state: ExperimentResultState = !experiment.start_date
+ ? "draft"
+ : metrics.some((metric) => metric.state === "error")
+ ? "error"
+ : metrics.length === 0 ||
+ metrics.every((metric) => metric.state === "insufficient_data")
+ ? "insufficient_data"
+ : "ready";
+
+ return {
+ state,
+ stale: staleRefreshTimes.length > 0,
+ lastRefresh:
+ staleRefreshTimes.sort()[0] ?? refreshTimes.sort().at(-1) ?? null,
+ primaryMetrics,
+ secondaryMetrics,
+ };
+}
+
const EVALUATION_TYPE_LABELS: Record<string, string> = {
llm_judge: "LLM judge",
hog: "Hog",
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.ts
index 74453b23b3c0..25eb19b8c3be 100644
--- a/products/desktop/packages/api-client/src/posthog-client.test.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts
@@ -114,6 +114,143 @@ describe("PostHogAPIClient", () => {
});
describe("getEvidencePreview", () => {
+ it("builds experiment presentation data from metric and exposure query responses", async () => {
+ const metricResponse = {
+ kind: "ExperimentQuery",
+ baseline: {
+ key: "control",
+ number_of_samples: 100,
+ sum: 10,
+ sum_squares: 10,
+ },
+ variant_results: [
+ {
+ key: "test",
+ method: "frequentist",
+ number_of_samples: 100,
+ sum: 12,
+ sum_squares: 12,
+ p_value: 0.04,
+ significant: true,
+ confidence_interval: [0.01, 0.39],
+ },
+ ],
+ significance_code: "significant",
+ is_cached: true,
+ last_refresh: new Date().toISOString(),
+ };
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ id: 1234,
+ name: "Checkout prompt",
+ feature_flag_key: "checkout-prompt",
+ feature_flag: { id: 3, key: "checkout-prompt" },
+ start_date: "2026-01-01T00:00:00Z",
+ metrics: [
+ {
+ kind: "ExperimentMetric",
+ uuid: "primary-1",
+ name: "Checkout conversion",
+ metric_type: "funnel",
+ },
+ ],
+ metrics_secondary: [
+ {
+ kind: "ExperimentMetric",
+ uuid: "secondary-1",
+ name: "Orders per user",
+ metric_type: "mean",
+ },
+ ],
+ saved_metrics: [],
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ )
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ kind: "ExperimentExposureQuery",
+ timeseries: [
+ {
+ variant: "control",
+ days: ["2026-01-01", "2026-01-02"],
+ exposure_counts: [45, 60],
+ },
+ {
+ variant: "test",
+ days: ["2026-01-01", "2026-01-02"],
+ exposure_counts: [43, 60],
+ },
+ ],
+ total_exposures: { control: 105, test: 103 },
+ date_range: { date_from: "2026-01-01", date_to: null },
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify(metricResponse), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify(metricResponse), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ const client = new PostHogAPIClient(
+ "https://app.posthog.test",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch },
+ );
+
+ const preview = await client.getEvidencePreview("experiment", "1234");
+
+ expect(preview).toMatchObject({
+ chart: {
+ title: "Daily exposures by variant",
+ labels: ["2026-01-01", "2026-01-02"],
+ series: [
+ { label: "control", data: [45, 60] },
+ { label: "test", data: [43, 60] },
+ ],
+ render: "bar",
+ },
+ });
+ expect(preview?.experimentResults).toMatchObject({
+ state: "ready",
+ primaryMetrics: [
+ {
+ name: "Checkout conversion",
+ variants: [
+ expect.objectContaining({ key: "control" }),
+ expect.objectContaining({ key: "test", uplift: "+20.0%" }),
+ ],
+ },
+ ],
+ secondaryMetrics: [{ name: "Orders per user" }],
+ });
+ const queryBodies = fetch.mock.calls
+ .slice(1)
+ .map((call) => JSON.parse(String((call[1] as RequestInit).body)));
+ expect(queryBodies.map((body) => body.query.kind)).toEqual([
+ "ExperimentExposureQuery",
+ "ExperimentQuery",
+ "ExperimentQuery",
+ ]);
+ expect(queryBodies.every((body) => body.refresh === undefined)).toBe(
+ true,
+ );
+ });
+
it("retrieves a person by UUID instead of taking the first search result", async () => {
const fetch = vi.fn().mockResolvedValue(
new Response(
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 24b950452a13..c0ca1ff751ea 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -79,18 +79,20 @@ import {
decorateFlagPreview,
decorateSurveyPreview,
type EvidencePreview,
- exposureFact,
+ type ExperimentMetricQueryResult,
+ experimentMetricQueries,
formatDay,
gridRows,
hogqlEscape,
- pivotDailyGroups,
shapeActionPreview,
shapeCohortPreview,
shapeDashboardPreview,
shapeErrorIssuePreview,
shapeEvaluationPreview,
shapeEventDefinitionPreview,
+ shapeExperimentExposureChart,
shapeExperimentPreview,
+ shapeExperimentResults,
shapeFlagPreview,
shapePersonPreview,
shapeRecordingPreview,
@@ -6529,25 +6531,20 @@ export class PostHogAPIClient {
return { results: data.results ?? [], columns: data.columns ?? [] };
}
- /**
- * Runs an arbitrary typed query node (TrendsQuery, HogQLQuery, ...) against
- * the team's project and returns the raw response. `refresh: "blocking"`
- * serves a fresh-enough cached result and computes synchronously otherwise —
- * the same mode PostHog insights use. Backs inbox report charts, whose query
- * nodes are scout-authored and arrive unparsed.
- */
async runQuery(
query: Record<string, unknown>,
+ options?: { refresh?: "blocking" | false },
): Promise<Record<string, unknown>> {
const teamId = await this.getTeamId();
const path = `/api/projects/${teamId}/query/`;
const url = new URL(`${this.api.baseUrl}${path}`);
+ const refresh = options?.refresh === false ? null : "blocking";
const response = await this.api.fetcher.fetch({
method: "post",
url,
path,
overrides: {
- body: JSON.stringify({ query, refresh: "blocking" }),
+ body: JSON.stringify({ query, ...(refresh ? { refresh } : {}) }),
},
});
const data = (await response.json()) as Record<string, unknown>;
@@ -6652,54 +6649,74 @@ export class PostHogAPIClient {
{ path: { project_id: projectId, id: numericId } },
);
const preview = shapeExperimentPreview(experiment);
- // Depth: unique persons exposed per variant, showing the experiment
- // is collecting and roughly balanced.
- if (!experiment.start_date || !experiment.feature_flag_key) {
- return preview;
- }
- const until = experiment.end_date
- ? ` AND timestamp <= parseDateTimeBestEffort('${hogqlEscape(experiment.end_date)}')`
- : "";
- const scope = `event = '$feature_flag_called' AND properties.$feature_flag = '${hogqlEscape(experiment.feature_flag_key)}' AND timestamp >= parseDateTimeBestEffort('${hogqlEscape(experiment.start_date)}')${until}`;
- const [exposures, dailyExposures] = await Promise.all([
- this.runQuery({
- kind: "HogQLQuery",
- query: `SELECT toString(properties.$feature_flag_response) AS variant, uniq(person_id) FROM events WHERE ${scope} GROUP BY variant ORDER BY variant`,
- }).catch(() => ({})),
- this.runQuery({
- kind: "HogQLQuery",
- query: `SELECT toDate(timestamp) AS day, toString(properties.$feature_flag_response) AS variant, uniq(person_id) FROM events WHERE ${scope} GROUP BY day, variant ORDER BY day`,
- }).catch(() => ({})),
- ]);
- const fact = exposureFact(gridRows(exposures));
- // "false" rows are flag evaluations outside the experiment, not a variant.
- const pivot = pivotDailyGroups(
- gridRows(dailyExposures).filter((row) => String(row[1]) !== "false"),
+ const primaryQueries = experimentMetricQueries(experiment, "primary");
+ const secondaryQueries = experimentMetricQueries(
+ experiment,
+ "secondary",
);
- const variantStats = gridRows(exposures)
- .filter((row) => typeof row[0] === "string" && row[0] !== "false")
- .slice(0, 4)
- .map((row) => ({
- label: `${row[0]} exposed`,
- value: compactCount(Number(row[1]) || 0),
- }));
+ if (!experiment.start_date) {
+ return {
+ ...preview,
+ experimentResults: shapeExperimentResults(experiment, null, [], []),
+ };
+ }
+
+ const runMetricQuery = async (
+ metric: unknown,
+ ): Promise<ExperimentMetricQueryResult> => {
+ if (!metric || typeof metric !== "object") {
+ return { response: null };
+ }
+ try {
+ const response = await this.runQuery(
+ {
+ kind: "ExperimentQuery",
+ metric,
+ experiment_id: numericId,
+ },
+ { refresh: false },
+ );
+ return {
+ response: response as Schemas.ExperimentQueryResponse,
+ };
+ } catch {
+ return { response: null };
+ }
+ };
+
+ const exposureQuery = experiment.feature_flag
+ ? this.runQuery(
+ {
+ kind: "ExperimentExposureQuery",
+ experiment_id: numericId,
+ experiment_name: experiment.name,
+ exposure_criteria: experiment.exposure_criteria,
+ feature_flag: experiment.feature_flag,
+ start_date: experiment.start_date,
+ end_date: experiment.end_date,
+ holdout: experiment.holdout,
+ },
+ { refresh: false },
+ ).catch(() => null)
+ : Promise.resolve(null);
+ const [exposureResponse, primaryResults, secondaryResults] =
+ await Promise.all([
+ exposureQuery,
+ Promise.all(primaryQueries.map(runMetricQuery)),
+ Promise.all(secondaryQueries.map(runMetricQuery)),
+ ]);
+
+ const experimentExposureResponse =
+ exposureResponse as Schemas.ExperimentExposureQueryResponse | null;
return {
...preview,
- facts: fact ? [...(preview.facts ?? []), fact] : preview.facts,
- stats: [...(preview.stats ?? []), ...variantStats],
- chart: pivot
- ? {
- title:
- pivot.omittedGroups > 0
- ? `Daily exposed users by variant (top ${pivot.series.length} of ${
- pivot.series.length + pivot.omittedGroups
- })`
- : "Daily exposed users by variant",
- labels: pivot.labels,
- series: pivot.series,
- render: "line" as const,
- }
- : undefined,
+ experimentResults: shapeExperimentResults(
+ experiment,
+ experimentExposureResponse,
+ primaryResults,
+ secondaryResults,
+ ),
+ chart: shapeExperimentExposureChart(experimentExposureResponse),
};
}
case "error": {
diff --git a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
index 6520b657558d..cafc5cefe420 100644
--- a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
@@ -25,6 +25,7 @@ import {
evidenceWebPath,
} from "../../../utils/evidenceLinks";
import { getObjectKind } from "../../../utils/objectKinds";
+import { ExperimentResultsSummary } from "../../posthog-objects/ExperimentResultsSummary";
import { buildEvidenceComposerContent } from "../evidenceComposer";
import {
EVIDENCE_PREVIEW_STALE_TIME,
@@ -167,16 +168,12 @@ export function EvidenceSparkline({
);
}
-/**
- * The hover card, presentation only. `preview` is the live lookup result:
- * `undefined` while loading, `null` when there is nothing to show (unknown
- * kind, failed lookup, or no session).
- */
export function EvidenceHoverCard({
target,
children,
url,
preview,
+ loadState = preview === undefined ? "loading" : preview ? "ready" : "missing",
onOpen = openExternalUrl,
onExpand,
}: {
@@ -184,6 +181,7 @@ export function EvidenceHoverCard({
children: ReactNode;
url: string | null;
preview: EvidenceCardData | null | undefined;
+ loadState?: "loading" | "error" | "missing" | "ready";
onOpen?: (url: string) => void;
onExpand?: (label: string) => void;
}) {
@@ -202,7 +200,15 @@ export function EvidenceHoverCard({
{/* For a query the source label duplicates the footer's open action. */}
{!isQuery && <span className="ml-auto shrink-0">{meta.source}</span>}
</div>
- {preview === undefined ? (
+ {target.kind === "experiment" && loadState !== "ready" ? (
+ <div className="mt-3">
+ <ExperimentResultsSummary
+ display="compact"
+ loadState={loadState}
+ results={preview?.experimentResults}
+ />
+ </div>
+ ) : loadState === "loading" ? (
<div className="mt-3 space-y-2" data-testid="evidence-preview-loading">
<div className="h-4 w-3/5 animate-pulse rounded bg-(--gray-a4)" />
<div className="h-9 w-full animate-pulse rounded bg-(--gray-a3)" />
@@ -260,6 +266,15 @@ export function EvidenceHoverCard({
))}
</div>
)}
+ {target.kind === "experiment" && (
+ <div className="mt-2.5">
+ <ExperimentResultsSummary
+ display="compact"
+ loadState="ready"
+ results={preview.experimentResults}
+ />
+ </div>
+ )}
</div>
) : (
<div className="mt-2.5">
@@ -371,12 +386,16 @@ function EvidenceHoverCardLoader({
},
);
// No session means no lookup: show the static card, not an endless skeleton.
- const preview =
- !client || query.isError
- ? null
+ const loadState = !client
+ ? "missing"
+ : query.isError
+ ? "error"
: query.isFetched
- ? (query.data ?? null)
- : undefined;
+ ? query.data
+ ? "ready"
+ : "missing"
+ : "loading";
+ const preview = query.data ?? null;
// A reference whose cited id has no page (an event name, a flag key) can
// still link out once the preview resolves the canonical id.
const resolvedUrl = useEvidenceUrl(
@@ -388,6 +407,7 @@ function EvidenceHoverCardLoader({
target={target}
url={url ?? resolvedUrl}
preview={preview}
+ loadState={loadState}
onExpand={onExpand}
>
{children}
diff --git a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
index c75b62131ec2..e4c82e6cae04 100644
--- a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
@@ -1,4 +1,7 @@
-import type { EvidenceDetailSection } from "@posthog/api-client/evidence-previews";
+import type {
+ EvidenceDetailSection,
+ ExperimentResultsPresentation,
+} from "@posthog/api-client/evidence-previews";
import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";
import {
type ChartHeadlineStat,
@@ -39,6 +42,7 @@ export interface EvidenceCardData {
render: "line" | "bar";
};
sections?: EvidenceDetailSection[];
+ experimentResults?: ExperimentResultsPresentation;
/** A dashboard's tiles, each resolvable to a live insight chart. */
tiles?: Array<{ shortId: string; name: string | null }>;
/** Canonical id when it differs from the cited one (a flag cited by key). */
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/ExperimentDeltaChart.tsx b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentDeltaChart.tsx
new file mode 100644
index 000000000000..ce7e4b0a6940
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentDeltaChart.tsx
@@ -0,0 +1,197 @@
+import { InfoIcon } from "@phosphor-icons/react";
+import type { ExperimentVariantResultPresentation } from "@posthog/api-client/evidence-previews";
+import { Text, Tooltip, TooltipContent, TooltipTrigger } from "@posthog/quill";
+import type { ReactElement } from "react";
+
+const EDGE_MARGIN_PERCENT = 3;
+
+function toPercent(value: number, axisRange: number): number {
+ const clamped = Math.max(-axisRange, Math.min(axisRange, value));
+ const fraction = (clamped / axisRange + 1) / 2;
+ return EDGE_MARGIN_PERCENT + fraction * (100 - 2 * EDGE_MARGIN_PERCENT);
+}
+
+function deltaTicks(axisRange: number): number[] {
+ const max = Math.ceil(axisRange * 10) / 10;
+ const magnitude = Math.floor(Math.log10(max));
+ const power = 10 ** magnitude;
+ const normalized = max / power;
+ const unit =
+ normalized <= 1
+ ? 0.2 * power
+ : normalized <= 2
+ ? 0.5 * power
+ : normalized <= 5
+ ? power
+ : 2 * power;
+ const limit = max * 0.9;
+ const steps = Math.ceil(limit / unit);
+ const decimals = Math.max(0, -magnitude + 1);
+ const ticks: number[] = [];
+ for (let step = -steps; step <= steps; step++) {
+ const value = Number((unit * step).toFixed(decimals));
+ if (Math.abs(value) <= limit) ticks.push(value);
+ }
+ return ticks;
+}
+
+function labelledTicks(axisRange: number): number[] {
+ const ticks = deltaTicks(axisRange);
+ if (ticks.length <= 7) return ticks;
+ const zero = ticks.indexOf(0);
+ return ticks.filter((_, index) => Math.abs(index - zero) % 2 === 0);
+}
+
+function formatTick(value: number): string {
+ const percent = value * 100;
+ if (percent === 0) return "0";
+ const rounded =
+ Math.abs(percent) < 1 ? percent.toFixed(1) : String(Math.round(percent));
+ return `${percent > 0 ? "+" : ""}${rounded}%`;
+}
+
+function GridLines({ axisRange }: { axisRange: number }): ReactElement {
+ return (
+ <>
+ {deltaTicks(axisRange).map((tick) => (
+ <span
+ key={tick}
+ className={`absolute inset-y-0 w-px ${tick === 0 ? "bg-muted-foreground/50" : "bg-border/70"}`}
+ style={{ left: `${toPercent(tick, axisRange)}%` }}
+ />
+ ))}
+ </>
+ );
+}
+
+export function ExperimentDeltaAxis({
+ axisRange,
+}: {
+ axisRange: number;
+}): ReactElement {
+ return (
+ <div className="w-full min-w-48">
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="mb-1 flex items-center gap-1 font-normal text-muted-foreground">
+ Uplift vs baseline
+ <InfoIcon size={12} />
+ </span>
+ }
+ />
+ <TooltipContent className="max-w-70" side="top">
+ Each bar covers the range the true uplift is likely to fall in. A bar
+ that crosses the zero line is not significant yet.
+ </TooltipContent>
+ </Tooltip>
+ <div className="relative h-3.5 w-full">
+ {labelledTicks(axisRange).map((tick) => (
+ <span
+ key={tick}
+ className={`-translate-x-1/2 absolute top-0 font-normal text-[10px] tabular-nums ${tick === 0 ? "text-muted-foreground" : "text-muted-foreground/70"}`}
+ style={{ left: `${toPercent(tick, axisRange)}%` }}
+ >
+ {formatTick(tick)}
+ </span>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function TooltipRow({
+ label,
+ value,
+}: {
+ label: string;
+ value: string;
+}): ReactElement {
+ return (
+ <span className="flex items-baseline justify-between gap-4">
+ <span className="text-muted-foreground">{label}</span>
+ <span className="tabular-nums">{value}</span>
+ </span>
+ );
+}
+
+export function ExperimentDeltaBar({
+ variant,
+ axisRange,
+}: {
+ variant: ExperimentVariantResultPresentation;
+ axisRange: number;
+}): ReactElement {
+ const bounds = variant.intervalBounds;
+ const significant = variant.significance === "significant";
+ const tone =
+ significant && variant.isImprovement === true
+ ? "bg-success-foreground"
+ : significant && variant.isImprovement === false
+ ? "bg-destructive-foreground"
+ : "bg-muted-foreground";
+ const left = bounds ? toPercent(bounds[0], axisRange) : 0;
+ const right = bounds ? toPercent(bounds[1], axisRange) : 0;
+
+ const track = (
+ <div className="group/delta relative h-7 w-full min-w-48">
+ <GridLines axisRange={axisRange} />
+ {!variant.isControl && bounds && (
+ <>
+ <span
+ className={`-translate-y-1/2 absolute top-1/2 h-[3px] rounded-full opacity-40 transition-opacity group-hover/delta:opacity-70 ${tone}`}
+ style={{
+ left: `${left}%`,
+ width: `${Math.max(right - left, 0.4)}%`,
+ }}
+ />
+ {[left, right].map((edge, index) => (
+ <span
+ key={index === 0 ? "lower" : "upper"}
+ className={`-translate-x-1/2 -translate-y-1/2 absolute top-1/2 h-2 w-[2px] rounded-full opacity-50 transition-opacity group-hover/delta:opacity-80 ${tone}`}
+ style={{ left: `${edge}%` }}
+ />
+ ))}
+ {variant.upliftValue !== null && (
+ <span
+ className={`-translate-x-1/2 -translate-y-1/2 absolute top-1/2 size-2.5 rounded-full ring-2 ring-card ${tone}`}
+ style={{
+ left: `${toPercent(variant.upliftValue, axisRange)}%`,
+ }}
+ />
+ )}
+ </>
+ )}
+ {!variant.isControl && !bounds && (
+ <Text
+ render={<span />}
+ size="xxs"
+ variant="muted"
+ className="-translate-y-1/2 absolute top-1/2 left-0"
+ >
+ Not enough data yet
+ </Text>
+ )}
+ </div>
+ );
+
+ if (variant.isControl || !bounds) return track;
+ return (
+ <Tooltip>
+ <TooltipTrigger render={track} />
+ <TooltipContent className="flex-col items-stretch gap-0.5" side="top">
+ <span className="font-medium">{variant.key}</span>
+ {variant.uplift && <TooltipRow label="Uplift" value={variant.uplift} />}
+ {variant.interval && (
+ <TooltipRow label="95% interval" value={variant.interval} />
+ )}
+ {variant.pValue && (
+ <TooltipRow label="p-value" value={variant.pValue} />
+ )}
+ {variant.chanceToWin && (
+ <TooltipRow label="Chance to win" value={variant.chanceToWin} />
+ )}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/ExperimentMetricResult.tsx b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentMetricResult.tsx
new file mode 100644
index 000000000000..ec125f5c2198
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentMetricResult.tsx
@@ -0,0 +1,314 @@
+import type {
+ ExperimentMetricResultPresentation,
+ ExperimentVariantResultPresentation,
+} from "@posthog/api-client/evidence-previews";
+import {
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+ Badge,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Text,
+} from "@posthog/quill";
+import type { ReactElement } from "react";
+import {
+ ExperimentDeltaAxis,
+ ExperimentDeltaBar,
+} from "./ExperimentDeltaChart";
+import { ExperimentResultNotice } from "./ExperimentResultNotice";
+
+const SIGNIFICANCE_LABELS = {
+ significant: "Significant",
+ not_significant: "Not significant",
+ insufficient_data: "Insufficient data",
+} as const;
+
+function directionClass(isImprovement: boolean | null): string {
+ if (isImprovement === true) return "text-success-foreground";
+ if (isImprovement === false) return "text-destructive-foreground";
+ return "text-foreground";
+}
+
+function MetricStateBadge({
+ metric,
+}: {
+ metric: ExperimentMetricResultPresentation;
+}): ReactElement | null {
+ if (metric.state === "error") {
+ return <Badge variant="destructive">Query failed</Badge>;
+ }
+ if (metric.state === "insufficient_data") {
+ return <Badge variant="warning">Insufficient data</Badge>;
+ }
+ return null;
+}
+
+function SignificanceBadge({
+ variant,
+}: {
+ variant: ExperimentVariantResultPresentation;
+}): ReactElement {
+ if (!variant.significance) {
+ return <span className="text-muted-foreground">Not available</span>;
+ }
+ return (
+ <Badge
+ variant={
+ variant.significance === "significant"
+ ? "success"
+ : variant.significance === "insufficient_data"
+ ? "warning"
+ : "default"
+ }
+ >
+ {SIGNIFICANCE_LABELS[variant.significance]}
+ </Badge>
+ );
+}
+
+function BestVariantLine({
+ metric,
+}: {
+ metric: ExperimentMetricResultPresentation;
+}): ReactElement | null {
+ const best = metric.bestVariant;
+ if (!best) return null;
+ return (
+ <span
+ className={`shrink-0 font-medium text-xs tabular-nums ${
+ best.significance === "significant"
+ ? directionClass(best.isImprovement)
+ : "text-muted-foreground"
+ }`}
+ >
+ Best observed: {best.key} {best.uplift}
+ </span>
+ );
+}
+
+function MetricHeading({
+ metric,
+}: {
+ metric: ExperimentMetricResultPresentation;
+}): ReactElement {
+ return (
+ <span className="flex min-w-0 flex-1 flex-wrap items-center justify-between gap-x-3 gap-y-1">
+ <Text
+ render={<span />}
+ size="sm"
+ weight="semibold"
+ className="min-w-0 truncate text-foreground"
+ >
+ {metric.name}
+ </Text>
+ <span className="flex shrink-0 items-center gap-2">
+ <BestVariantLine metric={metric} />
+ <MetricStateBadge metric={metric} />
+ </span>
+ </span>
+ );
+}
+
+function MetricDetail({
+ metric,
+}: {
+ metric: ExperimentMetricResultPresentation;
+}): ReactElement {
+ if (metric.error) {
+ return (
+ <ExperimentResultNotice tone="destructive">
+ {metric.error}
+ </ExperimentResultNotice>
+ );
+ }
+ if (metric.variants.length === 0) {
+ return (
+ <ExperimentResultNotice tone="neutral">
+ No variant results are available for this metric yet.
+ </ExperimentResultNotice>
+ );
+ }
+
+ const { axisRange } = metric;
+ return (
+ <div className="@container">
+ <Table size="sm" fullWidth>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Variant</TableHead>
+ <TableHead align="right">{metric.outcomeLabel}</TableHead>
+ <TableHead align="right">Uplift</TableHead>
+ <TableHead align="right">Significance</TableHead>
+ {axisRange !== null && (
+ <TableHead
+ expand
+ valign="bottom"
+ className="@3xl:table-cell hidden"
+ >
+ <ExperimentDeltaAxis axisRange={axisRange} />
+ </TableHead>
+ )}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {metric.variants.map((variant) => (
+ <TableRow key={variant.key}>
+ <TableCell valign="middle">
+ <span className="block truncate font-medium">
+ {variant.key}
+ {variant.isControl ? " (control)" : ""}
+ </span>
+ <Text
+ render={<span />}
+ size="xxs"
+ variant="muted"
+ className="block truncate tabular-nums"
+ >
+ {variant.sampleContext}
+ </Text>
+ </TableCell>
+ <TableCell
+ align="right"
+ valign="middle"
+ className="whitespace-nowrap tabular-nums"
+ >
+ {variant.outcome}
+ </TableCell>
+ <TableCell align="right" valign="middle">
+ {variant.isControl || !variant.uplift ? (
+ <span className="text-muted-foreground">&mdash;</span>
+ ) : (
+ <span
+ className={`whitespace-nowrap font-medium tabular-nums ${directionClass(variant.isImprovement)}`}
+ >
+ {variant.uplift}
+ </span>
+ )}
+ </TableCell>
+ <TableCell align="right" valign="middle">
+ {variant.isControl ? (
+ <span className="text-muted-foreground">&mdash;</span>
+ ) : (
+ <>
+ <SignificanceBadge variant={variant} />
+ {(variant.pValue || variant.chanceToWin) && (
+ <Text
+ render={<span />}
+ size="xxs"
+ variant="muted"
+ className="mt-0.5 block whitespace-nowrap tabular-nums"
+ >
+ {variant.pValue
+ ? `p-value ${variant.pValue}`
+ : `${variant.chanceToWin} chance to win`}
+ </Text>
+ )}
+ </>
+ )}
+ </TableCell>
+ {axisRange !== null && (
+ <TableCell
+ expand
+ valign="middle"
+ className="@3xl:table-cell hidden pr-0"
+ >
+ <ExperimentDeltaBar variant={variant} axisRange={axisRange} />
+ </TableCell>
+ )}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
+
+function CompactMetricRow({
+ metric,
+}: {
+ metric: ExperimentMetricResultPresentation;
+}): ReactElement {
+ const best = metric.bestVariant;
+ const detail = metric.error
+ ? "Query failed"
+ : best
+ ? `${best.key} vs control`
+ : "No comparison yet";
+ const significance =
+ metric.state === "insufficient_data"
+ ? "Insufficient data"
+ : best?.significance
+ ? SIGNIFICANCE_LABELS[best.significance]
+ : null;
+ return (
+ <div className="flex items-baseline justify-between gap-3 px-2.5 py-2">
+ <span className="min-w-0">
+ <Text
+ render={<span />}
+ size="xs"
+ weight="medium"
+ className="block truncate text-foreground"
+ >
+ {metric.name}
+ </Text>
+ <Text
+ render={<span />}
+ size="xxs"
+ variant="muted"
+ className="block truncate"
+ >
+ {detail}
+ </Text>
+ </span>
+ <span className="shrink-0 text-right">
+ <Text
+ render={<span />}
+ size="xs"
+ weight="semibold"
+ className={`block tabular-nums ${
+ best && best.significance === "significant"
+ ? directionClass(best.isImprovement)
+ : "text-foreground"
+ }`}
+ >
+ {best?.uplift ?? "—"}
+ </Text>
+ {significance && (
+ <Text render={<span />} size="xxs" variant="muted" className="block">
+ {significance}
+ </Text>
+ )}
+ </span>
+ </div>
+ );
+}
+
+export function ExperimentMetricResult({
+ metric,
+ display,
+}: {
+ metric: ExperimentMetricResultPresentation;
+ display: "compact" | "full";
+}): ReactElement {
+ if (display === "compact") {
+ return <CompactMetricRow metric={metric} />;
+ }
+ return (
+ <AccordionItem value={metric.id}>
+ <AccordionTrigger
+ data-attr="experiment-metric-toggle"
+ className="[&>span:first-child]:min-w-0 [&>span:first-child]:flex-1"
+ >
+ <MetricHeading metric={metric} />
+ </AccordionTrigger>
+ <AccordionContent>
+ <MetricDetail metric={metric} />
+ </AccordionContent>
+ </AccordionItem>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultNotice.tsx b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultNotice.tsx
new file mode 100644
index 000000000000..256368ea988f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultNotice.tsx
@@ -0,0 +1,25 @@
+import { Text } from "@posthog/quill";
+import type { ReactElement, ReactNode } from "react";
+
+export function ExperimentResultNotice({
+ tone,
+ children,
+}: {
+ tone: "neutral" | "warning" | "destructive";
+ children: ReactNode;
+}): ReactElement {
+ const toneClass = {
+ neutral: "border-border bg-muted text-muted-foreground",
+ warning: "border-warning/30 bg-warning/10 text-warning-foreground",
+ destructive:
+ "border-destructive/30 bg-destructive/10 text-destructive-foreground",
+ }[tone];
+ return (
+ <Text
+ size="xs"
+ className={`block rounded-md border px-2.5 py-2 leading-snug ${toneClass}`}
+ >
+ {children}
+ </Text>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultsSummary.stories.tsx b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultsSummary.stories.tsx
new file mode 100644
index 000000000000..67dc47f089df
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultsSummary.stories.tsx
@@ -0,0 +1,145 @@
+import type { ExperimentResultsPresentation } from "@posthog/api-client/evidence-previews";
+import { ExperimentResultsSummary } from "@posthog/ui/features/posthog-objects/ExperimentResultsSummary";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+
+const results: ExperimentResultsPresentation = {
+ state: "ready",
+ stale: false,
+ lastRefresh: "2026-08-16T12:00:00Z",
+ primaryMetrics: [
+ {
+ id: "checkout-conversion",
+ name: "Checkout conversion",
+ metricType: "primary",
+ state: "ready",
+ error: null,
+ outcomeLabel: "Conversions",
+ axisRange: 0.4,
+ bestVariant: {
+ key: "test",
+ uplift: "+34.0%",
+ significance: "significant",
+ isImprovement: true,
+ },
+ variants: [
+ {
+ key: "control",
+ isControl: true,
+ outcome: "312 · 6.00%",
+ sampleContext: "5.2K samples · 5.3K exposed",
+ uplift: null,
+ upliftValue: null,
+ intervalBounds: null,
+ upliftDirection: null,
+ isImprovement: null,
+ interval: null,
+ pValue: null,
+ chanceToWin: null,
+ significance: null,
+ },
+ {
+ key: "test",
+ isControl: false,
+ outcome: "410 · 8.04%",
+ sampleContext: "5.1K samples · 5.2K exposed",
+ uplift: "+34.0%",
+ upliftValue: 0.34,
+ intervalBounds: [0.011, 0.049],
+ upliftDirection: "positive",
+ isImprovement: true,
+ interval: "+1.10% to +4.90%",
+ pValue: "0.003",
+ chanceToWin: null,
+ significance: "significant",
+ },
+ ],
+ },
+ ],
+ secondaryMetrics: [
+ {
+ id: "orders-per-user",
+ name: "Orders per user",
+ metricType: "secondary",
+ state: "insufficient_data",
+ error: null,
+ outcomeLabel: "Outcome",
+ axisRange: null,
+ bestVariant: null,
+ variants: [],
+ },
+ ],
+};
+
+const sampleMetric = results.primaryMetrics[0];
+if (!sampleMetric) {
+ throw new Error("The experiment results story needs one sample metric.");
+}
+const manyResults: ExperimentResultsPresentation = {
+ ...results,
+ primaryMetrics: [sampleMetric],
+ secondaryMetrics: [
+ "Activation rate",
+ "Files uploaded",
+ "Invites sent",
+ "Seven-day retention",
+ "Revenue per user",
+ "Support requests",
+ ].map((name, index) => ({
+ ...sampleMetric,
+ id: `secondary-${index}`,
+ name,
+ metricType: "secondary" as const,
+ bestVariant: {
+ key: "test",
+ uplift: "+34.0%",
+ significance: index === 2 ? "significant" : "not_significant",
+ isImprovement: true,
+ },
+ })),
+};
+
+const meta: Meta<typeof ExperimentResultsSummary> = {
+ title: "Features/PostHog objects/ExperimentResultsSummary",
+ component: ExperimentResultsSummary,
+ decorators: [
+ (Story) => (
+ <div className="max-w-4xl p-4">
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export default meta;
+type Story = StoryObj<typeof ExperimentResultsSummary>;
+
+export const Full: Story = {
+ args: { display: "full", loadState: "ready", results },
+};
+
+export const Compact: Story = {
+ args: { display: "compact", loadState: "ready", results },
+ decorators: [
+ (Story) => (
+ <div className="w-80">
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export const ManyMetrics: Story = {
+ args: { display: "full", loadState: "ready", results: manyResults },
+};
+
+export const Stale: Story = {
+ args: {
+ display: "full",
+ loadState: "ready",
+ results: { ...results, stale: true },
+ },
+};
+
+export const Loading: Story = {
+ args: { display: "full", loadState: "loading", results: null },
+};
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultsSummary.test.tsx b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultsSummary.test.tsx
new file mode 100644
index 000000000000..a79b0c109877
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultsSummary.test.tsx
@@ -0,0 +1,180 @@
+import type { ExperimentResultsPresentation } from "@posthog/api-client/evidence-previews";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { ExperimentResultsSummary } from "./ExperimentResultsSummary";
+
+const variant = (
+ key: string,
+ overrides: Partial<
+ ExperimentResultsPresentation["primaryMetrics"][number]["variants"][number]
+ > = {},
+) => ({
+ key,
+ isControl: key === "control",
+ outcome: "125 · 12.5%",
+ sampleContext: "1K samples · 1K exposed",
+ uplift: key === "control" ? null : "+25.0%",
+ upliftValue: key === "control" ? null : 0.25,
+ intervalBounds: key === "control" ? null : ([0.05, 0.45] as [number, number]),
+ upliftDirection: key === "control" ? null : ("positive" as const),
+ isImprovement: key === "control" ? null : true,
+ interval: key === "control" ? null : "+5.00% to +45.0%",
+ pValue: key === "control" ? null : "0.020",
+ chanceToWin: null,
+ significance: key === "control" ? null : ("significant" as const),
+ ...overrides,
+});
+
+const metric = (
+ id: string,
+ name: string,
+ metricType: "primary" | "secondary",
+ overrides: Partial<
+ ExperimentResultsPresentation["primaryMetrics"][number]
+ > = {},
+) => ({
+ id,
+ name,
+ metricType,
+ state: "ready" as const,
+ error: null,
+ outcomeLabel: "Conversions",
+ axisRange: 0.45,
+ bestVariant: {
+ key: "test",
+ uplift: "+25.0%",
+ significance: "significant" as const,
+ isImprovement: true,
+ },
+ variants: [variant("control"), variant("test")],
+ ...overrides,
+});
+
+const results: ExperimentResultsPresentation = {
+ state: "ready",
+ stale: false,
+ lastRefresh: "2026-01-15T12:00:00Z",
+ primaryMetrics: [metric("primary-1", "Checkout conversion", "primary")],
+ secondaryMetrics: [
+ metric("secondary-1", "Orders per user", "secondary", {
+ variants: [
+ variant("control"),
+ variant("test", { pValue: "0.120", significance: "not_significant" }),
+ ],
+ bestVariant: {
+ key: "test",
+ uplift: "+25.0%",
+ significance: "not_significant",
+ isImprovement: true,
+ },
+ }),
+ ],
+};
+
+describe("ExperimentResultsSummary", () => {
+ it("reduces a hover card to primary metric headlines", () => {
+ render(
+ <ExperimentResultsSummary
+ display="compact"
+ loadState="ready"
+ results={results}
+ />,
+ );
+
+ expect(screen.getByText("Checkout conversion")).toBeInTheDocument();
+ expect(screen.getByText("test vs control")).toBeInTheDocument();
+ expect(screen.getByText("+25.0%")).toBeInTheDocument();
+ expect(screen.getByText("Significant")).toBeInTheDocument();
+ expect(screen.queryByText("Orders per user")).not.toBeInTheDocument();
+ expect(screen.queryByText("p-value 0.020")).not.toBeInTheDocument();
+ expect(
+ screen.getByText("+1 more metric on the full page"),
+ ).toBeInTheDocument();
+ });
+
+ it("opens primary metrics on the full page and keeps secondary metrics collapsed", () => {
+ render(
+ <ExperimentResultsSummary
+ display="full"
+ loadState="ready"
+ results={results}
+ />,
+ );
+
+ expect(screen.getByText("p-value 0.020")).toBeInTheDocument();
+ expect(screen.getByText("Uplift vs baseline")).toBeInTheDocument();
+ expect(screen.queryByText("p-value 0.120")).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: /Orders per user/ }));
+
+ expect(screen.getByText("p-value 0.120")).toBeInTheDocument();
+ });
+
+ it("caps hover cards at three metrics with a pointer to the full page", () => {
+ const manyMetrics = {
+ ...results,
+ primaryMetrics: [
+ metric("primary-1", "Metric one", "primary"),
+ metric("primary-2", "Metric two", "primary"),
+ metric("primary-3", "Metric three", "primary"),
+ ],
+ secondaryMetrics: [
+ metric("secondary-1", "Metric four", "secondary"),
+ metric("secondary-2", "Metric five", "secondary"),
+ metric("secondary-3", "Metric six", "secondary"),
+ ],
+ };
+ render(
+ <ExperimentResultsSummary
+ display="compact"
+ loadState="ready"
+ results={manyMetrics}
+ />,
+ );
+
+ expect(screen.getByText("Metric three")).toBeInTheDocument();
+ expect(screen.queryByText("Metric four")).not.toBeInTheDocument();
+ expect(
+ screen.getByText("+3 more metrics on the full page"),
+ ).toBeInTheDocument();
+ });
+
+ it.each([
+ ["loading", "loading", null, "experiment-results-loading"],
+ [
+ "failed lookup",
+ "error",
+ null,
+ "Couldn't load experiment results. Try again, or open the experiment in PostHog.",
+ ],
+ [
+ "draft",
+ "ready",
+ { ...results, state: "draft" },
+ "Results will appear after this experiment starts.",
+ ],
+ [
+ "insufficient data",
+ "ready",
+ { ...results, state: "insufficient_data" },
+ "There isn't enough data to determine significance yet.",
+ ],
+ ] as const)(
+ "renders the %s state",
+ (_name, loadState, stateResults, expected) => {
+ render(
+ <ExperimentResultsSummary
+ display="compact"
+ loadState={loadState}
+ results={stateResults}
+ />,
+ );
+
+ if (expected === "experiment-results-loading") {
+ expect(screen.getByTestId(expected)).toBeInTheDocument();
+ } else {
+ expect(screen.getByText(expected)).toBeInTheDocument();
+ }
+ },
+ );
+});
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultsSummary.tsx b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultsSummary.tsx
new file mode 100644
index 000000000000..89627951f2d4
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/ExperimentResultsSummary.tsx
@@ -0,0 +1,146 @@
+import type { ExperimentResultsPresentation } from "@posthog/api-client/evidence-previews";
+import { Accordion, Skeleton, Text } from "@posthog/quill";
+import type { ReactElement } from "react";
+import { ExperimentMetricResult } from "./ExperimentMetricResult";
+import { ExperimentResultNotice } from "./ExperimentResultNotice";
+
+export interface ExperimentResultsSummaryProps {
+ display: "compact" | "full";
+ loadState: "loading" | "error" | "missing" | "ready";
+ results: ExperimentResultsPresentation | null | undefined;
+}
+
+const MAX_COMPACT_METRICS = 3;
+
+export function ExperimentResultsSummary({
+ display,
+ loadState,
+ results,
+}: ExperimentResultsSummaryProps): ReactElement {
+ if (loadState === "loading") {
+ return (
+ <div
+ className="flex flex-col gap-2"
+ data-testid="experiment-results-loading"
+ >
+ <Skeleton
+ className={display === "compact" ? "h-20 w-full" : "h-36 w-full"}
+ />
+ {display === "full" && <Skeleton className="h-36 w-full" />}
+ </div>
+ );
+ }
+ if (loadState === "error") {
+ return (
+ <ExperimentResultNotice tone="destructive">
+ Couldn't load experiment results. Try again, or open the experiment in
+ PostHog.
+ </ExperimentResultNotice>
+ );
+ }
+ if (!results || loadState === "missing") {
+ return (
+ <ExperimentResultNotice tone="neutral">
+ Experiment results are not available in the current project.
+ </ExperimentResultNotice>
+ );
+ }
+ if (results.state === "draft") {
+ return (
+ <ExperimentResultNotice tone="neutral">
+ Results will appear after this experiment starts.
+ </ExperimentResultNotice>
+ );
+ }
+
+ const allMetrics = [...results.primaryMetrics, ...results.secondaryMetrics];
+ const headlineMetrics =
+ results.primaryMetrics.length > 0
+ ? results.primaryMetrics
+ : results.secondaryMetrics;
+ const metrics = headlineMetrics.slice(0, MAX_COMPACT_METRICS);
+ const hiddenMetricCount = allMetrics.length - metrics.length;
+
+ return (
+ <div className="flex flex-col gap-2" data-testid="experiment-results">
+ {results.stale && (
+ <ExperimentResultNotice tone="warning">
+ Cached results may be out of date
+ {results.lastRefresh
+ ? `. Last refreshed ${new Date(results.lastRefresh).toLocaleString("en-US", { dateStyle: "medium", timeStyle: "short" })}.`
+ : "."}
+ </ExperimentResultNotice>
+ )}
+ {results.state === "error" && (
+ <ExperimentResultNotice tone="destructive">
+ Some metric results couldn't load. Open the experiment in PostHog to
+ retry them.
+ </ExperimentResultNotice>
+ )}
+ {results.state === "insufficient_data" && (
+ <ExperimentResultNotice tone="warning">
+ There isn't enough data to determine significance yet.
+ </ExperimentResultNotice>
+ )}
+ {allMetrics.length === 0 ? (
+ <ExperimentResultNotice tone="neutral">
+ This experiment does not have any metrics yet.
+ </ExperimentResultNotice>
+ ) : display === "full" ? (
+ <div className="flex flex-col gap-4">
+ {results.primaryMetrics.length > 0 && (
+ <section>
+ <Text size="xs" weight="semibold" variant="muted">
+ Primary metrics ({results.primaryMetrics.length})
+ </Text>
+ <Accordion
+ multiple
+ defaultValue={results.primaryMetrics.map((metric) => metric.id)}
+ >
+ {results.primaryMetrics.map((metric) => (
+ <ExperimentMetricResult
+ key={metric.id}
+ metric={metric}
+ display="full"
+ />
+ ))}
+ </Accordion>
+ </section>
+ )}
+ {results.secondaryMetrics.length > 0 && (
+ <section>
+ <Text size="xs" weight="semibold" variant="muted">
+ Secondary metrics ({results.secondaryMetrics.length})
+ </Text>
+ <Accordion multiple>
+ {results.secondaryMetrics.map((metric) => (
+ <ExperimentMetricResult
+ key={metric.id}
+ metric={metric}
+ display="full"
+ />
+ ))}
+ </Accordion>
+ </section>
+ )}
+ </div>
+ ) : (
+ <div className="divide-y divide-border overflow-hidden rounded-md border border-border bg-card">
+ {metrics.map((metric) => (
+ <ExperimentMetricResult
+ key={metric.id}
+ metric={metric}
+ display="compact"
+ />
+ ))}
+ </div>
+ )}
+ {display === "compact" && hiddenMetricCount > 0 && (
+ <Text size="xxs" variant="muted">
+ +{hiddenMetricCount} more metric
+ {hiddenMetricCount === 1 ? "" : "s"} on the full page
+ </Text>
+ )}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
index 4f473d87d49f..6c09e4237f70 100644
--- a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
@@ -25,6 +25,7 @@ import {
getObjectKind,
POSTHOG_OBJECT_ICON_COLOR,
} from "@posthog/ui/utils/objectKinds";
+import { ExperimentResultsSummary } from "./ExperimentResultsSummary";
import { PostHogObjectDetails } from "./PostHogObjectDetails";
function StatStrip({
@@ -240,7 +241,16 @@ export function PostHogObjectPageView({
</header>
<div className="mt-6">
- {usesChartRenderer ? (
+ {objectKind === "experiment" ? (
+ <div className="flex flex-col gap-3">
+ <ExperimentResultsSummary
+ display="full"
+ loadState={state}
+ results={preview?.experimentResults}
+ />
+ {preview && <PostHogObjectDetails preview={preview} />}
+ </div>
+ ) : usesChartRenderer ? (
<MessageChartCard
spec={
objectKind === "insight"
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPageView.stories.tsx b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPageView.stories.tsx
index a02675ae8c37..d868e1d203cd 100644
--- a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPageView.stories.tsx
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPageView.stories.tsx
@@ -47,6 +47,76 @@ const experimentPreview: EvidenceCardData = {
title: "Upgrade prompt experiment",
detail: "Day 28 · Started Jul 24",
status: { label: "Running", tone: "positive" },
+ experimentResults: {
+ state: "ready",
+ stale: false,
+ lastRefresh: "2026-08-16T12:00:00Z",
+ primaryMetrics: [
+ {
+ id: "login-to-upload",
+ name: "Login to upload",
+ metricType: "primary",
+ state: "ready",
+ error: null,
+ outcomeLabel: "Conversions",
+ axisRange: 0.35,
+ bestVariant: {
+ key: "aggressive",
+ uplift: "+17.2%",
+ significance: "significant",
+ isImprovement: true,
+ },
+ variants: [
+ {
+ key: "control",
+ isControl: true,
+ outcome: "104 · 18.0%",
+ sampleContext: "578 samples · 578 exposed",
+ uplift: null,
+ upliftValue: null,
+ intervalBounds: null,
+ upliftDirection: null,
+ isImprovement: null,
+ interval: null,
+ pValue: null,
+ chanceToWin: null,
+ significance: null,
+ },
+ {
+ key: "aggressive",
+ isControl: false,
+ outcome: "125 · 21.1%",
+ sampleContext: "593 samples · 593 exposed",
+ uplift: "+17.2%",
+ upliftValue: 0.172,
+ intervalBounds: [0.021, 0.323],
+ upliftDirection: "positive",
+ isImprovement: true,
+ interval: "+2.10% to +32.3%",
+ pValue: "0.028",
+ chanceToWin: null,
+ significance: "significant",
+ },
+ {
+ key: "subtle",
+ isControl: false,
+ outcome: "108 · 19.2%",
+ sampleContext: "563 samples · 563 exposed",
+ uplift: "+6.67%",
+ upliftValue: 0.0667,
+ intervalBounds: [-0.081, 0.214],
+ upliftDirection: "positive",
+ isImprovement: true,
+ interval: "-8.10% to +21.4%",
+ pValue: "0.380",
+ chanceToWin: null,
+ significance: "not_significant",
+ },
+ ],
+ },
+ ],
+ secondaryMetrics: [],
+ },
stats: [
{ label: "Running for", value: "28 days" },
{ label: "control exposed", value: "578" },
@@ -54,14 +124,14 @@ const experimentPreview: EvidenceCardData = {
{ label: "subtle exposed", value: "563" },
],
chart: {
- title: "Daily exposed users by variant",
+ title: "Daily exposures by variant",
labels: DAYS,
series: [
{ label: "control", data: [40, 44, 39, 47, 52, 49, 55] },
{ label: "aggressive", data: [38, 45, 41, 44, 50, 47, 52] },
{ label: "subtle", data: [36, 40, 42, 41, 47, 45, 49] },
],
- render: "line",
+ render: "bar",
},
sections: [
{