Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 赠送余额一次性告知与计费页订单记录 (#1450)
Chris Zhangc5f78514edd0
diff --git a/apps/desktop/src/renderer/__tests__/promotionalGrantNotice.test.tsx b/apps/desktop/src/renderer/__tests__/promotionalGrantNotice.test.tsxnew file mode 100644index 0000000000..18578c6794--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/promotionalGrantNotice.test.tsx@@ -0,0 +1,314 @@+// @vitest-environment jsdom++/**+ * 「赠送余额已到账」一次性告知的判定、账号隔离与已读记账。+ *+ * 回归的是开通后的静默:服务端在开通 Cindy AI 时发一笔限期赠送余额,而金额与有效期的唯一+ * 展示位是计费页(设置 → 用量和计费)——用户走不到那儿(供应商卡片 2026-07-20 刻意剥离了+ * 计费展示),于是可能到过期都不知道账上有钱。这张卡补的是「已经发生的事要告知一次」。+ *+ * 三条不能退的判据在这里各有用例:企业账号**不渲染**(不是灰置,也不该为它发请求)、+ * 拿不到明细就不出卡(宁可不提醒,也不印占位金额)、已读态按账号 + grant 记账(换账号后+ * 新账号自己那笔必须还能告知一次)。+ */++import { act, cleanup, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type {+ ModelAccessCreditUsage,+ ModelAccessPromotionalGrantUsage,+} from '../../shared/modelAccess';++class MemLocalStorage {+ private store = new Map<string, string>();+ getItem(k: string): string | null {+ return this.store.has(k) ? (this.store.get(k) as string) : null;+ }+ setItem(k: string, v: string): void {+ this.store.set(k, v);+ }+ removeItem(k: string): void {+ this.store.delete(k);+ }+ clear(): void {+ this.store.clear();+ }+}++const auth = vi.hoisted(() => ({+ mode: 'cloud' as 'signed-out' | 'local' | 'cloud',+ membershipKind: 'personal' as 'personal' | 'org' | null,+ dataOwnerId: 'account-a' as string | null,+}));++vi.mock('@/contexts/AuthContext', () => ({+ useAuth: () => ({+ mode: auth.mode,+ dataOwnerId: auth.dataOwnerId,+ user: auth.membershipKind ? { membershipKind: auth.membershipKind } : null,+ }),+}));++// CN 区固定:金额格式化要有确定的币种,否则断言随构建区域漂移。+vi.mock('../../shared/brandRegion', () => ({+ CURRENT_CINDY_REGION: 'cn',+ CURRENT_APP_ID: 'com.xd.cindycn',+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ i18n: { language: 'en', resolvedLanguage: 'en' },+ t: (key: string, opts?: Record<string, unknown>) =>+ opts ? `${key}:${JSON.stringify(opts)}` : key,+ }),+}));++const navigate = vi.fn();+vi.mock('react-router-dom', () => ({+ useNavigate: () => navigate,+}));++function grant(over: Partial<ModelAccessPromotionalGrantUsage> = {}): ModelAccessPromotionalGrantUsage {+ return {+ grantId: 'grant-1',+ displayName: 'New user grant',+ originalAmount: '20',+ usedAmount: '0',+ remainingAmount: '20',+ expiresAt: '2026-08-30T15:59:00.000Z',+ state: 'active',+ ...over,+ };+}++function usage(grants: ModelAccessPromotionalGrantUsage[]): ModelAccessCreditUsage {+ const pool = { remaining: '20', used: '0', total: '20' };+ return {+ available: '20',+ plan: pool,+ purchased: pool,+ promotional: pool,+ promotionalGrants: grants,+ promotionalGrantsComplete: true,+ promotionalGrantConsistency: 'OBSERVED',+ ledgerUpdatedAt: '2026-08-01T00:00:00.000Z',+ scale: 9,+ observedAt: '2026-08-01T00:00:00.000Z',+ };+}++const ledger = vi.hoisted(() => ({+ getCreditUsage: undefined as unknown as ReturnType<typeof vi.fn>,+}));++let storage: MemLocalStorage;++beforeEach(() => {+ vi.resetModules();+ navigate.mockClear();+ auth.mode = 'cloud';+ auth.membershipKind = 'personal';+ auth.dataOwnerId = 'account-a';+ ledger.getCreditUsage = vi.fn(async () => usage([grant()]));+ storage = new MemLocalStorage();+ stubWindow();+});++function stubWindow(): void {+ vi.stubGlobal('window', {+ ...globalThis.window,+ localStorage: storage,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ electronAPI: { billing: { getCreditUsage: ledger.getCreditUsage } },+ });+ vi.stubGlobal('localStorage', storage);+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++async function renderNotice(enabled = true): Promise<void> {+ const { PromotionalGrantNotice } = await import('@/components/onboarding/PromotionalGrantNotice');+ await act(async () => {+ render(<PromotionalGrantNotice enabled={enabled} />);+ });+}++function noticeText(): string {+ return screen.getByTestId('promotional-grant-notice').textContent ?? '';+}++describe('PromotionalGrantNotice', () => {+ it('个人云账号有一笔生效中赠送 → 告知出现,金额与有效期都来自那笔 grant', async () => {+ await renderNotice();++ const text = noticeText();+ expect(text).toContain('onboarding.promotionalGrant.title');+ // 金额走 formatBillingAmount(CN 区 = CNY),不是把服务端字符串直接印上去。+ expect(text).toContain('20.00');+ expect(text).toContain('2026');+ });++ it('企业账号不渲染,也不为它去拉账本', async () => {+ // org 账号在整个计费面上都是「不渲染」而非灰置(canAccessBillingSettings 同一判据);+ // 顺带保证不发无谓的请求 —— 服务端对 org 会直接拒。+ auth.membershipKind = 'org';+ await renderNotice();++ expect(screen.queryByTestId('promotional-grant-notice')).toBeNull();+ expect(ledger.getCreditUsage).not.toHaveBeenCalled();+ });++ it('本地模式 / 未登录不渲染', async () => {+ auth.mode = 'local';+ auth.membershipKind = null;+ await renderNotice();++ expect(screen.queryByTestId('promotional-grant-notice')).toBeNull();+ expect(ledger.getCreditUsage).not.toHaveBeenCalled();+ });++ it('device-link 草稿(enabled=false)不出现,也不拉账本', async () => {+ await renderNotice(false);++ expect(screen.queryByTestId('promotional-grant-notice')).toBeNull();+ expect(ledger.getCreditUsage).not.toHaveBeenCalled();+ });++ it('拿不到赠送明细 → 不出这张卡(不印占位金额)', async () => {+ ledger.getCreditUsage = vi.fn(async () => {+ throw new Error('BALANCE_NOT_SUPPORTED');+ });+ stubWindow();+ await renderNotice();++ expect(screen.queryByTestId('promotional-grant-notice')).toBeNull();+ });++ it('只有已用完 / 已过期 / 已作废的赠送 → 不出现', async () => {+ ledger.getCreditUsage = vi.fn(async () =>+ usage([+ grant({ grantId: 'g-depleted', state: 'depleted' }),+ grant({ grantId: 'g-expired', state: 'expired' }),+ grant({ grantId: 'g-voided', state: 'voided' }),+ ]),+ );+ stubWindow();+ await renderNotice();++ expect(screen.queryByTestId('promotional-grant-notice')).toBeNull();+ });++ it('有效期解析不出来的 grant 不命中 —— 卡上必须印得出具体日期', async () => {+ ledger.getCreditUsage = vi.fn(async () => usage([grant({ expiresAt: 'not-a-date' })]));+ stubWindow();+ await renderNotice();++ expect(screen.queryByTestId('promotional-grant-notice')).toBeNull();+ });++ it('多笔生效中时取有效期最晚的那笔', async () => {+ ledger.getCreditUsage = vi.fn(async () =>+ usage([+ grant({ grantId: 'g-early', originalAmount: '5', expiresAt: '2026-08-10T00:00:00.000Z' }),+ grant({ grantId: 'g-late', originalAmount: '30', expiresAt: '2026-09-20T00:00:00.000Z' }),+ ]),+ );+ stubWindow();+ await renderNotice();++ expect(noticeText()).toContain('30.00');+ });++ it('点「知道了」后写入已读,重新挂载不再出现', async () => {+ await renderNotice();++ await act(async () => {+ screen.getByText('onboarding.promotionalGrant.acknowledge').click();+ });+ expect(screen.queryByTestId('promotional-grant-notice')).toBeNull();++ // 冷启动重来(同一份 localStorage)→ 一次性告知不该回弹。+ cleanup();+ await renderNotice();+ expect(screen.queryByTestId('promotional-grant-notice')).toBeNull();+ });++ it('「查看用量」同时记已读并跳计费页 —— 否则回到首屏它还在', async () => {+ await renderNotice();++ await act(async () => {+ screen.getByText('onboarding.promotionalGrant.openBilling').click();+ });+ expect(navigate).toHaveBeenCalledWith('/settings?tab=billing');++ cleanup();+ await renderNotice();+ expect(screen.queryByTestId('promotional-grant-notice')).toBeNull();+ });++ it('已读态按账号隔离:换账号后同一 grantId 仍会告知一次', async () => {+ await renderNotice();+ await act(async () => {+ screen.getByText('onboarding.promotionalGrant.acknowledge').click();+ });+ expect(screen.queryByTestId('promotional-grant-notice')).toBeNull();++ // 同一台机器换账号登录:新账号自己那笔赠送必须还能被告知,否则漏告知且查不出来。+ cleanup();+ auth.dataOwnerId = 'account-b';+ await renderNotice();+ expect(screen.getByTestId('promotional-grant-notice')).toBeTruthy();+ });++ it('另一笔新 grant 仍会告知(按 grant 记账,不是按账号一刀切)', async () => {+ const { acknowledgePromotionalGrant } = await import('@/state/promotionalGrantNotice');+ acknowledgePromotionalGrant('account-a', 'grant-1');++ ledger.getCreditUsage = vi.fn(async () => usage([grant({ grantId: 'grant-2' })]));+ stubWindow();+ await renderNotice();++ expect(screen.getByTestId('promotional-grant-notice')).toBeTruthy();+ });++ it('最晚到期那笔已读时,更早到期的未读赠送仍会告知(未读过滤先于挑选)', async () => {+ // 场景:运营补发了一笔更晚到期的赠送、用户读过;更早那笔从未告知。+ // 若先挑「最晚一笔」再看已读,已读的最晚笔会把未读的早笔永远遮蔽掉。+ const { acknowledgePromotionalGrant } = await import('@/state/promotionalGrantNotice');+ acknowledgePromotionalGrant('account-a', 'grant-late');++ ledger.getCreditUsage = vi.fn(async () =>+ usage([+ grant({ grantId: 'grant-late', expiresAt: '2026-09-30T15:59:00.000Z', originalAmount: '50' }),+ grant({ grantId: 'grant-early', expiresAt: '2026-08-30T15:59:00.000Z', originalAmount: '20' }),+ ]),+ );+ stubWindow();+ await renderNotice();++ // 出的是未读的早笔(金额 20),不是已读的晚笔,也不是不出。+ expect(noticeText()).toContain('20.00');+ });++ it('localStorage 持续不可用时,同会话连续确认与跨账号确认都不丢(内存兜底做并集)', async () => {+ storage.setItem = () => {+ throw new Error('QuotaExceededError');+ };+ stubWindow();+ const state = await import('@/state/promotionalGrantNotice');++ state.acknowledgePromotionalGrant('account-a', 'grant-1');+ // 第二次确认(换了账号)不能把第一次的内存记录整份覆盖掉。+ state.acknowledgePromotionalGrant('account-b', 'grant-2');++ const snapshot = state.getAcknowledgedPromotionalGrants();+ expect(state.isPromotionalGrantAcknowledged(snapshot, 'account-a', 'grant-1')).toBe(true);+ expect(state.isPromotionalGrantAcknowledged(snapshot, 'account-b', 'grant-2')).toBe(true);+ });+});diff --git a/apps/desktop/src/renderer/components/onboarding/PromotionalGrantNotice.tsx b/apps/desktop/src/renderer/components/onboarding/PromotionalGrantNotice.tsxnew file mode 100644index 0000000000..4f2107e2e7--- /dev/null+++ b/apps/desktop/src/renderer/components/onboarding/PromotionalGrantNotice.tsx@@ -0,0 +1,115 @@+/**+ * PromotionalGrantNotice —— 「已为你开通 Cindy AI,赠送余额已到账」的一次性告知。+ *+ * 出现条件由 usePromotionalGrantNotice 判定(能看计费 && 账本里有一笔生效中的赠送 &&+ * 未读),挂载方只决定位置与 device-link gate。它与 InheritedSubscriptionNotice **不互斥**:+ * 两者都是告知,同时成立时竖排即可 —— 一条讲「用的是哪个账号」,一条讲「账上有多少钱」。+ *+ * 形态逐项照抄 InheritedSubscriptionNotice(12px 容器 / 1px Board 边 / Card 底 / p-16 /+ * 28px 圆角方图标 / 标题 14px-500 / 描述 13px / 两个 8px 圆角文字按钮),不造新形态:+ * 同一个位置上的同一类东西(读过即止的告知条)必须长得一样。+ *+ * 「查看用量」同时记已读:用户已经被带到计费页看过金额与有效期了,回到首屏再提醒一次+ * 是重复叙事(同 InheritedSubscriptionNotice 的 openProviders)。+ */++import { useNavigate } from 'react-router-dom';+import { useTranslation } from 'react-i18next';+import { ChevronRight, Gift } from 'lucide-react';++import { cn } from '@/lib/utils';+import { usePromotionalGrantNotice } from '@/hooks/usePromotionalGrantNotice';+import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';+import { formatBillingAmount } from '@/features/billing/money';++/**+ * 结算币种由运行区域决定,与计费页 BILLING_CURRENCY 同一口径 —— 金额一律走+ * formatBillingAmount 格式化,组件不硬编码任何数字或币种符号。+ */+const BILLING_CURRENCY = CURRENT_CINDY_REGION === 'global' ? 'usd' : 'cny';++export function PromotionalGrantNotice({+ className,+ enabled = true,+}: {+ className?: string;+ enabled?: boolean;+}) {+ const { t, i18n } = useTranslation();+ const navigate = useNavigate();+ const notice = usePromotionalGrantNotice(enabled);++ if (!notice.visible || !notice.grant) return null;++ const billingLocale = i18n.resolvedLanguage ?? i18n.language;+ const expiresAt = Date.parse(notice.grant.expiresAt);+ // 有效期解析不出来就不出这张卡(hook 已过滤,这里是渲染期的第二道闸):卡上必须印出+ // 具体日期,印不出来的告知不如不出。+ if (!Number.isFinite(expiresAt)) return null;++ let expiresAtLabel: string;+ try {+ expiresAtLabel = new Intl.DateTimeFormat(billingLocale, { dateStyle: 'medium' }).format(+ expiresAt,+ );+ } catch {+ return null;+ }++ return (+ <section+ data-testid="promotional-grant-notice"+ className={cn(+ 'flex w-full items-start gap-3 rounded-xl border border-[var(--border-default)]',+ 'bg-[var(--surface-elevated)] p-4',+ className,+ )}+ >+ <div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-[var(--model-item-hover)]">+ <Gift size={15} className="text-[var(--text-secondary)]" />+ </div>+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <span className="text-[14px] font-medium leading-snug text-[var(--text-primary)]">+ {t('onboarding.promotionalGrant.title')}+ </span>+ <span className="text-[13px] leading-relaxed text-[var(--text-secondary)]">+ {t('onboarding.promotionalGrant.desc', {+ amount: formatBillingAmount(+ notice.grant.originalAmount,+ BILLING_CURRENCY,+ billingLocale,+ ),+ date: expiresAtLabel,+ })}+ </span>+ <div className="mt-1.5 flex items-center gap-2">+ <button+ type="button"+ onClick={() => {+ notice.acknowledge();+ navigate('/settings?tab=billing');+ }}+ className={cn(+ 'flex items-center gap-0.5 rounded-[8px] px-2 py-1 -ml-2',+ 'text-[13px] font-medium text-[var(--text-primary)]',+ 'transition-colors hover:bg-[var(--model-item-hover)] active:scale-[0.98]',+ )}+ >+ {t('onboarding.promotionalGrant.openBilling')}+ <ChevronRight size={14} className="shrink-0 text-[var(--text-tertiary)]" />+ </button>+ <button+ type="button"+ onClick={notice.acknowledge}+ className={cn(+ 'rounded-[8px] px-2 py-1 text-[13px] font-normal text-[var(--text-secondary)]',+ 'transition-colors hover:bg-[var(--model-item-hover)] active:scale-[0.98]',+ )}+ >+ {t('onboarding.promotionalGrant.acknowledge')}+ </button>+ </div>+ </div>+ </section>+ );+}diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsxindex e369a8fc36..822c3edd31 100644--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx@@ -31,6 +31,7 @@ import type {BillingCatalogOffer,BillingCatalogOfferUnavailableReason,BillingCatalogProduct,+ BillingPaymentOrder,BillingPendingPlanChange,BillingPurchaseOption,BillingSubscription,@@ -51,7 +52,7 @@ import {PlanChangeTargetDialog,type PlanChangeCandidate,} from './PlanChangeDialog';-import { useBillingCheckout } from './useBillingCheckout';+import { phaseForOrder, useBillingCheckout } from './useBillingCheckout';import { usePlanChange, type PlanChangeSettledKind } from './usePlanChange';type CatalogOfferEntry = {@@ -99,6 +100,46 @@ const SUBSCRIPTION_CANCELLABLE_STATUSES = SUBSCRIPTION_PURCHASE_BLOCKING_STATUSEconst PLAN_CHANGE_ENTRY_STATUSES: BillingSubscription['status'][] = ['ACTIVE'];+/**+ * 订单记录默认只列最近 10 笔。这一组回答的是「上次充了多少、那笔没付成的还在不在」,+ * 不是账目导出 —— 更早的记录没有分页器可翻,服务端还有下一页时只用一条提示条说明。+ */+const ORDER_HISTORY_LIMIT = 10;++/**+ * 订单状态 chip 的文案 key。刻意复用 checkout 的 `phaseForOrder` 而不是自己再写一套+ * status→文案映射:同一个 `CREATED`,支付弹窗说「等待支付」、列表说别的,是用户直接+ * 可见的不一致。两处必须由同一个判据推导。+ */+function orderStatusLabelKey(order: BillingPaymentOrder): string {+ switch (phaseForOrder(order)) {+ case 'COMPLETED':+ return 'billing.orders.states.completed';+ case 'CANCELED':+ return 'billing.orders.states.canceled';+ case 'EXPIRED':+ return 'billing.orders.states.expired';+ case 'FAILED':+ return 'billing.orders.states.failed';+ default:+ // phaseForOrder 对未终态一律返 AWAITING_PAYMENT(CREATED / PENDING)。+ return 'billing.orders.states.awaitingPayment';+ }+}++/** 「待支付」是这组里唯一可能还需要用户处理的状态,给它主文本色;其余保持二级色。 */+function isAwaitingPaymentOrder(order: BillingPaymentOrder): boolean {+ return phaseForOrder(order) === 'AWAITING_PAYMENT';+}++/**+ * 订单号在界面上只做「认得出是哪一单」用,全长展示会把左列挤没 —— 截断展示、完整值+ * 挂 title。截断取头部:服务端订单号带随机前缀,头 8 位已足够区分。+ */+function shortOrderId(orderId: string): string {+ return orderId.length > 8 ? orderId.slice(0, 8) : orderId;+}+function decimalParts(value: string): { value: bigint; scale: number } | null {const match = /^(0|[1-9]\d{0,14})(?:\.(\d{1,9}))?$/.exec(value.trim());if (!match) return null;@@ -248,6 +289,10 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullconst [usageDetailsUnavailable, setUsageDetailsUnavailable] = useState(false);const [loadingBalance, setLoadingBalance] = useState(true);const [balanceError, setBalanceError] = useState<BalanceIssue>(null);+ // 订单记录按账号天然隔离:BillingPage 用 `billing:<dataOwnerId>` 做 key,换账号会整段+ // 重挂,这份 state 连同缓存一起重建,不会把上一个账号的订单渲染给新账号。+ const [orders, setOrders] = useState<BillingPaymentOrder[]>([]);+ const [moreOrdersAvailable, setMoreOrdersAvailable] = useState(false);const [subscriptionDialogOpen, setSubscriptionDialogOpen] = useState(false);const [topupDialogOpen, setTopupDialogOpen] = useState(false);const [planChangeTargetOpen, setPlanChangeTargetOpen] = useState(false);@@ -304,6 +349,20 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null}}, []);+ const loadOrders = useCallback(async () => {+ try {+ const list = await billingApi.listOrders(ORDER_HISTORY_LIMIT);+ setOrders(list.orders);+ // nextCursor 是「服务端还有更早的记录」的唯一实证;这一组不做分页器,只据此出提示条。+ setMoreOrdersAvailable(list.nextCursor !== null);+ } catch {+ // 订单记录是补充叙事(钱是怎么来的),拿不到就整组不渲染 —— 余额 / 用量 / 赠送+ // 三组都不受影响,也不为它加一个空错误壳占版面。+ setOrders([]);+ setMoreOrdersAvailable(false);+ }+ }, []);+const loadSubscription = useCallback(async (fallback: BillingSubscription | null = null) => {setLoadingSubscription(true);setSubscriptionError(false);@@ -339,8 +398,11 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null.finally(() => setLoadingCatalog(false)),loadSubscription(),loadBalance(),+ // 进页面拉一次,「刷新」也跟着重拉;不加轮询 —— 订单只在用户自己发起支付时变化,+ // 而那条路径由 checkout 弹窗自己轮询。+ loadOrders(),]);- }, [loadBalance, loadSubscription]);+ }, [loadBalance, loadOrders, loadSubscription]);useEffect(() => {void loadBillingState();@@ -370,11 +432,27 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullsetCurrentSubscription(null);void loadSubscription();}- }, [checkout, loadSubscription]);+ // 关弹窗也刷一次订单:用户可能在 AWAITING_PAYMENT 中途放弃 —— 那笔「待支付」+ // 此刻就该出现在订单记录里,而不是等他手动点「刷新」才知道它还挂着。+ void loadOrders();+ }, [checkout, loadOrders, loadSubscription]);useEffect(() => {const previousPhase = previousCheckoutPhaseRef.current;previousCheckoutPhaseRef.current = checkout.state.phase;+ if (previousPhase === checkout.state.phase) return;+ // 订单记录跟着订单生命周期的每一次落位刷新,不只 COMPLETED:订单一创建(进入+ // AWAITING_PAYMENT)就已经是一条「待支付」记录;轮询落到 FAILED / EXPIRED /+ // CANCELED 时列表里那行的状态也变了。只刷 COMPLETED 会让其余终态全靠手动刷新。+ if (+ checkout.state.phase === 'AWAITING_PAYMENT' ||+ checkout.state.phase === 'COMPLETED' ||+ checkout.state.phase === 'FAILED' ||+ checkout.state.phase === 'EXPIRED' ||+ checkout.state.phase === 'CANCELED'+ ) {+ void loadOrders();+ }if (previousPhase !== 'COMPLETED' && checkout.state.phase === 'COMPLETED') {void loadBalance();if (checkout.state.kind === 'SUBSCRIPTION') {@@ -386,6 +464,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullcheckout.state.phase,checkout.state.subscription,loadBalance,+ loadOrders,loadSubscription,]);@@ -873,6 +952,22 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null<PromotionalGrantsCard usage={creditUsage} /></BillingGroup>)}++ {/* 空态(没有任何订单 / 拉不到)整组不渲染:页面保持现状,不加空壳 —— 从没在+ Cindy 内付过钱的用户不需要一个写着「暂无订单」的框告诉他这件事。 */}+ {orders.length > 0 && (+ <BillingGroup+ title={t('billing.orders.title')}+ description={t('billing.orders.description')}+ badge={+ <span className="shrink-0 rounded-full bg-[var(--surface-chip)] px-2.5 py-1 text-10 font-medium text-[var(--text-secondary)]">+ {t('billing.orders.count', { count: orders.length })}+ </span>+ }+ >+ <OrderHistoryCard orders={orders} hasMore={moreOrdersAvailable} />+ </BillingGroup>+ )}</div></div>@@ -1457,6 +1552,93 @@ function PromotionalGrantStatus({ state }: { state: ModelAccessPromotionalGrantS);}+/**+ * 订单记录卡。行结构与 PromotionalGrantsCard 同一套(12px 容器 + 1px 分隔行 + 左列双行+ * 加右侧数列),因为它们在同一页里是同一类东西:一条条只读流水。+ */+function OrderHistoryCard({+ orders,+ hasMore,+}: {+ orders: readonly BillingPaymentOrder[];+ hasMore: boolean;+}) {+ const { t, i18n } = useTranslation();+ const billingLocale = i18n.resolvedLanguage ?? i18n.language;+ /**+ * 支付方式只有在服务端还带着本单的支付动作时才知道 —— 订单投影(shared/billing.ts 的+ * BillingPaymentOrder)里没有收单渠道字段,终态订单通常也不再带 paymentAction。整批都+ * 拿不到时**整列不出**,免得留下一列破折号;有一单拿得到就保留该列并给缺的那些占位。+ */+ const showPaymentMethod = orders.some((order) => order.paymentAction !== null);+ return (+ <section className="overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]">+ {hasMore && (+ <p className="border-b border-[var(--border-default)] px-5 py-3 text-11 leading-4 text-[var(--text-tertiary)]">+ {t('billing.orders.incomplete', { count: orders.length })}+ </p>+ )}+ {/* 不像赠送明细那样封高 + 内滚:那边的行数由服务端历史决定(可达上百条),这边行数+ 由 ORDER_HISTORY_LIMIT 封死在 10,再套一层内滚只会凭空造出嵌套滚动区。 */}+ <div className="divide-y divide-[var(--border-default)]" role="list">+ {orders.map((order) => (+ <div+ key={order.orderId}+ role="listitem"+ className={cn(+ 'grid gap-x-3 gap-y-2 px-5 py-3.5 lg:items-center',+ showPaymentMethod+ ? 'grid-cols-3 lg:grid-cols-[minmax(0,1.4fr)_minmax(80px,0.7fr)_minmax(80px,0.8fr)_minmax(76px,0.6fr)]'+ : 'grid-cols-2 lg:grid-cols-[minmax(0,1.4fr)_minmax(80px,0.7fr)_minmax(76px,0.6fr)]',+ )}+ >+ <div+ className={cn(+ 'min-w-0 lg:col-span-1',+ showPaymentMethod ? 'col-span-3' : 'col-span-2',+ )}+ >+ <p className="truncate text-12 font-medium tabular-nums text-[var(--text-primary)]">+ {formatLedgerTimestamp(order.createdAt, billingLocale)}+ </p>+ {/* 订单号只用来对单,截断展示、完整值挂 title(客服场景要能复制全长)。 */}+ <p+ title={order.orderId}+ className="mt-1 truncate font-mono text-10 text-[var(--text-tertiary)]"+ >+ {t('billing.orders.orderId', { id: shortOrderId(order.orderId) })}+ </p>+ </div>+ <p className="min-w-0 truncate text-right text-12 font-medium tabular-nums text-[var(--text-primary)]">+ {formatMoney(order.amount, order.currency, billingLocale)}+ </p>+ {showPaymentMethod && (+ <p className="min-w-0 truncate text-11 text-[var(--text-secondary)]">+ {order.paymentAction+ ? t(`billing.paymentActions.${order.paymentAction.type}`)+ : '—'}+ </p>+ )}+ <div className="flex min-w-0 justify-end">+ <span+ className={cn(+ 'shrink-0 whitespace-nowrap rounded-full bg-[var(--surface-chip)] px-2.5 py-1',+ 'text-10 font-medium leading-[1.2]',+ isAwaitingPaymentOrder(order)+ ? 'text-[var(--text-primary)]'+ : 'text-[var(--text-secondary)]',+ )}+ >+ {t(orderStatusLabelKey(order))}+ </span>+ </div>+ </div>+ ))}+ </div>+ </section>+ );+}+function GrantAmount({ label, amount }: { label: string; amount: string }) {const { i18n } = useTranslation();const billingLocale = i18n.resolvedLanguage ?? i18n.language;diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsxindex 8f4e7e483e..f870f2ee34 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx@@ -3,6 +3,7 @@import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import type {+ BillingPaymentOrder,BillingSubscription,BillingSubscriptionPortalResult,} from '../../../../shared/billing';@@ -23,7 +24,7 @@ const authState = vi.hoisted(() => ({ dataOwnerId: 'account-fixture' as string |const checkout = {state: {open: false,- kind: null,+ kind: null as 'CREDIT_TOPUP' | 'SUBSCRIPTION' | null,phase: 'IDLE',intent: null,order: null,@@ -71,7 +72,10 @@ vi.mock('@/lib/toast', () => ({success: uiMocks.toastSuccess,},}));-vi.mock('../useBillingCheckout', () => ({+// 只替换 hook 本身:同模块的 phaseForOrder 是纯函数,订单记录的状态文案刻意复用它+// (支付弹窗与列表必须由同一个判据推导),整模块 mock 掉会把那条依赖一起挖空。+vi.mock('../useBillingCheckout', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../useBillingCheckout')>()),useBillingCheckout: () => checkout,}));vi.mock('qrcode', () => ({@@ -361,6 +365,7 @@ describe('BillingPage remote catalog rendering', () => {],})),getCurrentSubscription: vi.fn(async () => ({ subscription: null })),+ listOrders: vi.fn(async () => ({ orders: [], nextCursor: null })),openPaymentRedirect: vi.fn(async () => ({ success: true })),},openExternal: vi.fn(),@@ -1373,6 +1378,7 @@ describe('BillingPage plan change', () => {subscription: activeSubscription(),}),),+ listOrders: vi.fn(async () => ({ orders: [], nextCursor: null })),cancelCurrentSubscription: vi.fn(),quotePlanChange: vi.fn(),confirmPlanChange: vi.fn(),@@ -2110,3 +2116,201 @@ describe('BillingPage plan change', () => {expect(billing.refreshPlanChange).not.toHaveBeenCalled();});});++/**+ * 订单记录组。回归的是「页面只讲现在还有多少,不讲钱是怎么来的」——用户查不到上次充了多少、+ * 那笔没付成的还在不在。三条判据在这里各有用例:空态整组不渲染(不加空壳)、状态文案与支付+ * 弹窗同一判据(phaseForOrder)、服务端还有下一页时只出提示条不出分页器。+ */+describe('BillingPage order history', () => {+ const order = (over: Partial<BillingPaymentOrder> = {}): BillingPaymentOrder => ({+ orderId: 'ord_8f21c4de9a',+ productCode: 'credit_topup',+ offerCode: 'credit_topup_custom',+ // 刻意与余额 / 赠送池的数字不同:同一页里重复的金额会让断言抓错节点。+ amount: '33',+ currency: 'cny',+ status: 'SUCCEEDED',+ paymentAction: null,+ createdAt: '2026-08-01T13:07:00.000Z',+ updatedAt: '2026-08-01T13:09:00.000Z',+ ...over,+ });++ const install = (+ orders: BillingPaymentOrder[],+ nextCursor: string | null = null,+ ): ReturnType<typeof vi.fn> => {+ const listOrders = vi.fn(async () => ({ orders, nextCursor }));+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ billing: {+ getCreditUsage: vi.fn(async () => ({+ available: '20',+ plan: { remaining: '0', used: '0', total: '0' },+ purchased: { remaining: '0', used: '0', total: '0' },+ promotional: { remaining: '20', used: '0', total: '20' },+ promotionalGrants: [],+ promotionalGrantsComplete: true,+ promotionalGrantConsistency: 'OBSERVED' as const,+ ledgerUpdatedAt: null,+ scale: 9 as const,+ observedAt: '2026-08-01T00:00:00.000Z',+ })),+ getBalance: vi.fn(),+ getCatalog: vi.fn(async () => ({ products: [] })),+ getCurrentSubscription: vi.fn(async () => ({ subscription: null })),+ listOrders,+ openPaymentRedirect: vi.fn(async () => ({ success: true })),+ },+ openExternal: vi.fn(),+ },+ });+ return listOrders;+ };++ it('lists the most recent orders with amount, id and status', async () => {+ install([order()]);++ render(<BillingPage />);++ expect(await screen.findByText('billing.orders.title')).toBeTruthy();+ expect(screen.getByText('billing.orders.count:{"count":1}')).toBeTruthy();+ expect(screen.getByText('billing.orders.description')).toBeTruthy();+ // 订单号截断展示、完整值挂 title(客服场景要能复制全长)。+ expect(screen.getByText('billing.orders.orderId:{"id":"ord_8f21"}').title).toBe(+ 'ord_8f21c4de9a',+ );+ expect(+ screen.getByText(new Intl.NumberFormat('en', { style: 'currency', currency: 'CNY' }).format(33)),+ ).toBeTruthy();+ expect(screen.getByText('billing.orders.states.completed')).toBeTruthy();+ });++ it('asks the server for exactly the ten most recent orders', async () => {+ const listOrders = install([order()]);++ render(<BillingPage />);+ await screen.findByText('billing.orders.title');+ expect(listOrders).toHaveBeenCalledWith({ limit: 10 });+ });++ it('renders no group at all when there are no orders — the page keeps its current shape', async () => {+ install([]);++ render(<BillingPage />);+ // 等页面其余部分落地,再断言这一组确实没渲染(不是还没到)。+ await screen.findByText('billing.usage.promotionalDetails.title');+ expect(screen.queryByText('billing.orders.title')).toBeNull();+ });++ it('renders no group when the order list cannot be fetched', async () => {+ install([]);+ window.electronAPI.billing.listOrders = vi.fn(async () => {+ throw new Error('UNAVAILABLE');+ });++ render(<BillingPage />);+ await screen.findByText('billing.usage.promotionalDetails.title');+ expect(screen.queryByText('billing.orders.title')).toBeNull();+ });++ it('reloads the order history on every checkout phase landing, not only COMPLETED', async () => {+ const listOrders = install([order()]);+ const initialState = { ...checkout.state };++ const { rerender } = render(<BillingPage />);+ await screen.findByText('billing.orders.title');+ const baseline = listOrders.mock.calls.length;++ // 订单一创建(AWAITING_PAYMENT)就已经是一条「待支付」记录,列表必须立刻能看到。+ checkout.state = {+ ...initialState,+ open: true,+ kind: 'CREDIT_TOPUP',+ phase: 'AWAITING_PAYMENT',+ };+ rerender(<BillingPage />);+ await waitFor(() => expect(listOrders.mock.calls.length).toBe(baseline + 1));++ // 轮询落到失败终态时,那一行的状态 chip 也变了 —— 不能等用户手动刷新。+ checkout.state = { ...checkout.state, phase: 'FAILED' };+ rerender(<BillingPage />);+ await waitFor(() => expect(listOrders.mock.calls.length).toBe(baseline + 2));++ // 同一相位重复渲染不重拉:effect 只认「相位变化」,不是每次 render 都打接口。+ rerender(<BillingPage />);+ await screen.findByText('billing.orders.title');+ expect(listOrders.mock.calls.length).toBe(baseline + 2);++ checkout.state = initialState;+ });++ it('maps every payment status onto the checkout wording, not a second vocabulary', async () => {+ install([+ order({ orderId: 'o-succeeded', status: 'SUCCEEDED' }),+ order({ orderId: 'o-created', status: 'CREATED' }),+ order({ orderId: 'o-pending', status: 'PENDING' }),+ order({ orderId: 'o-canceled', status: 'CANCELED' }),+ order({ orderId: 'o-expired', status: 'EXPIRED' }),+ order({ orderId: 'o-failed', status: 'FAILED' }),+ ]);++ render(<BillingPage />);+ await screen.findByText('billing.orders.title');++ expect(screen.getByText('billing.orders.states.completed')).toBeTruthy();+ // CREATED 与 PENDING 都是「还没付成」,与 checkout 的 phaseForOrder 同一判据。+ expect(screen.getAllByText('billing.orders.states.awaitingPayment')).toHaveLength(2);+ expect(screen.getByText('billing.orders.states.canceled')).toBeTruthy();+ expect(screen.getByText('billing.orders.states.expired')).toBeTruthy();+ expect(screen.getByText('billing.orders.states.failed')).toBeTruthy();+ });++ it('drops the payment-method column when no order still carries a payment action', async () => {+ // 终态订单通常不再带 paymentAction;整批都没有时留一列破折号比不留更糟。+ install([order({ paymentAction: null })]);++ render(<BillingPage />);+ await screen.findByText('billing.orders.title');+ expect(screen.queryByText('billing.paymentActions.QR_CODE')).toBeNull();+ expect(screen.queryByText('—')).toBeNull();+ });++ it('keeps the payment-method column when at least one order carries a payment action', async () => {+ install([+ order({+ orderId: 'o-open',+ status: 'CREATED',+ paymentAction: {+ type: 'QR_CODE',+ value: 'https://example.invalid/qr',+ expiresAt: '2026-08-01T14:07:00.000Z',+ },+ }),+ order({ orderId: 'o-done' }),+ ]);++ render(<BillingPage />);+ await screen.findByText('billing.orders.title');+ expect(screen.getByText('billing.paymentActions.QR_CODE')).toBeTruthy();+ // 缺支付方式的那一单占位,不把列整掉。+ expect(screen.getByText('—')).toBeTruthy();+ });++ it('explains truncation instead of offering a pager when the server has older records', async () => {+ install([order()], 'cursor-2');++ render(<BillingPage />);+ expect(await screen.findByText('billing.orders.incomplete:{"count":1}')).toBeTruthy();+ });++ it('does not explain truncation when the server has nothing older', async () => {+ install([order()]);++ render(<BillingPage />);+ await screen.findByText('billing.orders.title');+ expect(screen.queryByText('billing.orders.incomplete:{"count":1}')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex fc8c9c5ffb..4f5429570b 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -61,6 +61,7 @@ import { useSelectableDevices } from '@/hooks/useControllableDevices';import { useProviderOnboarding } from '@/hooks/useProviderOnboarding';import { ConnectProviderCard } from '@/components/onboarding/ConnectProviderCard';import { InheritedSubscriptionNotice } from '@/components/onboarding/InheritedSubscriptionNotice';+import { PromotionalGrantNotice } from '@/components/onboarding/PromotionalGrantNotice';import { resolveDeviceLinkSubmission } from './deviceLinkCreateArgs';import { commitRemoteSessionHandoff } from './remoteSessionHandoff';import { AgentSelect } from '@/components/new-chat/AgentSelect';@@ -3736,6 +3737,14 @@ export function NewMakerDraftRoute() {enabled={!isDeviceLinkDraft}className="mt-6 self-stretch"/>+ {/* 「赠送余额已到账」一次性告知。与上面那条**不互斥**:两者都是告知,同时成立+ 时按发生顺序竖排(先讲用的是哪个账号,再讲账上有多少钱),都不与快速开始+ 互斥。device-link 草稿不出:那条对话跑在被控端,本机账号的赠送与它无关。+ 间距同样挂在组件自身,免得它不可见时留下一段空白 margin。 */}+ <PromotionalGrantNotice+ enabled={!isDeviceLinkDraft}+ className="mt-6 self-stretch"+ />{/* 快捷入口与输入框同宽:左右两缘都与上方 ChatInput 对齐(父列已封顶inputWidth)。此前封顶 800px 会在宽窗口下右缘短一截,视觉上没对齐(2026-07-24 用户反馈)。 */}diff --git a/apps/desktop/src/renderer/hooks/usePromotionalGrantNotice.ts b/apps/desktop/src/renderer/hooks/usePromotionalGrantNotice.tsnew file mode 100644index 0000000000..8b0b7aac81--- /dev/null+++ b/apps/desktop/src/renderer/hooks/usePromotionalGrantNotice.ts@@ -0,0 +1,109 @@+/**+ * usePromotionalGrantNotice —— 判定「开通 Cindy AI 后到账的那笔赠送余额该不该告知一次」,+ * 并把它做成一条一次性告知。+ *+ * 补的缺口:赠送余额是服务端在开通时自动发的一笔限期余额,客户端此前完全静默 —— 金额与+ * 有效期的唯一展示位是计费页(设置 → 用量和计费),而用户走不到那儿(供应商卡片 2026-07-20+ * 刻意剥离了计费展示)。结果是用户可能到过期都不知道账上有钱。+ *+ * 判定用四个条件,缺一不可:+ * 1. 调用方 gate(device-link 草稿等场景传 false);+ * 2. 当前身份能看计费(`canAccessBillingSettings` —— 企业账号是**不渲染**,不是灰置);+ * 3. 账本里确实有一笔生效中的赠送(`state === 'active'`),金额与有效期都取自它;+ * 4. 这笔赠送对这个账号还没被告知过。+ *+ * 第 3 条是硬要求:拿不到明细(租户不提供该查询 / 未开户 / 请求失败,hook 一律返 null)时+ * **不出这张卡** —— 告知的全部价值就是那两个具体数字,拿金额占位符去提醒用户比不提醒更糟。+ *+ * 「生效中」有多笔时取有效期最晚的那笔:新用户只有一笔,而多笔时最晚到期的那笔才是用户接下来+ * 真正会花到的钱;并列时按 grantId 定序,免得同一份数据在两次渲染里挑出不同的 grant。+ */++import { useMemo, useSyncExternalStore } from 'react';++import { canAccessBillingSettings } from '@/components/settings/billingVisibility';+import { useAuth } from '@/contexts/AuthContext';+import { useModelAccessCreditUsage } from '@/hooks/useModelAccessCreditUsage';+import type { ModelAccessPromotionalGrantUsage } from '../../shared/modelAccess';+import {+ acknowledgePromotionalGrant,+ getAcknowledgedPromotionalGrants,+ isPromotionalGrantAcknowledged,+ subscribePromotionalGrantNotice,+} from '@/state/promotionalGrantNotice';++export interface UsePromotionalGrantNoticeReturn {+ /** 是否该展示告知(有一笔未读的生效中赠送)。 */+ visible: boolean;+ /** 命中的那笔赠送(金额与有效期的来源);不可见时为 null。 */+ grant: ModelAccessPromotionalGrantUsage | null;+ /** 标记已读(一次性,不再出现)。 */+ acknowledge: () => void;+}++/**+ * 生效中、**且尚未告知过**的赠送里有效期最晚的那笔;并列按 grantId 定序保证结果稳定。+ *+ * 「未读」过滤必须发生在挑选**之前**:若先挑最晚一笔再看它读没读,一笔已读的最晚+ * 赠送会遮蔽其它仍未读的生效赠送(例如运营补发了一笔更晚到期的、用户读过,而更早+ * 那笔从未告知)——那些赠送就永远失去了唯一的告知机会。+ */+function activeUnacknowledgedGrantOf(+ grants: readonly ModelAccessPromotionalGrantUsage[],+ acknowledgedSnapshot: string,+ accountId: string,+): ModelAccessPromotionalGrantUsage | null {+ let best: ModelAccessPromotionalGrantUsage | null = null;+ let bestExpiry = Number.NEGATIVE_INFINITY;+ for (const grant of grants) {+ if (grant.state !== 'active') continue;+ // 解析不出有效期的行直接跳过:卡上要印这个日期,印不出来的不该命中。+ const expiry = Date.parse(grant.expiresAt);+ if (!Number.isFinite(expiry)) continue;+ if (isPromotionalGrantAcknowledged(acknowledgedSnapshot, accountId, grant.grantId)) continue;+ if (best === null || expiry > bestExpiry || (expiry === bestExpiry && grant.grantId > best.grantId)) {+ best = grant;+ bestExpiry = expiry;+ }+ }+ return best;+}++/**+ * @param enabled 调用方 gate(device-link 草稿传 false:那条对话跑在被控端,本机账号的+ * 赠送余额与它无关)。false 时连账本都不拉。+ */+export function usePromotionalGrantNotice(enabled = true): UsePromotionalGrantNoticeReturn {+ const { mode, user, dataOwnerId } = useAuth();+ const billingVisible = canAccessBillingSettings({+ mode,+ membershipKind: user?.membershipKind ?? null,+ });+ // 账本请求跟着 gate 走:企业账号 / 未登录 / device-link 草稿一律不发请求。+ const creditUsage = useModelAccessCreditUsage(enabled && billingVisible);++ const acknowledgedSnapshot = useSyncExternalStore(+ subscribePromotionalGrantNotice,+ getAcknowledgedPromotionalGrants,+ );++ const grant = useMemo(() => {+ if (!enabled || !billingVisible || !dataOwnerId || !creditUsage) return null;+ return activeUnacknowledgedGrantOf(+ creditUsage.promotionalGrants,+ acknowledgedSnapshot,+ dataOwnerId,+ );+ }, [enabled, billingVisible, dataOwnerId, creditUsage, acknowledgedSnapshot]);++ const acknowledge = useMemo(() => {+ const accountId = dataOwnerId;+ const grantId = grant?.grantId;+ return () => {+ if (!accountId || !grantId) return;+ acknowledgePromotionalGrant(accountId, grantId);+ };+ }, [dataOwnerId, grant?.grantId]);++ return { visible: grant !== null, grant, acknowledge };+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex c8ef888386..48d534ee0e 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5329,6 +5329,12 @@"openProviders": "Open Model Providers","acknowledge": "Got it","separator": ", "+ },+ "promotionalGrant": {+ "title": "Cindy AI is ready",+ "desc": "A promotional balance of {{amount}} has been added and is valid until {{date}}. You can add funds any time after it runs out or expires.",+ "openBilling": "View usage",+ "acknowledge": "Got it"}},"voiceInputOverlay": {@@ -8604,6 +8610,20 @@}}},+ "orders": {+ "title": "Order history",+ "description": "Only top-up and subscription orders started inside Cindy are listed. Orders awaiting payment are canceled automatically once they time out.",+ "count": "{{count}} orders",+ "incomplete": "There are many order records. Only the latest {{count}} are shown.",+ "orderId": "NO. {{id}}",+ "states": {+ "completed": "Completed",+ "awaitingPayment": "Awaiting payment",+ "canceled": "Canceled",+ "expired": "Expired",+ "failed": "Payment failed"+ }+ },"dialogs": {"subscription": {"title": "Choose a subscription plan"diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex cfa5b3509b..c76756c3b4 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5327,6 +5327,12 @@"openProviders": "モデルプロバイダーを開く","acknowledge": "了解","separator": "、"+ },+ "promotionalGrant": {+ "title": "Cindy AI の利用を開始しました",+ "desc": "特典残高 {{amount}} を付与しました。有効期限は {{date}} です。使い切った後や期限切れの後も、いつでもチャージできます。",+ "openBilling": "使用量を見る",+ "acknowledge": "了解"}},"voiceInputOverlay": {@@ -8591,6 +8597,20 @@}}},+ "orders": {+ "title": "注文履歴",+ "description": "Cindy 内で開始した残高チャージとサブスクリプションの注文のみを表示します。支払い待ちの注文は、期限を過ぎると自動的にキャンセルされます。",+ "count": "{{count}}件",+ "incomplete": "注文履歴が多いため、最新の{{count}}件のみ表示しています。",+ "orderId": "NO. {{id}}",+ "states": {+ "completed": "完了",+ "awaitingPayment": "支払い待ち",+ "canceled": "キャンセル済み",+ "expired": "期限切れ",+ "failed": "支払い失敗"+ }+ },"dialogs": {"subscription": {"title": "サブスクリプションプランを選択"diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 9cf334f73a..41a0d80b44 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5327,6 +5327,12 @@"openProviders": "모델 제공자 열기","acknowledge": "확인","separator": ", "+ },+ "promotionalGrant": {+ "title": "Cindy AI 사용이 시작되었습니다",+ "desc": "프로모션 잔액 {{amount}}이 지급되었으며 {{date}}까지 사용할 수 있습니다. 모두 사용하거나 기간이 지난 뒤에도 언제든 충전할 수 있습니다.",+ "openBilling": "사용량 보기",+ "acknowledge": "확인"}},"voiceInputOverlay": {@@ -8591,6 +8597,20 @@}}},+ "orders": {+ "title": "주문 내역",+ "description": "Cindy에서 시작한 잔액 충전 및 구독 주문만 표시합니다. 결제 대기 중인 주문은 시간이 지나면 자동으로 취소됩니다.",+ "count": "{{count}}건",+ "incomplete": "주문 내역이 많아 최근 {{count}}건만 표시합니다.",+ "orderId": "NO. {{id}}",+ "states": {+ "completed": "완료",+ "awaitingPayment": "결제 대기",+ "canceled": "취소됨",+ "expired": "만료됨",+ "failed": "결제 실패"+ }+ },"dialogs": {"subscription": {"title": "구독 요금제 선택"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex ddb07e4e22..ea950d5d6d 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5327,6 +5327,12 @@"openProviders": "打开模型供应商","acknowledge": "知道了","separator": "、"+ },+ "promotionalGrant": {+ "title": "已为你开通 Cindy AI",+ "desc": "赠送余额 {{amount}} 已到账,有效期至 {{date}}。用完或过期后可随时充值。",+ "openBilling": "查看用量",+ "acknowledge": "知道了"}},"voiceInputOverlay": {@@ -8591,6 +8597,20 @@}}},+ "orders": {+ "title": "订单记录",+ "description": "仅显示在 Cindy 内发起的充值与订阅订单。待支付订单超时后自动取消。",+ "count": "{{count}} 笔",+ "incomplete": "订单记录较多,当前仅显示最近的 {{count}} 笔。",+ "orderId": "NO. {{id}}",+ "states": {+ "completed": "已完成",+ "awaitingPayment": "待支付",+ "canceled": "已取消",+ "expired": "已过期",+ "failed": "支付失败"+ }+ },"dialogs": {"subscription": {"title": "选择订阅套餐"diff --git a/apps/desktop/src/renderer/state/promotionalGrantNotice.ts b/apps/desktop/src/renderer/state/promotionalGrantNotice.tsnew file mode 100644index 0000000000..7f1e442e3f--- /dev/null+++ b/apps/desktop/src/renderer/state/promotionalGrantNotice.ts@@ -0,0 +1,113 @@+/**+ * promotionalGrantNotice —— 「赠送余额已到账」这条一次性告知的已读状态,+ * localStorage 持久化,按「账号 + grant」分别记账。+ *+ * 为什么需要它:开通 Cindy AI 后服务端会发一笔限期赠送余额,而客户端此前完全静默 ——+ * 用户可能到过期都不知道账上有钱(赠送金额与有效期的唯一展示位是计费页,而用户走不到它)。+ * 这是产品原则 §4.1「用户操作的对象、影响范围…应清楚可见」缺的一半:钱已经到账,是「已经+ * 发生的事」,用户需要被告知一次,而不是被派一个待办。+ *+ * 与 inheritedSubscriptionNotice 同形态但**刻意不共用一个 key**:那条按 provider 记账,+ * 这条按账号 + grantId 记账。多记一层账号是硬要求 —— 同一台机器上换账号登录后,新账号自己+ * 那笔赠送必须还能告知一次;只按 grantId 记账在 grantId 服务端全局唯一时也不串号,但一旦+ * 服务端改成按账号分配序号就会静默漏掉新账号的告知,而漏告知是查不出来的 bug。+ *+ * 一次性语义:读过(或点过「查看用量」)就永不再出,不随余额变化回弹。+ */++const STORAGE_KEY = 'promotionalGrantNotice.acknowledgedKeys';++type Subscriber = () => void;+const subscribers = new Set<Subscriber>();++/** localStorage 不可用(隐私模式/配额)时的进程内兜底:至少本次会话内关得掉。 */+let memoryAcknowledged = new Set<string>();++function notify(): void {+ subscribers.forEach((cb) => cb());+}++/**+ * 记账键 = 账号 + grant。两段都 encodeURIComponent 后再拼,免得 accountId 或 grantId+ * 里出现 `:` / `,` 时两段边界错位(快照本身是逗号分隔的字符串,见 getAcknowledged…)。+ */+export function promotionalGrantNoticeKey(accountId: string, grantId: string): string {+ return `${encodeURIComponent(accountId)}:${encodeURIComponent(grantId)}`;+}++function readStored(): string[] {+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ if (!raw) return [];+ const parsed: unknown = JSON.parse(raw);+ // 坏数据(手改 / 旧 schema)按「没读过」处理,绝不因此抛错让首屏白屏。+ return Array.isArray(parsed) ? parsed.filter((v): v is string => typeof v === 'string') : [];+ } catch {+ return [];+ }+}++/**+ * 快照:已读的「账号:grant」键集合。+ *+ * 返回稳定字符串而不是 Set —— useSyncExternalStore 会按引用比对快照,每次新建 Set+ * 会让它认为状态一直在变(无限重渲染)。调用方用 `isPromotionalGrantAcknowledged` 判定。+ */+export function getAcknowledgedPromotionalGrants(): string {+ const keys = new Set([...readStored(), ...memoryAcknowledged]);+ return [...keys].sort().join(',');+}++/** 判定某个账号的某笔 grant 是否已读(入参 = getAcknowledged… 的快照)。 */+export function isPromotionalGrantAcknowledged(+ snapshot: string,+ accountId: string,+ grantId: string,+): boolean {+ if (snapshot.length === 0) return false;+ return snapshot.split(',').includes(promotionalGrantNoticeKey(accountId, grantId));+}++/** 标记这笔赠送的告知为已读(一次性,不再出现)。 */+export function acknowledgePromotionalGrant(accountId: string, grantId: string): void {+ // 三路合并:storage 里已有的 + 本会话内存兜底里已有的 + 本次新读的。少了中间那份,+ // localStorage 持续不可用时(隐私模式/配额)同会话第二次 acknowledge 会把第一次的+ // 内存记录整份覆盖掉 —— 切账号后前一个账号的已读也一并丢失,告知条复活。+ const next = new Set([+ ...readStored(),+ ...memoryAcknowledged,+ promotionalGrantNoticeKey(accountId, grantId),+ ]);+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify([...next]));+ // 写成功则 storage 是唯一真值源,不置内存态 —— 否则跨窗口清 key 后本窗口会+ // 因内存态永远判定已读(同 inheritedSubscriptionNotice 的既有教训)。+ memoryAcknowledged = new Set();+ } catch {+ memoryAcknowledged = next;+ }+ notify();+}++/** 订阅变化(useSyncExternalStore 形态)。返回 unsubscribe。 */+export function subscribePromotionalGrantNotice(cb: Subscriber): () => void {+ subscribers.add(cb);++ const storageHandler = (e: StorageEvent): void => {+ // key === null 是其它窗口 localStorage.clear();storageArea 过滤掉 sessionStorage。+ if (e.storageArea !== localStorage) return;+ if (e.key !== null && e.key !== STORAGE_KEY) return;+ cb();+ };+ window.addEventListener('storage', storageHandler);++ return () => {+ subscribers.delete(cb);+ window.removeEventListener('storage', storageHandler);+ };+}++/** 测试用:清空本模块的进程内兜底状态。 */+export function resetPromotionalGrantNoticeMemoryState(): void {+ memoryAcknowledged = new Set();+}