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