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

MessagesTimeline.test.tsx

445 lines13.9 KB

1import { EnvironmentId, MessageId } from "@t3tools/contracts";
2import { createRef, type ReactNode, type Ref } from "react";
3import { renderToStaticMarkup } from "react-dom/server";
4import { beforeAll, describe, expect, it, vi } from "vite-plus/test";
5import type { LegendListRef } from "@legendapp/list/react";
6​
7vi.mock("@legendapp/list/react", async () => {
8 const legendListTestId = "legend-list";
9​
10 const LegendList = (props: {
11 data: Array<{ id: string }>;
12 keyExtractor: (item: { id: string }) => string;
13 renderItem: (args: { item: { id: string } }) => ReactNode;
14 ListHeaderComponent?: ReactNode;
15 ListFooterComponent?: ReactNode;
16 anchoredEndSpace?: {
17 anchorIndex: number;
18 anchorMaxSize?: number;
19 anchorOffset?: number;
20 };
21 contentInsetEndAdjustment?: number;
22 ref?: Ref<LegendListRef>;
23 }) => (
24 <div
25 data-testid={legendListTestId}
26 data-anchor-index={props.anchoredEndSpace?.anchorIndex}
27 data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
28 data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
29 data-content-inset-end={props.contentInsetEndAdjustment}
30 >
31 {props.ListHeaderComponent}
32 {props.data.map((item) => (
33 <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
34 ))}
35 {props.ListFooterComponent}
36 </div>
37 );
38​
39 return { LegendList };
40});
41​
42function MockFileDiff(props: {
43 fileDiff: { name?: string | null; prevName?: string | null };
44 renderCustomHeader?: (fileDiff: {
45 name?: string | null;
46 prevName?: string | null;
47 }) => React.ReactNode;
48}) {
49 return (
50 <div data-testid="file-diff">
51 {props.renderCustomHeader?.(props.fileDiff)}
52 {props.fileDiff.name ?? props.fileDiff.prevName ?? "diff"}
53 </div>
54 );
56​
57vi.mock("@pierre/diffs/react", () => {
58 return { FileDiff: MockFileDiff };
59});
60​
61function matchMedia() {
62 return {
63 matches: false,
64 addEventListener: () => {},
65 removeEventListener: () => {},
66 };
68​
69beforeAll(() => {
70 const classList = {
71 add: () => {},
72 remove: () => {},
73 toggle: () => {},
74 contains: () => false,
75 };
76​
77 vi.stubGlobal("localStorage", {
78 getItem: () => null,
79 setItem: () => {},
80 removeItem: () => {},
81 clear: () => {},
82 });
83 vi.stubGlobal("window", {
84 matchMedia,
85 addEventListener: () => {},
86 removeEventListener: () => {},
87 requestAnimationFrame: (callback: FrameRequestCallback) => {
88 callback(0);
89 return 0;
90 },
91 cancelAnimationFrame: () => {},
92 desktopBridge: undefined,
93 });
94 vi.stubGlobal("document", {
95 documentElement: {
96 classList,
97 offsetHeight: 0,
98 },
99 });
100});
101​
102const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
103const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
104​
105function buildProps() {
106 return {
107 isWorking: false,
108 activeTurnInProgress: false,
109 activeTurnStartedAt: null,
110 listRef: createRef<LegendListRef | null>(),
111 latestTurn: null,
112 runningTurnId: null,
113 turnDiffSummaryByAssistantMessageId: new Map(),
114 routeThreadKey: "environment-local:thread-1",
115 onOpenTurnDiff: () => {},
116 revertTurnCountByUserMessageId: new Map(),
117 onRevertUserMessage: () => {},
118 isRevertingCheckpoint: false,
119 onImageExpand: () => {},
120 activeThreadEnvironmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
121 markdownCwd: undefined,
122 resolvedTheme: "light" as const,
123 timestampFormat: "locale" as const,
124 workspaceRoot: undefined,
125 anchorMessageId: null,
126 contentInsetEndAdjustment: 0,
127 onIsAtEndChange: () => {},
128 };
130​
131function buildLongUserMessageText(tail = "deep hidden detail only after expand") {
132 return Array.from({ length: 9 }, (_, index) =>
133 index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
134 ).join("\n");
136​
137function buildUserTimelineEntry(text: string) {
138 return {
139 id: "entry-1",
140 kind: "message" as const,
141 createdAt: MESSAGE_CREATED_AT,
142 message: {
143 id: MessageId.make("message-1"),
144 role: "user" as const,
145 text,
146 turnId: null,
147 createdAt: MESSAGE_CREATED_AT,
148 updatedAt: MESSAGE_CREATED_AT,
149 streaming: false,
150 },
151 };
153​
154describe("MessagesTimeline", () => {
155 it("anchors a sent attachment message using its measured height", async () => {
156 const { MessagesTimeline } = await import("./MessagesTimeline");
157 const firstEntry = buildUserTimelineEntry("First prompt.");
158 const secondEntry = {
159 ...buildUserTimelineEntry("Newest prompt."),
160 id: "entry-2",
161 message: {
162 ...buildUserTimelineEntry("Newest prompt.").message,
163 id: MessageId.make("message-2"),
164 attachments: [
165 {
166 type: "image" as const,
167 id: "attachment-1",
168 name: "screenshot.png",
169 mimeType: "image/png",
170 sizeBytes: 1,
171 previewUrl: "data:image/png;base64,iVBORw0KGgo=",
172 },
173 ],
174 },
175 };
176 const markup = renderToStaticMarkup(
177 <MessagesTimeline
178 {...buildProps()}
179 anchorMessageId={secondEntry.message.id}
180 contentInsetEndAdjustment={144}
181 timelineEntries={[firstEntry, secondEntry]}
182 />,
183 );
184​
185 expect(markup).toContain('data-anchor-index="1"');
186 expect(markup).toContain('data-anchor-offset="16"');
187 expect(markup).not.toContain("data-anchor-max-size=");
188 expect(markup).toContain('data-content-inset-end="144"');
189 });
190​
191 it("renders collapse controls for long user messages", async () => {
192 const { MessagesTimeline } = await import("./MessagesTimeline");
193 const markup = renderToStaticMarkup(
194 <MessagesTimeline
195 {...buildProps()}
196 timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
197 />,
198 );
199​
200 expect(markup).toContain("Show full message");
201 expect(markup).toContain('data-user-message-collapsed="true"');
202 expect(markup).toContain('data-user-message-fade="true"');
203 expect(markup).toContain('data-user-message-footer="true"');
204 });
205​
206 it("does not render collapse controls for short user messages", async () => {
207 const { MessagesTimeline } = await import("./MessagesTimeline");
208 const markup = renderToStaticMarkup(
209 <MessagesTimeline
210 {...buildProps()}
211 timelineEntries={[buildUserTimelineEntry("Short prompt.")]}
212 />,
213 );
214​
215 expect(markup).not.toContain("Show full message");
216 expect(markup).toContain('data-user-message-collapsible="false"');
217 });
218​
219 it("renders inline terminal labels with the composer chip UI", async () => {
220 const { MessagesTimeline } = await import("./MessagesTimeline");
221 const markup = renderToStaticMarkup(
222 <MessagesTimeline
223 {...buildProps()}
224 timelineEntries={[
225 buildUserTimelineEntry(
226 [
227 buildLongUserMessageText("yoo what's @terminal-1:1-5 mean"),
228 "",
229 "<terminal_context>",
230 "- Terminal 1 lines 1-5:",
231 " 1 | julius@mac effect-http-ws-cli % bun i",
232 " 2 | bun install v1.3.9 (cf6cdbbb)",
233 "</terminal_context>",
234 ].join("\n"),
235 ),
236 ]}
237 />,
238 );
239​
240 expect(markup).toContain("Terminal 1 lines 1-5");
241 expect(markup).toContain("lucide-terminal");
242 expect(markup).toContain("yoo what&#x27;s</p>");
243 expect(markup).toContain('<span aria-hidden="true"> </span>');
244 expect(markup).toContain("Show full message");
245 }, 20_000);
246​
247 it("renders chips for standalone element-pick context messages", async () => {
248 const { MessagesTimeline } = await import("./MessagesTimeline");
249 const markup = renderToStaticMarkup(
250 <MessagesTimeline
251 {...buildProps()}
252 timelineEntries={[
253 buildUserTimelineEntry(
254 [
255 "<element_context>",
256 "- <SubmitButton> (Button.tsx:12):",
257 " url: https://example.com/dashboard",
258 " selector: button.submit",
259 " source: /repo/src/Button.tsx:12:5",
260 " html:",
261 ' <button class="submit">Save</button>',
262 "</element_context>",
263 ].join("\n"),
264 ),
265 ]}
266 />,
267 );
268​
269 expect(markup).toContain("SubmitButton");
270 expect(markup).not.toContain("&lt;element_context");
271 expect(markup).not.toContain("<element_context");
272 });
273​
274 it("keeps the copy button for collapsed long user messages", async () => {
275 const { MessagesTimeline } = await import("./MessagesTimeline");
276 const markup = renderToStaticMarkup(
277 <MessagesTimeline
278 {...buildProps()}
279 timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
280 />,
281 );
282​
283 expect(markup).toContain('aria-label="Copy link"');
284 expect(markup).toContain('data-user-message-collapsed="true"');
285 expect(markup).toContain('data-user-message-footer="true"');
286 });
287​
288 it("renders context compaction entries in the normal work log", async () => {
289 const { MessagesTimeline } = await import("./MessagesTimeline");
290 const markup = renderToStaticMarkup(
291 <MessagesTimeline
292 {...buildProps()}
293 timelineEntries={[
294 {
295 id: "entry-1",
296 kind: "work",
297 createdAt: "2026-03-17T19:12:28.000Z",
298 entry: {
299 id: "work-1",
300 createdAt: "2026-03-17T19:12:28.000Z",
301 label: "Context compacted",
302 tone: "info",
303 },
304 },
305 ]}
306 />,
307 );
308​
309 expect(markup).toContain("Context compacted");
310 expect(markup).toContain("Work Log");
311 });
312​
313 it("formats changed file paths from the workspace root", async () => {
314 const { MessagesTimeline } = await import("./MessagesTimeline");
315 const markup = renderToStaticMarkup(
316 <MessagesTimeline
317 {...buildProps()}
318 timelineEntries={[
319 {
320 id: "entry-1",
321 kind: "work",
322 createdAt: "2026-03-17T19:12:28.000Z",
323 entry: {
324 id: "work-1",
325 createdAt: "2026-03-17T19:12:28.000Z",
326 label: "Updated files",
327 tone: "tool",
328 changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
329 },
330 },
331 ]}
332 workspaceRoot="C:/Users/mike/dev-stuff/t3code"
333 />,
334 );
335​
336 expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
337 expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
338 });
339​
340 it("renders review comment contexts as structured cards instead of raw tags", async () => {
341 const { MessagesTimeline } = await import("./MessagesTimeline");
342 const markup = renderToStaticMarkup(
343 <MessagesTimeline
344 {...buildProps()}
345 timelineEntries={[
346 {
347 id: "entry-1",
348 kind: "message",
349 createdAt: "2026-03-17T19:12:28.000Z",
350 message: {
351 id: MessageId.make("message-2"),
352 role: "user",
353 text: [
354 '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
355 "Wadduo",
356 "```diff",
357 "@@ -0,0 +47,2 @@",
358 '+ it("keeps valid zero-usage snapshots", () => {',
359 "+ expect(snapshot).not.toBeNull();",
360 "```",
361 "</review_comment>",
362 ].join("\n"),
363 turnId: null,
364 createdAt: "2026-03-17T19:12:28.000Z",
365 updatedAt: "2026-03-17T19:12:28.000Z",
366 streaming: false,
367 },
368 },
369 ]}
370 />,
371 );
372​
373 expect(markup).toContain("contextWindow.test.ts");
374 expect(markup).toContain("Wadduo");
375 expect(markup).toContain('data-testid="file-diff"');
376 expect(markup).not.toContain(">Review comment<");
377 expect(markup).not.toContain("&lt;review_comment");
378 expect(markup).not.toContain("&lt;/review_comment&gt;");
379 });
380​
381 it("renders file review comments as source code instead of diffs", async () => {
382 const { MessagesTimeline } = await import("./MessagesTimeline");
383 const markup = renderToStaticMarkup(
384 <MessagesTimeline
385 {...buildProps()}
386 timelineEntries={[
387 {
388 id: "entry-1",
389 kind: "message",
390 createdAt: "2026-03-17T19:12:28.000Z",
391 message: {
392 id: MessageId.make("message-source-comment"),
393 role: "user",
394 text: [
395 '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
396 "Clarify this.",
397 "```md",
398 "# Plan",
399 "- Step one",
400 "```",
401 "</review_comment>",
402 ].join("\n"),
403 turnId: null,
404 createdAt: "2026-03-17T19:12:28.000Z",
405 updatedAt: "2026-03-17T19:12:28.000Z",
406 streaming: false,
407 },
408 },
409 ]}
410 />,
411 );
412​
413 expect(markup).toContain("plan.md");
414 expect(markup).toContain("Clarify this.");
415 expect(markup).toContain("# Plan");
416 expect(markup).not.toContain('data-testid="file-diff"');
417 });
418​
419 it("renders a failure marker for failed tool lifecycle entries", async () => {
420 const { MessagesTimeline } = await import("./MessagesTimeline");
421 const markup = renderToStaticMarkup(
422 <MessagesTimeline
423 {...buildProps()}
424 timelineEntries={[
425 {
426 id: "entry-1",
427 kind: "work",
428 createdAt: "2026-03-17T19:12:28.000Z",
429 entry: {
430 id: "work-1",
431 createdAt: "2026-03-17T19:12:28.000Z",
432 label: "Glob",
433 tone: "tool",
434 toolLifecycleStatus: "failed",
435 detail: "No files found",
436 },
437 },
438 ]}
439 />,
440 );
441​
442 expect(markup).toContain("lucide-x");
443 expect(markup).toContain('aria-label="Tool call failed"');
444 });
445});