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