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