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

TimelineUserMessageRow.tsx

1,214 lines45.4 KB

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