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