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

GitActionsControl.tsx

1,092 lines38.1 KB

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