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

ChatView.browser.tsx

1,444 lines42.2 KB

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