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

composerContextPresentation.tsx

507 lines17.4 KB

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