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

TimelineUserMessageRow.tsx

1,364 lines50.9 KB

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