Open History to see the last commit
1import { InlineAudioPreview } from "../files/InlineAudioPreview";
2import { filePreviewKind } from "@t3tools/shared/filePreview";
3import { findRevealRef } from "./markdownFindContext";
4import { type MessageId, type ServerProviderSkill, ThreadId } from "@t3tools/contracts";
5import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
6import { Link } from "@tanstack/react-router";
7import { useQuietThreadShell } from "../../state/entities";
8import { useEnvironmentQuery } from "../../state/query";
9import { serverEnvironment } from "../../state/server";
10import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
11import { memo, use, useState, type ReactNode } from "react";
12import {
13 createMessageAttachmentPreviewProjector,
14 selectMessageImageResources,
15} from "../../session-logic";
16import {
17 type ChatFileAttachment,
18 isFileAttachment,
19 isImageAttachment,
20 isVideoAttachment,
21} from "../../types";
22import ChatMarkdown from "../ChatMarkdown";
23import {
24 CalendarClockIcon,
25 ChevronDownIcon,
26 DownloadIcon,
27 EyeIcon,
28 type LucideIcon,
29 MessagesSquareIcon,
30 Redo2Icon,
31 Undo2Icon,
32} from "lucide-react";
33import { Link as LinkIconNode } from "lucide";
34import { Button, InlineButton } from "../ui/button";
35import { useAssetUrlRefresh, useAssetUrls, useAssetUrlState } from "../../assets/assetUrls";
36import { AttachmentImage } from "../media/AttachmentImage";
37import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
38import {
39 buildAttachmentVideoAsset,
40 buildAttachmentVideoPreview,
41 buildExpandedImagePreview,
42} from "./ExpandedImagePreview";
43import {
44 SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
45 SnapShotAttachmentDetails,
46} from "./SnapShotAttachmentDetails";
47import { GuestMessageName, guestBubbleClassName } from "./guestMessageStyle";
48import { MessageCopyButton } from "./MessageCopyButton";
49import { promptLinkFor } from "../promptLinks/copyPromptLink";
50import { PierreEntryIcon } from "./PierreEntryIcon";
51import { shouldCollapseUserMessage } from "./MessagesTimeline.logic";
52import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
53import {
54 asKnownContextRecord,
55 resolveUserMessageContext,
56 selectedMessageContextFragment,
57} from "~/lib/composerContextRecords";
58import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
59import {
60 COMPOSER_CONTEXT_CLIPBOARD_MIME,
61 encodeComposerContextClipboardHtml,
62 encodeComposerContextFragment,
63} from "@t3tools/shared/composerContextClipboard";
64import { chatMarkdownClipboardPayload } from "../../markdown-clipboard";
65import type { ChatMarkdownContextReference } from "../ChatMarkdown";
66import { cn } from "~/lib/utils";
67import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
68import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
69import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext";
70import {
71 MESSAGE_HEADING_LEVEL,
72 MessageAuthorHeading,
73 TimelineRowTimestamp,
74} from "./TimelineRowParts";
75import { UserMessageContextReferenceChip } from "./UserMessageContextChips";
76import { resolvePreviewAnnotationImage } from "./TimelineUserMessageRow.logic";
77
78function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
79 const ctx = use(TimelineRowCtx);
80 // Row updates rebuild attachment objects, so the asset follows only the
81 // fields it reads.
82 const { downloadable, id, mimeType, name } = file;
83 const environmentId = ctx.activeThreadEnvironmentId;
84 const asset =
85 downloadable === false
86 ? null
87 : buildAttachmentVideoAsset(environmentId, { id, mimeType, name });
88 const resource = asset?.resource ?? null;
89 const assetUrl = useAssetUrlState(ctx.activeThreadEnvironmentId, resource);
90 const refreshAssetUrl = useAssetUrlRefresh(ctx.activeThreadEnvironmentId, resource);
91 const src = assetUrl._tag === "Success" ? assetUrl.url : (file.previewUrl ?? null);
92
93 if (asset === null && src === null) {
94 return (
95 <div className="flex aspect-[4/3] w-full items-center justify-center rounded-lg border border-border/80 bg-black px-2 py-3 text-center text-2xs text-white/70">
96 {file.name}
97 </div>
98 );
99 }
100
101 return (
102 <MediaVideoPlayer
103 src={src}
104 sourceFailed={
105 file.previewUrl === undefined && resource !== null && assetUrl._tag === "Failure"
106 }
107 label={file.name}
108 preload="visible"
109 onOpen={() => {
110 const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
111 if (preview) ctx.onImageExpand(preview);
112 }}
113 className="block aspect-[4/3] w-full"
114 videoClassName="aspect-auto size-full rounded-lg border border-border/80"
115 stateClassName="aspect-auto min-h-full rounded-lg border border-border/80 bg-black text-white"
116 onRetry={asset ? refreshAssetUrl : undefined}
117 actionsSource={asset ? { kind: "video", name: file.name, src, asset } : undefined}
118 />
119 );
120}
121
122export function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
123 const ctx = use(TimelineRowCtx);
124 return ctx.workflowOpening?.messageId === row.message.id ? (
125 <WorkflowOpeningBlock
126 opening={ctx.workflowOpening}
127 environmentId={ctx.activeThreadEnvironmentId}
128 onOpenThread={(threadId) => ctx.onOpenThread(ThreadId.make(threadId))}
129 />
130 ) : resolveUserMessagePresentation(row.message).attribution === "automation" ? (
131 <AutomationMessageRow row={row} />
132 ) : (
133 <UserTimelineRow row={row} />
134 );
135}
136
137/** Automation prompts are long, repeated runbooks; a folded bubble keeps them out of the way. */
138function AutomationMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
139 const ctx = use(TimelineRowCtx);
140 const [expanded, setExpanded] = useState(false);
141 const revealRef = findRevealRef(() => setExpanded(true));
142 const { text, scheduledTaskId } = resolveUserMessagePresentation(row.message);
143 const tasksQuery = useEnvironmentQuery(
144 scheduledTaskId
145 ? serverEnvironment.scheduledTasksLive({
146 environmentId: ctx.activeThreadEnvironmentId,
147 input: {},
148 })
149 : null,
150 );
151 const taskTitle = tasksQuery.data?.tasks.find((task) => task.id === scheduledTaskId)?.title;
152 const summary = taskTitle ?? text.trim().split(/\r?\n/, 1)[0] ?? "";
153
154 const revertTurnCount = row.revertTurnCount;
155 const promptLink = promptLinkFor(text);
156 // Find reads the DOM, so a folded prompt stays mounted but hidden while find is open.
157 const bodyMounted = expanded || ctx.findActive;
158
159 return (
160 <div className="group flex flex-col items-end gap-1" data-user-message-attribution="automation">
161 {row.message.inputIntent === "steer" ||
162 row.message.inputIntent === "promoted_queued_to_steer" ? (
163 <UserMessageIntentMarker intent={row.message.inputIntent} />
164 ) : null}
165 <div
166 className={cn(
167 "min-w-0 max-w-[80%] rounded-2xl bg-message text-message-foreground",
168 expanded && "w-full",
169 )}
170 >
171 <FoldedMessageHeader
172 icon={CalendarClockIcon}
173 label="Automation"
174 summary={summary}
175 expanded={expanded}
176 onToggle={() => setExpanded((value) => !value)}
177 />
178 {bodyMounted ? (
179 // `beforematch` does not bubble, so the reveal listener sits on the hidden fold itself.
180 <div
181 ref={revealRef}
182 hidden={!expanded}
183 className={cn("px-3 pb-3", !ctx.findActive && "max-h-96 overflow-auto")}
184 data-thread-find-text="true"
185 >
186 <UserMessageBody text={text} skills={ctx.skills} markdownCwd={ctx.markdownCwd} />
187 </div>
188 ) : null}
189 </div>
190 <UserMessageProjectedStatus row={row} />
191 {expanded ? (
192 <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">
193 <div className="flex shrink-0 items-center gap-2">
194 {scheduledTaskId ? (
195 <Link
196 to="/settings/scheduled-tasks"
197 search={{ environmentId: ctx.activeThreadEnvironmentId, taskId: scheduledTaskId }}
198 className="rounded-sm text-xs text-muted-foreground hover:underline focus-visible:outline-2 focus-visible:outline-ring"
199 >
200 Open automation
201 </Link>
202 ) : null}
203 <TimelineRowTimestamp
204 createdAt={row.message.createdAt}
205 timestampFormat={ctx.timestampFormat}
206 alwaysVisible
207 />
208 <div className="flex items-center gap-0.5">
209 {typeof revertTurnCount === "number" && (
210 <RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />
211 )}
212 <MessageCopyButton text={text} variant="ghost" />
213 {promptLink !== null && (
214 <MessageCopyButton
215 text={promptLink}
216 label="Copy prompt link"
217 icon={LinkIconNode}
218 variant="ghost"
219 />
220 )}
221 </div>
222 </div>
223 </div>
224 ) : null}
225 </div>
226 );
227}
228
229function FoldedMessageHeader(props: {
230 icon: LucideIcon;
231 label: string;
232 summary: string;
233 expanded: boolean;
234 onToggle: () => void;
235}) {
236 const Icon = props.icon;
237 return (
238 <button
239 type="button"
240 aria-expanded={props.expanded}
241 data-scroll-anchor-ignore
242 onClick={props.onToggle}
243 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"
244 >
245 <Icon className="size-4 shrink-0 stroke-2 text-muted-foreground" />
246 <span className="max-w-1/2 shrink-0 truncate text-muted-foreground">{props.label}</span>
247 <span className="min-w-0 flex-1 truncate">{props.summary}</span>
248 <ChevronDownIcon
249 className={cn(
250 "size-3.5 shrink-0 text-muted-foreground transition-transform",
251 props.expanded && "rotate-180",
252 )}
253 />
254 </button>
255 );
256}
257
258function UserMessageProjectedStatus({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
259 const status = row.projectedItem?.item.status;
260 if (
261 status === undefined ||
262 status === "completed" ||
263 status === "pending" ||
264 status === "waiting"
265 )
266 return null;
267 return (
268 <div className="me-1 flex items-center gap-1.5">
269 <span className="rounded-full border border-destructive/25 bg-destructive/8 px-1.5 py-0.5 text-3xs font-medium text-destructive">
270 {status}
271 </span>
272 </div>
273 );
274}
275
276function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
277 const ctx = use(TimelineRowCtx);
278 const { onImageExpand, onFileOpen } = ctx;
279 const senderThreadId = row.message.senderThreadId;
280 const resources = selectMessageImageResources(row.message.attachments);
281 const previewUrls = useAssetUrls(ctx.activeThreadEnvironmentId, resources);
282 const [projectPreviews] = useState(createMessageAttachmentPreviewProjector);
283 const previewUrlsById = new Map(
284 resources.flatMap((resource, index) => {
285 const url = previewUrls[index];
286 return url ? [[resource.attachmentId, url] as const] : [];
287 }),
288 );
289 const messageWithPreviews = projectPreviews(row.message, (attachment) =>
290 previewUrlsById.get(attachment.id),
291 );
292 const userImages = (messageWithPreviews.attachments ?? []).filter(isImageAttachment);
293 const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
294 const userVideos = userFiles.filter(isVideoAttachment);
295 const userAudio = userFiles.filter(
296 (file) => file.downloadable !== false && filePreviewKind(file) === "audio",
297 );
298 const otherUserFiles = userFiles.filter(
299 (file) => !isVideoAttachment(file) && !userAudio.includes(file),
300 );
301 const unknownAttachments = (row.message.attachments ?? []).filter(
302 (attachment) => !isImageAttachment(attachment) && !isFileAttachment(attachment),
303 );
304 const userMessage = resolveUserMessagePresentation(row.message);
305 // Messages from other agents fold to one line so the user's own messages stay easy to find.
306 const folded = userMessage.attribution === "agent";
307 const [expanded, setExpanded] = useState(false);
308 const revealFoldRef = findRevealRef(() => setExpanded(true));
309 const senderShell = useQuietThreadShell(
310 folded && senderThreadId
311 ? { environmentId: ctx.activeThreadEnvironmentId, threadId: senderThreadId }
312 : null,
313 );
314 const resolvedContext = resolveUserMessageContext(
315 userMessage.attribution === "guest" ? { ...row.message, text: userMessage.text } : row.message,
316 );
317 const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
318 const revertTurnCount = row.revertTurnCount;
319 const chippedAttachmentIds = new Set(
320 collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => {
321 const record = asKnownContextRecord(resolvedContext.recordsById.get(occurrence.contextId));
322 return record?.kind === "file" || record?.kind === "image" ? [record.attachmentId] : [];
323 }),
324 );
325 const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
326 const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));
327 const annotationRecordIds = resolvedContext.records
328 .filter((record) => record.kind === "preview-annotation")
329 .map((record) => record.contextId);
330 const plainText = replaceComposerContextReferences(
331 resolvedContext.text,
332 (reference) => reference.label,
333 );
334 const promptLink = promptLinkFor(plainText);
335 const foldSummary =
336 plainText
337 .split(/\r?\n/)
338 .find((line) => line.trim().length > 0)
339 ?.trim() ?? "";
340 const contextClipboardFragment =
341 resolvedContext.records.length === 0
342 ? null
343 : encodeComposerContextFragment({
344 version: 1,
345 source: {
346 environmentId: ctx.activeThreadEnvironmentId,
347 ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
348 messageId: row.message.id,
349 },
350 records: resolvedContext.records,
351 });
352 const onBodyCopyCapture = (event: React.ClipboardEvent<HTMLDivElement>) => {
353 if (resolvedContext.records.length === 0 || !event.clipboardData) return;
354 const selection = window.getSelection();
355 if (!selection || selection.isCollapsed) return;
356 const copiedMarkdown: string[] = [];
357 for (let index = 0; index < selection.rangeCount; index += 1) {
358 const container = document.createElement("div");
359 container.appendChild(selection.getRangeAt(index).cloneContents());
360 // Diagram source is copied text, not authority to export context records.
361 for (const element of container.querySelectorAll(
362 "[data-markdown-copy]:not([data-markdown-mermaid])",
363 )) {
364 copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");
365 }
366 }
367 const fragment = selectedMessageContextFragment({
368 markdown: copiedMarkdown.join("\n"),
369 records: resolvedContext.records,
370 environmentId: ctx.activeThreadEnvironmentId,
371 ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
372 messageId: row.message.id,
373 });
374 if (!fragment) return;
375 // Claim the copy: without preventDefault the browser default overwrites the
376 // custom MIME type. The default content must then be written back explicitly.
377 const payload = chatMarkdownClipboardPayload(selection);
378 event.preventDefault();
379 event.clipboardData.setData("text/plain", payload?.text ?? selection.toString());
380 if (payload) {
381 event.clipboardData.setData(
382 "text/html",
383 encodeComposerContextClipboardHtml(payload.text, fragment, payload.html),
384 );
385 }
386 event.clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);
387 };
388 const renderContextReference = (reference: ChatMarkdownContextReference) => {
389 const record = asKnownContextRecord(resolvedContext.recordsById.get(reference.contextId));
390 if (record?.kind === "file" && userAudio.some((file) => file.id === record.attachmentId))
391 return null;
392 const annotationImage =
393 record?.kind === "preview-annotation"
394 ? resolvePreviewAnnotationImage({
395 record,
396 recordsById: resolvedContext.recordsById,
397 userImages,
398 previewImages,
399 annotationRecordIds,
400 })
401 : null;
402 const attachment =
403 record?.kind === "image"
404 ? (userImages.find((image) => image.id === record.attachmentId) ?? null)
405 : record?.kind === "file"
406 ? (userFiles.find((file) => file.id === record.attachmentId) ?? null)
407 : null;
408 return (
409 <span data-thread-find-ignore>
410 <UserMessageContextReferenceChip
411 reference={reference}
412 record={record}
413 annotationImage={annotationImage}
414 attachment={attachment}
415 onExpandImage={(image) => {
416 const preview = buildExpandedImagePreview(userImages, image.id);
417 if (preview) onImageExpand(preview);
418 }}
419 onOpenFile={onFileOpen}
420 onExpandVideo={(file) => {
421 const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
422 if (preview) onImageExpand(preview);
423 }}
424 />
425 </span>
426 );
427 };
428
429 return (
430 <div
431 className="group flex flex-col items-end gap-1"
432 data-user-message-attribution={folded ? "agent" : undefined}
433 >
434 {userMessage.attribution === "t3code" ? (
435 <p
436 className="me-1 text-2xs text-muted-foreground/70"
437 data-user-message-attribution="t3code"
438 >
439 Sent by T3 Code
440 </p>
441 ) : null}
442 {/* The row's heading already names the guest for screen readers. */}
443 {userMessage.guestName !== undefined ? (
444 <div aria-hidden>
445 <GuestMessageName name={userMessage.guestName} />
446 </div>
447 ) : null}
448 {row.message.inputIntent === "steer" ||
449 row.message.inputIntent === "promoted_queued_to_steer" ? (
450 <UserMessageIntentMarker intent={row.message.inputIntent} />
451 ) : null}
452 <div
453 className={cn(
454 "relative min-w-0 max-w-[80%] rounded-2xl text-message-foreground",
455 userMessage.attribution === "guest" ? guestBubbleClassName(false) : "bg-message",
456 !folded && "p-3",
457 folded && expanded && "w-full",
458 )}
459 >
460 {folded ? (
461 <FoldedMessageHeader
462 icon={MessagesSquareIcon}
463 label={senderShell?.title.trim() || "Agent"}
464 summary={foldSummary}
465 expanded={expanded}
466 onToggle={() => setExpanded((value) => !value)}
467 />
468 ) : null}
469 {/* Find reads the DOM, so a folded message stays mounted but hidden while find is open. */}
470 {!folded || expanded || ctx.findActive ? (
471 <div
472 ref={folded ? revealFoldRef : undefined}
473 hidden={folded && !expanded}
474 className={cn(
475 folded && "px-3 pb-3",
476 folded && !ctx.findActive && "max-h-96 overflow-auto",
477 )}
478 >
479 <MessageAuthorHeading>
480 {userMessage.guestName === undefined ? "You" : `${userMessage.guestName} (guest)`}
481 </MessageAuthorHeading>
482 {(regularImages.length > 0 || userVideos.length > 0) && (
483 <div className="mb-2 grid max-w-[210px] grid-cols-2 gap-2">
484 {regularImages.map((image) => (
485 <div
486 key={image.id}
487 className={cn(
488 "bg-background/70",
489 image.source?.kind === "snap-shot" && image.previewUrl
490 ? cn(SNAP_SHOT_ATTACHMENT_FRAME_CLASS, "col-span-2")
491 : "aspect-[4/3] overflow-hidden rounded-lg border border-border/80",
492 )}
493 >
494 {image.previewUrl ? (
495 <button
496 type="button"
497 className="block h-full w-full cursor-zoom-in"
498 aria-label={`Preview ${image.name}`}
499 onClick={() => {
500 const preview = buildExpandedImagePreview(regularImages, image.id);
501 if (!preview) return;
502 ctx.onImageExpand(preview);
503 }}
504 >
505 <AttachmentImage
506 name={image.name}
507 mimeType={image.mimeType}
508 src={image.previewUrl}
509 alt={image.name}
510 decoding="async"
511 loading="lazy"
512 className="block size-full object-cover"
513 />
514 </button>
515 ) : (
516 <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-2xs text-muted-foreground/70">
517 {image.name}
518 </div>
519 )}
520 {image.previewUrl && image.source?.kind === "snap-shot" ? (
521 <SnapShotAttachmentDetails source={image.source} />
522 ) : null}
523 </div>
524 ))}
525 {userVideos.map((file) => (
526 <UserVideoAttachment key={file.id} file={file} />
527 ))}
528 </div>
529 )}
530 {userAudio.length > 0 ? (
531 <div className="mb-2 flex max-w-full flex-col gap-1">
532 {userAudio.map((file) => (
533 <InlineAudioPreview
534 key={file.id}
535 name={file.name}
536 environmentId={ctx.activeThreadEnvironmentId}
537 resource={{
538 _tag: "attachment",
539 attachmentId: file.id,
540 fileName: file.name,
541 mimeType: file.mimeType,
542 disposition: "inline",
543 }}
544 onOpen={() => ctx.onFileOpen(file)}
545 />
546 ))}
547 </div>
548 ) : null}
549 {unchippedFiles.length > 0 || unknownAttachments.length > 0 ? (
550 <div className="mb-2 flex flex-col gap-1">
551 {unchippedFiles.map((file) => {
552 const fileIdentity = (
553 <>
554 <PierreEntryIcon
555 pathValue={file.name}
556 kind="file"
557 theme={ctx.resolvedTheme}
558 />
559 <span className="min-w-0 flex-1 truncate">{file.name}</span>
560 </>
561 );
562 if (file.downloadable !== false) {
563 return (
564 <div key={file.id} className="flex min-w-0 items-center gap-1">
565 <button
566 type="button"
567 aria-label={`Preview ${file.name}`}
568 onClick={() => ctx.onFileOpen(file)}
569 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"
570 >
571 {fileIdentity}
572 <EyeIcon className="size-4 shrink-0" />
573 </button>
574 <Tooltip>
575 <TooltipTrigger
576 render={
577 <Button
578 size="icon-xs"
579 variant="ghost-muted"
580 aria-label={`Download ${file.name}`}
581 onClick={() => ctx.onFileDownload(file)}
582 />
583 }
584 >
585 <DownloadIcon />
586 </TooltipTrigger>
587 <TooltipPopup side="top">Download {file.name}</TooltipPopup>
588 </Tooltip>
589 </div>
590 );
591 }
592
593 return (
594 <div key={file.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
595 {fileIdentity}
596 </div>
597 );
598 })}
599 {unknownAttachments.map((attachment) => (
600 <div key={attachment.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
601 <PierreEntryIcon
602 pathValue={attachment.name}
603 kind="file"
604 theme={ctx.resolvedTheme}
605 />
606 <span className="min-w-0 flex-1 truncate">{attachment.name}</span>
607 </div>
608 ))}
609 </div>
610 ) : null}
611 <div onCopyCapture={onBodyCopyCapture}>
612 <CollapsibleUserMessageBody
613 text={resolvedContext.text}
614 renderContextReference={renderContextReference}
615 skills={ctx.skills}
616 markdownCwd={ctx.markdownCwd}
617 collapsible={!folded}
618 />
619 </div>
620 </div>
621 ) : null}
622 </div>
623 <UserMessageProjectedStatus row={row} />
624 {!folded || expanded ? (
625 <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">
626 <div className="flex shrink-0 items-center gap-2">
627 {folded && senderThreadId ? (
628 <InlineButton onClick={() => ctx.onOpenThread(senderThreadId)} tone="muted">
629 Open thread
630 </InlineButton>
631 ) : null}
632 <Tooltip>
633 <TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
634 {formatDayAwareTimestamp(row.message.createdAt, ctx.timestampFormat)}
635 </TooltipTrigger>
636 <TooltipPopup>
637 {formatChatTimestampTooltip(row.message.createdAt, ctx.timestampFormat)}
638 </TooltipPopup>
639 </Tooltip>
640 <div className="flex items-center gap-0.5">
641 {typeof revertTurnCount === "number" && (
642 <RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />
643 )}
644 {resolvedContext.text && (
645 <MessageCopyButton
646 text={contextClipboardFragment ? resolvedContext.text : plainText}
647 {...(contextClipboardFragment
648 ? {
649 extraFlavors: {
650 [COMPOSER_CONTEXT_CLIPBOARD_MIME]: contextClipboardFragment,
651 },
652 }
653 : {})}
654 variant="ghost"
655 />
656 )}
657 {promptLink !== null && (
658 <MessageCopyButton
659 text={promptLink}
660 label="Copy prompt link"
661 icon={LinkIconNode}
662 variant="ghost"
663 />
664 )}
665 </div>
666 </div>
667 </div>
668 ) : null}
669 </div>
670 );
671}
672
673function UserMessageIntentMarker({
674 intent,
675}: {
676 readonly intent: "steer" | "promoted_queued_to_steer";
677}) {
678 return (
679 <Tooltip>
680 <TooltipTrigger
681 render={
682 <div
683 className="me-1 flex items-center justify-end gap-1 text-xs leading-none text-muted-foreground"
684 data-user-message-intent={intent}
685 />
686 }
687 >
688 <Redo2Icon aria-hidden="true" className="size-3" />
689 Steer
690 </TooltipTrigger>
691 <TooltipPopup side="top">
692 {intent === "promoted_queued_to_steer"
693 ? "Originally queued, then promoted to steer the active turn"
694 : "Steered the active turn"}
695 </TooltipPopup>
696 </Tooltip>
697 );
698}
699
700function RevertUserMessageButton({
701 turnCount,
702 messageId,
703}: {
704 turnCount: number;
705 messageId: MessageId;
706}) {
707 const ctx = use(TimelineRowCtx);
708 const activity = use(TimelineRowActivityCtx);
709
710 return (
711 <Tooltip>
712 <TooltipTrigger
713 render={
714 <Button
715 type="button"
716 size="xs"
717 variant="ghost"
718 disabled={activity.isRevertingCheckpoint || activity.isWorking}
719 onClick={() => ctx.onRevertToTurnCount(turnCount, messageId)}
720 aria-label="Edit from here"
721 />
722 }
723 >
724 <Undo2Icon className="size-3" />
725 </TooltipTrigger>
726 <TooltipPopup side="top">Edit from here</TooltipPopup>
727 </Tooltip>
728 );
729}
730
731const COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM = 1.75;
732
733const COLLAPSED_USER_MESSAGE_FADE_MASK = `linear-gradient(to bottom, black calc(100% - ${COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM}rem), transparent)`;
734
735const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(props: {
736 text: string;
737 renderContextReference: (reference: ChatMarkdownContextReference) => ReactNode;
738 skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
739 markdownCwd: string | undefined;
740 collapsible?: boolean;
741 footer?: ReactNode;
742}) {
743 const [expanded, setExpanded] = useState(false);
744 const revealForFind = () => setExpanded(true);
745 const revealRef = findRevealRef(revealForFind);
746 const hasVisibleBody = props.text.trim().length > 0;
747 const canCollapse =
748 props.collapsible !== false && hasVisibleBody && shouldCollapseUserMessage(props.text);
749 const isCollapsed = canCollapse && !expanded;
750 const showCollapseControl = canCollapse;
751
752 return (
753 <div>
754 {hasVisibleBody ? (
755 <div
756 ref={revealRef}
757 className={cn("relative", isCollapsed && "max-h-44 overflow-hidden")}
758 data-user-message-body="true"
759 data-thread-find-text="true"
760 data-thread-find-fold={isCollapsed ? "" : undefined}
761 data-user-message-collapsed={isCollapsed ? "true" : "false"}
762 data-user-message-collapsible={canCollapse ? "true" : "false"}
763 data-user-message-fade={isCollapsed ? "true" : "false"}
764 style={
765 isCollapsed
766 ? {
767 WebkitMaskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
768 maskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
769 }
770 : undefined
771 }
772 >
773 <UserMessageBody
774 text={props.text}
775 renderContextReference={props.renderContextReference}
776 skills={props.skills}
777 markdownCwd={props.markdownCwd}
778 />
779 </div>
780 ) : null}
781 {showCollapseControl || props.footer ? (
782 <div
783 className={cn(
784 "mt-1.5 flex items-center gap-2",
785 showCollapseControl && props.footer ? "justify-between" : "justify-end",
786 )}
787 data-user-message-footer="true"
788 >
789 {showCollapseControl ? (
790 <Button
791 type="button"
792 size="xs"
793 variant="ghost-muted"
794 aria-expanded={expanded}
795 data-scroll-anchor-ignore
796 onClick={() => setExpanded((value) => !value)}
797 className="-ml-1"
798 >
799 {expanded ? "Show less" : "Show full message"}
800 </Button>
801 ) : null}
802 {props.footer ? (
803 <div className="ml-auto flex items-center gap-2">{props.footer}</div>
804 ) : null}
805 </div>
806 ) : null}
807 </div>
808 );
809});
810
811const UserMessageBody = memo(function UserMessageBody(props: {
812 text: string;
813 renderContextReference?: (reference: ChatMarkdownContextReference) => ReactNode;
814 skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
815 markdownCwd: string | undefined;
816}) {
817 const ctx = use(TimelineRowCtx);
818 if (props.text.length === 0) {
819 return null;
820 }
821 return (
822 <ChatMarkdown
823 text={props.text}
824 cwd={props.markdownCwd}
825 threadRef={ctx.threadRef ?? undefined}
826 skills={props.skills}
827 className="text-foreground"
828 lineBreaks
829 parseRawHtml={false}
830 renderContextReference={props.renderContextReference}
831 headingLevelOffset={MESSAGE_HEADING_LEVEL}
832 />
833 );
834});