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