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

14.7 KB
Raw Blame
import { useEffect, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { ExternalLink, Loader2, RefreshCw, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Notice } from "@/components/ui/notice";
import { settingsApi } from "@/lib/api";
import { qoderApi, qoderKeys, type QoderAccount } from "@/lib/api/qoder";
import type { QoderEdition } from "@/config/qoder";
import { extractErrorMessage } from "@/utils/errorUtils";
import { deliverLoginLink } from "@/lib/authLoginLink";
import { ConfirmDialog } from "@/components/ConfirmDialog";
import { HoverTip } from "@/components/ui/hover-tip";
import { cn } from "@/lib/utils";
import { ProviderIcon } from "@/components/ProviderIcon";
import { APP_DISPLAY_NAME } from "@/components/shell/AppGlyph";

/**
 * Qoder 的账号:设置里选的那个版本(国际版 / 国内版各一套账号)。看状态只刷新已收录的号;
 * Qoder 里登录了还没收录的号,用户点「收录」才收录。删除只从 CC Switch 移除,不替 Qoder 登出。
 */
export function QoderAccountLogin({ edition }: { edition: QoderEdition }) {
  const { t } = useTranslation();
  const app = "qoder" as const;
  const queryClient = useQueryClient();
  const auth = useQuery({
    queryKey: qoderKeys.auth(edition),
    queryFn: () => qoderApi.getAuthStatus(),
    retry: false,
    staleTime: 30_000,
  });
  const [flowId, setFlowId] = useState<string | null>(null);
  const [working, setWorking] = useState(false);
  const [starting, setStarting] = useState(false);
  const [error, setError] = useState("");
  const [deleting, setDeleting] = useState<QoderAccount | null>(null);
  const [removing, setRemoving] = useState(false);
  const [deleteError, setDeleteError] = useState("");
  const generation = useRef(0);
  // 每个收录的账号在供应商页有一张官方卡,登录、切号、删号后卡片跟着变
  const invalidateCards = () =>
    queryClient.invalidateQueries({ queryKey: ["providers", app] });
  const activeFlow = useRef<string | null>(null);
  const openedFlow = useRef<string | null>(null);
  const completedFlow = useRef<string | null>(null);
  const progress = useQuery({
    queryKey: qoderKeys.login(edition, flowId),
    queryFn: () => qoderApi.pollLogin(flowId!),
    enabled: Boolean(flowId),
    refetchInterval: 1500,
    retry: false,
    gcTime: 0,
  });

  useEffect(
    () => () => {
      generation.current += 1;
      const id = activeFlow.current;
      activeFlow.current = null;
      if (id) void qoderApi.cancelLogin(id).catch(() => {});
    },
    [edition],
  );

  const openBrowser = async (url: string) => {
    try {
      await settingsApi.openExternal(url);
    } catch {
      setError(t("qoder.loginBrowserFailed"));
    }
  };

  useEffect(() => {
    if (!flowId) return;
    const result = progress.data;
    if (
      result?.authUrl &&
      !result.complete &&
      !result.error &&
      !progress.error &&
      openedFlow.current !== flowId
    ) {
      openedFlow.current = flowId;
      // 和其他服务一样按授权中心「登录时自动打开浏览器」:关掉时只复制登录链接
      void deliverLoginLink(result.authUrl, t);
    }
    if (result?.error || progress.error) {
      setError(result?.error || extractErrorMessage(progress.error));
      setFlowId(null);
      activeFlow.current = null;
      setWorking(false);
      void qoderApi.cancelLogin(flowId).catch(() => {});
      return;
    }
    if (result?.complete && completedFlow.current !== flowId) {
      completedFlow.current = flowId;
      const current = generation.current;
      setFlowId(null);
      void (async () => {
        try {
          await qoderApi.cancelLogin(flowId);
          activeFlow.current = null;
          const status = await qoderApi.getAuthStatus();
          if (current !== generation.current) return;
          queryClient.setQueryData(qoderKeys.auth(edition), status);
          await invalidateCards();
          if (
            !status.accounts?.some((account) => account.id === result.accountId)
          )
            throw new Error(t("qoder.loginNotConfirmed"));
        } catch (cause) {
          if (current === generation.current)
            setError(extractErrorMessage(cause));
        } finally {
          if (current === generation.current) setWorking(false);
        }
      })();
    }
  }, [edition, flowId, progress.data, progress.error, queryClient, t]);

  const start = async (accountId?: string) => {
    if (working || removing) return;
    const current = ++generation.current;
    setWorking(true);
    setStarting(true);
    setError("");
    try {
      const id = await qoderApi.startLogin(accountId);
      if (current !== generation.current) {
        await qoderApi.cancelLogin(id);
        return;
      }
      activeFlow.current = id;
      setFlowId(id);
    } catch (cause) {
      if (current === generation.current) setError(extractErrorMessage(cause));
    } finally {
      if (current === generation.current) {
        setStarting(false);
        if (!activeFlow.current) setWorking(false);
      }
    }
  };

  const select = async (accountId: string) => {
    if (working || removing) return;
    setWorking(true);
    setError("");
    try {
      const status = await qoderApi.useAccount(accountId);
      queryClient.setQueryData(qoderKeys.auth(edition), status);
      await invalidateCards();
    } catch (cause) {
      setError(extractErrorMessage(cause));
    } finally {
      setWorking(false);
    }
  };

  const remove = async () => {
    if (!deleting || removing) return;
    setRemoving(true);
    setDeleteError("");
    try {
      const status = await qoderApi.deleteAccount(deleting.id);
      queryClient.setQueryData(qoderKeys.auth(edition), status);
      await invalidateCards();
      setDeleting(null);
    } catch (cause) {
      setDeleteError(extractErrorMessage(cause));
    } finally {
      setRemoving(false);
    }
  };
  const collect = async () => {
    if (working || removing) return;
    setWorking(true);
    setError("");
    try {
      const status = await qoderApi.importCurrentAccount();
      queryClient.setQueryData(qoderKeys.auth(edition), status);
      await invalidateCards();
    } catch (cause) {
      setError(extractErrorMessage(cause));
    } finally {
      setWorking(false);
    }
  };
  const accounts = auth.data?.accounts ?? [];
  const uncollected = auth.data?.uncollectedLogin;
  const label = (account: QoderAccount) =>
    account.username || account.email || "Qoder";
  const addButton = (
    <Button
      type="button"
      variant="quiet"
      size="compact"
      disabled={working || removing || !auth.data?.installed}
      onClick={() => void start()}
    >
      {starting && <Loader2 className="h-4 w-4 animate-spin" />}
      {t(accounts.length ? "qoder.addAccount" : "qoder.loginWithBrowser")}
    </Button>
  );
  const cancel = async () => {
    generation.current += 1;
    const id = activeFlow.current;
    setFlowId(null);
    setStarting(false);
    try {
      if (id) await qoderApi.cancelLogin(id);
    } catch (cause) {
      setError(extractErrorMessage(cause));
    } finally {
      activeFlow.current = null;
      setWorking(false);
      void auth.refetch();
    }
  };

  return (
    <section
      aria-label={APP_DISPLAY_NAME[app]}
      className="space-y-4 rounded-panel border border-border bg-surface p-4"
    >
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <ProviderIcon icon="qoder" name={APP_DISPLAY_NAME[app]} size={24} />
          <h3 className="text-strong text-fg-1">{APP_DISPLAY_NAME[app]}</h3>
        </div>
        {addButton}
      </div>
      <p className="text-body text-fg-2">{t("qoder.loginDescription")}</p>
      <div className="flex flex-wrap items-center gap-3">
        <span className="text-caption text-fg-2">
          {t("qoder.editionHint", {
            edition: t(
              edition === "cn" ? "qoder.chinaEdition" : "qoder.globalEdition",
            ),
          })}
        </span>
        <span role="status" className="text-caption text-fg-2">
          {auth.isPending
            ? t("common.loading")
            : auth.isError
              ? t("qoder.statusFailed")
              : accounts.length
                ? t("qoder.accountCount", { count: accounts.length })
                : !auth.data.installed
                  ? t("common.notInstalled")
                  : auth.data.loggedIn
                    ? t("qoder.signedIn")
                    : t("qoder.signedOut")}
        </span>
        <Button
          type="button"
          variant="quiet"
          size="icon-compact"
          disabled={working || removing || auth.isFetching}
          aria-label={t("qoder.refreshAccounts")}
          onClick={() => void auth.refetch()}
        >
          <RefreshCw
            className={cn("h-4 w-4", auth.isFetching && "animate-spin")}
          />
        </Button>
      </div>
      {auth.isError && (
        <Notice
          tone="danger"
          title={extractErrorMessage(auth.error)}
          actions={
            <Button
              type="button"
              variant="neutral"
              size="compact"
              onClick={() => void auth.refetch()}
            >
              {t("common.retry")}
            </Button>
          }
        />
      )}
      {auth.data && !auth.data.installed && (
        <Notice tone="warning" title={t("qoder.loginInstallRequired")} />
      )}
      {uncollected && (
        <Notice
          title={t("qoder.uncollectedLogin", { name: uncollected })}
          actions={
            <Button
              type="button"
              variant="neutral"
              size="compact"
              disabled={working || removing}
              onClick={() => void collect()}
            >
              {t("qoder.collectAccount")}
            </Button>
          }
        >
          {t("qoder.uncollectedLoginHint")}
        </Notice>
      )}
      {auth.data?.loggedIn && accounts.length === 0 && !uncollected && (
        <Notice
          title={t("qoder.loggedInAs", {
            name: auth.data.email || auth.data.username || "Qoder",
          })}
        >
          {auth.data.plan}
        </Notice>
      )}
      {accounts.length > 0 && (
        <div role="list" className="space-y-2">
          {accounts.map((account) => (
            <div
              key={account.id}
              role="listitem"
              className={cn(
                "flex items-center gap-3 rounded-panel border px-4 py-3",
                account.isCurrent
                  ? "border-direct-border bg-direct-soft"
                  : "border-border bg-surface",
              )}
            >
              <div className="min-w-0 flex-1">
                <div className="flex min-w-0 items-center gap-2">
                  <span className="truncate text-strong text-fg-1">
                    {label(account)}
                  </span>
                  {account.isCurrent && (
                    <span className="inline-flex shrink-0 items-center gap-1.5 text-caption text-fg-2">
                      <span className="h-1.5 w-1.5 rounded-full bg-direct" />
                      {t("qoder.currentAccount")}
                    </span>
                  )}
                </div>
                <p className="truncate text-caption text-fg-2">
                  {[
                    account.email !== account.username ? account.email : null,
                    account.plan,
                  ]
                    .filter(Boolean)
                    .join(" · ")}
                </p>
              </div>
              <Button
                type="button"
                variant="quiet"
                size="compact"
                disabled={working || removing || !auth.data?.installed}
                onClick={() => void start(account.id)}
              >
                {t("qoder.signInAgain")}
              </Button>
              <Button
                type="button"
                variant="neutral"
                size="compact"
                // 切号会覆盖 Qoder 现在的登录:先收录那个号,免得它丢掉
                disabled={
                  working || removing || !auth.data?.installed || !!uncollected
                }
                title={
                  uncollected ? t("qoder.uncollectedLoginHint") : undefined
                }
                onClick={() => void select(account.id)}
              >
                {t("qoder.useAccount")}
              </Button>
              <HoverTip
                content={t("qoder.deleteAccount", { name: label(account) })}
              >
                <Button
                  type="button"
                  variant="quiet"
                  size="icon-compact"
                  className="text-danger-text hover:bg-danger-soft hover:text-danger-text"
                  aria-label={t("qoder.deleteAccount", {
                    name: label(account),
                  })}
                  disabled={working || removing}
                  onClick={() => {
                    setDeleteError("");
                    setDeleting(account);
                  }}
                >
                  <Trash2 className="h-4 w-4" strokeWidth={1.5} />
                </Button>
              </HoverTip>
            </div>
          ))}
        </div>
      )}
      {error && (
        <p role="alert" className="text-body text-danger-text">
          {error}
        </p>
      )}
      {flowId && (
        <Notice title={t("qoder.loginWaiting")}>
          {progress.data?.authUrl && (
            <Button
              type="button"
              variant="quiet"
              size="compact"
              onClick={() => void openBrowser(progress.data!.authUrl!)}
            >
              <ExternalLink className="h-3.5 w-3.5" />
              {t("qoder.loginOpenBrowser")}
            </Button>
          )}
        </Notice>
      )}
      {(starting || flowId) && (
        <div className="flex gap-2">
          <Button
            type="button"
            variant="neutral"
            size="regular"
            onClick={() => void cancel()}
          >
            {t("common.cancel")}
          </Button>
        </div>
      )}
      <ConfirmDialog
        isOpen={Boolean(deleting)}
        title={t("qoder.deleteAccountTitle")}
        message={
          t(
            deleting?.isCurrent
              ? "qoder.deleteCurrentAccountConfirm"
              : "qoder.deleteAccountConfirm",
            { name: deleting ? label(deleting) : "" },
          ) + (deleteError ? `\n\n${deleteError}` : "")
        }
        confirmText={t("common.delete")}
        pending={removing}
        onConfirm={() => void remove()}
        onCancel={() => {
          if (!removing) setDeleting(null);
        }}
      />
    </section>
  );
}