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

TimelineUserMessageRow.tsx

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