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): reuse hover-fetched preview on insight and hogql object pages (#94363)

Shy Altera1aa8cc76cf4
diff --git a/products/desktop/packages/ui/src/features/editor/evidencePreview.test.ts b/products/desktop/packages/ui/src/features/editor/evidencePreview.test.ts
index ee506d160e77..c5fc05f2589e 100644
--- a/products/desktop/packages/ui/src/features/editor/evidencePreview.test.ts
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreview.test.ts
@@ -26,6 +26,10 @@ describe("fetchEvidencePreview", () => {
headline: { value: "1.5M", delta: { direction: "down" } },
spark: { points: [5096547, 1506301], render: "line" },
});
+ expect(preview?.chartData).toMatchObject({
+ type: "series",
+ labels: ["2026-08-13", "2026-08-14"],
+ });
});
it("summarizes a hogql table result by counts, never echoing column titles", async () => {
@@ -50,6 +54,10 @@ describe("fetchEvidencePreview", () => {
expect(preview?.detail).toBeUndefined();
expect(preview?.facts?.join(" ")).not.toContain("arrayJoin");
expect(preview?.facts?.join(" ")).not.toContain("ifNull");
+ expect(preview?.chartData).toMatchObject({
+ type: "table",
+ columns: ["arrayJoin(events.event)", "ifNull(count(), 0)"],
+ });
});
it("keeps raw SQL column titles out of a HogQL-backed insight preview", async () => {
@@ -127,6 +135,8 @@ describe("fetchEvidencePreview", () => {
title: "Checkout funnel",
spark: { points: [5096547, 1506301] },
});
+ expect(preview?.chartData).toMatchObject({ type: "series" });
+ expect(preview?.title).toBe("Checkout funnel");
});
it("uses the saved insight result without running a second query", async () => {
@@ -170,6 +180,13 @@ describe("fetchEvidencePreview", () => {
title: "Unique users per variant",
});
expect(runQuery).not.toHaveBeenCalled();
+
+ const preview = await fetchEvidencePreview(client, {
+ kind: "insight",
+ id: "sdyR2Pn8",
+ });
+ expect(preview?.chartData).toMatchObject({ type: "table" });
+ expect(runQuery).not.toHaveBeenCalled();
});
it("returns null for an insight id that does not resolve", async () => {
diff --git a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
index e4c82e6cae04..96144a8178ad 100644
--- a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
@@ -21,6 +21,13 @@ import type { EvidenceLinkTarget } from "../../utils/evidenceLinks";
export interface EvidenceCardData {
title: string;
detail?: string;
+ /**
+ * The object's own description, shown on the full page's subtitle. Kept
+ * separate from `detail`, which for a multi-series chart holds joined
+ * series labels for the hover card and is wrong on the page. Only insights
+ * set it today.
+ */
+ description?: string;
/** Lifecycle state as a badge label + tone, kept out of `detail`. */
status?: {
label: string;
@@ -34,6 +41,7 @@ export interface EvidenceCardData {
headline?: ChartHeadlineStat | null;
/** Mini chart of the primary series; `labels` carries bucket dates. */
spark?: { points: number[]; labels?: string[]; render: "line" | "bar" };
+ chartData?: ReportChartData;
/** A titled multi-series time chart, drawn with hover values on full pages. */
chart?: {
title: string;
@@ -110,10 +118,11 @@ async function hogqlPreview(
if (data.type === "series" && preview.spark) {
return {
...preview,
+ chartData: data,
facts: [`${data.labels.length} rows · ${data.series.length + 1} columns`],
};
}
- return preview;
+ return { ...preview, chartData: data };
}
async function insightPreview(
@@ -125,12 +134,20 @@ async function insightPreview(
const base: EvidenceCardData = {
title: insight.name || shortId,
detail: insight.description || undefined,
+ description: insight.description || undefined,
};
const plan = planReportChart(insight.query);
if (plan.kind !== "run") return base;
const response = insight.response ?? (await client.runQuery(plan.source));
- const chart = fromChartData(shapeReportChartData(response, plan), base.title);
- return { ...chart, title: base.title, detail: chart.detail ?? base.detail };
+ const data = shapeReportChartData(response, plan);
+ const chart = fromChartData(data, base.title);
+ return {
+ ...chart,
+ chartData: data,
+ title: base.title,
+ detail: chart.detail ?? base.detail,
+ description: insight.description || undefined,
+ };
}
/**
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.test.tsx b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.test.tsx
index b2be0616581e..9f49aab4d312 100644
--- a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.test.tsx
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.test.tsx
@@ -1,11 +1,10 @@
+import type { EvidenceCardData } from "@posthog/ui/features/editor/evidencePreview";
import { Theme } from "@radix-ui/themes";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { PostHogObjectPage } from "./PostHogObjectPage";
const writeText = vi.fn().mockResolvedValue(undefined);
-// Mirror the real hook: a flag page resolves only from a numeric id, so the
-// link is available only if the page passes the resolved id, not the key.
const useEvidenceUrl = vi.hoisted(() =>
vi.fn((_kind: string, id: string) =>
/^\d+$/.test(id)
@@ -14,14 +13,21 @@ const useEvidenceUrl = vi.hoisted(() =>
),
);
-vi.mock("@posthog/ui/hooks/useAuthenticatedQuery", () => ({
- useAuthenticatedQuery: () => ({
+vi.mock("@posthog/quill-charts", () => ({
+ BarChart: () => <div data-testid="chart-plot" />,
+ LineChart: () => <div data-testid="chart-plot" />,
+ TimeSeriesBarChart: () => <div data-testid="chart-plot" />,
+ TimeSeriesLineChart: () => <div data-testid="chart-plot" />,
+ useChartTheme: () => ({}),
+}));
+
+const queryState = vi.hoisted(() => ({
+ current: {
isPending: false,
isError: false,
data: {
title: "new-checkout-flow",
detail: "Enabled",
- // The preview resolves the flag key to its numeric id.
resolvedId: "42",
facts: ["100% rollout", "Used by 1 experiment"],
sections: [
@@ -33,7 +39,15 @@ vi.mock("@posthog/ui/hooks/useAuthenticatedQuery", () => ({
],
},
],
- },
+ } as EvidenceCardData | null,
+ },
+}));
+
+vi.mock("@posthog/ui/hooks/useAuthenticatedQuery", () => ({
+ useAuthenticatedQuery: () => ({
+ isPending: queryState.current.isPending,
+ isError: queryState.current.isError,
+ data: queryState.current.data,
}),
}));
@@ -42,8 +56,37 @@ vi.mock("@posthog/ui/features/editor/components/EvidenceRefChip", () => ({
EvidenceSparkline: () => null,
}));
+function setQueryState(state: {
+ isPending?: boolean;
+ isError?: boolean;
+ data?: EvidenceCardData | null;
+}): void {
+ queryState.current = {
+ isPending: state.isPending ?? false,
+ isError: state.isError ?? false,
+ data: state.data ?? null,
+ };
+}
+
describe("PostHogObjectPage", () => {
it("renders live reference details and copies the exact identifier", async () => {
+ setQueryState({
+ data: {
+ title: "new-checkout-flow",
+ detail: "Enabled",
+ resolvedId: "42",
+ facts: ["100% rollout", "Used by 1 experiment"],
+ sections: [
+ {
+ title: "Configuration",
+ fields: [
+ { label: "Type", value: "Boolean" },
+ { label: "Release conditions", value: "All users" },
+ ],
+ },
+ ],
+ },
+ });
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText },
@@ -72,7 +115,6 @@ describe("PostHogObjectPage", () => {
expect(
screen.getByText("Referenced 2 times in this task"),
).toBeInTheDocument();
- // A flag cited by key still links out, via the resolved numeric id.
expect(screen.getByText(/Open in PostHog/)).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Copy ID" }));
expect(writeText).toHaveBeenCalledWith("new-checkout-flow");
@@ -82,4 +124,198 @@ describe("PostHogObjectPage", () => {
).toBeInTheDocument(),
);
});
+
+ it("draws an insight's chart from the cached preview, with no loading state", () => {
+ setQueryState({
+ data: {
+ title: "Checkout funnel",
+ chartData: { type: "number", value: 68831577 },
+ },
+ });
+ render(
+ <Theme>
+ <PostHogObjectPage
+ fallbackName="Checkout funnel"
+ metadata={{
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ }}
+ />
+ </Theme>,
+ );
+
+ expect(screen.getByTestId("report-chart")).toBeInTheDocument();
+ expect(screen.getByText("68,831,577")).toBeInTheDocument();
+ });
+
+ it("shows a chart skeleton while the insight preview loads", () => {
+ setQueryState({ isPending: true, data: null });
+ render(
+ <Theme>
+ <PostHogObjectPage
+ fallbackName="Checkout funnel"
+ metadata={{
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ }}
+ />
+ </Theme>,
+ );
+
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ });
+
+ it("reports an insight the project does not resolve", () => {
+ setQueryState({ data: null });
+ render(
+ <Theme>
+ <PostHogObjectPage
+ fallbackName="Missing insight"
+ metadata={{
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "nope",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ }}
+ />
+ </Theme>,
+ );
+
+ expect(
+ screen.getByText(/No insight matches "nope" in the current project/),
+ ).toBeInTheDocument();
+ });
+
+ it("never titles a hogql chart card with raw SQL", () => {
+ setQueryState({
+ data: {
+ // hogqlPreview puts the first result column in the hover title.
+ title: "arrayJoin(events.event)",
+ chartData: {
+ type: "series",
+ labels: ["2026-08-13", "2026-08-14"],
+ series: [
+ {
+ key: "series-0",
+ label: "arrayJoin(events.event)",
+ data: [5096547, 1506301],
+ },
+ ],
+ render: "line",
+ isTimeSeries: true,
+ interval: "day",
+ },
+ },
+ });
+ render(
+ <Theme>
+ <PostHogObjectPage
+ fallbackName="Events by day"
+ metadata={{
+ reference_type: "posthog_object",
+ object_kind: "hogql",
+ object_id: "SELECT arrayJoin(events.event) ...",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ }}
+ />
+ </Theme>,
+ );
+
+ expect(screen.getByTestId("report-chart")).toBeInTheDocument();
+ // The page header and chart card use the chip label, never the raw SQL
+ // the hover reduction stored in the preview title or series label.
+ expect(screen.getAllByText("Events by day").length).toBeGreaterThan(0);
+ expect(screen.queryByText("arrayJoin(events.event)")).toBeNull();
+ });
+
+ it("keeps a multi-series insight's series labels out of the page subtitle", () => {
+ setQueryState({
+ data: {
+ title: "Checkout funnel",
+ // insightPreview stores joined series labels in the hover detail.
+ detail: "control · aggressive",
+ description: "Daily unique visitors",
+ chartData: {
+ type: "series",
+ labels: ["2026-08-13", "2026-08-14"],
+ series: [
+ { key: "series-0", label: "control", data: [40, 44] },
+ { key: "series-1", label: "aggressive", data: [38, 45] },
+ ],
+ render: "line",
+ isTimeSeries: true,
+ interval: "day",
+ },
+ },
+ });
+ render(
+ <Theme>
+ <PostHogObjectPage
+ fallbackName="Checkout funnel"
+ metadata={{
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ }}
+ />
+ </Theme>,
+ );
+
+ // The subtitle shows the insight's description, not the series labels.
+ expect(screen.getByText(/Daily unique visitors/)).toBeInTheDocument();
+ expect(screen.queryByText(/control · aggressive/)).toBeNull();
+ });
+
+ it("keeps a multi-series hogql query's column labels out of the page subtitle", () => {
+ setQueryState({
+ data: {
+ title: "ifNull(count(), 0)",
+ // hogqlPreview joins the result columns into the hover detail.
+ detail: "ifNull(count(), 0) · arrayJoin(events.event)",
+ chartData: {
+ type: "series",
+ labels: ["2026-08-13", "2026-08-14"],
+ series: [
+ { key: "series-0", label: "ifNull(count(), 0)", data: [40, 44] },
+ {
+ key: "series-1",
+ label: "arrayJoin(events.event)",
+ data: [38, 45],
+ },
+ ],
+ render: "line",
+ isTimeSeries: true,
+ interval: "day",
+ },
+ },
+ });
+ render(
+ <Theme>
+ <PostHogObjectPage
+ fallbackName="Events by day"
+ metadata={{
+ reference_type: "posthog_object",
+ object_kind: "hogql",
+ object_id: "SELECT arrayJoin(events.event), ifNull(count(), 0) ...",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ }}
+ />
+ </Theme>,
+ );
+
+ // The subtitle shows kind and source only, never the raw SQL detail.
+ expect(screen.queryByText(/ifNull\(count\(\), 0\)/)).toBeNull();
+ expect(screen.queryByText(/arrayJoin\(events\.event\)/)).toBeNull();
+ });
});
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 6c09e4237f70..92dd6ef4f632 100644
--- a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
@@ -1,5 +1,10 @@
import { CheckIcon, CopyIcon } from "@phosphor-icons/react";
import type { PostHogObjectArtifactMetadata } from "@posthog/core/canvas/runArtifactSchemas";
+import {
+ chartHeadlineStat,
+ reportChartHeightClass,
+ reportChartOpenTarget,
+} from "@posthog/core/inbox/reportCharts";
import {
Badge,
Button,
@@ -12,12 +17,20 @@ import {
Skeleton,
Text,
} from "@posthog/quill";
+import { getCloudUrlFromRegion } from "@posthog/shared";
+import { useAuthStateValue } from "@posthog/ui/features/auth/store";
import { useEvidenceUrl } from "@posthog/ui/features/editor/components/EvidenceRefChip";
import { MessageChartCard } from "@posthog/ui/features/editor/components/MessageChartCard";
import {
+ EVIDENCE_PREVIEW_STALE_TIME,
type EvidenceCardData,
+ evidencePreviewQueryKey,
fetchEvidencePreview,
} from "@posthog/ui/features/editor/evidencePreview";
+import {
+ type ReportChartCardState,
+ ReportChartCardView,
+} from "@posthog/ui/features/inbox/components/detail/ReportChartCard";
import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
import { useCopy } from "@posthog/ui/primitives/useCopy";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
@@ -28,6 +41,9 @@ import {
import { ExperimentResultsSummary } from "./ExperimentResultsSummary";
import { PostHogObjectDetails } from "./PostHogObjectDetails";
+const CHART_ERROR_MESSAGE =
+ "Couldn't run the query behind this chart. Open it in PostHog to investigate.";
+
function StatStrip({
stats,
}: {
@@ -84,6 +100,46 @@ const STATUS_BADGE_VARIANT = {
critical: "destructive",
} as const;
+function ObjectChartCard({
+ objectKind,
+ objectId,
+ title,
+ state,
+}: {
+ objectKind: string;
+ objectId: string;
+ title: string;
+ state: ReportChartCardState;
+}) {
+ const projectId = useAuthStateValue((s) => s.currentProjectId);
+ const cloudRegion = useAuthStateValue((s) => s.cloudRegion);
+ const data = state.kind === "data" ? state.data : null;
+ const openTarget =
+ projectId && cloudRegion
+ ? reportChartOpenTarget(
+ objectKind === "insight"
+ ? { kind: "SavedInsightNode", shortId: objectId }
+ : {
+ kind: "DataVisualizationNode",
+ source: { kind: "HogQLQuery", query: objectId },
+ },
+ { cloudUrl: getCloudUrlFromRegion(cloudRegion), projectId },
+ )
+ : null;
+ return (
+ <div className="mb-2">
+ <ReportChartCardView
+ chartId={`artifact:${objectKind}:${objectId}`}
+ title={title}
+ heightClass={reportChartHeightClass(null, data)}
+ state={state}
+ openTarget={openTarget}
+ stat={data ? chartHeadlineStat(data) : null}
+ />
+ </div>
+ );
+}
+
function FactChips({ facts }: { facts: string[] }) {
return (
<div className="flex flex-wrap gap-1.5">
@@ -182,7 +238,11 @@ export function PostHogObjectPageView({
const object = getObjectKind(objectKind);
const ObjectIcon = object.icon;
const usesChartRenderer = objectKind === "insight" || objectKind === "hogql";
- const title = preview?.title ?? fallbackName;
+ // A hogql preview's title is the first result column (raw SQL), a row
+ // count, or a formatted number, never the chip label, so the page shows the
+ // chip label instead. An insight's title is its live name and stays.
+ const title =
+ objectKind === "hogql" ? fallbackName : (preview?.title ?? fallbackName);
const status = preview?.status;
// The product name earns its place only when it adds context ("Insight ·
// Product analytics"); drop it when it restates the kind ("Feature flag ·
@@ -191,10 +251,14 @@ export function PostHogObjectPageView({
.toLowerCase()
.split(" ")[0]
.startsWith(object.kindLabel.toLowerCase().split(" ")[0]);
+ // A chart preview's `detail` joins its series labels for the hover card,
+ // which is raw SQL for hogql and duplicates the insight's legend; the page
+ // subtitle shows the object's own description instead, or nothing for hogql.
+ const subtitle = usesChartRenderer ? preview?.description : preview?.detail;
const metaLine = [
object.kindLabel,
showSource ? object.source : null,
- preview?.detail,
+ subtitle,
]
.filter(Boolean)
.join(" · ");
@@ -251,14 +315,40 @@ export function PostHogObjectPageView({
{preview && <PostHogObjectDetails preview={preview} />}
</div>
) : usesChartRenderer ? (
- <MessageChartCard
- spec={
- objectKind === "insight"
- ? { mode: "insight", shortId: objectId }
- : { mode: "hogql", query: objectId }
- }
- blockKey={`artifact:${objectKind}:${objectId}`}
- />
+ state === "loading" ? (
+ <Skeleton className="h-72 w-full rounded-lg" />
+ ) : state === "error" ? (
+ <ObjectChartCard
+ objectKind={objectKind}
+ objectId={objectId}
+ title={title}
+ state={{ kind: "error", message: CHART_ERROR_MESSAGE }}
+ />
+ ) : preview?.chartData ? (
+ <ObjectChartCard
+ objectKind={objectKind}
+ objectId={objectId}
+ title={title}
+ state={{ kind: "data", data: preview.chartData }}
+ />
+ ) : state === "missing" ? (
+ <ObjectChartCard
+ objectKind={objectKind}
+ objectId={objectId}
+ title={title}
+ state={{
+ kind: "error",
+ message: `No ${objectKind === "insight" ? "insight" : "query"} matches "${objectId}" in the current project.`,
+ }}
+ />
+ ) : (
+ <ObjectChartCard
+ objectKind={objectKind}
+ objectId={objectId}
+ title={title}
+ state={{ kind: "link-out" }}
+ />
+ )
) : state === "loading" ? (
// Mirrors the loaded layout (stat strip, chart, detail card) so
// content lands in place instead of reflowing the page.
@@ -301,18 +391,18 @@ export function PostHogObjectPage({
Partial<Omit<PostHogObjectArtifactMetadata, "object_kind" | "object_id">>;
fallbackName: string;
}) {
- const usesChartRenderer =
- metadata.object_kind === "insight" || metadata.object_kind === "hogql";
const query = useAuthenticatedQuery(
- ["evidence-preview", metadata.object_kind, metadata.object_id],
+ evidencePreviewQueryKey({
+ kind: metadata.object_kind,
+ id: metadata.object_id,
+ }),
(client) =>
fetchEvidencePreview(client, {
kind: metadata.object_kind,
id: metadata.object_id,
}),
{
- enabled: !usesChartRenderer,
- staleTime: 5 * 60 * 1000,
+ staleTime: EVIDENCE_PREVIEW_STALE_TIME,
refetchOnWindowFocus: false,
retry: 1,
},
@@ -321,15 +411,13 @@ export function PostHogObjectPage({
metadata.object_kind,
query.data?.resolvedId ?? metadata.object_id,
);
- const state = usesChartRenderer
- ? "ready"
- : query.isPending
- ? "loading"
- : query.isError
- ? "error"
- : query.data
- ? "ready"
- : "missing";
+ const state = query.isPending
+ ? "loading"
+ : query.isError
+ ? "error"
+ : query.data
+ ? "ready"
+ : "missing";
return (
<PostHogObjectPageView
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 d868e1d203cd..265938edb7b3 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
@@ -204,7 +204,37 @@ export const SqlQuery: Story = {
fallbackName: "Total pageviews",
url: "https://us.posthog.com/project/2/sql?open_query=SELECT+1",
state: "ready",
- preview: null,
+ preview: {
+ title: "Total pageviews",
+ chartData: { type: "number", value: 68831577 },
+ },
+ },
+};
+
+export const InsightChart: Story = {
+ args: {
+ objectKind: "insight",
+ objectId: "9pQx3",
+ fallbackName: "Checkout funnel",
+ url: "https://us.posthog.com/project/2/insights/9pQx3",
+ occurrenceCount: 2,
+ state: "ready",
+ preview: {
+ title: "Checkout funnel",
+ detail: "Daily unique visitors",
+ headline: { value: "1.5M", delta: { direction: "down", label: "70%" } },
+ spark: { points: [24, 32, 28, 46, 51, 63, 58], render: "line" },
+ chartData: {
+ type: "series",
+ labels: DAYS,
+ series: [
+ { key: "series-0", label: "DAU", data: [24, 32, 28, 46, 51, 63, 58] },
+ ],
+ render: "line",
+ isTimeSeries: true,
+ interval: "day",
+ },
+ },
},
};