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

GitActionsControl.tsx

1,173 lines40.0 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 { 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;
63​
64interface PendingDefaultBranchAction {
65 action: DefaultBranchConfirmableAction;
66 branchName: string;
67 includesCommit: boolean;
68 commitMessage?: string;
69 onConfirmed?: () => void;
70 filePaths?: string[];
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;
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[];
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`;
112​
113function resolveProgressDescription(progress: ActiveGitActionProgress): string | undefined {
114 if (progress.lastOutputLine) {
115 return progress.lastOutputLine;
116 }
117 return formatElapsedDescription(progress.hookStartedAtMs ?? progress.phaseStartedAtMs);
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.";
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 />;
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} />;
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 type: "error",
479 title: "Unable to open PR link",
480 description: err instanceof Error ? err.message : "An error occurred.",
481 data: threadToastData,
482 });
483 });
484 }, [gitStatusForActions, threadToastData]);
485​
486 runGitActionWithToast = useEffectEvent(
487 async ({
488 action,
489 commitMessage,
490 onConfirmed,
491 skipDefaultBranchPrompt = false,
492 statusOverride,
493 featureBranch = false,
494 progressToastId,
495 filePaths,
496 }: RunGitActionWithToastInput) => {
497 const actionStatus = statusOverride ?? gitStatusForActions;
498 const actionBranch = actionStatus?.branch ?? null;
499 const actionIsDefaultBranch = featureBranch ? false : isDefaultBranch;
500 const actionCanCommit =
501 action === "commit" || action === "commit_push" || action === "commit_push_pr";
502 const includesCommit =
503 actionCanCommit &&
504 (action === "commit" || !!actionStatus?.hasWorkingTreeChanges || featureBranch);
505 if (
506 !skipDefaultBranchPrompt &&
507 requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
508 actionBranch
509 ) {
510 if (
511 action !== "push" &&
512 action !== "create_pr" &&
513 action !== "commit_push" &&
514 action !== "commit_push_pr"
515 ) {
516 return;
517 }
518 setPendingDefaultBranchAction({
519 action,
520 branchName: actionBranch,
521 includesCommit,
522 ...(commitMessage ? { commitMessage } : {}),
523 ...(onConfirmed ? { onConfirmed } : {}),
524 ...(filePaths ? { filePaths } : {}),
525 });
526 return;
527 }
528 onConfirmed?.();
529​
530 const progressStages = buildGitActionProgressStages({
531 action,
532 hasCustomCommitMessage: !!commitMessage?.trim(),
533 hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
534 featureBranch,
535 shouldPushBeforePr:
536 action === "create_pr" &&
537 (!actionStatus?.hasUpstream || (actionStatus?.aheadCount ?? 0) > 0),
538 });
539 const scopedToastData = threadToastData ? { ...threadToastData } : undefined;
540 const actionId = randomUUID();
541 const resolvedProgressToastId =
542 progressToastId ??
543 toastManager.add({
544 type: "loading",
545 title: progressStages[0] ?? "Running git action...",
546 description: "Waiting for Git...",
547 timeout: 0,
548 data: scopedToastData,
549 });
550​
551 activeGitActionProgressRef.current = {
552 toastId: resolvedProgressToastId,
553 toastData: scopedToastData,
554 actionId,
555 title: progressStages[0] ?? "Running git action...",
556 phaseStartedAtMs: null,
557 hookStartedAtMs: null,
558 hookName: null,
559 lastOutputLine: null,
560 currentPhaseLabel: progressStages[0] ?? "Running git action...",
561 };
562​
563 if (progressToastId) {
564 toastManager.update(progressToastId, {
565 type: "loading",
566 title: progressStages[0] ?? "Running git action...",
567 description: "Waiting for Git...",
568 timeout: 0,
569 data: scopedToastData,
570 });
571 }
572​
573 const applyProgressEvent = (event: GitActionProgressEvent) => {
574 const progress = activeGitActionProgressRef.current;
575 if (!progress) {
576 return;
577 }
578 if (gitCwd && event.cwd !== gitCwd) {
579 return;
580 }
581 if (progress.actionId !== event.actionId) {
582 return;
583 }
584​
585 const now = Date.now();
586 switch (event.kind) {
587 case "action_started":
588 progress.phaseStartedAtMs = now;
589 progress.hookStartedAtMs = null;
590 progress.hookName = null;
591 progress.lastOutputLine = null;
592 break;
593 case "phase_started":
594 progress.title = event.label;
595 progress.currentPhaseLabel = event.label;
596 progress.phaseStartedAtMs = now;
597 progress.hookStartedAtMs = null;
598 progress.hookName = null;
599 progress.lastOutputLine = null;
600 break;
601 case "hook_started":
602 progress.title = `Running ${event.hookName}...`;
603 progress.hookName = event.hookName;
604 progress.hookStartedAtMs = now;
605 progress.lastOutputLine = null;
606 break;
607 case "hook_output":
608 progress.lastOutputLine = event.text;
609 break;
610 case "hook_finished":
611 progress.title = progress.currentPhaseLabel ?? "Committing...";
612 progress.hookName = null;
613 progress.hookStartedAtMs = null;
614 progress.lastOutputLine = null;
615 break;
616 case "action_finished":
617 // Let the resolved mutation update the toast so we keep the
618 // elapsed description visible until the final success state renders.
619 return;
620 case "action_failed":
621 // Let the rejected mutation publish the error toast to avoid a
622 // transient intermediate state before the final failure message.
623 return;
624 }
625​
626 updateActiveProgressToast();
627 };
628​
629 const promise = runImmediateGitActionMutation.mutateAsync({
630 actionId,
631 action,
632 ...(commitMessage ? { commitMessage } : {}),
633 ...(featureBranch ? { featureBranch } : {}),
634 ...(filePaths ? { filePaths } : {}),
635 onProgress: applyProgressEvent,
636 });
637​
638 try {
639 const result = await promise;
640 activeGitActionProgressRef.current = null;
641 syncThreadBranchAfterGitAction(result);
642 const closeResultToast = () => {
643 toastManager.close(resolvedProgressToastId);
644 };
645​
646 const toastCta = result.toast.cta;
647 let toastActionProps: {
648 children: string;
649 onClick: () => void;
650 } | null = null;
651 if (toastCta.kind === "run_action") {
652 toastActionProps = {
653 children: toastCta.label,
654 onClick: () => {
655 closeResultToast();
656 void runGitActionWithToast({
657 action: toastCta.action.kind,
658 });
659 },
660 };
661 } else if (toastCta.kind === "open_pr") {
662 toastActionProps = {
663 children: toastCta.label,
664 onClick: () => {
665 const api = readLocalApi();
666 if (!api) return;
667 closeResultToast();
668 void api.shell.openExternal(toastCta.url);
669 },
670 };
671 }
672​
673 const successToastBase = {
674 type: "success",
675 title: result.toast.title,
676 description: result.toast.description,
677 timeout: 0,
678 data: {
679 ...scopedToastData,
680 dismissAfterVisibleMs: 10_000,
681 },
682 } as const;
683​
684 if (toastActionProps) {
685 toastManager.update(resolvedProgressToastId, {
686 ...successToastBase,
687 actionProps: toastActionProps,
688 });
689 } else {
690 toastManager.update(resolvedProgressToastId, successToastBase);
691 }
692 } catch (err) {
693 activeGitActionProgressRef.current = null;
694 toastManager.update(resolvedProgressToastId, {
695 type: "error",
696 title: "Action failed",
697 description: err instanceof Error ? err.message : "An error occurred.",
698 data: scopedToastData,
699 });
700 }
701 },
702 );
703​
704 const continuePendingDefaultBranchAction = () => {
705 if (!pendingDefaultBranchAction) return;
706 const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
707 setPendingDefaultBranchAction(null);
708 void runGitActionWithToast({
709 action,
710 ...(commitMessage ? { commitMessage } : {}),
711 ...(onConfirmed ? { onConfirmed } : {}),
712 ...(filePaths ? { filePaths } : {}),
713 skipDefaultBranchPrompt: true,
714 });
715 };
716​
717 const checkoutFeatureBranchAndContinuePendingAction = () => {
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 featureBranch: true,
727 skipDefaultBranchPrompt: true,
728 });
729 };
730​
731 const runDialogActionOnNewBranch = () => {
732 if (!isCommitDialogOpen) return;
733 const commitMessage = dialogCommitMessage.trim();
734​
735 setIsCommitDialogOpen(false);
736 setDialogCommitMessage("");
737 setExcludedFiles(new Set());
738 setIsEditingFiles(false);
739​
740 void runGitActionWithToast({
741 action: "commit",
742 ...(commitMessage ? { commitMessage } : {}),
743 ...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
744 featureBranch: true,
745 skipDefaultBranchPrompt: true,
746 });
747 };
748​
749 const runQuickAction = () => {
750 if (quickAction.kind === "open_pr") {
751 void openExistingPr();
752 return;
753 }
754 if (quickAction.kind === "run_pull") {
755 const promise = pullMutation.mutateAsync();
756 toastManager.promise(promise, {
757 loading: { title: "Pulling...", data: threadToastData },
758 success: (result) => ({
759 title: result.status === "pulled" ? "Pulled" : "Already up to date",
760 description:
761 result.status === "pulled"
762 ? `Updated ${result.branch} from ${result.upstreamBranch ?? "upstream"}`
763 : `${result.branch} is already synchronized.`,
764 data: threadToastData,
765 }),
766 error: (err) => ({
767 title: "Pull failed",
768 description: err instanceof Error ? err.message : "An error occurred.",
769 data: threadToastData,
770 }),
771 });
772 void promise.catch(() => undefined);
773 return;
774 }
775 if (quickAction.kind === "show_hint") {
776 toastManager.add({
777 type: "info",
778 title: quickAction.label,
779 description: quickAction.hint,
780 data: threadToastData,
781 });
782 return;
783 }
784 if (quickAction.action) {
785 void runGitActionWithToast({ action: quickAction.action });
786 }
787 };
788​
789 const openDialogForMenuItem = (item: GitActionMenuItem) => {
790 if (item.disabled) return;
791 if (item.kind === "open_pr") {
792 void openExistingPr();
793 return;
794 }
795 if (item.dialogAction === "push") {
796 void runGitActionWithToast({ action: "push" });
797 return;
798 }
799 if (item.dialogAction === "create_pr") {
800 void runGitActionWithToast({ action: "create_pr" });
801 return;
802 }
803 setExcludedFiles(new Set());
804 setIsEditingFiles(false);
805 setIsCommitDialogOpen(true);
806 };
807​
808 const runDialogAction = () => {
809 if (!isCommitDialogOpen) return;
810 const commitMessage = dialogCommitMessage.trim();
811 setIsCommitDialogOpen(false);
812 setDialogCommitMessage("");
813 setExcludedFiles(new Set());
814 setIsEditingFiles(false);
815 void runGitActionWithToast({
816 action: "commit",
817 ...(commitMessage ? { commitMessage } : {}),
818 ...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
819 });
820 };
821​
822 const openChangedFileInEditor = useCallback(
823 (filePath: string) => {
824 const api = readLocalApi();
825 if (!api || !gitCwd) {
826 toastManager.add({
827 type: "error",
828 title: "Editor opening is unavailable.",
829 data: threadToastData,
830 });
831 return;
832 }
833 const target = resolvePathLinkTarget(filePath, gitCwd);
834 void openInPreferredEditor(api, target).catch((error) => {
835 toastManager.add({
836 type: "error",
837 title: "Unable to open file",
838 description: error instanceof Error ? error.message : "An error occurred.",
839 data: threadToastData,
840 });
841 });
842 },
843 [gitCwd, threadToastData],
844 );
845​
846 if (!gitCwd) return null;
847​
848 return (
849 <>
850 {!isRepo ? (
851 <Button
852 variant="outline"
853 size="xs"
854 disabled={initMutation.isPending}
855 onClick={() => initMutation.mutate()}
856 >
857 {initMutation.isPending ? "Initializing..." : "Initialize Git"}
858 </Button>
859 ) : (
860 <Group aria-label="Git actions" className="shrink-0">
861 {quickActionDisabledReason ? (
862 <Popover>
863 <PopoverTrigger
864 openOnHover
865 render={
866 <Button
867 aria-disabled="true"
868 className="cursor-not-allowed rounded-e-none border-e-0 opacity-64 before:rounded-e-none"
869 size="xs"
870 variant="outline"
871 />
872 }
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 </PopoverTrigger>
879 <PopoverPopup tooltipStyle side="bottom" align="start">
880 {quickActionDisabledReason}
881 </PopoverPopup>
882 </Popover>
883 ) : (
884 <Button
885 variant="outline"
886 size="xs"
887 disabled={isGitActionRunning || quickAction.disabled}
888 onClick={runQuickAction}
889 >
890 <GitQuickActionIcon quickAction={quickAction} />
891 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
892 {quickAction.label}
893 </span>
894 </Button>
895 )}
896 <GroupSeparator className="hidden @3xl/header-actions:block" />
897 <Menu
898 onOpenChange={(open) => {
899 if (open) {
900 void refreshGitStatus({
901 environmentId: activeEnvironmentId,
902 cwd: gitCwd,
903 }).catch(() => undefined);
904 }
905 }}
906 >
907 <MenuTrigger
908 render={<Button aria-label="Git action options" size="icon-xs" variant="outline" />}
909 disabled={isGitActionRunning}
910 >
911 <ChevronDownIcon aria-hidden="true" className="size-4" />
912 </MenuTrigger>
913 <MenuPopup align="end" className="w-full">
914 {gitActionMenuItems.map((item) => {
915 const disabledReason = getMenuActionDisabledReason({
916 item,
917 gitStatus: gitStatusForActions,
918 isBusy: isGitActionRunning,
919 hasOriginRemote,
920 });
921 if (item.disabled && disabledReason) {
922 return (
923 <Popover key={`${item.id}-${item.label}`}>
924 <PopoverTrigger
925 openOnHover
926 nativeButton={false}
927 render={<span className="block w-max cursor-not-allowed" />}
928 >
929 <MenuItem className="w-full" disabled>
930 <GitActionItemIcon icon={item.icon} />
931 {item.label}
932 </MenuItem>
933 </PopoverTrigger>
934 <PopoverPopup tooltipStyle side="left" align="center">
935 {disabledReason}
936 </PopoverPopup>
937 </Popover>
938 );
939 }
940​
941 return (
942 <MenuItem
943 key={`${item.id}-${item.label}`}
944 disabled={item.disabled}
945 onClick={() => {
946 openDialogForMenuItem(item);
947 }}
948 >
949 <GitActionItemIcon icon={item.icon} />
950 {item.label}
951 </MenuItem>
952 );
953 })}
954 {gitStatusForActions?.branch === null && (
955 <p className="px-2 py-1.5 text-xs text-warning">
956 Detached HEAD: create and checkout a branch to enable push and PR actions.
957 </p>
958 )}
959 {gitStatusForActions &&
960 gitStatusForActions.branch !== null &&
961 !gitStatusForActions.hasWorkingTreeChanges &&
962 gitStatusForActions.behindCount > 0 &&
963 gitStatusForActions.aheadCount === 0 && (
964 <p className="px-2 py-1.5 text-xs text-warning">
965 Behind upstream. Pull/rebase first.
966 </p>
967 )}
968 {gitStatusError && (
969 <p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError.message}</p>
970 )}
971 </MenuPopup>
972 </Menu>
973 </Group>
974 )}
975​
976 <Dialog
977 open={isCommitDialogOpen}
978 onOpenChange={(open) => {
979 if (!open) {
980 setIsCommitDialogOpen(false);
981 setDialogCommitMessage("");
982 setExcludedFiles(new Set());
983 setIsEditingFiles(false);
984 }
985 }}
986 >
987 <DialogPopup>
988 <DialogHeader>
989 <DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
990 <DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
991 </DialogHeader>
992 <DialogPanel className="space-y-4">
993 <div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
994 <div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
995 <span className="text-muted-foreground">Branch</span>
996 <span className="flex items-center justify-between gap-2">
997 <span className="font-medium">
998 {gitStatusForActions?.branch ?? "(detached HEAD)"}
999 </span>
1000 {isDefaultBranch && (
1001 <span className="text-right text-warning text-xs">Warning: default branch</span>
1002 )}
1003 </span>
1004 </div>
1005 <div className="space-y-1">
1006 <div className="flex items-center justify-between">
1007 <div className="flex items-center gap-2">
1008 {isEditingFiles && allFiles.length > 0 && (
1009 <Checkbox
1010 checked={allSelected}
1011 indeterminate={!allSelected && !noneSelected}
1012 onCheckedChange={() => {
1013 setExcludedFiles(
1014 allSelected ? new Set(allFiles.map((f) => f.path)) : new Set(),
1015 );
1016 }}
1017 />
1018 )}
1019 <span className="text-muted-foreground">Files</span>
1020 {!allSelected && !isEditingFiles && (
1021 <span className="text-muted-foreground">
1022 ({selectedFiles.length} of {allFiles.length})
1023 </span>
1024 )}
1025 </div>
1026 {allFiles.length > 0 && (
1027 <Button
1028 variant="ghost"
1029 size="xs"
1030 onClick={() => setIsEditingFiles((prev) => !prev)}
1032 {isEditingFiles ? "Done" : "Edit"}
1033 </Button>
1034 )}
1035 </div>
1036 {!gitStatusForActions || allFiles.length === 0 ? (
1037 <p className="font-medium">none</p>
1038 ) : (
1039 <div className="space-y-2">
1040 <ScrollArea className="h-44 rounded-md border border-input bg-background">
1041 <div className="space-y-1 p-1">
1042 {allFiles.map((file) => {
1043 const isExcluded = excludedFiles.has(file.path);
1044 return (
1045 <div
1046 key={file.path}
1047 className="flex w-full items-center gap-2 rounded-md px-2 py-1 font-mono text-xs transition-colors hover:bg-accent/50"
1049 {isEditingFiles && (
1050 <Checkbox
1051 checked={!excludedFiles.has(file.path)}
1052 onCheckedChange={() => {
1053 setExcludedFiles((prev) => {
1054 const next = new Set(prev);
1055 if (next.has(file.path)) {
1056 next.delete(file.path);
1057 } else {
1058 next.add(file.path);
1060 return next;
1061 });
1062 }}
1063 />
1064 )}
1065 <button
1066 type="button"
1067 className="flex flex-1 items-center justify-between gap-3 text-left truncate"
1068 onClick={() => openChangedFileInEditor(file.path)}
1070 <span
1071 className={`truncate${isExcluded ? " text-muted-foreground" : ""}`}
1073 {file.path}
1074 </span>
1075 <span className="shrink-0">
1076 {isExcluded ? (
1077 <span className="text-muted-foreground">Excluded</span>
1078 ) : (
1079 <>
1080 <span className="text-success">+{file.insertions}</span>
1081 <span className="text-muted-foreground"> / </span>
1082 <span className="text-destructive">-{file.deletions}</span>
1083 </>
1084 )}
1085 </span>
1086 </button>
1087 </div>
1088 );
1089 })}
1090 </div>
1091 </ScrollArea>
1092 <div className="flex justify-end font-mono">
1093 <span className="text-success">
1094 +{selectedFiles.reduce((sum, f) => sum + f.insertions, 0)}
1095 </span>
1096 <span className="text-muted-foreground"> / </span>
1097 <span className="text-destructive">
1098 -{selectedFiles.reduce((sum, f) => sum + f.deletions, 0)}
1099 </span>
1100 </div>
1101 </div>
1102 )}
1103 </div>
1104 </div>
1105 <div className="space-y-1">
1106 <p className="text-xs font-medium">Commit message (optional)</p>
1107 <Textarea
1108 value={dialogCommitMessage}
1109 onChange={(event) => setDialogCommitMessage(event.target.value)}
1110 placeholder="Leave empty to auto-generate"
1111 size="sm"
1112 />
1113 </div>
1114 </DialogPanel>
1115 <DialogFooter>
1116 <Button
1117 variant="outline"
1118 size="sm"
1119 onClick={() => {
1120 setIsCommitDialogOpen(false);
1121 setDialogCommitMessage("");
1122 setExcludedFiles(new Set());
1123 setIsEditingFiles(false);
1124 }}
1126 Cancel
1127 </Button>
1128 <Button
1129 variant="outline"
1130 size="sm"
1131 disabled={noneSelected}
1132 onClick={runDialogActionOnNewBranch}
1134 Commit on new branch
1135 </Button>
1136 <Button size="sm" disabled={noneSelected} onClick={runDialogAction}>
1137 Commit
1138 </Button>
1139 </DialogFooter>
1140 </DialogPopup>
1141 </Dialog>
1142​
1143 <Dialog
1144 open={pendingDefaultBranchAction !== null}
1145 onOpenChange={(open) => {
1146 if (!open) {
1147 setPendingDefaultBranchAction(null);
1149 }}
1151 <DialogPopup className="max-w-xl">
1152 <DialogHeader>
1153 <DialogTitle>
1154 {pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
1155 </DialogTitle>
1156 <DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
1157 </DialogHeader>
1158 <DialogFooter>
1159 <Button variant="outline" size="sm" onClick={() => setPendingDefaultBranchAction(null)}>
1160 Abort
1161 </Button>
1162 <Button variant="outline" size="sm" onClick={continuePendingDefaultBranchAction}>
1163 {pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
1164 </Button>
1165 <Button size="sm" onClick={checkoutFeatureBranchAndContinuePendingAction}>
1166 Checkout feature branch & continue
1167 </Button>
1168 </DialogFooter>
1169 </DialogPopup>
1170 </Dialog>
1171 </>
1172 );