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

ChatView.browser.tsx

880 lines25.2 KB

1// Production CSS is part of the behavior under test because row height depends on it.
2import "../index.css";
3​
4import {
5 ORCHESTRATION_WS_METHODS,
6 type MessageId,
7 type OrchestrationReadModel,
8 type ProjectId,
9 type ServerConfig,
10 type ThreadId,
11 type WsWelcomePayload,
12 WS_CHANNELS,
13 WS_METHODS,
14} from "@t3tools/contracts";
15import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
16import { HttpResponse, http, ws } from "msw";
17import { setupWorker } from "msw/browser";
18import { page } from "vitest/browser";
19import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
20import { render } from "vitest-browser-react";
21​
22import { 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 PROJECT_ID = "project-1" as ProjectId;
29const NOW_ISO = "2026-03-04T12:00:00.000Z";
30const BASE_TIME_MS = Date.parse(NOW_ISO);
31const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
32​
33interface WsRequestEnvelope {
34 id: string;
35 body: {
36 _tag: string;
37 [key: string]: unknown;
38 };
40​
41interface TestFixture {
42 snapshot: OrchestrationReadModel;
43 serverConfig: ServerConfig;
44 welcome: WsWelcomePayload;
46​
47let fixture: TestFixture;
48const wsRequests: WsRequestEnvelope["body"][] = [];
49const wsLink = ws.link(/ws(s)?:\/\/.*/);
50​
51interface ViewportSpec {
52 name: string;
53 width: number;
54 height: number;
55 textTolerancePx: number;
56 attachmentTolerancePx: number;
58​
59const DEFAULT_VIEWPORT: ViewportSpec = {
60 name: "desktop",
61 width: 960,
62 height: 1_100,
63 textTolerancePx: 44,
64 attachmentTolerancePx: 56,
65};
66const TEXT_VIEWPORT_MATRIX = [
67 DEFAULT_VIEWPORT,
68 { name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 },
69 { name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
70 { name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
71] as const satisfies readonly ViewportSpec[];
72const ATTACHMENT_VIEWPORT_MATRIX = [
73 DEFAULT_VIEWPORT,
74 { name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
75 { name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
76] as const satisfies readonly ViewportSpec[];
77​
78interface UserRowMeasurement {
79 measuredRowHeightPx: number;
80 timelineWidthMeasuredPx: number;
81 renderedInVirtualizedRegion: boolean;
83​
84interface MountedChatView {
85 cleanup: () => Promise<void>;
86 measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
87 setViewport: (viewport: ViewportSpec) => Promise<void>;
89​
90function isoAt(offsetSeconds: number): string {
91 return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString();
93​
94function createBaseServerConfig(): ServerConfig {
95 return {
96 cwd: "/repo/project",
97 keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
98 appearanceConfigPath: "/repo/project/.t3code-appearance.json",
99 keybindings: [],
100 appearance: {
101 uiFontFamily:
102 '"DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',
103 uiFontSizePx: 16,
104 monoFontFamily:
105 '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
106 terminalFontSizePx: 12,
107 },
108 keybindingsIssues: [],
109 appearanceIssues: [],
110 providers: [
111 {
112 provider: "codex",
113 status: "ready",
114 available: true,
115 authStatus: "authenticated",
116 checkedAt: NOW_ISO,
117 },
118 ],
119 availableEditors: [],
120 };
122​
123function createUserMessage(options: {
124 id: MessageId;
125 text: string;
126 offsetSeconds: number;
127 attachments?: Array<{
128 type: "image";
129 id: string;
130 name: string;
131 mimeType: string;
132 sizeBytes: number;
133 }>;
134}) {
135 return {
136 id: options.id,
137 role: "user" as const,
138 text: options.text,
139 ...(options.attachments ? { attachments: options.attachments } : {}),
140 turnId: null,
141 streaming: false,
142 createdAt: isoAt(options.offsetSeconds),
143 updatedAt: isoAt(options.offsetSeconds + 1),
144 };
146​
147function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) {
148 return {
149 id: options.id,
150 role: "assistant" as const,
151 text: options.text,
152 turnId: null,
153 streaming: false,
154 createdAt: isoAt(options.offsetSeconds),
155 updatedAt: isoAt(options.offsetSeconds + 1),
156 };
158​
159function createSnapshotForTargetUser(options: {
160 targetMessageId: MessageId;
161 targetText: string;
162 targetAttachmentCount?: number;
163}): OrchestrationReadModel {
164 const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
165​
166 for (let index = 0; index < 22; index += 1) {
167 const isTarget = index === 3;
168 const userId = `msg-user-${index}` as MessageId;
169 const assistantId = `msg-assistant-${index}` as MessageId;
170 const attachments =
171 isTarget && (options.targetAttachmentCount ?? 0) > 0
172 ? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({
173 type: "image" as const,
174 id: `attachment-${attachmentIndex + 1}`,
175 name: `attachment-${attachmentIndex + 1}.png`,
176 mimeType: "image/png",
177 sizeBytes: 128,
178 }))
179 : undefined;
180​
181 messages.push(
182 createUserMessage({
183 id: isTarget ? options.targetMessageId : userId,
184 text: isTarget ? options.targetText : `filler user message ${index}`,
185 offsetSeconds: messages.length * 3,
186 ...(attachments ? { attachments } : {}),
187 }),
188 );
189 messages.push(
190 createAssistantMessage({
191 id: assistantId,
192 text: `assistant filler ${index}`,
193 offsetSeconds: messages.length * 3,
194 }),
195 );
196 }
197​
198 return {
199 snapshotSequence: 1,
200 projects: [
201 {
202 id: PROJECT_ID,
203 title: "Project",
204 workspaceRoot: "/repo/project",
205 defaultModel: "gpt-5",
206 scripts: [],
207 createdAt: NOW_ISO,
208 updatedAt: NOW_ISO,
209 deletedAt: null,
210 },
211 ],
212 threads: [
213 {
214 id: THREAD_ID,
215 projectId: PROJECT_ID,
216 title: "Browser test thread",
217 model: "gpt-5",
218 interactionMode: "default",
219 runtimeMode: "full-access",
220 branch: "main",
221 worktreePath: null,
222 latestTurn: null,
223 createdAt: NOW_ISO,
224 updatedAt: NOW_ISO,
225 deletedAt: null,
226 messages,
227 activities: [],
228 proposedPlans: [],
229 checkpoints: [],
230 session: {
231 threadId: THREAD_ID,
232 status: "ready",
233 providerName: "codex",
234 runtimeMode: "full-access",
235 activeTurnId: null,
236 lastError: null,
237 updatedAt: NOW_ISO,
238 },
239 },
240 ],
241 updatedAt: NOW_ISO,
242 };
244​
245function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
246 return {
247 snapshot,
248 serverConfig: createBaseServerConfig(),
249 welcome: {
250 cwd: "/repo/project",
251 projectName: "Project",
252 bootstrapProjectId: PROJECT_ID,
253 bootstrapThreadId: THREAD_ID,
254 },
255 };
257​
258function createDraftOnlySnapshot(): OrchestrationReadModel {
259 const snapshot = createSnapshotForTargetUser({
260 targetMessageId: "msg-user-draft-target" as MessageId,
261 targetText: "draft thread",
262 });
263 return {
264 ...snapshot,
265 threads: [],
266 };
268​
269function resolveWsRpc(tag: string): unknown {
270 if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
271 return fixture.snapshot;
272 }
273 if (tag === WS_METHODS.serverGetConfig) {
274 return fixture.serverConfig;
275 }
276 if (tag === WS_METHODS.gitListBranches) {
277 return {
278 isRepo: true,
279 branches: [
280 {
281 name: "main",
282 current: true,
283 isDefault: true,
284 worktreePath: null,
285 },
286 ],
287 };
288 }
289 if (tag === WS_METHODS.gitStatus) {
290 return {
291 branch: "main",
292 hasWorkingTreeChanges: false,
293 workingTree: {
294 files: [],
295 insertions: 0,
296 deletions: 0,
297 },
298 hasUpstream: true,
299 aheadCount: 0,
300 behindCount: 0,
301 pr: null,
302 };
303 }
304 if (tag === WS_METHODS.projectsSearchEntries) {
305 return {
306 entries: [],
307 truncated: false,
308 };
309 }
310 return {};
312​
313const worker = setupWorker(
314 wsLink.addEventListener("connection", ({ client }) => {
315 client.send(
316 JSON.stringify({
317 type: "push",
318 channel: WS_CHANNELS.serverWelcome,
319 data: fixture.welcome,
320 }),
321 );
322 client.addEventListener("message", (event) => {
323 const rawData = event.data;
324 if (typeof rawData !== "string") return;
325 let request: WsRequestEnvelope;
326 try {
327 request = JSON.parse(rawData) as WsRequestEnvelope;
328 } catch {
329 return;
330 }
331 const method = request.body?._tag;
332 if (typeof method !== "string") return;
333 wsRequests.push(request.body);
334 client.send(
335 JSON.stringify({
336 id: request.id,
337 result: resolveWsRpc(method),
338 }),
339 );
340 });
341 }),
342 http.get("*/attachments/:attachmentId", () =>
343 HttpResponse.text(ATTACHMENT_SVG, {
344 headers: {
345 "Content-Type": "image/svg+xml",
346 },
347 }),
348 ),
349 http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
350);
351​
352async function nextFrame(): Promise<void> {
353 await new Promise<void>((resolve) => {
354 window.requestAnimationFrame(() => resolve());
355 });
357​
358async function waitForLayout(): Promise<void> {
359 await nextFrame();
360 await nextFrame();
361 await nextFrame();
363​
364async function setViewport(viewport: ViewportSpec): Promise<void> {
365 await page.viewport(viewport.width, viewport.height);
366 await waitForLayout();
368​
369async function waitForProductionStyles(): Promise<void> {
370 await vi.waitFor(
371 () => {
372 expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).not.toBe(
373 "",
374 );
375 expect(getComputedStyle(document.body).marginTop).toBe("0px");
376 },
377 {
378 timeout: 4_000,
379 interval: 16,
380 },
381 );
383​
384async function waitForElement<T extends Element>(
385 query: () => T | null,
386 errorMessage: string,
387): Promise<T> {
388 let element: T | null = null;
389 await vi.waitFor(
390 () => {
391 element = query();
392 expect(element, errorMessage).toBeTruthy();
393 },
394 {
395 timeout: 8_000,
396 interval: 16,
397 },
398 );
399 if (!element) {
400 throw new Error(errorMessage);
401 }
402 return element;
404​
405async function waitForComposerEditor(): Promise<HTMLElement> {
406 return waitForElement(
407 () => document.querySelector<HTMLElement>('[contenteditable="true"]'),
408 "Unable to find composer editor.",
409 );
411​
412async function waitForInteractionModeButton(expectedLabel: "Chat" | "Plan"): Promise<HTMLButtonElement> {
413 return waitForElement(
414 () =>
415 Array.from(document.querySelectorAll("button")).find(
416 (button) => button.textContent?.trim() === expectedLabel,
417 ) as HTMLButtonElement | null,
418 `Unable to find ${expectedLabel} interaction mode button.`,
419 );
421​
422async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
423 const images = Array.from(scope.querySelectorAll("img"));
424 if (images.length === 0) {
425 return;
426 }
427 await Promise.all(
428 images.map(
429 (image) =>
430 new Promise<void>((resolve) => {
431 if (image.complete) {
432 resolve();
433 return;
434 }
435 image.addEventListener("load", () => resolve(), { once: true });
436 image.addEventListener("error", () => resolve(), { once: true });
437 }),
438 ),
439 );
440 await waitForLayout();
442​
443async function measureUserRow(options: {
444 host: HTMLElement;
445 targetMessageId: MessageId;
446}): Promise<UserRowMeasurement> {
447 const { host, targetMessageId } = options;
448 const rowSelector = `[data-message-id="${targetMessageId}"][data-message-role="user"]`;
449​
450 const scrollContainer = await waitForElement(
451 () => host.querySelector<HTMLDivElement>("div.overflow-y-auto.overscroll-y-contain"),
452 "Unable to find ChatView message scroll container.",
453 );
454​
455 let row: HTMLElement | null = null;
456 await vi.waitFor(
457 async () => {
458 scrollContainer.scrollTop = 0;
459 scrollContainer.dispatchEvent(new Event("scroll"));
460 await waitForLayout();
461 row = host.querySelector<HTMLElement>(rowSelector);
462 expect(row, "Unable to locate targeted user message row.").toBeTruthy();
463 },
464 {
465 timeout: 8_000,
466 interval: 16,
467 },
468 );
469​
470 await waitForImagesToLoad(row!);
471 scrollContainer.scrollTop = 0;
472 scrollContainer.dispatchEvent(new Event("scroll"));
473 await nextFrame();
474​
475 const timelineRoot =
476 row!.closest<HTMLElement>('[data-timeline-root="true"]') ??
477 host.querySelector<HTMLElement>('[data-timeline-root="true"]');
478 if (!(timelineRoot instanceof HTMLElement)) {
479 throw new Error("Unable to locate timeline root container.");
480 }
481​
482 let timelineWidthMeasuredPx = 0;
483 let measuredRowHeightPx = 0;
484 let renderedInVirtualizedRegion = false;
485 await vi.waitFor(
486 async () => {
487 scrollContainer.scrollTop = 0;
488 scrollContainer.dispatchEvent(new Event("scroll"));
489 await nextFrame();
490 const measuredRow = host.querySelector<HTMLElement>(rowSelector);
491 expect(measuredRow, "Unable to measure targeted user row height.").toBeTruthy();
492 timelineWidthMeasuredPx = timelineRoot.getBoundingClientRect().width;
493 measuredRowHeightPx = measuredRow!.getBoundingClientRect().height;
494 renderedInVirtualizedRegion = measuredRow!.closest("[data-index]") instanceof HTMLElement;
495 expect(timelineWidthMeasuredPx, "Unable to measure timeline width.").toBeGreaterThan(0);
496 expect(measuredRowHeightPx, "Unable to measure targeted user row height.").toBeGreaterThan(0);
497 },
498 {
499 timeout: 4_000,
500 interval: 16,
501 },
502 );
503​
504 return { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion };
506​
507async function mountChatView(options: {
508 viewport: ViewportSpec;
509 snapshot: OrchestrationReadModel;
510 configureFixture?: (fixture: TestFixture) => void;
511}): Promise<MountedChatView> {
512 fixture = buildFixture(options.snapshot);
513 options.configureFixture?.(fixture);
514 await setViewport(options.viewport);
515 await waitForProductionStyles();
516​
517 const host = document.createElement("div");
518 host.style.position = "fixed";
519 host.style.inset = "0";
520 host.style.width = "100vw";
521 host.style.height = "100vh";
522 host.style.display = "grid";
523 host.style.overflow = "hidden";
524 document.body.append(host);
525​
526 const router = getRouter(
527 createMemoryHistory({
528 initialEntries: [`/${THREAD_ID}`],
529 }),
530 );
531​
532 const screen = await render(<RouterProvider router={router} />, {
533 container: host,
534 });
535​
536 await waitForLayout();
537​
538 return {
539 cleanup: async () => {
540 await screen.unmount();
541 host.remove();
542 },
543 measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
544 setViewport: async (viewport: ViewportSpec) => {
545 await setViewport(viewport);
546 await waitForProductionStyles();
547 },
548 };
550​
551async function measureUserRowAtViewport(options: {
552 snapshot: OrchestrationReadModel;
553 targetMessageId: MessageId;
554 viewport: ViewportSpec;
555}): Promise<UserRowMeasurement> {
556 const mounted = await mountChatView({
557 viewport: options.viewport,
558 snapshot: options.snapshot,
559 });
560​
561 try {
562 return await mounted.measureUserRow(options.targetMessageId);
563 } finally {
564 await mounted.cleanup();
565 }
567​
568describe("ChatView timeline estimator parity (full app)", () => {
569 beforeAll(async () => {
570 fixture = buildFixture(
571 createSnapshotForTargetUser({
572 targetMessageId: "msg-user-bootstrap" as MessageId,
573 targetText: "bootstrap",
574 }),
575 );
576 await worker.start({
577 onUnhandledRequest: "bypass",
578 quiet: true,
579 serviceWorker: {
580 url: "/mockServiceWorker.js",
581 },
582 });
583 });
584​
585 afterAll(async () => {
586 await worker.stop();
587 });
588​
589 beforeEach(async () => {
590 await setViewport(DEFAULT_VIEWPORT);
591 localStorage.clear();
592 document.body.innerHTML = "";
593 wsRequests.length = 0;
594 useComposerDraftStore.setState({
595 draftsByThreadId: {},
596 draftThreadsByThreadId: {},
597 projectDraftThreadIdByProjectId: {},
598 });
599 useStore.setState({
600 projects: [],
601 threads: [],
602 threadsHydrated: false,
603 });
604 });
605​
606 afterEach(() => {
607 document.body.innerHTML = "";
608 });
609​
610 it.each(TEXT_VIEWPORT_MATRIX)(
611 "keeps long user message estimate close at the $name viewport",
612 async (viewport) => {
613 const userText = "x".repeat(3_200);
614 const targetMessageId = `msg-user-target-long-${viewport.name}` as MessageId;
615 const mounted = await mountChatView({
616 viewport,
617 snapshot: createSnapshotForTargetUser({
618 targetMessageId,
619 targetText: userText,
620 }),
621 });
622​
623 try {
624 const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
625 await mounted.measureUserRow(targetMessageId);
626​
627 expect(renderedInVirtualizedRegion).toBe(true);
628​
629 const estimatedHeightPx = estimateTimelineMessageHeight(
630 { role: "user", text: userText, attachments: [] },
631 { timelineWidthPx: timelineWidthMeasuredPx },
632 );
633​
634 expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
635 viewport.textTolerancePx,
636 );
637 } finally {
638 await mounted.cleanup();
639 }
640 },
641 );
642​
643 it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
644 const userText = "x".repeat(3_200);
645 const targetMessageId = "msg-user-target-resize" as MessageId;
646 const mounted = await mountChatView({
647 viewport: TEXT_VIEWPORT_MATRIX[0],
648 snapshot: createSnapshotForTargetUser({
649 targetMessageId,
650 targetText: userText,
651 }),
652 });
653​
654 try {
655 const measurements: Array<UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }> = [];
656​
657 for (const viewport of TEXT_VIEWPORT_MATRIX) {
658 await mounted.setViewport(viewport);
659 const measurement = await mounted.measureUserRow(targetMessageId);
660 const estimatedHeightPx = estimateTimelineMessageHeight(
661 { role: "user", text: userText, attachments: [] },
662 { timelineWidthPx: measurement.timelineWidthMeasuredPx },
663 );
664​
665 expect(measurement.renderedInVirtualizedRegion).toBe(true);
666 expect(Math.abs(measurement.measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
667 viewport.textTolerancePx,
668 );
669 measurements.push({ ...measurement, viewport, estimatedHeightPx });
670 }
671​
672 expect(new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx))).size).toBeGreaterThanOrEqual(3);
673​
674 const byMeasuredWidth = measurements.toSorted(
675 (left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,
676 );
677 const narrowest = byMeasuredWidth[0]!;
678 const widest = byMeasuredWidth.at(-1)!;
679 expect(narrowest.timelineWidthMeasuredPx).toBeLessThan(widest.timelineWidthMeasuredPx);
680 expect(narrowest.measuredRowHeightPx).toBeGreaterThan(widest.measuredRowHeightPx);
681 expect(narrowest.estimatedHeightPx).toBeGreaterThan(widest.estimatedHeightPx);
682 } finally {
683 await mounted.cleanup();
684 }
685 });
686​
687 it("tracks additional rendered wrapping when ChatView width narrows between desktop and mobile viewports", async () => {
688 const userText = "x".repeat(2_400);
689 const targetMessageId = "msg-user-target-wrap" as MessageId;
690 const snapshot = createSnapshotForTargetUser({
691 targetMessageId,
692 targetText: userText,
693 });
694 const desktopMeasurement = await measureUserRowAtViewport({
695 viewport: TEXT_VIEWPORT_MATRIX[0],
696 snapshot,
697 targetMessageId,
698 });
699 const mobileMeasurement = await measureUserRowAtViewport({
700 viewport: TEXT_VIEWPORT_MATRIX[2],
701 snapshot,
702 targetMessageId,
703 });
704​
705 const estimatedDesktopPx = estimateTimelineMessageHeight(
706 { role: "user", text: userText, attachments: [] },
707 { timelineWidthPx: desktopMeasurement.timelineWidthMeasuredPx },
708 );
709 const estimatedMobilePx = estimateTimelineMessageHeight(
710 { role: "user", text: userText, attachments: [] },
711 { timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },
712 );
713​
714 const measuredDeltaPx = mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
715 const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;
716 expect(measuredDeltaPx).toBeGreaterThan(0);
717 expect(estimatedDeltaPx).toBeGreaterThan(0);
718 const ratio = estimatedDeltaPx / measuredDeltaPx;
719 expect(ratio).toBeGreaterThan(0.65);
720 expect(ratio).toBeLessThan(1.35);
721 });
722​
723 it.each(ATTACHMENT_VIEWPORT_MATRIX)(
724 "keeps user attachment estimate close at the $name viewport",
725 async (viewport) => {
726 const targetMessageId = `msg-user-target-attachments-${viewport.name}` as MessageId;
727 const userText = "message with image attachments";
728 const mounted = await mountChatView({
729 viewport,
730 snapshot: createSnapshotForTargetUser({
731 targetMessageId,
732 targetText: userText,
733 targetAttachmentCount: 3,
734 }),
735 });
736​
737 try {
738 const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
739 await mounted.measureUserRow(targetMessageId);
740​
741 expect(renderedInVirtualizedRegion).toBe(true);
742​
743 const estimatedHeightPx = estimateTimelineMessageHeight(
744 {
745 role: "user",
746 text: userText,
747 attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
748 },
749 { timelineWidthPx: timelineWidthMeasuredPx },
750 );
751​
752 expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
753 viewport.attachmentTolerancePx,
754 );
755 } finally {
756 await mounted.cleanup();
757 }
758 },
759 );
760​
761 it("opens the project cwd for draft threads without a worktree path", async () => {
762 useComposerDraftStore.setState({
763 draftThreadsByThreadId: {
764 [THREAD_ID]: {
765 projectId: PROJECT_ID,
766 createdAt: NOW_ISO,
767 runtimeMode: "full-access",
768 interactionMode: "default",
769 branch: null,
770 worktreePath: null,
771 envMode: "local",
772 },
773 },
774 projectDraftThreadIdByProjectId: {
775 [PROJECT_ID]: THREAD_ID,
776 },
777 });
778​
779 const mounted = await mountChatView({
780 viewport: DEFAULT_VIEWPORT,
781 snapshot: createDraftOnlySnapshot(),
782 configureFixture: (nextFixture) => {
783 nextFixture.serverConfig = {
784 ...nextFixture.serverConfig,
785 availableEditors: ["vscode"],
786 };
787 },
788 });
789​
790 try {
791 const openButton = await waitForElement(
792 () =>
793 Array.from(document.querySelectorAll("button")).find(
794 (button) => button.textContent?.trim() === "Open",
795 ) as HTMLButtonElement | null,
796 "Unable to find Open button.",
797 );
798 openButton.click();
799​
800 await vi.waitFor(
801 () => {
802 const openRequest = wsRequests.find((request) => request._tag === WS_METHODS.shellOpenInEditor);
803 expect(openRequest).toMatchObject({
804 _tag: WS_METHODS.shellOpenInEditor,
805 cwd: "/repo/project",
806 editor: "vscode",
807 });
808 },
809 { timeout: 8_000, interval: 16 },
810 );
811 } finally {
812 await mounted.cleanup();
813 }
814 });
815​
816 it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
817 const mounted = await mountChatView({
818 viewport: DEFAULT_VIEWPORT,
819 snapshot: createSnapshotForTargetUser({
820 targetMessageId: "msg-user-target-hotkey" as MessageId,
821 targetText: "hotkey target",
822 }),
823 });
824​
825 try {
826 const initialModeButton = await waitForInteractionModeButton("Chat");
827 expect(initialModeButton.title).toContain("enter plan mode");
828​
829 window.dispatchEvent(
830 new KeyboardEvent("keydown", {
831 key: "Tab",
832 shiftKey: true,
833 bubbles: true,
834 cancelable: true,
835 }),
836 );
837 await waitForLayout();
838​
839 expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
840​
841 const composerEditor = await waitForComposerEditor();
842 composerEditor.focus();
843 composerEditor.dispatchEvent(
844 new KeyboardEvent("keydown", {
845 key: "Tab",
846 shiftKey: true,
847 bubbles: true,
848 cancelable: true,
849 }),
850 );
851​
852 await vi.waitFor(
853 async () => {
854 expect((await waitForInteractionModeButton("Plan")).title).toContain(
855 "return to normal chat mode",
856 );
857 },
858 { timeout: 8_000, interval: 16 },
859 );
860​
861 composerEditor.dispatchEvent(
862 new KeyboardEvent("keydown", {
863 key: "Tab",
864 shiftKey: true,
865 bubbles: true,
866 cancelable: true,
867 }),
868 );
869​
870 await vi.waitFor(
871 async () => {
872 expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
873 },
874 { timeout: 8_000, interval: 16 },
875 );
876 } finally {
877 await mounted.cleanup();
878 }
879 });
880});