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

UserMessageContextChips.tsx

592 lines21.4 KB

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