A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
import { useRef } from "react";
import {
queryOptions,
useQuery,
useQueryClient,
type QueryClient,
type UseQueryResult,
} from "@tanstack/react-query";
import { subscriptionApi } from "@/lib/api/subscription";
import { kimiOAuthApi } from "@/lib/api/kimiOAuth";
import { authApi } from "@/lib/api";
import type { AppId } from "@/lib/api/types";
import type { ProviderMeta } from "@/types";
import type {
AgyAccountQuota,
ClaudeAccountPlan,
SubscriptionQuota,
} from "@/types/subscription";
import type { ManagedAuthProvider, ManagedAuthStatus } from "@/lib/api/auth";
import { resolveManagedAccountId } from "@/lib/authBinding";
import { PROVIDER_TYPES } from "@/config/constants";
import { appHas } from "@/config/appSpecs";
import {
managedAuthStatusQuery,
managedAuthStatusQueryKey,
} from "./managedAuth";
import { resolveDisplayUsage, type LastGoodSnapshot } from "./queries";
import { isManualIdle, useQuotaPolicy, type QuotaPolicy } from "./quotaPolicy";
import { extractErrorMessage } from "@/utils/errorUtils";
const REFETCH_INTERVAL = 5 * 60 * 1000; // 5 minutes
export const subscriptionKeys = {
all: ["subscription"] as const,
quota: (appId: AppId) => [...subscriptionKeys.all, "quota", appId] as const,
};
/**
* Antigravity 的登录状态。agy 的登录可能在外部终端被 `/logout`、`/login` 换掉,
* 窗口重新聚焦时跳过 30s staleTime 重读钥匙串,及时同步「agy 在用」徽标。
*/
export const agyAuthStatusQuery = queryOptions<ManagedAuthStatus>({
...managedAuthStatusQuery("agy_oauth"),
refetchOnWindowFocus: "always",
});
function resetAgyNotFoundQuotas(queryClient: QueryClient) {
// 清掉之前作为非当前号缓存的 not_found:使用 resetQueries 而非 removeQueries,
// 保留 Query 实例与仍在观察的组件(如自动模式下的绑号官方卡)的订阅连接,
// 同时把 data 重置为 undefined,便于紧接着的 invalidateQueries 正常重查或进入 manualIdle。
return queryClient.resetQueries({
queryKey: ["agy_oauth", "quota"],
predicate: (query) =>
(query.state.data as SubscriptionQuota | undefined)?.credentialStatus ===
"not_found",
});
}
export async function invalidateAgyQuotaCaches(
queryClient: QueryClient,
currentAccountId?: string | null,
) {
await resetAgyNotFoundQuotas(queryClient);
const tasks: Promise<void>[] = [
queryClient.invalidateQueries({ queryKey: subscriptionKeys.quota("agy") }),
queryClient.invalidateQueries({ queryKey: ["agy_oauth", "last_quota"] }),
];
if (currentAccountId === undefined) {
tasks.push(
queryClient.invalidateQueries({ queryKey: ["agy_oauth", "quota"] }),
);
} else {
// 非当前号只标 stale 不触发活跃重查,避免旧当前号在 React 卸载前多查一次 agy_account_quota 读钥匙串。
tasks.push(
queryClient.invalidateQueries({
queryKey: ["agy_oauth", "quota"],
predicate: (query) => query.queryKey[2] !== currentAccountId,
refetchType: "none",
}),
);
if (currentAccountId) {
tasks.push(
queryClient.invalidateQueries({
queryKey: ["agy_oauth", "quota", currentAccountId],
}),
);
}
}
await Promise.all(tasks);
}
/**
* Refresh the actual agy login and every Antigravity quota: only the account agy is
* signed in with can be queried, so a switch changes which one shows live numbers.
*/
export async function invalidateAgyLoginCaches(
queryClient: QueryClient,
options?: { awaitQuota?: boolean },
) {
const awaitQuota = options?.awaitQuota ?? true;
if (awaitQuota) {
await resetAgyNotFoundQuotas(queryClient);
}
// 先刷新当前登录号,再按最新的当前号失效额度缓存。
await queryClient.invalidateQueries({
queryKey: agyAuthStatusQuery.queryKey,
});
const statusState = queryClient.getQueryState<ManagedAuthStatus>(
agyAuthStatusQuery.queryKey,
);
const currentAccountId =
statusState && !statusState.isInvalidated
? (statusState.data?.default_account_id ?? null)
: undefined;
const quotaInvalidation = invalidateAgyQuotaCaches(
queryClient,
currentAccountId,
);
if (awaitQuota) {
await quotaInvalidation;
} else {
void quotaInvalidation.catch(() => undefined);
}
}
const inFlightAgyFocusStatusSync = new WeakMap<QueryClient, Promise<void>>();
/**
* 窗口重新聚焦时同步 Antigravity 登录状态;同一 QueryClient 并发聚焦(如多张绑号卡各自订阅)
* 共享本次状态检查并在检查完成后立即释放锁,避免卡在后续 7–30 秒额度重查期间而吞掉下一次聚焦切换。
* 若用户在外部终端换了号,同步清理旧的 not_found 并失效额度缓存。
*/
export async function syncAgyLoginOnWindowFocus(queryClient: QueryClient) {
const inFlight = inFlightAgyFocusStatusSync.get(queryClient);
if (inFlight) {
await inFlight;
return;
}
let shouldInvalidateQuotas = false;
let nextAccountId: string | null = null;
const statusSync = (async () => {
const previous = queryClient.getQueryData<ManagedAuthStatus>(
agyAuthStatusQuery.queryKey,
);
await queryClient.invalidateQueries({
queryKey: agyAuthStatusQuery.queryKey,
});
const nextState = queryClient.getQueryState<ManagedAuthStatus>(
agyAuthStatusQuery.queryKey,
);
if (
previous !== undefined &&
nextState &&
!nextState.isInvalidated &&
nextState.data !== undefined &&
previous.default_account_id !== nextState.data.default_account_id
) {
shouldInvalidateQuotas = true;
nextAccountId = nextState.data.default_account_id ?? null;
}
})().finally(() => {
if (inFlightAgyFocusStatusSync.get(queryClient) === statusSync) {
inFlightAgyFocusStatusSync.delete(queryClient);
}
});
inFlightAgyFocusStatusSync.set(queryClient, statusSync);
await statusSync;
if (shouldInvalidateQuotas) {
await invalidateAgyQuotaCaches(queryClient, nextAccountId);
}
}
/** Refresh Claude official auth accounts, default plan, and Claude quota caches. */
export async function invalidateClaudeOfficialLoginCaches(
queryClient: QueryClient,
) {
void queryClient
.invalidateQueries({
queryKey: subscriptionKeys.quota("claude"),
})
.catch(() => undefined);
await Promise.all([
queryClient.invalidateQueries({
queryKey: managedAuthStatusQueryKey("claude_official"),
}),
queryClient.invalidateQueries({
queryKey: ["claude_official", "default_plan"],
}),
]);
}
/**
* Refresh shared quota / default-plan caches when an Auth Center account is
* removed, logged out, or switched as default.
*/
export async function invalidateManagedAuthQuotaCaches(
queryClient: QueryClient,
authProvider: ManagedAuthProvider,
options?: { accountId?: string; allAccounts?: boolean },
) {
const statusKeys: Array<readonly unknown[]> = [];
const quotaKeys: Array<readonly unknown[]> = [];
const accountId = options?.accountId?.trim();
const allAccounts = options?.allAccounts === true;
if (authProvider === "agy_oauth") {
const resetKeys: Array<readonly unknown[]> = [
subscriptionKeys.quota("agy"),
];
if (allAccounts) {
resetKeys.push(["agy_oauth", "quota"], ["agy_oauth", "last_quota"]);
} else if (accountId) {
resetKeys.push(
["agy_oauth", "quota", accountId],
["agy_oauth", "last_quota", accountId],
);
}
void Promise.all(
resetKeys.map((queryKey) =>
queryClient.resetQueries({ queryKey }).catch(() => undefined),
),
);
if (allAccounts) {
await queryClient.invalidateQueries({
queryKey: agyAuthStatusQuery.queryKey,
});
} else {
await invalidateAgyLoginCaches(queryClient);
}
return;
}
if (authProvider === "codex_oauth") {
quotaKeys.push(["codex_oauth", "quota", "default"]);
if (allAccounts) {
quotaKeys.push(["codex_oauth", "quota"]);
} else if (accountId) {
quotaKeys.push(["codex_oauth", "quota", accountId]);
}
} else if (authProvider === "github_copilot") {
quotaKeys.push(["copilot", "quota", "default"]);
if (allAccounts) {
quotaKeys.push(["copilot", "quota"]);
} else if (accountId) {
quotaKeys.push(["copilot", "quota", accountId]);
}
} else if (authProvider === "xai_oauth") {
quotaKeys.push(["xai_oauth", "quota", "default"]);
if (allAccounts) {
quotaKeys.push(["xai_oauth", "quota"]);
} else if (accountId) {
quotaKeys.push(["xai_oauth", "quota", accountId]);
}
} else if (authProvider === "claude_official") {
statusKeys.push(["claude_official", "default_plan"]);
quotaKeys.push(subscriptionKeys.quota("claude"));
if (allAccounts) {
quotaKeys.push(["claude_official", "quota"]);
} else if (accountId) {
quotaKeys.push(["claude_official", "quota", accountId]);
}
} else if (authProvider === "codebuddy_oauth") {
if (allAccounts) {
quotaKeys.push(["codebuddy_oauth", "quota"]);
} else if (accountId) {
quotaKeys.push(["codebuddy_oauth", "quota", accountId]);
}
}
void Promise.all(
quotaKeys.map((queryKey) =>
queryClient.resetQueries({ queryKey }).catch(() => undefined),
),
);
await Promise.all(
statusKeys.map((queryKey) => queryClient.invalidateQueries({ queryKey })),
);
}
/**
* Grok 的 CLI 登录(~/.grok/auth.json)可能被后端改写之后要重读的缓存:
* 切到/保存绑了 xAI 账号的 Grok 官方卡会把原登录收进授权中心再换号,
* 移除/登出 xAI 账号也可能把 CLI 登录换掉。授权中心的 xAI 列表和
* 没绑号的 Grok 官方卡(查 CLI 当前登录的号)都要重读。
*/
export async function invalidateGrokCliLoginCaches(queryClient: QueryClient) {
await queryClient.invalidateQueries({
queryKey: managedAuthStatusQueryKey("xai_oauth"),
});
await queryClient.invalidateQueries({
queryKey: subscriptionKeys.quota("grokbuild"),
});
}
/**
* reject 且无可展示值时的失败占位:首次查询就失败(data 为 undefined),或
* react-query 保留的旧成功已超出 keep-last-good 窗口——合成一个失败结果,让
* 订阅视图仍渲染「查询失败」+ 刷新按钮,而不是 footer 整体消失、无从手动重查。
*/
const QUERY_REJECTED_PLACEHOLDER: SubscriptionQuota = {
tool: "",
credentialStatus: "valid",
credentialMessage: null,
success: false,
tiers: [],
extraUsage: null,
error: null,
queriedAt: null,
};
/**
* Keep-last-good:与 useUsageQuery 同一策略(resolveDisplayUsage)。
*
* 后端对纯传输失败(网络/超时/读体中断)已 reject——react-query 保留上次 data
* 并触发 retry,但那份 data 是陈旧的:以 `rejected` 标志交给 resolveDisplayUsage
* 按同一窗口处理(窗口内继续展示,超窗透出失败),与仍以 `Ok(success:false)`
* 返回的瞬时失败(HTTP 5xx/429)行为一致。确定性失败(过期/鉴权/解析)不掩盖,
* 立即透出。
*
* `scopeKey` 标识查询身份(appId / 绑定的账号 id):身份变化时丢弃旧快照,
* 避免用上一个账号的额度掩盖新账号的瞬时失败。
*/
function useQuotaKeepLastGood<T extends SubscriptionQuota>(
query: UseQueryResult<T>,
scopeKey: string,
policy: QuotaPolicy,
) {
const lastGoodRef = useRef<{
key: string;
snap: LastGoodSnapshot<T> | null;
}>({ key: scopeKey, snap: null });
if (lastGoodRef.current.key !== scopeKey) {
lastGoodRef.current = { key: scopeKey, snap: null };
}
if (query.data === undefined && query.dataUpdatedAt === 0 && !query.isError) {
lastGoodRef.current.snap = null;
}
const { data, lastGood } = resolveDisplayUsage(
query.data,
query.dataUpdatedAt,
lastGoodRef.current.snap,
Date.now(),
{ rejected: query.isError },
);
lastGoodRef.current.snap = lastGood;
return {
...query,
/** 只手动查询、还没查过:给界面放「点刷新查询额度」 */
manualIdle: isManualIdle(policy, query),
data:
data ??
(query.isError
? ({
...QUERY_REJECTED_PLACEHOLDER,
error: extractErrorMessage(query.error) || null,
} as T)
: undefined),
};
}
/**
* 开了自动查询时按 `minutes` 分钟轮询(至少 1 分钟),后台和窗口聚焦时也重取;没开或间隔为 0 时都不重取。
*/
function autoRefetch(
autoQuery: boolean,
minutes: number,
): {
refetchInterval: number | false;
refetchIntervalInBackground: boolean;
refetchOnWindowFocus: boolean;
} {
const refetchInterval =
autoQuery && minutes > 0 ? Math.max(minutes, 1) * 60 * 1000 : false;
return {
refetchInterval,
refetchIntervalInBackground: Boolean(refetchInterval),
refetchOnWindowFocus: Boolean(refetchInterval),
};
}
export function useSubscriptionQuota(
appId: AppId,
enabled: boolean,
autoQuery = false,
autoQueryIntervalMinutes = 5,
) {
const policy = useQuotaPolicy();
const autoAllowed = policy.autoAllowed;
const query = useQuery({
queryKey: subscriptionKeys.quota(appId),
queryFn: () => subscriptionApi.getQuota(appId),
enabled: autoAllowed && enabled && appHas(appId, "officialSubscription"),
...autoRefetch(autoAllowed && autoQuery, autoQueryIntervalMinutes),
staleTime:
autoQueryIntervalMinutes > 0
? Math.max(autoQueryIntervalMinutes, 1) * 60 * 1000
: REFETCH_INTERVAL,
retry: 1,
});
return useQuotaKeepLastGood(query, appId, policy);
}
export interface UseCodexOauthQuotaOptions {
enabled?: boolean;
/** 是否启用自动轮询与窗口 focus 重取 */
autoQuery?: boolean;
autoQueryIntervalMinutes?: number;
}
/**
* Codex OAuth 订阅额度查询 hook(按账号 ID)
*
* 直接以 cc-switch 自管的 ChatGPT 账号 ID 查询额度,供认证中心里逐个账号
* 展示用量时复用。Query key 与 `useCodexOauthQuota` 一致,绑定到同一账号的
* 供应商卡片与账号列表会自动去重共享同一份请求缓存。
* accountId 为 null 时使用 "default" 占位,让后端 fallback 到默认账号。
*/
export function useCodexOauthQuotaByAccountId(
accountId: string | null,
options: UseCodexOauthQuotaOptions = {},
) {
const {
enabled = true,
autoQuery = false,
autoQueryIntervalMinutes = 5,
} = options;
const policy = useQuotaPolicy();
const autoAllowed = policy.autoAllowed;
const query = useQuery({
queryKey: ["codex_oauth", "quota", accountId ?? "default"],
queryFn: () => subscriptionApi.getCodexOauthQuota(accountId),
enabled: autoAllowed && enabled,
...autoRefetch(autoAllowed && autoQuery, autoQueryIntervalMinutes),
staleTime:
autoQueryIntervalMinutes > 0
? Math.max(autoQueryIntervalMinutes, 1) * 60 * 1000
: REFETCH_INTERVAL,
retry: 1,
});
return useQuotaKeepLastGood(query, accountId ?? "default", policy);
}
/**
* Codex OAuth (ChatGPT Plus/Pro 反代) 订阅额度查询 hook
*
* 与 `useSubscriptionQuota` 平行:数据走 cc-switch 自管的 OAuth token,
* 而不是 Codex CLI 的 ~/.codex/auth.json。账号 ID 从供应商 meta 的
* authBinding 中解析,再委托给 `useCodexOauthQuotaByAccountId`。
*/
export function useCodexOauthQuota(
meta: ProviderMeta | undefined,
options: UseCodexOauthQuotaOptions = {},
) {
const accountId = resolveManagedAccountId(meta, PROVIDER_TYPES.CODEX_OAUTH);
return useCodexOauthQuotaByAccountId(accountId, options);
}
/**
* xAI OAuth (SuperGrok 反代) 订阅额度查询 hook
*
* 与 `useCodexOauthQuota` 平行:数据走 cc-switch 自管的 xAI OAuth token,
* 而不是 Grok CLI 的 ~/.grok/auth.json;后端复用同一个 grok.com 账单端点,
* 因此与 Grok Build 分区的官方订阅显示同一份额度。
*/
export function useXaiOauthQuota(
meta: ProviderMeta | undefined,
options: UseCodexOauthQuotaOptions = {},
) {
const accountId = resolveManagedAccountId(meta, PROVIDER_TYPES.XAI_OAUTH);
return useXaiOauthQuotaByAccountId(accountId, options);
}
/**
* xAI OAuth 订阅额度(按账号 ID):授权中心逐个账号显示额度时用。
* Query key 与 `useXaiOauthQuota` 一致,绑定同一账号的供应商卡片共用缓存。
*/
export function useXaiOauthQuotaByAccountId(
accountId: string | null,
options: UseCodexOauthQuotaOptions = {},
) {
const {
enabled = true,
autoQuery = false,
autoQueryIntervalMinutes = 5,
} = options;
const policy = useQuotaPolicy();
const autoAllowed = policy.autoAllowed;
const query = useQuery({
queryKey: ["xai_oauth", "quota", accountId ?? "default"],
queryFn: () => subscriptionApi.getXaiOauthQuota(accountId),
enabled: autoAllowed && enabled,
...autoRefetch(autoAllowed && autoQuery, autoQueryIntervalMinutes),
staleTime:
autoQueryIntervalMinutes > 0
? Math.max(autoQueryIntervalMinutes, 1) * 60 * 1000
: REFETCH_INTERVAL,
retry: 1,
});
return useQuotaKeepLastGood(query, accountId ?? "default", policy);
}
let agyForceRefreshEpoch = 0;
/** 授权中心「全部刷新」时调用:让下一次 Antigravity 额度重查跳过后端短时缓存。 */
export function markAgyQuotaForceRefresh() {
agyForceRefreshEpoch += 1;
}
/**
* Antigravity 账号的剩余额度(按账号 ID)。agy 当前登着的号问 agy 的 `/usage`,
* 别的号返回切走前最后一次查到的(没有时为 not_found)。
* 授权中心逐个账号、以及绑了这个账号的官方卡共用同一份缓存。
*/
export function useAgyAccountQuota(
accountId: string,
options: UseCodexOauthQuotaOptions = {},
) {
const {
enabled = true,
autoQuery = false,
autoQueryIntervalMinutes = 5,
} = options;
const force = useRef(false);
const seenForceEpoch = useRef(agyForceRefreshEpoch);
const policy = useQuotaPolicy();
const autoAllowed = policy.autoAllowed;
const query = useQuery<AgyAccountQuota>({
queryKey: ["agy_oauth", "quota", accountId],
queryFn: () => {
const skipCache =
force.current || seenForceEpoch.current !== agyForceRefreshEpoch;
force.current = false;
seenForceEpoch.current = agyForceRefreshEpoch;
return subscriptionApi.getAgyAccountQuota(accountId, skipCache);
},
enabled: autoAllowed && enabled,
...autoRefetch(autoAllowed && autoQuery, autoQueryIntervalMinutes),
// 缓存里如果是之前作为非当前号拿到的 not_found,成为当前号重新挂载时立刻重查,不等 5 分钟。
staleTime: (current) =>
current.state.data?.credentialStatus === "not_found"
? 0
: REFETCH_INTERVAL,
// 每次查都要冷启动一次 agy(~7–10s,超时 30s),失败/超时不自动重试以免翻倍耗时
retry: false,
});
const keepLastGood = useQuotaKeepLastGood(query, accountId, policy);
const refetch: typeof query.refetch = (refetchOptions) => {
force.current = true;
return query.refetch(refetchOptions);
};
return {
...keepLastGood,
refetch,
};
}
/**
* 只读 Antigravity 账号本地保存的上次额度快照(不读钥匙串、不启动 `agy`),
* 供授权中心非当前账号展示切走前的历史额度,不受手动查询开关限制。
*/
export function useAgyAccountLastQuota(accountId: string, enabled = true) {
return useQuery({
queryKey: ["agy_oauth", "last_quota", accountId],
queryFn: () => subscriptionApi.getAgyAccountLastQuota(accountId),
enabled: Boolean(accountId) && enabled,
staleTime: 0,
refetchOnWindowFocus: false,
retry: false,
});
}
/**
* Kimi 官方账号的剩余额度(按授权中心账号 ID,也就是它的供应商 ID)。
* 令牌快过期时后端会拿 Kimi 同款文件锁续期;授权中心那一行和官方卡共用同一份缓存。
*/
export function useKimiAccountQuota(
accountId: string,
options: UseCodexOauthQuotaOptions = {},
) {
const {
enabled = true,
autoQuery = false,
autoQueryIntervalMinutes = 5,
} = options;
const policy = useQuotaPolicy();
const autoAllowed = policy.autoAllowed;
const query = useQuery({
queryKey: ["kimi_oauth", "quota", accountId],
queryFn: () => kimiOAuthApi.quota(accountId),
enabled: autoAllowed && enabled,
...autoRefetch(autoAllowed && autoQuery, autoQueryIntervalMinutes),
staleTime: REFETCH_INTERVAL,
retry: 1,
});
return useQuotaKeepLastGood(query, accountId, policy);
}
let codebuddyForceRefreshEpoch = 0;
/** 授权中心「全部刷新」时调用:让下一次 CodeBuddy 额度重查同样跳过后端 5 分钟缓存。 */
export function markCodebuddyQuotaForceRefresh() {
codebuddyForceRefreshEpoch += 1;
}
/**
* CodeBuddy 账号的套餐与积分(按授权中心账号 ID,用该账号副本里的令牌只读查询)。
* 后端 5 分钟内走缓存;`refresh()` 与授权中心「全部刷新」会跳过缓存重查。
*/
export function useCodebuddyAccountQuota(accountId: string, lang: string) {
const force = useRef(false);
const seenForceEpoch = useRef(codebuddyForceRefreshEpoch);
const policy = useQuotaPolicy();
const query = useQuery({
queryKey: ["codebuddy_oauth", "quota", accountId, lang],
queryFn: () => {
const skipCache =
force.current || seenForceEpoch.current !== codebuddyForceRefreshEpoch;
force.current = false;
seenForceEpoch.current = codebuddyForceRefreshEpoch;
return authApi.codebuddyAccountQuota(accountId, lang, skipCache);
},
enabled: policy.autoAllowed,
staleTime: REFETCH_INTERVAL,
refetchOnWindowFocus: false,
retry: 1,
});
const refresh = () => {
force.current = true;
return query.refetch();
};
return { ...query, refresh, manualIdle: isManualIdle(policy, query) };
}
/**
* 绑了账号的 Claude 官方卡额度(按账号查):在用的号读默认登录,没在用的读它自己的账号目录。
* 令牌过期时后端会在那个目录里跑一次 `claude -p /usage`(Claude Code 自己刷新),可能要几秒。
*/
export function useClaudeAccountQuota(
accountId: string,
options: UseCodexOauthQuotaOptions = {},
) {
const {
enabled = true,
autoQuery = false,
autoQueryIntervalMinutes = 5,
} = options;
const policy = useQuotaPolicy();
const autoAllowed = policy.autoAllowed;
const queryClient = useQueryClient();
const query = useQuery({
queryKey: ["claude_official", "quota", accountId],
queryFn: async () => {
const quota = await subscriptionApi.getClaudeAccountQuota(accountId);
refreshAccountsOnPlanChange(queryClient, accountId, quota.plan);
return quota;
},
enabled: autoAllowed && enabled,
...autoRefetch(autoAllowed && autoQuery, autoQueryIntervalMinutes),
staleTime: REFETCH_INTERVAL,
retry: 1,
});
return useQuotaKeepLastGood(query, accountId, policy);
}
/**
* 查额度时后端顺手把凭据里的套餐记进了账号;和账号列表里的不一样(升级 / 降级过)时重新拉
* 列表,卡片副标题和授权中心显示的套餐就跟着变。
*/
function refreshAccountsOnPlanChange(
queryClient: QueryClient,
accountId: string,
plan: ClaudeAccountPlan | null | undefined,
) {
if (!plan?.subscriptionType) return;
const statusKey = ["managed-auth-status", "claude_official"];
const account = queryClient
.getQueryData<ManagedAuthStatus>(statusKey)
?.accounts.find((item) => item.id === accountId);
if (!account) return;
if (
(account.plan ?? null) !== plan.subscriptionType ||
(account.rate_limit_tier ?? null) !== (plan.rateLimitTier ?? null)
) {
void queryClient.invalidateQueries({ queryKey: statusKey });
}
}
/**
* Claude Code 默认登录的套餐(没绑账号的官方卡显示)。默认登录会随切卡、在 Claude Code 里
* 重新登录而变,所以不久存,回到窗口时重读。
*/
export function useClaudeDefaultPlan(enabled: boolean) {
return useQuery({
queryKey: ["claude_official", "default_plan"],
queryFn: () => subscriptionApi.getClaudeDefaultPlan(),
enabled,
staleTime: 60 * 1000,
refetchOnWindowFocus: true,
retry: false,
});
}