diff --git a/.gitignore b/.gitignore
index ea3076a05..122dc428d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -169,5 +169,6 @@ issues/
scripts/*
!scripts/release/
!scripts/release/**
+!scripts/sync-upstream-migration-checksums.sh
__pycache__/
*.pyc
diff --git a/Makefile b/Makefile
index 55d9b7353..4a853cefd 100644
--- a/Makefile
+++ b/Makefile
@@ -5,6 +5,7 @@ FRONTEND_CRITICAL_VITEST := \
src/api/__tests__/client.spec.ts \
src/api/__tests__/tokenRefresh.spec.ts \
src/api/__tests__/keys.bulkUpdate.spec.ts \
+ src/composables/__tests__/useModelWhitelist.spec.ts \
src/components/account/__tests__/OpenAIReferralCell.spec.ts \
src/components/account/__tests__/OpenAIReferralCell.transport.spec.ts \
src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \
diff --git a/README_CN.md b/README_CN.md
index 0c68b3620..0922e6f3d 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -55,8 +55,8 @@
-
-感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过此链接 注册,首次充值可额外获得 10% 赠送额度!
+
+感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过此链接 注册,首次充值可额外获得 10% 赠送额度!
@@ -64,11 +64,6 @@
Real GPT-5.6 series at 3% of OpenAI pricing — CodexEverywhere is democratizing access to frontier models for developers worldwide. We believe in transparency and honesty, with model quality verified by active community oversight for months. USD and crypto friendly. Start with a free $20 trial at codex-everywhere.com .
-
-
-感谢 BmoPlus 赞助了本项目!BmoPlus 是一家专为AI订阅重度用户打造的可靠 AI 账号代充服务商,提供稳定的 ChatGPT Plus / ChatGPT Pro(全程质保) / Claude Pro / Super Grok / Gemini Pro 的官方代充&成品账号。 通过BmoPlus AI成品号专卖/代充 注册下单的用户,可享GPT 官网订阅一折 的震撼价格!
-
-
感谢 Bestproxy 赞助了本项目!Bestproxy 是一家提供高纯度住宅IP,支持一号一IP独享,结合真实家庭网络与指纹隔离,可实现链路环境隔离,降低关联风控概率。
@@ -99,18 +94,6 @@
-
-
-感谢 Proxy4Free 赞助本项目!Proxy4Free 是面向开发者和 AI 应用的数据代理服务商,提供住宅代理、静态住宅代理、ISP 代理及数据中心代理等多种代理解决方案,适用于 Web Scraping、Browser Automation、AI Agent 等场景。支持全球 IP 资源、稳定连接与灵活切换,帮助开发者提升数据采集成功率,降低 IP 封禁风险。通过此链接注册 即可开始体验,轻松构建更稳定、高效的自动化工作流。
-
-
-
-
-
-感谢 Aimzoon 对本项目的赞助! Aimzoon 提供稳定、高性价比的 AI API 接入服务,支持开发者将常用 AI 服务快速接入 Codex、Claude Code、Gemini CLI 等编程工具。无需复杂配置,更快接入,更稳调用,更省成本。codex倍率优惠,特价倍率等促销不断,注册即送免费体验额度,让 AI 编程真正进入日常工作流。点击这里 注册体验!
-
-
-
Nagora 是专为开发者和团队打造的多模型 AI API 网关。通过一个账户和一枚 API Key,即可统一调用 26+ 款主流文本与图像模型,兼容 OpenAI、Anthropic 与 Gemini 协议,并可无缝接入 Claude Code、Codex、Gemini CLI 等开发工具。平台提供智能路由、自动故障转移、透明计费与统一账单,同时支持预算、限速、并发控制,让个人开发、团队协作和生产环境中的 AI 调用更稳定、更可控。无需改造现有应用,只需替换 Base URL 与 API Key,最快 1 分钟即可完成接入。
@@ -146,11 +129,6 @@
Swiftproxy 是面向开发者的高性能代理解决方案,提供稳定可靠的住宅代理和静态住宅代理服务。拥有 9000 万+ 纯净住宅 IP,覆盖全球,支持灵活轮换和精准地理定位,帮助网页抓取、AI 自动化、浏览器自动化、SEO 监控和多账号管理等项目突破访问限制,提升工作流效率。支持 HTTP(S) 和 SOCKS5 协议,兼容 Playwright、Selenium、Puppeteer 等主流自动化工具,动态代理流量用完为止永不过期,支持免费测试 — 立即开始免费测试 !
-
-
-DuckIP - 9000 万+ 全球住宅网络资源,覆盖 195+ 国家和地区,支持轮换和粘性会话,适用于公共数据采集、RAG 更新、模型评估和多区域数据工作负载。🟢住宅代理 - 8 折优惠;🟢静态住宅代理 - ¥50.00/IP 起;🟢无限住宅代理 - ¥19.8/小时 起。✅免费领取 500M 试用流量。
-
-
感谢 APIMart 赞助了本项目!APIMart 是专注于 AI 图片/视频生成的低价 API 平台,GPT-Image-2 低至 $0.006/张,1 美元可生成 160+ 张图片。图片、视频一套异步 API 通吃:提交任务获取 ID,通过轮询或回调获取结果;批量生成上万张图片也不会超时,切换模型无需修改代码。按量付费、无月费,通过此注册链接 注册即可开始使用。
@@ -171,6 +149,11 @@
ColaProxy 提供专为网页抓取、自动化和多账号管理打造的高质量住宅代理。免费试用,流量永不过期,价格低至 $0.3/GB,支持无限并发连接和智能 IP 轮换,带来更流畅、更稳定的代理体验。使用优惠码 COLA10 立享 9 折优惠,立即开始使用可靠的住宅代理扩展您的项目。立即开始使用 ColaProxy
+
+
+Modelflare:满血稳定不掺水,低成本享受全球 SOTA 模型。站点由美国 LLC 主体 Havenbyte LLC 运营,支持 GPT、Claude、Gemini、Grok 等主流模型和常用兼容协议,还支持 40 多种图片和视频模型。缓存补偿是一大亮点:部分 OpenAI 价格优先、稳定和高级分组提供每日 65%、75%、85% 的缓存命中率保障,符合条件的请求没达到目标的,平台补偿差额,结算后可在用量看板查看。特惠活动:单笔充值 US$20 即可解锁 0.015 倍价格倍率的 GPT 特惠分组,单笔充值 US$50 即可解锁 0.03 倍价格倍率的 Claude 特惠分组。通过专属链接 注册即可参与
+
+
## 项目概述
diff --git a/README_JA.md b/README_JA.md
index 26b9d0944..050601e63 100644
--- a/README_JA.md
+++ b/README_JA.md
@@ -54,8 +54,8 @@
-
-AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:こちらのリンク から登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント!
+
+AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:こちらのリンク から登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント!
@@ -63,11 +63,6 @@
OpenAI 公式価格のわずか 3% で本物の GPT-5.6 シリーズを提供 — CodexEverywhere は世界中の開発者にフロンティアモデルへのアクセスを民主化しています。私たちは透明性と誠実さを信条とし、モデル品質は数か月にわたるアクティブなコミュニティの監視によって検証されています。USD および暗号通貨に対応。codex-everywhere.com で $20 の無料トライアルから始めましょう。
-
-
-本プロジェクトにご支援いただいた BmoPlus に感謝いたします!BmoPlusは、AIサブスクリプションのヘビーユーザー向けに特化した信頼性の高いAIアカウントサービスプロバイダーであり、安定した ChatGPT Plus / ChatGPT Pro (完全保証) / Claude Pro / Super Grok / Gemini Pro の公式代行チャージおよび即納アカウントを提供しています。こちらのBmoPlus AIアカウント専門店/代行チャージ 経由でご登録・ご注文いただいたユーザー様は、GPTを 公式サイト価格の約1割(90% OFF) という驚異的な価格でご利用いただけます!
-
-
Bestproxy のご支援に感謝します!Bestproxy は高純度の住宅IPを提供し、1アカウント1IP専有をサポートしています。実際の家庭ネットワークとフィンガープリント分離を組み合わせることで、リンク環境の分離を実現し、関連付けによるリスク管理の確率を低減します。
@@ -98,18 +93,6 @@
-
-
-Proxy4Free のご支援に感謝します!Proxy4Free は開発者と AI アプリケーション向けのデータプロキシサービスプロバイダーで、住宅プロキシ、静的住宅プロキシ、ISP プロキシ、データセンタープロキシなど多様なプロキシソリューションを提供しており、Web Scraping、Browser Automation、AI Agent などのシナリオに適しています。グローバル IP リソース、安定した接続、柔軟な切り替えをサポートし、開発者のデータ収集成功率の向上と IP ブロックリスクの低減を支援します。こちらのリンクから登録 して、より安定した効率的な自動化ワークフローを簡単に構築しましょう。
-
-
-
-
-
-Aimzoon のご支援に感謝します!Aimzoon は安定してコストパフォーマンスに優れた AI API 接続サービスを提供し、開発者が主要な AI サービスを Codex、Claude Code、Gemini CLI などのコーディングツールへ素早く接続できるようにします。複雑な設定は不要で、より速い接続、より安定した呼び出し、より低いコストを実現。Codex レート割引や特価レートなどのキャンペーンも随時開催中、登録するだけで無料お試しクレジットをプレゼント。AI コーディングを日常のワークフローへ。こちら から登録してお試しください!
-
-
-
Nagora は、開発者やチーム向けに設計されたマルチモデルAI APIゲートウェイです。1つのアカウントと1つのAPIキーだけで、26種類以上の主要なテキストモデルおよび画像モデルを一元的に利用できます。OpenAI、Anthropic、Geminiの各プロトコルに対応し、Claude Code、Codex、Gemini CLIなどの開発ツールにもシームレスに接続できます。 プラットフォームには、インテリジェントルーティング、自動フェイルオーバー、透明性の高い料金体系、請求の一元管理に加え、予算管理、レート制限、同時実行数の制御機能が備わっています。これにより、個人開発、チームでの共同作業、本番環境におけるAI APIの利用を、より安定的かつ柔軟に管理できます。 既存のアプリケーションを改修する必要はありません。Base URLとAPIキーを置き換えるだけで、最短1分で導入を完了できます。
@@ -145,11 +128,6 @@
Swiftproxy は開発者向けの高性能プロキシソリューションで、安定して信頼できるレジデンシャルおよび静的レジデンシャルプロキシサービスを提供します。9,000 万以上のクリーンな住宅 IP を保有し、グローバルカバレッジ、柔軟なローテーション、精密なジオターゲティングにより、Web スクレイピング、AI オートメーション、ブラウザ自動化、SEO モニタリング、マルチアカウント管理などのプロジェクトがアクセス制限を克服し、ワークフロー効率を向上させます。HTTP(S) および SOCKS5 プロトコルに対応し、Playwright、Selenium、Puppeteer などの主要な自動化ツールと統合可能。動的プロキシトラフィックは使い切るまで期限切れなし、無料テストも利用可能 — 今すぐ無料テストを開始 !
-
-
-DuckIP - 195 以上の国と地域にわたる 9,000 万以上のグローバルレジデンシャルネットワークリソース。ローテーションとスティッキーセッションに対応し、パブリックデータ収集、RAG 更新、モデル評価、マルチリージョンデータワークロードに最適。🟢レジデンシャルプロキシ - 20% オフ;🟢スタティックレジデンシャルプロキシ - ¥50.00/IP から;🟢無制限レジデンシャルプロキシ - ¥19.8/時間 から。✅500M 無料トライアルを取得。
-
-
APIMart のご支援に感謝します!APIMart は AI 画像・動画生成に特化した低価格 API プラットフォームです。GPT-Image-2 は 1 枚 $0.006 から、1 ドルで 160 枚以上の画像を生成できます。画像と動画の両方に対応する非同期 API を 1 つで利用でき、タスクを送信して ID を取得し、ポーリングまたはコールバックで結果を取得できます。数万枚規模のバッチ処理でもタイムアウトせず、モデルを変更してもコードの変更は不要です。月額料金なしの従量課金制で、こちらの登録リンク からすぐに利用を開始できます。
@@ -170,6 +148,11 @@
ColaProxy は、Web スクレイピング、自動化、マルチアカウント管理向けに構築された高品質な住宅プロキシを提供します。有効期限なしのトラフィックで無料トライアルが利用でき、料金は $0.3/GB から、無制限の同時接続とインテリジェントな IP ローテーションにより、よりスムーズで安定したプロキシ体験を実現します。割引コード COLA10 で 10% オフ、信頼性の高い住宅プロキシでプロジェクトを今すぐスケールしましょう。ColaProxy を始める
+
+
+Modelflare:フルスペック、安定、水増しなし。世界の SOTA モデルを、より低いコストで。米国拠点の Havenbyte LLC が運営する Modelflare は、一般的な互換プロトコルを通じて GPT、Claude、Gemini、Grok などの主要モデルに対応し、さらに 40 以上の画像・動画モデルも利用できます。注目はキャッシュ補償です。対象の OpenAI グループ(価格優先・安定・プレミアム)は、1 日のキャッシュヒット率をそれぞれ 65%、75%、85% で保証します。対象リクエストがこの水準に達しない場合、Modelflare が差額を返金し、精算後に利用状況ダッシュボードで確認できます。特別オファー:US$20 を 1 回チャージすると、価格倍率 0.015 倍の GPT 割引グループが解放されます。US$50 を 1 回チャージすると、価格倍率 0.03 倍の Claude 割引グループが解放されます。こちらの専用リンク から登録して始めましょう。
+
+
## 概要
diff --git a/assets/partners/logos/aimzoon.jpg b/assets/partners/logos/aimzoon.jpg
deleted file mode 100644
index 3fa8c653c..000000000
Binary files a/assets/partners/logos/aimzoon.jpg and /dev/null differ
diff --git a/assets/partners/logos/modelflare.png b/assets/partners/logos/modelflare.png
new file mode 100644
index 000000000..d596cf8d5
Binary files /dev/null and b/assets/partners/logos/modelflare.png differ
diff --git a/assets/partners/logos/proxy4free.png b/assets/partners/logos/proxy4free.png
deleted file mode 100644
index c80741e4c..000000000
Binary files a/assets/partners/logos/proxy4free.png and /dev/null differ
diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION
index 5ed5faa5f..9ee1f786d 100644
--- a/backend/cmd/server/VERSION
+++ b/backend/cmd/server/VERSION
@@ -1 +1 @@
-1.1.10
+1.1.11
diff --git a/backend/cmd/server/wire.go b/backend/cmd/server/wire.go
index f279b354c..47034cf2f 100644
--- a/backend/cmd/server/wire.go
+++ b/backend/cmd/server/wire.go
@@ -104,6 +104,7 @@ func provideCleanup(
subscriptionExpiry *service.SubscriptionExpiryService,
usageCleanup *service.UsageCleanupService,
idempotencyCleanup *service.IdempotencyCleanupService,
+ geminiCachedContent *service.GeminiCachedContentService,
batchImageCleanup *service.BatchImageCleanupService,
batchImageWorker *service.BatchImageWorkerRuntime,
pricing *service.PricingService,
@@ -244,6 +245,12 @@ func provideCleanup(
}
return nil
}},
+ {"GeminiCachedContentService", func() error {
+ if geminiCachedContent != nil {
+ geminiCachedContent.Stop()
+ }
+ return nil
+ }},
{"BatchImageCleanupService", func() error {
if batchImageCleanup != nil {
batchImageCleanup.Stop()
diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go
index 71dc8aa65..e03eb7170 100644
--- a/backend/cmd/server/wire_gen.go
+++ b/backend/cmd/server/wire_gen.go
@@ -297,7 +297,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
userMessageQueueService := service.ProvideUserMessageQueueService(userMsgQueueCache, rpmCache, configConfig)
legacyEngine := securityaudit.NewLegacyModerationAdapter(contentModerationService)
coordinator := securityaudit.NewCoordinator(legacyEngine, promptService)
- gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator)
+ geminiCachedContentRepository := repository.NewGeminiCachedContentRepository(db)
+ geminiCachedContentService := service.ProvideGeminiCachedContentService(geminiCachedContentRepository, geminiMessagesCompatService, configConfig)
+ gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator, geminiCachedContentService)
openAIGatewayHandler := handler.ProvideOpenAIGatewayHandler(openAIGatewayService, pluginManager, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, opsService, grokQuotaService, configConfig, coordinator, compositeRouteResolver)
handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo, notificationEmailService)
totpHandler := handler.NewTotpHandler(totpService)
@@ -354,7 +356,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher)
channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService)
userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService)
- v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
+ v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
application := &Application{
Server: httpServer,
PromptAudit: promptService,
@@ -414,6 +416,7 @@ func provideCleanup(
subscriptionExpiry *service.SubscriptionExpiryService,
usageCleanup *service.UsageCleanupService,
idempotencyCleanup *service.IdempotencyCleanupService,
+ geminiCachedContent *service.GeminiCachedContentService,
batchImageCleanup *service.BatchImageCleanupService,
batchImageWorker *service.BatchImageWorkerRuntime,
pricing *service.PricingService,
@@ -553,6 +556,12 @@ func provideCleanup(
}
return nil
}},
+ {"GeminiCachedContentService", func() error {
+ if geminiCachedContent != nil {
+ geminiCachedContent.Stop()
+ }
+ return nil
+ }},
{"BatchImageCleanupService", func() error {
if batchImageCleanup != nil {
batchImageCleanup.Stop()
diff --git a/backend/cmd/server/wire_gen_test.go b/backend/cmd/server/wire_gen_test.go
index 384aebf68..4f083e795 100644
--- a/backend/cmd/server/wire_gen_test.go
+++ b/backend/cmd/server/wire_gen_test.go
@@ -74,6 +74,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
subscriptionExpirySvc,
&service.UsageCleanupService{},
idempotencyCleanupSvc,
+ service.NewGeminiCachedContentService(nil, nil, cfg),
&service.BatchImageCleanupService{},
nil, // batchImageWorker
pricingSvc,
diff --git a/backend/ent/group.go b/backend/ent/group.go
index b8aa08709..c602202bf 100644
--- a/backend/ent/group.go
+++ b/backend/ent/group.go
@@ -30,6 +30,8 @@ type Group struct {
Name string `json:"name,omitempty"`
// Description holds the value of the "description" field.
Description *string `json:"description,omitempty"`
+ // 名称与描述的界面语言译文:语言代码 -> {name, description};缺失的语言沿用 name/description
+ I18n domain.GroupI18n `json:"i18n,omitempty"`
// RateMultiplier holds the value of the "rate_multiplier" field.
RateMultiplier float64 `json:"rate_multiplier,omitempty"`
// 是否启用高峰时段倍率
@@ -258,7 +260,7 @@ func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
- case group.FieldVideoModelPrices, group.FieldModelPricing, group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelAllowlist, group.FieldCodexModelsManifestConfig, group.FieldReasoningEffortMappings:
+ case group.FieldI18n, group.FieldVideoModelPrices, group.FieldModelPricing, group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelAllowlist, group.FieldCodexModelsManifestConfig, group.FieldReasoningEffortMappings:
values[i] = new([]byte)
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
values[i] = new(sql.NullBool)
@@ -323,6 +325,14 @@ func (_m *Group) assignValues(columns []string, values []any) error {
_m.Description = new(string)
*_m.Description = value.String
}
+ case group.FieldI18n:
+ if value, ok := values[i].(*[]byte); !ok {
+ return fmt.Errorf("unexpected type %T for field i18n", values[i])
+ } else if value != nil && len(*value) > 0 {
+ if err := json.Unmarshal(*value, &_m.I18n); err != nil {
+ return fmt.Errorf("unmarshal field i18n: %w", err)
+ }
+ }
case group.FieldRateMultiplier:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field rate_multiplier", values[i])
@@ -817,6 +827,9 @@ func (_m *Group) String() string {
builder.WriteString(*v)
}
builder.WriteString(", ")
+ builder.WriteString("i18n=")
+ builder.WriteString(fmt.Sprintf("%v", _m.I18n))
+ builder.WriteString(", ")
builder.WriteString("rate_multiplier=")
builder.WriteString(fmt.Sprintf("%v", _m.RateMultiplier))
builder.WriteString(", ")
diff --git a/backend/ent/group/group.go b/backend/ent/group/group.go
index e978df85c..182636bfa 100644
--- a/backend/ent/group/group.go
+++ b/backend/ent/group/group.go
@@ -26,6 +26,8 @@ const (
FieldName = "name"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
+ // FieldI18n holds the string denoting the i18n field in the database.
+ FieldI18n = "i18n"
// FieldRateMultiplier holds the string denoting the rate_multiplier field in the database.
FieldRateMultiplier = "rate_multiplier"
// FieldPeakRateEnabled holds the string denoting the peak_rate_enabled field in the database.
@@ -228,6 +230,7 @@ var Columns = []string{
FieldDeletedAt,
FieldName,
FieldDescription,
+ FieldI18n,
FieldRateMultiplier,
FieldPeakRateEnabled,
FieldPeakStart,
@@ -326,6 +329,8 @@ var (
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
+ // DefaultI18n holds the default value on creation for the "i18n" field.
+ DefaultI18n domain.GroupI18n
// DefaultRateMultiplier holds the default value on creation for the "rate_multiplier" field.
DefaultRateMultiplier float64
// DefaultPeakRateEnabled holds the default value on creation for the "peak_rate_enabled" field.
diff --git a/backend/ent/group_create.go b/backend/ent/group_create.go
index 940577850..42b33cab7 100644
--- a/backend/ent/group_create.go
+++ b/backend/ent/group_create.go
@@ -92,6 +92,12 @@ func (_c *GroupCreate) SetNillableDescription(v *string) *GroupCreate {
return _c
}
+// SetI18n sets the "i18n" field.
+func (_c *GroupCreate) SetI18n(v domain.GroupI18n) *GroupCreate {
+ _c.mutation.SetI18n(v)
+ return _c
+}
+
// SetRateMultiplier sets the "rate_multiplier" field.
func (_c *GroupCreate) SetRateMultiplier(v float64) *GroupCreate {
_c.mutation.SetRateMultiplier(v)
@@ -1047,6 +1053,10 @@ func (_c *GroupCreate) defaults() error {
v := group.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
+ if _, ok := _c.mutation.I18n(); !ok {
+ v := group.DefaultI18n
+ _c.mutation.SetI18n(v)
+ }
if _, ok := _c.mutation.RateMultiplier(); !ok {
v := group.DefaultRateMultiplier
_c.mutation.SetRateMultiplier(v)
@@ -1230,6 +1240,9 @@ func (_c *GroupCreate) check() error {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Group.name": %w`, err)}
}
}
+ if _, ok := _c.mutation.I18n(); !ok {
+ return &ValidationError{Name: "i18n", err: errors.New(`ent: missing required field "Group.i18n"`)}
+ }
if _, ok := _c.mutation.RateMultiplier(); !ok {
return &ValidationError{Name: "rate_multiplier", err: errors.New(`ent: missing required field "Group.rate_multiplier"`)}
}
@@ -1465,6 +1478,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_spec.SetField(group.FieldDescription, field.TypeString, value)
_node.Description = &value
}
+ if value, ok := _c.mutation.I18n(); ok {
+ _spec.SetField(group.FieldI18n, field.TypeJSON, value)
+ _node.I18n = value
+ }
if value, ok := _c.mutation.RateMultiplier(); ok {
_spec.SetField(group.FieldRateMultiplier, field.TypeFloat64, value)
_node.RateMultiplier = value
@@ -1925,6 +1942,18 @@ func (u *GroupUpsert) ClearDescription() *GroupUpsert {
return u
}
+// SetI18n sets the "i18n" field.
+func (u *GroupUpsert) SetI18n(v domain.GroupI18n) *GroupUpsert {
+ u.Set(group.FieldI18n, v)
+ return u
+}
+
+// UpdateI18n sets the "i18n" field to the value that was provided on create.
+func (u *GroupUpsert) UpdateI18n() *GroupUpsert {
+ u.SetExcluded(group.FieldI18n)
+ return u
+}
+
// SetRateMultiplier sets the "rate_multiplier" field.
func (u *GroupUpsert) SetRateMultiplier(v float64) *GroupUpsert {
u.Set(group.FieldRateMultiplier, v)
@@ -3039,6 +3068,20 @@ func (u *GroupUpsertOne) ClearDescription() *GroupUpsertOne {
})
}
+// SetI18n sets the "i18n" field.
+func (u *GroupUpsertOne) SetI18n(v domain.GroupI18n) *GroupUpsertOne {
+ return u.Update(func(s *GroupUpsert) {
+ s.SetI18n(v)
+ })
+}
+
+// UpdateI18n sets the "i18n" field to the value that was provided on create.
+func (u *GroupUpsertOne) UpdateI18n() *GroupUpsertOne {
+ return u.Update(func(s *GroupUpsert) {
+ s.UpdateI18n()
+ })
+}
+
// SetRateMultiplier sets the "rate_multiplier" field.
func (u *GroupUpsertOne) SetRateMultiplier(v float64) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
@@ -4485,6 +4528,20 @@ func (u *GroupUpsertBulk) ClearDescription() *GroupUpsertBulk {
})
}
+// SetI18n sets the "i18n" field.
+func (u *GroupUpsertBulk) SetI18n(v domain.GroupI18n) *GroupUpsertBulk {
+ return u.Update(func(s *GroupUpsert) {
+ s.SetI18n(v)
+ })
+}
+
+// UpdateI18n sets the "i18n" field to the value that was provided on create.
+func (u *GroupUpsertBulk) UpdateI18n() *GroupUpsertBulk {
+ return u.Update(func(s *GroupUpsert) {
+ s.UpdateI18n()
+ })
+}
+
// SetRateMultiplier sets the "rate_multiplier" field.
func (u *GroupUpsertBulk) SetRateMultiplier(v float64) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
diff --git a/backend/ent/group_update.go b/backend/ent/group_update.go
index 29c04ecb0..c3bd82c35 100644
--- a/backend/ent/group_update.go
+++ b/backend/ent/group_update.go
@@ -97,6 +97,12 @@ func (_u *GroupUpdate) ClearDescription() *GroupUpdate {
return _u
}
+// SetI18n sets the "i18n" field.
+func (_u *GroupUpdate) SetI18n(v domain.GroupI18n) *GroupUpdate {
+ _u.mutation.SetI18n(v)
+ return _u
+}
+
// SetRateMultiplier sets the "rate_multiplier" field.
func (_u *GroupUpdate) SetRateMultiplier(v float64) *GroupUpdate {
_u.mutation.ResetRateMultiplier()
@@ -1581,6 +1587,9 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if _u.mutation.DescriptionCleared() {
_spec.ClearField(group.FieldDescription, field.TypeString)
}
+ if value, ok := _u.mutation.I18n(); ok {
+ _spec.SetField(group.FieldI18n, field.TypeJSON, value)
+ }
if value, ok := _u.mutation.RateMultiplier(); ok {
_spec.SetField(group.FieldRateMultiplier, field.TypeFloat64, value)
}
@@ -2291,6 +2300,12 @@ func (_u *GroupUpdateOne) ClearDescription() *GroupUpdateOne {
return _u
}
+// SetI18n sets the "i18n" field.
+func (_u *GroupUpdateOne) SetI18n(v domain.GroupI18n) *GroupUpdateOne {
+ _u.mutation.SetI18n(v)
+ return _u
+}
+
// SetRateMultiplier sets the "rate_multiplier" field.
func (_u *GroupUpdateOne) SetRateMultiplier(v float64) *GroupUpdateOne {
_u.mutation.ResetRateMultiplier()
@@ -3805,6 +3820,9 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
if _u.mutation.DescriptionCleared() {
_spec.ClearField(group.FieldDescription, field.TypeString)
}
+ if value, ok := _u.mutation.I18n(); ok {
+ _spec.SetField(group.FieldI18n, field.TypeJSON, value)
+ }
if value, ok := _u.mutation.RateMultiplier(); ok {
_spec.SetField(group.FieldRateMultiplier, field.TypeFloat64, value)
}
diff --git a/backend/ent/migrate/schema.go b/backend/ent/migrate/schema.go
index 88292b633..adfa072b0 100644
--- a/backend/ent/migrate/schema.go
+++ b/backend/ent/migrate/schema.go
@@ -908,6 +908,7 @@ var (
{Name: "deleted_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "name", Type: field.TypeString, Size: 100},
{Name: "description", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
+ {Name: "i18n", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}},
{Name: "rate_multiplier", Type: field.TypeFloat64, Default: 1, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
{Name: "peak_rate_enabled", Type: field.TypeBool, Default: false},
{Name: "peak_start", Type: field.TypeString, Size: 5, Default: ""},
@@ -979,22 +980,22 @@ var (
{
Name: "group_status",
Unique: false,
- Columns: []*schema.Column{GroupsColumns[12]},
+ Columns: []*schema.Column{GroupsColumns[13]},
},
{
Name: "group_platform",
Unique: false,
- Columns: []*schema.Column{GroupsColumns[14]},
+ Columns: []*schema.Column{GroupsColumns[15]},
},
{
Name: "group_subscription_type",
Unique: false,
- Columns: []*schema.Column{GroupsColumns[15]},
+ Columns: []*schema.Column{GroupsColumns[16]},
},
{
Name: "group_is_exclusive",
Unique: false,
- Columns: []*schema.Column{GroupsColumns[11]},
+ Columns: []*schema.Column{GroupsColumns[12]},
},
{
Name: "group_deleted_at",
@@ -1004,12 +1005,12 @@ var (
{
Name: "group_sort_order",
Unique: false,
- Columns: []*schema.Column{GroupsColumns[49]},
+ Columns: []*schema.Column{GroupsColumns[50]},
},
{
Name: "idx_groups_duplicate_operation_id_active",
Unique: true,
- Columns: []*schema.Column{GroupsColumns[13]},
+ Columns: []*schema.Column{GroupsColumns[14]},
Annotation: &entsql.IndexAnnotation{
Where: "duplicate_operation_id IS NOT NULL AND deleted_at IS NULL",
},
diff --git a/backend/ent/mutation.go b/backend/ent/mutation.go
index affee9d37..c6033a53d 100644
--- a/backend/ent/mutation.go
+++ b/backend/ent/mutation.go
@@ -22086,6 +22086,7 @@ type GroupMutation struct {
deleted_at *time.Time
name *string
description *string
+ i18n *domain.GroupI18n
rate_multiplier *float64
addrate_multiplier *float64
peak_rate_enabled *bool
@@ -22505,6 +22506,42 @@ func (m *GroupMutation) ResetDescription() {
delete(m.clearedFields, group.FieldDescription)
}
+// SetI18n sets the "i18n" field.
+func (m *GroupMutation) SetI18n(di domain.GroupI18n) {
+ m.i18n = &di
+}
+
+// I18n returns the value of the "i18n" field in the mutation.
+func (m *GroupMutation) I18n() (r domain.GroupI18n, exists bool) {
+ v := m.i18n
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldI18n returns the old "i18n" field's value of the Group entity.
+// If the Group object wasn't provided to the builder, the object is fetched from the database.
+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
+func (m *GroupMutation) OldI18n(ctx context.Context) (v domain.GroupI18n, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldI18n is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldI18n requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldI18n: %w", err)
+ }
+ return oldValue.I18n, nil
+}
+
+// ResetI18n resets all changes to the "i18n" field.
+func (m *GroupMutation) ResetI18n() {
+ m.i18n = nil
+}
+
// SetRateMultiplier sets the "rate_multiplier" field.
func (m *GroupMutation) SetRateMultiplier(f float64) {
m.rate_multiplier = &f
@@ -25921,7 +25958,7 @@ func (m *GroupMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *GroupMutation) Fields() []string {
- fields := make([]string, 0, 66)
+ fields := make([]string, 0, 67)
if m.created_at != nil {
fields = append(fields, group.FieldCreatedAt)
}
@@ -25937,6 +25974,9 @@ func (m *GroupMutation) Fields() []string {
if m.description != nil {
fields = append(fields, group.FieldDescription)
}
+ if m.i18n != nil {
+ fields = append(fields, group.FieldI18n)
+ }
if m.rate_multiplier != nil {
fields = append(fields, group.FieldRateMultiplier)
}
@@ -26138,6 +26178,8 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
return m.Name()
case group.FieldDescription:
return m.Description()
+ case group.FieldI18n:
+ return m.I18n()
case group.FieldRateMultiplier:
return m.RateMultiplier()
case group.FieldPeakRateEnabled:
@@ -26279,6 +26321,8 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
return m.OldName(ctx)
case group.FieldDescription:
return m.OldDescription(ctx)
+ case group.FieldI18n:
+ return m.OldI18n(ctx)
case group.FieldRateMultiplier:
return m.OldRateMultiplier(ctx)
case group.FieldPeakRateEnabled:
@@ -26445,6 +26489,13 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
}
m.SetDescription(v)
return nil
+ case group.FieldI18n:
+ v, ok := value.(domain.GroupI18n)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetI18n(v)
+ return nil
case group.FieldRateMultiplier:
v, ok := value.(float64)
if !ok {
@@ -27398,6 +27449,9 @@ func (m *GroupMutation) ResetField(name string) error {
case group.FieldDescription:
m.ResetDescription()
return nil
+ case group.FieldI18n:
+ m.ResetI18n()
+ return nil
case group.FieldRateMultiplier:
m.ResetRateMultiplier()
return nil
diff --git a/backend/ent/runtime/runtime.go b/backend/ent/runtime/runtime.go
index 60de682b3..8d7fb46b2 100644
--- a/backend/ent/runtime/runtime.go
+++ b/backend/ent/runtime/runtime.go
@@ -1037,204 +1037,208 @@ func init() {
return nil
}
}()
+ // groupDescI18n is the schema descriptor for i18n field.
+ groupDescI18n := groupFields[2].Descriptor()
+ // group.DefaultI18n holds the default value on creation for the i18n field.
+ group.DefaultI18n = groupDescI18n.Default.(domain.GroupI18n)
// groupDescRateMultiplier is the schema descriptor for rate_multiplier field.
- groupDescRateMultiplier := groupFields[2].Descriptor()
+ groupDescRateMultiplier := groupFields[3].Descriptor()
// group.DefaultRateMultiplier holds the default value on creation for the rate_multiplier field.
group.DefaultRateMultiplier = groupDescRateMultiplier.Default.(float64)
// groupDescPeakRateEnabled is the schema descriptor for peak_rate_enabled field.
- groupDescPeakRateEnabled := groupFields[3].Descriptor()
+ groupDescPeakRateEnabled := groupFields[4].Descriptor()
// group.DefaultPeakRateEnabled holds the default value on creation for the peak_rate_enabled field.
group.DefaultPeakRateEnabled = groupDescPeakRateEnabled.Default.(bool)
// groupDescPeakStart is the schema descriptor for peak_start field.
- groupDescPeakStart := groupFields[4].Descriptor()
+ groupDescPeakStart := groupFields[5].Descriptor()
// group.DefaultPeakStart holds the default value on creation for the peak_start field.
group.DefaultPeakStart = groupDescPeakStart.Default.(string)
// group.PeakStartValidator is a validator for the "peak_start" field. It is called by the builders before save.
group.PeakStartValidator = groupDescPeakStart.Validators[0].(func(string) error)
// groupDescPeakEnd is the schema descriptor for peak_end field.
- groupDescPeakEnd := groupFields[5].Descriptor()
+ groupDescPeakEnd := groupFields[6].Descriptor()
// group.DefaultPeakEnd holds the default value on creation for the peak_end field.
group.DefaultPeakEnd = groupDescPeakEnd.Default.(string)
// group.PeakEndValidator is a validator for the "peak_end" field. It is called by the builders before save.
group.PeakEndValidator = groupDescPeakEnd.Validators[0].(func(string) error)
// groupDescPeakRateMultiplier is the schema descriptor for peak_rate_multiplier field.
- groupDescPeakRateMultiplier := groupFields[6].Descriptor()
+ groupDescPeakRateMultiplier := groupFields[7].Descriptor()
// group.DefaultPeakRateMultiplier holds the default value on creation for the peak_rate_multiplier field.
group.DefaultPeakRateMultiplier = groupDescPeakRateMultiplier.Default.(float64)
// groupDescIsExclusive is the schema descriptor for is_exclusive field.
- groupDescIsExclusive := groupFields[7].Descriptor()
+ groupDescIsExclusive := groupFields[8].Descriptor()
// group.DefaultIsExclusive holds the default value on creation for the is_exclusive field.
group.DefaultIsExclusive = groupDescIsExclusive.Default.(bool)
// groupDescStatus is the schema descriptor for status field.
- groupDescStatus := groupFields[8].Descriptor()
+ groupDescStatus := groupFields[9].Descriptor()
// group.DefaultStatus holds the default value on creation for the status field.
group.DefaultStatus = groupDescStatus.Default.(string)
// group.StatusValidator is a validator for the "status" field. It is called by the builders before save.
group.StatusValidator = groupDescStatus.Validators[0].(func(string) error)
// groupDescDuplicateOperationID is the schema descriptor for duplicate_operation_id field.
- groupDescDuplicateOperationID := groupFields[9].Descriptor()
+ groupDescDuplicateOperationID := groupFields[10].Descriptor()
// group.DuplicateOperationIDValidator is a validator for the "duplicate_operation_id" field. It is called by the builders before save.
group.DuplicateOperationIDValidator = groupDescDuplicateOperationID.Validators[0].(func(string) error)
// groupDescPlatform is the schema descriptor for platform field.
- groupDescPlatform := groupFields[10].Descriptor()
+ groupDescPlatform := groupFields[11].Descriptor()
// group.DefaultPlatform holds the default value on creation for the platform field.
group.DefaultPlatform = groupDescPlatform.Default.(string)
// group.PlatformValidator is a validator for the "platform" field. It is called by the builders before save.
group.PlatformValidator = groupDescPlatform.Validators[0].(func(string) error)
// groupDescSubscriptionType is the schema descriptor for subscription_type field.
- groupDescSubscriptionType := groupFields[11].Descriptor()
+ groupDescSubscriptionType := groupFields[12].Descriptor()
// group.DefaultSubscriptionType holds the default value on creation for the subscription_type field.
group.DefaultSubscriptionType = groupDescSubscriptionType.Default.(string)
// group.SubscriptionTypeValidator is a validator for the "subscription_type" field. It is called by the builders before save.
group.SubscriptionTypeValidator = groupDescSubscriptionType.Validators[0].(func(string) error)
// groupDescDefaultValidityDays is the schema descriptor for default_validity_days field.
- groupDescDefaultValidityDays := groupFields[15].Descriptor()
+ groupDescDefaultValidityDays := groupFields[16].Descriptor()
// group.DefaultDefaultValidityDays holds the default value on creation for the default_validity_days field.
group.DefaultDefaultValidityDays = groupDescDefaultValidityDays.Default.(int)
// groupDescAllowImageGeneration is the schema descriptor for allow_image_generation field.
- groupDescAllowImageGeneration := groupFields[16].Descriptor()
+ groupDescAllowImageGeneration := groupFields[17].Descriptor()
// group.DefaultAllowImageGeneration holds the default value on creation for the allow_image_generation field.
group.DefaultAllowImageGeneration = groupDescAllowImageGeneration.Default.(bool)
// groupDescAllowBatchImageGeneration is the schema descriptor for allow_batch_image_generation field.
- groupDescAllowBatchImageGeneration := groupFields[17].Descriptor()
+ groupDescAllowBatchImageGeneration := groupFields[18].Descriptor()
// group.DefaultAllowBatchImageGeneration holds the default value on creation for the allow_batch_image_generation field.
group.DefaultAllowBatchImageGeneration = groupDescAllowBatchImageGeneration.Default.(bool)
// groupDescImageRateIndependent is the schema descriptor for image_rate_independent field.
- groupDescImageRateIndependent := groupFields[18].Descriptor()
+ groupDescImageRateIndependent := groupFields[19].Descriptor()
// group.DefaultImageRateIndependent holds the default value on creation for the image_rate_independent field.
group.DefaultImageRateIndependent = groupDescImageRateIndependent.Default.(bool)
// groupDescImageRateMultiplier is the schema descriptor for image_rate_multiplier field.
- groupDescImageRateMultiplier := groupFields[19].Descriptor()
+ groupDescImageRateMultiplier := groupFields[20].Descriptor()
// group.DefaultImageRateMultiplier holds the default value on creation for the image_rate_multiplier field.
group.DefaultImageRateMultiplier = groupDescImageRateMultiplier.Default.(float64)
// groupDescBatchImageDiscountMultiplier is the schema descriptor for batch_image_discount_multiplier field.
- groupDescBatchImageDiscountMultiplier := groupFields[23].Descriptor()
+ groupDescBatchImageDiscountMultiplier := groupFields[24].Descriptor()
// group.DefaultBatchImageDiscountMultiplier holds the default value on creation for the batch_image_discount_multiplier field.
group.DefaultBatchImageDiscountMultiplier = groupDescBatchImageDiscountMultiplier.Default.(float64)
// groupDescBatchImageHoldMultiplier is the schema descriptor for batch_image_hold_multiplier field.
- groupDescBatchImageHoldMultiplier := groupFields[24].Descriptor()
+ groupDescBatchImageHoldMultiplier := groupFields[25].Descriptor()
// group.DefaultBatchImageHoldMultiplier holds the default value on creation for the batch_image_hold_multiplier field.
group.DefaultBatchImageHoldMultiplier = groupDescBatchImageHoldMultiplier.Default.(float64)
// groupDescVideoRateIndependent is the schema descriptor for video_rate_independent field.
- groupDescVideoRateIndependent := groupFields[25].Descriptor()
+ groupDescVideoRateIndependent := groupFields[26].Descriptor()
// group.DefaultVideoRateIndependent holds the default value on creation for the video_rate_independent field.
group.DefaultVideoRateIndependent = groupDescVideoRateIndependent.Default.(bool)
// groupDescVideoRateMultiplier is the schema descriptor for video_rate_multiplier field.
- groupDescVideoRateMultiplier := groupFields[26].Descriptor()
+ groupDescVideoRateMultiplier := groupFields[27].Descriptor()
// group.DefaultVideoRateMultiplier holds the default value on creation for the video_rate_multiplier field.
group.DefaultVideoRateMultiplier = groupDescVideoRateMultiplier.Default.(float64)
// groupDescSearchPricePer1k is the schema descriptor for search_price_per_1k field.
- groupDescSearchPricePer1k := groupFields[32].Descriptor()
+ groupDescSearchPricePer1k := groupFields[33].Descriptor()
// group.SearchPricePer1kValidator is a validator for the "search_price_per_1k" field. It is called by the builders before save.
group.SearchPricePer1kValidator = groupDescSearchPricePer1k.Validators[0].(func(float64) error)
// groupDescAudioRealtimePricePerMin is the schema descriptor for audio_realtime_price_per_min field.
- groupDescAudioRealtimePricePerMin := groupFields[33].Descriptor()
+ groupDescAudioRealtimePricePerMin := groupFields[34].Descriptor()
// group.AudioRealtimePricePerMinValidator is a validator for the "audio_realtime_price_per_min" field. It is called by the builders before save.
group.AudioRealtimePricePerMinValidator = groupDescAudioRealtimePricePerMin.Validators[0].(func(float64) error)
// groupDescAudioTtsPricePerMillionChars is the schema descriptor for audio_tts_price_per_million_chars field.
- groupDescAudioTtsPricePerMillionChars := groupFields[34].Descriptor()
+ groupDescAudioTtsPricePerMillionChars := groupFields[35].Descriptor()
// group.AudioTtsPricePerMillionCharsValidator is a validator for the "audio_tts_price_per_million_chars" field. It is called by the builders before save.
group.AudioTtsPricePerMillionCharsValidator = groupDescAudioTtsPricePerMillionChars.Validators[0].(func(float64) error)
// groupDescAudioSttPricePerHour is the schema descriptor for audio_stt_price_per_hour field.
- groupDescAudioSttPricePerHour := groupFields[35].Descriptor()
+ groupDescAudioSttPricePerHour := groupFields[36].Descriptor()
// group.AudioSttPricePerHourValidator is a validator for the "audio_stt_price_per_hour" field. It is called by the builders before save.
group.AudioSttPricePerHourValidator = groupDescAudioSttPricePerHour.Validators[0].(func(float64) error)
// groupDescLongContextPricingEnabled is the schema descriptor for long_context_pricing_enabled field.
- groupDescLongContextPricingEnabled := groupFields[36].Descriptor()
+ groupDescLongContextPricingEnabled := groupFields[37].Descriptor()
// group.DefaultLongContextPricingEnabled holds the default value on creation for the long_context_pricing_enabled field.
group.DefaultLongContextPricingEnabled = groupDescLongContextPricingEnabled.Default.(bool)
// groupDescClaudeCodeOnly is the schema descriptor for claude_code_only field.
- groupDescClaudeCodeOnly := groupFields[38].Descriptor()
+ groupDescClaudeCodeOnly := groupFields[39].Descriptor()
// group.DefaultClaudeCodeOnly holds the default value on creation for the claude_code_only field.
group.DefaultClaudeCodeOnly = groupDescClaudeCodeOnly.Default.(bool)
// groupDescModelRoutingEnabled is the schema descriptor for model_routing_enabled field.
- groupDescModelRoutingEnabled := groupFields[42].Descriptor()
+ groupDescModelRoutingEnabled := groupFields[43].Descriptor()
// group.DefaultModelRoutingEnabled holds the default value on creation for the model_routing_enabled field.
group.DefaultModelRoutingEnabled = groupDescModelRoutingEnabled.Default.(bool)
// groupDescMcpXMLInject is the schema descriptor for mcp_xml_inject field.
- groupDescMcpXMLInject := groupFields[43].Descriptor()
+ groupDescMcpXMLInject := groupFields[44].Descriptor()
// group.DefaultMcpXMLInject holds the default value on creation for the mcp_xml_inject field.
group.DefaultMcpXMLInject = groupDescMcpXMLInject.Default.(bool)
// groupDescSupportedModelScopes is the schema descriptor for supported_model_scopes field.
- groupDescSupportedModelScopes := groupFields[44].Descriptor()
+ groupDescSupportedModelScopes := groupFields[45].Descriptor()
// group.DefaultSupportedModelScopes holds the default value on creation for the supported_model_scopes field.
group.DefaultSupportedModelScopes = groupDescSupportedModelScopes.Default.([]string)
// groupDescSortOrder is the schema descriptor for sort_order field.
- groupDescSortOrder := groupFields[45].Descriptor()
+ groupDescSortOrder := groupFields[46].Descriptor()
// group.DefaultSortOrder holds the default value on creation for the sort_order field.
group.DefaultSortOrder = groupDescSortOrder.Default.(int)
// groupDescAllowMessagesDispatch is the schema descriptor for allow_messages_dispatch field.
- groupDescAllowMessagesDispatch := groupFields[46].Descriptor()
+ groupDescAllowMessagesDispatch := groupFields[47].Descriptor()
// group.DefaultAllowMessagesDispatch holds the default value on creation for the allow_messages_dispatch field.
group.DefaultAllowMessagesDispatch = groupDescAllowMessagesDispatch.Default.(bool)
// groupDescAllowLive is the schema descriptor for allow_live field.
- groupDescAllowLive := groupFields[47].Descriptor()
+ groupDescAllowLive := groupFields[48].Descriptor()
// group.DefaultAllowLive holds the default value on creation for the allow_live field.
group.DefaultAllowLive = groupDescAllowLive.Default.(bool)
// groupDescForceOpenaiFast is the schema descriptor for force_openai_fast field.
- groupDescForceOpenaiFast := groupFields[48].Descriptor()
+ groupDescForceOpenaiFast := groupFields[49].Descriptor()
// group.DefaultForceOpenaiFast holds the default value on creation for the force_openai_fast field.
group.DefaultForceOpenaiFast = groupDescForceOpenaiFast.Default.(bool)
// groupDescFreeOpenaiFast is the schema descriptor for free_openai_fast field.
- groupDescFreeOpenaiFast := groupFields[49].Descriptor()
+ groupDescFreeOpenaiFast := groupFields[50].Descriptor()
// group.DefaultFreeOpenaiFast holds the default value on creation for the free_openai_fast field.
group.DefaultFreeOpenaiFast = groupDescFreeOpenaiFast.Default.(bool)
// groupDescRequireOauthOnly is the schema descriptor for require_oauth_only field.
- groupDescRequireOauthOnly := groupFields[50].Descriptor()
+ groupDescRequireOauthOnly := groupFields[51].Descriptor()
// group.DefaultRequireOauthOnly holds the default value on creation for the require_oauth_only field.
group.DefaultRequireOauthOnly = groupDescRequireOauthOnly.Default.(bool)
// groupDescRequirePrivacySet is the schema descriptor for require_privacy_set field.
- groupDescRequirePrivacySet := groupFields[51].Descriptor()
+ groupDescRequirePrivacySet := groupFields[52].Descriptor()
// group.DefaultRequirePrivacySet holds the default value on creation for the require_privacy_set field.
group.DefaultRequirePrivacySet = groupDescRequirePrivacySet.Default.(bool)
// groupDescDefaultMappedModel is the schema descriptor for default_mapped_model field.
- groupDescDefaultMappedModel := groupFields[52].Descriptor()
+ groupDescDefaultMappedModel := groupFields[53].Descriptor()
// group.DefaultDefaultMappedModel holds the default value on creation for the default_mapped_model field.
group.DefaultDefaultMappedModel = groupDescDefaultMappedModel.Default.(string)
// group.DefaultMappedModelValidator is a validator for the "default_mapped_model" field. It is called by the builders before save.
group.DefaultMappedModelValidator = groupDescDefaultMappedModel.Validators[0].(func(string) error)
// groupDescMessagesDispatchModelConfig is the schema descriptor for messages_dispatch_model_config field.
- groupDescMessagesDispatchModelConfig := groupFields[53].Descriptor()
+ groupDescMessagesDispatchModelConfig := groupFields[54].Descriptor()
// group.DefaultMessagesDispatchModelConfig holds the default value on creation for the messages_dispatch_model_config field.
group.DefaultMessagesDispatchModelConfig = groupDescMessagesDispatchModelConfig.Default.(domain.OpenAIMessagesDispatchModelConfig)
// groupDescModelAllowlist is the schema descriptor for model_allowlist field.
- groupDescModelAllowlist := groupFields[54].Descriptor()
+ groupDescModelAllowlist := groupFields[55].Descriptor()
// group.DefaultModelAllowlist holds the default value on creation for the model_allowlist field.
group.DefaultModelAllowlist = groupDescModelAllowlist.Default.(domain.GroupModelAllowlist)
// groupDescCodexModelsManifestConfig is the schema descriptor for codex_models_manifest_config field.
- groupDescCodexModelsManifestConfig := groupFields[55].Descriptor()
+ groupDescCodexModelsManifestConfig := groupFields[56].Descriptor()
// group.DefaultCodexModelsManifestConfig holds the default value on creation for the codex_models_manifest_config field.
group.DefaultCodexModelsManifestConfig = groupDescCodexModelsManifestConfig.Default.(domain.GroupCodexModelsManifestConfig)
// groupDescRpmLimit is the schema descriptor for rpm_limit field.
- groupDescRpmLimit := groupFields[56].Descriptor()
+ groupDescRpmLimit := groupFields[57].Descriptor()
// group.DefaultRpmLimit holds the default value on creation for the rpm_limit field.
group.DefaultRpmLimit = groupDescRpmLimit.Default.(int)
// groupDescMaxReasoningEffort is the schema descriptor for max_reasoning_effort field.
- groupDescMaxReasoningEffort := groupFields[57].Descriptor()
+ groupDescMaxReasoningEffort := groupFields[58].Descriptor()
// group.DefaultMaxReasoningEffort holds the default value on creation for the max_reasoning_effort field.
group.DefaultMaxReasoningEffort = groupDescMaxReasoningEffort.Default.(string)
// group.MaxReasoningEffortValidator is a validator for the "max_reasoning_effort" field. It is called by the builders before save.
group.MaxReasoningEffortValidator = groupDescMaxReasoningEffort.Validators[0].(func(string) error)
// groupDescMaxReasoningEffortOverLimit is the schema descriptor for max_reasoning_effort_over_limit field.
- groupDescMaxReasoningEffortOverLimit := groupFields[58].Descriptor()
+ groupDescMaxReasoningEffortOverLimit := groupFields[59].Descriptor()
// group.DefaultMaxReasoningEffortOverLimit holds the default value on creation for the max_reasoning_effort_over_limit field.
group.DefaultMaxReasoningEffortOverLimit = groupDescMaxReasoningEffortOverLimit.Default.(string)
// group.MaxReasoningEffortOverLimitValidator is a validator for the "max_reasoning_effort_over_limit" field. It is called by the builders before save.
group.MaxReasoningEffortOverLimitValidator = groupDescMaxReasoningEffortOverLimit.Validators[0].(func(string) error)
// groupDescReasoningEffortMappings is the schema descriptor for reasoning_effort_mappings field.
- groupDescReasoningEffortMappings := groupFields[59].Descriptor()
+ groupDescReasoningEffortMappings := groupFields[60].Descriptor()
// group.DefaultReasoningEffortMappings holds the default value on creation for the reasoning_effort_mappings field.
group.DefaultReasoningEffortMappings = groupDescReasoningEffortMappings.Default.([]domain.ReasoningEffortMapping)
// groupDescProfitControlEnabled is the schema descriptor for profit_control_enabled field.
- groupDescProfitControlEnabled := groupFields[60].Descriptor()
+ groupDescProfitControlEnabled := groupFields[61].Descriptor()
// group.DefaultProfitControlEnabled holds the default value on creation for the profit_control_enabled field.
group.DefaultProfitControlEnabled = groupDescProfitControlEnabled.Default.(bool)
// groupDescProfitMinMargin is the schema descriptor for profit_min_margin field.
- groupDescProfitMinMargin := groupFields[61].Descriptor()
+ groupDescProfitMinMargin := groupFields[62].Descriptor()
// group.DefaultProfitMinMargin holds the default value on creation for the profit_min_margin field.
group.DefaultProfitMinMargin = groupDescProfitMinMargin.Default.(float64)
// groupDescProfitSafetyBuffer is the schema descriptor for profit_safety_buffer field.
- groupDescProfitSafetyBuffer := groupFields[62].Descriptor()
+ groupDescProfitSafetyBuffer := groupFields[63].Descriptor()
// group.DefaultProfitSafetyBuffer holds the default value on creation for the profit_safety_buffer field.
group.DefaultProfitSafetyBuffer = groupDescProfitSafetyBuffer.Default.(float64)
idempotencyrecordMixin := schema.IdempotencyRecord{}.Mixin()
diff --git a/backend/ent/schema/group.go b/backend/ent/schema/group.go
index 1a77daa66..277f46852 100644
--- a/backend/ent/schema/group.go
+++ b/backend/ent/schema/group.go
@@ -44,6 +44,11 @@ func (Group) Fields() []ent.Field {
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
+ // 名称与描述的界面语言译文 (added by migration 242)
+ field.JSON("i18n", domain.GroupI18n{}).
+ Default(domain.GroupI18n{}).
+ SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
+ Comment("名称与描述的界面语言译文:语言代码 -> {name, description};缺失的语言沿用 name/description"),
field.Float("rate_multiplier").
SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
Default(1.0),
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index a9f0b6353..20756413e 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -979,6 +979,9 @@ const (
// GatewayConfig API网关相关配置
type GatewayConfig struct {
+ // MinOutputTokens is the minimum max_output_tokens used when
+ // converting Chat Completions or Anthropic requests to Responses.
+ MinOutputTokens int `mapstructure:"min_output_tokens"`
// 等待上游响应头的超时时间(秒),0表示无超时
// 注意:这不影响流式数据传输,只控制等待响应头的时间
ResponseHeaderTimeout int `mapstructure:"response_header_timeout"`
@@ -1005,6 +1008,8 @@ type GatewayConfig struct {
ProxyProbeResponseReadMaxBytes int64 `mapstructure:"proxy_probe_response_read_max_bytes"`
// Gemini 上游响应头调试日志开关(默认关闭,避免高频日志开销)
GeminiDebugResponseHeaders bool `mapstructure:"gemini_debug_response_headers"`
+ // GeminiCachedContentMaxTTLSeconds: Gemini 显式缓存单次可设置的最长有效期(秒),<=0 时按 86400 处理
+ GeminiCachedContentMaxTTLSeconds int `mapstructure:"gemini_cached_content_max_ttl_seconds"`
// ConnectionPoolIsolation: 上游连接池隔离策略(proxy/account/account_proxy)
ConnectionPoolIsolation string `mapstructure:"connection_pool_isolation"`
// ForceCodexCLI: 强制将 OpenAI `/v1/responses` 请求按 Codex CLI 处理。
@@ -2054,6 +2059,7 @@ func configureConfigSource(setConfigFile, addConfigPath func(string)) {
func setDefaults() {
viper.SetDefault("run_mode", RunModeStandard)
+ viper.SetDefault("gateway.min_output_tokens", 128)
viper.SetDefault("simple_mode.auto_create_default_groups", true)
viper.SetDefault("simple_mode_key_rate_limit_enabled", false)
@@ -2111,6 +2117,7 @@ func setDefaults() {
"api.openai.com",
"api.anthropic.com",
"api.kimi.com",
+ "api.kimi.ai",
"api.moonshot.ai",
"api.moonshot.cn",
"open.bigmodel.cn",
@@ -2561,6 +2568,7 @@ func setDefaults() {
viper.SetDefault("gateway.models_list_read_max_bytes", DefaultModelsListReadMaxBytes)
viper.SetDefault("gateway.proxy_probe_response_read_max_bytes", int64(1024*1024))
viper.SetDefault("gateway.gemini_debug_response_headers", false)
+ viper.SetDefault("gateway.gemini_cached_content_max_ttl_seconds", 86400)
viper.SetDefault("gateway.connection_pool_isolation", ConnectionPoolIsolationAccountProxy)
// HTTP 上游连接池配置(针对 5000+ 并发用户优化)
viper.SetDefault("gateway.max_idle_conns", 2560) // 最大空闲连接总数(高并发场景可调大)
@@ -2737,6 +2745,9 @@ func setEnvReachableDefaults() {
}
func (c *Config) Validate() error {
+ if c.Gateway.MinOutputTokens < 16 {
+ return fmt.Errorf("gateway.min_output_tokens must be at least 16")
+ }
forwardedClientIPHeaders, err := NormalizeForwardedClientIPHeaders(c.Security.ForwardedClientIPHeaders)
if err != nil {
return fmt.Errorf("security.forwarded_client_ip_headers: %w", err)
diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go
index b68a26d49..b41d710f9 100644
--- a/backend/internal/config/config_test.go
+++ b/backend/internal/config/config_test.go
@@ -10,6 +10,7 @@ import (
"testing"
"time"
+ "github.com/MACOS-DO/sub4api/internal/util/urlvalidator"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
)
@@ -30,6 +31,29 @@ func TestLoadDefaultModelsListReadMaxBytes(t *testing.T) {
require.Equal(t, DefaultModelsListReadMaxBytes, cfg.Gateway.ModelsListReadMaxBytes)
}
+func TestLoadDefaultMinOutputTokens(t *testing.T) {
+ resetViperWithJWTSecret(t)
+ cfg, err := Load()
+ require.NoError(t, err)
+ require.Equal(t, 128, cfg.Gateway.MinOutputTokens)
+}
+
+func TestLoadMinOutputTokensFromEnv(t *testing.T) {
+ resetViperWithJWTSecret(t)
+ t.Setenv("GATEWAY_MIN_OUTPUT_TOKENS", "16")
+ cfg, err := Load()
+ require.NoError(t, err)
+ require.Equal(t, 16, cfg.Gateway.MinOutputTokens)
+}
+
+func TestValidateMinOutputTokensMinimum(t *testing.T) {
+ resetViperWithJWTSecret(t)
+ cfg, err := Load()
+ require.NoError(t, err)
+ cfg.Gateway.MinOutputTokens = 15
+ require.EqualError(t, cfg.Validate(), "gateway.min_output_tokens must be at least 16")
+}
+
func TestLoadTimezonePrecedence(t *testing.T) {
tests := []struct {
name string
@@ -831,6 +855,7 @@ func TestLoadDefaultSecurityToggles(t *testing.T) {
wantHosts := []string{
"api.kimi.com",
+ "api.kimi.ai",
"api.moonshot.ai",
"api.moonshot.cn",
}
@@ -843,6 +868,19 @@ func TestLoadDefaultSecurityToggles(t *testing.T) {
t.Fatalf("URLAllowlist.UpstreamHosts missing %q; got %v", want, cfg.Security.URLAllowlist.UpstreamHosts)
}
}
+ opts := urlvalidator.ValidationOptions{
+ AllowedHosts: cfg.Security.URLAllowlist.UpstreamHosts,
+ RequireAllowlist: true,
+ AllowPrivate: cfg.Security.URLAllowlist.AllowPrivateHosts,
+ }
+ for _, host := range []string{"api.kimi.com", "api.kimi.ai"} {
+ target := "https://" + host + "/coding/v1/usages"
+ normalized, err := urlvalidator.ValidateHTTPSURL(target, opts)
+ require.NoError(t, err)
+ require.Equal(t, target, normalized)
+ _, err = urlvalidator.ValidateHTTPSURL("https://"+host+".attacker.example/coding/v1/usages", opts)
+ require.Error(t, err)
+ }
}
func TestLoadDefaultServerMode(t *testing.T) {
diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go
index 94f51a6d9..fcd116a5a 100644
--- a/backend/internal/domain/constants.go
+++ b/backend/internal/domain/constants.go
@@ -114,6 +114,14 @@ var DefaultAntigravityModelMapping = map[string]string{
// Claude 白名单
"claude-fable-5-1": "claude-fable-5-1", // 官方模型
"claude-fable-5": "claude-fable-5", // 官方模型
+ "claude-opus-5-5": "claude-opus-5-5-high", // 简称映射
+ "claude-opus-5-5-high": "claude-opus-5-5-high", // 官方模型
+ "claude-opus-5-5-medium": "claude-opus-5-5-medium", // 官方模型
+ "claude-opus-5-5-low": "claude-opus-5-5-low", // 官方模型
+ "claude-sonnet-5-5": "claude-sonnet-5-5-high", // 简称映射
+ "claude-sonnet-5-5-high": "claude-sonnet-5-5-high", // 官方模型
+ "claude-sonnet-5-5-medium": "claude-sonnet-5-5-medium", // 官方模型
+ "claude-sonnet-5-5-low": "claude-sonnet-5-5-low", // 官方模型
"claude-opus-4-8": "claude-opus-4-8", // 官方模型
"claude-opus-4-7": "claude-opus-4-7", // 官方模型
"claude-opus-4-6-thinking": "claude-opus-4-6-thinking", // 官方模型
@@ -171,6 +179,11 @@ var DefaultAntigravityModelMapping = map[string]string{
"gemini-3.8-flash-low": "gemini-3.8-flash-low",
"gemini-3.8-flash-medium": "gemini-3.8-flash-medium",
"gemini-3.8-flash-tiered": "gemini-3.8-flash-tiered",
+ // Gemini 4 Argon tiered models
+ "gemini-4-argon": "gemini-4-argon-high",
+ "gemini-4-argon-high": "gemini-4-argon-high",
+ "gemini-4-argon-low": "gemini-4-argon-low",
+ "gemini-4-argon-medium": "gemini-4-argon-medium",
// Gemini 3 image 兼容映射(向 3.1 image 迁移)
"gemini-3-pro-image": "gemini-3.1-flash-image",
"gemini-3-pro-image-preview": "gemini-3.1-flash-image",
diff --git a/backend/internal/domain/constants_test.go b/backend/internal/domain/constants_test.go
index 076688d6c..430d4802e 100644
--- a/backend/internal/domain/constants_test.go
+++ b/backend/internal/domain/constants_test.go
@@ -105,6 +105,28 @@ func TestDefaultAntigravityModelMapping_Gemini38FlashModels(t *testing.T) {
}
}
+func TestDefaultAntigravityModelMapping_Gemini4ArgonAndClaude55Models(t *testing.T) {
+ cases := map[string]string{
+ "gemini-4-argon": "gemini-4-argon-high",
+ "gemini-4-argon-high": "gemini-4-argon-high",
+ "gemini-4-argon-low": "gemini-4-argon-low",
+ "gemini-4-argon-medium": "gemini-4-argon-medium",
+ "claude-opus-5-5": "claude-opus-5-5-high",
+ "claude-opus-5-5-high": "claude-opus-5-5-high",
+ "claude-opus-5-5-low": "claude-opus-5-5-low",
+ "claude-opus-5-5-medium": "claude-opus-5-5-medium",
+ "claude-sonnet-5-5": "claude-sonnet-5-5-high",
+ "claude-sonnet-5-5-high": "claude-sonnet-5-5-high",
+ "claude-sonnet-5-5-low": "claude-sonnet-5-5-low",
+ "claude-sonnet-5-5-medium": "claude-sonnet-5-5-medium",
+ }
+ for from, want := range cases {
+ if got := DefaultAntigravityModelMapping[from]; got != want {
+ t.Fatalf("expected %s to map to %q, got %q", from, want, got)
+ }
+ }
+}
+
func TestDefaultBedrockModelMapping_ContainsNewClaudeModels(t *testing.T) {
t.Parallel()
diff --git a/backend/internal/domain/group_i18n.go b/backend/internal/domain/group_i18n.go
new file mode 100644
index 000000000..c02b1c5a4
--- /dev/null
+++ b/backend/internal/domain/group_i18n.go
@@ -0,0 +1,113 @@
+package domain
+
+import (
+ "strconv"
+ "strings"
+)
+
+// GroupLocaleText 是分组名称与描述在某个界面语言下的译文。
+// 字段为空表示该语言沿用分组自身的 name/description。
+type GroupLocaleText struct {
+ Name string `json:"name,omitempty"`
+ Description string `json:"description,omitempty"`
+}
+
+// GroupI18n 以界面语言代码(如 "en"、"zh")为键保存分组展示文案的译文。
+// 仅用于页面展示;分组的唯一性、搜索与各类日志仍以 name 为准。
+type GroupI18n map[string]GroupLocaleText
+
+// Localize 返回 name、description 在请求首选语言下的版本;该语言没有译文的字段保持原值。
+// acceptLanguage 是 Accept-Language 请求头。只采用其中优先级最高的语言:原字段的语言
+// 未知,退到次选语言的译文不一定比原字段更合适。
+func (m GroupI18n) Localize(acceptLanguage, name, description string) (string, string) {
+ text, ok := m.lookup(preferredLanguage(acceptLanguage))
+ if !ok {
+ return name, description
+ }
+ if text.Name != "" {
+ name = text.Name
+ }
+ if text.Description != "" {
+ description = text.Description
+ }
+ return name, description
+}
+
+// LocalizeName 是只需要名称时的 Localize。
+func (m GroupI18n) LocalizeName(acceptLanguage, name string) string {
+ name, _ = m.Localize(acceptLanguage, name, "")
+ return name
+}
+
+// CanonicalLocale 按 BCP 47 的惯用大小写书写语言代码:主语言小写,4 位文字代码首字母大写,
+// 2 位地区代码大写,其余小写(zh-hant-tw -> zh-Hant-TW);单字母扩展标记之后的部分全部小写。
+// 只调整大小写,不校验代码是否合法。
+func CanonicalLocale(locale string) string {
+ subtags := strings.Split(locale, "-")
+ extension := false
+ for i, subtag := range subtags {
+ subtag = strings.ToLower(subtag)
+ switch {
+ case i == 0 || extension:
+ case len(subtag) == 1:
+ extension = true
+ case len(subtag) == 2:
+ subtag = strings.ToUpper(subtag)
+ case len(subtag) == 4:
+ subtag = strings.ToUpper(subtag[:1]) + subtag[1:]
+ }
+ subtags[i] = subtag
+ }
+ return strings.Join(subtags, "-")
+}
+
+// lookup 先按完整语言代码匹配(zh-TW),再按主语言匹配(zh-CN -> zh),不区分大小写。
+// 写入时语言代码已统一为 CanonicalLocale,同一语言只有一个键;若存有仅大小写不同的多个键,
+// 规范写法的键优先,其余按字节序取最小者,保证同一请求语言的结果固定。
+func (m GroupI18n) lookup(tag string) (GroupLocaleText, bool) {
+ if tag == "" || len(m) == 0 {
+ return GroupLocaleText{}, false
+ }
+ primary, _, _ := strings.Cut(tag, "-")
+ for _, candidate := range []string{tag, primary} {
+ candidate = CanonicalLocale(candidate)
+ if text, ok := m[candidate]; ok {
+ return text, true
+ }
+ matched := ""
+ for locale := range m {
+ if strings.EqualFold(locale, candidate) && (matched == "" || locale < matched) {
+ matched = locale
+ }
+ }
+ if matched != "" {
+ return m[matched], true
+ }
+ }
+ return GroupLocaleText{}, false
+}
+
+// preferredLanguage 取 Accept-Language 中权重最高的语言代码,权重相同取靠前者;
+// 通配符 * 与 q=0 的条目不参与。
+func preferredLanguage(acceptLanguage string) string {
+ best, bestQ := "", 0.0
+ for _, part := range strings.Split(acceptLanguage, ",") {
+ tag, params, _ := strings.Cut(part, ";")
+ tag = strings.ReplaceAll(strings.TrimSpace(tag), "_", "-")
+ if tag == "" || tag == "*" {
+ continue
+ }
+ q := 1.0
+ if value, ok := strings.CutPrefix(strings.TrimSpace(params), "q="); ok {
+ parsed, err := strconv.ParseFloat(strings.TrimSpace(value), 64)
+ if err != nil {
+ continue
+ }
+ q = parsed
+ }
+ if q > bestQ {
+ best, bestQ = tag, q
+ }
+ }
+ return best
+}
diff --git a/backend/internal/domain/group_i18n_test.go b/backend/internal/domain/group_i18n_test.go
new file mode 100644
index 000000000..2860a0a6e
--- /dev/null
+++ b/backend/internal/domain/group_i18n_test.go
@@ -0,0 +1,107 @@
+package domain
+
+import "testing"
+
+func TestGroupI18nLocalize(t *testing.T) {
+ i18n := GroupI18n{
+ "en": {Name: "Standard", Description: "Pro + Max pool"},
+ "zh-TW": {Name: "標準"},
+ "ja": {Description: "説明のみ"},
+ }
+ const name, description = "标准", "号池"
+
+ tests := []struct {
+ title string
+ acceptLanguage string
+ wantName string
+ wantDescription string
+ }{
+ {"exact locale", "en", "Standard", "Pro + Max pool"},
+ {"region falls back to the primary language", "en-US", "Standard", "Pro + Max pool"},
+ {"locale match ignores case and underscore", "ZH_tw", "標準", description},
+ {"a missing field keeps the original text", "ja", name, "説明のみ"},
+ {"no translation for the language keeps both", "zh", name, description},
+ {"primary language does not match a regional translation", "zh-CN", name, description},
+ {"empty header keeps both", "", name, description},
+ {"wildcard only keeps both", "*", name, description},
+ // 原字段的语言未知,不退到次选语言:浏览器的 zh 用户不应拿到英文译文。
+ {"only the preferred language is considered", "zh-CN,zh;q=0.9,en;q=0.8", name, description},
+ {"highest weight wins over position", "zh;q=0.5, en;q=0.9", "Standard", "Pro + Max pool"},
+ {"equal weight keeps the first", "en, zh", "Standard", "Pro + Max pool"},
+ {"entries with q=0 are ignored", "en;q=0, ja", name, "説明のみ"},
+ {"malformed weight is skipped", "en;q=abc, ja", name, "説明のみ"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.title, func(t *testing.T) {
+ gotName, gotDescription := i18n.Localize(tt.acceptLanguage, name, description)
+ if gotName != tt.wantName || gotDescription != tt.wantDescription {
+ t.Fatalf("Localize(%q) = (%q, %q), want (%q, %q)",
+ tt.acceptLanguage, gotName, gotDescription, tt.wantName, tt.wantDescription)
+ }
+ })
+ }
+}
+
+func TestGroupI18nLocalize_NilMap(t *testing.T) {
+ var i18n GroupI18n
+
+ name, description := i18n.Localize("en", "标准", "号池")
+
+ if name != "标准" || description != "号池" {
+ t.Fatalf("nil translations must keep the original text, got (%q, %q)", name, description)
+ }
+ if got := i18n.LocalizeName("en", "标准"); got != "标准" {
+ t.Fatalf("LocalizeName on nil translations = %q", got)
+ }
+}
+
+func TestGroupI18nLocalizeName(t *testing.T) {
+ i18n := GroupI18n{"en": {Name: "Standard"}}
+
+ if got := i18n.LocalizeName("en", "标准"); got != "Standard" {
+ t.Fatalf("LocalizeName(en) = %q", got)
+ }
+ if got := i18n.LocalizeName("zh", "标准"); got != "标准" {
+ t.Fatalf("LocalizeName(zh) = %q", got)
+ }
+}
+
+func TestCanonicalLocale(t *testing.T) {
+ tests := map[string]string{
+ "en": "en",
+ "EN": "en",
+ "zh-tw": "zh-TW",
+ "ZH-Hant-tw": "zh-Hant-TW",
+ "es-419": "es-419",
+ "de-CH-1901": "de-CH-1901",
+ "en-US-x-Twain": "en-US-x-twain",
+ }
+ for in, want := range tests {
+ if got := CanonicalLocale(in); got != want {
+ t.Errorf("CanonicalLocale(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+// 写入路径已拒绝仅大小写不同的语言代码;已存在的此类数据读取时也必须得到固定结果。
+func TestGroupI18nLocalize_CaseCollidingKeysAreDeterministic(t *testing.T) {
+ tests := []struct {
+ title string
+ i18n GroupI18n
+ acceptLanguage string
+ want string
+ }{
+ {"canonical key wins", GroupI18n{"EN": {Name: "B"}, "en": {Name: "A"}, "En": {Name: "C"}}, "en", "A"},
+ {"otherwise the smallest key wins", GroupI18n{"eN": {Name: "B"}, "EN": {Name: "A"}}, "en", "A"},
+ {"primary language fallback is deterministic too", GroupI18n{"ZH": {Name: "B"}, "zh": {Name: "A"}}, "zh-CN", "A"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.title, func(t *testing.T) {
+ for range 200 {
+ if got := tt.i18n.LocalizeName(tt.acceptLanguage, "原名"); got != tt.want {
+ t.Fatalf("LocalizeName(%q) = %q, want %q", tt.acceptLanguage, got, tt.want)
+ }
+ }
+ })
+ }
+}
diff --git a/backend/internal/handler/admin/account_codex_import.go b/backend/internal/handler/admin/account_codex_import.go
index b604d2be1..9d7cb7e5b 100644
--- a/backend/internal/handler/admin/account_codex_import.go
+++ b/backend/internal/handler/admin/account_codex_import.go
@@ -908,14 +908,16 @@ func buildCodexAgentIdentityKeys(accountID string) []string {
return []string{"account:" + accountID}
}
-// buildCodexStoredIdentityKeys 生成存量账号索引键,保留 user/account 维度,
-// 让 accessToken-only 账号后续升级为完整 OAuth 时仍能命中并更新原账号。
+// buildCodexStoredIdentityKeys 生成存量账号索引键,按 workspace/account
+// 和 user 组合隔离身份,避免同一用户在不同 workspace 的账号误合并。
func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string) []string {
keys := make([]string, 0, 3)
accountID = strings.TrimSpace(accountID)
userID = strings.TrimSpace(userID)
accessToken = strings.TrimSpace(accessToken)
- if userID != "" {
+ if accountID != "" && userID != "" {
+ keys = append(keys, "account_user:"+codexCompositeIdentityKey(accountID, userID))
+ } else if userID != "" {
keys = append(keys, "user:"+userID)
}
if accountID == "" && userID == "" {
@@ -932,6 +934,10 @@ func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string)
return keys
}
+func codexCompositeIdentityKey(accountID, userID string) string {
+ return fmt.Sprintf("%d:%s%d:%s", len(accountID), accountID, len(userID), userID)
+}
+
func buildCodexAccountIndex(accounts []service.Account) *codexAccountIndex {
index := &codexAccountIndex{
accountsByKey: map[string][]service.Account{},
diff --git a/backend/internal/handler/admin/account_codex_import_test.go b/backend/internal/handler/admin/account_codex_import_test.go
index 3d440723d..6011178bb 100644
--- a/backend/internal/handler/admin/account_codex_import_test.go
+++ b/backend/internal/handler/admin/account_codex_import_test.go
@@ -303,8 +303,8 @@ func TestResolveCodexImportExpiryForNoRefreshTokenUsesEarlierRequestExpiry(t *te
func TestCodexIdentityKeysPreferStrongIdentifiers(t *testing.T) {
keys := buildCodexImportIdentityKeys("acct-1", "user-1", "same@example.com", "token", "refresh")
- if len(keys) == 0 || keys[0] != "user:user-1" {
- t.Fatalf("user key should have highest priority when refresh token exists: %v", keys)
+ if len(keys) == 0 || keys[0] != "account_user:6:acct-16:user-1" {
+ t.Fatalf("workspace-scoped user key should have highest priority when refresh token exists: %v", keys)
}
if keys[len(keys)-1] != "account:acct-1" {
t.Fatalf("shared account key should be the last fallback: %v", keys)
@@ -465,12 +465,84 @@ func TestCodexAccountIndexKeepsAllCandidatesForSharedAccountKey(t *testing.T) {
if got == nil || got.ID != member.ID {
t.Fatalf("Find by user key = %v, want member account ID %d", got, member.ID)
}
- if matchedKey != "user:user-2" {
- t.Fatalf("matched key = %q, want user:user-2", matchedKey)
+ if matchedKey != "account_user:6:team-16:user-2" {
+ t.Fatalf("matched key = %q, want account_user:6:team-16:user-2", matchedKey)
}
}
}
+func TestImportCodexSessionsSameUserDifferentWorkspacesCreatesSeparateAccounts(t *testing.T) {
+ svc := newCodexImportMemoryAdminService(nil)
+ handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
+ entries := []codexImportEntry{
+ {Index: 1, Value: buildCodexRefreshImportValue(t, "workspace-1", "shared-user", "refresh-1")},
+ {Index: 2, Value: buildCodexRefreshImportValue(t, "workspace-2", "shared-user", "refresh-2")},
+ }
+
+ result, err := handler.importCodexSessions(context.Background(), req, entries)
+ if err != nil {
+ t.Fatalf("importCodexSessions error = %v", err)
+ }
+ if result.Created != 2 || result.Updated != 0 || result.Skipped != 0 || result.Failed != 0 {
+ t.Fatalf("result = %+v, want two created accounts", result)
+ }
+ if len(svc.createdAccounts) != 2 {
+ t.Fatalf("created accounts = %d, want 2", len(svc.createdAccounts))
+ }
+ if got := svc.createdAccounts[0].Credentials["chatgpt_account_id"]; got != "workspace-1" {
+ t.Fatalf("first workspace = %v, want workspace-1", got)
+ }
+ if got := svc.createdAccounts[1].Credentials["chatgpt_account_id"]; got != "workspace-2" {
+ t.Fatalf("second workspace = %v, want workspace-2", got)
+ }
+}
+
+func TestCodexImportIdentityKeySeparatesDelimiterValues(t *testing.T) {
+ left := buildCodexImportIdentityKeys("ab:c", "shared-user", "", "", "refresh")
+ right := buildCodexImportIdentityKeys("ab", "c:shared-user", "", "", "refresh")
+ if left[0] == right[0] {
+ t.Fatalf("composite identity keys collided: %q", left[0])
+ }
+}
+
+func TestImportCodexSessionsSameWorkspaceAccountUpdatesAndDifferentUserIsolated(t *testing.T) {
+ svc := newCodexImportMemoryAdminService(nil)
+ handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
+ initialEntries := []codexImportEntry{
+ {Index: 1, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-1", "refresh-1")},
+ {Index: 2, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-2", "refresh-2")},
+ }
+
+ initialResult, err := handler.importCodexSessions(context.Background(), req, initialEntries)
+ if err != nil {
+ t.Fatalf("importCodexSessions error = %v", err)
+ }
+ if initialResult.Created != 2 || initialResult.Updated != 0 || initialResult.Skipped != 0 || initialResult.Failed != 0 {
+ t.Fatalf("initial result = %+v, want two created accounts", initialResult)
+ }
+
+ updateResult, err := handler.importCodexSessions(context.Background(), req, []codexImportEntry{
+ {Index: 3, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-1", "refresh-3")},
+ })
+ if err != nil {
+ t.Fatalf("importCodexSessions update error = %v", err)
+ }
+ if updateResult.Created != 0 || updateResult.Updated != 1 || updateResult.Skipped != 0 || updateResult.Failed != 0 {
+ t.Fatalf("update result = %+v, want one updated account", updateResult)
+ }
+ if len(svc.createdAccounts) != 2 || len(svc.updatedAccounts) != 1 {
+ t.Fatalf("created = %d, updated = %d, want 2 and 1", len(svc.createdAccounts), len(svc.updatedAccounts))
+ }
+ if svc.updatedAccounts[0].id != 100 {
+ t.Fatalf("updated account ID = %d, want user-1 account ID 100", svc.updatedAccounts[0].id)
+ }
+ if got := svc.updatedAccounts[0].input.Credentials["chatgpt_user_id"]; got != "user-1" {
+ t.Fatalf("updated user = %v, want user-1", got)
+ }
+}
+
func TestCodexAccountIndexUpsertReplacesSameAccount(t *testing.T) {
legacy := service.Account{
ID: 40,
diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go
index ddf63b133..7d10dbcfb 100644
--- a/backend/internal/handler/admin/account_handler.go
+++ b/backend/internal/handler/admin/account_handler.go
@@ -990,6 +990,22 @@ func (h *AccountHandler) GetOpenAIRequestTimezones(c *gin.Context) {
})
}
+// DetectOpenAIRequestTimezone 立即检测账号出口 IP 的时区(请求时区为「跟随 IP 出口」时)。
+// POST /api/v1/admin/accounts/:id/openai-request-timezone/detect
+func (h *AccountHandler) DetectOpenAIRequestTimezone(c *gin.Context) {
+ accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
+ if err != nil {
+ response.BadRequest(c, "Invalid account ID")
+ return
+ }
+ account, err := h.adminService.DetectOpenAIRequestTimezone(c.Request.Context(), accountID)
+ if err != nil {
+ response.ErrorFrom(c, err)
+ return
+ }
+ response.Success(c, h.buildAccountResponseWithRuntime(c.Request.Context(), account))
+}
+
func (h *AccountHandler) GetByID(c *gin.Context) {
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
@@ -3078,13 +3094,13 @@ func antigravityAccountTestModels(rawMapping any) []antigravity.ClaudeModel {
switch mapping := rawMapping.(type) {
case map[string]any:
for id := range mapping {
- if strings.TrimSpace(id) != "" {
+ if strings.TrimSpace(id) != "" && !strings.Contains(id, "*") {
mappedIDs = append(mappedIDs, id)
}
}
case map[string]string:
for id := range mapping {
- if strings.TrimSpace(id) != "" {
+ if strings.TrimSpace(id) != "" && !strings.Contains(id, "*") {
mappedIDs = append(mappedIDs, id)
}
}
diff --git a/backend/internal/handler/admin/account_handler_available_models_test.go b/backend/internal/handler/admin/account_handler_available_models_test.go
index e08a73374..24c8bca63 100644
--- a/backend/internal/handler/admin/account_handler_available_models_test.go
+++ b/backend/internal/handler/admin/account_handler_available_models_test.go
@@ -345,11 +345,12 @@ func TestAccountHandlerGetAvailableModels_Antigravity(t *testing.T) {
{name: "empty JSON mapping", credentials: map[string]any{"model_mapping": map[string]any{}}, want: defaults},
{name: "empty string mapping", credentials: map[string]any{"model_mapping": map[string]string{}}, want: defaults},
{name: "blank key", credentials: map[string]any{"model_mapping": map[string]any{" ": "upstream-model"}}, want: defaults},
- {name: "JSON mapping keys and metadata", credentials: map[string]any{"model_mapping": map[string]any{
- known.ID: known.ID, custom.ID: "upstream-model",
+ {name: "wildcard only falls back to defaults", credentials: map[string]any{"model_mapping": map[string]any{"claude-*": "claude-sonnet-4-6", "gemini-3*": "gemini-3-flash"}}, want: defaults},
+ {name: "JSON mapping keys and metadata skips wildcards", credentials: map[string]any{"model_mapping": map[string]any{
+ known.ID: known.ID, custom.ID: "upstream-model", "claude-*": "claude-sonnet-4-6",
}}, want: []antigravity.ClaudeModel{custom, known}},
- {name: "string mapping keys and metadata", credentials: map[string]any{"model_mapping": map[string]string{
- known.ID: known.ID, custom.ID: "upstream-model",
+ {name: "string mapping keys and metadata skips wildcards", credentials: map[string]any{"model_mapping": map[string]string{
+ known.ID: known.ID, custom.ID: "upstream-model", "gemini-*": "gemini-3-flash",
}}, want: []antigravity.ClaudeModel{custom, known}},
}
for _, tc := range cases {
diff --git a/backend/internal/handler/admin/admin_service_stub_test.go b/backend/internal/handler/admin/admin_service_stub_test.go
index 5873390a9..79a7c921f 100644
--- a/backend/internal/handler/admin/admin_service_stub_test.go
+++ b/backend/internal/handler/admin/admin_service_stub_test.go
@@ -811,6 +811,10 @@ func (s *stubAdminService) RevertAccountProxyFallback(ctx context.Context, id in
return nil
}
+func (s *stubAdminService) DetectOpenAIRequestTimezone(ctx context.Context, id int64) (*service.Account, error) {
+ return &service.Account{ID: id}, nil
+}
+
func (s *stubAdminService) CreateShadow(ctx context.Context, parentID int64, opts service.ShadowOptions) (*service.Account, error) {
if s.createSparkShadowErr != nil {
return nil, s.createSparkShadowErr
diff --git a/backend/internal/handler/admin/codex_ticket_handler.go b/backend/internal/handler/admin/codex_ticket_handler.go
index 096687031..1b0261e46 100644
--- a/backend/internal/handler/admin/codex_ticket_handler.go
+++ b/backend/internal/handler/admin/codex_ticket_handler.go
@@ -68,8 +68,7 @@ func (h *AccountHandler) GetCodexTicketHistory(c *gin.Context) {
reason = "disabled"
}
if available && h.codexTicketSettings != nil {
- proxies, err := h.codexTicketSettings.AvailableCodexTicketProxies(c.Request.Context())
- if err != nil || len(proxies) == 0 {
+ if !h.codexTicketSettings.CodexTicketManualProxyAvailable(c.Request.Context()) {
available, reason = false, "no_proxy"
}
}
@@ -183,12 +182,12 @@ func (h *ProxyHandler) GetCodexTicketPool(c *gin.Context) {
codexTicketError(c, service.ErrCodexTicketUnavailable)
return
}
- pool, err := h.codexTicketSettings.GetCodexTicketPool(c.Request.Context())
+ view, err := h.codexTicketSettings.DescribeCodexTicketPool(c.Request.Context())
if err != nil {
response.ErrorFrom(c, err)
return
}
- response.Success(c, pool)
+ response.Success(c, view)
}
func (h *ProxyHandler) UpdateCodexTicketPool(c *gin.Context) {
@@ -205,7 +204,7 @@ func (h *ProxyHandler) UpdateCodexTicketPool(c *gin.Context) {
response.BadRequest(c, err.Error())
return
}
- saved, err := h.codexTicketSettings.GetCodexTicketPool(c.Request.Context())
+ saved, err := h.codexTicketSettings.DescribeCodexTicketPool(c.Request.Context())
if err != nil {
response.ErrorFrom(c, err)
return
@@ -324,6 +323,32 @@ func (h *AccountHandler) GetCodexTicketCadence(c *gin.Context) {
response.Success(c, h.codexTicketGateway.CodexTicketCadence(c.Request.Context()))
}
+func (h *AccountHandler) GetCodexTicketProxySource(c *gin.Context) {
+ if h.codexTicketSettings == nil {
+ codexTicketError(c, service.ErrCodexTicketUnavailable)
+ return
+ }
+ response.Success(c, service.CodexTicketProxySource{Source: h.codexTicketSettings.GetCodexTicketProxySource(c.Request.Context())})
+}
+
+func (h *AccountHandler) UpdateCodexTicketProxySource(c *gin.Context) {
+ if h.codexTicketSettings == nil {
+ codexTicketError(c, service.ErrCodexTicketUnavailable)
+ return
+ }
+ var value service.CodexTicketProxySource
+ if err := c.ShouldBindJSON(&value); err != nil {
+ response.BadRequest(c, "Invalid proxy source")
+ return
+ }
+ source, err := h.codexTicketSettings.SetCodexTicketProxySource(c.Request.Context(), value.Source)
+ if err != nil {
+ response.BadRequest(c, err.Error())
+ return
+ }
+ response.Success(c, service.CodexTicketProxySource{Source: source})
+}
+
func (h *AccountHandler) UpdateCodexTicketCadence(c *gin.Context) {
if h.codexTicketSettings == nil {
codexTicketError(c, service.ErrCodexTicketUnavailable)
diff --git a/backend/internal/handler/admin/group_handler.go b/backend/internal/handler/admin/group_handler.go
index a5ccc87e3..e8bc1403d 100644
--- a/backend/internal/handler/admin/group_handler.go
+++ b/backend/internal/handler/admin/group_handler.go
@@ -142,6 +142,8 @@ type simpleModeGroupResponse struct {
Platform string `json:"platform"`
Status string `json:"status"`
+ I18n service.GroupI18n `json:"i18n,omitempty"`
+
AccountCount int64 `json:"account_count,omitempty"`
ActiveAccountCount int64 `json:"active_account_count,omitempty"`
RateLimitedAccountCount int64 `json:"rate_limited_account_count,omitempty"`
@@ -157,6 +159,7 @@ func groupForSimpleMode(group *service.Group) *simpleModeGroupResponse {
return &simpleModeGroupResponse{
ID: group.ID, Name: group.Name, Description: group.Description, Platform: group.Platform,
Status: group.Status,
+ I18n: group.I18n,
AccountCount: group.AccountCount,
ActiveAccountCount: group.ActiveAccountCount, RateLimitedAccountCount: group.RateLimitedAccountCount,
SortOrder: group.SortOrder, CreatedAt: group.CreatedAt, UpdatedAt: group.UpdatedAt,
@@ -167,7 +170,7 @@ func sanitizeCreateGroupRequestForSimpleMode(req *CreateGroupRequest) {
if req == nil {
return
}
- allowed := CreateGroupRequest{Name: req.Name, Description: req.Description, Platform: req.Platform}
+ allowed := CreateGroupRequest{Name: req.Name, Description: req.Description, I18n: req.I18n, Platform: req.Platform}
allowed.RateMultiplier = 1
allowed.SubscriptionType = service.SubscriptionTypeStandard
*req = allowed
@@ -177,13 +180,14 @@ func sanitizeUpdateGroupRequestForSimpleMode(req *UpdateGroupRequest) {
if req == nil {
return
}
- *req = UpdateGroupRequest{Name: req.Name, Description: req.Description}
+ *req = UpdateGroupRequest{Name: req.Name, Description: req.Description, I18n: req.I18n}
}
// CreateGroupRequest represents create group request
type CreateGroupRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
+ I18n service.GroupI18n `json:"i18n"` // 名称与描述的界面语言译文
Platform string `json:"platform" binding:"omitempty,group_platform"`
RateMultiplier float64 `json:"rate_multiplier"`
IsExclusive bool `json:"is_exclusive"`
@@ -258,6 +262,7 @@ type CreateGroupRequest struct {
type UpdateGroupRequest struct {
Name string `json:"name"`
Description *string `json:"description"`
+ I18n *service.GroupI18n `json:"i18n"` // 缺省不修改,传入则整体替换
Platform string `json:"platform" binding:"omitempty,group_platform"`
RateMultiplier *float64 `json:"rate_multiplier"`
IsExclusive *bool `json:"is_exclusive"`
@@ -664,6 +669,7 @@ func (h *GroupHandler) Create(c *gin.Context) {
group, err := h.adminService.CreateGroup(c.Request.Context(), &service.CreateGroupInput{
Name: req.Name,
Description: req.Description,
+ I18n: req.I18n,
Platform: req.Platform,
RateMultiplier: req.RateMultiplier,
IsExclusive: req.IsExclusive,
@@ -809,6 +815,7 @@ func (h *GroupHandler) Update(c *gin.Context) {
group, err := h.adminService.UpdateGroup(c.Request.Context(), groupID, &service.UpdateGroupInput{
Name: req.Name,
Description: req.Description,
+ I18n: req.I18n,
Platform: req.Platform,
RateMultiplier: req.RateMultiplier,
IsExclusive: req.IsExclusive,
diff --git a/backend/internal/handler/api_key_handler.go b/backend/internal/handler/api_key_handler.go
index d42de8aa1..1c2603e76 100644
--- a/backend/internal/handler/api_key_handler.go
+++ b/backend/internal/handler/api_key_handler.go
@@ -142,7 +142,7 @@ func (h *APIKeyHandler) List(c *gin.Context) {
out := make([]dto.APIKey, 0, len(keys))
for i := range keys {
- out = append(out, *dto.APIKeyFromService(&keys[i]))
+ out = append(out, *dto.APIKeyFromService(&keys[i]).Localized(c.GetHeader("Accept-Language")))
}
response.Paginated(c, out, result.Total, page, pageSize)
}
@@ -174,7 +174,7 @@ func (h *APIKeyHandler) GetByID(c *gin.Context) {
return
}
- response.Success(c, dto.APIKeyFromService(key))
+ response.Success(c, dto.APIKeyFromService(key).Localized(c.GetHeader("Accept-Language")))
}
// Create handles creating a new API key
@@ -222,7 +222,7 @@ func (h *APIKeyHandler) Create(c *gin.Context) {
if err != nil {
return nil, err
}
- return dto.APIKeyFromService(key), nil
+ return dto.APIKeyFromService(key).Localized(c.GetHeader("Accept-Language")), nil
})
}
@@ -290,7 +290,7 @@ func (h *APIKeyHandler) Update(c *gin.Context) {
return
}
- response.Success(c, dto.APIKeyFromService(key))
+ response.Success(c, dto.APIKeyFromService(key).Localized(c.GetHeader("Accept-Language")))
}
// Delete handles deleting an API key
@@ -334,7 +334,7 @@ func (h *APIKeyHandler) GetAvailableGroups(c *gin.Context) {
out := make([]dto.Group, 0, len(groups))
for i := range groups {
- out = append(out, *dto.GroupFromService(&groups[i]))
+ out = append(out, *dto.GroupFromService(&groups[i]).Localized(c.GetHeader("Accept-Language")))
}
response.Success(c, out)
}
diff --git a/backend/internal/handler/available_channel_handler.go b/backend/internal/handler/available_channel_handler.go
index 2815a5640..f71840737 100644
--- a/backend/internal/handler/available_channel_handler.go
+++ b/backend/internal/handler/available_channel_handler.go
@@ -62,6 +62,9 @@ type userAvailableGroup struct {
PeakEnd string `json:"peak_end"`
PeakRateMultiplier float64 `json:"peak_rate_multiplier"`
IsExclusive bool `json:"is_exclusive"`
+
+ // 不对外输出;List 按请求语言把 Name 换成译文后丢弃。
+ i18n service.GroupI18n
}
// userSupportedModelPricing 用户可见的定价字段白名单。
@@ -154,6 +157,7 @@ func (h *AvailableChannelHandler) List(c *gin.Context) {
return
}
+ acceptLanguage := c.GetHeader("Accept-Language")
out := make([]userAvailableChannel, 0, len(channels))
for _, ch := range channels {
if ch.Status != service.StatusActive {
@@ -163,6 +167,7 @@ func (h *AvailableChannelHandler) List(c *gin.Context) {
if len(visibleGroups) == 0 {
continue
}
+ localizeUserAvailableGroups(visibleGroups, acceptLanguage)
sections := buildPlatformSections(ch, visibleGroups)
if len(sections) == 0 {
continue
@@ -177,6 +182,13 @@ func (h *AvailableChannelHandler) List(c *gin.Context) {
response.Success(c, out)
}
+// localizeUserAvailableGroups 把分组名称就地换成请求首选语言的版本。
+func localizeUserAvailableGroups(groups []userAvailableGroup, acceptLanguage string) {
+ for i := range groups {
+ groups[i].Name = groups[i].i18n.LocalizeName(acceptLanguage, groups[i].Name)
+ }
+}
+
// buildPlatformSections 把一个渠道按 visibleGroups 的平台集合拆成有序的 section 列表:
// 每个 section 对应一个具体平台,只包含该平台的 groups 和 supported_models。
//
@@ -254,6 +266,7 @@ func filterUserVisibleGroups(
visible = append(visible, userAvailableGroup{
ID: g.ID,
Name: g.Name,
+ i18n: g.I18n,
Platform: g.Platform,
SubscriptionType: g.SubscriptionType,
RateMultiplier: g.RateMultiplier,
diff --git a/backend/internal/handler/dto/group_localize.go b/backend/internal/handler/dto/group_localize.go
new file mode 100644
index 000000000..6a9ce7d8f
--- /dev/null
+++ b/backend/internal/handler/dto/group_localize.go
@@ -0,0 +1,49 @@
+package dto
+
+// 用户侧接口在输出前调用 Localized:把分组的名称与描述换成请求首选语言
+// (Accept-Language)的版本,并去掉译文表。管理端接口不调用,保留原字段与译文表,
+// 分组编辑表单依赖原字段回写。
+
+// Localized 就地本地化分组并返回自身。
+func (g *Group) Localized(acceptLanguage string) *Group {
+ if g == nil {
+ return nil
+ }
+ g.Name, g.Description = g.I18n.Localize(acceptLanguage, g.Name, g.Description)
+ g.I18n = nil
+ return g
+}
+
+// Localized 本地化 API Key 所属分组并返回自身。
+func (k *APIKey) Localized(acceptLanguage string) *APIKey {
+ if k != nil {
+ k.Group.Localized(acceptLanguage)
+ }
+ return k
+}
+
+// Localized 本地化兑换码关联分组并返回自身。
+func (r *RedeemCode) Localized(acceptLanguage string) *RedeemCode {
+ if r != nil {
+ r.Group.Localized(acceptLanguage)
+ }
+ return r
+}
+
+// Localized 本地化使用记录关联的分组(含其 API Key 与订阅各自携带的分组)并返回自身。
+func (l *UsageLog) Localized(acceptLanguage string) *UsageLog {
+ if l != nil {
+ l.Group.Localized(acceptLanguage)
+ l.APIKey.Localized(acceptLanguage)
+ l.Subscription.Localized(acceptLanguage)
+ }
+ return l
+}
+
+// Localized 本地化订阅关联分组并返回自身。
+func (s *UserSubscription) Localized(acceptLanguage string) *UserSubscription {
+ if s != nil {
+ s.Group.Localized(acceptLanguage)
+ }
+ return s
+}
diff --git a/backend/internal/handler/dto/group_localize_test.go b/backend/internal/handler/dto/group_localize_test.go
new file mode 100644
index 000000000..978e0a1f1
--- /dev/null
+++ b/backend/internal/handler/dto/group_localize_test.go
@@ -0,0 +1,71 @@
+package dto
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/domain"
+ "github.com/stretchr/testify/require"
+)
+
+func localizableGroup() *Group {
+ return &Group{
+ ID: 1, Name: "标准", Description: "号池",
+ I18n: domain.GroupI18n{"en": {Name: "Standard", Description: "Pro + Max pool"}},
+ }
+}
+
+func TestGroupLocalized_ReplacesTextAndDropsTranslations(t *testing.T) {
+ g := localizableGroup().Localized("en")
+
+ require.Equal(t, "Standard", g.Name)
+ require.Equal(t, "Pro + Max pool", g.Description)
+
+ raw, err := json.Marshal(g)
+ require.NoError(t, err)
+ var decoded map[string]any
+ require.NoError(t, json.Unmarshal(raw, &decoded))
+ require.NotContains(t, decoded, "i18n", "user-facing output must not carry the translation table")
+}
+
+func TestGroupLocalized_KeepsOriginalWhenLanguageHasNoTranslation(t *testing.T) {
+ g := localizableGroup().Localized("zh")
+
+ require.Equal(t, "标准", g.Name)
+ require.Equal(t, "号池", g.Description)
+ require.Nil(t, g.I18n)
+}
+
+func TestLocalized_NilSafe(t *testing.T) {
+ require.Nil(t, (*Group)(nil).Localized("en"))
+ require.Nil(t, (*APIKey)(nil).Localized("en"))
+ require.Nil(t, (*RedeemCode)(nil).Localized("en"))
+ require.Nil(t, (*UsageLog)(nil).Localized("en"))
+ require.Nil(t, (*UserSubscription)(nil).Localized("en"))
+
+ // 未携带分组的记录原样返回
+ require.Nil(t, (&APIKey{}).Localized("en").Group)
+}
+
+func TestLocalized_NestedGroups(t *testing.T) {
+ key := (&APIKey{Group: localizableGroup()}).Localized("en")
+ require.Equal(t, "Standard", key.Group.Name)
+
+ code := (&RedeemCode{Group: localizableGroup()}).Localized("en")
+ require.Equal(t, "Standard", code.Group.Name)
+
+ sub := (&UserSubscription{Group: localizableGroup()}).Localized("en")
+ require.Equal(t, "Standard", sub.Group.Name)
+
+ // 使用记录除自身分组外,还带着 API Key 与订阅各自的分组
+ log := (&UsageLog{
+ Group: localizableGroup(),
+ APIKey: &APIKey{Group: localizableGroup()},
+ Subscription: &UserSubscription{Group: localizableGroup()},
+ }).Localized("en")
+ require.Equal(t, "Standard", log.Group.Name)
+ require.Equal(t, "Standard", log.APIKey.Group.Name)
+ require.Equal(t, "Standard", log.Subscription.Group.Name)
+ require.Nil(t, log.APIKey.Group.I18n)
+ require.Nil(t, log.Subscription.Group.I18n)
+}
diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go
index 8ff75e756..6a2b07631 100644
--- a/backend/internal/handler/dto/mappers.go
+++ b/backend/internal/handler/dto/mappers.go
@@ -182,6 +182,7 @@ func groupFromServiceBase(g *service.Group) Group {
ID: g.ID,
Name: g.Name,
Description: g.Description,
+ I18n: g.I18n,
Platform: g.Platform,
RateMultiplier: g.RateMultiplier,
IsExclusive: g.IsExclusive,
diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go
index 21e7077e2..a05857f1e 100644
--- a/backend/internal/handler/dto/types.go
+++ b/backend/internal/handler/dto/types.go
@@ -99,6 +99,10 @@ type Group struct {
IsExclusive bool `json:"is_exclusive"`
Status string `json:"status"`
+ // I18n 名称与描述的各语言译文。只有管理端输出;用户侧接口经 Localized 把
+ // name/description 换成请求语言的版本后清空本字段。
+ I18n domain.GroupI18n `json:"i18n,omitempty"`
+
SubscriptionType string `json:"subscription_type"`
DailyLimitUSD *float64 `json:"daily_limit_usd"`
WeeklyLimitUSD *float64 `json:"weekly_limit_usd"`
diff --git a/backend/internal/handler/endpoint.go b/backend/internal/handler/endpoint.go
index 38ce98a51..105f8dac6 100644
--- a/backend/internal/handler/endpoint.go
+++ b/backend/internal/handler/endpoint.go
@@ -32,6 +32,7 @@ const (
EndpointVideos = "/v1/videos"
EndpointSeedanceTasks = "/api/v3/contents/generations/tasks"
EndpointGeminiModels = "/v1beta/models"
+ EndpointGeminiCachedContents = "/v1beta/cachedContents"
)
const EndpointAntigravityGenerateContent = "/v1internal:streamGenerateContent"
@@ -53,6 +54,7 @@ const (
// "/v1/chat/completions" → "/v1/chat/completions"
// "/openai/v1/responses/foo" → "/v1/responses"
// "/v1beta/models/gemini:gen" → "/v1beta/models"
+// "/v1beta/cachedContents/abc" → "/v1beta/cachedContents"
//
// The OpenAI Responses API is also exposed via a few bare/alias
// routes that do not carry a "/v1/" prefix (top-level bare route and
@@ -117,6 +119,8 @@ func NormalizeInboundEndpoint(path string) string {
return EndpointResponses
case strings.Contains(path, EndpointGeminiModels):
return EndpointGeminiModels
+ case strings.Contains(path, EndpointGeminiCachedContents):
+ return EndpointGeminiCachedContents
default:
return path
}
@@ -194,7 +198,7 @@ func isBareOrSubpathOf(path, root string) bool {
// retain their paths. Grok raw Chat requests override this through the
// forwarding result consumed by resolveOpenAIUpstreamEndpoint.
// - Anthropic → /v1/messages
-// - Gemini → /v1beta/models
+// - Gemini → /v1beta/models(显式缓存管理接口保留 /v1beta/cachedContents)
// - Antigravity → /v1/messages (Claude) or gemini (Gemini)
// - Antigravity routes may target either Claude or Gemini, so the
// inbound endpoint is used to distinguish.
@@ -230,6 +234,9 @@ func DeriveUpstreamEndpoint(inbound, rawRequestPath, platform string) string {
return EndpointSystemOne
case service.PlatformGemini:
+ if inbound == EndpointGeminiCachedContents {
+ return EndpointGeminiCachedContents
+ }
return EndpointGeminiModels
case service.PlatformAntigravity:
diff --git a/backend/internal/handler/endpoint_test.go b/backend/internal/handler/endpoint_test.go
index 6bef9dcce..ac50a36a0 100644
--- a/backend/internal/handler/endpoint_test.go
+++ b/backend/internal/handler/endpoint_test.go
@@ -37,6 +37,8 @@ func TestNormalizeInboundEndpoint(t *testing.T) {
{"/v1/videos/generations", EndpointVideosGenerations},
{"/v1/videos/req_123", EndpointVideos},
{"/v1beta/models", EndpointGeminiModels},
+ {"/v1beta/cachedContents", EndpointGeminiCachedContents},
+ {"/v1beta/cachedContents/gfo2i2haszm3wbwiyivyok5cyddubfwsr77efg7h", EndpointGeminiCachedContents},
// Prefixed paths (antigravity, openai) — root Responses.
{"/antigravity/v1/messages", EndpointMessages},
@@ -102,6 +104,7 @@ func TestDeriveUpstreamEndpoint(t *testing.T) {
// Gemini.
{"gemini models", EndpointGeminiModels, "/v1beta/models/gemini:gen", service.PlatformGemini, EndpointGeminiModels},
+ {"gemini cached contents", EndpointGeminiCachedContents, "/v1beta/cachedContents/abc", service.PlatformGemini, EndpointGeminiCachedContents},
// OpenAI — root Responses.
{"openai responses root", EndpointResponses, "/v1/responses", service.PlatformOpenAI, EndpointResponses},
diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go
index 2f597e4e5..d50115451 100644
--- a/backend/internal/handler/gateway_handler.go
+++ b/backend/internal/handler/gateway_handler.go
@@ -52,12 +52,14 @@ type GatewayHandler struct {
errorPassthroughService *service.ErrorPassthroughService
contentModerationService *service.ContentModerationService
securityAuditCoordinator *securityaudit.Coordinator
- concurrencyHelper *ConcurrencyHelper
- userMsgQueueHelper *UserMsgQueueHelper
- maxAccountSwitches int
- maxAccountSwitchesGemini int
- cfg *config.Config
- settingService *service.SettingService
+ // geminiCachedContentService 管理 Gemini 显式缓存;为 nil 时相关接口不可用。
+ geminiCachedContentService *service.GeminiCachedContentService
+ concurrencyHelper *ConcurrencyHelper
+ userMsgQueueHelper *UserMsgQueueHelper
+ maxAccountSwitches int
+ maxAccountSwitchesGemini int
+ cfg *config.Config
+ settingService *service.SettingService
}
// NewGatewayHandler creates a new GatewayHandler
@@ -1195,7 +1197,7 @@ func (h *GatewayHandler) Models(c *gin.Context) {
return
}
- if len(availableModels) > 0 {
+ if len(availableModels) > 0 || (platform == service.PlatformOpenAI && availableModels != nil) {
writeModelsList(c, platform, availableModels)
return
}
@@ -1326,7 +1328,7 @@ func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID *
continue
}
platformModels := h.gatewayService.GetAvailableModels(ctx, groupID, platform)
- if len(platformModels) == 0 {
+ if len(platformModels) == 0 && (platform != service.PlatformOpenAI || platformModels == nil) {
// CN 供应商没有静态默认模型列表(defaultModelIDsForPlatform 的
// default 分支是 Claude 列表),composite 下只暴露账号映射键。
if _, ok := schedulablePlatforms[platform]; ok && !service.IsMultiProtocolAPIKeyProvider(platform) {
@@ -1475,6 +1477,9 @@ func writeOpenAIModelsList(c *gin.Context, modelIDs []string) {
// 与平台默认列表(fallbackModels)。账号映射为空时回落默认列表;Anthropic
// 平台两者取并集,其余平台以账号映射键为准。
func modelListingSource(platform string, availableModels, fallbackModels []string) []string {
+ if platform == service.PlatformOpenAI && availableModels != nil {
+ return availableModels
+ }
if len(availableModels) == 0 {
return fallbackModels
}
diff --git a/backend/internal/handler/gateway_models_test.go b/backend/internal/handler/gateway_models_test.go
index 6d975e000..83c0998c1 100644
--- a/backend/internal/handler/gateway_models_test.go
+++ b/backend/internal/handler/gateway_models_test.go
@@ -324,6 +324,12 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T
Credentials: map[string]any{"model_mapping": map[string]any{alias: "gpt-5.6-sol"}},
},
}
+ subscriptionDefaults := make([]string, 0)
+ for _, model := range openai.DefaultModelIDs() {
+ if model != "gpt-5.5" {
+ subscriptionDefaults = append(subscriptionDefaults, model)
+ }
+ }
tests := []struct {
name string
accounts []service.Account
@@ -333,7 +339,7 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T
{
name: "unmapped parent and Spark shadow retain defaults and aliases",
accounts: accounts,
- want: append(openai.DefaultModelIDs(), alias),
+ want: append(append([]string{}, subscriptionDefaults...), alias),
},
{
name: "unmapped API key account also contributes defaults",
@@ -343,7 +349,7 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T
{
name: "unmapped accounts alone retain default response shape",
accounts: accounts[:1],
- want: openai.DefaultModelIDs(),
+ want: subscriptionDefaults,
},
{
name: "custom list can select defaults and aliases",
@@ -372,7 +378,7 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T
Credentials: map[string]any{"model_mapping": map[string]any{"stale-model": "stale-model"}},
Extra: map[string]any{"openai_passthrough": true},
}}, accounts[1:]...),
- want: append(openai.DefaultModelIDs(), alias),
+ want: append(append([]string{}, subscriptionDefaults...), alias),
},
{
name: "unmapped accounts from another platform do not add defaults",
@@ -1408,6 +1414,60 @@ func modelIDsForTest(models []gatewayModelItemForTest) []string {
return ids
}
+func TestGatewayModels_AntigravityExplicitMappingAppearsInBothCatalogs(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ const groupID int64 = 93
+ mapping := map[string]any{
+ "gemini-3.8-flash": "gemini-3.8-flash-high",
+ "gemini-3.8-flash-high": "gemini-3.8-flash-high",
+ "claude-opus-4-6-thinking": "claude-opus-4-6-thinking",
+ "gemini-pro-agent": "gemini-pro-agent",
+ }
+ for _, platform := range []string{service.PlatformAntigravity, service.PlatformComposite, service.PlatformGemini} {
+ t.Run(platform, func(t *testing.T) {
+ h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{
+ byGroup: map[int64][]service.Account{groupID: {{
+ ID: 25, Platform: service.PlatformAntigravity,
+ Extra: map[string]any{"mixed_scheduling": true},
+ Credentials: map[string]any{"model_mapping": mapping},
+ }}},
+ })
+ want := []string{"gemini-3.8-flash", "gemini-3.8-flash-high", "gemini-pro-agent", "claude-opus-4-6-thinking"}
+ if platform == service.PlatformGemini {
+ want = want[:3]
+ }
+ for _, codex := range []bool{false, true} {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
+ c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
+ Group: &service.Group{ID: groupID, Platform: platform},
+ })
+ var ids []string
+ if codex {
+ h.CodexModels(c)
+ var got codexModelsResponseForTest
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
+ for _, model := range got.Models {
+ ids = append(ids, model.Slug)
+ }
+ } else {
+ h.Models(c)
+ var got gatewayModelsResponseForTest
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
+ ids = modelIDsForTest(got.Data)
+ }
+ require.Equal(t, http.StatusOK, rec.Code)
+ // 显式条目必须同时出现在两种目录;默认透传补齐的条目不锁定。
+ require.Subset(t, ids, want, "codex=%t", codex)
+ if platform == service.PlatformGemini {
+ require.NotContains(t, ids, "claude-opus-4-6-thinking", "codex=%t", codex)
+ }
+ }
+ })
+ }
+}
+
// gemini 分组混合调度:组内 antigravity 账号的 gemini-* 映射也应出现在 /v1/models,
// 与路由层(listSchedulableAccountsOnce 的 useMixedScheduling)同源;claude-* 不带入,
// 非混合调度的异平台账号(anthropic)仍被过滤。
diff --git a/backend/internal/handler/gemini_cached_contents_billing_test.go b/backend/internal/handler/gemini_cached_contents_billing_test.go
new file mode 100644
index 000000000..8f430809f
--- /dev/null
+++ b/backend/internal/handler/gemini_cached_contents_billing_test.go
@@ -0,0 +1,955 @@
+//go:build unit
+
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/pkg/ctxkey"
+ middleware "github.com/MACOS-DO/sub4api/internal/server/middleware"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ cachedBillingInputPrice = 0.00000125
+ cachedBillingStoragePrice = 0.0000045
+ cachedBillingAliasStoragePrice = 0.000009
+ cachedBillingTokens = 1_000_000
+)
+
+type cachedBillingRepo struct {
+ mu sync.Mutex
+ records map[string]*service.GeminiCachedContent
+ // mutations 按记录 id 保存修改意图。
+ mutations map[int64]cachedBillingMutation
+ failCommit bool
+ nextID int64
+ deleted []int64
+}
+
+type cachedBillingMutation struct {
+ token string
+ leaseUntil time.Time
+}
+
+func (r *cachedBillingRepo) Create(_ context.Context, record *service.GeminiCachedContent) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.nextID++
+ record.ID = r.nextID
+ cp := *record
+ r.records[record.PublicID] = &cp
+ return nil
+}
+
+func (r *cachedBillingRepo) GetForOwner(_ context.Context, apiKeyID int64, publicID string) (*service.GeminiCachedContent, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ record, ok := r.records[publicID]
+ if !ok || record.APIKeyID != apiKeyID || r.liveLocked(record.ID) == nil {
+ return nil, service.ErrGeminiCachedContentNotFound
+ }
+ cp := *record
+ return &cp, nil
+}
+
+func (r *cachedBillingRepo) ListForOwner(context.Context, int64, int64, time.Time, int64, int) ([]*service.GeminiCachedContent, error) {
+ return nil, nil
+}
+
+// liveLocked 返回未删除的记录;调用方须持有 mu。
+func (r *cachedBillingRepo) liveLocked(id int64) *service.GeminiCachedContent {
+ for _, deleted := range r.deleted {
+ if deleted == id {
+ return nil
+ }
+ }
+ for _, record := range r.records {
+ if record.ID == id {
+ return record
+ }
+ }
+ return nil
+}
+
+func (r *cachedBillingRepo) BeginMutation(_ context.Context, id int64, baseline time.Time, token string, lease time.Duration) (bool, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ record := r.liveLocked(id)
+ if record == nil {
+ return false, service.ErrGeminiCachedContentNotFound
+ }
+ if _, pending := r.mutations[id]; pending || !record.ExpireTime.Equal(baseline) {
+ return false, nil
+ }
+ r.mutations[id] = cachedBillingMutation{token: token, leaseUntil: time.Now().Add(lease)}
+ return true, nil
+}
+
+func (r *cachedBillingRepo) TakeOverStaleMutation(_ context.Context, id int64, token string, lease time.Duration) (*service.GeminiCachedContent, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ record := r.liveLocked(id)
+ mutation, pending := r.mutations[id]
+ if record == nil || !pending || mutation.leaseUntil.After(time.Now()) {
+ return nil, nil
+ }
+ r.mutations[id] = cachedBillingMutation{token: token, leaseUntil: time.Now().Add(lease)}
+ cp := *record
+ return &cp, nil
+}
+
+func (r *cachedBillingRepo) CommitMutation(_ context.Context, id int64, token string, expireTime time.Time) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.failCommit {
+ return errors.New("db unavailable")
+ }
+ record := r.liveLocked(id)
+ mutation, pending := r.mutations[id]
+ if record == nil || !pending || mutation.token != token {
+ return service.ErrGeminiCachedContentMutationConflict
+ }
+ record.ExpireTime = expireTime
+ delete(r.mutations, id)
+ return nil
+}
+
+func (r *cachedBillingRepo) ReleaseMutation(_ context.Context, id int64, token string) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if mutation, pending := r.mutations[id]; pending && mutation.token == token {
+ delete(r.mutations, id)
+ }
+ return nil
+}
+
+func (r *cachedBillingRepo) ListStaleMutations(_ context.Context, limit int) ([]int64, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ var ids []int64
+ for id, mutation := range r.mutations {
+ if len(ids) < limit && mutation.leaseUntil.Before(time.Now()) && r.liveLocked(id) != nil {
+ ids = append(ids, id)
+ }
+ }
+ return ids, nil
+}
+
+func (r *cachedBillingRepo) SoftDelete(_ context.Context, id int64) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.deleted = append(r.deleted, id)
+ return nil
+}
+
+// pendingMutation 返回记录是否有未清除的修改意图。
+func (r *cachedBillingRepo) pendingMutation(id int64) bool {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ _, pending := r.mutations[id]
+ return pending
+}
+
+// expireLease 让记录上的修改意图租约立即过期。
+func (r *cachedBillingRepo) expireLease(id int64) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ mutation := r.mutations[id]
+ mutation.leaseUntil = time.Now().Add(-time.Second)
+ r.mutations[id] = mutation
+}
+
+type cachedBillingAccountRepo struct {
+ service.AccountRepository
+ accounts map[int64]*service.Account
+}
+
+func (r *cachedBillingAccountRepo) GetByID(_ context.Context, id int64) (*service.Account, error) {
+ account, ok := r.accounts[id]
+ if !ok {
+ return nil, service.ErrAccountNotFound
+ }
+ cp := *account
+ return &cp, nil
+}
+
+type cachedBillingUpstream struct {
+ service.HTTPUpstream
+ mu sync.Mutex
+ createBody string
+ calls []string
+ // patchTTLs 按顺序记录 PATCH 请求体中的 ttl。
+ patchTTLs []string
+ beforePost func(n int)
+ // failures 按请求方法返回上游错误响应;transportErrors 按请求方法返回传输层错误(上游结果未知)。
+ failures map[string]cachedBillingUpstreamFailure
+ transportErrors map[string]error
+}
+
+type cachedBillingUpstreamFailure struct {
+ status int
+ body string
+}
+
+func (u *cachedBillingUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
+ var patch struct {
+ TTL string `json:"ttl"`
+ }
+ if req.Method == http.MethodPatch {
+ _ = json.NewDecoder(req.Body).Decode(&patch)
+ }
+ u.mu.Lock()
+ u.calls = append(u.calls, req.Method+" "+req.URL.Path)
+ n := len(u.calls)
+ if req.Method == http.MethodPatch {
+ u.patchTTLs = append(u.patchTTLs, patch.TTL)
+ }
+ failure, failed := u.failures[req.Method]
+ transportErr := u.transportErrors[req.Method]
+ u.mu.Unlock()
+ if transportErr != nil {
+ return nil, transportErr
+ }
+ if failed {
+ return &http.Response{StatusCode: failure.status, Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(failure.body))}, nil
+ }
+ body := "{}"
+ switch req.Method {
+ case http.MethodPost:
+ body = u.createBody
+ case http.MethodPatch:
+ if u.beforePost != nil {
+ u.beforePost(n)
+ }
+ seconds, _ := strconv.ParseInt(strings.TrimSuffix(patch.TTL, "s"), 10, 64)
+ body = fmt.Sprintf(`{"name":"cachedContents/up1","expireTime":%q}`, time.Now().Add(time.Duration(seconds)*time.Second).UTC().Format(time.RFC3339Nano))
+ }
+ return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(body))}, nil
+}
+
+func (u *cachedBillingUpstream) methodCalls(method string) int {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ n := 0
+ for _, call := range u.calls {
+ if strings.HasPrefix(call, method+" ") {
+ n++
+ }
+ }
+ return n
+}
+
+type cachedBillingUserRepo struct {
+ service.UserRepository
+ balance float64
+}
+
+func (r *cachedBillingUserRepo) GetByID(_ context.Context, id int64) (*service.User, error) {
+ return &service.User{ID: id, Balance: r.balance}, nil
+}
+
+func (r *cachedBillingUserRepo) DeductBalance(context.Context, int64, float64) error { return nil }
+
+type cachedBillingUsageRepo struct {
+ service.UsageLogRepository
+ mu sync.Mutex
+ logs []*service.UsageLog
+}
+
+func (r *cachedBillingUsageRepo) Create(_ context.Context, log *service.UsageLog) (bool, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.logs = append(r.logs, log)
+ return true, nil
+}
+
+func (r *cachedBillingUsageRepo) first() *service.UsageLog {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.logs[0]
+}
+
+func (r *cachedBillingUsageRepo) totals() []float64 {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ out := make([]float64, 0, len(r.logs))
+ for _, log := range r.logs {
+ out = append(out, log.TotalCost)
+ }
+ return out
+}
+
+type cachedBillingEnv struct {
+ h *GatewayHandler
+ repo *cachedBillingRepo
+ upstream *cachedBillingUpstream
+ usage *cachedBillingUsageRepo
+ apiKey *service.APIKey
+ group *service.Group
+ // accounts 是调度快照桩直接返回的账号对象,测试可改其凭据。
+ accounts map[int64]*service.Account
+}
+
+func newCachedBillingEnv(t *testing.T, balance float64, accountIDs ...int64) *cachedBillingEnv {
+ t.Helper()
+ dir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(dir, "model_pricing.json"), []byte(fmt.Sprintf(`{"gemini-2.5-pro":{
+ "litellm_provider":"gemini","mode":"chat","input_cost_per_token":%g,"output_cost_per_token":0.00001,
+ "cache_storage_cost_per_token_per_hour":%g},"gemini-alias":{
+ "litellm_provider":"gemini","mode":"chat","input_cost_per_token":%g,"output_cost_per_token":0.00001,
+ "cache_storage_cost_per_token_per_hour":%g}}`,
+ cachedBillingInputPrice, cachedBillingStoragePrice, cachedBillingInputPrice, cachedBillingAliasStoragePrice)), 0o644))
+ cfg := &config.Config{}
+ cfg.Pricing.DataDir = dir
+ cfg.Pricing.UpdateIntervalHours = 100000
+ cfg.Default.RateMultiplier = 1
+ pricing := service.NewPricingService(cfg, nil)
+ require.NoError(t, pricing.Initialize())
+ billing := service.NewBillingService(cfg, pricing)
+
+ groupID := int64(42)
+ group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformGemini, Status: service.StatusActive, RateMultiplier: 1}
+ accounts := map[int64]*service.Account{}
+ var scheduled []*service.Account
+ for _, id := range accountIDs {
+ account := &service.Account{ID: id, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey,
+ Credentials: map[string]any{"api_key": "k"}, Status: service.StatusActive, Schedulable: true,
+ Concurrency: 5, Priority: 1, AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}}
+ accounts[id] = account
+ scheduled = append(scheduled, account)
+ }
+ userRepo := &cachedBillingUserRepo{balance: balance}
+ usage := &cachedBillingUsageRepo{}
+ bcs := service.NewBillingCacheService(nil, userRepo, nil, nil, nil, nil, cfg, nil)
+ t.Cleanup(bcs.Stop)
+ snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: scheduled}, nil, nil, nil, nil)
+ gw := service.NewGatewayService(nil, &fakeGroupRepo{group: group}, usage, nil, userRepo, nil, nil, nil, cfg, snapshot, nil,
+ billing, nil, &service.BillingCacheService{}, nil, nil, &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ upstream := &cachedBillingUpstream{}
+ compat := service.NewGeminiMessagesCompatService(&cachedBillingAccountRepo{accounts: accounts}, nil, nil, nil, nil, nil, upstream, nil, cfg)
+ repo := &cachedBillingRepo{records: map[string]*service.GeminiCachedContent{}, mutations: map[int64]cachedBillingMutation{}}
+ h := &GatewayHandler{
+ gatewayService: gw,
+ billingCacheService: bcs,
+ concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatNone, 0),
+ geminiCachedContentService: service.NewGeminiCachedContentService(repo, compat, cfg),
+ }
+ apiKey := &service.APIKey{ID: 7, UserID: 3, GroupID: &groupID, Group: group, Status: service.StatusActive,
+ User: &service.User{ID: 3, Concurrency: 10, Balance: balance}}
+ return &cachedBillingEnv{h: h, repo: repo, upstream: upstream, usage: usage, apiKey: apiKey, group: group, accounts: accounts}
+}
+
+// TestGeminiExplicitCacheExclusions_FiltersUnsupportedAccountsFromSnapshot 候选过滤直接按快照里的凭据判定:
+// 第三方地址且未声明上游显式缓存的 Key 账号在选号前就被排除,官方地址与声明了上游显式缓存的账号保留。
+func TestGeminiExplicitCacheExclusions_FiltersUnsupportedAccountsFromSnapshot(t *testing.T) {
+ env := newCachedBillingEnv(t, 500, 900, 901, 902)
+ env.accounts[901].Credentials["base_url"] = "https://third.example.com"
+ env.accounts[902].Credentials["base_url"] = "https://gw.example.com"
+ env.accounts[902].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = true
+
+ groupID := env.group.ID
+ excluded, err := env.h.gatewayService.GeminiExplicitCacheExclusions(context.Background(), &groupID, 0)
+ require.NoError(t, err)
+ require.Equal(t, map[int64]struct{}{901: {}}, excluded)
+
+ excluded, err = env.h.gatewayService.GeminiExplicitCacheExclusions(context.Background(), &groupID, 902)
+ require.NoError(t, err)
+ require.Equal(t, map[int64]struct{}{900: {}, 901: {}}, excluded, "绑定缓存的请求只保留持有账号")
+}
+
+func (e *cachedBillingEnv) serve(method, target, body string, params gin.Params, call func(*gin.Context)) *httptest.ResponseRecorder {
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ req := httptest.NewRequest(method, target, strings.NewReader(body))
+ c.Request = req.WithContext(context.WithValue(req.Context(), ctxkey.Group, e.group))
+ c.Params = params
+ c.Set(string(middleware.ContextKeyAPIKey), e.apiKey)
+ c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: e.apiKey.UserID, Concurrency: 10})
+ call(c)
+ return rec
+}
+
+// waitForUsage 等待异步计费任务落库(无 worker 池时同步执行,直接返回)。
+func (e *cachedBillingEnv) waitForUsage(t *testing.T, n int) []float64 {
+ t.Helper()
+ require.Eventually(t, func() bool { return len(e.usage.totals()) >= n }, time.Second, 10*time.Millisecond)
+ return e.usage.totals()
+}
+
+func (e *cachedBillingEnv) create() *httptest.ResponseRecorder {
+ return e.serve(http.MethodPost, "/v1beta/cachedContents",
+ `{"model":"models/gemini-2.5-pro","ttl":"86400s","contents":[{"role":"user","parts":[{"text":"doc"}]}]}`,
+ nil, e.h.GeminiCachedContentsCreate)
+}
+
+func (e *cachedBillingEnv) seed(expire time.Time) {
+ e.repo.records["abc"] = &service.GeminiCachedContent{
+ ID: 100, PublicID: "abc", UserID: 3, APIKeyID: 7, GroupID: 42, AccountID: 900,
+ UpstreamName: "cachedContents/up1", Model: "gemini-2.5-pro", UpstreamModel: "models/gemini-2.5-pro",
+ TotalTokenCount: cachedBillingTokens, ExpireTime: expire,
+ }
+}
+
+func (e *cachedBillingEnv) patch() *httptest.ResponseRecorder {
+ return e.serve(http.MethodPatch, "/v1beta/cachedContents/abc?updateMask=ttl", `{"ttl":"86400s"}`,
+ gin.Params{{Key: "cacheID", Value: "abc"}}, e.h.GeminiCachedContentsPatch)
+}
+
+// TestGeminiCachedContentsPatch_UsesChannelUsageRecordedAtCreate 延长有效期沿用创建时的渠道计费口径:
+// 计费模型来源为请求模型时按别名定价,用量记录带渠道 ID。
+func TestGeminiCachedContentsPatch_UsesChannelUsageRecordedAtCreate(t *testing.T) {
+ env := newCachedBillingEnv(t, 500, 900)
+ env.seed(time.Now().Add(time.Hour))
+ env.repo.records["abc"].ChannelUsage = service.ChannelUsageFields{
+ ChannelID: 5, OriginalModel: "gemini-alias", ChannelMappedModel: "gemini-2.5-pro",
+ BillingModelSource: service.BillingModelSourceRequested,
+ }
+
+ rec := env.patch()
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ totals := env.waitForUsage(t, 1)
+ require.Len(t, totals, 1)
+ require.InDelta(t, cachedBillingTokens*cachedBillingAliasStoragePrice*23, totals[0], 0.01, "按创建时的计费模型(请求模型别名)计存储费")
+ usageLog := env.usage.first()
+ require.NotNil(t, usageLog.ChannelID)
+ require.Equal(t, int64(5), *usageLog.ChannelID)
+ require.True(t, strings.HasPrefix(usageLog.RequestID, "gcache:patch:abc:"), usageLog.RequestID)
+}
+
+func cachedBillingCreateBody(expire time.Time) string {
+ return fmt.Sprintf(`{"name":"cachedContents/up1","usageMetadata":{"totalTokenCount":%d},"expireTime":%q}`,
+ cachedBillingTokens, expire.UTC().Format(time.RFC3339Nano))
+}
+
+func TestGeminiCachedContentsCreate_ChargesInputAndStorage(t *testing.T) {
+ env := newCachedBillingEnv(t, 500, 900)
+ env.upstream.createBody = cachedBillingCreateBody(time.Now().Add(100 * time.Hour))
+
+ rec := env.create()
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ totals := env.waitForUsage(t, 1)
+ require.Len(t, totals, 1)
+ require.InDelta(t, cachedBillingTokens*cachedBillingInputPrice+cachedBillingTokens*cachedBillingStoragePrice*24, totals[0], 1e-9)
+ require.Len(t, env.repo.records, 1)
+ for _, record := range env.repo.records {
+ require.False(t, record.ExpireTime.After(time.Now().Add(24*time.Hour)), "本地到期时间不超过请求的有效期")
+ require.Equal(t, "gcache:create:"+record.PublicID, env.usage.first().RequestID, "费用行按缓存 ID 可检索")
+ }
+}
+
+func TestGeminiCachedContentsCreate_UnaffordableStorageDeletesUpstreamAndBillsInputOnly(t *testing.T) {
+ env := newCachedBillingEnv(t, 1, 900)
+ env.upstream.createBody = cachedBillingCreateBody(time.Now().Add(24 * time.Hour))
+
+ rec := env.create()
+ require.NotEqual(t, http.StatusOK, rec.Code)
+ require.Contains(t, rec.Body.String(), "error")
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodDelete), "删除已创建的上游缓存,避免产生存储费")
+ require.Empty(t, env.repo.records, "不登记缓存")
+ totals := env.waitForUsage(t, 1)
+ require.Len(t, totals, 1)
+ require.InDelta(t, cachedBillingTokens*cachedBillingInputPrice, totals[0], 1e-9, "只收已发生的缓存 token 输入费")
+}
+
+func TestGeminiCachedContentsCreate_UnusableUpstreamResponseCleansUpWithoutRetry(t *testing.T) {
+ env := newCachedBillingEnv(t, 500, 900, 901)
+ env.upstream.createBody = `{"name":"cachedContents/up1","expireTime":"2099-01-01T00:00:00Z"}`
+
+ rec := env.create()
+ require.Equal(t, http.StatusBadGateway, rec.Code)
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodPost), "不换号重建")
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodDelete), "删除已创建的上游缓存")
+ require.Empty(t, env.repo.records)
+ require.Empty(t, env.usage.totals())
+}
+
+func (e *cachedBillingEnv) patchTTL(id, ttl string) *httptest.ResponseRecorder {
+ return e.serve(http.MethodPatch, "/v1beta/cachedContents/"+id+"?updateMask=ttl", fmt.Sprintf(`{"ttl":%q}`, ttl),
+ gin.Params{{Key: "cacheID", Value: id}}, e.h.GeminiCachedContentsPatch)
+}
+
+// requireTTLNear 断言发往上游的 ttl("Ns")与 want 相差不超过 5 秒。
+func requireTTLNear(t *testing.T, ttl string, want time.Duration) {
+ t.Helper()
+ seconds, err := strconv.ParseInt(strings.TrimSuffix(ttl, "s"), 10, 64)
+ require.NoError(t, err, ttl)
+ require.InDelta(t, want.Seconds(), float64(seconds), 5, ttl)
+}
+
+// 同一缓存的修改串行执行:第一个 PATCH 的上游调用返回前,第二个 PATCH 直接得到 409 且不调用上游,
+// 本地到期时间与上游最后生效的修改一致,只按第一个 PATCH 实际推进的时长收费。
+func TestGeminiCachedContentsPatch_ConcurrentUpdateConflictsAndKeepsUpstreamInSync(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.seed(time.Now().Add(time.Hour))
+ env.upstream.beforePost = func(n int) {
+ if n == 1 {
+ rec := env.patchTTL("abc", "86400s")
+ require.Equal(t, http.StatusConflict, rec.Code, rec.Body.String())
+ require.Contains(t, rec.Body.String(), `"ABORTED"`)
+ }
+ }
+
+ rec := env.patchTTL("abc", "7200s")
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch), "冲突的修改不调用上游")
+ require.WithinDuration(t, time.Now().Add(2*time.Hour), env.repo.records["abc"].ExpireTime, 5*time.Second, "本地到期时间与上游一致")
+ require.False(t, env.repo.pendingMutation(100))
+ totals := env.waitForUsage(t, 1)
+ require.Len(t, totals, 1)
+ require.InDelta(t, cachedBillingTokens*cachedBillingStoragePrice, totals[0], cachedBillingTokens*cachedBillingStoragePrice*time.Minute.Hours(), "只收推进的 1 小时")
+}
+
+// 上游已修改但本地写回失败:不计费并保留修改意图;租约内的修改返回 409,
+// 租约过期后后台恢复把上游有效期回滚到修改前的到期时间并清除意图。
+func TestGeminiCachedContentsPatch_CommitFailureRollsBackUpstreamWithoutCharge(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ baseline := time.Now().Add(time.Hour)
+ env.seed(baseline)
+ env.repo.failCommit = true
+
+ require.Equal(t, http.StatusInternalServerError, env.patch().Code)
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch))
+ require.True(t, env.repo.pendingMutation(100), "上游可能已修改:保留修改意图")
+ require.Empty(t, env.usage.totals(), "未提交的修改不收费")
+
+ env.repo.failCommit = false
+ require.Equal(t, http.StatusConflict, env.patch().Code, "租约内的修改被拒绝")
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch))
+
+ env.repo.expireLease(100)
+ recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, 1, recovered)
+ require.Equal(t, 2, env.upstream.methodCalls(http.MethodPatch))
+ requireTTLNear(t, env.upstream.patchTTLs[1], time.Until(baseline))
+ require.False(t, env.repo.pendingMutation(100))
+ require.True(t, env.repo.records["abc"].ExpireTime.Equal(baseline), "本地到期时间保持修改前的值")
+ require.Empty(t, env.usage.totals())
+}
+
+// 租约过期的遗留修改意图在下一次修改前先回滚,随后的修改按修改前的到期时间计费。
+func TestGeminiCachedContentsPatch_StaleMutationRolledBackBeforeNextUpdate(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ baseline := time.Now().Add(time.Hour)
+ env.seed(baseline)
+ env.repo.failCommit = true
+ require.Equal(t, http.StatusInternalServerError, env.patch().Code)
+ env.repo.failCommit = false
+ env.repo.expireLease(100)
+
+ rec := env.patch()
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ require.Equal(t, 3, env.upstream.methodCalls(http.MethodPatch), "失败的修改、回滚、本次修改")
+ requireTTLNear(t, env.upstream.patchTTLs[1], time.Until(baseline))
+ require.Equal(t, "86400s", env.upstream.patchTTLs[2])
+ totals := env.waitForUsage(t, 1)
+ require.Len(t, totals, 1)
+ require.InDelta(t, cachedBillingTokens*cachedBillingStoragePrice*23, totals[0], 0.01)
+}
+
+// 上游结果未知(传输层错误)时保留修改意图等待回滚;上游明确拒绝时清除修改意图。两种情况都不收费。
+func TestGeminiCachedContentsPatch_MutationKeptOnlyWhenUpstreamOutcomeUnknown(t *testing.T) {
+ t.Run("transport error", func(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.seed(time.Now().Add(time.Hour))
+ env.upstream.transportErrors = map[string]error{http.MethodPatch: errors.New("connection reset")}
+
+ require.Equal(t, http.StatusBadGateway, env.patch().Code)
+ require.True(t, env.repo.pendingMutation(100))
+ require.Empty(t, env.usage.totals())
+ })
+ t.Run("upstream rejected", func(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.seed(time.Now().Add(time.Hour))
+ env.upstream.failures = map[string]cachedBillingUpstreamFailure{http.MethodPatch: {status: http.StatusBadRequest,
+ body: `{"error":{"code":400,"message":"invalid ttl","status":"INVALID_ARGUMENT"}}`}}
+
+ require.Equal(t, http.StatusBadRequest, env.patch().Code)
+ require.False(t, env.repo.pendingMutation(100))
+ require.Empty(t, env.usage.totals())
+ })
+}
+
+// 修改前的到期时间已过:恢复时删除上游缓存与本地记录。
+func TestGeminiCachedContentMutationRecovery_DeletesUpstreamWhenBaselineExpired(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.seed(time.Now().Add(-time.Minute))
+ env.repo.mutations[100] = cachedBillingMutation{token: "stale", leaseUntil: time.Now().Add(-time.Second)}
+
+ recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, 1, recovered)
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodDelete))
+ require.Zero(t, env.upstream.methodCalls(http.MethodPatch))
+ require.Equal(t, []int64{100}, env.repo.deleted)
+}
+
+// cachedBillingReservationCache 是启用在途预留时的计费缓存桩:余额与订阅用量取固定值,各维度预留按 key 记账。
+type cachedBillingReservationCache struct {
+ service.BillingCache
+ mu sync.Mutex
+ balance float64
+ sub *service.SubscriptionCacheData
+ reserved map[string]map[string]float64
+}
+
+func (c *cachedBillingReservationCache) GetUserBalance(context.Context, int64) (float64, error) {
+ return c.balance, nil
+}
+
+func (c *cachedBillingReservationCache) GetSubscriptionCache(context.Context, int64, int64) (*service.SubscriptionCacheData, error) {
+ return c.sub, nil
+}
+
+func (c *cachedBillingReservationCache) reserveLocked(key, requestID string, amount float64) float64 {
+ if c.reserved == nil {
+ c.reserved = map[string]map[string]float64{}
+ }
+ if c.reserved[key] == nil {
+ c.reserved[key] = map[string]float64{}
+ }
+ others := 0.0
+ for _, v := range c.reserved[key] {
+ others += v
+ }
+ c.reserved[key][requestID] = amount
+ return others
+}
+
+func (c *cachedBillingReservationCache) ReserveInflightBalance(_ context.Context, userID int64, requestID string, amount, balance float64, _ time.Duration) (bool, float64, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ key := fmt.Sprintf("user:%d", userID)
+ others := c.reserveLocked(key, requestID, amount)
+ if len(c.reserved[key]) > 1 && balance-others < amount {
+ delete(c.reserved[key], requestID)
+ return false, others, nil
+ }
+ return true, others, nil
+}
+
+func (c *cachedBillingReservationCache) ReleaseInflightBalance(_ context.Context, userID int64, requestID string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ delete(c.reserved[fmt.Sprintf("user:%d", userID)], requestID)
+ return nil
+}
+
+func (c *cachedBillingReservationCache) ReserveInflightScope(_ context.Context, scope, requestID string, amount float64, _ time.Duration) (float64, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.reserveLocked(scope, requestID, amount), nil
+}
+
+func (c *cachedBillingReservationCache) ReleaseInflightScope(_ context.Context, scope, requestID string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ delete(c.reserved[scope], requestID)
+ return nil
+}
+
+func enableCachedBillingReservations(t *testing.T, env *cachedBillingEnv, cache *cachedBillingReservationCache) {
+ t.Helper()
+ cfg := &config.Config{}
+ cfg.Billing.InflightReservation.Enabled = true
+ bcs := service.NewBillingCacheService(cache, nil, nil, nil, nil, nil, cfg, nil)
+ t.Cleanup(bcs.Stop)
+ env.h.billingCacheService = bcs
+}
+
+// 确定金额的续期费按 API Key 与余额维度预留:第一笔续期(约 $103.5)尚未入账时,
+// 第二个缓存的续期超出 Key 剩余额度或余额,在调用上游前被拒绝。
+func TestGeminiCachedContentsPatch_UnsettledChargeHoldsKeyQuotaAndBalance(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ balance, quota float64
+ }{
+ {name: "api key quota", balance: 1000, quota: 110},
+ {name: "balance", balance: 110},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ env := newCachedBillingEnv(t, tc.balance, 900)
+ env.seed(time.Now().Add(time.Hour))
+ second := *env.repo.records["abc"]
+ second.ID, second.PublicID, second.UpstreamName = 101, "def", "cachedContents/up2"
+ env.repo.records["def"] = &second
+ env.apiKey.Quota = tc.quota
+ enableCachedBillingReservations(t, env, &cachedBillingReservationCache{balance: tc.balance})
+ env.upstream.beforePost = func(n int) {
+ if n == 1 {
+ rec := env.patchTTL("def", "86400s")
+ require.NotEqual(t, http.StatusOK, rec.Code, rec.Body.String())
+ }
+ }
+
+ require.Equal(t, http.StatusOK, env.patch().Code)
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch), "第二笔续期没有到达上游")
+ })
+ }
+}
+
+// 订阅模式的确定金额费用按订阅维度预留:第一笔未入账时第二笔超出日剩余额度被拒绝,释放后放行。
+func TestReserveGeminiCachedContentCharge_UnsettledChargeHoldsSubscriptionHeadroom(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ limit := 110.0
+ env.group.SubscriptionType = service.SubscriptionTypeSubscription
+ env.group.DailyLimitUSD = &limit
+ enableCachedBillingReservations(t, env, &cachedBillingReservationCache{balance: 1000,
+ sub: &service.SubscriptionCacheData{Status: service.SubscriptionStatusActive, ExpiresAt: time.Now().Add(time.Hour)}})
+ sub := &service.UserSubscription{ID: 1, UserID: env.apiKey.UserID, GroupID: env.group.ID, Status: service.SubscriptionStatusActive,
+ ExpiresAt: time.Now().Add(time.Hour)}
+ reserve := func() (func(), error) {
+ var done func()
+ var err error
+ env.serve(http.MethodPatch, "/", `{}`, nil, func(c *gin.Context) {
+ done, err = env.h.reserveGeminiCachedContentCharge(c, env.apiKey, sub, 103.5)
+ })
+ return done, err
+ }
+
+ firstDone, err := reserve()
+ require.NoError(t, err)
+ _, err = reserve()
+ require.ErrorIs(t, err, service.ErrDailyLimitExceeded)
+ firstDone()
+ secondDone, err := reserve()
+ require.NoError(t, err)
+ secondDone()
+}
+
+func TestGeminiCachedContentsPatch_UnaffordableExtensionRejectedBeforeUpstream(t *testing.T) {
+ env := newCachedBillingEnv(t, 1, 900)
+ env.seed(time.Now().Add(time.Hour))
+
+ rec := env.patch()
+ require.NotEqual(t, http.StatusOK, rec.Code)
+ require.Zero(t, env.upstream.methodCalls(http.MethodPatch), "余额不足以支付延长部分时不调用上游")
+ require.Empty(t, env.usage.totals())
+}
+
+// 上游对缓存不存在的响应:AI Studio 403;Vertex 缓存资源接口 404,文案含上游缓存数字 ID。
+var cachedBillingUpstreamNotFoundCases = []struct {
+ name string
+ failure cachedBillingUpstreamFailure
+}{
+ {name: "ai studio 403", failure: cachedBillingUpstreamFailure{status: http.StatusForbidden,
+ body: `{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}`}},
+ {name: "vertex 404", failure: cachedBillingUpstreamFailure{status: http.StatusNotFound,
+ body: `{"error":{"code":404,"message":"Cached content 8079767076522164224 is not found.","status":"NOT_FOUND"}}`}},
+}
+
+func TestGeminiCachedContentsPatch_UpstreamNotFoundForgetsAndReturnsStandardForbidden(t *testing.T) {
+ for _, tc := range cachedBillingUpstreamNotFoundCases {
+ t.Run(tc.name, func(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.seed(time.Now().Add(time.Hour))
+ env.upstream.failures = map[string]cachedBillingUpstreamFailure{http.MethodPatch: tc.failure}
+
+ rec := env.patch()
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Equal(t, service.GeminiCachedContentNotFoundResponse, rec.Body.String())
+ require.NotContains(t, rec.Body.String(), "8079767076522164224", "不应暴露上游缓存 ID")
+ require.Equal(t, []int64{100}, env.repo.deleted, "上游已不存在的缓存应从本地移除")
+ require.Empty(t, env.usage.totals(), "上游未延长不收费")
+ })
+ }
+}
+
+func TestGeminiCachedContentsDelete_UpstreamNotFoundStillForgets(t *testing.T) {
+ for _, tc := range cachedBillingUpstreamNotFoundCases {
+ t.Run(tc.name, func(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.seed(time.Now().Add(time.Hour))
+ env.upstream.failures = map[string]cachedBillingUpstreamFailure{http.MethodDelete: tc.failure}
+
+ rec := env.serve(http.MethodDelete, "/v1beta/cachedContents/abc", "",
+ gin.Params{{Key: "cacheID", Value: "abc"}}, env.h.GeminiCachedContentsDelete)
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ require.JSONEq(t, `{}`, rec.Body.String())
+ require.Equal(t, []int64{100}, env.repo.deleted)
+ })
+ }
+}
+
+// 持有账号暂时不支持显式缓存(能力被关闭)时,恢复流程不能把修改意图当作已回滚而清除;
+// 能力恢复后再回滚上游并清除意图。
+func TestGeminiCachedContentMutationRecovery_KeepsIntentWhileAccountCannotCache(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.accounts[900].Credentials["base_url"] = "https://gw.example.com"
+ env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = true
+ baseline := time.Now().Add(time.Hour)
+ env.seed(baseline)
+ env.repo.failCommit = true
+ require.Equal(t, http.StatusInternalServerError, env.patch().Code)
+ require.True(t, env.repo.pendingMutation(100))
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch))
+ env.repo.failCommit = false
+ env.repo.expireLease(100)
+
+ env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = false
+ recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.Error(t, err, "账号暂不支持缓存时恢复失败")
+ require.Zero(t, recovered)
+ require.True(t, env.repo.pendingMutation(100), "未回滚上游前保留修改意图")
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch), "不改动上游")
+ require.Empty(t, env.repo.deleted)
+
+ env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = true
+ env.repo.expireLease(100)
+ recovered, err = env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, 1, recovered)
+ require.Equal(t, 2, env.upstream.methodCalls(http.MethodPatch))
+ requireTTLNear(t, env.upstream.patchTTLs[1], time.Until(baseline))
+ require.False(t, env.repo.pendingMutation(100))
+ require.True(t, env.repo.records["abc"].ExpireTime.Equal(baseline))
+ require.Empty(t, env.usage.totals())
+}
+
+// 持有账号长期不支持显式缓存,且修改前到期时间加上单次最长有效期都已过去:上游缓存必已自行过期,
+// 恢复流程不再保留意图,直接移除本地记录。
+func TestGeminiCachedContentMutationRecovery_AbandonsIntentOnceUpstreamMustHaveExpired(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.accounts[900].Credentials["base_url"] = "https://gw.example.com"
+ env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = true
+ env.seed(time.Now().Add(time.Hour))
+ env.repo.failCommit = true
+ require.Equal(t, http.StatusInternalServerError, env.patch().Code)
+ env.repo.failCommit = false
+ env.repo.expireLease(100)
+ env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = false
+
+ // 修改前到期时间 + 24h 上限 + 1h 容忍仍未过去:保留意图。
+ env.repo.records["abc"].ExpireTime = time.Now().Add(-20 * time.Hour)
+ recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.Error(t, err)
+ require.Zero(t, recovered)
+ require.True(t, env.repo.pendingMutation(100))
+ require.Empty(t, env.repo.deleted)
+
+ env.repo.expireLease(100)
+ env.repo.records["abc"].ExpireTime = time.Now().Add(-26 * time.Hour)
+ recovered, err = env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, 1, recovered)
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch), "不改动上游")
+ require.Zero(t, env.upstream.methodCalls(http.MethodDelete))
+ require.Equal(t, []int64{100}, env.repo.deleted)
+ require.Empty(t, env.usage.totals())
+
+ recovered, err = env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.NoError(t, err)
+ require.Zero(t, recovered, "作废的记录不再被选中")
+}
+
+// 作废判定的边界:默认上限 24h 加 1h 容忍;配置上限低于 24h 时仍按 24h 兜底。
+func TestGeminiCachedContentMutationRecovery_AbandonBoundary(t *testing.T) {
+ disableCache := func(env *cachedBillingEnv) {
+ env.accounts[900].Credentials["base_url"] = "https://gw.example.com"
+ env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = false
+ }
+ t.Run("within grace keeps intent", func(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.seed(time.Now().Add(-25*time.Hour + time.Minute))
+ env.repo.mutations[100] = cachedBillingMutation{token: "stale", leaseUntil: time.Now().Add(-time.Second)}
+ disableCache(env)
+
+ recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.Error(t, err)
+ require.Zero(t, recovered)
+ require.True(t, env.repo.pendingMutation(100))
+ require.Empty(t, env.repo.deleted)
+ })
+ t.Run("configured max ttl below default still waits a day", func(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.seed(time.Now().Add(-12 * time.Hour))
+ env.repo.mutations[100] = cachedBillingMutation{token: "stale", leaseUntil: time.Now().Add(-time.Second)}
+ disableCache(env)
+ cfg := &config.Config{}
+ cfg.Gateway.GeminiCachedContentMaxTTLSeconds = 3600
+ compat := service.NewGeminiMessagesCompatService(&cachedBillingAccountRepo{accounts: env.accounts}, nil, nil, nil, nil, nil, env.upstream, nil, cfg)
+ svc := service.NewGeminiCachedContentService(env.repo, compat, cfg)
+
+ recovered, err := svc.RecoverStaleMutations(context.Background())
+ require.Error(t, err)
+ require.Zero(t, recovered)
+ require.True(t, env.repo.pendingMutation(100))
+
+ env.repo.expireLease(100)
+ env.repo.records["abc"].ExpireTime = time.Now().Add(-26 * time.Hour)
+ recovered, err = svc.RecoverStaleMutations(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, 1, recovered)
+ require.Equal(t, []int64{100}, env.repo.deleted)
+ })
+}
+
+// 持有账号可用但上游回滚持续失败(如 Key 已失效):上游缓存必已自行过期后不再重试,移除本地记录。
+func TestGeminiCachedContentMutationRecovery_AbandonsIntentWhenRollbackKeepsFailing(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.seed(time.Now().Add(-time.Minute))
+ env.repo.mutations[100] = cachedBillingMutation{token: "stale", leaseUntil: time.Now().Add(-time.Second)}
+ env.upstream.failures = map[string]cachedBillingUpstreamFailure{http.MethodDelete: {status: http.StatusUnauthorized,
+ body: `{"error":{"code":401,"message":"API key not valid","status":"UNAUTHENTICATED"}}`}}
+
+ recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.Error(t, err, "上游缓存可能仍存活:保留意图等待重试")
+ require.Zero(t, recovered)
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodDelete))
+ require.True(t, env.repo.pendingMutation(100))
+ require.Empty(t, env.repo.deleted)
+
+ env.repo.expireLease(100)
+ env.repo.records["abc"].ExpireTime = time.Now().Add(-26 * time.Hour)
+ recovered, err = env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, 1, recovered)
+ require.Equal(t, 2, env.upstream.methodCalls(http.MethodDelete), "账号可用时仍先尝试回滚")
+ require.Equal(t, []int64{100}, env.repo.deleted)
+ require.Empty(t, env.usage.totals())
+}
+
+// 持有账号已删除时没有凭据可回滚上游:恢复流程移除本地记录并清除意图,不再重试。
+func TestGeminiCachedContentMutationRecovery_ForgetsRecordWhenAccountDeleted(t *testing.T) {
+ env := newCachedBillingEnv(t, 1000, 900)
+ env.seed(time.Now().Add(time.Hour))
+ env.repo.failCommit = true
+ require.Equal(t, http.StatusInternalServerError, env.patch().Code)
+ require.True(t, env.repo.pendingMutation(100))
+ env.repo.failCommit = false
+ env.repo.expireLease(100)
+
+ delete(env.accounts, 900)
+ recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, 1, recovered)
+ require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch), "无凭据,不改动上游")
+ require.Zero(t, env.upstream.methodCalls(http.MethodDelete))
+ require.Equal(t, []int64{100}, env.repo.deleted, "本地记录作废")
+ require.Empty(t, env.usage.totals())
+ require.Equal(t, http.StatusForbidden, env.serve(http.MethodGet, "/v1beta/cachedContents/abc", "", gin.Params{{Key: "cacheID", Value: "abc"}}, env.h.GeminiCachedContentsGet).Code, "作废的记录对客户端不可见")
+
+ recovered, err = env.h.geminiCachedContentService.RecoverStaleMutations(context.Background())
+ require.NoError(t, err)
+ require.Zero(t, recovered, "不再重复处理")
+}
diff --git a/backend/internal/handler/gemini_cached_contents_handler.go b/backend/internal/handler/gemini_cached_contents_handler.go
new file mode 100644
index 000000000..bd5136481
--- /dev/null
+++ b/backend/internal/handler/gemini_cached_contents_handler.go
@@ -0,0 +1,848 @@
+package handler
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ pkghttputil "github.com/MACOS-DO/sub4api/internal/pkg/httputil"
+ "github.com/MACOS-DO/sub4api/internal/pkg/ip"
+ "github.com/MACOS-DO/sub4api/internal/pkg/logger"
+ "github.com/MACOS-DO/sub4api/internal/server/middleware"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/gin-gonic/gin"
+ "go.uber.org/zap"
+)
+
+// geminiCachedContentCreateMaxAttempts 限制创建缓存时实际发往上游的账号数。
+const geminiCachedContentCreateMaxAttempts = 3
+
+// geminiCachedContentPersistTimeout 是上游操作完成后落库的超时;落库与客户端连接脱钩。
+const geminiCachedContentPersistTimeout = 15 * time.Second
+
+const geminiCachedContentUnavailableMessage = "The account holding this cached content is temporarily unavailable"
+
+// geminiCachedContentsPreamble 校验显式缓存管理接口的公共前置条件:gemini 分组、非 composite 分组、功能已装配。
+func (h *GatewayHandler) geminiCachedContentsPreamble(c *gin.Context, component string) (*service.APIKey, middleware.AuthSubject, *zap.Logger, bool) {
+ apiKey, ok := middleware.GetAPIKeyFromContext(c)
+ if !ok || apiKey == nil {
+ googleError(c, http.StatusUnauthorized, "Invalid API key")
+ return nil, middleware.AuthSubject{}, nil, false
+ }
+ authSubject, ok := middleware.GetAuthSubjectFromContext(c)
+ if !ok {
+ googleError(c, http.StatusInternalServerError, "User context not found")
+ return nil, middleware.AuthSubject{}, nil, false
+ }
+ if h.geminiCachedContentService == nil {
+ googlePlatformError(c, http.StatusNotFound, "Explicit context caching is not enabled")
+ return nil, middleware.AuthSubject{}, nil, false
+ }
+ if apiKey.Group == nil || apiKey.GroupID == nil || apiKey.Group.Platform == service.PlatformComposite {
+ googleError(c, http.StatusBadRequest, "Explicit context caching is not supported for this API key group")
+ return nil, middleware.AuthSubject{}, nil, false
+ }
+ if effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini {
+ googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
+ return nil, middleware.AuthSubject{}, nil, false
+ }
+ reqLog := requestLogger(
+ c,
+ component,
+ zap.Int64("user_id", authSubject.UserID),
+ zap.Int64("api_key_id", apiKey.ID),
+ zap.Any("group_id", apiKey.GroupID),
+ )
+ return apiKey, authSubject, reqLog, true
+}
+
+func readGeminiCachedContentBody(c *gin.Context) ([]byte, bool) {
+ body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request)
+ if err != nil {
+ if maxErr, ok := extractMaxBytesError(err); ok {
+ googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit))
+ return nil, false
+ }
+ googleError(c, http.StatusBadRequest, "Failed to read request body")
+ return nil, false
+ }
+ if len(body) == 0 {
+ googleError(c, http.StatusBadRequest, "Request body is empty")
+ return nil, false
+ }
+ return body, true
+}
+
+func (h *GatewayHandler) checkGeminiCachedContentBilling(c *gin.Context, reqLog *zap.Logger, apiKey *service.APIKey, subscription *service.UserSubscription) bool {
+ if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil {
+ reqLog.Info("gemini.cached_content.billing_eligibility_check_failed", zap.Error(err))
+ status, code, message, retryAfter := billingErrorDetails(err)
+ if retryAfter > 0 {
+ c.Header("Retry-After", strconv.Itoa(retryAfter))
+ }
+ googleErrorWithType(c, status, code, "", message)
+ return false
+ }
+ return true
+}
+
+// GeminiCachedContentsCreate POST /v1beta/cachedContents
+// 创建请求内一次性收取缓存 token 的输入费与整个有效期的存储费。
+func (h *GatewayHandler) GeminiCachedContentsCreate(c *gin.Context) {
+ apiKey, authSubject, reqLog, ok := h.geminiCachedContentsPreamble(c, "handler.gemini_v1beta.cached_contents.create")
+ if !ok {
+ return
+ }
+ svc := h.geminiCachedContentService
+
+ body, ok := readGeminiCachedContentBody(c)
+ if !ok {
+ return
+ }
+ req, err := service.ParseGeminiCachedContentCreateRequest(body, svc.Now(), svc.MaxTTL())
+ if err != nil {
+ googleError(c, http.StatusBadRequest, err.Error())
+ return
+ }
+ modelName := req.Model
+ reqLog = reqLog.With(zap.String("model", modelName))
+
+ setOpsRequestContext(c, modelName, false)
+ setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(false, false)))
+ pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context())
+ c.Request = c.Request.WithContext(pricingCtx)
+
+ if decision := h.checkSecurityAudit(c, reqLog, apiKey, authSubject, service.ContentModerationProtocolGemini, modelName, body); decision != nil && !decision.AllowNextStage {
+ googleSecurityAuditError(c, decision)
+ return
+ }
+
+ channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, modelName)
+ reqModel := modelName
+ if channelMapping.Mapped {
+ modelName = channelMapping.MappedModel
+ }
+
+ subscription, _ := middleware.GetSubscriptionFromContext(c)
+ geminiConcurrency := NewConcurrencyHelper(h.concurrencyHelper.concurrencyService, SSEPingFormatNone, 0)
+ streamStarted := false
+ userReleaseFunc, err := geminiConcurrency.AcquireUserSlotWithWait(c, authSubject.UserID, authSubject.Concurrency, false, &streamStarted)
+ if err != nil {
+ reqLog.Warn("gemini.cached_content.user_slot_acquire_failed", zap.Error(err))
+ googleConcurrencyError(c, err, "user")
+ return
+ }
+ userReleaseFunc = wrapReleaseOnDone(c.Request.Context(), userReleaseFunc)
+ if userReleaseFunc != nil {
+ defer userReleaseFunc()
+ }
+
+ if !h.checkGeminiCachedContentBilling(c, reqLog, apiKey, subscription) {
+ return
+ }
+ inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(modelName, body))
+ if err != nil {
+ reqLog.Info("gemini.cached_content.inflight_reservation_rejected", zap.Error(err))
+ status, code, message, retryAfter := billingErrorDetails(err)
+ if retryAfter > 0 {
+ c.Header("Retry-After", strconv.Itoa(retryAfter))
+ }
+ googleErrorWithType(c, status, code, "", message)
+ return
+ }
+ defer inflightRelease()
+
+ excluded, err := h.gatewayService.GeminiExplicitCacheExclusions(c.Request.Context(), apiKey.GroupID, 0)
+ if err != nil {
+ reqLog.Warn("gemini.cached_content.list_accounts_failed", zap.Error(err))
+ googleError(c, http.StatusServiceUnavailable, "No available Gemini accounts support explicit context caching")
+ return
+ }
+
+ var lastUpstreamErr *service.GeminiCachedContentUpstreamError
+ var ttlRejectedLimit time.Duration
+ for attempts := 0; attempts < geminiCachedContentCreateMaxAttempts; {
+ selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, "", modelName, excluded, "", int64(0))
+ if err != nil {
+ if failoverClientGone(c) {
+ return
+ }
+ reqLog.Info("gemini.cached_content.account_select_exhausted", zap.Error(err))
+ break
+ }
+ account := selection.Account
+ if !service.IsGeminiExplicitCacheAccount(account) {
+ if selection.Acquired && selection.ReleaseFunc != nil {
+ selection.ReleaseFunc()
+ }
+ excluded[account.ID] = struct{}{}
+ continue
+ }
+ ttl, ttlAllowed := req.TTLForAccount(account)
+ if !ttlAllowed {
+ if selection.Acquired && selection.ReleaseFunc != nil {
+ selection.ReleaseFunc()
+ }
+ excluded[account.ID] = struct{}{}
+ ttlRejectedLimit = max(ttlRejectedLimit, account.GeminiExplicitCacheUpstreamMaxTTL())
+ continue
+ }
+ accountReleaseFunc, ok := h.acquireGeminiCachedContentAccountSlot(c, reqLog, geminiConcurrency, selection)
+ if !ok {
+ return
+ }
+ admissionCtx := service.ContextWithSelectionProfitGate(c.Request.Context(), selection)
+ latest, vetoed, reason := h.gatewayService.GatewayProfitControlVetoLatest(admissionCtx, account)
+ if vetoed {
+ accountReleaseFunc()
+ reqLog.Debug("gemini.cached_content.account_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
+ excluded[account.ID] = struct{}{}
+ continue
+ }
+ account = latest
+ attempts++
+ setOpsSelectedAccount(c, account.ID, account.Platform)
+
+ mappedModel := account.GetMappedModel(modelName)
+ usageFields := clientRequestedUsageFields(c, channelMapping, reqModel, mappedModel)
+ if !h.gatewayService.CacheStoragePriced(c.Request.Context(), &service.RecordUsageInput{
+ Result: &service.ForwardResult{Model: modelName, UpstreamModel: mappedModel, CacheStorageTokenHours: 1},
+ APIKey: apiKey,
+ ChannelUsageFields: usageFields,
+ }) {
+ accountReleaseFunc()
+ googlePlatformError(c, http.StatusBadRequest, fmt.Sprintf("Explicit context caching is not available for model %s: storage pricing is not configured", modelName))
+ return
+ }
+ upstreamModel, err := service.GeminiCachedContentUpstreamModelResource(account, mappedModel)
+ if err != nil {
+ accountReleaseFunc()
+ reqLog.Warn("gemini.cached_content.upstream_model_invalid", zap.Int64("account_id", account.ID), zap.Error(err))
+ excluded[account.ID] = struct{}{}
+ continue
+ }
+ publicID, err := service.NewGeminiCachedContentPublicID()
+ if err != nil {
+ accountReleaseFunc()
+ googleError(c, http.StatusInternalServerError, "Failed to allocate cached content id")
+ return
+ }
+
+ upstream, err := svc.CreateUpstream(c.Request.Context(), account, req, mappedModel, publicID, ttl)
+ accountReleaseFunc()
+ if err != nil {
+ var upErr *service.GeminiCachedContentUpstreamError
+ if errors.As(err, &upErr) {
+ reqLog.Info("gemini.cached_content.upstream_create_failed", zap.Int64("account_id", account.ID), zap.Int("status", upErr.StatusCode))
+ if upErr.RetryableOnOtherAccount() {
+ lastUpstreamErr = upErr
+ excluded[account.ID] = struct{}{}
+ continue
+ }
+ h.writeGeminiCachedContentUpstreamError(c, upErr)
+ return
+ }
+ // 上游已返回成功但响应不可用:不换号重建,能识别出资源名时删除上游缓存。
+ var malformed *service.GeminiCachedContentMalformedResponseError
+ if errors.As(err, &malformed) {
+ reqLog.Error("gemini.cached_content.upstream_create_malformed", zap.Int64("account_id", account.ID), zap.Error(err))
+ if malformed.Name != "" {
+ h.cleanupGeminiCachedContentUpstream(reqLog, account, malformed.Name)
+ }
+ googleError(c, http.StatusBadGateway, "Upstream returned an invalid cached content response")
+ return
+ }
+ if failoverClientGone(c) {
+ return
+ }
+ reqLog.Warn("gemini.cached_content.upstream_create_error", zap.Int64("account_id", account.ID), zap.Error(err))
+ excluded[account.ID] = struct{}{}
+ continue
+ }
+
+ // 缓存 token 数在上游创建后才确定:按确定金额校验余额 / 额度并预留,不足时删除上游缓存,
+ // 只收取已发生的缓存 token 输入费。
+ tokens := upstream.TotalTokenCount
+ storageTokenHours := service.GeminiCachedContentStorageTokenHours(tokens, ttl)
+ amount := h.gatewayService.QuoteUsageCost(c.Request.Context(), &service.RecordUsageInput{
+ Result: &service.ForwardResult{
+ Model: modelName, UpstreamModel: mappedModel,
+ Usage: service.ClaudeUsage{InputTokens: int(tokens)}, CacheStorageTokenHours: storageTokenHours,
+ },
+ APIKey: apiKey, User: apiKey.User, Subscription: subscription, PricingAt: pricingAt, ChannelUsageFields: usageFields,
+ })
+ inflightRelease()
+ chargeDone, err := h.reserveGeminiCachedContentCharge(c, apiKey, subscription, amount)
+ if err != nil {
+ reqLog.Info("gemini.cached_content.storage_charge_rejected", zap.Float64("amount", amount), zap.Error(err))
+ h.cleanupGeminiCachedContentUpstream(reqLog, account, upstream.Name)
+ h.submitGeminiCachedContentUsage(c, apiKey, account, subscription, pricingAt,
+ service.GeminiCachedContentCreateUsageRequestID(publicID), modelName, mappedModel, int(tokens), 0, usageFields, body)
+ writeGeminiCachedContentBillingError(c, err)
+ return
+ }
+ defer chargeDone()
+
+ expireTime := service.ClampGeminiCachedContentExpire(upstream.ExpireTime, svc.Now().Add(ttl))
+ record := &service.GeminiCachedContent{
+ PublicID: publicID,
+ UserID: authSubject.UserID,
+ APIKeyID: apiKey.ID,
+ GroupID: *apiKey.GroupID,
+ AccountID: account.ID,
+ UpstreamName: upstream.Name,
+ Model: modelName,
+ UpstreamModel: upstreamModel,
+ DisplayName: req.DisplayName,
+ TotalTokenCount: tokens,
+ ExpireTime: expireTime,
+ ChannelUsage: usageFields,
+ }
+ persistCtx, cancelPersist := geminiCachedContentPersistContext(c)
+ err = svc.Save(persistCtx, record)
+ cancelPersist()
+ if err != nil {
+ reqLog.Error("gemini.cached_content.save_failed", zap.Int64("account_id", account.ID), zap.Error(err))
+ h.cleanupGeminiCachedContentUpstream(reqLog, account, record.UpstreamName)
+ googleError(c, http.StatusInternalServerError, "Failed to persist cached content")
+ return
+ }
+
+ h.submitGeminiCachedContentUsage(c, apiKey, account, subscription, pricingAt,
+ service.GeminiCachedContentCreateUsageRequestID(publicID), modelName, mappedModel, int(tokens), storageTokenHours, usageFields, body)
+ c.JSON(http.StatusOK, service.GeminiCachedContentView(record))
+ return
+ }
+
+ if lastUpstreamErr != nil {
+ h.writeGeminiCachedContentUpstreamError(c, lastUpstreamErr)
+ return
+ }
+ if ttlRejectedLimit > 0 {
+ googleError(c, http.StatusBadRequest, fmt.Sprintf("ttl exceeds the maximum allowed %ds by the upstream accounts", int64(ttlRejectedLimit.Seconds())))
+ return
+ }
+ markOpsRoutingCapacityLimited(c)
+ googleError(c, http.StatusServiceUnavailable, "No available Gemini accounts support explicit context caching")
+}
+
+// GeminiCachedContentsList GET /v1beta/cachedContents
+// 只返回当前 API Key 在当前分组下仍有效的缓存,不透传上游 list(同一账号上其他租户的缓存不可见)。
+func (h *GatewayHandler) GeminiCachedContentsList(c *gin.Context) {
+ apiKey, _, reqLog, ok := h.geminiCachedContentsPreamble(c, "handler.gemini_v1beta.cached_contents.list")
+ if !ok {
+ return
+ }
+ pageSize := service.GeminiCachedContentListDefaultPageSize
+ if raw := strings.TrimSpace(c.Query("pageSize")); raw != "" {
+ n, err := strconv.Atoi(raw)
+ if err != nil || n < 0 {
+ googleError(c, http.StatusBadRequest, "pageSize must be a non-negative integer")
+ return
+ }
+ if n > 0 {
+ pageSize = min(n, service.GeminiCachedContentListMaxPageSize)
+ }
+ }
+ beforeID := int64(0)
+ if raw := strings.TrimSpace(c.Query("pageToken")); raw != "" {
+ id, ok := decodeGeminiCachedContentPageToken(raw)
+ if !ok {
+ googleError(c, http.StatusBadRequest, "Invalid pageToken")
+ return
+ }
+ beforeID = id
+ }
+ records, err := h.geminiCachedContentService.List(c.Request.Context(), apiKey.ID, *apiKey.GroupID, beforeID, pageSize+1)
+ if err != nil {
+ reqLog.Error("gemini.cached_content.list_failed", zap.Error(err))
+ googleError(c, http.StatusInternalServerError, "Failed to list cached contents")
+ return
+ }
+ resp := gin.H{}
+ if len(records) > pageSize {
+ records = records[:pageSize]
+ resp["nextPageToken"] = encodeGeminiCachedContentPageToken(records[len(records)-1].ID)
+ }
+ if len(records) > 0 {
+ views := make([]map[string]any, 0, len(records))
+ for _, record := range records {
+ views = append(views, service.GeminiCachedContentView(record))
+ }
+ resp["cachedContents"] = views
+ }
+ c.JSON(http.StatusOK, resp)
+}
+
+// GeminiCachedContentsGet GET /v1beta/cachedContents/:cacheID
+func (h *GatewayHandler) GeminiCachedContentsGet(c *gin.Context) {
+ apiKey, _, reqLog, ok := h.geminiCachedContentsPreamble(c, "handler.gemini_v1beta.cached_contents.get")
+ if !ok {
+ return
+ }
+ record, ok := h.resolveGeminiCachedContentOrWrite(c, reqLog, apiKey, c.Param("cacheID"))
+ if !ok {
+ return
+ }
+ c.JSON(http.StatusOK, service.GeminiCachedContentView(record))
+}
+
+// GeminiCachedContentsPatch PATCH /v1beta/cachedContents/:cacheID
+// 只允许修改有效期;延长部分在本次请求内按增量时长收取存储费,缩短不退费。
+// 同一缓存的修改串行执行:上游修改、本地写回与计费都在修改意图的租约内完成,并发的修改返回 409。
+// 上游结果未知或本地写回失败的修改不计费,租约过期后由恢复流程把上游有效期回滚到修改前的到期时间。
+func (h *GatewayHandler) GeminiCachedContentsPatch(c *gin.Context) {
+ apiKey, _, reqLog, ok := h.geminiCachedContentsPreamble(c, "handler.gemini_v1beta.cached_contents.patch")
+ if !ok {
+ return
+ }
+ svc := h.geminiCachedContentService
+ body, ok := readGeminiCachedContentBody(c)
+ if !ok {
+ return
+ }
+ record, ok := h.resolveGeminiCachedContentOrWrite(c, reqLog, apiKey, c.Param("cacheID"))
+ if !ok {
+ return
+ }
+ account, err := svc.BoundAccount(c.Request.Context(), record)
+ if err != nil {
+ reqLog.Error("gemini.cached_content.load_account_failed", zap.Int64("account_id", record.AccountID), zap.Error(err))
+ googleError(c, http.StatusInternalServerError, "Failed to load cached content account")
+ return
+ }
+ if account == nil {
+ googleError(c, http.StatusServiceUnavailable, geminiCachedContentUnavailableMessage)
+ return
+ }
+ ttl, err := service.ParseGeminiCachedContentPatchRequest(body, c.Query("updateMask"), svc.Now(), svc.MaxTTLForAccount(account))
+ if err != nil {
+ googleError(c, http.StatusBadRequest, err.Error())
+ return
+ }
+ setOpsRequestContext(c, record.Model, false)
+ pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context())
+ c.Request = c.Request.WithContext(pricingCtx)
+
+ subscription, _ := middleware.GetSubscriptionFromContext(c)
+ if extension := svc.Now().Add(ttl).Sub(record.ExpireTime); extension > 0 {
+ usage := &service.RecordUsageInput{
+ Result: &service.ForwardResult{
+ Model: record.Model, UpstreamModel: record.UpstreamModelID(),
+ CacheStorageTokenHours: service.GeminiCachedContentStorageTokenHours(record.TotalTokenCount, extension),
+ },
+ APIKey: apiKey, User: apiKey.User, Subscription: subscription, PricingAt: pricingAt,
+ ChannelUsageFields: record.ChannelUsage,
+ }
+ if !h.gatewayService.CacheStoragePriced(c.Request.Context(), usage) {
+ googlePlatformError(c, http.StatusBadRequest, fmt.Sprintf("Explicit context caching is not available for model %s: storage pricing is not configured", record.Model))
+ return
+ }
+ if !h.checkGeminiCachedContentBilling(c, reqLog, apiKey, subscription) {
+ return
+ }
+ chargeDone, err := h.reserveGeminiCachedContentCharge(c, apiKey, subscription, h.gatewayService.QuoteUsageCost(c.Request.Context(), usage))
+ if err != nil {
+ reqLog.Info("gemini.cached_content.storage_charge_rejected", zap.Error(err))
+ writeGeminiCachedContentBillingError(c, err)
+ return
+ }
+ defer chargeDone()
+ }
+
+ setOpsSelectedAccount(c, account.ID, account.Platform)
+ mutation, err := svc.BeginMutation(c.Request.Context(), record)
+ if err != nil {
+ switch {
+ case errors.Is(err, service.ErrGeminiCachedContentNotFound):
+ googleError(c, http.StatusForbidden, service.GeminiCachedContentNotFoundMessage)
+ case errors.Is(err, service.ErrGeminiCachedContentMutationConflict):
+ reqLog.Info("gemini.cached_content.mutation_conflict", zap.Int64("account_id", account.ID), zap.Error(err))
+ writeGeminiCachedContentMutationConflict(c)
+ default:
+ reqLog.Error("gemini.cached_content.begin_mutation_failed", zap.Int64("account_id", account.ID), zap.Error(err))
+ googleError(c, http.StatusInternalServerError, "Failed to update cached content")
+ }
+ return
+ }
+ upstream, err := svc.PatchUpstream(c.Request.Context(), account, record, ttl)
+ if err != nil {
+ var upErr *service.GeminiCachedContentUpstreamError
+ upstreamRejected := errors.As(err, &upErr)
+ if upstreamRejected || errors.Is(err, service.ErrGeminiCachedContentRequestNotSent) {
+ // 上游有效期未变:清除修改意图。
+ persistCtx, cancelPersist := geminiCachedContentPersistContext(c)
+ if releaseErr := svc.ReleaseMutation(persistCtx, mutation); releaseErr != nil {
+ reqLog.Warn("gemini.cached_content.release_mutation_failed", zap.Error(releaseErr))
+ }
+ cancelPersist()
+ }
+ if upstreamRejected {
+ if upErr.NotFound() {
+ if forgetErr := svc.Forget(c.Request.Context(), record); forgetErr != nil {
+ reqLog.Warn("gemini.cached_content.forget_failed", zap.Error(forgetErr))
+ }
+ }
+ h.writeGeminiCachedContentUpstreamError(c, upErr)
+ return
+ }
+ reqLog.Warn("gemini.cached_content.upstream_patch_error", zap.Int64("account_id", account.ID), zap.Error(err))
+ googleError(c, http.StatusBadGateway, "Upstream request failed")
+ return
+ }
+ expireTime := service.ClampGeminiCachedContentExpire(upstream.ExpireTime, svc.Now().Add(ttl))
+ persistCtx, cancelPersist := geminiCachedContentPersistContext(c)
+ err = svc.CommitMutation(persistCtx, mutation, expireTime)
+ cancelPersist()
+ if err != nil {
+ reqLog.Error("gemini.cached_content.commit_mutation_failed", zap.Int64("account_id", account.ID), zap.Error(err))
+ if errors.Is(err, service.ErrGeminiCachedContentMutationConflict) {
+ writeGeminiCachedContentMutationConflict(c)
+ return
+ }
+ googleError(c, http.StatusInternalServerError, "Failed to persist cached content expiration")
+ return
+ }
+ // 提交前库中的到期时间一直是修改前的值:按本次实际推进的时长收费。
+ if extended := expireTime.Sub(mutation.Baseline()); extended > 0 {
+ h.submitGeminiCachedContentUsage(c, apiKey, account, subscription, pricingAt,
+ service.GeminiCachedContentPatchUsageRequestID(record.PublicID), record.Model, record.UpstreamModelID(), 0,
+ service.GeminiCachedContentStorageTokenHours(record.TotalTokenCount, extended), record.ChannelUsage, body)
+ }
+ c.JSON(http.StatusOK, service.GeminiCachedContentView(record))
+}
+
+// GeminiCachedContentsDelete DELETE /v1beta/cachedContents/:cacheID
+// 删除不退还已收取的存储费。
+func (h *GatewayHandler) GeminiCachedContentsDelete(c *gin.Context) {
+ apiKey, _, reqLog, ok := h.geminiCachedContentsPreamble(c, "handler.gemini_v1beta.cached_contents.delete")
+ if !ok {
+ return
+ }
+ svc := h.geminiCachedContentService
+ record, ok := h.resolveGeminiCachedContentOrWrite(c, reqLog, apiKey, c.Param("cacheID"))
+ if !ok {
+ return
+ }
+ account, err := svc.BoundAccount(c.Request.Context(), record)
+ if err != nil {
+ reqLog.Error("gemini.cached_content.load_account_failed", zap.Int64("account_id", record.AccountID), zap.Error(err))
+ googleError(c, http.StatusInternalServerError, "Failed to load cached content account")
+ return
+ }
+ if account != nil {
+ setOpsSelectedAccount(c, account.ID, account.Platform)
+ if err := svc.DeleteUpstream(c.Request.Context(), account, record); err != nil {
+ var upErr *service.GeminiCachedContentUpstreamError
+ if !errors.As(err, &upErr) {
+ reqLog.Warn("gemini.cached_content.upstream_delete_error", zap.Int64("account_id", account.ID), zap.Error(err))
+ googleError(c, http.StatusBadGateway, "Upstream request failed")
+ return
+ }
+ if !upErr.NotFound() {
+ h.writeGeminiCachedContentUpstreamError(c, upErr)
+ return
+ }
+ }
+ }
+ persistCtx, cancelPersist := geminiCachedContentPersistContext(c)
+ err = svc.Forget(persistCtx, record)
+ cancelPersist()
+ if err != nil {
+ reqLog.Error("gemini.cached_content.forget_failed", zap.Error(err))
+ googleError(c, http.StatusInternalServerError, "Failed to delete cached content")
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{})
+}
+
+func (h *GatewayHandler) resolveGeminiCachedContentOrWrite(c *gin.Context, reqLog *zap.Logger, apiKey *service.APIKey, cacheID string) (*service.GeminiCachedContent, bool) {
+ record, err := h.geminiCachedContentService.Resolve(c.Request.Context(), apiKey.ID, apiKey.GroupID, cacheID)
+ if err != nil {
+ if errors.Is(err, service.ErrGeminiCachedContentNotFound) {
+ googleError(c, http.StatusForbidden, service.GeminiCachedContentNotFoundMessage)
+ return nil, false
+ }
+ reqLog.Error("gemini.cached_content.lookup_failed", zap.Error(err))
+ googleError(c, http.StatusInternalServerError, "Failed to load cached content")
+ return nil, false
+ }
+ return record, true
+}
+
+// resolveGeminiCachedContentBinding 处理 generateContent / countTokens 请求对显式缓存的引用:
+// 校验归属与模型后把引用改写为上游资源名,返回绑定记录;请求未引用缓存时返回 nil。
+// 返回 false 表示已写出错误响应。
+func (h *GatewayHandler) resolveGeminiCachedContentBinding(c *gin.Context, reqLog *zap.Logger, apiKey *service.APIKey, modelName string, body []byte) (*service.GeminiCachedContent, []byte, bool) {
+ ref, err := service.FindGeminiCachedContentReference(body)
+ if err != nil {
+ googleError(c, http.StatusBadRequest, err.Error())
+ return nil, nil, false
+ }
+ if ref == nil {
+ return nil, body, true
+ }
+ if middleware.HasForcePlatform(c) || h.geminiCachedContentService == nil ||
+ apiKey.Group == nil || apiKey.Group.Platform == service.PlatformComposite {
+ googleError(c, http.StatusBadRequest, "cachedContent is not supported on this route")
+ return nil, nil, false
+ }
+ record, err := h.geminiCachedContentService.Resolve(c.Request.Context(), apiKey.ID, apiKey.GroupID, ref.Name)
+ if err != nil {
+ if errors.Is(err, service.ErrGeminiCachedContentNotFound) {
+ googleError(c, http.StatusForbidden, service.GeminiCachedContentNotFoundMessage)
+ return nil, nil, false
+ }
+ reqLog.Error("gemini.cached_content.lookup_failed", zap.Error(err))
+ googleError(c, http.StatusInternalServerError, "Failed to load cached content")
+ return nil, nil, false
+ }
+ if record.Model != modelName {
+ googleError(c, http.StatusBadRequest, fmt.Sprintf(
+ "Model used by GenerateContent request (models/%s) and CachedContent (models/%s) has to be the same.", modelName, record.Model))
+ return nil, nil, false
+ }
+ rewritten, err := service.RewriteGeminiCachedContentReference(body, ref, record.UpstreamName)
+ if err != nil {
+ googleError(c, http.StatusBadRequest, "Invalid cachedContent reference")
+ return nil, nil, false
+ }
+ return record, rewritten, true
+}
+
+// acquireGeminiCachedContentAccountSlot 获取选中账号的并发槽(含等待计划);返回 false 表示已写出错误响应。
+func (h *GatewayHandler) acquireGeminiCachedContentAccountSlot(c *gin.Context, reqLog *zap.Logger, helper *ConcurrencyHelper, selection *service.AccountSelectionResult) (func(), bool) {
+ if selection.Acquired {
+ release := selection.ReleaseFunc
+ if release == nil {
+ release = func() {}
+ }
+ return wrapReleaseOnDone(c.Request.Context(), release), true
+ }
+ account := selection.Account
+ if selection.WaitPlan == nil {
+ markOpsRoutingCapacityLimited(c)
+ googleError(c, http.StatusServiceUnavailable, "No available Gemini accounts")
+ return nil, false
+ }
+ canWait, err := helper.IncrementAccountWaitCount(c.Request.Context(), account.ID, selection.WaitPlan.MaxWaiting)
+ if err != nil {
+ reqLog.Warn("gemini.cached_content.account_wait_counter_increment_failed", zap.Int64("account_id", account.ID), zap.Error(err))
+ } else if !canWait {
+ googleError(c, http.StatusTooManyRequests, "Too many pending requests, please retry later")
+ return nil, false
+ }
+ streamStarted := false
+ release, acquireErr := helper.AcquireAccountSlotWithWaitTimeout(c, account.ID, selection.WaitPlan.MaxConcurrency, selection.WaitPlan.Timeout, false, &streamStarted)
+ if err == nil {
+ helper.DecrementAccountWaitCount(c.Request.Context(), account.ID)
+ }
+ if acquireErr != nil {
+ reqLog.Warn("gemini.cached_content.account_slot_acquire_failed", zap.Int64("account_id", account.ID), zap.Error(acquireErr))
+ googleConcurrencyError(c, acquireErr, "account")
+ return nil, false
+ }
+ if release == nil {
+ release = func() {}
+ }
+ return wrapReleaseOnDone(c.Request.Context(), release), true
+}
+
+// submitGeminiCachedContentUsage 记录缓存创建 / 延长的计费:inputTokens 按输入价计,storageTokenHours 按计费模型的存储单价计;
+// requestID 是带固定前缀的费用行标识(见 GeminiCachedContentUsageRequestIDPrefix),落库时不被请求 id 覆盖。
+func (h *GatewayHandler) submitGeminiCachedContentUsage(
+ c *gin.Context,
+ apiKey *service.APIKey,
+ account *service.Account,
+ subscription *service.UserSubscription,
+ pricingAt time.Time,
+ requestID string,
+ model string,
+ upstreamModel string,
+ inputTokens int,
+ storageTokenHours float64,
+ usageFields service.ChannelUsageFields,
+ payload []byte,
+) {
+ if inputTokens <= 0 && storageTokenHours <= 0 {
+ return
+ }
+ if upstreamModel == model {
+ upstreamModel = ""
+ }
+ result := &service.ForwardResult{
+ RequestID: requestID,
+ Model: model,
+ UpstreamModel: upstreamModel,
+ Usage: service.ClaudeUsage{InputTokens: inputTokens},
+ CacheStorageTokenHours: storageTokenHours,
+ }
+ inboundEndpoint := GetInboundEndpoint(c)
+ upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
+ userAgent := c.GetHeader("User-Agent")
+ clientIP := ip.GetClientIP(c)
+ requestPayloadHash := service.HashUsageRequestPayload(payload)
+ quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
+ h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
+ if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
+ Result: result,
+ APIKey: apiKey,
+ User: apiKey.User,
+ Account: account,
+ Subscription: subscription,
+ PricingAt: pricingAt,
+ InboundEndpoint: inboundEndpoint,
+ UpstreamEndpoint: upstreamEndpoint,
+ UserAgent: userAgent,
+ IPAddress: clientIP,
+ RequestPayloadHash: requestPayloadHash,
+ APIKeyService: h.apiKeyService,
+ QuotaPlatform: quotaPlatform,
+ ChannelUsageFields: usageFields,
+ }); err != nil {
+ logger.L().With(
+ zap.String("component", "handler.gemini_v1beta.cached_contents"),
+ zap.Int64("api_key_id", apiKey.ID),
+ zap.Int64("account_id", account.ID),
+ zap.String("request_id", result.RequestID),
+ ).Error("gemini.cached_content.record_usage_failed", zap.Error(err))
+ }
+ })
+}
+
+// geminiCachedContentPersistContext 返回与客户端连接脱钩的落库 context:上游操作已生效时,客户端断开不应让本地记录缺失。
+func geminiCachedContentPersistContext(c *gin.Context) (context.Context, context.CancelFunc) {
+ return context.WithTimeout(context.WithoutCancel(c.Request.Context()), geminiCachedContentPersistTimeout)
+}
+
+// cleanupGeminiCachedContentUpstream 尽力删除已在上游创建、但网关不会登记的缓存,避免其持续产生存储费。
+func (h *GatewayHandler) cleanupGeminiCachedContentUpstream(reqLog *zap.Logger, account *service.Account, upstreamName string) {
+ ctx, cancel := context.WithTimeout(context.Background(), geminiCachedContentPersistTimeout)
+ defer cancel()
+ if err := h.geminiCachedContentService.DeleteUpstream(ctx, account, &service.GeminiCachedContent{UpstreamName: upstreamName}); err != nil {
+ reqLog.Error("gemini.cached_content.orphan_cleanup_failed", zap.Int64("account_id", account.ID), zap.String("upstream_name", upstreamName), zap.Error(err))
+ }
+}
+
+// reserveGeminiCachedContentCharge 校验余额 / 订阅额度 / API Key 额度足以支付确定金额 amount(倍率后),
+// 并按该金额在用户、订阅、API Key 维度登记在途预留(不受预留上限封顶,见 ReserveFixedCharge)。
+// 返回的 done 须在 handler 结束时调用;预留随计费任务交接,落库后释放。
+func (h *GatewayHandler) reserveGeminiCachedContentCharge(c *gin.Context, apiKey *service.APIKey, subscription *service.UserSubscription, amount float64) (func(), error) {
+ ctx := c.Request.Context()
+ res, err := h.billingCacheService.ReserveFixedCharge(ctx, apiKey.User, apiKey, apiKey.Group, subscription, amount)
+ if err != nil {
+ return inflightNoop, err
+ }
+ if res == nil {
+ return inflightNoop, nil
+ }
+ c.Request = c.Request.WithContext(service.WithInflightReservation(ctx, res))
+ return res.HandlerDone, nil
+}
+
+// writeGeminiCachedContentMutationConflict 回写同一缓存的修改冲突(Google 并发冲突语义 ABORTED),客户端可稍后重试。
+func writeGeminiCachedContentMutationConflict(c *gin.Context) {
+ c.JSON(http.StatusConflict, gin.H{
+ "error": gin.H{
+ "code": http.StatusConflict,
+ "message": "Another update to this cached content is in progress, please retry later",
+ "status": "ABORTED",
+ },
+ })
+}
+
+func writeGeminiCachedContentBillingError(c *gin.Context, err error) {
+ status, code, message, retryAfter := billingErrorDetails(err)
+ if retryAfter > 0 {
+ c.Header("Retry-After", strconv.Itoa(retryAfter))
+ }
+ googleErrorWithType(c, status, code, "", message)
+}
+
+// writeGeminiCachedContentUpstreamError 回写上游错误:缓存不存在统一返回标准 403(各上游形态不同且可能含上游资源 ID);
+// 账号凭据或权限类错误不是客户端问题,统一改为 502;限流 / 不可用按普通 Gemini 路径处理(透传规则、通用映射),
+// 只有上游网关账号的这类响应反映持有缓存的上游账号状态,原样回写。
+func (h *GatewayHandler) writeGeminiCachedContentUpstreamError(c *gin.Context, upErr *service.GeminiCachedContentUpstreamError) {
+ status := upErr.StatusCode
+ message := strings.TrimSpace(extractGoogleErrorMessage(upErr.Body))
+ service.SetOpsUpstreamError(c, status, message, "")
+ if upErr.NotFound() {
+ service.MarkOpsRequestScopedError(c, "permission_error")
+ c.Data(http.StatusForbidden, "application/json", []byte(service.GeminiCachedContentNotFoundResponse))
+ return
+ }
+ if (status == http.StatusTooManyRequests || status >= http.StatusInternalServerError) && !upErr.UpstreamGateway {
+ h.handleGeminiFailoverExhausted(c, &service.UpstreamFailoverError{StatusCode: status, ResponseBody: upErr.Body})
+ return
+ }
+ if status == http.StatusUnauthorized || status == http.StatusForbidden {
+ googleError(c, http.StatusBadGateway, "Upstream account rejected the cached content request")
+ return
+ }
+ if len(upErr.Body) == 0 || !json.Valid(upErr.Body) {
+ if message == "" {
+ message = http.StatusText(status)
+ }
+ googleError(c, status, message)
+ return
+ }
+ c.Data(status, "application/json", upErr.Body)
+}
+
+func extractGoogleErrorMessage(body []byte) string {
+ var envelope struct {
+ Error struct {
+ Message string `json:"message"`
+ } `json:"error"`
+ }
+ if err := json.Unmarshal(body, &envelope); err != nil {
+ return ""
+ }
+ return envelope.Error.Message
+}
+
+func encodeGeminiCachedContentPageToken(id int64) string {
+ return base64.RawURLEncoding.EncodeToString([]byte(strconv.FormatInt(id, 10)))
+}
+
+func decodeGeminiCachedContentPageToken(raw string) (int64, bool) {
+ decoded, err := base64.RawURLEncoding.DecodeString(raw)
+ if err != nil {
+ return 0, false
+ }
+ id, err := strconv.ParseInt(string(decoded), 10, 64)
+ if err != nil || id <= 0 {
+ return 0, false
+ }
+ return id, true
+}
+
+// mergeAccountIDSets 返回两个账号 ID 集合的并集(不修改入参)。
+func mergeAccountIDSets(a, b map[int64]struct{}) map[int64]struct{} {
+ out := make(map[int64]struct{}, len(a)+len(b))
+ for id := range a {
+ out[id] = struct{}{}
+ }
+ for id := range b {
+ out[id] = struct{}{}
+ }
+ return out
+}
+
+// handleGeminiCachedContentFailoverExhausted 处理绑定缓存的请求在持有账号上重试耗尽:没有其他账号可换。
+// 上游网关账号的限流 / 不可用响应反映持有缓存的上游账号状态,原样返回供客户端判断;
+// 其余(含官方账号)仍按普通 Gemini 路径处理:透传规则、通用映射。
+func (h *GatewayHandler) handleGeminiCachedContentFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError) {
+ if failoverErr == nil || !failoverErr.BoundUpstreamPassthrough || len(failoverErr.ResponseBody) == 0 || !json.Valid(failoverErr.ResponseBody) {
+ h.handleGeminiFailoverExhausted(c, failoverErr)
+ return
+ }
+ service.SetOpsUpstreamError(c, failoverErr.StatusCode, service.ExtractUpstreamErrorMessage(failoverErr.ResponseBody), "")
+ c.Data(failoverErr.StatusCode, "application/json", failoverErr.ResponseBody)
+}
diff --git a/backend/internal/handler/gemini_cached_contents_handler_test.go b/backend/internal/handler/gemini_cached_contents_handler_test.go
new file mode 100644
index 000000000..7b9c99e27
--- /dev/null
+++ b/backend/internal/handler/gemini_cached_contents_handler_test.go
@@ -0,0 +1,264 @@
+//go:build unit
+
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ middleware "github.com/MACOS-DO/sub4api/internal/server/middleware"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "go.uber.org/zap"
+)
+
+type geminiCachedContentHandlerRepoStub struct {
+ records []*service.GeminiCachedContent
+}
+
+func (r *geminiCachedContentHandlerRepoStub) Create(_ context.Context, record *service.GeminiCachedContent) error {
+ record.ID = int64(len(r.records) + 1)
+ r.records = append(r.records, record)
+ return nil
+}
+
+func (r *geminiCachedContentHandlerRepoStub) GetForOwner(_ context.Context, apiKeyID int64, publicID string) (*service.GeminiCachedContent, error) {
+ for _, record := range r.records {
+ if record.PublicID == publicID && record.APIKeyID == apiKeyID {
+ return record, nil
+ }
+ }
+ return nil, service.ErrGeminiCachedContentNotFound
+}
+
+func (r *geminiCachedContentHandlerRepoStub) ListForOwner(_ context.Context, apiKeyID, groupID int64, activeAt time.Time, beforeID int64, limit int) ([]*service.GeminiCachedContent, error) {
+ var out []*service.GeminiCachedContent
+ for i := len(r.records) - 1; i >= 0; i-- {
+ record := r.records[i]
+ if record.APIKeyID == apiKeyID && record.GroupID == groupID && record.ExpireTime.After(activeAt) && (beforeID <= 0 || record.ID < beforeID) {
+ out = append(out, record)
+ }
+ if len(out) == limit {
+ break
+ }
+ }
+ return out, nil
+}
+
+func (r *geminiCachedContentHandlerRepoStub) BeginMutation(context.Context, int64, time.Time, string, time.Duration) (bool, error) {
+ return true, nil
+}
+
+func (r *geminiCachedContentHandlerRepoStub) TakeOverStaleMutation(context.Context, int64, string, time.Duration) (*service.GeminiCachedContent, error) {
+ return nil, nil
+}
+
+func (r *geminiCachedContentHandlerRepoStub) CommitMutation(context.Context, int64, string, time.Time) error {
+ return nil
+}
+
+func (r *geminiCachedContentHandlerRepoStub) ReleaseMutation(context.Context, int64, string) error {
+ return nil
+}
+
+func (r *geminiCachedContentHandlerRepoStub) ListStaleMutations(context.Context, int) ([]int64, error) {
+ return nil, nil
+}
+
+func (r *geminiCachedContentHandlerRepoStub) SoftDelete(context.Context, int64) error {
+ return nil
+}
+
+func newGeminiCachedContentHandlerForTest(repo *geminiCachedContentHandlerRepoStub) *GatewayHandler {
+ return &GatewayHandler{geminiCachedContentService: service.NewGeminiCachedContentService(repo, nil, &config.Config{})}
+}
+
+func geminiCachedContentTestAPIKey(platform string) *service.APIKey {
+ groupID := int64(42)
+ return &service.APIKey{ID: 7, UserID: 3, GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: platform}}
+}
+
+func newGeminiCachedContentTestContext(method, target string, apiKey *service.APIKey) (*gin.Context, *httptest.ResponseRecorder) {
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(method, target, nil)
+ c.Set(string(middleware.ContextKeyAPIKey), apiKey)
+ c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10})
+ return c, rec
+}
+
+func seedGeminiCachedContent(repo *geminiCachedContentHandlerRepoStub, publicID string, apiKeyID int64, expire time.Time) *service.GeminiCachedContent {
+ record := &service.GeminiCachedContent{
+ PublicID: publicID,
+ UserID: 3,
+ APIKeyID: apiKeyID,
+ GroupID: 42,
+ AccountID: 900,
+ UpstreamName: "cachedContents/upstream" + publicID,
+ Model: "gemini-3.8-flash",
+ UpstreamModel: "models/gemini-3.8-flash",
+ TotalTokenCount: 6273,
+ ExpireTime: expire,
+ CreatedAt: time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC),
+ UpdatedAt: time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC),
+ }
+ _ = repo.Create(context.Background(), record)
+ return record
+}
+
+func TestResolveGeminiCachedContentBinding(t *testing.T) {
+ repo := &geminiCachedContentHandlerRepoStub{}
+ seedGeminiCachedContent(repo, "abc", 7, time.Now().Add(time.Hour))
+ seedGeminiCachedContent(repo, "foreign", 8, time.Now().Add(time.Hour))
+ h := newGeminiCachedContentHandlerForTest(repo)
+ apiKey := geminiCachedContentTestAPIKey(service.PlatformGemini)
+
+ t.Run("request without cache passes through", func(t *testing.T) {
+ c, _ := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey)
+ body := []byte(`{"contents":[]}`)
+ record, out, ok := h.resolveGeminiCachedContentBinding(c, zap.NewNop(), apiKey, "gemini-3.8-flash", body)
+ require.True(t, ok)
+ require.Nil(t, record)
+ require.Equal(t, body, out)
+ })
+
+ t.Run("owned cache rewrites reference and binds account", func(t *testing.T) {
+ c, _ := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey)
+ record, out, ok := h.resolveGeminiCachedContentBinding(c, zap.NewNop(), apiKey, "gemini-3.8-flash",
+ []byte(`{"cachedContent":"cachedContents/abc","contents":[]}`))
+ require.True(t, ok)
+ require.Equal(t, int64(900), record.AccountID)
+ require.JSONEq(t, `{"cachedContent":"cachedContents/upstreamabc","contents":[]}`, string(out))
+ })
+
+ t.Run("cache owned by another key looks missing", func(t *testing.T) {
+ c, rec := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey)
+ _, _, ok := h.resolveGeminiCachedContentBinding(c, zap.NewNop(), apiKey, "gemini-3.8-flash",
+ []byte(`{"cachedContent":"cachedContents/foreign","contents":[]}`))
+ require.False(t, ok)
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Contains(t, rec.Body.String(), service.GeminiCachedContentNotFoundMessage)
+ })
+
+ t.Run("model must match the cache literally", func(t *testing.T) {
+ c, rec := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-flash-latest:generateContent", apiKey)
+ _, _, ok := h.resolveGeminiCachedContentBinding(c, zap.NewNop(), apiKey, "gemini-flash-latest",
+ []byte(`{"cachedContent":"cachedContents/abc","contents":[]}`))
+ require.False(t, ok)
+ require.Equal(t, http.StatusBadRequest, rec.Code)
+ require.Contains(t, rec.Body.String(), "has to be the same")
+ })
+
+ t.Run("composite groups are rejected", func(t *testing.T) {
+ composite := geminiCachedContentTestAPIKey(service.PlatformComposite)
+ c, rec := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", composite)
+ _, _, ok := h.resolveGeminiCachedContentBinding(c, zap.NewNop(), composite, "gemini-3.8-flash",
+ []byte(`{"cachedContent":"cachedContents/abc","contents":[]}`))
+ require.False(t, ok)
+ require.Equal(t, http.StatusBadRequest, rec.Code)
+ })
+}
+
+func TestGeminiCachedContentsListAndGet(t *testing.T) {
+ repo := &geminiCachedContentHandlerRepoStub{}
+ seedGeminiCachedContent(repo, "first", 7, time.Now().Add(time.Hour))
+ seedGeminiCachedContent(repo, "second", 7, time.Now().Add(time.Hour))
+ seedGeminiCachedContent(repo, "expired", 7, time.Now().Add(-time.Minute))
+ seedGeminiCachedContent(repo, "foreign", 8, time.Now().Add(time.Hour))
+ h := newGeminiCachedContentHandlerForTest(repo)
+ apiKey := geminiCachedContentTestAPIKey(service.PlatformGemini)
+
+ c, rec := newGeminiCachedContentTestContext(http.MethodGet, "/v1beta/cachedContents?pageSize=1", apiKey)
+ h.GeminiCachedContentsList(c)
+ require.Equal(t, http.StatusOK, rec.Code)
+ var page struct {
+ CachedContents []map[string]any `json:"cachedContents"`
+ NextPageToken string `json:"nextPageToken"`
+ }
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &page))
+ require.Len(t, page.CachedContents, 1)
+ require.Equal(t, "cachedContents/second", page.CachedContents[0]["name"])
+ require.NotEmpty(t, page.NextPageToken)
+
+ c, rec = newGeminiCachedContentTestContext(http.MethodGet, "/v1beta/cachedContents?pageSize=1&pageToken="+page.NextPageToken, apiKey)
+ h.GeminiCachedContentsList(c)
+ require.Equal(t, http.StatusOK, rec.Code)
+ page.NextPageToken = ""
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &page))
+ require.Len(t, page.CachedContents, 1)
+ require.Equal(t, "cachedContents/first", page.CachedContents[0]["name"])
+ require.Empty(t, page.NextPageToken, "过期与其他 Key 的缓存不出现在列表里")
+
+ c, rec = newGeminiCachedContentTestContext(http.MethodGet, "/v1beta/cachedContents/first", apiKey)
+ c.Params = gin.Params{{Key: "cacheID", Value: "first"}}
+ h.GeminiCachedContentsGet(c)
+ require.Equal(t, http.StatusOK, rec.Code)
+ var view map[string]any
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &view))
+ require.Equal(t, "cachedContents/first", view["name"])
+ require.Equal(t, "models/gemini-3.8-flash", view["model"])
+ require.NotContains(t, rec.Body.String(), "upstreamfirst", "上游资源名不暴露给客户端")
+
+ c, rec = newGeminiCachedContentTestContext(http.MethodGet, "/v1beta/cachedContents/foreign", apiKey)
+ c.Params = gin.Params{{Key: "cacheID", Value: "foreign"}}
+ h.GeminiCachedContentsGet(c)
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.True(t, strings.Contains(rec.Body.String(), service.GeminiCachedContentNotFoundMessage))
+}
+
+func TestHandleGeminiCachedContentFailoverExhausted(t *testing.T) {
+ h := &GatewayHandler{}
+ apiKey := geminiCachedContentTestAPIKey(service.PlatformGemini)
+ unavailable := `{"error":{"code":503,"message":"The account holding this cached content is temporarily unavailable","status":"UNAVAILABLE"}}`
+
+ c, rec := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey)
+ h.handleGeminiCachedContentFailoverExhausted(c, &service.UpstreamFailoverError{StatusCode: http.StatusServiceUnavailable, ResponseBody: []byte(unavailable), BoundUpstreamPassthrough: true})
+ require.Equal(t, http.StatusServiceUnavailable, rec.Code, "绑定缓存的请求无账号可换,上游网关的 503 原样返回")
+ require.JSONEq(t, unavailable, rec.Body.String())
+
+ c, rec = newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey)
+ h.handleGeminiCachedContentFailoverExhausted(c, &service.UpstreamFailoverError{StatusCode: http.StatusTooManyRequests, ResponseBody: []byte(`{"error":{"code":429,"message":"Too many pending requests, please retry later","status":"RESOURCE_EXHAUSTED"}}`), BoundUpstreamPassthrough: true})
+ require.Equal(t, http.StatusTooManyRequests, rec.Code)
+ require.Contains(t, rec.Body.String(), "Too many pending requests")
+
+ officialQuota := `{"error":{"code":429,"message":"You exceeded your current quota","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.QuotaFailure","violations":[{"quotaId":"GenerateRequestsPerDayPerProjectPerModel-FreeTier"}]}]}}`
+ c, rec = newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey)
+ h.handleGeminiCachedContentFailoverExhausted(c, &service.UpstreamFailoverError{StatusCode: http.StatusTooManyRequests, ResponseBody: []byte(officialQuota)})
+ require.Equal(t, http.StatusTooManyRequests, rec.Code, "官方账号的限流按普通 Gemini 路径映射")
+ require.NotContains(t, rec.Body.String(), "FreeTier", "不向客户端暴露上游账号的配额明细")
+ require.Contains(t, rec.Body.String(), "Upstream rate limit exceeded")
+
+ c, rec = newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey)
+ h.handleGeminiCachedContentFailoverExhausted(c, &service.UpstreamFailoverError{StatusCode: http.StatusUnauthorized, ResponseBody: []byte(`{"error":{"code":401,"message":"bad key"}}`)})
+ require.Equal(t, http.StatusBadGateway, rec.Code, "账号凭据类错误仍按网关映射,不透传给客户端")
+ require.NotContains(t, rec.Body.String(), "bad key")
+}
+
+func TestWriteGeminiCachedContentUpstreamError_RateLimitMappedUnlessUpstreamGateway(t *testing.T) {
+ h := &GatewayHandler{}
+ apiKey := geminiCachedContentTestAPIKey(service.PlatformGemini)
+ quota := `{"error":{"code":429,"message":"You exceeded your current quota","status":"RESOURCE_EXHAUSTED","details":[{"quotaId":"GenerateRequestsPerDayPerProjectPerModel-FreeTier"}]}}`
+
+ c, rec := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/cachedContents", apiKey)
+ h.writeGeminiCachedContentUpstreamError(c, &service.GeminiCachedContentUpstreamError{StatusCode: http.StatusTooManyRequests, Body: []byte(quota)})
+ require.Equal(t, http.StatusTooManyRequests, rec.Code)
+ require.NotContains(t, rec.Body.String(), "FreeTier", "官方账号的限流不透传配额明细")
+
+ c, rec = newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/cachedContents", apiKey)
+ h.writeGeminiCachedContentUpstreamError(c, &service.GeminiCachedContentUpstreamError{StatusCode: http.StatusTooManyRequests, Body: []byte(quota), UpstreamGateway: true})
+ require.Equal(t, http.StatusTooManyRequests, rec.Code)
+ require.JSONEq(t, quota, rec.Body.String(), "上游网关账号的限流反映持有缓存的上游账号状态,原样回写")
+
+ c, rec = newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/cachedContents", apiKey)
+ h.writeGeminiCachedContentUpstreamError(c, &service.GeminiCachedContentUpstreamError{StatusCode: http.StatusBadRequest, Body: []byte(`{"error":{"code":400,"message":"Cached content is too small","status":"INVALID_ARGUMENT"}}`)})
+ require.Equal(t, http.StatusBadRequest, rec.Code)
+ require.Contains(t, rec.Body.String(), "too small", "请求校验类错误仍原样回写")
+}
diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go
index d55aa1643..21792e469 100644
--- a/backend/internal/handler/gemini_v1beta_handler.go
+++ b/backend/internal/handler/gemini_v1beta_handler.go
@@ -39,9 +39,11 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
googleError(c, http.StatusUnauthorized, "Invalid API key")
return
}
- // 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组
+ // 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组(composite 分组允许路由到 antigravity)
forcePlatform, hasForcePlatform := middleware.GetForcePlatformFromContext(c)
- if !hasForcePlatform && effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini {
+ effectivePlatform := effectiveAPIKeyPlatform(c, apiKey)
+ if !hasForcePlatform && effectivePlatform != service.PlatformGemini &&
+ !servesCompositeAntigravityGemini(apiKey, effectivePlatform) {
googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
return
}
@@ -74,7 +76,7 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
return
}
- account, err := h.geminiCompatService.SelectAccountForAIStudioEndpoints(c.Request.Context(), apiKey.GroupID)
+ account, err := h.geminiCompatService.SelectAccountForModelsEndpoints(c.Request.Context(), apiKey.GroupID)
if err != nil {
if len(agModels) > 0 {
c.JSON(http.StatusOK, gemini.ModelsListResponse{Models: filterGeminiModels(agModels)})
@@ -85,7 +87,7 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
return
}
- res, err := h.geminiCompatService.ForwardAIStudioGET(c.Request.Context(), account, "/v1beta/models")
+ res, err := h.geminiCompatService.ForwardListModels(c.Request.Context(), account)
if err != nil {
googleError(c, http.StatusBadGateway, err.Error())
return
@@ -223,9 +225,11 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) {
googleError(c, http.StatusUnauthorized, "Invalid API key")
return
}
- // 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组
+ // 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组(composite 分组允许路由到 antigravity)
forcePlatform, hasForcePlatform := middleware.GetForcePlatformFromContext(c)
- if !hasForcePlatform && effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini {
+ effectivePlatform := effectiveAPIKeyPlatform(c, apiKey)
+ if !hasForcePlatform && effectivePlatform != service.PlatformGemini &&
+ !servesCompositeAntigravityGemini(apiKey, effectivePlatform) {
googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
return
}
@@ -244,14 +248,18 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) {
if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok && strings.TrimSpace(resolvedModel) != "" {
modelName = strings.TrimSpace(resolvedModel)
}
+ if !hasForcePlatform && servesCompositeAntigravityGemini(apiKey, effectivePlatform) && !isAntigravityGeminiModel(modelName) {
+ googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
+ return
+ }
- // 强制 antigravity 模式:返回 antigravity 模型信息
- if forcePlatform == service.PlatformAntigravity {
+ // 强制 antigravity 模式或 composite 路由到 antigravity:返回 antigravity 模型信息
+ if forcePlatform == service.PlatformAntigravity || effectivePlatform == service.PlatformAntigravity {
c.JSON(http.StatusOK, antigravity.FallbackGeminiModel(modelName))
return
}
- account, err := h.geminiCompatService.SelectAccountForAIStudioEndpoints(c.Request.Context(), apiKey.GroupID)
+ account, err := h.geminiCompatService.SelectAccountForModelsEndpoints(c.Request.Context(), apiKey.GroupID)
if err != nil {
// 没有 gemini 账户,检查是否有 antigravity 账户可用
hasAntigravity, _ := h.geminiCompatService.HasAntigravityAccounts(c.Request.Context(), apiKey.GroupID)
@@ -265,7 +273,7 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) {
return
}
- res, err := h.geminiCompatService.ForwardAIStudioGET(c.Request.Context(), account, "/v1beta/models/"+modelName)
+ res, err := h.geminiCompatService.ForwardGetModel(c.Request.Context(), account, modelName)
if err != nil {
googleError(c, http.StatusBadGateway, err.Error())
return
@@ -299,9 +307,11 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
zap.Any("group_id", apiKey.GroupID),
)
- // 检查平台:优先使用强制平台(/antigravity 路由,中间件已设置 request.Context),否则要求 gemini 分组
+ // 检查平台:优先使用强制平台(/antigravity 路由,中间件已设置 request.Context),否则要求 gemini 分组(composite 分组允许路由到 antigravity)
+ effectivePlatform := effectiveAPIKeyPlatform(c, apiKey)
if !middleware.HasForcePlatform(c) {
- if effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini {
+ if effectivePlatform != service.PlatformGemini &&
+ !servesCompositeAntigravityGemini(apiKey, effectivePlatform) {
googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
return
}
@@ -321,6 +331,10 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok && strings.TrimSpace(resolvedModel) != "" {
modelName = strings.TrimSpace(resolvedModel)
}
+ if !middleware.HasForcePlatform(c) && servesCompositeAntigravityGemini(apiKey, effectivePlatform) && !isAntigravityGeminiModel(modelName) {
+ googleError(c, http.StatusBadRequest, "API key group platform is not gemini")
+ return
+ }
stream := action == "streamGenerateContent"
reqLog = reqLog.With(zap.String("model", modelName), zap.String("action", action), zap.Bool("stream", stream))
@@ -356,6 +370,12 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
modelName = channelMapping.MappedModel
}
+ // 引用显式缓存的请求只能发往持有该缓存的账号,且不参与会话粘性与换号。
+ cachedContentBinding, body, ok := h.resolveGeminiCachedContentBinding(c, reqLog, apiKey, modelName, body)
+ if !ok {
+ return
+ }
+
// Get subscription (may be nil)
subscription, _ := middleware.GetSubscriptionFromContext(c)
@@ -382,11 +402,11 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
// 2) billing eligibility check (after wait)
if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil {
reqLog.Info("gemini.billing_eligibility_check_failed", zap.Error(err))
- status, _, message, retryAfter := billingErrorDetails(err)
+ status, code, message, retryAfter := billingErrorDetails(err)
if retryAfter > 0 {
c.Header("Retry-After", strconv.Itoa(retryAfter))
}
- googleError(c, status, message)
+ googleErrorWithType(c, status, code, "", message)
return
}
@@ -394,19 +414,22 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(modelName, body))
if err != nil {
reqLog.Info("gemini.inflight_reservation_rejected", zap.Error(err))
- status, _, message, retryAfter := billingErrorDetails(err)
+ status, code, message, retryAfter := billingErrorDetails(err)
if retryAfter > 0 {
c.Header("Retry-After", strconv.Itoa(retryAfter))
}
- googleError(c, status, message)
+ googleErrorWithType(c, status, code, "", message)
return
}
defer inflightRelease()
// 3) select account (sticky session based on request body)
// 优先使用 Gemini CLI 的会话标识(privileged-user-id + tmp 目录哈希)
- sessionHash := extractGeminiCLISessionHash(c, body)
- if sessionHash == "" {
+ sessionHash := ""
+ if cachedContentBinding == nil {
+ sessionHash = extractGeminiCLISessionHash(c, body)
+ }
+ if sessionHash == "" && cachedContentBinding == nil {
// Fallback: 使用通用的会话哈希生成逻辑(适用于其他客户端)
parsedReq, _ := service.ParseGatewayRequest(service.NewRequestBodyRef(body), domain.PlatformGemini)
if parsedReq != nil {
@@ -443,7 +466,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
var geminiPrefixHash string
var geminiSessionUUID string
var matchedDigestChain string
- useDigestFallback := sessionBoundAccountID == 0
+ useDigestFallback := sessionBoundAccountID == 0 && cachedContentBinding == nil
if useDigestFallback {
// 解析 Gemini 请求体
@@ -507,7 +530,21 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
hasBoundSession := sessionKey != "" && sessionBoundAccountID > 0
cleanedForUnknownBinding := false
- fs := NewFailoverState(h.maxAccountSwitchesGemini, hasBoundSession)
+ maxAccountSwitches := h.maxAccountSwitchesGemini
+ var cachedContentExclusions map[int64]struct{}
+ if cachedContentBinding != nil {
+ // 缓存只存在于绑定账号:排除分组内其余账号,失败不换号。
+ maxAccountSwitches = 0
+ sessionBoundAccountID = cachedContentBinding.AccountID
+ c.Request = c.Request.WithContext(service.WithGeminiCachedContentBound(c.Request.Context()))
+ cachedContentExclusions, err = h.gatewayService.GeminiExplicitCacheExclusions(c.Request.Context(), apiKey.GroupID, cachedContentBinding.AccountID)
+ if err != nil {
+ reqLog.Warn("gemini.cached_content.list_accounts_failed", zap.Error(err))
+ googleError(c, http.StatusServiceUnavailable, geminiCachedContentUnavailableMessage)
+ return
+ }
+ }
+ fs := NewFailoverState(maxAccountSwitches, hasBoundSession)
// 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。
// 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。
@@ -517,14 +554,38 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
}
for {
- selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, sessionKey, modelName, fs.FailedAccountIDs, "", int64(0)) // Gemini 不使用会话限制
+ excludedAccountIDs := fs.FailedAccountIDs
+ if cachedContentExclusions != nil {
+ excludedAccountIDs = mergeAccountIDSets(cachedContentExclusions, fs.FailedAccountIDs)
+ }
+ selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, sessionKey, modelName, excludedAccountIDs, "", int64(0)) // Gemini 不使用会话限制
+ if err == nil && cachedContentBinding != nil && selection.Account.ID != cachedContentBinding.AccountID {
+ if selection.Acquired && selection.ReleaseFunc != nil {
+ selection.ReleaseFunc()
+ }
+ err = service.ErrNoAvailableAccounts
+ }
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gemini.account_select_aborted_client_disconnected", zap.Error(err))
return
}
+ if cachedContentBinding != nil {
+ if fs.LastFailoverErr != nil {
+ h.handleGeminiCachedContentFailoverExhausted(c, fs.LastFailoverErr)
+ return
+ }
+ reqLog.Info("gemini.cached_content.bound_account_unavailable", zap.Int64("account_id", cachedContentBinding.AccountID), zap.Error(err))
+ markOpsRoutingCapacityLimited(c)
+ googleError(c, http.StatusServiceUnavailable, geminiCachedContentUnavailableMessage)
+ return
+ }
if len(fs.FailedAccountIDs) == 0 {
- cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, modelName, modelName, service.PlatformGemini)
+ diagPlatform := service.PlatformGemini
+ if p := effectiveAPIKeyPlatform(c, apiKey); p == service.PlatformAntigravity {
+ diagPlatform = service.PlatformAntigravity
+ }
+ cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, modelName, modelName, diagPlatform)
if !cls.ModelNotFound {
markOpsRoutingCapacityLimitedIfNoAvailable(c, err)
}
@@ -631,6 +692,11 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
accountReleaseFunc()
}
reqLog.Debug("gemini.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
+ if cachedContentBinding != nil {
+ markOpsRoutingCapacityLimited(c)
+ googleError(c, http.StatusServiceUnavailable, geminiCachedContentUnavailableMessage)
+ return
+ }
if fs.RecordProfitVeto(account.ID) == FailoverExhausted {
reqLog.Warn("gemini.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", fs.ProfitVetoCount()))
markOpsRoutingCapacityLimited(c)
@@ -684,6 +750,10 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
case FailoverContinue:
continue
case FailoverExhausted:
+ if cachedContentBinding != nil {
+ h.handleGeminiCachedContentFailoverExhausted(c, fs.LastFailoverErr)
+ return
+ }
h.handleGeminiFailoverExhausted(c, fs.LastFailoverErr)
return
case FailoverCanceled:
@@ -809,7 +879,8 @@ func (h *GatewayHandler) handleGeminiFailoverExhausted(c *gin.Context, failoverE
c.Set(service.OpsSkipPassthroughKey, true)
}
- googleError(c, respCode, msg)
+ // 按透传规则改写的是上游错误,不登记本地错误类型。
+ googleErrorWithType(c, respCode, "", "", msg)
return
}
}
@@ -844,7 +915,21 @@ type pathParseError struct{ msg string }
func (e *pathParseError) Error() string { return e.msg }
+// googleError 以 Google 错误格式回写网关产生的错误,并按状态码向 ops 登记错误类型:
+// 4xx 为客户端请求问题,其余状态码不登记(按平台错误统计)。
func googleError(c *gin.Context, status int, message string) {
+ googleErrorWithType(c, status, googleClientErrorType(status), "", message)
+}
+
+// googlePlatformError 以 Google 错误格式回写由平台侧原因(如管理员未完成配置)导致的错误,ops 按平台错误统计。
+func googlePlatformError(c *gin.Context, status int, message string) {
+ googleErrorWithType(c, status, "", "", message)
+}
+
+// googleErrorWithType 以 Google 错误格式回写错误,并向 ops 登记错误类型与错误码(Google 错误体没有 type 字段),
+// 与 Claude / OpenAI 格式错误同口径分类;errType 为空时不登记。
+func googleErrorWithType(c *gin.Context, status int, errType, code, message string) {
+ service.SetOpsLocalErrorType(c, errType, code)
c.JSON(status, gin.H{
"error": gin.H{
"code": status,
@@ -854,11 +939,27 @@ func googleError(c *gin.Context, status int, message string) {
})
}
+// googleClientErrorType 返回客户端请求类 4xx 状态码对应的 ops 错误类型;其余状态码返回空串。
+func googleClientErrorType(status int) string {
+ switch status {
+ case http.StatusBadRequest, http.StatusRequestEntityTooLarge:
+ return "invalid_request_error"
+ case http.StatusUnauthorized:
+ return "authentication_error"
+ case http.StatusForbidden:
+ return "permission_error"
+ case http.StatusNotFound:
+ return "not_found_error"
+ default:
+ return ""
+ }
+}
+
// googleConcurrencyError 以 Google 错误格式回写并发槽获取失败,状态码与文案
// 沿用 concurrencyErrorResponse 的统一映射(客户端断开为 499)。
func googleConcurrencyError(c *gin.Context, err error, slotType string) {
- status, _, _, message := concurrencyErrorResponse(err, slotType)
- googleError(c, status, message)
+ status, errType, code, message := concurrencyErrorResponse(err, slotType)
+ googleErrorWithType(c, status, errType, code, message)
}
func writeUpstreamResponse(c *gin.Context, res *service.UpstreamHTTPResult) {
@@ -970,3 +1071,16 @@ func derefGroupID(groupID *int64) int64 {
}
return *groupID
}
+
+func servesCompositeAntigravityGemini(apiKey *service.APIKey, effectivePlatform string) bool {
+ return apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite && effectivePlatform == service.PlatformAntigravity
+}
+
+func isAntigravityGeminiModel(model string) bool {
+ trimmed := strings.ToLower(strings.TrimSpace(strings.TrimPrefix(model, "models/")))
+ if trimmed == "" || strings.HasPrefix(trimmed, "claude-") {
+ return false
+ }
+ detected, ok := service.DetectModelPlatform(trimmed)
+ return ok && detected == service.PlatformGemini
+}
diff --git a/backend/internal/handler/gemini_v1beta_handler_test.go b/backend/internal/handler/gemini_v1beta_handler_test.go
index 4f56085bd..fd11d4681 100644
--- a/backend/internal/handler/gemini_v1beta_handler_test.go
+++ b/backend/internal/handler/gemini_v1beta_handler_test.go
@@ -109,7 +109,7 @@ func TestGeminiV1BetaHandler_ListModelsAntigravityFallback(t *testing.T) {
expectedBehavior string
}{
{
- name: "有Gemini账户-调用ForwardAIStudioGET",
+ name: "有Gemini账户-调用ForwardListModels",
hasGeminiAccount: true,
hasAntigravity: false,
expectedBehavior: "forward_to_upstream",
@@ -155,7 +155,7 @@ func TestGeminiV1BetaHandler_GetModelAntigravityFallback(t *testing.T) {
expectedBehavior string
}{
{
- name: "有Gemini账户-调用ForwardAIStudioGET",
+ name: "有Gemini账户-调用ForwardGetModel",
hasGeminiAccount: true,
hasAntigravity: false,
expectedBehavior: "forward_to_upstream",
@@ -216,3 +216,75 @@ func TestShouldFallbackGeminiModel_DelegatesScopeFallback(t *testing.T) {
}
require.True(t, shouldFallbackGeminiModel("gemini-future-model", res))
}
+
+func TestGeminiV1BetaGetModel_CompositeAntigravityRoute(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ t.Run("composite route to antigravity gemini model succeeds", func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ req := httptest.NewRequest(http.MethodGet, "/v1beta/models/gemini-4-argon", nil)
+ req = req.WithContext(service.WithCompositeRouteDecision(req.Context(), service.CompositeRouteDecision{
+ Matched: true,
+ TargetPlatform: service.PlatformAntigravity,
+ UpstreamModel: "gemini-4-argon-high",
+ }))
+ c.Request = req
+ c.Params = gin.Params{{Key: "model", Value: "gemini-4-argon"}}
+ groupID := int64(4)
+ c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{
+ ID: 1,
+ GroupID: &groupID,
+ Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
+ })
+
+ (&GatewayHandler{}).GeminiV1BetaGetModel(c)
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ require.Contains(t, rec.Body.String(), "models/gemini-4-argon-high")
+ })
+
+ t.Run("composite route to antigravity claude model is rejected on v1beta", func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ req := httptest.NewRequest(http.MethodGet, "/v1beta/models/claude-sonnet-5-5-high", nil)
+ req = req.WithContext(service.WithCompositeRouteDecision(req.Context(), service.CompositeRouteDecision{
+ Matched: true,
+ TargetPlatform: service.PlatformAntigravity,
+ UpstreamModel: "claude-sonnet-5-5-high",
+ }))
+ c.Request = req
+ c.Params = gin.Params{{Key: "model", Value: "claude-sonnet-5-5-high"}}
+ groupID := int64(4)
+ c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{
+ ID: 1,
+ GroupID: &groupID,
+ Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
+ })
+
+ (&GatewayHandler{}).GeminiV1BetaGetModel(c)
+ require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
+ })
+
+ t.Run("composite route to antigravity claude model is rejected on generateContent", func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ req := httptest.NewRequest(http.MethodPost, "/v1beta/models/claude-sonnet-5-5-high:generateContent", nil)
+ req = req.WithContext(service.WithCompositeRouteDecision(req.Context(), service.CompositeRouteDecision{
+ Matched: true,
+ TargetPlatform: service.PlatformAntigravity,
+ UpstreamModel: "claude-sonnet-5-5-high",
+ }))
+ c.Request = req
+ c.Params = gin.Params{{Key: "modelAction", Value: "/claude-sonnet-5-5-high:generateContent"}}
+ groupID := int64(4)
+ c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{
+ ID: 1,
+ GroupID: &groupID,
+ Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
+ })
+ c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1})
+
+ (&GatewayHandler{}).GeminiV1BetaModels(c)
+ require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
+ })
+}
diff --git a/backend/internal/handler/gemini_vertex_models_test.go b/backend/internal/handler/gemini_vertex_models_test.go
new file mode 100644
index 000000000..db1c4e09d
--- /dev/null
+++ b/backend/internal/handler/gemini_vertex_models_test.go
@@ -0,0 +1,83 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/server/middleware"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type geminiVertexModelsTokenCache struct{}
+
+func (geminiVertexModelsTokenCache) GetAccessToken(context.Context, string) (string, error) {
+ return "ya29.vertex-token", nil
+}
+
+func (geminiVertexModelsTokenCache) SetAccessToken(context.Context, string, string, time.Duration) error {
+ return nil
+}
+
+func (geminiVertexModelsTokenCache) DeleteAccessToken(context.Context, string) error {
+ return nil
+}
+
+func (geminiVertexModelsTokenCache) AcquireRefreshLock(context.Context, string, time.Duration) (bool, error) {
+ return false, nil
+}
+
+func (geminiVertexModelsTokenCache) ReleaseRefreshLock(context.Context, string) error {
+ return nil
+}
+
+// 分组里只有 Agent Platform (Vertex) 服务账号时,模型列表与模型详情接口返回 Vertex 上的 Gemini 模型。
+func TestGeminiV1BetaModelsEndpoints_VertexServiceAccountOnlyGroup(t *testing.T) {
+ groupID := int64(8)
+ repo := &geminiAllowlistAccountRepoStub{gatewayModelsAccountRepoStub: gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{groupID: {{
+ ID: 18,
+ Platform: service.PlatformGemini,
+ Type: service.AccountTypeServiceAccount,
+ Credentials: map[string]any{
+ "location": "global",
+ "service_account_json": map[string]any{
+ "type": "service_account",
+ "project_id": "proj",
+ "private_key": "-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----\n",
+ "client_email": "svc@proj.iam.gserviceaccount.com",
+ },
+ },
+ }}}}}
+ upstream := &geminiMixedModelsUpstream{status: http.StatusOK, body: `{"publisherModels":[{"name":"publishers/google/models/gemini-3.8-flash"}]}`}
+ tokenProvider := service.NewGeminiTokenProvider(nil, geminiVertexModelsTokenCache{}, nil)
+ h := &GatewayHandler{geminiCompatService: service.NewGeminiMessagesCompatService(repo, nil, nil, nil, tokenProvider, nil, upstream, nil, &config.Config{})}
+ apiKey := &service.APIKey{GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: service.PlatformGemini}}
+
+ t.Run("list", func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models", nil)
+ c.Set(string(middleware.ContextKeyAPIKey), apiKey)
+
+ h.GeminiV1BetaListModels(c)
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ require.JSONEq(t, `{"models":[{"name":"models/gemini-3.8-flash","supportedGenerationMethods":["generateContent","streamGenerateContent"]}]}`, rec.Body.String())
+ })
+
+ t.Run("get", func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models/gemini-3.8-flash", nil)
+ c.Params = gin.Params{{Key: "model", Value: "gemini-3.8-flash"}}
+ c.Set(string(middleware.ContextKeyAPIKey), apiKey)
+
+ h.GeminiV1BetaGetModel(c)
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ require.JSONEq(t, `{"name":"models/gemini-3.8-flash","supportedGenerationMethods":["generateContent","streamGenerateContent"]}`, rec.Body.String())
+ })
+}
diff --git a/backend/internal/handler/group_localize_test.go b/backend/internal/handler/group_localize_test.go
new file mode 100644
index 000000000..1bb984c67
--- /dev/null
+++ b/backend/internal/handler/group_localize_test.go
@@ -0,0 +1,92 @@
+package handler
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/stretchr/testify/require"
+)
+
+func TestToLocalizedModelPlazaGroups(t *testing.T) {
+ visible := []service.PlazaGroup{
+ {
+ ID: 1, Name: "标准", Description: "号池", Platform: "anthropic",
+ I18n: service.GroupI18n{"en": {Name: "Standard", Description: "Pro + Max pool"}},
+ },
+ {ID: 2, Name: "无译文", Description: "原描述", Platform: "openai"},
+ }
+
+ english := toLocalizedModelPlazaGroups(visible, nil, "en")
+ require.Equal(t, "Standard", english[0].Name)
+ require.Equal(t, "Pro + Max pool", english[0].Description)
+ require.Equal(t, "无译文", english[1].Name)
+ require.Equal(t, "原描述", english[1].Description)
+
+ chinese := toLocalizedModelPlazaGroups(visible, nil, "zh")
+ require.Equal(t, "标准", chinese[0].Name)
+ require.Equal(t, "号池", chinese[0].Description)
+
+ // service 层对象不被改写,同一批分组可继续按别的语言输出
+ require.Equal(t, "标准", visible[0].Name)
+
+ raw, err := json.Marshal(english[0])
+ require.NoError(t, err)
+ var decoded map[string]any
+ require.NoError(t, json.Unmarshal(raw, &decoded))
+ require.NotContains(t, decoded, "i18n")
+}
+
+func TestLocalizeUserAvailableGroups(t *testing.T) {
+ refs := []service.AvailableGroupRef{
+ {ID: 1, Name: "标准", Platform: "anthropic", I18n: service.GroupI18n{"en": {Name: "Standard"}}},
+ {ID: 2, Name: "无译文", Platform: "anthropic"},
+ }
+ allowed := map[int64]struct{}{1: {}, 2: {}}
+
+ english := filterUserVisibleGroups(refs, allowed)
+ localizeUserAvailableGroups(english, "en")
+ require.Equal(t, "Standard", english[0].Name)
+ require.Equal(t, "无译文", english[1].Name)
+
+ chinese := filterUserVisibleGroups(refs, allowed)
+ localizeUserAvailableGroups(chinese, "zh")
+ require.Equal(t, "标准", chinese[0].Name)
+
+ raw, err := json.Marshal(english[0])
+ require.NoError(t, err)
+ var decoded map[string]any
+ require.NoError(t, json.Unmarshal(raw, &decoded))
+ require.NotContains(t, decoded, "i18n")
+}
+
+// 用户侧 handler 输出带分组的 DTO 时必须经过 Localized,否则分组名称与描述会
+// 停留在原字段,并把译文表原样带给用户。管理端(handler/admin)不在此列。
+func TestUserFacingGroupDTOsAreLocalized(t *testing.T) {
+ mapperCall := regexp.MustCompile(`dto\.(APIKey|UserSubscription|RedeemCode|UsageLog|Group)FromService[A-Za-z]*\(`)
+
+ files, err := filepath.Glob("*.go")
+ require.NoError(t, err)
+
+ checked := 0
+ for _, file := range files {
+ if strings.HasSuffix(file, "_test.go") {
+ continue
+ }
+ source, err := os.ReadFile(file)
+ require.NoError(t, err)
+ for i, line := range strings.Split(string(source), "\n") {
+ if !mapperCall.MatchString(line) {
+ continue
+ }
+ checked++
+ require.Containsf(t, line, ".Localized(",
+ "%s:%d outputs a group DTO without Localized(Accept-Language)", file, i+1)
+ }
+ }
+ require.NotZero(t, checked, "expected to find user-facing group DTO call sites")
+}
diff --git a/backend/internal/handler/model_plaza_handler.go b/backend/internal/handler/model_plaza_handler.go
index f4d42cde1..c7d2747d8 100644
--- a/backend/internal/handler/model_plaza_handler.go
+++ b/backend/internal/handler/model_plaza_handler.go
@@ -151,10 +151,10 @@ func (h *ModelPlazaHandler) Get(c *gin.Context) {
visible := filterPlazaVisibleGroups(groups, allowedGroups, restrictPublicGroups)
- out := make([]modelPlazaGroup, 0, len(visible))
- for i := range visible {
- out = append(out, toModelPlazaGroupDTO(&visible[i], userRates))
- }
+ // 广场可匿名访问,分组文案随请求语言变化,提示中间缓存按语言区分。
+ // 追加而非覆盖:CORS 中间件已为具体来源写入 Vary: Origin。
+ c.Writer.Header().Add("Vary", "Accept-Language")
+ out := toLocalizedModelPlazaGroups(visible, userRates, c.GetHeader("Accept-Language"))
response.Success(c, modelPlazaResponse{
Description: rt.Description,
Groups: out,
@@ -185,6 +185,17 @@ func filterPlazaVisibleGroups(
return visible
}
+// toLocalizedModelPlazaGroups 转换可见分组,并把名称与描述换成请求首选语言的版本。
+func toLocalizedModelPlazaGroups(visible []service.PlazaGroup, userRates map[int64]float64, acceptLanguage string) []modelPlazaGroup {
+ out := make([]modelPlazaGroup, 0, len(visible))
+ for i := range visible {
+ group := toModelPlazaGroupDTO(&visible[i], userRates)
+ group.Name, group.Description = visible[i].I18n.Localize(acceptLanguage, group.Name, group.Description)
+ out = append(out, group)
+ }
+ return out
+}
+
// toModelPlazaGroupDTO 将 service 层广场分组映射为白名单 DTO,并合并用户专属倍率。
func toModelPlazaGroupDTO(g *service.PlazaGroup, userRates map[int64]float64) modelPlazaGroup {
models := make([]modelPlazaModel, 0, len(g.Models))
diff --git a/backend/internal/handler/model_plaza_handler_test.go b/backend/internal/handler/model_plaza_handler_test.go
index 0a164fd11..1df199faa 100644
--- a/backend/internal/handler/model_plaza_handler_test.go
+++ b/backend/internal/handler/model_plaza_handler_test.go
@@ -3,11 +3,14 @@
package handler
import (
+ "context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/server/middleware"
"github.com/MACOS-DO/sub4api/internal/service"
"github.com/gin-gonic/gin"
@@ -262,3 +265,43 @@ func TestFilterPlazaVisibleGroups_SubscribedExclusiveGroup(t *testing.T) {
require.Equal(t, int64(42), visible[0].ID)
}
}
+
+type plazaVarySettingRepo struct{ service.SettingRepository }
+
+func (plazaVarySettingRepo) GetMultiple(context.Context, []string) (map[string]string, error) {
+ return map[string]string{service.SettingKeyModelPlazaEnabled: "true"}, nil
+}
+
+type plazaVaryChannelRepo struct{ service.ChannelRepository }
+
+func (plazaVaryChannelRepo) ListAll(context.Context) ([]service.Channel, error) { return nil, nil }
+
+type plazaVaryGroupRepo struct{ service.GroupRepository }
+
+func (plazaVaryGroupRepo) ListActive(context.Context) ([]service.Group, error) { return nil, nil }
+
+func TestModelPlazaHandler_VaryKeepsCORSOrigin(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ h := NewModelPlazaHandler(
+ service.NewModelPlazaService(plazaVaryChannelRepo{}, plazaVaryGroupRepo{}, nil, nil, nil),
+ nil,
+ service.NewSettingService(plazaVarySettingRepo{}, &config.Config{}),
+ )
+ r := gin.New()
+ r.Use(middleware.CORS(config.CORSConfig{AllowedOrigins: []string{"https://a.example", "https://b.example"}}))
+ r.GET("/api/v1/model-plaza", h.Get)
+
+ for _, origin := range []string{"https://a.example", "https://b.example"} {
+ req := httptest.NewRequest(http.MethodGet, "/api/v1/model-plaza", nil)
+ req.Header.Set("Origin", origin)
+ req.Header.Set("Accept-Language", "en")
+ w := httptest.NewRecorder()
+
+ r.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusOK, w.Code, w.Body.String())
+ require.Equal(t, origin, w.Header().Get("Access-Control-Allow-Origin"))
+ // 共享缓存需同时按来源与语言区分,否则 A 来源的响应可能被复用给 B。
+ require.Equal(t, []string{"Origin", "Accept-Language"}, w.Header().Values("Vary"))
+ }
+}
diff --git a/backend/internal/handler/no_account_error.go b/backend/internal/handler/no_account_error.go
index 5f2002f7b..021b54630 100644
--- a/backend/internal/handler/no_account_error.go
+++ b/backend/internal/handler/no_account_error.go
@@ -123,10 +123,14 @@ func classifyNoAccountError(
result := diag.DiagnoseModelAvailabilityForPlatform(ctx, apiKey.GroupID, routingModel, platform)
if result.HasAccountsInPool && !result.HasModelSupport {
+ message := fmt.Sprintf("Model %q is not supported by any configured account in this group", displayModel)
+ if result.HasRetiredSubscriptionModel {
+ message = fmt.Sprintf("Model %q targets GPT-5.5, which retired from Codex with ChatGPT sign-in on October 14, 2026. Select an available replacement such as GPT-6.1 Sol or GPT-6 Luna, or configure an API-key upstream that supports GPT-5.5.", displayModel)
+ }
return noAccountErrorClassification{
Status: http.StatusNotFound,
ErrType: "model_not_found",
- Message: fmt.Sprintf("Model %q is not supported by any configured account in this group", displayModel),
+ Message: message,
ModelNotFound: true,
}
}
diff --git a/backend/internal/handler/no_account_error_test.go b/backend/internal/handler/no_account_error_test.go
index 6ff37fda0..6f8188f75 100644
--- a/backend/internal/handler/no_account_error_test.go
+++ b/backend/internal/handler/no_account_error_test.go
@@ -303,3 +303,22 @@ func TestClassifySelectionFailureError_StillUpgradesNonModelNotFoundFallback(t *
require.Equal(t, "rate_limit_error", got.ErrType)
require.False(t, got.ModelNotFound)
}
+
+func TestClassifyNoAccountError_GPT55Retirement(t *testing.T) {
+ groupID := int64(1)
+ apiKey := &service.APIKey{GroupID: &groupID}
+ fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasRetiredSubscriptionModel: true}}
+ cls := classifyNoAccountError(context.Background(), fd, apiKey, "gpt-5.5", "legacy", service.PlatformOpenAI)
+ require.Equal(t, http.StatusNotFound, cls.Status)
+ require.Equal(t, "model_not_found", cls.ErrType)
+ require.Contains(t, cls.Message, "retired")
+ require.Contains(t, cls.Message, "API-key")
+ fd.resp.HasModelSupport = true
+ cls = classifyNoAccountError(context.Background(), fd, apiKey, "gpt-5.5", "legacy", service.PlatformOpenAI)
+ require.Equal(t, http.StatusServiceUnavailable, cls.Status, "a temporarily unavailable API pool is not a retirement error")
+}
+
+func TestGPT55RetirementEmptyListingDoesNotUseDefaults(t *testing.T) {
+ require.Empty(t, modelListingSource(service.PlatformOpenAI, []string{}, []string{"gpt-5.5"}))
+ require.Equal(t, []string{"gpt-5.5"}, modelListingSource(service.PlatformOpenAI, nil, []string{"gpt-5.5"}))
+}
diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go
index 8e5506a87..13ef4157e 100644
--- a/backend/internal/handler/openai_gateway_handler.go
+++ b/backend/internal/handler/openai_gateway_handler.go
@@ -2558,6 +2558,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "Failed to resolve composite model route")
return
}
+ if decision.OAuthAmbiguous() {
+ service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
+ closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, decision.AmbiguousMessage())
+ return
+ }
if decision.Matched {
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
wsRouteModel = decision.UpstreamModel
diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go
index 719f36315..1a20c1990 100644
--- a/backend/internal/handler/ops_error_logger.go
+++ b/backend/internal/handler/ops_error_logger.go
@@ -1183,6 +1183,14 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
}
}
+ // Google 格式错误体没有 type 字段:按网关回写时登记的错误类型补齐。
+ if errType, code := service.OpsLocalErrorType(c); errType != "" && !parsed.StreamFailure &&
+ (parsed.ErrorType == "" || parsed.ErrorType == "api_error") {
+ parsed.ErrorType = errType
+ if code != "" {
+ parsed.Code = code
+ }
+ }
normalizedType := normalizeOpsErrorType(parsed.ErrorType, parsed.Code)
phase, isBusinessLimited, errorOwner, errorSource := classifyOpsErrorLog(c, normalizedType, parsed.Message, parsed.Code, status)
@@ -2214,6 +2222,11 @@ func classifyOpsSeverity(errType string, status int) string {
func classifyOpsErrorLog(c *gin.Context, errType, message, code string, status int) (phase string, isBusinessLimited bool, errorOwner string, errorSource string) {
phase = classifyOpsPhase(errType, message, code)
+ if service.IsOpsRequestScopedError(c) {
+ // 失败由请求内容决定:只按错误类型分类,上游错误上下文不参与归因。
+ isBusinessLimited = classifyOpsIsBusinessLimited(errType, phase, code, status, message)
+ return phase, isBusinessLimited, classifyOpsErrorOwner(phase, message), classifyOpsErrorSource(phase, message)
+ }
routingCapacityLimited := isOpsRoutingCapacityLimited(c)
clientBusinessLimited := service.HasOpsClientBusinessLimited(c)
localModelConfiguration := clientBusinessLimited && service.OpsClientBusinessLimitedReason(c) == service.OpsClientBusinessLimitedReasonLocalModelConfiguration
diff --git a/backend/internal/handler/ops_error_logger_google_test.go b/backend/internal/handler/ops_error_logger_google_test.go
new file mode 100644
index 000000000..f82758229
--- /dev/null
+++ b/backend/internal/handler/ops_error_logger_google_test.go
@@ -0,0 +1,135 @@
+package handler
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+// recordGoogleFormatOpsError 让 handle 以 Google 错误格式回写错误,返回 ops 中间件记录的错误日志。
+func recordGoogleFormatOpsError(t *testing.T, handle gin.HandlerFunc) *service.OpsInsertErrorLogInput {
+ t.Helper()
+ setupOpsErrorLogTestQueue(t, 1)
+ gin.SetMode(gin.TestMode)
+ ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ router := gin.New()
+ router.Use(OpsErrorLoggerMiddleware(ops))
+ router.POST("/v1beta/cachedContents", handle)
+
+ router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/v1beta/cachedContents", nil))
+
+ require.Equal(t, int64(1), OpsErrorLogQueueLength())
+ return (<-opsErrorLogQueue).entry
+}
+
+func TestOpsErrorLoggerMiddleware_GoogleClientErrorsClassifiedAsClient(t *testing.T) {
+ for _, tc := range []struct {
+ status int
+ errType string
+ phase string
+ }{
+ {status: http.StatusBadRequest, errType: "invalid_request_error", phase: "request"},
+ {status: http.StatusRequestEntityTooLarge, errType: "invalid_request_error", phase: "request"},
+ {status: http.StatusUnauthorized, errType: "authentication_error", phase: "auth"},
+ {status: http.StatusForbidden, errType: "permission_error", phase: "request"},
+ {status: http.StatusNotFound, errType: "not_found_error", phase: "request"},
+ } {
+ t.Run(http.StatusText(tc.status), func(t *testing.T) {
+ entry := recordGoogleFormatOpsError(t, func(c *gin.Context) {
+ googleError(c, tc.status, "client request problem")
+ })
+ require.Equal(t, tc.status, entry.StatusCode)
+ require.Equal(t, tc.errType, entry.ErrorType)
+ require.Equal(t, tc.phase, entry.ErrorPhase)
+ require.Equal(t, "client", entry.ErrorOwner)
+ require.Equal(t, "client_request", entry.ErrorSource)
+ require.Equal(t, "P3", entry.Severity)
+ })
+ }
+}
+
+func TestOpsErrorLoggerMiddleware_GooglePlatformErrorStaysPlatform(t *testing.T) {
+ entry := recordGoogleFormatOpsError(t, func(c *gin.Context) {
+ googlePlatformError(c, http.StatusBadRequest, "Explicit context caching is not available for model m: storage pricing is not configured")
+ })
+ require.Equal(t, "api_error", entry.ErrorType)
+ require.Equal(t, "internal", entry.ErrorPhase)
+ require.Equal(t, "platform", entry.ErrorOwner)
+ require.Equal(t, "gateway", entry.ErrorSource)
+}
+
+func TestOpsErrorLoggerMiddleware_GoogleServerErrorsNotTypedByStatus(t *testing.T) {
+ entry := recordGoogleFormatOpsError(t, func(c *gin.Context) {
+ googleError(c, http.StatusInternalServerError, "Failed to persist cached content")
+ })
+ require.Equal(t, "api_error", entry.ErrorType)
+ require.Equal(t, "platform", entry.ErrorOwner)
+}
+
+func TestOpsErrorLoggerMiddleware_GoogleBillingErrorMatchesClaudeFormat(t *testing.T) {
+ entry := recordGoogleFormatOpsError(t, func(c *gin.Context) {
+ status, code, message, _ := billingErrorDetails(service.ErrInsufficientBalance)
+ googleErrorWithType(c, status, code, "", message)
+ })
+ require.Equal(t, "billing_error", entry.ErrorType)
+ require.Equal(t, "request", entry.ErrorPhase)
+ require.Equal(t, "client", entry.ErrorOwner)
+ require.True(t, entry.IsBusinessLimited)
+}
+
+func TestOpsErrorLoggerMiddleware_GoogleConcurrencyErrorClassifiedAsRequest(t *testing.T) {
+ entry := recordGoogleFormatOpsError(t, func(c *gin.Context) {
+ googleConcurrencyError(c, &ConcurrencyError{SlotType: "user"}, "user")
+ })
+ require.Equal(t, http.StatusTooManyRequests, entry.StatusCode)
+ require.Equal(t, "rate_limit_error", entry.ErrorType)
+ require.Equal(t, "request", entry.ErrorPhase)
+ require.Equal(t, "client", entry.ErrorOwner)
+}
+
+func TestOpsErrorLoggerMiddleware_GoogleErrorAfterUpstreamFailureKeepsUpstreamAttribution(t *testing.T) {
+ entry := recordGoogleFormatOpsError(t, func(c *gin.Context) {
+ service.SetOpsUpstreamError(c, http.StatusBadRequest, "upstream rejected", "")
+ googleError(c, http.StatusBadRequest, "upstream rejected")
+ })
+ require.Equal(t, "upstream", entry.ErrorPhase)
+ require.Equal(t, "provider", entry.ErrorOwner)
+ require.Equal(t, "upstream_http", entry.ErrorSource)
+}
+
+func TestOpsErrorLoggerMiddleware_RequestScopedUpstreamErrorClassifiedAsClient(t *testing.T) {
+ entry := recordGoogleFormatOpsError(t, func(c *gin.Context) {
+ service.SetOpsUpstreamError(c, http.StatusBadRequest, "Invalid resource state for cache content 8079767076522164224.", "")
+ c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{{
+ Platform: service.PlatformGemini, AccountID: 173, UpstreamStatusCode: http.StatusBadRequest, Kind: "http_error",
+ Message: "Invalid resource state for cache content 8079767076522164224.",
+ }})
+ service.MarkOpsRequestScopedError(c, "permission_error")
+ c.Data(http.StatusForbidden, "application/json", []byte(service.GeminiCachedContentNotFoundResponse))
+ })
+ require.Equal(t, http.StatusForbidden, entry.StatusCode)
+ require.Equal(t, "permission_error", entry.ErrorType)
+ require.Equal(t, "request", entry.ErrorPhase)
+ require.Equal(t, "client", entry.ErrorOwner)
+ require.Equal(t, "client_request", entry.ErrorSource)
+ require.False(t, entry.IsBusinessLimited)
+ require.NotNil(t, entry.UpstreamStatusCode, "上游原始错误保留为明细")
+ require.Equal(t, http.StatusBadRequest, *entry.UpstreamStatusCode)
+}
+
+func TestSetOpsLocalErrorTypeClearsRequestScopedMark(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ service.MarkOpsRequestScopedError(c, "permission_error")
+ require.True(t, service.IsOpsRequestScopedError(c))
+
+ service.SetOpsLocalErrorType(c, "", "")
+ require.False(t, service.IsOpsRequestScopedError(c))
+ errType, code := service.OpsLocalErrorType(c)
+ require.Empty(t, errType)
+ require.Empty(t, code)
+}
diff --git a/backend/internal/handler/payment_handler.go b/backend/internal/handler/payment_handler.go
index 9c361f4f8..ddfdadde2 100644
--- a/backend/internal/handler/payment_handler.go
+++ b/backend/internal/handler/payment_handler.go
@@ -78,7 +78,7 @@ func (h *PaymentHandler) GetPlans(c *gin.Context) {
gi := groupInfo[p.GroupID]
result = append(result, planWithPlatform{
ID: int64(p.ID), GroupID: p.GroupID,
- GroupPlatform: gi.Platform, GroupName: gi.Name,
+ GroupPlatform: gi.Platform, GroupName: gi.I18n.LocalizeName(c.GetHeader("Accept-Language"), gi.Name),
RateMultiplier: gi.RateMultiplier, PeakRateEnabled: gi.PeakRateEnabled,
PeakStart: gi.PeakStart, PeakEnd: gi.PeakEnd, PeakRateMultiplier: gi.PeakRateMultiplier,
Name: p.Name, Description: p.Description, Price: p.Price, OriginalPrice: p.OriginalPrice,
@@ -126,7 +126,7 @@ func (h *PaymentHandler) GetCheckoutInfo(c *gin.Context) {
gi := groupInfo[p.GroupID]
planList = append(planList, checkoutPlan{
ID: int64(p.ID), GroupID: p.GroupID,
- GroupPlatform: gi.Platform, GroupName: gi.Name,
+ GroupPlatform: gi.Platform, GroupName: gi.I18n.LocalizeName(c.GetHeader("Accept-Language"), gi.Name),
RateMultiplier: gi.RateMultiplier,
PeakRateEnabled: gi.PeakRateEnabled, PeakStart: gi.PeakStart,
PeakEnd: gi.PeakEnd, PeakRateMultiplier: gi.PeakRateMultiplier,
diff --git a/backend/internal/handler/payment_webhook_handler.go b/backend/internal/handler/payment_webhook_handler.go
index 9706930c2..522cedf74 100644
--- a/backend/internal/handler/payment_webhook_handler.go
+++ b/backend/internal/handler/payment_webhook_handler.go
@@ -103,7 +103,7 @@ func (h *PaymentWebhookHandler) handleNotify(c *gin.Context, providerKey string)
headers[strings.ToLower(k)] = c.GetHeader(k)
}
- resolvedProviderKey, notification, err := verifyNotificationWithProviders(c.Request.Context(), providers, rawBody, headers)
+ verifiedProvider, notification, err := verifyNotificationWithProviders(c.Request.Context(), providers, rawBody, headers)
if err != nil {
truncatedBody := rawBody
if len(truncatedBody) > webhookLogTruncateLen {
@@ -115,12 +115,20 @@ func (h *PaymentWebhookHandler) handleNotify(c *gin.Context, providerKey string)
return
}
+ resolvedProviderKey := verifiedProvider.ProviderKey()
+
// nil notification means irrelevant event (e.g. Stripe non-payment event); return success.
if notification == nil {
writeSuccessResponse(c, resolvedProviderKey)
return
}
+ if err := h.paymentService.ConfirmNotificationUpstream(c.Request.Context(), verifiedProvider, notification); err != nil {
+ slog.Error("[Payment Webhook] upstream confirmation failed", "provider", resolvedProviderKey, "outTradeNo", notification.OrderID, "tradeNo", notification.TradeNo, "error", err)
+ c.String(http.StatusBadGateway, "confirm failed")
+ return
+ }
+
if err := h.paymentService.HandlePaymentNotification(c.Request.Context(), notification, resolvedProviderKey); err != nil {
// Unknown order: ack with 2xx so the provider stops retrying. This
// guards against foreign environments whose webhook endpoints are
@@ -170,7 +178,10 @@ func extractOutTradeNo(rawBody, providerKey string) string {
return ""
}
-func verifyNotificationWithProviders(ctx context.Context, providers []payment.Provider, rawBody string, headers map[string]string) (string, *payment.PaymentNotification, error) {
+// verifyNotificationWithProviders returns the provider instance that verified
+// the notification so later steps (upstream confirmation) use the same
+// merchant configuration.
+func verifyNotificationWithProviders(ctx context.Context, providers []payment.Provider, rawBody string, headers map[string]string) (payment.Provider, *payment.PaymentNotification, error) {
var lastErr error
for _, provider := range providers {
if provider == nil {
@@ -181,12 +192,12 @@ func verifyNotificationWithProviders(ctx context.Context, providers []payment.Pr
lastErr = err
continue
}
- return provider.ProviderKey(), notification, nil
+ return provider, notification, nil
}
if lastErr != nil {
- return "", nil, lastErr
+ return nil, nil, lastErr
}
- return "", nil, fmt.Errorf("no webhook provider could verify notification")
+ return nil, nil, fmt.Errorf("no webhook provider could verify notification")
}
// wxpaySuccessResponse is the JSON response expected by WeChat Pay webhook.
diff --git a/backend/internal/handler/payment_webhook_handler_test.go b/backend/internal/handler/payment_webhook_handler_test.go
index 477bc0c7c..18115d331 100644
--- a/backend/internal/handler/payment_webhook_handler_test.go
+++ b/backend/internal/handler/payment_webhook_handler_test.go
@@ -204,9 +204,9 @@ func TestVerifyNotificationWithProvidersReturnsMatchedProvider(t *testing.T) {
},
}
- providerKey, notification, err := verifyNotificationWithProviders(context.Background(), providers, "{}", map[string]string{"wechatpay-signature": "sig"})
+ provider, notification, err := verifyNotificationWithProviders(context.Background(), providers, "{}", map[string]string{"wechatpay-signature": "sig"})
require.NoError(t, err)
- require.Equal(t, payment.TypeWxpay, providerKey)
+ require.Equal(t, payment.TypeWxpay, provider.ProviderKey())
require.NotNil(t, notification)
require.Equal(t, "sub2_42", notification.OrderID)
}
diff --git a/backend/internal/handler/redeem_handler.go b/backend/internal/handler/redeem_handler.go
index 4255c912c..a28d6d6a5 100644
--- a/backend/internal/handler/redeem_handler.go
+++ b/backend/internal/handler/redeem_handler.go
@@ -59,7 +59,7 @@ func (h *RedeemHandler) Redeem(c *gin.Context) {
return
}
- response.Success(c, dto.RedeemCodeFromService(result))
+ response.Success(c, dto.RedeemCodeFromService(result).Localized(c.GetHeader("Accept-Language")))
}
// GetHistory returns the user's redemption history
@@ -98,7 +98,7 @@ func (h *RedeemHandler) GetHistory(c *gin.Context) {
}
out := make([]dto.RedeemCode, 0, len(codes))
for i := range codes {
- out = append(out, *dto.RedeemCodeFromService(&codes[i]))
+ out = append(out, *dto.RedeemCodeFromService(&codes[i]).Localized(c.GetHeader("Accept-Language")))
}
response.Paginated(c, out, result.Total, page, pageSize)
return
@@ -115,7 +115,7 @@ func (h *RedeemHandler) GetHistory(c *gin.Context) {
out := make([]dto.RedeemCode, 0, len(codes))
for i := range codes {
- out = append(out, *dto.RedeemCodeFromService(&codes[i]))
+ out = append(out, *dto.RedeemCodeFromService(&codes[i]).Localized(c.GetHeader("Accept-Language")))
}
response.Success(c, out)
}
diff --git a/backend/internal/handler/security_audit_errors.go b/backend/internal/handler/security_audit_errors.go
index bf1c53e0b..3c1ef424a 100644
--- a/backend/internal/handler/security_audit_errors.go
+++ b/backend/internal/handler/security_audit_errors.go
@@ -100,9 +100,14 @@ func googleSecurityAuditError(c *gin.Context, decision *securityaudit.Decision)
return
}
if decision.Legacy != nil && decision.Legacy.Blocked {
- googleError(c, securityAuditStatus(decision), securityAuditMessage(decision))
+ googleErrorWithType(c, securityAuditStatus(decision), securityAuditErrorCode(decision), "", securityAuditMessage(decision))
return
}
+ errType := "api_error"
+ if decision.Kind == securityaudit.DecisionBlock {
+ errType = "permission_error"
+ }
+ service.SetOpsLocalErrorType(c, errType, securityAuditErrorCode(decision))
status := securityAuditStatus(decision)
googleStatus := googleapi.HTTPStatusToGoogleStatus(status)
if status == http.StatusServiceUnavailable {
diff --git a/backend/internal/handler/security_audit_order_test.go b/backend/internal/handler/security_audit_order_test.go
index e9cb4e1f9..2e0182930 100644
--- a/backend/internal/handler/security_audit_order_test.go
+++ b/backend/internal/handler/security_audit_order_test.go
@@ -24,6 +24,7 @@ func TestPromptAuditGatePrecedesAccountBillingAndUpstreamSideEffects(t *testing.
{file: "gateway_handler_chat_completions.go", function: "ChatCompletions", auditToken: "checkSecurityAudit"},
{file: "gateway_handler_responses.go", function: "Responses", auditToken: "checkSecurityAudit"},
{file: "gemini_v1beta_handler.go", function: "GeminiV1BetaModels", auditToken: "checkSecurityAudit"},
+ {file: "gemini_cached_contents_handler.go", function: "GeminiCachedContentsCreate", auditToken: "checkSecurityAudit"},
{file: "openai_gateway_handler.go", function: "Responses", auditToken: "checkSecurityAudit"},
{file: "openai_gateway_handler.go", function: "Messages", auditToken: "checkSecurityAudit"},
{file: "openai_chat_completions.go", function: "ChatCompletions", auditToken: "checkSecurityAudit"},
diff --git a/backend/internal/handler/subscription_handler.go b/backend/internal/handler/subscription_handler.go
index f0fe68126..8275b31a7 100644
--- a/backend/internal/handler/subscription_handler.go
+++ b/backend/internal/handler/subscription_handler.go
@@ -59,7 +59,7 @@ func (h *SubscriptionHandler) List(c *gin.Context) {
out := make([]dto.UserSubscription, 0, len(subscriptions))
for i := range subscriptions {
- out = append(out, *dto.UserSubscriptionFromService(&subscriptions[i]))
+ out = append(out, *dto.UserSubscriptionFromService(&subscriptions[i]).Localized(c.GetHeader("Accept-Language")))
}
response.Success(c, out)
}
@@ -81,7 +81,7 @@ func (h *SubscriptionHandler) GetActive(c *gin.Context) {
out := make([]dto.UserSubscription, 0, len(subscriptions))
for i := range subscriptions {
- out = append(out, *dto.UserSubscriptionFromService(&subscriptions[i]))
+ out = append(out, *dto.UserSubscriptionFromService(&subscriptions[i]).Localized(c.GetHeader("Accept-Language")))
}
response.Success(c, out)
}
@@ -110,8 +110,11 @@ func (h *SubscriptionHandler) GetProgress(c *gin.Context) {
// Skip subscriptions with errors
continue
}
+ if sub.Group != nil {
+ progress.GroupName = sub.Group.I18n.LocalizeName(c.GetHeader("Accept-Language"), progress.GroupName)
+ }
result = append(result, SubscriptionProgressInfo{
- Subscription: dto.UserSubscriptionFromService(sub),
+ Subscription: dto.UserSubscriptionFromService(sub).Localized(c.GetHeader("Accept-Language")),
Progress: progress,
})
}
@@ -150,7 +153,7 @@ func (h *SubscriptionHandler) GetSummary(c *gin.Context) {
// Add group info if preloaded
if sub.Group != nil {
- item.GroupName = sub.Group.Name
+ item.GroupName = sub.Group.I18n.LocalizeName(c.GetHeader("Accept-Language"), sub.Group.Name)
if sub.Group.DailyLimitUSD != nil {
item.DailyLimitUSD = *sub.Group.DailyLimitUSD
}
diff --git a/backend/internal/handler/usage_handler.go b/backend/internal/handler/usage_handler.go
index f6c1a67c0..e3a2db812 100644
--- a/backend/internal/handler/usage_handler.go
+++ b/backend/internal/handler/usage_handler.go
@@ -254,7 +254,7 @@ func (h *UsageHandler) List(c *gin.Context) {
out := make([]dto.UsageLog, 0, len(records))
for i := range records {
- out = append(out, *dto.UsageLogFromService(&records[i]))
+ out = append(out, *dto.UsageLogFromService(&records[i]).Localized(c.GetHeader("Accept-Language")))
}
response.Paginated(c, out, result.Total, page, pageSize)
}
@@ -400,7 +400,7 @@ func (h *UsageHandler) GetByID(c *gin.Context) {
return
}
- response.Success(c, dto.UsageLogFromService(record))
+ response.Success(c, dto.UsageLogFromService(record).Localized(c.GetHeader("Accept-Language")))
}
// Stats handles getting usage statistics
diff --git a/backend/internal/handler/wire.go b/backend/internal/handler/wire.go
index e741a06f7..4c49e1f35 100644
--- a/backend/internal/handler/wire.go
+++ b/backend/internal/handler/wire.go
@@ -118,11 +118,13 @@ func ProvideGatewayHandler(
cfg *config.Config,
settingService *service.SettingService,
coordinator *securityaudit.Coordinator,
+ geminiCachedContentService *service.GeminiCachedContentService,
) *GatewayHandler {
h := NewGatewayHandler(gatewayService, openAIGatewayService, geminiCompatService, antigravityGatewayService,
userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool,
errorPassthroughService, contentModerationService, userMsgQueueService, cfg, settingService)
h.securityAuditCoordinator = coordinator
+ h.geminiCachedContentService = geminiCachedContentService
return h
}
diff --git a/backend/internal/payment/provider/alipay.go b/backend/internal/payment/provider/alipay.go
index 8ea4abb7b..d0e106707 100644
--- a/backend/internal/payment/provider/alipay.go
+++ b/backend/internal/payment/provider/alipay.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/MACOS-DO/sub4api/internal/payment"
+ infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
"github.com/smartwalle/alipay/v3"
)
@@ -24,7 +25,10 @@ const (
const (
alipayFundChangeYes = "Y"
alipayErrTradeNotExist = "ACQ.TRADE_NOT_EXIST"
- alipayRefundSuffix = "-refund"
+ alipayRefundStatusSucc = "REFUND_SUCCESS"
+ alipayRefundRequestSep = "-refund-"
+ // 支付宝提示退款发起后过早查询可能查不到、之后又处理成功;超过该时长仍无记录才判定失败。
+ alipayRefundQueryNotFoundGrace = 10 * time.Minute
)
var (
@@ -37,6 +41,12 @@ var (
alipayTradePagePay = func(client *alipay.Client, param alipay.TradePagePay) (*url.URL, error) {
return client.TradePagePay(param)
}
+ alipayTradeRefund = func(ctx context.Context, client *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
+ return client.TradeRefund(ctx, param)
+ }
+ alipayTradeFastPayRefundQuery = func(ctx context.Context, client *alipay.Client, param alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) {
+ return client.TradeFastPayRefundQuery(ctx, param)
+ }
)
// Alipay implements payment.Provider and payment.CancelableProvider using the smartwalle/alipay SDK.
@@ -338,32 +348,76 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
return nil, err
}
- result, err := client.TradeRefund(ctx, alipay.TradeRefund{
+ outRequestNo := fmt.Sprintf("%s%s%d", req.OrderID, alipayRefundRequestSep, time.Now().UnixNano())
+ result, err := alipayTradeRefund(ctx, client, alipay.TradeRefund{
OutTradeNo: req.OrderID,
RefundAmount: req.Amount,
RefundReason: req.Reason,
- OutRequestNo: fmt.Sprintf("%s-refund-%d", req.OrderID, time.Now().UnixNano()),
+ OutRequestNo: outRequestNo,
})
if err != nil {
return nil, fmt.Errorf("alipay TradeRefund: %w", err)
}
+ if result == nil {
+ return nil, fmt.Errorf("alipay TradeRefund: empty response")
+ }
refundStatus := payment.ProviderStatusPending
if result.FundChange == alipayFundChangeYes {
refundStatus = payment.ProviderStatusSuccess
}
- refundID := result.TradeNo
- if refundID == "" {
- refundID = req.OrderID + alipayRefundSuffix
- }
-
+ // fund_change != Y 时需凭退款请求号查询终态,因此 RefundID 记录 out_request_no。
return &payment.RefundResponse{
- RefundID: refundID,
+ RefundID: outRequestNo,
Status: refundStatus,
}, nil
}
+// QueryRefund 通过 alipay.trade.fastpay.refund.query 查询退款终态。refund_status 为 REFUND_SUCCESS
+// 表示成功;退款发起超过宽限期仍查不到记录表示支付宝未受理或退款失败;其余情况视为仍在处理中。
+func (a *Alipay) QueryRefund(ctx context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) {
+ orderID := strings.TrimSpace(req.OrderID)
+ outRequestNo := strings.TrimSpace(req.RefundID)
+ // 旧版本把支付宝交易号记为 RefundID,无法据此查询退款请求,只能人工核实。
+ if orderID == "" || !strings.HasPrefix(outRequestNo, orderID+alipayRefundRequestSep) {
+ return nil, infraerrors.BadRequest("REFUND_QUERY_UNSUPPORTED", "this refund was issued without a queryable refund request number; please verify manually")
+ }
+ client, err := a.getClient()
+ if err != nil {
+ return nil, err
+ }
+ result, err := alipayTradeFastPayRefundQuery(ctx, client, alipay.TradeFastPayRefundQuery{
+ OutTradeNo: orderID,
+ OutRequestNo: outRequestNo,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("alipay query refund: %w", err)
+ }
+ if result == nil {
+ return nil, fmt.Errorf("alipay query refund: empty response")
+ }
+ // SDK 对带签名的业务失败响应(如 ACQ.SYSTEM_ERROR)不返回 error,字段为空;
+ // 不检查错误码会被误判为"无退款记录"而失败收尾。
+ if result.IsFailure() {
+ return nil, fmt.Errorf("alipay query refund: %w", result.Error)
+ }
+
+ status := payment.ProviderStatusPending
+ switch {
+ case strings.TrimSpace(result.RefundStatus) == alipayRefundStatusSucc:
+ status = payment.ProviderStatusSuccess
+ case strings.TrimSpace(result.OutRequestNo) == "" && strings.TrimSpace(result.RefundAmount) == "" &&
+ alipayRefundAbsenceIsFinal(req.RequestedAt, time.Now()):
+ status = payment.ProviderStatusFailed
+ }
+ return &payment.RefundResponse{RefundID: outRequestNo, Status: status}, nil
+}
+
+func alipayRefundAbsenceIsFinal(requestedAt, now time.Time) bool {
+ return !requestedAt.IsZero() && now.Sub(requestedAt) >= alipayRefundQueryNotFoundGrace
+}
+
// CancelPayment closes a pending trade on Alipay.
func (a *Alipay) CancelPayment(ctx context.Context, tradeNo string) error {
client, err := a.getClient()
@@ -406,5 +460,6 @@ func parseAlipayAmount(values ...string) (float64, error) {
var (
_ payment.Provider = (*Alipay)(nil)
_ payment.CancelableProvider = (*Alipay)(nil)
+ _ payment.RefundQueryProvider = (*Alipay)(nil)
_ payment.MerchantIdentityProvider = (*Alipay)(nil)
)
diff --git a/backend/internal/payment/provider/alipay_test.go b/backend/internal/payment/provider/alipay_test.go
index 2ebeef72d..865f3aa63 100644
--- a/backend/internal/payment/provider/alipay_test.go
+++ b/backend/internal/payment/provider/alipay_test.go
@@ -8,6 +8,7 @@ import (
"net/url"
"strings"
"testing"
+ "time"
"github.com/MACOS-DO/sub4api/internal/payment"
"github.com/smartwalle/alipay/v3"
@@ -444,3 +445,129 @@ func TestParseAlipayAmount(t *testing.T) {
t.Fatal("expected error when no valid amount field exists")
}
}
+
+func TestAlipayRefundRecordsOutRequestNoAsRefundID(t *testing.T) {
+ origRefund := alipayTradeRefund
+ t.Cleanup(func() { alipayTradeRefund = origRefund })
+
+ for _, tc := range []struct {
+ fundChange string
+ wantStatus string
+ }{
+ {fundChange: alipayFundChangeYes, wantStatus: payment.ProviderStatusSuccess},
+ {fundChange: "N", wantStatus: payment.ProviderStatusPending},
+ } {
+ var gotOutRequestNo string
+ alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
+ if param.OutTradeNo != "sub2_7" || param.RefundAmount != "12.50" {
+ t.Fatalf("unexpected refund param: %+v", param)
+ }
+ gotOutRequestNo = param.OutRequestNo
+ return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: tc.fundChange}, nil
+ }
+
+ provider := &Alipay{client: &alipay.Client{}}
+ resp, err := provider.Refund(context.Background(), payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"})
+ if err != nil {
+ t.Fatalf("Refund() error = %v", err)
+ }
+ if resp.Status != tc.wantStatus {
+ t.Fatalf("fund_change=%s status = %q, want %q", tc.fundChange, resp.Status, tc.wantStatus)
+ }
+ if !strings.HasPrefix(gotOutRequestNo, "sub2_7-refund-") || resp.RefundID != gotOutRequestNo {
+ t.Fatalf("RefundID = %q, out_request_no = %q", resp.RefundID, gotOutRequestNo)
+ }
+ }
+}
+
+func TestAlipayQueryRefundMapsStatus(t *testing.T) {
+ origQuery := alipayTradeFastPayRefundQuery
+ t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery })
+
+ const outRequestNo = "sub2_7-refund-1760500000000000000"
+ ok := alipay.Error{Code: alipay.CodeSuccess, Msg: "Success"}
+ settled := time.Now().Add(-alipayRefundQueryNotFoundGrace - time.Minute)
+ for _, tc := range []struct {
+ name string
+ rsp *alipay.TradeFastPayRefundQueryRsp
+ requestedAt time.Time
+ wantStatus string
+ }{
+ {name: "success", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok, OutRequestNo: outRequestNo, RefundAmount: "12.50", RefundStatus: alipayRefundStatusSucc}, requestedAt: settled, wantStatus: payment.ProviderStatusSuccess},
+ {name: "record without final status", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok, OutRequestNo: outRequestNo, RefundAmount: "12.50"}, requestedAt: settled, wantStatus: payment.ProviderStatusPending},
+ {name: "no refund record after grace", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok}, requestedAt: settled, wantStatus: payment.ProviderStatusFailed},
+ {name: "no refund record within grace", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok}, requestedAt: time.Now().Add(-time.Minute), wantStatus: payment.ProviderStatusPending},
+ {name: "no refund record with unknown request time", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok}, wantStatus: payment.ProviderStatusPending},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ alipayTradeFastPayRefundQuery = func(_ context.Context, _ *alipay.Client, param alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) {
+ if param.OutTradeNo != "sub2_7" || param.OutRequestNo != outRequestNo {
+ t.Fatalf("unexpected query param: %+v", param)
+ }
+ return tc.rsp, nil
+ }
+ provider := &Alipay{client: &alipay.Client{}}
+ resp, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{OrderID: "sub2_7", RefundID: outRequestNo, RequestedAt: tc.requestedAt})
+ if err != nil {
+ t.Fatalf("QueryRefund() error = %v", err)
+ }
+ if resp.Status != tc.wantStatus || resp.RefundID != outRequestNo {
+ t.Fatalf("QueryRefund() = %+v, want status %q", resp, tc.wantStatus)
+ }
+ })
+ }
+}
+
+// SDK 对带签名的业务失败响应返回 err == nil,错误码只在响应体里。
+func TestAlipayQueryRefundBusinessFailureKeepsRefundPending(t *testing.T) {
+ origQuery := alipayTradeFastPayRefundQuery
+ t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery })
+
+ for _, rspErr := range []alipay.Error{
+ {Code: "40004", Msg: "Business Failed", SubCode: "ACQ.SYSTEM_ERROR", SubMsg: "系统错误"},
+ {Code: "20000", Msg: "Service Currently Unavailable", SubCode: "isp.unknow-error"},
+ {},
+ } {
+ alipayTradeFastPayRefundQuery = func(context.Context, *alipay.Client, alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) {
+ return &alipay.TradeFastPayRefundQueryRsp{Error: rspErr}, nil
+ }
+ provider := &Alipay{client: &alipay.Client{}}
+ resp, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{
+ OrderID: "sub2_7",
+ RefundID: "sub2_7-refund-1",
+ RequestedAt: time.Now().Add(-24 * time.Hour),
+ })
+ if err == nil {
+ t.Fatalf("code %q: QueryRefund() = %+v, want error", rspErr.Code, resp)
+ }
+ if rspErr.SubCode != "" && !strings.Contains(err.Error(), string(rspErr.Code)) {
+ t.Fatalf("code %q: error %q should carry the gateway code", rspErr.Code, err)
+ }
+ }
+}
+
+func TestAlipayQueryRefundErrorsKeepRefundPending(t *testing.T) {
+ origQuery := alipayTradeFastPayRefundQuery
+ t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery })
+
+ calls := 0
+ alipayTradeFastPayRefundQuery = func(context.Context, *alipay.Client, alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) {
+ calls++
+ return nil, errors.New("ACQ.SYSTEM_ERROR")
+ }
+ provider := &Alipay{client: &alipay.Client{}}
+
+ // 旧版本记录的是支付宝交易号,无法查询退款请求,需人工核实,且不能调用网关。
+ for _, legacyID := range []string{"", "2026101522001", "sub2_7-refund", "sub2_70-refund-1"} {
+ if _, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{OrderID: "sub2_7", RefundID: legacyID}); err == nil || !strings.Contains(err.Error(), "verify manually") {
+ t.Fatalf("legacy refund id %q: err = %v", legacyID, err)
+ }
+ }
+ if calls != 0 {
+ t.Fatalf("legacy refund ids must not reach the gateway, calls = %d", calls)
+ }
+
+ if _, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{OrderID: "sub2_7", RefundID: "sub2_7-refund-1"}); err == nil {
+ t.Fatal("gateway error must be returned so the refund stays pending")
+ }
+}
diff --git a/backend/internal/payment/provider/easypay.go b/backend/internal/payment/provider/easypay.go
index f58ac0c1b..aecb6791d 100644
--- a/backend/internal/payment/provider/easypay.go
+++ b/backend/internal/payment/provider/easypay.go
@@ -7,8 +7,10 @@ import (
"crypto/md5"
"encoding/hex"
"encoding/json"
+ "errors"
"fmt"
"io"
+ "math"
"net/http"
"net/url"
"sort"
@@ -27,6 +29,7 @@ const (
easypayHTTPTimeout = 10 * time.Second
maxEasypayResponseSize = 1 << 20 // 1MB
maxEasypayErrorSummary = 512
+ easypayAmountTolerance = 0.005
tradeStatusSuccess = "TRADE_SUCCESS"
signTypeMD5 = "MD5"
paymentModePopup = "popup"
@@ -301,32 +304,86 @@ func (e *EasyPay) upstreamPaymentType(paymentType string) string {
}
func (e *EasyPay) QueryOrder(ctx context.Context, tradeNo string) (*payment.QueryOrderResponse, error) {
+ result, err := e.queryOrder(ctx, tradeNo)
+ if err != nil {
+ return nil, err
+ }
+ responseTradeNo := tradeNo
+ if result.tradeNo != "" {
+ responseTradeNo = result.tradeNo
+ }
+ amount, _ := strconv.ParseFloat(result.money, 64)
+ return &payment.QueryOrderResponse{
+ TradeNo: responseTradeNo,
+ Status: result.status,
+ Amount: amount,
+ Metadata: e.MerchantIdentityMetadata(),
+ }, nil
+}
+
+// easyPayQueryResult is the normalized api.php?act=order answer. tradeNo is
+// the upstream trade number exactly as returned (empty when absent).
+type easyPayQueryResult struct {
+ status string
+ money string
+ tradeNo string
+}
+
+func (e *EasyPay) queryOrder(ctx context.Context, outTradeNo string) (*easyPayQueryResult, error) {
params := map[string]string{
"act": "order", "pid": e.config["pid"],
- "key": e.config["pkey"], "out_trade_no": tradeNo,
+ "key": e.config["pkey"], "out_trade_no": outTradeNo,
}
- body, err := e.post(ctx, e.apiBase()+"/api.php", params)
+ // 彩虹易支付 and ZPay read act=order parameters from $_GET only (a
+ // body-only request is answered with "No Act!"), while other forks read
+ // the form body; send them in both places.
+ query := url.Values{}
+ for k, v := range params {
+ query.Set(k, v)
+ }
+ body, err := e.post(ctx, e.apiBase()+"/api.php?"+query.Encode(), params)
if err != nil {
+ // The request URL carries the merchant key; never let it reach logs
+ // or audit records through *url.Error.
+ var urlErr *url.Error
+ if errors.As(err, &urlErr) {
+ err = urlErr.Err
+ }
return nil, fmt.Errorf("easypay query: %w", err)
}
+ // Scalars are decoded leniently: PHP deployments commonly serialize
+ // integer columns as strings ("status":"1").
type easyPayQueryData struct {
- TradeStatus *string `json:"trade_status"`
- Status *int `json:"status"`
- Money *string `json:"money"`
- TradeNo *string `json:"trade_no"`
+ TradeStatus *string `json:"trade_status"`
+ Status json.RawMessage `json:"status"`
+ Money json.RawMessage `json:"money"`
+ TradeNo json.RawMessage `json:"trade_no"`
+ OutTradeNo json.RawMessage `json:"out_trade_no"`
}
var resp struct {
- Code int `json:"code"`
- Msg string `json:"msg"`
- TradeStatus *string `json:"trade_status"`
- Status *int `json:"status"`
- Money *string `json:"money"`
- TradeNo *string `json:"trade_no"`
- Data easyPayQueryData `json:"data"`
+ easyPayQueryData
+ Code any `json:"code"`
+ Msg string `json:"msg"`
+ Data easyPayQueryData `json:"data"`
}
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("easypay parse query: %w", err)
}
+ // An explicit failure code wins over any paid-looking status field that
+ // may accompany it.
+ if resp.Code != nil && !easyPayResponseCodeIsSuccess(resp.Code) {
+ msg := strings.TrimSpace(resp.Msg)
+ if msg == "" {
+ msg = summarizeEasyPayResponse(body)
+ }
+ return nil, fmt.Errorf("easypay query failed: %s", msg)
+ }
+ // When the upstream echoes the order identity it must be this order; some
+ // implementations silently ignore unknown lookup parameters.
+ if echoed := easyPayJSONScalar(pickEasyPayJSON(resp.OutTradeNo, resp.Data.OutTradeNo)); echoed != "" && echoed != strings.TrimSpace(outTradeNo) {
+ return nil, fmt.Errorf("easypay query out_trade_no mismatch: expected %s, got %s", strings.TrimSpace(outTradeNo), echoed)
+ }
+
status := payment.ProviderStatusPending
if resp.TradeStatus != nil {
if *resp.TradeStatus == tradeStatusSuccess {
@@ -336,36 +393,72 @@ func (e *EasyPay) QueryOrder(ctx context.Context, tradeNo string) (*payment.Quer
if *resp.Data.TradeStatus == tradeStatusSuccess {
status = payment.ProviderStatusPaid
}
- } else if resp.Status != nil {
- if *resp.Status == easypayStatusPaid {
+ } else if raw := pickEasyPayJSON(resp.Status, resp.Data.Status); raw != nil {
+ if easyPayJSONScalar(raw) == strconv.Itoa(easypayStatusPaid) {
status = payment.ProviderStatusPaid
}
- } else if resp.Data.Status != nil && *resp.Data.Status == easypayStatusPaid {
- status = payment.ProviderStatusPaid
}
- money := ""
- if resp.Money != nil {
- money = *resp.Money
- } else if resp.Data.Money != nil {
- money = *resp.Data.Money
+ return &easyPayQueryResult{
+ status: status,
+ money: easyPayJSONScalar(pickEasyPayJSON(resp.Money, resp.Data.Money)),
+ tradeNo: easyPayJSONScalar(pickEasyPayJSON(resp.TradeNo, resp.Data.TradeNo)),
+ }, nil
+}
+
+// ConfirmNotification checks a verified success notification against the
+// upstream order before it is fulfilled, so crediting follows the gateway's
+// own order state (paid, amount, trade_no). The query is sent to this
+// instance's own apiBase with its own credentials.
+func (e *EasyPay) ConfirmNotification(ctx context.Context, n *payment.PaymentNotification) error {
+ if n == nil || n.Status != payment.NotificationStatusSuccess {
+ return nil
}
- responseTradeNo := tradeNo
- if resp.TradeNo != nil {
- if *resp.TradeNo != "" {
- responseTradeNo = *resp.TradeNo
+ result, err := e.queryOrder(ctx, n.OrderID)
+ if err != nil {
+ return fmt.Errorf("easypay confirm: %w", err)
+ }
+ if result.status != payment.ProviderStatusPaid {
+ return fmt.Errorf("easypay confirm: upstream reports order %s as not paid", n.OrderID)
+ }
+ queriedAmount, err := strconv.ParseFloat(result.money, 64)
+ if err != nil || math.Abs(queriedAmount-n.Amount) > easypayAmountTolerance {
+ return fmt.Errorf("easypay confirm: amount mismatch: notified %v, upstream %q", n.Amount, result.money)
+ }
+ if result.tradeNo != "" {
+ if n.TradeNo != "" && n.TradeNo != result.tradeNo {
+ return fmt.Errorf("easypay confirm: trade_no mismatch: notified %s, upstream %s", n.TradeNo, result.tradeNo)
}
- } else if resp.Data.TradeNo != nil && *resp.Data.TradeNo != "" {
- responseTradeNo = *resp.Data.TradeNo
+ n.TradeNo = result.tradeNo
}
+ return nil
+}
- amount, _ := strconv.ParseFloat(money, 64)
- return &payment.QueryOrderResponse{
- TradeNo: responseTradeNo,
- Status: status,
- Amount: amount,
- Metadata: e.MerchantIdentityMetadata(),
- }, nil
+func easyPayJSONScalar(raw json.RawMessage) string {
+ if len(raw) == 0 {
+ return ""
+ }
+ var str string
+ if err := json.Unmarshal(raw, &str); err == nil {
+ return strings.TrimSpace(str)
+ }
+ var num json.Number
+ if err := json.Unmarshal(raw, &num); err == nil {
+ return num.String()
+ }
+ return ""
+}
+
+// pickEasyPayJSON returns the top-level field when present, otherwise the
+// nested data field. JSON null counts as absent.
+func pickEasyPayJSON(top, nested json.RawMessage) json.RawMessage {
+ if len(top) > 0 && string(top) != "null" {
+ return top
+ }
+ if len(nested) > 0 && string(nested) != "null" {
+ return nested
+ }
+ return nil
}
func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[string]string) (*payment.PaymentNotification, error) {
@@ -379,7 +472,14 @@ func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[st
if !easyPayNotifyAllowedParams[k] {
return nil, fmt.Errorf("unexpected notify param: %s", k)
}
- params[k] = values.Get(k)
+ v := values.Get(k)
+ // Notify values are plain tokens; only the merchant-defined product
+ // name is free text. Delimiter characters elsewhere are rejected so
+ // each value maps to exactly one field of the signed string.
+ if k != "name" && strings.ContainsAny(v, "&=") {
+ return nil, fmt.Errorf("invalid notify param value: %s", k)
+ }
+ params[k] = v
}
sign := params["sign"]
if sign == "" {
@@ -388,22 +488,20 @@ func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[st
if !easyPayVerifySign(params, e.config["pkey"], sign) {
return nil, fmt.Errorf("invalid signature")
}
+ // Bind the notification to this instance's merchant directly instead of
+ // relying on the order snapshot, which legacy orders do not carry.
+ if expected, actual := strings.TrimSpace(e.config["pid"]), strings.TrimSpace(params["pid"]); actual != expected {
+ return nil, fmt.Errorf("easypay pid mismatch: expected %s, got %s", expected, actual)
+ }
status := payment.ProviderStatusFailed
if params["trade_status"] == tradeStatusSuccess {
status = payment.ProviderStatusSuccess
}
amount, _ := strconv.ParseFloat(params["money"], 64)
- metadata := e.MerchantIdentityMetadata()
- if pid := strings.TrimSpace(params["pid"]); pid != "" {
- if metadata == nil {
- metadata = map[string]string{}
- }
- metadata["pid"] = pid
- }
return &payment.PaymentNotification{
TradeNo: params["trade_no"], OrderID: params["out_trade_no"],
- Amount: amount, Status: status, RawData: rawBody, Metadata: metadata,
+ Amount: amount, Status: status, RawData: rawBody, Metadata: e.MerchantIdentityMetadata(),
}, nil
}
diff --git a/backend/internal/payment/provider/easypay_confirm_test.go b/backend/internal/payment/provider/easypay_confirm_test.go
new file mode 100644
index 000000000..a16d2f452
--- /dev/null
+++ b/backend/internal/payment/provider/easypay_confirm_test.go
@@ -0,0 +1,253 @@
+package provider
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/payment"
+)
+
+func newConfirmTestEasyPay(t *testing.T, body string, status int) (*EasyPay, *atomic.Int32) {
+ t.Helper()
+ var calls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ if err := r.ParseForm(); err != nil {
+ t.Errorf("ParseForm: %v", err)
+ }
+ q := r.URL.Query()
+ if r.URL.Path != "/api.php" || q.Get("act") != "order" || q.Get("pid") != "1001" || q.Get("key") != "pkey-1" || q.Get("out_trade_no") != "sub2_ORDER1" {
+ t.Errorf("unexpected query request: path=%s query=%v", r.URL.Path, q)
+ }
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(body))
+ }))
+ t.Cleanup(server.Close)
+ provider, err := NewEasyPay("test-instance", map[string]string{
+ "pid": "1001",
+ "pkey": "pkey-1",
+ "apiBase": server.URL,
+ "notifyUrl": "https://example.com/notify",
+ "returnUrl": "https://example.com/return",
+ })
+ if err != nil {
+ t.Fatalf("NewEasyPay: %v", err)
+ }
+ return provider, &calls
+}
+
+func confirmTestNotification() *payment.PaymentNotification {
+ return &payment.PaymentNotification{
+ TradeNo: "2026101600001",
+ OrderID: "sub2_ORDER1",
+ Amount: 10,
+ Status: payment.NotificationStatusSuccess,
+ }
+}
+
+func TestEasyPayConfirmNotification(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ body string
+ status int
+ notifyTrade string
+ wantErr string
+ wantTradeNo string
+ }{
+ {
+ name: "paid with matching amount and trade_no",
+ body: `{"code":1,"pid":1001,"out_trade_no":"sub2_ORDER1","trade_no":"2026101600001","money":"10.00","status":1}`,
+ notifyTrade: "2026101600001",
+ wantTradeNo: "2026101600001",
+ },
+ {
+ name: "missing notify trade_no is filled from upstream",
+ body: `{"code":1,"trade_no":"2026101600001","money":"10.00","trade_status":"TRADE_SUCCESS"}`,
+ wantTradeNo: "2026101600001",
+ },
+ {
+ name: "upstream not paid",
+ body: `{"code":1,"trade_no":"2026101600001","money":"10.00","status":0}`,
+ notifyTrade: "2026101600001",
+ wantErr: "not paid",
+ },
+ {
+ name: "upstream failure code with paid status",
+ body: `{"code":-1,"msg":"订单号不存在","status":1,"money":"10.00"}`,
+ notifyTrade: "2026101600001",
+ wantErr: "订单号不存在",
+ },
+ {
+ name: "amount mismatch",
+ body: `{"code":1,"trade_no":"2026101600001","money":"0.01","status":1}`,
+ notifyTrade: "2026101600001",
+ wantErr: "amount mismatch",
+ },
+ {
+ name: "missing upstream amount",
+ body: `{"code":1,"trade_no":"2026101600001","status":1}`,
+ notifyTrade: "2026101600001",
+ wantErr: "amount mismatch",
+ },
+ {
+ name: "trade_no conflict",
+ body: `{"code":1,"trade_no":"2026101699999","money":"10.00","status":1}`,
+ notifyTrade: "2026101600001",
+ wantErr: "trade_no mismatch",
+ },
+ {
+ name: "string status from PHP deployment",
+ body: `{"code":"1","pid":"1001","out_trade_no":"sub2_ORDER1","trade_no":"2026101600001","money":"10.00","status":"1"}`,
+ notifyTrade: "2026101600001",
+ wantTradeNo: "2026101600001",
+ },
+ {
+ name: "foreign order echo",
+ body: `{"code":1,"out_trade_no":"sub2_OTHER","trade_no":"2026101600001","money":"10.00","status":1}`,
+ notifyTrade: "2026101600001",
+ wantErr: "out_trade_no mismatch",
+ },
+ {
+ name: "upstream HTTP error body",
+ body: `502 Bad Gateway`,
+ status: http.StatusBadGateway,
+ notifyTrade: "2026101600001",
+ wantErr: "parse query",
+ },
+ }
+ for _, tt := range tests {
+ tt := tt
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ status := tt.status
+ if status == 0 {
+ status = http.StatusOK
+ }
+ provider, calls := newConfirmTestEasyPay(t, tt.body, status)
+ n := confirmTestNotification()
+ n.TradeNo = tt.notifyTrade
+ err := provider.ConfirmNotification(context.Background(), n)
+ if calls.Load() != 1 {
+ t.Fatalf("upstream query calls = %d, want 1", calls.Load())
+ }
+ if tt.wantErr != "" {
+ if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
+ t.Fatalf("ConfirmNotification error = %v, want containing %q", err, tt.wantErr)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("ConfirmNotification returned error: %v", err)
+ }
+ if n.TradeNo != tt.wantTradeNo {
+ t.Fatalf("trade_no = %q, want %q", n.TradeNo, tt.wantTradeNo)
+ }
+ })
+ }
+}
+
+func TestEasyPayConfirmNotificationSkipsNonSuccess(t *testing.T) {
+ t.Parallel()
+
+ provider, calls := newConfirmTestEasyPay(t, `{}`, http.StatusOK)
+ n := confirmTestNotification()
+ n.Status = payment.ProviderStatusFailed
+ if err := provider.ConfirmNotification(context.Background(), n); err != nil {
+ t.Fatalf("ConfirmNotification returned error: %v", err)
+ }
+ if calls.Load() != 0 {
+ t.Fatalf("upstream query calls = %d, want 0", calls.Load())
+ }
+}
+
+func TestEasyPayConfirmNotificationQueryTransportError(t *testing.T) {
+ t.Parallel()
+
+ server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
+ apiBase := server.URL
+ server.Close()
+ provider := newTestEasyPay(t, apiBase)
+ err := provider.ConfirmNotification(context.Background(), confirmTestNotification())
+ if err == nil {
+ t.Fatal("ConfirmNotification must fail when the upstream is unreachable")
+ }
+ // The query URL carries the merchant key; errors are logged and stored in
+ // the payment audit trail, so they must not echo the URL.
+ if strings.Contains(err.Error(), "pkey-1") || strings.Contains(err.Error(), "key=") {
+ t.Fatalf("error contains the merchant key: %v", err)
+ }
+}
+
+func TestEasyPayNotifyRejectsForeignPid(t *testing.T) {
+ t.Parallel()
+ e := easyPayPoCProvider()
+
+ for _, pid := range []string{"2000", ""} {
+ params := map[string]string{
+ "trade_no": "T1",
+ "out_trade_no": "ORDER123",
+ "type": "alipay",
+ "name": "balance recharge",
+ "money": "650.00",
+ "trade_status": tradeStatusSuccess,
+ }
+ if pid != "" {
+ params["pid"] = pid
+ }
+ params["sign"] = easyPaySign(params, e.config["pkey"])
+ q := url.Values{}
+ for k, v := range params {
+ q.Set(k, v)
+ }
+ if _, err := e.VerifyNotification(context.Background(), q.Encode(), nil); err == nil {
+ t.Fatalf("callback with pid %q must be rejected", pid)
+ }
+ }
+}
+
+func TestEasyPayNotifyAllowsFreeTextNameOnly(t *testing.T) {
+ t.Parallel()
+ e := easyPayPoCProvider()
+
+ base := map[string]string{
+ "pid": "1000",
+ "trade_no": "T1",
+ "out_trade_no": "ORDER123",
+ "type": "alipay",
+ "name": "Plan A&B = Pro",
+ "money": "650.00",
+ "trade_status": tradeStatusSuccess,
+ }
+ encode := func(params map[string]string) string {
+ signed := map[string]string{}
+ for k, v := range params {
+ signed[k] = v
+ }
+ signed["sign"] = easyPaySign(params, e.config["pkey"])
+ q := url.Values{}
+ for k, v := range signed {
+ q.Set(k, v)
+ }
+ return q.Encode()
+ }
+ if _, err := e.VerifyNotification(context.Background(), encode(base), nil); err != nil {
+ t.Fatalf("free-text name must be accepted: %v", err)
+ }
+ for _, field := range []string{"trade_no", "out_trade_no", "type", "money", "param"} {
+ params := map[string]string{}
+ for k, v := range base {
+ params[k] = v
+ }
+ params[field] = "v&k=x"
+ if _, err := e.VerifyNotification(context.Background(), encode(params), nil); err == nil {
+ t.Fatalf("value with &/= in %s must be rejected", field)
+ }
+ }
+}
diff --git a/backend/internal/payment/provider/easypay_query_test.go b/backend/internal/payment/provider/easypay_query_test.go
index 8a08d4348..64460fe68 100644
--- a/backend/internal/payment/provider/easypay_query_test.go
+++ b/backend/internal/payment/provider/easypay_query_test.go
@@ -20,6 +20,7 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) {
wantStatus string
wantTradeNo string
wantAmount float64
+ wantErr bool
}{
{
name: "top level trade success is paid",
@@ -64,10 +65,64 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) {
wantAmount: 3.21,
},
{
- name: "query failure with missing status is pending",
- body: `{"code":0,"msg":"订单不存在"}`,
+ name: "query failure code is an error",
+ body: `{"code":0,"msg":"订单不存在"}`,
+ wantErr: true,
+ },
+ {
+ name: "explicit failure code wins over paid status fields",
+ body: `{"code":-1,"msg":"签名错误","status":1,"trade_status":"TRADE_SUCCESS","money":"12.34"}`,
+ wantErr: true,
+ },
+ {
+ name: "string failure code is an error",
+ body: `{"code":"-1","msg":"error","status":1}`,
+ wantErr: true,
+ },
+ {
+ name: "foreign order echo is rejected",
+ body: `{"code":1,"pid":"pid-1","out_trade_no":"order-999","trade_status":"TRADE_SUCCESS","money":"12.34"}`,
+ wantErr: true,
+ },
+ {
+ name: "foreign order echo in nested data is rejected",
+ body: `{"code":1,"data":{"out_trade_no":"order-999","trade_status":"TRADE_SUCCESS","money":"12.34"}}`,
+ wantErr: true,
+ },
+ {
+ name: "string numeric status from PHP deployments is paid",
+ body: `{"code":"1","msg":"查询订单号成功!","trade_no":"2026101600001","out_trade_no":"order-123","pid":"1001","money":"12.34","status":"1"}`,
+ wantStatus: payment.ProviderStatusPaid,
+ wantTradeNo: "2026101600001",
+ wantAmount: 12.34,
+ },
+ {
+ name: "string numeric unpaid status is pending",
+ body: `{"code":1,"trade_no":"2026101600001","money":"12.34","status":"0"}`,
wantStatus: payment.ProviderStatusPending,
- wantTradeNo: orderID,
+ wantTradeNo: "2026101600001",
+ wantAmount: 12.34,
+ },
+ {
+ name: "documented caihong response with integer pid and status is paid",
+ body: `{"code":1,"msg":"查询订单号成功!","trade_no":"2016080622555342651","out_trade_no":"order-123","api_trade_no":"4200001","type":"alipay","pid":1001,"addtime":"2016-08-06 22:55:52","endtime":"2016-08-06 22:55:52","name":"VIP会员","money":"1.00","status":1,"param":"","buyer":""}`,
+ wantStatus: payment.ProviderStatusPaid,
+ wantTradeNo: "2016080622555342651",
+ wantAmount: 1,
+ },
+ {
+ name: "null top-level fields fall back to nested data",
+ body: `{"code":1,"status":null,"money":null,"trade_no":null,"data":{"status":1,"money":"5.00","trade_no":"data-789"}}`,
+ wantStatus: payment.ProviderStatusPaid,
+ wantTradeNo: "data-789",
+ wantAmount: 5,
+ },
+ {
+ name: "matching identity echo with numeric fields is paid",
+ body: `{"code":"1","pid":"pid-1","out_trade_no":"order-123","trade_status":"TRADE_SUCCESS","money":12.34,"trade_no":2026101600001}`,
+ wantStatus: payment.ProviderStatusPaid,
+ wantTradeNo: "2026101600001",
+ wantAmount: 12.34,
},
{
name: "missing fields are pending",
@@ -93,9 +148,16 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) {
if err := r.ParseForm(); err != nil {
t.Errorf("ParseForm: %v", err)
}
- gotForm = make(url.Values, len(r.PostForm))
+ // Parameters must be in the URL query (彩虹易支付 reads $_GET)
+ // and mirrored in the body for forks that read $_POST.
+ gotForm = r.URL.Query()
for key, values := range r.PostForm {
- gotForm[key] = append([]string(nil), values...)
+ if got := gotForm.Get(key); got != values[0] {
+ t.Errorf("body[%s] = %q, query has %q", key, values[0], got)
+ }
+ }
+ if len(r.PostForm) != len(gotForm) {
+ t.Errorf("body params %v do not mirror query params %v", r.PostForm, gotForm)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(tt.body))
@@ -104,6 +166,12 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) {
provider := newTestEasyPay(t, server.URL)
resp, err := provider.QueryOrder(context.Background(), orderID)
+ if tt.wantErr {
+ if err == nil {
+ t.Fatalf("QueryOrder succeeded, want error (response=%+v)", resp)
+ }
+ return
+ }
if err != nil {
t.Fatalf("QueryOrder returned error: %v", err)
}
diff --git a/backend/internal/payment/types.go b/backend/internal/payment/types.go
index 6421c4afe..dc3ec58ff 100644
--- a/backend/internal/payment/types.go
+++ b/backend/internal/payment/types.go
@@ -2,7 +2,10 @@
// registry, load balancing, and shared utilities for the payment subsystem.
package payment
-import "context"
+import (
+ "context"
+ "time"
+)
// PaymentType represents a supported payment method.
type PaymentType = string
@@ -192,6 +195,8 @@ type RefundQueryRequest struct {
OrderID string
RefundID string
Amount string
+ // RequestedAt 为退款进入 pending 的时间;零值表示未知。
+ RequestedAt time.Time
}
// RefundResponse is returned after a refund request.
@@ -234,6 +239,16 @@ type RefundQueryProvider interface {
QueryRefund(ctx context.Context, req RefundQueryRequest) (*RefundResponse, error)
}
+// NotificationConfirmer extends Provider for gateways whose verified
+// notifications are not sufficient proof of payment on their own. The webhook
+// path calls ConfirmNotification on the instance that verified the
+// notification before fulfillment; implementations query the upstream order
+// and may fill in missing notification fields (e.g. TradeNo) from it.
+type NotificationConfirmer interface {
+ Provider
+ ConfirmNotification(ctx context.Context, n *PaymentNotification) error
+}
+
// CancelableProvider extends Provider with the ability to cancel pending payments.
type CancelableProvider interface {
Provider
diff --git a/backend/internal/pkg/antigravity/claude_types.go b/backend/internal/pkg/antigravity/claude_types.go
index 61e32b615..3af852c8f 100644
--- a/backend/internal/pkg/antigravity/claude_types.go
+++ b/backend/internal/pkg/antigravity/claude_types.go
@@ -169,6 +169,12 @@ type modelDef struct {
var claudeModels = []modelDef{
{ID: "claude-fable-5-1", DisplayName: "Claude Fable 5.1", CreatedAt: "2026-09-01T00:00:00Z"},
{ID: "claude-fable-5", DisplayName: "Claude Fable 5", CreatedAt: "2026-06-09T00:00:00Z"},
+ {ID: "claude-opus-5-5-high", DisplayName: "Claude Opus 5.5 (High)", CreatedAt: "2026-09-22T00:00:00Z"},
+ {ID: "claude-opus-5-5-medium", DisplayName: "Claude Opus 5.5 (Medium)", CreatedAt: "2026-09-22T00:00:00Z"},
+ {ID: "claude-opus-5-5-low", DisplayName: "Claude Opus 5.5 (Low)", CreatedAt: "2026-09-22T00:00:00Z"},
+ {ID: "claude-sonnet-5-5-high", DisplayName: "Claude Sonnet 5.5 (High)", CreatedAt: "2026-09-28T00:00:00Z"},
+ {ID: "claude-sonnet-5-5-medium", DisplayName: "Claude Sonnet 5.5 (Medium)", CreatedAt: "2026-09-28T00:00:00Z"},
+ {ID: "claude-sonnet-5-5-low", DisplayName: "Claude Sonnet 5.5 (Low)", CreatedAt: "2026-09-28T00:00:00Z"},
{ID: "claude-opus-4-5-thinking", DisplayName: "Claude Opus 4.5 Thinking", CreatedAt: "2025-11-01T00:00:00Z"},
{ID: "claude-sonnet-4-5", DisplayName: "Claude Sonnet 4.5", CreatedAt: "2025-09-29T00:00:00Z"},
{ID: "claude-sonnet-4-5-thinking", DisplayName: "Claude Sonnet 4.5 Thinking", CreatedAt: "2025-09-29T00:00:00Z"},
@@ -208,6 +214,9 @@ var geminiModels = []modelDef{
{ID: "gemini-3.8-flash-low", DisplayName: "Gemini 3.8 Flash Low", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
{ID: "gemini-3.8-flash-medium", DisplayName: "Gemini 3.8 Flash Medium", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
{ID: "gemini-3.8-flash-tiered", DisplayName: "Gemini 3.8 Flash", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
+ {ID: "gemini-4-argon-high", DisplayName: "Gemini 4 Argon (High)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
+ {ID: "gemini-4-argon-low", DisplayName: "Gemini 4 Argon (Low)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
+ {ID: "gemini-4-argon-medium", DisplayName: "Gemini 4 Argon (Medium)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
{ID: "gemini-3-pro-preview", DisplayName: "Gemini 3 Pro Preview", CreatedAt: "2025-06-01T00:00:00Z", IsReasoning: true},
{ID: "gemini-3-pro-image", DisplayName: "Gemini 3 Pro Image", CreatedAt: "2025-06-01T00:00:00Z"},
}
@@ -277,6 +286,9 @@ func FallbackGeminiModel(model string) GeminiModel {
// IsGeminiReasoningModel 判断是否为不支持参数和强制 ToolConfig 的 Gemini 推理模型
func IsGeminiReasoningModel(modelID string) bool {
lowerID := strings.ToLower(modelID)
+ if strings.Contains(lowerID, "gemini-pro-agent") || strings.Contains(lowerID, "gemini-4-argon") {
+ return true
+ }
for _, m := range geminiModels {
if strings.Contains(lowerID, m.ID) && m.IsReasoning {
return true
diff --git a/backend/internal/pkg/antigravity/claude_types_test.go b/backend/internal/pkg/antigravity/claude_types_test.go
index 1aa5bca31..e65dcc286 100644
--- a/backend/internal/pkg/antigravity/claude_types_test.go
+++ b/backend/internal/pkg/antigravity/claude_types_test.go
@@ -39,6 +39,15 @@ func TestDefaultModels_ContainsNewAndLegacyImageModels(t *testing.T) {
"gemini-3.8-flash-low",
"gemini-3.8-flash-medium",
"gemini-3.8-flash-tiered",
+ "gemini-4-argon-high",
+ "gemini-4-argon-low",
+ "gemini-4-argon-medium",
+ "claude-opus-5-5-high",
+ "claude-opus-5-5-low",
+ "claude-opus-5-5-medium",
+ "claude-sonnet-5-5-high",
+ "claude-sonnet-5-5-low",
+ "claude-sonnet-5-5-medium",
}
for _, id := range requiredIDs {
@@ -67,3 +76,23 @@ func TestClaudeContentItem_ThinkingAlwaysHasSignature(t *testing.T) {
t.Fatalf("text block = %s, want %s", got, want)
}
}
+
+func TestIsGeminiReasoningModel_IncludesProAgent(t *testing.T) {
+ t.Parallel()
+
+ if !IsGeminiReasoningModel("gemini-pro-agent") {
+ t.Fatal("expected gemini-pro-agent to be recognized as a Gemini reasoning model")
+ }
+ if !IsGeminiReasoningModel("gemini-3.8-flash-high") {
+ t.Fatal("expected gemini-3.8-flash-high to be recognized as a Gemini reasoning model")
+ }
+ if !IsGeminiReasoningModel("gemini-4-argon") {
+ t.Fatal("expected gemini-4-argon to be recognized as a Gemini reasoning model")
+ }
+ if !IsGeminiReasoningModel("gemini-4-argon-high") {
+ t.Fatal("expected gemini-4-argon-high to be recognized as a Gemini reasoning model")
+ }
+ if IsGeminiReasoningModel("gemini-2.5-flash") {
+ t.Fatal("did not expect gemini-2.5-flash to be recognized as a Gemini reasoning model")
+ }
+}
diff --git a/backend/internal/pkg/antigravity/client.go b/backend/internal/pkg/antigravity/client.go
index f8925b623..052d68200 100644
--- a/backend/internal/pkg/antigravity/client.go
+++ b/backend/internal/pkg/antigravity/client.go
@@ -239,10 +239,39 @@ func TierIDToPlanType(tierID string) string {
if tierID == "" {
return "Free"
}
+ // Google 新增的细分档位(如 g1-ultra-lite-tier、g1-pro-plus-tier)仍归入 Ultra / Pro。
+ if plan := paidPlanFromTierID(tierID); plan != "" {
+ return plan
+ }
return tierID
}
}
+// paidPlanFromTierID 识别 g1-ultra-*-tier / g1-pro-*-tier 形式的付费档位 ID,未知时返回空串。
+func paidPlanFromTierID(tierID string) string {
+ id := strings.ToLower(strings.TrimSpace(tierID))
+ if !strings.HasSuffix(id, "-tier") {
+ return ""
+ }
+ switch {
+ case strings.HasPrefix(id, "g1-ultra-"):
+ return "Ultra"
+ case strings.HasPrefix(id, "g1-pro-"):
+ return "Pro"
+ default:
+ return ""
+ }
+}
+
+// IsPaidPlanType 判断账号记录的 plan_type 是否为付费套餐,兼容旧记录里直接保存的档位 ID。
+func IsPaidPlanType(planType string) bool {
+ switch strings.ToLower(strings.TrimSpace(planType)) {
+ case "pro", "ultra":
+ return true
+ }
+ return paidPlanFromTierID(planType) != ""
+}
+
// Client Antigravity API 客户端
type Client struct {
httpClient *http.Client
@@ -653,8 +682,22 @@ type FetchAvailableModelsResponse struct {
}
// FetchAvailableModels 获取可用模型和配额信息,返回解析后的结构体和原始 JSON
-// 支持 URL fallback:sandbox → daily → prod
+// 保留旧调用的 URL fallback:prod → daily。
func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectID string, bodyLimit int64) (*FetchAvailableModelsResponse, map[string]any, error) {
+ return c.fetchAvailableModels(ctx, BaseURLs, accessToken, projectID, bodyLimit, false)
+}
+
+// FetchAvailableModelsFromURL 获取指定端点的模型目录,不回退到其他端点。
+// 模型发现应使用与生成请求相同的端点,避免返回该端点无法访问的模型。
+func (c *Client) FetchAvailableModelsFromURL(ctx context.Context, baseURL, accessToken, projectID string, bodyLimit int64) (*FetchAvailableModelsResponse, map[string]any, error) {
+ baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
+ if baseURL == "" {
+ return nil, nil, errors.New("fetchAvailableModels base URL is required")
+ }
+ return c.fetchAvailableModels(ctx, []string{baseURL}, accessToken, projectID, bodyLimit, true)
+}
+
+func (c *Client) fetchAvailableModels(ctx context.Context, availableURLs []string, accessToken, projectID string, bodyLimit int64, fixedEndpoint bool) (*FetchAvailableModelsResponse, map[string]any, error) {
if c == nil || c.httpClient == nil {
return nil, nil, errors.New("antigravity client is not configured")
}
@@ -668,10 +711,10 @@ func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectI
return nil, nil, fmt.Errorf("序列化请求失败: %w", err)
}
- // 固定顺序:prod -> daily
- availableURLs := BaseURLs
-
fetchClient := c.fetchAvailableModelsHTTPClient()
+ if fixedEndpoint {
+ fetchClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ }
var lastErr error
for urlIdx, baseURL := range availableURLs {
apiURL := baseURL + "/v1internal:fetchAvailableModels"
diff --git a/backend/internal/pkg/antigravity/client_test.go b/backend/internal/pkg/antigravity/client_test.go
index 7a525879f..b6a342788 100644
--- a/backend/internal/pkg/antigravity/client_test.go
+++ b/backend/internal/pkg/antigravity/client_test.go
@@ -6,6 +6,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "io"
"net"
"net/http"
"net/http/httptest"
@@ -260,6 +261,8 @@ func TestTierIDToPlanType(t *testing.T) {
{"free-tier", "Free"},
{"g1-pro-tier", "Pro"},
{"g1-ultra-tier", "Ultra"},
+ {"g1-ultra-lite-tier", "Ultra"},
+ {"G1-Pro-Plus-Tier", "Pro"},
{"FREE-TIER", "Free"},
{"", "Free"},
{"unknown-tier", "unknown-tier"},
@@ -1468,6 +1471,113 @@ func TestClient_LoadCodeAssist_ContextCanceled_RealCall(t *testing.T) {
// Client.FetchAvailableModels - 真正调用方法的测试
// ---------------------------------------------------------------------------
+func TestClient_FetchAvailableModelsFromURL_UsesSelectedEndpoint(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1internal:fetchAvailableModels" || r.Method != http.MethodPost {
+ t.Errorf("unexpected model list request: %s %s", r.Method, r.URL.Path)
+ }
+ if r.Header.Get("Authorization") != "Bearer selected-token" {
+ t.Errorf("unexpected authorization header")
+ }
+ var body FetchAvailableModelsRequest
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Project != "selected-project" {
+ t.Errorf("unexpected project request: %+v, %v", body, err)
+ }
+ _, _ = w.Write([]byte(`{"models":{"gemini-3.8-flash-high":{"displayName":"Gemini 3.8 Flash High","supportsImages":true,"supportsThinking":true,"thinkingBudget":24576,"maxTokens":1048576,"maxOutputTokens":65536}}}`))
+ }))
+ defer server.Close()
+
+ client := mustNewClient(t, "")
+ response, raw, err := client.FetchAvailableModelsFromURL(context.Background(), server.URL, "selected-token", "selected-project", defaultFetchAvailableModelsBodyLimit)
+ if err != nil {
+ t.Fatalf("selected endpoint should return its catalog: %v", err)
+ }
+ model, ok := response.Models["gemini-3.8-flash-high"]
+ if !ok || model.SupportsThinking == nil || !*model.SupportsThinking || model.MaxTokens == nil || *model.MaxTokens != 1048576 {
+ t.Fatalf("selected endpoint metadata must remain available: %+v", model)
+ }
+ if raw["models"] == nil {
+ t.Fatal("selected endpoint raw catalog must remain available")
+ }
+}
+
+func TestClient_FetchAvailableModelsFromURL_DoesNotFollowAnotherEndpoint(t *testing.T) {
+ otherEndpointCalls := 0
+ other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ otherEndpointCalls++
+ _, _ = w.Write([]byte(`{"models":{"other-endpoint-model":{}}}`))
+ }))
+ defer other.Close()
+ selected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, other.URL+"/v1internal:fetchAvailableModels", http.StatusTemporaryRedirect)
+ }))
+ defer selected.Close()
+ withMockBaseURLs(t, []string{selected.URL, other.URL})
+
+ response, _, err := mustNewClient(t, "").FetchAvailableModelsFromURL(context.Background(), selected.URL, "token", "project", defaultFetchAvailableModelsBodyLimit)
+ if err == nil || response != nil {
+ t.Fatalf("selected endpoint redirect must not produce another endpoint's catalog: %v, %v", response, err)
+ }
+ if otherEndpointCalls != 0 {
+ t.Fatalf("model discovery must stay on selected endpoint; other endpoint received %d requests", otherEndpointCalls)
+ }
+}
+
+func TestClient_FetchAvailableModelsFromURL_DoesNotFallbackOnFailure(t *testing.T) {
+ for _, status := range []int{http.StatusNotFound, http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusForbidden} {
+ t.Run(fmt.Sprint(status), func(t *testing.T) {
+ otherEndpointCalls := 0
+ other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ otherEndpointCalls++
+ _, _ = w.Write([]byte(`{"models":{"other-endpoint-model":{}}}`))
+ }))
+ defer other.Close()
+ selected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(`{"error":"selected endpoint unavailable"}`))
+ }))
+ defer selected.Close()
+ withMockBaseURLs(t, []string{selected.URL, other.URL})
+
+ response, raw, err := mustNewClient(t, "").FetchAvailableModelsFromURL(context.Background(), selected.URL, "token", "project", defaultFetchAvailableModelsBodyLimit)
+ if err == nil || response != nil || raw != nil {
+ t.Fatalf("selected endpoint HTTP %d must fail without another catalog: %v, %v", status, response, err)
+ }
+ if otherEndpointCalls != 0 {
+ t.Fatalf("another endpoint must not receive fallback requests: %d", otherEndpointCalls)
+ }
+ if status == http.StatusForbidden {
+ if _, ok := err.(*ForbiddenError); !ok {
+ t.Fatalf("403 must preserve typed forbidden error: %T", err)
+ }
+ }
+ })
+ }
+}
+
+func TestClient_FetchAvailableModelsFromURL_ValidatesResponseAndLimit(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body string
+ limit int64
+ }{
+ {name: "invalid JSON", body: `not JSON`, limit: defaultFetchAvailableModelsBodyLimit},
+ {name: "oversized response", body: `{"models":{"model":{}}}`, limit: 8},
+ {name: "nonpositive limit", body: `{"models":{"model":{}}}`, limit: 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.WriteString(w, tc.body)
+ }))
+ defer server.Close()
+ _, _, err := mustNewClient(t, "").FetchAvailableModelsFromURL(context.Background(), server.URL, "token", "project", tc.limit)
+ if err == nil {
+ t.Fatal("invalid model catalog response or limit must fail")
+ }
+ })
+ }
+}
+
func TestClient_FetchAvailableModels_Success_RealCall(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -1787,6 +1897,51 @@ func TestClient_FetchAvailableModels_404Fallback_RealCall(t *testing.T) {
}
}
+func TestClient_HubUserAgentAndIDEVersionUseContextOverride(t *testing.T) {
+ withTestUserAgentVersionResolver(t)
+ ctx := context.WithValue(context.Background(), userAgentVersionTestContextKey{}, "3.4.5")
+ const expectedUserAgent = "antigravity/hub/3.4.5 windows/amd64"
+ for _, action := range []string{"generateContent", "streamGenerateContent"} {
+ req, err := NewAPIRequestWithURL(ctx, "https://upstream.example", action, "test-token", []byte(`{}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := req.Header.Get("User-Agent"); got != expectedUserAgent {
+ t.Fatalf("generation request must use the context Hub user agent: %q", got)
+ }
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("User-Agent"); got != expectedUserAgent {
+ t.Errorf("client API must use the context Hub user agent: %q", got)
+ }
+ switch r.URL.Path {
+ case "/v1internal:loadCodeAssist":
+ var body LoadCodeAssistRequest
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ if body.Metadata.IDEVersion != "3.4.5" {
+ t.Errorf("ideVersion must match the user agent version: %q", body.Metadata.IDEVersion)
+ }
+ _, _ = io.WriteString(w, `{"cloudaicompanionProject":"test-project"}`)
+ case "/v1internal:fetchAvailableModels":
+ _, _ = io.WriteString(w, `{"models":{"gemini-4-argon-high":{}}}`)
+ default:
+ t.Errorf("unexpected client endpoint: %s", r.URL.Path)
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer server.Close()
+ withMockBaseURLs(t, []string{server.URL})
+ client := mustNewClient(t, "")
+ if _, _, err := client.LoadCodeAssist(ctx, "test-token"); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := client.FetchAvailableModelsFromURL(ctx, server.URL, "test-token", "test-project", defaultFetchAvailableModelsBodyLimit); err != nil {
+ t.Fatal(err)
+ }
+}
+
func TestExtractProjectIDFromOnboardResponse(t *testing.T) {
t.Parallel()
diff --git a/backend/internal/pkg/antigravity/oauth.go b/backend/internal/pkg/antigravity/oauth.go
index 223a7b5d0..24482a763 100644
--- a/backend/internal/pkg/antigravity/oauth.go
+++ b/backend/internal/pkg/antigravity/oauth.go
@@ -34,7 +34,7 @@ const (
AntigravityUserAgentVersionEnv = "ANTIGRAVITY_USER_AGENT_VERSION"
// DefaultUserAgentVersion 是未通过环境变量或后台设置覆盖时使用的默认版本号。
- DefaultUserAgentVersion = "2.9.1"
+ DefaultUserAgentVersion = "2.23.0"
// 固定的 redirect_uri(用户需手动复制 code)
RedirectURI = "http://localhost:8085/callback"
@@ -123,9 +123,9 @@ func GetUserAgentVersionForContext(ctx context.Context) string {
// BuildUserAgent 使用指定版本号构造 User-Agent;版本为空或非法时回退默认值。
func BuildUserAgent(version string) string {
if normalized := NormalizeUserAgentVersion(version); normalized != "" {
- return fmt.Sprintf("antigravity/%s windows/amd64", normalized)
+ return fmt.Sprintf("antigravity/hub/%s windows/amd64", normalized)
}
- return fmt.Sprintf("antigravity/%s windows/amd64", defaultUserAgentVersion)
+ return fmt.Sprintf("antigravity/hub/%s windows/amd64", defaultUserAgentVersion)
}
// GetUserAgentForContext 返回当前请求应使用的 User-Agent。
diff --git a/backend/internal/pkg/antigravity/oauth_test.go b/backend/internal/pkg/antigravity/oauth_test.go
index 4ebc7e543..f75f2b4ff 100644
--- a/backend/internal/pkg/antigravity/oauth_test.go
+++ b/backend/internal/pkg/antigravity/oauth_test.go
@@ -3,16 +3,119 @@
package antigravity
import (
+ "context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"net/url"
"os"
+ "os/exec"
"strings"
"testing"
"time"
)
+func TestBuildUserAgentUsesHubClientFamily(t *testing.T) {
+ if got := BuildUserAgent(" 2.23.0 "); got != "antigravity/hub/2.23.0 windows/amd64" {
+ t.Fatalf("Hub client family must be sent with the configured version: %q", got)
+ }
+}
+
+func TestBuildUserAgentValidatesCustomVersion(t *testing.T) {
+ previous := defaultUserAgentVersion
+ defaultUserAgentVersion = "2.23.0"
+ t.Cleanup(func() { defaultUserAgentVersion = previous })
+ for _, tc := range []struct {
+ version string
+ want string
+ }{
+ {version: " 3.4.5 ", want: "antigravity/hub/3.4.5 windows/amd64"},
+ {version: "", want: "antigravity/hub/2.23.0 windows/amd64"},
+ {version: "hub/3.4.5", want: "antigravity/hub/2.23.0 windows/amd64"},
+ {version: "3.4", want: "antigravity/hub/2.23.0 windows/amd64"},
+ {version: "3.4.5\r\nInjected: header", want: "antigravity/hub/2.23.0 windows/amd64"},
+ } {
+ t.Run(tc.version, func(t *testing.T) {
+ if got := BuildUserAgent(tc.version); got != tc.want {
+ t.Fatalf("custom version must be validated before building Hub user agent: got %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+type userAgentVersionTestContextKey struct{}
+
+func withTestUserAgentVersionResolver(t *testing.T) {
+ t.Helper()
+ userAgentVersionMu.RLock()
+ previous := userAgentVersionResolver
+ userAgentVersionMu.RUnlock()
+ SetUserAgentVersionResolver(func(ctx context.Context) string {
+ version, _ := ctx.Value(userAgentVersionTestContextKey{}).(string)
+ return version
+ })
+ t.Cleanup(func() { SetUserAgentVersionResolver(previous) })
+}
+
+func TestGetUserAgentForContextPreservesVersionOverride(t *testing.T) {
+ withTestUserAgentVersionResolver(t)
+ previous := defaultUserAgentVersion
+ defaultUserAgentVersion = "2.23.0"
+ t.Cleanup(func() { defaultUserAgentVersion = previous })
+ for _, tc := range []struct {
+ version string
+ want string
+ }{
+ {version: " 3.4.5 ", want: "antigravity/hub/3.4.5 windows/amd64"},
+ {version: "invalid", want: "antigravity/hub/2.23.0 windows/amd64"},
+ } {
+ ctx := context.WithValue(context.Background(), userAgentVersionTestContextKey{}, tc.version)
+ if got := GetUserAgentForContext(ctx); got != tc.want {
+ t.Fatalf("context version override must use Hub family: got %q, want %q", got, tc.want)
+ }
+ }
+ if got := GetUserAgentForContext(nil); got != "antigravity/hub/2.23.0 windows/amd64" {
+ t.Fatalf("nil context must keep the default Hub user agent: %q", got)
+ }
+}
+
+func TestGetUserAgentEnvironmentOverride(t *testing.T) {
+ const expectedVersionEnv = "SUB2API_TEST_EXPECTED_ANTIGRAVITY_VERSION"
+ if expected := os.Getenv(expectedVersionEnv); expected != "" {
+ if got := GetDefaultUserAgentVersion(); got != expected {
+ t.Fatalf("environment version must be loaded during initialization: got %q, want %q", got, expected)
+ }
+ if got := GetUserAgent(); got != "antigravity/hub/"+expected+" windows/amd64" {
+ t.Fatalf("environment override must keep Hub family: %q", got)
+ }
+ return
+ }
+ for _, tc := range []struct {
+ version string
+ want string
+ }{
+ {version: " 3.4.5 ", want: "3.4.5"},
+ {version: "invalid", want: "2.23.0"},
+ } {
+ t.Run(tc.version, func(t *testing.T) {
+ binary, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ command := exec.Command(binary, "-test.run=^TestGetUserAgentEnvironmentOverride$")
+ for _, variable := range os.Environ() {
+ if !strings.HasPrefix(variable, AntigravityUserAgentVersionEnv+"=") && !strings.HasPrefix(variable, expectedVersionEnv+"=") {
+ command.Env = append(command.Env, variable)
+ }
+ }
+ command.Env = append(command.Env, AntigravityUserAgentVersionEnv+"="+tc.version, expectedVersionEnv+"="+tc.want)
+ if output, err := command.CombinedOutput(); err != nil {
+ t.Fatalf("environment override failed: %v\n%s", err, output)
+ }
+ })
+ }
+}
+
// ---------------------------------------------------------------------------
// getClientSecret
// ---------------------------------------------------------------------------
@@ -693,7 +796,10 @@ func TestConstants_值正确(t *testing.T) {
if RedirectURI != "http://localhost:8085/callback" {
t.Errorf("RedirectURI 不匹配: got %s", RedirectURI)
}
- if GetUserAgent() != "antigravity/2.9.1 windows/amd64" {
+ if DefaultUserAgentVersion != "2.23.0" {
+ t.Errorf("default Hub version must match the verified upstream release: got %s", DefaultUserAgentVersion)
+ }
+ if GetUserAgent() != "antigravity/hub/2.23.0 windows/amd64" {
t.Errorf("UserAgent 不匹配: got %s", GetUserAgent())
}
if SessionTTL != 30*time.Minute {
diff --git a/backend/internal/pkg/antigravity/request_transformer.go b/backend/internal/pkg/antigravity/request_transformer.go
index 9349e54ee..a13748926 100644
--- a/backend/internal/pkg/antigravity/request_transformer.go
+++ b/backend/internal/pkg/antigravity/request_transformer.go
@@ -588,6 +588,7 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu
ID: block.ToolUseID,
},
})
+ parts = append(parts, extractToolResultInlineParts(block.Content)...)
}
}
@@ -638,6 +639,31 @@ func parseToolResultContent(content json.RawMessage, isError bool) string {
return string(content)
}
+func extractToolResultInlineParts(content json.RawMessage) []GeminiPart {
+ if len(content) == 0 {
+ return nil
+ }
+ var innerBlocks []ContentBlock
+ if err := json.Unmarshal(content, &innerBlocks); err != nil {
+ return nil
+ }
+ var inlineParts []GeminiPart
+ for _, item := range innerBlocks {
+ if (item.Type == "image" || item.Type == "document") &&
+ item.Source != nil &&
+ item.Source.Type == "base64" &&
+ strings.TrimSpace(item.Source.Data) != "" {
+ inlineParts = append(inlineParts, GeminiPart{
+ InlineData: &GeminiInlineData{
+ MimeType: item.Source.MediaType,
+ Data: item.Source.Data,
+ },
+ })
+ }
+ }
+ return inlineParts
+}
+
// buildGenerationConfig 构建 generationConfig
const (
defaultMaxOutputTokens = 64000
diff --git a/backend/internal/pkg/antigravity/request_transformer_test.go b/backend/internal/pkg/antigravity/request_transformer_test.go
index 1aff9f577..7bdb40914 100644
--- a/backend/internal/pkg/antigravity/request_transformer_test.go
+++ b/backend/internal/pkg/antigravity/request_transformer_test.go
@@ -694,3 +694,64 @@ func TestToolConfigAlwaysPresent(t *testing.T) {
})
}
}
+
+func TestTransformClaudeToGemini_ToolResultImagesReachUpstream(t *testing.T) {
+ claudeReq := &ClaudeRequest{
+ Model: "claude-sonnet-4-5",
+ Messages: []ClaudeMessage{
+ {
+ Role: "assistant",
+ Content: json.RawMessage(`[
+ {"type":"tool_use","id":"toolu_img_1","name":"read_image","input":{"path":"colors.png"}}
+ ]`),
+ },
+ {
+ Role: "user",
+ Content: json.RawMessage(`[
+ {
+ "type":"tool_result",
+ "tool_use_id":"toolu_img_1",
+ "content":[
+ {"type":"text","text":"loaded colors.png"},
+ {"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}}
+ ]
+ },
+ {
+ "type":"tool_result",
+ "tool_use_id":"toolu_img_1",
+ "content":[
+ {"type":"image","source":{"type":"base64","media_type":"image/jpeg","data":"d29ybGQ="}}
+ ]
+ }
+ ]`),
+ },
+ },
+ }
+
+ body, err := TransformClaudeToGeminiWithOptions(claudeReq, "project-1", "claude-sonnet-4-5", DefaultTransformOptions())
+ require.NoError(t, err)
+
+ var req V1InternalRequest
+ require.NoError(t, json.Unmarshal(body, &req))
+ require.Len(t, req.Request.Contents, 2)
+
+ userParts := req.Request.Contents[1].Parts
+ require.Len(t, userParts, 4)
+
+ require.NotNil(t, userParts[0].FunctionResponse)
+ require.Equal(t, "read_image", userParts[0].FunctionResponse.Name)
+ require.Equal(t, "toolu_img_1", userParts[0].FunctionResponse.ID)
+ require.Equal(t, "loaded colors.png", userParts[0].FunctionResponse.Response["result"])
+
+ require.NotNil(t, userParts[1].InlineData)
+ require.Equal(t, "image/png", userParts[1].InlineData.MimeType)
+ require.Equal(t, "aGVsbG8=", userParts[1].InlineData.Data)
+
+ require.NotNil(t, userParts[2].FunctionResponse)
+ require.Equal(t, "read_image", userParts[2].FunctionResponse.Name)
+ require.Equal(t, "Command executed successfully.", userParts[2].FunctionResponse.Response["result"])
+
+ require.NotNil(t, userParts[3].InlineData)
+ require.Equal(t, "image/jpeg", userParts[3].InlineData.MimeType)
+ require.Equal(t, "d29ybGQ=", userParts[3].InlineData.Data)
+}
diff --git a/backend/internal/pkg/apicompat/anthropic_responses_test.go b/backend/internal/pkg/apicompat/anthropic_responses_test.go
index 5902128b9..700af63d4 100644
--- a/backend/internal/pkg/apicompat/anthropic_responses_test.go
+++ b/backend/internal/pkg/apicompat/anthropic_responses_test.go
@@ -1940,6 +1940,72 @@ func TestSonnet55SignedThinkingResponsesRoundTrip(t *testing.T) {
require.Equal(t, "tool_use", blocks[2].Type)
}
+func TestHaiku55ResponsesThinkingAndSampling(t *testing.T) {
+ for _, effort := range []string{"", "low", "medium", "high", "xhigh", "max", "none"} {
+ req := &ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), Reasoning: &ResponsesReasoning{Effort: effort}}
+ out, err := ResponsesToAnthropicRequest(req)
+ require.NoError(t, err, effort)
+ require.Zero(t, out.Thinking.BudgetTokens)
+ if effort == "none" {
+ require.Equal(t, "disabled", out.Thinking.Type)
+ require.Equal(t, "low", out.OutputConfig.Effort)
+ } else {
+ require.Equal(t, "adaptive", out.Thinking.Type)
+ if effort == "" {
+ effort = "medium"
+ }
+ require.Equal(t, effort, out.OutputConfig.Effort)
+ }
+ }
+ // Haiku 5.5 accepts forced tool_choice, unlike opus/sonnet 5.5.
+ for _, choice := range []string{`"required"`, `{"type":"function","name":"lookup"}`} {
+ out, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), ToolChoice: json.RawMessage(choice)})
+ require.NoError(t, err, choice)
+ require.NotEmpty(t, out.ToolChoice)
+ }
+ temperature := 0.7
+ _, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), Temperature: &temperature})
+ require.ErrorContains(t, err, "temperature")
+ for _, topP := range []float64{0.5, 0.995, 1} {
+ _, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), TopP: &topP})
+ require.ErrorContains(t, err, "top_p", "top_p=%v", topP)
+ }
+ _, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), Reasoning: &ResponsesReasoning{Effort: "minimal"}})
+ require.ErrorContains(t, err, "reasoning effort")
+
+ temperature = 1
+ topP := 0.99
+ _, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), Temperature: &temperature})
+ require.NoError(t, err)
+ _, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), TopP: &topP})
+ require.NoError(t, err)
+ _, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), Temperature: &temperature, TopP: &topP})
+ require.ErrorContains(t, err, "together")
+}
+
+func TestHaiku55SignedThinkingResponsesRoundTrip(t *testing.T) {
+ block := AnthropicContentBlock{Type: "thinking", Thinking: "", Signature: "signed-haiku-block"}
+ response := AnthropicToResponsesResponse(&AnthropicResponse{Model: "claude-haiku-5-5", Content: []AnthropicContentBlock{block, {Type: "text", Text: "progress"}, {Type: "tool_use", ID: "toolu_1", Name: "lookup", Input: json.RawMessage(`{}`)}}})
+ require.Len(t, response.Output, 3)
+ require.NotEmpty(t, response.Output[0].EncryptedContent)
+ require.Equal(t, "message", response.Output[1].Type)
+ raw, err := json.Marshal(response.Output)
+ require.NoError(t, err)
+ var items []ResponsesInputItem
+ require.NoError(t, json.Unmarshal(raw, &items))
+ items = append(items, ResponsesInputItem{Type: "function_call_output", CallID: response.Output[2].CallID, Output: "ok"})
+ raw, err = json.Marshal(items)
+ require.NoError(t, err)
+ converted, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: raw})
+ require.NoError(t, err)
+ require.Len(t, converted.Messages, 2)
+ var blocks []AnthropicContentBlock
+ require.NoError(t, json.Unmarshal(converted.Messages[0].Content, &blocks))
+ require.Equal(t, block, blocks[0])
+ require.Equal(t, "text", blocks[1].Type)
+ require.Equal(t, "tool_use", blocks[2].Type)
+}
+
func TestGPT6ChatSamplingAndCacheFields(t *testing.T) {
temperature := 0.7
for _, model := range []string{"gpt-6-sol", "gpt-6-luna"} {
diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses.go b/backend/internal/pkg/apicompat/anthropic_to_responses.go
index 6611d9446..c96e55d65 100644
--- a/backend/internal/pkg/apicompat/anthropic_to_responses.go
+++ b/backend/internal/pkg/apicompat/anthropic_to_responses.go
@@ -13,6 +13,12 @@ import (
// Chat Completions intermediary round-trip (e.g. thinking, cache_control,
// structured system prompts).
func AnthropicToResponses(req *AnthropicRequest) (*ResponsesRequest, error) {
+ return AnthropicToResponsesWithMinOutputTokens(req, DefaultMinMaxOutputTokens)
+}
+
+// AnthropicToResponsesWithMinOutputTokens converts an Anthropic request using
+// the supplied max_output_tokens floor.
+func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTokens int) (*ResponsesRequest, error) {
if err := openai.ValidateGPT61SolReasoningEffort(req.Model, anthropicReasoningEffort(req)); err != nil {
return nil, err
}
@@ -50,8 +56,8 @@ func AnthropicToResponses(req *AnthropicRequest) (*ResponsesRequest, error) {
if req.MaxTokens > 0 {
v := req.MaxTokens
- if v < minMaxOutputTokens {
- v = minMaxOutputTokens
+ if v < minOutputTokens {
+ v = minOutputTokens
}
out.MaxOutputTokens = &v
}
diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go
index 62c2f253f..ce1b8eca4 100644
--- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go
+++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go
@@ -53,7 +53,7 @@ func AnthropicToResponsesResponse(resp *AnthropicResponse) *ResponsesResponse {
for _, block := range resp.Content {
switch block.Type {
case "thinking", "redacted_thinking":
- if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model)) && (block.Signature != "" || block.Data != "") {
+ if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model) || claude.IsHaiku55(resp.Model)) && (block.Signature != "" || block.Data != "") {
item := ResponsesOutput{Type: "reasoning", ID: generateItemID(), EncryptedContent: encodeAnthropicThinking(block)}
if block.Thinking != "" {
item.Summary = []ResponsesSummary{{Type: "summary_text", Text: block.Thinking}}
@@ -72,7 +72,7 @@ func AnthropicToResponsesResponse(resp *AnthropicResponse) *ResponsesResponse {
})
}
case "text":
- if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model)) && block.Text != "" {
+ if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model) || claude.IsHaiku55(resp.Model)) && block.Text != "" {
outputs = append(outputs, ResponsesOutput{Type: "message", ID: generateItemID(), Role: "assistant", Status: "completed", Content: []ResponsesContentPart{{Type: "output_text", Text: block.Text}}})
continue
}
@@ -285,7 +285,7 @@ func ResponsesEventToSSE(evt ResponsesStreamEvent) (string, error) {
func anthToResHandleMessageStart(evt *AnthropicStreamEvent, state *AnthropicEventToResponsesState) []ResponsesStreamEvent {
if evt.Message != nil {
state.ResponseID = evt.Message.ID
- state.PreserveThinkingSignatures = state.PreserveThinkingSignatures || claude.IsOpus55(evt.Message.Model) || claude.IsSonnet55(evt.Message.Model)
+ state.PreserveThinkingSignatures = state.PreserveThinkingSignatures || claude.IsOpus55(evt.Message.Model) || claude.IsSonnet55(evt.Message.Model) || claude.IsHaiku55(evt.Message.Model)
if state.Model == "" {
state.Model = evt.Message.Model
}
diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go
index fc73afa3a..20a590c1c 100644
--- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go
+++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go
@@ -40,6 +40,12 @@ import (
// ResponsesToChatCompletionsRequest but avoids materializing the intermediate
// ResponsesRequest and the extra marshal/unmarshal cycle.
func AnthropicToChatCompletionsRequest(req *AnthropicRequest) (*ChatCompletionsRequest, error) {
+ return AnthropicToChatCompletionsRequestWithMinOutputTokens(req, DefaultMinMaxOutputTokens)
+}
+
+// AnthropicToChatCompletionsRequestWithMinOutputTokens converts an Anthropic
+// Messages request using the supplied max_completion_tokens floor.
+func AnthropicToChatCompletionsRequestWithMinOutputTokens(req *AnthropicRequest, minOutputTokens int) (*ChatCompletionsRequest, error) {
if req == nil {
return nil, fmt.Errorf("anthropic request is nil")
}
@@ -63,8 +69,8 @@ func AnthropicToChatCompletionsRequest(req *AnthropicRequest) (*ChatCompletionsR
if req.MaxTokens > 0 {
v := req.MaxTokens
- if v < minMaxOutputTokens {
- v = minMaxOutputTokens
+ if v < minOutputTokens {
+ v = minOutputTokens
}
out.MaxCompletionTokens = &v
}
diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go
index b278c28a8..13cc945ca 100644
--- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go
+++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go
@@ -267,6 +267,43 @@ func TestAnthropicToChatCompletionsRequest_MaxTokensFloor(t *testing.T) {
require.Equal(t, minMaxOutputTokens, *out.MaxCompletionTokens)
}
+func TestAnthropicToChatCompletionsRequestWithMinOutputTokens_ConfiguredFloor(t *testing.T) {
+ req := &AnthropicRequest{
+ Model: "claude-sonnet-4-20250514",
+ MaxTokens: 16,
+ Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}},
+ }
+
+ out, err := AnthropicToChatCompletionsRequestWithMinOutputTokens(req, 64)
+ require.NoError(t, err)
+ require.NotNil(t, out.MaxCompletionTokens)
+ require.Equal(t, 64, *out.MaxCompletionTokens)
+}
+
+func TestAnthropicToResponses_ConfiguredMaxTokensFloor(t *testing.T) {
+ for _, input := range []int{16, 64, 127} {
+ req := &AnthropicRequest{
+ Model: "claude-sonnet-4-20250514",
+ MaxTokens: input,
+ Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}},
+ }
+ out, err := AnthropicToResponsesWithMinOutputTokens(req, 16)
+ require.NoError(t, err)
+ require.NotNil(t, out.MaxOutputTokens)
+ require.Equal(t, input, *out.MaxOutputTokens)
+ }
+
+ req := &AnthropicRequest{
+ Model: "claude-sonnet-4-20250514",
+ MaxTokens: 1,
+ Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}},
+ }
+ out, err := AnthropicToResponsesWithMinOutputTokens(req, 16)
+ require.NoError(t, err)
+ require.NotNil(t, out.MaxOutputTokens)
+ require.Equal(t, 16, *out.MaxOutputTokens)
+}
+
func TestAnthropicToChatCompletionsRequest_ReasoningEffortMapping(t *testing.T) {
req := &AnthropicRequest{
Model: "gpt-5.4",
diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_test.go b/backend/internal/pkg/apicompat/chatcompletions_responses_test.go
index 1a27ef237..b94bc5c39 100644
--- a/backend/internal/pkg/apicompat/chatcompletions_responses_test.go
+++ b/backend/internal/pkg/apicompat/chatcompletions_responses_test.go
@@ -2,6 +2,7 @@ package apicompat
import (
"encoding/json"
+ "fmt"
"testing"
"github.com/stretchr/testify/assert"
@@ -290,6 +291,46 @@ func mustMarshalJSON(t *testing.T, value any) []byte {
}
func TestChatCompletionsToResponses_MaxTokens(t *testing.T) {
+ t.Run("default floor", func(t *testing.T) {
+ maxTokens := 1
+ req := &ChatCompletionsRequest{
+ Model: "gpt-4o",
+ MaxTokens: &maxTokens,
+ Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}},
+ }
+ resp, err := ChatCompletionsToResponses(req)
+ require.NoError(t, err)
+ require.NotNil(t, resp.MaxOutputTokens)
+ assert.Equal(t, DefaultMinMaxOutputTokens, *resp.MaxOutputTokens)
+ })
+
+ t.Run("configured floor", func(t *testing.T) {
+ for _, input := range []int{16, 64, 127, 128} {
+ input := input
+ t.Run(fmt.Sprintf("input_%d", input), func(t *testing.T) {
+ req := &ChatCompletionsRequest{
+ Model: "gpt-4o",
+ MaxTokens: &input,
+ Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}},
+ }
+ resp, err := ChatCompletionsToResponsesWithMinOutputTokens(req, 16)
+ require.NoError(t, err)
+ require.NotNil(t, resp.MaxOutputTokens)
+ assert.Equal(t, input, *resp.MaxOutputTokens)
+ })
+ }
+ input := 1
+ req := &ChatCompletionsRequest{
+ Model: "gpt-4o",
+ MaxTokens: &input,
+ Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}},
+ }
+ resp, err := ChatCompletionsToResponsesWithMinOutputTokens(req, 16)
+ require.NoError(t, err)
+ require.NotNil(t, resp.MaxOutputTokens)
+ assert.Equal(t, 16, *resp.MaxOutputTokens)
+ })
+
t.Run("max_tokens", func(t *testing.T) {
maxTokens := 100
req := &ChatCompletionsRequest{
@@ -318,6 +359,21 @@ func TestChatCompletionsToResponses_MaxTokens(t *testing.T) {
require.NotNil(t, resp.MaxOutputTokens)
assert.Equal(t, 500, *resp.MaxOutputTokens)
})
+
+ t.Run("max_completion_tokens_preferred before configured floor", func(t *testing.T) {
+ maxTokens := 500
+ maxCompletion := 1
+ req := &ChatCompletionsRequest{
+ Model: "gpt-4o",
+ MaxTokens: &maxTokens,
+ MaxCompletionTokens: &maxCompletion,
+ Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}},
+ }
+ resp, err := ChatCompletionsToResponsesWithMinOutputTokens(req, 16)
+ require.NoError(t, err)
+ require.NotNil(t, resp.MaxOutputTokens)
+ assert.Equal(t, 16, *resp.MaxOutputTokens)
+ })
}
func TestChatCompletionsToResponses_ReasoningEffort(t *testing.T) {
diff --git a/backend/internal/pkg/apicompat/chatcompletions_to_responses.go b/backend/internal/pkg/apicompat/chatcompletions_to_responses.go
index e7c447d0f..e12e366af 100644
--- a/backend/internal/pkg/apicompat/chatcompletions_to_responses.go
+++ b/backend/internal/pkg/apicompat/chatcompletions_to_responses.go
@@ -18,6 +18,12 @@ type chatMessageContent struct {
// true. store is always false and reasoning.encrypted_content is always
// included so that the response translator has full context.
func ChatCompletionsToResponses(req *ChatCompletionsRequest) (*ResponsesRequest, error) {
+ return ChatCompletionsToResponsesWithMinOutputTokens(req, DefaultMinMaxOutputTokens)
+}
+
+// ChatCompletionsToResponsesWithMinOutputTokens converts a Chat Completions
+// request using the supplied max_output_tokens floor.
+func ChatCompletionsToResponsesWithMinOutputTokens(req *ChatCompletionsRequest, minOutputTokens int) (*ResponsesRequest, error) {
if err := openai.ValidateGPT61SolReasoningEffort(req.Model, req.ReasoningEffort); err != nil {
return nil, err
}
@@ -62,8 +68,8 @@ func ChatCompletionsToResponses(req *ChatCompletionsRequest) (*ResponsesRequest,
}
if maxTokens > 0 {
v := maxTokens
- if v < minMaxOutputTokens {
- v = minMaxOutputTokens
+ if v < minOutputTokens {
+ v = minOutputTokens
}
out.MaxOutputTokens = &v
}
diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_request.go b/backend/internal/pkg/apicompat/responses_to_anthropic_request.go
index 3f5e2933d..e86b510a4 100644
--- a/backend/internal/pkg/apicompat/responses_to_anthropic_request.go
+++ b/backend/internal/pkg/apicompat/responses_to_anthropic_request.go
@@ -16,7 +16,8 @@ import (
func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, error) {
isOpus55 := claude.IsOpus55(req.Model)
isSonnet55 := claude.IsSonnet55(req.Model)
- system, messages, err := convertResponsesInputToAnthropic(req.Instructions, req.Input, isOpus55 || isSonnet55)
+ isHaiku55 := claude.IsHaiku55(req.Model)
+ system, messages, err := convertResponsesInputToAnthropic(req.Instructions, req.Input, isOpus55 || isSonnet55 || isHaiku55)
if err != nil {
return nil, err
}
@@ -56,11 +57,13 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro
out.ToolChoice = tc
}
- // The 5.5 models reject manual thinking and forced tool use. Sonnet 5.5
- // additionally supports between_tools to disable up-front thinking.
+ // The 5.5 models reject manual thinking. Opus/Sonnet 5.5 additionally reject
+ // forced tool use; Haiku 5.5 accepts it (starts with the tool call, no thinking
+ // block). Sonnet 5.5 supports between_tools to disable up-front thinking;
+ // Haiku 5.5 uses disabled (at high effort or below) instead.
// Resolve the upstream model before conversion: client aliases need not
// identify a Claude model.
- if isOpus55 || isSonnet55 {
+ if isOpus55 || isSonnet55 || isHaiku55 {
var choice struct {
Type string `json:"type"`
}
@@ -69,7 +72,7 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro
return nil, fmt.Errorf("invalid tool_choice: %w", err)
}
}
- if choice.Type == "any" || choice.Type == "tool" {
+ if (choice.Type == "any" || choice.Type == "tool") && !isHaiku55 {
return nil, fmt.Errorf("%s does not support forced tool_choice; use auto or none", req.Model)
}
effort := "medium"
@@ -82,6 +85,17 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro
return nil, fmt.Errorf("claude-sonnet-5-5 does not support non-default top_p")
}
}
+ if isHaiku55 {
+ if req.Temperature != nil && *req.Temperature != 1 {
+ return nil, fmt.Errorf("claude-haiku-5-5 does not support non-default temperature")
+ }
+ if req.TopP != nil && *req.TopP != 0.99 {
+ return nil, fmt.Errorf("claude-haiku-5-5 does not support non-default top_p")
+ }
+ if req.Temperature != nil && req.TopP != nil {
+ return nil, fmt.Errorf("claude-haiku-5-5 does not allow temperature and top_p together; omit both")
+ }
+ }
if req.Reasoning != nil && req.Reasoning.Effort != "" {
effort = req.Reasoning.Effort
}
@@ -96,6 +110,16 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro
out.OutputConfig.Effort = "low"
return out, nil
}
+ if isHaiku55 && effort == "none" {
+ // Haiku 5.5's lowest thinking mode is disabled (valid at high
+ // effort or below); low keeps token spend minimal like Sonnet above.
+ out.Thinking = &AnthropicThinking{Type: "disabled"}
+ if out.OutputConfig == nil {
+ out.OutputConfig = &AnthropicOutputConfig{}
+ }
+ out.OutputConfig.Effort = "low"
+ return out, nil
+ }
switch effort {
case "low", "medium", "high", "xhigh", "max":
default:
diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go
index b5864f2f2..956101bd7 100644
--- a/backend/internal/pkg/apicompat/types.go
+++ b/backend/internal/pkg/apicompat/types.go
@@ -860,6 +860,9 @@ func (d ChatDelta) reasoningText() *string {
// Shared constants
// ---------------------------------------------------------------------------
-// minMaxOutputTokens is the floor for max_output_tokens in a Responses request.
-// Very small values may cause upstream API errors, so we enforce a minimum.
-const minMaxOutputTokens = 128
+// DefaultMinMaxOutputTokens is the default floor for max_output_tokens in a
+// Responses request. Very small values may cause upstream API errors, so we
+// enforce a minimum.
+const DefaultMinMaxOutputTokens = 128
+
+const minMaxOutputTokens = DefaultMinMaxOutputTokens
diff --git a/backend/internal/pkg/claude/constants.go b/backend/internal/pkg/claude/constants.go
index 5e0f9fc27..1d0d6d3a3 100644
--- a/backend/internal/pkg/claude/constants.go
+++ b/backend/internal/pkg/claude/constants.go
@@ -223,6 +223,12 @@ var DefaultModels = []Model{
DisplayName: "Claude Haiku 4.5",
CreatedAt: "2025-10-01T00:00:00Z",
},
+ {
+ ID: "claude-haiku-5-5",
+ Type: "model",
+ DisplayName: "Claude Haiku 5.5",
+ CreatedAt: "2026-10-07T00:00:00Z",
+ },
}
// DefaultModelIDs 返回默认模型的 ID 列表
diff --git a/backend/internal/pkg/claude/constants_model_test.go b/backend/internal/pkg/claude/constants_model_test.go
index 4a58d540d..0a15c8d21 100644
--- a/backend/internal/pkg/claude/constants_model_test.go
+++ b/backend/internal/pkg/claude/constants_model_test.go
@@ -43,3 +43,16 @@ func TestDefaultModelsContainsSonnet55(t *testing.T) {
}
t.Fatal("claude-sonnet-5-5 missing from DefaultModels")
}
+
+func TestDefaultModelsContainsHaiku55(t *testing.T) {
+ t.Parallel()
+
+ for _, model := range DefaultModels {
+ if model.ID == "claude-haiku-5-5" {
+ require.Equal(t, "Claude Haiku 5.5", model.DisplayName)
+ require.Equal(t, "2026-10-07T00:00:00Z", model.CreatedAt)
+ return
+ }
+ }
+ t.Fatal("claude-haiku-5-5 missing from DefaultModels")
+}
diff --git a/backend/internal/pkg/claude/effort_catalog.go b/backend/internal/pkg/claude/effort_catalog.go
index a3039faac..2764adc07 100644
--- a/backend/internal/pkg/claude/effort_catalog.go
+++ b/backend/internal/pkg/claude/effort_catalog.go
@@ -27,6 +27,7 @@ var effortFamilies = []struct {
{family: "claude-opus-4-5", levels: effortLowMediumHigh},
{family: "claude-opus-5-5", levels: effortLowMediumHighXHighMax},
{family: "claude-opus-5", levels: effortLowMediumHighXHighMax},
+ {family: "claude-haiku-5-5", levels: effortLowMediumHighXHighMax},
}
// EffortLevelsForModel returns the output_config.effort values accepted by a
@@ -51,6 +52,11 @@ func IsSonnet55(model string) bool {
return normalizeEffortModelID(model) == "claude-sonnet-5-5"
}
+// IsHaiku55 identifies the fixed Haiku 5.5 ID after provider/local suffix normalization.
+func IsHaiku55(model string) bool {
+ return normalizeEffortModelID(model) == "claude-haiku-5-5"
+}
+
func normalizeEffortModelID(model string) string {
id := strings.ToLower(strings.TrimSpace(model))
id = strings.TrimPrefix(id, "models/")
@@ -70,6 +76,9 @@ func normalizeEffortModelID(model string) string {
if id == "claude-sonnet-5.5" {
id = "claude-sonnet-5-5"
}
+ if id == "claude-haiku-5.5" {
+ id = "claude-haiku-5-5"
+ }
if mapped, ok := ModelIDReverseOverrides[id]; ok {
id = mapped
}
diff --git a/backend/internal/pkg/claude/effort_catalog_test.go b/backend/internal/pkg/claude/effort_catalog_test.go
index e8f8e2f15..12f7cd451 100644
--- a/backend/internal/pkg/claude/effort_catalog_test.go
+++ b/backend/internal/pkg/claude/effort_catalog_test.go
@@ -18,6 +18,9 @@ func TestEffortLevelsForModel(t *testing.T) {
{model: "claude-opus-5", want: []string{"low", "medium", "high", "xhigh", "max"}},
{model: "anthropic/claude-opus-5.5", want: []string{"low", "medium", "high", "xhigh", "max"}},
{model: "claude-sonnet-5-5", want: []string{"low", "medium", "high", "xhigh", "max"}},
+ {model: "claude-haiku-5-5", want: []string{"low", "medium", "high", "xhigh", "max"}},
+ {model: "anthropic/claude-haiku-5.5", want: []string{"low", "medium", "high", "xhigh", "max"}},
+ {model: "us.anthropic.claude-haiku-5-5", want: []string{"low", "medium", "high", "xhigh", "max"}},
{model: "us.anthropic.claude-sonnet-5-5", want: []string{"low", "medium", "high", "xhigh", "max"}},
{model: "claude-opus-4-5-20251101", want: []string{"low", "medium", "high"}},
{model: "claude-haiku-4-5-20251001", want: nil},
@@ -57,3 +60,19 @@ func TestIsSonnet55(t *testing.T) {
require.False(t, IsSonnet55(model), model)
}
}
+
+func TestIsHaiku55(t *testing.T) {
+ t.Parallel()
+ for _, model := range []string{
+ "claude-haiku-5-5",
+ "anthropic/claude-haiku-5.5",
+ "anthropic.claude-haiku-5-5",
+ "us.anthropic.claude-haiku-5-5",
+ "global.anthropic.claude-haiku-5-5-thinking",
+ } {
+ require.True(t, IsHaiku55(model), model)
+ }
+ for _, model := range []string{"claude-haiku-5", "claude-haiku-4-5", "claude-haiku-4-5-20251001", "claude-sonnet-5-5", "claude-opus-5-5"} {
+ require.False(t, IsHaiku55(model), model)
+ }
+}
diff --git a/backend/internal/pkg/gemini/models.go b/backend/internal/pkg/gemini/models.go
index d5d4ed64c..1d38fc990 100644
--- a/backend/internal/pkg/gemini/models.go
+++ b/backend/internal/pkg/gemini/models.go
@@ -28,6 +28,7 @@ func DefaultModels() []Model {
{Name: "models/gemini-3.1-pro-preview", SupportedGenerationMethods: methods},
{Name: "models/gemini-3.1-pro-preview-customtools", SupportedGenerationMethods: methods},
{Name: "models/gemini-3.1-flash-image", SupportedGenerationMethods: methods},
+ {Name: "models/gemini-4-argon", SupportedGenerationMethods: methods},
}
}
diff --git a/backend/internal/pkg/geminicli/models.go b/backend/internal/pkg/geminicli/models.go
index cc9cbc80b..4e2fa55bb 100644
--- a/backend/internal/pkg/geminicli/models.go
+++ b/backend/internal/pkg/geminicli/models.go
@@ -20,6 +20,7 @@ var DefaultModels = []Model{
{ID: "gemini-3-pro-preview", Type: "model", DisplayName: "Gemini 3 Pro Preview", CreatedAt: ""},
{ID: "gemini-3.1-pro-preview", Type: "model", DisplayName: "Gemini 3.1 Pro Preview", CreatedAt: ""},
{ID: "gemini-3.1-flash-image", Type: "model", DisplayName: "Gemini 3.1 Flash Image", CreatedAt: ""},
+ {ID: "gemini-4-argon", Type: "model", DisplayName: "Gemini 4 Argon", CreatedAt: ""},
}
// GoogleOneModels is the conservative model set exposed for legacy Google One
diff --git a/backend/internal/repository/api_key_repo.go b/backend/internal/repository/api_key_repo.go
index f92e1e731..b84b871d2 100644
--- a/backend/internal/repository/api_key_repo.go
+++ b/backend/internal/repository/api_key_repo.go
@@ -857,7 +857,7 @@ func (r *apiKeyRepository) ResetRateLimitWindows(ctx context.Context, id int64)
// GetRateLimitData returns the current rate limit usage and window start times for an API key.
func (r *apiKeyRepository) GetRateLimitData(ctx context.Context, id int64) (result *service.APIKeyRateLimitData, err error) {
rows, err := r.sql.QueryContext(ctx, `
- SELECT usage_5h, usage_1d, usage_7d, window_5h_start, window_1d_start, window_7d_start
+ SELECT quota_used, usage_5h, usage_1d, usage_7d, window_5h_start, window_1d_start, window_7d_start
FROM api_keys
WHERE id = $1 AND deleted_at IS NULL`,
id)
@@ -873,7 +873,7 @@ func (r *apiKeyRepository) GetRateLimitData(ctx context.Context, id int64) (resu
return nil, service.ErrAPIKeyNotFound
}
data := &service.APIKeyRateLimitData{}
- if err := rows.Scan(&data.Usage5h, &data.Usage1d, &data.Usage7d, &data.Window5hStart, &data.Window1dStart, &data.Window7dStart); err != nil {
+ if err := rows.Scan(&data.QuotaUsed, &data.Usage5h, &data.Usage1d, &data.Usage7d, &data.Window5hStart, &data.Window1dStart, &data.Window7dStart); err != nil {
return nil, err
}
return data, rows.Err()
@@ -979,6 +979,7 @@ func groupEntityToService(g *dbent.Group) *service.Group {
ID: g.ID,
Name: g.Name,
Description: derefString(g.Description),
+ I18n: g.I18n,
Platform: g.Platform,
RateMultiplier: g.RateMultiplier,
IsExclusive: g.IsExclusive,
diff --git a/backend/internal/repository/api_key_repo_integration_test.go b/backend/internal/repository/api_key_repo_integration_test.go
index 6e1f5db07..637fab9ed 100644
--- a/backend/internal/repository/api_key_repo_integration_test.go
+++ b/backend/internal/repository/api_key_repo_integration_test.go
@@ -464,6 +464,10 @@ func (s *APIKeyRepoSuite) TestIncrementQuotaUsed_Basic() {
newQuota, err = s.repo.IncrementQuotaUsed(s.ctx, key.ID, 2.5)
s.Require().NoError(err, "IncrementQuotaUsed second")
s.Require().Equal(4.0, newQuota, "第二次递增后应为 4.0")
+
+ data, err := s.repo.GetRateLimitData(s.ctx, key.ID)
+ s.Require().NoError(err, "GetRateLimitData")
+ s.Require().Equal(4.0, data.QuotaUsed, "用量读取带回总额度已用量")
}
func (s *APIKeyRepoSuite) TestIncrementQuotaUsed_NotFound() {
diff --git a/backend/internal/repository/billing_inflight_cache.go b/backend/internal/repository/billing_inflight_cache.go
index 1800529b4..0b880c7f3 100644
--- a/backend/internal/repository/billing_inflight_cache.go
+++ b/backend/internal/repository/billing_inflight_cache.go
@@ -25,6 +25,20 @@ func billingInflightKeys(userID int64) (string, string) {
fmt.Sprintf("%s{%d}", billingInflightAmtKeyPrefix, userID)
}
+// 订阅 / API Key 维度在途预留(确定金额费用):
+// - billing:inflight_scope:{scope} ZSET member=requestID score=过期时间(ms)
+// - billing:inflight_scope_amt:{scope} HASH field=requestID value=预留金额(USD)
+//
+// 过期清理与释放语义与余额维度相同,不续期。
+const (
+ billingInflightScopeKeyPrefix = "billing:inflight_scope:"
+ billingInflightScopeAmtKeyPrefix = "billing:inflight_scope_amt:"
+)
+
+func billingInflightScopeKeys(scope string) (string, string) {
+ return billingInflightScopeKeyPrefix + "{" + scope + "}", billingInflightScopeAmtKeyPrefix + "{" + scope + "}"
+}
+
var (
// KEYS: [1]=zset [2]=hash
// ARGV: [1]=now_ms [2]=expire_at_ms [3]=member [4]=amount [5]=balance [6]=key_ttl_ms
@@ -85,6 +99,28 @@ var (
redis.call('HDEL', KEYS[2], ARGV[1])
return 1
`)
+
+ // KEYS: [1]=zset [2]=hash
+ // ARGV: [1]=now_ms [2]=expire_at_ms [3]=member [4]=amount [5]=key_ttl_ms
+ // 先清理已过期成员,再登记本次预留;返回登记前其他在途预留的合计(string),是否放行由调用方按权威用量判定。
+ reserveInflightScopeScript = redis.NewScript(`
+ local now = tonumber(ARGV[1])
+ local expired = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now)
+ if #expired > 0 then
+ redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now)
+ redis.call('HDEL', KEYS[2], unpack(expired))
+ end
+ local vals = redis.call('HVALS', KEYS[2])
+ local sum = 0
+ for i = 1, #vals do
+ sum = sum + (tonumber(vals[i]) or 0)
+ end
+ redis.call('ZADD', KEYS[1], tonumber(ARGV[2]), ARGV[3])
+ redis.call('HSET', KEYS[2], ARGV[3], ARGV[4])
+ redis.call('PEXPIRE', KEYS[1], ARGV[5])
+ redis.call('PEXPIRE', KEYS[2], ARGV[5])
+ return tostring(sum)
+ `)
)
// ReserveInflightBalance 实现 service.InflightBalanceReservationCache。
@@ -138,7 +174,35 @@ func (c *billingCache) RenewInflightBalance(ctx context.Context, userID int64, r
return n == 1, nil
}
+// ReserveInflightScope 实现 service.InflightScopeReservationCache。
+func (c *billingCache) ReserveInflightScope(ctx context.Context, scope, requestID string, amount float64, ttl time.Duration) (float64, error) {
+ zkey, hkey := billingInflightScopeKeys(scope)
+ now := time.Now().UnixMilli()
+ ttlMs := ttl.Milliseconds()
+ if ttlMs <= 0 {
+ ttlMs = 1
+ }
+ res, err := reserveInflightScopeScript.Run(ctx, c.rdb, []string{zkey, hkey},
+ now,
+ now+ttlMs,
+ requestID,
+ strconv.FormatFloat(amount, 'f', -1, 64),
+ ttlMs,
+ ).Text()
+ if err != nil {
+ return 0, err
+ }
+ return strconv.ParseFloat(res, 64)
+}
+
+// ReleaseInflightScope 实现 service.InflightScopeReservationCache。
+func (c *billingCache) ReleaseInflightScope(ctx context.Context, scope, requestID string) error {
+ zkey, hkey := billingInflightScopeKeys(scope)
+ return releaseInflightBalanceScript.Run(ctx, c.rdb, []string{zkey, hkey}, requestID).Err()
+}
+
var (
_ service.InflightBalanceReservationCache = (*billingCache)(nil)
_ service.InflightBalanceReservationRenewer = (*billingCache)(nil)
+ _ service.InflightScopeReservationCache = (*billingCache)(nil)
)
diff --git a/backend/internal/repository/billing_inflight_cache_test.go b/backend/internal/repository/billing_inflight_cache_test.go
index b9af3e4ac..c087395e2 100644
--- a/backend/internal/repository/billing_inflight_cache_test.go
+++ b/backend/internal/repository/billing_inflight_cache_test.go
@@ -285,3 +285,72 @@ func TestInflightReservation_RenewDoesNotResurrectExpiredMember(t *testing.T) {
require.NoError(t, err)
require.False(t, exists)
}
+
+func TestInflightScopeReservation_ReturnsOthersAndReleases(t *testing.T) {
+ mr, cache, _ := newInflightTestEnv(t, true, 60)
+ ctx := context.Background()
+
+ others, err := cache.ReserveInflightScope(ctx, "apikey:7", "r1", 3, time.Minute)
+ require.NoError(t, err)
+ require.Zero(t, others)
+ others, err = cache.ReserveInflightScope(ctx, "apikey:7", "r2", 2, time.Minute)
+ require.NoError(t, err)
+ require.InDelta(t, 3, others, 1e-9, "返回登记前其他在途预留的合计")
+ others, err = cache.ReserveInflightScope(ctx, "sub:7", "r3", 5, time.Minute)
+ require.NoError(t, err)
+ require.Zero(t, others, "不同维度互不影响")
+
+ require.NoError(t, cache.ReleaseInflightScope(ctx, "apikey:7", "r1"))
+ require.NoError(t, cache.ReleaseInflightScope(ctx, "apikey:7", "r1"))
+ others, err = cache.ReserveInflightScope(ctx, "apikey:7", "r4", 1, time.Minute)
+ require.NoError(t, err)
+ require.InDelta(t, 2, others, 1e-9)
+
+ mr.FastForward(2 * time.Minute)
+ others, err = cache.ReserveInflightScope(ctx, "apikey:7", "r5", 1, time.Minute)
+ require.NoError(t, err)
+ require.Zero(t, others, "过期预留不再计入")
+}
+
+func TestReserveFixedCharge_ConcurrentChargesAdmitOnlyWhatAPIKeyQuotaCovers(t *testing.T) {
+ _, cache, svc := newInflightTestEnv(t, true, 60)
+ ctx := context.Background()
+ user := &service.User{ID: 42}
+ apiKey := &service.APIKey{ID: 9, UserID: user.ID, Quota: 1.0}
+ require.NoError(t, cache.SetUserBalance(ctx, user.ID, 100))
+
+ const n = 20
+ var admitted atomic.Int32
+ reservations := make(chan *service.InflightReservation, n)
+ var wg sync.WaitGroup
+ start := make(chan struct{})
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ res, err := svc.ReserveFixedCharge(ctx, user, apiKey, nil, nil, 0.3)
+ if err != nil {
+ if !errors.Is(err, service.ErrAPIKeyQuotaExhausted) {
+ t.Errorf("unexpected error: %v", err)
+ }
+ return
+ }
+ admitted.Add(1)
+ reservations <- res
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(reservations)
+
+ require.Equal(t, int32(3), admitted.Load(), "Key 额度 1.0、每笔 0.3:同时在途的不超过 3 笔")
+ for res := range reservations {
+ res.Release()
+ }
+ zkey, _ := billingInflightScopeKeys("apikey:9")
+ remaining, err := cache.rdb.ZCard(ctx, zkey).Result()
+ require.NoError(t, err)
+ require.Zero(t, remaining)
+ require.Equal(t, int64(0), inflightCount(t, cache, user.ID))
+}
diff --git a/backend/internal/repository/gemini_cached_content_repo.go b/backend/internal/repository/gemini_cached_content_repo.go
new file mode 100644
index 000000000..d1621603d
--- /dev/null
+++ b/backend/internal/repository/gemini_cached_content_repo.go
@@ -0,0 +1,205 @@
+package repository
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/service"
+)
+
+type geminiCachedContentSQLExecutor interface {
+ ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
+ QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
+ QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
+}
+
+type geminiCachedContentRepository struct {
+ sql geminiCachedContentSQLExecutor
+}
+
+func NewGeminiCachedContentRepository(db *sql.DB) service.GeminiCachedContentRepository {
+ return &geminiCachedContentRepository{sql: db}
+}
+
+const geminiCachedContentColumns = `id, public_id, user_id, api_key_id, group_id, account_id, upstream_name, model,
+ upstream_model, display_name, total_token_count, expire_time, channel_usage, created_at, updated_at`
+
+func (r *geminiCachedContentRepository) Create(ctx context.Context, record *service.GeminiCachedContent) error {
+ channelUsage, err := json.Marshal(record.ChannelUsage)
+ if err != nil {
+ return err
+ }
+ row := r.sql.QueryRowContext(ctx, `
+INSERT INTO gemini_cached_contents (public_id, user_id, api_key_id, group_id, account_id, upstream_name, model,
+ upstream_model, display_name, total_token_count, expire_time, channel_usage)
+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
+RETURNING id, created_at, updated_at`,
+ record.PublicID, record.UserID, record.APIKeyID, record.GroupID, record.AccountID, record.UpstreamName,
+ record.Model, record.UpstreamModel, record.DisplayName, record.TotalTokenCount, record.ExpireTime, channelUsage)
+ if err := row.Scan(&record.ID, &record.CreatedAt, &record.UpdatedAt); err != nil {
+ return translatePersistenceError(err, nil, service.ErrGeminiCachedContentExists)
+ }
+ return nil
+}
+
+func (r *geminiCachedContentRepository) GetForOwner(ctx context.Context, apiKeyID int64, publicID string) (*service.GeminiCachedContent, error) {
+ record, err := scanGeminiCachedContent(r.sql.QueryRowContext(ctx, `SELECT `+geminiCachedContentColumns+`
+ FROM gemini_cached_contents
+ WHERE public_id = $1 AND api_key_id = $2 AND deleted_at IS NULL`, publicID, apiKeyID))
+ if err != nil {
+ return nil, translatePersistenceError(err, service.ErrGeminiCachedContentNotFound, nil)
+ }
+ return record, nil
+}
+
+func (r *geminiCachedContentRepository) ListForOwner(ctx context.Context, apiKeyID, groupID int64, activeAt time.Time, beforeID int64, limit int) ([]*service.GeminiCachedContent, error) {
+ if limit <= 0 {
+ limit = service.GeminiCachedContentListDefaultPageSize
+ }
+ rows, err := r.sql.QueryContext(ctx, `SELECT `+geminiCachedContentColumns+`
+ FROM gemini_cached_contents
+ WHERE api_key_id = $1 AND group_id = $2 AND deleted_at IS NULL AND expire_time > $3 AND ($4 <= 0 OR id < $4)
+ ORDER BY id DESC
+ LIMIT $5`, apiKeyID, groupID, activeAt, beforeID, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = rows.Close() }()
+ var out []*service.GeminiCachedContent
+ for rows.Next() {
+ record, err := scanGeminiCachedContent(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, record)
+ }
+ return out, rows.Err()
+}
+
+func (r *geminiCachedContentRepository) BeginMutation(ctx context.Context, id int64, baseline time.Time, token string, lease time.Duration) (bool, error) {
+ result, err := r.sql.ExecContext(ctx, `UPDATE gemini_cached_contents
+ SET mutation_token = $2, mutation_lease_until = NOW() + make_interval(secs => $3::double precision)
+ WHERE id = $1 AND deleted_at IS NULL AND mutation_token IS NULL AND expire_time = $4`,
+ id, token, lease.Seconds(), baseline)
+ if err != nil {
+ return false, err
+ }
+ affected, err := result.RowsAffected()
+ if err != nil {
+ return false, err
+ }
+ if affected > 0 {
+ return true, nil
+ }
+ var exists bool
+ if err := r.sql.QueryRowContext(ctx, `SELECT EXISTS (
+ SELECT 1 FROM gemini_cached_contents WHERE id = $1 AND deleted_at IS NULL)`, id).Scan(&exists); err != nil {
+ return false, err
+ }
+ if !exists {
+ return false, service.ErrGeminiCachedContentNotFound
+ }
+ return false, nil
+}
+
+func (r *geminiCachedContentRepository) TakeOverStaleMutation(ctx context.Context, id int64, token string, lease time.Duration) (*service.GeminiCachedContent, error) {
+ record, err := scanGeminiCachedContent(r.sql.QueryRowContext(ctx, `UPDATE gemini_cached_contents
+ SET mutation_token = $2, mutation_lease_until = NOW() + make_interval(secs => $3::double precision)
+ WHERE id = $1 AND deleted_at IS NULL AND mutation_token IS NOT NULL AND mutation_lease_until < NOW()
+ RETURNING `+geminiCachedContentColumns, id, token, lease.Seconds()))
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return record, nil
+}
+
+func (r *geminiCachedContentRepository) CommitMutation(ctx context.Context, id int64, token string, expireTime time.Time) error {
+ result, err := r.sql.ExecContext(ctx, `UPDATE gemini_cached_contents
+ SET expire_time = $3, updated_at = NOW(), mutation_token = NULL, mutation_lease_until = NULL
+ WHERE id = $1 AND deleted_at IS NULL AND mutation_token = $2`, id, token, expireTime)
+ if err != nil {
+ return err
+ }
+ affected, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if affected == 0 {
+ return service.ErrGeminiCachedContentMutationConflict
+ }
+ return nil
+}
+
+func (r *geminiCachedContentRepository) ReleaseMutation(ctx context.Context, id int64, token string) error {
+ _, err := r.sql.ExecContext(ctx, `UPDATE gemini_cached_contents
+ SET mutation_token = NULL, mutation_lease_until = NULL
+ WHERE id = $1 AND mutation_token = $2`, id, token)
+ return err
+}
+
+func (r *geminiCachedContentRepository) ListStaleMutations(ctx context.Context, limit int) ([]int64, error) {
+ rows, err := r.sql.QueryContext(ctx, `SELECT id FROM gemini_cached_contents
+ WHERE mutation_token IS NOT NULL AND deleted_at IS NULL AND mutation_lease_until < NOW()
+ ORDER BY mutation_lease_until
+ LIMIT $1`, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = rows.Close() }()
+ var ids []int64
+ for rows.Next() {
+ var id int64
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ ids = append(ids, id)
+ }
+ return ids, rows.Err()
+}
+
+func (r *geminiCachedContentRepository) SoftDelete(ctx context.Context, id int64) error {
+ _, err := r.sql.ExecContext(ctx, `UPDATE gemini_cached_contents
+ SET deleted_at = NOW(), updated_at = NOW()
+ WHERE id = $1 AND deleted_at IS NULL`, id)
+ return err
+}
+
+type geminiCachedContentScanner interface {
+ Scan(dest ...any) error
+}
+
+func scanGeminiCachedContent(row geminiCachedContentScanner) (*service.GeminiCachedContent, error) {
+ var record service.GeminiCachedContent
+ var channelUsage []byte
+ if err := row.Scan(
+ &record.ID,
+ &record.PublicID,
+ &record.UserID,
+ &record.APIKeyID,
+ &record.GroupID,
+ &record.AccountID,
+ &record.UpstreamName,
+ &record.Model,
+ &record.UpstreamModel,
+ &record.DisplayName,
+ &record.TotalTokenCount,
+ &record.ExpireTime,
+ &channelUsage,
+ &record.CreatedAt,
+ &record.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ if len(channelUsage) > 0 {
+ if err := json.Unmarshal(channelUsage, &record.ChannelUsage); err != nil {
+ return nil, err
+ }
+ }
+ return &record, nil
+}
diff --git a/backend/internal/repository/gemini_cached_content_repo_integration_test.go b/backend/internal/repository/gemini_cached_content_repo_integration_test.go
new file mode 100644
index 000000000..5a003207f
--- /dev/null
+++ b/backend/internal/repository/gemini_cached_content_repo_integration_test.go
@@ -0,0 +1,120 @@
+//go:build integration
+
+package repository
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/stretchr/testify/require"
+)
+
+func TestGeminiCachedContentRepository_Lifecycle(t *testing.T) {
+ ctx := context.Background()
+ tx := testTx(t)
+ repo := &geminiCachedContentRepository{sql: tx}
+ now := time.Now().UTC().Truncate(time.Microsecond)
+ suffix := time.Now().Format("150405.000000")
+ apiKeyID := int64(910001)
+
+ newRecord := func(publicID string, keyID, groupID int64, expire time.Time) *service.GeminiCachedContent {
+ return &service.GeminiCachedContent{
+ PublicID: publicID + suffix, UserID: 1, APIKeyID: keyID, GroupID: groupID, AccountID: 99,
+ UpstreamName: "cachedContents/up" + publicID, Model: "gemini-3.8-flash", UpstreamModel: "models/gemini-3.8-flash",
+ DisplayName: "label", TotalTokenCount: 2730, ExpireTime: expire,
+ ChannelUsage: service.ChannelUsageFields{ChannelID: 7, OriginalModel: "gemini-pro", ChannelMappedModel: "gemini-3.8-flash", BillingModelSource: "requested"},
+ }
+ }
+ first := newRecord("a", apiKeyID, 42, now.Add(time.Hour))
+ require.NoError(t, repo.Create(ctx, first))
+ require.Positive(t, first.ID)
+ require.False(t, first.CreatedAt.IsZero())
+ _, err := tx.ExecContext(ctx, `SAVEPOINT gemini_cached_content_duplicate`)
+ require.NoError(t, err)
+ require.ErrorIs(t, repo.Create(ctx, newRecord("a", apiKeyID, 42, now.Add(time.Hour))), service.ErrGeminiCachedContentExists)
+ _, err = tx.ExecContext(ctx, `ROLLBACK TO SAVEPOINT gemini_cached_content_duplicate`)
+ require.NoError(t, err)
+
+ second := newRecord("b", apiKeyID, 42, now.Add(time.Hour))
+ require.NoError(t, repo.Create(ctx, second))
+ require.NoError(t, repo.Create(ctx, newRecord("expired", apiKeyID, 42, now.Add(-time.Minute))))
+ require.NoError(t, repo.Create(ctx, newRecord("othergroup", apiKeyID, 43, now.Add(time.Hour))))
+ require.NoError(t, repo.Create(ctx, newRecord("otherkey", apiKeyID+1, 42, now.Add(time.Hour))))
+
+ got, err := repo.GetForOwner(ctx, apiKeyID, first.PublicID)
+ require.NoError(t, err)
+ require.Equal(t, "cachedContents/upa", got.UpstreamName)
+ require.Equal(t, int64(2730), got.TotalTokenCount)
+ require.True(t, got.ExpireTime.Equal(first.ExpireTime))
+ require.Equal(t, first.ChannelUsage, got.ChannelUsage, "创建时的渠道计费口径随记录持久化")
+ _, err = repo.GetForOwner(ctx, apiKeyID+1, first.PublicID)
+ require.ErrorIs(t, err, service.ErrGeminiCachedContentNotFound)
+
+ list, err := repo.ListForOwner(ctx, apiKeyID, 42, now, 0, 10)
+ require.NoError(t, err)
+ require.Len(t, list, 2)
+ require.Equal(t, second.PublicID, list[0].PublicID)
+ page, err := repo.ListForOwner(ctx, apiKeyID, 42, now, list[0].ID, 10)
+ require.NoError(t, err)
+ require.Len(t, page, 1)
+ require.Equal(t, first.PublicID, page[0].PublicID)
+
+ lease := 2 * time.Minute
+ acquired, err := repo.BeginMutation(ctx, first.ID, first.ExpireTime, "t1", lease)
+ require.NoError(t, err)
+ require.True(t, acquired)
+ acquired, err = repo.BeginMutation(ctx, first.ID, first.ExpireTime, "t2", lease)
+ require.NoError(t, err)
+ require.False(t, acquired, "有进行中的修改时不能再登记")
+ taken, err := repo.TakeOverStaleMutation(ctx, first.ID, "t2", lease)
+ require.NoError(t, err)
+ require.Nil(t, taken, "租约未过期不能接管")
+ require.ErrorIs(t, repo.CommitMutation(ctx, first.ID, "t2", now), service.ErrGeminiCachedContentMutationConflict)
+
+ newExpire := now.Add(3 * time.Hour)
+ require.NoError(t, repo.CommitMutation(ctx, first.ID, "t1", newExpire))
+ got, err = repo.GetForOwner(ctx, apiKeyID, first.PublicID)
+ require.NoError(t, err)
+ require.True(t, got.ExpireTime.Equal(newExpire))
+ require.ErrorIs(t, repo.CommitMutation(ctx, first.ID, "t1", now), service.ErrGeminiCachedContentMutationConflict, "提交后修改意图已清除")
+
+ acquired, err = repo.BeginMutation(ctx, first.ID, first.ExpireTime, "t3", lease)
+ require.NoError(t, err)
+ require.False(t, acquired, "到期时间已被其他修改改变")
+ acquired, err = repo.BeginMutation(ctx, first.ID, newExpire, "t3", lease)
+ require.NoError(t, err)
+ require.True(t, acquired)
+ stale, err := repo.ListStaleMutations(ctx, 10)
+ require.NoError(t, err)
+ require.NotContains(t, stale, first.ID)
+
+ _, err = tx.ExecContext(ctx, `UPDATE gemini_cached_contents SET mutation_lease_until = NOW() - INTERVAL '1 second' WHERE id = $1`, first.ID)
+ require.NoError(t, err)
+ stale, err = repo.ListStaleMutations(ctx, 10)
+ require.NoError(t, err)
+ require.Contains(t, stale, first.ID)
+ taken, err = repo.TakeOverStaleMutation(ctx, first.ID, "t4", lease)
+ require.NoError(t, err)
+ require.NotNil(t, taken)
+ require.True(t, taken.ExpireTime.Equal(newExpire), "接管返回修改前的到期时间")
+ require.ErrorIs(t, repo.CommitMutation(ctx, first.ID, "t3", now), service.ErrGeminiCachedContentMutationConflict, "被接管后原持有者不能提交")
+ require.NoError(t, repo.ReleaseMutation(ctx, first.ID, "t3"))
+ acquired, err = repo.BeginMutation(ctx, first.ID, newExpire, "t5", lease)
+ require.NoError(t, err)
+ require.False(t, acquired, "原持有者释放不影响接管者")
+ require.NoError(t, repo.ReleaseMutation(ctx, first.ID, "t4"))
+ stale, err = repo.ListStaleMutations(ctx, 10)
+ require.NoError(t, err)
+ require.NotContains(t, stale, first.ID)
+
+ require.NoError(t, repo.SoftDelete(ctx, first.ID))
+ _, err = repo.GetForOwner(ctx, apiKeyID, first.PublicID)
+ require.ErrorIs(t, err, service.ErrGeminiCachedContentNotFound)
+ _, err = repo.BeginMutation(ctx, first.ID, newExpire, "t6", lease)
+ require.ErrorIs(t, err, service.ErrGeminiCachedContentNotFound)
+ list, err = repo.ListForOwner(ctx, apiKeyID, 42, now, 0, 10)
+ require.NoError(t, err)
+ require.Len(t, list, 1)
+}
diff --git a/backend/internal/repository/group_repo.go b/backend/internal/repository/group_repo.go
index 2d2803365..8a0b32973 100644
--- a/backend/internal/repository/group_repo.go
+++ b/backend/internal/repository/group_repo.go
@@ -167,6 +167,10 @@ func createGroupRecord(ctx context.Context, client *dbent.Client, groupIn *servi
// 设置支持的模型系列(始终设置,空数组表示不限制)
builder = builder.SetSupportedModelScopes(groupIn.SupportedModelScopes)
+ if groupIn.I18n != nil {
+ builder = builder.SetI18n(groupIn.I18n)
+ }
+
created, err := builder.Save(ctx)
if err != nil {
return translatePersistenceError(err, nil, service.ErrGroupExists)
@@ -431,6 +435,12 @@ func (r *groupRepository) Update(ctx context.Context, groupIn *service.Group) er
// 处理 SupportedModelScopes(始终设置,空数组表示不限制)
builder = builder.SetSupportedModelScopes(groupIn.SupportedModelScopes)
+ i18n := groupIn.I18n
+ if i18n == nil {
+ i18n = service.GroupI18n{}
+ }
+ builder = builder.SetI18n(i18n)
+
updated, err := builder.Save(ctx)
if err != nil {
return translatePersistenceError(err, service.ErrGroupNotFound, service.ErrGroupExists)
@@ -957,6 +967,29 @@ func (r *groupRepository) deleteCascade(ctx context.Context, id int64, requireEm
if _, err := txClient.Group.Delete().Where(group.IDEQ(id)).Exec(ctx); err != nil {
return nil, err
}
+ // Lock and validate the text value before using JSONB operators. A legacy
+ // malformed setting must not prevent deletion or be silently replaced.
+ var moderationValue string
+ err = scanSingleRow(ctx, exec, `SELECT value FROM settings WHERE key = $1 FOR UPDATE`,
+ []any{service.SettingKeyContentModerationConfig}, &moderationValue)
+ if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return nil, err
+ }
+ // Keep the moderation scope in sync in the same transaction. Updating the
+ // setting row in SQL also serializes concurrent group deletions across nodes.
+ if err == nil && json.Valid([]byte(moderationValue)) {
+ if _, err := exec.ExecContext(ctx, `UPDATE settings
+ SET value = jsonb_set(value::jsonb, '{group_ids}',
+ (SELECT COALESCE(jsonb_agg(group_id ORDER BY ord), '[]'::jsonb)
+ FROM jsonb_array_elements(value::jsonb->'group_ids') WITH ORDINALITY AS ids(group_id, ord)
+ WHERE group_id <> to_jsonb($2::bigint)))::text,
+ updated_at = NOW()
+ WHERE key = $1 AND jsonb_typeof(value::jsonb->'group_ids') = 'array'
+ AND value::jsonb->'group_ids' @> jsonb_build_array($2::bigint)`,
+ service.SettingKeyContentModerationConfig, id); err != nil {
+ return nil, err
+ }
+ }
if tx != nil {
if err := tx.Commit(); err != nil {
diff --git a/backend/internal/repository/group_repo_integration_test.go b/backend/internal/repository/group_repo_integration_test.go
index 662dcf03d..a89dfea1a 100644
--- a/backend/internal/repository/group_repo_integration_test.go
+++ b/backend/internal/repository/group_repo_integration_test.go
@@ -5,7 +5,9 @@ package repository
import (
"context"
"database/sql"
+ "encoding/json"
"errors"
+ "fmt"
"strings"
"testing"
"time"
@@ -49,6 +51,55 @@ func TestGroupRepoSuite(t *testing.T) {
suite.Run(t, new(GroupRepoSuite))
}
+func TestModerationConfigWriteRejectsGroupDeletedAfterValidation(t *testing.T) {
+ ctx := context.Background()
+ client := testEntClient(t)
+ repo := newGroupRepositoryWithSQL(client, integrationDB)
+ settings := &settingRepository{client: client}
+ group := &service.Group{Name: "moderation-concurrent-delete", Platform: service.PlatformAnthropic, RateMultiplier: 1, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard}
+ require.NoError(t, repo.Create(ctx, group))
+ t.Cleanup(func() { _, _ = integrationDB.ExecContext(ctx, "DELETE FROM groups WHERE id=$1", group.ID) })
+ key := service.SettingKeyContentModerationConfig
+ previous, previousErr := settings.GetValue(ctx, key)
+ t.Cleanup(func() {
+ if previousErr == nil {
+ _ = settings.Set(ctx, key, previous)
+ } else {
+ _ = settings.Delete(ctx, key)
+ }
+ })
+ require.NoError(t, settings.Set(ctx, key, `{"all_groups":false,"group_ids":[]}`))
+
+ // Hold the deleter's group lock while the config writer starts with an ID
+ // that was valid before deletion. It must recheck after this transaction commits.
+ tx, err := integrationDB.BeginTx(ctx, nil)
+ require.NoError(t, err)
+ defer func() { _ = tx.Rollback() }()
+ var id int64
+ require.NoError(t, tx.QueryRowContext(ctx, "SELECT id FROM groups WHERE id=$1 FOR UPDATE", group.ID).Scan(&id))
+ finished := make(chan error, 1)
+ go func() {
+ finished <- settings.SetContentModerationConfig(ctx, `{"all_groups":false,"group_ids":[`+fmt.Sprint(group.ID)+`]}`, []int64{group.ID})
+ }()
+ select {
+ case err := <-finished:
+ t.Fatalf("config write passed a locked group before deletion: %v", err)
+ case <-time.After(100 * time.Millisecond):
+ }
+ _, err = tx.ExecContext(ctx, "UPDATE groups SET deleted_at=NOW() WHERE id=$1", group.ID)
+ require.NoError(t, err)
+ require.NoError(t, tx.Commit())
+ select {
+ case err := <-finished:
+ require.ErrorIs(t, err, service.ErrGroupNotFound)
+ case <-time.After(5 * time.Second):
+ t.Fatal("config write did not finish after deletion")
+ }
+ stored, err := settings.GetValue(ctx, key)
+ require.NoError(t, err)
+ require.JSONEq(t, `{"all_groups":false,"group_ids":[]}`, stored)
+}
+
// --- Create / GetByID / Update / Delete ---
func (s *GroupRepoSuite) TestCreate() {
@@ -201,6 +252,48 @@ func (s *GroupRepoSuite) TestUpdate() {
s.Require().Equal("updated", got.Name)
}
+func (s *GroupRepoSuite) TestI18n_RoundTrip() {
+ group := &service.Group{
+ Name: "i18n-roundtrip",
+ Platform: service.PlatformAnthropic,
+ RateMultiplier: 1.0,
+ Status: service.StatusActive,
+ SubscriptionType: service.SubscriptionTypeStandard,
+ I18n: service.GroupI18n{
+ "en": {Name: "Standard", Description: "Pro + Max pool"},
+ },
+ }
+ s.Require().NoError(s.repo.Create(s.ctx, group))
+
+ got, err := s.repo.GetByID(s.ctx, group.ID)
+ s.Require().NoError(err)
+ s.Require().Equal(group.I18n, got.I18n)
+
+ got.I18n = service.GroupI18n{"zh": {Description: "号池"}}
+ s.Require().NoError(s.repo.Update(s.ctx, got))
+ got, err = s.repo.GetByID(s.ctx, group.ID)
+ s.Require().NoError(err)
+ s.Require().Equal(service.GroupI18n{"zh": {Description: "号池"}}, got.I18n)
+
+ // 未携带译文的写入落库为空对象,而不是 JSON null。
+ got.I18n = nil
+ s.Require().NoError(s.repo.Update(s.ctx, got))
+ var stored string
+ s.Require().NoError(scanSingleRow(s.ctx, s.tx, "SELECT i18n::text FROM groups WHERE id = $1", []any{group.ID}, &stored))
+ s.Require().Equal("{}", stored)
+
+ plain := &service.Group{
+ Name: "i18n-default",
+ Platform: service.PlatformAnthropic,
+ RateMultiplier: 1.0,
+ Status: service.StatusActive,
+ SubscriptionType: service.SubscriptionTypeStandard,
+ }
+ s.Require().NoError(s.repo.Create(s.ctx, plain))
+ s.Require().NoError(scanSingleRow(s.ctx, s.tx, "SELECT i18n::text FROM groups WHERE id = $1", []any{plain.ID}, &stored))
+ s.Require().Equal("{}", stored)
+}
+
func (s *GroupRepoSuite) TestGetByID_PreservesMessagesDispatchModelConfig() {
group := &service.Group{
Name: "openai-dispatch",
@@ -257,8 +350,14 @@ func (s *GroupRepoSuite) TestDeleteCascadeIfEmptyRejectsGroupWithNonDeletedAccou
_, err := s.tx.ExecContext(s.ctx, "INSERT INTO account_groups (account_id, group_id, priority, created_at) VALUES ($1, $2, 1, NOW())", accountID, group.ID)
s.Require().NoError(err)
+ config, marshalErr := json.Marshal(map[string]any{"group_ids": []int64{group.ID}, "all_groups": false})
+ s.Require().NoError(marshalErr)
+ s.Require().NoError(NewSettingRepository(s.tx.Client()).Set(s.ctx, service.SettingKeyContentModerationConfig, string(config)))
_, err = s.repo.DeleteCascadeIfEmpty(s.ctx, group.ID)
s.Require().ErrorIs(err, service.ErrGroupNotEmpty)
+ stored, readErr := NewSettingRepository(s.tx.Client()).GetValue(s.ctx, service.SettingKeyContentModerationConfig)
+ s.Require().NoError(readErr)
+ s.Require().JSONEq(string(config), stored)
_, err = s.repo.GetByID(s.ctx, group.ID)
s.Require().NoError(err)
var bindings int
@@ -276,6 +375,76 @@ func (s *GroupRepoSuite) TestDeleteCascadeIfEmptyDeletesEmptyGroup() {
s.Require().ErrorIs(err, service.ErrGroupNotFound)
}
+func (s *GroupRepoSuite) TestDeleteCascadeRemovesOnlySelectedModerationGroup() {
+ for _, guarded := range []bool{false, true} {
+ name := map[bool]string{false: "normal", true: "guarded"}[guarded]
+ s.Run(name, func() {
+ deleted := &service.Group{Name: "moderation-deleted-" + name, Platform: service.PlatformAnthropic, RateMultiplier: 1, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard}
+ kept := &service.Group{Name: "moderation-kept-" + name, Platform: service.PlatformAnthropic, RateMultiplier: 1, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard}
+ s.Require().NoError(s.repo.Create(s.ctx, deleted))
+ s.Require().NoError(s.repo.Create(s.ctx, kept))
+ config := map[string]any{"group_ids": []int64{kept.ID, deleted.ID}, "all_groups": false, "mode": "observe"}
+ raw, err := json.Marshal(config)
+ s.Require().NoError(err)
+ s.Require().NoError(NewSettingRepository(s.tx.Client()).Set(s.ctx, service.SettingKeyContentModerationConfig, string(raw)))
+ if guarded {
+ _, err = s.repo.DeleteCascadeIfEmpty(s.ctx, deleted.ID)
+ } else {
+ _, err = s.repo.DeleteCascade(s.ctx, deleted.ID)
+ }
+ s.Require().NoError(err)
+ stored, err := NewSettingRepository(s.tx.Client()).GetValue(s.ctx, service.SettingKeyContentModerationConfig)
+ s.Require().NoError(err)
+ var got struct {
+ GroupIDs []int64 `json:"group_ids"`
+ Mode string `json:"mode"`
+ }
+ s.Require().NoError(json.Unmarshal([]byte(stored), &got))
+ s.Require().Equal([]int64{kept.ID}, got.GroupIDs)
+ s.Require().Equal("observe", got.Mode)
+ })
+ }
+}
+
+func (s *GroupRepoSuite) TestDeleteCascadeUnknownGroupPreservesModerationConfig() {
+ const original = `{"all_groups":false,"group_ids":[123,456],"mode":"observe"}`
+ s.Require().NoError(NewSettingRepository(s.tx.Client()).Set(s.ctx, service.SettingKeyContentModerationConfig, original))
+ for _, guarded := range []bool{false, true} {
+ var err error
+ if guarded {
+ _, err = s.repo.DeleteCascadeIfEmpty(s.ctx, -1)
+ } else {
+ _, err = s.repo.DeleteCascade(s.ctx, -1)
+ }
+ s.Require().ErrorIs(err, service.ErrGroupNotFound)
+ stored, readErr := NewSettingRepository(s.tx.Client()).GetValue(s.ctx, service.SettingKeyContentModerationConfig)
+ s.Require().NoError(readErr)
+ s.Require().JSONEq(original, stored)
+ }
+}
+
+func (s *GroupRepoSuite) TestDeleteCascadePreservesMalformedModerationConfig() {
+ for _, guarded := range []bool{false, true} {
+ name := map[bool]string{false: "normal", true: "guarded"}[guarded]
+ s.Run(name, func() {
+ group := &service.Group{Name: "malformed-moderation-" + name, Platform: service.PlatformAnthropic, RateMultiplier: 1, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard}
+ s.Require().NoError(s.repo.Create(s.ctx, group))
+ const malformed = `{"group_ids":[oops]}`
+ s.Require().NoError(NewSettingRepository(s.tx.Client()).Set(s.ctx, service.SettingKeyContentModerationConfig, malformed))
+ var err error
+ if guarded {
+ _, err = s.repo.DeleteCascadeIfEmpty(s.ctx, group.ID)
+ } else {
+ _, err = s.repo.DeleteCascade(s.ctx, group.ID)
+ }
+ s.Require().NoError(err)
+ stored, err := NewSettingRepository(s.tx.Client()).GetValue(s.ctx, service.SettingKeyContentModerationConfig)
+ s.Require().NoError(err)
+ s.Require().Equal(malformed, stored)
+ })
+ }
+}
+
func (s *GroupRepoSuite) TestDeleteCascadeIfEmptyIgnoresBindingsToSoftDeletedAccounts() {
group := &service.Group{Name: "guarded-soft-deleted-account", Platform: service.PlatformAnthropic, RateMultiplier: 1, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard}
s.Require().NoError(s.repo.Create(s.ctx, group))
diff --git a/backend/internal/repository/migrations_runner.go b/backend/internal/repository/migrations_runner.go
index fee406341..4dc1bea0d 100644
--- a/backend/internal/repository/migrations_runner.go
+++ b/backend/internal/repository/migrations_runner.go
@@ -96,6 +96,9 @@ var migrationChecksumCompatibilityRules = map[string]migrationChecksumCompatibil
"220_clear_non_grok_video_generation_config.sql": newMigrationChecksumCompatibilityRule("85e320b9ec64f2d3fcd8cf705b2b4e76a7b49f7a57140c14bff97f32691c818b", "3da48c8fdffe6390325f43d08b8e353e0a365df43d44a78dbbe655d0deb18402"),
"219_group_search_price_per_1k.sql": newMigrationChecksumCompatibilityRule("e86786ebcc3b14206fd2d321380a4e50e80cdadbfcf4962c639255e6a14008db", "df6ffd71b97e30ec2c8fe7b95e15783042dea58c553e32701ee7c42a5619af80"),
"218_group_audio_voice_pricing.sql": newMigrationChecksumCompatibilityRule("40ee9f3a2af0e0a5e99dabc878fd0fe98be1011f26bcfcefcac7197f7081f0e7", "c2a5e5b4ffd6968ad1c10593289fbc11192cdea19fec3ed9bce3a84eff9a8351"),
+ // Sub4API 1.1.10 曾修改上游 241(加入 openai_bps);文件已恢复为上游版本,
+ // 250_sub4api_normalize_241_checksum.sql 会把存量库 checksum 归一为上游值,此规则覆盖 250 执行前的那次启动。
+ "241_add_typesafe_platform.sql": newMigrationChecksumCompatibilityRule("b6559525bf8d0b5d7c617e7415944f0d1fae8c408e9131ace84139795f66dcd2", "6034ab0415266a5299a64d49f56b52dab8c61a3c5b2eaa82327c81cc5698a871"),
}
// ApplyMigrations 将嵌入的 SQL 迁移文件应用到指定的数据库。
diff --git a/backend/internal/repository/migrations_runner_checksum_test.go b/backend/internal/repository/migrations_runner_checksum_test.go
index 1fcb3be1e..1c546f3d5 100644
--- a/backend/internal/repository/migrations_runner_checksum_test.go
+++ b/backend/internal/repository/migrations_runner_checksum_test.go
@@ -3,6 +3,7 @@ package repository
import (
"testing"
+ dbmigrations "github.com/MACOS-DO/sub4api/migrations"
"github.com/stretchr/testify/require"
)
@@ -161,4 +162,40 @@ func TestIsMigrationChecksumCompatible(t *testing.T) {
)
require.False(t, ok)
})
+
+ t.Run("241 Sub4API历史checksum可兼容上游版本", func(t *testing.T) {
+ ok := isMigrationChecksumCompatible(
+ "241_add_typesafe_platform.sql",
+ "6034ab0415266a5299a64d49f56b52dab8c61a3c5b2eaa82327c81cc5698a871",
+ "b6559525bf8d0b5d7c617e7415944f0d1fae8c408e9131ace84139795f66dcd2",
+ )
+ require.True(t, ok)
+ })
+
+ t.Run("241未知checksum不兼容", func(t *testing.T) {
+ ok := isMigrationChecksumCompatible(
+ "241_add_typesafe_platform.sql",
+ "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
+ "b6559525bf8d0b5d7c617e7415944f0d1fae8c408e9131ace84139795f66dcd2",
+ )
+ require.False(t, ok)
+ })
+}
+
+// 241 的兼容规则与 241_0 / 250 中硬编码的上游 checksum 必须与内嵌文件一致。
+func TestMigration241ChecksumMatchesUpstreamFile(t *testing.T) {
+ const upstream = "b6559525bf8d0b5d7c617e7415944f0d1fae8c408e9131ace84139795f66dcd2"
+ content, err := dbmigrations.FS.ReadFile("241_add_typesafe_platform.sql")
+ require.NoError(t, err)
+ require.Equal(t, upstream, migrationChecksum(string(content)))
+ require.Equal(t, upstream, migrationChecksumCompatibilityRules["241_add_typesafe_platform.sql"].fileChecksum)
+
+ for _, name := range []string{
+ "241_0_sub4api_skip_typesafe_constraint_for_openai_bps.sql",
+ "250_sub4api_normalize_241_checksum.sql",
+ } {
+ content, err := dbmigrations.FS.ReadFile(name)
+ require.NoError(t, err)
+ require.Containsf(t, string(content), upstream, "%s must reference upstream 241 checksum", name)
+ }
}
diff --git a/backend/internal/repository/proxy_probe_service.go b/backend/internal/repository/proxy_probe_service.go
index 7cbaf63fb..a7b5b845a 100644
--- a/backend/internal/repository/proxy_probe_service.go
+++ b/backend/internal/repository/proxy_probe_service.go
@@ -168,6 +168,7 @@ func (s *proxyProbeService) parseIPAPI(body []byte, latencyMs int64) (*service.P
RegionName string `json:"regionName"`
Country string `json:"country"`
CountryCode string `json:"countryCode"`
+ Timezone string `json:"timezone"`
}
if err := json.Unmarshal(body, &ipInfo); err != nil {
@@ -194,6 +195,7 @@ func (s *proxyProbeService) parseIPAPI(body []byte, latencyMs int64) (*service.P
Region: region,
Country: ipInfo.Country,
CountryCode: ipInfo.CountryCode,
+ Timezone: ipInfo.Timezone,
}, latencyMs, nil
}
diff --git a/backend/internal/repository/proxy_probe_service_test.go b/backend/internal/repository/proxy_probe_service_test.go
index 45c342cb4..73976a390 100644
--- a/backend/internal/repository/proxy_probe_service_test.go
+++ b/backend/internal/repository/proxy_probe_service_test.go
@@ -133,7 +133,7 @@ func (s *ProxyProbeServiceSuite) TestProbeProxy_ProxyServerClosed() {
}
func (s *ProxyProbeServiceSuite) TestParseIPAPI_Success() {
- body := []byte(`{"status":"success","query":"1.2.3.4","city":"Beijing","regionName":"Beijing","country":"China","countryCode":"CN"}`)
+ body := []byte(`{"status":"success","query":"1.2.3.4","city":"Beijing","regionName":"Beijing","country":"China","countryCode":"CN","timezone":"Asia/Shanghai"}`)
info, latencyMs, err := s.prober.parseIPAPI(body, 100)
require.NoError(s.T(), err)
require.Equal(s.T(), int64(100), latencyMs)
@@ -142,6 +142,7 @@ func (s *ProxyProbeServiceSuite) TestParseIPAPI_Success() {
require.Equal(s.T(), "Beijing", info.Region)
require.Equal(s.T(), "China", info.Country)
require.Equal(s.T(), "CN", info.CountryCode)
+ require.Equal(s.T(), "Asia/Shanghai", info.Timezone)
}
func (s *ProxyProbeServiceSuite) TestParseIPAPI_Failure() {
diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go
index 7429f250f..2ff87caf5 100644
--- a/backend/internal/repository/scheduler_cache.go
+++ b/backend/internal/repository/scheduler_cache.go
@@ -999,7 +999,11 @@ func filterSchedulerCredentials(credentials map[string]any) map[string]any {
// the full account. Dropping it silently falls back to the platform threshold.
// BPS admission also needs workspace identity and JWT expiry before hydration;
// neither access_token nor refresh_token belongs in this metadata projection.
- keys := []string{"model_mapping", "compact_model_mapping", "api_key", "project_id", "oauth_type", "plan_type", "account_scheduling_threshold", "chatgpt_account_id", "expires_at"}
+ keys := []string{"model_mapping", "compact_model_mapping", "api_key", "project_id", "oauth_type", "plan_type", "account_scheduling_threshold", "chatgpt_account_id", "expires_at",
+ // Gemini 显式缓存的候选过滤(GeminiExplicitCacheExclusions)读本投影判定账号是否支持显式缓存:
+ // 官方地址、Vertex 认证方式与上游网关的显式缓存声明。缺这几个键时只能按类型粗筛,
+ // 不支持的账号要逐个选中后才被剔除。
+ "base_url", "auth_mode", service.GeminiExplicitCacheUpstreamCredentialKey, service.GeminiExplicitCacheUpstreamMaxTTLCredentialKey}
filtered := make(map[string]any)
for _, key := range keys {
if value, ok := credentials[key]; ok && value != nil {
diff --git a/backend/internal/repository/scheduler_cache_test.go b/backend/internal/repository/scheduler_cache_test.go
index 81231b308..bd8203ed2 100644
--- a/backend/internal/repository/scheduler_cache_test.go
+++ b/backend/internal/repository/scheduler_cache_test.go
@@ -20,6 +20,23 @@ func TestFilterSchedulerCredentialsKeepsSubscriptionPlanType(t *testing.T) {
require.NotContains(t, filtered, "refresh_token")
}
+func TestFilterSchedulerCredentialsKeepsGeminiExplicitCacheKeys(t *testing.T) {
+ filtered := filterSchedulerCredentials(map[string]any{
+ "api_key": "k",
+ "base_url": "https://gw.example.com",
+ "auth_mode": "apikey",
+ "service_account_json": "secret",
+ service.GeminiExplicitCacheUpstreamCredentialKey: true,
+ service.GeminiExplicitCacheUpstreamMaxTTLCredentialKey: 3600,
+ })
+
+ require.Equal(t, "https://gw.example.com", filtered["base_url"])
+ require.Equal(t, "apikey", filtered["auth_mode"])
+ require.Equal(t, true, filtered[service.GeminiExplicitCacheUpstreamCredentialKey])
+ require.Equal(t, 3600, filtered[service.GeminiExplicitCacheUpstreamMaxTTLCredentialKey])
+ require.NotContains(t, filtered, "service_account_json")
+}
+
func TestSchedulerMetadataAccountKeepsOpenAISubscriptionIdentity(t *testing.T) {
account := service.Account{
ID: 24,
diff --git a/backend/internal/repository/setting_repo.go b/backend/internal/repository/setting_repo.go
index fb4d2f2ac..a2e352fa8 100644
--- a/backend/internal/repository/setting_repo.go
+++ b/backend/internal/repository/setting_repo.go
@@ -2,6 +2,7 @@ package repository
import (
"context"
+ "errors"
"time"
"github.com/MACOS-DO/sub4api/ent"
@@ -9,6 +10,34 @@ import (
"github.com/MACOS-DO/sub4api/internal/service"
)
+// SetContentModerationConfig holds live group rows until the setting is written.
+// Deletion takes FOR UPDATE on the group before cleaning this setting, so both
+// operations follow the same lock order: groups, then settings.
+func (r *settingRepository) SetContentModerationConfig(ctx context.Context, value string, groupIDs []int64) error {
+ tx, err := r.client.Tx(ctx)
+ if err != nil && !errors.Is(err, ent.ErrTxStarted) {
+ return err
+ }
+ client := r.client
+ if err == nil {
+ defer func() { _ = tx.Rollback() }()
+ client = tx.Client()
+ }
+ if err := lockLiveGroups(ctx, client, groupIDs); err != nil {
+ return err
+ }
+ now := time.Now()
+ if err := client.Setting.Create().SetKey(service.SettingKeyContentModerationConfig).
+ SetValue(value).SetUpdatedAt(now).OnConflictColumns(setting.FieldKey).
+ UpdateNewValues().Exec(ctx); err != nil {
+ return err
+ }
+ if tx != nil {
+ return tx.Commit()
+ }
+ return nil
+}
+
type settingRepository struct {
client *ent.Client
}
diff --git a/backend/internal/repository/sub4api_241_compat_migration_integration_test.go b/backend/internal/repository/sub4api_241_compat_migration_integration_test.go
new file mode 100644
index 000000000..238605af4
--- /dev/null
+++ b/backend/internal/repository/sub4api_241_compat_migration_integration_test.go
@@ -0,0 +1,158 @@
+//go:build integration
+
+package repository
+
+import (
+ "context"
+ "testing"
+
+ dbent "github.com/MACOS-DO/sub4api/ent"
+ dbmigrations "github.com/MACOS-DO/sub4api/migrations"
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ migration241Name = "241_add_typesafe_platform.sql"
+ migration241UpstreamChecksum = "b6559525bf8d0b5d7c617e7415944f0d1fae8c408e9131ace84139795f66dcd2"
+ migration241Sub4APIChecksum = "6034ab0415266a5299a64d49f56b52dab8c61a3c5b2eaa82327c81cc5698a871"
+)
+
+func execMigrationFile(t *testing.T, ctx context.Context, client *dbent.Client, name string) error {
+ t.Helper()
+ content, err := dbmigrations.FS.ReadFile(name)
+ require.NoError(t, err)
+ _, err = client.ExecContext(ctx, string(content))
+ return err
+}
+
+func migration241Checksum(t *testing.T, ctx context.Context, client *dbent.Client) (string, bool) {
+ t.Helper()
+ rows, err := client.QueryContext(ctx, `SELECT checksum FROM schema_migrations WHERE filename = $1`, migration241Name)
+ require.NoError(t, err)
+ defer func() { _ = rows.Close() }()
+ if !rows.Next() {
+ require.NoError(t, rows.Err())
+ return "", false
+ }
+ var checksum string
+ require.NoError(t, rows.Scan(&checksum))
+ return checksum, true
+}
+
+// 还原 1.1.5–1.1.9 的状态:241 未应用,平台约束为 245 版本(含 openai_bps、不含 typesafe)。
+func restorePre241Sub4APIState(t *testing.T, ctx context.Context, client *dbent.Client) {
+ t.Helper()
+ for _, stmt := range []string{
+ `DELETE FROM schema_migrations WHERE filename = '241_add_typesafe_platform.sql'`,
+ `ALTER TABLE user_platform_quotas DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check`,
+ `ALTER TABLE user_platform_quotas ADD CONSTRAINT user_platform_quotas_platform_check
+ CHECK (platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok',
+ 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go'))`,
+ `ALTER TABLE composite_model_routes DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check`,
+ `ALTER TABLE composite_model_routes ADD CONSTRAINT composite_model_routes_target_platform_check
+ CHECK (target_platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok',
+ 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go'))`,
+ } {
+ _, err := client.ExecContext(ctx, stmt)
+ require.NoError(t, err)
+ }
+}
+
+// 1.1.5–1.1.9 且已有 openai_bps 行:上游 241 会校验失败,241_0 将其登记为已应用,
+// 随后 242/246 删除约束,openai_bps 数据保留。
+func TestSub4API241_SkipsUpstream241WhenOpenAIBPSRowsExist(t *testing.T) {
+ ctx := context.Background()
+ client := testEntTx(t).Client()
+ restorePre241Sub4APIState(t, ctx, client)
+
+ userID := mustCreateUserForQuota(t, client)
+ _, err := client.ExecContext(ctx, `
+INSERT INTO user_platform_quotas (user_id, platform, daily_limit_usd, daily_usage_usd, weekly_usage_usd, monthly_usage_usd, created_at, updated_at)
+VALUES ($1, 'openai_bps', 1, 0, 0, 0, NOW(), NOW())`, userID)
+ require.NoError(t, err)
+
+ // 不做处理时上游 241 确实会失败。
+ _, err = client.ExecContext(ctx, `SAVEPOINT before_241`)
+ require.NoError(t, err)
+ require.Error(t, execMigrationFile(t, ctx, client, migration241Name))
+ _, err = client.ExecContext(ctx, `ROLLBACK TO SAVEPOINT before_241`)
+ require.NoError(t, err)
+
+ require.NoError(t, execMigrationFile(t, ctx, client, "241_0_sub4api_skip_typesafe_constraint_for_openai_bps.sql"))
+ checksum, ok := migration241Checksum(t, ctx, client)
+ require.True(t, ok, "241 must be recorded so the runner skips it")
+ require.Equal(t, migration241UpstreamChecksum, checksum)
+
+ require.NoError(t, execMigrationFile(t, ctx, client, "242_drop_platform_check_constraints.sql"))
+ require.NoError(t, execMigrationFile(t, ctx, client, "246_redrop_platform_check_constraints.sql"))
+ require.NoError(t, execMigrationFile(t, ctx, client, "250_sub4api_normalize_241_checksum.sql"))
+ require.False(t, platformConstraintExists(t, ctx, client, "user_platform_quotas", "user_platform_quotas_platform_check"))
+ require.False(t, platformConstraintExists(t, ctx, client, "composite_model_routes", "composite_model_routes_target_platform_check"))
+
+ rows, err := client.QueryContext(ctx,
+ `SELECT COUNT(*) FROM user_platform_quotas WHERE user_id = $1 AND platform = 'openai_bps'`, userID)
+ require.NoError(t, err)
+ defer func() { _ = rows.Close() }()
+ require.True(t, rows.Next())
+ var count int
+ require.NoError(t, rows.Scan(&count))
+ require.Equal(t, 1, count)
+}
+
+// 1.1.5–1.1.9 但没有 openai_bps 行(以及新库):241_0 不登记,上游 241 正常执行。
+func TestSub4API241_RunsUpstream241WithoutOpenAIBPSRows(t *testing.T) {
+ ctx := context.Background()
+ client := testEntTx(t).Client()
+ restorePre241Sub4APIState(t, ctx, client)
+
+ require.NoError(t, execMigrationFile(t, ctx, client, "241_0_sub4api_skip_typesafe_constraint_for_openai_bps.sql"))
+ _, ok := migration241Checksum(t, ctx, client)
+ require.False(t, ok)
+
+ require.NoError(t, execMigrationFile(t, ctx, client, migration241Name))
+ require.True(t, platformConstraintExists(t, ctx, client, "user_platform_quotas", "user_platform_quotas_platform_check"))
+}
+
+// 1.1.10/1.1.11:241 已以 Sub4API 改动版 checksum 应用;241_0 不做任何事,250 归一为上游 checksum 且可重入。
+func TestSub4API241_NormalizesHistoricalChecksum(t *testing.T) {
+ ctx := context.Background()
+ client := testEntTx(t).Client()
+ _, err := client.ExecContext(ctx,
+ `UPDATE schema_migrations SET checksum = $1 WHERE filename = $2`, migration241Sub4APIChecksum, migration241Name)
+ require.NoError(t, err)
+
+ require.NoError(t, execMigrationFile(t, ctx, client, "241_0_sub4api_skip_typesafe_constraint_for_openai_bps.sql"))
+ checksum, ok := migration241Checksum(t, ctx, client)
+ require.True(t, ok)
+ require.Equal(t, migration241Sub4APIChecksum, checksum)
+
+ for range 2 {
+ require.NoError(t, execMigrationFile(t, ctx, client, "250_sub4api_normalize_241_checksum.sql"))
+ checksum, ok = migration241Checksum(t, ctx, client)
+ require.True(t, ok)
+ require.Equal(t, migration241UpstreamChecksum, checksum)
+ }
+}
+
+// 端到端:1.1.10/1.1.11 的库(241 记录为 Sub4API 改动版 checksum,241_0 / 250 未应用)
+// 经真实 runner 启动不报 checksum mismatch,并归一为上游 checksum。
+// 直接操作共享库,结束时状态与初始迁移后一致。
+func TestSub4API241_ApplyMigrationsUpgradesFrom1110(t *testing.T) {
+ ctx := context.Background()
+ _, err := integrationDB.ExecContext(ctx, `
+DELETE FROM schema_migrations WHERE filename IN (
+ '241_0_sub4api_skip_typesafe_constraint_for_openai_bps.sql',
+ '250_sub4api_normalize_241_checksum.sql')`)
+ require.NoError(t, err)
+ _, err = integrationDB.ExecContext(ctx,
+ `UPDATE schema_migrations SET checksum = $1 WHERE filename = $2`, migration241Sub4APIChecksum, migration241Name)
+ require.NoError(t, err)
+
+ require.NoError(t, ApplyMigrations(ctx, integrationDB))
+
+ var checksum string
+ require.NoError(t, integrationDB.QueryRowContext(ctx,
+ `SELECT checksum FROM schema_migrations WHERE filename = $1`, migration241Name).Scan(&checksum))
+ require.Equal(t, migration241UpstreamChecksum, checksum)
+ require.NoError(t, ApplyMigrations(ctx, integrationDB))
+}
diff --git a/backend/internal/repository/wire.go b/backend/internal/repository/wire.go
index 32cbced83..20870183f 100644
--- a/backend/internal/repository/wire.go
+++ b/backend/internal/repository/wire.go
@@ -82,6 +82,7 @@ var ProviderSet = wire.NewSet(
NewUsageLogRepository,
NewUsageBillingRepository,
NewBatchImageRepository,
+ NewGeminiCachedContentRepository,
NewIdempotencyRepository,
NewUsageCleanupRepository,
NewDashboardAggregationRepository,
diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go
index a16868d32..f9ddfd092 100644
--- a/backend/internal/server/routes/admin.go
+++ b/backend/internal/server/routes/admin.go
@@ -370,6 +370,8 @@ func registerAccountRoutes(admin *gin.RouterGroup, h *handler.Handlers, stepUpAu
accounts.GET("/:id", h.Admin.Account.GetByID)
accounts.GET("/codex-ticket-cadence", h.Admin.Account.GetCodexTicketCadence)
accounts.PUT("/codex-ticket-cadence", h.Admin.Account.UpdateCodexTicketCadence)
+ accounts.GET("/codex-ticket-proxy-source", h.Admin.Account.GetCodexTicketProxySource)
+ accounts.PUT("/codex-ticket-proxy-source", h.Admin.Account.UpdateCodexTicketProxySource)
accounts.GET("/codex-ticket-fingerprint", h.Admin.Account.GetCodexFingerprintVersion)
accounts.POST("/codex-ticket-fingerprint/refresh", h.Admin.Account.RefreshCodexFingerprint)
accounts.GET("/:id/codex-ticket-history", h.Admin.Account.GetCodexTicketHistory)
@@ -411,6 +413,7 @@ func registerAccountRoutes(admin *gin.RouterGroup, h *handler.Handlers, stepUpAu
accounts.GET("/:id/stats", h.Admin.Account.GetStats)
accounts.POST("/:id/clear-error", h.Admin.Account.ClearError)
accounts.POST("/:id/revert-proxy-fallback", h.Admin.Account.RevertProxyFallback)
+ accounts.POST("/:id/openai-request-timezone/detect", h.Admin.Account.DetectOpenAIRequestTimezone)
accounts.GET("/:id/usage", h.Admin.Account.GetUsage)
accounts.GET("/:id/today-stats", h.Admin.Account.GetTodayStats)
accounts.POST("/usage/batch", h.Admin.Account.GetBatchUsage)
diff --git a/backend/internal/server/routes/composite_platform_test.go b/backend/internal/server/routes/composite_platform_test.go
index 9c89af68f..a092204f9 100644
--- a/backend/internal/server/routes/composite_platform_test.go
+++ b/backend/internal/server/routes/composite_platform_test.go
@@ -185,6 +185,53 @@ func TestCompositeTargetPlatformMiddlewareRewritesNestedLiveModel(t *testing.T)
require.Equal(t, http.StatusNoContent, w.Code)
}
+// Scenario: 回归 —— openai OAuth 与 deepseek API Key 同时映射 gpt-6-astra 时,
+// 请求必须在路由层被拒绝,不能落到默认 Anthropic handler 后再按模型名猜平台。
+// 仅 API Key 的跨平台歧义保持原行为(放行且不解析平台)。
+func TestCompositeTargetPlatformMiddlewareRejectsOnlyOAuthAmbiguousOwnership(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, tc := range []struct {
+ name string
+ oauthClaimed bool
+ wantStatus int
+ }{
+ {name: "oauth claimant", oauthClaimed: true, wantStatus: http.StatusBadRequest},
+ {name: "apikey only", oauthClaimed: false, wantStatus: http.StatusNoContent},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ resolver := service.NewCompositeRouteResolver(nil)
+ resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) {
+ return service.CompositeModelOwnership{Ambiguous: true, OpenAIGatewayOAuthClaimed: tc.oauthClaimed}, nil
+ })
+ router := gin.New()
+ router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
+ groupID := int64(8)
+ c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
+ GroupID: &groupID,
+ Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
+ })
+ c.Next()
+ })))
+ router.Use(compositeTargetPlatformMiddleware(resolver))
+ router.POST("/v1/responses", func(c *gin.Context) {
+ _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context())
+ require.False(t, resolved)
+ c.Status(http.StatusNoContent)
+ })
+
+ req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-6-astra"}`))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, tc.wantStatus, w.Code)
+ if tc.oauthClaimed {
+ require.Contains(t, w.Body.String(), "explicit composite route")
+ }
+ })
+ }
+}
+
func TestCompositeRequestModelFromMultipartLiveSession(t *testing.T) {
var body bytes.Buffer
writer := multipart.NewWriter(&body)
diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go
index 2cb46e9a8..b4cce90ef 100644
--- a/backend/internal/server/routes/gateway.go
+++ b/backend/internal/server/routes/gateway.go
@@ -350,6 +350,12 @@ func RegisterGatewayRoutes(
gemini.GET("/models/:model", h.Gateway.GeminiV1BetaGetModel)
// Gin treats ":" as a param marker, but Gemini uses "{model}:{action}" in the same segment.
gemini.POST("/models/*modelAction", h.Gateway.GeminiV1BetaModels)
+ // 显式上下文缓存:网关自管资源 ID 与账号绑定,list/get 只读本地记录。
+ gemini.POST("/cachedContents", h.Gateway.GeminiCachedContentsCreate)
+ gemini.GET("/cachedContents", h.Gateway.GeminiCachedContentsList)
+ gemini.GET("/cachedContents/:cacheID", h.Gateway.GeminiCachedContentsGet)
+ gemini.PATCH("/cachedContents/:cacheID", h.Gateway.GeminiCachedContentsPatch)
+ gemini.DELETE("/cachedContents/:cacheID", h.Gateway.GeminiCachedContentsDelete)
}
// OpenAI Responses API(不带v1前缀的别名)— auto-route based on group platform
@@ -581,6 +587,14 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver)
c.Abort()
return
}
+ // 含 OAuth 账号的跨平台歧义是分组配置错误:拒绝而不是放行。否则未解析的
+ // 请求落到默认 Anthropic handler,handler 再按模型名前缀另猜平台,
+ // OAuth 凭据被送进不匹配的协议管线(如 ChatGPT token 发往 Anthropic)。
+ if decision.OAuthAmbiguous() {
+ service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": gin.H{"type": "invalid_request_error", "message": decision.AmbiguousMessage()}})
+ return
+ }
if decision.Matched {
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) {
diff --git a/backend/internal/server/routes/gateway_models_pinned_test.go b/backend/internal/server/routes/gateway_models_pinned_test.go
index 5b8257a78..67e559acb 100644
--- a/backend/internal/server/routes/gateway_models_pinned_test.go
+++ b/backend/internal/server/routes/gateway_models_pinned_test.go
@@ -27,6 +27,14 @@ func (r *pinnedModelsRoutesRepository) ListByGroup(context.Context, int64) ([]se
return []service.Account{r.account}, nil
}
+func (r *pinnedModelsRoutesRepository) ListSchedulableByGroupID(context.Context, int64) ([]service.Account, error) {
+ return []service.Account{r.account}, nil
+}
+
+func (r *pinnedModelsRoutesRepository) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]service.Account, error) {
+ return []service.Account{r.account}, nil
+}
+
type pinnedModelsRoutesUpstream struct {
service.HTTPUpstream
ordinaryCalls atomic.Int32
diff --git a/backend/internal/server/routes/prompt_audit_route_coverage_test.go b/backend/internal/server/routes/prompt_audit_route_coverage_test.go
index 49f8b68fa..2e1315487 100644
--- a/backend/internal/server/routes/prompt_audit_route_coverage_test.go
+++ b/backend/internal/server/routes/prompt_audit_route_coverage_test.go
@@ -47,6 +47,7 @@ func TestEveryGatewayPOSTRouteIsClassifiedForPromptAuditCoverage(t *testing.T) {
"/videos/edits": {"grok_media.go"},
"/videos/extensions": {"grok_media.go"},
"/models/*modelAction": {"gemini_v1beta_handler.go"},
+ "/cachedContents": {"gemini_cached_contents_handler.go"},
"/tts": {"grok_audio.go"},
"/web_search": {"gateway_web_search.go"},
"/x_search": {"gateway_web_search.go"},
diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go
index dc9b05edd..d2f7fe59e 100644
--- a/backend/internal/service/account.go
+++ b/backend/internal/service/account.go
@@ -8,6 +8,7 @@ import (
"log/slog"
"net/url"
"reflect"
+ "slices"
"sort"
"strconv"
"strings"
@@ -130,11 +131,20 @@ func isOpenAIPersonalAccessTokenAuthMode(value string) bool {
}
}
+// TempUnschedulableRule.Scope 的取值:命中后隔离的粒度。
+const (
+ TempUnschedScopeAccount = "account"
+ TempUnschedScopeModel = "model"
+)
+
type TempUnschedulableRule struct {
ErrorCode int `json:"error_code"`
Keywords []string `json:"keywords"`
DurationMinutes int `json:"duration_minutes"`
Description string `json:"description"`
+ // Scope 决定命中后的隔离粒度:account 暂停整个账号,model 只冷却本次请求的模型。
+ // 为空时模型已知且非 401 走模型级,否则账号级。
+ Scope string `json:"scope,omitempty"`
}
func (a *Account) IsActive() bool {
@@ -346,6 +356,13 @@ func (a *Account) IsGeminiGoogleOne() bool {
return a.Platform == PlatformGemini && a.Type == AccountTypeOAuth && a.GeminiOAuthType() == "google_one"
}
+// IsGeminiThirdPartyAPIKey reports whether a Gemini API Key account points at a
+// non-Google base URL. Such upstreams carry no AI Studio tier or daily quota.
+func (a *Account) IsGeminiThirdPartyAPIKey() bool {
+ return a != nil && a.Platform == PlatformGemini && a.Type == AccountTypeAPIKey &&
+ !isOfficialGeminiAPIBaseURL(a.GetCredential("base_url"))
+}
+
func (a *Account) CanGetUsage() bool {
return a.Type == AccountTypeOAuth
}
@@ -467,6 +484,7 @@ func (a *Account) GetTempUnschedulableRules() []TempUnschedulableRule {
Keywords: parseTempUnschedStrings(entry["keywords"]),
DurationMinutes: parseTempUnschedInt(entry["duration_minutes"]),
Description: parseTempUnschedString(entry["description"]),
+ Scope: normalizeTempUnschedScope(entry["scope"]),
}
if rule.ErrorCode <= 0 || rule.DurationMinutes <= 0 || len(rule.Keywords) == 0 {
@@ -479,6 +497,18 @@ func (a *Account) GetTempUnschedulableRules() []TempUnschedulableRule {
return rules
}
+// normalizeTempUnschedScope 只认 account / model 两个值,其余一律视为未设置。
+func normalizeTempUnschedScope(raw any) string {
+ switch strings.ToLower(strings.TrimSpace(parseTempUnschedString(raw))) {
+ case TempUnschedScopeAccount:
+ return TempUnschedScopeAccount
+ case TempUnschedScopeModel:
+ return TempUnschedScopeModel
+ default:
+ return ""
+ }
+}
+
func parseTempUnschedString(value any) string {
s, ok := value.(string)
if !ok {
@@ -668,26 +698,7 @@ func (a *Account) resolveModelMapping(rawMapping map[string]any) map[string]stri
}
if len(result) > 0 {
if a.Platform == domain.PlatformAntigravity {
- ensureAntigravityDefaultPassthroughs(result, []string{
- "gemini-3-flash",
- "gemini-3.1-pro-high",
- "gemini-3.1-pro-low",
- "gemini-3.6-flash",
- "gemini-3.6-flash-high",
- "gemini-3.6-flash-low",
- "gemini-3.6-flash-medium",
- "gemini-3.6-flash-tiered",
- "gemini-3.7-flash",
- "gemini-3.7-flash-high",
- "gemini-3.7-flash-low",
- "gemini-3.7-flash-medium",
- "gemini-3.7-flash-tiered",
- "gemini-3.8-flash",
- "gemini-3.8-flash-high",
- "gemini-3.8-flash-low",
- "gemini-3.8-flash-medium",
- "gemini-3.8-flash-tiered",
- })
+ ensureAntigravityDefaultPassthroughs(result, antigravityDefaultPassthroughModels)
applyAntigravityGemini31ProAliases(result)
}
return result
@@ -737,6 +748,51 @@ func modelMappingSignature(rawMapping map[string]any) uint64 {
return h.Sum64()
}
+// antigravityDefaultPassthroughModels 是 Antigravity 显式 model_mapping 运行时补齐的默认透传条目:
+// 让新模型发布前保存的映射也能调用这些模型。
+var antigravityDefaultPassthroughModels = []string{
+ "gemini-3-flash",
+ "gemini-3.1-pro-high",
+ "gemini-3.1-pro-low",
+ "gemini-3.6-flash",
+ "gemini-3.6-flash-high",
+ "gemini-3.6-flash-low",
+ "gemini-3.6-flash-medium",
+ "gemini-3.6-flash-tiered",
+ "gemini-3.7-flash",
+ "gemini-3.7-flash-high",
+ "gemini-3.7-flash-low",
+ "gemini-3.7-flash-medium",
+ "gemini-3.7-flash-tiered",
+ "gemini-3.8-flash",
+ "gemini-3.8-flash-high",
+ "gemini-3.8-flash-low",
+ "gemini-3.8-flash-medium",
+ "gemini-3.8-flash-tiered",
+}
+
+// isAntigravityInjectedDefaultPassthrough 判断 GetModelMapping 中的 key→target 是否仅由
+// resolveModelMapping 运行时补齐(管理员未写入 credentials.model_mapping)。
+func (a *Account) isAntigravityInjectedDefaultPassthrough(key, target string) bool {
+ if a == nil || a.Platform != domain.PlatformAntigravity || key != target || !slices.Contains(antigravityDefaultPassthroughModels, key) {
+ return false
+ }
+ rawMapping, _ := a.Credentials["model_mapping"].(map[string]any)
+ hasExplicitEntry := false
+ for _, v := range rawMapping {
+ if _, ok := v.(string); ok {
+ hasExplicitEntry = true
+ break
+ }
+ }
+ if !hasExplicitEntry {
+ // 空映射走默认目录,不做运行时补齐。
+ return false
+ }
+ _, configured := rawMapping[key].(string)
+ return !configured
+}
+
func ensureAntigravityDefaultPassthrough(mapping map[string]string, model string) {
if mapping == nil || model == "" {
return
@@ -865,6 +921,10 @@ func resolveRequestedModelInMapping(mapping map[string]string, requestedModel st
// (isDeepseekServableModel)——未知模型名透传上游只会得到 404/400,并误触发
// per-(账号,模型) 30 分钟冷却;带 [1m] 上下文后缀的写法先归一化再比对。
func (a *Account) IsModelSupported(requestedModel string) bool {
+ return supportsOpenAIRequestModel(a, requestedModel, false)
+}
+
+func (a *Account) isModelMappingSupported(requestedModel string) bool {
// 透传模式仅替换认证、模型语义完全交由上游决定,因此放行所有模型。
// 该短路必须在 model_mapping 判定之前:账号从"白名单模式"切换到透传后,
// credentials 里常残留旧的非空 model_mapping,若不在此放行,透传账号会被
@@ -1582,7 +1642,7 @@ func (a *Account) GetCodingPlanProvider() string {
}
baseURL := strings.ToLower(a.GetOpenAIBaseURL())
switch {
- case strings.Contains(baseURL, "api.kimi.com/coding"):
+ case isKimiCodingBaseURL(a.GetOpenAIBaseURL()):
return PlatformKimi
case strings.Contains(baseURL, "bigmodel.cn"), strings.Contains(baseURL, "api.z.ai"):
return PlatformZhipu
@@ -1595,6 +1655,24 @@ func (a *Account) GetCodingPlanProvider() string {
}
}
+func isKimiCodingBaseURL(baseURL string) bool {
+ parsed, err := url.Parse(baseURL)
+ if err != nil || parsed.Scheme != "https" || parsed.User != nil || parsed.Opaque != "" ||
+ parsed.RawQuery != "" || parsed.ForceQuery || strings.Contains(baseURL, "#") {
+ return false
+ }
+ host := strings.ToLower(parsed.Host)
+ if host != "api.kimi.com" && host != "api.kimi.ai" && host != "api.kimi.com:443" && host != "api.kimi.ai:443" {
+ return false
+ }
+ switch parsed.EscapedPath() {
+ case "/coding", "/coding/", "/coding/v1", "/coding/v1/":
+ return true
+ default:
+ return false
+ }
+}
+
func (a *Account) GetOpenAIAccessToken() string {
if !a.IsOpenAI() {
return ""
@@ -2279,7 +2357,10 @@ const (
// 三态:default(跟随渠道)/ enabled(强制开启)/ disabled(强制关闭)。
// 兼容旧 bool 值:true→enabled, false→default(并记录 debug 日志)。
func (a *Account) GetWebSearchEmulationMode() string {
- if a == nil || a.Platform != PlatformAnthropic || a.Type != AccountTypeAPIKey || a.Extra == nil {
+ // OpenAI API Key accounts reach this via /v1/messages; their upstreams
+ // (DeepSeek etc. over Chat Completions) have no web_search tool.
+ if a == nil || a.Type != AccountTypeAPIKey || a.Extra == nil ||
+ (a.Platform != PlatformAnthropic && a.Platform != PlatformOpenAI) {
return WebSearchModeDefault
}
raw := a.Extra[featureKeyWebSearchEmulation]
diff --git a/backend/internal/service/account_kimi_coding_test.go b/backend/internal/service/account_kimi_coding_test.go
new file mode 100644
index 000000000..d2d79e1e0
--- /dev/null
+++ b/backend/internal/service/account_kimi_coding_test.go
@@ -0,0 +1,83 @@
+package service
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestGetCodingPlanProvider_KimiOfficialURLs(t *testing.T) {
+ for _, host := range []string{"api.kimi.com", "api.kimi.ai", "API.KIMI.AI", "api.kimi.ai:443"} {
+ for _, path := range []string{"/coding", "/coding/", "/coding/v1", "/coding/v1/"} {
+ t.Run(host+path, func(t *testing.T) {
+ account := &Account{Platform: PlatformKimi, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "account_mode": AccountModeCoding,
+ "base_url": "https://" + host + path,
+ }}
+ require.Equal(t, PlatformKimi, account.GetCodingPlanProvider())
+ require.Equal(t, "https://"+host+"/coding/v1/usages", kimiQuotaURL(account.GetOpenAIBaseURL()))
+ account.Credentials["account_mode"] = AccountModePayG
+ require.Empty(t, account.GetCodingPlanProvider())
+ })
+ }
+ }
+}
+
+func TestGetCodingPlanProvider_KimiRejectsUnsafeURLs(t *testing.T) {
+ for _, baseURL := range []string{
+ "https://api.kimi.ai.attacker.example/coding/v1",
+ "https://api.kimi.com.attacker.example/coding/v1",
+ "https://fake-api.kimi.ai/coding/v1",
+ "https://relay.attacker.example/api.kimi.com/coding",
+ "https://relay.attacker.example/?target=api.kimi.ai/coding/v1",
+ "https://relay.attacker.example/#api.kimi.com/coding",
+ "https://api.kimi.ai@relay.attacker.example/coding/v1",
+ "https://user@api.kimi.ai/coding/v1",
+ "https://api.kimi.ai/coding-other",
+ "https://api.kimi.com/coding/v10",
+ "https://api.kimi.ai/coding/v1/usages",
+ "https://api.kimi.ai/v1?target=/coding/v1",
+ "https://api.kimi.ai/coding/v1?target=attacker",
+ "https://api.kimi.ai/coding/v1?",
+ "https://api.kimi.ai/coding/v1#attacker",
+ "https://api.kimi.ai/coding/v1#",
+ "https://api.kimi.ai/%63oding/v1",
+ "https://api.kimi.ai/coding%2fv1",
+ "https://api.kimi.ai/coding/../coding/v1",
+ "https://api.kimi.ai/CODING/v1",
+ "https://api.kimi.ai:8443/coding/v1",
+ "https://api.kimi.ai:/coding/v1",
+ "http://api.kimi.ai/coding/v1",
+ "//api.kimi.ai/coding/v1",
+ "https://api.kimi.ai/%zz",
+ } {
+ t.Run(baseURL, func(t *testing.T) {
+ account := &Account{Platform: PlatformKimi, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "account_mode": AccountModeCoding,
+ "base_url": baseURL,
+ }}
+ require.Empty(t, account.GetCodingPlanProvider())
+ })
+ }
+}
+
+func TestGetCodingPlanProvider_UnrelatedProvidersUnchanged(t *testing.T) {
+ for _, testCase := range []struct {
+ platform string
+ baseURL string
+ }{
+ {PlatformZhipu, "https://open.bigmodel.cn/api/coding/paas/v4"},
+ {PlatformZhipu, "https://api.z.ai/api/coding/paas/v4"},
+ {PlatformMiniMax, "https://api.minimax.io/v1"},
+ {PlatformMiniMax, "https://api.minimaxi.com/v1"},
+ {PlatformMiniMax, "https://api.minimax.com/v1"},
+ } {
+ t.Run(testCase.baseURL, func(t *testing.T) {
+ account := &Account{Platform: testCase.platform, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "account_mode": AccountModeCoding,
+ "base_url": testCase.baseURL,
+ }}
+ require.Equal(t, testCase.platform, account.GetCodingPlanProvider())
+ })
+ }
+}
diff --git a/backend/internal/service/account_stats_pricing_test.go b/backend/internal/service/account_stats_pricing_test.go
index 36b840f2f..0496ddeb6 100644
--- a/backend/internal/service/account_stats_pricing_test.go
+++ b/backend/internal/service/account_stats_pricing_test.go
@@ -933,7 +933,7 @@ func TestResolveAccountStatsCost_Gemini36FlashTierUsesFallbackPricing(t *testing
UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000}, 1, 0, "", time.Time{}, true,
)
require.NotNil(t, result)
- require.InDelta(t, 9.15, *result, 1e-12)
+ require.InDelta(t, 4.575, *result, 1e-12)
}
func TestResolveAccountStatsCost_AllMiss_ReturnsNil(t *testing.T) {
diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go
index cd26e957e..e9cd59e4e 100644
--- a/backend/internal/service/account_test_service.go
+++ b/backend/internal/service/account_test_service.go
@@ -2471,12 +2471,12 @@ func (s *AccountTestService) routeAntigravityTest(c *gin.Context, account *Accou
}
return s.testClaudeAccountConnection(c, account, modelID)
}
- return s.testAntigravityAccountConnection(c, account, modelID)
+ return s.testAntigravityAccountConnection(c, account, modelID, prompt)
}
// testAntigravityAccountConnection tests an Antigravity account's connection
// 支持 Claude 和 Gemini 两种协议,使用非流式请求
-func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, account *Account, modelID string) error {
+func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
ctx := c.Request.Context()
testModelID := antigravityConnectionTestModel(modelID)
@@ -2495,8 +2495,8 @@ func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, ac
// Send test_start event
s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID})
- // 调用 AntigravityGatewayService.TestConnection(复用协议转换逻辑)
- result, err := s.antigravityGatewayService.TestConnection(ctx, account, testModelID)
+ // 调用 AntigravityGatewayService.TestConnectionWithPrompt(复用协议转换逻辑)
+ result, err := s.antigravityGatewayService.TestConnectionWithPrompt(ctx, account, testModelID, prompt)
if err != nil {
return s.sendErrorAndEnd(c, err.Error())
}
@@ -2505,6 +2505,13 @@ func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, ac
if result.Text != "" {
s.sendEvent(c, TestEvent{Type: "content", Text: result.Text})
}
+ for _, img := range result.Images {
+ s.sendEvent(c, TestEvent{
+ Type: "image",
+ ImageURL: img.ImageURL,
+ MimeType: img.MimeType,
+ })
+ }
s.sendEvent(c, TestEvent{Type: "test_complete", Success: true})
return nil
@@ -2592,14 +2599,7 @@ func (s *AccountTestService) buildGeminiOAuthRequest(ctx context.Context, accoun
}
func (s *AccountTestService) buildGeminiServiceAccountRequest(ctx context.Context, account *Account, modelID string, payload []byte) (*http.Request, error) {
- if s.geminiTokenProvider == nil {
- return nil, fmt.Errorf("gemini token provider not configured")
- }
- accessToken, err := s.geminiTokenProvider.GetAccessToken(ctx, account)
- if err != nil {
- return nil, fmt.Errorf("failed to get service account access token: %w", err)
- }
- fullURL, err := buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(modelID), modelID, "streamGenerateContent", true)
+ fullURL, err := buildVertexGeminiAccountURL(account, modelID, "streamGenerateContent", true)
if err != nil {
return nil, err
}
@@ -2608,7 +2608,9 @@ func (s *AccountTestService) buildGeminiServiceAccountRequest(ctx context.Contex
return nil, err
}
req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Authorization", "Bearer "+accessToken)
+ if err := setVertexGeminiAuth(ctx, req, account, s.geminiTokenProvider); err != nil {
+ return nil, fmt.Errorf("failed to authenticate vertex request: %w", err)
+ }
return req, nil
}
diff --git a/backend/internal/service/account_test_service_antigravity_test.go b/backend/internal/service/account_test_service_antigravity_test.go
index b3362f3f6..6a14ea85c 100644
--- a/backend/internal/service/account_test_service_antigravity_test.go
+++ b/backend/internal/service/account_test_service_antigravity_test.go
@@ -3,6 +3,7 @@
package service
import (
+ "encoding/json"
"testing"
"github.com/stretchr/testify/require"
@@ -14,3 +15,68 @@ func TestAntigravityConnectionTestModel(t *testing.T) {
require.Equal(t, "claude-sonnet-4-6", antigravityConnectionTestModel(""))
require.Equal(t, "gemini-3.1-pro-preview", antigravityConnectionTestModel("gemini-3.1-pro-preview"))
}
+
+func TestAntigravityBuildGeminiTestRequest_IncludesValidatedToolConfig(t *testing.T) {
+ t.Parallel()
+
+ svc := &AntigravityGatewayService{}
+ raw, err := svc.buildGeminiTestRequestWithPrompt("proj-123", "gemini-3.8-flash-high", "")
+ require.NoError(t, err)
+
+ var v1Req map[string]any
+ require.NoError(t, json.Unmarshal(raw, &v1Req))
+ require.Equal(t, "proj-123", v1Req["project"])
+ require.Equal(t, "gemini-3.8-flash-high", v1Req["model"])
+
+ inner, ok := v1Req["request"].(map[string]any)
+ require.True(t, ok)
+ toolCfg, ok := inner["toolConfig"].(map[string]any)
+ require.True(t, ok, "expected toolConfig to be present in Gemini test request")
+ fcCfg, ok := toolCfg["functionCallingConfig"].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, "VALIDATED", fcCfg["mode"])
+}
+
+func TestAntigravityBuildGeminiTestRequestWithPrompt_ImageModel(t *testing.T) {
+ t.Parallel()
+
+ svc := &AntigravityGatewayService{}
+ raw, err := svc.buildGeminiTestRequestWithPrompt("proj-123", "gemini-3.1-flash-image", "a cute cat")
+ require.NoError(t, err)
+
+ var v1Req map[string]any
+ require.NoError(t, json.Unmarshal(raw, &v1Req))
+ inner, ok := v1Req["request"].(map[string]any)
+ require.True(t, ok)
+
+ genCfg, ok := inner["generationConfig"].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, []any{"TEXT", "IMAGE"}, genCfg["responseModalities"])
+
+ contents, ok := inner["contents"].([]any)
+ require.True(t, ok)
+ require.Len(t, contents, 1)
+ firstContent := contents[0].(map[string]any)
+ parts := firstContent["parts"].([]any)
+ require.Equal(t, "a cute cat", parts[0].(map[string]any)["text"])
+}
+
+func TestExtractContentFromSSEResponse_ExtractsTextAndInlineImages(t *testing.T) {
+ t.Parallel()
+
+ sse := "data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"Here is your image\"},{\"inlineData\":{\"mimeType\":\"image/png\",\"data\":\"iVBORw0KGgo=\"}}]}}]}}\n\n"
+ text, images := extractContentFromSSEResponse([]byte(sse))
+ require.Equal(t, "Here is your image", text)
+ require.Len(t, images, 1)
+ require.Equal(t, "image/png", images[0].MimeType)
+ require.Equal(t, "data:image/png;base64,iVBORw0KGgo=", images[0].ImageURL)
+}
+
+func TestAntigravityShouldUseGeminiTestBuilder_UsesMappedModel(t *testing.T) {
+ t.Parallel()
+
+ require.True(t, shouldUseAntigravityGeminiTestRequest("custom-alias", "gemini-2.5-flash"))
+ require.True(t, shouldUseAntigravityGeminiTestRequest("gemini-3.1-pro", "gemini-pro-agent"))
+ require.False(t, shouldUseAntigravityGeminiTestRequest("gemini-alias", "claude-sonnet-4-6"))
+ require.False(t, shouldUseAntigravityGeminiTestRequest("claude-sonnet-4-6", "claude-sonnet-4-6"))
+}
diff --git a/backend/internal/service/account_websearch_test.go b/backend/internal/service/account_websearch_test.go
index 6ed69d4cf..66fda055c 100644
--- a/backend/internal/service/account_websearch_test.go
+++ b/backend/internal/service/account_websearch_test.go
@@ -86,12 +86,30 @@ func TestGetWebSearchEmulationMode_MissingField(t *testing.T) {
require.Equal(t, WebSearchModeDefault, a.GetWebSearchEmulationMode())
}
-func TestGetWebSearchEmulationMode_NonAnthropicPlatform(t *testing.T) {
+func TestGetWebSearchEmulationMode_OpenAIAPIKey(t *testing.T) {
a := &Account{
Platform: PlatformOpenAI,
Type: AccountTypeAPIKey,
Extra: map[string]any{featureKeyWebSearchEmulation: "enabled"},
}
+ require.Equal(t, WebSearchModeEnabled, a.GetWebSearchEmulationMode())
+}
+
+func TestGetWebSearchEmulationMode_OpenAIOAuth(t *testing.T) {
+ a := &Account{
+ Platform: PlatformOpenAI,
+ Type: AccountTypeOAuth,
+ Extra: map[string]any{featureKeyWebSearchEmulation: "enabled"},
+ }
+ require.Equal(t, WebSearchModeDefault, a.GetWebSearchEmulationMode())
+}
+
+func TestGetWebSearchEmulationMode_OtherPlatform(t *testing.T) {
+ a := &Account{
+ Platform: PlatformGemini,
+ Type: AccountTypeAPIKey,
+ Extra: map[string]any{featureKeyWebSearchEmulation: "enabled"},
+ }
require.Equal(t, WebSearchModeDefault, a.GetWebSearchEmulationMode())
}
diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go
index da292ad19..ddff8d0bb 100644
--- a/backend/internal/service/admin_account.go
+++ b/backend/internal/service/admin_account.go
@@ -496,6 +496,10 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
if err := ValidateOpenAIRequestTimezoneExtra(input.Platform, accountExtra); err != nil {
return nil, err
}
+ if accountExtra != nil {
+ // 检测结果只由后端写入;跟随模式下时区在创建后检测得出。
+ preserveOpenAIRequestTimezoneDetection(nil, accountExtra)
+ }
accountExtra, err = normalizeGrokMediaEligibilityExtra(input.Platform, accountExtra)
if err != nil {
return nil, err
@@ -586,6 +590,7 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
}()
}
}
+ s.scheduleOpenAIRequestTimezoneDetection(account)
return account, nil
}
@@ -654,6 +659,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
}
}
wasOveragesEnabled := account.IsOveragesEnabled()
+ previousTimezoneMode := account.OpenAIRequestTimezoneMode()
+ previousProxyID := cloneAccountValuePointer(account.ProxyID)
+ _, hadTimezoneDetection := account.Extra[openAIRequestTimezoneDetectedExtraKey]
if input.Name != "" {
account.Name = input.Name
@@ -749,6 +757,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
normalizedExtra[key] = v
}
}
+ preserveOpenAIRequestTimezoneDetection(account.Extra, normalizedExtra)
normalizedExtra = MergeOpenAICodexTicketExtra(normalizedExtra, account.Extra)
normalizedExtra = prepareCodexFingerprintExtraForUpdate(account, normalizedExtra)
account.Extra = normalizedExtra
@@ -979,6 +988,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
if err != nil {
return nil, err
}
+ if !sameProxyID(previousProxyID, updated.ProxyID) || previousTimezoneMode != updated.OpenAIRequestTimezoneMode() || !hadTimezoneDetection {
+ s.scheduleOpenAIRequestTimezoneDetection(updated)
+ }
return updated, nil
}
@@ -1028,6 +1040,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
delete(input.Extra, OllamaCloudUsageSnapshotExtraKey)
delete(input.Extra, OpenCodeGoUsageAutoRefreshExtraKey)
delete(input.Extra, OpenCodeGoUsageSnapshotExtraKey)
+ delete(input.Extra, openAIRequestTimezoneDetectedExtraKey)
if len(input.AccountIDs) == 0 && input.Filters != nil {
accountIDs, err := s.resolveBulkUpdateTargetIDs(ctx, input.Filters)
@@ -1257,6 +1270,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
return nil, err
}
}
+ s.scheduleOpenAIRequestTimezoneDetectionByIDs(ctx, input.AccountIDs)
}
// Handle group bindings per account (requires individual operations).
@@ -1429,6 +1443,7 @@ func (s *adminServiceImpl) RevertAccountProxyFallback(ctx context.Context, id in
if err != nil {
return fmt.Errorf("get account after proxy revert: %w", err)
}
+ s.scheduleOpenAIRequestTimezoneDetection(account)
return s.propagateProxyToShadows(ctx, id, account.ProxyID)
}
diff --git a/backend/internal/service/admin_group.go b/backend/internal/service/admin_group.go
index e1401f6ec..84733dc51 100644
--- a/backend/internal/service/admin_group.go
+++ b/backend/internal/service/admin_group.go
@@ -374,7 +374,7 @@ func normalizeCreateGroupInputForSimpleMode(input *CreateGroupInput) {
return
}
*input = CreateGroupInput{
- Name: input.Name, Description: input.Description, Platform: input.Platform,
+ Name: input.Name, Description: input.Description, I18n: input.I18n, Platform: input.Platform,
RateMultiplier: 1, SubscriptionType: SubscriptionTypeStandard,
}
}
@@ -383,7 +383,7 @@ func normalizeUpdateGroupInputForSimpleMode(input *UpdateGroupInput) {
if input == nil {
return
}
- *input = UpdateGroupInput{Name: input.Name, Description: input.Description}
+ *input = UpdateGroupInput{Name: input.Name, Description: input.Description, I18n: input.I18n}
}
func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupInput) (*Group, error) {
@@ -396,6 +396,10 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn
if input.RateMultiplier <= 0 {
return nil, errors.New("rate_multiplier must be > 0")
}
+ i18n, err := normalizeGroupI18n(input.I18n)
+ if err != nil {
+ return nil, err
+ }
platform := NormalizeGroupPlatform(input.Platform)
// 固定账号 manifest 配置:账号绑定发生在创建之后,创建时无法校验成员关系,
@@ -567,6 +571,7 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn
group := &Group{
Name: input.Name,
Description: input.Description,
+ I18n: i18n,
Platform: platform,
RateMultiplier: input.RateMultiplier,
IsExclusive: input.IsExclusive,
@@ -778,6 +783,13 @@ func (s *adminServiceImpl) UpdateGroup(ctx context.Context, id int64, input *Upd
if input.Description != nil {
group.Description = *input.Description
}
+ if input.I18n != nil {
+ i18n, err := normalizeGroupI18n(*input.I18n)
+ if err != nil {
+ return nil, err
+ }
+ group.I18n = i18n
+ }
if input.Platform != "" {
group.Platform = input.Platform
}
diff --git a/backend/internal/service/admin_group_duplicate.go b/backend/internal/service/admin_group_duplicate.go
index 859d19d6f..b31a4ab33 100644
--- a/backend/internal/service/admin_group_duplicate.go
+++ b/backend/internal/service/admin_group_duplicate.go
@@ -97,6 +97,7 @@ func cloneGroupForDuplicate(source *Group, operationID string) *Group {
return &Group{
Name: duplicateGroupName(source.Name, 1),
Description: source.Description,
+ I18n: cloneGroupI18nForDuplicate(source.I18n),
Platform: source.Platform,
RateMultiplier: source.RateMultiplier,
PeakRateEnabled: source.PeakRateEnabled,
diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go
index d29873907..83e6dcdba 100644
--- a/backend/internal/service/admin_service.go
+++ b/backend/internal/service/admin_service.go
@@ -110,6 +110,8 @@ type AdminService interface {
// RevertAccountProxyFallback 将账号的 proxy_id 切回 proxy_fallback_origin_id,并清空 origin 字段。
// 若账号不存在返回 ErrAccountNotFound;若账号存在但不在 fallback 状态,返回 ErrAccountNotInFallback。
RevertAccountProxyFallback(ctx context.Context, id int64) error
+ // DetectOpenAIRequestTimezone 立即检测跟随出口 IP 的 OpenAI 账号的时区并写回。
+ DetectOpenAIRequestTimezone(ctx context.Context, id int64) (*Account, error)
// CreateShadow 为指定 OpenAI OAuth 母账号创建 spark 维度影子账号(一母一影)。
// 影子账号不持凭据(Credentials 恒为空),透传母账号凭据;继承母账号的 ProxyID。
CreateShadow(ctx context.Context, parentID int64, opts ShadowOptions) (*Account, error)
@@ -235,6 +237,7 @@ type AdminBoundAuthIdentityChannel struct {
type CreateGroupInput struct {
Name string
Description string
+ I18n GroupI18n // 名称与描述的界面语言译文
Platform string
RateMultiplier float64
IsExclusive bool
@@ -315,6 +318,7 @@ type CreateGroupInput struct {
type UpdateGroupInput struct {
Name string
Description *string
+ I18n *GroupI18n // nil 表示不修改;非 nil 整体替换
Platform string
RateMultiplier *float64 // 使用指针以支持设置为0
IsExclusive *bool
@@ -616,6 +620,7 @@ type ProxyExitInfo struct {
Region string
Country string
CountryCode string
+ Timezone string // IANA 时区,仅部分探测源(ip-api)返回
}
// ProxyExitInfoProber tests proxy connectivity and retrieves exit information
diff --git a/backend/internal/service/admin_service_group_i18n_test.go b/backend/internal/service/admin_service_group_i18n_test.go
new file mode 100644
index 000000000..e036a41fb
--- /dev/null
+++ b/backend/internal/service/admin_service_group_i18n_test.go
@@ -0,0 +1,150 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "net/http"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+ "github.com/stretchr/testify/require"
+)
+
+func TestAdminService_CreateGroup_NormalizesI18n(t *testing.T) {
+ repo := &groupRepoStubForAdmin{}
+ svc := &adminServiceImpl{groupRepo: repo}
+
+ _, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
+ Name: "Claude Code - 标准",
+ Platform: PlatformAnthropic,
+ RateMultiplier: 1.0,
+ I18n: GroupI18n{
+ "en": {Name: " Claude Code - Standard ", Description: "Pro + Max pool"},
+ "zh": {},
+ },
+ })
+
+ require.NoError(t, err)
+ require.NotNil(t, repo.created)
+ require.Equal(t, GroupI18n{
+ "en": {Name: "Claude Code - Standard", Description: "Pro + Max pool"},
+ }, repo.created.I18n)
+}
+
+func TestAdminService_CreateGroup_RejectsInvalidI18nLocale(t *testing.T) {
+ repo := &groupRepoStubForAdmin{}
+ svc := &adminServiceImpl{groupRepo: repo}
+
+ _, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
+ Name: "g",
+ Platform: PlatformAnthropic,
+ RateMultiplier: 1.0,
+ I18n: GroupI18n{"en_US": {Name: "x"}},
+ })
+
+ require.Error(t, err)
+ appErr := infraerrors.FromError(err)
+ require.Equal(t, int32(http.StatusBadRequest), appErr.Code)
+ require.Equal(t, "INVALID_GROUP_I18N", appErr.Reason)
+ require.Nil(t, repo.created)
+}
+
+func TestAdminService_CreateGroup_RejectsCaseCollidingI18nLocales(t *testing.T) {
+ repo := &groupRepoStubForAdmin{}
+ svc := &adminServiceImpl{groupRepo: repo}
+
+ _, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
+ Name: "默认",
+ Platform: PlatformAnthropic,
+ RateMultiplier: 1.0,
+ I18n: GroupI18n{"en": {Name: "English A"}, "EN": {Name: "English B"}},
+ })
+
+ require.Error(t, err)
+ appErr := infraerrors.FromError(err)
+ require.Equal(t, int32(http.StatusBadRequest), appErr.Code)
+ require.Equal(t, "INVALID_GROUP_I18N", appErr.Reason)
+ require.Nil(t, repo.created)
+}
+
+func TestAdminService_UpdateGroup_I18n(t *testing.T) {
+ newExisting := func() *Group {
+ return &Group{
+ ID: 1, Name: "标准", Platform: PlatformAnthropic, Status: StatusActive, RateMultiplier: 1,
+ I18n: GroupI18n{"en": {Name: "Standard"}},
+ }
+ }
+
+ t.Run("omitted i18n keeps stored translations", func(t *testing.T) {
+ repo := &groupRepoStubForAdmin{getByID: newExisting()}
+ svc := &adminServiceImpl{groupRepo: repo}
+
+ _, err := svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{Name: "标准版"})
+
+ require.NoError(t, err)
+ require.Equal(t, "标准版", repo.updated.Name)
+ require.Equal(t, GroupI18n{"en": {Name: "Standard"}}, repo.updated.I18n)
+ })
+
+ t.Run("provided i18n replaces stored translations as a whole", func(t *testing.T) {
+ repo := &groupRepoStubForAdmin{getByID: newExisting()}
+ svc := &adminServiceImpl{groupRepo: repo}
+ next := GroupI18n{"zh": {Description: " 号池 "}}
+
+ _, err := svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{I18n: &next})
+
+ require.NoError(t, err)
+ require.Equal(t, GroupI18n{"zh": {Description: "号池"}}, repo.updated.I18n)
+ })
+
+ t.Run("empty i18n clears stored translations", func(t *testing.T) {
+ repo := &groupRepoStubForAdmin{getByID: newExisting()}
+ svc := &adminServiceImpl{groupRepo: repo}
+ next := GroupI18n{}
+
+ _, err := svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{I18n: &next})
+
+ require.NoError(t, err)
+ require.NotNil(t, repo.updated.I18n)
+ require.Empty(t, repo.updated.I18n)
+ })
+
+ t.Run("invalid i18n is rejected before persisting", func(t *testing.T) {
+ repo := &groupRepoStubForAdmin{getByID: newExisting()}
+ svc := &adminServiceImpl{groupRepo: repo}
+ next := GroupI18n{"not a locale": {Name: "x"}}
+
+ _, err := svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{I18n: &next})
+
+ require.Error(t, err)
+ require.Equal(t, "INVALID_GROUP_I18N", infraerrors.FromError(err).Reason)
+ require.Nil(t, repo.updated)
+ })
+
+ // 简易模式只放行名称与描述,译文属于同一类展示文案,同样放行。
+ t.Run("simple mode keeps i18n editable", func(t *testing.T) {
+ repo := &groupRepoStubForAdmin{getByID: newExisting()}
+ svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}, groupRepo: repo}
+ next := GroupI18n{"en": {Name: "Standard v2"}}
+ rate := 9.0
+
+ _, err := svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{I18n: &next, RateMultiplier: &rate})
+
+ require.NoError(t, err)
+ require.Equal(t, GroupI18n{"en": {Name: "Standard v2"}}, repo.updated.I18n)
+ require.Equal(t, 1.0, repo.updated.RateMultiplier)
+ })
+}
+
+func TestCloneGroupForDuplicate_DropsNameTranslations(t *testing.T) {
+ source := &Group{
+ ID: 7, Name: "标准", Platform: PlatformAnthropic,
+ I18n: GroupI18n{"en": {Name: "Standard", Description: "Pro + Max pool"}},
+ }
+
+ clone := cloneGroupForDuplicate(source, "op-1")
+
+ require.Equal(t, GroupI18n{"en": {Description: "Pro + Max pool"}}, clone.I18n)
+}
diff --git a/backend/internal/service/antigravity_gateway_compat.go b/backend/internal/service/antigravity_gateway_compat.go
index 9caa4809f..0fe369bf5 100644
--- a/backend/internal/service/antigravity_gateway_compat.go
+++ b/backend/internal/service/antigravity_gateway_compat.go
@@ -71,7 +71,7 @@ func (s *AntigravityGatewayService) ForwardAsChatCompletions(
return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", "model is required")
}
- responsesRequest, err := apicompat.ChatCompletionsToResponses(&request)
+ responsesRequest, err := chatCompletionsToResponses(settingServiceConfig(s.settingService), &request)
if err != nil {
return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
}
diff --git a/backend/internal/service/antigravity_gateway_gemini.go b/backend/internal/service/antigravity_gateway_gemini.go
index 5a12ef074..c4ba27ac9 100644
--- a/backend/internal/service/antigravity_gateway_gemini.go
+++ b/backend/internal/service/antigravity_gateway_gemini.go
@@ -141,6 +141,8 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
injectedBody = reconciled
}
+ injectedBody = ensureGeminiFunctionCallThoughtSignatures(injectedBody)
+
// 包装请求
wrappedBody, err := s.wrapV1InternalRequest(projectID, mappedModel, injectedBody)
if err != nil {
diff --git a/backend/internal/service/antigravity_gateway_retry.go b/backend/internal/service/antigravity_gateway_retry.go
index f823bdf34..c21b733ad 100644
--- a/backend/internal/service/antigravity_gateway_retry.go
+++ b/backend/internal/service/antigravity_gateway_retry.go
@@ -78,12 +78,7 @@ func accountHasAntigravityPaidTier(account *Account) bool {
if !ok {
return false
}
- switch strings.ToLower(strings.TrimSpace(planType)) {
- case "pro", "ultra":
- return true
- default:
- return false
- }
+ return antigravity.IsPaidPlanType(planType)
}
// smartRetryAction 智能重试的处理结果
diff --git a/backend/internal/service/antigravity_gateway_service.go b/backend/internal/service/antigravity_gateway_service.go
index 2bd9e67aa..af99afa20 100644
--- a/backend/internal/service/antigravity_gateway_service.go
+++ b/backend/internal/service/antigravity_gateway_service.go
@@ -344,16 +344,32 @@ func (s *AntigravityGatewayService) IsModelSupported(requestedModel string) bool
strings.HasPrefix(requestedModel, "gemini-")
}
+// TestConnectionImage 测试连接返回的图片结果
+type TestConnectionImage struct {
+ ImageURL string
+ MimeType string
+}
+
// TestConnectionResult 测试连接结果
type TestConnectionResult struct {
- Text string // 响应文本
- MappedModel string // 实际使用的模型
+ Text string // 响应文本
+ Images []TestConnectionImage // 响应图片(图片生成模型)
+ MappedModel string // 实际使用的模型
+}
+
+func shouldUseAntigravityGeminiTestRequest(_, mappedModel string) bool {
+ return strings.HasPrefix(strings.ToLower(strings.TrimSpace(mappedModel)), "gemini-")
}
// TestConnection 测试 Antigravity 账号连接。
// 复用 antigravityRetryLoop 的完整重试 / credits overages / 智能重试逻辑,
// 与真实调度行为一致。差异:不做账号切换(测试指定账号)、不记录 ops 错误。
func (s *AntigravityGatewayService) TestConnection(ctx context.Context, account *Account, modelID string) (*TestConnectionResult, error) {
+ return s.TestConnectionWithPrompt(ctx, account, modelID, "")
+}
+
+// TestConnectionWithPrompt 测试 Antigravity 账号连接,支持为图片生成模型指定测试提示词。
+func (s *AntigravityGatewayService) TestConnectionWithPrompt(ctx context.Context, account *Account, modelID string, prompt string) (*TestConnectionResult, error) {
// 获取 token
if s.tokenProvider == nil {
@@ -377,8 +393,8 @@ func (s *AntigravityGatewayService) TestConnection(ctx context.Context, account
// 构建请求体
var requestBody []byte
- if strings.HasPrefix(modelID, "gemini-") {
- requestBody, err = s.buildGeminiTestRequest(projectID, mappedModel)
+ if shouldUseAntigravityGeminiTestRequest(modelID, mappedModel) {
+ requestBody, err = s.buildGeminiTestRequestWithPrompt(projectID, mappedModel, prompt)
} else {
requestBody, err = s.buildClaudeTestRequest(projectID, mappedModel)
}
@@ -434,8 +450,8 @@ func (s *AntigravityGatewayService) TestConnection(ctx context.Context, account
return nil, fmt.Errorf("API 返回 %d: %s", result.resp.StatusCode, string(respBody))
}
- text := extractTextFromSSEResponse(respBody)
- return &TestConnectionResult{Text: text, MappedModel: mappedModel}, nil
+ text, images := extractContentFromSSEResponse(respBody)
+ return &TestConnectionResult{Text: text, Images: images, MappedModel: mappedModel}, nil
}
// testConnectionHandleError 是 TestConnection 使用的轻量 handleError 回调。
@@ -451,9 +467,39 @@ func testConnectionHandleError(
return nil
}
-// buildGeminiTestRequest 构建 Gemini 格式测试请求
-// 使用最小 token 消耗:输入 "." + maxOutputTokens: 1
-func (s *AntigravityGatewayService) buildGeminiTestRequest(projectID, model string) ([]byte, error) {
+// buildGeminiTestRequestWithPrompt 构建 Gemini 格式测试请求
+// 文本模型使用最小 token 消耗:输入 "." + maxOutputTokens: 1;图片模型使用图片生成配置
+func (s *AntigravityGatewayService) buildGeminiTestRequestWithPrompt(projectID, model, prompt string) ([]byte, error) {
+ if isImageGenerationModel(model) {
+ imagePrompt := strings.TrimSpace(prompt)
+ if imagePrompt == "" {
+ imagePrompt = defaultGeminiImageTestPrompt
+ }
+ payload := map[string]any{
+ "contents": []map[string]any{
+ {
+ "role": "user",
+ "parts": []map[string]any{
+ {"text": imagePrompt},
+ },
+ },
+ },
+ "systemInstruction": map[string]any{
+ "parts": []map[string]any{
+ {"text": antigravity.GetDefaultIdentityPatch()},
+ },
+ },
+ "generationConfig": map[string]any{
+ "responseModalities": []string{"TEXT", "IMAGE"},
+ "imageConfig": map[string]any{
+ "aspectRatio": "1:1",
+ },
+ },
+ }
+ payloadBytes, _ := json.Marshal(payload)
+ return s.wrapV1InternalRequest(projectID, model, payloadBytes)
+ }
+
payload := map[string]any{
"contents": []map[string]any{
{
@@ -472,6 +518,11 @@ func (s *AntigravityGatewayService) buildGeminiTestRequest(projectID, model stri
"generationConfig": map[string]any{
"maxOutputTokens": 1,
},
+ "toolConfig": map[string]any{
+ "functionCallingConfig": map[string]any{
+ "mode": "VALIDATED",
+ },
+ },
}
payloadBytes, _ := json.Marshal(payload)
return s.wrapV1InternalRequest(projectID, model, payloadBytes)
@@ -504,9 +555,10 @@ func (s *AntigravityGatewayService) getClaudeTransformOptions(ctx context.Contex
return opts
}
-// extractTextFromSSEResponse 从 SSE 流式响应中提取文本
-func extractTextFromSSEResponse(respBody []byte) string {
+// extractContentFromSSEResponse 从 SSE 流式响应中提取文本和内联图片
+func extractContentFromSSEResponse(respBody []byte) (string, []TestConnectionImage) {
var texts []string
+ var images []TestConnectionImage
lines := bytes.Split(respBody, []byte("\n"))
for _, line := range lines {
@@ -532,7 +584,7 @@ func extractTextFromSSEResponse(respBody []byte) string {
continue
}
- // 尝试从 response.candidates[0].content.parts[].text 提取
+ // 尝试从 response.candidates[0].content.parts[] 提取
response, ok := data["response"].(map[string]any)
if !ok {
// 尝试直接从 candidates 提取(某些响应格式)
@@ -564,11 +616,21 @@ func extractTextFromSSEResponse(respBody []byte) string {
if text, ok := partMap["text"].(string); ok && text != "" {
texts = append(texts, text)
}
+ if inlineData, ok := partMap["inlineData"].(map[string]any); ok {
+ mimeType, _ := inlineData["mimeType"].(string)
+ b64Data, _ := inlineData["data"].(string)
+ if strings.HasPrefix(strings.ToLower(mimeType), "image/") && b64Data != "" {
+ images = append(images, TestConnectionImage{
+ ImageURL: fmt.Sprintf("data:%s;base64,%s", mimeType, b64Data),
+ MimeType: mimeType,
+ })
+ }
+ }
}
}
}
- return strings.Join(texts, "")
+ return strings.Join(texts, ""), images
}
// injectIdentityPatchToGeminiRequest 为 Gemini 格式请求注入身份提示词
diff --git a/backend/internal/service/antigravity_gateway_service_test.go b/backend/internal/service/antigravity_gateway_service_test.go
index d3c7638a2..635b478bf 100644
--- a/backend/internal/service/antigravity_gateway_service_test.go
+++ b/backend/internal/service/antigravity_gateway_service_test.go
@@ -2012,3 +2012,175 @@ func generateLargeUnwrapJSON(minSize int) []byte {
b, _ := json.Marshal(outer)
return b
}
+
+func TestAntigravityGatewayService_ForwardGemini_NonStreamPreservesFunctionCallAndThoughtSignature(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ body := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Tokyo."}]}],"tools":[{"functionDeclarations":[{"name":"get_weather","description":"Get weather","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]}]}`)
+
+ writer := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(writer)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-4-argon:generateContent", bytes.NewReader(body))
+
+ sseStream := strings.Join([]string{
+ `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_fc_1","functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_1"}}]}}],"usageMetadata":{"promptTokenCount":300,"candidatesTokenCount":16,"totalTokenCount":328,"thoughtsTokenCount":12},"modelVersion":"gemini-4-argon","responseId":"resp_1"}}`,
+ "",
+ `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":""}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":300,"candidatesTokenCount":22,"totalTokenCount":334,"thoughtsTokenCount":12},"modelVersion":"gemini-4-argon","responseId":"resp_1"}}`,
+ "",
+ }, "\n")
+
+ upstream := &queuedHTTPUpstreamStub{
+ responses: []*http.Response{{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(sseStream)),
+ }},
+ }
+ svc := &AntigravityGatewayService{
+ settingService: NewSettingService(&antigravitySettingRepoStub{}, &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}),
+ tokenProvider: &AntigravityTokenProvider{},
+ httpUpstream: upstream,
+ }
+ account := &Account{
+ ID: 109,
+ Name: "antigravity-fc-nonstream",
+ Platform: PlatformAntigravity,
+ Type: AccountTypeOAuth,
+ Status: StatusActive,
+ Concurrency: 1,
+ Credentials: map[string]any{
+ "access_token": "test-access-token",
+ "project_id": "test-project",
+ "model_mapping": map[string]any{
+ "gemini-4-argon": "gemini-4-argon",
+ },
+ },
+ }
+
+ result, err := svc.ForwardGemini(context.Background(), c, account, "gemini-4-argon", "generateContent", false, body, false)
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Equal(t, http.StatusOK, writer.Code)
+
+ var respPayload map[string]any
+ require.NoError(t, json.Unmarshal(writer.Body.Bytes(), &respPayload))
+ candidates, ok := respPayload["candidates"].([]any)
+ require.True(t, ok)
+ require.Len(t, candidates, 1)
+ candidate, ok := candidates[0].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, "STOP", candidate["finishReason"])
+
+ content, ok := candidate["content"].(map[string]any)
+ require.True(t, ok)
+ parts, ok := content["parts"].([]any)
+ require.True(t, ok)
+ require.Len(t, parts, 1, "trailing empty text part should not overwrite or pollute functionCall part")
+
+ part0, ok := parts[0].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, "sig_fc_1", part0["thoughtSignature"])
+ fc, ok := part0["functionCall"].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, "get_weather", fc["name"])
+ require.Equal(t, "call_1", fc["id"])
+ require.Equal(t, map[string]any{"city": "Tokyo"}, fc["args"])
+}
+
+func TestAntigravityGatewayService_ForwardGemini_StreamAndFunctionResponseFollowUp(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ // 1) Stream request with functionDeclarations returns unwrapped functionCall and thoughtSignature
+ streamReqBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Tokyo."}]}],"tools":[{"functionDeclarations":[{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]}]}`)
+ streamWriter := httptest.NewRecorder()
+ streamCtx, _ := gin.CreateTestContext(streamWriter)
+ streamCtx.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-4-argon:streamGenerateContent?alt=sse", bytes.NewReader(streamReqBody))
+
+ streamSSE := strings.Join([]string{
+ `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_stream_1","functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_s1"}}]}}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5}}}`,
+ "",
+ `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":""}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":6}}}`,
+ "",
+ }, "\n")
+
+ // 2) Non-stream follow-up with functionCall (missing thoughtSignature) + functionResponse (with inlineData image)
+ followUpReqBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Tokyo."}]},{"role":"model","parts":[{"functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_s1"}}]},{"role":"user","parts":[{"functionResponse":{"name":"get_weather","id":"call_s1","response":{"weather":"Sunny"},"parts":[{"inlineData":{"mimeType":"image/png","data":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}}]}}]}],"tools":[{"functionDeclarations":[{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]}]}`)
+ followUpWriter := httptest.NewRecorder()
+ followUpCtx, _ := gin.CreateTestContext(followUpWriter)
+ followUpCtx.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-4-argon:generateContent", bytes.NewReader(followUpReqBody))
+
+ followUpSSE := strings.Join([]string{
+ `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"It is sunny in "}]}}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":4}}}`,
+ "",
+ `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"Tokyo."}]}}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":6}}}`,
+ "",
+ `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_final","text":""}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":8}}}`,
+ "",
+ }, "\n")
+
+ upstream := &queuedHTTPUpstreamStub{
+ responses: []*http.Response{
+ {
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(streamSSE)),
+ },
+ {
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(followUpSSE)),
+ },
+ },
+ }
+
+ svc := &AntigravityGatewayService{
+ settingService: NewSettingService(&antigravitySettingRepoStub{}, &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}),
+ tokenProvider: &AntigravityTokenProvider{},
+ httpUpstream: upstream,
+ }
+ account := &Account{
+ ID: 110,
+ Name: "antigravity-fc-stream",
+ Platform: PlatformAntigravity,
+ Type: AccountTypeOAuth,
+ Status: StatusActive,
+ Concurrency: 1,
+ Credentials: map[string]any{
+ "access_token": "test-access-token",
+ "project_id": "test-project",
+ "model_mapping": map[string]any{
+ "gemini-4-argon": "gemini-4-argon",
+ },
+ },
+ }
+
+ res1, err := svc.ForwardGemini(context.Background(), streamCtx, account, "gemini-4-argon", "streamGenerateContent", true, streamReqBody, false)
+ require.NoError(t, err)
+ require.NotNil(t, res1)
+ require.Contains(t, streamWriter.Body.String(), `"functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_s1"}`)
+ require.Contains(t, streamWriter.Body.String(), `"thoughtSignature":"sig_stream_1"`)
+
+ res2, err := svc.ForwardGemini(context.Background(), followUpCtx, account, "gemini-4-argon", "generateContent", false, followUpReqBody, false)
+ require.NoError(t, err)
+ require.NotNil(t, res2)
+ require.Len(t, upstream.requestBodies, 2)
+
+ // Verify follow-up request had dummy thoughtSignature injected on functionCall and preserved functionResponse image part
+ secondSent := string(upstream.requestBodies[1])
+ require.Contains(t, secondSent, `"thoughtSignature":"skip_thought_signature_validator"`)
+ require.Contains(t, secondSent, `"mimeType":"image/png"`)
+
+ var followUpResp map[string]any
+ require.NoError(t, json.Unmarshal(followUpWriter.Body.Bytes(), &followUpResp))
+ cands, ok := followUpResp["candidates"].([]any)
+ require.True(t, ok)
+ cand0, ok := cands[0].(map[string]any)
+ require.True(t, ok)
+ content, ok := cand0["content"].(map[string]any)
+ require.True(t, ok)
+ parts, ok := content["parts"].([]any)
+ require.True(t, ok)
+ require.NotEmpty(t, parts)
+ firstPart, ok := parts[0].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, "It is sunny in Tokyo.", firstPart["text"])
+}
diff --git a/backend/internal/service/antigravity_gateway_streaming.go b/backend/internal/service/antigravity_gateway_streaming.go
index 7fa048c2e..184a02b8e 100644
--- a/backend/internal/service/antigravity_gateway_streaming.go
+++ b/backend/internal/service/antigravity_gateway_streaming.go
@@ -350,8 +350,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont
var firstTokenMs *int
var last map[string]any
var lastWithParts map[string]any
- var collectedImageParts []map[string]any // 收集所有包含图片的 parts
- var collectedTextParts []string // 收集所有文本片段
+ var collectedParts []map[string]any // 收集所有 parts(text、thinking、functionCall、inlineData 等)
type scanEvent struct {
line string
@@ -467,19 +466,10 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont
}
}
- // 保留最后一个有 parts 的响应
+ // 保留最后一个有 parts 的响应,并收集所有 parts
if parts := extractGeminiParts(parsed); len(parts) > 0 {
lastWithParts = parsed
- // 收集包含图片和文本的 parts
- for _, part := range parts {
- if inlineData, ok := part["inlineData"].(map[string]any); ok {
- collectedImageParts = append(collectedImageParts, part)
- _ = inlineData // 避免 unused 警告
- }
- if text, ok := part["text"].(string); ok && text != "" {
- collectedTextParts = append(collectedTextParts, text)
- }
- }
+ collectedParts = append(collectedParts, parts...)
}
case <-intervalCh:
@@ -506,14 +496,9 @@ returnResponse:
}
}
- // 如果收集到了图片 parts,需要合并到最终响应中
- if len(collectedImageParts) > 0 {
- finalResponse = mergeImagePartsToResponse(finalResponse, collectedImageParts)
- }
-
- // 如果收集到了文本,需要合并到最终响应中
- if len(collectedTextParts) > 0 {
- finalResponse = mergeTextPartsToResponse(finalResponse, collectedTextParts)
+ // 将收集的所有 parts 合并到最终响应中
+ if len(collectedParts) > 0 {
+ finalResponse = mergeCollectedPartsToResponse(finalResponse, collectedParts)
}
respBody, err := json.Marshal(finalResponse)
@@ -576,21 +561,27 @@ func mergeCollectedPartsToResponse(response map[string]any, collectedParts []map
return response
}
- result, _, setParts := getOrCreateGeminiParts(response)
+ result, existingParts, setParts := getOrCreateGeminiParts(response)
// 合并策略:
// 1. 保持原始顺序
- // 2. 连续的普通 text parts 合并为一个
+ // 2. 连续的普通 text parts 合并为一个,并保留关联的 thoughtSignature
// 3. thinking、functionCall、inlineData 等保持原样
var mergedParts []any
var textBuffer strings.Builder
+ var textSignature string
flushTextBuffer := func() {
- if textBuffer.Len() > 0 {
- mergedParts = append(mergedParts, map[string]any{
+ if textBuffer.Len() > 0 || textSignature != "" {
+ part := map[string]any{
"text": textBuffer.String(),
- })
+ }
+ if textSignature != "" {
+ part["thoughtSignature"] = textSignature
+ }
+ mergedParts = append(mergedParts, part)
textBuffer.Reset()
+ textSignature = ""
}
}
@@ -605,6 +596,9 @@ func mergeCollectedPartsToResponse(response map[string]any, collectedParts []map
} else {
// 普通 text,累积到 buffer
_, _ = textBuffer.WriteString(text)
+ if sig, ok := part["thoughtSignature"].(string); ok && sig != "" {
+ textSignature = sig
+ }
}
} else {
// 非 text part(functionCall、inlineData 等),先刷新 text buffer,然后保留原样
@@ -616,73 +610,11 @@ func mergeCollectedPartsToResponse(response map[string]any, collectedParts []map
// 刷新剩余的 text
flushTextBuffer()
- setParts(mergedParts)
- return result
-}
-
-// mergeImagePartsToResponse 将收集到的图片 parts 合并到 Gemini 响应中
-func mergeImagePartsToResponse(response map[string]any, imageParts []map[string]any) map[string]any {
- if len(imageParts) == 0 {
- return response
+ if len(mergedParts) == 0 {
+ mergedParts = existingParts
}
- result, existingParts, setParts := getOrCreateGeminiParts(response)
-
- // 检查现有 parts 中是否已经有图片
- for _, p := range existingParts {
- if pm, ok := p.(map[string]any); ok {
- if _, hasInline := pm["inlineData"]; hasInline {
- return result // 已有图片,不重复添加
- }
- }
- }
-
- // 添加收集到的图片 parts
- for _, imgPart := range imageParts {
- existingParts = append(existingParts, imgPart)
- }
- setParts(existingParts)
- return result
-}
-
-// mergeTextPartsToResponse 将收集到的文本合并到 Gemini 响应中
-func mergeTextPartsToResponse(response map[string]any, textParts []string) map[string]any {
- if len(textParts) == 0 {
- return response
- }
-
- mergedText := strings.Join(textParts, "")
- result, existingParts, setParts := getOrCreateGeminiParts(response)
-
- // 查找并更新第一个 text part,或创建新的
- newParts := make([]any, 0, len(existingParts)+1)
- textUpdated := false
-
- for _, p := range existingParts {
- pm, ok := p.(map[string]any)
- if !ok {
- newParts = append(newParts, p)
- continue
- }
- if _, hasText := pm["text"]; hasText && !textUpdated {
- // 用累积的文本替换
- newPart := make(map[string]any)
- for k, v := range pm {
- newPart[k] = v
- }
- newPart["text"] = mergedText
- newParts = append(newParts, newPart)
- textUpdated = true
- } else {
- newParts = append(newParts, pm)
- }
- }
-
- if !textUpdated {
- newParts = append([]any{map[string]any{"text": mergedText}}, newParts...)
- }
-
- setParts(newParts)
+ setParts(mergedParts)
return result
}
diff --git a/backend/internal/service/antigravity_gemini_thinking_variant.go b/backend/internal/service/antigravity_gemini_thinking_variant.go
index cf9cfe091..23949aac6 100644
--- a/backend/internal/service/antigravity_gemini_thinking_variant.go
+++ b/backend/internal/service/antigravity_gemini_thinking_variant.go
@@ -108,17 +108,6 @@ func geminiThinkingLevelFromClaudeThinking(thinking *antigravity.ThinkingConfig)
}
}
-// accountRawModelMappingHasKey 判断 key 是否由用户写在账号 credentials.model_mapping 里
-// (而不是 resolveModelMapping 运行时补进来的默认透传条目)。
-func accountRawModelMappingHasKey(account *Account, key string) bool {
- if account == nil || account.Credentials == nil {
- return false
- }
- raw, _ := account.Credentials["model_mapping"].(map[string]any)
- _, ok := raw[key]
- return ok
-}
-
// resolveGeminiThinkingVariant 为裸 Gemini 模型名挑选账号映射表里存在的思考深度变体。
// 返回 (映射后的上游模型名, 是否命中)。未命中时调用方应回退到常规 getMappedModel 流程。
func resolveGeminiThinkingVariant(account *Account, requestedModel string, body []byte) (string, bool) {
@@ -140,16 +129,16 @@ func resolveGeminiThinkingVariantForLevel(account *Account, requestedModel strin
if len(mapping) == 0 {
return "", false
}
- // 裸名本身已有"真正的"映射 → 尊重现有配置,不做推导。判定分两层:
- // 1. 映射目标不是自己(如 gemini-3.8-flash → gemini-3.8-flash-tiered):用户明确指定了目标;
- // 2. 映射目标是自己(原样透传):仅当这条是用户亲手写进 credentials.model_mapping 的才尊重。
- // resolveModelMapping 会给每个 Antigravity 账号自动补 gemini-3.x-flash 裸名自映射
- // (ensureAntigravityDefaultPassthroughs),而上游目录里并没有裸名模型,那条自映射
- // 正是导致 404 的来源,不能算作用户意图。
- if mapped, matched := resolveRequestedModelInMapping(mapping, model); matched {
- if strings.TrimSpace(mapped) != model || accountRawModelMappingHasKey(account, model) {
- return "", false
- }
+ // 裸名本身若已映射到其他具体模型(如 gemini-3.8-flash → gemini-3.8-flash-tiered、
+ // gemini-3.1-pro → gemini-pro-agent),尊重显式别名配置。
+ // 若裸名映射目标是自己(如前端从 DefaultAntigravityModelMapping 拉取并持久化的
+ // gemini-3.8-flash → gemini-3.8-flash,或 ensureAntigravityDefaultPassthroughs 注入的条目),
+ // 当映射表中存在该模型的精确思考变体(-high/-medium/-low/-tiered)时继续解析变体,
+ // 避免把上游不存在的裸名直接发出导致 404;而对已在映射表中的真实裸模型(如 gemini-2.5-flash),
+ // 仅查找精确变体键以避免被通配符误匹配。
+ mapped, modelMatched := resolveRequestedModelInMapping(mapping, model)
+ if modelMatched && strings.TrimSpace(mapped) != model {
+ return "", false
}
if preferred == "" {
@@ -163,8 +152,17 @@ func resolveGeminiThinkingVariantForLevel(account *Account, requestedModel strin
}
for _, level := range order {
candidate := model + "-" + level
- if mapped, matched := resolveRequestedModelInMapping(mapping, candidate); matched && strings.TrimSpace(mapped) != "" {
- return mapped, true
+ var (
+ variantMapped string
+ variantMatched bool
+ )
+ if modelMatched {
+ variantMapped, variantMatched = mapping[candidate]
+ } else {
+ variantMapped, variantMatched = resolveRequestedModelInMapping(mapping, candidate)
+ }
+ if variantMatched && strings.TrimSpace(variantMapped) != "" {
+ return variantMapped, true
}
}
return "", false
diff --git a/backend/internal/service/antigravity_gemini_thinking_variant_test.go b/backend/internal/service/antigravity_gemini_thinking_variant_test.go
index 4a115ac6e..8e96a1a8d 100644
--- a/backend/internal/service/antigravity_gemini_thinking_variant_test.go
+++ b/backend/internal/service/antigravity_gemini_thinking_variant_test.go
@@ -74,10 +74,10 @@ func TestResolveGeminiThinkingVariant(t *testing.T) {
{"agy low (1000) -> -low", catalog, "gemini-3.8-flash", budget("1000"), "gemini-3.8-flash-low", true},
{"models/ prefix stripped", catalog, "models/gemini-3.8-flash", budget("1000"), "gemini-3.8-flash-low", true},
{"no thinkingConfig -> -high", catalog, "gemini-3.8-flash", []byte(`{"contents":[]}`), "gemini-3.8-flash-high", true},
- // gemini-3.6/3.7/3.8-flash 的四个变体会被 resolveModelMapping 自动补齐,所以降级用一个不在默认表里的型号
{"only -high exists: low request degrades to high", map[string]string{
"gemini-3.5-flash-high": "gemini-3.5-flash-high",
}, "gemini-3.5-flash", budget("1000"), "gemini-3.5-flash-high", true},
+ // gemini-3.6/3.7/3.8-flash 的四个变体会被 resolveModelMapping 自动补齐(存量显式映射账号的兼容透传)。
{"injected default variants are usable", catalog, "gemini-3.6-flash", budget("1000"), "gemini-3.6-flash-low", true},
{"already suffixed: untouched", catalog, "gemini-3.8-flash-low", budget("-1"), "", false},
{"bare name explicitly mapped: untouched", catalog, "gemini-2.5-flash", budget("-1"), "", false},
@@ -90,16 +90,22 @@ func TestResolveGeminiThinkingVariant(t *testing.T) {
{"variant value is itself a mapping target", map[string]string{
"gemini-3.8-flash-high": "gemini-3.8-flash-tiered",
}, "gemini-3.8-flash", budget("-1"), "gemini-3.8-flash-tiered", true},
- {"user-written bare identity passthrough: respected", map[string]string{
+ // 前端持久化的默认目录含裸名自映射;-low 由默认透传补齐,按预算命中。
+ {"persisted default bare identity passthrough still resolves when variants exist", map[string]string{
"gemini-3.8-flash": "gemini-3.8-flash",
"gemini-3.8-flash-high": "gemini-3.8-flash-high",
- }, "gemini-3.8-flash", budget("1000"), "", false},
- {"runtime-injected bare passthrough (not in credentials): still resolved", map[string]string{
- // resolveModelMapping 会补 gemini-3.7-flash → gemini-3.7-flash 的默认透传,
- // 但 credentials 里没有这条,应当继续推导变体。
+ }, "gemini-3.8-flash", budget("1000"), "gemini-3.8-flash-low", true},
+ {"bare identity passthrough resolves a configured variant outside the default passthroughs", map[string]string{
+ "gemini-3.5-flash": "gemini-3.5-flash",
+ "gemini-3.5-flash-high": "gemini-3.5-flash-high",
+ }, "gemini-3.5-flash", budget("1000"), "gemini-3.5-flash-high", true},
+ {"wildcard mapping does not fabricate variants for non-tiered bare model", map[string]string{
+ "gemini-2.5*": "gemini-2.5-flash",
+ }, "gemini-2.5-flash", budget("-1"), "", false},
+ {"bare model absent from whitelist: configured variant still resolved", map[string]string{
"gemini-3.7-flash-medium": "gemini-3.7-flash-medium",
}, "gemini-3.7-flash", budget("4000"), "gemini-3.7-flash-medium", true},
- // 空 credentials 映射 → 走 DefaultAntigravityModelMapping,其中同样只有带后缀的 3.8 flash
+ // 空 credentials 映射保留默认目录兼容行为。
{"empty mapping falls back to default catalog", map[string]string{}, "gemini-3.8-flash", budget("-1"), "gemini-3.8-flash-high", true},
}
for _, tt := range tests {
diff --git a/backend/internal/service/antigravity_rate_limit_test.go b/backend/internal/service/antigravity_rate_limit_test.go
index c63ea9928..0e41871fa 100644
--- a/backend/internal/service/antigravity_rate_limit_test.go
+++ b/backend/internal/service/antigravity_rate_limit_test.go
@@ -844,6 +844,28 @@ func TestSetAntigravityModelRateLimits_GeminiWritesFamilyScope(t *testing.T) {
require.Equal(t, antigravityGeminiModelRateLimitKey, repo.modelRateLimitCalls[1].modelKey)
}
+func TestSetAntigravityModelRateLimits_ImageDoesNotWriteFamilyScope(t *testing.T) {
+ repo := &stubAntigravityAccountRepo{}
+ svc := &AntigravityGatewayService{}
+ account := &Account{ID: 789, Platform: PlatformAntigravity}
+ resetAt := time.Now().Add(30 * time.Second)
+
+ success := svc.setAntigravityModelRateLimits(
+ context.Background(),
+ repo,
+ account,
+ "gemini-3.1-flash-image-preview",
+ "[test]",
+ 429,
+ resetAt,
+ false,
+ )
+
+ require.True(t, success)
+ require.Len(t, repo.modelRateLimitCalls, 1)
+ require.Equal(t, "gemini-3.1-flash-image-preview", repo.modelRateLimitCalls[0].modelKey)
+}
+
func TestSetAntigravityModelRateLimits_DoesNotDoubleMapCustomChain(t *testing.T) {
repo := &stubAntigravityAccountRepo{}
svc := &AntigravityGatewayService{}
@@ -1071,6 +1093,15 @@ func TestResolveAntigravityForwardBaseURL(t *testing.T) {
name: "ultra defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": "ULTRA"}},
want: dailyURL,
},
+ {
+ name: "stored ultra tier id defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": "g1-ultra-lite-tier"}},
+ want: dailyURL,
+ },
+ {
+ name: "stored pro tier id defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": "g1-pro-tier"}},
+ want: dailyURL,
+ },
+ {name: "free tier id defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "free-tier"}}, want: prodURL},
{name: "free defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "free"}}, want: prodURL},
{name: "abnormal defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "Abnormal"}}, want: prodURL},
{name: "unknown defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "enterprise"}}, want: prodURL},
diff --git a/backend/internal/service/api_key_service.go b/backend/internal/service/api_key_service.go
index 61f79645f..200ec24de 100644
--- a/backend/internal/service/api_key_service.go
+++ b/backend/internal/service/api_key_service.go
@@ -130,6 +130,8 @@ type apiKeyAllByUserIDLister interface {
// APIKeyRateLimitData holds rate limit usage and window state for an API key.
type APIKeyRateLimitData struct {
+ // QuotaUsed 是总额度已用量(quota_used)。
+ QuotaUsed float64
Usage5h float64
Usage1d float64
Usage7d float64
diff --git a/backend/internal/service/apicompat_config.go b/backend/internal/service/apicompat_config.go
new file mode 100644
index 000000000..47e71ded3
--- /dev/null
+++ b/backend/internal/service/apicompat_config.go
@@ -0,0 +1,28 @@
+package service
+
+import (
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/pkg/apicompat"
+)
+
+func configuredMinOutputTokens(cfg *config.Config) int {
+ if cfg != nil && cfg.Gateway.MinOutputTokens >= 16 {
+ return cfg.Gateway.MinOutputTokens
+ }
+ return apicompat.DefaultMinMaxOutputTokens
+}
+
+func chatCompletionsToResponses(cfg *config.Config, req *apicompat.ChatCompletionsRequest) (*apicompat.ResponsesRequest, error) {
+ return apicompat.ChatCompletionsToResponsesWithMinOutputTokens(req, configuredMinOutputTokens(cfg))
+}
+
+func anthropicToResponses(cfg *config.Config, req *apicompat.AnthropicRequest) (*apicompat.ResponsesRequest, error) {
+ return apicompat.AnthropicToResponsesWithMinOutputTokens(req, configuredMinOutputTokens(cfg))
+}
+
+func settingServiceConfig(settingService *SettingService) *config.Config {
+ if settingService == nil {
+ return nil
+ }
+ return settingService.cfg
+}
diff --git a/backend/internal/service/billing_cache_service.go b/backend/internal/service/billing_cache_service.go
index bc261b481..228762b64 100644
--- a/backend/internal/service/billing_cache_service.go
+++ b/backend/internal/service/billing_cache_service.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"fmt"
+ "math"
"strconv"
"sync"
"sync/atomic"
@@ -573,6 +574,11 @@ func (s *BillingCacheService) InvalidateAPIKeyRateLimit(ctx context.Context, key
// resets expired windows in-memory and triggers async DB reset,
// and returns an error if any window limit is exceeded.
func (s *BillingCacheService) checkAPIKeyRateLimits(ctx context.Context, apiKey *APIKey) error {
+ return s.checkAPIKeyRateLimitsWithPending(ctx, apiKey, 0)
+}
+
+// checkAPIKeyRateLimitsWithPending 在窗口用量上叠加 pending(即将扣除的金额)后检查限速窗口。
+func (s *BillingCacheService) checkAPIKeyRateLimitsWithPending(ctx context.Context, apiKey *APIKey, pending float64) error {
if s.cache == nil {
// No cache: fall back to reading from DB directly
if s.apiKeyRateLimitLoader == nil {
@@ -583,7 +589,7 @@ func (s *BillingCacheService) checkAPIKeyRateLimits(ctx context.Context, apiKey
return nil // Don't block requests on DB errors
}
return s.evaluateRateLimits(ctx, apiKey, data.Usage5h, data.Usage1d, data.Usage7d,
- data.Window5hStart, data.Window1dStart, data.Window7dStart)
+ data.Window5hStart, data.Window1dStart, data.Window7dStart, pending)
}
cacheData, err := s.cache.GetAPIKeyRateLimit(ctx, apiKey.ID)
@@ -628,11 +634,11 @@ func (s *BillingCacheService) checkAPIKeyRateLimits(ctx context.Context, apiKey
t := time.Unix(cacheData.Window7d, 0)
w7d = &t
}
- return s.evaluateRateLimits(ctx, apiKey, cacheData.Usage5h, cacheData.Usage1d, cacheData.Usage7d, w5h, w1d, w7d)
+ return s.evaluateRateLimits(ctx, apiKey, cacheData.Usage5h, cacheData.Usage1d, cacheData.Usage7d, w5h, w1d, w7d, pending)
}
-// evaluateRateLimits checks usage against limits, triggering async resets for expired windows.
-func (s *BillingCacheService) evaluateRateLimits(ctx context.Context, apiKey *APIKey, usage5h, usage1d, usage7d float64, w5h, w1d, w7d *time.Time) error {
+// evaluateRateLimits checks usage (plus pending) against limits, triggering async resets for expired windows.
+func (s *BillingCacheService) evaluateRateLimits(ctx context.Context, apiKey *APIKey, usage5h, usage1d, usage7d float64, w5h, w1d, w7d *time.Time, pending float64) error {
needsReset := false
// Reset expired windows in-memory for check purposes
@@ -675,13 +681,16 @@ func (s *BillingCacheService) evaluateRateLimits(ctx context.Context, apiKey *AP
}
// Check limits
- if apiKey.RateLimit5h > 0 && usage5h >= apiKey.RateLimit5h {
+ exceeds := func(usage, limit float64) bool {
+ return limit > 0 && (usage >= limit || usage+pending > limit)
+ }
+ if exceeds(usage5h, apiKey.RateLimit5h) {
return ErrAPIKeyRateLimit5hExceeded
}
- if apiKey.RateLimit1d > 0 && usage1d >= apiKey.RateLimit1d {
+ if exceeds(usage1d, apiKey.RateLimit1d) {
return ErrAPIKeyRateLimit1dExceeded
}
- if apiKey.RateLimit7d > 0 && usage7d >= apiKey.RateLimit7d {
+ if exceeds(usage7d, apiKey.RateLimit7d) {
return ErrAPIKeyRateLimit7dExceeded
}
return nil
@@ -781,6 +790,110 @@ func (s *BillingCacheService) CheckBillingEligibility(ctx context.Context, user
return nil
}
+// ReserveFixedCharge 为扣费前即可确定金额的费用(倍率后 USD,如显式缓存存储费)做准入并登记在途预留。
+//
+// 余额模式要求缓存余额覆盖 amount 及用户的其他在途预留;订阅模式要求日 / 周 / 月剩余额度覆盖 amount;
+// API Key 总额度与限速窗口同样叠加 amount。订阅与 API Key 的用量取库中权威值,并叠加同一订阅 / Key 上其他
+// 在途预留:先登记本次预留再读用量,并发的两笔费用中后读用量的一方必然看到另一方(预留或已落库的扣费)。
+// 返回的句柄可能为 nil(未登记任何预留);调用方须在 handler 结束时调用 HandlerDone,预留在计费任务落库后释放。
+// 须在 CheckBillingEligibility 通过后调用;简易模式不校验。
+func (s *BillingCacheService) ReserveFixedCharge(ctx context.Context, user *User, apiKey *APIKey, group *Group, subscription *UserSubscription, amount float64) (*InflightReservation, error) {
+ if user == nil || amount <= 0 || math.IsNaN(amount) || math.IsInf(amount, 0) {
+ return nil, nil
+ }
+ if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple {
+ return nil, nil
+ }
+ subscriptionBill := group != nil && group.IsSubscriptionType() && subscription != nil
+ if !subscriptionBill {
+ balance, err := s.GetUserBalance(ctx, user.ID)
+ if err != nil {
+ return nil, ErrBillingServiceUnavailable.WithCause(err)
+ }
+ if balance < amount {
+ return nil, ErrInsufficientBalance
+ }
+ }
+ res, err := s.reserveInflight(ctx, user, group, subscription, amount, false, false)
+ if err != nil {
+ return nil, err
+ }
+ var subscriptionPending, apiKeyPending float64
+ if subscriptionBill && (group.HasDailyLimit() || group.HasWeeklyLimit() || group.HasMonthlyLimit()) {
+ res, subscriptionPending = s.reserveInflightScope(ctx, res, user.ID, inflightSubscriptionScope(subscription.ID), amount)
+ }
+ if apiKey != nil && (apiKey.Quota > 0 || apiKey.HasRateLimits()) {
+ res, apiKeyPending = s.reserveInflightScope(ctx, res, user.ID, inflightAPIKeyScope(apiKey.ID), amount)
+ }
+ if subscriptionBill {
+ err = s.checkFixedChargeSubscription(ctx, user.ID, group, amount+subscriptionPending)
+ }
+ if err == nil && apiKey != nil {
+ err = s.checkFixedChargeAPIKey(ctx, apiKey, amount+apiKeyPending)
+ }
+ if err != nil {
+ res.Release()
+ return nil, err
+ }
+ return res, nil
+}
+
+// checkFixedChargeSubscription 按库中订阅用量校验日 / 周 / 月剩余额度覆盖 pending。
+func (s *BillingCacheService) checkFixedChargeSubscription(ctx context.Context, userID int64, group *Group, pending float64) error {
+ read := s.GetSubscriptionStatus
+ if s.subRepo != nil {
+ read = s.getSubscriptionFromDB
+ }
+ subData, err := read(ctx, userID, group.ID)
+ if err != nil {
+ return ErrBillingServiceUnavailable.WithCause(err)
+ }
+ if group.HasDailyLimit() && subData.DailyUsage+pending > *group.DailyLimitUSD {
+ return ErrDailyLimitExceeded
+ }
+ if group.HasWeeklyLimit() && subData.WeeklyUsage+pending > *group.WeeklyLimitUSD {
+ return ErrWeeklyLimitExceeded
+ }
+ if group.HasMonthlyLimit() && subData.MonthlyUsage+pending > *group.MonthlyLimitUSD {
+ return ErrMonthlyLimitExceeded
+ }
+ return nil
+}
+
+// checkFixedChargeAPIKey 按库中 Key 用量校验总额度与限速窗口覆盖 pending;未接入仓储时使用请求上下文与限速缓存中的用量。
+func (s *BillingCacheService) checkFixedChargeAPIKey(ctx context.Context, apiKey *APIKey, pending float64) error {
+ if apiKey.Quota <= 0 && !apiKey.HasRateLimits() {
+ return nil
+ }
+ if s.apiKeyRateLimitLoader == nil {
+ if apiKey.Quota > 0 && apiKey.QuotaUsed+pending > apiKey.Quota {
+ return ErrAPIKeyQuotaExhausted
+ }
+ if apiKey.HasRateLimits() {
+ return s.checkAPIKeyRateLimitsWithPending(ctx, apiKey, pending)
+ }
+ return nil
+ }
+ data, err := s.apiKeyRateLimitLoader.GetRateLimitData(ctx, apiKey.ID)
+ if err != nil {
+ return ErrBillingServiceUnavailable.WithCause(err)
+ }
+ exceeds := func(usage, limit float64) bool {
+ return limit > 0 && usage+pending > limit
+ }
+ switch {
+ case exceeds(data.QuotaUsed, apiKey.Quota):
+ return ErrAPIKeyQuotaExhausted
+ case exceeds(data.EffectiveUsage5h(), apiKey.RateLimit5h):
+ return ErrAPIKeyRateLimit5hExceeded
+ case exceeds(data.EffectiveUsage1d(), apiKey.RateLimit1d):
+ return ErrAPIKeyRateLimit1dExceeded
+ case exceeds(data.EffectiveUsage7d(), apiKey.RateLimit7d):
+ return ErrAPIKeyRateLimit7dExceeded
+ }
+ return nil
+}
+
// checkSimpleModeAPIKeyRateLimits is deliberately DB-authoritative. Redis
// updates are asynchronous and can be dropped or missed after a committed
// transaction, so using the cache here could let a limited simple-mode key
diff --git a/backend/internal/service/billing_inflight_reservation.go b/backend/internal/service/billing_inflight_reservation.go
index a1924fe5e..d1129e878 100644
--- a/backend/internal/service/billing_inflight_reservation.go
+++ b/backend/internal/service/billing_inflight_reservation.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"math"
+ "strconv"
"strings"
"sync"
"sync/atomic"
@@ -25,6 +26,16 @@ type InflightBalanceReservationCache interface {
ReleaseInflightBalance(ctx context.Context, userID int64, requestID string) error
}
+// InflightScopeReservationCache 订阅 / API Key 维度在途预留的缓存能力(可选),用于扣费前即可确定金额的费用;
+// 未实现时这两个维度不登记预留(fail-open),准入仍按库中用量校验。
+type InflightScopeReservationCache interface {
+ // ReserveInflightScope 原子地清理 scope 下的过期预留并登记 requestID 的预留(ttl 后自动失效),
+ // 返回登记前该 scope 下其他在途预留的合计。
+ ReserveInflightScope(ctx context.Context, scope, requestID string, amount float64, ttl time.Duration) (float64, error)
+ // ReleaseInflightScope 释放 scope 下 requestID 的预留(幂等)。
+ ReleaseInflightScope(ctx context.Context, scope, requestID string) error
+}
+
// InflightBalanceReservationRenewer 可选:续期仍存活的预留(流式长请求期间防止 TTL 过期)。
type InflightBalanceReservationRenewer interface {
// RenewInflightBalance 若 requestID 仍存在则把其过期时间推迟到 now+ttl;返回是否仍存在。
@@ -54,11 +65,15 @@ const (
// 不再续期,所以最长持有时间受 TTL 约束(计费任务卡死时预留自动过期)。
// 所有方法对 nil 接收者安全。
type InflightReservation struct {
+ // cache 为 nil 表示未登记余额维度的预留。
cache InflightBalanceReservationCache
userID int64
requestID string
amount float64
ttl time.Duration
+ // scopes 是同一金额在订阅 / API Key 维度登记的预留(与余额维度共用 requestID),不续期。
+ scopeCache InflightScopeReservationCache
+ scopes []string
refs atomic.Int64
releaseOnce sync.Once
@@ -116,8 +131,15 @@ func (r *InflightReservation) Release() {
r.refs.Store(0)
relCtx, relCancel := context.WithTimeout(context.Background(), inflightReservationReleaseTimeout)
defer relCancel()
- if err := r.cache.ReleaseInflightBalance(relCtx, r.userID, r.requestID); err != nil {
- logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation release failed for user %d (expires by ttl): %v", r.userID, err)
+ if r.cache != nil {
+ if err := r.cache.ReleaseInflightBalance(relCtx, r.userID, r.requestID); err != nil {
+ logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation release failed for user %d (expires by ttl): %v", r.userID, err)
+ }
+ }
+ for _, scope := range r.scopes {
+ if err := r.scopeCache.ReleaseInflightScope(relCtx, scope, r.requestID); err != nil {
+ logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation release failed for %s (expires by ttl): %v", scope, err)
+ }
}
})
}
@@ -213,7 +235,7 @@ func (s *BillingCacheService) InflightReservationFailClosedOnUnpriced() bool {
// ReserveInflightBalance 简化封装:返回释放函数,不续期、不做计费交接(预留最长存活 TTL)。
func (s *BillingCacheService) ReserveInflightBalance(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64) (func(), error) {
- r, err := s.reserveInflight(ctx, user, group, subscription, estimate, false)
+ r, err := s.reserveInflight(ctx, user, group, subscription, estimate, false, true)
if err != nil {
return noopRelease, err
}
@@ -232,10 +254,50 @@ func (s *BillingCacheService) ReserveInflightBalance(ctx context.Context, user *
// 开关关闭 / 简易模式 / 订阅模式 / estimate <= 0 / 缓存不支持 / 余额读取失败 / Redis 执行失败。
// 仅当 Redis 明确判定 缓存余额 - 在途合计 < estimate(且已有在途请求)时返回 ErrInsufficientBalance。
func (s *BillingCacheService) ReserveInflight(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64) (*InflightReservation, error) {
- return s.reserveInflight(ctx, user, group, subscription, estimate, true)
+ return s.reserveInflight(ctx, user, group, subscription, estimate, true, true)
+}
+
+// inflightSubscriptionScope / inflightAPIKeyScope 是订阅 / API Key 维度在途预留的 scope 名。
+func inflightSubscriptionScope(subscriptionID int64) string {
+ return "sub:" + strconv.FormatInt(subscriptionID, 10)
+}
+
+func inflightAPIKeyScope(apiKeyID int64) string {
+ return "apikey:" + strconv.FormatInt(apiKeyID, 10)
+}
+
+// reserveInflightScope 在 scope 维度为 amount 登记在途预留并挂到 res 上(res 为 nil 时新建句柄),
+// 返回句柄与登记前该 scope 下其他在途预留的合计。开关关闭 / 缓存不支持 / Redis 执行失败时不登记(fail-open),合计按 0。
+func (s *BillingCacheService) reserveInflightScope(ctx context.Context, res *InflightReservation, userID int64, scope string, amount float64) (*InflightReservation, float64) {
+ cfg, ok := s.inflightReservationConfig()
+ if !ok {
+ return res, 0
+ }
+ sc, ok := s.cache.(InflightScopeReservationCache)
+ if !ok || sc == nil {
+ return res, 0
+ }
+ if res == nil {
+ ttl := defaultInflightReservationTTL
+ if cfg.TTLSeconds > 0 {
+ ttl = time.Duration(cfg.TTLSeconds) * time.Second
+ }
+ res = &InflightReservation{userID: userID, requestID: uuid.NewString(), amount: amount, ttl: ttl}
+ res.refs.Store(1)
+ }
+ reserveCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), inflightReservationReserveTimeout)
+ pending, err := sc.ReserveInflightScope(reserveCtx, scope, res.requestID, amount, res.ttl)
+ cancel()
+ if err != nil {
+ logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation failed for %s (fail-open): %v", scope, err)
+ return res, 0
+ }
+ res.scopeCache = sc
+ res.scopes = append(res.scopes, scope)
+ return res, pending
}
-func (s *BillingCacheService) reserveInflight(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64, renew bool) (*InflightReservation, error) {
+func (s *BillingCacheService) reserveInflight(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64, renew, capped bool) (*InflightReservation, error) {
cfg, ok := s.inflightReservationConfig()
if !ok || user == nil {
return nil, nil
@@ -243,7 +305,7 @@ func (s *BillingCacheService) reserveInflight(ctx context.Context, user *User, g
if group != nil && group.IsSubscriptionType() && subscription != nil {
return nil, nil
}
- if cfg.MaxReservationUSD > 0 && estimate > cfg.MaxReservationUSD {
+ if capped && cfg.MaxReservationUSD > 0 && estimate > cfg.MaxReservationUSD {
estimate = cfg.MaxReservationUSD
}
if estimate <= 0 || math.IsNaN(estimate) || math.IsInf(estimate, 0) {
diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go
index 13b0b33f6..2aabe21d1 100644
--- a/backend/internal/service/billing_service.go
+++ b/backend/internal/service/billing_service.go
@@ -444,6 +444,20 @@ func (s *BillingService) initFallbackPricing() {
CacheCreation1hPrice: 4e-6,
SupportsCacheBreakdown: true,
}
+ // Claude Haiku 5.5(2026-10-07,$0.10/$0.50,prompt 超 100k tokens 整单 5x)。
+ // 长文本阶梯与目录 *_above_100k_tokens 绝对价同口径,缺目录时回退也不丢阶梯。
+ s.fallbackPrices["claude-haiku-5-5"] = &ModelPricing{
+ InputPricePerToken: 0.1e-6,
+ OutputPricePerToken: 0.5e-6,
+ CacheCreationPricePerToken: 0.125e-6,
+ CacheReadPricePerToken: 0.01e-6,
+ CacheCreation5mPrice: 0.125e-6,
+ CacheCreation1hPrice: 0.2e-6,
+ SupportsCacheBreakdown: true,
+ LongContextInputThreshold: 100000,
+ LongContextInputMultiplier: 5,
+ LongContextOutputMultiplier: 5,
+ }
// Claude Fable 5.x uses the same input/output and cache-write prices, while
// Fable 5.1 reduces cache reads from $1 to $0.25 per MTok.
s.fallbackPrices["claude-fable-5"] = &ModelPricing{
@@ -474,14 +488,15 @@ func (s *BillingService) initFallbackPricing() {
SupportsCacheBreakdown: false,
}
- // Gemini 3.6 Flash (Google AI pricing: $1.50 input / $7.50 output /
- // $0.15 cached input per MTok). Antigravity's -high/-low/-medium/-tiered
- // aliases are matched below so unavailable remote pricing never records
- // token-bearing requests at $0.
+ // Gemini 3.6 Flash (Google AI pricing: $0.75 input / $3.75 output /
+ // $0.075 cached input per MTok, promotional through 2026-12-31; official
+ // rates double to $1.50/$7.50/$0.15 from 2027-01-01). Antigravity's
+ // -high/-low/-medium/-tiered aliases are matched below so unavailable
+ // remote pricing never records token-bearing requests at $0.
s.fallbackPrices["gemini-3.6-flash"] = &ModelPricing{
- InputPricePerToken: 1.5e-6,
- OutputPricePerToken: 7.5e-6,
- CacheReadPricePerToken: 0.15e-6,
+ InputPricePerToken: 0.75e-6,
+ OutputPricePerToken: 3.75e-6,
+ CacheReadPricePerToken: 0.075e-6,
SupportsCacheBreakdown: false,
}
@@ -509,6 +524,27 @@ func (s *BillingService) initFallbackPricing() {
SupportsCacheBreakdown: false,
}
+ // Gemini 4 Argon (Google AI pricing: $2 input / $10 output / $0.10 cached
+ // input per MTok, promotional through 2026-11-30; official rates double to
+ // $4/$20/$0.20 from 2026-12-01). One rate covers every prompt length.
+ // Antigravity's -high/-low/-medium aliases are matched below so unavailable
+ // remote pricing never records token-bearing requests at $0.
+ s.fallbackPrices["gemini-4-argon"] = &ModelPricing{
+ InputPricePerToken: 2e-6,
+ OutputPricePerToken: 10e-6,
+ CacheReadPricePerToken: 0.1e-6,
+ SupportsCacheBreakdown: false,
+ }
+
+ // Gemini 4 Argon Cyber Permissive (Vertex AI pricing: $4 input / $20 output /
+ // $0.20 cached input per MTok). The Gemini 4 Argon promotion does not apply.
+ s.fallbackPrices["gemini-4-argon-cyber-permissive"] = &ModelPricing{
+ InputPricePerToken: 4e-6,
+ OutputPricePerToken: 20e-6,
+ CacheReadPricePerToken: 0.2e-6,
+ SupportsCacheBreakdown: false,
+ }
+
// OpenAI GPT-5.4(业务指定价格)
s.fallbackPrices["gpt-5.4"] = &ModelPricing{
InputPricePerToken: 2.5e-6, // $2.5 per MTok
@@ -999,7 +1035,7 @@ func (s *BillingService) initFallbackPricing() {
// getFallbackPricing 根据模型系列获取回退价格
func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
- modelLower := strings.ToLower(model)
+ modelLower := normalizeAntigravityClaudeTierAlias(strings.ToLower(model))
if modelLower == "jev-latest" {
return s.fallbackPrices["jev-latest"]
}
@@ -1017,6 +1053,9 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
if claude.IsSonnet55(modelLower) {
return s.fallbackPrices["claude-sonnet-5-5"]
}
+ if claude.IsHaiku55(modelLower) {
+ return s.fallbackPrices["claude-haiku-5-5"]
+ }
if strings.Contains(modelLower, "opus") {
// "opus-5" 必须先判:不能用裸 "5" 匹配,否则 claude-opus-4-5 会被误判。
if strings.Contains(modelLower, "opus-5") || strings.Contains(modelLower, "opus5") {
@@ -1064,6 +1103,13 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
if strings.Contains(modelLower, "gemini-3.8-flash") || strings.Contains(modelLower, "gemini-3-8-flash") {
return s.fallbackPrices["gemini-3.8-flash"]
}
+ // Cyber 变体不享受 Gemini 4 Argon 的优惠价,必须先于 "gemini-4-argon" 判。
+ if strings.Contains(modelLower, "gemini-4-argon-cyber") {
+ return s.fallbackPrices["gemini-4-argon-cyber-permissive"]
+ }
+ if strings.Contains(modelLower, "gemini-4-argon") {
+ return s.fallbackPrices["gemini-4-argon"]
+ }
// DeepSeek 系列:官方模型 V4 Pro/Flash(含 vision-exp)按各自价卡;
// 其余 deepseek-*(含已停服的 deepseek-chat / deepseek-reasoner 与未知型号)
@@ -1325,6 +1371,18 @@ func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) {
return s.getModelPricingAt(model, timezone.Now())
}
+// CacheStoragePricePerTokenHour 返回模型的显式上下文缓存存储单价(每 token 每小时,USD)。
+// 优先级:价格表(override_file 等)按确定性识别配置的值 > 内置型号价 > 内置 Pro/Flash 系列兜底价;
+// 均未命中返回 0。
+func (s *BillingService) CacheStoragePricePerTokenHour(model string) float64 {
+ if s != nil && s.pricingService != nil {
+ if pricing := s.pricingService.GetIdentifiedModelPricing(model); pricing != nil && pricing.CacheStorageCostPerTokenPerHour > 0 {
+ return pricing.CacheStorageCostPerTokenPerHour
+ }
+ }
+ return builtinGeminiCacheStoragePrice(model)
+}
+
// getModelPricingAt 是 GetModelPricing 的带计费时点内部变体:pricingAt 显式
// 驱动 DeepSeek pro→Flash 切换判定(切换点前 Pro 价、之后 Flash 价),使
// 展示/估算路径可与历史补账同刻复算,测试也能用固定时点钉住断言。
@@ -1476,6 +1534,8 @@ type CostInput struct {
Resolver *ModelPricingResolver // 定价解析器
Resolved *ResolvedPricing // 可选:预解析的定价结果(避免重复 Resolve 调用)
LongContextBillingEnabled *bool
+ // DisableModelLongContextPricing 豁免模型价卡的长上下文附加费,不改变自定义区间价格。
+ DisableModelLongContextPricing bool
}
// CalculateCostUnified 统一计费入口,支持三种计费模式。
@@ -1491,7 +1551,7 @@ func (s *BillingService) CalculateCostUnified(input CostInput) (*CostBreakdown,
if err != nil {
return nil, err
}
- breakdown := s.computeTokenBreakdown(pricing, input.Tokens, input.RateMultiplier, input.ServiceTier, applyLongContextBilling)
+ breakdown := s.computeTokenBreakdown(pricing, input.Tokens, input.RateMultiplier, input.ServiceTier, applyLongContextBilling && !input.DisableModelLongContextPricing)
applyCostBreakdownMultiplier(breakdown, reasoningEffortBillingMultiplier(input.ReasoningEffort, pricing.ReasoningEffortMultipliers))
return breakdown, nil
}
@@ -1578,7 +1638,7 @@ func (s *BillingService) calculateTokenCost(resolved *ResolvedPricing, input Cos
}
// 官方长上下文阶梯仅在无区间定价时应用(区间定价已包含上下文分层)。
- applyLongCtx := len(resolved.Intervals) == 0 && contextTierPricingEnabled
+ applyLongCtx := len(resolved.Intervals) == 0 && contextTierPricingEnabled && !input.DisableModelLongContextPricing
breakdown := s.computeTokenBreakdown(pricing, input.Tokens, input.RateMultiplier, input.ServiceTier, applyLongCtx)
applyCostBreakdownMultiplier(breakdown, resolvedChannelTimeMultiplier(resolved, input.PricingAt))
diff --git a/backend/internal/service/billing_service_test.go b/backend/internal/service/billing_service_test.go
index 4d180337c..6cf50e711 100644
--- a/backend/internal/service/billing_service_test.go
+++ b/backend/internal/service/billing_service_test.go
@@ -2055,6 +2055,33 @@ func TestNewModelPricingCatalogFallbackAndContext(t *testing.T) {
require.False(t, cost.LongContextBillingApplied)
})
}
+ // claude-haiku-5-5:prompt 超 100k tokens 整单 5x(官方定价),
+ // billing/catalog/fallback 三源口径一致(issue #7919)。
+ for _, model := range []string{
+ "claude-haiku-5-5",
+ "anthropic/claude-haiku-5.5",
+ } {
+ t.Run(source+"/"+model, func(t *testing.T) {
+ for _, n := range []int{99999, 100000, 100001} {
+ tokens := UsageTokens{
+ InputTokens: n - 3000, OutputTokens: 500,
+ CacheReadTokens: 2000, CacheCreationTokens: 1000,
+ }
+ cost, err := svc.CalculateCost(model, tokens, 1)
+ require.NoError(t, err)
+ im, om := 1.0, 1.0
+ if n > 100000 {
+ im, om = 5.0, 5.0
+ }
+ require.InDelta(t, float64(tokens.InputTokens)*1e-7*im, cost.InputCost, 1e-10)
+ require.InDelta(t, 1000*1.25e-7*im, cost.CacheCreationCost, 1e-10)
+ require.InDelta(t, 2000*1e-8*im, cost.CacheReadCost, 1e-10)
+ require.InDelta(t, 500*5e-7*om, cost.OutputCost, 1e-10)
+ require.InDelta(t, cost.InputCost+cost.OutputCost+cost.CacheCreationCost+cost.CacheReadCost, cost.TotalCost, 1e-10)
+ require.Equal(t, n > 100000, cost.LongContextBillingApplied)
+ }
+ })
+ }
}
}
diff --git a/backend/internal/service/channel_available.go b/backend/internal/service/channel_available.go
index 262a38482..3a6c5aba2 100644
--- a/backend/internal/service/channel_available.go
+++ b/backend/internal/service/channel_available.go
@@ -16,6 +16,7 @@ import (
type AvailableGroupRef struct {
ID int64
Name string
+ I18n GroupI18n
Platform string
SubscriptionType string
RateMultiplier float64
@@ -66,6 +67,7 @@ func (s *ChannelService) ListAvailable(ctx context.Context) ([]AvailableChannel,
groupByID[g.ID] = AvailableGroupRef{
ID: g.ID,
Name: g.Name,
+ I18n: g.I18n,
Platform: g.Platform,
SubscriptionType: g.SubscriptionType,
RateMultiplier: g.RateMultiplier,
diff --git a/backend/internal/service/channel_monitor_checker.go b/backend/internal/service/channel_monitor_checker.go
index d8d29e895..a91ac50a4 100644
--- a/backend/internal/service/channel_monitor_checker.go
+++ b/backend/internal/service/channel_monitor_checker.go
@@ -642,6 +642,8 @@ var monitorAPIKeyPatterns = []struct {
{regexp.MustCompile(`xai-[A-Za-z0-9_-]{6,}`), "xai-***REDACTED***"},
// Gemini / Google API Key:固定前缀 + 35 位
{regexp.MustCompile(`AIza[A-Za-z0-9_-]{35}`), "AIza***REDACTED***"},
+ // Gemini auth key:AQ.Ab 前缀 + 48 位,长度放宽以覆盖格式变体
+ {regexp.MustCompile(`AQ\.Ab[A-Za-z0-9_-]{40,}`), "AQ.***REDACTED***"},
// JWT 三段式(Bearer 后常出现):eyJxxx.eyJxxx.signature
{regexp.MustCompile(`eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}`), "eyJ***REDACTED.JWT***"},
}
@@ -649,7 +651,7 @@ var monitorAPIKeyPatterns = []struct {
// sanitizeErrorMessage 擦除错误/响应文本中可能泄露的 API key。
// 处理两类来源:
// 1. URL query 中的 ?key= / ?api_key= 等(Go *url.Error 会回填完整 URL)
-// 2. 上游 HTTP body 文本里直接出现的 sk-* / xai-* / AIza* / JWT 等密钥碎片
+// 2. 上游 HTTP body 文本里直接出现的 sk-* / xai-* / AIza* / AQ.* / JWT 等密钥碎片
//
// 注意:与 gemini_messages_compat_service.go 的 sanitizeUpstreamErrorMessage 关注点类似但参数集更广,
// 监控模块独立维护,避免互相耦合。
diff --git a/backend/internal/service/channel_monitor_checker_body_test.go b/backend/internal/service/channel_monitor_checker_body_test.go
index 922eb8673..5c347cae8 100644
--- a/backend/internal/service/channel_monitor_checker_body_test.go
+++ b/backend/internal/service/channel_monitor_checker_body_test.go
@@ -279,6 +279,17 @@ func TestRunCheckForModel_Grok_RedactsXAIKeyFromUpstreamBody(t *testing.T) {
}
}
+func TestSanitizeErrorMessage_RedactsGeminiAuthKey(t *testing.T) {
+ authKey := "AQ." + "Ab" + strings.Repeat("Xy9_-z", 8)
+ got := sanitizeErrorMessage(`{"error":{"message":"API key not valid: ` + authKey + `"}}`)
+ if strings.Contains(got, authKey) {
+ t.Fatalf("Gemini auth key leaked: %q", got)
+ }
+ if !strings.Contains(got, "AQ.***REDACTED***") {
+ t.Fatalf("expected redaction marker, got %q", got)
+ }
+}
+
func TestRunCheckForModel_OpenAIResponses_DefaultRequest(t *testing.T) {
h := &openAICaptureHandler{}
endpoint := setupFakeOpenAI(t, h)
diff --git a/backend/internal/service/cn_provider_probe_url_test.go b/backend/internal/service/cn_provider_probe_url_test.go
index 19f2e747a..255499e88 100644
--- a/backend/internal/service/cn_provider_probe_url_test.go
+++ b/backend/internal/service/cn_provider_probe_url_test.go
@@ -6,7 +6,9 @@ package service
import (
"context"
+ "io"
"net/http"
+ "strings"
"testing"
"github.com/MACOS-DO/sub4api/internal/config"
@@ -72,15 +74,13 @@ func (r *fakeCNProbeAccountRepo) GetByID(ctx context.Context, id int64) (*Accoun
return r.account, nil
}
-// kimi coding 账号的 base_url 指向中转(含 api.kimi.com/coding 路径段即可被识别
-// 为 kimi coding plan)→ 衍生额度端点落在中转主机上,白名单未列名必须拒绝。
func TestCNProviderQuotaService_RejectsURLBlockedByPolicy(t *testing.T) {
repo := &fakeCNProbeAccountRepo{account: &Account{
ID: 1, Platform: PlatformKimi, Type: AccountTypeAPIKey, Status: StatusActive,
Credentials: map[string]any{
"account_mode": "coding",
"api_key": "sk-test",
- "base_url": "https://relay.attacker.example/api.kimi.com/coding",
+ "base_url": "https://api.kimi.ai/coding/v1",
},
}}
upstream := &recordingHTTPUpstream{}
@@ -92,6 +92,79 @@ func TestCNProviderQuotaService_RejectsURLBlockedByPolicy(t *testing.T) {
require.Zero(t, upstream.calls, "probe must not issue any upstream request when URL policy rejects the target")
}
+func TestCNProviderQuotaService_RejectsSpoofedKimiURL(t *testing.T) {
+ repo := &fakeCNProbeAccountRepo{account: &Account{
+ ID: 1, Platform: PlatformKimi, Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "account_mode": AccountModeCoding,
+ "api_key": "test-only-placeholder",
+ "base_url": "https://relay.attacker.example/api.kimi.com/coding",
+ },
+ }}
+ upstream := &recordingHTTPUpstream{}
+ svc := NewCNProviderQuotaService(repo, nil, upstream, nil)
+ _, err := svc.QueryUsage(context.Background(), 1)
+ require.ErrorContains(t, err, "CN_QUOTA_NOT_CODING_PLAN")
+ require.Zero(t, upstream.calls)
+}
+
+type kimiQuotaTestRepo struct {
+ fakeCNProbeAccountRepo
+ updates map[string]any
+}
+
+func (r *kimiQuotaTestRepo) UpdateExtra(ctx context.Context, id int64, updates map[string]any) error {
+ r.updates = updates
+ return nil
+}
+
+type kimiQuotaTestUpstream struct {
+ recordingHTTPUpstream
+ request *http.Request
+}
+
+func (u *kimiQuotaTestUpstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) {
+ u.calls++
+ u.request = req
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader(`{"limits":[{"detail":{"limit":100,"remaining":75}}],"usage":{"limit":1000,"remaining":800}}`)),
+ }, nil
+}
+
+func TestCNProviderQuotaService_KimiOfficialHosts(t *testing.T) {
+ for _, host := range []string{"api.kimi.com", "api.kimi.ai"} {
+ for _, path := range []string{"/coding", "/coding/", "/coding/v1", "/coding/v1/"} {
+ t.Run(host+path, func(t *testing.T) {
+ repo := &kimiQuotaTestRepo{fakeCNProbeAccountRepo: fakeCNProbeAccountRepo{account: &Account{
+ ID: 1, Platform: PlatformKimi, Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "account_mode": AccountModeCoding,
+ "api_key": "test-only-placeholder",
+ "base_url": "https://" + host + path,
+ },
+ }}}
+ upstream := &kimiQuotaTestUpstream{}
+ svc := NewCNProviderQuotaService(repo, nil, upstream, cnProbeAllowlistConfig(host))
+ result, err := svc.QueryUsage(context.Background(), 1)
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ require.True(t, result.CredentialValid)
+ require.True(t, result.Persisted)
+ require.Equal(t, PlatformKimi, result.Provider)
+ require.Len(t, result.Tiers, 2)
+ require.Equal(t, float64(25), result.Tiers[0].UsedPercent)
+ require.Equal(t, float64(20), result.Tiers[1].UsedPercent)
+ require.Equal(t, float64(25), repo.updates["kimi_5h_used_percent"])
+ require.Equal(t, 1, upstream.calls)
+ require.Equal(t, http.MethodGet, upstream.request.Method)
+ require.Equal(t, "https://"+host+"/coding/v1/usages", upstream.request.URL.String())
+ require.Equal(t, "Bearer test-only-placeholder", upstream.request.Header.Get("Authorization"))
+ })
+ }
+ }
+}
+
// deepseek payg 账号自定义 base_url → 余额端点落在中转主机上,必须先过策略。
func TestCNProviderBalanceService_RejectsURLBlockedByPolicy(t *testing.T) {
repo := &fakeCNProbeAccountRepo{account: &Account{
diff --git a/backend/internal/service/cn_provider_quota_service.go b/backend/internal/service/cn_provider_quota_service.go
index 39acdadde..3410e0931 100644
--- a/backend/internal/service/cn_provider_quota_service.go
+++ b/backend/internal/service/cn_provider_quota_service.go
@@ -497,7 +497,7 @@ func minimaxResetTime(v gjson.Result) string {
return time.UnixMilli(ms).UTC().Format(time.RFC3339)
}
-// cnZhipuWindow 标识智谱 TOKENS_LIMIT 条目所属窗口。
+// cnZhipuWindow 标识智谱额度条目(TOKENS_LIMIT / CREDIT_LIMIT)所属窗口。
type cnZhipuWindow int
const (
@@ -529,7 +529,8 @@ func classifyZhipuWindowUnit(unit int64) cnZhipuWindow {
//
// CREDIT_LIMIT(信用额度)与 TOKENS_LIMIT(token 窗口)度量不同:两者同时返回时
// 只让 TOKENS_LIMIT 参与 5h/weekly 槽位竞争,避免信用额度百分比污染阈值停调
-// 快照;仅当无任何 TOKENS_LIMIT 条目时才降级用 CREDIT_LIMIT 展示。
+// 快照;仅当无任何 TOKENS_LIMIT 条目时才降级用 CREDIT_LIMIT 展示 —— 此时
+// CREDIT_LIMIT 同样按 unit 分类(它也携带 unit),不依赖 reset 时间排序。
// 老套餐只回 1 条 TOKENS_LIMIT,自然降级为仅 5h;新套餐回 2 条。
func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier {
type entry struct {
@@ -537,6 +538,7 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier {
hasReset bool
percentage float64
resetISO string
+ unit int64
}
var (
fiveHour entry
@@ -546,8 +548,8 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier {
unclassified []entry
)
- classify := func(item gjson.Result, e entry) {
- switch classifyZhipuWindowUnit(item.Get("unit").Int()) {
+ classify := func(unit int64, e entry) {
+ switch classifyZhipuWindowUnit(unit) {
case cnZhipuWindow5h:
if !fiveHourSet {
fiveHour, fiveHourSet = e, true
@@ -592,10 +594,10 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier {
hasReset = resetISO != ""
}
}
- e := entry{resetMs: resetMs, hasReset: hasReset, percentage: percentage, resetISO: resetISO}
+ e := entry{resetMs: resetMs, hasReset: hasReset, percentage: percentage, resetISO: resetISO, unit: item.Get("unit").Int()}
if limitType == "TOKENS_LIMIT" {
hasTokensLimit = true
- classify(item, e)
+ classify(e.unit, e)
} else {
creditFallback = append(creditFallback, e)
}
@@ -603,8 +605,17 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier {
})
// 无任何 TOKENS_LIMIT 条目(部分套餐只报信用额度):降级用 CREDIT_LIMIT 展示。
+ // CREDIT_LIMIT 条目同样带 unit(3=5h / 6=weekly;实测 GLM Coding Plan 两条窗口
+ // 都是 CREDIT_LIMIT),必须和 TOKENS_LIMIT 一样先按 unit 显式分类 —— 否则会退化
+ // 成 reset 时间启发式,而周期末尾周窗口比 5h 更早重置,时间排序必然把两档标反。
if !hasTokensLimit {
- unclassified = append(unclassified, creditFallback...)
+ for _, e := range creditFallback {
+ if classifyZhipuWindowUnit(e.unit) != cnZhipuWindowUnknown {
+ classify(e.unit, e)
+ continue
+ }
+ unclassified = append(unclassified, e)
+ }
}
// 无 reset 的条目排前,再按 reset 升序,依次填入仍空缺的槽位。
diff --git a/backend/internal/service/cn_providers_test.go b/backend/internal/service/cn_providers_test.go
index b623c1eeb..74bb93c3a 100644
--- a/backend/internal/service/cn_providers_test.go
+++ b/backend/internal/service/cn_providers_test.go
@@ -126,6 +126,60 @@ func TestParseZhipuTokenTiers_UnitClassification(t *testing.T) {
require.InDelta(t, 70.0, tiers[1].UsedPercent, 1e-9)
}
+// TestParseZhipuTokenTiers_CreditLimitUnitClassification GLM Coding Plan 当前把 5h / weekly
+// 两条窗口都标成 CREDIT_LIMIT(实测 level=lite)。CREDIT_LIMIT 同样携带 unit,
+// 必须和 TOKENS_LIMIT 一样按 unit 显式分类,否则会退化成 reset 时间排序 ——
+// 此处刻意让 weekly 的 nextResetTime 早于 5h(周期末尾),两档会被标反。
+func TestParseZhipuTokenTiers_CreditLimitUnitClassification(t *testing.T) {
+ t.Parallel()
+ data := gjson.Parse(`{
+ "limits": [
+ {"type":"CREDIT_LIMIT","unit":3,"number":5,"percentage":14,"nextResetTime":1700000099999},
+ {"type":"CREDIT_LIMIT","unit":6,"number":1,"percentage":90,"nextResetTime":1700000000000}
+ ]
+ }`)
+ tiers := parseZhipuTokenTiers(data)
+ require.Len(t, tiers, 2)
+ require.Equal(t, "5h", tiers[0].Window)
+ require.InDelta(t, 14.0, tiers[0].UsedPercent, 1e-9)
+ require.Equal(t, "weekly", tiers[1].Window)
+ require.InDelta(t, 90.0, tiers[1].UsedPercent, 1e-9)
+}
+
+// TestParseZhipuTokenTiers_CreditLimitWithoutUnitFallback CREDIT_LIMIT 缺 unit 时,
+// 保留原有 fallback:无 nextResetTime 的优先归 5h,其余按 reset 升序填入剩余槽位。
+func TestParseZhipuTokenTiers_CreditLimitWithoutUnitFallback(t *testing.T) {
+ t.Parallel()
+ data := gjson.Parse(`{
+ "limits": [
+ {"type":"CREDIT_LIMIT","percentage":30,"nextResetTime":1700000000000},
+ {"type":"CREDIT_LIMIT","percentage":80}
+ ]
+ }`)
+ tiers := parseZhipuTokenTiers(data)
+ require.Len(t, tiers, 2)
+ require.Equal(t, "5h", tiers[0].Window)
+ require.InDelta(t, 80.0, tiers[0].UsedPercent, 1e-9)
+ require.Equal(t, "weekly", tiers[1].Window)
+ require.InDelta(t, 30.0, tiers[1].UsedPercent, 1e-9)
+}
+
+// TestParseZhipuTokenTiers_TokensLimitWinsOverCreditLimit 两种 type 同时返回时,
+// TOKENS_LIMIT 仍然优先占槽、CREDIT_LIMIT 不参与(原有语义保持不变)。
+func TestParseZhipuTokenTiers_TokensLimitWinsOverCreditLimit(t *testing.T) {
+ t.Parallel()
+ data := gjson.Parse(`{
+ "limits": [
+ {"type":"TOKENS_LIMIT","unit":3,"percentage":20,"nextResetTime":1700000000000},
+ {"type":"CREDIT_LIMIT","unit":6,"percentage":99,"nextResetTime":1700000099999}
+ ]
+ }`)
+ tiers := parseZhipuTokenTiers(data)
+ require.Len(t, tiers, 1)
+ require.Equal(t, "5h", tiers[0].Window)
+ require.InDelta(t, 20.0, tiers[0].UsedPercent, 1e-9)
+}
+
// TestParseZhipuTokenTiers_SingleTierOldPlan 老套餐仅回 1 条 → 降级为仅 5h。
func TestParseZhipuTokenTiers_SingleTierOldPlan(t *testing.T) {
t.Parallel()
diff --git a/backend/internal/service/codex_ticket_pool.go b/backend/internal/service/codex_ticket_pool.go
index b645d7f6e..1153571a0 100644
--- a/backend/internal/service/codex_ticket_pool.go
+++ b/backend/internal/service/codex_ticket_pool.go
@@ -103,3 +103,65 @@ func (s *SettingService) AvailableCodexTicketProxies(ctx context.Context) ([]Pro
sort.Slice(available, func(i, j int) bool { return available[i].ID < available[j].ID })
return available, nil
}
+
+type CodexTicketPoolProxyRef struct {
+ ID int64 `json:"id"`
+ Name string `json:"name,omitempty"`
+ Reason string `json:"reason,omitempty"` // deleted | disabled | expired
+}
+
+// CodexTicketPoolView 是代理池的已保存配置加上「此刻实际生效」的结果,供后台核对:
+// Effective 是打票会轮换的代理;Unavailable 是已勾选但当前不会被使用的代理。
+type CodexTicketPoolView struct {
+ CodexTicketPool
+ Source string `json:"source"`
+ Effective []CodexTicketPoolProxyRef `json:"effective"`
+ Unavailable []CodexTicketPoolProxyRef `json:"unavailable"`
+}
+
+func (s *SettingService) DescribeCodexTicketPool(ctx context.Context) (CodexTicketPoolView, error) {
+ pool, err := s.GetCodexTicketPool(ctx)
+ if err != nil {
+ return CodexTicketPoolView{}, err
+ }
+ view := CodexTicketPoolView{CodexTicketPool: pool, Source: s.GetCodexTicketProxySource(ctx),
+ Effective: []CodexTicketPoolProxyRef{}, Unavailable: []CodexTicketPoolProxyRef{}}
+ available, err := s.AvailableCodexTicketProxies(ctx)
+ if err != nil {
+ return view, err
+ }
+ effective := make(map[int64]bool, len(available))
+ for _, proxy := range available {
+ effective[proxy.ID] = true
+ view.Effective = append(view.Effective, CodexTicketPoolProxyRef{ID: proxy.ID, Name: proxy.Name})
+ }
+ if pool.Mode != "custom" {
+ return view, nil
+ }
+ found, err := s.proxyRepo.ListByIDs(ctx, pool.ProxyIDs)
+ if err != nil {
+ return view, err
+ }
+ byID := make(map[int64]Proxy, len(found))
+ for _, proxy := range found {
+ byID[proxy.ID] = proxy
+ }
+ now := time.Now()
+ for _, id := range pool.ProxyIDs {
+ if effective[id] {
+ continue
+ }
+ ref := CodexTicketPoolProxyRef{ID: id, Reason: "deleted"}
+ if proxy, ok := byID[id]; ok {
+ ref.Name = proxy.Name
+ switch {
+ case !proxy.IsActive():
+ ref.Reason = "disabled"
+ case proxy.IsExpired(now):
+ ref.Reason = "expired"
+ }
+ }
+ view.Unavailable = append(view.Unavailable, ref)
+ }
+ return view, nil
+}
diff --git a/backend/internal/service/codex_ticket_pool_test.go b/backend/internal/service/codex_ticket_pool_test.go
new file mode 100644
index 000000000..d2ed76a36
--- /dev/null
+++ b/backend/internal/service/codex_ticket_pool_test.go
@@ -0,0 +1,107 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/stretchr/testify/require"
+)
+
+type codexTicketPoolProxyRepo struct {
+ ProxyRepository
+ proxies []Proxy
+}
+
+func (r *codexTicketPoolProxyRepo) ListActive(context.Context) ([]Proxy, error) {
+ active := make([]Proxy, 0, len(r.proxies))
+ for _, proxy := range r.proxies {
+ if proxy.IsActive() {
+ active = append(active, proxy)
+ }
+ }
+ return active, nil
+}
+
+func (r *codexTicketPoolProxyRepo) ListByIDs(_ context.Context, ids []int64) ([]Proxy, error) {
+ found := make([]Proxy, 0, len(ids))
+ for _, proxy := range r.proxies {
+ for _, id := range ids {
+ if proxy.ID == id {
+ found = append(found, proxy)
+ }
+ }
+ }
+ return found, nil
+}
+
+func codexTicketPoolFixture(t *testing.T) (*SettingService, *runtimeSettingRepoStub, *codexTicketPoolProxyRepo) {
+ t.Helper()
+ repo := newRuntimeSettingRepoStub()
+ proxies := &codexTicketPoolProxyRepo{proxies: []Proxy{
+ {ID: 1, Name: "A", Protocol: "http", Host: "a.example.com", Port: 8001, Status: StatusActive},
+ {ID: 2, Name: "B", Protocol: "http", Host: "b.example.com", Port: 8002, Status: StatusActive},
+ {ID: 3, Name: "C", Protocol: "http", Host: "c.example.com", Port: 8003, Status: StatusActive},
+ }}
+ settings := &SettingService{settingRepo: repo, proxyRepo: proxies}
+ require.NoError(t, settings.SetCodexTicketPool(context.Background(), CodexTicketPool{Mode: "custom", ProxyIDs: []int64{2, 1}}))
+ return settings, repo, proxies
+}
+
+func TestCodexTicketCustomPoolNeverUsesUnselectedProxy(t *testing.T) {
+ settings, _, proxies := codexTicketPoolFixture(t)
+ svc := ticketTestService(t, config.OpenAICodexTicketConfig{Enabled: true}, nil)
+ svc.settingService = settings
+ account := ticketTestAccount(41)
+ accountProxyID := int64(3)
+ account.ProxyID, account.Proxy = &accountProxyID, &proxies.proxies[2]
+
+ used := map[string]int{}
+ for range 20 {
+ _, proxy, err := svc.chooseCodexTicketProxy(context.Background(), account, "gpt-6-astra")
+ require.NoError(t, err)
+ used[proxy.Name]++
+ }
+ require.Equal(t, map[string]int{"A": 10, "B": 10}, used, "the account's own proxy C must not leak into pool mode")
+
+ past := time.Now().Add(-time.Hour)
+ proxies.proxies[0].ExpiresAt = &past
+ for range 5 {
+ _, proxy, err := svc.chooseCodexTicketProxy(context.Background(), account, "gpt-6-astra")
+ require.NoError(t, err)
+ require.Equal(t, "B", proxy.Name)
+ }
+}
+
+func TestDescribeCodexTicketPoolReportsEffectiveAndUnavailable(t *testing.T) {
+ settings, repo, proxies := codexTicketPoolFixture(t)
+ view, err := settings.DescribeCodexTicketPool(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, CodexTicketProxySourcePool, view.Source)
+ require.Equal(t, []CodexTicketPoolProxyRef{{ID: 1, Name: "A"}, {ID: 2, Name: "B"}}, view.Effective)
+ require.Empty(t, view.Unavailable)
+
+ past := time.Now().Add(-time.Hour)
+ proxies.proxies[0].ExpiresAt = &past
+ proxies.proxies[1].Status = "disabled"
+ raw, err := json.Marshal(CodexTicketPool{Mode: "custom", ProxyIDs: []int64{1, 2, 9}})
+ require.NoError(t, err)
+ repo.values[codexTicketPoolSettingKey] = string(raw)
+ repo.values[codexTicketProxySourceSettingKey] = CodexTicketProxySourceAccount
+ view, err = settings.DescribeCodexTicketPool(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, CodexTicketProxySourceAccount, view.Source)
+ require.Empty(t, view.Effective)
+ require.Equal(t, []CodexTicketPoolProxyRef{
+ {ID: 1, Name: "A", Reason: "expired"},
+ {ID: 2, Name: "B", Reason: "disabled"},
+ {ID: 9, Reason: "deleted"},
+ }, view.Unavailable)
+
+ require.NoError(t, settings.SetCodexTicketPool(context.Background(), CodexTicketPool{Mode: "all"}))
+ view, err = settings.DescribeCodexTicketPool(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, []CodexTicketPoolProxyRef{{ID: 3, Name: "C"}}, view.Effective)
+}
diff --git a/backend/internal/service/codex_ticket_proxy_source.go b/backend/internal/service/codex_ticket_proxy_source.go
new file mode 100644
index 000000000..cbcf2415d
--- /dev/null
+++ b/backend/internal/service/codex_ticket_proxy_source.go
@@ -0,0 +1,71 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "strings"
+)
+
+const codexTicketProxySourceSettingKey = "openai_codex_ticket_proxy_source"
+
+const (
+ // CodexTicketProxySourcePool 打票出口从 Codex 打票代理池轮换(默认)。
+ CodexTicketProxySourcePool = "pool"
+ // CodexTicketProxySourceAccount 打票出口与账号业务请求一致:用账号绑定的代理,未绑定则直连。
+ CodexTicketProxySourceAccount = "account"
+)
+
+type CodexTicketProxySource struct {
+ Source string `json:"source"`
+}
+
+func normalizeCodexTicketProxySource(raw string) (string, error) {
+ switch source := strings.TrimSpace(raw); source {
+ case "", CodexTicketProxySourcePool:
+ return CodexTicketProxySourcePool, nil
+ case CodexTicketProxySourceAccount:
+ return source, nil
+ default:
+ return "", errors.New("source must be pool or account")
+ }
+}
+
+// GetCodexTicketProxySource 返回打票出口来源;未配置或读取失败时回退到代理池。
+func (s *SettingService) GetCodexTicketProxySource(ctx context.Context) string {
+ if s == nil || s.settingRepo == nil {
+ return CodexTicketProxySourcePool
+ }
+ raw, err := s.settingRepo.GetValue(ctx, codexTicketProxySourceSettingKey)
+ if err != nil {
+ return CodexTicketProxySourcePool
+ }
+ source, err := normalizeCodexTicketProxySource(raw)
+ if err != nil {
+ return CodexTicketProxySourcePool
+ }
+ return source
+}
+
+func (s *SettingService) SetCodexTicketProxySource(ctx context.Context, raw string) (string, error) {
+ if s == nil || s.settingRepo == nil {
+ return "", ErrSettingNotFound
+ }
+ source, err := normalizeCodexTicketProxySource(raw)
+ if err != nil {
+ return "", err
+ }
+ if err := s.settingRepo.Set(ctx, codexTicketProxySourceSettingKey, source); err != nil {
+ return "", err
+ }
+ return source, nil
+}
+
+// CodexTicketManualProxyAvailable 判断手动打票是否有可用出口:账号模式总有出口(代理或直连),
+// 代理池模式需要池内至少一个可用代理。
+func (s *SettingService) CodexTicketManualProxyAvailable(ctx context.Context) bool {
+ if s.GetCodexTicketProxySource(ctx) == CodexTicketProxySourceAccount {
+ return true
+ }
+ proxies, err := s.AvailableCodexTicketProxies(ctx)
+ return err == nil && len(proxies) > 0
+}
diff --git a/backend/internal/service/codex_ticket_proxy_source_test.go b/backend/internal/service/codex_ticket_proxy_source_test.go
new file mode 100644
index 000000000..203719410
--- /dev/null
+++ b/backend/internal/service/codex_ticket_proxy_source_test.go
@@ -0,0 +1,54 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/stretchr/testify/require"
+)
+
+func TestCodexTicketProxySourceDefaultsToPool(t *testing.T) {
+ repo := newRuntimeSettingRepoStub()
+ settings := &SettingService{settingRepo: repo, proxyRepo: &challengeHarvestProxyRepo{}}
+ require.Equal(t, CodexTicketProxySourcePool, settings.GetCodexTicketProxySource(context.Background()))
+
+ repo.values[codexTicketProxySourceSettingKey] = "bogus"
+ require.Equal(t, CodexTicketProxySourcePool, settings.GetCodexTicketProxySource(context.Background()))
+
+ _, err := settings.SetCodexTicketProxySource(context.Background(), "bogus")
+ require.Error(t, err)
+ source, err := settings.SetCodexTicketProxySource(context.Background(), " account ")
+ require.NoError(t, err)
+ require.Equal(t, CodexTicketProxySourceAccount, source)
+ require.Equal(t, CodexTicketProxySourceAccount, settings.GetCodexTicketProxySource(context.Background()))
+}
+
+func TestChooseCodexTicketProxyHonorsSource(t *testing.T) {
+ repo := newRuntimeSettingRepoStub()
+ svc := ticketTestService(t, config.OpenAICodexTicketConfig{Enabled: true}, nil)
+ svc.settingService = &SettingService{settingRepo: repo, proxyRepo: &challengeHarvestProxyRepo{}}
+
+ accountProxyID := int64(7)
+ account := ticketTestAccount(41)
+ account.ProxyID = &accountProxyID
+ account.Proxy = &Proxy{ID: accountProxyID, Name: "account-ip", Protocol: "socks5h", Host: "account.example.com", Port: 1080, Status: StatusActive}
+
+ url, proxy, err := svc.chooseCodexTicketProxy(context.Background(), account, "gpt-6-astra")
+ require.NoError(t, err)
+ require.Equal(t, int64(1), proxy.ID, "pool mode rotates the ticket proxy pool")
+ require.Equal(t, "http://proxy.example.com:8080", url)
+
+ repo.values[codexTicketProxySourceSettingKey] = CodexTicketProxySourceAccount
+ url, proxy, err = svc.chooseCodexTicketProxy(context.Background(), account, "gpt-6-astra")
+ require.NoError(t, err)
+ require.Equal(t, accountProxyID, proxy.ID)
+ require.Equal(t, "socks5h://account.example.com:1080", url)
+
+ direct := ticketTestAccount(42)
+ url, proxy, err = svc.chooseCodexTicketProxy(context.Background(), direct, "gpt-6-astra")
+ require.NoError(t, err)
+ require.Nil(t, proxy, "account without proxy harvests directly, like its business traffic")
+ require.Empty(t, url)
+ require.True(t, svc.settingService.CodexTicketManualProxyAvailable(context.Background()))
+}
diff --git a/backend/internal/service/composite_model_route.go b/backend/internal/service/composite_model_route.go
index df23d1d0a..7784891d1 100644
--- a/backend/internal/service/composite_model_route.go
+++ b/backend/internal/service/composite_model_route.go
@@ -32,6 +32,11 @@ type CompositeModelOwnership struct {
TargetPlatform string
Matched bool
Ambiguous bool
+ // OpenAIGatewayOAuthClaimed 表示声明方中含 OpenAI 网关族平台的 OAuth /
+ // setup-token 凭据。歧义请求无法解析平台,会落到默认的 Anthropic 网关
+ // handler:Anthropic / Gemini / Antigravity 的 OAuth 在那里有原生或兼容
+ // 转发,API Key 上游可能兼容多种格式,唯独这类凭据只能走 OpenAI 网关。
+ OpenAIGatewayOAuthClaimed bool
}
type CompositeModelOwnershipResolver func(context.Context, int64, string) (CompositeModelOwnership, error)
diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go
index 8ac9e95f0..cbf68cc83 100644
--- a/backend/internal/service/composite_platform_test.go
+++ b/backend/internal/service/composite_platform_test.go
@@ -13,7 +13,7 @@ type compositeOwnershipAccountRepo struct {
accounts []Account
}
-func (r *compositeOwnershipAccountRepo) ListSchedulableByGroupID(context.Context, int64) ([]Account, error) {
+func (r *compositeOwnershipAccountRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) {
return r.accounts, nil
}
@@ -103,6 +103,35 @@ func TestResolveCompositeModelOwnershipAllowsSamePlatformAndRejectsCrossPlatform
require.Equal(t, CompositeModelOwnership{Ambiguous: true}, ambiguous)
}
+// Scenario: 只有 OpenAI 网关族的 OAuth 声明方会被标记(API Key 上游可能兼容多协议,
+// Anthropic / Antigravity 的 OAuth 在默认 Anthropic handler 中可正常转发)
+func TestResolveCompositeModelOwnershipFlagsOpenAIGatewayOAuthClaimants(t *testing.T) {
+ groupID := int64(7)
+ repo := &compositeOwnershipAccountRepo{
+ accounts: []Account{
+ {ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": map[string]any{"gpt-6-astra": "gpt-6-astra"}}},
+ {ID: 2, Platform: PlatformDeepseek, Type: AccountTypeAPIKey, Credentials: map[string]any{"model_mapping": map[string]any{"gpt-6-astra": "deepseek-v4-pro", "apikey-only": "deepseek-v4-pro"}}},
+ {ID: 3, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"model_mapping": map[string]any{"apikey-only": "gpt-5"}}},
+ // Antigravity 账号创建时会把默认映射(含 claude-*)写入 model_mapping。
+ {ID: 4, Platform: PlatformAntigravity, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": map[string]any{"claude-opus-4-8": "claude-opus-4-8"}}},
+ {ID: 5, Platform: PlatformAnthropic, Type: AccountTypeSetupToken, Credentials: map[string]any{"model_mapping": map[string]any{"claude-opus-4-8": "claude-opus-4-8"}}},
+ },
+ }
+ svc := &GatewayService{accountRepo: repo}
+
+ withOAuth, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "gpt-6-astra")
+ require.NoError(t, err)
+ require.Equal(t, CompositeModelOwnership{Ambiguous: true, OpenAIGatewayOAuthClaimed: true}, withOAuth)
+
+ apiKeyOnly, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "apikey-only")
+ require.NoError(t, err)
+ require.Equal(t, CompositeModelOwnership{Ambiguous: true}, apiKeyOnly)
+
+ anthropicFamily, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "claude-opus-4-8")
+ require.NoError(t, err)
+ require.Equal(t, CompositeModelOwnership{Ambiguous: true}, anthropicFamily)
+}
+
func TestNewGatewayServiceWiresCompositeModelOwnershipResolver(t *testing.T) {
groupID := int64(7)
repo := &compositeOwnershipAccountRepo{
diff --git a/backend/internal/service/composite_route_resolver.go b/backend/internal/service/composite_route_resolver.go
index 2eccbf853..7f58ffbc4 100644
--- a/backend/internal/service/composite_route_resolver.go
+++ b/backend/internal/service/composite_route_resolver.go
@@ -5,8 +5,34 @@ import (
"fmt"
"sort"
"strings"
+
+ "github.com/MACOS-DO/sub4api/internal/domain"
+)
+
+const (
+ // CompositeRouteReasonAmbiguous marks a model whose explicit account
+ // mappings span several provider platforms.
+ CompositeRouteReasonAmbiguous = "model is exposed by multiple provider platforms"
+ // CompositeRouteReasonOAuthAmbiguous is the ambiguous case where a claimant
+ // holds an OAuth / setup-token credential that only the OpenAI gateway can
+ // carry, and the model-name fallback would also pick an OpenAI-gateway
+ // platform. The unresolved request would land in the Anthropic gateway
+ // handler and select those credentials, so this group misconfiguration must
+ // be rejected instead of guessing a platform from the model name.
+ CompositeRouteReasonOAuthAmbiguous = "model is exposed by multiple provider platforms including OAuth accounts"
)
+// OAuthAmbiguous reports whether the request must be rejected because the
+// cross-platform ownership involves OpenAI-gateway OAuth credentials.
+func (d CompositeRouteDecision) OAuthAmbiguous() bool {
+ return !d.Matched && d.Reason == CompositeRouteReasonOAuthAmbiguous
+}
+
+// AmbiguousMessage is the client-facing rejection for an OAuthAmbiguous decision.
+func (d CompositeRouteDecision) AmbiguousMessage() string {
+ return fmt.Sprintf("Model %q is mapped on multiple provider platforms in this group; configure an explicit composite route", d.PublicModel)
+}
+
type CompositeRouteResolver struct {
repo CompositeModelRouteRepository
modelOwnershipResolver CompositeModelOwnershipResolver
@@ -117,7 +143,12 @@ func (r *CompositeRouteResolver) Resolve(ctx context.Context, groupID int64, mod
return decision, fmt.Errorf("resolve account model ownership: %w", err)
}
} else if ownership.Ambiguous {
- decision.Reason = "model is exposed by multiple provider platforms"
+ decision.Reason = CompositeRouteReasonAmbiguous
+ // 未解析的请求由下游 handler 按模型名前缀兜底选平台;只有兜底落在
+ // OpenAI 网关族时,OpenAI 网关 OAuth 声明方才会被误送进 Anthropic 管线。
+ if guessed, ok := DetectModelPlatform(model); ok && ownership.OpenAIGatewayOAuthClaimed && domain.UsesOpenAIGateway(guessed) {
+ decision.Reason = CompositeRouteReasonOAuthAmbiguous
+ }
return decision, nil
} else if ownership.Matched {
platform := strings.TrimSpace(ownership.TargetPlatform)
diff --git a/backend/internal/service/composite_route_resolver_test.go b/backend/internal/service/composite_route_resolver_test.go
index 92827ab65..76e40e407 100644
--- a/backend/internal/service/composite_route_resolver_test.go
+++ b/backend/internal/service/composite_route_resolver_test.go
@@ -221,6 +221,33 @@ func TestCompositeRouteResolverDoesNotGuessAmbiguousAccountOwnership(t *testing.
require.False(t, decision.Matched)
require.Empty(t, decision.TargetPlatform)
require.Equal(t, "model is exposed by multiple provider platforms", decision.Reason)
+ require.False(t, decision.OAuthAmbiguous())
+}
+
+// Scenario: 含 OAuth 账号的跨平台歧义必须被识别为需拒绝的配置错误
+func TestCompositeRouteResolverFlagsOAuthAmbiguousOwnership(t *testing.T) {
+ resolver := NewCompositeRouteResolver(nil)
+ resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (CompositeModelOwnership, error) {
+ return CompositeModelOwnership{Ambiguous: true, OpenAIGatewayOAuthClaimed: true}, nil
+ })
+
+ // gpt-* 可被内置探测器识别,验证歧义不会退化为按模型名猜平台。
+ decision, err := resolver.Resolve(context.Background(), 7, "gpt-6-astra", CompositeRouteEndpointResponses)
+
+ require.NoError(t, err)
+ require.False(t, decision.Matched)
+ require.Empty(t, decision.TargetPlatform)
+ require.True(t, decision.OAuthAmbiguous())
+ require.Contains(t, decision.AmbiguousMessage(), `"gpt-6-astra"`)
+
+ // 兜底按模型名落到 Anthropic(如 OpenAI OAuth 映射 claude-* 给 Claude Code 用)
+ // 或无法兜底的自定义别名:OpenAI 网关 OAuth 不会被选中,保持原有行为。
+ for _, model := range []string{"claude-sonnet-4-6", "team-alias"} {
+ decision, err := resolver.Resolve(context.Background(), 7, model, CompositeRouteEndpointMessages)
+ require.NoError(t, err)
+ require.False(t, decision.OAuthAmbiguous(), "model=%s", model)
+ require.Equal(t, CompositeRouteReasonAmbiguous, decision.Reason, "model=%s", model)
+ }
}
func TestCompositeRouteResolverOwnershipLookupErrorFallsBackOnlyForDetectableModels(t *testing.T) {
diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go
index 5c5d51598..78ddbb656 100644
--- a/backend/internal/service/content_moderation.go
+++ b/backend/internal/service/content_moderation.go
@@ -720,7 +720,18 @@ func (s *ContentModerationService) UpdateConfig(ctx context.Context, input Updat
if err != nil {
return nil, fmt.Errorf("marshal content moderation config: %w", err)
}
- if err := s.settingRepo.Set(ctx, SettingKeyContentModerationConfig, string(raw)); err != nil {
+ var saveErr error
+ if writer, ok := s.settingRepo.(interface {
+ SetContentModerationConfig(context.Context, string, []int64) error
+ }); ok {
+ saveErr = writer.SetContentModerationConfig(ctx, string(raw), cfg.GroupIDs)
+ if errors.Is(saveErr, ErrGroupNotFound) {
+ return nil, infraerrors.BadRequest("INVALID_CONTENT_MODERATION_GROUP", "审计分组不存在")
+ }
+ } else {
+ saveErr = s.settingRepo.Set(ctx, SettingKeyContentModerationConfig, string(raw))
+ }
+ if err := saveErr; err != nil {
return nil, fmt.Errorf("save content moderation config: %w", err)
}
s.replaceRuntimeConfig(cfg, raw)
diff --git a/backend/internal/service/gateway_anthropic_base_url_test.go b/backend/internal/service/gateway_anthropic_base_url_test.go
new file mode 100644
index 000000000..9ca8f4b23
--- /dev/null
+++ b/backend/internal/service/gateway_anthropic_base_url_test.go
@@ -0,0 +1,106 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+func gatewayAnthropicBaseURLAccount(apiBaseURLs map[string]any) *Account {
+ return &Account{
+ ID: 8074,
+ Platform: PlatformDeepseek,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "api_key": "test-key",
+ "base_url": "https://api.deepseek.com",
+ "api_protocol": APIProtocolAdaptive,
+ "api_base_urls": apiBaseURLs,
+ },
+ }
+}
+
+func gatewayAnthropicBaseURLContext(t *testing.T) *gin.Context {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
+ return c
+}
+
+func TestGatewayService_AdaptiveAnthropicBaseURLRouting(t *testing.T) {
+ svc := &GatewayService{cfg: &config.Config{}}
+ body := []byte(`{"model":"deepseek-chat","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`)
+
+ t.Run("base present is used by messages and count_tokens", func(t *testing.T) {
+ account := gatewayAnthropicBaseURLAccount(map[string]any{
+ APIProtocolAnthropic: "https://anthropic.example.com",
+ APIProtocolChatCompletions: "https://chat.example.com",
+ })
+ c := gatewayAnthropicBaseURLContext(t)
+
+ req, _, err := svc.buildUpstreamRequest(context.Background(), c, account, body, "test-key", "apikey", "deepseek-chat", false, false)
+ require.NoError(t, err)
+ require.Equal(t, "https://anthropic.example.com/v1/messages?beta=true", req.URL.String())
+
+ countReq, _, err := svc.buildCountTokensRequest(context.Background(), c, account, body, "test-key", "apikey", "deepseek-chat", false)
+ require.NoError(t, err)
+ require.Equal(t, "https://anthropic.example.com/v1/messages/count_tokens?beta=true", countReq.URL.String())
+ })
+
+ t.Run("missing anthropic base uses provider fallback", func(t *testing.T) {
+ account := gatewayAnthropicBaseURLAccount(map[string]any{
+ APIProtocolChatCompletions: "https://chat.example.com",
+ })
+ req, _, err := svc.buildUpstreamRequest(context.Background(), gatewayAnthropicBaseURLContext(t), account, body, "test-key", "apikey", "deepseek-chat", false, false)
+ require.NoError(t, err)
+ require.Equal(t, "https://api.deepseek.com/anthropic/v1/messages?beta=true", req.URL.String())
+ })
+
+ t.Run("ordinary anthropic api key keeps base_url fallback", func(t *testing.T) {
+ account := &Account{
+ Platform: PlatformAnthropic,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "api_key": "test-key",
+ "base_url": "https://custom-anthropic.example.com",
+ },
+ }
+ req, _, err := svc.buildUpstreamRequest(context.Background(), gatewayAnthropicBaseURLContext(t), account, body, "test-key", "apikey", "deepseek-chat", false, false)
+ require.NoError(t, err)
+ require.Equal(t, "https://custom-anthropic.example.com/v1/messages?beta=true", req.URL.String())
+ })
+}
+
+func TestGatewayService_AnthropicPassthroughAndCountTokensUseSelectedBase(t *testing.T) {
+ svc := &GatewayService{cfg: &config.Config{}}
+ account := gatewayAnthropicBaseURLAccount(map[string]any{
+ APIProtocolAnthropic: "https://ollama.com",
+ })
+ body := []byte(`{"model":"deepseek-v4-flash","max_tokens":256000,"messages":[{"role":"user","content":"hi"}]}`)
+ c := gatewayAnthropicBaseURLContext(t)
+
+ passthroughReq, wireBody, err := svc.buildUpstreamRequestAnthropicAPIKeyPassthrough(context.Background(), c, account, body, "test-key")
+ require.NoError(t, err)
+ require.Equal(t, "https://ollama.com/v1/messages?beta=true", passthroughReq.URL.String())
+ require.Equal(t, "Bearer test-key", passthroughReq.Header.Get("Authorization"))
+ require.Equal(t, int64(65535), gjson.GetBytes(wireBody, "max_tokens").Int())
+
+ countPassthroughReq, err := svc.buildCountTokensRequestAnthropicAPIKeyPassthrough(context.Background(), c, account, body, "test-key")
+ require.NoError(t, err)
+ require.Equal(t, "https://ollama.com/v1/messages/count_tokens?beta=true", countPassthroughReq.URL.String())
+ require.Equal(t, "Bearer test-key", countPassthroughReq.Header.Get("Authorization"))
+
+ countReq, _, err := svc.buildCountTokensRequest(context.Background(), c, account, body, "test-key", "apikey", "deepseek-v4-flash", false)
+ require.NoError(t, err)
+ require.Equal(t, "https://ollama.com/v1/messages/count_tokens?beta=true", countReq.URL.String())
+ require.Equal(t, "Bearer test-key", countReq.Header.Get("Authorization"))
+}
diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go
index 39d4324b0..27072dcd6 100644
--- a/backend/internal/service/gateway_anthropic_passthrough.go
+++ b/backend/internal/service/gateway_anthropic_passthrough.go
@@ -184,7 +184,7 @@ func (s *GatewayService) forwardAnthropicAPIKeyPassthroughWithInput(
logger.LegacyPrintf("service.gateway", "[Anthropic Passthrough] Upstream error (retry exhausted, failover): Account=%d(%s) Status=%d RequestID=%s Body=%s",
account.ID, account.Name, resp.StatusCode, resp.Header.Get("x-request-id"), truncateString(string(respBody), 1000))
- s.handleRetryExhaustedSideEffects(ctx, resp, account)
+ s.handleRetryExhaustedSideEffects(ctx, resp, account, input.RequestModel)
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
@@ -209,7 +209,7 @@ func (s *GatewayService) forwardAnthropicAPIKeyPassthroughWithInput(
RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode),
}
}
- return s.handleRetryExhaustedError(ctx, resp, c, account)
+ return s.handleRetryExhaustedError(ctx, resp, c, account, input.RequestModel)
}
if resp.StatusCode >= 400 && s.shouldFailoverUpstreamError(resp.StatusCode) {
@@ -301,7 +301,7 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough(
) (*http.Request, []byte, error) {
body = stripDeferredToolCacheControl(body)
targetURL := claudeAPIURL
- baseURL := account.GetBaseURL()
+ baseURL := getAnthropicGatewayBaseURL(account)
if baseURL != "" {
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
if err != nil {
@@ -326,8 +326,8 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough(
}
// Ollama Cloud DeepSeek 出站 max_tokens clamp:判定与上方 targetURL 的
- // base 取值同源(GetBaseURL),详见 helper 注释。
- body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetBaseURL(), body)
+ // base 取值同源,详见 helper 注释。
+ body = clampOllamaCloudAnthropicMessagesMaxTokens(account, baseURL, body)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body))
if err != nil {
@@ -354,7 +354,7 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough(
req.Header.Del("cookie")
// Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方
// targetURL 的 base 取值),其余保持 extra/default 行为。
- setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL())
+ setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL)
if getHeaderRaw(req.Header, "content-type") == "" {
setHeaderRaw(req.Header, "content-type", "application/json")
diff --git a/backend/internal/service/gateway_bedrock.go b/backend/internal/service/gateway_bedrock.go
index 6ba666a8a..5cb66856e 100644
--- a/backend/internal/service/gateway_bedrock.go
+++ b/backend/internal/service/gateway_bedrock.go
@@ -130,7 +130,9 @@ func (s *GatewayService) forwardBedrock(
// 错误/failover 处理
if resp.StatusCode >= 400 {
- return s.handleBedrockUpstreamErrors(ctx, resp, c, account)
+ // 账号状态按模型隔离时用调度器的模型键(账号映射后的模型名),不是发往上游的 Bedrock 模型 ID;
+ // 两者不一致会让模型级冷却写到调度器不会读取的键上。
+ return s.handleBedrockUpstreamErrors(ctx, resp, c, account, account.GetMappedModel(reqModel))
}
// Bedrock 分支绕过通用 Forward 成功路径,这里保持上游接受回调语义一致。
@@ -263,12 +265,14 @@ func (s *GatewayService) executeBedrockUpstream(
return resp, nil
}
-// handleBedrockUpstreamErrors 处理 Bedrock 上游 4xx/5xx 错误(failover + 错误响应)
+// handleBedrockUpstreamErrors 处理 Bedrock 上游 4xx/5xx 错误(failover + 错误响应);
+// modelKey 是调度器按模型隔离账号状态时使用的模型键(account.GetMappedModel 的结果)。
func (s *GatewayService) handleBedrockUpstreamErrors(
ctx context.Context,
resp *http.Response,
c *gin.Context,
account *Account,
+ modelKey string,
) (*ForwardResult, error) {
// retry exhausted + failover
if s.shouldRetryUpstreamError(account, resp.StatusCode) {
@@ -280,7 +284,7 @@ func (s *GatewayService) handleBedrockUpstreamErrors(
logger.LegacyPrintf("service.gateway", "[Bedrock] Upstream error (retry exhausted, failover): Account=%d(%s) Status=%d Body=%s",
account.ID, account.Name, resp.StatusCode, truncateString(string(respBody), 1000))
- s.handleRetryExhaustedSideEffects(ctx, resp, account)
+ s.handleRetryExhaustedSideEffects(ctx, resp, account, modelKey)
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
@@ -297,7 +301,7 @@ func (s *GatewayService) handleBedrockUpstreamErrors(
RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode),
}
}
- return s.handleRetryExhaustedError(ctx, resp, c, account)
+ return s.handleRetryExhaustedError(ctx, resp, c, account, modelKey)
}
// non-retryable failover
@@ -306,7 +310,7 @@ func (s *GatewayService) handleBedrockUpstreamErrors(
_ = resp.Body.Close()
resp.Body = io.NopCloser(bytes.NewReader(respBody))
- s.handleFailoverSideEffects(ctx, resp, account)
+ s.handleFailoverSideEffects(ctx, resp, account, modelKey)
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
@@ -325,7 +329,7 @@ func (s *GatewayService) handleBedrockUpstreamErrors(
}
// other errors
- return s.handleErrorResponse(ctx, resp, c, account)
+ return s.handleErrorResponse(ctx, resp, c, account, modelKey)
}
// buildUpstreamRequestBedrock 构建 Bedrock 上游请求
diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go
index b4f33b470..e2c847e56 100644
--- a/backend/internal/service/gateway_claude_oauth_body.go
+++ b/backend/internal/service/gateway_claude_oauth_body.go
@@ -263,7 +263,11 @@ func normalizeClaudeOAuthRequestBody(body []byte, modelID string, opts claudeOAu
// temperature:真实 Claude Code CLI 总是发送 temperature(默认 1,客户端可覆盖)。
// 之前的实现直接 delete 会导致 payload 缺字段,与真实 CLI 字节级不一致。
// 策略:客户端传了什么就透传;没传则补默认 1。
- if !gjson.GetBytes(out, "temperature").Exists() && !claude.IsOpus55(modelID) {
+ // 例外:采样锁定的模型(sonnet-5-5/haiku-5-5)上 temperature+top_p 共存即 400,
+ // 客户端只传 top_p 时不得再补 temperature,否则网关自己制造 400(issue #7919)。
+ samplingLocked := claude.IsSonnet55(modelID) || claude.IsHaiku55(modelID)
+ if !gjson.GetBytes(out, "temperature").Exists() && !claude.IsOpus55(modelID) &&
+ (!samplingLocked || !gjson.GetBytes(out, "top_p").Exists()) {
if next, ok := setJSONValueBytes(out, "temperature", 1); ok {
out = next
modified = true
diff --git a/backend/internal/service/gateway_context_management_test.go b/backend/internal/service/gateway_context_management_test.go
index 7cd9e0b57..32644f7fb 100644
--- a/backend/internal/service/gateway_context_management_test.go
+++ b/backend/internal/service/gateway_context_management_test.go
@@ -371,6 +371,25 @@ func TestNormalizeClaudeOAuthRequestBody_HaikuShortModelStillNormalizesToDatedID
require.Equal(t, "claude-haiku-4-5-20251001", gjson.GetBytes(out, "model").String())
}
+// issue #7919:采样锁定的模型上 temperature+top_p 共存即 400,
+// 只传 top_p 时不得再补 temperature,否则网关自己制造 400。
+func TestNormalizeClaudeOAuthRequestBody_SkipsTemperatureTopUpWithTopPOnLockedModels(t *testing.T) {
+ for _, model := range []string{"claude-haiku-5-5", "claude-sonnet-5-5"} {
+ body := []byte(`{"model":"` + model + `","top_p":0.99,"messages":[]}`)
+ out, _ := normalizeClaudeOAuthRequestBody(body, model, claudeOAuthNormalizeOptions{})
+ require.False(t, gjson.GetBytes(out, "temperature").Exists(),
+ "model %s with top_p must not gain temperature", model)
+ require.Equal(t, 0.99, gjson.GetBytes(out, "top_p").Float())
+ }
+}
+
+func TestNormalizeClaudeOAuthRequestBody_StillTopsUpTemperatureWithoutTopP(t *testing.T) {
+ body := []byte(`{"model":"claude-haiku-5-5","messages":[]}`)
+ out, _ := normalizeClaudeOAuthRequestBody(body, "claude-haiku-5-5", claudeOAuthNormalizeOptions{})
+ require.Equal(t, int64(1), gjson.GetBytes(out, "temperature").Int(),
+ "无 top_p 时 temperature:1 补齐保持不变")
+}
+
func TestApplyClaudeCodeOAuthMimicryToBody_HaikuRewritesSystem(t *testing.T) {
account := &Account{ID: 405, Platform: PlatformAnthropic, Type: AccountTypeOAuth}
body := []byte(`{"model":"claude-haiku-4-5","system":"Pi project instructions","messages":[{"role":"user","content":"hello"}]}`)
diff --git a/backend/internal/service/gateway_count_tokens.go b/backend/internal/service/gateway_count_tokens.go
index c99648d34..66dfb4c6f 100644
--- a/backend/internal/service/gateway_count_tokens.go
+++ b/backend/internal/service/gateway_count_tokens.go
@@ -22,6 +22,13 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context,
s.countTokensError(c, http.StatusBadRequest, "invalid_request_error", "Request body is empty")
return fmt.Errorf("parse request: empty request")
}
+ // Antigravity 账户不支持 count_tokens,返回 404 让客户端 fallback 到本地估算。
+ // 返回 nil 避免 handler 层记录为错误,也不设置 ops 上游错误上下文。
+ // 凭据只能走其他协议的 OAuth 账号同理,且必须在取 token、建请求之前拦下。
+ if account != nil && (account.Platform == PlatformAntigravity || !anthropicMessagesCredentialAllowed(account)) {
+ s.countTokensError(c, http.StatusNotFound, "not_found_error", "count_tokens endpoint is not supported for this platform")
+ return nil
+ }
validationModel := parsed.Model
if account != nil {
@@ -42,13 +49,15 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context,
if account != nil && account.IsAnthropicAPIKeyPassthroughEnabled() {
passthroughBody := parsed.Body.Bytes()
+ passthroughModel := parsed.Model
if reqModel := parsed.Model; reqModel != "" {
if mappedModel := account.GetMappedModel(reqModel); mappedModel != reqModel {
passthroughBody = s.replaceModelInBody(passthroughBody, mappedModel)
+ passthroughModel = mappedModel
logger.LegacyPrintf("service.gateway", "CountTokens passthrough model mapping: %s -> %s (account: %s)", reqModel, mappedModel, account.Name)
}
}
- return s.forwardCountTokensAnthropicAPIKeyPassthrough(ctx, c, account, passthroughBody)
+ return s.forwardCountTokensAnthropicAPIKeyPassthrough(ctx, c, account, passthroughBody, passthroughModel)
}
// Bedrock 不支持 count_tokens 端点
@@ -103,13 +112,6 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context,
}
}
- // Antigravity 账户不支持 count_tokens,返回 404 让客户端 fallback 到本地估算。
- // 返回 nil 避免 handler 层记录为错误,也不设置 ops 上游错误上下文。
- if account.Platform == PlatformAntigravity {
- s.countTokensError(c, http.StatusNotFound, "not_found_error", "count_tokens endpoint is not supported for this platform")
- return nil
- }
-
// 应用模型映射:
// - APIKey 账号:使用账号级别的显式映射(如果配置),否则透传原始模型名
// - OAuth/SetupToken 账号:使用 Anthropic 标准映射(短ID → 长ID)
@@ -220,8 +222,8 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context,
// 处理错误响应
if resp.StatusCode >= 400 {
- // 标记账号状态(429/529等)
- s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody)
+ // 标记账号状态(429/529等);传入实际发往上游的模型,临时不可调度规则才能按模型隔离
+ s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, reqModel)
upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody))
upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg)
@@ -267,7 +269,9 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context,
return nil
}
-func (s *GatewayService) forwardCountTokensAnthropicAPIKeyPassthrough(ctx context.Context, c *gin.Context, account *Account, body []byte) error {
+// forwardCountTokensAnthropicAPIKeyPassthrough 透传 count_tokens 请求;upstreamModel 是 body 中实际发往上游的模型,
+// 仅用于上游错误处理按模型隔离。
+func (s *GatewayService) forwardCountTokensAnthropicAPIKeyPassthrough(ctx context.Context, c *gin.Context, account *Account, body []byte, upstreamModel string) error {
token, tokenType, err := s.GetAccessToken(ctx, account)
if err != nil {
s.countTokensError(c, http.StatusBadGateway, "upstream_error", "Failed to get access token")
@@ -322,7 +326,7 @@ func (s *GatewayService) forwardCountTokensAnthropicAPIKeyPassthrough(ctx contex
if resp.StatusCode >= 400 {
if s.rateLimitService != nil {
- s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody)
+ s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, upstreamModel)
}
upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody))
@@ -395,7 +399,7 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough(
) (*http.Request, error) {
body = stripDeferredToolCacheControl(body)
targetURL := claudeAPICountTokensURL
- baseURL := account.GetBaseURL()
+ baseURL := getAnthropicGatewayBaseURL(account)
if baseURL != "" {
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
if err != nil {
@@ -442,7 +446,7 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough(
req.Header.Del("cookie")
// Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方
// targetURL 的 base 取值),其余保持 extra/default 行为。
- setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL())
+ setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL)
if req.Header.Get("content-type") == "" {
req.Header.Set("content-type", "application/json")
@@ -463,8 +467,9 @@ func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Con
body = stripDeferredToolCacheControl(body)
// 确定目标 URL
targetURL := claudeAPICountTokensURL
+ baseURL := ""
if account.Type == AccountTypeAPIKey {
- baseURL := account.GetBaseURL()
+ baseURL = getAnthropicGatewayBaseURL(account)
if baseURL != "" {
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
if err != nil {
@@ -554,7 +559,7 @@ func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Con
} else {
// Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方
// targetURL 的 base 取值),其余保持 extra/default 行为。
- setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL())
+ setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL)
}
// 白名单透传 headers(恢复真实 wire casing)
diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go
index e66e35cad..922d0fda9 100644
--- a/backend/internal/service/gateway_forward.go
+++ b/backend/internal/service/gateway_forward.go
@@ -689,7 +689,7 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A
logger.LegacyPrintf("service.gateway", "[Forward] Upstream error (retry exhausted, failover): Account=%d(%s) Status=%d RequestID=%s Body=%s",
account.ID, account.Name, resp.StatusCode, resp.Header.Get("x-request-id"), truncateString(string(respBody), 1000))
- s.handleRetryExhaustedSideEffects(ctx, resp, account)
+ s.handleRetryExhaustedSideEffects(ctx, resp, account, reqModel)
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
@@ -713,7 +713,7 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A
RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode),
}
}
- return s.handleRetryExhaustedError(ctx, resp, c, account)
+ return s.handleRetryExhaustedError(ctx, resp, c, account, reqModel)
}
// 处理可切换账号的错误
diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go
index ed0716ae3..bdb237a8a 100644
--- a/backend/internal/service/gateway_forward_as_chat_completions.go
+++ b/backend/internal/service/gateway_forward_as_chat_completions.go
@@ -44,7 +44,7 @@ func (s *GatewayService) ForwardAsChatCompletions(
clientStream := ccReq.Stream
// 2. Convert CC → Responses → Anthropic (chained conversion)
- responsesReq, err := apicompat.ChatCompletionsToResponses(&ccReq)
+ responsesReq, err := chatCompletionsToResponses(s.cfg, &ccReq)
if err != nil {
return nil, fmt.Errorf("convert chat completions to responses: %w", err)
}
diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go
index 78a4af4f6..12a332439 100644
--- a/backend/internal/service/gateway_forward_as_responses.go
+++ b/backend/internal/service/gateway_forward_as_responses.go
@@ -37,7 +37,7 @@ func (s *GatewayService) ForwardAsResponses(
) (*ForwardResult, error) {
startTime := time.Now()
- normalizedBody, normalized, err := normalizeOpenAIResponsesLegacyIngress(body)
+ normalizedBody, normalized, err := normalizeOpenAIResponsesLegacyIngressWithConfig(s.cfg, body)
if err != nil {
return nil, err
}
diff --git a/backend/internal/service/gateway_hotpath_optimization_test.go b/backend/internal/service/gateway_hotpath_optimization_test.go
index 9c4404659..d5b5ce803 100644
--- a/backend/internal/service/gateway_hotpath_optimization_test.go
+++ b/backend/internal/service/gateway_hotpath_optimization_test.go
@@ -180,6 +180,10 @@ func (s *modelsListAccountRepoStub) ListSchedulableByGroupID(ctx context.Context
return out, nil
}
+func (s *modelsListAccountRepoStub) ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, _ []string, _ bool) ([]Account, error) {
+ return s.ListSchedulableByGroupID(ctx, *groupID)
+}
+
func (s *modelsListAccountRepoStub) ListSchedulable(ctx context.Context) ([]Account, error) {
s.listAllCalls.Add(1)
if s.err != nil {
diff --git a/backend/internal/service/gateway_image_reasoning_pricing_test.go b/backend/internal/service/gateway_image_reasoning_pricing_test.go
index 39309153b..322f3cb84 100644
--- a/backend/internal/service/gateway_image_reasoning_pricing_test.go
+++ b/backend/internal/service/gateway_image_reasoning_pricing_test.go
@@ -131,7 +131,7 @@ func TestCalculateRecordUsageCost_MediaReasoningPricing(t *testing.T) {
}
var err error
cost, err = svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey,
- []string{model}, 0.5, 0.5, 0.5, 0.5, UsageTokens{}, "", nil, time.Time{})
+ []string{model}, 0.5, 0.5, 0.5, 0.5, UsageTokens{}, "", nil, false, time.Time{})
require.NoError(t, err)
}
require.NotNil(t, cost)
diff --git a/backend/internal/service/gateway_model_availability.go b/backend/internal/service/gateway_model_availability.go
index 6ff256cda..816c2f133 100644
--- a/backend/internal/service/gateway_model_availability.go
+++ b/backend/internal/service/gateway_model_availability.go
@@ -21,6 +21,9 @@ type ModelAvailabilityDiagnosis struct {
// HasModelSupport is true if at least one account's model mapping admits
// the requested model.
HasModelSupport bool
+ // HasRetiredSubscriptionModel records a ChatGPT upstream blocked by model
+ // retirement, so an unsupported request can include migration guidance.
+ HasRetiredSubscriptionModel bool
}
// ModelAvailabilityDiagnoser is implemented by gateway services that can
diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go
index e1f99fc7f..460fd1f0e 100644
--- a/backend/internal/service/gateway_request.go
+++ b/backend/internal/service/gateway_request.go
@@ -570,7 +570,7 @@ func StripEmptyTextBlocks(body []byte) []byte {
// isClaude55SignedThinkingModel identifies models whose default thinking mode
// requires signed history to survive protocol conversion and request filtering.
func isClaude55SignedThinkingModel(model string) bool {
- return claude.IsOpus55(model) || claude.IsSonnet55(model)
+ return claude.IsOpus55(model) || claude.IsSonnet55(model) || claude.IsHaiku55(model)
}
// validateClaude55Request rejects settings that the upstream cannot honor.
@@ -580,14 +580,31 @@ func validateClaude55Request(body []byte, model string) error {
return nil
}
isSonnet55 := claude.IsSonnet55(model)
- switch gjson.GetBytes(body, "thinking.type").String() {
+ isHaiku55 := claude.IsHaiku55(model)
+ thinkingType := gjson.GetBytes(body, "thinking.type").String()
+ switch thinkingType {
case "disabled", "enabled":
+ if isHaiku55 {
+ // haiku-5-5:enabled 一律 400(用 adaptive);disabled 仅 high 及以下
+ // 可用,xhigh/max 上 400。见官方 migration guide。
+ if thinkingType == "enabled" {
+ return fmt.Errorf("claude-haiku-5-5 requires adaptive thinking; omit thinking or use thinking.type=adaptive and output_config.effort")
+ }
+ switch gjson.GetBytes(body, "output_config.effort").String() {
+ case "xhigh", "max":
+ return fmt.Errorf("claude-haiku-5-5 thinking.type=disabled supports only low, medium or high effort")
+ }
+ break
+ }
if isSonnet55 {
return fmt.Errorf("claude-sonnet-5-5 requires adaptive thinking or thinking.type=between_tools; omit thinking or use one of those modes")
}
return fmt.Errorf("claude-opus-5-5 requires adaptive thinking; omit thinking or use thinking.type=adaptive and output_config.effort")
case "between_tools":
if !isSonnet55 {
+ if isHaiku55 {
+ return fmt.Errorf("claude-haiku-5-5 requires adaptive thinking; thinking.type=between_tools is unsupported (use thinking.type=disabled at high effort or below)")
+ }
return fmt.Errorf("claude-opus-5-5 requires adaptive thinking; thinking.type=between_tools is unsupported")
}
effort := gjson.GetBytes(body, "output_config.effort").String()
@@ -604,22 +621,34 @@ func validateClaude55Request(body []byte, model string) error {
if isSonnet55 {
modelName = "claude-sonnet-5-5"
}
- if gjson.GetBytes(body, "tool_choice").String() == "required" {
- return fmt.Errorf("%s does not support forced tool_choice; use auto or none", modelName)
+ if isHaiku55 {
+ modelName = "claude-haiku-5-5"
}
- switch gjson.GetBytes(body, "tool_choice.type").String() {
- case "any", "tool", "function", "custom", "namespace":
- return fmt.Errorf("%s does not support forced tool_choice; use auto or none", modelName)
+ // haiku-5-5 接受强制 tool_choice(响应以 tool call 开头、无 thinking 块),
+ // 与 opus/sonnet-5-5 不同,不拦截。见官方 migration guide。
+ if !isHaiku55 {
+ if gjson.GetBytes(body, "tool_choice").String() == "required" {
+ return fmt.Errorf("%s does not support forced tool_choice; use auto or none", modelName)
+ }
+ switch gjson.GetBytes(body, "tool_choice.type").String() {
+ case "any", "tool", "function", "custom", "namespace":
+ return fmt.Errorf("%s does not support forced tool_choice; use auto or none", modelName)
+ }
}
- if isSonnet55 {
+ if isSonnet55 || isHaiku55 {
if temperature := gjson.GetBytes(body, "temperature"); temperature.Exists() && (temperature.Type != gjson.Number || temperature.Float() != 1) {
- return fmt.Errorf("claude-sonnet-5-5 does not support non-default temperature")
+ return fmt.Errorf("%s does not support non-default temperature", modelName)
}
- if topP := gjson.GetBytes(body, "top_p"); topP.Exists() && (topP.Type != gjson.Number || topP.Float() < 0.99 || topP.Float() > 1) {
- return fmt.Errorf("claude-sonnet-5-5 does not support non-default top_p")
+ // Haiku 5.5 只接受显式 top_p=0.99;保留 Sonnet 5.5 既有的区间策略。
+ if topP := gjson.GetBytes(body, "top_p"); topP.Exists() && (topP.Type != gjson.Number ||
+ (isHaiku55 && topP.Float() != 0.99) || (isSonnet55 && (topP.Float() < 0.99 || topP.Float() > 1))) {
+ return fmt.Errorf("%s does not support non-default top_p", modelName)
}
if gjson.GetBytes(body, "top_k").Exists() {
- return fmt.Errorf("claude-sonnet-5-5 does not support top_k")
+ return fmt.Errorf("%s does not support top_k", modelName)
+ }
+ if isHaiku55 && gjson.GetBytes(body, "temperature").Exists() && gjson.GetBytes(body, "top_p").Exists() {
+ return fmt.Errorf("%s does not allow temperature and top_p together; omit both", modelName)
}
}
return nil
diff --git a/backend/internal/service/gateway_request_haiku55_test.go b/backend/internal/service/gateway_request_haiku55_test.go
new file mode 100644
index 000000000..c81309792
--- /dev/null
+++ b/backend/internal/service/gateway_request_haiku55_test.go
@@ -0,0 +1,55 @@
+//go:build unit
+
+package service
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// issue #7919:claude-haiku-5-5 请求校验(官方 migration guide 口径)。
+func TestValidateClaude55Request_Haiku55(t *testing.T) {
+ const model = "claude-haiku-5-5"
+ const prefix = `{"model":"claude-haiku-5-5","max_tokens":16000,"messages":[{"role":"user","content":"hi"}]`
+ cases := []struct {
+ name string
+ // extra 为追加进最小合法请求的 JSON 片段(含前导逗号)
+ extra string
+ wantErr string // 为空表示期望通过
+ }{
+ {name: "adaptive thinking passes", extra: `,"thinking":{"type":"adaptive"},"output_config":{"effort":"medium"}`},
+ {name: "omitted thinking passes", extra: ``},
+ {name: "enabled thinking rejected", extra: `,"thinking":{"type":"enabled","budget_tokens":8000}`, wantErr: "requires adaptive thinking"},
+ {name: "拒绝 between_tools 并返回 Haiku 错误说明", extra: `,"thinking":{"type":"between_tools"}`, wantErr: "claude-haiku-5-5 requires adaptive thinking; thinking.type=between_tools is unsupported"},
+ {name: "disabled thinking allowed at medium effort", extra: `,"thinking":{"type":"disabled"},"output_config":{"effort":"medium"}`},
+ {name: "disabled thinking allowed when effort omitted", extra: `,"thinking":{"type":"disabled"}`},
+ {name: "disabled thinking rejected at xhigh", extra: `,"thinking":{"type":"disabled"},"output_config":{"effort":"xhigh"}`, wantErr: "supports only low, medium or high effort"},
+ {name: "disabled thinking rejected at max", extra: `,"thinking":{"type":"disabled"},"output_config":{"effort":"max"}`, wantErr: "supports only low, medium or high effort"},
+ {name: "temperature 1 passes", extra: `,"temperature":1`},
+ {name: "non-default temperature rejected", extra: `,"temperature":0.5`, wantErr: "non-default temperature"},
+ {name: "top_p 0.99 passes", extra: `,"top_p":0.99`},
+ {name: "拒绝 top_p=0.995", extra: `,"top_p":0.995`, wantErr: "non-default top_p"},
+ {name: "拒绝 top_p=1", extra: `,"top_p":1`, wantErr: "non-default top_p"},
+ {name: "拒绝字符串 top_p", extra: `,"top_p":"0.99"`, wantErr: "non-default top_p"},
+ {name: "top_p 0.5 rejected", extra: `,"top_p":0.5`, wantErr: "non-default top_p"},
+ {name: "top_k rejected", extra: `,"top_k":5`, wantErr: "does not support top_k"},
+ {name: "temperature and top_p together rejected", extra: `,"temperature":1,"top_p":0.99`, wantErr: "does not allow temperature and top_p together"},
+ {name: "forced tool_choice any allowed", extra: `,"tool_choice":{"type":"any"}`},
+ {name: "forced tool_choice required allowed", extra: `,"tool_choice":"required"`},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ body := []byte(prefix + tc.extra + "}")
+ err := validateClaude55Request(body, model)
+ if tc.wantErr == "" {
+ require.NoError(t, err)
+ return
+ }
+ require.Error(t, err)
+ require.True(t, strings.Contains(err.Error(), tc.wantErr),
+ "error %q should contain %q", err.Error(), tc.wantErr)
+ })
+ }
+}
diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go
index 316c6c13b..54ce480ba 100644
--- a/backend/internal/service/gateway_service.go
+++ b/backend/internal/service/gateway_service.go
@@ -20,7 +20,9 @@ import (
"unsafe"
"github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/pkg/logger"
+ "github.com/MACOS-DO/sub4api/internal/pkg/openai"
"github.com/MACOS-DO/sub4api/internal/pkg/xai"
"github.com/MACOS-DO/sub4api/internal/util/responseheaders"
"github.com/cespare/xxhash/v2"
@@ -649,6 +651,9 @@ type ForwardResult struct {
ImageSizeBreakdown map[string]int
SearchCount int
AudioUsage *AudioUsage
+ // CacheStorageTokenHours 显式上下文缓存的存储量(缓存 token 数 × 存储小时数),按计费模型的
+ // 存储单价折算为费用后叠加在 token 费用之上。
+ CacheStorageTokenHours float64
}
// GatewayFailureStage identifies which request stage failed. The zero value is
@@ -696,6 +701,7 @@ type UpstreamFailoverError struct {
SameAccountRetryMax int // 可选的错误级同账号重试上限,低于 handler 默认预算时优先采用
RequestScopedTransient bool // 故障因素与账号无关(如上游按客户端身份/模型容量降载):可同账号重试,但不得据此对账号做临时封禁
SafeToFailoverAfterWrite bool // 仅写出 SSE 注释等非语义字节时,仍可在同一客户端流中切换账号
+ BoundUpstreamPassthrough bool // 绑定显式缓存的请求在上游网关账号上收到的 429 / 5xx:反映持有缓存的上游账号状态,原样回写不走错误映射
Stage GatewayFailureStage
Scope GatewayFailureScope
Reason GatewayFailureReason
@@ -1456,6 +1462,12 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64,
}
// If no account has model_mapping, return nil (use default)
+ if !hasAnyMapping && platform == PlatformOpenAI {
+ models := filterRetiredOpenAIModelIDs(accounts, openai.DefaultModelIDs())
+ if len(models) != len(openai.DefaultModels) {
+ return models
+ }
+ }
if !hasAnyMapping {
if s.modelsListCache != nil {
s.modelsListCache.Set(cacheKey, []string(nil), s.modelsListCacheTTL)
@@ -1473,6 +1485,12 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64,
if platform == PlatformOpenAI {
models = supplementUnmappedOpenAIModels(accounts, models)
+ models = filterRetiredOpenAIModelIDs(accounts, models)
+ // nil means "use defaults" to listing callers; an empty filtered catalog
+ // must remain authoritative instead of resurrecting retired defaults.
+ if len(models) == 0 {
+ return models
+ }
}
if s.modelsListCache != nil {
@@ -1497,21 +1515,25 @@ func (s *GatewayService) resolveCompositeModelOwnership(ctx context.Context, gro
}
}
- accounts, err := s.accountRepo.ListSchedulableByGroupID(ctx, groupID)
+ // 归属取决于配置而非运行时健康:限流/临时不可调度不应让同一模型在
+ // 「唯一归属」与「歧义」之间来回翻转,否则配置错误只会间歇暴露。
+ accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, &groupID, domain.ConcretePlatformIDs(), false)
if err != nil {
return CompositeModelOwnership{}, err
}
platforms := make(map[string]struct{})
+ ownership := CompositeModelOwnership{}
for _, account := range accounts {
platform := strings.TrimSpace(account.Platform)
if platform == PlatformOpenAIBPS || !isConcreteRequestPlatform(platform) || !explicitModelMappingClaims(account, model) {
continue
}
platforms[platform] = struct{}{}
+ ownership.OpenAIGatewayOAuthClaimed = ownership.OpenAIGatewayOAuthClaimed ||
+ (account.IsOAuth() && domain.UsesOpenAIGateway(account.Platform))
}
- ownership := CompositeModelOwnership{}
if len(platforms) == 1 {
for platform := range platforms {
ownership.TargetPlatform = platform
diff --git a/backend/internal/service/gateway_upstream_request.go b/backend/internal/service/gateway_upstream_request.go
index 1430506a3..ef01376ec 100644
--- a/backend/internal/service/gateway_upstream_request.go
+++ b/backend/internal/service/gateway_upstream_request.go
@@ -9,6 +9,7 @@ import (
"strconv"
"strings"
+ "github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/pkg/claude"
"github.com/MACOS-DO/sub4api/internal/pkg/logger"
"github.com/MACOS-DO/sub4api/internal/util/urlvalidator"
@@ -18,7 +19,37 @@ import (
"github.com/gin-gonic/gin"
)
+// anthropicMessagesForeignOAuthReason 标记账号凭据与 Anthropic Messages 协议不匹配。
+const anthropicMessagesForeignOAuthReason = GatewayFailureReason("anthropic_messages_foreign_oauth")
+
+// anthropicMessagesCredentialAllowed 判断账号凭据能否经 Anthropic Messages 协议
+// 出站。OAuth / setup-token 只对签发它的供应商有效(ChatGPT token 只认
+// chatgpt.com),送错协议既泄露凭据,上游 401 还会被误记到账号头上;
+// API Key 不受限:其上游可能同时兼容多种协议格式。
+func anthropicMessagesCredentialAllowed(account *Account) bool {
+ if !account.IsOAuth() {
+ return true
+ }
+ spec, ok := domain.LookupPlatform(account.Platform)
+ return ok && spec.Gateway == domain.PlatformGatewayAnthropic
+}
+
+// checkAnthropicMessagesCredential 在发出任何上游请求前拦截不匹配的凭据。返回的
+// failover 错误只让 handler 换下一个账号:没有上游响应,也就不触发任何账号处罚。
+func checkAnthropicMessagesCredential(account *Account) error {
+ if anthropicMessagesCredentialAllowed(account) {
+ return nil
+ }
+ return &UpstreamFailoverError{
+ StatusCode: http.StatusBadGateway,
+ Reason: anthropicMessagesForeignOAuthReason,
+ }
+}
+
func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token, tokenType, modelID string, reqStream bool, mimicClaudeCode bool) (*http.Request, []byte, error) {
+ if err := checkAnthropicMessagesCredential(account); err != nil {
+ return nil, nil, err
+ }
body = stripDeferredToolCacheControl(body)
if account.Platform == PlatformAnthropic && account.Type == AccountTypeServiceAccount {
req, err := s.buildUpstreamRequestAnthropicVertex(ctx, c, account, body, token, modelID, reqStream)
@@ -27,8 +58,9 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
// 确定目标URL
targetURL := claudeAPIURL
+ baseURL := ""
if account.Type == AccountTypeAPIKey {
- baseURL := account.GetBaseURL()
+ baseURL = getAnthropicGatewayBaseURL(account)
if baseURL != "" {
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
if err != nil {
@@ -124,9 +156,9 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
}
// Ollama Cloud DeepSeek 出站 max_tokens clamp:判定与上方 targetURL 的
- // base 取值同源(GetBaseURL),仅实际上游为 ollama.com 且映射后出站模型
+ // base 取值同源,仅实际上游为 ollama.com 且映射后出站模型
// 为 DeepSeek 系时压到 cap,详见 helper 注释。
- body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetBaseURL(), body)
+ body = clampOllamaCloudAnthropicMessagesMaxTokens(account, baseURL, body)
req, err := http.NewRequestWithContext(ctx, "POST", targetURL, bytes.NewReader(body))
if err != nil {
@@ -139,7 +171,7 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
} else {
// Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方
// targetURL 的 base 取值),其余保持 extra/default 行为。
- setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL())
+ setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL)
}
// 白名单透传 headers
@@ -225,6 +257,16 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
return req, body, nil
}
+func getAnthropicGatewayBaseURL(account *Account) string {
+ if account == nil {
+ return ""
+ }
+ if baseURL := account.GetAnthropicProtocolBaseURL(); baseURL != "" {
+ return baseURL
+ }
+ return account.GetBaseURL()
+}
+
// vertexSupportedBetaTokens 是 Vertex AI 的 Anthropic 端点接受的 anthropic-beta
// 白名单。Vertex 对任何未知 token 直接 HTTP 400,故采用白名单(与 Bedrock 的
// bedrockSupportedBetaTokens 同思路)而非黑名单:未来 Claude Code 新增的、Vertex 尚未
@@ -419,11 +461,13 @@ func defaultAPIKeyBetaHeader(body []byte) string {
// The legacy streaming beta is incompatible with the stable computer and
// browser toolsets. The per-tool eager_input_streaming field remains available.
+// Applies to Sonnet 5.5 and Haiku 5.5, which share the computer_toolset_20260801
+// / browser_toolset_20260801 toolsets (Haiku 5.5 migration guide).
func filterSonnet55ToolsetBeta(header string, body []byte, modelID string) string {
if at := strings.IndexByte(modelID, '@'); at >= 0 {
modelID = modelID[:at] // Vertex's dated model ID
}
- if !claude.IsSonnet55(modelID) {
+ if !claude.IsSonnet55(modelID) && !claude.IsHaiku55(modelID) {
return header
}
for _, tool := range gjson.GetBytes(body, "tools").Array() {
diff --git a/backend/internal/service/gateway_upstream_request_test.go b/backend/internal/service/gateway_upstream_request_test.go
new file mode 100644
index 000000000..b6093e7fa
--- /dev/null
+++ b/backend/internal/service/gateway_upstream_request_test.go
@@ -0,0 +1,73 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+// Scenario: OAuth / setup-token 凭据只能走签发方协议,API Key 与其他凭据类型不受限
+func TestAnthropicMessagesCredentialAllowed(t *testing.T) {
+ cases := []struct {
+ platform string
+ typ string
+ allowed bool
+ }{
+ {PlatformAnthropic, AccountTypeOAuth, true},
+ {PlatformAnthropic, AccountTypeSetupToken, true},
+ {PlatformAnthropic, AccountTypeServiceAccount, true},
+ {PlatformAnthropic, AccountTypeBedrock, true},
+ {PlatformTypeSafe, AccountTypeOAuth, true},
+ {PlatformOpenAI, AccountTypeAPIKey, true},
+ {PlatformDeepseek, AccountTypeAPIKey, true},
+ {PlatformOpenAI, AccountTypeOAuth, false},
+ {PlatformOpenAI, AccountTypeSetupToken, false},
+ {PlatformGrok, AccountTypeOAuth, false},
+ {PlatformGemini, AccountTypeOAuth, false},
+ {PlatformAntigravity, AccountTypeOAuth, false},
+ }
+ for _, tc := range cases {
+ allowed := anthropicMessagesCredentialAllowed(&Account{ID: 1, Platform: tc.platform, Type: tc.typ})
+ require.Equal(t, tc.allowed, allowed, "%s/%s", tc.platform, tc.typ)
+ }
+}
+
+// Scenario: 回归 —— OpenAI OAuth 账号误入 Anthropic 管线时,在构建请求前即被拒绝
+// (ChatGPT token 不会发往 api.anthropic.com),且只让 handler 换号、不处罚账号
+func TestGatewayBuildUpstreamRequestRejectsForeignOAuthWithoutPenalty(t *testing.T) {
+ account := &Account{ID: 25, Platform: PlatformOpenAI, Type: AccountTypeOAuth}
+ body := []byte(`{"model":"gpt-6-astra","messages":[]}`)
+
+ req, _, err := (&GatewayService{}).buildUpstreamRequest(context.Background(), nil, account, body, "chatgpt-token", "oauth", "gpt-6-astra", true, false)
+ require.Nil(t, req)
+
+ var failoverErr *UpstreamFailoverError
+ require.True(t, errors.As(err, &failoverErr))
+ require.True(t, failoverErr.ShouldRetryNextAccount())
+ require.False(t, failoverErr.RetryableOnSameAccount, "same-account retry would end in temp-unschedulable")
+ require.False(t, failoverErr.IsCredentialFailure())
+ require.Equal(t, anthropicMessagesForeignOAuthReason, failoverErr.Reason)
+}
+
+// Scenario: count_tokens 对不匹配凭据按「平台不支持」返回 404,不取 token、不出站
+func TestForwardCountTokensRejectsForeignOAuthAsUnsupported(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", nil)
+
+ account := &Account{ID: 25, Platform: PlatformOpenAI, Type: AccountTypeOAuth}
+ parsed := &ParsedRequest{Model: "gpt-6-astra", Body: NewRequestBodyRef([]byte(`{"model":"gpt-6-astra","messages":[]}`))}
+
+ err := (&GatewayService{}).ForwardCountTokens(context.Background(), c, account, parsed)
+
+ require.NoError(t, err)
+ require.Equal(t, http.StatusNotFound, w.Code)
+}
diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go
index 71d8bc7a5..65347b004 100644
--- a/backend/internal/service/gateway_upstream_response.go
+++ b/backend/internal/service/gateway_upstream_response.go
@@ -527,13 +527,19 @@ func (s *GatewayService) handleErrorResponse(ctx context.Context, resp *http.Res
return nil, fmt.Errorf("upstream error: %d message=%s", resp.StatusCode, upstreamMsg)
}
-func (s *GatewayService) handleRetryExhaustedSideEffects(ctx context.Context, resp *http.Response, account *Account) {
+// handleRetryExhaustedSideEffects 在重试耗尽后标记账号状态;requestedModel 是实际发往上游的模型,
+// 临时不可调度规则据此按模型隔离。
+func (s *GatewayService) handleRetryExhaustedSideEffects(ctx context.Context, resp *http.Response, account *Account, requestedModel ...string) {
body, _ := s.readUpstreamErrorBody(resp)
statusCode := resp.StatusCode
// OAuth/Setup Token 账号的 403:标记账号异常
if account.IsOAuth() && statusCode == 403 {
- s.rateLimitService.HandleUpstreamError(ctx, account, statusCode, resp.Header, body)
+ if len(requestedModel) > 0 {
+ s.rateLimitService.HandleUpstreamError(ctx, account, statusCode, resp.Header, body, requestedModel[0])
+ } else {
+ s.rateLimitService.HandleUpstreamError(ctx, account, statusCode, resp.Header, body)
+ }
logger.LegacyPrintf("service.gateway", "Account %d: marked as error after %d retries for status %d", account.ID, maxRetryAttempts, statusCode)
} else {
// API Key 未配置错误码:不标记账号状态
@@ -553,14 +559,14 @@ func (s *GatewayService) handleFailoverSideEffects(ctx context.Context, resp *ht
// handleRetryExhaustedError 处理重试耗尽后的错误
// OAuth 403:标记账号异常
// API Key 未配置错误码:仅返回错误,不标记账号
-func (s *GatewayService) handleRetryExhaustedError(ctx context.Context, resp *http.Response, c *gin.Context, account *Account) (*ForwardResult, error) {
+func (s *GatewayService) handleRetryExhaustedError(ctx context.Context, resp *http.Response, c *gin.Context, account *Account, requestedModel ...string) (*ForwardResult, error) {
MarkResponseCommitted(c)
// Capture upstream error body before side-effects consume the stream.
respBody, _ := s.readUpstreamErrorBody(resp)
_ = resp.Body.Close()
resp.Body = io.NopCloser(bytes.NewReader(respBody))
- s.handleRetryExhaustedSideEffects(ctx, resp, account)
+ s.handleRetryExhaustedSideEffects(ctx, resp, account, requestedModel...)
upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody))
upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg)
diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go
index e0b7e6efe..bd5c374a8 100644
--- a/backend/internal/service/gateway_usage_billing.go
+++ b/backend/internal/service/gateway_usage_billing.go
@@ -241,7 +241,8 @@ func isForcedUsageBillingRequestID(requestID string) bool {
return strings.HasPrefix(id, "web_search:") ||
strings.HasPrefix(id, "grok-video:") ||
strings.HasPrefix(id, "grok_audio:") ||
- strings.HasPrefix(id, "grok_realtime:")
+ strings.HasPrefix(id, "grok_realtime:") ||
+ strings.HasPrefix(id, GeminiCachedContentUsageRequestIDPrefix)
}
// StableGrokAudioBillingRequestID is the durable usage_logs / dedup key for one
@@ -787,42 +788,9 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
cacheTTLOverridden = (result.Usage.CacheCreation5mTokens + result.Usage.CacheCreation1hTokens) > 0
}
- // 获取费率倍数(优先级:用户专属 > 分组默认 > 系统默认)
- multiplier := 1.0
- if s.cfg != nil {
- multiplier = s.cfg.Default.RateMultiplier
- }
- if apiKey.GroupID != nil && apiKey.Group != nil {
- groupDefault := apiKey.Group.RateMultiplier
- multiplier = s.ResolveUserGroupRateMultiplier(ctx, user.ID, *apiKey.GroupID, groupDefault)
- }
- // token 倍率叠加高峰因子(token 计费含图片 token,图片按次倍率不受影响)。高峰因子按请求时刻现算,
- // 不并入上面的 getUserGroupRateMultiplier,以免污染 user:group 倍率缓存。
- pricingAt := input.PricingAt
- if pricingAt.IsZero() {
- pricingAt = timezone.Now()
- }
- multiplier, imageMultiplier := computePeakAwareMultipliers(apiKey, multiplier, pricingAt)
-
- // 确定计费模型
- concreteBillingModel := forwardResultBillingModel(result.Model, result.UpstreamModel)
- billingModel := concreteBillingModel
- if input.BillingModelSource == BillingModelSourceChannelMapped && input.ChannelMappedModel != "" {
- billingModel = input.ChannelMappedModel
- }
- if input.BillingModelSource == BillingModelSourceRequested && input.OriginalModel != "" {
- billingModel = input.OriginalModel
- }
- // composite 分组的公开别名(如 all/claude)会经 OriginalModel/ChannelMappedModel
- // 进入上面的来源覆盖:任意别名查无价会静默落 $0,含家族词的别名则被价格表的
- // 家族模糊匹配错计(如 Opus 流量按 Sonnet 兜底价)。除非管理员为别名显式配置了
- // 渠道定价(OpenRouter 式自定价),composite 请求一律按实际转发的具体模型计费。
- if apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite {
- billingModel = s.compositeBillableModel(ctx, apiKey, billingModel, concreteBillingModel)
- }
- // 通用兜底(与 OpenAI 路径的 usageBillingModelCandidates 语义对齐):
- // 选定模型查不到任何价格时回退到实际转发的具体模型。已定价流量不受影响。
- billingModel = s.billableModelWithFallback(ctx, apiKey, billingModel, result.UpstreamModel, result.Model)
+ multiplier, imageMultiplier, pricingAt := s.recordUsageMultipliers(ctx, apiKey, user, input.PricingAt)
+ billingModel := s.recordUsageBillingModel(ctx, apiKey, result, input.ChannelUsageFields)
+ cacheStorageCost := s.cacheStorageCost(result, billingModel)
// 确定 RequestedModel(渠道映射前的原始模型)
requestedModel := result.Model
@@ -840,7 +808,7 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
input.BillingModelSource,
result.UpstreamResponseModel,
result.UpstreamResponseModelConflict,
- result.ImageCount > 0 || result.AudioUsage != nil || result.SearchCount > 0,
+ result.ImageCount > 0 || result.AudioUsage != nil || result.SearchCount > 0 || result.CacheStorageTokenHours > 0,
); responseModel != "" && !strings.EqualFold(responseModel, strings.TrimSpace(billingModel)) {
if identified, responseChannelPriced := s.hasIdentifiedResponseModelPricing(ctx, responseModel, apiKey); identified {
responseCost := s.calculateRecordUsageCost(ctx, result, apiKey, responseModel, multiplier, imageMultiplier, pricingAt)
@@ -866,8 +834,9 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
usageLog := s.buildRecordUsageLog(ctx, input, result, apiKey, user, account, subscription,
requestedModel, multiplier, imageMultiplier, accountRateMultiplier, billingType, cacheTTLOverridden, cost)
- // 计算账号统计定价费用(使用最终上游模型匹配自定义规则)
- if apiKey.GroupID != nil {
+ // 计算账号统计定价费用(使用最终上游模型匹配自定义规则)。纯存储费不是一次模型请求,
+ // 账号统计成本回落 total_cost(官方存储价)。
+ if apiKey.GroupID != nil && !isCacheStorageOnlyResult(result) {
applyAccountStatsCost(ctx, usageLog, s.channelService, s.billingService,
account.ID, *apiKey.GroupID, result.UpstreamModel, result.Model,
// Anthropic's input_tokens excludes cache_read and cache_creation (billed separately);
@@ -879,9 +848,10 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
CacheReadTokens: result.Usage.CacheReadInputTokens,
ImageOutputTokens: result.Usage.ImageOutputTokens,
},
- cost.TotalCost, pricingAt,
+ cost.TotalCost-cacheStorageCost, pricingAt,
accountStatsLongContextPricingEnabled(nil),
)
+ addCacheStorageToAccountStatsCost(usageLog, cacheStorageCost)
}
simpleModeKeyRateLimitOnly := simpleModeKeyRateLimitBillingEnabled(s.cfg, apiKey)
@@ -927,6 +897,112 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
return nil
}
+// recordUsageMultipliers 返回 token / 图片售价倍率(用户专属 > 分组默认 > 系统默认,token 倍率叠加高峰因子)
+// 与计价时刻;pricingAt 为零值时取当前时刻。
+func (s *GatewayService) recordUsageMultipliers(ctx context.Context, apiKey *APIKey, user *User, pricingAt time.Time) (float64, float64, time.Time) {
+ multiplier := 1.0
+ if s.cfg != nil {
+ multiplier = s.cfg.Default.RateMultiplier
+ }
+ if apiKey.GroupID != nil && apiKey.Group != nil {
+ multiplier = apiKey.Group.RateMultiplier
+ if user != nil {
+ multiplier = s.ResolveUserGroupRateMultiplier(ctx, user.ID, *apiKey.GroupID, multiplier)
+ }
+ }
+ // 高峰因子按请求时刻现算,不并入 getUserGroupRateMultiplier,以免污染 user:group 倍率缓存。
+ if pricingAt.IsZero() {
+ pricingAt = timezone.Now()
+ }
+ multiplier, imageMultiplier := computePeakAwareMultipliers(apiKey, multiplier, pricingAt)
+ return multiplier, imageMultiplier, pricingAt
+}
+
+// recordUsageBillingModel 按计费模型来源、composite 规则与无价兜底确定计费模型。
+func (s *GatewayService) recordUsageBillingModel(ctx context.Context, apiKey *APIKey, result *ForwardResult, fields ChannelUsageFields) string {
+ concreteBillingModel := forwardResultBillingModel(result.Model, result.UpstreamModel)
+ billingModel := concreteBillingModel
+ if fields.BillingModelSource == BillingModelSourceChannelMapped && fields.ChannelMappedModel != "" {
+ billingModel = fields.ChannelMappedModel
+ }
+ if fields.BillingModelSource == BillingModelSourceRequested && fields.OriginalModel != "" {
+ billingModel = fields.OriginalModel
+ }
+ // composite 分组的公开别名(如 all/claude)会经 OriginalModel/ChannelMappedModel
+ // 进入上面的来源覆盖:任意别名查无价会静默落 $0,含家族词的别名则被价格表的
+ // 家族模糊匹配错计(如 Opus 流量按 Sonnet 兜底价)。除非管理员为别名显式配置了
+ // 渠道定价(OpenRouter 式自定价),composite 请求一律按实际转发的具体模型计费。
+ if apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite {
+ billingModel = s.compositeBillableModel(ctx, apiKey, billingModel, concreteBillingModel)
+ }
+ // 通用兜底(与 OpenAI 路径的 usageBillingModelCandidates 语义对齐):
+ // 选定模型查不到任何价格时回退到实际转发的具体模型。已定价流量不受影响。
+ return s.billableModelWithFallback(ctx, apiKey, billingModel, result.UpstreamModel, result.Model)
+}
+
+// cacheStoragePrice 返回计费模型的显式缓存存储单价;计费模型未配置时依次回退到实际转发模型与请求模型。
+func (s *GatewayService) cacheStoragePrice(result *ForwardResult, billingModel string) float64 {
+ if s.billingService == nil {
+ return 0
+ }
+ for _, model := range []string{billingModel, result.UpstreamModel, result.Model} {
+ if strings.TrimSpace(model) == "" {
+ continue
+ }
+ if price := s.billingService.CacheStoragePricePerTokenHour(model); price > 0 {
+ return price
+ }
+ }
+ return 0
+}
+
+// cacheStorageCost 返回 result 的显式缓存存储费(USD,倍率前)。
+func (s *GatewayService) cacheStorageCost(result *ForwardResult, billingModel string) float64 {
+ if result.CacheStorageTokenHours <= 0 {
+ return 0
+ }
+ return result.CacheStorageTokenHours * s.cacheStoragePrice(result, billingModel)
+}
+
+// isCacheStorageOnlyResult 判断 result 是否只有显式缓存存储费(延长有效期):不含 token 用量,不算一次模型请求。
+func isCacheStorageOnlyResult(result *ForwardResult) bool {
+ u := result.Usage
+ return result.CacheStorageTokenHours > 0 && u.InputTokens == 0 && u.OutputTokens == 0 &&
+ u.CacheCreationInputTokens == 0 && u.CacheReadInputTokens == 0 && u.ImageOutputTokens == 0 &&
+ result.ImageCount == 0 && result.AudioUsage == nil && result.SearchCount == 0
+}
+
+// CacheStoragePriced 判断 RecordUsage 对 input.Result 采用的计费模型(含回退候选)是否配置了显式缓存存储单价。
+func (s *GatewayService) CacheStoragePriced(ctx context.Context, input *RecordUsageInput) bool {
+ billingModel := s.recordUsageBillingModel(ctx, input.APIKey, input.Result, input.ChannelUsageFields)
+ return s.cacheStoragePrice(input.Result, billingModel) > 0
+}
+
+// QuoteUsageCost 按与 RecordUsage 相同的倍率、计费模型与定价计算 input.Result 的应付金额(倍率后 USD),不记录也不扣费。
+func (s *GatewayService) QuoteUsageCost(ctx context.Context, input *RecordUsageInput) float64 {
+ user := input.User
+ if user == nil {
+ user = input.APIKey.User
+ }
+ multiplier, imageMultiplier, pricingAt := s.recordUsageMultipliers(ctx, input.APIKey, user, input.PricingAt)
+ billingModel := s.recordUsageBillingModel(ctx, input.APIKey, input.Result, input.ChannelUsageFields)
+ cost := s.calculateRecordUsageCost(ctx, input.Result, input.APIKey, billingModel, multiplier, imageMultiplier, pricingAt)
+ if cost == nil {
+ return 0
+ }
+ return cost.ActualCost
+}
+
+// addCacheStorageToAccountStatsCost 把显式缓存存储费按官方价叠加到账号统计成本。
+// 账号统计定价只覆盖 token 部分;统计成本为空时成本统计回落 total_cost,其中已含存储费。
+func addCacheStorageToAccountStatsCost(usageLog *UsageLog, storageCost float64) {
+ if usageLog == nil || usageLog.AccountStatsCost == nil || storageCost <= 0 {
+ return
+ }
+ cost := *usageLog.AccountStatsCost + storageCost
+ usageLog.AccountStatsCost = &cost
+}
+
// calculateRecordUsageCost 根据请求类型计算费用。
func (s *GatewayService) calculateRecordUsageCost(
ctx context.Context,
@@ -964,8 +1040,13 @@ func (s *GatewayService) calculateRecordUsageCost(
return s.billingService.CalculateAudioCost(result.AudioUsage.Mode, result.AudioUsage.DurationOrUnits, cfg, multiplier)
}
- // Token 计费;SearchCount 为叠加 surcharge(不替代 token)。
- tokenCost := s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt)
+ // Token 计费;SearchCount 为叠加 surcharge(不替代 token)。纯存储费不是一次模型请求,不计 token / 按次费用。
+ var tokenCost *CostBreakdown
+ if isCacheStorageOnlyResult(result) {
+ tokenCost = &CostBreakdown{}
+ } else {
+ tokenCost = s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt)
+ }
if result.SearchCount > 0 {
price := groupSearchPricePer1kFromAPIKey(apiKey)
if price != nil && *price == 0 {
@@ -980,6 +1061,14 @@ func (s *GatewayService) calculateRecordUsageCost(
tokenCost.ActualCost += searchCost.ActualCost
}
}
+ // 显式缓存存储费同为叠加 surcharge,与 token 费用使用同一计费模型与倍率。
+ if storageCost := s.cacheStorageCost(result, billingModel); storageCost > 0 {
+ if tokenCost == nil {
+ tokenCost = &CostBreakdown{}
+ }
+ tokenCost.TotalCost += storageCost
+ tokenCost.ActualCost += storageCost * multiplier
+ }
return tokenCost
}
diff --git a/backend/internal/service/gateway_usage_billing_request_id_test.go b/backend/internal/service/gateway_usage_billing_request_id_test.go
index 710f64d23..11e7dfcfe 100644
--- a/backend/internal/service/gateway_usage_billing_request_id_test.go
+++ b/backend/internal/service/gateway_usage_billing_request_id_test.go
@@ -31,9 +31,27 @@ func TestIsForcedUsageBillingRequestID(t *testing.T) {
require.True(t, isForcedUsageBillingRequestID("grok-video:task-1"))
require.True(t, isForcedUsageBillingRequestID("grok_audio:up-1"))
require.True(t, isForcedUsageBillingRequestID("grok_realtime:sess-1"))
+ require.True(t, isForcedUsageBillingRequestID(GeminiCachedContentCreateUsageRequestID("abc")))
require.False(t, isForcedUsageBillingRequestID("resp_abc"))
}
+func TestGeminiCachedContentUsageRequestIDs(t *testing.T) {
+ t.Parallel()
+ publicID, err := NewGeminiCachedContentPublicID()
+ require.NoError(t, err)
+ create := GeminiCachedContentCreateUsageRequestID(publicID)
+ patch := GeminiCachedContentPatchUsageRequestID(publicID)
+ require.Equal(t, "gcache:create:"+publicID, create)
+ require.True(t, strings.HasPrefix(patch, "gcache:patch:"+publicID+":"))
+ require.NotEqual(t, patch, GeminiCachedContentPatchUsageRequestID(publicID), "每次延长各自唯一")
+ require.LessOrEqual(t, len(create), 64, "usage_logs.request_id 列长 64")
+ require.LessOrEqual(t, len(patch), 64, "usage_logs.request_id 列长 64")
+
+ ctx := context.WithValue(context.Background(), ctxkey.ClientRequestID, "client-shared-id")
+ require.Equal(t, create, resolveUsageBillingRequestID(ctx, create), "缓存费用行不被客户端请求 id 覆盖")
+ require.Equal(t, patch, resolveUsageBillingRequestID(ctx, patch))
+}
+
func TestStableGrokAudioBillingRequestID(t *testing.T) {
t.Parallel()
require.Equal(t, "grok_audio:up-1", StableGrokAudioBillingRequestID("up-1"))
diff --git a/backend/internal/service/gateway_websearch_emulation.go b/backend/internal/service/gateway_websearch_emulation.go
index bb2f35909..d3716d713 100644
--- a/backend/internal/service/gateway_websearch_emulation.go
+++ b/backend/internal/service/gateway_websearch_emulation.go
@@ -52,13 +52,27 @@ func getWebSearchManager() *websearch.Manager {
// Judgment chain: manager exists → only web_search tool → global enabled → account/channel enabled.
// Account-level mode: "enabled" (force on), "disabled" (force off), "default" (follow channel).
func (s *GatewayService) shouldEmulateWebSearch(ctx context.Context, account *Account, groupID *int64, body []byte) bool {
- if getWebSearchManager() == nil {
+ return shouldEmulateWebSearchFor(ctx, s.settingService, s.channelService, account, groupID, body)
+}
+
+// shouldEmulateWebSearchFor is shared by the Anthropic gateway and the OpenAI
+// gateway's /v1/messages path.
+func shouldEmulateWebSearchFor(
+ ctx context.Context, settingService *SettingService, channelService *ChannelService,
+ account *Account, groupID *int64, body []byte,
+) bool {
+ if getWebSearchManager() == nil || account == nil || settingService == nil {
+ return false
+ }
+ // OpenAI OAuth/setup-token accounts retain native search regardless of
+ // channel configuration. Only API key accounts opt into emulation.
+ if account.Platform == PlatformOpenAI && account.Type != AccountTypeAPIKey {
return false
}
if !isOnlyWebSearchToolInBody(body) {
return false
}
- if !s.settingService.IsWebSearchEmulationEnabled(ctx) {
+ if !settingService.IsWebSearchEmulationEnabled(ctx) {
return false
}
@@ -69,10 +83,10 @@ func (s *GatewayService) shouldEmulateWebSearch(ctx context.Context, account *Ac
case WebSearchModeDisabled:
return false
default: // "default" → follow channel config
- if groupID == nil || s.channelService == nil {
+ if groupID == nil || channelService == nil {
return false
}
- ch, err := s.channelService.GetChannelForGroup(ctx, *groupID)
+ ch, err := channelService.GetChannelForGroup(ctx, *groupID)
if err != nil || ch == nil {
return false
}
@@ -143,14 +157,21 @@ func extractWebSearchTextFromContent(content gjson.Result) string {
func (s *GatewayService) handleWebSearchEmulation(
ctx context.Context, c *gin.Context, account *Account, parsed *ParsedRequest,
) (*ForwardResult, error) {
- startTime := time.Now()
-
// Release the serial queue lock immediately — we don't need upstream.
if parsed.OnUpstreamAccepted != nil {
parsed.OnUpstreamAccepted()
}
+ return writeEmulatedWebSearch(ctx, c, account, parsed.Body.Bytes(), parsed.Model, parsed.Stream)
+}
+
+// writeEmulatedWebSearch runs the search for the last user message and writes
+// an Anthropic Messages response (SSE when stream is true).
+func writeEmulatedWebSearch(
+ ctx context.Context, c *gin.Context, account *Account, body []byte, model string, stream bool,
+) (*ForwardResult, error) {
+ startTime := time.Now()
- query := extractSearchQueryFromBody(parsed.Body.Bytes())
+ query := extractSearchQueryFromBody(body)
if query == "" {
return nil, fmt.Errorf("web search emulation: no query found in messages")
}
@@ -173,12 +194,11 @@ func (s *GatewayService) handleWebSearchEmulation(
slog.Info("web search emulation: search completed",
"provider", providerName, "results_count", len(resp.Results))
- model := parsed.Model
if model == "" {
model = defaultWebSearchModel
}
- if parsed.Stream {
+ if stream {
return writeWebSearchStreamResponse(c, query, resp, model, startTime)
}
return writeWebSearchNonStreamResponse(c, query, resp, model, startTime)
diff --git a/backend/internal/service/gateway_websearch_emulation_test.go b/backend/internal/service/gateway_websearch_emulation_test.go
index e7eb7c2b5..06be3fe50 100644
--- a/backend/internal/service/gateway_websearch_emulation_test.go
+++ b/backend/internal/service/gateway_websearch_emulation_test.go
@@ -378,3 +378,88 @@ func TestShouldEmulateWebSearch_DefaultMode_NilChannelService(t *testing.T) {
// nil channelService + default mode → returns false
require.False(t, svc.shouldEmulateWebSearch(context.Background(), account, &groupID, webSearchToolBody))
}
+
+func TestShouldEmulateWebSearchFor_OpenAIAPIKeyAccountEnabled(t *testing.T) {
+ mgr := websearch.NewManager([]websearch.ProviderConfig{{Type: "brave", APIKey: "k"}}, nil)
+ SetWebSearchManager(mgr)
+ defer SetWebSearchManager(nil)
+
+ setGlobalWebSearchConfig(&WebSearchEmulationConfig{
+ Enabled: true,
+ Providers: []WebSearchProviderConfig{{Type: "brave", APIKey: "k"}},
+ })
+ defer clearGlobalWebSearchConfig()
+
+ settingSvc := newSettingServiceForWebSearchTest(true)
+ account := &Account{
+ ID: 1,
+ Platform: PlatformOpenAI,
+ Type: AccountTypeAPIKey,
+ Extra: map[string]any{featureKeyWebSearchEmulation: WebSearchModeEnabled},
+ }
+ groupID := int64(0)
+ require.True(t, shouldEmulateWebSearchFor(context.Background(), settingSvc, nil, account, &groupID, webSearchToolBody))
+ require.False(t, shouldEmulateWebSearchFor(context.Background(), settingSvc, nil, account, &groupID, nonWebSearchToolBody))
+}
+
+// Exercise the shared interception gate, including channel inheritance.
+func TestShouldEmulateWebSearchFor_AccountChannelModes(t *testing.T) {
+ previousManager := getWebSearchManager()
+ previousConfig := webSearchEmulationCache.Load()
+ SetWebSearchManager(websearch.NewManager([]websearch.ProviderConfig{{Type: "brave", APIKey: "k"}}, nil))
+ t.Cleanup(func() {
+ SetWebSearchManager(previousManager)
+ if previousConfig == nil {
+ clearGlobalWebSearchConfig()
+ } else {
+ webSearchEmulationCache.Store(previousConfig)
+ }
+ })
+
+ settingSvc := newSettingServiceForWebSearchTest(true)
+ groupID := int64(42)
+ for _, platform := range []string{PlatformOpenAI, PlatformAnthropic} {
+ for _, accountType := range []string{AccountTypeAPIKey, AccountTypeOAuth, AccountTypeSetupToken} {
+ for _, mode := range []string{WebSearchModeDefault, WebSearchModeEnabled, WebSearchModeDisabled} {
+ for _, channelEnabled := range []bool{false, true} {
+ channelMode := "channel_off"
+ if channelEnabled {
+ channelMode = "channel_on"
+ }
+ t.Run(platform+"/"+accountType+"/"+mode+"/"+channelMode, func(t *testing.T) {
+ account := &Account{
+ Platform: platform, Type: accountType,
+ Extra: map[string]any{featureKeyWebSearchEmulation: mode},
+ }
+ channelSvc := newChannelServiceWithCache(groupID, &Channel{
+ ID: 10, Status: StatusActive,
+ FeaturesConfig: map[string]any{
+ featureKeyWebSearchEmulation: map[string]any{platform: channelEnabled},
+ },
+ })
+ want := channelEnabled
+ if accountType == AccountTypeAPIKey {
+ switch mode {
+ case WebSearchModeEnabled:
+ want = true
+ case WebSearchModeDisabled:
+ want = false
+ }
+ } else if platform == PlatformOpenAI {
+ want = false
+ }
+ for _, globalEnabled := range []bool{false, true} {
+ setGlobalWebSearchConfig(&WebSearchEmulationConfig{
+ Enabled: globalEnabled,
+ Providers: []WebSearchProviderConfig{{Type: "brave", APIKey: "k"}},
+ })
+ require.Equal(t, globalEnabled && want, shouldEmulateWebSearchFor(
+ context.Background(), settingSvc, channelSvc, account, &groupID, webSearchToolBody),
+ "globalEnabled=%v", globalEnabled)
+ }
+ })
+ }
+ }
+ }
+ }
+}
diff --git a/backend/internal/service/gemini_cache_storage_pricing.go b/backend/internal/service/gemini_cache_storage_pricing.go
new file mode 100644
index 000000000..c08ed2f68
--- /dev/null
+++ b/backend/internal/service/gemini_cache_storage_pricing.go
@@ -0,0 +1,72 @@
+package service
+
+import (
+ "slices"
+ "strings"
+)
+
+// Gemini 显式上下文缓存存储的内置官方单价(USD / token / 小时,Standard 档)。
+// 存储价与上下文长度无关(≤200K 与 >200K 同价);Priority 档的更高存储价不在此列。
+// 来源:https://ai.google.dev/gemini-api/docs/pricing
+// 与 https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing
+const (
+ geminiProCacheStoragePrice = 4.5e-6 // $4.50 / 1M tokens / 小时
+ geminiFlashCacheStoragePrice = 1e-6 // $1.00 / 1M tokens / 小时,Flash-Lite 同价
+
+ // 3.6/3.7/3.8 Flash 的优惠价 $0.50 / 1M tokens / 小时,有效期至 2026-12-31,
+ // 2027-01-01 起恢复为 geminiFlashCacheStoragePrice。AI Studio 价目页直接标注该优惠价;
+ // Vertex 价目页存储价标 $1.00,优惠以「按该模型净消费返还 50% 抵扣金」发放,
+ // 官方未明确存储费是否在返还范围内,两类账号统一按优惠价计。
+ geminiFlashPromoCacheStoragePrice = 0.5e-6
+)
+
+// geminiCacheStorageModelPrices 是已发布型号的存储单价。模型名等于前缀,或以「前缀-」开头
+// (-preview、-customtools、-001 等变体)即命中;更具体的前缀排在前面。
+var geminiCacheStorageModelPrices = []struct {
+ prefix string
+ price float64
+}{
+ {"gemini-3.8-flash-cyber", geminiFlashCacheStoragePrice},
+ {"gemini-3.8-flash", geminiFlashPromoCacheStoragePrice},
+ {"gemini-3.7-flash", geminiFlashPromoCacheStoragePrice},
+ {"gemini-3.6-flash", geminiFlashPromoCacheStoragePrice},
+ {"gemini-3.5-flash-lite", geminiFlashCacheStoragePrice},
+ {"gemini-3.5-flash", geminiFlashCacheStoragePrice},
+ {"gemini-3.1-flash-lite", geminiFlashCacheStoragePrice},
+ {"gemini-3.1-pro", geminiProCacheStoragePrice},
+ {"gemini-3-flash", geminiFlashCacheStoragePrice},
+ {"gemini-3-pro", geminiProCacheStoragePrice},
+ {"gemini-2.5-flash-lite", geminiFlashCacheStoragePrice},
+ {"gemini-2.5-flash", geminiFlashCacheStoragePrice},
+ {"gemini-2.5-pro", geminiProCacheStoragePrice},
+ {"gemini-2.0-flash-lite", geminiFlashCacheStoragePrice},
+ {"gemini-2.0-flash", geminiFlashCacheStoragePrice},
+}
+
+// builtinGeminiCacheStoragePrice 返回内置的显式缓存存储单价:先按已发布型号匹配,未命中时按系列兜底,
+// Pro 系列取 geminiProCacheStoragePrice,Flash 与 Flash-Lite 系列取 geminiFlashCacheStoragePrice(标准价,
+// 不套用优惠价)。其他 Gemini 模型与非 Gemini 模型返回 0。
+func builtinGeminiCacheStoragePrice(model string) float64 {
+ name := lastSegment(strings.ToLower(strings.TrimSpace(model)))
+ if !strings.HasPrefix(name, "gemini-") {
+ return 0
+ }
+ parts := strings.Split(name, "-")
+ lite := slices.Contains(parts, "lite")
+ for _, entry := range geminiCacheStorageModelPrices {
+ // Flash-Lite 变体只匹配 Flash-Lite 条目:gemini-3.8-flash-lite 不能落到 3.8 Flash 的优惠价。
+ if lite != strings.HasSuffix(entry.prefix, "-lite") {
+ continue
+ }
+ if name == entry.prefix || strings.HasPrefix(name, entry.prefix+"-") {
+ return entry.price
+ }
+ }
+ switch {
+ case slices.Contains(parts, "pro"):
+ return geminiProCacheStoragePrice
+ case slices.Contains(parts, "flash"):
+ return geminiFlashCacheStoragePrice
+ }
+ return 0
+}
diff --git a/backend/internal/service/gemini_cache_storage_pricing_test.go b/backend/internal/service/gemini_cache_storage_pricing_test.go
new file mode 100644
index 000000000..1090f063d
--- /dev/null
+++ b/backend/internal/service/gemini_cache_storage_pricing_test.go
@@ -0,0 +1,80 @@
+//go:build unit
+
+package service
+
+import (
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuiltinGeminiCacheStoragePrice(t *testing.T) {
+ for _, tc := range []struct {
+ model string
+ want float64
+ }{
+ // 已发布型号
+ {"gemini-3.8-flash", 0.5e-6},
+ {"gemini-3.7-flash", 0.5e-6},
+ {"gemini-3.6-flash", 0.5e-6},
+ {"gemini-3.8-flash-cyber", 1e-6},
+ {"gemini-3.5-flash", 1e-6},
+ {"gemini-3.5-flash-lite", 1e-6},
+ {"gemini-3.1-flash-lite", 1e-6},
+ {"gemini-3.1-pro-preview", 4.5e-6},
+ {"gemini-3.1-pro-preview-customtools", 4.5e-6},
+ {"gemini-3-flash-preview", 1e-6},
+ {"gemini-3-pro-preview", 4.5e-6},
+ {"gemini-2.5-pro", 4.5e-6},
+ {"gemini-2.5-flash", 1e-6},
+ {"gemini-2.5-flash-lite", 1e-6},
+ {"gemini-2.0-flash-001", 1e-6},
+ {"gemini-2.0-flash-lite-001", 1e-6},
+ // 资源名与大小写
+ {"models/gemini-3.8-flash", 0.5e-6},
+ {"projects/p/locations/global/publishers/google/models/gemini-2.5-pro", 4.5e-6},
+ {" Gemini-3.8-Flash ", 0.5e-6},
+ // 系列兜底:未发布型号与别名按标准价
+ {"gemini-3.9-flash", 1e-6},
+ {"gemini-3.9-flash-lite", 1e-6},
+ {"gemini-3.8-flash-lite", 1e-6},
+ {"gemini-3.9-pro-preview", 4.5e-6},
+ {"gemini-flash-latest", 1e-6},
+ {"gemini-flash-lite-latest", 1e-6},
+ {"gemini-pro-latest", 4.5e-6},
+ // 无存储价(Gemini 4 Argon 仅支持隐式缓存)
+ {"gemini-4-argon", 0},
+ {"gemini-4-argon-high", 0},
+ {"gemini-4-argon-cyber-permissive", 0},
+ {"gemini-embedding-001", 0},
+ {"gemini-unknown-model", 0},
+ {"claude-sonnet-5-5", 0},
+ {"", 0},
+ } {
+ require.InDelta(t, tc.want, builtinGeminiCacheStoragePrice(tc.model), 1e-15, tc.model)
+ }
+}
+
+func TestCacheStoragePricePerTokenHourPriority(t *testing.T) {
+ pricing := &PricingService{}
+ data, err := pricing.parsePricingData([]byte(`{
+ "gemini-3.8-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075,"output_cost_per_token":0.00000375,
+ "cache_storage_cost_per_token_per_hour":0.000002},
+ "gemini-3.9-flash":{"litellm_provider":"gemini","input_cost_per_token":0.0000015,"output_cost_per_token":0.0000075,
+ "cache_storage_cost_per_token_per_hour":0.0000007},
+ "gemini-2.5-pro":{"litellm_provider":"gemini","input_cost_per_token":0.00000125,"output_cost_per_token":0.00001}}`))
+ require.NoError(t, err)
+ pricing.pricingData = data
+ billing := NewBillingService(&config.Config{}, pricing)
+
+ require.InDelta(t, 2e-6, billing.CacheStoragePricePerTokenHour("gemini-3.8-flash"), 1e-15, "价格表配置值优先于内置型号价")
+ require.InDelta(t, 0.7e-6, billing.CacheStoragePricePerTokenHour("gemini-3.9-flash"), 1e-15, "价格表配置值优先于内置系列兜底价")
+ require.InDelta(t, 4.5e-6, billing.CacheStoragePricePerTokenHour("gemini-2.5-pro"), 1e-15, "价格表条目缺存储价时取内置型号价")
+ require.InDelta(t, 0.5e-6, billing.CacheStoragePricePerTokenHour("gemini-3.7-flash"), 1e-15, "价格表无条目时取内置型号价")
+ require.InDelta(t, 4.5e-6, billing.CacheStoragePricePerTokenHour("gemini-3.9-pro"), 1e-15, "内置型号未命中时取系列兜底价")
+ require.Zero(t, billing.CacheStoragePricePerTokenHour("customer-alias"))
+
+ noCatalog := NewBillingService(&config.Config{}, nil)
+ require.InDelta(t, 0.5e-6, noCatalog.CacheStoragePricePerTokenHour("gemini-3.8-flash"), 1e-15, "无价格服务时取内置价")
+}
diff --git a/backend/internal/service/gemini_cached_content.go b/backend/internal/service/gemini_cached_content.go
new file mode 100644
index 000000000..92d7daf6f
--- /dev/null
+++ b/backend/internal/service/gemini_cached_content.go
@@ -0,0 +1,1226 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/base32"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "net/http"
+ "net/url"
+ "regexp"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+ "github.com/MACOS-DO/sub4api/internal/pkg/geminicli"
+ "github.com/MACOS-DO/sub4api/internal/pkg/logger"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+const (
+ // GeminiCachedContentNamePrefix 是缓存资源名前缀,网关与上游 AI Studio 一致。
+ GeminiCachedContentNamePrefix = "cachedContents/"
+ // GeminiCachedContentNotFoundMessage 与上游对不存在、已过期或无权访问的缓存返回的文案一致。
+ GeminiCachedContentNotFoundMessage = "CachedContent not found (or permission denied)"
+ // GeminiCachedContentNotFoundResponse 是网关对引用不存在缓存统一返回的 403 响应体(与 AI Studio 上游一致)。
+ GeminiCachedContentNotFoundResponse = `{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}`
+
+ geminiCachedContentDefaultTTL = time.Hour
+ geminiCachedContentDefaultMaxTTL = 24 * time.Hour
+ geminiCachedContentDisplayNameMaxRunes = 128
+ geminiCachedContentUpstreamTagPrefix = "s2a-"
+ geminiCachedContentResponseMaxBytes = 4 << 20
+ geminiCachedContentUpstreamTimeout = 5 * time.Minute
+ geminiCachedContentOfficialHost = "generativelanguage.googleapis.com"
+
+ // geminiCachedContentMutationUpstreamTimeout 是修改 / 删除上游缓存的单次调用超时。
+ geminiCachedContentMutationUpstreamTimeout = 30 * time.Second
+ // geminiCachedContentMutationLease 是修改意图的租约时长,须覆盖持有者在租约内的全部操作
+ // (一次上游修改与一次落库,或恢复流程的一次上游回滚与一次落库),租约过期后持有者不会再改动上游。
+ geminiCachedContentMutationLease = 2 * time.Minute
+ // geminiCachedContentMutationRecoveryInterval / geminiCachedContentMutationRecoveryBatch 约束后台回滚恢复的节奏;
+ // geminiCachedContentMutationRecoveryTimeout 是恢复单条记录的落库超时,与一次上游回滚合计不超过租约。
+ geminiCachedContentMutationRecoveryInterval = time.Minute
+ geminiCachedContentMutationRecoveryBatch = 50
+ geminiCachedContentMutationRecoveryTimeout = time.Minute
+ // geminiCachedContentMutationAbandonGrace 是判定"上游缓存必已自行过期"时额外容忍的网关与上游时钟偏差。
+ geminiCachedContentMutationAbandonGrace = time.Hour
+
+ // GeminiCachedContentListDefaultPageSize / GeminiCachedContentListMaxPageSize 约束 list 分页。
+ GeminiCachedContentListDefaultPageSize = 50
+ GeminiCachedContentListMaxPageSize = 1000
+)
+
+var (
+ ErrGeminiCachedContentNotFound = infraerrors.New(http.StatusNotFound, "GEMINI_CACHED_CONTENT_NOT_FOUND", "gemini cached content not found")
+ ErrGeminiCachedContentExists = infraerrors.New(http.StatusConflict, "GEMINI_CACHED_CONTENT_EXISTS", "gemini cached content already exists")
+ // ErrGeminiCachedContentMutationConflict 表示同一缓存有进行中的修改、到期时间已被其他修改改变,或修改意图已不属于调用方。
+ ErrGeminiCachedContentMutationConflict = infraerrors.New(http.StatusConflict, "GEMINI_CACHED_CONTENT_MUTATION_CONFLICT", "another update to this cached content is in progress")
+ // ErrGeminiCachedContentRequestNotSent 表示上游缓存请求在发出前失败(地址、凭据等),上游状态未被改变。
+ ErrGeminiCachedContentRequestNotSent = errors.New("gemini cached content request was not sent")
+ // errGeminiCachedContentAccountUnsupported 表示持有缓存的账号存在,但当前不支持显式缓存(能力被关闭或认证方式不支持)。
+ errGeminiCachedContentAccountUnsupported = errors.New("gemini cached content account does not support explicit caching")
+
+ geminiCachedContentPublicIDPattern = regexp.MustCompile(`^[a-z0-9]{1,64}$`)
+ geminiCachedContentAIStudioName = regexp.MustCompile(`^cachedContents/[A-Za-z0-9_-]+$`)
+ geminiCachedContentVertexName = regexp.MustCompile(`^projects/[A-Za-z0-9_.:-]+/locations/([a-z0-9-]+)/cachedContents/[A-Za-z0-9_-]+$`)
+ geminiCachedContentPublicIDEncoding = base32.StdEncoding.WithPadding(base32.NoPadding)
+)
+
+// GeminiCachedContent 是网关对外暴露的显式缓存与上游资源、账号、归属的绑定。
+type GeminiCachedContent struct {
+ ID int64
+ PublicID string
+ UserID int64
+ APIKeyID int64
+ GroupID int64
+ // AccountID 是持有上游缓存的账号;引用缓存的请求只能发往该账号。
+ AccountID int64
+ UpstreamName string
+ // Model 是客户端视角的模型名(渠道映射后,不含 models/ 前缀),引用缓存的请求模型必须与之字面一致。
+ Model string
+ // UpstreamModel 是创建时发给上游的模型资源名。
+ UpstreamModel string
+ DisplayName string
+ TotalTokenCount int64
+ ExpireTime time.Time
+ // ChannelUsage 是创建时的渠道计费口径(渠道 ID、请求模型、计费模型来源),延长有效期按同一口径计费。
+ ChannelUsage ChannelUsageFields
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+// PublicName 返回客户端可见的缓存资源名。
+func (c *GeminiCachedContent) PublicName() string {
+ return GeminiCachedContentNamePrefix + c.PublicID
+}
+
+// UpstreamModelID 返回上游模型资源名的末段(裸模型名),用于计费定价查找。
+func (c *GeminiCachedContent) UpstreamModelID() string {
+ model := c.UpstreamModel
+ if i := strings.LastIndex(model, "/"); i >= 0 {
+ model = model[i+1:]
+ }
+ return model
+}
+
+// GeminiCachedContentRepository 持久化显式缓存绑定。所有读取都过滤已软删除的记录。
+type GeminiCachedContentRepository interface {
+ Create(ctx context.Context, record *GeminiCachedContent) error
+ GetForOwner(ctx context.Context, apiKeyID int64, publicID string) (*GeminiCachedContent, error)
+ // ListForOwner 按 id 倒序返回分组内 expire_time 晚于 activeAt 的记录;beforeID>0 时只返回 id 更小的记录。
+ ListForOwner(ctx context.Context, apiKeyID, groupID int64, activeAt time.Time, beforeID int64, limit int) ([]*GeminiCachedContent, error)
+ // BeginMutation 在记录没有修改意图且 expire_time 仍为 baseline 时登记修改意图(token 与自数据库当前时间起的租约),
+ // 返回是否登记成功;记录不存在或已删除时返回 ErrGeminiCachedContentNotFound。
+ BeginMutation(ctx context.Context, id int64, baseline time.Time, token string, lease time.Duration) (bool, error)
+ // TakeOverStaleMutation 把记录上租约已过期的修改意图换成 token 与新租约并返回记录;没有可接管的意图时返回 nil。
+ TakeOverStaleMutation(ctx context.Context, id int64, token string, lease time.Duration) (*GeminiCachedContent, error)
+ // CommitMutation 由 token 的持有者写入新的到期时间并清除修改意图;token 已失效或记录已删除时返回
+ // ErrGeminiCachedContentMutationConflict。
+ CommitMutation(ctx context.Context, id int64, token string, expireTime time.Time) error
+ // ReleaseMutation 由 token 的持有者清除修改意图,不改变到期时间。
+ ReleaseMutation(ctx context.Context, id int64, token string) error
+ // ListStaleMutations 返回修改意图租约已过期的未删除记录 id。
+ ListStaleMutations(ctx context.Context, limit int) ([]int64, error)
+ SoftDelete(ctx context.Context, id int64) error
+}
+
+// IsGeminiExplicitCacheAccountType 只按平台与账号类型判断是否可能支持显式缓存,适用于调度快照账号。
+func IsGeminiExplicitCacheAccountType(account *Account) bool {
+ if account == nil || account.Platform != PlatformGemini {
+ return false
+ }
+ return account.Type == AccountTypeAPIKey || account.Type == AccountTypeServiceAccount
+}
+
+// IsGeminiExplicitCacheAccount 判断完整账号是否支持显式缓存:官方地址的 AI Studio API Key 账号、
+// 声明上游支持显式缓存的自定义地址 API Key 账号,或 Service Account JSON 认证的 Vertex 账号。
+// API Key 认证的 Vertex 账号不参与显式缓存:Vertex 缓存接口只接受 OAuth access token,不接受 API Key。
+func IsGeminiExplicitCacheAccount(account *Account) bool {
+ if !IsGeminiExplicitCacheAccountType(account) {
+ return false
+ }
+ if account.Type == AccountTypeServiceAccount {
+ return !account.IsVertexAPIKey()
+ }
+ if strings.TrimSpace(account.GetCredential("api_key")) == "" {
+ return false
+ }
+ return isOfficialGeminiAPIBaseURL(account.GetCredential("base_url")) || account.GeminiExplicitCacheUpstreamEnabled()
+}
+
+// GeminiExplicitCacheUpstreamCredentialKey / GeminiExplicitCacheUpstreamMaxTTLCredentialKey 是 API Key 账号凭据里
+// 声明上游实现显式缓存接口及其有效期上限的键;调度快照投影须保留它们,候选过滤才能直接判定账号是否支持显式缓存。
+const (
+ GeminiExplicitCacheUpstreamCredentialKey = "explicit_cache_upstream"
+ GeminiExplicitCacheUpstreamMaxTTLCredentialKey = "explicit_cache_upstream_max_ttl_seconds"
+)
+
+// GeminiExplicitCacheUpstreamEnabled 判断 API Key 账号是否声明其上游实现了显式缓存接口,
+// 并保证缓存只在创建它的上游账号上使用(本系统同版本网关)。
+func (a *Account) GeminiExplicitCacheUpstreamEnabled() bool {
+ if a == nil || a.Type != AccountTypeAPIKey || a.Credentials == nil {
+ return false
+ }
+ enabled, _ := a.Credentials[GeminiExplicitCacheUpstreamCredentialKey].(bool)
+ return enabled
+}
+
+// GeminiExplicitCacheUpstreamMaxTTL 返回上游网关允许的缓存最长有效期;0 表示未配置。
+func (a *Account) GeminiExplicitCacheUpstreamMaxTTL() time.Duration {
+ if !a.GeminiExplicitCacheUpstreamEnabled() {
+ return 0
+ }
+ var seconds float64
+ switch v := a.Credentials[GeminiExplicitCacheUpstreamMaxTTLCredentialKey].(type) {
+ case float64:
+ seconds = v
+ case int:
+ seconds = float64(v)
+ case int64:
+ seconds = float64(v)
+ case json.Number:
+ seconds, _ = v.Float64()
+ case string:
+ seconds, _ = strconv.ParseFloat(strings.TrimSpace(v), 64)
+ }
+ if seconds <= 0 || math.IsNaN(seconds) || math.IsInf(seconds, 0) {
+ return 0
+ }
+ return time.Duration(seconds) * time.Second
+}
+
+// geminiCachedContentAPIBase 返回 API Key 账号缓存接口的上游根地址。
+func geminiCachedContentAPIBase(account *Account) string {
+ if isOfficialGeminiAPIBaseURL(account.GetCredential("base_url")) {
+ return geminicli.AIStudioBaseURL
+ }
+ return account.GetGeminiBaseURL(geminicli.AIStudioBaseURL)
+}
+
+func isOfficialGeminiAPIBaseURL(raw string) bool {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return true
+ }
+ u, err := url.Parse(raw)
+ if err != nil {
+ return false
+ }
+ path := strings.TrimRight(u.Path, "/")
+ return strings.EqualFold(u.Scheme, "https") &&
+ strings.EqualFold(u.Hostname(), geminiCachedContentOfficialHost) &&
+ u.Port() == "" && path == "" && u.RawQuery == ""
+}
+
+// NewGeminiCachedContentPublicID 生成 40 位小写字母数字的缓存 ID。
+func NewGeminiCachedContentPublicID() (string, error) {
+ var b [25]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ return "", err
+ }
+ return strings.ToLower(geminiCachedContentPublicIDEncoding.EncodeToString(b[:])), nil
+}
+
+// GeminiCachedContentUsageRequestIDPrefix 是显式缓存创建 / 延长费用在 usage_logs.request_id 中的固定前缀:
+// 这类费用行是独立的扣费事件,不随客户端或网关请求 id 变化,按缓存 ID 即可检索一个缓存的全部费用行。
+// 两种格式都不超过 request_id 列的 64 字符。
+const GeminiCachedContentUsageRequestIDPrefix = "gcache:"
+
+// GeminiCachedContentCreateUsageRequestID 返回创建费用的 request_id("gcache:create:{id}");一个缓存只创建一次。
+func GeminiCachedContentCreateUsageRequestID(publicID string) string {
+ return GeminiCachedContentUsageRequestIDPrefix + "create:" + publicID
+}
+
+// GeminiCachedContentPatchUsageRequestID 返回一次延长费用的 request_id("gcache:patch:{id}:{8 位随机}");每次延长各自唯一。
+func GeminiCachedContentPatchUsageRequestID(publicID string) string {
+ var b [5]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ return GeminiCachedContentUsageRequestIDPrefix + "patch:" + publicID + ":" + strconv.FormatInt(time.Now().UnixNano()%(1<<40), 32)
+ }
+ return GeminiCachedContentUsageRequestIDPrefix + "patch:" + publicID + ":" + strings.ToLower(geminiCachedContentPublicIDEncoding.EncodeToString(b[:]))
+}
+
+// ParseGeminiCachedContentPublicID 从 "cachedContents/{id}" 或裸 id 中解析缓存 ID。
+func ParseGeminiCachedContentPublicID(name string) (string, bool) {
+ id := strings.TrimPrefix(strings.TrimSpace(name), GeminiCachedContentNamePrefix)
+ if !geminiCachedContentPublicIDPattern.MatchString(id) {
+ return "", false
+ }
+ return id, true
+}
+
+type geminiCachedContentBoundCtxKey struct{}
+
+// WithGeminiCachedContentBound 标记请求引用了显式缓存并已硬绑定到持有账号。
+func WithGeminiCachedContentBound(ctx context.Context) context.Context {
+ return context.WithValue(ctx, geminiCachedContentBoundCtxKey{}, true)
+}
+
+func geminiCachedContentBoundFromContext(ctx context.Context) bool {
+ if ctx == nil {
+ return false
+ }
+ bound, _ := ctx.Value(geminiCachedContentBoundCtxKey{}).(bool)
+ return bound
+}
+
+// isGeminiBoundCacheUpstreamPassthrough 判断绑定缓存的请求在上游网关账号上收到的错误是否只反映
+// 上游持有缓存的那个账号的状态(429 / 5xx),不应据此限流或重试本账号。
+func isGeminiBoundCacheUpstreamPassthrough(ctx context.Context, account *Account, statusCode int) bool {
+ if statusCode != http.StatusTooManyRequests && statusCode < http.StatusInternalServerError {
+ return false
+ }
+ return account.GeminiExplicitCacheUpstreamEnabled() && geminiCachedContentBoundFromContext(ctx)
+}
+
+// GeminiCachedContentReference 是请求体中引用显式缓存的位置。
+type GeminiCachedContentReference struct {
+ Name string
+ Paths []string
+}
+
+var geminiCachedContentReferencePaths = []string{"cachedContent", "generateContentRequest.cachedContent"}
+
+// FindGeminiCachedContentReference 返回 generateContent / countTokens 请求体中引用的缓存名;未引用时返回 nil。
+// 引用键重复、使用 snake_case 写法或多个位置引用不同缓存时返回错误,保证校验与改写的引用就是发往上游的引用。
+func FindGeminiCachedContentReference(body []byte) (*GeminiCachedContentReference, error) {
+ root := gjson.ParseBytes(body)
+ if !root.IsObject() {
+ return nil, nil
+ }
+ if err := checkGeminiCachedContentReferenceKeys(root, "cachedContent", "generateContentRequest"); err != nil {
+ return nil, err
+ }
+ if nested := root.Get("generateContentRequest"); nested.IsObject() {
+ if err := checkGeminiCachedContentReferenceKeys(nested, "cachedContent"); err != nil {
+ return nil, err
+ }
+ }
+ var ref *GeminiCachedContentReference
+ for _, path := range geminiCachedContentReferencePaths {
+ value := gjson.GetBytes(body, path)
+ if !value.Exists() || value.Type == gjson.Null {
+ continue
+ }
+ if value.Type != gjson.String {
+ return nil, errors.New("cachedContent must be a string")
+ }
+ name := strings.TrimSpace(value.String())
+ if name == "" {
+ continue
+ }
+ if ref == nil {
+ ref = &GeminiCachedContentReference{Name: name}
+ } else if ref.Name != name {
+ return nil, errors.New("conflicting cachedContent references")
+ }
+ ref.Paths = append(ref.Paths, path)
+ }
+ return ref, nil
+}
+
+// checkGeminiCachedContentReferenceKeys 拒绝对象中重复出现的 uniqueKeys 与 snake_case 写法的缓存引用键。
+func checkGeminiCachedContentReferenceKeys(obj gjson.Result, uniqueKeys ...string) error {
+ seen := make(map[string]bool, len(uniqueKeys))
+ var err error
+ obj.ForEach(func(key, value gjson.Result) bool {
+ name := key.String()
+ switch {
+ case name == "cached_content":
+ err = errors.New("cached_content is not supported, use cachedContent")
+ case name == "generate_content_request" && (value.Get("cachedContent").Exists() || value.Get("cached_content").Exists()):
+ err = errors.New("generate_content_request is not supported with cachedContent, use generateContentRequest")
+ case slices.Contains(uniqueKeys, name):
+ if seen[name] {
+ err = fmt.Errorf("duplicate %s field", name)
+ }
+ seen[name] = true
+ }
+ return err == nil
+ })
+ return err
+}
+
+// RewriteGeminiCachedContentReference 把请求体中的缓存引用改写为上游资源名。
+func RewriteGeminiCachedContentReference(body []byte, ref *GeminiCachedContentReference, upstreamName string) ([]byte, error) {
+ if ref == nil {
+ return body, nil
+ }
+ out := body
+ for _, path := range ref.Paths {
+ next, err := sjson.SetBytes(out, path, upstreamName)
+ if err != nil {
+ return nil, err
+ }
+ out = next
+ }
+ return out, nil
+}
+
+// GeminiCachedContentCreateRequest 是校验后的创建请求。
+type GeminiCachedContentCreateRequest struct {
+ // Model 为客户端请求的模型名(不含 models/ 前缀)。
+ Model string
+ TTL time.Duration
+ DisplayName string
+ // ttlExplicit 表示客户端显式指定了 ttl 或 expireTime。
+ ttlExplicit bool
+ payload map[string]any
+}
+
+// TTLSeconds 返回发往上游的整秒 TTL。
+func (r *GeminiCachedContentCreateRequest) TTLSeconds() int64 {
+ return int64(math.Ceil(r.TTL.Seconds()))
+}
+
+// TTLForAccount 返回在账号上创建缓存使用的整秒有效期。账号上限小于请求有效期时:
+// 未显式指定有效期的请求按账号上限创建,显式指定的返回 false(该账号不可用)。
+func (r *GeminiCachedContentCreateRequest) TTLForAccount(account *Account) (time.Duration, bool) {
+ ttl := time.Duration(r.TTLSeconds()) * time.Second
+ limit := account.GeminiExplicitCacheUpstreamMaxTTL()
+ if limit <= 0 || ttl <= limit {
+ return ttl, true
+ }
+ if r.ttlExplicit {
+ return 0, false
+ }
+ return limit, true
+}
+
+// ParseGeminiCachedContentCreateRequest 校验创建请求。未指定有效期时使用上游默认的 1 小时(不超过 maxTTL)。
+// 数字按原文保留,重新编码后发往上游的内容与请求一致。
+func ParseGeminiCachedContentCreateRequest(body []byte, now time.Time, maxTTL time.Duration) (*GeminiCachedContentCreateRequest, error) {
+ payload, err := decodeGeminiCachedContentPayload(body)
+ if err != nil {
+ return nil, err
+ }
+ rawModel, _ := payload["model"].(string)
+ model := strings.TrimPrefix(strings.TrimSpace(rawModel), "models/")
+ if model == "" {
+ return nil, errors.New("model is required")
+ }
+ if !IsSafeGeminiModelPathSegment(model) {
+ return nil, errors.New("model name must be in the format 'models/{model_name}'")
+ }
+
+ ttl, err := parseGeminiCachedContentExpiration(payload, now)
+ if err != nil {
+ return nil, err
+ }
+ ttlExplicit := ttl > 0
+ if ttl == 0 {
+ ttl = geminiCachedContentDefaultTTL
+ if maxTTL > 0 && ttl > maxTTL {
+ ttl = maxTTL
+ }
+ }
+ if maxTTL > 0 && ttl > maxTTL {
+ return nil, fmt.Errorf("ttl exceeds the maximum allowed %ds", int64(maxTTL.Seconds()))
+ }
+
+ displayName := ""
+ if raw, ok := payload["displayName"]; ok && raw != nil {
+ s, ok := raw.(string)
+ if !ok {
+ return nil, errors.New("displayName must be a string")
+ }
+ if utf8.RuneCountInString(s) > geminiCachedContentDisplayNameMaxRunes {
+ return nil, fmt.Errorf("displayName must be at most %d characters", geminiCachedContentDisplayNameMaxRunes)
+ }
+ displayName = s
+ }
+
+ for _, key := range []string{"name", "model", "displayName", "ttl", "expireTime", "createTime", "updateTime", "usageMetadata"} {
+ delete(payload, key)
+ }
+ return &GeminiCachedContentCreateRequest{Model: model, TTL: ttl, DisplayName: displayName, ttlExplicit: ttlExplicit, payload: payload}, nil
+}
+
+// ParseGeminiCachedContentPatchRequest 校验更新请求,只允许修改有效期,返回新的 TTL(自 now 起算)。
+func ParseGeminiCachedContentPatchRequest(body []byte, updateMask string, now time.Time, maxTTL time.Duration) (time.Duration, error) {
+ payload, err := decodeGeminiCachedContentPayload(body)
+ if err != nil {
+ return 0, err
+ }
+ for key := range payload {
+ switch key {
+ case "ttl", "expireTime", "name":
+ default:
+ return 0, errors.New("can not update immutable fields (model or display_name)")
+ }
+ }
+ for _, field := range strings.Split(updateMask, ",") {
+ switch strings.TrimSpace(field) {
+ case "", "ttl", "expireTime", "expire_time":
+ default:
+ return 0, errors.New("can not update immutable fields (model or display_name)")
+ }
+ }
+ ttl, err := parseGeminiCachedContentExpiration(payload, now)
+ if err != nil {
+ return 0, err
+ }
+ if ttl == 0 {
+ return 0, errors.New("ttl or expireTime is required")
+ }
+ if maxTTL > 0 && ttl > maxTTL {
+ return 0, fmt.Errorf("ttl exceeds the maximum allowed %ds", int64(maxTTL.Seconds()))
+ }
+ return ttl, nil
+}
+
+// geminiCachedContentFieldAliases 是缓存元数据字段的 snake_case 写法到 camelCase 的映射。
+var geminiCachedContentFieldAliases = map[string]string{
+ "display_name": "displayName",
+ "expire_time": "expireTime",
+ "create_time": "createTime",
+ "update_time": "updateTime",
+ "usage_metadata": "usageMetadata",
+}
+
+// decodeGeminiCachedContentPayload 解码缓存请求体(数字保留原文),并把 snake_case 写法的元数据字段改为 camelCase;
+// 同一字段两种写法同时出现时报错。
+func decodeGeminiCachedContentPayload(body []byte) (map[string]any, error) {
+ dec := json.NewDecoder(bytes.NewReader(body))
+ dec.UseNumber()
+ var payload map[string]any
+ if err := dec.Decode(&payload); err != nil || payload == nil {
+ return nil, errors.New("request body must be a JSON object")
+ }
+ if _, err := dec.Token(); !errors.Is(err, io.EOF) {
+ return nil, errors.New("request body must be a JSON object")
+ }
+ for alias, canonical := range geminiCachedContentFieldAliases {
+ value, ok := payload[alias]
+ if !ok {
+ continue
+ }
+ if _, dup := payload[canonical]; dup {
+ return nil, fmt.Errorf("only one of %s or %s may be set", canonical, alias)
+ }
+ delete(payload, alias)
+ payload[canonical] = value
+ }
+ return payload, nil
+}
+
+// parseGeminiCachedContentExpiration 解析 ttl / expireTime(二选一),未设置时返回 0;结果向上取整到秒,与发往上游的 ttl 一致。
+func parseGeminiCachedContentExpiration(payload map[string]any, now time.Time) (time.Duration, error) {
+ rawTTL, hasTTL := payload["ttl"]
+ rawExpire, hasExpire := payload["expireTime"]
+ hasTTL = hasTTL && rawTTL != nil
+ hasExpire = hasExpire && rawExpire != nil
+ if hasTTL && hasExpire {
+ return 0, errors.New("only one of ttl or expireTime may be set")
+ }
+ if hasTTL {
+ s, ok := rawTTL.(string)
+ if !ok {
+ return 0, errors.New("ttl must be a duration string such as \"3600s\"")
+ }
+ return parseGoogleDurationSeconds(s)
+ }
+ if hasExpire {
+ s, ok := rawExpire.(string)
+ if !ok {
+ return 0, errors.New("expireTime must be an RFC 3339 timestamp")
+ }
+ expire, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(s))
+ if err != nil {
+ return 0, errors.New("expireTime must be an RFC 3339 timestamp")
+ }
+ ttl := expire.Sub(now)
+ if ttl <= 0 {
+ return 0, errors.New("expireTime must be in the future")
+ }
+ return time.Duration(math.Ceil(ttl.Seconds())) * time.Second, nil
+ }
+ return 0, nil
+}
+
+func parseGoogleDurationSeconds(raw string) (time.Duration, error) {
+ raw = strings.TrimSpace(raw)
+ if !strings.HasSuffix(raw, "s") {
+ return 0, errors.New("ttl must be a duration string such as \"3600s\"")
+ }
+ seconds, err := strconv.ParseFloat(strings.TrimSuffix(raw, "s"), 64)
+ if err != nil || math.IsNaN(seconds) || math.IsInf(seconds, 0) {
+ return 0, errors.New("ttl must be a duration string such as \"3600s\"")
+ }
+ if seconds <= 0 {
+ return 0, errors.New("ttl must be positive")
+ }
+ if seconds > float64(math.MaxInt64/int64(time.Second)) {
+ return 0, errors.New("ttl is too large")
+ }
+ return time.Duration(math.Ceil(seconds)) * time.Second, nil
+}
+
+// GeminiCachedContentUpstream 是上游缓存资源的元数据。
+type GeminiCachedContentUpstream struct {
+ Name string
+ TotalTokenCount int64
+ ExpireTime time.Time
+}
+
+// GeminiCachedContentUpstreamError 是上游返回的非 2xx 响应。
+type GeminiCachedContentUpstreamError struct {
+ StatusCode int
+ Body []byte
+ // UpstreamGateway 表示响应来自声明实现显式缓存的上游网关账号:限流 / 不可用反映的是持有缓存的上游账号状态。
+ UpstreamGateway bool
+}
+
+func (e *GeminiCachedContentUpstreamError) Error() string {
+ return fmt.Sprintf("gemini cached content upstream error: %d", e.StatusCode)
+}
+
+// NotFound 判断上游是否报告缓存不存在(含已过期、已删除)。
+func (e *GeminiCachedContentUpstreamError) NotFound() bool {
+ return e != nil && isGeminiCachedContentNotFound(e.StatusCode, e.Body)
+}
+
+// GeminiCachedContentMalformedResponseError 表示上游返回 2xx 但响应体不可用;Name 非空时上游资源已经创建。
+type GeminiCachedContentMalformedResponseError struct {
+ Name string
+ Err error
+}
+
+func (e *GeminiCachedContentMalformedResponseError) Error() string {
+ return "gemini cached content upstream returned an unusable response: " + e.Err.Error()
+}
+
+func (e *GeminiCachedContentMalformedResponseError) Unwrap() error {
+ return e.Err
+}
+
+// RetryableOnOtherAccount 判断创建失败是否值得换一个账号重试(账号凭据、配额或上游可用性问题)。
+func (e *GeminiCachedContentUpstreamError) RetryableOnOtherAccount() bool {
+ if e == nil {
+ return false
+ }
+ switch e.StatusCode {
+ case http.StatusUnauthorized, http.StatusForbidden, http.StatusTooManyRequests:
+ return true
+ default:
+ return e.StatusCode >= 500
+ }
+}
+
+// GeminiCachedContentService 管理显式缓存的上游资源与网关绑定。
+type GeminiCachedContentService struct {
+ repo GeminiCachedContentRepository
+ compat *GeminiMessagesCompatService
+ cfg *config.Config
+ now func() time.Time
+
+ startOnce sync.Once
+ stopOnce sync.Once
+ stopCh chan struct{}
+}
+
+func NewGeminiCachedContentService(repo GeminiCachedContentRepository, compat *GeminiMessagesCompatService, cfg *config.Config) *GeminiCachedContentService {
+ return &GeminiCachedContentService{repo: repo, compat: compat, cfg: cfg, now: time.Now, stopCh: make(chan struct{})}
+}
+
+// Start 启动后台回滚恢复:定期处理租约已过期仍未清除的修改意图。
+func (s *GeminiCachedContentService) Start() {
+ if s == nil || s.repo == nil {
+ return
+ }
+ s.startOnce.Do(func() { go s.runMutationRecovery() })
+}
+
+// Stop 停止后台回滚恢复。
+func (s *GeminiCachedContentService) Stop() {
+ if s == nil {
+ return
+ }
+ s.stopOnce.Do(func() { close(s.stopCh) })
+}
+
+func (s *GeminiCachedContentService) runMutationRecovery() {
+ ticker := time.NewTicker(geminiCachedContentMutationRecoveryInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-s.stopCh:
+ return
+ case <-ticker.C:
+ recovered, err := s.RecoverStaleMutations(context.Background())
+ if err != nil {
+ logger.LegacyPrintf("service.gemini_cached_content", "Warning: gemini cached content mutation recovery failed (recovered=%d): %v", recovered, err)
+ } else if recovered > 0 {
+ logger.LegacyPrintf("service.gemini_cached_content", "gemini cached content mutation recovery rolled back %d stale mutations", recovered)
+ }
+ }
+ }
+}
+
+// Now 返回服务时钟。
+func (s *GeminiCachedContentService) Now() time.Time {
+ return s.now()
+}
+
+// MaxTTL 返回单次创建或延长允许的最长有效期。
+func (s *GeminiCachedContentService) MaxTTL() time.Duration {
+ if s.cfg != nil && s.cfg.Gateway.GeminiCachedContentMaxTTLSeconds > 0 {
+ return time.Duration(s.cfg.Gateway.GeminiCachedContentMaxTTLSeconds) * time.Second
+ }
+ return geminiCachedContentDefaultMaxTTL
+}
+
+// MaxTTLForAccount 返回在账号上可设置的最长有效期:全局上限与上游网关上限取较小值。
+func (s *GeminiCachedContentService) MaxTTLForAccount(account *Account) time.Duration {
+ limit := s.MaxTTL()
+ if upstream := account.GeminiExplicitCacheUpstreamMaxTTL(); upstream > 0 && upstream < limit {
+ return upstream
+ }
+ return limit
+}
+
+// GeminiCachedContentStorageTokenHours 返回 tokens 个缓存 token 存储 duration 的存储量(token·小时)。
+func GeminiCachedContentStorageTokenHours(tokens int64, duration time.Duration) float64 {
+ if tokens <= 0 || duration <= 0 {
+ return 0
+ }
+ return float64(tokens) * duration.Hours()
+}
+
+// ClampGeminiCachedContentExpire 返回本地记录与计费采用的到期时间:上游回报的到期时间不晚于 limit,缺失时取 limit。
+func ClampGeminiCachedContentExpire(upstream, limit time.Time) time.Time {
+ if upstream.IsZero() || upstream.After(limit) {
+ return limit
+ }
+ return upstream
+}
+
+// Resolve 返回 API Key 名下仍有效的缓存;不存在、不在当前分组或已过期时返回 ErrGeminiCachedContentNotFound。
+func (s *GeminiCachedContentService) Resolve(ctx context.Context, apiKeyID int64, groupID *int64, name string) (*GeminiCachedContent, error) {
+ publicID, ok := ParseGeminiCachedContentPublicID(name)
+ if !ok {
+ return nil, ErrGeminiCachedContentNotFound
+ }
+ record, err := s.repo.GetForOwner(ctx, apiKeyID, publicID)
+ if err != nil {
+ return nil, err
+ }
+ if groupID == nil || record.GroupID != *groupID || !record.ExpireTime.After(s.now()) {
+ return nil, ErrGeminiCachedContentNotFound
+ }
+ return record, nil
+}
+
+func (s *GeminiCachedContentService) Save(ctx context.Context, record *GeminiCachedContent) error {
+ return s.repo.Create(ctx, record)
+}
+
+func (s *GeminiCachedContentService) List(ctx context.Context, apiKeyID, groupID int64, beforeID int64, limit int) ([]*GeminiCachedContent, error) {
+ return s.repo.ListForOwner(ctx, apiKeyID, groupID, s.now(), beforeID, limit)
+}
+
+// GeminiCachedContentMutation 是一次已登记修改意图、尚未提交的有效期修改。持有期间同一缓存的其他修改被拒绝;
+// 未提交的修改(上游结果未知、落库失败、进程退出)在租约过期后由恢复流程把上游有效期回滚到 Baseline,不计费。
+type GeminiCachedContentMutation struct {
+ record *GeminiCachedContent
+ baseline time.Time
+ token string
+}
+
+// Baseline 返回修改前的到期时间:提交前它始终是库中的到期时间。
+func (m *GeminiCachedContentMutation) Baseline() time.Time {
+ return m.baseline
+}
+
+// BeginMutation 登记修改 record 有效期的意图并取得租约。同一缓存有进行中的修改,或库中到期时间已不是
+// record.ExpireTime 时返回 ErrGeminiCachedContentMutationConflict;租约已过期的遗留意图先回滚恢复再登记。
+func (s *GeminiCachedContentService) BeginMutation(ctx context.Context, record *GeminiCachedContent) (*GeminiCachedContentMutation, error) {
+ for attempt := 0; ; attempt++ {
+ token, err := NewGeminiCachedContentPublicID()
+ if err != nil {
+ return nil, err
+ }
+ acquired, err := s.repo.BeginMutation(ctx, record.ID, record.ExpireTime, token, geminiCachedContentMutationLease)
+ if err != nil {
+ return nil, err
+ }
+ if acquired {
+ return &GeminiCachedContentMutation{record: record, baseline: record.ExpireTime, token: token}, nil
+ }
+ if attempt > 0 {
+ return nil, ErrGeminiCachedContentMutationConflict
+ }
+ recovered, err := s.recoverStaleMutation(ctx, record.ID)
+ if err != nil {
+ return nil, errors.Join(ErrGeminiCachedContentMutationConflict, err)
+ }
+ if !recovered {
+ return nil, ErrGeminiCachedContentMutationConflict
+ }
+ }
+}
+
+// CommitMutation 写入新的到期时间并清除修改意图。修改意图已不属于 m(缓存已删除或租约已被接管)时返回
+// ErrGeminiCachedContentMutationConflict;其他失败时意图保留,由恢复流程回滚上游。
+func (s *GeminiCachedContentService) CommitMutation(ctx context.Context, m *GeminiCachedContentMutation, expireTime time.Time) error {
+ if err := s.repo.CommitMutation(ctx, m.record.ID, m.token, expireTime); err != nil {
+ return err
+ }
+ m.record.ExpireTime = expireTime
+ m.record.UpdatedAt = s.now()
+ return nil
+}
+
+// ReleaseMutation 放弃修改并清除修改意图,用于上游明确未改变有效期的情形。
+func (s *GeminiCachedContentService) ReleaseMutation(ctx context.Context, m *GeminiCachedContentMutation) error {
+ return s.repo.ReleaseMutation(ctx, m.record.ID, m.token)
+}
+
+// RecoverStaleMutations 回滚恢复一批租约已过期的修改意图,返回完成恢复的数量。
+func (s *GeminiCachedContentService) RecoverStaleMutations(ctx context.Context) (int, error) {
+ listCtx, cancel := context.WithTimeout(ctx, geminiCachedContentMutationRecoveryTimeout)
+ ids, err := s.repo.ListStaleMutations(listCtx, geminiCachedContentMutationRecoveryBatch)
+ cancel()
+ if err != nil {
+ return 0, err
+ }
+ recovered := 0
+ var errs []error
+ for _, id := range ids {
+ select {
+ case <-s.stopCh:
+ return recovered, errors.Join(errs...)
+ default:
+ }
+ itemCtx, cancel := context.WithTimeout(ctx, geminiCachedContentMutationRecoveryTimeout)
+ ok, err := s.recoverStaleMutation(itemCtx, id)
+ cancel()
+ if err != nil {
+ errs = append(errs, fmt.Errorf("cached content %d: %w", id, err))
+ continue
+ }
+ if ok {
+ recovered++
+ }
+ }
+ return recovered, errors.Join(errs...)
+}
+
+// recoverStaleMutation 接管 id 上租约已过期的修改意图,把上游有效期回滚到库中的到期时间后清除意图;
+// 库中到期时间已到时删除上游缓存与本地记录。没有可接管的意图时返回 false;回滚失败时意图保留,
+// 本次接管取得的新租约(geminiCachedContentMutationLease)过期后重试,期间同一缓存的修改返回 409。
+func (s *GeminiCachedContentService) recoverStaleMutation(ctx context.Context, id int64) (bool, error) {
+ token, err := NewGeminiCachedContentPublicID()
+ if err != nil {
+ return false, err
+ }
+ record, err := s.repo.TakeOverStaleMutation(ctx, id, token, geminiCachedContentMutationLease)
+ if err != nil || record == nil {
+ return false, err
+ }
+ forget, err := s.rollbackUpstream(ctx, record)
+ if err != nil {
+ return false, err
+ }
+ if forget {
+ return true, s.repo.SoftDelete(ctx, record.ID)
+ }
+ return true, s.repo.ReleaseMutation(ctx, record.ID, token)
+}
+
+// rollbackUpstream 把上游有效期改回 record.ExpireTime,剩余不足 1 秒时删除上游缓存;
+// 返回 true 表示上游缓存已不存在、或已没有凭据可触达(持有账号已删除),本地记录应移除。
+// 持有账号存在但当前不支持显式缓存时不改动上游,修改意图保留到账号恢复后重试;账号可用时总是先向上游回滚。
+// 两种情况下只要 mutationUpstreamMustHaveExpired 成立(上游缓存必已自行过期),本地记录直接作废,不再重试。
+func (s *GeminiCachedContentService) rollbackUpstream(ctx context.Context, record *GeminiCachedContent) (bool, error) {
+ account, err := s.boundAccount(ctx, record)
+ if errors.Is(err, errGeminiCachedContentAccountUnsupported) {
+ if s.mutationUpstreamMustHaveExpired(record) {
+ logger.LegacyPrintf("service.gemini_cached_content", "Warning: gemini cached content %d (upstream %s) has a pending mutation but account %d stopped supporting explicit caching and the upstream cache has expired since; dropping the local record", record.ID, record.UpstreamName, record.AccountID)
+ return true, nil
+ }
+ return false, fmt.Errorf("%w (account %d)", err, record.AccountID)
+ }
+ if err != nil {
+ return false, err
+ }
+ if account == nil {
+ logger.LegacyPrintf("service.gemini_cached_content", "Warning: gemini cached content %d (upstream %s) has a pending mutation but account %d no longer exists; dropping the local record without touching upstream", record.ID, record.UpstreamName, record.AccountID)
+ return true, nil
+ }
+ remaining := record.ExpireTime.Sub(s.now())
+ if remaining < time.Second {
+ err = s.DeleteUpstream(ctx, account, record)
+ } else {
+ _, err = s.PatchUpstream(ctx, account, record, remaining)
+ }
+ var upErr *GeminiCachedContentUpstreamError
+ if errors.As(err, &upErr) && upErr.NotFound() {
+ return true, nil
+ }
+ if err != nil {
+ if s.mutationUpstreamMustHaveExpired(record) {
+ logger.LegacyPrintf("service.gemini_cached_content", "Warning: gemini cached content %d (upstream %s) rollback keeps failing on account %d but the upstream cache has expired since; dropping the local record: %v", record.ID, record.UpstreamName, record.AccountID, err)
+ return true, nil
+ }
+ return false, err
+ }
+ return remaining < time.Second, nil
+}
+
+// mutationUpstreamMustHaveExpired 判断 record 上未完成修改所涉及的上游缓存是否必已自行过期:
+// 修改发生时记录尚未到期(Resolve 拒绝已过期记录),且单次延长不超过 MaxTTL,
+// 所以上游有效期最晚为 record.ExpireTime + MaxTTL;再过 geminiCachedContentMutationAbandonGrace 后判定为已过期。
+// MaxTTL 取判定时刻的配置并以默认上限兜底:配置被调低后判定可能早于上游真实过期,此时只影响运营方的上游存储费,
+// 不涉及用户计费。
+func (s *GeminiCachedContentService) mutationUpstreamMustHaveExpired(record *GeminiCachedContent) bool {
+ maxTTL := s.MaxTTL()
+ if maxTTL < geminiCachedContentDefaultMaxTTL {
+ maxTTL = geminiCachedContentDefaultMaxTTL
+ }
+ return s.now().After(record.ExpireTime.Add(maxTTL + geminiCachedContentMutationAbandonGrace))
+}
+
+func (s *GeminiCachedContentService) Forget(ctx context.Context, record *GeminiCachedContent) error {
+ return s.repo.SoftDelete(ctx, record.ID)
+}
+
+// BoundAccount 返回持有缓存的账号;账号已删除或不再支持显式缓存时返回 nil。
+func (s *GeminiCachedContentService) BoundAccount(ctx context.Context, record *GeminiCachedContent) (*Account, error) {
+ account, err := s.boundAccount(ctx, record)
+ if errors.Is(err, errGeminiCachedContentAccountUnsupported) {
+ return nil, nil
+ }
+ return account, err
+}
+
+// boundAccount 返回持有缓存的账号:账号已删除返回 nil;账号存在但当前不支持显式缓存返回
+// errGeminiCachedContentAccountUnsupported,调用方据此区分"永久不可用"与"暂时不可用"。
+func (s *GeminiCachedContentService) boundAccount(ctx context.Context, record *GeminiCachedContent) (*Account, error) {
+ if s.compat == nil || s.compat.accountRepo == nil {
+ return nil, errors.New("account repository not configured")
+ }
+ account, err := s.compat.accountRepo.GetByID(ctx, record.AccountID)
+ if err != nil {
+ if errors.Is(err, ErrAccountNotFound) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ if account == nil {
+ return nil, nil
+ }
+ if !IsGeminiExplicitCacheAccount(account) {
+ return nil, errGeminiCachedContentAccountUnsupported
+ }
+ return account, nil
+}
+
+// GeminiCachedContentUpstreamModelResource 返回创建缓存时发往上游的模型资源名。
+func GeminiCachedContentUpstreamModelResource(account *Account, mappedModel string) (string, error) {
+ switch account.Type {
+ case AccountTypeAPIKey:
+ return "models/" + mappedModel, nil
+ case AccountTypeServiceAccount:
+ projectID := strings.TrimSpace(account.VertexProjectID())
+ if projectID == "" {
+ return "", errors.New("vertex project_id is required")
+ }
+ location := strings.TrimSpace(account.VertexLocation(mappedModel))
+ if location == "" {
+ location = vertexDefaultLocation
+ }
+ if !vertexLocationPattern.MatchString(location) {
+ return "", fmt.Errorf("invalid vertex location: %s", location)
+ }
+ return fmt.Sprintf("projects/%s/locations/%s/publishers/google/models/%s", projectID, location, mappedModel), nil
+ default:
+ return "", fmt.Errorf("account type %s does not support explicit context caching", account.Type)
+ }
+}
+
+// CreateUpstream 在账号上创建上游缓存。
+func (s *GeminiCachedContentService) CreateUpstream(ctx context.Context, account *Account, req *GeminiCachedContentCreateRequest, mappedModel, publicID string, ttl time.Duration) (*GeminiCachedContentUpstream, error) {
+ upstreamModel, err := GeminiCachedContentUpstreamModelResource(account, mappedModel)
+ if err != nil {
+ return nil, err
+ }
+ payload := make(map[string]any, len(req.payload)+3)
+ for k, v := range req.payload {
+ payload[k] = v
+ }
+ payload["model"] = upstreamModel
+ payload["ttl"] = fmt.Sprintf("%ds", int64(math.Ceil(ttl.Seconds())))
+ payload["displayName"] = geminiCachedContentUpstreamTagPrefix + publicID
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return nil, err
+ }
+ base, err := s.apiBase(account)
+ if err != nil {
+ return nil, err
+ }
+ collectionURL, err := geminiCachedContentCollectionURL(account, base, mappedModel)
+ if err != nil {
+ return nil, err
+ }
+ respBody, err := s.doUpstream(ctx, account, http.MethodPost, collectionURL, body, geminiCachedContentUpstreamTimeout)
+ if err != nil {
+ return nil, err
+ }
+ upstream, err := parseGeminiCachedContentUpstream(respBody)
+ if err != nil {
+ return nil, err
+ }
+ if upstream.TotalTokenCount <= 0 {
+ return nil, &GeminiCachedContentMalformedResponseError{Name: upstream.Name, Err: errors.New("missing usageMetadata.totalTokenCount")}
+ }
+ return upstream, nil
+}
+
+// PatchUpstream 把上游缓存的有效期改为自现在起 ttl。
+func (s *GeminiCachedContentService) PatchUpstream(ctx context.Context, account *Account, record *GeminiCachedContent, ttl time.Duration) (*GeminiCachedContentUpstream, error) {
+ resourceURL, err := s.upstreamResourceURL(account, record)
+ if err != nil {
+ return nil, err
+ }
+ seconds := int64(math.Ceil(ttl.Seconds()))
+ body, _ := json.Marshal(map[string]any{"ttl": fmt.Sprintf("%ds", seconds)})
+ respBody, err := s.doUpstream(ctx, account, http.MethodPatch, resourceURL+"?updateMask=ttl", body, geminiCachedContentMutationUpstreamTimeout)
+ if err != nil {
+ return nil, err
+ }
+ out := &GeminiCachedContentUpstream{Name: record.UpstreamName}
+ if raw := gjson.GetBytes(respBody, "expireTime").String(); raw != "" {
+ if t, err := time.Parse(time.RFC3339Nano, raw); err == nil {
+ out.ExpireTime = t
+ }
+ }
+ return out, nil
+}
+
+// DeleteUpstream 删除上游缓存。
+func (s *GeminiCachedContentService) DeleteUpstream(ctx context.Context, account *Account, record *GeminiCachedContent) error {
+ resourceURL, err := s.upstreamResourceURL(account, record)
+ if err != nil {
+ return err
+ }
+ _, err = s.doUpstream(ctx, account, http.MethodDelete, resourceURL, nil, geminiCachedContentMutationUpstreamTimeout)
+ return err
+}
+
+// upstreamResourceURL 返回 record 对应上游缓存资源的地址;失败时请求不会发出。
+func (s *GeminiCachedContentService) upstreamResourceURL(account *Account, record *GeminiCachedContent) (string, error) {
+ base, err := s.apiBase(account)
+ if err != nil {
+ return "", geminiCachedContentNotSent(err)
+ }
+ resourceURL, err := geminiCachedContentResourceURL(account, base, record.UpstreamName)
+ if err != nil {
+ return "", geminiCachedContentNotSent(err)
+ }
+ return resourceURL, nil
+}
+
+func geminiCachedContentNotSent(err error) error {
+ return fmt.Errorf("%w: %w", ErrGeminiCachedContentRequestNotSent, err)
+}
+
+// doUpstream 调用上游缓存接口并返回 2xx 响应体,单次调用不超过 timeout。上游调用与客户端连接脱钩:客户端断开不会中途取消
+// 已发出的创建 / 修改,调用方据结果完成落库、计费或清理。请求发出前的失败包装为 ErrGeminiCachedContentRequestNotSent。
+func (s *GeminiCachedContentService) doUpstream(ctx context.Context, account *Account, method, target string, body []byte, timeout time.Duration) ([]byte, error) {
+ if s.compat == nil || s.compat.httpUpstream == nil {
+ return nil, geminiCachedContentNotSent(errors.New("gemini upstream client not configured"))
+ }
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout)
+ defer cancel()
+ var reader io.Reader
+ if body != nil {
+ reader = bytes.NewReader(body)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, target, reader)
+ if err != nil {
+ return nil, geminiCachedContentNotSent(err)
+ }
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ switch account.Type {
+ case AccountTypeAPIKey:
+ apiKey := strings.TrimSpace(account.GetCredential("api_key"))
+ if apiKey == "" {
+ return nil, geminiCachedContentNotSent(errors.New("gemini api_key not configured"))
+ }
+ req.Header.Set("x-goog-api-key", apiKey)
+ case AccountTypeServiceAccount:
+ if s.compat.tokenProvider == nil {
+ return nil, geminiCachedContentNotSent(errors.New("gemini token provider not configured"))
+ }
+ accessToken, err := s.compat.tokenProvider.GetAccessToken(ctx, account)
+ if err != nil {
+ return nil, geminiCachedContentNotSent(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+accessToken)
+ default:
+ return nil, geminiCachedContentNotSent(fmt.Errorf("account type %s does not support explicit context caching", account.Type))
+ }
+ proxyURL := ""
+ if account.ProxyID != nil && account.Proxy != nil {
+ proxyURL = account.Proxy.URL()
+ }
+ resp, err := s.compat.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = resp.Body.Close() }()
+ respBody, err := io.ReadAll(io.LimitReader(resp.Body, geminiCachedContentResponseMaxBytes))
+ success := resp.StatusCode >= 200 && resp.StatusCode < 300
+ if err != nil {
+ if success {
+ return nil, &GeminiCachedContentMalformedResponseError{Err: err}
+ }
+ return nil, err
+ }
+ if !success {
+ return nil, &GeminiCachedContentUpstreamError{StatusCode: resp.StatusCode, Body: respBody, UpstreamGateway: account.GeminiExplicitCacheUpstreamEnabled()}
+ }
+ return respBody, nil
+}
+
+// apiBase 返回 API Key 账号经地址校验后的上游根地址;Vertex 账号返回空串(地址由区域决定)。
+func (s *GeminiCachedContentService) apiBase(account *Account) (string, error) {
+ if account.Type != AccountTypeAPIKey {
+ return "", nil
+ }
+ if s.compat == nil {
+ return "", errors.New("gemini upstream client not configured")
+ }
+ return s.compat.validateUpstreamBaseURL(geminiCachedContentAPIBase(account))
+}
+
+func parseGeminiCachedContentUpstream(body []byte) (*GeminiCachedContentUpstream, error) {
+ name := strings.TrimSpace(gjson.GetBytes(body, "name").String())
+ if name == "" {
+ return nil, &GeminiCachedContentMalformedResponseError{Err: errors.New("missing name")}
+ }
+ if !geminiCachedContentAIStudioName.MatchString(name) && !geminiCachedContentVertexName.MatchString(name) {
+ return nil, &GeminiCachedContentMalformedResponseError{Err: fmt.Errorf("unexpected name %q", name)}
+ }
+ out := &GeminiCachedContentUpstream{
+ Name: name,
+ TotalTokenCount: gjson.GetBytes(body, "usageMetadata.totalTokenCount").Int(),
+ }
+ if raw := gjson.GetBytes(body, "expireTime").String(); raw != "" {
+ if t, err := time.Parse(time.RFC3339Nano, raw); err == nil {
+ out.ExpireTime = t
+ }
+ }
+ return out, nil
+}
+
+func geminiCachedContentCollectionURL(account *Account, base, mappedModel string) (string, error) {
+ switch account.Type {
+ case AccountTypeAPIKey:
+ base = strings.TrimRight(strings.TrimSpace(base), "/")
+ if base == "" {
+ return "", errors.New("gemini base url is required")
+ }
+ return base + "/v1beta/cachedContents", nil
+ case AccountTypeServiceAccount:
+ projectID := strings.TrimSpace(account.VertexProjectID())
+ if projectID == "" {
+ return "", errors.New("vertex project_id is required")
+ }
+ location := strings.TrimSpace(account.VertexLocation(mappedModel))
+ if location == "" {
+ location = vertexDefaultLocation
+ }
+ if !vertexLocationPattern.MatchString(location) {
+ return "", fmt.Errorf("invalid vertex location: %s", location)
+ }
+ return fmt.Sprintf("https://%s/v1/projects/%s/locations/%s/cachedContents",
+ geminiCachedContentVertexHost(location), url.PathEscape(projectID), url.PathEscape(location)), nil
+ default:
+ return "", fmt.Errorf("account type %s does not support explicit context caching", account.Type)
+ }
+}
+
+func geminiCachedContentResourceURL(account *Account, base, upstreamName string) (string, error) {
+ switch account.Type {
+ case AccountTypeAPIKey:
+ if !geminiCachedContentAIStudioName.MatchString(upstreamName) {
+ return "", fmt.Errorf("invalid upstream cached content name: %s", upstreamName)
+ }
+ base = strings.TrimRight(strings.TrimSpace(base), "/")
+ if base == "" {
+ return "", errors.New("gemini base url is required")
+ }
+ return base + "/v1beta/" + upstreamName, nil
+ case AccountTypeServiceAccount:
+ m := geminiCachedContentVertexName.FindStringSubmatch(upstreamName)
+ if m == nil {
+ return "", fmt.Errorf("invalid upstream cached content name: %s", upstreamName)
+ }
+ return fmt.Sprintf("https://%s/v1/%s", geminiCachedContentVertexHost(m[1]), upstreamName), nil
+ default:
+ return "", fmt.Errorf("account type %s does not support explicit context caching", account.Type)
+ }
+}
+
+func geminiCachedContentVertexHost(location string) string {
+ if location == "global" {
+ return "aiplatform.googleapis.com"
+ }
+ return location + "-aiplatform.googleapis.com"
+}
+
+// GeminiCachedContentView 返回客户端可见的缓存元数据。
+func GeminiCachedContentView(record *GeminiCachedContent) map[string]any {
+ view := map[string]any{
+ "name": record.PublicName(),
+ "model": "models/" + record.Model,
+ "usageMetadata": map[string]any{"totalTokenCount": record.TotalTokenCount},
+ "createTime": record.CreatedAt.UTC().Format(time.RFC3339Nano),
+ "updateTime": record.UpdatedAt.UTC().Format(time.RFC3339Nano),
+ "expireTime": record.ExpireTime.UTC().Format(time.RFC3339Nano),
+ }
+ if record.DisplayName != "" {
+ view["displayName"] = record.DisplayName
+ }
+ return view
+}
+
+// GeminiExplicitCacheExclusions 返回显式缓存请求在 gemini 分组内需要排除的可调度账号。
+// boundAccountID > 0 时只保留该账号;否则排除不支持显式缓存的账号。判定所需的凭据键
+// (api_key、base_url、auth_mode、上游显式缓存声明)都在调度快照投影内,候选过滤一次算全;
+// 选中后仍对完整账号复核。
+func (s *GatewayService) GeminiExplicitCacheExclusions(ctx context.Context, groupID *int64, boundAccountID int64) (map[int64]struct{}, error) {
+ accounts, _, err := s.listSchedulableAccounts(ctx, groupID, PlatformGemini, false)
+ if err != nil {
+ return nil, err
+ }
+ excluded := make(map[int64]struct{}, len(accounts))
+ for i := range accounts {
+ account := &accounts[i]
+ keep := IsGeminiExplicitCacheAccount(account)
+ if boundAccountID > 0 {
+ keep = account.ID == boundAccountID
+ }
+ if !keep {
+ excluded[account.ID] = struct{}{}
+ }
+ }
+ return excluded, nil
+}
diff --git a/backend/internal/service/gemini_cached_content_hardening_test.go b/backend/internal/service/gemini_cached_content_hardening_test.go
new file mode 100644
index 000000000..4d00d60f9
--- /dev/null
+++ b/backend/internal/service/gemini_cached_content_hardening_test.go
@@ -0,0 +1,480 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+const geminiCacheHardeningPricing = `{
+ "gemini-3.8-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075,"output_cost_per_token":0.00000375,
+ "cache_storage_cost_per_token_per_hour":0.0000005},
+ "gemini-2.5-pro":{"litellm_provider":"gemini","input_cost_per_token":0.00000125,"output_cost_per_token":0.00001,
+ "cache_storage_cost_per_token_per_hour":0.0000045}}`
+
+func newGeminiCacheBillingGatewayForTest(t *testing.T) (*GatewayService, *openAIRecordUsageLogRepoStub) {
+ t.Helper()
+ usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
+ svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{})
+ pricing := &PricingService{}
+ data, err := pricing.parsePricingData([]byte(geminiCacheHardeningPricing))
+ require.NoError(t, err)
+ pricing.pricingData = data
+ svc.billingService = NewBillingService(svc.cfg, pricing)
+ return svc, usageRepo
+}
+
+func TestGeminiCachedContentStoragePriceFollowsBillingModel(t *testing.T) {
+ ctx := context.Background()
+ svc, usageRepo := newGeminiCacheBillingGatewayForTest(t)
+ groupID := int64(33)
+ apiKey := &APIKey{ID: 821, GroupID: &groupID, User: &User{ID: 621},
+ Group: &Group{ID: groupID, Platform: PlatformGemini, RateMultiplier: 2, Hydrated: true}}
+ tokenHours := GeminiCachedContentStorageTokenHours(1000, 24*time.Hour)
+
+ mapped := &RecordUsageInput{
+ Result: &ForwardResult{RequestID: "cc-mapped", Model: "gemini-2.5-pro", UpstreamModel: "gemini-3.8-flash",
+ Usage: ClaudeUsage{InputTokens: 1000}, CacheStorageTokenHours: tokenHours},
+ APIKey: apiKey, User: apiKey.User, Account: &Account{ID: 713, Platform: PlatformGemini},
+ }
+ require.True(t, svc.CacheStoragePriced(ctx, mapped))
+ want := (1000*0.00000125 + tokenHours*0.0000045) * 2
+ require.InDelta(t, want, svc.QuoteUsageCost(ctx, mapped), 1e-12, "存储与 token 同按计费模型(请求模型)定价")
+ require.NoError(t, svc.RecordUsage(ctx, mapped))
+ require.InDelta(t, want, usageRepo.lastLog.ActualCost, 1e-12, "报价与实际计费同口径")
+
+ alias := &RecordUsageInput{
+ Result: &ForwardResult{Model: "customer-alias", UpstreamModel: "gemini-3.8-flash", CacheStorageTokenHours: tokenHours},
+ APIKey: apiKey,
+ }
+ require.True(t, svc.CacheStoragePriced(ctx, alias))
+ require.InDelta(t, tokenHours*0.0000005*2, svc.QuoteUsageCost(ctx, alias), 1e-12, "计费模型无存储价时回退到实际转发模型")
+
+ unpriced := &RecordUsageInput{
+ Result: &ForwardResult{Model: "customer-alias", UpstreamModel: "unknown-upstream", CacheStorageTokenHours: tokenHours},
+ APIKey: apiKey,
+ }
+ require.False(t, svc.CacheStoragePriced(ctx, unpriced))
+}
+
+func TestGeminiCachedContentStorageOnlyIsNotARequest(t *testing.T) {
+ ctx := context.Background()
+ svc, usageRepo := newGeminiCacheBillingGatewayForTest(t)
+ groupID := int64(34)
+ perRequest := 0.05
+ pricing := []ChannelModelPricing{{Models: []string{"gemini-3.8-flash"}, BillingMode: BillingModePerRequest, PerRequestPrice: &perRequest}}
+ svc.channelService = newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive,
+ AccountStatsPricingRules: []AccountStatsPricingRule{{GroupIDs: []int64{groupID}, Pricing: pricing}}}, groupID, PlatformGemini)
+ svc.resolver = NewModelPricingResolver(svc.channelService, svc.billingService)
+ apiKey := &APIKey{ID: 822, GroupID: &groupID, User: &User{ID: 622},
+ Group: &Group{ID: groupID, Platform: PlatformGemini, RateMultiplier: 1, Hydrated: true, ModelPricing: pricing}}
+ tokenHours := 20000.0
+ storage := tokenHours * 0.0000005
+
+ record := func(tokens int) *UsageLog {
+ require.NoError(t, svc.RecordUsage(ctx, &RecordUsageInput{
+ Result: &ForwardResult{RequestID: fmt.Sprintf("cc-%d", tokens), Model: "gemini-3.8-flash",
+ Usage: ClaudeUsage{InputTokens: tokens}, CacheStorageTokenHours: tokenHours},
+ APIKey: apiKey, User: apiKey.User, Account: &Account{ID: 712, Platform: PlatformGemini},
+ }))
+ return usageRepo.lastLog
+ }
+
+ created := record(10000)
+ require.InDelta(t, perRequest+storage, created.TotalCost, 1e-12, "创建是一次请求:按次价 + 存储费")
+ require.NotNil(t, created.AccountStatsCost)
+ require.InDelta(t, perRequest+storage, *created.AccountStatsCost, 1e-12)
+
+ extended := record(0)
+ require.InDelta(t, storage, extended.TotalCost, 1e-12, "延长有效期不算一次请求,只收存储费")
+ require.Nil(t, extended.AccountStatsCost, "账号统计成本回落 total_cost,不套按次规则")
+}
+
+func TestFindGeminiCachedContentReferenceRejectsAmbiguousKeys(t *testing.T) {
+ for name, body := range map[string]string{
+ "duplicate top-level": `{"cachedContent":"cachedContents/a","contents":[],"cachedContent":"cachedContents/b"}`,
+ "snake top-level": `{"cached_content":"cachedContents/a"}`,
+ "snake beside camel": `{"cachedContent":"cachedContents/a","cached_content":"cachedContents/b"}`,
+ "duplicate nested": `{"generateContentRequest":{"cachedContent":"cachedContents/a","cachedContent":"cachedContents/b"}}`,
+ "snake nested": `{"generateContentRequest":{"cached_content":"cachedContents/a"}}`,
+ "snake parent with cache": `{"generate_content_request":{"cachedContent":"cachedContents/a"}}`,
+ "duplicate nested parent": `{"generateContentRequest":{},"generateContentRequest":{"cachedContent":"cachedContents/a"}}`,
+ "conflicting two locations": `{"cachedContent":"cachedContents/a","generateContentRequest":{"cachedContent":"cachedContents/b"}}`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ _, err := FindGeminiCachedContentReference([]byte(body))
+ require.Error(t, err)
+ })
+ }
+
+ for name, body := range map[string]string{
+ "snake parent without cache": `{"generate_content_request":{"contents":[]}}`,
+ "key name inside content": `{"contents":[{"role":"user","cached_content":"x","parts":[{"text":"cached_content"}]}]}`,
+ "not an object": `[{"cachedContent":"cachedContents/a"}]`,
+ } {
+ t.Run("allows "+name, func(t *testing.T) {
+ ref, err := FindGeminiCachedContentReference([]byte(body))
+ require.NoError(t, err)
+ require.Nil(t, ref)
+ })
+ }
+
+ ref, err := FindGeminiCachedContentReference([]byte(`{"cachedContent":"cachedContents/a","generateContentRequest":{"cachedContent":"cachedContents/a"}}`))
+ require.NoError(t, err)
+ require.Equal(t, []string{"cachedContent", "generateContentRequest.cachedContent"}, ref.Paths)
+}
+
+func TestGeminiCachedContentPayloadNormalization(t *testing.T) {
+ now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC)
+ maxTTL := 24 * time.Hour
+
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","display_name":"docs","expire_time":"2026-10-09T10:00:00Z"}`), now, maxTTL)
+ require.NoError(t, err)
+ require.Equal(t, "docs", req.DisplayName)
+ require.Equal(t, 2*time.Hour, req.TTL)
+ for _, key := range []string{"display_name", "expire_time", "displayName", "expireTime"} {
+ require.NotContains(t, req.payload, key, "元数据字段不随内容发往上游")
+ }
+
+ for name, body := range map[string]string{
+ "both spellings": `{"model":"gemini-3.8-flash","displayName":"a","display_name":"b"}`,
+ "trailing data": `{"model":"gemini-3.8-flash"} {"model":"x"}`,
+ } {
+ t.Run("rejects "+name, func(t *testing.T) {
+ _, err := ParseGeminiCachedContentCreateRequest([]byte(body), now, maxTTL)
+ require.Error(t, err)
+ })
+ }
+
+ ttl, err := ParseGeminiCachedContentPatchRequest([]byte(`{"expire_time":"2026-10-09T09:00:00Z"}`), "", now, maxTTL)
+ require.NoError(t, err)
+ require.Equal(t, time.Hour, ttl)
+ _, err = ParseGeminiCachedContentPatchRequest([]byte(`{"display_name":"x"}`), "", now, maxTTL)
+ require.ErrorContains(t, err, "immutable")
+}
+
+func TestGeminiCachedContentTTLRoundsUpToWholeSeconds(t *testing.T) {
+ now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC)
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","ttl":"1e-10s"}`), now, 24*time.Hour)
+ require.NoError(t, err)
+ require.Equal(t, time.Second, req.TTL, "极小的显式有效期按 1 秒处理,不回落到默认 1 小时")
+ require.True(t, req.ttlExplicit)
+
+ ttl, err := ParseGeminiCachedContentPatchRequest([]byte(`{"ttl":"1e-10s"}`), "", now, 24*time.Hour)
+ require.NoError(t, err)
+ require.Equal(t, time.Second, ttl)
+
+ req, err = ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","expireTime":"2026-10-09T08:00:10.2Z"}`), now, 24*time.Hour)
+ require.NoError(t, err)
+ require.Equal(t, 11*time.Second, req.TTL, "expireTime 折算的有效期与发往上游的整秒 ttl 一致")
+}
+
+func TestGeminiCachedContentCreateKeepsNumbersVerbatim(t *testing.T) {
+ svc, httpStub := newGeminiCachedContentServiceForTest(t, http.StatusOK,
+ `{"name":"cachedContents/up1","usageMetadata":{"totalTokenCount":2000}}`)
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"models/gemini-3.8-flash","contents":[{"role":"user","parts":[
+ {"functionResponse":{"name":"lookup","response":{"order_id":1790000000000000001,"ratio":0.10}}}]}]}`), time.Now(), 24*time.Hour)
+ require.NoError(t, err)
+ account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "secret"}}
+ _, err = svc.CreateUpstream(context.Background(), account, req, "gemini-3.8-flash", "pub1", time.Hour)
+ require.NoError(t, err)
+ raw, err := io.ReadAll(httpStub.lastReq.Body)
+ require.NoError(t, err)
+ require.Contains(t, string(raw), `"order_id":1790000000000000001`)
+ require.Contains(t, string(raw), `"ratio":0.10`)
+}
+
+func TestGeminiCachedContentCreateUpstreamUnusableResponse(t *testing.T) {
+ account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "secret"}}
+ for name, tc := range map[string]struct {
+ body string
+ wantName string
+ }{
+ "missing token count": {`{"name":"cachedContents/up9","expireTime":"2099-01-01T00:00:00Z"}`, "cachedContents/up9"},
+ "zero token count": {`{"name":"cachedContents/up9","usageMetadata":{"totalTokenCount":0}}`, "cachedContents/up9"},
+ "unexpected name": {`{"name":"cachedContents/a/../b","usageMetadata":{"totalTokenCount":5}}`, ""},
+ "not json": {``, ""},
+ } {
+ t.Run(name, func(t *testing.T) {
+ svc, _ := newGeminiCachedContentServiceForTest(t, http.StatusOK, tc.body)
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash"}`), time.Now(), 24*time.Hour)
+ require.NoError(t, err)
+ _, err = svc.CreateUpstream(context.Background(), account, req, "gemini-3.8-flash", "pub1", time.Hour)
+ var malformed *GeminiCachedContentMalformedResponseError
+ require.ErrorAs(t, err, &malformed)
+ require.Equal(t, tc.wantName, malformed.Name)
+ })
+ }
+}
+
+type geminiCachedContentCtxProbeUpstream struct {
+ geminiCompatHTTPUpstreamStub
+ ctxErrAtSend error
+}
+
+func (s *geminiCachedContentCtxProbeUpstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) {
+ s.ctxErrAtSend = req.Context().Err()
+ return s.geminiCompatHTTPUpstreamStub.Do(req, proxyURL, accountID, accountConcurrency)
+}
+
+func TestGeminiCachedContentUpstreamCallIgnoresClientCancel(t *testing.T) {
+ up := &geminiCachedContentCtxProbeUpstream{geminiCompatHTTPUpstreamStub: geminiCompatHTTPUpstreamStub{response: &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(`{"name":"cachedContents/up1","usageMetadata":{"totalTokenCount":2000}}`)),
+ }}}
+ svc := NewGeminiCachedContentService(newGeminiCachedContentRepoStub(),
+ &GeminiMessagesCompatService{httpUpstream: up, cfg: &config.Config{}}, &config.Config{})
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash"}`), time.Now(), 24*time.Hour)
+ require.NoError(t, err)
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "secret"}}
+ _, err = svc.CreateUpstream(ctx, account, req, "gemini-3.8-flash", "pub1", time.Hour)
+ require.NoError(t, err)
+ require.NoError(t, up.ctxErrAtSend, "客户端断开不取消发往上游的创建")
+}
+
+func TestClampGeminiCachedContentExpire(t *testing.T) {
+ limit := time.Date(2026, 10, 10, 8, 0, 0, 0, time.UTC)
+ require.Equal(t, limit, ClampGeminiCachedContentExpire(time.Time{}, limit))
+ require.Equal(t, limit, ClampGeminiCachedContentExpire(limit.Add(100*time.Hour), limit), "上游回报的到期时间不超过请求的有效期")
+ earlier := limit.Add(-time.Second)
+ require.Equal(t, earlier, ClampGeminiCachedContentExpire(earlier, limit))
+}
+
+type geminiBoundCacheRateLimitRepo struct {
+ errorPolicyRepoStub
+ rateLimitedCalls int
+}
+
+func (r *geminiBoundCacheRateLimitRepo) SetRateLimited(context.Context, int64, time.Time) error {
+ r.rateLimitedCalls++
+ return nil
+}
+
+func TestGeminiForwardNative_BoundCacheUpstreamGatewayErrorsSkipAccountPenalty(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, status := range []int{http.StatusTooManyRequests, http.StatusServiceUnavailable} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ body := fmt.Sprintf(`{"error":{"code":%d,"message":"The account holding this cached content is temporarily unavailable","status":"UNAVAILABLE"}}`, status)
+ svc, httpStub, _ := newGeminiCachedContentTestService(status, body)
+ repo := &geminiBoundCacheRateLimitRepo{}
+ svc.accountRepo = repo
+ svc.rateLimitService = NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ account := &Account{ID: 711, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "api_key": "k", "base_url": "https://gw.example.com", "explicit_cache_upstream": true,
+ }}
+ c, _ := newGeminiNativeTestContext(t)
+
+ _, err := svc.ForwardNative(WithGeminiCachedContentBound(context.Background()), c, account,
+ "gemini-3.8-flash", "generateContent", false, []byte(geminiCachedContentRequestBody))
+
+ var failoverErr *UpstreamFailoverError
+ require.True(t, errors.As(err, &failoverErr), "交由绑定请求的耗尽处理透传")
+ require.Equal(t, status, failoverErr.StatusCode)
+ require.JSONEq(t, body, string(failoverErr.ResponseBody))
+ require.True(t, failoverErr.BoundUpstreamPassthrough, "标记为上游网关账号的响应,handler 原样回写")
+ require.False(t, failoverErr.RetryableOnSameAccount)
+ require.Equal(t, 1, httpStub.calls, "不在同一账号上退避重试")
+ require.Zero(t, repo.rateLimitedCalls, "不限流整个网关账号")
+ require.Zero(t, repo.tempCalls)
+ require.Zero(t, repo.setErrCalls)
+ })
+ }
+}
+
+type fixedChargeCacheStub struct {
+ billingCacheWorkerStub
+ balance float64
+ sub *SubscriptionCacheData
+ rate *APIKeyRateLimitCacheData
+ // reserved 按维度(user:{id} / scope 名)记录在途预留。
+ reserved map[string]map[string]float64
+}
+
+func (s *fixedChargeCacheStub) GetUserBalance(context.Context, int64) (float64, error) {
+ return s.balance, nil
+}
+
+func (s *fixedChargeCacheStub) GetSubscriptionCache(context.Context, int64, int64) (*SubscriptionCacheData, error) {
+ if s.sub == nil {
+ return nil, errors.New("cache miss")
+ }
+ return s.sub, nil
+}
+
+func (s *fixedChargeCacheStub) GetAPIKeyRateLimit(context.Context, int64) (*APIKeyRateLimitCacheData, error) {
+ if s.rate == nil {
+ return nil, errors.New("cache miss")
+ }
+ return s.rate, nil
+}
+
+func (s *fixedChargeCacheStub) reserve(key, requestID string, amount float64) float64 {
+ if s.reserved == nil {
+ s.reserved = map[string]map[string]float64{}
+ }
+ if s.reserved[key] == nil {
+ s.reserved[key] = map[string]float64{}
+ }
+ sum := 0.0
+ for _, v := range s.reserved[key] {
+ sum += v
+ }
+ s.reserved[key][requestID] = amount
+ return sum
+}
+
+func (s *fixedChargeCacheStub) ReserveInflightBalance(_ context.Context, userID int64, requestID string, amount, balance float64, _ time.Duration) (bool, float64, error) {
+ key := fmt.Sprintf("user:%d", userID)
+ others := s.reserve(key, requestID, amount)
+ if len(s.reserved[key]) > 1 && balance-others < amount {
+ delete(s.reserved[key], requestID)
+ return false, others, nil
+ }
+ return true, others, nil
+}
+
+func (s *fixedChargeCacheStub) ReleaseInflightBalance(_ context.Context, userID int64, requestID string) error {
+ delete(s.reserved[fmt.Sprintf("user:%d", userID)], requestID)
+ return nil
+}
+
+func (s *fixedChargeCacheStub) ReserveInflightScope(_ context.Context, scope, requestID string, amount float64, _ time.Duration) (float64, error) {
+ return s.reserve(scope, requestID, amount), nil
+}
+
+func (s *fixedChargeCacheStub) ReleaseInflightScope(_ context.Context, scope, requestID string) error {
+ delete(s.reserved[scope], requestID)
+ return nil
+}
+
+type fixedChargeAPIKeyRepoStub struct {
+ APIKeyRepository
+ data *APIKeyRateLimitData
+}
+
+func (r *fixedChargeAPIKeyRepoStub) GetRateLimitData(context.Context, int64) (*APIKeyRateLimitData, error) {
+ return r.data, nil
+}
+
+type fixedChargeSubscriptionRepoStub struct {
+ UserSubscriptionRepository
+ sub *UserSubscription
+}
+
+func (r *fixedChargeSubscriptionRepoStub) GetActiveByUserIDAndGroupID(context.Context, int64, int64) (*UserSubscription, error) {
+ return r.sub, nil
+}
+
+func TestReserveFixedCharge(t *testing.T) {
+ ctx := context.Background()
+ user := &User{ID: 1}
+ newSvc := func(cache *fixedChargeCacheStub) *BillingCacheService {
+ svc := NewBillingCacheService(cache, nil, nil, nil, nil, nil, &config.Config{}, nil)
+ t.Cleanup(svc.Stop)
+ return svc
+ }
+ reservingSvc := func(cache *fixedChargeCacheStub, subRepo UserSubscriptionRepository, apiKeyRepo APIKeyRepository) *BillingCacheService {
+ cfg := &config.Config{}
+ cfg.Billing.InflightReservation.Enabled = true
+ svc := NewBillingCacheService(cache, nil, subRepo, apiKeyRepo, nil, nil, cfg, nil)
+ t.Cleanup(svc.Stop)
+ return svc
+ }
+ reserve := func(svc *BillingCacheService, apiKey *APIKey, group *Group, sub *UserSubscription, amount float64) error {
+ res, err := svc.ReserveFixedCharge(ctx, user, apiKey, group, sub, amount)
+ res.Release()
+ return err
+ }
+
+ t.Run("balance must cover the amount", func(t *testing.T) {
+ svc := newSvc(&fixedChargeCacheStub{balance: 10})
+ require.NoError(t, reserve(svc, nil, nil, nil, 10))
+ require.ErrorIs(t, reserve(svc, nil, nil, nil, 10.01), ErrInsufficientBalance)
+ require.NoError(t, reserve(svc, nil, nil, nil, 0))
+ })
+
+ t.Run("subscription windows must cover the amount", func(t *testing.T) {
+ daily := 5.0
+ group := &Group{ID: 2, SubscriptionType: SubscriptionTypeSubscription, DailyLimitUSD: &daily}
+ svc := newSvc(&fixedChargeCacheStub{sub: &SubscriptionCacheData{
+ Status: SubscriptionStatusActive, ExpiresAt: time.Now().Add(time.Hour), DailyUsage: 3,
+ }})
+ sub := &UserSubscription{ID: 1}
+ require.NoError(t, reserve(svc, nil, group, sub, 2))
+ require.ErrorIs(t, reserve(svc, nil, group, sub, 2.5), ErrDailyLimitExceeded)
+ })
+
+ t.Run("api key quota and rate windows include the amount", func(t *testing.T) {
+ svc := newSvc(&fixedChargeCacheStub{balance: 100, rate: &APIKeyRateLimitCacheData{
+ Usage1d: 8, Window1d: time.Now().Unix(),
+ }})
+ quotaKey := &APIKey{ID: 5, Quota: 10, QuotaUsed: 9}
+ require.NoError(t, reserve(svc, quotaKey, nil, nil, 1))
+ require.ErrorIs(t, reserve(svc, quotaKey, nil, nil, 1.5), ErrAPIKeyQuotaExhausted)
+
+ windowKey := &APIKey{ID: 6, RateLimit1d: 10}
+ require.NoError(t, reserve(svc, windowKey, nil, nil, 2))
+ require.ErrorIs(t, reserve(svc, windowKey, nil, nil, 2.5), ErrAPIKeyRateLimit1dExceeded)
+ })
+
+ t.Run("usage is read from the database instead of request snapshots", func(t *testing.T) {
+ now := time.Now()
+ apiKeyRepo := &fixedChargeAPIKeyRepoStub{data: &APIKeyRateLimitData{QuotaUsed: 9.5, Usage1d: 8, Window1dStart: &now}}
+ svc := reservingSvc(&fixedChargeCacheStub{balance: 100}, nil, apiKeyRepo)
+ require.ErrorIs(t, reserve(svc, &APIKey{ID: 5, Quota: 10}, nil, nil, 1), ErrAPIKeyQuotaExhausted, "请求上下文中的 QuotaUsed 可能滞后")
+ require.ErrorIs(t, reserve(svc, &APIKey{ID: 6, RateLimit1d: 10}, nil, nil, 2.5), ErrAPIKeyRateLimit1dExceeded)
+
+ daily := 5.0
+ group := &Group{ID: 2, SubscriptionType: SubscriptionTypeSubscription, DailyLimitUSD: &daily}
+ subRepo := &fixedChargeSubscriptionRepoStub{sub: &UserSubscription{Status: SubscriptionStatusActive, DailyUsageUSD: 4}}
+ svc = reservingSvc(&fixedChargeCacheStub{sub: &SubscriptionCacheData{Status: SubscriptionStatusActive}}, subRepo, nil)
+ require.ErrorIs(t, reserve(svc, nil, group, &UserSubscription{ID: 1}, 2), ErrDailyLimitExceeded, "订阅缓存用量可能滞后")
+ })
+
+ t.Run("unsettled charges hold subscription and api key headroom", func(t *testing.T) {
+ daily := 110.0
+ group := &Group{ID: 2, SubscriptionType: SubscriptionTypeSubscription, DailyLimitUSD: &daily}
+ sub := &UserSubscription{ID: 1}
+ cache := &fixedChargeCacheStub{balance: 1000, sub: &SubscriptionCacheData{Status: SubscriptionStatusActive}}
+ svc := reservingSvc(cache, nil, nil)
+ first, err := svc.ReserveFixedCharge(ctx, user, nil, group, sub, 103.5)
+ require.NoError(t, err)
+ _, err = svc.ReserveFixedCharge(ctx, user, nil, group, sub, 103.5)
+ require.ErrorIs(t, err, ErrDailyLimitExceeded)
+ first.Release()
+ second, err := svc.ReserveFixedCharge(ctx, user, nil, group, sub, 103.5)
+ require.NoError(t, err)
+ second.Release()
+
+ apiKey := &APIKey{ID: 5, Quota: 110}
+ first, err = svc.ReserveFixedCharge(ctx, user, apiKey, nil, nil, 103.5)
+ require.NoError(t, err)
+ _, err = svc.ReserveFixedCharge(ctx, user, apiKey, nil, nil, 103.5)
+ require.ErrorIs(t, err, ErrAPIKeyQuotaExhausted)
+ first.Release()
+ for key, reservations := range cache.reserved {
+ require.Empty(t, reservations, "拒绝与释放都不留下预留:%s", key)
+ }
+ })
+
+ t.Run("simple mode skips the check", func(t *testing.T) {
+ cfg := &config.Config{RunMode: config.RunModeSimple}
+ svc := NewBillingCacheService(&fixedChargeCacheStub{}, nil, nil, nil, nil, nil, cfg, nil)
+ t.Cleanup(svc.Stop)
+ require.NoError(t, reserve(svc, nil, nil, nil, 1000))
+ })
+}
diff --git a/backend/internal/service/gemini_cached_content_not_found_test.go b/backend/internal/service/gemini_cached_content_not_found_test.go
new file mode 100644
index 000000000..e2637189c
--- /dev/null
+++ b/backend/internal/service/gemini_cached_content_not_found_test.go
@@ -0,0 +1,186 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+// 上游对不存在、已过期、已删除或不属于当前项目的显式缓存一律返回这个 403。
+const geminiCachedContentNotFoundBody = `{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}`
+
+func newGeminiCachedContentTestService(status int, body string) (*GeminiMessagesCompatService, *geminiCompatHTTPUpstreamStub, *errorPolicyRepoStub) {
+ repo := &errorPolicyRepoStub{}
+ httpStub := &geminiCompatHTTPUpstreamStub{
+ response: &http.Response{
+ StatusCode: status,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(body)),
+ },
+ }
+ svc := &GeminiMessagesCompatService{
+ httpUpstream: httpStub,
+ cfg: &config.Config{},
+ rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil),
+ }
+ return svc, httpStub, repo
+}
+
+func geminiDefaultPolicyAPIKeyAccount() *Account {
+ return &Account{
+ ID: 710,
+ Platform: PlatformGemini,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "api_key": "test-key",
+ },
+ }
+}
+
+const geminiCachedContentRequestBody = `{"cachedContent":"cachedContents/doesnotexist","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`
+
+func TestGeminiForwardNative_CachedContentNotFoundPassthroughWithoutAccountPenalty(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, tc := range []struct {
+ name string
+ action string
+ stream bool
+ }{
+ {name: "generateContent", action: "generateContent"},
+ {name: "streamGenerateContent", action: "streamGenerateContent", stream: true},
+ {name: "countTokens", action: "countTokens"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ svc, httpStub, repo := newGeminiCachedContentTestService(http.StatusForbidden, geminiCachedContentNotFoundBody)
+ c, rec := newGeminiNativeTestContext(t)
+
+ result, err := svc.ForwardNative(context.Background(), c, geminiDefaultPolicyAPIKeyAccount(),
+ "gemini-3.8-flash", tc.action, tc.stream, []byte(geminiCachedContentRequestBody))
+
+ require.Nil(t, result)
+ require.Error(t, err)
+ var failoverErr *UpstreamFailoverError
+ require.False(t, errors.As(err, &failoverErr), "缓存不存在是请求问题,不应换号")
+ require.Equal(t, 0, repo.setErrCalls, "不应把账号标记为错误")
+ require.Equal(t, 0, repo.tempCalls, "不应临时停调度")
+ require.Equal(t, 1, httpStub.calls, "不应重试")
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Equal(t, GeminiCachedContentNotFoundResponse, rec.Body.String(), "应返回标准缓存不存在响应")
+ require.True(t, IsOpsRequestScopedError(c), "缓存不存在按客户端请求错误统计")
+ })
+ }
+}
+
+func TestGeminiForwardNative_CachedContentNotFoundBypassesTempUnschedulableRules(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ svc, _, repo := newGeminiCachedContentTestService(http.StatusForbidden, geminiCachedContentNotFoundBody)
+ c, rec := newGeminiNativeTestContext(t)
+ account := geminiDefaultPolicyAPIKeyAccount()
+ account.Credentials["temp_unschedulable_enabled"] = true
+ account.Credentials["temp_unschedulable_rules"] = []any{
+ map[string]any{
+ "error_code": float64(403),
+ "keywords": []any{"permission denied"},
+ "duration_minutes": float64(10),
+ "description": "403 permission denied",
+ },
+ }
+
+ _, err := svc.ForwardNative(context.Background(), c, account,
+ "gemini-3.8-flash", "generateContent", false, []byte(geminiCachedContentRequestBody))
+
+ require.Error(t, err)
+ var failoverErr *UpstreamFailoverError
+ require.False(t, errors.As(err, &failoverErr))
+ require.Equal(t, 0, repo.tempCalls, "临时不可调度规则不应命中")
+ require.Equal(t, 0, repo.setErrCalls)
+ require.Equal(t, http.StatusForbidden, rec.Code)
+}
+
+func TestGeminiForwardNative_OtherForbiddenStillPenalizesAccount(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ body := `{"error":{"code":403,"message":"Your project has been denied access. Please contact support.","status":"PERMISSION_DENIED"}}`
+ svc, _, repo := newGeminiCachedContentTestService(http.StatusForbidden, body)
+ c, _ := newGeminiNativeTestContext(t)
+
+ _, err := svc.ForwardNative(context.Background(), c, geminiDefaultPolicyAPIKeyAccount(),
+ "gemini-3.8-flash", "generateContent", false, []byte(geminiCachedContentRequestBody))
+
+ var failoverErr *UpstreamFailoverError
+ require.True(t, errors.As(err, &failoverErr), "其他 403 仍按账号问题换号")
+ require.Equal(t, 1, repo.setErrCalls, "其他 403 仍标记账号错误")
+}
+
+// Vertex 对已删除 / 已过期缓存的响应(2026-10 实测):生成请求 400,缓存资源接口 404,文案含上游缓存数字 ID。
+const (
+ geminiVertexCachedContentInvalidStateBody = `{"error":{"code":400,"message":"Invalid resource state for cache content 8079767076522164224.","status":"FAILED_PRECONDITION"}}`
+ geminiVertexCachedContentNotFoundBody = `{"error":{"code":404,"message":"Cached content 8079767076522164224 is not found.","status":"NOT_FOUND"}}`
+)
+
+func TestIsGeminiCachedContentNotFound(t *testing.T) {
+ require.True(t, isGeminiCachedContentNotFound(http.StatusForbidden, []byte(geminiCachedContentNotFoundBody)))
+ require.True(t, isGeminiCachedContentNotFound(http.StatusForbidden,
+ []byte(`[{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}]`)))
+ require.True(t, isGeminiCachedContentNotFound(http.StatusBadRequest, []byte(geminiVertexCachedContentInvalidStateBody)))
+ require.True(t, isGeminiCachedContentNotFound(http.StatusNotFound, []byte(geminiVertexCachedContentNotFoundBody)))
+
+ require.False(t, isGeminiCachedContentNotFound(http.StatusBadRequest, []byte(geminiCachedContentNotFoundBody)))
+ require.False(t, isGeminiCachedContentNotFound(http.StatusForbidden,
+ []byte(`{"error":{"code":403,"message":"Permission denied: Consumer has been suspended.","status":"PERMISSION_DENIED"}}`)))
+ require.False(t, isGeminiCachedContentNotFound(http.StatusNotFound,
+ []byte(`{"error":{"code":404,"message":"Publisher Model `+"`projects/p/locations/global/publishers/google/models/gemini-9`"+` was not found.","status":"NOT_FOUND"}}`)))
+ require.False(t, isGeminiCachedContentNotFound(http.StatusBadRequest,
+ []byte(`{"error":{"code":400,"message":"Tool config, tools and system instruction should not be set in the request when using cached content.","status":"INVALID_ARGUMENT"}}`)))
+ require.False(t, isGeminiCachedContentNotFound(http.StatusInternalServerError, []byte(geminiVertexCachedContentNotFoundBody)))
+}
+
+func TestGeminiForwardNative_VertexCachedContentNotFoundReturnsStandardForbidden(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, tc := range []struct {
+ name string
+ status int
+ body string
+ action string
+ stream bool
+ }{
+ {name: "generate invalid resource state", status: http.StatusBadRequest, body: geminiVertexCachedContentInvalidStateBody, action: "generateContent"},
+ {name: "stream invalid resource state", status: http.StatusBadRequest, body: geminiVertexCachedContentInvalidStateBody, action: "streamGenerateContent", stream: true},
+ {name: "generate not found", status: http.StatusNotFound, body: geminiVertexCachedContentNotFoundBody, action: "generateContent"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ svc, httpStub, repo := newGeminiCachedContentTestService(tc.status, tc.body)
+ svc.tokenProvider = NewGeminiTokenProvider(nil, &fakeGeminiTokenCache{token: "ya29.test-token"}, nil)
+ c, rec := newGeminiNativeTestContext(t)
+ account := vertexServiceAccount()
+ account.ID = 811
+
+ result, err := svc.ForwardNative(context.Background(), c, account,
+ "gemini-3.8-flash", tc.action, tc.stream,
+ []byte(`{"cachedContent":"projects/proj-1/locations/global/cachedContents/8079767076522164224","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`))
+
+ require.Nil(t, result)
+ require.Error(t, err)
+ var failoverErr *UpstreamFailoverError
+ require.False(t, errors.As(err, &failoverErr), "缓存不存在是请求问题,不应换号")
+ require.Equal(t, 0, repo.setErrCalls)
+ require.Equal(t, 0, repo.tempCalls)
+ require.Empty(t, repo.modelRateLimitCalls, "404 不应按模型不存在记模型限流")
+ require.Equal(t, 1, httpStub.calls, "不应重试")
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Equal(t, GeminiCachedContentNotFoundResponse, rec.Body.String())
+ require.NotContains(t, rec.Body.String(), "8079767076522164224", "不应暴露上游缓存 ID")
+ require.True(t, IsOpsRequestScopedError(c), "缓存不存在按客户端请求错误统计")
+ errType, _ := OpsLocalErrorType(c)
+ require.Equal(t, "permission_error", errType)
+ })
+ }
+}
diff --git a/backend/internal/service/gemini_cached_content_test.go b/backend/internal/service/gemini_cached_content_test.go
new file mode 100644
index 000000000..1b7cca4dd
--- /dev/null
+++ b/backend/internal/service/gemini_cached_content_test.go
@@ -0,0 +1,522 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/stretchr/testify/require"
+)
+
+type geminiCachedContentRepoStub struct {
+ records map[string]*GeminiCachedContent
+ nextID int64
+ deleted []int64
+}
+
+func newGeminiCachedContentRepoStub() *geminiCachedContentRepoStub {
+ return &geminiCachedContentRepoStub{records: map[string]*GeminiCachedContent{}}
+}
+
+func (r *geminiCachedContentRepoStub) Create(_ context.Context, record *GeminiCachedContent) error {
+ r.nextID++
+ record.ID = r.nextID
+ r.records[record.PublicID] = record
+ return nil
+}
+
+func (r *geminiCachedContentRepoStub) GetForOwner(_ context.Context, apiKeyID int64, publicID string) (*GeminiCachedContent, error) {
+ record, ok := r.records[publicID]
+ if !ok || record.APIKeyID != apiKeyID {
+ return nil, ErrGeminiCachedContentNotFound
+ }
+ return record, nil
+}
+
+func (r *geminiCachedContentRepoStub) ListForOwner(_ context.Context, apiKeyID, groupID int64, activeAt time.Time, beforeID int64, limit int) ([]*GeminiCachedContent, error) {
+ var out []*GeminiCachedContent
+ for _, record := range r.records {
+ if record.APIKeyID == apiKeyID && record.GroupID == groupID && record.ExpireTime.After(activeAt) && (beforeID <= 0 || record.ID < beforeID) {
+ out = append(out, record)
+ }
+ }
+ if len(out) > limit {
+ out = out[:limit]
+ }
+ return out, nil
+}
+
+func (r *geminiCachedContentRepoStub) BeginMutation(context.Context, int64, time.Time, string, time.Duration) (bool, error) {
+ return true, nil
+}
+
+func (r *geminiCachedContentRepoStub) TakeOverStaleMutation(context.Context, int64, string, time.Duration) (*GeminiCachedContent, error) {
+ return nil, nil
+}
+
+func (r *geminiCachedContentRepoStub) CommitMutation(_ context.Context, id int64, _ string, expireTime time.Time) error {
+ for _, record := range r.records {
+ if record.ID == id {
+ record.ExpireTime = expireTime
+ return nil
+ }
+ }
+ return ErrGeminiCachedContentMutationConflict
+}
+
+func (r *geminiCachedContentRepoStub) ReleaseMutation(context.Context, int64, string) error {
+ return nil
+}
+
+func (r *geminiCachedContentRepoStub) ListStaleMutations(context.Context, int) ([]int64, error) {
+ return nil, nil
+}
+
+func (r *geminiCachedContentRepoStub) SoftDelete(_ context.Context, id int64) error {
+ r.deleted = append(r.deleted, id)
+ for key, record := range r.records {
+ if record.ID == id {
+ delete(r.records, key)
+ }
+ }
+ return nil
+}
+
+func TestParseGeminiCachedContentCreateRequest(t *testing.T) {
+ now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC)
+ maxTTL := 24 * time.Hour
+
+ t.Run("defaults to one hour and strips output-only fields", func(t *testing.T) {
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"models/gemini-3.8-flash","displayName":"docs",
+ "contents":[{"role":"user","parts":[{"text":"x"}]}],"name":"cachedContents/forged","usageMetadata":{"totalTokenCount":1}}`), now, maxTTL)
+ require.NoError(t, err)
+ require.Equal(t, "gemini-3.8-flash", req.Model)
+ require.Equal(t, time.Hour, req.TTL)
+ require.Equal(t, int64(3600), req.TTLSeconds())
+ require.Equal(t, "docs", req.DisplayName)
+ require.NotContains(t, req.payload, "name")
+ require.NotContains(t, req.payload, "usageMetadata")
+ require.Contains(t, req.payload, "contents")
+ })
+
+ t.Run("default is capped by a shorter max ttl", func(t *testing.T) {
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash"}`), now, 30*time.Minute)
+ require.NoError(t, err)
+ require.Equal(t, 30*time.Minute, req.TTL)
+ })
+
+ t.Run("fractional ttl rounds up to whole seconds", func(t *testing.T) {
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","ttl":"3.5s"}`), now, maxTTL)
+ require.NoError(t, err)
+ require.Equal(t, int64(4), req.TTLSeconds())
+ })
+
+ t.Run("expireTime converts to ttl", func(t *testing.T) {
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","expireTime":"2026-10-09T10:00:00Z"}`), now, maxTTL)
+ require.NoError(t, err)
+ require.Equal(t, 2*time.Hour, req.TTL)
+ })
+
+ for name, body := range map[string]string{
+ "missing model": `{"ttl":"60s"}`,
+ "vertex style model": `{"model":"projects/p/locations/l/publishers/google/models/x"}`,
+ "ttl and expireTime": `{"model":"m","ttl":"60s","expireTime":"2026-10-09T10:00:00Z"}`,
+ "ttl over max": `{"model":"m","ttl":"86401s"}`,
+ "non positive ttl": `{"model":"m","ttl":"0s"}`,
+ "ttl without unit": `{"model":"m","ttl":"60"}`,
+ "expireTime in past": `{"model":"m","expireTime":"2026-10-09T07:00:00Z"}`,
+ "displayName too long": `{"model":"m","displayName":"` + strings.Repeat("字", 129) + `"}`,
+ "not an object": `[]`,
+ } {
+ t.Run("rejects "+name, func(t *testing.T) {
+ _, err := ParseGeminiCachedContentCreateRequest([]byte(body), now, maxTTL)
+ require.Error(t, err)
+ })
+ }
+}
+
+func TestParseGeminiCachedContentPatchRequest(t *testing.T) {
+ now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC)
+ ttl, err := ParseGeminiCachedContentPatchRequest([]byte(`{"ttl":"7200s"}`), "ttl", now, 24*time.Hour)
+ require.NoError(t, err)
+ require.Equal(t, 2*time.Hour, ttl)
+
+ ttl, err = ParseGeminiCachedContentPatchRequest([]byte(`{"expireTime":"2026-10-09T09:00:00Z"}`), "", now, 24*time.Hour)
+ require.NoError(t, err)
+ require.Equal(t, time.Hour, ttl)
+
+ _, err = ParseGeminiCachedContentPatchRequest([]byte(`{"displayName":"x"}`), "displayName", now, 24*time.Hour)
+ require.ErrorContains(t, err, "immutable")
+ _, err = ParseGeminiCachedContentPatchRequest([]byte(`{"ttl":"60s"}`), "ttl,displayName", now, 24*time.Hour)
+ require.ErrorContains(t, err, "immutable")
+ _, err = ParseGeminiCachedContentPatchRequest([]byte(`{}`), "", now, 24*time.Hour)
+ require.Error(t, err)
+ _, err = ParseGeminiCachedContentPatchRequest([]byte(`{"ttl":"90000s"}`), "", now, 24*time.Hour)
+ require.ErrorContains(t, err, "maximum")
+}
+
+func TestGeminiCachedContentReferenceRewrite(t *testing.T) {
+ ref, err := FindGeminiCachedContentReference([]byte(`{"contents":[]}`))
+ require.NoError(t, err)
+ require.Nil(t, ref)
+
+ body := []byte(`{"cachedContent":"cachedContents/abc","contents":[]}`)
+ ref, err = FindGeminiCachedContentReference(body)
+ require.NoError(t, err)
+ require.Equal(t, "cachedContents/abc", ref.Name)
+ out, err := RewriteGeminiCachedContentReference(body, ref, "cachedContents/upstream1")
+ require.NoError(t, err)
+ require.JSONEq(t, `{"cachedContent":"cachedContents/upstream1","contents":[]}`, string(out))
+
+ countBody := []byte(`{"generateContentRequest":{"model":"models/m","cachedContent":"cachedContents/abc","contents":[]}}`)
+ ref, err = FindGeminiCachedContentReference(countBody)
+ require.NoError(t, err)
+ out, err = RewriteGeminiCachedContentReference(countBody, ref, "projects/1/locations/us-central1/cachedContents/9")
+ require.NoError(t, err)
+ require.JSONEq(t, `{"generateContentRequest":{"model":"models/m","cachedContent":"projects/1/locations/us-central1/cachedContents/9","contents":[]}}`, string(out))
+
+ _, err = FindGeminiCachedContentReference([]byte(`{"cachedContent":"cachedContents/a","generateContentRequest":{"cachedContent":"cachedContents/b"}}`))
+ require.Error(t, err)
+ _, err = FindGeminiCachedContentReference([]byte(`{"cachedContent":1}`))
+ require.Error(t, err)
+}
+
+func TestIsGeminiExplicitCacheAccount(t *testing.T) {
+ cases := []struct {
+ name string
+ account *Account
+ want bool
+ }{
+ {"official api key", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k"}}, true},
+ {"explicit official base url", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k", "base_url": "https://generativelanguage.googleapis.com/"}}, true},
+ {"reseller base url", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k", "base_url": "https://relay.example.com"}}, false},
+ {"upstream gateway with explicit cache switch", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k", "base_url": "https://relay.example.com", "explicit_cache_upstream": true}}, true},
+ {"official host with path prefix", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k", "base_url": "https://generativelanguage.googleapis.com/antigravity"}}, false},
+ {"missing api key", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey}, false},
+ {"vertex service account", &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount}, true},
+ {"vertex api key", &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"auth_mode": "apikey", "api_key": "k", "project_id": "my-project"}}, false},
+ {"oauth", &Account{Platform: PlatformGemini, Type: AccountTypeOAuth}, false},
+ {"antigravity api key", &Account{Platform: PlatformAntigravity, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k"}}, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ require.Equal(t, tc.want, IsGeminiExplicitCacheAccount(tc.account))
+ })
+ }
+}
+
+func TestGeminiCachedContentVertexURLs(t *testing.T) {
+ account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{
+ "project_id": "proj-1",
+ "location": "us-central1",
+ "vertex_model_locations": map[string]any{"gemini-3.8-flash": "global"},
+ }}
+ model, err := GeminiCachedContentUpstreamModelResource(account, "gemini-3.8-flash")
+ require.NoError(t, err)
+ require.Equal(t, "projects/proj-1/locations/global/publishers/google/models/gemini-3.8-flash", model)
+
+ collection, err := geminiCachedContentCollectionURL(account, "", "gemini-3.8-flash")
+ require.NoError(t, err)
+ require.Equal(t, "https://aiplatform.googleapis.com/v1/projects/proj-1/locations/global/cachedContents", collection)
+
+ collection, err = geminiCachedContentCollectionURL(account, "", "gemini-3.1-pro-preview")
+ require.NoError(t, err)
+ require.Equal(t, "https://us-central1-aiplatform.googleapis.com/v1/projects/proj-1/locations/us-central1/cachedContents", collection)
+
+ resource, err := geminiCachedContentResourceURL(account, "", "projects/123/locations/europe-west4/cachedContents/456")
+ require.NoError(t, err)
+ require.Equal(t, "https://europe-west4-aiplatform.googleapis.com/v1/projects/123/locations/europe-west4/cachedContents/456", resource)
+
+ _, err = geminiCachedContentResourceURL(account, "", "projects/123/locations/europe-west4/cachedContents/../x")
+ require.Error(t, err)
+ _, err = geminiCachedContentResourceURL(&Account{Type: AccountTypeAPIKey}, "https://generativelanguage.googleapis.com", "cachedContents/a/../b")
+ require.Error(t, err)
+}
+
+func newGeminiCachedContentServiceForTest(t *testing.T, status int, respBody string) (*GeminiCachedContentService, *geminiCompatHTTPUpstreamStub) {
+ t.Helper()
+ httpStub := &geminiCompatHTTPUpstreamStub{response: &http.Response{
+ StatusCode: status,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(respBody)),
+ }}
+ compat := &GeminiMessagesCompatService{httpUpstream: httpStub, cfg: &config.Config{}}
+ return NewGeminiCachedContentService(newGeminiCachedContentRepoStub(), compat, &config.Config{}), httpStub
+}
+
+func TestGeminiCachedContentCreateUpstreamAIStudio(t *testing.T) {
+ svc, httpStub := newGeminiCachedContentServiceForTest(t, http.StatusOK,
+ `{"name":"cachedContents/up123","model":"models/gemini-3.8-flash","usageMetadata":{"totalTokenCount":6273},"expireTime":"2026-10-09T09:50:26.591575799Z"}`)
+ account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "secret"}}
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"models/gemini-3.8-flash","displayName":"user label",
+ "systemInstruction":{"parts":[{"text":"sys"}]},"contents":[{"role":"user","parts":[{"text":"doc"}]}]}`), time.Now(), 24*time.Hour)
+ require.NoError(t, err)
+
+ upstream, err := svc.CreateUpstream(context.Background(), account, req, "gemini-3.8-flash", "pub1", req.TTL)
+ require.NoError(t, err)
+ require.Equal(t, "cachedContents/up123", upstream.Name)
+ require.Equal(t, int64(6273), upstream.TotalTokenCount)
+ require.Equal(t, 2026, upstream.ExpireTime.Year())
+
+ sent := httpStub.lastReq
+ require.Equal(t, http.MethodPost, sent.Method)
+ require.Equal(t, "https://generativelanguage.googleapis.com/v1beta/cachedContents", sent.URL.String())
+ require.Equal(t, "secret", sent.Header.Get("x-goog-api-key"))
+ raw, err := io.ReadAll(sent.Body)
+ require.NoError(t, err)
+ var payload map[string]any
+ require.NoError(t, json.Unmarshal(raw, &payload))
+ require.Equal(t, "models/gemini-3.8-flash", payload["model"])
+ require.Equal(t, "3600s", payload["ttl"])
+ require.Equal(t, "s2a-pub1", payload["displayName"], "上游 displayName 写网关标记,用户标签只存本地")
+ require.Contains(t, payload, "systemInstruction")
+ require.Contains(t, payload, "contents")
+}
+
+func TestGeminiCachedContentUpstreamErrorClassification(t *testing.T) {
+ notFoundBody := `{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}`
+ svc, _ := newGeminiCachedContentServiceForTest(t, http.StatusForbidden, notFoundBody)
+ account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "secret"}}
+ record := &GeminiCachedContent{UpstreamName: "cachedContents/up123"}
+
+ err := svc.DeleteUpstream(context.Background(), account, record)
+ var upErr *GeminiCachedContentUpstreamError
+ require.ErrorAs(t, err, &upErr)
+ require.True(t, upErr.NotFound())
+ require.True(t, upErr.RetryableOnOtherAccount())
+
+ quota := &GeminiCachedContentUpstreamError{StatusCode: http.StatusTooManyRequests}
+ require.True(t, quota.RetryableOnOtherAccount())
+ badRequest := &GeminiCachedContentUpstreamError{StatusCode: http.StatusBadRequest}
+ require.False(t, badRequest.RetryableOnOtherAccount())
+ require.False(t, badRequest.NotFound())
+}
+
+func TestGeminiCachedContentResolve(t *testing.T) {
+ repo := newGeminiCachedContentRepoStub()
+ now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC)
+ svc := NewGeminiCachedContentService(repo, nil, &config.Config{})
+ svc.now = func() time.Time { return now }
+ groupID := int64(5)
+ require.NoError(t, repo.Create(context.Background(), &GeminiCachedContent{
+ PublicID: "abc123", APIKeyID: 1, GroupID: groupID, ExpireTime: now.Add(time.Hour),
+ }))
+ require.NoError(t, repo.Create(context.Background(), &GeminiCachedContent{
+ PublicID: "expired1", APIKeyID: 1, GroupID: groupID, ExpireTime: now.Add(-time.Second),
+ }))
+
+ record, err := svc.Resolve(context.Background(), 1, &groupID, "cachedContents/abc123")
+ require.NoError(t, err)
+ require.Equal(t, "abc123", record.PublicID)
+
+ otherGroup := int64(6)
+ for name, call := range map[string]func() error{
+ "other api key": func() error {
+ _, err := svc.Resolve(context.Background(), 2, &groupID, "cachedContents/abc123")
+ return err
+ },
+ "other group": func() error {
+ _, err := svc.Resolve(context.Background(), 1, &otherGroup, "cachedContents/abc123")
+ return err
+ },
+ "expired": func() error {
+ _, err := svc.Resolve(context.Background(), 1, &groupID, "cachedContents/expired1")
+ return err
+ },
+ "malformed": func() error {
+ _, err := svc.Resolve(context.Background(), 1, &groupID, "cachedContents/../x")
+ return err
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ require.ErrorIs(t, call(), ErrGeminiCachedContentNotFound)
+ })
+ }
+}
+
+func TestGeminiCachedContentPublicID(t *testing.T) {
+ id, err := NewGeminiCachedContentPublicID()
+ require.NoError(t, err)
+ require.Len(t, id, 40)
+ parsed, ok := ParseGeminiCachedContentPublicID(GeminiCachedContentNamePrefix + id)
+ require.True(t, ok)
+ require.Equal(t, id, parsed)
+}
+
+func TestGeminiCachedContentStoragePricingAndSurcharge(t *testing.T) {
+ pricing := &PricingService{}
+ data, err := pricing.parsePricingData([]byte(`{"gemini-3.8-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075,
+ "output_cost_per_token":0.00000375,"cache_read_input_token_cost":0.000000075,"cache_storage_cost_per_token_per_hour":0.0000005}}`))
+ require.NoError(t, err)
+ pricing.pricingData = data
+ billing := NewBillingService(&config.Config{}, pricing)
+
+ price := billing.CacheStoragePricePerTokenHour("models/gemini-3.8-flash")
+ require.InDelta(t, 0.0000005, price, 1e-15)
+ require.Zero(t, billing.CacheStoragePricePerTokenHour("gemini-unknown-model"))
+
+ tokenHours := GeminiCachedContentStorageTokenHours(10000, 2*time.Hour)
+ require.InDelta(t, 20000, tokenHours, 1e-9)
+ storage := tokenHours * price
+ require.InDelta(t, 0.01, storage, 1e-12)
+
+ gateway := &GatewayService{billingService: billing}
+ groupID := int64(3)
+ apiKey := &APIKey{GroupID: &groupID, Group: &Group{ID: groupID, Hydrated: true}}
+ cost := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{
+ Model: "gemini-3.8-flash",
+ Usage: ClaudeUsage{InputTokens: 10000},
+ CacheStorageTokenHours: tokenHours,
+ }, apiKey, "gemini-3.8-flash", 2, 2, time.Now())
+ inputCost := 10000 * 0.00000075
+ require.InDelta(t, inputCost+storage, cost.TotalCost, 1e-12)
+ require.InDelta(t, (inputCost+storage)*2, cost.ActualCost, 1e-12)
+
+ storageOnly := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{
+ Model: "gemini-3.8-flash",
+ CacheStorageTokenHours: tokenHours,
+ }, apiKey, "gemini-3.8-flash", 1.5, 1.5, time.Now())
+ require.InDelta(t, storage, storageOnly.TotalCost, 1e-12)
+ require.InDelta(t, storage*1.5, storageOnly.ActualCost, 1e-12)
+}
+
+func TestGeminiCachedContentStorageCostInAccountStats(t *testing.T) {
+ const (
+ model = "gemini-3.8-flash"
+ groupID = int64(31)
+ inputTokens = 10000
+ storage = 0.01
+ inputPrice = 0.00000075
+ rulePrice = 0.0000002
+ )
+ newPricing := func() *PricingService {
+ pricing := &PricingService{}
+ data, err := pricing.parsePricingData([]byte(`{"gemini-3.8-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075,
+ "output_cost_per_token":0.00000375,"cache_storage_cost_per_token_per_hour":0.0000005}}`))
+ require.NoError(t, err)
+ pricing.pricingData = data
+ return pricing
+ }
+ officialInput := inputTokens * inputPrice
+
+ for _, tc := range []struct {
+ name string
+ channel *Channel
+ tokens int
+ wantStats float64
+ }{
+ {name: "no_channel", tokens: inputTokens, wantStats: officialInput + storage},
+ {name: "model_file_pricing", channel: &Channel{ID: 1, Status: StatusActive}, tokens: inputTokens, wantStats: officialInput + storage},
+ {name: "apply_pricing_to_account_stats", channel: &Channel{ID: 1, Status: StatusActive, ApplyPricingToAccountStats: true},
+ tokens: inputTokens, wantStats: officialInput + storage},
+ {name: "custom_rule", channel: &Channel{ID: 1, Status: StatusActive, AccountStatsPricingRules: []AccountStatsPricingRule{{
+ GroupIDs: []int64{groupID},
+ Pricing: []ChannelModelPricing{{Models: []string{model}, InputPrice: testPtrFloat64(rulePrice)}},
+ }}}, tokens: inputTokens, wantStats: inputTokens*rulePrice + storage},
+ {name: "storage_only_with_custom_rule", channel: &Channel{ID: 1, Status: StatusActive, AccountStatsPricingRules: []AccountStatsPricingRule{{
+ GroupIDs: []int64{groupID},
+ Pricing: []ChannelModelPricing{{Models: []string{model}, InputPrice: testPtrFloat64(rulePrice)}},
+ }}}, wantStats: storage},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
+ svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{})
+ svc.billingService = NewBillingService(svc.cfg, newPricing())
+ if tc.channel != nil {
+ svc.channelService = newTestChannelServiceForStats(t, tc.channel, groupID, PlatformGemini)
+ }
+ groupRate, accountRate := 1.5, 0.6
+ gid := groupID
+ err := svc.RecordUsage(context.Background(), &RecordUsageInput{
+ Result: &ForwardResult{
+ RequestID: GeminiCachedContentCreateUsageRequestID(tc.name),
+ Model: model,
+ Usage: ClaudeUsage{InputTokens: tc.tokens},
+ CacheStorageTokenHours: storage / 0.0000005,
+ },
+ APIKey: &APIKey{ID: 811, GroupID: &gid, Group: &Group{ID: groupID, Platform: PlatformGemini, RateMultiplier: groupRate, Hydrated: true}},
+ User: &User{ID: 611},
+ Account: &Account{ID: 711, Platform: PlatformGemini, RateMultiplier: &accountRate},
+ })
+ require.NoError(t, err)
+ log := usageRepo.lastLog
+ require.NotNil(t, log)
+
+ wantTotal := float64(tc.tokens)*inputPrice + storage
+ require.InDelta(t, wantTotal, log.TotalCost, 1e-12)
+ require.InDelta(t, wantTotal*groupRate, log.ActualCost, 1e-12, "售价 = 官方价 × 分组倍率")
+
+ statsCost := log.TotalCost
+ if log.AccountStatsCost != nil {
+ statsCost = *log.AccountStatsCost
+ }
+ require.InDelta(t, tc.wantStats, statsCost, 1e-12, "账号统计成本须含存储费且只计一次")
+ require.NotNil(t, log.AccountRateMultiplier)
+ require.InDelta(t, tc.wantStats*accountRate, statsCost**log.AccountRateMultiplier, 1e-12, "成本 = 统计成本 × 账号倍率")
+ })
+ }
+}
+
+func TestGeminiExplicitCacheUpstreamTTL(t *testing.T) {
+ now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC)
+ upstream := &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "api_key": "k", "base_url": "https://relay.example.com", "explicit_cache_upstream": true,
+ "explicit_cache_upstream_max_ttl_seconds": float64(1800),
+ }}
+ official := &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "api_key": "k", "explicit_cache_upstream_max_ttl_seconds": float64(1800),
+ }}
+ require.Equal(t, 30*time.Minute, upstream.GeminiExplicitCacheUpstreamMaxTTL())
+ require.Zero(t, official.GeminiExplicitCacheUpstreamMaxTTL(), "未开启开关时上限字段不生效")
+
+ svc := NewGeminiCachedContentService(newGeminiCachedContentRepoStub(), nil, &config.Config{})
+ require.Equal(t, 30*time.Minute, svc.MaxTTLForAccount(upstream))
+ require.Equal(t, 24*time.Hour, svc.MaxTTLForAccount(official))
+
+ implicit, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash"}`), now, 24*time.Hour)
+ require.NoError(t, err)
+ ttl, ok := implicit.TTLForAccount(upstream)
+ require.True(t, ok)
+ require.Equal(t, 30*time.Minute, ttl, "未显式指定有效期时按上游上限创建")
+ ttl, ok = implicit.TTLForAccount(official)
+ require.True(t, ok)
+ require.Equal(t, time.Hour, ttl)
+
+ explicit, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","ttl":"3600s"}`), now, 24*time.Hour)
+ require.NoError(t, err)
+ _, ok = explicit.TTLForAccount(upstream)
+ require.False(t, ok, "显式有效期超过上游上限时该账号不可用")
+ ttl, ok = explicit.TTLForAccount(official)
+ require.True(t, ok)
+ require.Equal(t, time.Hour, ttl)
+}
+
+func TestGeminiCachedContentCreateUpstreamGateway(t *testing.T) {
+ svc, httpStub := newGeminiCachedContentServiceForTest(t, http.StatusOK,
+ `{"name":"cachedContents/gatewayid0001","model":"models/gemini-3.8-flash","usageMetadata":{"totalTokenCount":2730},"expireTime":"2026-10-09T09:00:00Z"}`)
+ account := &Account{ID: 11, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "api_key": "downstream-key", "base_url": "https://upstream.example.com/gw/", "explicit_cache_upstream": true,
+ }}
+ req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","contents":[{"role":"user","parts":[{"text":"doc"}]}]}`), time.Now(), 24*time.Hour)
+ require.NoError(t, err)
+
+ upstream, err := svc.CreateUpstream(context.Background(), account, req, "gemini-3.8-flash", "pub2", 30*time.Minute)
+ require.NoError(t, err)
+ require.Equal(t, "cachedContents/gatewayid0001", upstream.Name)
+ require.Equal(t, "https://upstream.example.com/gw/v1beta/cachedContents", httpStub.lastReq.URL.String())
+ require.Equal(t, "downstream-key", httpStub.lastReq.Header.Get("x-goog-api-key"))
+ raw, err := io.ReadAll(httpStub.lastReq.Body)
+ require.NoError(t, err)
+ require.Contains(t, string(raw), `"ttl":"1800s"`)
+
+ resource, err := geminiCachedContentResourceURL(account, geminiCachedContentAPIBase(account), upstream.Name)
+ require.NoError(t, err)
+ require.Equal(t, "https://upstream.example.com/gw/v1beta/cachedContents/gatewayid0001", resource)
+}
diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go
index bb2503623..46e016ec7 100644
--- a/backend/internal/service/gemini_chat_completions_compat_service.go
+++ b/backend/internal/service/gemini_chat_completions_compat_service.go
@@ -42,7 +42,16 @@ func (s *GeminiMessagesCompatService) ForwardAsChatCompletions(
clientStream := ccReq.Stream
includeUsage := ccReq.StreamOptions != nil && ccReq.StreamOptions.IncludeUsage
- responsesReq, err := apicompat.ChatCompletionsToResponses(&ccReq)
+ // 历史推理内容不回传给 Gemini:Gemini 的思考连续性由 thoughtSignature 承载。
+ for i := range ccReq.Messages {
+ ccReq.Messages[i].ReasoningContent = ""
+ ccReq.Messages[i].Reasoning = ""
+ if ccReq.Messages[i].Role == "assistant" {
+ ccReq.Messages[i].Content = dropChatReasoningContentParts(ccReq.Messages[i].Content)
+ }
+ }
+
+ responsesReq, err := chatCompletionsToResponses(s.cfg, &ccReq)
if err != nil {
return nil, s.writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
}
@@ -92,6 +101,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions(
return nil, s.writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
}
geminiReq = ensureGeminiFunctionCallThoughtSignatures(geminiReq)
+ geminiReq = applyGeminiCompatThinkingConfig(geminiReq, claudeBody, mappedModel, clientStream)
proxyURL := ""
if account.ProxyID != nil && account.Proxy != nil {
@@ -112,12 +122,17 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions(
)
var resp *http.Response
+ // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。
+ var checkedPolicy *ErrorPolicyResult
for attempt := 1; attempt <= geminiMaxRetries; attempt++ {
upstreamReq, idHeader, err := buildReq(ctx)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
+ if failoverErr := s.handleVertexServiceAccountNotFound(ctx, c, account, err); failoverErr != nil {
+ return nil, failoverErr
+ }
return nil, s.writeChatCompletionsError(c, http.StatusBadGateway, "upstream_error", err.Error())
}
requestIDHeader = idHeader
@@ -127,11 +142,11 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions(
return nil, s.handleUpstreamTransportError(ctx, c, account, err)
}
- if matched, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel); matched {
- resp = rebuilt
+ checked, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel)
+ resp = rebuilt
+ checkedPolicy = checked
+ if checked != nil && *checked != ErrorPolicyNone {
break
- } else {
- resp = rebuilt
}
if resp.StatusCode >= 400 && s.shouldRetryGeminiUpstreamError(account, resp.StatusCode) {
@@ -196,7 +211,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions(
respBody := s.readUpstreamErrorBody(resp)
policy := ErrorPolicyNone
if s.rateLimitService != nil {
- policy = s.rateLimitService.CheckErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel)
+ policy = s.finalErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel, checkedPolicy)
}
// 与 messages 兼容层一致:只有 None / Matched 才走账号状态处理。
// Skipped(池模式、或自定义错误码未命中)与 TempUnscheduled 已由策略层裁决完毕。
@@ -399,19 +414,11 @@ func (s *GeminiMessagesCompatService) buildGeminiChatCompletionsUpstreamRequestF
case AccountTypeServiceAccount:
return func(ctx context.Context) (*http.Request, string, error) {
- if s.tokenProvider == nil {
- return nil, "", errors.New("gemini token provider not configured")
- }
- accessToken, err := s.tokenProvider.GetAccessToken(ctx, account)
- if err != nil {
- return nil, "", err
- }
-
action := "generateContent"
if clientStream {
action = "streamGenerateContent"
}
- fullURL, err := buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(mappedModel), mappedModel, action, clientStream)
+ fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, action, clientStream)
if err != nil {
return nil, "", err
}
@@ -422,7 +429,9 @@ func (s *GeminiMessagesCompatService) buildGeminiChatCompletionsUpstreamRequestF
return nil, "", err
}
upstreamReq.Header.Set("Content-Type", "application/json")
- upstreamReq.Header.Set("Authorization", "Bearer "+accessToken)
+ if err := setVertexGeminiAuth(ctx, upstreamReq, account, s.tokenProvider); err != nil {
+ return nil, "", err
+ }
return upstreamReq, "x-request-id", nil
}, "x-request-id"
@@ -571,6 +580,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom
openBlockIndex := -1
openBlockType := ""
seenText := ""
+ seenThought := ""
openToolIndex := -1
openToolName := ""
seenToolJSON := ""
@@ -625,6 +635,41 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom
}
for _, part := range extractGeminiParts(geminiResp) {
+ if text, ok := part["text"].(string); ok && isGeminiThoughtPart(part) {
+ delta, newSeen := computeGeminiTextDelta(seenThought, text)
+ seenThought = newSeen
+ if delta == "" {
+ continue
+ }
+ if openToolIndex >= 0 {
+ if closeOpenTool() {
+ return &geminiStreamResult{usage: &usage, firstTokenMs: firstTokenMs}, nil
+ }
+ }
+ if openBlockType != "thinking" {
+ if closeOpenBlock() {
+ return &geminiStreamResult{usage: &usage, firstTokenMs: firstTokenMs}, nil
+ }
+ idx := nextBlockIndex
+ nextBlockIndex++
+ openBlockIndex = idx
+ openBlockType = "thinking"
+ if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{
+ Type: "content_block_start",
+ Index: &idx,
+ ContentBlock: &apicompat.AnthropicContentBlock{Type: "thinking"},
+ }) {
+ return &geminiStreamResult{usage: &usage, firstTokenMs: firstTokenMs}, nil
+ }
+ }
+ if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{
+ Type: "content_block_delta",
+ Delta: &apicompat.AnthropicDelta{Type: "thinking_delta", Thinking: delta},
+ }) {
+ return &geminiStreamResult{usage: &usage, firstTokenMs: firstTokenMs}, nil
+ }
+ continue
+ }
if text, ok := part["text"].(string); ok && text != "" {
if openToolIndex >= 0 {
if closeOpenTool() {
diff --git a/backend/internal/service/gemini_compat_thinking.go b/backend/internal/service/gemini_compat_thinking.go
new file mode 100644
index 000000000..6c75dd919
--- /dev/null
+++ b/backend/internal/service/gemini_compat_thinking.go
@@ -0,0 +1,320 @@
+package service
+
+import (
+ "bytes"
+ "encoding/json"
+ "strconv"
+ "strings"
+
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+// geminiThinkingParam 是上游模型接受的思考参数形态。
+type geminiThinkingParam int
+
+const (
+ geminiThinkingParamNone geminiThinkingParam = iota
+ geminiThinkingParamBudget
+ geminiThinkingParamLevel
+)
+
+const (
+ gemini25ProMaxThinkingBudget = 32768
+ gemini25ProMinThinkingBudget = 128
+ gemini25FlashMaxThinkingBudget = 24576
+ gemini25FlashLiteMinThinkingBudget = 512
+)
+
+// geminiThinkingParamForModel 按上游模型名判断思考参数形态:2.5 系列用 thinkingBudget,
+// 3 及以上用 thinkingLevel。2.5 之前的版本、无法解析版本号的名字、图像/语音/向量类模型
+// 不写思考参数。
+func geminiThinkingParamForModel(model string) geminiThinkingParam {
+ name := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(model)), "models/")
+ rest, ok := strings.CutPrefix(name, "gemini-")
+ if !ok {
+ return geminiThinkingParamNone
+ }
+ for _, kind := range []string{"image", "tts", "embedding", "live", "audio"} {
+ if strings.Contains(rest, kind) {
+ return geminiThinkingParamNone
+ }
+ }
+ version, _, _ := strings.Cut(rest, "-")
+ majorText, minorText, _ := strings.Cut(version, ".")
+ major, err := strconv.Atoi(majorText)
+ if err != nil {
+ return geminiThinkingParamNone
+ }
+ minor := 0
+ if minorText != "" {
+ if minor, err = strconv.Atoi(minorText); err != nil {
+ return geminiThinkingParamNone
+ }
+ }
+ switch {
+ case major >= 3:
+ return geminiThinkingParamLevel
+ case major == 2 && minor >= 5:
+ return geminiThinkingParamBudget
+ default:
+ return geminiThinkingParamNone
+ }
+}
+
+// geminiModelNameCarriesThinkingTier 判断模型名是否以档位后缀结尾(如 -low/-high),
+// 这类名字由上游按名字选档,不再叠加思考档位参数。
+func geminiModelNameCarriesThinkingTier(model string) bool {
+ name := strings.ToLower(strings.TrimSpace(model))
+ for _, suffix := range []string{"-minimal", "-low", "-medium", "-high", "-xhigh", "-max", "-tiered"} {
+ if strings.HasSuffix(name, suffix) {
+ return true
+ }
+ }
+ return false
+}
+
+// claudeThinkingIntent 是 Anthropic 请求体里与思考相关的意图。
+type claudeThinkingIntent struct {
+ thinkingType string // enabled / adaptive / disabled / 空
+ tier string // minimal / low / medium / high / 空
+ budgetTokens int // thinking.type=enabled 时的 budget_tokens
+}
+
+// parseClaudeThinkingIntent 读取 Anthropic 请求的思考参数。thinking.type=disabled 优先于
+// output_config.effort;effort 归一到 minimal/low/medium/high,未识别的取值视为未指定。
+func parseClaudeThinkingIntent(claudeBody []byte) claudeThinkingIntent {
+ intent := claudeThinkingIntent{
+ thinkingType: strings.ToLower(strings.TrimSpace(gjson.GetBytes(claudeBody, "thinking.type").String())),
+ }
+ if intent.thinkingType == "disabled" {
+ intent.tier = "minimal"
+ return intent
+ }
+ switch strings.ToLower(strings.TrimSpace(gjson.GetBytes(claudeBody, "output_config.effort").String())) {
+ case "none", "minimal":
+ intent.tier = "minimal"
+ case "low":
+ intent.tier = "low"
+ case "medium":
+ intent.tier = "medium"
+ case "high", "xhigh", "max":
+ intent.tier = "high"
+ }
+ if intent.thinkingType == "enabled" {
+ intent.budgetTokens = int(gjson.GetBytes(claudeBody, "thinking.budget_tokens").Int())
+ }
+ return intent
+}
+
+// claudeRequestEnablesThinking 判断 Anthropic 请求是否开启了思考输出。
+func claudeRequestEnablesThinking(claudeBody []byte) bool {
+ switch parseClaudeThinkingIntent(claudeBody).thinkingType {
+ case "enabled", "adaptive":
+ return true
+ default:
+ return false
+ }
+}
+
+// geminiThinkingLevelFor 把思考意图映射为 thinkingLevel;返回空串表示交给模型默认档位。
+// minimal 只发给 flash 系列,其余模型用 low;medium 只发给 flash 系列与 Gemini 3.1 Pro,
+// 其余模型用 high(Gemini 3 及以上未指定档位时的默认档位)。
+func geminiThinkingLevelFor(model string, intent claudeThinkingIntent) string {
+ tier := intent.tier
+ if tier == "" && intent.budgetTokens > 0 {
+ switch {
+ case intent.budgetTokens <= 1024:
+ tier = "low"
+ case intent.budgetTokens <= 8192:
+ tier = "medium"
+ default:
+ tier = "high"
+ }
+ }
+ name := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(model)), "models/")
+ isFlash := strings.Contains(name, "flash")
+ if tier == "minimal" && !isFlash {
+ tier = "low"
+ }
+ if tier == "medium" && !isFlash && !strings.HasPrefix(name, "gemini-3.1-pro") {
+ tier = "high"
+ }
+ return tier
+}
+
+// geminiThinkingBudgetFor 把思考意图映射为 Gemini 2.5 的 thinkingBudget;ok=false 表示交给
+// 模型动态预算。Pro 不能关闭思考(最小 128,最大 32768),Flash 为 0–24576,
+// Flash-Lite 的正预算最小 512。
+func geminiThinkingBudgetFor(model string, intent claudeThinkingIntent) (budget int, ok bool) {
+ name := strings.ToLower(model)
+ isPro := strings.Contains(name, "pro")
+ maxBudget, minPositive := gemini25FlashMaxThinkingBudget, 1
+ switch {
+ case isPro:
+ maxBudget, minPositive = gemini25ProMaxThinkingBudget, gemini25ProMinThinkingBudget
+ case strings.Contains(name, "flash-lite"):
+ minPositive = gemini25FlashLiteMinThinkingBudget
+ }
+ switch intent.tier {
+ case "minimal":
+ if isPro {
+ return gemini25ProMinThinkingBudget, true
+ }
+ return 0, true
+ case "low":
+ budget = 1024
+ case "medium":
+ budget = 8192
+ case "high":
+ budget = maxBudget
+ default:
+ if intent.budgetTokens <= 0 {
+ return 0, false
+ }
+ budget = intent.budgetTokens
+ }
+ budget = min(max(budget, minPositive), maxBudget)
+ return budget, true
+}
+
+// applyGeminiCompatThinkingConfig 把兼容入口(Anthropic 形态请求体)的思考意图写进转换后的
+// Gemini 请求 generationConfig.thinkingConfig。includeThoughts 为 true 时要求上游返回
+// 思考摘要(thought=true 的 part);思考被关闭(预算为 0)时不要求。
+func applyGeminiCompatThinkingConfig(geminiReq, claudeBody []byte, upstreamModel string, includeThoughts bool) []byte {
+ param := geminiThinkingParamForModel(upstreamModel)
+ if param == geminiThinkingParamNone {
+ return geminiReq
+ }
+ intent := parseClaudeThinkingIntent(claudeBody)
+ out := geminiReq
+ thinkingOff := false
+ if !geminiModelNameCarriesThinkingTier(upstreamModel) {
+ switch param {
+ case geminiThinkingParamLevel:
+ if level := geminiThinkingLevelFor(upstreamModel, intent); level != "" {
+ out = setGeminiThinkingField(out, "thinkingLevel", level)
+ }
+ case geminiThinkingParamBudget:
+ if budget, ok := geminiThinkingBudgetFor(upstreamModel, intent); ok {
+ out = setGeminiThinkingField(out, "thinkingBudget", budget)
+ thinkingOff = budget == 0
+ }
+ }
+ }
+ if includeThoughts && !thinkingOff {
+ out = setGeminiThinkingField(out, "includeThoughts", true)
+ }
+ return out
+}
+
+func setGeminiThinkingField(body []byte, field string, value any) []byte {
+ updated, err := sjson.SetBytes(body, "generationConfig.thinkingConfig."+field, value)
+ if err != nil {
+ return body
+ }
+ return updated
+}
+
+// isGeminiThoughtPart 判断响应 part 是否为思考摘要。
+func isGeminiThoughtPart(part map[string]any) bool {
+ thought, _ := part["thought"].(bool)
+ return thought
+}
+
+// dropClaudeHistoryThinkingBlocks 删除 Anthropic 请求历史消息里的 thinking/redacted_thinking 块,
+// 只含思考块的消息整条删除;与 convertClaudeMessagesToGeminiContents 的取舍一致,供签名降级
+// 重试在把思考块改写成正文之前使用。
+func dropClaudeHistoryThinkingBlocks(claudeBody []byte) []byte {
+ var req map[string]any
+ if err := json.Unmarshal(claudeBody, &req); err != nil {
+ return claudeBody
+ }
+ messages, ok := req["messages"].([]any)
+ if !ok {
+ return claudeBody
+ }
+ changed := false
+ kept := make([]any, 0, len(messages))
+ for _, m := range messages {
+ mm, ok := m.(map[string]any)
+ if !ok {
+ kept = append(kept, m)
+ continue
+ }
+ blocks, ok := mm["content"].([]any)
+ if !ok {
+ kept = append(kept, m)
+ continue
+ }
+ filtered := make([]any, 0, len(blocks))
+ for _, block := range blocks {
+ if bm, ok := block.(map[string]any); ok {
+ if bt, _ := bm["type"].(string); bt == "thinking" || bt == "redacted_thinking" {
+ continue
+ }
+ }
+ filtered = append(filtered, block)
+ }
+ if len(filtered) == len(blocks) {
+ kept = append(kept, m)
+ continue
+ }
+ // 原消息是多块,转换器会过滤空白正文块;删掉思考块后同样过滤,避免剩下的单块空白正文被原样发出。
+ nonBlank := filtered[:0]
+ for _, block := range filtered {
+ if bm, ok := block.(map[string]any); ok {
+ if bt, _ := bm["type"].(string); bt == "text" {
+ if text, _ := bm["text"].(string); strings.TrimSpace(text) == "" {
+ continue
+ }
+ }
+ }
+ nonBlank = append(nonBlank, block)
+ }
+ filtered = nonBlank
+ changed = true
+ if len(filtered) == 0 {
+ continue
+ }
+ mm["content"] = filtered
+ kept = append(kept, mm)
+ }
+ if !changed {
+ return claudeBody
+ }
+ req["messages"] = kept
+ out, err := json.Marshal(req)
+ if err != nil {
+ return claudeBody
+ }
+ return out
+}
+
+// dropChatReasoningContentParts 删除 Chat Completions assistant 消息 content 数组里
+// type 为 thinking/reasoning 的部分;字符串形态的 content 原样返回。
+func dropChatReasoningContentParts(content json.RawMessage) json.RawMessage {
+ if !bytes.HasPrefix(bytes.TrimSpace(content), []byte("[")) {
+ return content
+ }
+ var parts []json.RawMessage
+ if err := json.Unmarshal(content, &parts); err != nil {
+ return content
+ }
+ kept := make([]json.RawMessage, 0, len(parts))
+ for _, part := range parts {
+ switch gjson.GetBytes(part, "type").String() {
+ case "thinking", "reasoning":
+ continue
+ }
+ kept = append(kept, part)
+ }
+ if len(kept) == len(parts) {
+ return content
+ }
+ out, err := json.Marshal(kept)
+ if err != nil {
+ return content
+ }
+ return out
+}
diff --git a/backend/internal/service/gemini_compat_thinking_test.go b/backend/internal/service/gemini_compat_thinking_test.go
new file mode 100644
index 000000000..feea6f890
--- /dev/null
+++ b/backend/internal/service/gemini_compat_thinking_test.go
@@ -0,0 +1,367 @@
+package service
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+func TestApplyGeminiCompatThinkingConfig(t *testing.T) {
+ budget := func(v int64) *int64 { return &v }
+ const baseReq = `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"maxOutputTokens":8192}}`
+ tests := []struct {
+ name string
+ model string
+ claudeBody string
+ includeThoughts bool
+ wantLevel string
+ wantBudget *int64
+ wantThoughts bool
+ wantNoConfig bool
+ }{
+ {name: "effort medium on flash", model: "gemini-3.8-flash", claudeBody: `{"output_config":{"effort":"medium"},"thinking":{"type":"enabled","budget_tokens":4096}}`, wantLevel: "medium"},
+ {name: "effort low", model: "gemini-3.7-flash", claudeBody: `{"output_config":{"effort":"low"}}`, wantLevel: "low"},
+ {name: "effort none on flash", model: "gemini-3.8-flash", claudeBody: `{"output_config":{"effort":"none"},"thinking":{"type":"enabled","budget_tokens":10240}}`, wantLevel: "minimal"},
+ {name: "effort minimal on pro", model: "gemini-3.1-pro-preview", claudeBody: `{"output_config":{"effort":"minimal"}}`, wantLevel: "low"},
+ {name: "effort medium on gemini 3 pro", model: "gemini-3-pro-preview", claudeBody: `{"output_config":{"effort":"medium"}}`, wantLevel: "high"},
+ {name: "effort medium on gemini 3.1 pro", model: "gemini-3.1-pro-preview", claudeBody: `{"output_config":{"effort":"medium"}}`, wantLevel: "medium"},
+ {name: "effort max", model: "gemini-3.7-flash", claudeBody: `{"output_config":{"effort":"max"}}`, wantLevel: "high"},
+ {name: "effort xhigh", model: "gemini-3.7-flash", claudeBody: `{"output_config":{"effort":"xhigh"}}`, wantLevel: "high"},
+ {name: "thinking disabled wins over effort", model: "gemini-3.8-flash", claudeBody: `{"thinking":{"type":"disabled"},"output_config":{"effort":"high"}}`, wantLevel: "minimal"},
+ {name: "budget only maps to high", model: "gemini-3.8-flash", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":31999}}`, wantLevel: "high"},
+ {name: "budget only maps to medium", model: "gemini-3.8-flash", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":4096}}`, wantLevel: "medium"},
+ {name: "budget only maps to low", model: "gemini-3.8-flash", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":1024}}`, wantLevel: "low"},
+ {name: "adaptive keeps default level", model: "gemini-3.7-flash", claudeBody: `{"thinking":{"type":"adaptive"}}`, includeThoughts: true, wantThoughts: true},
+ {name: "no thinking params streams thoughts only", model: "gemini-3.7-flash", claudeBody: `{}`, includeThoughts: true, wantThoughts: true},
+ {name: "unknown effort ignored", model: "gemini-3.7-flash", claudeBody: `{"output_config":{"effort":"turbo"}}`, wantNoConfig: true},
+ {name: "level with thoughts", model: "gemini-3.8-flash", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantLevel: "high", wantThoughts: true},
+ {name: "gemini 4 uses level", model: "gemini-4-argon", claudeBody: `{"output_config":{"effort":"low"}}`, wantLevel: "low"},
+ {name: "medium outside verified models becomes high", model: "gemini-4-argon", claudeBody: `{"output_config":{"effort":"medium"}}`, wantLevel: "high"},
+ {name: "medium budget outside verified models becomes high", model: "gemini-4-argon", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":4096}}`, wantLevel: "high"},
+ {name: "medium on unverified pro becomes high", model: "gemini-3.5-pro", claudeBody: `{"output_config":{"effort":"medium"}}`, wantLevel: "high"},
+ {name: "medium on flash lite", model: "gemini-3.1-flash-lite", claudeBody: `{"output_config":{"effort":"medium"}}`, wantLevel: "medium"},
+ {name: "tier suffix model keeps name tier", model: "gemini-4-argon-high", claudeBody: `{"output_config":{"effort":"low"}}`, includeThoughts: true, wantThoughts: true},
+ {name: "tiered suffix model keeps name tier", model: "gemini-3.8-flash-tiered", claudeBody: `{"output_config":{"effort":"low"}}`, includeThoughts: true, wantThoughts: true},
+ {name: "2.5 flash low", model: "gemini-2.5-flash", claudeBody: `{"output_config":{"effort":"low"}}`, wantBudget: budget(1024)},
+ {name: "2.5 flash high", model: "gemini-2.5-flash", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantBudget: budget(24576), wantThoughts: true},
+ {name: "2.5 flash none disables thinking and thoughts", model: "gemini-2.5-flash", claudeBody: `{"output_config":{"effort":"none"}}`, includeThoughts: true, wantBudget: budget(0)},
+ {name: "2.5 pro cannot disable thinking", model: "gemini-2.5-pro", claudeBody: `{"thinking":{"type":"disabled"}}`, includeThoughts: true, wantBudget: budget(128), wantThoughts: true},
+ {name: "2.5 pro high", model: "gemini-2.5-pro", claudeBody: `{"output_config":{"effort":"max"}}`, wantBudget: budget(32768)},
+ {name: "2.5 pro budget clamps up", model: "gemini-2.5-pro", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":50}}`, wantBudget: budget(128)},
+ {name: "2.5 flash budget clamps down", model: "gemini-2.5-flash", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":31999}}`, wantBudget: budget(24576)},
+ {name: "2.5 flash lite budget clamps up", model: "gemini-2.5-flash-lite", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":100}}`, wantBudget: budget(512)},
+ {name: "2.5 adaptive keeps dynamic budget", model: "gemini-2.5-flash", claudeBody: `{"thinking":{"type":"adaptive"}}`, wantNoConfig: true},
+ {name: "2.0 untouched", model: "gemini-2.0-flash", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantNoConfig: true},
+ {name: "image model untouched", model: "gemini-3-pro-image-preview", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantNoConfig: true},
+ {name: "unparsable model untouched", model: "gemini-flash-latest", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantNoConfig: true},
+ {name: "non gemini model untouched", model: "custom-model", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantNoConfig: true},
+ {name: "models prefix", model: "models/gemini-3.8-flash", claudeBody: `{"output_config":{"effort":"low"}}`, wantLevel: "low"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ out := applyGeminiCompatThinkingConfig([]byte(baseReq), []byte(tt.claudeBody), tt.model, tt.includeThoughts)
+ require.Equal(t, int64(8192), gjson.GetBytes(out, "generationConfig.maxOutputTokens").Int())
+ require.Equal(t, "hi", gjson.GetBytes(out, "contents.0.parts.0.text").String())
+ cfg := gjson.GetBytes(out, "generationConfig.thinkingConfig")
+ if tt.wantNoConfig {
+ require.False(t, cfg.Exists(), cfg.Raw)
+ return
+ }
+ require.Equal(t, tt.wantLevel, cfg.Get("thinkingLevel").String())
+ if tt.wantBudget != nil {
+ require.True(t, cfg.Get("thinkingBudget").Exists(), cfg.Raw)
+ require.Equal(t, *tt.wantBudget, cfg.Get("thinkingBudget").Int())
+ } else {
+ require.False(t, cfg.Get("thinkingBudget").Exists(), cfg.Raw)
+ }
+ require.Equal(t, tt.wantThoughts, cfg.Get("includeThoughts").Bool(), cfg.Raw)
+ require.False(t, cfg.Get("thinkingLevel").Exists() && cfg.Get("thinkingBudget").Exists(), "thinkingLevel and thinkingBudget are mutually exclusive")
+ })
+ }
+}
+
+func geminiCompatThinkingTestAccount() *Account {
+ return &Account{
+ ID: 611,
+ Platform: PlatformGemini,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{"api_key": "gemini-api-key"},
+ Concurrency: 1,
+ }
+}
+
+func TestGeminiForwardAsChatCompletions_StreamsThoughtsAsReasoningContent(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ upstreamBody := `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"Weighing options","thought":true}]}}]}` + "\n\n" +
+ `data: {"candidates":[{"content":{"role":"model","parts":[{"text":" carefully.","thought":true}]}}]}` + "\n\n" +
+ `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"Final answer","thoughtSignature":"sig"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":4,"candidatesTokenCount":2,"thoughtsTokenCount":7}}` + "\n\n"
+ upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(upstreamBody)),
+ }}}
+ svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}}
+ body := []byte(`{"model":"gemini-3.8-flash","stream":true,"reasoning_effort":"medium","messages":[{"role":"user","content":"hi"}]}`)
+ c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body)
+
+ result, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiCompatThinkingTestAccount(), body)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, recorder.Code)
+ require.Len(t, upstream.requestBodies, 1)
+ require.Equal(t, "medium", gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig.thinkingLevel").String())
+ require.True(t, gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig.includeThoughts").Bool())
+ require.Equal(t, "medium", optionalStringValue(result.ReasoningEffort))
+ require.Equal(t, 9, result.Usage.OutputTokens)
+
+ var reasoning, content strings.Builder
+ firstContentChunk, lastReasoningChunk := -1, -1
+ for i, line := range strings.Split(recorder.Body.String(), "\n") {
+ payload, ok := strings.CutPrefix(line, "data: ")
+ if !ok || payload == "[DONE]" {
+ continue
+ }
+ delta := gjson.Get(payload, "choices.0.delta")
+ if r := delta.Get("reasoning_content"); r.Exists() {
+ _, _ = reasoning.WriteString(r.String())
+ lastReasoningChunk = i
+ }
+ if text := delta.Get("content"); text.Exists() && text.String() != "" {
+ _, _ = content.WriteString(text.String())
+ if firstContentChunk < 0 {
+ firstContentChunk = i
+ }
+ }
+ }
+ require.Equal(t, "Weighing options carefully.", reasoning.String())
+ require.Equal(t, "Final answer", content.String())
+ require.Less(t, lastReasoningChunk, firstContentChunk)
+}
+
+func TestGeminiForwardAsChatCompletions_NonStreamForwardsEffortWithoutThoughts(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(`{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1}}`)),
+ }}}
+ svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}}
+ body := []byte(`{"model":"gemini-3.8-flash","reasoning_effort":"none","messages":[{"role":"user","content":"hi"}]}`)
+ c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body)
+
+ result, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiCompatThinkingTestAccount(), body)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, recorder.Code)
+ require.Len(t, upstream.requestBodies, 1)
+ cfg := gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig")
+ require.Equal(t, "minimal", cfg.Get("thinkingLevel").String())
+ require.False(t, cfg.Get("includeThoughts").Exists(), cfg.Raw)
+ require.Equal(t, "minimal", optionalStringValue(result.ReasoningEffort))
+ require.Equal(t, "ok", gjson.Get(recorder.Body.String(), "choices.0.message.content").String())
+}
+
+func TestGeminiMessagesForward_IncludeThoughtsFollowsClientThinking(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ tests := []struct {
+ name string
+ body string
+ wantThoughts bool
+ wantLevel string
+ }{
+ {name: "stream with adaptive thinking", body: `{"model":"gemini-3.7-flash","stream":true,"max_tokens":1024,"thinking":{"type":"adaptive"},"output_config":{"effort":"medium"},"messages":[{"role":"user","content":"hi"}]}`, wantThoughts: true, wantLevel: "medium"},
+ {name: "stream without thinking", body: `{"model":"gemini-3.7-flash","stream":true,"max_tokens":1024,"messages":[{"role":"user","content":"hi"}]}`},
+ {name: "non stream with thinking", body: `{"model":"gemini-3.7-flash","max_tokens":1024,"thinking":{"type":"enabled","budget_tokens":31999},"messages":[{"role":"user","content":"hi"}]}`, wantLevel: "high"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ stream := gjson.Get(tt.body, "stream").Bool()
+ respBody := `{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1}}`
+ contentType := "application/json"
+ if stream {
+ respBody = "data: " + respBody + "\n\n"
+ contentType = "text/event-stream"
+ }
+ upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{contentType}},
+ Body: io.NopCloser(strings.NewReader(respBody)),
+ }}}
+ svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}}
+ c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/messages", []byte(tt.body))
+
+ result, err := svc.Forward(context.Background(), c, geminiCompatThinkingTestAccount(), []byte(tt.body))
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, recorder.Code)
+ require.Len(t, upstream.requestBodies, 1)
+ cfg := gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig")
+ require.Equal(t, tt.wantThoughts, cfg.Get("includeThoughts").Bool(), cfg.Raw)
+ require.Equal(t, tt.wantLevel, cfg.Get("thinkingLevel").String(), cfg.Raw)
+ require.Equal(t, tt.wantLevel, optionalStringValue(result.ReasoningEffort))
+ })
+ }
+}
+
+func TestGeminiMessagesHandleStreamingResponse_EmitsThinkingBlockBeforeText(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ upstreamBody := `data: {"candidates":[{"content":{"parts":[{"text":"Plan the reply","thought":true}]}}]}` + "\n\n" +
+ `data: {"candidates":[{"content":{"parts":[{"text":"Hello"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":1,"thoughtsTokenCount":4}}` + "\n\n"
+ resp := &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(upstreamBody)),
+ }
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ svc := &GeminiMessagesCompatService{}
+
+ result, err := svc.handleStreamingResponse(c, resp, time.Now(), "claude-sonnet-4-5")
+ require.NoError(t, err)
+ require.NotNil(t, result.firstTokenMs)
+
+ events := parseAnthropicContentBlockEvents(t, rec.Body.String())
+ open := -1
+ var started []string
+ for _, ev := range events {
+ switch ev.event {
+ case "content_block_start":
+ require.Equalf(t, -1, open, "block %d opened while block %d was still open", ev.index, open)
+ open = ev.index
+ started = append(started, ev.blockType)
+ case "content_block_stop":
+ require.Equal(t, open, ev.index)
+ open = -1
+ }
+ }
+ require.Equal(t, -1, open)
+ require.Equal(t, []string{"thinking", "text"}, started)
+
+ out := rec.Body.String()
+ require.Contains(t, out, `"content_block":{"signature":"","thinking":"","type":"thinking"}`)
+ require.Contains(t, out, `"type":"thinking_delta"`)
+ require.Contains(t, out, `"thinking":"Plan the reply"`)
+ require.NotContains(t, out, `"text":"Plan the reply"`)
+}
+
+func TestConvertClaudeMessagesToGemini_DropsHistoryThinkingBlocks(t *testing.T) {
+ body := []byte(`{"model":"gemini-3.7-flash","max_tokens":1024,"messages":[
+ {"role":"user","content":"hi"},
+ {"role":"assistant","content":[{"type":"thinking","thinking":"PRIOR_THOUGHT","signature":""},{"type":"text","text":"Hello"}]},
+ {"role":"user","content":"again"},
+ {"role":"assistant","content":[{"type":"thinking","thinking":"ONLY_THOUGHT","signature":""},{"type":"redacted_thinking","data":"opaque"}]},
+ {"role":"user","content":"last"}
+ ]}`)
+ out, err := convertClaudeMessagesToGeminiGenerateContent(body)
+ require.NoError(t, err)
+ require.NotContains(t, string(out), "PRIOR_THOUGHT")
+ require.NotContains(t, string(out), "ONLY_THOUGHT")
+ require.NotContains(t, string(out), "opaque")
+
+ contents := gjson.GetBytes(out, "contents").Array()
+ require.Len(t, contents, 4)
+ require.Equal(t, "model", contents[1].Get("role").String())
+ require.Len(t, contents[1].Get("parts").Array(), 1)
+ require.Equal(t, "Hello", contents[1].Get("parts.0.text").String())
+ for i, content := range contents {
+ require.NotEmpty(t, content.Get("parts").Array(), "contents[%d] has empty parts", i)
+ }
+}
+
+func TestGeminiForwardAsChatCompletions_DropsHistoryReasoningContent(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(`{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1}}`)),
+ }}}
+ svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}}
+ body := []byte(`{"model":"gemini-3.8-flash","messages":[
+ {"role":"user","content":"hi"},
+ {"role":"assistant","content":"Hello","reasoning_content":"PRIOR_REASONING"},
+ {"role":"assistant","content":"Again","reasoning":"ALIAS_REASONING"},
+ {"role":"assistant","content":[{"type":"thinking","thinking":"PART_THINKING"},{"type":"reasoning","text":"PART_REASONING"},{"type":"text","text":"Third"}]},
+ {"role":"user","content":"next"}
+ ]}`)
+ c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body)
+
+ _, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiCompatThinkingTestAccount(), body)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, recorder.Code)
+ require.Len(t, upstream.requestBodies, 1)
+ sent := string(upstream.requestBodies[0])
+ require.NotContains(t, sent, "PRIOR_REASONING")
+ require.NotContains(t, sent, "ALIAS_REASONING")
+ require.NotContains(t, sent, "PART_THINKING")
+ require.NotContains(t, sent, "PART_REASONING")
+ require.NotContains(t, sent, "")
+ require.Contains(t, sent, "Third")
+ require.Contains(t, sent, "Hello")
+ require.Contains(t, sent, "Again")
+}
+
+func TestGeminiMessagesForward_SignatureRetryKeepsClientThinkingParams(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ okBody := "data: " + `{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1}}` + "\n\n"
+ upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{
+ {
+ StatusCode: http.StatusBadRequest,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(`{"error":{"code":400,"message":"Function call is missing a thought_signature","status":"INVALID_ARGUMENT"}}`)),
+ },
+ {
+ StatusCode: http.StatusBadRequest,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(`{"error":{"code":400,"message":"Function call is missing a thought_signature","status":"INVALID_ARGUMENT"}}`)),
+ },
+ {
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(okBody)),
+ },
+ }}
+ svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}}
+ body := []byte(`{"model":"claude-sonnet-4-5","stream":true,"max_tokens":1024,"thinking":{"type":"adaptive"},"output_config":{"effort":"low"},"messages":[
+ {"role":"user","content":"hi"},
+ {"role":"assistant","content":[{"type":"thinking","thinking":"RETRY_THOUGHT","signature":""},{"type":"tool_use","id":"toolu_1","name":"lookup","input":{"q":"x"}}]},
+ {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"found"}]},
+ {"role":"assistant","content":[{"type":"thinking","thinking":"RETRY_ONLY_THOUGHT","signature":""}]},
+ {"role":"user","content":"next"},
+ {"role":"assistant","content":[{"type":"thinking","thinking":"RETRY_BLANK_THOUGHT","signature":""},{"type":"text","text":""}]},
+ {"role":"user","content":"again"},
+ {"role":"assistant","content":[{"type":"thinking","thinking":"RETRY_SPACE_THOUGHT","signature":""},{"type":"text","text":" "}]},
+ {"role":"user","content":"last"}
+ ]}`)
+ account := geminiCompatThinkingTestAccount()
+ account.Credentials["model_mapping"] = map[string]any{"claude-sonnet-4-5": "gemini-3.8-flash"}
+ c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/messages", body)
+
+ result, err := svc.Forward(context.Background(), c, account, body)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, recorder.Code)
+ require.Len(t, upstream.requestBodies, 3)
+ for i, sent := range upstream.requestBodies {
+ require.NotContains(t, string(sent), "RETRY_THOUGHT", "request %d", i)
+ require.NotContains(t, string(sent), "RETRY_ONLY_THOUGHT", "request %d", i)
+ require.NotContains(t, string(sent), "RETRY_BLANK_THOUGHT", "request %d", i)
+ require.NotContains(t, string(sent), "RETRY_SPACE_THOUGHT", "request %d", i)
+ for j, content := range gjson.GetBytes(sent, "contents").Array() {
+ require.NotEmpty(t, content.Get("parts").Array(), "request %d contents[%d] has empty parts", i, j)
+ for k, part := range content.Get("parts").Array() {
+ if text := part.Get("text"); text.Exists() {
+ require.NotEmpty(t, strings.TrimSpace(text.String()), "request %d contents[%d].parts[%d] is blank text", i, j, k)
+ }
+ }
+ }
+ cfg := gjson.GetBytes(sent, "generationConfig.thinkingConfig")
+ require.Equal(t, "low", cfg.Get("thinkingLevel").String(), "request %d: %s", i, cfg.Raw)
+ require.True(t, cfg.Get("includeThoughts").Bool(), "request %d: %s", i, cfg.Raw)
+ }
+ require.Equal(t, "low", optionalStringValue(result.ReasoningEffort))
+}
diff --git a/backend/internal/service/gemini_error_policy_single_check_test.go b/backend/internal/service/gemini_error_policy_single_check_test.go
new file mode 100644
index 000000000..bcb12e299
--- /dev/null
+++ b/backend/internal/service/gemini_error_policy_single_check_test.go
@@ -0,0 +1,201 @@
+//go:build unit
+
+package service
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/pkg/tlsfingerprint"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+// ---------------------------------------------------------------------------
+// Gemini 三条转发路径对每个上游错误响应只检查一次错误策略:
+// - 重试循环内已检查的最终响应,循环外的错误处理复用该结果;
+// - 账号级 401 规则首次命中只临时不可调度,账号上已有 401 暂停记录时才升级为 error;
+// - 循环内未检查的最终响应(如 Claude 兼容层的非签名 400)在循环外检查。
+// ---------------------------------------------------------------------------
+
+type geminiSingleCheckRepoStub struct {
+ errorPolicyRepoStub
+ tempReason string
+}
+
+func (r *geminiSingleCheckRepoStub) SetTempUnschedulable(_ context.Context, _ int64, _ time.Time, reason string) error {
+ r.tempCalls++
+ r.tempReason = reason
+ return nil
+}
+
+func (r *geminiSingleCheckRepoStub) GetByID(_ context.Context, id int64) (*Account, error) {
+ return &Account{ID: id, TempUnschedulableReason: r.tempReason}, nil
+}
+
+type geminiSequenceUpstreamResponse struct {
+ status int
+ body string
+}
+
+type geminiSequenceUpstreamStub struct {
+ responses []geminiSequenceUpstreamResponse
+ calls int
+}
+
+func (s *geminiSequenceUpstreamStub) Do(*http.Request, string, int64, int) (*http.Response, error) {
+ r := s.responses[min(s.calls, len(s.responses)-1)]
+ s.calls++
+ return &http.Response{
+ StatusCode: r.status,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(r.body)),
+ }, nil
+}
+
+func (s *geminiSequenceUpstreamStub) DoWithTLS(req *http.Request, proxyURL string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
+ return s.Do(req, proxyURL, accountID, concurrency)
+}
+
+func newGeminiSingleCheckService(responses ...geminiSequenceUpstreamResponse) (*GeminiMessagesCompatService, *geminiSequenceUpstreamStub, *geminiSingleCheckRepoStub) {
+ repo := &geminiSingleCheckRepoStub{}
+ rateLimit := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ upstream := &geminiSequenceUpstreamStub{responses: responses}
+ svc := &GeminiMessagesCompatService{
+ accountRepo: repo,
+ httpUpstream: upstream,
+ rateLimitService: rateLimit,
+ cfg: &config.Config{},
+ }
+ return svc, upstream, repo
+}
+
+func geminiAPIKeyAccountWithTempRule(rule map[string]any) *Account {
+ return &Account{
+ ID: 830,
+ Platform: PlatformGemini,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "api_key": "test-key",
+ "temp_unschedulable_enabled": true,
+ "temp_unschedulable_rules": []any{rule},
+ },
+ }
+}
+
+const geminiSingleCheck401Body = `{"error":{"code":401,"message":"API key expired. Please renew the API key.","status":"UNAUTHENTICATED"}}`
+
+func geminiAccountScoped401Rule() map[string]any {
+ return map[string]any{
+ "error_code": float64(401),
+ "keywords": []any{"expired"},
+ "duration_minutes": float64(30),
+ "scope": TempUnschedScopeAccount,
+ }
+}
+
+// geminiSingleCheckForwarders 以三条转发路径各发一次请求,返回转发错误与 gin.Context。
+var geminiSingleCheckForwarders = []struct {
+ name string
+ forward func(t *testing.T, svc *GeminiMessagesCompatService, account *Account) (error, *gin.Context)
+}{
+ {
+ name: "native",
+ forward: func(t *testing.T, svc *GeminiMessagesCompatService, account *Account) (error, *gin.Context) {
+ c, _ := newGeminiNativeTestContext(t)
+ _, err := svc.ForwardNative(context.Background(), c, account, "gemini-2.5-flash", "generateContent", false,
+ []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`))
+ return err, c
+ },
+ },
+ {
+ name: "claude_compat",
+ forward: func(t *testing.T, svc *GeminiMessagesCompatService, account *Account) (error, *gin.Context) {
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ body := []byte(`{"model":"gemini-2.5-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body))
+ _, err := svc.Forward(context.Background(), c, account, body)
+ return err, c
+ },
+ },
+ {
+ name: "chat_completions_compat",
+ forward: func(t *testing.T, svc *GeminiMessagesCompatService, account *Account) (error, *gin.Context) {
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ body := []byte(`{"model":"gemini-2.5-flash","messages":[{"role":"user","content":"hi"}]}`)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
+ _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body)
+ return err, c
+ },
+ },
+}
+
+func TestGeminiForward_First401RuleHitOnlyTempUnschedules(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, fw := range geminiSingleCheckForwarders {
+ t.Run(fw.name, func(t *testing.T) {
+ svc, upstream, repo := newGeminiSingleCheckService(geminiSequenceUpstreamResponse{status: http.StatusUnauthorized, body: geminiSingleCheck401Body})
+
+ err, _ := fw.forward(t, svc, geminiAPIKeyAccountWithTempRule(geminiAccountScoped401Rule()))
+
+ var failoverErr *UpstreamFailoverError
+ require.True(t, errors.As(err, &failoverErr), "规则命中应换号,got %T: %v", err, err)
+ require.Equal(t, http.StatusUnauthorized, failoverErr.StatusCode)
+ require.Equal(t, 1, upstream.calls)
+ require.Equal(t, 1, repo.tempCalls, "首次 401 命中规则应临时不可调度")
+ require.Zero(t, repo.setErrCalls, "首次 401 命中规则不应升级为 error")
+ })
+ }
+}
+
+func TestGeminiForward_Repeated401RuleHitEscalatesToError(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, fw := range geminiSingleCheckForwarders {
+ t.Run(fw.name, func(t *testing.T) {
+ svc, _, repo := newGeminiSingleCheckService(geminiSequenceUpstreamResponse{status: http.StatusUnauthorized, body: geminiSingleCheck401Body})
+ repo.tempReason = `{"until_unix":1,"triggered_at_unix":1,"status_code":401,"matched_keyword":"expired","rule_index":0,"scope":"account"}`
+
+ _, _ = fw.forward(t, svc, geminiAPIKeyAccountWithTempRule(geminiAccountScoped401Rule()))
+
+ require.Zero(t, repo.tempCalls, "已有 401 暂停记录时直接升级,不临时不可调度")
+ require.Equal(t, 1, repo.setErrCalls, "已有 401 暂停记录时应升级为 error")
+ require.Contains(t, repo.lastErrorMsg, "Authentication failed (401)")
+ })
+ }
+}
+
+func TestGeminiForward_UncheckedFinalResponseIsCheckedAfterLoop(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ if testing.Short() {
+ t.Skip("包含一次 1s 的重试退避")
+ }
+ // 第一次 503 在循环内检查后重试;第二次非签名 400 走 Claude 兼容层的签名分支,循环内不检查。
+ svc, upstream, repo := newGeminiSingleCheckService(
+ geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: `{"error":{"code":503,"message":"backend busy","status":"UNAVAILABLE"}}`},
+ geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: `{"error":{"code":400,"message":"quota project misconfigured","status":"FAILED_PRECONDITION"}}`},
+ )
+ account := geminiAPIKeyAccountWithTempRule(map[string]any{
+ "error_code": float64(400),
+ "keywords": []any{"misconfigured"},
+ "duration_minutes": float64(30),
+ "scope": TempUnschedScopeAccount,
+ })
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ body := []byte(`{"model":"gemini-2.5-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body))
+
+ _, err := svc.Forward(context.Background(), c, account, body)
+
+ var failoverErr *UpstreamFailoverError
+ require.True(t, errors.As(err, &failoverErr), "400 规则命中应换号,got %T: %v", err, err)
+ require.Equal(t, 2, upstream.calls)
+ require.Equal(t, 1, repo.tempCalls, "循环内未检查的最终响应应在循环外检查")
+}
diff --git a/backend/internal/service/gemini_error_policy_test.go b/backend/internal/service/gemini_error_policy_test.go
index 73ae096b8..12f4f7d73 100644
--- a/backend/internal/service/gemini_error_policy_test.go
+++ b/backend/internal/service/gemini_error_policy_test.go
@@ -631,30 +631,159 @@ func TestHandleGeminiUpstreamError_VertexRetryInfoUsesParsedDelay(t *testing.T)
require.WithinDuration(t, before.Add(39*time.Second), repo.lastRateLimitReset, 2*time.Second)
}
-// Vertex(service_account)429 响应不带任何可解析的重置时间时,走短冷却兜底,
-// 不再冷却到 PST 午夜(按量付费没有每日配额,长冷却会导致整组不可用)。
-func TestHandleGeminiUpstreamError_VertexFallbackUsesShortCooldown(t *testing.T) {
+// Vertex(service_account)共享容量不足的 429 不写账号级限流:账号保持可调度,
+// 由请求内的同号退避重试与换号消化。
+func TestHandleGeminiUpstreamError_VertexSharedCapacityKeepsAccountSchedulable(t *testing.T) {
+ tests := []struct {
+ name string
+ body string
+ }{
+ {
+ name: "object",
+ body: `{"error":{"code":429,"message":"Resource exhausted. Please try again later. Please refer to https://cloud.google.com/vertex-ai/generative-ai/docs/error-code-429 for more details.","status":"RESOURCE_EXHAUSTED"}}`,
+ },
+ {
+ name: "array_wrapped",
+ body: `[{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}]`,
+ },
+ {
+ name: "empty_details",
+ body: `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED","details":[]}}`,
+ },
+ {
+ name: "documented_comma_wording",
+ body: `{"error":{"code":429,"message":"Resource exhausted, please try again later.","status":"RESOURCE_EXHAUSTED"}}`,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ repo := &rateLimit429AccountRepoStub{}
+ svc := &GeminiMessagesCompatService{accountRepo: repo}
+ account := &Account{
+ ID: 602,
+ Platform: PlatformGemini,
+ Type: AccountTypeServiceAccount,
+ Credentials: map[string]any{
+ "project_id": "my-vertex-project",
+ },
+ }
+
+ svc.handleGeminiUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{}, []byte(tt.body))
+
+ require.Zero(t, repo.rateLimitCalls)
+ })
+ }
+}
+
+// Vertex(service_account)项目配额、预留吞吐等账号自身的 429 不带可解析的重置时间时,
+// 走短冷却兜底,不冷却到 PST 午夜(按量付费没有每日配额,长冷却会导致整组不可用)。
+func TestHandleGeminiUpstreamError_VertexAccountScoped429UsesShortCooldown(t *testing.T) {
+ tests := []struct {
+ name string
+ body string
+ }{
+ {
+ name: "project_quota",
+ body: `{"error":{"code":429,"message":"Quota exceeded for aiplatform.googleapis.com/generate_content_requests_per_minute_per_project_per_base_model with base model: gemini-2.5-pro. Please submit a quota increase request.","status":"RESOURCE_EXHAUSTED"}}`,
+ },
+ {
+ name: "provisioned_throughput",
+ body: `{"error":{"code":429,"message":"Too many requests. Exceeded the Provisioned Throughput.","status":"RESOURCE_EXHAUSTED"}}`,
+ },
+ {
+ name: "quota_failure_details",
+ body: `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.QuotaFailure","violations":[{"subject":"project"}]}]}}`,
+ },
+ {
+ name: "other_status",
+ body: `{"error":{"code":429,"message":"Too many requests.","status":"UNAVAILABLE"}}`,
+ },
+ {
+ name: "unknown_wording",
+ body: `{"error":{"code":429,"message":"Rate limit exceeded for requests per minute per project.","status":"RESOURCE_EXHAUSTED"}}`,
+ },
+ {
+ name: "missing_message",
+ body: `{"error":{"code":429,"status":"RESOURCE_EXHAUSTED"}}`,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ repo := &rateLimit429AccountRepoStub{}
+ svc := &GeminiMessagesCompatService{accountRepo: repo}
+ account := &Account{
+ ID: 604,
+ Platform: PlatformGemini,
+ Type: AccountTypeServiceAccount,
+ Credentials: map[string]any{
+ "project_id": "my-vertex-project",
+ },
+ }
+
+ before := time.Now()
+ svc.handleGeminiUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{}, []byte(tt.body))
+
+ require.Equal(t, 1, repo.rateLimitCalls)
+ require.Equal(t, int64(604), repo.lastRateLimitID)
+ require.WithinDuration(t, before.Add(geminiVertexFallbackCooldown), repo.lastRateLimitReset, 2*time.Second)
+ // 显式守护:不应被冷却超过 15 分钟(更不应到次日 PST 午夜)
+ require.True(t, repo.lastRateLimitReset.Before(before.Add(15*time.Minute)))
+ })
+ }
+}
+
+// Vertex 共享容量形态的 429 只对 Vertex 账号豁免冷却:AI Studio 官方 API Key 与 Code Assist OAuth
+// 收到同样的响应体仍按各自语义冷却。
+func TestHandleGeminiUpstreamError_SharedCapacityBodyStillCoolsNonVertexAccounts(t *testing.T) {
+ body := []byte(`{"error":{"code":429,"message":"Resource exhausted. Please try again later. Please refer to https://cloud.google.com/vertex-ai/generative-ai/docs/error-code-429 for more details.","status":"RESOURCE_EXHAUSTED"}}`)
+ tests := []struct {
+ name string
+ account *Account
+ }{
+ {
+ name: "ai_studio_api_key",
+ account: &Account{ID: 605, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k"}},
+ },
+ {
+ name: "code_assist_oauth",
+ account: &Account{ID: 606, Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{
+ "oauth_type": "code_assist", "project_id": "my-code-assist-project",
+ }},
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ repo := &rateLimit429AccountRepoStub{}
+ svc := &GeminiMessagesCompatService{accountRepo: repo}
+
+ svc.handleGeminiUpstreamError(context.Background(), tt.account, http.StatusTooManyRequests, http.Header{}, body)
+
+ require.Equal(t, 1, repo.rateLimitCalls)
+ require.Equal(t, tt.account.ID, repo.lastRateLimitID)
+ })
+ }
+}
+
+// Vertex 429 文案里给出了重试时长时按该时长冷却,不归为共享容量不足。
+func TestHandleGeminiUpstreamError_VertexMessageRetryHintUsesParsedDelay(t *testing.T) {
repo := &rateLimit429AccountRepoStub{}
svc := &GeminiMessagesCompatService{accountRepo: repo}
-
account := &Account{
- ID: 602,
+ ID: 607,
Platform: PlatformGemini,
Type: AccountTypeServiceAccount,
Credentials: map[string]any{
"project_id": "my-vertex-project",
},
}
- body := []byte(`{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}`)
+ body := []byte(`{"error":{"code":429,"message":"Resource exhausted. Please retry in 5s","status":"RESOURCE_EXHAUSTED"}}`)
before := time.Now()
svc.handleGeminiUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{}, body)
require.Equal(t, 1, repo.rateLimitCalls)
- require.Equal(t, int64(602), repo.lastRateLimitID)
- require.WithinDuration(t, before.Add(geminiVertexFallbackCooldown), repo.lastRateLimitReset, 2*time.Second)
- // 显式守护:不应被冷却超过 15 分钟(更不应到次日 PST 午夜)
- require.True(t, repo.lastRateLimitReset.Before(before.Add(15*time.Minute)))
+ require.Equal(t, int64(607), repo.lastRateLimitID)
+ require.WithinDuration(t, before.Add(5*time.Second), repo.lastRateLimitReset, 2*time.Second)
}
// API Key(AI Studio)无法解析重置时间时仍冷却到 PST 午夜,行为保持不变。
@@ -677,6 +806,72 @@ func TestHandleGeminiUpstreamError_APIKeyFallbackStillPSTMidnight(t *testing.T)
require.WithinDuration(t, expected, repo.lastRateLimitReset, 5*time.Second)
}
+// 第三方上游 API Key 的 429 不套用 AI Studio 每日配额语义:只认显式重试时长,
+// 否则走全局 429 兜底冷却(未配置时默认 5 秒)。
+func TestHandleGeminiUpstreamError_ThirdPartyAPIKey429(t *testing.T) {
+ const relayBaseURL = "https://relay.example.com"
+ tests := []struct {
+ name string
+ baseURL string
+ body string
+ expectWait time.Duration
+ pstNight bool
+ }{
+ {
+ name: "no_reset_time_uses_global_fallback",
+ baseURL: relayBaseURL,
+ body: `{"error":{"code":429,"message":"You have exhausted your capacity on this model. Your quota will reset after 6h53m10s."}}`,
+ expectWait: defaultRateLimit429CooldownSeconds * time.Second,
+ },
+ {
+ name: "daily_quota_message_not_treated_as_pst_midnight",
+ baseURL: relayBaseURL,
+ body: `{"error":{"code":429,"message":"Quota exceeded for metric: generate_content_free_tier_requests, limit: 50 per day"}}`,
+ expectWait: defaultRateLimit429CooldownSeconds * time.Second,
+ },
+ {
+ name: "explicit_quota_reset_delay_respected",
+ baseURL: relayBaseURL,
+ body: `{"error":{"code":429,"message":"rate limit","details":[{"metadata":{"quotaResetDelay":"42s"}}]}}`,
+ expectWait: 42 * time.Second,
+ },
+ {
+ name: "official_base_url_keeps_pst_midnight",
+ baseURL: "https://generativelanguage.googleapis.com/",
+ body: `{"error":{"code":429,"message":"rate limit"}}`,
+ pstNight: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ repo := &rateLimit429AccountRepoStub{}
+ svc := &GeminiMessagesCompatService{
+ accountRepo: repo,
+ rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil),
+ }
+ account := &Account{
+ ID: 700,
+ Platform: PlatformGemini,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{"base_url": tt.baseURL},
+ }
+
+ before := time.Now()
+ svc.handleGeminiUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{}, []byte(tt.body))
+
+ require.Equal(t, 1, repo.rateLimitCalls)
+ require.Equal(t, int64(700), repo.lastRateLimitID)
+ if tt.pstNight {
+ expected := time.Unix(*nextGeminiDailyResetUnix(), 0)
+ require.WithinDuration(t, expected, repo.lastRateLimitReset, 5*time.Second)
+ return
+ }
+ require.WithinDuration(t, before.Add(tt.expectWait), repo.lastRateLimitReset, 2*time.Second)
+ })
+ }
+}
+
type geminiErrorPolicyRepo struct {
mockAccountRepoForGemini
setErrorCalls int
diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go
index 9677a2466..7456df528 100644
--- a/backend/internal/service/gemini_messages_compat_service.go
+++ b/backend/internal/service/gemini_messages_compat_service.go
@@ -45,8 +45,8 @@ const (
geminiRetryInfoTypeURL = "type.googleapis.com/google.rpc.RetryInfo"
// RetryInfo.retryDelay 的上限,防止异常值导致账号长时间不可用
geminiRetryInfoMaxDelay = 15 * time.Minute
- // Vertex(service_account,按量付费)429 无法解析重置时间时的兜底冷却:
- // 按量付费限速是短窗口 RPM/TPM,没有每日配额,不适用 PST 午夜重置
+ // Vertex(service_account)账号自身的 429(按量付费的项目配额、预留吞吐超额等)无法解析重置时间时的兜底冷却:
+ // 这类限速是短窗口 RPM/TPM,没有每日配额,不适用 PST 午夜重置;共享容量不足的 429 不冷却
geminiVertexFallbackCooldown = time.Minute
)
@@ -529,94 +529,6 @@ func (s *GeminiMessagesCompatService) HasAntigravityAccounts(ctx context.Context
return len(accounts) > 0, nil
}
-// SelectAccountForAIStudioEndpoints selects an account that is likely to succeed against
-// generativelanguage.googleapis.com (e.g. GET /v1beta/models).
-//
-// Preference order:
-// 1) API key accounts (AI Studio)
-// 2) OAuth accounts without project_id (AI Studio OAuth)
-// 3) OAuth accounts explicitly marked as ai_studio
-// 4) Any remaining Gemini accounts (fallback)
-func (s *GeminiMessagesCompatService) SelectAccountForAIStudioEndpoints(ctx context.Context, groupID *int64) (*Account, error) {
- accounts, err := s.listSchedulableAccountsOnce(ctx, groupID, PlatformGemini, true)
- if err != nil {
- return nil, fmt.Errorf("query accounts failed: %w", err)
- }
- if len(accounts) == 0 {
- return nil, errors.New("no available Gemini accounts")
- }
-
- rank := func(a *Account) int {
- if a == nil {
- return 999
- }
- switch a.Type {
- case AccountTypeAPIKey:
- if strings.TrimSpace(a.GetCredential("api_key")) != "" {
- return 0
- }
- return 9
- case AccountTypeOAuth:
- if strings.TrimSpace(a.GetCredential("project_id")) == "" {
- return 1
- }
- if strings.TrimSpace(a.GetCredential("oauth_type")) == "ai_studio" {
- return 2
- }
- // Code Assist OAuth tokens often lack AI Studio scopes for models listing.
- return 3
- case AccountTypeServiceAccount:
- // Vertex service accounts use aiplatform.googleapis.com, not the AI Studio
- // endpoint (generativelanguage.googleapis.com), so they cannot serve these requests.
- return 999
- default:
- return 10
- }
- }
-
- var selected *Account
- for i := range accounts {
- acc := &accounts[i]
- if selected == nil {
- selected = acc
- continue
- }
-
- r1, r2 := rank(acc), rank(selected)
- if r1 < r2 {
- selected = acc
- continue
- }
- if r1 > r2 {
- continue
- }
-
- if acc.Priority < selected.Priority {
- selected = acc
- } else if acc.Priority == selected.Priority {
- switch {
- case acc.LastUsedAt == nil && selected.LastUsedAt != nil:
- selected = acc
- case acc.LastUsedAt != nil && selected.LastUsedAt == nil:
- // keep selected
- case acc.LastUsedAt == nil && selected.LastUsedAt == nil:
- if acc.Type == AccountTypeOAuth && selected.Type != AccountTypeOAuth {
- selected = acc
- }
- default:
- if acc.LastUsedAt.Before(*selected.LastUsedAt) {
- selected = acc
- }
- }
- }
- }
-
- if selected == nil {
- return nil, errors.New("no available Gemini accounts")
- }
- return s.hydrateSelectedAccount(ctx, selected)
-}
-
func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) {
beginUpstreamResponseModelObservation(c)
beginGeminiImageOutputObservation(c)
@@ -644,6 +556,8 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
}
geminiReq = ensureGeminiFunctionCallThoughtSignatures(geminiReq)
+ includeThoughts := req.Stream && claudeRequestEnablesThinking(body)
+ geminiReq = applyGeminiCompatThinkingConfig(geminiReq, body, mappedModel, includeThoughts)
originalClaudeBody := body
proxyURL := ""
@@ -770,19 +684,11 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
case AccountTypeServiceAccount:
buildReq = func(ctx context.Context) (*http.Request, string, error) {
- if s.tokenProvider == nil {
- return nil, "", errors.New("gemini token provider not configured")
- }
- accessToken, err := s.tokenProvider.GetAccessToken(ctx, account)
- if err != nil {
- return nil, "", err
- }
-
action := "generateContent"
if req.Stream {
action = "streamGenerateContent"
}
- fullURL, err := buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(mappedModel), mappedModel, action, req.Stream)
+ fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, action, req.Stream)
if err != nil {
return nil, "", err
}
@@ -793,7 +699,9 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
return nil, "", err
}
upstreamReq.Header.Set("Content-Type", "application/json")
- upstreamReq.Header.Set("Authorization", "Bearer "+accessToken)
+ if err := setVertexGeminiAuth(ctx, upstreamReq, account, s.tokenProvider); err != nil {
+ return nil, "", err
+ }
return upstreamReq, "x-request-id", nil
}
requestIDHeader = "x-request-id"
@@ -803,13 +711,19 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
}
var resp *http.Response
+ // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。
+ var checkedPolicy *ErrorPolicyResult
signatureRetryStage := 0
for attempt := 1; attempt <= geminiMaxRetries; attempt++ {
+ checkedPolicy = nil
upstreamReq, idHeader, err := buildReq(ctx)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
+ if failoverErr := s.handleVertexServiceAccountNotFound(ctx, c, account, err); failoverErr != nil {
+ return nil, failoverErr
+ }
// Local build error: don't retry.
if strings.Contains(err.Error(), "missing project_id") {
return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
@@ -859,25 +773,28 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
var strippedClaudeBody []byte
stageName := ""
+ // 降级函数会把思考块改写成正文,Gemini 侧先删掉历史思考块再降级。
+ retrySourceBody := dropClaudeHistoryThinkingBlocks(originalClaudeBody)
// 路径说明:本处上游是 Gemini,但被剥离的 body 是 Anthropic 格式。传 originalModel
// (客户端原 Anthropic model)而非 mappedModel(上游 Gemini model),让剥离逻辑按
// 客户端请求的 Anthropic 子协议族判定(详见 ResolveThinkingProtocol 文档)。
switch signatureRetryStage {
case 0:
// Stage 1: disable thinking + thinking->text
- strippedClaudeBody = FilterThinkingBlocksForRetry(originalClaudeBody, originalModel)
+ strippedClaudeBody = FilterThinkingBlocksForRetry(retrySourceBody, originalModel)
stageName = "thinking-only"
signatureRetryStage = 1
default:
// Stage 2: additionally downgrade tool_use/tool_result blocks to text
- strippedClaudeBody = FilterSignatureSensitiveBlocksForRetry(originalClaudeBody, originalModel)
+ strippedClaudeBody = FilterSignatureSensitiveBlocksForRetry(retrySourceBody, originalModel)
stageName = "thinking+tools"
signatureRetryStage = 2
}
retryGeminiReq, txErr := convertClaudeMessagesToGeminiGenerateContent(strippedClaudeBody)
if txErr == nil {
logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: detected signature-related 400, retrying with downgraded Claude blocks (%s)", account.ID, stageName)
- geminiReq = retryGeminiReq
+ // 降级只改写历史块,思考参数沿用客户端原始请求。
+ geminiReq = applyGeminiCompatThinkingConfig(retryGeminiReq, originalClaudeBody, mappedModel, includeThoughts)
// Consume one retry budget attempt and continue with the updated request payload.
sleepGeminiBackoff(1)
continue
@@ -894,11 +811,11 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
}
// 错误策略优先:匹配则跳过重试直接处理。
- if matched, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel); matched {
- resp = rebuilt
+ checked, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel)
+ resp = rebuilt
+ checkedPolicy = checked
+ if checked != nil && *checked != ErrorPolicyNone {
break
- } else {
- resp = rebuilt
}
if resp.StatusCode >= 400 && s.shouldRetryGeminiUpstreamError(account, resp.StatusCode) {
@@ -914,7 +831,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
break
}
if resp.StatusCode == 429 {
- // Mark as rate-limited early so concurrent requests avoid this account.
+ // Apply account-scoped 429 handling early so concurrent requests avoid a rate-limited account.
s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody)
}
if attempt < geminiMaxRetries {
@@ -966,7 +883,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
respBody := s.readUpstreamErrorBody(resp)
// 统一错误策略:自定义错误码 + 临时不可调度
if s.rateLimitService != nil {
- policy := s.rateLimitService.CheckErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel)
+ policy := s.finalErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel, checkedPolicy)
switch policy {
case ErrorPolicySkipped:
upstreamReqID := resp.Header.Get(requestIDHeader)
@@ -1144,6 +1061,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
Stream: req.Stream,
Duration: time.Since(startTime),
FirstTokenMs: firstTokenMs,
+ ReasoningEffort: extractGeminiReasoningEffortFromBody(geminiReq),
ImageCount: imageCount,
ImageSize: imageSize,
ImageInputSize: imageInputSize,
@@ -1311,15 +1229,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
case AccountTypeServiceAccount:
buildReq = func(ctx context.Context) (*http.Request, string, error) {
- if s.tokenProvider == nil {
- return nil, "", errors.New("gemini token provider not configured")
- }
- accessToken, err := s.tokenProvider.GetAccessToken(ctx, account)
- if err != nil {
- return nil, "", err
- }
-
- fullURL, err := buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(mappedModel), mappedModel, upstreamAction, useUpstreamStream)
+ fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, upstreamAction, useUpstreamStream)
if err != nil {
return nil, "", err
}
@@ -1329,7 +1239,9 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
return nil, "", err
}
upstreamReq.Header.Set("Content-Type", "application/json")
- upstreamReq.Header.Set("Authorization", "Bearer "+accessToken)
+ if err := setVertexGeminiAuth(ctx, upstreamReq, account, s.tokenProvider); err != nil {
+ return nil, "", err
+ }
return upstreamReq, "x-request-id", nil
}
requestIDHeader = "x-request-id"
@@ -1339,12 +1251,18 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
}
var resp *http.Response
+ // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。
+ var checkedPolicy *ErrorPolicyResult
for attempt := 1; attempt <= geminiMaxRetries; attempt++ {
+ checkedPolicy = nil
upstreamReq, idHeader, err := buildReq(ctx)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
+ if failoverErr := s.handleVertexServiceAccountNotFound(ctx, c, account, err); failoverErr != nil {
+ return nil, failoverErr
+ }
// Local build error: don't retry.
if strings.Contains(err.Error(), "missing project_id") {
return nil, s.writeGoogleError(c, http.StatusBadRequest, err.Error())
@@ -1374,14 +1292,23 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
return nil, transportErr
}
- // 错误策略优先:匹配则跳过重试直接处理。
- if matched, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel); matched {
+ // 引用缓存不存在、上游网关持有缓存的账号不可用先于错误策略识别:错误策略会写临时不可调度,
+ // 重试与换号也无法恢复。
+ if passthrough, rebuilt := s.cachedContentPassthroughInLoop(ctx, account, resp); passthrough {
resp = rebuilt
break
} else {
resp = rebuilt
}
+ // 错误策略优先:匹配则跳过重试直接处理。
+ checked, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel)
+ resp = rebuilt
+ checkedPolicy = checked
+ if checked != nil && *checked != ErrorPolicyNone {
+ break
+ }
+
if resp.StatusCode >= 400 && s.shouldRetryGeminiUpstreamError(account, resp.StatusCode) {
respBody := s.readUpstreamErrorBody(resp)
_ = resp.Body.Close()
@@ -1467,6 +1394,14 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
if resp.StatusCode >= 400 {
respBody := s.readUpstreamErrorBody(resp)
+ // 引用缓存不存在是请求问题:统一返回 403,不改账号状态、不换号。
+ if isGeminiCachedContentNotFound(resp.StatusCode, respBody) {
+ return nil, s.writeGeminiCachedContentNotFound(c, account, resp, respBody, requestID, isOAuth)
+ }
+ // 上游网关的限流 / 不可用只针对其持有缓存的账号:不改本账号状态,交由绑定请求的耗尽处理透传。
+ if isGeminiBoundCacheUpstreamPassthrough(ctx, account, resp.StatusCode) {
+ return nil, &UpstreamFailoverError{StatusCode: resp.StatusCode, ResponseBody: respBody, BoundUpstreamPassthrough: true}
+ }
// Best-effort fallback for OAuth tokens missing AI Studio scopes when calling countTokens.
// This avoids Gemini SDKs failing hard during preflight token counting.
// Checked before error policy so it always works regardless of custom error codes.
@@ -1487,7 +1422,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
// 统一错误策略:自定义错误码 + 临时不可调度
if s.rateLimitService != nil {
- policy := s.rateLimitService.CheckErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel)
+ policy := s.finalErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel, checkedPolicy)
switch policy {
case ErrorPolicySkipped:
if failoverErr := s.skippedErrorPolicyFailoverError(c, account, resp.StatusCode, respBody, requestID); failoverErr != nil {
@@ -1656,14 +1591,14 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
}, nil
}
-// checkErrorPolicyInLoop 在重试循环内预检查错误策略。
-// 返回 true 表示策略已匹配(调用者应 break),resp 已重建可直接使用。
-// 返回 false 表示 ErrorPolicyNone,resp 已重建,调用者继续走重试逻辑。
+// checkErrorPolicyInLoop 在重试循环内对上游错误响应检查错误策略,resp 已重建可直接使用。
+// checked 为 nil 表示未检查(非错误响应或未配置限流服务);否则指向检查结果,
+// 非 ErrorPolicyNone 时调用者应 break 并由循环外的错误处理复用该结果。
func (s *GeminiMessagesCompatService) checkErrorPolicyInLoop(
ctx context.Context, account *Account, resp *http.Response, mappedModel string,
-) (matched bool, rebuilt *http.Response) {
+) (checked *ErrorPolicyResult, rebuilt *http.Response) {
if resp.StatusCode < 400 || s.rateLimitService == nil {
- return false, resp
+ return nil, resp
}
body := s.readUpstreamErrorBody(resp)
_ = resp.Body.Close()
@@ -1673,7 +1608,41 @@ func (s *GeminiMessagesCompatService) checkErrorPolicyInLoop(
Body: io.NopCloser(bytes.NewReader(body)),
}
policy := s.rateLimitService.CheckErrorPolicy(ctx, account, resp.StatusCode, body, mappedModel)
- return policy != ErrorPolicyNone, rebuilt
+ return &policy, rebuilt
+}
+
+// finalErrorPolicy 返回循环外处理最终上游错误响应时使用的错误策略。每个上游响应只检查一次:
+// 错误策略检查会触发临时不可调度规则,并据账号上已记录的 401 暂停把 401 升级为 error。
+// checked 非 nil 时它就是重试循环内对同一响应的检查结果,直接复用;否则在此检查。
+// 调用方保证 s.rateLimitService 非 nil。
+func (s *GeminiMessagesCompatService) finalErrorPolicy(
+ ctx context.Context, account *Account, statusCode int, body []byte, mappedModel string, checked *ErrorPolicyResult,
+) ErrorPolicyResult {
+ if checked != nil {
+ return *checked
+ }
+ return s.rateLimitService.CheckErrorPolicy(ctx, account, statusCode, body, mappedModel)
+}
+
+// cachedContentPassthroughInLoop 判断上游响应是否跳过同号重试与错误策略直接处理:引用缓存不存在,
+// 或绑定缓存的请求在上游网关账号上收到的 429 / 5xx。读取过的响应体以内存副本重建。
+func (s *GeminiMessagesCompatService) cachedContentPassthroughInLoop(ctx context.Context, account *Account, resp *http.Response) (passthrough bool, rebuilt *http.Response) {
+ if isGeminiBoundCacheUpstreamPassthrough(ctx, account, resp.StatusCode) {
+ return true, resp
+ }
+ switch resp.StatusCode {
+ case http.StatusBadRequest, http.StatusForbidden, http.StatusNotFound:
+ default:
+ return false, resp
+ }
+ body := s.readUpstreamErrorBody(resp)
+ _ = resp.Body.Close()
+ rebuilt = &http.Response{
+ StatusCode: resp.StatusCode,
+ Header: resp.Header.Clone(),
+ Body: io.NopCloser(bytes.NewReader(body)),
+ }
+ return isGeminiCachedContentNotFound(resp.StatusCode, body), rebuilt
}
func (s *GeminiMessagesCompatService) shouldRetryGeminiUpstreamError(account *Account, statusCode int) bool {
@@ -1781,36 +1750,53 @@ func (s *GeminiMessagesCompatService) writeGeminiCustomCodeSkippedError(c *gin.C
// 并记录 ops 错误事件。状态码保真:下游据此区分请求级错误与可重试的链路故障。
func (s *GeminiMessagesCompatService) writeGeminiNativeUpstreamError(c *gin.Context, account *Account, resp *http.Response, respBody []byte, requestID string, isOAuth bool) error {
respBody = unwrapIfNeeded(isOAuth, respBody)
+ upstreamMsg := s.recordGeminiNativeUpstreamError(c, account, resp.StatusCode, respBody, requestID)
+
+ contentType := resp.Header.Get("Content-Type")
+ if contentType == "" {
+ contentType = "application/json"
+ }
+ MarkResponseCommitted(c)
+ c.Data(resp.StatusCode, contentType, respBody)
+ if upstreamMsg == "" {
+ return fmt.Errorf("gemini upstream error: %d", resp.StatusCode)
+ }
+ return fmt.Errorf("gemini upstream error: %d message=%s", resp.StatusCode, upstreamMsg)
+}
+
+// writeGeminiCachedContentNotFound 记录上游原始错误,并向客户端统一返回缓存不存在的 403:
+// 各上游的响应形态不同,且 Vertex 的文案含上游缓存资源 ID。失败由请求引用的缓存决定,ops 按客户端请求错误统计。
+func (s *GeminiMessagesCompatService) writeGeminiCachedContentNotFound(c *gin.Context, account *Account, resp *http.Response, respBody []byte, requestID string, isOAuth bool) error {
+ respBody = unwrapIfNeeded(isOAuth, respBody)
+ upstreamMsg := s.recordGeminiNativeUpstreamError(c, account, resp.StatusCode, respBody, requestID)
+ MarkOpsRequestScopedError(c, "permission_error")
+ MarkResponseCommitted(c)
+ c.Data(http.StatusForbidden, "application/json", []byte(GeminiCachedContentNotFoundResponse))
+ return fmt.Errorf("gemini upstream error: %d message=%s", resp.StatusCode, upstreamMsg)
+}
+
+// recordGeminiNativeUpstreamError 把上游错误响应登记到 ops 上下文,返回脱敏后的上游错误文案。
+func (s *GeminiMessagesCompatService) recordGeminiNativeUpstreamError(c *gin.Context, account *Account, statusCode int, respBody []byte, requestID string) string {
upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody))
upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg)
upstreamDetail := s.upstreamErrorDetail(respBody)
if s.cfg != nil && s.cfg.Gateway.LogUpstreamErrorBody {
- logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini] native upstream error %d: %s", resp.StatusCode, truncateForLog(respBody, s.cfg.Gateway.LogUpstreamErrorBodyMaxBytes))
+ logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini] native upstream error %d: %s", statusCode, truncateForLog(respBody, s.cfg.Gateway.LogUpstreamErrorBodyMaxBytes))
}
- setOpsUpstreamError(c, resp.StatusCode, upstreamMsg, upstreamDetail)
+ setOpsUpstreamError(c, statusCode, upstreamMsg, upstreamDetail)
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
Platform: account.Platform,
AccountID: account.ID,
AccountName: account.Name,
- UpstreamStatusCode: resp.StatusCode,
+ UpstreamStatusCode: statusCode,
UpstreamRequestID: requestID,
Kind: "http_error",
Message: upstreamMsg,
Detail: upstreamDetail,
})
-
- contentType := resp.Header.Get("Content-Type")
- if contentType == "" {
- contentType = "application/json"
- }
- MarkResponseCommitted(c)
- c.Data(resp.StatusCode, contentType, respBody)
- if upstreamMsg == "" {
- return fmt.Errorf("gemini upstream error: %d", resp.StatusCode)
- }
- return fmt.Errorf("gemini upstream error: %d message=%s", resp.StatusCode, upstreamMsg)
+ return upstreamMsg
}
func sleepGeminiBackoff(attempt int) {
@@ -2155,6 +2141,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re
openBlockIndex := -1
openBlockType := ""
seenText := ""
+ seenThought := ""
openToolIndex := -1
openToolID := ""
openToolName := ""
@@ -2203,6 +2190,56 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re
parts := extractGeminiParts(geminiResp)
for _, part := range parts {
+ if text, ok := part["text"].(string); ok && isGeminiThoughtPart(part) {
+ delta, newSeen := computeGeminiTextDelta(seenThought, text)
+ seenThought = newSeen
+ if delta == "" {
+ continue
+ }
+ if openToolIndex >= 0 {
+ writeSSE(c.Writer, "content_block_stop", map[string]any{
+ "type": "content_block_stop",
+ "index": openToolIndex,
+ })
+ openToolIndex = -1
+ openToolName = ""
+ seenToolJSON = ""
+ }
+ if openBlockType != "thinking" {
+ if openBlockIndex >= 0 {
+ writeSSE(c.Writer, "content_block_stop", map[string]any{
+ "type": "content_block_stop",
+ "index": openBlockIndex,
+ })
+ }
+ openBlockType = "thinking"
+ openBlockIndex = nextBlockIndex
+ nextBlockIndex++
+ writeSSE(c.Writer, "content_block_start", map[string]any{
+ "type": "content_block_start",
+ "index": openBlockIndex,
+ "content_block": map[string]any{
+ "type": "thinking",
+ "thinking": "",
+ "signature": "",
+ },
+ })
+ }
+ if firstTokenMs == nil {
+ ms := int(time.Since(startTime).Milliseconds())
+ firstTokenMs = &ms
+ }
+ writeSSE(c.Writer, "content_block_delta", map[string]any{
+ "type": "content_block_delta",
+ "index": openBlockIndex,
+ "delta": map[string]any{
+ "type": "thinking_delta",
+ "thinking": delta,
+ },
+ })
+ flusher.Flush()
+ continue
+ }
if text, ok := part["text"].(string); ok && text != "" {
// Close an open tool_use block before starting text, mirroring
// the functionCall branch (which closes open text blocks) and
@@ -2635,6 +2672,25 @@ func isGeminiInsufficientScope(headers http.Header, body []byte) bool {
return strings.Contains(lower, "insufficient authentication scopes") || strings.Contains(lower, "access_token_scope_insufficient")
}
+// isGeminiCachedContentNotFound 识别请求引用的显式缓存不存在(含已过期、已删除、不属于当前项目)时上游的响应,
+// 这类响应由请求的 cachedContent 决定,与账号凭据状态无关:
+// - AI Studio 及本系统网关:一律 403 "CachedContent not found (or permission denied)";
+// - Vertex 生成请求:400 "Invalid resource state for cache content {id}.";
+// - Vertex 缓存资源 GET / PATCH / DELETE:404 "Cached content {id} is not found."。
+func isGeminiCachedContentNotFound(statusCode int, body []byte) bool {
+ lower := strings.ToLower(string(body))
+ switch statusCode {
+ case http.StatusForbidden:
+ return strings.Contains(lower, "cachedcontent not found")
+ case http.StatusBadRequest:
+ return strings.Contains(lower, "invalid resource state for cache content")
+ case http.StatusNotFound:
+ return strings.Contains(lower, "cached content") && strings.Contains(lower, "not found")
+ default:
+ return false
+ }
+}
+
func estimateGeminiCountTokens(reqBody []byte) int {
total := 0
@@ -2854,78 +2910,6 @@ func (s *GeminiMessagesCompatService) handleNativeStreamingResponse(c *gin.Conte
return &geminiNativeStreamResult{usage: usage, firstTokenMs: firstTokenMs}, nil
}
-// ForwardAIStudioGET forwards a GET request to AI Studio (generativelanguage.googleapis.com) for
-// endpoints like /v1beta/models and /v1beta/models/{model}.
-//
-// This is used to support Gemini SDKs that call models listing endpoints before generation.
-func (s *GeminiMessagesCompatService) ForwardAIStudioGET(ctx context.Context, account *Account, path string) (*UpstreamHTTPResult, error) {
- if account == nil {
- return nil, errors.New("account is nil")
- }
- // path 会被直接拼到上游 base URL 后面,因此按路径护栏逐片段校验,
- // 见 upstream_path_guard.go。
- sanitizedPath, ok := sanitizedUpstreamPathSuffix(path)
- if !ok || sanitizedPath == "" {
- return nil, errors.New("invalid path")
- }
- path = sanitizedPath
-
- baseURL := account.GetGeminiBaseURL(geminicli.AIStudioBaseURL)
- normalizedBaseURL, err := s.validateUpstreamBaseURL(baseURL)
- if err != nil {
- return nil, err
- }
- fullURL := strings.TrimRight(normalizedBaseURL, "/") + path
-
- var proxyURL string
- if account.ProxyID != nil && account.Proxy != nil {
- proxyURL = account.Proxy.URL()
- }
-
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil)
- if err != nil {
- return nil, err
- }
-
- switch account.Type {
- case AccountTypeAPIKey:
- apiKey := strings.TrimSpace(account.GetCredential("api_key"))
- if apiKey == "" {
- return nil, errors.New("gemini api_key not configured")
- }
- req.Header.Set("x-goog-api-key", apiKey)
- case AccountTypeOAuth:
- if s.tokenProvider == nil {
- return nil, errors.New("gemini token provider not configured")
- }
- accessToken, err := s.tokenProvider.GetAccessToken(ctx, account)
- if err != nil {
- return nil, err
- }
- req.Header.Set("Authorization", "Bearer "+accessToken)
- default:
- return nil, fmt.Errorf("unsupported account type: %s", account.Type)
- }
-
- resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency)
- if err != nil {
- return nil, err
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
- wwwAuthenticate := resp.Header.Get("Www-Authenticate")
- filteredHeaders := responseheaders.FilterHeaders(resp.Header, s.responseHeaderFilter)
- if wwwAuthenticate != "" {
- filteredHeaders.Set("Www-Authenticate", wwwAuthenticate)
- }
- return &UpstreamHTTPResult{
- StatusCode: resp.StatusCode,
- Headers: filteredHeaders,
- Body: body,
- }, nil
-}
-
// unwrapGeminiResponse 解包 Gemini OAuth 响应中的 response 字段
// 使用 gjson 零拷贝提取,避免完整 Unmarshal+Marshal
func unwrapGeminiResponse(raw []byte) ([]byte, error) {
@@ -3097,6 +3081,10 @@ func (s *GeminiMessagesCompatService) handleGeminiUpstreamError(ctx context.Cont
if account.IsPoolMode() && !account.IsCustomErrorCodesEnabled() {
return
}
+ if account.IsGeminiThirdPartyAPIKey() {
+ s.handleGeminiThirdParty429(ctx, account, body)
+ return
+ }
oauthType := account.GeminiOAuthType()
tierID := account.GeminiTierID()
@@ -3120,7 +3108,13 @@ func (s *GeminiMessagesCompatService) handleGeminiUpstreamError(ctx context.Cont
logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini 429] Account %d (Google One OAuth, tier=%s, project=%s) rate limited, cooldown=%v", account.ID, tierID, projectID, time.Until(ra).Truncate(time.Second))
}
} else if account.IsVertexServiceAccount() {
- // Vertex 按量付费:短窗限速,无每日配额,短冷却后即可恢复
+ // 共享容量不足描述的是请求当时的上游容量,不是账号额度:账号保持可调度,
+ // 由请求内的同号退避重试与换号消化。
+ if isVertexSharedCapacity429(body) {
+ logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini 429] Account %d (Vertex service account, project=%s) shared capacity exhausted, account stays schedulable", account.ID, projectID)
+ return
+ }
+ // 项目配额、预留吞吐等账号自身的限速是短窗口 RPM/TPM,无每日配额,短冷却后即可恢复
ra = time.Now().Add(geminiVertexFallbackCooldown)
logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini 429] Account %d (Vertex service account, project=%s) rate limited, cooldown=%v", account.ID, projectID, time.Until(ra).Truncate(time.Second))
} else {
@@ -3145,16 +3139,60 @@ func (s *GeminiMessagesCompatService) handleGeminiUpstreamError(ctx context.Cont
account.ID, resetTime, oauthType, tierID)
}
+// isVertexSharedCapacity429 判断 Vertex 429 是否为按量付费共享容量不足:RESOURCE_EXHAUSTED、
+// 不带任何错误明细(RetryInfo / QuotaFailure / ErrorInfo),文案为 "Resource exhausted ... try again later"
+// 且不涉及项目配额或预留吞吐。其他形态的 429 按账号自身限速处理。
+func isVertexSharedCapacity429(body []byte) bool {
+ errObj := gjson.GetBytes(body, "error")
+ if !errObj.Exists() {
+ errObj = gjson.GetBytes(body, "0.error")
+ }
+ if !errObj.IsObject() {
+ return false
+ }
+ if !strings.EqualFold(strings.TrimSpace(errObj.Get("status").String()), "RESOURCE_EXHAUSTED") {
+ return false
+ }
+ if len(errObj.Get("details").Array()) > 0 {
+ return false
+ }
+ msg := strings.ToLower(errObj.Get("message").String())
+ if !strings.Contains(msg, "resource exhausted") || !strings.Contains(msg, "try again later") {
+ return false
+ }
+ return !strings.Contains(msg, "quota") && !strings.Contains(msg, "provisioned throughput")
+}
+
+// handleGeminiThirdParty429 处理第三方上游的 429:不套用 AI Studio 每日配额语义,
+// 只认响应里显式给出的重试时间,否则走全局 429 兜底冷却。
+func (s *GeminiMessagesCompatService) handleGeminiThirdParty429(ctx context.Context, account *Account, body []byte) {
+ if resetAt := parseGeminiRetryDelayResetTime(body); resetAt != nil {
+ resetTime := time.Unix(*resetAt, 0)
+ _ = s.accountRepo.SetRateLimited(ctx, account.ID, resetTime)
+ logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini 429] Account %d (third-party API Key) rate limited until %v", account.ID, resetTime)
+ return
+ }
+ if s.rateLimitService != nil {
+ s.rateLimitService.apply429FallbackRateLimit(ctx, account, "gemini_third_party_no_reset_time")
+ return
+ }
+ _ = s.accountRepo.SetRateLimited(ctx, account.ID, time.Now().Add(defaultRateLimit429CooldownSeconds*time.Second))
+}
+
// ParseGeminiRateLimitResetTime 解析 Gemini 格式的 429 响应,返回重置时间的 Unix 时间戳
func ParseGeminiRateLimitResetTime(body []byte) *int64 {
- // 第一阶段:gjson 结构化提取
errMsg := gjson.GetBytes(body, "error.message").String()
if looksLikeGeminiDailyQuota(errMsg) {
if ts := nextGeminiDailyResetUnix(); ts != nil {
return ts
}
}
+ return parseGeminiRetryDelayResetTime(body)
+}
+// parseGeminiRetryDelayResetTime 只解析响应里显式给出的重试时长,返回重置时间的 Unix 时间戳。
+func parseGeminiRetryDelayResetTime(body []byte) *int64 {
+ // 第一阶段:gjson 结构化提取
// 遍历 error.details 查找 quotaResetDelay(AI Studio)或 RetryInfo.retryDelay(Vertex)
var found *int64
gjson.GetBytes(body, "error.details").ForEach(func(_, detail gjson.Result) bool {
@@ -3433,6 +3471,7 @@ func convertClaudeMessagesToGeminiContents(messages any, toolUseIDToName map[str
}
parts := make([]any, 0)
+ droppedThinking := false
switch content := mm["content"].(type) {
case string:
// 字符串形式的 content,保留所有内容(包括空白)
@@ -3440,12 +3479,18 @@ func convertClaudeMessagesToGeminiContents(messages any, toolUseIDToName map[str
case []any:
// 如果只有一个 block,不过滤空白(让上游 API 报错)
singleBlock := len(content) == 1
+ var toolImageParts []any
for _, block := range content {
bm, ok := block.(map[string]any)
if !ok {
continue
}
+ // 历史思考块不回传给 Gemini:Gemini 的思考连续性由 thoughtSignature 承载。
+ if bt, _ := bm["type"].(string); bt == "thinking" || bt == "redacted_thinking" {
+ droppedThinking = true
+ continue
+ }
bt, _ := bm["type"].(string)
switch bt {
case "text":
@@ -3480,14 +3525,20 @@ func convertClaudeMessagesToGeminiContents(messages any, toolUseIDToName map[str
if name == "" {
name = "tool"
}
+ text := extractClaudeContentText(bm["content"])
+ images := extractClaudeToolResultImageParts(bm["content"])
+ if text == "" && len(images) > 0 {
+ text = "[image attached below]"
+ }
parts = append(parts, map[string]any{
"functionResponse": map[string]any{
"name": name,
"response": map[string]any{
- "content": extractClaudeContentText(bm["content"]),
+ "content": text,
},
},
})
+ toolImageParts = append(toolImageParts, images...)
case "image":
if src, ok := bm["source"].(map[string]any); ok {
if srcType, _ := src["type"].(string); srcType == "base64" {
@@ -3510,9 +3561,14 @@ func convertClaudeMessagesToGeminiContents(messages any, toolUseIDToName map[str
}
}
}
+ parts = append(parts, toolImageParts...)
default:
// ignore
}
+ // 只含思考块的消息去掉思考后为空,整条跳过(Gemini 拒收空 parts)。
+ if droppedThinking && len(parts) == 0 {
+ continue
+ }
out = append(out, map[string]any{
"role": gRole,
@@ -3546,6 +3602,40 @@ func extractClaudeContentText(v any) string {
}
}
+func extractClaudeToolResultImageParts(v any) []any {
+ arr, ok := v.([]any)
+ if !ok {
+ return nil
+ }
+
+ parts := make([]any, 0)
+ for _, part := range arr {
+ pm, ok := part.(map[string]any)
+ if !ok || pm["type"] != "image" {
+ continue
+ }
+ source, ok := pm["source"].(map[string]any)
+ if !ok {
+ continue
+ }
+ if sourceType, _ := source["type"].(string); sourceType != "base64" {
+ continue
+ }
+ mediaType, _ := source["media_type"].(string)
+ data, _ := source["data"].(string)
+ if mediaType == "" || data == "" {
+ continue
+ }
+ parts = append(parts, map[string]any{
+ "inlineData": map[string]any{
+ "mimeType": mediaType,
+ "data": data,
+ },
+ })
+ }
+ return parts
+}
+
func convertClaudeToolsToGeminiTools(tools any) []any {
arr, ok := tools.([]any)
if !ok || len(arr) == 0 {
diff --git a/backend/internal/service/gemini_messages_compat_service_test.go b/backend/internal/service/gemini_messages_compat_service_test.go
index 2bd70c11c..6cdba32ba 100644
--- a/backend/internal/service/gemini_messages_compat_service_test.go
+++ b/backend/internal/service/gemini_messages_compat_service_test.go
@@ -704,6 +704,105 @@ func TestConvertClaudeMessagesToGeminiGenerateContent_AddsThoughtSignatureForToo
}
}
+func TestConvertClaudeMessagesToGeminiGenerateContent_ExtractsToolResultImages(t *testing.T) {
+ claudeReq := map[string]any{
+ "messages": []any{
+ map[string]any{
+ "role": "assistant",
+ "content": []any{
+ map[string]any{
+ "type": "tool_use",
+ "id": "toolu_123",
+ "name": "inspect",
+ "input": map[string]any{
+ "path": "image.png",
+ },
+ },
+ },
+ },
+ map[string]any{
+ "role": "user",
+ "content": []any{
+ map[string]any{
+ "type": "tool_result",
+ "tool_use_id": "toolu_123",
+ "content": []any{
+ map[string]any{"type": "text", "text": "found it"},
+ map[string]any{
+ "type": "image",
+ "source": map[string]any{
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "aGVsbG8=",
+ },
+ },
+ },
+ },
+ map[string]any{
+ "type": "tool_result",
+ "tool_use_id": "toolu_123",
+ "content": []any{
+ map[string]any{
+ "type": "image",
+ "source": map[string]any{
+ "type": "base64",
+ "media_type": "image/jpeg",
+ "data": "d29ybGQ=",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+ body, err := json.Marshal(claudeReq)
+ require.NoError(t, err)
+
+ converted, err := convertClaudeMessagesToGeminiGenerateContent(body)
+ require.NoError(t, err)
+
+ var geminiReq map[string]any
+ require.NoError(t, json.Unmarshal(converted, &geminiReq))
+ contents, ok := geminiReq["contents"].([]any)
+ require.True(t, ok)
+ content, ok := contents[1].(map[string]any)
+ require.True(t, ok)
+ parts, ok := content["parts"].([]any)
+ require.True(t, ok)
+ require.Len(t, parts, 4)
+
+ firstPart, ok := parts[0].(map[string]any)
+ require.True(t, ok)
+ firstResponse, ok := firstPart["functionResponse"].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, "inspect", firstResponse["name"])
+ firstResponseBody, ok := firstResponse["response"].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, "found it", firstResponseBody["content"])
+
+ secondPart, ok := parts[1].(map[string]any)
+ require.True(t, ok)
+ secondResponse, ok := secondPart["functionResponse"].(map[string]any)
+ require.True(t, ok)
+ secondResponseBody, ok := secondResponse["response"].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, "[image attached below]", secondResponseBody["content"])
+
+ firstImagePart, ok := parts[2].(map[string]any)
+ require.True(t, ok)
+ firstImage, ok := firstImagePart["inlineData"].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, "image/png", firstImage["mimeType"])
+ require.Equal(t, "aGVsbG8=", firstImage["data"])
+ secondImagePart, ok := parts[3].(map[string]any)
+ require.True(t, ok)
+ secondImage, ok := secondImagePart["inlineData"].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, "image/jpeg", secondImage["mimeType"])
+ require.Equal(t, "d29ybGQ=", secondImage["data"])
+}
+
func TestEnsureGeminiFunctionCallThoughtSignatures_InsertsWhenMissing(t *testing.T) {
geminiReq := map[string]any{
"contents": []any{
diff --git a/backend/internal/service/gemini_models_endpoints.go b/backend/internal/service/gemini_models_endpoints.go
new file mode 100644
index 000000000..f9c80c869
--- /dev/null
+++ b/backend/internal/service/gemini_models_endpoints.go
@@ -0,0 +1,302 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "slices"
+ "strings"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/gemini"
+ "github.com/MACOS-DO/sub4api/internal/pkg/geminicli"
+ "github.com/MACOS-DO/sub4api/internal/pkg/googleapi"
+ "github.com/MACOS-DO/sub4api/internal/util/responseheaders"
+)
+
+// Gemini 分组对外提供 AI Studio 兼容协议(GET /v1beta/models、/v1beta/models/{model}),
+// 分组内的账号可以是 AI Studio 兼容上游(API Key / OAuth),也可以是 Agent Platform (Vertex)。
+// 本文件把不同账号类型的模型接口统一成 AI Studio 格式的响应。
+
+// errGeminiModelsUpstreamStatus 在 Vertex 分页读取遇到非 2xx 时中止分页,原始响应由调用方另行保存。
+var errGeminiModelsUpstreamStatus = errors.New("upstream model list returned non-2xx status")
+
+// SelectAccountForModelsEndpoints 为模型列表与模型详情接口选择账号。
+//
+// 优先级:
+// 1. 配置了 api_key 的 API Key 账号
+// 2. 不带 project_id 的 OAuth 账号(AI Studio OAuth)
+// 3. 显式标记为 ai_studio 的 OAuth 账号
+// 4. Code Assist OAuth 账号(令牌常缺 AI Studio 权限范围,多半退回内置列表)
+// 5. 其余类型的账号
+// 6. Vertex 服务账号(服务账号 JSON 认证,读取 Google 发布方模型列表)
+// 7. Vertex API Key 账号(列表接口不接受 API Key,只能返回内置列表)
+//
+// Vertex 账号排在所有 AI Studio 兼容账号之后,混合分组始终由 AI Studio 兼容账号应答。
+// 同级账号按 priority、最近使用时间挑选。
+func (s *GeminiMessagesCompatService) SelectAccountForModelsEndpoints(ctx context.Context, groupID *int64) (*Account, error) {
+ accounts, err := s.listSchedulableAccountsOnce(ctx, groupID, PlatformGemini, true)
+ if err != nil {
+ return nil, fmt.Errorf("query accounts failed: %w", err)
+ }
+ if len(accounts) == 0 {
+ return nil, errors.New("no available Gemini accounts")
+ }
+
+ var selected *Account
+ for i := range accounts {
+ acc := &accounts[i]
+ if selected == nil {
+ selected = acc
+ continue
+ }
+
+ r1, r2 := modelsEndpointAccountRank(acc), modelsEndpointAccountRank(selected)
+ if r1 < r2 {
+ selected = acc
+ continue
+ }
+ if r1 > r2 {
+ continue
+ }
+
+ if acc.Priority < selected.Priority {
+ selected = acc
+ } else if acc.Priority == selected.Priority {
+ switch {
+ case acc.LastUsedAt == nil && selected.LastUsedAt != nil:
+ selected = acc
+ case acc.LastUsedAt != nil && selected.LastUsedAt == nil:
+ // keep selected
+ case acc.LastUsedAt == nil && selected.LastUsedAt == nil:
+ if acc.Type == AccountTypeOAuth && selected.Type != AccountTypeOAuth {
+ selected = acc
+ }
+ default:
+ if acc.LastUsedAt.Before(*selected.LastUsedAt) {
+ selected = acc
+ }
+ }
+ }
+ }
+
+ if selected == nil {
+ return nil, errors.New("no available Gemini accounts")
+ }
+ return s.hydrateSelectedAccount(ctx, selected)
+}
+
+// modelsEndpointAccountRank 返回账号在模型接口选号中的优先级,数值越小越优先,顺序见 SelectAccountForModelsEndpoints。
+func modelsEndpointAccountRank(a *Account) int {
+ if a == nil {
+ return 999
+ }
+ switch a.Type {
+ case AccountTypeAPIKey:
+ if strings.TrimSpace(a.GetCredential("api_key")) != "" {
+ return 0
+ }
+ return 9
+ case AccountTypeOAuth:
+ if strings.TrimSpace(a.GetCredential("project_id")) == "" {
+ return 1
+ }
+ if strings.TrimSpace(a.GetCredential("oauth_type")) == "ai_studio" {
+ return 2
+ }
+ return 3
+ case AccountTypeServiceAccount:
+ if a.IsVertexAPIKey() {
+ return 12
+ }
+ return 11
+ default:
+ return 10
+ }
+}
+
+// ForwardListModels 读取账号上游的模型列表,返回 AI Studio 格式的响应(GET /v1beta/models)。
+// AI Studio 兼容账号原样返回上游响应;Vertex 服务账号读取 Google 发布方模型列表后转换格式,
+// 上游非 2xx 时原样返回该响应;Vertex API Key 账号返回内置列表。
+func (s *GeminiMessagesCompatService) ForwardListModels(ctx context.Context, account *Account) (*UpstreamHTTPResult, error) {
+ if account == nil {
+ return nil, errors.New("account is nil")
+ }
+ if !account.IsVertexServiceAccount() {
+ return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models")
+ }
+ if account.IsVertexAPIKey() {
+ return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModelsList())
+ }
+
+ modelIDs, failure, err := s.listVertexGeminiModels(ctx, account, account.VertexLocation(""))
+ if err != nil {
+ return nil, err
+ }
+ if failure != nil {
+ return failure, nil
+ }
+ models := make([]gemini.Model, 0, len(modelIDs))
+ for _, modelID := range modelIDs {
+ models = append(models, gemini.FallbackModel(modelID))
+ }
+ return geminiModelsJSONResult(http.StatusOK, gemini.ModelsListResponse{Models: models})
+}
+
+// ForwardGetModel 读取账号上游的单个模型信息,返回 AI Studio 格式的响应(GET /v1beta/models/{model})。
+// Vertex 服务账号在该模型生成请求所用区域的模型列表中查找,找不到时返回 404;Vertex API Key 账号返回内置信息。
+func (s *GeminiMessagesCompatService) ForwardGetModel(ctx context.Context, account *Account, model string) (*UpstreamHTTPResult, error) {
+ if account == nil {
+ return nil, errors.New("account is nil")
+ }
+ if !account.IsVertexServiceAccount() {
+ return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models/"+model)
+ }
+ if account.IsVertexAPIKey() {
+ return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModel(model))
+ }
+
+ modelIDs, failure, err := s.listVertexGeminiModels(ctx, account, account.VertexLocation(model))
+ if err != nil {
+ return nil, err
+ }
+ if failure != nil {
+ return failure, nil
+ }
+ if slices.Contains(modelIDs, model) {
+ return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModel(model))
+ }
+ return geminiModelsJSONResult(http.StatusNotFound, map[string]any{
+ "error": map[string]any{
+ "code": http.StatusNotFound,
+ "message": fmt.Sprintf("models/%s is not found", model),
+ "status": googleapi.HTTPStatusToGoogleStatus(http.StatusNotFound),
+ },
+ })
+}
+
+// forwardGeminiModelsGET 向 AI Studio 兼容上游转发模型接口的 GET 请求。
+// path 会被直接拼到上游 base URL 后面,因此按路径护栏逐片段校验,见 upstream_path_guard.go。
+func (s *GeminiMessagesCompatService) forwardGeminiModelsGET(ctx context.Context, account *Account, path string) (*UpstreamHTTPResult, error) {
+ sanitizedPath, ok := sanitizedUpstreamPathSuffix(path)
+ if !ok || sanitizedPath == "" {
+ return nil, errors.New("invalid path")
+ }
+
+ baseURL := account.GetGeminiBaseURL(geminicli.AIStudioBaseURL)
+ normalizedBaseURL, err := s.validateUpstreamBaseURL(baseURL)
+ if err != nil {
+ return nil, err
+ }
+ fullURL := strings.TrimRight(normalizedBaseURL, "/") + sanitizedPath
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ switch account.Type {
+ case AccountTypeAPIKey:
+ apiKey := strings.TrimSpace(account.GetCredential("api_key"))
+ if apiKey == "" {
+ return nil, errors.New("gemini api_key not configured")
+ }
+ req.Header.Set("x-goog-api-key", apiKey)
+ case AccountTypeOAuth:
+ if s.tokenProvider == nil {
+ return nil, errors.New("gemini token provider not configured")
+ }
+ accessToken, err := s.tokenProvider.GetAccessToken(ctx, account)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Authorization", "Bearer "+accessToken)
+ default:
+ return nil, fmt.Errorf("unsupported account type: %s", account.Type)
+ }
+
+ return s.doGeminiModelsGET(req, account)
+}
+
+// listVertexGeminiModels 读取 Vertex 服务账号在指定区域可用的 Gemini 模型。
+// 上游返回非 2xx 时 failure 为该页的原始响应,modelIDs 与 err 均为空。
+func (s *GeminiMessagesCompatService) listVertexGeminiModels(ctx context.Context, account *Account, location string) (modelIDs []string, failure *UpstreamHTTPResult, err error) {
+ if s.tokenProvider == nil {
+ return nil, nil, errors.New("gemini token provider not configured")
+ }
+ accessToken, err := s.tokenProvider.GetAccessToken(ctx, account)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ modelIDs, err = listVertexGeminiPublisherModels(location, func(_ int, listURL string) ([]byte, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, listURL, nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Authorization", "Bearer "+accessToken)
+
+ res, err := s.doGeminiModelsGET(req, account)
+ if err != nil {
+ return nil, err
+ }
+ if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusMultipleChoices {
+ failure = res
+ return nil, errGeminiModelsUpstreamStatus
+ }
+ return res.Body, nil
+ })
+ if failure != nil {
+ return nil, failure, nil
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+ return modelIDs, nil, nil
+}
+
+// doGeminiModelsGET 发送模型接口请求并读取响应。响应体上限取 gateway.models_list_read_max_bytes,超出时报错;响应头按配置过滤。
+func (s *GeminiMessagesCompatService) doGeminiModelsGET(req *http.Request, account *Account) (*UpstreamHTTPResult, error) {
+ var proxyURL string
+ if account.ProxyID != nil && account.Proxy != nil {
+ proxyURL = account.Proxy.URL()
+ }
+
+ resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ bodyLimit := resolveModelsListReadLimit(s.cfg)
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1))
+ if int64(len(body)) > bodyLimit {
+ return nil, fmt.Errorf("upstream model list response exceeds %d bytes", bodyLimit)
+ }
+ wwwAuthenticate := resp.Header.Get("Www-Authenticate")
+ filteredHeaders := responseheaders.FilterHeaders(resp.Header, s.responseHeaderFilter)
+ if wwwAuthenticate != "" {
+ filteredHeaders.Set("Www-Authenticate", wwwAuthenticate)
+ }
+ return &UpstreamHTTPResult{
+ StatusCode: resp.StatusCode,
+ Headers: filteredHeaders,
+ Body: body,
+ }, nil
+}
+
+// geminiModelsJSONResult 把网关生成的模型接口响应包装成 UpstreamHTTPResult,交给 handler 统一写出。
+func geminiModelsJSONResult(status int, payload any) (*UpstreamHTTPResult, error) {
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return nil, err
+ }
+ return &UpstreamHTTPResult{
+ StatusCode: status,
+ Headers: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}},
+ Body: body,
+ }, nil
+}
diff --git a/backend/internal/service/gemini_models_endpoints_test.go b/backend/internal/service/gemini_models_endpoints_test.go
new file mode 100644
index 000000000..f809811df
--- /dev/null
+++ b/backend/internal/service/gemini_models_endpoints_test.go
@@ -0,0 +1,208 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/pkg/gemini"
+ "github.com/stretchr/testify/require"
+)
+
+func newGeminiModelsEndpointsTestService(accounts []Account, upstream HTTPUpstream) *GeminiMessagesCompatService {
+ repo := &mockAccountRepoForGemini{listByGroupFunc: func(context.Context, int64, []string) ([]Account, error) {
+ return accounts, nil
+ }}
+ return &GeminiMessagesCompatService{
+ accountRepo: repo,
+ httpUpstream: upstream,
+ cfg: &config.Config{},
+ tokenProvider: NewGeminiTokenProvider(nil, &vertexModelsTokenCacheStub{token: "ya29.vertex-token"}, nil),
+ }
+}
+
+func decodeGeminiModelNames(t *testing.T, body []byte) []string {
+ t.Helper()
+ var got gemini.ModelsListResponse
+ require.NoError(t, json.Unmarshal(body, &got))
+ names := make([]string, 0, len(got.Models))
+ for _, model := range got.Models {
+ require.Contains(t, model.SupportedGenerationMethods, "generateContent")
+ names = append(names, model.Name)
+ }
+ return names
+}
+
+func TestSelectAccountForModelsEndpoints_VertexServiceAccountOnlyGroup(t *testing.T) {
+ groupID := int64(8)
+ vertex := *vertexModelSyncTestAccount(nil)
+ vertex.ID = 18
+ svc := newGeminiModelsEndpointsTestService([]Account{vertex}, nil)
+
+ account, err := svc.SelectAccountForModelsEndpoints(context.Background(), &groupID)
+ require.NoError(t, err)
+ require.Equal(t, int64(18), account.ID)
+}
+
+func TestModelsEndpointAccountRank_Order(t *testing.T) {
+ ordered := []*Account{
+ {Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k"}},
+ {Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{}},
+ {Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{"project_id": "p", "oauth_type": "ai_studio"}},
+ {Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{"project_id": "p", "oauth_type": "code_assist"}},
+ {Platform: PlatformGemini, Type: AccountTypeUpstream, Credentials: map[string]any{"api_key": "k"}},
+ vertexModelSyncTestAccount(nil),
+ {Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"auth_mode": "apikey", "api_key": "AQ.k"}},
+ }
+ for i := 1; i < len(ordered); i++ {
+ require.Less(t, modelsEndpointAccountRank(ordered[i-1]), modelsEndpointAccountRank(ordered[i]), "position %d", i)
+ }
+}
+
+func TestSelectAccountForModelsEndpoints_PrefersAPIKeyOverVertex(t *testing.T) {
+ groupID := int64(8)
+ vertex := *vertexModelSyncTestAccount(nil)
+ vertex.ID = 18
+ apiKey := Account{ID: 19, Platform: PlatformGemini, Type: AccountTypeAPIKey, Priority: 9, Credentials: map[string]any{"api_key": "k"}}
+ svc := newGeminiModelsEndpointsTestService([]Account{vertex, apiKey}, nil)
+
+ account, err := svc.SelectAccountForModelsEndpoints(context.Background(), &groupID)
+ require.NoError(t, err)
+ require.Equal(t, int64(19), account.ID)
+}
+
+func TestForwardListModels_VertexServiceAccountReturnsAIStudioFormat(t *testing.T) {
+ upstream := &httpUpstreamRecorder{responses: []*http.Response{
+ vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[
+ {"name":"publishers/google/models/gemini-3.8-flash"},
+ {"name":"publishers/google/models/gemma4"}
+ ],"nextPageToken":"page-2"}`),
+ vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-2.5-flash"}]}`),
+ }}
+ svc := newGeminiModelsEndpointsTestService(nil, upstream)
+
+ res, err := svc.ForwardListModels(context.Background(), vertexModelSyncTestAccount(map[string]any{"location": "europe-west4"}))
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, res.StatusCode)
+ require.Equal(t, []string{"models/gemini-2.5-flash", "models/gemini-3.8-flash"}, decodeGeminiModelNames(t, res.Body))
+
+ require.Len(t, upstream.requests, 2)
+ require.Equal(t, "https://europe-west4-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", upstream.requests[0].URL.String())
+ require.Equal(t, "https://europe-west4-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300&pageToken=page-2", upstream.requests[1].URL.String())
+ for _, req := range upstream.requests {
+ require.Equal(t, "Bearer ya29.vertex-token", req.Header.Get("Authorization"))
+ }
+}
+
+func TestForwardListModels_VertexUpstreamErrorPassesThrough(t *testing.T) {
+ body := `{"error":{"code":403,"status":"PERMISSION_DENIED"}}`
+ upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusForbidden, body)}
+ svc := newGeminiModelsEndpointsTestService(nil, upstream)
+
+ res, err := svc.ForwardListModels(context.Background(), vertexModelSyncTestAccount(map[string]any{"location": "global"}))
+ require.NoError(t, err)
+ require.Equal(t, http.StatusForbidden, res.StatusCode)
+ require.JSONEq(t, body, string(res.Body))
+}
+
+func TestForwardListModels_VertexAPIKeyReturnsBuiltinList(t *testing.T) {
+ upstream := &httpUpstreamRecorder{}
+ svc := newGeminiModelsEndpointsTestService(nil, upstream)
+ account := &Account{ID: 174, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{
+ "auth_mode": "apikey",
+ "api_key": "AQ.test-key",
+ }}
+
+ res, err := svc.ForwardListModels(context.Background(), account)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, res.StatusCode)
+ expected, err := json.Marshal(gemini.FallbackModelsList())
+ require.NoError(t, err)
+ require.JSONEq(t, string(expected), string(res.Body))
+ require.Empty(t, upstream.requests)
+}
+
+func TestForwardListModels_APIKeyForwardsToBaseURL(t *testing.T) {
+ upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"models":[{"name":"models/gemini-native"}]}`)}
+ svc := newGeminiModelsEndpointsTestService(nil, upstream)
+ account := &Account{ID: 261, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "api_key": "sk-pool",
+ "base_url": "https://relay.example.com",
+ }}
+
+ res, err := svc.ForwardListModels(context.Background(), account)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, res.StatusCode)
+ require.JSONEq(t, `{"models":[{"name":"models/gemini-native"}]}`, string(res.Body))
+ require.Equal(t, "https://relay.example.com/v1beta/models", upstream.lastReq.URL.String())
+ require.Equal(t, "sk-pool", upstream.lastReq.Header.Get("x-goog-api-key"))
+}
+
+func TestForwardGetModel_VertexServiceAccountLooksUpModelList(t *testing.T) {
+ listBody := `{"publisherModels":[{"name":"publishers/google/models/gemini-3.8-flash"}]}`
+
+ t.Run("listed model", func(t *testing.T) {
+ upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, listBody)}
+ svc := newGeminiModelsEndpointsTestService(nil, upstream)
+
+ res, err := svc.ForwardGetModel(context.Background(), vertexModelSyncTestAccount(nil), "gemini-3.8-flash")
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, res.StatusCode)
+ var model gemini.Model
+ require.NoError(t, json.Unmarshal(res.Body, &model))
+ require.Equal(t, "models/gemini-3.8-flash", model.Name)
+ })
+
+ t.Run("unlisted model", func(t *testing.T) {
+ upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, listBody)}
+ svc := newGeminiModelsEndpointsTestService(nil, upstream)
+
+ res, err := svc.ForwardGetModel(context.Background(), vertexModelSyncTestAccount(nil), "gemini-unknown")
+ require.NoError(t, err)
+ require.Equal(t, http.StatusNotFound, res.StatusCode)
+ require.JSONEq(t, `{"error":{"code":404,"message":"models/gemini-unknown is not found","status":"NOT_FOUND"}}`, string(res.Body))
+ })
+}
+
+func TestForwardGetModel_VertexUsesModelLocation(t *testing.T) {
+ upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-3.8-flash"}]}`)}
+ svc := newGeminiModelsEndpointsTestService(nil, upstream)
+ account := vertexModelSyncTestAccount(map[string]any{
+ "location": "europe-west4",
+ "vertex_model_locations": map[string]any{"gemini-3.8-flash": "global"},
+ })
+
+ res, err := svc.ForwardGetModel(context.Background(), account, "gemini-3.8-flash")
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, res.StatusCode)
+ require.Equal(t, "https://aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", upstream.lastReq.URL.String())
+}
+
+func TestForwardListModels_VertexMidPaginationErrorPassesThrough(t *testing.T) {
+ body := `{"error":{"code":503,"status":"UNAVAILABLE"}}`
+ upstream := &httpUpstreamRecorder{responses: []*http.Response{
+ vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-3.8-flash"}],"nextPageToken":"page-2"}`),
+ vertexModelsJSONResponse(http.StatusServiceUnavailable, body),
+ }}
+ svc := newGeminiModelsEndpointsTestService(nil, upstream)
+
+ res, err := svc.ForwardListModels(context.Background(), vertexModelSyncTestAccount(nil))
+ require.NoError(t, err)
+ require.Equal(t, http.StatusServiceUnavailable, res.StatusCode)
+ require.JSONEq(t, body, string(res.Body))
+ require.Len(t, upstream.requests, 2)
+}
+
+func TestForwardListModels_ResponseOverReadLimitFails(t *testing.T) {
+ upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"models":[{"name":"models/gemini-native"}]}`)}
+ svc := newGeminiModelsEndpointsTestService(nil, upstream)
+ svc.cfg.Gateway.ModelsListReadMaxBytes = 16
+ account := &Account{ID: 261, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-pool"}}
+
+ _, err := svc.ForwardListModels(context.Background(), account)
+ require.ErrorContains(t, err, "exceeds 16 bytes")
+}
diff --git a/backend/internal/service/gemini_native_reasoning_pricing_test.go b/backend/internal/service/gemini_native_reasoning_pricing_test.go
index f6565cfa7..c978331a4 100644
--- a/backend/internal/service/gemini_native_reasoning_pricing_test.go
+++ b/backend/internal/service/gemini_native_reasoning_pricing_test.go
@@ -137,7 +137,7 @@ func TestGeminiNativeReasoningPricingUsesExplicitForwardedLevel(t *testing.T) {
}
}
-func TestGeminiChatCompatReasoningPricingIgnoresUnforwardedEffort(t *testing.T) {
+func TestGeminiChatCompatReasoningPricingUsesForwardedEffort(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, stream := range []bool{false, true} {
mode := "buffered"
@@ -168,8 +168,9 @@ func TestGeminiChatCompatReasoningPricingIgnoresUnforwardedEffort(t *testing.T)
require.NoError(t, err)
require.Equal(t, http.StatusOK, recorder.Code)
require.Len(t, upstream.requestBodies, 1)
- require.False(t, gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig").Exists())
- require.Nil(t, result.ReasoningEffort)
+ require.Equal(t, "high", gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig.thinkingLevel").String())
+ require.Equal(t, stream, gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig.includeThoughts").Bool())
+ require.Equal(t, "high", optionalStringValue(result.ReasoningEffort))
billing := NewBillingService(&config.Config{}, nil)
cost, err := billing.CalculateTokenCostForRequest(TokenCostRequest{
@@ -184,7 +185,7 @@ func TestGeminiChatCompatReasoningPricingIgnoresUnforwardedEffort(t *testing.T)
Resolver: NewModelPricingResolver(nil, billing),
})
require.NoError(t, err)
- require.InDelta(t, 1, cost.TotalCost, 1e-12)
+ require.InDelta(t, 2, cost.TotalCost, 1e-12)
})
}
}
diff --git a/backend/internal/service/gemini_quota.go b/backend/internal/service/gemini_quota.go
index d9f2e3734..118f02d9f 100644
--- a/backend/internal/service/gemini_quota.go
+++ b/backend/internal/service/gemini_quota.go
@@ -373,6 +373,10 @@ func geminiQuotaTierKeyForAccount(account *Account) string {
if account == nil || account.Platform != PlatformGemini {
return ""
}
+ // 本地模拟配额只适用于按 Google 账号等级限额的通道;第三方上游与 Vertex 按量付费不套用。
+ if account.IsGeminiThirdPartyAPIKey() || account.IsVertexServiceAccount() {
+ return ""
+ }
// Note: GeminiOAuthType() already defaults legacy (project_id present) to code_assist.
oauthType := strings.ToLower(strings.TrimSpace(account.GeminiOAuthType()))
diff --git a/backend/internal/service/gemini_quota_test.go b/backend/internal/service/gemini_quota_test.go
new file mode 100644
index 000000000..a9287a11d
--- /dev/null
+++ b/backend/internal/service/gemini_quota_test.go
@@ -0,0 +1,80 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/stretchr/testify/require"
+)
+
+func TestAccountIsGeminiThirdPartyAPIKey(t *testing.T) {
+ tests := []struct {
+ name string
+ account *Account
+ expected bool
+ }{
+ {"nil_account", nil, false},
+ {"empty_base_url_is_official", geminiQuotaAPIKeyAccount(""), false},
+ {"official_base_url", geminiQuotaAPIKeyAccount("https://generativelanguage.googleapis.com"), false},
+ {"official_base_url_trailing_slash", geminiQuotaAPIKeyAccount("https://generativelanguage.googleapis.com/"), false},
+ {"official_host_over_http", geminiQuotaAPIKeyAccount("http://generativelanguage.googleapis.com"), true},
+ {"official_host_with_path_prefix", geminiQuotaAPIKeyAccount("https://generativelanguage.googleapis.com/proxy"), true},
+ {"relay_base_url", geminiQuotaAPIKeyAccount("https://relay.example.com"), true},
+ {"oauth_account", &Account{Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{"base_url": "https://relay.example.com"}}, false},
+ {"vertex_service_account", &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount}, false},
+ {"non_gemini_platform", &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "https://relay.example.com"}}, false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ require.Equal(t, tt.expected, tt.account.IsGeminiThirdPartyAPIKey())
+ })
+ }
+}
+
+func TestGeminiQuotaService_QuotaForAccountSkipsThirdPartyAndVertex(t *testing.T) {
+ svc := NewGeminiQuotaService(&config.Config{}, nil)
+ ctx := context.Background()
+
+ quota, ok := svc.QuotaForAccount(ctx, geminiQuotaAPIKeyAccount(""))
+ require.True(t, ok)
+ require.Equal(t, int64(50), quota.ProRPD)
+
+ paid := geminiQuotaAPIKeyAccount("https://generativelanguage.googleapis.com")
+ paid.Credentials["tier_id"] = GeminiTierAIStudioPaid
+ quota, ok = svc.QuotaForAccount(ctx, paid)
+ require.True(t, ok)
+ require.Equal(t, int64(-1), quota.ProRPD)
+
+ relay := geminiQuotaAPIKeyAccount("https://relay.example.com")
+ relay.Credentials["tier_id"] = GeminiTierAIStudioFree
+ _, ok = svc.QuotaForAccount(ctx, relay)
+ require.False(t, ok, "第三方上游不套用 AI Studio 模拟配额")
+
+ vertex := &Account{
+ Platform: PlatformGemini,
+ Type: AccountTypeServiceAccount,
+ Credentials: map[string]any{"project_id": "my-project", "tier_id": "vertex"},
+ }
+ _, ok = svc.QuotaForAccount(ctx, vertex)
+ require.False(t, ok, "Vertex 按量付费不套用模拟配额")
+
+ googleOne := &Account{
+ Platform: PlatformGemini,
+ Type: AccountTypeOAuth,
+ Credentials: map[string]any{"oauth_type": "google_one", "tier_id": GeminiTierGoogleOneFree},
+ }
+ quota, ok = svc.QuotaForAccount(ctx, googleOne)
+ require.True(t, ok)
+ require.Positive(t, quota.SharedRPD)
+}
+
+func geminiQuotaAPIKeyAccount(baseURL string) *Account {
+ credentials := map[string]any{}
+ if baseURL != "" {
+ credentials["base_url"] = baseURL
+ }
+ return &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: credentials}
+}
diff --git a/backend/internal/service/gemini_vertex_api_key_forward_test.go b/backend/internal/service/gemini_vertex_api_key_forward_test.go
new file mode 100644
index 000000000..936c586b3
--- /dev/null
+++ b/backend/internal/service/gemini_vertex_api_key_forward_test.go
@@ -0,0 +1,165 @@
+//go:build unit
+
+package service
+
+import (
+ "bytes"
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/pkg/tlsfingerprint"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+const geminiVertexAPIKeyTestResponse = `{"candidates":[{"content":{"parts":[{"text":"hello"}],"role":"model"},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5,"totalTokenCount":15}}`
+
+func newGeminiVertexAPIKeyTestService() (*GeminiMessagesCompatService, *geminiCompatHTTPUpstreamStub) {
+ httpStub := &geminiCompatHTTPUpstreamStub{
+ response: &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"vertex-req-1"}},
+ Body: io.NopCloser(strings.NewReader(geminiVertexAPIKeyTestResponse)),
+ },
+ }
+ // tokenProvider 留空:API Key 认证不依赖 access token。
+ return &GeminiMessagesCompatService{httpUpstream: httpStub, cfg: &config.Config{}}, httpStub
+}
+
+func geminiVertexAPIKeyTestAccount(projectID string) *Account {
+ credentials := map[string]any{
+ "auth_mode": "apikey",
+ "api_key": "vertex-test-key",
+ "location": "us-central1",
+ "tier_id": "vertex",
+ }
+ if projectID != "" {
+ credentials["project_id"] = projectID
+ }
+ return &Account{
+ ID: 811,
+ Platform: PlatformGemini,
+ Type: AccountTypeServiceAccount,
+ Credentials: credentials,
+ Concurrency: 1,
+ }
+}
+
+func requireVertexAPIKeyAuth(t *testing.T, req *http.Request) {
+ t.Helper()
+ require.NotNil(t, req)
+ require.Equal(t, "vertex-test-key", req.Header.Get("x-goog-api-key"))
+ require.Empty(t, req.Header.Get("Authorization"))
+}
+
+func TestGeminiForwardNative_VertexAPIKeyWithoutProjectUsesExpressEndpoint(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ svc, httpStub := newGeminiVertexAPIKeyTestService()
+ c, _ := newGeminiNativeTestContext(t)
+
+ result, err := svc.ForwardNative(context.Background(), c, geminiVertexAPIKeyTestAccount(""),
+ "gemini-3-flash-preview", "generateContent", false, []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`))
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Equal(t, 1, httpStub.calls)
+ require.Equal(t, "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3-flash-preview:generateContent", httpStub.lastReq.URL.String())
+ requireVertexAPIKeyAuth(t, httpStub.lastReq)
+}
+
+func TestGeminiMessagesCompatServiceForward_VertexAPIKeyWithProjectUsesProjectEndpoint(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ svc, httpStub := newGeminiVertexAPIKeyTestService()
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
+ body := []byte(`{"model":"gemini-3-flash-preview","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`)
+
+ result, err := svc.Forward(context.Background(), c, geminiVertexAPIKeyTestAccount("my-project"), body)
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Equal(t, "https://us-central1-aiplatform.googleapis.com/v1/projects/my-project/locations/us-central1/publishers/google/models/gemini-3-flash-preview:generateContent", httpStub.lastReq.URL.String())
+ requireVertexAPIKeyAuth(t, httpStub.lastReq)
+}
+
+func TestGeminiForwardAsChatCompletions_VertexAPIKeyUsesAPIKeyHeader(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ svc, httpStub := newGeminiVertexAPIKeyTestService()
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ body := []byte(`{"model":"gemini-3-flash-preview","messages":[{"role":"user","content":"hi"}]}`)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
+
+ result, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiVertexAPIKeyTestAccount(""), body)
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Equal(t, "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3-flash-preview:generateContent", httpStub.lastReq.URL.String())
+ requireVertexAPIKeyAuth(t, httpStub.lastReq)
+}
+
+type geminiVertex429SequenceUpstream struct {
+ responses []*http.Response
+ calls int
+}
+
+func (s *geminiVertex429SequenceUpstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) {
+ resp := s.responses[min(s.calls, len(s.responses)-1)]
+ s.calls++
+ return resp, nil
+}
+
+func (s *geminiVertex429SequenceUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
+ return s.Do(req, proxyURL, accountID, accountConcurrency)
+}
+
+// Vertex 共享容量不足的 429 在同一账号上退避重试,成功后账号状态不变;绑定显式缓存的请求同样如此。
+func TestGeminiForwardNative_VertexSharedCapacity429RetriesSameAccountWithoutCooldown(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ sharedCapacity := `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}`
+ tests := []struct {
+ name string
+ ctx context.Context
+ }{
+ {name: "unbound", ctx: context.Background()},
+ {name: "bound_cached_content", ctx: WithGeminiCachedContentBound(context.Background())},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ upstream := &geminiVertex429SequenceUpstream{responses: []*http.Response{
+ {
+ StatusCode: http.StatusTooManyRequests,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(sharedCapacity)),
+ },
+ {
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(geminiVertexAPIKeyTestResponse)),
+ },
+ }}
+ repo := &geminiBoundCacheRateLimitRepo{}
+ svc := &GeminiMessagesCompatService{
+ httpUpstream: upstream,
+ cfg: &config.Config{},
+ accountRepo: repo,
+ rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil),
+ }
+ c, rec := newGeminiNativeTestContext(t)
+
+ result, err := svc.ForwardNative(tt.ctx, c, geminiVertexAPIKeyTestAccount("my-project"),
+ "gemini-3.7-flash", "generateContent", false, []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`))
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Equal(t, 2, upstream.calls, "429 后在同一账号上重试")
+ require.Zero(t, repo.rateLimitedCalls, "不写账号级限流")
+ require.Zero(t, repo.tempCalls)
+ require.Zero(t, repo.setErrCalls)
+ require.Empty(t, repo.modelRateLimitCalls)
+ })
+ }
+}
diff --git a/backend/internal/service/gemini_vertex_token_error.go b/backend/internal/service/gemini_vertex_token_error.go
new file mode 100644
index 000000000..7577dcca5
--- /dev/null
+++ b/backend/internal/service/gemini_vertex_token_error.go
@@ -0,0 +1,60 @@
+package service
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+)
+
+// vertexServiceAccountNotFoundReason 标识换取 SA access token 时 SA 已不存在。
+const vertexServiceAccountNotFoundReason GatewayFailureReason = "vertex_service_account_not_found"
+
+// geminiVertexCredentialFailoverBody 是 SA 凭据失效时挂在 failover 错误上的 Google 格式错误体,
+// 供 handler 在换号耗尽后做透传规则匹配与错误信息提取。
+var geminiVertexCredentialFailoverBody = []byte(`{"error":{"code":401,"message":"Upstream authentication failed","status":"UNAUTHENTICATED"}}`)
+
+// handleVertexServiceAccountNotFound 处理 Gemini 三条转发路径(原生 / Claude 兼容 /
+// Chat Completions 兼容)构造上游请求时换取 SA access token 失败、且 SA 已不存在的情况:
+//
+// - 账号置为 error 并停止调度,错误信息带上 token 端点的 error_description;
+// - 记录凭据获取阶段(stage=account_auth)的 Ops 事件,token 端点的状态码只出现在 Message 中;
+// - 返回 *UpstreamFailoverError(401),由 handler 的 failover 循环换号。
+//
+// 不是该类失败时返回 nil,由调用方继续处理。本函数不写响应。
+func (s *GeminiMessagesCompatService) handleVertexServiceAccountNotFound(ctx context.Context, c *gin.Context, account *Account, err error) *UpstreamFailoverError {
+ tokenErr, ok := vertexServiceAccountNotFoundError(err)
+ if !ok {
+ return nil
+ }
+
+ msg := "Service account token rejected (400): " + tokenErr.Description
+ stateCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), openAIAccountStateUpdateTimeout)
+ defer cancel()
+ if s.rateLimitService != nil {
+ s.rateLimitService.handleAuthError(stateCtx, account, msg)
+ } else if s.accountRepo != nil {
+ if setErr := s.accountRepo.SetError(stateCtx, account.ID, msg); setErr != nil {
+ slog.Warn("account_set_error_failed", "account_id", account.ID, "error", setErr)
+ }
+ }
+
+ event := OpsUpstreamErrorEvent{
+ Platform: account.Platform,
+ AccountID: account.ID,
+ AccountName: account.Name,
+ Kind: "failover",
+ Stage: string(GatewayFailureStageAccountAuth),
+ Scope: string(GatewayFailureScopeAccount),
+ Reason: string(vertexServiceAccountNotFoundReason),
+ Message: sanitizeUpstreamErrorMessage(err.Error()),
+ }
+ event.ProxyID, event.ProxyName = opsUpstreamProxyAttribution(account)
+ appendOpsUpstreamError(c, event)
+
+ return &UpstreamFailoverError{
+ StatusCode: http.StatusUnauthorized,
+ ResponseBody: geminiVertexCredentialFailoverBody,
+ }
+}
diff --git a/backend/internal/service/gemini_vertex_token_error_test.go b/backend/internal/service/gemini_vertex_token_error_test.go
new file mode 100644
index 000000000..b5eacfafd
--- /dev/null
+++ b/backend/internal/service/gemini_vertex_token_error_test.go
@@ -0,0 +1,207 @@
+//go:build unit
+
+package service
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/x509"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+// ---------------------------------------------------------------------------
+// 换取 SA access token 时 SA 已不存在(token 端点 400 invalid_grant
+// "Invalid grant: account not found")的契约,三条转发路径一致:
+// - 账号置为 error 并停止调度,错误信息带 token 端点的 error_description;
+// - 不发出上游请求,返回 *UpstreamFailoverError(401) 交给 handler 换号,service 不写响应;
+// - Ops 事件记为凭据获取阶段(stage=account_auth);
+// - 其他换 token 失败不改账号状态、不换号,直接回写 502。
+// ---------------------------------------------------------------------------
+
+const vertexAccountNotFoundTokenBody = `{"error":"invalid_grant","error_description":"Invalid grant: account not found"}`
+
+func newVertexTokenTestAccount(t *testing.T) *Account {
+ t.Helper()
+ privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+ require.NoError(t, err)
+ pemBytes := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})
+ saJSON, err := json.Marshal(map[string]string{
+ "type": "service_account",
+ "project_id": "proj-1",
+ "private_key_id": "kid-1",
+ "private_key": string(pemBytes),
+ "client_email": "svc@proj-1.iam.gserviceaccount.com",
+ })
+ require.NoError(t, err)
+ return &Account{
+ ID: 820,
+ Platform: PlatformGemini,
+ Type: AccountTypeServiceAccount,
+ Credentials: map[string]any{
+ "service_account_json": string(saJSON),
+ "project_id": "proj-1",
+ "location": "global",
+ },
+ }
+}
+
+func useVertexTokenEndpoint(t *testing.T, status int, body string) {
+ t.Helper()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(body))
+ }))
+ t.Cleanup(server.Close)
+ original := vertexServiceAccountTokenURL
+ vertexServiceAccountTokenURL = server.URL
+ t.Cleanup(func() { vertexServiceAccountTokenURL = original })
+}
+
+func newVertexTokenErrorService() (*GeminiMessagesCompatService, *geminiCompatHTTPUpstreamStub, *errorPolicyRepoStub) {
+ repo := &errorPolicyRepoStub{}
+ httpStub := &geminiCompatHTTPUpstreamStub{}
+ svc := &GeminiMessagesCompatService{
+ accountRepo: repo,
+ httpUpstream: httpStub,
+ tokenProvider: NewGeminiTokenProvider(repo, nil, nil),
+ rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil),
+ cfg: &config.Config{},
+ }
+ return svc, httpStub, repo
+}
+
+func requireVertexAccountNotFoundHandled(t *testing.T, c *gin.Context, err error, httpStub *geminiCompatHTTPUpstreamStub, repo *errorPolicyRepoStub) {
+ t.Helper()
+ var failoverErr *UpstreamFailoverError
+ require.True(t, errors.As(err, &failoverErr), "SA 不存在应换号,got %T: %v", err, err)
+ require.Equal(t, http.StatusUnauthorized, failoverErr.StatusCode)
+ require.Equal(t, string(geminiVertexCredentialFailoverBody), string(failoverErr.ResponseBody))
+ require.True(t, failoverErr.ShouldRetryNextAccount())
+ require.False(t, failoverErr.RetryableOnSameAccount)
+
+ require.Equal(t, 1, repo.setErrCalls, "SA 不存在应把账号置为 error")
+ require.Equal(t, "Service account token rejected (400): Invalid grant: account not found", repo.lastErrorMsg)
+ require.Zero(t, httpStub.calls, "换不到 token 时不应发出上游请求")
+ require.False(t, c.Writer.Written(), "换号场景不应写客户端响应")
+
+ raw, ok := c.Get(OpsUpstreamErrorsKey)
+ require.True(t, ok, "应记录 ops 上游错误事件")
+ events := raw.([]*OpsUpstreamErrorEvent)
+ require.Len(t, events, 1)
+ require.Equal(t, "failover", events[0].Kind)
+ require.Equal(t, int64(820), events[0].AccountID)
+ require.Equal(t, string(GatewayFailureStageAccountAuth), events[0].Stage)
+ require.Equal(t, string(GatewayFailureScopeAccount), events[0].Scope)
+ require.Equal(t, string(vertexServiceAccountNotFoundReason), events[0].Reason)
+ require.Zero(t, events[0].UpstreamStatusCode, "换 token 失败不占用上游状态码")
+ require.Contains(t, events[0].Message, "service account token request returned 400: Invalid grant: account not found")
+}
+
+func TestExchangeVertexServiceAccountToken_AccountNotFoundIsRecognized(t *testing.T) {
+ useVertexTokenEndpoint(t, http.StatusBadRequest, vertexAccountNotFoundTokenBody)
+ key, err := parseVertexServiceAccountKey(newVertexTokenTestAccount(t))
+ require.NoError(t, err)
+
+ _, _, err = exchangeVertexServiceAccountToken(contextWithTestTimeout(t), key, "")
+
+ require.EqualError(t, err, "service account token request returned 400: Invalid grant: account not found")
+ tokenErr, ok := vertexServiceAccountNotFoundError(fmt.Errorf("build request: %w", err))
+ require.True(t, ok)
+ require.Equal(t, "invalid_grant", tokenErr.Code)
+ require.Equal(t, "Invalid grant: account not found", tokenErr.Description)
+}
+
+func TestVertexServiceAccountNotFoundError_OnlyMatchesAccountNotFound(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ }{
+ {"other_invalid_grant", &vertexTokenRequestError{StatusCode: 400, Code: "invalid_grant", Description: "Invalid JWT Signature."}},
+ {"not_400", &vertexTokenRequestError{StatusCode: 401, Code: "invalid_grant", Description: "Invalid grant: account not found"}},
+ {"other_code", &vertexTokenRequestError{StatusCode: 400, Code: "invalid_request", Description: "Invalid grant: account not found"}},
+ {"server_error", &vertexTokenRequestError{StatusCode: 500, Message: "backend error"}},
+ {"plain_error", errors.New("service account token request returned 400: Invalid grant: account not found")},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ _, ok := vertexServiceAccountNotFoundError(tt.err)
+ require.False(t, ok)
+ })
+ }
+}
+
+func TestGeminiForwardNative_VertexServiceAccountNotFoundDisablesAndFailsOver(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ useVertexTokenEndpoint(t, http.StatusBadRequest, vertexAccountNotFoundTokenBody)
+ svc, httpStub, repo := newVertexTokenErrorService()
+ c, _ := newGeminiNativeTestContext(t)
+
+ result, err := svc.ForwardNative(context.Background(), c, newVertexTokenTestAccount(t),
+ "gemini-3.8-flash", "streamGenerateContent", true, []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`))
+
+ require.Nil(t, result)
+ requireVertexAccountNotFoundHandled(t, c, err, httpStub, repo)
+}
+
+func TestGeminiForward_VertexServiceAccountNotFoundDisablesAndFailsOver(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ useVertexTokenEndpoint(t, http.StatusBadRequest, vertexAccountNotFoundTokenBody)
+ svc, httpStub, repo := newVertexTokenErrorService()
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ body := []byte(`{"model":"gemini-3.8-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body))
+
+ result, err := svc.Forward(context.Background(), c, newVertexTokenTestAccount(t), body)
+
+ require.Nil(t, result)
+ requireVertexAccountNotFoundHandled(t, c, err, httpStub, repo)
+}
+
+func TestGeminiForwardAsChatCompletions_VertexServiceAccountNotFoundDisablesAndFailsOver(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ useVertexTokenEndpoint(t, http.StatusBadRequest, vertexAccountNotFoundTokenBody)
+ svc, httpStub, repo := newVertexTokenErrorService()
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ body := []byte(`{"model":"gemini-3.8-flash","messages":[{"role":"user","content":"hi"}]}`)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
+
+ result, err := svc.ForwardAsChatCompletions(context.Background(), c, newVertexTokenTestAccount(t), body)
+
+ require.Nil(t, result)
+ requireVertexAccountNotFoundHandled(t, c, err, httpStub, repo)
+}
+
+func TestGeminiForwardNative_OtherVertexTokenErrorKeepsAccountState(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ useVertexTokenEndpoint(t, http.StatusBadRequest, `{"error":"invalid_grant","error_description":"Invalid JWT Signature."}`)
+ svc, httpStub, repo := newVertexTokenErrorService()
+ c, rec := newGeminiNativeTestContext(t)
+
+ result, err := svc.ForwardNative(context.Background(), c, newVertexTokenTestAccount(t),
+ "gemini-3.8-flash", "generateContent", false, []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`))
+
+ require.Nil(t, result)
+ require.Error(t, err)
+ var failoverErr *UpstreamFailoverError
+ require.False(t, errors.As(err, &failoverErr), "未识别的换 token 失败不换号")
+ require.Zero(t, repo.setErrCalls, "未识别的换 token 失败不改账号状态")
+ require.Zero(t, httpStub.calls)
+ require.Equal(t, http.StatusBadGateway, rec.Code)
+ require.True(t, strings.Contains(rec.Body.String(), "Invalid JWT Signature."))
+}
diff --git a/backend/internal/service/group.go b/backend/internal/service/group.go
index 822db11cd..df8395842 100644
--- a/backend/internal/service/group.go
+++ b/backend/internal/service/group.go
@@ -19,6 +19,7 @@ type Group struct {
ID int64
Name string
Description string
+ I18n GroupI18n // 名称与描述的界面语言译文;缺失的语言沿用 Name/Description
Platform string
RateMultiplier float64
// 高峰时段倍率:peak_rate_enabled 为 true 且当前时刻处于 [PeakStart, PeakEnd) 时,
diff --git a/backend/internal/service/group_i18n.go b/backend/internal/service/group_i18n.go
new file mode 100644
index 000000000..6483ead5c
--- /dev/null
+++ b/backend/internal/service/group_i18n.go
@@ -0,0 +1,64 @@
+package service
+
+import (
+ "fmt"
+ "maps"
+ "regexp"
+ "slices"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/MACOS-DO/sub4api/internal/domain"
+ infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+)
+
+type GroupI18n = domain.GroupI18n
+type GroupLocaleText = domain.GroupLocaleText
+
+// groupI18nNameMaxRunes 与 groups.name 的长度上限一致。
+const groupI18nNameMaxRunes = 100
+
+// 语言代码只校验 BCP 47 形态(en、zh、zh-TW);具体提供哪些语言由前端语言包决定。
+var groupI18nLocalePattern = regexp.MustCompile(`^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$`)
+
+// normalizeGroupI18n 把语言代码统一为 domain.CanonicalLocale 的写法,去除译文首尾空白,
+// 并丢弃名称与描述都为空的语言。统一写法后重复的语言代码(如 en 与 EN)直接拒绝,
+// 不在其中任选一份。返回值始终非 nil,落库为 JSON 对象。
+func normalizeGroupI18n(in GroupI18n) (GroupI18n, error) {
+ out := make(GroupI18n, len(in))
+ seen := make(map[string]struct{}, len(in))
+ for _, raw := range slices.Sorted(maps.Keys(in)) {
+ if !groupI18nLocalePattern.MatchString(raw) {
+ return nil, infraerrors.BadRequest("INVALID_GROUP_I18N", fmt.Sprintf("invalid locale %q in i18n", raw))
+ }
+ locale := domain.CanonicalLocale(raw)
+ if _, dup := seen[locale]; dup {
+ return nil, infraerrors.BadRequest("INVALID_GROUP_I18N", fmt.Sprintf("duplicate locale %q in i18n", locale))
+ }
+ seen[locale] = struct{}{}
+ text := in[raw]
+ name := strings.TrimSpace(text.Name)
+ description := strings.TrimSpace(text.Description)
+ if utf8.RuneCountInString(name) > groupI18nNameMaxRunes {
+ return nil, infraerrors.BadRequest("INVALID_GROUP_I18N", fmt.Sprintf("i18n name for locale %q must be at most %d characters", locale, groupI18nNameMaxRunes))
+ }
+ if name == "" && description == "" {
+ continue
+ }
+ out[locale] = GroupLocaleText{Name: name, Description: description}
+ }
+ return out, nil
+}
+
+// cloneGroupI18nForDuplicate 复制译文中的描述。名称译文不随复制带走:
+// 副本的 name 已改写,沿用源分组的名称译文会让两个分组在该语言下同名。
+func cloneGroupI18nForDuplicate(in GroupI18n) GroupI18n {
+ out := make(GroupI18n, len(in))
+ for locale, text := range in {
+ if text.Description == "" {
+ continue
+ }
+ out[locale] = GroupLocaleText{Description: text.Description}
+ }
+ return out
+}
diff --git a/backend/internal/service/group_i18n_test.go b/backend/internal/service/group_i18n_test.go
new file mode 100644
index 000000000..c3fd84eaf
--- /dev/null
+++ b/backend/internal/service/group_i18n_test.go
@@ -0,0 +1,83 @@
+package service
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestNormalizeGroupI18n(t *testing.T) {
+ t.Run("nil input yields an empty non-nil map", func(t *testing.T) {
+ got, err := normalizeGroupI18n(nil)
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Empty(t, got)
+ })
+
+ t.Run("trims text and drops locales with nothing left", func(t *testing.T) {
+ got, err := normalizeGroupI18n(GroupI18n{
+ "en": {Name: " Standard ", Description: "\tPro + Max pool\n"},
+ "zh": {Name: " ", Description: ""},
+ "zh-TW": {Description: "僅描述"},
+ })
+ require.NoError(t, err)
+ require.Equal(t, GroupI18n{
+ "en": {Name: "Standard", Description: "Pro + Max pool"},
+ "zh-TW": {Description: "僅描述"},
+ }, got)
+ })
+
+ t.Run("locale codes are stored in canonical case", func(t *testing.T) {
+ got, err := normalizeGroupI18n(GroupI18n{
+ "EN": {Name: "Standard"},
+ "zh-tw": {Name: "標準"},
+ })
+ require.NoError(t, err)
+ require.Equal(t, GroupI18n{
+ "en": {Name: "Standard"},
+ "zh-TW": {Name: "標準"},
+ }, got)
+ })
+
+ t.Run("rejects locales that collide after canonicalization", func(t *testing.T) {
+ for _, in := range []GroupI18n{
+ {"en": {Name: "English A"}, "EN": {Name: "English B"}},
+ {"zh-TW": {Name: "標準"}, "zh-tw": {}},
+ } {
+ _, err := normalizeGroupI18n(in)
+ require.Errorf(t, err, "input %v should be rejected", in)
+ }
+ })
+
+ t.Run("rejects malformed locale codes", func(t *testing.T) {
+ for _, locale := range []string{"", "e", "en_US", "en-", "中文", "en us"} {
+ _, err := normalizeGroupI18n(GroupI18n{locale: {Name: "x"}})
+ require.Errorf(t, err, "locale %q should be rejected", locale)
+ }
+ })
+
+ t.Run("name length is capped in characters like groups.name", func(t *testing.T) {
+ atLimit := strings.Repeat("名", groupI18nNameMaxRunes)
+ got, err := normalizeGroupI18n(GroupI18n{"zh": {Name: atLimit}})
+ require.NoError(t, err)
+ require.Equal(t, atLimit, got["zh"].Name)
+
+ _, err = normalizeGroupI18n(GroupI18n{"zh": {Name: atLimit + "名"}})
+ require.Error(t, err)
+ })
+}
+
+func TestCloneGroupI18nForDuplicate(t *testing.T) {
+ source := GroupI18n{
+ "en": {Name: "Standard", Description: "Pro + Max pool"},
+ "zh": {Name: "标准"},
+ }
+
+ got := cloneGroupI18nForDuplicate(source)
+
+ // 副本改了 name;名称译文若照搬,副本与源分组在该语言下会同名。
+ require.Equal(t, GroupI18n{"en": {Description: "Pro + Max pool"}}, got)
+ require.Equal(t, "Standard", source["en"].Name, "source must not be mutated")
+ require.NotNil(t, cloneGroupI18nForDuplicate(nil))
+}
diff --git a/backend/internal/service/model_plaza_service.go b/backend/internal/service/model_plaza_service.go
index 0f24a13f1..37ef1e303 100644
--- a/backend/internal/service/model_plaza_service.go
+++ b/backend/internal/service/model_plaza_service.go
@@ -40,6 +40,7 @@ type PlazaGroup struct {
ID int64
Name string
Description string
+ I18n GroupI18n
Platform string
SubscriptionType string
RateMultiplier float64
@@ -125,6 +126,7 @@ func (s *ModelPlazaService) ListGroups(ctx context.Context) ([]PlazaGroup, error
ID: g.ID,
Name: g.Name,
Description: g.Description,
+ I18n: g.I18n,
Platform: g.Platform,
SubscriptionType: g.SubscriptionType,
RateMultiplier: g.RateMultiplier,
diff --git a/backend/internal/service/model_rate_limit.go b/backend/internal/service/model_rate_limit.go
index 970139a58..56644ab75 100644
--- a/backend/internal/service/model_rate_limit.go
+++ b/backend/internal/service/model_rate_limit.go
@@ -79,7 +79,7 @@ func (a *Account) modelRateLimitKeysForRequest(ctx context.Context, requestedMod
keys := []string{modelKey}
switch a.Platform {
case PlatformAntigravity:
- if isAntigravityGeminiModel(modelKey) && modelKey != antigravityGeminiModelRateLimitKey {
+ if isAntigravityGeminiModel(modelKey) && !isAntigravityGeminiImageModel(modelKey) && modelKey != antigravityGeminiModelRateLimitKey {
keys = append(keys, antigravityGeminiModelRateLimitKey)
}
case PlatformOpenAI:
@@ -164,12 +164,17 @@ func antigravityModelRateLimitKeys(model string) []string {
return nil
}
keys := []string{model}
- if isAntigravityGeminiModel(model) && model != antigravityGeminiModelRateLimitKey {
+ if isAntigravityGeminiModel(model) && !isAntigravityGeminiImageModel(model) && model != antigravityGeminiModelRateLimitKey {
keys = append(keys, antigravityGeminiModelRateLimitKey)
}
return keys
}
+func isAntigravityGeminiImageModel(model string) bool {
+ normalized := normalizeAntigravityModelName(model)
+ return strings.HasPrefix(normalized, "gemini-") && strings.Contains(normalized, "-image")
+}
+
func (a *Account) modelRateLimitResetAt(scope string) *time.Time {
if a == nil || a.Extra == nil || scope == "" {
return nil
diff --git a/backend/internal/service/model_rate_limit_test.go b/backend/internal/service/model_rate_limit_test.go
index 22e64f6db..9e81d5be7 100644
--- a/backend/internal/service/model_rate_limit_test.go
+++ b/backend/internal/service/model_rate_limit_test.go
@@ -255,6 +255,31 @@ func TestIsModelRateLimited_OpenAIImageGenerationIntentBlocksTextModelImageTool(
require.True(t, account.isModelRateLimitedWithContext(WithOpenAIImageGenerationIntent(context.Background()), "gpt-5.4"))
}
+func TestIsModelRateLimited_AntigravityImageDoesNotInheritGeminiFamilyLimit(t *testing.T) {
+ future := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
+ account := &Account{
+ Platform: PlatformAntigravity,
+ Extra: map[string]any{
+ modelRateLimitsKey: map[string]any{
+ antigravityGeminiModelRateLimitKey: map[string]any{
+ "rate_limit_reset_at": future,
+ },
+ },
+ },
+ }
+
+ for _, model := range []string{"gemini-3.1-flash-image", "gemini-3.1-flash-image-preview", "gemini-3-pro-image"} {
+ require.False(t, account.isModelRateLimitedWithContext(context.Background(), model), model)
+ }
+ require.True(t, account.isModelRateLimitedWithContext(context.Background(), "gemini-3-flash"))
+ rawLimits, ok := account.Extra[modelRateLimitsKey].(map[string]any)
+ require.True(t, ok)
+ rawLimits["gemini-3.1-flash-image"] = map[string]any{
+ "rate_limit_reset_at": future,
+ }
+ require.True(t, account.isModelRateLimitedWithContext(context.Background(), "gemini-3-pro-image-preview"))
+}
+
func TestIsModelRateLimited_Antigravity_ThinkingAffectsModelKey(t *testing.T) {
now := time.Now()
future := now.Add(10 * time.Minute).Format(time.RFC3339)
diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go
index 99f017143..120f61c34 100644
--- a/backend/internal/service/openai_account_runtime_block_fastpath.go
+++ b/backend/internal/service/openai_account_runtime_block_fastpath.go
@@ -158,7 +158,8 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont
// Isolate a custom temporary-unschedulable match to the known upstream
// model before entering the generic account error path. This keeps the
// account available to other models and avoids the account runtime blocker.
- if s.rateLimitService != nil && statusCode != http.StatusUnauthorized && len(canonicalModel) > 0 && strings.TrimSpace(canonicalModel[0]) != "" &&
+ if s.rateLimitService != nil && len(canonicalModel) > 0 && strings.TrimSpace(canonicalModel[0]) != "" &&
+ tempUnschedRulesApply(account, statusCode, responseBody, canonicalModel[0]) &&
s.rateLimitService.HandleTempUnschedulable(stateCtx, account, statusCode, responseBody, canonicalModel[0]) {
return true
}
@@ -173,7 +174,8 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont
return false
}
shouldDisable := s.rateLimitService.HandleUpstreamError(stateCtx, account, statusCode, headers, responseBody)
- modelTempMatched := statusCode != http.StatusUnauthorized && tempUnschedulableModel(stateCtx, nil) != "" &&
+ tempModel := tempUnschedulableModel(stateCtx, nil)
+ modelTempMatched := tempModel != "" && tempUnschedRulesApply(account, statusCode, responseBody, tempModel) &&
len(matchTempUnschedulableRules(account, statusCode, responseBody)) > 0
if shouldDisable && !modelTempMatched {
s.BlockAccountScheduling(account, time.Time{}, "upstream_disable")
diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go
index 4f5b11666..6dfb99761 100644
--- a/backend/internal/service/openai_account_scheduler.go
+++ b/backend/internal/service/openai_account_scheduler.go
@@ -1815,7 +1815,7 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx con
}) {
return false, "shadow_parent_unhealthy"
}
- if req.RequestedModel != "" && !account.IsModelSupported(req.RequestedModel) {
+ if req.RequestedModel != "" && !supportsOpenAIRequestModel(account, req.RequestedModel, req.RequireCompact) {
return false, "model_not_supported"
}
if req.GroupID != nil && s != nil && s.service != nil &&
diff --git a/backend/internal/service/openai_account_scheduler_test.go b/backend/internal/service/openai_account_scheduler_test.go
index eb964dfac..8d0046def 100644
--- a/backend/internal/service/openai_account_scheduler_test.go
+++ b/backend/internal/service/openai_account_scheduler_test.go
@@ -48,6 +48,10 @@ func (r schedulerTestOpenAIAccountRepo) ListSchedulableByGroupID(ctx context.Con
return append([]Account(nil), r.accounts...), nil
}
+func (r schedulerTestOpenAIAccountRepo) ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, _ []string, _ bool) ([]Account, error) {
+ return r.ListSchedulableByGroupID(ctx, *groupID)
+}
+
func (r schedulerTestOpenAIAccountRepo) ListSchedulableByPlatform(ctx context.Context, platform string) ([]Account, error) {
var result []Account
for _, acc := range r.accounts {
diff --git a/backend/internal/service/openai_alpha_search_billing_test.go b/backend/internal/service/openai_alpha_search_billing_test.go
index 897623896..dfa1cfb5c 100644
--- a/backend/internal/service/openai_alpha_search_billing_test.go
+++ b/backend/internal/service/openai_alpha_search_billing_test.go
@@ -51,7 +51,7 @@ func TestCalculateOpenAIRecordUsageCostWebSearchPerCall(t *testing.T) {
// 即使 token 倍率(含高峰,3.0)更高也不采用。
apiKey := &APIKey{ID: 1, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformOpenAI}}
result := &OpenAIForwardResult{Model: "gpt-5.6-sol", UpstreamModel: "gpt-5.6-sol", WebSearchCalls: 1}
- cost, err := svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 3.0, 1.0, 1.0, 2.0, UsageTokens{}, "", boolPtr(false), time.Time{})
+ cost, err := svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 3.0, 1.0, 1.0, 2.0, UsageTokens{}, "", boolPtr(false), false, time.Time{})
require.NoError(t, err)
require.Equal(t, string(BillingModePerRequest), cost.BillingMode)
require.InDelta(t, 0.01, cost.TotalCost, 1e-12)
@@ -59,7 +59,7 @@ func TestCalculateOpenAIRecordUsageCostWebSearchPerCall(t *testing.T) {
// 分组配置单价 0.005
apiKey.Group.WebSearchPricePerCall = float64Ptr(0.005)
- cost, err = svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 1.0, 1.0, 1.0, 1.0, UsageTokens{}, "", boolPtr(false), time.Time{})
+ cost, err = svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 1.0, 1.0, 1.0, 1.0, UsageTokens{}, "", boolPtr(false), false, time.Time{})
require.NoError(t, err)
require.InDelta(t, 0.005, cost.TotalCost, 1e-12)
require.InDelta(t, 0.005, cost.ActualCost, 1e-12)
@@ -67,7 +67,7 @@ func TestCalculateOpenAIRecordUsageCostWebSearchPerCall(t *testing.T) {
// WebSearchCalls = 0 时不得走按次分支(无定价数据会返回 pricing 错误,
// 证明回落到了 token 路径而不是被按次分支吞掉)。
result.WebSearchCalls = 0
- _, err = svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 1.0, 1.0, 1.0, 1.0, UsageTokens{InputTokens: 10}, "", boolPtr(false), time.Time{})
+ _, err = svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 1.0, 1.0, 1.0, 1.0, UsageTokens{InputTokens: 10}, "", boolPtr(false), false, time.Time{})
require.Error(t, err)
}
diff --git a/backend/internal/service/openai_codex_model_metadata.go b/backend/internal/service/openai_codex_model_metadata.go
index 16b56724e..32199cacb 100644
--- a/backend/internal/service/openai_codex_model_metadata.go
+++ b/backend/internal/service/openai_codex_model_metadata.go
@@ -123,6 +123,12 @@ func codexModelRoutingAccountIDs(group *Group, modelID string) []int64 {
return group.GetRoutingAccountIDs(strings.TrimSpace(modelID))
}
+func codexAccountServesPlatformModel(account *Account, platform, modelID string) bool {
+ return account.Platform == platform ||
+ (account.Platform == PlatformAntigravity && mixedListingAccountAllowed(platform, account) &&
+ mixedListingModelAllowed(platform, modelID))
+}
+
func groupCodexModelMetadata(
platform string,
modelID string,
@@ -168,7 +174,7 @@ func groupCodexModelMetadata(
if routed && !containsInt64(routedAccountIDs, account.ID) {
continue
}
- if account.Platform == platform && codexExplicitModelMappingClaims(*account, modelID) {
+ if codexAccountServesPlatformModel(account, platform, modelID) && codexExplicitModelMappingClaims(*account, modelID) {
explicitClaims = true
break
}
@@ -183,7 +189,7 @@ func groupCodexModelMetadata(
missingMetadata := false
for i := range accounts {
account := &accounts[i]
- if account.Platform != platform {
+ if !codexAccountServesPlatformModel(account, platform, modelID) {
continue
}
if routed && !containsInt64(routedAccountIDs, account.ID) {
@@ -251,7 +257,7 @@ func codexExplicitModelTargetsConflictForPlatform(accounts []Account, platform,
targets := make(map[string]struct{})
for i := range accounts {
account := &accounts[i]
- if account.Platform != platform {
+ if !codexAccountServesPlatformModel(account, platform, modelID) {
continue
}
mappedModel, matched := account.ResolveMappedModel(modelID)
diff --git a/backend/internal/service/openai_codex_model_metadata_test.go b/backend/internal/service/openai_codex_model_metadata_test.go
index 16ed878e9..aafe8aae1 100644
--- a/backend/internal/service/openai_codex_model_metadata_test.go
+++ b/backend/internal/service/openai_codex_model_metadata_test.go
@@ -9,6 +9,71 @@ import (
"github.com/stretchr/testify/require"
)
+func TestCodexCatalogUsesAntigravityCapabilitiesInGeminiMixedGroup(t *testing.T) {
+ const groupID int64 = 93
+ account := Account{
+ ID: 25, Platform: PlatformAntigravity, Type: AccountTypeOAuth,
+ Extra: map[string]any{"mixed_scheduling": true},
+ Credentials: map[string]any{"model_mapping": map[string]any{
+ "gemini-custom": "gemini-3.8-flash-high",
+ }},
+ }
+ reasoning := true
+ account.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{
+ Models: map[string]UpstreamModelMetadata{"gemini-3.8-flash-high": {
+ ID: "gemini-3.8-flash-high", Reasoning: &reasoning,
+ DefaultReasoningLevel: "high", SupportedReasoningLevels: []string{"high"},
+ InputModalities: []string{"text", "image"}, ContextWindow: 1_048_576,
+ MaxOutputTokens: 65_536,
+ }},
+ })
+ svc := &GatewayService{accountRepo: codexModelsVisibilityAccountRepo{
+ byGroup: map[int64][]Account{groupID: {account}},
+ }}
+ for _, platform := range []string{PlatformAntigravity, PlatformComposite, PlatformGemini} {
+ t.Run(platform, func(t *testing.T) {
+ body, err := svc.BuildCodexModelsManifestForGroup(context.Background(),
+ &Group{ID: groupID, Platform: platform}, "", []string{"gemini-custom"})
+ require.NoError(t, err)
+ model := decodeCodexManifestModels(t, body)[0]
+ require.Equal(t, "gemini-custom", model["slug"])
+ require.Equal(t, float64(1_048_576), model["context_window"])
+ require.Equal(t, []any{"text", "image"}, model["input_modalities"])
+ require.Equal(t, []string{"high"}, effortsFromManifestModel(t, model))
+ })
+ }
+}
+
+func TestCodexCatalogGeminiCapabilitiesExcludeNonMixedAntigravityAccounts(t *testing.T) {
+ const groupID int64 = 94
+ reasoning := true
+ native := Account{ID: 1, Platform: PlatformGemini, Type: AccountTypeAPIKey,
+ Credentials: map[string]any{"model_mapping": map[string]any{"gemini-custom": "gemini-3.8-flash-high"}},
+ }
+ native.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{
+ Models: map[string]UpstreamModelMetadata{"gemini-3.8-flash-high": {
+ ID: "gemini-3.8-flash-high", Reasoning: &reasoning,
+ SupportedReasoningLevels: []string{"high"}, InputModalities: []string{"text", "image"},
+ ContextWindow: 1_048_576,
+ }},
+ })
+ for _, extra := range []map[string]any{nil, {"mixed_scheduling": false}} {
+ // A peer lacking capabilities would narrow the catalog if included.
+ peer := Account{ID: 2, Platform: PlatformAntigravity, Type: AccountTypeOAuth,
+ Extra: extra, Credentials: native.Credentials}
+ svc := &GatewayService{accountRepo: codexModelsVisibilityAccountRepo{
+ byGroup: map[int64][]Account{groupID: {native, peer}},
+ }}
+ body, err := svc.BuildCodexModelsManifestForGroup(context.Background(),
+ &Group{ID: groupID, Platform: PlatformGemini}, "", []string{"gemini-custom"})
+ require.NoError(t, err)
+ model := decodeCodexManifestModels(t, body)[0]
+ require.Equal(t, float64(1_048_576), model["context_window"])
+ require.Equal(t, []any{"text", "image"}, model["input_modalities"])
+ require.Equal(t, []string{"high"}, effortsFromManifestModel(t, model))
+ }
+}
+
func TestAstraUltraCatalogPreservesWorkflowMetadata(t *testing.T) {
// Ultra is a Codex workflow. Its inference effort must survive catalog sync,
// aliases and group generation instead of silently falling back to max.
diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go
index 3bfea1d92..d02fbfb8a 100644
--- a/backend/internal/service/openai_codex_models_service.go
+++ b/backend/internal/service/openai_codex_models_service.go
@@ -187,13 +187,13 @@ func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels(
return nil
}
+ visible, accounts, err := loadCodexGroupCatalogAccounts(ctx, s.accountRepo, group.ID)
+ if err != nil {
+ return fmt.Errorf("load group configured Codex models: %w", err)
+ }
var configuredModels []string
if !group.CodexModelsManifestConfig.Enabled {
- var err error
- configuredModels, err = s.groupConfiguredCodexModelIDs(ctx, group)
- if err != nil {
- return fmt.Errorf("load group configured Codex models: %w", err)
- }
+ configuredModels = openAIConfiguredCodexModelIDsForGroup(visible, group)
}
body, changed, err := mergeConfiguredCodexModelsManifest(
manifest.Body,
@@ -211,7 +211,12 @@ func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels(
}
changed = true
}
- if changed {
+ filtered, retired, err := filterRetiredOpenAIPublicModelsBody(body, accounts, true)
+ if err != nil {
+ return fmt.Errorf("filter retired Codex models: %w", err)
+ }
+ body = filtered
+ if changed || retired {
manifest.Body = body
manifest.ETag = codexModelsManifestBodyETag(body)
}
@@ -222,17 +227,6 @@ func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels(
return nil
}
-func (s *OpenAIGatewayService) groupConfiguredCodexModelIDs(ctx context.Context, group *Group) ([]string, error) {
- if group == nil {
- return nil, nil
- }
- accounts, err := s.accountRepo.ListSchedulableByGroupID(ctx, group.ID)
- if err != nil {
- return nil, err
- }
- return openAIConfiguredCodexModelIDsForGroup(accounts, group), nil
-}
-
// loadCodexGroupCatalogAccounts separates picker membership from capability
// intersection. visible accounts are currently schedulable and decide which
// public aliases appear. catalog accounts are persistently enabled group
@@ -300,7 +294,7 @@ func openAIConfiguredCodexModelIDs(accounts []Account) []string {
func openAIConfiguredCodexModelIDsForGroup(accounts []Account, group *Group) []string {
models := supplementUnmappedOpenAIModels(accounts, openAIConfiguredCodexModelIDs(accounts))
if group == nil || !group.ModelAllowlistEnabled() {
- return models
+ return filterRetiredOpenAIModelIDs(accounts, models)
}
seen := make(map[string]struct{}, len(models)+len(group.ModelAllowlist.Models))
@@ -329,7 +323,7 @@ func openAIConfiguredCodexModelIDsForGroup(accounts []Account, group *Group) []s
}
}
sort.Strings(models)
- return models
+ return filterRetiredOpenAIModelIDs(accounts, models)
}
const (
@@ -487,7 +481,7 @@ func newConfiguredCodexModelDescriptor(modelID string) configuredCodexModelDescr
}
if isClaudeCodexModel(modelID) {
- if claude.IsOpus55(modelID) || claude.IsSonnet55(modelID) {
+ if claude.IsOpus55(modelID) || claude.IsSonnet55(modelID) || claude.IsHaiku55(modelID) {
descriptor.ContextWindow = 1_000_000
descriptor.MaxContextWindow = 1_000_000
}
@@ -546,6 +540,9 @@ func newConfiguredCodexModelDescriptor(modelID string) configuredCodexModelDescr
}
descriptor.Slug = modelID
descriptor.officialMetadata = openai.CodexGPT61SolMetadata
+ // The October 12, 2026 Codex/Work default increased to 500k after
+ // the bundled official snapshot. Explicit upstream metadata still wins.
+ descriptor.ContextWindow = 500_000
}
return descriptor
}
@@ -911,6 +908,19 @@ func buildCodexModelsManifestForAccounts(
if effectivePlatform == PlatformOpenAIBPS {
return buildOpenAIBPSCodexModelsManifest(modelIDs)
}
+ if effectivePlatform == PlatformOpenAI {
+ modelIDs = filterRetiredOpenAIModelIDs(accounts, modelIDs)
+ } else if effectivePlatform == PlatformComposite {
+ filtered := make([]string, 0, len(modelIDs))
+ for _, modelID := range modelIDs {
+ platform, target, resolved := resolveCodexCompositeModelTarget(modelID, accounts, compositeRoutes, compositeRoutesAvailable)
+ if resolved && platform == PlatformOpenAI && openAIModelRetiredForAccounts(accounts, target) {
+ continue
+ }
+ filtered = append(filtered, modelID)
+ }
+ modelIDs = filtered
+ }
imageInputModels := make(map[string]bool, len(modelIDs))
searchToolModels := make(map[string]bool, len(modelIDs))
metadataModels := codexCatalogMetadataModels(
@@ -1113,7 +1123,7 @@ func uniqueCodexMappedModel(accounts []Account, platform string, modelID string)
targets := make(map[string]struct{})
for i := range accounts {
account := &accounts[i]
- if account.Platform != platform {
+ if !codexAccountServesPlatformModel(account, platform, modelID) {
continue
}
mappedModel, matched := account.ResolveMappedModel(modelID)
diff --git a/backend/internal/service/openai_codex_models_service_test.go b/backend/internal/service/openai_codex_models_service_test.go
index 9706ec461..b968be45e 100644
--- a/backend/internal/service/openai_codex_models_service_test.go
+++ b/backend/internal/service/openai_codex_models_service_test.go
@@ -334,6 +334,14 @@ func TestNewConfiguredCodexModelDescriptorUsesProviderMetadataAndSafeFallback(t
require.Equal(t, "none", *claudeHaiku.DefaultReasoningLevel)
require.Equal(t, []string{"none"}, effortsFromConfiguredCodexLevels(claudeHaiku.SupportedReasoningLevels))
+ claudeHaiku55 := newConfiguredCodexModelDescriptor("claude-haiku-5-5")
+ require.Equal(t, "Claude Haiku 5.5", claudeHaiku55.DisplayName)
+ require.Equal(t, int64(1_000_000), claudeHaiku55.ContextWindow)
+ require.Equal(t, int64(1_000_000), claudeHaiku55.MaxContextWindow)
+ require.NotNil(t, claudeHaiku55.DefaultReasoningLevel)
+ require.Equal(t, "medium", *claudeHaiku55.DefaultReasoningLevel)
+ require.Equal(t, []string{"low", "medium", "high", "xhigh", "max"}, effortsFromConfiguredCodexLevels(claudeHaiku55.SupportedReasoningLevels))
+
gpt56 := newConfiguredCodexModelDescriptor("gpt-5.6-sol")
require.Equal(t, "GPT-5.6 Sol", gpt56.DisplayName)
require.Equal(t, "OpenAI GPT coding model routed through Sub2API.", gpt56.Description)
@@ -2403,7 +2411,7 @@ func TestFetchCodexModelsManifestAPIKeyDisablesResponsesLiteForAffectedModels(t
}
func TestFetchCodexModelsManifestOAuthPreservesResponsesLite(t *testing.T) {
- const manifestBody = ` {"models":[{"slug":"gpt-5.6-sol","use_responses_lite":true}]} `
+ const manifestBody = ` {"models":[{"slug":"gpt-5.6-sol","use_responses_lite":true},{"slug":"gpt-6.1-sol","context_window":500000,"max_context_window":1000000,"use_responses_lite":true}]} `
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(manifestBody))
}))
@@ -3798,7 +3806,7 @@ func TestGPT61SolOfflineCodexCatalog(t *testing.T) {
m := catalog.Models[0]
require.Equal(t, "gpt-6.1-sol", m["slug"])
require.Equal(t, "low", m["default_reasoning_level"])
- require.EqualValues(t, 272000, m["context_window"])
+ require.EqualValues(t, 500000, m["context_window"])
require.EqualValues(t, 872000, m["max_context_window"])
require.Equal(t, "xhigh", m["multi_agent_reasoning_effort"])
require.Equal(t, "v2", m["multi_agent_version"])
@@ -3851,3 +3859,25 @@ func TestGPT61SolAPIKeyCatalogUsesFullResponses(t *testing.T) {
require.Equal(t, false, catalog.Models[0]["use_responses_lite"])
require.Equal(t, "low", catalog.Models[0]["default_reasoning_level"])
}
+
+func TestGPT61SolAPIKeyCatalogContextWindow(t *testing.T) {
+ account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "https://api.openai.com"}}
+ for _, tc := range []struct {
+ name string
+ body string
+ want int64
+ }{
+ {"missing uses updated default", `{"models":[{"slug":"gpt-6.1-sol"}]}`, 500_000},
+ {"null uses updated default", `{"models":[{"slug":"gpt-6.1-sol","context_window":null}]}`, 500_000},
+ {"lower upstream window is preserved", `{"models":[{"slug":"gpt-6.1-sol","context_window":272000}]}`, 272_000},
+ {"higher upstream window is preserved", `{"models":[{"slug":"gpt-6.1-sol","context_window":1000000,"max_context_window":1000000}]}`, 1_000_000},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ body, err := completeAPIKeyCodexModelsManifestMetadata([]byte(tc.body), true, account)
+ require.NoError(t, err)
+ models := decodeCodexManifestModels(t, body)
+ require.Len(t, models, 1)
+ require.EqualValues(t, tc.want, models[0]["context_window"])
+ })
+ }
+}
diff --git a/backend/internal/service/openai_codex_ticket_harvest.go b/backend/internal/service/openai_codex_ticket_harvest.go
index 8ad01543e..fb21b8c5c 100644
--- a/backend/internal/service/openai_codex_ticket_harvest.go
+++ b/backend/internal/service/openai_codex_ticket_harvest.go
@@ -59,10 +59,18 @@ func (s *OpenAIGatewayService) codexTicketSupportedModel(model string) bool {
return false
}
-func (s *OpenAIGatewayService) chooseCodexTicketProxy(ctx context.Context, accountID int64, model string) (string, *Proxy, error) {
+// chooseCodexTicketProxy 选择打票出口。返回的 *Proxy 为 nil 表示直连(仅账号模式下账号未绑定代理时)。
+func (s *OpenAIGatewayService) chooseCodexTicketProxy(ctx context.Context, account *Account, model string) (string, *Proxy, error) {
if s.settingService == nil {
return "", nil, ErrCodexTicketNoProxy
}
+ accountID := account.ID
+ if s.settingService.GetCodexTicketProxySource(ctx) == CodexTicketProxySourceAccount {
+ if account.ProxyID != nil && account.Proxy != nil {
+ return account.Proxy.URL(), account.Proxy, nil
+ }
+ return "", nil, nil
+ }
proxies, err := s.settingService.AvailableCodexTicketProxies(ctx)
if err != nil {
return "", nil, err
@@ -197,12 +205,14 @@ func (s *OpenAIGatewayService) runCodexTicketAttemptWithChallengeGenerator(ctx c
}
return result, nil
}
- proxyURL, proxy, proxyErr := s.chooseCodexTicketProxy(ctx, account.ID, model)
+ proxyURL, proxy, proxyErr := s.chooseCodexTicketProxy(ctx, account, model)
if proxyErr != nil {
a.Outcome, a.ReasonCode = "error", "proxy_unavailable"
return result, proxyErr
}
- a.ProxyID, a.ProxyName = &proxy.ID, proxy.Name
+ if proxy != nil {
+ a.ProxyID, a.ProxyName = &proxy.ID, proxy.Name
+ }
if s.httpUpstream == nil {
a.Outcome, a.ReasonCode = "error", "upstream_unavailable"
return result, ErrCodexTicketUnavailable
diff --git a/backend/internal/service/openai_compact_fallback.go b/backend/internal/service/openai_compact_fallback.go
index 1a61e987a..d9877912b 100644
--- a/backend/internal/service/openai_compact_fallback.go
+++ b/backend/internal/service/openai_compact_fallback.go
@@ -57,6 +57,9 @@ func (s *OpenAIGatewayService) resolveOpenAICompactFallbackModel(account *Accoun
if account != nil {
if mapped, matched := account.ResolveCompactMappedModel(requestedModel); matched {
if mapped = strings.TrimSpace(mapped); mapped != "" {
+ if isRetiredOpenAISubscriptionModel(account, mapped) {
+ return ""
+ }
return mapped
}
}
@@ -68,7 +71,11 @@ func (s *OpenAIGatewayService) resolveOpenAICompactFallbackModel(account *Accoun
if fallback == "" {
return ""
}
- return strings.TrimSpace(resolveOpenAIAccountUpstreamModelForRequest(account, fallback, false))
+ resolved := strings.TrimSpace(resolveOpenAIAccountUpstreamModelForRequest(account, fallback, false))
+ if isRetiredOpenAISubscriptionModel(account, resolved) {
+ return ""
+ }
+ return resolved
}
func isOpenAICompactModelFailure(statusCode int, upstreamMsg string, upstreamBody []byte) bool {
diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go
index 27bc97c4f..a6edbcc8d 100644
--- a/backend/internal/service/openai_gateway_cc_pipeline.go
+++ b/backend/internal/service/openai_gateway_cc_pipeline.go
@@ -67,13 +67,26 @@ func (s *OpenAIGatewayService) newStreamHeaderWriter(c *gin.Context, upstream ht
// (下游 handleXxxErrorResponse 需要再次读取),返回原始错误体与脱敏后的
// 上游错误消息。
func (s *OpenAIGatewayService) readOpenAIUpstreamError(resp *http.Response) ([]byte, string) {
- respBody := s.readUpstreamErrorBody(resp)
+ respBody, upstreamMsg, _ := s.readOpenAIUpstreamErrorWithCompleteness(resp)
+ return respBody, upstreamMsg
+}
+
+func (s *OpenAIGatewayService) readOpenAIUpstreamErrorWithCompleteness(resp *http.Response) ([]byte, string, bool) {
+ limit := openAIUpstreamErrorBodyReadLimitForConfig(nil)
+ if s != nil {
+ limit = openAIUpstreamErrorBodyReadLimitForConfig(s.cfg)
+ }
+ respBody, readErr := io.ReadAll(io.LimitReader(resp.Body, limit+1))
+ complete := readErr == nil && int64(len(respBody)) <= limit
+ if int64(len(respBody)) > limit {
+ respBody = respBody[:limit]
+ }
_ = resp.Body.Close()
resp.Body = io.NopCloser(bytes.NewReader(respBody))
upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody))
upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg)
- return respBody, upstreamMsg
+ return respBody, upstreamMsg, complete
}
// failoverOpenAIUpstreamHTTPError 对 >=400 的上游响应做 failover 判定:命中时
diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go
index 54b5dd67d..8d6c99266 100644
--- a/backend/internal/service/openai_gateway_chat_completions.go
+++ b/backend/internal/service/openai_gateway_chat_completions.go
@@ -7,6 +7,8 @@ import (
"errors"
"fmt"
"net/http"
+ "regexp"
+ "strconv"
"strings"
"sync/atomic"
"time"
@@ -229,7 +231,7 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions(
// Normal path: convert Chat Completions → Responses.
// ChatCompletionsToResponses always sets Stream=true (upstream always streams).
chatReq.Model = upstreamModel
- responsesReq, err = apicompat.ChatCompletionsToResponses(&chatReq)
+ responsesReq, err = chatCompletionsToResponses(s.cfg, &chatReq)
if err != nil {
return nil, fmt.Errorf("convert chat completions to responses: %w", err)
}
@@ -370,7 +372,7 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions(
// 8. Handle error response with failover
if resp.StatusCode >= 400 {
- respBody, upstreamMsg := s.readOpenAIUpstreamError(resp)
+ respBody, upstreamMsg, completeErrorBody := s.readOpenAIUpstreamErrorWithCompleteness(resp)
if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) {
expectedTaskID := account.GetCredential("task_id")
if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil {
@@ -387,7 +389,24 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions(
zap.Int("upstream_status", resp.StatusCode),
zap.String("upstream_message", upstreamMsg),
)
- return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel)
+ return s.forwardAsRawChatCompletionsWithStartTime(ctx, c, account, body, defaultMappedModel, startTime)
+ }
+ responsesMode, _ := account.Extra[openai_compat.ExtraKeyResponsesMode].(string)
+ if account.IsOpenAIApiKey() &&
+ openai_compat.NormalizeResponsesSupportMode(responsesMode) == openai_compat.ResponsesSupportModeAuto &&
+ openai_compat.ResolveResponsesSupport(account.Extra) == openai_compat.ResponsesSupportYes &&
+ !isResponsesShape &&
+ (ctx == nil || ctx.Err() == nil) &&
+ (c.Request == nil || c.Request.Context().Err() == nil) &&
+ !IsResponseCommitted(c) &&
+ !c.Writer.Written() &&
+ completeErrorBody &&
+ isConvertedResponsesInputStringRejection(resp.StatusCode, respBody) {
+ logger.L().Info("openai chat_completions: structured Responses input rejected, falling back to raw chat completions",
+ zap.Int64("account_id", account.ID),
+ zap.Int("upstream_status", resp.StatusCode),
+ )
+ return s.forwardAsRawChatCompletionsWithStartTime(ctx, c, account, body, defaultMappedModel, startTime)
}
if foErr := s.failoverOpenAIUpstreamHTTPError(ctx, c, account, resp, respBody, upstreamMsg, upstreamModel); foErr != nil {
return nil, foErr
@@ -441,6 +460,155 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions(
return result, handleErr
}
+var responsesInputStringValidationError = regexp.MustCompile(`^['"]loc['"]\s*:\s*\(\s*['"]body['"]\s*,\s*['"]input['"]\s*,\s*['"]str['"]\s*\)$`)
+var responsesStringValidationMessage = regexp.MustCompile(`^['"]msg['"]\s*:\s*['"]Input should be a valid string['"]$`)
+var responsesStringValidationType = regexp.MustCompile(`^['"]type['"]\s*:\s*['"]string_type['"]$`)
+var responsesValidationErrors = regexp.MustCompile(`(?s)^([1-9][0-9]*) validation errors?(?: for [^\r\n:]+)?:\s*(\[.*\])$`)
+var responsesInvalidInputTypeMessage = regexp.MustCompile(`(?i)^(?:Invalid type for ['"]input['"]:\s*)?Expected a string(?: for input)?, but got an (?:array|object) instead\.?$`)
+
+func isResponsesInputStringValidationMessage(message string) bool {
+ match := responsesValidationErrors.FindStringSubmatch(strings.TrimSpace(message))
+ if match == nil {
+ return false
+ }
+ entries, ok := splitResponsesValidationFields(match[2][1 : len(match[2])-1])
+ count, err := strconv.Atoi(match[1])
+ if !ok || err != nil || count != len(entries) {
+ return false
+ }
+ matched := false
+ for _, entry := range entries {
+ if !strings.HasPrefix(entry, "{") || !strings.HasSuffix(entry, "}") {
+ return false
+ }
+ fields, ok := splitResponsesValidationFields(entry[1 : len(entry)-1])
+ if !ok {
+ return false
+ }
+ location, message, stringType := false, false, false
+ keys := make(map[string]bool, len(fields))
+ for _, field := range fields {
+ key, value, found := strings.Cut(field, ":")
+ key = strings.TrimSpace(key)
+ if !found || len(key) < 3 || (key[0] != '\'' && key[0] != '"') || key[len(key)-1] != key[0] || strings.TrimSpace(value) == "" || keys[key[1:len(key)-1]] {
+ return false
+ }
+ keys[key[1:len(key)-1]] = true
+ location = location || responsesInputStringValidationError.MatchString(field)
+ message = message || responsesStringValidationMessage.MatchString(field)
+ stringType = stringType || responsesStringValidationType.MatchString(field)
+ }
+ matched = matched || (location && message && stringType)
+ }
+ return matched
+}
+
+func splitResponsesValidationFields(value string) ([]string, bool) {
+ var fields []string
+ var brackets []byte
+ var quote byte
+ escaped := false
+ start := 0
+ for index := 0; index < len(value); index++ {
+ character := value[index]
+ if quote != 0 {
+ if escaped {
+ escaped = false
+ } else if character == '\\' {
+ escaped = true
+ } else if character == quote {
+ quote = 0
+ }
+ continue
+ }
+ switch character {
+ case '\'', '"':
+ quote = character
+ case '{', '[', '(':
+ brackets = append(brackets, character)
+ case '}', ']', ')':
+ if len(brackets) == 0 {
+ return nil, false
+ }
+ opening := brackets[len(brackets)-1]
+ if (character == '}' && opening != '{') || (character == ']' && opening != '[') || (character == ')' && opening != '(') {
+ return nil, false
+ }
+ brackets = brackets[:len(brackets)-1]
+ case ',':
+ if len(brackets) == 0 {
+ field := strings.TrimSpace(value[start:index])
+ if field == "" {
+ return nil, false
+ }
+ fields = append(fields, field)
+ start = index + 1
+ }
+ }
+ }
+ if quote != 0 || len(brackets) != 0 {
+ return nil, false
+ }
+ if field := strings.TrimSpace(value[start:]); field != "" {
+ fields = append(fields, field)
+ }
+ return fields, len(fields) > 0
+}
+
+func isConvertedResponsesInputStringRejection(status int, responseBody []byte) bool {
+ if status != http.StatusBadRequest || !json.Valid(responseBody) {
+ return false
+ }
+ envelope := gjson.ParseBytes(responseBody)
+ for _, object := range []gjson.Result{envelope, envelope.Get("error")} {
+ if !object.IsObject() {
+ return false
+ }
+ keys := make(map[string]bool)
+ unambiguous := true
+ object.ForEach(func(key, value gjson.Result) bool {
+ name := key.String()
+ if keys[name] {
+ unambiguous = false
+ return false
+ }
+ keys[name] = true
+ switch name {
+ case "usage", "output", "output_text", "choices", "tool_calls", "response", "status", "incomplete_details":
+ unambiguous = false
+ case "code":
+ code := strings.ToLower(strings.TrimSpace(value.String()))
+ unambiguous = code == "" || code == "invalid_type" || code == "invalid_request_error"
+ case "param":
+ param := strings.ToLower(strings.TrimSpace(value.String()))
+ unambiguous = param == "" || param == "input"
+ case "type":
+ errorType := strings.ToLower(strings.TrimSpace(value.String()))
+ unambiguous = errorType == "" || errorType == "invalid_type" || errorType == "invalid_request_error"
+ }
+ return unambiguous
+ })
+ if !unambiguous {
+ return false
+ }
+ }
+ message := gjson.GetBytes(responseBody, "error.message").String()
+ if isResponsesInputStringValidationMessage(message) {
+ return true
+ }
+ code := strings.ToLower(strings.TrimSpace(gjson.GetBytes(responseBody, "error.code").String()))
+ typ := strings.ToLower(strings.TrimSpace(gjson.GetBytes(responseBody, "error.type").String()))
+ if code != "invalid_type" && typ != "invalid_type" {
+ return false
+ }
+ param := strings.ToLower(strings.TrimSpace(gjson.GetBytes(responseBody, "error.param").String()))
+ if param != "input" {
+ return false
+ }
+ message = strings.ToLower(strings.TrimSpace(message))
+ return responsesInvalidInputTypeMessage.MatchString(message)
+}
+
func normalizeResponsesRequestServiceTier(req *apicompat.ResponsesRequest) {
if req == nil {
return
diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go
index df2884807..3ebac0add 100644
--- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go
+++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go
@@ -57,7 +57,7 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic(
clientStream := ccReq.Stream
// 2. Convert CC → Responses → Anthropic (chained conversion)
- responsesReq, err := apicompat.ChatCompletionsToResponses(&ccReq)
+ responsesReq, err := chatCompletionsToResponses(s.cfg, &ccReq)
if err != nil {
writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", "Failed to convert request")
return nil, fmt.Errorf("convert chat completions to responses: %w", err)
diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go
index 4a45a3e37..a97f800bb 100644
--- a/backend/internal/service/openai_gateway_chat_completions_raw.go
+++ b/backend/internal/service/openai_gateway_chat_completions_raw.go
@@ -61,7 +61,17 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions(
body []byte,
defaultMappedModel string,
) (*OpenAIForwardResult, error) {
- startTime := time.Now()
+ return s.forwardAsRawChatCompletionsWithStartTime(ctx, c, account, body, defaultMappedModel, time.Now())
+}
+
+func (s *OpenAIGatewayService) forwardAsRawChatCompletionsWithStartTime(
+ ctx context.Context,
+ c *gin.Context,
+ account *Account,
+ body []byte,
+ defaultMappedModel string,
+ startTime time.Time,
+) (*OpenAIForwardResult, error) {
// 1. Parse minimal fields needed for routing/billing
originalModel := gjson.GetBytes(body, "model").String()
diff --git a/backend/internal/service/openai_gateway_chat_completions_test.go b/backend/internal/service/openai_gateway_chat_completions_test.go
index f16325375..06d149d9d 100644
--- a/backend/internal/service/openai_gateway_chat_completions_test.go
+++ b/backend/internal/service/openai_gateway_chat_completions_test.go
@@ -3,7 +3,9 @@ package service
import (
"bytes"
"context"
+ "encoding/json"
"errors"
+ "fmt"
"io"
"net/http"
"net/http/httptest"
@@ -13,6 +15,7 @@ import (
"github.com/MACOS-DO/sub4api/internal/config"
"github.com/MACOS-DO/sub4api/internal/pkg/apicompat"
+ "github.com/MACOS-DO/sub4api/internal/pkg/openai_compat"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
@@ -32,6 +35,546 @@ func (w *openAIChatFailingWriter) Write(p []byte) (int, error) {
return w.ResponseWriter.Write(p)
}
+func TestForwardAsChatCompletions_ResponsesSupportedFallsBackWhenStructuredInputRequiresString(t *testing.T) {
+ for name, rejection := range map[string]string{
+ "OpenAI invalid type": `{"error":{"type":"invalid_request_error","code":"invalid_type","param":"input","message":"Invalid type for 'input': expected a string, but got an array instead."}}`,
+ "vLLM validation": `{"error":{"message":"1 validation error: [{'type':'string_type', 'loc':('body','input','str'), 'msg':'Input should be a valid string', 'input':[{'role':'user','content':'hi'}, {'role':'assistant','content':[{'type':'output_text'}]}, ResponseFunctionToolCall(type='function_call'), {'type':'function_call_output'}]}]"}}`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":[{"type":"text","text":"checking"},{"type":"thinking","thinking":"think"}],"tool_calls":[{"id":"call_1","type":"function","function":{"name":"lookup","arguments":"{}"}}]},{"role":"tool","tool_call_id":"call_1","content":"done"},{"role":"user","content":"what now"}],"stream":false}`)
+ originalBody := append([]byte(nil), body...)
+ logs, releaseLogs := captureStructuredLog(t)
+ defer releaseLogs()
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
+ c.Request.Header.Set("Content-Type", "application/json")
+
+ upstream := &httpUpstreamRecorder{responses: []*http.Response{
+ {
+ StatusCode: http.StatusBadRequest,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(
+ rejection,
+ )),
+ },
+ {
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid_raw_fallback"}},
+ Body: io.NopCloser(strings.NewReader(
+ `{"id":"chatcmpl_fallback","object":"chat.completion","model":"gpt-5.4","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`,
+ )),
+ },
+ }}
+ svc := &OpenAIGatewayService{
+ cfg: structuredInputRetryTestConfig(),
+ httpUpstream: upstream,
+ }
+ account := structuredInputRetryTestAccount()
+
+ result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Len(t, upstream.requests, 2)
+ require.Equal(t, "/v1/responses", upstream.requests[0].URL.Path)
+ require.True(t, gjson.GetBytes(upstream.bodies[0], "input").IsArray())
+ require.Equal(t, "/v1/chat/completions", upstream.requests[1].URL.Path)
+ require.JSONEq(t, string(body), string(upstream.bodies[1]))
+ require.Equal(t, originalBody, body)
+ require.Equal(t, "/v1/chat/completions", result.UpstreamEndpoint)
+ require.Equal(t, "/v1/chat/completions", GetActualOpenAIUpstreamEndpoint(c))
+ require.Equal(t, "ok", gjson.Get(rec.Body.String(), "choices.0.message.content").String())
+ require.True(t, logs.ContainsMessage("structured Responses input rejected"))
+ logs.mu.Lock()
+ defer logs.mu.Unlock()
+ for _, event := range logs.events {
+ require.NotContains(t, event.Fields, "upstream_message")
+ require.NotContains(t, event.Fields, "upstream_body")
+ require.NotContains(t, event.Message, rejection)
+ }
+ })
+ }
+}
+
+type openAIChatFallbackBoundaryReader struct {
+ io.Reader
+ beforeRead func()
+}
+
+func (reader *openAIChatFallbackBoundaryReader) Read(buffer []byte) (int, error) {
+ if reader.beforeRead != nil {
+ reader.beforeRead()
+ reader.beforeRead = nil
+ }
+ return reader.Reader.Read(buffer)
+}
+
+func TestForwardAsChatCompletions_StructuredInputRetrySafetyBoundaries(t *testing.T) {
+ rejection := `{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}`
+ validation := `"message":"1 validation error: [{'type':'string_type','loc':('body','input','str'),'msg':'Input should be a valid string'}]"`
+ for _, test := range []struct {
+ name string
+ body string
+ }{
+ {name: "duplicate error", body: strings.TrimSuffix(rejection, "}") + `,"error":{"code":"rate_limit_exceeded"}}`},
+ {name: "duplicate code", body: strings.Replace(rejection, `"code":"invalid_type"`, `"code":"invalid_type","code":"rate_limit_exceeded"`, 1)},
+ {name: "duplicate escaped param", body: strings.Replace(rejection, `"param":"input"`, `"param":"input","p\u0061ram":"tools"`, 1)},
+ {name: "duplicate message", body: strings.Replace(rejection, `"message":"Expected a string, but got an array instead."`, `"message":"Expected a string, but got an array instead.","message":"Input is too long."`, 1)},
+ {name: "contradictory error type", body: strings.Replace(rejection, `"error":{`, `"error":{"type":"authentication_error",`, 1)},
+ {name: "contradictory envelope type", body: strings.TrimSuffix(rejection, "}") + `,"type":"rate_limit_error"}`},
+ {name: "validation contradictory type", body: `{"error":{"type":"rate_limit_error",` + validation + `}}`},
+ {name: "validation contradictory envelope type", body: `{"type":"authentication_error","error":{` + validation + `}}`},
+ {name: "validation contradictory code", body: `{"error":{"code":"rate_limit_exceeded",` + validation + `}}`},
+ {name: "validation contradictory param", body: `{"error":{"param":"tools",` + validation + `}}`},
+ {name: "contradictory envelope code", body: strings.TrimSuffix(rejection, "}") + `,"code":"rate_limit_exceeded"}`},
+ {name: "contradictory envelope param", body: strings.TrimSuffix(rejection, "}") + `,"param":"tools"}`},
+ {name: "type cannot override code", body: strings.Replace(rejection, `"code":"invalid_type"`, `"code":"rate_limit_exceeded","type":"invalid_type"`, 1)},
+ {name: "usage", body: strings.TrimSuffix(rejection, "}") + `,"usage":{"input_tokens":12,"output_tokens":3}}`},
+ {name: "error usage", body: strings.Replace(rejection, `"error":{`, `"error":{"usage":{"input_tokens":12},`, 1)},
+ {name: "output", body: strings.TrimSuffix(rejection, "}") + `,"output":[{"type":"message","content":[{"type":"output_text","text":"partial"}]}]}`},
+ {name: "output text", body: strings.TrimSuffix(rejection, "}") + `,"output_text":"partial"}`},
+ {name: "tool calls", body: strings.TrimSuffix(rejection, "}") + `,"tool_calls":[{"id":"call_partial","type":"function","function":{"name":"lookup","arguments":"{}"}}]}`},
+ {name: "choices", body: strings.TrimSuffix(rejection, "}") + `,"choices":[{"delta":{"content":"partial"}}]}`},
+ {name: "nested response", body: strings.TrimSuffix(rejection, "}") + `,"response":{"status":"incomplete","usage":{"input_tokens":12},"output":[]}}`},
+ {name: "partial status", body: strings.TrimSuffix(rejection, "}") + `,"status":"in_progress"}`},
+ {name: "incomplete details", body: strings.TrimSuffix(rejection, "}") + `,"incomplete_details":{"reason":"max_output_tokens"}}`},
+ {name: "partial event", body: strings.TrimSuffix(rejection, "}") + `,"type":"response.output_text.delta","delta":"partial"}`},
+ {name: "caller canceled"},
+ {name: "request canceled"},
+ {name: "response committed"},
+ {name: "writer committed"},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":false}`)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ requestCtx, cancelRequest := context.WithCancel(context.Background())
+ defer cancelRequest()
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)).WithContext(requestCtx)
+ errorBody := test.body
+ if errorBody == "" {
+ errorBody = rejection
+ }
+ reader := &openAIChatFallbackBoundaryReader{Reader: strings.NewReader(errorBody), beforeRead: func() {
+ switch test.name {
+ case "caller canceled":
+ cancel()
+ case "request canceled":
+ cancelRequest()
+ case "response committed":
+ MarkResponseCommitted(c)
+ case "writer committed":
+ c.Writer.WriteHeaderNow()
+ }
+ }}
+ upstream := &httpUpstreamRecorder{resp: &http.Response{
+ StatusCode: http.StatusBadRequest,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(reader),
+ }}
+ svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream}
+ result, err := svc.ForwardAsChatCompletions(ctx, c, structuredInputRetryTestAccount(), body, "", "")
+ require.Error(t, err)
+ require.Nil(t, result)
+ require.Len(t, upstream.requests, 1)
+ require.Equal(t, "/v1/responses", upstream.requests[0].URL.Path)
+ })
+ }
+}
+
+func TestConvertedResponsesInputStringRejectionIsNarrow(t *testing.T) {
+ matching := []byte(`{"error":{"code":"invalid_type","param":"input","message":"Expected a string for input, but got an object instead."}}`)
+ require.True(t, isConvertedResponsesInputStringRejection(http.StatusBadRequest, matching))
+ require.True(t, isConvertedResponsesInputStringRejection(http.StatusBadRequest, []byte(`{"error":{"type":"invalid_type","param":"input","message":"Invalid type for 'input': expected a string, but got an array instead."}}`)))
+
+ for _, tc := range []struct {
+ name string
+ status int
+ body string
+ }{
+ {name: "nested content validation", status: http.StatusBadRequest, body: `{"error":{"message":"'loc':('body','input',0,'content','str'), 'msg':'Input should be a valid string'"}}`},
+ {name: "other field validation", status: http.StatusBadRequest, body: `{"error":{"message":"'loc':('body','model','str'), 'msg':'Input should be a valid string'"}}`},
+ {name: "generic string validation", status: http.StatusBadRequest, body: `{"error":{"message":"Input should be a valid string"}}`},
+ {name: "wrong status", status: http.StatusUnprocessableEntity, body: string(matching)},
+ {name: "authentication", status: http.StatusUnauthorized, body: string(matching)},
+ {name: "authorization", status: http.StatusForbidden, body: string(matching)},
+ {name: "rate limit", status: http.StatusTooManyRequests, body: string(matching)},
+ {name: "server error", status: http.StatusInternalServerError, body: string(matching)},
+ {name: "wrong parameter", status: http.StatusBadRequest, body: `{"error":{"code":"invalid_type","param":"tools","message":"Expected a string, but got an array instead."}}`},
+ {name: "wrong code", status: http.StatusBadRequest, body: `{"error":{"code":"invalid_request_error","param":"input","message":"Expected a string, but got an array instead."}}`},
+ {name: "unrelated input error", status: http.StatusBadRequest, body: `{"error":{"code":"invalid_type","param":"input","message":"Input is too long."}}`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ require.False(t, isConvertedResponsesInputStringRejection(tc.status, []byte(tc.body)))
+ })
+ }
+}
+
+func TestConvertedResponsesInputStringRejectionValidationBoundaries(t *testing.T) {
+ validation := `{'type': 'string_type', 'loc': ('body', 'input', 'str'), 'msg': 'Input should be a valid string', 'input': [{'role': 'user', 'content': 'hello'}]}`
+ for _, test := range []struct {
+ name string
+ message string
+ want bool
+ }{
+ {name: "complete Pydantic error", message: "1 validation error: [" + validation + "]", want: true},
+ {name: "multiple Pydantic errors", message: "2 validation errors for Request: [" + strings.Replace(validation, "'input', 'str'", "'model', 'str'", 1) + ", " + validation + "]", want: true},
+ {name: "double quoted keys", message: "1 validation error: [" + strings.ReplaceAll(validation, "'", `"`) + "]", want: true},
+ {name: "surrounding whitespace", message: " \n1 validation error: [" + validation + "]\n ", want: true},
+ {name: "escaped quote in history", message: `1 validation error: [{'type':'string_type','loc':('body','input','str'),'msg':'Input should be a valid string','input':[{'content':'can\'t [close] this }'}]}]`, want: true},
+ {name: "bare loc and msg", message: `'loc':('body','input','str'), 'msg':'Input should be a valid string'`},
+ {name: "echoed dictionary in unrelated error", message: "Invalid history: " + validation},
+ {name: "echoed fake loc and msg in input", message: `1 validation error: [{'type':'string_type','loc':('body','model','str'),'msg':'Input should be a valid string','input':{'loc':('body','input','str'),'msg':'Input should be a valid string'}}]`},
+ {name: "echoed fake loc and msg in quoted history", message: `1 validation error: [{'type':'string_type','loc':('body','input',0,'content','str'),'msg':'Input should be a valid string','input':"'loc':('body','input','str'), 'msg':'Input should be a valid string'"}]`},
+ {name: "echoed complete error in quoted history", message: `1 validation error: [{'type':'string_type','loc':('body','model','str'),'msg':'Input should be a valid string','input':"1 validation error: [{'type':'string_type','loc':('body','input','str'),'msg':'Input should be a valid string'}]"}]`},
+ {name: "truncated error list", message: "1 validation error: [" + validation},
+ {name: "truncated quoted input", message: `1 validation error: [{'type':'string_type','loc':('body','input','str'),'msg':'Input should be a valid string','input':'history}]`},
+ {name: "mismatched closing bracket", message: "1 validation error: [" + strings.TrimSuffix(validation, "}") + ")]"},
+ {name: "elided validation list", message: "240 validation errors: ... " + validation},
+ {name: "incorrect error count", message: "2 validation errors: [" + validation + "]"},
+ {name: "overflowed error count", message: "999999999999999999999999 validation errors: [" + validation + "]"},
+ {name: "duplicate location", message: "1 validation error: [" + strings.Replace(validation, "'input':", "'loc': ('body', 'model', 'str'), 'input':", 1) + "]"},
+ {name: "wrong validation type", message: "1 validation error: [" + strings.Replace(validation, "string_type", "value_error", 1) + "]"},
+ {name: "missing validation type", message: "1 validation error: [" + strings.Replace(validation, "'type': 'string_type', ", "", 1) + "]"},
+ {name: "location and message in different errors", message: "2 validation errors: [" + strings.Replace(validation, "Input should be a valid string", "Invalid history", 1) + ", " + strings.Replace(validation, "'input', 'str'", "'model', 'str'", 1) + "]"},
+ {name: "trailing echoed text", message: "1 validation error: [" + validation + "] echoed history"},
+ {name: "structured string array", message: "Expected a string, but got an array instead.", want: true},
+ {name: "structured object", message: "Invalid type for 'input': expected a string, but got an object instead.", want: true},
+ {name: "structured echoed history", message: "Invalid history containing 'expected a string' and 'got an array'"},
+ {name: "structured truncated message", message: "Expected a string, but got an array"},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ body, err := json.Marshal(map[string]any{"error": map[string]string{"message": test.message, "code": "invalid_type", "param": "input"}})
+ require.NoError(t, err)
+ require.Equal(t, test.want, isConvertedResponsesInputStringRejection(http.StatusBadRequest, body))
+ if test.want {
+ require.False(t, isConvertedResponsesInputStringRejection(http.StatusBadRequest, body[:len(body)-1]))
+ require.False(t, isConvertedResponsesInputStringRejection(http.StatusBadRequest, append(body, []byte(" trailing")...)))
+ }
+ })
+ }
+}
+
+func TestForwardAsChatCompletions_StructuredInputRetryRequiresCompleteErrorBody(t *testing.T) {
+ rejection := `{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}`
+ limit := int(openAIUpstreamErrorBodyReadLimitForConfig(structuredInputRetryTestConfig()))
+ for _, test := range []struct {
+ name string
+ payload string
+ readErr error
+ unknown bool
+ want bool
+ }{
+ {name: "complete JSON followed by read failure", payload: rejection, readErr: io.ErrUnexpectedEOF},
+ {name: "truncated JSON", payload: rejection[:len(rejection)-1]},
+ {name: "exact read limit", payload: rejection + strings.Repeat(" ", limit-len(rejection)), want: true},
+ {name: "one byte beyond read limit", payload: rejection + strings.Repeat(" ", limit-len(rejection)+1)},
+ {name: "valid JSON prefix before discarded suffix", payload: rejection + strings.Repeat(" ", limit-len(rejection)) + "trailing"},
+ {name: "unknown capability still retries after read failure", payload: rejection, readErr: io.ErrUnexpectedEOF, unknown: true, want: true},
+ {name: "unknown capability still retries beyond read limit", payload: rejection + strings.Repeat(" ", limit-len(rejection)+1), unknown: true, want: true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}]}`)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
+ errorBody := io.NopCloser(strings.NewReader(test.payload))
+ if test.readErr != nil {
+ errorBody = &openAIChatStreamReadErrorCloser{payload: []byte(test.payload), err: test.readErr}
+ }
+ account := structuredInputRetryTestAccount()
+ status := http.StatusBadRequest
+ if test.unknown {
+ delete(account.Extra, openai_compat.ExtraKeyResponsesSupported)
+ status = http.StatusNotFound
+ }
+ upstream := &httpUpstreamRecorder{responses: []*http.Response{
+ {StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: errorBody},
+ {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"id":"chatcmpl_retry","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`))},
+ }}
+ svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream}
+ result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
+ if test.want {
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Len(t, upstream.requests, 2)
+ } else {
+ require.Error(t, err)
+ require.Nil(t, result)
+ require.Len(t, upstream.requests, 1)
+ }
+ })
+ }
+}
+
+type openAIChatFallbackDelayReader struct {
+ io.Reader
+ elapsed time.Duration
+}
+
+func (reader *openAIChatFallbackDelayReader) Read(buffer []byte) (int, error) {
+ if reader.elapsed == 0 {
+ started := time.Now()
+ time.Sleep(30 * time.Millisecond)
+ reader.elapsed = time.Since(started)
+ }
+ return reader.Reader.Read(buffer)
+}
+
+func TestForwardAsChatCompletions_RawFallbackPreservesResponsesTiming(t *testing.T) {
+ for _, unknown := range []bool{false, true} {
+ for _, stream := range []bool{false, true} {
+ t.Run(fmt.Sprintf("unknown=%t/stream=%t", unknown, stream), func(t *testing.T) {
+ body := []byte(fmt.Sprintf(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":%t}`, stream))
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
+ account := structuredInputRetryTestAccount()
+ status := http.StatusBadRequest
+ if unknown {
+ delete(account.Extra, openai_compat.ExtraKeyResponsesSupported)
+ status = http.StatusNotFound
+ }
+ initialBody := &openAIChatFallbackDelayReader{Reader: strings.NewReader(`{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}`)}
+ responseBody := `{"id":"chatcmpl_retry","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`
+ contentType := "application/json"
+ if stream {
+ responseBody = "data: {\"id\":\"chatcmpl_retry\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1,\"total_tokens\":2}}\n\ndata: [DONE]\n\n"
+ contentType = "text/event-stream"
+ }
+ upstream := &httpUpstreamRecorder{responses: []*http.Response{
+ {StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(initialBody)},
+ {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(responseBody))},
+ }}
+ svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream}
+ result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Len(t, upstream.requests, 2)
+ require.Equal(t, "/v1/responses", upstream.requests[0].URL.Path)
+ require.Equal(t, "/v1/chat/completions", upstream.requests[1].URL.Path)
+ require.GreaterOrEqual(t, result.Duration, initialBody.elapsed)
+ if stream {
+ require.NotNil(t, result.FirstTokenMs)
+ require.GreaterOrEqual(t, *result.FirstTokenMs, int(initialBody.elapsed.Milliseconds()))
+ }
+ })
+ }
+ }
+}
+
+func TestForwardAsChatCompletions_StructuredInputRejectionDoesNotRetryIneligibleRequests(t *testing.T) {
+ rejection := `{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}`
+ for _, test := range []struct {
+ name string
+ mode string
+ unknown bool
+ platform string
+ protocol string
+ endpoint string
+ accountType string
+ responsesBody bool
+ nativeIngress bool
+ status int
+ rejection string
+ }{
+ {name: "forced Responses", mode: "force_responses"},
+ {name: "forced Responses without probe", mode: "force_responses", unknown: true},
+ {name: "unknown support", unknown: true},
+ {name: "Responses shaped Chat ingress", responsesBody: true},
+ {name: "native Responses ingress", responsesBody: true, nativeIngress: true},
+ {name: "native CN Responses protocol", platform: PlatformDeepseek},
+ {name: "adaptive Chat ingress stays raw", platform: PlatformKimi, protocol: APIProtocolAdaptive, endpoint: "/chat/completions"},
+ {name: "adaptive Responses shaped ingress stays Responses", platform: PlatformKimi, protocol: APIProtocolAdaptive, responsesBody: true},
+ {name: "adaptive Responses shaped ingress converts to Chat", platform: PlatformZhipu, protocol: APIProtocolAdaptive, responsesBody: true, endpoint: "/chat/completions"},
+ {name: "model routed Responses is not OpenAI retry eligible", platform: PlatformCommandCode, protocol: APIProtocolResponses},
+ {name: "OAuth", accountType: AccountTypeOAuth},
+ {name: "authentication", status: http.StatusUnauthorized},
+ {name: "authorization", status: http.StatusForbidden},
+ {name: "rate limit", status: http.StatusTooManyRequests},
+ {name: "unrelated validation", rejection: `{"error":{"code":"invalid_type","param":"tools","message":"Expected a string, but got an array instead."}}`},
+ {name: "nested validation", rejection: `{"error":{"message":"'loc':('body','input',0,'content','str'), 'msg':'Input should be a valid string'"}}`},
+ {name: "echoed validation", rejection: `{"error":{"message":"1 validation error: [{'type':'string_type','loc':('body','model','str'),'msg':'Input should be a valid string','input':{'loc':('body','input','str'),'msg':'Input should be a valid string'}}]"}}`},
+ {name: "echoed structured error", rejection: `{"error":{"code":"invalid_type","param":"input","message":"Invalid history containing expected a string but got an array"}}`},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":false}`)
+ if test.responsesBody {
+ body = []byte(`{"model":"gpt-5.4","input":[{"role":"user","content":"hello"}],"stream":false}`)
+ }
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
+ account := structuredInputRetryTestAccount()
+ account.Extra = map[string]any{openai_compat.ExtraKeyResponsesSupported: true, openai_compat.ExtraKeyResponsesMode: test.mode}
+ if test.unknown {
+ delete(account.Extra, openai_compat.ExtraKeyResponsesSupported)
+ }
+ if test.platform != "" {
+ account.Platform = test.platform
+ account.Credentials["api_protocol"] = APIProtocolResponses
+ }
+ if test.protocol != "" {
+ account.Credentials["api_protocol"] = test.protocol
+ }
+ if test.accountType != "" {
+ account.Type = test.accountType
+ account.Credentials["access_token"] = "test-token"
+ }
+ status := test.status
+ if status == 0 {
+ status = http.StatusBadRequest
+ }
+ errorBody := rejection
+ if test.rejection != "" {
+ errorBody = test.rejection
+ }
+ upstream := &httpUpstreamRecorder{resp: &http.Response{
+ StatusCode: status,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(errorBody)),
+ }}
+ svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream}
+ var result *OpenAIForwardResult
+ var err error
+ if test.nativeIngress {
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
+ result, err = svc.Forward(context.Background(), c, account, body)
+ } else {
+ result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
+ }
+ require.Error(t, err)
+ require.Nil(t, result)
+ require.Len(t, upstream.requests, 1)
+ endpoint := test.endpoint
+ if endpoint == "" {
+ endpoint = "/responses"
+ }
+ require.True(t, strings.HasSuffix(upstream.requests[0].URL.Path, endpoint))
+ var failover *UpstreamFailoverError
+ if status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusTooManyRequests {
+ require.ErrorAs(t, err, &failover)
+ require.Equal(t, status, failover.StatusCode)
+ } else {
+ require.False(t, errors.As(err, &failover))
+ require.True(t, c.Writer.Written())
+ }
+ })
+ }
+}
+
+func TestForwardAsChatCompletions_StructuredInputRetryPreservesStreamingAndMapping(t *testing.T) {
+ for _, useAccountMapping := range []bool{false, true} {
+ t.Run(fmt.Sprintf("account_mapping=%t", useAccountMapping), func(t *testing.T) {
+ body := []byte(`{"model":"client-model","messages":[{"role":"user","content":"hello"}],"stream":true,"stream_options":{"include_usage":false},"vendor_option":"preserve"}`)
+ originalBody := append([]byte(nil), body...)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
+ account := structuredInputRetryTestAccount()
+ account.Extra = map[string]any{openai_compat.ExtraKeyResponsesSupported: true, openai_compat.ExtraKeyResponsesMode: "auto"}
+ mappedModel := "gpt-5.4"
+ if useAccountMapping {
+ account.Credentials["model_mapping"] = map[string]any{"client-model": mappedModel}
+ }
+ stream := "data: {\"id\":\"chatcmpl_retry\",\"object\":\"chat.completion.chunk\",\"model\":\"gpt-5.4\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":9,\"completion_tokens\":4,\"total_tokens\":13}}\n\ndata: [DONE]\n\n"
+ upstream := &httpUpstreamRecorder{responses: []*http.Response{
+ {StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}`))},
+ {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(stream))},
+ }}
+ svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream}
+ defaultMappedModel := mappedModel
+ if useAccountMapping {
+ defaultMappedModel = ""
+ }
+ result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", defaultMappedModel)
+ require.NoError(t, err)
+ require.Len(t, upstream.requests, 2)
+ for _, outbound := range upstream.bodies {
+ require.Equal(t, mappedModel, gjson.GetBytes(outbound, "model").String())
+ require.True(t, gjson.GetBytes(outbound, "stream").Bool())
+ }
+ require.JSONEq(t, gjson.GetBytes(body, "messages").Raw, gjson.GetBytes(upstream.bodies[1], "messages").Raw)
+ require.Equal(t, "preserve", gjson.GetBytes(upstream.bodies[1], "vendor_option").String())
+ require.True(t, gjson.GetBytes(upstream.bodies[1], "stream_options.include_usage").Bool())
+ require.Equal(t, originalBody, body)
+ require.True(t, result.Stream)
+ require.Equal(t, mappedModel, result.BillingModel)
+ require.Equal(t, mappedModel, result.UpstreamModel)
+ require.Equal(t, 9, result.Usage.InputTokens)
+ require.Equal(t, 4, result.Usage.OutputTokens)
+ require.Equal(t, "/v1/chat/completions", result.UpstreamEndpoint)
+ require.Contains(t, rec.Header().Get("Content-Type"), "text/event-stream")
+ require.Contains(t, rec.Body.String(), "data: [DONE]")
+ })
+ }
+}
+
+func TestForwardAsChatCompletions_StructuredInputRetryIsBoundedAndPreservesRawErrors(t *testing.T) {
+ for _, status := range []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusTooManyRequests} {
+ t.Run(fmt.Sprintf("status=%d", status), func(t *testing.T) {
+ rejection := `{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}`
+ response := func(status int) *http.Response {
+ return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(rejection))}
+ }
+ body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":false}`)
+ account := structuredInputRetryTestAccount()
+ account.Extra = map[string]any{openai_compat.ExtraKeyResponsesSupported: true}
+ forward := func(retry bool) (*httptest.ResponseRecorder, error) {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
+ upstream := &httpUpstreamRecorder{responses: []*http.Response{response(status)}}
+ if retry {
+ upstream.responses = append([]*http.Response{response(http.StatusBadRequest)}, upstream.responses...)
+ }
+ svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream}
+ var result *OpenAIForwardResult
+ var err error
+ if retry {
+ result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
+ require.Len(t, upstream.requests, 2)
+ require.Equal(t, "/v1/chat/completions", upstream.requests[1].URL.Path)
+ } else {
+ result, err = svc.forwardAsRawChatCompletions(context.Background(), c, account, body, "")
+ require.Len(t, upstream.requests, 1)
+ }
+ require.Nil(t, result)
+ require.Error(t, err)
+ return rec, err
+ }
+ baseline, baselineErr := forward(false)
+ retried, retryErr := forward(true)
+ require.Equal(t, baseline.Code, retried.Code)
+ require.Equal(t, baseline.Body.String(), retried.Body.String())
+ require.Equal(t, baselineErr.Error(), retryErr.Error())
+ require.IsType(t, baselineErr, retryErr)
+ })
+ }
+}
+
+func structuredInputRetryTestConfig() *config.Config {
+ return &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{
+ Enabled: false,
+ AllowInsecureHTTP: true,
+ }}}
+}
+
+func structuredInputRetryTestAccount() *Account {
+ return &Account{
+ ID: 101,
+ Name: "raw-openai-apikey",
+ Platform: PlatformOpenAI,
+ Type: AccountTypeAPIKey,
+ Concurrency: 1,
+ Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"},
+ Extra: map[string]any{openai_compat.ExtraKeyResponsesSupported: true},
+ }
+}
+
type openAIChatStreamReadErrorCloser struct {
payload []byte
err error
@@ -1322,7 +1865,7 @@ func TestGPT61SolOnlyChatFallbackRejectsToolsAndDisabledReasoning(t *testing.T)
svc := &OpenAIGatewayService{cfg: &config.Config{}}
var err error
if responses {
- _, err = svc.forwardResponsesViaRawChatCompletions(context.Background(), c, account, []byte(body))
+ _, err = svc.forwardResponsesViaRawChatCompletions(context.Background(), c, account, []byte(body), time.Now())
} else {
_, err = svc.forwardAnthropicViaRawChatCompletions(context.Background(), c, account, []byte(body), "")
}
diff --git a/backend/internal/service/openai_gateway_cn_fixes_test.go b/backend/internal/service/openai_gateway_cn_fixes_test.go
index 870f658b5..59d1950b3 100644
--- a/backend/internal/service/openai_gateway_cn_fixes_test.go
+++ b/backend/internal/service/openai_gateway_cn_fixes_test.go
@@ -74,7 +74,7 @@ func TestCalculateOpenAIRecordUsageCost_EmptyCandidatesIsPricingUnavailable(t *t
_, err := svc.calculateOpenAIRecordUsageCost(
context.Background(), nil, apiKey, nil,
- 1.0, 1.0, 1.0, 1.0, UsageTokens{InputTokens: 100}, "", nil, time.Time{},
+ 1.0, 1.0, 1.0, 1.0, UsageTokens{InputTokens: 100}, "", nil, false, time.Time{},
)
require.Error(t, err)
require.True(t, isUsagePricingUnavailableError(err),
diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go
index c582cd966..9827ca0f6 100644
--- a/backend/internal/service/openai_gateway_count_tokens.go
+++ b/backend/internal/service/openai_gateway_count_tokens.go
@@ -104,7 +104,7 @@ func (s *OpenAIGatewayService) ForwardResponsesInputTokens(
return nil
}
if s.rateLimitService != nil {
- s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody)
+ s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, prepared.UpstreamModel)
}
upstreamMsg := sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody)))
setOpsUpstreamError(c, resp.StatusCode, upstreamMsg, "")
@@ -346,7 +346,7 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic(
}
if s.rateLimitService != nil {
- s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody)
+ s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, prepared.UpstreamModel)
}
if isOpenAIInputTokensUnsupported(resp.StatusCode, respBody) {
diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go
index 751716a6c..0ae99e3ce 100644
--- a/backend/internal/service/openai_gateway_forward.go
+++ b/backend/internal/service/openai_gateway_forward.go
@@ -69,7 +69,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
if normalized {
body = normalizedBody
}
- legacyIngressBody, legacyIngressChanged, legacyIngressErr := normalizeOpenAIResponsesLegacyIngress(body)
+ legacyIngressBody, legacyIngressChanged, legacyIngressErr := normalizeOpenAIResponsesLegacyIngressWithConfig(s.cfg, body)
if legacyIngressErr != nil {
return nil, legacyIngressErr
}
@@ -194,7 +194,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
// 账号映射未命中时以去除首尾空白的请求模型兜底,计费名与上游模型名一致。
return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, reqModel)
case APIProtocolChatCompletions:
- return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body)
+ return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body, startTime)
}
SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint)
if account.IsOpenAI() && (account.IsOpenAIApiKey() || account.IsOpenAIOAuthLike()) {
diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge.go b/backend/internal/service/openai_gateway_grok_chat_bridge.go
index 326f06e5b..dfae6bf7a 100644
--- a/backend/internal/service/openai_gateway_grok_chat_bridge.go
+++ b/backend/internal/service/openai_gateway_grok_chat_bridge.go
@@ -541,7 +541,7 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses(
return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel)
}
- responsesReq, err := apicompat.ChatCompletionsToResponses(&chatReq)
+ responsesReq, err := chatCompletionsToResponses(s.cfg, &chatReq)
if err != nil {
return nil, fmt.Errorf("convert grok chat completions to responses: %w", err)
}
diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go
index 48dc7b328..9b383e379 100644
--- a/backend/internal/service/openai_gateway_messages.go
+++ b/backend/internal/service/openai_gateway_messages.go
@@ -45,6 +45,16 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic(
rememberOpenCodeInboundBody(c, body)
beginUpstreamResponseModelObservation(c)
ClearActualOpenAIUpstreamEndpoint(c)
+ // Web Search 模拟:Chat Completions 转换会丢掉 web_search 工具,纯 web_search
+ // 请求在此直接调用搜索 API 构造 Anthropic 响应,不访问上游。
+ if groupID := getOpenAIGroupIDFromContext(c); shouldEmulateWebSearchFor(ctx, s.settingService, s.channelService, account, &groupID, body) {
+ stream := gjson.GetBytes(body, "stream").Bool()
+ res, err := writeEmulatedWebSearch(ctx, c, account, body, gjson.GetBytes(body, "model").String(), stream)
+ if err != nil {
+ return nil, err
+ }
+ return &OpenAIForwardResult{Model: res.Model, Stream: stream, Duration: res.Duration}, nil
+ }
if shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
SetActualOpenAIUpstreamEndpoint(c, "/v1/chat/completions")
}
@@ -144,7 +154,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic(
// 3. Convert Anthropic → Responses after compatibility-only replay guard.
anthropicReq.Model = upstreamModel
- responsesReq, err := apicompat.AnthropicToResponses(&anthropicReq)
+ responsesReq, err := anthropicToResponses(s.cfg, &anthropicReq)
if err != nil {
return nil, fmt.Errorf("convert anthropic to responses: %w", err)
}
diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go
index 7a0e6279f..3589347d3 100644
--- a/backend/internal/service/openai_gateway_messages_chat_fallback.go
+++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go
@@ -52,7 +52,10 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions(
clientStream := anthropicReq.Stream
// 2. Anthropic → Chat Completions (direct, no Responses intermediary)
- chatReq, err := apicompat.AnthropicToChatCompletionsRequest(&anthropicReq)
+ chatReq, err := apicompat.AnthropicToChatCompletionsRequestWithMinOutputTokens(
+ &anthropicReq,
+ configuredMinOutputTokens(s.cfg),
+ )
if err != nil {
writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return nil, fmt.Errorf("convert anthropic to chat completions: %w", err)
diff --git a/backend/internal/service/openai_gateway_model_availability.go b/backend/internal/service/openai_gateway_model_availability.go
index 861d3e672..e1715bd15 100644
--- a/backend/internal/service/openai_gateway_model_availability.go
+++ b/backend/internal/service/openai_gateway_model_availability.go
@@ -56,6 +56,9 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform(
diag := ModelAvailabilityDiagnosis{}
for i := range accounts {
diag.HasAccountsInPool = true
+ if isRetiredOpenAISubscriptionModel(&accounts[i], resolveOpenAIAccountUpstreamModelForRequest(&accounts[i], requestedModel, false)) {
+ diag.HasRetiredSubscriptionModel = true
+ }
// Mirrors the per-candidate filter used during account selection
// (openai_account_scheduler.isAccountRequestCompatible): empty
// model_mapping accepts everything; otherwise the explicit / wildcard
diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go
index 7217f633d..0c90914ec 100644
--- a/backend/internal/service/openai_gateway_passthrough.go
+++ b/backend/internal/service/openai_gateway_passthrough.go
@@ -214,6 +214,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough(
if account != nil && account.IsOpenAI() {
responsesLite := isOpenAIResponsesLiteHeader(c.GetHeader(responsesLiteHeader)) || isOpenAIResponsesLiteWebSocketPayload(body)
normalizedBody, normalized, normalizeErr := normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{
+ Config: s.cfg,
ResponsesLite: responsesLite,
Compact: isOpenAIResponsesCompactPath(c),
})
@@ -1905,6 +1906,9 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough(
responseFailedPending := false
var bareErrorPayload []byte
bareErrorAccountSideEffectsPending := false
+ // Passthrough leaves upstream events untouched; the tracker only learns the
+ // upstream created_at so a synthesized response.failed matches the stream.
+ var createdAtTracker responsesCreatedAtStamper
upstreamRequestID := strings.TrimSpace(resp.Header.Get("x-request-id"))
// pendingLines 在首个可见输出前保留前导事件,确保无输出失败仍可安全 failover。
pendingLines := make([]string, 0, 8)
@@ -1979,7 +1983,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough(
if clientDisconnected || !writePendingLines() {
return
}
- if _, err := fmt.Fprint(w, buildOpenAIResponseFailedSSE(responseID, originalModel, bareErrorPayload, failedMessage)); err != nil {
+ if _, err := fmt.Fprint(w, buildOpenAIResponseFailedSSE(responseID, originalModel, createdAtTracker.Value(), bareErrorPayload, failedMessage)); err != nil {
clientDisconnected = true
return
}
@@ -2054,6 +2058,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough(
}
}
eventType := effectiveOpenAISSEEventType(dataBytes, rawEventType)
+ createdAtTracker.Observe(dataBytes, eventType)
if codexFailureTerminal && sawBareError && !sawResponseFailed && eventType != "response.failed" {
suppressCurrentEvent = true
}
diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go
index cb0173442..89b322461 100644
--- a/backend/internal/service/openai_gateway_request_body.go
+++ b/backend/internal/service/openai_gateway_request_body.go
@@ -11,6 +11,7 @@ import (
"strings"
"unicode/utf8"
+ "github.com/MACOS-DO/sub4api/internal/config"
"github.com/MACOS-DO/sub4api/internal/pkg/apicompat"
"github.com/MACOS-DO/sub4api/internal/pkg/ctxkey"
"github.com/MACOS-DO/sub4api/internal/util/urlvalidator"
@@ -1433,7 +1434,12 @@ func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Ac
return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{ResponsesLite: responsesLite})
}
+func normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(cfg *config.Config, body []byte, account *Account, responsesLite bool) ([]byte, bool, error) {
+ return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{Config: cfg, ResponsesLite: responsesLite})
+}
+
type openAIResponsesCompatibilityOptions struct {
+ Config *config.Config
ResponsesLite bool
// Compact marks the /responses/compact wire shape, which is left as-is
// by request-shape compatibility rewrites such as web_search history.
@@ -1449,7 +1455,7 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account *
changed := false
if account.IsOpenAIOAuthLike() {
var err error
- normalized, changed, err = normalizeOpenAIResponsesLegacyIngress(body)
+ normalized, changed, err = normalizeOpenAIResponsesLegacyIngressWithConfig(opts.Config, body)
if err != nil {
return body, false, err
}
diff --git a/backend/internal/service/openai_gateway_response_flush_test.go b/backend/internal/service/openai_gateway_response_flush_test.go
index 1ce961fff..df221774d 100644
--- a/backend/internal/service/openai_gateway_response_flush_test.go
+++ b/backend/internal/service/openai_gateway_response_flush_test.go
@@ -371,7 +371,7 @@ func TestOpenAIResponseFlush_KeepaliveDoesNotSplitOpenEvent(t *testing.T) {
func TestOpenAIResponseFlush_FailedAndErrorEventsFlushAtBoundaries(t *testing.T) {
t.Run("failed at EOF", func(t *testing.T) {
body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" +
- "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"},\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n"
+ "data: {\"type\":\"response.failed\",\"response\":{\"created_at\":1700000000,\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"},\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n"
recorder := newOpenAIResponseFlushRecorder()
result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{})
@@ -381,7 +381,7 @@ func TestOpenAIResponseFlush_FailedAndErrorEventsFlushAtBoundaries(t *testing.T)
require.Equal(t, 3, result.usage.InputTokens)
gotBody, flushes := recorder.snapshot()
expectedBody := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" +
- "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"}}}\n"
+ "data: {\"type\":\"response.failed\",\"response\":{\"created_at\":1700000000,\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"}}}\n"
require.Equal(t, expectedBody, gotBody)
require.Len(t, flushes, 2)
require.Contains(t, flushes[1], "response.failed")
@@ -669,7 +669,7 @@ func (r *hangingOpenAISSEAfterTerminal) Close() error {
}
func TestOpenAIResponseFlush_TerminalEventEndsStreamWithoutEOF(t *testing.T) {
- body := "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":7,\"output_tokens\":5}}}\n\n"
+ body := "data: {\"type\":\"response.completed\",\"response\":{\"created_at\":1700000000,\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":7,\"output_tokens\":5}}}\n\n"
reader := &hangingOpenAISSEAfterTerminal{payload: []byte(body), release: make(chan struct{})}
recorder := newOpenAIResponseFlushRecorder()
resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamKeepaliveInterval: 1, StreamDataIntervalTimeout: 30})
diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go
index c14793611..648638caf 100644
--- a/backend/internal/service/openai_gateway_response_handling.go
+++ b/backend/internal/service/openai_gateway_response_handling.go
@@ -341,6 +341,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context.
}
needModelReplace := originalModel != mappedModel
+ var createdAtStamper responsesCreatedAtStamper
streamOutputAccumulator := apicompat.NewBufferedResponseAccumulator()
streamDoneItems := newResponsesStreamOutputItems()
streamImageOutputs := make([]json.RawMessage, 0, 1)
@@ -382,7 +383,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context.
}
if codexFailureTerminal && sawBareError && !sawResponseFailed && !clientDisconnected {
applyAttemptResponseHeaders()
- if _, err := writePendingString(buildOpenAIResponseFailedSSE(responseID, originalModel, bareErrorPayload, failedMessage)); err != nil {
+ if _, err := writePendingString(buildOpenAIResponseFailedSSE(responseID, originalModel, createdAtStamper.Value(), bareErrorPayload, failedMessage)); err != nil {
handlePendingWriteError(err)
} else {
failureDelivered = true
@@ -667,6 +668,11 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context.
data = string(sanitizedData)
line = "data: " + data
}
+ if stampedData, stamped := createdAtStamper.Stamp(dataBytes, eventType); stamped {
+ dataBytes = stampedData
+ data = string(stampedData)
+ line = "data: " + data
+ }
// Replace model in response if needed.
if needModelReplace {
line = s.replaceModelInSSELine(line, mappedModel, originalModel)
@@ -1667,6 +1673,7 @@ func (s *OpenAIGatewayService) handleNonStreamingResponse(ctx context.Context, r
return nil, fmt.Errorf("restore OpenAI namespace response: %w", err)
}
body = restoreCodexToolNamesFromContext(c, body)
+ body = ensureOpenAIResponseObjectCreatedAt(body)
responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter)
// Codex 协议要求 /responses/compact JSON 响应携带 x-codex-turn-state
// (codex-api/src/endpoint/compact.rs 从响应头捕获),显式回传。
@@ -1767,7 +1774,7 @@ func (s *OpenAIGatewayService) handleSSEToJSON(resp *http.Response, c *gin.Conte
return nil, fmt.Errorf("restore OpenAI namespace response: %w", restoreErr)
}
restoredBody = restoreCodexToolNamesFromContext(c, restoredBody)
- body = restoredBody
+ body = ensureOpenAIResponseObjectCreatedAt(restoredBody)
} else {
if originalModel != mappedModel {
bodyText = s.replaceModelInSSEBody(bodyText, mappedModel, originalModel)
@@ -1828,7 +1835,10 @@ func extractOpenAISSEErrorMessage(payload []byte) string {
return sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(payload)))
}
-func buildOpenAIResponseFailedSSE(responseID, model string, source []byte, fallbackMessage string) string {
+// buildOpenAIResponseFailedSSE synthesizes the response.failed terminal for a
+// stream that ended on a bare error. created_at and sequence_number are always
+// written: strict clients (grok-build, Codex) reject the frame without them.
+func buildOpenAIResponseFailedSSE(responseID, model string, createdAt int64, source []byte, fallbackMessage string) string {
responseID = strings.TrimSpace(responseID)
if responseID == "" {
responseID = "resp_" + strings.ReplaceAll(uuid.NewString(), "-", "")
@@ -1855,23 +1865,31 @@ func buildOpenAIResponseFailedSSE(responseID, model string, source []byte, fallb
if errorType != "" {
errorBody["type"] = errorType
}
+ if createdAt <= 0 {
+ createdAt = time.Now().Unix()
+ }
+ sequenceNumber := openAIResponsesFailedSequenceNumber(source)
response := gin.H{
- "id": responseID,
- "object": "response",
- "status": "failed",
- "output": []any{},
- "error": errorBody,
+ "id": responseID,
+ "object": "response",
+ "created_at": createdAt,
+ "status": "failed",
+ "output": []any{},
+ "error": errorBody,
}
if model = strings.TrimSpace(model); model != "" {
response["model"] = model
}
payload, err := marshalOpenAIUpstreamJSON(gin.H{
- "type": "response.failed",
- "response": response,
+ "type": "response.failed",
+ "sequence_number": sequenceNumber,
+ "response": response,
})
if err != nil {
// All values above are JSON primitives, so this is only a defensive fallback.
- payload = []byte(`{"type":"response.failed","response":{"status":"failed","output":[],"error":{"code":"upstream_error","message":"Upstream response failed"}}}`)
+ payload = []byte(`{"type":"response.failed","sequence_number":` + strconv.FormatInt(sequenceNumber, 10) +
+ `,"response":{"object":"response","created_at":` + strconv.FormatInt(createdAt, 10) +
+ `,"status":"failed","output":[],"error":{"code":"upstream_error","message":"Upstream response failed"}}}`)
}
return "event: response.failed\ndata: " + string(payload) + "\n\n"
}
diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback.go b/backend/internal/service/openai_gateway_responses_chat_fallback.go
index 60f701ee4..b1275ea4c 100644
--- a/backend/internal/service/openai_gateway_responses_chat_fallback.go
+++ b/backend/internal/service/openai_gateway_responses_chat_fallback.go
@@ -29,9 +29,8 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions(
c *gin.Context,
account *Account,
body []byte,
+ startTime time.Time,
) (*OpenAIForwardResult, error) {
- startTime := time.Now()
-
var responsesReq apicompat.ResponsesRequest
if err := json.Unmarshal(body, &responsesReq); err != nil {
writeOpenAIResponsesFallbackError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body")
diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback_test.go b/backend/internal/service/openai_gateway_responses_chat_fallback_test.go
index ff0de70b0..40622574a 100644
--- a/backend/internal/service/openai_gateway_responses_chat_fallback_test.go
+++ b/backend/internal/service/openai_gateway_responses_chat_fallback_test.go
@@ -5,6 +5,7 @@ package service
import (
"bytes"
"context"
+ "fmt"
"io"
"net/http"
"net/http/httptest"
@@ -19,6 +20,34 @@ import (
"github.com/tidwall/gjson"
)
+func TestForwardResponses_ChatFallbackPreservesProvidedStartTime(t *testing.T) {
+ for _, stream := range []bool{false, true} {
+ t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) {
+ body := []byte(fmt.Sprintf(`{"model":"gpt-5.4","input":"hello","stream":%t}`, stream))
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
+ responseBody := `{"id":"chatcmpl_timing","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`
+ contentType := "application/json"
+ if stream {
+ responseBody = "data: {\"id\":\"chatcmpl_timing\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1,\"total_tokens\":2}}\n\ndata: [DONE]\n\n"
+ contentType = "text/event-stream"
+ }
+ upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(responseBody))}}
+ svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
+ startTime := time.Now().Add(-time.Minute)
+ result, err := svc.forwardResponsesViaRawChatCompletions(context.Background(), c, forceChatResponsesFallbackAccount(), body, startTime)
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.GreaterOrEqual(t, result.Duration, time.Minute)
+ if stream {
+ require.NotNil(t, result.FirstTokenMs)
+ require.GreaterOrEqual(t, *result.FirstTokenMs, int(time.Minute.Milliseconds()))
+ }
+ })
+ }
+}
+
func TestForwardResponses_ForceChatCompletionsRoutesNonStreamingToChatCompletions(t *testing.T) {
gin.SetMode(gin.TestMode)
diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go
index 380186ddd..acdc6f6e3 100644
--- a/backend/internal/service/openai_gateway_scheduling.go
+++ b/backend/internal/service/openai_gateway_scheduling.go
@@ -446,7 +446,7 @@ func openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx context.Con
return "quota_auto_pause"
}
}
- if requestedModel != "" && !account.IsModelSupported(requestedModel) {
+ if requestedModel != "" && !supportsOpenAIRequestModel(account, requestedModel, requireCompact) {
return "model_not_supported"
}
if !account.SupportsOpenAIEndpointCapability(requiredCapability) {
diff --git a/backend/internal/service/openai_gateway_search_surcharge_test.go b/backend/internal/service/openai_gateway_search_surcharge_test.go
index d2d069ff5..ed9aed830 100644
--- a/backend/internal/service/openai_gateway_search_surcharge_test.go
+++ b/backend/internal/service/openai_gateway_search_surcharge_test.go
@@ -38,6 +38,7 @@ func TestCalculateOpenAIRecordUsageCost_SearchIsAdditiveToTokens(t *testing.T) {
UsageTokens{InputTokens: 1000, OutputTokens: 500},
"",
boolPtr(false),
+ false,
time.Time{},
)
require.NoError(t, err)
@@ -69,6 +70,7 @@ func TestCalculateOpenAIRecordUsageCost_SearchOnlyWhenNoTokenPricing(t *testing.
UsageTokens{},
"",
boolPtr(false),
+ false,
time.Time{},
)
require.NoError(t, err)
@@ -115,6 +117,7 @@ func TestCalculateOpenAIRecordUsageCost_TokenPricingErrorNotSwallowedBySearch(t
UsageTokens{InputTokens: 1000, OutputTokens: 500},
"",
boolPtr(false),
+ false,
time.Time{},
)
require.Error(t, err)
diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go
index 39da12304..ed0d8eb89 100644
--- a/backend/internal/service/openai_gateway_service.go
+++ b/backend/internal/service/openai_gateway_service.go
@@ -627,7 +627,14 @@ func (s *OpenAIGatewayService) ResolveChannelMappingAndRestrict(ctx context.Cont
return s.channelService.ResolveChannelMappingAndRestrict(ctx, groupID, model)
}
+// isCodexImageGenerationBridgeEnabled 决定是否为 Codex 客户端自动注入 hosted
+// image_generation 工具。该工具是 OpenAI Responses 专属能力,Kimi / DeepSeek /
+// MiniMax 等经 OpenAI 网关转发的原生 Responses 上游不识别,注入后会被 400 拒绝,
+// 因此非 OpenAI 平台账号一律不桥接,后续再按账号 → 渠道 → 全局的优先级取开关。
func (s *OpenAIGatewayService) isCodexImageGenerationBridgeEnabled(ctx context.Context, account *Account, apiKey *APIKey) bool {
+ if account == nil || account.Platform != PlatformOpenAI {
+ return false
+ }
if override := account.CodexImageGenerationBridgeOverride(); override != nil {
return *override
}
diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go
index b2a2f4c4e..bfce11ba1 100644
--- a/backend/internal/service/openai_gateway_usage.go
+++ b/backend/internal/service/openai_gateway_usage.go
@@ -14,6 +14,7 @@ import (
"github.com/MACOS-DO/sub4api/internal/config"
"github.com/MACOS-DO/sub4api/internal/pkg/logger"
+ "github.com/MACOS-DO/sub4api/internal/pkg/openai"
"github.com/MACOS-DO/sub4api/internal/pkg/timezone"
"go.uber.org/zap"
)
@@ -236,6 +237,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
serviceTier = strings.TrimSpace(*result.ServiceTier)
}
longContextBillingGate := openAILongContextBillingGate(billingAccount)
+ modelLongContextExempt := openAISubscriptionLongContextExempt(billingAccount, result)
cost, err = s.calculateOpenAIRecordUsageCost(
ctx,
result,
@@ -248,6 +250,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
tokens,
serviceTier,
longContextBillingGate,
+ modelLongContextExempt,
pricingAt,
)
if err != nil {
@@ -281,7 +284,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
responseModels := s.filterCNProviderBillingModelCandidates(ctx, account, apiKey, usageBillingModelCandidates(responseModel))
responseCost, responseErr := s.calculateOpenAIRecordUsageCost(
ctx, result, apiKey, responseModels, multiplier, imageMultiplier,
- videoMultiplier, baseMultiplier, tokens, serviceTier, longContextBillingGate, pricingAt,
+ videoMultiplier, baseMultiplier, tokens, serviceTier, longContextBillingGate, modelLongContextExempt, pricingAt,
)
// 基线定价源以 baselineBillingModel 为准:它正是 calculateOpenAIRecordUsageCost
// 内部做渠道定价判断时使用的模型,且"首候选有渠道价"必然意味着首候选就是实际
@@ -312,6 +315,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
tokens,
"",
longContextBillingGate,
+ modelLongContextExempt,
pricingAt,
)
if standardErr != nil && !isUsagePricingUnavailableError(standardErr) {
@@ -484,7 +488,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
applyAccountStatsCost(ctx, usageLog, s.channelService, s.billingService,
account.ID, *apiKey.GroupID, result.UpstreamModel, result.Model,
tokens, cost.TotalCost, pricingAt,
- accountStatsLongContextPricingEnabled(longContextBillingGate),
+ accountStatsLongContextPricingEnabled(longContextBillingGate) && !modelLongContextExempt,
)
}
@@ -557,6 +561,20 @@ func openAILongContextBillingGate(account *Account) *bool {
return &enabled
}
+// openAISubscriptionLongContextExempt 按实际凭据和最终发送模型判断订阅豁免。
+// GPT-6.1 Sol 的订阅请求不再收取模型长上下文附加费;API Key 仍使用 API 价卡。
+// 使用发送模型,避免客户别名、渠道计费模型或响应模型计费切换改变上游订阅规则。
+func openAISubscriptionLongContextExempt(account *Account, result *OpenAIForwardResult) bool {
+ if !account.IsOpenAIOAuthLike() || result == nil {
+ return false
+ }
+ model := strings.TrimSpace(result.UpstreamModel)
+ if model == "" {
+ model = result.Model
+ }
+ return openai.IsGPT61SolModelSpelling(model)
+}
+
func (s *OpenAIGatewayService) calculateOpenAIRecordUsageCost(
ctx context.Context,
result *OpenAIForwardResult,
@@ -569,6 +587,7 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageCost(
tokens UsageTokens,
serviceTier string,
longContextBillingGate *bool,
+ modelLongContextExempt bool,
pricingAt time.Time,
) (*CostBreakdown, error) {
billingModel := firstUsageBillingModel(billingModels)
@@ -625,6 +644,7 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageCost(
serviceTier,
optionalStringValue(result.ReasoningEffort),
longContextBillingGate,
+ modelLongContextExempt,
)
if err == nil {
tokenCost = cost
@@ -719,6 +739,7 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageTokenCost(
serviceTier string,
reasoningEffort string,
longContextBillingGate *bool,
+ modelLongContextExempt bool,
) (*CostBreakdown, error) {
if s.resolver != nil && apiKey.Group != nil {
gid := apiKey.Group.ID
@@ -726,7 +747,8 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageTokenCost(
Ctx: ctx, Model: billingModel, GroupID: &gid, Group: apiKey.Group,
Tokens: tokens, RequestCount: 1, RateMultiplier: multiplier, PricingAt: pricingAt,
ServiceTier: serviceTier, ReasoningEffort: reasoningEffort, Resolver: s.resolver,
- LongContextBillingEnabled: longContextBillingGate,
+ LongContextBillingEnabled: longContextBillingGate,
+ DisableModelLongContextPricing: modelLongContextExempt,
})
}
return s.billingService.calculateCostWithServiceTierPolicy(
@@ -734,7 +756,7 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageTokenCost(
tokens,
multiplier,
serviceTier,
- longContextBillingGate == nil || *longContextBillingGate,
+ (longContextBillingGate == nil || *longContextBillingGate) && !modelLongContextExempt,
)
}
diff --git a/backend/internal/service/openai_image_generation_controls_test.go b/backend/internal/service/openai_image_generation_controls_test.go
index 53afc1653..8270da82d 100644
--- a/backend/internal/service/openai_image_generation_controls_test.go
+++ b/backend/internal/service/openai_image_generation_controls_test.go
@@ -424,6 +424,76 @@ func TestOpenAIGatewayServiceForward_CodexBridgePreservesExistingToolChoice(t *t
require.Equal(t, "image_generation", gjson.GetBytes(upstream.lastBody, "tool_choice.type").String())
}
+// 国产原生 Responses 账号(Kimi / DeepSeek / MiniMax)在桥接由渠道级开关或全局开关
+// 单独打开时,发往上游的请求体都不能带 hosted image_generation 工具 / tool_choice / 桥接指令。
+func TestOpenAIGatewayServiceForward_CodexBridgeSkipsNativeCNResponsesAccounts(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ groupID := int64(4242)
+ triggers := []struct {
+ name string
+ global bool
+ channel *Channel
+ }{
+ {
+ name: "channel_openai_true_global_off",
+ global: false,
+ channel: &Channel{ID: 1, Status: StatusActive, FeaturesConfig: map[string]any{
+ featureKeyCodexImageGenerationBridge: map[string]any{PlatformOpenAI: true},
+ }},
+ },
+ {
+ name: "global_on_no_channel",
+ global: true,
+ },
+ }
+ for _, platform := range []string{PlatformKimi, PlatformDeepseek, PlatformMiniMax} {
+ for _, trig := range triggers {
+ t.Run(platform+"/"+trig.name, func(t *testing.T) {
+ upstream := &httpUpstreamRecorder{
+ resp: &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(`{"id":"resp_cn_codex","model":"cn-model","usage":{"input_tokens":1,"output_tokens":1}}`)),
+ },
+ }
+ svc := newOpenAIImageGenerationControlTestService(upstream)
+ svc.cfg.Gateway.CodexImageGenerationBridgeEnabled = trig.global
+ if trig.channel != nil {
+ svc.channelService = newOpenAIImageGenerationControlChannelService(groupID, trig.channel)
+ }
+ c, _ := newOpenAIImageGenerationControlTestContext(true, "codex_cli_rs/0.144.1")
+ account := &Account{
+ ID: 6100,
+ Name: platform + "-native-responses",
+ Platform: platform,
+ Type: AccountTypeAPIKey,
+ Status: StatusActive,
+ Schedulable: true,
+ Concurrency: 1,
+ Credentials: map[string]any{
+ "api_key": "sk-cn-test",
+ "api_protocol": APIProtocolResponses,
+ },
+ }
+ // 前置条件:账号确实走原生 Responses 转发,而不是 Chat Completions 转换链。
+ require.True(t, account.UsesNativeCNResponses())
+ require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account))
+
+ result, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"cn-model","input":"hello","stream":false,"tools":[{"type":"function","name":"shell","parameters":{"type":"object"}}]}`))
+
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.NotNil(t, upstream.lastReq)
+ require.Falsef(t, gjson.GetBytes(upstream.lastBody, `tools.#(type=="image_generation")`).Exists(), "image_generation tool injected into %s upstream body", platform)
+ require.Falsef(t, gjson.GetBytes(upstream.lastBody, "tool_choice").Exists(), "tool_choice injected into %s upstream body", platform)
+ require.NotContains(t, gjson.GetBytes(upstream.lastBody, "instructions").String(), codexImageGenerationBridgeMarker)
+ require.Equal(t, "shell", gjson.GetBytes(upstream.lastBody, "tools.0.name").String())
+ })
+ }
+ }
+}
+
func TestOpenAIGatewayServiceForward_CodexBridgeSkipsCompactRequests(t *testing.T) {
gin.SetMode(gin.TestMode)
@@ -524,6 +594,42 @@ func TestOpenAIGatewayService_CodexImageGenerationBridgeOverridePrecedence(t *te
},
want: false,
},
+ {
+ name: "kimi account ignores channel openai true",
+ global: false,
+ channel: &Channel{ID: 1, Status: StatusActive, FeaturesConfig: map[string]any{
+ featureKeyCodexImageGenerationBridge: map[string]any{PlatformOpenAI: true},
+ }},
+ account: &Account{Platform: PlatformKimi, Type: AccountTypeAPIKey},
+ want: false,
+ },
+ {
+ name: "kimi account ignores enabled global",
+ global: true,
+ account: &Account{Platform: PlatformKimi, Type: AccountTypeAPIKey},
+ want: false,
+ },
+ {
+ name: "deepseek account ignores enabled global",
+ global: true,
+ account: &Account{Platform: PlatformDeepseek, Type: AccountTypeAPIKey},
+ want: false,
+ },
+ {
+ name: "minimax account ignores channel openai true",
+ global: false,
+ channel: &Channel{ID: 1, Status: StatusActive, FeaturesConfig: map[string]any{
+ featureKeyCodexImageGenerationBridge: map[string]any{PlatformOpenAI: true},
+ }},
+ account: &Account{Platform: PlatformMiniMax, Type: AccountTypeAPIKey},
+ want: false,
+ },
+ {
+ name: "nil account never bridges",
+ global: true,
+ account: nil,
+ want: false,
+ },
}
for _, tt := range tests {
diff --git a/backend/internal/service/openai_model_retirement.go b/backend/internal/service/openai_model_retirement.go
new file mode 100644
index 000000000..d928c8ef2
--- /dev/null
+++ b/backend/internal/service/openai_model_retirement.go
@@ -0,0 +1,91 @@
+package service
+
+import (
+ "encoding/json"
+ "strings"
+)
+
+// GPT-5.5 retired from Codex with ChatGPT sign-in on 2026-10-14 at
+// 19:00 UTC. API-key upstreams remain supported. Do not infer upstream
+// eligibility from the API key a client uses to authenticate to this gateway.
+// https://learn.chatgpt.com/docs/models#gpt-55-retirement
+func isRetiredOpenAISubscriptionModel(account *Account, upstreamModel string) bool {
+ if account == nil || !account.IsOpenAI() || (!account.IsOpenAIOAuthLike() && !account.IsShadow()) {
+ return false
+ }
+ model := canonicalizeOpenAIModelAliasSpelling(upstreamModel)
+ return model == "gpt-5.5" || strings.HasPrefix(model, "gpt-5.5-")
+}
+
+// Only remove entries blocked by retirement. Unknown models and other platforms
+// retain their existing listing policy. An explicitly mapped replacement is
+// allowed, but a public alias targeting retired GPT-5.5 is not.
+func openAIModelRetiredForAccounts(accounts []Account, modelID string) bool {
+ retired := false
+ for i := range accounts {
+ account := &accounts[i]
+ if !account.IsOpenAI() {
+ continue
+ }
+ target := resolveOpenAIAccountUpstreamModelForRequest(account, modelID, false)
+ if isRetiredOpenAISubscriptionModel(account, target) {
+ retired = true
+ } else if account.IsModelSupported(modelID) {
+ return false
+ }
+ }
+ return retired
+}
+
+func filterRetiredOpenAIModelIDs(accounts []Account, models []string) []string {
+ filtered := make([]string, 0, len(models))
+ for _, model := range models {
+ if !openAIModelRetiredForAccounts(accounts, model) {
+ filtered = append(filtered, model)
+ }
+ }
+ return filtered
+}
+
+// Entries must already use client-visible names, not raw upstream IDs. Resolve
+// each public name exactly as routing does, after projection and before the
+// final client ETag is calculated. Preserve unknown fields.
+func filterRetiredOpenAIPublicModelsBody(body []byte, accounts []Account, codex bool) ([]byte, bool, error) {
+ field, idField := "data", "id"
+ if codex {
+ field, idField = "models", "slug"
+ }
+ envelope, entries, err := modelCatalogEntries(body, field)
+ if err != nil {
+ return nil, false, err
+ }
+ filtered := make([]json.RawMessage, 0, len(entries))
+ for _, raw := range entries {
+ var entry map[string]json.RawMessage
+ var id string
+ if json.Unmarshal(raw, &entry) == nil {
+ _ = json.Unmarshal(entry[idField], &id)
+ }
+ if !openAIModelRetiredForAccounts(accounts, id) {
+ filtered = append(filtered, raw)
+ }
+ }
+ if len(filtered) == len(entries) {
+ return body, false, nil
+ }
+ envelope[field], err = json.Marshal(filtered)
+ if err != nil {
+ return nil, false, err
+ }
+ encoded, err := json.Marshal(envelope)
+ return encoded, true, err
+}
+
+// Compact-only administrator mappings are evaluated against their actual
+// target, without treating an old client-visible name as a retired target.
+func supportsOpenAIRequestModel(account *Account, requestedModel string, requireCompact bool) bool {
+ if isRetiredOpenAISubscriptionModel(account, resolveOpenAIAccountUpstreamModelForRequest(account, requestedModel, requireCompact)) {
+ return false
+ }
+ return account.isModelMappingSupported(requestedModel)
+}
diff --git a/backend/internal/service/openai_model_retirement_test.go b/backend/internal/service/openai_model_retirement_test.go
new file mode 100644
index 000000000..4b31b7e1f
--- /dev/null
+++ b/backend/internal/service/openai_model_retirement_test.go
@@ -0,0 +1,236 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+func TestGPT55RetirementModelSupport(t *testing.T) {
+ for _, typ := range []string{AccountTypeOAuth, AccountTypeSetupToken, AccountTypeAPIKey} {
+ for _, passthrough := range []bool{false, true} {
+ t.Run(typ+"/passthrough="+map[bool]string{true: "true", false: "false"}[passthrough], func(t *testing.T) {
+ account := &Account{Platform: PlatformOpenAI, Type: typ, Extra: map[string]any{"openai_passthrough": passthrough}}
+ for _, model := range []string{"gpt-5.5", "openai/gpt-5.5-high", "gpt-5.5-2026-04-23", "GPT_5.5", "gpt-5.5-openai-compact"} {
+ require.Equal(t, typ == AccountTypeAPIKey, account.IsModelSupported(model), model)
+ }
+ require.True(t, account.IsModelSupported("gpt-6.1-sol"))
+ })
+ }
+ }
+ for _, mapping := range []map[string]any{
+ {"legacy": "gpt-5.5"}, {"legacy*": "gpt-5.5"},
+ } {
+ account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": mapping}}
+ require.False(t, account.IsModelSupported("legacy"))
+ }
+ account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": map[string]any{"gpt-5.5": "gpt-6.1-sol"}}}
+ require.True(t, account.IsModelSupported("gpt-5.5"), "explicit administrator replacement remains authoritative")
+ account.Type = AccountTypeAPIKey
+ require.True(t, account.IsModelSupported("gpt-5.5"))
+ parent := int64(3)
+ shadow := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, ParentAccountID: &parent}
+ require.False(t, shadow.IsModelSupported("gpt-5.5"))
+ require.False(t, isRetiredOpenAISubscriptionModel(&Account{Platform: PlatformAnthropic, Type: AccountTypeOAuth}, "gpt-5.5"))
+ require.False(t, isRetiredOpenAISubscriptionModel(account, "gpt-5.50"))
+}
+
+func TestGPT55RetirementCatalogs(t *testing.T) {
+ oauth := Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth}
+ api := Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
+ group := &Group{ID: 1, Platform: PlatformOpenAI}
+ for _, tc := range []struct {
+ name string
+ accounts []Account
+ wantGPT55 bool
+ }{
+ {"oauth", []Account{oauth}, false}, {"api", []Account{api}, true}, {"mixed", []Account{oauth, api}, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ repo := codexModelsVisibilityAccountRepo{byGroup: map[int64][]Account{1: tc.accounts}}
+ gateway := &GatewayService{accountRepo: repo}
+ models := gateway.GetAvailableModels(context.Background(), &group.ID, PlatformOpenAI)
+ if models != nil {
+ require.Equal(t, tc.wantGPT55, containsModelID(models, "gpt-5.5"))
+ }
+ body, err := buildCodexModelsManifestForAccounts(PlatformOpenAI, []string{"gpt-5.5", "gpt-6.1-sol"}, tc.accounts, group, nil, true)
+ require.NoError(t, err)
+ require.Equal(t, tc.wantGPT55, containsManifestModel(body, "gpt-5.5"))
+ // A stale/pinned upstream body must be filtered before evaluating its old ETag.
+ original := []byte(`{"models":[{"slug":"gpt-5.5","unknown":1},{"slug":"gpt-6.1-sol","unknown":2}],"unknown_top":3}`)
+ etag := CodexModelsManifestETag(original)
+ manifest := &OpenAIModelsResponse{Body: original, ETag: etag}
+ service := &OpenAIGatewayService{accountRepo: repo}
+ require.NoError(t, service.MergeGroupConfiguredCodexModels(context.Background(), group, manifest, etag))
+ if !tc.wantGPT55 {
+ require.False(t, manifest.NotModified)
+ require.NotEqual(t, etag, manifest.ETag)
+ require.False(t, containsManifestModel(manifest.Body, "gpt-5.5"))
+ require.Equal(t, int64(3), gjson.GetBytes(manifest.Body, "unknown_top").Int())
+ require.Equal(t, int64(2), gjson.GetBytes(manifest.Body, "models.0.unknown").Int())
+ }
+ })
+ }
+ // All configured entries retired: plain discovery must remain an authoritative empty list.
+ oauth.Credentials = map[string]any{"model_mapping": map[string]any{"gpt-5.5": "gpt-5.5"}}
+ repo := codexModelsVisibilityAccountRepo{byGroup: map[int64][]Account{1: {oauth}}}
+ models := (&GatewayService{accountRepo: repo}).GetAvailableModels(context.Background(), &group.ID, PlatformOpenAI)
+ require.NotNil(t, models)
+ require.Empty(t, models)
+}
+
+func containsModelID(models []string, id string) bool {
+ for _, model := range models {
+ if model == id {
+ return true
+ }
+ }
+ return false
+}
+func containsManifestModel(body []byte, id string) bool {
+ for _, m := range gjson.GetBytes(body, "models").Array() {
+ if m.Get("slug").String() == id {
+ return true
+ }
+ }
+ return false
+}
+
+func TestGPT55RetirementAccountProjection(t *testing.T) {
+ body := []byte(`{"object":"list","data":[{"id":"gpt-5.5"},{"id":"gpt-6.1-sol","unknown":true}],"unknown_top":true}`)
+ for _, typ := range []string{AccountTypeOAuth, AccountTypeAPIKey} {
+ account := &Account{Platform: PlatformOpenAI, Type: typ}
+ got, err := projectAccountModelsBody(body, account, nil, false)
+ require.NoError(t, err)
+ require.Equal(t, typ == AccountTypeAPIKey, strings.Contains(string(got), "gpt-5.5"))
+ require.True(t, gjson.GetBytes(got, "unknown_top").Bool())
+ require.True(t, json.Valid(got))
+ }
+}
+
+func TestGPT55RetirementProjectionUsesPublicNames(t *testing.T) {
+ for _, codex := range []bool{false, true} {
+ field, idField := "data", "id"
+ if codex {
+ field, idField = "models", "slug"
+ }
+ for _, tc := range []struct {
+ name string
+ mapping map[string]any
+ passthrough bool
+ api bool
+ want map[string]string
+ }{
+ {"one-hop", map[string]any{"legacy": "gpt-5.5", "gpt-5.5": "gpt-6.1-sol"}, false, false, map[string]string{"gpt-5.5": "live"}},
+ {"crossed", map[string]any{"gpt-6.1-sol": "gpt-5.5", "gpt-5.5": "gpt-6.1-sol"}, false, false, map[string]string{"gpt-5.5": "live"}},
+ {"wildcard", map[string]any{"legacy*": "gpt-5.5", "gpt-5.5": "gpt-6.1-sol"}, false, false, map[string]string{"gpt-5.5": "live"}},
+ {"passthrough", map[string]any{"gpt-6.1-sol": "gpt-5.5", "gpt-5.5": "gpt-6.1-sol"}, true, false, map[string]string{"gpt-6.1-sol": "live"}},
+ {"api", map[string]any{"legacy": "gpt-5.5", "gpt-5.5": "gpt-6.1-sol"}, false, true, map[string]string{"legacy": "retired", "gpt-5.5": "live"}},
+ } {
+ t.Run(field+"/"+tc.name, func(t *testing.T) {
+ account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth,
+ Credentials: map[string]any{"model_mapping": tc.mapping}, Extra: map[string]any{"openai_passthrough": tc.passthrough}}
+ if tc.api {
+ account.Type = AccountTypeAPIKey
+ }
+ group := &Group{Platform: PlatformOpenAI, ModelAllowlist: GroupModelAllowlist{Enabled: true, Models: []string{"legacy", "gpt-5.5", "gpt-6.1-sol"}}}
+ body, err := json.Marshal(map[string]any{field: []map[string]any{
+ {idField: "gpt-5.5", "source": "retired"}, {idField: "gpt-6.1-sol", "source": "live"},
+ }, "unknown_top": true})
+ require.NoError(t, err)
+ original := string(body)
+ got, err := projectAccountModelsBody(body, account, group, codex)
+ require.NoError(t, err)
+ require.Equal(t, original, string(body), "shared upstream cache must remain unchanged")
+ require.True(t, gjson.GetBytes(got, "unknown_top").Bool())
+ entries := gjson.GetBytes(got, field).Array()
+ require.Len(t, entries, len(tc.want), string(got))
+ for _, entry := range entries {
+ id := entry.Get(idField).String()
+ require.Contains(t, tc.want, id)
+ require.Equal(t, tc.want[id], entry.Get("source").String(), "metadata must come from the one-hop upstream target")
+ require.True(t, account.IsModelSupported(id), "catalog and routing must agree for %s", id)
+ }
+ if codex {
+ response := &OpenAIModelsResponse{Body: body, ETag: CodexModelsManifestETag(body)}
+ require.NoError(t, ApplyPinnedCodexModelsMapping(response, account, group))
+ require.JSONEq(t, string(got), string(response.Body))
+ require.Equal(t, codexModelsManifestBodyETag(response.Body), response.ETag)
+ group.ID = 1
+ group.CodexModelsManifestConfig.Enabled = true
+ service := &OpenAIGatewayService{accountRepo: codexModelsVisibilityAccountRepo{byGroup: map[int64][]Account{1: {*account}}}}
+ require.NoError(t, service.MergeGroupConfiguredCodexModels(context.Background(), group, response, CodexModelsManifestETag(body)))
+ require.False(t, response.NotModified, "an upstream ETag must not hide the projected catalog")
+ require.Equal(t, codexModelsManifestBodyETag(response.Body), response.ETag)
+ require.NoError(t, service.MergeGroupConfiguredCodexModels(context.Background(), group, response, response.ETag))
+ require.True(t, response.NotModified, "the final public ETag must support conditional requests")
+ }
+ })
+ }
+ }
+}
+
+func TestGPT55RetirementCompactFallbackKeepsSelectedModel(t *testing.T) {
+ for _, passthrough := range []bool{false, true} {
+ account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1,
+ Credentials: map[string]any{"access_token": "test-token"}, Extra: map[string]any{"openai_passthrough": passthrough}}
+ upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"id":"compact","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`))}}
+ svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{OpenAICompactModel: "gpt-5.5"}}, httpUpstream: upstream}
+ require.Empty(t, svc.resolveOpenAICompactFallbackModel(account, "gpt-6.1-sol"))
+ c := newOpenAICompactFallbackTestContext(t, "/v1/responses/compact")
+ _, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-6.1-sol","input":[],"instructions":"compact","stream":false}`))
+ require.NoError(t, err)
+ require.Equal(t, "gpt-6.1-sol", gjson.GetBytes(upstream.lastBody, "model").String())
+ account.Type = AccountTypeAPIKey
+ require.Equal(t, "gpt-5.5", svc.resolveOpenAICompactFallbackModel(account, "gpt-6.1-sol"))
+ }
+}
+
+func TestGPT55RetirementSchedulerAndDiagnosis(t *testing.T) {
+ ctx := context.Background()
+ groupID := int64(1)
+ oauth := Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true}
+ api := Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true}
+ for _, typ := range []string{AccountTypeOAuth, AccountTypeSetupToken, AccountTypeAPIKey} {
+ account := oauth
+ account.Type = typ
+ scheduler := &defaultOpenAIAccountScheduler{}
+ ok, _ := scheduler.isAccountRequestCompatibleReason(ctx, &account, OpenAIAccountScheduleRequest{RequestedModel: "gpt-5.5"})
+ require.Equal(t, typ == AccountTypeAPIKey, ok)
+ reason := openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx, &account, PlatformOpenAI, "gpt-5.5", false, "")
+ require.Equal(t, typ == AccountTypeAPIKey, reason == "")
+ }
+ oauth.Credentials = map[string]any{"compact_model_mapping": map[string]any{"gpt-6.1-sol": "gpt-5.5"}}
+ scheduler := &defaultOpenAIAccountScheduler{}
+ ok, reason := scheduler.isAccountRequestCompatibleReason(ctx, &oauth, OpenAIAccountScheduleRequest{RequestedModel: "gpt-6.1-sol", RequireCompact: true})
+ require.False(t, ok)
+ require.Equal(t, "model_not_supported", reason)
+ svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{OpenAICompactModel: "gpt-6.1-sol"}}}
+ require.Empty(t, svc.resolveOpenAICompactFallbackModel(&oauth, "gpt-6.1-sol"), "native compact retries must not use a retired explicit target")
+ oauth.Credentials = map[string]any{"compact_model_mapping": map[string]any{"gpt-5.5": "gpt-6.1-sol"}}
+ ok, _ = scheduler.isAccountRequestCompatibleReason(ctx, &oauth, OpenAIAccountScheduleRequest{RequestedModel: "gpt-5.5", RequireCompact: true})
+ require.True(t, ok, "an explicit compact replacement remains usable")
+ for _, accounts := range [][]Account{{oauth}, {oauth, api}} {
+ svc := &OpenAIGatewayService{accountRepo: codexModelsVisibilityAccountRepo{byGroup: map[int64][]Account{groupID: accounts}}}
+ diagnosis := svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.5", PlatformOpenAI)
+ require.True(t, diagnosis.HasAccountsInPool)
+ require.True(t, diagnosis.HasRetiredSubscriptionModel)
+ require.Equal(t, len(accounts) == 2, diagnosis.HasModelSupport)
+ }
+}
+
+func TestGPT55RetirementEmptyListingSource(t *testing.T) {
+ // A configured alias targeting retired GPT-5.5 must not reappear in a generated catalog.
+ account := Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": map[string]any{"legacy": "gpt-5.5"}}}
+ require.Empty(t, openAIConfiguredCodexModelIDsForGroup([]Account{account}, nil))
+ body, err := buildCodexModelsManifestForAccounts(PlatformComposite, []string{"gpt-5.5", "gpt-6.1-sol"}, []Account{account}, nil, nil, true)
+ require.NoError(t, err)
+ require.False(t, containsManifestModel(body, "gpt-5.5"))
+}
diff --git a/backend/internal/service/openai_models_list.go b/backend/internal/service/openai_models_list.go
index 634d65937..b6f68e18c 100644
--- a/backend/internal/service/openai_models_list.go
+++ b/backend/internal/service/openai_models_list.go
@@ -161,10 +161,22 @@ func standardOpenAIModelsBody(body []byte, fromManifest bool) ([]byte, error) {
}{Object: "list", Data: models})
}
-// projectAccountModelsBody applies the same public-name mapping to both model
-// representations while retaining the source entry's metadata. It never changes
-// the shared response and never synthesizes models absent from this account.
+// projectAccountModelsBody projects upstream entries to public names before
+// checking their routing eligibility. Applying account mappings to source IDs
+// would interpret upstream names as aliases and can retain retired targets or
+// discard metadata needed by a valid replacement alias.
func projectAccountModelsBody(body []byte, account *Account, group *Group, codex bool) ([]byte, error) {
+ projected, err := projectAccountModelAliases(body, account, group, codex)
+ if err != nil {
+ return nil, err
+ }
+ filtered, _, err := filterRetiredOpenAIPublicModelsBody(projected, []Account{*account}, codex)
+ return filtered, err
+}
+
+// projectAccountModelAliases retains the source entry's metadata, never changes
+// the shared response, and never synthesizes models absent from this account.
+func projectAccountModelAliases(body []byte, account *Account, group *Group, codex bool) ([]byte, error) {
if account.IsOpenAIPassthroughEnabled() || len(account.GetModelMapping()) == 0 {
return body, nil
}
diff --git a/backend/internal/service/openai_request_timezone.go b/backend/internal/service/openai_request_timezone.go
index a89216e2a..36babdc21 100644
--- a/backend/internal/service/openai_request_timezone.go
+++ b/backend/internal/service/openai_request_timezone.go
@@ -36,6 +36,9 @@ func ValidateOpenAIRequestTimezoneExtra(platform string, extra map[string]any) e
if extra == nil {
return nil
}
+ if err := validateOpenAIRequestTimezoneModeExtra(platform, extra); err != nil {
+ return err
+ }
raw, exists := extra[openAIRequestTimezoneExtraKey]
if !exists || raw == nil {
return nil
diff --git a/backend/internal/service/openai_request_timezone_detect.go b/backend/internal/service/openai_request_timezone_detect.go
new file mode 100644
index 000000000..f13a5c5c0
--- /dev/null
+++ b/backend/internal/service/openai_request_timezone_detect.go
@@ -0,0 +1,241 @@
+package service
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+)
+
+const (
+ openAIRequestTimezoneModeExtraKey = "openai_request_timezone_mode"
+ openAIRequestTimezoneDetectedExtraKey = "openai_request_timezone_detected"
+
+ // OpenAIRequestTimezoneModeFixed 使用账号上手选的固定时区(缺省值,存量账号均为此模式)。
+ OpenAIRequestTimezoneModeFixed = "fixed"
+ // OpenAIRequestTimezoneModeFollowProxy 时区跟随账号出口 IP:修改代理后检测出口所在地时区并写回账号。
+ OpenAIRequestTimezoneModeFollowProxy = "follow_proxy"
+
+ openAIRequestTimezoneDetectTimeout = 30 * time.Second
+)
+
+// OpenAIRequestTimezoneDetection 是最近一次出口时区检测的结果,存于 extra.openai_request_timezone_detected。
+// 检测失败时 Error 非空,Timezone 为空,账号继续沿用上一次成功写入的 openai_request_timezone。
+type OpenAIRequestTimezoneDetection struct {
+ IP string `json:"ip,omitempty"`
+ Country string `json:"country,omitempty"`
+ Region string `json:"region,omitempty"`
+ City string `json:"city,omitempty"`
+ Timezone string `json:"timezone,omitempty"`
+ ProxyID *int64 `json:"proxy_id,omitempty"`
+ DetectedAt string `json:"detected_at"`
+ Error string `json:"error,omitempty"`
+}
+
+var openAIRequestTimezoneDetecting sync.Map
+
+func (account *Account) OpenAIRequestTimezoneMode() string {
+ if account != nil && account.getExtraString(openAIRequestTimezoneModeExtraKey) == OpenAIRequestTimezoneModeFollowProxy {
+ return OpenAIRequestTimezoneModeFollowProxy
+ }
+ return OpenAIRequestTimezoneModeFixed
+}
+
+func (account *Account) followsProxyRequestTimezone() bool {
+ return account != nil && account.IsOpenAI() && !account.IsShadow() &&
+ account.OpenAIRequestTimezoneMode() == OpenAIRequestTimezoneModeFollowProxy
+}
+
+func validateOpenAIRequestTimezoneModeExtra(platform string, extra map[string]any) error {
+ raw, exists := extra[openAIRequestTimezoneModeExtraKey]
+ if !exists || raw == nil {
+ return nil
+ }
+ mode, ok := raw.(string)
+ if !ok || (mode != "" && mode != OpenAIRequestTimezoneModeFixed && mode != OpenAIRequestTimezoneModeFollowProxy) ||
+ (mode == OpenAIRequestTimezoneModeFollowProxy && platform != PlatformOpenAI) {
+ return infraerrors.New(http.StatusBadRequest, "INVALID_OPENAI_REQUEST_TIMEZONE_MODE", "openai_request_timezone_mode must be fixed or follow_proxy for an OpenAI account")
+ }
+ return nil
+}
+
+// preserveOpenAIRequestTimezoneDetection 让检测结果只由后端写入:编辑表单回传的旧检测记录被丢弃;
+// 跟随模式下表单回传的时区也被丢弃,保留库里最新检测到的时区,避免把刚写入的结果覆盖回旧值。
+func preserveOpenAIRequestTimezoneDetection(current, next map[string]any) {
+ if next == nil {
+ return
+ }
+ delete(next, openAIRequestTimezoneDetectedExtraKey)
+ if value, ok := current[openAIRequestTimezoneDetectedExtraKey]; ok {
+ next[openAIRequestTimezoneDetectedExtraKey] = value
+ }
+ if mode, _ := next[openAIRequestTimezoneModeExtraKey].(string); mode == OpenAIRequestTimezoneModeFollowProxy {
+ delete(next, openAIRequestTimezoneExtraKey)
+ if value, ok := current[openAIRequestTimezoneExtraKey]; ok {
+ next[openAIRequestTimezoneExtraKey] = value
+ }
+ }
+}
+
+func openAIRequestTimezoneProxyKey(proxyID *int64) int64 {
+ if proxyID == nil {
+ return 0
+ }
+ return *proxyID
+}
+
+func sameProxyID(a, b *int64) bool {
+ return openAIRequestTimezoneProxyKey(a) == openAIRequestTimezoneProxyKey(b)
+}
+
+func (s *adminServiceImpl) probeOpenAIRequestTimezone(ctx context.Context, account *Account) OpenAIRequestTimezoneDetection {
+ result := OpenAIRequestTimezoneDetection{DetectedAt: time.Now().UTC().Format(time.RFC3339)}
+ if account.ProxyID != nil {
+ id := *account.ProxyID
+ result.ProxyID = &id
+ }
+ if s.proxyProber == nil {
+ result.Error = "proxy prober unavailable"
+ return result
+ }
+ proxyURL := ""
+ if account.ProxyID != nil {
+ proxy := account.Proxy
+ if proxy == nil || proxy.ID != *account.ProxyID {
+ if s.proxyRepo == nil {
+ result.Error = "proxy repository unavailable"
+ return result
+ }
+ loaded, err := s.proxyRepo.GetByID(ctx, *account.ProxyID)
+ if err != nil || loaded == nil {
+ result.Error = "proxy not found"
+ return result
+ }
+ proxy = loaded
+ }
+ proxyURL = proxy.URL()
+ }
+ info, _, err := s.proxyProber.ProbeProxy(ctx, proxyURL)
+ if err != nil {
+ result.Error = err.Error()
+ return result
+ }
+ if info == nil {
+ result.Error = "empty probe result"
+ return result
+ }
+ result.IP, result.Country, result.Region, result.City = info.IP, info.Country, info.Region, info.City
+ timezone := strings.TrimSpace(info.Timezone)
+ switch {
+ case timezone == "":
+ result.Error = "exit IP lookup returned no timezone"
+ case !isAllowedOpenAIRequestTimezone(timezone):
+ result.Error = "unsupported timezone: " + timezone
+ default:
+ result.Timezone = timezone
+ }
+ return result
+}
+
+// applyOpenAIRequestTimezoneDetection 写回检测结果。写回前重新读取账号:若期间已切回固定时区或又换了代理,
+// 本次结果已过期,直接丢弃。
+func (s *adminServiceImpl) applyOpenAIRequestTimezoneDetection(ctx context.Context, accountID int64, result OpenAIRequestTimezoneDetection) error {
+ current, err := s.accountRepo.GetByID(ctx, accountID)
+ if err != nil {
+ return err
+ }
+ if !current.followsProxyRequestTimezone() || !sameProxyID(current.ProxyID, result.ProxyID) {
+ return nil
+ }
+ updates := map[string]any{openAIRequestTimezoneDetectedExtraKey: result}
+ if result.Timezone != "" {
+ updates[openAIRequestTimezoneExtraKey] = result.Timezone
+ }
+ return s.accountRepo.UpdateExtra(ctx, accountID, updates)
+}
+
+// scheduleOpenAIRequestTimezoneDetection 在后台为跟随出口 IP 的账号检测时区,不阻塞保存。
+// 同一批里出口相同(同一代理或都直连)的账号只探测一次。
+func (s *adminServiceImpl) scheduleOpenAIRequestTimezoneDetection(accounts ...*Account) {
+ byProxy := make(map[int64][]*Account)
+ for _, account := range accounts {
+ if !account.followsProxyRequestTimezone() {
+ continue
+ }
+ if _, running := openAIRequestTimezoneDetecting.LoadOrStore(account.ID, struct{}{}); running {
+ continue
+ }
+ key := openAIRequestTimezoneProxyKey(account.ProxyID)
+ byProxy[key] = append(byProxy[key], account)
+ }
+ if len(byProxy) == 0 {
+ return
+ }
+ go func() {
+ defer func() {
+ if r := recover(); r != nil {
+ slog.Error("openai_request_timezone_detect_panic", "recover", r)
+ }
+ }()
+ for _, group := range byProxy {
+ s.detectOpenAIRequestTimezoneGroup(group)
+ }
+ }()
+}
+
+func (s *adminServiceImpl) detectOpenAIRequestTimezoneGroup(group []*Account) {
+ defer func() {
+ for _, account := range group {
+ openAIRequestTimezoneDetecting.Delete(account.ID)
+ }
+ }()
+ ctx, cancel := context.WithTimeout(context.Background(), openAIRequestTimezoneDetectTimeout)
+ defer cancel()
+ result := s.probeOpenAIRequestTimezone(ctx, group[0])
+ for _, account := range group {
+ if err := s.applyOpenAIRequestTimezoneDetection(ctx, account.ID, result); err != nil {
+ slog.Warn("openai_request_timezone_detect_persist_failed", "account_id", account.ID, "error", err)
+ continue
+ }
+ if result.Error != "" {
+ slog.Info("openai_request_timezone_detect_failed", "account_id", account.ID, "error", result.Error)
+ }
+ }
+}
+
+func (s *adminServiceImpl) scheduleOpenAIRequestTimezoneDetectionByIDs(ctx context.Context, ids []int64) {
+ accounts := make([]*Account, 0, len(ids))
+ for _, id := range ids {
+ account, err := s.accountRepo.GetByID(ctx, id)
+ if err == nil && account != nil {
+ accounts = append(accounts, account)
+ }
+ }
+ s.scheduleOpenAIRequestTimezoneDetection(accounts...)
+}
+
+// DetectOpenAIRequestTimezone 立即检测账号出口 IP 的时区并写回(后台「重新检测」)。
+func (s *adminServiceImpl) DetectOpenAIRequestTimezone(ctx context.Context, id int64) (*Account, error) {
+ account, err := s.accountRepo.GetByID(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if !account.followsProxyRequestTimezone() {
+ return nil, infraerrors.BadRequest("OPENAI_REQUEST_TIMEZONE_NOT_FOLLOWING_PROXY", "account request timezone does not follow the exit IP")
+ }
+ if _, running := openAIRequestTimezoneDetecting.LoadOrStore(account.ID, struct{}{}); running {
+ return nil, infraerrors.New(http.StatusConflict, "OPENAI_REQUEST_TIMEZONE_DETECTING", "timezone detection is already running for this account")
+ }
+ defer openAIRequestTimezoneDetecting.Delete(account.ID)
+ probeCtx, cancel := context.WithTimeout(ctx, openAIRequestTimezoneDetectTimeout)
+ defer cancel()
+ result := s.probeOpenAIRequestTimezone(probeCtx, account)
+ if err := s.applyOpenAIRequestTimezoneDetection(ctx, account.ID, result); err != nil {
+ return nil, err
+ }
+ return s.accountRepo.GetByID(ctx, id)
+}
diff --git a/backend/internal/service/openai_request_timezone_detect_test.go b/backend/internal/service/openai_request_timezone_detect_test.go
new file mode 100644
index 000000000..ceefc8aa6
--- /dev/null
+++ b/backend/internal/service/openai_request_timezone_detect_test.go
@@ -0,0 +1,251 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "errors"
+ "maps"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+type timezoneDetectAccountRepo struct {
+ mockAccountRepoForGemini
+ mu sync.Mutex
+ accounts map[int64]*Account
+}
+
+func (r *timezoneDetectAccountRepo) clone(id int64) *Account {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ account, ok := r.accounts[id]
+ if !ok {
+ return nil
+ }
+ copied := *account
+ copied.Extra = maps.Clone(account.Extra)
+ return &copied
+}
+
+func (r *timezoneDetectAccountRepo) GetByID(_ context.Context, id int64) (*Account, error) {
+ if account := r.clone(id); account != nil {
+ return account, nil
+ }
+ return nil, ErrAccountNotFound
+}
+
+func (r *timezoneDetectAccountRepo) Create(_ context.Context, account *Account) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if account.ID == 0 {
+ account.ID = int64(len(r.accounts) + 100)
+ }
+ copied := *account
+ copied.Extra = maps.Clone(account.Extra)
+ r.accounts[account.ID] = &copied
+ return nil
+}
+
+func (r *timezoneDetectAccountRepo) Update(_ context.Context, account *Account) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ copied := *account
+ copied.Extra = maps.Clone(account.Extra)
+ r.accounts[account.ID] = &copied
+ return nil
+}
+
+func (r *timezoneDetectAccountRepo) UpdateExtra(_ context.Context, id int64, updates map[string]any) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ account := r.accounts[id]
+ if account.Extra == nil {
+ account.Extra = map[string]any{}
+ }
+ maps.Copy(account.Extra, updates)
+ return nil
+}
+
+func (r *timezoneDetectAccountRepo) BulkUpdate(_ context.Context, ids []int64, updates AccountBulkUpdate) (int64, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ for _, id := range ids {
+ if updates.ProxyID != nil {
+ proxyID := *updates.ProxyID
+ r.accounts[id].ProxyID = &proxyID
+ }
+ }
+ return int64(len(ids)), nil
+}
+
+type timezoneDetectProxyRepo struct{ ProxyRepository }
+
+func (timezoneDetectProxyRepo) GetByID(_ context.Context, id int64) (*Proxy, error) {
+ return &Proxy{ID: id, Protocol: "http", Host: "proxy.example.com", Port: int(8000 + id), Status: StatusActive}, nil
+}
+
+type timezoneDetectProber struct {
+ mu sync.Mutex
+ calls []string
+ info *ProxyExitInfo
+ err error
+}
+
+func (p *timezoneDetectProber) ProbeProxy(_ context.Context, proxyURL string) (*ProxyExitInfo, int64, error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.calls = append(p.calls, proxyURL)
+ return p.info, 1, p.err
+}
+
+func (p *timezoneDetectProber) callCount() int {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return len(p.calls)
+}
+
+func newTimezoneDetectService(prober *timezoneDetectProber, accounts ...*Account) (*adminServiceImpl, *timezoneDetectAccountRepo) {
+ repo := &timezoneDetectAccountRepo{accounts: map[int64]*Account{}}
+ for _, account := range accounts {
+ repo.accounts[account.ID] = account
+ }
+ return &adminServiceImpl{accountRepo: repo, proxyRepo: timezoneDetectProxyRepo{}, proxyProber: prober}, repo
+}
+
+func followProxyAccount(id int64, proxyID *int64, extra map[string]any) *Account {
+ merged := map[string]any{openAIRequestTimezoneModeExtraKey: OpenAIRequestTimezoneModeFollowProxy}
+ maps.Copy(merged, extra)
+ return &Account{ID: id, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, ProxyID: proxyID, Extra: merged}
+}
+
+func waitTimezoneDetection(t *testing.T, repo *timezoneDetectAccountRepo, id int64) map[string]any {
+ t.Helper()
+ var extra map[string]any
+ require.Eventually(t, func() bool {
+ extra = repo.clone(id).Extra
+ _, ok := extra[openAIRequestTimezoneDetectedExtraKey]
+ _, running := openAIRequestTimezoneDetecting.Load(id)
+ return ok && !running
+ }, 2*time.Second, 5*time.Millisecond)
+ return extra
+}
+
+func TestOpenAIRequestTimezoneModeValidation(t *testing.T) {
+ require.NoError(t, ValidateOpenAIRequestTimezoneExtra(PlatformOpenAI, map[string]any{openAIRequestTimezoneModeExtraKey: OpenAIRequestTimezoneModeFollowProxy}))
+ require.NoError(t, ValidateOpenAIRequestTimezoneExtra(PlatformOpenAI, map[string]any{openAIRequestTimezoneModeExtraKey: OpenAIRequestTimezoneModeFixed}))
+ require.Error(t, ValidateOpenAIRequestTimezoneExtra(PlatformOpenAI, map[string]any{openAIRequestTimezoneModeExtraKey: "auto"}))
+ require.Error(t, ValidateOpenAIRequestTimezoneExtra(PlatformAnthropic, map[string]any{openAIRequestTimezoneModeExtraKey: OpenAIRequestTimezoneModeFollowProxy}))
+ require.Equal(t, OpenAIRequestTimezoneModeFixed, (&Account{Platform: PlatformOpenAI}).OpenAIRequestTimezoneMode(), "existing accounts without a mode stay fixed")
+}
+
+func TestCreateFollowProxyAccountDetectsExitTimezone(t *testing.T) {
+ prober := &timezoneDetectProber{info: &ProxyExitInfo{IP: "203.0.113.7", Country: "日本", City: "东京", Timezone: "Asia/Tokyo"}}
+ svc, repo := newTimezoneDetectService(prober)
+ proxyID := int64(3)
+ account, err := svc.CreateAccount(context.Background(), &CreateAccountInput{
+ Name: "tz", Platform: PlatformOpenAI, Type: AccountTypeOAuth, ProxyID: &proxyID, SkipDefaultGroupBind: true,
+ Credentials: map[string]any{"access_token": "tok"},
+ Extra: map[string]any{openAIRequestTimezoneModeExtraKey: OpenAIRequestTimezoneModeFollowProxy},
+ })
+ require.NoError(t, err)
+ extra := waitTimezoneDetection(t, repo, account.ID)
+ require.Equal(t, "Asia/Tokyo", extra[openAIRequestTimezoneExtraKey])
+ require.Equal(t, "Asia/Tokyo", repo.clone(account.ID).OpenAIRequestTimezone())
+ require.Equal(t, []string{"http://proxy.example.com:8003"}, prober.calls)
+}
+
+func TestTimezoneDetectionFailureKeepsPreviousTimezone(t *testing.T) {
+ proxyID := int64(1)
+ cases := []struct {
+ name string
+ prober *timezoneDetectProber
+ extra map[string]any
+ want string
+ }{
+ {"probe error keeps last result", &timezoneDetectProber{err: errors.New("dial timeout")}, map[string]any{openAIRequestTimezoneExtraKey: "Europe/Berlin"}, "Europe/Berlin"},
+ {"first failure falls back to default", &timezoneDetectProber{info: &ProxyExitInfo{IP: "198.51.100.1"}}, nil, DefaultOpenAIRequestTimezone},
+ {"unsupported timezone is a failure", &timezoneDetectProber{info: &ProxyExitInfo{IP: "198.51.100.1", Timezone: "Mars/Olympus"}}, map[string]any{openAIRequestTimezoneExtraKey: "Europe/Berlin"}, "Europe/Berlin"},
+ }
+ for index, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ id := int64(10 + index)
+ svc, repo := newTimezoneDetectService(tc.prober, followProxyAccount(id, &proxyID, tc.extra))
+ updated, err := svc.DetectOpenAIRequestTimezone(context.Background(), id)
+ require.NoError(t, err)
+ require.Equal(t, tc.want, updated.OpenAIRequestTimezone())
+ detection, ok := repo.clone(id).Extra[openAIRequestTimezoneDetectedExtraKey].(OpenAIRequestTimezoneDetection)
+ require.True(t, ok)
+ require.NotEmpty(t, detection.Error)
+ })
+ }
+}
+
+func TestDetectRejectsFixedModeAccount(t *testing.T) {
+ account := &Account{ID: 5, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{openAIRequestTimezoneExtraKey: "Asia/Singapore"}}
+ prober := &timezoneDetectProber{info: &ProxyExitInfo{Timezone: "Asia/Tokyo"}}
+ svc, _ := newTimezoneDetectService(prober, account)
+ _, err := svc.DetectOpenAIRequestTimezone(context.Background(), 5)
+ require.Error(t, err)
+ require.Zero(t, prober.callCount())
+}
+
+func TestUpdateAccountTriggersDetectionOnlyWhenProxyOrModeChanges(t *testing.T) {
+ oldProxy, newProxy := int64(1), int64(2)
+ detected := map[string]any{openAIRequestTimezoneExtraKey: "Asia/Tokyo", openAIRequestTimezoneDetectedExtraKey: map[string]any{"timezone": "Asia/Tokyo"}}
+ prober := &timezoneDetectProber{info: &ProxyExitInfo{IP: "192.0.2.1", Timezone: "America/New_York"}}
+ svc, repo := newTimezoneDetectService(prober, followProxyAccount(21, &oldProxy, detected))
+
+ // Unchanged proxy: the form echoes a stale timezone, which must not overwrite the detected value.
+ _, err := svc.UpdateAccount(context.Background(), 21, &UpdateAccountInput{Extra: map[string]any{
+ openAIRequestTimezoneModeExtraKey: OpenAIRequestTimezoneModeFollowProxy,
+ openAIRequestTimezoneExtraKey: "Asia/Singapore",
+ }})
+ require.NoError(t, err)
+ time.Sleep(50 * time.Millisecond)
+ require.Zero(t, prober.callCount())
+ require.Equal(t, "Asia/Tokyo", repo.clone(21).Extra[openAIRequestTimezoneExtraKey])
+
+ // Proxy change re-detects.
+ delete(repo.accounts[21].Extra, openAIRequestTimezoneDetectedExtraKey)
+ _, err = svc.UpdateAccount(context.Background(), 21, &UpdateAccountInput{ProxyID: &newProxy})
+ require.NoError(t, err)
+ extra := waitTimezoneDetection(t, repo, 21)
+ require.Equal(t, "America/New_York", extra[openAIRequestTimezoneExtraKey])
+ require.Equal(t, 1, prober.callCount())
+}
+
+func TestUpdateFixedAccountNeverDetects(t *testing.T) {
+ oldProxy, newProxy := int64(1), int64(2)
+ account := &Account{ID: 31, Platform: PlatformOpenAI, Type: AccountTypeOAuth, ProxyID: &oldProxy, Extra: map[string]any{openAIRequestTimezoneExtraKey: "Asia/Singapore"}}
+ prober := &timezoneDetectProber{info: &ProxyExitInfo{Timezone: "Asia/Tokyo"}}
+ svc, repo := newTimezoneDetectService(prober, account)
+ _, err := svc.UpdateAccount(context.Background(), 31, &UpdateAccountInput{ProxyID: &newProxy})
+ require.NoError(t, err)
+ time.Sleep(50 * time.Millisecond)
+ require.Zero(t, prober.callCount())
+ require.Equal(t, "Asia/Singapore", repo.clone(31).OpenAIRequestTimezone())
+}
+
+func TestBulkProxyChangeProbesEachExitOnce(t *testing.T) {
+ proxyID := int64(4)
+ prober := &timezoneDetectProber{info: &ProxyExitInfo{IP: "192.0.2.9", Timezone: "Europe/London"}}
+ fixed := &Account{ID: 43, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{}}
+ svc, repo := newTimezoneDetectService(prober, followProxyAccount(41, nil, nil), followProxyAccount(42, nil, nil), fixed)
+ _, err := svc.BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{AccountIDs: []int64{41, 42, 43}, ProxyID: &proxyID})
+ require.NoError(t, err)
+ require.Equal(t, "Europe/London", waitTimezoneDetection(t, repo, 41)[openAIRequestTimezoneExtraKey])
+ require.Equal(t, "Europe/London", waitTimezoneDetection(t, repo, 42)[openAIRequestTimezoneExtraKey])
+ require.Equal(t, 1, prober.callCount())
+ require.NotContains(t, repo.clone(43).Extra, openAIRequestTimezoneDetectedExtraKey)
+}
+
+func TestStaleDetectionIsDiscardedAfterProxyChange(t *testing.T) {
+ oldProxy, newProxy := int64(1), int64(2)
+ svc, repo := newTimezoneDetectService(&timezoneDetectProber{}, followProxyAccount(51, &newProxy, nil))
+ require.NoError(t, svc.applyOpenAIRequestTimezoneDetection(context.Background(), 51, OpenAIRequestTimezoneDetection{ProxyID: &oldProxy, Timezone: "Asia/Tokyo"}))
+ require.NotContains(t, repo.clone(51).Extra, openAIRequestTimezoneExtraKey)
+}
diff --git a/backend/internal/service/openai_response_model_rewrite_test.go b/backend/internal/service/openai_response_model_rewrite_test.go
index 7c7035168..53c64a030 100644
--- a/backend/internal/service/openai_response_model_rewrite_test.go
+++ b/backend/internal/service/openai_response_model_rewrite_test.go
@@ -56,7 +56,7 @@ func TestMappedResponseModelForwarding(t *testing.T) {
contentType := "application/json"
body := payload
if kind == "responses" {
- payload = `{"type":"response.completed","response":{"id":"resp_1","model":"` + returned + `","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`
+ payload = `{"type":"response.completed","response":{"id":"resp_1","created_at":1700000000,"model":"` + returned + `","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`
want = strings.Replace(payload, `"model":"`+returned+`"`, `"model":"`+model+`"`, 1)
}
if kind != "json" {
diff --git a/backend/internal/service/openai_responses_created_at.go b/backend/internal/service/openai_responses_created_at.go
new file mode 100644
index 000000000..4387b02b5
--- /dev/null
+++ b/backend/internal/service/openai_responses_created_at.go
@@ -0,0 +1,94 @@
+package service
+
+import (
+ "strings"
+ "time"
+
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+// Strict Responses clients (Rust serde: grok-build, Codex) declare
+// Response.created_at as required — a response object without it fails the
+// whole turn with `missing field 'created_at'` (issues #5601, #8118).
+// Official upstreams always send it, but vendor gateways in front of Grok
+// subscriptions and gateway-synthesized terminal frames may not, so every
+// Response object leaving the gateway is stamped when the field is absent.
+
+// responsesCreatedAtStamper keeps one created_at per Responses stream: the
+// upstream's own value once seen, otherwise a single timestamp taken on first
+// use, so response.created and the terminal event always agree.
+type responsesCreatedAtStamper struct {
+ createdAt int64
+}
+
+func (s *responsesCreatedAtStamper) learn(value gjson.Result) {
+ if s.createdAt == 0 && value.Type == gjson.Number && value.Int() > 0 {
+ s.createdAt = value.Int()
+ }
+}
+
+// Value returns the stream's created_at, fixing it to now on first use.
+func (s *responsesCreatedAtStamper) Value() int64 {
+ if s.createdAt <= 0 {
+ s.createdAt = time.Now().Unix()
+ }
+ return s.createdAt
+}
+
+// Observe records the upstream created_at without modifying the payload.
+func (s *responsesCreatedAtStamper) Observe(payload []byte, eventType string) {
+ if !strings.HasPrefix(strings.TrimSpace(eventType), "response.") {
+ return
+ }
+ s.learn(gjson.GetBytes(payload, "response.created_at"))
+}
+
+// Stamp adds response.created_at to a Responses lifecycle event whose
+// response object lacks it (absent or null). Any other value is left as-is.
+func (s *responsesCreatedAtStamper) Stamp(payload []byte, eventType string) ([]byte, bool) {
+ if !strings.HasPrefix(strings.TrimSpace(eventType), "response.") {
+ return payload, false
+ }
+ response := gjson.GetBytes(payload, "response")
+ if !response.IsObject() {
+ return payload, false
+ }
+ createdAt := response.Get("created_at")
+ if createdAt.Exists() && createdAt.Type != gjson.Null {
+ s.learn(createdAt)
+ return payload, false
+ }
+ stamped, err := sjson.SetBytes(payload, "response.created_at", s.Value())
+ if err != nil {
+ return payload, false
+ }
+ return stamped, true
+}
+
+// ensureOpenAIResponseObjectCreatedAt stamps created_at onto a non-streaming
+// Response object (`"object":"response"`) that lacks it.
+func ensureOpenAIResponseObjectCreatedAt(body []byte) []byte {
+ if gjson.GetBytes(body, "object").String() != "response" {
+ return body
+ }
+ createdAt := gjson.GetBytes(body, "created_at")
+ if createdAt.Exists() && createdAt.Type != gjson.Null {
+ return body
+ }
+ stamped, err := sjson.SetBytes(body, "created_at", time.Now().Unix())
+ if err != nil {
+ return body
+ }
+ return stamped
+}
+
+// openAIResponsesFailedSequenceNumber reuses the sequence slot of the bare
+// error event a synthesized response.failed replaces (that error frame is
+// suppressed), keeping the client-visible sequence monotonic; 0 when unknown.
+func openAIResponsesFailedSequenceNumber(source []byte) int64 {
+ if seq := gjson.GetBytes(source, "sequence_number"); seq.Type == gjson.Number && seq.Int() >= 0 {
+ return seq.Int()
+ }
+ return 0
+}
diff --git a/backend/internal/service/openai_responses_created_at_test.go b/backend/internal/service/openai_responses_created_at_test.go
new file mode 100644
index 000000000..39c057ea7
--- /dev/null
+++ b/backend/internal/service/openai_responses_created_at_test.go
@@ -0,0 +1,355 @@
+package service
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+// issue #8118:grok-build(Rust serde)把 Response.created_at 当必填字段,缺失即
+// `missing field 'created_at'` 整轮读不出响应。网关送出的每个 Response 对象都必须带它。
+
+// sseDataPayloads 按顺序取出 SSE 文本里的全部 data 负载(跳过 [DONE])。
+func sseDataPayloads(body string) []string {
+ var payloads []string
+ for _, line := range strings.Split(body, "\n") {
+ data, ok := strings.CutPrefix(line, "data: ")
+ if !ok || strings.TrimSpace(data) == "[DONE]" {
+ continue
+ }
+ payloads = append(payloads, data)
+ }
+ return payloads
+}
+
+func TestResponsesCreatedAtStamper_StampsMissingAndKeepsStreamStable(t *testing.T) {
+ var stamper responsesCreatedAtStamper
+
+ created, changed := stamper.Stamp([]byte(`{"type":"response.created","response":{"id":"resp_1","status":"in_progress"}}`), "response.created")
+ require.True(t, changed)
+ first := gjson.GetBytes(created, "response.created_at")
+ require.Equal(t, gjson.Number, first.Type)
+ require.Positive(t, first.Int())
+
+ completed, changed := stamper.Stamp([]byte(`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`), "response.completed")
+ require.True(t, changed)
+ require.Equal(t, first.Int(), gjson.GetBytes(completed, "response.created_at").Int(), "同一条流的 created_at 必须一致")
+}
+
+func TestResponsesCreatedAtStamper_PreservesUpstreamValue(t *testing.T) {
+ var stamper responsesCreatedAtStamper
+ upstream := []byte(`{"type":"response.created","response":{"id":"resp_1","created_at":1700000000}}`)
+
+ out, changed := stamper.Stamp(upstream, "response.created")
+ require.False(t, changed)
+ require.Equal(t, string(upstream), string(out), "上游已带 created_at 时字节不变")
+
+ completed, changed := stamper.Stamp([]byte(`{"type":"response.completed","response":{"id":"resp_1"}}`), "response.completed")
+ require.True(t, changed)
+ require.EqualValues(t, 1700000000, gjson.GetBytes(completed, "response.created_at").Int(), "后续缺失时沿用上游值")
+ require.EqualValues(t, 1700000000, stamper.Value())
+}
+
+func TestResponsesCreatedAtStamper_NullIsTreatedAsMissing(t *testing.T) {
+ var stamper responsesCreatedAtStamper
+ out, changed := stamper.Stamp([]byte(`{"type":"response.created","response":{"id":"resp_1","created_at":null}}`), "response.created")
+ require.True(t, changed)
+ require.Equal(t, gjson.Number, gjson.GetBytes(out, "response.created_at").Type)
+}
+
+func TestResponsesCreatedAtStamper_LeavesOtherEventsUntouched(t *testing.T) {
+ cases := []struct {
+ name string
+ eventType string
+ payload string
+ }{
+ {"delta", "response.output_text.delta", `{"type":"response.output_text.delta","delta":"hi"}`},
+ {"bare_error", "error", `{"type":"error","error":{"message":"boom"}}`},
+ {"error_with_response_field", "error", `{"type":"error","response":{"id":"resp_1"}}`},
+ {"response_not_object", "response.created", `{"type":"response.created","response":"resp_1"}`},
+ {"non_numeric_created_at", "response.created", `{"type":"response.created","response":{"created_at":"2026-10-16T00:00:00Z"}}`},
+ {"invalid_json", "response.created", `not json`},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ var stamper responsesCreatedAtStamper
+ out, changed := stamper.Stamp([]byte(tc.payload), tc.eventType)
+ require.False(t, changed)
+ require.Equal(t, tc.payload, string(out))
+ })
+ }
+}
+
+func TestResponsesCreatedAtStamper_ObserveLearnsWithoutStamping(t *testing.T) {
+ var stamper responsesCreatedAtStamper
+ stamper.Observe([]byte(`{"type":"error","response":{"created_at":1600000000}}`), "error")
+ stamper.Observe([]byte(`{"type":"response.created","response":{"created_at":1700000000}}`), "response.created")
+ stamper.Observe([]byte(`{"type":"response.in_progress","response":{"created_at":1800000000}}`), "response.in_progress")
+ require.EqualValues(t, 1700000000, stamper.Value(), "记首个生命周期事件的上游值")
+}
+
+func TestEnsureOpenAIResponseObjectCreatedAt(t *testing.T) {
+ stamped := ensureOpenAIResponseObjectCreatedAt([]byte(`{"id":"resp_1","object":"response","status":"completed"}`))
+ require.Equal(t, gjson.Number, gjson.GetBytes(stamped, "created_at").Type)
+ require.Positive(t, gjson.GetBytes(stamped, "created_at").Int())
+
+ for _, body := range []string{
+ `{"id":"resp_1","object":"response","created_at":1700000000}`,
+ `{"id":"cmp_1","object":"response.compaction","output":[]}`,
+ `{"id":"resp_1","output":[]}`,
+ `not json`,
+ } {
+ require.Equal(t, body, string(ensureOpenAIResponseObjectCreatedAt([]byte(body))))
+ }
+}
+
+func TestBuildOpenAIResponseFailedSSE_CarriesCreatedAtAndSequenceNumber(t *testing.T) {
+ frame := buildOpenAIResponseFailedSSE("resp_1", "gpt-5.5", 1700000000,
+ []byte(`{"type":"error","sequence_number":7,"error":{"code":"server_is_overloaded","message":"busy"}}`), "")
+ payloads := sseDataPayloads(frame)
+ require.Len(t, payloads, 1)
+ event := payloads[0]
+ require.Equal(t, "response.failed", gjson.Get(event, "type").String())
+ require.EqualValues(t, 7, gjson.Get(event, "sequence_number").Int(), "沿用被替换的裸 error 帧序号")
+ require.EqualValues(t, 1700000000, gjson.Get(event, "response.created_at").Int())
+ require.Equal(t, "resp_1", gjson.Get(event, "response.id").String())
+ require.Equal(t, "failed", gjson.Get(event, "response.status").String())
+
+ frame = buildOpenAIResponseFailedSSE("", "", 0, []byte(`{"type":"error","error":{"message":"boom"}}`), "")
+ event = sseDataPayloads(frame)[0]
+ require.True(t, gjson.Get(event, "sequence_number").Exists(), "sequence_number 未知时也必须写出")
+ require.EqualValues(t, 0, gjson.Get(event, "sequence_number").Int())
+ require.Positive(t, gjson.Get(event, "response.created_at").Int(), "未知 created_at 时取当前时间")
+}
+
+func TestBuildOpenAIWSHTTPBridgeFailedEvent_CarriesCreatedAtAndSequenceNumber(t *testing.T) {
+ event := buildOpenAIWSHTTPBridgeFailedEvent("resp_1", "gpt-5.5", 1700000000,
+ []byte(`{"type":"error","sequence_number":4,"error":{"message":"boom"}}`), "")
+ require.Equal(t, "response.failed", gjson.GetBytes(event, "type").String())
+ require.EqualValues(t, 4, gjson.GetBytes(event, "sequence_number").Int())
+ require.EqualValues(t, 1700000000, gjson.GetBytes(event, "response.created_at").Int())
+
+ event = buildOpenAIWSHTTPBridgeFailedEvent("resp_1", "", 0, []byte(`{"type":"error","error":{"message":"boom"}}`), "")
+ require.EqualValues(t, 0, gjson.GetBytes(event, "sequence_number").Int())
+ require.Positive(t, gjson.GetBytes(event, "response.created_at").Int())
+}
+
+// Grok 账号挂在不发 created_at 的上游(第三方中转)后面:每个生命周期事件都要补齐,
+// 且同一条流取同一个值;增量事件字节不变。
+func TestHandleStreamingResponse_GrokStampsMissingCreatedAt(t *testing.T) {
+ delta := `{"type":"response.output_text.delta","sequence_number":2,"item_id":"msg_1","output_index":0,"content_index":0,"delta":"hi"}`
+ body := "event: response.created\n" +
+ `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_grok","object":"response","model":"grok-4.5","status":"in_progress","output":[]}}` + "\n\n" +
+ "event: response.in_progress\n" +
+ `data: {"type":"response.in_progress","sequence_number":1,"response":{"id":"resp_grok","object":"response","model":"grok-4.5","status":"in_progress","output":[]}}` + "\n\n" +
+ "event: response.output_text.delta\n" +
+ "data: " + delta + "\n\n" +
+ "event: response.completed\n" +
+ `data: {"type":"response.completed","sequence_number":3,"response":{"id":"resp_grok","object":"response","model":"grok-4.5","status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hi","annotations":[]}]}],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}}` + "\n\n"
+ recorder := newOpenAIResponseFlushRecorder()
+ account := &Account{ID: 8118, Platform: PlatformGrok, Type: AccountTypeAPIKey}
+
+ result, err := runOpenAIResponseFlushTestWithAccount(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}, account)
+
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Equal(t, 3, result.usage.InputTokens)
+ gotBody, _ := recorder.snapshot()
+ payloads := sseDataPayloads(gotBody)
+ require.Len(t, payloads, 4)
+ createdAt := gjson.Get(payloads[0], "response.created_at")
+ require.Equal(t, gjson.Number, createdAt.Type)
+ require.Positive(t, createdAt.Int())
+ for _, index := range []int{1, 3} {
+ require.Equal(t, createdAt.Int(), gjson.Get(payloads[index], "response.created_at").Int(), "payload %d", index)
+ }
+ require.Equal(t, delta, payloads[2], "非生命周期事件不得改动")
+ require.Equal(t, "hi", gjson.Get(payloads[3], "response.output.0.content.0.text").String())
+}
+
+// 官方上游自带 created_at:网关输出必须与上游逐字节一致(不引入任何改写)。
+func TestHandleStreamingResponse_GrokKeepsUpstreamCreatedAtBytes(t *testing.T) {
+ body := "event: response.created\n" +
+ `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_grok","object":"response","created_at":1774274151,"model":"grok-4.5","status":"in_progress","output":[]}}` + "\n\n" +
+ "event: response.completed\n" +
+ `data: {"type":"response.completed","sequence_number":1,"response":{"id":"resp_grok","object":"response","created_at":1774274151,"model":"grok-4.5","status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hi","annotations":[]}]}],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}}` + "\n\n"
+ recorder := newOpenAIResponseFlushRecorder()
+ account := &Account{ID: 8118, Platform: PlatformGrok, Type: AccountTypeOAuth}
+
+ _, err := runOpenAIResponseFlushTestWithAccount(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}, account)
+
+ require.NoError(t, err)
+ gotBody, _ := recorder.snapshot()
+ require.Equal(t, body, gotBody)
+}
+
+// OpenAI OAuth 流以裸 error 结束:合成的 response.failed 必须带 created_at
+// (与本流 response.created 一致)和 sequence_number。
+func TestHandleStreamingResponse_BareErrorSynthesizedFailedCarriesCreatedAt(t *testing.T) {
+ body := `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_bare","object":"response","created_at":1700000000,"status":"in_progress","output":[]}}` + "\n\n" +
+ `data: {"type":"response.output_text.delta","sequence_number":1,"item_id":"msg_1","output_index":0,"content_index":0,"delta":"partial"}` + "\n\n" +
+ `data: {"type":"error","sequence_number":2,"error":{"code":"server_is_overloaded","message":"busy"}}` + "\n\n" +
+ "data: [DONE]\n\n"
+ recorder := newOpenAIResponseFlushRecorder()
+
+ result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{})
+
+ require.Error(t, err)
+ require.NotNil(t, result)
+ gotBody, _ := recorder.snapshot()
+ require.NotContains(t, gotBody, `"type":"error"`)
+ var failed string
+ for _, payload := range sseDataPayloads(gotBody) {
+ if gjson.Get(payload, "type").String() == "response.failed" {
+ failed = payload
+ }
+ }
+ require.NotEmpty(t, failed, "必须合成 response.failed: %s", gotBody)
+ require.EqualValues(t, 1700000000, gjson.Get(failed, "response.created_at").Int())
+ require.EqualValues(t, 2, gjson.Get(failed, "sequence_number").Int())
+ require.Equal(t, "resp_bare", gjson.Get(failed, "response.id").String())
+}
+
+func TestHandleStreamingResponsePassthrough_BareErrorSynthesizedFailedCarriesCreatedAt(t *testing.T) {
+ upstream := `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_pt","object":"response","created_at":1700000000,"status":"in_progress","output":[]}}` + "\n\n" +
+ "event: error\n" +
+ `data: {"type":"error","sequence_number":1,"error":{"code":"content_policy","message":"request blocked by policy"}}` + "\n\n" +
+ "data: [DONE]\n\n"
+
+ _, recorder, _, err := runPassthroughFlushTest(t, io.NopCloser(strings.NewReader(upstream)), -1)
+
+ require.Error(t, err)
+ var failed string
+ for _, payload := range sseDataPayloads(recorder.Body.String()) {
+ if gjson.Get(payload, "type").String() == "response.failed" {
+ failed = payload
+ }
+ }
+ require.NotEmpty(t, failed, "必须合成 response.failed: %s", recorder.Body.String())
+ require.EqualValues(t, 1700000000, gjson.Get(failed, "response.created_at").Int())
+ require.EqualValues(t, 1, gjson.Get(failed, "sequence_number").Int())
+}
+
+func TestProxyOpenAIWSHTTPBridgeTurn_GrokStampsMissingCreatedAt(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ upstream := &httpUpstreamRecorder{resp: &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(strings.Join([]string{
+ `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_ws","object":"response","model":"grok-4.5","status":"in_progress"}}`,
+ "",
+ `data: {"type":"response.completed","sequence_number":1,"response":{"id":"resp_ws","object":"response","model":"grok-4.5","status":"completed","usage":{"input_tokens":1,"output_tokens":1}}}`,
+ "",
+ }, "\n"))),
+ }}
+ svc := &OpenAIGatewayService{
+ cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}},
+ httpUpstream: upstream,
+ }
+ account := &Account{ID: 8118, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1}
+ payload := []byte(`{"type":"response.create","model":"grok-4.5","stream":true,"input":"hi"}`)
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil)
+ var events [][]byte
+
+ result, err := svc.proxyOpenAIWSHTTPBridgeTurn(
+ context.Background(), c, account, "access-token", payload, len(payload),
+ "grok-4.5", "", "", "", "", 1,
+ func(message []byte) error {
+ events = append(events, append([]byte(nil), message...))
+ return nil
+ },
+ )
+
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Len(t, events, 2)
+ createdAt := gjson.GetBytes(events[0], "response.created_at")
+ require.Equal(t, gjson.Number, createdAt.Type)
+ require.Positive(t, createdAt.Int())
+ require.Equal(t, createdAt.Int(), gjson.GetBytes(events[1], "response.created_at").Int())
+}
+
+func TestProxyOpenAIWSHTTPBridgeTurn_BareErrorSynthesizedFailedCarriesCreatedAt(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ body := `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_eof","created_at":1700000000,"status":"in_progress"}}` + "\n\n" +
+ `data: {"type":"error","sequence_number":1,"error":{"code":"invalid_request","message":"bad request"}}` + "\n\n"
+ upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}}
+ svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream}
+ account := &Account{ID: 112, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Concurrency: 1}
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil)
+ payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`)
+ var writes [][]byte
+
+ _, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error {
+ writes = append(writes, append([]byte(nil), message...))
+ return nil
+ })
+
+ require.EqualError(t, err, "bad request")
+ require.Len(t, writes, 2)
+ require.Equal(t, "response.failed", gjson.GetBytes(writes[1], "type").String())
+ require.EqualValues(t, 1700000000, gjson.GetBytes(writes[1], "response.created_at").Int())
+ require.EqualValues(t, 1, gjson.GetBytes(writes[1], "sequence_number").Int())
+}
+
+func TestHandleNonStreamingResponse_StampsMissingCreatedAt(t *testing.T) {
+ run := func(t *testing.T, upstreamBody string) string {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
+ svc := &OpenAIGatewayService{cfg: &config.Config{}, toolCorrector: NewCodexToolCorrector()}
+ resp := &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(upstreamBody)),
+ }
+ result, err := svc.handleNonStreamingResponse(context.Background(), resp, c, &Account{ID: 8118, Platform: PlatformGrok, Type: AccountTypeAPIKey}, "grok-4.5", "grok-4.5")
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Equal(t, 3, result.usage.InputTokens)
+ return rec.Body.String()
+ }
+
+ missing := run(t, `{"id":"resp_1","object":"response","model":"grok-4.5","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}`)
+ require.Equal(t, gjson.Number, gjson.Get(missing, "created_at").Type)
+ require.Positive(t, gjson.Get(missing, "created_at").Int())
+
+ present := `{"id":"resp_1","object":"response","created_at":1700000000,"model":"grok-4.5","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}`
+ require.Equal(t, present, run(t, present))
+}
+
+func TestHandleSSEToJSON_StampsMissingCreatedAt(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
+ svc := &OpenAIGatewayService{cfg: &config.Config{}, toolCorrector: NewCodexToolCorrector()}
+ body := `data: {"type":"response.completed","response":{"id":"resp_1","object":"response","status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hi","annotations":[]}]}],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}}` + "\n\n"
+ resp := &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(body)),
+ }
+
+ result, err := svc.handleNonStreamingResponse(context.Background(), resp, c, &Account{ID: 8118, Platform: PlatformGrok, Type: AccountTypeOAuth}, "grok-4.5", "grok-4.5")
+
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ out := rec.Body.String()
+ require.Equal(t, "resp_1", gjson.Get(out, "id").String())
+ require.Positive(t, gjson.Get(out, "created_at").Int())
+}
diff --git a/backend/internal/service/openai_responses_ingress_compat.go b/backend/internal/service/openai_responses_ingress_compat.go
index 69de3f289..4b984a60e 100644
--- a/backend/internal/service/openai_responses_ingress_compat.go
+++ b/backend/internal/service/openai_responses_ingress_compat.go
@@ -5,6 +5,7 @@ import (
"fmt"
"strings"
+ "github.com/MACOS-DO/sub4api/internal/config"
"github.com/MACOS-DO/sub4api/internal/pkg/apicompat"
"github.com/tidwall/gjson"
)
@@ -13,6 +14,10 @@ import (
// payloads that a few Responses clients still emit. Native Responses input is
// always authoritative because this path has no separate full-replay attempt.
func normalizeOpenAIResponsesLegacyIngress(body []byte) ([]byte, bool, error) {
+ return normalizeOpenAIResponsesLegacyIngressWithConfig(nil, body)
+}
+
+func normalizeOpenAIResponsesLegacyIngressWithConfig(cfg *config.Config, body []byte) ([]byte, bool, error) {
if len(body) == 0 {
return body, false, nil
}
@@ -43,7 +48,7 @@ func normalizeOpenAIResponsesLegacyIngress(body []byte) ([]byte, bool, error) {
if hasMessages {
messages, messagesAreArray := messagesValue.([]any)
if messagesAreArray && len(messages) > 0 {
- legacy, err := convertLegacyResponsesMessages(body)
+ legacy, err := convertLegacyResponsesMessages(cfg, body)
if err != nil {
return body, false, err
}
@@ -105,13 +110,13 @@ type convertedLegacyResponsesMessages struct {
hasReasoningEffort bool
}
-func convertLegacyResponsesMessages(body []byte) (convertedLegacyResponsesMessages, error) {
+func convertLegacyResponsesMessages(cfg *config.Config, body []byte) (convertedLegacyResponsesMessages, error) {
var converted convertedLegacyResponsesMessages
var chatRequest apicompat.ChatCompletionsRequest
if err := json.Unmarshal(body, &chatRequest); err != nil {
return converted, fmt.Errorf("normalize legacy Responses messages: %w", err)
}
- responsesRequest, err := apicompat.ChatCompletionsToResponses(&chatRequest)
+ responsesRequest, err := chatCompletionsToResponses(cfg, &chatRequest)
if err != nil {
return converted, fmt.Errorf("normalize legacy Responses messages: %w", err)
}
diff --git a/backend/internal/service/openai_subscription_long_context_test.go b/backend/internal/service/openai_subscription_long_context_test.go
new file mode 100644
index 000000000..bdf5b9549
--- /dev/null
+++ b/backend/internal/service/openai_subscription_long_context_test.go
@@ -0,0 +1,238 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOpenAISubscriptionLongContextExempt(t *testing.T) {
+ oauth := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
+ for _, tt := range []struct {
+ name string
+ account *Account
+ result *OpenAIForwardResult
+ want bool
+ }{
+ {name: "空账号", result: &OpenAIForwardResult{Model: "gpt-6.1-sol"}},
+ {name: "空结果", account: oauth},
+ {name: "订阅", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6.1-sol"}, want: true},
+ {name: "别名", account: oauth, result: &OpenAIForwardResult{Model: "openai/GPT_6.1_SOL-max"}, want: true},
+ {name: "压缩", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6.1-sol-openai-compact"}, want: true},
+ {name: "映射到目标", account: oauth, result: &OpenAIForwardResult{Model: "custom", UpstreamModel: "gpt-6.1-sol"}, want: true},
+ {name: "映射离开目标", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6.1-sol", UpstreamModel: "gpt-6-sol"}},
+ {name: "仅计费标签相同", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6-sol", BillingModel: "gpt-6.1-sol"}},
+ {name: "仅响应标签相同", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6-sol", UpstreamResponseModel: "gpt-6.1-sol"}},
+ {name: "其他模型", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6-astra"}},
+ {name: "相似名称", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6.1-sol-preview"}},
+ {name: "API账号", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, result: &OpenAIForwardResult{Model: "gpt-6.1-sol"}},
+ {name: "其他平台", account: &Account{Platform: PlatformGrok, Type: AccountTypeOAuth}, result: &OpenAIForwardResult{Model: "gpt-6.1-sol"}},
+ {name: "订阅访问令牌", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeSetupToken}, result: &OpenAIForwardResult{Model: "gpt-6.1-sol"}, want: true},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ require.Equal(t, tt.want, openAISubscriptionLongContextExempt(tt.account, tt.result))
+ })
+ }
+}
+
+// 同时覆盖远程目录更新、静态兜底、旧计费入口和分组入口,校验真实扣款与账号成本。
+func TestOpenAIGatewayServiceRecordUsage_GPT61SolSubscriptionLongContext(t *testing.T) {
+ for _, catalog := range []bool{false, true} {
+ for _, groupMode := range []string{"无分组", "分组关闭", "分组开启"} {
+ for _, accountEnabled := range []bool{false, true} {
+ for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken, AccountTypeAPIKey} {
+ for _, tier := range []string{"", "priority"} {
+ name := fmt.Sprintf("目录=%t/%s/账号开关=%t/%s/%s", catalog, groupMode, accountEnabled, accountType, tier)
+ t.Run(name, func(t *testing.T) {
+ usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
+ userRepo := &openAIRecordUsageUserRepoStub{}
+ svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil)
+ if catalog {
+ svc.billingService = NewBillingService(svc.cfg, newStubPricingServiceFromJSON(t, `{
+ "gpt-6.1-sol": {"litellm_provider": "openai", "mode": "chat",
+ "input_cost_per_token": 2e-6, "output_cost_per_token": 10e-6,
+ "cache_read_input_token_cost": 0.1e-6, "cache_creation_input_token_cost": 2.5e-6,
+ "input_cost_per_token_above_272k_tokens": 4e-6,
+ "output_cost_per_token_above_272k_tokens": 15e-6}
+ }`))
+ }
+ apiKey := &APIKey{ID: 1}
+ if groupMode != "无分组" {
+ apiKey = openAIRecordUsageAPIKeyWithGroup(svc, 1, groupMode == "分组开启")
+ apiKey.GroupID = i64p(1)
+ apiKey.Group.RateMultiplier = 1.1
+ svc.channelService = newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive}, 1, PlatformOpenAI)
+ }
+ account := &Account{ID: 3, Platform: PlatformOpenAI, Type: accountType,
+ Extra: map[string]any{openAILongContextBillingEnabledKey: accountEnabled}}
+ err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
+ Result: &OpenAIForwardResult{
+ RequestID: name, Model: "gpt-6.1-sol", ServiceTier: &tier, Duration: time.Second,
+ // 普通输入只有 200k,由缓存使总上下文越过 272k。
+ Usage: OpenAIUsage{InputTokens: 300000, OutputTokens: 2000, CacheReadInputTokens: 80000, CacheCreationInputTokens: 20000},
+ },
+ APIKey: apiKey, User: &User{ID: 2}, Account: account,
+ })
+ require.NoError(t, err)
+ wantLong := accountType == AccountTypeAPIKey && (accountEnabled || groupMode == "分组开启")
+ inputFactor, outputFactor, tierFactor := 1.0, 1.0, 1.0
+ if wantLong {
+ inputFactor, outputFactor = 2, 1.5
+ }
+ if tier == "priority" {
+ tierFactor = 2
+ }
+ log := usageRepo.lastLog
+ require.NotNil(t, log)
+ require.Equal(t, wantLong, log.LongContextBillingApplied)
+ require.InDelta(t, 200000*2e-6*inputFactor*tierFactor, log.InputCost, 1e-12)
+ require.InDelta(t, 80000*0.1e-6*inputFactor*tierFactor, log.CacheReadCost, 1e-12)
+ require.InDelta(t, 20000*2.5e-6*inputFactor*tierFactor, log.CacheCreationCost, 1e-12)
+ require.InDelta(t, 2000*10e-6*outputFactor*tierFactor, log.OutputCost, 1e-12)
+ wantTotal := (0.458*inputFactor + 0.02*outputFactor) * tierFactor
+ require.InDelta(t, wantTotal, log.TotalCost, 1e-12)
+ require.InDelta(t, wantTotal*1.1, log.ActualCost, 1e-12)
+ require.Equal(t, 1, userRepo.deductCalls)
+ require.InDelta(t, wantTotal*1.1, userRepo.lastAmount, 1e-12)
+ if groupMode != "无分组" {
+ wantStats := 0.478 * tierFactor
+ if accountType == AccountTypeAPIKey && accountEnabled {
+ wantStats = (0.458*2 + 0.02*1.5) * tierFactor
+ }
+ require.NotNil(t, log.AccountStatsCost)
+ require.InDelta(t, wantStats, *log.AccountStatsCost, 1e-12)
+ }
+ })
+ }
+ }
+ }
+ }
+ }
+}
+
+func TestOpenAIGatewayServiceRecordUsage_GPT61SolUsesCredentialAndUpstreamModel(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ model string
+ upstream string
+ parentType string
+ wantTotal float64
+ wantLong bool
+ }{
+ {name: "客户别名映射到目标", model: "custom", upstream: "gpt-6.1-sol", parentType: AccountTypeOAuth, wantTotal: 0.62},
+ {name: "请求目标映射到旧模型", model: "gpt-6.1-sol", upstream: "gpt-6-sol", parentType: AccountTypeOAuth, wantTotal: 1.23, wantLong: true},
+ {name: "其他订阅模型", model: "gpt-6-sol", parentType: AccountTypeOAuth, wantTotal: 1.23, wantLong: true},
+ {name: "订阅母账号", model: "gpt-6.1-sol", parentType: AccountTypeOAuth, wantTotal: 0.62},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
+ svc := newOpenAIRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
+ parentID := int64(4)
+ svc.accountRepo = &openAIRecordUsageAccountRepoStub{account: &Account{
+ ID: parentID, Platform: PlatformOpenAI, Type: tt.parentType,
+ Extra: map[string]any{openAILongContextBillingEnabledKey: true},
+ }}
+ err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
+ Result: &OpenAIForwardResult{RequestID: tt.name, Model: tt.model, UpstreamModel: tt.upstream,
+ Usage: OpenAIUsage{InputTokens: 300000, OutputTokens: 2000}, Duration: time.Second},
+ APIKey: openAIRecordUsageAPIKeyWithGroup(svc, 1, true), User: &User{ID: 2},
+ Account: &Account{ID: 3, Platform: PlatformOpenAI, Type: AccountTypeOAuth, ParentAccountID: &parentID, QuotaDimension: QuotaDimensionSpark},
+ })
+ require.NoError(t, err)
+ require.Equal(t, tt.wantLong, usageRepo.lastLog.LongContextBillingApplied)
+ require.InDelta(t, tt.wantTotal, usageRepo.lastLog.TotalCost, 1e-12)
+ })
+ }
+}
+
+func TestCalculateCostUnified_ModelLongContextExemptionPreservesCustomIntervals(t *testing.T) {
+ service := NewBillingService(nil, nil)
+ for _, withResolver := range []bool{false, true} {
+ input := CostInput{Model: "gpt-6.1-sol", Tokens: UsageTokens{InputTokens: 300000}, RateMultiplier: 1,
+ LongContextBillingEnabled: boolPtr(true), DisableModelLongContextPricing: true}
+ if withResolver {
+ input.Ctx = context.Background()
+ input.Resolver = NewModelPricingResolver(nil, service)
+ }
+ cost, err := service.CalculateCostUnified(input)
+ require.NoError(t, err)
+ require.InDelta(t, 0.6, cost.TotalCost, 1e-12)
+ require.False(t, cost.LongContextBillingApplied)
+ if withResolver {
+ input.Resolved = &ResolvedPricing{
+ BasePricing: &ModelPricing{InputPricePerToken: 2e-6},
+ Intervals: []PricingInterval{{MinTokens: 272000, InputMultiplier: pricingMultiplier(3)}},
+ longContextPricingEnabled: true,
+ }
+ cost, err = service.CalculateCostUnified(input)
+ require.NoError(t, err)
+ require.InDelta(t, 1.8, cost.TotalCost, 1e-12, "管理员显式区间价格应保留")
+ }
+ }
+}
+
+func TestOpenAIGatewayServiceRecordUsage_GPT61SolLongContextBoundary(t *testing.T) {
+ for _, totalInput := range []int{271999, 272000, 272001} {
+ for _, accountType := range []string{AccountTypeOAuth, AccountTypeAPIKey} {
+ t.Run(fmt.Sprintf("%s/%d", accountType, totalInput), func(t *testing.T) {
+ usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
+ svc := newOpenAIRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
+ err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
+ Result: &OpenAIForwardResult{RequestID: "boundary", Model: "gpt-6.1-sol", Duration: time.Second,
+ Usage: OpenAIUsage{InputTokens: totalInput, OutputTokens: 1000}},
+ APIKey: openAIRecordUsageAPIKeyWithGroup(svc, 1, true), User: &User{ID: 2},
+ Account: &Account{ID: 3, Platform: PlatformOpenAI, Type: accountType,
+ Extra: map[string]any{openAILongContextBillingEnabledKey: true}},
+ })
+ require.NoError(t, err)
+ wantLong := accountType == AccountTypeAPIKey && totalInput > 272000
+ wantInput, wantOutput := float64(totalInput)*2e-6, 0.01
+ if wantLong {
+ wantInput *= 2
+ wantOutput *= 1.5
+ }
+ require.Equal(t, wantLong, usageRepo.lastLog.LongContextBillingApplied)
+ require.InDelta(t, wantInput, usageRepo.lastLog.InputCost, 1e-12)
+ require.InDelta(t, wantOutput, usageRepo.lastLog.OutputCost, 1e-12)
+ })
+ }
+ }
+}
+
+func TestOpenAIGatewayServiceRecordUsage_GPT61SolExemptionSurvivesRepricing(t *testing.T) {
+ usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
+ userRepo := &openAIRecordUsageUserRepoStub{}
+ svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil)
+ apiKey := openAIRecordUsageAPIKeyWithGroup(svc, 1, true)
+ apiKey.GroupID = i64p(1)
+ apiKey.Group.Platform = PlatformOpenAI
+ apiKey.Group.RateMultiplier = 1.1
+ apiKey.Group.FreeOpenAIFast = true
+ svc.channelService = newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive}, 1, PlatformOpenAI)
+ tier := "priority"
+ err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
+ Result: &OpenAIForwardResult{
+ RequestID: "repricing", Model: "gpt-6-sol", UpstreamModel: "gpt-6.1-sol", BillingModel: "gpt-6-sol",
+ UpstreamResponseModel: "gpt-6.1-sol", ServiceTier: &tier, Duration: time.Second,
+ Usage: OpenAIUsage{InputTokens: 300000, OutputTokens: 2000, CacheReadInputTokens: 80000},
+ },
+ APIKey: apiKey, User: &User{ID: 2},
+ Account: &Account{ID: 3, Platform: PlatformOpenAI, Type: AccountTypeOAuth,
+ Extra: map[string]any{openAILongContextBillingEnabledKey: true}},
+ ChannelUsageFields: ChannelUsageFields{BillingModelSource: BillingModelSourceResponse},
+ })
+ require.NoError(t, err)
+ // 响应模型改用较低的缓存价;免费 Fast 再按标准档扣款,两次重算均须保留豁免。
+ const standardCost = 220000*2e-6 + 80000*0.1e-6 + 2000*10e-6
+ require.InDelta(t, standardCost*2, usageRepo.lastLog.TotalCost, 1e-12)
+ require.InDelta(t, standardCost*1.1, usageRepo.lastLog.ActualCost, 1e-12)
+ require.InDelta(t, standardCost*1.1, userRepo.lastAmount, 1e-12)
+ require.False(t, usageRepo.lastLog.LongContextBillingApplied)
+ require.NotNil(t, usageRepo.lastLog.AccountStatsCost)
+ require.InDelta(t, standardCost*2, *usageRepo.lastLog.AccountStatsCost, 1e-12)
+}
diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go
index aaa8a9f36..4532566c5 100644
--- a/backend/internal/service/openai_ws_forwarder_ingress.go
+++ b/backend/internal/service/openai_ws_forwarder_ingress.go
@@ -270,7 +270,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
normalized = next
}
responsesLite := isOpenAIResponsesLiteWebSocketPayload(normalized)
- if compatibilityBody, compatibilityChanged, compatibilityErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(normalized, account, responsesLite); compatibilityErr != nil {
+ if compatibilityBody, compatibilityChanged, compatibilityErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, normalized, account, responsesLite); compatibilityErr != nil {
return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", compatibilityErr)
} else if compatibilityChanged {
normalized = compatibilityBody
diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go
index 65baa0fd1..490be4346 100644
--- a/backend/internal/service/openai_ws_forwarder_support.go
+++ b/backend/internal/service/openai_ws_forwarder_support.go
@@ -571,7 +571,7 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability(
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
return 0, nil, "", nil
}
- if requestedModel != "" && !account.IsModelSupported(requestedModel) {
+ if requestedModel != "" && !supportsOpenAIRequestModel(account, requestedModel, requireCompact) {
return 0, nil, "", nil
}
if !account.SupportsOpenAIEndpointCapability(requiredCapability) {
@@ -610,7 +610,7 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability(
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
return 0, nil, "", nil
}
- if requestedModel != "" && !latest.IsModelSupported(requestedModel) {
+ if requestedModel != "" && !supportsOpenAIRequestModel(latest, requestedModel, requireCompact) {
return 0, nil, "", nil
}
if !latest.SupportsOpenAIEndpointCapability(requiredCapability) {
diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go
index 3096c092a..9f0e1954e 100644
--- a/backend/internal/service/openai_ws_http_bridge.go
+++ b/backend/internal/service/openai_ws_http_bridge.go
@@ -9,6 +9,7 @@ import (
"io"
"net/http"
"slices"
+ "strconv"
"strings"
"time"
@@ -369,7 +370,10 @@ func buildOpenAIWSHTTPBridgeErrorEvent(statusCode int, message string) []byte {
return body
}
-func buildOpenAIWSHTTPBridgeFailedEvent(responseID, model string, source []byte, fallbackMessage string) []byte {
+// buildOpenAIWSHTTPBridgeFailedEvent synthesizes response.failed for a turn that
+// ended on a bare error. created_at and sequence_number are always written:
+// strict clients (grok-build, Codex) reject the frame without them.
+func buildOpenAIWSHTTPBridgeFailedEvent(responseID, model string, createdAt int64, source []byte, fallbackMessage string) []byte {
errorType := strings.TrimSpace(gjson.GetBytes(source, "error.type").String())
if errorType == "" {
errorType = strings.TrimSpace(gjson.GetBytes(source, "response.error.type").String())
@@ -392,16 +396,22 @@ func buildOpenAIWSHTTPBridgeFailedEvent(responseID, model string, source []byte,
if errorType != "" {
errorBody["type"] = errorType
}
+ if createdAt <= 0 {
+ createdAt = time.Now().Unix()
+ }
+ sequenceNumber := openAIResponsesFailedSequenceNumber(source)
response := map[string]any{
- "id": responseID, "object": "response", "status": "failed",
+ "id": responseID, "object": "response", "created_at": createdAt, "status": "failed",
"output": []any{}, "error": errorBody,
}
if model = strings.TrimSpace(model); model != "" {
response["model"] = model
}
- body, err := json.Marshal(map[string]any{"type": "response.failed", "sequence_number": 0, "response": response})
+ body, err := json.Marshal(map[string]any{"type": "response.failed", "sequence_number": sequenceNumber, "response": response})
if err != nil {
- return []byte(`{"type":"response.failed","sequence_number":0,"response":{"status":"failed","output":[],"error":{"code":"upstream_error","message":"Upstream response failed"}}}`)
+ return []byte(`{"type":"response.failed","sequence_number":` + strconv.FormatInt(sequenceNumber, 10) +
+ `,"response":{"object":"response","created_at":` + strconv.FormatInt(createdAt, 10) +
+ `,"status":"failed","output":[],"error":{"code":"upstream_error","message":"Upstream response failed"}}}`)
}
return body
}
@@ -641,6 +651,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn(
officialOpenAIResponses := account != nil && account.Platform == PlatformOpenAI
bareErrorPending := false
var bareErrorPayload []byte
+ var createdAtStamper responsesCreatedAtStamper
bareErrorMessage := ""
failureAccountSideEffectsApplied := false
mappedModel := actualModel
@@ -712,7 +723,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn(
if clientDisconnected {
return nil
}
- clientMessage := buildOpenAIWSHTTPBridgeFailedEvent(responseID, originalModel, bareErrorPayload, bareErrorMessage)
+ clientMessage := buildOpenAIWSHTTPBridgeFailedEvent(responseID, originalModel, createdAtStamper.Value(), bareErrorPayload, bareErrorMessage)
if rewritten, changed := sanitizeOpenAICapacityShedErrorCodeForClient(clientMessage); changed {
clientMessage = rewritten
}
@@ -794,6 +805,9 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn(
upstreamMessage = corrected
}
}
+ if stamped, changed := createdAtStamper.Stamp(upstreamMessage, eventType); changed {
+ upstreamMessage = stamped
+ }
replayCollector.AddEvent(eventType, upstreamMessage)
var upstreamEventErr error
diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go
index da24f4970..1dbcbec11 100644
--- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go
+++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go
@@ -747,7 +747,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough(
firstClientMessage = s.ReplaceModelInBody(firstClientMessage, capturedSessionModel)
}
firstMessageResponsesLite := isOpenAIResponsesLiteWebSocketPayload(firstClientMessage)
- if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(firstClientMessage, account, firstMessageResponsesLite); normalizeErr != nil {
+ if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, firstClientMessage, account, firstMessageResponsesLite); normalizeErr != nil {
return fmt.Errorf("normalize first websocket response.create: %w", normalizeErr)
} else if compatibilityChanged {
firstClientMessage = normalized
@@ -1005,7 +1005,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough(
responsesLite := isResponseCreate && isOpenAIResponsesLiteWebSocketPayload(payload)
if isResponseCreate {
payload = normalizeOpenAIRequestLocale(ctx, account, payload, "ws")
- if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(payload, account, responsesLite); normalizeErr != nil {
+ if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, payload, account, responsesLite); normalizeErr != nil {
return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", normalizeErr)
} else if compatibilityChanged {
payload = normalized
diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go
index 34b01b0e4..95b726d96 100644
--- a/backend/internal/service/ops_upstream_context.go
+++ b/backend/internal/service/ops_upstream_context.go
@@ -52,6 +52,14 @@ const (
// ensureForwardErrorResponse 检查此 key,为 true 时跳过兜底写入,避免在已完成的 JSON 后追加 SSE。
ResponseCommittedKey = "response_committed"
+ // OpsLocalErrorTypeKey / OpsLocalErrorCodeKey 记录网关以 Google 错误格式回写的错误类型与错误码:
+ // Google 错误体没有 type 字段,ops_error_logger 据此按与 Claude / OpenAI 格式错误相同的口径分类。
+ OpsLocalErrorTypeKey = "ops_local_error_type"
+ OpsLocalErrorCodeKey = "ops_local_error_code"
+ // OpsRequestScopedErrorKey 标记失败由请求内容决定(如引用的显式缓存不存在):只按错误类型分类,
+ // 上游错误上下文保留为明细但不参与归因。
+ OpsRequestScopedErrorKey = "ops_request_scoped_error"
+
OpsClientBusinessLimitedKey = "ops_client_business_limited"
OpsClientBusinessLimitedReasonKey = "ops_client_business_limited_reason"
OpsClientBusinessLimitedReasonIPRestriction = "api_key_ip_restriction"
@@ -134,6 +142,42 @@ func OpsClientBusinessLimitedReason(c *gin.Context) string {
return strings.TrimSpace(reason)
}
+// SetOpsLocalErrorType 登记响应错误体缺少的错误类型与错误码,并清除请求级失败标记;errType 为空表示不登记。
+func SetOpsLocalErrorType(c *gin.Context, errType, code string) {
+ if c == nil {
+ return
+ }
+ c.Set(OpsLocalErrorTypeKey, strings.TrimSpace(errType))
+ c.Set(OpsLocalErrorCodeKey, strings.TrimSpace(code))
+ c.Set(OpsRequestScopedErrorKey, false)
+}
+
+// OpsLocalErrorType 返回 SetOpsLocalErrorType 登记的错误类型与错误码;未登记时返回空串。
+func OpsLocalErrorType(c *gin.Context) (errType, code string) {
+ if c == nil {
+ return "", ""
+ }
+ errType = c.GetString(OpsLocalErrorTypeKey)
+ if errType == "" {
+ return "", ""
+ }
+ return errType, c.GetString(OpsLocalErrorCodeKey)
+}
+
+// MarkOpsRequestScopedError 登记错误类型,并标记失败由请求内容决定:上游错误上下文不参与 ops 归因。
+func MarkOpsRequestScopedError(c *gin.Context, errType string) {
+ if c == nil {
+ return
+ }
+ SetOpsLocalErrorType(c, errType, "")
+ c.Set(OpsRequestScopedErrorKey, true)
+}
+
+// IsOpsRequestScopedError 判断 MarkOpsRequestScopedError 是否标记了本次请求的失败。
+func IsOpsRequestScopedError(c *gin.Context) bool {
+ return c != nil && c.GetBool(OpsRequestScopedErrorKey)
+}
+
// OpsStreamError 描述承载在 2xx 响应上的带内错误:网关在响应状态已固化为 200 之后
// 就地以 SSE error 帧返回的错误(并发限流回退、Wait 后二次计费校验失败、流开始后才无
// 可用账号等),以及上游 2xx 正文或事件里携带的错误结果(NonStream 标记非流式正文)。
diff --git a/backend/internal/service/payment_config_plans.go b/backend/internal/service/payment_config_plans.go
index 2356a78d3..b5b8acba9 100644
--- a/backend/internal/service/payment_config_plans.go
+++ b/backend/internal/service/payment_config_plans.go
@@ -86,6 +86,9 @@ type PlanGroupInfo struct {
WeeklyLimitUSD *float64 `json:"weekly_limit_usd"`
MonthlyLimitUSD *float64 `json:"monthly_limit_usd"`
ModelScopes []string `json:"supported_model_scopes"`
+
+ // 不对外输出;handler 按请求语言用它换出 Name 的译文。
+ I18n GroupI18n `json:"-"`
}
// GetGroupInfoMap returns a map of group_id → PlanGroupInfo for the given plans.
@@ -119,6 +122,7 @@ func (s *PaymentConfigService) GetGroupInfoMap(ctx context.Context, plans []*dbe
WeeklyLimitUSD: g.WeeklyLimitUsd,
MonthlyLimitUSD: g.MonthlyLimitUsd,
ModelScopes: g.SupportedModelScopes,
+ I18n: g.I18n,
}
}
return m
diff --git a/backend/internal/service/payment_fulfillment.go b/backend/internal/service/payment_fulfillment.go
index 14ff8963f..0960b8413 100644
--- a/backend/internal/service/payment_fulfillment.go
+++ b/backend/internal/service/payment_fulfillment.go
@@ -18,6 +18,7 @@ import (
"github.com/MACOS-DO/sub4api/ent/paymentorder"
"github.com/MACOS-DO/sub4api/internal/payment"
infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+ "github.com/MACOS-DO/sub4api/internal/pkg/servertiming"
)
// ErrOrderNotFound is returned by HandlePaymentNotification when the webhook
@@ -56,6 +57,33 @@ func (s *PaymentService) HandlePaymentNotification(ctx context.Context, n *payme
return s.confirmPayment(ctx, order.ID, n.TradeNo, n.Amount, pk, n.Metadata)
}
+// ConfirmNotificationUpstream asks providers that implement
+// payment.NotificationConfirmer to confirm a verified success notification
+// against the upstream order, using the same instance that verified it.
+// Failures are recorded on the order's audit trail and returned so the webhook
+// answers non-success and the gateway retries.
+func (s *PaymentService) ConfirmNotificationUpstream(ctx context.Context, prov payment.Provider, n *payment.PaymentNotification) error {
+ confirmer, ok := prov.(payment.NotificationConfirmer)
+ if !ok || n == nil || n.Status != payment.NotificationStatusSuccess {
+ return nil
+ }
+ notifiedTradeNo := n.TradeNo
+ finishProviderCall := servertiming.ObserveDependency(ctx, "payment")
+ err := confirmer.ConfirmNotification(ctx, n)
+ finishProviderCall()
+ if err == nil {
+ return nil
+ }
+ if order, lookupErr := s.entClient.PaymentOrder.Query().Where(paymentorder.OutTradeNo(n.OrderID)).Only(ctx); lookupErr == nil {
+ s.writeAuditLog(ctx, order.ID, "PAYMENT_UPSTREAM_UNCONFIRMED", prov.ProviderKey(), map[string]any{
+ "detail": err.Error(),
+ "tradeNo": notifiedTradeNo,
+ "amount": n.Amount,
+ })
+ }
+ return err
+}
+
func parseLegacyPaymentOrderID(orderID string, lookupErr error) (int64, bool) {
if !dbent.IsNotFound(lookupErr) {
return 0, false
@@ -218,10 +246,38 @@ func (s *PaymentService) executeFulfillment(ctx context.Context, oid int64) erro
if err != nil {
return fmt.Errorf("get order: %w", err)
}
- if o.OrderType == payment.OrderTypeSubscription {
+ switch o.OrderType {
+ case payment.OrderTypeSubscription:
return s.ExecuteSubscriptionFulfillment(ctx, oid)
+ case payment.OrderTypeBalance:
+ return s.ExecuteBalanceFulfillment(ctx, oid)
+ default:
+ // 不支持的订单类型不履约:标记 FAILED 后正常返回,避免支付回调持续 500 重试。
+ s.rejectUnsupportedOrderType(ctx, o)
+ return nil
+ }
+}
+
+func isSupportedPaymentOrderType(orderType string) bool {
+ return orderType == payment.OrderTypeBalance || orderType == payment.OrderTypeSubscription
+}
+
+func (s *PaymentService) rejectUnsupportedOrderType(ctx context.Context, o *dbent.PaymentOrder) {
+ reason := "unsupported order type: " + o.OrderType
+ c, err := s.entClient.PaymentOrder.Update().
+ Where(
+ paymentorder.IDEQ(o.ID),
+ paymentorder.StatusIn(OrderStatusPaid, OrderStatusRecharging),
+ ).
+ SetStatus(OrderStatusFailed).SetFailedAt(time.Now()).SetFailedReason(reason).Save(ctx)
+ if err != nil {
+ slog.Error("mark unsupported order type FAILED", "orderID", o.ID, "error", err)
+ return
+ }
+ if c > 0 {
+ slog.Warn("payment order with unsupported order type not fulfilled", "orderID", o.ID, "orderType", o.OrderType)
+ s.writeAuditLog(ctx, o.ID, "FULFILLMENT_FAILED", "system", map[string]any{"reason": reason})
}
- return s.ExecuteBalanceFulfillment(ctx, oid)
}
func (s *PaymentService) ExecuteBalanceFulfillment(ctx context.Context, oid int64) error {
@@ -229,6 +285,9 @@ func (s *PaymentService) ExecuteBalanceFulfillment(ctx context.Context, oid int6
if err != nil {
return infraerrors.NotFound("NOT_FOUND", "order not found")
}
+ if o.OrderType != payment.OrderTypeBalance {
+ return infraerrors.BadRequest("INVALID_ORDER_TYPE", "order is not a balance order")
+ }
if o.Status == OrderStatusCompleted {
return nil
}
@@ -885,6 +944,9 @@ func (s *PaymentService) RetryFulfillment(ctx context.Context, oid int64) error
if o.Status != OrderStatusFailed && o.Status != OrderStatusPaid && o.Status != OrderStatusRecharging {
return infraerrors.BadRequest("INVALID_STATUS", "only paid, failed, and recoverable recharging orders can retry")
}
+ if !isSupportedPaymentOrderType(o.OrderType) {
+ return infraerrors.BadRequest("INVALID_ORDER_TYPE", "unsupported order type")
+ }
s.writeAuditLog(ctx, oid, "RECHARGE_RETRY", "admin", map[string]any{"detail": "admin manual retry"})
return s.executeFulfillment(ctx, oid)
}
diff --git a/backend/internal/service/payment_notification_confirm_test.go b/backend/internal/service/payment_notification_confirm_test.go
new file mode 100644
index 000000000..f1f205daa
--- /dev/null
+++ b/backend/internal/service/payment_notification_confirm_test.go
@@ -0,0 +1,101 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "errors"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/ent/paymentauditlog"
+ "github.com/MACOS-DO/sub4api/internal/payment"
+ "github.com/stretchr/testify/require"
+)
+
+type paymentConfirmTestProvider struct {
+ paymentFulfillmentTestProvider
+ err error
+ calls *int
+}
+
+func (p paymentConfirmTestProvider) ConfirmNotification(_ context.Context, n *payment.PaymentNotification) error {
+ *p.calls++
+ if p.err == nil && n.TradeNo == "" {
+ n.TradeNo = "upstream-trade"
+ }
+ return p.err
+}
+
+func TestConfirmNotificationUpstreamRecordsAuditOnFailure(t *testing.T) {
+ ctx := context.Background()
+ client := newPaymentConfigServiceTestClient(t)
+ user, err := client.User.Create().
+ SetEmail("confirm-upstream@example.com").
+ SetPasswordHash("hash").
+ SetUsername("confirm-upstream-user").
+ Save(ctx)
+ require.NoError(t, err)
+ order, err := client.PaymentOrder.Create().
+ SetUserID(user.ID).
+ SetUserEmail(user.Email).
+ SetUserName(user.Username).
+ SetAmount(10).
+ SetPayAmount(10).
+ SetFeeRate(0).
+ SetRechargeCode("PAY-CONFIRM-UPSTREAM").
+ SetOutTradeNo("sub2_confirm_upstream").
+ SetPaymentType(payment.TypeAlipay).
+ SetPaymentTradeNo("").
+ SetOrderType(payment.OrderTypeBalance).
+ SetStatus(OrderStatusPending).
+ SetExpiresAt(time.Now().Add(time.Hour)).
+ SetClientIP("127.0.0.1").
+ SetSrcHost("api.example.com").
+ Save(ctx)
+ require.NoError(t, err)
+
+ svc := &PaymentService{entClient: client}
+ calls := 0
+ prov := paymentConfirmTestProvider{
+ paymentFulfillmentTestProvider: paymentFulfillmentTestProvider{key: payment.TypeEasyPay},
+ err: errors.New("easypay confirm: upstream reports order sub2_confirm_upstream as not paid"),
+ calls: &calls,
+ }
+ n := &payment.PaymentNotification{OrderID: order.OutTradeNo, TradeNo: "T-unconfirmed", Amount: 10, Status: payment.NotificationStatusSuccess}
+
+ err = svc.ConfirmNotificationUpstream(ctx, prov, n)
+ require.Error(t, err)
+ require.Equal(t, 1, calls)
+
+ count, err := client.PaymentAuditLog.Query().
+ Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(order.ID, 10)), paymentauditlog.ActionEQ("PAYMENT_UPSTREAM_UNCONFIRMED")).
+ Count(ctx)
+ require.NoError(t, err)
+ require.Equal(t, 1, count)
+
+ reloaded, err := client.PaymentOrder.Get(ctx, order.ID)
+ require.NoError(t, err)
+ require.Equal(t, OrderStatusPending, reloaded.Status)
+}
+
+func TestConfirmNotificationUpstreamPassThrough(t *testing.T) {
+ svc := &PaymentService{}
+ n := &payment.PaymentNotification{OrderID: "sub2_x", Amount: 10, Status: payment.NotificationStatusSuccess}
+
+ // Providers without the confirmer capability keep their existing flow.
+ require.NoError(t, svc.ConfirmNotificationUpstream(context.Background(), paymentFulfillmentTestProvider{key: payment.TypeStripe}, n))
+
+ calls := 0
+ prov := paymentConfirmTestProvider{paymentFulfillmentTestProvider: paymentFulfillmentTestProvider{key: payment.TypeEasyPay}, calls: &calls}
+
+ // Non-success notifications are never fulfilled, so they are not queried.
+ failed := &payment.PaymentNotification{OrderID: "sub2_x", Status: payment.ProviderStatusFailed}
+ require.NoError(t, svc.ConfirmNotificationUpstream(context.Background(), prov, failed))
+ require.Equal(t, 0, calls)
+
+ require.NoError(t, svc.ConfirmNotificationUpstream(context.Background(), prov, n))
+ require.Equal(t, 1, calls)
+ require.Equal(t, "upstream-trade", n.TradeNo)
+}
diff --git a/backend/internal/service/payment_order.go b/backend/internal/service/payment_order.go
index a4948f060..642a3f697 100644
--- a/backend/internal/service/payment_order.go
+++ b/backend/internal/service/payment_order.go
@@ -120,11 +120,16 @@ func (s *PaymentService) CreateOrder(ctx context.Context, req CreateOrderRequest
}
func (s *PaymentService) validateOrderInput(ctx context.Context, req CreateOrderRequest, cfg *PaymentConfig) (*dbent.SubscriptionPlan, error) {
- if req.OrderType == payment.OrderTypeBalance && cfg.BalanceDisabled {
- return nil, infraerrors.Forbidden("BALANCE_PAYMENT_DISABLED", "balance recharge has been disabled")
- }
- if req.OrderType == payment.OrderTypeSubscription {
+ // 订单类型必须走白名单:未知类型会跳过充值开关与倍率计算,履约时却仍按余额到账。
+ switch req.OrderType {
+ case payment.OrderTypeBalance:
+ if cfg.BalanceDisabled {
+ return nil, infraerrors.Forbidden("BALANCE_PAYMENT_DISABLED", "balance recharge has been disabled")
+ }
+ case payment.OrderTypeSubscription:
return s.validateSubOrder(ctx, req)
+ default:
+ return nil, infraerrors.BadRequest("INVALID_ORDER_TYPE", "unsupported order type")
}
if math.IsNaN(req.Amount) || math.IsInf(req.Amount, 0) || req.Amount <= 0 {
return nil, infraerrors.BadRequest("INVALID_AMOUNT", "amount must be a positive number")
diff --git a/backend/internal/service/payment_order_type_test.go b/backend/internal/service/payment_order_type_test.go
new file mode 100644
index 000000000..a6a3775de
--- /dev/null
+++ b/backend/internal/service/payment_order_type_test.go
@@ -0,0 +1,80 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/ent/paymentauditlog"
+ "github.com/MACOS-DO/sub4api/internal/payment"
+ infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+ "github.com/stretchr/testify/require"
+)
+
+func TestValidateOrderInputRejectsUnknownOrderType(t *testing.T) {
+ svc := &PaymentService{}
+ for _, orderType := range []string{"x", "Balance", " balance", "subscription "} {
+ for _, disabled := range []bool{false, true} {
+ cfg := &PaymentConfig{BalanceDisabled: disabled}
+ plan, err := svc.validateOrderInput(context.Background(), CreateOrderRequest{OrderType: orderType, Amount: 10}, cfg)
+ require.Nil(t, plan)
+ require.Error(t, err, "order type %q must be rejected", orderType)
+ require.Equal(t, "INVALID_ORDER_TYPE", infraerrors.Reason(err), "order type %q", orderType)
+ }
+ }
+}
+
+func TestValidateOrderInputKeepsBalanceDisabledSwitch(t *testing.T) {
+ svc := &PaymentService{}
+ _, err := svc.validateOrderInput(context.Background(), CreateOrderRequest{OrderType: payment.OrderTypeBalance, Amount: 10}, &PaymentConfig{BalanceDisabled: true})
+ require.Equal(t, "BALANCE_PAYMENT_DISABLED", infraerrors.Reason(err))
+
+ plan, err := svc.validateOrderInput(context.Background(), CreateOrderRequest{OrderType: payment.OrderTypeBalance, Amount: 10}, &PaymentConfig{})
+ require.NoError(t, err)
+ require.Nil(t, plan)
+}
+
+func TestFulfillmentRejectsUnknownOrderType(t *testing.T) {
+ ctx := context.Background()
+ client := newPaymentConfigServiceTestClient(t)
+ order := createPaymentFulfillmentSubscriptionOrder(t, ctx, client, OrderStatusPaid, time.Now())
+ order, err := client.PaymentOrder.UpdateOneID(order.ID).
+ SetOrderType("x").
+ ClearPlanID().
+ ClearSubscriptionGroupID().
+ ClearSubscriptionDays().
+ Save(ctx)
+ require.NoError(t, err)
+
+ userRepo := &mockUserRepo{getByIDUser: &User{ID: order.UserID}}
+ userRepo.updateBalanceFn = func(context.Context, int64, float64) error {
+ t.Fatal("unknown order type must not credit balance")
+ return nil
+ }
+ svc := &PaymentService{entClient: client, userRepo: userRepo}
+
+ err = svc.ExecuteBalanceFulfillment(ctx, order.ID)
+ require.Equal(t, "INVALID_ORDER_TYPE", infraerrors.Reason(err))
+
+ // 不履约,但标记 FAILED 并正常返回,使支付回调得到确认而不是无限重试。
+ require.NoError(t, svc.executeFulfillment(ctx, order.ID))
+ reloaded, err := client.PaymentOrder.Get(ctx, order.ID)
+ require.NoError(t, err)
+ require.Equal(t, OrderStatusFailed, reloaded.Status)
+ require.NotNil(t, reloaded.FailedReason)
+ require.Contains(t, *reloaded.FailedReason, "unsupported order type")
+
+ // 回调重试经 alreadyProcessed 再次进入履约:幂等,不重复写审计。
+ require.NoError(t, svc.executeFulfillment(ctx, order.ID))
+ audits, err := client.PaymentAuditLog.Query().
+ Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(order.ID, 10)), paymentauditlog.ActionEQ("FULFILLMENT_FAILED")).
+ Count(ctx)
+ require.NoError(t, err)
+ require.Equal(t, 1, audits)
+
+ err = svc.RetryFulfillment(ctx, order.ID)
+ require.Equal(t, "INVALID_ORDER_TYPE", infraerrors.Reason(err))
+}
diff --git a/backend/internal/service/payment_refund.go b/backend/internal/service/payment_refund.go
index a1330b753..502e702a9 100644
--- a/backend/internal/service/payment_refund.go
+++ b/backend/internal/service/payment_refund.go
@@ -210,7 +210,8 @@ func (s *PaymentService) PrepareRefund(ctx context.Context, oid int64, amt float
if err != nil {
return nil, nil, infraerrors.NotFound("NOT_FOUND", "order not found")
}
- ok := []string{OrderStatusCompleted, OrderStatusRefundRequested, OrderStatusRefundPending, OrderStatusRefundFailed}
+ // REFUND_PENDING 只能通过 QueryAndFinalizeRefund 收敛:重新发起会重复扣减并向网关重复退款。
+ ok := []string{OrderStatusCompleted, OrderStatusRefundRequested, OrderStatusRefundFailed}
if !psSliceContains(ok, o.Status) {
return nil, nil, infraerrors.BadRequest("INVALID_STATUS", "order status does not allow refund")
}
@@ -295,8 +296,16 @@ func (s *PaymentService) deductAvailableBalance(ctx context.Context, userID int6
return repo.DeductAvailableBalance(ctx, userID, amount)
}
+// invalidateRefundBalanceCache 退款扣减或归还余额后失效计费缓存,否则网关在缓存 TTL 内仍按旧余额放行。
+func (s *PaymentService) invalidateRefundBalanceCache(ctx context.Context, userID int64) {
+ if s.redeemService == nil {
+ return
+ }
+ s.redeemService.invalidateRedeemCaches(ctx, userID, &RedeemCode{Type: RedeemTypeBalance})
+}
+
func (s *PaymentService) ExecuteRefund(ctx context.Context, p *RefundPlan) (*RefundResult, error) {
- c, err := s.entClient.PaymentOrder.Update().Where(paymentorder.IDEQ(p.OrderID), paymentorder.StatusIn(OrderStatusCompleted, OrderStatusRefundRequested, OrderStatusRefundPending, OrderStatusRefundFailed)).SetStatus(OrderStatusRefunding).Save(ctx)
+ c, err := s.entClient.PaymentOrder.Update().Where(paymentorder.IDEQ(p.OrderID), paymentorder.StatusIn(OrderStatusCompleted, OrderStatusRefundRequested, OrderStatusRefundFailed)).SetStatus(OrderStatusRefunding).Save(ctx)
if err != nil {
return nil, fmt.Errorf("lock: %w", err)
}
@@ -313,6 +322,7 @@ func (s *PaymentService) ExecuteRefund(ctx context.Context, p *RefundPlan) (*Ref
return nil, fmt.Errorf("deduction: %w", err)
}
p.BalanceToDeduct = deducted
+ s.invalidateRefundBalanceCache(ctx, p.Order.UserID)
} else {
slog.Warn("skipping balance deduction on retry (previous rollback failed)", "orderID", p.OrderID)
p.BalanceToDeduct = 0
@@ -436,31 +446,37 @@ func (s *PaymentService) QueryAndFinalizeRefund(ctx context.Context, oid int64)
return nil, infraerrors.BadRequest("REFUND_QUERY_UNSUPPORTED", "this payment provider does not support refund status query; please verify manually")
}
- pendingDetail := s.latestRefundPendingDetail(ctx, oid)
+ pendingDetail, err := s.latestRefundPendingDetail(ctx, oid)
+ if err != nil {
+ return nil, err
+ }
finishProviderCall := servertiming.ObserveDependency(ctx, "payment")
resp, err := queryProvider.QueryRefund(ctx, payment.RefundQueryRequest{
- TradeNo: o.PaymentTradeNo,
- OrderID: o.OutTradeNo,
- RefundID: pendingDetail.RefundID,
- Amount: formatGatewayRefundAmount(o.RefundAmount, o),
+ TradeNo: o.PaymentTradeNo,
+ OrderID: o.OutTradeNo,
+ RefundID: pendingDetail.RefundID,
+ Amount: formatGatewayRefundAmount(o.RefundAmount, o),
+ RequestedAt: pendingDetail.requestedAt,
})
finishProviderCall()
if err != nil {
return nil, fmt.Errorf("query refund: %w", err)
}
- if err := validateRefundProviderResponse(resp); err != nil {
- return s.finalizeRefundFailed(ctx, o, err)
- }
-
plan := s.refundFinalizePlan(o)
- if !pendingDetail.DeductionRollbackOK {
+ switch {
+ case pendingDetail.DeductionHeld:
+ pendingDetail.applyTo(plan)
+ case !pendingDetail.DeductionRollbackOK:
plan.BalanceToDeduct = 0
plan.SubDaysToDeduct = 0
- } else if o.OrderType == payment.OrderTypeSubscription {
+ case o.OrderType == payment.OrderTypeSubscription:
if early := s.prepDeduct(ctx, o, plan, true); early != nil {
return early, nil
}
}
+ if err := validateRefundProviderResponse(resp); err != nil {
+ return s.finalizeRefundFailed(ctx, plan, err)
+ }
switch strings.TrimSpace(resp.Status) {
case payment.ProviderStatusSuccess, payment.ProviderStatusRefunded:
return s.finalizePendingRefundSuccess(ctx, plan)
@@ -468,7 +484,7 @@ func (s *PaymentService) QueryAndFinalizeRefund(ctx context.Context, oid int64)
s.writeAuditLog(ctx, oid, "REFUND_QUERY_PENDING", "admin", map[string]any{"refundID": resp.RefundID})
return &RefundResult{Success: false, Warning: "gateway refund is still pending confirmation"}, nil
default:
- return s.finalizeRefundFailed(ctx, o, fmt.Errorf("payment refund returned unknown status: %s", strings.TrimSpace(resp.Status)))
+ return s.finalizeRefundFailed(ctx, plan, fmt.Errorf("payment refund returned unknown status: %s", strings.TrimSpace(resp.Status)))
}
}
@@ -505,6 +521,9 @@ func (s *PaymentService) finalizePendingRefundSuccess(ctx context.Context, p *Re
if err = tx.Commit(); err != nil {
return nil, fmt.Errorf("commit refund finalization: %w", err)
}
+ if !p.deductionHeld && p.DeductionType == payment.DeductionTypeBalance && p.BalanceToDeduct > 0 {
+ s.invalidateRefundBalanceCache(ctx, p.Order.UserID)
+ }
return result, nil
}
@@ -533,6 +552,10 @@ func (s *PaymentService) refundFinalizePlan(o *dbent.PaymentOrder) *RefundPlan {
}
func (s *PaymentService) applyRefundFinalDeduction(ctx context.Context, p *RefundPlan) error {
+ if p.deductionHeld {
+ // 进入 pending 时扣减已保留,终态成功无需再扣。
+ return nil
+ }
if p.DeductionType == payment.DeductionTypeBalance && p.BalanceToDeduct > 0 {
deducted, err := s.deductAvailableBalance(ctx, p.Order.UserID, p.BalanceToDeduct)
if err != nil {
@@ -554,30 +577,164 @@ func (s *PaymentService) applyRefundFinalDeduction(ctx context.Context, p *Refun
return nil
}
-func (s *PaymentService) finalizeRefundFailed(ctx context.Context, o *dbent.PaymentOrder, gErr error) (*RefundResult, error) {
- now := time.Now()
- _, _ = s.entClient.PaymentOrder.UpdateOneID(o.ID).SetStatus(OrderStatusRefundFailed).SetFailedAt(now).SetFailedReason(psErrMsg(gErr)).Save(ctx)
- s.writeAuditLog(ctx, o.ID, "REFUND_FAILED", "admin", map[string]any{"detail": psErrMsg(gErr)})
- return &RefundResult{Success: false, Warning: "gateway refund failed: " + psErrMsg(gErr)}, nil
+// finalizeRefundFailed 将 REFUND_PENDING 收敛为 REFUND_FAILED,并归还进入 pending 时保留的扣减。
+// 认领状态、归还扣减与审计在同一事务内完成:两者分开提交时,进程在中间退出会留下
+// 已失败但扣减未归还、且没有 REFUND_ROLLBACK_FAILED 标记的订单,重试退款会再扣一次。
+func (s *PaymentService) finalizeRefundFailed(ctx context.Context, p *RefundPlan, gErr error) (*RefundResult, error) {
+ warning := "gateway refund failed: " + psErrMsg(gErr)
+ returnErr, err := s.finalizeRefundFailedTx(ctx, p, gErr, nil)
+ if err != nil {
+ return nil, err
+ }
+ if returnErr == nil {
+ if p.deductionHeld && p.DeductionType == payment.DeductionTypeBalance && p.BalanceToDeduct > 0 {
+ s.invalidateRefundBalanceCache(ctx, p.Order.UserID)
+ }
+ return &RefundResult{Success: false, Warning: warning}, nil
+ }
+
+ // 归还失败(整个事务已回滚,订单仍为 REFUND_PENDING):仍收敛为 REFUND_FAILED,
+ // 并同事务写入 REFUND_ROLLBACK_FAILED,使重试退款跳过扣减,避免二次扣减。
+ slog.Error("[CRITICAL] refund failed but held deduction could not be returned", "orderID", p.OrderID, "error", returnErr)
+ if _, err := s.finalizeRefundFailedTx(ctx, p, gErr, returnErr); err != nil {
+ return nil, err
+ }
+ return &RefundResult{Success: false, Warning: warning + "; refund deduction rollback failed"}, nil
+}
+
+// finalizeRefundFailedTx 在单个事务内认领 REFUND_PENDING → REFUND_FAILED。rollbackErr 为 nil 时同事务
+// 归还保留的扣减,归还失败则回滚整个事务并通过 returnErr 返回;rollbackErr 非 nil 时不再归还,
+// 改为同事务记录 REFUND_ROLLBACK_FAILED。
+func (s *PaymentService) finalizeRefundFailedTx(ctx context.Context, p *RefundPlan, gErr, rollbackErr error) (returnErr error, err error) {
+ tx, err := s.entClient.Tx(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("begin refund failure finalization: %w", err)
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = tx.Rollback()
+ }
+ }()
+ txCtx := dbent.NewTxContext(ctx, tx)
+
+ claimed, err := tx.PaymentOrder.Update().
+ Where(paymentorder.IDEQ(p.OrderID), paymentorder.StatusEQ(OrderStatusRefundPending)).
+ SetStatus(OrderStatusRefundFailed).
+ SetFailedAt(time.Now()).
+ SetFailedReason(psErrMsg(gErr)).
+ Save(txCtx)
+ if err != nil {
+ return nil, fmt.Errorf("mark refund failed: %w", err)
+ }
+ if claimed == 0 {
+ return nil, infraerrors.Conflict("CONFLICT", "order status changed")
+ }
+
+ if p.deductionHeld && rollbackErr == nil {
+ if err := s.returnHeldRefundDeduction(txCtx, p); err != nil {
+ return err, nil
+ }
+ }
+ if rollbackErr != nil {
+ if err := createPaymentAuditLogTx(txCtx, tx.Client(), p.OrderID, "REFUND_ROLLBACK_FAILED", map[string]any{
+ "gatewayError": psErrMsg(gErr),
+ "rollbackError": psErrMsg(rollbackErr),
+ "balanceDeducted": p.BalanceToDeduct,
+ "subDaysDeducted": p.SubDaysToDeduct,
+ }); err != nil {
+ return nil, err
+ }
+ }
+ if err := createPaymentAuditLogTx(txCtx, tx.Client(), p.OrderID, "REFUND_FAILED", map[string]any{"detail": psErrMsg(gErr)}); err != nil {
+ return nil, err
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, fmt.Errorf("commit refund failure finalization: %w", err)
+ }
+ committed = true
+ return nil, nil
}
+// returnHeldRefundDeduction 归还进入 REFUND_PENDING 时保留的扣减;ctx 携带事务时随事务提交或回滚。
+func (s *PaymentService) returnHeldRefundDeduction(ctx context.Context, p *RefundPlan) error {
+ if p.DeductionType == payment.DeductionTypeBalance && p.BalanceToDeduct > 0 {
+ if err := s.userRepo.UpdateBalance(ctx, p.Order.UserID, p.BalanceToDeduct); err != nil {
+ return fmt.Errorf("return held balance deduction: %w", err)
+ }
+ }
+ if p.DeductionType == payment.DeductionTypeSubscription && p.SubDaysToDeduct > 0 && p.SubscriptionID > 0 {
+ if _, err := s.subscriptionSvc.ExtendSubscription(ctx, p.SubscriptionID, p.SubDaysToDeduct); err != nil {
+ return fmt.Errorf("return held subscription deduction: %w", err)
+ }
+ }
+ return nil
+}
+
+func createPaymentAuditLogTx(ctx context.Context, client *dbent.Client, oid int64, action string, detail map[string]any) error {
+ raw, err := json.Marshal(detail)
+ if err != nil {
+ return fmt.Errorf("marshal %s audit: %w", action, err)
+ }
+ if _, err := client.PaymentAuditLog.Create().
+ SetOrderID(strconv.FormatInt(oid, 10)).
+ SetAction(action).
+ SetDetail(string(raw)).
+ SetOperator("admin").
+ Save(ctx); err != nil {
+ return fmt.Errorf("write %s audit: %w", action, err)
+ }
+ return nil
+}
+
+// refundPendingAuditDetail 记录在 REFUND_PENDING 审计日志中。DeductionHeld 为 true 表示
+// 进入 pending 时扣减被保留;旧记录没有该字段,扣减已在 pending 时归还(DeductionRollbackOK)。
type refundPendingAuditDetail struct {
- RefundID string `json:"refundID"`
- DeductionRollbackOK bool `json:"deductionRollbackOK"`
+ RefundID string `json:"refundID"`
+ RefundAmount float64 `json:"refundAmount"`
+ Reason string `json:"reason"`
+ Force bool `json:"force"`
+ DeductionRollbackOK bool `json:"deductionRollbackOK,omitempty"`
+ DeductionHeld bool `json:"deductionHeld,omitempty"`
+ DeductionType string `json:"deductionType,omitempty"`
+ BalanceDeducted float64 `json:"balanceDeducted"`
+ SubDaysDeducted int `json:"subDaysDeducted"`
+ SubscriptionID int64 `json:"subscriptionID,omitempty"`
+ // requestedAt 取自审计记录的创建时间,不参与序列化。
+ requestedAt time.Time
}
-func (s *PaymentService) latestRefundPendingDetail(ctx context.Context, oid int64) refundPendingAuditDetail {
+func (d refundPendingAuditDetail) applyTo(p *RefundPlan) {
+ p.deductionHeld = true
+ p.DeductionType = d.DeductionType
+ if p.DeductionType == "" {
+ p.DeductionType = payment.DeductionTypeNone
+ }
+ p.BalanceToDeduct = d.BalanceDeducted
+ p.SubDaysToDeduct = d.SubDaysDeducted
+ p.SubscriptionID = d.SubscriptionID
+}
+
+// latestRefundPendingDetail 读取最近一次 REFUND_PENDING 审计。没有记录视为旧订单(扣减已在
+// pending 时归还);读取或解析失败必须返回错误:误判为旧记录会让保留的扣减被重复扣减或不再归还。
+func (s *PaymentService) latestRefundPendingDetail(ctx context.Context, oid int64) (refundPendingAuditDetail, error) {
+ detail := refundPendingAuditDetail{DeductionRollbackOK: true}
logEntry, err := s.entClient.PaymentAuditLog.Query().
Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(oid, 10)), paymentauditlog.ActionEQ("REFUND_PENDING")).
- Order(paymentauditlog.ByCreatedAt(sql.OrderDesc())).
+ Order(paymentauditlog.ByCreatedAt(sql.OrderDesc()), paymentauditlog.ByID(sql.OrderDesc())).
First(ctx)
- if err != nil || logEntry == nil {
- return refundPendingAuditDetail{DeductionRollbackOK: true}
+ if err != nil {
+ if dbent.IsNotFound(err) {
+ return detail, nil
+ }
+ return refundPendingAuditDetail{}, fmt.Errorf("load refund pending audit: %w", err)
+ }
+ if err := json.Unmarshal([]byte(logEntry.Detail), &detail); err != nil {
+ return refundPendingAuditDetail{}, fmt.Errorf("parse refund pending audit: %w", err)
}
- detail := refundPendingAuditDetail{DeductionRollbackOK: true}
- _ = json.Unmarshal([]byte(logEntry.Detail), &detail)
detail.RefundID = strings.TrimSpace(detail.RefundID)
- return detail
+ detail.requestedAt = logEntry.CreatedAt
+ return detail, nil
}
// getRefundProvider creates a provider using the order's original instance config.
@@ -644,16 +801,36 @@ func (s *PaymentService) markRefundOkTx(ctx context.Context, client *dbent.Clien
return &RefundResult{Success: true, BalanceDeducted: p.BalanceToDeduct, SubDaysDeducted: p.SubDaysToDeduct}, nil
}
-func (s *PaymentService) markRefundPending(ctx context.Context, p *RefundPlan, resp *payment.RefundResponse) (*RefundResult, error) {
- balanceDeducted := p.BalanceToDeduct
- subDaysDeducted := p.SubDaysToDeduct
- rollbackOK := s.RollbackRefund(ctx, p, nil)
- if rollbackOK {
- p.BalanceToDeduct = 0
- p.SubDaysToDeduct = 0
+// markRefundPending 在网关未给出终态时保留已执行的扣减:若此时归还,用户可在 pending 期间
+// 消费这部分余额,终态成功时只能扣到剩余余额。网关确认失败后由 finalizeRefundFailed 归还。
+// 订单状态与审计记录同事务写入,确保终态收敛时能读到保留的扣减。
+func (s *PaymentService) markRefundPending(ctx context.Context, p *RefundPlan, resp *payment.RefundResponse) (_ *RefundResult, err error) {
+ detail, err := json.Marshal(refundPendingAuditDetail{
+ RefundID: refundResponseID(resp),
+ RefundAmount: p.RefundAmount,
+ Reason: p.Reason,
+ Force: p.Force,
+ DeductionHeld: true,
+ DeductionType: p.DeductionType,
+ BalanceDeducted: p.BalanceToDeduct,
+ SubDaysDeducted: p.SubDaysToDeduct,
+ SubscriptionID: p.SubscriptionID,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("marshal refund pending audit: %w", err)
}
- _, err := s.entClient.PaymentOrder.UpdateOneID(p.OrderID).
+ tx, err := s.entClient.Tx(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("begin mark refund pending: %w", err)
+ }
+ defer func() {
+ if err != nil {
+ _ = tx.Rollback()
+ slog.Error("[CRITICAL] gateway refund pending but order not marked", "orderID", p.OrderID, "error", err)
+ }
+ }()
+ _, err = tx.PaymentOrder.UpdateOneID(p.OrderID).
SetStatus(OrderStatusRefundPending).
SetRefundAmount(p.RefundAmount).
SetRefundReason(p.Reason).
@@ -665,25 +842,18 @@ func (s *PaymentService) markRefundPending(ctx context.Context, p *RefundPlan, r
if err != nil {
return nil, fmt.Errorf("mark refund pending: %w", err)
}
-
- detail := map[string]any{
- "refundID": refundResponseID(resp),
- "refundAmount": p.RefundAmount,
- "reason": p.Reason,
- "force": p.Force,
- "balanceDeducted": p.BalanceToDeduct,
- "subDaysDeducted": p.SubDaysToDeduct,
- "balanceRolledBack": balanceDeducted,
- "subDaysRolledBack": subDaysDeducted,
- "deductionRollbackOK": rollbackOK,
+ if _, err = tx.PaymentAuditLog.Create().
+ SetOrderID(strconv.FormatInt(p.OrderID, 10)).
+ SetAction("REFUND_PENDING").
+ SetDetail(string(detail)).
+ SetOperator("admin").
+ Save(ctx); err != nil {
+ return nil, fmt.Errorf("write refund pending audit: %w", err)
}
- s.writeAuditLog(ctx, p.OrderID, "REFUND_PENDING", "admin", detail)
-
- warning := "gateway refund is pending confirmation"
- if !rollbackOK {
- warning += "; refund deduction rollback failed"
+ if err = tx.Commit(); err != nil {
+ return nil, fmt.Errorf("commit mark refund pending: %w", err)
}
- return &RefundResult{Success: false, Warning: warning}, nil
+ return &RefundResult{Success: false, Warning: "gateway refund is pending confirmation"}, nil
}
func refundResponseID(resp *payment.RefundResponse) string {
@@ -700,6 +870,7 @@ func (s *PaymentService) RollbackRefund(ctx context.Context, p *RefundPlan, gErr
s.writeAuditLog(ctx, p.OrderID, "REFUND_ROLLBACK_FAILED", "admin", map[string]any{"gatewayError": psErrMsg(gErr), "rollbackError": psErrMsg(err), "balanceDeducted": p.BalanceToDeduct})
return false
}
+ s.invalidateRefundBalanceCache(ctx, p.Order.UserID)
}
if p.DeductionType == payment.DeductionTypeSubscription && p.SubDaysToDeduct > 0 && p.SubscriptionID > 0 {
if _, err := s.subscriptionSvc.ExtendSubscription(ctx, p.SubscriptionID, p.SubDaysToDeduct); err != nil {
diff --git a/backend/internal/service/payment_refund_pending_hold_test.go b/backend/internal/service/payment_refund_pending_hold_test.go
new file mode 100644
index 000000000..9e70404a9
--- /dev/null
+++ b/backend/internal/service/payment_refund_pending_hold_test.go
@@ -0,0 +1,312 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "errors"
+ "math"
+ "strconv"
+ "testing"
+ "time"
+
+ dbent "github.com/MACOS-DO/sub4api/ent"
+ "github.com/MACOS-DO/sub4api/ent/paymentauditlog"
+ "github.com/MACOS-DO/sub4api/internal/payment"
+ infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+ "github.com/stretchr/testify/require"
+)
+
+type pendingRefundProviderTestDouble struct {
+ refundProviderTestDouble
+ queryStatus string
+ refundCalls int
+}
+
+func (p *pendingRefundProviderTestDouble) Refund(context.Context, payment.RefundRequest) (*payment.RefundResponse, error) {
+ p.refundCalls++
+ return &payment.RefundResponse{RefundID: "rf_hold", Status: payment.ProviderStatusPending}, nil
+}
+
+func (p *pendingRefundProviderTestDouble) QueryRefund(context.Context, payment.RefundQueryRequest) (*payment.RefundResponse, error) {
+ return &payment.RefundResponse{RefundID: "rf_hold", Status: p.queryStatus}, nil
+}
+
+// refundHoldWallet 模拟用户余额:DeductAvailableBalance 只能扣到当前余额。
+type refundHoldWallet struct {
+ balance float64
+ deductCalls int
+ restoreCalls int
+}
+
+func (w *refundHoldWallet) repo(userID int64) *mockUserRepo {
+ return &mockUserRepo{
+ getByIDUser: &User{ID: userID, Balance: w.balance},
+ deductAvailableBalanceFn: func(_ context.Context, _ int64, amount float64) (float64, error) {
+ w.deductCalls++
+ deducted := math.Min(amount, math.Max(w.balance, 0))
+ w.balance -= deducted
+ return deducted, nil
+ },
+ updateBalanceFn: func(_ context.Context, _ int64, amount float64) error {
+ w.restoreCalls++
+ w.balance += amount
+ return nil
+ },
+ }
+}
+
+func TestRefundPendingKeepsBalanceDeductedUntilGatewaySettles(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ queryStatus string
+ wantStatus string
+ wantBalance float64
+ wantRestore int
+ }{
+ {name: "gateway succeeds", queryStatus: payment.ProviderStatusSuccess, wantStatus: OrderStatusRefunded, wantBalance: 0},
+ {name: "gateway fails", queryStatus: payment.ProviderStatusFailed, wantStatus: OrderStatusRefundFailed, wantBalance: 100, wantRestore: 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx := context.Background()
+ client := newPaymentConfigServiceTestClient(t)
+ order := createCompletedRefundableOrderForTest(t, ctx, client, "hold-flow")
+
+ wallet := &refundHoldWallet{balance: 100}
+ prov := &pendingRefundProviderTestDouble{queryStatus: tc.queryStatus}
+ restore := replacePaymentProviderFactoryForTest(t, prov)
+ defer restore()
+ svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: wallet.repo(order.UserID)}
+
+ plan, early, err := svc.PrepareRefund(ctx, order.ID, 0, "user asked", false, true)
+ require.NoError(t, err)
+ require.Nil(t, early)
+ result, err := svc.ExecuteRefund(ctx, plan)
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.Contains(t, result.Warning, "pending confirmation")
+
+ // pending 期间余额必须保持扣减,否则用户可先消费再等网关退款成功。
+ require.Zero(t, wallet.balance)
+ require.Zero(t, wallet.restoreCalls)
+ reloaded, err := client.PaymentOrder.Get(ctx, order.ID)
+ require.NoError(t, err)
+ require.Equal(t, OrderStatusRefundPending, reloaded.Status)
+
+ // pending 订单不能再次发起退款(会重复扣减并重复调用网关)。
+ _, _, err = svc.PrepareRefund(ctx, order.ID, 0, "again", true, true)
+ require.Equal(t, "INVALID_STATUS", infraerrors.Reason(err))
+
+ result, err = svc.QueryAndFinalizeRefund(ctx, order.ID)
+ require.NoError(t, err)
+ require.Equal(t, tc.queryStatus == payment.ProviderStatusSuccess, result.Success)
+ if result.Success {
+ require.Equal(t, 100.0, result.BalanceDeducted)
+ }
+ require.Equal(t, 1, wallet.deductCalls, "held deduction must not be applied twice")
+ require.Equal(t, tc.wantRestore, wallet.restoreCalls)
+ require.Equal(t, tc.wantBalance, wallet.balance)
+ require.Equal(t, 1, prov.refundCalls)
+
+ reloaded, err = client.PaymentOrder.Get(ctx, order.ID)
+ require.NoError(t, err)
+ require.Equal(t, tc.wantStatus, reloaded.Status)
+
+ _, err = svc.QueryAndFinalizeRefund(ctx, order.ID)
+ require.Equal(t, "INVALID_STATUS", infraerrors.Reason(err))
+ require.Equal(t, tc.wantRestore, wallet.restoreCalls)
+ })
+ }
+}
+
+func TestFinalizeRefundFailedRestoresHeldDeductionOnce(t *testing.T) {
+ ctx := context.Background()
+ client := newPaymentConfigServiceTestClient(t)
+ order := createPendingRefundOrderWithDetailForTest(t, ctx, client, "hold-failed-once",
+ `{"refundID":"rf_test","deductionHeld":true,"deductionType":"balance","balanceDeducted":60}`)
+
+ wallet := &refundHoldWallet{}
+ svc := &PaymentService{entClient: client, userRepo: wallet.repo(order.UserID)}
+ plan := svc.refundFinalizePlan(order)
+ detail, err := svc.latestRefundPendingDetail(ctx, order.ID)
+ require.NoError(t, err)
+ detail.applyTo(plan)
+
+ first, err := svc.finalizeRefundFailed(ctx, plan, context.DeadlineExceeded)
+ require.NoError(t, err)
+ require.False(t, first.Success)
+ second, err := svc.finalizeRefundFailed(ctx, plan, context.DeadlineExceeded)
+ require.Nil(t, second)
+ require.Equal(t, "CONFLICT", infraerrors.Reason(err))
+
+ require.Equal(t, 1, wallet.restoreCalls)
+ require.Equal(t, 60.0, wallet.balance)
+}
+
+func TestQueryAndFinalizeRefundHeldDeductionWithoutBalanceDeduction(t *testing.T) {
+ ctx := context.Background()
+ client := newPaymentConfigServiceTestClient(t)
+ // 管理员选择不扣余额时,终态收敛也不能按旧逻辑补扣。
+ order := createPendingRefundOrderWithDetailForTest(t, ctx, client, "hold-no-deduct",
+ `{"refundID":"rf_test","deductionHeld":true,"deductionType":"none","balanceDeducted":0}`)
+
+ wallet := &refundHoldWallet{balance: 100}
+ restore := replacePaymentProviderFactoryForTest(t, &pendingRefundProviderTestDouble{queryStatus: payment.ProviderStatusSuccess})
+ defer restore()
+ svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: wallet.repo(order.UserID)}
+
+ result, err := svc.QueryAndFinalizeRefund(ctx, order.ID)
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ require.Zero(t, wallet.deductCalls)
+ require.Equal(t, 100.0, wallet.balance)
+}
+
+type successRefundProviderTestDouble struct {
+ refundProviderTestDouble
+ refundCalls int
+}
+
+func (p *successRefundProviderTestDouble) Refund(context.Context, payment.RefundRequest) (*payment.RefundResponse, error) {
+ p.refundCalls++
+ return &payment.RefundResponse{RefundID: "rf_retry", Status: payment.ProviderStatusSuccess}, nil
+}
+
+func countRefundAuditsForTest(t *testing.T, ctx context.Context, client *dbent.Client, orderID int64, action string) int {
+ t.Helper()
+ n, err := client.PaymentAuditLog.Query().
+ Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(orderID, 10)), paymentauditlog.ActionEQ(action)).
+ Count(ctx)
+ require.NoError(t, err)
+ return n
+}
+
+func TestFinalizeRefundFailedRecordsRollbackFailureWhenHeldDeductionCannotBeReturned(t *testing.T) {
+ ctx := context.Background()
+ client := newPaymentConfigServiceTestClient(t)
+ order := createPendingRefundOrderWithDetailForTest(t, ctx, client, "hold-return-fails",
+ `{"refundID":"rf_test","deductionHeld":true,"deductionType":"balance","balanceDeducted":60}`)
+
+ wallet := &refundHoldWallet{balance: 40}
+ repo := wallet.repo(order.UserID)
+ repo.updateBalanceFn = func(context.Context, int64, float64) error {
+ wallet.restoreCalls++
+ return errors.New("db unavailable")
+ }
+ restore := replacePaymentProviderFactoryForTest(t, &pendingRefundProviderTestDouble{queryStatus: payment.ProviderStatusFailed})
+ defer restore()
+ svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: repo}
+
+ result, err := svc.QueryAndFinalizeRefund(ctx, order.ID)
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.Contains(t, result.Warning, "refund deduction rollback failed")
+ require.Equal(t, 1, wallet.restoreCalls)
+ require.Equal(t, 40.0, wallet.balance)
+
+ reloaded, err := client.PaymentOrder.Get(ctx, order.ID)
+ require.NoError(t, err)
+ require.Equal(t, OrderStatusRefundFailed, reloaded.Status)
+ require.Equal(t, 1, countRefundAuditsForTest(t, ctx, client, order.ID, "REFUND_ROLLBACK_FAILED"))
+ require.Equal(t, 1, countRefundAuditsForTest(t, ctx, client, order.ID, "REFUND_FAILED"))
+
+ // 扣减仍被保留:重试退款必须跳过扣减,否则同一笔退款会扣两次。
+ retryProvider := &successRefundProviderTestDouble{}
+ restoreRetry := replacePaymentProviderFactoryForTest(t, retryProvider)
+ defer restoreRetry()
+ plan, early, err := svc.PrepareRefund(ctx, order.ID, 0, "retry", true, true)
+ require.NoError(t, err)
+ require.Nil(t, early)
+ retried, err := svc.ExecuteRefund(ctx, plan)
+ require.NoError(t, err)
+ require.True(t, retried.Success)
+ require.Zero(t, wallet.deductCalls)
+ require.Equal(t, 40.0, wallet.balance)
+ require.Equal(t, 1, retryProvider.refundCalls)
+}
+
+func TestFinalizeRefundFailedReturnsHeldDeductionAtomically(t *testing.T) {
+ ctx := context.Background()
+ client := newPaymentConfigServiceTestClient(t)
+ order := createPendingRefundOrderWithDetailForTest(t, ctx, client, "hold-return-atomic",
+ `{"refundID":"rf_test","deductionHeld":true,"deductionType":"balance","balanceDeducted":60}`)
+
+ wallet := &refundHoldWallet{}
+ restore := replacePaymentProviderFactoryForTest(t, &pendingRefundProviderTestDouble{queryStatus: payment.ProviderStatusFailed})
+ defer restore()
+ svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: wallet.repo(order.UserID)}
+
+ result, err := svc.QueryAndFinalizeRefund(ctx, order.ID)
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.NotContains(t, result.Warning, "rollback failed")
+ require.Equal(t, 1, wallet.restoreCalls)
+ require.Equal(t, 60.0, wallet.balance)
+ require.Equal(t, 1, countRefundAuditsForTest(t, ctx, client, order.ID, "REFUND_FAILED"))
+ require.Zero(t, countRefundAuditsForTest(t, ctx, client, order.ID, "REFUND_ROLLBACK_FAILED"))
+}
+
+func TestQueryAndFinalizeRefundRejectsUnreadablePendingAudit(t *testing.T) {
+ ctx := context.Background()
+ client := newPaymentConfigServiceTestClient(t)
+ // 审计无法解析时不能退化为旧逻辑:成功会二次扣减,失败会吞掉保留的扣减。
+ order := createPendingRefundOrderWithDetailForTest(t, ctx, client, "hold-bad-audit", `not-json`)
+
+ for _, queryStatus := range []string{payment.ProviderStatusSuccess, payment.ProviderStatusFailed} {
+ wallet := &refundHoldWallet{balance: 100}
+ restore := replacePaymentProviderFactoryForTest(t, &pendingRefundProviderTestDouble{queryStatus: queryStatus})
+ svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: wallet.repo(order.UserID)}
+
+ result, err := svc.QueryAndFinalizeRefund(ctx, order.ID)
+ restore()
+ require.Error(t, err, queryStatus)
+ require.Nil(t, result)
+ require.Zero(t, wallet.deductCalls)
+ require.Zero(t, wallet.restoreCalls)
+ require.Equal(t, 100.0, wallet.balance)
+ }
+
+ reloaded, err := client.PaymentOrder.Get(ctx, order.ID)
+ require.NoError(t, err)
+ require.Equal(t, OrderStatusRefundPending, reloaded.Status)
+}
+
+func createCompletedRefundableOrderForTest(t *testing.T, ctx context.Context, client *dbent.Client, suffix string) *dbent.PaymentOrder {
+ t.Helper()
+ user, err := client.User.Create().
+ SetEmail(suffix + "@example.com").
+ SetPasswordHash("hash").
+ SetUsername(suffix).
+ Save(ctx)
+ require.NoError(t, err)
+ inst, err := client.PaymentProviderInstance.Create().
+ SetProviderKey(payment.TypeStripe).
+ SetName(suffix + "-provider").
+ SetConfig("{}").
+ SetSupportedTypes("stripe").
+ SetEnabled(true).
+ SetRefundEnabled(true).
+ Save(ctx)
+ require.NoError(t, err)
+ order, err := client.PaymentOrder.Create().
+ SetUserID(user.ID).
+ SetUserEmail(user.Email).
+ SetUserName(user.Username).
+ SetAmount(100).
+ SetPayAmount(100).
+ SetFeeRate(0).
+ SetRechargeCode("REFUND-" + suffix).
+ SetOutTradeNo("sub2_" + suffix).
+ SetPaymentType(payment.TypeStripe).
+ SetPaymentTradeNo("pi_" + suffix).
+ SetOrderType(payment.OrderTypeBalance).
+ SetStatus(OrderStatusCompleted).
+ SetExpiresAt(time.Now().Add(time.Hour)).
+ SetPaidAt(time.Now()).
+ SetClientIP("127.0.0.1").
+ SetSrcHost("api.example.com").
+ SetProviderInstanceID(strconv.FormatInt(inst.ID, 10)).
+ Save(ctx)
+ require.NoError(t, err)
+ return order
+}
diff --git a/backend/internal/service/payment_refund_test.go b/backend/internal/service/payment_refund_test.go
index 07f73ca0c..e4965442e 100644
--- a/backend/internal/service/payment_refund_test.go
+++ b/backend/internal/service/payment_refund_test.go
@@ -299,7 +299,7 @@ func TestValidateRefundProviderResponseAcceptsPending(t *testing.T) {
require.Error(t, validateRefundProviderResponse(nil))
}
-func TestFinishRefundPendingMarksOrderPendingAndRollsBackDeduction(t *testing.T) {
+func TestFinishRefundPendingMarksOrderPendingAndHoldsDeduction(t *testing.T) {
ctx := context.Background()
client := newPaymentConfigServiceTestClient(t)
@@ -357,8 +357,8 @@ func TestFinishRefundPendingMarksOrderPendingAndRollsBackDeduction(t *testing.T)
require.NotNil(t, result)
require.False(t, result.Success)
require.Contains(t, result.Warning, "pending confirmation")
- require.Equal(t, 40.0, rolledBack)
- require.Zero(t, plan.BalanceToDeduct)
+ require.Zero(t, rolledBack, "deduction must stay held while the gateway refund is pending")
+ require.Equal(t, 40.0, plan.BalanceToDeduct)
reloaded, err := client.PaymentOrder.Get(ctx, order.ID)
require.NoError(t, err)
@@ -373,6 +373,11 @@ func TestFinishRefundPendingMarksOrderPendingAndRollsBackDeduction(t *testing.T)
Count(ctx)
require.NoError(t, err)
require.Equal(t, 1, pendingAudits)
+ detail, err := svc.latestRefundPendingDetail(ctx, order.ID)
+ require.NoError(t, err)
+ require.True(t, detail.DeductionHeld)
+ require.Equal(t, payment.DeductionTypeBalance, detail.DeductionType)
+ require.Equal(t, 40.0, detail.BalanceDeducted)
successAudits, err := client.PaymentAuditLog.Query().
Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(order.ID, 10)), paymentauditlog.ActionEQ("REFUND_SUCCESS")).
Count(ctx)
@@ -502,6 +507,26 @@ func TestQueryAndFinalizeRefundFinalizesProviderStatuses(t *testing.T) {
}
}
+func TestQueryAndFinalizeRefundPassesPendingAuditTimeToProvider(t *testing.T) {
+ ctx := context.Background()
+ client := newPaymentConfigServiceTestClient(t)
+ order := createPendingRefundOrderForTest(t, ctx, client, "query-requested-at")
+ pendingAudit, err := client.PaymentAuditLog.Query().
+ Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(order.ID, 10)), paymentauditlog.ActionEQ("REFUND_PENDING")).
+ Only(ctx)
+ require.NoError(t, err)
+
+ svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: &mockUserRepo{}}
+ prov := &refundQueryProviderTestDouble{refundResponse: &payment.RefundResponse{RefundID: "rf_test", Status: payment.ProviderStatusPending}}
+ restore := replacePaymentProviderFactoryForTest(t, prov)
+ defer restore()
+
+ _, err = svc.QueryAndFinalizeRefund(ctx, order.ID)
+ require.NoError(t, err)
+ require.Equal(t, "rf_test", prov.lastQuery.RefundID)
+ require.True(t, pendingAudit.CreatedAt.Equal(prov.lastQuery.RequestedAt), "RequestedAt = %v, want %v", prov.lastQuery.RequestedAt, pendingAudit.CreatedAt)
+}
+
func TestFinalizePendingRefundSuccessRejectsStaleCallerBeforeSecondDeduction(t *testing.T) {
ctx := context.Background()
client := newPaymentConfigServiceTestClient(t)
@@ -586,6 +611,11 @@ func TestQueryAndFinalizeRefundUnsupportedProviderReturnsClearError(t *testing.T
func createPendingRefundOrderForTest(t *testing.T, ctx context.Context, client *dbent.Client, suffix string) *dbent.PaymentOrder {
t.Helper()
+ return createPendingRefundOrderWithDetailForTest(t, ctx, client, suffix, `{"refundID":"rf_test","deductionRollbackOK":true}`)
+}
+
+func createPendingRefundOrderWithDetailForTest(t *testing.T, ctx context.Context, client *dbent.Client, suffix, pendingDetail string) *dbent.PaymentOrder {
+ t.Helper()
user, err := client.User.Create().
SetEmail(suffix + "@example.com").
@@ -631,7 +661,7 @@ func createPendingRefundOrderForTest(t *testing.T, ctx context.Context, client *
SetOrderID(strconv.FormatInt(order.ID, 10)).
SetAction("REFUND_PENDING").
SetOperator("admin").
- SetDetail(`{"refundID":"rf_test","deductionRollbackOK":true}`).
+ SetDetail(pendingDetail).
Save(ctx)
require.NoError(t, err)
return order
@@ -671,8 +701,10 @@ func (refundProviderTestDouble) Refund(context.Context, payment.RefundRequest) (
type refundQueryProviderTestDouble struct {
refundProviderTestDouble
refundResponse *payment.RefundResponse
+ lastQuery payment.RefundQueryRequest
}
-func (p *refundQueryProviderTestDouble) QueryRefund(context.Context, payment.RefundQueryRequest) (*payment.RefundResponse, error) {
+func (p *refundQueryProviderTestDouble) QueryRefund(_ context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) {
+ p.lastQuery = req
return p.refundResponse, nil
}
diff --git a/backend/internal/service/payment_resume_service.go b/backend/internal/service/payment_resume_service.go
index 92366c631..0a30bde66 100644
--- a/backend/internal/service/payment_resume_service.go
+++ b/backend/internal/service/payment_resume_service.go
@@ -244,7 +244,16 @@ func CanonicalizeReturnURL(raw string, srcHost string, srcURL string) (string, e
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return "", infraerrors.BadRequest("INVALID_RETURN_URL", "return_url must use http or https")
}
+ // The return URL is handed to payment gateways verbatim: keep it to a
+ // plain hostname or IP literal and the canonical path, without userinfo.
+ if parsed.User != nil {
+ return "", infraerrors.BadRequest("INVALID_RETURN_URL", "return_url must not contain user info")
+ }
+ if !isPlainReturnURLHost(parsed.Hostname()) {
+ return "", infraerrors.BadRequest("INVALID_RETURN_URL", "return_url host is invalid")
+ }
parsed.Fragment = ""
+ parsed.RawPath = ""
// Client-supplied query parameters are dropped: buildPaymentReturnURL adds
// its own signed set, and user-controlled pairs such as
// "trade_status=TRADE_SUCCESS" inside the signed return_url value can be
@@ -264,6 +273,25 @@ func CanonicalizeReturnURL(raw string, srcHost string, srcURL string) (string, e
return parsed.String(), nil
}
+// isPlainReturnURLHost reports whether host is an IP literal or a hostname
+// made only of letters, digits, '.', '-' and '_'.
+func isPlainReturnURLHost(host string) bool {
+ if host == "" {
+ return false
+ }
+ if net.ParseIP(host) != nil {
+ return true
+ }
+ for _, c := range host {
+ switch {
+ case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '.', c == '-', c == '_':
+ default:
+ return false
+ }
+ }
+ return true
+}
+
func allowedReturnURLHost(returnURLHost string, requestHost string, refererURL string) bool {
if sameOriginHost(returnURLHost, requestHost) {
return true
diff --git a/backend/internal/service/payment_resume_service_test.go b/backend/internal/service/payment_resume_service_test.go
index 0e81ba9a8..e012ad823 100644
--- a/backend/internal/service/payment_resume_service_test.go
+++ b/backend/internal/service/payment_resume_service_test.go
@@ -109,6 +109,42 @@ func TestCanonicalizeReturnURLStripsSmuggledTradeStatus(t *testing.T) {
}
}
+func TestCanonicalizeReturnURLRejectsNonPlainHostAndUserinfo(t *testing.T) {
+ t.Parallel()
+
+ badHost := "a&b=c.example.com"
+ cases := []struct {
+ name string
+ raw string
+ srcHost string
+ srcURL string
+ }{
+ {"host matched via referer", "https://" + badHost + "/payment/result", "app.example.com", "https://" + badHost + "/purchase"},
+ {"host matched via request host", "https://" + badHost + "/payment/result", badHost, ""},
+ {"userinfo", "https://a&b=c@app.example.com/payment/result", "app.example.com", ""},
+ }
+ for _, tc := range cases {
+ if got, err := CanonicalizeReturnURL(tc.raw, tc.srcHost, tc.srcURL); err == nil {
+ t.Fatalf("%s: CanonicalizeReturnURL accepted %q", tc.name, got)
+ }
+ }
+}
+
+func TestCanonicalizeReturnURLAllowsIPAndPortHosts(t *testing.T) {
+ t.Parallel()
+
+ for _, raw := range []string{
+ "http://127.0.0.1:3000/payment/result",
+ "http://[::1]:8080/payment/result",
+ "https://pay_site-1.example.com/payment/result",
+ } {
+ parsed, _ := url.Parse(raw)
+ if _, err := CanonicalizeReturnURL(raw, parsed.Host, ""); err != nil {
+ t.Fatalf("CanonicalizeReturnURL(%q) returned error: %v", raw, err)
+ }
+ }
+}
+
func TestCanonicalizeReturnURLRejectsRelativeURL(t *testing.T) {
t.Parallel()
diff --git a/backend/internal/service/payment_service.go b/backend/internal/service/payment_service.go
index 21379c7c5..240d67ccc 100644
--- a/backend/internal/service/payment_service.go
+++ b/backend/internal/service/payment_service.go
@@ -134,6 +134,8 @@ type RefundPlan struct {
BalanceToDeduct float64
SubDaysToDeduct int
SubscriptionID int64
+ // deductionHeld 表示扣减已在进入 REFUND_PENDING 前执行并保留,终态收敛时不再重复扣减。
+ deductionHeld bool
}
type RefundResult struct {
diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go
index 484c075b0..5d17f2ea2 100644
--- a/backend/internal/service/pricing_service.go
+++ b/backend/internal/service/pricing_service.go
@@ -139,6 +139,14 @@ var (
CacheReadInputTokenCost: 0.2e-6,
LiteLLMProvider: "anthropic", Mode: "chat", SupportsPromptCaching: true,
}
+ claudeHaiku55FallbackPricing = &LiteLLMModelPricing{
+ InputCostPerToken: 1e-7, OutputCostPerToken: 5e-7,
+ CacheCreationInputTokenCost: 1.25e-7, CacheCreationInputTokenCostAbove1hr: 2e-7,
+ CacheReadInputTokenCost: 1e-8,
+ LongContextInputTokenThreshold: 100000,
+ LongContextInputCostMultiplier: 5, LongContextOutputCostMultiplier: 5,
+ LiteLLMProvider: "anthropic", Mode: "chat", SupportsPromptCaching: true,
+ }
openAIGPT56SolFallbackPricing = &LiteLLMModelPricing{
InputCostPerToken: 5e-06,
InputCostPerTokenPriority: 1e-05,
@@ -223,6 +231,9 @@ type LiteLLMModelPricing struct {
OutputCostPerImageToken float64 `json:"output_cost_per_image_token"` // 图片输出 token 价格
InputCostPerImageToken float64 `json:"input_cost_per_image_token"` // 图片输入 token 价格(如 gpt-image-2 图片编辑)
CacheReadInputImageTokenCost float64 `json:"cache_read_input_image_token_cost"`
+ // CacheStorageCostPerTokenPerHour 显式上下文缓存存储单价(每 token 每小时,USD),一般由定价覆盖文件提供,
+ // 配置后优先于内置价(见 BillingService.CacheStoragePricePerTokenHour)。
+ CacheStorageCostPerTokenPerHour float64 `json:"cache_storage_cost_per_token_per_hour"`
// TokenPricingAbsent 表示源数据中 input/output token 价格均缺失(仅有图片价)。
// 此类条目只可用于图片计费,token 计费必须回退到 fallback 或 fail-closed,
@@ -258,6 +269,7 @@ type LiteLLMRawEntry struct {
OutputCostPerImageToken *float64 `json:"output_cost_per_image_token"`
InputCostPerImageToken *float64 `json:"input_cost_per_image_token"`
CacheReadInputImageTokenCost *float64 `json:"cache_read_input_image_token_cost"`
+ CacheStorageCostPerTokenPerHour *float64 `json:"cache_storage_cost_per_token_per_hour"`
}
// PricingService 动态价格服务
@@ -730,6 +742,9 @@ func (s *PricingService) parsePricingData(body []byte) (map[string]*LiteLLMModel
if entry.CacheReadInputImageTokenCost != nil {
pricing.CacheReadInputImageTokenCost = *entry.CacheReadInputImageTokenCost
}
+ if entry.CacheStorageCostPerTokenPerHour != nil {
+ pricing.CacheStorageCostPerTokenPerHour = *entry.CacheStorageCostPerTokenPerHour
+ }
hasExplicitLongContext := entry.LongContextInputTokenThreshold != nil ||
entry.LongContextInputCostMultiplier != nil ||
@@ -1291,10 +1306,10 @@ func (s *PricingService) buildModelLookupCandidates(modelLower string) []string
normalized := normalizeModelNameForPricing(modelLower)
// A tier-specific entry should take precedence when the pricing catalog gains
- // one later. Antigravity's Gemini Flash thinking tiers share the base rate,
+ // one later. Antigravity's Gemini thinking tiers share the base rate,
// so the normalized base remains the fallback after the exact aliases.
candidates := rawCandidates
- if normalizeGeminiThinkingTierAlias(lastSegment(modelLower)) != lastSegment(modelLower) {
+ if isAntigravityThinkingTierAlias(lastSegment(modelLower)) {
candidates = append(candidates, normalized)
} else {
// Prefer canonical model names for all other aliases (including models/xxx).
@@ -1350,15 +1365,37 @@ func normalizeModelNameForPricing(model string) string {
}
return canonical
}
- return normalizeGeminiThinkingTierAlias(model)
+ return normalizeAntigravityClaudeTierAlias(normalizeGeminiThinkingTierAlias(model))
}
-// normalizeGeminiThinkingTierAlias maps Antigravity's Gemini Flash
-// thinking-tier model IDs to the public base model. The tier controls reasoning
-// behavior, not the published token rate, so this keeps -high/-low/-medium and
-// -tiered requests on the corresponding base model's price card.
+// normalizeAntigravityClaudeTierAlias maps Antigravity's Claude 5.5 thinking-tier
+// model IDs (claude-opus-5-5-high, claude-sonnet-5-5-low, ...) to the public base
+// model. Like the Gemini tiers, the suffix selects reasoning depth rather than a
+// separate token rate; without this the IDs fall into substring family matching
+// and are billed as claude-opus-5 / claude-sonnet-4-5.
+func normalizeAntigravityClaudeTierAlias(model string) string {
+ for _, baseModel := range []string{"claude-opus-5-5", "claude-sonnet-5-5"} {
+ for _, tier := range []string{"-high", "-low", "-medium"} {
+ if model == baseModel+tier {
+ return baseModel
+ }
+ }
+ }
+ return model
+}
+
+// isAntigravityThinkingTierAlias reports whether model is an Antigravity
+// Gemini or Claude thinking-tier alias of a priced base model.
+func isAntigravityThinkingTierAlias(model string) bool {
+ return normalizeGeminiThinkingTierAlias(model) != model || normalizeAntigravityClaudeTierAlias(model) != model
+}
+
+// normalizeGeminiThinkingTierAlias maps Antigravity's Gemini thinking-tier
+// model IDs to the public base model. The tier controls reasoning behavior, not
+// the published token rate, so this keeps -high/-low/-medium and -tiered
+// requests on the corresponding base model's price card.
func normalizeGeminiThinkingTierAlias(model string) string {
- for _, baseModel := range []string{"gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash"} {
+ for _, baseModel := range []string{"gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash", "gemini-4-argon"} {
for _, tier := range []string{"-high", "-low", "-medium", "-tiered"} {
if model == baseModel+tier {
return baseModel
@@ -1396,6 +1433,7 @@ func (s *PricingService) extractBaseName(model string) string {
// matchByModelFamily 基于模型系列匹配
func (s *PricingService) matchByModelFamily(model string) *LiteLLMModelPricing {
+ model = normalizeAntigravityClaudeTierAlias(model)
if claude.IsOpus55(model) {
if pricing, ok := s.pricingData["claude-opus-5-5"]; ok {
return pricing
@@ -1408,6 +1446,12 @@ func (s *PricingService) matchByModelFamily(model string) *LiteLLMModelPricing {
}
return claudeSonnet55FallbackPricing
}
+ if claude.IsHaiku55(model) {
+ if pricing, ok := s.pricingData["claude-haiku-5-5"]; ok {
+ return pricing
+ }
+ return claudeHaiku55FallbackPricing
+ }
// modelFamily 定义一个模型系列的匹配和定价查找规则。
type modelFamily struct {
name string // 系列名称
diff --git a/backend/internal/service/pricing_service_test.go b/backend/internal/service/pricing_service_test.go
index 241484c87..14bfe564c 100644
--- a/backend/internal/service/pricing_service_test.go
+++ b/backend/internal/service/pricing_service_test.go
@@ -613,10 +613,10 @@ func TestBillingService_Gemini36FlashThinkingTierFallbacksAreBillable(t *testing
t.Run(model, func(t *testing.T) {
cost, err := svc.CalculateCost(model, tokens, 1)
require.NoError(t, err)
- require.InDelta(t, 1.5, cost.InputCost, 1e-12)
- require.InDelta(t, 7.5, cost.OutputCost, 1e-12)
- require.InDelta(t, 0.15, cost.CacheReadCost, 1e-12)
- require.InDelta(t, 9.15, cost.TotalCost, 1e-12)
+ require.InDelta(t, 0.75, cost.InputCost, 1e-12)
+ require.InDelta(t, 3.75, cost.OutputCost, 1e-12)
+ require.InDelta(t, 0.075, cost.CacheReadCost, 1e-12)
+ require.InDelta(t, 4.575, cost.TotalCost, 1e-12)
})
}
}
@@ -725,11 +725,98 @@ func TestDefaultPricingIncludesGemini36FlashRates(t *testing.T) {
t.Run(model, func(t *testing.T) {
pricing, err := billingSvc.GetModelPricing(model)
require.NoError(t, err)
- require.InDelta(t, 1.5e-6, pricing.InputPricePerToken, 1e-12)
- require.InDelta(t, 7.5e-6, pricing.OutputPricePerToken, 1e-12)
- require.InDelta(t, 0.15e-6, pricing.CacheReadPricePerToken, 1e-12)
+ require.InDelta(t, 0.75e-6, pricing.InputPricePerToken, 1e-12)
+ require.InDelta(t, 3.75e-6, pricing.OutputPricePerToken, 1e-12)
+ require.InDelta(t, 0.075e-6, pricing.CacheReadPricePerToken, 1e-12)
+ })
+ }
+}
+
+func TestPricingService_Gemini4ArgonThinkingTiersUseBasePricing(t *testing.T) {
+ basePricing := &LiteLLMModelPricing{InputCostPerToken: 2e-6, OutputCostPerToken: 10e-6, CacheReadInputTokenCost: 0.1e-6}
+ cyberPricing := &LiteLLMModelPricing{InputCostPerToken: 4e-6, OutputCostPerToken: 20e-6, CacheReadInputTokenCost: 0.2e-6}
+ svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{
+ "gemini-4-argon": basePricing,
+ "gemini-4-argon-cyber-permissive": cyberPricing,
+ }}
+
+ for _, model := range []string{
+ "gemini-4-argon",
+ "gemini-4-argon-high",
+ "gemini-4-argon-low",
+ "gemini-4-argon-medium",
+ "models/gemini-4-argon-high",
+ "projects/p/locations/global/publishers/google/models/gemini-4-argon",
+ } {
+ t.Run(model, func(t *testing.T) {
+ require.Same(t, basePricing, svc.GetModelPricing(model))
+ })
+ }
+ require.Same(t, cyberPricing, svc.GetModelPricing("gemini-4-argon-cyber-permissive"))
+}
+
+func TestBillingService_Gemini4ArgonFallbacksAreBillable(t *testing.T) {
+ svc := NewBillingService(&config.Config{}, nil)
+ tokens := UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000}
+
+ for _, tc := range []struct {
+ model string
+ input, output, read float64
+ }{
+ {"gemini-4-argon", 2, 10, 0.1},
+ {"gemini-4-argon-high", 2, 10, 0.1},
+ {"gemini-4-argon-low", 2, 10, 0.1},
+ {"gemini-4-argon-medium", 2, 10, 0.1},
+ {"models/gemini-4-argon", 2, 10, 0.1},
+ {"gemini-4-argon-cyber-permissive", 4, 20, 0.2},
+ {"gemini-4-argon-cyber", 4, 20, 0.2},
+ {"publishers/google/models/gemini-4-argon-cyber-permissive", 4, 20, 0.2},
+ } {
+ t.Run(tc.model, func(t *testing.T) {
+ cost, err := svc.CalculateCost(tc.model, tokens, 1)
+ require.NoError(t, err)
+ require.InDelta(t, tc.input, cost.InputCost, 1e-12)
+ require.InDelta(t, tc.output, cost.OutputCost, 1e-12)
+ require.InDelta(t, tc.read, cost.CacheReadCost, 1e-12)
+ require.InDelta(t, tc.input+tc.output+tc.read, cost.TotalCost, 1e-12)
+ })
+ }
+}
+
+func TestDefaultPricingIncludesGemini4ArgonRates(t *testing.T) {
+ data, err := os.ReadFile(filepath.Join("..", "..", "resources", "model-pricing", "model_prices_and_context_window.json"))
+ require.NoError(t, err)
+
+ pricingSvc := &PricingService{}
+ pricingData, err := pricingSvc.parsePricingData(data)
+ require.NoError(t, err)
+ pricingSvc.pricingData = pricingData
+
+ for _, tc := range []struct {
+ model string
+ provider string
+ input, output, read float64
+ }{
+ {"gemini-4-argon", "gemini", 2e-6, 10e-6, 0.1e-6},
+ {"gemini-4-argon-high", "gemini", 2e-6, 10e-6, 0.1e-6},
+ {"gemini-4-argon-cyber-permissive", "vertex_ai-language-models", 4e-6, 20e-6, 0.2e-6},
+ } {
+ t.Run(tc.model, func(t *testing.T) {
+ pricing := pricingSvc.GetModelPricing(tc.model)
+ require.NotNil(t, pricing)
+ require.Equal(t, tc.provider, pricing.LiteLLMProvider)
+ require.InDelta(t, tc.input, pricing.InputCostPerToken, 1e-15)
+ require.InDelta(t, tc.output, pricing.OutputCostPerToken, 1e-15)
+ require.InDelta(t, tc.read, pricing.CacheReadInputTokenCost, 1e-15)
+ // Priority 档为标准价的 1.8 倍;单一价档不分提示词长度,显式缓存不可用故无存储价。
+ require.InDelta(t, tc.input*1.8, pricing.InputCostPerTokenPriority, 1e-15)
+ require.InDelta(t, tc.output*1.8, pricing.OutputCostPerTokenPriority, 1e-15)
+ require.InDelta(t, tc.read*1.8, pricing.CacheReadInputTokenCostPriority, 1e-15)
+ require.Zero(t, pricing.LongContextInputTokenThreshold)
+ require.Zero(t, pricing.CacheStorageCostPerTokenPerHour)
})
}
+ require.Contains(t, pricingSvc.ListModelNamesByProvider("gemini"), "gemini-4-argon")
}
func TestDefaultPricingUsesCurrentCodexAutoReviewBaseRates(t *testing.T) {
@@ -1191,3 +1278,42 @@ func TestCalculateCost_ClaudeSonnetCatalogLadderIsDataDriven(t *testing.T) {
require.NoError(t, err)
require.False(t, cost.LongContextBillingApplied, "恰好 200000 不进高档(严格大于)")
}
+
+// Antigravity 的 Claude 5.5 思考档位 ID 只决定推理深度,必须按基础型号计价,
+// 不能落入子串家族匹配(opus-5-5-high → claude-opus-5、sonnet-5-5-high → sonnet-4-5)。
+func TestPricingService_AntigravityClaude55TiersUseBaseModelPricing(t *testing.T) {
+ opus := &LiteLLMModelPricing{InputCostPerToken: 4e-6, OutputCostPerToken: 20e-6}
+ sonnet := &LiteLLMModelPricing{InputCostPerToken: 2e-6, OutputCostPerToken: 10e-6}
+ svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{
+ "claude-opus-5-5": opus,
+ "claude-sonnet-5-5": sonnet,
+ "claude-opus-5": {InputCostPerToken: 5e-6, OutputCostPerToken: 25e-6},
+ "claude-sonnet-4-5": {InputCostPerToken: 3e-6, OutputCostPerToken: 15e-6},
+ }}
+ for _, tier := range []string{"high", "medium", "low"} {
+ require.Same(t, opus, svc.GetModelPricing("claude-opus-5-5-"+tier))
+ require.Same(t, sonnet, svc.GetModelPricing("claude-sonnet-5-5-"+tier))
+ }
+
+ // 价格目录缺基础型号时走家族兜底,同样不能落到 claude-opus-5 / sonnet-4-5。
+ sparse := &PricingService{pricingData: map[string]*LiteLLMModelPricing{
+ "claude-opus-5": {InputCostPerToken: 5e-6, OutputCostPerToken: 25e-6},
+ "claude-sonnet-4-5": {InputCostPerToken: 3e-6, OutputCostPerToken: 15e-6},
+ }}
+ require.Same(t, claudeOpus55FallbackPricing, sparse.GetModelPricing("claude-opus-5-5-high"))
+ require.Same(t, claudeSonnet55FallbackPricing, sparse.GetModelPricing("claude-sonnet-5-5-low"))
+}
+
+func TestBillingService_AntigravityClaude55TierFallbacksUseBaseRates(t *testing.T) {
+ svc := NewBillingService(&config.Config{}, nil)
+ tokens := UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000}
+ for _, tier := range []string{"high", "medium", "low"} {
+ for base, want := range map[string]string{"claude-opus-5-5": "claude-opus-5-5", "claude-sonnet-5-5": "claude-sonnet-5-5"} {
+ got, err := svc.CalculateCost(base+"-"+tier, tokens, 1)
+ require.NoError(t, err)
+ ref, err := svc.CalculateCost(want, tokens, 1)
+ require.NoError(t, err)
+ require.InDelta(t, ref.TotalCost, got.TotalCost, 1e-12, base+"-"+tier)
+ }
+ }
+}
diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go
index b4861c64b..39b1849f9 100644
--- a/backend/internal/service/ratelimit_service.go
+++ b/backend/internal/service/ratelimit_service.go
@@ -310,8 +310,9 @@ func (s *RateLimitService) CheckErrorPolicy(ctx context.Context, account *Accoun
}
if account.IsPoolMode() {
// 池模式只跳过默认账号状态处理;管理员显式配置的临时不可调度规则仍应生效。
- // 401 保留现有认证错误语义,避免改变重复 401 的升级行为。
- if statusCode != http.StatusUnauthorized && s.tryTempUnschedulable(ctx, account, statusCode, responseBody) {
+ // 401 只在非凭据级且命中显式模型级规则时由规则处理,其余保留现有认证错误语义。
+ if tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ctx, nil)) &&
+ s.tryTempUnschedulable(ctx, account, statusCode, responseBody) {
return ErrorPolicyTempUnscheduled
}
return ErrorPolicySkipped
@@ -337,9 +338,10 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc
customErrorCodesEnabled := account.IsCustomErrorCodesEnabled()
// 池模式默认不标记本地账号状态;但管理员显式配置的临时不可调度规则优先。
- // 401 保留现有认证错误语义,不在这里改变池模式的认证处理。
+ // 401 只在非凭据级且命中显式模型级规则时由规则处理,其余保留池模式现有的认证处理。
if account.IsPoolMode() && !customErrorCodesEnabled {
- if statusCode != http.StatusUnauthorized && s.tryTempUnschedulable(ctx, account, statusCode, responseBody) {
+ if tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ctx, nil)) &&
+ s.tryTempUnschedulable(ctx, account, statusCode, responseBody) {
return true
}
slog.Info("pool_mode_error_skipped", "account_id", account.ID, "status_code", statusCode)
@@ -385,9 +387,9 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc
}
}
- // 先尝试临时不可调度规则(401除外)
+ // 先尝试临时不可调度规则(401 仅限非凭据级且命中显式模型级规则)
// 如果匹配成功,直接返回,不执行后续禁用逻辑
- if statusCode != 401 {
+ if tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ctx, requestedModel)) {
if s.tryTempUnschedulable(ctx, account, statusCode, responseBody, firstRequestedModel(requestedModel)) {
return true
}
@@ -2587,6 +2589,62 @@ func firstRequestedModel(requestedModel []string) string {
return strings.TrimSpace(requestedModel[0])
}
+// tempUnschedRulesApply 决定本次错误是否交给临时不可调度规则处理。
+// 401 默认留给认证错误处理;只有首条命中规则按模型级生效时,才由规则只冷却该模型。
+func tempUnschedRulesApply(account *Account, statusCode int, responseBody []byte, modelKey string) bool {
+ if statusCode != http.StatusUnauthorized {
+ return true
+ }
+ matches := matchTempUnschedulableRules(account, statusCode, responseBody)
+ return len(matches) > 0 && tempUnschedHitUsesModelScope(account, matches[0].rule, modelKey, statusCode, responseBody)
+}
+
+// tempUnschedHitUsesModelScope 决定一次命中是否按模型级冷却:凭据级 401 始终按账号处理,
+// 其余由规则作用范围决定。
+func tempUnschedHitUsesModelScope(account *Account, rule TempUnschedulableRule, modelKey string, statusCode int, responseBody []byte) bool {
+ if statusCode == http.StatusUnauthorized && unauthorizedRequiresCredentialHandling(account, responseBody) {
+ return false
+ }
+ return tempUnschedRuleUsesModelScope(rule, modelKey, statusCode)
+}
+
+// unauthorizedRequiresCredentialHandling 识别凭据级 401:OAuth 账号与 Spark 影子
+// (失效缓存、刷新窗口、缺 refresh_token 停用),以及 OpenAI 明确的凭据失效
+// (token_invalidated / token_revoked、{"detail":"Unauthorized"})。
+func unauthorizedRequiresCredentialHandling(account *Account, responseBody []byte) bool {
+ if account == nil {
+ return false
+ }
+ if account.Type == AccountTypeOAuth || account.IsShadow() {
+ return true
+ }
+ if account.Platform != PlatformOpenAI {
+ return false
+ }
+ switch extractUpstreamErrorCode(responseBody) {
+ case "token_invalidated", "token_revoked":
+ return true
+ }
+ return gjson.GetBytes(responseBody, "detail").String() == "Unauthorized"
+}
+
+// tempUnschedRuleUsesModelScope 决定一次命中按模型级冷却还是账号级暂停。
+// 显式 scope 完全由规则决定;scope 为空时模型已知且非 401 走模型级。
+// 模型未知时无法隔离,一律账号级。
+func tempUnschedRuleUsesModelScope(rule TempUnschedulableRule, modelKey string, statusCode int) bool {
+ if strings.TrimSpace(modelKey) == "" {
+ return false
+ }
+ switch rule.Scope {
+ case TempUnschedScopeAccount:
+ return false
+ case TempUnschedScopeModel:
+ return true
+ default:
+ return statusCode != http.StatusUnauthorized
+ }
+}
+
type tempUnschedulableModelContextKey struct{}
func withTempUnschedulableModel(ctx context.Context, requestedModel []string) context.Context {
@@ -2651,10 +2709,17 @@ func (s *RateLimitService) tryTempUnschedulable(ctx context.Context, account *Ac
if !account.IsTempUnschedulableEnabled() {
return false
}
+ matches := matchTempUnschedulableRules(account, statusCode, responseBody)
+ if len(matches) == 0 {
+ return false
+ }
+ modelKey := tempUnschedulableModel(ctx, requestedModel)
// 401 首次命中可临时不可调度(给 token 刷新窗口);
// 若历史上已因 401 进入过临时不可调度,则本次应升级为 error(返回 false 交由默认错误逻辑处理)。
// Antigravity 跳过:其 401 由 applyErrorPolicy 的 temp_unschedulable_rules 自行控制,无需升级逻辑。
- if statusCode == http.StatusUnauthorized && account.Platform != PlatformAntigravity {
+ // 模型级命中只冷却模型、不写账号级状态,不参与升级。
+ if statusCode == http.StatusUnauthorized && account.Platform != PlatformAntigravity &&
+ !tempUnschedHitUsesModelScope(account, matches[0].rule, modelKey, statusCode, responseBody) {
reason := account.TempUnschedulableReason
// 缓存可能没有 reason,从 DB 回退读取
if reason == "" {
@@ -2668,8 +2733,8 @@ func (s *RateLimitService) tryTempUnschedulable(ctx context.Context, account *Ac
return false
}
}
- for _, match := range matchTempUnschedulableRules(account, statusCode, responseBody) {
- if s.triggerTempUnschedulable(ctx, account, match.rule, match.ruleIndex, statusCode, match.matchedKeyword, responseBody, tempUnschedulableModel(ctx, requestedModel)) {
+ for _, match := range matches {
+ if s.triggerTempUnschedulable(ctx, account, match.rule, match.ruleIndex, statusCode, match.matchedKeyword, responseBody, modelKey) {
return true
}
}
@@ -2719,6 +2784,8 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account
now := time.Now()
until := now.Add(time.Duration(rule.DurationMinutes) * time.Minute)
+ modelKey := firstRequestedModel(requestedModel)
+ modelScoped := tempUnschedHitUsesModelScope(account, rule, modelKey, statusCode, responseBody)
state := &TempUnschedState{
UntilUnix: until.Unix(),
@@ -2727,6 +2794,11 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account
MatchedKeyword: matchedKeyword,
RuleIndex: ruleIndex,
ErrorMessage: truncateTempUnschedMessage(responseBody, tempUnschedMessageMaxBytes),
+ Scope: TempUnschedScopeAccount,
+ }
+ if modelScoped {
+ state.Scope = TempUnschedScopeModel
+ state.Model = modelKey
}
reason := ""
@@ -2737,18 +2809,16 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account
reason = strings.TrimSpace(state.ErrorMessage)
}
- // Persist known-model failures under the model key so the scheduler excludes
- // only this (account, model) pair. Authentication and model-unknown failures
- // retain the legacy account-wide temporary-unschedulable behavior below.
- modelKey := firstRequestedModel(requestedModel)
- if modelKey != "" && statusCode != http.StatusUnauthorized {
+ // Persist model-scoped hits under the model key so the scheduler excludes
+ // only this (account, model) pair; every other hit pauses the whole account below.
+ if modelScoped {
if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, modelKey, until, reason); err != nil {
slog.Warn("temp_unsched_model_rate_limit_set_failed", "account_id", account.ID, "model", modelKey, "error", err)
// The rule matched, so fail over the current request even if persistence
// failed; never widen a model-scoped failure into an account-wide block.
return true
}
- slog.Info("account_model_temp_unschedulable", "account_id", account.ID, "model", modelKey, "until", until, "rule_index", ruleIndex, "status_code", statusCode)
+ slog.Info("account_model_temp_unschedulable", "account_id", account.ID, "model", modelKey, "until", until, "rule_index", ruleIndex, "rule_scope", rule.Scope, "status_code", statusCode)
return true
}
@@ -2764,7 +2834,7 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account
}
}
- slog.Info("account_temp_unschedulable", "account_id", account.ID, "until", until, "rule_index", ruleIndex, "status_code", statusCode)
+ slog.Info("account_temp_unschedulable", "account_id", account.ID, "until", until, "rule_index", ruleIndex, "rule_scope", rule.Scope, "status_code", statusCode)
return true
}
diff --git a/backend/internal/service/setting_codex_ticket_test.go b/backend/internal/service/setting_codex_ticket_test.go
index bfa324767..981692f69 100644
--- a/backend/internal/service/setting_codex_ticket_test.go
+++ b/backend/internal/service/setting_codex_ticket_test.go
@@ -65,7 +65,7 @@ func TestRefreshOpenAICodexTickets_DisabledSkipsHarvest(t *testing.T) {
func TestCodexTicketNeverFallsBackToHandEnteredProxy(t *testing.T) {
svc := ticketTestService(t, config.OpenAICodexTicketConfig{HarvestProxyURL: "http://legacy.example.com:8080"}, nil)
- _, _, err := svc.chooseCodexTicketProxy(context.Background(), 41, "gpt-6-astra")
+ _, _, err := svc.chooseCodexTicketProxy(context.Background(), ticketTestAccount(41), "gpt-6-astra")
require.ErrorIs(t, err, ErrCodexTicketNoProxy)
}
diff --git a/backend/internal/service/temp_unsched.go b/backend/internal/service/temp_unsched.go
index 92b7da3f7..67ecb8e70 100644
--- a/backend/internal/service/temp_unsched.go
+++ b/backend/internal/service/temp_unsched.go
@@ -16,6 +16,8 @@ type TempUnschedState struct {
TriggerCount int64 `json:"trigger_count,omitempty"` // 本次触发累计命中次数
TriggerThreshold int `json:"trigger_threshold,omitempty"` // 触发阈值
TriggerWindowMinutes int `json:"trigger_window_minutes,omitempty"` // 计数窗口(分钟)
+ Scope string `json:"scope,omitempty"` // 隔离粒度:account / model
+ Model string `json:"model,omitempty"` // 模型级时被冷却的模型键
}
// TempUnschedCache 临时不可调度缓存接口
diff --git a/backend/internal/service/temp_unsched_scope_test.go b/backend/internal/service/temp_unsched_scope_test.go
new file mode 100644
index 000000000..a586710eb
--- /dev/null
+++ b/backend/internal/service/temp_unsched_scope_test.go
@@ -0,0 +1,493 @@
+//go:build unit
+
+package service
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+type tempUnschedScopeRepoStub struct {
+ modelNotFoundAccountRepoStub
+ tempReasons []string
+ errorCalls int
+}
+
+func (r *tempUnschedScopeRepoStub) SetError(context.Context, int64, string) error {
+ r.errorCalls++
+ return nil
+}
+
+func (r *tempUnschedScopeRepoStub) SetTempUnschedulable(_ context.Context, _ int64, _ time.Time, reason string) error {
+ r.tempCalls++
+ r.tempReasons = append(r.tempReasons, reason)
+ return nil
+}
+
+func newTempUnschedScopeAccount(scope string, extra map[string]any) *Account {
+ rule := map[string]any{
+ "error_code": float64(http.StatusServiceUnavailable),
+ "keywords": []any{"unavailable"},
+ "duration_minutes": float64(10),
+ }
+ if scope != "" {
+ rule["scope"] = scope
+ }
+ for k, v := range extra {
+ rule[k] = v
+ }
+ return &Account{
+ ID: 202,
+ Platform: PlatformOpenAI,
+ Type: AccountTypeAPIKey,
+ Status: StatusActive,
+ Schedulable: true,
+ Credentials: map[string]any{
+ "temp_unschedulable_enabled": true,
+ "temp_unschedulable_rules": []any{rule},
+ },
+ }
+}
+
+var tempUnschedScopeBody = []byte(`{"error":{"message":"upstream unavailable"}}`)
+
+var (
+ tempUnschedScope401Body = []byte(`{"error":{"message":"unauthorized"}}`)
+ tempUnschedScopeRevoked401Body = []byte(`{"error":{"code":"token_revoked","message":"unauthorized"}}`)
+ tempUnschedScopeDetail401Body = []byte(`{"detail":"Unauthorized"}`)
+ tempUnschedScopePrevious401Mark = `{"status_code":401,"until_unix":1735689600}`
+)
+
+func tempUnschedScope401Rule(scope string) map[string]any {
+ rule := map[string]any{
+ "error_code": float64(http.StatusUnauthorized),
+ "keywords": []any{"unauthorized"},
+ "duration_minutes": float64(10),
+ }
+ if scope != "" {
+ rule["scope"] = scope
+ }
+ return rule
+}
+
+func newTempUnschedScope401Account(platform string, scopes ...string) *Account {
+ account := newTempUnschedScopeAccount("", nil)
+ account.Platform = platform
+ rules := make([]any, 0, len(scopes))
+ for _, scope := range scopes {
+ rules = append(rules, tempUnschedScope401Rule(scope))
+ }
+ account.Credentials["temp_unschedulable_rules"] = rules
+ return account
+}
+
+func TestGetTempUnschedulableRules_ParsesScope(t *testing.T) {
+ mk := func(keyword string, scope any) map[string]any {
+ rule := map[string]any{
+ "error_code": float64(http.StatusServiceUnavailable),
+ "keywords": []any{keyword},
+ "duration_minutes": float64(1),
+ }
+ if scope != nil {
+ rule["scope"] = scope
+ }
+ return rule
+ }
+ account := &Account{Credentials: map[string]any{
+ "temp_unschedulable_rules": []any{
+ mk("a", "account"),
+ mk("b", " Model "),
+ mk("c", "whatever"),
+ mk("d", nil),
+ },
+ }}
+
+ rules := account.GetTempUnschedulableRules()
+
+ require.Len(t, rules, 4)
+ require.Equal(t, TempUnschedScopeAccount, rules[0].Scope)
+ require.Equal(t, TempUnschedScopeModel, rules[1].Scope, "大小写与首尾空白应被归一化")
+ require.Empty(t, rules[2].Scope, "未知取值视为未设置")
+ require.Empty(t, rules[3].Scope)
+}
+
+func TestTempUnschedRuleUsesModelScope(t *testing.T) {
+ cases := []struct {
+ name string
+ scope string
+ model string
+ status int
+ want bool
+ }{
+ {"缺省 模型已知 非401 走模型级", "", "gpt-5.4", http.StatusServiceUnavailable, true},
+ {"缺省 401 走账号级", "", "gpt-5.4", http.StatusUnauthorized, false},
+ {"缺省 模型未知 走账号级", "", "", http.StatusServiceUnavailable, false},
+ {"显式账号级 模型已知 仍账号级", TempUnschedScopeAccount, "gpt-5.4", http.StatusServiceUnavailable, false},
+ {"显式模型级 401 仍模型级", TempUnschedScopeModel, "gpt-5.4", http.StatusUnauthorized, true},
+ {"显式模型级 模型未知 兜底账号级", TempUnschedScopeModel, " ", http.StatusServiceUnavailable, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := tempUnschedRuleUsesModelScope(TempUnschedulableRule{Scope: tc.scope}, tc.model, tc.status)
+ require.Equal(t, tc.want, got)
+ })
+ }
+}
+
+func TestHandleTempUnschedulable_ExplicitAccountScopePausesWholeAccountWithKnownModel(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ svc := &RateLimitService{accountRepo: repo}
+ account := newTempUnschedScopeAccount(TempUnschedScopeAccount, nil)
+
+ handled := svc.HandleTempUnschedulable(context.Background(), account, http.StatusServiceUnavailable, tempUnschedScopeBody, "gpt-5.4")
+
+ require.True(t, handled)
+ require.Equal(t, 1, repo.tempCalls)
+ require.Empty(t, repo.modelRateLimitCalls)
+
+ var state TempUnschedState
+ require.NoError(t, json.Unmarshal([]byte(repo.tempReasons[0]), &state))
+ require.Equal(t, TempUnschedScopeAccount, state.Scope)
+ require.Empty(t, state.Model)
+}
+
+func TestCheckErrorPolicy_ExplicitModelScopeKeeps401ModelScoped(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ svc := &RateLimitService{accountRepo: repo}
+ account := newTempUnschedScopeAccount(TempUnschedScopeModel, map[string]any{
+ "error_code": float64(http.StatusUnauthorized),
+ "keywords": []any{"unauthorized"},
+ })
+
+ result := svc.CheckErrorPolicy(context.Background(), account, http.StatusUnauthorized,
+ []byte(`{"error":{"message":"unauthorized"}}`), "gpt-5.4")
+
+ require.Equal(t, ErrorPolicyTempUnscheduled, result)
+ require.Zero(t, repo.tempCalls, "运营人员显式选了模型级,401 也不应连累整个账号")
+ require.Len(t, repo.modelRateLimitCalls, 1)
+ require.Equal(t, "gpt-5.4", repo.modelRateLimitCalls[0].scope)
+
+ var state TempUnschedState
+ require.NoError(t, json.Unmarshal([]byte(repo.modelRateLimitCalls[0].reason), &state))
+ require.Equal(t, TempUnschedScopeModel, state.Scope)
+ require.Equal(t, "gpt-5.4", state.Model)
+ require.Equal(t, http.StatusUnauthorized, state.StatusCode)
+}
+
+func TestHandleTempUnschedulable_ExplicitModelScopeFallsBackToAccountWhenModelUnknown(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ svc := &RateLimitService{accountRepo: repo}
+ account := newTempUnschedScopeAccount(TempUnschedScopeModel, nil)
+
+ handled := svc.HandleTempUnschedulable(context.Background(), account, http.StatusServiceUnavailable, tempUnschedScopeBody)
+
+ require.True(t, handled)
+ require.Equal(t, 1, repo.tempCalls)
+ require.Empty(t, repo.modelRateLimitCalls)
+}
+
+func TestOpenAIFailoverSideEffects_401FollowsTempUnschedScope(t *testing.T) {
+ cases := []struct {
+ name string
+ scopes []string
+ body []byte
+ poolMode bool
+ oauth bool
+ wantModel bool
+ wantTemp bool
+ wantSetError bool
+ wantBlocked bool
+ }{
+ {name: "显式模型级 只冷却模型", scopes: []string{TempUnschedScopeModel}, wantModel: true},
+ {name: "显式模型级 池模式 只冷却模型", scopes: []string{TempUnschedScopeModel}, poolMode: true, wantModel: true},
+ {name: "缺省 走认证错误处理", scopes: []string{""}, wantSetError: true, wantBlocked: true},
+ {name: "显式账号级 走认证错误处理", scopes: []string{TempUnschedScopeAccount}, wantSetError: true, wantBlocked: true},
+ {name: "首条命中为账号级 走认证错误处理", scopes: []string{TempUnschedScopeAccount, TempUnschedScopeModel}, wantSetError: true, wantBlocked: true},
+ {name: "缺省 池模式 保持跳过", scopes: []string{""}, poolMode: true},
+ {name: "显式模型级 token_revoked 走认证错误处理", scopes: []string{TempUnschedScopeModel}, body: tempUnschedScopeRevoked401Body, wantSetError: true, wantBlocked: true},
+ {name: "显式模型级 detail Unauthorized 走认证错误处理", scopes: []string{TempUnschedScopeModel}, body: tempUnschedScopeDetail401Body, wantSetError: true, wantBlocked: true},
+ {name: "显式模型级 token_revoked 池模式 保持跳过", scopes: []string{TempUnschedScopeModel}, body: tempUnschedScopeRevoked401Body, poolMode: true},
+ {name: "显式模型级 OAuth 走刷新窗口", scopes: []string{TempUnschedScopeModel}, oauth: true, wantTemp: true, wantBlocked: true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ gateway := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo, cfg: &config.Config{}}}
+ account := newTempUnschedScope401Account(PlatformOpenAI, tc.scopes...)
+ if tc.poolMode {
+ account.Credentials["pool_mode"] = true
+ }
+ if tc.oauth {
+ account.Type = AccountTypeOAuth
+ account.Credentials["refresh_token"] = "rt"
+ }
+ body := tc.body
+ if body == nil {
+ body = tempUnschedScope401Body
+ }
+
+ require.True(t, gateway.shouldFailoverOpenAIUpstreamResponse(account, http.StatusUnauthorized, "unauthorized", body))
+ gateway.handleFailoverSideEffects(context.Background(), &http.Response{
+ StatusCode: http.StatusUnauthorized,
+ Header: http.Header{},
+ }, account, body, "gpt-5.4")
+
+ require.Equal(t, tc.wantTemp, repo.tempCalls == 1, "SetTempUnschedulable=%d", repo.tempCalls)
+ require.Equal(t, tc.wantSetError, repo.errorCalls == 1, "SetError=%d", repo.errorCalls)
+ require.Equal(t, tc.wantBlocked, gateway.isOpenAIAccountRuntimeBlocked(account))
+ if tc.wantModel {
+ require.Len(t, repo.modelRateLimitCalls, 1)
+ require.Equal(t, "gpt-5.4", repo.modelRateLimitCalls[0].scope)
+ } else {
+ require.Empty(t, repo.modelRateLimitCalls)
+ }
+ })
+ }
+}
+
+func TestHandleUpstreamError_ExplicitModelScope401(t *testing.T) {
+ t.Run("模型已知 只冷却模型", func(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ svc := &RateLimitService{accountRepo: repo}
+ account := newTempUnschedScope401Account(PlatformAnthropic, TempUnschedScopeModel)
+
+ shouldDisable := svc.HandleUpstreamError(context.Background(), account, http.StatusUnauthorized, http.Header{}, tempUnschedScope401Body, "claude-sonnet-4-5")
+
+ require.True(t, shouldDisable)
+ require.Zero(t, repo.errorCalls)
+ require.Zero(t, repo.tempCalls)
+ require.Len(t, repo.modelRateLimitCalls, 1)
+ require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].scope)
+ })
+
+ t.Run("模型未知 按账号级规则走认证错误处理", func(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ svc := &RateLimitService{accountRepo: repo}
+ account := newTempUnschedScope401Account(PlatformAnthropic, TempUnschedScopeModel)
+
+ shouldDisable := svc.HandleUpstreamError(context.Background(), account, http.StatusUnauthorized, http.Header{}, tempUnschedScope401Body)
+
+ require.True(t, shouldDisable)
+ require.Equal(t, 1, repo.errorCalls)
+ require.Empty(t, repo.modelRateLimitCalls)
+ })
+}
+
+func TestCheckErrorPolicy_401FollowsTempUnschedScope(t *testing.T) {
+ cases := []struct {
+ name string
+ scope string
+ body []byte
+ oauth bool
+ previous401 bool
+ want ErrorPolicyResult
+ wantModel bool
+ wantTemp bool
+ }{
+ {name: "显式模型级 不参与重复 401 升级", scope: TempUnschedScopeModel, previous401: true, want: ErrorPolicyTempUnscheduled, wantModel: true},
+ {name: "缺省 第二次 401 升级", previous401: true, want: ErrorPolicyNone},
+ {name: "显式模型级 token_revoked 按账号暂停", scope: TempUnschedScopeModel, body: tempUnschedScopeRevoked401Body, want: ErrorPolicyTempUnscheduled, wantTemp: true},
+ {name: "显式模型级 detail Unauthorized 按账号暂停", scope: TempUnschedScopeModel, body: tempUnschedScopeDetail401Body, want: ErrorPolicyTempUnscheduled, wantTemp: true},
+ {name: "显式模型级 OAuth 按账号暂停", scope: TempUnschedScopeModel, oauth: true, want: ErrorPolicyTempUnscheduled, wantTemp: true},
+ {name: "显式模型级 凭据级第二次 401 升级", scope: TempUnschedScopeModel, body: tempUnschedScopeDetail401Body, previous401: true, want: ErrorPolicyNone},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ svc := &RateLimitService{accountRepo: repo}
+ account := newTempUnschedScope401Account(PlatformOpenAI, tc.scope)
+ if tc.oauth {
+ account.Type = AccountTypeOAuth
+ }
+ if tc.previous401 {
+ account.TempUnschedulableReason = tempUnschedScopePrevious401Mark
+ }
+ body := tc.body
+ if body == nil {
+ body = tempUnschedScope401Body
+ }
+
+ result := svc.CheckErrorPolicy(context.Background(), account, http.StatusUnauthorized, body, "gpt-5.4")
+
+ require.Equal(t, tc.want, result)
+ require.Equal(t, tc.wantTemp, repo.tempCalls == 1, "SetTempUnschedulable=%d", repo.tempCalls)
+ require.Equal(t, tc.wantModel, len(repo.modelRateLimitCalls) == 1)
+ })
+ }
+}
+
+// 计数入口把实际发往上游的模型交给错误处理:显式模型级 401 规则只冷却该模型,不把整号置为 error。
+func TestCountTokensEntries_ExplicitModelScope401OnlyCoolsModel(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ unauthorized := func() *http.Response {
+ return &http.Response{
+ StatusCode: http.StatusUnauthorized,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(`{"error":{"message":"unauthorized"}}`)),
+ }
+ }
+ cfg := &config.Config{
+ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize},
+ Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false, AllowInsecureHTTP: true}},
+ }
+ newContext := func(path string, body []byte) (*gin.Context, *httptest.ResponseRecorder) {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body))
+ return c, rec
+ }
+
+ t.Run("openai count_tokens as anthropic", func(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ upstream := &httpUpstreamRecorder{resp: unauthorized()}
+ svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, rateLimitService: &RateLimitService{accountRepo: repo, cfg: cfg}}
+ account := newTempUnschedScope401Account(PlatformOpenAI, TempUnschedScopeModel)
+ account.Credentials["api_key"] = "sk-test"
+ account.Credentials["base_url"] = "http://upstream.example"
+ account.Concurrency = 1
+ body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}]}`)
+ c, _ := newContext("/v1/messages/count_tokens", body)
+
+ require.Error(t, svc.ForwardCountTokensAsAnthropic(context.Background(), c, account, body, "gpt-5.4"))
+
+ require.Equal(t, "gpt-5.4", gjson.GetBytes(upstream.lastBody, "model").String())
+ require.Zero(t, repo.errorCalls)
+ require.Zero(t, repo.tempCalls)
+ require.Len(t, repo.modelRateLimitCalls, 1)
+ require.Equal(t, "gpt-5.4", repo.modelRateLimitCalls[0].scope)
+ })
+
+ t.Run("openai responses input_tokens", func(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ upstream := &httpUpstreamRecorder{resp: unauthorized()}
+ svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, rateLimitService: &RateLimitService{accountRepo: repo, cfg: cfg}}
+ account := newTempUnschedScope401Account(PlatformOpenAI, TempUnschedScopeModel)
+ account.Credentials["api_key"] = "sk-test"
+ account.Credentials["model_mapping"] = map[string]any{"gpt-5.4": "gpt-5.4-upstream"}
+ account.Concurrency = 1
+ body := []byte(`{"model":"gpt-5.4","input":"hello"}`)
+ c, _ := newContext("/v1/responses/input_tokens", body)
+
+ require.Error(t, svc.ForwardResponsesInputTokens(context.Background(), c, account, body))
+
+ require.NotNil(t, upstream.lastReq)
+ require.Equal(t, "gpt-5.4-upstream", gjson.GetBytes(upstream.lastBody, "model").String())
+ require.Zero(t, repo.errorCalls)
+ require.Zero(t, repo.tempCalls)
+ require.Len(t, repo.modelRateLimitCalls, 1)
+ require.Equal(t, "gpt-5.4-upstream", repo.modelRateLimitCalls[0].scope)
+ })
+
+ for _, passthrough := range []bool{false, true} {
+ name := "anthropic count_tokens"
+ if passthrough {
+ name = "anthropic count_tokens api key passthrough"
+ }
+ t.Run(name, func(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ upstream := &anthropicHTTPUpstreamRecorder{resp: unauthorized()}
+ svc := &GatewayService{
+ cfg: cfg,
+ responseHeaderFilter: compileResponseHeaderFilter(cfg),
+ httpUpstream: upstream,
+ rateLimitService: &RateLimitService{accountRepo: repo, cfg: cfg},
+ }
+ account := newTempUnschedScope401Account(PlatformAnthropic, TempUnschedScopeModel)
+ account.Credentials["api_key"] = "upstream-anthropic-key"
+ account.Credentials["base_url"] = "https://api.anthropic.com"
+ account.Credentials["model_mapping"] = map[string]any{"claude-sonnet-4-5": "claude-sonnet-4-5-upstream"}
+ account.Concurrency = 1
+ if passthrough {
+ account.Extra = map[string]any{"anthropic_passthrough": true}
+ }
+ body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}]}`)
+ c, _ := newContext("/v1/messages/count_tokens", body)
+ parsed := &ParsedRequest{Body: NewRequestBodyRef(body), Model: "claude-sonnet-4-5"}
+
+ require.Error(t, svc.ForwardCountTokens(context.Background(), c, account, parsed))
+
+ require.NotNil(t, upstream.lastReq)
+ require.Equal(t, "claude-sonnet-4-5-upstream", gjson.GetBytes(upstream.lastBody, "model").String())
+ require.Zero(t, repo.errorCalls)
+ require.Zero(t, repo.tempCalls)
+ require.Len(t, repo.modelRateLimitCalls, 1)
+ require.Equal(t, "claude-sonnet-4-5-upstream", repo.modelRateLimitCalls[0].scope)
+ })
+ }
+}
+
+// Bedrock 故障转移入口与重试耗尽入口把实际发往上游的模型交给错误处理:显式模型级规则只冷却该模型。
+func TestAnthropicFailoverEntries_ExplicitModelScopeOnlyCoolsModel(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}
+ newResponse := func(status int, body string) *http.Response {
+ return &http.Response{
+ StatusCode: status,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(body)),
+ }
+ }
+
+ t.Run("bedrock failover 401", func(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ upstream := &anthropicHTTPUpstreamRecorder{resp: newResponse(http.StatusUnauthorized, `{"message":"unauthorized"}`)}
+ svc := &GatewayService{cfg: cfg, httpUpstream: upstream, rateLimitService: &RateLimitService{accountRepo: repo, cfg: cfg}}
+ account := newTempUnschedScope401Account(PlatformAnthropic, TempUnschedScopeModel)
+ account.Type = AccountTypeBedrock
+ account.Status = StatusActive
+ account.Schedulable = true
+ account.Credentials["auth_mode"] = "apikey"
+ account.Credentials["api_key"] = "bedrock-key"
+ body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}]}`)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body))
+ parsed := &ParsedRequest{Body: NewRequestBodyRef(body), Model: "claude-sonnet-4-5"}
+
+ _, err := svc.forwardBedrock(context.Background(), c, account, parsed, time.Now())
+
+ var failover *UpstreamFailoverError
+ require.ErrorAs(t, err, &failover)
+ require.NotNil(t, upstream.lastReq)
+ require.Contains(t, upstream.lastReq.URL.Path, "anthropic.claude-sonnet-4-5-", "上游收到 Bedrock 模型 ID")
+ require.Zero(t, repo.errorCalls)
+ require.Zero(t, repo.tempCalls)
+ require.Len(t, repo.modelRateLimitCalls, 1)
+ // 冷却键必须是调度器查找的键(账号映射后的模型名),而不是 Bedrock 模型 ID。
+ scope := repo.modelRateLimitCalls[0].scope
+ require.Equal(t, "claude-sonnet-4-5", scope)
+ require.True(t, account.IsSchedulableForModelWithContext(context.Background(), "claude-sonnet-4-5"))
+ setAccountModelRateLimitSnapshot(account, scope, time.Now().Add(10*time.Minute), "temp_unschedulable", time.Now())
+ require.False(t, account.IsSchedulableForModelWithContext(context.Background(), "claude-sonnet-4-5"), "调度器按同一个键排除该模型")
+ })
+
+ t.Run("oauth retry exhausted 403", func(t *testing.T) {
+ repo := &tempUnschedScopeRepoStub{}
+ svc := &GatewayService{cfg: cfg, rateLimitService: &RateLimitService{accountRepo: repo, cfg: cfg}}
+ account := newTempUnschedScopeAccount(TempUnschedScopeModel, map[string]any{
+ "error_code": float64(http.StatusForbidden),
+ "keywords": []any{"forbidden"},
+ })
+ account.Platform = PlatformAnthropic
+ account.Type = AccountTypeOAuth
+
+ svc.handleRetryExhaustedSideEffects(context.Background(), newResponse(http.StatusForbidden, `{"error":{"message":"forbidden"}}`), account, "claude-sonnet-4-5")
+
+ require.Zero(t, repo.errorCalls)
+ require.Zero(t, repo.tempCalls)
+ require.Len(t, repo.modelRateLimitCalls, 1)
+ require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].scope)
+ })
+}
diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go
index b980c4358..d2cfed2ed 100644
--- a/backend/internal/service/upstream_models.go
+++ b/backend/internal/service/upstream_models.go
@@ -10,6 +10,7 @@ import (
"net/http"
"net/url"
"sort"
+ "strconv"
"strings"
"time"
@@ -25,6 +26,10 @@ const (
UpstreamModelMetadataExtraKey = "upstream_model_metadata"
UpstreamModelMetadataIncompleteCode = "upstream_model_metadata_incomplete"
UpstreamModelMetadataPartialCode = "upstream_model_metadata_partial"
+
+ vertexPublisherModelsPageSize = 300
+ vertexPublisherModelsMaxPages = 20
+ vertexGooglePublisherModelPrefix = "publishers/google/models/"
)
type UpstreamModelMetadata struct {
@@ -335,7 +340,11 @@ func configuredUpstreamModelsForCapabilitySync(account *Account) []string {
return nil
}
models := make([]string, 0)
- for _, mappedModel := range account.GetModelMapping() {
+ for requestedModel, mappedModel := range account.GetModelMapping() {
+ // Antigravity 运行时补齐的默认透传不是管理员配置的目标,上游目录未列出时不应拉低能力同步完整度。
+ if account.isAntigravityInjectedDefaultPassthrough(requestedModel, mappedModel) {
+ continue
+ }
mappedModel = strings.TrimSpace(mappedModel)
if mappedModel == "" || strings.Contains(mappedModel, "*") {
continue
@@ -733,57 +742,163 @@ func (s *AccountTestService) fetchUpstreamModelList(ctx context.Context, account
}
if account.Platform == PlatformAntigravity && account.Type != AccountTypeAPIKey {
- models, err := s.fetchAntigravityOAuthUpstreamModels(ctx, account)
- return models, nil, err
+ return s.fetchAntigravityOAuthUpstreamModels(ctx, account)
}
if s.httpUpstream == nil {
return nil, nil, newUpstreamModelSyncConfigError("Upstream HTTP client is not configured", nil)
}
+ if account.IsGemini() && account.IsVertexServiceAccount() {
+ models, err := s.fetchVertexGeminiUpstreamModels(ctx, account)
+ return models, nil, err
+ }
+
req, err := s.buildUpstreamModelsRequest(ctx, account)
if err != nil {
return nil, nil, err
}
- proxyURL := upstreamModelsProxyURL(account)
- resp, err := s.doUpstreamModelsRequest(req, proxyURL, account)
+ body, err := s.readUpstreamModelsResponse(req, account)
if err != nil {
- return nil, nil, newUpstreamModelSyncUpstreamError("Failed to request upstream model list", err)
+ return nil, nil, err
+ }
+
+ extractModels := extractUpstreamModelIDs
+ if account.IsGrok() {
+ extractModels = extractGrokUpstreamModelIDs
+ }
+ models, err := extractModels(body)
+ if err != nil {
+ return nil, nil, newUpstreamModelSyncUpstreamError("Upstream model list response was not valid JSON", err)
+ }
+ if len(models) == 0 {
+ return nil, nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil)
+ }
+
+ return models, body, nil
+}
+
+// readUpstreamModelsResponse 发送模型列表请求并读取受限大小的响应体;非 2xx 返回带状态码的同步错误。
+func (s *AccountTestService) readUpstreamModelsResponse(req *http.Request, account *Account) ([]byte, error) {
+ resp, err := s.doUpstreamModelsRequest(req, upstreamModelsProxyURL(account), account)
+ if err != nil {
+ return nil, newUpstreamModelSyncUpstreamError("Failed to request upstream model list", err)
}
defer func() { _ = resp.Body.Close() }()
bodyLimit := resolveModelsListReadLimit(s.cfg)
body, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1))
if err != nil {
- return nil, nil, newUpstreamModelSyncUpstreamError("Failed to read upstream model list", err)
+ return nil, newUpstreamModelSyncUpstreamError("Failed to read upstream model list", err)
}
if int64(len(body)) > bodyLimit {
- return nil, nil, newUpstreamModelSyncUpstreamError("Upstream model list response is too large", fmt.Errorf("response exceeds %d bytes", bodyLimit))
+ return nil, newUpstreamModelSyncUpstreamError("Upstream model list response is too large", fmt.Errorf("response exceeds %d bytes", bodyLimit))
}
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
- return nil, nil, &UpstreamModelSyncError{
+ return nil, &UpstreamModelSyncError{
Kind: UpstreamModelSyncErrorUpstream,
Message: fmt.Sprintf("Upstream model list request failed with HTTP %d", resp.StatusCode),
StatusCode: resp.StatusCode,
Err: fmt.Errorf("upstream model list returned HTTP %d", resp.StatusCode),
}
}
+ return body, nil
+}
- extractModels := extractUpstreamModelIDs
- if account.IsGrok() {
- extractModels = extractGrokUpstreamModelIDs
+// fetchVertexGeminiUpstreamModels 按账号默认区域读取 Vertex 上可用的 Gemini 模型。列表接口不接受 API Key。
+func (s *AccountTestService) fetchVertexGeminiUpstreamModels(ctx context.Context, account *Account) ([]string, error) {
+ if account.IsVertexAPIKey() {
+ return nil, newUpstreamModelSyncUnsupportedError("Vertex API key accounts do not support upstream model listing", nil)
}
- models, err := extractModels(body)
+ if _, err := parseVertexServiceAccountKey(account); err != nil {
+ return nil, newUpstreamModelSyncConfigError("Invalid Vertex service account credentials", err)
+ }
+ location := account.VertexLocation("")
+ if _, err := buildVertexPublisherModelsURL(location, ""); err != nil {
+ return nil, newUpstreamModelSyncConfigError("Invalid Vertex location", err)
+ }
+ if s.geminiTokenProvider == nil {
+ return nil, newUpstreamModelSyncConfigError("Gemini token provider is not configured", nil)
+ }
+ accessToken, err := s.geminiTokenProvider.GetAccessToken(ctx, account)
if err != nil {
- return nil, nil, newUpstreamModelSyncUpstreamError("Upstream model list response was not valid JSON", err)
+ return nil, newUpstreamModelSyncUpstreamError("Failed to get Vertex access token", err)
}
- if len(models) == 0 {
- return nil, nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil)
+ accessToken = strings.TrimSpace(accessToken)
+ if accessToken == "" {
+ return nil, newUpstreamModelSyncConfigError("No Vertex access token is available", nil)
}
- return models, body, nil
+ return listVertexGeminiPublisherModels(location, func(page int, listURL string) ([]byte, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, listURL, nil)
+ if err != nil {
+ return nil, newUpstreamModelSyncConfigError("Invalid Vertex model list URL", err)
+ }
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Authorization", "Bearer "+accessToken)
+
+ body, err := s.readUpstreamModelsResponse(req, account)
+ if err != nil {
+ // 只有首页的 404/405 表示列表端点不可用;翻页途中的失败不触发配置模型回退。
+ var syncErr *UpstreamModelSyncError
+ if page > 0 && errors.As(err, &syncErr) {
+ syncErr.StatusCode = 0
+ }
+ return nil, err
+ }
+ return body, nil
+ })
+}
+
+// listVertexGeminiPublisherModels 按区域分页读取 Google 发布方模型列表,只保留 gemini- 前缀的模型(去重排序)。
+// 区域端点还会列出 Gemma、Veo、AutoML 等非 Gemini 的模型花园条目;global 端点只含 Gemini。
+// fetchPage 负责发送请求并处理非 2xx 响应,返回该页的响应体;它返回的错误原样透出。
+func listVertexGeminiPublisherModels(location string, fetchPage func(page int, listURL string) ([]byte, error)) ([]string, error) {
+ models := make([]string, 0)
+ pageToken := ""
+ for page := 0; page < vertexPublisherModelsMaxPages; page++ {
+ listURL, err := buildVertexPublisherModelsURL(location, pageToken)
+ if err != nil {
+ return nil, newUpstreamModelSyncConfigError("Invalid Vertex location", err)
+ }
+ body, err := fetchPage(page, listURL)
+ if err != nil {
+ return nil, err
+ }
+ var response struct {
+ PublisherModels []struct {
+ Name string `json:"name"`
+ } `json:"publisherModels"`
+ NextPageToken string `json:"nextPageToken"`
+ }
+ if err := json.Unmarshal(body, &response); err != nil {
+ return nil, newUpstreamModelSyncUpstreamError("Upstream model list response was not valid JSON", err)
+ }
+ for _, entry := range response.PublisherModels {
+ name := strings.TrimSpace(entry.Name)
+ if !strings.HasPrefix(name, vertexGooglePublisherModelPrefix) {
+ continue
+ }
+ modelID := strings.TrimPrefix(name, vertexGooglePublisherModelPrefix)
+ if strings.HasPrefix(modelID, "gemini-") && len(modelID) > len("gemini-") {
+ models = append(models, modelID)
+ }
+ }
+
+ pageToken = strings.TrimSpace(response.NextPageToken)
+ if pageToken == "" {
+ if len(models) == 0 {
+ return nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil)
+ }
+ return dedupeAndSortModelIDs(models), nil
+ }
+ }
+ return nil, newUpstreamModelSyncUpstreamError(
+ "Upstream model list pagination did not finish",
+ fmt.Errorf("more than %d pages", vertexPublisherModelsMaxPages),
+ )
}
func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, account *Account) (*http.Request, error) {
@@ -1151,42 +1266,47 @@ func (s *AccountTestService) buildGeminiUpstreamModelsRequest(ctx context.Contex
return req, nil
}
-func (s *AccountTestService) fetchAntigravityOAuthUpstreamModels(ctx context.Context, account *Account) ([]string, error) {
+func (s *AccountTestService) fetchAntigravityOAuthUpstreamModels(ctx context.Context, account *Account) ([]string, []byte, error) {
if s.antigravityGatewayService == nil || s.antigravityGatewayService.GetTokenProvider() == nil {
- return nil, newUpstreamModelSyncConfigError("Antigravity token provider is not configured", nil)
+ return nil, nil, newUpstreamModelSyncConfigError("Antigravity token provider is not configured", nil)
}
accessToken, err := s.antigravityGatewayService.GetTokenProvider().GetAccessToken(ctx, account)
if err != nil {
- return nil, newUpstreamModelSyncUpstreamError("Failed to get Antigravity access token", err)
+ return nil, nil, newUpstreamModelSyncUpstreamError("Failed to get Antigravity access token", err)
}
accessToken = strings.TrimSpace(accessToken)
if accessToken == "" {
- return nil, newUpstreamModelSyncConfigError("No Antigravity access token is available", nil)
+ return nil, nil, newUpstreamModelSyncConfigError("No Antigravity access token is available", nil)
}
client, err := antigravity.NewClient(upstreamModelsProxyURL(account))
if err != nil {
- return nil, newUpstreamModelSyncConfigError("Failed to configure Antigravity client", err)
+ return nil, nil, newUpstreamModelSyncConfigError("Failed to configure Antigravity client", err)
}
- modelsResp, _, err := client.FetchAvailableModels(
+ modelsResp, raw, err := client.FetchAvailableModelsFromURL(
ctx,
+ resolveAntigravityForwardBaseURL(account),
accessToken,
strings.TrimSpace(account.GetCredential("project_id")),
resolveModelsListReadLimit(s.cfg),
)
if err != nil {
- return nil, newUpstreamModelSyncUpstreamError("Failed to fetch Antigravity available models", err)
+ return nil, nil, newUpstreamModelSyncUpstreamError("Failed to fetch Antigravity available models", err)
}
if modelsResp == nil || len(modelsResp.Models) == 0 {
- return nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil)
+ return nil, nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil)
}
models := make([]string, 0, len(modelsResp.Models))
for modelID := range modelsResp.Models {
models = append(models, strings.TrimSpace(modelID))
}
- return dedupeAndSortModelIDs(models), nil
+ body, err := json.Marshal(raw)
+ if err != nil {
+ return nil, nil, newUpstreamModelSyncUpstreamError("Failed to read Antigravity model metadata", err)
+ }
+ return dedupeAndSortModelIDs(models), body, nil
}
func (s *AccountTestService) doUpstreamModelsRequest(req *http.Request, proxyURL string, account *Account) (*http.Response, error) {
@@ -1218,6 +1338,26 @@ func buildOpenAIModelsURL(base string) string {
return buildOpenAIEndpointURL(base, "/v1/models")
}
+// buildVertexPublisherModelsURL 构造 Google 发布方模型列表地址。该接口只有 v1beta1 版本,pageSize 上限 300。
+func buildVertexPublisherModelsURL(location, pageToken string) (string, error) {
+ location = strings.TrimSpace(location)
+ if location == "" {
+ location = vertexDefaultLocation
+ }
+ if !vertexLocationPattern.MatchString(location) {
+ return "", fmt.Errorf("invalid vertex location: %s", location)
+ }
+ host := location + "-aiplatform.googleapis.com"
+ if location == "global" {
+ host = vertexGlobalHost
+ }
+ query := url.Values{"pageSize": []string{strconv.Itoa(vertexPublisherModelsPageSize)}}
+ if pageToken != "" {
+ query.Set("pageToken", pageToken)
+ }
+ return fmt.Sprintf("https://%s/v1beta1/publishers/google/models?%s", host, query.Encode()), nil
+}
+
func buildGeminiModelsURL(base string) string {
normalized := strings.TrimRight(strings.TrimSpace(base), "/")
if strings.HasSuffix(normalized, "/v1beta/models") {
@@ -1262,6 +1402,12 @@ type upstreamModelCapabilityEntry struct {
MaxContextWindow int64 `json:"max_context_window"`
MaxOutputTokens int64 `json:"max_output_tokens"`
Limit modelsDevLimit `json:"limit"`
+ DisplayNameCamel string `json:"displayName"`
+ SupportsImages *bool `json:"supportsImages"`
+ SupportsThinking *bool `json:"supportsThinking"`
+ ThinkingBudget *int64 `json:"thinkingBudget"`
+ MaxTokens int64 `json:"maxTokens"`
+ MaxOutputTokensCamel int64 `json:"maxOutputTokens"`
}
func extractUpstreamModelIDs(body []byte) ([]string, error) {
@@ -1310,12 +1456,33 @@ func extractUpstreamModelCatalog(body []byte, grok bool) ([]string, map[string]U
func extractUpstreamModelRawEntries(body []byte) ([]json.RawMessage, error) {
var response struct {
Data []json.RawMessage `json:"data"`
- Models []json.RawMessage `json:"models"`
+ Models json.RawMessage `json:"models"`
}
if err := json.Unmarshal(body, &response); err == nil && (response.Data != nil || response.Models != nil) {
- entries := make([]json.RawMessage, 0, len(response.Data)+len(response.Models))
- entries = append(entries, response.Data...)
- entries = append(entries, response.Models...)
+ entries := append([]json.RawMessage{}, response.Data...)
+ if len(response.Models) > 0 && string(response.Models) != "null" {
+ var list []json.RawMessage
+ if err := json.Unmarshal(response.Models, &list); err == nil {
+ entries = append(entries, list...)
+ } else {
+ // Antigravity keys its model catalog by the exact generation model ID.
+ var models map[string]map[string]json.RawMessage
+ if err := json.Unmarshal(response.Models, &models); err != nil {
+ return nil, fmt.Errorf("parse upstream model catalog: %w", err)
+ }
+ for modelID, fields := range models {
+ if fields == nil {
+ fields = make(map[string]json.RawMessage)
+ }
+ fields["id"], _ = json.Marshal(modelID)
+ raw, err := json.Marshal(fields)
+ if err != nil {
+ return nil, fmt.Errorf("parse upstream model metadata: %w", err)
+ }
+ entries = append(entries, raw)
+ }
+ }
+ }
return entries, nil
}
var entries []json.RawMessage
@@ -1331,6 +1498,34 @@ func upstreamMetadataFromCapabilityEntry(modelID string, entry upstreamModelCapa
levels = reasoningLevelsFromModelsDevOptions(entry.ReasoningOptions)
}
reasoning := entry.Reasoning
+ if reasoning == nil {
+ reasoning = entry.SupportsThinking
+ }
+ if len(levels) == 0 && entry.SupportsThinking != nil && *entry.SupportsThinking {
+ level := "high"
+ fixedLevel := normalizeReasoningLevel(modelID[strings.LastIndex(modelID, "-")+1:])
+ if fixedLevel != "" && fixedLevel != "none" {
+ level = fixedLevel
+ } else if entry.ThinkingBudget != nil {
+ switch budget := *entry.ThinkingBudget; {
+ case budget < 0:
+ case budget <= geminiThinkingBudgetLowMax:
+ level = "low"
+ case budget <= geminiThinkingBudgetMediumMax:
+ level = "medium"
+ }
+ }
+ if fixedLevel == "" || fixedLevel == "none" {
+ // Bare and tiered AGY models accept configurable budgets. The fetched
+ // thinkingBudget is their default, not the only supported budget.
+ levels = []string{"low", "medium", "high"}
+ if entry.DefaultReasoningLevel == "" {
+ entry.DefaultReasoningLevel = level
+ }
+ } else {
+ levels = []string{level}
+ }
+ }
if reasoning == nil && len(levels) > 0 {
inferred := len(levels) != 1 || levels[0] != "none"
reasoning = &inferred
@@ -1339,6 +1534,13 @@ func upstreamMetadataFromCapabilityEntry(modelID string, entry upstreamModelCapa
if len(modalities) == 0 {
modalities = entry.Modalities.Input
}
+ if len(modalities) == 0 && (entry.SupportsImages != nil || entry.SupportsThinking != nil || entry.MaxTokens > 0) {
+ // AGY models accept text; image input requires an explicit capability.
+ modalities = []string{"text"}
+ if entry.SupportsImages != nil && *entry.SupportsImages {
+ modalities = append(modalities, "image")
+ }
+ }
contextWindow := entry.ContextWindow
if contextWindow <= 0 {
contextWindow = entry.MaxContextWindow
@@ -1346,15 +1548,24 @@ func upstreamMetadataFromCapabilityEntry(modelID string, entry upstreamModelCapa
if contextWindow <= 0 {
contextWindow = entry.Limit.Context
}
+ if contextWindow <= 0 {
+ contextWindow = entry.MaxTokens
+ }
maxOutputTokens := entry.MaxOutputTokens
if maxOutputTokens <= 0 {
maxOutputTokens = entry.Limit.Output
}
+ if maxOutputTokens <= 0 {
+ maxOutputTokens = entry.MaxOutputTokensCamel
+ }
defaultReasoningLevel := normalizeReasoningLevel(entry.DefaultReasoningLevel)
if defaultReasoningLevel == "" && len(levels) > 0 {
defaultReasoningLevel = levels[0]
}
displayName := strings.TrimSpace(entry.DisplayName)
+ if displayName == "" {
+ displayName = strings.TrimSpace(entry.DisplayNameCamel)
+ }
if displayName == "" && strings.TrimSpace(entry.Name) != "" && strings.TrimSpace(entry.Name) != modelID {
displayName = strings.TrimSpace(entry.Name)
}
diff --git a/backend/internal/service/upstream_models_antigravity_test.go b/backend/internal/service/upstream_models_antigravity_test.go
new file mode 100644
index 000000000..e1f0846fe
--- /dev/null
+++ b/backend/internal/service/upstream_models_antigravity_test.go
@@ -0,0 +1,245 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/antigravity"
+ "github.com/stretchr/testify/require"
+)
+
+func antigravityModelSyncAccount(plan string) *Account {
+ return &Account{
+ ID: 121, Platform: PlatformAntigravity, Type: AccountTypeOAuth,
+ Credentials: map[string]any{
+ "access_token": "model-sync-test-token",
+ "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339),
+ "project_id": "model-sync-test-project",
+ "plan_type": plan,
+ },
+ }
+}
+
+func antigravityModelSyncService() *AccountTestService {
+ return &AccountTestService{
+ antigravityGatewayService: &AntigravityGatewayService{tokenProvider: &AntigravityTokenProvider{}},
+ cfg: upstreamModelSyncTestConfig(),
+ }
+}
+
+func withAntigravityModelSyncEndpoints(t *testing.T, production, daily string) {
+ t.Helper()
+ previous := antigravity.BaseURLs
+ antigravity.BaseURLs = []string{production, daily}
+ t.Cleanup(func() { antigravity.BaseURLs = previous })
+}
+
+func TestFetchUpstreamSupportedModelsAntigravityUsesGenerationEndpoint(t *testing.T) {
+ t.Setenv(antigravityForwardBaseURLEnv, "")
+ production := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.WriteString(w, `{"models":{"gemini-3.7-flash-high":{}}}`)
+ }))
+ defer production.Close()
+ daily := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.WriteString(w, `{"models":{"gemini-3.8-flash-high":{}}}`)
+ }))
+ defer daily.Close()
+ withAntigravityModelSyncEndpoints(t, production.URL, daily.URL)
+
+ for _, tc := range []struct {
+ name string
+ plan string
+ mode string
+ model string
+ }{
+ {name: "Ultra daily", plan: "Ultra", model: "gemini-3.8-flash-high"},
+ {name: "Pro daily", plan: "Pro", model: "gemini-3.8-flash-high"},
+ {name: "Free production", plan: "Free", model: "gemini-3.7-flash-high"},
+ {name: "explicit production", plan: "Ultra", mode: "prod", model: "gemini-3.7-flash-high"},
+ {name: "explicit daily", plan: "Free", mode: "daily", model: "gemini-3.8-flash-high"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv(antigravityForwardBaseURLEnv, tc.mode)
+ models, err := antigravityModelSyncService().FetchUpstreamSupportedModels(context.Background(), antigravityModelSyncAccount(tc.plan))
+ require.NoError(t, err)
+ require.Equal(t, []string{tc.model}, models, "catalog must come from the endpoint used for generation")
+ })
+ }
+}
+
+func TestSyncUpstreamModelCatalogAntigravityPreservesDirectCapabilities(t *testing.T) {
+ t.Setenv(antigravityForwardBaseURLEnv, "")
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.WriteString(w, `{"models":{"gemini-3.8-flash-high":{
+ "displayName":"Gemini 3.8 Flash High",
+ "supportsImages":true,"supportsThinking":true,"thinkingBudget":24576,
+ "maxTokens":1048576,"maxOutputTokens":65536
+ }}}`)
+ }))
+ defer server.Close()
+ withAntigravityModelSyncEndpoints(t, server.URL, server.URL)
+ account := antigravityModelSyncAccount("Ultra")
+ account.Credentials["model_mapping"] = map[string]any{"gemini-3.8-flash-high": "gemini-3.8-flash-high"}
+ registry := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusBadGateway, Body: io.NopCloser(strings.NewReader(`{"error":"registry unavailable"}`))}}
+ svc := antigravityModelSyncService()
+ svc.accountRepo = &upstreamModelMetadataRepoStub{}
+ svc.httpUpstream = registry
+
+ catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account)
+ require.NoError(t, err)
+ require.Equal(t, []string{"gemini-3.8-flash-high"}, catalog.Models)
+ require.Contains(t, catalog.Metadata, "gemini-3.8-flash-high")
+ metadata := catalog.Metadata["gemini-3.8-flash-high"]
+ require.Equal(t, "Gemini 3.8 Flash High", metadata.DisplayName)
+ require.NotNil(t, metadata.Reasoning)
+ require.True(t, *metadata.Reasoning)
+ require.Equal(t, []string{"high"}, metadata.SupportedReasoningLevels, "fixed variant must advertise only its own reasoning level")
+ require.Equal(t, "high", metadata.DefaultReasoningLevel)
+ require.Equal(t, []string{"text", "image"}, metadata.InputModalities)
+ require.Equal(t, int64(1048576), metadata.ContextWindow)
+ require.Equal(t, int64(65536), metadata.MaxOutputTokens)
+ require.Empty(t, registry.requests, "complete upstream capabilities must not need guessed registry capabilities")
+ require.Empty(t, catalog.Warnings)
+ snapshot := account.GetUpstreamModelMetadataSnapshot()
+ require.NotNil(t, snapshot)
+ require.Equal(t, "upstream", snapshot.Source)
+ serializedMetadata, err := json.Marshal(metadata)
+ require.NoError(t, err)
+ serializedSnapshotEntry, err := json.Marshal(snapshot.Models["gemini-3.8-flash-high"])
+ require.NoError(t, err)
+ require.JSONEq(t, string(serializedMetadata), string(serializedSnapshotEntry))
+}
+
+func TestSyncUpstreamModelCatalogAntigravityTieredReasoning(t *testing.T) {
+ t.Setenv(antigravityForwardBaseURLEnv, "")
+ for _, tc := range []struct {
+ budget string
+ defaultLevel string
+ }{
+ {budget: "-1", defaultLevel: "high"},
+ {budget: "0", defaultLevel: "low"},
+ {budget: "1024", defaultLevel: "low"},
+ {budget: "1025", defaultLevel: "medium"},
+ {budget: "4000", defaultLevel: "medium"},
+ {budget: "8192", defaultLevel: "medium"},
+ {budget: "8193", defaultLevel: "high"},
+ {defaultLevel: "high"},
+ } {
+ t.Run("budget="+tc.budget, func(t *testing.T) {
+ budgetJSON := ""
+ if tc.budget != "" {
+ budgetJSON = `"thinkingBudget":` + tc.budget + ","
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.WriteString(w, fmt.Sprintf(`{"models":{"gemini-3.8-flash-tiered":{
+ "supportsImages":false,"supportsThinking":true,%s
+ "maxTokens":1048576,"maxOutputTokens":65536
+ }}}`, budgetJSON))
+ }))
+ defer server.Close()
+ withAntigravityModelSyncEndpoints(t, server.URL, server.URL)
+ account := antigravityModelSyncAccount("Ultra")
+ account.Credentials["model_mapping"] = map[string]any{"gemini-3.8-flash-tiered": "gemini-3.8-flash-tiered"}
+ svc := antigravityModelSyncService()
+ svc.accountRepo = &upstreamModelMetadataRepoStub{}
+
+ catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account)
+ require.NoError(t, err)
+ metadata := catalog.Metadata["gemini-3.8-flash-tiered"]
+ require.Equal(t, []string{"low", "medium", "high"}, metadata.SupportedReasoningLevels)
+ require.Equal(t, tc.defaultLevel, metadata.DefaultReasoningLevel, "tiered default must follow its upstream thinking budget")
+ require.Equal(t, []string{"text"}, metadata.InputModalities)
+ })
+ }
+}
+
+func TestSyncUpstreamModelCatalogAntigravityMissingImageSupportIsTextOnly(t *testing.T) {
+ t.Setenv(antigravityForwardBaseURLEnv, "")
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.WriteString(w, `{"models":{"claude-plain":{
+ "supportsThinking":false,"maxTokens":200000,"maxOutputTokens":64000
+ }}}`)
+ }))
+ defer server.Close()
+ withAntigravityModelSyncEndpoints(t, server.URL, server.URL)
+ account := antigravityModelSyncAccount("Ultra")
+ account.Credentials["model_mapping"] = map[string]any{"claude-plain": "claude-plain"}
+ registry := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusBadGateway, Body: io.NopCloser(strings.NewReader(`{"error":"registry unavailable"}`))}}
+ svc := antigravityModelSyncService()
+ svc.accountRepo = &upstreamModelMetadataRepoStub{}
+ svc.httpUpstream = registry
+
+ catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account)
+ require.NoError(t, err)
+ metadata := catalog.Metadata["claude-plain"]
+ require.Equal(t, []string{"text"}, metadata.InputModalities, "missing image declaration must not advertise image input")
+ require.NotNil(t, metadata.Reasoning)
+ require.False(t, *metadata.Reasoning)
+ require.Empty(t, metadata.SupportedReasoningLevels)
+ require.Empty(t, registry.requests)
+}
+
+func TestSyncUpstreamModelCatalogAntigravityBudgetReasoningLevels(t *testing.T) {
+ t.Setenv(antigravityForwardBaseURLEnv, "")
+ for _, tc := range []struct {
+ model string
+ budget int
+ defaultLevel string
+ levels []string
+ }{
+ {model: "gemini-2.5-flash", budget: -1, defaultLevel: "high", levels: []string{"low", "medium", "high"}},
+ {model: "gemini-2.5-flash-lite", budget: 4000, defaultLevel: "medium", levels: []string{"low", "medium", "high"}},
+ {model: "gemini-3.8-flash-low", budget: -1, defaultLevel: "low", levels: []string{"low"}},
+ {model: "gemini-3.8-flash-medium", budget: 1000, defaultLevel: "medium", levels: []string{"medium"}},
+ {model: "gemini-3.8-flash-high", budget: 4000, defaultLevel: "high", levels: []string{"high"}},
+ } {
+ t.Run(tc.model, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.WriteString(w, fmt.Sprintf(`{"models":{%q:{
+ "supportsImages":true,"supportsThinking":true,"thinkingBudget":%d,
+ "maxTokens":1048576,"maxOutputTokens":65536
+ }}}`, tc.model, tc.budget))
+ }))
+ defer server.Close()
+ withAntigravityModelSyncEndpoints(t, server.URL, server.URL)
+ account := antigravityModelSyncAccount("Ultra")
+ account.Credentials["model_mapping"] = map[string]any{tc.model: tc.model}
+ svc := antigravityModelSyncService()
+ svc.accountRepo = &upstreamModelMetadataRepoStub{}
+
+ catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account)
+ require.NoError(t, err)
+ metadata := catalog.Metadata[tc.model]
+ require.Equal(t, tc.levels, metadata.SupportedReasoningLevels, "default budget must not restrict configurable models to one reasoning level")
+ require.Equal(t, tc.defaultLevel, metadata.DefaultReasoningLevel)
+ require.Empty(t, catalog.Warnings)
+ })
+ }
+}
+
+func TestConfiguredUpstreamModelsForCapabilitySyncSkipsInjectedAntigravityPassthroughs(t *testing.T) {
+ account := &Account{
+ Platform: PlatformAntigravity,
+ Credentials: map[string]any{"model_mapping": map[string]any{
+ "gemini-3.8-flash-high": "gemini-3.8-flash-high",
+ "gemini-3.8-flash": "gemini-3.8-flash-tiered",
+ "custom-alias": "gemini-3.6-flash-low",
+ }},
+ }
+ // 运行时补齐的默认透传仍可调用(存量账号兼容)。
+ require.True(t, account.IsModelSupported("gemini-3.7-flash-medium"))
+
+ got := configuredUpstreamModelsForCapabilitySync(account)
+ require.ElementsMatch(t, []string{"gemini-3.8-flash-high", "gemini-3.8-flash-tiered", "gemini-3.6-flash-low"}, got)
+
+ // 空映射走默认目录,其中的同名条目不是运行时补齐。
+ empty := &Account{Platform: PlatformAntigravity, Credentials: map[string]any{}}
+ require.Contains(t, configuredUpstreamModelsForCapabilitySync(empty), "gemini-3.8-flash-low")
+}
diff --git a/backend/internal/service/upstream_models_vertex_test.go b/backend/internal/service/upstream_models_vertex_test.go
new file mode 100644
index 000000000..bd4678614
--- /dev/null
+++ b/backend/internal/service/upstream_models_vertex_test.go
@@ -0,0 +1,276 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+type vertexModelsTokenCacheStub struct {
+ token string
+ calls int
+}
+
+func (c *vertexModelsTokenCacheStub) GetAccessToken(context.Context, string) (string, error) {
+ c.calls++
+ if c.token == "" {
+ return "", errors.New("missing token")
+ }
+ return c.token, nil
+}
+
+func (c *vertexModelsTokenCacheStub) SetAccessToken(context.Context, string, string, time.Duration) error {
+ return nil
+}
+
+func (c *vertexModelsTokenCacheStub) DeleteAccessToken(context.Context, string) error {
+ return nil
+}
+
+func (c *vertexModelsTokenCacheStub) AcquireRefreshLock(context.Context, string, time.Duration) (bool, error) {
+ return false, nil
+}
+
+func (c *vertexModelsTokenCacheStub) ReleaseRefreshLock(context.Context, string) error {
+ return nil
+}
+
+func vertexModelSyncTestAccount(credentials map[string]any) *Account {
+ merged := map[string]any{
+ "service_account_json": map[string]any{
+ "type": "service_account",
+ "project_id": "proj",
+ "private_key": "-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----\n",
+ "client_email": "svc@proj.iam.gserviceaccount.com",
+ },
+ }
+ for key, value := range credentials {
+ merged[key] = value
+ }
+ return &Account{
+ ID: 173,
+ Platform: PlatformGemini,
+ Type: AccountTypeServiceAccount,
+ Credentials: merged,
+ }
+}
+
+func vertexModelSyncTestService(upstream *httpUpstreamRecorder) *AccountTestService {
+ return &AccountTestService{
+ httpUpstream: upstream,
+ cfg: upstreamModelSyncTestConfig(),
+ geminiTokenProvider: NewGeminiTokenProvider(nil, &vertexModelsTokenCacheStub{token: "ya29.vertex-token"}, nil),
+ }
+}
+
+func vertexModelsJSONResponse(status int, body string) *http.Response {
+ return &http.Response{
+ StatusCode: status,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(body)),
+ }
+}
+
+func TestBuildVertexPublisherModelsURL(t *testing.T) {
+ t.Parallel()
+
+ u, err := buildVertexPublisherModelsURL("global", "")
+ require.NoError(t, err)
+ require.Equal(t, "https://aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", u)
+
+ u, err = buildVertexPublisherModelsURL("us-central1", "next/page+token")
+ require.NoError(t, err)
+ require.Equal(t, "https://us-central1-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300&pageToken=next%2Fpage%2Btoken", u)
+
+ u, err = buildVertexPublisherModelsURL("", "")
+ require.NoError(t, err)
+ require.Equal(t, "https://us-central1-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", u)
+
+ _, err = buildVertexPublisherModelsURL("evil.com/x", "")
+ require.Error(t, err)
+}
+
+// Scenario: Vertex SA 账号按账号区域分页读取发布方模型列表,只保留 gemini- 前缀模型。
+func TestFetchUpstreamSupportedModelsVertexServiceAccountPaginatesAndKeepsGemini(t *testing.T) {
+ t.Parallel()
+
+ upstream := &httpUpstreamRecorder{responses: []*http.Response{
+ vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[
+ {"name":"publishers/google/models/gemini-3.8-flash"},
+ {"name":"publishers/google/models/gemma4"},
+ {"name":"publishers/google/models/veo-3.1-generate-001"}
+ ],"nextPageToken":"page-2"}`),
+ vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[
+ {"name":" publishers/google/models/gemini-2.5-flash "},
+ {"name":"publishers/google/models/gemini-3.8-flash"},
+ {"name":"gemini-without-publisher-prefix"},
+ {"name":"publishers/anthropic/models/gemini-other-publisher"},
+ {"name":"publishers/google/models/gemini-"}
+ ]}`),
+ }}
+ svc := vertexModelSyncTestService(upstream)
+
+ models, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(map[string]any{
+ "location": "europe-west4",
+ }))
+ require.NoError(t, err)
+ require.Equal(t, []string{"gemini-2.5-flash", "gemini-3.8-flash"}, models)
+
+ require.Len(t, upstream.requests, 2)
+ require.Equal(t, "https://europe-west4-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", upstream.requests[0].URL.String())
+ require.Equal(t, "https://europe-west4-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300&pageToken=page-2", upstream.requests[1].URL.String())
+ for _, req := range upstream.requests {
+ require.Equal(t, http.MethodGet, req.Method)
+ require.Equal(t, "Bearer ya29.vertex-token", req.Header.Get("Authorization"))
+ }
+}
+
+func TestFetchUpstreamSupportedModelsVertexUpstreamErrorKeepsStatus(t *testing.T) {
+ t.Parallel()
+
+ upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusForbidden, `{"error":{"code":403,"status":"PERMISSION_DENIED"}}`)}
+ svc := vertexModelSyncTestService(upstream)
+
+ _, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(map[string]any{"location": "global"}))
+ var syncErr *UpstreamModelSyncError
+ require.ErrorAs(t, err, &syncErr)
+ require.Equal(t, UpstreamModelSyncErrorUpstream, syncErr.Kind)
+ require.Equal(t, http.StatusForbidden, syncErr.StatusCode)
+ require.Equal(t, "https://aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", upstream.lastReq.URL.String())
+}
+
+func TestFetchUpstreamSupportedModelsVertexWithoutGeminiModelsFails(t *testing.T) {
+ t.Parallel()
+
+ upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemma4"}]}`)}
+ svc := vertexModelSyncTestService(upstream)
+
+ _, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(nil))
+ var syncErr *UpstreamModelSyncError
+ require.ErrorAs(t, err, &syncErr)
+ require.Equal(t, UpstreamModelSyncErrorUpstream, syncErr.Kind)
+ require.Equal(t, "Upstream returned no supported models", syncErr.SafeMessage())
+}
+
+func TestFetchUpstreamSupportedModelsVertexStopsEndlessPagination(t *testing.T) {
+ t.Parallel()
+
+ responses := make([]*http.Response, 0, vertexPublisherModelsMaxPages)
+ for i := 0; i < vertexPublisherModelsMaxPages; i++ {
+ responses = append(responses, vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-3.8-flash"}],"nextPageToken":"again"}`))
+ }
+ upstream := &httpUpstreamRecorder{responses: responses}
+ svc := vertexModelSyncTestService(upstream)
+
+ _, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(nil))
+ var syncErr *UpstreamModelSyncError
+ require.ErrorAs(t, err, &syncErr)
+ require.Equal(t, "Upstream model list pagination did not finish", syncErr.SafeMessage())
+ require.Len(t, upstream.requests, vertexPublisherModelsMaxPages)
+}
+
+func TestFetchUpstreamSupportedModelsVertexAPIKeyUnsupported(t *testing.T) {
+ t.Parallel()
+
+ upstream := &httpUpstreamRecorder{}
+ svc := vertexModelSyncTestService(upstream)
+ account := &Account{
+ ID: 174,
+ Platform: PlatformGemini,
+ Type: AccountTypeServiceAccount,
+ Credentials: map[string]any{
+ "auth_mode": "apikey",
+ "api_key": "AQ.test-key",
+ },
+ }
+
+ _, err := svc.FetchUpstreamSupportedModels(context.Background(), account)
+ var syncErr *UpstreamModelSyncError
+ require.ErrorAs(t, err, &syncErr)
+ require.Equal(t, UpstreamModelSyncErrorUnsupported, syncErr.Kind)
+ require.Empty(t, upstream.requests)
+}
+
+func TestFetchUpstreamSupportedModelsVertexInvalidCredentialsIsConfigError(t *testing.T) {
+ t.Parallel()
+
+ cache := &vertexModelsTokenCacheStub{token: "ya29.vertex-token"}
+ upstream := &httpUpstreamRecorder{}
+ svc := &AccountTestService{
+ httpUpstream: upstream,
+ cfg: upstreamModelSyncTestConfig(),
+ geminiTokenProvider: NewGeminiTokenProvider(nil, cache, nil),
+ }
+ account := &Account{
+ ID: 175,
+ Platform: PlatformGemini,
+ Type: AccountTypeServiceAccount,
+ Credentials: map[string]any{"api_key": "not-a-service-account"},
+ }
+
+ _, err := svc.FetchUpstreamSupportedModels(context.Background(), account)
+ var syncErr *UpstreamModelSyncError
+ require.ErrorAs(t, err, &syncErr)
+ require.Equal(t, UpstreamModelSyncErrorConfiguration, syncErr.Kind)
+ require.Equal(t, "Invalid Vertex service account credentials", syncErr.SafeMessage())
+ require.Zero(t, cache.calls)
+ require.Empty(t, upstream.requests)
+}
+
+func TestFetchUpstreamSupportedModelsVertexInvalidLocationSkipsTokenExchange(t *testing.T) {
+ t.Parallel()
+
+ cache := &vertexModelsTokenCacheStub{token: "ya29.vertex-token"}
+ upstream := &httpUpstreamRecorder{}
+ svc := &AccountTestService{
+ httpUpstream: upstream,
+ cfg: upstreamModelSyncTestConfig(),
+ geminiTokenProvider: NewGeminiTokenProvider(nil, cache, nil),
+ }
+
+ _, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(map[string]any{
+ "location": "us-central1.evil.com",
+ }))
+ var syncErr *UpstreamModelSyncError
+ require.ErrorAs(t, err, &syncErr)
+ require.Equal(t, UpstreamModelSyncErrorConfiguration, syncErr.Kind)
+ require.Equal(t, "Invalid Vertex location", syncErr.SafeMessage())
+ require.Zero(t, cache.calls)
+ require.Empty(t, upstream.requests)
+}
+
+// Scenario: 翻页途中的 404 不能被当成列表端点不可用而回退到配置模型。
+func TestSyncUpstreamModelCatalogVertexMidPagination404DoesNotFallback(t *testing.T) {
+ t.Parallel()
+
+ upstream := &httpUpstreamRecorder{responses: []*http.Response{
+ vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-a"}],"nextPageToken":"page-2"}`),
+ vertexModelsJSONResponse(http.StatusNotFound, `{"error":{"code":404}}`),
+ }}
+ svc := vertexModelSyncTestService(upstream)
+
+ _, err := svc.SyncUpstreamModelCatalog(context.Background(), vertexModelSyncTestAccount(map[string]any{
+ "model_mapping": map[string]any{"x": "gemini-mapped"},
+ }))
+ var syncErr *UpstreamModelSyncError
+ require.ErrorAs(t, err, &syncErr)
+ require.Equal(t, UpstreamModelSyncErrorUpstream, syncErr.Kind)
+ require.Zero(t, syncErr.StatusCode)
+ require.Len(t, upstream.requests, 2)
+}
+
+func TestFetchUpstreamSupportedModelsVertexFirstPage404KeepsStatus(t *testing.T) {
+ t.Parallel()
+
+ upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusNotFound, `{"error":{"code":404}}`)}
+ svc := vertexModelSyncTestService(upstream)
+
+ _, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(nil))
+ require.True(t, upstreamModelListEndpointUnsupported(err))
+}
diff --git a/backend/internal/service/vertex_service_account.go b/backend/internal/service/vertex_service_account.go
index 085b60904..6a48e6057 100644
--- a/backend/internal/service/vertex_service_account.go
+++ b/backend/internal/service/vertex_service_account.go
@@ -29,6 +29,8 @@ const (
vertexServiceAccountCacheSkew = 5 * time.Minute
vertexLockWaitTime = 200 * time.Millisecond
vertexAnthropicVersion = "vertex-2023-10-16"
+ vertexGlobalHost = "aiplatform.googleapis.com"
+ vertexAuthModeAPIKey = "apikey"
)
var (
@@ -37,6 +39,9 @@ var (
vertexAnthropicAlreadyDatedIDPattern = regexp.MustCompile(`^.+@[0-9]{8}$`)
)
+// vertexServiceAccountTokenURL 是换取 SA access token 的端点,测试中替换为本地服务。
+var vertexServiceAccountTokenURL = vertexDefaultTokenURL
+
type vertexServiceAccountKey struct {
Type string `json:"type"`
ProjectID string `json:"project_id"`
@@ -58,6 +63,13 @@ func (a *Account) IsVertexServiceAccount() bool {
return a != nil && a.Type == AccountTypeServiceAccount
}
+// IsVertexAPIKey 判断 Gemini 平台的 Vertex 账号是否使用 API Key 认证(credentials.auth_mode=apikey)。
+// Anthropic 平台的 Vertex 账号只支持 Service Account JSON。
+func (a *Account) IsVertexAPIKey() bool {
+ return a.IsVertexServiceAccount() && a.Platform == PlatformGemini &&
+ strings.TrimSpace(a.GetCredential("auth_mode")) == vertexAuthModeAPIKey
+}
+
func (a *Account) VertexProjectID() string {
if a == nil {
return ""
@@ -129,7 +141,7 @@ func parseVertexServiceAccountJSON(raw []byte) (*vertexServiceAccountKey, error)
return nil, errors.New("service account json missing project_id")
}
// Always use the well-known Google token endpoint to prevent SSRF via crafted token_uri.
- key.TokenURI = vertexDefaultTokenURL
+ key.TokenURI = vertexServiceAccountTokenURL
return &key, nil
}
@@ -268,7 +280,12 @@ func exchangeVertexServiceAccountToken(ctx context.Context, key *vertexServiceAc
if msg == "" {
msg = string(bytes.TrimSpace(body))
}
- return "", 0, fmt.Errorf("service account token request returned %d: %s", resp.StatusCode, msg)
+ return "", 0, &vertexTokenRequestError{
+ StatusCode: resp.StatusCode,
+ Code: strings.TrimSpace(parsed.Error),
+ Description: strings.TrimSpace(parsed.ErrorDesc),
+ Message: msg,
+ }
}
if strings.TrimSpace(parsed.AccessToken) == "" {
return "", 0, errors.New("service account token response missing access_token")
@@ -283,6 +300,90 @@ func exchangeVertexServiceAccountToken(ctx context.Context, key *vertexServiceAc
return parsed.AccessToken, ttl, nil
}
+// vertexTokenRequestError 是 token 端点对换取 SA access token 请求返回的非 2xx 响应。
+type vertexTokenRequestError struct {
+ StatusCode int
+ Code string // 响应的 error 字段,如 invalid_grant
+ Description string // 响应的 error_description 字段
+ Message string
+}
+
+func (e *vertexTokenRequestError) Error() string {
+ return fmt.Sprintf("service account token request returned %d: %s", e.StatusCode, e.Message)
+}
+
+// vertexServiceAccountNotFoundError 识别 SA 已不存在:token 端点返回
+// 400 {"error":"invalid_grant","error_description":"Invalid grant: account not found"}。
+// 该凭据再也换不到 token,账号需要人工更换凭据。
+func vertexServiceAccountNotFoundError(err error) (*vertexTokenRequestError, bool) {
+ var tokenErr *vertexTokenRequestError
+ if !errors.As(err, &tokenErr) {
+ return nil, false
+ }
+ if tokenErr.StatusCode != http.StatusBadRequest || tokenErr.Code != "invalid_grant" ||
+ !strings.Contains(strings.ToLower(tokenErr.Description), "account not found") {
+ return nil, false
+ }
+ return tokenErr, true
+}
+
+// buildVertexGeminiAccountURL 按账号构造 Vertex Gemini 请求地址:未配置 project_id 的 API Key 账号
+// 走 Express mode 全局端点,其余账号走项目级端点。
+func buildVertexGeminiAccountURL(account *Account, model, action string, stream bool) (string, error) {
+ if account.IsVertexAPIKey() && account.VertexProjectID() == "" {
+ return buildVertexGeminiExpressURL(model, action, stream)
+ }
+ return buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(model), model, action, stream)
+}
+
+// buildVertexGeminiExpressURL 构造不带项目与区域的全局端点地址,仅 API Key 认证可用。
+func buildVertexGeminiExpressURL(model, action string, stream bool) (string, error) {
+ model = strings.TrimSpace(model)
+ action = strings.TrimSpace(action)
+ if model == "" {
+ return "", errors.New("vertex model is required")
+ }
+ if err := validateVertexGeminiAction(action); err != nil {
+ return "", err
+ }
+ u := fmt.Sprintf("https://%s/v1/publishers/google/models/%s:%s", vertexGlobalHost, url.PathEscape(model), action)
+ if stream {
+ u += "?alt=sse"
+ }
+ return u, nil
+}
+
+func validateVertexGeminiAction(action string) error {
+ switch action {
+ case "generateContent", "streamGenerateContent", "countTokens":
+ return nil
+ default:
+ return fmt.Errorf("unsupported vertex gemini action: %s", action)
+ }
+}
+
+// setVertexGeminiAuth 给 Vertex Gemini 请求设置认证头:API Key 账号用 x-goog-api-key,
+// Service Account JSON 账号用换取的 Bearer access token。
+func setVertexGeminiAuth(ctx context.Context, req *http.Request, account *Account, tokenProvider *GeminiTokenProvider) error {
+ if account.IsVertexAPIKey() {
+ apiKey := strings.TrimSpace(account.GetCredential("api_key"))
+ if apiKey == "" {
+ return errors.New("vertex api_key not configured")
+ }
+ req.Header.Set("x-goog-api-key", apiKey)
+ return nil
+ }
+ if tokenProvider == nil {
+ return errors.New("gemini token provider not configured")
+ }
+ accessToken, err := tokenProvider.GetAccessToken(ctx, account)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Authorization", "Bearer "+accessToken)
+ return nil
+}
+
func buildVertexGeminiURL(projectID, location, model, action string, stream bool) (string, error) {
projectID = strings.TrimSpace(projectID)
location = strings.TrimSpace(location)
@@ -300,14 +401,12 @@ func buildVertexGeminiURL(projectID, location, model, action string, stream bool
if model == "" {
return "", errors.New("vertex model is required")
}
- switch action {
- case "generateContent", "streamGenerateContent", "countTokens":
- default:
- return "", fmt.Errorf("unsupported vertex gemini action: %s", action)
+ if err := validateVertexGeminiAction(action); err != nil {
+ return "", err
}
host := fmt.Sprintf("%s-aiplatform.googleapis.com", location)
if location == "global" {
- host = "aiplatform.googleapis.com"
+ host = vertexGlobalHost
}
u := fmt.Sprintf(
"https://%s/v1/projects/%s/locations/%s/publishers/google/models/%s:%s",
diff --git a/backend/internal/service/vertex_service_account_test.go b/backend/internal/service/vertex_service_account_test.go
index 003f07200..ebb2ce040 100644
--- a/backend/internal/service/vertex_service_account_test.go
+++ b/backend/internal/service/vertex_service_account_test.go
@@ -30,6 +30,62 @@ func TestBuildVertexGeminiURLUsesGlobalEndpointHost(t *testing.T) {
require.Equal(t, "https://aiplatform.googleapis.com/v1/projects/my-project/locations/global/publishers/google/models/gemini-3-flash-preview:streamGenerateContent?alt=sse", got)
}
+func TestIsVertexAPIKey(t *testing.T) {
+ apiKeyCreds := map[string]any{"auth_mode": "apikey", "api_key": "k"}
+ require.True(t, (&Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: apiKeyCreds}).IsVertexAPIKey())
+ require.False(t, (&Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"service_account_json": "{}"}}).IsVertexAPIKey())
+ require.False(t, (&Account{Platform: PlatformAnthropic, Type: AccountTypeServiceAccount, Credentials: apiKeyCreds}).IsVertexAPIKey())
+ require.False(t, (&Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: apiKeyCreds}).IsVertexAPIKey())
+}
+
+func TestBuildVertexGeminiAccountURL(t *testing.T) {
+ cases := []struct {
+ name string
+ credentials map[string]any
+ want string
+ }{
+ {
+ name: "api key without project uses express global endpoint",
+ credentials: map[string]any{"auth_mode": "apikey", "api_key": "k", "location": "us-central1"},
+ want: "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3-flash-preview:streamGenerateContent?alt=sse",
+ },
+ {
+ name: "api key with project uses project endpoint",
+ credentials: map[string]any{"auth_mode": "apikey", "api_key": "k", "project_id": "my-project", "location": "us-central1"},
+ want: "https://us-central1-aiplatform.googleapis.com/v1/projects/my-project/locations/us-central1/publishers/google/models/gemini-3-flash-preview:streamGenerateContent?alt=sse",
+ },
+ {
+ name: "service account uses project endpoint",
+ credentials: map[string]any{"project_id": "sa-project", "location": "global"},
+ want: "https://aiplatform.googleapis.com/v1/projects/sa-project/locations/global/publishers/google/models/gemini-3-flash-preview:streamGenerateContent?alt=sse",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: tc.credentials}
+ got, err := buildVertexGeminiAccountURL(account, "gemini-3-flash-preview", "streamGenerateContent", true)
+ require.NoError(t, err)
+ require.Equal(t, tc.want, got)
+ })
+ }
+
+ account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"auth_mode": "apikey", "api_key": "k"}}
+ _, err := buildVertexGeminiAccountURL(account, "gemini-3-flash-preview", "rawPredict", false)
+ require.ErrorContains(t, err, "unsupported vertex gemini action")
+}
+
+func TestSetVertexGeminiAuthUsesAPIKeyHeader(t *testing.T) {
+ account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"auth_mode": "apikey", "api_key": " vertex-key "}}
+ req := httptest.NewRequest(http.MethodPost, "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3-flash-preview:generateContent", nil)
+
+ require.NoError(t, setVertexGeminiAuth(context.Background(), req, account, nil))
+ require.Equal(t, "vertex-key", req.Header.Get("x-goog-api-key"))
+ require.Empty(t, req.Header.Get("Authorization"))
+
+ account.Credentials["api_key"] = ""
+ require.ErrorContains(t, setVertexGeminiAuth(context.Background(), req, account, nil), "vertex api_key not configured")
+}
+
func TestBuildVertexAnthropicURL(t *testing.T) {
got, err := buildVertexAnthropicURL("my-project", "us-east5", "claude-sonnet-4-5@20250929", false)
require.NoError(t, err)
diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go
index 81abd34b7..29c1b4e33 100644
--- a/backend/internal/service/wire.go
+++ b/backend/internal/service/wire.go
@@ -640,6 +640,13 @@ func ProvideIdempotencyCleanupService(repo IdempotencyRepository, cfg *config.Co
return svc
}
+// ProvideGeminiCachedContentService creates GeminiCachedContentService and starts its mutation recovery loop.
+func ProvideGeminiCachedContentService(repo GeminiCachedContentRepository, compat *GeminiMessagesCompatService, cfg *config.Config) *GeminiCachedContentService {
+ svc := NewGeminiCachedContentService(repo, compat, cfg)
+ svc.Start()
+ return svc
+}
+
// ProvideScheduledTestService creates ScheduledTestService.
func ProvideScheduledTestService(
planRepo ScheduledTestPlanRepository,
@@ -885,6 +892,7 @@ var ProviderSet = wire.NewSet(
ProvideGrokOAuthService,
wire.Bind(new(GrokOAuthTokenService), new(*GrokOAuthService)),
NewGeminiOAuthService,
+ ProvideGeminiCachedContentService,
NewGeminiQuotaService,
NewCompositeTokenCacheInvalidator,
wire.Bind(new(TokenCacheInvalidator), new(*CompositeTokenCacheInvalidator)),
diff --git a/backend/internal/util/logredact/redact.go b/backend/internal/util/logredact/redact.go
index 9249b761c..8be6448a1 100644
--- a/backend/internal/util/logredact/redact.go
+++ b/backend/internal/util/logredact/redact.go
@@ -42,6 +42,8 @@ type textRedactPatterns struct {
var (
reGOCSPX = regexp.MustCompile(`GOCSPX-[0-9A-Za-z_-]{24,}`)
reAIza = regexp.MustCompile(`AIza[0-9A-Za-z_-]{35}`)
+ // Gemini auth key:AQ.Ab 前缀 + 48 位,长度放宽以覆盖格式变体。
+ reGeminiAuthKey = regexp.MustCompile(`AQ\.Ab[0-9A-Za-z_-]{40,}`)
defaultTextRedactPatterns = compileTextRedactPatterns(nil)
extraTextPatternCache sync.Map // map[string]*textRedactPatterns
@@ -99,6 +101,7 @@ func RedactText(input string, extraKeys ...string) string {
out := input
out = reGOCSPX.ReplaceAllString(out, "GOCSPX-***")
out = reAIza.ReplaceAllString(out, "AIza***")
+ out = reGeminiAuthKey.ReplaceAllString(out, "AQ.***")
out = patterns.reJSONLike.ReplaceAllString(out, `$1***$3`)
out = patterns.reQueryLike.ReplaceAllString(out, `$1=***`)
out = patterns.rePlain.ReplaceAllString(out, `$1$2***`)
diff --git a/backend/internal/util/logredact/redact_test.go b/backend/internal/util/logredact/redact_test.go
index 266db69db..e615f33e0 100644
--- a/backend/internal/util/logredact/redact_test.go
+++ b/backend/internal/util/logredact/redact_test.go
@@ -38,6 +38,28 @@ func TestRedactText_GOCSPX(t *testing.T) {
}
}
+func TestRedactText_GeminiAPIKeys(t *testing.T) {
+ legacyKey := "AI" + "za" + strings.Repeat("Ab1_-", 7)
+ authKey := "AQ." + "Ab" + strings.Repeat("Xy9_-z", 8)
+ in := "upstream rejected " + legacyKey + " and " + authKey + " for model gemini-3.1-pro"
+ out := RedactText(in)
+ if strings.Contains(out, legacyKey) || strings.Contains(out, authKey) {
+ t.Fatalf("expected Gemini keys redacted, got %q", out)
+ }
+ for _, want := range []string{"AIza***", "AQ.***", "for model gemini-3.1-pro"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("expected %q in %q", want, out)
+ }
+ }
+}
+
+func TestRedactText_GeminiAuthKeyPrefixAloneUnchanged(t *testing.T) {
+ in := "key format AQ.Ab... is documented"
+ if out := RedactText(in); out != in {
+ t.Fatalf("expected short AQ. prefix unchanged, got %q", out)
+ }
+}
+
func TestRedactText_ExtraKeyCacheUsesNormalizedSortedKey(t *testing.T) {
clearExtraTextPatternCache()
diff --git a/backend/internal/web/embed_test.go b/backend/internal/web/embed_test.go
index 329eb19bf..eeba5072d 100644
--- a/backend/internal/web/embed_test.go
+++ b/backend/internal/web/embed_test.go
@@ -653,11 +653,11 @@ func TestFrontendServer_Middleware(t *testing.T) {
// Request for existing static file
w := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "/logo.png", nil)
+ req := httptest.NewRequest(http.MethodGet, "/logo.svg", nil)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
- assert.Contains(t, w.Header().Get("Content-Type"), "image/png")
+ assert.Contains(t, w.Header().Get("Content-Type"), "image/svg+xml")
assert.Empty(t, w.Header().Get("Cache-Control"))
entries, err := fs.ReadDir(server.distFS, "assets")
@@ -772,11 +772,11 @@ func TestServeEmbeddedFrontend(t *testing.T) {
router.Use(middleware)
w := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "/logo.png", nil)
+ req := httptest.NewRequest(http.MethodGet, "/logo.svg", nil)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
- assert.Contains(t, w.Header().Get("Content-Type"), "image/png")
+ assert.Contains(t, w.Header().Get("Content-Type"), "image/svg+xml")
})
t.Run("serves_index_html_for_root", func(t *testing.T) {
diff --git a/backend/migrations/241_0_sub4api_skip_typesafe_constraint_for_openai_bps.sql b/backend/migrations/241_0_sub4api_skip_typesafe_constraint_for_openai_bps.sql
new file mode 100644
index 000000000..e0a51f818
--- /dev/null
+++ b/backend/migrations/241_0_sub4api_skip_typesafe_constraint_for_openai_bps.sql
@@ -0,0 +1,17 @@
+-- Sub4API: 上游 241_add_typesafe_platform.sql 会重建不含 openai_bps 的平台 CHECK 约束,
+-- 1.1.5–1.1.9 的存量库若已有 openai_bps 行(245_openai_bps_platform.sql),
+-- 首次执行 241 时约束校验会失败。上游迁移不可修改,故在 241 之前处理。
+--
+-- 241 重建的两个约束随后会被 242_drop_platform_check_constraints.sql /
+-- 246_redrop_platform_check_constraints.sql 删除,跳过 241 与执行它的最终结构一致,
+-- 因此仅在存在 openai_bps 行时将 241 登记为已应用(使用上游 checksum)。
+--
+-- 241 已应用(含 1.1.10/1.1.11 的历史 checksum)时 ON CONFLICT 不做任何事;
+-- 无 openai_bps 行(含新库)时不登记,上游 241 正常执行。
+
+INSERT INTO schema_migrations (filename, checksum)
+SELECT '241_add_typesafe_platform.sql',
+ 'b6559525bf8d0b5d7c617e7415944f0d1fae8c408e9131ace84139795f66dcd2'
+WHERE EXISTS (SELECT 1 FROM user_platform_quotas WHERE platform = 'openai_bps')
+ OR EXISTS (SELECT 1 FROM composite_model_routes WHERE target_platform = 'openai_bps')
+ON CONFLICT (filename) DO NOTHING;
diff --git a/backend/migrations/241_add_typesafe_platform.sql b/backend/migrations/241_add_typesafe_platform.sql
index 5bef23554..82a81de70 100644
--- a/backend/migrations/241_add_typesafe_platform.sql
+++ b/backend/migrations/241_add_typesafe_platform.sql
@@ -6,9 +6,6 @@
-- TypeSafe 不是对话模型,不进入渠道监控 provider,因此 channel_monitors /
-- channel_monitor_request_templates 的约束保持不变。
--
--- Sub4API: 保留 openai_bps(245_openai_bps_platform.sql),否则已有 openai_bps 行的
--- 存量库在此迁移会校验失败。
---
-- Runs after 238_opencode_go_platform.sql. DROP ... IF EXISTS 保证可重入;
-- 新约束是 238 的超集,存量行瞬时校验通过。
@@ -17,7 +14,7 @@ ALTER TABLE user_platform_quotas
ALTER TABLE user_platform_quotas
ADD CONSTRAINT user_platform_quotas_platform_check
- CHECK (platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok',
+ CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok',
'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'));
ALTER TABLE composite_model_routes
@@ -25,5 +22,5 @@ ALTER TABLE composite_model_routes
ALTER TABLE composite_model_routes
ADD CONSTRAINT composite_model_routes_target_platform_check
- CHECK (target_platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok',
+ CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok',
'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'));
diff --git a/backend/migrations/242_group_i18n.sql b/backend/migrations/242_group_i18n.sql
new file mode 100644
index 000000000..2e0ab2c63
--- /dev/null
+++ b/backend/migrations/242_group_i18n.sql
@@ -0,0 +1,5 @@
+ALTER TABLE groups
+ ADD COLUMN IF NOT EXISTS i18n JSONB NOT NULL DEFAULT '{}'::jsonb;
+
+COMMENT ON COLUMN groups.i18n IS
+ 'Per-locale display text for the group: {"":{"name":string,"description":string}}; locales or fields that are absent fall back to groups.name / groups.description';
diff --git a/backend/migrations/243_gemini_cached_contents.sql b/backend/migrations/243_gemini_cached_contents.sql
new file mode 100644
index 000000000..d3cbda27d
--- /dev/null
+++ b/backend/migrations/243_gemini_cached_contents.sql
@@ -0,0 +1,30 @@
+-- Gemini 显式缓存(cachedContents)的网关资源绑定。
+-- public_id 是网关对客户端暴露的缓存 ID;upstream_name 是上游资源名,
+-- 引用缓存的请求只能路由到 account_id 对应的账号。
+CREATE TABLE IF NOT EXISTS gemini_cached_contents (
+ id BIGSERIAL PRIMARY KEY,
+ public_id VARCHAR(64) NOT NULL,
+ user_id BIGINT NOT NULL,
+ api_key_id BIGINT NOT NULL,
+ group_id BIGINT NOT NULL,
+ account_id BIGINT NOT NULL,
+ upstream_name VARCHAR(512) NOT NULL,
+ model VARCHAR(255) NOT NULL,
+ upstream_model VARCHAR(512) NOT NULL,
+ display_name VARCHAR(512) NOT NULL DEFAULT '',
+ total_token_count BIGINT NOT NULL DEFAULT 0,
+ expire_time TIMESTAMPTZ NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ deleted_at TIMESTAMPTZ NULL
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS idx_gemini_cached_contents_public_id
+ ON gemini_cached_contents (public_id);
+
+CREATE INDEX IF NOT EXISTS idx_gemini_cached_contents_api_key_active
+ ON gemini_cached_contents (api_key_id, id DESC)
+ WHERE deleted_at IS NULL;
+
+CREATE INDEX IF NOT EXISTS idx_gemini_cached_contents_account
+ ON gemini_cached_contents (account_id);
diff --git a/backend/migrations/244_gemini_cached_contents_channel_usage.sql b/backend/migrations/244_gemini_cached_contents_channel_usage.sql
new file mode 100644
index 000000000..c72f097a7
--- /dev/null
+++ b/backend/migrations/244_gemini_cached_contents_channel_usage.sql
@@ -0,0 +1,4 @@
+-- Gemini 显式缓存创建时的渠道计费口径(渠道 ID / 请求模型 / 计费模型来源),
+-- 延长有效期按同一口径计费。
+ALTER TABLE gemini_cached_contents
+ ADD COLUMN IF NOT EXISTS channel_usage JSONB NOT NULL DEFAULT '{}'::jsonb;
diff --git a/backend/migrations/245_gemini_cached_contents_mutation_lease.sql b/backend/migrations/245_gemini_cached_contents_mutation_lease.sql
new file mode 100644
index 000000000..e0970efeb
--- /dev/null
+++ b/backend/migrations/245_gemini_cached_contents_mutation_lease.sql
@@ -0,0 +1,10 @@
+-- Gemini 显式缓存修改有效期的进行中操作(修改意图):mutation_token 标识持有者,
+-- mutation_lease_until 之前同一缓存的其他修改被拒绝;expire_time 在提交前保持修改前的值,
+-- 租约过期仍未清除的意图由恢复流程把上游有效期回滚到 expire_time。
+ALTER TABLE gemini_cached_contents
+ ADD COLUMN IF NOT EXISTS mutation_token VARCHAR(64) NULL,
+ ADD COLUMN IF NOT EXISTS mutation_lease_until TIMESTAMPTZ NULL;
+
+CREATE INDEX IF NOT EXISTS idx_gemini_cached_contents_pending_mutation
+ ON gemini_cached_contents (mutation_lease_until)
+ WHERE mutation_token IS NOT NULL AND deleted_at IS NULL;
diff --git a/backend/migrations/250_sub4api_normalize_241_checksum.sql b/backend/migrations/250_sub4api_normalize_241_checksum.sql
new file mode 100644
index 000000000..3d9fac6a5
--- /dev/null
+++ b/backend/migrations/250_sub4api_normalize_241_checksum.sql
@@ -0,0 +1,10 @@
+-- Sub4API 1.1.10/1.1.11 曾修改上游 241_add_typesafe_platform.sql(白名单加入 openai_bps),
+-- 存量库记录的是改动后的 checksum。241 已恢复为上游原版,此处将历史 checksum
+-- 归一为上游值,使库可在 Sub4API 与上游 Sub2API 之间互相切换。
+--
+-- 仅匹配已知的历史 checksum,可重入。
+
+UPDATE schema_migrations
+ SET checksum = 'b6559525bf8d0b5d7c617e7415944f0d1fae8c408e9131ace84139795f66dcd2'
+ WHERE filename = '241_add_typesafe_platform.sql'
+ AND checksum = '6034ab0415266a5299a64d49f56b52dab8c61a3c5b2eaa82327c81cc5698a871';
diff --git a/backend/migrations/typesafe_platform_migration_test.go b/backend/migrations/typesafe_platform_migration_test.go
index 04f94bdba..7eb238091 100644
--- a/backend/migrations/typesafe_platform_migration_test.go
+++ b/backend/migrations/typesafe_platform_migration_test.go
@@ -15,7 +15,7 @@ func TestTypeSafePlatformMigration(t *testing.T) {
require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check")
require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check")
require.Contains(t, sql,
- "CHECK (platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))")
+ "CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))")
require.Contains(t, sql,
- "CHECK (target_platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))")
+ "CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))")
}
diff --git a/backend/migrations/upstream_checksums.txt b/backend/migrations/upstream_checksums.txt
new file mode 100644
index 000000000..6f09ae22b
--- /dev/null
+++ b/backend/migrations/upstream_checksums.txt
@@ -0,0 +1,298 @@
+# Generated by scripts/sync-upstream-migration-checksums.sh from upstream 060d01604.
+# Upstream migrations must not be modified; add a new Sub4API migration instead.
+9ba0369779484625edcea7a7d1d4582397e31546db9149b05004990a3f16c630 001_init.sql
+aad3816e44f58ff007ea4df8092aae580f3f85180314c1deb1b1054b20892bbf 002_account_type_migration.sql
+4642fcb1ccd7954b1d3eef8f795cfba2ce21431257346cc5a7568cde61a60b13 003_subscription.sql
+fb171d084795906ce8e388eec34133dfa256e1ecb1621083f12aa47c6368bfd8 004_add_redeem_code_notes.sql
+2ae9e9ff98adb2a684aeb4d839be7ee00e7a26af167460f886133ac55361b5bf 005_schema_parity.sql
+900f5ba934e8d66bba7d94f1d34463a9022e0e72c3ce911260d7c703449a33ae 006_add_users_allowed_groups_compat.sql
+ed5d6553a86578d987088331bc8810808b75e554a160b66ff4626815ea838354 006_fix_invalid_subscription_expires_at.sql
+6953b71b92d0ed2f035137fdc4e4fb6cc056861b22e28c5612950c08cedf564e 006b_guard_users_allowed_groups.sql
+76694d87e70be4fa9d9f27cd308717685a426d9a64ded36a5a9517956ebec972 007_add_user_allowed_groups.sql
+f4bd452fb097a509120399b6121abb17d1a212330185b40f1e5ec69c6e16954a 008_seed_default_group.sql
+9a3c22b296ea5a628eb8b35b34318f035b9ac177dfc7d1db26b0901dcd98bafb 009_fix_usage_logs_cache_columns.sql
+3537ff30a25b71c93458f77e08ce5b60355e0a3068bfd49e2d9bdb6e6deee027 010_add_usage_logs_aggregated_indexes.sql
+ae4c6f5bab86f399ad812b7ffc927402c0a8decef85bf7c3d7a8877863ba520e 011_remove_duplicate_unique_indexes.sql
+5c829927c7f882fbe0258239c3673f865b03dfc3ee274674d7a2cedb06deaf24 012_add_user_subscription_soft_delete.sql
+4f2d8e9078f02de763977963f711ed2e82587b9ac72947c1b8019594b49d6dd8 013_log_orphan_allowed_groups.sql
+b63fc37ba6a6ffdcb50e082250be5f34f40632597d568bb97247c607198befcc 014_drop_legacy_allowed_groups.sql
+b6f7f2244cb66fa5a5b088a1f40d2694b95e23fce971bc2562bcbe306efe48d3 015_fix_settings_unique_constraint.sql
+213c9358247ca0072d9c6a441eb7e1df9513e7e8040e6ca4f0d616c319f588ba 016_soft_delete_partial_unique_indexes.sql
+af99c63b62dcd029b52b2693281e0dea4dfc751dadefd4cbbc894359f2cc8014 018_user_attributes.sql
+d45e05b4bb722b287377790583c2677b8666dbf7e02b626c93468491d4ce8cf8 019_migrate_wechat_to_attributes.sql
+0ffee69180cdb20aba0116dc2c20da781bbe9bd2418d41f30880bbf12f51efbe 020_add_temp_unschedulable.sql
+b54de1b9a4423224f7aef5e644d1af115214d58dd61befd3c25db3e709b9163a 024_add_gemini_tier_id.sql
+cff5e8fe80d8f8fd94cf6d9f2b01065f9b3ebdff8a99f941b927d530a418ba62 026_ops_metrics_aggregation_tables.sql
+68df49831cadfb2c5d1f8e24b8b36068be454cca9fdf6df1141593ee20c98dd8 027_usage_billing_consistency.sql
+8d52c15e184ffe112185eeaea5bad35afe3761dfb7cc9e9b1644445134420300 028_add_account_notes.sql
+024d6dd42321b3c0f35cf8e15766e1dda993c08c1d69878e8888d6cb4bccde2d 028_add_usage_logs_user_agent.sql
+e1276ed19c083a32eb62272abc9a9640e3aca1dc0cee8fc661de873959421d80 028_group_image_pricing.sql
+f0c5bb461d29a64410ed05a3f2dd478cf42deddbf1013e23f9468c573455f1be 029_add_group_claude_code_restriction.sql
+ce14c36d169e6d6d070069d11f35a8622298436c204a54a0ae580f0e63396a4f 029_usage_log_image_fields.sql
+d6ea81863b7d7031426009ed081ce76b14325664aa1782dd496a527ca0dab85b 030_add_account_expires_at.sql
+c9ce8db0e582b1a844e8529bb0cf3bd6ccf5bf6fa0949bb4955a963801a97da0 031_add_ip_address.sql
+e0f084b7533d53faee48f122a04ef3988625e61c6356448a07085236d8c96122 032_add_api_key_ip_restriction.sql
+913c0f2a90943c51aa0134cf7f4339dfdafad8b5e14738159a1841f14b4f8ff9 033_add_promo_codes.sql
+accf363544d187aecad4f1c68fe34118f86d1a931465e66490c530d3f3f1106d 033_ops_monitoring_vnext.sql
+1b2e69d10195f0264b034873e0a9d96bb946072886aad9f63307c08808689a56 034_ops_upstream_error_events.sql
+20bf67f62858c3c292c66ea667e9ac7d5c7b645077e6413a03700be1b480d962 034_usage_dashboard_aggregation_tables.sql
+91a02804ee4292e1dc33cda28335725b1011236bb19f577d2c8e6b4bcbffd3ba 035_usage_logs_partitioning.sql
+ed9ee240c43ef259f18a7ca440d73f285988d2aa57af229e0b69344f11af3bf4 036_ops_error_logs_add_is_count_tokens.sql
+e88635e14a2b9f04041495890c3d98125bae119ecf3936c070d82e017ee2a4c0 036_scheduler_outbox.sql
+e8a2bea65eac919a323738098402bb6ea53720cbe1111a6cec823d2d36ebfd20 037_add_account_rate_multiplier.sql
+72143a1ce3528ebc47472759c59011ec6993b25a3f22d50485538710047438c6 037_ops_alert_silences.sql
+4cc121d97c7f59e9def9397b7d0314d4dfbfe4cd831698359456dd49bf995ece 038_ops_errors_resolution_retry_results_and_standardize_classification.sql
+5dad52cd5a61ad98029ba2de4ea3903cbc9c40a43731dd8a3f8a8129277ec47b 039_ops_job_heartbeats_add_last_result.sql
+fb8727cfea19997101646457a3c31c3efc647e3cb2b8a0e04d06a24c3a608862 040_add_group_model_routing.sql
+5cee91bdfc5afe4815dba6b127755a76d33ab55a93419c5b51e57d8dfd9cba3a 041_add_model_routing_enabled.sql
+19788b90712c08865c65ae4a4615a1b6d148eb915bbf74297363257f945163c8 042_add_usage_cleanup_tasks.sql
+ee5428fb36a497799cb92ceffbbdc8e257a6e0c27aaae072152cac9bbc4d7dd8 042b_add_ops_system_metrics_switch_count.sql
+4d3a22daea84e74d902ee1a6cec44e8985372e127c085a7dec2e30a922241585 043_add_usage_cleanup_cancel_audit.sql
+7667812b71f86bb010afd0807c709c2415ca585d08995967982def2b35b46b9d 043b_add_group_invalid_request_fallback.sql
+744b989d9a852d3e5871149f5ae83494ed84ac00861c6f40494506c63195cb74 044_add_user_totp.sql
+944e8ed8950dc9c2cf95ee62bcf342ea2e15a771895b43da87efec85db921c31 044b_add_group_mcp_xml_inject.sql
+c8e0948f88871aa79af0de0898d3aa6e14106e7a31b1fc6ae61bda57ebd1f7a4 045_add_accounts_extra_index.sql
+6b2df139a5004bdfd2ea9d6fc39d28eec973340ba045472fb399856f49b46f99 045_add_announcements.sql
+d0602924f128c5bbf468924f5ec990f87cd7636619bf9b52b17bb015abf37d55 045_add_api_key_quota.sql
+b86a3243f965c569a97d96f5203853744e088f3c2b024ae243203ff96df8ceeb 046_add_sora_accounts.sql
+88b1408cab98801d90c717efb8002a5f5a75a509f424df0fc16d36100a1592e3 046_add_usage_log_reasoning_effort.sql
+5fa393ae8645c6cb7c019bc2f2e14f4b588e88719f56af4bde6160d37186fd2b 046b_add_group_supported_model_scopes.sql
+d806f44a7dd70b8a2f7abadcb5cc8bf75679db242dacab9c8a69886bc17ed10a 047_add_sora_pricing_and_media_type.sql
+b866ed6d784e7b43f48d6b8e5b138c8b040354ff2fc2be4569fa810b779e9c16 047_add_user_group_rate_multipliers.sql
+f86707582e0dab5f2f1e7f9abc8f0be7ebe36e1544e4a559be808d8b5712db3f 048_add_error_passthrough_rules.sql
+e27c5615388f95c3d638a572f33a570e9a0f89efaae2f88cafdd3a169cb64f56 049_unify_antigravity_model_mapping.sql
+dd4b8b866fdbaa5dc2ce0750be69faa65a7368fef1e937e3ab923bc35d5d5bd5 050_map_opus46_to_opus45.sql
+17896dac51029a101369bbe80a7c76f2a82838d890e2248d38f38462a931acd2 051_migrate_opus45_to_opus46_thinking.sql
+f49cc4729d382b30f1477a2423d0072e9b0203128b1dd01c7c6ac6ee4c050faa 052_add_group_sort_order.sql
+d2ea657ec24995664a8ddc1bfb9c3fe317646c7bcd12517dee8478bc6c36244a 052_migrate_upstream_to_apikey.sql
+9a17a5c2d98eea3656d36e7eb6c5238e839a40bf06a6fb599013bfbace8e0b46 053_add_security_secrets.sql
+70dceedd55b14bbca64d760ebdd857481b6d6c34367d308ca8a4f86b0374ed1e 053_add_skip_monitoring_to_error_passthrough.sql
+82de761156e03876653e7a6a4eee883cd927847036f779b0b9f34c42a8af7a7d 054_drop_legacy_cache_columns.sql
+a47aa0fdab66ba60ac57bf127254e86060bfe681735559751fec2386b6c36541 054_ops_system_logs.sql
+3d05c9ffe4aaffec1cb7e482bc45fc5e63986b856548956795b33421280329a0 055_add_cache_ttl_overridden.sql
+e3f815389414fd17e3c42db46e6ade842ffea87077965f2076356f4ee8f30bc2 056_add_api_key_last_used_at.sql
+879aa2f0803121671ca75525c861aac6711ee52ac2e5e69967ce8a872754819e 057_add_idempotency_records.sql
+b417bcfe71f6f60837d35bfff3ac3089300ea18c3d577a00f81d4861aa889c03 058_add_sonnet46_to_model_mapping.sql
+04e541c4600ccf3e54afae9506bb17db3335e02c0942958c120717147337e20f 059_add_gemini31_pro_to_model_mapping.sql
+e3b801643e696eec44c6d69b95bac268ef16f1e2bd4aa7953b2b7ba19c3c7358 060_add_gemini31_flash_image_to_model_mapping.sql
+60338e18704514a456f2c85e1c08e48471aa7229567bfdbcc90a33a897c1ab66 060_add_usage_log_openai_ws_mode.sql
+66207e7aa5dd0429c2e2c0fabdaf79783ff157fa0af2e81adff2ee03790ec65c 061_add_usage_log_request_type.sql
+10f404d291d8328d9871f8441796dcb2c5be6de86933d2f9d0238f48a0a611cb 062_add_scheduler_and_usage_composite_indexes_notx.sql
+23a5777e8c38f269f8777e959af33db063891a8ba19eae0a96ee9c22e6b10103 063_add_sora_client_tables.sql
+5dbc91ab545c7a190532b57490241f143112c74b064ea37ee3bf3c8aff2e5e49 064_add_api_key_rate_limits.sql
+7d86ccf0b2e47c0146f688933bef6b015043a38dec1cb6b4b42b2290e7cf4d8b 065_add_search_trgm_indexes.sql
+a316e86876a29399306b5bf562a0799ebb1150bfd2bdd2b16471b6248e2940d4 066_add_scheduled_test_tables.sql
+d632f3af1813169757f79e2d11b7cf36aff90cfb94494fff01ad8168d2c0af25 067_add_account_load_factor.sql
+04790bc2b16579c419c13285d553a6a63b90e2eb8f6b7222763b672cdb64cda6 068_add_announcement_notify_mode.sql
+c6d35422f140f97f5427f756eae929b243e3cbb362252806f179fbb7519b107f 069_add_group_messages_dispatch.sql
+1541e616629bfeb425972e6f0fd42fd9fea02e17268e49b87658ca70ff28db5f 070_add_scheduled_test_auto_recover.sql
+0d5fdeb0af615345b56cb3a5eaf88cb06bc90a51ba7a1f9f7646afd75ef61ce5 070_add_usage_log_service_tier.sql
+190436d16d8c3474c3967cf97425cde5b6ed22464f32cd3c4dfb4702138d4f4a 071_add_gemini25_flash_image_to_model_mapping.sql
+f4d5e56a3ad76351e5b8203604e6db266341c3471442c75fc95c14d4ecc71b6e 071_add_usage_billing_dedup.sql
+852071e0141f4d62a494952b34cd66df10d1c30b1d2041f9bc3cf194980e762b 072_add_usage_billing_dedup_created_at_brin_notx.sql
+45510d82c7f8b57c041938d6d446175618981d6e7381c91893f799bed622564d 073_add_usage_billing_dedup_archive.sql
+f262f4a73e845b5386d2f5fcaa0c85aed969ee7f2cbbd33e7a6d19ce259c51a3 074_add_usage_log_endpoints.sql
+127452235cfd5e9cf9d684918373c77a25282754953ecb21bcdcd1292709fc2a 075_add_usage_log_upstream_model.sql
+11e14b074ef0bd49f1a9833bb9e770e7a62aa5e73bfa25c6be44b3cb16fb42a0 075_map_haiku45_to_sonnet46.sql
+4c4fdb7c522eba61337e3ea7ec4c991b62bbd12da3bd4b88149dcc84aa6f9050 076_add_usage_log_upstream_model_index_notx.sql
+4ba95774acae88d66f54b0a5749e25c9e1dbaee523868f41e1dea1d226a4c089 077_add_usage_log_requested_model.sql
+0aea5dbb49e704f1a7ec82fe38ad0c5743cb55f85f8eda90610b48e7f03564d9 078_add_usage_log_requested_model_index_notx.sql
+551af172229cfbfb136558bbef02c2e1eb5443195806450b04961674afe9807d 079_ops_error_logs_add_endpoint_fields.sql
+0f22bd835ebae76401f8c41a96b5fc83f6b86bf12a07be3ee1ab5a8c494e9b3f 080_create_tls_fingerprint_profiles.sql
+8b347ceeb08e327fc8db16e20ff06bc558812d1e5938f63b117d3703196e654e 081_add_group_account_filter.sql
+b16b8db56880686c3f7a69d900273fa31df15dc429ff6c3d722fe987a16ceb3a 081_create_channels.sql
+fbcbe96f9db9a2c75cdc4fa13bc1e086fbdbbbb001bea8f0f5da2fdda494f9f7 082_refactor_channel_pricing.sql
+bd6bf4d2d5bdadcdfee23178613f659f74432d3a611a2299b9397bc355677359 083_channel_model_mapping.sql
+fd7a0dd5a51c82c8831d6a7b799584968d42bc4a11ad7fa76889e514764d3140 084_channel_billing_model_source.sql
+17bd1b3995f6b84d6bebe301f26f351f8a6358ff69ee333c3ca8d7ef939782e1 085_channel_restrict_and_per_request_price.sql
+f646613843c4453e91e065a21842f84f7d4a244d710c47ec703649f0ba48560b 086_channel_platform_pricing.sql
+8c1cee4ce04027cb5d5ae46721d3adfd147f1e180333ddd1ee2e868458edb28c 087_usage_log_billing_mode.sql
+e604cf3293612b2916f089c23392641fb6c4aac1d803d4d613a3ae410bc83606 088_channel_billing_model_source_channel_mapped.sql
+8ea075a203089518906a6765972d53456644682be8b1bed12baa48efa12f57d5 089_usage_log_image_output_tokens.sql
+5326d418f2ccc10ce8f4c8766ae490eccbc96c29ba76ea5807635985bbfb877c 090_drop_sora.sql
+82d6f70e6312df49a9fa24aee6035a3fe52c65e81a7d55be015bb165ba04ead3 091_add_group_messages_dispatch_model_config.sql
+798710c7f324021cbc913fe7edf0cde786c6832c89c16b66b55691ab09d8fb24 092_payment_orders.sql
+f1817214462dbca5f8a101728cba5c9c141da167ab25b1d582eb7d725aa6f9c3 093_payment_audit_logs.sql
+8655cbb69835beac545e4b98d17498f1b1215fcd14f9c7e6b80f789ea8515db1 094_removed_payment_channels.sql
+c69270d28e3f52097cbdeab7d7eedb8b1a38b2a2158e333b03a0b2c47a1363aa 095_channel_features.sql
+b81539b3bc5d4585d2e854329c60b23d020744db8c9bf6392dc43550a2924f24 095_subscription_plans.sql
+bbbeb7105344ff93a717054dc3d2cfbadf21f8a17034f232e3cf68a523cd3543 096_payment_provider_instances.sql
+5a6a64527ba6462ff76dda842d4be281b2d54192a88fbcf7324883af1fcffe37 097_fix_settings_updated_at_default.sql
+da103effd6affebe41a27af457983eadf0e610d73294984e223dbba68ffdbd04 098_migrate_purchase_subscription_to_custom_menu.sql
+ac356a570eb884de9ec6c016e21b3d9d7cbceb2596abe7ff2bb2afc18cfaa6cb 099_fix_migrated_purchase_menu_label_icon.sql
+9d8fb482beab73a952d689def49670be834788d53b5bb274dd33ad70f128d8d7 100_remove_easypay_from_enabled_payment_types.sql
+a442674cb9b22aacf1879995d23c73792cfb1bd0fb1d0d04f396cda2880d4cc2 101_add_account_stats_pricing.sql
+35b7939ce304df21f7a6d596f1ad9ff84ab427dac710ea58e1260e6efec7ba1a 101_add_balance_notify_fields.sql
+cbc95ac8fbb88c5de22e45f72c9c5113ac0109dcc810687ca84ceff42c16e801 101_add_channel_features_config.sql
+3f7ff2671954f5af21dda2bf499bd12eb6a1214b80c065a89927a85d72ca4426 101_add_payment_mode.sql
+d1bb182c71a66bd1e54481806b6a459ac3a2654353e7aef3ded9774779d1bdd1 102_add_balance_notify_threshold_type.sql
+1197c42b7f80e50f3c3b8eaf0cd9ec297d3c1e3cb54596f2d09e038ec2514465 102_add_out_trade_no_to_payment_orders.sql
+87d67f99c67e4bd02123082477dd499744582c5df2be6cc9bdc5a5884a2f226c 103_add_allow_user_refund.sql
+07a7875e44d38a9379a5294486af875beea80961fd9aaacb442dc6abb15e8a72 104_migrate_notify_emails_to_struct.sql
+e214ccd7d795fca6c04e7e198967b2c758fa08b03fdead33ed10723dd8408728 105_migrate_websearch_emulation_to_tristate.sql
+da7b6b4bd0e3350e3088e9e4ff0ab9e8b82c81b7527c6e1237aa7a299045ebc2 106_add_account_stats_pricing_intervals.sql
+8742f876b999808fc9f478fd2db06037b26d9ab74b10e872517211ee7805d663 107_add_account_cost_to_dashboard_tables.sql
+370c796b9b24e4617870698c9f2d9d782b22ac45fc6b7612957247daf60c8c5f 108_auth_identity_foundation_core.sql
+87646a866b17a329b01abb241b99e3874ee2c13c7d7bba3f6e37c53722a60e18 108a_widen_auth_identity_migration_report_type.sql
+2b380305e73ff0c13aa8c811e45897f2b36ca4a438f7b3e8f98e19ecb6bae0b3 109_auth_identity_compat_backfill.sql
+57a196a9810fb478fa001dfff110f5c76a7d87fb04f15e12e513fcb75402d7a6 110_pending_auth_and_provider_default_grants.sql
+c90a03f04806894ea79e7a999fea15cfe97181866fb2ff92bd1e3c719bef956f 111_payment_routing_and_scheduler_flags.sql
+ab871fc02da1eabe0de6ca74a119ee3cea9c727caed30af2ae07a0cd1176d1b8 112_add_payment_order_provider_key_snapshot.sql
+d22834c8e77127e2d14b988b5618b9e90b8cc20c5cb44a96dd0c0a504bc6a2ab 113_normalize_legacy_wechat_provider_key.sql
+264c6d1caceec74cdfa31c0e891bf9f836bf599e305b85e89d62128dbcd5445a 114_auth_identity_migration_report_resolution.sql
+022aadd97bb53e755f0cf7a3a957e0cb1a1353b0c39ec4de3234acd2871fd04f 115_auth_identity_legacy_external_backfill.sql
+07edb09fa8d04ffb172b0621e3c22f4d1757d20a24ae267b3b36b087ab72d488 116_auth_identity_legacy_external_safety_reports.sql
+44bbed8bd7d8fe3ba95480b7a79c80a844d15ecf796aad9ea9adaea9e83727a2 117_add_payment_order_provider_snapshot.sql
+ed272e0840730b6b8e7838513c4cc8817e8b5e488e27c88b5421adbece5e89c9 118_wechat_dual_mode_and_auth_source_defaults.sql
+0bbe809ae48a9d811dabda1ba1c74955bd71c4a9cc610f9128816818dfa6c11e 119_enforce_payment_orders_out_trade_no_unique.sql
+34aadc0db59a4e390f92a12b73bd74642d9724f33124f73638ae00089ea5e074 120_enforce_payment_orders_out_trade_no_unique_notx.sql
+d593328889933b1732c2167e1da8fbbc22582fab7b210bc8b5bad10853423804 120a_align_payment_orders_out_trade_no_index_name.sql
+4f95fb11a3f44b6cbedf72b5b6bbbdfb6c92147de1b4aa23dea2a1df2ab02603 121_auth_identity_migration_report_type_widen.sql
+25ef9751a95c3c7be99f209bee51dc7ece56366e427f46ad1d8ae066f4e0124e 122_pending_auth_completion_token_cleanup.sql
+7faba5ef65051b7ecb215b7fd2351b0828b7c48153ec688ac089c1588d2cde41 123_fix_legacy_auth_source_grant_on_signup_defaults.sql
+1133834c60d6232506b0bd6a519dcae1a0568cc9fc6a081dbda7bb8f6987835c 124_backfill_legacy_oidc_security_flags.sql
+d49e8d1024ee1912ead12487d997a146943c6da86400f2fa443bb16eb01aac59 125_add_channel_monitors.sql
+f77d3eed98860f8ebd4772a909441736e88e572352c0e6b137fa9c1860bd9d52 125_add_group_rpm_limit.sql
+a631f4adc0fe0b9f4665805fe3d708942cf18e30e74a3061073cc86febfd3f69 126_add_channel_monitor_aggregation.sql
+9b70af1aace9a0834a90b3423df0cac2fe6a561d25394d59a03679bd2259ec61 126_add_user_rpm_limit.sql
+591e97c2e960d8f4e197c710d6033654659536504f0e214abd8559c2677673e4 127_add_user_group_rpm_override.sql
+ac7decb355555a711a372e1ed0d7f1559af41cd796e4be1736f4f978f5f88735 127_drop_channel_monitor_deleted_at.sql
+af3cc2e5394bb720e647b08930f16d93c8f7818779aef39e283636baeffb0527 128_add_channel_monitor_request_templates.sql
+10324a1f1c176a5ab6bc24ac01eee8563f66ffabf4c013b8e4e023caf9f26328 129_seed_claude_code_template.sql
+b4a2425b182b261d55a9f3c2c7f5d574a0d3129b0a79b2d325c1618446d72ea3 130_add_user_affiliates.sql
+706c8102d96d0a10f2e2a23156a8cd8b414a241591fd65ab3e26425b2a54fe29 131_affiliate_rebate_hardening.sql
+49eb9990877096cdffa640cac8e1df2982952964166a0f8a02b327012c1e3e64 132_affiliate_custom_settings.sql
+bd6c9733923cf7219b1b758353e315039594180b31fedf897473d479f5ac1c2e 133_affiliate_rebate_freeze.sql
+80fb2e9033d58cc611412c97301e0c66a86a8bfcd178abfe7877b93519cd2d8a 134_affiliate_ledger_audit_snapshots.sql
+8a8bc4ad03b36bf001290c674a790597cf399ff79c7be298d6bb8071a66d8cf8 134_image_generation_group_controls.sql
+e5e3512fd7ff6e9225414bf79425fd8ddbf6d78a66998142bfb2441f8e7e4708 135_allow_email_oauth_provider_types.sql
+f9545c941580e8cad2b6b5ca4c6522bf1a6335b5a5a04bdc2b143678b289df67 135_content_moderation.sql
+72b6005ff64cddd845615e249d95858010dd6d3bd7a1d24b3e9a32eb03b76eb8 136_add_dingtalk_provider_type.sql
+08d6ff6a5ad1d2d4d16f9cdd4c5259cc7984b7363e46a91e32c12d56c8ec4f90 136_remove_ops_retry_replay.sql
+093f725651296f3e0914dbf3cb8d563c5304e023a03b1e42357c1b96570468f2 136_usage_log_image_size_metadata.sql
+e5211487d1828291db86b95ae353da0f246f6d8c9196b776b47a1d9bb1b9fdcf 137_redeem_code_expires_at.sql
+c638565f7152860a20774cfbe3577ee9c3433b65b5d81005c289af243bc51a84 138_channel_monitor_openai_api_mode.sql
+e844d46972b9c263abd7977f4f862065c8e783835f33abc7328486dcbb5e9d17 139_seed_openai_monitor_templates.sql
+6dc603ebee5a42ff53d9f4c69eda12075a08c2fa1c33271157effc6e11de2d83 140_extend_user_provider_default_grants_check.sql
+86c3d5318bfa70db158a74e2e5ae0dfc65ae5cf7c1b6bb7824e24eac29de0234 141_subscription_expiry_notify_enabled.sql
+fe485a0663f8948174819a2d36b06f260c2dd8a8e85b6e39cd85798b75090873 142_user_platform_quotas.sql
+b0a2cac2567db903a8967456fff348f59530c2633b4dae363c32a0e3b6503cb3 143_group_models_list_config.sql
+a9db755c09ef5a815f0c88ca0d5a0ce9f89e6f29602acf66d78beddbd1630aa1 144_add_opus48_to_model_mapping.sql
+193ea16f064f14f0b288d6a5a468db9c0fecfe23ac19b8c5b8b7cc42ae0b116d 145_deleted_api_key_audit.sql
+187616e08e77cd0af43e7eb59c8217c1138dc2d5dfed7be0f4ca952685db789f 145_ops_metrics_ttft_sample_count.sql
+e5a69fbd48ff1752b020c11551163e7c2218096102bba4a2e2d9c9741664800b 147_ops_error_log_api_key_prefix.sql
+b6399cb7560a0e5d5715e5ea1e842714705c13092f5f95ca22ee0be1bb8ab98f 148_add_ops_error_logs_user_time_index_notx.sql
+2019987ae2b26ad1008ad152f06f2474340f41705187ed931fdfb93542a5206b 149_proxy_expiry_fallback.sql
+08e0bc5840e17a8f812646b04ca2578ce20884e0458b9dfaa5eb14ce845bc7c3 150_account_group_scheduler_indexes_notx.sql
+fc788b8fd4d0542d183bdcf9d7d9b7d5b87c6f972138e126590a57657a0c3cfb 151_account_autopause_expiry_index_notx.sql
+2f5229d780ca0f9f4126485e9d66a219fb7be7f052c1dfce9da29a926da35ba6 151_channel_monitor_jitter.sql
+1a5a86bc3c986483ab286bd617ca69f1e80547bf7d7a7122fdbcded0fd7f68dd 152_scheduler_outbox_dedup_key.sql
+531f5c5c7f91d08d9881e1a5b9a275a090ee9924a731d1c4113df3f19454117e 153_scheduler_outbox_pending_dedup_key_index_notx.sql
+eafe102044d522a8967bea10ab1403e26642965d6794c20467f04752eaea70a0 154_account_spark_shadow.sql
+164e66c8d5a7eb654d8549389f84474c177caeed2bc49d12ee68665a7c19c058 154_add_ops_system_logs_api_key_id.sql
+8d7dc2676c72c35fd3850efe3bc1fedd6478c55cb99c815436d07683b3cbefd7 154a_account_spark_shadow_indexes_notx.sql
+5cd70d982135c1d91bf22f32276fad6678adc61c2416c775597c9bd6dd0d467b 155_add_ops_system_logs_api_key_id_index_notx.sql
+dc7dfec14273276aa666754ef351260b363acaf86faa14a2fc4442d9006422b1 156_content_moderation_matched_keyword.sql
+5cace8fa32c6174a72721cd9b01f28f4545de1fd7bcd9ca196a4225056ec4fb8 157_user_platform_quotas_add_grok.sql
+f3d7f7d41f6c452f94c65ea08b16f64fdb54f0c3528d28905a2bda40fbc58f83 158_add_group_peak_rate_multiplier.sql
+903a5719fb77f6cb468181fcc4c384b90477488f0b0b4ecec10f9c6f94341a21 158_enable_grok_media_generation_groups.sql
+d902b70982025ec519749faf058aab7631e82c3f48167b9a4ae4db718eb72cce 159_batch_image_foundation.sql
+aa2847f34a302696a92e0b49d753598c72cb32435cec1df0b5f351b830b39c8d 160_add_user_frozen_balance.sql
+8552cd5e8596cb0ae53a57bff877ebc4e09cba7b88a81cfce1a4a2877ed43450 160_batch_image_provider_refs.sql
+4012af3e43636cb6af22e0176d59d1fcc70615c0f310194329461ae462c4fbd6 161_batch_image_pricing_snapshot.sql
+5edaf34e9dc20c81cc98c896b25b0364f5ab61fb6419026e4e7e14617db4b05d 162_add_group_batch_image_generation_gate.sql
+8470c9edacf9c6342b4ae2a26153dc7b721787e83c260f987ec1290c4d8020d4 163_batch_image_default_discount_and_hold_ratio.sql
+720db73635df7262c531448ab43c95f4765a0c019ec3fbb615bcf01698a181b9 164_batch_image_download_and_user_delete.sql
+d4ef8a058136f9f107525df7c28a78f534ff332d3baff66de2e76f825ee34795 165_hide_pre_upstream_batch_image_failures.sql
+572addf4a29fcdf869ad66c9a89428cc673beb0d7c4bdfe22f532c3f946008be 166_batch_image_task_name.sql
+208169ee81fbf1f64c7071d0d0f869667db84bdc5b291a7d405ae25ffb5cde86 167_clear_auto_batch_image_task_names.sql
+3175e36000e92864a4fc72f6af5b2c41ccd17d721be77e8aeb2e972f6722aa35 168_restore_empty_batch_image_task_names.sql
+c6e95b7c170d8ff91ffb47307514b3b1deb14ea9a4a2ed164ece26a0814a2dde 169_batch_image_parent_batch.sql
+aa618d048cded096a831f03bee382ce08bcefb2b06941c09aa40e8f0895bf470 170_add_grok_video_pricing_controls.sql
+712e098d825336c8e22acfee6c6c0e8990245305d5b4bd7ac5a0159aa0b1957d 171_allow_video_usage_without_image_size.sql
+7e591f5fe2b05c5ee5c0b96cc0bcbdcbe32239981ec305033fea413fa4fe08eb 172_composite_model_routes.sql
+1c10e9fe18994e2f286139dd91490a2d1dabcdcf572b6331441bd2cd7e7c45b0 172_video_per_second_billing_metadata.sql
+c613a9bf01eeb3c7b8c78737d85ab9e23562876fd7bc8b9b375b0972eeb5da31 173_allow_cyber_blocked_usage_request_type.sql
+d4af66d7be685c60a4b47d340f7450a2e3ba385dd9e7b9da8e30d3026b964056 174_add_usage_log_long_context_billing.sql
+aec8fad2bbb6993340ac93762bd8df62fccc72a41ffeb63181ee8fa58f223a1d 174_add_usage_logs_api_key_latest_ip_index_notx.sql
+4df7ae7179ba35bd45ea8f4f06a9db1e6042fe562a80e8f15a4b286f8ec85437 174_group_web_search_price_per_call.sql
+176b7d3380d274b71fdae60556b68bc2e5da476e83c90d1e21e3130633deb80a 175_add_ops_system_logs_host.sql
+e34a4fc460620d4fcdf9b3914f997172496cc7790eb035cc31dd6bc90baebe46 175_default_openai_long_context_billing.sql
+31e54d9ca4d46a9c42de948428ef70fdfca0f790cbac8e78e37d68355947acca 175a_add_ops_system_logs_host_index_notx.sql
+75c6ab5b748433e072e227a9070d5c2f22adfe1d333be85445397f784efda308 176_channel_monitor_grok_provider.sql
+a7f4acf8fce09251585d76285a012675dc8baef120ef482e4d37c42019c81121 177_add_subscription_plan_currency.sql
+3b29a39d97a09d0e53ca66e5ba27847d7fb1cc3c13c09231faf4f55538fbe8af 178_channel_image_input_price.sql
+3b44efea7792d34d9b73d94c9ec93f622dd4d8987758443d07c98ccea651c0d1 179_usage_log_image_input_tokens.sql
+c34448727c106179ff72b25f6c0583f56e9985912695678f09457e2f51f9e69b 180_audit_logs.sql
+429011c514dfa3a65dd844cb19dfe32ceeae4068f499b15f915cee97687ed7bd 181_group_duplicate_operation_id.sql
+95968781819c2bb5fa8324dc2b5f576a769e9765ef51bd190cdad894e8be73ca 181_prompt_audit.sql
+e133a1a391dc048053aa0a843ea9ec9843ee94dc31cfd42aa30d9d910c493d8d 182_prompt_audit_full_prompt.sql
+16a2ffccfe0f03451ab5ab6edfe252501d09c5c8927e27d87bbc3f826a5d8871 183_ops_ingress_reject_aggregates.sql
+870ff546e67a8c59f99310fab34e2101af71332eea50fff17a6bfb2a4d0fdc7a 184_auth_cache_invalidation_outbox.sql
+043489b1e240068b949b15ac2f0edb6255503a544b0301cbff16274fb43ca3fd 185_group_reasoning_effort_policy.sql
+7b64b8493a6e2896f798e428e7302b23d1e03ee8b58b31566c67dbfbccbfe96a 186_alipay_mobile_precreate_deep_link.sql
+e4c8272402c47adf29583d21c05346d3d6fc00e3b8d5f4ad1184d0dce7ed9ec7 186_group_auth_cache_image_generation.sql
+3f6a27f01ce117cb981557d2bea847faa1893af8d147772b0159b3a0558181ec 187_add_usage_log_session_id.sql
+0233dba07a75bd9c740402a64e3af75c2a3884dfc8c4b63145df115e716fd35e 188_allow_live_usage_request_type.sql
+51172b10c160e7f560346dbaf736dc8e92feb793cd00169f5fb876c399460862 189_add_group_allow_live.sql
+14f65700704f92ca397d407bba98b5719c38503a7085a3253fabfc08b1c2dac5 190_add_users_email_alias_dedup_index_notx.sql
+d79e7093f28b1a2ba923da35d7376423683c9a5d21dffd0e581f3c45b5afd817 191_passkey_credentials.sql
+c128560346272041ce20dbed1d54955b7be95ca614bc1cd821a1b3b0adc37063 192_group_profit_control.sql
+5ab25a32239e64c6a6318ed71b72f1456b9e6fc6d4c06d162601af741cb16dd5 193_group_profit_control_auth_cache_invalidation.sql
+cad520cbfcf7af7ea9acae92e5bcbe27501fd9e3ad5b02e306f4f97be4410a82 194_add_usage_log_upstream_response_model.sql
+efe5668b284b3e0e7a27a6ebb138fb03aeeeb3593117232733b1f4cc13c9e2c1 194_channel_monitor_v2.sql
+692f2a75f0c62670b4d68986912bf24eb92f6377ec904d3806ff7d62b0da8355 195_add_usage_log_upstream_model_mismatch_index_notx.sql
+73c39ac374c722253135041466108836845828a6065b499c60e7f27d6b92c21c 195_channel_monitor_mode.sql
+75520645fc43e15b8d48bb28ce49c0e1633414db4267cba99ed1e4b2b334b7c4 196_channel_monitor_v2_ignored_error_categories.sql
+23d0489c1b421bc6d7c91bbfcb7006eb49a0d107f1e5ee441cc6502f8b280cbb 197_channel_monitor_v2_seed_popular_models.sql
+3e996b6f92520e657905964c9e9fc7f2a370e00ebcf1d43c9ad5df0412fb4e71 198_channel_monitor_v2_health_thresholds.sql
+6b11bb6342c385b3ecb27ab42d2ddf3d7eeda0d36d0dd804c66b33fb6310c7b5 199_channel_monitor_v2_fixed_rollups.sql
+86d16854b17a096c8e1dbd7e4897b30aabcd74adaee1390d7e7c5b0c4cea8e84 200_channel_monitor_v2_rollup_permissions.sql
+d5f3cf24c2ee94eb872cc9fa6508929886bcf779f5b0d7ba71ef450c58699601 201_channel_monitor_v2_refresh_5m.sql
+7d944e39abd71fee4845dac933536f3f891fcfd7fb926e1187b4e8a49b6edc3e 202_channel_monitor_v2_full_table_permissions.sql
+ae54ca5d660438136f559cf2b65dae15399281de195a19159d03ec596de4bb98 203_channel_monitor_v2_default_ignore_and_cache.sql
+772dc9127edd5af6eefd25b12c7b23752c0701537c4d8815ba3672c1ad65c3ba 204_channel_monitor_hide_throughput.sql
+9cc91f869c03ba5cc46696575959cbd1b74ba0e9ad380bcbc3a422259eddff80 205_channel_monitor_v2_reset_factory_cache_thresholds.sql
+e2bdbcafac7f07aa9eebc804dde013e3eef506a6b3a323d8548b01b8796905cd 206_channel_monitor_v2_privacy_defaults.sql
+e335f1b68ed1349661fab51bf4669619b7b116df31c1fb974c844b1c8a2f84d3 217_group_video_model_prices.sql
+a99ade7d0d464c67bf56814570050cc363ffad64eae2cb1e1ed760065f0b3585 218_group_audio_voice_pricing.sql
+430c2e3595342fe22c59e9676e9b18ea376f076324b77174a21e6f181f57f4b5 219_group_search_price_per_1k.sql
+cf4dbfa75ac27d93a30a6a14439fe7dccfc911c043358363d5ec47946aa0e28b 220_clear_non_grok_video_generation_config.sql
+1ba1940ef00e9a3831ec2afa90495660daba9191bfec311567228ed2a6e180e3 221_group_model_pricing.sql
+d1dea80dd961e8f4016ce95dc413ee28344adf6fce9964427452a95cb7dfc16f 222_group_usage_daily_rollups.sql
+68ab749e218a893f7c54d856510c8f8eb462d7ce4d8e300d5fa8b6a17cf631cc 223_group_usage_rollup_timezone.sql
+5227db3c1a6a1e2e422a9f9ba9d1f490c708b6c6dd91ce89f3c48115421a3e55 224_user_platform_quotas_add_cn_providers.sql
+bd8d6dff505e417eee69a2da300aa1df06e832fd668c7848f06944c7c0c3fd26 225_backfill_codex_fingerprint_seed.sql
+23f0a4da20f2f78f385e9f1cd1ed57db1a31b99b1ba54b0f498985e3a66647b1 225_channel_model_time_pricing.sql
+8b85d3a071e0822f75244cc242dbf56df83ac85f7fdca3940590185335b5c239 226_add_usage_log_effective_model_indexes_notx.sql
+c36c6c0ec6cc8727bb986e8cdc645990dcf8dad8f56a8c4647422e24e9dff88d 226_channel_monitor_quota_mode.sql
+ff6e3323b4bcb195a4f11bfa9b1b22286e77169f551b5c4294ab3d31828d8ff8 227_composite_routes_add_cn_providers.sql
+3d7c36d49e509b69f479e0a5b05d4074c49ea7ba8117f12f82764f09d6e3b542 228_channel_pricing_multipliers.sql
+b1e97991df385eba0f62426572d7d58a0ef5c96a876df356ba070cca68e88896 229_plugins.sql
+f33a1a3fdf1f0645a6813a5f87c344a18017193243133c4f45471dad3748d664 230_plugin_artifacts.sql
+7ab597b658dafa31f2b1d64b6057ff9e4c2da5a3b0e6581962d15d66f91ebfe4 231_add_usage_log_native_compaction_v2.sql
+a67f2a9dfeaa2bf935801727d97dc2def72e03d6c4e0bf9d503a4f88a03b3851 231_add_usage_log_requested_reasoning_effort.sql
+9867df4258aa7c4e55db96998ed07f4369032c6469dcf146a13c9906bb243514 231_user_restrict_public_groups.sql
+12c37559a68e6708a36d7f4c020fb20dfa07906639f1eeb3396d60a8069b864d 232_add_usage_log_upstream_request_id.sql
+62279a094bfd2090c4bc8e54e9fb45fd14ca3c361d6dccd2e068361d053dda80 232_channel_cache_write_1h_pricing.sql
+47ac2b5f0c50685538b642a9ecdd1aaa4fcd820390a4b8b87983a2805dbe1c78 232_group_force_openai_fast.sql
+b503ea8571f4f16c3f7de0d45b9035693ee15d708e0c19feb30e247646f00bd6 232_group_reasoning_effort_over_limit.sql
+87dea0c4b1d33209eee098cf472ca661011670b7910ebbcf7a611c69db737136 233_add_usage_log_upstream_request_id_index_notx.sql
+80925a7deb54ef23ed5fae1eb1e519764d3952686be7101e2cf739028269f9c3 233_group_free_openai_fast.sql
+e8f7749b4ed75ab1265a72c4d78b5139374d1edaeb6a4a5070f7f9593fa2bd4f 234_channel_max_reasoning_effort_multiplier.sql
+dfab2c7f97f83c77635b5f0d0c19ec9e849cbcd0bf7833583fb6197eac306e7b 234_group_codex_models_manifest_config.sql
+546fd53d114f9a8c402b019af71bf4685dc1968fd5cd25d054d095a58d806fbc 235_group_model_allowlist.sql
+0d8fbcd98750be1a58cec45fe2b866031b656ac6286b073ca061f8fa8fdc040e 236_group_model_allowlist_repair.sql
+f4c73d2dbce114ca7ade1aac51998c3465490f4f3c9b3e868e53590f3fa8601b 237_add_minimax_platform.sql
+6f987e251519bd3759e60da44620a5d777494cceb333b6ce394aa0ea536ef5a2 238_opencode_go_platform.sql
+052756d1b1ac951f002034bf0434f8a6ea943ec0a2a34541ca4374ba6278cce7 238_purge_unlimited_user_platform_quotas.sql
+420af91eec85bdb60474640612a0f4d069db6ddfb21e6ed702b89713f3599287 238b_content_moderation_engine_meta.sql
+66feb546785dfa385d8efd268a40276cd8ffdb0cead7026cd79e339a3b69edf1 239_channel_reasoning_effort_multipliers.sql
+3823bfea5f64feb58f5fcebc341c6877eaefc97834b4cd652c8e83ad08ed78da 240_affiliate_ledger_operation_id.sql
+18b6a524a9873d3e4a45e6f9bd03b6e69f4384b701825c659817e017f2e8244f 241_add_payment_order_bonus_amount.sql
+b6559525bf8d0b5d7c617e7415944f0d1fae8c408e9131ace84139795f66dcd2 241_add_typesafe_platform.sql
+a7725f31f637208d200e0f37d5270e9f263743d99fa9e4f1bb9a7387e8be5a61 242_drop_platform_check_constraints.sql
+e81c6818cc806bc54365c993f4cec1634f16a311451faf5cb1a875a1358774cd 242_group_i18n.sql
+2d345cff5c64b01e705f04ec972e5d5ec3d618fe71dc7d45bc80fdd38c6a89d5 243_gemini_cached_contents.sql
+9072cb37752a23c3a29cc0330a69837f09c5102375ee053d7bccf14634d3da29 244_gemini_cached_contents_channel_usage.sql
+75434a7beeb8aad09b3339708ed520604d153e99c7fe680a376e8c958aadb1e8 245_gemini_cached_contents_mutation_lease.sql
diff --git a/backend/migrations/upstream_checksums_test.go b/backend/migrations/upstream_checksums_test.go
new file mode 100644
index 000000000..061582cbd
--- /dev/null
+++ b/backend/migrations/upstream_checksums_test.go
@@ -0,0 +1,42 @@
+package migrations
+
+import (
+ "bufio"
+ "crypto/sha256"
+ "encoding/hex"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// 上游 Sub2API 的迁移文件必须原样保留:库在 Sub4API 与上游之间切换时,
+// migrations_runner 会按 checksum 校验已应用的迁移。需要调整时请新增 Sub4API 迁移。
+// 清单由 scripts/sync-upstream-migration-checksums.sh 生成。
+func TestUpstreamMigrationsAreUnmodified(t *testing.T) {
+ f, err := os.Open("upstream_checksums.txt")
+ require.NoError(t, err)
+ defer func() { _ = f.Close() }()
+
+ entries := 0
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ fields := strings.Fields(line)
+ require.Lenf(t, fields, 2, "malformed line: %q", line)
+ want, name := fields[0], fields[1]
+ entries++
+
+ content, err := FS.ReadFile(name)
+ require.NoErrorf(t, err, "upstream migration %s is missing", name)
+ sum := sha256.Sum256([]byte(strings.TrimSpace(string(content))))
+ require.Equalf(t, want, hex.EncodeToString(sum[:]),
+ "upstream migration %s was modified; restore it and add a new Sub4API migration instead", name)
+ }
+ require.NoError(t, scanner.Err())
+ require.NotZero(t, entries)
+}
diff --git a/backend/resources/model-pricing/model_prices_and_context_window.json b/backend/resources/model-pricing/model_prices_and_context_window.json
index 99db4dbbd..5e0f608d2 100644
--- a/backend/resources/model-pricing/model_prices_and_context_window.json
+++ b/backend/resources/model-pricing/model_prices_and_context_window.json
@@ -381,6 +381,40 @@
"supports_tool_choice": true,
"supports_vision": true
},
+ "claude-haiku-5-5": {
+ "cache_creation_input_token_cost": 1.25e-07,
+ "cache_creation_input_token_cost_above_1hr": 2e-07,
+ "cache_creation_input_token_cost_above_100k_tokens": 6.25e-07,
+ "cache_creation_input_token_cost_above_1hr_above_100k_tokens": 1e-06,
+ "cache_read_input_token_cost": 1e-08,
+ "cache_read_input_token_cost_above_100k_tokens": 5e-08,
+ "input_cost_per_token": 1e-07,
+ "input_cost_per_token_above_100k_tokens": 5e-07,
+ "litellm_provider": "anthropic",
+ "max_input_tokens": 1000000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "chat",
+ "output_cost_per_token": 5e-07,
+ "output_cost_per_token_above_100k_tokens": 2.5e-06,
+ "source": "https://platform.claude.com/docs/en/models/haiku-5-5/overview",
+ "supports_adaptive_thinking": true,
+ "supports_assistant_prefill": false,
+ "supports_computer_use": true,
+ "supports_function_calling": true,
+ "supports_max_reasoning_effort": true,
+ "supports_output_config": true,
+ "supports_pdf_input": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_response_schema": true,
+ "supports_sampling_params": false,
+ "supports_tool_choice": true,
+ "supports_vision": true,
+ "supports_xhigh_reasoning_effort": true,
+ "input_cost_per_token_batches": 5e-08,
+ "output_cost_per_token_batches": 2.5e-07
+ },
"claude-opus-4-1": {
"cache_creation_input_token_cost": 1.875e-05,
"cache_creation_input_token_cost_above_1hr": 3e-05,
@@ -2616,22 +2650,56 @@
"web_search_billing_unit": "per_query"
},
"gemini-3.6-flash": {
- "cache_read_input_token_cost": 1.5e-07,
- "cache_read_input_token_cost_priority": 2.7e-07,
- "input_cost_per_token": 1.5e-06,
- "input_cost_per_token_priority": 2.7e-06,
+ "cache_read_input_token_cost": 7.5e-08,
+ "cache_read_input_token_cost_priority": 1.35e-07,
+ "input_cost_per_token": 7.5e-07,
+ "input_cost_per_token_priority": 1.35e-06,
"litellm_provider": "vertex_ai-language-models",
"max_input_tokens": 1048576,
"max_output_tokens": 65536,
"max_tokens": 65536,
"mode": "chat",
- "output_cost_per_token": 7.5e-06,
- "output_cost_per_token_priority": 1.35e-05,
+ "output_cost_per_token": 3.75e-06,
+ "output_cost_per_token_priority": 6.75e-06,
"source": "https://ai.google.dev/gemini-api/docs/latest-model",
"supports_prompt_caching": true,
"supports_reasoning": true,
"supports_service_tier": true
},
+ "gemini-4-argon": {
+ "cache_read_input_token_cost": 1e-07,
+ "cache_read_input_token_cost_priority": 1.8e-07,
+ "input_cost_per_token": 2e-06,
+ "input_cost_per_token_priority": 3.6e-06,
+ "litellm_provider": "gemini",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65536,
+ "max_tokens": 65536,
+ "mode": "chat",
+ "output_cost_per_token": 1e-05,
+ "output_cost_per_token_priority": 1.8e-05,
+ "source": "https://ai.google.dev/gemini-api/docs/pricing",
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_service_tier": true
+ },
+ "gemini-4-argon-cyber-permissive": {
+ "cache_read_input_token_cost": 2e-07,
+ "cache_read_input_token_cost_priority": 3.6e-07,
+ "input_cost_per_token": 4e-06,
+ "input_cost_per_token_priority": 7.2e-06,
+ "litellm_provider": "vertex_ai-language-models",
+ "max_input_tokens": 1048576,
+ "max_output_tokens": 65536,
+ "max_tokens": 65536,
+ "mode": "chat",
+ "output_cost_per_token": 2e-05,
+ "output_cost_per_token_priority": 3.6e-05,
+ "source": "https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing",
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_service_tier": true
+ },
"gemini-embedding-001": {
"input_cost_per_token": 1.5e-07,
"litellm_provider": "vertex_ai-embedding-models",
diff --git a/changelog/1.1.11/CHANGELOG.md b/changelog/1.1.11/CHANGELOG.md
new file mode 100644
index 000000000..5c4d45c3e
--- /dev/null
+++ b/changelog/1.1.11/CHANGELOG.md
@@ -0,0 +1,32 @@
+# v1.1.11
+
+## 更新内容
+
+- 合并 SUB2API 0.2.16 ~ 0.2.17 版本。
+
+## 新增功能
+
+- 打票设置新增「打票出口 IP」选项,可选择打票请求从哪个 IP 发出:
+ - **使用打票代理池(默认)**:与之前一致,在「IP管理」页配置的 Codex 打票代理池中轮换;池内没有可用代理时不打票,不会直连。
+ - **使用账号自身的代理**:用账号绑定的代理打票,打票 IP 与该账号业务请求的出口一致;账号未绑定代理时直连(使用服务器 IP)。
+- OpenAI 账号「请求时区」新增「跟随 IP 出口」模式:新建账号、修改账号代理(含批量修改、切回原代理)或切换到该模式后,自动检测出口 IP 所在地的时区,并用于该账号请求的环境上下文;未绑定代理的账号按服务器 IP 检测。编辑账号时可查看检测到的出口 IP、所在地和时区,并可「重新检测」。
+
+## 优化改进
+
+- 优化打票相关设置的提示文案:「打票出口 IP」的每个选项都说明了实际出口与无可用代理时的行为;「IP管理」页的 Codex 打票代理池说明中注明仅在选择代理池模式时生效。
+- 选择「使用账号自身的代理」时,手动打票不再因代理池为空而不可用。
+
+## 问题修复
+
+- 修复「IP管理」页 Codex 打票代理池的保存状态与页面显示不一致,导致打票实际使用的代理与所选代理不符的问题:
+ - 代理池顶部常驻显示「当前打票轮换」的代理;「打票出口 IP」为账号自身代理时提示代理池不生效。
+ - 有未保存的修改时提示并高亮「保存代理池」,离开页面前二次确认;保存后以服务器结果为准。
+ - 页面加载完成前不可操作,避免加载结果覆盖刚做的勾选;在本页新增、编辑、删除代理后,代理池列表同步刷新。
+ - 已删除或停用但仍被勾选的代理会单独列出、可移除,保存时不再带上;已过期的代理标注「不参与打票」。
+- 修复数据库迁移 `241_add_typesafe_platform.sql` 被本地改动后与 SUB2API 上游校验和不一致的问题:该文件恢复为上游原样,存在 OpenAI BPS 账号时由新增的 Sub4API 迁移跳过该约束,并自动修正此前版本记录的校验和,升级时不再报 checksum mismatch;同时新增上游迁移校验和清单与测试,防止再次改动上游迁移文件。
+
+## 升级说明
+
+- 新建 OpenAI 账号的「请求时区」默认为「跟随 IP 出口」;已添加的账号不做修改,继续使用原来的固定时区(默认新加坡),如需跟随出口 IP 请在编辑账号时切换。时区检测失败时沿用上次检测结果,从未成功过则使用新加坡。
+- 新设置默认使用打票代理池,升级后打票行为不变;如需改为账号自身的代理,请在「系统设置 → 网关 → Codex」中调整「打票出口 IP」后点击「保存设置」。
+- 新版首次启动会自动执行 SUB2API 0.2.16 带来的数据库迁移(分组多语言、Gemini 显式缓存相关表)。
diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml
index 9754930e9..19b7559b8 100644
--- a/deploy/config.example.yaml
+++ b/deploy/config.example.yaml
@@ -217,6 +217,9 @@ security:
# 网关配置
# =============================================================================
gateway:
+ # Minimum max_output_tokens when converting Chat Completions or Anthropic requests to Responses (minimum 16, default 128)
+ # Chat Completions 或 Anthropic 请求转换为 Responses 时的最小 max_output_tokens(最小 16,默认 128)
+ min_output_tokens: 128
# Timeout for waiting upstream response headers (seconds)
# 等待上游响应头超时时间(秒)
response_header_timeout: 600
@@ -253,6 +256,9 @@ gateway:
# Enable Gemini upstream response header debug logs (default: false)
# 是否开启 Gemini 上游响应头调试日志(默认 false)
gemini_debug_response_headers: false
+ # Maximum TTL (seconds) a Gemini explicit context cache may be created or extended to (default: 86400)
+ # Gemini 显式上下文缓存单次可设置的最长有效期(秒,默认 86400);存储费在创建/延长请求中一次性收取
+ gemini_cached_content_max_ttl_seconds: 86400
# Connection pool isolation strategy:
# 连接池隔离策略:
# - proxy: Isolate by proxy, same proxy shares connection pool (suitable for few proxies, many accounts)
@@ -318,6 +324,8 @@ gateway:
# OpenAI /responses/compact 上游模型(默认 gpt-5.5)。
# Use this to avoid compact failures when newer models are not yet supported by the compact endpoint.
# 当 compact 端点暂未支持更新模型时,可通过这里降级规避失败。
+ # GPT-5.5 is API-only after its ChatGPT Codex retirement; subscription
+ # requests skip this retired fallback and keep their selected model.
openai_compact_model: "gpt-5.5"
# ChatGPT OAuth x-codex-turn-state ticket: harvest a 292-length header via a
# dedicated HTTP(S)/SOCKS proxy, store it for ttl_seconds (default 3600), then inject
@@ -1129,6 +1137,14 @@ pricing:
# 覆盖补丁文件(可选,优先级最高):条目按字段浅合并覆盖目录/回退数据,
# 字段值为 null 表示删除该字段。模型名须与目录键完全一致。
# 修改后在下一次哈希检查时按内容哈希自动重载,无需重启。
+ # Gemini explicit context caching storage price (USD per token per hour) comes
+ # from the field cache_storage_cost_per_token_per_hour here, e.g.
+ # {"gemini-3.8-flash": {"cache_storage_cost_per_token_per_hour": 0.0000005}};
+ # without it, built-in official prices apply (released models first, then the
+ # Pro / Flash series rate). Models with no price at all reject POST /v1beta/cachedContents.
+ # Gemini 显式缓存存储单价(每 token 每小时,USD)优先取这里的 cache_storage_cost_per_token_per_hour 字段,
+ # 未配置时使用内置官方价(先按已发布型号,再按 Pro / Flash 系列兜底);两者都没有的模型拒绝创建缓存。
+ # 目录中不存在的模型条目还须同时提供 input_cost_per_token / output_cost_per_token。
# override_file: "./data/model_pricing_overrides.json"
# Update interval in hours
# 更新间隔(小时)
diff --git a/docs/OPENAI_GPT55_RETIREMENT.md b/docs/OPENAI_GPT55_RETIREMENT.md
new file mode 100644
index 000000000..3c261373d
--- /dev/null
+++ b/docs/OPENAI_GPT55_RETIREMENT.md
@@ -0,0 +1,43 @@
+# GPT-5.5 retirement on ChatGPT-backed Codex accounts
+
+OpenAI retired GPT-5.5 from Codex with ChatGPT sign-in on October 14,
+2026 at 19:00 UTC (October 15 at 03:00 in Asia/Shanghai). Official API access
+is unaffected. See the [official migration notice](https://learn.chatgpt.com/docs/models#gpt-55-retirement).
+
+Sub2API applies this distinction to the upstream account, not the key used by
+clients to authenticate to Sub2API:
+
+- OpenAI OAuth and SetupToken accounts, including credential shadows, cannot
+ serve GPT-5.5. Normal, sticky, and compact scheduling exclude these targets.
+- API-key accounts retain GPT-5.5 support. In mixed groups, only eligible API-key
+ upstreams can serve it. Their actual model availability remains authoritative.
+- Public model lists and Codex catalogs omit models whose targets are retired on
+ the group's ChatGPT accounts and have no supporting API-key account. This also
+ filters stale/pinned catalog entries before calculating the client ETag.
+- Explicit administrator mappings to a supported replacement remain valid.
+ Aliases mapped *to* GPT-5.5 are excluded from ChatGPT account routing.
+ Remote catalogs are projected to public aliases before retirement filtering,
+ using the same single mapping step as routing. Source metadata and shared
+ upstream caches are preserved, including when source IDs are also alias keys.
+- Unsupported requests return the existing `model_not_found` error with migration
+ guidance when the availability diagnosis identifies a retired subscription
+ target. Client chat requests are not silently rewritten to a replacement.
+
+## Administrator migration
+
+Review group/account mappings, client defaults, custom agents and scheduled tasks
+that select GPT-5.5. OpenAI recommends GPT-6.1 Sol for eligible paid plans or
+GPT-6 Luna for Free/Go in the desktop app, subject to model availability. Check
+availability on the upstream account before selecting a replacement.
+
+The global `gateway.openai_compact_model` setting remains compatible with API-key
+upstreams. If that fallback resolves to retired GPT-5.5 on a ChatGPT account, it
+is not applied; compact requests keep their selected model. A compact-only
+account mapping targeting retired GPT-5.5 is ineligible for scheduling: update
+that explicit mapping. No stored settings are automatically rewritten.
+
+Changing the public registry, deleting GPT-5.5 pricing/history, or globally
+mapping GPT-5.5 to a new model is unnecessary and would affect valid API usage.
+
+Regression tests use local fixtures and stub upstream responses. They do not
+establish real subscription access to a replacement model.
diff --git a/frontend/src/api/admin/accounts.ts b/frontend/src/api/admin/accounts.ts
index 3f15db56a..a1de63dd1 100644
--- a/frontend/src/api/admin/accounts.ts
+++ b/frontend/src/api/admin/accounts.ts
@@ -1136,10 +1136,16 @@ export async function getOpenAIRequestTimezones(): Promise<{ default: string; ti
return data
}
+export async function detectOpenAIRequestTimezone(id: number): Promise {
+ const { data } = await apiClient.post(`/admin/accounts/${id}/openai-request-timezone/detect`)
+ return data
+}
+
export const accountsAPI = {
list,
listWithEtag,
getOpenAIRequestTimezones,
+ detectOpenAIRequestTimezone,
getUpstreamBillingRatesWithEtag,
getById,
create,
diff --git a/frontend/src/api/admin/codexTickets.ts b/frontend/src/api/admin/codexTickets.ts
index c57c69f94..db2a21b65 100644
--- a/frontend/src/api/admin/codexTickets.ts
+++ b/frontend/src/api/admin/codexTickets.ts
@@ -111,6 +111,17 @@ export async function saveCadence(value: { retry_min_seconds: number; retry_max_
await apiClient.put('/admin/accounts/codex-ticket-cadence', value)
}
+export type TicketProxySource = 'pool' | 'account'
+
+export async function proxySource(): Promise<{ source: TicketProxySource }> {
+ const { data } = await apiClient.get('/admin/accounts/codex-ticket-proxy-source')
+ return data
+}
+
+export async function saveProxySource(source: TicketProxySource): Promise {
+ await apiClient.put('/admin/accounts/codex-ticket-proxy-source', { source })
+}
+
export interface TicketParticipation {
enabled: boolean
models: Record
diff --git a/frontend/src/components/account/AccountGroupsCell.vue b/frontend/src/components/account/AccountGroupsCell.vue
index 37771275f..98b80d8f3 100644
--- a/frontend/src/components/account/AccountGroupsCell.vue
+++ b/frontend/src/components/account/AccountGroupsCell.vue
@@ -1,7 +1,7 @@
-
-
diff --git a/frontend/src/components/account/AccountTestModal.vue b/frontend/src/components/account/AccountTestModal.vue
index 5192d0b66..4ef3c50a9 100644
--- a/frontend/src/components/account/AccountTestModal.vue
+++ b/frontend/src/components/account/AccountTestModal.vue
@@ -298,7 +298,7 @@ const supportsGeminiImageTest = computed(() => {
const modelID = selectedModelId.value.toLowerCase()
if (!modelID.startsWith('gemini-') || !modelID.includes('-image')) return false
- return props.account?.platform === 'gemini' || (props.account?.platform === 'antigravity' && props.account?.type === 'apikey')
+ return props.account?.platform === 'gemini' || props.account?.platform === 'antigravity'
})
const supportsOpenAIImageTest = computed(() => {
diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue
index 16b165a49..6a41016da 100644
--- a/frontend/src/components/account/AccountUsageCell.vue
+++ b/frontend/src/components/account/AccountUsageCell.vue
@@ -492,6 +492,7 @@
-
+
{{ t('admin.accounts.gemini.rateLimit.unlimited') }}
@@ -597,7 +598,7 @@
-
+
void) | null = null
let visibilityObserver: IntersectionObserver | null = null
+// Gemini 第三方上游 API Key:没有 AI Studio 等级与本地模拟配额
+const isGeminiThirdPartyApiKey = computed(() => {
+ if (props.account.platform !== 'gemini' || props.account.type !== 'apikey') return false
+ const creds = props.account.credentials as GeminiCredentials | undefined
+ return !isOfficialGeminiBaseUrl(creds?.base_url)
+})
+
+const isGeminiVertex = computed(() => {
+ return props.account.platform === 'gemini' && props.account.type === 'service_account'
+})
+
// Show usage windows for OAuth and Setup Token accounts
const showUsageWindows = computed(() => {
// Gemini: we can always compute local usage windows from DB logs (simulated quotas).
- if (props.account.platform === 'gemini') return true
+ // 第三方上游 API Key 没有模拟配额,按普通 Key 账号展示今日统计与额度进度条。
+ if (props.account.platform === 'gemini') return !isGeminiThirdPartyApiKey.value
// 多协议 API Key 供应商:apikey 账号也有滚动用量窗口(coding plan / 订阅)或余额,
// 由 CNProviderQuotaCell / CNProviderBalanceCell 自行探测与展示。
if (isMultiProtocolApiKeyPlatform(props.account.platform)) {
@@ -776,7 +790,7 @@ const shouldFetchUsage = computed(() => {
return props.account.type === 'oauth' || props.account.type === 'setup-token'
}
if (props.account.platform === 'gemini') {
- return true
+ return !isGeminiThirdPartyApiKey.value && !isGeminiVertex.value
}
if (props.account.platform === 'antigravity') {
return props.account.type === 'oauth'
@@ -797,8 +811,9 @@ const cnBalanceCellVisible = computed(() => cnBalanceCellVisibleFn(props.account
const isBatchManaged = computed(() => typeof props.requestBatchedUsage === 'function')
+// Vertex 没有本地模拟配额,用量窗口展示今日统计
const showGeminiTodayStats = computed(() => {
- return props.account.platform === 'gemini' && props.account.type === 'service_account'
+ return isGeminiVertex.value
})
const geminiUsageAvailable = computed(() => {
@@ -962,6 +977,10 @@ const geminiOAuthType = computed(() => {
return (creds?.oauth_type || '').trim() || null
})
+const showGeminiQuotaPolicy = computed(() => {
+ return !isGeminiVertex.value
+})
+
// Gemini 是否为 Code Assist OAuth
const isGeminiCodeAssist = computed(() => {
if (props.account.platform !== 'gemini') return false
@@ -969,9 +988,10 @@ const isGeminiCodeAssist = computed(() => {
return creds?.oauth_type === 'code_assist' || (!creds?.oauth_type && !!creds?.project_id)
})
-const geminiChannelShort = computed((): 'ai studio' | 'gcp' | 'google one' | 'client' | null => {
+const geminiChannelShort = computed((): 'ai studio' | 'vertex' | 'gcp' | 'google one' | 'client' | null => {
if (props.account.platform !== 'gemini') return null
+ if (isGeminiVertex.value) return 'vertex'
// API Key accounts are AI Studio.
if (props.account.type === 'apikey') return 'ai studio'
@@ -985,6 +1005,7 @@ const geminiChannelShort = computed((): 'ai studio' | 'gcp' | 'google one' | 'cl
const geminiUserLevel = computed((): string | null => {
if (props.account.platform !== 'gemini') return null
+ if (isGeminiVertex.value) return null
const tier = (geminiTier.value || '').toString().trim()
const tierLower = tier.toLowerCase()
@@ -1042,7 +1063,7 @@ const geminiTierClass = computed(() => {
const channel = geminiChannelShort.value
const level = geminiUserLevel.value
- if (channel === 'client' || channel === 'ai studio') {
+ if (channel === 'client' || channel === 'ai studio' || channel === 'vertex') {
return 'bg-blue-100 text-blue-600 dark:bg-blue-900/40 dark:text-blue-300'
}
diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue
index 1f0c509d7..b21a2d1a3 100644
--- a/frontend/src/components/account/CreateAccountModal.vue
+++ b/frontend/src/components/account/CreateAccountModal.vue
@@ -391,8 +391,8 @@
- Vertex
- Service Account
+ {{ t('admin.accounts.vertexLabel') }}
+ {{ t('admin.accounts.vertexDesc') }}
@@ -840,17 +840,18 @@
- Vertex
+ {{ t('admin.accounts.vertexLabel') }}
- Service Account
+ {{ t('admin.accounts.vertexGeminiDesc') }}
{{ t('admin.accounts.gemini.accountType.apiKeyNote') }}
@@ -1078,7 +1079,7 @@
-
+
{{ t('admin.accounts.gemini.tier.label') }}
-
-
Service Account JSON
-
-
-
-
-
-
- {{ vertexClientEmail ? t('admin.accounts.vertexSaJsonLoaded') : t('admin.accounts.vertexSaJsonDrop') }}
-
-
- {{ vertexClientEmail ? t('admin.accounts.vertexSaJsonKeyHidden') : t('admin.accounts.vertexSaJsonDropHint') }}
-
-
-
-
- {{ t('admin.accounts.vertexSaJsonSelectBtn') }}
-
-
-
-
Project ID: {{ vertexProjectId }}
-
Client Email: {{ vertexClientEmail }}
-
+
-
+
-
Project ID
+
API Key
+
{{ t('admin.accounts.vertexApiKeyHint') }}
+
+
+
Project ID
+
+
{{ t('admin.accounts.vertexApiKeyProjectIdHint') }}
+
+
+
Location
+
+
+
+ {{ option.label }}
+
+
+
+
{{ t('admin.accounts.vertexLocationHint') }}
+
+
+
+
+
-
Location
-
Service Account JSON
+
+
-
+
+
+
+ {{ vertexClientEmail ? t('admin.accounts.vertexSaJsonLoaded') : t('admin.accounts.vertexSaJsonDrop') }}
+
+
+ {{ vertexClientEmail ? t('admin.accounts.vertexSaJsonKeyHidden') : t('admin.accounts.vertexSaJsonDropHint') }}
+
+
+
+
+ {{ t('admin.accounts.vertexSaJsonSelectBtn') }}
+
+
+
- Project ID: {{ vertexProjectId }}
+ Client Email: {{ vertexClientEmail }}
+
+
+
{{ t('admin.accounts.vertexSaJsonUploadHint') }}
+
+
+
+
+ Project ID
+
+
+
+
Location
+
+
- {{ option.label }}
-
-
-
-
{{ t('admin.accounts.vertexLocationHint') }}
+
+ {{ option.label }}
+
+
+
+
{{ t('admin.accounts.vertexLocationHint') }}
+
-
+
@@ -1512,9 +1590,9 @@
-
+
{{ t('admin.accounts.gemini.tier.label') }}
-
+
{{ t('admin.accounts.gemini.tier.aiStudio.free') }}
{{ t('admin.accounts.gemini.tier.aiStudio.paid') }}
@@ -1777,6 +1855,48 @@
+
+
+
+
+
{{ t('admin.accounts.explicitCacheUpstream') }}
+
+ {{ t('admin.accounts.explicitCacheUpstreamHint') }}
+
+
+
+
+
+
+
+ {{ t('admin.accounts.explicitCacheUpstreamInfo') }}
+
+
+
+
{{ t('admin.accounts.explicitCacheUpstreamMaxTTL') }}
+
+
+ {{ t('admin.accounts.explicitCacheUpstreamMaxTTLHint') }}
+
+
+
+
@@ -2623,6 +2743,44 @@
:placeholder="t('admin.accounts.tempUnschedulable.durationPlaceholder')"
/>
+
+
{{ t('admin.accounts.tempUnschedulable.scope') }}
+
+
+
+
+
+
+ {{ option.label }}
+ {{ option.description }}
+
+
+
+
{{ t('admin.accounts.tempUnschedulable.scopeHint') }}
+
{{ t('admin.accounts.tempUnschedulable.keywords') }}
-
+
{
case 'openai':
return 'sk-proj-...'
case 'gemini':
- return 'AIza...'
+ return 'AQ.Ab...'
case 'grok':
return 'xai-...'
case 'kimi':
@@ -4265,6 +4426,8 @@ interface TempUnschedRuleForm {
keywords: string
duration_minutes: number | null
description: string
+ // 作用范围:account 暂停整个账号,model 只冷却本次请求的模型。
+ scope: TempUnschedulableScope
}
// State
@@ -4515,6 +4678,8 @@ const DEFAULT_POOL_MODE_RETRY_COUNT = 3
const MAX_POOL_MODE_RETRY_COUNT = 10
const DEFAULT_POOL_MODE_RETRY_STATUS_CODES = [401, 403, 429]
const poolModeEnabled = ref(false)
+const explicitCacheUpstreamEnabled = ref(false)
+const explicitCacheUpstreamMaxTTL = ref
('')
const poolModeRetryCount = ref(DEFAULT_POOL_MODE_RETRY_COUNT)
const poolModeRetryStatusCodesInput = ref('')
@@ -4579,6 +4744,7 @@ const interceptWarmupRequests = ref(false)
const autoPauseOnExpired = ref(true)
const openaiPassthroughEnabled = ref(false)
const openAIRequestTimezone = ref('Asia/Singapore')
+const openAIRequestTimezoneMode = ref('follow_proxy')
// OpenAI Codex namespace 工具摊平兼容开关(仅 OAuth),缺省关闭即原样保留
const openaiFlattenNamespacesEnabled = ref(false)
const openAILongContextBillingEnabled = ref(false)
@@ -4651,6 +4817,17 @@ const vertexProjectId = ref('')
const vertexClientEmail = ref('')
const vertexLocation = ref('global')
const vertexServiceAccountDragActive = ref(false)
+const vertexAuthMode = ref<'service_account' | 'apikey'>('service_account')
+const vertexApiKey = ref('')
+// API Key 认证只对 Gemini 平台开放,Anthropic 平台的 Vertex 账号始终使用 Service Account JSON。
+const vertexUsesApiKey = computed(() => form.platform === 'gemini' && vertexAuthMode.value === 'apikey')
+// 两种认证方式的 Project ID 来源不同(JSON 读取 / 手填),切换时清空凭证字段避免串用。
+watch(vertexAuthMode, () => {
+ vertexServiceAccountJson.value = ''
+ vertexProjectId.value = ''
+ vertexClientEmail.value = ''
+ vertexApiKey.value = ''
+})
const tempUnschedEnabled = ref(false)
const tempUnschedRules = ref([])
const getModelMappingKey = createStableObjectKeyResolver('create-model-mapping')
@@ -4842,6 +5019,19 @@ const geminiHelpLinks = {
// Computed: current preset mappings based on platform
const presetMappings = computed(() => getPresetMappingsByPlatform(form.platform))
+const tempUnschedScopeOptions = computed>(() => [
+ {
+ value: 'model',
+ label: t('admin.accounts.tempUnschedulable.scopeModel'),
+ description: t('admin.accounts.tempUnschedulable.scopeModelDesc')
+ },
+ {
+ value: 'account',
+ label: t('admin.accounts.tempUnschedulable.scopeAccount'),
+ description: t('admin.accounts.tempUnschedulable.scopeAccountDesc')
+ }
+])
+
const tempUnschedPresets = computed(() => [
{
label: t('admin.accounts.tempUnschedulable.presets.overloadLabel'),
@@ -4849,7 +5039,8 @@ const tempUnschedPresets = computed(() => [
error_code: 529,
keywords: 'overloaded, too many',
duration_minutes: 60,
- description: t('admin.accounts.tempUnschedulable.presets.overloadDesc')
+ description: t('admin.accounts.tempUnschedulable.presets.overloadDesc'),
+ scope: 'model' as const
}
},
{
@@ -4858,7 +5049,8 @@ const tempUnschedPresets = computed(() => [
error_code: 429,
keywords: 'rate limit, too many requests',
duration_minutes: 10,
- description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc')
+ description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc'),
+ scope: 'model' as const
}
},
{
@@ -4867,7 +5059,8 @@ const tempUnschedPresets = computed(() => [
error_code: 503,
keywords: 'unavailable, maintenance',
duration_minutes: 30,
- description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc')
+ description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc'),
+ scope: 'model' as const
}
}
])
@@ -5060,6 +5253,8 @@ watch(
vertexProjectId.value = ''
vertexClientEmail.value = ''
vertexLocation.value = 'global'
+ vertexAuthMode.value = 'service_account'
+ vertexApiKey.value = ''
// Reset Anthropic/Antigravity-specific settings when switching to other platforms
if (newPlatform !== 'anthropic' && newPlatform !== 'antigravity') {
interceptWarmupRequests.value = false
@@ -5258,7 +5453,8 @@ const addTempUnschedRule = (preset?: TempUnschedRuleForm) => {
error_code: null,
keywords: '',
duration_minutes: 30,
- description: ''
+ description: '',
+ scope: 'model'
})
}
@@ -5281,6 +5477,7 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => {
keywords: string[]
duration_minutes: number
description: string
+ scope: TempUnschedulableScope
}> = []
for (const rule of rules) {
@@ -5300,7 +5497,8 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => {
error_code: Math.trunc(errorCode),
keywords,
duration_minutes: Math.trunc(duration),
- description: rule.description.trim()
+ description: rule.description.trim(),
+ scope: rule.scope
})
}
@@ -5473,6 +5671,7 @@ const resetForm = () => {
form.notes = ''
form.platform = 'anthropic'
openAIRequestTimezone.value = 'Asia/Singapore'
+ openAIRequestTimezoneMode.value = 'follow_proxy'
form.type = 'oauth'
form.credentials = {}
form.proxy_id = null
@@ -5515,6 +5714,8 @@ const resetForm = () => {
poolModeEnabled.value = false
poolModeRetryCount.value = DEFAULT_POOL_MODE_RETRY_COUNT
poolModeRetryStatusCodesInput.value = ''
+ explicitCacheUpstreamEnabled.value = false
+ explicitCacheUpstreamMaxTTL.value = ''
customErrorCodesEnabled.value = false
selectedErrorCodes.value = []
customErrorCodeInput.value = null
@@ -5569,6 +5770,8 @@ const resetForm = () => {
vertexProjectId.value = ''
vertexClientEmail.value = ''
vertexLocation.value = 'global'
+ vertexAuthMode.value = 'service_account'
+ vertexApiKey.value = ''
tempUnschedEnabled.value = false
tempUnschedRules.value = []
geminiOAuthType.value = 'code_assist'
@@ -5600,7 +5803,12 @@ const buildOpenAIExtra = (base?: Record): Record = { ...(base || {}) }
- extra.openai_request_timezone = openAIRequestTimezone.value
+ extra.openai_request_timezone_mode = openAIRequestTimezoneMode.value
+ if (openAIRequestTimezoneMode.value === 'fixed') {
+ extra.openai_request_timezone = openAIRequestTimezone.value
+ } else {
+ delete extra.openai_request_timezone
+ }
if (accountCategory.value === 'oauth-based') {
extra.openai_oauth_responses_websockets_v2_mode = openaiOAuthResponsesWebSocketV2Mode.value
extra.openai_oauth_responses_websockets_v2_enabled = isOpenAIWSModeEnabled(openaiOAuthResponsesWebSocketV2Mode.value)
@@ -5949,6 +6157,28 @@ const handleSubmit = async () => {
appStore.showError(t('admin.accounts.pleaseEnterAccountName'))
return
}
+ if (vertexUsesApiKey.value) {
+ if (!vertexApiKey.value.trim()) {
+ appStore.showError(t('admin.accounts.vertexApiKeyRequired'))
+ return
+ }
+ const projectId = vertexProjectId.value.trim()
+ if (projectId && !vertexLocation.value.trim()) {
+ appStore.showError(t('admin.accounts.vertexLocationRequired'))
+ return
+ }
+ const credentials: Record = {
+ auth_mode: 'apikey',
+ api_key: vertexApiKey.value.trim(),
+ location: vertexLocation.value.trim() || 'global',
+ tier_id: 'vertex'
+ }
+ if (projectId) {
+ credentials.project_id = projectId
+ }
+ await createAccountAndFinish(form.platform, 'service_account' as AccountType, credentials)
+ return
+ }
if (!parseVertexServiceAccountJson()) {
return
}
@@ -5990,7 +6220,7 @@ const handleSubmit = async () => {
base_url: apiKeyBaseUrl.value.trim() || defaultBaseUrl,
api_key: apiKeyValue.value.trim()
}
- if (form.platform === 'gemini') {
+ if (form.platform === 'gemini' && isOfficialGeminiBaseUrl(apiKeyBaseUrl.value)) {
credentials.tier_id = geminiTierAIStudio.value
}
@@ -6053,6 +6283,12 @@ const handleSubmit = async () => {
}
}
+ applyExplicitCacheUpstreamCredentials(
+ credentials,
+ form.platform === 'gemini' && !isOfficialGeminiBaseUrl(apiKeyBaseUrl.value) && explicitCacheUpstreamEnabled.value,
+ explicitCacheUpstreamMaxTTL.value
+ )
+
// Add custom error codes if enabled
if (customErrorCodesEnabled.value) {
credentials.custom_error_codes_enabled = true
diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue
index 2da01aec8..4086e39bf 100644
--- a/frontend/src/components/account/EditAccountModal.vue
+++ b/frontend/src/components/account/EditAccountModal.vue
@@ -241,7 +241,7 @@
account.platform === 'openai'
? 'sk-proj-...'
: account.platform === 'gemini'
- ? 'AIza...'
+ ? 'AQ.Ab...'
: account.platform === 'antigravity'
? 'sk-...'
: account.platform === 'grok'
@@ -502,6 +502,48 @@
+
+
+
+
+
{{ t('admin.accounts.explicitCacheUpstream') }}
+
+ {{ t('admin.accounts.explicitCacheUpstreamHint') }}
+
+
+
+
+
+
+
+ {{ t('admin.accounts.explicitCacheUpstreamInfo') }}
+
+
+
+
{{ t('admin.accounts.explicitCacheUpstreamMaxTTL') }}
+
+
+ {{ t('admin.accounts.explicitCacheUpstreamMaxTTLHint') }}
+
+
+
+
@@ -917,8 +959,30 @@
+
+
API Key
+
+
{{ t('admin.accounts.vertexApiKeyHint') }}
+
-
+
+
Project ID
+
+
{{ t('admin.accounts.vertexApiKeyProjectIdHint') }}
+
+
-
+
Location
+
+
{{ t('admin.accounts.tempUnschedulable.scope') }}
+
+
+
+
+
+
+ {{ option.label }}
+ {{ option.description }}
+
+
+
+
{{ t('admin.accounts.tempUnschedulable.scopeHint') }}
+
{{ t('admin.accounts.tempUnschedulable.keywords') }}
-
+
-
+
@@ -3166,11 +3274,13 @@ import type {
OpenAICompactMode,
OpenAIResponsesMode,
OpenAIEndpointCapability,
+ OpenAIRequestTimezoneMode,
OllamaCloudUsageState,
GrokMediaEligibilityMode,
GrokMediaEligibilityState,
OpenCodeGoUsageState,
- OpenCodeGoUsageWindow
+ OpenCodeGoUsageWindow,
+ TempUnschedulableScope
} from '@/types'
import BaseDialog from '@/components/common/BaseDialog.vue'
import ConfirmDialog from '@/components/common/ConfirmDialog.vue'
@@ -3187,6 +3297,11 @@ import ModelWhitelistSelector from '@/components/account/ModelWhitelistSelector.
import QuotaLimitCard from '@/components/account/QuotaLimitCard.vue'
import GrokBaseUrlPresets from '@/components/account/GrokBaseUrlPresets.vue'
import CnBaseUrlPresets from '@/components/account/CnBaseUrlPresets.vue'
+import {
+ applyExplicitCacheUpstreamCredentials,
+ isOfficialGeminiBaseUrl,
+ normalizeExplicitCacheUpstreamMaxTTL
+} from '@/utils/geminiExplicitCache'
import OpenCodeGoProtocolRulesEditor from '@/components/account/OpenCodeGoProtocolRulesEditor.vue'
import HeaderOverrideEditor from '@/components/account/HeaderOverrideEditor.vue'
import OllamaCloudUsageSettings from '@/components/account/OllamaCloudUsageSettings.vue'
@@ -3407,6 +3522,8 @@ interface TempUnschedRuleForm {
keywords: string
duration_minutes: number | null
description: string
+ // 作用范围:account 暂停整个账号,model 只冷却本次请求的模型。
+ scope: TempUnschedulableScope
}
// State
@@ -3581,6 +3698,12 @@ const editBedrockApiKeyValue = ref('')
const editVertexProjectId = ref('')
const editVertexClientEmail = ref('')
const editVertexLocation = ref('us-central1')
+const editVertexApiKey = ref('')
+const isVertexAPIKeyMode = computed(() =>
+ props.account?.platform === 'gemini' &&
+ props.account?.type === 'service_account' &&
+ (props.account?.credentials as Record
)?.auth_mode === 'apikey'
+)
const isBedrockAPIKeyMode = computed(() =>
props.account?.type === 'bedrock' &&
(props.account?.credentials as Record)?.auth_mode === 'apikey'
@@ -3594,6 +3717,8 @@ const MAX_POOL_MODE_RETRY_COUNT = 10
const DEFAULT_POOL_MODE_RETRY_STATUS_CODES = [401, 403, 429]
const GROK_CLIENT_TOOL_CACHE_EXTRA_KEY = 'grok_client_tool_cache_enabled'
const poolModeEnabled = ref(false)
+const explicitCacheUpstreamEnabled = ref(false)
+const explicitCacheUpstreamMaxTTL = ref('')
const poolModeRetryCount = ref(DEFAULT_POOL_MODE_RETRY_COUNT)
const poolModeRetryStatusCodesInput = ref('')
@@ -3759,6 +3884,7 @@ const customBaseUrl = ref('')
// OpenAI 自动透传开关(OAuth/API Key)
const openaiPassthroughEnabled = ref(false)
const openAIRequestTimezone = ref('Asia/Singapore')
+const openAIRequestTimezoneMode = ref('fixed')
// OpenAI Codex namespace 工具摊平兼容开关(仅 OAuth),缺省关闭即原样保留
const openaiFlattenNamespacesEnabled = ref(false)
const openAILongContextBillingEnabled = ref(false)
@@ -4035,6 +4161,19 @@ const openAICompactStatusKey = computed(() => {
// Computed: current preset mappings based on platform
const presetMappings = computed(() => getPresetMappingsByPlatform(props.account?.platform || 'anthropic'))
+const tempUnschedScopeOptions = computed>(() => [
+ {
+ value: 'model',
+ label: t('admin.accounts.tempUnschedulable.scopeModel'),
+ description: t('admin.accounts.tempUnschedulable.scopeModelDesc')
+ },
+ {
+ value: 'account',
+ label: t('admin.accounts.tempUnschedulable.scopeAccount'),
+ description: t('admin.accounts.tempUnschedulable.scopeAccountDesc')
+ }
+])
+
const tempUnschedPresets = computed(() => [
{
label: t('admin.accounts.tempUnschedulable.presets.overloadLabel'),
@@ -4042,7 +4181,8 @@ const tempUnschedPresets = computed(() => [
error_code: 529,
keywords: 'overloaded, too many',
duration_minutes: 60,
- description: t('admin.accounts.tempUnschedulable.presets.overloadDesc')
+ description: t('admin.accounts.tempUnschedulable.presets.overloadDesc'),
+ scope: 'model' as const
}
},
{
@@ -4051,7 +4191,8 @@ const tempUnschedPresets = computed(() => [
error_code: 429,
keywords: 'rate limit, too many requests',
duration_minutes: 10,
- description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc')
+ description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc'),
+ scope: 'model' as const
}
},
{
@@ -4060,7 +4201,8 @@ const tempUnschedPresets = computed(() => [
error_code: 503,
keywords: 'unavailable, maintenance',
duration_minutes: 30,
- description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc')
+ description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc'),
+ scope: 'model' as const
}
}
])
@@ -4220,6 +4362,7 @@ const syncFormFromAccount = (newAccount: Account | null) => {
editVertexProjectId.value = ''
editVertexClientEmail.value = ''
editVertexLocation.value = 'us-central1'
+ editVertexApiKey.value = ''
antigravityProjectId.value =
newAccount.platform === 'antigravity' &&
newAccount.type === 'oauth' &&
@@ -4251,6 +4394,7 @@ const syncFormFromAccount = (newAccount: Account | null) => {
// Load OpenAI passthrough toggle (OpenAI OAuth/SetupToken/API Key)
openaiPassthroughEnabled.value = false
openAIRequestTimezone.value = 'Asia/Singapore'
+ openAIRequestTimezoneMode.value = 'fixed'
openaiFlattenNamespacesEnabled.value = false
openAILongContextBillingEnabled.value = false
editPlanType.value = ''
@@ -4271,6 +4415,8 @@ const syncFormFromAccount = (newAccount: Account | null) => {
if (newAccount.platform === 'openai' && (newAccount.type === 'oauth' || newAccount.type === 'setup-token' || newAccount.type === 'apikey')) {
openaiPassthroughEnabled.value = extra?.openai_passthrough === true || extra?.openai_oauth_passthrough === true
openAIRequestTimezone.value = typeof extra?.openai_request_timezone === 'string' ? extra.openai_request_timezone : 'Asia/Singapore'
+ // 未设置模式的存量账号保持固定时区。
+ openAIRequestTimezoneMode.value = extra?.openai_request_timezone_mode === 'follow_proxy' ? 'follow_proxy' : 'fixed'
openaiFlattenNamespacesEnabled.value =
newAccount.type === 'oauth' && extra?.openai_responses_flatten_namespaces === true
const longContextBillingValue = extra?.openai_long_context_billing_enabled
@@ -4335,6 +4481,8 @@ const syncFormFromAccount = (newAccount: Account | null) => {
anthropicAPIKeyAuthScheme.value = extra?.anthropic_apikey_auth_scheme === 'authorization_bearer'
? 'authorization_bearer'
: 'x_api_key'
+ }
+ if ((newAccount.platform === 'anthropic' || newAccount.platform === 'openai') && newAccount.type === 'apikey') {
// 三态:string "default"/"enabled"/"disabled",向后兼容旧 bool
const wsVal = extra?.web_search_emulation
if (wsVal === 'enabled' || wsVal === 'disabled') {
@@ -4545,6 +4693,10 @@ const syncFormFromAccount = (newAccount: Account | null) => {
)
poolModeRetryStatusCodesInput.value = formatPoolModeRetryStatusCodes(credentials.pool_mode_retry_status_codes)
+ explicitCacheUpstreamEnabled.value = credentials.explicit_cache_upstream === true
+ explicitCacheUpstreamMaxTTL.value =
+ normalizeExplicitCacheUpstreamMaxTTL(credentials.explicit_cache_upstream_max_ttl_seconds) ?? ''
+
// Load custom error codes
customErrorCodesEnabled.value = credentials.custom_error_codes_enabled === true
const existingErrorCodes = credentials.custom_error_codes as number[] | undefined
@@ -4592,6 +4744,7 @@ const syncFormFromAccount = (newAccount: Account | null) => {
editVertexProjectId.value = (credentials.project_id as string) || ''
editVertexClientEmail.value = (credentials.client_email as string) || ''
editVertexLocation.value = (credentials.location as string) || (credentials.vertex_location as string) || 'us-central1'
+ editVertexApiKey.value = ''
// Load model mappings for service_account
loadModelRestrictionFromMapping(credentials.model_mapping as Record | undefined)
@@ -4618,6 +4771,8 @@ const syncFormFromAccount = (newAccount: Account | null) => {
poolModeEnabled.value = false
poolModeRetryCount.value = DEFAULT_POOL_MODE_RETRY_COUNT
poolModeRetryStatusCodesInput.value = ''
+ explicitCacheUpstreamEnabled.value = false
+ explicitCacheUpstreamMaxTTL.value = ''
customErrorCodesEnabled.value = false
selectedErrorCodes.value = []
}
@@ -4731,7 +4886,7 @@ const syncAntigravityUpstreamModels = async () => {
appStore.showWarning(t('admin.accounts.syncUpstreamModelsMetadataPartial'))
}
} catch (error) {
- const message = error instanceof Error ? error.message : t('admin.accounts.syncUpstreamModelsFailed')
+ const message = extractApiErrorMessage(error, t('admin.accounts.syncUpstreamModelsFailed'))
appStore.showError(t('admin.accounts.syncUpstreamModelsError', { message }))
} finally {
isSyncingAntigravityUpstream.value = false
@@ -4800,7 +4955,8 @@ const addTempUnschedRule = (preset?: TempUnschedRuleForm) => {
error_code: null,
keywords: '',
duration_minutes: 30,
- description: ''
+ description: '',
+ scope: 'model'
})
}
@@ -4823,6 +4979,7 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => {
keywords: string[]
duration_minutes: number
description: string
+ scope: TempUnschedulableScope
}> = []
for (const rule of rules) {
@@ -4842,7 +4999,8 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => {
error_code: Math.trunc(errorCode),
keywords,
duration_minutes: Math.trunc(duration),
- description: rule.description.trim()
+ description: rule.description.trim(),
+ scope: rule.scope
})
}
@@ -4940,11 +5098,13 @@ function loadTempUnschedRules(credentials?: Record) {
tempUnschedRules.value = rawRules.map((rule) => {
const entry = rule as Record
+ const errorCode = toPositiveNumber(entry.error_code)
return {
- error_code: toPositiveNumber(entry.error_code),
+ error_code: errorCode,
keywords: formatTempUnschedKeywords(entry.keywords),
duration_minutes: toPositiveNumber(entry.duration_minutes),
- description: typeof entry.description === 'string' ? entry.description : ''
+ description: typeof entry.description === 'string' ? entry.description : '',
+ scope: resolveTempUnschedScope(entry.scope, errorCode)
}
})
}
@@ -5043,6 +5203,16 @@ function formatTempUnschedKeywords(value: unknown) {
return ''
}
+// 未设置 scope 的规则由后端按「401 账号级、其余模型级」处理,这里按同一规则回显,
+// 保证打开再保存不改变规则行为。
+function resolveTempUnschedScope(value: unknown, errorCode: number | null): TempUnschedulableScope {
+ const scope = typeof value === 'string' ? value.trim().toLowerCase() : ''
+ if (scope === 'account' || scope === 'model') {
+ return scope
+ }
+ return errorCode === 401 ? 'account' : 'model'
+}
+
const splitTempUnschedKeywords = (value: string) => {
return value
.split(/[,;]/)
@@ -5350,6 +5520,12 @@ const handleSubmit = async () => {
delete newCredentials.pool_mode_retry_status_codes
}
+ applyExplicitCacheUpstreamCredentials(
+ newCredentials,
+ props.account.platform === 'gemini' && !isOfficialGeminiBaseUrl(editBaseUrl.value) && explicitCacheUpstreamEnabled.value,
+ explicitCacheUpstreamMaxTTL.value
+ )
+
// Add custom error codes if enabled
if (customErrorCodesEnabled.value) {
newCredentials.custom_error_codes_enabled = true
@@ -5401,35 +5577,61 @@ const handleSubmit = async () => {
} else if ((props.account.platform === 'gemini' || props.account.platform === 'anthropic') && props.account.type === 'service_account') {
const currentCredentials = (props.account.credentials as Record) || {}
const newCredentials: Record = { ...currentCredentials }
+ const credentialsStatus = props.account.credentials_status
- if (!editVertexProjectId.value.trim()) {
- appStore.showError(t('admin.accounts.vertexSaJsonMissingProjectId'))
- return
- }
- if (!editVertexClientEmail.value.trim()) {
- appStore.showError(t('admin.accounts.vertexSaJsonMissingClientEmail'))
- return
- }
- if (!editVertexLocation.value.trim()) {
- appStore.showError(t('admin.accounts.vertexLocationRequired'))
- return
- }
+ if (isVertexAPIKeyMode.value) {
+ // API Key 已脱敏不再随 credentials 返回,存在性读 credentials_status;留空表示保留原 Key。
+ const newApiKey = editVertexApiKey.value.trim()
+ const hasExistingApiKey = credentialsStatus
+ ? Boolean(credentialsStatus.has_api_key)
+ : Boolean(currentCredentials.api_key)
+ if (!newApiKey && !hasExistingApiKey) {
+ appStore.showError(t('admin.accounts.vertexApiKeyRequired'))
+ return
+ }
+ const projectId = editVertexProjectId.value.trim()
+ if (projectId && !editVertexLocation.value.trim()) {
+ appStore.showError(t('admin.accounts.vertexLocationRequired'))
+ return
+ }
+ if (newApiKey) {
+ newCredentials.api_key = newApiKey
+ }
+ if (projectId) {
+ newCredentials.project_id = projectId
+ } else {
+ delete newCredentials.project_id
+ }
+ newCredentials.location = editVertexLocation.value.trim() || 'global'
+ } else {
+ if (!editVertexProjectId.value.trim()) {
+ appStore.showError(t('admin.accounts.vertexSaJsonMissingProjectId'))
+ return
+ }
+ if (!editVertexClientEmail.value.trim()) {
+ appStore.showError(t('admin.accounts.vertexSaJsonMissingClientEmail'))
+ return
+ }
+ if (!editVertexLocation.value.trim()) {
+ appStore.showError(t('admin.accounts.vertexLocationRequired'))
+ return
+ }
- // SA JSON 已脱敏不再随 credentials 返回,存在性优先读 credentials_status。
- // 若后端尚未升级(无 credentials_status),回退读旧结构 service_account_json / service_account。
- const credentialsStatus = props.account.credentials_status
- const hasExistingServiceAccountJson = credentialsStatus
- ? Boolean(
- credentialsStatus.has_service_account_json || credentialsStatus.has_service_account
- )
- : Boolean(currentCredentials.service_account_json || currentCredentials.service_account)
- if (!hasExistingServiceAccountJson) {
- appStore.showError(t('admin.accounts.vertexSaJsonRequired'))
- return
+ // SA JSON 已脱敏不再随 credentials 返回,存在性优先读 credentials_status。
+ // 若后端尚未升级(无 credentials_status),回退读旧结构 service_account_json / service_account。
+ const hasExistingServiceAccountJson = credentialsStatus
+ ? Boolean(
+ credentialsStatus.has_service_account_json || credentialsStatus.has_service_account
+ )
+ : Boolean(currentCredentials.service_account_json || currentCredentials.service_account)
+ if (!hasExistingServiceAccountJson) {
+ appStore.showError(t('admin.accounts.vertexSaJsonRequired'))
+ return
+ }
+ newCredentials.project_id = editVertexProjectId.value.trim()
+ newCredentials.client_email = editVertexClientEmail.value.trim()
+ newCredentials.location = editVertexLocation.value.trim()
}
- newCredentials.project_id = editVertexProjectId.value.trim()
- newCredentials.client_email = editVertexClientEmail.value.trim()
- newCredentials.location = editVertexLocation.value.trim()
newCredentials.tier_id = 'vertex'
// Add model mapping if configured
@@ -5752,7 +5954,9 @@ const handleSubmit = async () => {
if (props.account.platform === 'openai' && (props.account.type === 'oauth' || props.account.type === 'setup-token' || props.account.type === 'apikey')) {
const currentExtra = (props.account.extra as Record) || {}
const newExtra: Record = { ...currentExtra }
- newExtra.openai_request_timezone = openAIRequestTimezone.value
+ newExtra.openai_request_timezone_mode = openAIRequestTimezoneMode.value
+ // 跟随模式下时区由后端检测写入,不回传表单值。
+ if (openAIRequestTimezoneMode.value === 'fixed') newExtra.openai_request_timezone = openAIRequestTimezone.value
const hadCodexCLIOnlyEnabled = currentExtra.codex_cli_only === true
if (props.account.type === 'oauth' || props.account.type === 'setup-token') {
newExtra.openai_oauth_responses_websockets_v2_mode = openaiOAuthResponsesWebSocketV2Mode.value
@@ -5795,6 +5999,11 @@ const handleSubmit = async () => {
newExtra.images_url_to_b64_json = true
} else {
delete newExtra.images_url_to_b64_json
+ }
+ if (webSearchEmulationMode.value === 'default') {
+ delete newExtra.web_search_emulation
+ } else {
+ newExtra.web_search_emulation = webSearchEmulationMode.value
}
}
if (autoPause5hThreshold.value != null && autoPause5hThreshold.value > 0) {
diff --git a/frontend/src/components/account/ModelWhitelistSelector.vue b/frontend/src/components/account/ModelWhitelistSelector.vue
index d953c21ce..aa09de7bb 100644
--- a/frontend/src/components/account/ModelWhitelistSelector.vue
+++ b/frontend/src/components/account/ModelWhitelistSelector.vue
@@ -155,6 +155,7 @@ import ModelIcon from '@/components/common/ModelIcon.vue'
import Icon from '@/components/icons/Icon.vue'
import { allModels, getModelsByPlatform } from '@/composables/useModelWhitelist'
import { supportsUpstreamModelSync } from '@/constants/platformCatalog'
+import { extractApiErrorMessage } from '@/utils/apiError'
const { t } = useI18n()
@@ -343,7 +344,7 @@ const syncUpstreamModels = async () => {
appStore.showWarning(t('admin.accounts.syncUpstreamModelsMetadataPartial'))
}
} catch (error) {
- const message = error instanceof Error ? error.message : t('admin.accounts.syncUpstreamModelsFailed')
+ const message = extractApiErrorMessage(error, t('admin.accounts.syncUpstreamModelsFailed'))
appStore.showError(t('admin.accounts.syncUpstreamModelsError', { message }))
} finally {
isSyncingUpstream.value = false
diff --git a/frontend/src/components/account/OpenAIRequestTimezoneField.vue b/frontend/src/components/account/OpenAIRequestTimezoneField.vue
index a7e52d6e1..96aab8561 100644
--- a/frontend/src/components/account/OpenAIRequestTimezoneField.vue
+++ b/frontend/src/components/account/OpenAIRequestTimezoneField.vue
@@ -1,48 +1,125 @@
{{ t('admin.accounts.openai.requestTimezone') }}
-
-
{{ t('admin.accounts.openai.requestTimezoneDesc') }}
-
{{ t('admin.accounts.openai.requestTimezoneLoadFailed') }}
+
+
+
+ {{ option.label }}
+
+
+
+
+
{{ t('admin.accounts.openai.requestTimezoneFollowDesc') }}
+
+
+ {{ t('admin.accounts.openai.requestTimezoneDetected', { timezone: detection.timezone, ip: detection.ip || '-', location: location || '-', time: detectedAt }) }}
+
+
+ {{ t('admin.accounts.openai.requestTimezoneDetectFailed', { error: detection.error, timezone: modelValue || defaultTimezone }) }}
+
+ {{ t('admin.accounts.openai.requestTimezoneNotDetected', { timezone: modelValue || defaultTimezone }) }}
+
+ {{ detecting ? t('admin.accounts.openai.requestTimezoneDetecting') : t('admin.accounts.openai.requestTimezoneRedetect') }}
+
+
+
{{ t('admin.accounts.openai.requestTimezoneDetectAfterSave') }}
+
+
+
+
+
+
+ {{ t('admin.accounts.openai.requestTimezoneDesc') }}
+ {{ t('admin.accounts.openai.requestTimezoneLoadFailed') }}
+
diff --git a/frontend/src/components/admin/group/GroupRPMOverridesModal.vue b/frontend/src/components/admin/group/GroupRPMOverridesModal.vue
index f1c6d97bb..50c15aac8 100644
--- a/frontend/src/components/admin/group/GroupRPMOverridesModal.vue
+++ b/frontend/src/components/admin/group/GroupRPMOverridesModal.vue
@@ -246,6 +246,7 @@ const currentPage = ref(1)
const pageSize = ref(10)
let searchTimeout: ReturnType
+let loadVersion = 0
const platformColorClass = computed(() => {
switch (props.group?.platform) {
@@ -273,16 +274,22 @@ const cloneEntries = (entries: GroupRPMOverrideEntry[]): LocalEntry[] => {
const loadEntries = async () => {
if (!props.group) return
+ const version = loadVersion
loading.value = true
+ serverEntries.value = []
+ localEntries.value = []
try {
- serverEntries.value = await adminAPI.groups.getGroupRPMOverrides(props.group.id)
+ const entries = await adminAPI.groups.getGroupRPMOverrides(props.group.id)
+ if (version !== loadVersion) return
+ serverEntries.value = entries
localEntries.value = cloneEntries(serverEntries.value)
adjustPage()
} catch (error) {
+ if (version !== loadVersion) return
appStore.showError(t('admin.groups.failedToLoad'))
console.error('Error loading RPM overrides:', error)
} finally {
- loading.value = false
+ if (version === loadVersion) loading.value = false
}
}
@@ -291,8 +298,9 @@ const adjustPage = () => {
if (currentPage.value > totalPages) currentPage.value = totalPages
}
-watch(() => props.show, (val) => {
- if (val && props.group) {
+watch([() => props.show, () => props.group?.id], ([show]) => {
+ loadVersion++
+ if (show && props.group) {
currentPage.value = 1
searchQuery.value = ''
searchResults.value = []
@@ -423,6 +431,7 @@ if (typeof document !== 'undefined') {
document.addEventListener('click', handleClickOutside)
}
onUnmounted(() => {
+ loadVersion++
clearTimeout(searchTimeout)
document.removeEventListener('click', handleClickOutside)
})
diff --git a/frontend/src/components/admin/group/GroupRateMultipliersModal.vue b/frontend/src/components/admin/group/GroupRateMultipliersModal.vue
index efeb95e0e..dfcd238f3 100644
--- a/frontend/src/components/admin/group/GroupRateMultipliersModal.vue
+++ b/frontend/src/components/admin/group/GroupRateMultipliersModal.vue
@@ -426,7 +426,7 @@ const updateLocalRate = (userId: number, value: string) => {
return
}
const num = parseFloat(value)
- if (isNaN(num)) return
+ if (!Number.isFinite(num) || num <= 0) return
entry.rate_multiplier = num
}
diff --git a/frontend/src/components/admin/group/__tests__/GroupI18nField.spec.ts b/frontend/src/components/admin/group/__tests__/GroupI18nField.spec.ts
new file mode 100644
index 000000000..c91176a07
--- /dev/null
+++ b/frontend/src/components/admin/group/__tests__/GroupI18nField.spec.ts
@@ -0,0 +1,197 @@
+import { enableAutoUnmount, mount } from '@vue/test-utils'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { defineComponent, h, reactive } from 'vue'
+
+import GroupI18nField from '../GroupI18nField.vue'
+import type { GroupI18n } from '@/types'
+
+vi.mock('vue-i18n', async () => {
+ const actual = await vi.importActual('vue-i18n')
+ return {
+ ...actual,
+ useI18n: () => ({
+ t: (key: string, params?: Record) =>
+ params ? `${key}:${params.language}` : key
+ })
+ }
+})
+
+// 用例把组件挂到 document.body 上以断言焦点,逐例卸载避免互相残留
+enableAutoUnmount(afterEach)
+
+// 挂载一个 v-model 双向绑定的宿主,贴近分组表单里的真实用法。
+const mountField = (
+ initial: { text: string; i18n: GroupI18n },
+ fieldProps: Record = {}
+) => {
+ const state = reactive({ text: initial.text, i18n: initial.i18n })
+ const host = defineComponent({
+ setup() {
+ return () =>
+ h(GroupI18nField, {
+ label: 'Name',
+ field: 'name',
+ ...fieldProps,
+ modelValue: state.text,
+ 'onUpdate:modelValue': (value: string) => {
+ state.text = value
+ },
+ i18n: state.i18n,
+ 'onUpdate:i18n': (value: GroupI18n) => {
+ state.i18n = value
+ }
+ })
+ }
+ })
+ return { wrapper: mount(host, { attachTo: document.body }), state }
+}
+
+type Wrapper = ReturnType['wrapper']
+
+const trigger = (wrapper: Wrapper) => wrapper.get('[data-testid="group-i18n-menu"]')
+const menuItems = (wrapper: Wrapper) => wrapper.findAll('button[data-locale]')
+const choose = async (wrapper: Wrapper, locale: string) => {
+ await trigger(wrapper).trigger('click')
+ await wrapper.get(`button[data-locale="${locale}"]`).trigger('click')
+}
+
+describe('GroupI18nField', () => {
+ it('renders the label and the switcher on one row above a single input', () => {
+ const { wrapper } = mountField({ text: '标准', i18n: { en: { name: 'Standard' } } })
+
+ const labelRow = wrapper.get('label').element.parentElement!
+ expect(wrapper.get('label').text()).toBe('Name')
+ expect(labelRow.contains(trigger(wrapper).element)).toBe(true)
+ expect(labelRow.contains(wrapper.get('input').element)).toBe(false)
+ expect(wrapper.findAll('input')).toHaveLength(1)
+ })
+
+ it('starts on the default content', async () => {
+ const { wrapper, state } = mountField({ text: '标准', i18n: { en: { name: 'Standard' } } })
+ const input = wrapper.get('input')
+
+ expect(input.element.value).toBe('标准')
+ expect(trigger(wrapper).text()).toBe('admin.groups.i18nField.default')
+
+ await input.setValue('标准版')
+
+ expect(state.text).toBe('标准版')
+ expect(state.i18n).toEqual({ en: { name: 'Standard' } })
+ })
+
+ it('lists the default content and an add or edit entry per interface language', async () => {
+ const { wrapper } = mountField({
+ text: '标准',
+ i18n: { en: { name: 'Standard' }, zh: { description: '仅描述' } }
+ })
+
+ await trigger(wrapper).trigger('click')
+
+ expect(menuItems(wrapper).map((item) => [item.attributes('data-locale'), item.text()])).toEqual([
+ ['default', 'admin.groups.i18nField.default'],
+ ['en', 'admin.groups.i18nField.edit:English'],
+ ['zh', 'admin.groups.i18nField.add:中文']
+ ])
+ })
+
+ it('switches the same input to the chosen language version', async () => {
+ const { wrapper, state } = mountField({ text: '标准', i18n: { en: { name: 'Standard' } } })
+
+ await choose(wrapper, 'en')
+
+ expect(menuItems(wrapper)).toHaveLength(0)
+ expect(wrapper.findAll('input')).toHaveLength(1)
+ const input = wrapper.get('input')
+ expect(input.element.value).toBe('Standard')
+ expect(document.activeElement).toBe(input.element)
+ expect(trigger(wrapper).text()).toBe('English')
+
+ await input.setValue('Standard v2')
+
+ expect(state.text).toBe('标准')
+ expect(state.i18n).toEqual({ en: { name: 'Standard v2' } })
+ })
+
+ it('starts a new language version empty and keeps the other field of that language', async () => {
+ const { wrapper, state } = mountField({
+ text: '标准',
+ i18n: { en: { description: 'Pro + Max pool' } }
+ })
+
+ await choose(wrapper, 'en')
+ const input = wrapper.get('input')
+ expect(input.element.value).toBe('')
+ expect(input.attributes('placeholder')).toBe('admin.groups.i18nField.placeholder:English')
+
+ await input.setValue('Standard')
+
+ expect(state.i18n).toEqual({ en: { name: 'Standard', description: 'Pro + Max pool' } })
+ })
+
+ it('returns to the default content from a language version', async () => {
+ const { wrapper } = mountField({ text: '标准', i18n: { en: { name: 'Standard' } } })
+
+ await choose(wrapper, 'en')
+ await choose(wrapper, 'zh')
+ expect(wrapper.get('input').element.value).toBe('')
+
+ await choose(wrapper, 'default')
+
+ expect(wrapper.get('input').element.value).toBe('标准')
+ expect(trigger(wrapper).text()).toBe('admin.groups.i18nField.default')
+ })
+
+ it('marks the version being edited in the menu', async () => {
+ const { wrapper } = mountField({ text: '标准', i18n: {} })
+
+ await choose(wrapper, 'zh')
+ await trigger(wrapper).trigger('click')
+
+ const checked = menuItems(wrapper)
+ .filter((item) => item.find('svg').exists())
+ .map((item) => item.attributes('data-locale'))
+ expect(checked).toEqual(['zh'])
+ })
+
+ it('requires only the default content and keeps the form placeholder for it', async () => {
+ const { wrapper } = mountField(
+ { text: '', i18n: {} },
+ { required: true, placeholder: 'Enter name', 'data-tour': 'group-form-name' }
+ )
+ const input = wrapper.get('input')
+ expect(input.attributes('required')).toBeDefined()
+ expect(input.attributes('placeholder')).toBe('Enter name')
+ expect(input.attributes('data-tour')).toBe('group-form-name')
+
+ await choose(wrapper, 'en')
+
+ expect(wrapper.get('input').attributes('required')).toBeUndefined()
+ })
+
+ it('switches a single textarea for multiline fields', async () => {
+ const { wrapper, state } = mountField(
+ { text: '号池', i18n: {} },
+ { field: 'description', multiline: true, rows: '3' }
+ )
+ expect(wrapper.findAll('textarea')).toHaveLength(1)
+ expect(wrapper.get('textarea').attributes('rows')).toBe('3')
+
+ await choose(wrapper, 'en')
+ await wrapper.get('textarea').setValue('Pro + Max pool')
+
+ expect(wrapper.findAll('textarea')).toHaveLength(1)
+ expect(state.i18n).toEqual({ en: { description: 'Pro + Max pool' } })
+ expect(state.text).toBe('号池')
+ })
+
+ it('closes the menu when clicking elsewhere', async () => {
+ const { wrapper } = mountField({ text: '标准', i18n: {} })
+ await trigger(wrapper).trigger('click')
+ expect(menuItems(wrapper)).toHaveLength(3)
+
+ document.body.click()
+ await wrapper.vm.$nextTick()
+
+ expect(menuItems(wrapper)).toHaveLength(0)
+ })
+})
diff --git a/frontend/src/components/admin/group/__tests__/GroupRPMOverridesModal.requests.spec.ts b/frontend/src/components/admin/group/__tests__/GroupRPMOverridesModal.requests.spec.ts
new file mode 100644
index 000000000..bd4c3ffc1
--- /dev/null
+++ b/frontend/src/components/admin/group/__tests__/GroupRPMOverridesModal.requests.spec.ts
@@ -0,0 +1,100 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
+import type { AdminGroup } from '@/types'
+import GroupRPMOverridesModal from '../GroupRPMOverridesModal.vue'
+
+const mocks = vi.hoisted(() => ({ getGroupRPMOverrides: vi.fn(), batchSetGroupRPMOverrides: vi.fn(), showError: vi.fn() }))
+vi.mock('@/api/admin', () => ({ adminAPI: { groups: mocks } }))
+vi.mock('@/stores/app', () => ({ useAppStore: () => ({ showError: mocks.showError, showSuccess: vi.fn() }) }))
+vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
+enableAutoUnmount(afterEach)
+beforeEach(() => vi.resetAllMocks())
+afterEach(() => vi.restoreAllMocks())
+
+function deferred() {
+ let resolve!: (value: unknown) => void
+ let reject!: (reason: unknown) => void
+ const promise = new Promise((res, rej) => { resolve = res; reject = rej })
+ return { promise, resolve, reject }
+}
+
+const group = (id: number) => ({ id, name: `Group ${id}`, platform: 'openai', rpm_limit: 100 } as AdminGroup)
+const entries = (id: number) => [{ user_id: id, user_name: '', user_email: `user${id}@example.com`, user_status: 'active', rpm_override: 100 }]
+
+async function openGroup() {
+ const wrapper = mount(GroupRPMOverridesModal, {
+ props: { show: false, group: group(1) },
+ global: { stubs: {
+ BaseDialog: { props: ['show'], template: '
' },
+ Icon: true, PlatformIcon: true, Pagination: true
+ } }
+ })
+ await wrapper.setProps({ show: true })
+ return wrapper
+}
+
+describe('group RPM override request ownership', () => {
+ it('keeps the reopened group data when an older response finishes last', async () => {
+ const old = deferred()
+ mocks.getGroupRPMOverrides.mockReturnValueOnce(old.promise).mockResolvedValueOnce(entries(2))
+ const wrapper = await openGroup()
+ await wrapper.setProps({ show: false })
+ await wrapper.setProps({ show: true, group: group(2) })
+ await flushPromises()
+ old.resolve(entries(1))
+ await flushPromises()
+ expect(wrapper.get('tbody').text()).toContain('user2@example.com')
+ expect(wrapper.get('tbody').text()).not.toContain('user1@example.com')
+ await wrapper.get('tbody input[type="number"]').setValue('200')
+ await wrapper.findAll('button').find(button => button.text() === 'common.save')!.trigger('click')
+ expect(mocks.batchSetGroupRPMOverrides).toHaveBeenCalledWith(2, [{ user_id: 2, rpm_override: 200 }])
+ })
+
+ it('does not end the new load or report an error when an old request fails', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ const old = deferred()
+ const current = deferred()
+ mocks.getGroupRPMOverrides.mockReturnValueOnce(old.promise).mockReturnValueOnce(current.promise)
+ const wrapper = await openGroup()
+ await wrapper.setProps({ show: false })
+ await wrapper.setProps({ show: true, group: group(2) })
+ old.reject(new Error('old request failed'))
+ await flushPromises()
+ expect(mocks.showError).not.toHaveBeenCalled()
+ expect(wrapper.find('svg.animate-spin').exists()).toBe(true)
+ current.resolve(entries(2))
+ await flushPromises()
+ expect(wrapper.get('tbody').text()).toContain('user2@example.com')
+ })
+
+ it('loads a different group while the dialog remains open', async () => {
+ mocks.getGroupRPMOverrides.mockResolvedValueOnce(entries(1)).mockResolvedValueOnce(entries(2))
+ const wrapper = await openGroup()
+ await flushPromises()
+ await wrapper.setProps({ group: group(2) })
+ await flushPromises()
+ expect(mocks.getGroupRPMOverrides).toHaveBeenLastCalledWith(2)
+ expect(wrapper.get('tbody').text()).toContain('user2@example.com')
+ })
+
+ it('discards the previous group draft before loading the next group', async () => {
+ mocks.getGroupRPMOverrides.mockResolvedValueOnce(entries(1)).mockReturnValueOnce(deferred().promise)
+ const wrapper = await openGroup()
+ await flushPromises()
+ await wrapper.get('tbody input[type="number"]').setValue('200')
+ await wrapper.setProps({ show: false })
+ await wrapper.setProps({ show: true, group: group(2) })
+ expect(wrapper.findAll('button').some(button => button.text() === 'common.save')).toBe(false)
+ })
+
+ it('ignores a request failure after unmounting', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ const request = deferred()
+ mocks.getGroupRPMOverrides.mockReturnValue(request.promise)
+ const wrapper = await openGroup()
+ wrapper.unmount()
+ request.reject(new Error('offline'))
+ await flushPromises()
+ expect(mocks.showError).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/components/admin/group/__tests__/GroupRateMultipliersModal.edit.spec.ts b/frontend/src/components/admin/group/__tests__/GroupRateMultipliersModal.edit.spec.ts
new file mode 100644
index 000000000..e1fc6c557
--- /dev/null
+++ b/frontend/src/components/admin/group/__tests__/GroupRateMultipliersModal.edit.spec.ts
@@ -0,0 +1,52 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
+import type { AdminGroup } from '@/types'
+import GroupRateMultipliersModal from '../GroupRateMultipliersModal.vue'
+
+const mocks = vi.hoisted(() => ({ getGroupRateMultipliers: vi.fn(), batchSetGroupRateMultipliers: vi.fn() }))
+vi.mock('@/api/admin', () => ({ adminAPI: { groups: mocks } }))
+vi.mock('@/stores/app', () => ({ useAppStore: () => ({ showSuccess: vi.fn(), showError: vi.fn() }) }))
+vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
+enableAutoUnmount(afterEach)
+beforeEach(() => {
+ vi.resetAllMocks()
+ mocks.getGroupRateMultipliers.mockResolvedValue([
+ { user_id: 7, user_email: 'user@example.com', user_name: '', user_status: 'active', rate_multiplier: 2, rpm_override: null }
+ ])
+})
+
+async function openEditor() {
+ const wrapper = mount(GroupRateMultipliersModal, {
+ props: { show: false, group: { id: 1, name: 'Group', platform: 'openai', rate_multiplier: 1 } as AdminGroup },
+ global: { stubs: {
+ BaseDialog: { props: ['show'], template: '
' },
+ Icon: true, PlatformIcon: true, Pagination: true
+ } }
+ })
+ await wrapper.setProps({ show: true })
+ await flushPromises()
+ return wrapper
+}
+
+describe('group rate multiplier edits', () => {
+ it.each(['0', '-1'])('does not stage invalid custom rate %s', async (value) => {
+ const wrapper = await openEditor()
+ await wrapper.get('tbody input[type="number"]').setValue(value)
+ expect(wrapper.findAll('button').some(button => button.text() === 'common.save')).toBe(false)
+ expect(mocks.batchSetGroupRateMultipliers).not.toHaveBeenCalled()
+ })
+
+ it.each([['0.5', 0.5], ['1e-3', 0.001]])('saves positive rate %s', async (value, expected) => {
+ const wrapper = await openEditor()
+ await wrapper.get('tbody input[type="number"]').setValue(value)
+ await wrapper.findAll('button').find(button => button.text() === 'common.save')!.trigger('click')
+ expect(mocks.batchSetGroupRateMultipliers).toHaveBeenCalledWith(1, [{ user_id: 7, rate_multiplier: expected }])
+ })
+
+ it('still removes an override when its input is cleared', async () => {
+ const wrapper = await openEditor()
+ await wrapper.get('tbody input[type="number"]').setValue('')
+ await wrapper.findAll('button').find(button => button.text() === 'common.save')!.trigger('click')
+ expect(mocks.batchSetGroupRateMultipliers).toHaveBeenCalledWith(1, [])
+ })
+})
diff --git a/frontend/src/components/admin/proxy/CodexTicketProxyPool.vue b/frontend/src/components/admin/proxy/CodexTicketProxyPool.vue
index f46e8a102..2817c6e59 100644
--- a/frontend/src/components/admin/proxy/CodexTicketProxyPool.vue
+++ b/frontend/src/components/admin/proxy/CodexTicketProxyPool.vue
@@ -1,31 +1,174 @@
-
{{ zh ? 'Codex 打票代理池' : 'Codex ticket proxy pool' }} {{ zh ? '复用 IP 设置中的可用代理,按池轮换;无可用代理时不直连。' : 'Rotate available proxies from IP settings; never connect directly without one.' }}
-
{{ saving ? '…' : zh ? '保存代理池' : 'Save pool' }}
+
+
{{ zh ? 'Codex 打票代理池' : 'Codex ticket proxy pool' }}
+
{{ zh ? '复用 IP 设置中的可用代理,按池轮换;无可用代理时不直连。仅在系统设置「打票出口 IP」选择代理池时生效。修改后需点击「保存代理池」。' : 'Rotate available proxies from IP settings; never connect directly without one. Applies only when Settings → Ticket egress IP uses the pool. Click Save pool to apply changes.' }}
+
+
+ {{ zh ? '有未保存的修改' : 'Unsaved changes' }}
+ {{ saving ? '…' : zh ? '保存代理池' : 'Save pool' }}
+
+
{{ error }}
- {{ zh ? '代理池已保存' : 'Proxy pool saved' }}
- {{ zh ? '全部可用代理' : 'All available proxies' }} {{ zh ? '自定义选择' : 'Custom selection' }}
- {{ proxy.name }} {{ zh ? '无可用代理,请先添加代理。' : 'No available proxies; add one first.' }}
+ {{ zh ? '代理池已保存' : 'Proxy pool saved' }}
+
+
+
+ {{ zh ? '当前未生效:系统设置中「打票出口 IP」为「使用账号自身的代理」,打票走各账号绑定的代理,此代理池不参与。' : "Not in effect: Settings → Ticket egress IP is set to each account's own proxy, so this pool is ignored." }}
+
+
+ {{ zh ? '当前打票轮换:' : 'Tickets currently rotate through: ' }}
+ {{ view.effective.map(proxy => proxy.name).join('、') }}
+
+ {{ zh ? '当前没有可用代理,不会打票。' : 'No usable proxy; tickets will not be harvested.' }}
+
+
+
+ {{ zh ? '全部可用代理' : 'All available proxies' }}
+ {{ zh ? '自定义选择' : 'Custom selection' }}
+
+
+
+
+
+
+
+ {{ proxy.name }}
+ · {{ proxy.host }}:{{ proxy.port }}
+
+ {{ zh ? '已过期,不参与打票' : 'Expired, not used' }}
+
+ {{ zh ? '无可用代理,请先添加代理。' : 'No available proxies; add one first.' }}
+
+
+ {{ zh ? '已勾选但当前不可用(不会参与打票):' : 'Selected but unavailable (not used):' }}
+
+ {{ item.label }} ×
+
+
+
+
diff --git a/frontend/src/components/admin/proxy/__tests__/CodexTicketProxyPool.spec.ts b/frontend/src/components/admin/proxy/__tests__/CodexTicketProxyPool.spec.ts
new file mode 100644
index 000000000..b3b721e19
--- /dev/null
+++ b/frontend/src/components/admin/proxy/__tests__/CodexTicketProxyPool.spec.ts
@@ -0,0 +1,106 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ref } from 'vue'
+import CodexTicketProxyPool from '../CodexTicketProxyPool.vue'
+
+const { get, put, getAll } = vi.hoisted(() => ({ get: vi.fn(), put: vi.fn(), getAll: vi.fn() }))
+
+vi.mock('@/api/client', () => ({ apiClient: { get, put } }))
+vi.mock('@/api/admin', () => ({ adminAPI: { proxies: { getAll } } }))
+vi.mock('vue-i18n', () => ({ useI18n: () => ({ locale: ref('zh-CN') }) }))
+vi.mock('vue-router', () => ({ onBeforeRouteLeave: vi.fn() }))
+
+const proxy = (id: number, name: string, extra: Record = {}) => ({
+ id, name, protocol: 'http', host: `${name.toLowerCase()}.example.com`, port: 8000 + id, status: 'active', expires_at: null, ...extra
+})
+const proxies = [proxy(1, 'A'), proxy(2, 'B'), proxy(3, 'C')]
+const view = (overrides: Record = {}) => ({
+ mode: 'custom', proxy_ids: [3], source: 'pool', effective: [{ id: 3, name: 'C' }], unavailable: [], ...overrides
+})
+
+function deferred() {
+ let resolve!: (value: T) => void
+ const promise = new Promise(r => { resolve = r })
+ return { promise, resolve }
+}
+
+describe('CodexTicketProxyPool', () => {
+ beforeEach(() => {
+ getAll.mockResolvedValue(proxies)
+ get.mockResolvedValue({ data: view() })
+ })
+ afterEach(() => vi.clearAllMocks())
+
+ it('shows which proxies tickets actually rotate through', async () => {
+ const wrapper = mount(CodexTicketProxyPool)
+ await flushPromises()
+ expect(wrapper.get('[data-testid="pool-effective"]').text()).toContain('当前打票轮换:C')
+ expect(wrapper.find('[data-testid="pool-dirty"]').exists()).toBe(false)
+ wrapper.unmount()
+ })
+
+ it('flags unsaved edits and only treats the saved server state as current', async () => {
+ put.mockResolvedValue({ data: view({ proxy_ids: [1, 2], effective: [{ id: 1, name: 'A' }, { id: 2, name: 'B' }] }) })
+ const wrapper = mount(CodexTicketProxyPool)
+ await flushPromises()
+ await wrapper.get('[data-testid="pool-proxy-3"]').setValue(false)
+ await wrapper.get('[data-testid="pool-proxy-1"]').setValue(true)
+ await wrapper.get('[data-testid="pool-proxy-2"]').setValue(true)
+ expect(wrapper.find('[data-testid="pool-dirty"]').exists()).toBe(true)
+ expect(wrapper.get('[data-testid="pool-effective"]').text()).toContain('C')
+
+ await wrapper.get('[data-testid="pool-save"]').trigger('click')
+ await flushPromises()
+ expect(put).toHaveBeenCalledWith('/admin/proxies/codex-ticket-pool', { mode: 'custom', proxy_ids: [1, 2] })
+ expect(wrapper.find('[data-testid="pool-dirty"]').exists()).toBe(false)
+ expect(wrapper.get('[data-testid="pool-effective"]').text()).toContain('A、B')
+ wrapper.unmount()
+ })
+
+ it('keeps inputs disabled until the saved pool has loaded', async () => {
+ const pending = deferred<{ data: ReturnType }>()
+ get.mockReturnValue(pending.promise)
+ const wrapper = mount(CodexTicketProxyPool)
+ await flushPromises()
+ expect((wrapper.get('[data-testid="pool-mode-custom"]').element as HTMLInputElement).disabled).toBe(true)
+ pending.resolve({ data: view() })
+ await flushPromises()
+ expect((wrapper.get('[data-testid="pool-mode-custom"]').element as HTMLInputElement).disabled).toBe(false)
+ wrapper.unmount()
+ })
+
+ it('lists selections that are no longer available and does not resubmit them', async () => {
+ get.mockResolvedValue({ data: view({ proxy_ids: [1, 9], effective: [{ id: 1, name: 'A' }], unavailable: [{ id: 9, name: 'Old', reason: 'deleted' }] }) })
+ put.mockResolvedValue({ data: view({ proxy_ids: [1, 2], effective: [{ id: 1, name: 'A' }, { id: 2, name: 'B' }] }) })
+ const wrapper = mount(CodexTicketProxyPool)
+ await flushPromises()
+ expect(wrapper.get('[data-testid="pool-hidden"]').text()).toContain('Old')
+ await wrapper.get('[data-testid="pool-proxy-2"]').setValue(true)
+ await wrapper.get('[data-testid="pool-save"]').trigger('click')
+ await flushPromises()
+ expect(put).toHaveBeenCalledWith('/admin/proxies/codex-ticket-pool', { mode: 'custom', proxy_ids: [1, 2] })
+ wrapper.unmount()
+ })
+
+ it('says the pool is ignored when tickets use each account proxy', async () => {
+ get.mockResolvedValue({ data: view({ source: 'account' }) })
+ const wrapper = mount(CodexTicketProxyPool)
+ await flushPromises()
+ expect(wrapper.get('[data-testid="pool-effective"]').text()).toContain('此代理池不参与')
+ wrapper.unmount()
+ })
+
+ it('reload picks up proxies added elsewhere without discarding unsaved edits', async () => {
+ getAll.mockResolvedValueOnce([proxy(3, 'C')])
+ const wrapper = mount(CodexTicketProxyPool)
+ await flushPromises()
+ expect(wrapper.find('[data-testid="pool-proxy-1"]').exists()).toBe(false)
+ await wrapper.get('[data-testid="pool-mode-all"]').setValue(true)
+ await (wrapper.vm as unknown as { reload: () => Promise }).reload()
+ await flushPromises()
+ expect((wrapper.get('[data-testid="pool-mode-all"]').element as HTMLInputElement).checked).toBe(true)
+ await wrapper.get('[data-testid="pool-mode-custom"]').setValue(true)
+ expect(wrapper.find('[data-testid="pool-proxy-1"]').exists()).toBe(true)
+ wrapper.unmount()
+ })
+})
diff --git a/frontend/src/components/common/GroupBadge.vue b/frontend/src/components/common/GroupBadge.vue
index b87399d03..25fc5e54f 100644
--- a/frontend/src/components/common/GroupBadge.vue
+++ b/frontend/src/components/common/GroupBadge.vue
@@ -8,7 +8,7 @@
- {{ name }}
+ {{ name }}
@@ -45,6 +45,8 @@ interface Props {
peakEnd?: string
peakRateMultiplier?: number
showRate?: boolean
+ /** Allow full group names to wrap in layouts that have room for multiple lines. */
+ truncate?: boolean
daysRemaining?: number | null // 剩余天数(订阅类型时使用)
/**
* 订阅分组默认在右侧 label 展示"订阅"或剩余天数;
@@ -57,6 +59,7 @@ interface Props {
const props = withDefaults(defineProps(), {
subscriptionType: 'standard',
showRate: true,
+ truncate: true,
daysRemaining: null,
userRateMultiplier: null,
peakRateEnabled: false,
diff --git a/frontend/src/components/common/LocaleSwitcher.vue b/frontend/src/components/common/LocaleSwitcher.vue
index 417e5a23b..5dd2fb35f 100644
--- a/frontend/src/components/common/LocaleSwitcher.vue
+++ b/frontend/src/components/common/LocaleSwitcher.vue
@@ -69,6 +69,8 @@ async function selectLocale(code: string) {
try {
await setLocale(code)
isOpen.value = false
+ // 分组名称等内容由后端按请求语言返回,整页刷新让已加载的数据换成新语言
+ window.location.reload()
} finally {
switching.value = false
}
diff --git a/frontend/src/components/common/PlatformTypeBadge.vue b/frontend/src/components/common/PlatformTypeBadge.vue
index 13e6f5ad0..0748b5bcc 100644
--- a/frontend/src/components/common/PlatformTypeBadge.vue
+++ b/frontend/src/components/common/PlatformTypeBadge.vue
@@ -109,7 +109,7 @@ const typeLabel = computed(() => {
case 'bedrock':
return 'AWS'
case 'service_account':
- return 'Vertex'
+ return 'Agent Platform (Vertex)'
default:
return props.type
}
diff --git a/frontend/src/components/common/Select.vue b/frontend/src/components/common/Select.vue
index c062bd4fd..68825af14 100644
--- a/frontend/src/components/common/Select.vue
+++ b/frontend/src/components/common/Select.vue
@@ -446,6 +446,7 @@ const onTriggerKeyDown = () => {
}
const onDropdownKeyDown = (e: KeyboardEvent) => {
+ if (e.isComposing) return
switch (e.key) {
case 'ArrowDown':
e.preventDefault()
diff --git a/frontend/src/components/common/__tests__/LocaleSwitcher.spec.ts b/frontend/src/components/common/__tests__/LocaleSwitcher.spec.ts
new file mode 100644
index 000000000..ddd9b4e44
--- /dev/null
+++ b/frontend/src/components/common/__tests__/LocaleSwitcher.spec.ts
@@ -0,0 +1,60 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import LocaleSwitcher from '../LocaleSwitcher.vue'
+
+const { setLocale } = vi.hoisted(() => ({ setLocale: vi.fn() }))
+
+vi.mock('@/i18n', () => ({
+ setLocale,
+ availableLocales: [
+ { code: 'en', name: 'English', flag: '🇺🇸' },
+ { code: 'zh', name: '中文', flag: '🇨🇳' }
+ ]
+}))
+
+vi.mock('vue-i18n', () => ({ useI18n: () => ({ locale: { value: 'zh' } }) }))
+
+const reload = vi.fn()
+
+const mountSwitcher = () =>
+ mount(LocaleSwitcher, { global: { stubs: { Icon: true, transition: false } } })
+
+const choose = async (wrapper: ReturnType, name: string) => {
+ await wrapper.get('button').trigger('click')
+ const option = wrapper.findAll('button').find((button) => button.text().includes(name))
+ await option!.trigger('click')
+ await flushPromises()
+}
+
+describe('LocaleSwitcher', () => {
+ beforeEach(() => {
+ setLocale.mockReset().mockResolvedValue(undefined)
+ reload.mockReset()
+ vi.stubGlobal('location', { ...window.location, reload })
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ // 分组名称等内容由后端按请求语言返回,已加载的数据要靠整页刷新换成新语言
+ it('reloads the page after switching to another language', async () => {
+ const wrapper = mountSwitcher()
+
+ await choose(wrapper, 'English')
+
+ expect(setLocale).toHaveBeenCalledWith('en')
+ expect(reload).toHaveBeenCalledTimes(1)
+ expect(setLocale.mock.invocationCallOrder[0]).toBeLessThan(reload.mock.invocationCallOrder[0])
+ })
+
+ it('does nothing when the current language is chosen again', async () => {
+ const wrapper = mountSwitcher()
+
+ await choose(wrapper, '中文')
+
+ expect(setLocale).not.toHaveBeenCalled()
+ expect(reload).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/components/common/__tests__/Select.ime.spec.ts b/frontend/src/components/common/__tests__/Select.ime.spec.ts
new file mode 100644
index 000000000..7d92ab201
--- /dev/null
+++ b/frontend/src/components/common/__tests__/Select.ime.spec.ts
@@ -0,0 +1,32 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { enableAutoUnmount, mount } from '@vue/test-utils'
+import { nextTick } from 'vue'
+import Select from '../Select.vue'
+
+vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
+enableAutoUnmount(afterEach)
+afterEach(() => { document.body.innerHTML = '' })
+
+describe('Select IME keyboard input', () => {
+ it.each(['Enter', 'Escape', 'ArrowDown', 'ArrowUp'])('leaves composing %s to the input method', async (key) => {
+ const wrapper = mount(Select, {
+ attachTo: document.body,
+ props: { modelValue: null, searchable: true, options: [
+ { value: 'first', label: 'First' }, { value: 'second', label: 'Second' }
+ ] }
+ })
+ await wrapper.get('button').trigger('click')
+ await nextTick()
+ const input = document.querySelector('.select-search-input')!
+ expect(document.activeElement).toBe(input)
+ const composing = new KeyboardEvent('keydown', { key, isComposing: true, bubbles: true, cancelable: true })
+ input.dispatchEvent(composing)
+ await nextTick()
+ expect(composing.defaultPrevented).toBe(false)
+ expect(wrapper.emitted('update:modelValue')).toBeUndefined()
+ expect(wrapper.get('button').attributes('aria-expanded')).toBe('true')
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
+ await nextTick()
+ expect(wrapper.emitted('update:modelValue')).toEqual([['first']])
+ })
+})
diff --git a/frontend/src/components/payment/PaymentQRDialog.vue b/frontend/src/components/payment/PaymentQRDialog.vue
index 7dff831a6..621d8f010 100644
--- a/frontend/src/components/payment/PaymentQRDialog.vue
+++ b/frontend/src/components/payment/PaymentQRDialog.vue
@@ -234,12 +234,13 @@ async function tryRecoverPendingOrder(order: PaymentOrder): Promise {
- remainingSeconds.value--
+ remainingSeconds.value = Math.max(0, Math.floor((deadline - Date.now()) / 1000))
if (remainingSeconds.value <= 0) {
expired.value = true
cleanup()
diff --git a/frontend/src/components/payment/PaymentStatusPanel.vue b/frontend/src/components/payment/PaymentStatusPanel.vue
index e751c4222..243ffac76 100644
--- a/frontend/src/components/payment/PaymentStatusPanel.vue
+++ b/frontend/src/components/payment/PaymentStatusPanel.vue
@@ -450,9 +450,10 @@ async function pollStatus() {
function startCountdown(seconds: number) {
remainingSeconds.value = Math.max(0, seconds)
+ const deadline = Date.now() + remainingSeconds.value * 1000
if (remainingSeconds.value <= 0) { setOutcome('expired'); return }
countdownTimer = setInterval(() => {
- remainingSeconds.value--
+ remainingSeconds.value = Math.max(0, Math.floor((deadline - Date.now()) / 1000))
if (remainingSeconds.value <= 0) { setOutcome('expired'); cleanup() }
}, 1000)
}
diff --git a/frontend/src/components/payment/__tests__/paymentCountdown.spec.ts b/frontend/src/components/payment/__tests__/paymentCountdown.spec.ts
new file mode 100644
index 000000000..fec389247
--- /dev/null
+++ b/frontend/src/components/payment/__tests__/paymentCountdown.spec.ts
@@ -0,0 +1,68 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { enableAutoUnmount, mount } from '@vue/test-utils'
+import PaymentQRDialog from '../PaymentQRDialog.vue'
+import PaymentStatusPanel from '../PaymentStatusPanel.vue'
+import PaymentQRCodeView from '@/views/user/PaymentQRCodeView.vue'
+
+vi.mock('vue-i18n', async (importOriginal) => ({
+ ...await importOriginal(),
+ useI18n: () => ({ t: (key: string) => key }),
+}))
+vi.mock('@/components/layout/AppLayout.vue', () => ({
+ default: { template: '
' },
+}))
+vi.mock('@/stores/payment', () => ({
+ usePaymentStore: () => ({ pollOrderStatus: vi.fn().mockResolvedValue(null) }),
+}))
+vi.mock('@/stores', () => ({ useAppStore: () => ({ showError: vi.fn() }) }))
+vi.mock('@/api/payment', () => ({ paymentAPI: {} }))
+vi.mock('qrcode', () => ({ default: { toCanvas: vi.fn() } }))
+vi.mock('vue-router', () => ({
+ useRoute: () => ({ query: { order_id: '42', expires_at: new Date(Date.now() + 120_000).toISOString() } }),
+ useRouter: () => ({ push: vi.fn() }),
+}))
+
+enableAutoUnmount(afterEach)
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-09-30T12:00:00Z'))
+})
+afterEach(() => vi.useRealTimers())
+
+async function open(kind: 'dialog' | 'panel' | 'page') {
+ const props = { orderId: 42, qrCode: '', expiresAt: new Date(Date.now() + 120_000).toISOString(), paymentType: 'custom' }
+ const global = { stubs: {
+ Icon: true,
+ AppLayout: { template: '
' },
+ BaseDialog: { props: ['show'], template: '
' },
+ } }
+ if (kind === 'page') return mount(PaymentQRCodeView, { global })
+ if (kind === 'panel') return mount(PaymentStatusPanel, { props, global })
+ const wrapper = mount(PaymentQRDialog, { props: { ...props, show: false }, global })
+ await wrapper.setProps({ show: true })
+ return wrapper
+}
+
+describe.each(['dialog', 'panel', 'page'] as const)('payment countdown: %s', (kind) => {
+ it('catches up after timers were suspended', async () => {
+ const wrapper = await open(kind)
+ expect(wrapper.text()).toContain('02:00')
+ vi.setSystemTime(Date.now() + 65_000)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(wrapper.text()).toContain('00:54')
+ })
+
+ it('expires and stops polling on the first overdue tick', async () => {
+ const wrapper = await open(kind)
+ vi.setSystemTime(Date.now() + 121_000)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(wrapper.text()).toContain('payment.qr.expired')
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('still counts down normally', async () => {
+ const wrapper = await open(kind)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(wrapper.text()).toContain('01:59')
+ })
+})
diff --git a/frontend/src/composables/__tests__/useGeminiOAuth.errors.spec.ts b/frontend/src/composables/__tests__/useGeminiOAuth.errors.spec.ts
new file mode 100644
index 000000000..e2f255558
--- /dev/null
+++ b/frontend/src/composables/__tests__/useGeminiOAuth.errors.spec.ts
@@ -0,0 +1,39 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { useGeminiOAuth } from '../useGeminiOAuth'
+
+const mocks = vi.hoisted(() => ({ generateAuthUrl: vi.fn(), showError: vi.fn() }))
+vi.mock('@/api/admin', () => ({ adminAPI: { gemini: { generateAuthUrl: mocks.generateAuthUrl } } }))
+vi.mock('@/stores/app', () => ({ useAppStore: () => ({ showError: mocks.showError }) }))
+vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
+beforeEach(() => vi.resetAllMocks())
+
+describe('Gemini authorization URL errors', () => {
+ it.each([
+ [{ status: 400, message: 'Selected proxy is unavailable' }, 'Selected proxy is unavailable'],
+ [{ response: { data: { detail: 'OAuth is not configured' } } }, 'OAuth is not configured'],
+ [{}, 'admin.accounts.oauth.gemini.failedToGenerateUrl'],
+ [null, 'admin.accounts.oauth.gemini.failedToGenerateUrl']
+ ])('preserves useful API feedback for %j', async (error, expected) => {
+ mocks.generateAuthUrl.mockRejectedValue(error)
+ const oauth = useGeminiOAuth()
+ expect(await oauth.generateAuthUrl(7)).toBe(false)
+ expect(oauth.error.value).toBe(expected)
+ expect(mocks.showError).toHaveBeenCalledWith(expected)
+ expect(oauth.loading.value).toBe(false)
+ expect(oauth.authUrl.value).toBe('')
+ })
+
+ it('can retry successfully after an error', async () => {
+ mocks.generateAuthUrl.mockRejectedValueOnce({ message: 'Temporary failure' }).mockResolvedValueOnce({
+ auth_url: 'https://example.com/auth', session_id: 'session', state: 'state'
+ })
+ const oauth = useGeminiOAuth()
+ await oauth.generateAuthUrl(7)
+ expect(await oauth.generateAuthUrl(7, ' project ')).toBe(true)
+ expect(oauth.error.value).toBe('')
+ expect(oauth.authUrl.value).toBe('https://example.com/auth')
+ expect(oauth.sessionId.value).toBe('session')
+ expect(oauth.state.value).toBe('state')
+ expect(mocks.generateAuthUrl).toHaveBeenLastCalledWith({ proxy_id: 7, project_id: 'project' })
+ })
+})
diff --git a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts
index 75c2b371b..97d132b1a 100644
--- a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts
+++ b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts
@@ -100,6 +100,16 @@ describe('useModelWhitelist', () => {
]))
})
+ it('Claude 默认白名单保存后允许 Haiku 5.5,预设使用同一模型 ID', () => {
+ const models: string[] = getModelsByPlatform('anthropic')
+ const mapping: Record | null = buildModelMappingObject('whitelist', models, [])
+
+ expect(mapping?.['claude-haiku-5-5']).toBe('claude-haiku-5-5')
+ expect(getPresetMappingsByPlatform('anthropic')).toEqual(expect.arrayContaining([
+ expect.objectContaining({ label: 'Haiku 5.5', from: 'claude-haiku-5-5', to: 'claude-haiku-5-5' })
+ ]))
+ })
+
it('xAI 模型列表包含 Grok 4.5 官方模型和别名', () => {
const models = getModelsByPlatform('grok')
@@ -161,6 +171,21 @@ describe('useModelWhitelist', () => {
expect(models).toContain('gemini-3.1-pro')
})
+ it('Gemini 4 Argon 在 gemini 与 antigravity 平台使用对应真实模型 ID 与预设映射', () => {
+ expect(getModelsByPlatform('gemini')).toContain('gemini-4-argon')
+ const agModels = getModelsByPlatform('antigravity')
+ expect(agModels).not.toContain('gemini-4-argon')
+ expect(agModels).toContain('gemini-4-argon-high')
+ expect(agModels).toContain('gemini-4-argon-medium')
+ expect(agModels).toContain('gemini-4-argon-low')
+ expect(getPresetMappingsByPlatform('antigravity')).toEqual(expect.arrayContaining([
+ expect.objectContaining({ from: 'gemini-4-argon', to: 'gemini-4-argon-high' }),
+ expect.objectContaining({ from: 'gemini-4-argon-high', to: 'gemini-4-argon-high' }),
+ expect.objectContaining({ from: 'gemini-4-argon-medium', to: 'gemini-4-argon-medium' }),
+ expect.objectContaining({ from: 'gemini-4-argon-low', to: 'gemini-4-argon-low' })
+ ]))
+ })
+
it('whitelist 模式会忽略通配符条目', () => {
const mapping = buildModelMappingObject('whitelist', ['claude-*', 'gemini-3.1-flash-image'], [])
expect(mapping).toEqual({
diff --git a/frontend/src/composables/useGeminiOAuth.ts b/frontend/src/composables/useGeminiOAuth.ts
index 51abdbbfe..955070402 100644
--- a/frontend/src/composables/useGeminiOAuth.ts
+++ b/frontend/src/composables/useGeminiOAuth.ts
@@ -2,6 +2,7 @@ import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'
import { adminAPI } from '@/api/admin'
+import { extractApiErrorMessage } from '@/utils/apiError'
import type { GeminiOAuthCapabilities } from '@/api/admin/gemini'
export interface GeminiTokenInfo {
@@ -61,8 +62,8 @@ export function useGeminiOAuth() {
sessionId.value = response.session_id
state.value = response.state
return true
- } catch (err: any) {
- error.value = err.response?.data?.detail || t('admin.accounts.oauth.gemini.failedToGenerateUrl')
+ } catch (err: unknown) {
+ error.value = extractApiErrorMessage(err, t('admin.accounts.oauth.gemini.failedToGenerateUrl'))
appStore.showError(error.value)
return false
} finally {
diff --git a/frontend/src/composables/useModelWhitelist.ts b/frontend/src/composables/useModelWhitelist.ts
index 4b9a117fa..cf1db7315 100644
--- a/frontend/src/composables/useModelWhitelist.ts
+++ b/frontend/src/composables/useModelWhitelist.ts
@@ -39,6 +39,7 @@ export const claudeModels = [
'claude-opus-5-5',
'claude-opus-5',
'claude-sonnet-5-5',
+ 'claude-haiku-5-5',
'claude-sonnet-5',
'claude-sonnet-4-6',
'claude-fable-5-1',
@@ -56,15 +57,22 @@ const geminiModels = [
'gemini-2.5-pro',
'gemini-3.5-flash',
'gemini-3-flash-preview',
- 'gemini-3-pro-preview'
+ 'gemini-3-pro-preview',
+ 'gemini-4-argon'
]
// Antigravity 官方支持的模型(精确匹配)
// 基于官方 API 返回的模型列表,只支持 Claude 4.5+ 和 Gemini 2.5+
const antigravityModels = [
- // Claude 4.5+ 系列
+ // Claude 4.5+ / 5.5 系列
'claude-fable-5-1',
'claude-fable-5',
+ 'claude-opus-5-5-high',
+ 'claude-opus-5-5-medium',
+ 'claude-opus-5-5-low',
+ 'claude-sonnet-5-5-high',
+ 'claude-sonnet-5-5-medium',
+ 'claude-sonnet-5-5-low',
'claude-opus-4-6',
'claude-opus-4-6-thinking',
'claude-opus-4-7',
@@ -88,7 +96,28 @@ const antigravityModels = [
'gemini-3.1-pro',
'gemini-3.1-pro-high',
'gemini-3.1-pro-low',
+ 'gemini-pro-agent',
'gemini-3-pro-image',
+ // Gemini 3.6 / 3.7 / 3.8 Flash 系列
+ 'gemini-3.6-flash',
+ 'gemini-3.6-flash-low',
+ 'gemini-3.6-flash-medium',
+ 'gemini-3.6-flash-high',
+ 'gemini-3.6-flash-tiered',
+ 'gemini-3.7-flash',
+ 'gemini-3.7-flash-low',
+ 'gemini-3.7-flash-medium',
+ 'gemini-3.7-flash-high',
+ 'gemini-3.7-flash-tiered',
+ 'gemini-3.8-flash',
+ 'gemini-3.8-flash-low',
+ 'gemini-3.8-flash-medium',
+ 'gemini-3.8-flash-high',
+ 'gemini-3.8-flash-tiered',
+ // Gemini 4 Argon 系列
+ 'gemini-4-argon-low',
+ 'gemini-4-argon-medium',
+ 'gemini-4-argon-high',
// 其他
'gpt-oss-120b-medium',
'tab_flash_lite_preview'
@@ -299,6 +328,7 @@ const anthropicPresetMappings = [
{ label: 'Opus 5', from: 'claude-opus-5', to: 'claude-opus-5', color: 'bg-purple-100 text-purple-700 hover:bg-purple-200 dark:bg-purple-900/30 dark:text-purple-400' },
{ label: 'Haiku 3.5', from: 'claude-3-5-haiku-20241022', to: 'claude-3-5-haiku-20241022', color: 'bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400' },
{ label: 'Haiku 4.5', from: 'claude-haiku-4-5-20251001', to: 'claude-haiku-4-5-20251001', color: 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400' },
+ { label: 'Haiku 5.5', from: 'claude-haiku-5-5', to: 'claude-haiku-5-5', color: 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400' },
{ label: 'Opus->Sonnet', from: 'claude-opus-4-6', to: 'claude-sonnet-4-5-20250929', color: 'bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400' }
]
@@ -355,7 +385,22 @@ const grokPresetMappings = [
// Antigravity 预设映射(支持通配符)
const antigravityPresetMappings = [
+ // Claude 5.5 / Gemini 4 Argon / 3.8 Flash 推荐映射
+ { label: '4 Argon→High', from: 'gemini-4-argon', to: 'gemini-4-argon-high', color: 'bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400' },
+ { label: '4 Argon High', from: 'gemini-4-argon-high', to: 'gemini-4-argon-high', color: 'bg-orange-100 text-orange-700 hover:bg-orange-200 dark:bg-orange-900/30 dark:text-orange-400' },
+ { label: '4 Argon Medium', from: 'gemini-4-argon-medium', to: 'gemini-4-argon-medium', color: 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200 dark:bg-yellow-900/30 dark:text-yellow-400' },
+ { label: '4 Argon Low', from: 'gemini-4-argon-low', to: 'gemini-4-argon-low', color: 'bg-lime-100 text-lime-700 hover:bg-lime-200 dark:bg-lime-900/30 dark:text-lime-400' },
+ { label: '3.8 Flash', from: 'gemini-3.8-flash', to: 'gemini-3.8-flash', color: 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400' },
+ { label: '3.8 Flash High', from: 'gemini-3.8-flash-high', to: 'gemini-3.8-flash-high', color: 'bg-teal-100 text-teal-700 hover:bg-teal-200 dark:bg-teal-900/30 dark:text-teal-400' },
+ { label: 'Opus 5.5→High', from: 'claude-opus-5-5', to: 'claude-opus-5-5-high', color: 'bg-pink-100 text-pink-700 hover:bg-pink-200 dark:bg-pink-900/30 dark:text-pink-400' },
+ { label: 'Opus 5.5 High', from: 'claude-opus-5-5-high', to: 'claude-opus-5-5-high', color: 'bg-pink-100 text-pink-700 hover:bg-pink-200 dark:bg-pink-900/30 dark:text-pink-400' },
+ { label: 'Opus 5.5 Medium', from: 'claude-opus-5-5-medium', to: 'claude-opus-5-5-medium', color: 'bg-purple-100 text-purple-700 hover:bg-purple-200 dark:bg-purple-900/30 dark:text-purple-400' },
+ { label: 'Sonnet 5.5→High', from: 'claude-sonnet-5-5', to: 'claude-sonnet-5-5-high', color: 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200 dark:bg-indigo-900/30 dark:text-indigo-400' },
+ { label: 'Sonnet 5.5 High', from: 'claude-sonnet-5-5-high', to: 'claude-sonnet-5-5-high', color: 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200 dark:bg-indigo-900/30 dark:text-indigo-400' },
+ { label: 'Sonnet 5.5 Medium', from: 'claude-sonnet-5-5-medium', to: 'claude-sonnet-5-5-medium', color: 'bg-cyan-100 text-cyan-700 hover:bg-cyan-200 dark:bg-cyan-900/30 dark:text-cyan-400' },
// Claude 通配符映射
+ { label: 'Claude→Sonnet 5.5', from: 'claude-*', to: 'claude-sonnet-5-5-high', color: 'bg-blue-100 text-blue-700 hover:bg-blue-200 dark:bg-blue-900/30 dark:text-blue-400' },
+ { label: 'Opus→Opus 5.5', from: 'claude-opus-*', to: 'claude-opus-5-5-high', color: 'bg-purple-100 text-purple-700 hover:bg-purple-200 dark:bg-purple-900/30 dark:text-purple-400' },
{ label: 'Claude→Sonnet', from: 'claude-*', to: 'claude-sonnet-4-5', color: 'bg-blue-100 text-blue-700 hover:bg-blue-200 dark:bg-blue-900/30 dark:text-blue-400' },
{ label: 'Fable 5.1', from: 'claude-fable-5-1', to: 'claude-fable-5-1', color: 'bg-rose-100 text-rose-700 hover:bg-rose-200 dark:bg-rose-900/30 dark:text-rose-400' },
{ label: 'Fable 5', from: 'claude-fable-5', to: 'claude-fable-5', color: 'bg-rose-100 text-rose-700 hover:bg-rose-200 dark:bg-rose-900/30 dark:text-rose-400' },
@@ -366,7 +411,8 @@ const antigravityPresetMappings = [
{ label: 'Sonnet4.5→4.6', from: 'claude-sonnet-4-5-20250929', to: 'claude-sonnet-4-6', color: 'bg-cyan-100 text-cyan-700 hover:bg-cyan-200 dark:bg-cyan-900/30 dark:text-cyan-400' },
{ label: 'Sonnet3.5→4.6', from: 'claude-3-5-sonnet-20241022', to: 'claude-sonnet-4-6', color: 'bg-teal-100 text-teal-700 hover:bg-teal-200 dark:bg-teal-900/30 dark:text-teal-400' },
{ label: 'Opus4.5→4.6', from: 'claude-opus-4-5-20251101', to: 'claude-opus-4-6-thinking', color: 'bg-violet-100 text-violet-700 hover:bg-violet-200 dark:bg-violet-900/30 dark:text-violet-400' },
- // Gemini 3→3.1 映射
+ // Gemini 3→3.1 / 4 Argon 映射
+ { label: '3.1-Pro→4-Argon-High', from: 'gemini-3.1-pro*', to: 'gemini-4-argon-high', color: 'bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400' },
{ label: '3-Pro-Preview→Pro-Agent', from: 'gemini-3-pro-preview', to: 'gemini-pro-agent', color: 'bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400' },
{ label: '3-Pro-High→Pro-Agent', from: 'gemini-3-pro-high', to: 'gemini-pro-agent', color: 'bg-orange-100 text-orange-700 hover:bg-orange-200 dark:bg-orange-900/30 dark:text-orange-400' },
{ label: '3-Pro-Low→3.1-Pro-Low', from: 'gemini-3-pro-low', to: 'gemini-3.1-pro-low', color: 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200 dark:bg-yellow-900/30 dark:text-yellow-400' },
@@ -376,6 +422,7 @@ const antigravityPresetMappings = [
{ label: '3.1-Pro-Low透传', from: 'gemini-3.1-pro-low', to: 'gemini-3.1-pro-low', color: 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200 dark:bg-yellow-900/30 dark:text-yellow-400' },
{ label: '3.1-Pro-Preview→Pro-Agent', from: 'gemini-3.1-pro-preview', to: 'gemini-pro-agent', color: 'bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400' },
// Gemini 通配符映射
+ { label: 'Gemini 3→3.8 Flash', from: 'gemini-3*', to: 'gemini-3.8-flash-high', color: 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200 dark:bg-yellow-900/30 dark:text-yellow-400' },
{ label: 'Gemini 3→Flash', from: 'gemini-3*', to: 'gemini-3-flash', color: 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200 dark:bg-yellow-900/30 dark:text-yellow-400' },
{ label: 'Gemini 2.5→Flash', from: 'gemini-2.5*', to: 'gemini-2.5-flash', color: 'bg-orange-100 text-orange-700 hover:bg-orange-200 dark:bg-orange-900/30 dark:text-orange-400' },
{ label: '2.5-Flash-Image透传', from: 'gemini-2.5-flash-image', to: 'gemini-2.5-flash-image', color: 'bg-sky-100 text-sky-700 hover:bg-sky-200 dark:bg-sky-900/30 dark:text-sky-400' },
diff --git a/frontend/src/features/channel-monitor-v2/MonitorSettingsPanel.vue b/frontend/src/features/channel-monitor-v2/MonitorSettingsPanel.vue
index 12ed52444..0d70a4b9b 100644
--- a/frontend/src/features/channel-monitor-v2/MonitorSettingsPanel.vue
+++ b/frontend/src/features/channel-monitor-v2/MonitorSettingsPanel.vue
@@ -89,6 +89,24 @@
{{ t('channelMonitorV2.settings.platformsHint') }}
+
+
+
+ {{ t('channelMonitorV2.settings.addPlatform') }}
+
+
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
+import Select from '@/components/common/Select.vue'
+import { CONCRETE_PLATFORM_OPTIONS } from '@/constants/platforms'
import Toggle from '@/components/common/Toggle.vue'
import Icon from '@/components/icons/Icon.vue'
import { useAppStore } from '@/stores/app'
@@ -284,6 +304,18 @@ const saving = ref(false)
const draft = ref
(null)
const original = ref('')
const groups = ref([])
+const selectedPlatform = ref('')
+const availablePlatforms = computed(() =>
+ CONCRETE_PLATFORM_OPTIONS.filter(
+ (option) => !draft.value?.platforms.some((platform) => platform.platform === option.value)
+ )
+)
+
+function addPlatform() {
+ if (!draft.value || !availablePlatforms.value.some((option) => option.value === selectedPlatform.value)) return
+ draft.value.platforms.push({ platform: selectedPlatform.value, enabled: true, models: [] })
+ selectedPlatform.value = ''
+}
const dirty = computed(() => (draft.value ? JSON.stringify(draft.value) !== original.value : false))
const namedModelCount = computed(
diff --git a/frontend/src/features/channel-monitor-v2/__tests__/MonitorSettingsPanel.spec.ts b/frontend/src/features/channel-monitor-v2/__tests__/MonitorSettingsPanel.spec.ts
new file mode 100644
index 000000000..c5cb4fc35
--- /dev/null
+++ b/frontend/src/features/channel-monitor-v2/__tests__/MonitorSettingsPanel.spec.ts
@@ -0,0 +1,153 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import Select from '@/components/common/Select.vue'
+import MonitorSettingsPanel from '../MonitorSettingsPanel.vue'
+import { CONCRETE_PLATFORM_OPTIONS } from '@/constants/platforms'
+import type { MonitorConfig } from '@/api/channelMonitorV2'
+
+const mocks = vi.hoisted(() => ({
+ getConfig: vi.fn(),
+ updateConfig: vi.fn(),
+ groups: vi.fn(),
+ showError: vi.fn(),
+ showSuccess: vi.fn(),
+}))
+vi.mock('@/api/channelMonitorV2', () => ({
+ getConfig: mocks.getConfig,
+ updateConfig: mocks.updateConfig,
+ MONITOR_ERROR_CATEGORIES: ['authentication', 'network'],
+}))
+vi.mock('@/api/admin', () => ({ adminAPI: { groups: { getAllIncludingInactive: mocks.groups } } }))
+vi.mock('@/stores/app', () => ({ useAppStore: () => ({
+ cachedPublicSettings: { channel_monitor_enabled: true },
+ showError: mocks.showError,
+ showSuccess: mocks.showSuccess,
+}) }))
+vi.mock('@/utils/featureFlags', () => ({
+ getChannelMonitorMode: () => 'v2',
+ isChannelMonitorV2Mode: () => true,
+}))
+vi.mock('vue-i18n', () => ({
+ useI18n: () => ({ t: (key: string) => key, te: () => false }),
+}))
+
+function config(): MonitorConfig {
+ return {
+ version: 2,
+ enabled: true,
+ refresh_interval_seconds: 60,
+ platforms: [
+ { platform: 'openai', enabled: false, models: ['gpt-4'] },
+ { platform: 'custom-provider', enabled: true, models: ['custom-model'] },
+ ],
+ group_ids: [42],
+ ignored_error_categories: [],
+ health_thresholds: {
+ minimum_sample: 70, warning_error_rate: 0.1, critical_error_rate: 0.3,
+ target_ttft_ms: 1500, warning_ttft_ms: 2000, critical_ttft_ms: 5000,
+ warning_cache_rate: 0.7, critical_cache_rate: 0.4,
+ error_weight: 0.5, ttft_weight: 0.3, cache_weight: 0.2,
+ },
+ }
+}
+
+async function panel(value = config()) {
+ mocks.getConfig.mockResolvedValue(value)
+ const wrapper = mount(MonitorSettingsPanel, { global: { stubs: { RouterLink: true, teleport: true } } })
+ await flushPromises()
+ return wrapper
+}
+
+function button(wrapper: Awaited>, key: string) {
+ return wrapper.findAll('button').find((item) => item.text() === 'channelMonitorV2.settings.' + key)!
+}
+
+async function add(wrapper: Awaited>, platform: string) {
+ wrapper.findComponent(Select).vm.$emit('update:modelValue', platform)
+ await flushPromises()
+ await button(wrapper, 'addPlatform').trigger('click')
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.groups.mockResolvedValue([])
+ mocks.updateConfig.mockImplementation(async (value) => JSON.parse(JSON.stringify(value)))
+})
+
+describe('MonitorSettingsPanel platform configuration', () => {
+ it('adds a missing provider and saves its models without changing existing settings', async () => {
+ const original = config()
+ const wrapper = await panel(original)
+ expect(button(wrapper, 'save').attributes('disabled')).toBeDefined()
+ expect(wrapper.findComponent(Select).props('options')).not.toContainEqual(expect.objectContaining({ value: 'openai' }))
+
+ await wrapper.findComponent(Select).find('button').trigger('click')
+ const option = wrapper.findAll('[role="option"]').find((item) => item.text() === 'DeepSeek')!
+ await option.trigger('click')
+ await button(wrapper, 'addPlatform').trigger('click')
+ expect(button(wrapper, 'addPlatform').attributes('disabled')).toBeDefined()
+ expect(wrapper.findComponent(Select).props('options')).not.toContainEqual(
+ expect.objectContaining({ value: 'deepseek' })
+ )
+ const models = wrapper.findAll('input[type="text"]').at(-1)!
+ await models.setValue(' deepseek-chat, deepseek-reasoner, deepseek-chat ')
+ await button(wrapper, 'save').trigger('click')
+ await flushPromises()
+
+ expect(mocks.updateConfig).toHaveBeenCalledWith({
+ ...original,
+ platforms: [...original.platforms, {
+ platform: 'deepseek', enabled: true, models: ['deepseek-chat', 'deepseek-reasoner'],
+ }],
+ })
+ expect(button(wrapper, 'save').attributes('disabled')).toBeDefined()
+ expect(original.platforms).toHaveLength(2)
+
+ const persisted = mocks.updateConfig.mock.results[0].value
+ wrapper.unmount()
+ const reloaded = await panel(await persisted)
+ expect((reloaded.findAll('input[type="text"]').at(-1)!.element as HTMLInputElement).value).toBe('deepseek-chat, deepseek-reasoner')
+ expect(reloaded.findComponent(Select).props('options')).not.toContainEqual(
+ expect.objectContaining({ value: 'deepseek' })
+ )
+ reloaded.unmount()
+ })
+
+ it('can start with no configured platforms and rejects duplicate additions', async () => {
+ const wrapper = await panel({ ...config(), platforms: [] })
+ expect(button(wrapper, 'addPlatform').attributes('disabled')).toBeDefined()
+ await add(wrapper, 'kimi')
+ await add(wrapper, 'kimi')
+ await button(wrapper, 'save').trigger('click')
+ await flushPromises()
+ expect(mocks.updateConfig.mock.calls[0][0].platforms).toEqual([
+ { platform: 'kimi', enabled: true, models: [] },
+ ])
+ wrapper.unmount()
+ })
+
+ it('restores the server config and available options when saving fails', async () => {
+ const wrapper = await panel()
+ mocks.updateConfig.mockRejectedValueOnce(new Error('save failed'))
+ await add(wrapper, 'minimax')
+ await button(wrapper, 'save').trigger('click')
+ await flushPromises()
+ expect(mocks.showError).toHaveBeenCalledOnce()
+ expect(wrapper.findComponent(Select).props('options')).toContainEqual(
+ expect.objectContaining({ value: 'minimax' })
+ )
+ expect(wrapper.findAll('input[type="text"]')).toHaveLength(2)
+ expect(button(wrapper, 'save').attributes('disabled')).toBeDefined()
+ wrapper.unmount()
+ })
+
+ it('hides the add control after every supported platform is configured', async () => {
+ const wrapper = await panel({
+ ...config(),
+ platforms: CONCRETE_PLATFORM_OPTIONS.map(({ value }) => ({ platform: value, enabled: true, models: [] })),
+ })
+ expect(wrapper.findComponent(Select).exists()).toBe(false)
+ expect(button(wrapper, 'addPlatform')).toBeUndefined()
+ wrapper.unmount()
+ })
+})
diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts
index 1e08307e4..cf3944993 100644
--- a/frontend/src/i18n/locales/en/admin/accounts.ts
+++ b/frontend/src/i18n/locales/en/admin/accounts.ts
@@ -193,8 +193,6 @@ export default {
editAccount: 'Edit Account',
deleteAccount: 'Delete Account',
searchAccounts: 'Search accounts...',
- moreFilters: 'More filters',
- moreFiltersActive: 'More filters ({count} active)',
notes: 'Notes',
notesPlaceholder: 'Enter notes',
notesHint: 'Notes are optional',
@@ -530,7 +528,7 @@ export default {
tempUnschedulable: {
title: 'Temp Unschedulable',
statusTitle: 'Temp Unschedulable Status',
- hint: 'Disable accounts temporarily when error code and keyword both match.',
+ hint: 'When error code and keyword both match, pause the whole account or cool down only the model for the configured duration, per the rule scope.',
notice: 'Rules are evaluated in order and require both error code and keyword match.',
addRule: 'Add Rule',
ruleOrder: 'Rule Order',
@@ -546,6 +544,12 @@ export default {
keywords: 'Keywords',
keywordsPlaceholder: 'e.g. overloaded, too many requests',
keywordsHint: 'Separate keywords with commas; any keyword match will trigger.',
+ scope: 'Scope',
+ scopeModel: 'Model',
+ scopeModelDesc: 'Cool down only the requested model',
+ scopeAccount: 'Account',
+ scopeAccountDesc: 'Pause scheduling for the whole account',
+ scopeHint: 'Model-scoped rules fall back to account scope when the request model cannot be identified.',
description: 'Description',
descriptionPlaceholder: 'Optional note for this rule',
rulesInvalid: 'Add at least one rule with error code, keywords, and duration.',
@@ -704,10 +708,18 @@ export default {
claudeConsole: 'Claude Console',
bedrockLabel: 'AWS Bedrock',
bedrockDesc: 'SigV4 / API Key',
- vertexLabel: 'Vertex',
+ vertexLabel: 'Agent Platform (Vertex)',
vertexDesc: 'Service Account',
- vertexAnthropicHint: 'Use a Google Cloud Service Account JSON to call Anthropic Claude via Vertex AI. It is recommended to configure model mapping to map client Claude model names to Vertex model IDs.',
- vertexGeminiHint: 'Use a Google Cloud Service Account JSON to access Vertex AI Gemini. It is recommended to place Vertex accounts in a separate group to avoid mixing with AI Studio/Gemini OAuth on the same models.',
+ vertexGeminiDesc: 'Service Account / API Key',
+ vertexAnthropicHint: 'Use a Google Cloud Service Account JSON to call Anthropic Claude via Agent Platform (Vertex). It is recommended to configure model mapping to map client Claude model names to Agent Platform (Vertex) model IDs.',
+ vertexGeminiHint: 'Call Gemini via Agent Platform (Vertex) with a Service Account JSON or an API key. It is recommended to place these accounts in a separate group to avoid mixing with AI Studio/Gemini OAuth on the same models.',
+ vertexAuthMode: 'Authentication',
+ vertexAuthModeServiceAccount: 'Service Account JSON',
+ vertexAuthModeApiKey: 'API Key',
+ vertexApiKeyHint: 'Create it on the Agent Platform API Keys page in the Google Cloud console. Google\'s explicit context caching API does not accept API keys, so these accounts do not serve explicit caching or batch image generation; implicit caching still applies.',
+ vertexApiKeyRequired: 'Please enter an API key',
+ vertexApiKeyProjectIdPlaceholder: 'Optional',
+ vertexApiKeyProjectIdHint: 'Leave empty to use the express mode global endpoint (location is ignored). For a standard API key bound to a service account, enter the Project ID to call the project endpoint with Project ID + Location.',
vertexSaJsonLabel: 'Service Account JSON',
vertexSaJsonLoaded: 'Service Account JSON loaded',
vertexSaJsonDrop: 'Drop Service Account JSON here',
@@ -717,8 +729,8 @@ export default {
vertexSaJsonUploadHint: 'After uploading or dropping a JSON file, the project_id will be auto-extracted. Key content is only used for account creation.',
vertexSaJsonEditHint: 'Service Account JSON is not shown on the edit page; to change the JSON, delete the account and recreate it.',
vertexProjectIdPlaceholder: 'Auto-extracted from JSON',
- vertexLocationHint: 'Available locations vary by Vertex model. Select the default endpoint location for this account.',
- vertexLocationRequired: 'Please enter a Vertex location',
+ vertexLocationHint: 'Available locations vary by model. Select the default endpoint location for this account.',
+ vertexLocationRequired: 'Please select a location',
vertexSaJsonMissingFields: 'Service Account JSON is missing project_id, client_email, or private_key',
vertexSaJsonMissingProjectId: 'Service Account JSON is missing project_id',
vertexSaJsonMissingClientEmail: 'Service Account JSON is missing client_email',
@@ -747,6 +759,16 @@ export default {
requestTimezone: 'Request timezone',
requestTimezoneDesc: 'Timezone in environment context for this OpenAI account. Defaults to Singapore; preserves original client dates, times and language preferences.',
requestTimezoneLoadFailed: 'Timezone choices could not be loaded. The default Singapore timezone remains available.',
+ requestTimezoneModeFollow: 'Follow exit IP',
+ requestTimezoneModeFixed: 'Fixed timezone',
+ requestTimezoneFollowDesc: "After saving the account or changing its proxy, the exit IP's timezone is detected and used in this account's environment context; accounts without a proxy use the server IP. If detection fails, the last result is kept (Singapore if it never succeeded).",
+ requestTimezoneDetected: 'Timezone {timezone} · exit IP {ip} ({location}) · detected {time}',
+ requestTimezoneDetectFailed: 'Detection failed: {error}; still using {timezone}',
+ requestTimezoneNotDetected: 'Not detected yet; using {timezone}',
+ requestTimezoneDetectAfterSave: "The exit IP's timezone is detected after saving; Singapore is used until then.",
+ requestTimezoneRedetect: 'Detect again',
+ requestTimezoneDetecting: 'Detecting…',
+ requestTimezoneDetectError: 'Timezone detection failed',
oauthPassthrough: 'Auto passthrough (auth only)',
oauthPassthroughDesc:
'When enabled, this OpenAI account uses automatic passthrough: the gateway forwards request/response as-is and only swaps auth, while keeping billing/concurrency/audit and necessary safety filtering.',
@@ -990,6 +1012,12 @@ export default {
poolModeRetryStatusCodes: 'Retry Status Codes',
poolModeRetryStatusCodesHint:
'Comma-separated HTTP status codes (100-599) that trigger same-account retry in pool mode. Leave blank to use defaults ({default}).',
+ explicitCacheUpstream: 'Upstream Supports Explicit Caching',
+ explicitCacheUpstreamHint: 'Enable only when the upstream is this system with explicit caching support',
+ explicitCacheUpstreamInfo:
+ 'When enabled, this account can create Gemini explicit caches (cachedContents). A cache is only used on this account and never fails over. The upstream must route each cache to the account that created it; account-pool gateways or upstreams without explicit caching support will make caches unreliable.',
+ explicitCacheUpstreamMaxTTL: 'Upstream Cache TTL Limit (seconds)',
+ explicitCacheUpstreamMaxTTLHint: 'Maximum TTL allowed by the upstream gateway; requests above it are not sent to this account. Leave blank to use this site\'s limit.',
customErrorCodes: 'Custom Error Codes',
customErrorCodesHint: 'Only stop scheduling for selected error codes',
customErrorCodesWarning:
@@ -1545,7 +1573,7 @@ export default {
modelPassthroughDesc:
'All model requests are forwarded directly to the Gemini API without model restrictions or mappings.',
baseUrlHint: 'Leave default for official Gemini API',
- apiKeyHint: 'Your Gemini API Key (starts with AIza)',
+ apiKeyHint: 'New AI Studio keys start with AQ. (legacy keys start with AIza); for a third-party upstream, use the key it provides',
tier: {
label: 'Account Tier',
hint: 'Tip: The system will try to auto-detect the tier first; if auto-detection is unavailable or fails, your selected tier is used as a fallback (simulated quota).',
@@ -1568,8 +1596,8 @@ export default {
accountType: {
oauthTitle: 'OAuth (Gemini)',
oauthDesc: 'Authorize with your Google account and choose an OAuth type.',
- apiKeyTitle: 'API Key (AI Studio)',
- apiKeyDesc: 'Fastest setup. Use an AIza API key.',
+ apiKeyTitle: 'API Key',
+ apiKeyDesc: 'An official AI Studio key, or a Gemini-compatible third-party upstream.',
apiKeyNote:
'Best for light testing. Free tier has strict rate limits and data may be used for training.',
apiKeyLink: 'Get API Key',
@@ -1630,7 +1658,7 @@ export default {
docs: {
codeAssist: 'Code Assist Quotas',
aiStudio: 'AI Studio Pricing',
- vertex: 'Vertex AI Quotas'
+ vertex: 'Agent Platform (Vertex) Quotas'
},
simulatedNote: 'Simulated quota, for reference only',
rows: {
diff --git a/frontend/src/i18n/locales/en/admin/ops.ts b/frontend/src/i18n/locales/en/admin/ops.ts
index c68b7ebea..acfdcb207 100644
--- a/frontend/src/i18n/locales/en/admin/ops.ts
+++ b/frontend/src/i18n/locales/en/admin/ops.ts
@@ -428,6 +428,7 @@ export default {
kind: 'Kind',
platform: 'Platform',
model: 'Model',
+ account: 'Account',
duration: 'Duration',
status: 'Status',
requestId: 'Request ID',
diff --git a/frontend/src/i18n/locales/en/admin/overview.ts b/frontend/src/i18n/locales/en/admin/overview.ts
index e6e07ddd6..1b79627bd 100644
--- a/frontend/src/i18n/locales/en/admin/overview.ts
+++ b/frontend/src/i18n/locales/en/admin/overview.ts
@@ -973,6 +973,12 @@ export default {
yes: 'Yes',
no: 'No'
},
+ i18nField: {
+ default: 'Default',
+ add: 'Add {language} version',
+ edit: 'Edit {language} version',
+ placeholder: '{language} version; leave empty to show the default text'
+ },
enterGroupName: 'Enter group name',
optionalDescription: 'Optional description',
platformHint: 'Select the platform this group is associated with',
diff --git a/frontend/src/i18n/locales/en/batchImage.ts b/frontend/src/i18n/locales/en/batchImage.ts
index d7b227487..bfc0dc55d 100644
--- a/frontend/src/i18n/locales/en/batchImage.ts
+++ b/frontend/src/i18n/locales/en/batchImage.ts
@@ -96,7 +96,7 @@ export default {
noUsableImage: 'No usable image was generated.',
cancelled: 'Job cancelled.',
waiting: 'Waiting for results.',
- emptyImageOutput: 'The upstream returned a result, but this item has no image content. This usually means a single Gemini/Vertex generation failed or was blocked by safety policies.',
+ emptyImageOutput: 'The upstream returned a result, but this item has no image content. This usually means a single Gemini/Agent Platform (Vertex) generation failed or was blocked by safety policies.',
providerItemFailed: 'The upstream result for this item has no usable image.',
},
imagePreview: {
@@ -174,10 +174,10 @@ export default {
loadingModels: 'Loading available models...',
noModels: 'No available models',
noModelsHint: 'This key’s group has no models configured for batch image generation.',
- noCompatibleAccount: 'No usable upstream batch image account is available for this key’s group. Contact an administrator to check the group’s schedulable Gemini API key or Vertex service account and model support.',
+ noCompatibleAccount: 'No usable upstream batch image account is available for this key’s group. Contact an administrator to check the group’s schedulable Gemini API key or Agent Platform (Vertex) service account and model support.',
unsupportedProvider: 'The batch image provider for this job is not available. Contact an administrator to check the batch image provider configuration.',
providerSubmitFailed: 'The upstream batch image job failed to submit. Contact an administrator to check the upstream account, model permission, or provider status.',
- vertexGcsBucketMissing: 'Vertex batch image generation is missing the managed GCS bucket configuration. Contact an administrator to configure BATCH_IMAGE_VERTEX_MANAGED_GCS_BUCKET before submitting again.',
+ vertexGcsBucketMissing: 'Agent Platform (Vertex) batch image generation is missing the managed GCS bucket configuration. Contact an administrator to configure BATCH_IMAGE_VERTEX_MANAGED_GCS_BUCKET before submitting again.',
queueFailed: 'The task queue is temporarily unavailable, so the batch job was not queued. Contact an administrator to check the queue service.',
billingHoldFailed: 'The cost hold failed, so the batch job was not submitted. Contact an administrator to check billing or balance hold service.',
groupDisabled: 'Batch image generation is not enabled for this key’s group. Choose another enabled key or contact an administrator.',
diff --git a/frontend/src/i18n/locales/en/channelMonitorV2.ts b/frontend/src/i18n/locales/en/channelMonitorV2.ts
index 1d94a154d..d23d6cbd4 100644
--- a/frontend/src/i18n/locales/en/channelMonitorV2.ts
+++ b/frontend/src/i18n/locales/en/channelMonitorV2.ts
@@ -96,6 +96,8 @@ export default {
refreshTitle: 'Aggregation interval',
refreshHint: 'Affects matrix time granularity and refresh cadence',
refreshAria: 'Aggregation interval',
+ selectPlatform: 'Select a platform',
+ addPlatform: 'Add platform',
platformsTitle: 'Platforms and models',
platformsHint:
'Leave empty = show all real model names; when filled, only listed models get their own rows and the rest roll into “Other”',
diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts
index d4f769c60..50fdb1dae 100644
--- a/frontend/src/i18n/locales/zh/admin/accounts.ts
+++ b/frontend/src/i18n/locales/zh/admin/accounts.ts
@@ -192,8 +192,6 @@ export default {
editAccount: '编辑账号',
deleteAccount: '删除账号',
searchAccounts: '搜索账号...',
- moreFilters: '更多筛选',
- moreFiltersActive: '更多筛选(已启用 {count} 项)',
notes: '备注',
notesPlaceholder: '请输入备注',
notesHint: '备注可选',
@@ -578,7 +576,7 @@ export default {
tempUnschedulable: {
title: '临时不可调度',
statusTitle: '临时不可调度状态',
- hint: '当错误码与关键词同时匹配时,账号会在指定时间内被临时禁用。',
+ hint: '当错误码与关键词同时匹配时,按规则的作用范围在指定时间内暂停整个账号,或只冷却对应模型。',
notice: '规则按顺序匹配,需同时满足错误码与关键词。',
addRule: '添加规则',
ruleOrder: '规则序号',
@@ -594,6 +592,12 @@ export default {
keywords: '关键词',
keywordsPlaceholder: '例如 overloaded, too many requests',
keywordsHint: '多个关键词用逗号分隔,匹配时必须命中其中之一。',
+ scope: '作用范围',
+ scopeModel: '模型级',
+ scopeModelDesc: '只冷却本次请求的模型',
+ scopeAccount: '账户级',
+ scopeAccountDesc: '暂停整个账号的调度',
+ scopeHint: '无法识别请求模型时,模型级规则按账户级处理。',
description: '描述',
descriptionPlaceholder: '可选,便于记忆规则用途',
rulesInvalid: '请至少填写一条包含错误码、关键词和时长的规则。',
@@ -822,10 +826,18 @@ export default {
claudeConsole: 'Claude Console',
bedrockLabel: 'AWS Bedrock',
bedrockDesc: 'SigV4 / API Key',
- vertexLabel: 'Vertex',
+ vertexLabel: 'Agent Platform (Vertex)',
vertexDesc: 'Service Account',
- vertexAnthropicHint: '使用 Google Cloud Service Account JSON 通过 Vertex AI 调用 Anthropic Claude。建议配置模型映射,将客户端 Claude 模型名映射到 Vertex 模型 ID。',
- vertexGeminiHint: '使用 Google Cloud Service Account JSON 访问 Vertex AI Gemini。建议将 Vertex 账号放入独立分组,避免和 AI Studio/Gemini OAuth 同模型混调。',
+ vertexGeminiDesc: 'Service Account / API Key',
+ vertexAnthropicHint: '使用 Google Cloud Service Account JSON 通过 Agent Platform (Vertex) 调用 Anthropic Claude。建议配置模型映射,将客户端 Claude 模型名映射到 Agent Platform (Vertex) 模型 ID。',
+ vertexGeminiHint: '通过 Agent Platform (Vertex) 调用 Gemini,支持 Service Account JSON 或 API Key 认证。建议将此类账号放入独立分组,避免和 AI Studio/Gemini OAuth 同模型混调。',
+ vertexAuthMode: '认证方式',
+ vertexAuthModeServiceAccount: 'Service Account JSON',
+ vertexAuthModeApiKey: 'API Key',
+ vertexApiKeyHint: '在 Google Cloud 控制台 Agent Platform 的 API Keys 页面创建。Google 显式缓存接口不接受 API Key,此类账号不参与显式缓存与批量生图;隐式缓存正常生效。',
+ vertexApiKeyRequired: '请输入 API Key',
+ vertexApiKeyProjectIdPlaceholder: '可选',
+ vertexApiKeyProjectIdHint: '留空走 Express mode 全局端点(不区分 Location);绑定 Service Account 的标准 API Key 可填写 Project ID,按 Project ID + Location 访问。',
vertexSaJsonLabel: 'Service Account JSON',
vertexSaJsonLoaded: '已读取 Service Account JSON',
vertexSaJsonDrop: '拖入 Service Account JSON',
@@ -835,8 +847,8 @@ export default {
vertexSaJsonUploadHint: '上传或拖入 JSON 后会自动读取 project_id,密钥内容仅用于创建账号提交。',
vertexSaJsonEditHint: 'Service Account JSON 不在编辑页显示;需要更换 JSON 时请删除账号后重新创建。',
vertexProjectIdPlaceholder: '从 JSON 自动读取',
- vertexLocationHint: '不同 Vertex 模型可用 location 可能不同,这里选择账号默认 endpoint location。',
- vertexLocationRequired: '请填写 Vertex location',
+ vertexLocationHint: '不同模型可用 location 可能不同,这里选择账号默认 endpoint location。',
+ vertexLocationRequired: '请选择 Location',
vertexSaJsonMissingFields: 'Service Account JSON 缺少 project_id、client_email 或 private_key',
vertexSaJsonMissingProjectId: 'Service Account JSON 缺少 project_id',
vertexSaJsonMissingClientEmail: 'Service Account JSON 缺少 client_email',
@@ -865,6 +877,16 @@ export default {
requestTimezone: '请求时区',
requestTimezoneDesc: '此 OpenAI 账号环境上下文中的时区,默认新加坡;保留客户端原始日期、时间和语言偏好。',
requestTimezoneLoadFailed: '时区列表加载失败,仍可使用默认的新加坡时区。',
+ requestTimezoneModeFollow: '跟随 IP 出口',
+ requestTimezoneModeFixed: '固定时区',
+ requestTimezoneFollowDesc: '保存账号或修改代理后,自动检测出口 IP 所在地的时区,并用于此账号请求的环境上下文;未绑定代理时按服务器 IP 检测。检测失败时沿用上次结果(从未成功则为新加坡)。',
+ requestTimezoneDetected: '当前时区 {timezone} · 出口 IP {ip}({location})· 检测于 {time}',
+ requestTimezoneDetectFailed: '检测失败:{error};继续使用 {timezone}',
+ requestTimezoneNotDetected: '尚未检测,暂用 {timezone}',
+ requestTimezoneDetectAfterSave: '保存后自动检测出口 IP 的时区,检测完成前暂用新加坡时区。',
+ requestTimezoneRedetect: '重新检测',
+ requestTimezoneDetecting: '检测中…',
+ requestTimezoneDetectError: '时区检测失败',
oauthPassthrough: '自动透传(仅替换认证)',
oauthPassthroughDesc:
'开启后,该 OpenAI 账号将自动透传请求与响应,仅替换认证并保留计费/并发/审计及必要安全过滤;如遇兼容性问题可随时关闭回滚。',
@@ -1093,6 +1115,12 @@ export default {
poolModeRetryCountHint: '仅在池模式下生效。0 表示不原地重试;默认 {default},最大 {max}。',
poolModeRetryStatusCodes: '同账号重试状态码',
poolModeRetryStatusCodesHint: '仅在池模式下生效。以英文逗号分隔的 HTTP 状态码(100-599),命中时触发同账号重试。留空使用默认值({default})。',
+ explicitCacheUpstream: '上游支持显式缓存',
+ explicitCacheUpstreamHint: '仅当上游是已支持显式缓存的本系统时开启',
+ explicitCacheUpstreamInfo:
+ '开启后该账号可创建 Gemini 显式缓存(cachedContents):缓存只在本账号上使用,失败不换号。上游必须保证缓存只发往创建它的账号;号池类网关或未支持显式缓存的上游开启后,缓存会时有时无。',
+ explicitCacheUpstreamMaxTTL: '上游缓存有效期上限(秒)',
+ explicitCacheUpstreamMaxTTLHint: '填写上游网关允许的最长有效期,超出的请求不会发往该账号;留空沿用本站上限。',
customErrorCodes: '自定义错误码',
customErrorCodesHint: '仅对选中的错误码停止调度',
customErrorCodesWarning:
@@ -1636,7 +1664,7 @@ export default {
modelPassthrough: 'Gemini 直接转发模型',
modelPassthroughDesc: '所有模型请求将直接转发至 Gemini API,不进行模型限制或映射。',
baseUrlHint: '留空使用官方 Gemini API',
- apiKeyHint: '您的 Gemini API Key(以 AIza 开头)',
+ apiKeyHint: 'AI Studio 新建的 Key 以 AQ. 开头(旧版以 AIza 开头);第三方上游填写其提供的 Key',
tier: {
label: '账号等级',
hint: '提示:系统会优先尝试自动识别账号等级;若自动识别不可用或失败,则使用你选择的等级作为回退(本地模拟配额)。',
@@ -1659,8 +1687,8 @@ export default {
accountType: {
oauthTitle: 'OAuth 授权(Gemini)',
oauthDesc: '使用 Google 账号授权,并选择 OAuth 子类型。',
- apiKeyTitle: 'API 密钥(AI Studio)',
- apiKeyDesc: '最快接入方式,使用 AIza API Key。',
+ apiKeyTitle: 'API 密钥',
+ apiKeyDesc: 'AI Studio 官方 Key,或兼容 Gemini 协议的第三方上游。',
apiKeyNote: '适合轻量测试。免费层限流严格,数据可能用于训练。',
apiKeyLink: '获取 API Key',
quotaLink: '配额说明'
@@ -1720,7 +1748,7 @@ export default {
docs: {
codeAssist: 'Code Assist 配额',
aiStudio: 'AI Studio 定价',
- vertex: 'Vertex AI 配额'
+ vertex: 'Agent Platform (Vertex) 配额'
},
simulatedNote: '本地模拟配额,仅供参考',
rows: {
diff --git a/frontend/src/i18n/locales/zh/admin/ops.ts b/frontend/src/i18n/locales/zh/admin/ops.ts
index bc37c1245..e3c14b598 100644
--- a/frontend/src/i18n/locales/zh/admin/ops.ts
+++ b/frontend/src/i18n/locales/zh/admin/ops.ts
@@ -428,6 +428,7 @@ export default {
kind: '类型',
platform: '平台',
model: '模型',
+ account: '账号',
duration: '耗时',
status: '状态码',
requestId: '请求ID',
diff --git a/frontend/src/i18n/locales/zh/admin/overview.ts b/frontend/src/i18n/locales/zh/admin/overview.ts
index 85426f04b..9088319bc 100644
--- a/frontend/src/i18n/locales/zh/admin/overview.ts
+++ b/frontend/src/i18n/locales/zh/admin/overview.ts
@@ -1007,6 +1007,12 @@ export default {
privacySetOnlyEnabled: '已启用 — Privacy 未设置的账号将被排除',
disabled: '未启用'
},
+ i18nField: {
+ default: '默认',
+ add: '新增 {language} 版',
+ edit: '编辑 {language} 版',
+ placeholder: '{language} 版,留空则显示默认内容'
+ },
enterGroupName: '请输入分组名称',
optionalDescription: '可选描述',
platformHint: '选择此分组关联的平台',
diff --git a/frontend/src/i18n/locales/zh/batchImage.ts b/frontend/src/i18n/locales/zh/batchImage.ts
index cf018cef8..5aafcae77 100644
--- a/frontend/src/i18n/locales/zh/batchImage.ts
+++ b/frontend/src/i18n/locales/zh/batchImage.ts
@@ -96,7 +96,7 @@ export default {
noUsableImage: '未生成可用图片',
cancelled: '任务已取消',
waiting: '等待生成结果',
- emptyImageOutput: '上游返回了结果,但这条没有图片内容。通常是 Gemini/Vertex 单条生成失败或被安全策略拦截。',
+ emptyImageOutput: '上游返回了结果,但这条没有图片内容。通常是 Gemini/Agent Platform (Vertex) 单条生成失败或被安全策略拦截。',
providerItemFailed: '上游返回的这条结果没有可用图片。',
},
imagePreview: {
@@ -174,10 +174,10 @@ export default {
loadingModels: '加载可用模型中...',
noModels: '无可用模型',
noModelsHint: '当前密钥所属分组没有配置可用于批量生图的模型。',
- noCompatibleAccount: '当前密钥所属分组没有可用的批量生图上游账号。请联系管理员检查:该分组是否绑定了可调度的 Gemini API Key 或 Vertex 服务账号,以及账号是否支持所选模型。',
+ noCompatibleAccount: '当前密钥所属分组没有可用的批量生图上游账号。请联系管理员检查:该分组是否绑定了可调度的 Gemini API Key 或 Agent Platform (Vertex) Service Account 账号,以及账号是否支持所选模型。',
unsupportedProvider: '这个任务使用的批量生图通道当前不可用。请联系管理员检查批量生图通道配置。',
providerSubmitFailed: '上游批量生图任务提交失败。请联系管理员检查上游账号状态、模型权限或服务状态。',
- vertexGcsBucketMissing: 'Vertex 批量生图缺少托管 GCS 存储桶配置。请联系管理员配置 BATCH_IMAGE_VERTEX_MANAGED_GCS_BUCKET 后再提交。',
+ vertexGcsBucketMissing: 'Agent Platform (Vertex) 批量生图缺少托管 GCS 存储桶配置。请联系管理员配置 BATCH_IMAGE_VERTEX_MANAGED_GCS_BUCKET 后再提交。',
queueFailed: '任务队列暂时不可用,批量任务没有成功入队。请联系管理员检查队列服务。',
billingHoldFailed: '费用冻结失败,批量任务没有成功提交。请联系管理员检查余额冻结或计费服务。',
groupDisabled: '当前密钥所属分组没有开启批量生图。你可以换一个已开启批量生图的密钥,或联系管理员开启。',
diff --git a/frontend/src/i18n/locales/zh/channelMonitorV2.ts b/frontend/src/i18n/locales/zh/channelMonitorV2.ts
index 1df03acbd..77b396b6b 100644
--- a/frontend/src/i18n/locales/zh/channelMonitorV2.ts
+++ b/frontend/src/i18n/locales/zh/channelMonitorV2.ts
@@ -95,6 +95,8 @@ export default {
refreshTitle: '汇总频率',
refreshHint: '影响矩阵时间粒度与刷新节奏',
refreshAria: '汇总频率',
+ selectPlatform: '选择平台',
+ addPlatform: '添加平台',
platformsTitle: '平台与模型',
platformsHint: '留空 = 展示全部真实模型名;填写后仅名单内单独成行,其余归入「其他」',
modelsPlaceholder: '留空=全部真实模型;或填写主流模型名单(其余归其他)',
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index e6a35cedb..88d8d9393 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -564,6 +564,16 @@ export interface ReasoningEffortMapping {
model?: string
}
+/** 分组名称与描述在某个语言下的译文;字段为空表示沿用分组自身的 name/description。 */
+export interface GroupLocaleText {
+ name?: string
+ description?: string
+}
+
+/** 以语言代码(en、zh…)为键的分组文案译文。 */
+export type GroupI18n = Record
+
+// 用户侧接口返回的 name / description 已由后端按请求语言(Accept-Language)选好
export interface Group {
id: number
name: string
@@ -627,6 +637,8 @@ export interface Group {
}
export interface AdminGroup extends Group {
+ // 管理端的 name / description 始终是原字段,各语言译文另放在 i18n 里
+ i18n?: GroupI18n
force_openai_fast: boolean
free_openai_fast: boolean
model_pricing: import('@/api/admin/channels').ChannelModelPricing[]
@@ -793,6 +805,7 @@ export interface UpdateApiKeyRequest {
export interface CreateGroupRequest {
name: string
description?: string | null
+ i18n?: GroupI18n
platform?: GroupPlatform
rate_multiplier?: number
is_exclusive?: boolean
@@ -858,6 +871,7 @@ export interface CreateGroupRequest {
export interface UpdateGroupRequest {
name?: string
description?: string | null
+ i18n?: GroupI18n
platform?: GroupPlatform
rate_multiplier?: number
is_exclusive?: boolean
@@ -1010,6 +1024,7 @@ export interface ProxyQualityCheckResult {
export interface GeminiCredentials {
// API Key authentication
api_key?: string
+ base_url?: string
// OAuth authentication
access_token?: string
@@ -1034,11 +1049,15 @@ export interface GeminiCredentials {
model_mapping?: Record
}
+export type TempUnschedulableScope = 'account' | 'model'
+
export interface TempUnschedulableRule {
error_code: number
keywords: string[]
duration_minutes: number
description: string
+ // 作用范围:account 暂停整个账号,model 只冷却本次请求的模型;缺省时 401 按 account、其余按 model 处理。
+ scope?: TempUnschedulableScope
}
export interface TempUnschedulableState {
@@ -1046,6 +1065,8 @@ export interface TempUnschedulableState {
triggered_at_unix: number
status_code: number
matched_keyword: string
+ scope?: TempUnschedulableScope
+ model?: string
rule_index: number
error_message: string
trigger_count?: number
@@ -1207,6 +1228,20 @@ export interface OpenCodeGoUsageSettings {
export type { BPSCredentialState } from "@/utils/openaiBps"
+export type OpenAIRequestTimezoneMode = 'fixed' | 'follow_proxy'
+
+/** 最近一次「跟随 IP 出口」时区检测结果;error 非空表示失败,账号沿用上次的时区。 */
+export interface OpenAIRequestTimezoneDetection {
+ ip?: string
+ country?: string
+ region?: string
+ city?: string
+ timezone?: string
+ proxy_id?: number
+ detected_at: string
+ error?: string
+}
+
export interface Account {
id: number
name: string
@@ -1240,6 +1275,8 @@ export interface Account {
// Extra fields including Codex usage, OpenAI compact capability, and model-level rate limits.
extra?: (CodexUsageSnapshot & OpenAICompactState & {
openai_request_timezone?: string
+ openai_request_timezone_mode?: OpenAIRequestTimezoneMode
+ openai_request_timezone_detected?: OpenAIRequestTimezoneDetection
model_rate_limits?: Record
antigravity_credits_overages?: Record
upstream_billing_probe_enabled?: boolean
diff --git a/frontend/src/utils/__tests__/geminiExplicitCache.spec.ts b/frontend/src/utils/__tests__/geminiExplicitCache.spec.ts
new file mode 100644
index 000000000..ef9f80158
--- /dev/null
+++ b/frontend/src/utils/__tests__/geminiExplicitCache.spec.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest'
+import {
+ applyExplicitCacheUpstreamCredentials,
+ isOfficialGeminiBaseUrl,
+ normalizeExplicitCacheUpstreamMaxTTL
+} from '../geminiExplicitCache'
+
+describe('isOfficialGeminiBaseUrl', () => {
+ it('treats empty and the official host as official', () => {
+ expect(isOfficialGeminiBaseUrl('')).toBe(true)
+ expect(isOfficialGeminiBaseUrl(undefined)).toBe(true)
+ expect(isOfficialGeminiBaseUrl('https://generativelanguage.googleapis.com')).toBe(true)
+ expect(isOfficialGeminiBaseUrl('https://generativelanguage.googleapis.com/')).toBe(true)
+ })
+
+ it('treats relays, path prefixes and invalid urls as custom', () => {
+ expect(isOfficialGeminiBaseUrl('https://relay.example.com')).toBe(false)
+ expect(isOfficialGeminiBaseUrl('https://generativelanguage.googleapis.com/gw')).toBe(false)
+ expect(isOfficialGeminiBaseUrl('http://generativelanguage.googleapis.com')).toBe(false)
+ expect(isOfficialGeminiBaseUrl('not a url')).toBe(false)
+ })
+})
+
+describe('applyExplicitCacheUpstreamCredentials', () => {
+ it('writes the switch and an optional ttl cap', () => {
+ const credentials: Record = {}
+ applyExplicitCacheUpstreamCredentials(credentials, true, '1800')
+ expect(credentials).toEqual({ explicit_cache_upstream: true, explicit_cache_upstream_max_ttl_seconds: 1800 })
+
+ applyExplicitCacheUpstreamCredentials(credentials, true, '')
+ expect(credentials).toEqual({ explicit_cache_upstream: true })
+ })
+
+ it('removes both fields when disabled', () => {
+ const credentials: Record = {
+ api_key: 'k',
+ explicit_cache_upstream: true,
+ explicit_cache_upstream_max_ttl_seconds: 600
+ }
+ applyExplicitCacheUpstreamCredentials(credentials, false, 600)
+ expect(credentials).toEqual({ api_key: 'k' })
+ })
+
+ it('ignores non-positive caps', () => {
+ expect(normalizeExplicitCacheUpstreamMaxTTL(0)).toBeNull()
+ expect(normalizeExplicitCacheUpstreamMaxTTL(-5)).toBeNull()
+ expect(normalizeExplicitCacheUpstreamMaxTTL('abc')).toBeNull()
+ expect(normalizeExplicitCacheUpstreamMaxTTL(90.7)).toBe(90)
+ })
+})
diff --git a/frontend/src/utils/geminiExplicitCache.ts b/frontend/src/utils/geminiExplicitCache.ts
new file mode 100644
index 000000000..72fc31170
--- /dev/null
+++ b/frontend/src/utils/geminiExplicitCache.ts
@@ -0,0 +1,47 @@
+const OFFICIAL_GEMINI_API_HOST = 'generativelanguage.googleapis.com'
+
+/** Gemini API Key 账号的 base_url 是否为官方地址;留空视为官方地址。 */
+export function isOfficialGeminiBaseUrl(raw: string | null | undefined): boolean {
+ const value = (raw ?? '').trim()
+ if (!value) return true
+ try {
+ const url = new URL(value)
+ const path = url.pathname.replace(/\/+$/, '')
+ return (
+ url.protocol === 'https:' &&
+ url.hostname.toLowerCase() === OFFICIAL_GEMINI_API_HOST &&
+ url.port === '' &&
+ path === '' &&
+ url.search === ''
+ )
+ } catch {
+ return false
+ }
+}
+
+/** 上游缓存有效期上限(秒):非正数或非数字视为未配置。 */
+export function normalizeExplicitCacheUpstreamMaxTTL(value: unknown): number | null {
+ if (value === null || value === undefined || value === '') return null
+ const seconds = Number(value)
+ return Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : null
+}
+
+/** 把上游显式缓存开关写入(或移出)账号凭据。 */
+export function applyExplicitCacheUpstreamCredentials(
+ credentials: Record,
+ enabled: boolean,
+ maxTTL: unknown
+): void {
+ if (!enabled) {
+ delete credentials.explicit_cache_upstream
+ delete credentials.explicit_cache_upstream_max_ttl_seconds
+ return
+ }
+ credentials.explicit_cache_upstream = true
+ const seconds = normalizeExplicitCacheUpstreamMaxTTL(maxTTL)
+ if (seconds === null) {
+ delete credentials.explicit_cache_upstream_max_ttl_seconds
+ } else {
+ credentials.explicit_cache_upstream_max_ttl_seconds = seconds
+ }
+}
diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue
index 8a843a09e..04e0d0ee8 100644
--- a/frontend/src/views/admin/AccountsView.vue
+++ b/frontend/src/views/admin/AccountsView.vue
@@ -4,7 +4,6 @@
- {{ t("admin.groups.form.name") }}
-
- {{
- t("admin.groups.form.description")
- }}
-
+ />
{{
@@ -2127,24 +2127,24 @@
class="space-y-5"
>
- {{ t("admin.groups.form.name") }}
-
- {{
- t("admin.groups.form.description")
- }}
-
+ />
{{
@@ -4279,6 +4279,7 @@ import type {
CompositeRouteDecision,
CompositeRouteEndpoint,
CompositeRouteMatchType,
+ GroupI18n,
GroupPlatform,
SubscriptionType,
} from "@/types";
@@ -4299,6 +4300,7 @@ import Select from "@/components/common/Select.vue";
import PlatformIcon from "@/components/common/PlatformIcon.vue";
import { platformLabel } from "@/utils/platformColors";
import Icon from "@/components/icons/Icon.vue";
+import GroupI18nField from "@/components/admin/group/GroupI18nField.vue";
import GroupRateMultipliersModal from "@/components/admin/group/GroupRateMultipliersModal.vue";
import GroupRPMOverridesModal from "@/components/admin/group/GroupRPMOverridesModal.vue";
import GroupCapacityBadge from "@/components/common/GroupCapacityBadge.vue";
@@ -4941,6 +4943,7 @@ const submitEditAllowlistCustomEntry = () => {
const createForm = reactive({
name: "",
description: "",
+ i18n: {} as GroupI18n,
platform: "anthropic" as GroupPlatform,
rate_multiplier: 1.0,
is_exclusive: false,
@@ -5305,6 +5308,7 @@ const convertApiFormatToRoutingRules = async (
const editForm = reactive({
name: "",
description: "",
+ i18n: {} as GroupI18n,
platform: "anthropic" as GroupPlatform,
rate_multiplier: 1.0,
is_exclusive: false,
@@ -5768,6 +5772,7 @@ const closeCreateModal = () => {
clearAllAccountSearchState();
createForm.name = "";
createForm.description = "";
+ createForm.i18n = {};
createForm.platform = "anthropic";
createForm.rate_multiplier = 1.0;
createForm.is_exclusive = false;
@@ -6023,6 +6028,7 @@ const handleCreateGroup = async () => {
? {
name: createForm.name,
description: createForm.description,
+ i18n: createForm.i18n,
platform: createForm.platform,
}
: requestData;
@@ -6049,6 +6055,12 @@ const handleEdit = async (group: AdminGroup) => {
editingGroup.value = group;
editForm.name = group.name;
editForm.description = group.description || "";
+ editForm.i18n = Object.fromEntries(
+ Object.entries(group.i18n ?? {}).map(([locale, text]) => [
+ locale,
+ { ...text },
+ ]),
+ );
editForm.platform = group.platform;
editForm.rate_multiplier = group.rate_multiplier;
editForm.is_exclusive = group.is_exclusive;
@@ -6374,6 +6386,7 @@ const handleUpdateGroup = async () => {
? {
name: editForm.name,
description: editForm.description,
+ i18n: editForm.i18n,
}
: payload;
await adminAPI.groups.update(editingGroup.value.id, requestData);
diff --git a/frontend/src/views/admin/ProxiesView.vue b/frontend/src/views/admin/ProxiesView.vue
index 1ce109ca3..5344ba2ff 100644
--- a/frontend/src/views/admin/ProxiesView.vue
+++ b/frontend/src/views/admin/ProxiesView.vue
@@ -2,7 +2,7 @@
-
+
@@ -1189,6 +1189,9 @@ const buildProxyQueryFilters = () => ({
sort_order: sortState.sort_order
})
+const codexTicketPoolRef = ref | null>(null)
+let proxiesLoadedOnce = false
+
const loadProxies = async () => {
if (abortController) {
abortController.abort()
@@ -1209,6 +1212,10 @@ const loadProxies = async () => {
proxies.value = response.items
pagination.total = response.total
pagination.pages = response.pages
+ // The ticket pool panel loads on its own mount; afterwards keep its proxy list in step
+ // with additions, edits and deletions made on this page.
+ if (proxiesLoadedOnce) void codexTicketPoolRef.value?.reload?.()
+ proxiesLoadedOnce = true
} catch (error) {
if (isAbortError(error)) {
return
diff --git a/frontend/src/views/admin/ops/components/OpsDashboardHeader.vue b/frontend/src/views/admin/ops/components/OpsDashboardHeader.vue
index 35bb9e7a3..5eaef8563 100644
--- a/frontend/src/views/admin/ops/components/OpsDashboardHeader.vue
+++ b/frontend/src/views/admin/ops/components/OpsDashboardHeader.vue
@@ -10,7 +10,7 @@ import { adminAPI } from '@/api'
import { opsAPI, type OpsDashboardOverview, type OpsMetricThresholds, type OpsRealtimeTrafficSummary } from '@/api/admin/ops'
import type { OpsRequestDetailsPreset } from './OpsRequestDetailsModal.vue'
import { useAdminSettingsStore } from '@/stores'
-import { formatNumber } from '@/utils/format'
+import { formatDateTimeLocalInput, formatNumber } from '@/utils/format'
import { formatMemorySizeMB } from '../utils/opsFormatters'
type RealtimeWindow = '1min' | '5min' | '30min' | '1h'
@@ -178,8 +178,8 @@ function handleTimeRangeChange(val: string | number | boolean | null) {
// 初始化为最近1小时
const now = new Date()
const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000)
- customStartTimeInput.value = oneHourAgo.toISOString().slice(0, 16)
- customEndTimeInput.value = now.toISOString().slice(0, 16)
+ customStartTimeInput.value = formatDateTimeLocalInput(oneHourAgo.getTime() / 1000)
+ customEndTimeInput.value = formatDateTimeLocalInput(now.getTime() / 1000)
showCustomTimeRangeDialog.value = true
} else {
emit('update:timeRange', newValue)
diff --git a/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue b/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue
index d38882989..8d2d26621 100644
--- a/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue
+++ b/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue
@@ -8,6 +8,7 @@ import { useClipboard } from '@/composables/useClipboard'
import { useAppStore } from '@/stores'
import { opsAPI, type OpsRequestDetailsParams, type OpsRequestDetail } from '@/api/admin/ops'
import { parseTimeRangeMinutes, formatDateTime } from '../utils/opsFormatters'
+import { getAccountNameMap } from '../utils/accountNameMap'
export interface OpsRequestDetailsPreset {
title: string
@@ -44,6 +45,7 @@ const items = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
+const accountNameById = ref>(new Map())
const close = () => emit('update:modelValue', false)
@@ -93,6 +95,7 @@ const fetchData = async () => {
const res = await opsAPI.listRequestDetails(params)
items.value = res.items || []
total.value = res.total || 0
+ refreshAccountNames()
} catch (e: any) {
console.error('[OpsRequestDetailsModal] Failed to fetch request details', e)
appStore.showError(e?.message || t('admin.ops.requestDetails.failedToLoad'))
@@ -159,6 +162,27 @@ const kindBadgeClass = (kind: string) => {
if (kind === 'error') return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300'
return 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300'
}
+
+// 明细行只带 account_id;账号名来自 lite 账号列表映射,缺项时强制刷新一次缓存(新建账号场景)。
+async function refreshAccountNames() {
+ const ids = items.value
+ .map(row => row.account_id)
+ .filter((id): id is number => typeof id === 'number' && id > 0)
+ if (ids.length === 0) return
+ try {
+ let map = await getAccountNameMap()
+ if (ids.some(id => !map.has(id))) map = await getAccountNameMap(true)
+ accountNameById.value = map
+ } catch (e) {
+ console.warn('[OpsRequestDetailsModal] Failed to load account names', e)
+ }
+}
+
+function accountLabel(row: OpsRequestDetail): string {
+ const id = row.account_id
+ if (typeof id !== 'number' || id <= 0) return '-'
+ return accountNameById.value.get(id) || `#${id}`
+}
@@ -212,6 +236,9 @@ const kindBadgeClass = (kind: string) => {
{{ formatDateTime(row.created_at) }}
{{ row.model || '-' }}
+
+ {{ t('admin.ops.requestDetails.table.account') }}: {{ accountLabel(row) }}
+
{{ latencyLabel }}: {{ formatLatency(row) }}
{{ row.status_code ?? '-' }}
@@ -251,6 +278,9 @@ const kindBadgeClass = (kind: string) => {
{{ t('admin.ops.requestDetails.table.model') }}
+
+ {{ t('admin.ops.requestDetails.table.account') }}
+
{{ latencyLabel }}
@@ -281,6 +311,9 @@ const kindBadgeClass = (kind: string) => {
{{ row.model || '-' }}
+
+ {{ accountLabel(row) }}
+
{{ formatLatency(row) }}
diff --git a/frontend/src/views/admin/ops/components/__tests__/OpsDashboardHeader.timezone.spec.ts b/frontend/src/views/admin/ops/components/__tests__/OpsDashboardHeader.timezone.spec.ts
new file mode 100644
index 000000000..838a116e2
--- /dev/null
+++ b/frontend/src/views/admin/ops/components/__tests__/OpsDashboardHeader.timezone.spec.ts
@@ -0,0 +1,54 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
+import OpsDashboardHeader from '../OpsDashboardHeader.vue'
+
+vi.mock('@/api', () => ({ adminAPI: { groups: { getAll: vi.fn().mockResolvedValue([]) } } }))
+vi.mock('@/api/admin/ops', () => ({ opsAPI: { getRealtimeTrafficSummary: vi.fn().mockResolvedValue({ enabled: true, summary: null }) } }))
+vi.mock('@/stores', () => ({ useAdminSettingsStore: () => ({ opsRealtimeMonitoringEnabled: true, setOpsRealtimeMonitoringEnabledLocal: vi.fn() }) }))
+vi.mock('vue-i18n', async () => ({
+ ...await vi.importActual
('vue-i18n'),
+ useI18n: () => ({ t: (key: string) => key })
+}))
+enableAutoUnmount(afterEach)
+beforeEach(() => vi.stubEnv('TZ', 'Asia/Shanghai'))
+afterEach(() => { vi.useRealTimers(); vi.unstubAllEnvs() })
+
+async function openCustomRange(now: Date) {
+ expect(now.getTimezoneOffset()).toBe(-480)
+ vi.useFakeTimers()
+ vi.setSystemTime(now)
+ const wrapper = mount(OpsDashboardHeader, {
+ props: { platform: '', groupId: null, timeRange: '1h', queryMode: 'auto', loading: false, lastUpdated: null },
+ global: { stubs: {
+ Select: true, HelpTooltip: true, Icon: true,
+ BaseDialog: { props: ['show'], template: '
' }
+ } }
+ })
+ await flushPromises()
+ const selector = wrapper.findAllComponents({ name: 'Select' }).find(select =>
+ select.props('options').some((option: { value: unknown }) => option.value === 'custom')
+ )!
+ selector.vm.$emit('update:modelValue', 'custom')
+ await flushPromises()
+ return wrapper
+}
+
+describe('ops custom time range timezone', () => {
+ it.each([
+ [14, 23, '2026-10-09T13:23', '2026-10-09T14:23'],
+ [0, 15, '2026-10-08T23:15', '2026-10-09T00:15']
+ ] as const)('prefills the previous local hour at %i:%i', async (hour, minute, start, end) => {
+ const wrapper = await openCustomRange(new Date(2026, 9, 9, hour, minute))
+ const inputs = wrapper.findAll('input[type="datetime-local"]')
+ expect(inputs.map(input => input.element.value)).toEqual([start, end])
+ })
+
+ it('submits the previous real hour without applying the timezone offset twice', async () => {
+ const now = new Date(2026, 9, 9, 14, 23)
+ const wrapper = await openCustomRange(now)
+ await wrapper.findAll('button').find(button => button.text() === 'common.confirm')!.trigger('click')
+ expect(wrapper.emitted('update:customTimeRange')).toEqual([
+ [new Date(now.getTime() - 3600000).toISOString(), now.toISOString()]
+ ])
+ })
+})
diff --git a/frontend/src/views/admin/ops/components/__tests__/OpsRequestDetailsModal.spec.ts b/frontend/src/views/admin/ops/components/__tests__/OpsRequestDetailsModal.spec.ts
index be856162a..25099077f 100644
--- a/frontend/src/views/admin/ops/components/__tests__/OpsRequestDetailsModal.spec.ts
+++ b/frontend/src/views/admin/ops/components/__tests__/OpsRequestDetailsModal.spec.ts
@@ -4,14 +4,17 @@ import type { OpsDashboardOverview } from '@/api/admin/ops'
import { flushPromises, mount, shallowMount } from '@vue/test-utils'
import OpsDashboardHeader from '../OpsDashboardHeader.vue'
import OpsRequestDetailsModal from '../OpsRequestDetailsModal.vue'
+import { resetAccountNameCacheForTests } from '../../utils/accountNameMap'
-const { listRequestDetails, viewport } = vi.hoisted(() => ({
+const { listRequestDetails, listAccounts, viewport } = vi.hoisted(() => ({
listRequestDetails: vi.fn(),
+ listAccounts: vi.fn(),
viewport: { desktop: true },
}))
vi.mock('@vueuse/core', () => ({ useMediaQuery: () => ref(viewport.desktop) }))
vi.mock('@/api/admin/ops', () => ({ opsAPI: { listRequestDetails } }))
+vi.mock('@/api/admin/accounts', () => ({ accountsAPI: { list: listAccounts } }))
vi.mock('@/api', () => ({ adminAPI: { groups: { getAll: vi.fn().mockResolvedValue([]) } } }))
vi.mock('@/stores', () => ({
useAppStore: () => ({ showError: vi.fn() }),
@@ -36,15 +39,23 @@ async function openDetails(sort: 'duration_desc' | 'ttft_desc') {
describe('Ops request latency details', () => {
beforeEach(() => {
vi.clearAllMocks()
+ resetAccountNameCacheForTests()
viewport.desktop = true
listRequestDetails.mockResolvedValue({
items: [
- { kind: 'success', created_at: '2026-09-10T00:00:00Z', duration_ms: 12000, first_token_ms: 800 },
- { kind: 'success', created_at: '2026-09-10T00:00:01Z', duration_ms: 9000, first_token_ms: 0 },
- { kind: 'success', created_at: '2026-09-10T00:00:02Z', duration_ms: 5000, first_token_ms: null },
+ { kind: 'success', created_at: '2026-09-10T00:00:00Z', duration_ms: 12000, first_token_ms: 800, account_id: 101 },
+ { kind: 'success', created_at: '2026-09-10T00:00:01Z', duration_ms: 9000, first_token_ms: 0, account_id: 102 },
+ { kind: 'success', created_at: '2026-09-10T00:00:02Z', duration_ms: 5000, first_token_ms: null, account_id: 999 },
],
total: 3,
})
+ listAccounts.mockResolvedValue({
+ items: [
+ { id: 101, name: 'acc-alpha' },
+ { id: 102, name: 'acc-beta' },
+ ],
+ total: 2,
+ })
})
it('opens the TTFT card with first-token sorting and successful requests', async () => {
@@ -74,11 +85,21 @@ describe('Ops request latency details', () => {
expect(wrapper.text()).not.toContain('12000 ms')
expect(wrapper.text()).not.toContain('9000 ms')
expect(wrapper.text()).not.toContain('5000 ms')
- if (desktop) expect(wrapper.findAll('tbody tr')[2].findAll('td')[4].text()).toBe('-')
+ if (desktop) expect(wrapper.findAll('tbody tr')[2].findAll('td')[5].text()).toBe('-')
else expect(wrapper.text()).toContain('admin.ops.ttftLabel: -')
wrapper.unmount()
})
+ it('shows account names with id fallback in the account column', async () => {
+ const wrapper = await openDetails('ttft_desc')
+ expect(wrapper.text()).toContain('admin.ops.requestDetails.table.account')
+ const accountCells = wrapper.findAll('tbody tr').map(tr => tr.findAll('td')[4].text())
+ expect(accountCells).toEqual(['acc-alpha', 'acc-beta', '#999'])
+ // 999 不在账号映射里,应触发一次强制刷新重建缓存
+ expect(listAccounts).toHaveBeenCalledTimes(2)
+ wrapper.unmount()
+ })
+
it('keeps total duration for duration details', async () => {
const wrapper = await openDetails('duration_desc')
expect(listRequestDetails).toHaveBeenCalledWith(expect.objectContaining({ sort: 'duration_desc' }))
diff --git a/frontend/src/views/admin/ops/utils/accountNameMap.ts b/frontend/src/views/admin/ops/utils/accountNameMap.ts
new file mode 100644
index 000000000..c69b36e98
--- /dev/null
+++ b/frontend/src/views/admin/ops/utils/accountNameMap.ts
@@ -0,0 +1,33 @@
+import { accountsAPI } from '@/api/admin/accounts'
+
+// 运维监控请求明细只带 account_id,账号名由前端用 lite 账号列表建映射;
+// 模块级缓存避免每次打开弹窗都拉全量账号。
+const ACCOUNT_NAME_PAGE_SIZE = 1000
+
+let accountNameCache: Map | null = null
+
+export async function getAccountNameMap(force = false): Promise> {
+ if (!force && accountNameCache) return accountNameCache
+
+ const map = new Map()
+ let page = 1
+ let total = Number.POSITIVE_INFINITY
+ while (map.size < total) {
+ const res = await accountsAPI.list(page, ACCOUNT_NAME_PAGE_SIZE, {
+ lite: '1',
+ include_scheduler_score: '0'
+ })
+ total = res.total || 0
+ const items = res.items || []
+ if (items.length === 0) break
+ for (const item of items) map.set(item.id, item.name)
+ page++
+ }
+
+ accountNameCache = map
+ return map
+}
+
+export function resetAccountNameCacheForTests() {
+ accountNameCache = null
+}
diff --git a/frontend/src/views/user/ChannelStatusV1View.vue b/frontend/src/views/user/ChannelStatusV1View.vue
index 041650c6c..8d36f9c8a 100644
--- a/frontend/src/views/user/ChannelStatusV1View.vue
+++ b/frontend/src/views/user/ChannelStatusV1View.vue
@@ -7,7 +7,7 @@
:loading="loading"
:auto-refresh="autoRefresh"
@update:window="handleWindowChange"
- @refresh="manualReload"
+ @refresh="refresh()"
/>
reload(true),
+ onRefresh: () => refresh(true),
shouldPause: () => document.hidden || loading.value,
})
const countdown = autoRefresh.countdown
@@ -109,8 +109,8 @@ async function reload(silent = false) {
}
}
-async function manualReload() {
- await reload(false)
+async function refresh(silent = false) {
+ await reload(silent)
// After base reload, refresh any cached detail records so non-7d availability
// values stay in sync without forcing the user to switch tabs again.
if (currentWindow.value !== '7d') {
diff --git a/frontend/src/views/user/PaymentQRCodeView.vue b/frontend/src/views/user/PaymentQRCodeView.vue
index 0569bf690..b535b1468 100644
--- a/frontend/src/views/user/PaymentQRCodeView.vue
+++ b/frontend/src/views/user/PaymentQRCodeView.vue
@@ -157,12 +157,13 @@ async function pollStatus() {
function startCountdown(seconds: number) {
remainingSeconds.value = Math.max(0, seconds)
+ const deadline = Date.now() + remainingSeconds.value * 1000
if (remainingSeconds.value <= 0) {
expired.value = true
return
}
countdownTimer = setInterval(() => {
- remainingSeconds.value--
+ remainingSeconds.value = Math.max(0, Math.floor((deadline - Date.now()) / 1000))
if (remainingSeconds.value <= 0) {
expired.value = true
cleanup()
diff --git a/frontend/src/views/user/PaymentView.vue b/frontend/src/views/user/PaymentView.vue
index 4727e1602..4e64af2ef 100644
--- a/frontend/src/views/user/PaymentView.vue
+++ b/frontend/src/views/user/PaymentView.vue
@@ -874,7 +874,6 @@ async function createOrder(orderAmount: number, orderType: OrderType, planId?: n
path: '/payment/stripe',
query: {
order_id: String(result.order_id),
- client_secret: result.client_secret,
method: stripeMethod || undefined,
resume_token: result.resume_token || undefined,
},
@@ -1082,7 +1081,6 @@ async function attemptMobileQrFallback(err: unknown, context: MobileQrFallbackCo
path: '/payment/stripe',
query: {
order_id: String(result.order_id),
- client_secret: result.client_secret,
method: stripeMethod,
resume_token: result.resume_token || undefined,
},
diff --git a/frontend/src/views/user/StripePaymentView.vue b/frontend/src/views/user/StripePaymentView.vue
index b845cfac5..2e6a5bbbf 100644
--- a/frontend/src/views/user/StripePaymentView.vue
+++ b/frontend/src/views/user/StripePaymentView.vue
@@ -136,9 +136,14 @@ let redirectTimer: ReturnType | null = null
onMounted(async () => {
const orderId = Number(route.query.order_id)
- const clientSecret = String(route.query.client_secret || '')
const method = String(route.query.method || '')
const resumeToken = typeof route.query.resume_token === 'string' ? route.query.resume_token : undefined
+ // client_secret 只从本浏览器下单时写入的恢复快照读取,且快照订单必须与 URL 订单一致:
+ // 不信任 URL 中的 client_secret,避免页面展示的订单与实际收款的 PaymentIntent 被拼接错绑。
+ const restored = typeof window !== 'undefined'
+ ? readPaymentRecoverySnapshot(window.localStorage.getItem(PAYMENT_RECOVERY_STORAGE_KEY), { resumeToken })
+ : null
+ const clientSecret = orderId && restored?.orderId === orderId ? restored.clientSecret : ''
if (!orderId || !clientSecret) {
loading.value = false
@@ -147,15 +152,7 @@ onMounted(async () => {
}
try {
- if (typeof window !== 'undefined') {
- const restored = readPaymentRecoverySnapshot(
- window.localStorage.getItem(PAYMENT_RECOVERY_STORAGE_KEY),
- { resumeToken },
- )
- if (restored?.orderId === orderId) {
- currency.value = normalizePaymentCurrency(restored.currency)
- }
- }
+ currency.value = normalizePaymentCurrency(restored?.currency)
const res = await paymentAPI.getOrder(orderId)
order.value = res.data
if (res.data.currency) {
diff --git a/frontend/src/views/user/__tests__/ChannelStatusV1View.details.spec.ts b/frontend/src/views/user/__tests__/ChannelStatusV1View.details.spec.ts
new file mode 100644
index 000000000..7c5273edf
--- /dev/null
+++ b/frontend/src/views/user/__tests__/ChannelStatusV1View.details.spec.ts
@@ -0,0 +1,77 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { enableAutoUnmount, flushPromises, shallowMount } from '@vue/test-utils'
+import ChannelStatusV1View from '../ChannelStatusV1View.vue'
+
+const mocks = vi.hoisted(() => ({ list: vi.fn(), status: vi.fn() }))
+vi.mock('@/api/channelMonitor', () => mocks)
+vi.mock('@/stores/app', () => ({ useAppStore: () => ({ cachedPublicSettings: { channel_monitor_enabled: true }, showError: vi.fn() }) }))
+vi.mock('vue-i18n', async () => ({
+ ...await vi.importActual('vue-i18n'),
+ useI18n: () => ({ t: (key: string) => key })
+}))
+enableAutoUnmount(afterEach)
+afterEach(() => { vi.useRealTimers(); localStorage.clear() })
+
+function detail(availability: number) {
+ return { id: 1, models: [{ model: 'model', availability_15d: availability, availability_30d: availability }] }
+}
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.resetAllMocks()
+ localStorage.clear()
+ localStorage.setItem('channel-status-auto-refresh', JSON.stringify({ enabled: true, interval_seconds: 30 }))
+ mocks.list.mockImplementation(async () => ({ items: [{ id: 1, name: 'Monitor', primary_model: 'model', primary_status: 'operational', availability_7d: 99 }] }))
+ mocks.status.mockResolvedValue(detail(90))
+})
+
+function mountView() {
+ return shallowMount(ChannelStatusV1View, {
+ global: { stubs: {
+ AppLayout: { template: '
' },
+ MonitorHero: { props: ['loading'], emits: ['update:window', 'refresh'], template: `
+ 15d
+ 30d
+ Refresh
+
` },
+ MonitorCardGrid: false,
+ MonitorCard: { props: ['availabilityValue'], template: '{{ availabilityValue }} ' }
+ } }
+ })
+}
+
+describe('channel monitor automatic detail refresh', () => {
+ it.each(['fifteen', 'thirty'])('refreshes the cached %s-day availability on timer ticks', async (tab) => {
+ const wrapper = mountView()
+ await flushPromises()
+ await wrapper.get('.' + tab).trigger('click')
+ await flushPromises()
+ expect(wrapper.get('output').text()).toBe('90')
+ mocks.status.mockResolvedValue(detail(98))
+ await vi.advanceTimersByTimeAsync(30000)
+ await flushPromises()
+ expect(wrapper.get('output').text()).toBe('98')
+ expect(mocks.status).toHaveBeenCalledTimes(2)
+ expect(wrapper.get('[data-loading]').attributes('data-loading')).toBe('false')
+ })
+
+ it('keeps the seven-day view on the list endpoint without extra detail requests', async () => {
+ const wrapper = mountView()
+ await flushPromises()
+ await vi.advanceTimersByTimeAsync(30000)
+ await flushPromises()
+ expect(mocks.list).toHaveBeenCalledTimes(2)
+ expect(mocks.status).not.toHaveBeenCalled()
+ expect(wrapper.get('output').text()).toBe('99')
+ })
+
+ it('still refreshes cached availability on manual reload', async () => {
+ const wrapper = mountView()
+ await flushPromises()
+ await wrapper.get('.fifteen').trigger('click')
+ await flushPromises()
+ mocks.status.mockResolvedValue(detail(98))
+ await wrapper.get('.refresh').trigger('click')
+ await flushPromises()
+ expect(wrapper.get('output').text()).toBe('98')
+ })
+})
diff --git a/frontend/src/views/user/__tests__/StripePaymentView.spec.ts b/frontend/src/views/user/__tests__/StripePaymentView.spec.ts
index 0d85126a3..5d2c6a23f 100644
--- a/frontend/src/views/user/__tests__/StripePaymentView.spec.ts
+++ b/frontend/src/views/user/__tests__/StripePaymentView.spec.ts
@@ -65,6 +65,10 @@ vi.mock('@stripe/stripe-js/pure', () => ({
import StripePaymentView from '../StripePaymentView.vue'
import { formatPaymentAmount } from '@/components/payment/currency'
+import {
+ PAYMENT_RECOVERY_STORAGE_KEY,
+ type PaymentRecoverySnapshot,
+} from '@/components/payment/paymentFlow'
import type { PaymentOrder } from '@/types/payment'
function orderFactory(overrides: Partial = {}): PaymentOrder {
@@ -86,6 +90,33 @@ function orderFactory(overrides: Partial = {}): PaymentOrder {
}
}
+function stripeSnapshot(overrides: Partial = {}): PaymentRecoverySnapshot {
+ return {
+ orderId: 42,
+ amount: 100,
+ qrCode: '',
+ expiresAt: '2099-01-01T00:30:00.000Z',
+ paymentType: 'stripe',
+ payUrl: '/payment/stripe?order_id=42',
+ outTradeNo: 'sub2_stripe_42',
+ clientSecret: 'pi_secret_42',
+ intentId: '',
+ currency: 'CNY',
+ countryCode: '',
+ paymentEnv: '',
+ payAmount: 103,
+ orderType: 'balance',
+ paymentMode: '',
+ resumeToken: '',
+ createdAt: Date.UTC(2099, 0, 1, 0, 0, 0),
+ ...overrides,
+ }
+}
+
+function writeSnapshot(overrides: Partial = {}) {
+ window.localStorage.setItem(PAYMENT_RECOVERY_STORAGE_KEY, JSON.stringify(stripeSnapshot(overrides)))
+}
+
function mountView() {
return shallowMount(StripePaymentView, {
global: {
@@ -101,7 +132,6 @@ describe('StripePaymentView', () => {
beforeEach(() => {
routeState.query = {
order_id: '42',
- client_secret: 'pi_secret_42',
}
routerPush.mockReset()
getOrder.mockReset().mockResolvedValue({ data: orderFactory() })
@@ -119,6 +149,42 @@ describe('StripePaymentView', () => {
stripeInstance.confirmAlipayPayment.mockReset()
stripeInstance.confirmWechatPayPayment.mockReset()
window.localStorage.clear()
+ writeSnapshot()
+ })
+
+ it('uses the client secret from the local snapshot of the same order', async () => {
+ routeState.query.method = 'alipay'
+ mountView()
+ await flushPromises()
+ await flushPromises()
+
+ expect(getOrder).toHaveBeenCalledWith(42)
+ expect(stripeInstance.confirmAlipayPayment).toHaveBeenCalledWith('pi_secret_42', expect.any(Object))
+ })
+
+ it('ignores a client secret supplied in the URL query', async () => {
+ window.localStorage.clear()
+ routeState.query = { order_id: '42', client_secret: 'pi_other_secret', method: 'alipay' }
+
+ const wrapper = mountView()
+ await flushPromises()
+
+ expect(getOrder).not.toHaveBeenCalled()
+ expect(loadStripe).not.toHaveBeenCalled()
+ expect(stripeInstance.confirmAlipayPayment).not.toHaveBeenCalled()
+ expect(wrapper.text()).toContain('payment.stripeMissingParams')
+ })
+
+ it('rejects a snapshot that belongs to a different order', async () => {
+ writeSnapshot({ orderId: 7, clientSecret: 'pi_secret_7' })
+ routeState.query = { order_id: '42', client_secret: 'pi_secret_42', method: 'alipay' }
+
+ const wrapper = mountView()
+ await flushPromises()
+
+ expect(getOrder).not.toHaveBeenCalled()
+ expect(stripeInstance.confirmAlipayPayment).not.toHaveBeenCalled()
+ expect(wrapper.text()).toContain('payment.stripeMissingParams')
})
it.each(['alipay', 'wechat_pay', ''])('does not start %s payment after leaving during SDK loading', async (method) => {
@@ -178,7 +244,8 @@ describe('StripePaymentView', () => {
expect(vi.getTimerCount()).toBe(0)
})
- it('本地恢复快照缺失时使用订单接口返回的 Stripe 币种展示金额', async () => {
+ it('本地恢复快照未记录币种时使用订单接口返回的 Stripe 币种展示金额', async () => {
+ writeSnapshot({ currency: '' })
getOrder.mockResolvedValue({
data: orderFactory({ currency: 'HKD', pay_amount: 103 }),
})
diff --git a/scripts/sync-upstream-migration-checksums.sh b/scripts/sync-upstream-migration-checksums.sh
new file mode 100755
index 000000000..1c3b2d55b
--- /dev/null
+++ b/scripts/sync-upstream-migration-checksums.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+# 从上游 Sub2API 重新生成 backend/migrations/upstream_checksums.txt。
+# 合并上游后运行一次;backend/migrations/upstream_checksums_test.go 会校验
+# 同名迁移文件与上游完全一致(checksum 算法与 migrations_runner 相同:去首尾空白后 sha256)。
+#
+# 默认以 HEAD 与 sub2api/main 的 merge-base(即最近一次合入的上游提交)为基准,
+# 避免把尚未合入的上游新迁移写进清单。
+#
+# 用法:scripts/sync-upstream-migration-checksums.sh [upstream-ref]
+set -euo pipefail
+root=$(git rev-parse --show-toplevel)
+out="$root/backend/migrations/upstream_checksums.txt"
+if [[ $# -ge 1 ]]; then
+ ref=$1
+else
+ git fetch --quiet sub2api
+ ref=$(git merge-base HEAD sub2api/main)
+fi
+tmp=$(mktemp)
+trap 'rm -f "$tmp"' EXIT
+git ls-tree --name-only "$ref" -- backend/migrations/ | grep '\.sql$' | sort | while read -r path; do
+ sum=$(git show "$ref:$path" | python3 -c 'import hashlib,sys; print(hashlib.sha256(sys.stdin.buffer.read().decode().strip().encode()).hexdigest())')
+ printf '%s %s\n' "$sum" "${path##*/}"
+done >"$tmp"
+{
+ printf '# Generated by scripts/sync-upstream-migration-checksums.sh from upstream %s.\n' "$(git rev-parse --short "$ref")"
+ printf '# Upstream migrations must not be modified; add a new Sub4API migration instead.\n'
+ cat "$tmp"
+} >"$out"
+echo "wrote $(wc -l <"$tmp") entries to ${out#$root/}"