Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerContextPresentation.tsx

643 lines20.8 KB

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 { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
57import {
58 ContextChipPopover,
59 ContextChipShell,
60 FileChip,
61 ImageChipButton,
62 PULL_REQUEST_CHIP_KINDS,
63 PullRequestChip,
64 UnresolvedChip,
65} from "./contextChipParts";
66​
67export interface ComposerImageContextAttachment extends Omit<ComposerImageAttachment, "file"> {
68 readonly file: File | null;
69 readonly uploadedAttachmentId?: string | undefined;
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);
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;
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 );
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;
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");
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 <Tooltip>
258 <TooltipTrigger
259 render={
260 <ImageChipButton
261 name={props.record.name}
262 previewUrl={props.record.previewUrl}
263 size={formatAttachmentSize(props.record.sizeBytes, messages)}
264 suffix={suffix}
265 onClick={() => actions.expandImage(props.record.id)}
266 />
267 }
268 />
269 <TooltipPopup side="top" className="whitespace-pre-wrap">
270 {attachmentTooltip(props.record, props.upload, messages)}
271 </TooltipPopup>
272 </Tooltip>
273 );
275​
276function FileContextChip(props: {
277 record: ComposerFileAttachment;
278 upload: AttachmentUploadState | undefined;
279}) {
280 const gt = useGT();
281 const messages = useMessages();
282 const actions = use(ComposerContextActionsContext);
283 const { resolvedTheme } = useTheme();
284 const needsReattach = composerFileNeedsReattach(props.record);
285 const uploadSuffix = useUploadStatusSuffix(props.record.id, props.upload);
286 const suffix = needsReattach ? gt("attach again") : uploadSuffix;
287 const size = formatAttachmentSize(props.record.sizeBytes, messages);
288 const isVideo = videoMimeType(props.record) !== null;
289 return (
290 <FileChip
291 name={props.record.name}
292 svgPreview={
293 isSvgAttachment(props.record)
294 ? {
295 file: props.record.file,
296 environmentId: props.record.uploadEnvironmentId,
297 attachmentId: props.record.uploadedAttachmentId,
298 }
299 : undefined
300 }
301 size={size}
302 isVideo={isVideo}
303 theme={resolvedTheme}
304 error={props.upload?.status === "failed"}
305 unresolved={needsReattach}
306 suffix={suffix}
307 accessibleLabel={
308 isVideo && !needsReattach
309 ? gt("Preview video attachment, {name}, {size}", { name: props.record.name, size })
310 : gt("File attachment, {name}, {size}", { name: props.record.name, size })
311 }
312 onOpen={
313 !needsReattach
314 ? () =>
315 isVideo ? actions.expandVideo(props.record.id) : actions.openFile(props.record.id)
316 : undefined
317 }
318 tooltip={
319 needsReattach
320 ? gt("{name} was not saved with this draft. Attach it again to send it.", {
321 name: props.record.name,
322 })
323 : attachmentTooltip(props.record, props.upload, messages)
324 }
325 />
326 );
328​
329function PullRequestContextChip(props: { record: ReviewCommentContext; kind: ContextChipKind }) {
330 const actions = use(ComposerContextActionsContext);
331 const messages = useMessages();
332 const metadata = props.record.pullRequest;
333 if (metadata === undefined) return null;
334 return (
335 <PullRequestChip
336 metadata={metadata}
337 environmentId={actions.environmentId}
338 label={reviewCommentContextLabel(props.record, messages)}
339 kindLabel={pullRequestContextKindLabel(props.record, messages)}
340 kind={props.kind}
341 onOpen={actions.openPullRequest}
342 />
343 );
345​
346function ReviewCommentContextChip(props: {
347 record: ReviewCommentContext;
348 isPullRequest: boolean;
349 detailsMode: ContextPresentationCapability["details"];
350 kind: ContextChipKind;
351}) {
352 const messages = useMessages();
353 return (
354 <ContextChip
355 icon={props.isPullRequest ? <PullRequestGlyph.pullRequest /> : <MessageCircleIcon />}
356 label={reviewCommentContextLabel(props.record, messages)}
357 kindLabel={
358 props.isPullRequest
359 ? pullRequestContextKindLabel(props.record, messages)
360 : msg("Review comment")
361 }
362 details={<ComposerReviewCommentDetails comment={props.record} />}
363 detailsMode={props.detailsMode}
364 kind={props.kind}
365 />
366 );
368​
369function previewAnnotationTooltip(
370 annotation: PreviewAnnotationPayload,
371 resolve: MessageResolver,
372): string {
373 const lines = [annotation.pageTitle?.trim() || annotation.pageUrl];
374 if (annotation.comment.trim()) lines.push("", annotation.comment.trim());
375 const targets: string[] = [];
376 const { elements, regions, strokes, styleChanges } = annotation;
377 if (elements.length > 0) {
378 targets.push(
379 resolve(
380 msg("{count, plural, one {{count} element} other {{count} elements}}", {
381 count: elements.length,
382 }),
383 ),
384 );
385 }
386 if (regions.length > 0) {
387 targets.push(
388 resolve(
389 msg("{count, plural, one {{count} region} other {{count} regions}}", {
390 count: regions.length,
391 }),
392 ),
393 );
394 }
395 if (strokes.length > 0) {
396 targets.push(
397 resolve(
398 msg("{count, plural, one {{count} drawing} other {{count} drawings}}", {
399 count: strokes.length,
400 }),
401 ),
402 );
403 }
404 if (styleChanges.length > 0) {
405 targets.push(
406 resolve(
407 msg("{count, plural, one {{count} style change} other {{count} style changes}}", {
408 count: styleChanges.length,
409 }),
410 ),
411 );
412 }
413 if (targets.length > 0) lines.push("", targets.join(", "));
414 return lines.join("\n");
416​
417function ComposerReviewCommentDetails({ comment }: { comment: ReviewCommentContext }) {
418 const messages = useMessages();
419 return (
420 <div className="space-y-2 overflow-hidden rounded-lg border border-border/70 bg-background/70 p-3">
421 <div className="space-y-1">
422 <div className="truncate text-xs font-medium text-foreground">{comment.filePath}</div>
423 <div className="text-secondary-label text-2xs">
424 {reviewCommentSectionText(comment.sectionTitle, messages)} ·{" "}
425 {reviewCommentRangeText(comment.rangeLabel, messages)}
426 </div>
427 </div>
428 {comment.text.trim() ? <ChatMarkdown text={comment.text.trim()} cwd={undefined} /> : null}
429 {comment.diff.trim() ? (
430 <div className="flex h-64 min-h-0 flex-col overflow-hidden rounded-md border border-border">
431 <ReadOnlySourcePreview name="review.diff" text={comment.diff} />
432 </div>
433 ) : null}
434 </div>
435 );
437​
438function PreviewAnnotationContextChip(props: {
439 annotation: PreviewAnnotationPayload;
440 screenshot: ComposerImageAttachment | undefined;
441 detailsMode: ContextPresentationCapability["details"];
442}) {
443 const m = useMessages();
444 return (
445 <ContextChip
446 icon={<MousePointerClickIcon />}
447 label={previewAnnotationContextLabel(props.annotation, m)}
448 kindLabel={msg("Preview annotation")}
449 details={
450 <ComposerPreviewAnnotationDetails
451 annotation={props.annotation}
452 screenshot={props.screenshot}
453 />
454 }
455 detailsMode={props.detailsMode}
456 kind="preview-annotation"
457 />
458 );
460​
461function ComposerPreviewAnnotationDetails({
462 annotation,
463 screenshot,
464}: {
465 annotation: PreviewAnnotationPayload;
466 screenshot: ComposerImageAttachment | undefined;
467}) {
468 const gt = useGT();
469 const m = useMessages();
470 const summary = previewAnnotationTooltip(annotation, m);
471 const screenshotUrl = annotation.screenshot?.dataUrl || screenshot?.previewUrl;
472 return (
473 <div className="overflow-hidden rounded-lg border border-border/70 bg-background/70">
474 {screenshotUrl ? (
475 <img
476 src={screenshotUrl}
477 alt={gt("Annotated preview crop")}
478 className="max-h-64 w-full border-border/70 border-b bg-muted object-contain"
479 />
480 ) : (
481 <div className="border-border/70 border-b bg-muted/40 px-3 py-2 text-secondary-label text-xs">
482 <T>Screenshot unavailable</T>
483 </div>
484 )}
485 <div className="whitespace-pre-wrap wrap-break-word px-3 py-2.5 text-sm text-foreground">
486 {summary}
487 </div>
488 </div>
489 );
491​
492function ComposerThreadContextChip(props: { record: ThreadContextRecord }) {
493 const { environmentId } = use(ComposerContextActionsContext);
494 const linkedEnvironments = useLinkedEnvironments(environmentId);
495 return (
496 <ThreadContextChip
497 record={props.record}
498 unreadable={
499 environmentId !== null &&
500 props.record.environmentId !== environmentId &&
501 !linkedEnvironments.has(props.record.environmentId)
502 }
503 />
504 );
506​
507function UnresolvedContextChip(props: { label: string }) {
508 const gt = useGT();
509 return (
510 <UnresolvedChip
511 label={props.label}
512 tooltip={gt("This context is no longer available. Remove it or attach it again.")}
513 />
514 );
516​
517interface ComposerContextRenderContext {
518 label: string;
520​
521const composerContextPresentationRegistry = createContextPresentationRegistry<
522 ComposerDraftContextRecord,
523 ComposerContextRenderContext,
524 ReactElement
525>({
526 requiredKinds: [
527 "image",
528 "file",
529 "terminal",
530 "review-comment",
531 "preview-annotation",
532 "thread",
533 "environment",
534 ],
535 handlers: [
536 {
537 kind: "terminal",
538 canRender: (entry) => entry.kind === "terminal",
539 render: (entry, context, definition) =>
540 entry.kind === "terminal" ? (
541 <ComposerPendingTerminalContextChip
542 context={entry.record}
543 detailsMode={definition.capabilities.details}
544 />
545 ) : (
546 <UnresolvedContextChip label={context.label} />
547 ),
548 },
549 {
550 kind: "image",
551 canRender: (entry) => entry.kind === "image",
552 render: (entry, context) =>
553 entry.kind === "image" ? (
554 <ImageContextChip record={entry.record} upload={entry.upload} />
555 ) : (
556 <UnresolvedContextChip label={context.label} />
557 ),
558 },
559 {
560 kind: "file",
561 canRender: (entry) => entry.kind === "file",
562 render: (entry, context) =>
563 entry.kind === "file" ? (
564 <FileContextChip record={entry.record} upload={entry.upload} />
565 ) : (
566 <UnresolvedContextChip label={context.label} />
567 ),
568 },
569 {
570 kind: "review-comment",
571 canRender: (entry) => entry.kind === "review-comment",
572 render: (entry, context, definition) => {
573 if (entry.kind !== "review-comment") {
574 return <UnresolvedContextChip label={context.label} />;
575 }
576 const isPullRequest = isPullRequestSummaryContext(entry.record);
577 const pullRequestState = pullRequestContextDisplayState(entry.record) ?? "unknown";
578 if (isPullRequest && entry.record.pullRequest !== undefined) {
579 return (
580 <PullRequestContextChip
581 record={entry.record}
582 kind={PULL_REQUEST_CHIP_KINDS[pullRequestState]}
583 />
584 );
585 }
586 return (
587 <ReviewCommentContextChip
588 record={entry.record}
589 isPullRequest={isPullRequest}
590 detailsMode={definition.capabilities.details}
591 kind={isPullRequest ? PULL_REQUEST_CHIP_KINDS[pullRequestState] : "review-comment"}
592 />
593 );
594 },
595 },
596 {
597 kind: "preview-annotation",
598 canRender: (entry) => entry.kind === "preview-annotation",
599 render: (entry, context, definition) =>
600 entry.kind === "preview-annotation" ? (
601 <PreviewAnnotationContextChip
602 annotation={entry.record}
603 screenshot={entry.screenshot}
604 detailsMode={definition.capabilities.details}
605 />
606 ) : (
607 <UnresolvedContextChip label={context.label} />
608 ),
609 },
610 {
611 kind: "thread",
612 canRender: (entry) => entry.kind === "thread",
613 render: (entry, context) =>
614 entry.kind === "thread" ? (
615 <ComposerThreadContextChip record={entry.record} />
616 ) : (
617 <UnresolvedContextChip label={context.label} />
618 ),
619 },
620 {
621 kind: "environment",
622 canRender: (entry) => entry.kind === "environment",
623 render: (entry, context) =>
624 entry.kind === "environment" ? (
625 <EnvironmentContextChip record={entry.record} />
626 ) : (
627 <UnresolvedContextChip label={context.label} />
628 ),
629 },
630 ],
631 fallback: (_kind, _entry, context) => <UnresolvedContextChip label={context.label} />,
632});
633​
634export function ComposerContextReferenceChip(props: {
635 kind: string;
636 contextId: string;
637 label: string;
638}): ReactElement {
639 const records = use(ComposerContextRecordsContext);
640 return composerContextPresentationRegistry.render(props.kind, records.get(props.contextId), {
641 label: props.label,
642 });