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