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