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

TimelineUserMessageRow.tsx

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