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

TimelineUserMessageRow.tsx

856 lines32.8 KB

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 );
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 );
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 );
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;
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 );
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 );
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 <AttachmentImage
528 name={image.name}
529 mimeType={image.mimeType}
530 src={image.previewUrl}
531 alt={image.name}
532 decoding="async"
533 loading="lazy"
534 className="block size-full object-cover"
535 />
536 </button>
537 ) : (
538 <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-2xs text-muted-foreground/70">
539 {image.name}
540 </div>
541 )}
542 {image.previewUrl && image.source?.kind === "snap-shot" ? (
543 <SnapShotAttachmentDetails source={image.source} />
544 ) : null}
545 </div>
546 ))}
547 {userVideos.map((file) => (
548 <UserVideoAttachment key={file.id} file={file} />
549 ))}
550 </div>
551 )}
552 {userAudio.length > 0 ? (
553 <div className="mb-2 flex max-w-full flex-col gap-1">
554 {userAudio.map((file) => (
555 <InlineAudioPreview
556 key={file.id}
557 name={file.name}
558 environmentId={ctx.activeThreadEnvironmentId}
559 resource={{
560 _tag: "attachment",
561 attachmentId: file.id,
562 fileName: file.name,
563 mimeType: file.mimeType,
564 disposition: "inline",
565 }}
566 onOpen={() => ctx.onFileOpen(file)}
567 />
568 ))}
569 </div>
570 ) : null}
571 {unchippedFiles.length > 0 || unknownAttachments.length > 0 ? (
572 <div className="mb-2 flex flex-col gap-1">
573 {unchippedFiles.map((file) => {
574 const fileIdentity = (
575 <>
576 <PierreEntryIcon
577 pathValue={file.name}
578 kind="file"
579 theme={ctx.resolvedTheme}
580 />
581 <span className="min-w-0 flex-1 truncate">{file.name}</span>
582 </>
583 );
584 if (file.downloadable !== false) {
585 return (
586 <div key={file.id} className="flex min-w-0 items-center gap-1">
587 <button
588 type="button"
589 aria-label={`Preview ${file.name}`}
590 onClick={() => ctx.onFileOpen(file)}
591 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"
592 >
593 {fileIdentity}
594 <EyeIcon className="size-4 shrink-0" />
595 </button>
596 <Tooltip>
597 <TooltipTrigger
598 render={
599 <Button
600 size="icon-xs"
601 variant="ghost-muted"
602 aria-label={`Download ${file.name}`}
603 onClick={() => ctx.onFileDownload(file)}
604 />
605 }
606 >
607 <DownloadIcon />
608 </TooltipTrigger>
609 <TooltipPopup side="top">Download {file.name}</TooltipPopup>
610 </Tooltip>
611 </div>
612 );
613 }
614​
615 return (
616 <div key={file.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
617 {fileIdentity}
618 </div>
619 );
620 })}
621 {unknownAttachments.map((attachment) => (
622 <div key={attachment.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
623 <PierreEntryIcon
624 pathValue={attachment.name}
625 kind="file"
626 theme={ctx.resolvedTheme}
627 />
628 <span className="min-w-0 flex-1 truncate">{attachment.name}</span>
629 </div>
630 ))}
631 </div>
632 ) : null}
633 <div onCopyCapture={onBodyCopyCapture}>
634 <CollapsibleUserMessageBody
635 text={resolvedContext.text}
636 renderContextReference={renderContextReference}
637 skills={ctx.skills}
638 markdownCwd={ctx.markdownCwd}
639 collapsible={!folded}
640 />
641 </div>
642 </div>
643 ) : null}
644 </div>
645 <UserMessageProjectedStatus row={row} />
646 {!folded || expanded ? (
647 <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">
648 <div className="flex shrink-0 items-center gap-2">
649 {folded && senderThreadId ? (
650 <InlineButton onClick={() => ctx.onOpenThread(senderThreadId)} tone="muted">
651 Open thread
652 </InlineButton>
653 ) : null}
654 <Tooltip>
655 <TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
656 {formatDayAwareTimestamp(row.message.createdAt, ctx.timestampFormat)}
657 </TooltipTrigger>
658 <TooltipPopup>
659 {formatChatTimestampTooltip(row.message.createdAt, ctx.timestampFormat)}
660 </TooltipPopup>
661 </Tooltip>
662 <div className="flex items-center gap-0.5">
663 {typeof revertTurnCount === "number" && (
664 <RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />
665 )}
666 {resolvedContext.text && (
667 <MessageCopyButton
668 text={contextClipboardFragment ? resolvedContext.text : plainText}
669 {...(contextClipboardFragment
670 ? {
671 extraFlavors: {
672 [COMPOSER_CONTEXT_CLIPBOARD_MIME]: contextClipboardFragment,
673 },
674 }
675 : {})}
676 variant="ghost"
677 />
678 )}
679 {promptLink !== null && (
680 <MessageCopyButton
681 text={promptLink}
682 label="Copy prompt link"
683 icon={LinkIconNode}
684 variant="ghost"
685 />
686 )}
687 </div>
688 </div>
689 </div>
690 ) : null}
691 </div>
692 );
694​
695function UserMessageIntentMarker({
696 intent,
697}: {
698 readonly intent: "steer" | "promoted_queued_to_steer";
699}) {
700 return (
701 <Tooltip>
702 <TooltipTrigger
703 render={
704 <div
705 className="me-1 flex items-center justify-end gap-1 text-xs leading-none text-muted-foreground"
706 data-user-message-intent={intent}
707 />
708 }
709 >
710 <Redo2Icon aria-hidden="true" className="size-3" />
711 Steer
712 </TooltipTrigger>
713 <TooltipPopup side="top">
714 {intent === "promoted_queued_to_steer"
715 ? "Originally queued, then promoted to steer the active turn"
716 : "Steered the active turn"}
717 </TooltipPopup>
718 </Tooltip>
719 );
721​
722function RevertUserMessageButton({
723 turnCount,
724 messageId,
725}: {
726 turnCount: number;
727 messageId: MessageId;
728}) {
729 const ctx = use(TimelineRowCtx);
730 const activity = use(TimelineRowActivityCtx);
731​
732 return (
733 <Tooltip>
734 <TooltipTrigger
735 render={
736 <Button
737 type="button"
738 size="xs"
739 variant="ghost"
740 disabled={activity.isRevertingCheckpoint || activity.isWorking}
741 onClick={() => ctx.onRevertToTurnCount(turnCount, messageId)}
742 aria-label="Edit from here"
743 />
744 }
745 >
746 <Undo2Icon className="size-3" />
747 </TooltipTrigger>
748 <TooltipPopup side="top">Edit from here</TooltipPopup>
749 </Tooltip>
750 );
752​
753const COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM = 1.75;
754​
755const COLLAPSED_USER_MESSAGE_FADE_MASK = `linear-gradient(to bottom, black calc(100% - ${COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM}rem), transparent)`;
756​
757const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(props: {
758 text: string;
759 renderContextReference: (reference: ChatMarkdownContextReference) => ReactNode;
760 skills: ReadonlyArray<ServerProviderSkill>;
761 markdownCwd: string | undefined;
762 collapsible?: boolean;
763 footer?: ReactNode;
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 || props.footer ? (
804 <div
805 className={cn(
806 "mt-1.5 flex items-center gap-2",
807 showCollapseControl && props.footer ? "justify-between" : "justify-end",
808 )}
809 data-user-message-footer="true"
810 >
811 {showCollapseControl ? (
812 <Button
813 type="button"
814 size="xs"
815 variant="ghost-muted"
816 aria-expanded={expanded}
817 data-scroll-anchor-ignore
818 onClick={() => setExpanded((value) => !value)}
819 className="-ml-1"
820 >
821 {expanded ? "Show less" : "Show full message"}
822 </Button>
823 ) : null}
824 {props.footer ? (
825 <div className="ml-auto flex items-center gap-2">{props.footer}</div>
826 ) : null}
827 </div>
828 ) : null}
829 </div>
830 );
831});
832​
833const UserMessageBody = memo(function UserMessageBody(props: {
834 text: string;
835 renderContextReference?: (reference: ChatMarkdownContextReference) => ReactNode;
836 skills: ReadonlyArray<ServerProviderSkill>;
837 markdownCwd: string | undefined;
838}) {
839 const ctx = use(TimelineRowCtx);
840 if (props.text.length === 0) {
841 return null;
842 }
843 return (
844 <ChatMarkdown
845 text={props.text}
846 cwd={props.markdownCwd}
847 threadRef={ctx.threadRef ?? undefined}
848 skills={props.skills}
849 className="text-foreground"
850 lineBreaks
851 parseRawHtml={false}
852 renderContextReference={props.renderContextReference}
853 headingLevelOffset={MESSAGE_HEADING_LEVEL}
854 />
855 );
856});