: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(code): hide incomplete streaming link destinations (#79142)
Adam Bowker4411235d2608
diff --git a/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.test.tsx b/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.test.tsxindex 64e2a782c45e..8ea5c010dee9 100644--- a/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.test.tsx+++ b/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.test.tsx@@ -41,4 +41,25 @@ describe("StreamingMarkdown", () => {expect(screen.getByText("All done.")).toBeInTheDocument();expect(screen.queryByLabelText("Copy code")).toBeNull();});++ it("shows a link label without exposing its incomplete destination", () => {+ renderInTheme(+ <StreamingMarkdown content="Download [the report](https://example.com/report?token=secret" />,+ );++ expect(screen.getByText("Download the report")).toBeInTheDocument();+ expect(screen.queryByText(/example\.com/)).toBeNull();+ expect(screen.queryByRole("link")).toBeNull();+ });++ it("renders the link when its destination is complete", () => {+ renderInTheme(+ <StreamingMarkdown content="Download [the report](https://example.com/report)" />,+ );++ expect(screen.getByRole("link", { name: /the report/ })).toHaveAttribute(+ "href",+ "https://example.com/report",+ );+ });});diff --git a/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.tsx b/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.tsxindex 77fff28afe37..07ea1c0d9a00 100644--- a/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.tsx+++ b/products/desktop/packages/ui/src/features/editor/components/StreamingMarkdown.tsx@@ -2,7 +2,11 @@ import { CodeBlock } from "@posthog/ui/primitives/CodeBlock";import { memo, useMemo } from "react";import type { Components } from "react-markdown";import { MarkdownRenderer } from "./MarkdownRenderer";-import { parseOpenFence, splitMarkdownBlocks } from "./splitMarkdownBlocks";+import {+ maskOpenLinkDestination,+ parseOpenFence,+ splitMarkdownBlocks,+} from "./splitMarkdownBlocks";interface StreamingMarkdownProps {content: string;@@ -52,7 +56,9 @@ export const StreamingMarkdown = memo(function StreamingMarkdown({return (<MarkdownRendererkey={key}- content={block}+ content={+ index === lastIndex ? maskOpenLinkDestination(block) : block+ }componentsOverride={componentsOverride}/>);diff --git a/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.test.ts b/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.test.tsindex 8062c566b830..3042fe61755d 100644--- a/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.test.ts+++ b/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.test.ts@@ -1,5 +1,10 @@import { describe, expect, it } from "vitest";-import { parseOpenFence, splitMarkdownBlocks } from "./splitMarkdownBlocks";+import {+ markOpenLinkDestination,+ maskOpenLinkDestination,+ parseOpenFence,+ splitMarkdownBlocks,+} from "./splitMarkdownBlocks";describe("splitMarkdownBlocks", () => {it.each([@@ -109,3 +114,110 @@ describe("parseOpenFence", () => {});});});++describe("maskOpenLinkDestination", () => {+ it("shows the label while hiding an incomplete destination", () => {+ expect(+ maskOpenLinkDestination(+ "Download [the report](https://example.com/a-very-long?token=secret",+ ),+ ).toBe("Download the report");+ });++ it("leaves a completed link unchanged", () => {+ const markdown = "Download [the report](https://example.com/report) now";+ expect(maskOpenLinkDestination(markdown)).toBe(markdown);+ });++ it("waits for nested destination parentheses to close", () => {+ expect(maskOpenLinkDestination("See [docs](https://example.com/a(b)")).toBe(+ "See docs",+ );+ });++ it("ignores link syntax inside inline code", () => {+ const markdown = "`[label](https://example.com/incomplete`";+ expect(maskOpenLinkDestination(markdown)).toBe(markdown);+ });++ it("treats an unmatched backtick as literal text", () => {+ expect(+ maskOpenLinkDestination(+ "Unmatched ` then [report](https://example.com/private",+ ),+ ).toBe("Unmatched ` then report");+ });++ it("supports nested brackets and escaped destination parentheses", () => {+ expect(+ maskOpenLinkDestination("See [the [new] docs](https://example.com/a\\("),+ ).toBe("See the [new] docs");+ });++ it("shows image alt text while hiding an incomplete destination", () => {+ expect(+ maskOpenLinkDestination("Preview: ,+ ).toBe("Preview: chart");+ });++ it("masks the destination at every streaming boundary", () => {+ const markdown =+ "Download [the report](https://example.com/report?token=secret)";+ const destinationStart = markdown.indexOf("https://");++ for (let end = destinationStart; end < markdown.length; end++) {+ const rendered = maskOpenLinkDestination(markdown.slice(0, end));+ expect(rendered).not.toContain("example.com");+ expect(rendered).not.toContain("token=secret");+ }++ expect(maskOpenLinkDestination(markdown)).toBe(markdown);+ });++ it("does not treat an escaped exclamation mark as an image marker", () => {+ expect(+ maskOpenLinkDestination("\\,+ ).toBe("\\!label");+ });++ it("handles angle-bracket destinations containing parentheses", () => {+ const complete = "[docs](<https://example.com/a(b>)";+ expect(maskOpenLinkDestination(complete)).toBe(complete);+ expect(maskOpenLinkDestination("[docs](<https://example.com/a(b>")).toBe(+ "docs",+ );+ });++ it.each([+ '[docs](https://example.com "a title")',+ "[docs](https://example.com 'a title')",+ "[docs](https://example.com (a title))",+ '[docs](<https://example.com/a(b)> "a title")',+ ])("recognizes a completed destination with a title: %s", (markdown) => {+ expect(maskOpenLinkDestination(markdown)).toBe(markdown);+ });++ it.each([+ '[docs](https://example.com "an unfinished title',+ "[docs](https://example.com (an unfinished title)",+ '[docs](<https://example.com/a(b)> "title"',+ ])("masks an incomplete destination or title: %s", (markdown) => {+ expect(maskOpenLinkDestination(markdown)).toBe("docs");+ });+});++describe("markOpenLinkDestination", () => {+ it("replaces an incomplete destination with a renderable pending link", () => {+ expect(+ markOpenLinkDestination(+ "Here is [the file](https://example.com/long",+ "#pending",+ ),+ ).toBe("Here is [the file](#pending)");+ });++ it("leaves a completed link unchanged", () => {+ const markdown = "Here is [the file](https://example.com/file)";+ expect(markOpenLinkDestination(markdown, "#pending")).toBe(markdown);+ });+});diff --git a/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.ts b/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.tsindex 8fe1971bf306..1a223b2321a1 100644--- a/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.ts+++ b/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.ts@@ -109,3 +109,162 @@ export function parseOpenFence(const code = afterMarker === -1 ? "" : block.slice(afterMarker + 1);return { before, code };}++function findClosingBacktickRun(src: string, start: number): number | null {+ let runLength = 1;+ while (src[start + runLength] === "`") runLength++;++ let cursor = start + runLength;+ while (cursor < src.length) {+ const next = src.indexOf("`", cursor);+ if (next === -1) return null;+ let closingLength = 1;+ while (src[next + closingLength] === "`") closingLength++;+ if (closingLength === runLength) return next + closingLength;+ cursor = next + closingLength;+ }+ return null;+}++function isEscaped(src: string, index: number): boolean {+ let backslashes = 0;+ while (+ index - backslashes - 1 >= 0 &&+ src[index - backslashes - 1] === "\\"+ ) {+ backslashes++;+ }+ return backslashes % 2 === 1;+}++function skipWhitespace(src: string, start: number): number {+ let cursor = start;+ while (/\s/.test(src[cursor] ?? "")) cursor++;+ return cursor;+}++function findTitleEnd(src: string, start: number): number | null {+ const closer = src[start] === "(" ? ")" : src[start];+ let cursor = start + 1;+ while (cursor < src.length) {+ if (src[cursor] === "\\") {+ cursor += 2;+ continue;+ }+ if (src[cursor] === closer) return cursor + 1;+ cursor++;+ }+ return null;+}++function findLinkDestinationEnd(src: string, start: number): number | null {+ let cursor = skipWhitespace(src, start);++ if (src[cursor] === ")") return cursor + 1;++ if (src[cursor] === "<") {+ cursor++;+ while (cursor < src.length && src[cursor] !== ">") {+ if (src[cursor] === "\\") cursor++;+ cursor++;+ }+ if (src[cursor] !== ">") return null;+ cursor++;+ } else {+ let nestedParentheses = 0;+ while (cursor < src.length) {+ if (src[cursor] === "\\") {+ cursor += 2;+ continue;+ }+ if (src[cursor] === "(") nestedParentheses++;+ if (src[cursor] === ")") {+ if (nestedParentheses === 0) return cursor + 1;+ nestedParentheses--;+ }+ if (/\s/.test(src[cursor]) && nestedParentheses === 0) break;+ cursor++;+ }+ }++ const suffixStart = cursor;+ cursor = skipWhitespace(src, cursor);+ if (src[cursor] === ")") return cursor + 1;+ if (cursor === suffixStart || !['"', "'", "("].includes(src[cursor])) {+ return null;+ }++ const titleEnd = findTitleEnd(src, cursor);+ if (titleEnd === null) return null;+ cursor = skipWhitespace(src, titleEnd);+ return src[cursor] === ")" ? cursor + 1 : null;+}++function replaceOpenLinkDestination(+ src: string,+ replacement: (label: string) => string,+): string {+ let cursor = 0;++ while (cursor < src.length) {+ if (src[cursor] === "\\") {+ cursor += 2;+ continue;+ }+ if (src[cursor] === "`") {+ cursor = findClosingBacktickRun(src, cursor) ?? cursor + 1;+ continue;+ }+ if (src[cursor] !== "[") {+ cursor++;+ continue;+ }++ const linkStart =+ cursor > 0 && src[cursor - 1] === "!" && !isEscaped(src, cursor - 1)+ ? cursor - 1+ : cursor;+ const labelStart = cursor + 1;+ let labelDepth = 1;+ cursor++;++ while (cursor < src.length && labelDepth > 0) {+ if (src[cursor] === "\\") {+ cursor += 2;+ continue;+ }+ if (src[cursor] === "`") {+ cursor = findClosingBacktickRun(src, cursor) ?? cursor + 1;+ continue;+ }+ if (src[cursor] === "[") labelDepth++;+ if (src[cursor] === "]") labelDepth--;+ cursor++;+ }++ if (labelDepth > 0 || src[cursor] !== "(") continue;++ const labelEnd = cursor - 1;+ if (findLinkDestinationEnd(src, cursor + 1) === null) {+ return (+ src.slice(0, linkStart) + replacement(src.slice(labelStart, labelEnd))+ );+ }+ }++ return src;+}++export function maskOpenLinkDestination(src: string): string {+ return replaceOpenLinkDestination(src, (label) => label);+}++export function markOpenLinkDestination(+ src: string,+ pendingDestination: string,+): string {+ return replaceOpenLinkDestination(+ src,+ (label) => `[${label}](${pendingDestination})`,+ );+}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.tsxindex bdca00379729..9e0e225c3e9f 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@@ -1,6 +1,6 @@import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vitest";-import { ChatMarkdown } from "./ChatMarkdown";+import { ChatMarkdown, ChatStreamingMarkdown } from "./ChatMarkdown";describe("ChatMarkdown", () => {it("does not load remote markdown images", () => {@@ -13,3 +13,30 @@ describe("ChatMarkdown", () => {expect(html).not.toContain("http://127.0.0.1/action");});});++describe("ChatStreamingMarkdown", () => {+ it("shows a pending link without exposing its incomplete destination", () => {+ const html = renderToStaticMarkup(+ <ChatStreamingMarkdown content="Download [the report](https://example.com/report?token=secret" />,+ );++ expect(html).toContain("Download ");+ expect(html).toContain("the report");+ expect(html).not.toContain("example.com");+ expect(html).not.toContain("token=secret");+ expect(html).not.toContain("<a");+ expect(html).toContain('aria-label="Link loading"');+ expect(html).toContain("text-primary");+ expect(html).toContain("underline");+ expect(html).toContain("animate-spin");+ });++ it("renders the link when its destination is complete", () => {+ const html = renderToStaticMarkup(+ <ChatStreamingMarkdown content="Download [the report](https://example.com/report)" />,+ );++ expect(html).toContain('href="https://example.com/report"');+ expect(html).toContain("the report");+ });+});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.tsxindex eb475ad56976..c1429bb7160c 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@@ -1,4 +1,4 @@-import { Check, Copy } from "@phosphor-icons/react";+import { Check, CircleNotch, Copy } from "@phosphor-icons/react";import {Heading,Separator,@@ -11,6 +11,7 @@ import {Text,} from "@posthog/quill";import {+ markOpenLinkDestination,parseOpenFence,splitMarkdownBlocks,} from "@posthog/ui/features/editor/components/splitMarkdownBlocks";@@ -28,6 +29,8 @@ import Markdown, { type Components } from "react-markdown";import rehypeSanitize from "rehype-sanitize";import remarkGfm from "remark-gfm";+const PENDING_LINK_DESTINATION = "#posthog-streaming-link";+function ChatCodeBlock({code,children,@@ -66,16 +69,29 @@ const components: Components = {p: ({ children }) => (<Text className="text-sm leading-[1.5]">{children}</Text>),- a: ({ children, href }) => (- <a- href={href}- target="_blank"- rel="noreferrer"- className="text-primary underline underline-offset-2"- >- {children}- </a>- ),+ a: ({ children, href }) => {+ if (href === PENDING_LINK_DESTINATION) {+ return (+ <output+ className="inline-flex items-center gap-1 text-primary underline underline-offset-2"+ aria-label="Link loading"+ >+ {children}+ <CircleNotch className="size-3 animate-spin" aria-hidden="true" />+ </output>+ );+ }+ return (+ <a+ href={href}+ target="_blank"+ rel="noreferrer"+ className="text-primary underline underline-offset-2"+ >+ {children}+ </a>+ );+ },img: ({ alt }) => (<Text className="text-muted-foreground text-sm">Remote image blocked{alt ? `: ${alt}` : ""}@@ -212,7 +228,16 @@ export const ChatStreamingMarkdown = memo(function ChatStreamingMarkdown({</div>);}- return <ChatMarkdown key={key} content={block} />;+ return (+ <ChatMarkdown+ key={key}+ content={+ index === lastIndex+ ? markOpenLinkDestination(block, PENDING_LINK_DESTINATION)+ : block+ }+ />+ );})}</div>);