Open History to see the last commit
1import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
2import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3import { useCallback, useEffect, useMemo, useState } from "react";
4import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
5import { GitHubIcon } from "./Icons";
6import {
7 buildGitActionProgressStages,
8 buildMenuItems,
9 type GitActionIconName,
10 type GitActionMenuItem,
11 type GitQuickAction,
12 type DefaultBranchConfirmableAction,
13 requiresDefaultBranchConfirmation,
14 resolveDefaultBranchActionDialogCopy,
15 resolveQuickAction,
16 summarizeGitResult,
17} from "./GitActionsControl.logic";
18import { useAppSettings } from "~/appSettings";
19import { Button } from "~/components/ui/button";
20import { Checkbox } from "~/components/ui/checkbox";
21import {
22 Dialog,
23 DialogDescription,
24 DialogFooter,
25 DialogHeader,
26 DialogPanel,
27 DialogPopup,
28 DialogTitle,
29} from "~/components/ui/dialog";
30import { Group, GroupSeparator } from "~/components/ui/group";
31import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
32import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
33import { ScrollArea } from "~/components/ui/scroll-area";
34import { Textarea } from "~/components/ui/textarea";
35import { toastManager } from "~/components/ui/toast";
36import { openInPreferredEditor } from "~/editorPreferences";
37import {
38 gitBranchesQueryOptions,
39 gitInitMutationOptions,
40 gitMutationKeys,
41 gitPullMutationOptions,
42 gitRunStackedActionMutationOptions,
43 gitStatusQueryOptions,
44 invalidateGitQueries,
45} from "~/lib/gitReactQuery";
46import { resolvePathLinkTarget } from "~/terminal-links";
47import { readNativeApi } from "~/nativeApi";
48
49interface GitActionsControlProps {
50 gitCwd: string | null;
51 activeThreadId: ThreadId | null;
52}
53
54interface PendingDefaultBranchAction {
55 action: DefaultBranchConfirmableAction;
56 branchName: string;
57 includesCommit: boolean;
58 commitMessage?: string;
59 forcePushOnlyProgress: boolean;
60 onConfirmed?: () => void;
61 filePaths?: string[];
62}
63
64type GitActionToastId = ReturnType<typeof toastManager.add>;
65
66function getMenuActionDisabledReason({
67 item,
68 gitStatus,
69 isBusy,
70 hasOriginRemote,
71}: {
72 item: GitActionMenuItem;
73 gitStatus: GitStatusResult | null;
74 isBusy: boolean;
75 hasOriginRemote: boolean;
76}): string | null {
77 if (!item.disabled) return null;
78 if (isBusy) return "Git action in progress.";
79 if (!gitStatus) return "Git status is unavailable.";
80
81 const hasBranch = gitStatus.branch !== null;
82 const hasChanges = gitStatus.hasWorkingTreeChanges;
83 const hasOpenPr = gitStatus.pr?.state === "open";
84 const isAhead = gitStatus.aheadCount > 0;
85 const isBehind = gitStatus.behindCount > 0;
86
87 if (item.id === "commit") {
88 if (!hasChanges) {
89 return "Worktree is clean. Make changes before committing.";
90 }
91 return "Commit is currently unavailable.";
92 }
93
94 if (item.id === "push") {
95 if (!hasBranch) {
96 return "Detached HEAD: checkout a branch before pushing.";
97 }
98 if (hasChanges) {
99 return "Commit or stash local changes before pushing.";
100 }
101 if (isBehind) {
102 return "Branch is behind upstream. Pull/rebase before pushing.";
103 }
104 if (!gitStatus.hasUpstream && !hasOriginRemote) {
105 return 'Add an "origin" remote before pushing.';
106 }
107 if (!isAhead) {
108 return "No local commits to push.";
109 }
110 return "Push is currently unavailable.";
111 }
112
113 if (hasOpenPr) {
114 return "View PR is currently unavailable.";
115 }
116 if (!hasBranch) {
117 return "Detached HEAD: checkout a branch before creating a PR.";
118 }
119 if (hasChanges) {
120 return "Commit local changes before creating a PR.";
121 }
122 if (!gitStatus.hasUpstream && !hasOriginRemote) {
123 return 'Add an "origin" remote before creating a PR.';
124 }
125 if (!isAhead) {
126 return "No local commits to include in a PR.";
127 }
128 if (isBehind) {
129 return "Branch is behind upstream. Pull/rebase before creating a PR.";
130 }
131 return "Create PR is currently unavailable.";
132}
133
134const COMMIT_DIALOG_TITLE = "Commit changes";
135const COMMIT_DIALOG_DESCRIPTION =
136 "Review and confirm your commit. Leave the message blank to auto-generate one.";
137
138function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
139 if (icon === "commit") return <GitCommitIcon />;
140 if (icon === "push") return <CloudUploadIcon />;
141 return <GitHubIcon />;
142}
143
144function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
145 const iconClassName = "size-3.5";
146 if (quickAction.kind === "open_pr") return <GitHubIcon className={iconClassName} />;
147 if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
148 if (quickAction.kind === "run_action") {
149 if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
150 if (quickAction.action === "commit_push") return <CloudUploadIcon className={iconClassName} />;
151 return <GitHubIcon className={iconClassName} />;
152 }
153 if (quickAction.label === "Commit") return <GitCommitIcon className={iconClassName} />;
154 return <InfoIcon className={iconClassName} />;
155}
156
157export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) {
158 const { settings } = useAppSettings();
159 const threadToastData = useMemo(
160 () => (activeThreadId ? { threadId: activeThreadId } : undefined),
161 [activeThreadId],
162 );
163 const queryClient = useQueryClient();
164 const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
165 const [dialogCommitMessage, setDialogCommitMessage] = useState("");
166 const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
167 const [isEditingFiles, setIsEditingFiles] = useState(false);
168 const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
169 useState<PendingDefaultBranchAction | null>(null);
170
171 const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
172
173 const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd));
174 // Default to true while loading so we don't flash init controls.
175 const isRepo = branchList?.isRepo ?? true;
176 const hasOriginRemote = branchList?.hasOriginRemote ?? false;
177 const currentBranch = branchList?.branches.find((branch) => branch.current)?.name ?? null;
178 const isGitStatusOutOfSync =
179 !!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
180
181 useEffect(() => {
182 if (!isGitStatusOutOfSync) return;
183 void invalidateGitQueries(queryClient);
184 }, [isGitStatusOutOfSync, queryClient]);
185
186 const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
187
188 const allFiles = gitStatusForActions?.workingTree.files ?? [];
189 const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
190 const allSelected = excludedFiles.size === 0;
191 const noneSelected = selectedFiles.length === 0;
192
193 const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient }));
194
195 const runImmediateGitActionMutation = useMutation(
196 gitRunStackedActionMutationOptions({
197 cwd: gitCwd,
198 queryClient,
199 model: settings.textGenerationModel ?? null,
200 }),
201 );
202 const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
203
204 const isRunStackedActionRunning =
205 useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
206 const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
207 const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
208 const isDefaultBranch = useMemo(() => {
209 const branchName = gitStatusForActions?.branch;
210 if (!branchName) return false;
211 const current = branchList?.branches.find((branch) => branch.name === branchName);
212 return current?.isDefault ?? (branchName === "main" || branchName === "master");
213 }, [branchList?.branches, gitStatusForActions?.branch]);
214
215 const gitActionMenuItems = useMemo(
216 () => buildMenuItems(gitStatusForActions, isGitActionRunning, hasOriginRemote),
217 [gitStatusForActions, hasOriginRemote, isGitActionRunning],
218 );
219 const quickAction = useMemo(
220 () =>
221 resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultBranch, hasOriginRemote),
222 [gitStatusForActions, hasOriginRemote, isDefaultBranch, isGitActionRunning],
223 );
224 const quickActionDisabledReason = quickAction.disabled
225 ? (quickAction.hint ?? "This action is currently unavailable.")
226 : null;
227 const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
228 ? resolveDefaultBranchActionDialogCopy({
229 action: pendingDefaultBranchAction.action,
230 branchName: pendingDefaultBranchAction.branchName,
231 includesCommit: pendingDefaultBranchAction.includesCommit,
232 })
233 : null;
234
235 const openExistingPr = useCallback(async () => {
236 const api = readNativeApi();
237 if (!api) {
238 toastManager.add({
239 type: "error",
240 title: "Link opening is unavailable.",
241 data: threadToastData,
242 });
243 return;
244 }
245 const prUrl = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : null;
246 if (!prUrl) {
247 toastManager.add({
248 type: "error",
249 title: "No open PR found.",
250 data: threadToastData,
251 });
252 return;
253 }
254 void api.shell.openExternal(prUrl).catch((err) => {
255 toastManager.add({
256 type: "error",
257 title: "Unable to open PR link",
258 description: err instanceof Error ? err.message : "An error occurred.",
259 data: threadToastData,
260 });
261 });
262 }, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
263
264 const runGitActionWithToast = useCallback(
265 async ({
266 action,
267 commitMessage,
268 forcePushOnlyProgress = false,
269 onConfirmed,
270 skipDefaultBranchPrompt = false,
271 statusOverride,
272 featureBranch = false,
273 isDefaultBranchOverride,
274 progressToastId,
275 filePaths,
276 }: {
277 action: GitStackedAction;
278 commitMessage?: string;
279 forcePushOnlyProgress?: boolean;
280 onConfirmed?: () => void;
281 skipDefaultBranchPrompt?: boolean;
282 statusOverride?: GitStatusResult | null;
283 featureBranch?: boolean;
284 isDefaultBranchOverride?: boolean;
285 progressToastId?: GitActionToastId;
286 filePaths?: string[];
287 }) => {
288 const actionStatus = statusOverride ?? gitStatusForActions;
289 const actionBranch = actionStatus?.branch ?? null;
290 const actionIsDefaultBranch =
291 isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);
292 const includesCommit =
293 !forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
294 if (
295 !skipDefaultBranchPrompt &&
296 requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
297 actionBranch
298 ) {
299 if (action !== "commit_push" && action !== "commit_push_pr") {
300 return;
301 }
302 setPendingDefaultBranchAction({
303 action,
304 branchName: actionBranch,
305 includesCommit,
306 ...(commitMessage ? { commitMessage } : {}),
307 forcePushOnlyProgress,
308 ...(onConfirmed ? { onConfirmed } : {}),
309 ...(filePaths ? { filePaths } : {}),
310 });
311 return;
312 }
313 onConfirmed?.();
314
315 const progressStages = buildGitActionProgressStages({
316 action,
317 hasCustomCommitMessage: !!commitMessage?.trim(),
318 hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
319 forcePushOnly: forcePushOnlyProgress,
320 featureBranch,
321 });
322 const resolvedProgressToastId =
323 progressToastId ??
324 toastManager.add({
325 type: "loading",
326 title: progressStages[0] ?? "Running git action...",
327 timeout: 0,
328 data: threadToastData,
329 });
330
331 if (progressToastId) {
332 toastManager.update(progressToastId, {
333 type: "loading",
334 title: progressStages[0] ?? "Running git action...",
335 timeout: 0,
336 data: threadToastData,
337 });
338 }
339
340 let stageIndex = 0;
341 const stageInterval = setInterval(() => {
342 stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
343 toastManager.update(resolvedProgressToastId, {
344 title: progressStages[stageIndex] ?? "Running git action...",
345 type: "loading",
346 timeout: 0,
347 data: threadToastData,
348 });
349 }, 1100);
350
351 const stopProgressUpdates = () => {
352 clearInterval(stageInterval);
353 };
354
355 const promise = runImmediateGitActionMutation.mutateAsync({
356 action,
357 ...(commitMessage ? { commitMessage } : {}),
358 ...(featureBranch ? { featureBranch } : {}),
359 ...(filePaths ? { filePaths } : {}),
360 });
361
362 try {
363 const result = await promise;
364 stopProgressUpdates();
365 const resultToast = summarizeGitResult(result);
366
367 const existingOpenPrUrl =
368 actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
369 const prUrl = result.pr.url ?? existingOpenPrUrl;
370 const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
371 const shouldOfferOpenPrCta =
372 (action === "commit_push" || action === "commit_push_pr") &&
373 !!prUrl &&
374 (!actionIsDefaultBranch ||
375 result.pr.status === "created" ||
376 result.pr.status === "opened_existing");
377 const shouldOfferCreatePrCta =
378 action === "commit_push" &&
379 !prUrl &&
380 result.push.status === "pushed" &&
381 !actionIsDefaultBranch;
382 const closeResultToast = () => {
383 toastManager.close(resolvedProgressToastId);
384 };
385
386 toastManager.update(resolvedProgressToastId, {
387 type: "success",
388 title: resultToast.title,
389 description: resultToast.description,
390 timeout: 0,
391 data: {
392 ...threadToastData,
393 dismissAfterVisibleMs: 10_000,
394 },
395 ...(shouldOfferPushCta
396 ? {
397 actionProps: {
398 children: "Push",
399 onClick: () => {
400 void runGitActionWithToast({
401 action: "commit_push",
402 forcePushOnlyProgress: true,
403 onConfirmed: closeResultToast,
404 statusOverride: actionStatus,
405 isDefaultBranchOverride: actionIsDefaultBranch,
406 });
407 },
408 },
409 }
410 : shouldOfferOpenPrCta
411 ? {
412 actionProps: {
413 children: "View PR",
414 onClick: () => {
415 const api = readNativeApi();
416 if (!api) return;
417 closeResultToast();
418 void api.shell.openExternal(prUrl);
419 },
420 },
421 }
422 : shouldOfferCreatePrCta
423 ? {
424 actionProps: {
425 children: "Create PR",
426 onClick: () => {
427 closeResultToast();
428 void runGitActionWithToast({
429 action: "commit_push_pr",
430 forcePushOnlyProgress: true,
431 statusOverride: actionStatus,
432 isDefaultBranchOverride: actionIsDefaultBranch,
433 });
434 },
435 },
436 }
437 : {}),
438 });
439 } catch (err) {
440 stopProgressUpdates();
441 toastManager.update(resolvedProgressToastId, {
442 type: "error",
443 title: "Action failed",
444 description: err instanceof Error ? err.message : "An error occurred.",
445 data: threadToastData,
446 });
447 }
448 },
449
450 [
451 isDefaultBranch,
452 runImmediateGitActionMutation,
453 setPendingDefaultBranchAction,
454 threadToastData,
455 gitStatusForActions,
456 ],
457 );
458
459 const continuePendingDefaultBranchAction = useCallback(() => {
460 if (!pendingDefaultBranchAction) return;
461 const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
462 pendingDefaultBranchAction;
463 setPendingDefaultBranchAction(null);
464 void runGitActionWithToast({
465 action,
466 ...(commitMessage ? { commitMessage } : {}),
467 forcePushOnlyProgress,
468 ...(onConfirmed ? { onConfirmed } : {}),
469 ...(filePaths ? { filePaths } : {}),
470 skipDefaultBranchPrompt: true,
471 });
472 }, [pendingDefaultBranchAction, runGitActionWithToast]);
473
474 const checkoutNewBranchAndRunAction = useCallback(
475 (actionParams: {
476 action: GitStackedAction;
477 commitMessage?: string;
478 forcePushOnlyProgress?: boolean;
479 onConfirmed?: () => void;
480 filePaths?: string[];
481 }) => {
482 void runGitActionWithToast({
483 ...actionParams,
484 featureBranch: true,
485 skipDefaultBranchPrompt: true,
486 });
487 },
488 [runGitActionWithToast],
489 );
490
491 const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
492 if (!pendingDefaultBranchAction) return;
493 const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
494 pendingDefaultBranchAction;
495 setPendingDefaultBranchAction(null);
496 checkoutNewBranchAndRunAction({
497 action,
498 ...(commitMessage ? { commitMessage } : {}),
499 forcePushOnlyProgress,
500 ...(onConfirmed ? { onConfirmed } : {}),
501 ...(filePaths ? { filePaths } : {}),
502 });
503 }, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
504
505 const runDialogActionOnNewBranch = useCallback(() => {
506 if (!isCommitDialogOpen) return;
507 const commitMessage = dialogCommitMessage.trim();
508
509 setIsCommitDialogOpen(false);
510 setDialogCommitMessage("");
511 setExcludedFiles(new Set());
512 setIsEditingFiles(false);
513
514 checkoutNewBranchAndRunAction({
515 action: "commit",
516 ...(commitMessage ? { commitMessage } : {}),
517 ...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
518 });
519 }, [
520 allSelected,
521 isCommitDialogOpen,
522 dialogCommitMessage,
523 checkoutNewBranchAndRunAction,
524 selectedFiles,
525 ]);
526
527 const runQuickAction = useCallback(() => {
528 if (quickAction.kind === "open_pr") {
529 void openExistingPr();
530 return;
531 }
532 if (quickAction.kind === "run_pull") {
533 const promise = pullMutation.mutateAsync();
534 toastManager.promise(promise, {
535 loading: { title: "Pulling...", data: threadToastData },
536 success: (result) => ({
537 title: result.status === "pulled" ? "Pulled" : "Already up to date",
538 description:
539 result.status === "pulled"
540 ? `Updated ${result.branch} from ${result.upstreamBranch ?? "upstream"}`
541 : `${result.branch} is already synchronized.`,
542 data: threadToastData,
543 }),
544 error: (err) => ({
545 title: "Pull failed",
546 description: err instanceof Error ? err.message : "An error occurred.",
547 data: threadToastData,
548 }),
549 });
550 void promise.catch(() => undefined);
551 return;
552 }
553 if (quickAction.kind === "show_hint") {
554 toastManager.add({
555 type: "info",
556 title: quickAction.label,
557 description: quickAction.hint,
558 data: threadToastData,
559 });
560 return;
561 }
562 if (quickAction.action) {
563 void runGitActionWithToast({ action: quickAction.action });
564 }
565 }, [openExistingPr, pullMutation, quickAction, runGitActionWithToast, threadToastData]);
566
567 const openDialogForMenuItem = useCallback(
568 (item: GitActionMenuItem) => {
569 if (item.disabled) return;
570 if (item.kind === "open_pr") {
571 void openExistingPr();
572 return;
573 }
574 if (item.dialogAction === "push") {
575 void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
576 return;
577 }
578 if (item.dialogAction === "create_pr") {
579 void runGitActionWithToast({ action: "commit_push_pr" });
580 return;
581 }
582 setExcludedFiles(new Set());
583 setIsEditingFiles(false);
584 setIsCommitDialogOpen(true);
585 },
586 [openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
587 );
588
589 const runDialogAction = useCallback(() => {
590 if (!isCommitDialogOpen) return;
591 const commitMessage = dialogCommitMessage.trim();
592 setIsCommitDialogOpen(false);
593 setDialogCommitMessage("");
594 setExcludedFiles(new Set());
595 setIsEditingFiles(false);
596 void runGitActionWithToast({
597 action: "commit",
598 ...(commitMessage ? { commitMessage } : {}),
599 ...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
600 });
601 }, [
602 allSelected,
603 dialogCommitMessage,
604 isCommitDialogOpen,
605 runGitActionWithToast,
606 selectedFiles,
607 setDialogCommitMessage,
608 setIsCommitDialogOpen,
609 ]);
610
611 const openChangedFileInEditor = useCallback(
612 (filePath: string) => {
613 const api = readNativeApi();
614 if (!api || !gitCwd) {
615 toastManager.add({
616 type: "error",
617 title: "Editor opening is unavailable.",
618 data: threadToastData,
619 });
620 return;
621 }
622 const target = resolvePathLinkTarget(filePath, gitCwd);
623 void openInPreferredEditor(api, target).catch((error) => {
624 toastManager.add({
625 type: "error",
626 title: "Unable to open file",
627 description: error instanceof Error ? error.message : "An error occurred.",
628 data: threadToastData,
629 });
630 });
631 },
632 [gitCwd, threadToastData],
633 );
634
635 if (!gitCwd) return null;
636
637 return (
638 <>
639 {!isRepo ? (
640 <Button
641 variant="outline"
642 size="xs"
643 disabled={initMutation.isPending}
644 onClick={() => initMutation.mutate()}
645 >
646 {initMutation.isPending ? "Initializing..." : "Initialize Git"}
647 </Button>
648 ) : (
649 <Group aria-label="Git actions">
650 {quickActionDisabledReason ? (
651 <Popover>
652 <PopoverTrigger
653 openOnHover
654 render={
655 <Button
656 aria-disabled="true"
657 className="cursor-not-allowed rounded-e-none border-e-0 opacity-64 before:rounded-e-none"
658 size="xs"
659 variant="outline"
660 />
661 }
662 >
663 <GitQuickActionIcon quickAction={quickAction} />
664 <span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
665 {quickAction.label}
666 </span>
667 </PopoverTrigger>
668 <PopoverPopup tooltipStyle side="bottom" align="start">
669 {quickActionDisabledReason}
670 </PopoverPopup>
671 </Popover>
672 ) : (
673 <Button
674 variant="outline"
675 size="xs"
676 disabled={isGitActionRunning || quickAction.disabled}
677 onClick={runQuickAction}
678 >
679 <GitQuickActionIcon quickAction={quickAction} />
680 <span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
681 {quickAction.label}
682 </span>
683 </Button>
684 )}
685 <GroupSeparator className="hidden @sm/header-actions:block" />
686 <Menu
687 onOpenChange={(open) => {
688 if (open) void invalidateGitQueries(queryClient);
689 }}
690 >
691 <MenuTrigger
692 render={<Button aria-label="Git action options" size="icon-xs" variant="outline" />}
693 disabled={isGitActionRunning}
694 >
695 <ChevronDownIcon aria-hidden="true" className="size-4" />
696 </MenuTrigger>
697 <MenuPopup align="end" className="w-full">
698 {gitActionMenuItems.map((item) => {
699 const disabledReason = getMenuActionDisabledReason({
700 item,
701 gitStatus: gitStatusForActions,
702 isBusy: isGitActionRunning,
703 hasOriginRemote,
704 });
705 if (item.disabled && disabledReason) {
706 return (
707 <Popover key={`${item.id}-${item.label}`}>
708 <PopoverTrigger
709 openOnHover
710 nativeButton={false}
711 render={<span className="block w-max cursor-not-allowed" />}
712 >
713 <MenuItem className="w-full" disabled>
714 <GitActionItemIcon icon={item.icon} />
715 {item.label}
716 </MenuItem>
717 </PopoverTrigger>
718 <PopoverPopup tooltipStyle side="left" align="center">
719 {disabledReason}
720 </PopoverPopup>
721 </Popover>
722 );
723 }
724
725 return (
726 <MenuItem
727 key={`${item.id}-${item.label}`}
728 disabled={item.disabled}
729 onClick={() => {
730 openDialogForMenuItem(item);
731 }}
732 >
733 <GitActionItemIcon icon={item.icon} />
734 {item.label}
735 </MenuItem>
736 );
737 })}
738 {gitStatusForActions?.branch === null && (
739 <p className="px-2 py-1.5 text-xs text-warning">
740 Detached HEAD: create and checkout a branch to enable push and PR actions.
741 </p>
742 )}
743 {gitStatusForActions &&
744 gitStatusForActions.branch !== null &&
745 !gitStatusForActions.hasWorkingTreeChanges &&
746 gitStatusForActions.behindCount > 0 &&
747 gitStatusForActions.aheadCount === 0 && (
748 <p className="px-2 py-1.5 text-xs text-warning">
749 Behind upstream. Pull/rebase first.
750 </p>
751 )}
752 {isGitStatusOutOfSync && (
753 <p className="px-2 py-1.5 text-xs text-muted-foreground">
754 Refreshing git status...
755 </p>
756 )}
757 {gitStatusError && (
758 <p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError.message}</p>
759 )}
760 </MenuPopup>
761 </Menu>
762 </Group>
763 )}
764
765 <Dialog
766 open={isCommitDialogOpen}
767 onOpenChange={(open) => {
768 if (!open) {
769 setIsCommitDialogOpen(false);
770 setDialogCommitMessage("");
771 setExcludedFiles(new Set());
772 setIsEditingFiles(false);
773 }
774 }}
775 >
776 <DialogPopup>
777 <DialogHeader>
778 <DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
779 <DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
780 </DialogHeader>
781 <DialogPanel className="space-y-4">
782 <div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
783 <div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
784 <span className="text-muted-foreground">Branch</span>
785 <span className="flex items-center justify-between gap-2">
786 <span className="font-medium">
787 {gitStatusForActions?.branch ?? "(detached HEAD)"}
788 </span>
789 {isDefaultBranch && (
790 <span className="text-right text-warning text-xs">Warning: default branch</span>
791 )}
792 </span>
793 </div>
794 <div className="space-y-1">
795 <div className="flex items-center justify-between">
796 <div className="flex items-center gap-2">
797 {isEditingFiles && allFiles.length > 0 && (
798 <Checkbox
799 checked={allSelected}
800 indeterminate={!allSelected && !noneSelected}
801 onCheckedChange={() => {
802 setExcludedFiles(
803 allSelected ? new Set(allFiles.map((f) => f.path)) : new Set(),
804 );
805 }}
806 />
807 )}
808 <span className="text-muted-foreground">Files</span>
809 {!allSelected && !isEditingFiles && (
810 <span className="text-muted-foreground">
811 ({selectedFiles.length} of {allFiles.length})
812 </span>
813 )}
814 </div>
815 {allFiles.length > 0 && (
816 <Button
817 variant="ghost"
818 size="xs"
819 onClick={() => setIsEditingFiles((prev) => !prev)}
820 >
821 {isEditingFiles ? "Done" : "Edit"}
822 </Button>
823 )}
824 </div>
825 {!gitStatusForActions || allFiles.length === 0 ? (
826 <p className="font-medium">none</p>
827 ) : (
828 <div className="space-y-2">
829 <ScrollArea className="h-44 rounded-md border border-input bg-background">
830 <div className="space-y-1 p-1">
831 {allFiles.map((file) => {
832 const isExcluded = excludedFiles.has(file.path);
833 return (
834 <div
835 key={file.path}
836 className="flex w-full items-center gap-2 rounded-md px-2 py-1 font-mono text-xs transition-colors hover:bg-accent/50"
837 >
838 {isEditingFiles && (
839 <Checkbox
840 checked={!excludedFiles.has(file.path)}
841 onCheckedChange={() => {
842 setExcludedFiles((prev) => {
843 const next = new Set(prev);
844 if (next.has(file.path)) {
845 next.delete(file.path);
846 } else {
847 next.add(file.path);
848 }
849 return next;
850 });
851 }}
852 />
853 )}
854 <button
855 type="button"
856 className="flex flex-1 items-center justify-between gap-3 text-left truncate"
857 onClick={() => openChangedFileInEditor(file.path)}
858 >
859 <span
860 className={`truncate${isExcluded ? " text-muted-foreground" : ""}`}
861 >
862 {file.path}
863 </span>
864 <span className="shrink-0">
865 {isExcluded ? (
866 <span className="text-muted-foreground">Excluded</span>
867 ) : (
868 <>
869 <span className="text-success">+{file.insertions}</span>
870 <span className="text-muted-foreground"> / </span>
871 <span className="text-destructive">-{file.deletions}</span>
872 </>
873 )}
874 </span>
875 </button>
876 </div>
877 );
878 })}
879 </div>
880 </ScrollArea>
881 <div className="flex justify-end font-mono">
882 <span className="text-success">
883 +{selectedFiles.reduce((sum, f) => sum + f.insertions, 0)}
884 </span>
885 <span className="text-muted-foreground"> / </span>
886 <span className="text-destructive">
887 -{selectedFiles.reduce((sum, f) => sum + f.deletions, 0)}
888 </span>
889 </div>
890 </div>
891 )}
892 </div>
893 </div>
894 <div className="space-y-1">
895 <p className="text-xs font-medium">Commit message (optional)</p>
896 <Textarea
897 value={dialogCommitMessage}
898 onChange={(event) => setDialogCommitMessage(event.target.value)}
899 placeholder="Leave empty to auto-generate"
900 size="sm"
901 />
902 </div>
903 </DialogPanel>
904 <DialogFooter>
905 <Button
906 variant="outline"
907 size="sm"
908 onClick={() => {
909 setIsCommitDialogOpen(false);
910 setDialogCommitMessage("");
911 setExcludedFiles(new Set());
912 setIsEditingFiles(false);
913 }}
914 >
915 Cancel
916 </Button>
917 <Button
918 variant="outline"
919 size="sm"
920 disabled={noneSelected}
921 onClick={runDialogActionOnNewBranch}
922 >
923 Commit on new branch
924 </Button>
925 <Button size="sm" disabled={noneSelected} onClick={runDialogAction}>
926 Commit
927 </Button>
928 </DialogFooter>
929 </DialogPopup>
930 </Dialog>
931
932 <Dialog
933 open={pendingDefaultBranchAction !== null}
934 onOpenChange={(open) => {
935 if (!open) {
936 setPendingDefaultBranchAction(null);
937 }
938 }}
939 >
940 <DialogPopup className="max-w-xl">
941 <DialogHeader>
942 <DialogTitle>
943 {pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
944 </DialogTitle>
945 <DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
946 </DialogHeader>
947 <DialogFooter>
948 <Button variant="outline" size="sm" onClick={() => setPendingDefaultBranchAction(null)}>
949 Abort
950 </Button>
951 <Button variant="outline" size="sm" onClick={continuePendingDefaultBranchAction}>
952 {pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
953 </Button>
954 <Button size="sm" onClick={checkoutFeatureBranchAndContinuePendingAction}>
955 Checkout feature branch & continue
956 </Button>
957 </DialogFooter>
958 </DialogPopup>
959 </Dialog>
960 </>
961 );
962}