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