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

TimelineUserMessageRow.tsx

1,199 lines44.7 KB

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