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