Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

renderScenarios.renders.tsx

281 lines9.7 KB

1// Render scenarios for scripts/render-metrics.ts. Each one mounts real components on
2// fixed fixtures, counts React commits and component renders while it drives them,
3// and writes the counts through the writeRenderReport browser command. They mount the
4// components ChatView composes, not ChatView, which needs a live environment connection.
5import { EnvironmentId, MessageId } from "@t3tools/contracts";
6import type { LegendListRef } from "@legendapp/list/react";
7import { createRef, useRef, useState, type ComponentProps, type ReactNode } from "react";
8import { expect, it, vi } from "vite-plus/test";
9import { commands, userEvent } from "vite-plus/test/browser";
10​
11import "~/index.css";
12​
13import { MessagesTimeline } from "~/components/chat/MessagesTimeline";
14import {
15 ComposerPromptEditorTiptap as ComposerPromptEditor,
16 type ComposerPromptEditorHandle,
17} from "~/components/ComposerPromptEditorTiptap";
18import { commitsSoFar, startCounting, stopCounting } from "./renderCounter";
19import { render } from "./render";
20​
21declare module "vite-plus/test/browser" {
22 interface BrowserCommands {
23 /** Defined in vite.config.ts for the renders project. */
24 writeRenderReport: (scenario: string, json: string) => Promise<void>;
25 }
27​
28vi.mock(import("~/state/query"), async (original) => ({
29 ...(await original()),
30 useEnvironmentQuery: (() => ({
31 data: { tasks: [] },
32 dataUpdatedAt: 0,
33 error: null,
34 failure: null,
35 isPending: false,
36 isSuccess: true,
37 refresh: () => {},
38 })) as never,
39}));
40​
41const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
42const CREATED_AT = "2026-03-17T19:12:28.000Z";
43const HISTORY_TURNS = 20;
44const STREAM_DELTAS = 30;
45const TYPED_TEXT = "fix the flaky tests!";
46​
47type TimelineProps = ComponentProps<typeof MessagesTimeline>;
48type Entry = TimelineProps["timelineEntries"][number];
49​
50function message(id: string, role: "user" | "assistant", text: string, streaming = false): Entry {
51 return {
52 id: `entry-${id}`,
53 kind: "message",
54 createdAt: CREATED_AT,
55 message: {
56 id: MessageId.make(id),
57 role,
58 text,
59 runId: null,
60 createdAt: CREATED_AT,
61 updatedAt: CREATED_AT,
62 streaming,
63 },
64 } as Entry;
66​
67// A thread with history: user prompts and markdown answers with lists and inline code.
68// No fenced code: Shiki highlights it asynchronously, and whether a block first renders
69// its fallback varies run to run.
70function history(thread: string): Entry[] {
71 return Array.from({ length: HISTORY_TURNS }, (_, turn) => [
72 message(`${thread}-user-${turn}`, "user", `${thread}: question ${turn} about the sidebar`),
73 message(
74 `${thread}-assistant-${turn}`,
75 "assistant",
76 `Answer ${turn} for ${thread}.\n\n- checked \`Sidebar.tsx\`\n- ran the tests\n\n` +
77 "The width is now `clamp(next, MIN_WIDTH, MAX_WIDTH)`, so the layout no longer jumps.",
78 ),
79 ]).flat();
81​
82// Props that some trees under comparison have dropped. A JSX spread is not checked for
83// excess properties, so this file type-checks on trees with and without them.
84const versionedProps = { onManualNavigation: () => {} };
85​
86// One list handle per mounted timeline, as ChatView keeps one: the timeline compares the
87// handle across renders, and a new one per render would skip its scroll-to-end and settle work.
88function timelineFor() {
89 const listRef = createRef<LegendListRef | null>();
90 return (thread: string, entries: Entry[]) => (
91 <MessagesTimeline
92 timelineEntries={entries}
93 isWorking={false}
94 listRef={listRef}
95 latestRun={null}
96 turnDiffSummaries={[]}
97 runs={[]}
98 routeThreadKey={`environment-local:${thread}`}
99 onOpenTurnDiff={() => {}}
100 onOpenThread={() => {}}
101 onForkFromRun={async () => {}}
102 supportsConversationRollback={false}
103 onRevertToTurnCount={() => {}}
104 isRevertingCheckpoint={false}
105 onImageExpand={() => {}}
106 activeThreadEnvironmentId={ENVIRONMENT_ID}
107 markdownCwd={undefined}
108 resolvedTheme="light"
109 timestampFormat="locale"
110 workspaceRoot={undefined}
111 anchorMessageId={null}
112 onAnchorReady={() => {}}
113 onAnchorSizeChanged={() => {}}
114 contentInsetEndAdjustment={0}
115 emptyPlaceholderInset={0}
116 liveFollowEnabled
117 onIsAtEndChange={() => {}}
118 {...versionedProps}
119 />
120 );
122​
123function sizedContainer() {
124 const container = document.createElement("div");
125 container.style.cssText = "height: 900px; width: 900px; display: flex; flex-direction: column;";
126 return container;
128​
129// Legend List measures rows, and the minimap follows scroll, on later frames, and how
130// much of that lands inside a window varies run to run. Every window opens and closes
131// on a quiet tree: no commit across two consecutive checks.
132async function quiet() {
133 let seen = -1;
134 await vi.waitFor(
135 () => {
136 const now = commitsSoFar();
137 const settled = now === seen;
138 seen = now;
139 expect(settled).toBe(true);
140 },
141 { interval: 100, timeout: 10_000 },
142 );
144​
145// Off the guest page the connection runtime retries a missing environment on timers, and
146// its atom updates commit at varying times. On it, the runtime fails once and stays quiet.
147function onGuestPage(): Disposable {
148 const previous = `${window.location.pathname}${window.location.search}`;
149 window.history.replaceState(window.history.state, "", "/guest?share=render-scenarios");
150 return {
151 [Symbol.dispose]: () => window.history.replaceState(window.history.state, "", previous),
152 };
154​
155// A first mount loads lazy modules, web fonts and syntax highlighting at varying times.
156// Each scenario mounts its tree once uncounted, so the counted run starts warm.
157async function warmUp(ui: ReactNode, container?: HTMLElement) {
158 await using screen = await render(ui, container ? { container } : {});
159 await document.fonts.ready;
160 await quiet();
161 expect(screen.container.childElementCount).toBeGreaterThan(0);
163​
164async function report(scenario: string) {
165 await quiet();
166 const counts = stopCounting();
167 await commands.writeRenderReport(scenario, JSON.stringify(counts));
169​
170it("mount-thread", async () => {
171 using _guest = onGuestPage();
172 const timeline = timelineFor();
173 await warmUp(timelineFor()("thread-warm", history("thread-warm")), sizedContainer());
174 startCounting();
175 await using screen = await render(timeline("thread-a", history("thread-a")), {
176 container: sizedContainer(),
177 });
178 await expect.element(screen.getByText(`Answer ${HISTORY_TURNS - 1} for thread-a.`)).toBeVisible();
179 await report("mount-thread");
180});
181​
182it("stream-assistant-turn", async () => {
183 using _guest = onGuestPage();
184 const timeline = timelineFor();
185 const base = history("thread-a");
186 const streamed = (text: string) => [
187 ...base,
188 message("live-user", "user", "Continue"),
189 message("live-assistant", "assistant", text, true),
190 ];
191 await warmUp(timelineFor()("thread-warm", streamed("warm")), sizedContainer());
192 await using screen = await render(timeline("thread-a", streamed("")), {
193 container: sizedContainer(),
194 });
195 await expect.element(screen.getByText("Continue")).toBeVisible();
196 await quiet();
197​
198 startCounting();
199 let text = "";
200 for (let delta = 0; delta < STREAM_DELTAS; delta++) {
201 text += `word${delta} `;
202 await screen.rerender(timeline("thread-a", streamed(text)));
203 }
204 await expect
205 .element(screen.getByText(`word${STREAM_DELTAS - 1}`, { exact: false }))
206 .toBeVisible();
207 await report("stream-assistant-turn");
208});
209​
210// Thread A to B and back, each switch counted until the tree is quiet again. Commits
211// are not reported: the minimap's follow-up renders sometimes split across two frames,
212// so the commit count varies by one while the renders stay identical.
213it("switch-thread", async () => {
214 using _guest = onGuestPage();
215 const timeline = timelineFor();
216 const a = history("thread-a");
217 const b = history("thread-b");
218 const lastAnswer = (thread: string) =>
219 screen.getByText(`Answer ${HISTORY_TURNS - 1} for ${thread}.`);
220 await warmUp(timelineFor()("thread-warm", a), sizedContainer());
221 await using screen = await render(timeline("thread-a", a), { container: sizedContainer() });
222 await expect.element(lastAnswer("thread-a")).toBeVisible();
223​
224 await quiet();
225 startCounting();
226 await screen.rerender(timeline("thread-b", b));
227 await expect.element(lastAnswer("thread-b")).toBeVisible();
228 await quiet();
229 const toB = stopCounting();
230 startCounting();
231 await screen.rerender(timeline("thread-a", a));
232 await expect.element(lastAnswer("thread-a")).toBeVisible();
233 await quiet();
234 const toA = stopCounting();
235​
236 const components = { ...toB.components };
237 for (const [name, count] of Object.entries(toA.components)) {
238 components[name] = (components[name] ?? 0) + count;
239 }
240 await commands.writeRenderReport(
241 "switch-thread",
242 JSON.stringify({
243 commits: null,
244 renders: toB.renders + toA.renders,
245 components,
246 }),
247 );
248});
249​
250function Composer() {
251 const [prompt, setPrompt] = useState({ value: "", cursor: 0 });
252 const editorRef = useRef<ComposerPromptEditorHandle>(null);
253 return (
254 <ComposerPromptEditor
255 editorRef={editorRef}
256 value={prompt.value}
257 cursor={prompt.cursor}
258 richTextEnabled
259 contextRecords={new Map()}
260 skills={[]}
261 disabled={false}
262 placeholder="Ask anything"
263 onChange={(value, cursor) => setPrompt({ value, cursor })}
264 onPaste={() => {}}
265 />
266 );
268​
269it("type-in-composer", async () => {
270 using _guest = onGuestPage();
271 await warmUp(<Composer />);
272 await using screen = await render(<Composer />);
273 const editor = screen.getByRole("textbox");
274 await userEvent.click(editor);
275 await quiet();
276​
277 startCounting();
278 await userEvent.type(editor, TYPED_TEXT);
279 await expect.element(editor).toHaveTextContent(TYPED_TEXT);
280 await report("type-in-composer");
281});