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

TimelineUserMessageRow.tsx

805 lines31.1 KB

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