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 ChatAttachment,
6 ComposerContextId,
7 EnvironmentContextRecord,
8 EnvironmentId,
9 PreviewAnnotationPayload,
10 ThreadContextRecord,
11} from "@t3tools/contracts";
12import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
13import { videoMimeType } from "@t3tools/shared/video";
14import { MessageCircleIcon, MousePointerClickIcon } from "lucide-react";
15import { createContext, type ReactElement, type ReactNode, use } from "react";
16import { msg, T, useGT, useMessages } from "gt-react";
17import type { MessageResolver } from "../i18n/messages";
18import { ComposerContextActionsContext } from "./composerContextActions";
19
20import type { ComposerFileAttachment, ComposerImageAttachment } from "~/composerDraftStore";
21import { composerFileNeedsReattach } from "~/composerDraftStore";
22import { useTheme } from "~/hooks/useTheme";
23import {
24 attachmentUploadFailureText,
25 type AttachmentUploadState,
26} from "~/lib/attachmentUploadState";
27import { useAttachmentUploadProgress } from "~/hooks/useAttachmentUploadProgress";
28import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
29import {
30 fileContextReference,
31 imageContextReference,
32 isPullRequestSummaryContext,
33 previewAnnotationContextId,
34 previewAnnotationContextLabel,
35 pullRequestContextDisplayState,
36 pullRequestContextKindLabel,
37 reviewCommentContextId,
38 reviewCommentContextLabel,
39 reviewCommentRangeText,
40 reviewCommentSectionText,
41 terminalContextReference,
42 uploadedAttachmentContextRecord,
43} from "~/lib/composerContextRecords";
44import type { TerminalContextDraft } from "~/lib/terminalContext";
45import type { ReviewCommentContext } from "~/reviewCommentContext";
46import { isQueuedFileAttachment, isQueuedImageAttachment } from "./chat/queuedMessageEdit";
47import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
48import { EnvironmentContextChip } from "./EnvironmentContextChip";
49import { ThreadContextChip } from "./ThreadContextChip";
50import { useLinkedEnvironments } from "~/state/peerLinks";
51import {
52 createContextPresentationRegistry,
53 type ContextPresentationCapability,
54} from "./contextPresentationRegistry";
55import type { ContextChipKind } from "./ContextChip";
56import {
57 ContextChipPopover,
58 ContextChipShell,
59 FileChip,
60 ImageChipButton,
61 PULL_REQUEST_CHIP_KINDS,
62 PullRequestChip,
63 UnresolvedChip,
64} from "./contextChipParts";
65import { SharedTooltipTrigger } from "./ui/shared-tooltip";
66
67export interface ComposerImageContextAttachment extends Omit<ComposerImageAttachment, "file"> {
68 readonly file: File | null;
69 readonly uploadedAttachmentId?: string | undefined;
70}
71
72export type ComposerDraftContextRecord =
73 | { kind: "terminal"; record: TerminalContextDraft }
74 | { kind: "review-comment"; record: ReviewCommentContext }
75 | {
76 kind: "preview-annotation";
77 record: PreviewAnnotationPayload;
78 screenshot?: ComposerImageAttachment | undefined;
79 }
80 | {
81 kind: "image";
82 record: ComposerImageContextAttachment;
83 upload?: AttachmentUploadState | undefined;
84 contextId?: ComposerContextId | undefined;
85 }
86 | {
87 kind: "file";
88 record: ComposerFileAttachment;
89 upload?: AttachmentUploadState | undefined;
90 contextId?: ComposerContextId | undefined;
91 }
92 | { kind: "thread"; record: ThreadContextRecord }
93 | { kind: "environment"; record: EnvironmentContextRecord };
94
95export {
96 ComposerContextActionsContext,
97 type ComposerContextActions,
98} from "./composerContextActions";
99
100export type ComposerDraftContextRecords = ReadonlyMap<string, ComposerDraftContextRecord>;
101
102export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new Map();
103
104export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) {
105 if (entry.kind !== "image" && entry.kind !== "file") return null;
106 return uploadedAttachmentContextRecord(entry.record, entry.upload, entry.contextId);
107}
108
109export const ComposerContextRecordsContext = createContext<ComposerDraftContextRecords>(
110 EMPTY_COMPOSER_CONTEXT_RECORDS,
111);
112
113export function composerContextRecordsFromDraft(input: {
114 terminalContexts: ReadonlyArray<TerminalContextDraft>;
115 reviewComments?: ReadonlyArray<ReviewCommentContext>;
116 previewAnnotations?: ReadonlyArray<PreviewAnnotationPayload>;
117 threadContexts?: ReadonlyArray<ThreadContextRecord>;
118 environmentContexts?: ReadonlyArray<EnvironmentContextRecord>;
119 images?: ReadonlyArray<ComposerImageAttachment>;
120 files?: ReadonlyArray<ComposerFileAttachment>;
121 existingAttachments?:
122 | ReadonlyArray<{
123 readonly attachment: ChatAttachment;
124 readonly url: string | null;
125 readonly contextIds?: ReadonlyArray<ComposerContextId> | undefined;
126 }>
127 | undefined;
128 environmentId?: EnvironmentId | undefined;
129 uploadsByImageId?: Readonly<Record<string, AttachmentUploadState>>;
130}): ComposerDraftContextRecords {
131 const records = new Map<string, ComposerDraftContextRecord>();
132 for (const entry of input.existingAttachments ?? []) {
133 for (const contextId of entry.contextIds ?? []) {
134 if (isQueuedImageAttachment(entry.attachment)) {
135 records.set(contextId, {
136 kind: "image",
137 contextId,
138 record: {
139 ...entry.attachment,
140 previewUrl: entry.url ?? "",
141 file: null,
142 uploadedAttachmentId: entry.attachment.id,
143 },
144 });
145 } else if (isQueuedFileAttachment(entry.attachment)) {
146 records.set(contextId, {
147 kind: "file",
148 contextId,
149 record: {
150 ...entry.attachment,
151 file: null,
152 uploadedAttachmentId: entry.attachment.id,
153 ...(input.environmentId ? { uploadEnvironmentId: input.environmentId } : {}),
154 },
155 });
156 }
157 }
158 }
159 for (const record of input.images ?? []) {
160 records.set(imageContextReference(record).contextId, {
161 kind: "image",
162 record,
163 upload: input.uploadsByImageId?.[record.id],
164 });
165 }
166 for (const record of input.files ?? []) {
167 records.set(fileContextReference(record).contextId, {
168 kind: "file",
169 record,
170 upload: input.uploadsByImageId?.[record.id],
171 });
172 }
173 for (const record of input.terminalContexts) {
174 records.set(terminalContextReference(record).contextId, { kind: "terminal", record });
175 }
176 for (const record of input.reviewComments ?? []) {
177 records.set(reviewCommentContextId(record.id), { kind: "review-comment", record });
178 }
179 const imagesById = new Map((input.images ?? []).map((image) => [image.id, image]));
180 for (const record of input.previewAnnotations ?? []) {
181 records.set(previewAnnotationContextId(record.id), {
182 kind: "preview-annotation",
183 record,
184 screenshot: imagesById.get(record.id),
185 });
186 }
187 for (const record of input.threadContexts ?? []) {
188 records.set(record.contextId, { kind: "thread", record });
189 }
190 for (const record of input.environmentContexts ?? []) {
191 records.set(record.contextId, { kind: "environment", record });
192 }
193 return records;
194}
195
196function ContextChip(props: {
197 icon: ReactElement;
198 label: string;
199 kindLabel: string;
200 details: ReactNode;
201 detailsMode: ContextPresentationCapability["details"];
202 kind: ContextChipKind;
203}) {
204 const m = useMessages();
205 const kindLabel = m(props.kindLabel);
206 if (props.detailsMode === "popover") {
207 return (
208 <ContextChipPopover
209 kind={props.kind}
210 icon={props.icon}
211 label={props.label}
212 accessibleLabel={kindLabel + ", " + props.label}
213 >
214 {props.details}
215 </ContextChipPopover>
216 );
217 }
218 return (
219 <ContextChipShell
220 kind={props.kind}
221 icon={props.icon}
222 label={props.label}
223 aria-label={props.detailsMode === "tooltip" ? `${kindLabel}, ${props.label}` : undefined}
224 tooltip={props.detailsMode === "tooltip" ? props.details : undefined}
225 />
226 );
227}
228
229function useUploadStatusSuffix(
230 key: string,
231 upload: AttachmentUploadState | undefined,
232): string | null {
233 const gt = useGT();
234 const progress = useAttachmentUploadProgress(key, upload);
235 if (upload?.status === "failed") return gt("upload failed");
236 return progress;
237}
238
239function attachmentTooltip(
240 attachment: Pick<ComposerImageContextAttachment | ComposerFileAttachment, "name" | "sizeBytes">,
241 upload: AttachmentUploadState | undefined,
242 resolve: MessageResolver,
243): string {
244 const lines = [attachment.name, formatAttachmentSize(attachment.sizeBytes, resolve)];
245 if (upload?.status === "failed") lines.push("", attachmentUploadFailureText(upload, resolve));
246 return lines.join("\n");
247}
248
249function ImageContextChip(props: {
250 record: ComposerImageContextAttachment;
251 upload: AttachmentUploadState | undefined;
252}) {
253 const actions = use(ComposerContextActionsContext);
254 const messages = useMessages();
255 const suffix = useUploadStatusSuffix(props.record.id, props.upload);
256 return (
257 <SharedTooltipTrigger
258 render={
259 <ImageChipButton
260 name={props.record.name}
261 previewUrl={props.record.previewUrl}
262 size={formatAttachmentSize(props.record.sizeBytes, messages)}
263 suffix={suffix}
264 onClick={() => actions.expandImage(props.record.id)}
265 />
266 }
267 label={attachmentTooltip(props.record, props.upload, messages)}
268 className="whitespace-pre-wrap"
269 />
270 );
271}
272
273function FileContextChip(props: {
274 record: ComposerFileAttachment;
275 upload: AttachmentUploadState | undefined;
276}) {
277 const gt = useGT();
278 const messages = useMessages();
279 const actions = use(ComposerContextActionsContext);
280 const { resolvedTheme } = useTheme();
281 const needsReattach = composerFileNeedsReattach(props.record);
282 const uploadSuffix = useUploadStatusSuffix(props.record.id, props.upload);
283 const suffix = needsReattach ? gt("attach again") : uploadSuffix;
284 const size = formatAttachmentSize(props.record.sizeBytes, messages);
285 const isVideo = videoMimeType(props.record) !== null;
286 return (
287 <FileChip
288 name={props.record.name}
289 svgPreview={
290 isSvgAttachment(props.record)
291 ? {
292 file: props.record.file,
293 environmentId: props.record.uploadEnvironmentId,
294 attachmentId: props.record.uploadedAttachmentId,
295 }
296 : undefined
297 }
298 size={size}
299 isVideo={isVideo}
300 theme={resolvedTheme}
301 error={props.upload?.status === "failed"}
302 unresolved={needsReattach}
303 suffix={suffix}
304 accessibleLabel={
305 isVideo && !needsReattach
306 ? gt("Preview video attachment, {name}, {size}", { name: props.record.name, size })
307 : gt("File attachment, {name}, {size}", { name: props.record.name, size })
308 }
309 onOpen={
310 !needsReattach
311 ? () =>
312 isVideo ? actions.expandVideo(props.record.id) : actions.openFile(props.record.id)
313 : undefined
314 }
315 tooltip={
316 needsReattach
317 ? gt("{name} was not saved with this draft. Attach it again to send it.", {
318 name: props.record.name,
319 })
320 : attachmentTooltip(props.record, props.upload, messages)
321 }
322 />
323 );
324}
325
326function PullRequestContextChip(props: { record: ReviewCommentContext; kind: ContextChipKind }) {
327 const actions = use(ComposerContextActionsContext);
328 const messages = useMessages();
329 const metadata = props.record.pullRequest;
330 if (metadata === undefined) return null;
331 return (
332 <PullRequestChip
333 metadata={metadata}
334 environmentId={actions.environmentId}
335 label={reviewCommentContextLabel(props.record, messages)}
336 kindLabel={pullRequestContextKindLabel(props.record, messages)}
337 kind={props.kind}
338 onOpen={actions.openPullRequest}
339 />
340 );
341}
342
343function ReviewCommentContextChip(props: {
344 record: ReviewCommentContext;
345 isPullRequest: boolean;
346 detailsMode: ContextPresentationCapability["details"];
347 kind: ContextChipKind;
348}) {
349 const messages = useMessages();
350 return (
351 <ContextChip
352 icon={props.isPullRequest ? <PullRequestGlyph.pullRequest /> : <MessageCircleIcon />}
353 label={reviewCommentContextLabel(props.record, messages)}
354 kindLabel={
355 props.isPullRequest
356 ? pullRequestContextKindLabel(props.record, messages)
357 : msg("Review comment")
358 }
359 details={<ComposerReviewCommentDetails comment={props.record} />}
360 detailsMode={props.detailsMode}
361 kind={props.kind}
362 />
363 );
364}
365
366function previewAnnotationTooltip(
367 annotation: PreviewAnnotationPayload,
368 resolve: MessageResolver,
369): string {
370 const lines = [annotation.pageTitle?.trim() || annotation.pageUrl];
371 if (annotation.comment.trim()) lines.push("", annotation.comment.trim());
372 const targets: string[] = [];
373 const { elements, regions, strokes, styleChanges } = annotation;
374 if (elements.length > 0) {
375 targets.push(
376 resolve(
377 msg("{count, plural, one {{count} element} other {{count} elements}}", {
378 count: elements.length,
379 }),
380 ),
381 );
382 }
383 if (regions.length > 0) {
384 targets.push(
385 resolve(
386 msg("{count, plural, one {{count} region} other {{count} regions}}", {
387 count: regions.length,
388 }),
389 ),
390 );
391 }
392 if (strokes.length > 0) {
393 targets.push(
394 resolve(
395 msg("{count, plural, one {{count} drawing} other {{count} drawings}}", {
396 count: strokes.length,
397 }),
398 ),
399 );
400 }
401 if (styleChanges.length > 0) {
402 targets.push(
403 resolve(
404 msg("{count, plural, one {{count} style change} other {{count} style changes}}", {
405 count: styleChanges.length,
406 }),
407 ),
408 );
409 }
410 if (targets.length > 0) lines.push("", targets.join(", "));
411 return lines.join("\n");
412}
413
414function ComposerReviewCommentDetails({ comment }: { comment: ReviewCommentContext }) {
415 const messages = useMessages();
416 return (
417 <div className="space-y-2 overflow-hidden rounded-lg border border-border/70 bg-background/70 p-3">
418 <div className="space-y-1">
419 <div className="truncate text-xs font-medium text-foreground">{comment.filePath}</div>
420 <div className="text-secondary-label text-2xs">
421 {reviewCommentSectionText(comment.sectionTitle, messages)} ·{" "}
422 {reviewCommentRangeText(comment.rangeLabel, messages)}
423 </div>
424 </div>
425 {comment.text.trim() ? <ChatMarkdown text={comment.text.trim()} cwd={undefined} /> : null}
426 {comment.diff.trim() ? (
427 <div className="flex h-64 min-h-0 flex-col overflow-hidden rounded-md border border-border">
428 <ReadOnlySourcePreview name="review.diff" text={comment.diff} />
429 </div>
430 ) : null}
431 </div>
432 );
433}
434
435function PreviewAnnotationContextChip(props: {
436 annotation: PreviewAnnotationPayload;
437 screenshot: ComposerImageAttachment | undefined;
438 detailsMode: ContextPresentationCapability["details"];
439}) {
440 const m = useMessages();
441 return (
442 <ContextChip
443 icon={<MousePointerClickIcon />}
444 label={previewAnnotationContextLabel(props.annotation, m)}
445 kindLabel={msg("Preview annotation")}
446 details={
447 <ComposerPreviewAnnotationDetails
448 annotation={props.annotation}
449 screenshot={props.screenshot}
450 />
451 }
452 detailsMode={props.detailsMode}
453 kind="preview-annotation"
454 />
455 );
456}
457
458function ComposerPreviewAnnotationDetails({
459 annotation,
460 screenshot,
461}: {
462 annotation: PreviewAnnotationPayload;
463 screenshot: ComposerImageAttachment | undefined;
464}) {
465 const gt = useGT();
466 const m = useMessages();
467 const summary = previewAnnotationTooltip(annotation, m);
468 const screenshotUrl = annotation.screenshot?.dataUrl || screenshot?.previewUrl;
469 return (
470 <div className="overflow-hidden rounded-lg border border-border/70 bg-background/70">
471 {screenshotUrl ? (
472 <img
473 src={screenshotUrl}
474 alt={gt("Annotated preview crop")}
475 className="max-h-64 w-full border-border/70 border-b bg-muted object-contain"
476 />
477 ) : (
478 <div className="border-border/70 border-b bg-muted/40 px-3 py-2 text-secondary-label text-xs">
479 <T>Screenshot unavailable</T>
480 </div>
481 )}
482 <div className="whitespace-pre-wrap wrap-break-word px-3 py-2.5 text-sm text-foreground">
483 {summary}
484 </div>
485 </div>
486 );
487}
488
489function ComposerThreadContextChip(props: { record: ThreadContextRecord }) {
490 const { environmentId } = use(ComposerContextActionsContext);
491 const linkedEnvironments = useLinkedEnvironments(environmentId);
492 return (
493 <ThreadContextChip
494 record={props.record}
495 unreadable={
496 environmentId !== null &&
497 props.record.environmentId !== environmentId &&
498 !linkedEnvironments.has(props.record.environmentId)
499 }
500 />
501 );
502}
503
504function UnresolvedContextChip(props: { label: string }) {
505 const gt = useGT();
506 return (
507 <UnresolvedChip
508 label={props.label}
509 tooltip={gt("This context is no longer available. Remove it or attach it again.")}
510 />
511 );
512}
513
514interface ComposerContextRenderContext {
515 label: string;
516}
517
518const composerContextPresentationRegistry = createContextPresentationRegistry<
519 ComposerDraftContextRecord,
520 ComposerContextRenderContext,
521 ReactElement
522>({
523 requiredKinds: [
524 "image",
525 "file",
526 "terminal",
527 "review-comment",
528 "preview-annotation",
529 "thread",
530 "environment",
531 ],
532 handlers: [
533 {
534 kind: "terminal",
535 canRender: (entry) => entry.kind === "terminal",
536 render: (entry, context, definition) =>
537 entry.kind === "terminal" ? (
538 <ComposerPendingTerminalContextChip
539 context={entry.record}
540 detailsMode={definition.capabilities.details}
541 />
542 ) : (
543 <UnresolvedContextChip label={context.label} />
544 ),
545 },
546 {
547 kind: "image",
548 canRender: (entry) => entry.kind === "image",
549 render: (entry, context) =>
550 entry.kind === "image" ? (
551 <ImageContextChip record={entry.record} upload={entry.upload} />
552 ) : (
553 <UnresolvedContextChip label={context.label} />
554 ),
555 },
556 {
557 kind: "file",
558 canRender: (entry) => entry.kind === "file",
559 render: (entry, context) =>
560 entry.kind === "file" ? (
561 <FileContextChip record={entry.record} upload={entry.upload} />
562 ) : (
563 <UnresolvedContextChip label={context.label} />
564 ),
565 },
566 {
567 kind: "review-comment",
568 canRender: (entry) => entry.kind === "review-comment",
569 render: (entry, context, definition) => {
570 if (entry.kind !== "review-comment") {
571 return <UnresolvedContextChip label={context.label} />;
572 }
573 const isPullRequest = isPullRequestSummaryContext(entry.record);
574 const pullRequestState = pullRequestContextDisplayState(entry.record) ?? "unknown";
575 if (isPullRequest && entry.record.pullRequest !== undefined) {
576 return (
577 <PullRequestContextChip
578 record={entry.record}
579 kind={PULL_REQUEST_CHIP_KINDS[pullRequestState]}
580 />
581 );
582 }
583 return (
584 <ReviewCommentContextChip
585 record={entry.record}
586 isPullRequest={isPullRequest}
587 detailsMode={definition.capabilities.details}
588 kind={isPullRequest ? PULL_REQUEST_CHIP_KINDS[pullRequestState] : "review-comment"}
589 />
590 );
591 },
592 },
593 {
594 kind: "preview-annotation",
595 canRender: (entry) => entry.kind === "preview-annotation",
596 render: (entry, context, definition) =>
597 entry.kind === "preview-annotation" ? (
598 <PreviewAnnotationContextChip
599 annotation={entry.record}
600 screenshot={entry.screenshot}
601 detailsMode={definition.capabilities.details}
602 />
603 ) : (
604 <UnresolvedContextChip label={context.label} />
605 ),
606 },
607 {
608 kind: "thread",
609 canRender: (entry) => entry.kind === "thread",
610 render: (entry, context) =>
611 entry.kind === "thread" ? (
612 <ComposerThreadContextChip record={entry.record} />
613 ) : (
614 <UnresolvedContextChip label={context.label} />
615 ),
616 },
617 {
618 kind: "environment",
619 canRender: (entry) => entry.kind === "environment",
620 render: (entry, context) =>
621 entry.kind === "environment" ? (
622 <EnvironmentContextChip record={entry.record} />
623 ) : (
624 <UnresolvedContextChip label={context.label} />
625 ),
626 },
627 ],
628 fallback: (_kind, _entry, context) => <UnresolvedContextChip label={context.label} />,
629});
630
631export function ComposerContextReferenceChip(props: {
632 kind: string;
633 contextId: string;
634 label: string;
635}): ReactElement {
636 const records = use(ComposerContextRecordsContext);
637 return composerContextPresentationRegistry.render(props.kind, records.get(props.contextId), {
638 label: props.label,
639 });
640}