: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(mobilehog): render posthog object tags as chips and cards (#109538)
Dylan Martine9b950c4895a
diff --git a/products/desktop/apps/mobilehog/src/components/Markdown.tsx b/products/desktop/apps/mobilehog/src/components/Markdown.tsxindex 8405a91e64e4..993381c4dee8 100644--- a/products/desktop/apps/mobilehog/src/components/Markdown.tsx+++ b/products/desktop/apps/mobilehog/src/components/Markdown.tsx@@ -1,5 +1,6 @@+import type { ObjectTagRef } from "@posthog/core/inbox/objectTags";import { isSafeExternalUrl } from "@posthog/shared";-import { type MarkedToken, marked, type Token, type Tokens } from "marked";+import type { MarkedToken, Token, Tokens } from "marked";import { type ReactNode, useMemo, useState } from "react";import {type ColorValue,@@ -12,8 +13,18 @@ import {View,} from "react-native";import { MermaidDiagram } from "@/components/MermaidDiagram";-import { splitImageRuns } from "@/lib/markdown";+import {+ ObjectCard,+ openObjectUrl,+ useObjectUrl,+} from "@/components/ObjectCard";+import { lexMarkdown, splitImageRuns } from "@/lib/markdown";import { isClosedFence, isMermaidLang } from "@/lib/mermaid";+import {+ isObjectCardToken,+ isObjectRefToken,+ isObjectTagMarkup,+} from "@/lib/objectTags";import { colors, fonts } from "@/lib/theme";interface MarkdownProps {@@ -25,14 +36,29 @@ function openLink(href: string): void {if (isSafeExternalUrl(href)) Linking.openURL(href).catch(() => {});}+// Kinds without a page in PostHog read as plain text.+function ObjectChip({ target }: { target: ObjectTagRef }): ReactNode {+ const url = useObjectUrl(target.kind, target.id);+ return url ? (+ <Text style={styles.chip} onPress={() => openObjectUrl(url)}>+ {target.label}+ </Text>+ ) : (+ target.label+ );+}+function renderInline(tokens: Token[] | undefined,color: ColorValue,linked = false,): ReactNode[] {return (tokens ?? []).map((raw, index) => {- const token = raw as MarkedToken;const key = String(index);+ if (isObjectRefToken(raw)) {+ return <ObjectChip key={key} target={raw.ref} />;+ }+ const token = raw as MarkedToken;switch (token.type) {case "strong":return (@@ -82,6 +108,8 @@ function renderInline();case "br":return "\n";+ case "html":+ return isObjectTagMarkup(token.text) ? null : token.text;case "text":return token.tokens ? (<Text key={key}>{renderInline(token.tokens, color, linked)}</Text>@@ -238,8 +266,11 @@ function renderBlocks(color: ColorValue,): ReactNode[] {return (tokens ?? []).map((raw, index) => {+ const key = `${index}-${raw.type}`;+ if (isObjectCardToken(raw)) {+ return <ObjectCard key={key} spec={raw.spec} />;+ }const token = raw as MarkedToken;- const key = `${index}-${token.type}`;switch (token.type) {case "code":return isMermaidLang(token.lang) && isClosedFence(token.raw) ? (@@ -292,7 +323,7 @@ function renderBlocks(}export function Markdown({ text, color = colors.ink }: MarkdownProps) {- const tokens = useMemo(() => marked.lexer(text), [text]);+ const tokens = useMemo(() => lexMarkdown(text), [text]);return <View style={styles.root}>{renderBlocks(tokens, color)}</View>;}@@ -350,6 +381,11 @@ const styles = StyleSheet.create({},imagePending: { aspectRatio: 16 / 9 },link: { color: colors.accent, textDecorationLine: "underline" },+ chip: {+ fontFamily: fonts.sansMedium,+ color: colors.accent,+ backgroundColor: colors.fill,+ },table: {borderWidth: StyleSheet.hairlineWidth,borderColor: colors.line,diff --git a/products/desktop/apps/mobilehog/src/components/ObjectCard.tsx b/products/desktop/apps/mobilehog/src/components/ObjectCard.tsxnew file mode 100644index 000000000000..f02c0befbc13--- /dev/null+++ b/products/desktop/apps/mobilehog/src/components/ObjectCard.tsx@@ -0,0 +1,137 @@+import { getObjectKind } from "@posthog/core/inbox/objectTags";+import { isSafeExternalUrl } from "@posthog/shared";+import { type ReactElement, useState } from "react";+import { Linking, Pressable, StyleSheet, Text } from "react-native";+import { useAuth } from "@/lib/auth";+import { type ObjectCardSpec, objectWebUrl } from "@/lib/objectTags";+import { useInsightSummary } from "@/lib/queries";+import { colors, fonts } from "@/lib/theme";++const COLLAPSED_LINES = 3;++export function useObjectUrl(kind: string, id: string): string | null {+ const session = useAuth((s) => s.session);+ return session+ ? objectWebUrl(session.host, session.projectId, kind, id)+ : null;+}++export function openObjectUrl(url: string | null): void {+ if (url && isSafeExternalUrl(url)) Linking.openURL(url).catch(() => {});+}++function meta(kind: string): string {+ const { kindLabel, source } = getObjectKind(kind);+ return `${kindLabel} · ${source}`;+}++function InsightCard({+ shortId,+ title,+}: {+ shortId: string;+ title?: string;+}): ReactElement {+ const insight = useInsightSummary(shortId);+ const url = useObjectUrl("insight", shortId);+ const name = title ?? insight.data?.name;+ const placeholder = insight.isLoading+ ? "Loading"+ : insight.isError || insight.data === null+ ? "Couldn't load this insight."+ : "Untitled insight";+ return (+ <Pressable+ onPress={() => openObjectUrl(url)}+ style={({ pressed }) => [styles.card, pressed && styles.pressed]}+ >+ <Text style={styles.meta}>{meta("insight")}</Text>+ {name ? (+ <Text style={styles.title} numberOfLines={2}>+ {name}+ </Text>+ ) : (+ <Text style={styles.muted}>{placeholder}</Text>+ )}+ {insight.data?.description ? (+ <Text style={styles.description} numberOfLines={3}>+ {insight.data.description}+ </Text>+ ) : null}+ </Pressable>+ );+}++function QueryCard({+ query,+ title,+}: {+ query: string;+ title?: string;+}): ReactElement {+ const url = useObjectUrl("hogql", query);+ const [expanded, setExpanded] = useState(false);+ return (+ <Pressable+ onPress={() => openObjectUrl(url)}+ style={({ pressed }) => [styles.card, pressed && styles.pressed]}+ >+ <Text style={styles.meta}>{meta("hogql")}</Text>+ <Text style={styles.title} numberOfLines={2}>+ {title ?? "SQL query"}+ </Text>+ <Text+ style={styles.query}+ numberOfLines={expanded ? undefined : COLLAPSED_LINES}+ >+ {query}+ </Text>+ <Pressable hitSlop={8} onPress={() => setExpanded(!expanded)}>+ <Text style={styles.toggle}>{expanded ? "Show less" : "Show all"}</Text>+ </Pressable>+ </Pressable>+ );+}++export function ObjectCard({ spec }: { spec: ObjectCardSpec }): ReactElement {+ return spec.mode === "insight" ? (+ <InsightCard shortId={spec.shortId} title={spec.title} />+ ) : (+ <QueryCard query={spec.query} title={spec.title} />+ );+}++const styles = StyleSheet.create({+ card: {+ backgroundColor: colors.surface,+ borderRadius: 16,+ padding: 12,+ gap: 6,+ },+ pressed: { opacity: 0.5 },+ meta: { fontFamily: fonts.sansMedium, fontSize: 12, color: colors.inkMute },+ title: {+ fontFamily: fonts.sansSemi,+ fontSize: 15,+ lineHeight: 20,+ color: colors.ink,+ },+ description: {+ fontFamily: fonts.sans,+ fontSize: 14,+ lineHeight: 20,+ color: colors.inkSoft,+ },+ muted: { fontFamily: fonts.sans, fontSize: 14, color: colors.inkMute },+ query: {+ fontFamily: fonts.mono,+ fontSize: 12,+ lineHeight: 17,+ color: colors.inkSoft,+ backgroundColor: colors.code,+ borderRadius: 8,+ padding: 8,+ overflow: "hidden",+ },+ toggle: { fontFamily: fonts.sansMedium, fontSize: 13, color: colors.accent },+});diff --git a/products/desktop/apps/mobilehog/src/lib/auth.test.ts b/products/desktop/apps/mobilehog/src/lib/auth.test.tsnew file mode 100644index 000000000000..ce9b55cfdd86--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/auth.test.ts@@ -0,0 +1,50 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const secureStore = vi.hoisted(() => ({+ deleteItemAsync: vi.fn(),+ getItemAsync: vi.fn(),+ setItemAsync: vi.fn(),+}));++vi.mock("expo/fetch", () => ({ fetch: vi.fn() }));+vi.mock("expo-secure-store", () => secureStore);+vi.mock("expo-auth-session", () => ({}));+vi.mock("expo-web-browser", () => ({ maybeCompleteAuthSession: vi.fn() }));++import { type Session, useAuth } from "./auth";++const savedSession: Session = {+ region: "us",+ host: "https://us.posthog.com",+ apiKey: "old-access-token",+ refreshToken: "old-refresh-token",+ expiresAt: Date.now() + 60_000,+ scopedTeams: [42],+ projectId: 42,+ projectName: "Demo project",+ userId: 7,+ userName: "Pat",+};++describe("mobilehog auth", () => {+ beforeEach(() => {+ secureStore.deleteItemAsync.mockReset();+ secureStore.getItemAsync.mockReset();+ secureStore.setItemAsync.mockReset();+ useAuth.setState({ session: null, hydrated: false, generation: 0 });+ });++ it("forces an existing OAuth session to reauthorize after scopes change", async () => {+ secureStore.getItemAsync.mockResolvedValue(JSON.stringify(savedSession));++ await useAuth.getState().hydrate();++ expect(secureStore.deleteItemAsync).toHaveBeenCalledWith(+ "mobilehog_session",+ );+ expect(useAuth.getState()).toMatchObject({+ session: null,+ hydrated: true,+ });+ });+});diff --git a/products/desktop/apps/mobilehog/src/lib/auth.ts b/products/desktop/apps/mobilehog/src/lib/auth.tsindex 9e08892f5c15..b818f73d0bf8 100644--- a/products/desktop/apps/mobilehog/src/lib/auth.ts+++ b/products/desktop/apps/mobilehog/src/lib/auth.ts@@ -5,6 +5,7 @@ import { POSTHOG_HOST } from "@/config";import {CLOUD_HOSTS,type CloudRegion,+ OAUTH_SCOPE_VERSION,refreshOAuth,type SignInOptions,signInWithOAuth,@@ -23,6 +24,7 @@ export interface Session {expiresAt?: number;// The projects an OAuth token may reach; empty or missing means no limit.scopedTeams?: number[];+ scopeVersion?: number;projectId: number;projectName: string;userId: number;@@ -218,10 +220,19 @@ export const useAuth = create<AuthState>((set, get) => {try {const raw = await SecureStore.getItemAsync(SESSION_KEY);if (get().generation !== generation || get().session) return;- set({- session: raw ? (JSON.parse(raw) as Session) : null,- hydrated: true,- });+ const session = raw ? (JSON.parse(raw) as Session) : null;+ if (+ session &&+ session.region !== "local" &&+ session.scopeVersion !== OAUTH_SCOPE_VERSION+ ) {+ await SecureStore.deleteItemAsync(SESSION_KEY);+ if (get().generation === generation && !get().session) {+ set({ session: null, hydrated: true });+ }+ return;+ }+ set({ session, hydrated: true });} catch {if (get().generation === generation) set({ hydrated: true });}@@ -240,7 +251,11 @@ export const useAuth = create<AuthState>((set, get) => {expiresAt: Date.now() + tokens.expires_in * 1000,projectId: tokens.scoped_teams?.[0],});- return { ...session, scopedTeams: tokens.scoped_teams };+ return {+ ...session,+ scopedTeams: tokens.scoped_teams,+ scopeVersion: OAUTH_SCOPE_VERSION,+ };}),refresh: async () => {diff --git a/products/desktop/apps/mobilehog/src/lib/markdown.ts b/products/desktop/apps/mobilehog/src/lib/markdown.tsindex 78bdd3eb8754..d9ae12a920ae 100644--- a/products/desktop/apps/mobilehog/src/lib/markdown.ts+++ b/products/desktop/apps/mobilehog/src/lib/markdown.ts@@ -1,5 +1,6 @@import { isSafeExternalUrl } from "@posthog/shared";-import type { Token, Tokens } from "marked";+import { Marked, type Token, type Tokens } from "marked";+import { objectTagExtensions } from "@/lib/objectTags";export type InlineRun =| { kind: "text"; tokens: Token[] }@@ -80,3 +81,8 @@ export function splitImageRuns(tokens: Token[]): InlineRun[] {flush();return runs;}++export function lexMarkdown(text: string): Token[] {+ const markdown = new Marked({ extensions: objectTagExtensions() });+ return markdown.Lexer.lex(text, markdown.defaults);+}diff --git a/products/desktop/apps/mobilehog/src/lib/oauth.ts b/products/desktop/apps/mobilehog/src/lib/oauth.tsindex 16b2f090b703..7ea3bc4fdc5e 100644--- a/products/desktop/apps/mobilehog/src/lib/oauth.ts+++ b/products/desktop/apps/mobilehog/src/lib/oauth.ts@@ -25,10 +25,13 @@ const SCOPES = ["task:write","integration:read","conversation:write",+ "insight:read","query:read","llm_skill:read",];+export const OAUTH_SCOPE_VERSION = 1;+export interface OAuthTokens {access_token: string;expires_in: number;diff --git a/products/desktop/apps/mobilehog/src/lib/objectTags.test.ts b/products/desktop/apps/mobilehog/src/lib/objectTags.test.tsnew file mode 100644index 000000000000..dc47d62e7a54--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/objectTags.test.ts@@ -0,0 +1,239 @@+import type { Token } from "marked";+import { describe, expect, it } from "vitest";+import { lexMarkdown } from "./markdown";+import { isObjectTagMarkup, objectWebUrl } from "./objectTags";++// The token tree without raw source, so cases read as structure.+function shape(text: string): unknown {+ return JSON.parse(+ JSON.stringify(lexMarkdown(text), (key, value) =>+ key === "raw" || key === "escaped" ? undefined : value,+ ),+ );+}++function inline(text: string): Token[] {+ const [paragraph] = lexMarkdown(text) as { tokens: Token[] }[];+ return paragraph.tokens;+}++describe("object tags in markdown", () => {+ it("turns an inline tag into a reference with its label", () => {+ expect(+ inline('See <insight id="9pQx3">checkout funnel</insight> now'),+ ).toEqual([+ expect.objectContaining({ type: "text", text: "See " }),+ expect.objectContaining({+ type: "objectRef",+ ref: { kind: "insight", id: "9pQx3", label: "checkout funnel" },+ }),+ expect.objectContaining({ type: "text", text: " now" }),+ ]);+ });++ it.each([+ ['<flag id="42"/>', { kind: "flag", id: "42", label: "42" }],+ [+ '<hogql label="errors today">SELECT 1</hogql>',+ { kind: "hogql", id: "SELECT 1", label: "errors today" },+ ],+ [+ '<feature_flag id="7">beta</feature_flag>',+ { kind: "flag", id: "7", label: "beta" },+ ],+ ])("reads %s", (tag, ref) => {+ expect(inline(`x ${tag}`)[1]).toEqual(+ expect.objectContaining({ type: "objectRef", ref }),+ );+ });++ it.each([+ ['<gizmo id="1">Gizmo</gizmo>', "Gizmo"],+ ["<insight>Checkout funnel</insight>", "Checkout funnel"],+ ])(+ "renders only the label when %s cannot become a reference",+ (tag, label) => {+ expect(inline(`x ${tag}`)[1]).toEqual(+ expect.objectContaining({ type: "text", text: label }),+ );+ },+ );++ it("leaves other html alone", () => {+ expect(inline("x <b>bold</b>")[1]).toEqual(+ expect.objectContaining({ type: "html", text: "<b>" }),+ );+ });++ it.each([+ [+ '<insight id="9pQx3" display="block"/>',+ { mode: "insight", shortId: "9pQx3" },+ ],+ [+ '<hogql display="block" title="DAU">SELECT count() FROM events</hogql>',+ { mode: "hogql", query: "SELECT count() FROM events", title: "DAU" },+ ],+ [+ '<hogql display="block" title="DAU">\nSELECT 1\n\nFROM events\n</hogql>',+ { mode: "hogql", query: "SELECT 1\n\nFROM events", title: "DAU" },+ ],+ ])("turns a block tag on its own line into a card: %s", (text, spec) => {+ expect(shape(text)).toEqual([{ type: "objectCard", spec }]);+ });++ it("keeps a block tag inside a sentence as a reference", () => {+ expect(inline('Look: <insight id="a" display="block"/>')[1]).toEqual(+ expect.objectContaining({ type: "objectRef" }),+ );+ });++ it("starts a standalone card after prose on the previous line", () => {+ expect(shape('Here it is:\n<insight id="abc" display="block"/>')).toEqual([+ expect.objectContaining({ type: "paragraph", text: "Here it is:" }),+ {+ type: "objectCard",+ spec: { mode: "insight", shortId: "abc" },+ },+ ]);+ });++ it("renders a block tag of a kind without a card as a reference", () => {+ expect(shape('<dashboard id="7" display="block"/>')).toEqual([+ {+ type: "paragraph",+ text: '<dashboard id="7" display="block"/>',+ tokens: [+ {+ type: "objectRef",+ ref: { kind: "dashboard", id: "7", label: "7" },+ },+ ],+ },+ ]);+ });++ it("keeps text indented under a block tag without a card", () => {+ expect(shape('<dashboard id="7" display="block"/>\n text')).toEqual([+ expect.objectContaining({+ type: "paragraph",+ tokens: [+ expect.objectContaining({ type: "objectRef" }),+ expect.objectContaining({ type: "text", text: "\ntext" }),+ ],+ }),+ ]);+ });++ it("keeps a code block after a blank line under a block tag", () => {+ const tokens = lexMarkdown(+ '<dashboard id="7" display="block"/>\n\n code',+ );+ expect(tokens.map((token) => token.type)).toEqual([+ "paragraph",+ "space",+ "code",+ ]);+ });++ it.each([+ 'See <insight id="9pQx3',+ 'See <insight id="9pQx3"',+ 'See <insight id="9pQx3" title="Check',+ 'See <insight id="9pQx3">chec',+ 'See <insight id="9pQx3">checkout</insi',+ "See <insight",+ ])("hides an unfinished tag: %s", (text) => {+ expect(inline(text)).toEqual([+ expect.objectContaining({ type: "text", text: "See " }),+ expect.objectContaining({ type: "text", text: "" }),+ ]);+ });++ it("hides an unfinished block tag through blank lines", () => {+ expect(shape('<hogql display="block">\nSELECT 1\n\nFROM events')).toEqual([+ { type: "html", text: "" },+ ]);+ });++ it.each([+ `See <insight${" a= ".repeat(2000)}!`,+ `See <insight${' a="x" '.repeat(2000)}`,+ ])("preserves the source while scanning a large unfinished tag", (text) => {+ expect(+ lexMarkdown(text)+ .map((token) => token.raw)+ .join(""),+ ).toBe(text);+ });++ it("does not hide a tag name in prose", () => {+ expect(inline("x <insight, then y")).toEqual([+ expect.objectContaining({ type: "text", text: "x <insight, then y" }),+ ]);+ });++ it("does not hide a closed malformed tag or the text after it", () => {+ const tokens = inline("See <insight id=x/> now");+ expect(tokens.map((token) => token.raw).join("")).toBe(+ "See <insight id=x/> now",+ );+ expect(tokens.at(-1)).toEqual(+ expect.objectContaining({ type: "text", text: " now" }),+ );+ });++ it("caps the cards in one message and resets for the next", () => {+ const text = Array.from(+ { length: 12 },+ (_, i) => `<insight id="i${i}" display="block"/>`,+ ).join("\n\n");+ const cards = (source: string) =>+ lexMarkdown(source).filter((token) => token.type === "objectCard").length;+ expect(cards(text)).toBe(10);+ expect(cards(text)).toBe(10);+ });++ it("keeps tags in code literal", () => {+ expect(+ shape(+ '`<insight id="x"/>`\n\n```\n<insight id="x" display="block"/>\n```',+ ),+ ).toEqual([+ expect.objectContaining({+ type: "paragraph",+ tokens: [{ type: "codespan", text: '<insight id="x"/>' }],+ }),+ { type: "space" },+ { type: "code", lang: "", text: '<insight id="x" display="block"/>' },+ ]);+ });+});++describe("isObjectTagMarkup", () => {+ it.each([+ ['<insight id="x">', true],+ ["</insight>", true],+ ['<hogql display="block">', true],+ ["<b>", false],+ ["<br/>", false],+ ])("%s -> %s", (html, expected) => {+ expect(isObjectTagMarkup(html)).toBe(expected);+ });+});++describe("objectWebUrl", () => {+ it.each([+ ["insight", "9pQx3", "https://us.posthog.com/project/2/insights/9pQx3"],+ [+ "hogql",+ "SELECT 1 & 2",+ "https://us.posthog.com/project/2/sql?open_query=SELECT%201%20%26%202",+ ],+ ["flag", "42", "https://us.posthog.com/project/2/feature_flags/42"],+ ["flag", "my-flag", null],+ ["gizmo", "1", null],+ ])("%s %s", (kind, id, expected) => {+ expect(objectWebUrl("https://us.posthog.com/", 2, kind, id)).toBe(expected);+ });+});diff --git a/products/desktop/apps/mobilehog/src/lib/objectTags.ts b/products/desktop/apps/mobilehog/src/lib/objectTags.tsnew file mode 100644index 000000000000..573854b0b80f--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/objectTags.ts@@ -0,0 +1,203 @@+import {+ buildObjectTagRef,+ type ObjectTagRef,+ objectWebPath,+ parseObjectTagAttrs,+ resolveObjectKindName,+} from "@posthog/core/inbox/objectTags";+import type { Token, TokenizerExtension } from "marked";++// Agents embed PostHog objects in replies as tags, e.g.+// <insight id="9pQx3">checkout funnel</insight>+// <insight id="9pQx3" display="block"/>+// <hogql display="block" title="DAU">SELECT ...</hogql>+// These marked extensions turn them into chip and card tokens. Code spans and+// fences are tokenized first, so tags inside them stay literal.++// Each card makes a request on mount; past the cap a block tag becomes a chip.+const MAX_CARDS = 10;++const TAG_RE =+ /^<([a-z][\w-]*)((?:\s+[a-z][\w-]*\s*=\s*"[^"]*")*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>)/;+const BLOCK_TAIL_RE = /^[ \t]*(?:\n+|$)/;+const BLOCK_TAG_START_RE =+ /(?:^|\n) {0,3}<(?:(?:insight)|(?:hogql))(?=[\s/>])(?=[^>\n]*\sdisplay\s*=\s*"block"(?=\s|\/?>))[^>\n]*\/?>/;+const OPEN_TAG_RE = /^<([a-z][\w-]*)(?:\s+[a-z][\w-]*\s*=\s*"[^"]*")*\s*>/;+const TAG_NAME_RE = /^<([a-z][\w-]*)/;+// One piece of an opening tag that is still streaming. Each piece consumes at+// least one character and the pieces cannot overlap, so a scan stays linear.+const PARTIAL_PART_RE = /\s+|[a-z][\w-]*|=|"[^"]*"|"[^"]*$|\/$/y;+const TAG_START_RE = /<[a-z]/;+const MARKUP_RE = /^<\/?([a-z][\w-]*)/;++export type ObjectCardSpec =+ | { mode: "insight"; shortId: string; title?: string }+ | { mode: "hogql"; query: string; title?: string };++export interface ObjectCardToken {+ type: "objectCard";+ raw: string;+ spec: ObjectCardSpec;+}++export interface ObjectRefToken {+ type: "objectRef";+ raw: string;+ ref: ObjectTagRef;+}++interface MatchedTag {+ raw: string;+ name: string;+ kind: string | null;+ attrs: Record<string, string>;+ body?: string;+}++function matchTag(src: string): MatchedTag | null {+ const match = TAG_RE.exec(src);+ if (!match) return null;+ return {+ raw: match[0],+ name: match[1],+ kind: resolveObjectKindName(match[1]),+ attrs: parseObjectTagAttrs(match[2]),+ body: match[3],+ };+}++function cardSpec(tag: MatchedTag): ObjectCardSpec | null {+ if (tag.attrs.display !== "block") return null;+ const title = tag.attrs.title?.trim() || undefined;+ if (tag.kind === "insight") {+ const shortId = tag.attrs.id?.trim();+ return shortId ? { mode: "insight", shortId, title } : null;+ }+ if (tag.kind === "hogql") {+ const query = tag.body?.trim();+ return query ? { mode: "hogql", query, title } : null;+ }+ return null;+}++// An unknown kind is still an object tag when it carries an id.+function isObjectTag(tag: MatchedTag): boolean {+ return tag.kind !== null || "id" in tag.attrs;+}++// Unknown kinds, and known kinds without an id or query, keep only their label.+function inlineToken(tag: MatchedTag): Token {+ const ref = tag.kind+ ? buildObjectTagRef(tag.kind, tag.attrs, tag.body)+ : null;+ if (ref) return { type: "objectRef", raw: tag.raw, ref } as Token;+ const label = tag.body?.trim() || tag.attrs.label?.trim();+ return { type: "text", raw: tag.raw, text: label ?? "" };+}++// A known tag that is still streaming has no end yet. It hides up to the end of+// the text, so neither its markup nor its half-written label shows.+// The name of a tag whose opening markup runs to the end of the text.+function partialTagName(src: string): string | null {+ const head = TAG_NAME_RE.exec(src);+ if (!head) return null;+ PARTIAL_PART_RE.lastIndex = head[0].length;+ while (PARTIAL_PART_RE.lastIndex < src.length) {+ if (!PARTIAL_PART_RE.exec(src)) return null;+ }+ return head[1];+}++function isUnfinishedTag(src: string): boolean {+ const name = OPEN_TAG_RE.exec(src)?.[1] ?? partialTagName(src);+ if (!name || resolveObjectKindName(name) === null) return false;+ return !new RegExp(`</${name}\\s*>`).test(src);+}++// A fresh set per document, so the card cap counts one message at a time.+export function objectTagExtensions(): TokenizerExtension[] {+ let cards = 0;+ return [+ {+ name: "objectCard",+ level: "block",+ start(src) {+ const match = BLOCK_TAG_START_RE.exec(src);+ return match ? match.index + match[0].lastIndexOf("<") : undefined;+ },+ tokenizer(src) {+ const indent = /^ {0,3}/.exec(src)?.[0].length ?? 0;+ const source = src.slice(indent);+ const tag = matchTag(source);+ if (!tag) {+ return isUnfinishedTag(source)+ ? { type: "html", raw: src, text: "" }+ : undefined;+ }+ if (!isObjectTag(tag)) return undefined;+ const end = indent + tag.raw.length;+ const tail = BLOCK_TAIL_RE.exec(src.slice(end));+ if (!tail) return undefined;+ const raw = src.slice(0, end + tail[0].length);+ const spec = cardSpec(tag);+ if (spec && cards < MAX_CARDS) {+ cards++;+ return { type: "objectCard", raw, spec };+ }+ // Like a Markdown paragraph, the fallback leaves its line breaks to the+ // lexer, so a blank line still ends it.+ return {+ type: "paragraph",+ raw: src.slice(0, end + tail[0].trimEnd().length),+ text: tag.raw,+ tokens: this.lexer.inline(tag.raw),+ };+ },+ },+ {+ name: "objectRef",+ level: "inline",+ start(src) {+ const index = src.search(TAG_START_RE);+ return index === -1 ? undefined : index;+ },+ tokenizer(src) {+ const tag = matchTag(src);+ if (tag) return isObjectTag(tag) ? inlineToken(tag) : undefined;+ return isUnfinishedTag(src)+ ? { type: "text", raw: src, text: "" }+ : undefined;+ },+ },+ ];+}++export function isObjectCardToken(+ token: Token,+): token is Token & ObjectCardToken {+ return token.type === "objectCard";+}++export function isObjectRefToken(+ token: Token,+): token is Token & ObjectRefToken {+ return token.type === "objectRef";+}++// Markup of a known tag that is malformed or still streaming stays hidden.+export function isObjectTagMarkup(html: string): boolean {+ const match = MARKUP_RE.exec(html.trim());+ return match !== null && resolveObjectKindName(match[1]) !== null;+}++export function objectWebUrl(+ host: string,+ projectId: number,+ kind: string,+ id: string,+): string | null {+ const path = objectWebPath(kind, id);+ return path+ ? `${host.replace(/\/+$/, "")}/project/${projectId}${path}`+ : null;+}diff --git a/products/desktop/apps/mobilehog/src/lib/queries.ts b/products/desktop/apps/mobilehog/src/lib/queries.tsindex 546d2bb6758d..424419dbe073 100644--- a/products/desktop/apps/mobilehog/src/lib/queries.ts+++ b/products/desktop/apps/mobilehog/src/lib/queries.ts@@ -30,6 +30,7 @@ export const keys = {["run-artifacts", taskId, runId] as const,photoUrl: (taskId: string, runId: string, artifactId: string) =>["photo-url", taskId, runId, artifactId] as const,+ insight: (shortId: string) => ["insights", shortId] as const,};// Presigned photo URLs expire after an hour; refresh them well before that.@@ -130,6 +131,16 @@ export function useTask(taskId: string) {});}+export function useInsightSummary(shortId: string) {+ const session = useAuth((s) => s.session);+ return useQuery({+ queryKey: keys.insight(shortId),+ queryFn: () => getClient().getInsightSummary(shortId),+ enabled: !!session,+ staleTime: 5 * 60_000,+ });+}+// The gateway may not be running locally, so the pill always has a default.export function useModels() {const session = useAuth((s) => s.session);diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.tsindex 95051c9928d8..c1d7258c8ffb 100644--- a/products/desktop/packages/api-client/src/posthog-client.test.ts+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts@@ -421,6 +421,39 @@ describe("PostHogAPIClient", () => {});});+ describe("getInsightSummary", () => {+ it("reads the insight from cache and falls back to its derived name", async () => {+ const fetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ id: 1,+ short_id: "sdyR2Pn8",+ name: "",+ derived_name: "Pageview count",+ description: "",+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );+ const client = new PostHogAPIClient(+ "https://app.posthog.test",+ async () => "token",+ async () => "token",+ 42,+ { fetch },+ );++ await expect(client.getInsightSummary("sdyR2Pn8")).resolves.toEqual({+ name: "Pageview count",+ description: null,+ });+ const url = fetch.mock.calls[0][0] as URL;+ expect(url.pathname).toBe("/api/projects/42/insights/sdyR2Pn8/");+ expect(url.searchParams.get("basic")).toBe("true");+ expect(url.searchParams.get("refresh")).toBe("force_cache");+ });+ });+describe("getEvidencePreview", () => {it("retrieves an Inbox report from the signals endpoint", async () => {const fetch = vi.fn().mockResolvedValue(diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 025135a18be5..beda4c356b53 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -7770,6 +7770,39 @@ export class PostHogAPIClient {}}+ /**+ * The insight's name and description by short id. Reads the cache only, so+ * a reference card never runs the insight's query.+ */+ async getInsightSummary(shortId: string): Promise<{+ name: string | null;+ description: string | null;+ } | null> {+ const projectId = (await this.getTeamId()).toString();+ try {+ const urlPath = `/api/projects/${projectId}/insights/${encodeURIComponent(shortId)}/`;+ const url = new URL(`${this.api.baseUrl}${urlPath}`);+ url.searchParams.set("basic", "true");+ url.searchParams.set("refresh", "force_cache");+ const response = await this.api.fetcher.fetch({+ method: "get",+ url,+ path: urlPath,+ });+ const insight = (await response.json()) as Pick<+ Schemas.Insight,+ "name" | "derived_name" | "description"+ >;+ return {+ name: insight.name || insight.derived_name || null,+ description: insight.description || null,+ };+ } catch (error) {+ if (requestErrorStatus(error) === 404) return null;+ throw error;+ }+ }+/*** 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