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

19.9 KB
Raw Blame
import { useState, useCallback, useRef, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "@/lib/toast";
import { authApi } from "@/lib/api";
import { CODEX_OAUTH_DUPLICATE_ACCOUNT_ERROR } from "@/lib/api/auth";
import type { CodexLoginMethod, ManagedLoginMethod } from "@/lib/api/auth";
import { deliverLoginLink, readAuthOpenBrowser } from "@/lib/authLoginLink";
import { copyText } from "@/lib/clipboard";
import {
  agyAuthStatusQuery,
  invalidateAgyLoginCaches,
  invalidateAgyQuotaCaches,
  invalidateManagedAuthQuotaCaches,
  subscriptionKeys,
  syncAgyLoginOnWindowFocus,
} from "@/lib/query/subscription";
import { subscribeWindowFocus } from "@/lib/windowActivity";
import type {
  ManagedAuthAccount,
  ManagedAuthProvider,
  ManagedAuthStatus,
  ManagedAuthDeviceCodeResponse,
} from "@/lib/api";

type PollingState = "idle" | "polling" | "success" | "error";
type LoginRequest = {
  targetAccountId?: string;
  generation: number;
  loginMethod?: ManagedLoginMethod;
};

export interface CompletedManagedLogin {
  account: ManagedAuthAccount;
  created: boolean;
}

export interface ManagedAuthOptions {
  /** 登录完成、账号已收录(状态已刷新)后回调,参数是这次登上的账号 */
  onLoginComplete?: (account: ManagedAuthAccount) => void;
}

export function useManagedAuth(
  authProvider: ManagedAuthProvider,
  githubDomain?: string,
  loginMethod?: CodexLoginMethod,
  options?: ManagedAuthOptions,
) {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const queryKey = ["managed-auth-status", authProvider];

  const [pollingState, setPollingState] = useState<PollingState>("idle");
  const [deviceCode, setDeviceCode] =
    useState<ManagedAuthDeviceCodeResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [lastCompletedLogin, setLastCompletedLogin] =
    useState<CompletedManagedLogin | null>(null);

  const pollingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(
    null,
  );
  const pollingTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const flowGenerationRef = useRef(0);
  const activeDeviceCodeRef = useRef<string | null>(null);
  const retryTargetAccountIdRef = useRef<string | undefined>(undefined);
  const flowTransitionRef = useRef<Promise<void>>(Promise.resolve());
  const onLoginCompleteRef = useRef(options?.onLoginComplete);
  onLoginCompleteRef.current = options?.onLoginComplete;

  const {
    data: authStatus,
    isLoading: isLoadingStatus,
    isSuccess: isStatusSuccess,
    isError: isStatusError,
    refetch: refetchStatus,
  } = useQuery<ManagedAuthStatus>({
    queryKey,
    queryFn: () => authApi.authGetStatus(authProvider),
    staleTime: 30000,
    // agy 的登录可能在外部终端被 /logout、/login 换掉:回到窗口时重读钥匙串同步「agy 在用」徽标。
    ...(authProvider === "agy_oauth"
      ? { refetchOnWindowFocus: agyAuthStatusQuery.refetchOnWindowFocus }
      : {}),
    // A rejected xAI refresh token is persisted as `requires_reauth` by the
    // proxy hot path. Periodically refresh local status so an already-open Auth
    // Center stops showing the account as logged in without requiring a reload.
    // WorkBuddy auto-absorbs the desktop app's current sign-in on every status
    // read, so poll while the Auth Center is open to surface a freshly logged-in
    // account (and refresh its snapshot) without a manual "import" click.
    // CodeBuddy 与 Antigravity 的当前账号可能在终端/外部被换掉,定期本地刷新状态(不发网络请求)。
    refetchInterval:
      pollingState === "polling"
        ? false
        : authProvider === "xai_oauth" ||
            authProvider === "codebuddy_oauth" ||
            authProvider === "agy_oauth"
          ? 15_000
          : authProvider === "workbuddy_account"
            ? 5_000
            : false,
  });

  const stopPolling = useCallback(() => {
    if (pollingIntervalRef.current) {
      clearInterval(pollingIntervalRef.current);
      pollingIntervalRef.current = null;
    }
    if (pollingTimeoutRef.current) {
      clearTimeout(pollingTimeoutRef.current);
      pollingTimeoutRef.current = null;
    }
  }, []);

  const cancelBackendFlow = useCallback(
    async (deviceCode: string | null): Promise<boolean> => {
      // Codex(设备码)、Antigravity(本机回调服务)、CodeBuddy(等凭据文件变化)和 Claude
      // 官方账号(后台的 claude 进程)在后端记着这次登录,要通知取消
      if (
        (authProvider !== "codex_oauth" &&
          authProvider !== "agy_oauth" &&
          authProvider !== "codebuddy_oauth" &&
          authProvider !== "claude_official") ||
        !deviceCode
      )
        return true;
      try {
        const cancelled = await authApi.authCancelLogin(
          authProvider,
          deviceCode,
        );
        if (!cancelled || authProvider === "agy_oauth") {
          await queryClient.invalidateQueries({
            queryKey: ["managed-auth-status", authProvider],
          });
        }
        return cancelled;
      } catch (e) {
        console.debug("[ManagedAuth] Failed to cancel device flow:", e);
        await queryClient.invalidateQueries({
          queryKey: ["managed-auth-status", authProvider],
        });
        return false;
      }
    },
    [authProvider, queryClient],
  );

  const queueBackendCancellation = useCallback(
    (deviceCode: string | null) => {
      const transition = flowTransitionRef.current.then(async () => {
        await cancelBackendFlow(deviceCode);
      });
      flowTransitionRef.current = transition;
      return transition;
    },
    [cancelBackendFlow],
  );

  useEffect(() => {
    if (authProvider !== "agy_oauth") return;
    // windowActivity 仅在隐藏/最小化时切换 focusManager,从外部终端切回可见窗口时需显式监听窗口焦点。
    return subscribeWindowFocus(() => {
      void syncAgyLoginOnWindowFocus(queryClient);
    });
  }, [authProvider, queryClient]);

  useEffect(() => {
    return () => {
      flowGenerationRef.current += 1;
      void cancelBackendFlow(activeDeviceCodeRef.current);
      activeDeviceCodeRef.current = null;
      stopPolling();
    };
  }, [cancelBackendFlow, stopPolling]);

  const startLoginMutation = useMutation({
    mutationFn: ({ targetAccountId, loginMethod: method }: LoginRequest) =>
      method
        ? authApi.authStartLogin(
            authProvider,
            githubDomain,
            targetAccountId,
            method,
          )
        : authApi.authStartLogin(authProvider, githubDomain, targetAccountId),
    onSuccess: async (response, request) => {
      if (request.generation !== flowGenerationRef.current) {
        void cancelBackendFlow(response.device_code);
        return;
      }
      activeDeviceCodeRef.current = response.device_code;
      setDeviceCode(response);
      setPollingState("polling");
      setError(null);

      // 按授权中心的偏好打开浏览器,或只复制登录链接。终端登录(CodeBuddy)没有登录页,
      // 后端已经打开了终端;Claude 官方账号在 Windows 上由 Claude Code 自己打开了登录页
      const linkOnly =
        response.browser_opened || !response.verification_uri
          ? false
          : (await deliverLoginLink(response.verification_uri, t)).linkOnly;
      if (request.generation !== flowGenerationRef.current) return;

      // Browser login has no verification code; leave the clipboard untouched.
      // 只复制了链接时也不复制验证码,免得盖掉剪贴板里的链接(等待块里有复制按钮)
      const browserFlow = !response.user_code;
      if (!browserFlow && !linkOnly) {
        try {
          await copyText(response.user_code);
        } catch (e) {
          console.debug("[ManagedAuth] Failed to copy user code:", e);
        }
      }
      if (request.generation !== flowGenerationRef.current) return;

      // Add a small buffer on top of GitHub's suggested interval to avoid
      // hitting slow_down responses too aggressively during device polling.
      // The browser flow only checks a local result, so it can poll quickly.
      const interval = browserFlow
        ? 1500
        : Math.max((response.interval || 5) + 3, 8) * 1000;
      let pollInFlight = false;
      const expiresAt = Date.now() + response.expires_in * 1000;

      const pollOnce = async () => {
        if (request.generation !== flowGenerationRef.current) return;
        if (pollInFlight) return;
        if (Date.now() > expiresAt) {
          stopPolling();
          activeDeviceCodeRef.current = null;
          void cancelBackendFlow(response.device_code);
          flowGenerationRef.current += 1;
          setPollingState("error");
          setError(
            t("codexOauth.loginExpired", {
              defaultValue: "Login expired. Please try again.",
            }),
          );
          return;
        }

        try {
          pollInFlight = true;
          const newAccount = await authApi.authPollForAccount(
            authProvider,
            response.device_code,
            githubDomain,
          );
          if (request.generation !== flowGenerationRef.current) return;
          if (newAccount) {
            stopPolling();
            activeDeviceCodeRef.current = null;
            flowGenerationRef.current += 1;
            const completionGeneration = flowGenerationRef.current;
            const previousIds = new Set(
              (
                queryClient.getQueryData<ManagedAuthStatus>(queryKey)
                  ?.accounts ?? []
              ).map((item) => item.id),
            );
            const created = !previousIds.has(newAccount.id);
            setLastCompletedLogin({ account: newAccount, created });
            setPollingState("success");
            const refreshedStatus = await refetchStatus();
            await queryClient.invalidateQueries({ queryKey });
            if (authProvider === "agy_oauth") {
              await invalidateAgyLoginCaches(queryClient);
            }
            if (completionGeneration !== flowGenerationRef.current) return;
            if (authProvider === "agy_oauth") {
              const nextStatus =
                refreshedStatus.data ??
                queryClient.getQueryData<ManagedAuthStatus>(queryKey);
              await invalidateAgyQuotaCaches(
                queryClient,
                nextStatus?.default_account_id ?? null,
              );
              if (completionGeneration !== flowGenerationRef.current) return;
            }
            onLoginCompleteRef.current?.(newAccount);
            setPollingState("idle");
            setDeviceCode(null);
          }
        } catch (e) {
          if (request.generation !== flowGenerationRef.current) return;
          const errorMessage = e instanceof Error ? e.message : String(e);
          if (
            !errorMessage.includes("pending") &&
            !errorMessage.includes("slow_down")
          ) {
            stopPolling();
            activeDeviceCodeRef.current = null;
            void cancelBackendFlow(response.device_code);
            flowGenerationRef.current += 1;
            setPollingState("error");
            setError(
              authProvider === "codex_oauth" &&
                errorMessage === CODEX_OAUTH_DUPLICATE_ACCOUNT_ERROR
                ? t("codexOauth.duplicateAccount", {
                    defaultValue: "该 ChatGPT 账号已添加,请直接使用现有账号。",
                  })
                : errorMessage,
            );
          }
        } finally {
          pollInFlight = false;
        }
      };

      pollingIntervalRef.current = setInterval(pollOnce, interval);
      pollingTimeoutRef.current = setTimeout(() => {
        if (request.generation !== flowGenerationRef.current) return;
        stopPolling();
        activeDeviceCodeRef.current = null;
        void cancelBackendFlow(response.device_code);
        flowGenerationRef.current += 1;
        setPollingState("error");
        setError(
          t("codexOauth.loginExpired", {
            defaultValue: "Login expired. Please try again.",
          }),
        );
      }, response.expires_in * 1000);
      void pollOnce();
    },
    onError: (e, request) => {
      if (request.generation !== flowGenerationRef.current) return;
      setPollingState("error");
      setError(e instanceof Error ? e.message : String(e));
    },
  });

  const logoutMutation = useMutation({
    mutationFn: () => authApi.authLogout(authProvider),
    onSuccess: async () => {
      setPollingState("idle");
      setDeviceCode(null);
      setError(null);
      setLastCompletedLogin(null);
      queryClient.setQueryData(queryKey, {
        provider: authProvider,
        authenticated: false,
        default_account_id: null,
        accounts: [],
      });
      await queryClient.invalidateQueries({ queryKey });
    },
    onError: async (e) => {
      console.error("[ManagedAuth] Failed to logout:", e);
      setError(e instanceof Error ? e.message : String(e));
      await refetchStatus();
    },
    onSettled: async () => {
      if (authProvider === "codex_oauth") {
        await queryClient.invalidateQueries({
          queryKey: ["providers", "codex"],
        });
      }
      // 移除/登出的 xAI 账号若正是 Grok CLI 当前登录的号,后端会把 CLI 登录让出来:
      // 没绑号的 Grok 官方卡查的就是 CLI 当前登录,要重查
      if (authProvider === "xai_oauth") {
        await queryClient.invalidateQueries({
          queryKey: subscriptionKeys.quota("grokbuild"),
        });
      }
      await invalidateManagedAuthQuotaCaches(queryClient, authProvider, {
        allAccounts: true,
      });
    },
  });

  const removeAccountMutation = useMutation({
    mutationFn: (accountId: string) =>
      authApi.authRemoveAccount(authProvider, accountId),
    onSuccess: async () => {
      // 删号会结束进行中的登录:停掉轮询并通知后端取消,免得旧流程之后被当成完成
      flowGenerationRef.current += 1;
      const previousDeviceCode = activeDeviceCodeRef.current;
      activeDeviceCodeRef.current = null;
      stopPolling();
      if (previousDeviceCode) {
        void cancelBackendFlow(previousDeviceCode);
      }
      setPollingState("idle");
      setDeviceCode(null);
      setError(null);
      toast.success(
        t("managedAuth.accountRemoved", {
          defaultValue: "账号已移除",
        }),
      );
      await refetchStatus();
      await queryClient.invalidateQueries({ queryKey });
    },
    onError: async (e) => {
      console.error("[ManagedAuth] Failed to remove account:", e);
      setError(e instanceof Error ? e.message : String(e));
      // Account removal can succeed before provider unbinding fails.
      if (authProvider === "codex_oauth") await refetchStatus();
    },
    onSettled: async (_, __, accountId) => {
      if (authProvider === "codex_oauth") {
        await queryClient.invalidateQueries({
          queryKey: ["providers", "codex"],
        });
      }
      // 移除/登出的 xAI 账号若正是 Grok CLI 当前登录的号,后端会把 CLI 登录让出来:
      // 没绑号的 Grok 官方卡查的就是 CLI 当前登录,要重查
      if (authProvider === "xai_oauth") {
        await queryClient.invalidateQueries({
          queryKey: subscriptionKeys.quota("grokbuild"),
        });
      }
      await invalidateManagedAuthQuotaCaches(queryClient, authProvider, {
        accountId,
      });
    },
  });

  const setDefaultAccountMutation = useMutation({
    mutationFn: (accountId: string) =>
      authApi.authSetDefaultAccount(authProvider, accountId),
    onSuccess: async () => {
      if (authProvider === "agy_oauth") {
        toast.success(
          t("authCenter.agy.switched", {
            defaultValue: "已切换,若 Antigravity 正在运行,重启后生效。",
          }),
        );
        return;
      }
      await refetchStatus();
      await queryClient.invalidateQueries({ queryKey });
    },
    onError: (e) => {
      console.error("[ManagedAuth] Failed to set default account:", e);
      setError(e instanceof Error ? e.message : String(e));
      if (authProvider === "agy_oauth") {
        toast.error(e instanceof Error ? e.message : String(e));
      }
    },
    onSettled: async () => {
      await invalidateManagedAuthQuotaCaches(queryClient, authProvider);
    },
  });

  const beginLogin = useCallback(
    (targetAccountId?: string) => {
      const previousDeviceCode = activeDeviceCodeRef.current;
      activeDeviceCodeRef.current = null;
      const generation = flowGenerationRef.current + 1;
      flowGenerationRef.current = generation;
      retryTargetAccountIdRef.current = targetAccountId;
      setPollingState("idle");
      setDeviceCode(null);
      setError(null);
      setLastCompletedLogin(null);
      stopPolling();
      void queueBackendCancellation(previousDeviceCode).then(() => {
        if (generation !== flowGenerationRef.current) return;
        // Claude 官方账号在 Windows 上由 Claude Code 自己开浏览器:不打开时要告诉后端
        const method: ManagedLoginMethod | undefined =
          authProvider === "claude_official" && !readAuthOpenBrowser()
            ? "copy_link"
            : loginMethod;
        startLoginMutation.mutate({
          targetAccountId,
          generation,
          loginMethod: method,
        });
      });
    },
    [
      authProvider,
      queueBackendCancellation,
      startLoginMutation,
      stopPolling,
      loginMethod,
    ],
  );

  const startAuth = useCallback(() => beginLogin(), [beginLogin]);

  const reauthAccount = useCallback(
    (accountId: string) => {
      beginLogin(accountId);
    },
    [beginLogin],
  );

  const retryAuth = useCallback(
    () => beginLogin(retryTargetAccountIdRef.current),
    [beginLogin],
  );

  /** 取消这次登录,返回后端取消完成的 Promise(CodeBuddy 取消时要恢复原来的登录,调用方可以等它) */
  const cancelAuthAndWait = useCallback(() => {
    flowGenerationRef.current += 1;
    const previousDeviceCode = activeDeviceCodeRef.current;
    activeDeviceCodeRef.current = null;
    retryTargetAccountIdRef.current = undefined;
    stopPolling();
    setPollingState("idle");
    setDeviceCode(null);
    setError(null);
    setLastCompletedLogin(null);
    return queueBackendCancellation(previousDeviceCode);
  }, [queueBackendCancellation, stopPolling]);

  const cancelAuth = useCallback(() => {
    void cancelAuthAndWait();
  }, [cancelAuthAndWait]);

  const logout = useCallback(() => {
    logoutMutation.mutate();
  }, [logoutMutation]);

  const removeAccount = useCallback(
    (accountId: string) => {
      removeAccountMutation.mutate(accountId);
    },
    [removeAccountMutation],
  );

  const setDefaultAccount = useCallback(
    (accountId: string) => {
      setDefaultAccountMutation.mutate(accountId);
    },
    [setDefaultAccountMutation],
  );

  const accounts = authStatus?.accounts ?? [];

  return {
    authStatus,
    isLoadingStatus,
    // Distinguish "status loaded successfully" from "loading / failed" so
    // callers don't treat a failed query's empty `accounts` as authoritative.
    isStatusSuccess,
    isStatusError,
    accounts,
    hasAnyAccount: accounts.length > 0,
    isAuthenticated: authStatus?.authenticated ?? false,
    defaultAccountId: authStatus?.default_account_id ?? null,
    migrationError: authStatus?.migration_error ?? null,
    pollingState,
    deviceCode,
    error,
    lastCompletedLogin,
    isPolling: pollingState === "polling",
    isAddingAccount: startLoginMutation.isPending || pollingState === "polling",
    isRemovingAccount: removeAccountMutation.isPending,
    isSettingDefaultAccount: setDefaultAccountMutation.isPending,
    startAuth,
    addAccount: startAuth,
    reauthAccount,
    retryAuth,
    cancelAuth,
    cancelAuthAndWait,
    logout,
    removeAccount,
    setDefaultAccount,
    refetchStatus,
  };
}