Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitActionsControl.tsx

1,157 lines39.6 KB

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