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(claude): 经内置 CLI 的 get_usage 恢复订阅套餐余量

Dash1d131dde4a92
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeNativeCli.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeNativeCli.test.ts
index 8ca290f2f2..a60cecfcaa 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeNativeCli.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeNativeCli.test.ts
@@ -37,7 +37,9 @@ vi.mock('node:child_process', () => ({ spawn: h.spawn }));
import {
claudeCliNetworkEnv,
parseClaudeCliLoginStatus,
+ parseClaudeCliPlanUsageLine,
peekClaudeCliLoginStatus,
+ readClaudeCliPlanUsage,
readClaudeCliLoginStatus,
refreshClaudeCliLoginStatus,
resetClaudeNativeCliForTest,
@@ -263,3 +265,85 @@ describe('runClaudeCliLogin', () => {
expect(h.spawn).not.toHaveBeenCalled();
});
});
+
+type FakeSdkChild = FakeChild & { stdin: EventEmitter & { write: ReturnType<typeof vi.fn> } };
+
+/** SDK 模式的假 CLI:收到 get_usage 请求后按 reply 回一行(reply 为 null 时不回)。 */
+function fakeSdkChild(reply: (requestId: string) => unknown): FakeSdkChild {
+ const child = fakeChild('hang') as FakeSdkChild;
+ const stdin = new EventEmitter() as FakeSdkChild['stdin'];
+ stdin.write = vi.fn((line: string) => {
+ const message = JSON.parse(line) as { request_id: string; request: { subtype: string } };
+ if (message.request.subtype !== 'get_usage') return true;
+ const response = reply(message.request_id);
+ if (response !== null) {
+ setImmediate(() => {
+ child.stdout.emit('data', Buffer.from(`{"type":"system","subtype":"init"}\n${JSON.stringify(response)}\n`));
+ });
+ }
+ return true;
+ });
+ child.stdin = stdin;
+ return child;
+}
+
+const RATE_LIMITS = { limits: [{ kind: 'session', percent: 5, resets_at: '2026-09-26T04:00:00Z' }] };
+
+describe('readClaudeCliPlanUsage', () => {
+ it('发 get_usage 控制请求,取 rate_limits 后结束 CLI;拉起时隔离项目设置 / MCP / 会话记录', async () => {
+ const child = fakeSdkChild((id) => ({
+ type: 'control_response',
+ response: {
+ subtype: 'success',
+ request_id: id,
+ response: { subscription_type: 'max', rate_limits_available: true, rate_limits: RATE_LIMITS },
+ },
+ }));
+ h.spawn.mockReturnValue(child);
+ await expect(readClaudeCliPlanUsage()).resolves.toEqual({ rateLimits: RATE_LIMITS, subscriptionType: 'max' });
+ const args = argsOf(h.spawn.mock.calls[0]!);
+ expect(args).toEqual(expect.arrayContaining([
+ '--input-format', 'stream-json', '--no-session-persistence', '--strict-mcp-config', '--setting-sources', 'user',
+ ]));
+ const request = JSON.parse(child.stdin.write.mock.calls[1]![0] as string);
+ expect(request.request).toEqual({ subtype: 'get_usage', skip_behaviors: true });
+ expect(child.kill).toHaveBeenCalled();
+ });
+
+ it('账号没有套餐余量 → null;控制请求报错 / CLI 提前退出 → 抛错', async () => {
+ h.spawn.mockReturnValueOnce(fakeSdkChild((id) => ({
+ type: 'control_response',
+ response: { subtype: 'success', request_id: id, response: { rate_limits_available: false, rate_limits: null } },
+ })));
+ await expect(readClaudeCliPlanUsage()).resolves.toBeNull();
+
+ h.spawn.mockReturnValueOnce(fakeSdkChild((id) => ({
+ type: 'control_response',
+ response: { subtype: 'error', request_id: id, error: 'get_usage is not supported in this context' },
+ })));
+ await expect(readClaudeCliPlanUsage()).rejects.toThrow('not supported');
+
+ const exiting = fakeSdkChild(() => null);
+ h.spawn.mockReturnValueOnce(exiting);
+ const pending = readClaudeCliPlanUsage();
+ setImmediate(() => exiting.emit('close', 1));
+ await expect(pending).rejects.toThrow('exited');
+ });
+
+ it('内置 CLI 不可用时不拉起进程', async () => {
+ h.binary = null;
+ await expect(readClaudeCliPlanUsage()).rejects.toThrow('unavailable');
+ expect(h.spawn).not.toHaveBeenCalled();
+ });
+});
+
+describe('parseClaudeCliPlanUsageLine', () => {
+ it('忽略非本请求的行与无法解析的行', () => {
+ expect(parseClaudeCliPlanUsageLine('not json')).toBeNull();
+ expect(parseClaudeCliPlanUsageLine('{"type":"system"}')).toBeNull();
+ expect(parseClaudeCliPlanUsageLine(JSON.stringify({
+ type: 'control_response',
+ response: { subtype: 'success', request_id: 'cindy-init', response: {} },
+ }))).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/claude-native-cli.ts b/apps/desktop/src/main/maker-host/claude-native-cli.ts
index 92368b6690..7b0ad9ac7e 100644
--- a/apps/desktop/src/main/maker-host/claude-native-cli.ts
+++ b/apps/desktop/src/main/maker-host/claude-native-cli.ts
@@ -261,6 +261,117 @@ export async function readClaudeCliLoginStatus(options?: {
return refreshClaudeCliLoginStatus();
}
+// ── 套餐余量 ──────────────────────────────────────────────────────────────────
+
+const PLAN_USAGE_TIMEOUT_MS = 20_000;
+const PLAN_USAGE_REQUEST_ID = 'cindy-plan-usage';
+
+export interface ClaudeCliPlanUsage {
+ /** `get_usage` 响应的 `rate_limits`(与 claude.ai /usage 同形,由 shared 解析器 fail-safe 解析)。 */
+ rateLimits: unknown;
+ subscriptionType?: string;
+}
+
+/**
+ * 读 Claude 订阅套餐余量:拉起内置 CLI 的 SDK 模式,发 `get_usage` 控制请求(CLI 的
+ * /usage 同源,结构化返回),拿到响应即结束进程。请求由 CLI 用自己的登录发出,Cindy
+ * 不接触凭证;不发用户消息,不产生模型调用。
+ *
+ * `get_usage` 是 CLI 标注为 Experimental 的控制请求,响应形状可能变化 —— 这里只取
+ * `rate_limits` 原样交给调用方解析。CLI 声明当前账号没有套餐余量(非订阅 / 教育版等)
+ * 时返回 null;启动失败、超时、控制请求报错时抛错,由调用方退避。
+ */
+export async function readClaudeCliPlanUsage(): Promise<ClaudeCliPlanUsage | null> {
+ const binary = cliBinaryPath();
+ if (!binary) throw new Error('claude cli unavailable');
+ const env = await cliEnv({ network: true });
+ // --setting-sources user:不读工作区的项目级设置(它们可改写上游 / 鉴权);
+ // --strict-mcp-config:不拉起用户配置的 MCP server;--no-session-persistence:不落会话记录。
+ const args = [
+ '-p',
+ '--input-format', 'stream-json',
+ '--output-format', 'stream-json',
+ '--verbose',
+ '--no-session-persistence',
+ '--strict-mcp-config',
+ '--setting-sources', 'user',
+ ];
+ return new Promise((resolve, reject) => {
+ let child: ChildProcess;
+ try {
+ child = spawn(binary, args, { env, stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
+ } catch (err) {
+ reject(err);
+ return;
+ }
+ let settled = false;
+ let buffer = '';
+ const finish = (err: Error | null, value?: ClaudeCliPlanUsage | null) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ child.kill();
+ if (err) reject(err);
+ else resolve(value ?? null);
+ };
+ const timer = setTimeout(() => finish(new Error('claude get_usage timed out')), PLAN_USAGE_TIMEOUT_MS);
+ child.once('error', (err) => finish(err));
+ child.once('close', (code) => finish(new Error(`claude cli exited before get_usage response (code ${code})`)));
+ child.stdin?.on('error', () => {
+ /* 进程提前退出时写 stdin 会 EPIPE,由 close 分支给结论。 */
+ });
+ child.stdout?.on('data', (chunk: Buffer) => {
+ buffer += chunk.toString('utf8');
+ let newline: number;
+ while ((newline = buffer.indexOf('\n')) >= 0) {
+ const line = buffer.slice(0, newline).trim();
+ buffer = buffer.slice(newline + 1);
+ if (!line) continue;
+ const outcome = parseClaudeCliPlanUsageLine(line);
+ if (outcome) finish(outcome.error ? new Error(outcome.error) : null, outcome.usage);
+ }
+ });
+ const write = (message: unknown) => child.stdin?.write(`${JSON.stringify(message)}\n`);
+ write({ type: 'control_request', request_id: 'cindy-init', request: { subtype: 'initialize' } });
+ write({
+ type: 'control_request',
+ request_id: PLAN_USAGE_REQUEST_ID,
+ request: { subtype: 'get_usage', skip_behaviors: true },
+ });
+ });
+}
+
+/**
+ * 解析 CLI stream-json 输出的一行。不是 `get_usage` 的 control_response 时返回 null
+ * (继续读);是则返回结论:error 为控制请求失败,usage 为 null 表示账号没有套餐余量。
+ */
+export function parseClaudeCliPlanUsageLine(
+ line: string,
+): { error?: string; usage: ClaudeCliPlanUsage | null } | null {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line);
+ } catch {
+ return null;
+ }
+ if (!parsed || typeof parsed !== 'object') return null;
+ const message = parsed as { type?: unknown; response?: unknown };
+ if (message.type !== 'control_response' || !message.response || typeof message.response !== 'object') return null;
+ const response = message.response as Record<string, unknown>;
+ if (response.request_id !== PLAN_USAGE_REQUEST_ID) return null;
+ if (response.subtype !== 'success') {
+ return { error: `claude get_usage failed: ${optionalString(response.error) ?? 'unknown error'}`, usage: null };
+ }
+ const body = response.response && typeof response.response === 'object'
+ ? (response.response as Record<string, unknown>)
+ : {};
+ if (body.rate_limits_available === false || !body.rate_limits || typeof body.rate_limits !== 'object') {
+ return { usage: null };
+ }
+ const subscriptionType = optionalString(body.subscription_type);
+ return { usage: { rateLimits: body.rate_limits, ...(subscriptionType ? { subscriptionType } : {}) } };
+}
+
// ── 登录 ──────────────────────────────────────────────────────────────────────
let currentLogin: { key: string | undefined; abort: AbortController } | null = null;
diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.ts
index aafa882d21..f6c8c6775b 100644
--- a/apps/desktop/src/main/maker-ipc/usage.ts
+++ b/apps/desktop/src/main/maker-ipc/usage.ts
@@ -19,9 +19,10 @@ import {
triggerClaudeAccountUsageRefresh,
} from '../usage/claudeAccountUsage.js';
import {
+ parseClaudeOAuthUsageResponse,
parseClaudeSdkRateLimitInfo,
- type ClaudeSubscriptionUsageSnapshot,
} from '../../shared/claudeSubscriptionUsage.js';
+import { createClaudeSubscriptionUsageReader } from '../usage/claudeSubscriptionUsageRefresh.js';
import {
XaiSubscriptionUsageRateLimitedError,
XaiSubscriptionUsageUnauthorizedError,
@@ -70,6 +71,7 @@ import { isOpenAiSubscriptionProviderId } from '../maker-host/codex-account-auth
import { desktopCodexAuthAdapter } from '../maker-host/auth-adapters.js';
import { hasClaudeNativeLogin } from '../maker-host/claude-native-auth.js';
import { peekClaudeCliLoginStatus } from '../maker-host/claude-native-cli-status.js';
+import { readClaudeCliPlanUsage } from '../maker-host/claude-native-cli.js';
import { getGrokAccessToken, hasGrokOAuthLogin } from '../maker-host/grok-oauth-login.js';
import { outboundFetch } from '../maker-host/outbound-fetch.js';
import { createCodexRateLimitResetService } from '../usage/codexRateLimitReset.js';
@@ -90,40 +92,29 @@ function currentClaudeAccountFingerprint(): string | null {
/**
* 内置 Claude 订阅的余量 reader。订阅会话由内置 CLI 用自己的登录直连 Anthropic,Cindy
- * 不持有订阅 token,也不去查用量端点;快照只来自 CLI 在会话里上报的 SDK
- * `rate_limit_event`(见 registerMakerUsageIpc 的 setClaudeRateLimitInfoListener),
- * 按 headers 源同口径增量合并、持久化。这里只负责读缓存与凭证变化后的清理。
+ * 不持有订阅 token。完整余量(5h / 周 / 分模型周限 / extra usage)由 CLI 的 `get_usage`
+ * 控制请求查询(CLI 自己发请求,节流 / 退避在 reader 内部);会话里 CLI 上报的 SDK
+ * `rate_limit_event`(见 registerMakerUsageIpc 的 setClaudeRateLimitInfoListener)按
+ * headers 源口径增量合并,补 turn 内的实时性。
*/
-interface ClaudeSubscriptionUsageReader {
- /** IPC / device-link 读:缓存快照(未连接时 null)。 */
- read(): Promise<ClaudeSubscriptionUsageSnapshot | null>;
- /** turn-done 钩子:没有可主动拉取的端点,保留接口形状。 */
- triggerRefresh(): void;
- /** 登录态变化后的强制同步:未连接时无条件清快照并广播。 */
- syncForCredentialChange(): Promise<void>;
-}
-
-const claudeSubscriptionUsageReader: ClaudeSubscriptionUsageReader = {
- async read(): Promise<ClaudeSubscriptionUsageSnapshot | null> {
- if (!hasClaudeNativeLogin()) return null;
- const snapshot = await readClaudeSubscriptionUsageSnapshot();
- const fingerprint = currentClaudeAccountFingerprint();
- if (snapshot?.accountFingerprint && fingerprint && snapshot.accountFingerprint !== fingerprint) {
- await clearClaudeSubscriptionUsageSnapshot();
- return null;
- }
- return snapshot;
+const claudeSubscriptionUsageReader = createClaudeSubscriptionUsageReader({
+ readAccount: () => (hasClaudeNativeLogin() ? currentClaudeAccountFingerprint() ?? '' : null),
+ fetchSnapshot: async () => {
+ const usage = await readClaudeCliPlanUsage();
+ if (!usage) return 'empty';
+ const snapshot = parseClaudeOAuthUsageResponse(usage.rateLimits, Date.now());
+ if (!snapshot) return 'empty';
+ const subscriptionType = usage.subscriptionType ?? peekClaudeCliLoginStatus()?.subscriptionType;
+ return subscriptionType ? { ...snapshot, subscriptionType } : snapshot;
},
- // 没有可主动拉取的余量端点:余量随会话里的 rate_limit_event 更新。
- triggerRefresh(): void {},
- async syncForCredentialChange(): Promise<void> {
- if (!hasClaudeNativeLogin()) {
- await clearClaudeSubscriptionUsageSnapshot();
- return;
- }
- await claudeSubscriptionUsageReader.read();
+ recordSnapshot: recordClaudeSubscriptionUsageSnapshot,
+ clearSnapshot: clearClaudeSubscriptionUsageSnapshot,
+ readCachedSnapshot: readClaudeSubscriptionUsageSnapshot,
+ now: () => Date.now(),
+ onRefreshError: (err) => {
+ log.warn('claude subscription usage refresh failed:', err instanceof Error ? err.message : String(err));
},
-};
+});
/**
* Claude turn done 后的订阅余量刷新钩子 (register.ts 消费) —— fire-and-forget,
@@ -138,7 +129,7 @@ export function triggerClaudeSubscriptionUsageRefresh(providerId?: string): void
* Claude 订阅登录态变化(CLI 登录 / 登出 / 换号 / Cindy 断开)后的余量同步钩子(bootstrap
* 的 CLAUDE_OAUTH_LOGIN / LOGOUT handler 与 CLI 登录态监听消费):
* - 未连接 → 清快照并广播 null(chip 立即回占位态);
- * - 换号 → 指纹校验清掉旧账号快照,新余量等下一次会话上报。
+ * - 登录 / 换号 → 指纹校验清掉旧账号快照,并经 CLI `get_usage` 拉取新账号余量。
* renderer 不需要感知 auth 事件, 全靠既有 usage:claude-subscription-changed push。
*/
export function syncClaudeSubscriptionUsageForAuthChange(providerId?: string): void {
diff --git a/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.ts b/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.ts
new file mode 100644
index 0000000000..e1e71371ec
--- /dev/null
+++ b/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.ts
@@ -0,0 +1,139 @@
+/**
+ * claudeSubscriptionUsageRefresh —— CLI get_usage 余量 reader 的节流、失败退避与换号清理。
+ */
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ClaudeSubscriptionUsageSnapshot } from '../../../shared/claudeSubscriptionUsage.js';
+import { createClaudeSubscriptionUsageReader } from '../claudeSubscriptionUsageRefresh.js';
+
+const SNAPSHOT: ClaudeSubscriptionUsageSnapshot = {
+ fiveHour: { utilization: 5, resetsAt: 1 },
+ sevenDay: { utilization: 2, resetsAt: 2 },
+ scoped: [],
+ source: 'oauth-endpoint',
+ updatedAt: 0,
+};
+
+function setup(options: { account?: string | null; cached?: ClaudeSubscriptionUsageSnapshot | null } = {}) {
+ const state = {
+ account: options.account === undefined ? 'acct-a' : options.account,
+ cached: options.cached ?? null,
+ now: 1_000_000,
+ };
+ const deps = {
+ readAccount: vi.fn(() => state.account),
+ fetchSnapshot: vi.fn(async (): Promise<ClaudeSubscriptionUsageSnapshot | 'empty'> => SNAPSHOT),
+ recordSnapshot: vi.fn(async (snapshot: ClaudeSubscriptionUsageSnapshot) => {
+ state.cached = snapshot;
+ }),
+ clearSnapshot: vi.fn(async () => {
+ state.cached = null;
+ }),
+ readCachedSnapshot: vi.fn(async () => state.cached),
+ now: () => state.now,
+ onRefreshError: vi.fn(),
+ };
+ const reader = createClaudeSubscriptionUsageReader(deps, {
+ throttleMs: 1_000,
+ failureBackoffInitialMs: 10_000,
+ failureBackoffMaxMs: 40_000,
+ });
+ return { state, deps, reader };
+}
+
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+describe('createClaudeSubscriptionUsageReader', () => {
+ it('cached-first:读立即返回缓存,后台拉取并附上账号指纹', async () => {
+ const { deps, reader, state } = setup({ cached: { ...SNAPSHOT, source: 'unified-headers' } });
+ await expect(reader.read()).resolves.toMatchObject({ source: 'unified-headers' });
+ await flush();
+ expect(deps.fetchSnapshot).toHaveBeenCalledTimes(1);
+ expect(state.cached).toMatchObject({ source: 'oauth-endpoint', accountFingerprint: 'acct-a' });
+ });
+
+ it('节流窗口内不重复拉起 CLI,过了窗口再拉', async () => {
+ const { deps, reader, state } = setup();
+ await reader.read();
+ await flush();
+ reader.triggerRefresh();
+ await reader.read();
+ await flush();
+ expect(deps.fetchSnapshot).toHaveBeenCalledTimes(1);
+ state.now += 1_001;
+ reader.triggerRefresh();
+ await flush();
+ expect(deps.fetchSnapshot).toHaveBeenCalledTimes(2);
+ });
+
+ it('失败指数退避,成功后复位', async () => {
+ const { deps, reader, state } = setup();
+ deps.fetchSnapshot.mockRejectedValue(new Error('claude get_usage timed out'));
+ reader.triggerRefresh();
+ await flush();
+ expect(deps.onRefreshError).toHaveBeenCalledTimes(1);
+
+ state.now += 5_000; // 过了节流,仍在 10s 退避内
+ reader.triggerRefresh();
+ await flush();
+ expect(deps.fetchSnapshot).toHaveBeenCalledTimes(1);
+
+ state.now += 6_000;
+ reader.triggerRefresh();
+ await flush();
+ expect(deps.fetchSnapshot).toHaveBeenCalledTimes(2);
+
+ state.now += 15_000; // 第二次失败退避翻倍到 20s
+ reader.triggerRefresh();
+ await flush();
+ expect(deps.fetchSnapshot).toHaveBeenCalledTimes(2);
+
+ deps.fetchSnapshot.mockResolvedValue(SNAPSHOT);
+ state.now += 6_000;
+ reader.triggerRefresh();
+ await flush();
+ expect(deps.fetchSnapshot).toHaveBeenCalledTimes(3);
+ expect(state.cached).toMatchObject({ accountFingerprint: 'acct-a' });
+ });
+
+ it("CLI 报账号没有套餐余量('empty')→ 清缓存", async () => {
+ const { deps, reader, state } = setup({ cached: SNAPSHOT });
+ deps.fetchSnapshot.mockResolvedValue('empty');
+ reader.triggerRefresh();
+ await flush();
+ expect(state.cached).toBeNull();
+ });
+
+ it('未连接:读返回 null 且不拉起 CLI;syncForCredentialChange 无条件清快照', async () => {
+ const { deps, reader } = setup({ account: null, cached: SNAPSHOT });
+ await expect(reader.read()).resolves.toBeNull();
+ reader.triggerRefresh();
+ await flush();
+ expect(deps.fetchSnapshot).not.toHaveBeenCalled();
+ await reader.syncForCredentialChange();
+ expect(deps.clearSnapshot).toHaveBeenCalledTimes(1);
+ });
+
+ it('换号:缓存属于别的账号时立即清除并为新账号拉取', async () => {
+ const { deps, reader, state } = setup({ account: 'acct-b', cached: { ...SNAPSHOT, accountFingerprint: 'acct-a' } });
+ await expect(reader.read()).resolves.toBeNull();
+ await flush();
+ expect(deps.clearSnapshot).toHaveBeenCalled();
+ expect(state.cached).toMatchObject({ accountFingerprint: 'acct-b' });
+ });
+
+ it('拉取期间换号:旧账号的结果被丢弃,收尾后为新账号补拉', async () => {
+ const { deps, reader, state } = setup();
+ let release: (value: ClaudeSubscriptionUsageSnapshot) => void = () => {};
+ deps.fetchSnapshot.mockImplementationOnce(() => new Promise((resolve) => { release = resolve; }));
+ reader.triggerRefresh();
+ state.account = 'acct-b';
+ const synced = reader.syncForCredentialChange();
+ release(SNAPSHOT);
+ await synced;
+ await flush();
+ await flush();
+ expect(deps.fetchSnapshot).toHaveBeenCalledTimes(2);
+ expect(state.cached).toMatchObject({ accountFingerprint: 'acct-b' });
+ });
+});
diff --git a/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.ts b/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.ts
new file mode 100644
index 0000000000..d2e20ecf5c
--- /dev/null
+++ b/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.ts
@@ -0,0 +1,180 @@
+/**
+ * claudeSubscriptionUsageRefresh — Claude 订阅余量的 cached-first reader(纯逻辑,依赖注入)。
+ *
+ * 数据由内置 CLI 的 `get_usage` 控制请求提供(CLI 用自己的登录查询,Cindy 不接触凭证),
+ * 每次都要拉起一个 CLI 进程,所以:
+ * - IPC 读立即返回缓存快照,后台按节流刷新(recordSnapshot 内部广播给 renderer);
+ * - 节流默认 180s,turn 内的实时性由会话里的 SDK rate_limit_event 增量兜住;
+ * - 失败(CLI 未就绪 / 超时 / 请求报错)指数退避,5min 起 ×2 封顶 30min。
+ *
+ * 身份维度是 CLI 登录账号的指纹(邮箱派生,不含邮箱原文);指纹变化即换号,节流 / 退避
+ * 重新计,持久化快照按指纹校验归属。
+ */
+
+import type { ClaudeSubscriptionUsageSnapshot } from '../../shared/claudeSubscriptionUsage.js';
+
+interface ClaudeSubscriptionUsageRefreshDeps {
+ /** 当前已连接的 Claude 订阅账号指纹;未连接 → null。账号已连接但指纹未知时返回空串。 */
+ readAccount(): string | null;
+ /**
+ * 拉一次快照。snapshot = 正常;'empty' = CLI 声明账号没有套餐余量,或返回里解析不出
+ * 任何窗口(应清缓存降级为无数据)。失败时抛错。
+ */
+ fetchSnapshot(): Promise<ClaudeSubscriptionUsageSnapshot | 'empty'>;
+ recordSnapshot(snapshot: ClaudeSubscriptionUsageSnapshot): Promise<void>;
+ clearSnapshot(): Promise<void>;
+ readCachedSnapshot(): Promise<ClaudeSubscriptionUsageSnapshot | null>;
+ now(): number;
+ onRefreshError(err: unknown): void;
+}
+
+interface ClaudeSubscriptionUsageRefreshOptions {
+ throttleMs?: number;
+ failureBackoffInitialMs?: number;
+ failureBackoffMaxMs?: number;
+}
+
+const DEFAULT_THROTTLE_MS = 180_000;
+const DEFAULT_BACKOFF_INITIAL_MS = 5 * 60_000;
+const DEFAULT_BACKOFF_MAX_MS = 30 * 60_000;
+
+export interface ClaudeSubscriptionUsageReader {
+ /** cached-first 读(IPC handler 用):立即返回缓存快照,后台按节流刷新。 */
+ read(): Promise<ClaudeSubscriptionUsageSnapshot | null>;
+ /** 显式触发一次后台刷新(turn-done 钩子用),同样吃节流 / 退避。 */
+ triggerRefresh(): void;
+ /**
+ * 登录态变化(CLI 登录 / 登出 / 换号 / Cindy 断开)后的强制同步。未连接时**无条件**清
+ * 持久化快照并广播(本进程可能从未观察过登录,磁盘上仍可能残留上一周期的快照)。
+ */
+ syncForCredentialChange(): Promise<void>;
+}
+
+export function createClaudeSubscriptionUsageReader(
+ deps: ClaudeSubscriptionUsageRefreshDeps,
+ options: ClaudeSubscriptionUsageRefreshOptions = {},
+): ClaudeSubscriptionUsageReader {
+ const throttleMs = options.throttleMs ?? DEFAULT_THROTTLE_MS;
+ const backoffInitialMs = options.failureBackoffInitialMs ?? DEFAULT_BACKOFF_INITIAL_MS;
+ const backoffMaxMs = options.failureBackoffMaxMs ?? DEFAULT_BACKOFF_MAX_MS;
+
+ let inFlight: Promise<void> | null = null;
+ let inFlightAccount: string | null = null;
+ // 节流 / 退避状态按账号记 —— 换号立即重新计。
+ let stateAccount: string | null = null;
+ let lastRefreshAt = 0;
+ let backoffMs = 0;
+ let backoffUntil = 0;
+
+ function resetStateForAccount(account: string): void {
+ if (stateAccount === account) return;
+ stateAccount = account;
+ lastRefreshAt = 0;
+ backoffMs = 0;
+ backoffUntil = 0;
+ }
+
+ function readAccountSafe(): string | null {
+ try {
+ return deps.readAccount();
+ } catch (err) {
+ deps.onRefreshError(err);
+ return null;
+ }
+ }
+
+ async function clearSnapshotSafe(): Promise<void> {
+ try {
+ await deps.clearSnapshot();
+ } catch (err) {
+ deps.onRefreshError(err);
+ }
+ }
+
+ /** 缓存快照属于别的账号(同机在 CLI 里换号)。指纹缺失按未知归属沿用,不误清。 */
+ function belongsToOtherAccount(snapshot: ClaudeSubscriptionUsageSnapshot | null, account: string): boolean {
+ return Boolean(snapshot?.accountFingerprint && account && snapshot.accountFingerprint !== account);
+ }
+
+ function refreshFor(account: string): Promise<void> {
+ if (inFlight) {
+ // 飞行中的请求属于另一个账号:旧结果会被丢弃,收尾后按当时的账号补一次。
+ if (inFlightAccount !== account) {
+ return inFlight.finally(() => {
+ const current = readAccountSafe();
+ if (current !== null) void refreshFor(current);
+ });
+ }
+ return inFlight;
+ }
+
+ resetStateForAccount(account);
+ const now = deps.now();
+ if (now < backoffUntil) return Promise.resolve();
+ if (lastRefreshAt > 0 && now - lastRefreshAt < throttleMs) return Promise.resolve();
+
+ lastRefreshAt = now;
+ inFlightAccount = account;
+ inFlight = (async () => {
+ try {
+ const result = await deps.fetchSnapshot();
+ backoffMs = 0;
+ backoffUntil = 0;
+ if (readAccountSafe() !== account) return;
+ if (result === 'empty') {
+ await deps.clearSnapshot();
+ return;
+ }
+ await deps.recordSnapshot({ ...result, ...(account ? { accountFingerprint: account } : {}) });
+ } catch (err) {
+ backoffMs = backoffMs > 0 ? Math.min(backoffMs * 2, backoffMaxMs) : backoffInitialMs;
+ backoffUntil = deps.now() + backoffMs;
+ deps.onRefreshError(err);
+ } finally {
+ inFlight = null;
+ inFlightAccount = null;
+ }
+ })();
+ return inFlight;
+ }
+
+ return {
+ async read(): Promise<ClaudeSubscriptionUsageSnapshot | null> {
+ const account = readAccountSafe();
+ if (account === null) return null;
+ const cached = await deps.readCachedSnapshot();
+ if (belongsToOtherAccount(cached, account)) {
+ await clearSnapshotSafe();
+ void refreshFor(account);
+ return null;
+ }
+ void refreshFor(account);
+ return cached;
+ },
+
+ triggerRefresh(): void {
+ // 节流 / 退避预检在读账号之前:本方法被每个 Claude turn-done 无条件调用。
+ const now = deps.now();
+ if (inFlight) return;
+ if (now < backoffUntil) return;
+ if (lastRefreshAt > 0 && now - lastRefreshAt < throttleMs) return;
+ const account = readAccountSafe();
+ if (account !== null) void refreshFor(account);
+ },
+
+ async syncForCredentialChange(): Promise<void> {
+ const account = readAccountSafe();
+ if (account === null) {
+ stateAccount = null;
+ lastRefreshAt = 0;
+ backoffMs = 0;
+ backoffUntil = 0;
+ await clearSnapshotSafe();
+ return;
+ }
+ const cached = await deps.readCachedSnapshot();
+ if (belongsToOtherAccount(cached, account)) await clearSnapshotSafe();
+ void refreshFor(account);
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
index b2b8e3491d..29c5c65d40 100644
--- a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
@@ -299,7 +299,7 @@ describe('ProvidersSection — 深链定位', () => {
);
it.each(['subscriptionAccount', 'openAiAccount'] as const)(
- 'collapses usage on %s changes but retains expansion on quota refresh',
+ 'shows usage windows without a details disclosure across %s changes',
async (identityField) => {
const account = { title: 'ChatGPT', windows: [{ key: 'weekly', title: 'Weekly', window: { utilization: 20 }, detail: 'Weekly usage details' }] };
vi.mocked(useProviderSubscriptionCard).mockReturnValue(account);
@@ -309,16 +309,13 @@ describe('ProvidersSection — 深链定位', () => {
});
providersState.providers = [provider];
const view = render(<MemoryRouter><ProvidersSection /></MemoryRouter>);
- fireEvent.click(await screen.findByRole('button', { name: 'quotaCard.usageTitle' }));
- const refresh = () => view.rerender(
- <MemoryRouter><ProvidersSection /></MemoryRouter>,
- );
- vi.mocked(useProviderSubscriptionCard).mockReturnValue({ ...account, updatedAt: Date.now() });
- refresh();
- expect(screen.getByRole('button', { name: 'quotaCard.usageTitle' }).getAttribute('aria-expanded')).toBe('true');
+ const usage = await screen.findByTestId('provider-usage-module');
+ expect(within(usage).getByRole('progressbar', { name: 'Weekly' })).toBeTruthy();
+ expect(within(usage).queryByText('Weekly usage details')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'quotaCard.usageTitle' })).toBeNull();
providersState.providers = [{ ...provider, [identityField]: { source: 'oauth', identity: '[email protected]' } }];
- refresh();
- expect(screen.getByRole('button', { name: 'quotaCard.usageTitle' }).getAttribute('aria-expanded')).toBe('false');
+ view.rerender(<MemoryRouter><ProvidersSection /></MemoryRouter>);
+ expect(within(screen.getByTestId('provider-usage-module')).getByRole('progressbar', { name: 'Weekly' })).toBeTruthy();
},
);
diff --git a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
index ecf59cc56c..6263c0bec9 100644
--- a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
+++ b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
@@ -10,7 +10,6 @@ import { useTranslation } from 'react-i18next';
import { computeQuotaPace, type QuotaPace } from '@/lib/quotaPace';
import { cn } from '@/lib/utils';
-import { Button } from '@/components/ui/button';
import {
formatQuotaResetCountdown,
formatQuotaResetAt,
@@ -122,7 +121,6 @@ function WindowBlock({
breakdown,
showAbsoluteReset = false,
compact = false,
- expanded = false,
nowMs,
paceNowMs,
locale,
@@ -136,7 +134,6 @@ function WindowBlock({
breakdown?: UsageCardWindow['breakdown'];
showAbsoluteReset?: boolean;
compact?: boolean;
- expanded?: boolean;
nowMs: number;
paceNowMs: number | null;
locale: string | undefined;
@@ -171,83 +168,90 @@ function WindowBlock({
nowMs: paceNowMs,
});
const paceLine = pace === null ? null : formatPaceLine(pace, t);
+ const titleNode = (
+ <div
+ id={titleId}
+ data-severity={severity}
+ className={cn(
+ 'font-medium tracking-[-0.005em]',
+ compact ? 'min-w-0 truncate text-13' : 'mb-2 text-14',
+ severity === 'crit' ? 'text-[var(--quota-bar-crit)]' : 'text-[var(--text-primary)]',
+ )}
+ >
+ {title}
+ {severityAnnouncement !== null ? (
+ // 告警不能只依赖颜色;标题与进度条共用对应级别的屏幕阅读器文案。
+ <span className="sr-only">,{severityAnnouncement}</span>
+ ) : null}
+ </div>
+ );
+ const bar = (
+ <QuotaBar
+ usedPercent={window.utilization}
+ showRemaining={showRemaining}
+ severity={severity}
+ aria-labelledby={titleId}
+ aria-valuetext={percentText}
+ />
+ );
+
+ if (compact) {
+ // 嵌入态(设置页)一行一个窗口:标题 | 进度条 | 百分比 | 重置倒计时,列宽由外层 grid 统一,
+ // 各行进度条左右对齐。明细(绝对重置时间 / 节奏 / breakdown)只在悬浮卡里展示。
+ return (
+ <section
+ data-testid="quota-window"
+ className="col-span-full grid grid-cols-subgrid items-center py-[7px] tabular-nums"
+ >
+ {titleNode}
+ {bar}
+ <span className="text-right font-medium text-[var(--text-primary)]">{percentText}</span>
+ <span className="text-right text-12 text-[var(--text-secondary)]">{resetCountdown}</span>
+ </section>
+ );
+ }
return (
<section data-testid="quota-window" className="px-4 pb-1 pt-2">
- <div className={compact ? 'flex flex-wrap items-center gap-x-3 gap-y-1' : undefined}>
- <div
- id={titleId}
- data-severity={severity}
- className={cn(
- 'font-medium tracking-[-0.005em]',
- compact ? 'text-13' : 'mb-2 text-14',
- severity === 'crit' ? 'text-[var(--quota-bar-crit)]' : 'text-[var(--text-primary)]',
- )}
- >
- {title}
- {severityAnnouncement !== null ? (
- // 告警不能只依赖颜色;标题与进度条共用对应级别的屏幕阅读器文案。
- <span className="sr-only">,{severityAnnouncement}</span>
- ) : null}
- </div>
- <QuotaBar
- className={compact ? 'w-28 shrink-0' : undefined}
- usedPercent={window.utilization}
- showRemaining={showRemaining}
- severity={severity}
- aria-labelledby={titleId}
- aria-valuetext={percentText}
- />
- <div
- className={cn(
- 'flex items-baseline justify-between gap-3 tabular-nums',
- !compact && 'mt-[7px]',
- )}
- >
+ <div>
+ {titleNode}
+ {bar}
+ <div className="mt-[7px] flex items-baseline justify-between gap-3 tabular-nums">
<span className="font-medium text-[var(--text-primary)]">{percentText}</span>
{resetCountdown !== null ? (
<span className="flex min-w-0 flex-col items-end text-right text-12 text-[var(--text-secondary)]">
<span>{resetCountdown}</span>
- {!compact && showAbsoluteReset && resetAt !== null && (
+ {showAbsoluteReset && resetAt !== null && (
<span>{t('quotaCard.resetAt', { at: resetAt })}</span>
)}
</span>
) : null}
</div>
</div>
- {(!compact || expanded) && (
- <>
- {compact && resetAt !== null && (
- <div className="mt-1 text-12 text-[var(--text-secondary)]">
- {t('quotaCard.resetAt', { at: resetAt })}
- </div>
- )}
- {detail ? (
- <div className="mt-1 text-12 text-[var(--text-secondary)]">{detail}</div>
- ) : null}
- {breakdown?.length ? (
- <dl
- data-testid="quota-window-breakdown"
- className="mt-2 space-y-1 text-12 text-[var(--text-secondary)]"
- >
- {breakdown.map(({ label, value }, index) => (
- <div key={index} className="flex items-baseline justify-between gap-3">
- <dt className="min-w-0 break-words">{label}</dt>
- <dd className="shrink-0 tabular-nums">{value}</dd>
- </div>
- ))}
- </dl>
- ) : null}
- {paceLine !== null ? (
- <div
- data-testid="quota-pace"
- className="mt-[3px] text-12 tabular-nums text-[var(--text-secondary)]"
- >
- {paceLine}
+ {detail ? (
+ <div className="mt-1 text-12 text-[var(--text-secondary)]">{detail}</div>
+ ) : null}
+ {breakdown?.length ? (
+ <dl
+ data-testid="quota-window-breakdown"
+ className="mt-2 space-y-1 text-12 text-[var(--text-secondary)]"
+ >
+ {breakdown.map(({ label, value }, index) => (
+ <div key={index} className="flex items-baseline justify-between gap-3">
+ <dt className="min-w-0 break-words">{label}</dt>
+ <dd className="shrink-0 tabular-nums">{value}</dd>
</div>
- ) : null}
- </>
- )}
+ ))}
+ </dl>
+ ) : null}
+ {paceLine !== null ? (
+ <div
+ data-testid="quota-pace"
+ className="mt-[3px] text-12 tabular-nums text-[var(--text-secondary)]"
+ >
+ {paceLine}
+ </div>
+ ) : null}
</section>
);
}
@@ -438,25 +442,27 @@ export function QuotaHoverCard({
nowMs = Date.now(),
}: QuotaHoverCardProps) {
const { t, i18n } = useTranslation();
- const [expanded, setExpanded] = React.useState(false);
const embedded = variant === 'embedded';
- const detailsId = React.useId();
// 测试可只注入 t;运行时再优先跟随应用当前语言格式化日期。
const locale = i18n?.resolvedLanguage ?? i18n?.language;
const { title, planLabel, windows, details = [], notices = [], emptyText, updatedAt } = account;
- // Pace also requires a valid reset time; balances and notices are always visible.
- const hasWindowDetails = windows.some(
- ({ window, detail, breakdown }) =>
- formatQuotaResetAt(window.resetsAt, nowMs, locale) !== null ||
- Boolean(detail) ||
- Boolean(breakdown?.length),
- );
// Use observation time for pace so a stale snapshot cannot drift as the card renders.
const paceNowMs = typeof updatedAt === 'number' && Number.isFinite(updatedAt) ? updatedAt : null;
const staleMinutes =
paceNowMs !== null && nowMs - paceNowMs > STALE_AFTER_MS
? Math.floor((nowMs - paceNowMs) / 60_000)
: null;
+ const windowBlocks = windows.map(({ key, ...displayWindow }) => (
+ <WindowBlock
+ key={key}
+ {...displayWindow}
+ compact={embedded}
+ nowMs={nowMs}
+ paceNowMs={paceNowMs}
+ locale={locale}
+ t={t}
+ />
+ ));
return (
<div
@@ -478,7 +484,6 @@ export function QuotaHoverCard({
'min-h-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]',
!embedded && 'overflow-y-auto pt-[6px]',
)}
- id={detailsId}
>
{title && (!embedded || !hideIdentity) ? (
<>
@@ -496,18 +501,17 @@ export function QuotaHoverCard({
</>
) : null}
{!embedded && title && (windows.length > 0 || emptyText) ? <CardDivider /> : null}
- {windows.map(({ key, ...displayWindow }) => (
- <WindowBlock
- key={key}
- {...displayWindow}
- compact={embedded}
- expanded={expanded}
- nowMs={nowMs}
- paceNowMs={paceNowMs}
- locale={locale}
- t={t}
- />
- ))}
+ {embedded && windowBlocks.length ? (
+ // 嵌入态各行是 subgrid,共用这里的四列:标题 | 进度条 | 百分比 | 重置倒计时。
+ <div
+ data-testid="quota-window-grid"
+ className="grid grid-cols-[max-content_minmax(64px,1fr)_max-content_max-content] gap-x-4 px-4 py-1"
+ >
+ {windowBlocks}
+ </div>
+ ) : (
+ windowBlocks
+ )}
{emptyText ? (
<div className="px-4 py-2 text-[var(--text-secondary)]">{emptyText}</div>
) : null}
@@ -558,19 +562,6 @@ export function QuotaHoverCard({
) : null}
</div>
- {embedded && hasWindowDetails && (
- <Button
- variant="secondary"
- type="button"
- aria-expanded={expanded}
- aria-controls={detailsId}
- onClick={() => setExpanded((value) => !value)}
- className="mx-4 w-fit gap-1"
- >
- <span aria-hidden="true">{expanded ? '▾' : '▸'}</span>
- {t('quotaCard.usageTitle')}
- </Button>
- )}
{dashboardLabel ? (
<>
<CardDivider />
diff --git a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
index e4864909e4..02f6847940 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
@@ -92,7 +92,7 @@ function weeklyAtProgress(utilization: number, progress: number) {
describe('QuotaHoverCard', () => {
it.each([undefined, null, 0, NaN, Infinity, 1e20])(
- 'omits the disclosure when windows have no displayable details (reset=%s)',
+ 'renders embedded windows without a reset time (reset=%s)',
(resetsAt) => {
render(<UsageCard variant="embedded" nowMs={NOW_MS} account={{
windows: [{ key: 'weekly', title: 'Weekly', window: { utilization: 20, resetsAt }, breakdown: [] }],
@@ -100,22 +100,38 @@ describe('QuotaHoverCard', () => {
}} />);
expect(screen.getByRole('progressbar')).toBeTruthy();
expect(screen.getByText('Balance available')).toBeTruthy();
- expect(screen.queryByRole('button', { name: 'quotaCard.usageTitle' })).toBeNull();
+ expect(screen.queryByRole('button')).toBeNull();
},
);
- it.each(['detail', 'breakdown'] as const)('discloses %s without a reset date', (kind) => {
- render(<UsageCard variant="embedded" account={{ windows: [
+ it.each(['detail', 'breakdown'] as const)('shows %s only in the popover, not the embedded card', (kind) => {
+ const account = { windows: [
{ key: 'plain', title: 'Plain', window: { utilization: 10 } },
{ key: 'detailed', title: 'Detailed', window: { utilization: 20 },
...(kind === 'detail' ? { detail: 'Extra usage' } : { breakdown: [{ label: 'Extra usage', value: '10' }] }),
},
- ] }} />);
+ ] };
+ const { rerender } = render(<UsageCard variant="embedded" account={account} />);
expect(screen.queryByText('Extra usage')).toBeNull();
- fireEvent.click(screen.getByRole('button', { name: 'quotaCard.usageTitle' }));
+ expect(screen.queryByRole('button')).toBeNull();
+ rerender(<UsageCard account={account} />);
expect(screen.getByText('Extra usage')).toBeTruthy();
});
+ it('lays embedded windows out as aligned grid rows', () => {
+ render(<UsageCard variant="embedded" account={{ windows: [
+ { key: 'a', title: '5 小时', window: { utilization: 10 } },
+ { key: 'b', title: 'Fable 周限', window: { utilization: 0 } },
+ ] }} />);
+ const grid = screen.getByTestId('quota-window-grid');
+ const rows = screen.getAllByTestId('quota-window');
+ expect(rows).toHaveLength(2);
+ for (const row of rows) {
+ expect(row.parentElement).toBe(grid);
+ expect(row.classList.contains('grid-cols-subgrid')).toBe(true);
+ }
+ });
+
it('hides duplicate identity without windows and only makes the popover region focusable', () => {
const account = { title: 'ChatGPT', planLabel: 'Pro', windows: [], emptyText: 'Waiting for usage' };
const { rerender } = render(<UsageCard variant="embedded" hideIdentity account={account} />);
@@ -189,17 +205,10 @@ describe('QuotaHoverCard', () => {
expect(screen.getByText('剩余 24%')).toBeTruthy();
expect(screen.getByText('7小时 5分钟后重置')).toBeTruthy();
expect(screen.queryByText('17:05 重置')).toBeNull();
- const detailsButton = screen.getByRole('button', { name: 'quotaCard.usageTitle' });
- expect(detailsButton.getAttribute('aria-expanded')).toBe('false');
- fireEvent.click(detailsButton);
- expect(detailsButton.getAttribute('aria-expanded')).toBe('true');
- expect(screen.getByText('17:05 重置')).toBeTruthy();
- expect(screen.getByText('8月7日 00:00 重置')).toBeTruthy();
- expect(screen.getByText('8月6日 23:59 重置')).toBeTruthy();
- expect(screen.getByText('18:30 重置')).toBeTruthy();
+ expect(screen.queryByRole('button')).toBeNull();
});
- it('keeps balances, alerts and stale data visible while embedded details are collapsed', () => {
+ it('keeps balances, alerts and stale data visible in the embedded card without pace details', () => {
render(
<UsageCard
variant="embedded"
@@ -229,11 +238,7 @@ describe('QuotaHoverCard', () => {
expect(screen.getByText('quotaCard.staleData:10')).toBeTruthy();
expect(screen.queryByTestId('quota-pace')).toBeNull();
expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBe('8');
- const button = screen.getByRole('button', { name: 'quotaCard.usageTitle' });
- fireEvent.click(button);
- expect(screen.getByTestId('quota-pace')).toBeTruthy();
- fireEvent.click(button);
- expect(screen.queryByTestId('quota-pace')).toBeNull();
+ expect(screen.queryByRole('button')).toBeNull();
});
it('prioritizes countdown in compact cards and updates to pending after reset', () => {
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index f4e60f55e9..4a7dbe05a4 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -82,7 +82,9 @@ Claude.ai 登录,也不得收集、存储或中转订阅凭证。Cindy 因此
直连,只注入 Anthropic 一方的子代理模型覆写。
- 「断开」只撤销 Cindy 的使用许可(`nativeProviderAuthBinding`),不登出 CLI。
旧版独立 Claude 账号已停用,但不删除其已存凭证。
-- 额度从 SDK `rate_limit_event` 读取,模型列表来自 SDK `supportedModels` 与 Registry;
+- 套餐余量由内置 CLI 的 `get_usage` 控制请求查询(CLI 用自己的登录发请求,拉起时不读
+ 项目级设置、不起 MCP、不落会话记录),会话内的 SDK `rate_limit_event` 做增量刷新;
+ 模型列表来自 SDK `supportedModels` 与 Registry;
不得为此恢复用订阅 token 直接调用 Anthropic API。
- 实现见 [claude-native-cli.ts](../../apps/desktop/src/main/maker-host/claude-native-cli.ts)、
[env-builder.ts](../../packages/maker-core/src/agents/claude-code/env-builder.ts);回归见