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

UserMessageContextChips.tsx

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