:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): mobile live PostHog object tags in agent messages (#83690)
Tom Owers26c7c32fd9b8
diff --git a/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.test.tsx b/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.test.tsxindex 2e6a89850377..ba50e97d3bc1 100644--- a/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.test.tsx+++ b/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.test.tsx@@ -46,6 +46,18 @@ describe("MarkdownText", () => {present: ["☐", "☑"],absent: ["•", "1."],},+ {+ name: "object tag renders its label without the raw markup",+ content: 'Check the <insight id="9pQx3">checkout funnel</insight> now',+ present: ["checkout funnel", "Check the", "now"],+ absent: ["<insight", "</insight"],+ },+ {+ name: "still-streaming object tag renders nothing",+ content: 'Loading <flag id="4',+ present: ["Loading"],+ absent: ["<flag"],+ },])("$name", ({ content, present, absent }) => {const tree = renderTree(content);for (const marker of present) {diff --git a/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.tsx b/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.tsxindex b12b4a386620..c8ca3a0997f4 100644--- a/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.tsx+++ b/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.tsx@@ -1,3 +1,4 @@+import { parseObjectTags } from "@posthog/core/inbox/objectTags";import { useMemo } from "react";import { ScrollView, Text, View } from "react-native";import { getCloudUrlFromRegion, useAuthStore } from "@/features/auth";@@ -10,6 +11,7 @@ import { useThemeColors } from "@/lib/theme";import { CopyButton } from "./CopyButton";import { GithubRefChip } from "./GithubRefChip";import { MarkdownImage } from "./MarkdownImage";+import { ObjectTagChip, ObjectTagPreviewProvider } from "./ObjectTagChip";import { PostHogRefChip } from "./PostHogRefChip";const IMAGE_LINE_PATTERN = /^!\[([^\]]*)\]\(([^)\s]+)\)\s*$/;@@ -256,6 +258,23 @@ function renderPlainText(text: string,posthogUrlOptions: ParsePostHogUrlOptions,keyBase: string,+): React.ReactNode[] {+ const nodes: React.ReactNode[] = [];+ for (const [i, segment] of parseObjectTags(text).entries()) {+ const key = `${keyBase}-${i}`;+ if (segment.type === "tag") {+ nodes.push(<ObjectTagChip key={key} tag={segment.ref} />);+ } else {+ nodes.push(...renderUrlText(segment.value, posthogUrlOptions, key));+ }+ }+ return nodes;+}++function renderUrlText(+ text: string,+ posthogUrlOptions: ParsePostHogUrlOptions,+ keyBase: string,): React.ReactNode[] {const nodes: React.ReactNode[] = [];let lastIndex = 0;@@ -446,7 +465,7 @@ export function MarkdownText({[cloudRegion],);- return (+ const rendered = (<View style={{ gap: 8 }}>{blocks.map((block, i) => {const key = `block-${i}`;@@ -649,4 +668,6 @@ export function MarkdownText({})}</View>);++ return <ObjectTagPreviewProvider>{rendered}</ObjectTagPreviewProvider>;}diff --git a/products/desktop/apps/mobile/src/features/chat/components/ObjectTagChip.tsx b/products/desktop/apps/mobile/src/features/chat/components/ObjectTagChip.tsxnew file mode 100644index 000000000000..418ecff32fab--- /dev/null+++ b/products/desktop/apps/mobile/src/features/chat/components/ObjectTagChip.tsx@@ -0,0 +1,182 @@+import type { EvidencePreview } from "@posthog/api-client/evidence-previews";+import {+ getObjectKind,+ type ObjectTagRef,+ objectWebPath,+} from "@posthog/core/inbox/objectTags";+import { useQuery } from "@tanstack/react-query";+import {+ Bug,+ ChartLine,+ ChatCircleText,+ ClipboardText,+ CursorClick,+ Database,+ Flag,+ Flask,+ type Icon,+ Lightning,+ PlayCircle,+ Pulse,+ ShieldCheck,+ Sparkle,+ SquaresFour,+ User,+ UsersThree,+} from "phosphor-react-native";+import { createContext, type ReactNode, useContext, useState } from "react";+import { ActivityIndicator, Pressable, Text, View } from "react-native";+import { SheetContainer } from "@/components/SheetContainer";+import { getCloudUrlFromRegion, useAuthStore } from "@/features/auth";+import { openExternalUrl } from "@/lib/openExternalUrl";+import { getPostHogApiClient } from "@/lib/posthogApiClient";+import { useThemeColors } from "@/lib/theme";++const KIND_ICONS: Record<string, Icon> = {+ insight: ChartLine,+ hogql: Database,+ dashboard: SquaresFour,+ error: Bug,+ replay: PlayCircle,+ flag: Flag,+ experiment: Flask,+ survey: ClipboardText,+ ticket: ChatCircleText,+ trace: Sparkle,+ eval: ShieldCheck,+ event: Lightning,+ cohort: UsersThree,+ action: CursorClick,+ person: User,+};++const ObjectTagContext = createContext<(tag: ObjectTagRef) => void>(() => {});++function useObjectPreviewUrl(kind: string, id: string): string | null {+ const cloudRegion = useAuthStore((state) => state.cloudRegion);+ const projectId = useAuthStore((state) => state.projectId);+ const path = objectWebPath(kind, id);+ if (!path || !cloudRegion || !projectId) return null;+ return `${getCloudUrlFromRegion(cloudRegion)}/project/${projectId}${path}`;+}++function ObjectPreviewSheet({+ tag,+ onClose,+}: {+ tag: ObjectTagRef;+ onClose: () => void;+}) {+ const themeColors = useThemeColors();+ const meta = getObjectKind(tag.kind);+ const KindIcon = KIND_ICONS[tag.kind] ?? Pulse;++ const { data, isLoading } = useQuery<EvidencePreview | null>({+ queryKey: ["evidence-preview", tag.kind, tag.id],+ staleTime: 5 * 60 * 1000,+ retry: 1,+ queryFn: () => getPostHogApiClient().getEvidencePreview(tag.kind, tag.id),+ });++ const url = useObjectPreviewUrl(tag.kind, data?.resolvedId ?? tag.id);++ return (+ <SheetContainer open onClose={onClose}>+ <View className="gap-3 px-5 pt-2">+ <View className="flex-row items-center gap-1.5">+ <KindIcon size={13} color={themeColors.gray[9]} />+ <Text className="font-mono text-[11px] text-gray-9 uppercase tracking-wide">+ {meta.kindLabel}+ </Text>+ <Text className="ml-auto text-[11px] text-gray-9">{meta.source}</Text>+ </View>++ {isLoading ? (+ <ActivityIndicator color={themeColors.gray[9]} />+ ) : (+ <View className="gap-2">+ <Text className="font-semibold text-[15px] text-gray-12 leading-snug">+ {data?.title ?? tag.label}+ </Text>+ {data?.detail && (+ <Text className="text-[12px] text-gray-10 leading-snug">+ {data.detail}+ </Text>+ )}+ {data?.facts && data.facts.length > 0 && (+ <View className="flex-row flex-wrap gap-1.5">+ {data.facts.map((fact) => (+ <Text+ key={fact}+ className="rounded bg-gray-3 px-1.5 py-0.5 text-[11px] text-gray-11"+ >+ {fact}+ </Text>+ ))}+ </View>+ )}+ {tag.kind === "hogql" && (+ <Text className="rounded bg-gray-3 p-2 font-mono text-[11px] text-gray-11 leading-4">+ {tag.id}+ </Text>+ )}+ </View>+ )}++ {url && (+ <Pressable+ onPress={() => openExternalUrl(url)}+ className="mt-1 self-start rounded-md bg-gray-3 px-3 py-1.5"+ accessibilityRole="button"+ >+ <Text className="text-[12px] text-accent-11">+ Open in PostHog ↗+ </Text>+ </Pressable>+ )}+ </View>+ </SheetContainer>+ );+}++/**+ * Holds the single preview sheet for a message. The sheet is a Modal, so it+ * cannot render from inside a chip (chips live inside a paragraph `Text`);+ * chips open it through context instead.+ */+export function ObjectTagPreviewProvider({+ children,+}: {+ children: ReactNode;+}) {+ const [active, setActive] = useState<ObjectTagRef | null>(null);+ return (+ <ObjectTagContext.Provider value={setActive}>+ {children}+ {active && (+ <ObjectPreviewSheet tag={active} onClose={() => setActive(null)} />+ )}+ </ObjectTagContext.Provider>+ );+}++/**+ * Inline reference to a PostHog object in an agent message, authored as a+ * `<kind id="...">label</kind>` tag. Tapping opens a sheet that resolves the+ * object's live name and status. Previews fetch only on tap, so a message full+ * of references never fans out concurrent authenticated queries.+ */+export function ObjectTagChip({ tag }: { tag: ObjectTagRef }) {+ const openPreview = useContext(ObjectTagContext);+ const meta = getObjectKind(tag.kind);+ return (+ <Text+ onPress={() => openPreview(tag)}+ className="rounded-md bg-gray-3 px-1.5 py-0.5 text-[12px] text-gray-12"+ accessibilityRole="button"+ accessibilityLabel={`${meta.kindLabel}: ${tag.label}`}+ >+ {tag.label}+ </Text>+ );+}diff --git a/products/desktop/apps/mobile/src/test/setup.ts b/products/desktop/apps/mobile/src/test/setup.tsindex 998bc54c20e9..bff97520a7e0 100644--- a/products/desktop/apps/mobile/src/test/setup.ts+++ b/products/desktop/apps/mobile/src/test/setup.ts@@ -8,6 +8,12 @@ vi.mock("expo-constants", () => ({},}));+// expo/fetch and expo-application ship as source that vitest's node environment+// cannot load (Flow syntax, a missing __DEV__ global), wedging any module — e.g.+// the PostHog API client — that imports them transitively.+vi.mock("expo/fetch", () => ({ fetch: vi.fn() }));+vi.mock("expo-application", () => ({ nativeApplicationVersion: "0.0.0-test" }));+vi.mock("@react-native-async-storage/async-storage", () => {const store = new Map<string, string>();return {@@ -59,6 +65,17 @@ vi.mock("phosphor-react-native", async () => {Bug: icon("Bug"),Camera: icon("Camera"),Cards: icon("Cards"),+ ChartLine: icon("ChartLine"),+ ChatCircleText: icon("ChatCircleText"),+ ClipboardText: icon("ClipboardText"),+ CursorClick: icon("CursorClick"),+ Database: icon("Database"),+ Flag: icon("Flag"),+ Flask: icon("Flask"),+ PlayCircle: icon("PlayCircle"),+ Pulse: icon("Pulse"),+ SquaresFour: icon("SquaresFour"),+ User: icon("User"),CaretDown: icon("CaretDown"),CaretLeft: icon("CaretLeft"),CaretRight: icon("CaretRight"),diff --git a/products/desktop/packages/core/src/inbox/objectTags.test.ts b/products/desktop/packages/core/src/inbox/objectTags.test.tsnew file mode 100644index 000000000000..4cc4bdb728c4--- /dev/null+++ b/products/desktop/packages/core/src/inbox/objectTags.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from "vitest";+import {+ type ObjectTagRef,+ objectWebPath,+ parseObjectTags,+} from "./objectTags";++function tags(text: string): ObjectTagRef[] {+ return parseObjectTags(text)+ .filter((segment) => segment.type === "tag")+ .map((segment) => segment.ref);+}++function texts(text: string): string[] {+ return parseObjectTags(text)+ .filter((segment) => segment.type === "text")+ .map((segment) => segment.value);+}++describe("parseObjectTags", () => {+ it("parses a self-closing tag into a reference", () => {+ expect(tags('<flag id="42"/>')).toEqual([+ { kind: "flag", id: "42", label: "42" },+ ]);+ });++ it("uses the body as the label for an open/close tag", () => {+ expect(tags('<insight id="9pQx3">checkout funnel</insight>')).toEqual([+ { kind: "insight", id: "9pQx3", label: "checkout funnel" },+ ]);+ });++ it("treats the body as the query for hogql references", () => {+ expect(+ tags('<hogql label="errors">SELECT count() FROM events</hogql>'),+ ).toEqual([+ { kind: "hogql", id: "SELECT count() FROM events", label: "errors" },+ ]);+ });++ it("resolves an alias to its registry kind", () => {+ expect(tags('<recording id="s1"/>')).toEqual([+ { kind: "replay", id: "s1", label: "s1" },+ ]);+ });++ it("keeps text around a tag literal", () => {+ expect(texts('see <flag id="42"/> here')).toEqual(["see ", " here"]);+ });++ it("leaves unknown tag names literal", () => {+ expect(tags("<span>hello</span>")).toEqual([]);+ expect(texts("<span>hello</span>")).toEqual(["<span>hello</span>"]);+ });++ it("hides a still-streaming tag until it completes", () => {+ expect(parseObjectTags('checkout <insight id="9pQx3">chec')).toEqual([+ { type: "text", value: "checkout " },+ ]);+ });++ it("drops a complete tag missing its id", () => {+ expect(parseObjectTags("<flag></flag>")).toEqual([]);+ });+});++describe("objectWebPath", () => {+ it("builds a page path for a known kind", () => {+ expect(objectWebPath("insight", "9pQx3")).toBe("/insights/9pQx3");+ });++ it("returns null for a flag cited by key", () => {+ expect(objectWebPath("flag", "my-flag-key")).toBeNull();+ expect(objectWebPath("flag", "42")).toBe("/feature_flags/42");+ });+});diff --git a/products/desktop/packages/core/src/inbox/objectTags.ts b/products/desktop/packages/core/src/inbox/objectTags.tsnew file mode 100644index 000000000000..c945cacf9386--- /dev/null+++ b/products/desktop/packages/core/src/inbox/objectTags.ts@@ -0,0 +1,228 @@+import { unescapeXmlAttr } from "@posthog/shared";++// Object tags are the message-side counterpart of the `<file path="..."/>`+// attachment convention: agents embed references to PostHog objects in their+// replies, and hosts render them as live chips instead of raw text.+//+// <insight id="9pQx3">checkout funnel</insight>+// <flag id="42"/>+// <hogql label="errors today">SELECT count() FROM events ...</hogql>+//+// This module is host-agnostic: it owns the kind registry (minus icons, which+// are a host concern) and the parser that turns free text into an ordered run+// of text and tag segments. Rendering lives in each host.++export interface ObjectKindMeta {+ /** 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. Returns null when this id has no direct+ * page; omitted when the kind has no canonical page at all.+ */+ webPath?: (encodedId: string, rawId: string) => string | null;+}++export const OBJECT_KINDS: Record<string, ObjectKindMeta> = {+ insight: {+ kindLabel: "Insight",+ source: "Product analytics",+ webPath: (id) => `/insights/${id}`,+ },+ // For hogql the "id" is the SQL itself; the chip opens the SQL editor.+ hogql: {+ kindLabel: "SQL query",+ source: "SQL editor",+ webPath: (id) => `/sql?open_query=${id}`,+ },+ dashboard: {+ kindLabel: "Dashboard",+ source: "Product analytics",+ webPath: (id) => `/dashboard/${id}`,+ },+ error: {+ kindLabel: "Error issue",+ source: "Error tracking",+ webPath: (id) => `/error_tracking/${id}`,+ },+ replay: {+ kindLabel: "Session replay",+ source: "Session replay",+ webPath: (id) => `/replay/${id}`,+ },+ flag: {+ kindLabel: "Feature flag",+ source: "Feature flags",+ // Flag pages only resolve by numeric id, so a flag cited by key gets no+ // direct URL until its preview resolves the numeric id.+ webPath: (id, raw) => (/^\d+$/.test(raw) ? `/feature_flags/${id}` : null),+ },+ experiment: {+ kindLabel: "Experiment",+ source: "Experiments",+ webPath: (id) => `/experiments/${id}`,+ },+ survey: {+ kindLabel: "Survey",+ source: "Surveys",+ webPath: (id) => `/surveys/${id}`,+ },+ ticket: {+ kindLabel: "Support tickets",+ source: "Conversations",+ webPath: (id) => `/support/tickets/${id}`,+ },+ trace: {+ kindLabel: "LLM trace",+ source: "AI observability",+ webPath: (id) => `/ai-observability/traces/${id}`,+ },+ eval: {+ kindLabel: "Evaluation",+ source: "AI evals",+ webPath: (id) => `/ai-evals/evaluations/${id}`,+ },+ event: {+ kindLabel: "Events",+ source: "Product analytics",+ webPath: (id, raw) =>+ /^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(raw)+ ? `/data-management/events/${id}`+ : null,+ },+ cohort: {+ kindLabel: "Cohort",+ source: "Product analytics",+ webPath: (id) => `/cohorts/${id}`,+ },+ action: {+ kindLabel: "Action",+ source: "Product analytics",+ webPath: (id) => `/data-management/actions/${id}`,+ },+ person: {+ 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: ObjectKindMeta = {+ 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): ObjectKindMeta {+ return OBJECT_KINDS[kind] ?? GENERIC_OBJECT_KIND;+}++/** Project-relative PostHog web path for a reference, or null when it has none. */+export function objectWebPath(kind: string, id: string): string | null {+ const build = getObjectKind(kind).webPath;+ return build ? build(encodeURIComponent(id), id) : null;+}++export interface ObjectTagRef {+ /** Resolved registry kind. */+ kind: string;+ /** Object id, or the SQL text for a hogql reference. */+ id: string;+ /** Display text for the chip. */+ label: string;+}++export type ObjectTagSegment =+ | { type: "text"; value: string }+ | { type: "tag"; ref: ObjectTagRef };++const COMPLETE_TAG_RE =+ /<([a-z][\w-]*)((?:\s+[a-z][\w-]*\s*=\s*"[^"]*")*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>)/g;+const ATTR_RE = /([a-z][\w-]*)\s*=\s*"([^"]*)"/g;+const KNOWN_TAG_START_RE = /<([a-z][\w-]*)/g;++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 buildRef(+ kind: string,+ attrs: Record<string, string>,+ body: string | undefined,+): ObjectTagRef | null {+ if (kind === "hogql") {+ const query = (body ?? "").trim();+ if (!query) return null;+ const label = attrs.title?.trim() || attrs.label?.trim() || "SQL query";+ return { kind, id: query, label };+ }+ const id = attrs.id?.trim();+ if (!id) return null;+ const label = attrs.title?.trim() || body?.trim() || id;+ return { kind, id, label };+}++/**+ * Index where a known object tag begins streaming but hasn't been completed,+ * or null. Complete tags are consumed before this runs, so any remaining+ * `<knownkind` marks a half-streamed tag whose markup should stay hidden.+ */+function incompleteTagStart(text: string): number | null {+ KNOWN_TAG_START_RE.lastIndex = 0;+ let found: number | null = null;+ let match: RegExpExecArray | null;+ // biome-ignore lint/suspicious/noAssignInExpressions: regex exec loop+ while ((match = KNOWN_TAG_START_RE.exec(text)) !== null) {+ if (resolveObjectKindName(match[1])) found = match.index;+ }+ return found;+}++/**+ * Split text into an ordered run of literal text and object-tag references.+ * Unknown tag names stay literal, and a still-streaming tag renders nothing+ * until its closing markup arrives.+ */+export function parseObjectTags(text: string): ObjectTagSegment[] {+ const segments: ObjectTagSegment[] = [];+ let cursor = 0;+ COMPLETE_TAG_RE.lastIndex = 0;+ let match: RegExpExecArray | null;+ // biome-ignore lint/suspicious/noAssignInExpressions: regex exec loop+ while ((match = COMPLETE_TAG_RE.exec(text)) !== null) {+ const kind = resolveObjectKindName(match[1]);+ if (!kind) continue;+ const ref = buildRef(kind, parseAttrs(match[2]), match[3]);+ if (!ref) continue;+ if (match.index > cursor) {+ segments.push({ type: "text", value: text.slice(cursor, match.index) });+ }+ segments.push({ type: "tag", ref });+ cursor = match.index + match[0].length;+ }++ let tail = text.slice(cursor);+ const partial = incompleteTagStart(tail);+ if (partial !== null) tail = tail.slice(0, partial);+ if (tail) segments.push({ type: "text", value: tail });+ return segments;+}