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): live PostHog object tags in agent messages (#83182)

Shy Alterb41367fb68f4
diff --git a/products/desktop/packages/api-client/src/evidence-previews.test.ts b/products/desktop/packages/api-client/src/evidence-previews.test.ts
new file mode 100644
index 000000000000..84066a157cd3
--- /dev/null
+++ b/products/desktop/packages/api-client/src/evidence-previews.test.ts
@@ -0,0 +1,386 @@
+import { describe, expect, it } from "vitest";
+import {
+ compactCount,
+ dailySparkPoints,
+ decorateFlagPreview,
+ decorateSurveyPreview,
+ exposureFact,
+ gridRows,
+ hogqlEscape,
+ shapeCohortPreview,
+ shapeDashboardPreview,
+ shapeErrorIssuePreview,
+ shapeEvaluationPreview,
+ shapeEventDefinitionPreview,
+ shapeExperimentPreview,
+ shapeFlagPreview,
+ shapePersonPreview,
+ shapeRecordingPreview,
+ shapeSurveyPreview,
+ shapeTicketPreview,
+ shapeTracePreview,
+} from "./evidence-previews";
+import type { Schemas } from "./generated";
+
+// The shapers only read the fields they show; build minimal inputs and cast.
+describe("evidence preview shaping", () => {
+ it("keys the flag preview by key and carries the numeric id for links", () => {
+ const preview = shapeFlagPreview({
+ id: 42,
+ key: "new-checkout-flow",
+ name: "New checkout rollout",
+ active: true,
+ filters: {
+ groups: [{ rollout_percentage: 25 }],
+ multivariate: { variants: [{ key: "a" }, { key: "b" }] },
+ },
+ experiment_set: [7],
+ } as unknown as Schemas.FeatureFlag);
+ expect(preview).toEqual({
+ title: "new-checkout-flow",
+ detail: "Enabled · New checkout rollout",
+ facts: ["25% rollout", "2 variants", "Used by 1 experiment"],
+ resolvedId: "42",
+ });
+ });
+
+ it("shows a disabled flag without a name as just the state", () => {
+ const preview = shapeFlagPreview({
+ id: 7,
+ key: "old-flag",
+ active: false,
+ } as Schemas.FeatureFlag);
+ expect(preview.detail).toBe("Disabled");
+ });
+
+ it.each([
+ ["draft", {}, "Draft"],
+ ["running", { start_date: "2024-01-03T10:00:00Z" }, /^Running since Jan 3/],
+ [
+ "ended",
+ { start_date: "2024-01-03T10:00:00Z", end_date: "2024-02-02T10:00:00Z" },
+ /^Ended 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);
+ }
+ });
+
+ it("humanizes the error issue status", () => {
+ const preview = shapeErrorIssuePreview({
+ id: "018f",
+ name: "TypeError in CouponValidator",
+ status: "pending_release",
+ first_seen: "2024-01-03T10:00:00Z",
+ } as Schemas.ErrorTrackingIssueFull);
+ expect(preview.detail).toMatch(/^Pending release · First seen Jan 3/);
+ });
+
+ it.each([
+ ["minutes", 754, /^13 min/],
+ ["seconds", 42, /^42s/],
+ ])("formats the recording duration in %s", (_unit, seconds, expected) => {
+ const preview = shapeRecordingPreview({
+ id: "s_1",
+ distinct_id: "user-1",
+ recording_duration: seconds,
+ start_time: "2024-01-03T10:00:00Z",
+ } as Schemas.SessionRecording);
+ expect(preview.title).toBe("Session by user-1");
+ expect(preview.detail).toMatch(expected);
+ });
+
+ it("surfaces a recording's activity and entry page as facts", () => {
+ const preview = shapeRecordingPreview({
+ id: "s_1",
+ distinct_id: "user-1",
+ recording_duration: 120,
+ click_count: 42,
+ console_error_count: 3,
+ start_url: "https://app.example.com/checkout?step=2",
+ } as Schemas.SessionRecording);
+ expect(preview.facts).toEqual([
+ "42 clicks",
+ "3 console errors",
+ "app.example.com/checkout",
+ ]);
+ });
+
+ it("describes an evaluation with its state, reason, and type", () => {
+ expect(
+ shapeEvaluationPreview({
+ id: "ev1",
+ name: "Faithfulness eval",
+ enabled: true,
+ status: "degraded",
+ status_reason: "Provider key expired",
+ evaluation_type: "llm_judge",
+ } as unknown as Schemas.Evaluation),
+ ).toEqual({
+ title: "Faithfulness eval",
+ detail: "Enabled · Provider key expired",
+ facts: ["LLM judge"],
+ });
+ });
+
+ it("names a dashboard's tiles instead of counting them", () => {
+ const preview = shapeDashboardPreview({
+ id: 12,
+ name: "Growth",
+ tiles: [
+ { insight: { name: "DAU" } },
+ { insight: { name: "Signup funnel" } },
+ { insight: { name: "Revenue" } },
+ { insight: { name: "Churn" } },
+ ],
+ } as unknown as Schemas.Dashboard);
+ expect(preview.facts).toEqual([
+ "DAU",
+ "Signup funnel",
+ "Revenue",
+ "+1 more",
+ ]);
+ });
+
+ // 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([
+ [
+ [{ insight: { name: "DAU" } }, {}, {}],
+ ["DAU", "+2 more"],
+ ],
+ [
+ [
+ { insight: { name: "DAU" } },
+ { insight: { name: "Revenue" } },
+ {},
+ {},
+ {},
+ ],
+ ["DAU", "Revenue", "+3 more"],
+ ],
+ ])("counts unnamed tiles in the remainder", (tiles, expected) => {
+ const preview = shapeDashboardPreview({
+ id: 12,
+ name: "Growth",
+ tiles,
+ } as unknown as Schemas.Dashboard);
+ expect(preview.facts).toEqual(expected);
+ });
+
+ it("describes a cohort by its size, falling back to the description", () => {
+ expect(
+ shapeCohortPreview({
+ id: 31,
+ name: "Power users",
+ count: 1247,
+ } as Schemas.Cohort).detail,
+ ).toBe("1,247 people");
+ expect(
+ shapeCohortPreview({
+ id: 31,
+ name: "Power users",
+ count: null,
+ description: "Weekly active users",
+ } as Schemas.Cohort).detail,
+ ).toBe("Weekly active users");
+ });
+
+ it("summarizes a ticket with its snippet, state line, and traffic", () => {
+ const preview = shapeTicketPreview({
+ id: "t1",
+ ticket_number: 841,
+ email_subject: "Coupon code rejected at checkout",
+ status: "on_hold",
+ priority: "high",
+ channel_source: "email",
+ message_count: 12,
+ last_message_at: "2024-01-03T10:00:00Z",
+ last_message_text: "Still failing after clearing cookies",
+ assignee: { id: "u1", type: "user", user: { first_name: "Ann" } },
+ } as unknown as Schemas.Ticket);
+ expect(preview.title).toBe("Coupon code rejected at checkout");
+ expect(preview.detail).toBe("“Still failing after clearing cookies”");
+ expect(preview.facts).toEqual([
+ "On hold · High · Email",
+ "12 messages · last reply Jan 3, 2024",
+ "Assigned to Ann",
+ ]);
+ });
+
+ it("falls back to the ticket number when there is no subject", () => {
+ const preview = shapeTicketPreview({
+ id: "t1",
+ ticket_number: 841,
+ channel_source: "widget",
+ } as unknown as Schemas.Ticket);
+ expect(preview.title).toBe("Ticket #841");
+ });
+
+ it("identifies a person by name or email and carries the uuid for links", () => {
+ expect(
+ shapePersonPreview({
+ id: 1,
+ name: "",
+ uuid: "0192-aaaa",
+ distinct_ids: ["d1"],
+ properties: { email: "[email protected]" },
+ created_at: "2024-03-01T00:00:00Z",
+ last_seen_at: "2024-01-03T10:00:00Z",
+ } as unknown as Schemas.PersonRecord),
+ ).toMatchObject({
+ title: "[email protected]",
+ detail: expect.stringMatching(/^Last seen Jan 3/),
+ resolvedId: "0192-aaaa",
+ });
+ });
+
+ it("adds a person's country and browser as pills", () => {
+ const preview = shapePersonPreview({
+ id: 1,
+ name: "Ann",
+ uuid: "u1",
+ distinct_ids: ["d1"],
+ properties: { $geoip_country_name: "Germany", $browser: "Chrome" },
+ created_at: "2024-03-01T00:00:00Z",
+ } as unknown as Schemas.PersonRecord);
+ expect(preview.facts).toEqual(["Germany", "Chrome"]);
+ });
+
+ it("verifies an event by its definition and resolves the page id", () => {
+ expect(
+ shapeEventDefinitionPreview({
+ id: "def-1",
+ name: "cart_saved",
+ last_seen_at: "2024-01-03T10:00:00Z",
+ } as unknown as Schemas.EventDefinitionRecord),
+ ).toMatchObject({
+ title: "cart_saved",
+ detail: expect.stringMatching(/^Last seen Jan 3/),
+ resolvedId: "def-1",
+ });
+ });
+
+ it.each([
+ ["quotes", "it's", "it\\'s"],
+ ["backslashes", "a\\b", "a\\\\b"],
+ ])("escapes %s for hogql interpolation", (_name, input, expected) => {
+ expect(hogqlEscape(input)).toBe(expected);
+ });
+
+ it("reduces a daily grid to spark points and compact totals", () => {
+ const rows = gridRows({
+ results: [
+ ["2024-01-01", 5100000],
+ ["2024-01-02", 4900000],
+ ],
+ });
+ expect(dailySparkPoints(rows)).toEqual([5100000, 4900000]);
+ expect(compactCount(10000000)).toBe("10M");
+ });
+
+ // Guards the rounding boundary: the unit is picked after the mantissa
+ // rounds, so a value that rounds to 1000 of the lower unit promotes.
+ it.each([
+ [999499, "999K"],
+ [999500, "1M"],
+ [999999, "1M"],
+ [-999999, "-1M"],
+ [999499999, "999M"],
+ [999500000, "1B"],
+ [999999999, "1B"],
+ ])("formats %d as %s without a four-digit mantissa", (input, expected) => {
+ expect(compactCount(input)).toBe(expected);
+ });
+
+ it("leads a stale flag with the verdict and PostHog's reason", () => {
+ const preview = decorateFlagPreview(
+ {
+ title: "old-flag",
+ detail: "Enabled · Old rollout",
+ facts: ["100% rollout"],
+ },
+ { status: "stale", reason: "Rolled out to 100% for at least 30 days" },
+ [
+ ["2024-01-01", 900000],
+ ["2024-01-02", 1200000],
+ ],
+ );
+ expect(preview.detail).toBe("Rolled out to 100% for at least 30 days");
+ expect(preview.facts).toEqual(["Stale", "100% rollout", "2.1M calls (7d)"]);
+ expect(preview.spark).toEqual({
+ points: [900000, 1200000],
+ render: "line",
+ });
+ });
+
+ it("summarizes variant exposures, dropping boolean noise", () => {
+ expect(
+ exposureFact([
+ ["control", 12400],
+ ["test", 12100],
+ ["false", 900],
+ ]),
+ ).toBe("control 12.4K · test 12.1K");
+ expect(exposureFact([])).toBeNull();
+ });
+
+ it("rolls a trace up to generations, cost, latency, and errors", () => {
+ expect(
+ shapeTracePreview([7, 0.42, 18.3, ["gpt-5", "claude-4"], 2]),
+ ).toEqual({
+ title: "7 generations",
+ facts: ["$0.42", "18.3s", "2 models", "2 errors"],
+ });
+ expect(shapeTracePreview([0, 0, 0, [], 0])).toBeNull();
+ });
+
+ it("adds responses and response rate from survey stats", () => {
+ const preview = decorateSurveyPreview(
+ { title: "Checkout survey", detail: "Running since Jan 3" },
+ {
+ stats: { "survey sent": { total_count: 128 } },
+ rates: { response_rate: 34.4 },
+ },
+ );
+ expect(preview.facts).toEqual(["128 responses", "34% response rate"]);
+ });
+
+ it("describes a running experiment with its day counter and split", () => {
+ const start = new Date(Date.now() - 11.5 * 86_400_000).toISOString();
+ const preview = shapeExperimentPreview({
+ id: 7,
+ name: "Reminder timing",
+ start_date: start,
+ feature_flag_key: "reminder-timing",
+ parameters: {
+ feature_flag_variants: [
+ { key: "control", rollout_percentage: 50 },
+ { key: "test", rollout_percentage: 50 },
+ ],
+ },
+ } as unknown as Schemas.Experiment);
+ expect(preview.detail).toMatch(/· Day 12$/);
+ expect(preview.facts).toEqual([
+ "2 variants (50/50)",
+ "Flag: reminder-timing",
+ ]);
+ });
+
+ it("describes a survey that has not started as a draft", () => {
+ const preview = shapeSurveyPreview({
+ id: "srv-11",
+ name: "Checkout survey",
+ } as Schemas.Survey);
+ expect(preview).toEqual({ title: "Checkout survey", detail: "Draft" });
+ });
+});
diff --git a/products/desktop/packages/api-client/src/evidence-previews.ts b/products/desktop/packages/api-client/src/evidence-previews.ts
new file mode 100644
index 000000000000..1bcfb1265ed9
--- /dev/null
+++ b/products/desktop/packages/api-client/src/evidence-previews.ts
@@ -0,0 +1,464 @@
+// Evidence previews — resolve an `evidence:<kind>/<id>` citation in an agent
+// message to a small live summary of the PostHog object it points at. The
+// citation carries only the reference; names and status are fetched when the
+// preview is shown, so transcripts never embed a stale copy of the data.
+//
+// The per-kind shaping is kept here (pure, unit-tested) so the client method
+// stays a thin "fetch by kind, shape result" dispatch.
+
+import type { Schemas } from "./generated";
+
+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". */
+ detail?: string;
+ /** 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" };
+ /**
+ * 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.
+ */
+ resolvedId?: string;
+}
+
+/** Escape a value for interpolation into a single-quoted HogQL string. */
+export function hogqlEscape(value: string): string {
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+}
+
+/** 87342 -> "87.3K"; keeps small numbers plain. */
+export function compactCount(value: number): string {
+ const abs = Math.abs(value);
+ const format = (scaled: number, suffix: string): string => {
+ const rounded =
+ scaled >= 100 ? Math.round(scaled) : Number(scaled.toFixed(1));
+ return `${rounded}${suffix}`;
+ };
+ // Enter each unit where the one below would round up to 1000 (999_999 ->
+ // "1000K"), so it promotes to the next unit ("1M") instead of showing a
+ // four-digit mantissa.
+ if (abs >= 999.5e6) return format(value / 1e9, "B");
+ if (abs >= 999.5e3) return format(value / 1e6, "M");
+ if (abs >= 1e3) return format(value / 1e3, "K");
+ return Number.isInteger(value) ? String(value) : value.toFixed(1);
+}
+
+export function gridRows(grid: Record<string, unknown>): unknown[][] {
+ return (Array.isArray(grid.results) ? grid.results : []).filter(
+ (row): row is unknown[] => Array.isArray(row),
+ );
+}
+
+function cellNumber(value: unknown): number | null {
+ const parsed = typeof value === "number" ? value : Number(value);
+ return Number.isFinite(parsed) ? parsed : null;
+}
+
+/** (day, count) rows -> sparkline points, oldest first. */
+export function dailySparkPoints(rows: unknown[][]): number[] {
+ return rows.map((row) => cellNumber(row[1]) ?? 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> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function formatDay(iso: string): string {
+ const date = new Date(iso);
+ if (Number.isNaN(date.getTime())) return iso;
+ const sameYear = date.getFullYear() === new Date().getFullYear();
+ return date.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ ...(sameYear ? {} : { year: "numeric" }),
+ });
+}
+
+/** "pending_release" -> "Pending release". */
+function humanizeStatus(status: string): string {
+ const words = status.replace(/_/g, " ");
+ return words.charAt(0).toUpperCase() + words.slice(1);
+}
+
+export function shapeFlagPreview(flag: Schemas.FeatureFlag): EvidencePreview {
+ const state = flag.active ? "Enabled" : "Disabled";
+ const name = flag.name?.trim();
+
+ const facts: string[] = [];
+ const filters = isRecord(flag.filters) ? flag.filters : {};
+ const groups = Array.isArray(filters.groups) ? filters.groups : [];
+ if (groups.length === 1 && isRecord(groups[0])) {
+ const rollout = groups[0].rollout_percentage;
+ if (typeof rollout === "number") facts.push(`${rollout}% rollout`);
+ } else if (groups.length > 1) {
+ facts.push(count(groups.length, "release condition"));
+ }
+ const multivariate = isRecord(filters.multivariate)
+ ? filters.multivariate
+ : null;
+ const variants = Array.isArray(multivariate?.variants)
+ ? multivariate.variants.length
+ : 0;
+ if (variants > 0) facts.push(count(variants, "variant"));
+ if (flag.experiment_set?.length) {
+ facts.push(`Used by ${count(flag.experiment_set.length, "experiment")}`);
+ }
+
+ return {
+ title: flag.key,
+ detail: name ? `${state} · ${name}` : state,
+ facts,
+ resolvedId: String(flag.id),
+ };
+}
+
+export function shapeExperimentPreview(
+ experiment: Schemas.Experiment,
+): EvidencePreview {
+ let detail: string;
+ if (experiment.end_date) {
+ detail = `Ended ${formatDay(experiment.end_date)}`;
+ } else if (experiment.start_date) {
+ 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}`;
+ } else {
+ detail = "Draft";
+ }
+
+ const facts: string[] = [];
+ const parameters: Record<string, unknown> = isRecord(experiment.parameters)
+ ? experiment.parameters
+ : {};
+ 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})`);
+ }
+ if (experiment.feature_flag_key) {
+ facts.push(`Flag: ${experiment.feature_flag_key}`);
+ }
+ const primaryMetric = experiment.saved_metrics?.find(
+ (metric) => typeof metric.name === "string" && metric.name,
+ );
+ if (primaryMetric) facts.push(`Metric: ${primaryMetric.name}`);
+ return { title: experiment.name, detail, facts };
+}
+
+const EVALUATION_TYPE_LABELS: Record<string, string> = {
+ llm_judge: "LLM judge",
+ hog: "Hog",
+ sentiment: "Sentiment",
+};
+
+export function shapeEvaluationPreview(
+ evaluation: Schemas.Evaluation,
+): EvidencePreview {
+ const state = evaluation.enabled ? "Enabled" : "Disabled";
+ const reason = evaluation.status_reason?.trim();
+ const typeLabel =
+ EVALUATION_TYPE_LABELS[String(evaluation.evaluation_type)] ??
+ String(evaluation.evaluation_type);
+ return {
+ title: evaluation.name,
+ detail: reason ? `${state} · ${reason}` : state,
+ facts: [typeLabel],
+ };
+}
+
+/** (variant, unique persons) rows -> "control 12.4K · test 12.1K". */
+export function exposureFact(rows: unknown[][]): string | null {
+ const parts = rows
+ .filter((row) => typeof row[0] === "string" && row[0] !== "false")
+ .slice(0, 4)
+ .map((row) => `${row[0]} ${compactCount(Number(row[1]) || 0)}`);
+ return parts.length > 0 ? parts.join(" · ") : null;
+}
+
+/**
+ * Fold the status check and 7-day call volume into a flag preview. A stale
+ * flag leads with that verdict: PostHog's reason ("rolled out to 100% for 30+
+ * days") replaces the name echo because it says what to do about the flag.
+ */
+export function decorateFlagPreview(
+ preview: EvidencePreview,
+ status: Schemas.FeatureFlagStatusResponse | null,
+ volumeRows: unknown[][],
+): EvidencePreview {
+ const facts = [...(preview.facts ?? [])];
+ let detail = preview.detail;
+ if (status?.status?.toLowerCase() === "stale") {
+ facts.unshift("Stale");
+ 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)`);
+ return {
+ ...preview,
+ detail,
+ facts,
+ spark: points.length > 1 ? { points, render: "line" } : undefined,
+ };
+}
+
+/** One-line trace rollup from the aggregate row over its generations. */
+export function shapeTracePreview(row: unknown[]): EvidencePreview | null {
+ const generations = Number(row?.[0]) || 0;
+ if (generations <= 0) return null;
+ const facts: string[] = [];
+ const cost = Number(row[1]);
+ if (Number.isFinite(cost) && cost > 0) facts.push(`$${cost}`);
+ const latency = Number(row[2]);
+ if (Number.isFinite(latency) && latency > 0) facts.push(`${latency}s`);
+ const models = Array.isArray(row[3])
+ ? row[3].filter((m): m is string => typeof m === "string" && m !== "")
+ : [];
+ if (models.length === 1) facts.push(models[0]);
+ 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 };
+}
+
+/** Fold `surveys/{id}/stats/` into a survey preview: responses and rate. */
+export function decorateSurveyPreview(
+ preview: EvidencePreview,
+ stats: Record<string, unknown> | null,
+): EvidencePreview {
+ if (!stats) return preview;
+ const facts = [...(preview.facts ?? [])];
+ const byEvent = isRecord(stats.stats) ? stats.stats : {};
+ const sent = isRecord(byEvent["survey sent"])
+ ? Number(byEvent["survey sent"].total_count)
+ : Number.NaN;
+ if (Number.isFinite(sent)) facts.push(count(sent, "response"));
+ const rates = isRecord(stats.rates) ? stats.rates : {};
+ const responseRate = Number(rates.response_rate);
+ if (Number.isFinite(responseRate) && responseRate > 0) {
+ facts.push(`${Math.round(responseRate)}% response rate`);
+ }
+ return { ...preview, facts };
+}
+
+export function shapeErrorIssuePreview(
+ issue: Schemas.ErrorTrackingIssueFull,
+): EvidencePreview {
+ const firstSeen = `First seen ${formatDay(issue.first_seen)}`;
+ return {
+ title: issue.name || "Untitled issue",
+ detail: issue.status
+ ? `${humanizeStatus(issue.status)} · ${firstSeen}`
+ : firstSeen,
+ };
+}
+
+export function shapeRecordingPreview(
+ recording: Schemas.SessionRecording,
+): EvidencePreview {
+ const person =
+ recording.person?.name ||
+ recording.person?.distinct_ids?.[0] ||
+ recording.distinct_id;
+ const duration =
+ recording.recording_duration >= 60
+ ? `${Math.round(recording.recording_duration / 60)} min`
+ : `${Math.round(recording.recording_duration)}s`;
+ const parts = [duration];
+ if (recording.start_time) parts.push(formatDay(recording.start_time));
+
+ const facts: string[] = [];
+ if (
+ typeof recording.active_seconds === "number" &&
+ recording.active_seconds >= 60 &&
+ recording.active_seconds < recording.recording_duration
+ ) {
+ facts.push(`${Math.round(recording.active_seconds / 60)} min active`);
+ }
+ if (typeof recording.click_count === "number" && recording.click_count > 0) {
+ facts.push(count(recording.click_count, "click"));
+ }
+ if (
+ typeof recording.console_error_count === "number" &&
+ recording.console_error_count > 0
+ ) {
+ facts.push(count(recording.console_error_count, "console error"));
+ }
+ if (recording.start_url) {
+ try {
+ const url = new URL(recording.start_url);
+ facts.push(`${url.host}${url.pathname === "/" ? "" : url.pathname}`);
+ } catch {
+ // Not a parsable URL; skip the fact rather than show garbage.
+ }
+ }
+
+ return {
+ title: person ? `Session by ${person}` : "Session recording",
+ detail: parts.join(" · "),
+ facts,
+ };
+}
+
+export function shapeDashboardPreview(
+ dashboard: Schemas.Dashboard,
+): EvidencePreview {
+ // Tile names say what the dashboard covers; the count only says how big.
+ const facts: string[] = [];
+ const tiles = Array.isArray(dashboard.tiles) ? dashboard.tiles : [];
+ const names = tiles
+ .map((tile) =>
+ isRecord(tile) && isRecord(tile.insight) ? tile.insight.name : null,
+ )
+ .filter((name): name is string => typeof name === "string" && name !== "");
+ if (names.length > 0) {
+ const shown = names.slice(0, 3);
+ facts.push(...shown);
+ // Count from what we showed, not from tiles.length: unnamed tiles are
+ // filtered out of names, so a fixed -3 undercounts the remainder.
+ const remaining = tiles.length - shown.length;
+ if (remaining > 0) facts.push(`+${remaining} more`);
+ } else if (Array.isArray(dashboard.tiles)) {
+ facts.push(count(tiles.length, "tile"));
+ }
+ return {
+ title: dashboard.name || "Untitled dashboard",
+ detail: dashboard.description || undefined,
+ facts,
+ };
+}
+
+export function shapeCohortPreview(cohort: Schemas.Cohort): EvidencePreview {
+ const detail =
+ typeof cohort.count === "number"
+ ? count(cohort.count, "person", "people")
+ : cohort.description || undefined;
+ return {
+ title: cohort.name || "Untitled cohort",
+ detail,
+ facts: [cohort.is_static ? "Static" : "Dynamic"],
+ };
+}
+
+export function shapeActionPreview(action: Schemas.Action): EvidencePreview {
+ return {
+ title: action.name || "Untitled action",
+ detail: action.description || undefined,
+ facts: action.steps?.length
+ ? [count(action.steps.length, "match step")]
+ : undefined,
+ };
+}
+
+export function shapeTicketPreview(ticket: Schemas.Ticket): EvidencePreview {
+ const status = ticket.status ? humanizeStatus(ticket.status) : null;
+ const priority =
+ typeof ticket.priority === "string" && ticket.priority
+ ? humanizeStatus(ticket.priority)
+ : null;
+ const channel = ticket.channel_source
+ ? humanizeStatus(String(ticket.channel_source))
+ : null;
+
+ const facts: string[] = [];
+ const statusLine = [status, priority, channel].filter(Boolean).join(" · ");
+ if (statusLine) facts.push(statusLine);
+ if (typeof ticket.message_count === "number") {
+ const messages = count(ticket.message_count, "message");
+ facts.push(
+ ticket.last_message_at
+ ? `${messages} · last reply ${formatDay(ticket.last_message_at)}`
+ : messages,
+ );
+ }
+ const assignedUser = isRecord(ticket.assignee) ? ticket.assignee.user : null;
+ if (assignedUser) {
+ const name =
+ assignedUser.name ||
+ [assignedUser.first_name, assignedUser.last_name]
+ .filter(Boolean)
+ .join(" ") ||
+ assignedUser.email;
+ if (name) facts.push(`Assigned to ${name}`);
+ }
+
+ const snippet = ticket.last_message_text?.trim();
+ return {
+ title: ticket.email_subject?.trim() || `Ticket #${ticket.ticket_number}`,
+ detail: snippet
+ ? `“${snippet.length > 120 ? `${snippet.slice(0, 120)}…` : snippet}”`
+ : undefined,
+ facts,
+ };
+}
+
+export function shapePersonPreview(
+ person: Schemas.PersonRecord,
+): EvidencePreview {
+ const properties = isRecord(person.properties) ? person.properties : {};
+ const email = typeof properties.email === "string" ? properties.email : null;
+ const title = person.name?.trim() || email || "Anonymous person";
+
+ const parts: string[] = [];
+ if (person.last_seen_at) {
+ parts.push(`Last seen ${formatDay(person.last_seen_at)}`);
+ }
+ if (person.created_at) {
+ parts.push(`First seen ${formatDay(person.created_at)}`);
+ }
+ const facts: string[] = [];
+ if (email && email !== title) facts.push(email);
+ const country = properties.$geoip_country_name;
+ if (typeof country === "string" && country) facts.push(country);
+ const browser = properties.$browser;
+ if (typeof browser === "string" && browser) facts.push(browser);
+ return {
+ title,
+ detail: parts.join(" · ") || undefined,
+ facts,
+ resolvedId: person.uuid,
+ };
+}
+
+export function shapeEventDefinitionPreview(
+ definition: Schemas.EventDefinitionRecord,
+): EvidencePreview {
+ return {
+ title: definition.name,
+ detail: definition.last_seen_at
+ ? `Last seen ${formatDay(definition.last_seen_at)}`
+ : undefined,
+ resolvedId: definition.id,
+ };
+}
+
+export function shapeSurveyPreview(survey: Schemas.Survey): EvidencePreview {
+ let detail: string;
+ if (survey.end_date) {
+ detail = `Ended ${formatDay(survey.end_date)}`;
+ } else if (survey.start_date) {
+ detail = `Running since ${formatDay(survey.start_date)}`;
+ } else {
+ detail = "Draft";
+ }
+ return { title: survey.name, detail };
+}
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index a218a8fef4c3..25dd9bef57a9 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -116,6 +116,29 @@ import {
type HogQLGrid,
shapeAgentAnalytics,
} from "./agent-analytics";
+import {
+ compactCount,
+ dailySparkPoints,
+ decorateFlagPreview,
+ decorateSurveyPreview,
+ type EvidencePreview,
+ exposureFact,
+ gridRows,
+ hogqlEscape,
+ shapeActionPreview,
+ shapeCohortPreview,
+ shapeDashboardPreview,
+ shapeErrorIssuePreview,
+ shapeEvaluationPreview,
+ shapeEventDefinitionPreview,
+ shapeExperimentPreview,
+ shapeFlagPreview,
+ shapePersonPreview,
+ shapeRecordingPreview,
+ shapeSurveyPreview,
+ shapeTicketPreview,
+ shapeTracePreview,
+} from "./evidence-previews";
import {
ApiRequestError,
buildApiFetcher,
@@ -7039,6 +7062,264 @@ export class PostHogAPIClient {
return data;
}
+ /**
+ * The insight's identity and query node, by short id. Backs saved-insight
+ * chart cards in agent messages: the caller plans and runs the query.
+ */
+ async getInsightDefinition(shortId: string): Promise<{
+ name: string | null;
+ description: string | null;
+ query: unknown;
+ } | 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,
+ };
+ }
+
+ /**
+ * Resolves an `evidence:<kind>/<id>` citation from an agent message to a
+ * small live summary of the object it points at. Returns null for kinds
+ * without a lookup and for ids that don't resolve, so the caller can fall
+ * back to a static reference. Query-backed kinds (hogql, insight) resolve
+ * in the UI instead, where chart shaping lives.
+ */
+ async getEvidencePreview(
+ kind: string,
+ id: string,
+ ): Promise<EvidencePreview | null> {
+ const projectId = (await this.getTeamId()).toString();
+ const numericId = /^\d+$/.test(id) ? Number(id) : null;
+
+ switch (kind) {
+ case "flag": {
+ let flag: Schemas.FeatureFlag | undefined;
+ if (numericId !== null) {
+ flag = await this.api.get(
+ "/api/projects/{project_id}/feature_flags/{id}/",
+ { path: { project_id: projectId, id: numericId } },
+ );
+ } else {
+ // Agents often cite flags by key; the API only retrieves by
+ // numeric id, so find the exact key through the list search.
+ const page = await this.api.get(
+ "/api/projects/{project_id}/feature_flags/",
+ { path: { project_id: projectId }, query: { search: id } },
+ );
+ flag = page.results.find((entry) => entry.key === id);
+ }
+ if (!flag) return null;
+ // Depth: PostHog's own staleness verdict, and whether anything still
+ // evaluates the flag (7-day call volume).
+ const [status, volume] = await Promise.all([
+ this.api
+ .get("/api/projects/{project_id}/feature_flags/{id}/status/", {
+ path: { project_id: projectId, id: flag.id },
+ })
+ .catch(() => null),
+ this.runQuery({
+ kind: "HogQLQuery",
+ query: `SELECT toDate(timestamp) AS day, count() FROM events WHERE event = '$feature_flag_called' AND properties.$feature_flag = '${hogqlEscape(flag.key)}' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY day ORDER BY day`,
+ }).catch(() => ({})),
+ ]);
+ return decorateFlagPreview(
+ shapeFlagPreview(flag),
+ status,
+ gridRows(volume),
+ );
+ }
+ case "experiment": {
+ if (numericId === null) return null;
+ const experiment = await this.api.get(
+ "/api/projects/{project_id}/experiments/{id}/",
+ { path: { project_id: projectId, id: numericId } },
+ );
+ const preview = shapeExperimentPreview(experiment);
+ // Depth: unique persons exposed per variant, showing the experiment
+ // is collecting and roughly balanced.
+ if (!experiment.start_date || !experiment.feature_flag_key) {
+ return preview;
+ }
+ const until = experiment.end_date
+ ? ` AND timestamp <= parseDateTimeBestEffort('${hogqlEscape(experiment.end_date)}')`
+ : "";
+ const 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 fact = exposureFact(gridRows(exposures));
+ return fact
+ ? { ...preview, facts: [...(preview.facts ?? []), fact] }
+ : preview;
+ }
+ case "error": {
+ // The issue's identity plus its 30-day activity: total events, users
+ // affected, and a daily-occurrence spark answering "still firing?".
+ const scope = `event = '$exception' AND properties.$exception_issue_id = '${hogqlEscape(id)}' AND timestamp >= now() - INTERVAL 30 DAY`;
+ const [issue, totals, daily] = await Promise.all([
+ this.api.get(
+ "/api/environments/{project_id}/error_tracking/issues/{id}/",
+ { path: { project_id: projectId, id } },
+ ),
+ this.runQuery({
+ kind: "HogQLQuery",
+ query: `SELECT count(), uniq(person_id) FROM events WHERE ${scope}`,
+ }).catch(() => ({})),
+ this.runQuery({
+ kind: "HogQLQuery",
+ query: `SELECT toDate(timestamp) AS day, count() FROM events WHERE ${scope} GROUP BY day ORDER BY day`,
+ }).catch(() => ({})),
+ ]);
+ const preview = shapeErrorIssuePreview(issue);
+ const totalRow = gridRows(totals)[0];
+ const facts = [...(preview.facts ?? [])];
+ const users = totalRow ? Number(totalRow[1]) : 0;
+ const events = totalRow ? Number(totalRow[0]) : 0;
+ if (Number.isFinite(users) && users > 0) {
+ facts.unshift(
+ `${compactCount(users)} users · ${compactCount(events)} events (30d)`,
+ );
+ }
+ const points = dailySparkPoints(gridRows(daily));
+ return {
+ ...preview,
+ facts,
+ spark:
+ points.length > 1 ? { points, render: "bar" as const } : undefined,
+ };
+ }
+ case "event": {
+ // Verify the event against its definition (also yields the id that
+ // makes the reference clickable), then chart its 14-day volume.
+ const definition = await this.api
+ .get("/api/projects/{project_id}/event_definitions/by_name/", {
+ path: { project_id: projectId },
+ query: { name: id },
+ })
+ .catch(() => null);
+ if (!definition) return null;
+ const volume = await this.runQuery({
+ kind: "HogQLQuery",
+ 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 total = points.reduce((sum, value) => sum + value, 0);
+ return {
+ ...preview,
+ facts:
+ total > 0 ? [`${compactCount(total)} events (14d)`] : undefined,
+ spark:
+ points.length > 1 ? { points, render: "line" as const } : undefined,
+ };
+ }
+ case "ticket": {
+ const ticket = await this.api.get(
+ "/api/projects/{project_id}/conversations/tickets/{id}/",
+ { path: { project_id: projectId, id } },
+ );
+ return shapeTicketPreview(ticket);
+ }
+ case "person": {
+ const page = await this.api.get("/api/projects/{project_id}/persons/", {
+ path: { project_id: projectId },
+ query: { search: id },
+ });
+ const person = page.results?.[0];
+ return person ? shapePersonPreview(person) : null;
+ }
+ case "replay": {
+ const recording = await this.api.get(
+ "/api/projects/{project_id}/session_recordings/{id}/",
+ { path: { project_id: projectId, id } },
+ );
+ return shapeRecordingPreview(recording);
+ }
+ case "survey": {
+ const [survey, stats] = await Promise.all([
+ this.api.get("/api/projects/{project_id}/surveys/{id}/", {
+ path: { project_id: projectId, id },
+ }),
+ this.api
+ .get("/api/projects/{project_id}/surveys/{id}/stats/", {
+ path: { project_id: projectId, id },
+ query: {},
+ })
+ .catch(() => null),
+ ]);
+ return decorateSurveyPreview(
+ shapeSurveyPreview(survey),
+ stats as Record<string, unknown> | null,
+ );
+ }
+ case "trace": {
+ const rollup = await this.runQuery({
+ kind: "HogQLQuery",
+ query: `SELECT count(), round(sum(toFloat(properties.$ai_total_cost_usd)), 3), round(sum(toFloat(properties.$ai_latency)), 1), groupUniqArray(properties.$ai_model), countIf(toString(properties.$ai_is_error) IN ('true', '1')) FROM events WHERE event IN ('$ai_generation', '$ai_embedding') AND properties.$ai_trace_id = '${hogqlEscape(id)}'`,
+ });
+ const row = gridRows(rollup)[0];
+ return row ? shapeTracePreview(row) : null;
+ }
+ case "dashboard": {
+ if (numericId === null) return null;
+ const dashboard = await this.api.get(
+ "/api/projects/{project_id}/dashboards/{id}/",
+ { path: { project_id: projectId, id: numericId }, query: {} },
+ );
+ return shapeDashboardPreview(dashboard);
+ }
+ case "cohort": {
+ if (numericId === null) return null;
+ const cohort = await this.api.get(
+ "/api/projects/{project_id}/cohorts/{id}/",
+ { path: { project_id: projectId, id: numericId } },
+ );
+ return shapeCohortPreview(cohort);
+ }
+ case "action": {
+ if (numericId === null) return null;
+ const [action, volume] = await Promise.all([
+ this.api.get("/api/projects/{project_id}/actions/{id}/", {
+ path: { project_id: projectId, id: numericId },
+ query: {},
+ }),
+ this.runQuery({
+ 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(() => ({})),
+ ]);
+ const preview = shapeActionPreview(action);
+ const points = dailySparkPoints(gridRows(volume));
+ const total = points.reduce((sum, value) => sum + value, 0);
+ const facts = [...(preview.facts ?? [])];
+ if (total > 0) facts.unshift(`${compactCount(total)} matches (14d)`);
+ return {
+ ...preview,
+ facts,
+ spark:
+ points.length > 1 ? { points, render: "line" as const } : undefined,
+ };
+ }
+ case "eval": {
+ const evaluation = await this.api.get(
+ "/api/environments/{project_id}/evaluations/{id}/",
+ { path: { project_id: projectId, id } },
+ );
+ return shapeEvaluationPreview(evaluation);
+ }
+ default:
+ return null;
+ }
+ }
+
/**
* Agent observability rollup over the agents' `$ai_*` events — KPIs (spend,
* sessions, failure rate, p95), a 14-day daily trend + WoW deltas, and
diff --git a/products/desktop/packages/core/src/inbox/reportCharts.test.ts b/products/desktop/packages/core/src/inbox/reportCharts.test.ts
index b6b4c4e0d498..837b548bc850 100644
--- a/products/desktop/packages/core/src/inbox/reportCharts.test.ts
+++ b/products/desktop/packages/core/src/inbox/reportCharts.test.ts
@@ -1,6 +1,7 @@
import type { SignalReportChartSize } from "@posthog/shared/types";
import { describe, expect, it } from "vitest";
import {
+ chartHeadlineStat,
planReportChart,
type ReportChartData,
type ReportChartPlan,
@@ -168,6 +169,52 @@ describe("reportCharts", () => {
});
});
+ it("sorts a descending-date HogQL grid so the headline reads the latest bucket", () => {
+ const data = shapeReportChartData(
+ {
+ columns: ["day", "errors"],
+ results: [
+ ["2026-08-03", 30],
+ ["2026-08-02", 20],
+ ["2026-08-01", 10],
+ ],
+ },
+ runPlan(hogqlNode({ display: "ActionsLineGraph" })),
+ );
+ expect(data).toMatchObject({
+ type: "series",
+ isTimeSeries: true,
+ labels: ["2026-08-01", "2026-08-02", "2026-08-03"],
+ series: [{ label: "errors", data: [10, 20, 30] }],
+ });
+ // The latest bucket is 30 (up from 20), not the first row's 10.
+ expect(chartHeadlineStat(data)).toMatchObject({
+ value: "30",
+ delta: { direction: "up" },
+ });
+ });
+
+ it("sorts an out-of-order breakdown grid before pivoting", () => {
+ const data = shapeReportChartData(
+ {
+ columns: ["day", "browser", "count"],
+ results: [
+ ["2026-08-02", "Chrome", 7],
+ ["2026-08-01", "Chrome", 5],
+ ["2026-08-01", "Safari", 2],
+ ],
+ },
+ runPlan(hogqlNode({ display: "ActionsBar" })),
+ );
+ expect(data).toMatchObject({
+ labels: ["2026-08-01", "2026-08-02"],
+ series: [
+ { label: "Chrome", data: [5, 7] },
+ { label: "Safari", data: [2, 0] },
+ ],
+ });
+ });
+
it("keeps a categorical grid as a bar chart with string labels", () => {
const data = shapeReportChartData(
{
@@ -194,6 +241,39 @@ describe("reportCharts", () => {
["total"],
{ type: "number", value: 42 },
],
+ [
+ "a date-keyed grid becomes a line chart",
+ [
+ ["2026-08-08", 4957305],
+ ["2026-08-09", 5103586],
+ ],
+ ["day", "active_users"],
+ { type: "series", render: "line", isTimeSeries: true },
+ ],
+ [
+ "a short category-keyed grid becomes a bar chart",
+ [
+ ["$pageview", 7848625],
+ ["$autocapture", 11150213],
+ ],
+ ["event", "events"],
+ { type: "series", render: "bar", isTimeSeries: false },
+ ],
+ [
+ "a date+breakdown grid pivots into a multi-series line",
+ [
+ ["2026-08-01", "Chrome", 5],
+ ["2026-08-02", "Chrome", 7],
+ ],
+ ["day", "browser", "count"],
+ { type: "series", render: "line", isTimeSeries: true },
+ ],
+ [
+ "a single data row stays a table",
+ [["granted", 12]],
+ ["scope", "count"],
+ { type: "table" },
+ ],
[
"non-numeric grid falls back to a table",
[["a", "b"]],
@@ -206,6 +286,32 @@ describe("reportCharts", () => {
).toMatchObject(expected);
});
+ it("auto display: too many categories for a readable bar stays a table", () => {
+ const results = Array.from({ length: 31 }, (_, i) => [`cat-${i}`, i]);
+ expect(
+ shapeReportChartData(
+ { columns: ["name", "count"], results },
+ runPlan(hogqlNode()),
+ ),
+ ).toMatchObject({ type: "table" });
+ });
+
+ it("auto display: a numeric grid wider than the series cap stays a table", () => {
+ // 16 numeric metrics past the date key exceed the 15-series cap; plotting
+ // would silently drop columns, so keep the full grid as a table.
+ const columns = [
+ "day",
+ ...Array.from({ length: 16 }, (_, i) => `m${i + 1}`),
+ ];
+ const results = [
+ ["2026-08-01", ...Array.from({ length: 16 }, (_, i) => i)],
+ ["2026-08-02", ...Array.from({ length: 16 }, (_, i) => i + 1)],
+ ];
+ expect(
+ shapeReportChartData({ columns, results }, runPlan(hogqlNode())),
+ ).toMatchObject({ type: "table", columns });
+ });
+
it("returns empty for a response with no rows", () => {
expect(
shapeReportChartData({ columns: [], results: [] }, runPlan(hogqlNode())),
@@ -289,4 +395,59 @@ describe("reportCharts", () => {
])("returns null when there is nowhere to link: %s", (_name, query) => {
expect(reportChartOpenTarget(query, OPEN_OPTS)).toBeNull();
});
+
+ const headlineSeries = (
+ points: number[][],
+ isTimeSeries = true,
+ ): ReportChartData => ({
+ type: "series",
+ render: "line",
+ labels: points[0].map((_, i) => `d${i}`),
+ series: points.map((data, i) => ({ key: `${i}`, label: `s${i}`, data })),
+ isTimeSeries,
+ interval: "day",
+ });
+
+ it("headlines a single series with its latest value and step change", () => {
+ expect(chartHeadlineStat(headlineSeries([[69650, 77400, 17100]]))).toEqual({
+ value: "17.1K",
+ delta: { label: "78%", direction: "down" },
+ });
+ });
+
+ it.each([
+ [0.04, "0.04"],
+ [0.004, "0.004"],
+ [-0.04, "-0.04"],
+ [999.96, "1K"],
+ [999999, "1M"],
+ [999999999, "1B"],
+ ])(
+ "keeps a small nonzero headline visible and promotes at the unit boundary (%d -> %s)",
+ (last, expected) => {
+ expect(chartHeadlineStat(headlineSeries([[last]]))?.value).toBe(expected);
+ },
+ );
+
+ it.each([
+ [
+ "a categorical chart has no latest value",
+ headlineSeries([[1, 2, 3]], false),
+ ],
+ [
+ "multiple series have no one honest headline",
+ headlineSeries([
+ [1, 2],
+ [3, 4],
+ ]),
+ ],
+ ["empty series", headlineSeries([[]])],
+ ["non-series data", { type: "number", value: 5 } as ReportChartData],
+ ])("returns no headline for %s", (_name, data) => {
+ expect(chartHeadlineStat(data)).toBeNull();
+ });
+
+ it("hides a step change too small to read as a trend", () => {
+ expect(chartHeadlineStat(headlineSeries([[1000, 1002]]))?.delta).toBeNull();
+ });
});
diff --git a/products/desktop/packages/core/src/inbox/reportCharts.ts b/products/desktop/packages/core/src/inbox/reportCharts.ts
index b50e8dc4e93f..0dadc19b501e 100644
--- a/products/desktop/packages/core/src/inbox/reportCharts.ts
+++ b/products/desktop/packages/core/src/inbox/reportCharts.ts
@@ -98,8 +98,77 @@ export type ReportChartData =
| { type: "table"; columns: string[]; rows: unknown[][] }
| { type: "empty" };
+/** 87342 -> "87.3K"; keeps small numbers plain without reading a nonzero value as 0. */
+function compactChartValue(value: number): string {
+ const abs = Math.abs(value);
+ const format = (scaled: number, suffix: string): string => {
+ const rounded =
+ scaled >= 100 ? Math.round(scaled) : Number(scaled.toFixed(1));
+ return `${rounded}${suffix}`;
+ };
+ // Enter each unit where the one below would round up to 1000 at its display
+ // precision, so a value never shows a four-digit mantissa ("1000K" -> "1M").
+ if (abs >= 999.5e6) return format(value / 1e9, "B");
+ if (abs >= 999.5e3) return format(value / 1e6, "M");
+ if (abs >= 999.95) return format(value / 1e3, "K");
+ if (Number.isInteger(value)) return String(value);
+ // A small nonzero value must not read as "0.0" beside a delta chip; when one
+ // decimal rounds to zero, fall back to two significant figures (0.04, 0.004).
+ const oneDecimal = value.toFixed(1);
+ return Number.parseFloat(oneDecimal) === 0
+ ? `${Number(value.toPrecision(2))}`
+ : oneDecimal;
+}
+
+export interface ChartHeadlineStat {
+ /** Latest value of the series, compact ("17.1K"). */
+ value: string;
+ /** Change against the previous point; null when too small to show. */
+ delta: { label: string; direction: "up" | "down" } | null;
+}
+
+/** Changes under this read as noise on a headline, not a trend. */
+const MIN_DELTA_PCT = 0.5;
+
+/**
+ * Headline for a chart card: the latest value and its step change. Only a
+ * single-series chart has one honest headline; anything else returns null.
+ */
+export function chartHeadlineStat(
+ data: ReportChartData,
+): ChartHeadlineStat | null {
+ // "Latest value and step change" only reads honestly on a single time
+ // series; categorical bars have no "latest" and no meaningful step.
+ if (
+ data.type !== "series" ||
+ !data.isTimeSeries ||
+ data.series.length !== 1
+ ) {
+ return null;
+ }
+ const points = data.series[0].data;
+ const last = points[points.length - 1];
+ if (typeof last !== "number" || !Number.isFinite(last)) return null;
+ const previous = points.length > 1 ? points[points.length - 2] : null;
+ let delta: ChartHeadlineStat["delta"] = null;
+ if (
+ typeof previous === "number" &&
+ Number.isFinite(previous) &&
+ previous !== 0
+ ) {
+ const pct = ((last - previous) / Math.abs(previous)) * 100;
+ if (Math.abs(pct) >= MIN_DELTA_PCT) {
+ const label = `${Math.abs(pct) >= 10 ? Math.round(Math.abs(pct)) : Math.abs(pct).toFixed(1)}%`;
+ delta = { label, direction: pct >= 0 ? "up" : "down" };
+ }
+ }
+ return { value: compactChartValue(last), delta };
+}
+
const MAX_SERIES = 15;
const MAX_TABLE_ROWS = 100;
+// Past this many categories a bar chart is unreadable; a table serves better.
+const MAX_BAR_CATEGORIES = 30;
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
const DATE_TIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}/;
@@ -246,18 +315,50 @@ function shapeHogQLResponse(
: asTable(rows, columns);
}
- if (render === "line" || render === "bar") {
- const firstColumnDates = rows.every((row) => isDateLike(row[0]));
- const width = rows[0].length;
- const numericTail = (row: unknown[]): boolean =>
- row.slice(1).every((cell) => asFiniteNumber(cell) !== null);
+ const firstColumnDates = rows.every((row) => isDateLike(row[0]));
+ const width = rows[0].length;
+ const numericTail = (row: unknown[]): boolean =>
+ row.slice(1).every((cell) => asFiniteNumber(cell) !== null);
+
+ // Infer the chart for "auto" the way the SQL editor's visualization does:
+ // a date-keyed grid is a time series, a short category-keyed grid of
+ // numbers is a bar chart, anything else stays a table.
+ let effectiveRender = render;
+ if (render === "auto" && rows.length >= 2) {
+ // A grid wider than MAX_SERIES would lose its extra columns to the series
+ // cap below, so keep it a table rather than plot a partial chart, the way
+ // pivotBreakdownGrid already falls back for too many breakdowns.
+ const chartable =
+ (rows.every(numericTail) && width - 1 <= MAX_SERIES) ||
+ (width === 3 && firstColumnDates && !numericTail(rows[0]));
+ if (chartable && firstColumnDates) {
+ effectiveRender = "line";
+ } else if (chartable && width >= 2 && rows.length <= MAX_BAR_CATEGORIES) {
+ effectiveRender = "bar";
+ }
+ }
- if (width === 3 && firstColumnDates && !numericTail(rows[0])) {
- const pivoted = pivotBreakdownGrid(rows, columns);
- if (pivoted && rows.every((row) => asFiniteNumber(row[2]) !== null)) {
+ if (effectiveRender === "line" || effectiveRender === "bar") {
+ // A time series has to plot oldest -> newest, but a HogQL result can arrive
+ // in any order (ClickHouse GROUP BY with no ORDER BY, or ORDER BY ... DESC).
+ // Sort date-keyed rows chronologically so the chart, sparkline, and headline
+ // all read the true latest bucket; categorical grids keep the query's order.
+ const chartRows = firstColumnDates
+ ? [...rows].sort((a, b) => {
+ const x = String(a[0]);
+ const y = String(b[0]);
+ return x < y ? -1 : x > y ? 1 : 0;
+ })
+ : rows;
+ if (width === 3 && firstColumnDates && !numericTail(chartRows[0])) {
+ const pivoted = pivotBreakdownGrid(chartRows, columns);
+ if (
+ pivoted &&
+ chartRows.every((row) => asFiniteNumber(row[2]) !== null)
+ ) {
return {
type: "series",
- render,
+ render: effectiveRender,
labels: pivoted.labels,
series: pivoted.series,
isTimeSeries: true,
@@ -265,16 +366,16 @@ function shapeHogQLResponse(
};
}
}
- if (width >= 2 && rows.every(numericTail)) {
- const labels = normalizeDayLabels(rows.map((row) => String(row[0])));
+ if (width >= 2 && chartRows.every(numericTail)) {
+ const labels = normalizeDayLabels(chartRows.map((row) => String(row[0])));
const series = columns.slice(1, 1 + MAX_SERIES).map((column, index) => ({
key: `column-${index}`,
label: column || `Series ${index + 1}`,
- data: rows.map((row) => asFiniteNumber(row[index + 1]) ?? 0),
+ data: chartRows.map((row) => asFiniteNumber(row[index + 1]) ?? 0),
}));
return {
type: "series",
- render,
+ render: effectiveRender,
labels,
series,
isTimeSeries: firstColumnDates,
diff --git a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.stories.tsx b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.stories.tsx
new file mode 100644
index 000000000000..637e288262ae
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.stories.tsx
@@ -0,0 +1,162 @@
+import {
+ EvidenceHoverCard,
+ EvidenceRefChip,
+} from "@posthog/ui/features/editor/components/EvidenceRefChip";
+import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+
+const meta: Meta<typeof EvidenceRefChip> = {
+ title: "Features/Editor/EvidenceRefChip",
+ component: EvidenceRefChip,
+ parameters: {
+ layout: "padded",
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof EvidenceRefChip>;
+
+export const AllKinds: Story = {
+ render: () => (
+ <div className="flex max-w-md flex-col items-start gap-2 text-[13px]">
+ <EvidenceRefChip target={{ kind: "insight", id: "9pQx3" }}>
+ Checkout funnel
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "dashboard", id: "12" }}>
+ Growth dashboard
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "error", id: "018f44aa-9c2b" }}>
+ CouponValidator TypeError
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "replay", id: "s_01HQ4K" }}>
+ 14 rageclick recordings
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "flag", id: "new-checkout-flow" }}>
+ new-checkout-flow
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "experiment", id: "42" }}>
+ Reminder timing experiment
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "survey", id: "srv_11" }}>
+ Checkout survey verbatims
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "ticket", id: "conv_88" }}>
+ 9 “coupon” tickets
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "trace", id: "t_9f2ab4" }}>
+ Slow generation traces
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "eval", id: "ev_faith" }}>
+ Faithfulness eval
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "event", id: "cart_saved" }}>
+ cart_saved events
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "cohort", id: "31" }}>
+ Power users cohort
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "action", id: "5" }}>
+ Clicked upgrade action
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "person", id: "0192-aaaa" }}>
+ the affected user
+ </EvidenceRefChip>
+ <EvidenceRefChip target={{ kind: "something-new", id: "x1" }}>
+ Unknown kind falls back
+ </EvidenceRefChip>
+ </div>
+ ),
+};
+
+/**
+ * The hover card resolves the object live when opened. These stories render
+ * the card itself in each state: loading, resolved, and the static fallback
+ * when nothing can be fetched.
+ */
+export const HoverCardStates: Story = {
+ render: () => (
+ <div className="flex flex-wrap items-start gap-4">
+ <div className="rounded-md border border-(--gray-a5) bg-(--color-panel-solid)">
+ <EvidenceHoverCard
+ target={{ kind: "insight", id: "9pQx3" }}
+ url={null}
+ preview={undefined}
+ >
+ Checkout funnel
+ </EvidenceHoverCard>
+ </div>
+ <div className="rounded-md border border-(--gray-a5) bg-(--color-panel-solid)">
+ <EvidenceHoverCard
+ target={{ kind: "insight", id: "9pQx3" }}
+ url="https://us.posthog.com/project/2/insights/9pQx3"
+ preview={{
+ title: "Coupon → purchase conversion",
+ detail: "Funnel conversion, last 30 days",
+ }}
+ >
+ Checkout funnel
+ </EvidenceHoverCard>
+ </div>
+ <div className="rounded-md border border-(--gray-a5) bg-(--color-panel-solid)">
+ <EvidenceHoverCard
+ target={{ kind: "flag", id: "new-checkout-flow" }}
+ url={null}
+ preview={{
+ title: "new-checkout-flow",
+ detail: "Enabled · New checkout rollout",
+ facts: ["100% rollout", "Used by 1 experiment"],
+ }}
+ >
+ new-checkout-flow
+ </EvidenceHoverCard>
+ </div>
+ <div className="rounded-md border border-(--gray-a5) bg-(--color-panel-solid)">
+ <EvidenceHoverCard
+ target={{ kind: "hogql", id: "SELECT toDate(timestamp) AS day ..." }}
+ url="https://us.posthog.com/project/2/sql"
+ preview={{
+ title: "active_users",
+ headline: {
+ value: "1.5M",
+ delta: { label: "71%", direction: "down" },
+ },
+ spark: {
+ points: [4.9, 5.1, 5.7, 5.8, 5.7, 5.1, 1.5],
+ render: "line",
+ },
+ }}
+ >
+ active users per day
+ </EvidenceHoverCard>
+ </div>
+ <div className="rounded-md border border-(--gray-a5) bg-(--color-panel-solid)">
+ <EvidenceHoverCard
+ target={{ kind: "ticket", id: "conv_88" }}
+ url="https://us.posthog.com/project/2/insights/9pQx3"
+ preview={null}
+ >
+ 9 “coupon” tickets
+ </EvidenceHoverCard>
+ </div>
+ </div>
+ ),
+};
+
+export const InsideAgentMessage: Story = {
+ render: () => (
+ <div className="max-w-xl">
+ <MarkdownRenderer
+ content={[
+ 'The <insight id="9pQx3">coupon → purchase conversion</insight> dropped',
+ "41% → 28% on Jan 3, the same day",
+ '<error id="018f44aa">a TypeError in CouponValidator</error> first',
+ 'appeared, and <replay id="s_01HQ4K">14 recordings</replay> show users',
+ "retrying the field before leaving. This area is gated by",
+ '<flag id="42">new-checkout-flow</flag>, and',
+ "<hogql label=\"1,247 sessions\">SELECT count(distinct $session_id) FROM events WHERE event = '$exception'</hogql>",
+ "hit the error this week.",
+ ].join(" ")}
+ />
+ </div>
+ ),
+};
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
new file mode 100644
index 000000000000..792fb9830b62
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.test.tsx
@@ -0,0 +1,247 @@
+import { Theme } from "@radix-ui/themes";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../shell/openExternal", () => ({
+ openExternalUrl: vi.fn(),
+}));
+
+// The hover card resolves its preview through the app shell; without it the
+// loader renders the static card, which is all the chip tests need.
+vi.mock("../../auth/authClient", () => ({
+ useOptionalAuthenticatedClient: () => null,
+}));
+vi.mock("../../../hooks/useAuthenticatedQuery", () => ({
+ useAuthenticatedQuery: () => ({
+ isPending: true,
+ isError: false,
+ isFetched: false,
+ data: undefined,
+ }),
+}));
+
+import { openExternalUrl } from "../../../shell/openExternal";
+import { ANONYMOUS_AUTH_STATE, useAuthStore } from "../../auth/store";
+import { EvidenceHoverCard, EvidenceRefChip } from "./EvidenceRefChip";
+import { MarkdownRenderer } from "./MarkdownRenderer";
+
+function renderInTheme(node: React.ReactNode) {
+ return render(<Theme>{node}</Theme>);
+}
+
+function signIn() {
+ useAuthStore.setState({
+ authState: {
+ ...ANONYMOUS_AUTH_STATE,
+ cloudRegion: "us",
+ currentProjectId: 2,
+ },
+ });
+}
+
+afterEach(() => {
+ useAuthStore.setState({ authState: ANONYMOUS_AUTH_STATE });
+});
+
+describe("EvidenceRefChip", () => {
+ it("renders as plain text without a project to link into", () => {
+ renderInTheme(
+ <EvidenceRefChip target={{ kind: "insight", id: "9pQx3" }}>
+ Checkout funnel
+ </EvidenceRefChip>,
+ );
+ expect(screen.getByText("Checkout funnel")).toBeDefined();
+ expect(screen.queryByRole("link")).toBeNull();
+ });
+
+ it("derives the PostHog url from the reference and opens it externally", () => {
+ signIn();
+ renderInTheme(
+ <EvidenceRefChip target={{ kind: "insight", id: "9pQx3" }}>
+ Checkout funnel
+ </EvidenceRefChip>,
+ );
+ const link = screen.getByRole("link", { name: "Checkout funnel" });
+ fireEvent.click(link);
+ expect(openExternalUrl).toHaveBeenCalledWith(
+ "https://us.posthog.com/project/2/insights/9pQx3",
+ );
+ });
+
+ it("stays plain for a kind with no canonical page even when signed in", () => {
+ signIn();
+ renderInTheme(
+ <EvidenceRefChip target={{ kind: "event", id: "cart_saved" }}>
+ cart_saved events
+ </EvidenceRefChip>,
+ );
+ expect(screen.queryByRole("link")).toBeNull();
+ });
+
+ it("renders from an evidence: markdown link in agent output", () => {
+ // Guards the whole path: url transform must keep the scheme and the `a`
+ // component must dispatch to the chip instead of an external link.
+ renderInTheme(
+ <MarkdownRenderer
+ content="The [coupon funnel](evidence:insight/9pQx3) dropped."
+ renderObjectTags
+ />,
+ );
+ expect(screen.getByText("coupon funnel")).toBeDefined();
+ // Without auth context the reference is not a link at all — a plain
+ // external-link fallback would render one.
+ expect(screen.queryByRole("link")).toBeNull();
+ });
+
+ it("opens the card from keyboard focus on a linked reference", () => {
+ signIn();
+ renderInTheme(
+ <EvidenceRefChip target={{ kind: "insight", id: "9pQx3" }}>
+ Checkout funnel
+ </EvidenceRefChip>,
+ );
+ const link = screen.getByRole("link", { name: "Checkout funnel" });
+ fireEvent.focus(link);
+ // The card is a focus-managed dialog, not a tooltip: its controls are
+ // real elements a keyboard user can Tab to.
+ expect(screen.getByRole("dialog")).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: /Open in PostHog/ }),
+ ).toBeDefined();
+ });
+
+ it("gives an unlinked reference a focusable trigger that opens the card", () => {
+ // A flag cited by key or an event cited by name has no chip URL, so the
+ // card's "Open in PostHog" is the only route to the object; the trigger
+ // must therefore be reachable and operable by keyboard.
+ signIn();
+ renderInTheme(
+ <EvidenceRefChip target={{ kind: "event", id: "cart_saved" }}>
+ cart_saved events
+ </EvidenceRefChip>,
+ );
+ const trigger = screen.getByRole("button", { name: "cart_saved events" });
+ expect(trigger.getAttribute("tabindex")).toBe("0");
+ fireEvent.click(trigger);
+ expect(screen.getByRole("dialog")).toBeDefined();
+ });
+});
+
+describe("EvidenceHoverCard", () => {
+ it.each([
+ ["loading", undefined, "evidence-preview-loading", "evidence-preview"],
+ [
+ "resolved",
+ { title: "Checkout funnel", detail: "conversion, last 30 days" },
+ "evidence-preview",
+ "evidence-preview-loading",
+ ],
+ ["unavailable", null, null, "evidence-preview"],
+ ])("shows the %s state", (_state, preview, shown, hidden) => {
+ renderInTheme(
+ <EvidenceHoverCard
+ target={{ kind: "insight", id: "9pQx3" }}
+ url={null}
+ preview={preview}
+ >
+ Checkout funnel
+ </EvidenceHoverCard>,
+ );
+ if (shown) expect(screen.getByTestId(shown)).toBeDefined();
+ expect(screen.queryByTestId(hidden)).toBeNull();
+ if (preview) {
+ expect(screen.getByText("conversion, last 30 days")).toBeDefined();
+ }
+ });
+
+ it("draws a sparkline and headline for a series preview and opens on click", () => {
+ const onOpen = vi.fn();
+ renderInTheme(
+ <EvidenceHoverCard
+ target={{ kind: "hogql", id: "SELECT 1" }}
+ url="https://us.posthog.com/project/2/sql?open_query=SELECT%201"
+ onOpen={onOpen}
+ preview={{
+ title: "active_users",
+ headline: {
+ value: "1.5M",
+ delta: { label: "71%", direction: "down" },
+ },
+ spark: { points: [5, 5.1, 5.7, 1.5], render: "line" },
+ }}
+ >
+ active users per day
+ </EvidenceHoverCard>,
+ );
+ expect(screen.getByTestId("evidence-sparkline")).toBeDefined();
+ expect(screen.getByText("1.5M")).toBeDefined();
+ fireEvent.click(screen.getByRole("button", { name: /Open in PostHog/ }));
+ expect(onOpen).toHaveBeenCalledWith(
+ "https://us.posthog.com/project/2/sql?open_query=SELECT%201",
+ );
+ });
+
+ it("hangs bar-sparkline negatives below the shared zero baseline", () => {
+ renderInTheme(
+ <EvidenceHoverCard
+ target={{ kind: "hogql", id: "SELECT 1" }}
+ url={null}
+ preview={{
+ title: "change by category",
+ spark: { points: [-10, 5], render: "bar" },
+ }}
+ >
+ per-category change
+ </EvidenceHoverCard>,
+ );
+ const bars = screen
+ .getByTestId("evidence-sparkline")
+ .querySelectorAll("rect");
+ expect(bars).toHaveLength(2);
+ const y = (el: Element) => Number(el.getAttribute("y"));
+ const h = (el: Element) => Number(el.getAttribute("height"));
+ // Zero line sits at y≈10.67: the -10 bar hangs below it with real height
+ // (not the 0.5 clamp it collapsed to when measured from the chart bottom),
+ // and the +5 bar rises from that same baseline.
+ expect(y(bars[0])).toBeCloseTo(10.67, 1);
+ expect(h(bars[0])).toBeCloseTo(17.33, 1);
+ expect(y(bars[1]) + h(bars[1])).toBeCloseTo(10.67, 1);
+ });
+
+ it("expands the truncated SQL footer into the full query on click", () => {
+ const sql =
+ "SELECT toDate(timestamp) AS day, count() FROM events GROUP BY day";
+ renderInTheme(
+ <EvidenceHoverCard
+ target={{ kind: "hogql", id: sql }}
+ url={null}
+ preview={{ title: "day" }}
+ >
+ events per day
+ </EvidenceHoverCard>,
+ );
+ expect(screen.queryByTestId("evidence-query")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: /SELECT toDate/ }));
+ expect(screen.getByTestId("evidence-query").textContent).toBe(sql);
+ fireEvent.click(screen.getByRole("button", { name: "Hide query" }));
+ expect(screen.queryByTestId("evidence-query")).toBeNull();
+ });
+
+ it("renders preview facts as pills", () => {
+ renderInTheme(
+ <EvidenceHoverCard
+ target={{ kind: "flag", id: "42" }}
+ url={null}
+ preview={{
+ title: "new-checkout-flow",
+ detail: "Enabled",
+ facts: ["100% rollout", "Used by 1 experiment"],
+ }}
+ >
+ new-checkout-flow
+ </EvidenceHoverCard>,
+ );
+ expect(screen.getByText("100% rollout")).toBeDefined();
+ expect(screen.getByText("Used by 1 experiment")).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
new file mode 100644
index 000000000000..5f34613f71ed
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
@@ -0,0 +1,422 @@
+import { Popover } from "@base-ui/react/popover";
+import { getCloudUrlFromRegion } from "@posthog/shared";
+import { type MouseEvent, type ReactNode, useId, useState } from "react";
+import { useOptionalAuthenticatedClient } from "../../../features/auth/authClient";
+import { useAuthStateValue } from "../../../features/auth/store";
+import { useAuthenticatedQuery } from "../../../hooks/useAuthenticatedQuery";
+import { openExternalUrl } from "../../../shell/openExternal";
+import {
+ type EvidenceLinkTarget,
+ evidenceWebPath,
+} from "../../../utils/evidenceLinks";
+import { getObjectKind } from "../../../utils/objectKinds";
+import {
+ type EvidenceCardData,
+ fetchEvidencePreview,
+} from "../evidencePreview";
+
+/**
+ * Inline evidence reference inside an agent message, authored as a
+ * `<kind id="...">label</kind>` object tag (see remarkObjectTags).
+ *
+ * Renders as a dotted-underline span with a small kind icon, so it reads as
+ * part of the sentence and wraps like text. The underline is a bottom border
+ * rather than text-decoration: decoration never paints under an atomic
+ * inline like the icon's svg, while a bottom border runs under the full
+ * reference on every wrapped line fragment.
+ *
+ * The reference carries only `kind/id`. Hovering or focusing mounts the card,
+ * which resolves the object's live name and status through the PostHog API
+ * (for `hogql`, runs the query); clicking a linked reference opens the object
+ * in PostHog at a URL derived from the reference and the current project.
+ * Nothing about the object is stored in the message itself.
+ *
+ * The card is a Base UI popover, not a tooltip: it holds real controls (the
+ * query toggle, "Open in PostHog"), so it must be a focus-managed overlay —
+ * Tab moves from the chip into the card and operates its buttons, Escape
+ * closes, and assistive tech sees an interactive popup rather than the whole
+ * card flattened into description text.
+ */
+
+const SPARK_W = 100;
+const SPARK_H = 30;
+const SPARK_PAD = 2;
+// PostHog's first data-viz color, same source quill-charts reads; the hex
+// fallback keeps the spark on-brand where the theme variable isn't defined
+// (the tooltip portals outside the theme root).
+const 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({
+ points,
+ render,
+}: {
+ points: number[];
+ render: "line" | "bar";
+}) {
+ const gradientId = useId();
+ const max = Math.max(...points);
+ const min = render === "bar" ? Math.min(0, ...points) : Math.min(...points);
+ const range = max - min || 1;
+ const scaleY = (value: number): number =>
+ SPARK_H - SPARK_PAD - ((value - min) / range) * (SPARK_H - 2 * SPARK_PAD);
+
+ if (render === "bar") {
+ const step = SPARK_W / points.length;
+ const gap = Math.min(step * 0.25, 2);
+ // Bars grow from the zero line, so a negative point extends below it.
+ // Measuring to the chart bottom instead would shrink or invert them once
+ // any point is negative (min drops below 0 and lifts the zero line).
+ const baseline = scaleY(0);
+ return (
+ <svg
+ viewBox={`0 0 ${SPARK_W} ${SPARK_H}`}
+ preserveAspectRatio="none"
+ className="h-9 w-full"
+ role="img"
+ aria-label="Column sparkline"
+ data-testid="evidence-sparkline"
+ >
+ {points.map((point, index) => {
+ const y = scaleY(point);
+ return (
+ <rect
+ // biome-ignore lint/suspicious/noArrayIndexKey: static series, never reorders
+ key={index}
+ x={index * step + gap / 2}
+ width={step - gap}
+ y={Math.min(y, baseline)}
+ height={Math.max(Math.abs(y - baseline), 0.5)}
+ fill={SPARK_COLOR}
+ fillOpacity={0.85}
+ />
+ );
+ })}
+ </svg>
+ );
+ }
+
+ const coords = points.map(
+ (point, index) =>
+ [
+ points.length === 1 ? 0 : (index / (points.length - 1)) * SPARK_W,
+ scaleY(point),
+ ] as const,
+ );
+ const line = coords
+ .map(
+ ([x, y], index) =>
+ `${index === 0 ? "M" : "L"}${x.toFixed(1)} ${y.toFixed(1)}`,
+ )
+ .join(" ");
+ const [lastX, lastY] = coords[coords.length - 1];
+ return (
+ <svg
+ viewBox={`0 0 ${SPARK_W} ${SPARK_H}`}
+ preserveAspectRatio="none"
+ className="h-9 w-full"
+ role="img"
+ aria-label="Trend sparkline"
+ data-testid="evidence-sparkline"
+ >
+ <defs>
+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stopColor={SPARK_COLOR} stopOpacity={0.25} />
+ <stop offset="100%" stopColor={SPARK_COLOR} stopOpacity={0.02} />
+ </linearGradient>
+ </defs>
+ <path
+ d={`${line} L${SPARK_W} ${SPARK_H} L0 ${SPARK_H} Z`}
+ fill={`url(#${gradientId})`}
+ />
+ <path
+ d={line}
+ fill="none"
+ stroke={SPARK_COLOR}
+ strokeWidth={1.6}
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ <circle cx={lastX} cy={lastY} r={2} fill={SPARK_COLOR} />
+ </svg>
+ );
+}
+
+/**
+ * The hover card, presentation only. `preview` is the live lookup result:
+ * `undefined` while loading, `null` when there is nothing to show (unknown
+ * kind, failed lookup, or no session).
+ */
+export function EvidenceHoverCard({
+ target,
+ children,
+ url,
+ preview,
+ onOpen = openExternalUrl,
+}: {
+ target: EvidenceLinkTarget;
+ children: ReactNode;
+ url: string | null;
+ preview: EvidenceCardData | null | undefined;
+ onOpen?: (url: string) => void;
+}) {
+ const meta = getObjectKind(target.kind);
+ const KindIcon = meta.icon;
+ const isQuery = target.kind === "hogql";
+ const [showQuery, setShowQuery] = useState(false);
+ return (
+ <div className="w-80 p-3.5">
+ <div className="flex items-center gap-1.5 text-(--gray-9) text-[10.5px]">
+ <KindIcon size={12} aria-hidden />
+ <span className="truncate uppercase tracking-[0.06em]">
+ {meta.kindLabel}
+ </span>
+ {/* For a query the source label duplicates the footer's open action. */}
+ {!isQuery && <span className="ml-auto shrink-0">{meta.source}</span>}
+ </div>
+ {preview === undefined ? (
+ <div className="mt-3 space-y-2" data-testid="evidence-preview-loading">
+ <div className="h-4 w-3/5 animate-pulse rounded bg-(--gray-a4)" />
+ <div className="h-9 w-full animate-pulse rounded bg-(--gray-a3)" />
+ </div>
+ ) : preview ? (
+ <div className="mt-2.5" data-testid="evidence-preview">
+ <div className="flex items-baseline justify-between gap-3">
+ <span className="min-w-0 truncate font-semibold text-(--gray-12) text-[14px] leading-snug">
+ {preview.title}
+ </span>
+ {preview.headline && (
+ <span className="flex shrink-0 items-baseline gap-1">
+ <span className="font-semibold text-(--gray-12) text-[15px] tabular-nums leading-none">
+ {preview.headline.value}
+ </span>
+ {preview.headline.delta && (
+ <span
+ className={`font-medium text-[11px] tabular-nums ${
+ preview.headline.delta.direction === "up"
+ ? "text-(--green-11)"
+ : "text-(--red-11)"
+ }`}
+ >
+ {preview.headline.delta.direction === "up" ? "▲" : "▼"}
+ {preview.headline.delta.label}
+ </span>
+ )}
+ </span>
+ )}
+ </div>
+ {preview.spark && preview.spark.points.length > 1 && (
+ <div className="mt-2.5">
+ <Sparkline
+ points={preview.spark.points}
+ render={preview.spark.render}
+ />
+ </div>
+ )}
+ {preview.detail && (
+ <div className="mt-1.5 text-(--gray-10) text-[11.5px] leading-snug">
+ {preview.detail}
+ </div>
+ )}
+ {preview.facts && preview.facts.length > 0 && (
+ <div className="mt-2 flex flex-wrap gap-1">
+ {preview.facts.map((fact) => (
+ <span
+ key={fact}
+ className="max-w-full truncate rounded-[4px] bg-(--gray-a3) px-1.5 py-0.5 text-(--gray-11) text-[10px]"
+ >
+ {fact}
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="mt-2.5">
+ <span className="block font-semibold text-(--gray-12) text-[14px] leading-snug">
+ {children}
+ </span>
+ </div>
+ )}
+ {isQuery && showQuery && (
+ <div className="mt-3 max-h-36 overflow-y-auto rounded-[4px] bg-(--gray-a3) p-2">
+ <pre
+ className="m-0 select-text whitespace-pre-wrap break-all font-mono text-(--gray-11) text-[10.5px] leading-relaxed"
+ data-testid="evidence-query"
+ >
+ {target.id}
+ </pre>
+ </div>
+ )}
+ <div className="mt-3 flex items-center justify-between gap-3 text-[10.5px]">
+ {isQuery ? (
+ <button
+ type="button"
+ onClick={() => setShowQuery((open) => !open)}
+ className="min-w-0 cursor-pointer truncate border-none bg-transparent p-0 text-left font-mono text-(--gray-8) transition-colors hover:text-(--gray-11)"
+ >
+ {showQuery ? "Hide query" : target.id}
+ </button>
+ ) : (
+ <span className="truncate font-mono text-(--gray-8)">
+ {target.id}
+ </span>
+ )}
+ {url && (
+ <button
+ type="button"
+ onClick={() => onOpen(url)}
+ className="shrink-0 cursor-pointer border-none bg-transparent p-0 text-(--gray-10) text-[10.5px] transition-colors hover:text-(--gray-12)"
+ >
+ Open in PostHog ↗
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Fetching wrapper around the card. Mounted only while the tooltip is open,
+ * so the lookup is lazy: a transcript full of references costs nothing until
+ * one is hovered, and react-query caches the result across hovers.
+ */
+function EvidenceHoverCardLoader({
+ target,
+ children,
+ url,
+}: {
+ target: EvidenceLinkTarget;
+ children: ReactNode;
+ url: string | null;
+}) {
+ const client = useOptionalAuthenticatedClient();
+ const query = useAuthenticatedQuery(
+ ["evidence-preview", target.kind, target.id],
+ (apiClient) => fetchEvidencePreview(apiClient, target),
+ {
+ staleTime: 5 * 60 * 1000,
+ refetchOnWindowFocus: false,
+ retry: 1,
+ // The card unmounts when the tooltip closes, so without this a preview
+ // that already failed would refetch on every hover (re-running a hogql
+ // or error lookup against /query/); the static fallback covers the miss.
+ retryOnMount: false,
+ },
+ );
+ // No session means no lookup: show the static card, not an endless skeleton.
+ const preview =
+ !client || query.isError
+ ? null
+ : query.isFetched
+ ? (query.data ?? null)
+ : undefined;
+ // A reference whose cited id has no page (an event name, a flag key) can
+ // still link out once the preview resolves the canonical id.
+ const resolvedUrl = useEvidenceUrl(
+ target.kind,
+ preview?.resolvedId ?? target.id,
+ );
+ return (
+ <EvidenceHoverCard
+ target={target}
+ url={url ?? resolvedUrl}
+ preview={preview}
+ >
+ {children}
+ </EvidenceHoverCard>
+ );
+}
+
+/** PostHog web URL for a reference in the current project, when it has one. */
+export function useEvidenceUrl(kind: string, id: string): string | null {
+ const projectId = useAuthStateValue((state) => state.currentProjectId);
+ const cloudRegion = useAuthStateValue((state) => state.cloudRegion);
+ const path = evidenceWebPath(kind, id);
+ if (!path || !cloudRegion || !projectId) return null;
+ return `${getCloudUrlFromRegion(cloudRegion)}/project/${projectId}${path}`;
+}
+
+export function EvidenceRefChip({
+ target,
+ children,
+}: {
+ target: EvidenceLinkTarget;
+ children: ReactNode;
+}) {
+ const meta = getObjectKind(target.kind);
+ const KindIcon = meta.icon;
+ const url = useEvidenceUrl(target.kind, target.id);
+ const [open, setOpen] = useState(false);
+
+ const openInPostHog = (event: MouseEvent<HTMLAnchorElement>) => {
+ event.preventDefault();
+ if (url) openExternalUrl(url);
+ };
+
+ const refClass =
+ "border-b border-dotted border-(--gray-a8) pb-px text-(--gray-12) no-underline hover:border-solid hover:border-(--gray-a11)";
+ const inner = (
+ <>
+ <KindIcon
+ size={12}
+ className="mr-[3px] inline-block translate-y-[-1px] align-middle text-(--gray-10)"
+ aria-hidden
+ />
+ {children}
+ </>
+ );
+
+ return (
+ <Popover.Root open={open} onOpenChange={setOpen}>
+ <Popover.Trigger
+ openOnHover
+ delay={200}
+ closeDelay={100}
+ nativeButton={false}
+ // Focus opens the card the way the tooltip used to, so a keyboard
+ // user can preview a linked reference whose Enter action navigates
+ // to PostHog instead of toggling the popover.
+ onFocus={() => setOpen(true)}
+ render={
+ url ? (
+ // Keep the truthful role: Enter follows the link (opens the
+ // object in PostHog), 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}
+ // biome-ignore lint/a11y/noRedundantRoles: not redundant — the popover trigger injects role="button" without it
+ role="link"
+ className={refClass}
+ >
+ {inner}
+ </a>
+ ) : (
+ // No page to link to: the reference is a real popover trigger
+ // (focusable, Enter/Space opens the card), since the card's
+ // "Open in PostHog" action is the only route to the object.
+ <span className={`${refClass} cursor-pointer`}>{inner}</span>
+ )
+ }
+ />
+ {open && (
+ <Popover.Portal>
+ {/* Self-styled like primitives/Tooltip: quill's popover CSS isn't
+ loaded on every surface that renders chips (see ChatMarkdown). */}
+ <Popover.Positioner side="top" sideOffset={8} className="z-[9999]">
+ <Popover.Popup
+ className="dark rounded-[6px] border border-(--gray-4) bg-(--gray-2) text-(--gray-12) outline-none"
+ style={{ boxShadow: "0 4px 12px rgba(0, 0, 0, 0.25)" }}
+ >
+ <EvidenceHoverCardLoader target={target} url={url}>
+ {children}
+ </EvidenceHoverCardLoader>
+ </Popover.Popup>
+ </Popover.Positioner>
+ </Popover.Portal>
+ )}
+ </Popover.Root>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.objectTags.test.tsx b/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.objectTags.test.tsx
new file mode 100644
index 000000000000..3840f0fe0dbb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.objectTags.test.tsx
@@ -0,0 +1,195 @@
+import { Theme } from "@radix-ui/themes";
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+// quill-charts is canvas-backed and does not load in the test environment;
+// the tag-to-card dispatch around it is what these tests exercise.
+vi.mock("@posthog/quill-charts", () => ({
+ BarChart: () => <div data-testid="chart-plot" />,
+ LineChart: () => <div data-testid="chart-plot" />,
+ TimeSeriesBarChart: () => <div data-testid="chart-plot" />,
+ TimeSeriesLineChart: () => <div data-testid="chart-plot" />,
+ useChartTheme: () => ({}),
+}));
+
+// Cards resolve their data through the app shell; without it they render
+// their loading state, which is all the dispatch tests need.
+vi.mock("../../auth/authClient", () => ({
+ useOptionalAuthenticatedClient: () => null,
+}));
+vi.mock("../../../hooks/useAuthenticatedQuery", () => ({
+ useAuthenticatedQuery: () => ({
+ isPending: true,
+ isError: false,
+ isFetched: false,
+ data: undefined,
+ }),
+}));
+
+import { MarkdownRenderer } from "./MarkdownRenderer";
+
+function renderMarkdown(content: string) {
+ return render(
+ <Theme>
+ <MarkdownRenderer content={content} renderObjectTags />
+ </Theme>,
+ );
+}
+
+function renderUntrustedMarkdown(content: string) {
+ return render(
+ <Theme>
+ <MarkdownRenderer content={content} />
+ </Theme>,
+ );
+}
+
+describe("object tags in agent markdown", () => {
+ it("renders an inline object tag as a reference chip with its label", () => {
+ renderMarkdown(
+ 'The <insight id="9pQx3">checkout funnel</insight> dropped.',
+ );
+ expect(screen.getByText("checkout funnel")).toBeDefined();
+ expect(screen.queryByText(/<insight/)).toBeNull();
+ });
+
+ it("falls back to the id as the label for a self-closing tag", () => {
+ renderMarkdown('Gated by <flag id="42"/> since Jan 3.');
+ expect(screen.getByText("42")).toBeDefined();
+ expect(screen.queryByText(/<flag/)).toBeNull();
+ });
+
+ it("keeps markdown formatting inside a tag label", () => {
+ renderMarkdown(
+ 'See <error id="018f">the **CouponValidator** issue</error>.',
+ );
+ expect(screen.getByText("CouponValidator").tagName).toBe("STRONG");
+ });
+
+ it.each([
+ ["session-replay", '<session-replay id="s1">a recording</session-replay>'],
+ ["feature-flag", '<feature-flag id="7">the flag</feature-flag>'],
+ ])("resolves the %s alias", (_alias, tag) => {
+ renderMarkdown(`Watch ${tag} now.`);
+ expect(screen.queryByText(/</)).toBeNull();
+ });
+
+ it("shows an inline hogql tag as its label, not its SQL", () => {
+ renderMarkdown(
+ 'We saw <hogql label="signups today">SELECT count() FROM events</hogql> spike.',
+ );
+ expect(screen.getByText("signups today")).toBeDefined();
+ expect(screen.queryByText(/SELECT count/)).toBeNull();
+ });
+
+ it("renders a block insight tag as a chart card", () => {
+ renderMarkdown('Here it is:\n\n<insight id="9pQx3" display="block"/>\n');
+ expect(screen.getByTestId("report-chart")).toBeDefined();
+ });
+
+ it("renders a block hogql tag as a chart card titled from the tag", () => {
+ renderMarkdown(
+ '<hogql display="block" title="DAU, last 7 days">\nSELECT 1\n</hogql>\n',
+ );
+ expect(screen.getByTestId("report-chart")).toBeDefined();
+ expect(screen.getByText("DAU, last 7 days")).toBeDefined();
+ expect(screen.queryByText(/SELECT 1/)).toBeNull();
+ });
+
+ it("renders a block replay tag as a watchable card", () => {
+ renderMarkdown('Watch it:\n\n<replay id="s_01HQ4K" display="block"/>\n');
+ expect(screen.getByTestId("replay-card")).toBeDefined();
+ });
+
+ it("lifts a single-line block tag out of its paragraph into a card", () => {
+ // Markdown parses `<hogql ...>SELECT ...</hogql>` on one line as inline
+ // html inside a paragraph, not an HTML block; without the lift it would
+ // downgrade to an inline chip.
+ renderMarkdown(
+ '<hogql display="block" title="One-liner">SELECT 1</hogql>\n',
+ );
+ expect(screen.getByTestId("report-chart")).toBeDefined();
+ expect(screen.getByText("One-liner")).toBeDefined();
+ });
+
+ it.each([
+ [
+ "a list item",
+ '- Signups jumped:\n\n <hogql display="block" title="Nested chart">SELECT 1</hogql>\n',
+ ],
+ [
+ "a blockquote",
+ '> Note:\n>\n> <hogql display="block" title="Nested chart">SELECT 1</hogql>\n',
+ ],
+ ])("renders a block tag nested in %s as a chart card", (_where, content) => {
+ renderMarkdown(content);
+ expect(screen.getByTestId("report-chart")).toBeDefined();
+ expect(screen.getByText("Nested chart")).toBeDefined();
+ expect(screen.queryByText(/SELECT 1/)).toBeNull();
+ });
+
+ it("leaves tags inside code fences literal", () => {
+ const { container } = renderMarkdown(
+ 'Example:\n\n```xml\n<insight id="9pQx3">label</insight>\n```\n',
+ );
+ expect(container.querySelector("code")?.textContent).toContain(
+ '<insight id="9pQx3">',
+ );
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ });
+
+ it("renders nothing for a half-streamed tag instead of raw text", () => {
+ renderMarkdown('<hogql display="block" title="DAU">\nSELECT 1');
+ expect(screen.queryByText(/hogql|SELECT/)).toBeNull();
+ });
+
+ it("leaves unknown tags unrendered rather than guessing", () => {
+ renderMarkdown('A <made-up-tag id="1">thing</made-up-tag> here.');
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ // The label text still flows through; only the tags themselves vanish.
+ expect(screen.getByText(/thing/)).toBeDefined();
+ });
+
+ it("caps block cards per message; overflow degrades to inline chips", () => {
+ // Every block card executes a query on mount, so one message must not
+ // fan out unbounded concurrent queries. Past the cap (10) a block tag
+ // renders as a hover-gated inline chip instead.
+ const tags = Array.from(
+ { length: 12 },
+ (_, i) => `<hogql display="block" title="Q${i}">SELECT ${i}</hogql>\n`,
+ ).join("\n");
+ renderMarkdown(tags);
+ expect(screen.getAllByTestId("report-chart")).toHaveLength(10);
+ // The two overflow tags fall back to the inline chip's default label.
+ expect(screen.getAllByText("SQL query")).toHaveLength(2);
+ });
+});
+
+describe("object tags in untrusted markdown (default)", () => {
+ it("does not render a block tag as a live chart card", () => {
+ renderUntrustedMarkdown(
+ 'Here it is:\n\n<hogql display="block" title="DAU">\nSELECT 1\n</hogql>\n',
+ );
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ });
+
+ it("does not render a posthog-chart fence as a live chart card", () => {
+ const { container } = renderUntrustedMarkdown(
+ '```posthog-chart\n{"mode":"hogql","query":"SELECT 1"}\n```\n',
+ );
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ expect(container.querySelector("code")?.textContent).toContain(
+ '"mode":"hogql"',
+ );
+ });
+
+ it("does not render an evidence: link as a reference chip", () => {
+ const { container } = renderUntrustedMarkdown(
+ "See [errors today](evidence:hogql/SELECT%201).",
+ );
+ // The href is stripped by the default url transform, so the chip (whose
+ // hover preview would run the query) never mounts.
+ expect(container.querySelector('a[href^="evidence:"]')).toBeNull();
+ expect(screen.getByText("errors today")).toBeDefined();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx b/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
index 5722b6fdf2eb..980fc96bb5ac 100644
--- a/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
@@ -1,12 +1,21 @@
import { isPostHogCodeDeeplink } from "@posthog/shared";
import { ArtifactRefChip } from "@posthog/ui/features/editor/components/ArtifactRefChip";
+import { EvidenceRefChip } from "@posthog/ui/features/editor/components/EvidenceRefChip";
import { GithubRefChip } from "@posthog/ui/features/editor/components/GithubRefChip";
+import { MessageChartCard } from "@posthog/ui/features/editor/components/MessageChartCard";
import { parseGithubIssueUrl } from "@posthog/ui/features/message-editor/githubIssueUrl";
import { CodeBlock } from "@posthog/ui/primitives/CodeBlock";
import { Divider } from "@posthog/ui/primitives/Divider";
import { HighlightedCode } from "@posthog/ui/primitives/HighlightedCode";
import { List, ListItem } from "@posthog/ui/primitives/List";
import { parseArtifactLink } from "@posthog/ui/utils/artifactLinks";
+import {
+ chartBlockKey,
+ isGeneratedChartBlock,
+ parseChartBlock,
+} from "@posthog/ui/utils/chartBlocks";
+import { parseEvidenceLink } from "@posthog/ui/utils/evidenceLinks";
+import { remarkObjectTags } from "@posthog/ui/utils/remarkObjectTags";
import { handleShareLinkClick } from "@posthog/ui/utils/shareLinks";
import { Blockquote, Checkbox, Code, Kbd, Text } from "@radix-ui/themes";
import { memo, useMemo } from "react";
@@ -18,6 +27,14 @@ import { openExternalUrl } from "../../../shell/openExternal";
interface MarkdownRendererProps {
content: string;
+ /**
+ * Render PostHog object tags (`<insight/>`, `<hogql/>`…) as live reference
+ * chips and chart cards. Off by default because rich objects execute
+ * authenticated queries against the viewer's project: only agent-authored
+ * surfaces may enable this, never GitHub comments, user messages, or other
+ * untrusted content.
+ */
+ renderObjectTags?: boolean;
remarkPluginsOverride?: PluggableList;
componentsOverride?: Partial<Components>;
rehypePlugins?: PluggableList;
@@ -38,6 +55,16 @@ function markdownUrlTransform(value: string, key: string): string {
return defaultUrlTransform(value);
}
+function objectTagUrlTransform(value: string, key: string): string {
+ // Object references (authored as `<kind id="...">` tags, normalized to
+ // `evidence:` links by remarkObjectTags) render as inline reference chips
+ // with a hover preview; see EvidenceRefChip. Their previews run
+ // authenticated queries, so the scheme survives only when the surface
+ // opted into object tags.
+ if (key === "href" && value.startsWith("evidence:")) return value;
+ return markdownUrlTransform(value, key);
+}
+
const HeadingText = ({ children }: { children: React.ReactNode }) => (
<Text as="p" className="mb-2 text-(--accent-11) text-sm leading-relaxed">
<strong>{children}</strong>
@@ -109,7 +136,7 @@ export const baseComponents: Components = {
</Blockquote>
),
code: ({ children, className }) => {
- const match = className?.match(/language-(\w+)/);
+ const match = className?.match(/language-([\w-]+)/);
if (!match) {
return <Code variant="ghost">{children}</Code>;
}
@@ -120,7 +147,9 @@ export const baseComponents: Components = {
/>
);
},
- pre: ({ children }) => <CodeBlock size="1">{children}</CodeBlock>,
+ pre: ({ children }) => {
+ return <CodeBlock size="1">{children}</CodeBlock>;
+ },
em: ({ children }) => <em>{children}</em>,
i: ({ children }) => <i>{children}</i>,
strong: ({ children }) => <strong>{children}</strong>,
@@ -128,6 +157,12 @@ export const baseComponents: Components = {
<del className="text-(--gray-9) line-through">{children}</del>
),
a: ({ href, children }) => {
+ const evidenceTarget = parseEvidenceLink(href);
+ if (evidenceTarget) {
+ return (
+ <EvidenceRefChip target={evidenceTarget}>{children}</EvidenceRefChip>
+ );
+ }
const artifactTarget = parseArtifactLink(href);
if (artifactTarget && href) {
return (
@@ -200,10 +235,43 @@ export const baseComponents: Components = {
),
};
+/**
+ * Components for surfaces that opted into object tags: `posthog-chart` code
+ * nodes generated by remarkObjectTags render as live chart cards. Dispatch
+ * requires the plugin's private AST marker, so a hand-authored
+ * ```posthog-chart fence stays inert even here.
+ */
+const objectTagComponents: Components = {
+ ...baseComponents,
+ code: (props) => {
+ const { children, node } = props;
+ if (isGeneratedChartBlock(node)) {
+ const source = String(children).replace(/\n$/, "");
+ const spec = parseChartBlock(source);
+ // Malformed or half-streamed JSON renders nothing rather than raw JSON;
+ // the block completes (or stays broken) on the next stream snapshot.
+ if (!spec) return null;
+ return <MessageChartCard spec={spec} blockKey={chartBlockKey(source)} />;
+ }
+ const BaseCode = baseComponents.code;
+ return typeof BaseCode === "function" ? <BaseCode {...props} /> : null;
+ },
+ pre: (props) => {
+ // A chart block renders as a full card, not inside a code block shell.
+ if (isGeneratedChartBlock(props.node?.children[0])) {
+ return props.children;
+ }
+ const BasePre = baseComponents.pre;
+ return typeof BasePre === "function" ? <BasePre {...props} /> : null;
+ },
+};
+
export const defaultRemarkPlugins = [remarkGfm];
+const objectTagRemarkPlugins = [...defaultRemarkPlugins, remarkObjectTags];
export const MarkdownRenderer = memo(function MarkdownRenderer({
content,
+ renderObjectTags = false,
remarkPluginsOverride,
componentsOverride,
rehypePlugins,
@@ -212,20 +280,22 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
() => preprocessMarkdown(content),
[content],
);
- const plugins = remarkPluginsOverride ?? defaultRemarkPlugins;
+ const plugins =
+ remarkPluginsOverride ??
+ (renderObjectTags ? objectTagRemarkPlugins : defaultRemarkPlugins);
+ const base = renderObjectTags ? objectTagComponents : baseComponents;
const components = useMemo(
- () =>
- componentsOverride
- ? { ...baseComponents, ...componentsOverride }
- : baseComponents,
- [componentsOverride],
+ () => (componentsOverride ? { ...base, ...componentsOverride } : base),
+ [componentsOverride, base],
);
return (
<ReactMarkdown
remarkPlugins={plugins}
rehypePlugins={rehypePlugins}
components={components}
- urlTransform={markdownUrlTransform}
+ urlTransform={
+ renderObjectTags ? objectTagUrlTransform : markdownUrlTransform
+ }
>
{processedContent}
</ReactMarkdown>
diff --git a/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.stories.tsx b/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.stories.tsx
new file mode 100644
index 000000000000..c1f23b05903e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.stories.tsx
@@ -0,0 +1,85 @@
+import { chartHeadlineStat } from "@posthog/core/inbox/reportCharts";
+import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
+import { MessageChartCard } from "@posthog/ui/features/editor/components/MessageChartCard";
+import { ReportChartCardView } from "@posthog/ui/features/inbox/components/detail/ReportChartCard";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+
+const meta: Meta<typeof MessageChartCard> = {
+ title: "Features/Editor/MessageChartCard",
+ component: MessageChartCard,
+ parameters: {
+ layout: "padded",
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof MessageChartCard>;
+
+/**
+ * What a resolved chart card looks like: the query ran and came back as a
+ * single series, so the header carries the headline value and step change.
+ * (Storybook has no PostHog session, so the live-query stories below show
+ * the loading state instead.)
+ */
+export const ResolvedCard: Story = {
+ render: () => {
+ const data = {
+ type: "series" as const,
+ render: "line" as const,
+ labels: [
+ "2026-08-07",
+ "2026-08-08",
+ "2026-08-09",
+ "2026-08-10",
+ "2026-08-11",
+ "2026-08-12",
+ "2026-08-13",
+ "2026-08-14",
+ ],
+ series: [
+ {
+ key: "0:DAU",
+ label: "DAU",
+ data: [69650, 39431, 47804, 85174, 83213, 81434, 79541, 17100],
+ },
+ ],
+ isTimeSeries: true,
+ interval: "day" as const,
+ };
+ return (
+ <div className="max-w-xl">
+ <ReportChartCardView
+ chartId="story-resolved"
+ title="Daily active users, last 7 days"
+ caption="The drop on Aug 14 lines up with the checkout deploy."
+ heightClass="h-52"
+ state={{ kind: "data", data }}
+ openTarget={{ url: "https://example.com", label: "Open insight" }}
+ stat={chartHeadlineStat(data)}
+ />
+ </div>
+ );
+ },
+};
+
+export const TagsInsideAgentMessage: Story = {
+ render: () => (
+ <div className="max-w-xl">
+ <MarkdownRenderer
+ content={[
+ "Here's the daily active user count for the last 7 days:",
+ "",
+ '<hogql display="block" title="Daily active users, last 7 days" caption="The drop on Aug 14 lines up with the checkout deploy.">',
+ "SELECT toDate(timestamp) AS day, count(DISTINCT person_id) AS dau",
+ "FROM events WHERE timestamp >= now() - INTERVAL 7 DAY GROUP BY day ORDER BY day",
+ "</hogql>",
+ "",
+ "**Weekday vs. weekend pattern** is very clear, with Mon-Thu holding 79K-85K.",
+ "The same trend as the saved insight:",
+ "",
+ '<insight id="9pQx3" display="block"/>',
+ ].join("\n")}
+ />
+ </div>
+ ),
+};
diff --git a/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.test.tsx b/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.test.tsx
new file mode 100644
index 000000000000..d6e2b9b02662
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.test.tsx
@@ -0,0 +1,85 @@
+import { Theme } from "@radix-ui/themes";
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+// quill-charts is canvas-backed and does not load in the test environment;
+// the card chrome around it is what this test exercises.
+vi.mock("@posthog/quill-charts", () => ({
+ BarChart: () => <div data-testid="chart-plot" />,
+ LineChart: () => <div data-testid="chart-plot" />,
+ TimeSeriesBarChart: () => <div data-testid="chart-plot" />,
+ TimeSeriesLineChart: () => <div data-testid="chart-plot" />,
+ useChartTheme: () => ({}),
+}));
+
+// Chart cards resolve their data through the app shell's query client; here
+// they stay in their loading state, which still proves the dispatch.
+vi.mock("../../../hooks/useAuthenticatedQuery", () => ({
+ useAuthenticatedQuery: () => ({
+ isPending: true,
+ isError: false,
+ isFetched: false,
+ data: undefined,
+ }),
+}));
+
+import { MarkdownRenderer } from "./MarkdownRenderer";
+
+describe("posthog-chart blocks in agent markdown", () => {
+ it("renders a generated chart block as a card instead of a code block", () => {
+ // remarkObjectTags converts block-display tags into marked code nodes;
+ // the code component must parse them into a card and the pre component
+ // must not wrap the card in a code-block shell.
+ render(
+ <Theme>
+ <MarkdownRenderer
+ content={
+ '<hogql display="block" title="Daily active users">\nSELECT 1\n</hogql>\n'
+ }
+ renderObjectTags
+ />
+ </Theme>,
+ );
+ expect(screen.getByTestId("report-chart")).toBeDefined();
+ expect(screen.getByText("Daily active users")).toBeDefined();
+ expect(screen.queryByText(/SELECT 1/)).toBeNull();
+ expect(screen.queryByLabelText("Copy code")).toBeNull();
+ });
+
+ it("leaves ordinary fenced code inside the code-block shell", () => {
+ // The chart dispatch made `pre` conditionally unwrap; a plain fence must
+ // keep its highlighted code-block chrome and never become a chart card.
+ const { container } = render(
+ <Theme>
+ <MarkdownRenderer
+ content={"```ts\nconst a = 1;\n```\n"}
+ renderObjectTags
+ />
+ </Theme>,
+ );
+ // Highlighting splits the code into spans, so match the joined text.
+ expect(container.querySelector("code")?.textContent).toBe("const a = 1;");
+ expect(screen.getByLabelText("Copy code")).toBeDefined();
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ });
+
+ it("keeps a hand-authored posthog-chart fence as code, never a live card", () => {
+ // Only code nodes generated by remarkObjectTags carry the private AST
+ // marker; a literal fence in the markdown text must stay inert, or any
+ // pasted text could run authenticated queries.
+ const { container } = render(
+ <Theme>
+ <MarkdownRenderer
+ content={
+ '```posthog-chart\n{"mode":"hogql","query":"SELECT 1","title":"Daily active users"}\n```\n'
+ }
+ renderObjectTags
+ />
+ </Theme>,
+ );
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ expect(container.querySelector("code")?.textContent).toContain(
+ '"mode":"hogql"',
+ );
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.tsx b/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.tsx
new file mode 100644
index 000000000000..946d682ba47f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/MessageChartCard.tsx
@@ -0,0 +1,187 @@
+import {
+ chartHeadlineStat,
+ planReportChart,
+ type ReportChartData,
+ reportChartHeightClass,
+ reportChartOpenTarget,
+ shapeReportChartData,
+} from "@posthog/core/inbox/reportCharts";
+import { getCloudUrlFromRegion } from "@posthog/shared";
+import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import {
+ type ReportChartCardState,
+ ReportChartCardView,
+} from "@posthog/ui/features/inbox/components/detail/ReportChartCard";
+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
+import type { ChartBlockSpec } from "@posthog/ui/utils/chartBlocks";
+import { useMemo } from "react";
+import { ReplayBlockCard } from "./ReplayBlockCard";
+
+/**
+ * Full-size chart card for a block-display object tag in an agent message
+ * (`<insight display="block"/>` or `<hogql display="block">...`). Renders
+ * through the same card and quill-charts pipeline as report charts, so agent
+ * charts and report charts look and behave identically. Both modes resolve
+ * live at render time; the message stores only the reference or the query.
+ */
+
+const CHART_ERROR_MESSAGE =
+ "Couldn't run the query behind this chart. Open it in PostHog to investigate.";
+
+function useOpenOptions(): { cloudUrl: string; projectId: number } | null {
+ const projectId = useAuthStateValue((state) => state.currentProjectId);
+ const cloudRegion = useAuthStateValue((state) => state.cloudRegion);
+ if (!projectId || !cloudRegion) return null;
+ return { cloudUrl: getCloudUrlFromRegion(cloudRegion), projectId };
+}
+
+function ChartCard({
+ blockKey,
+ title,
+ caption,
+ state,
+ openTarget,
+}: {
+ blockKey: string;
+ title: string;
+ caption?: string;
+ state: ReportChartCardState;
+ openTarget: ReturnType<typeof reportChartOpenTarget>;
+}) {
+ const data = state.kind === "data" ? state.data : null;
+ return (
+ <div className="mb-2">
+ <ReportChartCardView
+ chartId={blockKey}
+ title={title}
+ caption={caption}
+ heightClass={reportChartHeightClass(null, data)}
+ state={state}
+ openTarget={openTarget}
+ stat={data ? chartHeadlineStat(data) : null}
+ />
+ </div>
+ );
+}
+
+function queryState(query: {
+ isPending: boolean;
+ isError: boolean;
+ data: ReportChartData | undefined;
+}): ReportChartCardState {
+ if (query.isPending) return { kind: "loading" };
+ if (query.isError || !query.data)
+ return { kind: "error", message: CHART_ERROR_MESSAGE };
+ return { kind: "data", data: query.data };
+}
+
+function HogqlChartCard({
+ spec,
+ blockKey,
+}: {
+ spec: Extract<ChartBlockSpec, { mode: "hogql" }>;
+ blockKey: string;
+}) {
+ const openOptions = useOpenOptions();
+ const node = useMemo(
+ () => ({
+ kind: "DataVisualizationNode",
+ source: { kind: "HogQLQuery", query: spec.query },
+ }),
+ [spec.query],
+ );
+ const plan = useMemo(() => planReportChart(node), [node]);
+ const query = useAuthenticatedQuery<ReportChartData>(
+ ["message-chart-block", blockKey],
+ async (client) => {
+ if (plan.kind !== "run") return { type: "empty" };
+ const response = await client.runQuery(plan.source);
+ return shapeReportChartData(response, plan);
+ },
+ { staleTime: 5 * 60 * 1000, refetchOnWindowFocus: false, retry: 1 },
+ );
+ return (
+ <ChartCard
+ blockKey={blockKey}
+ title={spec.title ?? "Query result"}
+ caption={spec.caption}
+ state={queryState(query)}
+ openTarget={openOptions ? reportChartOpenTarget(node, openOptions) : null}
+ />
+ );
+}
+
+interface InsightChartResult {
+ name: string | null;
+ data: ReportChartData | null;
+}
+
+function InsightChartCard({
+ spec,
+ blockKey,
+}: {
+ spec: Extract<ChartBlockSpec, { mode: "insight" }>;
+ blockKey: string;
+}) {
+ const openOptions = useOpenOptions();
+ const query = useAuthenticatedQuery<InsightChartResult | null>(
+ ["message-chart-block", blockKey],
+ async (client) => {
+ const insight = await client.getInsightDefinition(spec.shortId);
+ 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);
+ return { name: insight.name, data: shapeReportChartData(response, plan) };
+ },
+ { staleTime: 5 * 60 * 1000, refetchOnWindowFocus: false, retry: 1 },
+ );
+
+ const state: ReportChartCardState =
+ query.isPending || (!query.isError && query.data === undefined)
+ ? { kind: "loading" }
+ : query.isError
+ ? { kind: "error", message: CHART_ERROR_MESSAGE }
+ : query.data === null
+ ? {
+ kind: "error",
+ message: `No insight matches "${spec.shortId}" in the current project.`,
+ }
+ : query.data?.data
+ ? { kind: "data", data: query.data.data }
+ : { kind: "link-out" };
+
+ return (
+ <ChartCard
+ blockKey={blockKey}
+ title={spec.title ?? query.data?.name ?? "Insight"}
+ caption={spec.caption}
+ state={state}
+ openTarget={
+ openOptions
+ ? reportChartOpenTarget(
+ { kind: "SavedInsightNode", shortId: spec.shortId },
+ openOptions,
+ )
+ : null
+ }
+ />
+ );
+}
+
+export function MessageChartCard({
+ spec,
+ blockKey,
+}: {
+ spec: ChartBlockSpec;
+ /** Stable identity for the block, e.g. a hash of its source. */
+ blockKey: string;
+}) {
+ if (spec.mode === "insight") {
+ return <InsightChartCard spec={spec} blockKey={blockKey} />;
+ }
+ if (spec.mode === "replay") {
+ return <ReplayBlockCard spec={spec} />;
+ }
+ return <HogqlChartCard spec={spec} blockKey={blockKey} />;
+}
diff --git a/products/desktop/packages/ui/src/features/editor/components/ReplayBlockCard.test.tsx b/products/desktop/packages/ui/src/features/editor/components/ReplayBlockCard.test.tsx
new file mode 100644
index 000000000000..8e34b8faec1d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/ReplayBlockCard.test.tsx
@@ -0,0 +1,64 @@
+import { Theme } from "@radix-ui/themes";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../shell/openExternal", () => ({
+ openExternalUrl: vi.fn(),
+}));
+vi.mock("../../../hooks/useAuthenticatedQuery", () => ({
+ useAuthenticatedQuery: () => ({
+ isPending: false,
+ isError: false,
+ data: {
+ title: "Session by [email protected]",
+ detail: "12 min · Jan 3",
+ facts: ["42 clicks"],
+ },
+ }),
+}));
+
+import { openExternalUrl } from "../../../shell/openExternal";
+import { ANONYMOUS_AUTH_STATE, useAuthStore } from "../../auth/store";
+import { ReplayBlockCard } from "./ReplayBlockCard";
+
+afterEach(() => {
+ useAuthStore.setState({ authState: ANONYMOUS_AUTH_STATE });
+});
+
+describe("ReplayBlockCard", () => {
+ it("shows the recording and links into PostHog's player, never an embed", () => {
+ useAuthStore.setState({
+ authState: {
+ ...ANONYMOUS_AUTH_STATE,
+ cloudRegion: "us",
+ currentProjectId: 2,
+ },
+ });
+ render(
+ <Theme>
+ <ReplayBlockCard spec={{ mode: "replay", sessionId: "s_01HQ4K" }} />
+ </Theme>,
+ );
+ expect(screen.getByText("Session by [email protected]")).toBeDefined();
+ expect(screen.getByText("42 clicks")).toBeDefined();
+ // Playback stays in PostHog: no iframe, no sharing prompt.
+ expect(document.querySelector("iframe")).toBeNull();
+ expect(screen.queryByText(/link sharing/)).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: /Watch in PostHog/ }));
+ expect(openExternalUrl).toHaveBeenCalledWith(
+ "https://us.posthog.com/project/2/replay/s_01HQ4K",
+ );
+ });
+
+ it("disables the watch button without a project to link into", () => {
+ render(
+ <Theme>
+ <ReplayBlockCard spec={{ mode: "replay", sessionId: "s_01HQ4K" }} />
+ </Theme>,
+ );
+ expect(
+ screen.getByRole("button", { name: /Watch in PostHog/ }),
+ ).toHaveProperty("disabled", true);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/editor/components/ReplayBlockCard.tsx b/products/desktop/packages/ui/src/features/editor/components/ReplayBlockCard.tsx
new file mode 100644
index 000000000000..9bc5ef85197b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/ReplayBlockCard.tsx
@@ -0,0 +1,77 @@
+import { PlayIcon } from "@phosphor-icons/react";
+import { Button } from "@posthog/ui/primitives/Button";
+import { useAuthenticatedQuery } from "../../../hooks/useAuthenticatedQuery";
+import { openExternalUrl } from "../../../shell/openExternal";
+import type { ChartBlockSpec } from "../../../utils/chartBlocks";
+import { fetchEvidencePreview } from "../evidencePreview";
+import { useEvidenceUrl } from "./EvidenceRefChip";
+
+/**
+ * Full-size card for `<replay id="..." display="block"/>`: the recording's
+ * identity and activity, linking into PostHog's player. Playback stays in
+ * PostHog on purpose - the embeddable player requires link sharing, which
+ * makes the recording viewable by anyone with the link.
+ */
+export function ReplayBlockCard({
+ spec,
+}: {
+ spec: Extract<ChartBlockSpec, { mode: "replay" }>;
+}) {
+ const openUrl = useEvidenceUrl("replay", spec.sessionId);
+
+ const metadata = useAuthenticatedQuery(
+ ["evidence-preview", "replay", spec.sessionId],
+ (apiClient) =>
+ fetchEvidencePreview(apiClient, { kind: "replay", id: spec.sessionId }),
+ { staleTime: 5 * 60 * 1000, refetchOnWindowFocus: false, retry: 1 },
+ );
+
+ const preview = metadata.data ?? null;
+ const title = spec.title ?? preview?.title ?? "Session replay";
+
+ return (
+ <figure
+ className="m-0 mb-2 flex flex-col gap-2 rounded-(--radius-2) border border-(--gray-4) bg-(--color-panel-solid) p-3"
+ data-testid="replay-card"
+ >
+ <span className="min-w-0 break-words font-semibold text-[13px] text-gray-12">
+ {title}
+ </span>
+ {(preview?.detail || (preview?.facts?.length ?? 0) > 0) && (
+ <div className="flex flex-wrap items-center gap-1.5">
+ {preview?.detail && (
+ <span className="text-(--gray-10) text-[11.5px]">
+ {preview.detail}
+ </span>
+ )}
+ {preview?.facts?.map((fact) => (
+ <span
+ key={fact}
+ className="max-w-full truncate rounded-[4px] bg-(--gray-a3) px-1.5 py-0.5 text-(--gray-11) text-[10px]"
+ >
+ {fact}
+ </span>
+ ))}
+ </div>
+ )}
+ <div className="flex items-center justify-center rounded-(--radius-1) bg-(--gray-a2) py-8">
+ <Button
+ type="button"
+ variant="soft"
+ color="gray"
+ size="1"
+ disabled={!openUrl}
+ onClick={() => openUrl && openExternalUrl(openUrl)}
+ >
+ <PlayIcon size={12} />
+ Watch in PostHog
+ </Button>
+ </div>
+ {spec.caption && (
+ <figcaption className="m-0 text-[11px] text-gray-10">
+ {spec.caption}
+ </figcaption>
+ )}
+ </figure>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.tsx b/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.tsx
index 07ea1c0d9a00..e24db252289c 100644
--- a/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.tsx
@@ -10,6 +10,9 @@ import {
interface StreamingMarkdownProps {
content: string;
+ /** See {@link MarkdownRenderer}: only trusted agent-authored surfaces may
+ * enable object tags, because they execute authenticated queries. */
+ renderObjectTags?: boolean;
componentsOverride?: Partial<Components>;
}
@@ -28,6 +31,7 @@ interface StreamingMarkdownProps {
*/
export const StreamingMarkdown = memo(function StreamingMarkdown({
content,
+ renderObjectTags,
componentsOverride,
}: StreamingMarkdownProps) {
const blocks = useMemo(() => splitMarkdownBlocks(content), [content]);
@@ -44,6 +48,7 @@ export const StreamingMarkdown = memo(function StreamingMarkdown({
{openFence.before.trim() ? (
<MarkdownRenderer
content={openFence.before}
+ renderObjectTags={renderObjectTags}
componentsOverride={componentsOverride}
/>
) : null}
@@ -59,6 +64,7 @@ export const StreamingMarkdown = memo(function StreamingMarkdown({
content={
index === lastIndex ? maskOpenLinkDestination(block) : block
}
+ renderObjectTags={renderObjectTags}
componentsOverride={componentsOverride}
/>
);
diff --git a/products/desktop/packages/ui/src/features/editor/evidencePreview.test.ts b/products/desktop/packages/ui/src/features/editor/evidencePreview.test.ts
new file mode 100644
index 000000000000..332a9b755784
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreview.test.ts
@@ -0,0 +1,96 @@
+import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";
+import { describe, expect, it, vi } from "vitest";
+import { fetchEvidencePreview } from "./evidencePreview";
+
+function fakeClient(overrides: Record<string, unknown>): PostHogAPIClient {
+ return overrides as unknown as PostHogAPIClient;
+}
+
+describe("fetchEvidencePreview", () => {
+ it("reduces a hogql time series to a headline and sparkline", async () => {
+ const client = fakeClient({
+ runQuery: vi.fn().mockResolvedValue({
+ columns: ["day", "active_users"],
+ results: [
+ ["2026-08-13", 5096547],
+ ["2026-08-14", 1506301],
+ ],
+ }),
+ });
+ const preview = await fetchEvidencePreview(client, {
+ kind: "hogql",
+ id: "SELECT ...",
+ });
+ expect(preview).toMatchObject({
+ title: "active_users",
+ headline: { value: "1.5M", delta: { direction: "down" } },
+ spark: { points: [5096547, 1506301], render: "line" },
+ });
+ });
+
+ it("shows a single-cell hogql result as its value", async () => {
+ const client = fakeClient({
+ runQuery: vi.fn().mockResolvedValue({
+ columns: ["count"],
+ results: [[68831577]],
+ }),
+ });
+ const preview = await fetchEvidencePreview(client, {
+ kind: "hogql",
+ id: "SELECT count() FROM events",
+ });
+ expect(preview).toMatchObject({ title: "68,831,577" });
+ });
+
+ it("runs a saved insight's query and keeps the insight's name as the title", async () => {
+ const client = fakeClient({
+ getInsightDefinition: vi.fn().mockResolvedValue({
+ name: "Checkout funnel",
+ description: null,
+ query: {
+ kind: "InsightVizNode",
+ source: { kind: "TrendsQuery" },
+ },
+ }),
+ runQuery: vi.fn().mockResolvedValue({
+ results: [
+ {
+ label: "DAU",
+ days: ["2026-08-13", "2026-08-14"],
+ data: [5096547, 1506301],
+ },
+ ],
+ }),
+ });
+ const preview = await fetchEvidencePreview(client, {
+ kind: "insight",
+ id: "9pQx3",
+ });
+ expect(preview).toMatchObject({
+ title: "Checkout funnel",
+ spark: { points: [5096547, 1506301] },
+ });
+ });
+
+ it("returns null for an insight id that does not resolve", async () => {
+ const client = fakeClient({
+ getInsightDefinition: vi.fn().mockResolvedValue(null),
+ });
+ expect(
+ await fetchEvidencePreview(client, { kind: "insight", id: "nope" }),
+ ).toBeNull();
+ });
+
+ it("delegates object kinds to the client's preview lookup", async () => {
+ const getEvidencePreview = vi
+ .fn()
+ .mockResolvedValue({ title: "new-checkout-flow", detail: "Enabled" });
+ const client = fakeClient({ getEvidencePreview });
+ const preview = await fetchEvidencePreview(client, {
+ kind: "flag",
+ id: "42",
+ });
+ expect(getEvidencePreview).toHaveBeenCalledWith("flag", "42");
+ expect(preview).toMatchObject({ title: "new-checkout-flow" });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
new file mode 100644
index 000000000000..38bf6c8d5795
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
@@ -0,0 +1,117 @@
+import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";
+import {
+ type ChartHeadlineStat,
+ chartHeadlineStat,
+ planReportChart,
+ type ReportChartData,
+ shapeReportChartData,
+} from "@posthog/core/inbox/reportCharts";
+import type { EvidenceLinkTarget } from "../../utils/evidenceLinks";
+
+/**
+ * What the evidence hover card shows for a resolved reference. Built lazily
+ * when the card mounts: object kinds resolve their live name and status,
+ * query-backed kinds (hogql, insight) run their query and reduce the result
+ * to a headline and a sparkline.
+ */
+export interface EvidenceCardData {
+ title: string;
+ detail?: string;
+ /** Short scannable attributes, e.g. "100% rollout" or "42 clicks". */
+ facts?: 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" };
+ /** Canonical id when it differs from the cited one (a flag cited by key). */
+ resolvedId?: string;
+}
+
+const MAX_SPARK_POINTS = 60;
+
+/** Reduce a shaped chart result to the card's headline + sparkline. */
+function fromChartData(
+ data: ReportChartData,
+ fallbackTitle: string,
+): EvidenceCardData {
+ if (data.type === "number") {
+ return { title: data.value.toLocaleString("en-US") };
+ }
+ if (data.type === "series" && data.series.length > 0) {
+ const primary = data.series[0];
+ return {
+ title: primary.label,
+ detail:
+ data.series.length > 1
+ ? data.series.map((entry) => entry.label).join(" · ")
+ : undefined,
+ headline: chartHeadlineStat(data),
+ spark: {
+ points: primary.data.slice(-MAX_SPARK_POINTS),
+ render: data.render,
+ },
+ };
+ }
+ if (data.type === "table") {
+ return {
+ title: `${data.rows.length.toLocaleString("en-US")} ${data.rows.length === 1 ? "row" : "rows"}`,
+ detail: data.columns.join(", ") || undefined,
+ };
+ }
+ return { title: fallbackTitle };
+}
+
+async function hogqlPreview(
+ client: PostHogAPIClient,
+ query: string,
+): Promise<EvidenceCardData> {
+ const source = { kind: "HogQLQuery", query };
+ const response = await client.runQuery(source);
+ const data = shapeReportChartData(response, {
+ kind: "run",
+ source,
+ render: "auto",
+ });
+ const preview = fromChartData(data, "No result");
+ if (data.type === "series" && preview.spark) {
+ return {
+ ...preview,
+ facts: [`${data.labels.length} rows · ${data.series.length + 1} columns`],
+ };
+ }
+ return preview;
+}
+
+async function insightPreview(
+ client: PostHogAPIClient,
+ shortId: string,
+): Promise<EvidenceCardData | null> {
+ const insight = await client.getInsightDefinition(shortId);
+ if (!insight) return null;
+ const base: EvidenceCardData = {
+ title: insight.name || shortId,
+ detail: insight.description || undefined,
+ };
+ const plan = planReportChart(insight.query);
+ if (plan.kind !== "run") return base;
+ const response = await client.runQuery(plan.source);
+ const chart = fromChartData(shapeReportChartData(response, plan), base.title);
+ return { ...chart, title: base.title, detail: chart.detail ?? base.detail };
+}
+
+/**
+ * Resolve the live preview behind an evidence reference. Returns null when
+ * there is nothing to show, so the card falls back to its static form.
+ */
+export async function fetchEvidencePreview(
+ client: PostHogAPIClient,
+ target: EvidenceLinkTarget,
+): Promise<EvidenceCardData | null> {
+ if (target.kind === "hogql") {
+ return hogqlPreview(client, target.id);
+ }
+ if (target.kind === "insight") {
+ return insightPreview(client, target.id);
+ }
+ return client.getEvidencePreview(target.kind, target.id);
+}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/ReportChartCard.tsx b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportChartCard.tsx
index 493e530c199f..0b8ad06d9587 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/detail/ReportChartCard.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportChartCard.tsx
@@ -1,5 +1,6 @@
import { ArrowSquareOutIcon } from "@phosphor-icons/react";
import {
+ type ChartHeadlineStat,
planReportChart,
type ReportChartData,
type ReportChartOpenTarget,
@@ -157,6 +158,8 @@ interface ReportChartCardViewProps {
state: ReportChartCardState;
openTarget: ReportChartOpenTarget | null;
onOpenExternal?: (url: string) => void;
+ /** Latest value + step change, shown on the right of the header. */
+ stat?: ChartHeadlineStat | null;
}
/** Pure card; the container resolves the query, plan, and open target. */
@@ -168,6 +171,7 @@ export function ReportChartCardView({
state,
openTarget,
onOpenExternal = openExternalUrl,
+ stat,
}: ReportChartCardViewProps) {
const body = (() => {
switch (state.kind) {
@@ -229,6 +233,26 @@ export function ReportChartCardView({
<span className="min-w-0 break-words font-semibold text-[13px] text-gray-12">
{title}
</span>
+ {stat && (
+ <span
+ className="flex shrink-0 items-baseline gap-1.5"
+ data-testid="chart-headline-stat"
+ >
+ <span className="font-semibold text-[17px] text-gray-12 tabular-nums leading-none">
+ {stat.value}
+ </span>
+ {stat.delta && (
+ // The delta carries no metric polarity, so a rise here isn't
+ // necessarily good (errors, latency, cost all land in these
+ // cards). Stay neutral and let the arrow convey direction alone,
+ // matching how the main app leaves an unlabelled change uncolored.
+ <span className="font-medium text-(--gray-11) text-[11px] tabular-nums">
+ {stat.delta.direction === "up" ? "▲" : "▼"}
+ {stat.delta.label}
+ </span>
+ )}
+ </span>
+ )}
{openTarget && (
<Button
type="button"
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.test.tsx
index 6720911c6cd2..cf3956680910 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.test.tsx
@@ -1,5 +1,17 @@
import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
+
+// Chart cards resolve their data through the app shell's query client; here
+// they stay in their loading state, which is all the dispatch tests need.
+vi.mock("../../../../hooks/useAuthenticatedQuery", () => ({
+ useAuthenticatedQuery: () => ({
+ isPending: true,
+ isError: false,
+ isFetched: false,
+ data: undefined,
+ }),
+}));
+
import { ChatMarkdown, ChatStreamingMarkdown } from "./ChatMarkdown";
describe("ChatMarkdown", () => {
@@ -31,6 +43,51 @@ Verdict: valid.
});
});
+describe("ChatMarkdown object tags", () => {
+ // The chat thread has its own sanitized renderer, which silently dropped
+ // object tags while the session view rendered them; these lock the thread
+ // to the same tag support.
+ it("renders an inline object tag as a reference chip", () => {
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ content={'The <insight id="9pQx3">checkout funnel</insight> dropped.'}
+ renderObjectTags
+ />,
+ );
+ expect(html).toContain("checkout funnel");
+ expect(html).not.toContain("&lt;insight");
+ // The chip's kind icon renders beside the label; a plain drop would not.
+ expect(html).toContain("<svg");
+ });
+
+ it("renders a block hogql tag as a chart card, not code or raw text", () => {
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ content={
+ '<hogql display="block" title="DAU, last 7 days">SELECT 1</hogql>'
+ }
+ renderObjectTags
+ />,
+ );
+ expect(html).toContain("report-chart");
+ expect(html).toContain("DAU, last 7 days");
+ expect(html).not.toContain("SELECT 1");
+ });
+
+ it("does not run object tags in untrusted content by default", () => {
+ // User bubbles and other non-agent surfaces render without the opt-in;
+ // their tags must never resolve to live queries or chart cards.
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ content={
+ '<hogql display="block" title="DAU">SELECT 1</hogql>\n\n```posthog-chart\n{"mode":"hogql","query":"SELECT 1"}\n```'
+ }
+ />,
+ );
+ expect(html).not.toContain("report-chart");
+ });
+});
+
describe("ChatStreamingMarkdown", () => {
it("shows a pending link without exposing its incomplete destination", () => {
const html = renderToStaticMarkup(
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx
index 9adfdc23f653..1c76f02feda1 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx
@@ -11,6 +11,8 @@ import {
Text,
} from "@posthog/quill";
import { ArtifactRefChip } from "@posthog/ui/features/editor/components/ArtifactRefChip";
+import { EvidenceRefChip } from "@posthog/ui/features/editor/components/EvidenceRefChip";
+import { MessageChartCard } from "@posthog/ui/features/editor/components/MessageChartCard";
import {
markOpenLinkDestination,
parseOpenFence,
@@ -25,11 +27,20 @@ import {
import { HighlightedCode } from "@posthog/ui/primitives/HighlightedCode";
import { useCopy } from "@posthog/ui/primitives/useCopy";
import { parseArtifactLink } from "@posthog/ui/utils/artifactLinks";
+import {
+ CHART_BLOCK_MARKER,
+ chartBlockKey,
+ isGeneratedChartBlock,
+ parseChartBlock,
+} from "@posthog/ui/utils/chartBlocks";
+import { parseEvidenceLink } from "@posthog/ui/utils/evidenceLinks";
+import { remarkObjectTags } from "@posthog/ui/utils/remarkObjectTags";
import { IconButton } from "@radix-ui/themes";
import { memo, type ReactNode, useMemo } from "react";
-import Markdown, { type Components } from "react-markdown";
-import rehypeSanitize from "rehype-sanitize";
+import Markdown, { type Components, defaultUrlTransform } from "react-markdown";
+import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import remarkGfm from "remark-gfm";
+import type { PluggableList } from "unified";
const PENDING_LINK_DESTINATION = "#posthog-streaming-link";
@@ -83,6 +94,12 @@ const components: Components = {
</output>
);
}
+ const evidenceTarget = parseEvidenceLink(href);
+ if (evidenceTarget) {
+ return (
+ <EvidenceRefChip target={evidenceTarget}>{children}</EvidenceRefChip>
+ );
+ }
const link = (
<a
href={href}
@@ -115,9 +132,19 @@ const components: Components = {
</ol>
),
li: ({ children }) => <li className="text-sm">{children}</li>,
- code: ({ className, children }) => {
+ code: ({ className, children, node }) => {
const text = String(children).replace(/\n$/, "");
- const match = /language-(\w+)/.exec(className ?? "");
+ const match = /language-([\w-]+)/.exec(className ?? "");
+ // Block-display object tags normalize to posthog-chart code nodes (see
+ // remarkObjectTags); they render as chart cards, not code. Dispatch
+ // requires the plugin's private AST marker so a hand-authored fence stays
+ // inert. Malformed or half-streamed specs render nothing rather than raw
+ // JSON.
+ if (isGeneratedChartBlock(node)) {
+ const spec = parseChartBlock(text);
+ if (!spec) return null;
+ return <MessageChartCard spec={spec} blockKey={chartBlockKey(text)} />;
+ }
// Fenced blocks (carry a language, or span multiple lines) render as a boxed, copyable
// block; short inline spans stay inline. `pre` below is a passthrough so the box lives here,
// where the raw code string is in hand.
@@ -183,19 +210,56 @@ const components: Components = {
td: ({ children }) => <TableCell>{children}</TableCell>,
};
-const remarkPlugins = [remarkGfm];
-const rehypePlugins = [rehypeSanitize];
+// The internal `evidence:` hrefs never reach the DOM (the `a` component
+// renders them as chips), but they must survive react-markdown's default
+// transform, which empties unknown protocols.
+function chatUrlTransform(value: string, key: string): string {
+ if (key === "href" && value.startsWith("evidence:")) return value;
+ return defaultUrlTransform(value);
+}
+
+const remarkPlugins: PluggableList = [remarkGfm];
+const objectTagRemarkPlugins: PluggableList = [remarkGfm, remarkObjectTags];
+// The default sanitize schema, plus what remarkObjectTags emits: the internal
+// `evidence:` reference links (they never reach the DOM as hrefs; the `a`
+// component renders them as chips) and the private marker on generated chart
+// code nodes (unforgeable from text, since raw HTML is never parsed here).
+const rehypePlugins: PluggableList = [
+ [
+ rehypeSanitize,
+ {
+ ...defaultSchema,
+ attributes: {
+ ...defaultSchema.attributes,
+ code: [...(defaultSchema.attributes?.code ?? []), CHART_BLOCK_MARKER],
+ },
+ protocols: {
+ ...defaultSchema.protocols,
+ href: [...(defaultSchema.protocols?.href ?? []), "evidence"],
+ },
+ },
+ ],
+];
+
+interface ChatMarkdownProps {
+ content: string;
+ /** See MarkdownRenderer: only trusted agent-authored surfaces may enable
+ * object tags, because they execute authenticated queries. */
+ renderObjectTags?: boolean;
+}
export const ChatMarkdown = memo(function ChatMarkdown({
content,
-}: {
- content: string;
-}) {
+ renderObjectTags = false,
+}: ChatMarkdownProps) {
return (
<div className="flex flex-col gap-3 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
<Markdown
- remarkPlugins={remarkPlugins}
+ remarkPlugins={
+ renderObjectTags ? objectTagRemarkPlugins : remarkPlugins
+ }
rehypePlugins={rehypePlugins}
+ urlTransform={renderObjectTags ? chatUrlTransform : defaultUrlTransform}
components={components}
>
{content}
@@ -216,9 +280,8 @@ export const ChatMarkdown = memo(function ChatMarkdown({
*/
export const ChatStreamingMarkdown = memo(function ChatStreamingMarkdown({
content,
-}: {
- content: string;
-}) {
+ renderObjectTags,
+}: ChatMarkdownProps) {
const blocks = useMemo(() => splitMarkdownBlocks(content), [content]);
const lastIndex = blocks.length - 1;
@@ -231,7 +294,10 @@ export const ChatStreamingMarkdown = memo(function ChatStreamingMarkdown({
return (
<div key={key} className="flex flex-col gap-3">
{openFence.before.trim() ? (
- <ChatMarkdown content={openFence.before} />
+ <ChatMarkdown
+ content={openFence.before}
+ renderObjectTags={renderObjectTags}
+ />
) : null}
<ChatCodeBlock code={openFence.code}>
<code className="font-mono text-xs">{openFence.code}</code>
@@ -247,6 +313,7 @@ export const ChatStreamingMarkdown = memo(function ChatStreamingMarkdown({
? markOpenLinkDestination(block, PENDING_LINK_DESTINATION)
: block
}
+ renderObjectTags={renderObjectTags}
/>
);
})}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
index b1720274fb1a..93313098cbf0 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
@@ -734,9 +734,9 @@ const AgentProse = memo(function AgentProse({
<ChatBubble variant="ghost">
<ChatBubbleContent>
{isStreaming ? (
- <ChatStreamingMarkdown content={smoothed} />
+ <ChatStreamingMarkdown content={smoothed} renderObjectTags />
) : (
- <ChatMarkdown content={text} />
+ <ChatMarkdown content={text} renderObjectTags />
)}
</ChatBubbleContent>
</ChatBubble>
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/AgentMessage.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/AgentMessage.tsx
index 56f13bb11ae6..c89b63cec10d 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/AgentMessage.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/AgentMessage.tsx
@@ -74,11 +74,13 @@ export const AgentMessage = memo(function AgentMessage({
{isStreaming ? (
<StreamingMarkdown
content={smoothed}
+ renderObjectTags
componentsOverride={agentComponents}
/>
) : (
<MarkdownRenderer
content={content}
+ renderObjectTags
componentsOverride={agentComponents}
/>
)}
diff --git a/products/desktop/packages/ui/src/utils/chartBlocks.test.ts b/products/desktop/packages/ui/src/utils/chartBlocks.test.ts
new file mode 100644
index 000000000000..9a8a2beb5d9c
--- /dev/null
+++ b/products/desktop/packages/ui/src/utils/chartBlocks.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vitest";
+import { chartBlockKey, parseChartBlock } from "./chartBlocks";
+
+describe("chartBlocks", () => {
+ it("parses an insight reference", () => {
+ expect(
+ parseChartBlock('{"mode":"insight","shortId":"9pQx3","title":"DAU"}'),
+ ).toEqual({
+ mode: "insight",
+ shortId: "9pQx3",
+ title: "DAU",
+ caption: undefined,
+ });
+ });
+
+ it("parses a hogql query with title and caption", () => {
+ expect(
+ parseChartBlock(
+ '{"mode":"hogql","query":"SELECT 1","title":"T","caption":"C"}',
+ ),
+ ).toEqual({ mode: "hogql", query: "SELECT 1", title: "T", caption: "C" });
+ });
+
+ it("caps a runaway title so it cannot flood the card", () => {
+ const spec = parseChartBlock(
+ `{"mode":"hogql","query":"SELECT 1","title":"${"x".repeat(400)}"}`,
+ );
+ expect(spec?.title?.length).toBe(120);
+ });
+
+ it("parses a replay reference", () => {
+ expect(parseChartBlock('{"mode":"replay","sessionId":"s_01HQ4K"}')).toEqual(
+ {
+ mode: "replay",
+ sessionId: "s_01HQ4K",
+ title: undefined,
+ caption: undefined,
+ },
+ );
+ });
+
+ it.each([
+ ["malformed JSON", '{"mode":"hogql","query":'],
+ ["unknown mode", '{"mode":"data","series":[]}'],
+ ["insight without an id", '{"mode":"insight"}'],
+ ["hogql without a query", '{"mode":"hogql","query":" "}'],
+ ["non-object payload", '"SELECT 1"'],
+ ])("returns null for %s", (_name, source) => {
+ expect(parseChartBlock(source)).toBeNull();
+ });
+
+ it("keys equal sources identically and different sources apart", () => {
+ const a = '{"mode":"hogql","query":"SELECT 1"}';
+ const b = '{"mode":"hogql","query":"SELECT 2"}';
+ expect(chartBlockKey(a)).toBe(chartBlockKey(a));
+ expect(chartBlockKey(a)).not.toBe(chartBlockKey(b));
+ });
+});
diff --git a/products/desktop/packages/ui/src/utils/chartBlocks.ts b/products/desktop/packages/ui/src/utils/chartBlocks.ts
new file mode 100644
index 000000000000..105aaa9cd990
--- /dev/null
+++ b/products/desktop/packages/ui/src/utils/chartBlocks.ts
@@ -0,0 +1,87 @@
+/**
+ * The internal spec for full-size chart cards in agent messages.
+ *
+ * Agents author charts as block-display object tags (see remarkObjectTags):
+ *
+ * <insight id="9pQx3" display="block"/>
+ * <hogql display="block" title="DAU, last 7 days">SELECT ...</hogql>
+ *
+ * The plugin normalizes those into a `posthog-chart` code node whose body is
+ * this JSON spec; the markdown renderer draws it as a chart card instead of
+ * highlighted code. A chart is always a reference (a saved insight) or a
+ * query - never inline data - so every render resolves live and transcripts
+ * never store a stale copy of the numbers.
+ */
+
+/**
+ * hast property remarkObjectTags stamps on the chart code nodes it generates.
+ * Chart-card dispatch requires it, so only plugin-generated blocks resolve to
+ * live queries: markdown text cannot set AST data, and the sanitize schemas on
+ * raw-HTML surfaces strip `data-*` from `code`, so a hand-authored
+ * ```posthog-chart fence or literal `<code data-posthog-chart>` stays inert.
+ */
+export const CHART_BLOCK_MARKER = "dataPosthogChart";
+
+/** True when a hast `code` element carries the {@link CHART_BLOCK_MARKER}. */
+export function isGeneratedChartBlock(node: unknown): boolean {
+ if (typeof node !== "object" || node === null) return false;
+ const properties = (node as { properties?: Record<string, unknown> })
+ .properties;
+ return properties?.[CHART_BLOCK_MARKER] != null;
+}
+
+const MAX_TITLE_LENGTH = 120;
+const MAX_CAPTION_LENGTH = 300;
+const MAX_QUERY_LENGTH = 20_000;
+
+export type ChartBlockSpec =
+ | { mode: "insight"; shortId: string; title?: string; caption?: string }
+ | { mode: "hogql"; query: string; title?: string; caption?: string }
+ | { mode: "replay"; sessionId: string; title?: string; caption?: string };
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function capText(value: unknown, max: number): string | undefined {
+ return typeof value === "string" && value.trim()
+ ? value.trim().slice(0, max)
+ : undefined;
+}
+
+/** Stable identity for a block: keys React elements and the query cache. */
+export function chartBlockKey(source: string): string {
+ let hash = 5381;
+ for (let i = 0; i < source.length; i++) {
+ hash = ((hash << 5) + hash + source.charCodeAt(i)) | 0;
+ }
+ return `chart-block-${(hash >>> 0).toString(36)}`;
+}
+
+/** Parse a `posthog-chart` node body into a spec, or null when malformed. */
+export function parseChartBlock(source: string): ChartBlockSpec | null {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(source);
+ } catch {
+ return null;
+ }
+ if (!isRecord(raw)) return null;
+
+ const title = capText(raw.title, MAX_TITLE_LENGTH);
+ const caption = capText(raw.caption, MAX_CAPTION_LENGTH);
+
+ if (raw.mode === "insight") {
+ const shortId = capText(raw.shortId, 64);
+ return shortId ? { mode: "insight", shortId, title, caption } : null;
+ }
+ if (raw.mode === "hogql") {
+ const query = capText(raw.query, MAX_QUERY_LENGTH);
+ return query ? { mode: "hogql", query, title, caption } : null;
+ }
+ if (raw.mode === "replay") {
+ const sessionId = capText(raw.sessionId, 200);
+ return sessionId ? { mode: "replay", sessionId, title, caption } : null;
+ }
+ return null;
+}
diff --git a/products/desktop/packages/ui/src/utils/evidenceLinks.test.ts b/products/desktop/packages/ui/src/utils/evidenceLinks.test.ts
new file mode 100644
index 000000000000..d7b9efe8334e
--- /dev/null
+++ b/products/desktop/packages/ui/src/utils/evidenceLinks.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+import { evidenceWebPath, parseEvidenceLink } from "./evidenceLinks";
+
+describe("evidenceLinks", () => {
+ it.each([
+ ["evidence:insight/9pQx3", { kind: "insight", id: "9pQx3" }],
+ ["evidence:error/018f-44aa", { kind: "error", id: "018f-44aa" }],
+ ["evidence:custom-kind/abc_123", { kind: "custom-kind", id: "abc_123" }],
+ ["evidence:flag/my%2Fflag", { kind: "flag", id: "my/flag" }],
+ ])("parses %s", (href, expected) => {
+ expect(parseEvidenceLink(href)).toEqual(expected);
+ });
+
+ it("ignores query params so links from older transcripts still resolve", () => {
+ expect(
+ parseEvidenceLink(
+ "evidence:insight/9pQx3?value=28.1%25&desc=down&series=1,2&url=https%3A%2F%2Fexample.com",
+ ),
+ ).toEqual({ kind: "insight", id: "9pQx3" });
+ });
+
+ it.each([
+ [undefined],
+ ["https://example.com/evidence:insight/x"],
+ ["evidence:"],
+ ["evidence:insight"],
+ ["evidence:insight/"],
+ ["evidence:/9pQx3"],
+ ["evidence:Insight/9pQx3"],
+ ["chart:9pQx3"],
+ ])("returns null for %s", (href) => {
+ expect(parseEvidenceLink(href)).toBeNull();
+ });
+
+ it.each([
+ ["insight", "9pQx3", "/insights/9pQx3"],
+ ["dashboard", "12", "/dashboard/12"],
+ ["error", "018f-44aa", "/error_tracking/018f-44aa"],
+ ["replay", "s_01HQ4K", "/replay/s_01HQ4K"],
+ ["flag", "42", "/feature_flags/42"],
+ ["experiment", "7", "/experiments/7"],
+ ["survey", "srv-11", "/surveys/srv-11"],
+ ["ticket", "conv_88", "/support/tickets/conv_88"],
+ ["trace", "t_9f2ab4", "/ai-observability/traces/t_9f2ab4"],
+ ["eval", "ev_faith", "/ai-evals/evaluations/ev_faith"],
+ ["cohort", "31", "/cohorts/31"],
+ ["action", "5", "/data-management/actions/5"],
+ ["person", "0192-aaaa", "/persons/0192-aaaa"],
+ ["hogql", "SELECT 1", "/sql?open_query=SELECT%201"],
+ // Flag pages only resolve by numeric id, so a key gets no direct URL.
+ ["flag", "my-flag-key", null],
+ // Kinds without a canonical object page.
+ ["event", "cart_saved", null],
+ ["something-new", "x1", null],
+ ])("maps %s/%s to %s", (kind, id, expected) => {
+ expect(evidenceWebPath(kind, id)).toBe(expected);
+ });
+
+ it("URL-encodes the id in the web path", () => {
+ expect(evidenceWebPath("insight", "a/b c")).toBe("/insights/a%2Fb%20c");
+ });
+});
diff --git a/products/desktop/packages/ui/src/utils/evidenceLinks.ts b/products/desktop/packages/ui/src/utils/evidenceLinks.ts
new file mode 100644
index 000000000000..163f201463da
--- /dev/null
+++ b/products/desktop/packages/ui/src/utils/evidenceLinks.ts
@@ -0,0 +1,59 @@
+import { getObjectKind } from "./objectKinds";
+
+/**
+ * The internal `evidence:<kind>/<id>` href form for object references inside
+ * agent messages. Agents author references as `<kind id="...">` tags (see
+ * remarkObjectTags), which normalize to link nodes with this scheme; the
+ * scheme survives `markdownUrlTransform` (like `chart:` links do) and the
+ * markdown `a` component renders it as an inline reference chip.
+ *
+ * The reference carries no data. Names, status, and the open-in-PostHog URL
+ * are resolved live when the reference is shown, so transcripts never embed
+ * a stale copy of the data. For `hogql` references the id is the SQL itself.
+ */
+
+const EVIDENCE_SCHEME = "evidence:";
+const KIND_ID_RE = /^([a-z][a-z0-9-]*)\/([^/?#]+)$/;
+
+export interface EvidenceLinkTarget {
+ /** Free-form kind slug; well-known kinds get a dedicated icon and source label. */
+ kind: string;
+ id: string;
+}
+
+function decodePart(part: string): string {
+ try {
+ return decodeURIComponent(part);
+ } catch {
+ return part;
+ }
+}
+
+/**
+ * Parse an `evidence:` href into a target, or null when it isn't one.
+ * A query string is tolerated and ignored: earlier links carried display
+ * params, and the reference alone identifies the object.
+ */
+export function parseEvidenceLink(
+ href: string | undefined,
+): EvidenceLinkTarget | null {
+ if (!href || !href.startsWith(EVIDENCE_SCHEME)) return null;
+
+ const rest = href.slice(EVIDENCE_SCHEME.length);
+ const queryIndex = rest.indexOf("?");
+ const path = queryIndex === -1 ? rest : rest.slice(0, queryIndex);
+
+ const match = KIND_ID_RE.exec(path);
+ if (!match) return null;
+
+ return { kind: match[1], id: decodePart(match[2]) };
+}
+
+/**
+ * Project-relative PostHog web path for an evidence target, or null when the
+ * kind has no canonical page to open. Paths come from the kind registry.
+ */
+export function evidenceWebPath(kind: string, id: string): string | null {
+ const build = getObjectKind(kind).webPath;
+ return build ? build(encodeURIComponent(id), id) : null;
+}
diff --git a/products/desktop/packages/ui/src/utils/objectKinds.ts b/products/desktop/packages/ui/src/utils/objectKinds.ts
new file mode 100644
index 000000000000..e2fd3ac5ca55
--- /dev/null
+++ b/products/desktop/packages/ui/src/utils/objectKinds.ts
@@ -0,0 +1,174 @@
+import {
+ BugIcon,
+ ChartLineIcon,
+ ChatCircleTextIcon,
+ ClipboardTextIcon,
+ CursorClickIcon,
+ DatabaseIcon,
+ FlagIcon,
+ FlaskIcon,
+ type Icon,
+ LightningIcon,
+ PlayCircleIcon,
+ PulseIcon,
+ ShieldCheckIcon,
+ SparkleIcon,
+ SquaresFourIcon,
+ UserIcon,
+ UsersThreeIcon,
+} from "@phosphor-icons/react";
+
+/**
+ * The registry of PostHog object kinds an agent can embed in a message as
+ * `<kind id="...">label</kind>` tags (see remarkObjectTags).
+ *
+ * Adding a kind here is all it takes for the inline chip: icon, labels, and
+ * the click-through URL. Two opt-ins live elsewhere:
+ * - a live hover preview needs a case in `PostHogAPIClient.getEvidencePreview`
+ * - `block: true` needs a card renderer in `MessageChartCard`
+ */
+export interface ObjectKindDef {
+ icon: Icon;
+ /** Human name of the kind, e.g. "Insight". */
+ kindLabel: string;
+ /** Product the object comes from, e.g. "Product analytics". */
+ source: string;
+ /**
+ * Project-relative PostHog web path, mirroring the canonical route table
+ * (the `generate-app-url` MCP tool carries the same list). Return null when
+ * this id has no direct page; omit when the kind has no canonical page.
+ */
+ webPath?: (encodedId: string, rawId: string) => string | null;
+ /** Renders as a full chart card when the tag says display="block". */
+ block?: boolean;
+}
+
+export const OBJECT_KINDS: Record<string, ObjectKindDef> = {
+ insight: {
+ icon: ChartLineIcon,
+ kindLabel: "Insight",
+ source: "Product analytics",
+ webPath: (id) => `/insights/${id}`,
+ block: true,
+ },
+ // For hogql the "id" is the SQL itself; the chip opens the SQL editor and
+ // the hover card runs the query live.
+ hogql: {
+ icon: DatabaseIcon,
+ kindLabel: "SQL query",
+ source: "SQL editor",
+ webPath: (id) => `/sql?open_query=${id}`,
+ block: true,
+ },
+ dashboard: {
+ icon: SquaresFourIcon,
+ kindLabel: "Dashboard",
+ source: "Product analytics",
+ webPath: (id) => `/dashboard/${id}`,
+ },
+ error: {
+ icon: BugIcon,
+ kindLabel: "Error issue",
+ source: "Error tracking",
+ webPath: (id) => `/error_tracking/${id}`,
+ },
+ replay: {
+ icon: PlayCircleIcon,
+ kindLabel: "Session replay",
+ source: "Session replay",
+ webPath: (id) => `/replay/${id}`,
+ block: true,
+ },
+ flag: {
+ icon: FlagIcon,
+ kindLabel: "Feature flag",
+ source: "Feature flags",
+ // Flag pages only resolve by numeric id, so a flag cited by key gets no
+ // direct URL (its hover preview still resolves through the list search).
+ webPath: (id, raw) => (/^\d+$/.test(raw) ? `/feature_flags/${id}` : null),
+ },
+ experiment: {
+ icon: FlaskIcon,
+ kindLabel: "Experiment",
+ source: "Experiments",
+ webPath: (id) => `/experiments/${id}`,
+ },
+ survey: {
+ icon: ClipboardTextIcon,
+ kindLabel: "Survey",
+ source: "Surveys",
+ webPath: (id) => `/surveys/${id}`,
+ },
+ ticket: {
+ icon: ChatCircleTextIcon,
+ kindLabel: "Support tickets",
+ source: "Conversations",
+ webPath: (id) => `/support/tickets/${id}`,
+ },
+ trace: {
+ icon: SparkleIcon,
+ kindLabel: "LLM trace",
+ source: "AI observability",
+ webPath: (id) => `/ai-observability/traces/${id}`,
+ },
+ eval: {
+ icon: ShieldCheckIcon,
+ kindLabel: "Evaluation",
+ source: "AI evals",
+ webPath: (id) => `/ai-evals/evaluations/${id}`,
+ },
+ event: {
+ icon: LightningIcon,
+ kindLabel: "Events",
+ source: "Product analytics",
+ // Cited by name; the page needs the definition id, which the hover
+ // preview resolves (resolvedId) before the card can link out.
+ webPath: (id, raw) =>
+ /^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(raw)
+ ? `/data-management/events/${id}`
+ : null,
+ },
+ cohort: {
+ icon: UsersThreeIcon,
+ kindLabel: "Cohort",
+ source: "Product analytics",
+ webPath: (id) => `/cohorts/${id}`,
+ },
+ action: {
+ icon: CursorClickIcon,
+ kindLabel: "Action",
+ source: "Product analytics",
+ webPath: (id) => `/data-management/actions/${id}`,
+ },
+ person: {
+ icon: UserIcon,
+ kindLabel: "Person",
+ source: "Product analytics",
+ webPath: (id) => `/persons/${id}`,
+ },
+};
+
+/** Alternate tag names agents plausibly write, mapped to registry kinds. */
+const OBJECT_KIND_ALIASES: Record<string, string> = {
+ "session-replay": "replay",
+ recording: "replay",
+ "feature-flag": "flag",
+ sql: "hogql",
+};
+
+export const GENERIC_OBJECT_KIND: ObjectKindDef = {
+ icon: PulseIcon,
+ kindLabel: "Evidence",
+ source: "PostHog",
+};
+
+/** Registry kind for a tag name, or null when the tag isn't an object tag. */
+export function resolveObjectKindName(tag: string): string | null {
+ if (OBJECT_KINDS[tag]) return tag;
+ const alias = OBJECT_KIND_ALIASES[tag];
+ return alias && OBJECT_KINDS[alias] ? alias : null;
+}
+
+export function getObjectKind(kind: string): ObjectKindDef {
+ return OBJECT_KINDS[kind] ?? GENERIC_OBJECT_KIND;
+}
diff --git a/products/desktop/packages/ui/src/utils/remarkObjectTags.ts b/products/desktop/packages/ui/src/utils/remarkObjectTags.ts
new file mode 100644
index 000000000000..6aab24e0fefa
--- /dev/null
+++ b/products/desktop/packages/ui/src/utils/remarkObjectTags.ts
@@ -0,0 +1,314 @@
+import { unescapeXmlAttr } from "@posthog/shared";
+import type { Parent, PhrasingContent, Root, RootContent } from "mdast";
+import { CHART_BLOCK_MARKER } from "./chartBlocks";
+import { resolveObjectKindName } from "./objectKinds";
+
+/**
+ * Remark plugin for the object tags agents embed in replies, the message-side
+ * counterpart of the `<file path="..."/>` attachment convention:
+ *
+ * <insight id="9pQx3">checkout funnel</insight>
+ * <flag id="42"/>
+ * <hogql label="errors today">SELECT count() FROM events ...</hogql>
+ * <insight id="9pQx3" display="block"/>
+ * <hogql display="block" title="DAU, last 7 days">SELECT ...</hogql>
+ *
+ * Tags normalize to the renderer's internal nodes, so the components stay
+ * syntax-agnostic: inline tags become `evidence:<kind>/<id>` link nodes (the
+ * reference chip), block tags become `posthog-chart` code nodes (the chart
+ * card). Working on the AST keeps two guarantees for free: tags inside code
+ * fences and inline code stay literal, and a half-streamed tag renders
+ * nothing until the stream completes it (raw HTML nodes are not rendered).
+ *
+ * Only tags whose name resolves in the kind registry are touched; anything
+ * else keeps react-markdown's default behavior.
+ */
+
+/**
+ * Ceiling on block-display conversions per document. Every block card
+ * executes an authenticated query on mount, so an unbounded tag count would
+ * let one message fan out arbitrarily many concurrent queries; past the cap a
+ * block tag degrades to an inline chip, which fetches only on hover.
+ */
+const MAX_BLOCK_TAGS = 10;
+
+/** Mutable per-document budget threaded through the transform. */
+interface TransformState {
+ blockBudget: number;
+}
+
+const OPEN_TAG_RE = /^<([a-z][\w-]*)((?:\s+[a-z][\w-]*\s*=\s*"[^"]*")*)\s*>$/;
+const COMPLETE_TAG_RE =
+ /^<([a-z][\w-]*)((?:\s+[a-z][\w-]*\s*=\s*"[^"]*")*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>)$/;
+const ATTR_RE = /([a-z][\w-]*)\s*=\s*"([^"]*)"/g;
+
+interface ParsedTag {
+ kind: string;
+ attrs: Record<string, string>;
+ /** Raw body text when the whole tag sat in one html node. */
+ body?: string;
+ /** Parsed label nodes when the open/close pair spanned siblings. */
+ labelNodes?: PhrasingContent[];
+}
+
+function parseAttrs(raw: string): Record<string, string> {
+ const attrs: Record<string, string> = {};
+ for (const match of raw.matchAll(ATTR_RE)) {
+ attrs[match[1]] = unescapeXmlAttr(match[2]);
+ }
+ return attrs;
+}
+
+function matchCompleteTag(value: string): ParsedTag | null {
+ const match = COMPLETE_TAG_RE.exec(value.trim());
+ if (!match) return null;
+ const kind = resolveObjectKindName(match[1]);
+ if (!kind) return null;
+ return { kind, attrs: parseAttrs(match[2]), body: match[3] };
+}
+
+function matchOpenTag(
+ value: string,
+): { tag: string; kind: string; attrs: Record<string, string> } | null {
+ const match = OPEN_TAG_RE.exec(value.trim());
+ if (!match) return null;
+ const kind = resolveObjectKindName(match[1]);
+ if (!kind) return null;
+ return { tag: match[1], kind, attrs: parseAttrs(match[2]) };
+}
+
+function text(value: string): PhrasingContent {
+ return { type: "text", value };
+}
+
+/** Plain text of the nodes between an open and close tag (SQL bodies). */
+function nodesToText(nodes: PhrasingContent[]): string {
+ return nodes
+ .map((node) => {
+ if ("value" in node && typeof node.value === "string") return node.value;
+ if ("children" in node) {
+ return nodesToText(node.children as PhrasingContent[]);
+ }
+ return "";
+ })
+ .join("");
+}
+
+function inlineNode(tag: ParsedTag): PhrasingContent | null {
+ if (tag.kind === "hogql") {
+ const query = (
+ tag.body ?? (tag.labelNodes ? nodesToText(tag.labelNodes) : "")
+ ).trim();
+ if (!query) return null;
+ return {
+ type: "link",
+ url: `evidence:hogql/${encodeURIComponent(query)}`,
+ children: [text(tag.attrs.label?.trim() || "SQL query")],
+ };
+ }
+ const id = tag.attrs.id?.trim();
+ if (!id) return null;
+ const label = tag.labelNodes?.length
+ ? tag.labelNodes
+ : [text(tag.body?.trim() || id)];
+ return {
+ type: "link",
+ url: `evidence:${tag.kind}/${encodeURIComponent(id)}`,
+ children: label,
+ };
+}
+
+/** Serialized spec for the chart-card code node; parseChartBlock reads it. */
+function blockNode(tag: ParsedTag): RootContent | null {
+ const title = tag.attrs.title?.trim() || undefined;
+ const caption = tag.attrs.caption?.trim() || undefined;
+ let spec: Record<string, unknown> | null = null;
+ if (tag.kind === "hogql") {
+ const query = (
+ tag.body ?? (tag.labelNodes ? nodesToText(tag.labelNodes) : "")
+ ).trim();
+ if (query) spec = { mode: "hogql", query, title, caption };
+ } else if (tag.kind === "insight") {
+ const shortId = tag.attrs.id?.trim();
+ if (shortId) spec = { mode: "insight", shortId, title, caption };
+ } else if (tag.kind === "replay") {
+ const sessionId = tag.attrs.id?.trim();
+ if (sessionId) spec = { mode: "replay", sessionId, title, caption };
+ }
+ if (!spec) return null;
+ return {
+ type: "code",
+ lang: "posthog-chart",
+ value: JSON.stringify(spec),
+ // The marker is what lets the renderer trust this node: it can only be
+ // set from the AST, never from markdown text, so a hand-authored
+ // ```posthog-chart fence stays inert (see isGeneratedChartBlock).
+ data: { hProperties: { [CHART_BLOCK_MARKER]: "true" } },
+ };
+}
+
+function convert(
+ tag: ParsedTag,
+ inFlow: boolean,
+ state: TransformState,
+): RootContent | null {
+ if (inFlow && tag.attrs.display === "block" && state.blockBudget > 0) {
+ const block = blockNode(tag);
+ if (block) {
+ state.blockBudget--;
+ return block;
+ }
+ }
+ const inline = inlineNode(tag);
+ if (!inline) return null;
+ // A chip at block level needs a paragraph around it to flow as text.
+ return inFlow
+ ? ({ type: "paragraph", children: [inline] } as RootContent)
+ : (inline as RootContent);
+}
+
+/** The node opens a known tag (streaming may not have completed it yet). */
+function startsKnownTag(value: string): boolean {
+ const match = /^<\/?([a-z][\w-]*)/.exec(value.trim());
+ return match !== null && resolveObjectKindName(match[1]) !== null;
+}
+
+/**
+ * Consume the html node at `index` (plus, for a spanning open/close pair, the
+ * siblings up to the closing node). Returns null when it isn't an object tag;
+ * returns zero nodes for a known tag the stream hasn't completed yet, so a
+ * half-streamed tag shows nothing rather than raw markup.
+ */
+function consumeHtml(
+ children: RootContent[],
+ index: number,
+ inFlow: boolean,
+ state: TransformState,
+): { nodes: RootContent[]; nextIndex: number } | null {
+ const value = (children[index] as { value: string }).value;
+
+ const complete = matchCompleteTag(value);
+ if (complete) {
+ const node = convert(complete, inFlow, state);
+ return { nodes: node ? [node] : [], nextIndex: index + 1 };
+ }
+
+ const open = matchOpenTag(value);
+ if (open) {
+ for (let j = index + 1; j < children.length; j++) {
+ const sibling = children[j];
+ if (
+ sibling.type === "html" &&
+ sibling.value.trim() === `</${open.tag}>`
+ ) {
+ const label = children.slice(index + 1, j) as PhrasingContent[];
+ const node = convert(
+ { kind: open.kind, attrs: open.attrs, labelNodes: label },
+ inFlow,
+ state,
+ );
+ return { nodes: node ? [node] : [], nextIndex: j + 1 };
+ }
+ }
+ }
+
+ // Known tag, malformed or still streaming: hide the markup itself. Any
+ // in-between label text keeps flowing until the closing tag arrives.
+ if (startsKnownTag(value)) return { nodes: [], nextIndex: index + 1 };
+ return null;
+}
+
+/**
+ * A paragraph that is nothing but one block-display tag becomes the block
+ * node itself. Markdown only forms an HTML *block* when the opening tag line
+ * carries nothing else, so the common single-line form
+ * `<hogql display="block">SELECT ...</hogql>` arrives as a paragraph of
+ * inline html; without the lift it would downgrade to an inline chip.
+ */
+function liftParagraphBlockTag(
+ paragraph: Parent,
+ state: TransformState,
+): RootContent | null {
+ if (state.blockBudget <= 0) return null;
+ const kids = paragraph.children as RootContent[];
+ if (kids.length === 0) return null;
+
+ let block: RootContent | null = null;
+ if (kids.length === 1 && kids[0].type === "html") {
+ const tag = matchCompleteTag(kids[0].value);
+ block = tag && tag.attrs.display === "block" ? blockNode(tag) : null;
+ } else {
+ const first = kids[0];
+ const last = kids[kids.length - 1];
+ if (first.type !== "html" || last.type !== "html") return null;
+ const open = matchOpenTag(first.value);
+ if (
+ !open ||
+ open.attrs.display !== "block" ||
+ last.value.trim() !== `</${open.tag}>`
+ ) {
+ return null;
+ }
+ block = blockNode({
+ kind: open.kind,
+ attrs: open.attrs,
+ labelNodes: kids.slice(1, -1) as PhrasingContent[],
+ });
+ }
+ if (block) state.blockBudget--;
+ return block;
+}
+
+/**
+ * MDAST containers whose children are block content, so a lifted chart code
+ * node is valid inside them. Phrasing containers (paragraph, heading,
+ * emphasis) are absent on purpose: a block tag nested in their inline flow
+ * stays an inline chip rather than becoming an invalid nested block.
+ */
+const FLOW_CONTAINERS = new Set([
+ "listItem",
+ "blockquote",
+ "footnoteDefinition",
+]);
+
+function transformChildren(
+ parent: Parent,
+ inFlow: boolean,
+ state: TransformState,
+): void {
+ const out: RootContent[] = [];
+ const children = parent.children as RootContent[];
+ for (let i = 0; i < children.length; i++) {
+ const child = children[i];
+ if (child.type === "html") {
+ const consumed = consumeHtml(children, i, inFlow, state);
+ if (consumed) {
+ out.push(...consumed.nodes);
+ i = consumed.nextIndex - 1;
+ continue;
+ }
+ }
+ if (inFlow && child.type === "paragraph") {
+ const lifted = liftParagraphBlockTag(child as Parent, state);
+ if (lifted) {
+ out.push(lifted);
+ continue;
+ }
+ }
+ if ("children" in child) {
+ transformChildren(
+ child as Parent,
+ FLOW_CONTAINERS.has(child.type),
+ state,
+ );
+ }
+ out.push(child);
+ }
+ parent.children = out as Parent["children"];
+}
+
+export function remarkObjectTags() {
+ return (tree: Root): void => {
+ transformChildren(tree, true, { blockBudget: MAX_BLOCK_TAGS });
+ };
+}
diff --git a/products/desktop/packages/ui/vitest.config.ts b/products/desktop/packages/ui/vitest.config.ts
index 81eb433cd96a..8b407be80b09 100644
--- a/products/desktop/packages/ui/vitest.config.ts
+++ b/products/desktop/packages/ui/vitest.config.ts
@@ -17,9 +17,22 @@ export default defineConfig({
"@posthog/host-router": fileURLToPath(
new URL("../host-router/src", import.meta.url),
),
+ // quill-charts' dist imports dayjs plugins without the .js extension,
+ // which Vite's browser resolution accepts but vitest's Node resolution
+ // rejects; map them so any test that loads quill-charts can run.
+ "dayjs/plugin/customParseFormat": "dayjs/plugin/customParseFormat.js",
+ "dayjs/plugin/timezone": "dayjs/plugin/timezone.js",
+ "dayjs/plugin/utc": "dayjs/plugin/utc.js",
},
},
test: {
+ server: {
+ deps: {
+ // Process quill-charts through Vite instead of Node so the dayjs
+ // aliases above apply to its imports too.
+ inline: ["@posthog/quill-charts"],
+ },
+ },
globals: true,
...trunkTestOptions,
environment: "jsdom",
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
index d27043fe3267..b0ef03d637b0 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
@@ -662,7 +662,14 @@ Optimize for the fewest shell round trips.
- Batch related commands into one Bash invocation using \`&&\` (e.g. \`npm run typecheck && npm run lint && npm test\`).
- Emit all independent tool calls in the same response.
- Read multiple files at once.
-- Never rerun a command solely to reproduce output you already have.`;
+- Never rerun a command solely to reproduce output you already have.
+
+## Rich output in replies
+Embed the PostHog objects behind your conclusions as XML tags, the same convention as \`<file path="..."/>\` attachments. Every tag is a live reference the app resolves when shown - never restate the object's data in your text, and never put tags inside code fences.
+- Inline reference: \`<kind id="...">short human label</kind>\` inside a sentence, e.g. \`The <insight id="9pQx3">checkout funnel</insight> dropped after <flag id="42">new-checkout-flow</flag> rolled out.\` Kinds: insight, dashboard, error, replay, flag, experiment, survey, ticket, trace, eval, event, cohort, action, person. Use the object's id (insights: the short id; feature flags: the numeric id, falling back to the key; persons: the uuid). It renders as a chip with a live hover preview that opens the object in PostHog.
+- Inline SQL: \`<hogql label="signups today">SELECT count() FROM events WHERE ...</hogql>\` - the SQL is the tag body, the label is what the sentence shows. Hovering runs the query live; clicking opens the SQL editor.
+- Full-size chart, for any numeric or time-series answer (always prefer this over a markdown table): a saved insight \`<insight id="9pQx3" display="block"/>\` or a query \`<hogql display="block" title="Daily active users, last 7 days" caption="optional context">SELECT ...</hogql>\`. The chart executes live on every view. Include the time range in the title, and keep blank lines out of the SQL body.
+- Recording card: \`<replay id="<session_id>" display="block"/>\` renders the recording's details with a link into PostHog's player. Use it when a specific session is the evidence.`;
if (channelMode) {
prompt += `