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

composerContextPresentation.tsx

654 lines21.0 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, plural, part } 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;
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 <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 );
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: props.record.name }}, ${{ size }}`
307 : gt`File attachment, ${{ 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: props.record.name }} was not saved with this draft. Attach it again to send it.`
318 : attachmentTooltip(props.record, props.upload, messages)
319 }
320 />
321 );
323​
324function PullRequestContextChip(props: { record: ReviewCommentContext; kind: ContextChipKind }) {
325 const actions = use(ComposerContextActionsContext);
326 const messages = useMessages();
327 const metadata = props.record.pullRequest;
328 if (metadata === undefined) return null;
329 return (
330 <PullRequestChip
331 metadata={metadata}
332 environmentId={actions.environmentId}
333 label={reviewCommentContextLabel(props.record, messages)}
334 kindLabel={pullRequestContextKindLabel(props.record, messages)}
335 kind={props.kind}
336 onOpen={actions.openPullRequest}
337 />
338 );
340​
341function ReviewCommentContextChip(props: {
342 record: ReviewCommentContext;
343 isPullRequest: boolean;
344 detailsMode: ContextPresentationCapability["details"];
345 kind: ContextChipKind;
346}) {
347 const messages = useMessages();
348 return (
349 <ContextChip
350 icon={props.isPullRequest ? <PullRequestGlyph.pullRequest /> : <MessageCircleIcon />}
351 label={reviewCommentContextLabel(props.record, messages)}
352 kindLabel={
353 props.isPullRequest
354 ? pullRequestContextKindLabel(props.record, messages)
355 : msg("Review comment")
356 }
357 details={<ComposerReviewCommentDetails comment={props.record} />}
358 detailsMode={props.detailsMode}
359 kind={props.kind}
360 />
361 );
363​
364function previewAnnotationTooltip(
365 annotation: PreviewAnnotationPayload,
366 resolve: MessageResolver,
367): string {
368 const lines = [annotation.pageTitle?.trim() || annotation.pageUrl];
369 if (annotation.comment.trim()) lines.push("", annotation.comment.trim());
370 const targets: string[] = [];
371 const { elements, regions, strokes, styleChanges } = annotation;
372 if (elements.length > 0) {
373 targets.push(
374 resolve(
375 msg`${plural(
376 { count: elements.length },
377 {
378 one: part`${{ count: elements.length }} element`,
379 other: part`${{ count: elements.length }} elements`,
380 },
381 )}`,
382 ),
383 );
384 }
385 if (regions.length > 0) {
386 targets.push(
387 resolve(
388 msg`${plural(
389 { count: regions.length },
390 {
391 one: part`${{ count: regions.length }} region`,
392 other: part`${{ count: regions.length }} regions`,
393 },
394 )}`,
395 ),
396 );
397 }
398 if (strokes.length > 0) {
399 targets.push(
400 resolve(
401 msg`${plural(
402 { count: strokes.length },
403 {
404 one: part`${{ count: strokes.length }} drawing`,
405 other: part`${{ count: strokes.length }} drawings`,
406 },
407 )}`,
408 ),
409 );
410 }
411 if (styleChanges.length > 0) {
412 targets.push(
413 resolve(
414 msg`${plural(
415 { count: styleChanges.length },
416 {
417 one: part`${{ count: styleChanges.length }} style change`,
418 other: part`${{ count: styleChanges.length }} style changes`,
419 },
420 )}`,
421 ),
422 );
423 }
424 if (targets.length > 0) lines.push("", targets.join(", "));
425 return lines.join("\n");
427​
428function ComposerReviewCommentDetails({ comment }: { comment: ReviewCommentContext }) {
429 const messages = useMessages();
430 return (
431 <div className="space-y-2 overflow-hidden rounded-lg border border-border/70 bg-background/70 p-3">
432 <div className="space-y-1">
433 <div className="truncate text-xs font-medium text-foreground">{comment.filePath}</div>
434 <div className="text-secondary-label text-2xs">
435 {reviewCommentSectionText(comment.sectionTitle, messages)} ·{" "}
436 {reviewCommentRangeText(comment.rangeLabel, messages)}
437 </div>
438 </div>
439 {comment.text.trim() ? <ChatMarkdown text={comment.text.trim()} cwd={undefined} /> : null}
440 {comment.diff.trim() ? (
441 <div className="flex h-64 min-h-0 flex-col overflow-hidden rounded-md border border-border">
442 <ReadOnlySourcePreview name="review.diff" text={comment.diff} />
443 </div>
444 ) : null}
445 </div>
446 );
448​
449function PreviewAnnotationContextChip(props: {
450 annotation: PreviewAnnotationPayload;
451 screenshot: ComposerImageAttachment | undefined;
452 detailsMode: ContextPresentationCapability["details"];
453}) {
454 const m = useMessages();
455 return (
456 <ContextChip
457 icon={<MousePointerClickIcon />}
458 label={previewAnnotationContextLabel(props.annotation, m)}
459 kindLabel={msg("Preview annotation")}
460 details={
461 <ComposerPreviewAnnotationDetails
462 annotation={props.annotation}
463 screenshot={props.screenshot}
464 />
465 }
466 detailsMode={props.detailsMode}
467 kind="preview-annotation"
468 />
469 );
471​
472function ComposerPreviewAnnotationDetails({
473 annotation,
474 screenshot,
475}: {
476 annotation: PreviewAnnotationPayload;
477 screenshot: ComposerImageAttachment | undefined;
478}) {
479 const gt = useGT();
480 const m = useMessages();
481 const summary = previewAnnotationTooltip(annotation, m);
482 const screenshotUrl = annotation.screenshot?.dataUrl || screenshot?.previewUrl;
483 return (
484 <div className="overflow-hidden rounded-lg border border-border/70 bg-background/70">
485 {screenshotUrl ? (
486 <img
487 src={screenshotUrl}
488 alt={gt`Annotated preview crop`}
489 className="max-h-64 w-full border-border/70 border-b bg-muted object-contain"
490 />
491 ) : (
492 <div className="border-border/70 border-b bg-muted/40 px-3 py-2 text-secondary-label text-xs">
493 <T>Screenshot unavailable</T>
494 </div>
495 )}
496 <div className="whitespace-pre-wrap wrap-break-word px-3 py-2.5 text-sm text-foreground">
497 {summary}
498 </div>
499 </div>
500 );
502​
503function ComposerThreadContextChip(props: { record: ThreadContextRecord }) {
504 const { environmentId } = use(ComposerContextActionsContext);
505 const linkedEnvironments = useLinkedEnvironments(environmentId);
506 return (
507 <ThreadContextChip
508 record={props.record}
509 unreadable={
510 environmentId !== null &&
511 props.record.environmentId !== environmentId &&
512 !linkedEnvironments.has(props.record.environmentId)
513 }
514 />
515 );
517​
518function UnresolvedContextChip(props: { label: string }) {
519 const gt = useGT();
520 return (
521 <UnresolvedChip
522 label={props.label}
523 tooltip={gt`This context is no longer available. Remove it or attach it again.`}
524 />
525 );
527​
528interface ComposerContextRenderContext {
529 label: string;
531​
532const composerContextPresentationRegistry = createContextPresentationRegistry<
533 ComposerDraftContextRecord,
534 ComposerContextRenderContext,
535 ReactElement
536>({
537 requiredKinds: [
538 "image",
539 "file",
540 "terminal",
541 "review-comment",
542 "preview-annotation",
543 "thread",
544 "environment",
545 ],
546 handlers: [
547 {
548 kind: "terminal",
549 canRender: (entry) => entry.kind === "terminal",
550 render: (entry, context, definition) =>
551 entry.kind === "terminal" ? (
552 <ComposerPendingTerminalContextChip
553 context={entry.record}
554 detailsMode={definition.capabilities.details}
555 />
556 ) : (
557 <UnresolvedContextChip label={context.label} />
558 ),
559 },
560 {
561 kind: "image",
562 canRender: (entry) => entry.kind === "image",
563 render: (entry, context) =>
564 entry.kind === "image" ? (
565 <ImageContextChip record={entry.record} upload={entry.upload} />
566 ) : (
567 <UnresolvedContextChip label={context.label} />
568 ),
569 },
570 {
571 kind: "file",
572 canRender: (entry) => entry.kind === "file",
573 render: (entry, context) =>
574 entry.kind === "file" ? (
575 <FileContextChip record={entry.record} upload={entry.upload} />
576 ) : (
577 <UnresolvedContextChip label={context.label} />
578 ),
579 },
580 {
581 kind: "review-comment",
582 canRender: (entry) => entry.kind === "review-comment",
583 render: (entry, context, definition) => {
584 if (entry.kind !== "review-comment") {
585 return <UnresolvedContextChip label={context.label} />;
586 }
587 const isPullRequest = isPullRequestSummaryContext(entry.record);
588 const pullRequestState = pullRequestContextDisplayState(entry.record) ?? "unknown";
589 if (isPullRequest && entry.record.pullRequest !== undefined) {
590 return (
591 <PullRequestContextChip
592 record={entry.record}
593 kind={PULL_REQUEST_CHIP_KINDS[pullRequestState]}
594 />
595 );
596 }
597 return (
598 <ReviewCommentContextChip
599 record={entry.record}
600 isPullRequest={isPullRequest}
601 detailsMode={definition.capabilities.details}
602 kind={isPullRequest ? PULL_REQUEST_CHIP_KINDS[pullRequestState] : "review-comment"}
603 />
604 );
605 },
606 },
607 {
608 kind: "preview-annotation",
609 canRender: (entry) => entry.kind === "preview-annotation",
610 render: (entry, context, definition) =>
611 entry.kind === "preview-annotation" ? (
612 <PreviewAnnotationContextChip
613 annotation={entry.record}
614 screenshot={entry.screenshot}
615 detailsMode={definition.capabilities.details}
616 />
617 ) : (
618 <UnresolvedContextChip label={context.label} />
619 ),
620 },
621 {
622 kind: "thread",
623 canRender: (entry) => entry.kind === "thread",
624 render: (entry, context) =>
625 entry.kind === "thread" ? (
626 <ComposerThreadContextChip record={entry.record} />
627 ) : (
628 <UnresolvedContextChip label={context.label} />
629 ),
630 },
631 {
632 kind: "environment",
633 canRender: (entry) => entry.kind === "environment",
634 render: (entry, context) =>
635 entry.kind === "environment" ? (
636 <EnvironmentContextChip record={entry.record} />
637 ) : (
638 <UnresolvedContextChip label={context.label} />
639 ),
640 },
641 ],
642 fallback: (_kind, _entry, context) => <UnresolvedContextChip label={context.label} />,
643});
644​
645export function ComposerContextReferenceChip(props: {
646 kind: string;
647 contextId: string;
648 label: string;
649}): ReactElement {
650 const records = use(ComposerContextRecordsContext);
651 return composerContextPresentationRegistry.render(props.kind, records.get(props.contextId), {
652 label: props.label,
653 });