Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): add invoice request flow (#3573)

nanaco73b346d15f7d
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 6ae8b1571c..88e2fd6706 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -32,6 +32,7 @@ import {
createWindowBackdropMaterialArgument,
WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,
} from '../shared/windowBackdrop.js';
+import { isAllowedBillingMailtoRequest } from '../shared/billing.js';
import path from 'node:path';
import fs from 'node:fs';
import os from 'node:os';
@@ -5936,13 +5937,18 @@ const registerIpcHandlers = () => {
// macOS Privacy panes that Settings uses for permission onboarding.
ipcMain.handle(
'shell:open-external',
- async (_event: Electron.IpcMainInvokeEvent, url: string): Promise<{ success: boolean }> => {
+ async (event: Electron.IpcMainInvokeEvent, url: string): Promise<{ success: boolean }> => {
try {
const parsed = new URL(url);
const isWebUrl = parsed.protocol === 'http:' || parsed.protocol === 'https:';
+ // Mail links are restricted to the fixed billing inbox. Renderer content may
+ // provide the localized subject/body, but it must not choose a recipient or
+ // use mailto as a general-purpose external scheme.
+ const isBillingMailto =
+ isAllowedBillingMailtoRequest(url, isTrustedAppRendererEvent(event));
const isAllowedSystemSettingsUrl =
process.platform === 'darwin' && allowedSystemSettingsUrls.has(url);
- if (!isWebUrl && !isAllowedSystemSettingsUrl) {
+ if (!isWebUrl && !isBillingMailto && !isAllowedSystemSettingsUrl) {
return { success: false };
}
await shell.openExternal(url);
diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
index bacfbb2584..eebbdc76ec 100644
--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx
+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
@@ -3,13 +3,14 @@ import * as Dialog from '@radix-ui/react-dialog';
import {
ArrowRight,
Check,
+ CircleDollarSign,
ChevronDown,
ChevronRight,
ChevronUp,
- CircleDollarSign,
Copy,
CreditCard,
ExternalLink,
+ Mail,
PackageOpen,
RefreshCcw,
X,
@@ -17,6 +18,7 @@ import {
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router-dom';
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import {
DropdownMenu,
@@ -31,6 +33,7 @@ import { useAuth } from '@/contexts/AuthContext';
import { cn } from '@/lib/utils';
import { extractIpcError } from '@/utils/ipcError';
import {
+ BILLING_SUPPORT_EMAIL,
BILLING_SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES,
type BillingCatalog,
type BillingCatalogOffer,
@@ -38,6 +41,7 @@ import {
type BillingCatalogProduct,
type BillingPaymentOrder,
type BillingPendingPlanChange,
+ type BillingPurchaseOption,
type BillingSubscription,
} from '../../../shared/billing';
import type {
@@ -93,6 +97,8 @@ type CurrentPlanFacts = {
const SUBSCRIPTION_CANCELLABLE_STATUSES = BILLING_SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES;
const PLAN_CHANGE_ENTRY_STATUSES: BillingSubscription['status'][] = ['ACTIVE'];
+const INVOICE_REQUIRED_FIELDS = ['invoiceTitle', 'contact', 'phone', 'email'] as const;
+const GMAIL_COMPOSE_URL = 'https://mail.google.com/mail/?view=cm&fs=1';
/**
* 订单记录默认只列最近 10 笔。这一组回答的是「上次充了多少、那笔没付成的还在不在」,
@@ -1777,6 +1783,7 @@ function OrderHistoryCard({
}) {
const { t, i18n } = useTranslation();
const billingLocale = i18n.resolvedLanguage ?? i18n.language;
+ const [invoiceOrder, setInvoiceOrder] = useState<BillingPaymentOrder | null>(null);
const copyOrderId = async (orderId: string) => {
try {
await navigator.clipboard.writeText(orderId);
@@ -1863,14 +1870,211 @@ function OrderHistoryCard({
>
{t(orderStatusLabelKey(order))}
</span>
+ {phaseForOrder(order) === 'COMPLETED' && (
+ <button
+ type="button"
+ onClick={() => setInvoiceOrder(order)}
+ className="h-7 shrink-0 select-none rounded-full border border-[var(--border-default)] px-2.5 text-10 font-medium text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t('billing.orders.invoice.action')}
+ </button>
+ )}
</div>
</div>
))}
</div>
+ <InvoiceRequestDialog order={invoiceOrder} onClose={() => setInvoiceOrder(null)} />
</section>
);
}
+function InvoiceRequestDialog({
+ order,
+ onClose,
+}: {
+ order: BillingPaymentOrder | null;
+ onClose: () => void;
+}) {
+ const { t, i18n } = useTranslation();
+ const { confirm } = useConfirmDialog();
+ const billingLocale = i18n.resolvedLanguage ?? i18n.language;
+ const sendInvoiceLockRef = useRef(false);
+ // BillingPaymentOrder does not carry the actual acquiring provider, and a
+ // terminal order usually has no paymentAction. Never present an action type
+ // such as QR_CODE/REDIRECT as the user's payment method.
+ const paymentMethod = t('billing.orders.invoice.notAvailable');
+ const buildInvoiceEmail = () => {
+ if (!order) return null;
+ const subject = t('billing.orders.invoice.emailSubject', { orderId: order.orderId });
+ const body = t('billing.orders.invoice.emailBody', {
+ orderId: order.orderId,
+ application: 'Cindy',
+ paymentMethod,
+ amount: formatMoney(order.amount, order.currency, billingLocale),
+ });
+ return { subject, body };
+ };
+ const invoiceEmail = buildInvoiceEmail();
+ const invoiceMailto =
+ invoiceEmail === null
+ ? ''
+ : `mailto:${BILLING_SUPPORT_EMAIL}?subject=${encodeURIComponent(
+ invoiceEmail.subject,
+ )}&body=${encodeURIComponent(invoiceEmail.body)}`;
+ const gmailComposeUrl =
+ invoiceEmail === null
+ ? ''
+ : `${GMAIL_COMPOSE_URL}&${new URLSearchParams({
+ to: BILLING_SUPPORT_EMAIL,
+ su: invoiceEmail.subject,
+ body: invoiceEmail.body,
+ }).toString()}`;
+ const description = t('billing.orders.invoice.description', {
+ email: BILLING_SUPPORT_EMAIL,
+ });
+ const [descriptionBeforeEmail, descriptionAfterEmail] = description.split(BILLING_SUPPORT_EMAIL);
+ const copySupportEmail = async () => {
+ try {
+ await navigator.clipboard.writeText(BILLING_SUPPORT_EMAIL);
+ toast.success(t('billing.orders.invoice.emailCopied'));
+ } catch {
+ toast.error(t('billing.orders.invoice.emailCopyFailed'));
+ }
+ };
+ const openGmailFallback = async () => {
+ if (!gmailComposeUrl) return false;
+ try {
+ const confirmed = await confirm({
+ title: t('billing.orders.invoice.gmailFallbackTitle'),
+ description: t('billing.orders.invoice.gmailFallbackDescription'),
+ confirmText: t('billing.orders.invoice.gmailFallbackConfirm'),
+ cancelText: t('billing.actions.close'),
+ autoFocusConfirm: true,
+ });
+ if (!confirmed) return false;
+ const result = await window.electronAPI.openExternal(gmailComposeUrl);
+ return result.success;
+ } catch {
+ return false;
+ }
+ };
+ const showSendFailed = () => {
+ toast.error(t('billing.orders.invoice.sendFailed', { email: BILLING_SUPPORT_EMAIL }));
+ };
+ const sendInvoiceRequest = () => {
+ if (!order || !invoiceMailto || sendInvoiceLockRef.current) return;
+ sendInvoiceLockRef.current = true;
+ void window.electronAPI
+ .openExternal(invoiceMailto)
+ .then(async (result) => {
+ if (result.success) {
+ onClose();
+ return;
+ }
+ if (await openGmailFallback()) {
+ onClose();
+ return;
+ }
+ showSendFailed();
+ })
+ .catch(async () => {
+ if (await openGmailFallback()) {
+ onClose();
+ return;
+ }
+ showSendFailed();
+ })
+ .finally(() => {
+ sendInvoiceLockRef.current = false;
+ });
+ };
+
+ const invoiceContent = order ? (
+ <div>
+ <p className="text-12 leading-5 text-[var(--confirm-desc)]">
+ {descriptionBeforeEmail}
+ <button
+ type="button"
+ onClick={() => void copySupportEmail()}
+ className="font-mono text-[var(--text-primary)] underline decoration-[var(--border-default)] underline-offset-2 transition-colors hover:text-[var(--text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {BILLING_SUPPORT_EMAIL}
+ </button>
+ {descriptionAfterEmail}
+ </p>
+
+ <div className="mt-4 divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]">
+ <InvoiceInfoRow
+ label={t('billing.orders.invoice.fields.orderId')}
+ value={order.orderId}
+ mono
+ />
+ <InvoiceInfoRow label={t('billing.orders.invoice.fields.application')} value="Cindy" />
+ <InvoiceInfoRow
+ label={t('billing.orders.invoice.fields.paymentMethod')}
+ value={paymentMethod}
+ />
+ <InvoiceInfoRow
+ label={t('billing.orders.invoice.fields.amount')}
+ value={formatMoney(order.amount, order.currency, billingLocale)}
+ />
+ </div>
+
+ <div className="mt-4 py-3">
+ <p className="text-12 leading-5 text-[var(--confirm-title)]">
+ {t('billing.orders.invoice.requiredInfo')}
+ </p>
+ <ul className="mt-2 list-disc space-y-1 pl-5 text-12 leading-5 text-[var(--confirm-desc)]">
+ {INVOICE_REQUIRED_FIELDS.map((field) => (
+ <li key={field}>{t(`billing.orders.invoice.fields.${field}`)}</li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ ) : null;
+
+ return (
+ <ConfirmDialog
+ open={order !== null}
+ onOpenChange={(open) => {
+ if (open || sendInvoiceLockRef.current) return;
+ onClose();
+ }}
+ title={t('billing.orders.invoice.title')}
+ content={invoiceContent}
+ maxWidth={460}
+ confirmText={t('billing.orders.invoice.sendAction')}
+ cancelText={t('billing.actions.close')}
+ autoFocusConfirm
+ confirmIcon={<Mail className="h-3.5 w-3.5" strokeWidth={1.8} />}
+ onConfirm={sendInvoiceRequest}
+ />
+ );
+}
+
+function InvoiceInfoRow({
+ label,
+ value,
+ mono = false,
+}: {
+ label: string;
+ value: string;
+ mono?: boolean;
+}) {
+ return (
+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.35fr)] gap-3 px-3.5 py-2.5 text-12">
+ <span className="text-[var(--text-primary)]">{label}</span>
+ <span
+ className={cn(
+ 'min-w-0 break-all text-right text-[var(--text-primary)]',
+ mono && 'font-mono text-11',
+ )}
+ >
+ {value}
+ </span>
+ </div>
+ );
+}
function GrantAmount({ label, amount }: { label: string; amount: string }) {
const { i18n } = useTranslation();
const billingLocale = i18n.resolvedLanguage ?? i18n.language;
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
index cb23c1bd84..0d3784aaf7 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
@@ -62,6 +62,24 @@ vi.mock('react-i18next', () => ({
'billing.providers.stripe': 'stripe',
};
if (providerLabels[key]) return providerLabels[key];
+ if (key === 'billing.orders.invoice.emailBody') {
+ return [
+ 'Hello,',
+ '',
+ 'I would like to request an invoice for the following order:',
+ '',
+ '────────────────────',
+ `Order ID: ${params?.orderId ?? ''}`,
+ 'Application: Cindy',
+ 'Payment method: Scan to pay',
+ 'Invoice amount: CN¥33.00',
+ 'Invoice title: ',
+ 'Contact person: ',
+ 'Phone number: ',
+ 'Email: ',
+ '────────────────────',
+ ].join('\n');
+ }
return params ? `${key}:${JSON.stringify(params)}` : key;
},
}),
@@ -2919,7 +2937,7 @@ describe('BillingPage order history', () => {
maker: {
refreshBuiltinProviderModels: modelCatalogMocks.refreshBuiltinProviderModels,
},
- openExternal: vi.fn(),
+ openExternal: vi.fn(async () => ({ success: true })),
},
});
return listOrders;
@@ -2952,6 +2970,172 @@ describe('BillingPage order history', () => {
expect(screen.getByText('billing.orders.states.completed')).toBeTruthy();
});
+ it('opens a static invoice request prompt with the order details and support email', async () => {
+ const fullOrderId = 'c2309a98-d776-4ad9-99b3-418951f13c7f';
+ install([
+ order({
+ orderId: fullOrderId,
+ paymentAction: {
+ type: 'QR_CODE',
+ value: 'https://example.invalid/qr',
+ expiresAt: '2026-08-01T14:07:00.000Z',
+ },
+ }),
+ ]);
+
+ render(<BillingPage />);
+
+ fireEvent.click(await screen.findByRole('button', { name: 'billing.orders.invoice.action' }));
+
+ expect(await screen.findByRole('alertdialog')).toBeTruthy();
+ const sendButton = screen.getByRole('button', {
+ name: 'billing.orders.invoice.sendAction',
+ });
+ await waitFor(() => expect(document.activeElement).toBe(sendButton));
+ expect(screen.getByText('billing.orders.invoice.title')).toBeTruthy();
+ const supportEmailButton = screen.getByRole('button', { name: '[email protected]' });
+ expect(supportEmailButton.getAttribute('href')).toBeNull();
+ expect(screen.getByText(fullOrderId)).toBeTruthy();
+ expect(
+ within(await screen.findByRole('alertdialog')).getByText(
+ 'billing.orders.invoice.notAvailable',
+ ),
+ ).toBeTruthy();
+ expect(screen.getByText('billing.orders.invoice.fields.invoiceTitle')).toBeTruthy();
+ expect(screen.getByText('billing.orders.invoice.fields.contact')).toBeTruthy();
+ expect(screen.getByText('billing.orders.invoice.fields.phone')).toBeTruthy();
+ expect(screen.getByText('billing.orders.invoice.fields.email')).toBeTruthy();
+
+ fireEvent.click(supportEmailButton);
+ await waitFor(() => expect(uiMocks.clipboardWriteText).toHaveBeenCalledWith('[email protected]'));
+ expect(uiMocks.toastSuccess).toHaveBeenCalledWith('billing.orders.invoice.emailCopied');
+
+ fireEvent.click(screen.getByRole('button', { name: 'billing.orders.invoice.sendAction' }));
+ await waitFor(() => expect(window.electronAPI.openExternal).toHaveBeenCalledTimes(1));
+ const mailto = vi.mocked(window.electronAPI.openExternal).mock.calls[0][0] as string;
+ expect(mailto).toMatch(/^mailto:xd-billing@xd\.com\?/);
+ expect(mailto).toContain('%20');
+ expect(mailto).toContain('body=');
+ const mailBody = new URLSearchParams(mailto.split('?')[1]).get('body');
+ expect(mailBody).toContain('I would like to request an invoice for the following order:');
+ expect(mailBody).toContain('────────────────────');
+ expect(mailBody).toContain('\n\n');
+ expect(mailBody).toContain('Invoice title: ');
+ });
+
+ it('opens a prefilled Gmail compose page when the mail app cannot be opened', async () => {
+ install([order({ orderId: 'o-gmail-fallback' })]);
+ const openExternal = vi.mocked(window.electronAPI.openExternal);
+ openExternal.mockResolvedValueOnce({ success: false }).mockResolvedValueOnce({ success: true });
+ uiMocks.confirm.mockResolvedValueOnce(true);
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByRole('button', { name: 'billing.orders.invoice.action' }));
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'billing.orders.invoice.sendAction' }),
+ );
+
+ await waitFor(() => expect(openExternal).toHaveBeenCalledTimes(2));
+ const gmailUrl = new URL(openExternal.mock.calls[1][0] as string);
+ expect(gmailUrl.origin + gmailUrl.pathname).toBe('https://mail.google.com/mail/');
+ expect(gmailUrl.searchParams.get('view')).toBe('cm');
+ expect(gmailUrl.searchParams.get('fs')).toBe('1');
+ expect(gmailUrl.searchParams.get('to')).toBe('[email protected]');
+ expect(gmailUrl.searchParams.get('su')).toContain('o-gmail-fallback');
+ expect(gmailUrl.searchParams.get('body')).toContain('o-gmail-fallback');
+ expect(screen.queryByRole('alertdialog')).toBeNull();
+ expect(uiMocks.confirm).toHaveBeenCalledWith({
+ title: 'billing.orders.invoice.gmailFallbackTitle',
+ description: 'billing.orders.invoice.gmailFallbackDescription',
+ confirmText: 'billing.orders.invoice.gmailFallbackConfirm',
+ cancelText: 'billing.actions.close',
+ autoFocusConfirm: true,
+ });
+ });
+
+ it('also tries Gmail when opening the mail app rejects', async () => {
+ install([order({ orderId: 'o-gmail-rejected' })]);
+ const openExternal = vi.mocked(window.electronAPI.openExternal);
+ openExternal
+ .mockRejectedValueOnce(new Error('no mail handler'))
+ .mockResolvedValueOnce({ success: true });
+ uiMocks.confirm.mockResolvedValueOnce(true);
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByRole('button', { name: 'billing.orders.invoice.action' }));
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'billing.orders.invoice.sendAction' }),
+ );
+
+ await waitFor(() => expect(openExternal).toHaveBeenCalledTimes(2));
+ expect(openExternal.mock.calls[1][0]).toContain('https://mail.google.com/mail/?view=cm&fs=1');
+ expect(screen.queryByRole('alertdialog')).toBeNull();
+ });
+
+ it('does not open Gmail without explicit consent after the mail app fails', async () => {
+ install([order({ orderId: 'o-gmail-no-consent' })]);
+ const openExternal = vi.mocked(window.electronAPI.openExternal);
+ openExternal.mockResolvedValueOnce({ success: false });
+ uiMocks.confirm.mockResolvedValueOnce(false);
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByRole('button', { name: 'billing.orders.invoice.action' }));
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'billing.orders.invoice.sendAction' }),
+ );
+
+ await waitFor(() => expect(uiMocks.confirm).toHaveBeenCalledTimes(1));
+ expect(openExternal).toHaveBeenCalledTimes(1);
+ expect(uiMocks.toastError).toHaveBeenCalledWith(
+ 'billing.orders.invoice.sendFailed:{"email":"[email protected]"}',
+ );
+ expect(screen.getByRole('alertdialog')).toBeTruthy();
+ expect(screen.getByText('o-gmail-no-consent')).toBeTruthy();
+ });
+
+ it('ignores repeated send activations while the mail request is pending', async () => {
+ install([order({ orderId: 'o-gmail-double-click' })]);
+ const openExternal = vi.mocked(window.electronAPI.openExternal);
+ let resolveOpenExternal: ((result: { success: boolean }) => void) | undefined;
+ openExternal.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveOpenExternal = resolve;
+ }),
+ );
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByRole('button', { name: 'billing.orders.invoice.action' }));
+ const sendButton = await screen.findByRole('button', {
+ name: 'billing.orders.invoice.sendAction',
+ });
+ fireEvent.click(sendButton);
+ fireEvent.click(sendButton);
+
+ expect(openExternal).toHaveBeenCalledTimes(1);
+ resolveOpenExternal?.({ success: true });
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());
+ });
+
+ it('only offers invoice requests for completed orders', async () => {
+ install([
+ order({ orderId: 'o-completed', status: 'SUCCEEDED' }),
+ order({ orderId: 'o-pending', status: 'PENDING' }),
+ order({ orderId: 'o-failed', status: 'FAILED' }),
+ ]);
+
+ render(<BillingPage />);
+
+ await screen.findByText('billing.orders.title');
+ const invoiceButtons = screen.getAllByRole('button', {
+ name: 'billing.orders.invoice.action',
+ });
+ expect(invoiceButtons).toHaveLength(1);
+ expect(invoiceButtons[0].closest('[role="listitem"]')?.textContent).toContain(
+ 'o-com****leted',
+ );
+ });
+
it('copies the complete order id from both the id text and copy icon', async () => {
const fullOrderId = 'c2309a98-d776-4ad9-99b3-418951f13c7f';
install([order({ orderId: fullOrderId })]);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index a7a42d2eb0..904cbe21da 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -11252,6 +11252,32 @@
"success": "Order ID copied",
"failed": "Order ID wasn’t copied — try again"
},
+ "invoice": {
+ "action": "Request Invoice",
+ "title": "Request an Invoice",
+ "description": "Please email the following information to {{email}} to request an invoice.",
+ "requiredInfo": "Please include these details in your email:",
+ "emailSubject": "Invoice request for order {{orderId}}",
+ "emailBody": "Hello,\n\nI would like to request an invoice for the following order:\n\n────────────────────\nOrder ID: {{orderId}}\nApplication: {{application}}\nPayment method: {{paymentMethod}}\nInvoice amount: {{amount}}\nInvoice title: \nContact person: \nPhone number: \nEmail: \n────────────────────\n\nThank you.",
+ "sendAction": "Send Invoice Request",
+ "emailCopied": "Support email copied",
+ "emailCopyFailed": "Support email wasn’t copied — try again",
+ "sendFailed": "Couldn’t open your email app. Please email {{email}} manually.",
+ "gmailFallbackTitle": "Open Gmail instead?",
+ "gmailFallbackDescription": "Your invoice request includes order details. Opening Gmail will share this information with Google. Continue?",
+ "gmailFallbackConfirm": "Open Gmail",
+ "notAvailable": "Not available",
+ "fields": {
+ "orderId": "Order ID",
+ "application": "Application",
+ "paymentMethod": "Payment method",
+ "amount": "Invoice amount",
+ "invoiceTitle": "Invoice title",
+ "contact": "Contact person",
+ "phone": "Phone number",
+ "email": "Email"
+ }
+ },
"states": {
"completed": "Completed",
"awaitingPayment": "Awaiting payment",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 26082fa245..68e2997f7d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -11235,6 +11235,32 @@
"success": "注文 ID をコピーしました",
"failed": "注文 ID をコピーできませんでした。もう一度お試しください。"
},
+ "invoice": {
+ "action": "請求書を申請",
+ "title": "請求書を申請",
+ "description": "請求書の発行を申請するには、以下の情報を {{email}} までメールでお送りください。",
+ "requiredInfo": "メールには以下の情報を記載してください:",
+ "emailSubject": "注文 {{orderId}} の請求書発行申請",
+ "emailBody": "こんにちは。\n\n以下の注文について請求書の発行を申請します。\n\n────────────────────\n注文 ID:{{orderId}}\nアプリケーション:{{application}}\n支払い方法:{{paymentMethod}}\n請求金額:{{amount}}\n請求書宛名:\n担当者名:\n電話番号:\nメールアドレス:\n────────────────────\n\nよろしくお願いいたします。",
+ "sendAction": "請求書の申請を送信",
+ "emailCopied": "サポートメールアドレスをコピーしました",
+ "emailCopyFailed": "サポートメールアドレスをコピーできませんでした。もう一度お試しください。",
+ "sendFailed": "メールアプリを開けませんでした。{{email}} まで手動でメールをお送りください。",
+ "gmailFallbackTitle": "Gmailを開きますか?",
+ "gmailFallbackDescription": "請求書の申請には注文情報が含まれます。Gmailを開くと、この情報がGoogleに共有されます。続行しますか?",
+ "gmailFallbackConfirm": "Gmailを開く",
+ "notAvailable": "情報なし",
+ "fields": {
+ "orderId": "注文 ID",
+ "application": "アプリケーション",
+ "paymentMethod": "支払い方法",
+ "amount": "請求金額",
+ "invoiceTitle": "請求書宛名",
+ "contact": "担当者名",
+ "phone": "電話番号",
+ "email": "メールアドレス"
+ }
+ },
"states": {
"completed": "完了",
"awaitingPayment": "支払い待ち",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 4de8a4cd64..124b3666fa 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -11235,6 +11235,32 @@
"success": "주문 ID를 복사했습니다",
"failed": "주문 ID를 복사하지 못했습니다. 다시 시도해 주세요."
},
+ "invoice": {
+ "action": "세금계산서 신청",
+ "title": "세금계산서 신청",
+ "description": "세금계산서 발급을 신청하려면 다음 정보를 {{email}}로 보내 주세요.",
+ "requiredInfo": "이메일에 다음 정보를 포함해 주세요:",
+ "emailSubject": "주문 {{orderId}} 세금계산서 발급 신청",
+ "emailBody": "안녕하세요.\n\n다음 주문에 대한 세금계산서 발급을 신청합니다.\n\n────────────────────\n주문 ID: {{orderId}}\n애플리케이션: {{application}}\n결제 수단: {{paymentMethod}}\n발행 금액: {{amount}}\n청구서 제목: \n담당자: \n전화번호: \n이메일: \n────────────────────\n\n감사합니다.",
+ "sendAction": "세금계산서 신청 보내기",
+ "emailCopied": "고객센터 이메일을 복사했습니다",
+ "emailCopyFailed": "고객센터 이메일을 복사하지 못했습니다. 다시 시도해 주세요.",
+ "sendFailed": "이메일 앱을 열 수 없습니다. {{email}}로 직접 이메일을 보내 주세요.",
+ "gmailFallbackTitle": "Gmail을 대신 열까요?",
+ "gmailFallbackDescription": "청구서 신청에 주문 정보가 포함되어 있습니다. Gmail을 열면 이 정보가 Google에 공유됩니다. 계속하시겠어요?",
+ "gmailFallbackConfirm": "Gmail 열기",
+ "notAvailable": "정보 없음",
+ "fields": {
+ "orderId": "주문 ID",
+ "application": "애플리케이션",
+ "paymentMethod": "결제 수단",
+ "amount": "발행 금액",
+ "invoiceTitle": "청구서 제목",
+ "contact": "담당자",
+ "phone": "전화번호",
+ "email": "이메일"
+ }
+ },
"states": {
"completed": "완료",
"awaitingPayment": "결제 대기",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 26ea9752e2..99158f7c79 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -11235,6 +11235,32 @@
"success": "订单 ID 已复制",
"failed": "复制订单 ID 失败,请重试"
},
+ "invoice": {
+ "action": "申请开票",
+ "title": "申请开票",
+ "description": "请将以下信息发送至客服邮箱 {{email}},以申请开具发票。",
+ "requiredInfo": "邮件中请提供以下信息:",
+ "emailSubject": "申请开具订单 {{orderId}} 的发票",
+ "emailBody": "您好,\n\n我想申请开具以下订单的发票:\n\n────────────────────\n订单号:{{orderId}}\n应用:{{application}}\n支付方式:{{paymentMethod}}\n开票金额:{{amount}}\n发票抬头:\n联系人:\n联系电话:\n邮箱:\n────────────────────\n\n谢谢。",
+ "sendAction": "发送开票申请",
+ "emailCopied": "客服邮箱已复制",
+ "emailCopyFailed": "复制客服邮箱失败,请重试",
+ "sendFailed": "无法打开邮件应用,请手动发送邮件至 {{email}}。",
+ "gmailFallbackTitle": "改用 Gmail 打开?",
+ "gmailFallbackDescription": "开票申请中包含订单信息。打开 Gmail 会将这些信息分享给 Google,是否继续?",
+ "gmailFallbackConfirm": "打开 Gmail",
+ "notAvailable": "暂无信息",
+ "fields": {
+ "orderId": "订单号",
+ "application": "应用",
+ "paymentMethod": "支付方式",
+ "amount": "开票金额",
+ "invoiceTitle": "发票抬头",
+ "contact": "联系人",
+ "phone": "联系电话",
+ "email": "邮箱"
+ }
+ },
"states": {
"completed": "已完成",
"awaitingPayment": "待支付",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 3ba52c5206..7696b11f39 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -11235,6 +11235,32 @@
"success": "訂單 ID 已複製",
"failed": "複製訂單 ID 失敗,請再試一次"
},
+ "invoice": {
+ "action": "申請開票",
+ "title": "申請開票",
+ "description": "請將以下資訊寄送至客服信箱 {{email}},以申請開立發票。",
+ "requiredInfo": "郵件中請提供以下資訊:",
+ "emailSubject": "申請開立訂單 {{orderId}} 的發票",
+ "emailBody": "您好,\n\n我想申請開立以下訂單的發票:\n\n────────────────────\n訂單號:{{orderId}}\n應用程式:{{application}}\n付款方式:{{paymentMethod}}\n開票金額:{{amount}}\n發票抬頭:\n聯絡人:\n聯絡電話:\n信箱:\n────────────────────\n\n謝謝。",
+ "sendAction": "寄送開票申請",
+ "emailCopied": "客服信箱已複製",
+ "emailCopyFailed": "複製客服信箱失敗,請再試一次",
+ "sendFailed": "無法開啟郵件應用程式,請手動寄送郵件至 {{email}}。",
+ "gmailFallbackTitle": "改用 Gmail 開啟?",
+ "gmailFallbackDescription": "開票申請中包含訂單資訊。開啟 Gmail 會將這些資訊分享給 Google,是否繼續?",
+ "gmailFallbackConfirm": "開啟 Gmail",
+ "notAvailable": "暫無資訊",
+ "fields": {
+ "orderId": "訂單號",
+ "application": "應用程式",
+ "paymentMethod": "付款方式",
+ "amount": "開票金額",
+ "invoiceTitle": "發票抬頭",
+ "contact": "聯絡人",
+ "phone": "聯絡電話",
+ "email": "信箱"
+ }
+ },
"states": {
"completed": "已完成",
"awaitingPayment": "待支付",
diff --git a/apps/desktop/src/shared/__tests__/billing.test.ts b/apps/desktop/src/shared/__tests__/billing.test.ts
new file mode 100644
index 0000000000..d4a83e3010
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/billing.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+
+import { isAllowedBillingMailto, isAllowedBillingMailtoRequest } from '../billing.js';
+
+describe('billing mailto policy', () => {
+ it('allows localized subject and body for the fixed support inbox', () => {
+ expect(
+ isAllowedBillingMailto(
+ 'mailto:[email protected]?subject=Invoice%20request&body=Order%20details',
+ ),
+ ).toBe(true);
+ });
+
+ 'rejects recipient-affecting %s headers',
+ (header) => {
+ expect(isAllowedBillingMailto(`mailto:[email protected]?subject=x&${header}`)).toBe(false);
+ },
+ );
+
+ it('rejects duplicate prefill fields', () => {
+ expect(isAllowedBillingMailto('mailto:[email protected]?subject=first&subject=second')).toBe(
+ false,
+ );
+ });
+
+ it('rejects fragments that could be interpreted differently by native mail handlers', () => {
+ expect(
+ isAllowedBillingMailto('mailto:[email protected]?subject=x#&[email protected]'),
+ ).toBe(false);
+ });
+
+ it.each(['%0D%0ABcc%3Aattacker%40example.com', '%09Bcc%3Aattacker%40example.com'])
+ ('rejects control characters in the subject', (subject) => {
+ expect(
+ isAllowedBillingMailto(`mailto:[email protected]?subject=${subject}&body=details`),
+ ).toBe(false);
+ });
+
+ it('rejects alternate recipients and malformed mailto URLs', () => {
+ expect(isAllowedBillingMailto('mailto:[email protected]?subject=x')).toBe(false);
+ expect(isAllowedBillingMailto('mailto://[email protected]?subject=x')).toBe(false);
+ expect(isAllowedBillingMailto('mailto:xd-billing%40xd.com%FF?subject=x')).toBe(false);
+ });
+
+ it('requires a trusted sender in addition to the URL policy', () => {
+ expect(isAllowedBillingMailtoRequest('mailto:[email protected]?subject=x', false)).toBe(false);
+ expect(isAllowedBillingMailtoRequest('mailto:[email protected]?subject=x', true)).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/shared/billing.ts b/apps/desktop/src/shared/billing.ts
index 7c56d7a355..4f61cd51a4 100644
--- a/apps/desktop/src/shared/billing.ts
+++ b/apps/desktop/src/shared/billing.ts
@@ -7,6 +7,49 @@
import type { ModelAccessBalance, ModelAccessCreditUsage } from './modelAccess';
+export const BILLING_SUPPORT_EMAIL = '[email protected]';
+
+/**
+ * Validates the only mailto URL that Desktop may hand to the system shell.
+ * Subject/body are display data from the renderer; recipient-affecting headers
+ * must stay outside this capability boundary.
+ */
+export function isAllowedBillingMailto(value: unknown): value is string {
+ if (typeof value !== 'string') return false;
+ try {
+ const parsed = new URL(value);
+ const queryKeys = [...parsed.searchParams.keys()];
+ const hasDuplicateQueryKey = new Set(queryKeys).size !== queryKeys.length;
+ const subject = parsed.searchParams.get('subject');
+ const hasSubjectControlCharacter =
+ subject !== null && /[\u0000-\u001f\u007f-\u009f]/u.test(subject);
+ return (
+ parsed.protocol === 'mailto:' &&
+ decodeURIComponent(parsed.pathname).toLowerCase() === BILLING_SUPPORT_EMAIL &&
+ !parsed.username &&
+ !parsed.password &&
+ !parsed.host &&
+ !parsed.hash &&
+ !hasDuplicateQueryKey &&
+ !hasSubjectControlCharacter &&
+ queryKeys.every((key) => key === 'subject' || key === 'body')
+ );
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Keeps the sender check explicit at the main-process adapter boundary. The
+ * URL policy alone is not sufficient authorization for a privileged shell call.
+ */
+export function isAllowedBillingMailtoRequest(
+ value: unknown,
+ isTrustedSender: boolean,
+): value is string {
+ return isTrustedSender && isAllowedBillingMailto(value);
+}
+
export const BILLING_INVOKE = {
GET_BALANCE: 'billing:get-balance',
GET_CREDIT_USAGE: 'billing:get-credit-usage',