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

TimelineUserMessageRow.tsx

1,237 lines46.2 KB

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