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