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 { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
18import {
19 fileContextReference,
20 imageContextReference,
21 isPullRequestSummaryContext,
22 pullRequestContextDisplayState,
23 pullRequestContextKindLabel,
24 previewAnnotationContextId,
25 previewAnnotationContextLabel,
26 reviewCommentContextId,
27 reviewCommentContextLabel,
28 terminalContextReference,
29 uploadedAttachmentContextRecord,
30} from "~/lib/composerContextRecords";
31import type { TerminalContextDraft } from "~/lib/terminalContext";
32import type { ReviewCommentContext } from "~/reviewCommentContext";
33import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
34import { ThreadContextChip } from "./ThreadContextChip";
35import {
36 createContextPresentationRegistry,
37 type ContextPresentationCapability,
38} from "./contextPresentationRegistry";
39import type { ContextChipKind } from "./ContextChip";
40import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
41import {
42 ContextChipPopover,
43 ContextChipShell,
44 FileChip,
45 ImageChipButton,
46 PULL_REQUEST_CHIP_KINDS,
47 PullRequestChip,
48 UnresolvedChip,
49} from "./contextChipParts";
50
51/**
52 * Draft-side payload behind a context reference chip. Each kind keeps its existing draft
53 * shape; the editor only needs a way to look one up by id.
54 */
55export type ComposerDraftContextRecord =
56 | { kind: "terminal"; record: TerminalContextDraft }
57 | { kind: "review-comment"; record: ReviewCommentContext }
58 | {
59 kind: "preview-annotation";
60 record: PreviewAnnotationPayload;
61 /** The crop, which the draft stores as an image sharing the annotation's id. */
62 screenshot?: ComposerImageAttachment | undefined;
63 }
64 | { kind: "image"; record: ComposerImageAttachment; upload?: AttachmentUploadState | undefined }
65 | { kind: "file"; record: ComposerFileAttachment; upload?: AttachmentUploadState | undefined }
66 | { kind: "thread"; record: ThreadContextRecord };
67
68/** What a chip can do beyond showing itself; the composer supplies the handlers. */
69export interface ComposerContextActions {
70 environmentId: EnvironmentId | null;
71 expandImage: (imageId: string) => void;
72 expandVideo: (fileId: string) => void;
73 openFile: (fileId: string) => void;
74 openMention: (path: string) => void;
75 openPullRequest: (event: MouseEvent<HTMLElement>, url: string) => void;
76}
77
78export const ComposerContextActionsContext = createContext<ComposerContextActions>({
79 environmentId: null,
80 expandImage: () => {},
81 expandVideo: () => {},
82 openFile: () => {},
83 openMention: () => {},
84 openPullRequest: () => {},
85});
86
87export type ComposerDraftContextRecords = ReadonlyMap<string, ComposerDraftContextRecord>;
88
89export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new Map();
90
91export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) {
92 if (entry.kind !== "image" && entry.kind !== "file") return null;
93 return uploadedAttachmentContextRecord(entry.record, entry.upload);
94}
95
96export const ComposerContextRecordsContext = createContext<ComposerDraftContextRecords>(
97 EMPTY_COMPOSER_CONTEXT_RECORDS,
98);
99
100export function composerContextRecordsFromDraft(input: {
101 terminalContexts: ReadonlyArray<TerminalContextDraft>;
102 reviewComments?: ReadonlyArray<ReviewCommentContext>;
103 previewAnnotations?: ReadonlyArray<PreviewAnnotationPayload>;
104 threadContexts?: ReadonlyArray<ThreadContextRecord>;
105 images?: ReadonlyArray<ComposerImageAttachment>;
106 files?: ReadonlyArray<ComposerFileAttachment>;
107 uploadsByImageId?: Readonly<Record<string, AttachmentUploadState>>;
108}): ComposerDraftContextRecords {
109 const records = new Map<string, ComposerDraftContextRecord>();
110 for (const record of input.images ?? []) {
111 records.set(imageContextReference(record).contextId, {
112 kind: "image",
113 record,
114 upload: input.uploadsByImageId?.[record.id],
115 });
116 }
117 for (const record of input.files ?? []) {
118 records.set(fileContextReference(record).contextId, {
119 kind: "file",
120 record,
121 upload: input.uploadsByImageId?.[record.id],
122 });
123 }
124 for (const record of input.terminalContexts) {
125 records.set(terminalContextReference(record).contextId, { kind: "terminal", record });
126 }
127 for (const record of input.reviewComments ?? []) {
128 records.set(reviewCommentContextId(record.id), { kind: "review-comment", record });
129 }
130 const imagesById = new Map((input.images ?? []).map((image) => [image.id, image]));
131 for (const record of input.previewAnnotations ?? []) {
132 records.set(previewAnnotationContextId(record.id), {
133 kind: "preview-annotation",
134 record,
135 screenshot: imagesById.get(record.id),
136 });
137 }
138 for (const record of input.threadContexts ?? []) {
139 records.set(record.contextId, { kind: "thread", record });
140 }
141 return records;
142}
143
144function ContextChip(props: {
145 icon: ReactElement;
146 label: string;
147 kindLabel: string;
148 details: ReactNode;
149 detailsMode: ContextPresentationCapability["details"];
150 kind: ContextChipKind;
151}) {
152 if (props.detailsMode === "popover") {
153 return (
154 <ContextChipPopover
155 kind={props.kind}
156 icon={props.icon}
157 label={props.label}
158 accessibleLabel={props.kindLabel + ", " + props.label}
159 >
160 {props.details}
161 </ContextChipPopover>
162 );
163 }
164 return (
165 <ContextChipShell
166 kind={props.kind}
167 icon={props.icon}
168 label={props.label}
169 aria-label={
170 props.detailsMode === "tooltip" ? `${props.kindLabel}, ${props.label}` : undefined
171 }
172 tooltip={props.detailsMode === "tooltip" ? props.details : undefined}
173 />
174 );
175}
176
177function uploadStatusSuffix(upload: AttachmentUploadState | undefined): string | null {
178 if (upload?.status === "uploading") return formatAttachmentUploadProgress(upload.progress);
179 if (upload?.status === "failed") return "upload failed";
180 return null;
181}
182
183function attachmentTooltip(
184 attachment: ComposerImageAttachment | ComposerFileAttachment,
185 upload: AttachmentUploadState | undefined,
186): string {
187 const lines = [attachment.name, formatAttachmentSize(attachment.sizeBytes)];
188 if (upload?.status === "failed") lines.push("", upload.reason);
189 return lines.join("\n");
190}
191
192function ImageContextChip(props: {
193 record: ComposerImageAttachment;
194 upload: AttachmentUploadState | undefined;
195}) {
196 const actions = use(ComposerContextActionsContext);
197 return (
198 <Tooltip>
199 <TooltipTrigger
200 render={
201 <ImageChipButton
202 name={props.record.name}
203 previewUrl={props.record.previewUrl}
204 size={formatAttachmentSize(props.record.sizeBytes)}
205 suffix={uploadStatusSuffix(props.upload)}
206 onClick={() => actions.expandImage(props.record.id)}
207 />
208 }
209 />
210 <TooltipPopup side="top" className="whitespace-pre-wrap">
211 {attachmentTooltip(props.record, props.upload)}
212 </TooltipPopup>
213 </Tooltip>
214 );
215}
216
217function FileContextChip(props: {
218 record: ComposerFileAttachment;
219 upload: AttachmentUploadState | undefined;
220}) {
221 const actions = use(ComposerContextActionsContext);
222 const { resolvedTheme } = useTheme();
223 const needsReattach = composerFileNeedsReattach(props.record);
224 const suffix = needsReattach ? "attach again" : uploadStatusSuffix(props.upload);
225 const size = formatAttachmentSize(props.record.sizeBytes);
226 const isVideo = videoMimeType(props.record) !== null;
227 return (
228 <FileChip
229 name={props.record.name}
230 size={size}
231 isVideo={isVideo}
232 theme={resolvedTheme}
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; kind: ContextChipKind }) {
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 kind={props.kind}
263 onOpen={actions.openPullRequest}
264 />
265 );
266}
267
268function previewAnnotationTooltip(annotation: PreviewAnnotationPayload): string {
269 const lines = [annotation.pageTitle?.trim() || annotation.pageUrl];
270 if (annotation.comment.trim()) lines.push("", annotation.comment.trim());
271 const targets: string[] = [];
272 const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
273 if (annotation.elements.length > 0) targets.push(plural(annotation.elements.length, "element"));
274 if (annotation.regions.length > 0) targets.push(plural(annotation.regions.length, "region"));
275 if (annotation.strokes.length > 0) targets.push(plural(annotation.strokes.length, "drawing"));
276 if (annotation.styleChanges.length > 0) {
277 targets.push(plural(annotation.styleChanges.length, "style change"));
278 }
279 if (targets.length > 0) lines.push("", targets.join(", "));
280 return lines.join("\n");
281}
282
283function ComposerReviewCommentDetails({ comment }: { comment: ReviewCommentContext }) {
284 return (
285 <div className="space-y-2 overflow-hidden rounded-lg border border-border/70 bg-background/70 p-3">
286 <div className="space-y-1">
287 <div className="truncate text-xs font-medium text-foreground">{comment.filePath}</div>
288 <div className="text-secondary-label text-2xs">
289 {comment.sectionTitle} · {comment.rangeLabel}
290 </div>
291 </div>
292 {comment.text.trim() ? <ChatMarkdown text={comment.text.trim()} cwd={undefined} /> : null}
293 {comment.diff.trim() ? (
294 <div className="flex h-64 min-h-0 flex-col overflow-hidden rounded-md border border-border">
295 <ReadOnlySourcePreview name="review.diff" text={comment.diff} />
296 </div>
297 ) : null}
298 </div>
299 );
300}
301
302function ComposerPreviewAnnotationDetails({
303 annotation,
304 screenshot,
305}: {
306 annotation: PreviewAnnotationPayload;
307 screenshot: ComposerImageAttachment | undefined;
308}) {
309 const summary = previewAnnotationTooltip(annotation);
310 // The draft drops the annotation's own data URL and keeps the crop as an image.
311 const screenshotUrl = annotation.screenshot?.dataUrl || screenshot?.previewUrl;
312 return (
313 <div className="overflow-hidden rounded-lg border border-border/70 bg-background/70">
314 {screenshotUrl ? (
315 <img
316 src={screenshotUrl}
317 alt="Annotated preview crop"
318 className="max-h-64 w-full border-border/70 border-b bg-muted object-contain"
319 />
320 ) : (
321 <div className="border-border/70 border-b bg-muted/40 px-3 py-2 text-secondary-label text-xs">
322 Screenshot unavailable
323 </div>
324 )}
325 <div className="whitespace-pre-wrap wrap-break-word px-3 py-2.5 text-sm text-foreground">
326 {summary}
327 </div>
328 </div>
329 );
330}
331
332function UnresolvedContextChip(props: { label: string }) {
333 return (
334 <UnresolvedChip
335 label={props.label}
336 tooltip="This context is no longer available. Remove it or attach it again."
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 kind={PULL_REQUEST_CHIP_KINDS[pullRequestState]}
399 />
400 );
401 }
402 return (
403 <ContextChip
404 icon={isPullRequest ? <PullRequestGlyph.pullRequest /> : <MessageCircleIcon />}
405 label={reviewCommentContextLabel(entry.record)}
406 kindLabel={isPullRequest ? pullRequestContextKindLabel(entry.record) : "Review comment"}
407 details={<ComposerReviewCommentDetails comment={entry.record} />}
408 detailsMode={definition.capabilities.details}
409 kind={isPullRequest ? PULL_REQUEST_CHIP_KINDS[pullRequestState] : "review-comment"}
410 />
411 );
412 },
413 },
414 {
415 kind: "preview-annotation",
416 canRender: (entry) => entry.kind === "preview-annotation",
417 render: (entry, context, definition) =>
418 entry.kind === "preview-annotation" ? (
419 <ContextChip
420 icon={<MousePointerClickIcon />}
421 label={previewAnnotationContextLabel(entry.record)}
422 kindLabel="Preview annotation"
423 details={
424 <ComposerPreviewAnnotationDetails
425 annotation={entry.record}
426 screenshot={entry.screenshot}
427 />
428 }
429 detailsMode={definition.capabilities.details}
430 kind="preview-annotation"
431 />
432 ) : (
433 <UnresolvedContextChip label={context.label} />
434 ),
435 },
436 {
437 kind: "thread",
438 canRender: (entry) => entry.kind === "thread",
439 render: (entry, context) =>
440 entry.kind === "thread" ? (
441 <ThreadContextChip record={entry.record} />
442 ) : (
443 <UnresolvedContextChip label={context.label} />
444 ),
445 },
446 ],
447 fallback: (_kind, _entry, context) => <UnresolvedContextChip label={context.label} />,
448});
449
450/** Compact chip for one reference. Unknown kinds and missing records use the registry fallback. */
451export function ComposerContextReferenceChip(props: {
452 kind: string;
453 contextId: string;
454 label: string;
455}): ReactElement {
456 const records = use(ComposerContextRecordsContext);
457 return composerContextPresentationRegistry.render(props.kind, records.get(props.contextId), {
458 label: props.label,
459 });
460}