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(desktop): 补充 Codex 重置卡悬停信息 (#822)

Chener5771061505f0
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b0cf90d908..5542be388f 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1,4 +1,5 @@
import { contextBridge, ipcRenderer, webUtils } from 'electron';
+import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
import {
AGENT_ISLAND_GET_DISPLAY_OPTIONS_CHANNEL,
AGENT_ISLAND_PREVIEW_SOUND_CHANNEL,
@@ -4581,6 +4582,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:usage:today', agentKind),
getAccount: (agentKind: 'claude-code' | 'codex'): Promise<unknown> =>
ipcRenderer.invoke('maker:usage:account', agentKind),
+ /** Codex app-server authoritative windows and banked reset-credit metadata. */
+ getCodexRateLimits: (): Promise<MobileCodexRateLimitsResult> =>
+ ipcRenderer.invoke('maker:usage:codex-rate-limits'),
/** Claude 订阅账号余量 (5h/周/分模型窗口, cached-first, main 侧按需后台刷新)。 */
getClaudeSubscription: (): Promise<unknown | null> =>
ipcRenderer.invoke('maker:usage:claude-subscription'),
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
index 5700df7eec..2c9baac025 100644
--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
@@ -10,8 +10,18 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
const sourcePath = resolve(__dirname, '..', 'components', 'status', 'TodaySpendChip.tsx');
+const preloadPath = resolve(__dirname, '..', '..', 'preload', 'preload.ts');
+const rendererTypesPath = resolve(__dirname, '..', 'vite-env.d.ts');
// Windows CRLF 检出下 \n 字面量断言会失配,统一归一化成 LF 再断言。
const source = readFileSync(sourcePath, 'utf8').replace(/\r\n/g, '\n');
+const preloadSource = readFileSync(preloadPath, 'utf8').replace(/\r\n/g, '\n');
+const rendererTypesSource = readFileSync(rendererTypesPath, 'utf8').replace(/\r\n/g, '\n');
+const localeSources = ['en', 'zh-CN', 'ja', 'ko'].map((locale) =>
+ readFileSync(
+ resolve(__dirname, '..', 'i18n', 'locales', locale, 'common.json'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n'),
+);
describe('TodaySpendChip dashboard routing', () => {
it('separates the latest user-round total from final-segment token details', () => {
@@ -109,6 +119,41 @@ describe('TodaySpendChip dashboard routing', () => {
expect(source).toContain("isChatgptBridge ? 'openai-web' : 'app-server',");
});
+ it('shows the shared mobile Codex reset-credit summary for local Desktop sessions', () => {
+ // 主进程已有 authoritative read;Desktop renderer 需补齐 preload + 类型链路。
+ expect(preloadSource).toContain(
+ 'getCodexRateLimits: (): Promise<MobileCodexRateLimitsResult>',
+ );
+ expect(preloadSource).toContain(
+ "ipcRenderer.invoke('maker:usage:codex-rate-limits')",
+ );
+ expect(rendererTypesSource).toContain(
+ 'getCodexRateLimits: () => Promise<',
+ );
+ // 仅本机 Codex OAuth 会话读取本机账号数据;远程 / bridge 不张冠李戴。
+ expect(source).toContain(
+ 'useCodexRateLimits(isCodexOauth && !isAnyRemoteSession)',
+ );
+ // 复用 Mobile 的中性汇总字段;Desktop 按当前界面语言渲染 label / 次数 / 本地时间。
+ expect(source).toContain('summarizeCodexRateLimitReset');
+ // 复用 chip 现有 tick 时间基准,跨日时本地时间文案会重新格式化。
+ expect(source).toContain(
+ 'summarizeCodexRateLimitReset(codexRateLimits, windowLabelNowMs)',
+ );
+ expect(source).toContain('resetSummary?.hasResetCreditCount');
+ expect(source).toContain('resetSummary?.earliestExpiryAt');
+ expect(source).toContain("t('todaySpend.codex.resetCreditsAvailableLine'");
+ expect(source).toContain("t('todaySpend.codex.resetCreditEarliestExpiryLine'");
+ expect(source).toContain('i18n.resolvedLanguage ?? i18n.language');
+ expect(source).not.toContain('resetSummary?.resetRows');
+ for (const localeSource of localeSources) {
+ expect(localeSource).toContain('"resetCreditsAvailableLine"');
+ expect(localeSource).toContain('"resetCreditEarliestExpiryLine"');
+ }
+ // 长时间挂载时每次重新悬停都会刷新,首次瞬态失败与外部消费/授予不会永久陈旧。
+ expect(source).toContain('onMouseEnter={refreshCodexRateLimits}');
+ });
+
it('keeps Codex OAuth subscription details in the chip and tooltip', () => {
expect(source).not.toContain('CODEX_CREDIT_USD_RATE');
expect(source).not.toContain('usdFormatted');
diff --git a/apps/desktop/src/renderer/__tests__/useCodexRateLimits.test.ts b/apps/desktop/src/renderer/__tests__/useCodexRateLimits.test.ts
new file mode 100644
index 0000000000..61da35b8b8
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/useCodexRateLimits.test.ts
@@ -0,0 +1,105 @@
+// @vitest-environment jsdom
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
+import {
+ readCodexRateLimitsSafely,
+ useCodexRateLimits,
+} from '@/hooks/useCodexRateLimits';
+
+const result: MobileCodexRateLimitsResult = {
+ account: { email: null, accountId: null, planType: 'plus' },
+ rateLimits: {},
+ rateLimitsByLimitId: null,
+ rateLimitResetCredits: { availableCount: 2, credits: [] },
+ resetOffer: null,
+};
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('useCodexRateLimits', () => {
+ it('loads the existing Desktop Codex rate-limit channel when enabled', async () => {
+ const getCodexRateLimits = vi.fn().mockResolvedValue(result);
+ vi.stubGlobal('electronAPI', {
+ maker: { usage: { getCodexRateLimits } },
+ });
+
+ const { result: hook } = renderHook(() => useCodexRateLimits(true));
+
+ await waitFor(() => expect(hook.current.snapshot).toBe(result));
+ expect(getCodexRateLimits).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not read local Codex account data when disabled', () => {
+ const getCodexRateLimits = vi.fn().mockResolvedValue(result);
+ vi.stubGlobal('electronAPI', {
+ maker: { usage: { getCodexRateLimits } },
+ });
+
+ const { result: hook } = renderHook(() => useCodexRateLimits(false));
+
+ expect(hook.current.snapshot).toBeNull();
+ expect(getCodexRateLimits).not.toHaveBeenCalled();
+ });
+
+ it('retries a transient initial failure when the tooltip asks for fresh data', async () => {
+ const getCodexRateLimits = vi.fn()
+ .mockRejectedValueOnce(new Error('app-server starting'))
+ .mockResolvedValueOnce(result);
+ vi.stubGlobal('electronAPI', {
+ maker: { usage: { getCodexRateLimits } },
+ });
+
+ const { result: hook } = renderHook(() => useCodexRateLimits(true));
+
+ await waitFor(() => expect(getCodexRateLimits).toHaveBeenCalledTimes(1));
+ expect(hook.current.snapshot).toBeNull();
+
+ act(() => hook.current.refresh());
+
+ await waitFor(() => expect(hook.current.snapshot).toBe(result));
+ expect(getCodexRateLimits).toHaveBeenCalledTimes(2);
+ });
+
+ it('clears the old account and refetches after a Codex auth change', async () => {
+ const nextResult: MobileCodexRateLimitsResult = {
+ ...result,
+ account: { ...result.account, accountId: 'next-account' },
+ rateLimitResetCredits: { availableCount: 1, credits: [] },
+ };
+ const getCodexRateLimits = vi.fn()
+ .mockResolvedValueOnce(result)
+ .mockResolvedValueOnce(nextResult);
+ let onStateChanged: ((payload: { agentKind: string }) => void) | undefined;
+ vi.stubGlobal('electronAPI', {
+ maker: {
+ auth: {
+ onStateChanged: vi.fn((callback) => {
+ onStateChanged = callback;
+ return vi.fn();
+ }),
+ },
+ usage: { getCodexRateLimits },
+ },
+ });
+
+ const { result: hook } = renderHook(() => useCodexRateLimits(true));
+ await waitFor(() => expect(hook.current.snapshot).toBe(result));
+
+ act(() => onStateChanged?.({ agentKind: 'codex' }));
+
+ await waitFor(() => expect(hook.current.snapshot).toBe(nextResult));
+ expect(getCodexRateLimits).toHaveBeenCalledTimes(2);
+ });
+
+ it('degrades to null when the preload API is absent or the read fails', async () => {
+ await expect(readCodexRateLimitsSafely(undefined)).resolves.toBeNull();
+ await expect(readCodexRateLimitsSafely(
+ vi.fn().mockRejectedValue(new Error('app-server unavailable')),
+ )).resolves.toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index de067e6473..480bd20a98 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -34,6 +34,10 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
+import {
+ summarizeCodexRateLimitReset,
+ type CodexRateLimitResetSummary,
+} from '@cindy/maker-shared/session-controls';
import { cn } from '@/lib/utils';
import {
@@ -72,6 +76,7 @@ import {
type ClaudeUsageWindow,
} from '../../../shared/claudeSubscriptionUsage';
import { useCodexRuntimeRoute } from '@/hooks/useCodexRuntimeRoute';
+import { useCodexRateLimits } from '@/hooks/useCodexRateLimits';
import { useXaiRateLimit, type XaiRateLimitSnapshot } from '@/hooks/useXaiRateLimit';
import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';
import { buildTurnUsageTooltipLines } from '@/lib/turnUsageTooltip';
@@ -233,6 +238,28 @@ function formatResetAt(epochSeconds: number | null | undefined): string | null {
).format(date);
}
+/** Codex 重置卡到期时间:沿用产品的“当天时分、跨天月日+时分”,按界面语言本地化。 */
+function formatResetCreditExpiryAt(
+ epochSeconds: number | null | undefined,
+ nowMs: number,
+ locale: string,
+): string | null {
+ if (typeof epochSeconds !== 'number' || !Number.isFinite(epochSeconds) || epochSeconds <= 0) {
+ return null;
+ }
+ const date = new Date(epochSeconds * 1000);
+ const now = new Date(nowMs);
+ const sameDay = date.getFullYear() === now.getFullYear()
+ && date.getMonth() === now.getMonth()
+ && date.getDate() === now.getDate();
+ return new Intl.DateTimeFormat(
+ locale,
+ sameDay
+ ? { hour: 'numeric', minute: '2-digit' }
+ : { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' },
+ ).format(date);
+}
+
/**
* chip 主体用的紧凑剩余时长(距 reset 还有多久): 单级精度 + 向上取整 ——
* 「7天」/「3小时」/「45分钟」/「41秒」。Codex 与 Claude 订阅两种形态统一用它当窗口
@@ -452,7 +479,9 @@ function buildCodexTooltipNode(
snapshot: RateLimitSnapshot | null,
sessionTokens: number | null,
sessionValueMoney: RegionalMoney | null,
+ resetSummary: CodexRateLimitResetSummary | null,
t: TFunction,
+ locale: string,
usageDashboardLabel: string | null,
nowMs: number,
latestTurnUsage: LatestTurnUsageSummary | null,
@@ -460,6 +489,7 @@ function buildCodexTooltipNode(
const lines: string[] = [];
if (!snapshot) {
lines.push(t('todaySpend.codex.waitingDetail'));
+ pushCodexResetCreditLines(lines, resetSummary, t, locale, nowMs);
appendLatestTurnUsageLines(lines, latestTurnUsage, t);
pushDashboardLinkLine(lines, usageDashboardLabel);
return buildTooltipNode(lines);
@@ -490,6 +520,7 @@ function buildCodexTooltipNode(
lines.push(t('todaySpend.codex.balanceAvailable'));
}
pushSessionValueLines(lines, sessionValueMoney, sessionTokens, t);
+ pushCodexResetCreditLines(lines, resetSummary, t, locale, nowMs);
for (const window of getCodexWindowUsages(snapshot, t, nowMs)) {
const base = t('todaySpend.codex.windowLine', {
@@ -856,6 +887,29 @@ function pushSessionValueLines(
}
}
+/** 与 Mobile 共用中性汇总字段;Desktop label、次数和时间按当前界面语言展示。 */
+function pushCodexResetCreditLines(
+ lines: string[],
+ resetSummary: CodexRateLimitResetSummary | null,
+ t: TFunction,
+ locale: string,
+ nowMs: number,
+): void {
+ if (resetSummary?.hasResetCreditCount) {
+ lines.push(t('todaySpend.codex.resetCreditsAvailableLine', {
+ count: resetSummary.availableCount,
+ }));
+ }
+ const expiryAt = formatResetCreditExpiryAt(
+ resetSummary?.earliestExpiryAt,
+ nowMs,
+ locale,
+ );
+ if (expiryAt) {
+ lines.push(t('todaySpend.codex.resetCreditEarliestExpiryLine', { at: expiryAt }));
+ }
+}
+
/**
* xAI(SuperGrok bridge)tooltip —— 尽力档:有限流快照(bridge 抓到 x-ratelimit-* 头)就
* 显示剩余请求/tokens,拿不到诚实标注「无订阅额度明细」,只显示价值估算 + token 累计。
@@ -943,7 +997,8 @@ export function TodaySpendChip({
remoteHostId,
deviceLinkDeviceId,
}: TodaySpendChipProps) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
+ const formatterLocale = i18n.resolvedLanguage ?? i18n.language;
// device-link 远程会话:turn 跑在被控端、消耗被控端账号,计费形态(订阅/网关)与账号
// 余量的事实都在被控端 —— 本机的 route 观察 / 账号快照与之无关,一律不读、不据此分类。
const isDeviceLinkRemote = Boolean(deviceLinkDeviceId);
@@ -1057,6 +1112,10 @@ export function TodaySpendChip({
// 促销桶, 见 useAccountUsage.matchCodexBucketForModel)。
modelId,
);
+ const {
+ snapshot: codexRateLimits,
+ refresh: refreshCodexRateLimits,
+ } = useCodexRateLimits(isCodexOauth && !isAnyRemoteSession);
// xAI 限流快照同为本机 main 抓的 —— 远程会话(SSH / device-link)同样抑制,回落价值估算。
const xaiRateLimit = useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession);
// cc 与 codex-api 共用同一把 XD gateway key 的 LiteLLM quota; codex-oauth 不订阅。
@@ -1096,6 +1155,10 @@ export function TodaySpendChip({
? t('todaySpend.openClaudeUsage')
: null;
const [windowLabelNowMs, setWindowLabelNowMs] = React.useState(() => Date.now());
+ const codexResetSummary = React.useMemo(
+ () => summarizeCodexRateLimitReset(codexRateLimits, windowLabelNowMs),
+ [codexRateLimits, windowLabelNowMs],
+ );
// 当前形态下 chip 展示的限额窗口段 (Codex 订阅 / Claude 订阅共用结构);
// 其它形态为空数组, 两个 rollup slot 空转。
@@ -1263,7 +1326,9 @@ export function TodaySpendChip({
accountUsage,
sessionTokens,
sessionEstimatedValueMoney,
+ codexResetSummary,
t,
+ formatterLocale,
usageDashboardLabel,
windowLabelNowMs,
latestTurnUsage,
@@ -1400,7 +1465,12 @@ export function TodaySpendChip({
);
return (
- <div ref={chipRef} className="inline-flex h-5 shrink-0 items-center gap-3">
+ <div
+ ref={chipRef}
+ className="inline-flex h-5 shrink-0 items-center gap-3"
+ onMouseEnter={refreshCodexRateLimits}
+ onFocusCapture={refreshCodexRateLimits}
+ >
<Tip text={tooltipNode}>
{isDashboardClickable ? (
<button
diff --git a/apps/desktop/src/renderer/hooks/useCodexRateLimits.ts b/apps/desktop/src/renderer/hooks/useCodexRateLimits.ts
new file mode 100644
index 0000000000..154874d552
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useCodexRateLimits.ts
@@ -0,0 +1,88 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
+
+type CodexRateLimitsReader = () => Promise<MobileCodexRateLimitsResult>;
+type CodexAuthStateSubscriber = (
+ callback: (payload: { agentKind?: string }) => void,
+) => () => void;
+
+function readCodexRateLimitsReader(): CodexRateLimitsReader | undefined {
+ return (window as unknown as {
+ electronAPI?: {
+ maker?: {
+ usage?: {
+ getCodexRateLimits?: CodexRateLimitsReader;
+ };
+ };
+ };
+ }).electronAPI?.maker?.usage?.getCodexRateLimits;
+}
+
+function readCodexAuthStateSubscriber(): CodexAuthStateSubscriber | undefined {
+ return (window as unknown as {
+ electronAPI?: {
+ maker?: {
+ auth?: {
+ onStateChanged?: CodexAuthStateSubscriber;
+ };
+ };
+ };
+ }).electronAPI?.maker?.auth?.onStateChanged;
+}
+
+/** Missing/older preload and failed app-server reads both degrade to no extra tooltip rows. */
+export async function readCodexRateLimitsSafely(
+ reader: CodexRateLimitsReader | undefined,
+): Promise<MobileCodexRateLimitsResult | null> {
+ if (!reader) return null;
+ try {
+ return await reader();
+ } catch {
+ return null;
+ }
+}
+
+export interface CodexRateLimitsState {
+ snapshot: MobileCodexRateLimitsResult | null;
+ /** Best-effort authoritative refetch, used when the tooltip is opened again. */
+ refresh: () => void;
+}
+
+export function useCodexRateLimits(enabled: boolean): CodexRateLimitsState {
+ const [snapshot, setSnapshot] = useState<MobileCodexRateLimitsResult | null>(null);
+ const requestVersionRef = useRef(0);
+
+ const refresh = useCallback(() => {
+ if (!enabled) return;
+ const requestVersion = ++requestVersionRef.current;
+ void readCodexRateLimitsSafely(readCodexRateLimitsReader()).then((next) => {
+ if (requestVersionRef.current === requestVersion) setSnapshot(next);
+ });
+ }, [enabled]);
+
+ useEffect(() => {
+ if (!enabled) {
+ requestVersionRef.current += 1;
+ setSnapshot(null);
+ return;
+ }
+
+ refresh();
+ const onStateChanged = readCodexAuthStateSubscriber();
+ const unsubscribe = onStateChanged?.((payload) => {
+ if (payload.agentKind !== 'codex') return;
+ // Never show the previous account while the new authoritative read settles.
+ requestVersionRef.current += 1;
+ setSnapshot(null);
+ refresh();
+ });
+
+ return () => {
+ requestVersionRef.current += 1;
+ unsubscribe?.();
+ };
+ }, [enabled, refresh]);
+
+ return { snapshot, refresh };
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 6322f3faba..daa97ecb82 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3174,6 +3174,8 @@
"balanceAvailable": "Balance available",
"balanceDepleted": "Balance depleted",
"balanceUnlimited": "Balance Unlimited",
+ "resetCreditsAvailableLine": "Available resets: {{count}}",
+ "resetCreditEarliestExpiryLine": "Earliest expiry: {{at}}",
"windowLine": "{{label}} {{remaining}} left ({{used}} used)",
"windowSegment": "{{label}} {{remaining}} left",
"resetAt": "resets {{at}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index bce137d1e4..91bf8ef782 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3173,6 +3173,8 @@
"balanceAvailable": "残高あり",
"balanceDepleted": "残高なし",
"balanceUnlimited": "残高無制限",
+ "resetCreditsAvailableLine": "利用可能なリセット:{{count}}回",
+ "resetCreditEarliestExpiryLine": "最も早い有効期限:{{at}}",
"windowLine": "{{label}} 残り {{remaining}} (使用済み {{used}})",
"windowSegment": "{{label}} 残り {{remaining}}",
"resetAt": "{{at}} にリセット",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 6ffcccbff3..2f57f62a08 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3173,6 +3173,8 @@
"balanceAvailable": "잔액 사용 가능",
"balanceDepleted": "잔액 소진",
"balanceUnlimited": "잔액 무제한",
+ "resetCreditsAvailableLine": "사용 가능한 재설정: {{count}}회",
+ "resetCreditEarliestExpiryLine": "가장 빠른 만료: {{at}}",
"windowLine": "{{label}} 남음 {{remaining}} (사용 {{used}})",
"windowSegment": "{{label}} {{remaining}} 남음",
"resetAt": "{{at}} 재설정",
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 4ef42b4daa..220cfc4c4a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3173,6 +3173,8 @@
"balanceAvailable": "余额可用",
"balanceDepleted": "余额已耗尽",
"balanceUnlimited": "余额不限",
+ "resetCreditsAvailableLine": "可用重置:{{count}} 次",
+ "resetCreditEarliestExpiryLine": "最早过期:{{at}}",
"windowLine": "{{label}} 剩余 {{remaining}} (已用 {{used}})",
"windowSegment": "{{label}} 剩余 {{remaining}}",
"resetAt": "{{at}} 重置",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 97dcd5b72d..9135c80767 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4326,6 +4326,10 @@ interface ElectronAPI {
cachedTokens?: number;
}>;
getAccount: (agentKind: 'claude-code' | 'codex') => Promise<unknown | null>;
+ /** Codex app-server authoritative windows and banked reset-credit metadata. */
+ getCodexRateLimits: () => Promise<
+ import('@cindy/maker-shared/device-link-contract').MobileCodexRateLimitsResult
+ >;
/** provider-scoped 模型单价表;XD 价格与 model-access /models 同快照更新。 */
getModelPricing: () => Promise<
import('../shared/regionalMoney').ModelPricingCatalog | null
diff --git a/packages/maker-shared/src/__tests__/sessionControls.test.ts b/packages/maker-shared/src/__tests__/sessionControls.test.ts
index 2c689670e6..d234ba1280 100644
--- a/packages/maker-shared/src/__tests__/sessionControls.test.ts
+++ b/packages/maker-shared/src/__tests__/sessionControls.test.ts
@@ -82,6 +82,10 @@ describe('summarizeCodexRateLimitReset', () => {
]);
expect(summary?.rows[3]).toMatchObject({ label: '最早过期' });
expect(summary?.rows[3].value).toMatch(/^\d{2}:\d{2}$/);
+ expect(summary).toMatchObject({
+ hasResetCreditCount: true,
+ earliestExpiryAt: base.resetOffer.expiresAt,
+ });
});
it('does not offer reset before exhaustion and leaves offer expiry to desktop', () => {
@@ -117,7 +121,13 @@ describe('summarizeCodexRateLimitReset', () => {
resetOffer: null,
}, NOW_MS);
- expect(summary).toMatchObject({ availableCount: 0, shouldPrompt: true, canReset: false });
+ expect(summary).toMatchObject({
+ availableCount: 0,
+ hasResetCreditCount: false,
+ earliestExpiryAt: null,
+ shouldPrompt: true,
+ canReset: false,
+ });
expect(summary?.rows).not.toContainEqual(expect.objectContaining({ label: '可用重置' }));
});
});
diff --git a/packages/maker-shared/src/sessionControls.ts b/packages/maker-shared/src/sessionControls.ts
index c3cae32272..92518e4eb6 100644
--- a/packages/maker-shared/src/sessionControls.ts
+++ b/packages/maker-shared/src/sessionControls.ts
@@ -141,9 +141,13 @@ export function summarizeAccountRateLimits(value: unknown, nowMs: number): {
return rows.length > 0 ? { rows } : null;
}
-/** Mobile presentation model for banked Codex reset credits and their bound account. */
+/** Shared reset-credit summary; `rows` preserves Mobile UI while neutral fields serve other surfaces. */
export interface CodexRateLimitResetSummary {
rows: Array<{ label: string; value: string }>;
+ /** Whether app-server returned reset-credit availability (including an explicit zero). */
+ hasResetCreditCount: boolean;
+ /** Earliest available reset-credit expiry, as Unix epoch seconds. */
+ earliestExpiryAt: number | null;
availableCount: number;
canReset: boolean;
shouldPrompt: boolean;
@@ -162,15 +166,16 @@ export function summarizeCodexRateLimitReset(
if (value.account.email) rows.push({ label: '账号', value: value.account.email });
if (value.account.accountId) rows.push({ label: 'Workspace', value: value.account.accountId });
+ const hasResetCreditCount = Boolean(value.rateLimitResetCredits);
const availableCount = Math.max(0, Math.floor(value.rateLimitResetCredits?.availableCount ?? 0));
- if (value.rateLimitResetCredits) {
+ if (hasResetCreditCount) {
rows.push({ label: '可用重置', value: `${availableCount} 次` });
}
- const earliestExpiry = value.resetOffer?.expiresAt ?? earliestCreditExpiry(
+ const earliestExpiryAt = value.resetOffer?.expiresAt ?? earliestCreditExpiry(
value.rateLimitResetCredits?.credits ?? null,
);
- const expiryText = formatRateLimitResetAt(earliestExpiry, nowMs);
+ const expiryText = formatRateLimitResetAt(earliestExpiryAt, nowMs);
if (expiryText) rows.push({ label: '最早过期', value: expiryText });
const snapshots = [
@@ -190,6 +195,8 @@ export function summarizeCodexRateLimitReset(
return {
rows,
+ hasResetCreditCount,
+ earliestExpiryAt,
availableCount,
shouldPrompt,
canReset: shouldPrompt