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