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

UserMessageContextChips.tsx

600 lines21.8 KB

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