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。

fix(claude): 余量刷新换号竞态、无法识别的响应保留缓存、窄宽度排版

Dashc6f52cff2054
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 a60cecfcaa..95536267a6 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeNativeCli.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeNativeCli.test.ts
@@ -346,4 +346,14 @@ describe('parseClaudeCliPlanUsageLine', () => {
response: { subtype: 'success', request_id: 'cindy-init', response: {} },
}))).toBeNull();
});
+
+ it('只有 rate_limits_available=false 才算没有余量;缺 rate_limits 按形状变化报错', () => {
+ const line = (response: unknown) => JSON.stringify({
+ type: 'control_response',
+ response: { subtype: 'success', request_id: 'cindy-plan-usage', response },
+ });
+ expect(parseClaudeCliPlanUsageLine(line({ rate_limits_available: false }))).toEqual({ usage: null });
+ expect(parseClaudeCliPlanUsageLine(line({ rate_limits_available: true }))?.error).toMatch('no rate_limits');
+ expect(parseClaudeCliPlanUsageLine(line({}))?.error).toMatch('no rate_limits');
+ });
});
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 7b0ad9ac7e..11f2423445 100644
--- a/apps/desktop/src/main/maker-host/claude-native-cli.ts
+++ b/apps/desktop/src/main/maker-host/claude-native-cli.ts
@@ -278,8 +278,9 @@ export interface ClaudeCliPlanUsage {
* 不接触凭证;不发用户消息,不产生模型调用。
*
* `get_usage` 是 CLI 标注为 Experimental 的控制请求,响应形状可能变化 —— 这里只取
- * `rate_limits` 原样交给调用方解析。CLI 声明当前账号没有套餐余量(非订阅 / 教育版等)
- * 时返回 null;启动失败、超时、控制请求报错时抛错,由调用方退避。
+ * `rate_limits` 原样交给调用方解析。CLI 明确声明当前账号没有套餐余量
+ * (`rate_limits_available: false`)时返回 null;启动失败、超时、控制请求报错或响应缺
+ * `rate_limits` 时抛错,由调用方退避。
*/
export async function readClaudeCliPlanUsage(): Promise<ClaudeCliPlanUsage | null> {
const binary = cliBinaryPath();
@@ -365,8 +366,10 @@ export function parseClaudeCliPlanUsageLine(
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 };
+ // 只有 CLI 明确声明没有套餐余量才返回 null;缺 rate_limits 按形状变化报错,不当成「没有」。
+ if (body.rate_limits_available === false) return { usage: null };
+ if (!body.rate_limits || typeof body.rate_limits !== 'object') {
+ return { error: 'claude get_usage response has no rate_limits', usage: null };
}
const subscriptionType = optionalString(body.subscription_type);
return { usage: { rateLimits: body.rate_limits, ...(subscriptionType ? { subscriptionType } : {}) } };
diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.ts
index f6c8c6775b..5d2c7acb7b 100644
--- a/apps/desktop/src/main/maker-ipc/usage.ts
+++ b/apps/desktop/src/main/maker-ipc/usage.ts
@@ -103,7 +103,8 @@ const claudeSubscriptionUsageReader = createClaudeSubscriptionUsageReader({
const usage = await readClaudeCliPlanUsage();
if (!usage) return 'empty';
const snapshot = parseClaudeOAuthUsageResponse(usage.rateLimits, Date.now());
- if (!snapshot) return 'empty';
+ // get_usage 是 Experimental:解析不出窗口按形状变化处理,抛错退避并保留已有缓存。
+ if (!snapshot) throw new Error('claude get_usage returned unrecognized rate_limits');
const subscriptionType = usage.subscriptionType ?? peekClaudeCliLoginStatus()?.subscriptionType;
return subscriptionType ? { ...snapshot, subscriptionType } : snapshot;
},
diff --git a/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.ts b/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.ts
index e1e71371ec..cafdf74435 100644
--- a/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsageRefresh.test.ts
@@ -122,6 +122,39 @@ describe('createClaudeSubscriptionUsageReader', () => {
expect(state.cached).toMatchObject({ accountFingerprint: 'acct-b' });
});
+ it('拉取失败(含返回形状无法识别)保留已有缓存,不当成没有余量', async () => {
+ const cached = { ...SNAPSHOT, source: 'unified-headers' as const };
+ const { deps, reader, state } = setup({ cached });
+ deps.fetchSnapshot.mockRejectedValue(new Error('claude get_usage returned unrecognized rate_limits'));
+ reader.triggerRefresh();
+ await flush();
+ expect(deps.clearSnapshot).not.toHaveBeenCalled();
+ expect(state.cached).toBe(cached);
+ });
+
+ it('读缓存期间换号:不返回也不清理,避免把旧账号余量给新账号或误删新账号快照', async () => {
+ const { deps, reader, state } = setup({ cached: { ...SNAPSHOT, accountFingerprint: 'acct-a' } });
+ deps.readCachedSnapshot.mockImplementationOnce(async () => {
+ const snapshot = state.cached;
+ state.account = 'acct-b';
+ return snapshot;
+ });
+ await expect(reader.read()).resolves.toBeNull();
+ expect(deps.clearSnapshot).not.toHaveBeenCalled();
+ expect(deps.fetchSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('syncForCredentialChange 读缓存期间又换号:交给新账号那次同步,本次不清理', async () => {
+ const { deps, reader, state } = setup({ account: 'acct-b', cached: { ...SNAPSHOT, accountFingerprint: 'acct-b' } });
+ deps.readCachedSnapshot.mockImplementationOnce(async () => {
+ state.account = 'acct-c';
+ return { ...SNAPSHOT, accountFingerprint: 'acct-a' };
+ });
+ await reader.syncForCredentialChange();
+ expect(deps.clearSnapshot).not.toHaveBeenCalled();
+ expect(deps.fetchSnapshot).not.toHaveBeenCalled();
+ });
+
it('拉取期间换号:旧账号的结果被丢弃,收尾后为新账号补拉', async () => {
const { deps, reader, state } = setup();
let release: (value: ClaudeSubscriptionUsageSnapshot) => void = () => {};
diff --git a/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.ts b/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.ts
index d2e20ecf5c..e765be67a1 100644
--- a/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.ts
+++ b/apps/desktop/src/main/usage/claudeSubscriptionUsageRefresh.ts
@@ -17,8 +17,9 @@ interface ClaudeSubscriptionUsageRefreshDeps {
/** 当前已连接的 Claude 订阅账号指纹;未连接 → null。账号已连接但指纹未知时返回空串。 */
readAccount(): string | null;
/**
- * 拉一次快照。snapshot = 正常;'empty' = CLI 声明账号没有套餐余量,或返回里解析不出
- * 任何窗口(应清缓存降级为无数据)。失败时抛错。
+ * 拉一次快照。snapshot = 正常;'empty' = CLI **明确**声明账号没有套餐余量(清缓存降级为
+ * 无数据)。失败或返回形状无法识别时抛错:退避重试并保留缓存(含会话 rate_limit_event
+ * 写入的余量),不把「看不懂」当成「没有」。
*/
fetchSnapshot(): Promise<ClaudeSubscriptionUsageSnapshot | 'empty'>;
recordSnapshot(snapshot: ClaudeSubscriptionUsageSnapshot): Promise<void>;
@@ -92,8 +93,13 @@ export function createClaudeSubscriptionUsageReader(
}
/** 缓存快照属于别的账号(同机在 CLI 里换号)。指纹缺失按未知归属沿用,不误清。 */
- function belongsToOtherAccount(snapshot: ClaudeSubscriptionUsageSnapshot | null, account: string): boolean {
- return Boolean(snapshot?.accountFingerprint && account && snapshot.accountFingerprint !== account);
+ function belongsToOtherAccount(
+ snapshot: ClaudeSubscriptionUsageSnapshot | null,
+ account: string,
+ ): boolean {
+ return Boolean(
+ snapshot?.accountFingerprint && account && snapshot.accountFingerprint !== account,
+ );
}
function refreshFor(account: string): Promise<void> {
@@ -125,7 +131,10 @@ export function createClaudeSubscriptionUsageReader(
await deps.clearSnapshot();
return;
}
- await deps.recordSnapshot({ ...result, ...(account ? { accountFingerprint: account } : {}) });
+ await deps.recordSnapshot({
+ ...result,
+ ...(account ? { accountFingerprint: account } : {}),
+ });
} catch (err) {
backoffMs = backoffMs > 0 ? Math.min(backoffMs * 2, backoffMaxMs) : backoffInitialMs;
backoffUntil = deps.now() + backoffMs;
@@ -143,6 +152,9 @@ export function createClaudeSubscriptionUsageReader(
const account = readAccountSafe();
if (account === null) return null;
const cached = await deps.readCachedSnapshot();
+ // 读缓存期间换号:按旧账号做的归属判断已失效,既不返回(可能是旧账号的余量)也不清理
+ // (新账号的快照可能刚写入)。新账号的余量随登录态同步 / 刷新广播。
+ if (readAccountSafe() !== account) return null;
if (belongsToOtherAccount(cached, account)) {
await clearSnapshotSafe();
void refreshFor(account);
@@ -173,6 +185,8 @@ export function createClaudeSubscriptionUsageReader(
return;
}
const cached = await deps.readCachedSnapshot();
+ // 同 read():期间又换号时交给新账号那次同步处理,本次不清理、不刷新。
+ if (readAccountSafe() !== account) return;
if (belongsToOtherAccount(cached, account)) await clearSnapshotSafe();
void refreshFor(account);
},
diff --git a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
index 6263c0bec9..dacf2f5074 100644
--- a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
+++ b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
@@ -206,7 +206,12 @@ function WindowBlock({
{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>
+ <span
+ className="min-w-0 truncate text-right text-12 text-[var(--text-secondary)]"
+ title={resetCountdown ?? undefined}
+ >
+ {resetCountdown}
+ </span>
</section>
);
}
@@ -228,9 +233,7 @@ function WindowBlock({
) : null}
</div>
</div>
- {detail ? (
- <div className="mt-1 text-12 text-[var(--text-secondary)]">{detail}</div>
- ) : null}
+ {detail ? <div className="mt-1 text-12 text-[var(--text-secondary)]">{detail}</div> : null}
{breakdown?.length ? (
<dl
data-testid="quota-window-breakdown"
@@ -503,9 +506,10 @@ export function QuotaHoverCard({
{!embedded && title && (windows.length > 0 || emptyText) ? <CardDivider /> : null}
{embedded && windowBlocks.length ? (
// 嵌入态各行是 subgrid,共用这里的四列:标题 | 进度条 | 百分比 | 重置倒计时。
+ // 窄宽度时倒计时列先收缩截断(全文见 title),进度条再缩到 48px,不横向溢出。
<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"
+ className="grid grid-cols-[max-content_minmax(48px,1fr)_max-content_minmax(0,max-content)] gap-x-4 px-4 py-1"
>
{windowBlocks}
</div>
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 02f6847940..45a7cd7eaf 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
@@ -130,6 +130,17 @@ describe('QuotaHoverCard', () => {
expect(row.parentElement).toBe(grid);
expect(row.classList.contains('grid-cols-subgrid')).toBe(true);
}
+ // 窄宽度:倒计时列可收缩截断,不把余量挤出容器。
+ expect(grid.className).toContain('minmax(0,max-content)');
+ });
+
+ it('keeps the full reset countdown available when the embedded column truncates', () => {
+ render(<UsageCard variant="embedded" nowMs={NOW_MS} account={{ windows: [
+ { key: 'a', title: '5 小时', window: { utilization: 10, resetsAt: (NOW_MS + 65 * 60_000) / 1000 } },
+ ] }} />);
+ const countdown = screen.getByText('1小时 5分钟后重置');
+ expect(countdown.classList.contains('truncate')).toBe(true);
+ expect(countdown.getAttribute('title')).toBe('1小时 5分钟后重置');
});
it('hides duplicate identity without windows and only makes the popover region focusable', () => {