Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(chat): smooth, reading-pace streaming with word fade-in (#18491)

Vasco Schiavob34ac59e691d
diff --git a/__tests__/components/conversation-events/chat/messages-markdown-render-stability.test.tsx b/__tests__/components/conversation-events/chat/messages-markdown-render-stability.test.tsx
index f258234c41..50963d65f0 100644
--- a/__tests__/components/conversation-events/chat/messages-markdown-render-stability.test.tsx
+++ b/__tests__/components/conversation-events/chat/messages-markdown-render-stability.test.tsx
@@ -105,7 +105,10 @@ describe("Messages markdown render stability", () => {
);
}
- expect(screen.getByText("Live update 5")).toBeInTheDocument();
+ // Streamed words are separate spans, so match the bubble's text.
+ expect(screen.getAllByTestId("agent-message").at(-1)).toHaveTextContent(
+ "Live update 5",
+ );
expect(recordSyntaxHighlight).not.toHaveBeenCalled();
});
});
diff --git a/__tests__/components/conversation-events/chat/messages-model-messages.test.tsx b/__tests__/components/conversation-events/chat/messages-model-messages.test.tsx
index dd9e450046..5c19d3aa26 100644
--- a/__tests__/components/conversation-events/chat/messages-model-messages.test.tsx
+++ b/__tests__/components/conversation-events/chat/messages-model-messages.test.tsx
@@ -1,4 +1,4 @@
-import { screen } from "@testing-library/react";
+import { screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import { renderWithProviders } from "test-utils";
import { Messages } from "#/components/conversation-events/chat/messages";
@@ -74,7 +74,12 @@ describe("Messages model entries", () => {
rerender(<Messages messages={[mergedDelta]} allEvents={[mergedDelta]} />);
- // Revealed on a clock (#15493), so the added text lands over a frame or two.
- expect(await screen.findByText("First second third")).toBeInTheDocument();
+ // Revealed on a clock (#15493), so the added text lands over a few frames.
+ // Streamed words are separate spans, so match the bubble's text.
+ await waitFor(() =>
+ expect(screen.getByTestId("agent-message")).toHaveTextContent(
+ "First second third",
+ ),
+ );
});
});
diff --git a/__tests__/components/conversation-events/chat/streamed-reply-handoff.test.tsx b/__tests__/components/conversation-events/chat/streamed-reply-handoff.test.tsx
new file mode 100644
index 0000000000..9ef9a09656
--- /dev/null
+++ b/__tests__/components/conversation-events/chat/streamed-reply-handoff.test.tsx
@@ -0,0 +1,88 @@
+import { act, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { renderWithProviders } from "test-utils";
+import { Messages } from "#/components/conversation-events/chat/messages";
+import { MessageEvent } from "#/types/agent-server/core";
+import { StreamingDeltaEvent } from "#/types/agent-server/core/events/streaming-delta-event";
+
+const slot = (content: string): StreamingDeltaEvent => ({
+ id: "item-1",
+ timestamp: "2026-06-12T12:00:00Z",
+ source: "agent",
+ kind: "StreamingDeltaEvent",
+ content,
+ reasoning_content: null,
+});
+
+// The durable message carries the slot's id and replaces it in place.
+const finished = (text: string): MessageEvent => ({
+ id: "item-1",
+ timestamp: "2026-06-12T12:00:00Z",
+ source: "agent",
+ llm_message: { role: "assistant", content: [{ type: "text", text }] },
+ activated_skills: [],
+ extended_content: [],
+});
+
+describe("a streamed reply finishing", () => {
+ let now = 0;
+ let callbacks: Map<number, FrameRequestCallback>;
+ const tick = (count: number) => {
+ for (let i = 0; i < count; i += 1) {
+ now += 16;
+ const scheduled = [...callbacks.values()];
+ callbacks.clear();
+ act(() => scheduled.forEach((callback) => callback(now)));
+ }
+ };
+
+ beforeEach(() => {
+ now = 0;
+ callbacks = new Map();
+ let nextHandle = 1;
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
+ const handle = nextHandle;
+ nextHandle += 1;
+ callbacks.set(handle, callback);
+ return handle;
+ });
+ vi.stubGlobal("cancelAnimationFrame", (handle: number) => {
+ callbacks.delete(handle);
+ });
+ vi.spyOn(performance, "now").mockImplementation(() => now);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it("keeps revealing where the slot left off instead of jumping", () => {
+ const text = `Hello${" world".repeat(30)}`;
+ const { rerender } = renderWithProviders(
+ <Messages messages={[slot("Hello")]} allEvents={[slot("Hello")]} />,
+ );
+
+ rerender(
+ <Messages messages={[finished(text)]} allEvents={[finished(text)]} />,
+ );
+ tick(10);
+ const bubble = () => screen.getByTestId("agent-message");
+ const shown = bubble().textContent ?? "";
+ expect(shown).toContain("Hello world");
+ expect(shown).not.toContain(text);
+
+ // ~185 characters at the reveal pace, then the finished message renders.
+ tick(240);
+ expect(bubble()).toHaveTextContent(text);
+ expect(bubble().querySelector("[data-stream-word]")).toBeNull();
+ });
+
+ it("shows a message that was never streamed at once", () => {
+ const text = `Hello${" world".repeat(30)}`;
+ renderWithProviders(
+ <Messages messages={[finished(text)]} allEvents={[finished(text)]} />,
+ );
+ expect(screen.getByTestId("agent-message")).toHaveTextContent(text);
+ });
+});
diff --git a/__tests__/components/features/markdown/markdown-renderer-streaming.test.tsx b/__tests__/components/features/markdown/markdown-renderer-streaming.test.tsx
new file mode 100644
index 0000000000..ab72030bc7
--- /dev/null
+++ b/__tests__/components/features/markdown/markdown-renderer-streaming.test.tsx
@@ -0,0 +1,127 @@
+import React from "react";
+import { render } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { MarkdownRenderer } from "#/components/features/markdown/markdown-renderer";
+
+describe("MarkdownRenderer while streaming", () => {
+ const reply = [
+ "Here is the **plan**:",
+ "",
+ "1. Read the file",
+ "",
+ "2. Fix the bug",
+ "",
+ "Then:",
+ "",
+ "- tight",
+ "- list",
+ "",
+ "- turns loose",
+ "",
+ " indented code",
+ "",
+ " continues",
+ "",
+ "| a | b |",
+ "| - | - |",
+ "| 1 | 2 |",
+ "",
+ "```ts",
+ "const x = 1;",
+ "",
+ "const y = 2;",
+ "```",
+ "",
+ "<details>",
+ "",
+ "Hidden",
+ "",
+ "</details>",
+ "",
+ "> [!NOTE]",
+ "> Done.",
+ ].join("\n");
+
+ /**
+ * React updating a node in place can leave an emptied `style=""`, split
+ * text nodes, or a different attribute order than a fresh render; none of
+ * it changes what is shown, so compare DOM equality (attribute
+ * order-insensitive) with those normalized away. The per-word fade spans
+ * exist only while streaming, so they are unwrapped too.
+ */
+ const rendersSame = (actual: Element, expected: Element) => {
+ const normalized = (element: Element) => {
+ const clone = element.cloneNode(true) as Element;
+ clone
+ .querySelectorAll("[data-stream-word]")
+ .forEach((span) => span.replaceWith(...span.childNodes));
+ clone
+ .querySelectorAll('[style=""]')
+ .forEach((node) => node.removeAttribute("style"));
+ clone.normalize();
+ return clone;
+ };
+ return normalized(actual).isEqualNode(normalized(expected));
+ };
+
+ it("renders every prefix as the finished message would", () => {
+ const streamed = render(
+ <MarkdownRenderer includeStandard includeHeadings streaming>
+ {""}
+ </MarkdownRenderer>,
+ );
+
+ for (let end = 1; end <= reply.length; end += 1) {
+ const prefix = reply.slice(0, end);
+ streamed.rerender(
+ <MarkdownRenderer includeStandard includeHeadings streaming>
+ {prefix}
+ </MarkdownRenderer>,
+ );
+ const whole = render(
+ <MarkdownRenderer includeStandard includeHeadings>
+ {prefix}
+ </MarkdownRenderer>,
+ );
+ expect(
+ rendersSame(streamed.container, whole.container),
+ `prefix of ${end}:\n${streamed.container.innerHTML}\n---\n${whole.container.innerHTML}`,
+ ).toBe(true);
+ whole.unmount();
+ }
+ });
+
+ it("does not re-render blocks that are already finished", () => {
+ let paragraphRenders = 0;
+ function CountingParagraph({ children }: { children?: React.ReactNode }) {
+ paragraphRenders += 1;
+ return <p>{children}</p>;
+ }
+ const components = { p: CountingParagraph };
+
+ const { rerender } = render(
+ <MarkdownRenderer components={components} streaming>
+ {"First.\n\nSecond.\n\nThird.\n\nFou"}
+ </MarkdownRenderer>,
+ );
+ paragraphRenders = 0;
+
+ rerender(
+ <MarkdownRenderer components={components} streaming>
+ {"First.\n\nSecond.\n\nThird.\n\nFourth is longer"}
+ </MarkdownRenderer>,
+ );
+ // "First." and "Second." are frozen; only the tail is rendered again.
+ expect(paragraphRenders).toBe(2);
+ });
+
+ it("starts over when the text is replaced by a retry", () => {
+ const { container, rerender } = render(
+ <MarkdownRenderer streaming>
+ {"Old one.\n\nOld two.\n\nOld"}
+ </MarkdownRenderer>,
+ );
+ rerender(<MarkdownRenderer streaming>{"New"}</MarkdownRenderer>);
+ expect(container.textContent).toBe("New");
+ });
+});
diff --git a/__tests__/components/features/markdown/rehype-fade-in-words.test.tsx b/__tests__/components/features/markdown/rehype-fade-in-words.test.tsx
new file mode 100644
index 0000000000..740cb31772
--- /dev/null
+++ b/__tests__/components/features/markdown/rehype-fade-in-words.test.tsx
@@ -0,0 +1,96 @@
+import React from "react";
+import { render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { MarkdownRenderer } from "#/components/features/markdown/markdown-renderer";
+import {
+ RevealClock,
+ STREAM_WORD_FADE_MS,
+} from "#/components/features/markdown/rehype-fade-in-words";
+
+describe("RevealClock", () => {
+ it("reports when each part was revealed until its fade is over", () => {
+ const clock = new RevealClock();
+ clock.advance(5, 0);
+ clock.advance(9, 100);
+
+ expect(clock.revealedAt(2)).toBe(0);
+ expect(clock.revealedAt(7)).toBe(100);
+
+ clock.advance(12, STREAM_WORD_FADE_MS + 50);
+ // The first part has settled; later parts still have a time.
+ expect(clock.revealedAt(2)).toBeNull();
+ expect(clock.revealedAt(7)).toBe(100);
+ });
+
+ it("treats text as shown after a reset", () => {
+ const clock = new RevealClock();
+ clock.advance(5, 0);
+ clock.reset(20);
+ expect(clock.revealedAt(10)).toBeNull();
+ });
+});
+
+describe("streamed words fading in", () => {
+ let now = 0;
+
+ beforeEach(() => {
+ now = 0;
+ vi.spyOn(performance, "now").mockImplementation(() => now);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ const word = (container: HTMLElement, text: string) =>
+ [...container.querySelectorAll<HTMLElement>("[data-stream-word]")].find(
+ (span) => span.textContent === text,
+ );
+
+ it("fades in new words and leaves settled ones alone", () => {
+ const { container, rerender } = render(
+ <MarkdownRenderer streaming>{"Hello"}</MarkdownRenderer>,
+ );
+ expect(word(container, "Hello")).toHaveClass("stream-word-fade");
+
+ now = 1000;
+ rerender(<MarkdownRenderer streaming>{"Hello world"}</MarkdownRenderer>);
+ expect(word(container, "Hello")).not.toHaveClass("stream-word-fade");
+ expect(word(container, "world")).toHaveClass("stream-word-fade");
+ expect(word(container, "world")?.style.animationDelay).toBe("0ms");
+ });
+
+ it("resumes a word's fade when its block is re-created", () => {
+ const { container, rerender } = render(
+ <MarkdownRenderer streaming>{"One.\n\nTwo.\n\nThr"}</MarkdownRenderer>,
+ );
+
+ // "Two." freezes, so the tail holding "Three." is a new block.
+ now = 100;
+ rerender(
+ <MarkdownRenderer streaming>
+ {"One.\n\nTwo.\n\nThree.\n\nFou"}
+ </MarkdownRenderer>,
+ );
+
+ // Revealed (as "Thr") 100ms ago: it continues, not restarts, its fade.
+ expect(word(container, "Three.")?.style.animationDelay).toBe("-100ms");
+ });
+
+ it("does not split code", () => {
+ const { container } = render(
+ <MarkdownRenderer streaming>
+ {"Run `npm test` now\n\n```sh\nnpm run build\n```"}
+ </MarkdownRenderer>,
+ );
+ expect(word(container, "Run")).toBeDefined();
+ expect(container.querySelector("code [data-stream-word]")).toBeNull();
+ });
+
+ it("adds nothing to a finished message", () => {
+ const { container } = render(
+ <MarkdownRenderer>{"Hello world"}</MarkdownRenderer>,
+ );
+ expect(container.querySelector("[data-stream-word]")).toBeNull();
+ });
+});
diff --git a/__tests__/hooks/use-scroll-to-bottom.test.ts b/__tests__/hooks/use-scroll-to-bottom.test.ts
index e3d30f0ba0..2f7d30b33a 100644
--- a/__tests__/hooks/use-scroll-to-bottom.test.ts
+++ b/__tests__/hooks/use-scroll-to-bottom.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
+import { afterEach, describe, expect, it, vi, beforeEach } from "vitest";
import { renderHook, act } from "@testing-library/react";
import { useScrollToBottom } from "#/hooks/use-scroll-to-bottom";
import type { RefObject } from "react";
@@ -123,4 +123,98 @@ describe("useScrollToBottom", () => {
expect(result.current.autoScroll).toBe(true);
});
});
+ describe("following content that grows in place", () => {
+ let frames: Map<number, FrameRequestCallback>;
+ const tick = () => {
+ const scheduled = [...frames.values()];
+ frames.clear();
+ act(() => scheduled.forEach((callback) => callback(0)));
+ };
+
+ beforeEach(() => {
+ frames = new Map();
+ let nextHandle = 1;
+ vi.stubGlobal(
+ "requestAnimationFrame",
+ (callback: FrameRequestCallback) => {
+ const handle = nextHandle;
+ nextHandle += 1;
+ frames.set(handle, callback);
+ return handle;
+ },
+ );
+ vi.stubGlobal("cancelAnimationFrame", (handle: number) => {
+ frames.delete(handle);
+ });
+ // Pinned to the bottom: 1000 - 500.
+ mock.state.scrollTop = 500;
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("keeps the bottom in view as the content grows", () => {
+ renderHook(() => useScrollToBottom(ref, true));
+
+ mock.state.scrollHeight = 1100;
+ tick();
+ expect(mock.state.scrollTop).toBe(600);
+ });
+
+ it("stops following as soon as the user scrolls up", () => {
+ const { result } = renderHook(() => useScrollToBottom(ref, true));
+ tick();
+
+ // The user scrolls up before React has re-rendered with autoScroll off.
+ mock.state.scrollTop = 300;
+ mock.state.scrollHeight = 1100;
+ tick();
+ expect(mock.state.scrollTop).toBe(300);
+ expect(result.current.autoScroll).toBe(false);
+
+ mock.state.scrollHeight = 1200;
+ tick();
+ expect(mock.state.scrollTop).toBe(300);
+ });
+
+ it("does not mistake the content shrinking for the user scrolling up", () => {
+ const { result } = renderHook(() => useScrollToBottom(ref, true));
+ tick();
+
+ // The browser clamps scrollTop when the content gets shorter.
+ mock.state.scrollHeight = 950;
+ mock.state.scrollTop = 450;
+ tick();
+ mock.state.scrollHeight = 1050;
+ tick();
+
+ expect(result.current.autoScroll).toBe(true);
+ expect(mock.state.scrollTop).toBe(550);
+ });
+
+ it("leaves the scroll position alone when the user is not pinned", () => {
+ const { result } = renderHook(() => useScrollToBottom(ref, true));
+ act(() => result.current.setAutoScroll(false));
+ mock.state.scrollTop = 100;
+
+ mock.state.scrollHeight = 1100;
+ tick();
+ expect(mock.state.scrollTop).toBe(100);
+ });
+
+ it("only runs while content is growing", () => {
+ const { rerender } = renderHook(
+ ({ follow }) => useScrollToBottom(ref, follow),
+ { initialProps: { follow: false } },
+ );
+ expect(frames.size).toBe(0);
+
+ rerender({ follow: true });
+ expect(frames.size).toBe(1);
+
+ rerender({ follow: false });
+ expect(frames.size).toBe(0);
+ });
+ });
});
diff --git a/__tests__/hooks/use-streamed-text.test.tsx b/__tests__/hooks/use-streamed-text.test.tsx
index 3560215e78..7f675f0e54 100644
--- a/__tests__/hooks/use-streamed-text.test.tsx
+++ b/__tests__/hooks/use-streamed-text.test.tsx
@@ -1,6 +1,9 @@
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { act, renderHook } from "@testing-library/react";
-import { useStreamedText } from "#/hooks/use-streamed-text";
+import {
+ useIsRevealingStreamedText,
+ useStreamedText,
+} from "#/hooks/use-streamed-text";
/** Drive `requestAnimationFrame` by hand so the reveal cadence is explicit. */
function manualFrames() {
@@ -17,6 +20,8 @@ function manualFrames() {
vi.stubGlobal("cancelAnimationFrame", (handle: number) => {
callbacks.delete(handle);
});
+ // Arrivals are timed with `performance.now()`; keep it on the same clock.
+ vi.spyOn(performance, "now").mockImplementation(() => now);
return {
/** Advance one 16ms frame. */
@@ -43,6 +48,7 @@ describe("useStreamedText", () => {
afterEach(() => {
vi.unstubAllGlobals();
+ vi.restoreAllMocks();
});
it("shows the initial text immediately", () => {
@@ -60,16 +66,83 @@ describe("useStreamedText", () => {
// Not committed on arrival β€” the clock has not ticked yet.
expect(result.current).toBe("Hi");
- frames.tick();
+ // Under one character per frame at this pace, so give it a few.
+ frames.tick(3);
expect(result.current.length).toBeGreaterThan("Hi".length);
expect(result.current.length).toBeLessThan(202);
- // It still catches up: the backlog drains within a short window.
- frames.tick(40);
+ // At ~60 chars/s, 200 characters take about 3.3s rather than one burst.
+ frames.tick(60);
+ expect(result.current.length).toBeLessThan(100);
+ frames.tick(160);
expect(result.current).toBe(`Hi${"x".repeat(200)}`);
expect(frames.pending()).toBe(0);
});
+ it("reveals bursty chunks at a steady pace", () => {
+ // ~55 chars/s: one 12-char burst every 13 frames.
+ const chunk = "x".repeat(12);
+ const framesPerChunk = 13;
+ const { result, rerender } = renderHook(
+ ({ text }) => useStreamedText(text),
+ { initialProps: { text: "" } },
+ );
+
+ const halves: number[] = [];
+ for (let i = 1; i <= 8; i += 1) {
+ rerender({ text: chunk.repeat(i) });
+ // Compare the first and second half of each gap between bursts.
+ for (const frameCount of [6, framesPerChunk - 6]) {
+ const before = result.current.length;
+ frames.tick(frameCount);
+ halves.push((result.current.length - before) / frameCount);
+ }
+ }
+
+ // Each burst is spread across the gap until the next one rather than
+ // revealed up front and followed by a pause.
+ expect(Math.min(...halves)).toBeGreaterThan(0.5);
+ expect(Math.max(...halves)).toBeLessThan(1.5);
+ });
+
+ it("caps the pace for a fast model but never trails it far", () => {
+ const { result, rerender } = renderHook(
+ ({ text }) => useStreamedText(text),
+ { initialProps: { text: "" } },
+ );
+ // A model streaming ~600 chars/s, one 10-char chunk per frame.
+ let length = 0;
+ const stream = (frameCount: number) => {
+ for (let f = 0; f < frameCount; f += 1) {
+ length += 10;
+ rerender({ text: "x".repeat(length) });
+ frames.tick();
+ }
+ };
+
+ stream(62); // ~1s
+ // Revealed at a reading pace, not at the model's 600 chars/s.
+ expect(result.current.length).toBeLessThan(100);
+
+ stream(1180); // ~20s in total
+ // Past ~10s of backlog it speeds up, so it never trails further.
+ expect(length - result.current.length).toBeLessThan(600 * 10);
+ });
+
+ it("reports while text is still being revealed", () => {
+ const revealing = renderHook(() => useIsRevealingStreamedText());
+ const { rerender } = renderHook(({ text }) => useStreamedText(text), {
+ initialProps: { text: "Hi" },
+ });
+ expect(revealing.result.current).toBe(false);
+
+ rerender({ text: `Hi${"x".repeat(40)}` });
+ expect(revealing.result.current).toBe(true);
+
+ frames.tick(60);
+ expect(revealing.result.current).toBe(false);
+ });
+
it("snaps when the text is not an extension of what is shown", () => {
const { result, rerender } = renderHook(
({ text }) => useStreamedText(text),
diff --git a/__tests__/utils/split-stable-markdown.test.ts b/__tests__/utils/split-stable-markdown.test.ts
new file mode 100644
index 0000000000..dffb155def
--- /dev/null
+++ b/__tests__/utils/split-stable-markdown.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vitest";
+import { advanceStableMarkdownBoundary } from "#/utils/split-stable-markdown";
+
+const tailAfter = (text: string, from = 0) =>
+ text.slice(advanceStableMarkdownBoundary(text, from));
+
+describe("advanceStableMarkdownBoundary", () => {
+ it("keeps everything in the tail while there is a single block", () => {
+ expect(tailAfter("Just one paragraph")).toBe("Just one paragraph");
+ });
+
+ it("freezes a block once the block after it is complete", () => {
+ expect(tailAfter("First.\n\nSecond.\n\nStill typ")).toBe(
+ "Second.\n\nStill typ",
+ );
+ });
+
+ it("does not freeze a block while the next one may still merge into it", () => {
+ // `2` becomes the list's second item once the `.` arrives.
+ expect(tailAfter("1. Read the file\n\n2")).toBe("1. Read the file\n\n2");
+ });
+
+ it("only parses after `from`, resolving offsets against the full text", () => {
+ const text = "One.\n\nTwo.\n\nThree.\n\nFour";
+ const first = advanceStableMarkdownBoundary("One.\n\nTwo.\n\nTh", 0);
+ expect(first).toBe("One.\n\n".length);
+ expect(tailAfter(text, first)).toBe("Three.\n\nFour");
+ });
+
+ it("does not split blocks that are not separated by a blank line", () => {
+ expect(tailAfter("# Title\nBody text\n\nMore\n\nEven more")).toBe(
+ "# Title\nBody text\n\nMore\n\nEven more",
+ );
+ });
+
+ it("keeps a loose list together across its blank lines", () => {
+ expect(tailAfter("- one\n\n- two\n\n- thr")).toBe(
+ "- one\n\n- two\n\n- thr",
+ );
+ });
+
+ it("keeps an unclosed code fence together across blank lines", () => {
+ const text = "Intro.\n\nMore.\n\n```ts\nconst a = 1;\n\nconst b = 2;\n";
+ expect(tailAfter(text)).toBe(
+ "More.\n\n```ts\nconst a = 1;\n\nconst b = 2;\n",
+ );
+ });
+
+ it("stops before raw HTML, which can span blank lines", () => {
+ const text = "Intro.\n\n<details>\n\nInside.\n\n</details>\n\nAfter";
+ expect(tailAfter(text)).toBe("<details>\n\nInside.\n\n</details>\n\nAfter");
+ });
+
+ it("stops before a link definition, which resolves other references", () => {
+ const text = "See [docs].\n\n[docs]: https://example.com\n\nMore [docs]";
+ expect(tailAfter(text)).toBe("[docs]: https://example.com\n\nMore [docs]");
+ });
+});
diff --git a/package-lock.json b/package-lock.json
index ab8e1ea1d4..2792e2e9c9 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -35,6 +35,7 @@
"i18next-http-backend": "4.0.2",
"isbot": "5.2.1",
"lucide-react": "1.25.0",
+ "mdast-util-from-markdown": "2.0.3",
"monaco-editor": "0.56.0",
"posthog-js": "1.415.0",
"react": "19.3.0",
diff --git a/package.json b/package.json
index e1df39d5b7..0bf4dca072 100644
--- a/package.json
+++ b/package.json
@@ -45,6 +45,7 @@
"i18next-http-backend": "4.0.2",
"isbot": "5.2.1",
"lucide-react": "1.25.0",
+ "mdast-util-from-markdown": "2.0.3",
"monaco-editor": "0.56.0",
"posthog-js": "1.415.0",
"react": "19.3.0",
diff --git a/src/components/conversation-events/chat/event-message.tsx b/src/components/conversation-events/chat/event-message.tsx
index fbd3ca44ba..1e215fb3ba 100644
--- a/src/components/conversation-events/chat/event-message.tsx
+++ b/src/components/conversation-events/chat/event-message.tsx
@@ -20,6 +20,7 @@ import {
isStreamingDeltaEvent,
isConversationStateUpdateEvent,
isGoalConversationStateUpdateEvent,
+ isMessageEvent,
} from "#/types/agent-server/type-guards";
import { useConfig } from "#/hooks/query/use-config";
import { useConversationStore } from "#/stores/conversation-store";
@@ -37,6 +38,7 @@ import { CollapsibleThinking } from "./event-message-components/collapsible-thin
import { HookExecutionEventMessage } from "./event-message-components/hook-execution-event-message";
import { CorrectiveNudgeMessage } from "./event-message-components/corrective-nudge-message";
import { createSkillReadyEvent } from "./event-content-helpers/create-skill-ready-event";
+import { parseMessageFromEvent } from "./event-content-helpers/parse-message-from-event";
import { isCorrectiveNudge } from "./event-content-helpers/should-render-event";
import { shouldShowPlanPreview } from "./hooks/use-plan-preview-events";
import { getReasoningContent, splitInlineThink } from "./event-thought-helpers";
@@ -200,9 +202,16 @@ function EventMessageComponent({
// Streaming slots render on a clock rather than at the granularity the
// network delivered (#15493). Unconditional: hooks cannot be nested in the
- // per-kind branches below, and a non-slot event has no streamed content.
+ // per-kind branches below. A finished agent message is fed through it too:
+ // it replaces its slot in place, so the reveal carries on from where the
+ // slot left off instead of the unrevealed rest appearing at once. Any other
+ // message mounts complete and is shown as is.
+ const finishedReply =
+ isMessageEvent(event) && event.source === "agent"
+ ? parseMessageFromEvent(event)
+ : "";
const streamedContent = useStreamedText(
- isStreamingDeltaEvent(event) ? (event.content ?? "") : "",
+ isStreamingDeltaEvent(event) ? (event.content ?? "") : finishedReply,
);
// Common props for components that need them
@@ -242,13 +251,13 @@ function EventMessageComponent({
);
}
- if (isStreamingDeltaEvent(event)) {
+ const renderStreamingReply = (reasoning: string) => {
// Route an inline <think> block to the thinking section, not the bubble.
const { reasoning: inlineThink, message } = splitInlineThink(
streamedContent,
{ streaming: true },
);
- const reasoningContent = [event.reasoning_content ?? "", inlineThink]
+ const reasoningContent = [reasoning, inlineThink]
.filter(Boolean)
.join("\n\n");
return (
@@ -260,10 +269,20 @@ function EventMessageComponent({
message={message}
isFromPlanningAgent={isFromPlanningAgent}
timestamp={event.timestamp}
+ isStreaming
/>
)}
</>
);
+ };
+
+ if (isStreamingDeltaEvent(event)) {
+ return renderStreamingReply(event.reasoning_content ?? "");
+ }
+
+ // The finished reply is still being revealed: keep the streaming bubble.
+ if (isMessageEvent(event) && streamedContent.length < finishedReply.length) {
+ return renderStreamingReply(getReasoningContent(event.llm_message));
}
// Finish actions
diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsx
index 70f77459d9..e44ae28222 100644
--- a/src/components/features/chat/chat-interface.tsx
+++ b/src/components/features/chat/chat-interface.tsx
@@ -16,6 +16,7 @@ import { InteractiveChatBox } from "./interactive-chat-box";
import { AgentState } from "#/types/agent-state";
import { useFilteredEvents } from "#/hooks/use-filtered-events";
import { useScrollToBottom } from "#/hooks/use-scroll-to-bottom";
+import { useIsRevealingStreamedText } from "#/hooks/use-streamed-text";
import { useLoadOlderEvents } from "#/hooks/use-load-older-events";
import { useAutoRefreshFilesOnEdit } from "#/hooks/use-auto-refresh-files-on-edit";
import { WorkspaceFilesForChatProvider } from "./chat-markdown-path-code";
@@ -118,6 +119,9 @@ export function ChatInterface({
);
const { t } = useTranslation("openhands");
const scrollRef = React.useRef<HTMLDivElement>(null);
+ // A streamed reply grows inside one event as it is revealed, so follow it
+ // frame by frame while it does.
+ const isRevealingStreamedText = useIsRevealingStreamedText();
const {
scrollDomToBottom,
onChatBodyScroll,
@@ -125,7 +129,7 @@ export function ChatInterface({
autoScroll,
setAutoScroll,
setHitBottom,
- } = useScrollToBottom(scrollRef);
+ } = useScrollToBottom(scrollRef, isRevealingStreamedText);
const {
mutate: newConversationCommand,
isPending: isNewConversationPending,
diff --git a/src/components/features/chat/chat-message.tsx b/src/components/features/chat/chat-message.tsx
index c575628995..37d3d67bc4 100644
--- a/src/components/features/chat/chat-message.tsx
+++ b/src/components/features/chat/chat-message.tsx
@@ -31,6 +31,8 @@ interface ChatMessageProps {
onDismiss?: () => void;
onStop?: () => void;
timestamp?: string;
+ /** The message is a reply still being streamed in. */
+ isStreaming?: boolean;
}
export function ChatMessage({
@@ -44,6 +46,7 @@ export function ChatMessage({
onDismiss,
onStop,
timestamp,
+ isStreaming = false,
}: React.PropsWithChildren<ChatMessageProps>) {
const { t, i18n } = useTranslation("openhands");
const [isHovering, setIsHovering] = React.useState(false);
@@ -134,6 +137,7 @@ export function ChatMessage({
includeHeadings
allowHtml={type !== "user"}
components={chatBubbleMarkdownComponents}
+ streaming={isStreaming}
>
{message}
</MarkdownRenderer>
diff --git a/src/components/features/markdown/markdown-renderer.tsx b/src/components/features/markdown/markdown-renderer.tsx
index 96003b23e6..c0b861c4b4 100644
--- a/src/components/features/markdown/markdown-renderer.tsx
+++ b/src/components/features/markdown/markdown-renderer.tsx
@@ -15,6 +15,8 @@ import { table, th, td } from "./table";
import { blockquote } from "./blockquote";
import { hr } from "./horizontal-rule";
import { remarkGithubAlerts } from "./remark-github-alerts";
+import { advanceStableMarkdownBoundary } from "#/utils/split-stable-markdown";
+import { RevealClock, rehypeFadeInWords } from "./rehype-fade-in-words";
// Build a sanitize schema that extends rehype-sanitize's defaults with a
// few markdown-friendly additions. The defaults strip `<script>`, event
@@ -117,6 +119,99 @@ interface MarkdownRendererProps {
* blocks, anchor targets, etc.).
*/
allowHtml?: boolean;
+ /**
+ * The content is still being appended to (a streamed reply). Finished
+ * blocks are then parsed once and only the tail is re-parsed per update,
+ * so a long reply does not cost a full parse every frame. Newly revealed
+ * words fade in.
+ */
+ streaming?: boolean;
+}
+
+const remarkPlugins: PluggableList = [
+ remarkGithubAlerts,
+ remarkGfm,
+ remarkBreaks,
+];
+
+// `rehype-raw` parses raw HTML embedded in the markdown into the rehype
+// tree. `rehype-sanitize` then strips anything dangerous (scripts,
+// event handlers, `javascript:` URLs, etc.). The order matters: sanitize
+// must run *after* raw so it sees the parsed HTML nodes.
+const htmlRehypePlugins: PluggableList = [
+ rehypeRaw,
+ [rehypeSanitize, MARKDOWN_SANITIZE_SCHEMA],
+];
+
+function MarkdownBlockComponent({
+ source,
+ components,
+ rehypePlugins,
+ clock,
+ blockStart,
+}: {
+ source: string;
+ components: Components;
+ rehypePlugins: PluggableList | undefined;
+ /** Set while streaming: fade in words as they are revealed. */
+ clock: RevealClock | undefined;
+ blockStart: number;
+}) {
+ return (
+ <Markdown
+ components={components}
+ remarkPlugins={remarkPlugins}
+ rehypePlugins={
+ clock
+ ? [
+ ...(rehypePlugins ?? []),
+ [rehypeFadeInWords, { clock, blockStart }],
+ ]
+ : rehypePlugins
+ }
+ >
+ {source}
+ </Markdown>
+ );
+}
+
+const MarkdownBlock = React.memo(MarkdownBlockComponent);
+
+/**
+ * Split streamed markdown into its stable blocks plus the tail, remembering
+ * the boundaries so each update parses only the text after the last one, and
+ * record when each part was revealed. Text that is not an extension of the
+ * previous render (a retry) starts over, shown at once.
+ */
+function useStreamedMarkdownBlocks(text: string, streaming: boolean) {
+ const previousRef = React.useRef({ text: "", offsets: [0] });
+ const [clock] = React.useState(() => new RevealClock());
+
+ const blocks = React.useMemo(() => {
+ if (!streaming) {
+ return [{ source: text, start: 0 }];
+ }
+ const previous = previousRef.current;
+ const isExtension = text.startsWith(previous.text);
+ if (isExtension) {
+ clock.advance(text.length);
+ } else {
+ clock.reset(text.length);
+ }
+ const offsets = isExtension ? [...previous.offsets] : [0];
+ const last = offsets[offsets.length - 1];
+ const boundary = advanceStableMarkdownBoundary(text, last);
+ if (boundary > last) {
+ offsets.push(boundary);
+ }
+ previousRef.current = { text, offsets };
+ return offsets.map((start, index) => ({
+ source: text.slice(start, offsets[index + 1]),
+ start,
+ }));
+ }, [text, streaming, clock]);
+
+ return { blocks, clock: streaming ? clock : undefined };
}
/**
@@ -139,52 +234,62 @@ function MarkdownRendererComponent({
includeStandard = false,
includeHeadings = false,
allowHtml = true,
+ streaming = false,
}: MarkdownRendererProps) {
- // Build the components object with defaults and optional additions
- const components: Components = {
- code,
- ul,
- ol,
- li,
- hr,
- table,
- th,
- td,
- blockquote,
- ...(includeStandard && {
- a: anchor,
- p: paragraph,
+ // Build the components object with defaults and optional additions.
+ // Memoized so streamed blocks that did not change skip re-rendering.
+ const components = React.useMemo<Components>(
+ () => ({
+ code,
+ ul,
+ ol,
+ li,
+ hr,
+ table,
+ th,
+ td,
+ blockquote,
+ ...(includeStandard && {
+ a: anchor,
+ p: paragraph,
+ }),
+ ...(includeHeadings && {
+ h1,
+ h2,
+ h3,
+ h4,
+ h5,
+ h6,
+ }),
+ ...customComponents, // Custom components override defaults
}),
- ...(includeHeadings && {
- h1,
- h2,
- h3,
- h4,
- h5,
- h6,
- }),
- ...customComponents, // Custom components override defaults
- };
-
- const markdownContent = content ?? children ?? "";
+ [customComponents, includeStandard, includeHeadings],
+ );
- // `rehype-raw` parses raw HTML embedded in the markdown into the rehype
- // tree. `rehype-sanitize` then strips anything dangerous (scripts,
- // event handlers, `javascript:` URLs, etc.). The order matters: sanitize
- // must run *after* raw so it sees the parsed HTML nodes.
- const rehypePlugins: PluggableList | undefined = allowHtml
- ? [rehypeRaw, [rehypeSanitize, MARKDOWN_SANITIZE_SCHEMA]]
- : undefined;
+ const { blocks, clock } = useStreamedMarkdownBlocks(
+ content ?? children ?? "",
+ streaming,
+ );
+ const rehypePlugins = allowHtml ? htmlRehypePlugins : undefined;
+ // Blocks render as siblings in one wrapper, joined by the newline the
+ // parser puts between top-level blocks, so the DOM (and `first:` / `last:`
+ // spacing) matches the finished message rendered in one piece.
return (
<div data-testid="markdown-renderer">
- <Markdown
- components={components}
- remarkPlugins={[remarkGithubAlerts, remarkGfm, remarkBreaks]}
- rehypePlugins={rehypePlugins}
- >
- {markdownContent}
- </Markdown>
+ {blocks.map(({ source, start }, index) => (
+ // Blocks only ever append, so the index is a stable identity.
+ <React.Fragment key={index}>
+ {index > 0 && "\n"}
+ <MarkdownBlock
+ source={source}
+ components={components}
+ rehypePlugins={rehypePlugins}
+ clock={clock}
+ blockStart={start}
+ />
+ </React.Fragment>
+ ))}
</div>
);
}
diff --git a/src/components/features/markdown/rehype-fade-in-words.ts b/src/components/features/markdown/rehype-fade-in-words.ts
new file mode 100644
index 0000000000..f0f01549c7
--- /dev/null
+++ b/src/components/features/markdown/rehype-fade-in-words.ts
@@ -0,0 +1,118 @@
+import type { Plugin } from "unified";
+import type { ElementContent, Root } from "hast";
+import { SKIP, visit } from "unist-util-visit";
+
+/** Must match the `stream-word-fade` animation in index.css. */
+export const STREAM_WORD_FADE_MS = 280;
+
+/** Text inside these is not split into words. */
+const SKIP_TAGS = new Set(["pre", "code", "svg", "math", "script", "style"]);
+
+/**
+ * Records when each part of a streamed text was revealed, so a word's fade can
+ * be resumed where it was rather than restarted when its element is re-created
+ * (a streamed block is re-mounted when the block before it is frozen).
+ */
+export class RevealClock {
+ private segments: { start: number; at: number }[] = [];
+
+ private length = 0;
+
+ /** The text now shown is `length` long. */
+ advance(length: number, at = performance.now()) {
+ if (length > this.length) {
+ this.segments.push({ start: this.length, at });
+ this.length = length;
+ }
+ // Segments whose fade is over no longer need a time.
+ while (
+ this.segments.length > 0 &&
+ at - this.segments[0].at >= STREAM_WORD_FADE_MS
+ ) {
+ this.segments.shift();
+ }
+ }
+
+ /** Treat text up to `length` as already shown, e.g. after a retry snapped in. */
+ reset(length: number) {
+ this.segments = [];
+ this.length = length;
+ }
+
+ /** When the character at `offset` was revealed, or null if long enough ago. */
+ revealedAt(offset: number): number | null {
+ for (let i = this.segments.length - 1; i >= 0; i -= 1) {
+ if (this.segments[i].start <= offset) {
+ return this.segments[i].at;
+ }
+ }
+ return null;
+ }
+}
+
+interface FadeInWordsOptions {
+ clock: RevealClock;
+ /** Offset of this block's source within the whole streamed text. */
+ blockStart: number;
+}
+
+/**
+ * Wrap each word of a streamed reply in a span, and fade in the ones revealed
+ * within the last `STREAM_WORD_FADE_MS`. Every word keeps a span (not only the
+ * fading ones) so elements stay put as text is appended; a negative
+ * `animation-delay` places a re-created word at its current point in the fade.
+ *
+ * Text nodes after inline markup carry no source position, so their offsets
+ * continue from the previous one β€” off by the markup's few characters, which
+ * is invisible in the timing.
+ */
+export const rehypeFadeInWords: Plugin<[FadeInWordsOptions], Root> =
+ ({ clock, blockStart }) =>
+ (tree) => {
+ const renderedAt = performance.now();
+ let cursor = 0;
+
+ const wordSpan = (word: string, offset: number): ElementContent => {
+ const revealedAt = clock.revealedAt(blockStart + offset);
+ const elapsed = revealedAt === null ? Infinity : renderedAt - revealedAt;
+ return {
+ type: "element",
+ tagName: "span",
+ properties:
+ elapsed < STREAM_WORD_FADE_MS
+ ? {
+ dataStreamWord: true,
+ className: ["stream-word-fade"],
+ style: `animation-delay:${-Math.round(elapsed)}ms`,
+ }
+ : { dataStreamWord: true },
+ children: [{ type: "text", value: word }],
+ };
+ };
+
+ visit(tree, (node, index, parent) => {
+ if (node.type === "element" && SKIP_TAGS.has(node.tagName)) {
+ return SKIP;
+ }
+ if (node.type !== "text" || !parent || index === undefined) {
+ return undefined;
+ }
+ cursor = node.position?.start.offset ?? cursor;
+ const parts: ElementContent[] = [];
+ let offset = cursor;
+ for (const part of node.value.split(/(\s+)/)) {
+ if (part) {
+ parts.push(
+ /\S/.test(part)
+ ? wordSpan(part, offset)
+ : { type: "text", value: part },
+ );
+ }
+ offset += part.length;
+ }
+ cursor += node.value.length;
+ parent.children.splice(index, 1, ...parts);
+ // Continue after the inserted nodes: their text is already split.
+ return index + parts.length;
+ });
+ };
diff --git a/src/hooks/use-scroll-to-bottom.ts b/src/hooks/use-scroll-to-bottom.ts
index 13c5cf149b..1cbc8cdc31 100644
--- a/src/hooks/use-scroll-to-bottom.ts
+++ b/src/hooks/use-scroll-to-bottom.ts
@@ -1,6 +1,20 @@
-import { RefObject, useState, useCallback, useRef } from "react";
+import {
+ RefObject,
+ useState,
+ useCallback,
+ useRef,
+ useEffect,
+ useLayoutEffect,
+} from "react";
-export function useScrollToBottom(scrollRef: RefObject<HTMLDivElement | null>) {
+/**
+ * @param followContent Content is growing in place (a streamed reply), so keep
+ * the bottom in view frame by frame while the user is pinned to it.
+ */
+export function useScrollToBottom(
+ scrollRef: RefObject<HTMLDivElement | null>,
+ followContent = false,
+) {
// Track whether the user is currently near the bottom of the scroll area.
// Used by consumers to decide whether to scroll when new UI elements appear.
// NOT used for automatic content-following.
@@ -61,6 +75,42 @@ export function useScrollToBottom(scrollRef: RefObject<HTMLDivElement | null>) {
}
}, [scrollRef]);
+ // A streamed reply grows inside a single event, so nothing re-renders to
+ // scroll it into view. The user scrolling up is read from the element each
+ // frame: the `autoscroll` state that records it lags a render behind, and
+ // following until then would yank them back down.
+ const autoscrollRef = useRef(autoscroll);
+ useLayoutEffect(() => {
+ autoscrollRef.current = autoscroll;
+ }, [autoscroll]);
+
+ useEffect(() => {
+ const dom = scrollRef.current;
+ if (!followContent || !dom || typeof requestAnimationFrame !== "function") {
+ return undefined;
+ }
+
+ let lastTop = dom.scrollTop;
+ let frame = 0;
+ const follow = () => {
+ const bottom = dom.scrollHeight - dom.clientHeight;
+ if (autoscrollRef.current) {
+ // Content shrinking also lowers scrollTop, but leaves it at the bottom.
+ if (dom.scrollTop < lastTop - 1 && dom.scrollTop < bottom - 1) {
+ autoscrollRef.current = false;
+ setAutoscroll(false);
+ } else if (dom.scrollTop < bottom - 1) {
+ dom.scrollTop = bottom;
+ }
+ }
+ lastTop = dom.scrollTop;
+ frame = requestAnimationFrame(follow);
+ };
+
+ frame = requestAnimationFrame(follow);
+ return () => cancelAnimationFrame(frame);
+ }, [followContent, scrollRef]);
+
return {
scrollRef,
autoScroll: autoscroll,
diff --git a/src/hooks/use-streamed-text.ts b/src/hooks/use-streamed-text.ts
index fd87478dea..74e5483851 100644
--- a/src/hooks/use-streamed-text.ts
+++ b/src/hooks/use-streamed-text.ts
@@ -1,29 +1,68 @@
import React from "react";
+import { create } from "zustand";
/**
- * Window over which the unrevealed backlog is drained. Short enough that the
- * text never visibly trails the model, long enough that a burst of tokens
- * reads as typing rather than as a paste.
+ * Reveal pace, in characters per millisecond (60 chars/s). Fast models deliver
+ * several hundred characters a second; revealing at that pace reads as text
+ * being dumped rather than written.
*/
-const DRAIN_WINDOW_MS = 120;
+const PACE = 0.06;
+
+/**
+ * How far the reveal may trail the model before it speeds up beyond `PACE`:
+ * past this backlog, it drains at least `backlog / MAX_LAG_MS`, so a long
+ * reply from a fast model never ends up more than ~10 seconds behind.
+ */
+const MAX_LAG_MS = 10000;
+
+/**
+ * Hooks still revealing text, so the chat can keep following a reply that is
+ * still typing out after its stream has already finished.
+ */
+const useRevealingStore = create<{ ids: ReadonlySet<symbol> }>(() => ({
+ ids: new Set(),
+}));
+
+const setRevealing = (id: symbol, isRevealing: boolean) =>
+ useRevealingStore.setState((state) => {
+ if (state.ids.has(id) === isRevealing) {
+ return state;
+ }
+ const ids = new Set(state.ids);
+ if (isRevealing) {
+ ids.add(id);
+ } else {
+ ids.delete(id);
+ }
+ return { ids };
+ });
+
+/** Whether any streamed text is still being revealed on screen. */
+export const useIsRevealingStreamedText = () =>
+ useRevealingStore((state) => state.ids.size > 0);
/**
* Reveal `target` on a clock rather than at the granularity the network
* happened to deliver it (#15493).
*
- * The rate is proportional to the backlog, so a fast model is revealed fast
- * and a slow one still reads smoothly; text that is not an extension of what
- * is already on screen (a superseding retry, or a different slot) snaps
+ * Text is revealed at a steady `PACE`, so chunks that land in bursts read as
+ * writing instead of a jump followed by a pause; only a backlog worth more
+ * than `MAX_LAG_MS` speeds it up. Text that is not an extension of what is
+ * already on screen (a superseding retry, or a different slot) snaps
* immediately rather than being re-typed.
*/
export function useStreamedText(target: string): string {
const [revealed, setRevealed] = React.useState(target);
const revealedRef = React.useRef(target);
+ // Fractional reveal position: the pace is under one character per frame.
+ const positionRef = React.useRef(target.length);
const frameRef = React.useRef<number | null>(null);
+ const [revealId] = React.useState(() => Symbol("streamed-text"));
React.useEffect(() => {
const commit = (next: string) => {
revealedRef.current = next;
+ positionRef.current = next.length;
setRevealed(next);
};
@@ -44,30 +83,32 @@ export function useStreamedText(target: string): string {
const elapsed = lastTick ? now - lastTick : 16;
lastTick = now;
- const backlog = target.length - revealedRef.current.length;
- const step = Math.max(
- 1,
- Math.ceil((backlog * elapsed) / DRAIN_WINDOW_MS),
- );
- const nextLength = Math.min(
- target.length,
- revealedRef.current.length + step,
- );
- commit(target.slice(0, nextLength));
+ const backlog = target.length - positionRef.current;
+ const step = Math.max(PACE, backlog / MAX_LAG_MS) * elapsed;
+ const position = Math.min(target.length, positionRef.current + step);
+ const nextLength = Math.floor(position);
+ if (nextLength !== revealedRef.current.length) {
+ commit(target.slice(0, nextLength));
+ }
+ positionRef.current = position;
if (nextLength < target.length) {
frameRef.current = requestAnimationFrame(tick);
+ } else {
+ setRevealing(revealId, false);
}
};
+ setRevealing(revealId, true);
frameRef.current = requestAnimationFrame(tick);
return () => {
+ setRevealing(revealId, false);
if (frameRef.current !== null) {
cancelAnimationFrame(frameRef.current);
frameRef.current = null;
}
};
- }, [target]);
+ }, [target, revealId]);
return revealed;
}
diff --git a/src/index.css b/src/index.css
index 766e7e9810..bc91ecaa97 100644
--- a/src/index.css
+++ b/src/index.css
@@ -93,6 +93,27 @@ code {
scroll-timeline: 100ms;
}
+/* Words of a streamed reply fade in as they are revealed. The duration must
+ match STREAM_WORD_FADE_MS in rehype-fade-in-words.ts. */
+@keyframes stream-word-fade {
+ from {
+ opacity: 0.15;
+ }
+ to {
+ opacity: 1;
+ }
+}
+
+.stream-word-fade {
+ animation: stream-word-fade 280ms ease-out both;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .stream-word-fade {
+ animation: none;
+ }
+}
+
@keyframes environment-switch-content-refresh {
0% {
opacity: 1;
diff --git a/src/utils/split-stable-markdown.ts b/src/utils/split-stable-markdown.ts
new file mode 100644
index 0000000000..3e72ccbc56
--- /dev/null
+++ b/src/utils/split-stable-markdown.ts
@@ -0,0 +1,45 @@
+import { fromMarkdown } from "mdast-util-from-markdown";
+
+/**
+ * Advance the end of the markdown prefix that can no longer change as text is
+ * appended, parsing only what lies after `from`.
+ *
+ * A top-level block is stable once the block after it, across a blank line, is
+ * itself complete (another block follows it). Until then the next block can
+ * still merge back: in `1. a\n\n2` the `2` becomes the list's second item once
+ * the `.` arrives, which also turns the whole list loose. A streamed reply can
+ * then render its finished blocks once and re-parse only the tail, instead of
+ * the whole message every frame.
+ *
+ * Raw HTML (a `<details>` spanning blank lines) and link definitions (which
+ * resolve references elsewhere) cannot be read block by block, so the boundary
+ * stops before them and the rest stays in the tail. The finished message is
+ * rendered in one piece, so this only affects the reply while it streams.
+ */
+export function advanceStableMarkdownBoundary(
+ text: string,
+ from: number,
+): number {
+ const tail = text.slice(from);
+ const blocks = fromMarkdown(tail).children;
+ let boundary = from;
+
+ for (let i = 0; i < blocks.length - 2; i += 1) {
+ const block = blocks[i];
+ if (block.type === "html" || block.type === "definition") {
+ break;
+ }
+ const end = block.position?.end.offset;
+ const nextStart = blocks[i + 1].position?.start.offset;
+ if (
+ end === undefined ||
+ nextStart === undefined ||
+ !/\n[ \t]*\n/.test(tail.slice(end, nextStart))
+ ) {
+ break;
+ }
+ boundary = from + nextStart;
+ }
+
+ return boundary;
+}
diff --git a/vite.config.ts b/vite.config.ts
index 7b3ab2a08c..26241f541a 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -298,6 +298,7 @@ export default defineConfig(({ mode }) => {
"@monaco-editor/react",
"react-textarea-autosize",
"react-markdown",
+ "mdast-util-from-markdown",
"remark-gfm",
"remark-breaks",
"react-syntax-highlighter",