: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(desktop): stop re-parsing a whole streaming message per frame (#99764)
Charles Vien425cb69553e8
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 3042fe61755d..489bf55a9326 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,9 +1,11 @@import { describe, expect, it } from "vitest";import {+ type MarkdownBlockSplit,markOpenLinkDestination,maskOpenLinkDestination,parseOpenFence,splitMarkdownBlocks,+ splitMarkdownBlocksFrom,} from "./splitMarkdownBlocks";describe("splitMarkdownBlocks", () => {@@ -73,6 +75,31 @@ describe("splitMarkdownBlocks", () => {});});+describe("splitMarkdownBlocksFrom", () => {+ it.each([+ "para one\n\npara two\n\npara three",+ "a\n\n\n\nb\n\nc",+ "# Heading\n\nText with **bold**.\n\n- a\n- b\n",+ "Intro\n\n```ts\nconst x = 1;\n\nconst y = 2;\n```\n\nOutro\n\n",+ "```ts\ndone\n```\ntext\n```ts\npartial\n\nstill open",+ ])(+ "matches a full split at every prefix of a streamed message: %j",+ (message) => {+ let previous: MarkdownBlockSplit | null = null;+ for (let end = 1; end <= message.length; end++) {+ const src = message.slice(0, end);+ previous = splitMarkdownBlocksFrom(src, previous);+ expect(previous.blocks).toEqual(splitMarkdownBlocks(src));+ }+ },+ );++ it("falls back to a full split when the message is replaced", () => {+ const previous = splitMarkdownBlocksFrom("old\n\nmessage", null);+ expect(splitMarkdownBlocksFrom("new", previous).blocks).toEqual(["new"]);+ });+});+describe("parseOpenFence", () => {it("returns null when the block has no fence", () => {expect(parseOpenFence("just text\n\nmore text")).toBeNull();diff --git a/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.ts b/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.tsindex 1a223b2321a1..16dd0afa82d9 100644--- a/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.ts+++ b/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.ts@@ -78,6 +78,37 @@ export function splitMarkdownBlocks(src: string): string[] {return blocks;}+export interface MarkdownBlockSplit {+ src: string;+ blocks: string[];+}++export function splitMarkdownBlocksFrom(+ src: string,+ previous: MarkdownBlockSplit | null,+): MarkdownBlockSplit {+ if (+ !previous ||+ previous.blocks.length === 0 ||+ src.length < previous.src.length ||+ !src.startsWith(previous.src)+ ) {+ return { src, blocks: splitMarkdownBlocks(src) };+ }+ // Re-cut the stable blocks from the CURRENT source instead of carrying the old+ // strings over: a substring keeps its whole backing string alive, so reusing them+ // would pin one full copy of the message per frame that ever stabilized a block.+ const stable: string[] = [];+ let tailStart = 0;+ for (let i = 0; i < previous.blocks.length - 1; i++) {+ const end = tailStart + previous.blocks[i].length;+ stable.push(src.slice(tailStart, end));+ tailStart = end;+ }+ const tail = splitMarkdownBlocks(src.slice(tailStart));+ return { src, blocks: stable.concat(tail) };+}+/*** For a block that ends inside an unterminated code fence, split it into the* prose/markdown preceding the OPEN fence and the code accumulated so far (thediff --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 0e31285552fc..9b91aa09d13e 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@@ -15,9 +15,10 @@ import { EvidenceRefChip } from "@posthog/ui/features/editor/components/Evidenceimport { githubRefChipFor } from "@posthog/ui/features/editor/components/githubRefChipFor";import { MessageChartCard } from "@posthog/ui/features/editor/components/MessageChartCard";import {+ type MarkdownBlockSplit,markOpenLinkDestination,parseOpenFence,- splitMarkdownBlocks,+ splitMarkdownBlocksFrom,} from "@posthog/ui/features/editor/components/splitMarkdownBlocks";import {BareFileLink,@@ -25,6 +26,7 @@ import {InlineFileLink,looksLikeBareFilename,} from "@posthog/ui/features/sessions/components/session-update/fileLinkChips";+import { useThrottledValue } from "@posthog/ui/hooks/useThrottledValue";import { HighlightedCode } from "@posthog/ui/primitives/HighlightedCode";import { MermaidDiagram } from "@posthog/ui/primitives/MermaidDiagram";import { Spinner } from "@posthog/ui/primitives/Spinner";@@ -40,7 +42,7 @@ import { 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, useMemo } from "react";+import { memo, type ReactNode, useMemo, useRef } from "react";import Markdown, { type Components, defaultUrlTransform } from "react-markdown";import rehypeSanitize, { defaultSchema } from "rehype-sanitize";import remarkGfm from "remark-gfm";@@ -277,6 +279,46 @@ export const ChatMarkdown = memo(function ChatMarkdown({);});+function useMarkdownSplit(+ content: string,+ seed?: MarkdownBlockSplit,+): MarkdownBlockSplit {+ const ref = useRef<MarkdownBlockSplit | null>(null);+ if (seed && seed.src === content) {+ ref.current = seed;+ } else if (ref.current?.src !== content) {+ ref.current = splitMarkdownBlocksFrom(content, ref.current);+ }+ return ref.current;+}++const LARGE_TAIL_CHARS = 2_000;+const MIN_TAIL_PARSE_INTERVAL_MS = 100;+const MAX_TAIL_PARSE_INTERVAL_MS = 500;+const MAX_INTERVAL_TAIL_CHARS = 50_000;++function tailParseInterval(tailLength: number): number {+ const span = MAX_INTERVAL_TAIL_CHARS - LARGE_TAIL_CHARS;+ const progress = Math.min(+ 1,+ Math.max(0, tailLength - LARGE_TAIL_CHARS) / span,+ );+ return (+ MIN_TAIL_PARSE_INTERVAL_MS ++ progress * (MAX_TAIL_PARSE_INTERVAL_MS - MIN_TAIL_PARSE_INTERVAL_MS)+ );+}++function useStreamingTail(block: string) {+ return useMemo(+ () => ({+ openFence: parseOpenFence(block),+ linked: markOpenLinkDestination(block, PENDING_LINK_DESTINATION),+ }),+ [block],+ );+}+/*** Streaming variant of {@link ChatMarkdown}: splits the message into top-level blocks so completed* blocks keep a stable string and their memoized parse is reused — each streamed frame re-parses@@ -291,25 +333,41 @@ export const ChatStreamingMarkdown = memo(function ChatStreamingMarkdown({content,renderObjectTags,}: ChatMarkdownProps) {- const blocks = useMemo(() => splitMarkdownBlocks(content), [content]);+ const liveSplit = useMarkdownSplit(content);+ const liveTailLength = liveSplit.blocks[liveSplit.blocks.length - 1].length;+ const renderedContent = useThrottledValue(+ content,+ tailParseInterval(liveTailLength),+ liveTailLength > LARGE_TAIL_CHARS,+ );+ const { blocks } = useMarkdownSplit(renderedContent, liveSplit);const lastIndex = blocks.length - 1;+ const tail = useStreamingTail(blocks[lastIndex]);return (<div className="flex flex-col gap-3 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">{blocks.map((block, index) => {const key = `b${index}`;- const openFence = index === lastIndex ? parseOpenFence(block) : null;- if (openFence) {+ if (index !== lastIndex) {+ return (+ <ChatMarkdown+ key={key}+ content={block}+ renderObjectTags={renderObjectTags}+ />+ );+ }+ if (tail.openFence) {return (<div key={key} className="flex flex-col gap-3">- {openFence.before.trim() ? (+ {tail.openFence.before.trim() ? (<ChatMarkdown- content={openFence.before}+ content={tail.openFence.before}renderObjectTags={renderObjectTags}/>) : null}- <ChatCodeBlock code={openFence.code}>- <code className="font-mono text-xs">{openFence.code}</code>+ <ChatCodeBlock code={tail.openFence.code}>+ <code className="font-mono text-xs">{tail.openFence.code}</code></ChatCodeBlock></div>);@@ -317,11 +375,7 @@ export const ChatStreamingMarkdown = memo(function ChatStreamingMarkdown({return (<ChatMarkdownkey={key}- content={- index === lastIndex- ? markOpenLinkDestination(block, PENDING_LINK_DESTINATION)- : block- }+ content={tail.linked}renderObjectTags={renderObjectTags}/>);diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsxindex 06a46131885d..a016c5a81e92 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx@@ -129,6 +129,7 @@ import {import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { TIP_KEYS } from "@posthog/ui/features/settings/tipKeys";import { SkillButtonActionMessage } from "@posthog/ui/features/skill-buttons/components/SkillButtonActionMessage";+import { useRecentlyChanged } from "@posthog/ui/hooks/useRecentlyChanged";import { toast } from "@posthog/ui/primitives/toast";import { useCopy } from "@posthog/ui/primitives/useCopy";import { track } from "@posthog/ui/shell/analytics";@@ -660,6 +661,8 @@ function MessageContextMenu({);}+const GROWING_TEXT_SETTLE_MS = 500;+/*** Start-aligned assistant prose bubble. Streamed tokens arrive in bursts; `useSmoothedText` reveals* them at a steady character rate so the text reads as even typing (text present on mount shows@@ -677,6 +680,7 @@ const AgentProse = memo(function AgentProse({isStreaming?: boolean;}) {const smoothed = useSmoothedText(text);+ const growing = useRecentlyChanged(text, GROWING_TEXT_SETTLE_MS);return (<MessageContextMenu value={text}>@@ -684,7 +688,7 @@ const AgentProse = memo(function AgentProse({<ChatMessageContent className="gap-1"><ChatBubble variant="ghost"><ChatBubbleContent>- {isStreaming ? (+ {isStreaming || growing ? (<ChatStreamingMarkdown content={smoothed} renderObjectTags />) : (<ChatMarkdown content={text} renderObjectTags />diff --git a/products/desktop/packages/ui/src/hooks/useRecentlyChanged.test.tsx b/products/desktop/packages/ui/src/hooks/useRecentlyChanged.test.tsxnew file mode 100644index 000000000000..9e902c05cd80--- /dev/null+++ b/products/desktop/packages/ui/src/hooks/useRecentlyChanged.test.tsx@@ -0,0 +1,69 @@+import { act, render, renderHook } from "@testing-library/react";+import { StrictMode, useLayoutEffect } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useRecentlyChanged } from "./useRecentlyChanged";++describe("useRecentlyChanged", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("starts settled, reports changes, and settles again once the value holds still", () => {+ const { result, rerender } = renderHook(+ ({ value }) => useRecentlyChanged(value, 500),+ { initialProps: { value: "finished message" } },+ );+ expect(result.current).toBe(false);++ rerender({ value: "finished message plus" });+ expect(result.current).toBe(true);++ act(() => vi.advanceTimersByTime(400));+ rerender({ value: "finished message plus more" });+ act(() => vi.advanceTimersByTime(400));+ expect(result.current).toBe(true);++ act(() => vi.advanceTimersByTime(100));+ expect(result.current).toBe(false);+ });++ it("reports the change in the commit that first renders the new value", () => {+ const committed: boolean[] = [];+ function Probe({ value }: { value: string }) {+ const changing = useRecentlyChanged(value, 500);+ useLayoutEffect(() => {+ committed.push(changing);+ });+ return null;+ }++ const { rerender } = render(<Probe value="finished message" />);+ rerender(<Probe value="finished message plus" />);++ expect(committed).toEqual([false, true]);+ });++ it("stays settled on mount under StrictMode", () => {+ const committed: boolean[] = [];+ function Probe({ value }: { value: string }) {+ const changing = useRecentlyChanged(value, 500);+ useLayoutEffect(() => {+ committed.push(changing);+ });+ return null;+ }++ render(+ <StrictMode>+ <Probe value="finished message" />+ </StrictMode>,+ );+ act(() => vi.advanceTimersByTime(500));++ expect(committed.some(Boolean)).toBe(false);+ });+});diff --git a/products/desktop/packages/ui/src/hooks/useRecentlyChanged.ts b/products/desktop/packages/ui/src/hooks/useRecentlyChanged.tsnew file mode 100644index 000000000000..a05e903d4299--- /dev/null+++ b/products/desktop/packages/ui/src/hooks/useRecentlyChanged.ts@@ -0,0 +1,28 @@+import { useEffect, useState } from "react";++/**+ * True from the first render that sees a new `value` until the value holds still for+ * `settleMs`. The change is detected during render, not in an effect, so a caller can+ * switch how it renders in the same commit the new value arrives in.+ */+export function useRecentlyChanged<T>(value: T, settleMs: number): boolean {+ const [seen, setSeen] = useState<{ value: T; changing: boolean }>({+ value,+ changing: false,+ });++ if (!Object.is(seen.value, value)) {+ setSeen({ value, changing: true });+ }++ useEffect(() => {+ if (!seen.changing) return;+ const timer = setTimeout(+ () => setSeen((current) => ({ ...current, changing: false })),+ settleMs,+ );+ return () => clearTimeout(timer);+ }, [seen, settleMs]);++ return seen.changing;+}diff --git a/products/desktop/packages/ui/src/hooks/useThrottledValue.test.ts b/products/desktop/packages/ui/src/hooks/useThrottledValue.test.tsnew file mode 100644index 000000000000..e9ec66cf532b--- /dev/null+++ b/products/desktop/packages/ui/src/hooks/useThrottledValue.test.ts@@ -0,0 +1,48 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useThrottledValue } from "./useThrottledValue";++describe("useThrottledValue", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("collapses a burst into the last value and lands it when the interval ends", () => {+ const { result, rerender } = renderHook(+ ({ value }) => useThrottledValue(value, 100),+ { initialProps: { value: "a" } },+ );+ expect(result.current).toBe("a");++ act(() => vi.advanceTimersByTime(10));+ rerender({ value: "ab" });+ rerender({ value: "abc" });+ expect(result.current).toBe("a");++ act(() => vi.advanceTimersByTime(100));+ expect(result.current).toBe("abc");+ });++ it("passes the live value through while disabled and until the next emission after re-enabling", () => {+ const { result, rerender } = renderHook(+ ({ value, enabled }) => useThrottledValue(value, 100, enabled),+ { initialProps: { value: "a", enabled: true } },+ );++ act(() => vi.advanceTimersByTime(10));+ rerender({ value: "ab", enabled: false });+ expect(result.current).toBe("ab");++ rerender({ value: "abc", enabled: true });+ expect(result.current).toBe("abc");+ rerender({ value: "abcd", enabled: true });+ expect(result.current).toBe("abcd");++ act(() => vi.advanceTimersByTime(100));+ expect(result.current).toBe("abcd");+ });+});diff --git a/products/desktop/packages/ui/src/hooks/useThrottledValue.ts b/products/desktop/packages/ui/src/hooks/useThrottledValue.tsnew file mode 100644index 000000000000..e9938200518c--- /dev/null+++ b/products/desktop/packages/ui/src/hooks/useThrottledValue.ts@@ -0,0 +1,37 @@+import { useEffect, useRef, useState } from "react";++/**+ * Emit `value` at most once every `intervalMs` while `enabled`. While disabled the live+ * value passes straight through, and it keeps passing through after re-enabling until the+ * next emission lands, so the returned value never moves backwards.+ */+export function useThrottledValue<T>(+ value: T,+ intervalMs: number,+ enabled = true,+): T {+ const [throttled, setThrottled] = useState(value);+ const lastEmittedAtRef = useRef(0);+ const staleRef = useRef(false);++ useEffect(() => {+ if (!enabled) {+ staleRef.current = true;+ return;+ }+ const emit = (): void => {+ lastEmittedAtRef.current = Date.now();+ staleRef.current = false;+ setThrottled(value);+ };+ const elapsed = Date.now() - lastEmittedAtRef.current;+ if (elapsed >= intervalMs) {+ emit();+ return;+ }+ const timer = setTimeout(emit, intervalMs - elapsed);+ return () => clearTimeout(timer);+ }, [value, intervalMs, enabled]);++ return enabled && !staleRef.current ? throttled : value;+}