Skip to content

Commit cb9629e

Browse files
perf(web): thread switches skip re-parsing, sidebar scrolling, and composer layout reads (#27823)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 81899ce commit cb9629e

6 files changed

Lines changed: 102 additions & 4 deletions

File tree

‎apps/web/src/components/ChatMarkdown.browser.test.tsx‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,18 @@ const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({
1616
workspaceSearch: vi.fn(),
1717
filesystemMetadata: vi.fn(),
1818
}));
19+
const parsedSources = vi.hoisted(() => [] as string[]);
20+
vi.mock(import("mdast-util-from-markdown"), async (original) => {
21+
const actual = await original();
22+
return {
23+
...actual,
24+
fromMarkdown: ((source: string, ...rest: never[]) => {
25+
parsedSources.push(String(source));
26+
return (actual.fromMarkdown as (...args: unknown[]) => unknown)(source, ...rest);
27+
}) as typeof actual.fromMarkdown,
28+
};
29+
});
30+
1931
vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
2032
...(await original()),
2133
useAtomQueryRunner: ((family: unknown) =>
@@ -99,6 +111,7 @@ it("keeps compact audio playback loaded across signed URL renewals", async () =>
99111
});
100112

101113
function setup() {
114+
parsedSources.length = 0;
102115
settingsOverrides.mathRenderingEnabled = false;
103116
renderDiagram.mockReset();
104117
workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
@@ -139,6 +152,19 @@ it("loads a host image through the page's own route when there is no environment
139152
);
140153
});
141154

155+
it("reuses the parse of a streaming reply's finished blocks when it remounts", async () => {
156+
setup();
157+
const message = (
158+
<ChatMarkdown cwd="/tmp/project" text={"Finished block\n\nStill growing"} isStreaming />
159+
);
160+
{
161+
await using _first = await render(message);
162+
}
163+
await using screen = await render(message);
164+
await expect.element(screen.getByText("Still growing")).toBeVisible();
165+
expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1);
166+
});
167+
142168
describe("ChatMarkdown favicon privacy", () => {
143169
it("suppresses private link images while preserving public links across updates", async () => {
144170
setup();

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1767,7 +1767,8 @@ function ChatMarkdown({
17671767
: CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS
17681768
}
17691769
shared={!uncachedPlugins}
1770-
cache={!props.isStreaming}
1770+
// Every block before the last is finished, so its parse can be reused.
1771+
cache={!props.isStreaming || index < blocks.length - 1}
17711772
/>
17721773
))}
17731774
</ChatMarkdownRendererContext>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { expect, it } from "vite-plus/test";
2+
3+
import { render } from "../../../test/render";
4+
import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt";
5+
6+
function Composer({ text }: { readonly text: string }) {
7+
const [multiline, observeBody] = useComposerMultilinePrompt();
8+
return (
9+
<div ref={observeBody} style={{ width: 200, lineHeight: "20px" }}>
10+
<div data-testid="composer-editor" contentEditable suppressContentEditableWarning>
11+
{text}
12+
</div>
13+
<output>{multiline ? "multiline" : "single line"}</output>
14+
</div>
15+
);
16+
}
17+
18+
it("notices when typing makes the prompt wrap", async () => {
19+
await using screen = await render(<Composer text="short" />, { router: false });
20+
await expect.element(screen.getByText("single line")).toBeVisible();
21+
await screen.rerender(<Composer text={"a long prompt that wraps ".repeat(6)} />);
22+
await expect.element(screen.getByText("multiline")).toBeVisible();
23+
});

‎apps/web/src/components/chat/useComposerMultilinePrompt.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,24 @@ export function useComposerMultilinePrompt(): readonly [
2727
const [isMultiline, setIsMultiline] = useState(false);
2828
const observeBody = (body: HTMLElement | null) => {
2929
if (!body) return;
30+
// Measuring reads layout, so one measurement per frame runs after all of the frame's DOM
31+
// writes instead of forcing a layout after each mutation.
32+
let frame: number | null = null;
3033
const measure = () => {
31-
const next = measureComposerMultilinePrompt(body);
32-
if (next !== null) setIsMultiline(next);
34+
if (frame !== null) return;
35+
frame = requestAnimationFrame(() => {
36+
frame = null;
37+
const next = measureComposerMultilinePrompt(body);
38+
if (next !== null) setIsMultiline(next);
39+
});
3340
};
3441
measure();
3542
const editor = body.querySelector<HTMLElement>('[data-testid="composer-editor"]');
3643
const stopObserving = observeResize(editor ? [body, editor] : body, measure);
3744
const mutationObserver = new MutationObserver(measure);
3845
mutationObserver.observe(body, { childList: true, characterData: true, subtree: true });
3946
return () => {
47+
if (frame !== null) cancelAnimationFrame(frame);
4048
stopObserving();
4149
mutationObserver.disconnect();
4250
};

‎apps/web/src/components/sidebar/routeReveal.browser.test.tsx‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { describe, expect, it } from "vite-plus/test";
1+
import { describe, expect, it, vi } from "vite-plus/test";
2+
import { userEvent } from "vite-plus/test/browser";
23

34
import { render } from "../../../test/render";
45
import { type SidebarRouteReveal, useActiveRowReveal } from "./routeReveal";
@@ -17,6 +18,7 @@ function RevealList(props: {
1718
<li
1819
key={key}
1920
ref={key === props.activeKey ? (row) => revealActiveRow(row, key) : undefined}
21+
tabIndex={-1}
2022
style={{ height: ROW_HEIGHT_PX }}
2123
>
2224
{key}
@@ -46,6 +48,41 @@ describe("useActiveRowReveal", () => {
4648
await expect.element(target).toBeInViewport();
4749
});
4850

51+
it("leaves the list where it is when the user clicked the row that opened the thread", async () => {
52+
const reveal = newReveal();
53+
const keys = rowKeys(50);
54+
await using screen = await render(
55+
<RevealList reveal={reveal} rowKeys={keys} activeKey="thread-0" />,
56+
// No router: the route arrives as the activeKey prop.
57+
{ router: false },
58+
);
59+
await userEvent.hover(screen.getByText("thread-2", { exact: true }));
60+
// Even a no-op scroll forces a layout of the thread being opened.
61+
using scrollIntoView = vi.spyOn(Element.prototype, "scrollIntoView");
62+
63+
await screen.rerender(<RevealList reveal={reveal} rowKeys={keys} activeKey="thread-2" />);
64+
65+
await vi.waitFor(() => expect(reveal.pendingKey).toBeNull());
66+
expect(scrollIntoView).not.toHaveBeenCalled();
67+
});
68+
69+
it("reveals a focused row scrolled out of view when the keyboard opens its thread", async () => {
70+
const reveal = newReveal();
71+
const keys = rowKeys(50);
72+
await using screen = await render(
73+
<RevealList reveal={reveal} rowKeys={keys} activeKey="thread-0" />,
74+
// No router: the route arrives as the activeKey prop.
75+
{ router: false },
76+
);
77+
const target = screen.getByText("thread-40", { exact: true });
78+
target.element().focus({ preventScroll: true });
79+
await expect.element(target).not.toBeInViewport();
80+
81+
await screen.rerender(<RevealList reveal={reveal} rowKeys={keys} activeKey="thread-40" />);
82+
83+
await expect.element(target).toBeInViewport();
84+
});
85+
4986
it("reveals the active row when it mounts after the shells arrive", async () => {
5087
const reveal = newReveal();
5188
// The route already names the thread, but its environment's shells have not

‎apps/web/src/components/sidebar/routeReveal.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ export function useActiveRowReveal(reveal: SidebarRouteReveal, routeKey: string
3838
if (reveal.pendingKey !== rowKey && !mountRevealOwed.current) return;
3939
completeSidebarRouteReveal(reveal);
4040
mountRevealOwed.current = false;
41+
// A row under the pointer was just clicked, so it is in view; scrolling it would force a
42+
// layout mid-commit. Keyboard activation can come from a focused row scrolled out of view.
43+
if (row.matches(":hover")) return;
4144
row.scrollIntoView({ block: "nearest" });
4245
};
4346
}

0 commit comments

Comments
 (0)