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

TimelineUserMessageRow.tsx

914 lines35.7 KB

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