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

main
tsx 499 lines 17.5 KB
Raw
1 import type {
2 EnvironmentId,
3 PullRequestActor,
4 PullRequestDiffSide,
5 PullRequestRef,
6 PullRequestReviewPosition,
7 PullRequestReviewThread,
8 PullRequestThreadCommentsResult,
9 PullRequestThreadComment,
10 } from "@t3tools/contracts";
11 import {
12 HammerIcon,
13 MessageSquareIcon,
14 MessageSquarePlusIcon,
15 Trash2Icon,
16 CircleCheckIcon,
17 CircleIcon,
18 } from "lucide-react";
19 import { T, useGT } from "gt-react";
20 import { type ReactNode, useRef, useState } from "react";
21 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
22
23 import { RelativeTime } from "~/components/RelativeTime";
24 import { cn } from "~/lib/utils";
25 import { SpeechTextField, TextFieldSpeechControls } from "~/speech/useTextFieldSpeech";
26
27 import { Button } from "../ui/button";
28 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
29 import { PullRequestEditButton } from "./PullRequestEditButton";
30 import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
31 import {
32 editPullRequestThreadComment,
33 mergePullRequestThreadComments,
34 visibleBody,
35 } from "./pullRequestDetail.logic";
36 import { PullRequestActorAvatar, PullRequestActorLabel } from "./pullRequestPresentation";
37 import { PullRequestMarkdown } from "./PullRequestMarkdown";
38 import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
39 import { PullRequestReactionBar } from "./PullRequestReactions";
40 import type { PendingReviewComment } from "./pullRequestReviewStore";
41 import {
42 PullRequestMarkdownTextarea,
43 type PullRequestCompletionScope,
44 } from "./PullRequestMarkdownTextarea";
45
46 const CARD_CLASS =
47 "mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 text-sm shadow-sm";
48
49 function submitKeys(input: {
50 readonly value: string;
51 readonly pending: boolean;
52 readonly allowEmpty?: boolean;
53 readonly onSubmit: () => void;
54 readonly onCancel?: (() => void) | undefined;
55 }) {
56 return (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
57 if (event.key === "Escape" && input.onCancel) {
58 event.preventDefault();
59 input.onCancel();
60 }
61 if (isCommentSubmitShortcut(event, input.value, input.pending, input.allowEmpty)) {
62 event.preventDefault();
63 input.onSubmit();
64 }
65 };
66 }
67
68 export function toViewerSide(side: PullRequestDiffSide) {
69 return side === "left" ? ("deletions" as const) : ("additions" as const);
70 }
71
72 export function getReviewPositionAnchor(position: PullRequestReviewPosition): {
73 line: number;
74 side: PullRequestDiffSide;
75 } {
76 switch (position.kind) {
77 case "added":
78 return { line: position.newLine, side: "right" };
79 case "deleted":
80 return { line: position.oldLine, side: "left" };
81 case "context":
82 return {
83 line: position.side === "left" ? position.oldLine : position.newLine,
84 side: position.side,
85 };
86 }
87 }
88
89 export function PendingReviewCommentCard({
90 comment,
91 onRemove,
92 }: {
93 comment: PendingReviewComment;
94 onRemove: () => void;
95 }) {
96 const gt = useGT();
97 return (
98 <div
99 className={cn(CARD_CLASS, "border-dashed")}
100 contentEditable={false}
101 onPointerDown={(event) => event.stopPropagation()}
102 >
103 <div className="flex items-center gap-2 text-xs text-muted-foreground">
104 <MessageSquareIcon className="size-3.5" />
105 <span>
106 <T>Pending. Sent when you submit the review</T>
107 </span>
108 <Button
109 size="icon-xs"
110 variant="ghost"
111 className="ml-auto"
112 aria-label={gt("Discard this comment")}
113 onClick={onRemove}
114 >
115 <Trash2Icon className="size-3.5" />
116 </Button>
117 </div>
118 <p className="mt-2 whitespace-pre-wrap leading-relaxed">{comment.body}</p>
119 </div>
120 );
121 }
122
123 /** The conversations on one diff line. Resolved ones hide behind their authors' avatars. */
124 export function InlineReviewThreads({
125 threads,
126 renderThread,
127 }: {
128 threads: ReadonlyArray<PullRequestReviewThread>;
129 renderThread: (thread: PullRequestReviewThread, hidden: boolean) => ReactNode;
130 }) {
131 const gt = useGT();
132 const [shown, setShown] = useState<ReadonlySet<string>>(() => new Set());
133 // A conversation seen open stays shown once resolved, so it does not vanish under the reader.
134 const open = threads.filter((thread) => !thread.isResolved);
135 if (open.some((thread) => !shown.has(thread.id))) {
136 setShown(new Set([...shown, ...open.map((thread) => thread.id)]));
137 }
138 const resolved = threads.filter((thread) => thread.isResolved);
139 const expanded = resolved.every((thread) => shown.has(thread.id));
140 const authors = new Map<string, PullRequestActor | null>();
141 for (const comment of resolved.flatMap((thread) => thread.comments)) {
142 authors.set(comment.author?.login ?? "ghost", comment.author);
143 }
144 if (authors.size === 0) authors.set("ghost", null);
145 const label = gt(
146 "{count, plural, =1 {Resolved conversation} other {{count} resolved conversations}}",
147 { count: resolved.length },
148 );
149 return (
150 <>
151 {resolved.length > 0 ? (
152 <Tooltip>
153 <TooltipTrigger
154 render={
155 <button
156 type="button"
157 data-resolved-threads
158 aria-label={label}
159 aria-expanded={expanded}
160 // Sits on the commented line, which is the row above this annotation.
161 className="absolute right-3 bottom-full flex h-[var(--diffs-line-height,20px)] cursor-pointer items-center -space-x-1 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
162 contentEditable={false}
163 onPointerDown={(event) => event.stopPropagation()}
164 onClick={() =>
165 setShown(new Set((expanded ? open : threads).map((thread) => thread.id)))
166 }
167 />
168 }
169 >
170 {[...authors].slice(0, 3).map(([login, author]) => (
171 <PullRequestActorAvatar
172 key={login}
173 actor={author}
174 className="ring-1 ring-background"
175 />
176 ))}
177 </TooltipTrigger>
178 <TooltipPopup side="left">{label}</TooltipPopup>
179 </Tooltip>
180 ) : null}
181 {threads.map((thread) => renderThread(thread, thread.isResolved && !shown.has(thread.id)))}
182 </>
183 );
184 }
185
186 export function ReviewThreadCard({
187 thread,
188 workspaceRoot,
189 canReply,
190 canResolve,
191 canReact,
192 environmentId,
193 reference,
194 completionScope,
195 pending,
196 fixPending,
197 fixLabel,
198 onFix,
199 onAddToChat,
200 onReply,
201 onLoadMore,
202 canEditComment,
203 onEditComment,
204 onToggleResolved,
205 onReacted,
206 hidden,
207 }: {
208 thread: PullRequestReviewThread;
209 workspaceRoot: string;
210 canReply: boolean;
211 canResolve: boolean;
212 canReact: boolean;
213 environmentId: EnvironmentId;
214 reference: PullRequestRef;
215 completionScope: PullRequestCompletionScope | null;
216 pending: boolean;
217 fixPending?: boolean;
218 fixLabel?: string;
219 onFix?: () => void;
220 /**
221 * Absent where there is no composer beside the panel to add the conversation to. Handed the
222 * thread with every comment the reader has loaded, not only the first page.
223 */
224 onAddToChat?: (thread: PullRequestReviewThread) => void;
225 onReply: (body: string) => Promise<boolean>;
226 onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;
227 canEditComment: (comment: PullRequestThreadComment) => boolean;
228 onEditComment: (commentId: string, body: string) => Promise<boolean>;
229 onToggleResolved: () => void;
230 onReacted: () => void;
231 /** Set on a diff line. Hidden draws nothing but stays mounted, so an unsent reply survives. */
232 hidden?: boolean;
233 }) {
234 const gt = useGT();
235 const [expanded, setExpanded] = useState(hidden !== undefined || !thread.isResolved);
236 const [replying, setReplying] = useState(false);
237 const [reply, setReply] = useState("");
238 const [editingId, setEditingId] = useState<string | null>(null);
239 const [savingEdit, setSavingEdit] = useState(false);
240 const sendingRef = useRef(false);
241 const replyRef = useRef<HTMLTextAreaElement>(null);
242 const [loadedPage, setLoadedPage] = useState<
243 (PullRequestThreadCommentsResult & { readonly threadId: string }) | null
244 >(null);
245 const [loadingMore, setLoadingMore] = useState(false);
246 const currentPage = loadedPage?.threadId === thread.id ? loadedPage : null;
247 const comments = mergePullRequestThreadComments(thread.comments, currentPage?.comments ?? []);
248 const nextCommentsCursor =
249 currentPage === null ? (thread.nextCommentsCursor ?? null) : currentPage.nextCursor;
250 const commentCount = thread.commentCount ?? comments.length;
251
252 const saveEdit = async (commentId: string, body: string) => {
253 if (savingEdit) return;
254 setSavingEdit(true);
255 const saved = await onEditComment(commentId, body);
256 setSavingEdit(false);
257 if (saved) {
258 setLoadedPage((previous) =>
259 previous?.threadId === thread.id
260 ? {
261 ...previous,
262 comments: editPullRequestThreadComment(previous.comments, commentId, body),
263 }
264 : previous,
265 );
266 setEditingId(null);
267 }
268 };
269
270 const send = async (text: string) => {
271 const trimmed = text.trim();
272 if (trimmed.length === 0 || pending || sendingRef.current) return;
273 sendingRef.current = true;
274 const result = await settlePromise(() => onReply(trimmed));
275 sendingRef.current = false;
276 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
277 if (!result.value) return;
278 // Replies return no comment; retain loaded data and reopen pagination for a later read.
279 setLoadedPage((previous) =>
280 previous?.threadId === thread.id
281 ? {
282 ...previous,
283 nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null,
284 }
285 : previous,
286 );
287 setReply("");
288 setReplying(false);
289 };
290 const loadMore = async () => {
291 if (nextCommentsCursor === null || loadingMore) return;
292 setLoadingMore(true);
293 const result = await settlePromise(() => onLoadMore(nextCommentsCursor));
294 setLoadingMore(false);
295 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
296 const page = result.value;
297 if (page === null) return;
298 setLoadedPage((previous) => ({
299 threadId: thread.id,
300 comments: mergePullRequestThreadComments(
301 previous?.threadId === thread.id ? previous.comments : [],
302 page.comments,
303 ),
304 nextCursor: page.nextCursor,
305 }));
306 };
307
308 if (hidden) return null;
309
310 return (
311 <div
312 className={cn(CARD_CLASS, !expanded && "py-1")}
313 contentEditable={false}
314 onPointerDown={(event) => event.stopPropagation()}
315 >
316 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
317 {thread.isResolved ? (
318 <CircleCheckIcon className="size-3.5 text-success-foreground" />
319 ) : (
320 <CircleIcon className="size-3.5" />
321 )}
322 <button
323 type="button"
324 className="hover:text-foreground"
325 aria-expanded={expanded}
326 onClick={() => setExpanded((current) => !current)}
327 >
328 {thread.isResolved
329 ? gt("Resolved", { $context: "review thread state" })
330 : gt("Open", { $context: "review thread state" })}{" "}
331 ·{" "}
332 {gt("{count, plural, one {{count} comment} other {{count} comments}}", {
333 count: commentCount,
334 })}
335 </button>
336 {thread.isOutdated ? <span>outdated</span> : null}
337 {onFix ? (
338 <Button
339 size="compact"
340 variant="ghost"
341 className="ml-auto"
342 disabled={pending || fixPending}
343 onClick={onFix}
344 >
345 <HammerIcon className="size-3" />
346 {fixPending ? gt("Preparing...") : (fixLabel ?? gt("Fix in a thread"))}
347 </Button>
348 ) : null}
349 {onAddToChat && comments.some((comment) => visibleBody(comment.body) !== null) ? (
350 <Button
351 size="compact"
352 variant="ghost"
353 className={onFix ? undefined : "ml-auto"}
354 onClick={() => onAddToChat({ ...thread, comments })}
355 >
356 <MessageSquarePlusIcon className="size-3" />
357 <T>Add to chat</T>
358 </Button>
359 ) : null}
360 {canResolve ? (
361 <Button
362 size="compact"
363 variant="ghost"
364 className={onFix || onAddToChat ? undefined : "ml-auto"}
365 disabled={pending}
366 onClick={onToggleResolved}
367 >
368 {thread.isResolved ? gt("Unresolve") : gt("Resolve")}
369 </Button>
370 ) : null}
371 </div>
372
373 {expanded ? (
374 <>
375 <div className="mt-2 space-y-3">
376 {comments.map((comment) => (
377 <article key={comment.id} className="group min-w-0">
378 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
379 <PullRequestActorLabel actor={comment.author} />
380 <span>
381 <RelativeTime timestamp={comment.createdAt} />
382 </span>
383 <PullRequestReactionBar
384 className="ml-auto justify-end"
385 reactions={comment.reactions ?? []}
386 canReact={canReact}
387 subjectId={comment.id}
388 environmentId={environmentId}
389 reference={reference}
390 onRefresh={onReacted}
391 />
392 </div>
393 {editingId === comment.id ? (
394 <PullRequestMarkdownEditor
395 className="mt-1"
396 value={comment.body}
397 cwd={workspaceRoot}
398 environmentId={environmentId}
399 completionScope={completionScope}
400 label={gt("Edit comment")}
401 saving={savingEdit}
402 onSave={(body) => void saveEdit(comment.id, body)}
403 onCancel={() => setEditingId(null)}
404 />
405 ) : (
406 <div className="mt-1 flex items-start gap-1">
407 <PullRequestMarkdown
408 className="min-w-0 flex-1 text-sm"
409 text={comment.body}
410 cwd={workspaceRoot}
411 environmentId={environmentId}
412 />
413 {canEditComment(comment) ? (
414 <PullRequestEditButton
415 aria-label={gt("Edit comment")}
416 onClick={() => setEditingId(comment.id)}
417 />
418 ) : null}
419 </div>
420 )}
421 </article>
422 ))}
423 </div>
424 {nextCommentsCursor !== null ? (
425 <div className="mt-2">
426 <Button
427 size="xs"
428 variant="ghost"
429 disabled={loadingMore}
430 onClick={() => void loadMore()}
431 >
432 {loadingMore ? gt("Loading...") : gt("Load more comments")}
433 </Button>
434 </div>
435 ) : null}
436
437 {canReply ? (
438 replying ? (
439 <SpeechTextField
440 environmentId={environmentId}
441 projectId={reference.projectId}
442 ownerKey={JSON.stringify(["pr-reply", environmentId, reference, thread.id])}
443 text={reply}
444 textareaRef={replyRef}
445 onTextChange={setReply}
446 disabled={pending}
447 >
448 {(speech) => (
449 <div className="mt-2">
450 <PullRequestMarkdownTextarea
451 ref={replyRef}
452 readOnly={speech.freezesEditor}
453 autoFocus
454 size="sm"
455 completionScope={completionScope}
456 value={reply}
457 placeholder={gt("Reply", { $context: "noun, placeholder" })}
458 aria-label={gt("Reply to this conversation")}
459 onValueChange={setReply}
460 onKeyDown={submitKeys({
461 value: reply,
462 pending,
463 allowEmpty: speech.blocksSubmission,
464 onSubmit: () => speech.submitAfterDictation((text) => void send(text)),
465 onCancel: () =>
466 speech.state.phase === "idle" ? setReplying(false) : speech.cancel(),
467 })}
468 />
469 <div className="mt-2 flex flex-wrap items-center justify-end gap-2">
470 <TextFieldSpeechControls speech={speech} disabled={pending} />
471 <Button size="xs" variant="ghost" onClick={() => setReplying(false)}>
472 <T>Cancel</T>
473 </Button>
474 <Button
475 size="xs"
476 disabled={
477 speech.preparing ||
478 pending ||
479 (!speech.blocksSubmission && reply.trim().length === 0)
480 }
481 onClick={() => speech.submitAfterDictation((text) => void send(text))}
482 >
483 <T context="verb, button">Reply</T>
484 </Button>
485 </div>
486 </div>
487 )}
488 </SpeechTextField>
489 ) : (
490 <Button size="xs" variant="ghost" className="mt-2" onClick={() => setReplying(true)}>
491 <T context="verb, button">Reply</T>
492 </Button>
493 )
494 ) : null}
495 </>
496 ) : null}
497 </div>
498 );
499 }