Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
merge: 合并 PR #354 并修复计费 P1
Lizif660007da712
diff --cc apps/desktop/src/renderer/features/billing/BillingPage.tsxindex adff73ee94,9a4ed0723b..1104e24494--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx@@@ -127,6 -137,17 +137,17 @@@ function formatLedgerTimestamp(value: s}}-function formatBillingDate(value: string | null): string | null {++function formatBillingDate(value: string | null, locale: string): string | null {+ if (!value) return null;+ const timestamp = Date.parse(value);+ if (!Number.isFinite(timestamp)) return null;+ try {- return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium' }).format(timestamp);++ return new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(timestamp);+ } catch {+ return null;+ }+ }+function isCustomTopup(offer: BillingCatalogOffer): boolean {return offer.amount === null && offer.minAmount !== null && offer.maxAmount !== null;}@@@ -198,7 -219,7 +219,8 @@@ export function BillingPage()}export function BillingSettingsSection({ accountId }: { accountId: string | null }) {-- const { t } = useTranslation();++ const { t, i18n } = useTranslation();++ const billingLocale = i18n.resolvedLanguage ?? i18n.language;const [catalog, setCatalog] = useState<BillingCatalog | null>(null);const [catalogError, setCatalogError] = useState(false);const [loadingCatalog, setLoadingCatalog] = useState(true);@@@ -320,12 -348,12 +349,7 @@@: [],})),)-- .filter(isCatalogOfferVisible)-- .sort((left, right) => {-- const productOrder = left.product.sortOrder - right.product.sortOrder;-- if (productOrder !== 0) return productOrder;-- return left.offer.code.localeCompare(right.offer.code);-- });++ .filter(isCatalogOfferVisible);}, [catalog]);const subscriptionOffers = useMemo(@@@ -423,6 -451,19 +447,19 @@@currentSubscription?.status === 'ACTIVE' &&!currentSubscription.cancelAtPeriodEnd &¤tPlan?.offer.interval === 'MONTH';+ const currentPlanFacts = useMemo(() => {+ if (!currentSubscription) return null;+ const plan = currentSubscription.effectivePlan;+ return {+ name: planNameOf(plan?.product.code) ?? t('billing.settings.subscriptionCard.unnamedPlan'),+ status: currentSubscription.status,+ price: plan ? formatMoney(plan.terms.amount, plan.terms.currency) : null,+ interval: plan?.offer.interval ?? null,+ includedCredits: plan?.terms.creditAmount ?? null,- periodEndAt: formatBillingDate(currentSubscription.currentPeriodEndAt),++ periodEndAt: formatBillingDate(currentSubscription.currentPeriodEndAt, billingLocale),+ cancelAtPeriodEnd: currentSubscription.cancelAtPeriodEnd,+ };- }, [currentSubscription, planNameOf, t]);++ }, [billingLocale, currentSubscription, planNameOf, t]);// UI candidates only. The quote is the authority on whether a target is// actually reachable; this filter just avoids offering obviously invaliddiff --cc apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsxindex 27bf163f92,206058ac0f..bef93ad4d1--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx@@@ -2,7 -2,8 +2,13 @@@import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+ import type { BillingPaymentOrder, BillingSubscription } from '../../../../shared/billing';+++const i18n = {++ language: 'en',++ resolvedLanguage: 'en' as string | undefined,++};+const checkout = {state: {open: false,@@@ -27,6 -32,6 +37,7 @@@vi.mock('react-i18next', () => ({useTranslation: () => ({++ i18n,t: (key: string, params?: Record<string, string>) => {const providerLabels: Record<string, string> = {'billing.providers.alipay': 'alipay',@@@ -55,6 -60,6 +66,8 @@@ import { BillingPage } from '../Billingdescribe('BillingPage remote catalog rendering', () => {beforeEach(() => {++ i18n.language = 'en';++ i18n.resolvedLanguage = 'en';Object.assign(checkout.state, {open: false,kind: null,@@@ -333,6 -343,144 +351,213 @@@expect(screen.getByText('billing.usage.detailsUnavailable')).toBeTruthy();});+ it('shows current plan price, included credits, status, and renewal date', async () => {++ i18n.resolvedLanguage = 'ja';+ window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({+ subscription: {+ subscriptionId: 'subscription_fixture',+ status: 'ACTIVE' as const,+ currentPeriodStartAt: '2026-07-01T00:00:00.000Z',+ currentPeriodEndAt: '2026-08-01T00:00:00.000Z',+ entitlementValidUntil: '2026-08-02T00:00:00.000Z',+ cancelAtPeriodEnd: false,+ effectivePlan: {+ version: 1 as const,+ product: { code: 'plus', kind: 'SUBSCRIPTION' as const, level: 1 },+ offer: { code: 'plus_month', interval: 'MONTH' as const },+ terms: { amount: '9', currency: 'usd', creditAmount: '100', rolloverCap: '0' },+ capturedAt: '2026-07-01T00:00:00.000Z',+ },+ purchaseAttemptId: null,+ paymentAction: null,+ },+ }));++ render(<BillingPage />);++ expect(await screen.findByText('Configured subscription')).toBeTruthy();+ expect(screen.getByText('billing.subscriptionStatus.ACTIVE')).toBeTruthy();+ expect(+ screen.getByText((text) =>+ text.startsWith('billing.settings.subscriptionCard.priceInterval'),+ ),+ ).toBeTruthy();+ expect(+ screen.getByText((text) =>+ text.startsWith('billing.settings.subscriptionCard.includedCredits'),+ ),+ ).toBeTruthy();+ expect(- screen.getByText((text) => text.startsWith('billing.settings.subscriptionCard.renewsAt')),++ screen.getByText('billing.settings.subscriptionCard.renewsAt:{"date":"2026/08/01"}'),+ ).toBeTruthy();+ expect(screen.getByText('billing.settings.subscriptionCard.changeAction')).toBeTruthy();+ });+++ it('preserves the server order for offers within the same product', async () => {++ window.electronAPI.billing.getCatalog = vi.fn(async () => ({++ products: [++ {++ code: 'ordered_topup',++ name: 'Ordered top-up',++ kind: 'CREDIT_TOPUP' as const,++ level: null,++ sortOrder: 1,++ offers: [++ {++ code: 'z_twenty',++ interval: null,++ currency: 'cny',++ amount: '20',++ minAmount: null,++ maxAmount: null,++ creditAmount: '20',++ rolloverCap: null,++ purchaseOptions: [++ {++ id: 'listing_twenty',++ provider: 'alipay',++ capability: 'ONE_TIME_PAYMENT' as const,++ paymentAction: 'QR_CODE' as const,++ },++ ],++ },++ {++ code: 'a_hundred',++ interval: null,++ currency: 'cny',++ amount: '100',++ minAmount: null,++ maxAmount: null,++ creditAmount: '100',++ rolloverCap: null,++ purchaseOptions: [++ {++ id: 'listing_hundred',++ provider: 'alipay',++ capability: 'ONE_TIME_PAYMENT' as const,++ paymentAction: 'QR_CODE' as const,++ },++ ],++ },++ ],++ },++ ],++ }));++++ render(<BillingPage />);++ fireEvent.click(await screen.findByText('billing.settings.topupCard.action'));++++ const offerNames = await screen.findAllByText('Ordered top-up');++ const offerButtons = offerNames.map((name) => name.closest('button')!);++ const twenty = new Intl.NumberFormat(undefined, {++ style: 'currency',++ currency: 'CNY',++ }).format(20);++ const hundred = new Intl.NumberFormat(undefined, {++ style: 'currency',++ currency: 'CNY',++ }).format(100);++ expect(offerButtons[0].textContent).toContain(twenty);++ expect(offerButtons[1].textContent).toContain(hundred);++ });+++ it('shows an end date for period-end cancellation and omits invalid dates', async () => {+ const subscription = {+ subscriptionId: 'subscription_fixture',+ status: 'ACTIVE' as const,+ currentPeriodStartAt: null,+ currentPeriodEndAt: '2026-08-01T00:00:00.000Z',+ entitlementValidUntil: null,+ cancelAtPeriodEnd: true,+ effectivePlan: null,+ purchaseAttemptId: null,+ paymentAction: null,+ };+ window.electronAPI.billing.getCurrentSubscription = vi+ .fn()+ .mockResolvedValueOnce({ subscription })+ .mockResolvedValueOnce({+ subscription: { ...subscription, currentPeriodEndAt: 'not-a-date' },+ });++ render(<BillingPage />);+ expect(+ await screen.findByText((text) =>+ text.startsWith('billing.settings.subscriptionCard.endsAt'),+ ),+ ).toBeTruthy();++ fireEvent.click(screen.getByText('billing.actions.refreshCatalog'));+ await waitFor(() =>+ expect(+ screen.queryByText((text) => text.startsWith('billing.settings.subscriptionCard.endsAt')),+ ).toBeNull(),+ );+ expect(+ screen.queryByText((text) => text.startsWith('billing.settings.subscriptionCard.renewsAt')),+ ).toBeNull();+ });++ it('places recoverable checkout actions before the balance overview', async () => {+ const order = {+ orderId: 'order_pending',+ productCode: 'credit_topup',+ offerCode: 'credit_topup_custom',+ amount: '10',+ currency: 'cny',+ status: 'PENDING' as const,+ fulfillmentStatus: 'NOT_STARTED' as const,+ paymentAction: null,+ createdAt: '2026-07-24T00:00:00.000Z',+ updatedAt: '2026-07-24T00:00:00.000Z',+ };+ checkout.recoverables.topups = [order];++ render(<BillingPage />);++ const recovery = screen.getByText('billing.recovery.title');+ const balanceTitle = await screen.findByText('billing.balance.title');+ expect(recovery.compareDocumentPosition(balanceTitle) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ fireEvent.click(screen.getByText((text) => text.startsWith('billing.recovery.continueTopup')));+ expect(checkout.resumeTopup).toHaveBeenCalledWith(order);+ });++ it('offers a user-initiated retry entry after background recovery fails', async () => {+ Object.assign(checkout.state, {+ open: false,+ kind: 'TOPUP',+ phase: 'FAILED',+ intent: {+ version: 1,+ kind: 'TOPUP',+ idempotencyKey: 'desktop:topup:uncertain',+ request: {+ offerCode: 'credit_topup_custom',+ amount: '10',+ purchaseOptionId: 'listing_alipay',+ },+ orderId: null,+ createdAt: '2026-07-24T00:00:00.000Z',+ },+ order: null,+ subscription: null,+ error: true,+ });++ render(<BillingPage />);++ const resume = screen.getByText('billing.recovery.continueFailed');+ const balanceTitle = await screen.findByText('billing.balance.title');+ expect(resume.compareDocumentPosition(balanceTitle) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ fireEvent.click(resume);+ expect(checkout.resumeFailed).toHaveBeenCalledTimes(1);+ expect(checkout.retry).not.toHaveBeenCalled();+ });+it('shows usage progress and each promotional grant with its own state and expiry', async () => {window.electronAPI.billing.getCreditUsage = vi.fn(async () => ({available: '66',diff --cc apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.tsindex eb5254e299,80d3523ad9..1b37644cdb--- a/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts+++ b/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts@@@ -230,8 -231,12 +231,59 @@@ describe('billing checkout phase projecpurchaseAttemptId: 'purchase_pending',createdAt: '2026-01-01T00:00:00.000Z',});++ act(() => result.current.resumeSubscription(result.current.recoverables.subscription!));+ expect(result.current.state.open).toBe(true);+ expect(result.current.state.subscription).toEqual(pending);+ });+++ it('keeps polling a restored paid top-up in the background until fulfillment succeeds', async () => {++ const paidOrder = {++ orderId: 'order_paid',++ productCode: 'credit_topup',++ offerCode: 'credit_topup_20',++ amount: '20',++ currency: 'cny',++ status: 'SUCCEEDED' as const,++ fulfillmentStatus: 'PENDING' as const,++ paymentAction: null,++ createdAt: '2026-01-01T00:00:00.000Z',++ updatedAt: '2026-01-01T00:01:00.000Z',++ };++ writeBillingCheckoutIntent(ACCOUNT_ID, {++ version: 1,++ kind: 'TOPUP',++ idempotencyKey: 'desktop:topup:paid-intent',++ request: {++ offerCode: 'credit_topup_20',++ purchaseOptionId: 'listing_alipay',++ },++ orderId: paidOrder.orderId,++ createdAt: '2026-01-01T00:00:00.000Z',++ });++ api.listOrders.mockResolvedValue({ orders: [paidOrder], nextCursor: null });++ api.getOrder.mockResolvedValue({++ ...paidOrder,++ fulfillmentStatus: 'SUCCEEDED',++ });++++ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));++ await waitFor(() => expect(result.current.recovering).toBe(false));++ expect(result.current.state).toMatchObject({++ open: false,++ phase: 'FULFILLING',++ order: paidOrder,++ });++++ act(() => window.dispatchEvent(new Event('focus')));++++ await waitFor(() => expect(result.current.state.phase).toBe('COMPLETED'));++ expect(api.getOrder).toHaveBeenCalledWith(paidOrder.orderId);++ expect(result.current.state.open).toBe(false);++ expect(result.current.recoverables.topups).toEqual([]);++ expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();+ });+it('does not replace a persisted subscription intent with another current subscription', async () => {const intent = {version: 1 as const,diff --cc apps/desktop/src/renderer/features/billing/useBillingCheckout.tsindex 64c84a0341,02632fdc95..2aa41728e4--- a/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts+++ b/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts@@@ -291,13 -306,13 +306,14 @@@ export function useBillingCheckout(accoconst refreshActive = useCallback(async () => {await withRequestLock(async () => {const current = stateRef.current;++ const presentation: CheckoutPresentation = current.open ? 'VISIBLE' : 'BACKGROUND';try {if (current.kind === 'TOPUP' && current.order) {const order =current.phase === 'AWAITING_PAYMENT'? await billingApi.refreshTopup(current.order.orderId): await billingApi.getOrder(current.order.orderId);-- applyOrder(order, current.intent);++ applyOrder(order, current.intent, presentation);return;}if (current.kind === 'SUBSCRIPTION' && current.subscription) {@@@ -305,8 -320,8 +321,8 @@@current.phase === 'AWAITING_PAYMENT' && current.subscription.purchaseAttemptId? await billingApi.refreshSubscriptionPurchase(current.subscription.purchaseAttemptId): (await billingApi.getCurrentSubscription()).subscription;-- if (subscription && !applySubscription(subscription, current.intent)) {-- failCurrentOperation();++ if (subscription && !applySubscription(subscription, current.intent, presentation)) {++ failCurrentOperation(presentation);}}} catch {@@@ -540,7 -577,7 +578,9 @@@}, [accountId, applyOrder, applySubscription, failCurrentOperation]);useEffect(() => {-- if (!state.open || (state.phase !== 'AWAITING_PAYMENT' && state.phase !== 'FULFILLING')) return;++ const shouldPoll =++ state.phase === 'FULFILLING' || (state.open && state.phase === 'AWAITING_PAYMENT');++ if (!shouldPoll) return;const timer = window.setInterval(() => {if (document.visibilityState === 'visible') void refreshActive();}, 3_000);diff --cc apps/mobile/src/__tests__/newSession.test.tsindex 327ceec92a,327ceec92a..ba556b95b1--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@@ -26,6 -26,6 +26,10 @@@ importimport type { ProviderModelRow } from '@/session/providerModelSections';import type { RemoteSession } from '@/session/types';++// Windows checkout(core.autocrlf)下源码是 CRLF;统一归一成 LF,含 \n 的多行片段断言才跨平台成立。++const readTextLf = (...args: Parameters<typeof readFileSync>): string =>++ String(readFileSync(...args)).replace(/\r\n/g, '\n');++// 文案已 i18n 化;固定 zh-CN 让字面量断言与语言环境解耦(全局 mock 默认 en-US)。beforeAll(async () => {await i18n.changeLanguage('zh-CN');@@@ -328,13 -328,13 +332,13 @@@ describe('pickNewSessionDefaultDevice'// 避免锚点(如 deps 数组)变化时 indexOf 失效产生误导性报错。describe('new session default device follows the home device filter', () => {it('sends the deviceExplicit flag only when the home list is filtered to one device', () => {-- const homeSource = readFileSync(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8');++ const homeSource = readTextLf(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8');// 筛选某台电脑时带显式标记;"所有对话"(selectedDeviceId=null)不带,保留记忆回落。expect(homeSource).toContain("...(selectedDeviceId ? { deviceExplicit: '1' } : {})");});it('treats the deviceExplicit route flag as an explicit device on the new-session screen', () => {-- const newSource = readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');++ const newSource = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');expect(newSource).toContain('deviceExplicit?: string;');expect(newSource).toContain("readRouteString(params.deviceExplicit) === '1'");});@@@ -715,7 -715,7 +719,7 @@@ describe('new session model', () =>describe('new session composer surface', () => {it('does not double-apply the Android safe-area inset to the top navigation', () => {-- const newSource = readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');++ const newSource = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');expect(newSource).toContain("const NEW_SESSION_SCREEN_TOP_PADDING = Platform.OS === 'android' ? 0 : spacing.xl;",@@@ -724,7 -724,7 +728,7 @@@});it('uses the shared platform keyboard avoidance rule for the new-session composer', () => {-- const newSource = readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');++ const newSource = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');const normalizedNewSource = newSource.replace(/\r\n/g, '\n');expect(newSource).toContain("import { keyboardAvoidingBehaviorForPlatform } from '@/session/mobileNativeShellLayout';");@@@ -735,9 -735,9 +739,9 @@@});it('uses the shared mobile composer row rather than a separate input implementation', () => {-- const newSource = readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');-- const sessionSource = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');-- const sharedSource = readFileSync(resolve(process.cwd(), 'src/session/MobileComposerInputRow.tsx'), 'utf8');++ const newSource = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');++ const sessionSource = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');++ const sharedSource = readTextLf(resolve(process.cwd(), 'src/session/MobileComposerInputRow.tsx'), 'utf8');const newComposerStart = newSource.indexOf('<MobileComposerInputRow');const newComposerEnd = newSource.indexOf('\n />', newComposerStart) + '\n />'.length;const newComposerSource = newSource.slice(newComposerStart, newComposerEnd);diff --cc packages/anthropic-compat-proxy/src/server-outbound-proxy.test.tsindex e2fa116955,e2fa116955..db4d04d261--- a/packages/anthropic-compat-proxy/src/server-outbound-proxy.test.ts+++ b/packages/anthropic-compat-proxy/src/server-outbound-proxy.test.ts@@@ -6,10 -6,10 +6,10 @@@ import { listenOnAvailableLoopbackPortimport type { ProxyHandle } from './types.js';/**-- * 出站代理链路的 server 级验证。技巧:上游统一用保证不可解析的 `.invalid` 假域 ——++ * 出站代理链路的 server 级验证。代理路径用保证不可解析的 `.invalid` 假域 ——* 经代理转发时压根不需要解析上游域名(http 走绝对形式、https 由代理端拨号),-- * 因此「请求打到了 mini 代理」本身就证明代理路径生效;直连分支则以 DNS 失败收尾,-- * 验证 fail-open 不炸链路。++ * 因此「请求打到了 mini 代理」本身就证明代理路径生效;直连回退则使用本机测试++ * 上游,确定性验证 fail-open 后请求确实抵达直连目标。*/describe('anthropic-compat-proxy outbound proxy wiring', () => {let proxy: ProxyHandle | null = null;@@@ -110,28 -110,28 +110,40 @@@});it('falls back to direct connection when the resolver throws or returns unsupported urls', async () => {++ let directRequests = 0;++ const upstream = createHttpServer((_req, res) => {++ directRequests += 1;++ res.writeHead(200, { 'content-type': 'application/json' });++ res.end(JSON.stringify({ direct: true }));++ });++ const upstreamPort = await listenOnAvailableLoopbackPort(upstream);++ cleanups.push(() => new Promise<void>((r) => upstream.close(() => r())));++const warns: string[] = [];proxy = await createAnthropicCompatProxy({-- upstream: 'http://upstream.invalid:8080',++ // URL parsing keeps 0.0.0.0 distinct from the explicit loopback forms that++ // bypass the resolver, while Node routes it to this local test server.++ upstream: `http://0.0.0.0:${upstreamPort}`,transformRequest: [],resolveOutboundProxy: () => { throw new Error('resolver boom'); },logger: { warn: (msg) => { warns.push(msg); } },});-- // 直连假域必然失败,但必须是 502(fail-open 走到了直连),而非 resolver 异常炸链路。++ // resolver 异常不能炸掉请求;fail-open 后必须实际抵达直连上游。const res = await fetch(`${proxy.url}/v1/messages`, {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ model: 'x', messages: [] }),});-- expect(res.status).toBe(502);++ expect(res.status).toBe(200);++ expect(await res.json()).toEqual({ direct: true });expect(warns.some((m) => m.includes('outbound proxy resolver threw'))).toBe(true);await proxy.dispose();const warns2: string[] = [];proxy = await createAnthropicCompatProxy({-- upstream: 'http://upstream.invalid:8080',++ upstream: `http://0.0.0.0:${upstreamPort}`,transformRequest: [],resolveOutboundProxy: () => 'socks5://127.0.0.1:1080',logger: { warn: (msg) => { warns2.push(msg); } },@@@ -141,7 -141,7 +153,9 @@@headers: { 'content-type': 'application/json' },body: JSON.stringify({ model: 'x', messages: [] }),});-- expect(res2.status).toBe(502);++ expect(res2.status).toBe(200);++ expect(await res2.json()).toEqual({ direct: true });expect(warns2.some((m) => m.includes('unsupported outbound proxy url'))).toBe(true);++ expect(directRequests).toBe(2);});});