:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(lemon-ui): render urls in error toasts as clickable links (#87074)
Joe Martin321fdc2a7e42
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c41aa5f6bfce..138ebd1321f5 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4393,9 +4393,9 @@ snapshots:lemon-ui-lemon-text-area-markdown--lemon-text-markdown-with-text--light:hash: v1.k794b7964.2a0bb72ced637238cfc496b82b4f9fb848c7af10d49fd6085acd2925363b67e8.mHXsr6MVeOP2d5GGAs3VwuQ6kPgsj2A1UmohZ8F6yvolemon-ui-lemon-toast--billing-error--dark:- hash: v1.k794b7964.5da9c7bd53e4abb187399898f25a23ce8ced2d774f698c8a924ec2e154735aea.kzKa6tePw16XYNP0JNkqr0zY7bhGuxd_AaGizrrUrh8+ hash: v1.k794b7964.64b7887afb2ef6cd92e9c5f57ea84e66f5114bd0a6a03372ab1a3e081ac8789b.Gnx0TCdqk4r0PMRBztDGPk7_FMV6JoVOLbJ6DPFhtK4lemon-ui-lemon-toast--billing-error--light:- hash: v1.k794b7964.cf189dec2258bd206d131ff1e99bc8cba48295d0fb4913d858d2b187a35811ec.mW58dBj9TPtYgJbJA2B40DAoMXkNLGrPvo11MUG5lkc+ hash: v1.k794b7964.970981e3c67cb222ae7d614ad99edfd3abcc2781761b32fdea61ad715e657403.VVHlir2g0uZ7WnoaRwr9ENJoAapYp6YuU2_CUbnAEUYlemon-ui-lemon-toast--error-with-incident-note--dark:hash: v1.k794b7964.1c601ff99ec62768254d37d7453e6b02071de2bf96df39d4ea47c734bc9d0035.ezD5TEDT6BIROQhjSuw1MSU2O6j8Zjai7vN33EgCQxklemon-ui-lemon-toast--error-with-incident-note--light:diff --git a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsx b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsxindex 2ff406eef714..3cd9bf87400e 100644--- a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsx+++ b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsx@@ -1,6 +1,8 @@+import '@testing-library/jest-dom'+import { act, fireEvent, render } from '@testing-library/react'-import { GET_HELP_BUTTON, ToastContent } from './LemonToast'+import { GET_HELP_BUTTON, ToastContent, withClickableUrls } from './LemonToast'describe('LemonToast', () => {const writeText = jest.fn((_text: string) => Promise.resolve())@@ -34,4 +36,27 @@ describe('LemonToast', () => {expect(!!container.querySelector('[data-attr="toast-copy-button"]')).toBe(expected)})++ // Wiring guard for the error toast path: the message must go through the trusted-only+ // renderDetailWithLinks (URL linked in place, prose untouched), not a linkify-everything helper.+ it('links a PostHog URL in place without changing the message text', () => {+ const { container } = render(+ <>{withClickableUrls('Visit https://posthog.com/docs to fix this, then retry.')}</>+ )++ const link = container.querySelector('a')!+ expect(link).toHaveAttribute('href', 'https://posthog.com/docs')+ expect(container).toHaveTextContent('Visit https://posthog.com/docs to fix this, then retry.')+ })++ it('leaves a URL outside posthog.com as plain text', () => {+ const { container } = render(<>{withClickableUrls('More info: https://example.com/details')}</>)++ expect(container.querySelector('a')).toBeNull()+ expect(container).toHaveTextContent('More info: https://example.com/details')+ })++ it('returns a message without URLs unchanged', () => {+ expect(withClickableUrls('Load experiment failed')).toBe('Load experiment failed')+ })})diff --git a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsxindex 346d474d3ac2..aa3594f3d516 100644--- a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx+++ b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx@@ -6,6 +6,7 @@ import { IconCheckCircle, IconCopy, IconInfo, IconWarning, IconX } from '@posthoimport { getIncidentStatus, STATUS_PAGE_BASE } from 'lib/components/HelpMenu/incidentStatus'import { isChristmas } from 'lib/holidays'+import { renderDetailWithLinks } from 'lib/utils/renderDetailWithLinks'import { hashCodeForString } from 'lib/utils/strings'import { writeToClipboard } from 'lib/utils/writeToClipboard'@@ -161,6 +162,18 @@ function ensureToastId<T>(return { ...toastOptions, toastId }}+/**+ * Backend error details often embed a raw docs URL ("... see our docs: https://posthog.com/docs/..."),+ * which as plain toast text is unclickable. `renderDetailWithLinks` links PostHog-host URLs in place,+ * leaving the prose (and any untrusted URL) untouched, so the copy button still carries the full text.+ */+export function withClickableUrls(message: string | JSX.Element): string | JSX.Element {+ if (typeof message !== 'string' || !message.includes('http')) {+ return message+ }+ return <>{renderDetailWithLinks(message)}</>+}+function withIncidentNote(message: string | JSX.Element): string | JSX.Element {const status = getIncidentStatus()if (status === 'operational') {@@ -268,7 +281,7 @@ export const lemonToast = {toast.error(<ToastContenttype="error"- message={withIncidentNote(message)}+ message={withIncidentNote(withClickableUrls(message))}// Show button if explicitly provided, or show GET_HELP_BUTTON unless hideButton is truebutton={button !== undefined ? button : hideButton ? undefined : GET_HELP_BUTTON}id={id}@@ -314,7 +327,7 @@ export const lemonToast = {return (<ToastContenttype="error"- message={withIncidentNote(data?.message || messages.error)}+ message={withIncidentNote(withClickableUrls(data?.message || messages.error))}button={button}id={id}/>diff --git a/frontend/src/lib/utils/renderDetailWithLinks.test.tsx b/frontend/src/lib/utils/renderDetailWithLinks.test.tsxnew file mode 100644index 000000000000..372aa158feb0--- /dev/null+++ b/frontend/src/lib/utils/renderDetailWithLinks.test.tsx@@ -0,0 +1,30 @@+import { isValidElement } from 'react'++import { renderDetailWithLinks } from 'lib/utils/renderDetailWithLinks'++describe('renderDetailWithLinks', () => {+ const linkedUrls = (detail: string): string[] =>+ renderDetailWithLinks(detail)+ .filter((part): part is JSX.Element => isValidElement(part))+ .map((el) => (el.props as { to: string }).to)++ it.each([+ ['links a PostHog docs URL', 'see https://posthog.com/docs/x for help', ['https://posthog.com/docs/x']],+ ['links a PostHog subdomain URL', 'visit https://eu.posthog.com/foo now', ['https://eu.posthog.com/foo']],+ [+ 'strips trailing punctuation from the href',+ 'read https://posthog.com/docs/x.',+ ['https://posthog.com/docs/x'],+ ],+ [+ 'links the production memory-limit docs URL including its fragment',+ 'see our docs for more ways to speed it up: https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries',+ ['https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries'],+ ],+ ['leaves an external URL as plain text', 'go to https://evil.example.com/phish', []],+ ['leaves a lookalike host as plain text', 'open https://posthog.com.evil.com/x here', []],+ ['renders plain detail with no links', 'This query ran out of memory.', []],+ ])('%s', (_name, detail, expected) => {+ expect(linkedUrls(detail)).toEqual(expected)+ })+})diff --git a/frontend/src/lib/utils/renderDetailWithLinks.tsx b/frontend/src/lib/utils/renderDetailWithLinks.tsxnew file mode 100644index 000000000000..18417f2f4911--- /dev/null+++ b/frontend/src/lib/utils/renderDetailWithLinks.tsx@@ -0,0 +1,21 @@+import { Link } from 'lib/lemon-ui/Link'+import { isTrustedPostHogUrl } from 'lib/utils/trustedUrl'++// Stop the capture before trailing sentence punctuation so a URL ending a sentence (".", ")") keeps+// a clean href. No `g` flag needed: split() finds all matches and interleaves the captured URLs.+const DETAIL_URL_REGEX = /(https?:\/\/[^\s]*[^\s.,;:!?)\]}'"])/++// Render embedded URLs (e.g. backend docs links) as clickable links. Only PostHog-host URLs are+// linkified — error detail can echo user-controlled text.+export function renderDetailWithLinks(detail: string): (string | JSX.Element)[] {+ // Splitting on a capturing group interleaves text and URL matches, so odd indexes are the URLs+ return detail.split(DETAIL_URL_REGEX).map((part, index) =>+ index % 2 === 1 && isTrustedPostHogUrl(part) ? (+ <Link key={index} to={part} target="_blank">+ {part}+ </Link>+ ) : (+ part+ )+ )+}diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsxindex 534c50bd443c..0c6d194a0acb 100644--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx@@ -26,7 +26,7 @@ import { LoadingBar } from 'lib/lemon-ui/LoadingBar'import posthog from 'lib/posthog-typed'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'import { humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'-import { isTrustedPostHogUrl } from 'lib/utils/trustedUrl'+import { renderDetailWithLinks } from 'lib/utils/renderDetailWithLinks'import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'import { insightLogic, insightOverridesPresent } from 'scenes/insights/insightLogic'@@ -67,10 +67,6 @@ const MEMORY_LIMIT_AI_PROMPT = autoRunMaxPrompt("This insight ran out of memory before it could finish. Help me work out why it's scanning so much data and how to fix it: a shorter date range, narrower filters, or materializing the data.")-// Stop the capture before trailing sentence punctuation so a URL ending a sentence (".", ")") keeps-// a clean href. No `g` flag needed: split() finds all matches and interleaves the captured URLs.-const DETAIL_URL_REGEX = /(https?:\/\/[^\s]*[^\s.,;:!?)\]}'"])/-export function InsightEmptyState({heading,detail,@@ -580,21 +576,6 @@ export function InsightTimeoutState({ queryId }: { queryId?: string | null }): J)}-// Render embedded URLs (e.g. backend docs links) as clickable links. Only PostHog-host URLs are-// linkified — error detail can echo user-controlled text.-export function renderDetailWithLinks(detail: string): (string | JSX.Element)[] {- // Splitting on a capturing group interleaves text and URL matches, so odd indexes are the URLs- return detail.split(DETAIL_URL_REGEX).map((part, index) =>- index % 2 === 1 && isTrustedPostHogUrl(part) ? (- <Link key={index} to={part} target="_blank">- {part}- </Link>- ) : (- part- )- )-}-/** Kind of the query that errored, unwrapping InsightVizNode/DataTableNode wrappers to the source query. */function queryKindForReporting(query: Record<string, any> | Node | null | undefined): string | null {const record = query as Record<string, any> | null | undefineddiff --git a/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsx b/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsxindex 0702d3cc047e..2e28be0c58a8 100644--- a/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsx+++ b/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsx@@ -3,7 +3,6 @@ import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'import '@testing-library/jest-dom'import { cleanup, render } from '@testing-library/react'-import { isValidElement } from 'react'import { teamLogic } from 'scenes/teamLogic'@@ -11,7 +10,7 @@ import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { TeamType } from '~/types'-import { InsightEmptyState, renderDetailWithLinks } from './EmptyStates'+import { InsightEmptyState } from './EmptyStates'describe('EmptyStates', () => {describe('<InsightEmptyState />', () => {@@ -78,33 +77,4 @@ describe('EmptyStates', () => {expect(!!container.querySelector('[data-attr="insight-empty-state"]')).toBe(!expectSampleData)})})-- describe('renderDetailWithLinks', () => {- const linkedUrls = (detail: string): string[] =>- renderDetailWithLinks(detail)- .filter((part): part is JSX.Element => isValidElement(part))- .map((el) => (el.props as { to: string }).to)-- it.each([- ['links a PostHog docs URL', 'see https://posthog.com/docs/x for help', ['https://posthog.com/docs/x']],- ['links a PostHog subdomain URL', 'visit https://eu.posthog.com/foo now', ['https://eu.posthog.com/foo']],- [- 'strips trailing punctuation from the href',- 'read https://posthog.com/docs/x.',- ['https://posthog.com/docs/x'],- ],- [- 'links the production memory-limit docs URL including its fragment',- 'see our docs for more ways to speed it up: https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries',- [- 'https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries',- ],- ],- ['leaves an external URL as plain text', 'go to https://evil.example.com/phish', []],- ['leaves a lookalike host as plain text', 'open https://posthog.com.evil.com/x here', []],- ['renders plain detail with no links', 'This query ran out of memory.', []],- ])('%s', (_name, detail, expected) => {- expect(linkedUrls(detail)).toEqual(expected)- })- })})