Skip to content

Open-source, local-first AI agent for real work.

6.6 KB
Raw Blame
import { useTranslation } from "@vetta-org/plugin-sdk";
import { ButtonGroup, ButtonGroupItem } from "@vetta-org/ui";
import { useCallback, useEffect, useRef, useState } from "react";
import {
	aheadBehind,
	gitFetch,
	gitPublishBranch,
	gitPull,
	gitPush,
	gitSync,
} from "../git/run";
import { preflightPush } from "../git/publish";
import { emitRefreshSignal, notifyError, onRefreshSignal } from "../git/runtime";
import { ConfirmDialog } from "./ConfirmDialog";
import { FetchIcon, PullIcon, PushIcon, SyncIcon } from "./icons";

type ActionKind = "fetch" | "pull" | "push" | "sync";

/** A branch with no upstream, pending the user's go-ahead to publish it. */
interface PendingPublish {
	branch: string;
	remote: string;
}

/**
 * Left-side action row in the changes toolbar: fetch / pull / push (with
 * ahead-behind counts) plus the working-tree added/deleted line totals. Reloads
 * on the shared refresh signal and after each action.
 */
export function GitActions({ root, labelled = false }: { root: string; labelled?: boolean }): JSX.Element {
	const { t } = useTranslation();
	const [ab, setAb] = useState<{ ahead: number; behind: number } | null>(null);
	const [busy, setBusy] = useState<ActionKind | null>(null);
	const [pendingPublish, setPendingPublish] = useState<PendingPublish | null>(null);
	// Reloads overlap (refresh signal + post-action), and they finish out of order;
	// only the newest one may write state.
	const reloadIdRef = useRef(0);

	const reload = useCallback(() => {
		const id = ++reloadIdRef.current;
		aheadBehind(root)
			.then((value) => {
				if (id === reloadIdRef.current) setAb(value);
			})
			.catch(() => {
				if (id === reloadIdRef.current) setAb(null);
			});
	}, [root]);

	useEffect(() => {
		reload();
		return onRefreshSignal(reload);
	}, [reload]);

	/**
	 * Run one toolbar action with the shared busy/error handling. `fn` may return
	 * "deferred" to hand control to a dialog instead of finishing the action.
	 */
	const runAction = useCallback(
		(kind: ActionKind, fn: () => Promise<"done" | "deferred">) => {
			if (busy) return;
			setBusy(kind);
			fn()
				.then((outcome) => {
					if (outcome !== "done") return;
					emitRefreshSignal();
					reload();
				})
				.catch((err: unknown) => notifyError(String(err instanceof Error ? err.message : err), err))
				.finally(() => setBusy(null));
		},
		[busy, reload],
	);

	/**
	 * Pushing an unpublished branch: bare `git push` fails outright ("has no
	 * upstream branch"), which every freshly created branch would hit. Resolve the
	 * branch + remote and ask, rather than silently writing tracking config.
	 * The decision itself is shared with the header popover (git/publish.ts).
	 */
	const ensurePublish = useCallback(async (): Promise<"done" | "deferred"> => {
		const pre = await preflightPush(root);
		if (pre.kind === "error") throw new Error(t(pre.key));
		if (pre.kind === "needs-publish") {
			setPendingPublish({ branch: pre.branch, remote: pre.remote });
			return "deferred";
		}
		return "done";
	}, [root, t]);

	const handlePush = useCallback(() => {
		runAction("push", async () => {
			const outcome = await ensurePublish();
			if (outcome !== "done") return outcome;
			await gitPush(root);
			return "done";
		});
	}, [runAction, ensurePublish, root]);

	// Syncing an unpublished branch has nothing to pull; publishing IS the sync.
	const handleSync = useCallback(() => {
		runAction("sync", async () => {
			const outcome = await ensurePublish();
			if (outcome !== "done") return outcome;
			await gitSync(root);
			return "done";
		});
	}, [runAction, ensurePublish, root]);

	const confirmPublish = useCallback(() => {
		const target = pendingPublish;
		if (!target) return;
		setPendingPublish(null);
		runAction("push", async () => {
			await gitPublishBranch(root, target.remote, target.branch);
			return "done";
		});
	}, [pendingPublish, runAction, root]);

	const spin = (kind: ActionKind): string => (busy === kind ? "animate-spin" : "");

	/** One toolbar action, rendered either as a bare icon or as a labelled segment. */
	const items: Array<{
		kind: ActionKind;
		/** Visible label; kept short so the segments stay compact. */
		label: string;
		/** Tooltip, where the longer explanation lives. */
		title: string;
		icon: (className: string) => JSX.Element;
		count?: number;
		tone?: string;
		onClick: () => void;
	}> = [
		{
			kind: "fetch",
			label: t("action.fetch"),
			title: t("action.fetch"),
			icon: (cn) => <FetchIcon className={cn} />,
			onClick: () => runAction("fetch", async () => (await gitFetch(root), "done")),
		},
		{
			kind: "pull",
			label: t("action.pull"),
			title: t("action.pull"),
			icon: (cn) => <PullIcon className={cn} />,
			count: ab && ab.behind > 0 ? ab.behind : undefined,
			tone: "text-sky-500",
			onClick: () => runAction("pull", async () => (await gitPull(root), "done")),
		},
		{
			kind: "push",
			label: t("action.push"),
			title: t("action.push"),
			icon: (cn) => <PushIcon className={cn} />,
			count: ab && ab.ahead > 0 ? ab.ahead : undefined,
			tone: "text-emerald-500",
			onClick: handlePush,
		},
		{ kind: "sync", label: t("action.syncLabel"), title: t("action.sync"), icon: (cn) => <SyncIcon className={cn} />, onClick: handleSync },
	];

	return (
		<div className="flex items-center gap-2">
			{/* 宿主按钮组:宽面板下多显示一行文案,窄面板下只留图标。 */}
			<ButtonGroup blur={false}>
				{items.map((item) => {
					const count =
						item.count !== undefined ? (
							<span className={`text-[11px] font-semibold tabular-nums leading-none ${item.tone ?? ""}`}>{item.count}</span>
						) : null;
					const label =
						labelled || count ? (
							<span className="inline-flex items-center gap-1">
								{labelled && <span className="text-[12px] font-normal">{item.label}</span>}
								{count}
							</span>
						) : undefined;
					return (
						<ButtonGroupItem
							key={item.kind}
							title={item.count ? `${item.title} (${item.count})` : item.title}
							aria-label={item.title}
							disabled={busy !== null}
							onClick={item.onClick}
							icon={item.icon(`h-4 w-4 ${item.count ? (item.tone ?? "") : "text-muted-foreground"} ${spin(item.kind)}`)}
							label={label}
							className={label ? "px-2" : undefined}
						/>
					);
				})}
			</ButtonGroup>

			<ConfirmDialog
				open={pendingPublish !== null}
				title={t("publish.title")}
				description={
					pendingPublish
						? t("publish.description", { branch: pendingPublish.branch, remote: pendingPublish.remote })
						: undefined
				}
				confirmLabel={t("publish.confirm")}
				onConfirm={confirmPublish}
				onCancel={() => setPendingPublish(null)}
			/>
		</div>
	);
}