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

main
tsx 572 lines 20.6 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import {
3 canEditPullRequestMaintainerEdits,
4 maintainerEditsChoiceInForce,
5 type MaintainerEditsChoice,
6 } from "@t3tools/client-runtime/pull-request-editing";
7 import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
8 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9 import type {
10 EnvironmentId,
11 PullRequestAction,
12 PullRequestDetail,
13 PullRequestMergeMethod,
14 PullRequestRef,
15 ScopedThreadRef,
16 } from "@t3tools/contracts";
17 import {
18 ArrowUpRightIcon,
19 BookOpenIcon,
20 CopyIcon,
21 HammerIcon,
22 LinkIcon,
23 MessageCircleQuestionIcon,
24 MoreHorizontalIcon,
25 RotateCcwIcon,
26 ScrollTextIcon,
27 Trash2Icon,
28 } from "lucide-react";
29 import { Branch, msg, T, useGT, useMessages } from "gt-react";
30 import { useId, useState } from "react";
31
32 import { useOpenLink } from "~/browser/useOpenLink";
33 import { m } from "~/i18n/messages";
34
35 import { shortcutLabelForCommand } from "~/keybindings";
36 import { pullRequestEnvironment } from "~/state/pullRequests";
37 import { primaryServerKeybindingsAtom } from "~/state/server";
38 import { useAtomCommand } from "~/state/use-atom-command";
39 import { Button } from "../ui/button";
40 import {
41 Menu,
42 MenuCheckboxItem,
43 MenuItem,
44 MenuPopup,
45 MenuRadioGroup,
46 MenuRadioItem,
47 MenuSeparator,
48 MenuShortcut,
49 MenuTrigger,
50 } from "../ui/menu";
51 import { RefreshIcon } from "../ui/refresh-icon";
52 import { toastManager } from "../ui/toast";
53 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
54 import { ActOnEnvironmentPicker, type PerformPullRequestAction } from "./PullRequestDetailActions";
55 import {
56 PULL_REQUEST_MERGE_METHOD_LABELS,
57 pullRequestActionMenuHasGroup,
58 readableFailure,
59 } from "./pullRequestDetail.logic";
60 import { PullRequestGlyph } from "./pullRequestIcons";
61 import type { PickableEnvironment } from "./pullRequestProjectAssignment.logic";
62 import { PullRequestThreadLinks } from "./PullRequestThreadLinks";
63 import { useInlineActionConfirm } from "./useInlineActionConfirm";
64
65 import { changeRequestTermKind } from "./changeRequestTerm";
66
67 /** Everything else the reader can do with the pull request, behind the header's overflow button. */
68 export function PullRequestActionsMenu({
69 environmentId,
70 reference,
71 pullRequestKey,
72 detail,
73 terminology,
74 threadRef,
75 linkThreadRef,
76 onThreadPickerOpenChange,
77 refreshing,
78 refreshFromHost,
79 handoff,
80 attachesToComposer,
81 askAboutPullRequest,
82 explainPullRequest,
83 canFixFindings,
84 startFixFindings,
85 handoffLabels,
86 canWriteGuide,
87 guideRunning,
88 guideWritten,
89 writeGuide,
90 pickableEnvironments,
91 actingEnvironmentId,
92 onActingEnvironmentChange,
93 can,
94 autoMergeArmed,
95 showsDraftToggle,
96 showsMergeNow,
97 showsAutoMerge,
98 showsMergeMethods,
99 allowedMergeMethods,
100 selectedMergeMethod,
101 onSelectMergeMethod,
102 showsDeleteBranch,
103 environmentConnected,
104 canWriteSourceControl,
105 onMaintainerEditsSaved,
106 confirmDeleteBranch,
107 pendingAction,
108 perform,
109 openOnHostText,
110 copyReference,
111 }: {
112 environmentId: EnvironmentId;
113 reference: PullRequestRef;
114 pullRequestKey: string;
115 detail: Pick<
116 PullRequestDetail,
117 | "url"
118 | "state"
119 | "isDraft"
120 | "headBranch"
121 | "capabilities"
122 | "viewerPermissions"
123 | "maintainerCanModify"
124 | "observedAt"
125 >;
126 terminology: ChangeRequestTerminology;
127 threadRef: ScopedThreadRef | null;
128 linkThreadRef: ScopedThreadRef | null;
129 onThreadPickerOpenChange: (open: boolean) => void;
130 refreshing: boolean;
131 refreshFromHost: () => Promise<void>;
132 handoff: string | null;
133 attachesToComposer: boolean;
134 askAboutPullRequest: () => void;
135 explainPullRequest: () => void;
136 canFixFindings: boolean;
137 startFixFindings: () => void;
138 handoffLabels: { readonly fixFindings: string };
139 canWriteGuide: boolean;
140 guideRunning: boolean;
141 guideWritten: boolean;
142 writeGuide: () => void;
143 pickableEnvironments: ReadonlyArray<PickableEnvironment>;
144 actingEnvironmentId: EnvironmentId;
145 onActingEnvironmentChange: (environmentId: EnvironmentId) => void;
146 can: (action: PullRequestAction) => boolean;
147 autoMergeArmed: boolean;
148 showsDraftToggle: boolean;
149 showsMergeNow: boolean;
150 showsAutoMerge: boolean;
151 showsMergeMethods: boolean;
152 allowedMergeMethods: ReadonlyArray<PullRequestMergeMethod>;
153 selectedMergeMethod: PullRequestMergeMethod;
154 onSelectMergeMethod: (method: PullRequestMergeMethod) => void;
155 showsDeleteBranch: boolean;
156 environmentConnected: boolean;
157 canWriteSourceControl: boolean;
158 onMaintainerEditsSaved: () => void;
159 confirmDeleteBranch: () => Promise<void>;
160 pendingAction: PullRequestAction | null;
161 perform: PerformPullRequestAction;
162 openOnHostText: string;
163 copyReference: (value: string, failureTitle: string) => void;
164 }) {
165 const gt = useGT();
166 const openLink = useOpenLink(threadRef);
167 const resolve = useMessages();
168 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
169 const inlineConfirm = useInlineActionConfirm(pullRequestKey);
170 const actionPending = pendingAction !== null;
171 const maintainerEditsHintId = useId();
172 const updatePullRequest = useAtomCommand(pullRequestEnvironment.update, {
173 reportFailure: false,
174 });
175 const [maintainerEditsChoice, setMaintainerEditsChoice] = useState<MaintainerEditsChoice | null>(
176 null,
177 );
178 const [maintainerEditsSaving, setMaintainerEditsSaving] = useState(false);
179 const maintainerEditsChoiceKept = maintainerEditsChoiceInForce(
180 maintainerEditsChoice,
181 pullRequestKey,
182 detail.observedAt,
183 maintainerEditsSaving,
184 );
185 if (maintainerEditsChoiceKept !== maintainerEditsChoice) {
186 setMaintainerEditsChoice(maintainerEditsChoiceKept);
187 }
188 const maintainerCanModify = maintainerEditsChoiceKept?.value ?? detail.maintainerCanModify;
189 const canSaveMaintainerEdits =
190 canWriteSourceControl && environmentConnected && !maintainerEditsSaving;
191 const saveMaintainerEdits = async (value: boolean) => {
192 if (!canSaveMaintainerEdits) return;
193 const previousChoice = maintainerEditsChoice;
194 setMaintainerEditsChoice({ key: pullRequestKey, observedAt: detail.observedAt, value });
195 setMaintainerEditsSaving(true);
196 const result = await updatePullRequest({
197 environmentId,
198 input: { ...reference, maintainerCanModify: value },
199 });
200 setMaintainerEditsSaving(false);
201 if (result._tag === "Failure") {
202 setMaintainerEditsChoice(previousChoice);
203 toastManager.add({
204 type: "error",
205 title: m(msg("Could not save maintainer access")),
206 description: readableFailure(squashAtomCommandFailure(result), m(msg("Try again."))),
207 });
208 return;
209 }
210 onMaintainerEditsSaved();
211 };
212 return (
213 <Menu>
214 <Tooltip>
215 <TooltipTrigger
216 render={
217 <MenuTrigger
218 render={
219 <Button
220 aria-label={
221 refreshing
222 ? gt(
223 "Refreshing {term, select, mr {merge request} cr {change request} other {pull request}}",
224 { term: changeRequestTermKind(terminology) },
225 )
226 : gt(
227 "More {term, select, mr {merge request} cr {change request} other {pull request}} actions",
228 { term: changeRequestTermKind(terminology) },
229 )
230 }
231 size="icon-xs"
232 variant="ghost-muted"
233 />
234 }
235 >
236 {refreshing ? (
237 <RefreshIcon refreshing size="md" />
238 ) : (
239 <MoreHorizontalIcon className="size-4" />
240 )}
241 </MenuTrigger>
242 }
243 />
244 <TooltipPopup>
245 {refreshing
246 ? gt(
247 "Refreshing {term, select, mr {merge request} cr {change request} other {pull request}}",
248 { term: changeRequestTermKind(terminology) },
249 )
250 : gt(
251 "More {term, select, mr {merge request} cr {change request} other {pull request}} actions",
252 { term: changeRequestTermKind(terminology) },
253 )}
254 </TooltipPopup>
255 </Tooltip>
256 <MenuPopup align="end" side="bottom">
257 <PullRequestThreadLinks
258 display="menu-item"
259 environmentId={environmentId}
260 reference={reference}
261 url={detail.url}
262 threadRef={linkThreadRef}
263 onPickerOpenChange={onThreadPickerOpenChange}
264 />
265 <MenuItem disabled={refreshing} onClick={() => void refreshFromHost()}>
266 <RefreshIcon size="sm" refreshing={refreshing} />
267 <T context="verb, menu item">Refresh</T>
268 </MenuItem>
269 <MenuItem disabled={handoff !== null} onClick={askAboutPullRequest}>
270 <MessageCircleQuestionIcon className="mt-1 size-3.5 shrink-0 self-start" />
271 <span className="flex min-w-0 flex-col">
272 <span>{handoff === "ask" ? gt("Opening...") : gt("Ask a question")}</span>
273 <span className="text-xs text-muted-foreground">
274 {attachesToComposer
275 ? gt(
276 "Adds the {term, select, mr {merge request} cr {change request} other {pull request}} to this thread's composer.",
277 { term: changeRequestTermKind(terminology) },
278 )
279 : gt(
280 "Opens a thread that knows which {term, select, mr {merge request} cr {change request} other {pull request}} you mean.",
281 {
282 term: changeRequestTermKind(terminology),
283 },
284 )}
285 </span>
286 </span>
287 </MenuItem>
288 <MenuItem disabled={handoff !== null} onClick={explainPullRequest}>
289 <BookOpenIcon className="mt-1 size-3.5 shrink-0 self-start" />
290 <span className="flex min-w-0 flex-col">
291 <span>
292 {handoff === "explain"
293 ? gt("Opening...")
294 : gt("Explain this {term, select, mr {MR} cr {change request} other {PR}}", {
295 term: changeRequestTermKind(terminology),
296 })}
297 </span>
298 <span className="text-xs text-muted-foreground">
299 <T>A walk through the diff and what to read closely.</T>
300 </span>
301 </span>
302 </MenuItem>
303 <MenuItem disabled={handoff !== null || !canFixFindings} onClick={startFixFindings}>
304 <HammerIcon className="size-3.5" />
305 {handoff === "findings" ? gt("Preparing...") : handoffLabels.fixFindings}
306 </MenuItem>
307 {canWriteGuide ? (
308 <MenuItem disabled={guideRunning} onClick={writeGuide}>
309 <ScrollTextIcon className="size-3.5" />
310 {guideRunning
311 ? gt("Writing guide...")
312 : !guideWritten
313 ? gt("Write guide")
314 : gt("Rewrite guide")}
315 </MenuItem>
316 ) : null}
317 {pickableEnvironments.length > 0 ? (
318 <ActOnEnvironmentPicker
319 environments={pickableEnvironments}
320 value={actingEnvironmentId}
321 onChange={onActingEnvironmentChange}
322 disabled={handoff !== null}
323 />
324 ) : null}
325 <MenuSeparator />
326 {canEditPullRequestMaintainerEdits(detail) ? (
327 <>
328 <MenuCheckboxItem
329 variant="icon"
330 checked={maintainerCanModify === true}
331 disabled={!canSaveMaintainerEdits}
332 closeOnClick={false}
333 aria-label={gt("Allow edits from maintainers")}
334 aria-describedby={maintainerEditsHintId}
335 onCheckedChange={(value) => void saveMaintainerEdits(value)}
336 >
337 <span className="flex max-w-xs flex-col gap-0.5">
338 <span>
339 <T>Allow edits from maintainers</T>
340 </span>
341 <span id={maintainerEditsHintId} className="text-xs text-muted-foreground">
342 <T>
343 Maintainers can push to this branch. If your fork has workflows, this can also
344 give access to its secrets.
345 </T>
346 </span>
347 {maintainerEditsSaving ? (
348 <span role="status" className="text-xs text-muted-foreground">
349 <T>Saving…</T>
350 </span>
351 ) : null}
352 </span>
353 </MenuCheckboxItem>
354 <MenuSeparator />
355 </>
356 ) : null}
357 {detail.state === "open" ? (
358 <>
359 {showsDraftToggle ? (
360 <MenuItem
361 disabled={actionPending}
362 onClick={() => void perform(detail.isDraft ? "ready" : "draft")}
363 >
364 {detail.isDraft ? (
365 <PullRequestGlyph.pullRequest className="size-3.5" />
366 ) : (
367 <PullRequestGlyph.draft className="size-3.5" />
368 )}
369 {detail.isDraft ? gt("Ready for review") : gt("Convert to draft")}
370 </MenuItem>
371 ) : null}
372 {showsMergeNow ? (
373 <MenuItem
374 closeOnClick={inlineConfirm.isArmed("merge")}
375 aria-label={inlineConfirm.isArmed("merge") ? gt("Confirm merge?") : gt("Merge now")}
376 disabled={actionPending}
377 {...inlineConfirm.props("merge", () => void perform("merge", selectedMergeMethod))}
378 >
379 <PullRequestGlyph.merged className="size-3.5" />
380 {inlineConfirm.isArmed("merge") ? gt("Confirm merge?") : gt("Merge now")}
381 </MenuItem>
382 ) : null}
383 {autoMergeArmed && can("disable-auto-merge") ? (
384 <MenuItem disabled={actionPending} onClick={() => void perform("disable-auto-merge")}>
385 <PullRequestGlyph.merged className="size-3.5" />
386 <T>Disable auto-merge</T>
387 </MenuItem>
388 ) : showsAutoMerge ? (
389 <MenuItem
390 closeOnClick={inlineConfirm.isArmed("enable-auto-merge")}
391 aria-label={
392 inlineConfirm.isArmed("enable-auto-merge")
393 ? gt("Confirm auto-merge?")
394 : gt("Enable auto-merge")
395 }
396 disabled={actionPending}
397 {...inlineConfirm.props(
398 "enable-auto-merge",
399 () => void perform("enable-auto-merge", selectedMergeMethod),
400 )}
401 >
402 <PullRequestGlyph.merged className="size-3.5" />
403 {inlineConfirm.isArmed("enable-auto-merge")
404 ? gt("Confirm auto-merge?")
405 : gt("Enable auto-merge")}
406 </MenuItem>
407 ) : null}
408 {showsMergeMethods ? (
409 <>
410 {showsDraftToggle || showsMergeNow || showsAutoMerge ? <MenuSeparator /> : null}
411 <MenuRadioGroup
412 value={selectedMergeMethod}
413 onValueChange={(method) => onSelectMergeMethod(method as PullRequestMergeMethod)}
414 >
415 {allowedMergeMethods.map((method) => (
416 <MenuRadioItem
417 key={method}
418 value={method}
419 disabled={actionPending}
420 closeOnClick
421 >
422 <span className="flex min-w-0 items-center gap-2">
423 <PullRequestGlyph.merged className="size-3.5" />
424 <span>{resolve(PULL_REQUEST_MERGE_METHOD_LABELS[method])}</span>
425 </span>
426 </MenuRadioItem>
427 ))}
428 </MenuRadioGroup>
429 </>
430 ) : null}
431 {pullRequestActionMenuHasGroup(
432 showsDraftToggle,
433 showsAutoMerge || showsMergeNow,
434 showsMergeMethods,
435 ) ? (
436 <MenuSeparator />
437 ) : null}
438 </>
439 ) : null}
440 <MenuItem onClick={(event) => void openLink(detail.url, { event }).catch(console.error)}>
441 <ArrowUpRightIcon className="size-3.5" />
442 {openOnHostText}
443 </MenuItem>
444 <MenuItem
445 onClick={() =>
446 copyReference(
447 detail.url,
448 resolve(
449 msg("Failed to copy {term, select, mr {MR} cr {change request} other {PR}} link", {
450 term: changeRequestTermKind(terminology),
451 }),
452 ),
453 )
454 }
455 >
456 <LinkIcon className="size-3.5" />
457 <T>Copy link</T>
458 <MenuShortcut>
459 {shortcutLabelForCommand(keybindings, "thread.copyReference")}
460 </MenuShortcut>
461 </MenuItem>
462 <MenuItem
463 onClick={() =>
464 copyReference(
465 `#${reference.number}`,
466 resolve(
467 msg(
468 "Failed to copy {term, select, mr {MR} cr {change request} other {PR}} number",
469 { term: changeRequestTermKind(terminology) },
470 ),
471 ),
472 )
473 }
474 >
475 <CopyIcon className="size-3.5" />
476 <T>
477 Copy{" "}
478 <Branch branch={changeRequestTermKind(terminology)} mr="MR" cr="change request">
479 PR
480 </Branch>{" "}
481 number
482 </T>
483 <MenuShortcut>
484 {shortcutLabelForCommand(keybindings, "pullRequest.copyNumber")}
485 </MenuShortcut>
486 </MenuItem>
487 {detail.state === "open" && can("close") ? (
488 <>
489 <MenuSeparator />
490 <MenuItem
491 closeOnClick={inlineConfirm.isArmed("close")}
492 aria-label={
493 inlineConfirm.isArmed("close")
494 ? gt("Confirm close?")
495 : gt(
496 "Close {term, select, mr {merge request} cr {change request} other {pull request}}",
497 { term: changeRequestTermKind(terminology) },
498 )
499 }
500 variant="destructive"
501 disabled={actionPending}
502 {...inlineConfirm.props("close", () => void perform("close"))}
503 >
504 <PullRequestGlyph.closed className="size-3.5" />
505 {inlineConfirm.isArmed("close")
506 ? gt("Confirm close?")
507 : gt(
508 "Close {term, select, mr {merge request} cr {change request} other {pull request}}",
509 { term: changeRequestTermKind(terminology) },
510 )}
511 </MenuItem>
512 </>
513 ) : detail.state === "closed" && can("reopen") ? (
514 <>
515 <MenuSeparator />
516 <MenuItem disabled={actionPending} onClick={() => void perform("reopen")}>
517 <PullRequestGlyph.reopen className="size-3.5" />
518 <T>
519 Reopen{" "}
520 <Branch
521 branch={changeRequestTermKind(terminology)}
522 mr="merge request"
523 cr="change request"
524 >
525 pull request
526 </Branch>
527 </T>
528 </MenuItem>
529 </>
530 ) : detail.state === "merged" && can("revert") ? (
531 <>
532 <MenuSeparator />
533 <MenuItem
534 closeOnClick={inlineConfirm.isArmed("revert")}
535 aria-label={
536 inlineConfirm.isArmed("revert") ? gt("Confirm revert?") : gt("Revert changes")
537 }
538 variant={inlineConfirm.isArmed("revert") ? "destructive" : "default"}
539 disabled={actionPending}
540 {...inlineConfirm.props("revert", () => void perform("revert"))}
541 >
542 <RotateCcwIcon className="size-3.5" />
543 {inlineConfirm.isArmed("revert") ? gt("Confirm revert?") : gt("Revert changes")}
544 </MenuItem>
545 </>
546 ) : null}
547 {showsDeleteBranch ? (
548 <>
549 <MenuSeparator />
550 <MenuItem
551 variant="destructive"
552 disabled={actionPending || !environmentConnected}
553 onClick={() => void confirmDeleteBranch()}
554 >
555 <Trash2Icon className="mt-1 size-3.5 shrink-0 self-start" />
556 <span className="flex min-w-0 flex-col">
557 <span>
558 {pendingAction === "delete-branch"
559 ? gt("Deleting branch...")
560 : gt("Delete branch")}
561 </span>
562 <span className="truncate text-xs text-muted-foreground">
563 {environmentConnected ? detail.headBranch : gt("Reconnect to delete this branch")}
564 </span>
565 </span>
566 </MenuItem>
567 </>
568 ) : null}
569 </MenuPopup>
570 </Menu>
571 );
572 }