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