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