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 React from "react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import type { AppId } from "@/lib/api";
import { useSubscriptionQuota } from "@/lib/query/subscription";
import type { QuotaTier, SubscriptionQuota } from "@/types/subscription";
import { QuotaBars, QuotaLines } from "@/components/quota/QuotaLines";
import { useQuotaDisplay } from "@/components/quota/useQuotaDisplay";
import {
creditsBreakdownItem,
creditsLine,
failedLines,
resetCreditsLine,
resetText,
tierLine,
type QuotaBreakdown,
type QuotaDisplay,
type QuotaLine,
} from "@/components/quota/quotaRules";
interface SubscriptionQuotaFooterProps {
appId: AppId;
inline?: boolean;
isCurrent?: boolean;
autoQueryInterval?: number;
}
interface SubscriptionQuotaViewProps {
quota: SubscriptionQuota | undefined;
loading: boolean;
/** 原样传 refetch:额度列靠它返回的结果判断点击重查的成败 */
refetch: () => unknown;
/**
* 用于 `subscription.expiredHint` 的 {tool} 插值(CLI 命令名);解耦了 hook 的 appId。
* 不传=账号由 CC Switch 自管(Codex / xAI OAuth),没有 CLI 命令可跑,提示改为去授权中心重新登录
*/
appIdForExpiredHint?: string;
inline?: boolean;
/** 按档写剩余还是已用;由外层按设置传入,这里不读设置(见 useQuotaDisplay) */
display?: QuotaDisplay;
/** 查询成功但一档都没有时写的一句(Kimi 没订阅的号返回空对象);不给时不显示 */
emptyText?: string;
/** 只手动查询、还没查过(hook 的 manualIdle):写「点刷新查询额度」 */
idle?: boolean;
}
/** 已知 tier 名称的显示映射(官方订阅 + Token Plan 共用) */
export const TIER_I18N_KEYS: Record<string, string> = {
five_hour: "subscription.fiveHour",
seven_day: "subscription.sevenDay",
seven_day_fable: "subscription.sevenDayFable",
seven_day_opus: "subscription.sevenDayOpus",
seven_day_sonnet: "subscription.sevenDaySonnet",
// Codex 免费方案的次要窗口是 30 天(付费方案为 7 天)
"30_day": "subscription.thirtyDay",
// Gemini 模型分类
gemini_pro: "subscription.geminiPro",
gemini_flash: "subscription.geminiFlash",
gemini_flash_lite: "subscription.geminiFlashLite",
// Antigravity:Gemini 一组、Claude 和 GPT 一组,各有 5 小时和每周两档;Pro 档另有 Argon 每周
agy_gemini_five_hour: "subscription.agyGeminiFiveHour",
agy_gemini_weekly: "subscription.agyGeminiWeekly",
agy_gemini_argon_weekly: "subscription.agyGeminiArgonWeekly",
agy_third_party_five_hour: "subscription.agyThirdPartyFiveHour",
agy_third_party_weekly: "subscription.agyThirdPartyWeekly",
// Token Plan(five_hour 已在上方官方映射中)
weekly_limit: "subscription.sevenDay",
// 火山方舟 Agent Plan / Coding Plan 的月窗口
monthly: "subscription.monthly",
kimi_monthly_total: "subscription.kimiMonthlyTotal",
kimi_monthly_code: "subscription.kimiMonthlyCode",
// Grok credit 额度的兜底窗口(重置距离可识别时归入 weekly_limit/monthly)
credits: "subscription.credits",
// GitHub Copilot
premium: "subscription.copilotPremium",
};
/** 卡片上不显示的档(展开时仍列出) */
const HIDDEN_INLINE_TIERS = new Set(["seven_day_sonnet"]);
/**
* 卡片上按组只留剩余最少的一档、标签写组名(展开时仍逐档列出):
* Antigravity 的 Gemini、Claude 和 GPT 两组各有 5 小时和每周两档(Pro 档 Gemini 组另有 Argon 每周),
* 四五档在卡片上放不下。Argon 也算进 Gemini 组,卡片始终两行、位置不随用量跳。
* Kimi 的两个月额度池同样只显示剩余最少的一档,明细保留各自的值。
*/
const INLINE_TIER_GROUPS: Record<string, string> = {
agy_gemini_five_hour: "subscription.agyGemini",
agy_gemini_weekly: "subscription.agyGemini",
agy_gemini_argon_weekly: "subscription.agyGemini",
agy_third_party_five_hour: "subscription.agyThirdParty",
agy_third_party_weekly: "subscription.agyThirdParty",
kimi_monthly_total: "subscription.monthly",
kimi_monthly_code: "subscription.monthly",
};
/**
* Antigravity 卡片按组合并后,使用各语言的短档名(`subscription.short.agy*`,
* 如中文「Gemini 每周 85%」「Claude 5 小时 100%」,英文「Gemini Wk 85%」「Claude 5h 100%」),
* 省掉「剩余」二字,既跟其他 App 保持 locale 一致,又能一眼分清窗口且不拉宽额度列。
*/
const AGY_COMPACT_INLINE_TIERS = new Set([
"agy_gemini_five_hour",
"agy_gemini_weekly",
"agy_gemini_argon_weekly",
"agy_third_party_five_hour",
"agy_third_party_weekly",
]);
/**
* 卡片按组折叠时优先保留的档位:Antigravity 卡片固定展示 5 小时档(每周 / Argon 放在下拉明细里),
* 避免两行在「5 小时」和「每周」之间来回跳动;若某组缺失 5 小时档则回退到组内剩余最少的一档。
*/
const PREFERRED_INLINE_GROUP_TIERS: Record<string, string> = {
"subscription.agyGemini": "agy_gemini_five_hour",
"subscription.agyThirdParty": "agy_third_party_five_hour",
};
export function collapseInlineGroups(tiers: QuotaTier[]): QuotaTier[] {
const kept = new Map<string, QuotaTier>();
for (const tier of tiers) {
const group = INLINE_TIER_GROUPS[tier.name] ?? tier.name;
const preferred = PREFERRED_INLINE_GROUP_TIERS[group];
const current = kept.get(group);
if (!current) {
kept.set(group, tier);
continue;
}
if (preferred) {
if (tier.name === preferred) {
kept.set(group, tier);
} else if (
current.name !== preferred &&
tier.utilization > current.utilization
) {
kept.set(group, tier);
}
continue;
}
if (tier.utilization > current.utilization) {
kept.set(group, tier);
}
}
return tiers.filter((tier) =>
[...kept.values()].some((keptTier) => keptTier === tier),
);
}
/**
* 卡片按组合并过档位时(Antigravity),整列做成一个下拉逐档列出:
* 「Gemini 5 小时 4h59m后重置 剩余 100%」。没合并时不需要(null)
*/
export function tierBreakdown(
t: TFunction,
tiers: QuotaTier[],
display: QuotaDisplay = "left",
): QuotaBreakdown | null {
const known = tiers.filter((tier) => tier.name in TIER_I18N_KEYS);
if (collapseInlineGroups(known).length === known.length) return null;
return {
title: t("quota.windows.title"),
openLabel: t("quota.windows.showAll"),
items: known.map((tier) => {
const label = tierLabel(t, tier.name);
const line = tierLine(t, tier, label, { display });
return {
key: tier.name,
label,
hint: resetText(t, line) ?? undefined,
value: line.value ?? line.text,
tone: line.tone,
};
}),
};
}
export function tierLabel(t: TFunction, name: string, inline = false): string {
const key = (inline && INLINE_TIER_GROUPS[name]) || TIER_I18N_KEYS[name];
return key ? t(key) : name;
}
/** 卡片合并行里的短档名(`subscription.short.*`,英日用缩写) */
export function tierShortLabel(
t: TFunction,
name: string,
inline = false,
): string {
if (inline && INLINE_TIER_GROUPS[name]) return t(INLINE_TIER_GROUPS[name]);
const key = TIER_I18N_KEYS[name];
return key ? t(key.replace("subscription.", "subscription.short.")) : name;
}
/** 已知档位 → 额度行 */
export function tierLines(
t: TFunction,
tiers: QuotaTier[],
{
inline = false,
display = "left",
}: { inline?: boolean; display?: QuotaDisplay } = {},
): { label: string; line: QuotaLine }[] {
const known = tiers
.filter((tier) => tier.name in TIER_I18N_KEYS)
.filter((tier) => !inline || !HIDDEN_INLINE_TIERS.has(tier.name));
return (inline ? collapseInlineGroups(known) : known).map((tier) => {
const compact = inline && AGY_COMPACT_INLINE_TIERS.has(tier.name);
const group = inline ? INLINE_TIER_GROUPS[tier.name] : undefined;
const label = compact
? tierShortLabel(t, tier.name)
: group
? t(group)
: tierLabel(t, tier.name);
return {
label,
line: tierLine(t, tier, label, {
short: compact ? label : group ? label : tierShortLabel(t, tier.name),
display,
compact,
}),
};
});
}
/**
* 一份查询成功的订阅额度要画的行:各档,再加存下的重置次数和 Credits 余额(只有 ChatGPT 订阅有)。
* Credits 要等额度用完才扣,卡片上平时不占位置(点开重置次数能看到),有一档用完才露出来,并排在重置次数前面:
* 卡片合并行放不下时按剩余挑段,两者都没有比例、谁在前留谁(见 pickLines)
*/
export function quotaRows(
t: TFunction,
quota: SubscriptionQuota,
locale: string,
{
inline = false,
display = "left",
}: { inline?: boolean; display?: QuotaDisplay } = {},
): { label: string; line: QuotaLine }[] {
const rows = tierLines(t, quota.tiers || [], { inline, display });
// 一档都没有时额度整块不显示,重置次数、余额也不单独出来
if (rows.length === 0) return rows;
const balance = creditsLine(t, quota.creditsBalance, { locale });
// 卡片上点开重置次数时附带余额(展开时余额自己有一行,不重复)
const resets = resetCreditsLine(t, quota.resetCredits, {
locale,
footer: inline && balance ? [creditsBreakdownItem(t, balance)] : undefined,
});
const credits =
inline && !rows.some((row) => row.line.left <= 0) ? null : balance;
const resetsRow = resets && {
label: t("quota.resetCredits.label"),
line: resets,
};
const creditsRow = credits && {
label: t("quota.credits.label"),
line: credits,
};
const extras = inline ? [creditsRow, resetsRow] : [resetsRow, creditsRow];
return [
...rows,
...extras.filter((row): row is NonNullable<typeof row> => Boolean(row)),
];
}
/** 额度查询失败的原因:登录过期 / 令牌待刷新写固定文案,其余写后端给的错误 */
export function quotaFailureReason(
t: TFunction,
quota: SubscriptionQuota,
): string {
if (quota.credentialStatus === "expired") {
return t("quota.reason.loginExpired");
}
if (quota.credentialStatus === "refresh_pending") {
return t("quota.reason.tokenRefreshPending");
}
return quota.error || t("subscription.queryFailed");
}
/** 「额度只在手动刷新时查询」开着、还没查过时的占位:一句灰字 + 刷新 */
export function ManualQuotaIdle({
inline,
loading = false,
refetch,
}: {
inline: boolean;
loading?: boolean;
refetch: () => unknown;
}) {
const { t } = useTranslation();
const text = t("quota.manualIdle");
if (inline) {
return (
<QuotaLines
lines={[{ key: "idle", left: Infinity, tone: "muted", text }]}
queriedAt={null}
loading={loading}
onRefresh={refetch}
/>
);
}
return (
<QuotaBars
className="mt-3"
title={t("subscription.title")}
rows={[]}
loading={loading}
onRefresh={refetch}
footer={<p className="text-caption text-fg-3">{text}</p>}
/>
);
}
/**
* 纯展示组件:渲染 SubscriptionQuota 的状态(not_found / parse_error 不显示;
* 登录过期 / 令牌待刷新 / 查询失败写「额度查询失败」+ 原因;成功按档写剩余或已用),支持卡片(inline)和展开两种布局。
*
* 数据源由调用方 hook 注入,方便不同的额度后端复用同一套渲染逻辑:
* - `SubscriptionQuotaFooter`(CLI 凭据路径,by appId)
* - `CodexOauthQuotaFooter`(cc-switch 自管 OAuth 路径,by ChatGPT account)
*/
export const SubscriptionQuotaView: React.FC<SubscriptionQuotaViewProps> = ({
quota,
loading,
refetch,
appIdForExpiredHint,
inline = false,
display = "left",
emptyText,
idle = false,
}) => {
const { t, i18n } = useTranslation();
// 只手动查询、还没查过:写一句提示,点刷新再查(首次手动加载期间也保留占位让图标转圈)
if (!quota && idle) {
return (
<ManualQuotaIdle inline={inline} loading={loading} refetch={refetch} />
);
}
// 无凭据 / 凭据解析错误 → 不显示(静默)
if (!quota || quota.credentialStatus === "not_found") return null;
if (quota.credentialStatus === "parse_error") return null;
if (!quota.success) {
// 登录过期和令牌待刷新都是重新登录一次就能解决,展开时给同一条提示
const expired =
quota.credentialStatus === "expired" ||
quota.credentialStatus === "refresh_pending";
const reason = quotaFailureReason(t, quota);
const lines = failedLines(t, reason);
if (inline) {
return (
<QuotaLines
lines={lines}
queriedAt={quota.queriedAt}
loading={loading}
onRefresh={refetch}
/>
);
}
return (
<QuotaBars
className="mt-3"
title={t("subscription.title")}
rows={[]}
loading={loading}
onRefresh={refetch}
footer={
<p className="text-caption">
<span className="font-medium text-danger-text">
{t("quota.failed")}
</span>{" "}
<span className="text-fg-3">
{expired
? appIdForExpiredHint
? t("subscription.expiredHint", { tool: appIdForExpiredHint })
: t("subscription.expiredHintAccounts")
: reason}
</span>
</p>
}
/>
);
}
const rows = quotaRows(t, quota, i18n.language, { inline, display });
if (rows.length === 0) {
if (!emptyText) return null;
if (inline) {
return (
<QuotaLines
lines={[
{ key: "empty", left: Infinity, tone: "muted", text: emptyText },
]}
queriedAt={quota.queriedAt}
loading={loading}
onRefresh={refetch}
/>
);
}
return (
<QuotaBars
className="mt-3"
title={t("subscription.title")}
rows={[]}
queriedAt={quota.queriedAt}
loading={loading}
onRefresh={refetch}
footer={<p className="text-caption text-fg-3">{emptyText}</p>}
/>
);
}
if (inline) {
return (
<QuotaLines
lines={rows.map((row) => row.line)}
queriedAt={quota.queriedAt}
loading={loading}
onRefresh={refetch}
breakdown={tierBreakdown(t, quota.tiers || [], display) ?? undefined}
/>
);
}
const extra = quota.extraUsage;
return (
<QuotaBars
className="mt-3"
title={t("subscription.title", { defaultValue: "Subscription Quota" })}
rows={rows}
queriedAt={quota.queriedAt}
loading={loading}
onRefresh={refetch}
footer={
extra?.isEnabled ? (
<div className="mt-2 border-t border-border pt-2 text-caption text-fg-2">
<span className="font-medium">
{t("subscription.extraUsage")}:{" "}
</span>
<span className="tabular-nums">
{extra.currency === "USD" ? "$" : ""}
{(extra.usedCredits ?? 0).toFixed(2)}
{extra.monthlyLimit != null && (
<>
{" "}
/ {extra.currency === "USD" ? "$" : ""}
{extra.monthlyLimit.toFixed(2)}
</>
)}
</span>
</div>
) : null
}
/>
);
};
/**
* CLI 凭据路径下的薄 wrapper:通过 useSubscriptionQuota(appId) 自取数据
* 后转发到 SubscriptionQuotaView。
*/
const SubscriptionQuotaFooter: React.FC<SubscriptionQuotaFooterProps> = ({
appId,
inline = false,
isCurrent = false,
autoQueryInterval = 5,
}) => {
const display = useQuotaDisplay();
const {
data: quota,
isFetching: loading,
refetch,
manualIdle,
} = useSubscriptionQuota(
appId,
isCurrent,
isCurrent && autoQueryInterval > 0,
autoQueryInterval,
);
if (!isCurrent) return null;
return (
<SubscriptionQuotaView
quota={quota}
loading={loading}
refetch={refetch}
idle={manualIdle}
// expiredHint 里的 {tool} 是 CLI 命令名:Grok 的命令是 `grok` 而非 appId
appIdForExpiredHint={appId === "grokbuild" ? "grok" : appId}
inline={inline}
display={display}
/>
);
};
export default SubscriptionQuotaFooter;