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