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): let agents cite posthog objects as markdown links (#108550)

Shy Alter1fa83754f532
diff --git a/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts b/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts
index 6be8ab61a215..bcc3d531fc31 100644
--- a/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts
+++ b/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts
@@ -21,6 +21,7 @@ export interface ObjectKindData {
block: boolean
/** The tag body is the object id itself rather than a label (hogql: the SQL). */
idIsBody: boolean
+ urlAliases: readonly string[]
}
export const OBJECT_KIND_DATA = {
@@ -31,6 +32,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: true,
idIsBody: false,
+ urlAliases: ['/i/{id}'],
},
hogql: {
kindLabel: 'SQL query',
@@ -39,6 +41,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: true,
idIsBody: true,
+ urlAliases: ['/insights/new#q={query}'],
},
dashboard: {
kindLabel: 'Dashboard',
@@ -47,6 +50,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
error: {
kindLabel: 'Error issue',
@@ -55,6 +59,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
replay: {
kindLabel: 'Session replay',
@@ -63,6 +68,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: true,
idIsBody: false,
+ urlAliases: ['/replay/home?sessionRecordingId={id}'],
},
flag: {
kindLabel: 'Feature flag',
@@ -71,6 +77,7 @@ export const OBJECT_KIND_DATA = {
idPattern: '^\\d+$',
block: false,
idIsBody: false,
+ urlAliases: [],
},
experiment: {
kindLabel: 'Experiment',
@@ -79,6 +86,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
survey: {
kindLabel: 'Survey',
@@ -87,6 +95,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
ticket: {
kindLabel: 'Support tickets',
@@ -95,6 +104,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
report: {
kindLabel: 'Inbox report',
@@ -103,6 +113,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
trace: {
kindLabel: 'LLM trace',
@@ -111,6 +122,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
eval: {
kindLabel: 'Evaluation',
@@ -119,6 +131,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
event: {
kindLabel: 'Events',
@@ -127,6 +140,7 @@ export const OBJECT_KIND_DATA = {
idPattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F-]{27,}$',
block: false,
idIsBody: false,
+ urlAliases: [],
},
cohort: {
kindLabel: 'Cohort',
@@ -135,6 +149,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
action: {
kindLabel: 'Action',
@@ -143,6 +158,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
person: {
kindLabel: 'Person',
@@ -151,6 +167,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
} satisfies Record<string, ObjectKindData>
@@ -174,4 +191,9 @@ export const FALLBACK_OBJECT_KIND_DATA: ObjectKindData = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
}
+
+export const RESERVED_URL_IDS: readonly string[] = ['new', 'home', 'playlists', 'settings', 'configuration', 'options']
+
+export const APP_HOST_ALIASES: Record<string, string> = { 'app.posthog.com': 'us.posthog.com' }
diff --git a/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.test.ts b/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.test.ts
index e97381038bf9..dd0103c219c3 100644
--- a/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.test.ts
+++ b/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.test.ts
@@ -1,6 +1,7 @@
import { rewriteAgentObjectTags } from './rewriteAgentObjectTags'
const BASE = '/project/2'
+const APP = window.location.origin
describe('rewriteAgentObjectTags', () => {
it.each([
@@ -104,6 +105,32 @@ describe('rewriteAgentObjectTags', () => {
expect(rewriteAgentObjectTags(once, BASE)).toBe(once)
})
+ it.each([
+ [
+ 'a raw SQL link',
+ `Daily users:\n\n[DAU, last 7 days](${APP}/project/2/sql?open_query=SELECT%20count()%20FROM%20events "Bots excluded")\n\nDone.`,
+ `Daily users:\n\n**[DAU, last 7 days](${APP}/project/2/sql?open_query=SELECT%20count()%20FROM%20events)**\n\`\`\`\nSELECT count() FROM events\n\`\`\`\n_Bots excluded_\n\nDone.`,
+ ],
+ [
+ 'a query node SQL link',
+ `[Q](/project/2/sql?open_query=${encodeURIComponent(JSON.stringify({ kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'SELECT 1' } }))})`,
+ `**[Q](/project/2/sql?open_query=${encodeURIComponent(JSON.stringify({ kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'SELECT 1' } }))})**\n\`\`\`\nSELECT 1\n\`\`\``,
+ ],
+ ])('shows the query under %s alone in its paragraph', (_name, input, expected) => {
+ expect(rewriteAgentObjectTags(input, BASE)).toBe(expected)
+ expect(rewriteAgentObjectTags(expected, BASE)).toBe(expected)
+ })
+
+ it.each([
+ ['an inline SQL link', `See [q](${APP}/project/2/sql?open_query=SELECT%201) now.`],
+ ['a SQL link in a list', `- [q](${APP}/project/2/sql?open_query=SELECT%201)`],
+ ['a SQL link inside a fence', `\`\`\`\n\n[q](${APP}/project/2/sql?open_query=SELECT%201)\n\n\`\`\``],
+ ['a SQL-shaped link on another host', '[q](https://evil.example/project/2/sql?open_query=SELECT%201)'],
+ ['a link to another page', `[docs](${APP}/docs?open_query=x)`],
+ ])('leaves %s as written', (_name, input) => {
+ expect(rewriteAgentObjectTags(input, BASE)).toBe(input)
+ })
+
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.ts
index 1d99f3fd143b..86e8a7fd09b2 100644
--- a/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.ts
+++ b/frontend/src/lib/components/AgentObjectTags/rewriteAgentObjectTags.ts
@@ -39,6 +39,8 @@ 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_STANDALONE_LINK = /^\[([^[\]\n]*)\]\((?:<([^<>\n]*)>|(\S+?))(?:[ \t]+"([^"\n]*)")?\)[ \t]*$/
+const RE_SQL_EDITOR_PATH = /^(?:\/project\/\d+)?\/sql$/
const RE_PARTIAL_OPEN_TAG = /^<(?:[a-z][\w-]*(?:\s[^>]*)?)?$/
// Only the five entities the desktop composer's XML serializer emits (`escapeXmlAttr`);
@@ -246,6 +248,87 @@ export function objectKindLink(
return { kind, url: objectUrl(projectBase, kind, objectId) }
}
+function sqlBlock(title: string, url: string | null, sql: string, caption: string): string {
+ 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]
+ if (caption) {
+ lines.push(`_${caption}_`)
+ }
+ return lines.join('\n')
+}
+
+function hogqlFromQueryNode(raw: string): string | null {
+ let node: unknown
+ try {
+ node = JSON.parse(raw)
+ } catch {
+ return null
+ }
+ for (let depth = 0; depth < 3; depth++) {
+ if (typeof node !== 'object' || node === null) {
+ return null
+ }
+ const record = node as Record<string, unknown>
+ if (record.kind === 'HogQLQuery' && typeof record.query === 'string') {
+ return record.query
+ }
+ node = record.source
+ }
+ return null
+}
+
+function sqlFromEditorUrl(href: string): string | null {
+ let url: URL
+ try {
+ url = new URL(href, window.location.origin)
+ } catch {
+ return null
+ }
+ if (url.origin !== window.location.origin || !RE_SQL_EDITOR_PATH.test(url.pathname)) {
+ return null
+ }
+ const value = url.searchParams.get('open_query')?.trim()
+ if (!value) {
+ return null
+ }
+ return value.startsWith('{') ? (hogqlFromQueryNode(value)?.trim() ?? null) || null : value
+}
+
+function expandStandaloneSqlLinks(text: string): string {
+ if (!text.includes('open_query=')) {
+ return text
+ }
+ const spans = scanCode(text)
+ const lines = text.split('\n')
+ let offset = 0
+ let changed = false
+ const output = lines.map((line, index) => {
+ const lineStart = offset
+ offset += line.length + 1
+ const match = RE_STANDALONE_LINK.exec(line)
+ if (
+ !match ||
+ inSpan(lineStart, spans) ||
+ (index > 0 && lines[index - 1].trim()) ||
+ (index < lines.length - 1 && lines[index + 1].trim())
+ ) {
+ return line
+ }
+ const href = match[2] ?? match[3]
+ const sql = sqlFromEditorUrl(href)
+ if (sql === null) {
+ return line
+ }
+ changed = true
+ const destination = match[2] !== undefined ? `<${href}>` : href
+ const title = safeLabel(match[1]) || OBJECT_KIND_DATA.hogql.kindLabel
+ const url = href.length > MAX_LINK_URL_LENGTH ? null : destination
+ return sqlBlock(title, url, sql, safeLabel(match[4] ?? ''))
+ })
+ return changed ? output.join('\n') : text
+}
+
function renderHogql(tag: Tag, projectBase: string): string | null {
// A body written by the desktop composer is XML-escaped, so `&lt;` is a `<` in the SQL.
const sql = unescapeXml(tag.body).trim()
@@ -260,17 +343,10 @@ function renderHogql(tag: Tag, projectBase: string): string | null {
}
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')
+ // and spill the rest of the query into ordinary markdown. Same treatment as every
+ // other agent-authored string here: without it the caption is the one attribute
+ // that could smuggle markdown link/image syntax.
+ return sqlBlock(title, url, sql, safeLabel(tag.attrs['caption'] || ''))
}
function renderReference(tag: Tag, kind: ObjectKindData, projectBase: string): string | null {
@@ -385,6 +461,7 @@ function heldSuffixStart(text: string, spans: Span[], searchFrom: number): numbe
* on every render, including on text it already rewrote.
*/
export function rewriteAgentObjectTags(text: string, projectBase: string): string {
+ text = expandStandaloneSqlLinks(text)
if (!text.includes('<')) {
return text
}
diff --git a/packages/agent/packages/agent-contracts/src/objectTagKinds.generated.ts b/packages/agent/packages/agent-contracts/src/objectTagKinds.generated.ts
index ea03c315d9c5..37fbd059143a 100644
--- a/packages/agent/packages/agent-contracts/src/objectTagKinds.generated.ts
+++ b/packages/agent/packages/agent-contracts/src/objectTagKinds.generated.ts
@@ -2,6 +2,6 @@
// Source of truth: posthog/object_tags/kinds.py — after editing it,
// run `hogli build:projections` and commit the result.
-/** The kind list the rich-output prompt teaches agents. */
-export const OBJECT_TAG_PROMPT_KIND_LIST =
- "insight, dashboard, error, replay, flag, experiment, survey, ticket, report, trace, eval, event, cohort, action, person";
+/** The object paths the rich-output prompt teaches agents to link. */
+export const OBJECT_LINK_PROMPT_PATH_LIST =
+ "insight `/insights/<id>`, dashboard `/dashboard/<id>`, error `/error_tracking/<id>`, replay `/replay/<id>`, flag `/feature_flags/<id>`, experiment `/experiments/<id>`, survey `/surveys/<id>`, ticket `/support/tickets/<id>`, report `/inbox/<id>`, trace `/ai-observability/traces/<id>`, eval `/ai-evals/evaluations/<id>`, event `/data-management/events/<id>`, cohort `/cohorts/<id>`, action `/data-management/actions/<id>`, person `/persons/<id>`";
diff --git a/packages/agent/packages/agent-contracts/src/rich-output-prompt.test.ts b/packages/agent/packages/agent-contracts/src/rich-output-prompt.test.ts
index 74c54b15f7e9..c2a24c6fc2b5 100644
--- a/packages/agent/packages/agent-contracts/src/rich-output-prompt.test.ts
+++ b/packages/agent/packages/agent-contracts/src/rich-output-prompt.test.ts
@@ -1,5 +1,20 @@
import { describe, expect, it } from "vitest";
-import { appendRichOutputPrompt } from "./rich-output-prompt";
+import {
+ appendRichOutputPrompt,
+ RICH_OUTPUT_PROMPT_LEAD,
+} from "./rich-output-prompt";
+
+const PROJECT_URL = "https://us.posthog.com/project/2";
+const LEGACY_TAG_PROMPT = `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, report, 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; Inbox reports: the report uuid; 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.
+- Some PostHog MCP query tools render their result as an interactive chart in the conversation, and the tool result says so. When the tool result says the user already sees the result as an interactive view, do not embed the same data again as a \`<hogql>\` chart; write the conclusion in text and let that view carry the data. When it does not, the tool renders nothing on its own, so follow the full-size chart rule above.
+- 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.`;
+
+function count(text: string, part: string): number {
+ return text.split(part).length - 1;
+}
describe("appendRichOutputPrompt", () => {
it.each(["slack", "posthog_ai", "unknown"])(
@@ -7,10 +22,14 @@ describe("appendRichOutputPrompt", () => {
(interactionOrigin) => {
const basePrompt = "Answer clearly.";
const desktopPrompt = appendRichOutputPrompt(basePrompt);
+ const legacyPrompt = `${basePrompt}\n\n## Rich output in replies\n${LEGACY_TAG_PROMPT}`;
expect(appendRichOutputPrompt(desktopPrompt, interactionOrigin)).toBe(
basePrompt,
);
+ expect(appendRichOutputPrompt(legacyPrompt, interactionOrigin)).toBe(
+ basePrompt,
+ );
expect(appendRichOutputPrompt(basePrompt, interactionOrigin)).toBe(
basePrompt,
);
@@ -19,4 +38,33 @@ describe("appendRichOutputPrompt", () => {
);
},
);
+
+ it("teaches links into the session's project", () => {
+ const prompt = appendRichOutputPrompt("Answer.", "desktop", PROJECT_URL);
+
+ expect(prompt).toContain(`${PROJECT_URL}/insights/9pQx3`);
+ expect(prompt).toContain(`${PROJECT_URL}/sql?open_query=`);
+ expect(prompt).not.toContain("<PostHog host>");
+ });
+
+ it("replaces tag guidance an older client sent and keeps the sections around it", () => {
+ const prompt = appendRichOutputPrompt(
+ `Answer.\n\n## Rich output in replies\n${LEGACY_TAG_PROMPT}\n\n## Cloud\nKeep me.`,
+ "desktop",
+ PROJECT_URL,
+ );
+
+ expect(prompt).not.toContain("as XML tags");
+ expect(prompt).toContain("Answer.\n\n## Cloud\nKeep me.");
+ expect(count(prompt, RICH_OUTPUT_PROMPT_LEAD)).toBe(1);
+ });
+
+ it("keeps one block across layers, and a layer without a project keeps the known one", () => {
+ const once = appendRichOutputPrompt("Answer.", "desktop", PROJECT_URL);
+ const twice = appendRichOutputPrompt(once, "desktop", PROJECT_URL);
+
+ expect(twice).toBe(once);
+ expect(appendRichOutputPrompt(once)).toBe(once);
+ expect(count(twice, "## Rich output in replies")).toBe(1);
+ });
});
diff --git a/packages/agent/packages/agent-contracts/src/rich-output-prompt.ts b/packages/agent/packages/agent-contracts/src/rich-output-prompt.ts
index f2a093d7ffb4..45f4d238a9c7 100644
--- a/packages/agent/packages/agent-contracts/src/rich-output-prompt.ts
+++ b/packages/agent/packages/agent-contracts/src/rich-output-prompt.ts
@@ -1,38 +1,54 @@
-import { OBJECT_TAG_PROMPT_KIND_LIST } from "./objectTagKinds.generated";
+import { OBJECT_LINK_PROMPT_PATH_LIST } from "./objectTagKinds.generated";
-/**
- * Prompt block teaching an agent the object-tag vocabulary the desktop
- * renders as live references (chips, hover previews, chart cards). Shared by
- * every agent runtime so its syntax stays in sync with what `remarkObjectTags`
- * parses; the kind list itself is generated from the registry
- * (posthog/object_tags/kinds.py) so the prompt cannot drift from what the
- * renderers understand.
- */
-export const RICH_OUTPUT_TAGS_PROMPT = `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: ${OBJECT_TAG_PROMPT_KIND_LIST}. Use the object's id (insights: the short id; feature flags: the numeric id, falling back to the key; Inbox reports: the report uuid; 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.
-- Some PostHog MCP query tools render their result as an interactive chart in the conversation, and the tool result says so. When the tool result says the user already sees the result as an interactive view, do not embed the same data again as a \`<hogql>\` chart; write the conclusion in text and let that view carry the data. When it does not, the tool renders nothing on its own, so follow the full-size chart rule above.
-- 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.`;
+export const RICH_OUTPUT_PROMPT_HEADING = "## Rich output in replies";
+export const RICH_OUTPUT_PROMPT_LEAD =
+ "Link the PostHog objects behind your conclusions as Markdown links";
+
+const FALLBACK_PROJECT_URL = "https://<PostHog host>/project/<project id>";
+const BLOCK_END = String.raw`Use it when a specific session is the evidence\.`;
+const BLOCK_BODY = String.raw`(?:(?!\n## )[\s\S])*?${BLOCK_END}`;
+const OPTIONAL_HEADING = String.raw`(?:\n\n${RICH_OUTPUT_PROMPT_HEADING}\n)?`;
+const LEGACY_TAG_BLOCK = new RegExp(
+ `${OPTIONAL_HEADING}Embed the PostHog objects behind your conclusions as XML tags${BLOCK_BODY}`,
+ "g",
+);
+const LINK_BLOCK = new RegExp(
+ `${OPTIONAL_HEADING}${RICH_OUTPUT_PROMPT_LEAD}${BLOCK_BODY}`,
+ "g",
+);
+
+export function getProjectWebUrl(
+ appUrl: string,
+ projectId: number | string,
+): string {
+ return `${appUrl.replace(/\/+$/, "")}/project/${projectId}`;
+}
+
+export function renderRichOutputPrompt(projectUrl?: string | null): string {
+ const base = projectUrl?.replace(/\/+$/, "") || FALLBACK_PROJECT_URL;
+ return `${RICH_OUTPUT_PROMPT_LEAD} to their pages in this project, ${base}. The app recognizes these links and shows each one as a live object, so never restate the object's data in your text, and never put the links inside code fences or inline code. A link to another host or project stays a plain link.
+- Inline reference: \`[short human label](${base}/<path>)\` inside a sentence, e.g. \`The [checkout funnel](${base}/insights/9pQx3) dropped after [new-checkout-flow](${base}/feature_flags/42) rolled out.\` Paths: ${OBJECT_LINK_PROMPT_PATH_LIST}. Use the object's id (insights: the short id; feature flags: the numeric id, never the key; Inbox reports: the report uuid; persons: the uuid; events: the event definition uuid). When a tool result gives a \`_posthogUrl\` for the object, link to that URL. It renders as a chip with a live hover preview that opens the object in PostHog.
+- Inline SQL: \`[signups today](${base}/sql?open_query=SELECT%20count()%20FROM%20events)\`. Percent-encode the SQL the way encodeURIComponent does: spaces as %20 (never +), and encode every %, #, &, +, ", <, >, [, ] and line break. 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): put the link to a saved insight or a SQL query alone in its own paragraph, with a blank line before and after it and not inside a list or table, e.g. \`[Daily active users, last 7 days](${base}/sql?open_query=SELECT%20...)\`. The link text is the chart title, so include the time range. An optional quoted link title adds a caption: \`[title](url "caption")\`. The chart executes live on every view.
+- Some PostHog MCP query tools render their result as an interactive chart in the conversation, and the tool result says so. When the tool result says the user already sees the result as an interactive view, do not link the same query again as a chart; write the conclusion in text and let that view carry the data. When it does not, the tool renders nothing on its own, so follow the full-size chart rule above.
+- Recording card: a link to \`${base}/replay/<session_id>\` alone in its own paragraph renders the recording's details with a link into PostHog's player. Use it when a specific session is the evidence.`;
+}
export function appendRichOutputPrompt(
prompt: string,
interactionOrigin?: string | null,
+ projectUrl?: string | null,
): string {
+ const withoutLegacy = prompt.replace(LEGACY_TAG_BLOCK, "");
if (
interactionOrigin &&
interactionOrigin !== "desktop" &&
interactionOrigin !== "signal_report"
) {
- return prompt
- .replaceAll(
- `\n\n## Rich output in replies\n${RICH_OUTPUT_TAGS_PROMPT}`,
- "",
- )
- .replaceAll(RICH_OUTPUT_TAGS_PROMPT, "");
+ return withoutLegacy.replace(LINK_BLOCK, "");
}
- if (prompt.includes(RICH_OUTPUT_TAGS_PROMPT)) {
- return prompt;
+ if (!projectUrl && withoutLegacy.search(LINK_BLOCK) !== -1) {
+ return withoutLegacy;
}
- return `${prompt}\n\n## Rich output in replies\n${RICH_OUTPUT_TAGS_PROMPT}`;
+ return `${withoutLegacy.replace(LINK_BLOCK, "")}\n\n${RICH_OUTPUT_PROMPT_HEADING}\n${renderRichOutputPrompt(projectUrl)}`;
}
diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.ts
index 38529f09239c..c7b2b1327673 100644
--- a/packages/agent/packages/agent/src/server/agent-server.ts
+++ b/packages/agent/packages/agent/src/server/agent-server.ts
@@ -32,7 +32,10 @@ import {
toAcpMcpServers,
} from "@posthog/agent-contracts";
import { prependProductEngineerPrompt } from "@posthog/agent-contracts/product-engineer-prompt";
-import { appendRichOutputPrompt } from "@posthog/agent-contracts/rich-output-prompt";
+import {
+ appendRichOutputPrompt,
+ getProjectWebUrl,
+} from "@posthog/agent-contracts/rich-output-prompt";
import { execGh } from "@posthog/git/gh";
import { getCurrentBranch, getRemoteUrl } from "@posthog/git/queries";
import { ghTokenEnv } from "@posthog/git/signed-commit";
@@ -235,6 +238,7 @@ export function buildCloudSessionSystemPrompt(
cloudAppend: string,
userPrompt: ClaudeCodeConfig["systemPrompt"],
interactionOrigin?: string | null,
+ projectUrl?: string | null,
): string | { append: string } {
const prompt = [
typeof userPrompt === "string" ? userPrompt : userPrompt?.append,
@@ -245,6 +249,7 @@ export function buildCloudSessionSystemPrompt(
const combinedPrompt = appendRichOutputPrompt(
prependProductEngineerPrompt(prompt),
interactionOrigin,
+ projectUrl,
);
return typeof userPrompt === "string"
@@ -4385,6 +4390,7 @@ export class AgentServer {
cloudAppend,
userPrompt,
this.isSlackReplyContext() ? "slack" : this.getCloudInteractionOrigin(),
+ getProjectWebUrl(this.config.apiUrl, this.config.projectId),
);
return this.isSlackReplyContext()
? appendSte100Guidance(sessionPrompt)
diff --git a/packages/agent/packages/agent/src/server/cloud-session-prompt.test.ts b/packages/agent/packages/agent/src/server/cloud-session-prompt.test.ts
index 16ffb542f8b9..8d4befb14702 100644
--- a/packages/agent/packages/agent/src/server/cloud-session-prompt.test.ts
+++ b/packages/agent/packages/agent/src/server/cloud-session-prompt.test.ts
@@ -1,5 +1,5 @@
import { PRODUCT_ENGINEER_PROMPT } from "@posthog/agent-contracts/product-engineer-prompt";
-import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/agent-contracts/rich-output-prompt";
+import { RICH_OUTPUT_PROMPT_LEAD } from "@posthog/agent-contracts/rich-output-prompt";
import { describe, expect, it } from "vitest";
import { buildCloudSessionSystemPrompt } from "./agent-server";
@@ -33,7 +33,7 @@ describe("buildCloudSessionSystemPrompt", () => {
const text = typeof prompt === "string" ? prompt : prompt.append;
expect(text).toContain(PRODUCT_ENGINEER_PROMPT);
- expect(text.includes(RICH_OUTPUT_TAGS_PROMPT)).toBe(richOutput);
+ expect(text.includes(RICH_OUTPUT_PROMPT_LEAD)).toBe(richOutput);
expect(text.indexOf(PRODUCT_ENGINEER_PROMPT)).toBeLessThan(
text.indexOf("Cloud task instructions."),
);
diff --git a/packages/agent/packages/harness/src/extensions/enrichment/extension.test.ts b/packages/agent/packages/harness/src/extensions/enrichment/extension.test.ts
index c4b6d016845b..351e2394bbe7 100644
--- a/packages/agent/packages/harness/src/extensions/enrichment/extension.test.ts
+++ b/packages/agent/packages/harness/src/extensions/enrichment/extension.test.ts
@@ -3,7 +3,7 @@ import type {
ExtensionContext,
ToolResultEvent,
} from "@earendil-works/pi-coding-agent";
-import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/agent-contracts/rich-output-prompt";
+import { RICH_OUTPUT_PROMPT_LEAD } from "@posthog/agent-contracts/rich-output-prompt";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createPiEnrichmentExtension } from "./extension";
@@ -82,7 +82,7 @@ describe("createPiEnrichmentExtension", () => {
expect(
beforeAgentStartHandler?.({
systemPrompt: "Base system prompt",
- }).systemPrompt.includes(RICH_OUTPUT_TAGS_PROMPT),
+ }).systemPrompt.includes(RICH_OUTPUT_PROMPT_LEAD),
).toBe(richOutput);
const result = await handler?.(
diff --git a/packages/agent/packages/harness/src/extensions/enrichment/extension.ts b/packages/agent/packages/harness/src/extensions/enrichment/extension.ts
index 4bf047a3f1c2..f36cb8f2b632 100644
--- a/packages/agent/packages/harness/src/extensions/enrichment/extension.ts
+++ b/packages/agent/packages/harness/src/extensions/enrichment/extension.ts
@@ -4,7 +4,10 @@ import {
type ExtensionFactory,
isReadToolResult,
} from "@earendil-works/pi-coding-agent";
-import { appendRichOutputPrompt } from "@posthog/agent-contracts/rich-output-prompt";
+import {
+ appendRichOutputPrompt,
+ getProjectWebUrl,
+} from "@posthog/agent-contracts/rich-output-prompt";
import { createEnrichment, enrichFileForAgent } from "./file-enricher";
export interface PiEnrichmentConfig {
@@ -26,6 +29,10 @@ export function createPiEnrichmentExtension(config: PiEnrichmentConfig): {
systemPrompt: appendRichOutputPrompt(
event.systemPrompt,
config.interactionOrigin,
+ getProjectWebUrl(
+ config.publicApiUrl ?? config.apiUrl,
+ config.projectId,
+ ),
),
}));
diff --git a/posthog/object_tags/kinds.py b/posthog/object_tags/kinds.py
index 7f98b300e24b..c0c0d450a7ff 100644
--- a/posthog/object_tags/kinds.py
+++ b/posthog/object_tags/kinds.py
@@ -43,6 +43,7 @@ class ObjectKindSpec:
block: bool = False
# The tag body is the object id itself rather than a label (hogql: the SQL).
id_is_body: bool = False
+ url_aliases: tuple[str, ...] = ()
OBJECT_KINDS: dict[str, ObjectKindSpec] = {
@@ -51,6 +52,7 @@ OBJECT_KINDS: dict[str, ObjectKindSpec] = {
source="Product analytics",
path_template="/insights/{id}",
block=True,
+ url_aliases=("/i/{id}",),
),
"hogql": ObjectKindSpec(
kind_label="SQL query",
@@ -58,6 +60,7 @@ OBJECT_KINDS: dict[str, ObjectKindSpec] = {
path_template="/sql?open_query={id}",
block=True,
id_is_body=True,
+ url_aliases=("/insights/new#q={query}",),
),
"dashboard": ObjectKindSpec(
kind_label="Dashboard",
@@ -74,6 +77,7 @@ OBJECT_KINDS: dict[str, ObjectKindSpec] = {
source="Session replay",
path_template="/replay/{id}",
block=True,
+ url_aliases=("/replay/home?sessionRecordingId={id}",),
),
"flag": ObjectKindSpec(
kind_label="Feature flag",
@@ -145,6 +149,10 @@ OBJECT_KIND_ALIASES: dict[str, str] = {
"sql": "hogql",
}
+RESERVED_URL_IDS: tuple[str, ...] = ("new", "home", "playlists", "settings", "configuration", "options")
+
+APP_HOST_ALIASES: dict[str, str] = {"app.posthog.com": "us.posthog.com"}
+
# Rendering fallback for a tag whose kind nobody registered.
FALLBACK_OBJECT_KIND = ObjectKindSpec(kind_label="Evidence", source="PostHog")
diff --git a/posthog/object_tags/projection.py b/posthog/object_tags/projection.py
index f6dacb1edba5..45f2f70419b8 100755
--- a/posthog/object_tags/projection.py
+++ b/posthog/object_tags/projection.py
@@ -11,7 +11,14 @@ Registered in ``tools/hogli-commands/hogli_commands/projections.py``; run
import json
-from posthog.object_tags.kinds import FALLBACK_OBJECT_KIND, OBJECT_KIND_ALIASES, OBJECT_KINDS, ObjectKindSpec
+from posthog.object_tags.kinds import (
+ APP_HOST_ALIASES,
+ FALLBACK_OBJECT_KIND,
+ OBJECT_KIND_ALIASES,
+ OBJECT_KINDS,
+ RESERVED_URL_IDS,
+ ObjectKindSpec,
+)
HEADER = """\
// THIS FILE IS AUTOGENERATED by posthog/object_tags/projection.py. DO NOT EDIT.
@@ -39,6 +46,7 @@ export interface ObjectKindData {
block: boolean;
/** The tag body is the object id itself rather than a label (hogql: the SQL). */
idIsBody: boolean;
+ urlAliases: readonly string[];
}
"""
@@ -51,6 +59,7 @@ def _entry(spec: ObjectKindSpec, indent: str) -> str:
f"idPattern: {json.dumps(spec.id_pattern)}",
f"block: {json.dumps(spec.block)}",
f"idIsBody: {json.dumps(spec.id_is_body)}",
+ f"urlAliases: {json.dumps(list(spec.url_aliases))}",
]
body = "".join(f"{indent} {field},\n" for field in fields)
return "{\n" + body + indent + "}"
@@ -77,17 +86,24 @@ def render_registry_ts() -> str:
+ "\n"
+ "/** Rendering fallback for a tag whose kind nobody registered. */\n"
+ f"export const FALLBACK_OBJECT_KIND_DATA: ObjectKindData = {_entry(FALLBACK_OBJECT_KIND, '')};\n"
+ + "\n"
+ + f"export const RESERVED_URL_IDS: readonly string[] = {json.dumps(list(RESERVED_URL_IDS))};\n"
+ + "\n"
+ + f"export const APP_HOST_ALIASES: Record<string, string> = {json.dumps(APP_HOST_ALIASES)};\n"
)
def render_prompt_kinds_ts() -> str:
- # hogql is taught by its own prompt bullet, not the kind list.
- names = ", ".join(name for name, spec in OBJECT_KINDS.items() if not spec.id_is_body)
+ paths = ", ".join(
+ f"{name} `{spec.path_template.replace('{id}', '<id>')}`"
+ for name, spec in OBJECT_KINDS.items()
+ if spec.path_template is not None and not spec.id_is_body
+ )
return (
HEADER
+ "\n"
- + "/** The kind list the rich-output prompt teaches agents. */\n"
- + f"export const OBJECT_TAG_PROMPT_KIND_LIST = {json.dumps(names)};\n"
+ + "/** The object paths the rich-output prompt teaches agents to link. */\n"
+ + f"export const OBJECT_LINK_PROMPT_PATH_LIST = {json.dumps(paths)};\n"
)
diff --git a/posthog/slack/formatting.py b/posthog/slack/formatting.py
index 87803b189501..906c00f9903c 100644
--- a/posthog/slack/formatting.py
+++ b/posthog/slack/formatting.py
@@ -1,3 +1,10 @@
+import re
+
+_RE_MARKDOWN_LINK = re.compile(
+ r'(?<![!\\])\[([^\[\]\n]*)\]\((?:<[^<>\n]*>|(?:[^()\s]|\((?:[^()\s]|\([^()\s]*\))*\))+)(?:[ \t]+"[^"\n]*")?\)'
+)
+
+
def escape_slack_mrkdwn(text: str) -> str:
"""Escape Slack mrkdwn control characters in user-supplied text.
@@ -16,3 +23,7 @@ def channel_id_from_target(value: str) -> str:
opens a direct message, so a member target resolves the same way as a channel target.
"""
return value.split("|", 1)[0].strip()
+
+
+def markdown_links_to_labels(text: str) -> str:
+ return _RE_MARKDOWN_LINK.sub(lambda match: match.group(1), text)
diff --git a/posthog/slack/test/test_formatting.py b/posthog/slack/test/test_formatting.py
index 9960838775b6..37ef981eb18c 100644
--- a/posthog/slack/test/test_formatting.py
+++ b/posthog/slack/test/test_formatting.py
@@ -2,7 +2,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from posthog.slack.formatting import escape_slack_mrkdwn
+from posthog.slack.formatting import escape_slack_mrkdwn, markdown_links_to_labels
class TestEscapeSlackMrkdwn(SimpleTestCase):
@@ -15,3 +15,23 @@ class TestEscapeSlackMrkdwn(SimpleTestCase):
)
def test_escapes_slack_control_chars(self, _name, raw, expected):
assert escape_slack_mrkdwn(raw) == expected
+
+
+class TestMarkdownLinksToLabels(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("plain_link", "See [the funnel](https://us.posthog.com/project/2/insights/a).", "See the funnel."),
+ (
+ "sql_link_with_nested_parentheses",
+ "Ran [errors](https://us.posthog.com/project/2/sql?open_query=SELECT%20count(if(x))%20FROM%20events) today",
+ "Ran errors today",
+ ),
+ ("angle_bracket_destination", "[q](<https://x.example/sql?open_query=SELECT 1>)", "q"),
+ ("link_with_title", '[chart](https://x.example/a "caption")', "chart"),
+ ("image_stays", "![img](https://x.example/a.png)", "![img](https://x.example/a.png)"),
+ ("bracketed_text_stays", "See [1] and arr[0]", "See [1] and arr[0]"),
+ ("no_links", "plain **bold** text", "plain **bold** text"),
+ ]
+ )
+ def test_replaces_links_with_labels(self, _name, raw, expected):
+ assert markdown_links_to_labels(raw) == expected
diff --git a/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts b/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts
index ec7414b527ad..083d70dc53bb 100644
--- a/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts
+++ b/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts
@@ -246,7 +246,9 @@ test.describe("Pi enrichment", () => {
expect(eventDefinitionRequests).toBe(1);
expect(eventStatsRequests).toBe(1);
expect(initialModelRequest).toContain("## Rich output in replies");
- expect(initialModelRequest).toContain('<kind id=\\"...\\">');
+ expect(initialModelRequest).toContain(
+ "https://us.posthog.com/project/1/insights/9pQx3",
+ );
expect(enrichedModelRequest).toContain(
'[PostHog] Event: \\"checkout_completed\\"',
);
diff --git a/products/desktop/apps/mobile/src/lib/posthogUrl.test.ts b/products/desktop/apps/mobile/src/lib/posthogUrl.test.ts
index fcabab5c8f88..d249c29dd890 100644
--- a/products/desktop/apps/mobile/src/lib/posthogUrl.test.ts
+++ b/products/desktop/apps/mobile/src/lib/posthogUrl.test.ts
@@ -33,6 +33,14 @@ describe("parsePostHogUrl", () => {
});
});
+ it("labels a SQL editor link by its query, not its project path", () => {
+ expect(
+ parsePostHogUrl(
+ "https://us.posthog.com/project/7/sql?open_query=SELECT%201",
+ )?.defaultLabel,
+ ).toBe("SQL query");
+ });
+
it("parses relative insight paths using the signed-in app host", () => {
expect(
parsePostHogUrl("/insights/UiFKIsO3", {
diff --git a/products/desktop/apps/mobile/src/lib/posthogUrl.ts b/products/desktop/apps/mobile/src/lib/posthogUrl.ts
index 3a0dbf1d6b1f..7fa7b9ad087e 100644
--- a/products/desktop/apps/mobile/src/lib/posthogUrl.ts
+++ b/products/desktop/apps/mobile/src/lib/posthogUrl.ts
@@ -125,6 +125,10 @@ function labelForProjectView(
return refId ? labelWithId("Replay", refId) : "Replay";
case "error_tracking":
return refId ? labelWithId("Error", refId) : "Error tracking";
+ case "sql":
+ return parsed.searchParams.get("open_query")?.trim()
+ ? "SQL query"
+ : "SQL editor";
default:
return null;
}
diff --git a/products/desktop/docs/CLOUD-TASK-ARTIFACTS.md b/products/desktop/docs/CLOUD-TASK-ARTIFACTS.md
index f45b9228913c..08052873417d 100644
--- a/products/desktop/docs/CLOUD-TASK-ARTIFACTS.md
+++ b/products/desktop/docs/CLOUD-TASK-ARTIFACTS.md
@@ -10,7 +10,10 @@ Repository changes should continue to be delivered through git rather than dupli
## PostHog object references
-A completed assistant message can reference a PostHog object with an object tag, such as `<insight id="9pQx3">Checkout funnel</insight>`. Desktop extracts these tags after the turn completes and registers them in the same run artifact manifest with `type: reference` and `source: posthog_object`.
+A completed assistant message can reference a PostHog object with a Markdown link to the object's page in the signed-in project, such as `[Checkout funnel](https://us.posthog.com/project/2/insights/9pQx3)`.
+Older messages use an object tag, such as `<insight id="9pQx3">Checkout funnel</insight>`, and Desktop still reads them.
+A link to another host or another project is not a reference.
+Desktop extracts these references after the turn completes and registers them in the same run artifact manifest with `type: reference` and `source: posthog_object`.
Reference artifacts do not upload a file and do not have a storage path, size, or download URL. Their metadata stores the object kind, exact identifier, source message IDs, and occurrence count. Replaying the same completed message updates the existing entry instead of creating another one.
diff --git a/products/desktop/packages/core/src/inbox/objectKinds.generated.ts b/products/desktop/packages/core/src/inbox/objectKinds.generated.ts
index a1f8536a4e33..3289e8986d8b 100644
--- a/products/desktop/packages/core/src/inbox/objectKinds.generated.ts
+++ b/products/desktop/packages/core/src/inbox/objectKinds.generated.ts
@@ -21,6 +21,7 @@ export interface ObjectKindData {
block: boolean;
/** The tag body is the object id itself rather than a label (hogql: the SQL). */
idIsBody: boolean;
+ urlAliases: readonly string[];
}
export const OBJECT_KIND_DATA = {
@@ -31,6 +32,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: true,
idIsBody: false,
+ urlAliases: ["/i/{id}"],
},
hogql: {
kindLabel: "SQL query",
@@ -39,6 +41,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: true,
idIsBody: true,
+ urlAliases: ["/insights/new#q={query}"],
},
dashboard: {
kindLabel: "Dashboard",
@@ -47,6 +50,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
error: {
kindLabel: "Error issue",
@@ -55,6 +59,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
replay: {
kindLabel: "Session replay",
@@ -63,6 +68,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: true,
idIsBody: false,
+ urlAliases: ["/replay/home?sessionRecordingId={id}"],
},
flag: {
kindLabel: "Feature flag",
@@ -71,6 +77,7 @@ export const OBJECT_KIND_DATA = {
idPattern: "^\\d+$",
block: false,
idIsBody: false,
+ urlAliases: [],
},
experiment: {
kindLabel: "Experiment",
@@ -79,6 +86,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
survey: {
kindLabel: "Survey",
@@ -87,6 +95,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
ticket: {
kindLabel: "Support tickets",
@@ -95,6 +104,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
report: {
kindLabel: "Inbox report",
@@ -103,6 +113,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
trace: {
kindLabel: "LLM trace",
@@ -111,6 +122,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
eval: {
kindLabel: "Evaluation",
@@ -119,6 +131,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
event: {
kindLabel: "Events",
@@ -127,6 +140,7 @@ export const OBJECT_KIND_DATA = {
idPattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F-]{27,}$",
block: false,
idIsBody: false,
+ urlAliases: [],
},
cohort: {
kindLabel: "Cohort",
@@ -135,6 +149,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
action: {
kindLabel: "Action",
@@ -143,6 +158,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
person: {
kindLabel: "Person",
@@ -151,6 +167,7 @@ export const OBJECT_KIND_DATA = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
},
} satisfies Record<string, ObjectKindData>;
@@ -174,4 +191,18 @@ export const FALLBACK_OBJECT_KIND_DATA: ObjectKindData = {
idPattern: null,
block: false,
idIsBody: false,
+ urlAliases: [],
+};
+
+export const RESERVED_URL_IDS: readonly string[] = [
+ "new",
+ "home",
+ "playlists",
+ "settings",
+ "configuration",
+ "options",
+];
+
+export const APP_HOST_ALIASES: Record<string, string> = {
+ "app.posthog.com": "us.posthog.com",
};
diff --git a/products/desktop/packages/core/src/message-editor/content.test.ts b/products/desktop/packages/core/src/message-editor/content.test.ts
index b2f5f81ecafc..3ad561560111 100644
--- a/products/desktop/packages/core/src/message-editor/content.test.ts
+++ b/products/desktop/packages/core/src/message-editor/content.test.ts
@@ -1,6 +1,7 @@
-import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";
+import { renderRichOutputPrompt } from "@posthog/shared/rich-output-prompt";
import { describe, expect, it } from "vitest";
import { getAbsoluteAttachmentPaths } from "../editor/cloud-prompt";
+import { OBJECT_KIND_DATA } from "../inbox/objectKinds.generated";
import {
contentToXml,
type EditorContent,
@@ -442,7 +443,12 @@ describe("xmlToContent", () => {
});
describe("PostHog object kind prompt", () => {
- it.each(POSTHOG_OBJECT_KINDS)("teaches agents the %s tag", (kind) => {
- expect(RICH_OUTPUT_TAGS_PROMPT).toContain(kind);
- });
+ it.each(POSTHOG_OBJECT_KINDS)(
+ "teaches agents to link the %s page",
+ (kind) => {
+ const template = OBJECT_KIND_DATA[kind].pathTemplate ?? "";
+ expect(template).not.toBe("");
+ expect(renderRichOutputPrompt()).toContain(template.split("{id}")[0]);
+ },
+ );
});
diff --git a/products/desktop/packages/core/src/posthog-objects/objectUrls.test.ts b/products/desktop/packages/core/src/posthog-objects/objectUrls.test.ts
new file mode 100644
index 000000000000..c8cbe1a56977
--- /dev/null
+++ b/products/desktop/packages/core/src/posthog-objects/objectUrls.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+import { parsePostHogObjectUrl } from "./objectUrls";
+
+const CONTEXT = { appUrl: "https://us.posthog.com", projectId: 2 };
+const PROJECT = "https://us.posthog.com/project/2";
+const HOGQL_NODE = encodeURIComponent(
+ JSON.stringify({
+ kind: "DataVisualizationNode",
+ source: { kind: "HogQLQuery", query: "SELECT 1" },
+ }),
+);
+
+describe("parsePostHogObjectUrl", () => {
+ it.each([
+ [`${PROJECT}/insights/9pQx3`, ["insight", "9pQx3"]],
+ [`${PROJECT}/insights/9pQx3/edit?x=1`, ["insight", "9pQx3"]],
+ [`${PROJECT}/i/9pQx3`, ["insight", "9pQx3"]],
+ ["https://us.posthog.com/insights/9pQx3", ["insight", "9pQx3"]],
+ ["https://app.posthog.com/project/2/insights/9pQx3", ["insight", "9pQx3"]],
+ [
+ `${PROJECT}/sql?open_query=SELECT%20count()%20FROM%20events`,
+ ["hogql", "SELECT count() FROM events"],
+ ],
+ [`${PROJECT}/sql?open_query=SELECT+1`, ["hogql", "SELECT 1"]],
+ [`${PROJECT}/sql?open_query=${HOGQL_NODE}`, ["hogql", "SELECT 1"]],
+ [`${PROJECT}/insights/new#q=${HOGQL_NODE}`, ["hogql", "SELECT 1"]],
+ [`${PROJECT}/replay/0190-s1?t=30`, ["replay", "0190-s1"]],
+ [
+ `${PROJECT}/replay/home?sessionRecordingId=0190-s1`,
+ ["replay", "0190-s1"],
+ ],
+ [`${PROJECT}/feature_flags/42`, ["flag", "42"]],
+ [`${PROJECT}/persons/a%20b`, ["person", "a b"]],
+ [`${PROJECT}/feature_flags/my-key`, null],
+ [`${PROJECT}/insights/new`, null],
+ [
+ `${PROJECT}/insights/new#q=${encodeURIComponent('{"kind":"TrendsQuery"}')}`,
+ null,
+ ],
+ [`${PROJECT}/replay/home`, null],
+ [`${PROJECT}/sql?open_query=`, null],
+ [`${PROJECT}/settings/project`, null],
+ ["https://us.posthog.com/project/3/insights/9pQx3", null],
+ ["https://eu.posthog.com/project/2/insights/9pQx3", null],
+ ["https://us.posthog.com.evil.example/project/2/insights/9pQx3", null],
+ ["javascript:alert(1)", null],
+ ["evidence:insight/9pQx3", null],
+ ])("resolves %s", (url, expected) => {
+ const ref = parsePostHogObjectUrl(url, CONTEXT);
+ expect(ref ? [ref.kind, ref.id] : null).toEqual(expected);
+ });
+
+ it("keeps the exact page the link opens", () => {
+ expect(
+ parsePostHogObjectUrl(`${PROJECT}/replay/s1?t=30`, CONTEXT)?.href,
+ ).toBe(`${PROJECT}/replay/s1?t=30`);
+ });
+
+ it("recognizes nothing without a signed-in project", () => {
+ expect(parsePostHogObjectUrl(`${PROJECT}/insights/9pQx3`, null)).toBe(null);
+ });
+});
diff --git a/products/desktop/packages/core/src/posthog-objects/objectUrls.ts b/products/desktop/packages/core/src/posthog-objects/objectUrls.ts
new file mode 100644
index 000000000000..358535bcb509
--- /dev/null
+++ b/products/desktop/packages/core/src/posthog-objects/objectUrls.ts
@@ -0,0 +1,164 @@
+import {
+ APP_HOST_ALIASES,
+ OBJECT_KIND_DATA,
+ type ObjectKindData,
+ type ObjectKindName,
+ RESERVED_URL_IDS,
+} from "../inbox/objectKinds.generated";
+
+export interface PostHogLinkContext {
+ appUrl: string;
+ projectId: number | string;
+}
+
+export interface PostHogObjectUrlRef {
+ kind: string;
+ id: string;
+ href: string;
+}
+
+interface UrlTemplate {
+ kind: string;
+ segments: string[];
+ idIndex: number;
+ paramSource: "query" | "fragment" | null;
+ paramKey: string;
+ queryNode: boolean;
+ guard: RegExp | null;
+ idIsBody: boolean;
+}
+
+function pathSegments(path: string): string[] {
+ return path.split("/").filter(Boolean);
+}
+
+function compileTemplate(
+ kind: string,
+ data: ObjectKindData,
+ template: string,
+): UrlTemplate {
+ const hashIndex = template.indexOf("#");
+ const beforeHash = hashIndex === -1 ? template : template.slice(0, hashIndex);
+ const fragment = hashIndex === -1 ? "" : template.slice(hashIndex + 1);
+ const queryIndex = beforeHash.indexOf("?");
+ const path = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex);
+ const query = queryIndex === -1 ? "" : beforeHash.slice(queryIndex + 1);
+ const segments = pathSegments(path);
+ const [paramKey = "", placeholder = ""] = (query || fragment).split("=");
+ return {
+ kind,
+ segments,
+ idIndex: segments.indexOf("{id}"),
+ paramSource: query ? "query" : fragment ? "fragment" : null,
+ paramKey,
+ queryNode: placeholder === "{query}",
+ guard: data.idPattern ? new RegExp(data.idPattern) : null,
+ idIsBody: data.idIsBody,
+ };
+}
+
+const URL_TEMPLATES: UrlTemplate[] = (
+ Object.entries(OBJECT_KIND_DATA) as [string, ObjectKindData][]
+).flatMap(([kind, data]) =>
+ [data.pathTemplate, ...data.urlAliases]
+ .filter((template): template is string => template !== null)
+ .map((template) => compileTemplate(kind, data, template)),
+);
+
+function appHost(host: string): string {
+ const lower = host.toLowerCase();
+ return APP_HOST_ALIASES[lower] ?? lower;
+}
+
+function decodePart(part: string): string {
+ try {
+ return decodeURIComponent(part);
+ } catch {
+ return part;
+ }
+}
+
+function hogqlFromQueryNode(raw: string): string | null {
+ let node: unknown;
+ try {
+ node = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ for (let depth = 0; depth < 3; depth++) {
+ if (typeof node !== "object" || node === null) return null;
+ const record = node as Record<string, unknown>;
+ if (record.kind === "HogQLQuery" && typeof record.query === "string") {
+ return record.query;
+ }
+ node = record.source;
+ }
+ return null;
+}
+
+function matchTemplate(
+ template: UrlTemplate,
+ segments: string[],
+ url: URL,
+): string | null {
+ if (template.idIndex !== -1) {
+ if (segments.length <= template.idIndex) return null;
+ for (let i = 0; i < template.idIndex; i++) {
+ if (segments[i] !== template.segments[i]) return null;
+ }
+ const value = decodePart(segments[template.idIndex]);
+ return RESERVED_URL_IDS.includes(value) ? null : value;
+ }
+ if (
+ segments.length !== template.segments.length ||
+ segments.some((segment, i) => segment !== template.segments[i])
+ ) {
+ return null;
+ }
+ if (!template.paramSource) return null;
+ const params =
+ template.paramSource === "query"
+ ? url.searchParams
+ : new URLSearchParams(url.hash.slice(1));
+ const value = params.get(template.paramKey);
+ if (!value) return null;
+ return template.queryNode ? hogqlFromQueryNode(value) : value;
+}
+
+export function parsePostHogObjectUrl(
+ href: string | undefined,
+ context: PostHogLinkContext | null,
+): PostHogObjectUrlRef | null {
+ if (!href || !context) return null;
+ let url: URL;
+ let base: URL;
+ try {
+ url = new URL(href.trim());
+ base = new URL(context.appUrl);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
+ if (appHost(url.host) !== appHost(base.host)) return null;
+ let segments = pathSegments(url.pathname);
+ if (segments[0] === "project") {
+ if (segments[1] !== String(context.projectId)) return null;
+ segments = segments.slice(2);
+ }
+ for (const template of URL_TEMPLATES) {
+ let value = matchTemplate(template, segments, url);
+ if (value && template.idIsBody && value.trimStart().startsWith("{")) {
+ value = hogqlFromQueryNode(value);
+ }
+ const id = value?.trim();
+ if (!id) continue;
+ if (template.guard && !template.guard.test(id)) continue;
+ return { kind: template.kind, id, href: url.toString() };
+ }
+ return null;
+}
+
+export function objectUrlLabel(ref: PostHogObjectUrlRef): string {
+ const { kindLabel, idIsBody } = OBJECT_KIND_DATA[ref.kind as ObjectKindName];
+ return idIsBody ? kindLabel : `${kindLabel} ${ref.id}`;
+}
diff --git a/products/desktop/packages/core/src/posthog-objects/references.test.ts b/products/desktop/packages/core/src/posthog-objects/references.test.ts
index 25bb455785bb..55b5bcd3324a 100644
--- a/products/desktop/packages/core/src/posthog-objects/references.test.ts
+++ b/products/desktop/packages/core/src/posthog-objects/references.test.ts
@@ -25,6 +25,52 @@ describe("extractPostHogObjectReferences", () => {
expect(extractPostHogObjectReferences(markdown)).toEqual(expected);
});
+ it.each([
+ [
+ "a labeled link",
+ "The [Checkout funnel](https://us.posthog.com/project/2/insights/9pQx3) dropped.",
+ [{ kind: "insight", id: "9pQx3", label: "Checkout funnel" }],
+ ],
+ [
+ "a SQL link with nested parentheses",
+ "[Errors](https://us.posthog.com/project/2/sql?open_query=SELECT%20count(if(x))%20FROM%20events)",
+ [
+ {
+ kind: "hogql",
+ id: "SELECT count(if(x)) FROM events",
+ label: "Errors",
+ },
+ ],
+ ],
+ [
+ "a SQL link with raw spaces in angle brackets",
+ "[Errors](<https://us.posthog.com/project/2/sql?open_query=SELECT count() FROM events>)",
+ [{ kind: "hogql", id: "SELECT count() FROM events", label: "Errors" }],
+ ],
+ [
+ "a bare URL at the end of a sentence",
+ "See https://us.posthog.com/project/2/feature_flags/42.",
+ [{ kind: "flag", id: "42", label: "Feature flag 42" }],
+ ],
+ [
+ "a link in another project",
+ "[x](https://us.posthog.com/project/3/insights/9pQx3)",
+ [],
+ ],
+ [
+ "a link in inline code",
+ "`[x](https://us.posthog.com/project/2/insights/9pQx3)`",
+ [],
+ ],
+ ] as const)("extracts %s", (_name, markdown, expected) => {
+ expect(
+ extractPostHogObjectReferences(markdown, {
+ appUrl: "https://us.posthog.com",
+ projectId: 2,
+ }),
+ ).toEqual(expected);
+ });
+
it("ignores tags in code and deduplicates the completed message", () => {
const tag = '<insight id="9pQx3">Checkout funnel</insight>';
expect(
@@ -53,6 +99,10 @@ describe("extractPostHogObjectReferences", () => {
"multi-backtick inline span",
['``<insight id="9pQx3">Checkout funnel</insight>``'],
],
+ [
+ "indented code block",
+ ["Example:", "", ' <insight id="9pQx3">Checkout funnel</insight>'],
+ ],
] as const)(
"ignores tags the renderer shows as code inside a %s",
(_label, lines) => {
@@ -60,6 +110,18 @@ describe("extractPostHogObjectReferences", () => {
},
);
+ it("keeps tags indented under a list item", () => {
+ expect(
+ extractPostHogObjectReferences(
+ [
+ "1. Signups",
+ "",
+ ' <insight id="9pQx3">Checkout funnel</insight>',
+ ].join("\n"),
+ ),
+ ).toEqual([{ kind: "insight", id: "9pQx3", label: "Checkout funnel" }]);
+ });
+
it("stays fast on many unmatched opening tags", () => {
const hostile = `${'<insight id="x">'.repeat(20_000)}\n<flag id="real" />`;
const start = performance.now();
diff --git a/products/desktop/packages/core/src/posthog-objects/references.ts b/products/desktop/packages/core/src/posthog-objects/references.ts
index 1fda3ef320f2..1de5dccc3652 100644
--- a/products/desktop/packages/core/src/posthog-objects/references.ts
+++ b/products/desktop/packages/core/src/posthog-objects/references.ts
@@ -3,6 +3,11 @@ import {
parseObjectTagAttrs,
resolveObjectKindName,
} from "@posthog/core/inbox/objectTags";
+import {
+ objectUrlLabel,
+ type PostHogLinkContext,
+ parsePostHogObjectUrl,
+} from "@posthog/core/posthog-objects/objectUrls";
// Opening tags and closing tags are matched separately so an unmatched opener
// costs one regex step instead of a lazy scan to the end of the message; the
@@ -10,6 +15,9 @@ import {
const OPEN_TAG_PATTERN =
/<([a-z][\w-]*)((?:\s+[a-z][\w-]*\s*=\s*"[^"]*")*)\s*(\/>|>)/g;
const CLOSE_TAG_PATTERN = /<\/([a-z][\w-]*)\s*>/g;
+const URL_PATTERN = /<(https?:\/\/[^>\n]+)>|https?:\/\/[^\s<>"'`[\]]+/g;
+const LINK_LABEL_PATTERN = /(?<!!)\[([^[\]\n]*)\]\($/;
+const LIST_MARKER_PATTERN = /^ {0,3}(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$)/;
const MAX_REFERENCES = 50;
const MAX_OBJECT_ID_LENGTH = 16_384;
const MAX_LABEL_LENGTH = 255;
@@ -72,10 +80,22 @@ function stripInlineCode(line: string): string {
// renderer shows as code. Mirrors the fence rules react-markdown applies:
// backtick or tilde fences of three or more, up to three leading spaces, closed
// only by a same-character run at least as long as the opener. Indented code
-// blocks are left alone on purpose — a line-based strip would also drop real
-// tags nested under list items; full parsing lives in the AST plugin instead.
+// blocks are blanked only outside lists, because list items indent real tags.
+function indentWidth(line: string): number {
+ let width = 0;
+ for (const char of line) {
+ if (char === " ") width++;
+ else if (char === "\t") width += 4 - (width % 4);
+ else break;
+ }
+ return width;
+}
+
function stripCode(markdown: string): string {
let fence: { char: string; length: number } | null = null;
+ let inList = false;
+ let inIndentedCode = false;
+ let afterBlank = true;
return markdown
.split("\n")
.map((line) => {
@@ -89,6 +109,23 @@ function stripCode(markdown: string): string {
if (closes) fence = null;
return "";
}
+ if (line.trim() === "") {
+ afterBlank = true;
+ return "";
+ }
+ const indent = indentWidth(line);
+ const followsBlank = afterBlank;
+ afterBlank = false;
+ if (indent >= 4 && (inIndentedCode || (followsBlank && !inList))) {
+ inIndentedCode = true;
+ return "";
+ }
+ inIndentedCode = false;
+ if (LIST_MARKER_PATTERN.test(line)) {
+ inList = true;
+ } else if (indent === 0 && followsBlank) {
+ inList = false;
+ }
if (fenceMatch) {
fence = { char: fenceMatch[1][0], length: fenceMatch[1].length };
return "";
@@ -148,12 +185,44 @@ function* scanTags(text: string): Generator<TagMatch> {
}
}
+function trimBareUrl(candidate: string): string {
+ let url = candidate.replace(/[.,;:!?*_~]+$/, "");
+ while (url.endsWith(")") && url.split(")").length > url.split("(").length) {
+ url = url.slice(0, -1).replace(/[.,;:!?*_~]+$/, "");
+ }
+ return url;
+}
+
+function linkCandidates(text: string): { label: string; url: string }[] {
+ return Array.from(text.matchAll(URL_PATTERN), (match) => ({
+ label:
+ LINK_LABEL_PATTERN.exec(
+ text.slice(Math.max(0, match.index - MAX_LABEL_LENGTH), match.index),
+ )?.[1] ?? "",
+ url: match[1] ?? trimBareUrl(match[0]),
+ }));
+}
+
export function extractPostHogObjectReferences(
markdown: string,
+ links: PostHogLinkContext | null = null,
): PostHogObjectReference[] {
const references: PostHogObjectReference[] = [];
const seen = new Set<string>();
- for (const match of scanTags(stripCode(markdown))) {
+ const add = (kind: string, id: string, label: string): boolean => {
+ if (id.length > MAX_OBJECT_ID_LENGTH) return false;
+ const key = `${kind}\0${id}`;
+ if (seen.has(key)) return false;
+ seen.add(key);
+ references.push({
+ kind,
+ id,
+ label: label.replace(/\s+/g, " ").trim().slice(0, MAX_LABEL_LENGTH),
+ });
+ return references.length >= MAX_REFERENCES;
+ };
+ const text = stripCode(markdown);
+ for (const match of scanTags(text)) {
const kind = resolveObjectKindName(match.name);
if (!kind) continue;
const ref = buildObjectTagRef(
@@ -161,16 +230,17 @@ export function extractPostHogObjectReferences(
parseObjectTagAttrs(match.rawAttributes),
match.body,
);
- if (!ref || ref.id.length > MAX_OBJECT_ID_LENGTH) continue;
- const key = `${ref.kind}\0${ref.id}`;
- if (seen.has(key)) continue;
- seen.add(key);
- references.push({
- kind: ref.kind,
- id: ref.id,
- label: ref.label.replace(/\s+/g, " ").trim().slice(0, MAX_LABEL_LENGTH),
- });
- if (references.length >= MAX_REFERENCES) break;
+ if (ref && add(ref.kind, ref.id, ref.label)) return references;
+ }
+ if (!links) return references;
+ for (const candidate of linkCandidates(text)) {
+ const ref = parsePostHogObjectUrl(candidate.url, links);
+ if (!ref) continue;
+ const label =
+ candidate.label.trim() && candidate.label.trim() !== candidate.url.trim()
+ ? candidate.label
+ : objectUrlLabel(ref);
+ if (add(ref.kind, ref.id, label)) return references;
}
return references;
}
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index e5d565e35cd9..d3a95d1dfddc 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -3417,9 +3417,26 @@ export class SessionService {
}
if (!session?.taskId || !tally.agentText) return;
- const references = extractPostHogObjectReferences(tally.agentText);
+ void this.registerTurnReferences(
+ session.taskId,
+ taskRunId,
+ tally.agentText,
+ `turn-${tally.startedAtTs}`,
+ );
+ }
+
+ private async registerTurnReferences(
+ taskId: string,
+ taskRunId: string,
+ agentText: string,
+ sourceMessageId: string,
+ ): Promise<void> {
+ const auth = await this.getCloudCommandAuth().catch(() => null);
+ const references = extractPostHogObjectReferences(
+ agentText,
+ auth ? { appUrl: auth.apiHost, projectId: auth.teamId } : null,
+ );
if (references.length === 0) return;
- const sourceMessageId = `turn-${tally.startedAtTs}`;
const inputs: PostHogObjectReferenceInput[] = references.map(
(reference) => ({
name: reference.label,
@@ -3428,7 +3445,7 @@ export class SessionService {
source_message_id: sourceMessageId,
}),
);
- this.registerPostHogReferences(session.taskId, taskRunId, inputs);
+ this.registerPostHogReferences(taskId, taskRunId, inputs);
}
// References enter the pending map before the attempt and leave it only on
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 6cc431a318d9..d6c4fc450130 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -1625,6 +1625,7 @@ export interface AnnouncementProperties {
export interface EvidencePreviewShownProperties {
kind: string;
cache: "hit" | "miss";
+ reference_source: "link" | "tag";
}
export interface EvidencePreviewReadyProperties {
diff --git a/products/desktop/packages/ui/src/features/editor/components/AgentObjectLinks.stories.tsx b/products/desktop/packages/ui/src/features/editor/components/AgentObjectLinks.stories.tsx
new file mode 100644
index 000000000000..d8c2b71b9d37
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/AgentObjectLinks.stories.tsx
@@ -0,0 +1,94 @@
+import {
+ ANONYMOUS_AUTH_STATE,
+ useAuthStore,
+} from "@posthog/ui/features/auth/store";
+import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
+import type { Decorator, Meta, StoryObj } from "@storybook/react-vite";
+import { useEffect } from "react";
+
+const PROJECT = "https://us.posthog.com/project/2";
+const sql = (query: string) =>
+ `${PROJECT}/sql?open_query=${encodeURIComponent(query)}`;
+
+const signedIn: Decorator = (Story) => {
+ useEffect(() => {
+ const previous = useAuthStore.getState().authState;
+ useAuthStore.setState({
+ authState: {
+ ...ANONYMOUS_AUTH_STATE,
+ cloudRegion: "us",
+ currentProjectId: 2,
+ },
+ });
+ return () => useAuthStore.setState({ authState: previous });
+ }, []);
+ return (
+ <div className="max-w-xl">
+ <Story />
+ </div>
+ );
+};
+
+const meta: Meta<typeof MarkdownRenderer> = {
+ title: "Features/Editor/Agent object links",
+ component: MarkdownRenderer,
+ decorators: [signedIn],
+ parameters: { layout: "padded" },
+};
+
+export default meta;
+type Story = StoryObj<typeof MarkdownRenderer>;
+
+export const AgentReply: Story = {
+ args: {
+ renderObjectTags: true,
+ content: [
+ `The [coupon to purchase conversion](${PROJECT}/insights/9pQx3) dropped from 41% to 28% on Jan 3. [A TypeError in CouponValidator](${PROJECT}/error_tracking/018f44aa-0000-7000-8000-000000000001) first appeared the same day, behind [new-checkout-flow](${PROJECT}/feature_flags/42). [1,247 sessions](${sql("SELECT count(DISTINCT $session_id) FROM events WHERE event = '$exception'")}) hit the error this week.`,
+ "",
+ `[Daily active users, last 7 days](${sql("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")} "The drop on Aug 14 lines up with the checkout deploy.")`,
+ "",
+ "The saved funnel shows the same drop:",
+ "",
+ `[Coupon funnel, last 30 days](${PROJECT}/insights/9pQx3)`,
+ "",
+ "One user retried the coupon field four times before they left:",
+ "",
+ `[The failed checkout](${PROJECT}/replay/0190f8a1-sess?t=42)`,
+ ].join("\n"),
+ },
+};
+
+export const LinksThatStayPlain: Story = {
+ args: {
+ renderObjectTags: true,
+ content: [
+ `- An insight in [another project](https://us.posthog.com/project/3/insights/9pQx3) or [another region](https://eu.posthog.com/project/2/insights/9pQx3) stays a plain link.`,
+ `- A page that is not an object, like [project settings](${PROJECT}/settings/project), stays a plain link.`,
+ `- A flag cited by key, like [new-checkout-flow](${PROJECT}/feature_flags/new-checkout-flow), has no page, so it stays a plain link.`,
+ `- A chart link inside a list, like [DAU](${sql("SELECT 1")}), stays an inline chip.`,
+ `- Code stays code: \`[DAU](${PROJECT}/insights/9pQx3)\``,
+ "- The docs stay a normal link: [PostHog docs](https://posthog.com/docs).",
+ ].join("\n"),
+ },
+};
+
+export const TagsAndLinksRenderTheSame: Story = {
+ render: () => (
+ <div className="flex flex-col gap-4">
+ <MarkdownRenderer
+ renderObjectTags
+ content={`Old tags: the <insight id="9pQx3">checkout funnel</insight> dropped after <flag id="42">new-checkout-flow</flag> rolled out, see <hogql label="errors today">SELECT count() FROM events WHERE event = '$exception'</hogql>.`}
+ />
+ <MarkdownRenderer
+ renderObjectTags
+ content={`New links: the [checkout funnel](${PROJECT}/insights/9pQx3) dropped after [new-checkout-flow](${PROJECT}/feature_flags/42) rolled out, see [errors today](${sql("SELECT count() FROM events WHERE event = '$exception'")}).`}
+ />
+ </div>
+ ),
+};
+
+export const UntrustedContent: Story = {
+ args: {
+ content: `A user pasted [this chart](${sql("SELECT 1")}) and [this insight](${PROJECT}/insights/9pQx3). User content never runs queries, so both stay plain links.`,
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
index a3fbd758692f..834fa47ab067 100644
--- a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
@@ -2,7 +2,6 @@ import { Popover } from "@base-ui/react/popover";
import { CheckIcon, CopyIcon } from "@phosphor-icons/react";
import { isPostHogObjectKind } from "@posthog/core/message-editor/content";
import { Button } from "@posthog/quill";
-import { getCloudUrlFromRegion } from "@posthog/shared";
import { useOpenInboxReport } from "@posthog/ui/features/inbox/hooks/useOpenInboxReport";
import { useQueryClient } from "@tanstack/react-query";
import {
@@ -14,7 +13,6 @@ import {
useState,
} from "react";
import { useOptionalAuthenticatedClient } from "../../../features/auth/authClient";
-import { useAuthStateValue } from "../../../features/auth/store";
import { useDraftStore } from "../../../features/message-editor/draftStore";
import { usePanelLayoutStore } from "../../../features/panels/panelLayoutStore";
import { useSessionTaskId } from "../../../features/sessions/useSessionTaskId";
@@ -38,6 +36,7 @@ import {
trackEvidencePreviewShown,
} from "../evidencePreviewAnalytics";
import { useEvidencePreviewPrefetch } from "../useEvidencePreviewPrefetch";
+import { usePostHogLinkContext } from "../usePostHogLinkContext";
/**
* Inline evidence reference inside an agent message, authored as a
@@ -363,14 +362,15 @@ function EvidenceHoverCardLoader({
const shownTrackedRef = useRef(false);
const kind = target.kind;
const id = target.id;
+ const referenceSource = target.href ? "link" : "tag";
useEffect(() => {
if (shownTrackedRef.current) return;
shownTrackedRef.current = true;
const cached =
queryClient.getQueryState(evidencePreviewQueryKey({ kind, id }))
?.status === "success";
- trackEvidencePreviewShown(kind, cached);
- }, [queryClient, kind, id]);
+ trackEvidencePreviewShown(kind, cached, referenceSource);
+ }, [queryClient, kind, id, referenceSource]);
const query = useAuthenticatedQuery(
evidencePreviewQueryKey(target),
(apiClient) => fetchEvidencePreviewTimed(apiClient, target, "hover"),
@@ -416,11 +416,10 @@ function EvidenceHoverCardLoader({
/** 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 links = usePostHogLinkContext();
const path = evidenceWebPath(kind, id);
- if (!path || !cloudRegion || !projectId) return null;
- return `${getCloudUrlFromRegion(cloudRegion)}/project/${projectId}${path}`;
+ if (!path || !links) return null;
+ return `${links.appUrl}/project/${links.projectId}${path}`;
}
interface EvidenceRefChipProps {
@@ -450,7 +449,8 @@ function EvidenceRefChipContent({
}) {
const meta = getObjectKind(target.kind);
const KindIcon = meta.icon;
- const url = useEvidenceUrl(target.kind, target.id);
+ const canonicalUrl = useEvidenceUrl(target.kind, target.id);
+ const url = target.href ?? canonicalUrl;
const taskId = useSessionTaskId();
const objectKind = isPostHogObjectKind(target.kind) ? target.kind : null;
const [open, setOpen] = useState(false);
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
index 7a4ff6b904c0..50bb60a1c001 100644
--- 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
@@ -1,7 +1,7 @@
import { Theme } from "@radix-ui/themes";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, 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.
@@ -27,8 +27,11 @@ vi.mock("../../../hooks/useAuthenticatedQuery", () => ({
}),
}));
+import { ANONYMOUS_AUTH_STATE, useAuthStore } from "../../auth/store";
import { MarkdownRenderer } from "./MarkdownRenderer";
+const PROJECT = "https://us.posthog.com/project/2";
+
const queryClient = new QueryClient();
function renderMarkdown(content: string) {
@@ -172,6 +175,98 @@ describe("object tags in agent markdown", () => {
});
});
+describe("PostHog object links in agent markdown", () => {
+ beforeEach(() => {
+ useAuthStore.setState({
+ authState: {
+ ...ANONYMOUS_AUTH_STATE,
+ cloudRegion: "us",
+ currentProjectId: 2,
+ },
+ });
+ });
+
+ afterEach(() => {
+ useAuthStore.setState({ authState: ANONYMOUS_AUTH_STATE });
+ });
+
+ it("renders an inline object link as a reference chip", () => {
+ renderMarkdown(`The [checkout funnel](${PROJECT}/insights/9pQx3) dropped.`);
+ expect(screen.getByText("checkout funnel").closest("a")?.href).toBe(
+ `${PROJECT}/insights/9pQx3`,
+ );
+ expect(screen.queryByLabelText("external link icon")).toBeNull();
+ });
+
+ it.each([
+ [
+ "an insight",
+ `Here it is:\n\n[Checkout funnel, last 30 days](${PROJECT}/insights/9pQx3)\n`,
+ "Checkout funnel, last 30 days",
+ ],
+ [
+ "a SQL query",
+ `[DAU, last 7 days](${PROJECT}/sql?open_query=SELECT%201 "Excludes bots")\n`,
+ "DAU, last 7 days",
+ ],
+ [
+ "a tool result query",
+ `[DAU](${PROJECT}/insights/new#q=${encodeURIComponent(JSON.stringify({ kind: "DataTableNode", source: { kind: "HogQLQuery", query: "SELECT 1" } }))})\n`,
+ "DAU",
+ ],
+ ])(
+ "renders a link to %s alone in its paragraph as a chart card",
+ (_what, content, title) => {
+ renderMarkdown(content);
+ expect(screen.getByTestId("report-chart")).toBeDefined();
+ expect(screen.getByText(title)).toBeDefined();
+ },
+ );
+
+ it("renders a replay link alone in its paragraph as a watchable card", () => {
+ renderMarkdown(
+ `Watch it:\n\n[The failed checkout](${PROJECT}/replay/s_01HQ4K)\n`,
+ );
+ expect(screen.getByTestId("replay-card")).toBeDefined();
+ });
+
+ it.each([
+ ["a list", `- [DAU](${PROJECT}/sql?open_query=SELECT%201)\n`],
+ ["a sentence", `See [DAU](${PROJECT}/sql?open_query=SELECT%201) now.\n`],
+ ])("keeps a chart link inside %s as an inline chip", (_where, content) => {
+ renderMarkdown(content);
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ expect(screen.getByText("DAU")).toBeDefined();
+ expect(screen.queryByLabelText("external link icon")).toBeNull();
+ });
+
+ it.each([
+ ["another project", "https://us.posthog.com/project/3/insights/9pQx3"],
+ ["another region", "https://eu.posthog.com/project/2/insights/9pQx3"],
+ ["a page that is not an object", `${PROJECT}/settings/project`],
+ ])("leaves a link to %s as a plain link", (_what, url) => {
+ renderMarkdown(`[the page](${url})\n`);
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ expect(screen.getByLabelText("external link icon")).toBeDefined();
+ });
+
+ it("does not turn a half-streamed link into a live query", () => {
+ renderMarkdown(`[DAU](${PROJECT}/sql?open_query=SELECT%20count(`);
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ });
+
+ it("does not run an object link in untrusted content", () => {
+ renderUntrustedMarkdown(`[DAU](${PROJECT}/sql?open_query=SELECT%201)\n`);
+ expect(screen.queryByTestId("report-chart")).toBeNull();
+ expect(screen.getByLabelText("external link icon")).toBeDefined();
+ });
+
+ it("labels a bare object URL with its kind", () => {
+ renderMarkdown(`Gated by ${PROJECT}/feature_flags/42 since Jan 3.`);
+ expect(screen.getByText("Feature flag 42")).toBeDefined();
+ });
+});
+
describe("object tags in untrusted markdown (default)", () => {
it("does not render a block tag as a live chart card", () => {
renderUntrustedMarkdown(
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 28eff017c517..fdae00b875be 100644
--- a/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
@@ -3,6 +3,7 @@ import { ArtifactRefChip } from "@posthog/ui/features/editor/components/Artifact
import { EvidenceRefChip } from "@posthog/ui/features/editor/components/EvidenceRefChip";
import { githubRefChipFor } from "@posthog/ui/features/editor/components/githubRefChipFor";
import { MessageChartCard } from "@posthog/ui/features/editor/components/MessageChartCard";
+import { useObjectTagRemarkPlugins } from "@posthog/ui/features/editor/usePostHogLinkContext";
import { CodeBlock } from "@posthog/ui/primitives/CodeBlock";
import { Divider } from "@posthog/ui/primitives/Divider";
import { HighlightedCode } from "@posthog/ui/primitives/HighlightedCode";
@@ -19,7 +20,6 @@ import {
isMermaidCodeBlock,
MERMAID_LANGUAGE,
} from "@posthog/ui/utils/mermaidBlocks";
-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";
@@ -162,8 +162,8 @@ export const baseComponents: Components = {
del: ({ children }) => (
<del className="text-(--gray-9) line-through">{children}</del>
),
- a: ({ href, children }) => {
- const evidenceTarget = parseEvidenceLink(href);
+ a: ({ href, children, node }) => {
+ const evidenceTarget = parseEvidenceLink(href, node?.properties);
if (evidenceTarget) {
return (
<EvidenceRefChip target={evidenceTarget}>{children}</EvidenceRefChip>
@@ -263,7 +263,6 @@ const objectTagComponents: Components = {
};
export const defaultRemarkPlugins = [remarkGfm];
-const objectTagRemarkPlugins = [...defaultRemarkPlugins, remarkObjectTags];
export const MarkdownRenderer = memo(function MarkdownRenderer({
content,
@@ -276,6 +275,7 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
() => preprocessMarkdown(content),
[content],
);
+ const objectTagRemarkPlugins = useObjectTagRemarkPlugins();
const plugins =
remarkPluginsOverride ??
(renderObjectTags ? objectTagRemarkPlugins : defaultRemarkPlugins);
diff --git a/products/desktop/packages/ui/src/features/editor/evidencePreviewAnalytics.test.ts b/products/desktop/packages/ui/src/features/editor/evidencePreviewAnalytics.test.ts
index 6ef578b5d922..e926259c7521 100644
--- a/products/desktop/packages/ui/src/features/editor/evidencePreviewAnalytics.test.ts
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreviewAnalytics.test.ts
@@ -37,7 +37,7 @@ describe("evidence preview analytics", () => {
await expect(
fetchEvidencePreviewTimed(client, { kind: "flag", id: "42" }, "hover"),
).resolves.toEqual({ title: "Anything" });
- expect(() => trackEvidencePreviewShown("flag", false)).not.toThrow();
+ expect(() => trackEvidencePreviewShown("flag", false, "tag")).not.toThrow();
});
it("reports ready with kind, source and load latency — and no reference contents", async () => {
@@ -89,13 +89,14 @@ describe("evidence preview analytics", () => {
it("reports shown with the cache state and no reference id", () => {
const track = bindTracker();
- trackEvidencePreviewShown("insight", false);
+ trackEvidencePreviewShown("insight", false, "link");
expect(track).toHaveBeenCalledWith(
ANALYTICS_EVENTS.EVIDENCE_PREVIEW_SHOWN,
{
kind: "insight",
cache: "miss",
+ reference_source: "link",
},
);
});
diff --git a/products/desktop/packages/ui/src/features/editor/evidencePreviewAnalytics.ts b/products/desktop/packages/ui/src/features/editor/evidencePreviewAnalytics.ts
index deefe69d95e1..bb8461817614 100644
--- a/products/desktop/packages/ui/src/features/editor/evidencePreviewAnalytics.ts
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreviewAnalytics.ts
@@ -14,10 +14,15 @@ function tracker(): AnalyticsTracker | null {
return resolveServiceOptional<AnalyticsTracker>(ANALYTICS_TRACKER);
}
-export function trackEvidencePreviewShown(kind: string, cached: boolean): void {
+export function trackEvidencePreviewShown(
+ kind: string,
+ cached: boolean,
+ referenceSource: "link" | "tag",
+): void {
tracker()?.track(ANALYTICS_EVENTS.EVIDENCE_PREVIEW_SHOWN, {
kind,
cache: cached ? "hit" : "miss",
+ reference_source: referenceSource,
});
}
diff --git a/products/desktop/packages/ui/src/features/editor/usePostHogLinkContext.ts b/products/desktop/packages/ui/src/features/editor/usePostHogLinkContext.ts
new file mode 100644
index 000000000000..fccf2000c876
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/usePostHogLinkContext.ts
@@ -0,0 +1,24 @@
+import type { PostHogLinkContext } from "@posthog/core/posthog-objects/objectUrls";
+import { getCloudUrlFromRegion } from "@posthog/shared";
+import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import { remarkObjectTags } from "@posthog/ui/utils/remarkObjectTags";
+import { useMemo } from "react";
+import remarkGfm from "remark-gfm";
+import type { PluggableList } from "unified";
+
+export function usePostHogLinkContext(): PostHogLinkContext | null {
+ const projectId = useAuthStateValue((state) => state.currentProjectId);
+ const cloudRegion = useAuthStateValue((state) => state.cloudRegion);
+ return useMemo(
+ () =>
+ cloudRegion && projectId
+ ? { appUrl: getCloudUrlFromRegion(cloudRegion), projectId }
+ : null,
+ [cloudRegion, projectId],
+ );
+}
+
+export function useObjectTagRemarkPlugins(): PluggableList {
+ const links = usePostHogLinkContext();
+ return useMemo(() => [remarkGfm, [remarkObjectTags, { links }]], [links]);
+}
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 38506f733a08..28e8dec4629a 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
@@ -2,7 +2,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { renderToStaticMarkup as renderMarkup } from "react-dom/server";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("mermaid", () => ({
default: {
@@ -79,6 +79,10 @@ vi.mock("@posthog/ui/features/code-editor/hooks/useFileContent", () => ({
useWorkspaceFileAsBase64,
}));
+import {
+ ANONYMOUS_AUTH_STATE,
+ useAuthStore,
+} from "@posthog/ui/features/auth/store";
import { SessionTaskIdProvider } from "@posthog/ui/features/sessions/useSessionTaskId";
import {
ChatMarkdown,
@@ -191,6 +195,10 @@ describe("resolveLocalImage", () => {
});
describe("ChatMarkdown object tags", () => {
+ afterEach(() => {
+ useAuthStore.setState({ authState: ANONYMOUS_AUTH_STATE });
+ });
+
// 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.
@@ -221,6 +229,36 @@ describe("ChatMarkdown object tags", () => {
expect(html).not.toContain("SELECT 1");
});
+ it.each([
+ [
+ "an inline link as a chip that opens the cited page",
+ "The [checkout funnel](https://us.posthog.com/project/2/replay/s1?t=30) dropped.",
+ 'href="https://us.posthog.com/project/2/replay/s1?t=30"',
+ ],
+ [
+ "a SQL link alone in its paragraph as a chart card",
+ "[DAU, last 7 days](https://us.posthog.com/project/2/sql?open_query=SELECT%201)",
+ "report-chart",
+ ],
+ ])("renders %s", (_what, content, expected) => {
+ useAuthStore.setState({
+ authState: {
+ ...ANONYMOUS_AUTH_STATE,
+ cloudRegion: "us",
+ currentProjectId: 2,
+ },
+ });
+ const { container, unmount } = render(
+ <QueryClientProvider client={queryClient}>
+ <ChatMarkdown content={content} renderObjectTags />
+ </QueryClientProvider>,
+ );
+ const html = container.innerHTML;
+ unmount();
+ expect(html).toContain(expected);
+ expect(html).not.toContain('target="_blank"');
+ });
+
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.
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 5d8335d62f55..61fdd7a8988f 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
@@ -21,6 +21,7 @@ import {
parseOpenFence,
splitMarkdownBlocks,
} from "@posthog/ui/features/editor/components/splitMarkdownBlocks";
+import { useObjectTagRemarkPlugins } from "@posthog/ui/features/editor/usePostHogLinkContext";
import {
BareFileLink,
hasDirectoryPath,
@@ -41,9 +42,11 @@ import {
isGeneratedChartBlock,
parseChartBlock,
} from "@posthog/ui/utils/chartBlocks";
-import { parseEvidenceLink } from "@posthog/ui/utils/evidenceLinks";
+import {
+ OBJECT_LINK_HREF,
+ parseEvidenceLink,
+} from "@posthog/ui/utils/evidenceLinks";
import { MERMAID_LANGUAGE } from "@posthog/ui/utils/mermaidBlocks";
-import { remarkObjectTags } from "@posthog/ui/utils/remarkObjectTags";
import { IconButton } from "@radix-ui/themes";
import { memo, type ReactNode, useEffect, useMemo, useRef } from "react";
import Markdown, { type Components, defaultUrlTransform } from "react-markdown";
@@ -193,7 +196,7 @@ const components: Components = {
p: ({ children }) => (
<Text className="text-sm leading-[1.5]">{children}</Text>
),
- a: ({ children, href }) => {
+ a: ({ children, href, node }) => {
if (href === PENDING_LINK_DESTINATION) {
return (
<output
@@ -205,7 +208,7 @@ const components: Components = {
</output>
);
}
- const evidenceTarget = parseEvidenceLink(href);
+ const evidenceTarget = parseEvidenceLink(href, node?.properties);
if (evidenceTarget) {
return (
<EvidenceRefChip target={evidenceTarget}>{children}</EvidenceRefChip>
@@ -331,7 +334,6 @@ function chatUrlTransform(value: string, key: string): string {
}
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
@@ -344,6 +346,7 @@ const rehypePlugins: PluggableList = [
attributes: {
...defaultSchema.attributes,
code: [...(defaultSchema.attributes?.code ?? []), CHART_BLOCK_MARKER],
+ a: [...(defaultSchema.attributes?.a ?? []), OBJECT_LINK_HREF],
},
protocols: {
...defaultSchema.protocols,
@@ -364,6 +367,7 @@ export const ChatMarkdown = memo(function ChatMarkdown({
content,
renderObjectTags = false,
}: ChatMarkdownProps) {
+ const objectTagRemarkPlugins = useObjectTagRemarkPlugins();
return (
<div className="flex flex-col gap-3 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
<Markdown
diff --git a/products/desktop/packages/ui/src/utils/evidenceLinks.ts b/products/desktop/packages/ui/src/utils/evidenceLinks.ts
index 163f201463da..e142ad79225d 100644
--- a/products/desktop/packages/ui/src/utils/evidenceLinks.ts
+++ b/products/desktop/packages/ui/src/utils/evidenceLinks.ts
@@ -13,12 +13,14 @@ import { getObjectKind } from "./objectKinds";
*/
const EVIDENCE_SCHEME = "evidence:";
+export const OBJECT_LINK_HREF = "dataPosthogHref";
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;
+ href?: string;
}
function decodePart(part: string): string {
@@ -36,6 +38,7 @@ function decodePart(part: string): string {
*/
export function parseEvidenceLink(
href: string | undefined,
+ properties?: Record<string, unknown>,
): EvidenceLinkTarget | null {
if (!href || !href.startsWith(EVIDENCE_SCHEME)) return null;
@@ -46,7 +49,9 @@ export function parseEvidenceLink(
const match = KIND_ID_RE.exec(path);
if (!match) return null;
- return { kind: match[1], id: decodePart(match[2]) };
+ const target = { kind: match[1], id: decodePart(match[2]) };
+ const original = properties?.[OBJECT_LINK_HREF];
+ return typeof original === "string" ? { ...target, href: original } : target;
}
/**
diff --git a/products/desktop/packages/ui/src/utils/remarkObjectTags.ts b/products/desktop/packages/ui/src/utils/remarkObjectTags.ts
index 6aab24e0fefa..6897e5758214 100644
--- a/products/desktop/packages/ui/src/utils/remarkObjectTags.ts
+++ b/products/desktop/packages/ui/src/utils/remarkObjectTags.ts
@@ -1,7 +1,14 @@
+import {
+ objectUrlLabel,
+ type PostHogLinkContext,
+ type PostHogObjectUrlRef,
+ parsePostHogObjectUrl,
+} from "@posthog/core/posthog-objects/objectUrls";
import { unescapeXmlAttr } from "@posthog/shared";
-import type { Parent, PhrasingContent, Root, RootContent } from "mdast";
+import type { Link, Parent, PhrasingContent, Root, RootContent } from "mdast";
import { CHART_BLOCK_MARKER } from "./chartBlocks";
-import { resolveObjectKindName } from "./objectKinds";
+import { OBJECT_LINK_HREF } from "./evidenceLinks";
+import { getObjectKind, resolveObjectKindName } from "./objectKinds";
/**
* Remark plugin for the object tags agents embed in replies, the message-side
@@ -35,6 +42,11 @@ const MAX_BLOCK_TAGS = 10;
/** Mutable per-document budget threaded through the transform. */
interface TransformState {
blockBudget: number;
+ links: PostHogLinkContext | null;
+}
+
+export interface RemarkObjectTagsOptions {
+ links?: PostHogLinkContext | null;
}
const OPEN_TAG_RE = /^<([a-z][\w-]*)((?:\s+[a-z][\w-]*\s*=\s*"[^"]*")*)\s*>$/;
@@ -259,6 +271,67 @@ function liftParagraphBlockTag(
return block;
}
+function isAutoLink(node: Link): boolean {
+ return (
+ nodesToText(node.children as PhrasingContent[]).trim() === node.url.trim()
+ );
+}
+
+function objectLinkRef(
+ node: Link,
+ previous: RootContent | undefined,
+ state: TransformState,
+): PostHogObjectUrlRef | null {
+ if (!state.links) return null;
+ if (previous?.type === "text" && /\]\(<?$/.test(previous.value)) return null;
+ return parsePostHogObjectUrl(node.url, state.links);
+}
+
+function inlineLinkNode(node: Link, ref: PostHogObjectUrlRef): PhrasingContent {
+ return {
+ type: "link",
+ url: `evidence:${ref.kind}/${encodeURIComponent(ref.id)}`,
+ children: isAutoLink(node)
+ ? [text(objectUrlLabel(ref))]
+ : (node.children as PhrasingContent[]),
+ data: { hProperties: { [OBJECT_LINK_HREF]: ref.href } },
+ };
+}
+
+function blockLinkNode(
+ node: Link,
+ ref: PostHogObjectUrlRef,
+): RootContent | null {
+ if (!getObjectKind(ref.kind).block) return null;
+ const attrs: Record<string, string> = { id: ref.id };
+ const title = isAutoLink(node)
+ ? ""
+ : nodesToText(node.children as PhrasingContent[]).trim();
+ if (title) attrs.title = title;
+ if (node.title?.trim()) attrs.caption = node.title;
+ return blockNode({
+ kind: ref.kind,
+ attrs,
+ body: ref.kind === "hogql" ? ref.id : undefined,
+ });
+}
+
+function liftParagraphObjectLink(
+ paragraph: Parent,
+ state: TransformState,
+): RootContent | null {
+ if (state.blockBudget <= 0) return null;
+ const kids = (paragraph.children as RootContent[]).filter(
+ (kid) => !(kid.type === "text" && !kid.value.trim()),
+ );
+ if (kids.length !== 1 || kids[0].type !== "link") return null;
+ const ref = objectLinkRef(kids[0], undefined, state);
+ if (!ref) return null;
+ const block = blockLinkNode(kids[0], ref);
+ 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,
@@ -288,8 +361,19 @@ function transformChildren(
continue;
}
}
+ if (child.type === "link") {
+ const ref = objectLinkRef(child, children[i - 1], state);
+ if (ref) {
+ out.push(inlineLinkNode(child, ref) as RootContent);
+ continue;
+ }
+ }
if (inFlow && child.type === "paragraph") {
- const lifted = liftParagraphBlockTag(child as Parent, state);
+ const lifted =
+ liftParagraphBlockTag(child as Parent, state) ??
+ (parent.type === "root"
+ ? liftParagraphObjectLink(child as Parent, state)
+ : null);
if (lifted) {
out.push(lifted);
continue;
@@ -307,8 +391,11 @@ function transformChildren(
parent.children = out as Parent["children"];
}
-export function remarkObjectTags() {
+export function remarkObjectTags(options: RemarkObjectTagsOptions = {}) {
return (tree: Root): void => {
- transformChildren(tree, true, { blockBudget: MAX_BLOCK_TAGS });
+ transformChildren(tree, true, {
+ blockBudget: MAX_BLOCK_TAGS,
+ links: options.links ?? null,
+ });
};
}
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
index d8800f890968..cf5ec7cec853 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
@@ -189,7 +189,7 @@ vi.mock("node:fs", async (importOriginal) => {
// --- Import after mocks ---
import { fetchGatewayModels } from "@posthog/agent/gateway-models";
import { PRODUCT_ENGINEER_PROMPT } from "@posthog/shared/product-engineer-prompt";
-import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";
+import { RICH_OUTPUT_PROMPT_LEAD } from "@posthog/shared/rich-output-prompt";
import {
AgentService,
buildAutoApproveOutcome,
@@ -1537,7 +1537,7 @@ describe("AgentService", () => {
const prompt = buildChannelPrompt(systemPromptOverride);
expect(prompt).toContain(PRODUCT_ENGINEER_PROMPT);
- expect(prompt).toContain(RICH_OUTPUT_TAGS_PROMPT);
+ expect(prompt).toContain(RICH_OUTPUT_PROMPT_LEAD);
expect(prompt.indexOf(PRODUCT_ENGINEER_PROMPT)).toBeLessThan(
prompt.indexOf(systemPromptOverride ?? "PostHog context:"),
);
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 5541e89031c4..e75c19d6cdae 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
@@ -95,7 +95,10 @@ import {
TypedEventEmitter,
} from "@posthog/shared";
import { prependProductEngineerPrompt } from "@posthog/shared/product-engineer-prompt";
-import { appendRichOutputPrompt } from "@posthog/shared/rich-output-prompt";
+import {
+ appendRichOutputPrompt,
+ getProjectWebUrl,
+} from "@posthog/shared/rich-output-prompt";
import { inject, injectable, preDestroy } from "inversify";
import { WORKSPACE_REPOSITORY } from "../../db/identifiers";
import type { IWorkspaceRepository } from "../../db/repositories/workspace-repository";
@@ -902,11 +905,17 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
): {
append: string;
} {
+ const projectUrl = getProjectWebUrl(
+ credentials.apiHost,
+ credentials.projectId,
+ );
// Overrides replace task guidance, but product engineering and rich-output rules stay available.
if (systemPromptOverride) {
return {
append: appendRichOutputPrompt(
prependProductEngineerPrompt(systemPromptOverride),
+ undefined,
+ projectUrl,
),
};
}
@@ -929,7 +938,11 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
);
return {
- append: appendRichOutputPrompt(prependProductEngineerPrompt(prompt)),
+ append: appendRichOutputPrompt(
+ prependProductEngineerPrompt(prompt),
+ undefined,
+ projectUrl,
+ ),
};
}
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index c7fdb7dc97ca..d278fa9a0470 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -29,6 +29,7 @@ from posthog.ph_client import ph_scoped_capture
from posthog.slack.formatting import (
channel_id_from_target as _channel_id_from_target,
escape_slack_mrkdwn as _escape_mrkdwn,
+ markdown_links_to_labels,
)
from posthog.slack.markdown import slack_markdown_block as _markdown_block
@@ -306,6 +307,9 @@ def _summary_excerpt(summary: str) -> str:
first_line = text.splitlines()[0].strip()
if not first_line:
return ""
+ if len(first_line) <= _SUMMARY_EXCERPT_MAX_LEN:
+ return first_line
+ first_line = markdown_links_to_labels(first_line)
if len(first_line) <= _SUMMARY_EXCERPT_MAX_LEN:
return first_line
return first_line[: _SUMMARY_EXCERPT_MAX_LEN - 3].rstrip() + "..."
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index 3ce8470d50f0..734d3faa3861 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -72,6 +72,11 @@ def test_summary_excerpt_truncates_first_line_at_600_chars() -> None:
assert _summary_excerpt(long_line).endswith("...")
+def test_summary_excerpt_keeps_links_out_of_the_cut() -> None:
+ sql_link = "[the query](https://us.posthog.com/project/2/sql?open_query=" + "SELECT%201%20" * 60 + ")"
+ assert _summary_excerpt(f"Errors rose, see {sql_link} for details.") == "Errors rose, see the query for details."
+
+
def _plain_text_block_texts(blocks: list[dict]) -> list[str]:
"""Every plain_text string in the message — mentions here would render as raw `<@…>`."""
texts: list[str] = []
diff --git a/products/tasks/backend/loop_notifications.py b/products/tasks/backend/loop_notifications.py
index e3c9398a2751..f81474a67a2d 100644
--- a/products/tasks/backend/loop_notifications.py
+++ b/products/tasks/backend/loop_notifications.py
@@ -23,7 +23,7 @@ from slack_sdk.errors import SlackApiError
from posthog.email import EmailMessage, get_email_team_and_org_context, is_email_available
from posthog.models.integration import Integration, SlackIntegration
from posthog.redis import get_client
-from posthog.slack.formatting import escape_slack_mrkdwn
+from posthog.slack.formatting import escape_slack_mrkdwn, markdown_links_to_labels
from posthog.tasks.push_notifications import send_user_push
from products.notifications.backend.facade.api import (
@@ -200,7 +200,10 @@ def _send_slack(
return
report = payload.get("report")
slack_body = str(report) if report else body
- text = _truncate(f"*{escape_slack_mrkdwn(title)}*\n{escape_slack_mrkdwn(slack_body)}", _SLACK_BODY_MAX_CHARS)
+ text = f"*{escape_slack_mrkdwn(title)}*\n{escape_slack_mrkdwn(slack_body)}"
+ if len(text) > _SLACK_BODY_MAX_CHARS:
+ text = f"*{escape_slack_mrkdwn(title)}*\n{escape_slack_mrkdwn(markdown_links_to_labels(slack_body))}"
+ text = _truncate(text, _SLACK_BODY_MAX_CHARS)
SlackIntegration(integration, source="loop_notifications").client.chat_postMessage(
channel=channel, text=text, unfurl_links=False, unfurl_media=False
)
diff --git a/products/tasks/backend/tests/test_loop_notifications.py b/products/tasks/backend/tests/test_loop_notifications.py
index a4f7132e3bb9..5b9e1be043c3 100644
--- a/products/tasks/backend/tests/test_loop_notifications.py
+++ b/products/tasks/backend/tests/test_loop_notifications.py
@@ -301,6 +301,23 @@ class TestDispatchLoopEventSlackReport(LoopNotificationsTestCase):
unfurl_media=False,
)
+ @patch(f"{LOOP_NOTIFICATIONS_MODULE}.create_notification")
+ @patch(f"{LOOP_NOTIFICATIONS_MODULE}.SlackIntegration")
+ def test_slack_report_over_the_limit_keeps_links_out_of_the_cut(self, mock_slack_cls, _mock_create_notification):
+ loop = self.create_loop_with_slack()
+ fake_client = MagicMock()
+ mock_slack_cls.return_value.client = fake_client
+ sql_link = "[the query](https://us.posthog.com/project/2/sql?open_query=" + "SELECT%201%20" * 300 + ")"
+
+ dispatch_loop_event(loop, "run_completed", {"report": f"Errors rose, see {sql_link} for details."})
+
+ fake_client.chat_postMessage.assert_called_once_with(
+ channel="C123",
+ text='*Loop "Daily digest" finished*\nErrors rose, see the query for details.',
+ unfurl_links=False,
+ unfurl_media=False,
+ )
+
@patch(f"{LOOP_NOTIFICATIONS_MODULE}.create_notification")
@patch(f"{LOOP_NOTIFICATIONS_MODULE}.SlackIntegration")
def test_slack_report_escapes_control_tokens(self, mock_slack_cls, _mock_create_notification):