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

TimelineUserMessageRow.tsx

725 lines28.0 KB

1import { findRevealRef } from "./markdownFindContext";
2import { type MessageId, type ServerProviderSkill, ThreadId } from "@t3tools/contracts";
3import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
4import { Link } from "@tanstack/react-router";
5import { useEnvironmentQuery } from "../../state/query";
6import { serverEnvironment } from "../../state/server";
7import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
8import { memo, use, useState, type ReactNode } from "react";
9import {
10 createMessageAttachmentPreviewProjector,
11 selectMessageImageResources,
12} from "../../session-logic";
13import {
14 type ChatFileAttachment,
15 isFileAttachment,
16 isImageAttachment,
17 isVideoAttachment,
18} from "../../types";
19import ChatMarkdown from "../ChatMarkdown";
20import {
21 CalendarClockIcon,
22 ChevronDownIcon,
23 DownloadIcon,
24 EyeIcon,
25 Redo2Icon,
26 Undo2Icon,
27} from "lucide-react";
28import { Link as LinkIconNode } from "lucide";
29import { Button, InlineButton } from "../ui/button";
30import { useAssetUrlRefresh, useAssetUrls, useAssetUrlState } from "../../assets/assetUrls";
31import { AttachmentImage } from "../media/AttachmentImage";
32import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
33import {
34 buildAttachmentVideoAsset,
35 buildAttachmentVideoPreview,
36 buildExpandedImagePreview,
37} from "./ExpandedImagePreview";
38import {
39 SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
40 SnapShotAttachmentDetails,
41} from "./SnapShotAttachmentDetails";
42import { MessageCopyButton } from "./MessageCopyButton";
43import { promptLinkFor } from "../promptLinks/copyPromptLink";
44import { PierreEntryIcon } from "./PierreEntryIcon";
45import { shouldCollapseUserMessage } from "./MessagesTimeline.logic";
46import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
47import {
48 asKnownContextRecord,
49 resolveUserMessageContext,
50 selectedMessageContextFragment,
51} from "~/lib/composerContextRecords";
52import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
53import {
54 COMPOSER_CONTEXT_CLIPBOARD_MIME,
55 encodeComposerContextClipboardHtml,
56 encodeComposerContextFragment,
57} from "@t3tools/shared/composerContextClipboard";
58import { chatMarkdownClipboardPayload } from "../../markdown-clipboard";
59import type { ChatMarkdownContextReference } from "../ChatMarkdown";
60import { cn } from "~/lib/utils";
61import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
62import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
63import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext";
64import {
65 MESSAGE_HEADING_LEVEL,
66 MessageAuthorHeading,
67 TimelineRowTimestamp,
68} from "./TimelineRowParts";
69import { UserMessageContextReferenceChip } from "./UserMessageContextChips";
70import { resolvePreviewAnnotationImage } from "./TimelineUserMessageRow.logic";
71​
72function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
73 const ctx = use(TimelineRowCtx);
74 // Row updates rebuild attachment objects, so the asset follows only the
75 // fields it reads.
76 const { downloadable, id, mimeType, name } = file;
77 const environmentId = ctx.activeThreadEnvironmentId;
78 const asset =
79 downloadable === false
80 ? null
81 : buildAttachmentVideoAsset(environmentId, { id, mimeType, name });
82 const resource = asset?.resource ?? null;
83 const assetUrl = useAssetUrlState(ctx.activeThreadEnvironmentId, resource);
84 const refreshAssetUrl = useAssetUrlRefresh(ctx.activeThreadEnvironmentId, resource);
85 const src = assetUrl._tag === "Success" ? assetUrl.url : (file.previewUrl ?? null);
86​
87 if (asset === null && src === null) {
88 return (
89 <div className="flex aspect-[4/3] w-full items-center justify-center rounded-lg border border-border/80 bg-black px-2 py-3 text-center text-2xs text-white/70">
90 {file.name}
91 </div>
92 );
93 }
94​
95 return (
96 <MediaVideoPlayer
97 src={src}
98 sourceFailed={
99 file.previewUrl === undefined && resource !== null && assetUrl._tag === "Failure"
100 }
101 label={file.name}
102 preload="visible"
103 onOpen={() => {
104 const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
105 if (preview) ctx.onImageExpand(preview);
106 }}
107 className="block aspect-[4/3] w-full"
108 videoClassName="aspect-auto size-full rounded-lg border border-border/80"
109 stateClassName="aspect-auto min-h-full rounded-lg border border-border/80 bg-black text-white"
110 onRetry={asset ? refreshAssetUrl : undefined}
111 actionsSource={asset ? { kind: "video", name: file.name, src, asset } : undefined}
112 />
113 );
115​
116export function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
117 const ctx = use(TimelineRowCtx);
118 return ctx.workflowOpening?.messageId === row.message.id ? (
119 <WorkflowOpeningBlock
120 opening={ctx.workflowOpening}
121 environmentId={ctx.activeThreadEnvironmentId}
122 onOpenThread={(threadId) => ctx.onOpenThread(ThreadId.make(threadId))}
123 />
124 ) : resolveUserMessagePresentation(row.message).attribution === "automation" ? (
125 <AutomationMessageRow row={row} />
126 ) : (
127 <UserTimelineRow row={row} />
128 );
130​
131/** Automation prompts are long, repeated runbooks; a folded bubble keeps them out of the way. */
132function AutomationMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
133 const ctx = use(TimelineRowCtx);
134 const [expanded, setExpanded] = useState(false);
135 const revealRef = findRevealRef(() => setExpanded(true));
136 const { text, scheduledTaskId } = resolveUserMessagePresentation(row.message);
137 const tasksQuery = useEnvironmentQuery(
138 scheduledTaskId
139 ? serverEnvironment.scheduledTasksLive({
140 environmentId: ctx.activeThreadEnvironmentId,
141 input: {},
142 })
143 : null,
144 );
145 const taskTitle = tasksQuery.data?.tasks.find((task) => task.id === scheduledTaskId)?.title;
146 const summary = taskTitle ?? text.trim().split(/\r?\n/, 1)[0] ?? "";
147​
148 const revertTurnCount = row.revertTurnCount;
149 const promptLink = promptLinkFor(text);
150 // Find reads the DOM, so a folded prompt stays mounted but hidden while find is open.
151 const bodyMounted = expanded || ctx.findActive;
152​
153 return (
154 <div className="group flex flex-col items-end gap-1" data-user-message-attribution="automation">
155 {row.message.inputIntent === "steer" ||
156 row.message.inputIntent === "promoted_queued_to_steer" ? (
157 <UserMessageIntentMarker intent={row.message.inputIntent} />
158 ) : null}
159 <div
160 className={cn(
161 "min-w-0 max-w-[80%] rounded-2xl bg-message text-message-foreground",
162 expanded && "w-full",
163 )}
164 >
165 <button
166 type="button"
167 aria-expanded={expanded}
168 data-scroll-anchor-ignore
169 onClick={() => setExpanded((value) => !value)}
170 className="flex w-full min-w-0 items-center gap-1.5 rounded-2xl px-3 py-2 text-left text-sm focus-visible:outline-2 focus-visible:outline-ring"
171 >
172 <CalendarClockIcon className="size-4 shrink-0 stroke-2 text-muted-foreground" />
173 <span className="shrink-0 text-muted-foreground">Automation</span>
174 <span className="min-w-0 flex-1 truncate">{summary}</span>
175 <ChevronDownIcon
176 className={cn(
177 "size-3.5 shrink-0 text-muted-foreground transition-transform",
178 expanded && "rotate-180",
179 )}
180 />
181 </button>
182 {bodyMounted ? (
183 // `beforematch` does not bubble, so the reveal listener sits on the hidden fold itself.
184 <div
185 ref={revealRef}
186 hidden={!expanded}
187 className={cn("px-3 pb-3", !ctx.findActive && "max-h-96 overflow-auto")}
188 data-thread-find-text="true"
189 >
190 <UserMessageBody text={text} skills={ctx.skills} markdownCwd={ctx.markdownCwd} />
191 </div>
192 ) : null}
193 </div>
194 <UserMessageProjectedStatus row={row} />
195 {expanded ? (
196 <div className="flex w-full max-w-[80%] items-center justify-end pe-1 text-xs tabular-nums opacity-0 transition-opacity duration-200 pointer-coarse:opacity-100 focus-within:opacity-100 group-hover:opacity-100">
197 <div className="flex shrink-0 items-center gap-2">
198 {scheduledTaskId ? (
199 <Link
200 to="/settings/scheduled-tasks"
201 search={{ environmentId: ctx.activeThreadEnvironmentId, taskId: scheduledTaskId }}
202 className="rounded-sm text-xs text-muted-foreground hover:underline focus-visible:outline-2 focus-visible:outline-ring"
203 >
204 Open automation
205 </Link>
206 ) : null}
207 <TimelineRowTimestamp
208 createdAt={row.message.createdAt}
209 timestampFormat={ctx.timestampFormat}
210 alwaysVisible
211 />
212 <div className="flex items-center gap-0.5">
213 {typeof revertTurnCount === "number" && (
214 <RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />
215 )}
216 <MessageCopyButton text={text} variant="ghost" />
217 {promptLink !== null && (
218 <MessageCopyButton
219 text={promptLink}
220 label="Copy prompt link"
221 icon={LinkIconNode}
222 variant="ghost"
223 />
224 )}
225 </div>
226 </div>
227 </div>
228 ) : null}
229 </div>
230 );
232​
233function UserMessageProjectedStatus({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
234 const status = row.projectedItem?.item.status;
235 if (
236 status === undefined ||
237 status === "completed" ||
238 status === "pending" ||
239 status === "waiting"
240 )
241 return null;
242 return (
243 <div className="me-1 flex items-center gap-1.5">
244 <span className="rounded-full border border-destructive/25 bg-destructive/8 px-1.5 py-0.5 text-3xs font-medium text-destructive">
245 {status}
246 </span>
247 </div>
248 );
250​
251function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
252 const ctx = use(TimelineRowCtx);
253 const { onImageExpand, onFileOpen } = ctx;
254 const senderThreadId = row.message.senderThreadId;
255 const resources = selectMessageImageResources(row.message.attachments);
256 const previewUrls = useAssetUrls(ctx.activeThreadEnvironmentId, resources);
257 const [projectPreviews] = useState(createMessageAttachmentPreviewProjector);
258 const previewUrlsById = new Map(
259 resources.flatMap((resource, index) => {
260 const url = previewUrls[index];
261 return url ? [[resource.attachmentId, url] as const] : [];
262 }),
263 );
264 const messageWithPreviews = projectPreviews(row.message, (attachment) =>
265 previewUrlsById.get(attachment.id),
266 );
267 const userImages = (messageWithPreviews.attachments ?? []).filter(isImageAttachment);
268 const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
269 const userVideos = userFiles.filter(isVideoAttachment);
270 const otherUserFiles = userFiles.filter((file) => !isVideoAttachment(file));
271 const unknownAttachments = (row.message.attachments ?? []).filter(
272 (attachment) => !isImageAttachment(attachment) && !isFileAttachment(attachment),
273 );
274 const userMessage = resolveUserMessagePresentation(row.message);
275 const resolvedContext = resolveUserMessageContext(row.message);
276 const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
277 const revertTurnCount = row.revertTurnCount;
278 const chippedAttachmentIds = new Set(
279 collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => {
280 const record = asKnownContextRecord(resolvedContext.recordsById.get(occurrence.contextId));
281 return record?.kind === "file" || record?.kind === "image" ? [record.attachmentId] : [];
282 }),
283 );
284 const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
285 const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));
286 const annotationRecordIds = resolvedContext.records
287 .filter((record) => record.kind === "preview-annotation")
288 .map((record) => record.contextId);
289 const plainText = replaceComposerContextReferences(
290 resolvedContext.text,
291 (reference) => reference.label,
292 );
293 const promptLink = promptLinkFor(plainText);
294 const contextClipboardFragment =
295 resolvedContext.records.length === 0
296 ? null
297 : encodeComposerContextFragment({
298 version: 1,
299 source: {
300 environmentId: ctx.activeThreadEnvironmentId,
301 ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
302 messageId: row.message.id,
303 },
304 records: resolvedContext.records,
305 });
306 const onBodyCopyCapture = (event: React.ClipboardEvent<HTMLDivElement>) => {
307 if (resolvedContext.records.length === 0 || !event.clipboardData) return;
308 const selection = window.getSelection();
309 if (!selection || selection.isCollapsed) return;
310 const copiedMarkdown: string[] = [];
311 for (let index = 0; index < selection.rangeCount; index += 1) {
312 const container = document.createElement("div");
313 container.appendChild(selection.getRangeAt(index).cloneContents());
314 // Diagram source is copied text, not authority to export context records.
315 for (const element of container.querySelectorAll(
316 "[data-markdown-copy]:not([data-markdown-mermaid])",
317 )) {
318 copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");
319 }
320 }
321 const fragment = selectedMessageContextFragment({
322 markdown: copiedMarkdown.join("\n"),
323 records: resolvedContext.records,
324 environmentId: ctx.activeThreadEnvironmentId,
325 ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
326 messageId: row.message.id,
327 });
328 if (!fragment) return;
329 // Claim the copy: without preventDefault the browser default overwrites the
330 // custom MIME type. The default content must then be written back explicitly.
331 const payload = chatMarkdownClipboardPayload(selection);
332 event.preventDefault();
333 event.clipboardData.setData("text/plain", payload?.text ?? selection.toString());
334 if (payload) {
335 event.clipboardData.setData(
336 "text/html",
337 encodeComposerContextClipboardHtml(payload.text, fragment, payload.html),
338 );
339 }
340 event.clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);
341 };
342 const renderContextReference = (reference: ChatMarkdownContextReference) => {
343 const record = asKnownContextRecord(resolvedContext.recordsById.get(reference.contextId));
344 const annotationImage =
345 record?.kind === "preview-annotation"
346 ? resolvePreviewAnnotationImage({
347 record,
348 recordsById: resolvedContext.recordsById,
349 userImages,
350 previewImages,
351 annotationRecordIds,
352 })
353 : null;
354 const attachment =
355 record?.kind === "image"
356 ? (userImages.find((image) => image.id === record.attachmentId) ?? null)
357 : record?.kind === "file"
358 ? (userFiles.find((file) => file.id === record.attachmentId) ?? null)
359 : null;
360 return (
361 <span data-thread-find-ignore>
362 <UserMessageContextReferenceChip
363 reference={reference}
364 record={record}
365 annotationImage={annotationImage}
366 attachment={attachment}
367 onExpandImage={(image) => {
368 const preview = buildExpandedImagePreview(userImages, image.id);
369 if (preview) onImageExpand(preview);
370 }}
371 onOpenFile={onFileOpen}
372 onExpandVideo={(file) => {
373 const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
374 if (preview) onImageExpand(preview);
375 }}
376 />
377 </span>
378 );
379 };
380​
381 return (
382 <div className="group flex flex-col items-end gap-1">
383 {userMessage.attribution === "t3code" ? (
384 <p
385 className="me-1 text-2xs text-muted-foreground/70"
386 data-user-message-attribution="t3code"
387 >
388 Sent by T3 Code
389 </p>
390 ) : userMessage.attribution === "agent" ? (
391 <p className="me-1 text-2xs text-muted-foreground/70" data-user-message-attribution="agent">
392 {senderThreadId ? (
393 <InlineButton
394 onClick={() => ctx.onOpenThread(senderThreadId)}
395 tone="muted"
396 aria-label="Open sending thread"
397 >
398 Sent by another agent
399 </InlineButton>
400 ) : (
401 "Sent by another agent"
402 )}
403 </p>
404 ) : null}
405 {row.message.inputIntent === "steer" ||
406 row.message.inputIntent === "promoted_queued_to_steer" ? (
407 <UserMessageIntentMarker intent={row.message.inputIntent} />
408 ) : null}
409 <div className="relative max-w-[80%] rounded-2xl bg-message p-3 text-message-foreground">
410 <MessageAuthorHeading>You</MessageAuthorHeading>
411 {(regularImages.length > 0 || userVideos.length > 0) && (
412 <div className="mb-2 grid max-w-[210px] grid-cols-2 gap-2">
413 {regularImages.map((image) => (
414 <div
415 key={image.id}
416 className={cn(
417 "bg-background/70",
418 image.source?.kind === "snap-shot" && image.previewUrl
419 ? cn(SNAP_SHOT_ATTACHMENT_FRAME_CLASS, "col-span-2")
420 : "aspect-[4/3] overflow-hidden rounded-lg border border-border/80",
421 )}
422 >
423 {image.previewUrl ? (
424 <button
425 type="button"
426 className="block h-full w-full cursor-zoom-in"
427 aria-label={`Preview ${image.name}`}
428 onClick={() => {
429 const preview = buildExpandedImagePreview(regularImages, image.id);
430 if (!preview) return;
431 ctx.onImageExpand(preview);
432 }}
433 >
434 <AttachmentImage
435 name={image.name}
436 mimeType={image.mimeType}
437 src={image.previewUrl}
438 alt={image.name}
439 decoding="async"
440 className="block size-full object-cover"
441 />
442 </button>
443 ) : (
444 <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-2xs text-muted-foreground/70">
445 {image.name}
446 </div>
447 )}
448 {image.previewUrl && image.source?.kind === "snap-shot" ? (
449 <SnapShotAttachmentDetails source={image.source} />
450 ) : null}
451 </div>
452 ))}
453 {userVideos.map((file) => (
454 <UserVideoAttachment key={file.id} file={file} />
455 ))}
456 </div>
457 )}
458 {unchippedFiles.length > 0 || unknownAttachments.length > 0 ? (
459 <div className="mb-2 flex flex-col gap-1">
460 {unchippedFiles.map((file) => {
461 const fileIdentity = (
462 <>
463 <PierreEntryIcon pathValue={file.name} kind="file" theme={ctx.resolvedTheme} />
464 <span className="min-w-0 flex-1 truncate">{file.name}</span>
465 </>
466 );
467 if (file.downloadable !== false) {
468 return (
469 <div key={file.id} className="flex min-w-0 items-center gap-1">
470 <button
471 type="button"
472 aria-label={`Preview ${file.name}`}
473 onClick={() => ctx.onFileOpen(file)}
474 className="focus-visible:ring-ring/70 flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-sm hover:underline focus-visible:ring-2 focus-visible:ring-inset focus-visible:outline-none"
475 >
476 {fileIdentity}
477 <EyeIcon className="size-4 shrink-0" />
478 </button>
479 <Tooltip>
480 <TooltipTrigger
481 render={
482 <Button
483 size="icon-xs"
484 variant="ghost-muted"
485 aria-label={`Download ${file.name}`}
486 onClick={() => ctx.onFileDownload(file)}
487 />
488 }
489 >
490 <DownloadIcon />
491 </TooltipTrigger>
492 <TooltipPopup side="top">Download {file.name}</TooltipPopup>
493 </Tooltip>
494 </div>
495 );
496 }
497​
498 return (
499 <div key={file.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
500 {fileIdentity}
501 </div>
502 );
503 })}
504 {unknownAttachments.map((attachment) => (
505 <div key={attachment.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
506 <PierreEntryIcon
507 pathValue={attachment.name}
508 kind="file"
509 theme={ctx.resolvedTheme}
510 />
511 <span className="min-w-0 flex-1 truncate">{attachment.name}</span>
512 </div>
513 ))}
514 </div>
515 ) : null}
516 <div onCopyCapture={onBodyCopyCapture}>
517 <CollapsibleUserMessageBody
518 text={resolvedContext.text}
519 renderContextReference={renderContextReference}
520 skills={ctx.skills}
521 markdownCwd={ctx.markdownCwd}
522 />
523 </div>
524 </div>
525 <UserMessageProjectedStatus row={row} />
526 <div className="flex w-full max-w-[80%] items-center justify-end pe-1 text-xs tabular-nums opacity-0 transition-opacity duration-200 pointer-coarse:opacity-100 focus-within:opacity-100 group-hover:opacity-100">
527 <div className="flex shrink-0 items-center gap-2">
528 <Tooltip>
529 <TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
530 {formatDayAwareTimestamp(row.message.createdAt, ctx.timestampFormat)}
531 </TooltipTrigger>
532 <TooltipPopup>
533 {formatChatTimestampTooltip(row.message.createdAt, ctx.timestampFormat)}
534 </TooltipPopup>
535 </Tooltip>
536 <div className="flex items-center gap-0.5">
537 {typeof revertTurnCount === "number" && (
538 <RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />
539 )}
540 {resolvedContext.text && (
541 <MessageCopyButton
542 text={contextClipboardFragment ? resolvedContext.text : plainText}
543 {...(contextClipboardFragment
544 ? {
545 extraFlavors: { [COMPOSER_CONTEXT_CLIPBOARD_MIME]: contextClipboardFragment },
546 }
547 : {})}
548 variant="ghost"
549 />
550 )}
551 {promptLink !== null && (
552 <MessageCopyButton
553 text={promptLink}
554 label="Copy prompt link"
555 icon={LinkIconNode}
556 variant="ghost"
557 />
558 )}
559 </div>
560 </div>
561 </div>
562 </div>
563 );
565​
566function UserMessageIntentMarker({
567 intent,
568}: {
569 readonly intent: "steer" | "promoted_queued_to_steer";
570}) {
571 return (
572 <Tooltip>
573 <TooltipTrigger
574 render={
575 <div
576 className="me-1 flex items-center justify-end gap-1 text-xs leading-none text-muted-foreground"
577 data-user-message-intent={intent}
578 />
579 }
580 >
581 <Redo2Icon aria-hidden="true" className="size-3" />
582 Steer
583 </TooltipTrigger>
584 <TooltipPopup side="top">
585 {intent === "promoted_queued_to_steer"
586 ? "Originally queued, then promoted to steer the active turn"
587 : "Steered the active turn"}
588 </TooltipPopup>
589 </Tooltip>
590 );
592​
593function RevertUserMessageButton({
594 turnCount,
595 messageId,
596}: {
597 turnCount: number;
598 messageId: MessageId;
599}) {
600 const ctx = use(TimelineRowCtx);
601 const activity = use(TimelineRowActivityCtx);
602​
603 return (
604 <Tooltip>
605 <TooltipTrigger
606 render={
607 <Button
608 type="button"
609 size="xs"
610 variant="ghost"
611 disabled={activity.isRevertingCheckpoint || activity.isWorking}
612 onClick={() => ctx.onRevertToTurnCount(turnCount, messageId)}
613 aria-label="Edit from here"
614 />
615 }
616 >
617 <Undo2Icon className="size-3" />
618 </TooltipTrigger>
619 <TooltipPopup side="top">Edit from here</TooltipPopup>
620 </Tooltip>
621 );
623​
624const COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM = 1.75;
625​
626const COLLAPSED_USER_MESSAGE_FADE_MASK = `linear-gradient(to bottom, black calc(100% - ${COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM}rem), transparent)`;
627​
628const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(props: {
629 text: string;
630 renderContextReference: (reference: ChatMarkdownContextReference) => ReactNode;
631 skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
632 markdownCwd: string | undefined;
633 footer?: ReactNode;
634}) {
635 const [expanded, setExpanded] = useState(false);
636 const revealForFind = () => setExpanded(true);
637 const revealRef = findRevealRef(revealForFind);
638 const hasVisibleBody = props.text.trim().length > 0;
639 const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text);
640 const isCollapsed = canCollapse && !expanded;
641 const showCollapseControl = canCollapse;
642​
643 return (
644 <div>
645 {hasVisibleBody ? (
646 <div
647 ref={revealRef}
648 className={cn("relative", isCollapsed && "max-h-44 overflow-hidden")}
649 data-user-message-body="true"
650 data-thread-find-text="true"
651 data-thread-find-fold={isCollapsed ? "" : undefined}
652 data-user-message-collapsed={isCollapsed ? "true" : "false"}
653 data-user-message-collapsible={canCollapse ? "true" : "false"}
654 data-user-message-fade={isCollapsed ? "true" : "false"}
655 style={
656 isCollapsed
657 ? {
658 WebkitMaskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
659 maskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
660 }
661 : undefined
662 }
663 >
664 <UserMessageBody
665 text={props.text}
666 renderContextReference={props.renderContextReference}
667 skills={props.skills}
668 markdownCwd={props.markdownCwd}
669 />
670 </div>
671 ) : null}
672 {showCollapseControl || props.footer ? (
673 <div
674 className={cn(
675 "mt-1.5 flex items-center gap-2",
676 showCollapseControl && props.footer ? "justify-between" : "justify-end",
677 )}
678 data-user-message-footer="true"
679 >
680 {showCollapseControl ? (
681 <Button
682 type="button"
683 size="xs"
684 variant="ghost-muted"
685 aria-expanded={expanded}
686 data-scroll-anchor-ignore
687 onClick={() => setExpanded((value) => !value)}
688 className="-ml-1"
689 >
690 {expanded ? "Show less" : "Show full message"}
691 </Button>
692 ) : null}
693 {props.footer ? (
694 <div className="ml-auto flex items-center gap-2">{props.footer}</div>
695 ) : null}
696 </div>
697 ) : null}
698 </div>
699 );
700});
701​
702const UserMessageBody = memo(function UserMessageBody(props: {
703 text: string;
704 renderContextReference?: (reference: ChatMarkdownContextReference) => ReactNode;
705 skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
706 markdownCwd: string | undefined;
707}) {
708 const ctx = use(TimelineRowCtx);
709 if (props.text.length === 0) {
710 return null;
711 }
712 return (
713 <ChatMarkdown
714 text={props.text}
715 cwd={props.markdownCwd}
716 threadRef={ctx.threadRef ?? undefined}
717 skills={props.skills}
718 className="text-foreground"
719 lineBreaks
720 parseRawHtml={false}
721 renderContextReference={props.renderContextReference}
722 headingLevelOffset={MESSAGE_HEADING_LEVEL}
723 />
724 );
725});