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): richer object pages with live charts (#85965)

Shy Alter60c7c5e35949
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 84066a157cd3..be938e05eb19 100644
--- a/products/desktop/packages/api-client/src/evidence-previews.test.ts
+++ b/products/desktop/packages/api-client/src/evidence-previews.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import {
+ cohortCriteriaSection,
compactCount,
dailySparkPoints,
decorateFlagPreview,
@@ -7,6 +8,8 @@ import {
exposureFact,
gridRows,
hogqlEscape,
+ pivotDailyGroups,
+ shapeActionPreview,
shapeCohortPreview,
shapeDashboardPreview,
shapeErrorIssuePreview,
@@ -36,12 +39,53 @@ describe("evidence preview shaping", () => {
},
experiment_set: [7],
} as unknown as Schemas.FeatureFlag);
- expect(preview).toEqual({
+ expect(preview).toMatchObject({
title: "new-checkout-flow",
- detail: "Enabled · New checkout rollout",
+ detail: "New checkout rollout",
+ status: { label: "Enabled", tone: "positive" },
facts: ["25% rollout", "2 variants", "Used by 1 experiment"],
resolvedId: "42",
});
+ expect(preview.sections).toContainEqual({
+ title: "Configuration",
+ fields: expect.arrayContaining([
+ { label: "Type", value: "Multivariate" },
+ { label: "Release conditions", value: "1 condition" },
+ ]),
+ });
+ });
+
+ it("summarizes flag release conditions without exposing raw filter JSON", () => {
+ const preview = shapeFlagPreview({
+ id: 42,
+ key: "new-checkout-flow",
+ active: true,
+ filters: {
+ groups: [
+ {
+ properties: [
+ {
+ key: "plan",
+ operator: "exact",
+ value: "pro",
+ },
+ ],
+ rollout_percentage: 25,
+ variant: "test",
+ },
+ ],
+ },
+ } as unknown as Schemas.FeatureFlag);
+
+ expect(preview.sections).toContainEqual({
+ title: "Release conditions",
+ fields: [
+ {
+ label: "Set 1",
+ value: "plan exact pro · 25% rollout · Variant: test",
+ },
+ ],
+ });
});
it("shows a disabled flag without a name as just the state", () => {
@@ -50,30 +94,57 @@ describe("evidence preview shaping", () => {
key: "old-flag",
active: false,
} as Schemas.FeatureFlag);
- expect(preview.detail).toBe("Disabled");
+ expect(preview.detail).toBeUndefined();
+ expect(preview.status).toEqual({ label: "Disabled", tone: "neutral" });
});
it.each([
- ["draft", {}, "Draft"],
- ["running", { start_date: "2024-01-03T10:00:00Z" }, /^Running since Jan 3/],
+ ["draft", {}, "Draft", undefined],
+ [
+ "running",
+ { start_date: "2024-01-03T10:00:00Z" },
+ "Running",
+ /· Started Jan 3/,
+ ],
[
"ended",
{ start_date: "2024-01-03T10:00:00Z", end_date: "2024-02-02T10:00:00Z" },
- /^Ended Feb 2/,
+ "Ended",
+ /^Jan 3(, \d{4})? to Feb 2/,
],
- ])("describes a %s experiment", (_state, dates, expected) => {
- const preview = shapeExperimentPreview({
- id: 7,
- name: "Reminder timing",
- ...dates,
- } as Schemas.Experiment);
- expect(preview.title).toBe("Reminder timing");
- if (typeof expected === "string") {
- expect(preview.detail).toBe(expected);
- } else {
- expect(preview.detail).toMatch(expected);
- }
- });
+ ] as const)(
+ "describes a %s experiment",
+ (_state, dates, statusLabel, detail) => {
+ const preview = shapeExperimentPreview({
+ id: 7,
+ name: "Reminder timing",
+ ...dates,
+ } as Schemas.Experiment);
+ expect(preview.title).toBe("Reminder timing");
+ expect(preview.status?.label).toBe(statusLabel);
+ if (detail) {
+ expect(preview.detail).toMatch(detail);
+ } else {
+ expect(preview.detail).toBeUndefined();
+ }
+ },
+ );
+
+ it.each([
+ ["paused", "Paused", "caution"],
+ ["exposure_frozen", "Exposure frozen", "neutral"],
+ ] as const)(
+ "labels a %s experiment from the API status, not the start date",
+ (apiStatus, label, tone) => {
+ const preview = shapeExperimentPreview({
+ id: 7,
+ name: "Reminder timing",
+ start_date: "2024-01-03T10:00:00Z",
+ status: apiStatus,
+ } as unknown as Schemas.Experiment);
+ expect(preview.status).toEqual({ label, tone });
+ },
+ );
it("humanizes the error issue status", () => {
const preview = shapeErrorIssuePreview({
@@ -82,7 +153,11 @@ describe("evidence preview shaping", () => {
status: "pending_release",
first_seen: "2024-01-03T10:00:00Z",
} as Schemas.ErrorTrackingIssueFull);
- expect(preview.detail).toMatch(/^Pending release · First seen Jan 3/);
+ expect(preview.detail).toMatch(/^First seen Jan 3/);
+ expect(preview.status).toEqual({
+ label: "Pending release",
+ tone: "neutral",
+ });
});
it.each([
@@ -125,7 +200,7 @@ describe("evidence preview shaping", () => {
status_reason: "Provider key expired",
evaluation_type: "llm_judge",
} as unknown as Schemas.Evaluation),
- ).toEqual({
+ ).toMatchObject({
title: "Faithfulness eval",
detail: "Enabled · Provider key expired",
facts: ["LLM judge"],
@@ -151,6 +226,32 @@ describe("evidence preview shaping", () => {
]);
});
+ it("exposes chartable tiles by insight short id, skipping tiles without one", () => {
+ const preview = shapeDashboardPreview({
+ id: 12,
+ name: "Growth",
+ tiles: [
+ { insight: { name: "DAU", short_id: "abc123" } },
+ { insight: { name: "Text tile without insight id" } },
+ { text: { body: "A text tile" } },
+ ],
+ } as unknown as Schemas.Dashboard);
+ expect(preview.tiles).toEqual([{ shortId: "abc123", name: "DAU" }]);
+ });
+
+ it("caps chartable tiles so a large dashboard doesn't open one query per tile", () => {
+ const tiles = Array.from({ length: 20 }, (_, index) => ({
+ insight: { name: `Insight ${index}`, short_id: `id${index}` },
+ }));
+ const preview = shapeDashboardPreview({
+ id: 12,
+ name: "Growth",
+ tiles,
+ } as unknown as Schemas.Dashboard);
+ expect(preview.tiles).toHaveLength(6);
+ expect(preview.tiles?.[0]).toEqual({ shortId: "id0", name: "Insight 0" });
+ });
+
// The remainder counts unnamed tiles too: named tiles are shown, but every
// tile that filtered out of the name list still has to appear in "+N more".
it.each([
@@ -195,6 +296,219 @@ describe("evidence preview shaping", () => {
).toBe("Weekly active users");
});
+ it("describes cohort membership criteria as prose, skipping unknown nodes", () => {
+ const sections = cohortCriteriaSection({
+ properties: {
+ type: "OR",
+ values: [
+ {
+ type: "AND",
+ values: [
+ {
+ type: "behavioral",
+ value: "performed_event",
+ key: "$pageview",
+ time_value: 30,
+ time_interval: "day",
+ },
+ {
+ type: "person",
+ key: "email",
+ operator: "icontains",
+ value: "@example.com",
+ },
+ ],
+ },
+ {
+ type: "OR",
+ values: [
+ { type: "mystery", key: "??" },
+ {
+ type: "behavioral",
+ value: "performed_event_multiple",
+ key: "file saved",
+ operator: "gte",
+ operator_value: 3,
+ time_value: 1,
+ time_interval: "week",
+ },
+ ],
+ },
+ ],
+ },
+ });
+ expect(sections).toEqual([
+ {
+ title: "Membership criteria",
+ fields: [
+ {
+ label: "Group 1",
+ value:
+ "Completed $pageview in the last 30 days and email contains @example.com",
+ },
+ {
+ label: "Group 2 (or)",
+ value: "Completed file saved at least 3 times in the last 1 week",
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("renders negated criteria as their negative meaning", () => {
+ const sections = cohortCriteriaSection({
+ properties: {
+ type: "AND",
+ values: [
+ {
+ type: "AND",
+ values: [
+ {
+ type: "behavioral",
+ value: "performed_event",
+ key: "checkout",
+ negation: true,
+ },
+ {
+ type: "cohort",
+ value: "Power users",
+ negation: true,
+ },
+ {
+ type: "person",
+ key: "email",
+ operator: "icontains",
+ value: "@example.com",
+ negation: true,
+ },
+ ],
+ },
+ ],
+ },
+ });
+ expect(sections).toEqual([
+ {
+ title: "Membership criteria",
+ fields: [
+ {
+ label: "Criteria",
+ value:
+ "Did not complete checkout and Is not in cohort Power users and email does not contain @example.com",
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("renders the legacy multiple-event alias with its count rule", () => {
+ const sections = cohortCriteriaSection({
+ properties: {
+ type: "AND",
+ values: [
+ {
+ type: "AND",
+ values: [
+ {
+ type: "behavioral",
+ value: "performed_event_multiple_times",
+ key: "$pageview",
+ operator: "gte",
+ operator_value: 5,
+ time_value: 30,
+ time_interval: "day",
+ },
+ ],
+ },
+ ],
+ },
+ });
+ expect(sections[0]?.fields[0]?.value).toBe(
+ "Completed $pageview at least 5 times in the last 30 days",
+ );
+ });
+
+ it("returns no criteria section for a static or malformed cohort", () => {
+ expect(cohortCriteriaSection(undefined)).toEqual([]);
+ expect(cohortCriteriaSection({ properties: { values: "junk" } })).toEqual(
+ [],
+ );
+ });
+
+ it("pivots (day, group, count) rows into zero-filled series per group", () => {
+ expect(
+ pivotDailyGroups([
+ ["2026-08-02", "control", 4],
+ ["2026-08-01", "control", 2],
+ ["2026-08-01", "test", 3],
+ ]),
+ ).toEqual({
+ labels: ["2026-08-01", "2026-08-02"],
+ series: [
+ { label: "control", data: [2, 4] },
+ { label: "test", data: [3, 0] },
+ ],
+ omittedGroups: 0,
+ });
+ expect(pivotDailyGroups([["2026-08-01", "control", 2]])).toBeNull();
+ });
+
+ it("keeps the highest-volume groups and counts the omitted ones", () => {
+ // 7 variants over 2 days; "control" has the largest total but appears last
+ // in row order, so first-seen slicing would have dropped it.
+ const variants: Array<[string, number]> = [
+ ["a", 1],
+ ["b", 2],
+ ["c", 3],
+ ["d", 4],
+ ["e", 5],
+ ["f", 6],
+ ["control", 100],
+ ];
+ const rows = ["2026-08-01", "2026-08-02"].flatMap((day) =>
+ variants.map(([variant, count]) => [day, variant, count]),
+ );
+ const pivot = pivotDailyGroups(rows);
+ expect(pivot?.omittedGroups).toBe(1);
+ expect(pivot?.series.map((entry) => entry.label)).toEqual([
+ "control",
+ "f",
+ "e",
+ "d",
+ "c",
+ "b",
+ ]);
+ });
+
+ it("describes action match groups in its details", () => {
+ const preview = shapeActionPreview({
+ id: 42,
+ name: "Checkout click",
+ description: "Tracks checkout clicks",
+ steps: [
+ {
+ event: "$autocapture",
+ url: "/checkout",
+ selector: "button[data-attr=checkout]",
+ properties: [{ key: "$current_url", value: "/checkout" }],
+ },
+ ],
+ is_calculating: false,
+ last_calculated_at: "2024-01-03T10:00:00Z",
+ created_at: "2024-01-02T10:00:00Z",
+ } as unknown as Schemas.Action);
+
+ expect(preview.sections).toContainEqual({
+ title: "Match groups",
+ fields: [
+ {
+ label: "Group 1",
+ value:
+ "Event: $autocapture · URL: /checkout · Selector: button[data-attr=checkout] · 1 property",
+ },
+ ],
+ });
+ });
+
it("summarizes a ticket with its snippet, state line, and traffic", () => {
const preview = shapeTicketPreview({
id: "t1",
@@ -319,6 +633,7 @@ describe("evidence preview shaping", () => {
expect(preview.facts).toEqual(["Stale", "100% rollout", "2.1M calls (7d)"]);
expect(preview.spark).toEqual({
points: [900000, 1200000],
+ labels: ["2024-01-01", "2024-01-02"],
render: "line",
});
});
@@ -337,7 +652,7 @@ describe("evidence preview shaping", () => {
it("rolls a trace up to generations, cost, latency, and errors", () => {
expect(
shapeTracePreview([7, 0.42, 18.3, ["gpt-5", "claude-4"], 2]),
- ).toEqual({
+ ).toMatchObject({
title: "7 generations",
facts: ["$0.42", "18.3s", "2 models", "2 errors"],
});
@@ -369,7 +684,7 @@ describe("evidence preview shaping", () => {
],
},
} as unknown as Schemas.Experiment);
- expect(preview.detail).toMatch(/· Day 12$/);
+ expect(preview.detail).toMatch(/^Day 12 ·/);
expect(preview.facts).toEqual([
"2 variants (50/50)",
"Flag: reminder-timing",
@@ -381,6 +696,9 @@ describe("evidence preview shaping", () => {
id: "srv-11",
name: "Checkout survey",
} as Schemas.Survey);
- expect(preview).toEqual({ title: "Checkout survey", detail: "Draft" });
+ expect(preview).toMatchObject({
+ title: "Checkout survey",
+ status: { label: "Draft", tone: "neutral" },
+ });
});
});
diff --git a/products/desktop/packages/api-client/src/evidence-previews.ts b/products/desktop/packages/api-client/src/evidence-previews.ts
index 1bcfb1265ed9..111acd8737b9 100644
--- a/products/desktop/packages/api-client/src/evidence-previews.ts
+++ b/products/desktop/packages/api-client/src/evidence-previews.ts
@@ -8,15 +8,58 @@
import type { Schemas } from "./generated";
+export interface EvidenceDetailField {
+ label: string;
+ value: string;
+}
+
+export interface EvidenceDetailSection {
+ title: string;
+ fields: EvidenceDetailField[];
+}
+
export interface EvidencePreview {
/** The object's name in PostHog. */
title: string;
- /** One line of status or context, e.g. "Enabled" or "Running since Jan 3". */
+ /** One line of context, e.g. the object's description or timeline. */
detail?: string;
+ /**
+ * The object's lifecycle state as a badge: label plus a tone the UI maps to
+ * a color. Kept out of `detail` so surfaces can style it.
+ */
+ status?: {
+ label: string;
+ tone: "positive" | "neutral" | "caution" | "critical";
+ };
/** Short scannable attributes, e.g. "100% rollout" or "42 clicks". */
facts?: string[];
- /** Mini chart of the object's recent activity, oldest point first. */
- spark?: { points: number[]; render: "line" | "bar" };
+ /**
+ * Headline numbers as label/value pairs. Full pages draw these as a stat
+ * strip and then skip the fact chips; hover chips keep using `facts`.
+ */
+ stats?: Array<{ label: string; value: string }>;
+ /**
+ * Mini chart of the object's recent activity, oldest point first. `labels`
+ * carries the bucket dates so a full page can draw a real chart with hover
+ * values; the hover chip's sparkline ignores them.
+ */
+ spark?: { points: number[]; labels?: string[]; render: "line" | "bar" };
+ /**
+ * A titled multi-series time chart (e.g. experiment exposures per variant),
+ * drawn with hover values on full pages; hover chips ignore it.
+ */
+ chart?: {
+ title: string;
+ labels: string[];
+ series: Array<{ label: string; data: number[] }>;
+ render: "line" | "bar";
+ };
+ sections?: EvidenceDetailSection[];
+ /**
+ * A dashboard's tiles, each resolvable to a live insight chart, so a full
+ * page can render the metrics themselves rather than describe them.
+ */
+ tiles?: Array<{ shortId: string; name: string | null }>;
/**
* Canonical id when it differs from the cited one (a feature flag cited by
* key, an event cited by name), so the caller can build the object's URL.
@@ -62,15 +105,53 @@ export function dailySparkPoints(rows: unknown[][]): number[] {
return rows.map((row) => cellNumber(row[1]) ?? 0);
}
+/** (day, count) rows -> the points' bucket dates, oldest first. */
+export function dailySparkLabels(rows: unknown[][]): string[] {
+ return rows.map((row) => String(row[0]));
+}
+
function count(n: number, noun: string, plural = `${noun}s`): string {
return `${n.toLocaleString("en-US")} ${n === 1 ? noun : plural}`;
}
-function isRecord(value: unknown): value is Record<string, unknown> {
+type QueryRecord = Record<string, unknown>;
+
+function isRecord(value: unknown): value is QueryRecord {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
-function formatDay(iso: string): string {
+/** An "Activity" section from (label, value) pairs, dropping empty values. */
+export function activitySection(
+ fields: Array<[string, string | null | undefined]>,
+): EvidenceDetailSection[] {
+ return detailSection("Activity", fields);
+}
+
+function detailSection(
+ title: string,
+ fields: Array<[string, string | null | undefined]>,
+): EvidenceDetailSection[] {
+ const present = fields.flatMap(([label, value]) =>
+ value ? [{ label, value }] : [],
+ );
+ return present.length > 0 ? [{ title, fields: present }] : [];
+}
+
+function stringValue(value: unknown): string | null {
+ if (typeof value === "string" && value) return value;
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
+ if (typeof value === "boolean") return value ? "Yes" : "No";
+ return null;
+}
+
+function conciseValue(value: unknown): string | null {
+ const valueAsString = stringValue(value);
+ if (valueAsString) return valueAsString.slice(0, 120);
+ if (Array.isArray(value)) return value.map(String).join(", ").slice(0, 120);
+ return null;
+}
+
+export function formatDay(iso: string): string {
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return iso;
const sameYear = date.getFullYear() === new Date().getFullYear();
@@ -87,8 +168,55 @@ function humanizeStatus(status: string): string {
return words.charAt(0).toUpperCase() + words.slice(1);
}
+function actionStepSummary(step: unknown): string | null {
+ if (!isRecord(step)) return null;
+ const terms = [
+ ["Event", conciseValue(step.event)],
+ ["URL", conciseValue(step.url)],
+ ["Selector", conciseValue(step.selector)],
+ ["Text", conciseValue(step.text)],
+ ["Link", conciseValue(step.href)],
+ ].flatMap(([label, value]) => (value ? [`${label}: ${value}`] : []));
+ const properties = Array.isArray(step.properties)
+ ? step.properties.length
+ : 0;
+ if (properties > 0) terms.push(count(properties, "property"));
+ return terms.length > 0 ? terms.join(" · ") : null;
+}
+
+function flagConditionSummary(group: unknown): string | null {
+ if (!isRecord(group)) return null;
+ const properties = Array.isArray(group.properties)
+ ? group.properties
+ .flatMap((property) => {
+ if (!isRecord(property)) return [];
+ const key = conciseValue(property.key);
+ const operator = conciseValue(property.operator) ?? "equals";
+ const value = conciseValue(property.value);
+ return key && value ? [`${key} ${operator} ${value}`] : [];
+ })
+ .join(", ")
+ : "";
+ const rollout =
+ typeof group.rollout_percentage === "number"
+ ? `${group.rollout_percentage}% rollout`
+ : null;
+ const variant = conciseValue(group.variant);
+ const summary = [properties, rollout, variant ? `Variant: ${variant}` : null]
+ .filter(Boolean)
+ .join(" · ");
+ return summary || null;
+}
+
+function surveyQuestionSummary(question: unknown): string | null {
+ if (!isRecord(question)) return null;
+ const prompt = conciseValue(question.question);
+ const type = conciseValue(question.type);
+ if (!prompt) return type;
+ return type ? `${prompt} (${humanizeStatus(type)})` : prompt;
+}
+
export function shapeFlagPreview(flag: Schemas.FeatureFlag): EvidencePreview {
- const state = flag.active ? "Enabled" : "Disabled";
const name = flag.name?.trim();
const facts: string[] = [];
@@ -103,6 +231,7 @@ export function shapeFlagPreview(flag: Schemas.FeatureFlag): EvidencePreview {
const multivariate = isRecord(filters.multivariate)
? filters.multivariate
: null;
+ const isMultivariate = multivariate !== null;
const variants = Array.isArray(multivariate?.variants)
? multivariate.variants.length
: 0;
@@ -111,10 +240,69 @@ export function shapeFlagPreview(flag: Schemas.FeatureFlag): EvidencePreview {
facts.push(`Used by ${count(flag.experiment_set.length, "experiment")}`);
}
+ const flagType = flag.is_remote_configuration
+ ? "Remote config"
+ : isMultivariate
+ ? "Multivariate"
+ : "Boolean";
+ const singleRollout =
+ groups.length === 1 && isRecord(groups[0])
+ ? groups[0].rollout_percentage
+ : null;
+ const stats: Array<{ label: string; value: string }> = [
+ ...(typeof singleRollout === "number"
+ ? [{ label: "Rollout", value: `${singleRollout}%` }]
+ : groups.length > 1
+ ? [{ label: "Release conditions", value: String(groups.length) }]
+ : []),
+ ...(variants > 0 ? [{ label: "Variants", value: String(variants) }] : []),
+ { label: "Type", value: flagType },
+ ];
return {
title: flag.key,
- detail: name ? `${state} · ${name}` : state,
+ detail: name || undefined,
+ status: flag.active
+ ? { label: "Enabled", tone: "positive" }
+ : { label: "Disabled", tone: "neutral" },
facts,
+ stats,
+ sections: [
+ ...detailSection("Configuration", [
+ ["Type", flagType],
+ [
+ "Release conditions",
+ groups.length ? count(groups.length, "condition") : "All users",
+ ],
+ [
+ "Evaluation runtime",
+ flag.evaluation_runtime === "all"
+ ? "All runtimes"
+ : flag.evaluation_runtime
+ ? humanizeStatus(String(flag.evaluation_runtime))
+ : null,
+ ],
+ [
+ "Experience continuity",
+ flag.ensure_experience_continuity === null ||
+ flag.ensure_experience_continuity === undefined
+ ? null
+ : flag.ensure_experience_continuity
+ ? "Enabled"
+ : "Disabled",
+ ],
+ [
+ "Last called",
+ flag.last_called_at ? formatDay(flag.last_called_at) : null,
+ ],
+ ]),
+ ...detailSection(
+ "Release conditions",
+ groups.map((group, index) => [
+ `Set ${index + 1}`,
+ flagConditionSummary(group),
+ ]),
+ ),
+ ],
resolvedId: String(flag.id),
};
}
@@ -122,19 +310,39 @@ export function shapeFlagPreview(flag: Schemas.FeatureFlag): EvidencePreview {
export function shapeExperimentPreview(
experiment: Schemas.Experiment,
): EvidencePreview {
- let detail: string;
- if (experiment.end_date) {
- detail = `Ended ${formatDay(experiment.end_date)}`;
+ let detail: string | undefined;
+ let status: EvidencePreview["status"];
+ // The API's status distinguishes paused and exposure-frozen experiments,
+ // which both still have a start date and no end date, so the date range alone
+ // reads them as "Running". The generated enum is narrower than the backend's
+ // real values, so read the status as a plain string; fall back to the dates
+ // for responses without one.
+ const apiStatus: string | null =
+ typeof experiment.status === "string" ? experiment.status : null;
+ if (apiStatus === "paused" || apiStatus === "exposure_frozen") {
+ status =
+ apiStatus === "paused"
+ ? { label: "Paused", tone: "caution" }
+ : { label: "Exposure frozen", tone: "neutral" };
+ if (experiment.start_date) {
+ detail = `Started ${formatDay(experiment.start_date)}`;
+ }
+ } else if (experiment.end_date) {
+ status = { label: "Ended", tone: "neutral" };
+ detail = experiment.start_date
+ ? `${formatDay(experiment.start_date)} to ${formatDay(experiment.end_date)}`
+ : `Ended ${formatDay(experiment.end_date)}`;
} else if (experiment.start_date) {
+ status = { label: "Running", tone: "positive" };
const days = Math.max(
1,
Math.ceil(
(Date.now() - new Date(experiment.start_date).getTime()) / 86_400_000,
),
);
- detail = `Running since ${formatDay(experiment.start_date)} · Day ${days}`;
+ detail = `Day ${days} · Started ${formatDay(experiment.start_date)}`;
} else {
- detail = "Draft";
+ status = { label: "Draft", tone: "neutral" };
}
const facts: string[] = [];
@@ -144,15 +352,18 @@ export function shapeExperimentPreview(
const variants = Array.isArray(parameters.feature_flag_variants)
? parameters.feature_flag_variants.filter(isRecord)
: [];
- if (variants.length > 1) {
- const split = variants
- .map((variant) =>
- typeof variant.rollout_percentage === "number"
- ? String(variant.rollout_percentage)
- : "?",
- )
- .join("/");
- facts.push(`${count(variants.length, "variant")} (${split})`);
+ const variantSplit =
+ variants.length > 1
+ ? variants
+ .map((variant) =>
+ typeof variant.rollout_percentage === "number"
+ ? String(variant.rollout_percentage)
+ : "?",
+ )
+ .join("/")
+ : null;
+ if (variantSplit) {
+ facts.push(`${count(variants.length, "variant")} (${variantSplit})`);
}
if (experiment.feature_flag_key) {
facts.push(`Flag: ${experiment.feature_flag_key}`);
@@ -161,7 +372,75 @@ export function shapeExperimentPreview(
(metric) => typeof metric.name === "string" && metric.name,
);
if (primaryMetric) facts.push(`Metric: ${primaryMetric.name}`);
- return { title: experiment.name, detail, facts };
+ const outcome =
+ typeof experiment.conclusion === "string" && experiment.conclusion
+ ? humanizeStatus(experiment.conclusion)
+ : null;
+ const metricNames = (metrics: unknown): Array<[string, string | null]> =>
+ (Array.isArray(metrics) ? metrics.filter(isRecord) : []).flatMap(
+ (metric, index) => {
+ const name =
+ conciseValue(metric.name) ??
+ (isRecord(metric.source) ? conciseValue(metric.source.name) : null);
+ return name ? [[`Metric ${index + 1}`, name]] : [];
+ },
+ );
+ const savedMetricNames: Array<[string, string | null]> = (
+ experiment.saved_metrics ?? []
+ ).flatMap((metric, index) =>
+ typeof metric.name === "string" && metric.name
+ ? [[`Shared metric ${index + 1}`, metric.name]]
+ : [],
+ );
+ const stats: Array<{ label: string; value: string }> = [];
+ if (experiment.start_date && !experiment.end_date) {
+ const days = Math.max(
+ 1,
+ Math.ceil(
+ (Date.now() - new Date(experiment.start_date).getTime()) / 86_400_000,
+ ),
+ );
+ stats.push({ label: "Running for", value: count(days, "day") });
+ } else if (experiment.end_date) {
+ stats.push({ label: "Ended", value: formatDay(experiment.end_date) });
+ }
+ if (variants.length > 0) {
+ stats.push({ label: "Variants", value: String(variants.length) });
+ }
+ return {
+ title: experiment.name,
+ detail,
+ status,
+ facts,
+ stats,
+ sections: [
+ ...detailSection("Configuration", [
+ ["Hypothesis", experiment.description || null],
+ ["Feature flag", experiment.feature_flag_key],
+ ["Variants", variantSplit],
+ ["Primary metric", primaryMetric?.name ?? null],
+ ["Conclusion", outcome],
+ ["Conclusion notes", experiment.conclusion_comment || null],
+ [
+ "Created",
+ experiment.created_at ? formatDay(experiment.created_at) : null,
+ ],
+ ]),
+ ...detailSection("Metrics", [
+ ...metricNames(experiment.metrics),
+ ...savedMetricNames,
+ ]),
+ ...detailSection(
+ "Variants",
+ variants.map((variant, index) => [
+ conciseValue(variant.key) ?? `Variant ${index + 1}`,
+ typeof variant.rollout_percentage === "number"
+ ? `${variant.rollout_percentage}% rollout`
+ : null,
+ ]),
+ ),
+ ],
+ };
}
const EVALUATION_TYPE_LABELS: Record<string, string> = {
@@ -178,10 +457,93 @@ export function shapeEvaluationPreview(
const typeLabel =
EVALUATION_TYPE_LABELS[String(evaluation.evaluation_type)] ??
String(evaluation.evaluation_type);
+ const modelConfiguration = (evaluation as unknown as Record<string, unknown>)
+ .model_configuration;
+ const model = isRecord(modelConfiguration)
+ ? stringValue(modelConfiguration.model)
+ : null;
+ const conditions = Array.isArray(evaluation.conditions)
+ ? evaluation.conditions.length
+ : 0;
return {
title: evaluation.name,
detail: reason ? `${state} · ${reason}` : state,
facts: [typeLabel],
+ sections: [
+ ...detailSection("Configuration", [
+ ["State", state],
+ ["Method", typeLabel],
+ ["Model", model],
+ [
+ "Trigger conditions",
+ conditions ? count(conditions, "condition") : "All matching data",
+ ],
+ [
+ "Updated",
+ evaluation.updated_at ? formatDay(evaluation.updated_at) : null,
+ ],
+ ]),
+ ...detailSection(
+ "Trigger conditions",
+ (Array.isArray(evaluation.conditions) ? evaluation.conditions : []).map(
+ (condition, index) => [
+ `Condition ${index + 1}`,
+ flagConditionSummary(condition),
+ ],
+ ),
+ ),
+ ],
+ };
+}
+
+const MAX_CHART_SERIES = 6;
+
+/**
+ * (day, group, count) rows -> one series per group, zero-filled across the
+ * days that appear anywhere in the grid. Days are sorted ascending. Groups are
+ * ranked by total count (descending, then by name) and capped at
+ * MAX_CHART_SERIES, so the highest-volume groups survive and the cut is
+ * deterministic rather than dependent on row order. `omittedGroups` reports how
+ * many were dropped, so the caller can say a chart is partial instead of hiding
+ * groups silently.
+ */
+export function pivotDailyGroups(rows: unknown[][]): {
+ labels: string[];
+ series: Array<{ label: string; data: number[] }>;
+ omittedGroups: number;
+} | null {
+ const labels = [...new Set(rows.map((row) => String(row[0])))].sort();
+ const groupTotals = new Map<string, number>();
+ for (const row of rows) {
+ const group = String(row[1]);
+ groupTotals.set(
+ group,
+ (groupTotals.get(group) ?? 0) + (cellNumber(row[2]) ?? 0),
+ );
+ }
+ if (labels.length < 2 || groupTotals.size === 0) return null;
+ const rankedGroups = [...groupTotals.keys()].sort((a, b) => {
+ const byTotal = (groupTotals.get(b) ?? 0) - (groupTotals.get(a) ?? 0);
+ return byTotal !== 0 ? byTotal : a < b ? -1 : a > b ? 1 : 0;
+ });
+ const shownGroups = rankedGroups.slice(0, MAX_CHART_SERIES);
+ const labelIndex = new Map(labels.map((label, i) => [label, i]));
+ const series = shownGroups.map((label) => ({
+ label,
+ data: labels.map(() => 0),
+ }));
+ const seriesByGroup = new Map(series.map((entry) => [entry.label, entry]));
+ for (const row of rows) {
+ const target = seriesByGroup.get(String(row[1]));
+ const position = labelIndex.get(String(row[0]));
+ if (target && position !== undefined) {
+ target.data[position] = cellNumber(row[2]) ?? 0;
+ }
+ }
+ return {
+ labels,
+ series,
+ omittedGroups: rankedGroups.length - shownGroups.length,
};
}
@@ -206,18 +568,37 @@ export function decorateFlagPreview(
): EvidencePreview {
const facts = [...(preview.facts ?? [])];
let detail = preview.detail;
+ let state = preview.status;
if (status?.status?.toLowerCase() === "stale") {
facts.unshift("Stale");
+ state = { label: "Stale", tone: "caution" };
if (status.reason) detail = status.reason;
}
const points = dailySparkPoints(volumeRows);
const total = points.reduce((sum, value) => sum + value, 0);
if (total > 0) facts.push(`${compactCount(total)} calls (7d)`);
+ const stats = [
+ ...(preview.stats ?? []),
+ ...(total > 0
+ ? [{ label: "Calls in 7 days", value: compactCount(total) }]
+ : []),
+ ];
return {
...preview,
detail,
+ status: state,
facts,
- spark: points.length > 1 ? { points, render: "line" } : undefined,
+ stats,
+ spark:
+ points.length > 1
+ ? { points, labels: dailySparkLabels(volumeRows), render: "line" }
+ : undefined,
+ sections: [
+ ...(preview.sections ?? []),
+ ...detailSection("Activity", [
+ ["Calls in 7 days", total > 0 ? compactCount(total) : null],
+ ]),
+ ],
};
}
@@ -237,7 +618,20 @@ export function shapeTracePreview(row: unknown[]): EvidencePreview | null {
else if (models.length > 1) facts.push(count(models.length, "model"));
const errors = Number(row[4]) || 0;
if (errors > 0) facts.push(count(errors, "error"));
- return { title: count(generations, "generation"), facts };
+ return {
+ title: count(generations, "generation"),
+ facts,
+ sections: detailSection("Trace", [
+ ["Generations", count(generations, "generation")],
+ ["Cost", Number.isFinite(cost) && cost > 0 ? `$${cost}` : null],
+ [
+ "Latency",
+ Number.isFinite(latency) && latency > 0 ? `${latency}s` : null,
+ ],
+ ["Models", models.length ? models.join(", ") : null],
+ ["Errors", errors > 0 ? count(errors, "error") : null],
+ ]),
+ };
}
/** Fold `surveys/{id}/stats/` into a survey preview: responses and rate. */
@@ -257,18 +651,52 @@ export function decorateSurveyPreview(
if (Number.isFinite(responseRate) && responseRate > 0) {
facts.push(`${Math.round(responseRate)}% response rate`);
}
- return { ...preview, facts };
+ return {
+ ...preview,
+ facts,
+ sections: [
+ ...(preview.sections ?? []),
+ ...detailSection("Results", [
+ ["Responses", Number.isFinite(sent) ? count(sent, "response") : null],
+ [
+ "Response rate",
+ Number.isFinite(responseRate) && responseRate > 0
+ ? `${Math.round(responseRate)}%`
+ : null,
+ ],
+ ]),
+ ],
+ };
}
export function shapeErrorIssuePreview(
issue: Schemas.ErrorTrackingIssueFull,
): EvidencePreview {
const firstSeen = `First seen ${formatDay(issue.first_seen)}`;
+ const assignee = issue.assignee
+ ? `${issue.assignee.type} (${issue.assignee.id})`
+ : null;
return {
title: issue.name || "Untitled issue",
- detail: issue.status
- ? `${humanizeStatus(issue.status)} · ${firstSeen}`
- : firstSeen,
+ detail: firstSeen,
+ status: issue.status
+ ? {
+ label: humanizeStatus(issue.status),
+ tone: issue.status === "active" ? "caution" : "neutral",
+ }
+ : undefined,
+ sections: detailSection("Issue", [
+ ["Status", issue.status ? humanizeStatus(issue.status) : null],
+ ["First seen", formatDay(issue.first_seen)],
+ ["Assignee", assignee],
+ [
+ "Linked issues",
+ issue.external_issues?.length
+ ? count(issue.external_issues.length, "issue")
+ : null,
+ ],
+ ["Affected cohort", issue.cohort?.name ?? null],
+ ]),
};
}
@@ -316,9 +744,40 @@ export function shapeRecordingPreview(
title: person ? `Session by ${person}` : "Session recording",
detail: parts.join(" · "),
facts,
+ sections: detailSection("Session", [
+ ["Duration", duration],
+ [
+ "Active time",
+ typeof recording.active_seconds === "number"
+ ? `${Math.round(recording.active_seconds)}s`
+ : null,
+ ],
+ ["Start URL", recording.start_url],
+ [
+ "Clicks",
+ recording.click_count ? count(recording.click_count, "click") : null,
+ ],
+ [
+ "Console errors",
+ recording.console_error_count
+ ? count(recording.console_error_count, "console error")
+ : null,
+ ],
+ [
+ "Expires",
+ recording.expiry_time ? formatDay(recording.expiry_time) : null,
+ ],
+ ]),
};
}
+// Each rendered tile mounts a card that fires its own blocking insight
+// refresh, and those queries share no concurrency limit, so an uncapped list
+// opens one long-running request per tile at once when the page mounts. Bound
+// the preview to a handful of tiles, matching the Insights section; the whole
+// dashboard stays one "Open in PostHog" click away.
+const MAX_DASHBOARD_CHART_TILES = 6;
+
export function shapeDashboardPreview(
dashboard: Schemas.Dashboard,
): EvidencePreview {
@@ -340,32 +799,289 @@ export function shapeDashboardPreview(
} else if (Array.isArray(dashboard.tiles)) {
facts.push(count(tiles.length, "tile"));
}
+ const filters = isRecord(dashboard.filters) ? dashboard.filters : {};
+ const variables = isRecord(dashboard.variables) ? dashboard.variables : {};
+ const chartTiles = tiles
+ .flatMap((tile) => {
+ if (!isRecord(tile) || !isRecord(tile.insight)) return [];
+ const shortId = tile.insight.short_id;
+ if (typeof shortId !== "string" || !shortId) return [];
+ return [
+ {
+ shortId,
+ name:
+ typeof tile.insight.name === "string" ? tile.insight.name : null,
+ },
+ ];
+ })
+ .slice(0, MAX_DASHBOARD_CHART_TILES);
return {
title: dashboard.name || "Untitled dashboard",
detail: dashboard.description || undefined,
facts,
+ tiles: chartTiles,
+ sections: [
+ ...detailSection("Dashboard", [
+ ["Tiles", count(tiles.length, "tile")],
+ ["Shared", dashboard.is_shared ? "Yes" : "No"],
+ [
+ "Filters",
+ Object.keys(filters).length
+ ? count(Object.keys(filters).length, "filter")
+ : null,
+ ],
+ [
+ "Variables",
+ Object.keys(variables).length
+ ? count(Object.keys(variables).length, "variable")
+ : null,
+ ],
+ [
+ "Last refreshed",
+ dashboard.last_refresh ? formatDay(dashboard.last_refresh) : null,
+ ],
+ ]),
+ ...detailSection(
+ "Insights",
+ names.slice(0, 6).map((name, index) => [`Tile ${index + 1}`, name]),
+ ),
+ ],
};
}
+const PROPERTY_OPERATOR_LABELS: Record<string, string> = {
+ exact: "is",
+ is_not: "is not",
+ icontains: "contains",
+ not_icontains: "does not contain",
+ regex: "matches",
+ not_regex: "does not match",
+ gt: "is greater than",
+ gte: "is at least",
+ lt: "is less than",
+ lte: "is at most",
+ is_set: "is set",
+ is_not_set: "is not set",
+};
+
+const NEGATED_PROPERTY_OPERATOR_LABELS: Record<string, string> = {
+ exact: "is not",
+ is_not: "is",
+ icontains: "does not contain",
+ not_icontains: "contains",
+ regex: "does not match",
+ not_regex: "matches",
+ gt: "is at most",
+ gte: "is less than",
+ lt: "is at least",
+ lte: "is greater than",
+ is_set: "is not set",
+ is_not_set: "is set",
+};
+
+const COUNT_OPERATOR_LABELS: Record<string, string> = {
+ gte: "at least",
+ lte: "at most",
+ gt: "more than",
+ lt: "fewer than",
+ eq: "exactly",
+ exact: "exactly",
+};
+
+// Older cohort builders store aliases the backend resolves to a canonical value.
+// Desktop reads the raw filters blob, so it normalizes them itself. Mirror of
+// BEHAVIORAL_VALUE_ALIASES in posthog/models/property/property.py.
+const BEHAVIORAL_VALUE_ALIASES = new Map<string, string>([
+ ["performed_event_multiple_times", "performed_event_multiple"],
+]);
+
+function describeBehavioralCriterion(criterion: QueryRecord): string | null {
+ const event = conciseValue(criterion.key) ?? "an event";
+ const window =
+ typeof criterion.time_value === "number" && criterion.time_interval
+ ? ` in the last ${criterion.time_value} ${String(criterion.time_interval)}${criterion.time_value === 1 ? "" : "s"}`
+ : "";
+ const negated = criterion.negation === true;
+ const rawKind = String(criterion.value ?? "");
+ const kind = BEHAVIORAL_VALUE_ALIASES.get(rawKind) ?? rawKind;
+ if (kind === "performed_event")
+ return `${negated ? "Did not complete" : "Completed"} ${event}${window}`;
+ if (kind === "performed_event_multiple") {
+ const times = asCount(criterion.operator_value);
+ const operator = COUNT_OPERATOR_LABELS[String(criterion.operator)] ?? "";
+ const bound =
+ times !== null
+ ? ` ${operator ? `${operator} ` : ""}${count(times, "time")}`
+ : " multiple times";
+ return `Completed ${event}${bound}${window}`;
+ }
+ if (kind === "performed_event_first_time")
+ return `Completed ${event} for the first time${window}`;
+ if (kind === "performed_event_regularly")
+ return `Completed ${event} regularly${window}`;
+ if (kind === "performed_event_sequence") {
+ const then = conciseValue(criterion.seq_event);
+ const verb = negated ? "Did not complete" : "Completed";
+ return `${verb} ${event}${then ? ` then ${then}` : " in a sequence"}${window}`;
+ }
+ if (kind === "stopped_performing_event") return `Stopped doing ${event}`;
+ if (kind === "restarted_performing_event")
+ return `Returned to doing ${event}`;
+ if (!kind) return null;
+ return `${humanizeStatus(kind)}: ${event}${window}`;
+}
+
+function asCount(value: unknown): number | null {
+ const parsed = typeof value === "number" ? value : Number(value);
+ return Number.isFinite(parsed) ? parsed : null;
+}
+
+function describeCohortCriterion(criterion: QueryRecord): string | null {
+ const type = String(criterion.type ?? "");
+ if (type === "behavioral") return describeBehavioralCriterion(criterion);
+ const negated = criterion.negation === true;
+ if (type === "cohort")
+ return `Is ${negated ? "not " : ""}in cohort ${conciseValue(criterion.value) ?? "?"}`;
+ if (type === "static-cohort")
+ return `Is ${negated ? "not " : ""}in a static cohort`;
+ if (type === "person" || type === "event" || type === "group") {
+ const key = conciseValue(criterion.key);
+ if (!key) return null;
+ const rawOperator = String(criterion.operator ?? "");
+ const labels = negated
+ ? NEGATED_PROPERTY_OPERATOR_LABELS
+ : PROPERTY_OPERATOR_LABELS;
+ const operator =
+ labels[rawOperator] ??
+ (criterion.operator
+ ? `${negated ? "not " : ""}${humanizeStatus(rawOperator).toLowerCase()}`
+ : negated
+ ? "is not"
+ : "is");
+ const value = conciseValue(criterion.value);
+ const needsValue = !rawOperator.includes("is_set");
+ return `${key} ${operator}${needsValue && value ? ` ${value}` : ""}`;
+ }
+ return null;
+}
+
+/**
+ * A dynamic cohort's membership rules as prose, one field per match group.
+ * The filter tree is untrusted JSON, so anything unrecognized is skipped
+ * rather than rendered raw.
+ */
+export function cohortCriteriaSection(
+ filters: unknown,
+): EvidenceDetailSection[] {
+ const properties =
+ isRecord(filters) && isRecord(filters.properties)
+ ? filters.properties
+ : null;
+ const groups = (
+ Array.isArray(properties?.values) ? properties.values : []
+ ).filter(isRecord);
+ const outerAny = properties?.type === "OR";
+ const fields = groups.flatMap((group, index) => {
+ const criteria = (Array.isArray(group.values) ? group.values : [])
+ .filter(isRecord)
+ .map(describeCohortCriterion)
+ .filter((line): line is string => line !== null);
+ if (criteria.length === 0) return [];
+ const joiner = group.type === "OR" ? " or " : " and ";
+ const label =
+ groups.length > 1
+ ? `Group ${index + 1}${outerAny && index > 0 ? " (or)" : ""}`
+ : "Criteria";
+ return [[label, criteria.join(joiner)] as [string, string]];
+ });
+ return detailSection("Membership criteria", fields);
+}
+
export function shapeCohortPreview(cohort: Schemas.Cohort): EvidencePreview {
const detail =
typeof cohort.count === "number"
? count(cohort.count, "person", "people")
: cohort.description || undefined;
+ const type = cohort.is_static ? "Static" : "Dynamic";
+ const experiments = cohort.experiment_set ?? [];
return {
title: cohort.name || "Untitled cohort",
detail,
- facts: [cohort.is_static ? "Static" : "Dynamic"],
+ facts: [type],
+ stats: [
+ ...(typeof cohort.count === "number"
+ ? [{ label: "People", value: compactCount(cohort.count) }]
+ : []),
+ { label: "Type", value: type },
+ ...(cohort.last_calculation
+ ? [
+ {
+ label: "Last calculated",
+ value: formatDay(cohort.last_calculation),
+ },
+ ]
+ : []),
+ ],
+ sections: [
+ ...detailSection("Cohort", [
+ ["Description", cohort.description || null],
+ ["Type", type],
+ [
+ "People",
+ typeof cohort.count === "number"
+ ? count(cohort.count, "person", "people")
+ : null,
+ ],
+ [
+ "Last calculated",
+ cohort.last_calculation ? formatDay(cohort.last_calculation) : null,
+ ],
+ ["Calculation state", cohort.is_calculating ? "Calculating" : null],
+ [
+ "Calculation errors",
+ cohort.errors_calculating ? String(cohort.errors_calculating) : null,
+ ],
+ [
+ "Linked experiments",
+ experiments.length ? count(experiments.length, "experiment") : null,
+ ],
+ ["Created", cohort.created_at ? formatDay(cohort.created_at) : null],
+ ]),
+ ...cohortCriteriaSection(cohort.filters),
+ ],
};
}
export function shapeActionPreview(action: Schemas.Action): EvidencePreview {
+ const matchSteps = action.steps?.length ?? 0;
return {
title: action.name || "Untitled action",
detail: action.description || undefined,
- facts: action.steps?.length
- ? [count(action.steps.length, "match step")]
- : undefined,
+ facts: matchSteps ? [count(matchSteps, "match step")] : undefined,
+ sections: [
+ ...detailSection("Matching", [
+ ["Match groups", matchSteps ? count(matchSteps, "group") : null],
+ ["Calculation state", action.is_calculating ? "Calculating" : "Ready"],
+ [
+ "Last calculated",
+ action.last_calculated_at
+ ? formatDay(action.last_calculated_at)
+ : null,
+ ],
+ [
+ "Tags",
+ action.tags?.length ? action.tags.map(String).join(", ") : null,
+ ],
+ ["Created", action.created_at ? formatDay(action.created_at) : null],
+ ]),
+ ...detailSection(
+ "Match groups",
+ (action.steps ?? []).map((step, index) => [
+ `Group ${index + 1}`,
+ actionStepSummary(step),
+ ]),
+ ),
+ ],
};
}
@@ -408,6 +1124,24 @@ export function shapeTicketPreview(ticket: Schemas.Ticket): EvidencePreview {
? `“${snippet.length > 120 ? `${snippet.slice(0, 120)}…` : snippet}”`
: undefined,
facts,
+ sections: detailSection("Ticket", [
+ ["Status", status],
+ ["Priority", priority],
+ ["Channel", channel],
+ [
+ "Assignee",
+ typeof assignedUser?.name === "string" ? assignedUser.name : null,
+ ],
+ [
+ "Messages",
+ typeof ticket.message_count === "number"
+ ? count(ticket.message_count, "message")
+ : null,
+ ],
+ ["Created", ticket.created_at ? formatDay(ticket.created_at) : null],
+ ["Updated", ticket.updated_at ? formatDay(ticket.updated_at) : null],
+ ["SLA due", ticket.sla_due_at ? formatDay(ticket.sla_due_at) : null],
+ ]),
};
}
@@ -435,6 +1169,22 @@ export function shapePersonPreview(
title,
detail: parts.join(" · ") || undefined,
facts,
+ sections: detailSection("Person", [
+ [
+ "Distinct IDs",
+ person.distinct_ids.length
+ ? person.distinct_ids.slice(0, 3).join(", ")
+ : null,
+ ],
+ ["First seen", person.created_at ? formatDay(person.created_at) : null],
+ [
+ "Last seen",
+ person.last_seen_at ? formatDay(person.last_seen_at) : null,
+ ],
+ ["Email", email],
+ ["Country", stringValue(properties.$geoip_country_name)],
+ ["Browser", stringValue(properties.$browser)],
+ ]),
resolvedId: person.uuid,
};
}
@@ -447,18 +1197,80 @@ export function shapeEventDefinitionPreview(
detail: definition.last_seen_at
? `Last seen ${formatDay(definition.last_seen_at)}`
: undefined,
+ stats: [
+ ...(definition.created_at
+ ? [{ label: "First seen", value: formatDay(definition.created_at) }]
+ : []),
+ ...(definition.last_seen_at
+ ? [{ label: "Last seen", value: formatDay(definition.last_seen_at) }]
+ : []),
+ ],
+ sections: detailSection("Event", [
+ [
+ "First seen",
+ definition.created_at ? formatDay(definition.created_at) : null,
+ ],
+ [
+ "Last seen",
+ definition.last_seen_at ? formatDay(definition.last_seen_at) : null,
+ ],
+ ["Action", definition.is_action ? "Yes" : "No"],
+ [
+ "Calculation state",
+ definition.is_calculating ? "Calculating" : "Ready",
+ ],
+ [
+ "Tags",
+ definition.tags?.length ? definition.tags.map(String).join(", ") : null,
+ ],
+ ]),
resolvedId: definition.id,
};
}
export function shapeSurveyPreview(survey: Schemas.Survey): EvidencePreview {
- let detail: string;
+ let detail: string | undefined;
+ let status: EvidencePreview["status"];
if (survey.end_date) {
+ status = { label: "Ended", tone: "neutral" };
detail = `Ended ${formatDay(survey.end_date)}`;
} else if (survey.start_date) {
- detail = `Running since ${formatDay(survey.start_date)}`;
+ status = { label: "Running", tone: "positive" };
+ detail = `Since ${formatDay(survey.start_date)}`;
} else {
- detail = "Draft";
+ status = { label: "Draft", tone: "neutral" };
}
- return { title: survey.name, detail };
+ const questions = Array.isArray(survey.questions)
+ ? survey.questions.length
+ : 0;
+ return {
+ title: survey.name,
+ detail,
+ status,
+ sections: [
+ ...detailSection("Survey", [
+ ["State", survey.archived ? "Archived" : null],
+ [
+ "Type",
+ typeof survey.type === "string" ? humanizeStatus(survey.type) : null,
+ ],
+ ["Questions", questions ? count(questions, "question") : null],
+ [
+ "Response limit",
+ survey.responses_limit ? String(survey.responses_limit) : null,
+ ],
+ ["Starts", survey.start_date ? formatDay(survey.start_date) : null],
+ ["Ends", survey.end_date ? formatDay(survey.end_date) : null],
+ ]),
+ ...detailSection(
+ "Questions",
+ (Array.isArray(survey.questions) ? survey.questions : [])
+ .slice(0, 6)
+ .map((question, index) => [
+ `Question ${index + 1}`,
+ surveyQuestionSummary(question),
+ ]),
+ ),
+ ],
+ };
}
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 373f19f9c293..ed925a66df38 100644
--- a/products/desktop/packages/api-client/src/posthog-client.test.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts
@@ -10,6 +10,168 @@ import {
} from "./posthog-client";
describe("PostHogAPIClient", () => {
+ describe("getInsightDefinition", () => {
+ it("loads the saved insight with a blocking refresh and returns its result", async () => {
+ const fetch = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ id: 1,
+ short_id: "sdyR2Pn8",
+ name: "Unique users per variant",
+ derived_name: null,
+ description: "Feature flag calls",
+ query: { kind: "InsightVizNode", source: { kind: "TrendsQuery" } },
+ result: [
+ {
+ label: "$feature_flag_called - true",
+ data: [],
+ days: [],
+ aggregated_value: 2,
+ },
+ ],
+ columns: null,
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+ const client = new PostHogAPIClient(
+ "https://app.posthog.test",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch },
+ );
+
+ await expect(client.getInsightDefinition("sdyR2Pn8")).resolves.toEqual({
+ name: "Unique users per variant",
+ description: "Feature flag calls",
+ query: { kind: "InsightVizNode", source: { kind: "TrendsQuery" } },
+ response: {
+ results: [
+ {
+ label: "$feature_flag_called - true",
+ data: [],
+ days: [],
+ aggregated_value: 2,
+ },
+ ],
+ columns: [],
+ },
+ });
+ const url = fetch.mock.calls[0][0] as URL;
+ expect(url.pathname).toBe("/api/projects/42/insights/sdyR2Pn8/");
+ expect(url.searchParams.get("refresh")).toBe("blocking");
+ });
+
+ it("returns null when the saved insight does not exist", async () => {
+ const fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ detail: "Not found." }), {
+ status: 404,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ const client = new PostHogAPIClient(
+ "https://app.posthog.test",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch },
+ );
+
+ await expect(client.getInsightDefinition("missing")).resolves.toBeNull();
+ });
+ });
+
+ describe("getEvidencePreview", () => {
+ it("retrieves a person by UUID instead of taking the first search result", async () => {
+ const fetch = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ id: 1,
+ uuid: "0192aaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ name: "Ann",
+ distinct_ids: ["ann-1"],
+ properties: { email: "[email protected]" },
+ created_at: "2024-01-03T10:00:00Z",
+ last_seen_at: "2024-01-04T10:00:00Z",
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+ const client = new PostHogAPIClient(
+ "https://app.posthog.test",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch },
+ );
+
+ await expect(
+ client.getEvidencePreview(
+ "person",
+ "0192aaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ ),
+ ).resolves.toMatchObject({
+ title: "Ann",
+ resolvedId: "0192aaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ });
+ const url = fetch.mock.calls[0][0] as URL;
+ expect(url.pathname).toBe(
+ "/api/projects/42/persons/0192aaaa-bbbb-cccc-dddd-eeeeeeeeeeee/",
+ );
+ });
+
+ it("resolves a UUID-shaped distinct id when retrieve-by-uuid 404s", async () => {
+ const distinctId = "0192aaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ detail: "Not found." }), {
+ status: 404,
+ headers: { "Content-Type": "application/json" },
+ }),
+ )
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ results: [
+ {
+ id: 1,
+ uuid: "0192ffff-1111-2222-3333-444444444444",
+ name: "Ann",
+ distinct_ids: [distinctId],
+ properties: { email: "[email protected]" },
+ created_at: "2024-01-03T10:00:00Z",
+ last_seen_at: "2024-01-04T10:00:00Z",
+ },
+ ],
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+ const client = new PostHogAPIClient(
+ "https://app.posthog.test",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch },
+ );
+
+ await expect(
+ client.getEvidencePreview("person", distinctId),
+ ).resolves.toMatchObject({
+ title: "Ann",
+ resolvedId: "0192ffff-1111-2222-3333-444444444444",
+ });
+ expect((fetch.mock.calls[0][0] as URL).pathname).toBe(
+ `/api/projects/42/persons/${distinctId}/`,
+ );
+ const listUrl = fetch.mock.calls[1][0] as URL;
+ expect(listUrl.pathname).toBe("/api/projects/42/persons/");
+ expect(listUrl.searchParams.get("search")).toBe(distinctId);
+ });
+ });
+
it("fetches later task pages before reporting complete results", async () => {
const client = new PostHogAPIClient(
"https://app.posthog.test",
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 393df2aa9440..ade886423c4f 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -72,14 +72,18 @@ import type {
} from "@posthog/shared/domain-types";
import { buildPosthogProjectHeaderRecord } from "@posthog/shared/posthog-property-headers";
import {
+ activitySection,
compactCount,
+ dailySparkLabels,
dailySparkPoints,
decorateFlagPreview,
decorateSurveyPreview,
type EvidencePreview,
exposureFact,
+ formatDay,
gridRows,
hogqlEscape,
+ pivotDailyGroups,
shapeActionPreview,
shapeCohortPreview,
shapeDashboardPreview,
@@ -6041,19 +6045,33 @@ export class PostHogAPIClient {
name: string | null;
description: string | null;
query: unknown;
+ response: Record<string, unknown> | null;
} | null> {
const projectId = (await this.getTeamId()).toString();
- const page = await this.api.get("/api/projects/{project_id}/insights/", {
- path: { project_id: projectId },
- query: { short_id: shortId },
- });
- const insight = page.results[0];
- if (!insight) return null;
- return {
- name: insight.name || insight.derived_name || null,
- description: insight.description || null,
- query: insight.query ?? null,
- };
+ try {
+ const insight = await this.api.get(
+ "/api/projects/{project_id}/insights/{id}/",
+ {
+ path: { project_id: projectId, id: shortId },
+ query: { refresh: "blocking" },
+ },
+ );
+ return {
+ name: insight.name || insight.derived_name || null,
+ description: insight.description || null,
+ query: insight.query ?? null,
+ response:
+ insight.result === null || insight.result === undefined
+ ? null
+ : {
+ results: insight.result,
+ columns: insight.columns ?? [],
+ },
+ };
+ } catch (error) {
+ if (requestErrorStatus(error) === 404) return null;
+ throw error;
+ }
}
/**
@@ -6122,14 +6140,47 @@ export class PostHogAPIClient {
const until = experiment.end_date
? ` AND timestamp <= parseDateTimeBestEffort('${hogqlEscape(experiment.end_date)}')`
: "";
- const exposures = await this.runQuery({
- kind: "HogQLQuery",
- query: `SELECT toString(properties.$feature_flag_response) AS variant, uniq(person_id) FROM events WHERE event = '$feature_flag_called' AND properties.$feature_flag = '${hogqlEscape(experiment.feature_flag_key)}' AND timestamp >= parseDateTimeBestEffort('${hogqlEscape(experiment.start_date)}')${until} GROUP BY variant ORDER BY variant`,
- }).catch(() => ({}));
+ 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));
- return fact
- ? { ...preview, facts: [...(preview.facts ?? []), fact] }
- : preview;
+ // "false" rows are flag evaluations outside the experiment, not a variant.
+ const pivot = pivotDailyGroups(
+ gridRows(dailyExposures).filter((row) => String(row[1]) !== "false"),
+ );
+ 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),
+ }));
+ 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,
+ };
}
case "error": {
// The issue's identity plus its 30-day activity: total events, users
@@ -6159,12 +6210,29 @@ export class PostHogAPIClient {
`${compactCount(users)} users · ${compactCount(events)} events (30d)`,
);
}
- const points = dailySparkPoints(gridRows(daily));
+ const stats = [
+ ...(preview.stats ?? []),
+ ...(users > 0
+ ? [
+ { label: "Users in 30 days", value: compactCount(users) },
+ { label: "Events in 30 days", value: compactCount(events) },
+ ]
+ : []),
+ ];
+ const dailyRows = gridRows(daily);
+ const points = dailySparkPoints(dailyRows);
return {
...preview,
facts,
+ stats,
spark:
- points.length > 1 ? { points, render: "bar" as const } : undefined,
+ points.length > 1
+ ? {
+ points,
+ labels: dailySparkLabels(dailyRows),
+ render: "bar" as const,
+ }
+ : undefined,
};
}
case "event": {
@@ -6182,14 +6250,27 @@ export class PostHogAPIClient {
query: `SELECT toDate(timestamp) AS day, count() FROM events WHERE event = '${hogqlEscape(id)}' AND timestamp >= now() - INTERVAL 14 DAY GROUP BY day ORDER BY day`,
}).catch(() => ({}));
const preview = shapeEventDefinitionPreview(definition);
- const points = dailySparkPoints(gridRows(volume));
+ const volumeRows = gridRows(volume);
+ const points = dailySparkPoints(volumeRows);
const total = points.reduce((sum, value) => sum + value, 0);
return {
...preview,
facts:
total > 0 ? [`${compactCount(total)} events (14d)`] : undefined,
+ stats: [
+ ...(total > 0
+ ? [{ label: "Events in 14 days", value: compactCount(total) }]
+ : []),
+ ...(preview.stats ?? []),
+ ],
spark:
- points.length > 1 ? { points, render: "line" as const } : undefined,
+ points.length > 1
+ ? {
+ points,
+ labels: dailySparkLabels(volumeRows),
+ render: "line" as const,
+ }
+ : undefined,
};
}
case "ticket": {
@@ -6200,11 +6281,32 @@ export class PostHogAPIClient {
return shapeTicketPreview(ticket);
}
case "person": {
+ if (/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(id)) {
+ // A UUID-shaped id can be a person uuid or a UUID-shaped distinct id
+ // (posthog-js writes anonymous distinct ids as UUIDs). Retrieve-by-id
+ // matches only the person uuid, so a 404 (no such uuid) or 400 (the id
+ // isn't a valid person uuid) means fall through and resolve it as a
+ // distinct id below rather than giving up.
+ const person = await this.api
+ .get("/api/projects/{project_id}/persons/{id}/", {
+ path: { project_id: projectId, id },
+ query: {},
+ })
+ .catch((error) => {
+ const status = requestErrorStatus(error);
+ if (status === 404 || status === 400) return null;
+ throw error;
+ });
+ if (person) return shapePersonPreview(person);
+ }
const page = await this.api.get("/api/projects/{project_id}/persons/", {
path: { project_id: projectId },
query: { search: id },
});
- const person = page.results?.[0];
+ const person = page.results?.find(
+ (candidate) =>
+ candidate.uuid === id || candidate.distinct_ids?.includes(id),
+ );
return person ? shapePersonPreview(person) : null;
}
case "replay": {
@@ -6257,7 +6359,7 @@ export class PostHogAPIClient {
}
case "action": {
if (numericId === null) return null;
- const [action, volume] = await Promise.all([
+ const [action, volume, totals] = await Promise.all([
this.api.get("/api/projects/{project_id}/actions/{id}/", {
path: { project_id: projectId, id: numericId },
query: {},
@@ -6266,17 +6368,61 @@ export class PostHogAPIClient {
kind: "HogQLQuery",
query: `SELECT toDate(timestamp) AS day, count() FROM events WHERE matchesAction(${numericId}) AND timestamp >= now() - INTERVAL 14 DAY GROUP BY day ORDER BY day`,
}).catch(() => ({})),
+ this.runQuery({
+ kind: "HogQLQuery",
+ query: `SELECT count(), uniq(person_id), max(timestamp) FROM events WHERE matchesAction(${numericId}) AND timestamp >= now() - INTERVAL 30 DAY`,
+ }).catch(() => ({})),
]);
const preview = shapeActionPreview(action);
- const points = dailySparkPoints(gridRows(volume));
+ const volumeRows = gridRows(volume);
+ const points = dailySparkPoints(volumeRows);
const total = points.reduce((sum, value) => sum + value, 0);
const facts = [...(preview.facts ?? [])];
if (total > 0) facts.unshift(`${compactCount(total)} matches (14d)`);
+ const totalsRow = gridRows(totals)[0];
+ const matches30d = totalsRow ? Number(totalsRow[0]) : 0;
+ const users30d = totalsRow ? Number(totalsRow[1]) : 0;
+ const lastSeen =
+ totalsRow && typeof totalsRow[2] === "string" && matches30d > 0
+ ? totalsRow[2]
+ : null;
+ if (users30d > 0) facts.push(`${compactCount(users30d)} users (30d)`);
return {
...preview,
facts,
+ stats: [
+ ...(total > 0
+ ? [{ label: "Matches in 14 days", value: compactCount(total) }]
+ : []),
+ ...(users30d > 0
+ ? [{ label: "Users in 30 days", value: compactCount(users30d) }]
+ : []),
+ ...(lastSeen
+ ? [{ label: "Last seen", value: formatDay(lastSeen) }]
+ : []),
+ ],
spark:
- points.length > 1 ? { points, render: "line" as const } : undefined,
+ points.length > 1
+ ? {
+ points,
+ labels: dailySparkLabels(volumeRows),
+ render: "line" as const,
+ }
+ : undefined,
+ sections: [
+ ...activitySection([
+ [
+ "Matches in 30 days",
+ matches30d > 0 ? compactCount(matches30d) : null,
+ ],
+ [
+ "Unique users in 30 days",
+ users30d > 0 ? compactCount(users30d) : null,
+ ],
+ ["Last seen", lastSeen ? formatDay(lastSeen) : null],
+ ]),
+ ...(preview.sections ?? []),
+ ],
};
}
case "eval": {
diff --git a/products/desktop/packages/core/src/inbox/reportCharts.test.ts b/products/desktop/packages/core/src/inbox/reportCharts.test.ts
index 837b548bc850..5bef712ce217 100644
--- a/products/desktop/packages/core/src/inbox/reportCharts.test.ts
+++ b/products/desktop/packages/core/src/inbox/reportCharts.test.ts
@@ -28,6 +28,15 @@ const trendsNode = (display?: string) => ({
},
});
+const stickinessNode = (display?: string) => ({
+ kind: "InsightVizNode",
+ source: {
+ kind: "StickinessQuery",
+ series: [{ event: "$pageview" }],
+ ...(display ? { stickinessFilter: { display } } : {}),
+ },
+});
+
const runPlan = (query: unknown) => {
const plan = planReportChart(query);
if (plan.kind !== "run")
@@ -44,12 +53,36 @@ describe("reportCharts", () => {
[{ kind: "SavedInsightNode", shortId: 42 }, "invalid"],
[{ kind: "SavedInsightNode", shortId: "abc123" }, "saved-insight"],
[{ kind: "InsightVizNode" }, "invalid"],
- [{ kind: "InsightVizNode", source: { kind: "FunnelsQuery" } }, "open-only"],
+ [{ kind: "InsightVizNode", source: { kind: "FunnelsQuery" } }, "run"],
+ [
+ {
+ kind: "InsightVizNode",
+ source: {
+ kind: "FunnelsQuery",
+ funnelsFilter: { funnelVizType: "time_to_convert" },
+ },
+ },
+ "open-only",
+ ],
+ [
+ {
+ kind: "InsightVizNode",
+ source: {
+ kind: "FunnelsQuery",
+ funnelsFilter: { funnelVizType: "steps" },
+ compareFilter: { compare: true },
+ },
+ },
+ "open-only",
+ ],
+ [{ kind: "InsightVizNode", source: { kind: "LifecycleQuery" } }, "run"],
[
{ kind: "InsightVizNode", source: { kind: "RetentionQuery" } },
"open-only",
],
[trendsNode(), "run"],
+ [trendsNode("WorldMap"), "run"],
+ [trendsNode("BoxPlot"), "open-only"],
[
{ kind: "DataVisualizationNode", source: { kind: "EventsQuery" } },
"open-only",
@@ -65,17 +98,159 @@ describe("reportCharts", () => {
it.each([
[trendsNode(), "line"],
+ [stickinessNode(), "bar"],
[trendsNode("ActionsBar"), "bar"],
+ [trendsNode("ActionsStackedBar"), "bar"],
+ [trendsNode("ActionsLineGraphCumulative"), "line"],
+ [trendsNode("ActionsTable"), "table"],
+ [trendsNode("WorldMap"), "table"],
[trendsNode("BoldNumber"), "number"],
+ [trendsNode("Metric"), "number"],
[hogqlNode(), "auto"],
[hogqlNode({ display: "ActionsLineGraph" }), "line"],
[hogqlNode({ display: "ActionsBar" }), "bar"],
[hogqlNode({ display: "BoldNumber" }), "number"],
- [hogqlNode({ display: "ActionsTable" }), "auto"],
+ [hogqlNode({ display: "ActionsTable" }), "table"],
])("planReportChart(%j) picks render %s", (query, render) => {
expect(runPlan(query).render).toBe(render);
});
+ it("shapes a lifecycle response into bars, keeping negative statuses", () => {
+ const data = shapeReportChartData(
+ {
+ results: [
+ {
+ label: "new",
+ days: ["2026-08-01", "2026-08-02"],
+ data: [5, 8],
+ },
+ {
+ label: "dormant",
+ days: ["2026-08-01", "2026-08-02"],
+ data: [-3, -6],
+ },
+ ],
+ },
+ runPlan({
+ kind: "InsightVizNode",
+ source: { kind: "LifecycleQuery" },
+ }),
+ );
+ expect(data).toMatchObject({
+ type: "series",
+ render: "bar",
+ labels: ["2026-08-01", "2026-08-02"],
+ series: [
+ { label: "new", data: [5, 8] },
+ { label: "dormant", data: [-3, -6] },
+ ],
+ });
+ });
+
+ it("drops lifecycle statuses the saved insight has toggled off", () => {
+ const data = shapeReportChartData(
+ {
+ results: [
+ {
+ label: "new",
+ status: "new",
+ days: ["2026-08-01", "2026-08-02"],
+ data: [5, 8],
+ },
+ {
+ label: "dormant",
+ status: "dormant",
+ days: ["2026-08-01", "2026-08-02"],
+ data: [-3, -6],
+ },
+ ],
+ },
+ runPlan({
+ kind: "InsightVizNode",
+ source: {
+ kind: "LifecycleQuery",
+ lifecycleFilter: { toggledLifecycles: ["new"] },
+ },
+ }),
+ );
+ expect(data).toMatchObject({
+ type: "series",
+ render: "bar",
+ series: [{ label: "new", data: [5, 8] }],
+ });
+ });
+
+ it("labels compared aggregate rows with their period", () => {
+ const data = shapeReportChartData(
+ {
+ results: [
+ {
+ label: "Pageviews",
+ aggregated_value: 120,
+ compare_label: "current",
+ },
+ {
+ label: "Pageviews",
+ aggregated_value: 80,
+ compare_label: "previous",
+ },
+ ],
+ },
+ runPlan(trendsNode("ActionsTable")),
+ );
+ expect(data).toMatchObject({
+ type: "table",
+ rows: [
+ ["Pageviews (current)", 120],
+ ["Pageviews (previous)", 80],
+ ],
+ });
+ });
+
+ it("shapes a steps funnel into one bar per step", () => {
+ const data = shapeReportChartData(
+ {
+ results: [
+ { name: "$pageview", order: 0, count: 120 },
+ { name: "sign up", custom_name: "Signed up", order: 1, count: 45 },
+ ],
+ },
+ runPlan({ kind: "InsightVizNode", source: { kind: "FunnelsQuery" } }),
+ );
+ expect(data).toMatchObject({
+ type: "series",
+ render: "bar",
+ labels: ["$pageview", "Signed up"],
+ series: [{ label: "Users", data: [120, 45] }],
+ });
+ });
+
+ it("shapes a breakdown funnel into one series per breakdown value", () => {
+ const data = shapeReportChartData(
+ {
+ results: [
+ [
+ { name: "$pageview", count: 80, breakdown_value: ["Chrome"] },
+ { name: "sign up", count: 30, breakdown_value: ["Chrome"] },
+ ],
+ [
+ { name: "$pageview", count: 40, breakdown_value: ["Safari"] },
+ { name: "sign up", count: 10, breakdown_value: ["Safari"] },
+ ],
+ ],
+ },
+ runPlan({ kind: "InsightVizNode", source: { kind: "FunnelsQuery" } }),
+ );
+ expect(data).toMatchObject({
+ type: "series",
+ labels: ["$pageview", "sign up"],
+ series: [
+ { label: "Chrome", data: [80, 30] },
+ { label: "Safari", data: [40, 10] },
+ ],
+ });
+ });
+
it("shapes a trends response into a time series", () => {
const data = shapeReportChartData(
{
@@ -107,6 +282,79 @@ describe("reportCharts", () => {
expect(data).toEqual({ type: "number", value: 42 });
});
+ it.each([
+ [
+ "table",
+ "ActionsTable",
+ {
+ type: "table",
+ columns: ["Breakdown", "Total"],
+ rows: [
+ ["true", 2],
+ ["No value", 4],
+ ],
+ },
+ ],
+ [
+ "categorical bar",
+ "ActionsBarValue",
+ {
+ type: "series",
+ render: "bar",
+ labels: ["true", "No value"],
+ series: [{ label: "Total", data: [2, 4] }],
+ },
+ ],
+ ])(
+ "keeps aggregate-only Trends results visible as a %s",
+ (_name, display, expected) => {
+ const data = shapeReportChartData(
+ {
+ results: [
+ {
+ label: "$feature_flag_called - true",
+ breakdown_value: "true",
+ aggregated_value: 2,
+ data: [],
+ days: ["2026-08-01"],
+ },
+ {
+ label: "$feature_flag_called - None",
+ breakdown_value: null,
+ aggregated_value: 4,
+ data: [],
+ days: ["2026-08-01"],
+ },
+ ],
+ },
+ runPlan(trendsNode(display)),
+ );
+ expect(data).toMatchObject(expected);
+ },
+ );
+
+ it("uses stickiness bucket labels instead of numeric day indexes", () => {
+ const data = shapeReportChartData(
+ {
+ results: [
+ {
+ label: "$pageview",
+ data: [10, 5],
+ labels: ["1 day", "2 days"],
+ days: [1, 2],
+ },
+ ],
+ },
+ runPlan(stickinessNode()),
+ );
+ expect(data).toMatchObject({
+ type: "series",
+ render: "bar",
+ labels: ["1 day", "2 days"],
+ isTimeSeries: false,
+ });
+ });
+
it("normalizes midnight-stamped day buckets to plain dates", () => {
const data = shapeReportChartData(
{
diff --git a/products/desktop/packages/core/src/inbox/reportCharts.ts b/products/desktop/packages/core/src/inbox/reportCharts.ts
index 0dadc19b501e..02e7b7eb677d 100644
--- a/products/desktop/packages/core/src/inbox/reportCharts.ts
+++ b/products/desktop/packages/core/src/inbox/reportCharts.ts
@@ -2,7 +2,7 @@ import type { SignalReportChartSize } from "@posthog/shared/types";
type QueryNode = Record<string, unknown>;
-export type ReportChartRender = "line" | "bar" | "number" | "auto";
+export type ReportChartRender = "line" | "bar" | "number" | "table" | "auto";
/**
* What to do with a chart's stored query. The backend only guarantees the
@@ -22,14 +22,46 @@ function isRecord(value: unknown): value is QueryNode {
}
function renderFromDisplay(display: unknown): ReportChartRender {
- if (display === "BoldNumber") return "number";
- if (display === "ActionsBar" || display === "ActionsBarValue") return "bar";
- if (display === "ActionsLineGraph" || display === "ActionsAreaGraph") {
+ if (display === "BoldNumber" || display === "Metric") return "number";
+ if (
+ display === "ActionsBar" ||
+ display === "ActionsUnstackedBar" ||
+ display === "ActionsStackedBar" ||
+ display === "ActionsBarValue" ||
+ display === "ActionsPie"
+ ) {
+ return "bar";
+ }
+ if (
+ display === "ActionsLineGraph" ||
+ display === "ActionsAreaGraph" ||
+ display === "ActionsLineGraphCumulative"
+ ) {
return "line";
}
+ if (display === "ActionsTable" || display === "WorldMap") return "table";
return "auto";
}
+function trendsRenderFromDisplay(
+ display: unknown,
+ sourceKind: "TrendsQuery" | "StickinessQuery",
+): ReportChartRender | null {
+ if (display === undefined || display === "Auto") {
+ return sourceKind === "StickinessQuery" ? "bar" : "line";
+ }
+ if (
+ display === "CalendarHeatmap" ||
+ display === "TwoDimensionalHeatmap" ||
+ display === "BoxPlot" ||
+ display === "SlopeGraph" ||
+ display === "ScatterPlot"
+ ) {
+ return null;
+ }
+ return renderFromDisplay(display);
+}
+
export function planReportChart(query: unknown): ReportChartPlan {
if (!isRecord(query) || typeof query.kind !== "string") {
return { kind: "invalid" };
@@ -42,6 +74,31 @@ export function planReportChart(query: unknown): ReportChartPlan {
const source = isRecord(query.source) ? query.source : null;
if (query.kind === "InsightVizNode") {
if (!source) return { kind: "invalid" };
+ // Lifecycle results share the trends series shape, and PostHog draws them
+ // as bars; run them rather than degrade to a link-out card.
+ if (source.kind === "LifecycleQuery") {
+ return { kind: "run", source, render: "bar" };
+ }
+ // Only the step visualization maps onto a categorical bar chart; the
+ // trends and time-to-convert visualizations have different result shapes.
+ if (source.kind === "FunnelsQuery") {
+ const filter = isRecord(source.funnelsFilter)
+ ? source.funnelsFilter
+ : null;
+ const vizType = filter?.funnelVizType;
+ if (vizType !== undefined && vizType !== "steps") {
+ return { kind: "open-only" };
+ }
+ // Compare merges current and previous periods into one response the
+ // categorical bar chart cannot disambiguate, so degrade to a link-out card.
+ const compareFilter = isRecord(source.compareFilter)
+ ? source.compareFilter
+ : null;
+ if (compareFilter?.compare === true) {
+ return { kind: "open-only" };
+ }
+ return { kind: "run", source, render: "bar" };
+ }
if (source.kind !== "TrendsQuery" && source.kind !== "StickinessQuery") {
return { kind: "open-only" };
}
@@ -50,12 +107,8 @@ export function planReportChart(query: unknown): ReportChartPlan {
? source.trendsFilter
: source.stickinessFilter;
const display = isRecord(filter) ? filter.display : undefined;
- const render = renderFromDisplay(display);
- return {
- kind: "run",
- source,
- render: render === "auto" ? "line" : render,
- };
+ const render = trendsRenderFromDisplay(display, source.kind);
+ return render ? { kind: "run", source, render } : { kind: "open-only" };
}
if (query.kind === "DataVisualizationNode") {
if (!source || source.kind !== "HogQLQuery") {
@@ -210,49 +263,143 @@ function normalizeDayLabels(labels: string[]): string[] {
return matches.map((match) => (match as RegExpExecArray)[1]);
}
+function trendsAggregateValue(result: QueryNode): number | null {
+ const aggregated = asFiniteNumber(result.aggregated_value);
+ if (aggregated !== null) return aggregated;
+ const data = Array.isArray(result.data) ? result.data : [];
+ if (data.length === 0) return null;
+ return data.reduce<number>(
+ (sum, value) => sum + (asFiniteNumber(value) ?? 0),
+ 0,
+ );
+}
+
+function trendsAggregateLabel(result: QueryNode, index: number): string {
+ // A compared insight returns the current and previous periods as two results
+ // with identical labels; the period lives only in compare_label.
+ const period =
+ typeof result.compare_label === "string" && result.compare_label
+ ? ` (${result.compare_label})`
+ : "";
+ if (Object.hasOwn(result, "breakdown_value")) {
+ const value = result.breakdown_value;
+ if (value === null || value === undefined || value === "")
+ return `No value${period}`;
+ if (Array.isArray(value)) return value.map(String).join(" · ") + period;
+ return `${String(value)}${period}`;
+ }
+ const label =
+ typeof result.label === "string" && result.label
+ ? result.label
+ : `Series ${index + 1}`;
+ return `${label}${period}`;
+}
+
+function shapeTrendsAggregates(
+ seriesResults: QueryNode[],
+ render: ReportChartRender,
+): ReportChartData {
+ const entries = seriesResults.flatMap((result, index) => {
+ const value = trendsAggregateValue(result);
+ return value === null
+ ? []
+ : [{ label: trendsAggregateLabel(result, index), value }];
+ });
+ if (entries.length === 0) return { type: "empty" };
+ if (render === "number") {
+ return {
+ type: "number",
+ value: entries.reduce((sum, entry) => sum + entry.value, 0),
+ };
+ }
+ if (render === "bar" && entries.length <= MAX_BAR_CATEGORIES) {
+ return {
+ type: "series",
+ render: "bar",
+ labels: entries.map((entry) => entry.label),
+ series: [
+ {
+ key: "aggregate-values",
+ label: "Total",
+ data: entries.map((entry) => entry.value),
+ },
+ ],
+ isTimeSeries: false,
+ interval: "day",
+ };
+ }
+ const hasBreakdown = seriesResults.some((result) =>
+ Object.hasOwn(result, "breakdown_value"),
+ );
+ return asTable(
+ entries.map((entry) => [entry.label, entry.value]),
+ [hasBreakdown ? "Breakdown" : "Series", "Total"],
+ );
+}
+
function shapeTrendsResponse(
response: QueryNode,
- render: ReportChartRender,
+ plan: Extract<ReportChartPlan, { kind: "run" }>,
): ReportChartData {
const results = Array.isArray(response.results) ? response.results : [];
- const seriesResults = results.filter(isRecord);
+ let seriesResults = results.filter(isRecord);
+ // The backend returns all four lifecycle statuses regardless of the saved
+ // insight's display filter; the web renderer drops the untoggled ones
+ // client-side, so this chart has to as well.
+ if (plan.source.kind === "LifecycleQuery") {
+ const lifecycleFilter = isRecord(plan.source.lifecycleFilter)
+ ? plan.source.lifecycleFilter
+ : null;
+ const toggled = Array.isArray(lifecycleFilter?.toggledLifecycles)
+ ? lifecycleFilter.toggledLifecycles.filter(
+ (status): status is string => typeof status === "string",
+ )
+ : null;
+ if (toggled) {
+ seriesResults = seriesResults.filter((result) =>
+ toggled.includes(String(result.status)),
+ );
+ }
+ }
if (seriesResults.length === 0) return { type: "empty" };
- if (render === "number") {
- const total = seriesResults.reduce((sum, result) => {
- const aggregated = asFiniteNumber(result.aggregated_value);
- if (aggregated !== null) return sum + aggregated;
- const data = Array.isArray(result.data) ? result.data : [];
- return (
- sum + data.reduce<number>((s, v) => s + (asFiniteNumber(v) ?? 0), 0)
- );
- }, 0);
- return { type: "number", value: total };
+ if (plan.render === "number" || plan.render === "table") {
+ return shapeTrendsAggregates(seriesResults, plan.render);
}
- const first = seriesResults[0];
+ const resultsWithData = seriesResults.filter(
+ (result) => Array.isArray(result.data) && result.data.length > 0,
+ );
+ if (resultsWithData.length === 0) {
+ return shapeTrendsAggregates(seriesResults, plan.render);
+ }
+
+ const first = resultsWithData[0];
+ const useStickinessLabels =
+ plan.source.kind === "StickinessQuery" && Array.isArray(first.labels);
const labels = (
- Array.isArray(first.days) ? first.days : (first.labels ?? [])
+ useStickinessLabels
+ ? first.labels
+ : Array.isArray(first.days)
+ ? first.days
+ : (first.labels ?? [])
) as unknown[];
const stringLabels = normalizeDayLabels(labels.map(String));
- if (stringLabels.length === 0) return { type: "empty" };
+ if (stringLabels.length === 0) {
+ return shapeTrendsAggregates(seriesResults, plan.render);
+ }
- const series = seriesResults.slice(0, MAX_SERIES).map((result, index) => {
- const data = (Array.isArray(result.data) ? result.data : []).map(
- (v) => asFiniteNumber(v) ?? 0,
- );
- return {
- key: `series-${index}`,
- label:
- typeof result.label === "string" && result.label
- ? result.label
- : `Series ${index + 1}`,
- data,
- };
- });
+ const series = resultsWithData.slice(0, MAX_SERIES).map((result, index) => ({
+ key: `series-${index}`,
+ label:
+ typeof result.label === "string" && result.label
+ ? result.label
+ : `Series ${index + 1}`,
+ data: (result.data as unknown[]).map((value) => asFiniteNumber(value) ?? 0),
+ }));
return {
type: "series",
- render: render === "bar" ? "bar" : "line",
+ render: plan.render === "bar" ? "bar" : "line",
labels: stringLabels,
series,
isTimeSeries: stringLabels.every(isDateLike),
@@ -387,6 +534,52 @@ function shapeHogQLResponse(
return asTable(rows, columns);
}
+function funnelStepName(step: QueryNode, index: number): string {
+ if (typeof step.custom_name === "string" && step.custom_name)
+ return step.custom_name;
+ if (typeof step.name === "string" && step.name) return step.name;
+ return `Step ${index + 1}`;
+}
+
+/**
+ * A steps funnel becomes a categorical bar chart: one bar per step, one
+ * series per breakdown. Results arrive either as a flat step list or, with a
+ * breakdown, as one step list per breakdown value.
+ */
+function shapeFunnelsResponse(response: QueryNode): ReportChartData {
+ const results = Array.isArray(response.results) ? response.results : [];
+ const branches: QueryNode[][] = results.every(Array.isArray)
+ ? (results as unknown[][]).map((branch) => branch.filter(isRecord))
+ : [results.filter(isRecord)];
+ const steps = branches[0] ?? [];
+ if (steps.length === 0) return { type: "empty" };
+
+ const labels = steps.map((step, index) => funnelStepName(step, index));
+ const series = branches.slice(0, MAX_SERIES).map((branch, index) => {
+ const breakdown = branch[0]?.breakdown_value;
+ const label = Array.isArray(breakdown)
+ ? breakdown.map(String).join(" · ")
+ : breakdown !== undefined && breakdown !== null && breakdown !== ""
+ ? String(breakdown)
+ : branches.length > 1
+ ? `Series ${index + 1}`
+ : "Users";
+ return {
+ key: `funnel-${index}`,
+ label,
+ data: labels.map((_, step) => asFiniteNumber(branch[step]?.count) ?? 0),
+ };
+ });
+ return {
+ type: "series",
+ render: "bar",
+ labels,
+ series,
+ isTimeSeries: false,
+ interval: "day",
+ };
+}
+
function asTable(rows: unknown[][], columns: string[]): ReportChartData {
return { type: "table", columns, rows: rows.slice(0, MAX_TABLE_ROWS) };
}
@@ -402,9 +595,13 @@ export function shapeReportChartData(
): ReportChartData {
if (
plan.source.kind === "TrendsQuery" ||
- plan.source.kind === "StickinessQuery"
+ plan.source.kind === "StickinessQuery" ||
+ plan.source.kind === "LifecycleQuery"
) {
- return shapeTrendsResponse(response, plan.render);
+ return shapeTrendsResponse(response, plan);
+ }
+ if (plan.source.kind === "FunnelsQuery") {
+ return shapeFunnelsResponse(response);
}
return shapeHogQLResponse(response, plan.render);
}
diff --git a/products/desktop/packages/core/src/panels/panelTypes.ts b/products/desktop/packages/core/src/panels/panelTypes.ts
index f07ea211b6f5..ded6fe1b349a 100644
--- a/products/desktop/packages/core/src/panels/panelTypes.ts
+++ b/products/desktop/packages/core/src/panels/panelTypes.ts
@@ -48,6 +48,15 @@ export type TabData =
type: "artifact";
runId: string;
artifactId: string;
+ /** PostHog object kind (e.g. "flag") when the artifact is a PostHog reference. */
+ objectKind?: string;
+ }
+ | {
+ // A PostHog object opened from an inline reference chip; renders the
+ // object page straight from kind + id, with no run artifact behind it.
+ type: "posthog-object";
+ objectKind: string;
+ objectId: string;
}
| {
type: "other";
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx
index e38705ea8b1a..56e6c998b5d7 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx
@@ -277,6 +277,7 @@ export function ActivityTimeline({
runId,
artifactId: payload.artifactId,
name: payload.name,
+ objectKind: payload.objectKind ?? undefined,
});
};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
index 9cb62d9e770e..b5abbf027c27 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
@@ -268,13 +268,14 @@ describe("TaskArtifactsList", () => {
expect(screen.getByText("report.md")).toBeInTheDocument();
expect(screen.getByText("Checkout funnel")).toBeInTheDocument();
expect(
- screen.getByText(/^Insight · Product analytics · Referenced 2 times/),
+ screen.getByText(/^Insight · Referenced 2 times/),
).toBeInTheDocument();
fireEvent.click(screen.getByText("Checkout funnel"));
expect(mocks.openArtifactTab).toHaveBeenCalledWith("task-1", {
runId: "run-1",
artifactId: "phref-1",
name: "Checkout funnel",
+ objectKind: "insight",
});
expect(
screen.queryByRole("button", { name: "Download Checkout funnel" }),
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
index 4e0a5a35ace9..49298ac57008 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
@@ -57,7 +57,10 @@ import {
import { FileIcon } from "@posthog/ui/primitives/FileIcon";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { formatFileSize } from "@posthog/ui/utils/formatFileSize";
-import { getObjectKind } from "@posthog/ui/utils/objectKinds";
+import {
+ getObjectKind,
+ POSTHOG_OBJECT_ICON_COLOR,
+} from "@posthog/ui/utils/objectKinds";
import { useMemo, useState } from "react";
const EMPTY_COMMENTS: ResourceComment[] = [];
@@ -361,7 +364,6 @@ function PostHogObjectRow({
const ObjectIcon = object.icon;
const meta = [
object.kindLabel,
- object.source,
occurrenceCount > 1 ? `Referenced ${occurrenceCount} times` : null,
uploadedAt ? formatRelativeTimeShort(uploadedAt) : null,
]
@@ -370,10 +372,12 @@ function PostHogObjectRow({
return (
<ArtifactCard
- icon={<ObjectIcon size={16} />}
+ icon={<ObjectIcon size={16} color={POSTHOG_OBJECT_ICON_COLOR} />}
title={name}
meta={meta}
- onOpen={() => openArtifactTab(taskId, { runId, artifactId, name })}
+ onOpen={() =>
+ openArtifactTab(taskId, { runId, artifactId, name, objectKind })
+ }
actions={<CommentCountBadge count={commentCount} />}
/>
);
diff --git a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.test.tsx b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.test.tsx
index 465ce94a684b..8240e74f7650 100644
--- a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.test.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.test.tsx
@@ -145,9 +145,7 @@ describe("EvidenceRefChip", () => {
</SessionTaskIdProvider>,
);
- fireEvent.click(
- screen.getByRole("button", { name: `${kind} reference` }),
- );
+ fireEvent.focus(screen.getByRole("link", { name: `${kind} reference` }));
expect(
screen.getByRole("button", { name: "Ask about this" }),
).toBeDefined();
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 62563d4968ee..2ea5a68f5ff4 100644
--- a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
@@ -7,6 +7,7 @@ import { type MouseEvent, type ReactNode, useId, useState } from "react";
import { useOptionalAuthenticatedClient } from "../../../features/auth/authClient";
import { useAuthStateValue } from "../../../features/auth/store";
import { useDraftStore } from "../../../features/message-editor/draftStore";
+import { usePanelLayoutStore } from "../../../features/panels/panelLayoutStore";
import { useSessionTaskId } from "../../../features/sessions/useSessionTaskId";
import { useAuthenticatedQuery } from "../../../hooks/useAuthenticatedQuery";
import { useCopy } from "../../../primitives/useCopy";
@@ -55,7 +56,7 @@ const SPARK_PAD = 2;
const SPARK_COLOR = "var(--evidence-spark-color, var(--data-color-1, #1d4aff))";
/** Mini chart of the preview's primary series: a line for time series, columns for categories. */
-function Sparkline({
+export function EvidenceSparkline({
points,
render,
}: {
@@ -220,15 +221,17 @@ export function EvidenceHoverCard({
</div>
{preview.spark && preview.spark.points.length > 1 && (
<div className="mt-2.5">
- <Sparkline
+ <EvidenceSparkline
points={preview.spark.points}
render={preview.spark.render}
/>
</div>
)}
- {preview.detail && (
+ {(preview.status || preview.detail) && (
<div className="mt-1.5 text-(--gray-10) text-[11.5px] leading-snug">
- {preview.detail}
+ {[preview.status?.label, preview.detail]
+ .filter(Boolean)
+ .join(" · ")}
</div>
)}
{preview.facts && preview.facts.length > 0 && (
@@ -405,9 +408,21 @@ export function EvidenceRefChip({
setOpen(false);
}
: undefined;
+ const openPostHogObjectTab = usePanelLayoutStore(
+ (state) => state.openPostHogObjectTab,
+ );
- const openInPostHog = (event: MouseEvent<HTMLAnchorElement>) => {
+ const openReference = (event: MouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
+ if (taskId) {
+ openPostHogObjectTab(taskId, {
+ kind: target.kind,
+ id: target.id,
+ name: typeof children === "string" ? children : target.id,
+ });
+ setOpen(false);
+ return;
+ }
if (url) openExternalUrl(url);
};
@@ -436,13 +451,14 @@ export function EvidenceRefChip({
// to PostHog instead of toggling the popover.
onFocus={() => setOpen(true)}
render={
- url ? (
+ url || taskId ? (
// Keep the truthful role: Enter follows the link (opens the
- // object in PostHog), it does not act as a popover button.
+ // object's page in the app, or in PostHog outside a session), it
+ // does not act as a popover button.
// biome-ignore lint/a11y/useSemanticElements: the element already is an <a>; the explicit role restores link semantics the popover trigger's role="button" would override
<a
- href={url}
- onClick={openInPostHog}
+ href={url ?? "#"}
+ onClick={openReference}
// biome-ignore lint/a11y/noRedundantRoles: not redundant — the popover trigger injects role="button" without it
role="link"
className={refClass}
diff --git a/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.tsx b/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.tsx
index 946d682ba47f..3a5e378eb595 100644
--- a/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.tsx
@@ -131,7 +131,7 @@ function InsightChartCard({
if (!insight) return null;
const plan = planReportChart(insight.query);
if (plan.kind !== "run") return { name: insight.name, data: null };
- const response = await client.runQuery(plan.source);
+ const response = insight.response ?? (await client.runQuery(plan.source));
return { name: insight.name, data: shapeReportChartData(response, plan) };
},
{ staleTime: 5 * 60 * 1000, refetchOnWindowFocus: false, retry: 1 },
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 332a9b755784..cddb31457564 100644
--- a/products/desktop/packages/ui/src/features/editor/evidencePreview.test.ts
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreview.test.ts
@@ -72,6 +72,50 @@ describe("fetchEvidencePreview", () => {
});
});
+ it("uses the saved insight result without running a second query", async () => {
+ const runQuery = vi.fn();
+ const client = fakeClient({
+ getInsightDefinition: vi.fn().mockResolvedValue({
+ name: "Unique users per variant",
+ description: null,
+ query: {
+ kind: "InsightVizNode",
+ source: {
+ kind: "TrendsQuery",
+ trendsFilter: { display: "ActionsTable" },
+ },
+ },
+ response: {
+ results: [
+ {
+ label: "$feature_flag_called - true",
+ breakdown_value: "true",
+ data: [],
+ days: [],
+ aggregated_value: 2,
+ },
+ {
+ label: "$feature_flag_called - None",
+ breakdown_value: null,
+ data: [],
+ days: [],
+ aggregated_value: 4,
+ },
+ ],
+ },
+ }),
+ runQuery,
+ });
+
+ await expect(
+ fetchEvidencePreview(client, { kind: "insight", id: "sdyR2Pn8" }),
+ ).resolves.toMatchObject({
+ title: "Unique users per variant",
+ detail: "Breakdown, Total",
+ });
+ expect(runQuery).not.toHaveBeenCalled();
+ });
+
it("returns null for an insight id that does not resolve", async () => {
const client = fakeClient({
getInsightDefinition: vi.fn().mockResolvedValue(null),
diff --git a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
index 38bf6c8d5795..f5e476467442 100644
--- a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
@@ -1,3 +1,4 @@
+import type { EvidenceDetailSection } from "@posthog/api-client/evidence-previews";
import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";
import {
type ChartHeadlineStat,
@@ -17,12 +18,29 @@ import type { EvidenceLinkTarget } from "../../utils/evidenceLinks";
export interface EvidenceCardData {
title: string;
detail?: string;
+ /** Lifecycle state as a badge label + tone, kept out of `detail`. */
+ status?: {
+ label: string;
+ tone: "positive" | "neutral" | "caution" | "critical";
+ };
/** Short scannable attributes, e.g. "100% rollout" or "42 clicks". */
facts?: string[];
+ /** Headline numbers for the full page's stat strip; chips use `facts`. */
+ stats?: Array<{ label: string; value: string }>;
/** Latest value + step change when the result is a single time series. */
headline?: ChartHeadlineStat | null;
- /** Mini chart of the primary series. */
- spark?: { points: number[]; render: "line" | "bar" };
+ /** Mini chart of the primary series; `labels` carries bucket dates. */
+ spark?: { points: number[]; labels?: string[]; render: "line" | "bar" };
+ /** A titled multi-series time chart, drawn with hover values on full pages. */
+ chart?: {
+ title: string;
+ labels: string[];
+ series: Array<{ label: string; data: number[] }>;
+ render: "line" | "bar";
+ };
+ sections?: EvidenceDetailSection[];
+ /** 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). */
resolvedId?: string;
}
@@ -94,7 +112,7 @@ async function insightPreview(
};
const plan = planReportChart(insight.query);
if (plan.kind !== "run") return base;
- const response = await client.runQuery(plan.source);
+ 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 };
}
diff --git a/products/desktop/packages/ui/src/features/panels/hooks/usePanelLayoutHooks.test.tsx b/products/desktop/packages/ui/src/features/panels/hooks/usePanelLayoutHooks.test.tsx
new file mode 100644
index 000000000000..6026ea0cbeb0
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/panels/hooks/usePanelLayoutHooks.test.tsx
@@ -0,0 +1,40 @@
+import { PackageIcon } from "@phosphor-icons/react";
+import type { Task } from "@posthog/shared/domain-types";
+import { renderHook } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import type { Tab } from "../panelTypes";
+import { useTabInjection } from "./usePanelLayoutHooks";
+
+vi.mock("../../actions/ActionTabIcon", () => ({
+ ActionTabIcon: () => null,
+}));
+
+vi.mock("../../sidebar/useCwd", () => ({
+ useCwd: () => null,
+}));
+
+vi.mock("../../task-detail/components/TabContentRenderer", () => ({
+ TabContentRenderer: () => null,
+}));
+
+describe("useTabInjection", () => {
+ it("uses the artifact icon instead of inferring an icon from an artifact name", () => {
+ const tabs: Tab[] = [
+ {
+ id: "artifact-reference-1",
+ label: "export.sql",
+ data: {
+ type: "artifact",
+ runId: "run-1",
+ artifactId: "reference-1",
+ },
+ },
+ ];
+
+ const { result } = renderHook(() =>
+ useTabInjection(tabs, "main-panel", "task-1", {} as Task, vi.fn()),
+ );
+
+ expect(result.current[0].icon).toMatchObject({ type: PackageIcon });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/panels/hooks/usePanelLayoutHooks.tsx b/products/desktop/packages/ui/src/features/panels/hooks/usePanelLayoutHooks.tsx
index 1874a5aaa3ba..7c8d07fe6fb1 100644
--- a/products/desktop/packages/ui/src/features/panels/hooks/usePanelLayoutHooks.tsx
+++ b/products/desktop/packages/ui/src/features/panels/hooks/usePanelLayoutHooks.tsx
@@ -2,6 +2,7 @@ import {
ChartLineUp,
ChatCenteredText,
FileText,
+ PackageIcon,
Scroll,
Terminal,
} from "@phosphor-icons/react";
@@ -10,6 +11,10 @@ import type { Task } from "@posthog/shared/domain-types";
import { useCallback, useEffect, useMemo, useRef } from "react";
import type { ImperativePanelGroupHandle } from "react-resizable-panels";
import { FileIcon } from "../../../primitives/FileIcon";
+import {
+ getObjectKind,
+ POSTHOG_OBJECT_ICON_COLOR,
+} from "../../../utils/objectKinds";
import { ActionTabIcon } from "../../actions/ActionTabIcon";
import { useCwd } from "../../sidebar/useCwd";
import { TabContentRenderer } from "../../task-detail/components/TabContentRenderer";
@@ -119,8 +124,16 @@ export function useTabInjection(
icon = <Scroll size={14} />;
} else if (tab.data.type === "autoresearch") {
icon = <ChartLineUp size={14} />;
+ } else if (tab.data.type === "posthog-object") {
+ const ObjectIcon = getObjectKind(tab.data.objectKind).icon;
+ icon = <ObjectIcon size={14} color={POSTHOG_OBJECT_ICON_COLOR} />;
} else if (tab.data.type === "artifact") {
- icon = <FileIcon filename={tab.label} size={14} />;
+ if (tab.data.objectKind) {
+ const ObjectIcon = getObjectKind(tab.data.objectKind).icon;
+ icon = <ObjectIcon size={14} color={POSTHOG_OBJECT_ICON_COLOR} />;
+ } else {
+ icon = <PackageIcon size={14} />;
+ }
}
}
diff --git a/products/desktop/packages/ui/src/features/panels/panelLayoutStore.test.ts b/products/desktop/packages/ui/src/features/panels/panelLayoutStore.test.ts
index ed6734fec8c1..6037404c7c08 100644
--- a/products/desktop/packages/ui/src/features/panels/panelLayoutStore.test.ts
+++ b/products/desktop/packages/ui/src/features/panels/panelLayoutStore.test.ts
@@ -193,6 +193,48 @@ describe("panelLayoutStore", () => {
});
});
+ describe("openPostHogObjectTab", () => {
+ beforeEach(() => {
+ usePanelLayoutStore.getState().initializeTask("task-1");
+ });
+
+ it("opens distinct tabs for hogql queries that share a long prefix", () => {
+ // A hogql reference's id is the SQL itself, so two queries can share a
+ // long header and differ only in a trailing clause. A truncated tab id
+ // would collide and show the first query under the second reference.
+ const prefix =
+ "SELECT event, count() AS total FROM events WHERE timestamp > now() - INTERVAL 30 DAY AND event = '$pageview' GROUP BY event";
+ const first = `${prefix} ORDER BY total DESC LIMIT 10`;
+ const second = `${prefix} ORDER BY total ASC LIMIT 5`;
+
+ usePanelLayoutStore.getState().openPostHogObjectTab("task-1", {
+ kind: "hogql",
+ id: first,
+ name: "Top events",
+ });
+ usePanelLayoutStore.getState().openPostHogObjectTab("task-1", {
+ kind: "hogql",
+ id: second,
+ name: "Bottom events",
+ });
+
+ const tree = getPanelTree("task-1");
+ if (tree.type !== "leaf") throw new Error("Expected the main panel");
+ const objectTabs = tree.content.tabs.filter(
+ (tab) => tab.data.type === "posthog-object",
+ );
+ expect(objectTabs).toHaveLength(2);
+ expect(new Set(objectTabs.map((tab) => tab.id)).size).toBe(2);
+
+ const secondTab = objectTabs.at(-1);
+ expect(tree.content.activeTabId).toBe(secondTab?.id);
+ expect(secondTab?.data).toMatchObject({
+ type: "posthog-object",
+ objectId: second,
+ });
+ });
+ });
+
describe("closeTab", () => {
beforeEach(() => {
usePanelLayoutStore.getState().initializeTask("task-1");
diff --git a/products/desktop/packages/ui/src/features/panels/panelLayoutStore.ts b/products/desktop/packages/ui/src/features/panels/panelLayoutStore.ts
index 13832c2c7f46..c0746324c4e4 100644
--- a/products/desktop/packages/ui/src/features/panels/panelLayoutStore.ts
+++ b/products/desktop/packages/ui/src/features/panels/panelLayoutStore.ts
@@ -1,4 +1,5 @@
import { channelDisplayLabel } from "@posthog/core/canvas/channelName";
+import { contentHash } from "@posthog/core/code-review/contentHash";
import {
addRecentFile,
addActionTab as coreAddActionTab,
@@ -70,7 +71,16 @@ export interface PanelLayoutStore {
openAutoresearchTab: (taskId: string) => void;
openArtifactTab: (
taskId: string,
- artifact: { runId: string; artifactId: string; name: string },
+ artifact: {
+ runId: string;
+ artifactId: string;
+ name: string;
+ objectKind?: string;
+ },
+ ) => void;
+ openPostHogObjectTab: (
+ taskId: string,
+ object: { kind: string; id: string; name: string },
) => void;
keepTab: (taskId: string, panelId: string, tabId: string) => void;
closeTab: (taskId: string, panelId: string, tabId: string) => void;
@@ -309,6 +319,32 @@ export const usePanelLayoutStore = createWithEqualityFn<PanelLayoutStore>()(
type: "artifact",
runId: artifact.runId,
artifactId: artifact.artifactId,
+ objectKind: artifact.objectKind,
+ },
+ "main",
+ ) as Partial<TaskLayout>,
+ ),
+ );
+ },
+
+ openPostHogObjectTab: (taskId, object) => {
+ // Ids can be long (a hogql reference's id is the SQL itself); the tab
+ // id only has to be stable per object, not carry the whole value. Hash
+ // the full id so two ids sharing a long prefix can't collide onto one tab.
+ const tabId = `posthog-object:${object.kind}:${contentHash(object.id)}`;
+ set((state) =>
+ updateTaskLayout(
+ state,
+ taskId,
+ (layout) =>
+ coreOpenReadonlyTab(
+ layout,
+ tabId,
+ object.name,
+ {
+ type: "posthog-object",
+ objectKind: object.kind,
+ objectId: object.id,
},
"main",
) as Partial<TaskLayout>,
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectDetails.stories.tsx b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectDetails.stories.tsx
new file mode 100644
index 000000000000..9fce53bbbadb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectDetails.stories.tsx
@@ -0,0 +1,69 @@
+import type { EvidencePreview } from "@posthog/api-client/evidence-previews";
+import { PostHogObjectDetails } from "@posthog/ui/features/posthog-objects/PostHogObjectDetails";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+
+const preview: EvidencePreview = {
+ title: "Checkout rollout",
+ spark: {
+ points: [24, 32, 28, 46, 51, 63, 58],
+ labels: [
+ "2026-08-10",
+ "2026-08-11",
+ "2026-08-12",
+ "2026-08-13",
+ "2026-08-14",
+ "2026-08-15",
+ "2026-08-16",
+ ],
+ render: "line",
+ },
+ chart: {
+ title: "Daily exposed users by variant",
+ labels: ["2026-08-10", "2026-08-11", "2026-08-12", "2026-08-13"],
+ series: [
+ { label: "control", data: [40, 44, 39, 47] },
+ { label: "test", data: [38, 45, 41, 44] },
+ ],
+ render: "line",
+ },
+ sections: [
+ {
+ title: "Configuration",
+ fields: [
+ { label: "State", value: "Enabled" },
+ { label: "Type", value: "Multivariate" },
+ { label: "Release conditions", value: "2 conditions" },
+ { label: "Evaluation runtime", value: "Both client and server" },
+ ],
+ },
+ {
+ title: "Activity",
+ fields: [
+ { label: "Calls in 7 days", value: "302" },
+ { label: "Staleness", value: "Active" },
+ ],
+ },
+ ],
+};
+
+const meta: Meta<typeof PostHogObjectDetails> = {
+ title: "Features/PostHog objects/PostHogObjectDetails",
+ component: PostHogObjectDetails,
+ parameters: { layout: "padded" },
+};
+
+export default meta;
+type Story = StoryObj<typeof PostHogObjectDetails>;
+
+export const WithActivity: Story = {
+ args: { preview },
+};
+
+export const DetailsOnly: Story = {
+ args: {
+ preview: {
+ ...preview,
+ spark: undefined,
+ },
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectDetails.test.ts b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectDetails.test.ts
new file mode 100644
index 000000000000..955a625fbf42
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectDetails.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+import { foldSections } from "./PostHogObjectDetails";
+
+describe("foldSections", () => {
+ it("keeps a single-field section under its own heading, not a neighbor's", () => {
+ // The default experiment shape: a one-field Metrics section sits between two
+ // multi-field sections. Folding it onto the last card mislabeled the metric
+ // as a variant, so each section must keep its own heading and fields.
+ const folded = foldSections([
+ {
+ title: "Configuration",
+ fields: [
+ { label: "Type", value: "Multivariate" },
+ { label: "Release conditions", value: "1 condition" },
+ ],
+ },
+ { title: "Metrics", fields: [{ label: "Metric 1", value: "Signups" }] },
+ {
+ title: "Variants",
+ fields: [
+ { label: "control", value: "50% rollout" },
+ { label: "test", value: "50% rollout" },
+ ],
+ },
+ ]);
+ expect(folded.map((section) => section.title)).toEqual([
+ "Configuration",
+ "Metrics",
+ "Variants",
+ ]);
+ expect(
+ folded.find((section) => section.title === "Metrics")?.fields,
+ ).toEqual([{ label: "Metric 1", value: "Signups" }]);
+ expect(
+ folded.find((section) => section.title === "Variants")?.fields,
+ ).toEqual([
+ { label: "control", value: "50% rollout" },
+ { label: "test", value: "50% rollout" },
+ ]);
+ });
+
+ it("merges sections that share a heading into one card", () => {
+ const folded = foldSections([
+ {
+ title: "Release conditions",
+ fields: [{ label: "Set 1", value: "plan is pro" }],
+ },
+ {
+ title: "Release conditions",
+ fields: [{ label: "Set 2", value: "country is US" }],
+ },
+ ]);
+ expect(folded).toEqual([
+ {
+ title: "Release conditions",
+ fields: [
+ { label: "Set 1", value: "plan is pro" },
+ { label: "Set 2", value: "country is US" },
+ ],
+ },
+ ]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectDetails.tsx b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectDetails.tsx
new file mode 100644
index 000000000000..495f0d58726a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectDetails.tsx
@@ -0,0 +1,201 @@
+import {
+ compactCount,
+ type EvidencePreview,
+} from "@posthog/api-client/evidence-previews";
+import { Card, CardContent, Text } from "@posthog/quill";
+import {
+ TimeSeriesBarChart,
+ TimeSeriesLineChart,
+ useChartTheme,
+} from "@posthog/quill-charts";
+import { EvidenceSparkline } from "@posthog/ui/features/editor/components/EvidenceRefChip";
+
+/**
+ * A daily series as a real chart with hover values. The hover chip keeps the
+ * passive sparkline; a full page has room for axes, a legend, and a tooltip.
+ */
+function DailySeriesChart({
+ labels,
+ series,
+ render,
+}: {
+ labels: string[];
+ series: Array<{ label: string; data: number[] }>;
+ render: "line" | "bar";
+}) {
+ const theme = useChartTheme();
+ const keyed = series.map((entry, index) => ({
+ key: `series-${index}`,
+ label: entry.label,
+ data: entry.data,
+ }));
+ const config = {
+ xAxis: { interval: "day" as const, timezone: "UTC" },
+ legend: series.length > 1 ? { show: true } : undefined,
+ };
+ return (
+ <div className="mt-2 flex h-40 w-full flex-col">
+ {render === "bar" ? (
+ <TimeSeriesBarChart
+ series={keyed}
+ labels={labels}
+ theme={theme}
+ config={config}
+ />
+ ) : (
+ <TimeSeriesLineChart
+ series={keyed}
+ labels={labels}
+ theme={theme}
+ config={config}
+ />
+ )}
+ </div>
+ );
+}
+
+function CardTitle({ children }: { children: string }) {
+ return (
+ <Text
+ variant="muted"
+ className="block text-[11px] uppercase tracking-wider"
+ >
+ {children}
+ </Text>
+ );
+}
+
+/**
+ * Latest point of a single series with its step change, so the chart answers
+ * "where is it now?" without hovering. Mirrors the inbox report cards; the
+ * delta stays uncolored because a rise here isn't necessarily good.
+ */
+function SeriesHeadline({ points }: { points: number[] }) {
+ const last = points[points.length - 1];
+ const previous = points.length > 1 ? points[points.length - 2] : null;
+ if (typeof last !== "number" || !Number.isFinite(last)) return null;
+ let delta: { label: string; up: boolean } | null = null;
+ if (
+ typeof previous === "number" &&
+ Number.isFinite(previous) &&
+ previous !== 0
+ ) {
+ const pct = ((last - previous) / Math.abs(previous)) * 100;
+ if (Math.abs(pct) >= 0.5) {
+ delta = {
+ label: `${Math.abs(pct) >= 10 ? Math.round(Math.abs(pct)) : Math.abs(pct).toFixed(1)}%`,
+ up: pct >= 0,
+ };
+ }
+ }
+ return (
+ <span className="flex shrink-0 items-baseline gap-1.5">
+ <span className="font-semibold text-[15px] text-foreground tabular-nums leading-none">
+ {compactCount(last)}
+ </span>
+ {delta && (
+ <span className="font-medium text-[11px] text-muted-foreground tabular-nums">
+ {delta.up ? "▲" : "▼"}
+ {delta.label}
+ </span>
+ )}
+ </span>
+ );
+}
+
+type Section = NonNullable<EvidencePreview["sections"]>[number];
+
+/**
+ * Merge sections that share a heading into one card, so a field never lands
+ * under a title that belongs to a different section. A uniquely-titled section
+ * keeps its own card even when it holds a single field: a correct one-field
+ * card beats folding a fact under a heading that contradicts it.
+ */
+export function foldSections(sections: Section[]): Section[] {
+ const byTitle = new Map<string, Section>();
+ const order: string[] = [];
+ for (const section of sections) {
+ const existing = byTitle.get(section.title);
+ if (existing) {
+ existing.fields = [...existing.fields, ...section.fields];
+ } else {
+ byTitle.set(section.title, { ...section, fields: [...section.fields] });
+ order.push(section.title);
+ }
+ }
+ return order.map((title) => byTitle.get(title) as Section);
+}
+
+export function PostHogObjectDetails({
+ preview,
+}: {
+ preview: EvidencePreview;
+}) {
+ const sections = foldSections(preview.sections ?? []);
+ const showActivity = preview.spark && preview.spark.points.length > 1;
+ const chart = preview.chart;
+
+ if (!showActivity && !chart && sections.length === 0) return null;
+
+ return (
+ <div className="flex flex-col gap-3">
+ {showActivity && preview.spark && (
+ <Card size="sm">
+ <CardContent>
+ <div className="flex items-center justify-between gap-2">
+ <CardTitle>Activity</CardTitle>
+ <SeriesHeadline points={preview.spark.points} />
+ </div>
+ {preview.spark.labels &&
+ preview.spark.labels.length === preview.spark.points.length ? (
+ <DailySeriesChart
+ labels={preview.spark.labels}
+ series={[{ label: "Activity", data: preview.spark.points }]}
+ render={preview.spark.render}
+ />
+ ) : (
+ <EvidenceSparkline
+ points={preview.spark.points}
+ render={preview.spark.render}
+ />
+ )}
+ </CardContent>
+ </Card>
+ )}
+ {chart && (
+ <Card size="sm">
+ <CardContent>
+ <CardTitle>{chart.title}</CardTitle>
+ <DailySeriesChart
+ labels={chart.labels}
+ series={chart.series}
+ render={chart.render}
+ />
+ </CardContent>
+ </Card>
+ )}
+ {sections.map((section) => (
+ <Card key={section.title} size="sm">
+ <CardContent>
+ <CardTitle>{section.title}</CardTitle>
+ <dl className="mt-2.5 flex flex-col">
+ {section.fields.map((field, index) => (
+ <div
+ key={`${field.label}:${index}`}
+ className="flex items-baseline gap-4 py-[5px]"
+ >
+ <dt className="w-40 shrink-0 text-muted-foreground text-xs">
+ {field.label}
+ </dt>
+ <dd className="min-w-0 break-words font-medium text-[13px] text-foreground tabular-nums leading-snug">
+ {field.value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ );
+}
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 8f899b80fb4a..b2be0616581e 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
@@ -4,6 +4,15 @@ 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)
+ ? `https://us.posthog.com/project/2/feature_flags/${id}`
+ : null,
+ ),
+);
vi.mock("@posthog/ui/hooks/useAuthenticatedQuery", () => ({
useAuthenticatedQuery: () => ({
@@ -12,20 +21,25 @@ vi.mock("@posthog/ui/hooks/useAuthenticatedQuery", () => ({
data: {
title: "new-checkout-flow",
detail: "Enabled",
- facts: ["100% rollout", "Used by 1 experiment"],
// The preview resolves the flag key to its numeric id.
resolvedId: "42",
+ facts: ["100% rollout", "Used by 1 experiment"],
+ sections: [
+ {
+ title: "Configuration",
+ fields: [
+ { label: "Type", value: "Boolean" },
+ { label: "Release conditions", value: "All users" },
+ ],
+ },
+ ],
},
}),
}));
vi.mock("@posthog/ui/features/editor/components/EvidenceRefChip", () => ({
- // 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.
- useEvidenceUrl: (_kind: string, id: string) =>
- /^\d+$/.test(id)
- ? `https://us.posthog.com/project/2/feature_flags/${id}`
- : null,
+ useEvidenceUrl,
+ EvidenceSparkline: () => null,
}));
describe("PostHogObjectPage", () => {
@@ -51,16 +65,20 @@ describe("PostHogObjectPage", () => {
expect(screen.getAllByText("new-checkout-flow")).toHaveLength(2);
expect(screen.getByText("100% rollout")).toBeInTheDocument();
+ expect(useEvidenceUrl).toHaveBeenLastCalledWith("flag", "42");
+ expect(screen.getByText("Configuration")).toBeInTheDocument();
+ expect(screen.getByText("Release conditions")).toBeInTheDocument();
+ expect(screen.getByText("All users")).toBeInTheDocument();
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 reference" }));
+ fireEvent.click(screen.getByRole("button", { name: "Copy ID" }));
expect(writeText).toHaveBeenCalledWith("new-checkout-flow");
await waitFor(() =>
expect(
- screen.getByRole("button", { name: "Reference copied" }),
+ screen.getByRole("button", { name: "ID copied" }),
).toBeInTheDocument(),
);
});
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 772d04a74c06..4f473d87d49f 100644
--- a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
@@ -1,6 +1,17 @@
import { CheckIcon, CopyIcon } from "@phosphor-icons/react";
import type { PostHogObjectArtifactMetadata } from "@posthog/core/canvas/runArtifactSchemas";
-import { Button, Heading, Skeleton, Text } from "@posthog/quill";
+import {
+ Badge,
+ Button,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ Heading,
+ Skeleton,
+ Text,
+} from "@posthog/quill";
import { useEvidenceUrl } from "@posthog/ui/features/editor/components/EvidenceRefChip";
import { MessageChartCard } from "@posthog/ui/features/editor/components/MessageChartCard";
import {
@@ -10,66 +21,263 @@ import {
import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
import { useCopy } from "@posthog/ui/primitives/useCopy";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
-import { getObjectKind } from "@posthog/ui/utils/objectKinds";
+import {
+ getObjectKind,
+ POSTHOG_OBJECT_ICON_COLOR,
+} from "@posthog/ui/utils/objectKinds";
+import { PostHogObjectDetails } from "./PostHogObjectDetails";
-function ObjectContent({
- metadata,
- preview,
+function StatStrip({
+ stats,
}: {
- metadata: PostHogObjectArtifactMetadata;
- preview: EvidenceCardData | null;
+ stats: Array<{ label: string; value: string }>;
}) {
- if (metadata.object_kind === "insight") {
- return (
- <MessageChartCard
- spec={{ mode: "insight", shortId: metadata.object_id }}
- blockKey={`artifact:${metadata.object_kind}:${metadata.object_id}`}
- />
- );
- }
- if (metadata.object_kind === "hogql") {
- return (
- <MessageChartCard
- spec={{ mode: "hogql", query: metadata.object_id }}
- blockKey={`artifact:${metadata.object_kind}:${metadata.object_id}`}
- />
- );
- }
- if (metadata.object_kind === "replay") {
- return (
- <MessageChartCard
- spec={{ mode: "replay", sessionId: metadata.object_id }}
- blockKey={`artifact:${metadata.object_kind}:${metadata.object_id}`}
- />
- );
- }
- if (!preview) {
+ return (
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ {stats.slice(0, 8).map((stat) => (
+ <div
+ key={stat.label}
+ className="rounded-lg border border-border bg-card px-3.5 py-2.5"
+ >
+ <div className="truncate text-[11px] text-muted-foreground">
+ {stat.label}
+ </div>
+ <div className="mt-0.5 truncate font-semibold text-foreground text-lg tabular-nums tracking-tight">
+ {stat.value}
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/**
+ * The object's identifier as a labeled chip; clicking copies it. A quill
+ * Button in the same variant and size as "Open in PostHog" beside it, so the
+ * two read as one control row.
+ */
+function IdChip({ id }: { id: string }) {
+ const { copied, copy } = useCopy();
+ return (
+ <Button
+ variant="outline"
+ size="sm"
+ data-attr="posthog-object-copy-reference"
+ aria-label={copied ? "ID copied" : "Copy ID"}
+ onClick={() => copy(id)}
+ className="max-w-44"
+ >
+ <span className="font-medium text-[10px] text-muted-foreground uppercase tracking-wide">
+ ID
+ </span>
+ <span className="truncate font-mono">{id}</span>
+ {copied ? <CheckIcon size={12} /> : <CopyIcon size={12} />}
+ </Button>
+ );
+}
+
+const STATUS_BADGE_VARIANT = {
+ positive: "success",
+ neutral: "default",
+ caution: "warning",
+ critical: "destructive",
+} as const;
+
+function FactChips({ facts }: { facts: string[] }) {
+ return (
+ <div className="flex flex-wrap gap-1.5">
+ {facts.map((fact) => (
+ <span
+ key={fact}
+ className="rounded-md border border-border bg-muted px-2 py-0.5 text-muted-foreground text-xs"
+ >
+ {fact}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+function ObjectContent({ preview }: { preview: EvidenceCardData }) {
+ // A dashboard is its metrics: render each tile's insight as a live chart
+ // and skip the descriptive cards, which only restate what the charts show.
+ if (preview.tiles && preview.tiles.length > 0) {
return (
- <div className="rounded-md border border-border bg-muted p-4">
- <Text>This object is not available in the current project.</Text>
- <Text className="mt-1 text-muted-foreground text-sm">
- Check the identifier or open PostHog to review access.
- </Text>
+ <div className="flex flex-col gap-3">
+ {preview.tiles.map((tile, index) => (
+ <MessageChartCard
+ key={`${tile.shortId}:${index}`}
+ spec={{ mode: "insight", shortId: tile.shortId }}
+ blockKey={`artifact:dashboard-tile:${index}:${tile.shortId}`}
+ />
+ ))}
</div>
);
}
+ const stats = (preview.stats ?? []).filter((stat) => stat.value);
+ return (
+ <div className="flex flex-col gap-3">
+ {stats.length > 0 ? (
+ <StatStrip stats={stats} />
+ ) : preview.facts && preview.facts.length > 0 ? (
+ <FactChips facts={preview.facts} />
+ ) : null}
+ <PostHogObjectDetails preview={preview} />
+ </div>
+ );
+}
+
+function UnavailableObject({
+ isError,
+ objectKind,
+}: {
+ isError: boolean;
+ objectKind: string;
+}) {
+ const ObjectIcon = getObjectKind(objectKind).icon;
+ return (
+ <Empty className="rounded-lg border border-border">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <ObjectIcon size={18} />
+ </EmptyMedia>
+ <EmptyTitle>
+ {isError
+ ? "Couldn't load this object"
+ : "This object is not available in the current project"}
+ </EmptyTitle>
+ <EmptyDescription>
+ {isError
+ ? "Try again, or open PostHog to review it."
+ : "Check the identifier or open PostHog to review access."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+}
+
+export interface PostHogObjectViewProps {
+ objectKind: string;
+ objectId: string;
+ /** Shown while the preview loads or when the object has no live name. */
+ fallbackName: string;
+ url: string | null;
+ /** Omitted when the page isn't backed by a run artifact (chip-opened). */
+ occurrenceCount?: number;
+ state: "loading" | "error" | "missing" | "ready";
+ preview: EvidenceCardData | null;
+}
+
+/** Pure page body; `PostHogObjectPage` resolves the preview and URL. */
+export function PostHogObjectPageView({
+ objectKind,
+ objectId,
+ fallbackName,
+ url,
+ occurrenceCount,
+ state,
+ preview,
+}: PostHogObjectViewProps) {
+ const object = getObjectKind(objectKind);
+ const ObjectIcon = object.icon;
+ const usesChartRenderer = objectKind === "insight" || objectKind === "hogql";
+ const title = 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 ·
+ // Feature flags", "SQL query · SQL editor").
+ const showSource = !object.source
+ .toLowerCase()
+ .split(" ")[0]
+ .startsWith(object.kindLabel.toLowerCase().split(" ")[0]);
+ const metaLine = [
+ object.kindLabel,
+ showSource ? object.source : null,
+ preview?.detail,
+ ]
+ .filter(Boolean)
+ .join(" · ");
+
return (
- <div className="rounded-md border border-border bg-card p-4">
- {preview.detail && (
- <Text className="text-muted-foreground">{preview.detail}</Text>
- )}
- {preview.facts && preview.facts.length > 0 && (
- <div className="mt-3 flex flex-wrap gap-1.5">
- {preview.facts.map((fact) => (
- <span
- key={fact}
- className="rounded-sm bg-muted px-2 py-1 text-muted-foreground text-xs"
- >
- {fact}
- </span>
- ))}
+ <div className="h-full overflow-y-auto">
+ <div className="mx-auto flex w-full max-w-4xl flex-col px-8 py-8">
+ <header className="flex flex-wrap items-center justify-between gap-x-6 gap-y-3">
+ <div className="flex min-w-0 flex-1 basis-72 items-center gap-3">
+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg border border-border bg-card">
+ <ObjectIcon size={20} color={POSTHOG_OBJECT_ICON_COLOR} />
+ </div>
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <Heading size="base" className="truncate tracking-tight">
+ {title}
+ </Heading>
+ {status && (
+ <Badge variant={STATUS_BADGE_VARIANT[status.tone]}>
+ {status.label}
+ </Badge>
+ )}
+ </div>
+ <Text size="sm" variant="muted" className="mt-0.5 block truncate">
+ {metaLine}
+ </Text>
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ {/* A hogql reference's id is the SQL itself, not an identifier
+ worth copying; the chart card already shows the query. */}
+ {objectKind !== "hogql" && <IdChip id={objectId} />}
+ {url && (
+ <Button
+ variant="outline"
+ size="sm"
+ data-attr="posthog-object-open-in-posthog"
+ onClick={() => openExternalUrl(url)}
+ >
+ Open in PostHog ↗
+ </Button>
+ )}
+ </div>
+ </header>
+
+ <div className="mt-6">
+ {usesChartRenderer ? (
+ <MessageChartCard
+ spec={
+ objectKind === "insight"
+ ? { mode: "insight", shortId: objectId }
+ : { mode: "hogql", query: objectId }
+ }
+ blockKey={`artifact:${objectKind}:${objectId}`}
+ />
+ ) : state === "loading" ? (
+ // Mirrors the loaded layout (stat strip, chart, detail card) so
+ // content lands in place instead of reflowing the page.
+ <div className="flex flex-col gap-3">
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ {[0, 1, 2, 3].map((tile) => (
+ <Skeleton key={tile} className="h-[62px] w-full rounded-lg" />
+ ))}
+ </div>
+ <Skeleton className="h-56 w-full rounded-lg" />
+ <Skeleton className="h-40 w-full rounded-lg" />
+ </div>
+ ) : preview ? (
+ <ObjectContent preview={preview} />
+ ) : (
+ <UnavailableObject
+ isError={state === "error"}
+ objectKind={objectKind}
+ />
+ )}
</div>
- )}
+
+ {occurrenceCount !== undefined && (
+ <div className="mt-6 border-border border-t pt-4 text-muted-foreground text-xs">
+ Referenced {occurrenceCount.toLocaleString()}{" "}
+ {occurrenceCount === 1 ? "time" : "times"} in this task
+ </div>
+ )}
+ </div>
</div>
);
}
@@ -78,16 +286,13 @@ export function PostHogObjectPage({
metadata,
fallbackName,
}: {
- metadata: PostHogObjectArtifactMetadata;
+ /** Only kind + id when opened from an inline reference chip. */
+ metadata: Pick<PostHogObjectArtifactMetadata, "object_kind" | "object_id"> &
+ Partial<Omit<PostHogObjectArtifactMetadata, "object_kind" | "object_id">>;
fallbackName: string;
}) {
- const object = getObjectKind(metadata.object_kind);
- const ObjectIcon = object.icon;
- const { copied, copy } = useCopy();
- const usesBlockRenderer =
- metadata.object_kind === "insight" ||
- metadata.object_kind === "hogql" ||
- metadata.object_kind === "replay";
+ const usesChartRenderer =
+ metadata.object_kind === "insight" || metadata.object_kind === "hogql";
const query = useAuthenticatedQuery(
["evidence-preview", metadata.object_kind, metadata.object_id],
(client) =>
@@ -96,76 +301,35 @@ export function PostHogObjectPage({
id: metadata.object_id,
}),
{
- enabled: !usesBlockRenderer,
+ enabled: !usesChartRenderer,
staleTime: 5 * 60 * 1000,
refetchOnWindowFocus: false,
retry: 1,
},
);
- // A flag cited by key or an event cited by name has no page under the cited
- // id; link out via the id the preview resolved, as EvidenceRefChip does.
const url = useEvidenceUrl(
metadata.object_kind,
query.data?.resolvedId ?? metadata.object_id,
);
- const title = query.data?.title ?? fallbackName;
+ const state = usesChartRenderer
+ ? "ready"
+ : query.isPending
+ ? "loading"
+ : query.isError
+ ? "error"
+ : query.data
+ ? "ready"
+ : "missing";
return (
- <div className="h-full overflow-y-auto">
- <div className="mx-auto flex w-full max-w-4xl flex-col gap-5 px-6 py-7">
- <header className="flex items-start justify-between gap-4">
- <div className="min-w-0">
- <div className="mb-2 flex items-center gap-1.5 text-muted-foreground text-xs uppercase tracking-wide">
- <ObjectIcon size={14} />
- <span>{object.kindLabel}</span>
- <span>·</span>
- <span>{object.source}</span>
- </div>
- <Heading size="xl" className="truncate">
- {title}
- </Heading>
- <div className="mt-2 flex items-center gap-1 font-mono text-muted-foreground text-xs">
- <span className="max-w-xl truncate">{metadata.object_id}</span>
- <button
- type="button"
- data-attr="posthog-object-copy-reference"
- aria-label={copied ? "Reference copied" : "Copy reference"}
- onClick={() => copy(metadata.object_id)}
- className="inline-flex size-6 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent hover:bg-fill-hover hover:text-foreground"
- >
- {copied ? <CheckIcon size={12} /> : <CopyIcon size={12} />}
- </button>
- </div>
- </div>
- {url && (
- <Button
- variant="outline"
- data-attr="posthog-object-open-in-posthog"
- onClick={() => openExternalUrl(url)}
- >
- Open in PostHog ↗
- </Button>
- )}
- </header>
-
- {usesBlockRenderer ? (
- <ObjectContent metadata={metadata} preview={null} />
- ) : query.isPending ? (
- <div className="space-y-3">
- <Skeleton className="h-44 w-full" />
- <Skeleton className="h-16 w-full" />
- </div>
- ) : query.isError ? (
- <ObjectContent metadata={metadata} preview={null} />
- ) : (
- <ObjectContent metadata={metadata} preview={query.data ?? null} />
- )}
-
- <div className="border-border border-t pt-4 text-muted-foreground text-xs">
- Referenced {metadata.occurrence_count.toLocaleString()}{" "}
- {metadata.occurrence_count === 1 ? "time" : "times"} in this task
- </div>
- </div>
- </div>
+ <PostHogObjectPageView
+ objectKind={metadata.object_kind}
+ objectId={metadata.object_id}
+ fallbackName={fallbackName}
+ url={url}
+ occurrenceCount={metadata.occurrence_count}
+ state={state}
+ preview={query.data ?? null}
+ />
);
}
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
new file mode 100644
index 000000000000..a02675ae8c37
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPageView.stories.tsx
@@ -0,0 +1,163 @@
+import type { EvidenceCardData } from "@posthog/ui/features/editor/evidencePreview";
+import { PostHogObjectPageView } from "@posthog/ui/features/posthog-objects/PostHogObjectPage";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+
+const DAYS = [
+ "2026-08-10",
+ "2026-08-11",
+ "2026-08-12",
+ "2026-08-13",
+ "2026-08-14",
+ "2026-08-15",
+ "2026-08-16",
+];
+
+const flagPreview: EvidenceCardData = {
+ title: "pi-harness",
+ detail: "Cloud task harness rollout",
+ status: { label: "Enabled", tone: "positive" },
+ stats: [
+ { label: "Rollout", value: "100%" },
+ { label: "Variants", value: "3" },
+ { label: "Type", value: "Multivariate" },
+ { label: "Calls in 7 days", value: "1.2K" },
+ ],
+ spark: { points: [24, 32, 28, 46, 51, 63, 58], labels: DAYS, render: "line" },
+ sections: [
+ {
+ title: "Configuration",
+ fields: [
+ { label: "Type", value: "Multivariate" },
+ { label: "Release conditions", value: "2 conditions" },
+ { label: "Evaluation runtime", value: "Both client and server" },
+ { label: "Last called", value: "Aug 16" },
+ ],
+ },
+ {
+ title: "Release conditions",
+ fields: [
+ { label: "Set 1", value: "plan is pro · 25% rollout · Variant: test" },
+ { label: "Set 2", value: "75% rollout" },
+ ],
+ },
+ ],
+};
+
+const experimentPreview: EvidenceCardData = {
+ title: "Upgrade prompt experiment",
+ detail: "Day 28 · Started Jul 24",
+ status: { label: "Running", tone: "positive" },
+ stats: [
+ { label: "Running for", value: "28 days" },
+ { label: "control exposed", value: "578" },
+ { label: "aggressive exposed", value: "593" },
+ { label: "subtle exposed", value: "563" },
+ ],
+ chart: {
+ title: "Daily exposed users 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",
+ },
+ sections: [
+ {
+ title: "Configuration",
+ fields: [
+ {
+ label: "Hypothesis",
+ value: "A softer upgrade prompt converts more users.",
+ },
+ { label: "Feature flag", value: "upgrade-prompt-v1" },
+ { label: "Variants", value: "34/33/33" },
+ { label: "Created", value: "Jul 24" },
+ ],
+ },
+ {
+ title: "Metrics",
+ fields: [
+ { label: "Metric 1", value: "Login to upload" },
+ { label: "Metric 2", value: "Downloads per user" },
+ ],
+ },
+ {
+ title: "Variants",
+ fields: [
+ { label: "control", value: "34% rollout" },
+ { label: "aggressive", value: "33% rollout" },
+ { label: "subtle", value: "33% rollout" },
+ ],
+ },
+ ],
+};
+
+const meta: Meta<typeof PostHogObjectPageView> = {
+ title: "Features/PostHog objects/PostHogObjectPageView",
+ component: PostHogObjectPageView,
+ parameters: { layout: "fullscreen" },
+};
+
+export default meta;
+type Story = StoryObj<typeof PostHogObjectPageView>;
+
+export const FeatureFlag: Story = {
+ args: {
+ objectKind: "flag",
+ objectId: "390",
+ fallbackName: "pi-harness",
+ url: "https://us.posthog.com/project/2/feature_flags/390",
+ occurrenceCount: 4,
+ state: "ready",
+ preview: flagPreview,
+ },
+};
+
+export const Experiment: Story = {
+ args: {
+ objectKind: "experiment",
+ objectId: "5",
+ fallbackName: "Upgrade prompt experiment",
+ url: "https://us.posthog.com/project/2/experiments/5",
+ occurrenceCount: 5,
+ state: "ready",
+ preview: experimentPreview,
+ },
+};
+
+export const SqlQuery: Story = {
+ args: {
+ objectKind: "hogql",
+ objectId: "SELECT count() FROM events WHERE event = '$pageview'",
+ fallbackName: "Total pageviews",
+ url: "https://us.posthog.com/project/2/sql?open_query=SELECT+1",
+ state: "ready",
+ preview: null,
+ },
+};
+
+export const Loading: Story = {
+ args: {
+ objectKind: "flag",
+ objectId: "390",
+ fallbackName: "pi-harness",
+ url: null,
+ occurrenceCount: 4,
+ state: "loading",
+ preview: null,
+ },
+};
+
+export const MissingObject: Story = {
+ args: {
+ objectKind: "flag",
+ objectId: "does-not-exist",
+ fallbackName: "does-not-exist",
+ url: null,
+ occurrenceCount: 1,
+ state: "missing",
+ preview: null,
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx
index 59a3eb0d07b6..b8bccac95b93 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx
@@ -7,6 +7,7 @@ import {
} from "../../code-review/components/LazyReviewPages";
import type { Tab } from "../../panels/panelTypes";
import { PiSessionView } from "../../pi-sessions/PiSessionView";
+import { PostHogObjectPage } from "../../posthog-objects/PostHogObjectPage";
import { ArtifactPreview } from "../../sessions/components/ArtifactPreview";
import { useIsCloudTask } from "../../workspace/useWorkspace";
import { ActionPanel } from "./ActionPanel";
@@ -92,6 +93,17 @@ export function TabContentRenderer({
/>
);
+ case "posthog-object":
+ return (
+ <PostHogObjectPage
+ metadata={{
+ object_kind: data.objectKind,
+ object_id: data.objectId,
+ }}
+ fallbackName={tab.label}
+ />
+ );
+
case "other":
switch (tab.id) {
case "files":
diff --git a/products/desktop/packages/ui/src/utils/objectKinds.ts b/products/desktop/packages/ui/src/utils/objectKinds.ts
index e2fd3ac5ca55..c2fe2452d36d 100644
--- a/products/desktop/packages/ui/src/utils/objectKinds.ts
+++ b/products/desktop/packages/ui/src/utils/objectKinds.ts
@@ -43,6 +43,14 @@ export interface ObjectKindDef {
block?: boolean;
}
+/**
+ * The brand primary (orange in light, yellow in dark): PostHog object icons
+ * carry it wherever they appear so PostHog-native artifacts read as PostHog at
+ * a glance next to files and PRs. Passed as the phosphor `color` prop (an SVG
+ * fill), which quill highlight rules can't reset the way `currentColor` can.
+ */
+export const POSTHOG_OBJECT_ICON_COLOR = "var(--primary)";
+
export const OBJECT_KINDS: Record<string, ObjectKindDef> = {
insight: {
icon: ChartLineIcon,