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(desktop): 额度卡片周限区增加消耗节奏预测(pace) (#1307)

Marioe8dfe4d7d530
diff --git a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
index 9a432ce5a9..23a5bf4f0b 100644
--- a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
+++ b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
@@ -8,6 +8,7 @@ import React from 'react';
import type { TFunction } from 'i18next';
import { useTranslation } from 'react-i18next';
+import { computeQuotaPace, type QuotaPace } from '@/lib/quotaPace';
import { cn } from '@/lib/utils';
import type {
ClaudeSubscriptionUsageSnapshot,
@@ -52,9 +53,13 @@ interface DisplayWindow {
key: string;
title: string;
window: ClaudeUsageWindow;
+ paceWindowMinutes?: number;
}
const STALE_AFTER_MS = 5 * 60_000;
+const WEEKLY_WINDOW_MINUTES = 10_080;
+/** 产品定档:±5 个百分点内视为正常节奏。 */
+const PACE_TREND_DELTA_PERCENT = 5;
function clampPercent(value: number): number {
if (!Number.isFinite(value)) return 0;
@@ -148,16 +153,32 @@ function CardDivider() {
return <div aria-hidden="true" className="mx-4 my-1.5 h-px bg-[var(--border-default)]" />;
}
+/** 将 pace 偏差映射成不承诺精确耗尽时间的粗略趋势。 */
+function formatPaceLine(pace: QuotaPace, t: TFunction): string {
+ const { deltaPercent } = pace;
+ if (deltaPercent > PACE_TREND_DELTA_PERCENT) {
+ return t('quotaCard.paceTrendFast');
+ }
+ if (deltaPercent < -PACE_TREND_DELTA_PERCENT) {
+ return t('quotaCard.paceTrendSlow');
+ }
+ return t('quotaCard.paceTrendNormal');
+}
+
function WindowBlock({
title,
window,
+ paceWindowMinutes,
nowMs,
+ paceNowMs,
locale,
t,
}: {
title: string;
window: ClaudeUsageWindow;
+ paceWindowMinutes?: number;
nowMs: number;
+ paceNowMs: number | null;
locale: string | undefined;
t: TFunction;
}) {
@@ -171,6 +192,21 @@ function WindowBlock({
? t('quotaCard.limitWarning')
: null;
const resetAt = formatResetAt(window.resetsAt, nowMs, locale);
+ // 窗口已过重置点,旧观测的节奏失真,待新快照。
+ const resetPassed =
+ typeof window.resetsAt === 'number' &&
+ Number.isFinite(window.resetsAt) &&
+ nowMs > window.resetsAt * 1000;
+ const pace =
+ paceWindowMinutes === undefined || paceNowMs === null || resetPassed
+ ? null
+ : computeQuotaPace({
+ utilization: window.utilization,
+ resetsAt: window.resetsAt,
+ windowMinutes: paceWindowMinutes,
+ nowMs: paceNowMs,
+ });
+ const paceLine = pace === null ? null : formatPaceLine(pace, t);
return (
<section data-testid="quota-window" className="px-4 pb-1 pt-2">
@@ -199,6 +235,14 @@ function WindowBlock({
</span>
) : null}
</div>
+ {paceLine !== null ? (
+ <div
+ data-testid="quota-pace"
+ className="mt-[3px] text-xs tabular-nums text-[var(--text-secondary)]"
+ >
+ {paceLine}
+ </div>
+ ) : null}
</section>
);
}
@@ -350,6 +394,13 @@ export function QuotaHoverCard({
// 测试可只注入 t;运行时再优先跟随应用当前语言格式化日期。
const locale = i18n?.resolvedLanguage ?? i18n?.language;
const planLabel = formatPlanType(snapshot?.subscriptionType);
+ // utilization 是 updatedAt 时刻的观测值,用观测时刻算节奏,避免旧快照随渲染时间自漂移;
+ // 缺有效观测时刻则不算节奏——回退渲染时刻会让趋势随倒计时重渲染无新数据自跳档。
+ const paceNowMs = snapshot
+ && typeof snapshot.updatedAt === 'number'
+ && Number.isFinite(snapshot.updatedAt)
+ ? snapshot.updatedAt
+ : null;
const windows: DisplayWindow[] = [];
if (isDisplayableWindow(snapshot?.fiveHour)) {
@@ -364,6 +415,7 @@ export function QuotaHoverCard({
key: 'seven-day',
title: t('quotaCard.weeklyLabel'),
window: snapshot.sevenDay,
+ paceWindowMinutes: WEEKLY_WINDOW_MINUTES,
});
}
// 持久化旧快照可能把 scoped 写成非数组;脏容器按缺失处理,避免 .entries() 崩溃。
@@ -431,7 +483,9 @@ export function QuotaHoverCard({
key={displayWindow.key}
title={displayWindow.title}
window={displayWindow.window}
+ paceWindowMinutes={displayWindow.paceWindowMinutes}
nowMs={nowMs}
+ paceNowMs={paceNowMs}
locale={locale}
t={t}
/>
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index e11a6433a5..960a227964 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -1434,7 +1434,9 @@ export function TodaySpendChip({
// (含滚动动画的每一帧), 直接进 tick effect 依赖会让定时器反复重建。
const resetsAtSignature = chipWindows.map((window) => window.resetsAtMs ?? 'na').join(',');
const chipResetsAtMsList = React.useMemo(
- () => chipWindows.map((window) => window.resetsAtMs),
+ () => resetsAtSignature === ''
+ ? []
+ : resetsAtSignature.split(',').map((value) => (value === 'na' ? null : Number(value))),
[resetsAtSignature],
);
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 0be5c630e2..0bf6716137 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
@@ -17,6 +17,9 @@ vi.mock('react-i18next', () => ({
if (key === 'quotaCard.limitRejected') return '已触发套餐限额,请求可能被拒绝';
if (key === 'quotaCard.limitWarning') return '接近套餐限额';
if (key === 'quotaCard.resetAt') return `${options.at} 重置`;
+ if (key === 'quotaCard.paceTrendFast') return '按当前平均速度偏快(粗略趋势)';
+ if (key === 'quotaCard.paceTrendNormal') return '按当前平均速度正常(粗略趋势)';
+ if (key === 'quotaCard.paceTrendSlow') return '按当前平均速度偏慢(粗略趋势)';
if (key === 'quotaCard.tokenBreakdown') {
return `(输入 ${options.input} · 输出 ${options.output})`;
}
@@ -40,6 +43,7 @@ vi.mock('react-i18next', () => ({
import { QuotaHoverCard } from '../QuotaHoverCard';
const NOW_MS = new Date(2026, 7, 1, 10, 0, 0).getTime();
+const WEEKLY_WINDOW_MS = 7 * 24 * 60 * 60_000;
function epochSeconds(year: number, month: number, day: number, hour: number, minute: number) {
return new Date(year, month, day, hour, minute, 0).getTime() / 1000;
@@ -54,6 +58,14 @@ function makeSnapshot(
};
}
+/** 按周窗口进度构造稳定输入,便于精确覆盖趋势百分点边界。 */
+function weeklyAtProgress(utilization: number, progress: number) {
+ return {
+ utilization,
+ resetsAt: (NOW_MS + WEEKLY_WINDOW_MS * (1 - progress)) / 1000,
+ };
+}
+
describe('QuotaHoverCard', () => {
it('renders only the waiting branch when snapshot is null', () => {
render(<QuotaHoverCard snapshot={null} nowMs={NOW_MS} />);
@@ -645,4 +657,137 @@ describe('QuotaHoverCard', () => {
expect(screen.getByText('5 小时').getAttribute('data-severity')).toBe('normal');
expect(screen.getByText('周限').getAttribute('data-severity')).toBe('normal');
});
+
+ it.each([
+ { label: '偏快', utilization: 31, expected: '按当前平均速度偏快(粗略趋势)' },
+ { label: '+5 边界', utilization: 30, expected: '按当前平均速度正常(粗略趋势)' },
+ { label: '正常', utilization: 25, expected: '按当前平均速度正常(粗略趋势)' },
+ { label: '-5 边界', utilization: 20, expected: '按当前平均速度正常(粗略趋势)' },
+ { label: '偏慢', utilization: 19, expected: '按当前平均速度偏慢(粗略趋势)' },
+ ])('renders the $label weekly pace trend', ({ utilization, expected }) => {
+ render(
+ <QuotaHoverCard
+ snapshot={makeSnapshot({ updatedAt: NOW_MS, sevenDay: weeklyAtProgress(utilization, 0.25) })}
+ nowMs={NOW_MS}
+ />,
+ );
+
+ expect(screen.getByTestId('quota-pace').textContent).toBe(expected);
+ });
+
+ it('keeps the pace line muted at a 68-point critical delta', () => {
+ render(
+ <QuotaHoverCard
+ snapshot={makeSnapshot({ updatedAt: NOW_MS, sevenDay: weeklyAtProgress(93, 0.25) })}
+ nowMs={NOW_MS}
+ />,
+ );
+
+ const pace = screen.getByTestId('quota-pace');
+ expect(pace.textContent).toBe('按当前平均速度偏快(粗略趋势)');
+ expect(pace.getAttribute('data-severity')).toBeNull();
+ expect(pace.classList.contains('text-[var(--text-secondary)]')).toBe(true);
+ expect(pace.className).not.toContain('quota-bar-crit');
+ });
+
+ it('hides the pace line when the snapshot has no valid updatedAt observation time', () => {
+ render(
+ <QuotaHoverCard
+ snapshot={makeSnapshot({ sevenDay: weeklyAtProgress(31, 0.25) })}
+ nowMs={NOW_MS}
+ />,
+ );
+
+ // 没有观测时刻就无法把利用率钉在时间轴上;不算节奏,避免趋势随重渲染自跳档。
+ expect(screen.queryByTestId('quota-pace')).toBeNull();
+ });
+
+ it('keeps the pace trend stable when the same snapshot renders 30 minutes later', () => {
+ const snapshot = makeSnapshot({
+ updatedAt: NOW_MS,
+ sevenDay: weeklyAtProgress(30.1, 0.25),
+ });
+ const { rerender } = render(<QuotaHoverCard snapshot={snapshot} nowMs={NOW_MS} />);
+ const originalText = screen.getByTestId('quota-pace').textContent;
+
+ rerender(
+ <QuotaHoverCard snapshot={snapshot} nowMs={NOW_MS + 30 * 60_000} />,
+ );
+
+ expect(originalText).toBe('按当前平均速度偏快(粗略趋势)');
+ expect(screen.getByTestId('quota-pace').textContent).toBe(originalText);
+ });
+
+ it('hides weekly pace after reset until a fresh snapshot arrives', () => {
+ const resetsAtMs = NOW_MS - 60 * 60_000;
+ render(
+ <QuotaHoverCard
+ snapshot={makeSnapshot({
+ updatedAt: resetsAtMs - 24 * 60 * 60_000,
+ sevenDay: {
+ utilization: 30,
+ resetsAt: resetsAtMs / 1000,
+ },
+ })}
+ nowMs={NOW_MS}
+ />,
+ );
+
+ expect(screen.queryByTestId('quota-pace')).toBeNull();
+ });
+
+ it('renders no pace for a scoped-only weekly snapshot', () => {
+ // 分模型周限有意不做节奏预测(计划范围决定)。
+ render(
+ <QuotaHoverCard
+ snapshot={makeSnapshot({
+ scoped: [{
+ modelDisplayName: 'Opus',
+ ...weeklyAtProgress(93, 0.25),
+ }],
+ })}
+ nowMs={NOW_MS}
+ />,
+ );
+
+ expect(screen.getByText('Opus 周限')).toBeTruthy();
+ expect(screen.queryByTestId('quota-pace')).toBeNull();
+ });
+
+ it('hides weekly pace when the window is missing, lacks a reset, or is under 3% elapsed', () => {
+ const { rerender } = render(
+ <QuotaHoverCard
+ snapshot={makeSnapshot({
+ fiveHour: {
+ utilization: 50,
+ resetsAt: epochSeconds(2026, 7, 1, 12, 0),
+ },
+ })}
+ nowMs={NOW_MS}
+ />,
+ );
+
+ expect(screen.queryByTestId('quota-pace')).toBeNull();
+
+ rerender(
+ <QuotaHoverCard
+ snapshot={makeSnapshot({ sevenDay: { utilization: 30, resetsAt: null } })}
+ nowMs={NOW_MS}
+ />,
+ );
+ expect(screen.queryByTestId('quota-pace')).toBeNull();
+
+ rerender(
+ <QuotaHoverCard
+ snapshot={makeSnapshot({
+ sevenDay: {
+ utilization: 30,
+ resetsAt: epochSeconds(2026, 7, 8, 8, 0),
+ },
+ })}
+ nowMs={NOW_MS}
+ />,
+ );
+ expect(screen.queryByTestId('quota-pace')).toBeNull();
+ });
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 4380e3a15a..e7c5470158 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4256,6 +4256,9 @@
"cacheLabel": "Cache",
"modelLabel": "Model",
"staleData": "Data updated {{minutes}} minutes ago",
+ "paceTrendFast": "Trending fast at the current average pace (rough estimate)",
+ "paceTrendNormal": "Trending normally at the current average pace (rough estimate)",
+ "paceTrendSlow": "Trending slowly at the current average pace (rough estimate)",
"waiting": "Claude subscription usage will update after the next request completes."
},
"usageDetails": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 78042053de..5fba1330b3 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4254,6 +4254,9 @@
"cacheLabel": "キャッシュ",
"modelLabel": "モデル",
"staleData": "データは {{minutes}} 分前に更新されました",
+ "paceTrendFast": "現在の平均使用ペースは速めです(おおよその傾向)",
+ "paceTrendNormal": "現在の平均使用ペースは通常です(おおよその傾向)",
+ "paceTrendSlow": "現在の平均使用ペースは遅めです(おおよその傾向)",
"waiting": "Claude サブスクリプションの使用量は次のリクエスト完了後に更新されます。"
},
"usageDetails": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index ce2b117d65..2882109410 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4254,6 +4254,9 @@
"cacheLabel": "캐시",
"modelLabel": "모델",
"staleData": "데이터가 {{minutes}}분 전에 업데이트되었습니다",
+ "paceTrendFast": "현재 평균 사용 속도는 빠른 편입니다(대략적인 추세)",
+ "paceTrendNormal": "현재 평균 사용 속도는 보통입니다(대략적인 추세)",
+ "paceTrendSlow": "현재 평균 사용 속도는 느린 편입니다(대략적인 추세)",
"waiting": "Claude 구독 사용량은 다음 요청이 완료된 후 업데이트됩니다."
},
"usageDetails": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 0bc0e54664..880eecfd7e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4254,6 +4254,9 @@
"cacheLabel": "缓存",
"modelLabel": "模型",
"staleData": "数据更新于 {{minutes}} 分钟前",
+ "paceTrendFast": "按当前平均速度偏快(粗略趋势)",
+ "paceTrendNormal": "按当前平均速度正常(粗略趋势)",
+ "paceTrendSlow": "按当前平均速度偏慢(粗略趋势)",
"waiting": "Claude 订阅余量会在下一轮完成后更新。"
},
"usageDetails": {
diff --git a/apps/desktop/src/renderer/lib/__tests__/quotaPace.test.ts b/apps/desktop/src/renderer/lib/__tests__/quotaPace.test.ts
new file mode 100644
index 0000000000..0b3703508b
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/quotaPace.test.ts
@@ -0,0 +1,205 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ computeQuotaPace,
+ type QuotaPace,
+ type QuotaPaceInput,
+} from '../quotaPace';
+
+const NOW_MS = 1_800_000_000_000;
+const FIVE_HOUR_MINUTES = 300;
+const WEEKLY_MINUTES = 10_080;
+
+/** 按窗口已过比例构造确定性的重置时间,避免测试依赖系统时钟。 */
+function inputAtProgress(
+ utilization: number,
+ progress: number,
+ windowMinutes = FIVE_HOUR_MINUTES,
+): QuotaPaceInput {
+ const durationMs = windowMinutes * 60 * 1000;
+ return {
+ utilization,
+ resetsAt: (NOW_MS + durationMs * (1 - progress)) / 1000,
+ windowMinutes,
+ nowMs: NOW_MS,
+ };
+}
+
+function requirePace(input: QuotaPaceInput): QuotaPace {
+ const result = computeQuotaPace(input);
+ expect(result).not.toBeNull();
+ return result!;
+}
+
+describe('computeQuotaPace — 防御条件', () => {
+ it.each([
+ ['null', null],
+ ['undefined', undefined],
+ ['NaN', Number.NaN],
+ ['正无穷', Number.POSITIVE_INFINITY],
+ ['负无穷', Number.NEGATIVE_INFINITY],
+ ] as const)('重置时间为 %s 时返回 null', (_label, resetsAt) => {
+ expect(
+ computeQuotaPace({
+ utilization: 50,
+ resetsAt,
+ windowMinutes: FIVE_HOUR_MINUTES,
+ nowMs: NOW_MS,
+ }),
+ ).toBeNull();
+ });
+
+ it.each([
+ ['零', 0],
+ ['负数', -1],
+ ['NaN', Number.NaN],
+ ['正无穷', Number.POSITIVE_INFINITY],
+ ['负无穷', Number.NEGATIVE_INFINITY],
+ ])('窗口分钟数为%s时返回 null', (_label, windowMinutes) => {
+ expect(
+ computeQuotaPace({
+ utilization: 50,
+ resetsAt: NOW_MS / 1000 + 60,
+ windowMinutes,
+ nowMs: NOW_MS,
+ }),
+ ).toBeNull();
+ });
+
+ it.each([
+ ['恰好到期', NOW_MS / 1000],
+ ['已经过期', NOW_MS / 1000 - 1],
+ ])('%s时返回 null', (_label, resetsAt) => {
+ expect(
+ computeQuotaPace({
+ utilization: 50,
+ resetsAt,
+ windowMinutes: FIVE_HOUR_MINUTES,
+ nowMs: NOW_MS,
+ }),
+ ).toBeNull();
+ });
+
+ it('重置时间超过窗口总时长时返回 null', () => {
+ const durationSeconds = FIVE_HOUR_MINUTES * 60;
+ expect(
+ computeQuotaPace({
+ utilization: 50,
+ resetsAt: NOW_MS / 1000 + durationSeconds + 1,
+ windowMinutes: FIVE_HOUR_MINUTES,
+ nowMs: NOW_MS,
+ }),
+ ).toBeNull();
+ });
+
+ it('窗口刚开始且已有用量时返回 null', () => {
+ const durationSeconds = WEEKLY_MINUTES * 60;
+ expect(
+ computeQuotaPace({
+ utilization: 1,
+ resetsAt: NOW_MS / 1000 + durationSeconds,
+ windowMinutes: WEEKLY_MINUTES,
+ nowMs: NOW_MS,
+ }),
+ ).toBeNull();
+ });
+
+ it('窗口经过 2.9% 时拒绝预测,恰好 3% 时开始预测', () => {
+ expect(computeQuotaPace(inputAtProgress(3, 0.029))).toBeNull();
+
+ const boundary = requirePace(inputAtProgress(3, 0.03));
+ expect(boundary).toEqual({
+ deltaPercent: 0,
+ expectedUsedPercent: 3,
+ actualUsedPercent: 3,
+ etaSeconds: null,
+ willLastToReset: true,
+ });
+ });
+});
+
+describe('computeQuotaPace — 配额节奏预测', () => {
+ it('周窗口中段按节奏消耗,恰好能撑到重置', () => {
+ expect(requirePace(inputAtProgress(50, 0.5, WEEKLY_MINUTES))).toEqual({
+ deltaPercent: 0,
+ expectedUsedPercent: 50,
+ actualUsedPercent: 50,
+ etaSeconds: null,
+ willLastToReset: true,
+ });
+ });
+
+ it('5 小时窗口超速,预计在重置前耗尽', () => {
+ const pace = requirePace(inputAtProgress(75, 0.5));
+ expect(pace.deltaPercent).toBe(25);
+ expect(pace.expectedUsedPercent).toBe(50);
+ expect(pace.actualUsedPercent).toBe(75);
+ expect(pace.etaSeconds).toBeCloseTo(3_000, 10);
+ expect(pace.willLastToReset).toBe(false);
+ });
+
+ it('5 小时窗口低于节奏,富余额度能撑到重置', () => {
+ expect(requirePace(inputAtProgress(25, 0.5))).toEqual({
+ deltaPercent: -25,
+ expectedUsedPercent: 50,
+ actualUsedPercent: 25,
+ etaSeconds: null,
+ willLastToReset: true,
+ });
+ });
+
+ it('已有窗口进度但实际用量为 0,不计算 ETA 且能撑到重置', () => {
+ expect(requirePace(inputAtProgress(0, 0.25))).toEqual({
+ deltaPercent: -25,
+ expectedUsedPercent: 25,
+ actualUsedPercent: 0,
+ etaSeconds: null,
+ willLastToReset: true,
+ });
+ });
+
+ it('实际用量达到 100% 时立即耗尽', () => {
+ expect(requirePace(inputAtProgress(100, 0.25, WEEKLY_MINUTES))).toEqual({
+ deltaPercent: 75,
+ expectedUsedPercent: 25,
+ actualUsedPercent: 100,
+ etaSeconds: 0,
+ willLastToReset: false,
+ });
+ });
+
+ it.each([
+ {
+ label: 'NaN 按 0 处理',
+ utilization: Number.NaN,
+ actualUsedPercent: 0,
+ deltaPercent: -50,
+ etaSeconds: null,
+ willLastToReset: true,
+ },
+ {
+ label: '负数夹到 0',
+ utilization: -5,
+ actualUsedPercent: 0,
+ deltaPercent: -50,
+ etaSeconds: null,
+ willLastToReset: true,
+ },
+ {
+ label: '超过上限夹到 100',
+ utilization: 250,
+ actualUsedPercent: 100,
+ deltaPercent: 50,
+ etaSeconds: 0,
+ willLastToReset: false,
+ },
+ ])('$label', ({ utilization, actualUsedPercent, deltaPercent, etaSeconds, willLastToReset }) => {
+ expect(requirePace(inputAtProgress(utilization, 0.5))).toEqual({
+ deltaPercent,
+ expectedUsedPercent: 50,
+ actualUsedPercent,
+ etaSeconds,
+ willLastToReset,
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/quotaPace.ts b/apps/desktop/src/renderer/lib/quotaPace.ts
new file mode 100644
index 0000000000..d445c922de
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/quotaPace.ts
@@ -0,0 +1,78 @@
+export interface QuotaPaceInput {
+ /** 0-100 已用百分比;允许脏值,由函数内部收敛。 */
+ utilization: number;
+ /** 配额窗口重置时间,epoch 秒。 */
+ resetsAt: number | null | undefined;
+ /** 窗口总时长(分钟),例如 5 小时为 300、周窗口为 10080。 */
+ windowMinutes: number;
+ /** 注入的当前时间,epoch 毫秒。 */
+ nowMs: number;
+}
+
+export interface QuotaPace {
+ /** 实际用量减去按时间推算的期望用量;正数表示超速,负数表示有富余。 */
+ deltaPercent: number;
+ expectedUsedPercent: number;
+ actualUsedPercent: number;
+ /** 按当前速率从现在到耗尽的秒数;能撑到重置时不返回 ETA。 */
+ etaSeconds: number | null;
+ willLastToReset: boolean;
+}
+
+const MIN_PREDICTION_PROGRESS = 0.03;
+
+function clamp(value: number, minimum: number, maximum: number): number {
+ return Math.min(maximum, Math.max(minimum, value));
+}
+
+/**
+ * 根据当前窗口的已用时间和实际用量,预测额度能否撑到下一次重置。
+ *
+ * 窗口进度不足 3% 时样本过少,不做预测;所有时间均由调用方注入,函数无副作用。
+ */
+export function computeQuotaPace(input: QuotaPaceInput): QuotaPace | null {
+ const { resetsAt, windowMinutes, nowMs } = input;
+
+ if (resetsAt == null || !Number.isFinite(resetsAt)) return null;
+ if (!Number.isFinite(windowMinutes) || windowMinutes <= 0) return null;
+
+ const duration = windowMinutes * 60 * 1000;
+ const timeUntilReset = resetsAt * 1000 - nowMs;
+ if (timeUntilReset <= 0) return null;
+ if (timeUntilReset > duration) return null;
+
+ const elapsed = clamp(duration - timeUntilReset, 0, duration);
+ const actual = Number.isFinite(input.utilization)
+ ? clamp(input.utilization, 0, 100)
+ : 0;
+
+ // 窗口刚开始却已有用量时,无法从零时长估算消耗速率。
+ if (elapsed === 0 && actual > 0) return null;
+ if (elapsed / duration < MIN_PREDICTION_PROGRESS) return null;
+
+ const expected = clamp((elapsed / duration) * 100, 0, 100);
+ const result = {
+ deltaPercent: actual - expected,
+ expectedUsedPercent: expected,
+ actualUsedPercent: actual,
+ };
+
+ if (actual >= 100) {
+ return { ...result, etaSeconds: 0, willLastToReset: false };
+ }
+
+ if (actual === 0) {
+ return { ...result, etaSeconds: null, willLastToReset: true };
+ }
+
+ const elapsedSeconds = elapsed / 1000;
+ const timeUntilResetSeconds = timeUntilReset / 1000;
+ const rate = actual / elapsedSeconds;
+ const candidate = (100 - actual) / rate;
+
+ if (candidate >= timeUntilResetSeconds) {
+ return { ...result, etaSeconds: null, willLastToReset: true };
+ }
+
+ return { ...result, etaSeconds: candidate, willLastToReset: false };
+}