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

TimelineUserMessageRow.tsx

619 lines24.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 { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
6import { memo, use, useState, type ReactNode } from "react";
7import {
8 createMessageAttachmentPreviewProjector,
9 selectMessageImageResources,
10} from "../../session-logic";
11import {
12 type ChatFileAttachment,
13 isFileAttachment,
14 isImageAttachment,
15 isVideoAttachment,
16} from "../../types";
17import ChatMarkdown from "../ChatMarkdown";
18import { DownloadIcon, EyeIcon, Redo2Icon, Undo2Icon } from "lucide-react";
19import { Link as LinkIconNode } from "lucide";
20import { Button, InlineButton } from "../ui/button";
21import { useAssetUrlRefresh, useAssetUrls, useAssetUrlState } from "../../assets/assetUrls";
22import { AttachmentImage } from "../media/AttachmentImage";
23import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
24import {
25 buildAttachmentVideoAsset,
26 buildAttachmentVideoPreview,
27 buildExpandedImagePreview,
28} from "./ExpandedImagePreview";
29import {
30 SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
31 SnapShotAttachmentDetails,
32} from "./SnapShotAttachmentDetails";
33import { MessageCopyButton } from "./MessageCopyButton";
34import { promptLinkFor } from "../promptLinks/copyPromptLink";
35import { PierreEntryIcon } from "./PierreEntryIcon";
36import { shouldCollapseUserMessage } from "./MessagesTimeline.logic";
37import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
38import {
39 asKnownContextRecord,
40 resolveUserMessageContext,
41 selectedMessageContextFragment,
42} from "~/lib/composerContextRecords";
43import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
44import {
45 COMPOSER_CONTEXT_CLIPBOARD_MIME,
46 encodeComposerContextClipboardHtml,
47 encodeComposerContextFragment,
48} from "@t3tools/shared/composerContextClipboard";
49import { chatMarkdownClipboardPayload } from "../../markdown-clipboard";
50import type { ChatMarkdownContextReference } from "../ChatMarkdown";
51import { cn } from "~/lib/utils";
52import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
53import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
54import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext";
55import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts";
56import { UserMessageContextReferenceChip } from "./UserMessageContextChips";
57import { resolvePreviewAnnotationImage } from "./TimelineUserMessageRow.logic";
58​
59function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
60 const ctx = use(TimelineRowCtx);
61 // Row updates rebuild attachment objects, so the asset follows only the
62 // fields it reads.
63 const { downloadable, id, mimeType, name } = file;
64 const environmentId = ctx.activeThreadEnvironmentId;
65 const asset =
66 downloadable === false
67 ? null
68 : buildAttachmentVideoAsset(environmentId, { id, mimeType, name });
69 const resource = asset?.resource ?? null;
70 const assetUrl = useAssetUrlState(ctx.activeThreadEnvironmentId, resource);
71 const refreshAssetUrl = useAssetUrlRefresh(ctx.activeThreadEnvironmentId, resource);
72 const src = assetUrl._tag === "Success" ? assetUrl.url : (file.previewUrl ?? null);
73​
74 if (asset === null && src === null) {
75 return (
76 <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">
77 {file.name}
78 </div>
79 );
80 }
81​
82 return (
83 <MediaVideoPlayer
84 src={src}
85 sourceFailed={
86 file.previewUrl === undefined && resource !== null && assetUrl._tag === "Failure"
87 }
88 label={file.name}
89 preload="visible"
90 onOpen={() => {
91 const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
92 if (preview) ctx.onImageExpand(preview);
93 }}
94 className="block aspect-[4/3] w-full"
95 videoClassName="aspect-auto size-full rounded-lg border border-border/80"
96 stateClassName="aspect-auto min-h-full rounded-lg border border-border/80 bg-black text-white"
97 onRetry={asset ? refreshAssetUrl : undefined}
98 actionsSource={asset ? { kind: "video", name: file.name, src, asset } : undefined}
99 />
100 );
102​
103export function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
104 const ctx = use(TimelineRowCtx);
105 return ctx.workflowOpening?.messageId === row.message.id ? (
106 <WorkflowOpeningBlock
107 opening={ctx.workflowOpening}
108 environmentId={ctx.activeThreadEnvironmentId}
109 onOpenThread={(threadId) => ctx.onOpenThread(ThreadId.make(threadId))}
110 />
111 ) : (
112 <UserTimelineRow row={row} />
113 );
115​
116function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
117 const ctx = use(TimelineRowCtx);
118 const { onImageExpand, onFileOpen } = ctx;
119 const senderThreadId = row.message.senderThreadId;
120 const resources = selectMessageImageResources(row.message.attachments);
121 const previewUrls = useAssetUrls(ctx.activeThreadEnvironmentId, resources);
122 const [projectPreviews] = useState(createMessageAttachmentPreviewProjector);
123 const previewUrlsById = new Map(
124 resources.flatMap((resource, index) => {
125 const url = previewUrls[index];
126 return url ? [[resource.attachmentId, url] as const] : [];
127 }),
128 );
129 const messageWithPreviews = projectPreviews(row.message, (attachment) =>
130 previewUrlsById.get(attachment.id),
131 );
132 const userImages = (messageWithPreviews.attachments ?? []).filter(isImageAttachment);
133 const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
134 const userVideos = userFiles.filter(isVideoAttachment);
135 const otherUserFiles = userFiles.filter((file) => !isVideoAttachment(file));
136 const unknownAttachments = (row.message.attachments ?? []).filter(
137 (attachment) => !isImageAttachment(attachment) && !isFileAttachment(attachment),
138 );
139 const userMessage = resolveUserMessagePresentation(row.message);
140 const resolvedContext = resolveUserMessageContext(row.message);
141 const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
142 const revertTurnCount = row.revertTurnCount;
143 const chippedAttachmentIds = new Set(
144 collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => {
145 const record = asKnownContextRecord(resolvedContext.recordsById.get(occurrence.contextId));
146 return record?.kind === "file" || record?.kind === "image" ? [record.attachmentId] : [];
147 }),
148 );
149 const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
150 const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));
151 const annotationRecordIds = resolvedContext.records
152 .filter((record) => record.kind === "preview-annotation")
153 .map((record) => record.contextId);
154 const plainText = replaceComposerContextReferences(
155 resolvedContext.text,
156 (reference) => reference.label,
157 );
158 const promptLink = promptLinkFor(plainText);
159 const contextClipboardFragment =
160 resolvedContext.records.length === 0
161 ? null
162 : encodeComposerContextFragment({
163 version: 1,
164 source: {
165 environmentId: ctx.activeThreadEnvironmentId,
166 ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
167 messageId: row.message.id,
168 },
169 records: resolvedContext.records,
170 });
171 const onBodyCopyCapture = (event: React.ClipboardEvent<HTMLDivElement>) => {
172 if (resolvedContext.records.length === 0 || !event.clipboardData) return;
173 const selection = window.getSelection();
174 if (!selection || selection.isCollapsed) return;
175 const copiedMarkdown: string[] = [];
176 for (let index = 0; index < selection.rangeCount; index += 1) {
177 const container = document.createElement("div");
178 container.appendChild(selection.getRangeAt(index).cloneContents());
179 // Diagram source is copied text, not authority to export context records.
180 for (const element of container.querySelectorAll(
181 "[data-markdown-copy]:not([data-markdown-mermaid])",
182 )) {
183 copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");
184 }
185 }
186 const fragment = selectedMessageContextFragment({
187 markdown: copiedMarkdown.join("\n"),
188 records: resolvedContext.records,
189 environmentId: ctx.activeThreadEnvironmentId,
190 ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
191 messageId: row.message.id,
192 });
193 if (!fragment) return;
194 // Claim the copy: without preventDefault the browser default overwrites the
195 // custom MIME type. The default content must then be written back explicitly.
196 const payload = chatMarkdownClipboardPayload(selection);
197 event.preventDefault();
198 event.clipboardData.setData("text/plain", payload?.text ?? selection.toString());
199 if (payload) {
200 event.clipboardData.setData(
201 "text/html",
202 encodeComposerContextClipboardHtml(payload.text, fragment, payload.html),
203 );
204 }
205 event.clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);
206 };
207 const renderContextReference = (reference: ChatMarkdownContextReference) => {
208 const record = asKnownContextRecord(resolvedContext.recordsById.get(reference.contextId));
209 const annotationImage =
210 record?.kind === "preview-annotation"
211 ? resolvePreviewAnnotationImage({
212 record,
213 recordsById: resolvedContext.recordsById,
214 userImages,
215 previewImages,
216 annotationRecordIds,
217 })
218 : null;
219 const attachment =
220 record?.kind === "image"
221 ? (userImages.find((image) => image.id === record.attachmentId) ?? null)
222 : record?.kind === "file"
223 ? (userFiles.find((file) => file.id === record.attachmentId) ?? null)
224 : null;
225 return (
226 <span data-thread-find-ignore>
227 <UserMessageContextReferenceChip
228 reference={reference}
229 record={record}
230 annotationImage={annotationImage}
231 attachment={attachment}
232 onExpandImage={(image) => {
233 const preview = buildExpandedImagePreview(userImages, image.id);
234 if (preview) onImageExpand(preview);
235 }}
236 onOpenFile={onFileOpen}
237 onExpandVideo={(file) => {
238 const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
239 if (preview) onImageExpand(preview);
240 }}
241 />
242 </span>
243 );
244 };
245​
246 return (
247 <div className="group flex flex-col items-end gap-1">
248 {userMessage.attribution === "automation" ? (
249 <p
250 className="me-1 text-2xs text-muted-foreground/70"
251 data-user-message-attribution="automation"
252 >
253 {userMessage.scheduledTaskId ? (
254 <Link
255 to="/settings/scheduled-tasks"
256 search={{
257 environmentId: ctx.activeThreadEnvironmentId,
258 taskId: userMessage.scheduledTaskId,
259 }}
260 className="rounded-sm hover:text-muted-foreground hover:underline focus-visible:outline-2 focus-visible:outline-ring"
261 >
262 Sent by automation
263 </Link>
264 ) : (
265 "Sent by automation"
266 )}
267 </p>
268 ) : userMessage.attribution === "t3code" ? (
269 <p
270 className="me-1 text-2xs text-muted-foreground/70"
271 data-user-message-attribution="t3code"
272 >
273 Sent by T3 Code
274 </p>
275 ) : userMessage.attribution === "agent" ? (
276 <p className="me-1 text-2xs text-muted-foreground/70" data-user-message-attribution="agent">
277 {senderThreadId ? (
278 <InlineButton
279 onClick={() => ctx.onOpenThread(senderThreadId)}
280 tone="muted"
281 aria-label="Open sending thread"
282 >
283 Sent by another agent
284 </InlineButton>
285 ) : (
286 "Sent by another agent"
287 )}
288 </p>
289 ) : null}
290 {row.message.inputIntent === "steer" ||
291 row.message.inputIntent === "promoted_queued_to_steer" ? (
292 <UserMessageIntentMarker intent={row.message.inputIntent} />
293 ) : null}
294 <div className="relative max-w-[80%] rounded-2xl bg-message p-3 text-message-foreground">
295 <MessageAuthorHeading>You</MessageAuthorHeading>
296 {(regularImages.length > 0 || userVideos.length > 0) && (
297 <div className="mb-2 grid max-w-[210px] grid-cols-2 gap-2">
298 {regularImages.map((image) => (
299 <div
300 key={image.id}
301 className={cn(
302 "bg-background/70",
303 image.source?.kind === "snap-shot" && image.previewUrl
304 ? cn(SNAP_SHOT_ATTACHMENT_FRAME_CLASS, "col-span-2")
305 : "aspect-[4/3] overflow-hidden rounded-lg border border-border/80",
306 )}
307 >
308 {image.previewUrl ? (
309 <button
310 type="button"
311 className="block h-full w-full cursor-zoom-in"
312 aria-label={`Preview ${image.name}`}
313 onClick={() => {
314 const preview = buildExpandedImagePreview(regularImages, image.id);
315 if (!preview) return;
316 ctx.onImageExpand(preview);
317 }}
318 >
319 <AttachmentImage
320 name={image.name}
321 mimeType={image.mimeType}
322 src={image.previewUrl}
323 alt={image.name}
324 decoding="async"
325 className="block size-full object-cover"
326 />
327 </button>
328 ) : (
329 <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-2xs text-muted-foreground/70">
330 {image.name}
331 </div>
332 )}
333 {image.previewUrl && image.source?.kind === "snap-shot" ? (
334 <SnapShotAttachmentDetails source={image.source} />
335 ) : null}
336 </div>
337 ))}
338 {userVideos.map((file) => (
339 <UserVideoAttachment key={file.id} file={file} />
340 ))}
341 </div>
342 )}
343 {unchippedFiles.length > 0 || unknownAttachments.length > 0 ? (
344 <div className="mb-2 flex flex-col gap-1">
345 {unchippedFiles.map((file) => {
346 const fileIdentity = (
347 <>
348 <PierreEntryIcon pathValue={file.name} kind="file" theme={ctx.resolvedTheme} />
349 <span className="min-w-0 flex-1 truncate">{file.name}</span>
350 </>
351 );
352 if (file.downloadable !== false) {
353 return (
354 <div key={file.id} className="flex min-w-0 items-center gap-1">
355 <button
356 type="button"
357 aria-label={`Preview ${file.name}`}
358 onClick={() => ctx.onFileOpen(file)}
359 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"
360 >
361 {fileIdentity}
362 <EyeIcon className="size-4 shrink-0" />
363 </button>
364 <Tooltip>
365 <TooltipTrigger
366 render={
367 <Button
368 size="icon-xs"
369 variant="ghost-muted"
370 aria-label={`Download ${file.name}`}
371 onClick={() => ctx.onFileDownload(file)}
372 />
373 }
374 >
375 <DownloadIcon />
376 </TooltipTrigger>
377 <TooltipPopup side="top">Download {file.name}</TooltipPopup>
378 </Tooltip>
379 </div>
380 );
381 }
382​
383 return (
384 <div key={file.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
385 {fileIdentity}
386 </div>
387 );
388 })}
389 {unknownAttachments.map((attachment) => (
390 <div key={attachment.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
391 <PierreEntryIcon
392 pathValue={attachment.name}
393 kind="file"
394 theme={ctx.resolvedTheme}
395 />
396 <span className="min-w-0 flex-1 truncate">{attachment.name}</span>
397 </div>
398 ))}
399 </div>
400 ) : null}
401 <div onCopyCapture={onBodyCopyCapture}>
402 <CollapsibleUserMessageBody
403 text={resolvedContext.text}
404 renderContextReference={renderContextReference}
405 skills={ctx.skills}
406 markdownCwd={ctx.markdownCwd}
407 />
408 </div>
409 </div>
410 {row.projectedItem &&
411 row.projectedItem.item.status !== "completed" &&
412 row.projectedItem.item.status !== "pending" &&
413 row.projectedItem.item.status !== "waiting" ? (
414 <div className="me-1 flex items-center gap-1.5">
415 <span className="rounded-full border border-destructive/25 bg-destructive/8 px-1.5 py-0.5 text-3xs font-medium text-destructive">
416 {row.projectedItem.item.status}
417 </span>
418 </div>
419 ) : null}
420 <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">
421 <div className="flex shrink-0 items-center gap-2">
422 <Tooltip>
423 <TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
424 {formatDayAwareTimestamp(row.message.createdAt, ctx.timestampFormat)}
425 </TooltipTrigger>
426 <TooltipPopup>
427 {formatChatTimestampTooltip(row.message.createdAt, ctx.timestampFormat)}
428 </TooltipPopup>
429 </Tooltip>
430 <div className="flex items-center gap-0.5">
431 {typeof revertTurnCount === "number" && (
432 <RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />
433 )}
434 {resolvedContext.text && (
435 <MessageCopyButton
436 text={contextClipboardFragment ? resolvedContext.text : plainText}
437 {...(contextClipboardFragment
438 ? {
439 extraFlavors: { [COMPOSER_CONTEXT_CLIPBOARD_MIME]: contextClipboardFragment },
440 }
441 : {})}
442 variant="ghost"
443 />
444 )}
445 {promptLink !== null && (
446 <MessageCopyButton
447 text={promptLink}
448 label="Copy prompt link"
449 icon={LinkIconNode}
450 variant="ghost"
451 />
452 )}
453 </div>
454 </div>
455 </div>
456 </div>
457 );
459​
460function UserMessageIntentMarker({
461 intent,
462}: {
463 readonly intent: "steer" | "promoted_queued_to_steer";
464}) {
465 return (
466 <Tooltip>
467 <TooltipTrigger
468 render={
469 <div
470 className="me-1 flex items-center justify-end gap-1 text-xs leading-none text-muted-foreground"
471 data-user-message-intent={intent}
472 />
473 }
474 >
475 <Redo2Icon aria-hidden="true" className="size-3" />
476 Steer
477 </TooltipTrigger>
478 <TooltipPopup side="top">
479 {intent === "promoted_queued_to_steer"
480 ? "Originally queued, then promoted to steer the active turn"
481 : "Steered the active turn"}
482 </TooltipPopup>
483 </Tooltip>
484 );
486​
487function RevertUserMessageButton({
488 turnCount,
489 messageId,
490}: {
491 turnCount: number;
492 messageId: MessageId;
493}) {
494 const ctx = use(TimelineRowCtx);
495 const activity = use(TimelineRowActivityCtx);
496​
497 return (
498 <Tooltip>
499 <TooltipTrigger
500 render={
501 <Button
502 type="button"
503 size="xs"
504 variant="ghost"
505 disabled={activity.isRevertingCheckpoint || activity.isWorking}
506 onClick={() => ctx.onRevertToTurnCount(turnCount, messageId)}
507 aria-label="Edit from here"
508 />
509 }
510 >
511 <Undo2Icon className="size-3" />
512 </TooltipTrigger>
513 <TooltipPopup side="top">Edit from here</TooltipPopup>
514 </Tooltip>
515 );
517​
518const COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM = 1.75;
519​
520const COLLAPSED_USER_MESSAGE_FADE_MASK = `linear-gradient(to bottom, black calc(100% - ${COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM}rem), transparent)`;
521​
522const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(props: {
523 text: string;
524 renderContextReference: (reference: ChatMarkdownContextReference) => ReactNode;
525 skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
526 markdownCwd: string | undefined;
527 footer?: ReactNode;
528}) {
529 const [expanded, setExpanded] = useState(false);
530 const revealForFind = () => setExpanded(true);
531 const revealRef = findRevealRef(revealForFind);
532 const hasVisibleBody = props.text.trim().length > 0;
533 const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text);
534 const isCollapsed = canCollapse && !expanded;
535 const showCollapseControl = canCollapse;
536​
537 return (
538 <div>
539 {hasVisibleBody ? (
540 <div
541 ref={revealRef}
542 className={cn("relative", isCollapsed && "max-h-44 overflow-hidden")}
543 data-user-message-body="true"
544 data-thread-find-text="true"
545 data-thread-find-fold={isCollapsed ? "" : undefined}
546 data-user-message-collapsed={isCollapsed ? "true" : "false"}
547 data-user-message-collapsible={canCollapse ? "true" : "false"}
548 data-user-message-fade={isCollapsed ? "true" : "false"}
549 style={
550 isCollapsed
551 ? {
552 WebkitMaskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
553 maskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
554 }
555 : undefined
556 }
557 >
558 <UserMessageBody
559 text={props.text}
560 renderContextReference={props.renderContextReference}
561 skills={props.skills}
562 markdownCwd={props.markdownCwd}
563 />
564 </div>
565 ) : null}
566 {showCollapseControl || props.footer ? (
567 <div
568 className={cn(
569 "mt-1.5 flex items-center gap-2",
570 showCollapseControl && props.footer ? "justify-between" : "justify-end",
571 )}
572 data-user-message-footer="true"
573 >
574 {showCollapseControl ? (
575 <Button
576 type="button"
577 size="xs"
578 variant="ghost-muted"
579 aria-expanded={expanded}
580 data-scroll-anchor-ignore
581 onClick={() => setExpanded((value) => !value)}
582 className="-ml-1"
583 >
584 {expanded ? "Show less" : "Show full message"}
585 </Button>
586 ) : null}
587 {props.footer ? (
588 <div className="ml-auto flex items-center gap-2">{props.footer}</div>
589 ) : null}
590 </div>
591 ) : null}
592 </div>
593 );
594});
595​
596const UserMessageBody = memo(function UserMessageBody(props: {
597 text: string;
598 renderContextReference?: (reference: ChatMarkdownContextReference) => ReactNode;
599 skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
600 markdownCwd: string | undefined;
601}) {
602 const ctx = use(TimelineRowCtx);
603 if (props.text.length === 0) {
604 return null;
605 }
606 return (
607 <ChatMarkdown
608 text={props.text}
609 cwd={props.markdownCwd}
610 threadRef={ctx.threadRef ?? undefined}
611 skills={props.skills}
612 className="text-foreground"
613 lineBreaks
614 parseRawHtml={false}
615 renderContextReference={props.renderContextReference}
616 headingLevelOffset={MESSAGE_HEADING_LEVEL}
617 />
618 );
619});