Files
t3code/apps/web/src/components/GitActionsControl.tsx
T

2226 lines
81 KiB
TypeScript

import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
import { useAtomValue } from "@effect/atom-react";
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
type ScopedThreadRef,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type {
GitRunStackedActionResult,
GitStackedAction,
SourceControlCloneProtocol,
SourceControlProviderDiscoveryItem,
SourceControlProviderKind,
SourceControlPublishRepositoryResult,
SourceControlRepositoryVisibility,
VcsStatusResult,
} from "@t3tools/contracts";
import { useNavigate } from "@tanstack/react-router";
import * as Option from "effect/Option";
import {
type MouseEvent,
useCallback,
useEffect,
useEffectEvent,
useMemo,
useRef,
useState,
} from "react";
import { flushSync } from "react-dom";
import {
CheckIcon,
ChevronDownIcon,
CloudDownloadIcon,
CloudUploadIcon,
FileDiffIcon,
GitBranchPlusIcon,
GitCommitIcon,
InfoIcon,
LockIcon,
GlobeIcon,
} from "lucide-react";
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
import {
AzureDevOpsIcon,
BitbucketIcon,
GitHubIcon,
GitLabIcon,
ForgejoIcon,
GitCafeIcon,
} from "~/components/Icons";
import { RadioGroup } from "~/components/ui/radio-group";
import { Spinner } from "~/components/ui/spinner";
import { Toggle, ToggleGroup } from "~/components/ui/toggle-group";
import { cn } from "~/lib/utils";
import { useOpenPrLink } from "~/lib/openPullRequestLink";
import {
buildMenuItems,
formatGitActionElapsed,
GIT_ACTION_SUCCESS_VISIBLE_MS,
type GitActionProgressPresentation,
type GitActionIconName,
type GitActionMenuItem,
type GitQuickAction,
type DefaultBranchConfirmableAction,
requiresDefaultBranchConfirmation,
resolveDefaultBranchActionDialogCopy,
resolveGitActionProgressPresentation,
resolveGitActionResultToastTiming,
resolveLiveThreadBranchUpdate,
resolveThreadBranchMetadataPatch,
resolveQuickAction,
resolveThreadBranchUpdate,
} from "./GitActionsControl.logic";
import { WizardPopup, WizardHeader, WizardSteps, WizardPanel, WizardFooter } from "./ui/wizard";
import { StartTruncatedPath } from "./StartTruncatedPath";
import { Button } from "~/components/ui/button";
import { Checkbox } from "~/components/ui/checkbox";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "~/components/ui/dialog";
import { Group, GroupSeparator } from "~/components/ui/group";
import { Input } from "~/components/ui/input";
import {
Menu,
MenuItem,
MenuItemLabel,
MenuPopup,
MenuSub,
MenuSubTrigger,
MenuSubPopup,
MenuTrigger,
} from "~/components/ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Textarea } from "~/components/ui/textarea";
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { useOpenInPreferredEditor } from "~/editorPreferences";
import {
useGitStackedAction,
useSourceControlActionRunning,
useSourceControlPublishRepositoryAction,
useVcsInitAction,
useVcsPullAction,
} from "~/lib/sourceControlActions";
import { useThreadProjection, useThreadShell } from "~/state/entities";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { useEnvironmentQuery } from "~/state/query";
import { serverEnvironment } from "~/state/server";
import { sourceControlEnvironment } from "~/state/sourceControl";
import { threadEnvironment } from "~/state/threads";
import { useAtomCommand } from "~/state/use-atom-command";
import { vcsActionManager, vcsEnvironment } from "~/state/vcs";
import { randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
import {
THREAD_DETAILS_PANEL_CHEVRON_CLASS,
THREAD_DETAILS_PANEL_ICON_CLASS,
THREAD_DETAILS_PANEL_LABEL_CLASS,
THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
} from "./chat/threadDetailsPanelStyles";
import { getSourceControlPresentation } from "~/sourceControlPresentation";
import { useOpenLink } from "~/browser/useOpenLink";
interface GitActionsControlProps {
presentation?: "toolbar" | "menu";
gitCwd: string | null;
activeThreadRef: ScopedThreadRef | null;
draftId?: DraftId;
/**
* Opens the thread's own change request beside it. Absent when the thread has no project to
* place it against, in which case it still opens in the browser.
*/
onOpenPullRequest?: ((number: number) => void) | undefined;
displayMode?: "toolbar" | "panel";
compact?: boolean;
onOpenChanges?: () => void;
}
interface PendingDefaultBranchAction {
action: DefaultBranchConfirmableAction;
branchName: string;
includesCommit: boolean;
commitMessage?: string;
onConfirmed?: () => void;
filePaths?: string[];
}
type PublishProviderKind = Extract<
SourceControlProviderKind,
"github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops" | "gitcafe"
>;
type GitActionToastId = ReturnType<typeof toastManager.add>;
interface RunGitActionWithToastInput {
action: GitStackedAction;
commitMessage?: string;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: VcsStatusResult | null;
featureBranch?: boolean;
filePaths?: string[];
}
interface InlineGitActionSuccess {
readonly title: string;
readonly description: string | null;
readonly scopeKey: string;
}
const GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS = 250;
type RefreshVcsStatus = (target: {
readonly environmentId: ScopedThreadRef["environmentId"];
readonly input: { readonly cwd: string };
}) => Promise<unknown>;
function requestVcsStatusRefresh(
refresh: RefreshVcsStatus,
environmentId: ScopedThreadRef["environmentId"] | null,
cwd: string | null,
): void {
if (environmentId === null || cwd === null) {
return;
}
void refresh({ environmentId, input: { cwd } });
}
const RUNNING_SOURCE_CONTROL_ACTIONS = ["runStackedAction", "pull", "publishRepository"] as const;
const PUBLISH_PROVIDER_OPTIONS = [
{
value: "forgejo",
label: "Forgejo / Gitea",
description: "Your signed-in server",
host: "your server",
pathPlaceholder: "owner/repo",
Icon: ForgejoIcon,
},
{
value: "github",
label: "GitHub",
description: "github.com",
host: "github.com",
pathPlaceholder: "owner/repo",
Icon: GitHubIcon,
},
{
value: "gitlab",
label: "GitLab",
description: "gitlab.com",
host: "gitlab.com",
pathPlaceholder: "group/project",
Icon: GitLabIcon,
},
{
value: "bitbucket",
label: "Bitbucket",
description: "bitbucket.org",
host: "bitbucket.org",
pathPlaceholder: "workspace/repository",
Icon: BitbucketIcon,
},
{
value: "azure-devops",
label: "Azure DevOps",
description: "dev.azure.com",
host: "dev.azure.com",
pathPlaceholder: "project/repository",
Icon: AzureDevOpsIcon,
},
{
value: "gitcafe",
label: "GitCafe",
description: "git.cafe",
host: "git.cafe",
pathPlaceholder: "owner/repo",
Icon: GitCafeIcon,
},
] as const satisfies ReadonlyArray<{
readonly value: PublishProviderKind;
readonly label: string;
readonly description: string;
readonly host: string;
readonly pathPlaceholder: string;
readonly Icon: typeof GitHubIcon;
}>;
function publishProviderOption(provider: PublishProviderKind) {
return (
PUBLISH_PROVIDER_OPTIONS.find((option) => option.value === provider) ??
PUBLISH_PROVIDER_OPTIONS[0]
);
}
function isPublishProviderKind(
provider: SourceControlProviderKind,
): provider is PublishProviderKind {
return PUBLISH_PROVIDER_OPTIONS.some((option) => option.value === provider);
}
function getPublishProviderReadiness(input: {
provider: PublishProviderKind;
sourceControlProviders: ReadonlyArray<SourceControlProviderDiscoveryItem>;
}): { readonly ready: boolean; readonly hint: string | null } {
const discovered = input.sourceControlProviders.find(
(provider) => provider.kind === input.provider,
);
if (!discovered) {
return {
ready: false,
hint: "Provider status unavailable. Open Settings -> Source Control and rescan.",
};
}
if (discovered.status !== "available") {
return { ready: false, hint: discovered.installHint };
}
if (discovered.auth.status === "unauthenticated") {
return {
ready: false,
hint:
Option.getOrNull(discovered.auth.detail) ??
`${discovered.label} is not authenticated. Open Settings -> Source Control for setup guidance.`,
};
}
return { ready: true, hint: null };
}
function getMenuActionDisabledReason({
item,
gitStatus,
isBusy,
hasPrimaryRemote,
}: {
item: GitActionMenuItem;
gitStatus: VcsStatusResult | null;
isBusy: boolean;
hasPrimaryRemote: boolean;
}): string | null {
if (!item.disabled) return null;
if (isBusy) return "Git action in progress.";
if (!gitStatus) return "Git status is unavailable.";
const hasBranch = gitStatus.refName !== null;
const hasChanges = gitStatus.hasWorkingTreeChanges;
const isAhead = gitStatus.aheadCount > 0;
const isBehind = gitStatus.behindCount > 0;
const terminology = getSourceControlPresentation(gitStatus.sourceControlProvider).terminology;
if (item.id === "commit") {
if (!hasChanges) {
return "Worktree is clean. Make changes before committing.";
}
return "Commit is currently unavailable.";
}
if (item.id === "push") {
if (!hasBranch) {
return "Detached HEAD: check out a branch before pushing.";
}
if (hasChanges) {
return "Commit or stash local changes before pushing.";
}
if (isBehind) {
return "Branch is behind upstream. Pull/rebase before pushing.";
}
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
return 'Add an "origin" remote before pushing.';
}
if (!isAhead) {
return "No local commits to push.";
}
return "Push is currently unavailable.";
}
if (!hasBranch) {
return `Detached HEAD: check out a branch before creating a ${terminology.singular}.`;
}
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
return `Add an "origin" remote before creating a ${terminology.singular}.`;
}
if ((gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) <= 0) {
return `No local commits to include in a ${terminology.singular}.`;
}
if (isBehind) {
return `Branch is behind upstream. Pull/rebase before creating a ${terminology.singular}.`;
}
return `Create ${terminology.singular} is currently unavailable.`;
}
const COMMIT_DIALOG_TITLE = "Commit changes";
const COMMIT_DIALOG_DESCRIPTION =
"Review and confirm your commit. Leave the message blank to auto-generate one.";
function GitActionItemIcon({
icon,
SourceControlIcon,
}: {
icon: GitActionIconName;
SourceControlIcon: ReturnType<typeof getSourceControlPresentation>["Icon"];
}) {
if (icon === "commit") return <GitCommitIcon />;
if (icon === "push") return <CloudUploadIcon />;
return <SourceControlIcon />;
}
function GitQuickActionIcon({
quickAction,
SourceControlIcon,
className = "size-3.5",
}: {
quickAction: GitQuickAction;
className?: string;
SourceControlIcon: ReturnType<typeof getSourceControlPresentation>["Icon"];
}) {
if (quickAction.kind === "open_publish") return <CloudUploadIcon className={className} />;
if (quickAction.kind === "run_pull") return <CloudDownloadIcon className={className} />;
if (quickAction.kind === "run_action") {
if (quickAction.action === "commit") return <GitCommitIcon className={className} />;
if (quickAction.action === "push" || quickAction.action === "commit_push") {
return <CloudUploadIcon className={className} />;
}
return <SourceControlIcon className={className} />;
}
if (quickAction.label === "Commit") return <GitCommitIcon className={className} />;
if (quickAction.label === "Push") return <CloudUploadIcon className={className} />;
return <InfoIcon className={className} />;
}
function GitActionElapsedTime({
startedAtMs,
className,
}: {
startedAtMs: number | null;
className?: string;
}) {
const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
if (startedAtMs === null) {
return;
}
const intervalId = window.setInterval(() => {
setNowMs(Date.now());
}, 1_000);
return () => window.clearInterval(intervalId);
}, [startedAtMs]);
const elapsed = formatGitActionElapsed(startedAtMs, nowMs);
if (!elapsed) {
return null;
}
return <p className={className}>{elapsed}</p>;
}
function GitActionProgressButtonContent({
progress,
isPanel,
}: {
progress: GitActionProgressPresentation;
isPanel: boolean;
}) {
const hasOutput = progress.output !== null;
return (
<div
aria-atomic="false"
aria-live="polite"
className={cn(
"grid min-w-0 flex-1 items-center",
// Pin the title row to the button's minimum content height so output
// expands below it. Panel controls leave 24px after padding and border.
// No row gap: collapsed output must not add height. The panel's elapsed
// counter uses the menu-chevron slot, so it has no trailing column.
isPanel
? "grid-cols-[auto_minmax(0,1fr)] grid-rows-[1.5rem] gap-x-3"
: "grid-cols-[auto_minmax(0,1fr)_auto] grid-rows-[1.25rem] gap-x-2.5 sm:grid-rows-[1rem]",
)}
role="status"
>
<Spinner aria-hidden="true" className="row-start-1 -mx-0.5 shrink-0" />
<p
className={cn(
"row-start-1 min-w-0 truncate text-left",
isPanel && THREAD_DETAILS_PANEL_LABEL_CLASS,
)}
>
{progress.status}
</p>
{!isPanel ? (
<GitActionElapsedTime
startedAtMs={progress.startedAtMs}
className="row-start-1 text-2xs font-normal tabular-nums text-muted-foreground"
/>
) : null}
<div
className={cn(
"col-start-2 grid min-w-0 transition-[grid-template-rows,opacity] duration-200 ease-out motion-reduce:transition-none",
!isPanel && "col-span-2",
hasOutput ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
)}
>
<div className="min-h-0 overflow-hidden">
<Tooltip>
<TooltipTrigger
render={
<p className="truncate pt-0.5 text-left text-2xs font-normal text-muted-foreground" />
}
>
{progress.output}
</TooltipTrigger>
<TooltipPopup side="bottom" className="max-w-96 break-words">
{progress.output}
</TooltipPopup>
</Tooltip>
</div>
</div>
</div>
);
}
function GitActionSuccessButtonContent({ success }: { success: InlineGitActionSuccess }) {
const hasDescription = success.description !== null;
return (
<div
aria-live="polite"
className="grid min-w-0 flex-1 grid-cols-[auto_minmax(0,1fr)] grid-rows-[1.5rem] items-center gap-x-3"
role="status"
>
<CheckIcon aria-hidden="true" className="size-3.5 shrink-0 text-success" />
<p className={cn("min-w-0 truncate text-left", THREAD_DETAILS_PANEL_LABEL_CLASS)}>
{success.title}
</p>
<div
className={cn(
"col-start-2 grid min-w-0 transition-[grid-template-rows,opacity] duration-200 ease-out motion-reduce:transition-none",
hasDescription ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
)}
>
<div className="min-h-0 overflow-hidden">
<Tooltip>
<TooltipTrigger
render={
<p className="truncate pt-0.5 text-left text-2xs font-normal text-muted-foreground" />
}
>
{success.description}
</TooltipTrigger>
<TooltipPopup side="bottom" className="max-w-96 break-words">
{success.description}
</TooltipPopup>
</Tooltip>
</div>
</div>
</div>
);
}
interface PublishRepositoryDialogProps {
readonly open: boolean;
readonly onOpenChange: (open: boolean) => void;
readonly environmentId: ScopedThreadRef["environmentId"] | null;
/** Thread the dialog was opened from, so the new repository can open beside it. */
readonly threadRef: ScopedThreadRef | null;
readonly gitCwd: string;
}
function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const openLink = useOpenLink(props.threadRef);
const navigate = useNavigate();
const sourceControlDiscovery = useEnvironmentQuery(
props.environmentId === null
? null
: sourceControlEnvironment.discovery({
environmentId: props.environmentId,
input: {},
}),
);
const [selectedPublishProvider, setSelectedPublishProvider] =
useState<PublishProviderKind | null>(null);
const [publishRepositoryOverride, setPublishRepositoryOverride] = useState<string | null>(null);
const [publishVisibility, setPublishVisibility] =
useState<SourceControlRepositoryVisibility>("private");
const [publishRemoteName, setPublishRemoteName] = useState("origin");
const [publishProtocol, setPublishProtocol] = useState<SourceControlCloneProtocol>("ssh");
const [publishWizardStep, setPublishWizardStep] = useState(0);
const [publishAdvancedOpen, setPublishAdvancedOpen] = useState(false);
const [publishError, setPublishError] = useState<string | null>(null);
const [publishResult, setPublishResult] = useState<SourceControlPublishRepositoryResult | null>(
null,
);
const sourceControlScope = useMemo(
() => ({
environmentId: props.environmentId,
cwd: props.gitCwd,
}),
[props.environmentId, props.gitCwd],
);
const publishRepositoryAction = useSourceControlPublishRepositoryAction(sourceControlScope);
const publishAccountByProvider = useMemo(() => {
const accounts: Record<PublishProviderKind, string | null> = {
github: null,
gitlab: null,
forgejo: null,
bitbucket: null,
"azure-devops": null,
gitcafe: null,
};
for (const provider of sourceControlDiscovery.data?.sourceControlProviders ?? []) {
if (isPublishProviderKind(provider.kind)) {
accounts[provider.kind] = Option.getOrNull(provider.auth.account);
}
}
return accounts;
}, [sourceControlDiscovery.data]);
const publishProviderReadiness = useMemo(() => {
const sourceControlProviders = sourceControlDiscovery.data?.sourceControlProviders ?? [];
return Object.fromEntries(
PUBLISH_PROVIDER_OPTIONS.map((option) => [
option.value,
getPublishProviderReadiness({
provider: option.value,
sourceControlProviders,
}),
]),
) as Record<PublishProviderKind, { readonly ready: boolean; readonly hint: string | null }>;
}, [sourceControlDiscovery.data]);
const hasReadyPublishProvider = useMemo(
() => PUBLISH_PROVIDER_OPTIONS.some((option) => publishProviderReadiness[option.value].ready),
[publishProviderReadiness],
);
const sortedPublishProviderOptions = useMemo(
() =>
PUBLISH_PROVIDER_OPTIONS.toSorted((left, right) => {
const leftReady = publishProviderReadiness[left.value].ready;
const rightReady = publishProviderReadiness[right.value].ready;
if (leftReady !== rightReady) {
return leftReady ? -1 : 1;
}
return left.label.localeCompare(right.label);
}),
[publishProviderReadiness],
);
const firstReadyPublishProvider = sortedPublishProviderOptions.find(
(option) => publishProviderReadiness[option.value].ready,
)?.value;
const publishProvider =
selectedPublishProvider !== null && publishProviderReadiness[selectedPublishProvider].ready
? selectedPublishProvider
: (firstReadyPublishProvider ?? selectedPublishProvider ?? "github");
const selectedPublishProviderReadiness = publishProviderReadiness[publishProvider];
const publishRepositoryPrefill = publishAccountByProvider[publishProvider]
? `${publishAccountByProvider[publishProvider]}/`
: "";
const publishRepository = publishRepositoryOverride ?? publishRepositoryPrefill;
const currentPublishProvider = publishProviderOption(publishProvider);
const publishHost =
publishProvider === "forgejo"
? (Option.getOrNull(
sourceControlDiscovery.data?.sourceControlProviders.find(
(provider) => provider.kind === "forgejo",
)?.auth.host ?? Option.none(),
) ?? currentPublishProvider.host)
: currentPublishProvider.host;
const publishPathPlaceholder = currentPublishProvider.pathPlaceholder;
const publishProviderLabel = currentPublishProvider.label;
const publishWizardSteps = ["Provider", "Repository", "Summary"] as const;
const publishWizardStepSummaries = [
publishProviderLabel,
publishResult?.repository.nameWithOwner ?? null,
null,
] as const;
const canSubmitPublishRepository = useMemo(() => {
if (!publishRepositoryAction.isAllowed || !selectedPublishProviderReadiness.ready) return false;
if (publishRepositoryAction.isPending) return false;
const repositoryParts = publishRepository.trim().split("/");
const owner = repositoryParts[0]?.trim() ?? "";
const rest = repositoryParts.slice(1);
const name = rest.join("/").trim();
return owner.length > 0 && name.length > 0;
}, [
publishRepository,
publishRepositoryAction.isAllowed,
publishRepositoryAction.isPending,
selectedPublishProviderReadiness,
]);
const submitPublishRepository = useCallback(() => {
if (!canSubmitPublishRepository) {
return;
}
setPublishError(null);
void (async () => {
const result = await publishRepositoryAction.run({
provider: publishProvider,
repository: publishRepository.trim(),
visibility: publishVisibility,
remoteName: publishRemoteName.trim() || "origin",
protocol: publishProtocol,
});
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
setPublishError(error instanceof Error ? error.message : "An error occurred.");
}
return;
}
flushSync(() => {
setPublishResult(result.value);
setPublishWizardStep(2);
});
})();
}, [
canSubmitPublishRepository,
props.environmentId,
props.gitCwd,
publishProtocol,
publishProvider,
publishRemoteName,
publishRepository,
publishRepositoryAction,
publishVisibility,
]);
const resetState = useCallback(() => {
setPublishRemoteName("origin");
setPublishRepositoryOverride(null);
setPublishWizardStep(0);
setPublishAdvancedOpen(false);
setPublishError(null);
setPublishResult(null);
}, []);
const handleOpenChange = useCallback(
(open: boolean) => {
props.onOpenChange(open);
if (!open) {
resetState();
}
},
[props, resetState],
);
const openSourceControlSettings = useCallback(() => {
handleOpenChange(false);
void navigate({ to: "/settings/source-control" });
}, [handleOpenChange, navigate]);
return (
<Dialog open={props.open} onOpenChange={handleOpenChange}>
<WizardPopup>
<WizardHeader
title="Publish repository"
description="Pick where to host it, then point us at a repo to push to."
>
<WizardSteps
steps={publishWizardSteps}
currentStep={publishWizardStep}
summaries={publishWizardStepSummaries}
showSummaries
isStepDisabled={(index) =>
publishWizardStep === 2 ||
index >= publishWizardSteps.length - 1 ||
index > publishWizardStep
}
onStepChange={setPublishWizardStep}
/>
</WizardHeader>
<WizardPanel>
<div className={cn("space-y-2", publishWizardStep !== 0 && "hidden")}>
<span id="publish-provider-cards-label" className="text-xs font-medium text-foreground">
Provider
</span>
<RadioGroup
value={publishProvider}
onValueChange={(value) => {
setSelectedPublishProvider(value as PublishProviderKind);
setPublishRepositoryOverride(null);
}}
aria-labelledby="publish-provider-cards-label"
className="grid grid-cols-2"
>
{sortedPublishProviderOptions.map((option) => {
const readiness = publishProviderReadiness[option.value];
const isSelected = publishProvider === option.value && readiness.ready;
if (!readiness.ready) {
return (
<div
key={option.value}
className="relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-64 dark:border-transparent dark:bg-white/[0.035]"
>
<option.Icon className="size-5 shrink-0 text-muted-foreground" aria-hidden />
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
<Tooltip>
<TooltipTrigger
render={
<Button
variant="warning-outline"
size="micro"
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
openSourceControlSettings();
}}
>
Setup Required
</Button>
}
/>
<TooltipPopup side="top" align="end">
{readiness.hint ??
"Open Settings -> Source Control to configure this provider."}
</TooltipPopup>
</Tooltip>
</div>
);
}
return (
<RadioPrimitive.Root
key={option.value}
value={option.value}
className={cn(
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
"focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
isSelected
? "border-primary bg-background shadow-sm ring-2 ring-inset ring-primary/35 dark:border-transparent dark:bg-primary/10 dark:shadow-none dark:ring-1 dark:ring-primary/30"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50 dark:border-transparent dark:bg-white/[0.035] dark:hover:bg-accent",
)}
>
<option.Icon className="size-5 shrink-0" aria-hidden />
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
</RadioPrimitive.Root>
);
})}
</RadioGroup>
</div>
<div className={cn("space-y-5", publishWizardStep !== 1 && "hidden")}>
<div className="space-y-2">
<label
htmlFor="publish-repository-path"
className="text-xs font-medium text-foreground"
>
Repository
</label>
<div className="flex items-stretch overflow-hidden rounded-md border border-input bg-background focus-within:outline-2 focus-within:-outline-offset-2 focus-within:outline-ring">
<span className="flex shrink-0 items-center gap-1.5 border-r border-input bg-muted/50 px-2.5 font-mono text-xs text-muted-foreground">
<currentPublishProvider.Icon className="size-3.5" />
{publishHost}/
</span>
<input
id="publish-repository-path"
name="publish-repository-path"
value={publishRepository}
onChange={(event) => {
setPublishRepositoryOverride(event.target.value);
}}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
submitPublishRepository();
}
}}
placeholder={publishPathPlaceholder}
disabled={publishRepositoryAction.isPending}
className="w-full bg-transparent px-3 py-2 font-mono text-sm placeholder:text-muted-foreground/60 focus:outline-none"
/>
</div>
</div>
<div className="space-y-2">
<span
id="publish-visibility-cards-label"
className="text-xs font-medium text-foreground"
>
Visibility
</span>
<RadioGroup
value={publishVisibility}
onValueChange={(value) =>
setPublishVisibility(value as SourceControlRepositoryVisibility)
}
aria-labelledby="publish-visibility-cards-label"
disabled={publishRepositoryAction.isPending}
className="grid grid-cols-2"
>
{[
{
value: "private" as const,
label: "Private",
description: "Only invited people",
Icon: LockIcon,
},
{
value: "public" as const,
label: "Public",
description: "Anyone on the web",
Icon: GlobeIcon,
},
].map((option) => {
const isSelected = publishVisibility === option.value;
return (
<RadioPrimitive.Root
key={option.value}
value={option.value}
className={cn(
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2.5 text-left outline-none transition-[background-color,border-color,box-shadow]",
"focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
isSelected
? "border-primary bg-background shadow-sm ring-2 ring-inset ring-primary/35 dark:border-transparent dark:bg-primary/10 dark:shadow-none dark:ring-1 dark:ring-primary/30"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50 dark:border-transparent dark:bg-white/[0.035] dark:hover:bg-accent",
)}
>
<option.Icon className="size-4 shrink-0 text-muted-foreground" aria-hidden />
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium text-foreground">
{option.label}
</span>
<span className="block text-xs text-muted-foreground">
{option.description}
</span>
</span>
</RadioPrimitive.Root>
);
})}
</RadioGroup>
</div>
<div>
<button
type="button"
onClick={() => setPublishAdvancedOpen((prev) => !prev)}
aria-expanded={publishAdvancedOpen}
className="flex items-center gap-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
>
<ChevronDownIcon
className={cn(
"size-3.5 transition-transform",
publishAdvancedOpen ? "" : "-rotate-90",
)}
/>
Advanced
</button>
{publishAdvancedOpen ? (
<div className="mt-3 grid gap-3 sm:grid-cols-2">
<label className="space-y-1.5" htmlFor="publish-remote-name">
<span className="text-xs font-medium text-foreground">Remote</span>
<Input
id="publish-remote-name"
value={publishRemoteName}
onChange={(event) => setPublishRemoteName(event.target.value)}
placeholder="origin"
disabled={publishRepositoryAction.isPending}
/>
</label>
<div className="space-y-1.5">
<span
id="publish-protocol-label"
className="text-xs font-medium text-foreground"
>
Protocol
</span>
<ToggleGroup
value={[publishProtocol]}
onValueChange={(next) => {
const protocol = next[0];
if (protocol === "ssh" || protocol === "https") {
setPublishProtocol(protocol);
}
}}
aria-labelledby="publish-protocol-label"
disabled={publishRepositoryAction.isPending}
>
<Toggle value="ssh">SSH</Toggle>
<Toggle value="https">HTTPS</Toggle>
</ToggleGroup>
</div>
</div>
) : null}
</div>
{publishRepositoryAction.isPending ? (
<div
role="status"
aria-live="polite"
className="flex items-center gap-2 rounded-md border border-input bg-muted/40 px-3 py-2 text-xs text-muted-foreground dark:border-transparent dark:bg-white/[0.035]"
>
<Spinner size="sm" aria-hidden />
Publishing repository to {publishProviderLabel}...
</div>
) : null}
{publishError && !publishRepositoryAction.isPending ? (
<div
role="alert"
className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
>
<p className="font-medium">Publish failed</p>
<p className="mt-0.5 text-destructive/90">{publishError}</p>
</div>
) : null}
</div>
<div className={cn("space-y-4", publishWizardStep !== 2 && "hidden")}>
{publishResult ? (
<>
<div className="flex flex-col items-center gap-2 py-1 text-center">
<span className="grid size-8 place-items-center rounded-full bg-success/15 text-success">
<CheckIcon className="size-4" aria-hidden />
</span>
<h3 className="text-sm font-semibold text-foreground">
{publishResult.status === "pushed"
? "Repository published"
: "Repository created"}
</h3>
<p className="max-w-xs text-pretty text-xs text-muted-foreground">
{publishResult.status === "pushed"
? `${publishResult.branch} is now live on ${publishProviderLabel}.`
: `Remote "${publishResult.remoteName}" is set up. Make a commit and push it to share your code.`}
</p>
</div>
<div className="flex items-center gap-2 rounded-lg border border-input bg-muted/40 px-3 py-2 dark:border-transparent dark:bg-white/[0.035]">
<currentPublishProvider.Icon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">
{publishResult.repository.nameWithOwner}
</span>
</div>
<Button
variant="outline"
size="sm"
className="w-full"
onClick={() => {
void openLink(publishResult.repository.url).catch(() => undefined);
}}
>
Open on {publishProviderLabel}
</Button>
</>
) : (
<div className="rounded-md border border-input bg-background px-3 py-2 text-xs text-muted-foreground dark:border-transparent dark:bg-white/[0.035]">
Publish result unavailable.
</div>
)}
</div>
</WizardPanel>
<WizardFooter>
{publishWizardStep === 2 ? (
<Button onClick={() => handleOpenChange(false)}>Done</Button>
) : (
<>
<Button
variant="outline"
disabled={publishRepositoryAction.isPending}
onClick={() => {
if (publishWizardStep === 0) {
handleOpenChange(false);
return;
}
setPublishWizardStep((step) => Math.max(0, step - 1));
}}
>
{publishWizardStep === 0 ? "Cancel" : "Back"}
</Button>
{publishWizardStep < 1 ? (
<Button
disabled={!hasReadyPublishProvider || !selectedPublishProviderReadiness.ready}
onClick={() => setPublishWizardStep((step) => Math.min(1, step + 1))}
>
Next
</Button>
) : (
<Button disabled={!canSubmitPublishRepository} onClick={submitPublishRepository}>
{publishRepositoryAction.isPending ? (
<>
<Spinner size="sm" aria-hidden />
Publishing...
</>
) : (
"Publish"
)}
</Button>
)}
</>
)}
</WizardFooter>
</WizardPopup>
</Dialog>
);
}
export default function GitActionsControl({
presentation = "toolbar",
gitCwd,
activeThreadRef,
draftId,
displayMode = "toolbar",
compact = false,
onOpenChanges,
}: GitActionsControlProps) {
const isPanel = displayMode === "panel";
const ActionGroup = isPanel ? "div" : Group;
const panelAnchorRef = useRef<HTMLDivElement | null>(null);
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
"thread branch metadata update",
);
const activeEnvironmentId = activeThreadRef?.environmentId ?? null;
const successScopeKey = `${activeEnvironmentId ?? ""}\u0000${gitCwd ?? ""}`;
const canWriteSourceControl = useEnvironmentScope(
activeEnvironmentId,
AuthSourceControlWriteScope,
);
const canOperateThread = useEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope);
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(activeEnvironmentId));
const openInPreferredEditor = useOpenInPreferredEditor(
activeEnvironmentId,
serverConfig?.availableEditors ?? [],
);
const threadToastData = useMemo(
() => (activeThreadRef ? { threadRef: activeThreadRef } : undefined),
[activeThreadRef],
);
const activeServerThreadShell = useThreadShell(activeThreadRef);
const openPrLink = useOpenPrLink(activeThreadRef ?? undefined);
const activeDraftThread = useComposerDraftStore((store) =>
draftId
? store.getDraftSession(draftId)
: activeThreadRef
? store.getDraftThreadByRef(activeThreadRef)
: null,
);
const activeServerThreadProjection = useThreadProjection(
activeDraftThread !== null && activeServerThreadShell === null ? null : activeThreadRef,
);
const activeServerThread =
activeServerThreadShell ?? activeServerThreadProjection?.projection.thread ?? null;
const isLocalDraftThread = activeDraftThread !== null && activeServerThread === null;
const canChangeThreadBranch = canWriteSourceControl && (isLocalDraftThread || canOperateThread);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
const [isEditingFiles, setIsEditingFiles] = useState(false);
const [isPublishDialogOpen, setIsPublishDialogOpen] = useState(false);
const [inlineSuccess, setInlineSuccess] = useState<InlineGitActionSuccess | null>(null);
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const sourceControlScope = useMemo(
() => ({ environmentId: activeEnvironmentId, cwd: gitCwd }),
[activeEnvironmentId, gitCwd],
);
const vcsActionState = useAtomValue(vcsActionManager.stateAtom(sourceControlScope));
const visibleInlineSuccess = inlineSuccess?.scopeKey === successScopeKey ? inlineSuccess : null;
let runGitActionWithToast: (input: RunGitActionWithToastInput) => Promise<void>;
useEffect(() => {
if (!inlineSuccess) return;
const timeoutId = window.setTimeout(() => {
setInlineSuccess(null);
}, GIT_ACTION_SUCCESS_VISIBLE_MS);
return () => window.clearTimeout(timeoutId);
}, [inlineSuccess]);
const persistThreadBranchSync = useCallback(
(branch: string | null, manualSelection = false) => {
if (!activeThreadRef) {
return;
}
if (activeServerThread) {
if (
!readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) ||
activeServerThread.branch === branch
) {
return;
}
void updateThreadMetadata({
environmentId: activeThreadRef.environmentId,
input: {
threadId: activeThreadRef.threadId,
...resolveThreadBranchMetadataPatch(branch, activeServerThread.branch),
},
});
return;
}
if (!activeDraftThread || activeDraftThread.branch === branch) {
return;
}
setDraftThreadContext(draftId ?? activeThreadRef, {
branch,
worktreePath: activeDraftThread.worktreePath,
environmentSelection: manualSelection
? "manual"
: (activeDraftThread.environmentSelection ??
(activeDraftThread.branch ? "manual" : "auto")),
});
},
[
activeDraftThread,
activeServerThread,
activeThreadRef,
draftId,
setDraftThreadContext,
updateThreadMetadata,
],
);
const syncThreadBranchAfterGitAction = useCallback(
(result: GitRunStackedActionResult) => {
const branchUpdate = resolveThreadBranchUpdate(result);
if (!branchUpdate) {
return;
}
persistThreadBranchSync(branchUpdate.branch, true);
},
[persistThreadBranchSync],
);
const gitStatusQuery = useEnvironmentQuery(
activeEnvironmentId !== null && gitCwd !== null
? vcsEnvironment.status({
environmentId: activeEnvironmentId,
input: { cwd: gitCwd },
})
: null,
);
const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
reportFailure: false,
});
const { data: gitStatus, error: gitStatusError } = gitStatusQuery;
const sourceControlPresentation = useMemo(
() => getSourceControlPresentation(gitStatus?.sourceControlProvider),
[gitStatus?.sourceControlProvider],
);
const changeRequestTerminology = sourceControlPresentation.terminology;
const SourceControlIcon = sourceControlPresentation.Icon;
// Default to true while loading so we don't flash init controls.
const isRepo = gitStatus?.isRepo ?? true;
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
const gitStatusForActions = gitStatus;
// Matches the diff panel's Changes view. Older servers only report uncommitted totals.
const changesTotals = gitStatusForActions?.branchChanges ?? gitStatusForActions?.workingTree;
const allFiles = gitStatusForActions?.workingTree.files ?? [];
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
const allSelected = excludedFiles.size === 0;
const noneSelected = selectedFiles.length === 0;
const initAction = useVcsInitAction(sourceControlScope);
const runImmediateGitAction = useGitStackedAction(sourceControlScope);
const pullAction = useVcsPullAction(sourceControlScope);
const isGitActionRunning = useSourceControlActionRunning(
sourceControlScope,
RUNNING_SOURCE_CONTROL_ACTIONS,
);
const isSelectingWorktreeBase =
!activeServerThread &&
activeDraftThread?.envMode === "worktree" &&
activeDraftThread.worktreePath === null;
useEffect(() => {
if (isGitActionRunning || isSelectingWorktreeBase || activeServerThread) {
return;
}
const branchUpdate = resolveLiveThreadBranchUpdate({
threadBranch: activeDraftThread?.branch ?? null,
gitStatus: gitStatusForActions,
});
if (!branchUpdate) {
return;
}
persistThreadBranchSync(branchUpdate.branch);
}, [
activeServerThread,
activeDraftThread?.branch,
gitStatusForActions,
isGitActionRunning,
isSelectingWorktreeBase,
persistThreadBranchSync,
]);
const isDefaultRef = useMemo(() => {
return gitStatusForActions?.isDefaultRef ?? false;
}, [gitStatusForActions?.isDefaultRef]);
const gitActionMenuItems = useMemo(
() => buildMenuItems(gitStatusForActions, isGitActionRunning, hasPrimaryRemote),
[gitStatusForActions, hasPrimaryRemote, isGitActionRunning],
);
const quickAction = useMemo(
() =>
resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultRef, hasPrimaryRemote),
[gitStatusForActions, hasPrimaryRemote, isDefaultRef, isGitActionRunning],
);
const quickActionDisabledReason = !canWriteSourceControl
? "This connection cannot change source control."
: quickAction.disabled
? (quickAction.hint ?? "This action is currently unavailable.")
: null;
const gitActionProgress = resolveGitActionProgressPresentation(vcsActionState);
const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
? resolveDefaultBranchActionDialogCopy({
action: pendingDefaultBranchAction.action,
branchName: pendingDefaultBranchAction.branchName,
includesCommit: pendingDefaultBranchAction.includesCommit,
terminology: changeRequestTerminology,
})
: null;
useEffect(() => {
if (gitCwd === null) {
return;
}
let refreshTimeout: number | null = null;
const scheduleRefreshCurrentGitStatus = () => {
if (refreshTimeout !== null) {
window.clearTimeout(refreshTimeout);
}
refreshTimeout = window.setTimeout(() => {
refreshTimeout = null;
requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd);
}, GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS);
};
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
scheduleRefreshCurrentGitStatus();
}
};
window.addEventListener("focus", scheduleRefreshCurrentGitStatus);
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
if (refreshTimeout !== null) {
window.clearTimeout(refreshTimeout);
}
window.removeEventListener("focus", scheduleRefreshCurrentGitStatus);
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, [activeEnvironmentId, gitCwd, refreshVcsStatus]);
runGitActionWithToast = useEffectEvent(
async ({
action,
commitMessage,
onConfirmed,
skipDefaultBranchPrompt = false,
statusOverride,
featureBranch = false,
filePaths,
}: RunGitActionWithToastInput) => {
if (
activeEnvironmentId === null ||
!readEnvironmentScope(activeEnvironmentId, AuthSourceControlWriteScope) ||
(featureBranch &&
!isLocalDraftThread &&
!readEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope))
)
return;
const actionStatus = statusOverride ?? gitStatusForActions;
const actionBranch = actionStatus?.refName ?? null;
const actionIsDefaultBranch = featureBranch ? false : isDefaultRef;
const actionCanCommit =
action === "commit" || action === "commit_push" || action === "commit_push_pr";
const includesCommit =
actionCanCommit &&
(action === "commit" || !!actionStatus?.hasWorkingTreeChanges || featureBranch);
if (
!skipDefaultBranchPrompt &&
requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
actionBranch
) {
if (
action !== "push" &&
action !== "create_pr" &&
action !== "commit_push" &&
action !== "commit_push_pr"
) {
return;
}
setPendingDefaultBranchAction({
action,
branchName: actionBranch,
includesCommit,
...(commitMessage ? { commitMessage } : {}),
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
});
return;
}
onConfirmed?.();
setInlineSuccess(null);
const scopedToastData = threadToastData ? { ...threadToastData } : undefined;
const actionId = randomUUID();
const result = await runImmediateGitAction.run({
actionId,
action,
...(commitMessage ? { commitMessage } : {}),
...(featureBranch ? { featureBranch } : {}),
...(filePaths ? { filePaths } : {}),
// A pull request the action opens is linked to the thread it ran beside. Drafts
// have no server thread yet, so there is nothing to link to.
...(activeServerThread ? { threadId: activeServerThread.id } : {}),
...(activeDraftThread ? { projectId: activeDraftThread.projectId } : {}),
});
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
const errorToastTiming = resolveGitActionResultToastTiming("error");
toastManager.add(
stackedThreadToast({
type: "error",
title: "Action failed",
description: error instanceof Error ? error.message : "An error occurred.",
timeout: errorToastTiming.timeout,
...(scopedToastData !== undefined ? { data: scopedToastData } : {}),
}),
);
return;
}
const actionResult = result.value;
syncThreadBranchAfterGitAction(actionResult);
if (isPanel) {
setInlineSuccess({
title: actionResult.toast.title,
description: actionResult.toast.description ?? null,
scopeKey: successScopeKey,
});
return;
}
let resultToastId: GitActionToastId | null = null;
const closeResultToast = () => {
if (resultToastId !== null) {
toastManager.close(resultToastId);
}
};
const toastCta = actionResult.toast.cta;
let toastActionProps: {
children: string;
onClick: (event: MouseEvent<HTMLButtonElement>) => void;
} | null = null;
if (toastCta.kind === "run_action") {
toastActionProps = {
children: toastCta.label,
onClick: () => {
closeResultToast();
void runGitActionWithToast({
action: toastCta.action.kind,
});
},
};
} else if (toastCta.kind === "open_pr") {
toastActionProps = {
children: toastCta.label,
onClick: (event) => {
closeResultToast();
openPrLink(event, toastCta.url);
},
};
}
const successToastTiming = resolveGitActionResultToastTiming("success");
const successToastData = {
...scopedToastData,
...(successToastTiming.dismissAfterVisibleMs !== null
? { dismissAfterVisibleMs: successToastTiming.dismissAfterVisibleMs }
: {}),
};
if (toastActionProps) {
resultToastId = toastManager.add(
stackedThreadToast({
type: "success",
title: actionResult.toast.title,
description: actionResult.toast.description,
timeout: successToastTiming.timeout,
actionProps: toastActionProps,
data: successToastData,
}),
);
} else {
resultToastId = toastManager.add({
type: "success",
title: actionResult.toast.title,
description: actionResult.toast.description,
timeout: successToastTiming.timeout,
data: successToastData,
});
}
},
);
const continuePendingDefaultBranchAction = () => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
skipDefaultBranchPrompt: true,
});
};
const checkoutFeatureBranchAndContinuePendingAction = () => {
if (!canChangeThreadBranch || !pendingDefaultBranchAction) return;
const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
featureBranch: true,
skipDefaultBranchPrompt: true,
});
};
const runDialogActionOnNewBranch = () => {
if (!canChangeThreadBranch || !isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
setExcludedFiles(new Set());
setIsEditingFiles(false);
void runGitActionWithToast({
action: "commit",
...(commitMessage ? { commitMessage } : {}),
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
featureBranch: true,
skipDefaultBranchPrompt: true,
});
};
const runQuickAction = () => {
if (quickAction.kind === "open_publish") {
setIsPublishDialogOpen(true);
return;
}
if (quickAction.kind === "run_pull") {
void (async () => {
setInlineSuccess(null);
const result = await pullAction.run();
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
const errorToastTiming = resolveGitActionResultToastTiming("error");
toastManager.add(
stackedThreadToast({
type: "error",
title: "Pull failed",
description: error instanceof Error ? error.message : "An error occurred.",
timeout: errorToastTiming.timeout,
...(threadToastData !== undefined ? { data: threadToastData } : {}),
}),
);
return;
}
const pullResult = result.value;
const title = pullResult.status === "pulled" ? "Pulled" : "Already up to date";
const description =
pullResult.status === "pulled"
? `Updated ${pullResult.refName} from ${pullResult.upstreamRef ?? "upstream"}`
: `${pullResult.refName} is already synchronized.`;
if (isPanel) {
setInlineSuccess({ title, description, scopeKey: successScopeKey });
return;
}
const successToastTiming = resolveGitActionResultToastTiming("success");
toastManager.add({
type: "success",
title,
description,
timeout: successToastTiming.timeout,
data: {
...threadToastData,
...(successToastTiming.dismissAfterVisibleMs !== null
? { dismissAfterVisibleMs: successToastTiming.dismissAfterVisibleMs }
: {}),
},
});
})();
return;
}
if (quickAction.kind === "show_hint") {
toastManager.add({
type: "info",
title: quickAction.label,
description: quickAction.hint,
data: threadToastData,
});
return;
}
if (quickAction.action) {
void runGitActionWithToast({ action: quickAction.action });
}
};
const openDialogForMenuItem = (item: GitActionMenuItem) => {
if (item.disabled) return;
if (item.dialogAction === "push") {
void runGitActionWithToast({ action: "push" });
return;
}
if (item.dialogAction === "create_pr") {
void runGitActionWithToast({ action: "create_pr" });
return;
}
setExcludedFiles(new Set());
setIsEditingFiles(false);
setIsCommitDialogOpen(true);
};
const runDialogAction = () => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
setExcludedFiles(new Set());
setIsEditingFiles(false);
void runGitActionWithToast({
action: "commit",
...(commitMessage ? { commitMessage } : {}),
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
});
};
const openChangedFileInEditor = useCallback(
(filePath: string) => {
if (!gitCwd) {
toastManager.add({
type: "error",
title: "Editor opening is unavailable.",
data: threadToastData,
});
return;
}
const target = resolvePathLinkTarget(filePath, gitCwd);
void (async () => {
const result = await openInPreferredEditor(target);
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open file",
description: error instanceof Error ? error.message : "An error occurred.",
...(threadToastData !== undefined ? { data: threadToastData } : {}),
}),
);
})();
},
[gitCwd, openInPreferredEditor, threadToastData],
);
const canPublishRepository =
canWriteSourceControl && isRepo && gitStatusForActions !== null && !hasPrimaryRemote;
const initializeGit = () => {
void (async () => {
const result = await initAction.run();
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Git initialization failed",
description: error instanceof Error ? error.message : "An error occurred.",
...(threadToastData !== undefined ? { data: threadToastData } : {}),
}),
);
})();
};
const gitItems = (
<>
{gitActionMenuItems.map((item) => {
const disabledReason = getMenuActionDisabledReason({
item,
gitStatus: gitStatusForActions,
isBusy: isGitActionRunning,
hasPrimaryRemote,
});
if (item.disabled && disabledReason && presentation === "menu") {
return (
<div key={`${item.id}-${item.label}`}>
<MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
<GitActionItemIcon icon={item.icon} SourceControlIcon={SourceControlIcon} />
<MenuItemLabel>{item.label}</MenuItemLabel>
</MenuItem>
<p className="max-w-64 px-2 pb-2 text-xs text-muted-foreground">{disabledReason}</p>
</div>
);
}
if (item.disabled && disabledReason) {
return (
<Popover key={`${item.id}-${item.label}`}>
<PopoverTrigger
openOnHover
nativeButton={false}
render={<span className="block w-full cursor-not-allowed" />}
>
<MenuItem
density={presentation === "menu" ? "touch" : "default"}
className="w-full"
disabled
>
<GitActionItemIcon icon={item.icon} SourceControlIcon={SourceControlIcon} />
<MenuItemLabel>{item.label}</MenuItemLabel>
</MenuItem>
</PopoverTrigger>
<PopoverPopup tooltipStyle side="left" align="center">
{disabledReason}
</PopoverPopup>
</Popover>
);
}
return (
<MenuItem
density={presentation === "menu" ? "touch" : "default"}
key={`${item.id}-${item.label}`}
disabled={!canWriteSourceControl || item.disabled}
onClick={() => {
openDialogForMenuItem(item);
}}
>
<GitActionItemIcon icon={item.icon} SourceControlIcon={SourceControlIcon} />
<MenuItemLabel>{item.label}</MenuItemLabel>
</MenuItem>
);
})}
{canPublishRepository ? (
<MenuItem
density={presentation === "menu" ? "touch" : "default"}
disabled={isGitActionRunning}
onClick={() => {
setIsPublishDialogOpen(true);
}}
>
<CloudUploadIcon />
<MenuItemLabel>Publish repository...</MenuItemLabel>
</MenuItem>
) : null}
{gitStatusForActions?.refName === null && (
<p className="px-2 py-1.5 text-xs text-warning">
Detached HEAD: create and check out a branch to enable push and pull request actions.
</p>
)}
{gitStatusForActions &&
gitStatusForActions.refName !== null &&
!gitStatusForActions.hasWorkingTreeChanges &&
gitStatusForActions.behindCount > 0 &&
gitStatusForActions.aheadCount === 0 && (
<p className="px-2 py-1.5 text-xs text-warning">Behind upstream. Pull/rebase first.</p>
)}
{gitStatusError && <p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError}</p>}
</>
);
if (!gitCwd) return null;
return (
<>
{presentation === "menu" ? (
!isRepo ? (
<MenuItem
density={presentation === "menu" ? "touch" : "default"}
disabled={initAction.isPending}
onClick={initializeGit}
>
<GitBranchPlusIcon className="size-4" />
<MenuItemLabel>
{initAction.isPending ? "Initializing..." : "Initialize Git"}
</MenuItemLabel>
</MenuItem>
) : (
<>
<MenuItem
density={presentation === "menu" ? "touch" : "default"}
disabled={isGitActionRunning || quickAction.disabled || !!quickActionDisabledReason}
onClick={runQuickAction}
>
<GitQuickActionIcon
className="size-4"
quickAction={quickAction}
SourceControlIcon={SourceControlIcon}
/>
<MenuItemLabel>{quickAction.label}</MenuItemLabel>
</MenuItem>
{quickActionDisabledReason && (
<p className="max-w-64 px-2 py-1.5 text-xs text-warning">
{quickActionDisabledReason}
</p>
)}
<MenuSub
onOpenChange={(open) => {
if (open) requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd);
}}
>
<MenuSubTrigger density="touch" disabled={isGitActionRunning}>
<SourceControlIcon className="size-4" />
<MenuItemLabel>Git actions</MenuItemLabel>
</MenuSubTrigger>
<MenuSubPopup>{gitItems}</MenuSubPopup>
</MenuSub>
</>
)
) : !isRepo ? (
<ThreadDetailsControl
size="xs"
variant={isPanel ? "ghost" : "outline"}
part="row"
panel={isPanel}
disabled={!canWriteSourceControl || initAction.isPending}
onClick={initializeGit}
>
<GitBranchPlusIcon className="size-3.5" aria-hidden />
<span className={cn("ml-0.5", isPanel && THREAD_DETAILS_PANEL_LABEL_CLASS)}>
{initAction.isPending ? "Initializing..." : "Initialize Git"}
</span>
</ThreadDetailsControl>
) : compact && !gitActionProgress && !visibleInlineSuccess ? null : (
<ActionGroup
role="group"
aria-label="Git actions"
{...(isPanel ? { ref: panelAnchorRef } : {})}
className={cn(
"shrink-0",
isPanel && THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
isPanel && gitActionProgress && "bg-black/[0.035] dark:bg-white/[0.055]",
)}
>
{gitActionProgress ? (
<ThreadDetailsControl
aria-label={
gitActionProgress.output
? `${gitActionProgress.status} ${gitActionProgress.output}`
: gitActionProgress.status
}
part="primary"
panel={isPanel}
multiline
className={isPanel ? undefined : "max-w-72"}
disabled
size="xs"
variant={isPanel ? "ghost" : "outline"}
>
<GitActionProgressButtonContent isPanel={isPanel} progress={gitActionProgress} />
</ThreadDetailsControl>
) : isPanel && visibleInlineSuccess ? (
<ThreadDetailsControl part="primary" multiline disabled size="xs" variant="ghost">
<GitActionSuccessButtonContent success={visibleInlineSuccess} />
</ThreadDetailsControl>
) : quickActionDisabledReason ? (
<Popover>
<PopoverTrigger
openOnHover
render={
<ThreadDetailsControl
aria-disabled="true"
part="primary"
panel={isPanel}
size="xs"
variant={isPanel ? "ghost" : "outline"}
/>
}
>
<GitQuickActionIcon
quickAction={quickAction}
SourceControlIcon={SourceControlIcon}
{...(isPanel ? { className: THREAD_DETAILS_PANEL_ICON_CLASS } : {})}
/>
<span
className={cn(
"sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
isPanel && cn("not-sr-only ml-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
)}
>
{quickAction.label}
</span>
</PopoverTrigger>
<PopoverPopup tooltipStyle side="bottom" align="start">
{quickActionDisabledReason}
</PopoverPopup>
</Popover>
) : (
<ThreadDetailsControl
variant={isPanel ? "ghost" : "outline"}
size="xs"
part="primary"
panel={isPanel}
disabled={!canWriteSourceControl || isGitActionRunning || quickAction.disabled}
onClick={runQuickAction}
>
<GitQuickActionIcon
quickAction={quickAction}
SourceControlIcon={SourceControlIcon}
{...(isPanel ? { className: THREAD_DETAILS_PANEL_ICON_CLASS } : {})}
/>
<span
className={cn(
"sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
isPanel && cn("not-sr-only ml-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
)}
>
{quickAction.label}
</span>
</ThreadDetailsControl>
)}
{isPanel && gitActionProgress ? (
// The menu is disabled while an action runs, so its chevron slot
// hosts the elapsed counter instead, leaving the full row width to
// the status text. Pinned to the title row so it stays put when
// the output row expands below.
<GitActionElapsedTime
startedAtMs={gitActionProgress.startedAtMs}
className="flex h-8 shrink-0 items-center self-start pe-2.5 text-2xs font-normal tabular-nums text-muted-foreground"
/>
) : (
<>
{isPanel ? (
<span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
) : (
<GroupSeparator className="hidden @3xl/header-actions:block" />
)}
<Menu
onOpenChange={(open) => {
if (open) {
requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd);
}
}}
>
<MenuTrigger
render={
<ThreadDetailsControl
aria-label="Git action options"
size={isPanel ? "sm" : "icon-xs"}
variant={isPanel ? "ghost" : "outline"}
part="secondary"
panel={isPanel}
/>
}
disabled={isGitActionRunning}
>
<ChevronDownIcon
aria-hidden="true"
className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
/>
</MenuTrigger>
<MenuPopup
align="end"
{...(isPanel ? { anchor: panelAnchorRef } : {})}
className={isPanel ? "w-(--anchor-width)" : "w-full"}
>
{gitItems}
</MenuPopup>
</Menu>
</>
)}
</ActionGroup>
)}
{isPanel && isRepo ? (
<ThreadDetailsControl
type="button"
variant="ghost"
size="sm"
part="row"
disabled={!onOpenChanges}
onClick={onOpenChanges}
>
<FileDiffIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} aria-hidden />
<span className={cn("flex-1 text-left", THREAD_DETAILS_PANEL_LABEL_CLASS)}>Changes</span>
<span className="flex items-center gap-1 font-mono text-2xs tabular-nums">
<span className="text-success">+{changesTotals?.insertions ?? 0}</span>
<span className="text-destructive">-{changesTotals?.deletions ?? 0}</span>
</span>
</ThreadDetailsControl>
) : null}
<Dialog
open={isCommitDialogOpen}
onOpenChange={(open) => {
if (!open) {
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
setExcludedFiles(new Set());
setIsEditingFiles(false);
}
}}
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
<DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
</DialogHeader>
<DialogPanel>
<div className="space-y-3 rounded-xl bg-zinc-25 p-3 text-sm ring-1 ring-black/5 dark:bg-white/[0.035] dark:ring-white/5">
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
<span className="text-muted-foreground">Branch</span>
<span className="flex items-center justify-between gap-2">
<span className="font-medium">
{gitStatusForActions?.refName ?? "(detached HEAD)"}
</span>
{isDefaultRef && <span className="text-right text-warning">Default branch</span>}
</span>
</div>
<div className="space-y-1">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{isEditingFiles && allFiles.length > 0 && (
<Checkbox
checked={allSelected}
indeterminate={!allSelected && !noneSelected}
onCheckedChange={() => {
setExcludedFiles(
allSelected ? new Set(allFiles.map((f) => f.path)) : new Set(),
);
}}
/>
)}
<span className="text-muted-foreground">Files</span>
{!allSelected && !isEditingFiles && (
<span className="text-muted-foreground">
({selectedFiles.length} of {allFiles.length})
</span>
)}
</div>
{allFiles.length > 0 && (
<Button
variant="ghost"
size="xs"
onClick={() => setIsEditingFiles((prev) => !prev)}
>
{isEditingFiles ? "Done" : "Edit"}
</Button>
)}
</div>
{!gitStatusForActions || allFiles.length === 0 ? (
<p className="font-medium">none</p>
) : (
<div className="space-y-2">
<div className="h-44 rounded-lg bg-card ring-1 ring-black/5 dark:bg-white/[0.025] dark:ring-white/5">
<ScrollArea>
<div className="space-y-1 p-1">
{allFiles.map((file) => {
const isExcluded = excludedFiles.has(file.path);
return (
<div
key={file.path}
className="flex w-full items-center gap-2 rounded-md px-2 py-1 font-mono hover:bg-accent/50"
>
{isEditingFiles && (
<Checkbox
checked={!excludedFiles.has(file.path)}
onCheckedChange={() => {
setExcludedFiles((prev) => {
const next = new Set(prev);
if (next.has(file.path)) {
next.delete(file.path);
} else {
next.add(file.path);
}
return next;
});
}}
/>
)}
<button
type="button"
className="flex min-w-0 flex-1 items-center justify-between gap-3 text-left"
disabled={!canOperateThread}
aria-label={`Open ${file.path} in editor`}
onClick={() => openChangedFileInEditor(file.path)}
>
<StartTruncatedPath
path={file.path}
className={`flex-1${isExcluded ? " text-muted-foreground" : ""}`}
/>
<span className="shrink-0">
{isExcluded ? (
<span className="text-muted-foreground">Excluded</span>
) : (
<>
<span className="text-diff-addition">
+{file.insertions}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-diff-deletion">
-{file.deletions}
</span>
</>
)}
</span>
</button>
</div>
);
})}
</div>
</ScrollArea>
</div>
<div className="flex justify-end font-mono">
<span className="text-diff-addition">
+{selectedFiles.reduce((sum, f) => sum + f.insertions, 0)}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-diff-deletion">
-{selectedFiles.reduce((sum, f) => sum + f.deletions, 0)}
</span>
</div>
</div>
)}
</div>
</div>
<div className="space-y-1">
<p className="text-sm font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
placeholder="Leave empty to auto-generate"
size="sm"
/>
</div>
</DialogPanel>
<DialogFooter variant="bare">
<Button
variant="outline"
size="sm"
onClick={() => {
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
setExcludedFiles(new Set());
setIsEditingFiles(false);
}}
>
Cancel
</Button>
<Button
variant="outline"
size="sm"
disabled={!canChangeThreadBranch || noneSelected}
onClick={runDialogActionOnNewBranch}
>
Commit on new branch
</Button>
<Button
size="sm"
disabled={!canWriteSourceControl || noneSelected}
onClick={runDialogAction}
>
Commit
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
<PublishRepositoryDialog
open={isPublishDialogOpen}
onOpenChange={setIsPublishDialogOpen}
environmentId={activeEnvironmentId}
threadRef={activeThreadRef}
gitCwd={gitCwd}
/>
<Dialog
open={pendingDefaultBranchAction !== null}
onOpenChange={(open) => {
if (!open) {
setPendingDefaultBranchAction(null);
}
}}
>
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>
{pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
</DialogTitle>
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
</DialogHeader>
<DialogFooter variant="bare" className="sm:flex-wrap sm:items-center">
<Button
className="w-full sm:mr-auto sm:w-auto"
variant="outline"
size="sm"
onClick={() => setPendingDefaultBranchAction(null)}
>
Abort
</Button>
<Button
className="w-full max-w-full sm:w-auto"
variant="outline"
size="sm-multiline"
onClick={continuePendingDefaultBranchAction}
disabled={!canWriteSourceControl}
>
{pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
</Button>
<Button
className="w-full max-w-full sm:w-auto"
size="sm-multiline"
onClick={checkoutFeatureBranchAndContinuePendingAction}
disabled={!canChangeThreadBranch}
>
Check out feature branch & continue
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
</>
);
}