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

UserMessageContextChips.tsx

594 lines21.9 KB

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 { 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 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 {
51 SkillChipPopover,
52 skillInstructionsOpener,
53 skillPopoverDescription,
54} from "./SkillInlineText";
55import { formatWorkspaceRelativePath } from "../../filePathDisplay";
56import {
57 buildReviewCommentRenderablePatch,
58 formatReviewCommentFence,
59 type ReviewCommentContext,
60} from "../../reviewCommentContext";
61import { TimelineRowCtx } from "./timelineRowContext";
62​
63function UserMessageMentionChip(props: {
64 record: Extract<KnownComposerContextRecord, { kind: "mention" }>;
65 copyMarkdown: string;
66}) {
67 const ctx = use(TimelineRowCtx);
68 return (
69 <Tooltip>
70 <TooltipTrigger
71 render={
72 <ContextChip
73 kind={documentChipKindForFileName(props.record.path) ?? "mention"}
74 render={<button type="button" />}
75 aria-label={`Preview ${props.record.path}`}
76 data-markdown-copy={props.copyMarkdown}
77 onClick={() => {
78 if (ctx.threadRef)
79 useRightPanelStore.getState().openFile(ctx.threadRef, props.record.path);
80 }}
81 >
82 <WorkspaceEntryIcon
83 path={props.record.path}
84 environmentId={ctx.activeThreadEnvironmentId}
85 cwd={ctx.workspaceRoot}
86 theme={ctx.resolvedTheme}
87 />
88 <ContextChipLabel>{props.record.label}</ContextChipLabel>
89 </ContextChip>
90 }
91 />
92 <TooltipPopup>
93 <WorkspaceEntryTooltip
94 path={props.record.path}
95 environmentId={ctx.activeThreadEnvironmentId}
96 cwd={ctx.workspaceRoot}
97 />
98 </TooltipPopup>
99 </Tooltip>
100 );
102​
103function UserMessageSkillChip(props: {
104 record: Extract<KnownComposerContextRecord, { kind: "skill" }>;
105 copyMarkdown: string;
106}) {
107 const { skills, threadRef } = use(TimelineRowCtx);
108 const skill = skills.find((candidate) => candidate.name === props.record.name);
109 return (
110 <SkillChipPopover
111 label={props.record.label || props.record.name}
112 description={skill ? skillPopoverDescription(skill) : null}
113 copyMarkdown={props.copyMarkdown}
114 onViewInstructions={skillInstructionsOpener(threadRef, skill)}
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 <UserMessageSkillChip record={record} copyMarkdown={context.copyMarkdown} />
316 ) : (
317 <UnavailableUserMessageContextChip {...context} />
318 ),
319 },
320 {
321 kind: "thread",
322 canRender: (record) => record.kind === "thread",
323 render: (record, context) =>
324 record.kind === "thread" ? (
325 <ThreadContextChip record={record} copyMarkdown={context.copyMarkdown} />
326 ) : (
327 <UnavailableUserMessageContextChip {...context} />
328 ),
329 },
330 {
331 kind: "image",
332 canRender: (record, context) =>
333 record.kind === "image" &&
334 context.attachment !== null &&
335 isImageAttachment(context.attachment),
336 render: (record, context) => {
337 if (
338 record.kind !== "image" ||
339 context.attachment === null ||
340 !isImageAttachment(context.attachment)
341 ) {
342 return <UnavailableUserMessageContextChip {...context} />;
343 }
344 const attachment = context.attachment;
345 return (
346 <ImageChipButton
347 name={record.name}
348 previewUrl={attachment.previewUrl}
349 size={formatAttachmentSize(record.sizeBytes)}
350 data-markdown-copy={context.copyMarkdown}
351 onClick={() => context.onExpandImage(attachment)}
352 />
353 );
354 },
355 },
356 {
357 kind: "file",
358 canRender: (record, context) =>
359 record.kind === "file" && context.attachment !== null && context.attachment.type === "file",
360 render: (record, context) => {
361 if (
362 record.kind !== "file" ||
363 context.attachment === null ||
364 context.attachment.type !== "file"
365 ) {
366 return <UnavailableUserMessageContextChip {...context} />;
367 }
368 const attachment = context.attachment;
369 const isVideo = isVideoAttachment(attachment);
370 const disabled =
371 attachment.downloadable === false && (!isVideo || attachment.previewUrl === undefined);
372 const size = formatAttachmentSize(record.sizeBytes);
373 return (
374 <FileChip
375 name={record.name}
376 svgPreview={
377 isSvgAttachment(attachment)
378 ? { environmentId: context.environmentId, attachmentId: attachment.id }
379 : undefined
380 }
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, activeThreadEnvironmentId } = 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 environmentId: activeThreadEnvironmentId,
520 reference: props.reference,
521 annotationImage: props.annotationImage,
522 attachment: props.attachment,
523 resolvedTheme,
524 copyMarkdown,
525 onExpandImage: props.onExpandImage,
526 onExpandVideo: props.onExpandVideo,
527 onOpenFile: props.onOpenFile,
528 });
530​
531function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentContext }) {
532 const renderedAppearance = useRenderedAppearance();
533 const ctx = use(TimelineRowCtx);
534 const fenceLanguage = comment.fenceLanguage ?? "diff";
535 const renderablePatch = getRenderablePatch(
536 buildReviewCommentRenderablePatch(comment),
537 `review-comment:${comment.id}`,
538 );
539​
540 return (
541 <div className="space-y-2 rounded-lg border border-border/70 bg-background/70 p-3">
542 <div className="space-y-1">
543 <div className="text-xs font-medium text-foreground">
544 {formatWorkspaceRelativePath(comment.filePath, ctx.workspaceRoot)}
545 </div>
546 <div className="text-2xs text-muted-foreground">
547 {comment.sectionTitle} · {comment.rangeLabel}
548 </div>
549 </div>
550 {comment.text.length > 0 && (
551 <div className="wrap-break-word text-sm">
552 <ChatMarkdown
553 text={comment.text}
554 cwd={ctx.markdownCwd}
555 threadRef={ctx.threadRef ?? undefined}
556 skills={ctx.skills}
557 parseRawHtml={false}
558 lineBreaks
559 />
560 </div>
561 )}
562 {fenceLanguage !== "diff" && comment.diff.trim().length > 0 && (
563 <ChatMarkdown
564 text={formatReviewCommentFence(fenceLanguage, comment.diff)}
565 cwd={ctx.markdownCwd}
566 threadRef={ctx.threadRef ?? undefined}
567 skills={ctx.skills}
568 className="text-foreground"
569 />
570 )}
571 {renderablePatch?.kind === "files" && (
572 <DiffWorkerPoolProvider>
573 {renderablePatch.files.map((fileDiff) => (
574 <FileDiff
575 key={resolveFileDiffPath(fileDiff)}
576 fileDiff={fileDiff}
577 options={{
578 collapsed: false,
579 diffStyle: "unified",
580 theme: resolveDiffThemeName(renderedAppearance),
581 preferredHighlighter: PREFERRED_HIGHLIGHTER,
582 }}
583 />
584 ))}
585 </DiffWorkerPoolProvider>
586 )}
587 {renderablePatch?.kind === "raw" && (
588 <pre className="overflow-x-auto rounded-md bg-muted/40 p-2 text-xs">
589 {renderablePatch.text}
590 </pre>
591 )}
592 </div>
593 );