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