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

TimelineUserMessageRow.tsx

1,182 lines44.1 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 { formatBytes } from "../../lib/formatBytes";
58import { shouldCollapseUserMessage } from "./MessagesTimeline.logic";
59import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
60import {
61 asKnownContextRecord,
62 resolveUserMessageContext,
63 selectedMessageContextFragment,
64} from "~/lib/composerContextRecords";
65import {
66 collectComposerContextReferences,
67 formatComposerContextReference,
68} from "@t3tools/shared/composerContextReferences";
69import {
70 COMPOSER_CONTEXT_CLIPBOARD_MIME,
71 encodeComposerContextClipboardHtml,
72 encodeComposerContextFragment,
73} from "@t3tools/shared/composerContextClipboard";
74import { chatMarkdownClipboardPayload } from "../../markdown-clipboard";
75import type { ChatMarkdownContextReference } from "../ChatMarkdown";
76import { cn } from "~/lib/utils";
77import { useMediaQuery } from "~/hooks/useMediaQuery";
78import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
79import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
80import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext";
81import {
82 MESSAGE_HEADING_LEVEL,
83 MessageAuthorHeading,
84 TimelineRowTimestamp,
85} from "./TimelineRowParts";
86import { UserMessageContextReferenceChip } from "./UserMessageContextChips";
87import {
88 resolvePreviewAnnotationImage,
89 userMessageFileLabel,
90} from "./TimelineUserMessageRow.logic";
91​
92// Drawn inside the media so dark screenshots keep an edge on the dark background.
93const MEDIA_EDGE_CLASS_NAME =
94 "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";
95​
96const BUBBLE_CHIP_CLASS_NAME =
97 "[&_[data-slot=context-chip]]:[--context-chip-ink:var(--context-chip-message,var(--context-chip-accent))]";
98​
99function UserFileCard({
100 file,
101 copyMarkdown,
102}: {
103 readonly file: ChatFileAttachment;
104 readonly copyMarkdown: string | undefined;
105}) {
106 const ctx = use(TimelineRowCtx);
107 const pastedText = file.source?._tag === "pasted-text";
108 const label = userMessageFileLabel(file);
109 const extension = /\.([a-z0-9]{1,8})$/i.exec(file.name)?.[1]?.toUpperCase() ?? "File";
110 const identity = (
111 <>
112 <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-background/60">
113 <PierreEntryIcon pathValue={file.name} kind="file" theme={ctx.resolvedTheme} />
114 </span>
115 <span className="min-w-0 flex-1">
116 <span className="block truncate text-sm font-medium group-hover/file:underline">
117 {label}
118 </span>
119 <span className="block text-xs text-muted-foreground tabular-nums">
120 {file.downloadable === false ? (
121 "Sending…"
122 ) : (
123 <>
124 {!pastedText && `${extension} · `}
125 {formatBytes(file.sizeBytes)}
126 </>
127 )}
128 </span>
129 </span>
130 </>
131 );
132 return (
133 <div
134 data-markdown-copy={copyMarkdown}
135 className="flex w-64 max-w-full items-center gap-1 rounded-2xl bg-message py-2 ps-2 pe-1 text-message-foreground"
136 >
137 {file.downloadable === false ? (
138 <>
139 <div className="flex min-w-0 flex-1 items-center gap-3">{identity}</div>
140 <Button size="icon-xs" variant="ghost-muted" disabled aria-label="Sending attachment">
141 <DownloadIcon />
142 </Button>
143 </>
144 ) : (
145 <>
146 <button
147 type="button"
148 aria-label={`Preview ${label}`}
149 onClick={() => ctx.onFileOpen(file)}
150 className="group/file focus-visible:ring-ring/70 flex min-w-0 flex-1 cursor-pointer items-center gap-3 rounded-xl text-left focus-visible:ring-2 focus-visible:ring-inset focus-visible:outline-none"
151 >
152 {identity}
153 </button>
154 <Tooltip>
155 <TooltipTrigger
156 render={
157 <Button
158 size="icon-xs"
159 variant="ghost-muted"
160 aria-label={`Download ${label}`}
161 onClick={() => ctx.onFileDownload(file)}
162 />
163 }
164 >
165 <DownloadIcon />
166 </TooltipTrigger>
167 <TooltipPopup side="top">Download {label}</TooltipPopup>
168 </Tooltip>
169 </>
170 )}
171 </div>
172 );
174​
175function UserVideoAttachment({
176 file,
177 standalone = false,
178 cornerClassName,
179}: {
180 readonly file: ChatFileAttachment;
181 readonly standalone?: boolean;
182 readonly cornerClassName?: string | undefined;
183}) {
184 const ctx = use(TimelineRowCtx);
185 // Row updates rebuild attachment objects, so the asset follows only the
186 // fields it reads.
187 const { downloadable, id, mimeType, name } = file;
188 const environmentId = ctx.activeThreadEnvironmentId;
189 const asset =
190 downloadable === false
191 ? null
192 : buildAttachmentVideoAsset(environmentId, { id, mimeType, name });
193 const resource = asset?.resource ?? null;
194 const assetUrl = useAssetUrlState(ctx.activeThreadEnvironmentId, resource);
195 const refreshAssetUrl = useAssetUrlRefresh(ctx.activeThreadEnvironmentId, resource);
196 const src = assetUrl._tag === "Success" ? assetUrl.url : (file.previewUrl ?? null);
197​
198 if (asset === null && src === null) {
199 return (
200 <div
201 className={cn(
202 "flex aspect-[4/3] w-full items-center justify-center bg-black px-2 py-3 text-center text-2xs text-white/70",
203 standalone
204 ? cn(MEDIA_EDGE_CLASS_NAME, "rounded-2xl", cornerClassName)
205 : "rounded-lg border border-border/80",
206 )}
207 >
208 {file.name}
209 </div>
210 );
211 }
212​
213 const player = (
214 <MediaVideoPlayer
215 src={src}
216 sourceFailed={
217 file.previewUrl === undefined && resource !== null && assetUrl._tag === "Failure"
218 }
219 label={file.name}
220 preload="visible"
221 onOpen={() => {
222 const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
223 if (preview) ctx.onImageExpand(preview);
224 }}
225 className="block aspect-[4/3] w-full"
226 videoClassName={cn(
227 "aspect-auto size-full",
228 !standalone && "rounded-lg border border-border/80",
229 )}
230 stateClassName={cn(
231 "aspect-auto min-h-full bg-black text-white",
232 !standalone && "rounded-lg border border-border/80",
233 )}
234 onRetry={asset ? refreshAssetUrl : undefined}
235 actionsSource={asset ? { kind: "video", name: file.name, src, asset } : undefined}
236 />
237 );
238 return standalone ? (
239 <div className={cn(MEDIA_EDGE_CLASS_NAME, "overflow-hidden rounded-2xl", cornerClassName)}>
240 {player}
241 </div>
242 ) : (
243 player
244 );
246​
247export function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
248 const ctx = use(TimelineRowCtx);
249 return ctx.workflowOpening?.messageId === row.message.id ? (
250 <WorkflowOpeningBlock
251 opening={ctx.workflowOpening}
252 environmentId={ctx.activeThreadEnvironmentId}
253 onOpenThread={(threadId) => ctx.onOpenThread(ThreadId.make(threadId))}
254 />
255 ) : resolveUserMessagePresentation(row.message).attribution === "automation" ? (
256 <AutomationMessageRow row={row} />
257 ) : (
258 <UserTimelineRow row={row} />
259 );
261​
262/** Automation prompts are long, repeated runbooks; a folded bubble keeps them out of the way. */
263function AutomationMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
264 const ctx = use(TimelineRowCtx);
265 const [expanded, setExpanded] = useState(false);
266 const revealRef = findRevealRef(() => setExpanded(true));
267 const { text, scheduledTaskId } = resolveUserMessagePresentation(row.message);
268 const summary =
269 useScheduledTaskTitle(ctx.activeThreadEnvironmentId, scheduledTaskId) ??
270 text.trim().split(/\r?\n/, 1)[0] ??
271 "";
272​
273 const revertTurnCount = row.revertTurnCount;
274 const promptLink = promptLinkFor(text);
275 // Find reads the DOM, so a folded prompt stays mounted but hidden while find is open.
276 const bodyMounted = expanded || ctx.findActive;
277​
278 return (
279 <div className="group flex flex-col items-end gap-1" data-user-message-attribution="automation">
280 {row.message.inputIntent === "steer" ||
281 row.message.inputIntent === "promoted_queued_to_steer" ? (
282 <UserMessageIntentMarker intent={row.message.inputIntent} />
283 ) : null}
284 <div
285 className={cn(
286 "min-w-0 max-w-[80%] rounded-2xl bg-message text-message-foreground",
287 BUBBLE_CHIP_CLASS_NAME,
288 expanded && "w-full",
289 )}
290 >
291 <MessageAuthorHeading>Automation</MessageAuthorHeading>
292 <FoldedMessageHeader
293 icon={CalendarClockIcon}
294 label="Automation"
295 summary={summary}
296 expanded={expanded}
297 onToggle={() => setExpanded((value) => !value)}
298 />
299 {bodyMounted ? (
300 // `beforematch` does not bubble, so the reveal listener sits on the hidden fold itself.
301 <div
302 ref={revealRef}
303 hidden={!expanded}
304 className={cn("px-3 pb-3", !ctx.findActive && "max-h-96 overflow-auto")}
305 data-thread-find-text="true"
306 >
307 <UserMessageBody text={text} skills={ctx.skills} markdownCwd={ctx.markdownCwd} />
308 </div>
309 ) : null}
310 </div>
311 <UserMessageProjectedStatus row={row} />
312 {expanded ? (
313 <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">
314 <div className="flex shrink-0 items-center gap-2">
315 {scheduledTaskId ? (
316 <Link
317 to="/settings/scheduled-tasks"
318 search={{ environmentId: ctx.activeThreadEnvironmentId, taskId: scheduledTaskId }}
319 className="rounded-sm text-xs text-muted-foreground hover:underline focus-visible:outline-2 focus-visible:outline-ring"
320 >
321 Open automation
322 </Link>
323 ) : null}
324 <TimelineRowTimestamp
325 createdAt={row.message.createdAt}
326 timestampFormat={ctx.timestampFormat}
327 alwaysVisible
328 />
329 <div className="flex items-center gap-0.5">
330 {typeof revertTurnCount === "number" && (
331 <RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />
332 )}
333 <MessageCopyButton text={text} variant="ghost" />
334 {promptLink !== null && (
335 <MessageCopyButton
336 text={promptLink}
337 label="Copy prompt link"
338 icon={LinkIconNode}
339 variant="ghost"
340 />
341 )}
342 </div>
343 </div>
344 </div>
345 ) : null}
346 </div>
347 );
349​
350export function useScheduledTaskTitle(
351 environmentId: EnvironmentId,
352 scheduledTaskId: ScheduledTaskId | undefined,
353): string | undefined {
354 const tasksQuery = useEnvironmentQuery(
355 scheduledTaskId ? serverEnvironment.scheduledTasksLive({ environmentId, input: {} }) : null,
356 );
357 return tasksQuery.data?.tasks.find((task) => task.id === scheduledTaskId)?.title;
359​
360export function FoldedMessageHeader(props: {
361 icon: LucideIcon;
362 label: string;
363 summary: string;
364 expanded: boolean;
365 onToggle: () => void;
366}) {
367 const Icon = props.icon;
368 return (
369 <button
370 type="button"
371 aria-expanded={props.expanded}
372 data-scroll-anchor-ignore
373 onClick={props.onToggle}
374 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"
375 >
376 <Icon className="size-4 shrink-0 stroke-2 text-muted-foreground" />
377 <span className="max-w-1/2 shrink-0 truncate text-muted-foreground">{props.label}</span>
378 <span className="min-w-0 flex-1 truncate">{props.summary}</span>
379 <ChevronDownIcon
380 className={cn(
381 "size-3.5 shrink-0 text-muted-foreground transition-transform",
382 props.expanded && "rotate-180",
383 )}
384 />
385 </button>
386 );
388​
389function UserMessageProjectedStatus({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
390 const status = row.projectedItem?.item.status;
391 if (
392 status === undefined ||
393 status === "completed" ||
394 status === "pending" ||
395 status === "waiting"
396 )
397 return null;
398 return (
399 <div className="me-1 flex items-center gap-1.5">
400 <span className="rounded-full border border-destructive/25 bg-destructive/8 px-1.5 py-0.5 text-3xs font-medium text-destructive">
401 {status}
402 </span>
403 </div>
404 );
406​
407function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
408 const ctx = use(TimelineRowCtx);
409 const { onImageExpand, onFileOpen } = ctx;
410 const coarsePointer = useMediaQuery({ pointer: "coarse" });
411 const senderThreadId = row.message.senderThreadId;
412 const resources = selectMessageImageResources(row.message.attachments);
413 const previewUrls = useAssetUrls(ctx.activeThreadEnvironmentId, resources);
414 const [projectPreviews] = useState(createMessageAttachmentPreviewProjector);
415 const previewUrlsById = new Map(
416 resources.flatMap((resource, index) => {
417 const url = previewUrls[index];
418 return url ? [[resource.attachmentId, url] as const] : [];
419 }),
420 );
421 const messageWithPreviews = projectPreviews(row.message, (attachment) =>
422 previewUrlsById.get(attachment.id),
423 );
424 const userImages = (messageWithPreviews.attachments ?? []).filter(isImageAttachment);
425 const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
426 const userVideos = userFiles.filter(isVideoAttachment);
427 const userAudio = userFiles.filter(
428 (file) => file.downloadable !== false && filePreviewKind(file) === "audio",
429 );
430 const otherUserFiles = userFiles.filter(
431 (file) => !isVideoAttachment(file) && !userAudio.includes(file),
432 );
433 const unknownAttachments = (row.message.attachments ?? []).filter(
434 (attachment) => !isImageAttachment(attachment) && !isFileAttachment(attachment),
435 );
436 const userMessage = resolveUserMessagePresentation(row.message);
437 // Messages from other agents fold to one line so the user's own messages stay easy to find.
438 const folded = userMessage.attribution === "agent";
439 const [expanded, setExpanded] = useState(false);
440 const revealFoldRef = findRevealRef(() => setExpanded(true));
441 const senderShell = useQuietThreadShell(
442 folded && senderThreadId
443 ? { environmentId: ctx.activeThreadEnvironmentId, threadId: senderThreadId }
444 : null,
445 );
446 const senderLabel = senderShell?.title.trim() || "Agent";
447 const resolvedContext = resolveUserMessageContext({ ...row.message, text: userMessage.text });
448 const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
449 const revertTurnCount = row.revertTurnCount;
450 const attachmentReferences = collectComposerContextReferences(resolvedContext.text).flatMap(
451 (occurrence) => {
452 const record = asKnownContextRecord(resolvedContext.recordsById.get(occurrence.contextId));
453 return record?.kind === "file" || record?.kind === "image"
454 ? [
455 {
456 attachmentId: record.attachmentId,
457 contextId: occurrence.contextId,
458 source: occurrence.source,
459 },
460 ]
461 : [];
462 },
463 );
464 const chippedAttachmentIds = new Set(
465 attachmentReferences.map((reference) => reference.attachmentId),
466 );
467 const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
468 const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));
469 // Images or videos sent without words show as media, not as a bubble around them.
470 const mediaOnly =
471 !folded &&
472 userMessage.attribution !== "guest" &&
473 resolvedContext.text.trim() === "" &&
474 userAudio.length === 0 &&
475 unchippedFiles.length === 0 &&
476 unknownAttachments.length === 0 &&
477 regularImages.length + userVideos.length > 0;
478 // Media sent with words sits above the bubble as its own shape, like a chat app.
479 const mediaAboveText =
480 !folded &&
481 userMessage.attribution !== "guest" &&
482 !mediaOnly &&
483 regularImages.length + userVideos.length > 0;
484 const standaloneMedia = mediaOnly || mediaAboveText;
485 // A lone image keeps its own shape; a 4:3 crop hides most of a wide screenshot.
486 const loneImage = standaloneMedia && userVideos.length === 0 && regularImages.length === 1;
487 // Several images share one rounded shape, split by hairlines.
488 const collage =
489 standaloneMedia &&
490 userVideos.length === 0 &&
491 regularImages.length > 1 &&
492 regularImages.every((image) => image.source?.kind !== "snap-shot");
493 // Corners that touch the bubble or a neighbouring message tighten, like the bubble's.
494 const mediaCornerClassName = cn(
495 row.groupedWithPrevious && "rounded-tr-md",
496 (mediaAboveText || row.groupedWithNext) && "rounded-br-md",
497 );
498 // Files sent without words show as cards, not as a bubble around a name chip.
499 const fileCardsOnly =
500 !folded &&
501 userMessage.attribution !== "guest" &&
502 otherUserFiles.length > 0 &&
503 regularImages.length + userVideos.length + userAudio.length + unknownAttachments.length === 0 &&
504 replaceComposerContextReferences(resolvedContext.text, (reference) =>
505 attachmentReferences.some(
506 (attached) =>
507 attached.contextId === reference.contextId &&
508 otherUserFiles.some((file) => file.id === attached.attachmentId),
509 )
510 ? ""
511 : reference.label,
512 ).trim() === "";
513 const audioOnly =
514 !folded &&
515 userMessage.attribution !== "guest" &&
516 userAudio.length > 0 &&
517 regularImages.length + userVideos.length + otherUserFiles.length + unknownAttachments.length ===
518 0 &&
519 replaceComposerContextReferences(resolvedContext.text, (reference) =>
520 attachmentReferences.some(
521 (attached) =>
522 attached.contextId === reference.contextId &&
523 userAudio.some((file) => file.id === attached.attachmentId),
524 )
525 ? ""
526 : reference.label,
527 ).trim() === "";
528 const annotationRecordIds = resolvedContext.records
529 .filter((record) => record.kind === "preview-annotation")
530 .map((record) => record.contextId);
531 const plainText = replaceComposerContextReferences(
532 resolvedContext.text,
533 (reference) => reference.label,
534 );
535 const promptLink = promptLinkFor(plainText);
536 const foldSummary =
537 plainText
538 .split(/\r?\n/)
539 .find((line) => line.trim().length > 0)
540 ?.trim() ?? "";
541 const mediaCopyRecords = mediaOnly
542 ? resolvedContext.records.flatMap((record) => {
543 const known = asKnownContextRecord(record);
544 return (known?.kind === "image" || known?.kind === "file") &&
545 (regularImages.some((image) => image.id === known.attachmentId) ||
546 userVideos.some((file) => file.id === known.attachmentId))
547 ? [known]
548 : [];
549 })
550 : [];
551 const copyRecords = mediaOnly ? mediaCopyRecords : resolvedContext.records;
552 const contextClipboardFragment =
553 copyRecords.length === 0
554 ? null
555 : encodeComposerContextFragment({
556 version: 1,
557 source: {
558 environmentId: ctx.activeThreadEnvironmentId,
559 ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
560 messageId: row.message.id,
561 },
562 records: copyRecords,
563 });
564 const copyText =
565 resolvedContext.text || mediaCopyRecords.map(formatComposerContextReference).join("\n");
566 const onBodyCopyCapture = (event: React.ClipboardEvent<HTMLDivElement>) => {
567 if (resolvedContext.records.length === 0 || !event.clipboardData) return;
568 const selection = window.getSelection();
569 if (!selection || selection.isCollapsed) return;
570 const copiedMarkdown: string[] = [];
571 for (let index = 0; index < selection.rangeCount; index += 1) {
572 const container = document.createElement("div");
573 container.appendChild(selection.getRangeAt(index).cloneContents());
574 // Diagram source is copied text, not authority to export context records.
575 for (const element of container.querySelectorAll(
576 "[data-markdown-copy]:not([data-markdown-mermaid])",
577 )) {
578 copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");
579 }
580 }
581 const fragment = selectedMessageContextFragment({
582 markdown: copiedMarkdown.join("\n"),
583 records: resolvedContext.records,
584 environmentId: ctx.activeThreadEnvironmentId,
585 ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
586 messageId: row.message.id,
587 });
588 if (!fragment) return;
589 // Claim the copy: without preventDefault the browser default overwrites the
590 // custom MIME type. The default content must then be written back explicitly.
591 const payload = chatMarkdownClipboardPayload(selection);
592 event.preventDefault();
593 event.clipboardData.setData("text/plain", payload?.text ?? selection.toString());
594 if (payload) {
595 event.clipboardData.setData(
596 "text/html",
597 encodeComposerContextClipboardHtml(payload.text, fragment, payload.html),
598 );
599 }
600 event.clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);
601 };
602 const renderContextReference = (reference: ChatMarkdownContextReference) => {
603 const record = asKnownContextRecord(resolvedContext.recordsById.get(reference.contextId));
604 if (record?.kind === "file" && userAudio.some((file) => file.id === record.attachmentId))
605 return null;
606 const annotationImage =
607 record?.kind === "preview-annotation"
608 ? resolvePreviewAnnotationImage({
609 record,
610 recordsById: resolvedContext.recordsById,
611 userImages,
612 previewImages,
613 annotationRecordIds,
614 })
615 : null;
616 const attachment =
617 record?.kind === "image"
618 ? (userImages.find((image) => image.id === record.attachmentId) ?? null)
619 : record?.kind === "file"
620 ? (userFiles.find((file) => file.id === record.attachmentId) ?? null)
621 : null;
622 return (
623 <span data-thread-find-ignore>
624 <UserMessageContextReferenceChip
625 reference={reference}
626 record={record}
627 annotationImage={annotationImage}
628 attachment={attachment}
629 onExpandImage={(image) => {
630 const preview = buildExpandedImagePreview(userImages, image.id);
631 if (preview) onImageExpand(preview);
632 }}
633 onOpenFile={onFileOpen}
634 onExpandVideo={(file) => {
635 const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
636 if (preview) onImageExpand(preview);
637 }}
638 />
639 </span>
640 );
641 };
642​
643 const mediaBlock =
644 regularImages.length > 0 || userVideos.length > 0 ? (
645 <div
646 className={cn(
647 "grid",
648 !standaloneMedia
649 ? "mb-2 max-w-[210px] grid-cols-2 gap-2"
650 : loneImage
651 ? "max-w-full"
652 : collage
653 ? cn(
654 MEDIA_EDGE_CLASS_NAME,
655 "w-80 max-w-full gap-px overflow-hidden rounded-2xl bg-black/9 dark:bg-white/12",
656 mediaCornerClassName,
657 regularImages.length === 2
658 ? "auto-rows-[12rem] grid-cols-2"
659 : regularImages.length === 3
660 ? "auto-rows-[calc(6rem-0.5px)] grid-cols-[3fr_2fr]"
661 : "auto-rows-[6rem] grid-cols-2",
662 )
663 : regularImages.length + userVideos.length === 1
664 ? "w-80 max-w-full"
665 : "w-80 max-w-full grid-cols-2 gap-2",
666 )}
667 >
668 {regularImages.map((image, index) => (
669 <div
670 key={image.id}
671 className={cn(
672 "bg-background/70",
673 image.source?.kind === "snap-shot" && image.previewUrl
674 ? cn(
675 "col-span-2",
676 standaloneMedia
677 ? cn(
678 MEDIA_EDGE_CLASS_NAME,
679 "min-h-16 justify-self-end overflow-hidden rounded-2xl",
680 loneImage && mediaCornerClassName,
681 )
682 : SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
683 )
684 : loneImage
685 ? cn(MEDIA_EDGE_CLASS_NAME, "overflow-hidden rounded-2xl", mediaCornerClassName)
686 : collage
687 ? cn(
688 "overflow-hidden bg-background",
689 regularImages.length === 3 && index === 0 && "row-span-2",
690 regularImages.length > 3 &&
691 regularImages.length % 2 === 1 &&
692 index === regularImages.length - 1 &&
693 "col-span-2",
694 )
695 : standaloneMedia
696 ? cn(MEDIA_EDGE_CLASS_NAME, "aspect-[4/3] overflow-hidden rounded-2xl")
697 : "aspect-[4/3] overflow-hidden rounded-lg border border-border/80",
698 )}
699 >
700 {image.previewUrl ? (
701 <button
702 type="button"
703 className="block h-full w-full cursor-zoom-in"
704 aria-label={`Preview ${image.name}`}
705 onClick={() => {
706 const preview = buildExpandedImagePreview(regularImages, image.id);
707 if (!preview) return;
708 ctx.onImageExpand(preview);
709 }}
710 >
711 {/* Isolate the thumbnail raster from nearby activity repaints in Chromium. */}
712 <AttachmentImage
713 name={image.name}
714 mimeType={image.mimeType}
715 src={image.previewUrl}
716 alt={image.name}
717 decoding="async"
718 loading="lazy"
719 className={cn(
720 "block transform-gpu",
721 standaloneMedia && image.source?.kind === "snap-shot"
722 ? "h-auto max-h-48 w-auto min-w-24 max-w-full object-contain"
723 : loneImage
724 ? "h-48 w-auto min-w-24 max-w-full object-cover"
725 : "size-full object-cover",
726 )}
727 />
728 </button>
729 ) : (
730 <div
731 className={cn(
732 "flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-2xs text-muted-foreground/70",
733 loneImage && "h-48 w-64 max-w-full",
734 collage && "h-full",
735 )}
736 >
737 {image.name}
738 </div>
739 )}
740 {image.previewUrl && image.source?.kind === "snap-shot" ? (
741 <SnapShotAttachmentDetails source={image.source} />
742 ) : null}
743 </div>
744 ))}
745 {userVideos.map((file) => (
746 <UserVideoAttachment
747 key={file.id}
748 file={file}
749 standalone={standaloneMedia}
750 cornerClassName={
751 regularImages.length + userVideos.length === 1 ? mediaCornerClassName : undefined
752 }
753 />
754 ))}
755 </div>
756 ) : null;
757​
758 // Touch shows actions all the time, and narrow lanes have no room beside the
759 // bubble, so both keep the actions on their own line.
760 const floatActions = row.groupedWithNext === true && !coarsePointer;
761 const messageActions = (
762 <div
763 className={cn(
764 "flex items-center justify-end gap-x-2 gap-y-0.5",
765 floatActions ? "flex-wrap" : "shrink-0",
766 )}
767 >
768 {folded && senderThreadId ? (
769 <InlineButton onClick={() => ctx.onOpenThread(senderThreadId)} tone="muted">
770 Open thread
771 </InlineButton>
772 ) : null}
773 <Tooltip>
774 <TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
775 {formatDayAwareTimestamp(row.message.createdAt, ctx.timestampFormat)}
776 </TooltipTrigger>
777 <TooltipPopup>
778 {formatChatTimestampTooltip(row.message.createdAt, ctx.timestampFormat)}
779 </TooltipPopup>
780 </Tooltip>
781 <div className={cn("flex items-center gap-0.5", floatActions && "flex-wrap justify-end")}>
782 {typeof revertTurnCount === "number" && (
783 <RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />
784 )}
785 {copyText && (
786 <MessageCopyButton
787 text={contextClipboardFragment ? copyText : plainText}
788 {...(contextClipboardFragment
789 ? {
790 extraFlavors: {
791 [COMPOSER_CONTEXT_CLIPBOARD_MIME]: contextClipboardFragment,
792 },
793 }
794 : {})}
795 variant="ghost"
796 />
797 )}
798 {promptLink !== null && (
799 <MessageCopyButton
800 text={promptLink}
801 label="Copy prompt link"
802 icon={LinkIconNode}
803 variant="ghost"
804 />
805 )}
806 </div>
807 </div>
808 );
809 return (
810 <div
811 className="group @container flex flex-col items-end gap-1"
812 data-user-message-attribution={folded ? "agent" : undefined}
813 >
814 {userMessage.attribution === "t3code" ? (
815 <p
816 className="me-1 text-2xs text-muted-foreground/70"
817 data-user-message-attribution="t3code"
818 >
819 Sent by T3 Code
820 </p>
821 ) : null}
822 {/* The row's heading already names the guest for screen readers. */}
823 {userMessage.guestName !== undefined ? (
824 <div aria-hidden>
825 <GuestMessageName name={userMessage.guestName} />
826 </div>
827 ) : null}
828 {(row.message.inputIntent === "steer" ||
829 row.message.inputIntent === "promoted_queued_to_steer") &&
830 !row.continuesSteer ? (
831 <UserMessageIntentMarker intent={row.message.inputIntent} />
832 ) : null}
833 {mediaAboveText ? (
834 <div className="flex max-w-[80%] justify-end">
835 {/* The heading leads the media so screen readers reach it before the images. */}
836 <MessageAuthorHeading>You</MessageAuthorHeading>
837 {mediaBlock}
838 </div>
839 ) : null}
840 <div
841 className={cn(
842 "relative min-w-0 max-w-[80%] rounded-2xl text-message-foreground",
843 (mediaAboveText || row.groupedWithPrevious) && "rounded-tr-md",
844 row.groupedWithNext && "rounded-br-md",
845 BUBBLE_CHIP_CLASS_NAME,
846 userMessage.attribution === "guest"
847 ? guestBubbleClassName(false)
848 : !mediaOnly && !fileCardsOnly && !audioOnly && "bg-message",
849 !folded && !mediaOnly && !fileCardsOnly && !audioOnly && "p-3",
850 folded && expanded && "w-full",
851 )}
852 >
853 {/* Outside the fold so a collapsed message still has a heading to navigate to. */}
854 {mediaAboveText ? null : (
855 <MessageAuthorHeading>
856 {folded
857 ? senderLabel
858 : userMessage.guestName === undefined
859 ? "You"
860 : `${userMessage.guestName} (guest)`}
861 </MessageAuthorHeading>
862 )}
863 {folded ? (
864 <FoldedMessageHeader
865 icon={MessagesSquareIcon}
866 label={senderLabel}
867 summary={foldSummary}
868 expanded={expanded}
869 onToggle={() => setExpanded((value) => !value)}
870 />
871 ) : null}
872 {/* Find reads the DOM, so a folded message stays mounted but hidden while find is open. */}
873 {!folded || expanded || ctx.findActive ? (
874 <div
875 ref={folded ? revealFoldRef : undefined}
876 hidden={folded && !expanded}
877 className={cn(
878 folded && "px-3 pb-3",
879 folded && !ctx.findActive && "max-h-96 overflow-auto",
880 )}
881 >
882 {!mediaAboveText && mediaBlock}
883 {userAudio.length > 0 ? (
884 <div className={cn("flex max-w-full flex-col gap-1", !audioOnly && "mb-2")}>
885 {userAudio.map((file) => (
886 <InlineAudioPreview
887 key={file.id}
888 name={file.name}
889 variant={audioOnly ? "bubble" : "chip"}
890 environmentId={ctx.activeThreadEnvironmentId}
891 resource={{
892 _tag: "attachment",
893 attachmentId: file.id,
894 fileName: file.name,
895 mimeType: file.mimeType,
896 disposition: "inline",
897 }}
898 onOpen={() => ctx.onFileOpen(file)}
899 />
900 ))}
901 </div>
902 ) : null}
903 {fileCardsOnly ? (
904 <div className="flex flex-col items-end gap-1" onCopyCapture={onBodyCopyCapture}>
905 {otherUserFiles.map((file) => (
906 <UserFileCard
907 key={file.id}
908 file={file}
909 copyMarkdown={
910 attachmentReferences.find((reference) => reference.attachmentId === file.id)
911 ?.source
912 }
913 />
914 ))}
915 </div>
916 ) : null}
917 {!fileCardsOnly && (unchippedFiles.length > 0 || unknownAttachments.length > 0) ? (
918 <div className="mb-2 flex flex-col gap-1">
919 {unchippedFiles.map((file) => {
920 const pastedText = file.source?._tag === "pasted-text";
921 const label = userMessageFileLabel(file);
922 const fileIdentity = (
923 <>
924 <PierreEntryIcon
925 pathValue={file.name}
926 kind="file"
927 theme={ctx.resolvedTheme}
928 />
929 <span className="min-w-0 flex-1">
930 <span className="block truncate">{label}</span>
931 {file.downloadable === false || pastedText ? (
932 <span className="block text-xs text-muted-foreground tabular-nums">
933 {file.downloadable === false ? "Sending…" : formatBytes(file.sizeBytes)}
934 </span>
935 ) : null}
936 </span>
937 </>
938 );
939 if (file.downloadable !== false) {
940 return (
941 <div key={file.id} className="flex min-w-0 items-center gap-1">
942 <button
943 type="button"
944 aria-label={`Preview ${label}`}
945 onClick={() => ctx.onFileOpen(file)}
946 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"
947 >
948 {fileIdentity}
949 <EyeIcon className="size-4 shrink-0" />
950 </button>
951 <Tooltip>
952 <TooltipTrigger
953 render={
954 <Button
955 size="icon-xs"
956 variant="ghost-muted"
957 aria-label={`Download ${label}`}
958 onClick={() => ctx.onFileDownload(file)}
959 />
960 }
961 >
962 <DownloadIcon />
963 </TooltipTrigger>
964 <TooltipPopup side="top">Download {label}</TooltipPopup>
965 </Tooltip>
966 </div>
967 );
968 }
969​
970 return (
971 <div key={file.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
972 {fileIdentity}
973 </div>
974 );
975 })}
976 {unknownAttachments.map((attachment) => (
977 <div key={attachment.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
978 <PierreEntryIcon
979 pathValue={attachment.name}
980 kind="file"
981 theme={ctx.resolvedTheme}
982 />
983 <span className="min-w-0 flex-1 truncate">{attachment.name}</span>
984 </div>
985 ))}
986 </div>
987 ) : null}
988 {fileCardsOnly || audioOnly ? null : (
989 <div onCopyCapture={onBodyCopyCapture}>
990 <CollapsibleUserMessageBody
991 text={resolvedContext.text}
992 renderContextReference={renderContextReference}
993 skills={ctx.skills}
994 markdownCwd={ctx.markdownCwd}
995 collapsible={!folded}
996 />
997 </div>
998 )}
999 </div>
1000 ) : null}
1001 {floatActions ? (
1002 <div
1003 className={cn(
1004 "absolute end-full top-1/2 me-2 hidden w-max max-w-[calc(20cqw-0.5rem)] -translate-y-1/2 @min-[37rem]:flex",
1005 ACTIONS_REVEAL_CLASS_NAME,
1006 )}
1008 {messageActions}
1009 </div>
1010 ) : null}
1011 </div>
1012 <UserMessageProjectedStatus row={row} />
1013 {!folded || expanded ? (
1014 <div
1015 className={cn(
1016 "flex w-full max-w-[80%] justify-end pe-1",
1017 floatActions && "@min-[37rem]:hidden",
1018 ACTIONS_REVEAL_CLASS_NAME,
1019 )}
1021 {messageActions}
1022 </div>
1023 ) : null}
1024 </div>
1025 );
1027​
1028const ACTIONS_REVEAL_CLASS_NAME =
1029 "items-center text-xs tabular-nums opacity-0 transition-opacity duration-200 pointer-coarse:opacity-100 focus-within:opacity-100 group-hover:opacity-100";
1030​
1031function UserMessageIntentMarker({
1032 intent,
1033}: {
1034 readonly intent: "steer" | "promoted_queued_to_steer";
1035}) {
1036 return (
1037 <Tooltip>
1038 <TooltipTrigger
1039 render={
1040 <div
1041 className="me-1 flex items-center justify-end gap-1 text-xs leading-none text-muted-foreground"
1042 data-user-message-intent={intent}
1043 />
1046 <Redo2Icon aria-hidden="true" className="size-3" />
1047 Steer
1048 </TooltipTrigger>
1049 <TooltipPopup side="top">
1050 {intent === "promoted_queued_to_steer"
1051 ? "Originally queued, then promoted to steer the active turn"
1052 : "Steered the active turn"}
1053 </TooltipPopup>
1054 </Tooltip>
1055 );
1057​
1058function RevertUserMessageButton({
1059 turnCount,
1060 messageId,
1061}: {
1062 turnCount: number;
1063 messageId: MessageId;
1064}) {
1065 const ctx = use(TimelineRowCtx);
1066 const activity = use(TimelineRowActivityCtx);
1067​
1068 return (
1069 <Tooltip>
1070 <TooltipTrigger
1071 render={
1072 <Button
1073 type="button"
1074 size="xs"
1075 variant="ghost"
1076 disabled={activity.isRevertingCheckpoint || activity.isWorking}
1077 onClick={() => ctx.onRevertToTurnCount(turnCount, messageId)}
1078 aria-label="Edit from here"
1079 />
1082 <PencilIcon className="size-3" />
1083 </TooltipTrigger>
1084 <TooltipPopup side="top">Edit from here</TooltipPopup>
1085 </Tooltip>
1086 );
1088​
1089const COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM = 1.75;
1090​
1091const COLLAPSED_USER_MESSAGE_FADE_MASK = `linear-gradient(to bottom, black calc(100% - ${COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM}rem), transparent)`;
1092​
1093const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(props: {
1094 text: string;
1095 renderContextReference: (reference: ChatMarkdownContextReference) => ReactNode;
1096 skills: ReadonlyArray<ServerProviderSkill>;
1097 markdownCwd: string | undefined;
1098 collapsible?: boolean;
1099}) {
1100 const [expanded, setExpanded] = useState(false);
1101 const revealForFind = () => setExpanded(true);
1102 const revealRef = findRevealRef(revealForFind);
1103 const hasVisibleBody = props.text.trim().length > 0;
1104 const canCollapse =
1105 props.collapsible !== false && hasVisibleBody && shouldCollapseUserMessage(props.text);
1106 const isCollapsed = canCollapse && !expanded;
1107 const showCollapseControl = canCollapse;
1108​
1109 return (
1110 <div>
1111 {hasVisibleBody ? (
1112 <div
1113 ref={revealRef}
1114 className={cn("relative", isCollapsed && "max-h-44 overflow-hidden")}
1115 data-user-message-body="true"
1116 data-thread-find-text="true"
1117 data-thread-find-fold={isCollapsed ? "" : undefined}
1118 data-user-message-collapsed={isCollapsed ? "true" : "false"}
1119 data-user-message-collapsible={canCollapse ? "true" : "false"}
1120 data-user-message-fade={isCollapsed ? "true" : "false"}
1121 style={
1122 isCollapsed
1123 ? {
1124 WebkitMaskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
1125 maskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
1127 : undefined
1130 <UserMessageBody
1131 text={props.text}
1132 renderContextReference={props.renderContextReference}
1133 skills={props.skills}
1134 markdownCwd={props.markdownCwd}
1135 />
1136 </div>
1137 ) : null}
1138 {showCollapseControl ? (
1139 <div className="mt-1.5 flex items-center justify-end gap-2" data-user-message-footer="true">
1140 {showCollapseControl ? (
1141 <Button
1142 type="button"
1143 size="xs"
1144 variant="ghost-muted"
1145 aria-expanded={expanded}
1146 data-scroll-anchor-ignore
1147 onClick={() => setExpanded((value) => !value)}
1148 className="-ml-1"
1150 {expanded ? "Show less" : "Show full message"}
1151 </Button>
1152 ) : null}
1153 </div>
1154 ) : null}
1155 </div>
1156 );
1157});
1158​
1159const UserMessageBody = memo(function UserMessageBody(props: {
1160 text: string;
1161 renderContextReference?: (reference: ChatMarkdownContextReference) => ReactNode;
1162 skills: ReadonlyArray<ServerProviderSkill>;
1163 markdownCwd: string | undefined;
1164}) {
1165 const ctx = use(TimelineRowCtx);
1166 if (props.text.length === 0) {
1167 return null;
1169 return (
1170 <ChatMarkdown
1171 text={props.text}
1172 cwd={props.markdownCwd}
1173 threadRef={ctx.threadRef ?? undefined}
1174 skills={props.skills}
1175 className="text-foreground"
1176 lineBreaks
1177 parseRawHtml={false}
1178 renderContextReference={props.renderContextReference}
1179 headingLevelOffset={MESSAGE_HEADING_LEVEL}
1180 />
1181 );
1182});