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

ChatView.browser.tsx

711 lines20.2 KB

1// Production CSS is part of the behavior under test because row height depends on it.
2import "../index.css";
3​
4import {
5 ORCHESTRATION_WS_METHODS,
6 type MessageId,
7 type OrchestrationReadModel,
8 type ProjectId,
9 type ServerConfig,
10 type ThreadId,
11 type WsWelcomePayload,
12 WS_CHANNELS,
13 WS_METHODS,
14} from "@t3tools/contracts";
15import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
16import { HttpResponse, http, ws } from "msw";
17import { setupWorker } from "msw/browser";
18import { page } from "vitest/browser";
19import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
20import { render } from "vitest-browser-react";
21​
22import { getRouter } from "../router";
23import { useStore } from "../store";
24import { estimateTimelineMessageHeight } from "./timelineHeight";
25​
26const THREAD_ID = "thread-browser-test" as ThreadId;
27const PROJECT_ID = "project-1" as ProjectId;
28const NOW_ISO = "2026-03-04T12:00:00.000Z";
29const BASE_TIME_MS = Date.parse(NOW_ISO);
30const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
31​
32interface WsRequestEnvelope {
33 id: string;
34 body: {
35 _tag: string;
36 [key: string]: unknown;
37 };
39​
40interface TestFixture {
41 snapshot: OrchestrationReadModel;
42 serverConfig: ServerConfig;
43 welcome: WsWelcomePayload;
45​
46let fixture: TestFixture;
47const wsLink = ws.link(/ws(s)?:\/\/.*/);
48​
49interface ViewportSpec {
50 name: string;
51 width: number;
52 height: number;
53 textTolerancePx: number;
54 attachmentTolerancePx: number;
56​
57const DEFAULT_VIEWPORT: ViewportSpec = {
58 name: "desktop",
59 width: 960,
60 height: 1_100,
61 textTolerancePx: 44,
62 attachmentTolerancePx: 56,
63};
64const TEXT_VIEWPORT_MATRIX = [
65 DEFAULT_VIEWPORT,
66 { name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 },
67 { name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
68 { name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
69] as const satisfies readonly ViewportSpec[];
70const ATTACHMENT_VIEWPORT_MATRIX = [
71 DEFAULT_VIEWPORT,
72 { name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
73 { name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
74] as const satisfies readonly ViewportSpec[];
75​
76interface UserRowMeasurement {
77 measuredRowHeightPx: number;
78 timelineWidthMeasuredPx: number;
79 renderedInVirtualizedRegion: boolean;
81​
82interface MountedChatView {
83 cleanup: () => Promise<void>;
84 measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
85 setViewport: (viewport: ViewportSpec) => Promise<void>;
87​
88function isoAt(offsetSeconds: number): string {
89 return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString();
91​
92function createBaseServerConfig(): ServerConfig {
93 return {
94 cwd: "/repo/project",
95 keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
96 keybindings: [],
97 issues: [],
98 providers: [
99 {
100 provider: "codex",
101 status: "ready",
102 available: true,
103 authStatus: "authenticated",
104 checkedAt: NOW_ISO,
105 },
106 ],
107 availableEditors: [],
108 };
110​
111function createUserMessage(options: {
112 id: MessageId;
113 text: string;
114 offsetSeconds: number;
115 attachments?: Array<{
116 type: "image";
117 id: string;
118 name: string;
119 mimeType: string;
120 sizeBytes: number;
121 }>;
122}) {
123 return {
124 id: options.id,
125 role: "user" as const,
126 text: options.text,
127 ...(options.attachments ? { attachments: options.attachments } : {}),
128 turnId: null,
129 streaming: false,
130 createdAt: isoAt(options.offsetSeconds),
131 updatedAt: isoAt(options.offsetSeconds + 1),
132 };
134​
135function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) {
136 return {
137 id: options.id,
138 role: "assistant" as const,
139 text: options.text,
140 turnId: null,
141 streaming: false,
142 createdAt: isoAt(options.offsetSeconds),
143 updatedAt: isoAt(options.offsetSeconds + 1),
144 };
146​
147function createSnapshotForTargetUser(options: {
148 targetMessageId: MessageId;
149 targetText: string;
150 targetAttachmentCount?: number;
151}): OrchestrationReadModel {
152 const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
153​
154 for (let index = 0; index < 22; index += 1) {
155 const isTarget = index === 3;
156 const userId = `msg-user-${index}` as MessageId;
157 const assistantId = `msg-assistant-${index}` as MessageId;
158 const attachments =
159 isTarget && (options.targetAttachmentCount ?? 0) > 0
160 ? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({
161 type: "image" as const,
162 id: `attachment-${attachmentIndex + 1}`,
163 name: `attachment-${attachmentIndex + 1}.png`,
164 mimeType: "image/png",
165 sizeBytes: 128,
166 }))
167 : undefined;
168​
169 messages.push(
170 createUserMessage({
171 id: isTarget ? options.targetMessageId : userId,
172 text: isTarget ? options.targetText : `filler user message ${index}`,
173 offsetSeconds: messages.length * 3,
174 ...(attachments ? { attachments } : {}),
175 }),
176 );
177 messages.push(
178 createAssistantMessage({
179 id: assistantId,
180 text: `assistant filler ${index}`,
181 offsetSeconds: messages.length * 3,
182 }),
183 );
184 }
185​
186 return {
187 snapshotSequence: 1,
188 projects: [
189 {
190 id: PROJECT_ID,
191 title: "Project",
192 workspaceRoot: "/repo/project",
193 defaultModel: "gpt-5",
194 scripts: [],
195 createdAt: NOW_ISO,
196 updatedAt: NOW_ISO,
197 deletedAt: null,
198 },
199 ],
200 threads: [
201 {
202 id: THREAD_ID,
203 projectId: PROJECT_ID,
204 title: "Browser test thread",
205 model: "gpt-5",
206 interactionMode: "default",
207 runtimeMode: "full-access",
208 branch: "main",
209 worktreePath: null,
210 latestTurn: null,
211 createdAt: NOW_ISO,
212 updatedAt: NOW_ISO,
213 deletedAt: null,
214 messages,
215 activities: [],
216 proposedPlans: [],
217 checkpoints: [],
218 session: {
219 threadId: THREAD_ID,
220 status: "ready",
221 providerName: "codex",
222 runtimeMode: "full-access",
223 activeTurnId: null,
224 lastError: null,
225 updatedAt: NOW_ISO,
226 },
227 },
228 ],
229 updatedAt: NOW_ISO,
230 };
232​
233function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
234 return {
235 snapshot,
236 serverConfig: createBaseServerConfig(),
237 welcome: {
238 cwd: "/repo/project",
239 projectName: "Project",
240 bootstrapProjectId: PROJECT_ID,
241 bootstrapThreadId: THREAD_ID,
242 },
243 };
245​
246function resolveWsRpc(tag: string): unknown {
247 if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
248 return fixture.snapshot;
249 }
250 if (tag === WS_METHODS.serverGetConfig) {
251 return fixture.serverConfig;
252 }
253 if (tag === WS_METHODS.gitListBranches) {
254 return {
255 isRepo: true,
256 branches: [
257 {
258 name: "main",
259 current: true,
260 isDefault: true,
261 worktreePath: null,
262 },
263 ],
264 };
265 }
266 if (tag === WS_METHODS.gitStatus) {
267 return {
268 branch: "main",
269 hasWorkingTreeChanges: false,
270 workingTree: {
271 files: [],
272 insertions: 0,
273 deletions: 0,
274 },
275 hasUpstream: true,
276 aheadCount: 0,
277 behindCount: 0,
278 pr: null,
279 };
280 }
281 if (tag === WS_METHODS.projectsSearchEntries) {
282 return {
283 entries: [],
284 truncated: false,
285 };
286 }
287 return {};
289​
290const worker = setupWorker(
291 wsLink.addEventListener("connection", ({ client }) => {
292 client.send(
293 JSON.stringify({
294 type: "push",
295 channel: WS_CHANNELS.serverWelcome,
296 data: fixture.welcome,
297 }),
298 );
299 client.addEventListener("message", (event) => {
300 const rawData = event.data;
301 if (typeof rawData !== "string") return;
302 let request: WsRequestEnvelope;
303 try {
304 request = JSON.parse(rawData) as WsRequestEnvelope;
305 } catch {
306 return;
307 }
308 const method = request.body?._tag;
309 if (typeof method !== "string") return;
310 client.send(
311 JSON.stringify({
312 id: request.id,
313 result: resolveWsRpc(method),
314 }),
315 );
316 });
317 }),
318 http.get("*/attachments/:attachmentId", () =>
319 HttpResponse.text(ATTACHMENT_SVG, {
320 headers: {
321 "Content-Type": "image/svg+xml",
322 },
323 }),
324 ),
325 http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
326);
327​
328async function nextFrame(): Promise<void> {
329 await new Promise<void>((resolve) => {
330 window.requestAnimationFrame(() => resolve());
331 });
333​
334async function waitForLayout(): Promise<void> {
335 await nextFrame();
336 await nextFrame();
337 await nextFrame();
339​
340async function setViewport(viewport: ViewportSpec): Promise<void> {
341 await page.viewport(viewport.width, viewport.height);
342 await waitForLayout();
344​
345async function waitForProductionStyles(): Promise<void> {
346 await vi.waitFor(
347 () => {
348 expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).not.toBe(
349 "",
350 );
351 expect(getComputedStyle(document.body).marginTop).toBe("0px");
352 },
353 {
354 timeout: 4_000,
355 interval: 16,
356 },
357 );
359​
360async function waitForElement<T extends Element>(
361 query: () => T | null,
362 errorMessage: string,
363): Promise<T> {
364 let element: T | null = null;
365 await vi.waitFor(
366 () => {
367 element = query();
368 expect(element, errorMessage).toBeTruthy();
369 },
370 {
371 timeout: 8_000,
372 interval: 16,
373 },
374 );
375 if (!element) {
376 throw new Error(errorMessage);
377 }
378 return element;
380​
381async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
382 const images = Array.from(scope.querySelectorAll("img"));
383 if (images.length === 0) {
384 return;
385 }
386 await Promise.all(
387 images.map(
388 (image) =>
389 new Promise<void>((resolve) => {
390 if (image.complete) {
391 resolve();
392 return;
393 }
394 image.addEventListener("load", () => resolve(), { once: true });
395 image.addEventListener("error", () => resolve(), { once: true });
396 }),
397 ),
398 );
399 await waitForLayout();
401​
402async function measureUserRow(options: {
403 host: HTMLElement;
404 targetMessageId: MessageId;
405}): Promise<UserRowMeasurement> {
406 const { host, targetMessageId } = options;
407 const rowSelector = `[data-message-id="${targetMessageId}"][data-message-role="user"]`;
408​
409 const scrollContainer = await waitForElement(
410 () => host.querySelector<HTMLDivElement>("div.overflow-y-auto.overscroll-y-contain"),
411 "Unable to find ChatView message scroll container.",
412 );
413​
414 let row: HTMLElement | null = null;
415 await vi.waitFor(
416 async () => {
417 scrollContainer.scrollTop = 0;
418 scrollContainer.dispatchEvent(new Event("scroll"));
419 await waitForLayout();
420 row = host.querySelector<HTMLElement>(rowSelector);
421 expect(row, "Unable to locate targeted user message row.").toBeTruthy();
422 },
423 {
424 timeout: 8_000,
425 interval: 16,
426 },
427 );
428​
429 await waitForImagesToLoad(row!);
430 scrollContainer.scrollTop = 0;
431 scrollContainer.dispatchEvent(new Event("scroll"));
432 await nextFrame();
433​
434 const timelineRoot =
435 row!.closest<HTMLElement>('[data-timeline-root="true"]') ??
436 host.querySelector<HTMLElement>('[data-timeline-root="true"]');
437 if (!(timelineRoot instanceof HTMLElement)) {
438 throw new Error("Unable to locate timeline root container.");
439 }
440​
441 let timelineWidthMeasuredPx = 0;
442 let measuredRowHeightPx = 0;
443 let renderedInVirtualizedRegion = false;
444 await vi.waitFor(
445 async () => {
446 scrollContainer.scrollTop = 0;
447 scrollContainer.dispatchEvent(new Event("scroll"));
448 await nextFrame();
449 const measuredRow = host.querySelector<HTMLElement>(rowSelector);
450 expect(measuredRow, "Unable to measure targeted user row height.").toBeTruthy();
451 timelineWidthMeasuredPx = timelineRoot.getBoundingClientRect().width;
452 measuredRowHeightPx = measuredRow!.getBoundingClientRect().height;
453 renderedInVirtualizedRegion = measuredRow!.closest("[data-index]") instanceof HTMLElement;
454 expect(timelineWidthMeasuredPx, "Unable to measure timeline width.").toBeGreaterThan(0);
455 expect(measuredRowHeightPx, "Unable to measure targeted user row height.").toBeGreaterThan(0);
456 },
457 {
458 timeout: 4_000,
459 interval: 16,
460 },
461 );
462​
463 return { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion };
465​
466async function mountChatView(options: {
467 viewport: ViewportSpec;
468 snapshot: OrchestrationReadModel;
469}): Promise<MountedChatView> {
470 fixture = buildFixture(options.snapshot);
471 await setViewport(options.viewport);
472 await waitForProductionStyles();
473​
474 const host = document.createElement("div");
475 host.style.position = "fixed";
476 host.style.inset = "0";
477 host.style.width = "100vw";
478 host.style.height = "100vh";
479 host.style.display = "grid";
480 host.style.overflow = "hidden";
481 document.body.append(host);
482​
483 const router = getRouter(
484 createMemoryHistory({
485 initialEntries: [`/${THREAD_ID}`],
486 }),
487 );
488​
489 const screen = await render(<RouterProvider router={router} />, {
490 container: host,
491 });
492​
493 await waitForLayout();
494​
495 return {
496 cleanup: async () => {
497 await screen.unmount();
498 host.remove();
499 },
500 measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
501 setViewport: async (viewport: ViewportSpec) => {
502 await setViewport(viewport);
503 await waitForProductionStyles();
504 },
505 };
507​
508async function measureUserRowAtViewport(options: {
509 snapshot: OrchestrationReadModel;
510 targetMessageId: MessageId;
511 viewport: ViewportSpec;
512}): Promise<UserRowMeasurement> {
513 const mounted = await mountChatView({
514 viewport: options.viewport,
515 snapshot: options.snapshot,
516 });
517​
518 try {
519 return await mounted.measureUserRow(options.targetMessageId);
520 } finally {
521 await mounted.cleanup();
522 }
524​
525describe("ChatView timeline estimator parity (full app)", () => {
526 beforeAll(async () => {
527 fixture = buildFixture(
528 createSnapshotForTargetUser({
529 targetMessageId: "msg-user-bootstrap" as MessageId,
530 targetText: "bootstrap",
531 }),
532 );
533 await worker.start({
534 onUnhandledRequest: "bypass",
535 quiet: true,
536 serviceWorker: {
537 url: "/mockServiceWorker.js",
538 },
539 });
540 });
541​
542 afterAll(async () => {
543 await worker.stop();
544 });
545​
546 beforeEach(async () => {
547 await setViewport(DEFAULT_VIEWPORT);
548 localStorage.clear();
549 document.body.innerHTML = "";
550 useStore.setState({
551 projects: [],
552 threads: [],
553 threadsHydrated: false,
554 });
555 });
556​
557 afterEach(() => {
558 document.body.innerHTML = "";
559 });
560​
561 it.each(TEXT_VIEWPORT_MATRIX)(
562 "keeps long user message estimate close at the $name viewport",
563 async (viewport) => {
564 const userText = "x".repeat(3_200);
565 const targetMessageId = `msg-user-target-long-${viewport.name}` as MessageId;
566 const mounted = await mountChatView({
567 viewport,
568 snapshot: createSnapshotForTargetUser({
569 targetMessageId,
570 targetText: userText,
571 }),
572 });
573​
574 try {
575 const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
576 await mounted.measureUserRow(targetMessageId);
577​
578 expect(renderedInVirtualizedRegion).toBe(true);
579​
580 const estimatedHeightPx = estimateTimelineMessageHeight(
581 { role: "user", text: userText, attachments: [] },
582 { timelineWidthPx: timelineWidthMeasuredPx },
583 );
584​
585 expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
586 viewport.textTolerancePx,
587 );
588 } finally {
589 await mounted.cleanup();
590 }
591 },
592 );
593​
594 it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
595 const userText = "x".repeat(3_200);
596 const targetMessageId = "msg-user-target-resize" as MessageId;
597 const mounted = await mountChatView({
598 viewport: TEXT_VIEWPORT_MATRIX[0],
599 snapshot: createSnapshotForTargetUser({
600 targetMessageId,
601 targetText: userText,
602 }),
603 });
604​
605 try {
606 const measurements: Array<UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }> = [];
607​
608 for (const viewport of TEXT_VIEWPORT_MATRIX) {
609 await mounted.setViewport(viewport);
610 const measurement = await mounted.measureUserRow(targetMessageId);
611 const estimatedHeightPx = estimateTimelineMessageHeight(
612 { role: "user", text: userText, attachments: [] },
613 { timelineWidthPx: measurement.timelineWidthMeasuredPx },
614 );
615​
616 expect(measurement.renderedInVirtualizedRegion).toBe(true);
617 expect(Math.abs(measurement.measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
618 viewport.textTolerancePx,
619 );
620 measurements.push({ ...measurement, viewport, estimatedHeightPx });
621 }
622​
623 expect(new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx))).size).toBeGreaterThanOrEqual(3);
624​
625 const byMeasuredWidth = measurements.toSorted(
626 (left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,
627 );
628 const narrowest = byMeasuredWidth[0]!;
629 const widest = byMeasuredWidth.at(-1)!;
630 expect(narrowest.timelineWidthMeasuredPx).toBeLessThan(widest.timelineWidthMeasuredPx);
631 expect(narrowest.measuredRowHeightPx).toBeGreaterThan(widest.measuredRowHeightPx);
632 expect(narrowest.estimatedHeightPx).toBeGreaterThan(widest.estimatedHeightPx);
633 } finally {
634 await mounted.cleanup();
635 }
636 });
637​
638 it("tracks additional rendered wrapping when ChatView width narrows between desktop and mobile viewports", async () => {
639 const userText = "x".repeat(2_400);
640 const targetMessageId = "msg-user-target-wrap" as MessageId;
641 const snapshot = createSnapshotForTargetUser({
642 targetMessageId,
643 targetText: userText,
644 });
645 const desktopMeasurement = await measureUserRowAtViewport({
646 viewport: TEXT_VIEWPORT_MATRIX[0],
647 snapshot,
648 targetMessageId,
649 });
650 const mobileMeasurement = await measureUserRowAtViewport({
651 viewport: TEXT_VIEWPORT_MATRIX[2],
652 snapshot,
653 targetMessageId,
654 });
655​
656 const estimatedDesktopPx = estimateTimelineMessageHeight(
657 { role: "user", text: userText, attachments: [] },
658 { timelineWidthPx: desktopMeasurement.timelineWidthMeasuredPx },
659 );
660 const estimatedMobilePx = estimateTimelineMessageHeight(
661 { role: "user", text: userText, attachments: [] },
662 { timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },
663 );
664​
665 const measuredDeltaPx = mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
666 const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;
667 expect(measuredDeltaPx).toBeGreaterThan(0);
668 expect(estimatedDeltaPx).toBeGreaterThan(0);
669 const ratio = estimatedDeltaPx / measuredDeltaPx;
670 expect(ratio).toBeGreaterThan(0.65);
671 expect(ratio).toBeLessThan(1.35);
672 });
673​
674 it.each(ATTACHMENT_VIEWPORT_MATRIX)(
675 "keeps user attachment estimate close at the $name viewport",
676 async (viewport) => {
677 const targetMessageId = `msg-user-target-attachments-${viewport.name}` as MessageId;
678 const userText = "message with image attachments";
679 const mounted = await mountChatView({
680 viewport,
681 snapshot: createSnapshotForTargetUser({
682 targetMessageId,
683 targetText: userText,
684 targetAttachmentCount: 3,
685 }),
686 });
687​
688 try {
689 const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
690 await mounted.measureUserRow(targetMessageId);
691​
692 expect(renderedInVirtualizedRegion).toBe(true);
693​
694 const estimatedHeightPx = estimateTimelineMessageHeight(
695 {
696 role: "user",
697 text: userText,
698 attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
699 },
700 { timelineWidthPx: timelineWidthMeasuredPx },
701 );
702​
703 expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
704 viewport.attachmentTolerancePx,
705 );
706 } finally {
707 await mounted.cleanup();
708 }
709 },
710 );
711});