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