Open History to see the last commit
1import ChatMarkdown from "./ChatMarkdown";
2import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview";
3import type { PreviewAnnotationPayload, ThreadContextRecord } from "@t3tools/contracts";
4import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
5import { videoMimeType } from "@t3tools/shared/video";
6import { MessageCircleIcon, MousePointerClickIcon } from "lucide-react";
7import { createContext, type MouseEvent, type ReactElement, type ReactNode, use } from "react";
8import type { EnvironmentId } from "@t3tools/contracts";
9
10import type { ComposerFileAttachment, ComposerImageAttachment } from "~/composerDraftStore";
11import { composerFileNeedsReattach } from "~/composerDraftStore";
12import { useTheme } from "~/hooks/useTheme";
13import {
14 formatAttachmentUploadProgress,
15 type AttachmentUploadState,
16} from "~/lib/attachmentUploadState";
17import { cn } from "~/lib/utils";
18import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
19import {
20 fileContextReference,
21 imageContextReference,
22 isPullRequestSummaryContext,
23 pullRequestContextDisplayState,
24 pullRequestContextKindLabel,
25 previewAnnotationContextId,
26 previewAnnotationContextLabel,
27 reviewCommentContextId,
28 reviewCommentContextLabel,
29 terminalContextReference,
30 uploadedAttachmentContextRecord,
31} from "~/lib/composerContextRecords";
32import type { TerminalContextDraft } from "~/lib/terminalContext";
33import type { ReviewCommentContext } from "~/reviewCommentContext";
34import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
35import { ThreadContextChip } from "./ThreadContextChip";
36import {
37 createContextPresentationRegistry,
38 type ContextPresentationCapability,
39} from "./contextPresentationRegistry";
40import {
41 COMPOSER_INLINE_CHIP_CLASS_NAME,
42 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
43 COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
44 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES,
45 CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES,
46 PULL_REQUEST_INLINE_CHIP_TONE_CLASS_NAMES,
47} from "./composerInlineChip";
48import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
49import {
50 ContextChipPopover,
51 ContextChipShell,
52 FileChip,
53 ImageChipButton,
54 PullRequestChip,
55 UnresolvedChip,
56} from "./contextChipParts";
57
58/**
59 * Draft-side payload behind a context reference chip. Each kind keeps its existing draft
60 * shape; the editor only needs a way to look one up by id.
61 */
62export type ComposerDraftContextRecord =
63 | { kind: "terminal"; record: TerminalContextDraft }
64 | { kind: "review-comment"; record: ReviewCommentContext }
65 | { kind: "preview-annotation"; record: PreviewAnnotationPayload }
66 | { kind: "image"; record: ComposerImageAttachment; upload?: AttachmentUploadState | undefined }
67 | { kind: "file"; record: ComposerFileAttachment; upload?: AttachmentUploadState | undefined }
68 | { kind: "thread"; record: ThreadContextRecord };
69
70/** What a chip can do beyond showing itself; the composer supplies the handlers. */
71export interface ComposerContextActions {
72 environmentId: EnvironmentId | null;
73 expandImage: (imageId: string) => void;
74 expandVideo: (fileId: string) => void;
75 openFile: (fileId: string) => void;
76 openMention: (path: string) => void;
77 openPullRequest: (event: MouseEvent<HTMLElement>, url: string) => void;
78}
79
80export const ComposerContextActionsContext = createContext<ComposerContextActions>({
81 environmentId: null,
82 expandImage: () => {},
83 expandVideo: () => {},
84 openFile: () => {},
85 openMention: () => {},
86 openPullRequest: () => {},
87});
88
89export type ComposerDraftContextRecords = ReadonlyMap<string, ComposerDraftContextRecord>;
90
91export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new Map();
92
93export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) {
94 if (entry.kind !== "image" && entry.kind !== "file") return null;
95 return uploadedAttachmentContextRecord(entry.record, entry.upload);
96}
97
98export const ComposerContextRecordsContext = createContext<ComposerDraftContextRecords>(
99 EMPTY_COMPOSER_CONTEXT_RECORDS,
100);
101
102export function composerContextRecordsFromDraft(input: {
103 terminalContexts: ReadonlyArray<TerminalContextDraft>;
104 reviewComments?: ReadonlyArray<ReviewCommentContext>;
105 previewAnnotations?: ReadonlyArray<PreviewAnnotationPayload>;
106 threadContexts?: ReadonlyArray<ThreadContextRecord>;
107 images?: ReadonlyArray<ComposerImageAttachment>;
108 files?: ReadonlyArray<ComposerFileAttachment>;
109 uploadsByImageId?: Readonly<Record<string, AttachmentUploadState>>;
110}): ComposerDraftContextRecords {
111 const records = new Map<string, ComposerDraftContextRecord>();
112 for (const record of input.images ?? []) {
113 records.set(imageContextReference(record).contextId, {
114 kind: "image",
115 record,
116 upload: input.uploadsByImageId?.[record.id],
117 });
118 }
119 for (const record of input.files ?? []) {
120 records.set(fileContextReference(record).contextId, {
121 kind: "file",
122 record,
123 upload: input.uploadsByImageId?.[record.id],
124 });
125 }
126 for (const record of input.terminalContexts) {
127 records.set(terminalContextReference(record).contextId, { kind: "terminal", record });
128 }
129 for (const record of input.reviewComments ?? []) {
130 records.set(reviewCommentContextId(record.id), { kind: "review-comment", record });
131 }
132 for (const record of input.previewAnnotations ?? []) {
133 records.set(previewAnnotationContextId(record.id), { kind: "preview-annotation", record });
134 }
135 for (const record of input.threadContexts ?? []) {
136 records.set(record.contextId, { kind: "thread", record });
137 }
138 return records;
139}
140
141function ContextChip(props: {
142 icon: ReactElement;
143 label: string;
144 kindLabel: string;
145 details: ReactNode;
146 detailsMode: ContextPresentationCapability["details"];
147 toneClassName: string;
148}) {
149 const content = (
150 <ContextChipShell
151 icon={props.icon}
152 label={props.label}
153 className={cn(COMPOSER_INLINE_CHIP_CLASS_NAME, props.toneClassName)}
154 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
155 interactive={props.detailsMode === "popover"}
156 aria-hidden={props.detailsMode === "popover" ? true : undefined}
157 aria-label={
158 props.detailsMode === "tooltip" ? `${props.kindLabel}, ${props.label}` : undefined
159 }
160 tooltip={props.detailsMode === "tooltip" ? props.details : undefined}
161 />
162 );
163 if (props.detailsMode === "popover") {
164 return (
165 <ContextChipPopover accessibleLabel={props.kindLabel + ", " + props.label} chip={content}>
166 {props.details}
167 </ContextChipPopover>
168 );
169 }
170 return content;
171}
172
173function uploadStatusSuffix(upload: AttachmentUploadState | undefined): string | null {
174 if (upload?.status === "uploading") return formatAttachmentUploadProgress(upload.progress);
175 if (upload?.status === "failed") return "upload failed";
176 return null;
177}
178
179function attachmentTooltip(
180 attachment: ComposerImageAttachment | ComposerFileAttachment,
181 upload: AttachmentUploadState | undefined,
182): string {
183 const lines = [attachment.name, formatAttachmentSize(attachment.sizeBytes)];
184 if (upload?.status === "failed") lines.push("", upload.reason);
185 return lines.join("\n");
186}
187
188function ImageContextChip(props: {
189 record: ComposerImageAttachment;
190 upload: AttachmentUploadState | undefined;
191}) {
192 const actions = use(ComposerContextActionsContext);
193 return (
194 <Tooltip>
195 <TooltipTrigger
196 render={
197 <ImageChipButton
198 name={props.record.name}
199 previewUrl={props.record.previewUrl}
200 className={COMPOSER_INLINE_CHIP_CLASS_NAME}
201 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
202 size={formatAttachmentSize(props.record.sizeBytes)}
203 suffix={uploadStatusSuffix(props.upload)}
204 onClick={() => actions.expandImage(props.record.id)}
205 />
206 }
207 />
208 <TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
209 {attachmentTooltip(props.record, props.upload)}
210 </TooltipPopup>
211 </Tooltip>
212 );
213}
214
215function FileContextChip(props: {
216 record: ComposerFileAttachment;
217 upload: AttachmentUploadState | undefined;
218}) {
219 const actions = use(ComposerContextActionsContext);
220 const { resolvedTheme } = useTheme();
221 const needsReattach = composerFileNeedsReattach(props.record);
222 const suffix = needsReattach ? "attach again" : uploadStatusSuffix(props.upload);
223 const size = formatAttachmentSize(props.record.sizeBytes);
224 const isVideo = videoMimeType(props.record) !== null;
225 return (
226 <FileChip
227 name={props.record.name}
228 size={size}
229 isVideo={isVideo}
230 theme={resolvedTheme}
231 className={COMPOSER_INLINE_CHIP_CLASS_NAME}
232 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
233 error={props.upload?.status === "failed"}
234 unresolved={needsReattach}
235 suffix={suffix}
236 accessibleLabel={`${isVideo && !needsReattach ? "Preview video" : "File"} attachment, ${props.record.name}, ${size}`}
237 onOpen={
238 !needsReattach
239 ? () =>
240 isVideo ? actions.expandVideo(props.record.id) : actions.openFile(props.record.id)
241 : undefined
242 }
243 tooltip={
244 needsReattach
245 ? `${props.record.name} was not saved with this draft. Attach it again to send it.`
246 : attachmentTooltip(props.record, props.upload)
247 }
248 />
249 );
250}
251
252function PullRequestContextChip(props: { record: ReviewCommentContext; toneClassName: string }) {
253 const actions = use(ComposerContextActionsContext);
254 const metadata = props.record.pullRequest;
255 if (metadata === undefined) return null;
256 return (
257 <PullRequestChip
258 metadata={metadata}
259 environmentId={actions.environmentId}
260 label={reviewCommentContextLabel(props.record)}
261 kindLabel={pullRequestContextKindLabel(props.record)}
262 className={cn(COMPOSER_INLINE_CHIP_CLASS_NAME, props.toneClassName)}
263 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
264 onOpen={actions.openPullRequest}
265 />
266 );
267}
268
269function previewAnnotationTooltip(annotation: PreviewAnnotationPayload): string {
270 const lines = [annotation.pageTitle?.trim() || annotation.pageUrl];
271 if (annotation.comment.trim()) lines.push("", annotation.comment.trim());
272 const targets: string[] = [];
273 const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
274 if (annotation.elements.length > 0) targets.push(plural(annotation.elements.length, "element"));
275 if (annotation.regions.length > 0) targets.push(plural(annotation.regions.length, "region"));
276 if (annotation.strokes.length > 0) targets.push(plural(annotation.strokes.length, "drawing"));
277 if (annotation.styleChanges.length > 0) {
278 targets.push(plural(annotation.styleChanges.length, "style change"));
279 }
280 if (targets.length > 0) lines.push("", targets.join(", "));
281 return lines.join("\n");
282}
283
284function ComposerReviewCommentDetails({ comment }: { comment: ReviewCommentContext }) {
285 return (
286 <div className="space-y-2 overflow-hidden rounded-lg border border-border/70 bg-background/70 p-3">
287 <div className="space-y-1">
288 <div className="truncate text-xs font-medium text-foreground">{comment.filePath}</div>
289 <div className="text-secondary-label text-[11px]">
290 {comment.sectionTitle} · {comment.rangeLabel}
291 </div>
292 </div>
293 {comment.text.trim() ? <ChatMarkdown text={comment.text.trim()} cwd={undefined} /> : null}
294 {comment.diff.trim() ? (
295 <div className="flex h-64 min-h-0 flex-col overflow-hidden rounded-md border border-border">
296 <ReadOnlySourcePreview name="review.diff" text={comment.diff} />
297 </div>
298 ) : null}
299 </div>
300 );
301}
302
303function ComposerPreviewAnnotationDetails({
304 annotation,
305}: {
306 annotation: PreviewAnnotationPayload;
307}) {
308 const summary = previewAnnotationTooltip(annotation);
309 return (
310 <div className="overflow-hidden rounded-lg border border-border/70 bg-background/70">
311 {annotation.screenshot?.dataUrl ? (
312 <img
313 src={annotation.screenshot.dataUrl}
314 alt="Annotated preview crop"
315 className="max-h-64 w-full border-border/70 border-b bg-muted object-contain"
316 />
317 ) : (
318 <div className="border-border/70 border-b bg-muted/40 px-3 py-2 text-secondary-label text-xs">
319 Screenshot unavailable
320 </div>
321 )}
322 <div className="whitespace-pre-wrap wrap-break-word px-3 py-2.5 text-sm text-foreground">
323 {summary}
324 </div>
325 </div>
326 );
327}
328
329function UnresolvedContextChip(props: { label: string }) {
330 return (
331 <UnresolvedChip
332 label={props.label}
333 className={COMPOSER_INLINE_CHIP_CLASS_NAME}
334 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
335 tooltip="This context is no longer available. Remove it or attach it again."
336 tooltipClassName="max-w-80 leading-tight"
337 />
338 );
339}
340
341interface ComposerContextRenderContext {
342 label: string;
343}
344
345const composerContextPresentationRegistry = createContextPresentationRegistry<
346 ComposerDraftContextRecord,
347 ComposerContextRenderContext,
348 ReactElement
349>({
350 requiredKinds: ["image", "file", "terminal", "review-comment", "preview-annotation", "thread"],
351 handlers: [
352 {
353 kind: "terminal",
354 canRender: (entry) => entry.kind === "terminal",
355 render: (entry, context, definition) =>
356 entry.kind === "terminal" ? (
357 <ComposerPendingTerminalContextChip
358 context={entry.record}
359 detailsMode={definition.capabilities.details}
360 />
361 ) : (
362 <UnresolvedContextChip label={context.label} />
363 ),
364 },
365 {
366 kind: "image",
367 canRender: (entry) => entry.kind === "image",
368 render: (entry, context) =>
369 entry.kind === "image" ? (
370 <ImageContextChip record={entry.record} upload={entry.upload} />
371 ) : (
372 <UnresolvedContextChip label={context.label} />
373 ),
374 },
375 {
376 kind: "file",
377 canRender: (entry) => entry.kind === "file",
378 render: (entry, context) =>
379 entry.kind === "file" ? (
380 <FileContextChip record={entry.record} upload={entry.upload} />
381 ) : (
382 <UnresolvedContextChip label={context.label} />
383 ),
384 },
385 {
386 kind: "review-comment",
387 canRender: (entry) => entry.kind === "review-comment",
388 render: (entry, context, definition) => {
389 if (entry.kind !== "review-comment") {
390 return <UnresolvedContextChip label={context.label} />;
391 }
392 const isPullRequest = isPullRequestSummaryContext(entry.record);
393 const pullRequestState = pullRequestContextDisplayState(entry.record) ?? "unknown";
394 if (isPullRequest && entry.record.pullRequest !== undefined) {
395 return (
396 <PullRequestContextChip
397 record={entry.record}
398 toneClassName={PULL_REQUEST_INLINE_CHIP_TONE_CLASS_NAMES[pullRequestState]}
399 />
400 );
401 }
402 return (
403 <ContextChip
404 icon={
405 isPullRequest ? (
406 <PullRequestGlyph.pullRequest
407 className={cn(
408 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
409 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES["pull-request"],
410 "size-3.5",
411 )}
412 />
413 ) : (
414 <MessageCircleIcon
415 className={cn(
416 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
417 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES["review-comment"],
418 "size-3.5",
419 )}
420 />
421 )
422 }
423 label={reviewCommentContextLabel(entry.record)}
424 kindLabel={isPullRequest ? pullRequestContextKindLabel(entry.record) : "Review comment"}
425 details={<ComposerReviewCommentDetails comment={entry.record} />}
426 detailsMode={definition.capabilities.details}
427 toneClassName={
428 isPullRequest
429 ? PULL_REQUEST_INLINE_CHIP_TONE_CLASS_NAMES[pullRequestState]
430 : CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES["review-comment"]
431 }
432 />
433 );
434 },
435 },
436 {
437 kind: "preview-annotation",
438 canRender: (entry) => entry.kind === "preview-annotation",
439 render: (entry, context, definition) =>
440 entry.kind === "preview-annotation" ? (
441 <ContextChip
442 icon={
443 <MousePointerClickIcon
444 className={cn(
445 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
446 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES["preview-annotation"],
447 "size-3.5",
448 )}
449 />
450 }
451 label={previewAnnotationContextLabel(entry.record)}
452 kindLabel="Preview annotation"
453 details={<ComposerPreviewAnnotationDetails annotation={entry.record} />}
454 detailsMode={definition.capabilities.details}
455 toneClassName={CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES["preview-annotation"]}
456 />
457 ) : (
458 <UnresolvedContextChip label={context.label} />
459 ),
460 },
461 {
462 kind: "thread",
463 canRender: (entry) => entry.kind === "thread",
464 render: (entry, context) =>
465 entry.kind === "thread" ? (
466 <ThreadContextChip
467 record={entry.record}
468 className={COMPOSER_INLINE_CHIP_CLASS_NAME}
469 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
470 />
471 ) : (
472 <UnresolvedContextChip label={context.label} />
473 ),
474 },
475 ],
476 fallback: (_kind, _entry, context) => <UnresolvedContextChip label={context.label} />,
477});
478
479/** Compact chip for one reference. Unknown kinds and missing records use the registry fallback. */
480export function ComposerContextReferenceChip(props: {
481 kind: string;
482 contextId: string;
483 label: string;
484}): ReactElement {
485 const records = use(ComposerContextRecordsContext);
486 return composerContextPresentationRegistry.render(props.kind, records.get(props.contextId), {
487 label: props.label,
488 });
489}