: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
chore(desktop): trim the streaming markdown throttle (#99904)
Charles Vien31bdd48dff65
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 489bf55a9326..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,11 +1,9 @@import { describe, expect, it } from "vitest";import {- type MarkdownBlockSplit,markOpenLinkDestination,maskOpenLinkDestination,parseOpenFence,splitMarkdownBlocks,- splitMarkdownBlocksFrom,} from "./splitMarkdownBlocks";describe("splitMarkdownBlocks", () => {@@ -75,31 +73,6 @@ 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 16dd0afa82d9..1a223b2321a1 100644--- a/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.ts+++ b/products/desktop/packages/ui/src/features/editor/components/splitMarkdownBlocks.ts@@ -78,37 +78,6 @@ 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 1fea47fb798d..87d418889c74 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,10 +15,9 @@ 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,- splitMarkdownBlocksFrom,+ splitMarkdownBlocks,} from "@posthog/ui/features/editor/components/splitMarkdownBlocks";import {BareFileLink,@@ -42,7 +41,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, useRef } from "react";+import { memo, type ReactNode, useEffect, useMemo, useRef } from "react";import Markdown, { type Components, defaultUrlTransform } from "react-markdown";import rehypeSanitize, { defaultSchema } from "rehype-sanitize";import remarkGfm from "remark-gfm";@@ -279,43 +278,18 @@ 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 TAIL_CHARS_PER_INTERVAL_MS = 100;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],+ return Math.min(+ MAX_TAIL_PARSE_INTERVAL_MS,+ Math.max(+ MIN_TAIL_PARSE_INTERVAL_MS,+ tailLength / TAIL_CHARS_PER_INTERVAL_MS,+ ),);}@@ -333,16 +307,30 @@ export const ChatStreamingMarkdown = memo(function ChatStreamingMarkdown({content,renderObjectTags,}: ChatMarkdownProps) {- const liveSplit = useMarkdownSplit(content);- const liveTailLength = liveSplit.blocks[liveSplit.blocks.length - 1].length;+ // The throttle has to be sized before the split that measures the tail, so it reads the+ // last rendered tail instead: the interval lags by at most one interval.+ const tailLengthRef = useRef(0);const renderedContent = useThrottledValue(content,- tailParseInterval(liveTailLength),- liveTailLength > LARGE_TAIL_CHARS,+ tailParseInterval(tailLengthRef.current),+ tailLengthRef.current > LARGE_TAIL_CHARS,+ );+ const blocks = useMemo(+ () => splitMarkdownBlocks(renderedContent),+ [renderedContent],);- const { blocks } = useMarkdownSplit(renderedContent, liveSplit);const lastIndex = blocks.length - 1;- const tail = useStreamingTail(blocks[lastIndex]);+ const tailBlock = blocks[lastIndex];+ useEffect(() => {+ tailLengthRef.current = tailBlock.length;+ }, [tailBlock]);+ const tail = useMemo(+ () => ({+ openFence: parseOpenFence(tailBlock),+ linked: markOpenLinkDestination(tailBlock, PENDING_LINK_DESTINATION),+ }),+ [tailBlock],+ );return (<div className="flex flex-col gap-3 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">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 a016c5a81e92..6caa1eb3071e 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,7 +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 { useDebouncedValue } from "@posthog/ui/primitives/hooks/useDebouncedValue";import { toast } from "@posthog/ui/primitives/toast";import { useCopy } from "@posthog/ui/primitives/useCopy";import { track } from "@posthog/ui/shell/analytics";@@ -680,7 +680,10 @@ const AgentProse = memo(function AgentProse({isStreaming?: boolean;}) {const smoothed = useSmoothedText(text);- const growing = useRecentlyChanged(text, GROWING_TEXT_SETTLE_MS);+ const { isPending: growing } = useDebouncedValue(+ text,+ GROWING_TEXT_SETTLE_MS,+ );return (<MessageContextMenu value={text}>diff --git a/products/desktop/packages/ui/src/hooks/useRecentlyChanged.test.tsx b/products/desktop/packages/ui/src/hooks/useRecentlyChanged.test.tsxdeleted file mode 100644index 9e902c05cd80..000000000000--- a/products/desktop/packages/ui/src/hooks/useRecentlyChanged.test.tsx+++ /dev/null@@ -1,69 +0,0 @@-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.tsdeleted file mode 100644index a05e903d4299..000000000000--- a/products/desktop/packages/ui/src/hooks/useRecentlyChanged.ts+++ /dev/null@@ -1,28 +0,0 @@-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;-}