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

UserMessageContextChips.tsx

603 lines22.0 KB

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