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