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

TimelineUserMessageRow.tsx

841 lines32.4 KB

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