Open History to see the last commit
1import { documentChipKindForFileName } from "~/pierre-icons";
2import { isSvgAttachment } from "@t3tools/shared/image";
3import { useRenderedAppearance } from "../../hooks/useTheme";
4import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
5import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
6import { useRightPanelStore } from "~/rightPanelStore";
7import { COMPOSER_CONTEXT_KINDS } from "@t3tools/contracts";
8import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
9import { use, type ReactNode } from "react";
10import { FileDiff } from "@pierre/diffs/react";
11import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
12import {
13 type ChatFileAttachment,
14 type ChatImageAttachment,
15 isImageAttachment,
16 isVideoAttachment,
17} from "../../types";
18import {
19 getRenderablePatch,
20 resolveDiffThemeName,
21 resolveFileDiffPath,
22} from "../../lib/diffRendering";
23import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting";
24import ChatMarkdown from "../ChatMarkdown";
25import { EnvironmentContextChip } from "../EnvironmentContextChip";
26import { ThreadContextChip } from "../ThreadContextChip";
27import { MessageCircleIcon, MousePointerClickIcon, PaintbrushIcon } from "lucide-react";
28import type { ComposerContextId, KnownComposerContextRecord } from "@t3tools/contracts";
29import { buildExpandedImagePreview } from "./ExpandedImagePreview";
30import { WorkspaceEntryIcon, WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
31import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
32import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
33import {
34 ContextChipPopover as UserMessageContextPopover,
35 FileChip,
36 ImageChipButton,
37 PULL_REQUEST_CHIP_KINDS,
38 PullRequestChip,
39 UnresolvedChip,
40} from "../contextChipParts";
41import {
42 isPullRequestSummaryContext,
43 pullRequestContextDisplayState,
44 pullRequestContextKindLabel,
45 reviewCommentContextLabel,
46} from "~/lib/composerContextRecords";
47import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
48import { ContextChip, ContextChipLabel, type ContextChipKind } from "../ContextChip";
49import { createContextPresentationRegistry } from "../contextPresentationRegistry";
50import type { ChatMarkdownContextReference } from "../ChatMarkdown";
51import {
52 SkillChipPopover,
53 skillInstructionsOpener,
54 skillPopoverDescription,
55} from "./SkillInlineText";
56import { formatWorkspaceRelativePath } from "../../filePathDisplay";
57import {
58 buildReviewCommentRenderablePatch,
59 formatReviewCommentFence,
60 type ReviewCommentContext,
61} from "../../reviewCommentContext";
62import { TimelineRowCtx } from "./timelineRowContext";
63
64function UserMessageMentionChip(props: {
65 record: Extract<KnownComposerContextRecord, { kind: "mention" }>;
66 copyMarkdown: string;
67}) {
68 const ctx = use(TimelineRowCtx);
69 return (
70 <Tooltip>
71 <TooltipTrigger
72 render={
73 <ContextChip
74 kind={documentChipKindForFileName(props.record.path) ?? "mention"}
75 render={<button type="button" />}
76 aria-label={`Preview ${props.record.path}`}
77 data-markdown-copy={props.copyMarkdown}
78 onClick={() => {
79 if (ctx.threadRef)
80 useRightPanelStore.getState().openFile(ctx.threadRef, props.record.path);
81 }}
82 >
83 <WorkspaceEntryIcon
84 path={props.record.path}
85 environmentId={ctx.activeThreadEnvironmentId}
86 cwd={ctx.workspaceRoot}
87 theme={ctx.resolvedTheme}
88 />
89 <ContextChipLabel>{props.record.label}</ContextChipLabel>
90 </ContextChip>
91 }
92 />
93 <TooltipPopup>
94 <WorkspaceEntryTooltip
95 path={props.record.path}
96 environmentId={ctx.activeThreadEnvironmentId}
97 cwd={ctx.workspaceRoot}
98 />
99 </TooltipPopup>
100 </Tooltip>
101 );
102}
103
104function UserMessageSkillChip(props: {
105 record: Extract<KnownComposerContextRecord, { kind: "skill" }>;
106 copyMarkdown: string;
107}) {
108 const { skills, threadRef } = use(TimelineRowCtx);
109 const skill = skills.find((candidate) => candidate.name === props.record.name);
110 return (
111 <SkillChipPopover
112 label={props.record.label || props.record.name}
113 description={skill ? skillPopoverDescription(skill) : null}
114 copyMarkdown={props.copyMarkdown}
115 onViewInstructions={skillInstructionsOpener(threadRef, skill)}
116 />
117 );
118}
119
120function UserMessagePullRequestContextChip(props: {
121 record: Extract<KnownComposerContextRecord, { kind: "review-comment" }>;
122 copyMarkdown: string;
123 kind: ContextChipKind;
124}) {
125 const { activeThreadEnvironmentId, openPullRequest } = use(TimelineRowCtx);
126 const metadata = props.record.pullRequest;
127 if (metadata === undefined) return null;
128 return (
129 <PullRequestChip
130 metadata={metadata}
131 environmentId={activeThreadEnvironmentId}
132 label={reviewCommentContextLabel(props.record)}
133 kindLabel={pullRequestContextKindLabel(props.record)}
134 kind={props.kind}
135 copyMarkdown={props.copyMarkdown}
136 onOpen={openPullRequest}
137 />
138 );
139}
140
141function UserMessagePreviewAnnotationDetails(props: {
142 record: Extract<KnownComposerContextRecord, { kind: "preview-annotation" }>;
143 image: ChatImageAttachment | null;
144}) {
145 const ctx = use(TimelineRowCtx);
146 const visibleElements = props.record.elements ?? [];
147 return (
148 <div className="max-w-full overflow-hidden rounded-lg border border-border/70 bg-background/70">
149 {props.image?.previewUrl ? (
150 <button
151 type="button"
152 className="block max-h-64 w-full cursor-zoom-in overflow-hidden border-b border-border/70 bg-muted"
153 aria-label={`Preview ${props.image.name}`}
154 onClick={() => {
155 if (!props.image) return;
156 const preview = buildExpandedImagePreview([props.image], props.image.id);
157 if (preview) ctx.onImageExpand(preview);
158 }}
159 >
160 <img
161 src={props.image.previewUrl}
162 alt="Annotated preview crop"
163 className="max-h-64 w-full object-contain"
164 />
165 </button>
166 ) : (
167 <div className="border-b border-border/70 bg-muted/40 px-3 py-2 text-secondary-label text-xs">
168 Screenshot unavailable
169 </div>
170 )}
171 <div className="min-w-0 px-3 py-2.5">
172 <div className="text-message-foreground text-xs font-medium">
173 {props.record.pageTitle?.trim() || props.record.pageUrl || "Preview annotation"}
174 </div>
175 {props.record.comment ? (
176 <div className="mt-1 whitespace-pre-wrap wrap-break-word text-sm">
177 {props.record.comment}
178 </div>
179 ) : null}
180 <div className="mt-1 flex items-center gap-2 text-secondary-label text-3xs">
181 {props.record.targetSummary ? (
182 <span className="truncate">{props.record.targetSummary}</span>
183 ) : null}
184 {(props.record.styleChanges?.length ?? 0) > 0 ? (
185 <span className="inline-flex shrink-0 items-center gap-1">
186 <PaintbrushIcon className="size-3" />
187 {props.record.styleChanges?.length ?? 0}
188 </span>
189 ) : null}
190 </div>
191 {visibleElements.length > 0 ? (
192 <div className="mt-2 space-y-2 border-t border-border/60 pt-2">
193 {visibleElements.map((element) => {
194 const source = element.source;
195 const sourceLabel = source?.fileName
196 ? `${source.fileName}${source.lineNumber === null ? "" : `:${source.lineNumber}`}`
197 : null;
198 return (
199 <div
200 key={`${element.selector}\u0000${element.tagName}\u0000${sourceLabel ?? ""}\u0000${element.htmlPreview}`}
201 className="min-w-0"
202 >
203 <div className="flex min-w-0 items-center gap-2 text-xs">
204 <code className="truncate text-message-foreground">
205 {element.selector || `<${element.tagName}>`}
206 </code>
207 {sourceLabel ? (
208 <span className="ml-auto shrink-0 text-secondary-label">{sourceLabel}</span>
209 ) : null}
210 </div>
211 {element.htmlPreview?.trim() ? (
212 <pre className="mt-1 max-h-24 overflow-auto whitespace-pre-wrap rounded bg-muted/60 px-2 py-1.5 text-3xs leading-relaxed">
213 {element.htmlPreview.trim()}
214 </pre>
215 ) : null}
216 </div>
217 );
218 })}
219 </div>
220 ) : null}
221 </div>
222 </div>
223 );
224}
225
226function UserMessageElementDetails({
227 record,
228}: {
229 record: Extract<KnownComposerContextRecord, { kind: "element" }>;
230}) {
231 const sourceLabel = record.source?.fileName
232 ? `${record.source.fileName}${record.source.lineNumber === null ? "" : `:${record.source.lineNumber}`}`
233 : null;
234 return (
235 <div className="max-w-full overflow-hidden rounded-lg border border-border/70 bg-background/70">
236 <div className="border-b border-border/70 px-3 py-2.5">
237 <div className="truncate text-message-foreground text-xs font-medium">
238 {record.pageTitle?.trim() || record.pageUrl}
239 </div>
240 <div className="mt-0.5 truncate text-secondary-label text-3xs">{record.pageUrl}</div>
241 </div>
242 <div className="space-y-2 px-3 py-2.5">
243 <div className="flex min-w-0 items-center gap-2 text-xs">
244 <code className="truncate text-message-foreground">
245 {record.selector || `<${record.tagName}>`}
246 </code>
247 {sourceLabel ? (
248 <span className="ml-auto shrink-0 text-secondary-label">{sourceLabel}</span>
249 ) : null}
250 </div>
251 {record.htmlPreview?.trim() ? (
252 <div className="flex h-40 flex-col overflow-hidden rounded border border-border">
253 <ReadOnlySourcePreview name="element.html" text={record.htmlPreview} />
254 </div>
255 ) : null}
256 {record.styles?.trim() ? (
257 <div className="flex h-32 flex-col overflow-hidden rounded border border-border">
258 <ReadOnlySourcePreview name="styles.css" text={record.styles} />
259 </div>
260 ) : null}
261 </div>
262 </div>
263 );
264}
265
266interface UserMessageContextRenderContext {
267 environmentId: import("@t3tools/contracts").EnvironmentId;
268 reference: ChatMarkdownContextReference;
269 annotationImage: ChatImageAttachment | null;
270 attachment: ChatImageAttachment | ChatFileAttachment | null;
271 resolvedTheme: "light" | "dark";
272 copyMarkdown: string;
273 onExpandImage: (image: ChatImageAttachment) => void;
274 onExpandVideo: (file: ChatFileAttachment) => void;
275 onOpenFile: (file: ChatFileAttachment) => void;
276}
277
278function UnavailableUserMessageContextChip(props: UserMessageContextRenderContext) {
279 return (
280 <UnresolvedChip
281 label={props.reference.label}
282 copyMarkdown={props.copyMarkdown}
283 tooltip="This context is no longer available."
284 />
285 );
286}
287
288const userMessageContextPresentationRegistry = createContextPresentationRegistry<
289 KnownComposerContextRecord,
290 UserMessageContextRenderContext,
291 ReactNode
292>({
293 requiredKinds: COMPOSER_CONTEXT_KINDS,
294 handlers: [
295 {
296 kind: "mention",
297 canRender: (record) => record.kind === "mention",
298 render: (record, context) =>
299 record.kind === "mention" ? (
300 <UserMessageMentionChip record={record} copyMarkdown={context.copyMarkdown} />
301 ) : (
302 <UnavailableUserMessageContextChip {...context} />
303 ),
304 },
305 {
306 kind: "skill",
307 canRender: (record) => record.kind === "skill",
308 render: (record, context) =>
309 record.kind === "skill" ? (
310 <UserMessageSkillChip record={record} copyMarkdown={context.copyMarkdown} />
311 ) : (
312 <UnavailableUserMessageContextChip {...context} />
313 ),
314 },
315 {
316 kind: "thread",
317 canRender: (record) => record.kind === "thread",
318 render: (record, context) =>
319 record.kind === "thread" ? (
320 <ThreadContextChip record={record} copyMarkdown={context.copyMarkdown} />
321 ) : (
322 <UnavailableUserMessageContextChip {...context} />
323 ),
324 },
325 {
326 kind: "environment",
327 canRender: (record) => record.kind === "environment",
328 render: (record, context) =>
329 record.kind === "environment" ? (
330 <EnvironmentContextChip record={record} copyMarkdown={context.copyMarkdown} />
331 ) : (
332 <UnavailableUserMessageContextChip {...context} />
333 ),
334 },
335 {
336 kind: "image",
337 canRender: (record, context) =>
338 record.kind === "image" &&
339 context.attachment !== null &&
340 isImageAttachment(context.attachment),
341 render: (record, context) => {
342 if (
343 record.kind !== "image" ||
344 context.attachment === null ||
345 !isImageAttachment(context.attachment)
346 ) {
347 return <UnavailableUserMessageContextChip {...context} />;
348 }
349 const attachment = context.attachment;
350 return (
351 <ImageChipButton
352 name={record.name}
353 previewUrl={attachment.previewUrl}
354 size={formatAttachmentSize(record.sizeBytes)}
355 data-markdown-copy={context.copyMarkdown}
356 onClick={() => context.onExpandImage(attachment)}
357 />
358 );
359 },
360 },
361 {
362 kind: "file",
363 canRender: (record, context) =>
364 record.kind === "file" && context.attachment !== null && context.attachment.type === "file",
365 render: (record, context) => {
366 if (
367 record.kind !== "file" ||
368 context.attachment === null ||
369 context.attachment.type !== "file"
370 ) {
371 return <UnavailableUserMessageContextChip {...context} />;
372 }
373 const attachment = context.attachment;
374 const isVideo = isVideoAttachment(attachment);
375 const disabled =
376 attachment.downloadable === false && (!isVideo || attachment.previewUrl === undefined);
377 const size = formatAttachmentSize(record.sizeBytes);
378 return (
379 <FileChip
380 name={record.name}
381 svgPreview={
382 isSvgAttachment(attachment)
383 ? { environmentId: context.environmentId, attachmentId: attachment.id }
384 : undefined
385 }
386 size={size}
387 isVideo={isVideo}
388 theme={context.resolvedTheme}
389 disabled={disabled}
390 accessibleLabel={`${isVideo ? "Video" : "File"} attachment, ${record.name}, ${size}`}
391 copyMarkdown={context.copyMarkdown}
392 onOpen={() =>
393 isVideo ? context.onExpandVideo(attachment) : context.onOpenFile(attachment)
394 }
395 tooltip={`${record.name}\n${size}`}
396 />
397 );
398 },
399 },
400 {
401 kind: "terminal",
402 canRender: (record) => record.kind === "terminal",
403 render: (record, context, definition) =>
404 record.kind === "terminal" ? (
405 <span data-markdown-copy={context.copyMarkdown}>
406 <TerminalContextInlineChip
407 label={record.label}
408 terminalLabel={record.terminalLabel}
409 lineStart={record.lineStart}
410 lineEnd={record.lineEnd}
411 text={record.text}
412 detailsMode={definition.capabilities.details}
413 />
414 </span>
415 ) : (
416 <UnavailableUserMessageContextChip {...context} />
417 ),
418 },
419 {
420 kind: "element",
421 canRender: (record) => record.kind === "element",
422 render: (record, context) =>
423 record.kind === "element" ? (
424 <UserMessageContextPopover
425 copyMarkdown={context.copyMarkdown}
426 accessibleLabel={`Browser element, ${record.label}`}
427 kind="element"
428 icon={<MousePointerClickIcon />}
429 label={record.label}
430 >
431 <UserMessageElementDetails record={record} />
432 </UserMessageContextPopover>
433 ) : (
434 <UnavailableUserMessageContextChip {...context} />
435 ),
436 },
437 {
438 kind: "review-comment",
439 canRender: (record) => record.kind === "review-comment",
440 render: (record, context) => {
441 if (record.kind !== "review-comment") {
442 return <UnavailableUserMessageContextChip {...context} />;
443 }
444 const isPullRequest = isPullRequestSummaryContext(record);
445 const label = reviewCommentContextLabel(record);
446 const kindLabel = isPullRequest ? pullRequestContextKindLabel(record) : "Review comment";
447 const pullRequestState = pullRequestContextDisplayState(record) ?? "unknown";
448 if (isPullRequest && record.pullRequest !== undefined) {
449 return (
450 <UserMessagePullRequestContextChip
451 record={record}
452 copyMarkdown={context.copyMarkdown}
453 kind={PULL_REQUEST_CHIP_KINDS[pullRequestState]}
454 />
455 );
456 }
457 return (
458 <UserMessageContextPopover
459 copyMarkdown={context.copyMarkdown}
460 accessibleLabel={`${kindLabel}, ${label}${record.pullRequest ? `, ${record.pullRequest.title}` : ""}`}
461 kind={isPullRequest ? PULL_REQUEST_CHIP_KINDS[pullRequestState] : "review-comment"}
462 icon={isPullRequest ? <PullRequestGlyph.pullRequest /> : <MessageCircleIcon />}
463 label={label}
464 >
465 <UserMessageReviewCommentCard
466 comment={{
467 id: record.contextId,
468 sectionId: record.sectionId,
469 sectionTitle: record.sectionTitle,
470 filePath: record.filePath,
471 startIndex: record.startIndex,
472 endIndex: record.endIndex,
473 rangeLabel: record.rangeLabel,
474 text: record.text,
475 diff: record.diff,
476 ...(record.fenceLanguage !== undefined
477 ? { fenceLanguage: record.fenceLanguage }
478 : {}),
479 ...(record.pullRequest !== undefined ? { pullRequest: record.pullRequest } : {}),
480 }}
481 />
482 </UserMessageContextPopover>
483 );
484 },
485 },
486 {
487 kind: "preview-annotation",
488 canRender: (record) => record.kind === "preview-annotation",
489 render: (record, context) =>
490 record.kind === "preview-annotation" ? (
491 <UserMessageContextPopover
492 copyMarkdown={context.copyMarkdown}
493 accessibleLabel={`Preview annotation, ${record.label}`}
494 kind="preview-annotation"
495 icon={<MousePointerClickIcon />}
496 label={record.label}
497 >
498 <UserMessagePreviewAnnotationDetails record={record} image={context.annotationImage} />
499 </UserMessageContextPopover>
500 ) : (
501 <UnavailableUserMessageContextChip {...context} />
502 ),
503 },
504 ],
505 fallback: (_kind, _record, context) => <UnavailableUserMessageContextChip {...context} />,
506});
507
508export function UserMessageContextReferenceChip(props: {
509 reference: ChatMarkdownContextReference;
510 record: KnownComposerContextRecord | undefined;
511 annotationImage: ChatImageAttachment | null;
512 attachment: ChatImageAttachment | ChatFileAttachment | null;
513 onExpandImage: (image: ChatImageAttachment) => void;
514 onExpandVideo: (file: ChatFileAttachment) => void;
515 onOpenFile: (file: ChatFileAttachment) => void;
516}) {
517 const { resolvedTheme, activeThreadEnvironmentId } = use(TimelineRowCtx);
518 const copyMarkdown = formatComposerContextReference({
519 kind: props.reference.kind,
520 contextId: props.reference.contextId as ComposerContextId,
521 label: props.reference.label,
522 });
523 return userMessageContextPresentationRegistry.render(props.reference.kind, props.record, {
524 environmentId: activeThreadEnvironmentId,
525 reference: props.reference,
526 annotationImage: props.annotationImage,
527 attachment: props.attachment,
528 resolvedTheme,
529 copyMarkdown,
530 onExpandImage: props.onExpandImage,
531 onExpandVideo: props.onExpandVideo,
532 onOpenFile: props.onOpenFile,
533 });
534}
535
536function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentContext }) {
537 const renderedAppearance = useRenderedAppearance();
538 const ctx = use(TimelineRowCtx);
539 const fenceLanguage = comment.fenceLanguage ?? "diff";
540 const renderablePatch = getRenderablePatch(
541 buildReviewCommentRenderablePatch(comment),
542 `review-comment:${comment.id}`,
543 );
544
545 return (
546 <div className="space-y-2 rounded-lg border border-border/70 bg-background/70 p-3">
547 <div className="space-y-1">
548 <div className="text-xs font-medium text-foreground">
549 {formatWorkspaceRelativePath(comment.filePath, ctx.workspaceRoot)}
550 </div>
551 <div className="text-2xs text-muted-foreground">
552 {comment.sectionTitle} · {comment.rangeLabel}
553 </div>
554 </div>
555 {comment.text.length > 0 && (
556 <div className="wrap-break-word text-sm">
557 <ChatMarkdown
558 text={comment.text}
559 cwd={ctx.markdownCwd}
560 threadRef={ctx.threadRef ?? undefined}
561 skills={ctx.skills}
562 parseRawHtml={false}
563 lineBreaks
564 />
565 </div>
566 )}
567 {fenceLanguage !== "diff" && comment.diff.trim().length > 0 && (
568 <ChatMarkdown
569 text={formatReviewCommentFence(fenceLanguage, comment.diff)}
570 cwd={ctx.markdownCwd}
571 threadRef={ctx.threadRef ?? undefined}
572 skills={ctx.skills}
573 className="text-foreground"
574 />
575 )}
576 {renderablePatch?.kind === "files" && (
577 <DiffWorkerPoolProvider>
578 {renderablePatch.files.map((fileDiff) => (
579 <FileDiff
580 key={resolveFileDiffPath(fileDiff)}
581 fileDiff={fileDiff}
582 options={{
583 collapsed: false,
584 diffStyle: "unified",
585 theme: resolveDiffThemeName(renderedAppearance),
586 preferredHighlighter: PREFERRED_HIGHLIGHTER,
587 }}
588 />
589 ))}
590 </DiffWorkerPoolProvider>
591 )}
592 {renderablePatch?.kind === "raw" && (
593 <pre className="overflow-x-auto rounded-md bg-muted/40 p-2 text-xs">
594 {renderablePatch.text}
595 </pre>
596 )}
597 </div>
598 );
599}