@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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