Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

1.9 KB
Raw Blame
import { useCallback, useRef } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "@/lib/toast";
import { authApi } from "@/lib/api";
import { invalidateAgyLoginCaches } from "@/lib/query/subscription";
import { extractErrorMessage } from "@/utils/errorUtils";

/**
 * Antigravity 账号切换共享 hook(供应商卡片和授权中心共用)。
 */
export function useAgyAccountSwitch() {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const busy = useRef(false);

  const { mutateAsync, isPending } = useMutation({
    mutationFn: (accountId: string) =>
      authApi.authSetDefaultAccount("agy_oauth", accountId),
  });

  const switchToAccount = useCallback(
    async (accountId: string, name: string) => {
      if (busy.current) return;
      busy.current = true;
      let attemptedSwitch = false;
      try {
        attemptedSwitch = true;
        await mutateAsync(accountId);
        toast.success(
          t("agy.official.switched", {
            name,
            defaultValue:
              "已切换到「{{name}}」,若 Antigravity 正在运行,重启后生效。",
          }),
          { closeButton: true },
        );
      } catch (error) {
        toast.error(
          t("agy.official.switchFailed", {
            defaultValue: "切换 Antigravity 账号失败",
          }),
          {
            description: extractErrorMessage(error) || String(error),
            closeButton: true,
          },
        );
      } finally {
        busy.current = false;
        if (attemptedSwitch) {
          await Promise.all([
            queryClient.invalidateQueries({ queryKey: ["providers", "agy"] }),
            invalidateAgyLoginCaches(queryClient),
          ]);
        }
      }
    },
    [mutateAsync, queryClient, t],
  );

  return { switchToAccount, switching: isPending };
}