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

ChatView.browser.tsx

1,250 lines36.7 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 OrchestrationSessionStatus,
15} from "@t3tools/contracts";
16import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
17import { HttpResponse, http, ws } from "msw";
18import { setupWorker } from "msw/browser";
19import { page } from "vitest/browser";
20import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
21import { render } from "vitest-browser-react";
22​
23import { useComposerDraftStore } from "../composerDraftStore";
24import { isMacPlatform } from "../lib/utils";
25import { getRouter } from "../router";
26import { useStore } from "../store";
27import { estimateTimelineMessageHeight } from "./timelineHeight";
28​
29const THREAD_ID = "thread-browser-test" as ThreadId;
30const UUID_ROUTE_RE = /^\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
31const PROJECT_ID = "project-1" as ProjectId;
32const NOW_ISO = "2026-03-04T12:00:00.000Z";
33const BASE_TIME_MS = Date.parse(NOW_ISO);
34const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
35​
36interface WsRequestEnvelope {
37 id: string;
38 body: {
39 _tag: string;
40 [key: string]: unknown;
41 };
43​
44interface TestFixture {
45 snapshot: OrchestrationReadModel;
46 serverConfig: ServerConfig;
47 welcome: WsWelcomePayload;
49​
50let fixture: TestFixture;
51const wsRequests: WsRequestEnvelope["body"][] = [];
52const wsLink = ws.link(/ws(s)?:\/\/.*/);
53​
54interface ViewportSpec {
55 name: string;
56 width: number;
57 height: number;
58 textTolerancePx: number;
59 attachmentTolerancePx: number;
61​
62const DEFAULT_VIEWPORT: ViewportSpec = {
63 name: "desktop",
64 width: 960,
65 height: 1_100,
66 textTolerancePx: 44,
67 attachmentTolerancePx: 56,
68};
69const TEXT_VIEWPORT_MATRIX = [
70 DEFAULT_VIEWPORT,
71 { name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 },
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[];
75const ATTACHMENT_VIEWPORT_MATRIX = [
76 DEFAULT_VIEWPORT,
77 { name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
78 { name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
79] as const satisfies readonly ViewportSpec[];
80​
81interface UserRowMeasurement {
82 measuredRowHeightPx: number;
83 timelineWidthMeasuredPx: number;
84 renderedInVirtualizedRegion: boolean;
86​
87interface MountedChatView {
88 cleanup: () => Promise<void>;
89 measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
90 setViewport: (viewport: ViewportSpec) => Promise<void>;
91 router: ReturnType<typeof getRouter>;
93​
94function isoAt(offsetSeconds: number): string {
95 return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString();
97​
98function createBaseServerConfig(): ServerConfig {
99 return {
100 cwd: "/repo/project",
101 keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
102 keybindings: [],
103 issues: [],
104 providers: [
105 {
106 provider: "codex",
107 status: "ready",
108 available: true,
109 authStatus: "authenticated",
110 checkedAt: NOW_ISO,
111 },
112 ],
113 availableEditors: [],
114 };
116​
117function createUserMessage(options: {
118 id: MessageId;
119 text: string;
120 offsetSeconds: number;
121 attachments?: Array<{
122 type: "image";
123 id: string;
124 name: string;
125 mimeType: string;
126 sizeBytes: number;
127 }>;
128}) {
129 return {
130 id: options.id,
131 role: "user" as const,
132 text: options.text,
133 ...(options.attachments ? { attachments: options.attachments } : {}),
134 turnId: null,
135 streaming: false,
136 createdAt: isoAt(options.offsetSeconds),
137 updatedAt: isoAt(options.offsetSeconds + 1),
138 };
140​
141function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) {
142 return {
143 id: options.id,
144 role: "assistant" as const,
145 text: options.text,
146 turnId: null,
147 streaming: false,
148 createdAt: isoAt(options.offsetSeconds),
149 updatedAt: isoAt(options.offsetSeconds + 1),
150 };
152​
153function createSnapshotForTargetUser(options: {
154 targetMessageId: MessageId;
155 targetText: string;
156 targetAttachmentCount?: number;
157 sessionStatus?: OrchestrationSessionStatus;
158}): OrchestrationReadModel {
159 const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
160​
161 for (let index = 0; index < 22; index += 1) {
162 const isTarget = index === 3;
163 const userId = `msg-user-${index}` as MessageId;
164 const assistantId = `msg-assistant-${index}` as MessageId;
165 const attachments =
166 isTarget && (options.targetAttachmentCount ?? 0) > 0
167 ? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({
168 type: "image" as const,
169 id: `attachment-${attachmentIndex + 1}`,
170 name: `attachment-${attachmentIndex + 1}.png`,
171 mimeType: "image/png",
172 sizeBytes: 128,
173 }))
174 : undefined;
175​
176 messages.push(
177 createUserMessage({
178 id: isTarget ? options.targetMessageId : userId,
179 text: isTarget ? options.targetText : `filler user message ${index}`,
180 offsetSeconds: messages.length * 3,
181 ...(attachments ? { attachments } : {}),
182 }),
183 );
184 messages.push(
185 createAssistantMessage({
186 id: assistantId,
187 text: `assistant filler ${index}`,
188 offsetSeconds: messages.length * 3,
189 }),
190 );
191 }
192​
193 return {
194 snapshotSequence: 1,
195 projects: [
196 {
197 id: PROJECT_ID,
198 title: "Project",
199 workspaceRoot: "/repo/project",
200 defaultModel: "gpt-5",
201 scripts: [],
202 createdAt: NOW_ISO,
203 updatedAt: NOW_ISO,
204 deletedAt: null,
205 },
206 ],
207 threads: [
208 {
209 id: THREAD_ID,
210 projectId: PROJECT_ID,
211 title: "Browser test thread",
212 model: "gpt-5",
213 interactionMode: "default",
214 runtimeMode: "full-access",
215 branch: "main",
216 worktreePath: null,
217 latestTurn: null,
218 createdAt: NOW_ISO,
219 updatedAt: NOW_ISO,
220 deletedAt: null,
221 messages,
222 activities: [],
223 proposedPlans: [],
224 checkpoints: [],
225 session: {
226 threadId: THREAD_ID,
227 status: options.sessionStatus ?? "ready",
228 providerName: "codex",
229 runtimeMode: "full-access",
230 activeTurnId: null,
231 lastError: null,
232 updatedAt: NOW_ISO,
233 },
234 },
235 ],
236 updatedAt: NOW_ISO,
237 };
239​
240function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
241 return {
242 snapshot,
243 serverConfig: createBaseServerConfig(),
244 welcome: {
245 cwd: "/repo/project",
246 projectName: "Project",
247 bootstrapProjectId: PROJECT_ID,
248 bootstrapThreadId: THREAD_ID,
249 },
250 };
252​
253function addThreadToSnapshot(
254 snapshot: OrchestrationReadModel,
255 threadId: ThreadId,
256): OrchestrationReadModel {
257 return {
258 ...snapshot,
259 snapshotSequence: snapshot.snapshotSequence + 1,
260 threads: [
261 ...snapshot.threads,
262 {
263 id: threadId,
264 projectId: PROJECT_ID,
265 title: "New thread",
266 model: "gpt-5",
267 interactionMode: "default",
268 runtimeMode: "full-access",
269 branch: "main",
270 worktreePath: null,
271 latestTurn: null,
272 createdAt: NOW_ISO,
273 updatedAt: NOW_ISO,
274 deletedAt: null,
275 messages: [],
276 activities: [],
277 proposedPlans: [],
278 checkpoints: [],
279 session: {
280 threadId,
281 status: "ready",
282 providerName: "codex",
283 runtimeMode: "full-access",
284 activeTurnId: null,
285 lastError: null,
286 updatedAt: NOW_ISO,
287 },
288 },
289 ],
290 };
292​
293function createDraftOnlySnapshot(): OrchestrationReadModel {
294 const snapshot = createSnapshotForTargetUser({
295 targetMessageId: "msg-user-draft-target" as MessageId,
296 targetText: "draft thread",
297 });
298 return {
299 ...snapshot,
300 threads: [],
301 };
303​
304function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
305 const snapshot = createSnapshotForTargetUser({
306 targetMessageId: "msg-user-plan-target" as MessageId,
307 targetText: "plan thread",
308 });
309 const planMarkdown = [
310 "# Ship plan mode follow-up",
311 "",
312 "- Step 1: capture the thread-open trace",
313 "- Step 2: identify the main-thread bottleneck",
314 "- Step 3: keep collapsed cards cheap",
315 "- Step 4: render the full markdown only on demand",
316 "- Step 5: preserve export and save actions",
317 "- Step 6: add regression coverage",
318 "- Step 7: verify route transitions stay responsive",
319 "- Step 8: confirm no server-side work changed",
320 "- Step 9: confirm short plans still render normally",
321 "- Step 10: confirm long plans stay collapsed by default",
322 "- Step 11: confirm preview text is still useful",
323 "- Step 12: confirm plan follow-up flow still works",
324 "- Step 13: confirm timeline virtualization still behaves",
325 "- Step 14: confirm theme styling still looks correct",
326 "- Step 15: confirm save dialog behavior is unchanged",
327 "- Step 16: confirm download behavior is unchanged",
328 "- Step 17: confirm code fences do not parse until expand",
329 "- Step 18: confirm preview truncation ends cleanly",
330 "- Step 19: confirm markdown links still open in editor after expand",
331 "- Step 20: confirm deep hidden detail only appears after expand",
332 "",
333 "```ts",
334 "export const hiddenPlanImplementationDetail = 'deep hidden detail only after expand';",
335 "```",
336 ].join("\n");
337​
338 return {
339 ...snapshot,
340 threads: snapshot.threads.map((thread) =>
341 thread.id === THREAD_ID
342 ? Object.assign({}, thread, {
343 proposedPlans: [
344 {
345 id: "plan-browser-test",
346 turnId: null,
347 planMarkdown,
348 createdAt: isoAt(1_000),
349 updatedAt: isoAt(1_001),
350 },
351 ],
352 updatedAt: isoAt(1_001),
353 })
354 : thread,
355 ),
356 };
358​
359function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
360 const tag = body._tag;
361 if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
362 return fixture.snapshot;
363 }
364 if (tag === WS_METHODS.serverGetConfig) {
365 return fixture.serverConfig;
366 }
367 if (tag === WS_METHODS.gitListBranches) {
368 return {
369 isRepo: true,
370 hasOriginRemote: true,
371 branches: [
372 {
373 name: "main",
374 current: true,
375 isDefault: true,
376 worktreePath: null,
377 },
378 ],
379 };
380 }
381 if (tag === WS_METHODS.gitStatus) {
382 return {
383 branch: "main",
384 hasWorkingTreeChanges: false,
385 workingTree: {
386 files: [],
387 insertions: 0,
388 deletions: 0,
389 },
390 hasUpstream: true,
391 aheadCount: 0,
392 behindCount: 0,
393 pr: null,
394 };
395 }
396 if (tag === WS_METHODS.projectsSearchEntries) {
397 return {
398 entries: [],
399 truncated: false,
400 };
401 }
402 if (tag === WS_METHODS.terminalOpen) {
403 return {
404 threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID,
405 terminalId: typeof body.terminalId === "string" ? body.terminalId : "default",
406 cwd: typeof body.cwd === "string" ? body.cwd : "/repo/project",
407 status: "running",
408 pid: 123,
409 history: "",
410 exitCode: null,
411 exitSignal: null,
412 updatedAt: NOW_ISO,
413 };
414 }
415 return {};
417​
418const worker = setupWorker(
419 wsLink.addEventListener("connection", ({ client }) => {
420 client.send(
421 JSON.stringify({
422 type: "push",
423 sequence: 1,
424 channel: WS_CHANNELS.serverWelcome,
425 data: fixture.welcome,
426 }),
427 );
428 client.addEventListener("message", (event) => {
429 const rawData = event.data;
430 if (typeof rawData !== "string") return;
431 let request: WsRequestEnvelope;
432 try {
433 request = JSON.parse(rawData) as WsRequestEnvelope;
434 } catch {
435 return;
436 }
437 const method = request.body?._tag;
438 if (typeof method !== "string") return;
439 wsRequests.push(request.body);
440 client.send(
441 JSON.stringify({
442 id: request.id,
443 result: resolveWsRpc(request.body),
444 }),
445 );
446 });
447 }),
448 http.get("*/attachments/:attachmentId", () =>
449 HttpResponse.text(ATTACHMENT_SVG, {
450 headers: {
451 "Content-Type": "image/svg+xml",
452 },
453 }),
454 ),
455 http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
456);
457​
458async function nextFrame(): Promise<void> {
459 await new Promise<void>((resolve) => {
460 window.requestAnimationFrame(() => resolve());
461 });
463​
464async function waitForLayout(): Promise<void> {
465 await nextFrame();
466 await nextFrame();
467 await nextFrame();
469​
470async function setViewport(viewport: ViewportSpec): Promise<void> {
471 await page.viewport(viewport.width, viewport.height);
472 await waitForLayout();
474​
475async function waitForProductionStyles(): Promise<void> {
476 await vi.waitFor(
477 () => {
478 expect(
479 getComputedStyle(document.documentElement).getPropertyValue("--background").trim(),
480 ).not.toBe("");
481 expect(getComputedStyle(document.body).marginTop).toBe("0px");
482 },
483 {
484 timeout: 4_000,
485 interval: 16,
486 },
487 );
489​
490async function waitForElement<T extends Element>(
491 query: () => T | null,
492 errorMessage: string,
493): Promise<T> {
494 let element: T | null = null;
495 await vi.waitFor(
496 () => {
497 element = query();
498 expect(element, errorMessage).toBeTruthy();
499 },
500 {
501 timeout: 8_000,
502 interval: 16,
503 },
504 );
505 if (!element) {
506 throw new Error(errorMessage);
507 }
508 return element;
510​
511async function waitForURL(
512 router: ReturnType<typeof getRouter>,
513 predicate: (pathname: string) => boolean,
514 errorMessage: string,
515): Promise<string> {
516 let pathname = "";
517 await vi.waitFor(
518 () => {
519 pathname = router.state.location.pathname;
520 expect(predicate(pathname), errorMessage).toBe(true);
521 },
522 { timeout: 8_000, interval: 16 },
523 );
524 return pathname;
526​
527async function waitForComposerEditor(): Promise<HTMLElement> {
528 return waitForElement(
529 () => document.querySelector<HTMLElement>('[contenteditable="true"]'),
530 "Unable to find composer editor.",
531 );
533​
534async function waitForInteractionModeButton(
535 expectedLabel: "Chat" | "Plan",
536): Promise<HTMLButtonElement> {
537 return waitForElement(
538 () =>
539 Array.from(document.querySelectorAll("button")).find(
540 (button) => button.textContent?.trim() === expectedLabel,
541 ) as HTMLButtonElement | null,
542 `Unable to find ${expectedLabel} interaction mode button.`,
543 );
545​
546async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
547 const images = Array.from(scope.querySelectorAll("img"));
548 if (images.length === 0) {
549 return;
550 }
551 await Promise.all(
552 images.map(
553 (image) =>
554 new Promise<void>((resolve) => {
555 if (image.complete) {
556 resolve();
557 return;
558 }
559 image.addEventListener("load", () => resolve(), { once: true });
560 image.addEventListener("error", () => resolve(), { once: true });
561 }),
562 ),
563 );
564 await waitForLayout();
566​
567async function measureUserRow(options: {
568 host: HTMLElement;
569 targetMessageId: MessageId;
570}): Promise<UserRowMeasurement> {
571 const { host, targetMessageId } = options;
572 const rowSelector = `[data-message-id="${targetMessageId}"][data-message-role="user"]`;
573​
574 const scrollContainer = await waitForElement(
575 () => host.querySelector<HTMLDivElement>("div.overflow-y-auto.overscroll-y-contain"),
576 "Unable to find ChatView message scroll container.",
577 );
578​
579 let row: HTMLElement | null = null;
580 await vi.waitFor(
581 async () => {
582 scrollContainer.scrollTop = 0;
583 scrollContainer.dispatchEvent(new Event("scroll"));
584 await waitForLayout();
585 row = host.querySelector<HTMLElement>(rowSelector);
586 expect(row, "Unable to locate targeted user message row.").toBeTruthy();
587 },
588 {
589 timeout: 8_000,
590 interval: 16,
591 },
592 );
593​
594 await waitForImagesToLoad(row!);
595 scrollContainer.scrollTop = 0;
596 scrollContainer.dispatchEvent(new Event("scroll"));
597 await nextFrame();
598​
599 const timelineRoot =
600 row!.closest<HTMLElement>('[data-timeline-root="true"]') ??
601 host.querySelector<HTMLElement>('[data-timeline-root="true"]');
602 if (!(timelineRoot instanceof HTMLElement)) {
603 throw new Error("Unable to locate timeline root container.");
604 }
605​
606 let timelineWidthMeasuredPx = 0;
607 let measuredRowHeightPx = 0;
608 let renderedInVirtualizedRegion = false;
609 await vi.waitFor(
610 async () => {
611 scrollContainer.scrollTop = 0;
612 scrollContainer.dispatchEvent(new Event("scroll"));
613 await nextFrame();
614 const measuredRow = host.querySelector<HTMLElement>(rowSelector);
615 expect(measuredRow, "Unable to measure targeted user row height.").toBeTruthy();
616 timelineWidthMeasuredPx = timelineRoot.getBoundingClientRect().width;
617 measuredRowHeightPx = measuredRow!.getBoundingClientRect().height;
618 renderedInVirtualizedRegion = measuredRow!.closest("[data-index]") instanceof HTMLElement;
619 expect(timelineWidthMeasuredPx, "Unable to measure timeline width.").toBeGreaterThan(0);
620 expect(measuredRowHeightPx, "Unable to measure targeted user row height.").toBeGreaterThan(0);
621 },
622 {
623 timeout: 4_000,
624 interval: 16,
625 },
626 );
627​
628 return { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion };
630​
631async function mountChatView(options: {
632 viewport: ViewportSpec;
633 snapshot: OrchestrationReadModel;
634 configureFixture?: (fixture: TestFixture) => void;
635}): Promise<MountedChatView> {
636 fixture = buildFixture(options.snapshot);
637 options.configureFixture?.(fixture);
638 await setViewport(options.viewport);
639 await waitForProductionStyles();
640​
641 const host = document.createElement("div");
642 host.style.position = "fixed";
643 host.style.inset = "0";
644 host.style.width = "100vw";
645 host.style.height = "100vh";
646 host.style.display = "grid";
647 host.style.overflow = "hidden";
648 document.body.append(host);
649​
650 const router = getRouter(
651 createMemoryHistory({
652 initialEntries: [`/${THREAD_ID}`],
653 }),
654 );
655​
656 const screen = await render(<RouterProvider router={router} />, {
657 container: host,
658 });
659​
660 await waitForLayout();
661​
662 return {
663 cleanup: async () => {
664 await screen.unmount();
665 host.remove();
666 },
667 measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
668 setViewport: async (viewport: ViewportSpec) => {
669 await setViewport(viewport);
670 await waitForProductionStyles();
671 },
672 router,
673 };
675​
676async function measureUserRowAtViewport(options: {
677 snapshot: OrchestrationReadModel;
678 targetMessageId: MessageId;
679 viewport: ViewportSpec;
680}): Promise<UserRowMeasurement> {
681 const mounted = await mountChatView({
682 viewport: options.viewport,
683 snapshot: options.snapshot,
684 });
685​
686 try {
687 return await mounted.measureUserRow(options.targetMessageId);
688 } finally {
689 await mounted.cleanup();
690 }
692​
693describe("ChatView timeline estimator parity (full app)", () => {
694 beforeAll(async () => {
695 fixture = buildFixture(
696 createSnapshotForTargetUser({
697 targetMessageId: "msg-user-bootstrap" as MessageId,
698 targetText: "bootstrap",
699 }),
700 );
701 await worker.start({
702 onUnhandledRequest: "bypass",
703 quiet: true,
704 serviceWorker: {
705 url: "/mockServiceWorker.js",
706 },
707 });
708 });
709​
710 afterAll(async () => {
711 await worker.stop();
712 });
713​
714 beforeEach(async () => {
715 await setViewport(DEFAULT_VIEWPORT);
716 localStorage.clear();
717 document.body.innerHTML = "";
718 wsRequests.length = 0;
719 useComposerDraftStore.setState({
720 draftsByThreadId: {},
721 draftThreadsByThreadId: {},
722 projectDraftThreadIdByProjectId: {},
723 });
724 useStore.setState({
725 projects: [],
726 threads: [],
727 threadsHydrated: false,
728 });
729 });
730​
731 afterEach(() => {
732 document.body.innerHTML = "";
733 });
734​
735 it.each(TEXT_VIEWPORT_MATRIX)(
736 "keeps long user message estimate close at the $name viewport",
737 async (viewport) => {
738 const userText = "x".repeat(3_200);
739 const targetMessageId = `msg-user-target-long-${viewport.name}` as MessageId;
740 const mounted = await mountChatView({
741 viewport,
742 snapshot: createSnapshotForTargetUser({
743 targetMessageId,
744 targetText: userText,
745 }),
746 });
747​
748 try {
749 const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
750 await mounted.measureUserRow(targetMessageId);
751​
752 expect(renderedInVirtualizedRegion).toBe(true);
753​
754 const estimatedHeightPx = estimateTimelineMessageHeight(
755 { role: "user", text: userText, attachments: [] },
756 { timelineWidthPx: timelineWidthMeasuredPx },
757 );
758​
759 expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
760 viewport.textTolerancePx,
761 );
762 } finally {
763 await mounted.cleanup();
764 }
765 },
766 );
767​
768 it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
769 const userText = "x".repeat(3_200);
770 const targetMessageId = "msg-user-target-resize" as MessageId;
771 const mounted = await mountChatView({
772 viewport: TEXT_VIEWPORT_MATRIX[0],
773 snapshot: createSnapshotForTargetUser({
774 targetMessageId,
775 targetText: userText,
776 }),
777 });
778​
779 try {
780 const measurements: Array<
781 UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }
782 > = [];
783​
784 for (const viewport of TEXT_VIEWPORT_MATRIX) {
785 await mounted.setViewport(viewport);
786 const measurement = await mounted.measureUserRow(targetMessageId);
787 const estimatedHeightPx = estimateTimelineMessageHeight(
788 { role: "user", text: userText, attachments: [] },
789 { timelineWidthPx: measurement.timelineWidthMeasuredPx },
790 );
791​
792 expect(measurement.renderedInVirtualizedRegion).toBe(true);
793 expect(Math.abs(measurement.measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
794 viewport.textTolerancePx,
795 );
796 measurements.push({ ...measurement, viewport, estimatedHeightPx });
797 }
798​
799 expect(
800 new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx)))
801 .size,
802 ).toBeGreaterThanOrEqual(3);
803​
804 const byMeasuredWidth = measurements.toSorted(
805 (left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,
806 );
807 const narrowest = byMeasuredWidth[0]!;
808 const widest = byMeasuredWidth.at(-1)!;
809 expect(narrowest.timelineWidthMeasuredPx).toBeLessThan(widest.timelineWidthMeasuredPx);
810 expect(narrowest.measuredRowHeightPx).toBeGreaterThan(widest.measuredRowHeightPx);
811 expect(narrowest.estimatedHeightPx).toBeGreaterThan(widest.estimatedHeightPx);
812 } finally {
813 await mounted.cleanup();
814 }
815 });
816​
817 it("tracks additional rendered wrapping when ChatView width narrows between desktop and mobile viewports", async () => {
818 const userText = "x".repeat(2_400);
819 const targetMessageId = "msg-user-target-wrap" as MessageId;
820 const snapshot = createSnapshotForTargetUser({
821 targetMessageId,
822 targetText: userText,
823 });
824 const desktopMeasurement = await measureUserRowAtViewport({
825 viewport: TEXT_VIEWPORT_MATRIX[0],
826 snapshot,
827 targetMessageId,
828 });
829 const mobileMeasurement = await measureUserRowAtViewport({
830 viewport: TEXT_VIEWPORT_MATRIX[2],
831 snapshot,
832 targetMessageId,
833 });
834​
835 const estimatedDesktopPx = estimateTimelineMessageHeight(
836 { role: "user", text: userText, attachments: [] },
837 { timelineWidthPx: desktopMeasurement.timelineWidthMeasuredPx },
838 );
839 const estimatedMobilePx = estimateTimelineMessageHeight(
840 { role: "user", text: userText, attachments: [] },
841 { timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },
842 );
843​
844 const measuredDeltaPx =
845 mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
846 const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;
847 expect(measuredDeltaPx).toBeGreaterThan(0);
848 expect(estimatedDeltaPx).toBeGreaterThan(0);
849 const ratio = estimatedDeltaPx / measuredDeltaPx;
850 expect(ratio).toBeGreaterThan(0.65);
851 expect(ratio).toBeLessThan(1.35);
852 });
853​
854 it.each(ATTACHMENT_VIEWPORT_MATRIX)(
855 "keeps user attachment estimate close at the $name viewport",
856 async (viewport) => {
857 const targetMessageId = `msg-user-target-attachments-${viewport.name}` as MessageId;
858 const userText = "message with image attachments";
859 const mounted = await mountChatView({
860 viewport,
861 snapshot: createSnapshotForTargetUser({
862 targetMessageId,
863 targetText: userText,
864 targetAttachmentCount: 3,
865 }),
866 });
867​
868 try {
869 const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
870 await mounted.measureUserRow(targetMessageId);
871​
872 expect(renderedInVirtualizedRegion).toBe(true);
873​
874 const estimatedHeightPx = estimateTimelineMessageHeight(
875 {
876 role: "user",
877 text: userText,
878 attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
879 },
880 { timelineWidthPx: timelineWidthMeasuredPx },
881 );
882​
883 expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
884 viewport.attachmentTolerancePx,
885 );
886 } finally {
887 await mounted.cleanup();
888 }
889 },
890 );
891​
892 it("opens the project cwd for draft threads without a worktree path", async () => {
893 useComposerDraftStore.setState({
894 draftThreadsByThreadId: {
895 [THREAD_ID]: {
896 projectId: PROJECT_ID,
897 createdAt: NOW_ISO,
898 runtimeMode: "full-access",
899 interactionMode: "default",
900 branch: null,
901 worktreePath: null,
902 envMode: "local",
903 },
904 },
905 projectDraftThreadIdByProjectId: {
906 [PROJECT_ID]: THREAD_ID,
907 },
908 });
909​
910 const mounted = await mountChatView({
911 viewport: DEFAULT_VIEWPORT,
912 snapshot: createDraftOnlySnapshot(),
913 configureFixture: (nextFixture) => {
914 nextFixture.serverConfig = {
915 ...nextFixture.serverConfig,
916 availableEditors: ["vscode"],
917 };
918 },
919 });
920​
921 try {
922 const openButton = await waitForElement(
923 () =>
924 Array.from(document.querySelectorAll("button")).find(
925 (button) => button.textContent?.trim() === "Open",
926 ) as HTMLButtonElement | null,
927 "Unable to find Open button.",
928 );
929 openButton.click();
930​
931 await vi.waitFor(
932 () => {
933 const openRequest = wsRequests.find(
934 (request) => request._tag === WS_METHODS.shellOpenInEditor,
935 );
936 expect(openRequest).toMatchObject({
937 _tag: WS_METHODS.shellOpenInEditor,
938 cwd: "/repo/project",
939 editor: "vscode",
940 });
941 },
942 { timeout: 8_000, interval: 16 },
943 );
944 } finally {
945 await mounted.cleanup();
946 }
947 });
948​
949 it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
950 const mounted = await mountChatView({
951 viewport: DEFAULT_VIEWPORT,
952 snapshot: createSnapshotForTargetUser({
953 targetMessageId: "msg-user-target-hotkey" as MessageId,
954 targetText: "hotkey target",
955 }),
956 });
957​
958 try {
959 const initialModeButton = await waitForInteractionModeButton("Chat");
960 expect(initialModeButton.title).toContain("enter plan mode");
961​
962 window.dispatchEvent(
963 new KeyboardEvent("keydown", {
964 key: "Tab",
965 shiftKey: true,
966 bubbles: true,
967 cancelable: true,
968 }),
969 );
970 await waitForLayout();
971​
972 expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
973​
974 const composerEditor = await waitForComposerEditor();
975 composerEditor.focus();
976 composerEditor.dispatchEvent(
977 new KeyboardEvent("keydown", {
978 key: "Tab",
979 shiftKey: true,
980 bubbles: true,
981 cancelable: true,
982 }),
983 );
984​
985 await vi.waitFor(
986 async () => {
987 expect((await waitForInteractionModeButton("Plan")).title).toContain(
988 "return to normal chat mode",
989 );
990 },
991 { timeout: 8_000, interval: 16 },
992 );
993​
994 composerEditor.dispatchEvent(
995 new KeyboardEvent("keydown", {
996 key: "Tab",
997 shiftKey: true,
998 bubbles: true,
999 cancelable: true,
1000 }),
1001 );
1002​
1003 await vi.waitFor(
1004 async () => {
1005 expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
1006 },
1007 { timeout: 8_000, interval: 16 },
1008 );
1009 } finally {
1010 await mounted.cleanup();
1012 });
1013​
1014 it("shows a pointer cursor for the running stop button", async () => {
1015 const mounted = await mountChatView({
1016 viewport: DEFAULT_VIEWPORT,
1017 snapshot: createSnapshotForTargetUser({
1018 targetMessageId: "msg-user-stop-button-cursor" as MessageId,
1019 targetText: "stop button cursor target",
1020 sessionStatus: "running",
1021 }),
1022 });
1023​
1024 try {
1025 const stopButton = await waitForElement(
1026 () => document.querySelector<HTMLButtonElement>('button[aria-label="Stop generation"]'),
1027 "Unable to find stop generation button.",
1028 );
1029​
1030 expect(getComputedStyle(stopButton).cursor).toBe("pointer");
1031 } finally {
1032 await mounted.cleanup();
1034 });
1035​
1036 it("keeps the new thread selected after clicking the new-thread button", async () => {
1037 const mounted = await mountChatView({
1038 viewport: DEFAULT_VIEWPORT,
1039 snapshot: createSnapshotForTargetUser({
1040 targetMessageId: "msg-user-new-thread-test" as MessageId,
1041 targetText: "new thread selection test",
1042 }),
1043 });
1044​
1045 try {
1046 // Wait for the sidebar to render with the project.
1047 const newThreadButton = page.getByTestId("new-thread-button");
1048 await expect.element(newThreadButton).toBeInTheDocument();
1049​
1050 await newThreadButton.click();
1051​
1052 // The route should change to a new draft thread ID.
1053 const newThreadPath = await waitForURL(
1054 mounted.router,
1055 (path) => UUID_ROUTE_RE.test(path),
1056 "Route should have changed to a new draft thread UUID.",
1057 );
1058 const newThreadId = newThreadPath.slice(1) as ThreadId;
1059​
1060 // The composer editor should be present for the new draft thread.
1061 await waitForComposerEditor();
1062​
1063 // Simulate the snapshot sync arriving from the server after the draft
1064 // thread has been promoted to a server thread (thread.create + turn.start
1065 // succeeded). The snapshot now includes the new thread, and the sync
1066 // should clear the draft without disrupting the route.
1067 const { syncServerReadModel } = useStore.getState();
1068 syncServerReadModel(addThreadToSnapshot(fixture.snapshot, newThreadId));
1069​
1070 // Clear the draft now that the server thread exists (mirrors EventRouter behavior).
1071 useComposerDraftStore.getState().clearDraftThread(newThreadId);
1072​
1073 // The route should still be on the new thread — not redirected away.
1074 await waitForURL(
1075 mounted.router,
1076 (path) => path === newThreadPath,
1077 "New thread should remain selected after snapshot sync clears the draft.",
1078 );
1079​
1080 // The empty thread view and composer should still be visible.
1081 await expect
1082 .element(page.getByText("Send a message to start the conversation."))
1083 .toBeInTheDocument();
1084 await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument();
1085 } finally {
1086 await mounted.cleanup();
1088 });
1089​
1090 it("creates a new thread from the global chat.new shortcut", async () => {
1091 const mounted = await mountChatView({
1092 viewport: DEFAULT_VIEWPORT,
1093 snapshot: createSnapshotForTargetUser({
1094 targetMessageId: "msg-user-chat-shortcut-test" as MessageId,
1095 targetText: "chat shortcut test",
1096 }),
1097 configureFixture: (nextFixture) => {
1098 nextFixture.serverConfig = {
1099 ...nextFixture.serverConfig,
1100 keybindings: [
1102 command: "chat.new",
1103 shortcut: {
1104 key: "o",
1105 metaKey: false,
1106 ctrlKey: false,
1107 shiftKey: true,
1108 altKey: false,
1109 modKey: true,
1110 },
1111 whenAst: {
1112 type: "not",
1113 node: { type: "identifier", name: "terminalFocus" },
1114 },
1115 },
1116 ],
1117 };
1118 },
1119 });
1120​
1121 try {
1122 const useMetaForMod = isMacPlatform(navigator.platform);
1123 window.dispatchEvent(
1124 new KeyboardEvent("keydown", {
1125 key: "o",
1126 shiftKey: true,
1127 metaKey: useMetaForMod,
1128 ctrlKey: !useMetaForMod,
1129 bubbles: true,
1130 cancelable: true,
1131 }),
1132 );
1133​
1134 await waitForURL(
1135 mounted.router,
1136 (path) => UUID_ROUTE_RE.test(path),
1137 "Route should have changed to a new draft thread UUID from the shortcut.",
1138 );
1139 } finally {
1140 await mounted.cleanup();
1142 });
1143​
1144 it("creates a fresh draft after the previous draft thread is promoted", async () => {
1145 const mounted = await mountChatView({
1146 viewport: DEFAULT_VIEWPORT,
1147 snapshot: createSnapshotForTargetUser({
1148 targetMessageId: "msg-user-promoted-draft-shortcut-test" as MessageId,
1149 targetText: "promoted draft shortcut test",
1150 }),
1151 configureFixture: (nextFixture) => {
1152 nextFixture.serverConfig = {
1153 ...nextFixture.serverConfig,
1154 keybindings: [
1156 command: "chat.new",
1157 shortcut: {
1158 key: "o",
1159 metaKey: false,
1160 ctrlKey: false,
1161 shiftKey: true,
1162 altKey: false,
1163 modKey: true,
1164 },
1165 whenAst: {
1166 type: "not",
1167 node: { type: "identifier", name: "terminalFocus" },
1168 },
1169 },
1170 ],
1171 };
1172 },
1173 });
1174​
1175 try {
1176 const newThreadButton = page.getByTestId("new-thread-button");
1177 await expect.element(newThreadButton).toBeInTheDocument();
1178 await newThreadButton.click();
1179​
1180 const promotedThreadPath = await waitForURL(
1181 mounted.router,
1182 (path) => UUID_ROUTE_RE.test(path),
1183 "Route should have changed to a promoted draft thread UUID.",
1184 );
1185 const promotedThreadId = promotedThreadPath.slice(1) as ThreadId;
1186​
1187 const { syncServerReadModel } = useStore.getState();
1188 syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
1189 useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
1190​
1191 const useMetaForMod = isMacPlatform(navigator.platform);
1192 window.dispatchEvent(
1193 new KeyboardEvent("keydown", {
1194 key: "o",
1195 shiftKey: true,
1196 metaKey: useMetaForMod,
1197 ctrlKey: !useMetaForMod,
1198 bubbles: true,
1199 cancelable: true,
1200 }),
1201 );
1202​
1203 const freshThreadPath = await waitForURL(
1204 mounted.router,
1205 (path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath,
1206 "Shortcut should create a fresh draft instead of reusing the promoted thread.",
1207 );
1208 expect(freshThreadPath).not.toBe(promotedThreadPath);
1209 } finally {
1210 await mounted.cleanup();
1212 });
1213​
1214 it("keeps long proposed plans lightweight until the user expands them", async () => {
1215 const mounted = await mountChatView({
1216 viewport: DEFAULT_VIEWPORT,
1217 snapshot: createSnapshotWithLongProposedPlan(),
1218 });
1219​
1220 try {
1221 await waitForElement(
1222 () =>
1223 Array.from(document.querySelectorAll("button")).find(
1224 (button) => button.textContent?.trim() === "Expand plan",
1225 ) as HTMLButtonElement | null,
1226 "Unable to find Expand plan button.",
1227 );
1228​
1229 expect(document.body.textContent).not.toContain("deep hidden detail only after expand");
1230​
1231 const expandButton = await waitForElement(
1232 () =>
1233 Array.from(document.querySelectorAll("button")).find(
1234 (button) => button.textContent?.trim() === "Expand plan",
1235 ) as HTMLButtonElement | null,
1236 "Unable to find Expand plan button.",
1237 );
1238 expandButton.click();
1239​
1240 await vi.waitFor(
1241 () => {
1242 expect(document.body.textContent).toContain("deep hidden detail only after expand");
1243 },
1244 { timeout: 8_000, interval: 16 },
1245 );
1246 } finally {
1247 await mounted.cleanup();
1249 });
1250});