: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
fix(posthog-ai): render agent object tags as links instead of stripping them (#101455)
Vojta Bartošdb5ce00fed71
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e466de8b319f..67fded96cc2c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6033,13 +6033,13 @@ snapshots:products-posthog-ai-debuglogsmenu--staff-primitive--light:hash: v1.k794b7964.f19770892ea0bf6cae9997d6e364c4694a74f607e4e087d83c850a92cbaaae75.FxREU9FWVvU9WvA0uMJYiYzrSDQDhi_TBKi4lAV_pq8products-posthog-ai-markdownmessage--desktop-conversation--dark:- hash: v1.k794b7964.c908676310f415537ca83ea9cb4dfe0c2b85ff894d3984bbdb519ab27734f134.qC_FMYS0XvdgxK8zkBTol3af8o9B1yt50Bvw_Hqh3A4+ hash: v1.k794b7964.a1cd2283b18448b21ae52d62f18e05b94db9c4a96fc71738334f7a6a3aafa9da.SkqGN4c2lKUPPGvEwgYSCithZAHKAdoSrnUb9d-p9e0products-posthog-ai-markdownmessage--desktop-conversation--light:- hash: v1.k794b7964.84bc67ddb80ff9e45ac761ffd252c65dac81d831f9e49ba41c337662efd32c4e.C3ZqsqW7xcq0Jhl5bjN_wINP4Idp0eDaDY_TFBGTul0+ hash: v1.k794b7964.c8286557b00172dca36a0d3e5a1061330f4701825cc3d7d614ab0ce7b7d210c1.SP5EeHdk2EVSl3tk5gR26LZK5WUF7y5eP9OYz0mc4Mkproducts-posthog-ai-markdownmessage--narrow--dark:- hash: v1.k794b7964.e77e2f37b19e26eca8b5e52be9831d0429294d63f305ee16fb641d5e6d842c5a.QIidfBcNV5M3O5MBQuehpK8R9g_B0VpGgK8I6PtvnPg+ hash: v1.k794b7964.f7c555149379230fa37b772b3646d57f50ad95786c848cf1bfe16d70fd936170.MZLNygo-G4HG79tswcCCtcbNjIhysajt6U2XIZqrJ0Eproducts-posthog-ai-markdownmessage--narrow--light:- hash: v1.k794b7964.e0e85811ba4860e1f5f0facc9a069a3acda781e9e8cddf50378a23171e4866ad.1SQK2-d5PrZQBx0GSvO2qRv8n4tgM5X4qYQ34NjLWTo+ hash: v1.k794b7964.d2882f58f54e18814d3dac68b2ce7c243e8c44b14b830f4e6464b682d9a8edc9.oHFOlkFZ5v9nmOnYyNGamUVY34qYSIeA9GchABGr3Rwproducts-posthog-ai-onboardingtakeover--awaiting-clip--dark:hash: v1.k794b7964.ce34e421ee0ac8dc6b49c9bc2d52791298561b4ab0ae74add1780c7b1e82114f.QZzI-wxiMSzGEymlFhQuyVyPBJs10NJUpnH6GOxDlO0products-posthog-ai-onboardingtakeover--awaiting-clip--light:diff --git a/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.test.ts b/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.test.tsnew file mode 100644index 000000000000..e97381038bf9--- /dev/null+++ b/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.test.ts@@ -0,0 +1,110 @@+import { rewriteAgentObjectTags } from './rewriteAgentObjectTags'++const BASE = '/project/2'++describe('rewriteAgentObjectTags', () => {+ it.each([+ [+ 'labeled inline tag',+ 'See <insight id="9pQx3">checkout funnel</insight>.',+ 'See [checkout funnel](/project/2/insights/9pQx3).',+ ],+ [+ 'self-closing block tag with a title (the empty-bullet repro)',+ '- <insight id="geFISqzd" display="block" title="Sandbox 2.0 — external chats"/>',+ '- [Sandbox 2.0 — external chats](/project/2/insights/geFISqzd)',+ ],+ [+ 'bare-id body written by older notebook tools',+ 'See <insight>abc123</insight>.',+ 'See [Insight abc123](/project/2/insights/abc123).',+ ],+ ['alias kind', '<recording id="s1">the session</recording>', '[the session](/project/2/replay/s1)'],+ [+ 'flag cited by numeric id links, by key stays a label',+ '<flag id="42">new-flow</flag> vs <flag id="my-key">old-flow</flag>',+ '[new-flow](/project/2/feature_flags/42) vs old-flow',+ ],+ [+ 'inline hogql links into the SQL editor',+ 'See <hogql label="signups today">SELECT count() FROM events</hogql>.',+ 'See [signups today](/project/2/sql?open_query=SELECT%20count%28%29%20FROM%20events).',+ ],+ [+ 'unknown kind keeps the label and drops the markup',+ 'From <inbox id="r1">the report</inbox>.',+ 'From the report.',+ ],+ [+ 'label unsafe for a markdown link is sanitized',+ '<insight id="a">Error [rate] > 1% | daily</insight>',+ '[Error rate > 1% daily](/project/2/insights/a)',+ ],+ ])('%s', (_name, input, expected) => {+ expect(rewriteAgentObjectTags(input, BASE)).toBe(expected)+ })++ it('renders a block hogql tag as a linked title over a fence with its caption', () => {+ const input = 'Numbers:\n<hogql display="block" title="DAU" caption="last 7 days">SELECT 1</hogql>\nDone.'+ expect(rewriteAgentObjectTags(input, BASE)).toBe(+ 'Numbers:\n\n**[DAU](/project/2/sql?open_query=SELECT%201)**\n```\nSELECT 1\n```\n_last 7 days_\n\nDone.'+ )+ })++ it.each([+ ['inline code', 'Use `<insight id="a">kept</insight>`.'],+ ['fenced code', '```xml\n<insight id="a">kept</insight>\n```'],+ ['plain text without tags', 'Nothing to do here.'],+ ['unknown non-object markup', 'A <div>block</div> stays.'],+ ['an unclosed fence containing a tag', 'Before\n```\n<insight id="a">x</insight>'],+ ['a trailing opener inside inline code', 'Use `<insight id="a">`'],+ ['a trailing partial that matches no kind', 'plain <widget'],+ ['a comparison that looks like a partial tag', 'value a<b'],+ ])('leaves %s untouched', (_name, input) => {+ expect(rewriteAgentObjectTags(input, BASE)).toBe(input)+ })++ it.each([+ ['a partial opener of a known kind', 'Streaming <insi', 'Streaming '],+ ['a complete opener whose closer has not arrived', 'Streaming <insight id="a">Runtime', 'Streaming '],+ ['an unregistered opener carrying an id', 'From <inbox id="r1">the rep', 'From '],+ ])('holds back %s until the rest of the chunk arrives', (_name, input, expected) => {+ expect(rewriteAgentObjectTags(input, BASE)).toBe(expected)+ })++ it('does not split a complete hogql tag whose SQL quotes tag markup', () => {+ expect(rewriteAgentObjectTags('See <hogql label="q">SELECT \'<insight id="x">\'</hogql>.', BASE)).toBe(+ 'See [q](/project/2/sql?open_query=SELECT%20%27%3Cinsight%20id%3D%22x%22%3E%27).'+ )+ })++ it('grows the fence past any backtick run in the SQL', () => {+ expect(rewriteAgentObjectTags('<hogql display="block" title="T">a\n```\nb</hogql>', BASE)).toBe(+ '**[T](/project/2/sql?open_query=a%0A%60%60%60%0Ab)**\n````\na\n```\nb\n````'+ )+ })++ it('keeps markdown link syntax in a caption inert', () => {+ expect(+ rewriteAgentObjectTags(+ '<hogql display="block" title="T" caption="">SELECT 1</hogql>',+ BASE+ )+ ).toBe('**[T](/project/2/sql?open_query=SELECT%201)**\n```\nSELECT 1\n```\n_! x (https://evil.test/p)_')+ })++ it('drops a list marker whose only content is a promoted block', () => {+ expect(rewriteAgentObjectTags('- <hogql display="block" title="T">SELECT 1</hogql>', BASE)).toBe(+ '**[T](/project/2/sql?open_query=SELECT%201)**\n```\nSELECT 1\n```'+ )+ })++ it('is idempotent over its own output', () => {+ const once = rewriteAgentObjectTags('- <insight id="a" display="block" title="T"/>', BASE)+ expect(rewriteAgentObjectTags(once, BASE)).toBe(once)+ })++ it('links project-relative when no project base is known', () => {+ expect(rewriteAgentObjectTags('<insight id="a">x</insight>', '')).toBe('[x](/insights/a)')+ })+})diff --git a/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.ts b/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.tsnew file mode 100644index 000000000000..545d2cf41ac0--- /dev/null+++ b/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.ts@@ -0,0 +1,422 @@+/**+ * Rewrite agent object tags into markdown the web app can render.+ *+ * Agents cite PostHog objects with XML-style tags+ * (`<insight id="9pQx3">checkout funnel</insight>`,+ * `<insight id="x" display="block" title="…"/>`). The desktop app renders them+ * as chips; the web markdown pipeline (`ReactMarkdown` with `skipHtml`) drops+ * raw HTML nodes, so a label-less block tag renders as nothing. This module+ * runs before markdown parsing and turns each tag into a link into the+ * current project, a fenced SQL block, or just the label.+ *+ * The kind registry is generated from `posthog/object_tags/kinds.py`, and the+ * transform mirrors the Slack renderer+ * (`products/tasks/backend/temporal/slack_relay/object_tags.py`) minus its+ * Slack-specific escaping, so a reply reads the same on both surfaces. Tags+ * inside fenced code blocks and inline code spans stay literal. A trailing+ * tag or fence that is still streaming in is held back from the rendered+ * output; it re-renders whole once the rest of the chunk arrives.+ */+import { OBJECT_KIND_ALIASES, OBJECT_KIND_DATA, ObjectKindData } from './objectKinds.generated'++// A link whose URL is longer than this degrades to its plain label; a SQL editor+// deep link carries the whole query in the query string.+const MAX_LINK_URL_LENGTH = 2000++// A streamed render that ends inside a tag would flash the fragments as raw text;+// hold back at most this much so a genuinely unterminated tag still shows eventually.+const MAX_HELD_SUFFIX = 4000++const RE_OPEN_TAG = /<([a-z][\w-]*)((?:\s+[a-z][\w-]*\s*=\s*"[^"]*")*)\s*(\/>|>)/g+const RE_CLOSE_TAG = /<\/([a-z][\w-]*)\s*>/g+const RE_ATTR = /([a-z][\w-]*)\s*=\s*"([^"]*)"/g+const RE_FENCE_LINE = /^ {0,3}(`{3,}|~{3,})/+const RE_BACKTICK_RUN = /`+/g+const RE_LABEL_UNSAFE = /[[\]|]/g+const RE_BARE_ID = /^[\w$.:-]{1,64}$/+const RE_PARTIAL_OPEN_TAG = /^<(?:[a-z][\w-]*(?:\s[^>]*)?)?$/++// Only the five entities the desktop composer's XML serializer emits (`escapeXmlAttr`);+// the full HTML entity table would rewrite SQL literals such as `'©'`.+const XML_ENTITIES: Record<string, string> = {+ '"': '"',+ ''': "'",+ '<': '<',+ '>': '>',+ '&': '&',+}+const RE_XML_ENTITY = /&(?:quot|apos|lt|gt|amp);/g++function unescapeXml(value: string): string {+ return value.replace(RE_XML_ENTITY, (entity) => XML_ENTITIES[entity])+}++interface Span {+ start: number+ end: number+}++interface Tag {+ name: string+ attrs: Record<string, string>+ body: string+ start: number+ end: number+}++function resolveKind(name: string): ObjectKindData | null {+ const canonical = OBJECT_KIND_ALIASES[name] ?? name+ return (OBJECT_KIND_DATA as Record<string, ObjectKindData>)[canonical] ?? null+}++function parseAttrs(raw: string): Record<string, string> {+ const attrs: Record<string, string> = {}+ for (const match of raw.matchAll(RE_ATTR)) {+ attrs[match[1]] = unescapeXml(match[2])+ }+ return attrs+}++/** CommonMark inline code on one line: a run of N backticks closes on the next run of exactly N. */+function inlineCodeSpans(line: string, offset: number): Span[] {+ const runs = Array.from(line.matchAll(RE_BACKTICK_RUN))+ const spans: Span[] = []+ let index = 0+ while (index < runs.length) {+ const opener = runs[index]+ const length = opener[0].length+ const closerIndex = runs.findIndex((run, i) => i > index && run[0].length === length)+ if (closerIndex === -1) {+ index += 1+ continue+ }+ const closer = runs[closerIndex]+ spans.push({ start: offset + opener.index, end: offset + closer.index + closer[0].length })+ index = closerIndex + 1+ }+ return spans+}++/**+ * Fenced blocks and inline code, found in one pass over the lines. Mirrors the+ * desktop renderer's fence rules: a backtick or tilde fence of three or more,+ * closed only by a run of the same character at least as long with nothing else+ * on the line, and an unclosed fence runs to the end of the text.+ */+function scanCode(text: string): Span[] {+ const spans: Span[] = []+ let fenceChar = ''+ let fenceLength = 0+ let fenceStart = 0+ let offset = 0+ for (const line of text.split('\n')) {+ const fence = RE_FENCE_LINE.exec(line)+ if (fenceChar) {+ const closes =+ fence !== null &&+ fence[1][0] === fenceChar &&+ fence[1].length >= fenceLength &&+ line.slice(fence[0].length).trim() === ''+ if (closes) {+ spans.push({ start: fenceStart, end: offset + line.length })+ fenceChar = ''+ }+ } else if (fence) {+ fenceChar = fence[1][0]+ fenceLength = fence[1].length+ fenceStart = offset+ } else {+ spans.push(...inlineCodeSpans(line, offset))+ }+ offset += line.length + 1+ }+ if (fenceChar) {+ spans.push({ start: fenceStart, end: text.length })+ }+ return spans+}++/**+ * Find complete tags in `text` in order, without overlaps. Openers that start+ * inside code spans are not tags, and a tag whose closer never arrives is not a+ * tag either: the text stays as it was.+ */+function scanTags(text: string, skipSpans: Span[]): Tag[] {+ const closers = new Map<string, RegExpExecArray[]>()+ for (const close of text.matchAll(RE_CLOSE_TAG)) {+ const list = closers.get(close[1]) ?? []+ list.push(close)+ closers.set(close[1], list)+ }+ const cursors = new Map<string, number>()+ const tags: Tag[] = []+ let nextAllowed = 0+ let spanCursor = 0+ for (const match of text.matchAll(RE_OPEN_TAG)) {+ const start = match.index+ // Openers and spans are both in text order, so the span cursor only moves forward.+ while (spanCursor < skipSpans.length && skipSpans[spanCursor].end <= start) {+ spanCursor += 1+ }+ const inCode =+ spanCursor < skipSpans.length && skipSpans[spanCursor].start <= start && start < skipSpans[spanCursor].end+ if (start < nextAllowed || inCode) {+ continue+ }+ const name = match[1]+ const attrs = parseAttrs(match[2])+ const openEnd = start + match[0].length+ if (match[3] === '/>') {+ tags.push({ name, attrs, body: '', start, end: openEnd })+ nextAllowed = openEnd+ continue+ }+ const candidates = closers.get(name) ?? []+ let cursor = cursors.get(name) ?? 0+ while (cursor < candidates.length && candidates[cursor].index < openEnd) {+ cursor += 1+ }+ cursors.set(name, cursor)+ if (cursor >= candidates.length) {+ continue+ }+ const close = candidates[cursor]+ tags.push({ name, attrs, body: text.slice(openEnd, close.index), start, end: close.index + close[0].length })+ nextAllowed = close.index + close[0].length+ }+ return tags+}++function safeLabel(label: string): string {+ // Brackets and pipes end a markdown link label early, and a raw angle bracket+ // would parse as HTML that `skipHtml` then drops. The entities render back as+ // the characters.+ const collapsed = label.replace(RE_LABEL_UNSAFE, ' ').split(/\s+/).filter(Boolean).join(' ')+ return collapsed.replace(/</g, '<').replace(/>/g, '>')+}++function link(label: string, url: string | null): string {+ if (url === null || url.length > MAX_LINK_URL_LENGTH) {+ return label+ }+ return `[${label}](${url})`+}++function encodeObjectId(objectId: string): string {+ // `encodeURIComponent` leaves `!'()*` bare, but an unencoded `)` ends a+ // markdown `[label](url)` link early. Encoding them also matches Python's+ // `quote(safe="")`, so the Slack renderer and this one emit identical URLs.+ return encodeURIComponent(objectId).replace(+ /[!'()*]/g,+ (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`+ )+}++// Guard patterns are static generated data and this module runs on every render+// of every streamed message, so compile them once at module load.+const ID_GUARDS = new Map<ObjectKindData, RegExp>(+ Object.values(OBJECT_KIND_DATA).flatMap((data) =>+ data.idPattern !== null ? [[data, new RegExp(data.idPattern)] as const] : []+ )+)++function objectUrl(projectBase: string, kind: ObjectKindData, objectId: string): string | null {+ if (kind.pathTemplate === null) {+ return null+ }+ const guard = ID_GUARDS.get(kind)+ if (guard && !guard.test(objectId)) {+ return null+ }+ return projectBase + kind.pathTemplate.replace('{id}', encodeObjectId(objectId))+}++function renderHogql(tag: Tag, projectBase: string): string | null {+ // A body written by the desktop composer is XML-escaped, so `<` is a `<` in the SQL.+ const sql = unescapeXml(tag.body).trim()+ if (!sql) {+ return null+ }+ const hogql = OBJECT_KIND_DATA.hogql+ const url = objectUrl(projectBase, hogql, sql)+ if (tag.attrs['display'] !== 'block') {+ const label = safeLabel(tag.attrs['label'] || tag.attrs['title'] || '') || hogql.kindLabel+ return link(label, url)+ }+ const title = safeLabel(tag.attrs['title'] || '') || hogql.kindLabel+ // A backtick run in the SQL at least as long as the fence would close it early+ // and spill the rest of the query into ordinary markdown.+ const longestRun = Math.max(0, ...Array.from(sql.matchAll(RE_BACKTICK_RUN), (run) => run[0].length))+ const fence = '`'.repeat(Math.max(3, longestRun + 1))+ const lines = [`**${link(title, url)}**`, fence, sql, fence]+ // Same treatment as every other agent-authored string here: without it the+ // caption is the one attribute that could smuggle markdown link/image syntax.+ const caption = safeLabel(tag.attrs['caption'] || '')+ if (caption) {+ lines.push(`_${caption}_`)+ }+ return lines.join('\n')+}++function renderReference(tag: Tag, kind: ObjectKindData, projectBase: string): string | null {+ let objectId = (tag.attrs['id'] || '').trim()+ let body = tag.body.trim()+ if (!objectId && RE_BARE_ID.test(body)) {+ // The older `<insight>abc123</insight>` form Max's notebook tools still write.+ objectId = body+ body = ''+ }+ if (!objectId) {+ // A tag with a title but no id (a notebook query node) has no page to link; keep the title.+ return safeLabel(tag.attrs['title'] || '') || null+ }+ const label = safeLabel(tag.attrs['title'] || body) || `${kind.kindLabel} ${safeLabel(objectId)}`+ return link(label, objectUrl(projectBase, kind, objectId))+}++function renderTag(tag: Tag, projectBase: string): string | null {+ const kind = resolveKind(tag.name)+ if (kind === null) {+ // An agent sometimes extends the convention to a kind nobody renders+ // (`<inbox id="…">`). The label is still the useful part, so keep it and+ // drop the markup — but only for tags shaped like object references.+ const label = safeLabel(tag.body)+ return 'id' in tag.attrs && label ? label : null+ }+ if (kind.idIsBody) {+ return renderHogql(tag, projectBase)+ }+ return renderReference(tag, kind, projectBase)+}++// One compiled closer pattern per kind name; only registered kinds reach the+// lookup, so the cache stays a couple dozen entries.+const CLOSER_RES = new Map<string, RegExp>()++function closerRe(name: string): RegExp {+ let re = CLOSER_RES.get(name)+ if (!re) {+ re = new RegExp(`</${name}\\s*>`)+ CLOSER_RES.set(name, re)+ }+ return re+}++const KNOWN_TAG_NAMES = [...Object.keys(OBJECT_KIND_DATA), ...Object.keys(OBJECT_KIND_ALIASES)]+const RE_ID_ATTR = /(?:^|\s)id\s*=/++function inSpan(position: number, spans: Span[]): boolean {+ return spans.some((span) => span.start <= position && position < span.end)+}++/**+ * Could this partial tag fragment still become a tag the renderer would touch?+ * Either the name so far is a prefix of a registered kind, or the fragment+ * already carries an `id` attribute (the object-shaped improvisations the+ * renderer keeps the label of). Anything else — `plain <widget` — is prose.+ */+function partialCouldBecomeTag(fragment: string): boolean {+ const name = /^<([a-z][\w-]*)/.exec(fragment)?.[1] ?? ''+ if (/\s/.test(fragment)) {+ // The name is complete; only the attributes are still streaming.+ return resolveKind(name) !== null || RE_ID_ATTR.test(fragment.slice(1 + name.length))+ }+ return KNOWN_TAG_NAMES.some((known) => known.startsWith(name))+}++/**+ * Index where a trailing object tag that has not finished streaming in begins,+ * or null. Mirrors the Slack relay's `split_incomplete_tag_suffix`, minus its+ * fence holding: the Slack splitter is stateless across flushes and must keep+ * an open fence buffered, while here the whole text re-renders every chunk and+ * `scanCode` already keeps tags inside an open fence literal.+ *+ * Only the region after `searchFrom` (the end of the last complete tag) is+ * considered, so tag-shaped text inside a complete tag's body — SQL quoting+ * `'<insight id="x">'` — never splits the text. Openers inside code spans are+ * prose, not streaming tags.+ */+function heldSuffixStart(text: string, spans: Span[], searchFrom: number): number | null {+ const lastLt = text.lastIndexOf('<')+ if (+ lastLt >= searchFrom &&+ !inSpan(lastLt, spans) &&+ !text.slice(lastLt).includes('>') &&+ RE_PARTIAL_OPEN_TAG.test(text.slice(lastLt)) &&+ partialCouldBecomeTag(text.slice(lastLt))+ ) {+ return lastLt+ }+ let lastOpen: { start: number; end: number; name: string } | null = null+ for (const match of text.matchAll(RE_OPEN_TAG)) {+ if (match.index < searchFrom || match[3] !== '>' || inSpan(match.index, spans)) {+ continue+ }+ if (resolveKind(match[1]) !== null || RE_ID_ATTR.test(match[2])) {+ lastOpen = { start: match.index, end: match.index + match[0].length, name: match[1] }+ }+ }+ if (lastOpen !== null && !closerRe(lastOpen.name).test(text.slice(lastOpen.end))) {+ return lastOpen.start+ }+ return null+}++/**+ * Replace agent object tags in `text` with markdown links into the project.+ *+ * `projectBase` is the app path every object link hangs off, e.g. `/project/2`.+ * Text with no tags passes through unchanged, so the transform is safe to run+ * on every render, including on text it already rewrote.+ */+export function rewriteAgentObjectTags(text: string, projectBase: string): string {+ if (!text.includes('<')) {+ return text+ }+ const spans = scanCode(text)+ const tags = scanTags(text, spans)+ // Complete tags all end before the held region starts, so the slice below+ // cannot invalidate them.+ const searchFrom = tags.length > 0 ? tags[tags.length - 1].end : 0+ const held = heldSuffixStart(text, spans, searchFrom)+ if (held !== null && text.length - held <= MAX_HELD_SUFFIX) {+ text = text.slice(0, held)+ }+ if (tags.length === 0) {+ return text+ }+ const base = projectBase.replace(/\/$/, '')+ let output = ''+ let position = 0+ let needsParagraphBreak = false+ for (const tag of tags) {+ const rendered = renderTag(tag, base)+ if (rendered === null) {+ continue+ }+ let before = text.slice(position, tag.start)+ if (needsParagraphBreak) {+ // The fence must end its line, so anything after it starts a new paragraph.+ before = '\n\n' + before.replace(/^\n+/, '')+ }+ needsParagraphBreak = false+ output += before+ if (rendered.includes('\n')) {+ // A fenced block only survives markdown conversion as its own paragraph.+ // A list marker whose only content is this block would be left as an+ // empty bullet once the block moves out, so the bare marker goes too.+ output = output.replace(/(^|\n)[ \t]{0,3}(?:[-*+]|\d{1,9}[.)])[ \t]*$/, '$1')+ if (output.trim() && !output.endsWith('\n\n')) {+ output = output.replace(/\n+$/, '') + '\n\n'+ }+ needsParagraphBreak = true+ }+ output += rendered+ position = tag.end+ }+ let rest = text.slice(position)+ if (needsParagraphBreak && rest.trim()) {+ rest = '\n\n' + rest.replace(/^\n+/, '')+ }+ return output + rest+}diff --git a/products/posthog_ai/frontend/messages/MarkdownMessage.test.tsx b/products/posthog_ai/frontend/messages/MarkdownMessage.test.tsxindex 1e08e916721b..9c5b54e07eae 100644--- a/products/posthog_ai/frontend/messages/MarkdownMessage.test.tsx+++ b/products/posthog_ai/frontend/messages/MarkdownMessage.test.tsx@@ -10,21 +10,37 @@ jest.mock('lib/lemon-ui/LemonMarkdown', () => ({}))describe('MarkdownMessage', () => {- it.each([- ['inline reference', 'Read <report id="example-report">the report</report>.', 'Read .'],- ['query block', '<hogql display="block" title="Daily signups">SELECT 1</hogql>', ''],- ['code example', '`<insight id="example">Funnel</insight>`', '``'],- ])('removes %s from a Desktop conversation', (_name, content, expected) => {- const { container } = render(<MarkdownMessage id="desktop-message" content={content} />)- expect(container.textContent).toBe(expected)+ it('renders an inline reference as a link carrying the agent label', () => {+ const { container } = render(+ <MarkdownMessage id="desktop-message" content='Read <report id="example-report">the report</report>.' />+ )+ expect(container.textContent).toBe('Read [the report](/inbox/example-report).')+ })++ it('renders a query block as a linked title over its SQL', () => {+ const { container } = render(+ <MarkdownMessage+ id="desktop-message"+ content='<hogql display="block" title="Daily signups">SELECT 1</hogql>'+ />+ )+ expect(container.textContent).toContain('[Daily signups](/sql?open_query=SELECT%201)')+ expect(container.textContent).toContain('SELECT 1')+ })++ it('leaves a tag inside inline code literal', () => {+ const { container } = render(+ <MarkdownMessage id="desktop-message" content='`<insight id="example">Funnel</insight>`' />+ )+ expect(container.textContent).toBe('`<insight id="example">Funnel</insight>`')})- it('hides the tag body during streaming', () => {+ it('hides the tag body during streaming and links it once complete', () => {const { container, rerender } = render(<MarkdownMessage id="streamed-message" content='Read <insight id="example">the' />)expect(container.textContent).toBe('Read ')rerender(<MarkdownMessage id="streamed-message" content='Read <insight id="example">the funnel</insight>.' />)- expect(container.textContent).toBe('Read .')+ expect(container.textContent).toBe('Read [the funnel](/insights/example).')})})diff --git a/products/posthog_ai/frontend/messages/MarkdownMessage.tsx b/products/posthog_ai/frontend/messages/MarkdownMessage.tsxindex eaabdb7152be..bdcae0052c81 100644--- a/products/posthog_ai/frontend/messages/MarkdownMessage.tsx+++ b/products/posthog_ai/frontend/messages/MarkdownMessage.tsx@@ -1,9 +1,10 @@import { marked } from 'marked'import { memo, useMemo } from 'react'+import { rewriteAgentObjectTags } from 'lib/components/AgentObjectTags/rewriteAgentObjectTags'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'--import { stripObjectTags } from '../utils/stripObjectTags'+import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'+import { urls } from 'scenes/urls'function parseMarkdownIntoBlocks(markdown: string): string[] {// Convert single newlines to markdown line breaks (two spaces + newline)@@ -12,6 +13,13 @@ function parseMarkdownIntoBlocks(markdown: string): string[] {return tokens.map((token) => token.raw)}+function rewriteObjectTags(markdown: string, teamId: number | null): string {+ // Agent object tags (`<insight id="…">label</insight>`) become links into the+ // current project, carrying the agent's label; stripping them instead posted+ // empty bullets wherever a reply cited an object.+ return rewriteAgentObjectTags(markdown, teamId !== null ? urls.project(teamId) : '')+}+/*** The optimized markdown renderer for messages.* Splits the markdown into blocks, so they can individually be memoized.@@ -25,7 +33,9 @@ export const MarkdownMessage = memo(function MarkdownMessage({id: stringclassName?: string}): JSX.Element {- const blocks = useMemo(() => parseMarkdownIntoBlocks(stripObjectTags(content)), [content])+ // The team id is a memo dependency so a project switch re-points existing links.+ const teamId = getCurrentTeamIdOrNone()+ const blocks = useMemo(() => parseMarkdownIntoBlocks(rewriteObjectTags(content, teamId)), [content, teamId])return (<LemonMarkdown.Container className={className}>{blocks.map((block, index) => (diff --git a/products/posthog_ai/frontend/utils/stripObjectTags.test.ts b/products/posthog_ai/frontend/utils/stripObjectTags.test.tsdeleted file mode 100644index 3a221218c6dc..000000000000--- a/products/posthog_ai/frontend/utils/stripObjectTags.test.ts+++ /dev/null@@ -1,47 +0,0 @@-import { stripObjectTags } from './stripObjectTags'--describe('stripObjectTags', () => {- it.each([- 'insight',- 'dashboard',- 'error',- 'replay',- 'flag',- 'experiment',- 'survey',- 'ticket',- 'report',- 'trace',- 'eval',- 'event',- 'cohort',- 'action',- 'person',- 'session-replay',- 'recording',- 'feature-flag',- 'feature_flag',- ])('removes the entire %s element', (kind) => {- expect(stripObjectTags(`Before <${kind} id="example">hidden label</${kind}> after.`)).toBe('Before after.')- })-- it.each([- ['SQL payload and title', '<hogql title="Daily signups" label="Fallback" display="block">SELECT 1</hogql>', ''],- ['SQL alias', '<sql>SELECT 1</sql>', ''],- ['self-closing block', '<replay id="example" title="Recording" display="block"/>', ''],- ['single-quoted attributes', "<insight id='example'>Hidden</insight>", ''],- ['nested same kind', '<insight>outer<insight>inner</insight>tail</insight>Kept', 'Kept'],- ['nested other kind', '<insight>outer<report>inner</report>tail</insight>Kept', 'Kept'],- ['consecutive elements', '<insight>One</insight><hogql>SELECT 1</hogql>Kept', 'Kept'],- ['unfinished body', 'Before <hogql title="Hidden">SELECT', 'Before '],- ['stray closing tag', 'Before </insight> after', 'Before after'],- ['inline code', 'Use `<insight>Hidden</insight>`.', 'Use ``.'],- ['fenced code', '```xml\n<insight>Hidden</insight>\n```', '```xml\n\n```'],- ['mixed code', '~~~\nKeep this.\n<insight>Hidden</insight>\n~~~', '~~~\nKeep this.\n\n~~~'],- ['unknown markup', '<summary>Keep this</summary>', '<summary>Keep this</summary>'],- ['Slack mention', '<@U000EXAMPLE|Example>', '<@U000EXAMPLE|Example>'],- ['empty text', '', ''],- ])('handles %s', (_name, content, expected) => {- expect(stripObjectTags(content)).toBe(expected)- })-})diff --git a/products/posthog_ai/frontend/utils/stripObjectTags.ts b/products/posthog_ai/frontend/utils/stripObjectTags.tsdeleted file mode 100644index 668bfc566c0f..000000000000--- a/products/posthog_ai/frontend/utils/stripObjectTags.ts+++ /dev/null@@ -1,62 +0,0 @@-const OBJECT_TAG_KINDS = new Set([- 'insight',- 'hogql',- 'dashboard',- 'error',- 'replay',- 'flag',- 'experiment',- 'survey',- 'ticket',- 'report',- 'trace',- 'eval',- 'event',- 'cohort',- 'action',- 'person',- 'session-replay',- 'recording',- 'feature-flag',- 'feature_flag',- 'sql',-])--const OBJECT_TAG = /<(\/?)([a-z][\w-]*)(?:\s+[a-z][\w-]*\s*=\s*(?:"[^"]*"|'[^']*'))*\s*(\/?)>/g--export function stripObjectTags(text: string): string {- const pieces: string[] = []- let cursor = 0- let activeKind: string | null = null- let depth = 0- for (const tag of text.matchAll(OBJECT_TAG)) {- const [, closing, kind, selfClosing] = tag- if (!OBJECT_TAG_KINDS.has(kind)) {- continue- }- if (activeKind !== null) {- if (kind === activeKind) {- if (closing) {- depth--- } else if (!selfClosing) {- depth++- }- if (depth === 0) {- activeKind = null- cursor = tag.index + tag[0].length- }- }- continue- }- pieces.push(text.slice(cursor, tag.index))- cursor = tag.index + tag[0].length- if (!closing && !selfClosing) {- activeKind = kind- depth = 1- }- }- if (activeKind === null) {- pieces.push(text.slice(cursor))- }- return pieces.join('')-}