Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(mobile): 任务菜单显示 Claude、SuperGrok 订阅额度与 ChatGPT credits (#5367)

Dash8426052a72d7
diff --git a/apps/desktop/src/shared/claudeSubscriptionUsage.ts b/apps/desktop/src/shared/claudeSubscriptionUsage.ts
index 3a372bd864..d847ee5c16 100644
--- a/apps/desktop/src/shared/claudeSubscriptionUsage.ts
+++ b/apps/desktop/src/shared/claudeSubscriptionUsage.ts
@@ -20,61 +20,23 @@
* 而不是抛错;完全解析不出内容时返回 null,调用方按"无数据"处理(绝不从 token 用量反推)。
*/
-/** 单个用量窗口(5h / 周 / 分模型周)。utilization 一律 0-100 已用百分比。 */
-export interface ClaudeUsageWindow {
- utilization: number;
- /** Unix epoch 秒;缺失 = 未知。 */
- resetsAt?: number | null;
- /** 服务端判定的告警级别(端点 limits[].severity,如 'normal';headers 源无此字段)。 */
- severity?: string | null;
-}
-
-/** 分模型周窗口(端点 limits[] 里 kind=weekly_scoped 的条目)。 */
-export interface ClaudeScopedUsageWindow extends ClaudeUsageWindow {
- /** scope.model.display_name,如 'Fable' / 'Opus' / 'Sonnet'。 */
- modelDisplayName: string;
- /** scope.model.id(端点常为 null)。 */
- modelId?: string | null;
-}
-
-/** extra usage(usage credits)状态 —— 套餐打满后的按量付费通道。 */
-export interface ClaudeExtraUsageSnapshot {
- isEnabled: boolean;
- /** 0-100;仅启用且服务端给值时有。 */
- utilization?: number | null;
- /**
- * 已用 credits(服务端原值)。单位未文档化,不要当货币金额展示;
- * 仅保留原始值,等拿到 extra-usage 账号实样后再定展示口径。
- */
- usedCredits?: number | null;
- /** 月度上限原值;0 = 不限。单位未文档化,不要当货币金额展示。 */
- monthlyLimit?: number | null;
-}
-
-export interface ClaudeSubscriptionUsageSnapshot {
- /** 5 小时滚动窗口。 */
- fiveHour?: ClaudeUsageWindow | null;
- /** 总周限窗口。 */
- sevenDay?: ClaudeUsageWindow | null;
- /** 分模型周窗口(仅 oauth-endpoint 源有)。 */
- scoped?: ClaudeScopedUsageWindow[];
- /** 订阅套餐(凭证 blob 的 subscriptionType: pro / max 等,记录时由 main 一并写入)。 */
- subscriptionType?: string | null;
- /** headers 源的整体状态:allowed / allowed_warning / rejected。 */
- rateLimitStatus?: string | null;
- /** headers 源:当前代表性(最紧)窗口名,如 'five_hour' / 'seven_day'。 */
- representativeClaim?: string | null;
- extraUsage?: ClaudeExtraUsageSnapshot | null;
- source?: 'oauth-endpoint' | 'unified-headers' | string | null;
- /** 快照生成时间(ms epoch)。 */
- updatedAt?: number | null;
- /**
- * 归属账号的 OAuth token 指纹(sha256 截断, main 记录时附加, 不含 token 原文)。
- * 同机换号时 reader 据此判定持久化快照已过期, 避免 chip 闪上一个账号的余量。
- * 缺失(旧快照 / 仅 headers 源)时按未知归属处理, 不据此清除。
- */
- accountFingerprint?: string | null;
-}
+import {
+ matchScopedWindowForModel,
+ scopedWindowBelongsToFamily,
+ type ClaudeExtraUsageSnapshot,
+ type ClaudeScopedUsageWindow,
+ type ClaudeSubscriptionUsageSnapshot,
+ type ClaudeUsageWindow,
+} from '@cindy/maker-shared/subscription-usage';
+
+// 快照契约与模型窗口匹配在 maker-shared,mobile 任务菜单复用同一份口径。
+export type {
+ ClaudeExtraUsageSnapshot,
+ ClaudeScopedUsageWindow,
+ ClaudeSubscriptionUsageSnapshot,
+ ClaudeUsageWindow,
+} from '@cindy/maker-shared/subscription-usage';
+export { claudeModelFamily, matchScopedWindowForModel } from '@cindy/maker-shared/subscription-usage';
function isPlainObject(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -370,58 +332,6 @@ export function mergeClaudeSubscriptionUsageSnapshot(
};
}
-// ── 方案 B:当前模型 → scoped 窗口匹配 ───────────────────────────────────────
-
-/**
- * 从 model id 提取模型家族名(与端点 scope.model.display_name 对齐的小写词)。
- * 'claude-fable-5[1m]' → 'fable';'claude-opus-4-8' → 'opus';'sonnet' → 'sonnet'
- * 未识别 → null(调用方回退总周限)。
- */
-export function claudeModelFamily(modelId: string | null | undefined): string | null {
- const normalized = (modelId ?? '').trim().toLowerCase().replace(/\[[^\]]*\]\s*$/, '');
- if (!normalized) return null;
- // 顺序无关 —— 家族名互斥地出现在 Anthropic model id 里。
- for (const family of ['fable', 'mythos', 'opus', 'sonnet', 'haiku']) {
- if (normalized.includes(family)) return family;
- }
- return null;
-}
-
-/**
- * 判断一个分模型周窗口是否属于指定家族。
- *
- * 优先用窗口自带的 `modelId` 经 `claudeModelFamily` 归类(权威、精确);`modelId`
- * 缺失或无法归类(端点常为 null,或 id 形态不在识别表里)时,回退用 `modelDisplayName`
- * 的变体包含匹配——端点对 display_name 的口径历史上有 "Fable" / "Claude Fable" /
- * "Fable 5" 等形态,精确等于会漏掉变体(issue #3244)。家族名互斥,不会跨家族误命中。
- *
- * matcher(`matchScopedWindowForModel`)与 legacy 兜底去重共用这一份口径,避免两份
- * includes 规则漂移。
- */
-function scopedWindowBelongsToFamily(
- window: ClaudeScopedUsageWindow,
- family: string,
-): boolean {
- const fromId = claudeModelFamily(window.modelId);
- if (fromId) return fromId === family;
- return window.modelDisplayName.trim().toLowerCase().includes(family);
-}
-
-/**
- * 找当前会话模型对应的分模型周窗口(chip 方案 B:第二栏跟随当前模型)。
- * 找不到 → null,调用方回退 sevenDay 总周限(绝不臆造)。家族归属口径见
- * scopedWindowBelongsToFamily。
- */
-export function matchScopedWindowForModel(
- scoped: ClaudeScopedUsageWindow[] | null | undefined,
- modelId: string | null | undefined,
-): ClaudeScopedUsageWindow | null {
- if (!scoped || scoped.length === 0) return null;
- const family = claudeModelFamily(modelId);
- if (!family) return null;
- return scoped.find((w) => scopedWindowBelongsToFamily(w, family)) ?? null;
-}
-
// ── 告警判定(chip 变红的口径;tooltip 另有 status 分流,见 TodaySpendChip) ───
/**
diff --git a/apps/desktop/src/shared/xaiSubscriptionUsage.ts b/apps/desktop/src/shared/xaiSubscriptionUsage.ts
index 2b94013ce6..a50225f6a2 100644
--- a/apps/desktop/src/shared/xaiSubscriptionUsage.ts
+++ b/apps/desktop/src/shared/xaiSubscriptionUsage.ts
@@ -13,35 +13,15 @@
* 字段在但解不出数、只有未来 billingPeriodEnd、或非周窗口,都不能推断 0%。
*/
-/** 分产品周用量(页面「Grok Build 2%」)。 */
-export interface XaiProductUsage {
- /** 上游 product id,如 GrokBuild。 */
- product: string;
- /** 0-100 已用百分比。 */
- usagePercent: number;
-}
+import {
+ isXaiWeeklyUsageCurrent,
+ type XaiProductUsage,
+ type XaiSubscriptionUsageSnapshot,
+} from '@cindy/maker-shared/subscription-usage';
-export interface XaiSubscriptionUsageSnapshot {
- /** 套餐展示名,如 SuperGrok Heavy。 */
- planLabel?: string | null;
- /** 0-100 本周已用百分比(页面「2% 已使用」)。 */
- creditUsagePercent?: number | null;
- /** Unix epoch 秒;周窗口重置时刻。 */
- resetsAt?: number | null;
- /** 分产品已用百分比。 */
- productUsage?: XaiProductUsage[];
- /**
- * 额外使用点数余额。单位按 grok.com 页面为美元;0 / 缺失不要当「免费额度」展示。
- */
- prepaidBalance?: number | null;
- source?: 'cli-billing' | string | null;
- updatedAt?: number | null;
- /**
- * 稳定账号指纹(OIDC sub 的不可逆哈希)。换 SuperGrok 号时用来丢掉旧快照。
- * 不是 access token 哈希 —— token 刷新会轮换。
- */
- accountFingerprint?: string | null;
-}
+// 快照契约与新鲜度判定在 maker-shared,mobile 任务菜单复用同一份口径。
+export type { XaiProductUsage, XaiSubscriptionUsageSnapshot } from '@cindy/maker-shared/subscription-usage';
+export { isXaiWeeklyUsageCurrent, XAI_USAGE_STALE_MS } from '@cindy/maker-shared/subscription-usage';
function isPlainObject(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -198,34 +178,6 @@ export function formatXaiProductLabel(product: string): string {
return trimmed.replace(/([a-z])([A-Z])/g, '$1 $2');
}
-/** 超过这个时间没刷新到新快照,就不再当「当前额度」展示。 */
-export const XAI_USAGE_STALE_MS = 30 * 60 * 1000;
-
-/**
- * 周窗口数字是否还能当当前额度:过了 TTL,或已经过了 resetsAt 却还没新快照,
- * 都不当当前值(避免无限显示旧百分比 / 卡在「重置中」)。套餐名仍可单独展示。
- */
-export function isXaiWeeklyUsageCurrent(
- snapshot: XaiSubscriptionUsageSnapshot | null | undefined,
- nowMs: number,
-): boolean {
- if (!snapshot) return false;
- if (
- typeof snapshot.creditUsagePercent !== 'number'
- || !Number.isFinite(snapshot.creditUsagePercent)
- ) {
- return false;
- }
- if (typeof snapshot.updatedAt !== 'number' || !Number.isFinite(snapshot.updatedAt) || snapshot.updatedAt <= 0) {
- return false;
- }
- if (nowMs - snapshot.updatedAt > XAI_USAGE_STALE_MS) return false;
- if (typeof snapshot.resetsAt === 'number' && Number.isFinite(snapshot.resetsAt) && snapshot.resetsAt > 0) {
- if (nowMs >= snapshot.resetsAt * 1000) return false;
- }
- return true;
-}
-
const WINDOW_ALERT_UTILIZATION_PERCENT = 90;
/** chip 警示:周已用 ≥90%。 */
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index 2690bd4815..9e0182475d 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -267,6 +267,31 @@ describe("mobile maker transport", () => {
"Account scope unsupported",
);
});
+ it("reads subscription snapshots by family, scoping only independent accounts", async () => {
+ const calls: Array<[string, unknown[] | undefined]> = [];
+ const invoke: RemoteInvoke = async (_deviceId, channel, args) => {
+ calls.push([channel, args]);
+ return (args?.length ? { providerId: args[0] } : { creditUsagePercent: 1 }) as never;
+ };
+ const maker = createMobileMakerTransport({ deviceId: "dev-1", invoke });
+ await maker.getSubscriptionUsage("claude", "anthropic");
+ await maker.getSubscriptionUsage("xai");
+ await maker.getSubscriptionUsage("xai", "grok-second");
+ await maker.getClaudeSessionRoute("s1");
+ expect(calls).toEqual([
+ ["maker:usage:claude-subscription", []],
+ ["maker:usage:xai-subscription", []],
+ ["maker:usage:xai-subscription", ["grok-second"]],
+ ["maker:claude-session-route:get", ["s1"]],
+ ]);
+ const legacy = createMobileMakerTransport({
+ deviceId: "dev-1",
+ invoke: async () => ({ creditUsagePercent: 1 }) as never,
+ });
+ await expect(legacy.getSubscriptionUsage("xai", "grok-second")).rejects.toThrow(
+ "Account scope unsupported",
+ );
+ });
it("documents the remote channels used by the mobile transport", () => {
expect(MOBILE_MAKER_CHANNELS).toEqual([
"maker:create-session",
@@ -305,6 +330,9 @@ describe("mobile maker transport", () => {
"local-db:messages:estimatedSessionValue",
"maker:usage:codex-rate-limits",
"maker:usage:codex-rate-limit-reset",
+ "maker:usage:claude-subscription",
+ "maker:usage:xai-subscription",
+ "maker:claude-session-route:get",
"maker:api-key:present",
"maker:list-agent-commands",
"maker:list-agent-skills",
diff --git a/apps/mobile/src/__tests__/readSessionMenuAccountUsage.test.ts b/apps/mobile/src/__tests__/readSessionMenuAccountUsage.test.ts
index a81b43b8cf..2fb5f1af17 100644
--- a/apps/mobile/src/__tests__/readSessionMenuAccountUsage.test.ts
+++ b/apps/mobile/src/__tests__/readSessionMenuAccountUsage.test.ts
@@ -1,6 +1,17 @@
import { describe, expect, it, vi } from "vitest";
import type { MobileCodexRateLimitsResult } from "@cindy/maker-shared/device-link-contract";
-import { readSessionMenuAccountUsage } from "@/session/readSessionMenuAccountUsage";
+import { REMOTE_INVOKE_ALLOWLIST } from "@cindy/device-link";
+import {
+ NATIVE_SUBSCRIPTION_AUTHS,
+ NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS,
+} from "@cindy/model-providers/types";
+import { SUBSCRIPTION_USAGE_CHANNELS } from "@/device-link/mobileMakerTransport";
+import {
+ isSubscriptionUsageSource,
+ readSessionMenuAccountUsage,
+ sessionSubscriptionFamily,
+ SUBSCRIPTION_USAGE_SOURCES,
+} from "@/session/readSessionMenuAccountUsage";
import type { RemoteSession } from "@/session/types";
const session = {
@@ -26,6 +37,8 @@ const reader = () => ({
primary: { usedPercent: 40, windowMinutes: 300 },
updatedAt: 1000,
}),
+ getSubscriptionUsage: vi.fn<() => Promise<unknown>>().mockResolvedValue(null),
+ getClaudeSessionRoute: vi.fn<() => Promise<unknown>>().mockResolvedValue(null),
});
describe("existing remote quota compatibility", () => {
@@ -35,6 +48,7 @@ describe("existing remote quota compatibility", () => {
const selected = { ...session, providerId: provider.id };
await readSessionMenuAccountUsage(selected, r, provider);
expect(r.getCodexRateLimits).toHaveBeenCalledWith(provider.id);
+ r.getAccountUsage.mockClear();
r.getCodexRateLimits.mockRejectedValue(new Error('legacy host'));
await expect(readSessionMenuAccountUsage(selected, r, provider)).rejects.toThrow('legacy host');
expect(r.getAccountUsage).not.toHaveBeenCalled();
@@ -49,7 +63,9 @@ describe("existing remote quota compatibility", () => {
windows: [{ remainingPercent: 75, minutes: 300 }],
});
expect(r.getCodexRateLimits).toHaveBeenCalledOnce();
- expect(r.getAccountUsage).not.toHaveBeenCalled();
+ // Only the account snapshot's credits are read alongside the control read.
+ expect(r.getAccountUsage).toHaveBeenCalledWith("codex");
+ expect(result.credits).toBeUndefined();
expect(JSON.stringify(result)).not.toContain("private");
});
@@ -92,7 +108,7 @@ describe("existing remote quota compatibility", () => {
},
);
- it.each([null, undefined, "", " ", "anthropic", "custom"])(
+ it.each([null, undefined, "", " ", "custom"])(
"does not attribute Gateway usage to a Pi task without a confirmed Gateway source: %s",
async (providerId) => {
const r = reader();
@@ -102,7 +118,7 @@ describe("existing remote quota compatibility", () => {
currency: "CNY",
});
for (const agentKind of ["pi", "cc"] as const) {
- for (const model of ["claude-sonnet-4-6", "chatgpt/gpt-5"]) {
+ for (const model of ["claude-sonnet-4-6"]) {
const result = await readSessionMenuAccountUsage(
{ ...session, agentKind, providerId, model },
r,
@@ -365,3 +381,320 @@ describe("existing remote quota compatibility", () => {
]);
});
});
+
+describe("subscription quota for every subscription family", () => {
+ const nowSec = () => Math.floor(Date.now() / 1000);
+ const claudeSnapshot = () => ({
+ subscriptionType: "max",
+ updatedAt: 2000,
+ fiveHour: { utilization: 30, resetsAt: nowSec() + 3600 },
+ sevenDay: { utilization: 55, resetsAt: nowSec() + 86400 },
+ scoped: [
+ { modelDisplayName: "Opus", utilization: 92, resetsAt: nowSec() + 86400 },
+ { modelDisplayName: "Sonnet", utilization: 10 },
+ ],
+ });
+
+ it.each(["cc", "pi", "codex"] as const)(
+ "reads the desktop Claude subscription for an Anthropic %s task",
+ async (agentKind) => {
+ const r = reader();
+ r.getSubscriptionUsage.mockResolvedValue(claudeSnapshot());
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind, providerId: "anthropic", model: "claude-opus-5-5" },
+ r,
+ );
+ expect(r.getSubscriptionUsage).toHaveBeenCalledWith("claude", "anthropic");
+ expect(result).toMatchObject({
+ source: "claude",
+ plan: "max",
+ updatedAt: 2000,
+ amounts: [],
+ });
+ expect(result.windows.map(({ id, minutes, modelLabel, remainingPercent }) => ({
+ id,
+ minutes,
+ modelLabel,
+ remainingPercent,
+ }))).toEqual([
+ { id: "five-hour", minutes: 300, modelLabel: undefined, remainingPercent: 70 },
+ { id: "seven-day", minutes: 10080, modelLabel: undefined, remainingPercent: 45 },
+ { id: "model:seven-day", minutes: 10080, modelLabel: "Opus", remainingPercent: 8 },
+ ]);
+ expect(r.getAccountUsage).not.toHaveBeenCalled();
+ expect(r.getCodexRateLimits).not.toHaveBeenCalled();
+ },
+ );
+
+ it("skips expired and malformed Claude windows instead of inventing quota", async () => {
+ const r = reader();
+ r.getSubscriptionUsage.mockResolvedValue({
+ fiveHour: { utilization: 99, resetsAt: 1 },
+ sevenDay: { utilization: "55" },
+ scoped: [null, { utilization: 10 }],
+ });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind: "cc", providerId: "anthropic", model: "claude-sonnet-5" },
+ r,
+ );
+ expect(result).toMatchObject({ source: "claude", windows: [], plan: null });
+ });
+
+ it("reads an independent subscription account by its own id", async () => {
+ const r = reader();
+ const provider = { id: "grok-second", auth: { method: "oauth" as const, native: "xai" as const } };
+ await readSessionMenuAccountUsage(
+ { ...session, agentKind: "pi", providerId: provider.id, model: "grok-4.6" },
+ r,
+ provider,
+ );
+ expect(r.getSubscriptionUsage).toHaveBeenCalledWith("xai", "grok-second");
+ });
+
+ it("reads the SuperGrok weekly quota and purchased credits", async () => {
+ const r = reader();
+ r.getSubscriptionUsage.mockResolvedValue({
+ planLabel: "SuperGrok Heavy",
+ creditUsagePercent: 25,
+ resetsAt: nowSec() + 86400,
+ prepaidBalance: 4.5,
+ updatedAt: Date.now(),
+ });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind: "pi", providerId: "xai", model: "grok-4.6" },
+ r,
+ );
+ expect(r.getSubscriptionUsage).toHaveBeenCalledWith("xai", "xai");
+ expect(result).toMatchObject({
+ source: "xai",
+ plan: "SuperGrok Heavy",
+ windows: [{ id: "week", minutes: 10080, remainingPercent: 75 }],
+ amounts: [{ id: "balance", amount: 4.5, currency: "USD" }],
+ });
+ });
+
+ it("does not present a stale SuperGrok percentage or balance as current", async () => {
+ const r = reader();
+ r.getSubscriptionUsage.mockResolvedValue({
+ planLabel: "SuperGrok",
+ creditUsagePercent: 25,
+ prepaidBalance: 4.5,
+ updatedAt: Date.now() - 2 * 60 * 60_000,
+ });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind: "cc", providerId: "xai", model: "xai/grok-4.6" },
+ r,
+ );
+ expect(result).toMatchObject({ source: "xai", plan: "SuperGrok", windows: [], amounts: [] });
+ });
+
+ it.each([
+ ["cc", "chatgpt/gpt-5", "chatgpt", "codex"],
+ ["pi", "chatgpt/gpt-5", "chatgpt", "codex"],
+ ["cc", "xai/grok-4.6", "xai", "xai"],
+ ["codex", "xai/grok-4.6", "xai", "xai"],
+ ] as const)(
+ "attributes a providerless %s %s task to the default %s account",
+ async (agentKind, model, source, kind) => {
+ const r = reader();
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind, providerId: null, model },
+ r,
+ );
+ expect(result.source).toBe(source);
+ if (kind === "xai") expect(r.getSubscriptionUsage).toHaveBeenCalledWith("xai", undefined);
+ else expect(r.getAccountUsage).toHaveBeenCalledWith("codex");
+ expect(r.getClaudeSessionRoute).not.toHaveBeenCalled();
+ },
+ );
+
+ it("does not attribute a bridge model to another family's selected account", async () => {
+ const r = reader();
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind: "cc", providerId: "anthropic", model: "xai/grok-4.6" },
+ r,
+ );
+ expect(result.source).toBe("unavailable");
+ expect(r.getSubscriptionUsage).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["subscription", "claude"],
+ ["gateway", "gateway"],
+ [null, "unavailable"],
+ ] as const)(
+ "follows the host-observed route of a default Claude Code task: %s",
+ async (route, source) => {
+ const r = reader();
+ r.getClaudeSessionRoute.mockResolvedValue(route);
+ r.getAccountUsage.mockResolvedValue({ currency: "USD", spend: 1, maxBudget: 10 });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind: "cc", providerId: null, model: "claude-opus-5-5" },
+ r,
+ );
+ expect(r.getClaudeSessionRoute).toHaveBeenCalledWith("s1");
+ expect(result.source).toBe(source);
+ if (source === "claude")
+ expect(r.getSubscriptionUsage).toHaveBeenCalledWith("claude", undefined);
+ else expect(r.getSubscriptionUsage).not.toHaveBeenCalled();
+ },
+ );
+
+ it("keeps a default Claude Code task unattributed on hosts without the route channel", async () => {
+ const r = reader();
+ r.getClaudeSessionRoute.mockRejectedValue({ code: "CHANNEL_NOT_ALLOWED" });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind: "cc", providerId: null, model: "claude-opus-5-5" },
+ r,
+ );
+ expect(result.source).toBe("unavailable");
+ expect(r.getSubscriptionUsage).not.toHaveBeenCalled();
+ expect(r.getAccountUsage).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { code: "NOT_CONNECTED", message: "offline" },
+ new Error("[DEVICE_LINK_TIMEOUT] timed out"),
+ ])("fails the read on a transient route lookup error so cached quota is kept: %o", async (error) => {
+ const r = reader();
+ r.getClaudeSessionRoute.mockRejectedValue(error);
+ await expect(
+ readSessionMenuAccountUsage(
+ { ...session, agentKind: "cc", providerId: null, model: "claude-opus-5-5" },
+ r,
+ ),
+ ).rejects.toBe(error);
+ expect(r.getSubscriptionUsage).not.toHaveBeenCalled();
+ });
+
+ it("treats a channel-not-allowed error message as an older host", async () => {
+ const r = reader();
+ r.getClaudeSessionRoute.mockRejectedValue(new Error("[DEVICE_LINK_CHANNEL_NOT_ALLOWED] nope"));
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind: "cc", providerId: null, model: "claude-opus-5-5" },
+ r,
+ );
+ expect(result.source).toBe("unavailable");
+ });
+
+ it("surfaces an old host's missing subscription channel as a failed read", async () => {
+ const r = reader();
+ const error = { code: "CHANNEL_NOT_ALLOWED" };
+ r.getSubscriptionUsage.mockRejectedValue(error);
+ await expect(
+ readSessionMenuAccountUsage(
+ { ...session, agentKind: "cc", providerId: "anthropic", model: "claude-opus-5-5" },
+ r,
+ ),
+ ).rejects.toBe(error);
+ });
+});
+
+describe("new subscription families cannot be skipped", () => {
+ it.each(NATIVE_SUBSCRIPTION_AUTHS)(
+ "routes the default %s account to its own subscription quota",
+ async (family) => {
+ const r = reader();
+ const providerId = NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS[family];
+ const routed = {
+ ...session,
+ agentKind: family === "codex" ? ("codex" as const) : ("pi" as const),
+ providerId,
+ model: family === "codex" ? "gpt-6-astra" : "any-model",
+ };
+ expect(sessionSubscriptionFamily(routed)).toBe(family);
+ const result = await readSessionMenuAccountUsage(routed, r);
+ expect(result.source).toBe(SUBSCRIPTION_USAGE_SOURCES[family]);
+ expect(isSubscriptionUsageSource(result.source)).toBe(true);
+ },
+ );
+
+ it("reads every subscription snapshot channel the desktop exposes remotely", () => {
+ const exposed = [...REMOTE_INVOKE_ALLOWLIST].filter((channel) =>
+ /^maker:usage:[a-z0-9-]+-subscription$/.test(channel),
+ );
+ expect(exposed.length).toBeGreaterThan(0);
+ expect(Object.values(SUBSCRIPTION_USAGE_CHANNELS).sort()).toEqual(exposed.sort());
+ });
+
+ it.each(["en", "ja", "ko", "zh-CN", "zh-TW"])(
+ "labels every subscription source in %s",
+ async (locale) => {
+ const { default: strings } = await import(`../i18n/locales/${locale}/session.json`);
+ const labels = strings.menu.usage.source as Record<string, string>;
+ for (const source of Object.values(SUBSCRIPTION_USAGE_SOURCES))
+ expect(labels[source]?.trim()).toBeTruthy();
+ },
+ );
+});
+
+describe("ChatGPT credits", () => {
+ it.each([
+ [{ hasCredits: true, unlimited: false, balance: "1,234.5" }, { balance: 1234.5, status: null }],
+ [{ hasCredits: true, unlimited: true, balance: null }, { balance: null, status: "unlimited" }],
+ [{ hasCredits: false, unlimited: false, balance: "0" }, { balance: 0, status: "depleted" }],
+ [{ hasCredits: false, unlimited: false, balance: "12.5" }, { balance: 12.5, status: "depleted" }],
+ [{ hasCredits: true, unlimited: false }, { balance: null, status: "available" }],
+ [{ hasCredits: true, unlimited: false, balance: "n/a" }, { balance: null, status: "available" }],
+ ])("projects the account credit state %o", async (credits, expected) => {
+ const r = reader();
+ r.getCodexRateLimits.mockResolvedValue({
+ ...quota(),
+ rateLimits: { primary: { usedPercent: 25, windowMinutes: 300 }, credits },
+ } as MobileCodexRateLimitsResult);
+ const result = await readSessionMenuAccountUsage(session, r);
+ expect(result.credits).toEqual(expected);
+ expect(result.windows).toHaveLength(1);
+ });
+
+ it("reads credits from the account snapshot when the control read omits them", async () => {
+ const r = reader();
+ r.getAccountUsage.mockResolvedValue({
+ appServerBuckets: {
+ codex: { credits: { hasCredits: true, unlimited: false, balance: "42" } },
+ },
+ });
+ const result = await readSessionMenuAccountUsage(session, r);
+ expect(result).toMatchObject({
+ windows: [{ remainingPercent: 75 }],
+ credits: { balance: 42, status: null },
+ });
+ });
+
+ it("fails the read when the credits snapshot is transiently unavailable", async () => {
+ const r = reader();
+ const error = new Error("[NOT_CONNECTED] offline");
+ r.getAccountUsage.mockRejectedValue(error);
+ await expect(readSessionMenuAccountUsage(session, r)).rejects.toBe(error);
+ });
+
+ it("reads credits of the selected independent account only", async () => {
+ const r = reader();
+ const provider = { id: "openai-second", auth: { method: "oauth" as const, native: "codex" as const } };
+ await readSessionMenuAccountUsage({ ...session, providerId: provider.id }, r, provider);
+ expect(r.getAccountUsage).toHaveBeenCalledWith("codex", "openai-second");
+ });
+
+ it("reads credits from the ChatGPT bridge web slot", async () => {
+ const r = reader();
+ r.getAccountUsage.mockResolvedValue({
+ credits: { hasCredits: false, unlimited: false },
+ webSnapshot: {
+ primary: { usedPercent: 20 },
+ credits: { hasCredits: true, unlimited: false, balance: "8" },
+ },
+ });
+ const result = await readSessionMenuAccountUsage(
+ { ...session, agentKind: "pi", model: "chatgpt/gpt-5" },
+ r,
+ );
+ expect(result.credits).toEqual({ balance: 8, status: null });
+ });
+
+ it("omits credits when the account reports none", async () => {
+ const r = reader();
+ r.getAccountUsage.mockResolvedValue({ primary: { usedPercent: 10 } });
+ const result = await readSessionMenuAccountUsage(session, r);
+ expect(result).not.toHaveProperty("credits");
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts b/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
index e3548c94a3..5336c371b3 100644
--- a/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
+++ b/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
@@ -84,4 +84,21 @@ describe("task menu usage presentation", () => {
});
expect(rows[1]).toMatchObject({ value: "等待刷新", warning: false });
});
+ it.each([
+ [{ balance: 1234.5, status: null }, "剩余 1,234.50", false],
+ [{ balance: null, status: "unlimited" }, "不限", false],
+ [{ balance: 0, status: "depleted" }, "剩余 0.00 · 已耗尽", true],
+ [{ balance: null, status: "available" }, "可用", false],
+ ] as const)("shows ChatGPT credits %o after the quota windows", (credits, value, warning) => {
+ const account: SessionMenuAccountUsage = {
+ source: "chatgpt",
+ plan: null,
+ updatedAt: 1,
+ amounts: [],
+ windows: [{ id: "a", minutes: 300, remainingPercent: 50, resetsAt: null }],
+ credits,
+ };
+ const rows = accountUsageRows(account, i18n.t, "zh-CN");
+ expect(rows[1]).toEqual({ label: "Credits", value, warning });
+ });
});
diff --git a/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx b/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx
index ae9bc7acaf..b81a5b0fda 100644
--- a/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx
+++ b/apps/mobile/src/__tests__/useSessionMenuUsage.test.tsx
@@ -34,9 +34,9 @@ const session = (id: string): RemoteSession =>
function reader(): SessionMenuUsageReader {
return {
getCodexRateLimits: vi.fn(async () => account),
- getAccountUsage: vi.fn(async () => {
- throw new Error("unavailable");
- }),
+ getAccountUsage: vi.fn(async (): Promise<unknown> => null),
+ getSubscriptionUsage: vi.fn(async () => null),
+ getClaudeSessionRoute: vi.fn(async () => null),
getSessionEstimatedValue: vi.fn(async () => ({
totalValueMoney: {
amount: 12,
@@ -178,7 +178,8 @@ describe("menu usage refresh lifecycle", () => {
account: { ...account.account, planType: "wrong-provider" },
}),
);
- expect(h.value.account?.source).toBe("unavailable");
+ expect(h.value.account?.source).toBe("xai");
+ expect(h.value.account?.plan).toBeNull();
expect(h.value.account?.windows).toEqual([]);
});
it("does not reuse web quota across an unresolved source and a Gateway switch", async () => {
@@ -191,8 +192,10 @@ describe("menu usage refresh lifecycle", () => {
agentKind: "pi" as const,
model: "chatgpt/gpt-5",
};
+ // A providerless non-bridge Pi model has no confirmed account route.
+ const unresolved = { ...task, providerId: null, model: "gpt-5" };
await h.render(task);
- await h.render({ ...task, providerId: null });
+ await h.render(unresolved);
expect(h.value.account?.source).toBe("unavailable");
expect(r.getAccountUsage).toHaveBeenCalledTimes(1);
vi.mocked(r.getAccountUsage).mockResolvedValue({
@@ -206,7 +209,7 @@ describe("menu usage refresh lifecycle", () => {
);
expect(h.value.account?.source).toBe("gateway");
expect(h.value.account?.windows).toEqual([]);
- await h.render({ ...task, providerId: null });
+ await h.render(unresolved);
expect(h.value.account?.source).toBe("unavailable");
expect(h.value.account?.amounts).toEqual([]);
expect(r.getAccountUsage).toHaveBeenCalledTimes(2);
@@ -218,6 +221,7 @@ describe("menu usage refresh lifecycle", () => {
vi.mocked(r.getCodexRateLimits).mockRejectedValue(
new Error("DEVICE_OFFLINE"),
);
+ vi.mocked(r.getAccountUsage).mockRejectedValue(new Error("DEVICE_OFFLINE"));
vi.mocked(r.getSessionEstimatedValue).mockRejectedValue(
new Error("DEVICE_OFFLINE"),
);
@@ -233,6 +237,7 @@ describe("menu usage refresh lifecycle", () => {
vi.mocked(r.getCodexRateLimits).mockRejectedValue(
new Error("CHANNEL_NOT_ALLOWED"),
);
+ vi.mocked(r.getAccountUsage).mockRejectedValue(new Error("unavailable"));
const h = harness(r);
await h.render();
expect(h.value.account).toBeNull();
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index d6288f0fba..ed49274d78 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -60,6 +60,10 @@ import type {
MobileVoiceDictionaryLearningResult,
} from "@cindy/maker-shared/device-link-contract";
import type { ProviderView } from "@cindy/model-providers/registry";
+import {
+ NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS,
+ type NativeSubscriptionAuth,
+} from "@cindy/model-providers/types";
import type { RewindPreviewPayload } from "@/session/rewindPreview";
import type {
MobileRemoteMediaFetchOptions,
@@ -127,6 +131,17 @@ export interface CreateSessionResult {
export type MobileAgentKind = "claude-code" | "codex" | "pi";
+/**
+ * 订阅家族 → 被控端余量快照 channel。ChatGPT 走 Codex 自有控制面
+ * (getCodexRateLimits / getAccountUsage),其余家族各有一个只读快照 channel。
+ * 以 NativeSubscriptionAuth 为键:新增订阅家族时这里漏接会直接编译失败。
+ */
+export type SubscriptionUsageKind = Exclude<NativeSubscriptionAuth, "codex">;
+export const SUBSCRIPTION_USAGE_CHANNELS = {
+ claude: "maker:usage:claude-subscription",
+ xai: "maker:usage:xai-subscription",
+} as const satisfies Record<SubscriptionUsageKind, string>;
+
export type MobileSlashCommand =
| { kind: "agent-builtin"; name: string; description: string }
| {
@@ -583,6 +598,17 @@ export interface MobileMakerTransport {
): Promise<{ totalValueMoney?: unknown; totalValueUsd?: number }>;
/** Codex app-server authoritative windows plus banked reset credits and a bound reset offer. */
getCodexRateLimits(providerId?: string): Promise<MobileCodexRateLimitsResult>;
+ /**
+ * 被控端订阅账号余量快照(只读,cached-first;Claude 5h/周/分模型窗口、SuperGrok 周用量)。
+ * 默认账号不传 providerId;独立账号的回包必须回显同一 providerId,否则按旧被控端处理。
+ * 老被控端 CHANNEL_NOT_ALLOWED → 调用方保留「暂未获取」提示。
+ */
+ getSubscriptionUsage(
+ kind: SubscriptionUsageKind,
+ providerId?: string,
+ ): Promise<unknown>;
+ /** cc 默认路由会话在被控端 proxy 观察到的生效计费路由('gateway' | 'subscription' | null)。 */
+ getClaudeSessionRoute(sessionId: string): Promise<unknown>;
/** Consume the desktop-issued offer; retries must pass the same idempotency key. */
resetCodexRateLimits(
idempotencyKey: string,
@@ -1177,6 +1203,24 @@ export function createMobileMakerTransport({
throw new Error("PRECONDITION_FAILED: Account scope unsupported");
return result;
},
+ getSubscriptionUsage: async (kind, providerId) => {
+ // 默认账号不带参数,兼容只认默认账号的老被控端。
+ const scoped =
+ providerId && providerId !== NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS[kind];
+ const result = await call<unknown>(
+ SUBSCRIPTION_USAGE_CHANNELS[kind],
+ scoped ? [providerId] : undefined,
+ );
+ if (
+ scoped &&
+ result &&
+ (result as { providerId?: string }).providerId !== providerId
+ )
+ throw new Error("PRECONDITION_FAILED: Account scope unsupported");
+ return result;
+ },
+ getClaudeSessionRoute: (sessionId) =>
+ call("maker:claude-session-route:get", [sessionId]),
resetCodexRateLimits: async (idempotencyKey, providerId) => {
const result = await call<MobileCodexRateLimitResetResult>(
"maker:usage:codex-rate-limit-reset",
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index 55e91ed23b..c6f293d7cc 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -426,6 +426,11 @@
"today": "Used today",
"unavailable": "Unavailable",
"quotaUnavailable": "Account quota unavailable",
+ "credits": "Credits",
+ "creditsRemaining": "{{credits}} remaining",
+ "creditsUnlimited": "Unlimited",
+ "creditsDepleted": "Depleted",
+ "creditsAvailable": "Available",
"lastUpdated": "Last updated {{time}}",
"taskUsage": "Task usage",
"taskValue": "Task value",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 3e69839d2e..e162163817 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -426,6 +426,11 @@
"today": "今日の使用額",
"unavailable": "未取得",
"quotaUnavailable": "アカウントのクォータを取得できません",
+ "credits": "Credits",
+ "creditsRemaining": "残り {{credits}}",
+ "creditsUnlimited": "無制限",
+ "creditsDepleted": "残高なし",
+ "creditsAvailable": "残高あり",
"lastUpdated": "最終更新 {{time}}",
"taskUsage": "タスクの使用量",
"taskValue": "タスクの価値",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index bf8b68c94e..7f327e83c2 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -422,6 +422,11 @@
"today": "오늘 사용액",
"unavailable": "가져오지 못함",
"quotaUnavailable": "계정 할당량을 가져오지 못했습니다",
+ "credits": "Credits",
+ "creditsRemaining": "{{credits}} 남음",
+ "creditsUnlimited": "무제한",
+ "creditsDepleted": "소진",
+ "creditsAvailable": "사용 가능",
"lastUpdated": "마지막 업데이트 {{time}}",
"taskUsage": "작업 사용량",
"taskValue": "작업 가치",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index ea0359ce5e..e0fae9c1e4 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -422,6 +422,11 @@
"today": "今日已用",
"unavailable": "暂未获取",
"quotaUnavailable": "暂未获取账号配额",
+ "credits": "Credits",
+ "creditsRemaining": "剩余 {{credits}}",
+ "creditsUnlimited": "不限",
+ "creditsDepleted": "已耗尽",
+ "creditsAvailable": "可用",
"lastUpdated": "上次更新 {{time}}",
"taskUsage": "本任务用量",
"taskValue": "本任务价值",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index ef5b5bb50d..f0f0bab3e2 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -426,6 +426,11 @@
"today": "今日已用",
"unavailable": "暫未取得",
"quotaUnavailable": "暫未取得帳號配額",
+ "credits": "Credits",
+ "creditsRemaining": "剩餘 {{credits}}",
+ "creditsUnlimited": "不限",
+ "creditsDepleted": "已耗盡",
+ "creditsAvailable": "可用",
"lastUpdated": "上次更新 {{time}}",
"taskUsage": "本任務用量",
"taskValue": "本任務價值",
diff --git a/apps/mobile/src/session/SessionUsageSummary.tsx b/apps/mobile/src/session/SessionUsageSummary.tsx
index 7c4488cff5..e76774211c 100644
--- a/apps/mobile/src/session/SessionUsageSummary.tsx
+++ b/apps/mobile/src/session/SessionUsageSummary.tsx
@@ -18,6 +18,7 @@ import {
} from "@/theme/tokens";
import type { RemoteSession } from "./types";
import type { useSessionMenuUsage } from "./useSessionMenuUsage";
+import { isSubscriptionUsageSource } from "./readSessionMenuAccountUsage";
import {
accountUsageRows,
formatSessionUsageMoney,
@@ -116,8 +117,7 @@ export function SessionUsageSummary({
amounts.mixed || (!amounts.total && account?.accountOnly)
? t("session.menu.usage.taskUsage")
: amounts.total?.kind === "value-estimate" ||
- (!amounts.total &&
- (source === "chatgpt" || source === "claude" || source === "xai"))
+ (!amounts.total && isSubscriptionUsageSource(source))
? t("session.menu.usage.taskValue")
: t("session.menu.usage.taskCost");
const stale =
diff --git a/apps/mobile/src/session/readSessionMenuAccountUsage.ts b/apps/mobile/src/session/readSessionMenuAccountUsage.ts
index 29dc0545c2..2005bb95c1 100644
--- a/apps/mobile/src/session/readSessionMenuAccountUsage.ts
+++ b/apps/mobile/src/session/readSessionMenuAccountUsage.ts
@@ -1,16 +1,29 @@
import { selectCodexUsageForModel } from "@cindy/maker-shared/codex-usage-buckets";
+import { formatRemoteError } from "@cindy/maker-shared/device-link-contract";
+import {
+ isXaiWeeklyUsageCurrent,
+ matchScopedWindowForModel,
+ type ClaudeScopedUsageWindow,
+ type XaiSubscriptionUsageSnapshot,
+} from "@cindy/maker-shared/subscription-usage";
+import {
+ NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS,
+ type NativeSubscriptionAuth,
+} from "@cindy/model-providers/types";
import type { MobileMakerTransport } from "@/device-link/mobileMakerTransport";
import type { RemoteSession } from "./types";
import {
canUseLocalCodexRateLimitControl,
- isSessionOpenAiAccount,
type OpenAiAccountProvider,
shouldFallbackToLegacyCodexUsage,
} from "./sessionControls";
type Reader = Pick<
MobileMakerTransport,
- "getCodexRateLimits" | "getAccountUsage"
+ | "getCodexRateLimits"
+ | "getAccountUsage"
+ | "getSubscriptionUsage"
+ | "getClaudeSessionRoute"
>;
/** Mobile presentation only; this shape is never sent through device-link. */
export interface SessionMenuAccountUsage {
@@ -32,7 +45,26 @@ export interface SessionMenuAccountUsage {
}>;
/** The account read cannot prove this task's frozen auth route. */
accountOnly?: boolean;
+ /** ChatGPT's own credits (not money): the reported balance and/or the account's credit state. */
+ credits?: {
+ balance: number | null;
+ status: "unlimited" | "depleted" | "available" | null;
+ };
+}
+/** Display source of each subscription family; keyed so a new family cannot be skipped. */
+export const SUBSCRIPTION_USAGE_SOURCES = {
+ codex: "chatgpt",
+ claude: "claude",
+ xai: "xai",
+} as const satisfies Record<NativeSubscriptionAuth, SessionMenuAccountUsage["source"]>;
+export function isSubscriptionUsageSource(
+ source: SessionMenuAccountUsage["source"] | undefined,
+): boolean {
+ return (Object.values(SUBSCRIPTION_USAGE_SOURCES) as string[]).includes(
+ source ?? "",
+ );
}
+
const empty = (
source: SessionMenuAccountUsage["source"],
): SessionMenuAccountUsage => ({
@@ -48,8 +80,101 @@ const record = (value: unknown): Record<string, unknown> =>
value !== null && typeof value === "object"
? (value as Record<string, unknown>)
: {};
+const clampPercent = (value: number) => Math.max(0, Math.min(100, value));
+
+type ClaudeSessionRoute = "gateway" | "subscription" | null;
+
+/** The subscription family behind a provider selection, or null for Gateway / API routes. */
+function accountFamily(
+ providerId: string | null,
+ accountProvider?: OpenAiAccountProvider,
+): NativeSubscriptionAuth | null {
+ if (!providerId) return null;
+ for (const [family, id] of Object.entries(
+ NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS,
+ ))
+ if (id === providerId) return family as NativeSubscriptionAuth;
+ if (accountProvider?.id !== providerId || accountProvider.auth?.method !== "oauth")
+ return null;
+ return accountProvider.auth.native ?? null;
+}
+
+/**
+ * The subscription this task consumes, mirroring the desktop device-link chip.
+ * Model bridge prefixes decide the consumed account; an unselected Claude Code route
+ * is only attributed when the host has observed it (claudeRoute), never from login state.
+ */
+export function sessionSubscriptionFamily(
+ session: Pick<
+ RemoteSession,
+ "agentKind" | "model" | "providerId" | "remoteHostId"
+ >,
+ accountProvider?: OpenAiAccountProvider,
+ claudeRoute: ClaudeSessionRoute = null,
+): NativeSubscriptionAuth | null {
+ if (session.remoteHostId?.trim()) return null;
+ if (canUseLocalCodexRateLimitControl(session, accountProvider)) return "codex";
+ const provider = session.providerId?.trim() || null;
+ const family = accountFamily(provider, accountProvider);
+ const model = session.model.trim();
+ // The host routes these prefixes to the subscription bridge on their own; with no
+ // selected provider they consume the family's default account.
+ if (model.startsWith("chatgpt/"))
+ return session.agentKind !== "codex" && (family === "codex" || provider === null)
+ ? "codex"
+ : null;
+ if (model.startsWith("xai/"))
+ return family === "xai" || provider === null ? "xai" : null;
+ // Pi catalog ids lack the xai/ prefix, so the selected account decides.
+ if (family === "xai" || family === "claude") return family;
+ return provider === null &&
+ session.agentKind === "cc" &&
+ claudeRoute === "subscription"
+ ? "claude"
+ : null;
+}
-/** Reuse the existing remote Codex read, including its account-change fallback guard. */
+type FamilyReader = (
+ session: RemoteSession,
+ reader: Reader,
+) => Promise<SessionMenuAccountUsage>;
+/** One reader per subscription family. Adding a family without a reader fails type checking. */
+const SUBSCRIPTION_READERS: Record<NativeSubscriptionAuth, FamilyReader> = {
+ codex: (session, reader) =>
+ session.agentKind === "codex"
+ ? readCodexAccount(session, reader)
+ : readChatgptBridgeAccount(session, reader),
+ claude: readClaudeAccount,
+ xai: readXaiAccount,
+};
+
+function isChannelNotAllowedError(error: unknown): boolean {
+ return formatRemoteError(error).includes("CHANNEL_NOT_ALLOWED");
+}
+
+/** The host's observed billing route for a default-route Claude Code task. */
+async function readDefaultClaudeRoute(
+ session: RemoteSession,
+ reader: Reader,
+): Promise<ClaudeSessionRoute> {
+ const model = session.model.trim();
+ if (
+ session.agentKind !== "cc" ||
+ session.providerId?.trim() ||
+ model.startsWith("chatgpt/") ||
+ model.startsWith("xai/")
+ )
+ return null;
+ // Only an older host without the channel means "route unknown". Transient failures
+ // must reject so the menu keeps the previous quota and marks it stale.
+ const route = await reader.getClaudeSessionRoute(session.id).catch((error) => {
+ if (isChannelNotAllowedError(error)) return null;
+ throw error;
+ });
+ return route === "gateway" || route === "subscription" ? route : null;
+}
+
+/** Read the account quota behind this task's route; never another route's account. */
export async function readSessionMenuAccountUsage(
session: RemoteSession,
reader: Reader,
@@ -57,34 +182,17 @@ export async function readSessionMenuAccountUsage(
): Promise<SessionMenuAccountUsage> {
if (session.remoteHostId?.trim()) return empty("unavailable");
// The host projects runtime-effective selection onto providerId. Missing
- // selection alone proves neither a Gateway nor an OpenAI web account route.
+ // selection alone proves neither a Gateway nor a subscription route.
const provider = session.providerId?.trim() || null;
const model = session.model.trim();
- if (canUseLocalCodexRateLimitControl(session, accountProvider))
- return readCodexAccount(session, reader);
- if (
- session.agentKind !== "codex" &&
- isSessionOpenAiAccount(provider, accountProvider) &&
- model.startsWith("chatgpt/")
- ) {
- const payload = record(await (session.providerId && session.providerId !== 'openai' ? reader.getAccountUsage("codex", session.providerId) : reader.getAccountUsage("codex")));
- // The ChatGPT bridge uses the web slot, not the CLI's app-server bucket.
- const web =
- payload.webSnapshot ?? (payload.source === "openai-web" ? payload : null);
- return projectCodexAccount(
- web,
- session.model,
- undefined,
- null,
- null,
- false,
- );
- }
+ const claudeRoute = await readDefaultClaudeRoute(session, reader);
+ const family = sessionSubscriptionFamily(session, accountProvider, claudeRoute);
+ if (family) return SUBSCRIPTION_READERS[family](session, reader);
const gateway =
provider === "xd" ||
(provider === null &&
- session.agentKind === "codex" &&
- model.startsWith("codex/"));
+ ((session.agentKind === "codex" && model.startsWith("codex/")) ||
+ claudeRoute === "gateway"));
if (gateway) {
const payload = record(await reader.getAccountUsage("claude-code"));
const result = empty("gateway");
@@ -114,12 +222,114 @@ export async function readSessionMenuAccountUsage(
}
return result;
}
- // Claude/xAI subscription and personal balance reads are not exposed by existing remote APIs.
return empty(
- provider && !["anthropic", "xai", "openai"].includes(provider)
- ? "api"
- : "unavailable",
+ provider && !accountFamily(provider, accountProvider) ? "api" : "unavailable",
+ );
+}
+
+/** Independent accounts are read by their own id; the family default reads without one. */
+function accountScope(session: RemoteSession): string | undefined {
+ return session.providerId?.trim() || undefined;
+}
+
+async function readChatgptBridgeAccount(
+ session: RemoteSession,
+ reader: Reader,
+): Promise<SessionMenuAccountUsage> {
+ const payload = record(await (session.providerId && session.providerId !== 'openai' ? reader.getAccountUsage("codex", session.providerId) : reader.getAccountUsage("codex")));
+ // The ChatGPT bridge uses the web slot, not the CLI's app-server bucket.
+ const web =
+ payload.webSnapshot ?? (payload.source === "openai-web" ? payload : null);
+ return projectCodexAccount(
+ web,
+ session.model,
+ undefined,
+ null,
+ null,
+ false,
+ );
+}
+
+async function readClaudeAccount(
+ session: RemoteSession,
+ reader: Reader,
+): Promise<SessionMenuAccountUsage> {
+ const snapshot = record(
+ await reader.getSubscriptionUsage("claude", accountScope(session)),
);
+ const result = empty("claude");
+ result.plan =
+ typeof snapshot.subscriptionType === "string" &&
+ snapshot.subscriptionType.trim()
+ ? snapshot.subscriptionType.trim()
+ : null;
+ result.updatedAt = finite(snapshot.updatedAt) ? snapshot.updatedAt : null;
+ const now = Date.now();
+ const add = (
+ id: string,
+ minutes: number,
+ raw: unknown,
+ modelLabel?: string,
+ ) => {
+ const window = record(raw);
+ if (!finite(window.utilization)) return;
+ const resetsAt = finite(window.resetsAt) ? window.resetsAt : null;
+ if (resetsAt !== null && resetsAt * 1000 <= now) return;
+ result.windows.push({
+ id,
+ ...(modelLabel ? { modelLabel } : {}),
+ minutes,
+ remainingPercent: clampPercent(100 - window.utilization),
+ resetsAt,
+ });
+ };
+ // Overall and model-specific limits both constrain the task; show each that applies.
+ add("five-hour", 300, snapshot.fiveHour);
+ add("seven-day", 10080, snapshot.sevenDay);
+ const scoped = (Array.isArray(snapshot.scoped) ? snapshot.scoped : []).filter(
+ (window): window is ClaudeScopedUsageWindow =>
+ typeof record(window).modelDisplayName === "string",
+ );
+ const modelWindow = matchScopedWindowForModel(scoped, session.model);
+ if (modelWindow)
+ add("model:seven-day", 10080, modelWindow, modelWindow.modelDisplayName);
+ return result;
+}
+
+async function readXaiAccount(
+ session: RemoteSession,
+ reader: Reader,
+): Promise<SessionMenuAccountUsage> {
+ const snapshot = record(
+ await reader.getSubscriptionUsage("xai", accountScope(session)),
+ );
+ const result = empty("xai");
+ result.plan =
+ typeof snapshot.planLabel === "string" && snapshot.planLabel.trim()
+ ? snapshot.planLabel.trim()
+ : null;
+ result.updatedAt = finite(snapshot.updatedAt) ? snapshot.updatedAt : null;
+ const current = isXaiWeeklyUsageCurrent(
+ snapshot as XaiSubscriptionUsageSnapshot,
+ Date.now(),
+ );
+ if (current && finite(snapshot.creditUsagePercent)) {
+ result.windows.push({
+ id: "week",
+ minutes: 10080,
+ remainingPercent: clampPercent(100 - snapshot.creditUsagePercent),
+ resetsAt: finite(snapshot.resetsAt) ? snapshot.resetsAt : null,
+ });
+ }
+ // A zero balance is not a free allowance; only show purchased credits, and only
+ // while the snapshot is current (the desktop card hides both together).
+ if (current && finite(snapshot.prepaidBalance) && snapshot.prepaidBalance > 0)
+ result.amounts.push({
+ id: "balance",
+ amount: snapshot.prepaidBalance,
+ currency: "USD",
+ });
+ return result;
}
async function readCodexAccount(
@@ -130,15 +340,25 @@ async function readCodexAccount(
let byLimitId: unknown;
let observedAt: number | null = null;
let plan: string | null = null;
+ let creditSources: unknown[] = [];
+ const readAccountUsage = () =>
+ session.providerId && session.providerId !== 'openai'
+ ? reader.getAccountUsage("codex", session.providerId)
+ : reader.getAccountUsage("codex");
try {
const result = await (session.providerId && session.providerId !== 'openai' ? reader.getCodexRateLimits(session.providerId) : reader.getCodexRateLimits());
raw = result.rateLimits;
byLimitId = result.rateLimitsByLimitId;
plan = result.account.planType;
observedAt = Date.now();
+ // The control read omits credits; the desktop card reads them from the account
+ // snapshot this read just recorded. Every host has that channel, so a failure is
+ // transient and fails the read: the menu keeps the previous values marked stale.
+ const usage = record(await readAccountUsage());
+ creditSources = [usage, ...Object.values(record(usage.appServerBuckets))];
} catch (error) {
if ((session.providerId && session.providerId !== 'openai') || !shouldFallbackToLegacyCodexUsage(error)) throw error;
- raw = await (session.providerId && session.providerId !== 'openai' ? reader.getAccountUsage("codex", session.providerId) : reader.getAccountUsage("codex"));
+ raw = await readAccountUsage();
}
return projectCodexAccount(
raw,
@@ -147,6 +367,7 @@ async function readCodexAccount(
observedAt,
plan,
true,
+ creditSources,
);
}
@@ -157,6 +378,7 @@ function projectCodexAccount(
observedAt: number | null,
plan: string | null,
accountOnly: boolean,
+ creditSources: unknown[] = [],
): SessionMenuAccountUsage {
const payload = record(raw);
const now = Date.now();
@@ -207,6 +429,11 @@ function projectCodexAccount(
});
}
}
+ const credits = projectCodexCredits([
+ ...snapshots,
+ payload,
+ ...creditSources.map(record),
+ ]);
return {
source: "chatgpt",
accountOnly,
@@ -214,5 +441,35 @@ function projectCodexAccount(
updatedAt: timestamps.length > 0 ? Math.min(...timestamps) : observedAt,
windows,
amounts: [],
+ ...(credits ? { credits } : {}),
};
}
+
+/** Credits are account-wide; same facts and precedence as the desktop ChatGPT card. */
+function projectCodexCredits(
+ snapshots: Array<Record<string, unknown>>,
+): SessionMenuAccountUsage["credits"] | null {
+ const credits = snapshots
+ .map((snapshot) => record(snapshot.credits))
+ .find(
+ (value) =>
+ typeof value.hasCredits === "boolean" ||
+ typeof value.unlimited === "boolean",
+ );
+ if (!credits) return null;
+ const raw =
+ typeof credits.balance === "string"
+ ? credits.balance.trim().replace(/,/g, "")
+ : "";
+ const balance = raw && Number.isFinite(Number(raw)) ? Number(raw) : null;
+ // A reported balance and an exhausted state are both facts; keep both.
+ const status =
+ credits.unlimited === true
+ ? "unlimited"
+ : credits.hasCredits === false
+ ? "depleted"
+ : credits.hasCredits === true && balance === null
+ ? "available"
+ : null;
+ return balance === null && status === null ? null : { balance, status };
+}
diff --git a/apps/mobile/src/session/sessionUsagePresentation.ts b/apps/mobile/src/session/sessionUsagePresentation.ts
index 0da7c3b5b7..3cd15287b4 100644
--- a/apps/mobile/src/session/sessionUsagePresentation.ts
+++ b/apps/mobile/src/session/sessionUsagePresentation.ts
@@ -101,6 +101,33 @@ export function accountUsageRows(
: {}),
});
}
+ const credits = account.credits;
+ if (credits) {
+ const parts = [
+ credits.balance === null
+ ? null
+ : t("session.menu.usage.creditsRemaining", {
+ credits: credits.balance.toLocaleString(locale, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }),
+ }),
+ credits.status === null
+ ? null
+ : t(
+ {
+ unlimited: "session.menu.usage.creditsUnlimited",
+ depleted: "session.menu.usage.creditsDepleted",
+ available: "session.menu.usage.creditsAvailable",
+ }[credits.status],
+ ),
+ ].filter((part): part is string => part !== null);
+ rows.push({
+ label: t("session.menu.usage.credits"),
+ value: parts.join(" · "),
+ warning: credits.status === "depleted",
+ });
+ }
for (const amount of account.amounts) {
const money: RemoteMoney = {
amount: amount.amount,
diff --git a/apps/mobile/src/session/useSessionMenuUsage.ts b/apps/mobile/src/session/useSessionMenuUsage.ts
index f8ed25f397..a384373a22 100644
--- a/apps/mobile/src/session/useSessionMenuUsage.ts
+++ b/apps/mobile/src/session/useSessionMenuUsage.ts
@@ -14,7 +14,11 @@ import {
export type SessionMenuUsageReader = Pick<
MobileMakerTransport,
- "getSessionEstimatedValue" | "getCodexRateLimits" | "getAccountUsage"
+ | "getSessionEstimatedValue"
+ | "getCodexRateLimits"
+ | "getAccountUsage"
+ | "getSubscriptionUsage"
+ | "getClaudeSessionRoute"
>;
interface UsageState {
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index aba23b7bcc..c22a8b6a86 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -79,6 +79,7 @@
"./work-activity-projection": "./src/workActivityProjection.ts",
"./worktree-paths": "./src/worktreePaths.ts",
"./codex-usage-buckets": "./src/codexUsageBuckets.ts",
+ "./subscription-usage": "./src/subscriptionUsage.ts",
"./bot-learning": "./src/botLearning.ts",
"./botCollaboration": "./src/botCollaboration.ts",
"./botDirectMessage": "./src/botDirectMessage.ts",
diff --git a/packages/maker-shared/src/__tests__/subscriptionUsage.test.ts b/packages/maker-shared/src/__tests__/subscriptionUsage.test.ts
new file mode 100644
index 0000000000..ea3de6157b
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/subscriptionUsage.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+import {
+ claudeModelFamily,
+ isXaiWeeklyUsageCurrent,
+ matchScopedWindowForModel,
+} from '../subscriptionUsage.js';
+
+describe('subscription usage shared rules', () => {
+ it.each([
+ ['claude-fable-5[1m]', 'fable'],
+ ['claude-opus-5-5[1m] ', 'opus'],
+ ['Claude-Sonnet-5', 'sonnet'],
+ ['haiku[', 'haiku'],
+ ['gpt-5', null],
+ ['', null],
+ ])('maps %s to its Claude family', (model, family) => {
+ expect(claudeModelFamily(model)).toBe(family);
+ });
+
+ it('stays linear on adversarial bracket input', () => {
+ const started = Date.now();
+ expect(claudeModelFamily(`${'['.repeat(200_000)}opus`)).toBe('opus');
+ expect(Date.now() - started).toBeLessThan(500);
+ });
+
+ it('matches the model weekly window by id first, then display name', () => {
+ const scoped = [
+ { modelDisplayName: 'Claude Fable 5', utilization: 10 },
+ { modelDisplayName: 'Other', modelId: 'claude-opus-4-8', utilization: 20 },
+ ];
+ expect(matchScopedWindowForModel(scoped, 'claude-fable-5[1m]')?.utilization).toBe(10);
+ expect(matchScopedWindowForModel(scoped, 'claude-opus-5-5')?.utilization).toBe(20);
+ expect(matchScopedWindowForModel(scoped, 'claude-sonnet-5')).toBeNull();
+ });
+
+ it('treats only fresh, unreset SuperGrok snapshots as current', () => {
+ const now = 1_000_000_000;
+ const fresh = { creditUsagePercent: 10, updatedAt: now - 60_000, resetsAt: now / 1000 + 60 };
+ expect(isXaiWeeklyUsageCurrent(fresh, now)).toBe(true);
+ expect(isXaiWeeklyUsageCurrent({ ...fresh, updatedAt: now - 31 * 60_000 }, now)).toBe(false);
+ expect(isXaiWeeklyUsageCurrent({ ...fresh, resetsAt: now / 1000 - 1 }, now)).toBe(false);
+ });
+});
diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.ts
index 7d93c82a01..3a4143671b 100644
--- a/packages/maker-shared/src/deviceLinkContract.ts
+++ b/packages/maker-shared/src/deviceLinkContract.ts
@@ -320,6 +320,11 @@ export const MOBILE_REMOTE_INVOKE_CHANNELS = [
// reset 使用 desktop 预签发、账号绑定的幂等 offer,手机不能自行指定 creditId。
'maker:usage:codex-rate-limits',
'maker:usage:codex-rate-limit-reset',
+ // 订阅账号余量快照(只读;Claude / SuperGrok)与 cc 默认路由会话的生效计费路由。
+ // 老被控端 CHANNEL_NOT_ALLOWED → 任务菜单保留「暂未获取账号配额」。
+ 'maker:usage:claude-subscription',
+ 'maker:usage:xai-subscription',
+ 'maker:claude-session-route:get',
// 网关 API key presence-only 探测(只回 boolean;拉不到 → unknown,折扣版不置灰)。
'maker:api-key:present',
'maker:list-agent-commands',
diff --git a/packages/maker-shared/src/subscriptionUsage.ts b/packages/maker-shared/src/subscriptionUsage.ts
new file mode 100644
index 0000000000..eb9bdd549c
--- /dev/null
+++ b/packages/maker-shared/src/subscriptionUsage.ts
@@ -0,0 +1,189 @@
+/**
+ * subscriptionUsage — 订阅账号余量快照的跨端契约与必须同口径的纯判定。
+ *
+ * 这些快照由被控端 desktop 读取(`maker:usage:claude-subscription` /
+ * `maker:usage:xai-subscription`),desktop renderer 与 mobile 任务菜单都要按同一套规则
+ * 选窗口、判新鲜度 —— 两份实现必然漂移(见 codexUsageBuckets 的同类教训)。
+ * 来源解析(端点 / headers 归一化)仍在 desktop shared,只在被控端执行。
+ */
+
+// ── Claude 订阅 ──────────────────────────────────────────────────────────────
+
+/** 单个用量窗口(5h / 周 / 分模型周)。utilization 一律 0-100 已用百分比。 */
+export interface ClaudeUsageWindow {
+ utilization: number;
+ /** Unix epoch 秒;缺失 = 未知。 */
+ resetsAt?: number | null;
+ /** 服务端判定的告警级别(端点 limits[].severity,如 'normal';headers 源无此字段)。 */
+ severity?: string | null;
+}
+
+/** 分模型周窗口(端点 limits[] 里 kind=weekly_scoped 的条目)。 */
+export interface ClaudeScopedUsageWindow extends ClaudeUsageWindow {
+ /** scope.model.display_name,如 'Fable' / 'Opus' / 'Sonnet'。 */
+ modelDisplayName: string;
+ /** scope.model.id(端点常为 null)。 */
+ modelId?: string | null;
+}
+
+/** extra usage(usage credits)状态 —— 套餐打满后的按量付费通道。 */
+export interface ClaudeExtraUsageSnapshot {
+ isEnabled: boolean;
+ /** 0-100;仅启用且服务端给值时有。 */
+ utilization?: number | null;
+ /**
+ * 已用 credits(服务端原值)。单位未文档化,不要当货币金额展示;
+ * 仅保留原始值,等拿到 extra-usage 账号实样后再定展示口径。
+ */
+ usedCredits?: number | null;
+ /** 月度上限原值;0 = 不限。单位未文档化,不要当货币金额展示。 */
+ monthlyLimit?: number | null;
+}
+
+export interface ClaudeSubscriptionUsageSnapshot {
+ /** 5 小时滚动窗口。 */
+ fiveHour?: ClaudeUsageWindow | null;
+ /** 总周限窗口。 */
+ sevenDay?: ClaudeUsageWindow | null;
+ /** 分模型周窗口(仅 oauth-endpoint 源有)。 */
+ scoped?: ClaudeScopedUsageWindow[];
+ /** 订阅套餐(凭证 blob 的 subscriptionType: pro / max 等,记录时由 main 一并写入)。 */
+ subscriptionType?: string | null;
+ /** headers 源的整体状态:allowed / allowed_warning / rejected。 */
+ rateLimitStatus?: string | null;
+ /** headers 源:当前代表性(最紧)窗口名,如 'five_hour' / 'seven_day'。 */
+ representativeClaim?: string | null;
+ extraUsage?: ClaudeExtraUsageSnapshot | null;
+ source?: 'oauth-endpoint' | 'unified-headers' | string | null;
+ /** 快照生成时间(ms epoch)。 */
+ updatedAt?: number | null;
+ /**
+ * 归属账号的 OAuth token 指纹(sha256 截断, main 记录时附加, 不含 token 原文)。
+ * 同机换号时 reader 据此判定持久化快照已过期, 避免 chip 闪上一个账号的余量。
+ * 缺失(旧快照 / 仅 headers 源)时按未知归属处理, 不据此清除。
+ */
+ accountFingerprint?: string | null;
+}
+
+// ── 方案 B:当前模型 → scoped 窗口匹配 ───────────────────────────────────────
+
+/**
+ * 去掉末尾的 `[...]` 后缀(如 `[1m]`),等价于 `/\[[^\]]*\]\s*$/`。不用正则:
+ * model id 来自远端数据,该正则在大量 `[` 的输入上是多项式回溯(CodeQL)。
+ */
+function stripTrailingBracketSuffix(value: string): string {
+ const close = value.trimEnd().length - 1;
+ if (close < 0 || value[close] !== ']') return value;
+ const open = value.indexOf('[', value.lastIndexOf(']', close - 1) + 1);
+ return open >= 0 && open < close ? value.slice(0, open) : value;
+}
+
+/**
+ * 从 model id 提取模型家族名(与端点 scope.model.display_name 对齐的小写词)。
+ * 'claude-fable-5[1m]' → 'fable';'claude-opus-4-8' → 'opus';'sonnet' → 'sonnet'
+ * 未识别 → null(调用方回退总周限)。
+ */
+export function claudeModelFamily(modelId: string | null | undefined): string | null {
+ const normalized = stripTrailingBracketSuffix((modelId ?? '').trim().toLowerCase());
+ if (!normalized) return null;
+ // 顺序无关 —— 家族名互斥地出现在 Anthropic model id 里。
+ for (const family of ['fable', 'mythos', 'opus', 'sonnet', 'haiku']) {
+ if (normalized.includes(family)) return family;
+ }
+ return null;
+}
+
+/**
+ * 判断一个分模型周窗口是否属于指定家族。
+ *
+ * 优先用窗口自带的 `modelId` 经 `claudeModelFamily` 归类(权威、精确);`modelId`
+ * 缺失或无法归类(端点常为 null,或 id 形态不在识别表里)时,回退用 `modelDisplayName`
+ * 的变体包含匹配——端点对 display_name 的口径历史上有 "Fable" / "Claude Fable" /
+ * "Fable 5" 等形态,精确等于会漏掉变体(issue #3244)。家族名互斥,不会跨家族误命中。
+ *
+ * matcher(`matchScopedWindowForModel`)与 legacy 兜底去重共用这一份口径,避免两份
+ * includes 规则漂移。
+ */
+export function scopedWindowBelongsToFamily(
+ window: ClaudeScopedUsageWindow,
+ family: string,
+): boolean {
+ const fromId = claudeModelFamily(window.modelId);
+ if (fromId) return fromId === family;
+ return window.modelDisplayName.trim().toLowerCase().includes(family);
+}
+
+/**
+ * 找当前会话模型对应的分模型周窗口(chip 方案 B:第二栏跟随当前模型)。
+ * 找不到 → null,调用方回退 sevenDay 总周限(绝不臆造)。家族归属口径见
+ * scopedWindowBelongsToFamily。
+ */
+export function matchScopedWindowForModel(
+ scoped: ClaudeScopedUsageWindow[] | null | undefined,
+ modelId: string | null | undefined,
+): ClaudeScopedUsageWindow | null {
+ if (!scoped || scoped.length === 0) return null;
+ const family = claudeModelFamily(modelId);
+ if (!family) return null;
+ return scoped.find((w) => scopedWindowBelongsToFamily(w, family)) ?? null;
+}
+
+// ── xAI(SuperGrok)订阅 ───────────────────────────────────────────────────────
+
+/** 分产品周用量(页面「Grok Build 2%」)。 */
+export interface XaiProductUsage {
+ /** 上游 product id,如 GrokBuild。 */
+ product: string;
+ /** 0-100 已用百分比。 */
+ usagePercent: number;
+}
+
+export interface XaiSubscriptionUsageSnapshot {
+ /** 套餐展示名,如 SuperGrok Heavy。 */
+ planLabel?: string | null;
+ /** 0-100 本周已用百分比(页面「2% 已使用」)。 */
+ creditUsagePercent?: number | null;
+ /** Unix epoch 秒;周窗口重置时刻。 */
+ resetsAt?: number | null;
+ /** 分产品已用百分比。 */
+ productUsage?: XaiProductUsage[];
+ /**
+ * 额外使用点数余额。单位按 grok.com 页面为美元;0 / 缺失不要当「免费额度」展示。
+ */
+ prepaidBalance?: number | null;
+ source?: 'cli-billing' | string | null;
+ updatedAt?: number | null;
+ /**
+ * 稳定账号指纹(OIDC sub 的不可逆哈希)。换 SuperGrok 号时用来丢掉旧快照。
+ * 不是 access token 哈希 —— token 刷新会轮换。
+ */
+ accountFingerprint?: string | null;
+}
+
+/** 超过这个时间没刷新到新快照,就不再当「当前额度」展示。 */
+export const XAI_USAGE_STALE_MS = 30 * 60 * 1000;
+
+/**
+ * 周窗口数字是否还能当当前额度:过了 TTL,或已经过了 resetsAt 却还没新快照,
+ * 都不当当前值(避免无限显示旧百分比 / 卡在「重置中」)。套餐名仍可单独展示。
+ */
+export function isXaiWeeklyUsageCurrent(
+ snapshot: XaiSubscriptionUsageSnapshot | null | undefined,
+ nowMs: number,
+): boolean {
+ if (!snapshot) return false;
+ if (
+ typeof snapshot.creditUsagePercent !== 'number'
+ || !Number.isFinite(snapshot.creditUsagePercent)
+ ) {
+ return false;
+ }
+ if (typeof snapshot.updatedAt !== 'number' || !Number.isFinite(snapshot.updatedAt) || snapshot.updatedAt <= 0) {
+ return false;
+ }
+ if (nowMs - snapshot.updatedAt > XAI_USAGE_STALE_MS) return false;
+ if (typeof snapshot.resetsAt === 'number' && Number.isFinite(snapshot.resetsAt) && snapshot.resetsAt > 0) {
+ if (nowMs >= snapshot.resetsAt * 1000) return false;
+ }
+ return true;
+}
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index 6e3f735746..f5bec0fa7c 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -44,6 +44,7 @@ export type {
ProviderRuntimeModelConfig,
PiReasoningEffort,
PiModelApi,
+ NativeSubscriptionAuth,
ProviderPreset,
ProviderPresetRuntime,
PresetSortRegion,
@@ -52,7 +53,7 @@ export type {
OAuthProviderDescriptor,
} from "./types.js";
-export { PI_MODEL_APIS, PI_REASONING_EFFORTS } from "./types.js";
+export { NATIVE_SUBSCRIPTION_AUTHS, NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS, PI_MODEL_APIS, PI_REASONING_EFFORTS } from "./types.js";
export { isLocalOnlyProviderForAgent, isOpenAiSubscriptionProvider, providerCatalogId, isCustomRoutedProvider, isOrganizationManagedProvider } from './provider-identity.js';
export { sourceProviderForPreset } from './providerPresetIdentity.js';
export { isMimoTokenPlanPreset } from './mimoPresentation.js';
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index d841b53a2e..e496743915 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -55,6 +55,20 @@ export const PI_MODEL_APIS = [
] as const;
export type PiModelApi = (typeof PI_MODEL_APIS)[number];
+/**
+ * Cindy 自带鉴权的订阅账号家族(ChatGPT / Claude / SuperGrok)。新增订阅家族只在这里加一项:
+ * 各端按家族读取账号余量的入口都以 `Record<NativeSubscriptionAuth, …>` 声明,漏接会直接
+ * 编译失败(mobile 任务菜单见 readSessionMenuAccountUsage)。
+ */
+export const NATIVE_SUBSCRIPTION_AUTHS = ["codex", "claude", "xai"] as const;
+export type NativeSubscriptionAuth = (typeof NATIVE_SUBSCRIPTION_AUTHS)[number];
+/** 每个订阅家族的内置默认账号 providerId(独立账号另有自己的 id,以 auth.native 标识家族)。 */
+export const NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS = {
+ codex: "openai",
+ claude: "anthropic",
+ xai: "xai",
+} as const satisfies Record<NativeSubscriptionAuth, string>;
+
/** Provider runtime 上游实际接受的推理 wire protocol。 */
export type ProviderWireProtocol =
"anthropic-messages" | "openai-responses" | "openai-chat" | "google-generative-ai";
@@ -512,7 +526,7 @@ export interface Provider {
* OAuth Runner(generic-oauth);不带描述符的 oauth 供应商 = host bespoke 鉴权
* (anthropic / openai / xai 现状)。
*/
- auth: { method: AuthMethod; oauth?: OAuthProviderDescriptor; native?: "codex" | "claude" | "xai" };
+ auth: { method: AuthMethod; oauth?: OAuthProviderDescriptor; native?: NativeSubscriptionAuth };
/** 用户使用该供应商时的额度来源;旧目录可缺省,由 source 从 bundled 同 id 条目补齐。 */
access?: ProviderAccess;
/**
@@ -794,7 +808,7 @@ export interface CustomProviderConfig {
auth?:
| { method: "apiKey"; oauth?: never; native?: never }
| { method: "oauth"; oauth: OAuthProviderDescriptor; native?: never }
- | { method: "oauth"; native: "codex" | "claude" | "xai"; oauth?: never }
+ | { method: "oauth"; native: NativeSubscriptionAuth; oauth?: never }
| { method: "none"; oauth?: never; native?: never };
/** per-runtime 独立配置(键为 agent,只含已配置的 runtime;至少一个)。 */
runtimes: Partial<Record<AgentKind, CustomProviderRuntimeConfig>>;