Feat/pricing config enhancement (#781)

* feat(db): add pricing config fields to proxy_config table

- Add default_cost_multiplier field per app type
- Add pricing_model_source field (request/response)
- Add request_model field to proxy_request_logs table
- Implement schema migration v5

* feat(api): add pricing config commands and provider meta fields

- Add get/set commands for default cost multiplier
- Add get/set commands for pricing model source
- Extend ProviderMeta with cost_multiplier and pricing_model_source
- Register new commands in Tauri invoke handler

* fix(proxy): apply cost multiplier to total cost only

- Move multiplier calculation from per-item to total cost
- Add resolve_pricing_config for provider-level override
- Include request_model and cost_multiplier in usage logs
- Return new fields in get_request_logs API

* feat(ui): add pricing config UI and usage log enhancements

- Add pricing config section to provider advanced settings
- Refactor PricingConfigPanel to compact table layout
- Display all three apps (Claude/Codex/Gemini) in one view
- Add multiplier column and request model display to logs
- Add frontend API wrappers for pricing config

* feat(i18n): add pricing config translations

- Add zh/en/ja translations for pricing defaults config
- Add translations for multiplier, requestModel, responseModel
- Add provider pricing config translations

* fix(pricing): align backfill cost calculation with real-time logic

- Fix backfill to deduct cache_read_tokens from input (avoid double billing)
- Apply multiplier only to total cost, not to each item
- Add multiplier display in request detail panel with i18n support
- Use AppError::localized for backend error messages
- Fix init_proxy_config_rows to use per-app default values
- Fix silent failure in set_default_cost_multiplier/set_pricing_model_source
- Add clippy allow annotation for test mutex across await

* style: format code with cargo fmt and prettier

* fix(tests): correct error type assertions in proxy DAO tests

The tests expected AppError::InvalidInput but the DAO functions use
AppError::localized() which returns AppError::Localized variant.
Updated assertions to match the correct error type with key validation.

---------

Co-authored-by: Jason <farion1231@gmail.com>
This commit is contained in:
Dex Miller
2026-01-27 10:43:05 +08:00
committed by GitHub
parent c00f431d67
commit 785e1b5add
27 changed files with 2123 additions and 283 deletions
+371 -136
View File
@@ -1,6 +1,5 @@
import { useState } from "react";
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Table,
TableBody,
@@ -19,10 +18,31 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useModelPricing, useDeleteModelPricing } from "@/lib/query/usage";
import { PricingEditModal } from "./PricingEditModal";
import type { ModelPricing } from "@/types/usage";
import { Plus, Pencil, Trash2, ChevronDown, ChevronRight } from "lucide-react";
import { Plus, Pencil, Trash2, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { proxyApi } from "@/lib/api/proxy";
const PRICING_APPS = ["claude", "codex", "gemini"] as const;
type PricingApp = (typeof PRICING_APPS)[number];
type PricingModelSource = "request" | "response";
interface AppConfig {
multiplier: string;
source: PricingModelSource;
}
type AppConfigState = Record<PricingApp, AppConfig>;
export function PricingConfigPanel() {
const { t } = useTranslation();
@@ -31,13 +51,137 @@ export function PricingConfigPanel() {
const [editingModel, setEditingModel] = useState<ModelPricing | null>(null);
const [isAddingNew, setIsAddingNew] = useState(false);
const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
const [isExpanded, setIsExpanded] = useState(false);
// 三个应用的配置状态
const [appConfigs, setAppConfigs] = useState<AppConfigState>({
claude: { multiplier: "1", source: "response" },
codex: { multiplier: "1", source: "response" },
gemini: { multiplier: "1", source: "response" },
});
const [originalConfigs, setOriginalConfigs] = useState<AppConfigState | null>(
null,
);
const [isConfigLoading, setIsConfigLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
// 检查是否有改动
const isDirty =
originalConfigs !== null &&
PRICING_APPS.some(
(app) =>
appConfigs[app].multiplier !== originalConfigs[app].multiplier ||
appConfigs[app].source !== originalConfigs[app].source,
);
// 加载所有应用的配置
useEffect(() => {
let isMounted = true;
const loadAllConfigs = async () => {
setIsConfigLoading(true);
try {
const results = await Promise.all(
PRICING_APPS.map(async (app) => {
const [multiplier, source] = await Promise.all([
proxyApi.getDefaultCostMultiplier(app),
proxyApi.getPricingModelSource(app),
]);
return {
app,
multiplier,
source: (source === "request"
? "request"
: "response") as PricingModelSource,
};
}),
);
if (!isMounted) return;
const newState: AppConfigState = {
claude: { multiplier: "1", source: "response" },
codex: { multiplier: "1", source: "response" },
gemini: { multiplier: "1", source: "response" },
};
for (const result of results) {
newState[result.app] = {
multiplier: result.multiplier,
source: result.source,
};
}
setAppConfigs(newState);
setOriginalConfigs(newState);
} catch (error) {
const message =
error instanceof Error
? error.message
: typeof error === "string"
? error
: "Unknown error";
toast.error(
t("settings.globalProxy.pricingLoadFailed", { error: message }),
);
} finally {
if (isMounted) setIsConfigLoading(false);
}
};
loadAllConfigs();
return () => {
isMounted = false;
};
}, [t]);
// 保存所有配置
const handleSaveAll = async () => {
// 验证所有倍率
for (const app of PRICING_APPS) {
const trimmed = appConfigs[app].multiplier.trim();
if (!trimmed) {
toast.error(
`${t(`apps.${app}`)}: ${t("settings.globalProxy.defaultCostMultiplierRequired")}`,
);
return;
}
if (!/^-?\d+(?:\.\d+)?$/.test(trimmed)) {
toast.error(
`${t(`apps.${app}`)}: ${t("settings.globalProxy.defaultCostMultiplierInvalid")}`,
);
return;
}
}
setIsSaving(true);
try {
await Promise.all(
PRICING_APPS.flatMap((app) => [
proxyApi.setDefaultCostMultiplier(
app,
appConfigs[app].multiplier.trim(),
),
proxyApi.setPricingModelSource(app, appConfigs[app].source),
]),
);
toast.success(t("settings.globalProxy.pricingSaved"));
setOriginalConfigs({ ...appConfigs });
} catch (error) {
const message =
error instanceof Error
? error.message
: typeof error === "string"
? error
: "Unknown error";
toast.error(
t("settings.globalProxy.pricingSaveFailed", { error: message }),
);
} finally {
setIsSaving(false);
}
};
const handleDelete = (modelId: string) => {
deleteMutation.mutate(modelId, {
onSuccess: () => {
setDeleteConfirm(null);
},
onSuccess: () => setDeleteConfirm(null),
});
};
@@ -55,151 +199,242 @@ export function PricingConfigPanel() {
if (isLoading) {
return (
<Card className="border rounded-lg">
<CardHeader
className="cursor-pointer"
onClick={() => setIsExpanded(!isExpanded)}
>
<div className="flex items-center gap-2">
<ChevronRight className="h-4 w-4" />
<CardTitle className="text-base">
{t("usage.modelPricing")}
</CardTitle>
</div>
</CardHeader>
</Card>
<div className="flex items-center justify-center p-4">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
);
}
if (error) {
return (
<Card className="border rounded-lg">
<CardHeader
className="cursor-pointer"
onClick={() => setIsExpanded(!isExpanded)}
>
<div className="flex items-center gap-2">
{isExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
<CardTitle className="text-base">
{t("usage.modelPricing")}
</CardTitle>
</div>
</CardHeader>
{isExpanded && (
<CardContent>
<Alert variant="destructive">
<AlertDescription>
{t("usage.loadPricingError")}: {String(error)}
</AlertDescription>
</Alert>
</CardContent>
)}
</Card>
<Alert variant="destructive">
<AlertDescription>
{t("usage.loadPricingError")}: {String(error)}
</AlertDescription>
</Alert>
);
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between mb-4">
<h4 className="text-sm font-medium text-muted-foreground">
{t("usage.modelPricingDesc")} {t("usage.perMillion")}
</h4>
<Button
onClick={(e) => {
e.stopPropagation();
handleAddNew();
}}
size="sm"
>
<Plus className="mr-1 h-4 w-4" />
{t("common.add")}
</Button>
</div>
<div className="space-y-6">
{/* 全局计费默认配置 - 紧凑表格布局 */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<div>
<h4 className="text-sm font-medium">
{t("settings.globalProxy.pricingDefaultsTitle")}
</h4>
<p className="text-xs text-muted-foreground">
{t("settings.globalProxy.pricingDefaultsDescription")}
</p>
</div>
<Button
onClick={handleSaveAll}
disabled={isConfigLoading || isSaving || !isDirty}
size="sm"
>
{isSaving ? (
<>
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
{t("common.saving")}
</>
) : (
t("common.save")
)}
</Button>
</div>
<div className="space-y-4">
{!pricing || pricing.length === 0 ? (
<Alert>
<AlertDescription>{t("usage.noPricingData")}</AlertDescription>
</Alert>
{isConfigLoading ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
) : (
<div className="rounded-md bg-card/60 shadow-sm">
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("usage.model")}</TableHead>
<TableHead>{t("usage.displayName")}</TableHead>
<TableHead className="text-right">
{t("usage.inputCost")}
</TableHead>
<TableHead className="text-right">
{t("usage.outputCost")}
</TableHead>
<TableHead className="text-right">
{t("usage.cacheReadCost")}
</TableHead>
<TableHead className="text-right">
{t("usage.cacheWriteCost")}
</TableHead>
<TableHead className="text-right">
{t("common.actions")}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{pricing.map((model) => (
<TableRow key={model.modelId}>
<TableCell className="font-mono text-sm">
{model.modelId}
</TableCell>
<TableCell>{model.displayName}</TableCell>
<TableCell className="text-right font-mono text-sm">
${model.inputCostPerMillion}
</TableCell>
<TableCell className="text-right font-mono text-sm">
${model.outputCostPerMillion}
</TableCell>
<TableCell className="text-right font-mono text-sm">
${model.cacheReadCostPerMillion}
</TableCell>
<TableCell className="text-right font-mono text-sm">
${model.cacheCreationCostPerMillion}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-1">
<Button
variant="ghost"
size="icon"
onClick={() => {
setIsAddingNew(false);
setEditingModel(model);
}}
title={t("common.edit")}
>
<Pencil className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => setDeleteConfirm(model.modelId)}
title={t("common.delete")}
className="text-destructive hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
<div className="rounded-md border border-border/50 overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border/50 bg-muted/30">
<th className="px-3 py-2 text-left font-medium text-muted-foreground w-24">
{t("settings.globalProxy.pricingAppLabel")}
</th>
<th className="px-3 py-2 text-left font-medium text-muted-foreground">
{t("settings.globalProxy.defaultCostMultiplierLabel")}
</th>
<th className="px-3 py-2 text-left font-medium text-muted-foreground">
{t("settings.globalProxy.pricingModelSourceLabel")}
</th>
</tr>
</thead>
<tbody>
{PRICING_APPS.map((app, idx) => (
<tr
key={app}
className={
idx < PRICING_APPS.length - 1
? "border-b border-border/30"
: ""
}
>
<td className="px-3 py-1.5 font-medium">
{t(`apps.${app}`)}
</td>
<td className="px-3 py-1.5">
<Input
type="number"
step="0.01"
inputMode="decimal"
value={appConfigs[app].multiplier}
onChange={(e) =>
setAppConfigs((prev) => ({
...prev,
[app]: { ...prev[app], multiplier: e.target.value },
}))
}
disabled={isSaving}
placeholder="1"
className="h-7 w-24"
/>
</td>
<td className="px-3 py-1.5">
<Select
value={appConfigs[app].source}
onValueChange={(value) =>
setAppConfigs((prev) => ({
...prev,
[app]: {
...prev[app],
source: value as PricingModelSource,
},
}))
}
disabled={isSaving}
>
<SelectTrigger className="h-7 w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="response">
{t(
"settings.globalProxy.pricingModelSourceResponse",
)}
</SelectItem>
<SelectItem value="request">
{t(
"settings.globalProxy.pricingModelSourceRequest",
)}
</SelectItem>
</SelectContent>
</Select>
</td>
</tr>
))}
</TableBody>
</Table>
</tbody>
</table>
</div>
)}
</div>
{/* 分隔线 */}
<div className="border-t border-border/50" />
{/* 模型定价配置 */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h4 className="text-sm font-medium text-muted-foreground">
{t("usage.modelPricingDesc")} {t("usage.perMillion")}
</h4>
<Button
onClick={(e) => {
e.stopPropagation();
handleAddNew();
}}
size="sm"
>
<Plus className="mr-1 h-4 w-4" />
{t("common.add")}
</Button>
</div>
<div className="space-y-4">
{!pricing || pricing.length === 0 ? (
<Alert>
<AlertDescription>{t("usage.noPricingData")}</AlertDescription>
</Alert>
) : (
<div className="rounded-md bg-card/60 shadow-sm">
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("usage.model")}</TableHead>
<TableHead>{t("usage.displayName")}</TableHead>
<TableHead className="text-right">
{t("usage.inputCost")}
</TableHead>
<TableHead className="text-right">
{t("usage.outputCost")}
</TableHead>
<TableHead className="text-right">
{t("usage.cacheReadCost")}
</TableHead>
<TableHead className="text-right">
{t("usage.cacheWriteCost")}
</TableHead>
<TableHead className="text-right">
{t("common.actions")}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{pricing.map((model) => (
<TableRow key={model.modelId}>
<TableCell className="font-mono text-sm">
{model.modelId}
</TableCell>
<TableCell>{model.displayName}</TableCell>
<TableCell className="text-right font-mono text-sm">
${model.inputCostPerMillion}
</TableCell>
<TableCell className="text-right font-mono text-sm">
${model.outputCostPerMillion}
</TableCell>
<TableCell className="text-right font-mono text-sm">
${model.cacheReadCostPerMillion}
</TableCell>
<TableCell className="text-right font-mono text-sm">
${model.cacheCreationCostPerMillion}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-1">
<Button
variant="ghost"
size="icon"
onClick={() => {
setIsAddingNew(false);
setEditingModel(model);
}}
title={t("common.edit")}
>
<Pencil className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => setDeleteConfirm(model.modelId)}
title={t("common.delete")}
className="text-destructive hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</div>
</div>
{editingModel && (
<PricingEditModal
open={!!editingModel}
+31 -1
View File
@@ -184,6 +184,9 @@ export function RequestDetailPanel({
<div>
<dt className="text-muted-foreground">
{t("usage.inputCost", "输入成本")}
<span className="ml-1 text-xs">
({t("usage.baseCost", "基础")})
</span>
</dt>
<dd className="font-mono">
${parseFloat(request.inputCostUsd).toFixed(6)}
@@ -192,6 +195,9 @@ export function RequestDetailPanel({
<div>
<dt className="text-muted-foreground">
{t("usage.outputCost", "输出成本")}
<span className="ml-1 text-xs">
({t("usage.baseCost", "基础")})
</span>
</dt>
<dd className="font-mono">
${parseFloat(request.outputCostUsd).toFixed(6)}
@@ -200,6 +206,9 @@ export function RequestDetailPanel({
<div>
<dt className="text-muted-foreground">
{t("usage.cacheReadCost", "缓存读取成本")}
<span className="ml-1 text-xs">
({t("usage.baseCost", "基础")})
</span>
</dt>
<dd className="font-mono">
${parseFloat(request.cacheReadCostUsd).toFixed(6)}
@@ -208,14 +217,35 @@ export function RequestDetailPanel({
<div>
<dt className="text-muted-foreground">
{t("usage.cacheCreationCost", "缓存写入成本")}
<span className="ml-1 text-xs">
({t("usage.baseCost", "基础")})
</span>
</dt>
<dd className="font-mono">
${parseFloat(request.cacheCreationCostUsd).toFixed(6)}
</dd>
</div>
<div className="col-span-2 border-t pt-3">
{/* 显示成本倍率(如果不等于1) */}
{request.costMultiplier &&
parseFloat(request.costMultiplier) !== 1 && (
<div className="col-span-2 border-t pt-3">
<dt className="text-muted-foreground">
{t("usage.costMultiplier", "成本倍率")}
</dt>
<dd className="font-mono">×{request.costMultiplier}</dd>
</div>
)}
<div
className={`col-span-2 ${request.costMultiplier && parseFloat(request.costMultiplier) !== 1 ? "" : "border-t"} pt-3`}
>
<dt className="text-muted-foreground">
{t("usage.totalCost", "总成本")}
{request.costMultiplier &&
parseFloat(request.costMultiplier) !== 1 && (
<span className="ml-1 text-xs">
({t("usage.withMultiplier", "含倍率")})
</span>
)}
</dt>
<dd className="text-lg font-semibold text-primary">
${parseFloat(request.totalCostUsd).toFixed(6)}
+33 -7
View File
@@ -250,7 +250,7 @@ export function RequestLogTable() {
<TableHead className="whitespace-nowrap">
{t("usage.provider")}
</TableHead>
<TableHead className="min-w-[280px] whitespace-nowrap">
<TableHead className="min-w-[200px] whitespace-nowrap">
{t("usage.billingModel")}
</TableHead>
<TableHead className="text-right whitespace-nowrap">
@@ -265,6 +265,9 @@ export function RequestLogTable() {
<TableHead className="text-right min-w-[90px] whitespace-nowrap">
{t("usage.cacheCreationTokens")}
</TableHead>
<TableHead className="text-right whitespace-nowrap">
{t("usage.multiplier")}
</TableHead>
<TableHead className="text-right whitespace-nowrap">
{t("usage.totalCost")}
</TableHead>
@@ -280,7 +283,7 @@ export function RequestLogTable() {
{logs.length === 0 ? (
<TableRow>
<TableCell
colSpan={10}
colSpan={11}
className="text-center text-muted-foreground"
>
{t("usage.noData")}
@@ -297,11 +300,25 @@ export function RequestLogTable() {
<TableCell>
{log.providerName || t("usage.unknownProvider")}
</TableCell>
<TableCell
className="font-mono text-sm max-w-[280px] truncate"
title={log.model}
>
{log.model}
<TableCell className="font-mono text-xs max-w-[200px]">
<div
className="truncate"
title={
log.requestModel && log.requestModel !== log.model
? `${t("usage.requestModel")}: ${log.requestModel}\n${t("usage.responseModel")}: ${log.model}`
: log.model
}
>
{log.model}
</div>
{log.requestModel && log.requestModel !== log.model && (
<div
className="truncate text-muted-foreground text-[10px]"
title={log.requestModel}
>
{log.requestModel}
</div>
)}
</TableCell>
<TableCell className="text-right">
{log.inputTokens.toLocaleString()}
@@ -315,6 +332,15 @@ export function RequestLogTable() {
<TableCell className="text-right">
{log.cacheCreationTokens.toLocaleString()}
</TableCell>
<TableCell className="text-right font-mono text-xs">
{parseFloat(log.costMultiplier) !== 1 ? (
<span className="text-orange-600">
×{log.costMultiplier}
</span>
) : (
<span className="text-muted-foreground">×1</span>
)}
</TableCell>
<TableCell className="text-right">
${parseFloat(log.totalCostUsd).toFixed(6)}
</TableCell>