The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): localize billing shell and state feedback
brooklyn!36d2229e3892
diff --git a/apps/desktop/src/app/settings/billing/auto-reload-row.tsx b/apps/desktop/src/app/settings/billing/auto-reload-row.tsxindex 876e82b8900..d430945d1a4 100644--- a/apps/desktop/src/app/settings/billing/auto-reload-row.tsx+++ b/apps/desktop/src/app/settings/billing/auto-reload-row.tsx@@ -3,6 +3,7 @@ import { useState } from 'react'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'+import { useI18n } from '@/i18n'import { cn } from '@/lib/utils'import { ListRow, Pill } from '../primitives'@@ -24,6 +25,8 @@ export function AutoReloadRow({bounds: Pick<BillingStateResponse, 'max_usd' | 'min_usd'>row: BillingAccountRowView}) {+ const { t } = useI18n()+ const b = t.settings.billing.autoReloadconst api = useBillingApi()const queryClient = useQueryClient()const [confirmDisable, setConfirmDisable] = useState(false)@@ -32,7 +35,7 @@ export function AutoReloadRow({// save — opening Manage on a prefilled (possibly below-min) config must not// flash an error (spec §9).const [showErrors, setShowErrors] = useState(false)- const [message, setMessage] = useState<null | { kind: 'error' | 'success'; text: string }>(null)+ const [message, setMessage] = useState<null | { kind: 'error' | 'success'; text: 'updated' | 'turnedOff' }>(null)const [refusal, setRefusal] = useState<BillingRefusal | null>(null)const [reloadTo, setReloadTo] = useState(@@ -45,7 +48,7 @@ export function AutoReloadRow({initialAutoReloadAmount(autoReload.threshold_usd, autoReload.threshold_display))- const validation = validateAutoReloadInputs(threshold, reloadTo, bounds)+ const validation = validateAutoReloadInputs(threshold, reloadTo, bounds, t.settings.billing)const busy = savingconst maxBound = bounds.max_usd ?? undefinedconst minBound = bounds.min_usd ?? undefined@@ -95,7 +98,7 @@ export function AutoReloadRow({}await queryClient.invalidateQueries({ queryKey: ['billing', 'state'] })- setMessage({ kind: 'success', text: 'Auto-refill updated.' })+ setMessage({ kind: 'success', text: 'updated' })setEditing(false)}@@ -125,7 +128,7 @@ export function AutoReloadRow({}await queryClient.invalidateQueries({ queryKey: ['billing', 'state'] })- setMessage({ kind: 'success', text: 'Auto-refill turned off.' })+ setMessage({ kind: 'success', text: 'turnedOff' })setEditing(false)}@@ -142,7 +145,7 @@ export function AutoReloadRow({</div>) : null}<BillingRefusalInline refusal={refusal} />- {message && <InlineMessage kind={message.kind}>{message.text}</InlineMessage>}+ {message && <InlineMessage kind={message.kind}>{b[message.text]}</InlineMessage>}</>}description={row.description}@@ -178,9 +181,9 @@ export function AutoReloadRow({<div aria-hidden={!editing} className={cn('space-y-2 [grid-area:stack]', !editing && 'invisible')}><div className="grid gap-2 @2xl:grid-cols-2"><label className="min-w-0 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">- Threshold+ {b.threshold}<Input- aria-label="Auto-refill threshold"+ aria-label={b.thresholdAria}className="mt-1 py-[3px]"disabled={busy || !editing}inputMode="decimal"@@ -195,9 +198,9 @@ export function AutoReloadRow({/></label><label className="min-w-0 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">- Reload to+ {b.reloadTo}<Input- aria-label="Auto-refill reload-to amount"+ aria-label={b.reloadToAria}className="mt-1 py-[3px]"disabled={busy || !editing}inputMode="decimal"@@ -218,9 +221,9 @@ export function AutoReloadRow({</div>{confirmDisable ? (<div className="flex min-w-0 flex-wrap items-center gap-2 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">- <span>Turn off auto-refill?</span>+ <span>{b.turnOffConfirm}</span><Button disabled={busy} onClick={() => void disable()} size="sm" type="button" variant="outline">- Turn off+ {b.turnOff}</Button><Buttondisabled={busy}@@ -229,7 +232,7 @@ export function AutoReloadRow({type="button"variant="ghost">- Cancel+ {b.cancel}</Button></div>) : (@@ -241,7 +244,7 @@ export function AutoReloadRow({type="button"variant="outline">- Disable+ {b.disable}</Button>)}{/* Refusal stays INSIDE the reserved layer so it never pushes Usage. */}@@ -250,7 +253,7 @@ export function AutoReloadRow({{/* VIEW layer — success feedback overlaid in the same cell when not editing. */}{!editing && message && (<div className="[grid-area:stack]">- <InlineMessage kind={message.kind}>{message.text}</InlineMessage>+ <InlineMessage kind={message.kind}>{b[message.text]}</InlineMessage></div>)}</div>@@ -261,15 +264,15 @@ export function AutoReloadRow({{editing ? (<><Button disabled={busy || !validation.values} onClick={() => void save()} size="sm" type="button">- {busy ? 'Saving…' : 'Save'}+ {busy ? b.saving : b.save}</Button><Button disabled={busy} onClick={cancelEdit} size="sm" type="button" variant="outline">- Cancel+ {b.cancel}</Button></>) : (<Button onClick={openEdit} size="sm" type="button" variant="outline">- Manage+ {b.manage}</Button>)}</div>diff --git a/apps/desktop/src/app/settings/billing/billing-amounts.ts b/apps/desktop/src/app/settings/billing/billing-amounts.tsindex 0b0e5517b92..088a916ae38 100644--- a/apps/desktop/src/app/settings/billing/billing-amounts.ts+++ b/apps/desktop/src/app/settings/billing/billing-amounts.ts@@ -1,3 +1,6 @@+import type { Translations } from '@/i18n'+import { en } from '@/i18n/en'+import type { BillingStateResponse } from './types'import { EMPTY_BILLING_VALUE } from './use-billing-state'@@ -49,22 +52,23 @@ export function initialAutoReloadAmount(...candidates: Array<null | string | undexport function validateAutoReloadInputs(thresholdRaw: string,reloadToRaw: string,- bounds: Pick<BillingStateResponse, 'max_usd' | 'min_usd'>+ bounds: Pick<BillingStateResponse, 'max_usd' | 'min_usd'>,+ b: Translations['settings']['billing'] = en.settings.billing): { error?: string; values?: { reloadTo: string; threshold: string } } {- const threshold = validateBillingAmount('Threshold', thresholdRaw, bounds)+ const threshold = validateBillingAmount(b.autoReload.threshold, thresholdRaw, bounds, b.amountValidation)if (threshold.error || threshold.amount == null) {return { error: threshold.error }}- const reloadTo = validateBillingAmount('Reload-to', reloadToRaw, bounds)+ const reloadTo = validateBillingAmount(b.amountValidation.reloadTo, reloadToRaw, bounds, b.amountValidation)if (reloadTo.error || reloadTo.amount == null) {return { error: reloadTo.error }}if (reloadTo.amount <= threshold.amount) {- return { error: 'Reload-to amount must be greater than the threshold.' }+ return { error: b.amountValidation.greaterThanThreshold }}return {@@ -78,30 +82,31 @@ export function validateAutoReloadInputs(export function validateBillingAmount(label: string,raw: string,- bounds: Pick<BillingStateResponse, 'max_usd' | 'min_usd'>+ bounds: Pick<BillingStateResponse, 'max_usd' | 'min_usd'>,+ copy: Translations['settings']['billing']['amountValidation'] = en.settings.billing.amountValidation): { amount?: number; error?: string } {const cleaned = raw.trim().replace(/^\$/, '').trim()if (!cleaned || !/^\d+(\.\d{1,2})?$/.test(cleaned)) {- return { error: `${label}: enter a dollar amount with at most 2 decimal places.` }+ return { error: copy.decimal(label) }}const amount = Number(cleaned)if (!(amount > 0)) {- return { error: `${label}: amount must be greater than $0.` }+ return { error: copy.positive(label) }}const min = parseAmount(bounds.min_usd)if (min != null && amount < min) {- return { error: `${label}: minimum is ${formatMoney(min)}.` }+ return { error: copy.minimum(label, formatMoney(min)) }}const max = parseAmount(bounds.max_usd)if (max != null && amount > max) {- return { error: `${label}: maximum is ${formatMoney(max)}.` }+ return { error: copy.maximum(label, formatMoney(max)) }}return { amount }diff --git a/apps/desktop/src/app/settings/billing/current-plan-card.tsx b/apps/desktop/src/app/settings/billing/current-plan-card.tsxindex ce879dfd7c3..638aae97480 100644--- a/apps/desktop/src/app/settings/billing/current-plan-card.tsx+++ b/apps/desktop/src/app/settings/billing/current-plan-card.tsx@@ -1,4 +1,5 @@import { Button } from '@/components/ui/button'+import { useI18n } from '@/i18n'import { ExternalLink } from '@/lib/icons'import { BillingRefusalInline } from './inline-feedback'@@ -8,6 +9,8 @@ import type { BillingPlanCardView } from './use-billing-state'import { useResumeFlow } from './use-subscription-change'export function CurrentPlanCard({ onViewPlans, plan }: { onViewPlans: () => void; plan: BillingPlanCardView }) {+ const { t } = useI18n()+ const b = t.settings.billingconst resumeFlow = useResumeFlow()return (@@ -22,7 +25,7 @@ export function CurrentPlanCard({ onViewPlans, plan }: { onViewPlans: () => void</span>{plan.price && (<span className="text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">- {plan.price}/mo+ {b.perMonth(plan.price)}</span>)}</div>@@ -40,7 +43,7 @@ export function CurrentPlanCard({ onViewPlans, plan }: { onViewPlans: () => void{/* Scheduled downgrade → chargeless undo (subscription.resume), no confirm. */}{plan.pending && (<Button disabled={resumeFlow.busy} onClick={() => void resumeFlow.resume()} size="sm" type="button">- {resumeFlow.busy ? 'Undoing…' : 'Undo'}+ {resumeFlow.busy ? b.plan.undoing : b.plan.undo}</Button>)}{plan.link && (diff --git a/apps/desktop/src/app/settings/billing/errors.ts b/apps/desktop/src/app/settings/billing/errors.tsindex 0357bf42442..ee82be54993 100644--- a/apps/desktop/src/app/settings/billing/errors.ts+++ b/apps/desktop/src/app/settings/billing/errors.ts@@ -1,3 +1,6 @@+import type { Translations } from '@/i18n'+import { en } from '@/i18n/en'+import type { BillingRefusal } from './api'export interface BillingRefusalPresentation {@@ -8,51 +11,52 @@ export interface BillingRefusalPresentation {const portalAction = (url?: string): BillingRefusalPresentation['action'] => ({ type: 'portal', url })-const retryMessage = (refusal: BillingRefusal): string => {- const mins = refusal.retryAfter ? ` (try again in ~${Math.max(1, Math.round(refusal.retryAfter / 60))} min)` : ''+const retryMessage = (refusal: BillingRefusal, copy: Translations['settings']['billing']['errors']): string => {+ const mins = refusal.retryAfter ? Math.max(1, Math.round(refusal.retryAfter / 60)) : 0- return `🟡 Too many charges right now${mins}. This isn't a payment failure.`+ return copy.rateLimited.message(mins)}-const stripeRetryMessage = (refusal: BillingRefusal): string => {- const mins = refusal.retryAfter ? ` (try again in ~${Math.max(1, Math.round(refusal.retryAfter / 60))} min)` : ''+const stripeRetryMessage = (refusal: BillingRefusal, copy: Translations['settings']['billing']['errors']): string => {+ const mins = refusal.retryAfter ? Math.max(1, Math.round(refusal.retryAfter / 60)) : 0- return `Stripe is having trouble — try again shortly${mins}`+ return copy.stripeUnavailable.message(mins)}-export const resolveRefusal = (refusal: BillingRefusal): BillingRefusalPresentation => {+export const resolveRefusal = (+ refusal: BillingRefusal,+ copy: Translations['settings']['billing']['errors'] = en.settings.billing.errors+): BillingRefusalPresentation => {switch (refusal.kind) {case 'consent_required':return {action: portalAction(refusal.portalUrl),- message: 'Confirm this card for terminal charges in the portal',- title: 'Card confirmation needed'+ message: copy.consentRequired.message,+ title: copy.consentRequired.title}case 'insufficient_scope':return {action: { type: 'step_up' },- message: 'This needs Remote Spending allowed. Start a top-up to allow it, then retry.',- title: 'Remote Spending needs approval'+ message: copy.insufficientScope.message,+ title: copy.insufficientScope.title}case 'remote_spending_revoked': {const who =- refusal.actor === 'admin'- ? 'An admin stopped remote spending for this terminal.'- : 'You stopped remote spending for this terminal.'+ refusal.actor === 'admin' ? copy.remoteSpendingRevoked.messageByAdmin : copy.remoteSpendingRevoked.messageBySelfreturn {action: portalAction(refusal.portalUrl),- message: `${who} Reconnect from Settings → Gateway to re-authorize this device.`,- title: 'Remote spending was stopped'+ message: copy.remoteSpendingReconnect(who),+ title: copy.remoteSpendingRevoked.title}}case 'session_revoked':return {action: portalAction(refusal.portalUrl),- message: 'Your session was logged out. Sign in again from Settings → Gateway.',- title: 'Session logged out'+ message: copy.sessionRevoked.message,+ title: copy.sessionRevoked.title}case 'cli_billing_disabled':@@ -60,39 +64,36 @@ export const resolveRefusal = (refusal: BillingRefusal): BillingRefusalPresentatcase 'remote_spending_disabled':return {action: portalAction(refusal.portalUrl),- message:- "Remote spending is off for this account — a billing admin can turn it on from the portal's Hermes Agent page.",- title: 'Remote spending is off'+ message: copy.cliBillingDisabled.message,+ title: copy.cliBillingDisabled.title}case 'role_required':return {action: portalAction(refusal.portalUrl),- message: 'Adding funds needs an org admin/owner. Ask an admin, or manage on the portal.',- title: 'Admin role required'+ message: copy.roleRequired.message,+ title: copy.roleRequired.title}case 'idempotency_conflict':return {action: { type: 'none' },- message: '🔴 That charge key was already used for a different amount. Start a fresh top-up.',- title: 'Start a fresh top-up'+ message: copy.idempotencyConflict.message,+ title: copy.idempotencyConflict.title}case 'no_payment_method':return {action: portalAction(refusal.portalUrl),- message:- '💳 No saved card for terminal charges yet. Set one up on the portal ' +- "(one-time credit buys don't save a reusable card).",- title: 'No saved card'+ message: copy.noPaymentMethod.message,+ title: copy.noPaymentMethod.title}case 'org_access_denied':return {action: { type: 'none' },- message: "This token isn't bound to an org you can manage",- title: 'Org access denied'+ message: copy.orgAccessDenied.message,+ title: copy.orgAccessDenied.title}case 'monthly_cap_exceeded': {const remaining = refusal.payload?.remainingUsd@@ -101,9 +102,9 @@ export const resolveRefusal = (refusal: BillingRefusal): BillingRefusalPresentataction: portalAction(refusal.portalUrl),message:remaining != null- ? `🔴 Monthly spend cap reached — $${remaining} headroom left.`- : '🔴 Monthly spend cap reached.',- title: 'Monthly spend cap reached'+ ? copy.monthlyCapExceeded.messageHeadroom(remaining)+ : copy.monthlyCapExceeded.messageReached,+ title: copy.monthlyCapExceeded.title}}@@ -112,52 +113,50 @@ export const resolveRefusal = (refusal: BillingRefusal): BillingRefusalPresentatcase 'temporarily_unavailable':return {action: { type: 'retry' },- message: retryMessage(refusal),- title: 'Too many charges right now'+ message: retryMessage(refusal, copy),+ title: copy.rateLimited.title}case 'stripe_unavailable':return {action: { type: 'retry' },- message: stripeRetryMessage(refusal),- title: 'Stripe is having trouble'+ message: stripeRetryMessage(refusal, copy),+ title: copy.stripeUnavailable.title}case 'upgrade_cap_exceeded':return {action: { type: 'none' },- message: 'Daily plan-change limit reached — try again tomorrow',- title: 'Daily plan-change limit reached'+ message: copy.upgradeCapExceeded.message,+ title: copy.upgradeCapExceeded.title}case 'endpoint_unavailable':return {action: { type: 'retry' },- message:- refusal.message ||- 'Billing endpoint returned a non-JSON response (it may not be available on this deployment).',- title: 'Billing endpoint unavailable'+ message: refusal.message || copy.endpointUnavailable.message,+ title: copy.endpointUnavailable.title}case 'timeout':return {action: { type: 'retry' },- message: refusal.message || 'Billing request timed out.',- title: 'Billing request timed out'+ message: refusal.message || copy.timeout.message,+ title: copy.timeout.title}case 'transport':return {action: { type: 'retry' },- message: refusal.message || 'Billing request failed before reaching the gateway.',- title: 'Billing connection failed'+ message: refusal.message || copy.transport.message,+ title: copy.transport.title}default:return {action: { type: 'none' },- message: refusal.message || 'Billing request failed.',- title: 'Billing request failed'+ message: refusal.message || copy.default.message,+ title: copy.default.title}}}diff --git a/apps/desktop/src/app/settings/billing/index.test.tsx b/apps/desktop/src/app/settings/billing/index.test.tsxindex 3283c5e429b..027d01bc248 100644--- a/apps/desktop/src/app/settings/billing/index.test.tsx+++ b/apps/desktop/src/app/settings/billing/index.test.tsx@@ -1,9 +1,11 @@import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import type { ReactNode } from 'react'import { MemoryRouter } from 'react-router'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { type I18nContextValue, I18nProvider, useI18n } from '@/i18n'+import { formatMoney } from './billing-amounts'import {billingDevFixtures,@@ -79,6 +81,51 @@ afterEach(() => {})describe('BillingSettings', () => {+ it('changes billing shell language without losing the credit amount or issuing a charge', async () => {+ apiMocks.fetchBillingState.mockResolvedValue(okBilling(postTrainBillingState))+ apiMocks.fetchSubscriptionState.mockResolvedValue(okSubscription(postTrainSubscriptionState))+ let language!: I18nContextValue++ function Surface() {+ language = useI18n()++ return <BillingSettings />+ }++ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ render(+ <MemoryRouter>+ <I18nProvider configClient={null} initialLocale="zh">+ <QueryClientProvider client={client}>+ <Surface />+ </QueryClientProvider>+ </I18nProvider>+ </MemoryRouter>+ )+ await screen.findByText('支付与额度')+ expect(screen.getByText('余额')).toBeTruthy()+ const input = screen.getByRole('spinbutton', { name: '自定义充值金额' }) as HTMLInputElement+ fireEvent.change(input, { target: { value: '37' } })+ await act(() => language.setLocale('zh-hant'))+ expect(screen.getByText('支付與額度')).toBeTruthy()+ expect(screen.getByText('餘額')).toBeTruthy()+ expect((screen.getByRole('spinbutton', { name: '自訂儲值金額' }) as HTMLInputElement).value).toBe('37')+ expect(apiMocks.charge).not.toHaveBeenCalled()+ apiMocks.charge.mockResolvedValue({+ ok: false,+ refusal: { kind: 'stripe_unavailable', message: '', retryAfter: 120 },+ idempotencyKey: 'fixture-charge'+ })+ fireEvent.click(screen.getByRole('button', { name: '購買' }))+ await screen.findByText(/Stripe 遇到問題/)+ await act(() => language.setLocale('zh'))+ expect(screen.getByText(/Stripe 遇到问题/)).toBeTruthy()+ expect(apiMocks.charge).toHaveBeenCalledTimes(1)+ expect(apiMocks.charge).toHaveBeenCalledWith('37', undefined)+ expect(screen.getAllByText(postTrainSubscriptionState.current!.tier_name!).length).toBeGreaterThan(0)+ client.clear()+ })+it('renders the post-train payload with enabled buy controls and card provenance', async () => {apiMocks.fetchBillingState.mockResolvedValue(okBilling(postTrainBillingState))apiMocks.fetchSubscriptionState.mockResolvedValue(okSubscription(postTrainSubscriptionState))diff --git a/apps/desktop/src/app/settings/billing/index.tsx b/apps/desktop/src/app/settings/billing/index.tsxindex e1f57882a1f..c97130dd438 100644--- a/apps/desktop/src/app/settings/billing/index.tsx+++ b/apps/desktop/src/app/settings/billing/index.tsx@@ -163,6 +163,9 @@ function AccountRow({ billing, row }: { billing?: BillingStateResponse; row: Bil}function BuyCreditsRow({ billing, row }: { billing: BillingStateResponse; row: BillingAccountRowView }) {+ const { t } = useI18n()+ const b = t.settings.billing+const presets = useMemo(() =>billing.charge_presets.map((amount, index) => ({@@ -200,7 +203,7 @@ function BuyCreditsRow({ billing, row }: { billing: BillingStateResponse; row: Bvalue={amount}/><Input- aria-label="Custom credit amount"+ aria-label={b.buyCredits.customAmount}containerClassName="w-16"disabled={controlsDisabled}inputMode="decimal"@@ -219,7 +222,7 @@ function BuyCreditsRow({ billing, row }: { billing: BillingStateResponse; row: Bvalue={amount}/><Button disabled={!canBuy} onClick={startBuy} size="xs" type="button" variant="secondary">- Buy+ {b.buyCredits.buyButton}</Button></div>}@@ -258,12 +261,14 @@ function BuyCreditsOutcome({onRetry: () => voidoutcome: ReturnType<typeof useChargeFlow>['outcome']}) {+ const { t } = useI18n()+ const b = t.settings.billingconst stepUp = useStepUpFlow()if (busy) {return (<div className="mt-2 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">- Processing… checking settlement+ {b.buyCredits.processing}</div>)}@@ -275,7 +280,7 @@ function BuyCreditsOutcome({if (outcome.kind === 'success') {return (<div className="mt-2 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">- {formatMoney(outcome.amountUsd ?? amount)} added. Balance is refreshing.+ {b.buyCredits.added(formatMoney(outcome.amountUsd ?? amount))}</div>)}@@ -288,7 +293,7 @@ function BuyCreditsOutcome({</span>{outcome.portalUrl && (<Button onClick={() => onPortal(outcome.portalUrl)} size="sm" type="button" variant="outline">- Open portal+ {b.buyCredits.openPortal}<ExternalLink className="size-3.5" /></Button>)}@@ -305,13 +310,13 @@ function BuyCreditsOutcome({</span>{outcome.action?.type === 'retry' && (<Button onClick={onRetry} size="sm" type="button" variant="outline">- Retry+ {b.buyCredits.retry}</Button>)}{outcome.action?.type === 'step_up' && <StepUpInlineAction flow={stepUp} />}{portalUrl && (<Button onClick={() => onPortal(portalUrl)} size="sm" type="button" variant="outline">- Open portal+ {b.buyCredits.openPortal}<ExternalLink className="size-3.5" /></Button>)}@@ -320,8 +325,10 @@ function BuyCreditsOutcome({}function UsageBar({ bar, fallbackLabel }: { bar?: BillingUsageRowView['bar']; fallbackLabel: string }) {+ const { t } = useI18n()+const resolvedBar = bar ?? {- label: `${fallbackLabel} usage`,+ label: t.settings.billing.usageLabel(fallbackLabel),state: 'neutral',tone: 'topup',value: 0@@ -383,10 +390,13 @@ function BillingFixtureSelect({onValueChange: (value: BillingFixtureSelection) => voidvalue: BillingFixtureSelection}) {+ const { t } = useI18n()+ const b = t.settings.billing+return (<div className="flex items-center gap-1.5 text-(--ui-text-tertiary)"><Wrench className="size-3.5 shrink-0" />- <span className="text-xs font-normal">preview</span>+ <span className="text-xs font-normal">{b.preview}</span><Select onValueChange={value => onValueChange(value as BillingFixtureSelection)} value={value}><SelectTriggeraria-label="Billing preview fixture (dev only)"@@ -466,6 +476,8 @@ function BillingSettingsContent({fixtureName?: BillingFixtureSelectiononFixtureChange?: (value: BillingFixtureSelection) => void}) {+ const { t } = useI18n()+ const b = t.settings.billingconst [subView, setSubView] = useRouteEnumParam<BillingSubView>('bview', BILLING_VIEWS, 'overview')// Fixture mode flows through the SAME query path — the simulated api (supplied by@@ -487,7 +499,7 @@ function BillingSettingsContent({const billingResult = billingState.dataconst subscriptionResult = subscriptionState.data- const view = deriveBillingView(billingResult, subscriptionResult)+ const view = deriveBillingView(billingResult, subscriptionResult, b)const billing = billingResult?.ok ? billingResult.data : undefinedconst { paymentRow, refillRow, topupRow } = view@@ -526,7 +538,7 @@ function BillingSettingsContent({</div>{view.plan && (- <SettingsSection icon={Package} title="Plan">+ <SettingsSection icon={Package} title={b.sections.plan}><CurrentPlanCard onViewPlans={() => setSubView('plans')} plan={view.plan} />{view.planFootnote && (<div className="mt-1 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">@@ -540,7 +552,7 @@ function BillingSettingsContent({<SettingsSectionaside={paymentRow ? <PaymentMethodAside row={paymentRow} /> : undefined}icon={CreditCard}- title="Payment & credits"+ title={b.sections.paymentAndCredits}>{accountRows.map(row => (<AccountRow billing={billing} key={row.id} row={row} />@@ -549,7 +561,7 @@ function BillingSettingsContent({)}{view.usageRows.length > 0 && (- <SettingsSection icon={BarChart3} title="Usage">+ <SettingsSection icon={BarChart3} title={b.sections.usage}><div className="@container">{view.usageRows.map(row => (<UsageRow key={row.id} row={row} />@@ -560,7 +572,9 @@ function BillingSettingsContent({{// no endpoint yet — NAS capability-board gap- FEATURE_BILLING_INVOICES ? <SectionHeading icon={BarChart3} title="Invoices" /> : null+ FEATURE_BILLING_INVOICES ? (+ <SectionHeading icon={BarChart3} title={t.settings.billing.sections.invoices} />+ ) : null}</SettingsContent>)diff --git a/apps/desktop/src/app/settings/billing/inline-feedback.tsx b/apps/desktop/src/app/settings/billing/inline-feedback.tsxindex dcc3e27993a..338f46b9b59 100644--- a/apps/desktop/src/app/settings/billing/inline-feedback.tsx+++ b/apps/desktop/src/app/settings/billing/inline-feedback.tsx@@ -1,4 +1,5 @@import { Button } from '@/components/ui/button'+import { useI18n } from '@/i18n'import { openExternalLink } from '@/lib/external-link'import { ExternalLink } from '@/lib/icons'@@ -7,12 +8,15 @@ import { resolveRefusal } from './errors'import { useStepUpFlow } from './use-step-up'export function StepUpInlineAction({ flow }: { flow: ReturnType<typeof useStepUpFlow> }) {+ const { t } = useI18n()+ const b = t.settings.billing.stepUp+if (flow.verification) {return (<span className="inline-flex min-w-0 flex-wrap items-center gap-2"><span className="font-mono text-[0.72rem] font-semibold text-foreground">{flow.verification.code}</span><Button onClick={flow.openVerification} size="sm" type="button" variant="outline">- Open verification page+ {b.openVerification}<ExternalLink className="size-3.5" /></Button></span>@@ -26,31 +30,32 @@ export function StepUpInlineAction({ flow }: { flow: ReturnType<typeof useStepUp{flow.message.title}: {flow.message.text}</span><Button onClick={flow.dismiss} size="sm" type="button" variant="outline">- Dismiss+ {b.dismiss}</Button></span>)}if (flow.phase === 'waiting') {- return <span>Waiting for verification link…</span>+ return <span>{b.waiting}</span>}return (<Button onClick={() => void flow.start()} size="sm" type="button" variant="outline">- Verify to continue+ {b.verify}</Button>)}export function BillingRefusalInline({ refusal }: { refusal: BillingRefusal | null }) {+ const { t } = useI18n()const stepUp = useStepUpFlow()if (!refusal) {return null}- const resolved = resolveRefusal(refusal)+ const resolved = resolveRefusal(refusal, t.settings.billing.errors)const portalUrl = resolved.action.type === 'portal' ? resolved.action.url : undefinedreturn (@@ -61,7 +66,7 @@ export function BillingRefusalInline({ refusal }: { refusal: BillingRefusal | nu{resolved.action.type === 'step_up' && <StepUpInlineAction flow={stepUp} />}{portalUrl && (<Button onClick={() => openExternalLink(portalUrl)} size="sm" type="button" variant="outline">- Open portal+ {t.settings.billing.buyCredits.openPortal}<ExternalLink className="size-3.5" /></Button>)}diff --git a/apps/desktop/src/app/settings/billing/plans-view.tsx b/apps/desktop/src/app/settings/billing/plans-view.tsxindex 728a8142387..f00e427c5da 100644--- a/apps/desktop/src/app/settings/billing/plans-view.tsx+++ b/apps/desktop/src/app/settings/billing/plans-view.tsx@@ -1,6 +1,7 @@import { useEffect, useRef } from 'react'import { Button } from '@/components/ui/button'+import { type Translations, useI18n } from '@/i18n'import { openExternalLink } from '@/lib/external-link'import { ChevronLeft, ExternalLink } from '@/lib/icons'import { cn } from '@/lib/utils'@@ -16,9 +17,15 @@ type DowngradeFlow = ReturnType<typeof useDowngradeFlow>// The human sentence for the panel body, derived purely from the phase. `null` while// a refusal is the only thing to show (BillingRefusalInline renders that separately).-function previewMessage(phase: DowngradePhase, fallbackTierName: string): null | string {+function previewMessage(+ phase: DowngradePhase,+ fallbackTierName: string,+ b: Translations['settings']['billing']+): null | string {+ const bp = b.plan+if (phase.kind === 'previewing') {- return 'Checking this change…'+ return bp.checkingChange}if (phase.kind === 'previewFailed') {@@ -27,28 +34,27 @@ function previewMessage(phase: DowngradePhase, fallbackTierName: string): null |const { preview } = phaseconst targetName = preview.target_tier_name ?? fallbackTierName- const creditsDelta = formatMonthlyCreditsDelta(preview.monthly_credits_delta)+ const creditsDelta = formatMonthlyCreditsDelta(preview.monthly_credits_delta, b)switch (preview.effect) {case 'blocked':- return preview.reason ?? 'That change cannot be made here.'+ return preview.reason ?? bp.cannotChangecase 'no_op':- return `You are already on ${targetName} — nothing to change.`+ return bp.alreadyOn(targetName)case 'scheduled':- return (- `Change to ${targetName} — takes effect ${formatBillingDate(preview.effective_at)}. No charge now; ` +- `you keep your current plan until then.${creditsDelta ? ` Monthly credits change: ${creditsDelta}.` : ''}`- )+ return bp.effectScheduled(targetName, formatBillingDate(preview.effective_at), creditsDelta ?? '')default:- return 'This change cannot be scheduled here.'+ return bp.notScheduleable}}// The in-card preview → confirm panel for a downgrade (mirrors the TUI confirm flow).function DowngradeConfirm({ flow, tier }: { flow: DowngradeFlow; tier: BillingPlanTierView }) {+ const { t } = useI18n()+ const bp = t.settings.billing.planconst active = flow.activeconst panelRef = useRef<HTMLDivElement>(null)const open = active?.target.tierId === tier.tierId@@ -69,7 +75,7 @@ function DowngradeConfirm({ flow, tier }: { flow: DowngradeFlow; tier: BillingPlconst captionCn = 'text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)'const refusal = phase.kind === 'previewFailed' || phase.kind === 'scheduleFailed' ? phase.refusal : nullconst busy = phase.kind === 'previewing' || phase.kind === 'scheduling'- const message = previewMessage(phase, tier.name)+ const message = previewMessage(phase, tier.name, t.settings.billing)const canConfirm =(phase.kind === 'ready' && phase.preview.effect === 'scheduled') ||@@ -91,19 +97,19 @@ function DowngradeConfirm({ flow, tier }: { flow: DowngradeFlow; tier: BillingPl<div className="flex min-w-0 flex-wrap items-center gap-2">{phase.kind === 'previewFailed' ? (<Button disabled={busy} onClick={flow.retryPreview} size="sm" type="button">- Try again+ {bp.tryAgain}</Button>) : canConfirm ? (<Button disabled={busy} onClick={() => void flow.confirm()} size="sm" type="button">{phase.kind === 'scheduling'- ? 'Scheduling…'+ ? bp.scheduling: phase.kind === 'scheduleFailed'- ? 'Try again'- : 'Confirm downgrade'}+ ? bp.tryAgain+ : bp.confirmDowngrade}</Button>) : null}<Button disabled={busy} onClick={flow.cancel} size="sm" type="button" variant="outline">- Cancel+ {bp.cancel}</Button></div></div>@@ -111,6 +117,8 @@ function DowngradeConfirm({ flow, tier }: { flow: DowngradeFlow; tier: BillingPl}function PlanCard({ flow, tier }: { flow: DowngradeFlow; tier: BillingPlanTierView }) {+ const { t } = useI18n()+ const bp = t.settings.billing.planconst isCurrent = tier.state === 'current'const confirming = flow.active?.target.tierId === tier.tierIdconst cardRef = useRef<HTMLDivElement>(null)@@ -143,7 +151,7 @@ function PlanCard({ flow, tier }: { flow: DowngradeFlow; tier: BillingPlanTierVi{tier.name}</div><div className="text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">- {tier.priceDisplay}/mo+ {t.settings.billing.perMonth(tier.priceDisplay)}</div></div></div>@@ -155,9 +163,9 @@ function PlanCard({ flow, tier }: { flow: DowngradeFlow; tier: BillingPlanTierVi)}<div className="mt-auto min-w-0 pt-1">- {isCurrent && <Pill tone="primary">Current plan</Pill>}+ {isCurrent && <Pill tone="primary">{bp.current}</Pill>}- {tier.state === 'scheduled' && <Pill>Scheduled</Pill>}+ {tier.state === 'scheduled' && <Pill>{bp.scheduled}</Pill>}{tier.state === 'upgrade' && (<Button@@ -183,7 +191,7 @@ function PlanCard({ flow, tier }: { flow: DowngradeFlow; tier: BillingPlanTierVitype="button"variant="outline">- Downgrade+ {bp.downgrade}</Button>))}</div>@@ -192,6 +200,8 @@ function PlanCard({ flow, tier }: { flow: DowngradeFlow; tier: BillingPlanTierVi}export function BillingPlansView({ onBack, tiers }: { onBack: () => void; tiers: BillingPlanTierView[] }) {+ const { t } = useI18n()+ const bp = t.settings.billing.plan// A scheduled downgrade lands the user back on the overview, where the plan card// now shows the pending state with its undo.const flow = useDowngradeFlow({ onScheduled: onBack })@@ -200,7 +210,7 @@ export function BillingPlansView({ onBack, tiers }: { onBack: () => void; tiers:<div className="@container"><div className="mb-2.5 flex items-center gap-2 pt-2 text-[length:var(--conversation-text-font-size)] font-medium"><Button- aria-label="Back to billing"+ aria-label={bp.backAria}className="size-7 p-0 text-(--ui-text-tertiary)"disabled={flow.mutating}onClick={onBack}@@ -210,7 +220,7 @@ export function BillingPlansView({ onBack, tiers }: { onBack: () => void; tiers:><ChevronLeft className="size-4" /></Button>- <span>Plans</span>+ <span>{bp.title}</span></div>{tiers.length > 0 ? (@@ -221,7 +231,7 @@ export function BillingPlansView({ onBack, tiers }: { onBack: () => void; tiers:</div>) : (<div className="rounded-xl bg-(--ui-bg-quaternary) p-4 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">- No plans are available to change to right now.+ {bp.empty}</div>)}</div>diff --git a/apps/desktop/src/app/settings/billing/use-billing-state.test.ts b/apps/desktop/src/app/settings/billing/use-billing-state.test.tsindex af2fecb42dc..04405da25cc 100644--- a/apps/desktop/src/app/settings/billing/use-billing-state.test.ts+++ b/apps/desktop/src/app/settings/billing/use-billing-state.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from 'vitest'+import { TRANSLATIONS } from '@/i18n'++import type { BillingRefusal } from './api'+import { resolveRefusal } from './errors'import {billingDevFixtures,endpointUnavailableBilling,@@ -56,6 +60,95 @@ function monthlyCapRowForSpent(spent: string) {}describe('deriveBillingView', () => {+ it.each(['zh', 'zh-hant'] as const)(+ 'localizes every billing fixture in %s without changing status, amounts or control policy',+ locale => {+ const b = TRANSLATIONS[locale].settings.billing++ for (const fixture of Object.values(billingDevFixtures)) {+ const english = deriveBillingView(fixture.billing, fixture.subscription)+ const view = deriveBillingView(fixture.billing, fixture.subscription, b)+ expect(view.status).toBe(english.status)+ expect(view.summary[0].label).not.toBe(english.summary[0].label)+ expect(view.usageRows.map(row => row.id)).toEqual(english.usageRows.map(row => row.id))+ expect(view.usageRows.map(row => row.bar?.value)).toEqual(english.usageRows.map(row => row.bar?.value))+ expect(view.topupRow?.chips).toEqual(english.topupRow?.chips)+ expect(view.topupRow?.action?.disabled).toEqual(english.topupRow?.action?.disabled)+ expect(view.plan?.tierName).toEqual(english.plan?.tierName)+ expect(view.plan?.price).toEqual(english.plan?.price)++ if (english.notice) {+ expect(view.notice?.title).not.toBe(english.notice.title)+ expect(view.notice?.action?.url).toEqual(english.notice.action?.url)+ }+ }++ const free = deriveBillingView(+ okBilling({ ...loggedOutBillingState, free_tier: true }),+ okSubscription(loggedOutSubscriptionState),+ b+ )++ expect(free.notice?.title).toBe(b.freeTier.title)+ expect(free.status).toBe('free_tier')+ expect(free.usageRows).toEqual([])+ }+ )++ it.each(['zh', 'zh-hant'] as const)(+ 'localizes known refusal titles in %s while preserving identifiers, interpolations and remedies',+ locale => {+ const copy = TRANSLATIONS[locale].settings.billing.errors++ const kinds: BillingRefusal['kind'][] = [+ 'consent_required',+ 'insufficient_scope',+ 'remote_spending_revoked',+ 'session_revoked',+ 'cli_billing_disabled',+ 'remote_spending_disabled',+ 'role_required',+ 'idempotency_conflict',+ 'no_payment_method',+ 'org_access_denied',+ 'monthly_cap_exceeded',+ 'rate_limited',+ 'temporarily_unavailable',+ 'stripe_unavailable',+ 'upgrade_cap_exceeded',+ 'endpoint_unavailable',+ 'timeout',+ 'transport',+ 'unknown'+ ]++ for (const kind of kinds) {+ const refusal: BillingRefusal = {+ kind,+ message: '',+ retryAfter: 120,+ portalUrl: 'https://fixture.test/billing',+ actor: 'admin',+ payload: { remainingUsd: '17.42' }+ }++ const before = structuredClone(refusal)+ const english = resolveRefusal(refusal)+ const local = resolveRefusal(refusal, copy)+ expect(local.title).not.toBe(english.title)+ expect(local.message).not.toBe(english.message)+ expect(local.action).toEqual(english.action)+ expect(refusal).toEqual(before)++ if (kind === 'monthly_cap_exceeded') {expect(local.message).toContain('17.42')}++ if (kind === 'stripe_unavailable') {expect(local.message).toContain('2')}+ }++ expect(resolveRefusal({ kind: 'unknown', message: 'Server notice Ω' }, copy).message).toBe('Server notice Ω')+ }+ )+it('derives the deployed-today shape with fail-open disabled charge controls', () => {const view = deriveBillingView(okBilling(todayBillingState), okSubscription(todaySubscriptionState))diff --git a/apps/desktop/src/app/settings/billing/use-billing-state.ts b/apps/desktop/src/app/settings/billing/use-billing-state.tsindex 288c31ecf7a..bbd5aa037d9 100644--- a/apps/desktop/src/app/settings/billing/use-billing-state.ts+++ b/apps/desktop/src/app/settings/billing/use-billing-state.ts@@ -1,5 +1,7 @@import { useQuery } from '@tanstack/react-query'+import type { Translations } from '@/i18n'+import { en } from '@/i18n/en'import { fmtDate } from '@/lib/time'import { FREE_TIER_MODEL } from '@/store/free-tier'import { openFreeTierSignIn } from '@/store/free-tier-sign-in'@@ -32,7 +34,7 @@ const BILLING_QUERY_OPTIONS = {} as constexport interface BillingSummaryItemView {- label: 'Auto-refill' | 'Balance' | 'Connectors' | 'Model' | 'Plan'+ label: stringtone?: 'muted' | 'primary'value: string}@@ -188,12 +190,13 @@ export function useSubscriptionState(enabled = true) {export function deriveBillingView(stateResult?: BillingResult<BillingStateResponse>,- subscriptionResult?: BillingResult<SubscriptionStateResponse>+ subscriptionResult?: BillingResult<SubscriptionStateResponse>,+ b: Translations['settings']['billing'] = en.settings.billing): BillingView {if (!stateResult) {return {status: 'loading',- summary: emptySummary(),+ summary: emptySummary(b),tiers: [],usageRows: []}@@ -201,9 +204,9 @@ export function deriveBillingView(if (!stateResult.ok) {return {- notice: refusalNotice(stateResult.refusal),+ notice: refusalNotice(stateResult.refusal, b),status: 'refusal',- summary: emptySummary(),+ summary: emptySummary(b),tiers: [],usageRows: []}@@ -216,18 +219,21 @@ export function deriveBillingView(// `logged_in` is false and the generic "connect your account" notice would// otherwise win and tell the user to go to the portal.if (billing.free_tier) {- return freeTierView(billing)+ return freeTierView(billing, b)}if (!billing.logged_in || subscription?.logged_in === false) {return {notice: {- action: { label: 'Open portal ↗', url: billing.portal_url ?? subscription?.portal_url ?? FALLBACK_PORTAL_URL },- message: 'Run /portal in the TUI or open the Nous portal to connect your account.',- title: 'Connect your Nous account'+ action: {+ label: b.state.notice.loggedOut.action,+ url: billing.portal_url ?? subscription?.portal_url ?? FALLBACK_PORTAL_URL+ },+ message: b.state.notice.loggedOut.message,+ title: b.state.notice.loggedOut.title},status: 'logged_out',- summary: emptySummary(),+ summary: emptySummary(b),tiers: [],usageRows: []}@@ -240,26 +246,30 @@ export function deriveBillingView(// Computed once and threaded to both the card (caption + undo) and the grid// (Scheduled marker), so the two never disagree about what's pending.const pending = pendingTransition(subscription?.current)- const tiers = derivePlanTiers(subscription, billing.portal_url, capable, pending)+ const tiers = derivePlanTiers(subscription, billing.portal_url, capable, pending, b)return {- notice: noCardNotice(billing),- paymentRow: paymentMethodRow(billing),- plan: derivePlanCard(billing, subscription, subscriptionResult, tiers, capable, pending),- refillRow: autoReloadRow(billing),+ notice: noCardNotice(billing, b),+ paymentRow: paymentMethodRow(billing, b),+ plan: derivePlanCard(billing, subscription, subscriptionResult, tiers, capable, pending, b),+ refillRow: autoReloadRow(billing, b),status: 'normal',summary: [- { label: 'Balance', value: displayBalance(billing) },- { label: 'Plan', value: displayPlan(subscription, billing.usage) },+ { label: b.summary.balance, value: displayBalance(billing) },+ { label: b.summary.plan, value: displayPlan(subscription, billing.usage, b) },{- label: 'Auto-refill',+ label: b.summary.autoRefill,tone: billing.auto_reload?.enabled ? 'primary' : billing.auto_reload ? 'muted' : undefined,- value: billing.auto_reload ? (billing.auto_reload.enabled ? 'Enabled' : 'Off') : EMPTY_BILLING_VALUE+ value: billing.auto_reload+ ? billing.auto_reload.enabled+ ? b.state.autoRefill.enabledPill+ : b.state.autoRefill.offPill+ : EMPTY_BILLING_VALUE}],tiers,- topupRow: buyCreditsRow(billing),- usageRows: deriveUsageRows(billing, subscription)+ topupRow: buyCreditsRow(billing, b),+ usageRows: deriveUsageRows(billing, subscription, b)}}@@ -312,11 +322,11 @@ export function formatBillingDate(value?: null | string): string {return fmtDate.format(date)}-function emptySummary(): BillingSummaryItemView[] {+function emptySummary(b: Translations['settings']['billing']): BillingSummaryItemView[] {return [- { label: 'Balance', value: EMPTY_BILLING_VALUE },- { label: 'Plan', value: EMPTY_BILLING_VALUE },- { label: 'Auto-refill', value: EMPTY_BILLING_VALUE }+ { label: b.summary.balance, value: EMPTY_BILLING_VALUE },+ { label: b.summary.plan, value: EMPTY_BILLING_VALUE },+ { label: b.summary.autoRefill, value: EMPTY_BILLING_VALUE }]}@@ -326,38 +336,36 @@ function emptySummary(): BillingSummaryItemView[] {* summary, and a single plan card whose only action is signing in — no payment,* credits, auto-refill or usage sections at all.*/-function freeTierView(billing: BillingStateResponse): BillingView {+function freeTierView(billing: BillingStateResponse, b: Translations['settings']['billing']): BillingView {return {notice: {- action: { label: 'Sign in', onSelect: openFreeTierSignIn },- message: 'Sign in with a Nous account to unlock more models and tools.',- title: "You're on the Nous free tier",+ action: { label: b.freeTier.signIn, onSelect: openFreeTierSignIn },+ message: b.freeTier.message,+ title: b.freeTier.title,tone: 'info'},plan: {- caption:- 'Runs on nous/welcome with connectors included. Signing in keeps your connectors and adds the tools that need an account and every other model.',- tierName: 'Nous · free tier'+ caption: b.freeTier.caption,+ tierName: b.freeTier.name},- planFootnote:- 'The free tier has no balance and nothing to pay. Payment and usage appear when you sign in with a Nous account.',+ planFootnote: b.freeTier.footnote,status: 'free_tier',summary: [- { label: 'Plan', value: 'Free tier' },- { label: 'Model', value: billing.free_tier_model ?? FREE_TIER_MODEL },- { label: 'Connectors', tone: 'primary', value: 'Included' }+ { label: b.summary.plan, value: b.freeTier.plan },+ { label: b.freeTier.model, value: billing.free_tier_model ?? FREE_TIER_MODEL },+ { label: b.freeTier.connectors, tone: 'primary', value: b.freeTier.included }],tiers: [],usageRows: []}}-function refusalNotice(refusal: BillingRefusal): BillingNoticeView {- const resolved = resolveRefusal(refusal)+function refusalNotice(refusal: BillingRefusal, b: Translations['settings']['billing']): BillingNoticeView {+ const resolved = resolveRefusal(refusal, b.errors)const portalUrl = resolved.action.type === 'portal' ? resolved.action.url : undefinedreturn {- action: portalUrl ? { label: 'Open portal ↗', url: portalUrl } : undefined,+ action: portalUrl ? { label: b.state.notice.loggedOut.action, url: portalUrl } : undefined,message: resolved.message,title: resolved.title,tone: 'warn'@@ -367,15 +375,18 @@ function refusalNotice(refusal: BillingRefusal): BillingNoticeView {// A logged-in account with no card can't buy credits or manage auto-refill, and// every one of those controls disables silently — so lead the page with a single// warn banner that names the blocker and links straight to the fix.-function noCardNotice(billing: BillingStateResponse): BillingNoticeView | undefined {+function noCardNotice(+ billing: BillingStateResponse,+ b: Translations['settings']['billing']+): BillingNoticeView | undefined {if (billing.card) {return undefined}return {- action: { label: 'Add card ↗', url: billing.portal_url ?? FALLBACK_PORTAL_BILLING_URL },- message: 'Buying top-up credits and auto-refill stay disabled until a card is on file. Add one on the portal.',- title: 'No payment method on file',+ action: { label: b.state.notice.noCard.action, url: billing.portal_url ?? FALLBACK_PORTAL_BILLING_URL },+ message: b.state.notice.noCard.message,+ title: b.state.notice.noCard.title,tone: 'warn'}}@@ -403,10 +414,13 @@ function plansCapable(// Monthly credits are dollars; NAS sends a bare decimal string. Never render a// bare number — always "$110 credits/mo" (mirrors the retired subscriptionTierChips).-function creditsPerMonthDisplay(monthlyCredits: null | string): string | undefined {+function creditsPerMonthDisplay(+ monthlyCredits: null | string,+ b: Translations['settings']['billing']+): string | undefined {const credits = Number((monthlyCredits ?? '').replace(/,/g, ''))- return Number.isFinite(credits) && credits > 0 ? `$${credits.toLocaleString('en-US')} credits/mo` : undefined+ return Number.isFinite(credits) && credits > 0 ? b.creditsPerMonth(`$${credits.toLocaleString('en-US')}`) : undefined}/**@@ -415,14 +429,17 @@ function creditsPerMonthDisplay(monthlyCredits: null | string): string | undefin* ("−$88/mo"), never the raw number. Zero / absent → null so the caller hides* the line entirely.*/-export function formatMonthlyCreditsDelta(delta?: null | string): null | string {+export function formatMonthlyCreditsDelta(+ delta?: null | string,+ b: Translations['settings']['billing'] = en.settings.billing+): null | string {const amount = parseAmount(delta)if (amount == null || amount === 0) {return null}- return `${amount < 0 ? '−' : '+'}${formatMoney(Math.abs(amount))}/mo`+ return b.perMonth(`${amount < 0 ? '−' : '+'}${formatMoney(Math.abs(amount))}`)}/**@@ -439,10 +456,11 @@ function derivePlanCard(subscriptionResult: BillingResult<SubscriptionStateResponse> | undefined,tiers: BillingPlanTierView[],capable: boolean,- pending: PendingPlanTransition | undefined+ pending: PendingPlanTransition | undefined,+ b: Translations['settings']['billing']): BillingPlanCardView {const current = subscription?.current- const tierName = current?.tier_name ?? billing.usage?.plan_name ?? 'Free'+ const tierName = current?.tier_name ?? billing.usage?.plan_name ?? b.state.planCard.freeTier// Price resolves against the UNFILTERED catalog so a grandfathered current tier// still shows its price.const price = findCurrentTier(subscription)?.dollars_per_month_display@@ -450,14 +468,14 @@ function derivePlanCard(const unavailable = subscriptionResult ? !subscriptionResult.ok : falseconst caption = unavailable- ? 'Subscription details are unavailable; opening the portal is still available.'+ ? b.state.planCard.unavailableCaption: pending? pending.kind === 'downgrade'- ? `Changes to ${pending.tierName} on ${pending.when}.`- : `Cancels on ${pending.when}.`+ ? b.state.planCard.downgradeCaption(pending.tierName, pending.when)+ : b.state.planCard.cancellationCaption(pending.when): current- ? `Renews ${renewal}`- : 'No active subscription — paid models draw down top-up credits.'+ ? b.state.planCard.renewsCaption(renewal)+ : b.state.planCard.noSubscriptionCaption// Actionable = a paid tier above (upgrade) or an in-app downgrade below the current// one. Ticket 11 counts downgrades (they act in-app, so they carry no `action`); a@@ -465,14 +483,14 @@ function derivePlanCard(const hasActionableTier = tiers.some(tier => tier.state === 'upgrade' || tier.state === 'downgrade')if (capable && hasActionableTier) {- return { action: { label: current ? 'Change plan' : 'View plans' }, caption, pending, price, tierName }+ return { action: { label: current ? b.plan.changePlan : b.plan.viewPlans }, caption, pending, price, tierName }}return {caption,// No in-app action → always hand off to the portal so the user isn't stranded.link: {- label: 'Adjust plan ↗',+ label: b.state.planCard.adjustPlanAction,url: buildManageSubscriptionUrl(subscription, subscription?.portal_url ?? billing.portal_url)},pending,@@ -526,7 +544,8 @@ function derivePlanTiers(subscription: null | SubscriptionStateResponse,fallbackPortalUrl: null | string,capable: boolean,- pending: PendingPlanTransition | undefined+ pending: PendingPlanTransition | undefined,+ b: Translations['settings']['billing']): BillingPlanTierView[] {if (!capable || !subscription) {return []@@ -558,7 +577,7 @@ function derivePlanTiers(return gridTiers.map((tier): BillingPlanTierView => {const base: BillingPlanTierBase = {- creditsDisplay: creditsPerMonthDisplay(tier.monthly_credits),+ creditsDisplay: creditsPerMonthDisplay(tier.monthly_credits, b),name: tier.name,priceDisplay: tier.dollars_per_month_display,tierId: tier.tier_id@@ -584,13 +603,19 @@ function derivePlanTiers(return {...base,- action: { label: 'Choose ↗', url: buildManageSubscriptionUrl(subscription, manageBase, tier.tier_id) },+ action: {+ label: b.state.planCard.chooseAction,+ url: buildManageSubscriptionUrl(subscription, manageBase, tier.tier_id)+ },state: 'upgrade'}})}-function paymentMethodRow(billing: BillingStateResponse): BillingAccountRowView {+function paymentMethodRow(+ billing: BillingStateResponse,+ b: Translations['settings']['billing']+): BillingAccountRowView {const portalUrl = billing.portal_url ?? FALLBACK_PORTAL_BILLING_URLconst card = billing.card@@ -599,81 +624,83 @@ function paymentMethodRow(billing: BillingStateResponse): BillingAccountRowView// it. The reason (buys/auto-refill are blocked) already leads the page as a// notice, so the row stays a bare call-to-action with no redundant status text.return {- action: { label: 'Add payment method', url: portalUrl },+ action: { label: b.state.paymentMethod.addAction, url: portalUrl },description: '',id: 'payment_method',- title: 'Payment method'+ title: b.state.paymentMethod.title}}return {- action: { label: 'Update', url: portalUrl },- description: 'Manage the card used for top-ups and subscription renewals.',+ action: { label: b.state.paymentMethod.updateAction, url: portalUrl },+ description: b.state.paymentMethod.description,id: 'payment_method',- title: 'Payment method',- value: `${capitalize(card.brand)} •••• ${card.last4}${provenanceSuffix(card.resolved_via)}`+ title: b.state.paymentMethod.title,+ value: `${capitalize(card.brand)} •••• ${card.last4}${provenanceSuffix(card.resolved_via, b)}`}}-function buyCreditsRow(billing: BillingStateResponse): BillingAccountRowView {+function buyCreditsRow(billing: BillingStateResponse, b: Translations['settings']['billing']): BillingAccountRowView {if (!billing.card) {// The no-card blocker is already spelled out by the page-level warn banner// (noCardNotice); repeating it here — emoji and all — just clutters the row,// so keep the plain "what buying does" line and let the controls sit disabled.return {- action: { disabled: true, label: 'Buy' },+ action: { disabled: true, label: b.buyCredits.buyButton },chips: billing.charge_presets.map(amount => ({ disabled: true, label: formatMoney(amount) })),- description: 'A single charge on your card, added to your balance today.',+ description: b.state.buyCredits.description,id: 'buy_credits',- title: 'Buy credits now'+ title: b.buyCredits.title}}- const disabledReason = buyCreditsDisabledReason(billing)+ const disabledReason = buyCreditsDisabledReason(billing, b)if (disabledReason) {return {description: disabledReason,id: 'buy_credits',- title: 'Buy credits now'+ title: b.buyCredits.title}}return {- action: { disabled: true, label: 'Buy' },+ action: { disabled: true, label: b.buyCredits.buyButton },chips: billing.charge_presets.map(amount => ({ disabled: true, label: formatMoney(amount) })),- description: 'A single charge on your card, added to your balance today.',+ description: b.state.buyCredits.description,id: 'buy_credits',- title: 'Buy credits now'+ title: b.buyCredits.title}}// The generic first sentence shared by the off / absent / divergent states,// where the concrete amounts aren't the headline. The configured state overrides// this with the disambiguating "Charges $X … below $Y." sentence (spec §8).-const AUTO_REFILL_GENERIC = 'Keep your balance topped up when it drops below your threshold.'+// Read inside the view-building path (not at module init) so the description+// follows the active locale after a runtime locale switch.-function autoReloadRow(billing: BillingStateResponse): BillingAccountRowView {+function autoReloadRow(billing: BillingStateResponse, b: Translations['settings']['billing']): BillingAccountRowView {const autoReload = billing.auto_reload+ const autoRefillGeneric = b.state.autoRefill.genericDescriptionif (!autoReload) {return {- action: { disabled: true, label: 'Manage' },- caption: 'Manage auto-refill from the portal.',- description: AUTO_REFILL_GENERIC,+ action: { disabled: true, label: b.autoReload.manage },+ caption: b.state.autoRefill.manageCaption,+ description: autoRefillGeneric,id: 'auto_reload',pill: { label: EMPTY_BILLING_VALUE, tone: 'muted' },- title: 'Refill when low'+ title: b.state.autoRefill.title}}if (!autoReload.enabled) {return {- caption: 'Turn on auto-refill from the portal',- description: AUTO_REFILL_GENERIC,+ caption: b.state.autoRefill.turnOnCaption,+ description: autoRefillGeneric,id: 'auto_reload',- pill: { label: 'Off', tone: 'muted' },- title: 'Refill when low'+ pill: { label: b.state.autoRefill.offPill, tone: 'muted' },+ title: b.state.autoRefill.title}}@@ -681,16 +708,16 @@ function autoReloadRow(billing: BillingStateResponse): BillingAccountRowView {// the default enabled path below — the same treatment as a canonical card.if (autoReload.card?.kind === 'distinct') {const { brand, last4 } = autoReload.card- const cardLabel = brand && last4 ? `${capitalize(brand)} ••${last4}` : 'a different card'+ const cardLabel = brand && last4 ? `${capitalize(brand)} ••${last4}` : b.state.autoRefill.distinctCardFallbackconst portalUrl = billing.portal_url ?? FALLBACK_PORTAL_BILLING_URLreturn {- action: { label: 'Reconcile ↗', url: portalUrl },- caption: `Auto-refill charges ${cardLabel} — reconcile on the portal`,- description: AUTO_REFILL_GENERIC,+ action: { label: b.state.autoRefill.reconcileAction, url: portalUrl },+ caption: b.state.autoRefill.distinctCardCaption(cardLabel),+ description: autoRefillGeneric,id: 'auto_reload',- pill: { label: 'Enabled', tone: 'primary' },- title: 'Refill when low'+ pill: { label: b.state.autoRefill.enabledPill, tone: 'primary' },+ title: b.state.autoRefill.title}}@@ -698,22 +725,23 @@ function autoReloadRow(billing: BillingStateResponse): BillingAccountRowView {const threshold = autoReload.threshold_display || formatMoney(autoReload.threshold_usd)return {- action: { label: 'Manage' },+ action: { label: b.autoReload.manage },// Numbers live in the first sentence (spec §8); the swap region below carries// the editable fields, so no redundant caption here.- description: `Charges ${reloadTo} automatically when your balance falls below ${threshold}.`,+ description: b.state.autoRefill.chargesDescription(reloadTo, threshold),id: 'auto_reload',// The only row that edits in place — AutoReloadRow keys its swap layout off this// flag rather than sniffing the action label.manageInApp: true,- pill: { label: 'Enabled', tone: 'primary' },- title: 'Refill when low'+ pill: { label: b.state.autoRefill.enabledPill, tone: 'primary' },+ title: b.state.autoRefill.title}}function deriveUsageRows(billing: BillingStateResponse,- subscription: null | SubscriptionStateResponse+ subscription: null | SubscriptionStateResponse,+ b: Translations['settings']['billing']): BillingUsageRowView[] {const rows: BillingUsageRowView[] = []const current = subscription?.current@@ -726,8 +754,12 @@ function deriveUsageRows(const subscriptionValue =remaining != null && monthly != null? remaining < 0- ? `${formatMoney(0)} of ${formatMoney(monthly)} left · ${formatMoney(Math.abs(remaining))} over`- : `${formatMoney(remaining)} of ${formatMoney(monthly)} left`+ ? b.state.usage.subscriptionCredits.valueOver(+ formatMoney(0),+ formatMoney(monthly),+ formatMoney(Math.abs(remaining))+ )+ : b.state.usage.subscriptionCredits.valueOf(formatMoney(remaining), formatMoney(monthly)): (usage?.subscription_remaining_display ?? usage?.plan_bar?.remaining_display ?? EMPTY_BILLING_VALUE)const remainingFraction = remaining != null && monthly != null && monthly > 0 ? remaining / monthly : null@@ -736,16 +768,18 @@ function deriveUsageRows(bar:remainingFraction != null? {- label: 'Subscription credits remaining',+ label: b.state.usage.subscriptionCredits.barLabel,state: remainingFraction <= 0.1 ? 'danger' : 'ok',tone: 'subscription',track: remaining != null && remaining <= 0 ? 'danger' : undefined,value: clamp01(remainingFraction)}: undefined,- caption: `Resets ${formatBillingDate(current?.cycle_ends_at ?? usage?.renews_at)}`,+ caption: b.state.usage.subscriptionCredits.captionResets(+ formatBillingDate(current?.cycle_ends_at ?? usage?.renews_at)+ ),id: 'subscription_credits',- title: 'Subscription credits',+ title: b.state.usage.subscriptionCredits.title,value: subscriptionValue})@@ -754,9 +788,9 @@ function deriveUsageRows(// No bar: top-ups have no denominator (the wire carries only the current// balance, and the pool is open-ended), so a fill fraction would be fiction.rows.push({- caption: 'Does not expire',+ caption: b.state.usage.topupCredits.caption,id: 'topup_credits',- title: 'Top-up credits',+ title: b.state.usage.topupCredits.title,value: topupValue})@@ -766,22 +800,28 @@ function deriveUsageRows(const limit = parseAmount(cap.limit_usd)const spent = parseAmount(cap.spent_this_month_usd) ?? 0const usedFraction = limit != null && limit > 0 ? spent / limit : null- const value = `${cap.spent_display || formatMoney(spent)} of ${cap.limit_display || formatMoney(limit)} used`++ const value = b.state.usage.monthlyCap.valueUsed(+ cap.spent_display || formatMoney(spent),+ cap.limit_display || formatMoney(limit)+ )rows.push({bar:usedFraction != null? {- label: 'Monthly spend cap used',+ label: b.state.usage.monthlyCap.barLabel,state: usedFraction >= 0.9 ? 'danger' : 'ok',tone: 'cap',track: usedFraction >= 1 ? 'danger' : undefined,value: clamp01(usedFraction)}: undefined,- caption: cap.is_default_ceiling ? 'Default ceiling' : 'Monthly remote spending',+ caption: cap.is_default_ceiling+ ? b.state.usage.monthlyCap.captionDefault+ : b.state.usage.monthlyCap.captionSpending,id: 'monthly_cap',- title: 'Monthly spend cap',+ title: b.state.usage.monthlyCap.title,value})}@@ -793,7 +833,11 @@ function displayBalance(billing: BillingStateResponse): string {return nonEmpty(billing.balance_display) ?? formatMoney(billing.balance_usd)}-function displayPlan(subscription: null | SubscriptionStateResponse, usage?: UsageModelData): string {+function displayPlan(+ subscription: null | SubscriptionStateResponse,+ usage: UsageModelData | undefined,+ b: Translations['settings']['billing']+): string {const current = subscription?.currentconst tier = current?.tier_name ?? usage?.plan_name@@ -803,7 +847,7 @@ function displayPlan(subscription: null | SubscriptionStateResponse, usage?: Usaconst price = findCurrentTier(subscription)?.dollars_per_month_display- return price ? `${tier} · ${price}/mo` : tier+ return price ? `${tier} · ${b.perMonth(price)}` : tier}function topupCreditsValue(billing: BillingStateResponse, usage?: UsageModelData): string {@@ -815,36 +859,43 @@ function topupCreditsValue(billing: BillingStateResponse, usage?: UsageModelData)}-function buyCreditsDisabledReason(billing: BillingStateResponse): null | string {+function buyCreditsDisabledReason(+ billing: BillingStateResponse,+ b: Translations['settings']['billing']+): null | string {if (!billing.is_admin) {- return resolveRefusal({ kind: 'role_required', message: '' }).message+ return resolveRefusal({ kind: 'role_required', message: '' }, b.errors).message}if (!billing.cli_billing_enabled) {- return resolveRefusal({ kind: 'cli_billing_disabled', message: '', portalUrl: billing.portal_url ?? undefined })- .message+ return resolveRefusal(+ { kind: 'cli_billing_disabled', message: '', portalUrl: billing.portal_url ?? undefined },+ b.errors+ ).message}if (!billing.can_charge) {- return resolveRefusal({ kind: 'remote_spending_disabled', message: '', portalUrl: billing.portal_url ?? undefined })- .message+ return resolveRefusal(+ { kind: 'remote_spending_disabled', message: '', portalUrl: billing.portal_url ?? undefined },+ b.errors+ ).message}return null}-function provenanceSuffix(resolvedVia?: null | string): string {+function provenanceSuffix(resolvedVia: null | string | undefined, b: Translations['settings']['billing']): string {if (!resolvedVia) {return ''}const labels: Record<string, string> = {- autoRefill: 'auto-refill card',- customerDefault: 'customer default',- subPin: 'subscription card'+ autoRefill: b.state.paymentMethod.provenance.autoRefill,+ customerDefault: b.state.paymentMethod.provenance.customerDefault,+ subPin: b.state.paymentMethod.provenance.subPin}- return ` - ${labels[resolvedVia] ?? resolvedVia}`+ return b.state.paymentMethod.provenance.suffix(labels[resolvedVia] ?? resolvedVia)}function capitalize(value: string): string {diff --git a/apps/desktop/src/app/settings/billing/use-charge-poller.test.ts b/apps/desktop/src/app/settings/billing/use-charge-poller.test.tsindex 82f6df182fe..70a47e7d1db 100644--- a/apps/desktop/src/app/settings/billing/use-charge-poller.test.ts+++ b/apps/desktop/src/app/settings/billing/use-charge-poller.test.ts@@ -150,7 +150,7 @@ describe('pollChargeSettlement', () => {portalUrl: 'https://portal.nousresearch.com/billing'})- expect(outcome).toEqual({+ expect(outcome).toMatchObject({kind: 'ambiguous',message: 'Charge may still settle. Check the portal before retrying.',portalUrl: 'https://portal.nousresearch.com/billing',diff --git a/apps/desktop/src/app/settings/billing/use-charge-poller.ts b/apps/desktop/src/app/settings/billing/use-charge-poller.tsindex 02ef7dbf931..aea8b4df92c 100644--- a/apps/desktop/src/app/settings/billing/use-charge-poller.ts+++ b/apps/desktop/src/app/settings/billing/use-charge-poller.ts@@ -7,6 +7,9 @@ import {import { useQueryClient } from '@tanstack/react-query'import { useCallback, useRef, useState } from 'react'+import { type Translations, useI18n } from '@/i18n'+import { en } from '@/i18n/en'+import type { BillingApi, BillingRefusal } from './api'import { useBillingApi } from './api'import { resolveRefusal } from './errors'@@ -26,12 +29,17 @@ export type ChargeFlowOutcome =| {action?: { type: 'portal'; url?: string } | { type: 'retry' } | { type: 'step_up' }kind: 'failure'+ copy: 'failed' | 'check' | 'untracked' | 'refusal'+ refusal?: BillingRefusal+ reason?: null | stringmessage: stringretryFreshKey: booleantitle: string}| {kind: 'ambiguous'+ copy: 'unconfirmed' | 'timeout'+ refusal?: BillingRefusalmessage: stringportalUrl?: stringtitle: string@@ -96,16 +104,18 @@ export async function pollChargeSettlement(return {amountUsd: settlement.status.amount_usd,kind: 'success',- message: settlement.status.amount_usd ? `$${settlement.status.amount_usd} added.` : 'Credits added.'+ message: en.settings.billing.charge.added(settlement.status.amount_usd ?? '')}case 'failed':return {action: { type: 'retry' },kind: 'failure',+ copy: 'failed',+ reason: settlement.status.reason,message: renderChargeFailed(settlement.status.reason),retryFreshKey: true,- title: 'Charge failed'+ title: en.settings.billing.charge.failedTitle}case 'ambiguous': {if (settlement.status && refusalPolicy(settlement.error).ambiguousMidPoll) {@@ -115,26 +125,32 @@ export async function pollChargeSettlement(return {kind: 'ambiguous',- message: `${resolved.message} Your last charge's outcome is unconfirmed - check your balance/history before retrying.`,+ copy: 'unconfirmed',+ refusal,+ message: en.settings.billing.charge.unconfirmedBody(resolved.message),portalUrl: portalUrl ?? opts.portalUrl ?? undefined,- title: 'Charge outcome unconfirmed'+ title: en.settings.billing.charge.unconfirmedTitle}}return {kind: 'failure',- message: observed.refusal?.message || 'Could not check the charge.',+ copy: 'check',+ reason: observed.refusal?.message,+ message: observed.refusal?.message || en.settings.billing.charge.checkBody,retryFreshKey: true,- title: 'Could not check charge'+ title: en.settings.billing.charge.checkTitle}}case 'refused':return {kind: 'failure',- message: observed.refusal?.message || settlement.status.message || 'Could not check the charge.',+ copy: 'check',+ reason: observed.refusal?.message || settlement.status.message,+ message: observed.refusal?.message || settlement.status.message || en.settings.billing.charge.checkBody,retryFreshKey: true,- title: 'Could not check charge'+ title: en.settings.billing.charge.checkTitle}case 'cancelled':@@ -173,6 +189,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {}export function useChargeFlow() {+ const { t } = useI18n()const api = useBillingApi()const queryClient = useQueryClient()const [phase, setPhase] = useState<ChargeFlowPhase>('idle')@@ -223,6 +240,8 @@ export function useChargeFlow() {setOutcome({action,kind: 'failure',+ copy: 'refusal',+ refusal: chargeResult.refusal,message: resolved.message,retryFreshKey: false,title: resolved.title@@ -239,9 +258,10 @@ export function useChargeFlow() {if (!chargeId) {setOutcome({kind: 'failure',- message: 'The billing service accepted the request but did not return a charge id.',+ copy: 'untracked',+ message: en.settings.billing.charge.untrackedBody,retryFreshKey: true,- title: 'Charge could not be tracked'+ title: en.settings.billing.charge.untrackedTitle})setPhaseState('done')@@ -264,7 +284,7 @@ export function useChargeFlow() {[api, queryClient, setPhaseState])- return { outcome, phase, reset, start }+ return { outcome: outcome ? localizeChargeOutcome(outcome, t.settings.billing) : null, phase, reset, start }}function shouldReuseIdempotencyKey(refusal: BillingRefusal): boolean {@@ -274,24 +294,60 @@ function shouldReuseIdempotencyKey(refusal: BillingRefusal): boolean {function timeoutOutcome(portalUrl?: null | string): ChargeFlowOutcome {return {kind: 'ambiguous',- message: 'Charge may still settle. Check the portal before retrying.',+ copy: 'timeout',+ message: en.settings.billing.charge.timeoutBody,portalUrl: portalUrl ?? undefined,- title: 'Still processing after 5 minutes'+ title: en.settings.billing.charge.timeoutTitle}}-function renderChargeFailed(reason?: null | string): string {+function renderChargeFailed(reason: null | string | undefined, copy = en.settings.billing.charge): string {switch ((reason || '').trim()) {case 'authentication_required':- return 'Your bank requires verification (3DS). Complete it on the portal to finish this purchase.'+ return copy.authenticationRequiredcase 'payment_method_expired':- return 'Your card has expired. Update it on the portal.'+ return copy.expiredcase 'card_declined':- return 'Your card was declined. Try another card on the portal.'+ return copy.declineddefault:- return `The charge didn't go through (${reason || 'processing_error'}).`+ return copy.failedBody(reason || 'processing_error')+ }+}++// Repaint completed feedback on a locale switch without replaying a charge.+function localizeChargeOutcome(outcome: ChargeFlowOutcome, b: Translations['settings']['billing']): ChargeFlowOutcome {+ if (outcome.kind === 'success') {return { ...outcome, message: b.charge.added(outcome.amountUsd ?? '') }}++ switch (outcome.copy) {+ case 'refusal': {+ if (!outcome.refusal) {return outcome}+ const resolved = resolveRefusal(outcome.refusal, b.errors)++ return { ...outcome, message: resolved.message, title: resolved.title }+ }++ case 'unconfirmed':+ return outcome.refusal+ ? {+ ...outcome,+ message: b.charge.unconfirmedBody(resolveRefusal(outcome.refusal, b.errors).message),+ title: b.charge.unconfirmedTitle+ }+ : outcome++ case 'failed':+ return { ...outcome, message: renderChargeFailed(outcome.reason, b.charge), title: b.charge.failedTitle }++ case 'check':+ return { ...outcome, message: outcome.reason || b.charge.checkBody, title: b.charge.checkTitle }++ case 'untracked':+ return { ...outcome, message: b.charge.untrackedBody, title: b.charge.untrackedTitle }++ case 'timeout':+ return { ...outcome, message: b.charge.timeoutBody, title: b.charge.timeoutTitle }}}diff --git a/apps/desktop/src/app/settings/billing/use-step-up.ts b/apps/desktop/src/app/settings/billing/use-step-up.tsindex 9cb276afa62..6ed2c586d22 100644--- a/apps/desktop/src/app/settings/billing/use-step-up.ts+++ b/apps/desktop/src/app/settings/billing/use-step-up.ts@@ -2,8 +2,10 @@ import { useStore } from '@nanostores/react'import { useQueryClient } from '@tanstack/react-query'import { useCallback, useEffect, useRef, useState } from 'react'+import { useI18n } from '@/i18n'import { $gateway } from '@/store/gateway'+import type { BillingRefusal } from './api'import { useBillingApi } from './api'import { resolveRefusal } from './errors'@@ -21,13 +23,19 @@ export interface StepUpMessage {}export function useStepUpFlow() {+ const { t } = useI18n()+ const b = t.settings.billingconst api = useBillingApi()const gateway = useStore($gateway)const queryClient = useQueryClient()const offRef = useRef<(() => void) | null>(null)const runningRef = useRef(false)const runIdRef = useRef(0)- const [message, setMessage] = useState<StepUpMessage | null>(null)++ const [message, setMessage] = useState<+ null | { status: 'denied' | 'success' } | { status: 'refusal'; refusal: BillingRefusal }+ >(null)+const [phase, setPhase] = useState<StepUpPhase>('idle')const [verification, setVerification] = useState<StepUpVerification | null>(null)@@ -102,23 +110,13 @@ export function useStepUpFlow() {unsubscribe()if (!result.ok) {- const resolved = resolveRefusal(result.refusal)-- setMessage({- kind: 'error',- text: resolved.message,- title: resolved.title- })+ setMessage({ status: 'refusal', refusal: result.refusal })return}if (!result.data.granted) {- setMessage({- kind: 'error',- text: 'Verification finished without allowing Remote Spending for this terminal.',- title: 'Verification was not approved'- })+ setMessage({ status: 'denied' })return}@@ -127,12 +125,20 @@ export function useStepUpFlow() {queryClient.invalidateQueries({ queryKey: ['billing', 'state'] }),queryClient.invalidateQueries({ queryKey: ['billing', 'subscription'] })])- setMessage({- kind: 'success',- text: 'Remote Spending is allowed for this terminal.',- title: 'Verification complete'- })+ setMessage({ status: 'success' })}, [api, gateway, queryClient, unsubscribe])- return { dismiss, message, openVerification, phase, start, verification }+ let displayMessage: StepUpMessage | null = null++ if (message?.status === 'refusal') {+ const resolved = resolveRefusal(message.refusal, b.errors)+ displayMessage = { kind: 'error', text: resolved.message, title: resolved.title }+ } else if (message) {+ displayMessage =+ message.status === 'success'+ ? { kind: 'success', text: b.stepUp.successBody, title: b.stepUp.successTitle }+ : { kind: 'error', text: b.stepUp.deniedBody, title: b.stepUp.deniedTitle }+ }++ return { dismiss, message: displayMessage, openVerification, phase, start, verification }}diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex e9e27301d29..bd7879d5bc1 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -1870,6 +1870,280 @@ export const en: Translations = {deleted: model => `${model} deleted.`,deleteFailed: 'Delete failed'},+ billing: {+ perMonth: amount => `${amount}/mo`,+ creditsPerMonth: amount => `${amount} credits/mo`,+ usageLabel: label => `${label} usage`,+ freeTier: {+ signIn: 'Sign in',+ title: "You're on the Nous free tier",+ message: 'Sign in with a Nous account to unlock more models and tools.',+ caption:+ 'Runs on nous/welcome with connectors included. Signing in keeps your connectors and adds the tools that need an account and every other model.',+ name: 'Nous · free tier',+ footnote:+ 'The free tier has no balance and nothing to pay. Payment and usage appear when you sign in with a Nous account.',+ plan: 'Free tier',+ model: 'Model',+ connectors: 'Connectors',+ included: 'Included'+ },+ amountValidation: {+ reloadTo: 'Reload-to',+ greaterThanThreshold: 'Reload-to amount must be greater than the threshold.',+ decimal: label => `${label}: enter a dollar amount with at most 2 decimal places.`,+ positive: label => `${label}: amount must be greater than $0.`,+ minimum: (label, amount) => `${label}: minimum is ${amount}.`,+ maximum: (label, amount) => `${label}: maximum is ${amount}.`+ },+ stepUp: {+ openVerification: 'Open verification page',+ dismiss: 'Dismiss',+ waiting: 'Waiting for verification link…',+ verify: 'Verify to continue',+ deniedTitle: 'Verification was not approved',+ deniedBody: 'Verification finished without allowing Remote Spending for this terminal.',+ successTitle: 'Verification complete',+ successBody: 'Remote Spending is allowed for this terminal.'+ },+ charge: {+ added: amount => (amount ? `$${amount} added.` : 'Credits added.'),+ failedTitle: 'Charge failed',+ unconfirmedTitle: 'Charge outcome unconfirmed',+ unconfirmedBody: message =>+ `${message} Your last charge's outcome is unconfirmed - check your balance/history before retrying.`,+ checkTitle: 'Could not check charge',+ checkBody: 'Could not check the charge.',+ untrackedTitle: 'Charge could not be tracked',+ untrackedBody: 'The billing service accepted the request but did not return a charge id.',+ timeoutTitle: 'Still processing after 5 minutes',+ timeoutBody: 'Charge may still settle. Check the portal before retrying.',+ authenticationRequired:+ 'Your bank requires verification (3DS). Complete it on the portal to finish this purchase.',+ expired: 'Your card has expired. Update it on the portal.',+ declined: 'Your card was declined. Try another card on the portal.',+ failedBody: reason => `The charge didn't go through (${reason}).`+ },+ title: 'Billing',+ preview: 'preview',+ summary: {+ balance: 'Balance',+ plan: 'Plan',+ autoRefill: 'Auto-refill'+ },+ sections: {+ invoices: 'Invoices',++ plan: 'Plan',+ paymentAndCredits: 'Payment & credits',+ usage: 'Usage'+ },+ usage: {+ title: 'Usage'+ },+ buyCredits: {+ customAmount: 'Custom credit amount',+ title: 'Buy credits now',+ buyButton: 'Buy',+ processing: 'Processing… checking settlement',+ added: amount => `${amount} added. Balance is refreshing.`,+ retry: 'Retry',+ openPortal: 'Open portal'+ },+ plan: {+ title: 'Plans',+ changePlan: 'Change plan',+ viewPlans: 'View plans',+ backAria: 'Back to billing',+ current: 'Current plan',+ scheduled: 'Scheduled',+ empty: 'No plans are available to change to right now.',+ undo: 'Undo',+ undoing: 'Undoing…',+ downgrade: 'Downgrade',+ confirmDowngrade: 'Confirm downgrade',+ tryAgain: 'Try again',+ checkingChange: 'Checking this change…',+ cannotChange: 'That change cannot be made here.',+ alreadyOn: name => `You are already on ${name} — nothing to change.`,+ notScheduleable: 'This change cannot be scheduled here.',+ scheduling: 'Scheduling…',+ cancel: 'Cancel',+ effectScheduled: (targetName, effectiveAt, creditsDelta) =>+ `Change to ${targetName} — takes effect ${effectiveAt}. No charge now; you keep your current plan until then.${creditsDelta ? ` Monthly credits change: ${creditsDelta}.` : ''}`+ },+ autoReload: {+ threshold: 'Threshold',+ thresholdAria: 'Auto-refill threshold',+ reloadTo: 'Reload to',+ reloadToAria: 'Auto-refill reload-to amount',+ turnOffConfirm: 'Turn off auto-refill?',+ turnOff: 'Turn off',+ disable: 'Disable',+ updated: 'Auto-refill updated.',+ turnedOff: 'Auto-refill turned off.',+ manage: 'Manage',+ save: 'Save',+ saving: 'Saving…',+ cancel: 'Cancel'+ },+ state: {+ notice: {+ loggedOut: {+ title: 'Connect your Nous account',+ message: 'Run /portal in the TUI or open the Nous portal to connect your account.',+ action: 'Open portal ↗'+ },+ noCard: {+ title: 'No payment method on file',+ message:+ 'Buying top-up credits and auto-refill stay disabled until a card is on file. Add one on the portal.',+ action: 'Add card ↗'+ }+ },+ paymentMethod: {+ title: 'Payment method',+ description: 'Manage the card used for top-ups and subscription renewals.',+ addAction: 'Add payment method',+ updateAction: 'Update',+ provenance: {+ autoRefill: 'auto-refill card',+ customerDefault: 'customer default',+ subPin: 'subscription card',+ suffix: label => ` - ${label}`+ }+ },+ buyCredits: {+ description: 'A single charge on your card, added to your balance today.'+ },+ autoRefill: {+ title: 'Refill when low',+ genericDescription: 'Keep your balance topped up when it drops below your threshold.',+ offPill: 'Off',+ enabledPill: 'Enabled',+ notAvailablePill: '—',+ manageCaption: 'Manage auto-refill from the portal.',+ turnOnCaption: 'Turn on auto-refill from the portal',+ chargesDescription: (reloadTo, threshold) =>+ `Charges ${reloadTo} automatically when your balance falls below ${threshold}.`,+ distinctCardCaption: cardLabel => `Auto-refill charges ${cardLabel} — reconcile on the portal`,+ distinctCardFallback: 'a different card',+ reconcileAction: 'Reconcile ↗'+ },+ usage: {+ subscriptionCredits: {+ title: 'Subscription credits',+ barLabel: 'Subscription credits remaining',+ captionResets: date => `Resets ${date}`,+ valueOf: (remaining, monthly) => `${remaining} of ${monthly} left`,+ valueOver: (remaining, monthly, over) => `${remaining} of ${monthly} left · ${over} over`+ },+ topupCredits: {+ title: 'Top-up credits',+ caption: 'Does not expire'+ },+ monthlyCap: {+ title: 'Monthly spend cap',+ barLabel: 'Monthly spend cap used',+ captionDefault: 'Default ceiling',+ captionSpending: 'Monthly remote spending',+ valueUsed: (spent, limit) => `${spent} of ${limit} used`+ }+ },+ planCard: {+ freeTier: 'Free',+ chooseAction: 'Choose ↗',+ adjustPlanAction: 'Adjust plan ↗',+ unavailableCaption: 'Subscription details are unavailable; opening the portal is still available.',+ downgradeCaption: (tierName, when) => `Changes to ${tierName} on ${when}.`,+ cancellationCaption: when => `Cancels on ${when}.`,+ renewsCaption: date => `Renews ${date}`,+ noSubscriptionCaption: 'No active subscription — paid models draw down top-up credits.'+ }+ },+ errors: {+ consentRequired: {+ title: 'Card confirmation needed',+ message: 'Confirm this card for terminal charges in the portal'+ },+ insufficientScope: {+ title: 'Remote Spending needs approval',+ message: 'This needs Remote Spending allowed. Start a top-up to allow it, then retry.'+ },+ remoteSpendingRevoked: {+ title: 'Remote spending was stopped',+ messageByAdmin: 'An admin stopped remote spending for this terminal.',+ messageBySelf: 'You stopped remote spending for this terminal.'+ },+ remoteSpendingReconnect: who => `${who} Reconnect from Settings -> Gateway to re-authorize this device.`,+ sessionRevoked: {+ title: 'Session logged out',+ message: 'Your session was logged out. Sign in again from Settings → Gateway.'+ },+ cliBillingDisabled: {+ title: 'Remote spending is off',+ message:+ "Remote spending is off for this account — a billing admin can turn it on from the portal's Hermes Agent page."+ },+ roleRequired: {+ title: 'Admin role required',+ message: 'Adding funds needs an org admin/owner. Ask an admin, or manage on the portal.'+ },+ idempotencyConflict: {+ title: 'Start a fresh top-up',+ message: '🔴 That charge key was already used for a different amount. Start a fresh top-up.'+ },+ noPaymentMethod: {+ title: 'No saved card',+ message:+ '💳 No saved card for terminal charges yet. Set one up on the portal ' ++ "(one-time credit buys don't save a reusable card)."+ },+ orgAccessDenied: {+ title: 'Org access denied',+ message: "This token isn't bound to an org you can manage"+ },+ monthlyCapExceeded: {+ title: 'Monthly spend cap reached',+ messageReached: '🔴 Monthly spend cap reached.',+ messageHeadroom: remaining => `🔴 Monthly spend cap reached — $${remaining} headroom left.`+ },+ rateLimited: {+ title: 'Too many charges right now',+ message: mins =>+ mins > 0+ ? `🟡 Too many charges right now (try again in ~${mins} min). This isn't a payment failure.`+ : "🟡 Too many charges right now. This isn't a payment failure."+ },+ stripeUnavailable: {+ title: 'Stripe is having trouble',+ message: mins =>+ mins > 0+ ? `Stripe is having trouble — try again in ~${mins} min`+ : 'Stripe is having trouble — try again shortly'+ },+ upgradeCapExceeded: {+ title: 'Daily plan-change limit reached',+ message: 'Daily plan-change limit reached — try again tomorrow'+ },+ endpointUnavailable: {+ title: 'Billing endpoint unavailable',+ message: 'Billing endpoint returned a non-JSON response (it may not be available on this deployment).'+ },+ timeout: {+ title: 'Billing request timed out',+ message: 'Billing request timed out.'+ },+ transport: {+ title: 'Billing connection failed',+ message: 'Billing request failed before reaching the gateway.'+ },+ default: {+ title: 'Billing request failed',+ message: 'Billing request failed.'+ }+ }+ },providers: {connectAccount: 'Connect an account',haveApiKey: 'Have an API key instead?',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 105324b20ba..4dea364c90b 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -1582,6 +1582,217 @@ export interface Translations {deleted: (model: string) => stringdeleteFailed: string}+ billing: {+ perMonth: (amount: string) => string+ creditsPerMonth: (amount: string) => string+ usageLabel: (label: string) => string+ freeTier: {+ signIn: string+ title: string+ message: string+ caption: string+ name: string+ footnote: string+ plan: string+ model: string+ connectors: string+ included: string+ }+ amountValidation: {+ reloadTo: string+ greaterThanThreshold: string+ decimal: (label: string) => string+ positive: (label: string) => string+ minimum: (label: string, amount: string) => string+ maximum: (label: string, amount: string) => string+ }+ stepUp: {+ openVerification: string+ dismiss: string+ waiting: string+ verify: string+ deniedTitle: string+ deniedBody: string+ successTitle: string+ successBody: string+ }+ charge: {+ added: (amount: string) => string+ failedTitle: string+ unconfirmedTitle: string+ unconfirmedBody: (message: string) => string+ checkTitle: string+ checkBody: string+ untrackedTitle: string+ untrackedBody: string+ timeoutTitle: string+ timeoutBody: string+ authenticationRequired: string+ expired: string+ declined: string+ failedBody: (reason: string) => string+ }+ title: string+ preview: string+ summary: {+ balance: string+ plan: string+ autoRefill: string+ }+ sections: {+ invoices: string++ plan: string+ paymentAndCredits: string+ usage: string+ }+ usage: {+ title: string+ }+ buyCredits: {+ customAmount: string+ title: string+ buyButton: string+ processing: string+ added: (amount: string) => string+ retry: string+ openPortal: string+ }+ plan: {+ title: string+ changePlan: string+ viewPlans: string+ backAria: string+ current: string+ scheduled: string+ empty: string+ undo: string+ undoing: string+ downgrade: string+ confirmDowngrade: string+ tryAgain: string+ checkingChange: string+ cannotChange: string+ alreadyOn: (name: string) => string+ notScheduleable: string+ scheduling: string+ cancel: string+ effectScheduled: (targetName: string, effectiveAt: string, creditsDelta: string) => string+ }+ autoReload: {+ threshold: string+ thresholdAria: string+ reloadTo: string+ reloadToAria: string+ turnOffConfirm: string+ turnOff: string+ disable: string+ updated: string+ turnedOff: string+ manage: string+ save: string+ saving: string+ cancel: string+ }+ state: {+ notice: {+ loggedOut: { title: string; message: string; action: string }+ noCard: { title: string; message: string; action: string }+ }+ paymentMethod: {+ title: string+ description: string+ addAction: string+ updateAction: string+ provenance: {+ autoRefill: string+ customerDefault: string+ subPin: string+ suffix: (label: string) => string+ }+ }+ buyCredits: {+ description: string+ }+ autoRefill: {+ title: string+ genericDescription: string+ offPill: string+ enabledPill: string+ notAvailablePill: string+ manageCaption: string+ turnOnCaption: string+ chargesDescription: (reloadTo: string, threshold: string) => string+ distinctCardCaption: (cardLabel: string) => string+ distinctCardFallback: string+ reconcileAction: string+ }+ usage: {+ subscriptionCredits: {+ title: string+ barLabel: string+ captionResets: (date: string) => string+ valueOf: (remaining: string, monthly: string) => string+ valueOver: (remaining: string, monthly: string, over: string) => string+ }+ topupCredits: {+ title: string+ caption: string+ }+ monthlyCap: {+ title: string+ barLabel: string+ captionDefault: string+ captionSpending: string+ valueUsed: (spent: string, limit: string) => string+ }+ }+ planCard: {+ freeTier: string+ chooseAction: string+ adjustPlanAction: string+ unavailableCaption: string+ downgradeCaption: (tierName: string, when: string) => string+ cancellationCaption: (when: string) => string+ renewsCaption: (date: string) => string+ noSubscriptionCaption: string+ }+ }+ errors: {+ consentRequired: { title: string; message: string }+ insufficientScope: { title: string; message: string }+ remoteSpendingRevoked: {+ title: string+ messageByAdmin: string+ messageBySelf: string+ }+ remoteSpendingReconnect: (who: string) => string+ sessionRevoked: { title: string; message: string }+ cliBillingDisabled: { title: string; message: string }+ roleRequired: { title: string; message: string }+ idempotencyConflict: { title: string; message: string }+ noPaymentMethod: { title: string; message: string }+ orgAccessDenied: { title: string; message: string }+ monthlyCapExceeded: {+ title: string+ messageReached: string+ messageHeadroom: (remaining: string) => string+ }+ rateLimited: {+ title: string+ message: (mins: number) => string+ }+ stripeUnavailable: {+ title: string+ message: (mins: number) => string+ }+ upgradeCapExceeded: { title: string; message: string }+ endpointUnavailable: { title: string; message: string }+ timeout: { title: string; message: string }+ transport: { title: string; message: string }+ default: { title: string; message: string }+ }+ }providers: {connectAccount: stringhaveApiKey: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex ac300898fd0..fed4ec1fed5 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -1455,6 +1455,229 @@ export const zhHant = defineLocale({deleted: model => `已刪除 ${model}。`,deleteFailed: '刪除失敗'},+ billing: {+ perMonth: amount => `${amount}/月`,+ creditsPerMonth: amount => `${amount} 額度/月`,+ usageLabel: label => `${label}用量`,+ freeTier: {+ signIn: '登入',+ title: '你正在使用 Nous 免費服務',+ message: '登入 Nous 帳戶以解鎖更多模型和工具。',+ caption: '使用 nous/welcome,包含連接器。登入後會保留連接器,並增加需要帳戶的工具和其他所有模型。',+ name: 'Nous · 免費服務',+ footnote: '免費服務沒有餘額,無需付款。登入 Nous 帳戶後才會顯示支付與用量。',+ plan: '免費服務',+ model: '模型',+ connectors: '連接器',+ included: '已包含'+ },+ amountValidation: {+ reloadTo: '儲值金額',+ greaterThanThreshold: '儲值金額必須大於門檻。',+ decimal: label => `${label}:請輸入最多含兩位小數的美元金額。`,+ positive: label => `${label}:金額必須大於 $0。`,+ minimum: (label, amount) => `${label}:最低金額為 ${amount}。`,+ maximum: (label, amount) => `${label}:最高金額為 ${amount}。`+ },+ stepUp: {+ openVerification: '開啟驗證頁面',+ dismiss: '關閉',+ waiting: '正在等待驗證連結…',+ verify: '驗證以繼續',+ deniedTitle: '驗證未獲核准',+ deniedBody: '驗證已結束,但未允許此終端進行遠端支出。',+ successTitle: '驗證完成',+ successBody: '此終端已獲准進行遠端支出。'+ },+ charge: {+ added: amount => (amount ? `已加入 $${amount}。` : '已加入額度。'),+ failedTitle: '扣款失敗',+ unconfirmedTitle: '扣款結果尚未確認',+ unconfirmedBody: message => `${message} 上次扣款結果尚未確認,請在重試前檢查餘額和歷史記錄。`,+ checkTitle: '無法檢查扣款',+ checkBody: '無法檢查扣款。',+ untrackedTitle: '無法追蹤扣款',+ untrackedBody: '帳單服務已接受請求,但未傳回扣款識別碼。',+ timeoutTitle: '5 分鐘後仍在處理',+ timeoutBody: '扣款仍可能結算,請在重試前檢查入口網站。',+ authenticationRequired: '銀行要求驗證(3DS)。請在入口網站完成驗證以完成本次購買。',+ expired: '銀行卡已到期。請在入口網站中更新。',+ declined: '銀行卡遭拒。請在入口網站中嘗試另一張卡。',+ failedBody: reason => `扣款未成功(${reason})。`+ },+ title: '帳單',+ preview: '預覽',+ summary: { balance: '餘額', plan: '方案', autoRefill: '自動儲值' },+ sections: {+ invoices: '發票',+ plan: '方案',+ paymentAndCredits: '支付與額度',+ usage: '用量'+ },+ usage: { title: '用量' },+ buyCredits: {+ customAmount: '自訂儲值金額',+ title: '立即購買額度',+ buyButton: '購買',+ processing: '處理中…正在確認結算',+ added: amount => `已加入 ${amount},正在重新整理餘額。`,+ retry: '重試',+ openPortal: '開啟入口網站'+ },+ plan: {+ title: '方案',+ changePlan: '變更方案',+ viewPlans: '查看方案',+ backAria: '返回帳單',+ current: '目前方案',+ scheduled: '已排定',+ empty: '目前沒有可切換的方案。',+ undo: '復原',+ undoing: '正在復原…',+ downgrade: '降級',+ confirmDowngrade: '確認降級',+ tryAgain: '重試',+ checkingChange: '正在檢查此變更…',+ cannotChange: '無法在此進行該變更。',+ alreadyOn: name => `你已使用 ${name},無需變更。`,+ notScheduleable: '無法在此排定該變更。',+ scheduling: '正在排定…',+ cancel: '取消',+ effectScheduled: (targetName, effectiveAt, creditsDelta) =>+ `變更為 ${targetName},於 ${effectiveAt} 生效。現在不扣款;在此之前保留目前方案。${creditsDelta ? `每月額度變化:${creditsDelta}。` : ''}`+ },+ autoReload: {+ threshold: '門檻',+ thresholdAria: '自動儲值門檻',+ reloadTo: '儲值金額',+ reloadToAria: '自動儲值金額',+ turnOffConfirm: '關閉自動儲值?',+ turnOff: '關閉',+ disable: '停用',+ updated: '自動儲值已更新。',+ turnedOff: '自動儲值已關閉。',+ manage: '管理',+ save: '儲存',+ saving: '正在儲存…',+ cancel: '取消'+ },+ state: {+ notice: {+ loggedOut: {+ title: '連接你的 Nous 帳戶',+ message: '在 TUI 中執行 /portal,或開啟 Nous 入口網站連接帳戶。',+ action: '開啟入口網站 ↗'+ },+ noCard: {+ title: '尚未新增付款方式',+ message: '新增銀行卡後才能購買額度和使用自動儲值。請在入口網站中新增。',+ action: '新增銀行卡 ↗'+ }+ },+ paymentMethod: {+ title: '付款方式',+ description: '管理用於儲值和訂閱續費的銀行卡。',+ addAction: '新增付款方式',+ updateAction: '更新',+ provenance: {+ autoRefill: '自動儲值卡',+ customerDefault: '帳戶預設卡',+ subPin: '訂閱卡',+ suffix: label => ` - ${label}`+ }+ },+ buyCredits: { description: '從銀行卡一次性扣款,今天即可計入餘額。' },+ autoRefill: {+ title: '餘額不足時儲值',+ genericDescription: '餘額低於門檻時自動補充額度。',+ offPill: '已關閉',+ enabledPill: '已啟用',+ notAvailablePill: '—',+ manageCaption: '在入口網站中管理自動儲值。',+ turnOnCaption: '在入口網站中開啟自動儲值',+ chargesDescription: (reloadTo, threshold) => `餘額低於 ${threshold} 時自動扣款 ${reloadTo}。`,+ distinctCardCaption: cardLabel => `自動儲值使用 ${cardLabel} 扣款,請在入口網站中核對`,+ distinctCardFallback: '另一張銀行卡',+ reconcileAction: '核對 ↗'+ },+ usage: {+ subscriptionCredits: {+ title: '訂閱額度',+ barLabel: '剩餘訂閱額度',+ captionResets: date => `於 ${date} 重設`,+ valueOf: (remaining, monthly) => `${monthly} 中剩餘 ${remaining}`,+ valueOver: (remaining, monthly, over) => `${monthly} 中剩餘 ${remaining} · 超出 ${over}`+ },+ topupCredits: { title: '儲值額度', caption: '不會到期' },+ monthlyCap: {+ title: '每月支出上限',+ barLabel: '已用每月支出限額',+ captionDefault: '預設上限',+ captionSpending: '每月遠端支出',+ valueUsed: (spent, limit) => `${limit} 中已用 ${spent}`+ }+ },+ planCard: {+ freeTier: '免費',+ chooseAction: '選擇 ↗',+ adjustPlanAction: '調整方案 ↗',+ unavailableCaption: '訂閱詳細資料暫不可用,仍可開啟入口網站。',+ downgradeCaption: (tierName, when) => `於 ${when} 變更為 ${tierName}。`,+ cancellationCaption: when => `於 ${when} 取消。`,+ renewsCaption: date => `於 ${date} 續費`,+ noSubscriptionCaption: '沒有有效訂閱,付費模型會扣除儲值額度。'+ }+ },+ errors: {+ consentRequired: { title: '需要確認銀行卡', message: '請在入口網站中確認此卡可用於終端扣款' },+ insufficientScope: {+ title: '需要核准遠端支出',+ message: '此操作需要遠端支出權限。請發起一次儲值以授權,然後重試。'+ },+ remoteSpendingRevoked: {+ title: '遠端支出已停止',+ messageByAdmin: '管理員已停止此終端的遠端支出。',+ messageBySelf: '你已停止此終端的遠端支出。'+ },+ remoteSpendingReconnect: who => `${who} 請從「設定 → 閘道」重新連線以重新授權此裝置。`,+ sessionRevoked: { title: '工作階段已登出', message: '你的工作階段已登出。請從「設定 → 閘道」重新登入。' },+ cliBillingDisabled: {+ title: '遠端支出已關閉',+ message: '此帳戶的遠端支出已關閉,帳單管理員可在入口網站的 Hermes Agent 頁面開啟。'+ },+ roleRequired: {+ title: '需要管理員權限',+ message: '新增資金需要組織管理員或擁有者權限。請聯絡管理員,或在入口網站中管理。'+ },+ idempotencyConflict: { title: '請發起新的儲值', message: '🔴 此扣款識別碼已用於另一金額。請發起新的儲值。' },+ noPaymentMethod: {+ title: '沒有已儲存的銀行卡',+ message: '💳 尚未儲存用於終端扣款的銀行卡。請在入口網站中設定(一次性購買額度不會儲存可重複使用的卡)。'+ },+ orgAccessDenied: { title: '組織存取遭拒', message: '此權杖未綁定到你可管理的組織' },+ monthlyCapExceeded: {+ title: '已達每月支出上限',+ messageReached: '🔴 已達每月支出上限。',+ messageHeadroom: remaining => `🔴 已達每月支出上限,剩餘額度為 $${remaining}。`+ },+ rateLimited: {+ title: '目前扣款請求過多',+ message: mins => `🟡 目前扣款請求過多${mins > 0 ? `(請約 ${mins} 分鐘後重試)` : ''}。這不是付款失敗。`+ },+ stripeUnavailable: {+ title: 'Stripe 遇到問題',+ message: mins => (mins > 0 ? `Stripe 遇到問題,請約 ${mins} 分鐘後重試` : 'Stripe 遇到問題,請稍後重試')+ },+ upgradeCapExceeded: { title: '已達每日方案變更次數上限', message: '已達每日方案變更次數上限,請明天重試' },+ endpointUnavailable: {+ title: '帳單端點不可用',+ message: '帳單端點傳回了非 JSON 回應(此部署可能不支援該端點)。'+ },+ timeout: { title: '帳單請求逾時', message: '帳單請求逾時。' },+ transport: { title: '帳單連線失敗', message: '帳單請求在到達閘道前失敗。' },+ default: { title: '帳單請求失敗', message: '帳單請求失敗。' }+ }+ },providers: {connectAccount: '連結帳號',haveApiKey: '改用 API 金鑰?',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex b6daca7bbd6..bf281fae764 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -1808,6 +1808,229 @@ export const zh = defineLocale({deleted: model => `已删除 ${model}。`,deleteFailed: '删除失败'},+ billing: {+ perMonth: amount => `${amount}/月`,+ creditsPerMonth: amount => `${amount} 额度/月`,+ usageLabel: label => `${label}用量`,+ freeTier: {+ signIn: '登录',+ title: '你正在使用 Nous 免费服务',+ message: '登录 Nous 账户以解锁更多模型和工具。',+ caption: '使用 nous/welcome,包含连接器。登录后会保留连接器,并增加需要账户的工具和其他所有模型。',+ name: 'Nous · 免费服务',+ footnote: '免费服务没有余额,无需支付。登录 Nous 账户后才会显示支付与用量。',+ plan: '免费服务',+ model: '模型',+ connectors: '连接器',+ included: '已包含'+ },+ amountValidation: {+ reloadTo: '充值金额',+ greaterThanThreshold: '充值金额必须大于阈值。',+ decimal: label => `${label}:请输入最多含两位小数的美元金额。`,+ positive: label => `${label}:金额必须大于 $0。`,+ minimum: (label, amount) => `${label}:最低金额为 ${amount}。`,+ maximum: (label, amount) => `${label}:最高金额为 ${amount}。`+ },+ stepUp: {+ openVerification: '打开验证页面',+ dismiss: '关闭',+ waiting: '正在等待验证链接…',+ verify: '验证以继续',+ deniedTitle: '验证未获批准',+ deniedBody: '验证已结束,但未允许此终端进行远程支出。',+ successTitle: '验证完成',+ successBody: '此终端已获准进行远程支出。'+ },+ charge: {+ added: amount => (amount ? `已添加 $${amount}。` : '已添加额度。'),+ failedTitle: '扣款失败',+ unconfirmedTitle: '扣款结果尚未确认',+ unconfirmedBody: message => `${message} 上次扣款结果尚未确认,请在重试前检查余额和历史记录。`,+ checkTitle: '无法检查扣款',+ checkBody: '无法检查扣款。',+ untrackedTitle: '无法跟踪扣款',+ untrackedBody: '账单服务已接受请求,但未返回扣款标识。',+ timeoutTitle: '5 分钟后仍在处理',+ timeoutBody: '扣款仍可能结算,请在重试前检查门户。',+ authenticationRequired: '银行要求验证(3DS)。请在门户完成验证以完成本次购买。',+ expired: '银行卡已过期。请在门户中更新。',+ declined: '银行卡被拒绝。请在门户中尝试另一张卡。',+ failedBody: reason => `扣款未成功(${reason})。`+ },+ title: '账单',+ preview: '预览',+ summary: { balance: '余额', plan: '套餐', autoRefill: '自动充值' },+ sections: {+ invoices: '发票',+ plan: '套餐',+ paymentAndCredits: '支付与额度',+ usage: '用量'+ },+ usage: { title: '用量' },+ buyCredits: {+ customAmount: '自定义充值金额',+ title: '立即购买额度',+ buyButton: '购买',+ processing: '处理中…正在确认结算',+ added: amount => `已添加 ${amount},正在刷新余额。`,+ retry: '重试',+ openPortal: '打开门户'+ },+ plan: {+ title: '套餐',+ changePlan: '更改套餐',+ viewPlans: '查看套餐',+ backAria: '返回账单',+ current: '当前套餐',+ scheduled: '已安排',+ empty: '目前没有可切换的套餐。',+ undo: '撤销',+ undoing: '正在撤销…',+ downgrade: '降级',+ confirmDowngrade: '确认降级',+ tryAgain: '重试',+ checkingChange: '正在检查此变更…',+ cannotChange: '无法在此进行该变更。',+ alreadyOn: name => `你已使用 ${name},无需更改。`,+ notScheduleable: '无法在此安排该变更。',+ scheduling: '正在安排…',+ cancel: '取消',+ effectScheduled: (targetName, effectiveAt, creditsDelta) =>+ `更改为 ${targetName},于 ${effectiveAt} 生效。现在不扣费;在此之前保留当前套餐。${creditsDelta ? `每月额度变化:${creditsDelta}。` : ''}`+ },+ autoReload: {+ threshold: '阈值',+ thresholdAria: '自动充值阈值',+ reloadTo: '充值金额',+ reloadToAria: '自动充值金额',+ turnOffConfirm: '关闭自动充值?',+ turnOff: '关闭',+ disable: '禁用',+ updated: '自动充值已更新。',+ turnedOff: '自动充值已关闭。',+ manage: '管理',+ save: '保存',+ saving: '正在保存…',+ cancel: '取消'+ },+ state: {+ notice: {+ loggedOut: {+ title: '连接你的 Nous 账户',+ message: '在 TUI 中运行 /portal,或打开 Nous 门户连接账户。',+ action: '打开门户 ↗'+ },+ noCard: {+ title: '尚未添加支付方式',+ message: '添加银行卡后才能购买额度和使用自动充值。请在门户中添加。',+ action: '添加银行卡 ↗'+ }+ },+ paymentMethod: {+ title: '支付方式',+ description: '管理用于充值和订阅续费的银行卡。',+ addAction: '添加支付方式',+ updateAction: '更新',+ provenance: {+ autoRefill: '自动充值卡',+ customerDefault: '账户默认卡',+ subPin: '订阅卡',+ suffix: label => ` - ${label}`+ }+ },+ buyCredits: { description: '从银行卡一次性扣款,今天即可计入余额。' },+ autoRefill: {+ title: '余额不足时充值',+ genericDescription: '余额低于阈值时自动补充额度。',+ offPill: '已关闭',+ enabledPill: '已启用',+ notAvailablePill: '—',+ manageCaption: '在门户中管理自动充值。',+ turnOnCaption: '在门户中开启自动充值',+ chargesDescription: (reloadTo, threshold) => `余额低于 ${threshold} 时自动扣款 ${reloadTo}。`,+ distinctCardCaption: cardLabel => `自动充值使用 ${cardLabel} 扣款,请在门户中核对`,+ distinctCardFallback: '另一张银行卡',+ reconcileAction: '核对 ↗'+ },+ usage: {+ subscriptionCredits: {+ title: '订阅额度',+ barLabel: '剩余订阅额度',+ captionResets: date => `于 ${date} 重置`,+ valueOf: (remaining, monthly) => `${monthly} 中剩余 ${remaining}`,+ valueOver: (remaining, monthly, over) => `${monthly} 中剩余 ${remaining} · 超出 ${over}`+ },+ topupCredits: { title: '充值额度', caption: '不会过期' },+ monthlyCap: {+ title: '每月支出上限',+ barLabel: '已用每月支出限额',+ captionDefault: '默认上限',+ captionSpending: '每月远程支出',+ valueUsed: (spent, limit) => `${limit} 中已用 ${spent}`+ }+ },+ planCard: {+ freeTier: '免费',+ chooseAction: '选择 ↗',+ adjustPlanAction: '调整套餐 ↗',+ unavailableCaption: '订阅详情暂不可用,仍可打开门户。',+ downgradeCaption: (tierName, when) => `于 ${when} 更改为 ${tierName}。`,+ cancellationCaption: when => `于 ${when} 取消。`,+ renewsCaption: date => `于 ${date} 续费`,+ noSubscriptionCaption: '没有有效订阅,付费模型会扣除充值额度。'+ }+ },+ errors: {+ consentRequired: { title: '需要确认银行卡', message: '请在门户中确认此卡可用于终端扣款' },+ insufficientScope: {+ title: '需要批准远程支出',+ message: '此操作需要远程支出权限。请发起一次充值以授权,然后重试。'+ },+ remoteSpendingRevoked: {+ title: '远程支出已停止',+ messageByAdmin: '管理员已停止此终端的远程支出。',+ messageBySelf: '你已停止此终端的远程支出。'+ },+ remoteSpendingReconnect: who => `${who} 请从“设置 → 网关”重新连接以重新授权此设备。`,+ sessionRevoked: { title: '会话已登出', message: '你的会话已登出。请从“设置 → 网关”重新登录。' },+ cliBillingDisabled: {+ title: '远程支出已关闭',+ message: '此账户的远程支出已关闭,账单管理员可在门户的 Hermes Agent 页面开启。'+ },+ roleRequired: {+ title: '需要管理员权限',+ message: '添加资金需要组织管理员或所有者权限。请联系管理员,或在门户中管理。'+ },+ idempotencyConflict: { title: '请发起新的充值', message: '🔴 此扣款标识已用于另一金额。请发起新的充值。' },+ noPaymentMethod: {+ title: '没有已保存的银行卡',+ message: '💳 尚未保存用于终端扣款的银行卡。请在门户中设置(一次性购买额度不会保存可重复使用的卡)。'+ },+ orgAccessDenied: { title: '组织访问被拒绝', message: '此令牌未绑定到你可管理的组织' },+ monthlyCapExceeded: {+ title: '已达每月支出上限',+ messageReached: '🔴 已达每月支出上限。',+ messageHeadroom: remaining => `🔴 已达每月支出上限,剩余额度为 $${remaining}。`+ },+ rateLimited: {+ title: '当前扣款请求过多',+ message: mins => `🟡 当前扣款请求过多${mins > 0 ? `(请约 ${mins} 分钟后重试)` : ''}。这不是支付失败。`+ },+ stripeUnavailable: {+ title: 'Stripe 遇到问题',+ message: mins => (mins > 0 ? `Stripe 遇到问题,请约 ${mins} 分钟后重试` : 'Stripe 遇到问题,请稍后重试')+ },+ upgradeCapExceeded: { title: '已达每日套餐变更次数上限', message: '已达每日套餐变更次数上限,请明天重试' },+ endpointUnavailable: {+ title: '账单端点不可用',+ message: '账单端点返回了非 JSON 响应(此部署可能不支持该端点)。'+ },+ timeout: { title: '账单请求超时', message: '账单请求超时。' },+ transport: { title: '账单连接失败', message: '账单请求在到达网关前失败。' },+ default: { title: '账单请求失败', message: '账单请求失败。' }+ }+ },providers: {connectAccount: '连接账号',haveApiKey: '改用 API 密钥?',