Compare commits

..

4 Commits

Author SHA1 Message Date
YoVinchen 5bccb4f65b Keep cache-control merge regressions easy to review
Reflow the two long cache-control regression assertions in transform.rs so the neighboring merge cases stay rustfmt-aligned and easier to scan.

This keeps the preserved code change separate from the untracked Markdown design notes the user did not want committed.

Constraint: Exclude Markdown design files from the commit while preserving the local code change
Rejected: Include docs in the same commit | user explicitly asked to leave Markdown files out
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Treat this as a readability-only test change; do not infer runtime behavior changes from it
Tested: cargo test --manifest-path src-tauri/Cargo.toml test_anthropic_to_openai_drops_ --lib
Tested: cargo check --manifest-path src-tauri/Cargo.toml --tests
Tested: pnpm format:check
Tested: pnpm typecheck
Not-tested: Full application integration and manual flows
2026-04-11 23:48:45 +08:00
YoVinchen b4f0f7cec3 Merge branch 'main' into codex/issue-1881-cache-control 2026-04-11 23:42:18 +08:00
YoVinchen ad89c4719a Tighten cache hint inheritance for merged system prompts
The follow-up cache hint fix still treated mixed present/absent\ncache_control across fragmented system prompts as inheritable, which\nexpanded the cache scope after prompt collapse. Treat that mix as\nambiguous and only preserve cache_control when every merged fragment\nexplicitly agrees on the same value.\n\nConstraint: Must preserve strict-backend system prompt normalization from #1942\nRejected: Inherit first present cache_control | widens cache scope when later fragments were intentionally uncached\nConfidence: high\nScope-risk: narrow\nReversibility: clean\nDirective: Any future merged-system cache hint logic should treat missing cache_control as semantically significant\nTested: cargo test proxy::providers::transform --manifest-path src-tauri/Cargo.toml\nNot-tested: End-to-end upstream caching behavior against cache-aware relays\nRelated: #1881\nRelated: #1946
2026-04-08 11:16:52 +08:00
YoVinchen b11e36963f Preserve cache hints when collapsing system prompts
Strict OpenAI-compatible chat backends still need fragmented Claude\nsystem prompts collapsed into one leading system message, but that\nnormalization should not silently drop stable cache hints. Preserve\nmessage-level cache_control when the merged system fragments agree,\nand fall back to omitting it when the fragments conflict.\n\nConstraint: Must keep single-system normalization for Nvidia/Qwen-style chat backends\nRejected: Always copy the first cache_control | could misrepresent conflicting cache boundaries\nConfidence: high\nScope-risk: narrow\nReversibility: clean\nDirective: If system prompt merging changes again, preserve cache_control whenever the merged metadata is unambiguous\nTested: cargo test proxy::providers::transform --manifest-path src-tauri/Cargo.toml\nNot-tested: End-to-end prompt caching behavior against cache-aware OpenAI-compatible upstreams\nRelated: #1881
2026-04-08 10:17:16 +08:00
94 changed files with 2474 additions and 4132 deletions
+12 -12
View File
@@ -37,8 +37,8 @@ MiniMax-M2.7 is a next-generation large language model designed for autonomous e
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td> <td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for CC Switch users: if you register via <a href="https://aigocode.com/invite/CC-SWITCH">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td> <td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/drGuwc9k">this link</a> and complete real-name verification to receive ¥20 in bonus credit, usable across models on the platform. SiliconFlow is also now compatible with OpenClaw, allowing users to connect a SiliconFlow API key and call major AI models for free.</td>
</tr> </tr>
<tr> <tr>
@@ -47,8 +47,8 @@ MiniMax-M2.7 is a next-generation large language model designed for autonomous e
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td> <td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/drGuwc9k">this link</a> and complete real-name verification to receive ¥20 in bonus credit, usable across models on the platform. SiliconFlow is also now compatible with OpenClaw, allowing users to connect a SiliconFlow API key and call major AI models for free.</td> <td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for CC Switch users: if you register via <a href="https://aigocode.com/invite/CC-SWITCH">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td>
</tr> </tr>
<tr> <tr>
@@ -72,21 +72,21 @@ Claude Code / Codex / Gemini official channels at 38% / 2% / 9% of original pric
<td>Thanks to Compshare for sponsoring this project! Compshare is UCloud's AI cloud platform, providing stable and comprehensive domestic and international model APIs with just one key. Featuring cost-effective monthly and pay-as-you-go Coding Plan packages at 60-80% off official prices. Supports Claude Code, Codex, and API access. Enterprise-grade high concurrency, 24/7 technical support, and self-service invoicing. Users who register via <a href="https://www.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch">this link</a> will receive a free 5 CNY platform trial credit!</td> <td>Thanks to Compshare for sponsoring this project! Compshare is UCloud's AI cloud platform, providing stable and comprehensive domestic and international model APIs with just one key. Featuring cost-effective monthly and pay-as-you-go Coding Plan packages at 60-80% off official prices. Supports Claude Code, Codex, and API access. Enterprise-grade high concurrency, 24/7 technical support, and self-service invoicing. Users who register via <a href="https://www.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch">this link</a> will receive a free 5 CNY platform trial credit!</td>
</tr> </tr>
<tr>
<td width="180"><a href="https://www.right.codes/register?aff=CCSWITCH"><img src="assets/partners/logos/rightcode.jpg" alt="RightCode" width="150"></a></td>
<td>Thank you to Right Code for sponsoring this project! Right Code reliably provides routing services for models such as Claude Code, Codex, and Gemini. It features a highly cost-effective Codex monthly subscription plan and <strong>supports quota rollovers—unused quota from one day can be carried over and used the next day.</strong> Invoices are available upon top-up. Enterprise and team users can receive dedicated one-on-one support. Right Code also offers an exclusive discount for CC Switch users: register via <a href="https://www.right.codes/register?aff=CCSWITCH">this link</a>, and with every top-up you will receive pay-as-you-go credit equivalent to 25% of the amount paid.</td>
</tr>
<tr> <tr>
<td width="180"><a href="https://aicoding.sh/i/CCSWITCH"><img src="assets/partners/logos/aicoding.jpg" alt="AICoding" width="150"></a></td> <td width="180"><a href="https://aicoding.sh/i/CCSWITCH"><img src="assets/partners/logos/aicoding.jpg" alt="AICoding" width="150"></a></td>
<td>Thanks to AICoding.sh for sponsoring this project! AICoding.sh — Global AI Model API Relay Service at Unbeatable Prices! Claude Code at 19% of original price, GPT at just 1%! Trusted by hundreds of enterprises for cost-effective AI services. Supports Claude Code, GPT, Gemini and major domestic models, with enterprise-grade high concurrency, fast invoicing, and 24/7 dedicated technical support. CC Switch users who register via <a href="https://aicoding.sh/i/CCSWITCH">this link</a> get 10% off their first top-up!</td> <td>Thanks to AICoding.sh for sponsoring this project! AICoding.sh — Global AI Model API Relay Service at Unbeatable Prices! Claude Code at 19% of original price, GPT at just 1%! Trusted by hundreds of enterprises for cost-effective AI services. Supports Claude Code, GPT, Gemini and major domestic models, with enterprise-grade high concurrency, fast invoicing, and 24/7 dedicated technical support. CC Switch users who register via <a href="https://aicoding.sh/i/CCSWITCH">this link</a> get 10% off their first top-up!</td>
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch"><img src="assets/partners/logos/crazyrouter.png" alt="Crazyrouter" width="150"></a></td> <td width="180"><a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch"><img src="assets/partners/logos/crazyrouter.jpg" alt="Crazyrouter" width="150"></a></td>
<td>Thanks to Crazyrouter for sponsoring this project! Crazyrouter is a high-performance AI API aggregation platform — one API key for 300+ models including Claude Code, Codex, Gemini CLI, and more. All models at 55% of official pricing with auto-failover, smart routing, and unlimited concurrency. Crazyrouter offers an exclusive deal for CC Switch users: register via <a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch">this link</a> to get <strong>$2 free credit</strong> instantly, plus enter promo code `CCSWITCH` on your first top-up for an extra <strong>30% bonus credit</strong>! </td> <td>Thanks to Crazyrouter for sponsoring this project! Crazyrouter is a high-performance AI API aggregation platform — one API key for 300+ models including Claude Code, Codex, Gemini CLI, and more. All models at 55% of official pricing with auto-failover, smart routing, and unlimited concurrency. Crazyrouter offers an exclusive deal for CC Switch users: register via <a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch">this link</a> to get <strong>$2 free credit</strong> instantly, plus enter promo code `CCSWITCH` on your first top-up for an extra <strong>30% bonus credit</strong>! </td>
</tr> </tr>
<tr>
<td width="180"><a href="https://www.right.codes/register?aff=CCSWITCH"><img src="assets/partners/logos/rightcode.jpg" alt="RightCode" width="150"></a></td>
<td>Thank you to Right Code for sponsoring this project! Right Code reliably provides routing services for models such as Claude Code, Codex, and Gemini. It features a highly cost-effective Codex monthly subscription plan and <strong>supports quota rollovers—unused quota from one day can be carried over and used the next day.</strong> Invoices are available upon top-up. Enterprise and team users can receive dedicated one-on-one support. Right Code also offers an exclusive discount for CC Switch users: register via <a href="https://www.right.codes/register?aff=CCSWITCH">this link</a>, and with every top-up you will receive pay-as-you-go credit equivalent to 25% of the amount paid.</td>
</tr>
<tr> <tr>
<td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td> <td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
<td>Thanks to SSSAiCode for sponsoring this project! SSSAiCode is a stable and reliable API relay service, dedicated to providing stable, reliable, and affordable Claude and Codex model services, <strong>offering high cost-effective official Claude service at just ¥0.5/$ equivalent</strong>, supporting monthly and pay-as-you-go billing plans with same-day fast invoicing. SSSAiCode offers a special deal for CC Switch users: register via <a href="https://www.sssaicode.com/register?ref=DCP0SM">this link</a> to enjoy $10 extra credit on every top-up!</td> <td>Thanks to SSSAiCode for sponsoring this project! SSSAiCode is a stable and reliable API relay service, dedicated to providing stable, reliable, and affordable Claude and Codex model services, <strong>offering high cost-effective official Claude service at just ¥0.5/$ equivalent</strong>, supporting monthly and pay-as-you-go billing plans with same-day fast invoicing. SSSAiCode offers a special deal for CC Switch users: register via <a href="https://www.sssaicode.com/register?ref=DCP0SM">this link</a> to enjoy $10 extra credit on every top-up!</td>
@@ -98,8 +98,8 @@ Claude Code / Codex / Gemini official channels at 38% / 2% / 9% of original pric
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://lemondata.cc/r/FFX1ZDUP"><img src="assets/partners/logos/lemondata.png" alt="LemonData" width="150"></a></td> <td width="180"><a href="https://x-code.cc/register?aff=IbPp"><img src="assets/partners/logos/xcodeapi.png" alt="XCodeAPI" width="150"></a></td>
<td>Thanks to LemonData for sponsoring this project! LemonData is a high-performance AI API aggregation platform — one API key for 300+ models including GPT, Claude, Gemini, DeepSeek, and more. All models priced 3070% below official rates with auto-failover, smart routing, and unlimited concurrency. New users get $1 free credit instantly upon registration — sign up via <a href="https://lemondata.cc/r/FFX1ZDUP">this link</a>to claim your bonus and start building right away</strong>!</td> <td>Thanks to XCodeAPI for sponsoring this project! XCodeAPI offers a special benefit for CC Switch users: register via <a href="https://x-code.cc/register?aff=IbPp">this link</a> and get an extra 10% credit bonus on your first order! (Contact the site admin to claim)</td>
</tr> </tr>
<tr> <tr>
+12 -14
View File
@@ -37,8 +37,8 @@ MiniMax-M2.7 は、自律的進化と実世界の生産性向上のために設
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td> <td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>本プロジェクトは AIGoCode のスポンサー提供でお届けしています。AIGoCode は、Claude Code・Codex・最新の Gemini モデルを統合したオールインワンのAIコーディングプラットフォームで、安定性・高速性・コストパフォーマンスに優れた開発サービスを提供します。柔軟なサブスクリプションプランを備え、レスポンスも非常に高速です。さらに、CC Switch ユーザー向けの特典として、<a href="https://aigocode.com/invite/CC-SWITCH">このリンク</a>から登録すると、初回チャージ時に10%分のボーナスクレジットが付与されます!</td> <td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/drGuwc9k">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥20 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td>
</tr> </tr>
<tr> <tr>
@@ -47,8 +47,8 @@ MiniMax-M2.7 は、自律的進化と実世界の生産性向上のために設
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td> <td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/drGuwc9k">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥20 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td> <td>本プロジェクトは AIGoCode のスポンサー提供でお届けしています。AIGoCode は、Claude Code・Codex・最新の Gemini モデルを統合したオールインワンのAIコーディングプラットフォームで、安定性・高速性・コストパフォーマンスに優れた開発サービスを提供します。柔軟なサブスクリプションプランを備え、レスポンスも非常に高速です。さらに、CC Switch ユーザー向けの特典として、<a href="https://aigocode.com/invite/CC-SWITCH">このリンク</a>から登録すると、初回チャージ時に10%分のボーナスクレジットが付与されます!</td>
</tr> </tr>
<tr> <tr>
@@ -73,6 +73,9 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://www.right.codes/register?aff=CCSWITCH"><img src="assets/partners/logos/rightcode.jpg" alt="RightCode" width="150"></a></td>
<td>本プロジェクトへのご支援として、Right Code にご協賛いただき誠にありがとうございます。Right Code は、Claude Code、Codex、Gemini などのモデルに対応した中継(プロキシ)サービスを安定して提供しています。特に高いコストパフォーマンスを誇る Codex の月額プランを主力としており、<strong>未使用分の利用枠を翌日に繰り越して利用できる(繰越対応)</strong>点が特長です。チャージ(入金)後に請求書の発行が可能で、企業・チーム向けには専任担当による個別対応も行っています。さらに CC Switch ユーザー向けの特別優待として、<a href="https://www.right.codes/register?aff=CCSWITCH">こちらのリンク</a>からご登録いただくと、チャージのたびに実支払額の 25% 相当の従量課金クレジットが付与されます。</td>
</tr>
<tr> <tr>
<td width="180"><a href="https://aicoding.sh/i/CCSWITCH"><img src="assets/partners/logos/aicoding.jpg" alt="AICoding" width="150"></a></td> <td width="180"><a href="https://aicoding.sh/i/CCSWITCH"><img src="assets/partners/logos/aicoding.jpg" alt="AICoding" width="150"></a></td>
@@ -80,15 +83,10 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch"><img src="assets/partners/logos/crazyrouter.png" alt="Crazyrouter" width="150"></a></td> <td width="180"><a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch"><img src="assets/partners/logos/crazyrouter.jpg" alt="Crazyrouter" width="150"></a></td>
<td>Crazyrouter のご支援に感謝します!Crazyrouter は高性能 AI API アグリゲーションプラットフォームです。1 つの API キーで Claude Code、Codex、Gemini CLI など 300 以上のモデルにアクセス可能。全モデルが公式価格の 55% で利用でき、自動フェイルオーバー、スマートルーティング、無制限同時接続に対応。CC Switch ユーザー向けの限定特典:<a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch">こちらのリンク</a>から登録すると <strong>$2 の無料クレジット</strong> を即時進呈。さらに初回チャージ時にプロモコード `CCSWITCH` を入力すると <strong>30% のボーナスクレジット</strong> が追加されます!</td> <td>Crazyrouter のご支援に感謝します!Crazyrouter は高性能 AI API アグリゲーションプラットフォームです。1 つの API キーで Claude Code、Codex、Gemini CLI など 300 以上のモデルにアクセス可能。全モデルが公式価格の 55% で利用でき、自動フェイルオーバー、スマートルーティング、無制限同時接続に対応。CC Switch ユーザー向けの限定特典:<a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch">こちらのリンク</a>から登録すると <strong>$2 の無料クレジット</strong> を即時進呈。さらに初回チャージ時にプロモコード `CCSWITCH` を入力すると <strong>30% のボーナスクレジット</strong> が追加されます!</td>
</tr> </tr>
<tr>
<td width="180"><a href="https://www.right.codes/register?aff=CCSWITCH"><img src="assets/partners/logos/rightcode.jpg" alt="RightCode" width="150"></a></td>
<td>本プロジェクトへのご支援として、Right Code にご協賛いただき誠にありがとうございます。Right Code は、Claude Code、Codex、Gemini などのモデルに対応した中継(プロキシ)サービスを安定して出しています。特に高いコストパフォーマンスを誇る Codex の月刊プランを主力としており、<strong>未使用分の利用枠を翌日に繰り越して利用できる(繰越対応)</strong>점이特长です。チャージ(入金)後に請求書の発行が可能で、企業・チーム向けには専任担当による個別対応も行っています。さらに CC Switch ユーザー向けの特別優待として、<a href="https://www.right.codes/register?aff=CCSWITCH">こちらのリンク</a>からご登録くと、チャージのたびに実支払額の 25% 相当の従量課金クレジットが付与されます。</td>
</tr>
<tr> <tr>
<td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td> <td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
<td>SSSAiCode のご支援に感謝します!SSSAiCode は安定性と信頼性に優れた API 中継サービスで、安定的で信頼性が高く、手頃な価格の Claude・Codex モデルサービスを提供しています。<strong>高コストパフォーマンスの公式 Claude サービスを 0.5¥/$ 換算で提供</strong>、月額制・Paygo など多様な課金方式に対応し、当日の迅速な請求書発行をサポート。CC Switch ユーザー向けの特別特典:<a href="https://www.sssaicode.com/register?ref=DCP0SM">こちらのリンク</a>から登録すると、毎回のチャージで $10 の追加ボーナスを受けられます!</td> <td>SSSAiCode のご支援に感謝します!SSSAiCode は安定性と信頼性に優れた API 中継サービスで、安定的で信頼性が高く、手頃な価格の Claude・Codex モデルサービスを提供しています。<strong>高コストパフォーマンスの公式 Claude サービスを 0.5¥/$ 換算で提供</strong>、月額制・Paygo など多様な課金方式に対応し、当日の迅速な請求書発行をサポート。CC Switch ユーザー向けの特別特典:<a href="https://www.sssaicode.com/register?ref=DCP0SM">こちらのリンク</a>から登録すると、毎回のチャージで $10 の追加ボーナスを受けられます!</td>
@@ -98,11 +96,11 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
<td width="180"><a href="https://www.openclaudecode.cn/register?aff=aOYQ"><img src="assets/partners/logos/mikubanner.svg" alt="Micu" width="150"></a></td> <td width="180"><a href="https://www.openclaudecode.cn/register?aff=aOYQ"><img src="assets/partners/logos/mikubanner.svg" alt="Micu" width="150"></a></td>
<td>Micu API のご支援に感謝します!Micu API は、最高のコストパフォーマンスと高い安定性を追求するグローバル大規模言語モデル中継サービスプロバイダーです。法人企業がバックアップしており、サービス停止のリスクを排除、迅速な正規請求書発行に対応!「試行コストゼロ」をモットーに、最低 1 元からチャージ可能で手数料無料、いつでも返金可能!CC Switch ユーザー向けの限定特典:<a href="https://www.openclaudecode.cn/register?aff=aOYQ">こちらのリンク</a>から登録し、チャージ時にプロモコード「ccswitch」を入力すると <strong>10% 割引</strong> が適用されます!</td> <td>Micu API のご支援に感謝します!Micu API は、最高のコストパフォーマンスと高い安定性を追求するグローバル大規模言語モデル中継サービスプロバイダーです。法人企業がバックアップしており、サービス停止のリスクを排除、迅速な正規請求書発行に対応!「試行コストゼロ」をモットーに、最低 1 元からチャージ可能で手数料無料、いつでも返金可能!CC Switch ユーザー向けの限定特典:<a href="https://www.openclaudecode.cn/register?aff=aOYQ">こちらのリンク</a>から登録し、チャージ時にプロモコード「ccswitch」を入力すると <strong>10% 割引</strong> が適用されます!</td>
</tr> </tr>
<tr>
<td width="180"><a href="https://lemondata.cc/r/FFX1ZDUP"><img src="assets/partners/logos/lemondata.png" alt="LemonData" width="150"></a></td>
<td>LemonData のご支援に感謝します!LemonData は高性能 AI API アグリゲーションプラットフォームで、GPT、Claude、Gemini、DeepSeek など 300 以上のモデルに 1 つの API キーでアクセス可能。全モデルが公式価格の 30〜70% オフで自動フェイルオーバー、スマートルーティング、無制限同時接続に対応。新規ユーザーは登録だけで即座に $1 の無料クレジットを獲得 — <a href="https://lemondata.cc/r/FFX1ZDUP">こちらのリンク</a>から登録してボーナスを獲得し、すぐに開発を始めましょう!</td>
</tr>
<tr>
<td width="180"><a href="https://x-code.cc/register?aff=IbPp"><img src="assets/partners/logos/xcodeapi.png" alt="XCodeAPI" width="150"></a></td>
<td>XCodeAPI のご支援に感謝します!CC Switch ユーザー向けの特別特典:<a href="https://x-code.cc/register?aff=IbPp">こちらのリンク</a>から登録すると、初回注文で 10% の追加クレジットボーナスがもらえます!(サイト管理者に連絡して受け取りください)</td>
</tr>
<tr> <tr>
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td> <td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
+14 -14
View File
@@ -37,8 +37,8 @@ MiniMax M2.7 是 MiniMax 首个深度参与自我迭代的模型,可自主构
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td> <td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_zh.jpg" alt="SiliconFlow" width="150"></a></td>
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一个集成了 Claude Code、Codex 以及 Gemini 最新模型的一站式平台,为你提供稳定、高效且高性价比的AI编程服务。本站提供灵活的订阅计划,零封号风险,国内直连,无需魔法,极速响应。AIGoCode 为 CC Switch 的用户提供了特别福利,通过<a href="https://aigocode.com/invite/CC-SWITCH">此链接</a>注册的用户首次充值可以获得额外10%奖励额度!</td> <td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/drGuwc9k">此链接</a>注册并完成实名认证,即可获得 ¥20 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td>
</tr> </tr>
<tr> <tr>
@@ -47,8 +47,8 @@ MiniMax M2.7 是 MiniMax 首个深度参与自我迭代的模型,可自主构
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_zh.jpg" alt="SiliconFlow" width="150"></a></td> <td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/drGuwc9k">此链接</a>注册并完成实名认证,即可获得 ¥20 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td> <td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一个集成了 Claude Code、Codex 以及 Gemini 最新模型的一站式平台,为你提供稳定、高效且高性价比的AI编程服务。本站提供灵活的订阅计划,零封号风险,国内直连,无需魔法,极速响应。AIGoCode 为 CC Switch 的用户提供了特别福利,通过<a href="https://aigocode.com/invite/CC-SWITCH">此链接</a>注册的用户首次充值可以获得额外10%奖励额度!</td>
</tr> </tr>
<tr> <tr>
@@ -73,21 +73,21 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
<td>感谢优云智算赞助了本项目!优云智算是UCloud旗下AI云平台,提供稳定、全面的国内外模型API,仅一个key即可调用。主打包月、按量的高性价比 Coding Plan 套餐,基于官方2~5折优惠。支持接入 Claude Code、Codex 及 API 调用。支持企业高并发、7*24技术支持、自助开票。通过<a href="https://www.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch">此链接</a>注册的用户,可得免费5元平台体验金!</td> <td>感谢优云智算赞助了本项目!优云智算是UCloud旗下AI云平台,提供稳定、全面的国内外模型API,仅一个key即可调用。主打包月、按量的高性价比 Coding Plan 套餐,基于官方2~5折优惠。支持接入 Claude Code、Codex 及 API 调用。支持企业高并发、7*24技术支持、自助开票。通过<a href="https://www.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch">此链接</a>注册的用户,可得免费5元平台体验金!</td>
</tr> </tr>
<tr>
<td width="180"><a href="https://www.right.codes/register?aff=CCSWITCH"><img src="assets/partners/logos/rightcode.jpg" alt="RightCode" width="150"></a></td>
<td>感谢 Right Code 赞助了本项目!Right Code 稳定提供 Claude Code、Codex、Gemini 等模型的中转服务。主打<strong>极高性价比</strong>的Codex包月套餐,<strong>提供额度转结,套餐当天用不完的额度,第二天还能接着用!</strong>充值即可开票,企业、团队用户一对一对接。同时为 CC Switch 的用户提供了特别优惠:通过<a href="https://www.right.codes/register?aff=CCSWITCH">此链接</a>注册,每次充值均可获得实付金额25%的按量额度!</td>
</tr>
<tr> <tr>
<td width="180"><a href="https://aicoding.sh/i/CCSWITCH"><img src="assets/partners/logos/aicoding.jpg" alt="AICoding" width="150"></a></td> <td width="180"><a href="https://aicoding.sh/i/CCSWITCH"><img src="assets/partners/logos/aicoding.jpg" alt="AICoding" width="150"></a></td>
<td>感谢 AICoding.sh 赞助了本项目!AICoding.sh —— 全球大模型 API 超值中转服务!Claude Code 1.9 折,GPT 0.1 折,已为数百家企业提供高性价比 AI 服务。支持 Claude Code、GPT、Gemini 及国内主流模型,企业级高并发、极速开票、7×24 专属技术支持,通过<a href="https://aicoding.sh/i/CCSWITCH">此链接</a> 注册的 CC Switch 用户,首充可享受九折优惠!</td> <td>感谢 AICoding.sh 赞助了本项目!AICoding.sh —— 全球大模型 API 超值中转服务!Claude Code 1.9 折,GPT 0.1 折,已为数百家企业提供高性价比 AI 服务。支持 Claude Code、GPT、Gemini 及国内主流模型,企业级高并发、极速开票、7×24 专属技术支持,通过<a href="https://aicoding.sh/i/CCSWITCH">此链接</a> 注册的 CC Switch 用户,首充可享受九折优惠!</td>
</tr> </tr>
<tr> <tr>
<td width="180"><a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch"><img src="assets/partners/logos/crazyrouter.png" alt="Crazyrouter" width="150"></a></td> <td width="180"><a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch"><img src="assets/partners/logos/crazyrouter.jpg" alt="Crazyrouter" width="150"></a></td>
<td>感谢 Crazyrouter 赞助了本项目!Crazyrouter 是一个高性能 AI API 聚合平台——一个 API Key 即可访问 300+ 模型,包括 Claude Code、Codex、Gemini CLI 等。全部模型低至官方定价的 55%,支持自动故障转移、智能路由和无限并发。Crazyrouter 为 CC Switch 用户提供了专属优惠:通过<a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch">此链接</a>注册即可获得 <strong>$2 免费额度</strong>,首次充值时输入优惠码 `CCSWITCH` 还可获得额外 <strong>30% 奖励额度</strong></td> <td>感谢 Crazyrouter 赞助了本项目!Crazyrouter 是一个高性能 AI API 聚合平台——一个 API Key 即可访问 300+ 模型,包括 Claude Code、Codex、Gemini CLI 等。全部模型低至官方定价的 55%,支持自动故障转移、智能路由和无限并发。Crazyrouter 为 CC Switch 用户提供了专属优惠:通过<a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch">此链接</a>注册即可获得 <strong>$2 免费额度</strong>,首次充值时输入优惠码 `CCSWITCH` 还可获得额外 <strong>30% 奖励额度</strong></td>
</tr> </tr>
<tr>
<td width="180"><a href="https://www.right.codes/register?aff=CCSWITCH"><img src="assets/partners/logos/rightcode.jpg" alt="RightCode" width="150"></a></td>
<td>感谢 Right Code 赞助了本项目!Right Code 稳定提供 Claude Code、Codex、Gemini 等模型的中转服务。主打<strong>极高性价比</strong>的Codex包月套餐,<strong>提供额度转结,套餐当天用不完的额度,第二天还能接着用!</strong>充值即可开票,企业、团队用户一对一对接。同时为 CC Switch 的用户提供了特别优惠:通过<a href="https://www.right.codes/register?aff=CCSWITCH">此链接</a>注册,每次充值均可获得实付金额25%的按量额度!</td>
</tr>
<tr> <tr>
<td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td> <td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
<td>感谢 SSSAiCode 赞助了本项目!SSSAiCode 是一家稳定可靠的API中转站,致力于提供稳定、可靠、平价的Claude、CodeX模型服务,<strong>提供高性价比折合0.5¥/$的官方Claude服务</strong>,支持包月、Paygo多种计费方式、支持当日快速开票,SSSAiCode为本软件的用户提供特别优惠,使用<a href="https://www.sssaicode.com/register?ref=DCP0SM">此链接</a>注册每次充值均可享受10$的额外奖励!</td> <td>感谢 SSSAiCode 赞助了本项目!SSSAiCode 是一家稳定可靠的API中转站,致力于提供稳定、可靠、平价的Claude、CodeX模型服务,<strong>提供高性价比折合0.5¥/$的官方Claude服务</strong>,支持包月、Paygo多种计费方式、支持当日快速开票,SSSAiCode为本软件的用户提供特别优惠,使用<a href="https://www.sssaicode.com/register?ref=DCP0SM">此链接</a>注册每次充值均可享受10$的额外奖励!</td>
@@ -97,11 +97,11 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
<td width="180"><a href="https://www.openclaudecode.cn/register?aff=aOYQ"><img src="assets/partners/logos/mikubanner.svg" alt="Micu" width="150"></a></td> <td width="180"><a href="https://www.openclaudecode.cn/register?aff=aOYQ"><img src="assets/partners/logos/mikubanner.svg" alt="Micu" width="150"></a></td>
<td>感谢 米醋API 赞助了本项目!米醋API 是一家致力于提供极致性价比与高稳定性的全球大模型中转服务商。米醋API 背后有实体企业做核心保障,杜绝跑路风险,支持极速正规开票!我们主打“试错零成本”:1 元起充低门槛,0 手续费随时退款!米醋API 为本软件的用户提供了特别优惠,使用<a href="https://www.openclaudecode.cn/register?aff=aOYQ">此链接</a>注册并在充值时填写"ccswitch"优惠码可享九折优惠!</td> <td>感谢 米醋API 赞助了本项目!米醋API 是一家致力于提供极致性价比与高稳定性的全球大模型中转服务商。米醋API 背后有实体企业做核心保障,杜绝跑路风险,支持极速正规开票!我们主打“试错零成本”:1 元起充低门槛,0 手续费随时退款!米醋API 为本软件的用户提供了特别优惠,使用<a href="https://www.openclaudecode.cn/register?aff=aOYQ">此链接</a>注册并在充值时填写"ccswitch"优惠码可享九折优惠!</td>
</tr> </tr>
<tr>
<td width="180"><a href="https://lemondata.cc/r/FFX1ZDUP"><img src="assets/partners/logos/lemondata.png" alt="LemonData" width="150"></a></td>
<td>感谢 LemonData 赞助了本项目!LemonData 是一个高性能 AI API 聚合平台——一个 API Key 即可访问 GPT、Claude、Gemini、DeepSeek 等 300+ 模型。所有模型定价为官方价格的 30%-70%,支持自动故障转移、智能路由和无限并发。新用户注册即获 $1 免费额度——通过<a href="https://lemondata.cc/r/FFX1ZDUP">此链接</a>注册即可领取奖励,立即开始开发!</td>
</tr>
<tr>
<td width="180"><a href="https://x-code.cc/register?aff=IbPp"><img src="assets/partners/logos/xcodeapi.png" alt="XCodeAPI" width="150"></a></td>
<td>感谢 XCodeAPI 赞助了本项目!XCodeAPI 为本软件的用户提供特别福利,使用<a href="https://x-code.cc/register?aff=IbPp">此链接</a>注册后首单加赠10%的额度!(联系站长领取)</td>
</tr>
<tr> <tr>
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td> <td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

-195
View File
@@ -1,195 +0,0 @@
# 4.2 App Routing
## Overview
App routing means letting CC Switch route a specific application's API requests through the local routing service.
When routing is enabled:
- The app's API requests are forwarded through local routing
- Request logs and usage statistics can be recorded
- Failover functionality becomes available
## Prerequisites
The routing service must be started before using the app routing feature.
## Enable Routing
### Location
Settings > Advanced > Routing Service > App Routing area
### Steps
1. Ensure the routing service is started
2. Find the "App Routing" area
3. Enable the toggle for the desired apps
### Routing Toggles
| Toggle | Effect |
|--------|--------|
| Claude Routing | Route Claude Code requests |
| Codex Routing | Route Codex requests |
| Gemini Routing | Route Gemini CLI requests |
Multiple app routings can be enabled simultaneously.
## How Routing Works
### Configuration Changes
When routing is enabled, CC Switch modifies the app's configuration file to point the API endpoint to the local routing service.
**Claude configuration change**:
```json
// Before routing
{
"env": {
"ANTHROPIC_BASE_URL": "https://api.anthropic.com"
}
}
// After routing
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:15721"
}
}
```
**Codex configuration change**:
```toml
# Before routing
base_url = "https://api.openai.com/v1"
# After routing
base_url = "http://127.0.0.1:15721/v1"
```
**Gemini configuration change**:
```bash
# Before routing
GOOGLE_GEMINI_BASE_URL=https://generativelanguage.googleapis.com
# After routing
GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:15721
```
### Request Forwarding
When the routing service receives a request:
1. Identifies the request source (Claude/Codex/Gemini)
2. Looks up the currently enabled provider for that app
3. Forwards the request to the provider's actual endpoint
4. Records the request log
5. Returns the response to the app
## Routing Status Indicators
### Main Interface Indicators
When routing is enabled, the main interface shows the following changes:
- **Routing logo color**: Changes from colorless to green
- **Provider cards**: The currently active provider shows a green border
### Provider Card States
| State | Border Color | Description |
|-------|--------------|-------------|
| Currently Active | Blue | Provider in the config file (non-routing mode) |
| Routing Active | Green | Provider actually used by routing |
| Normal | Default | Unused provider |
## Disable Routing
### Steps
1. Turn off the corresponding app's routing toggle in the routing panel
2. Or directly stop the routing service
### Configuration Restoration
When disabling routing, CC Switch will:
1. Restore the app configuration to its pre-routing state
2. Save current request logs
## Routing and Provider Switching
### Switching Providers in Routing Mode
When switching providers in routing mode:
1. Click the "Enable" button on a provider in the main interface
2. The routing service immediately uses the new provider to forward requests
3. **No need to restart the CLI tool**
This is a major advantage of routing mode: provider switching takes effect instantly.
### Switching Without Routing
When switching providers without routing:
1. Configuration file is modified
2. CLI tool must be restarted for changes to take effect
## Multi-app Routing
Multiple apps can be routed simultaneously, each managed independently:
- Independent provider configurations
- Independent failover queues
- Independent request statistics
## Use Cases
### Scenario 1: Usage Monitoring
Enable routing + log recording to monitor API usage.
### Scenario 2: Quick Switching
With routing enabled, switching providers does not require restarting CLI tools.
### Scenario 3: Failover
Enabling routing is a prerequisite for using the failover feature.
## Notes
### Performance Impact
Routing adds minimal latency (typically < 10ms), negligible for most scenarios.
### Network Requirements
In routing mode, CLI tools must be able to access the local routing address.
### Configuration Backup
Before enabling routing, CC Switch backs up the original configuration and restores it when disabled.
## FAQ
### Requests Fail After Enabling Routing
Check:
- Is the routing service running normally
- Is the provider configuration correct
- Is the network working properly
### Configuration Not Restored After Disabling Routing
Possible causes:
- Routing service exited abnormally
- Configuration file was modified by another program
Solutions:
- Manually edit the provider and re-save
- Or re-enable and then disable routing
+195
View File
@@ -0,0 +1,195 @@
# 4.2 App Takeover
## Overview
App takeover means letting CC Switch's proxy intercept and forward a specific application's API requests.
When takeover is enabled:
- The app's API requests are forwarded through the local proxy
- Request logs and usage statistics can be recorded
- Failover functionality becomes available
## Prerequisites
The proxy service must be started before using the app takeover feature.
## Enable Takeover
### Location
Settings > Advanced > Proxy Service > App Takeover area
### Steps
1. Ensure the proxy service is started
2. Find the "App Takeover" area
3. Enable the toggle for the desired apps
### Takeover Toggles
| Toggle | Effect |
|--------|--------|
| Claude Takeover | Intercept Claude Code requests |
| Codex Takeover | Intercept Codex requests |
| Gemini Takeover | Intercept Gemini CLI requests |
Multiple app takeovers can be enabled simultaneously.
## How Takeover Works
### Configuration Changes
When takeover is enabled, CC Switch modifies the app's configuration file to point the API endpoint to the local proxy.
**Claude configuration change**:
```json
// Before takeover
{
"env": {
"ANTHROPIC_BASE_URL": "https://api.anthropic.com"
}
}
// After takeover
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:15721"
}
}
```
**Codex configuration change**:
```toml
# Before takeover
base_url = "https://api.openai.com/v1"
# After takeover
base_url = "http://127.0.0.1:15721/v1"
```
**Gemini configuration change**:
```bash
# Before takeover
GOOGLE_GEMINI_BASE_URL=https://generativelanguage.googleapis.com
# After takeover
GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:15721
```
### Request Forwarding
When the proxy receives a request:
1. Identifies the request source (Claude/Codex/Gemini)
2. Looks up the currently enabled provider for that app
3. Forwards the request to the provider's actual endpoint
4. Records the request log
5. Returns the response to the app
## Takeover Status Indicators
### Main Interface Indicators
When takeover is enabled, the main interface shows the following changes:
- **Proxy logo color**: Changes from colorless to green
- **Provider cards**: The currently active provider shows a green border
### Provider Card States
| State | Border Color | Description |
|-------|--------------|-------------|
| Currently Active | Blue | Provider in the config file (non-proxy mode) |
| Proxy Active | Green | Provider actually used by the proxy |
| Normal | Default | Unused provider |
## Disable Takeover
### Steps
1. Turn off the corresponding app's takeover toggle in the proxy panel
2. Or directly stop the proxy service
### Configuration Restoration
When disabling takeover, CC Switch will:
1. Restore the app configuration to its pre-takeover state
2. Save current request logs
## Takeover and Provider Switching
### Switching Providers in Takeover Mode
When switching providers in takeover mode:
1. Click the "Enable" button on a provider in the main interface
2. The proxy immediately uses the new provider to forward requests
3. **No need to restart the CLI tool**
This is a major advantage of takeover mode: provider switching takes effect instantly.
### Switching Without Takeover
When switching providers without takeover:
1. Configuration file is modified
2. CLI tool must be restarted for changes to take effect
## Multi-app Takeover
Multiple apps can be taken over simultaneously, each managed independently:
- Independent provider configurations
- Independent failover queues
- Independent request statistics
## Use Cases
### Scenario 1: Usage Monitoring
Enable takeover + log recording to monitor API usage.
### Scenario 2: Quick Switching
With takeover enabled, switching providers does not require restarting CLI tools.
### Scenario 3: Failover
Enabling takeover is a prerequisite for using the failover feature.
## Notes
### Performance Impact
The proxy adds minimal latency (typically < 10ms), negligible for most scenarios.
### Network Requirements
In takeover mode, CLI tools must be able to access the local proxy address.
### Configuration Backup
Before enabling takeover, CC Switch backs up the original configuration and restores it when disabled.
## FAQ
### Requests Fail After Takeover
Check:
- Is the proxy service running normally
- Is the provider configuration correct
- Is the network working properly
### Configuration Not Restored After Disabling Takeover
Possible causes:
- Proxy exited abnormally
- Configuration file was modified by another program
Solutions:
- Manually edit the provider and re-save
- Or re-enable and then disable takeover
+1 -1
View File
@@ -79,7 +79,7 @@ CC Switch User Manual
| File | Description | | File | Description |
|------|-------------| |------|-------------|
| [4.1-service.md](./4-proxy/4.1-service.md) | Start proxy, configuration, running status | | [4.1-service.md](./4-proxy/4.1-service.md) | Start proxy, configuration, running status |
| [4.2-routing.md](./4-proxy/4.2-routing.md) | App routing, configuration changes, status indicators | | [4.2-takeover.md](./4-proxy/4.2-takeover.md) | App takeover, configuration changes, status indicators |
| [4.3-failover.md](./4-proxy/4.3-failover.md) | Failover queue, circuit breaker, health status | | [4.3-failover.md](./4-proxy/4.3-failover.md) | Failover queue, circuit breaker, health status |
| [4.4-usage.md](./4-proxy/4.4-usage.md) | Usage statistics, trend charts, pricing configuration | | [4.4-usage.md](./4-proxy/4.4-usage.md) | Usage statistics, trend charts, pricing configuration |
| [4.5-model-test.md](./4-proxy/4.5-model-test.md) | Model test, health check, latency testing | | [4.5-model-test.md](./4-proxy/4.5-model-test.md) | Model test, health check, latency testing |
-195
View File
@@ -1,195 +0,0 @@
# 4.2 アプリケーションルーティング
## 機能説明
アプリケーションルーティングとは、CC Switch のルーティングサービスが特定アプリの API リクエストをルーティングすることです。
ルーティングを有効にすると:
- アプリの API リクエストがローカルルーティング経由で転送される
- リクエストログと使用量の統計を記録できる
- フェイルオーバー機能を使用できる
## 前提条件
アプリケーションルーティング機能を使用する前に、ルーティングサービスを起動する必要があります。
## ルーティングの有効化
### 操作場所
設定 → 詳細 → ルーティングサービス → アプリケーションルーティングエリア
### 操作手順
1. ルーティングサービスが起動していることを確認
2. 「アプリケーションルーティング」エリアを見つける
3. 必要なアプリのスイッチをオンにする
### ルーティングスイッチ
| スイッチ | 作用 |
|------|------|
| Claude ルーティング | Claude Code のリクエストをルーティング |
| Codex ルーティング | Codex のリクエストをルーティング |
| Gemini ルーティング | Gemini CLI のリクエストをルーティング |
複数のアプリのルーティングを同時に有効にできます。
## ルーティングの仕組み
### 設定の変更
ルーティングを有効にすると、CC Switch はアプリの設定ファイルを変更し、API エンドポイントをローカルルーティングに向けます。
**Claude 設定の変更**
```json
// ルーティング前
{
"env": {
"ANTHROPIC_BASE_URL": "https://api.anthropic.com"
}
}
// ルーティング後
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:15721"
}
}
```
**Codex 設定の変更**
```toml
# ルーティング前
base_url = "https://api.openai.com/v1"
# ルーティング後
base_url = "http://127.0.0.1:15721/v1"
```
**Gemini 設定の変更**
```bash
# ルーティング前
GOOGLE_GEMINI_BASE_URL=https://generativelanguage.googleapis.com
# ルーティング後
GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:15721
```
### リクエストの転送
ルーティングサービスがリクエストを受信すると:
1. リクエスト元を識別(Claude/Codex/Gemini
2. そのアプリで現在有効なプロバイダーを検索
3. プロバイダーの実際のエンドポイントにリクエストを転送
4. リクエストログを記録
5. アプリにレスポンスを返却
## ルーティングステータスの表示
### メイン画面の表示
ルーティングを有効にすると、メイン画面に以下の変化があります:
- **ルーティング Logo の色**:無色から緑に変化
- **プロバイダーカード**:現在アクティブなプロバイダーに緑の枠が表示
### プロバイダーカードの状態
| 状態 | 枠の色 | 説明 |
|------|----------|------|
| 現在有効 | 青 | 設定ファイル内のプロバイダー(非ルーティングモード) |
| ルーティングアクティブ | 緑 | ルーティングが実際に使用しているプロバイダー |
| 通常 | デフォルト | 使用されていないプロバイダー |
## ルーティングの無効化
### 操作手順
1. ルーティングパネルで対応するアプリのルーティングスイッチをオフにする
2. またはルーティングサービスを直接停止
### 設定の復元
ルーティングを無効にすると、CC Switch は以下を実行します:
1. アプリの設定をルーティング前の状態に復元
2. 現在のリクエストログを保存
## ルーティングとプロバイダーの切り替え
### ルーティングモードでのプロバイダー切り替え
ルーティングモードでプロバイダーを切り替える場合:
1. メイン画面でプロバイダーの「有効化」ボタンをクリック
2. ルーティングサービスが新しいプロバイダーを使用してリクエストを即座に転送
3. **CLI ツールの再起動は不要**
これがルーティングモードの大きなメリットです:プロバイダーの切り替えが即座に反映されます。
### 非ルーティングモードでのプロバイダー切り替え
非ルーティングモードでプロバイダーを切り替える場合:
1. 設定ファイルを変更
2. CLI ツールの再起動が必要
## 複数アプリのルーティング
複数のアプリを同時にルーティングでき、それぞれ独立して管理されます:
- 独立したプロバイダー設定
- 独立したフェイルオーバーキュー
- 独立したリクエスト統計
## 使用シーン
### シーン 1:使用量の監視
ルーティング + ログ記録を有効にして、API の使用状況を監視します。
### シーン 2:素早い切り替え
ルーティングを有効にすると、プロバイダーの切り替えに CLI ツールの再起動が不要になります。
### シーン 3:フェイルオーバー
ルーティングの有効化はフェイルオーバー機能を使用するための前提条件です。
## 注意事項
### パフォーマンスへの影響
ルーティングにより少量のレイテンシ(通常 < 10ms)が追加されますが、ほとんどのシーンでは無視できます。
### ネットワーク要件
ルーティングモードでは、CLI ツールがローカルルーティングアドレスにアクセスできる必要があります。
### 設定のバックアップ
ルーティングを有効にする前に、CC Switch は元の設定をバックアップし、無効化時に復元します。
## よくある質問
### ルーティング後にリクエストが失敗する
確認事項:
- ルーティングサービスが正常に実行されているか
- プロバイダーの設定が正しいか
- ネットワークが正常か
### ルーティングを無効にしても設定が復元されない
考えられる原因:
- ルーティングサービスの異常終了
- 設定ファイルが他のプログラムに変更された
解決方法:
- プロバイダーを手動で編集して保存し直す
- または再度ルーティングを有効にしてから無効にする
+195
View File
@@ -0,0 +1,195 @@
# 4.2 アプリケーション接管
## 機能説明
アプリケーション接管とは、CC Switch のプロキシが特定アプリの API リクエストを接管することです。
接管を有効にすると:
- アプリの API リクエストがローカルプロキシ経由で転送される
- リクエストログと使用量の統計を記録できる
- フェイルオーバー機能を使用できる
## 前提条件
アプリケーション接管機能を使用する前に、プロキシサービスを起動する必要があります。
## 接管の有効化
### 操作場所
設定 → 詳細 → プロキシサービス → アプリケーション接管エリア
### 操作手順
1. プロキシサービスが起動していることを確認
2. 「アプリケーション接管」エリアを見つける
3. 必要なアプリのスイッチをオンにする
### 接管スイッチ
| スイッチ | 作用 |
|------|------|
| Claude 接管 | Claude Code のリクエストを接管 |
| Codex 接管 | Codex のリクエストを接管 |
| Gemini 接管 | Gemini CLI のリクエストを接管 |
複数のアプリの接管を同時に有効にできます。
## 接管の仕組み
### 設定の変更
接管を有効にすると、CC Switch はアプリの設定ファイルを変更し、API エンドポイントをローカルプロキシに向けます。
**Claude 設定の変更**
```json
// 接管前
{
"env": {
"ANTHROPIC_BASE_URL": "https://api.anthropic.com"
}
}
// 接管後
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:15721"
}
}
```
**Codex 設定の変更**
```toml
# 接管前
base_url = "https://api.openai.com/v1"
# 接管後
base_url = "http://127.0.0.1:15721/v1"
```
**Gemini 設定の変更**
```bash
# 接管前
GOOGLE_GEMINI_BASE_URL=https://generativelanguage.googleapis.com
# 接管後
GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:15721
```
### リクエストの転送
プロキシがリクエストを受信すると:
1. リクエスト元を識別(Claude/Codex/Gemini
2. そのアプリで現在有効なプロバイダーを検索
3. プロバイダーの実際のエンドポイントにリクエストを転送
4. リクエストログを記録
5. アプリにレスポンスを返却
## 接管ステータスの表示
### メイン画面の表示
接管を有効にすると、メイン画面に以下の変化があります:
- **プロキシ Logo の色**:無色から緑に変化
- **プロバイダーカード**:現在アクティブなプロバイダーに緑の枠が表示
### プロバイダーカードの状態
| 状態 | 枠の色 | 説明 |
|------|----------|------|
| 現在有効 | 青 | 設定ファイル内のプロバイダー(非プロキシモード) |
| プロキシアクティブ | 緑 | プロキシが実際に使用しているプロバイダー |
| 通常 | デフォルト | 使用されていないプロバイダー |
## 接管の無効化
### 操作手順
1. プロキシパネルで対応するアプリの接管スイッチをオフにする
2. またはプロキシサービスを直接停止
### 設定の復元
接管を無効にすると、CC Switch は以下を実行します:
1. アプリの設定を接管前の状態に復元
2. 現在のリクエストログを保存
## 接管とプロバイダーの切り替え
### 接管モードでのプロバイダー切り替え
接管モードでプロバイダーを切り替える場合:
1. メイン画面でプロバイダーの「有効化」ボタンをクリック
2. プロキシが新しいプロバイダーを使用してリクエストを即座に転送
3. **CLI ツールの再起動は不要**
これが接管モードの大きなメリットです:プロバイダーの切り替えが即座に反映されます。
### 非接管モードでのプロバイダー切り替え
非接管モードでプロバイダーを切り替える場合:
1. 設定ファイルを変更
2. CLI ツールの再起動が必要
## 複数アプリの接管
複数のアプリを同時に接管でき、それぞれ独立して管理されます:
- 独立したプロバイダー設定
- 独立したフェイルオーバーキュー
- 独立したリクエスト統計
## 使用シーン
### シーン 1:使用量の監視
接管 + ログ記録を有効にして、API の使用状況を監視します。
### シーン 2:素早い切り替え
接管を有効にすると、プロバイダーの切り替えに CLI ツールの再起動が不要になります。
### シーン 3:フェイルオーバー
接管の有効化はフェイルオーバー機能を使用するための前提条件です。
## 注意事項
### パフォーマンスへの影響
プロキシにより少量のレイテンシ(通常 < 10ms)が追加されますが、ほとんどのシーンでは無視できます。
### ネットワーク要件
接管モードでは、CLI ツールがローカルプロキシアドレスにアクセスできる必要があります。
### 設定のバックアップ
接管を有効にする前に、CC Switch は元の設定をバックアップし、無効化時に復元します。
## よくある質問
### 接管後にリクエストが失敗する
確認事項:
- プロキシサービスが正常に実行されているか
- プロバイダーの設定が正しいか
- ネットワークが正常か
### 接管を無効にしても設定が復元されない
考えられる原因:
- プロキシの異常終了
- 設定ファイルが他のプログラムに変更された
解決方法:
- プロバイダーを手動で編集して保存し直す
- または接管を再度有効にしてから無効にする
+1 -1
View File
@@ -79,7 +79,7 @@ CC Switch ユーザーマニュアル
| ファイル | 内容 | | ファイル | 内容 |
|------|------| |------|------|
| [4.1-service.md](./4-proxy/4.1-service.md) | プロキシの起動、設定項目、実行状態 | | [4.1-service.md](./4-proxy/4.1-service.md) | プロキシの起動、設定項目、実行状態 |
| [4.2-routing.md](./4-proxy/4.2-routing.md) | アプリケーションルーティング、設定変更、ステータス表示 | | [4.2-takeover.md](./4-proxy/4.2-takeover.md) | アプリケーション接管、設定変更、ステータス表示 |
| [4.3-failover.md](./4-proxy/4.3-failover.md) | フェイルオーバーキュー、サーキットブレーカー、ヘルスステータス | | [4.3-failover.md](./4-proxy/4.3-failover.md) | フェイルオーバーキュー、サーキットブレーカー、ヘルスステータス |
| [4.4-usage.md](./4-proxy/4.4-usage.md) | 使用量統計、トレンドグラフ、料金設定 | | [4.4-usage.md](./4-proxy/4.4-usage.md) | 使用量統計、トレンドグラフ、料金設定 |
| [4.5-model-test.md](./4-proxy/4.5-model-test.md) | モデルテスト、ヘルスチェック、レイテンシテスト | | [4.5-model-test.md](./4-proxy/4.5-model-test.md) | モデルテスト、ヘルスチェック、レイテンシテスト |
-195
View File
@@ -1,195 +0,0 @@
# 4.2 应用路由
## 功能说明
应用路由是指让 CC Switch 路由特定应用的 API 请求。
开启路由后:
- 应用的 API 请求会通过本地路由转发
- 可以记录请求日志和统计用量
- 可以使用故障转移功能
## 前提条件
使用应用路由功能前,需要先启动路由服务。
## 开启路由
### 操作位置
设置 → 高级 → 路由服务 → 应用路由区域
### 操作步骤
1. 确保路由服务已启动
2. 找到「应用路由」区域
3. 为需要的应用开启开关
### 路由开关
| 开关 | 作用 |
|------|------|
| Claude 路由 | 路由 Claude Code 的请求 |
| Codex 路由 | 路由 Codex 的请求 |
| Gemini 路由 | 路由 Gemini CLI 的请求 |
可以同时开启多个应用的路由。
## 路由原理
### 配置修改
开启路由后,CC Switch 会修改应用的配置文件,将 API 端点指向本地路由。
**Claude 配置变更**
```json
// 路由前
{
"env": {
"ANTHROPIC_BASE_URL": "https://api.anthropic.com"
}
}
// 路由后
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:15721"
}
}
```
**Codex 配置变更**
```toml
# 路由前
base_url = "https://api.openai.com/v1"
# 路由后
base_url = "http://127.0.0.1:15721/v1"
```
**Gemini 配置变更**
```bash
# 路由前
GOOGLE_GEMINI_BASE_URL=https://generativelanguage.googleapis.com
# 路由后
GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:15721
```
### 请求转发
路由收到请求后:
1. 识别请求来源(Claude/Codex/Gemini
2. 查找该应用当前启用的供应商
3. 将请求转发到供应商的实际端点
4. 记录请求日志
5. 返回响应给应用
## 路由状态指示
### 主界面指示
开启路由后,主界面会有以下变化:
- **路由 Logo 颜色**:从无色变为绿色
- **供应商卡片**:当前活跃的供应商显示绿色边框
### 供应商卡片状态
| 状态 | 边框颜色 | 说明 |
|------|----------|------|
| 当前启用 | 蓝色 | 配置文件中的供应商(非路由模式) |
| 路由活跃 | 绿色 | 路由实际使用的供应商 |
| 普通 | 默认 | 未使用的供应商 |
## 关闭路由
### 操作步骤
1. 在路由面板中关闭对应应用的路由开关
2. 或直接停止路由服务
### 配置恢复
关闭路由时,CC Switch 会:
1. 将应用配置恢复到路由前的状态
2. 保存当前的请求日志
## 路由与供应商切换
### 路由模式下切换供应商
在路由模式下切换供应商:
1. 在主界面点击供应商的「启用」按钮
2. 路由立即使用新供应商转发请求
3. **无需重启 CLI 工具**
这是路由模式的一大优势:切换供应商即时生效。
### 非路由模式下切换
在非路由模式下切换供应商:
1. 修改配置文件
2. 需要重启 CLI 工具才能生效
## 多应用路由
可以同时路由多个应用,每个应用独立管理:
- 独立的供应商配置
- 独立的故障转移队列
- 独立的请求统计
## 使用场景
### 场景一:用量监控
开启路由 + 日志记录,监控 API 使用情况。
### 场景二:快速切换
开启路由后,切换供应商无需重启 CLI 工具。
### 场景三:故障转移
开启路由是使用故障转移功能的前提。
## 注意事项
### 性能影响
路由会增加少量延迟(通常 < 10ms),对于大多数场景可以忽略。
### 网络要求
路由模式下,CLI 工具需要能够访问本地路由地址。
### 配置备份
开启路由前,CC Switch 会备份原始配置,关闭时恢复。
## 常见问题
### 路由后请求失败
检查:
- 路由服务是否正常运行
- 供应商配置是否正确
- 网络是否正常
### 关闭路由后配置未恢复
可能原因:
- 路由异常退出
- 配置文件被其他程序修改
解决方法:
- 手动编辑供应商,重新保存
- 或重新启用再关闭路由
+195
View File
@@ -0,0 +1,195 @@
# 4.2 应用接管
## 功能说明
应用接管是指让 CC Switch 代理接管特定应用的 API 请求。
开启接管后:
- 应用的 API 请求会通过本地代理转发
- 可以记录请求日志和统计用量
- 可以使用故障转移功能
## 前提条件
使用应用接管功能前,需要先启动代理服务。
## 开启接管
### 操作位置
设置 → 高级 → 代理服务 → 应用接管区域
### 操作步骤
1. 确保代理服务已启动
2. 找到「应用接管」区域
3. 为需要的应用开启开关
### 接管开关
| 开关 | 作用 |
|------|------|
| Claude 接管 | 接管 Claude Code 的请求 |
| Codex 接管 | 接管 Codex 的请求 |
| Gemini 接管 | 接管 Gemini CLI 的请求 |
可以同时开启多个应用的接管。
## 接管原理
### 配置修改
开启接管后,CC Switch 会修改应用的配置文件,将 API 端点指向本地代理。
**Claude 配置变更**
```json
// 接管前
{
"env": {
"ANTHROPIC_BASE_URL": "https://api.anthropic.com"
}
}
// 接管后
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:15721"
}
}
```
**Codex 配置变更**
```toml
# 接管前
base_url = "https://api.openai.com/v1"
# 接管后
base_url = "http://127.0.0.1:15721/v1"
```
**Gemini 配置变更**
```bash
# 接管前
GOOGLE_GEMINI_BASE_URL=https://generativelanguage.googleapis.com
# 接管后
GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:15721
```
### 请求转发
代理收到请求后:
1. 识别请求来源(Claude/Codex/Gemini
2. 查找该应用当前启用的供应商
3. 将请求转发到供应商的实际端点
4. 记录请求日志
5. 返回响应给应用
## 接管状态指示
### 主界面指示
开启接管后,主界面会有以下变化:
- **代理 Logo 颜色**:从无色变为绿色
- **供应商卡片**:当前活跃的供应商显示绿色边框
### 供应商卡片状态
| 状态 | 边框颜色 | 说明 |
|------|----------|------|
| 当前启用 | 蓝色 | 配置文件中的供应商(非代理模式) |
| 代理活跃 | 绿色 | 代理实际使用的供应商 |
| 普通 | 默认 | 未使用的供应商 |
## 关闭接管
### 操作步骤
1. 在代理面板中关闭对应应用的接管开关
2. 或直接停止代理服务
### 配置恢复
关闭接管时,CC Switch 会:
1. 将应用配置恢复到接管前的状态
2. 保存当前的请求日志
## 接管与供应商切换
### 接管模式下切换供应商
在接管模式下切换供应商:
1. 在主界面点击供应商的「启用」按钮
2. 代理立即使用新供应商转发请求
3. **无需重启 CLI 工具**
这是接管模式的一大优势:切换供应商即时生效。
### 非接管模式下切换
在非接管模式下切换供应商:
1. 修改配置文件
2. 需要重启 CLI 工具才能生效
## 多应用接管
可以同时接管多个应用,每个应用独立管理:
- 独立的供应商配置
- 独立的故障转移队列
- 独立的请求统计
## 使用场景
### 场景一:用量监控
开启接管 + 日志记录,监控 API 使用情况。
### 场景二:快速切换
开启接管后,切换供应商无需重启 CLI 工具。
### 场景三:故障转移
开启接管是使用故障转移功能的前提。
## 注意事项
### 性能影响
代理会增加少量延迟(通常 < 10ms),对于大多数场景可以忽略。
### 网络要求
接管模式下,CLI 工具需要能够访问本地代理地址。
### 配置备份
开启接管前,CC Switch 会备份原始配置,关闭时恢复。
## 常见问题
### 接管后请求失败
检查:
- 代理服务是否正常运行
- 供应商配置是否正确
- 网络是否正常
### 关闭接管后配置未恢复
可能原因:
- 代理异常退出
- 配置文件被其他程序修改
解决方法:
- 手动编辑供应商,重新保存
- 或重新启用再关闭接管
+1 -1
View File
@@ -79,7 +79,7 @@
| 文件 | 内容 | | 文件 | 内容 |
|------|------| |------|------|
| [4.1-service.md](./4-proxy/4.1-service.md) | 启动代理、配置项、运行状态 | | [4.1-service.md](./4-proxy/4.1-service.md) | 启动代理、配置项、运行状态 |
| [4.2-routing.md](./4-proxy/4.2-routing.md) | 应用路由、配置修改、状态指示 | | [4.2-takeover.md](./4-proxy/4.2-takeover.md) | 应用接管、配置修改、状态指示 |
| [4.3-failover.md](./4-proxy/4.3-failover.md) | 故障转移队列、熔断器、健康状态 | | [4.3-failover.md](./4-proxy/4.3-failover.md) | 故障转移队列、熔断器、健康状态 |
| [4.4-usage.md](./4-proxy/4.4-usage.md) | 用量统计、趋势图表、定价配置 | | [4.4-usage.md](./4-proxy/4.4-usage.md) | 用量统计、趋势图表、定价配置 |
| [4.5-model-test.md](./4-proxy/4.5-model-test.md) | 模型检查、健康检测、延迟测试 | | [4.5-model-test.md](./4-proxy/4.5-model-test.md) | 模型检查、健康检测、延迟测试 |
-1
View File
@@ -67,7 +67,6 @@
"@radix-ui/react-tooltip": "^1.2.8", "@radix-ui/react-tooltip": "^1.2.8",
"@radix-ui/react-visually-hidden": "^1.2.4", "@radix-ui/react-visually-hidden": "^1.2.4",
"@tanstack/react-query": "^5.90.3", "@tanstack/react-query": "^5.90.3",
"@tanstack/react-virtual": "^3.13.23",
"@tauri-apps/api": "^2.8.0", "@tauri-apps/api": "^2.8.0",
"@tauri-apps/plugin-dialog": "^2.4.0", "@tauri-apps/plugin-dialog": "^2.4.0",
"@tauri-apps/plugin-process": "^2.0.0", "@tauri-apps/plugin-process": "^2.0.0",
-20
View File
@@ -89,9 +89,6 @@ importers:
'@tanstack/react-query': '@tanstack/react-query':
specifier: ^5.90.3 specifier: ^5.90.3
version: 5.90.3(react@18.3.1) version: 5.90.3(react@18.3.1)
'@tanstack/react-virtual':
specifier: ^3.13.23
version: 3.13.23(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
'@tauri-apps/api': '@tauri-apps/api':
specifier: ^2.8.0 specifier: ^2.8.0
version: 2.8.0 version: 2.8.0
@@ -1471,15 +1468,6 @@ packages:
peerDependencies: peerDependencies:
react: ^18 || ^19 react: ^18 || ^19
'@tanstack/react-virtual@3.13.23':
resolution: {integrity: sha512-XnMRnHQ23piOVj2bzJqHrRrLg4r+F86fuBcwteKfbIjJrtGxb4z7tIvPVAe4B+4UVwo9G4Giuz5fmapcrnZ0OQ==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
'@tanstack/virtual-core@3.13.23':
resolution: {integrity: sha512-zSz2Z2HNyLjCplANTDyl3BcdQJc2k1+yyFoKhNRmCr7V7dY8o8q5m8uFTI1/Pg1kL+Hgrz6u3Xo6eFUB7l66cg==}
'@tauri-apps/api@2.8.0': '@tauri-apps/api@2.8.0':
resolution: {integrity: sha512-ga7zdhbS2GXOMTIZRT0mYjKJtR9fivsXzsyq5U3vjDL0s6DTMwYRm0UHNjzTY5dh4+LSC68Sm/7WEiimbQNYlw==} resolution: {integrity: sha512-ga7zdhbS2GXOMTIZRT0mYjKJtR9fivsXzsyq5U3vjDL0s6DTMwYRm0UHNjzTY5dh4+LSC68Sm/7WEiimbQNYlw==}
@@ -4287,14 +4275,6 @@ snapshots:
'@tanstack/query-core': 5.90.3 '@tanstack/query-core': 5.90.3
react: 18.3.1 react: 18.3.1
'@tanstack/react-virtual@3.13.23(react-dom@18.3.1(react@18.3.1))(react@18.3.1)':
dependencies:
'@tanstack/virtual-core': 3.13.23
react: 18.3.1
react-dom: 18.3.1(react@18.3.1)
'@tanstack/virtual-core@3.13.23': {}
'@tauri-apps/api@2.8.0': {} '@tauri-apps/api@2.8.0': {}
'@tauri-apps/cli-darwin-arm64@2.8.1': '@tauri-apps/cli-darwin-arm64@2.8.1':
-5
View File
@@ -11,11 +11,6 @@
"updater:default", "updater:default",
"core:window:allow-set-skip-taskbar", "core:window:allow-set-skip-taskbar",
"core:window:allow-start-dragging", "core:window:allow-start-dragging",
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-is-maximized",
"core:window:allow-close",
"core:window:allow-set-decorations",
"process:allow-restart", "process:allow-restart",
"dialog:default" "dialog:default"
] ]
-13
View File
@@ -253,19 +253,6 @@ pub async fn switch_proxy_provider(
app_type: String, app_type: String,
provider_id: String, provider_id: String,
) -> Result<(), String> { ) -> Result<(), String> {
// Block official providers during proxy takeover
let provider = state
.db
.get_provider_by_id(&provider_id, &app_type)
.map_err(|e| format!("读取供应商失败: {e}"))?
.ok_or_else(|| format!("供应商不存在: {provider_id}"))?;
if provider.category.as_deref() == Some("official") {
return Err(
"代理接管模式下不能切换到官方供应商 (Cannot switch to official provider during proxy takeover)"
.to_string(),
);
}
state state
.proxy_service .proxy_service
.switch_proxy_target(&app_type, &provider_id) .switch_proxy_target(&app_type, &provider_id)
+3 -12
View File
@@ -116,24 +116,15 @@ pub async fn stream_check_all_providers(
claude_api_format_override, claude_api_format_override,
) )
.await .await
.unwrap_or_else(|e| { .unwrap_or_else(|e| StreamCheckResult {
let (http_status, message) = match &e {
crate::error::AppError::HttpStatus { status, .. } => (
Some(*status),
StreamCheckService::classify_http_status(*status).to_string(),
),
_ => (None, e.to_string()),
};
StreamCheckResult {
status: HealthStatus::Failed, status: HealthStatus::Failed,
success: false, success: false,
message, message: e.to_string(),
response_time_ms: None, response_time_ms: None,
http_status, http_status: None,
model_used: String::new(), model_used: String::new(),
tested_at: chrono::Utc::now().timestamp(), tested_at: chrono::Utc::now().timestamp(),
retry_count: 0, retry_count: 0,
}
}); });
let _ = state let _ = state
+2 -10
View File
@@ -35,26 +35,18 @@ pub fn get_usage_trends(
#[tauri::command] #[tauri::command]
pub fn get_provider_stats( pub fn get_provider_stats(
state: State<'_, AppState>, state: State<'_, AppState>,
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<String>, app_type: Option<String>,
) -> Result<Vec<ProviderStats>, AppError> { ) -> Result<Vec<ProviderStats>, AppError> {
state state.db.get_provider_stats(app_type.as_deref())
.db
.get_provider_stats(start_date, end_date, app_type.as_deref())
} }
/// 获取模型统计 /// 获取模型统计
#[tauri::command] #[tauri::command]
pub fn get_model_stats( pub fn get_model_stats(
state: State<'_, AppState>, state: State<'_, AppState>,
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<String>, app_type: Option<String>,
) -> Result<Vec<ModelStats>, AppError> { ) -> Result<Vec<ModelStats>, AppError> {
state state.db.get_model_stats(app_type.as_deref())
.db
.get_model_stats(start_date, end_date, app_type.as_deref())
} }
/// 获取请求日志列表 /// 获取请求日志列表
+1 -1
View File
@@ -44,7 +44,7 @@ use std::sync::Mutex;
/// 当前 Schema 版本号 /// 当前 Schema 版本号
/// 每次修改表结构时递增,并在 schema.rs 中添加相应的迁移逻辑 /// 每次修改表结构时递增,并在 schema.rs 中添加相应的迁移逻辑
pub(crate) const SCHEMA_VERSION: i32 = 9; pub(crate) const SCHEMA_VERSION: i32 = 8;
/// 安全地序列化 JSON,避免 unwrap panic /// 安全地序列化 JSON,避免 unwrap panic
pub(crate) fn to_json_string<T: Serialize>(value: &T) -> Result<String, AppError> { pub(crate) fn to_json_string<T: Serialize>(value: &T) -> Result<String, AppError> {
+14 -246
View File
@@ -418,11 +418,6 @@ impl Database {
Self::migrate_v7_to_v8(conn)?; Self::migrate_v7_to_v8(conn)?;
Self::set_user_version(conn, 8)?; Self::set_user_version(conn, 8)?;
} }
8 => {
log::info!("迁移数据库从 v8 到 v9(全面补充模型定价)");
Self::migrate_v8_to_v9(conn)?;
Self::set_user_version(conn, 9)?;
}
_ => { _ => {
return Err(AppError::Database(format!( return Err(AppError::Database(format!(
"未知的数据库版本 {version},无法迁移到 {SCHEMA_VERSION}" "未知的数据库版本 {version},无法迁移到 {SCHEMA_VERSION}"
@@ -1149,25 +1144,6 @@ impl Database {
Ok(()) Ok(())
} }
/// v8 → v9: 全面补充模型定价(清空 + 重新 seed)
fn migrate_v8_to_v9(conn: &Connection) -> Result<(), AppError> {
conn.execute(
"CREATE TABLE IF NOT EXISTS model_pricing (
model_id TEXT PRIMARY KEY, display_name TEXT NOT NULL,
input_cost_per_million TEXT NOT NULL, output_cost_per_million TEXT NOT NULL,
cache_read_cost_per_million TEXT NOT NULL DEFAULT '0',
cache_creation_cost_per_million TEXT NOT NULL DEFAULT '0'
)",
[],
)
.map_err(|e| AppError::Database(format!("创建 model_pricing 表失败: {e}")))?;
conn.execute("DELETE FROM model_pricing", [])
.map_err(|e| AppError::Database(format!("清空模型定价失败: {e}")))?;
Self::seed_model_pricing(conn)?;
log::info!("v8 -> v9 迁移完成:已刷新全部模型定价数据");
Ok(())
}
/// 插入默认模型定价数据 /// 插入默认模型定价数据
/// 格式: (model_id, display_name, input, output, cache_read, cache_creation) /// 格式: (model_id, display_name, input, output, cache_read, cache_creation)
/// 注意: model_id 使用短横线格式(如 claude-haiku-4-5),与 API 返回的模型名称标准化后一致 /// 注意: model_id 使用短横线格式(如 claude-haiku-4-5),与 API 返回的模型名称标准化后一致
@@ -1515,38 +1491,6 @@ impl Database {
"0.02", "0.02",
"0", "0",
), ),
(
"doubao-seed-2-0-pro",
"Doubao Seed 2.0 Pro",
"0.47",
"2.37",
"0",
"0",
),
(
"doubao-seed-2-0-code",
"Doubao Seed 2.0 Code",
"0.47",
"2.37",
"0",
"0",
),
(
"doubao-seed-2-0-lite",
"Doubao Seed 2.0 Lite",
"0.25",
"2",
"0",
"0",
),
(
"doubao-seed-2-0-mini",
"Doubao Seed 2.0 Mini",
"0.03",
"0.31",
"0",
"0",
),
// DeepSeek 系列 // DeepSeek 系列
( (
"deepseek-v3.2", "deepseek-v3.2",
@@ -1568,17 +1512,17 @@ impl Database {
( (
"deepseek-chat", "deepseek-chat",
"DeepSeek Chat", "DeepSeek Chat",
"0.27", "0.28",
"1.10", "0.42",
"0.07", "0.028",
"0", "0",
), ),
( (
"deepseek-reasoner", "deepseek-reasoner",
"DeepSeek Reasoner", "DeepSeek Reasoner",
"0.55", "0.28",
"2.19", "0.42",
"0.14", "0.028",
"0", "0",
), ),
// Kimi (月之暗面) // Kimi (月之暗面)
@@ -1599,7 +1543,7 @@ impl Database {
"0.14", "0.14",
"0", "0",
), ),
("kimi-k2.5", "Kimi K2.5", "0.60", "2.50", "0.10", "0"), ("kimi-k2.5", "Kimi K2.5", "0.60", "3.00", "0.10", "0"),
// MiniMax 系列 // MiniMax 系列
("minimax-m2.1", "MiniMax M2.1", "0.27", "0.95", "0.03", "0"), ("minimax-m2.1", "MiniMax M2.1", "0.27", "0.95", "0.03", "0"),
( (
@@ -1611,211 +1555,35 @@ impl Database {
"0", "0",
), ),
("minimax-m2", "MiniMax M2", "0.27", "0.95", "0.03", "0"), ("minimax-m2", "MiniMax M2", "0.27", "0.95", "0.03", "0"),
("minimax-m2.5", "MiniMax M2.5", "0.12", "0.95", "0.03", "0"),
(
"minimax-m2.5-lightning",
"MiniMax M2.5 Lightning",
"0.30",
"2.40",
"0.03",
"0",
),
(
"minimax-m2.7",
"MiniMax M2.7",
"0.30",
"1.20",
"0.06",
"0.375",
),
(
"minimax-m2.7-highspeed",
"MiniMax M2.7 Highspeed",
"0.60",
"2.40",
"0.06",
"0.375",
),
// GLM (智谱) // GLM (智谱)
("glm-4.7", "GLM-4.7", "0.39", "1.75", "0.04", "0"), ("glm-4.7", "GLM-4.7", "0.39", "1.75", "0.04", "0"),
("glm-4.6", "GLM-4.6", "0.28", "1.11", "0.03", "0"), ("glm-4.6", "GLM-4.6", "0.28", "1.11", "0.03", "0"),
("glm-5", "GLM-5", "0.72", "2.30", "0", "0"), // Mimo (小米)
("glm-5.1", "GLM-5.1", "0.95", "3.15", "0", "0"),
// MiMo (小米)
( (
"mimo-v2-flash", "mimo-v2-flash",
"MiMo V2 Flash", "Mimo V2 Flash",
"0.09", "0.09",
"0.29", "0.29",
"0.009", "0.009",
"0", "0",
), ),
("mimo-v2-pro", "MiMo V2 Pro", "1", "3", "0", "0"),
// Qwen 系列 (阿里巴巴)
("qwen3.6-plus", "Qwen3.6 Plus", "0.325", "1.95", "0", "0"),
("qwen3.5-plus", "Qwen3.5 Plus", "0.26", "1.56", "0", "0"),
("qwen3-max", "Qwen3 Max", "0.78", "3.90", "0", "0"),
(
"qwen3-235b-a22b",
"Qwen3 235B-A22B",
"0.70",
"8.40",
"0",
"0",
),
(
"qwen3-coder-plus",
"Qwen3 Coder Plus",
"0.65",
"3.25",
"0",
"0",
),
(
"qwen3-coder-flash",
"Qwen3 Coder Flash",
"0.195",
"0.975",
"0",
"0",
),
(
"qwen3-coder-next",
"Qwen3 Coder Next",
"0.12",
"0.75",
"0",
"0",
),
("qwq-plus", "QwQ Plus", "0.80", "2.40", "0", "0"),
("qwq-32b", "QwQ 32B", "0.20", "0.60", "0", "0"),
("qwen3-32b", "Qwen3 32B", "0.16", "0.64", "0", "0"),
// Grok 系列 (xAI)
(
"grok-4.20-0309-reasoning",
"Grok 4.20 Reasoning",
"2",
"6",
"0.20",
"0",
),
(
"grok-4.20-0309-non-reasoning",
"Grok 4.20",
"2",
"6",
"0.20",
"0",
),
(
"grok-4-1-fast-reasoning",
"Grok 4.1 Fast Reasoning",
"0.20",
"0.50",
"0.05",
"0",
),
(
"grok-4-1-fast-non-reasoning",
"Grok 4.1 Fast",
"0.20",
"0.50",
"0.05",
"0",
),
("grok-4", "Grok 4", "3", "15", "0.75", "0"),
(
"grok-code-fast-1",
"Grok Code Fast",
"0.20",
"1.50",
"0.02",
"0",
),
("grok-3", "Grok 3", "3", "15", "0.75", "0"),
("grok-3-mini", "Grok 3 Mini", "0.25", "0.50", "0.075", "0"),
// Mistral 系列
("codestral-2508", "Codestral", "0.30", "0.90", "0.03", "0"),
(
"devstral-small-1.1",
"Devstral Small 1.1",
"0.07",
"0.28",
"0.01",
"0",
),
("devstral-2-2512", "Devstral 2", "0.40", "0.90", "0.04", "0"),
(
"devstral-medium",
"Devstral Medium",
"0.40",
"2",
"0.04",
"0",
),
(
"mistral-large-3-2512",
"Mistral Large 3",
"0.50",
"1.50",
"0.05",
"0",
),
(
"mistral-medium-3.1",
"Mistral Medium 3.1",
"0.40",
"2",
"0.04",
"0",
),
(
"mistral-small-3.2-24b",
"Mistral Small 3.2",
"0.075",
"0.20",
"0.01",
"0",
),
("magistral-medium", "Magistral Medium", "2", "5", "0", "0"),
// Cohere 系列
("command-a", "Cohere Command A", "2.50", "10", "0", "0"),
(
"command-r-plus",
"Cohere Command R+",
"2.50",
"10",
"0",
"0",
),
("command-r", "Cohere Command R", "0.15", "0.60", "0", "0"),
// OpenAI 补充
("o3-pro", "OpenAI o3-pro", "20", "80", "0", "0"),
("o3-mini", "OpenAI o3-mini", "0.55", "2.20", "0.55", "0"),
("o1", "OpenAI o1", "15", "60", "7.50", "0"),
("o1-mini", "OpenAI o1-mini", "0.55", "2.20", "0.55", "0"),
("codex-mini", "Codex Mini", "0.75", "3", "0.025", "0"),
("gpt-5-mini", "GPT-5 Mini", "0.25", "2", "0.025", "0"),
("gpt-5-nano", "GPT-5 Nano", "0.05", "0.40", "0.005", "0"),
]; ];
let mut stmt = conn for (model_id, display_name, input, output, cache_read, cache_creation) in pricing_data {
.prepare( conn.execute(
"INSERT OR IGNORE INTO model_pricing ( "INSERT OR IGNORE INTO model_pricing (
model_id, display_name, input_cost_per_million, output_cost_per_million, model_id, display_name, input_cost_per_million, output_cost_per_million,
cache_read_cost_per_million, cache_creation_cost_per_million cache_read_cost_per_million, cache_creation_cost_per_million
) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", ) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
) rusqlite::params![
.map_err(|e| AppError::Database(format!("准备模型定价语句失败: {e}")))?;
for (model_id, display_name, input, output, cache_read, cache_creation) in pricing_data {
stmt.execute(rusqlite::params![
model_id, model_id,
display_name, display_name,
input, input,
output, output,
cache_read, cache_read,
cache_creation cache_creation
]) ],
)
.map_err(|e| AppError::Database(format!("插入模型定价失败: {e}")))?; .map_err(|e| AppError::Database(format!("插入模型定价失败: {e}")))?;
} }
-2
View File
@@ -44,8 +44,6 @@ pub enum AppError {
McpValidation(String), McpValidation(String),
#[error("{0}")] #[error("{0}")]
Message(String), Message(String),
#[error("HTTP {status}: {body}")]
HttpStatus { status: u16, body: String },
#[error("{zh} ({en})")] #[error("{zh} ({en})")]
Localized { Localized {
key: &'static str, key: &'static str,
-4
View File
@@ -971,10 +971,6 @@ pub fn run() {
// 静默启动:根据设置决定是否显示主窗口 // 静默启动:根据设置决定是否显示主窗口
let settings = crate::settings::get_settings(); let settings = crate::settings::get_settings();
if let Some(window) = app.get_webview_window("main") { if let Some(window) = app.get_webview_window("main") {
// 在窗口首次显示前同步装饰状态,避免前端加载后再切换导致标题栏闪烁
// 仅 Linux 生效:解决 Wayland 下系统窗口按钮不可用的问题
#[cfg(target_os = "linux")]
let _ = window.set_decorations(!settings.use_app_window_controls);
if settings.silent_startup { if settings.silent_startup {
// 静默启动模式:保持窗口隐藏 // 静默启动模式:保持窗口隐藏
let _ = window.hide(); let _ = window.hide();
+1 -6
View File
@@ -61,12 +61,7 @@ pub fn read_opencode_config() -> Result<Value, AppError> {
} }
let content = std::fs::read_to_string(&path).map_err(|e| AppError::io(&path, e))?; let content = std::fs::read_to_string(&path).map_err(|e| AppError::io(&path, e))?;
json5::from_str(&content).map_err(|e| { serde_json::from_str(&content).map_err(|e| AppError::json(&path, e))
AppError::Config(format!(
"Failed to parse OpenCode config: {}: {e}",
path.display()
))
})
} }
pub fn write_opencode_config(config: &Value) -> Result<(), AppError> { pub fn write_opencode_config(config: &Value) -> Result<(), AppError> {
+29 -3
View File
@@ -172,6 +172,29 @@ pub struct ProviderTestConfig {
pub max_retries: Option<u32>, pub max_retries: Option<u32>,
} }
/// 供应商单独的代理配置
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProviderProxyConfig {
/// 是否启用单独配置(false 时使用全局/系统代理)
#[serde(default)]
pub enabled: bool,
/// 代理类型:http, https, socks5
#[serde(rename = "proxyType", skip_serializing_if = "Option::is_none")]
pub proxy_type: Option<String>,
/// 代理主机
#[serde(rename = "proxyHost", skip_serializing_if = "Option::is_none")]
pub proxy_host: Option<String>,
/// 代理端口
#[serde(rename = "proxyPort", skip_serializing_if = "Option::is_none")]
pub proxy_port: Option<u16>,
/// 代理用户名(可选)
#[serde(rename = "proxyUsername", skip_serializing_if = "Option::is_none")]
pub proxy_username: Option<String>,
/// 代理密码(可选)
#[serde(rename = "proxyPassword", skip_serializing_if = "Option::is_none")]
pub proxy_password: Option<String>,
}
/// 认证绑定来源 /// 认证绑定来源
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
@@ -239,6 +262,9 @@ pub struct ProviderMeta {
/// 供应商单独的模型测试配置 /// 供应商单独的模型测试配置
#[serde(rename = "testConfig", skip_serializing_if = "Option::is_none")] #[serde(rename = "testConfig", skip_serializing_if = "Option::is_none")]
pub test_config: Option<ProviderTestConfig>, pub test_config: Option<ProviderTestConfig>,
/// 供应商单独的代理配置
#[serde(rename = "proxyConfig", skip_serializing_if = "Option::is_none")]
pub proxy_config: Option<ProviderProxyConfig>,
/// Claude API 格式(仅 Claude 供应商使用) /// Claude API 格式(仅 Claude 供应商使用)
/// - "anthropic": 原生 Anthropic Messages API,直接透传 /// - "anthropic": 原生 Anthropic Messages API,直接透传
/// - "openai_chat": OpenAI Chat Completions 格式,需要转换 /// - "openai_chat": OpenAI Chat Completions 格式,需要转换
@@ -256,9 +282,9 @@ pub struct ProviderMeta {
/// 是否将 base_url 视为完整 API 端点(不拼接 endpoint 路径) /// 是否将 base_url 视为完整 API 端点(不拼接 endpoint 路径)
#[serde(rename = "isFullUrl", skip_serializing_if = "Option::is_none")] #[serde(rename = "isFullUrl", skip_serializing_if = "Option::is_none")]
pub is_full_url: Option<bool>, pub is_full_url: Option<bool>,
/// Prompt cache key for OpenAI Responses-compatible endpoints. /// Prompt cache key for OpenAI-compatible endpoints.
/// When set, injected into converted Responses requests to improve cache hit rate. /// When set, injected into converted requests to improve cache hit rate.
/// If not set, provider ID is used automatically during Claude -> Responses conversion. /// If not set, provider ID is used automatically during format conversion.
#[serde(rename = "promptCacheKey", skip_serializing_if = "Option::is_none")] #[serde(rename = "promptCacheKey", skip_serializing_if = "Option::is_none")]
pub prompt_cache_key: Option<String>, pub prompt_cache_key: Option<String>,
/// 累加模式应用中,该 provider 是否已写入 live config。 /// 累加模式应用中,该 provider 是否已写入 live config。
+40 -513
View File
@@ -8,8 +8,6 @@
//! //!
//! 参考实现: https://github.com/caozhiyuan/copilot-api //! 参考实现: https://github.com/caozhiyuan/copilot-api
use std::collections::HashSet;
use serde_json::Value; use serde_json::Value;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use uuid::Uuid; use uuid::Uuid;
@@ -23,9 +21,6 @@ pub struct CopilotClassification {
pub is_warmup: bool, pub is_warmup: bool,
/// 是否为上下文压缩请求 /// 是否为上下文压缩请求
pub is_compact: bool, pub is_compact: bool,
/// 是否为 Claude Code 子代理请求(Agent tool 生成的 subagent
/// 子代理请求应设置 x-interaction-type=conversation-subagent,不计 premium interaction
pub is_subagent: bool,
} }
/// 分类 Anthropic 格式的请求体,决定 Copilot 请求头。 /// 分类 Anthropic 格式的请求体,决定 Copilot 请求头。
@@ -43,17 +38,12 @@ pub struct CopilotClassification {
/// ///
/// `compact_detection`:是否启用 compact 检测。为 false 时跳过, /// `compact_detection`:是否启用 compact 检测。为 false 时跳过,
/// 确保 `CopilotOptimizerConfig.compact_detection` 开关真正生效。 /// 确保 `CopilotOptimizerConfig.compact_detection` 开关真正生效。
///
/// `subagent_detection`:是否启用子代理检测。为 true 时,会扫描首条用户消息
/// 中的 `__SUBAGENT_MARKER__` 标记,将子代理请求标记为不计费。
pub fn classify_request( pub fn classify_request(
body: &Value, body: &Value,
has_anthropic_beta: bool, has_anthropic_beta: bool,
compact_detection: bool, compact_detection: bool,
subagent_detection: bool,
) -> CopilotClassification { ) -> CopilotClassification {
let is_compact = compact_detection && is_compact_request(body); let is_compact = compact_detection && is_compact_request(body);
let is_subagent = subagent_detection && detect_subagent(body);
let messages = match body.get("messages").and_then(|m| m.as_array()) { let messages = match body.get("messages").and_then(|m| m.as_array()) {
Some(msgs) if !msgs.is_empty() => msgs, Some(msgs) if !msgs.is_empty() => msgs,
@@ -62,7 +52,6 @@ pub fn classify_request(
initiator: "user", initiator: "user",
is_warmup: is_warmup_request(body, has_anthropic_beta, false), is_warmup: is_warmup_request(body, has_anthropic_beta, false),
is_compact: false, is_compact: false,
is_subagent,
} }
} }
}; };
@@ -73,33 +62,29 @@ pub fn classify_request(
// 只有 role=user 的消息需要细分 // 只有 role=user 的消息需要细分
if role != "user" { if role != "user" {
return CopilotClassification { return CopilotClassification {
initiator: if is_subagent { "agent" } else { "user" }, initiator: "user",
is_warmup: false, is_warmup: false,
is_compact, is_compact,
is_subagent,
}; };
} }
// 判定逻辑(与 copilot-api 的 merge-then-classify 效果对齐): // 参考实现的判定逻辑(Messages API 路径):
// 只要 content 数组中包含 tool_result → 视为工具续写 → agent // 如果 content 数组,检查是否有非 tool_result 的 block
// 这覆盖了 skill/edit hook/plan follow-up 等常见场景, // 有 → "user",全是 tool_result → "agent"
// 它们的 content 通常是 [tool_result, text] 混合形态。 // 如果 content 是字符串 → "user"
// copilot-api 通过先 mergetext 吸收进 tool_result)再 classify 实现同等效果;
// 直接在分类层处理更稳健,不依赖 merge 启用状态和执行顺序。
let is_user_initiated = match last_msg.get("content") { let is_user_initiated = match last_msg.get("content") {
Some(content) if content.is_array() => { Some(content) if content.is_array() => {
let blocks = content.as_array().unwrap(); let blocks = content.as_array().unwrap();
// 含有 tool_result → 工具续写(agent),否则 → 用户发起user // 存在非 tool_result block → 用户发起
!blocks blocks
.iter() .iter()
.any(|block| block.get("type").and_then(|t| t.as_str()) == Some("tool_result")) .any(|block| block.get("type").and_then(|t| t.as_str()) != Some("tool_result"))
} }
Some(content) if content.is_string() => true, Some(content) if content.is_string() => true,
_ => false, _ => false,
}; };
// 子代理请求始终标记为 agent(即使首条消息包含用户文本) let initiator = if !is_user_initiated || is_compact {
let initiator = if is_subagent || !is_user_initiated || is_compact {
"agent" "agent"
} else { } else {
"user" "user"
@@ -109,7 +94,6 @@ pub fn classify_request(
initiator, initiator,
is_warmup: initiator == "user" && is_warmup_request(body, has_anthropic_beta, is_compact), is_warmup: initiator == "user" && is_warmup_request(body, has_anthropic_beta, is_compact),
is_compact, is_compact,
is_subagent,
} }
} }
@@ -139,12 +123,24 @@ fn is_warmup_request(body: &Value, has_anthropic_beta: bool, is_compact: bool) -
fn is_compact_request(body: &Value) -> bool { fn is_compact_request(body: &Value) -> bool {
// 信号 1: system prompt 以 Claude Code compact 专用前缀开头 // 信号 1: system prompt 以 Claude Code compact 专用前缀开头
// 用户在 Claude Code 中无法直接控制 system prompt,这是最可靠的信号 // 用户在 Claude Code 中无法直接控制 system prompt,这是最可靠的信号
let system_text = extract_system_text(body); if let Some(system) = body.get("system") {
let system_text = if let Some(s) = system.as_str() {
s.to_string()
} else if let Some(arr) = system.as_array() {
arr.iter()
.filter_map(|b| b.get("text").and_then(|t| t.as_str()))
.collect::<Vec<_>>()
.join(" ")
} else {
String::new()
};
if system_text if system_text
.starts_with("You are a helpful AI assistant tasked with summarizing conversations") .starts_with("You are a helpful AI assistant tasked with summarizing conversations")
{ {
return true; return true;
} }
}
// 信号 2 & 3: 检查最后一条用户消息中的机器生成特征 // 信号 2 & 3: 检查最后一条用户消息中的机器生成特征
let messages = match body.get("messages").and_then(|m| m.as_array()) { let messages = match body.get("messages").and_then(|m| m.as_array()) {
@@ -263,9 +259,8 @@ pub fn merge_tool_results(mut body: Value) -> Value {
/// 基于最后一条用户消息内容生成确定性 Request ID。 /// 基于最后一条用户消息内容生成确定性 Request ID。
/// ///
/// CC Switch 额外策略(参考项目 copilot-api 使用随机 UUID /// 与参考实现对齐
/// - 哈希输入: sessionId + lastUserContent(排除 tool_result 和 cache_control /// - 哈希输入: sessionId + lastUserContent(排除 tool_result 和 cache_control
/// - 相同内容产生相同 ID,可能帮助 Copilot 去重
/// - 找不到用户内容时退化为随机 UUID /// - 找不到用户内容时退化为随机 UUID
/// - 使用 UUID v4 格式 /// - 使用 UUID v4 格式
pub fn deterministic_request_id(body: &Value, session_id: &str) -> String { pub fn deterministic_request_id(body: &Value, session_id: &str) -> String {
@@ -290,176 +285,8 @@ pub fn deterministic_request_id(body: &Value, session_id: &str) -> String {
} }
} }
/// 基于 session ID 生成稳定的 Interaction ID。
///
/// 与参考实现(copilot-api session.ts)对齐:
/// - 同一主对话的所有请求共享同一个 interaction ID
/// - 哈希输入: 仅 session ID(不包含消息内容,与 request ID 不同)
/// - Copilot 用此 ID 将请求聚合为同一个 "interaction",影响 premium 计费归属
/// - 空 session ID 时返回 None(不应注入随机值,避免 interaction 碎片化)
pub fn deterministic_interaction_id(session_id: &str) -> Option<String> {
if session_id.is_empty() {
return None;
}
let mut hasher = Sha256::new();
hasher.update(b"interaction:");
hasher.update(session_id.as_bytes());
let result = hasher.finalize();
let mut bytes = [0u8; 16];
bytes.copy_from_slice(&result[..16]);
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1
Some(Uuid::from_bytes(bytes).to_string())
}
/// 检测请求是否来自 Claude Code 子代理(Agent tool 生成的 subagent)。
///
/// Claude Code 的 Agent tool 会在子代理首条用户消息的 `<system-reminder>` 标签中
/// 注入 `__SUBAGENT_MARKER__` JSON 标记,格式如:
/// ```json
/// {"__SUBAGENT_MARKER__": {"session_id": "...", "agent_id": "...", "agent_type": "..."}}
/// ```
///
/// 扫描策略(与 copilot-api 的 subagent-marker.ts 对齐):
/// 1. 遍历所有 user 消息(不仅是第一条,因为 context 压缩可能重排消息)
/// 2. 在消息文本中查找 `__SUBAGENT_MARKER__` 关键字
/// 3. 找到即判定为子代理请求
fn detect_subagent(body: &Value) -> bool {
// 信号 1: 显式 __SUBAGENT_MARKER__Claude Code 2.x+ 自动注入)
if extract_system_text(body).contains("__SUBAGENT_MARKER__") {
return true;
}
if let Some(messages) = body.get("messages").and_then(|m| m.as_array()) {
for msg in messages {
if msg.get("role").and_then(|r| r.as_str()) != Some("user") {
continue;
}
let text = extract_text_from_message(msg);
if text.contains("__SUBAGENT_MARKER__") {
return true;
}
}
}
// 信号 2fallback: metadata.user_id 包含子代理标识
// Claude Code 的 Agent tool 会将 subagent session 标记为
// "parentSessionId_agent_agentId" 格式,检测 "_agent_" 后缀
if let Some(user_id) = body.pointer("/metadata/user_id").and_then(|v| v.as_str()) {
// "_agent_" 是 Claude Code Agent tool 的内部标记
if user_id.contains("_agent_") {
return true;
}
}
// 信号 3fallback: system prompt 包含 Claude Code 子代理的典型框架文本
// Agent tool 生成的子代理会在 system prompt 中包含由 Agent tool 注入的任务描述,
// 但主对话的 system prompt 由 Claude Code CLI 直接生成,两者格式不同
// 这个信号不够可靠(用户 prompt 也可能包含这些词),因此只作为辅助判据
// 暂不启用,预留接口
false
}
/// 清理孤立的 tool_result — 没有对应 tool_use 的 tool_result 转为 text block。
///
/// 场景:上下文压缩、消息截断等可能导致 assistant 消息中的 tool_use 被删除,
/// 但后续 user 消息中的 tool_result 仍在。上游 API 可能因不匹配而报错/重试。
///
/// 与 copilot-api 的 `sanitizeOrphanToolResults` 对齐。
pub fn sanitize_orphan_tool_results(mut body: Value) -> Value {
let messages = match body.get_mut("messages").and_then(|m| m.as_array_mut()) {
Some(msgs) if msgs.len() >= 2 => msgs,
_ => return body,
};
// Anthropic 协议要求 tool_result 紧跟其对应 tool_use 所在的 assistant turn。
// 只检查 messages[i-1](紧邻上一条 assistant)来判定是否 orphan
// 与参考实现 sanitizeOrphanToolResults 对齐。
for i in 1..messages.len() {
if messages[i].get("role").and_then(|r| r.as_str()) != Some("user") {
continue;
}
// 收集紧邻上一条 assistant 的 tool_use id
let prev_tool_use_ids: HashSet<String> =
if messages[i - 1].get("role").and_then(|r| r.as_str()) == Some("assistant") {
messages[i - 1]
.get("content")
.and_then(|c| c.as_array())
.map(|blocks| {
blocks
.iter()
.filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("tool_use"))
.filter_map(|b| b.get("id").and_then(|i| i.as_str()).map(String::from))
.collect()
})
.unwrap_or_default()
} else {
// 上一条不是 assistant → 这条 user 中的所有 tool_result 都是 orphan
HashSet::new()
};
let content = match messages[i]
.get_mut("content")
.and_then(|c| c.as_array_mut())
{
Some(blocks) => blocks,
None => continue,
};
for block in content.iter_mut() {
if block.get("type").and_then(|t| t.as_str()) != Some("tool_result") {
continue;
}
let tool_use_id = block
.get("tool_use_id")
.and_then(|id| id.as_str())
.unwrap_or("");
// 空 tool_use_id 或不在紧邻 assistant 的 tool_use 中 → orphan
if tool_use_id.is_empty() || !prev_tool_use_ids.contains(tool_use_id) {
let content_text = match block.get("content") {
Some(c) if c.is_string() => c.as_str().unwrap_or("").to_string(),
Some(c) if c.is_array() => c
.as_array()
.unwrap()
.iter()
.filter_map(|b| b.get("text").and_then(|t| t.as_str()))
.collect::<Vec<_>>()
.join("\n"),
_ => String::new(),
};
*block = serde_json::json!({
"type": "text",
"text": format!("[Tool result for {}]: {}", tool_use_id, content_text)
});
}
}
}
body
}
// ─── 内部辅助 ───────────────────────────────── // ─── 内部辅助 ─────────────────────────────────
/// 从请求体的 `system` 字段提取文本(处理 string/array 两种格式)。
fn extract_system_text(body: &Value) -> String {
match body.get("system") {
Some(s) if s.is_string() => s.as_str().unwrap_or("").to_string(),
Some(arr) if arr.is_array() => arr
.as_array()
.unwrap()
.iter()
.filter_map(|b| b.get("text").and_then(|t| t.as_str()))
.collect::<Vec<_>>()
.join(" "),
_ => String::new(),
}
}
/// 查找最后一条 user 消息的非 tool_result 文本内容。 /// 查找最后一条 user 消息的非 tool_result 文本内容。
/// ///
/// 与参考实现的 `findLastUserContent` 对齐: /// 与参考实现的 `findLastUserContent` 对齐:
@@ -606,7 +433,7 @@ mod tests {
{"role": "user", "content": "Hello, please help me write some code"} {"role": "user", "content": "Hello, please help me write some code"}
] ]
}); });
let result = classify_request(&body, false, true, false); let result = classify_request(&body, false, true);
assert_eq!(result.initiator, "user"); assert_eq!(result.initiator, "user");
assert!(!result.is_compact); assert!(!result.is_compact);
} }
@@ -621,7 +448,7 @@ mod tests {
]} ]}
] ]
}); });
let result = classify_request(&body, false, true, false); let result = classify_request(&body, false, true);
assert_eq!(result.initiator, "user"); assert_eq!(result.initiator, "user");
} }
@@ -641,16 +468,15 @@ mod tests {
]} ]}
] ]
}); });
let result = classify_request(&body, true, true, false); let result = classify_request(&body, true, true);
assert_eq!(result.initiator, "agent"); assert_eq!(result.initiator, "agent");
assert!(!result.is_warmup); assert!(!result.is_warmup);
} }
#[test] #[test]
fn test_classify_tool_result_with_text_block() { fn test_classify_tool_result_with_text_block() {
// tool_result + text blockskill/edit hook/plan follow-up 的常见形态) // 参考实现的关键场景:tool_result + text block
// 有 tool_result → 视为工具续写 → agent // 有 tool_result block → 仍然是 "user"
// 与 copilot-api 的 merge-then-classify 效果对齐
let body = json!({ let body = json!({
"model": "claude-sonnet-4-20250514", "model": "claude-sonnet-4-20250514",
"messages": [ "messages": [
@@ -660,8 +486,8 @@ mod tests {
]} ]}
] ]
}); });
let result = classify_request(&body, false, true, false); let result = classify_request(&body, false, true);
assert_eq!(result.initiator, "agent"); assert_eq!(result.initiator, "user");
} }
#[test] #[test]
@@ -670,14 +496,14 @@ mod tests {
"model": "claude-sonnet-4-20250514", "model": "claude-sonnet-4-20250514",
"messages": [] "messages": []
}); });
let result = classify_request(&body, false, true, false); let result = classify_request(&body, false, true);
assert_eq!(result.initiator, "user"); assert_eq!(result.initiator, "user");
} }
#[test] #[test]
fn test_classify_no_messages() { fn test_classify_no_messages() {
let body = json!({"model": "claude-sonnet-4-20250514"}); let body = json!({"model": "claude-sonnet-4-20250514"});
let result = classify_request(&body, false, true, false); let result = classify_request(&body, false, true);
assert_eq!(result.initiator, "user"); assert_eq!(result.initiator, "user");
} }
@@ -691,7 +517,7 @@ mod tests {
{"role": "user", "content": "Here is the conversation history to summarize..."} {"role": "user", "content": "Here is the conversation history to summarize..."}
] ]
}); });
let result = classify_request(&body, false, true, false); let result = classify_request(&body, false, true);
assert_eq!(result.initiator, "agent"); assert_eq!(result.initiator, "agent");
assert!(result.is_compact); assert!(result.is_compact);
} }
@@ -707,7 +533,7 @@ mod tests {
]} ]}
] ]
}); });
let result = classify_request(&body, false, true, false); let result = classify_request(&body, false, true);
assert_eq!(result.initiator, "agent"); assert_eq!(result.initiator, "agent");
assert!(result.is_compact); assert!(result.is_compact);
} }
@@ -722,7 +548,7 @@ mod tests {
{"role": "user", "content": "Summarize"} {"role": "user", "content": "Summarize"}
] ]
}); });
let result = classify_request(&body, false, false, false); // compact_detection=false let result = classify_request(&body, false, false); // compact_detection=false
assert_eq!(result.initiator, "user"); // 不被标记为 agent assert_eq!(result.initiator, "user"); // 不被标记为 agent
assert!(!result.is_compact); assert!(!result.is_compact);
} }
@@ -736,7 +562,7 @@ mod tests {
{"role": "user", "content": "Please summarize the conversation so far into a concise summary."} {"role": "user", "content": "Please summarize the conversation so far into a concise summary."}
] ]
}); });
let result = classify_request(&body, false, true, false); let result = classify_request(&body, false, true);
// 没有 system prompt 强特征,也没有 CRITICAL 指令 → 不是 compact → user // 没有 system prompt 强特征,也没有 CRITICAL 指令 → 不是 compact → user
assert_eq!(result.initiator, "user"); assert_eq!(result.initiator, "user");
assert!(!result.is_compact); assert!(!result.is_compact);
@@ -753,7 +579,7 @@ mod tests {
] ]
}); });
// has_anthropic_beta=true, 无 tools → warmup // has_anthropic_beta=true, 无 tools → warmup
let result = classify_request(&body, true, true, false); let result = classify_request(&body, true, true);
assert!(result.is_warmup); assert!(result.is_warmup);
} }
@@ -766,7 +592,7 @@ mod tests {
] ]
}); });
// has_anthropic_beta=false → 不是 warmup // has_anthropic_beta=false → 不是 warmup
let result = classify_request(&body, false, true, false); let result = classify_request(&body, false, true);
assert!(!result.is_warmup); assert!(!result.is_warmup);
} }
@@ -780,7 +606,7 @@ mod tests {
] ]
}); });
// 有 tools → 不是 warmup(即使有 anthropic-beta // 有 tools → 不是 warmup(即使有 anthropic-beta
let result = classify_request(&body, true, true, false); let result = classify_request(&body, true, true);
assert!(!result.is_warmup); assert!(!result.is_warmup);
} }
@@ -795,7 +621,7 @@ mod tests {
]} ]}
] ]
}); });
let result = classify_request(&body, true, true, false); let result = classify_request(&body, true, true);
assert_eq!(result.initiator, "agent"); assert_eq!(result.initiator, "agent");
assert!(!result.is_warmup); assert!(!result.is_warmup);
} }
@@ -1005,44 +831,6 @@ mod tests {
assert!(Uuid::parse_str(&id).is_ok()); assert!(Uuid::parse_str(&id).is_ok());
} }
// === deterministic_interaction_id 测试 ===
#[test]
fn test_interaction_id_stable_for_same_session() {
let id1 = deterministic_interaction_id("session_abc");
let id2 = deterministic_interaction_id("session_abc");
assert_eq!(id1, id2);
}
#[test]
fn test_interaction_id_differs_across_sessions() {
let id1 = deterministic_interaction_id("session_abc");
let id2 = deterministic_interaction_id("session_def");
assert_ne!(id1, id2);
}
#[test]
fn test_interaction_id_differs_from_request_id() {
let body = json!({
"messages": [{"role": "user", "content": "Hello"}]
});
let interaction = deterministic_interaction_id("session_abc").unwrap();
let request = deterministic_request_id(&body, "session_abc");
assert_ne!(interaction, request);
}
#[test]
fn test_interaction_id_empty_session_is_none() {
// 无 session 时不应生成 interaction ID(避免碎片化)
assert!(deterministic_interaction_id("").is_none());
}
#[test]
fn test_interaction_id_is_valid_uuid() {
let id = deterministic_interaction_id("test_session").unwrap();
assert!(Uuid::parse_str(&id).is_ok());
}
// === compact 检测增强测试 === // === compact 检测增强测试 ===
#[test] #[test]
@@ -1110,265 +898,4 @@ mod tests {
}); });
assert!(is_compact_request(&body)); assert!(is_compact_request(&body));
} }
// === detect_subagent 测试 ===
#[test]
fn test_detect_subagent_with_marker_in_user_message() {
let body = json!({
"messages": [
{"role": "user", "content": [
{"type": "text", "text": "<system-reminder>\n{\"__SUBAGENT_MARKER__\":{\"session_id\":\"abc123\",\"agent_id\":\"explore-1\",\"agent_type\":\"Explore\"}}\n</system-reminder>\nPlease search the codebase for auth handlers"}
]}
]
});
assert!(detect_subagent(&body));
}
#[test]
fn test_detect_subagent_with_marker_in_system() {
let body = json!({
"system": "You are an agent. {\"__SUBAGENT_MARKER__\":{\"session_id\":\"abc\",\"agent_id\":\"plan-1\",\"agent_type\":\"Plan\"}}",
"messages": [
{"role": "user", "content": "Design the implementation plan"}
]
});
assert!(detect_subagent(&body));
}
#[test]
fn test_detect_subagent_no_marker() {
let body = json!({
"messages": [
{"role": "user", "content": "Hello, please help me write code"}
]
});
assert!(!detect_subagent(&body));
}
#[test]
fn test_detect_subagent_via_metadata_user_id() {
// fallback 信号: metadata.user_id 包含 "_agent_" 标记
let body = json!({
"metadata": {
"user_id": "session_abc123_agent_explore-1"
},
"messages": [
{"role": "user", "content": "Search for files"}
]
});
assert!(detect_subagent(&body));
}
#[test]
fn test_detect_subagent_normal_user_id_not_matched() {
// 普通 session ID 不应被误判
let body = json!({
"metadata": {
"user_id": "session_abc123"
},
"messages": [
{"role": "user", "content": "Hello"}
]
});
assert!(!detect_subagent(&body));
}
#[test]
fn test_classify_subagent_sets_agent_initiator() {
let body = json!({
"messages": [
{"role": "user", "content": [
{"type": "text", "text": "<system-reminder>\n{\"__SUBAGENT_MARKER__\":{\"session_id\":\"abc\",\"agent_id\":\"explore-1\",\"agent_type\":\"Explore\"}}\n</system-reminder>\nSearch for files"}
]}
]
});
let result = classify_request(&body, false, true, true);
assert_eq!(result.initiator, "agent");
assert!(result.is_subagent);
}
#[test]
fn test_classify_subagent_disabled_flag() {
let body = json!({
"messages": [
{"role": "user", "content": [
{"type": "text", "text": "<system-reminder>\n{\"__SUBAGENT_MARKER__\":{\"session_id\":\"abc\",\"agent_id\":\"explore-1\",\"agent_type\":\"Explore\"}}\n</system-reminder>\nSearch for files"}
]}
]
});
// subagent_detection=false → 不检测子代理
let result = classify_request(&body, false, true, false);
assert_eq!(result.initiator, "user");
assert!(!result.is_subagent);
}
// === sanitize_orphan_tool_results 测试 ===
#[test]
fn test_sanitize_orphan_tool_results_converts_orphans() {
let body = json!({
"messages": [
{"role": "user", "content": "Help me"},
{"role": "assistant", "content": [
{"type": "tool_use", "id": "tool_1", "name": "read_file", "input": {}}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "tool_1", "content": "file contents"},
{"type": "tool_result", "tool_use_id": "tool_orphan", "content": "orphan data"}
]}
]
});
let result = sanitize_orphan_tool_results(body);
let msgs = result["messages"].as_array().unwrap();
let last_content = msgs[2]["content"].as_array().unwrap();
// tool_1 保留为 tool_result
assert_eq!(last_content[0]["type"], "tool_result");
// tool_orphan 转为 text
assert_eq!(last_content[1]["type"], "text");
assert!(last_content[1]["text"]
.as_str()
.unwrap()
.contains("tool_orphan"));
}
#[test]
fn test_sanitize_orphan_tool_results_no_orphans() {
let body = json!({
"messages": [
{"role": "assistant", "content": [
{"type": "tool_use", "id": "tool_1", "name": "read_file", "input": {}}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "tool_1", "content": "ok"}
]}
]
});
let result = sanitize_orphan_tool_results(body.clone());
// 无孤立 tool_result,不应有变化
assert_eq!(result["messages"][1]["content"][0]["type"], "tool_result");
}
#[test]
fn test_sanitize_orphan_non_adjacent_assistant_tool_use_is_orphan() {
// tool_use 在更早的 assistant 中,但 tool_result 的紧邻上一条是另一个 assistant
// → 对 Anthropic 协议来说这个 tool_result 是 orphan
let body = json!({
"messages": [
{"role": "user", "content": "step 1"},
{"role": "assistant", "content": [
{"type": "tool_use", "id": "old_tool", "name": "search", "input": {}}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "old_tool", "content": "found it"}
]},
{"role": "assistant", "content": [
{"type": "text", "text": "OK, now let me think..."}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "old_tool", "content": "stale ref"}
]}
]
});
let result = sanitize_orphan_tool_results(body);
let msgs = result["messages"].as_array().unwrap();
// messages[2]: 紧邻 assistant 有 old_tool → 保留
assert_eq!(msgs[2]["content"][0]["type"], "tool_result");
// messages[4]: 紧邻 assistant 无 tool_use → orphan → text
assert_eq!(msgs[4]["content"][0]["type"], "text");
}
#[test]
fn test_sanitize_orphan_prev_not_assistant() {
// tool_result 紧邻上一条是 user(非 assistant)→ 全部 orphan
let body = json!({
"messages": [
{"role": "user", "content": "first"},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "t1", "content": "data"}
]}
]
});
let result = sanitize_orphan_tool_results(body);
assert_eq!(result["messages"][1]["content"][0]["type"], "text");
}
/// 关键场景:orphan tool_result(上下文压缩丢失了紧邻 tool_use)
/// 在分类时仍应被视为 agent continuation,不能因为后续的 sanitize
/// 将其转为 text 而变成 user 请求。
///
/// 这个测试验证 classify_request 在原始(未 sanitize)的 body 上
/// 正确识别 orphan tool_result 为 agent。
#[test]
fn test_orphan_tool_result_classified_as_agent_before_sanitize() {
// 场景:最后一条 user 消息全是 tool_result,但紧邻的 assistant
// 消息里没有对应的 tool_use(因上下文压缩丢失了)
let body = json!({
"messages": [
{"role": "assistant", "content": "I'll help you with that."},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "orphan_tool_1", "content": "file contents here"},
{"type": "tool_result", "tool_use_id": "orphan_tool_2", "content": "another result"}
]}
]
});
// 在原始 body 上分类 → 全是 tool_result → agent
let classification = classify_request(&body, false, false, false);
assert_eq!(classification.initiator, "agent");
// sanitize 后 → tool_result 变为 text → 如果再分类就会变成 user
let sanitized = sanitize_orphan_tool_results(body);
let classification_after = classify_request(&sanitized, false, false, false);
assert_eq!(
classification_after.initiator, "user",
"sanitize 后 orphan tool_result 变为 text,分类变成 user — \
sanitize "
);
}
/// orphan tool_result + text 混合场景:
/// 分类器直接识别含 tool_result 的消息为 agent(无论是否有 text block),
/// 不依赖 merge 的执行顺序。即使 orphan tool_result 后续被 sanitize 转为 text
/// 分类结果在此之前已经确定为 agent。
#[test]
fn test_orphan_tool_result_with_text_classified_as_agent() {
let body = json!({
"messages": [
{"role": "assistant", "content": "Processing..."},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "orphan_1", "content": "result data"},
{"type": "text", "text": "Here's the output from the tool"}
]}
]
});
// 含有 tool_result → agent(无论是否有 text block
let classification = classify_request(&body, false, false, false);
assert_eq!(classification.initiator, "agent");
// sanitize 后 orphan tool_result 变为 text → 纯 text → 分类会变成 user
// 但正确的执行顺序是先分类再 sanitize,所以这不是问题
let sanitized = sanitize_orphan_tool_results(body);
let classification_after = classify_request(&sanitized, false, false, false);
assert_eq!(classification_after.initiator, "user");
}
#[test]
fn test_sanitize_orphan_empty_tool_use_id_is_orphan() {
// tool_use_id 为空或缺失 → 无法匹配任何 tool_use → orphan
let body = json!({
"messages": [
{"role": "assistant", "content": [
{"type": "tool_use", "id": "tool_1", "name": "read", "input": {}}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "", "content": "empty id"},
{"type": "tool_result", "content": "missing id field"}
]}
]
});
let result = sanitize_orphan_tool_results(body);
let content = result["messages"][1]["content"].as_array().unwrap();
assert_eq!(content[0]["type"], "text");
assert_eq!(content[1]["type"], "text");
}
} }
+27 -83
View File
@@ -776,42 +776,32 @@ impl RequestForwarder {
== Some("github_copilot") == Some("github_copilot")
|| base_url.contains("githubcopilot.com"); || base_url.contains("githubcopilot.com");
// --- Copilot 优化器:分类 + 请求体优化(在格式转换之前执行) --- // --- Copilot 优化器:请求体优化 + 分类(在格式转换之前执行) ---
// 注意:确定性 ID 也在此处计算,因为 mapped_body 在格式转换时会被 move // 注意:确定性 ID 也在此处计算,因为 mapped_body 在格式转换时会被 move
//
// 执行顺序(与 copilot-api 对齐):
// 1. 先在原始 body 上分类(保留 tool_result 语义,避免误判为 user
// 2. 再清洗孤立 tool_result(防止上游 API 报错)
// 3. 再合并 tool_result + text(减少 premium 计费)
let copilot_optimization = if is_copilot && self.copilot_optimizer_config.enabled { let copilot_optimization = if is_copilot && self.copilot_optimizer_config.enabled {
// 1. 在原始 body 上分类 — 必须在清洗/合并之前执行 // 1. Tool result 合并 — 必须在分类之前执行
// 孤立 tool_result 仍保持 tool_result 类型,分类能正确识别为 agent // 合并将 [tool_result, text] 变为 [tool_result(含text)]
// 分类才能正确识别为 agent(全是 tool_result)而非 user(有 text block
if self.copilot_optimizer_config.tool_result_merging {
mapped_body = super::copilot_optimizer::merge_tool_results(mapped_body);
}
// 2. 在合并后的 body 上进行分类
let has_anthropic_beta = headers.contains_key("anthropic-beta"); let has_anthropic_beta = headers.contains_key("anthropic-beta");
let classification = super::copilot_optimizer::classify_request( let classification = super::copilot_optimizer::classify_request(
&mapped_body, &mapped_body,
has_anthropic_beta, has_anthropic_beta,
self.copilot_optimizer_config.compact_detection, self.copilot_optimizer_config.compact_detection,
self.copilot_optimizer_config.subagent_detection,
); );
log::debug!( log::debug!(
"[Copilot] 优化器分类: initiator={}, is_warmup={}, is_compact={}, is_subagent={}", "[Copilot] 优化器分类: initiator={}, is_warmup={}, is_compact={}",
classification.initiator, classification.initiator,
classification.is_warmup, classification.is_warmup,
classification.is_compact, classification.is_compact
classification.is_subagent
); );
// 2. 孤立 tool_result 清理 — 分类完成后再清洗 // 3. Warmup 小模型降级
// 防止上游 API 因不匹配的 tool_result 报错导致重试/重复计费
mapped_body = super::copilot_optimizer::sanitize_orphan_tool_results(mapped_body);
// 3. Tool result 合并 — 将 [tool_result, text] 变为 [tool_result(含text)]
if self.copilot_optimizer_config.tool_result_merging {
mapped_body = super::copilot_optimizer::merge_tool_results(mapped_body);
}
// 4. Warmup 小模型降级
if self.copilot_optimizer_config.warmup_downgrade && classification.is_warmup { if self.copilot_optimizer_config.warmup_downgrade && classification.is_warmup {
log::info!( log::info!(
"[Copilot] Warmup 请求降级到模型: {}", "[Copilot] Warmup 请求降级到模型: {}",
@@ -822,52 +812,22 @@ impl RequestForwarder {
} }
// 预计算确定性 Request ID(在 body 被 move 之前) // 预计算确定性 Request ID(在 body 被 move 之前)
// Session 提取优先级(与 session.rs extract_from_metadata 对齐): // 使用 session_id 从 body.metadata.user_id 或请求头提取
// 1. metadata.user_id 中的 _session_ 后缀 let session_id = body
// 2. metadata.session_id(直接字段) .pointer("/metadata/user_id")
// 3. raw metadata.user_id(整串 fallback
// 4. x-session-id header
let metadata = body.get("metadata");
let session_id = metadata
.and_then(|m| m.get("user_id"))
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.and_then(super::session::parse_session_from_user_id) .or_else(|| headers.get("x-session-id").and_then(|v| v.to_str().ok()))
.or_else(|| { .unwrap_or("");
metadata
.and_then(|m| m.get("session_id"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
})
.or_else(|| {
metadata
.and_then(|m| m.get("user_id"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
})
.or_else(|| {
headers
.get("x-session-id")
.and_then(|v| v.to_str().ok())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
})
.unwrap_or_default();
let det_request_id = if self.copilot_optimizer_config.deterministic_request_id { let det_request_id = if self.copilot_optimizer_config.deterministic_request_id {
Some(super::copilot_optimizer::deterministic_request_id( Some(super::copilot_optimizer::deterministic_request_id(
&mapped_body, &mapped_body,
&session_id, session_id,
)) ))
} else { } else {
None None
}; };
// 从 session ID 派生稳定的 interaction ID(同一主对话共享) Some((classification, det_request_id))
let interaction_id =
super::copilot_optimizer::deterministic_interaction_id(&session_id);
Some((classification, det_request_id, interaction_id))
} else { } else {
None None
}; };
@@ -1079,18 +1039,12 @@ impl RequestForwarder {
} }
// --- Copilot 优化器:动态 header 注入 --- // --- Copilot 优化器:动态 header 注入 ---
if let Some((ref classification, ref det_request_id, ref interaction_id)) = if let Some((ref classification, ref det_request_id)) = copilot_optimization {
copilot_optimization
{
for (name, value) in auth_headers.iter_mut() { for (name, value) in auth_headers.iter_mut() {
match name.as_str() { match name.as_str() {
"x-initiator" if self.copilot_optimizer_config.request_classification => { "x-initiator" if self.copilot_optimizer_config.request_classification => {
*value = http::HeaderValue::from_static(classification.initiator); *value = http::HeaderValue::from_static(classification.initiator);
} }
"x-interaction-type" if classification.is_subagent => {
// 子代理请求:conversation-subagent 不计 premium interaction
*value = http::HeaderValue::from_static("conversation-subagent");
}
"x-request-id" | "x-agent-task-id" => { "x-request-id" | "x-agent-task-id" => {
if let Some(ref det_id) = det_request_id { if let Some(ref det_id) = det_request_id {
if let Ok(hv) = http::HeaderValue::from_str(det_id) { if let Ok(hv) = http::HeaderValue::from_str(det_id) {
@@ -1101,19 +1055,6 @@ impl RequestForwarder {
_ => {} _ => {}
} }
} }
// x-interaction-id:仅在有 session 时注入(不在 get_auth_headers 中)
if let Some(ref iid) = interaction_id {
if let Ok(hv) = http::HeaderValue::from_str(iid) {
auth_headers.push((http::HeaderName::from_static("x-interaction-id"), hv));
}
}
if classification.is_subagent {
log::info!(
"[Copilot] 子代理请求: x-initiator=agent, x-interaction-type=conversation-subagent"
);
}
} }
// Copilot 指纹头名(由 get_auth_headers 注入,需在原始头中去重) // Copilot 指纹头名(由 get_auth_headers 注入,需在原始头中去重)
@@ -1128,7 +1069,6 @@ impl RequestForwarder {
// 新增 headers // 新增 headers
"x-initiator", "x-initiator",
"x-interaction-type", "x-interaction-type",
"x-interaction-id",
"x-vscode-user-agent-library-version", "x-vscode-user-agent-library-version",
"x-request-id", "x-request-id",
"x-agent-task-id", "x-agent-task-id",
@@ -1347,8 +1287,12 @@ impl RequestForwarder {
self.non_streaming_timeout self.non_streaming_timeout
}; };
// 获取全局代理 URL // 解析上游代理 URL(供应商单独代理 > 全局代理 > 无)
let upstream_proxy_url: Option<String> = super::http_client::get_current_proxy_url(); let proxy_config = provider.meta.as_ref().and_then(|m| m.proxy_config.as_ref());
let upstream_proxy_url: Option<String> = proxy_config
.filter(|c| c.enabled)
.and_then(super::http_client::build_proxy_url_from_config)
.or_else(super::http_client::get_current_proxy_url);
// SOCKS5 代理不支持 CONNECT 隧道,需要用 reqwest // SOCKS5 代理不支持 CONNECT 隧道,需要用 reqwest
let is_socks_proxy = upstream_proxy_url let is_socks_proxy = upstream_proxy_url
@@ -1364,7 +1308,7 @@ impl RequestForwarder {
let response = if is_socks_proxy { let response = if is_socks_proxy {
// SOCKS5 代理:只能走 reqwest(不支持 header case 保留) // SOCKS5 代理:只能走 reqwest(不支持 header case 保留)
log::debug!("[Forwarder] Using reqwest for SOCKS5 proxy"); log::debug!("[Forwarder] Using reqwest for SOCKS5 proxy");
let client = super::http_client::get(); let client = super::http_client::get_for_provider(proxy_config);
let mut request = client.post(&url); let mut request = client.post(&url);
if !self.non_streaming_timeout.is_zero() { if !self.non_streaming_timeout.is_zero() {
request = request.timeout(self.non_streaming_timeout); request = request.timeout(self.non_streaming_timeout);
+6 -4
View File
@@ -20,8 +20,7 @@ use super::{
}, },
response_processor::{ response_processor::{
create_logged_passthrough_stream, process_response, read_decoded_body, create_logged_passthrough_stream, process_response, read_decoded_body,
strip_entity_headers_for_rebuilt_body, strip_hop_by_hop_response_headers, strip_entity_headers_for_rebuilt_body, SseUsageCollector,
SseUsageCollector,
}, },
server::ProxyState, server::ProxyState,
types::*, types::*,
@@ -217,6 +216,10 @@ async fn handle_claude_transform(
"Cache-Control", "Cache-Control",
axum::http::HeaderValue::from_static("no-cache"), axum::http::HeaderValue::from_static("no-cache"),
); );
headers.insert(
"Connection",
axum::http::HeaderValue::from_static("keep-alive"),
);
let body = axum::body::Body::from_stream(logged_stream); let body = axum::body::Body::from_stream(logged_stream);
return Ok((headers, body).into_response()); return Ok((headers, body).into_response());
@@ -284,7 +287,6 @@ async fn handle_claude_transform(
// 构建响应 // 构建响应
let mut builder = axum::response::Response::builder().status(status); let mut builder = axum::response::Response::builder().status(status);
strip_entity_headers_for_rebuilt_body(&mut response_headers); strip_entity_headers_for_rebuilt_body(&mut response_headers);
strip_hop_by_hop_response_headers(&mut response_headers);
for (key, value) in response_headers.iter() { for (key, value) in response_headers.iter() {
builder = builder.header(key, value); builder = builder.header(key, value);
@@ -601,7 +603,7 @@ async fn log_usage(
model model
}; };
let request_id = usage.dedup_request_id(); let request_id = uuid::Uuid::new_v4().to_string();
if let Err(e) = logger.log_with_calculation( if let Err(e) = logger.log_with_calculation(
request_id, request_id,
+98
View File
@@ -3,6 +3,7 @@
//! 提供支持全局代理配置的 HTTP 客户端。 //! 提供支持全局代理配置的 HTTP 客户端。
//! 所有需要发送 HTTP 请求的模块都应使用此模块提供的客户端。 //! 所有需要发送 HTTP 请求的模块都应使用此模块提供的客户端。
use crate::provider::ProviderProxyConfig;
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
use reqwest::Client; use reqwest::Client;
use std::env; use std::env;
@@ -333,6 +334,103 @@ pub fn mask_url(url: &str) -> String {
} }
} }
/// 根据供应商单独代理配置构建代理 URL
///
/// 将 ProviderProxyConfig 转换为代理 URL 字符串
pub fn build_proxy_url_from_config(config: &ProviderProxyConfig) -> Option<String> {
let proxy_type = config.proxy_type.as_deref().unwrap_or("http");
let host = config.proxy_host.as_deref()?;
let port = config.proxy_port?;
// 构建带认证的代理 URL
if let (Some(username), Some(password)) = (&config.proxy_username, &config.proxy_password) {
if !username.is_empty() && !password.is_empty() {
return Some(format!(
"{proxy_type}://{username}:{password}@{host}:{port}"
));
}
}
Some(format!("{proxy_type}://{host}:{port}"))
}
/// 根据供应商单独代理配置构建 HTTP 客户端
///
/// 如果供应商配置了单独代理(enabled = true),则使用该代理构建客户端;
/// 否则返回 None,调用方应使用全局客户端。
///
/// # Arguments
/// * `proxy_config` - 供应商的代理配置
///
/// # Returns
/// 如果配置有效则返回 Some(Client),否则返回 None
pub fn build_client_for_provider(proxy_config: Option<&ProviderProxyConfig>) -> Option<Client> {
let config = proxy_config.filter(|c| c.enabled)?;
let proxy_url = build_proxy_url_from_config(config)?;
log::debug!(
"[ProviderProxy] Building client with proxy: {}",
mask_url(&proxy_url)
);
// 构建带代理的客户端
let proxy = match reqwest::Proxy::all(&proxy_url) {
Ok(p) => p,
Err(e) => {
log::error!(
"[ProviderProxy] Failed to create proxy from '{}': {}",
mask_url(&proxy_url),
e
);
return None;
}
};
match Client::builder()
.timeout(Duration::from_secs(600))
.connect_timeout(Duration::from_secs(30))
.pool_max_idle_per_host(10)
.tcp_keepalive(Duration::from_secs(60))
.no_gzip()
.no_brotli()
.no_deflate()
.proxy(proxy)
.build()
{
Ok(client) => {
log::info!(
"[ProviderProxy] Client built with proxy: {}",
mask_url(&proxy_url)
);
Some(client)
}
Err(e) => {
log::error!("[ProviderProxy] Failed to build client: {e}");
None
}
}
}
/// 获取供应商专用的 HTTP 客户端
///
/// 优先使用供应商单独代理配置,如果未启用则返回全局客户端。
///
/// # Arguments
/// * `proxy_config` - 供应商的代理配置
///
/// # Returns
/// 返回适合该供应商的 HTTP 客户端
pub fn get_for_provider(proxy_config: Option<&ProviderProxyConfig>) -> Client {
// 优先使用供应商单独代理
if let Some(client) = build_client_for_provider(proxy_config) {
return client;
}
// 回退到全局客户端
get()
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+3 -40
View File
@@ -81,48 +81,12 @@ pub fn transform_claude_request_for_api_format(
provider: &Provider, provider: &Provider,
api_format: &str, api_format: &str,
) -> Result<serde_json::Value, ProxyError> { ) -> Result<serde_json::Value, ProxyError> {
// Copilot 场景:优先从 metadata.user_id 提取 session ID 作为 cache key let cache_key = provider
// 格式: "uuid_sessionId" → 提取 "_" 后面的部分作为 session 标识
// 同一会话的请求共享 cache key,提升 Copilot 缓存命中率
let is_copilot = provider
.meta
.as_ref()
.and_then(|m| m.provider_type.as_deref())
== Some("github_copilot")
|| provider
.settings_config
.get("baseUrl")
.and_then(|v| v.as_str())
.is_some_and(|u| u.contains("githubcopilot.com"));
let session_cache_key: Option<String> = if is_copilot {
let metadata = body.get("metadata");
// Session 提取优先级(与 forwarder 和 session.rs 统一):
// 1. metadata.user_id 中的 _session_ 后缀
// 2. metadata.session_id(直接字段)
metadata
.and_then(|m| m.get("user_id"))
.and_then(|v| v.as_str())
.and_then(super::super::session::parse_session_from_user_id)
.or_else(|| {
metadata
.and_then(|m| m.get("session_id"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
})
} else {
None
};
let cache_key = session_cache_key
.as_deref()
.or_else(|| {
provider
.meta .meta
.as_ref() .as_ref()
.and_then(|m| m.prompt_cache_key.as_deref()) .and_then(|m| m.prompt_cache_key.as_deref())
})
.unwrap_or(&provider.id); .unwrap_or(&provider.id);
match api_format { match api_format {
"openai_responses" => { "openai_responses" => {
// Codex OAuth (ChatGPT Plus/Pro 反代) 需要在请求体里强制 store: false // Codex OAuth (ChatGPT Plus/Pro 反代) 需要在请求体里强制 store: false
@@ -138,7 +102,7 @@ pub fn transform_claude_request_for_api_format(
is_codex_oauth, is_codex_oauth,
) )
} }
"openai_chat" => super::transform::anthropic_to_openai(body), "openai_chat" => super::transform::anthropic_to_openai(body, Some(cache_key)),
_ => Ok(body), _ => Ok(body),
} }
} }
@@ -492,7 +456,6 @@ impl ProviderAdapter for ClaudeAdapter {
HeaderName::from_static("x-interaction-type"), HeaderName::from_static("x-interaction-type"),
HeaderValue::from_static("conversation-agent"), HeaderValue::from_static("conversation-agent"),
), ),
// x-interaction-id 由 forwarder 按需注入(仅在有 session 时)
( (
HeaderName::from_static("x-vscode-user-agent-library-version"), HeaderName::from_static("x-vscode-user-agent-library-version"),
HeaderValue::from_static("electron-fetch"), HeaderValue::from_static("electron-fetch"),
+1 -31
View File
@@ -85,16 +85,8 @@ struct ToolBlockState {
name: String, name: String,
started: bool, started: bool,
pending_args: String, pending_args: String,
/// 连续空白字符计数 — 用于检测 Copilot 无限换行 bug
/// 当 function call 参数中出现连续 20+ 空白字符时,强制终止流
consecutive_whitespace: usize,
/// 是否已因无限空白 bug 被中止
aborted: bool,
} }
/// 无限空白 bug 的连续空白字符阈值
const INFINITE_WHITESPACE_THRESHOLD: usize = 20;
/// 创建 Anthropic SSE 流 /// 创建 Anthropic SSE 流
pub fn create_anthropic_sse_stream<E: std::error::Error + Send + 'static>( pub fn create_anthropic_sse_stream<E: std::error::Error + Send + 'static>(
stream: impl Stream<Item = Result<Bytes, E>> + Send + 'static, stream: impl Stream<Item = Result<Bytes, E>> + Send + 'static,
@@ -305,16 +297,9 @@ pub fn create_anthropic_sse_stream<E: std::error::Error + Send + 'static>(
name: String::new(), name: String::new(),
started: false, started: false,
pending_args: String::new(), pending_args: String::new(),
consecutive_whitespace: 0,
aborted: false,
} }
}); });
// 如果此 tool call 已被中止(无限空白 bug),跳过后续处理
if state.aborted {
continue;
}
if let Some(id) = &tool_call.id { if let Some(id) = &tool_call.id {
state.id = id.clone(); state.id = id.clone();
} }
@@ -343,22 +328,7 @@ pub fn create_anthropic_sse_stream<E: std::error::Error + Send + 'static>(
.as_ref() .as_ref()
.and_then(|f| f.arguments.clone()); .and_then(|f| f.arguments.clone());
let immediate_delta = if let Some(args) = args_delta { let immediate_delta = if let Some(args) = args_delta {
// 无限空白 bug 检测:跟踪连续空白字符 if state.started {
for ch in args.chars() {
if ch.is_whitespace() {
state.consecutive_whitespace += 1;
} else {
state.consecutive_whitespace = 0;
}
}
if state.consecutive_whitespace >= INFINITE_WHITESPACE_THRESHOLD {
log::warn!(
"[Copilot] 检测到无限空白 bug (tool: {}), 中止此 tool call 流",
state.name
);
state.aborted = true;
None
} else if state.started {
Some(args) Some(args)
} else { } else {
state.pending_args.push_str(&args); state.pending_args.push_str(&args);
+41 -22
View File
@@ -71,8 +71,10 @@ pub fn resolve_reasoning_effort(body: &Value) -> Option<&'static str> {
} }
} }
/// Anthropic 请求 → OpenAI Chat Completions 请求 /// Anthropic 请求 → OpenAI 请求
pub fn anthropic_to_openai(body: Value) -> Result<Value, ProxyError> { ///
/// `cache_key`: optional prompt_cache_key to inject for improved cache routing
pub fn anthropic_to_openai(body: Value, cache_key: Option<&str>) -> Result<Value, ProxyError> {
let mut result = json!({}); let mut result = json!({});
// NOTE: 模型映射由上游统一处理(proxy::model_mapper),格式转换层只做结构转换。 // NOTE: 模型映射由上游统一处理(proxy::model_mapper),格式转换层只做结构转换。
@@ -173,6 +175,11 @@ pub fn anthropic_to_openai(body: Value) -> Result<Value, ProxyError> {
result["tool_choice"] = v.clone(); result["tool_choice"] = v.clone();
} }
// Inject prompt_cache_key for improved cache routing on OpenAI-compatible endpoints
if let Some(key) = cache_key {
result["prompt_cache_key"] = json!(key);
}
Ok(result) Ok(result)
} }
@@ -583,7 +590,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["model"], "claude-3-opus"); assert_eq!(result["model"], "claude-3-opus");
assert_eq!(result["max_tokens"], 1024); assert_eq!(result["max_tokens"], 1024);
assert_eq!(result["messages"][0]["role"], "user"); assert_eq!(result["messages"][0]["role"], "user");
@@ -599,7 +606,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["messages"][0]["role"], "system"); assert_eq!(result["messages"][0]["role"], "system");
assert_eq!( assert_eq!(
result["messages"][0]["content"], result["messages"][0]["content"],
@@ -621,7 +628,7 @@ mod tests {
}] }]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["tools"][0]["type"], "function"); assert_eq!(result["tools"][0]["type"], "function");
assert_eq!(result["tools"][0]["function"]["name"], "get_weather"); assert_eq!(result["tools"][0]["function"]["name"], "get_weather");
} }
@@ -638,7 +645,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["messages"].as_array().unwrap().len(), 2); assert_eq!(result["messages"].as_array().unwrap().len(), 2);
assert_eq!(result["messages"][0]["role"], "system"); assert_eq!(result["messages"][0]["role"], "system");
assert_eq!( assert_eq!(
@@ -661,7 +668,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["messages"][0]["role"], "system"); assert_eq!(result["messages"][0]["role"], "system");
assert_eq!( assert_eq!(
result["messages"][0]["content"], result["messages"][0]["content"],
@@ -682,7 +689,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["messages"][0]["role"], "system"); assert_eq!(result["messages"][0]["role"], "system");
assert_eq!( assert_eq!(
result["messages"][0]["content"], result["messages"][0]["content"],
@@ -705,7 +712,7 @@ mod tests {
}] }]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
let msg = &result["messages"][0]; let msg = &result["messages"][0];
assert_eq!(msg["role"], "assistant"); assert_eq!(msg["role"], "assistant");
assert!(msg.get("tool_calls").is_some()); assert!(msg.get("tool_calls").is_some());
@@ -725,7 +732,7 @@ mod tests {
}] }]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
let msg = &result["messages"][0]; let msg = &result["messages"][0];
assert_eq!(msg["role"], "tool"); assert_eq!(msg["role"], "tool");
assert_eq!(msg["tool_call_id"], "call_123"); assert_eq!(msg["tool_call_id"], "call_123");
@@ -797,19 +804,31 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["model"], "gpt-4o"); assert_eq!(result["model"], "gpt-4o");
} }
#[test] #[test]
fn test_anthropic_to_openai_does_not_inject_prompt_cache_key() { fn test_anthropic_to_openai_with_cache_key() {
let input = json!({ let input = json!({
"model": "claude-3-opus", "model": "claude-3-opus",
"max_tokens": 1024, "max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, Some("provider-123")).unwrap();
assert_eq!(result["prompt_cache_key"], "provider-123");
}
#[test]
fn test_anthropic_to_openai_no_cache_key() {
let input = json!({
"model": "claude-3-opus",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_openai(input, None).unwrap();
assert!(result.get("prompt_cache_key").is_none()); assert!(result.get("prompt_cache_key").is_none());
} }
@@ -835,7 +854,7 @@ mod tests {
}] }]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
// System message cache_control preserved // System message cache_control preserved
assert_eq!(result["messages"][0]["cache_control"]["type"], "ephemeral"); assert_eq!(result["messages"][0]["cache_control"]["type"], "ephemeral");
// Text block cache_control preserved // Text block cache_control preserved
@@ -1089,7 +1108,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert!(result.get("reasoning_effort").is_none()); assert!(result.get("reasoning_effort").is_none());
} }
@@ -1102,7 +1121,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["reasoning_effort"], "medium"); assert_eq!(result["reasoning_effort"], "medium");
} }
@@ -1115,7 +1134,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["reasoning_effort"], "xhigh"); assert_eq!(result["reasoning_effort"], "xhigh");
} }
@@ -1128,7 +1147,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["reasoning_effort"], "low"); assert_eq!(result["reasoning_effort"], "low");
} }
@@ -1141,7 +1160,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["reasoning_effort"], "xhigh"); assert_eq!(result["reasoning_effort"], "xhigh");
} }
@@ -1153,7 +1172,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert!(result.get("reasoning_effort").is_none()); assert!(result.get("reasoning_effort").is_none());
} }
@@ -1166,7 +1185,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert!( assert!(
result.get("max_tokens").is_none(), result.get("max_tokens").is_none(),
"{model} should not have max_tokens" "{model} should not have max_tokens"
@@ -1186,7 +1205,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}] "messages": [{"role": "user", "content": "Hello"}]
}); });
let result = anthropic_to_openai(input).unwrap(); let result = anthropic_to_openai(input, None).unwrap();
assert_eq!(result["max_tokens"], 1024); assert_eq!(result["max_tokens"], 1024);
assert!(result.get("max_completion_tokens").is_none()); assert!(result.get("max_completion_tokens").is_none());
} }
+4 -129
View File
@@ -11,7 +11,7 @@ use super::{
usage::parser::TokenUsage, usage::parser::TokenUsage,
ProxyError, ProxyError,
}; };
use axum::http::{header::HeaderMap, HeaderName}; use axum::http::header::HeaderMap;
use axum::response::{IntoResponse, Response}; use axum::response::{IntoResponse, Response};
use bytes::Bytes; use bytes::Bytes;
use futures::stream::{Stream, StreamExt}; use futures::stream::{Stream, StreamExt};
@@ -68,41 +68,6 @@ fn get_content_encoding(headers: &HeaderMap) -> Option<String> {
.filter(|s| !s.is_empty() && s != "identity") .filter(|s| !s.is_empty() && s != "identity")
} }
/// RFC 2616 / RFC 7230 中定义的不应被代理继续转发的响应头。
const HOP_BY_HOP_RESPONSE_HEADERS: &[&str] = &[
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"proxy-connection",
"te",
"trailer",
"trailers",
"transfer-encoding",
"upgrade",
];
/// 移除响应侧 hop-by-hop 头,以及 `Connection` 中点名的扩展头。
pub(crate) fn strip_hop_by_hop_response_headers(headers: &mut HeaderMap) {
let connection_listed_headers: Vec<HeaderName> = headers
.get_all(axum::http::header::CONNECTION)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(','))
.map(str::trim)
.filter(|name| !name.is_empty())
.filter_map(|name| HeaderName::from_bytes(name.as_bytes()).ok())
.collect();
for name in HOP_BY_HOP_RESPONSE_HEADERS {
headers.remove(*name);
}
for name in connection_listed_headers {
headers.remove(name);
}
}
/// 移除在重建响应体后会失真的实体头。 /// 移除在重建响应体后会失真的实体头。
pub(crate) fn strip_entity_headers_for_rebuilt_body(headers: &mut HeaderMap) { pub(crate) fn strip_entity_headers_for_rebuilt_body(headers: &mut HeaderMap) {
headers.remove(axum::http::header::CONTENT_ENCODING); headers.remove(axum::http::header::CONTENT_ENCODING);
@@ -198,13 +163,10 @@ pub async fn handle_streaming(
); );
} }
let mut response_headers = response.headers().clone();
strip_hop_by_hop_response_headers(&mut response_headers);
let mut builder = axum::response::Response::builder().status(status); let mut builder = axum::response::Response::builder().status(status);
// 复制响应头 // 复制响应头
for (key, value) in &response_headers { for (key, value) in response.headers() {
builder = builder.header(key, value); builder = builder.header(key, value);
} }
@@ -245,9 +207,8 @@ pub async fn handle_non_streaming(
} else { } else {
Duration::ZERO Duration::ZERO
}; };
let (mut response_headers, status, body_bytes) = let (response_headers, status, body_bytes) =
read_decoded_body(response, ctx.tag, body_timeout).await?; read_decoded_body(response, ctx.tag, body_timeout).await?;
strip_hop_by_hop_response_headers(&mut response_headers);
log::debug!( log::debug!(
"[{}] 上游响应体内容: {}", "[{}] 上游响应体内容: {}",
@@ -567,7 +528,7 @@ async fn log_usage_internal(
model model
}; };
let request_id = usage.dedup_request_id(); let request_id = uuid::Uuid::new_v4().to_string();
log::debug!( log::debug!(
"[{app_type}] 记录请求日志: id={request_id}, provider={provider_id}, model={model}, streaming={is_streaming}, status={status_code}, latency_ms={latency_ms}, first_token_ms={first_token_ms:?}, session={}, input={}, output={}, cache_read={}, cache_creation={}", "[{app_type}] 记录请求日志: id={request_id}, provider={provider_id}, model={model}, streaming={is_streaming}, status={status_code}, latency_ms={latency_ms}, first_token_ms={first_token_ms:?}, session={}, input={}, output={}, cache_read={}, cache_creation={}",
@@ -754,90 +715,6 @@ mod tests {
assert_eq!(super::strip_sse_field("id:1", "data"), None); assert_eq!(super::strip_sse_field("id:1", "data"), None);
} }
#[test]
fn test_strip_hop_by_hop_response_headers_removes_standard_headers() {
let mut headers = HeaderMap::new();
headers.insert(
axum::http::header::CONNECTION,
axum::http::HeaderValue::from_static("keep-alive"),
);
headers.insert(
axum::http::header::HeaderName::from_static("keep-alive"),
axum::http::HeaderValue::from_static("timeout=5"),
);
headers.insert(
axum::http::header::TRANSFER_ENCODING,
axum::http::HeaderValue::from_static("chunked"),
);
headers.insert(
axum::http::header::HeaderName::from_static("proxy-connection"),
axum::http::HeaderValue::from_static("keep-alive"),
);
headers.insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("application/json"),
);
headers.insert(
axum::http::header::CONTENT_LENGTH,
axum::http::HeaderValue::from_static("12"),
);
strip_hop_by_hop_response_headers(&mut headers);
assert!(!headers.contains_key(axum::http::header::CONNECTION));
assert!(!headers.contains_key("keep-alive"));
assert!(!headers.contains_key(axum::http::header::TRANSFER_ENCODING));
assert!(!headers.contains_key("proxy-connection"));
assert_eq!(
headers.get(axum::http::header::CONTENT_TYPE),
Some(&axum::http::HeaderValue::from_static("application/json"))
);
assert_eq!(
headers.get(axum::http::header::CONTENT_LENGTH),
Some(&axum::http::HeaderValue::from_static("12"))
);
}
#[test]
fn test_strip_hop_by_hop_response_headers_removes_connection_listed_extensions() {
let mut headers = HeaderMap::new();
headers.append(
axum::http::header::CONNECTION,
axum::http::HeaderValue::from_static("x-trace-hop, x-debug-hop"),
);
headers.append(
axum::http::header::CONNECTION,
axum::http::HeaderValue::from_static("upgrade"),
);
headers.insert(
axum::http::header::HeaderName::from_static("x-trace-hop"),
axum::http::HeaderValue::from_static("trace"),
);
headers.insert(
axum::http::header::HeaderName::from_static("x-debug-hop"),
axum::http::HeaderValue::from_static("debug"),
);
headers.insert(
axum::http::header::UPGRADE,
axum::http::HeaderValue::from_static("websocket"),
);
headers.insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("text/event-stream"),
);
strip_hop_by_hop_response_headers(&mut headers);
assert!(!headers.contains_key(axum::http::header::CONNECTION));
assert!(!headers.contains_key("x-trace-hop"));
assert!(!headers.contains_key("x-debug-hop"));
assert!(!headers.contains_key(axum::http::header::UPGRADE));
assert_eq!(
headers.get(axum::http::header::CONTENT_TYPE),
Some(&axum::http::HeaderValue::from_static("text/event-stream"))
);
}
fn build_state(db: Arc<Database>) -> ProxyState { fn build_state(db: Arc<Database>) -> ProxyState {
ProxyState { ProxyState {
db: db.clone(), db: db.clone(),
@@ -907,7 +784,6 @@ mod tests {
cache_read_tokens: 0, cache_read_tokens: 0,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model: None, model: None,
message_id: None,
}; };
log_usage_internal( log_usage_internal(
@@ -967,7 +843,6 @@ mod tests {
cache_read_tokens: 0, cache_read_tokens: 0,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model: None, model: None,
message_id: None,
}; };
log_usage_internal( log_usage_internal(
+7
View File
@@ -23,6 +23,7 @@ use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::{oneshot, RwLock}; use tokio::sync::{oneshot, RwLock};
use tokio::task::JoinHandle; use tokio::task::JoinHandle;
use tower_http::cors::{Any, CorsLayer};
/// 代理服务器状态(共享) /// 代理服务器状态(共享)
#[derive(Clone)] #[derive(Clone)]
@@ -274,6 +275,11 @@ impl ProxyServer {
} }
fn build_router(&self) -> Router { fn build_router(&self) -> Router {
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
Router::new() Router::new()
// 健康检查 // 健康检查
.route("/health", get(handlers::health_check)) .route("/health", get(handlers::health_check))
@@ -322,6 +328,7 @@ impl ProxyServer {
.route("/gemini/v1beta/*path", post(handlers::handle_gemini)) .route("/gemini/v1beta/*path", post(handlers::handle_gemini))
// 提高默认请求体大小限制(避免 413 Payload Too Large // 提高默认请求体大小限制(避免 413 Payload Too Large
.layer(DefaultBodyLimit::max(200 * 1024 * 1024)) .layer(DefaultBodyLimit::max(200 * 1024 * 1024))
.layer(cors)
.with_state(self.state.clone()) .with_state(self.state.clone())
} }
+1 -1
View File
@@ -337,7 +337,7 @@ fn extract_from_metadata(body: &serde_json::Value) -> Option<SessionIdResult> {
/// 从 user_id 解析 session_id /// 从 user_id 解析 session_id
/// ///
/// 格式: `user_identifier_session_actual_session_id` /// 格式: `user_identifier_session_actual_session_id`
pub(super) fn parse_session_from_user_id(user_id: &str) -> Option<String> { fn parse_session_from_user_id(user_id: &str) -> Option<String> {
// 查找 "_session_" 分隔符 // 查找 "_session_" 分隔符
if let Some(pos) = user_id.find("_session_") { if let Some(pos) = user_id.find("_session_") {
let session_id = &user_id[pos + 9..]; // "_session_" 长度为 9 let session_id = &user_id[pos + 9..]; // "_session_" 长度为 9
+4 -9
View File
@@ -291,12 +291,8 @@ pub struct CopilotOptimizerConfig {
/// 确定性 Request ID(默认开启,P3 优先级) /// 确定性 Request ID(默认开启,P3 优先级)
#[serde(default = "default_true")] #[serde(default = "default_true")]
pub deterministic_request_id: bool, pub deterministic_request_id: bool,
/// Subagent 检测(默认开启)— 识别 Claude Code 子代理请求, /// Warmup 小模型降级(默认关闭,P4 优先级,opt-in)
/// 设置 x-initiator=agent + x-interaction-type=conversation-subagent,避免子代理计费 #[serde(default)]
#[serde(default = "default_true")]
pub subagent_detection: bool,
/// Warmup 小模型降级(默认开启 — 与参考实现对齐,避免探针请求消耗 premium quota
#[serde(default = "default_true")]
pub warmup_downgrade: bool, pub warmup_downgrade: bool,
/// Warmup 降级使用的模型(默认 "gpt-4o-mini" /// Warmup 降级使用的模型(默认 "gpt-4o-mini"
#[serde(default = "default_warmup_model")] #[serde(default = "default_warmup_model")]
@@ -304,7 +300,7 @@ pub struct CopilotOptimizerConfig {
} }
fn default_warmup_model() -> String { fn default_warmup_model() -> String {
"gpt-5-mini".to_string() "gpt-4o-mini".to_string()
} }
impl Default for CopilotOptimizerConfig { impl Default for CopilotOptimizerConfig {
@@ -315,8 +311,7 @@ impl Default for CopilotOptimizerConfig {
tool_result_merging: true, tool_result_merging: true,
compact_detection: true, compact_detection: true,
deterministic_request_id: true, deterministic_request_id: true,
subagent_detection: true, warmup_downgrade: false,
warmup_downgrade: true,
warmup_model: "gpt-4o-mini".to_string(), warmup_model: "gpt-4o-mini".to_string(),
} }
} }
-4
View File
@@ -114,7 +114,6 @@ mod tests {
cache_read_tokens: 200, cache_read_tokens: 200,
cache_creation_tokens: 100, cache_creation_tokens: 100,
model: None, model: None,
message_id: None,
}; };
let pricing = ModelPricing::from_strings("3.0", "15.0", "0.3", "3.75").unwrap(); let pricing = ModelPricing::from_strings("3.0", "15.0", "0.3", "3.75").unwrap();
@@ -145,7 +144,6 @@ mod tests {
cache_read_tokens: 0, cache_read_tokens: 0,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model: None, model: None,
message_id: None,
}; };
let pricing = ModelPricing::from_strings("3.0", "15.0", "0", "0").unwrap(); let pricing = ModelPricing::from_strings("3.0", "15.0", "0", "0").unwrap();
@@ -167,7 +165,6 @@ mod tests {
cache_read_tokens: 0, cache_read_tokens: 0,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model: None, model: None,
message_id: None,
}; };
let multiplier = Decimal::from_str("1.0").unwrap(); let multiplier = Decimal::from_str("1.0").unwrap();
@@ -184,7 +181,6 @@ mod tests {
cache_read_tokens: 1, cache_read_tokens: 1,
cache_creation_tokens: 1, cache_creation_tokens: 1,
model: None, model: None,
message_id: None,
}; };
let pricing = ModelPricing::from_strings("0.075", "0.3", "0.01875", "0.075").unwrap(); let pricing = ModelPricing::from_strings("0.075", "0.3", "0.01875", "0.075").unwrap();
+1 -2
View File
@@ -73,7 +73,7 @@ impl<'a> UsageLogger<'a> {
}); });
conn.execute( conn.execute(
"INSERT OR REPLACE INTO proxy_request_logs ( "INSERT INTO proxy_request_logs (
request_id, provider_id, app_type, model, request_model, request_id, provider_id, app_type, model, request_model,
input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens,
input_cost_usd, output_cost_usd, cache_read_cost_usd, cache_creation_cost_usd, total_cost_usd, input_cost_usd, output_cost_usd, cache_read_cost_usd, cache_creation_cost_usd, total_cost_usd,
@@ -358,7 +358,6 @@ mod tests {
cache_read_tokens: 0, cache_read_tokens: 0,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model: None, model: None,
message_id: None,
}; };
logger.log_with_calculation( logger.log_with_calculation(
+2 -38
View File
@@ -9,9 +9,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
/// Session 日志 request_id 前缀,与 `session_usage.rs` 中的格式保持一致
pub const SESSION_REQUEST_ID_PREFIX: &str = "session:";
/// Token 使用量统计 /// Token 使用量统计
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TokenUsage { pub struct TokenUsage {
@@ -21,22 +18,6 @@ pub struct TokenUsage {
pub cache_creation_tokens: u32, pub cache_creation_tokens: u32,
/// 从响应中提取的实际模型名称(如果可用) /// 从响应中提取的实际模型名称(如果可用)
pub model: Option<String>, pub model: Option<String>,
/// 从响应中提取的消息 ID(用于跨源去重)
///
/// Claude API: `msg_xxx`,与 session JSONL 中的 `message.id` 一致
#[serde(skip)]
pub message_id: Option<String>,
}
impl TokenUsage {
/// 生成与 session 日志共享的 request_id,用于跨源去重。
/// 有 message_id 时返回 `session:{id}`,否则回退到随机 UUID。
pub fn dedup_request_id(&self) -> String {
self.message_id
.as_ref()
.map(|mid| format!("{SESSION_REQUEST_ID_PREFIX}{mid}"))
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string())
}
} }
/// API 类型 /// API 类型
@@ -58,10 +39,6 @@ impl TokenUsage {
.get("model") .get("model")
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.map(|s| s.to_string()); .map(|s| s.to_string());
let message_id = body
.get("id")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
Some(Self { Some(Self {
input_tokens: usage.get("input_tokens")?.as_u64()? as u32, input_tokens: usage.get("input_tokens")?.as_u64()? as u32,
@@ -75,7 +52,6 @@ impl TokenUsage {
.and_then(|v| v.as_u64()) .and_then(|v| v.as_u64())
.unwrap_or(0) as u32, .unwrap_or(0) as u32,
model, model,
message_id,
}) })
} }
@@ -84,23 +60,18 @@ impl TokenUsage {
pub fn from_claude_stream_events(events: &[Value]) -> Option<Self> { pub fn from_claude_stream_events(events: &[Value]) -> Option<Self> {
let mut usage = Self::default(); let mut usage = Self::default();
let mut model: Option<String> = None; let mut model: Option<String> = None;
let mut message_id: Option<String> = None;
for event in events { for event in events {
if let Some(event_type) = event.get("type").and_then(|v| v.as_str()) { if let Some(event_type) = event.get("type").and_then(|v| v.as_str()) {
match event_type { match event_type {
"message_start" => { "message_start" => {
if let Some(message) = event.get("message") { // 从 message_start 提取模型名称
if model.is_none() { if model.is_none() {
if let Some(message) = event.get("message") {
if let Some(m) = message.get("model").and_then(|v| v.as_str()) { if let Some(m) = message.get("model").and_then(|v| v.as_str()) {
model = Some(m.to_string()); model = Some(m.to_string());
} }
} }
if message_id.is_none() {
if let Some(id) = message.get("id").and_then(|v| v.as_str()) {
message_id = Some(id.to_string());
}
}
} }
if let Some(msg_usage) = event.get("message").and_then(|m| m.get("usage")) { if let Some(msg_usage) = event.get("message").and_then(|m| m.get("usage")) {
// 从 message_start 获取 input_tokens(原生 Claude API // 从 message_start 获取 input_tokens(原生 Claude API
@@ -166,7 +137,6 @@ impl TokenUsage {
if usage.input_tokens > 0 || usage.output_tokens > 0 { if usage.input_tokens > 0 || usage.output_tokens > 0 {
usage.model = model; usage.model = model;
usage.message_id = message_id;
Some(usage) Some(usage)
} else { } else {
None None
@@ -183,7 +153,6 @@ impl TokenUsage {
cache_read_tokens: 0, cache_read_tokens: 0,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model: None, model: None,
message_id: None,
}) })
} }
@@ -233,7 +202,6 @@ impl TokenUsage {
.and_then(|v| v.as_u64()) .and_then(|v| v.as_u64())
.unwrap_or(0) as u32, .unwrap_or(0) as u32,
model, model,
message_id: None,
}) })
} }
@@ -277,7 +245,6 @@ impl TokenUsage {
.and_then(|v| v.as_u64()) .and_then(|v| v.as_u64())
.unwrap_or(0) as u32, .unwrap_or(0) as u32,
model, model,
message_id: None,
}) })
} }
@@ -372,7 +339,6 @@ impl TokenUsage {
cache_read_tokens: cached_tokens, cache_read_tokens: cached_tokens,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model, model,
message_id: None,
}) })
} }
@@ -417,7 +383,6 @@ impl TokenUsage {
.unwrap_or(0) as u32, .unwrap_or(0) as u32,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model, model,
message_id: None,
}) })
} }
@@ -468,7 +433,6 @@ impl TokenUsage {
cache_read_tokens: total_cache_read, cache_read_tokens: total_cache_read,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model, model,
message_id: None,
}) })
} else { } else {
None None
+1 -1
View File
@@ -41,7 +41,7 @@ pub async fn fetch_models(
} }
let models_url = build_models_url(base_url, is_full_url)?; let models_url = build_models_url(base_url, is_full_url)?;
let client = crate::proxy::http_client::get(); let client = crate::proxy::http_client::get_for_provider(None);
let response = client let response = client
.get(&models_url) .get(&models_url)
+10 -5
View File
@@ -1099,7 +1099,7 @@ pub(crate) fn write_gemini_live(provider: &Provider) -> Result<(), AppError> {
// One-time auth type detection to avoid repeated detection // One-time auth type detection to avoid repeated detection
let auth_type = detect_gemini_auth_type(provider); let auth_type = detect_gemini_auth_type(provider);
let env_map = json_to_env(&provider.settings_config)?; let mut env_map = json_to_env(&provider.settings_config)?;
// Prepare config to write to ~/.gemini/settings.json // Prepare config to write to ~/.gemini/settings.json
// Behavior: // Behavior:
@@ -1143,12 +1143,17 @@ pub(crate) fn write_gemini_live(provider: &Provider) -> Result<(), AppError> {
match auth_type { match auth_type {
GeminiAuthType::GoogleOfficial => { GeminiAuthType::GoogleOfficial => {
// Google Official uses OAuth, no API key validation needed. // Google official uses OAuth, clear env
// Write user's env vars as-is (e.g. GEMINI_MODEL, custom vars). env_map.clear();
write_gemini_env_atomic(&env_map)?; write_gemini_env_atomic(&env_map)?;
} }
GeminiAuthType::Packycode | GeminiAuthType::Generic => { GeminiAuthType::Packycode => {
// API Key mode -- require GEMINI_API_KEY // PackyCode provider, uses API Key (strict validation on switch)
validate_gemini_settings_strict(&provider.settings_config)?;
write_gemini_env_atomic(&env_map)?;
}
GeminiAuthType::Generic => {
// Generic provider, uses API Key (strict validation on switch)
validate_gemini_settings_strict(&provider.settings_config)?; validate_gemini_settings_strict(&provider.settings_config)?;
write_gemini_env_atomic(&env_map)?; write_gemini_env_atomic(&env_map)?;
} }
-10
View File
@@ -1407,16 +1407,6 @@ impl ProviderService {
// Hot-switch only when BOTH: this app is taken over AND proxy server is actually running // Hot-switch only when BOTH: this app is taken over AND proxy server is actually running
let should_hot_switch = (is_app_taken_over || live_taken_over) && is_proxy_running; let should_hot_switch = (is_app_taken_over || live_taken_over) && is_proxy_running;
// Block switching to official providers when proxy takeover is active.
// Using a proxy with official APIs (Anthropic/OpenAI/Google) may cause account bans.
if should_hot_switch && _provider.category.as_deref() == Some("official") {
return Err(AppError::localized(
"switch.official_blocked_by_proxy",
"代理接管模式下不能切换到官方供应商,使用代理访问官方 API 可能导致账号被封禁。请先关闭代理接管,或选择第三方供应商。",
"Cannot switch to official provider while proxy takeover is active. Using proxy with official APIs may cause account bans.",
));
}
if should_hot_switch { if should_hot_switch {
// Proxy takeover mode: hot-switch only, don't write Live config // Proxy takeover mode: hot-switch only, don't write Live config
log::info!( log::info!(
-29
View File
@@ -15,7 +15,6 @@ use crate::services::provider::{
use serde_json::{json, Value}; use serde_json::{json, Value};
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use tauri::Emitter;
use tokio::sync::RwLock; use tokio::sync::RwLock;
/// 用于接管 Live 配置时的占位符(避免客户端提示缺少 key,同时不泄露真实 Token) /// 用于接管 Live 配置时的占位符(避免客户端提示缺少 key,同时不泄露真实 Token)
@@ -376,26 +375,6 @@ impl ProxyService {
// 7) 兼容旧逻辑:写入 any-of 标志(失败不影响功能) // 7) 兼容旧逻辑:写入 any-of 标志(失败不影响功能)
let _ = self.db.set_live_takeover_active(true).await; let _ = self.db.set_live_takeover_active(true).await;
// 8) Warn if the current provider is official (risk of account ban via proxy)
if let Ok(Some(current_id)) =
crate::settings::get_effective_current_provider(&self.db, &app)
{
if let Ok(Some(provider)) = self.db.get_provider_by_id(&current_id, app_type_str) {
if provider.category.as_deref() == Some("official") {
if let Some(handle) = self.app_handle.read().await.as_ref() {
let _ = handle.emit(
"proxy-official-warning",
serde_json::json!({
"appType": app_type_str,
"providerName": provider.name,
}),
);
}
}
}
}
return Ok(()); return Ok(());
} }
@@ -1569,14 +1548,6 @@ impl ProxyService {
.map_err(|e| format!("读取供应商失败: {e}"))? .map_err(|e| format!("读取供应商失败: {e}"))?
.ok_or_else(|| format!("供应商不存在: {provider_id}"))?; .ok_or_else(|| format!("供应商不存在: {provider_id}"))?;
// Defense-in-depth: block official providers during proxy takeover
if provider.category.as_deref() == Some("official") {
return Err(
"代理接管模式下不能切换到官方供应商 (Cannot switch to official provider during proxy takeover)"
.to_string(),
);
}
let logical_target_changed = let logical_target_changed =
crate::settings::get_effective_current_provider(&self.db, &app_type_enum) crate::settings::get_effective_current_provider(&self.db, &app_type_enum)
.map_err(|e| format!("读取当前供应商失败: {e}"))? .map_err(|e| format!("读取当前供应商失败: {e}"))?
+1 -6
View File
@@ -278,11 +278,7 @@ fn sync_single_file(db: &Database, file_path: &Path) -> Result<(u32, u32), AppEr
continue; continue;
} }
let request_id = format!( let request_id = format!("session:{}", msg.message_id);
"{}{}",
crate::proxy::usage::parser::SESSION_REQUEST_ID_PREFIX,
msg.message_id
);
// 跳过 output_tokens 为 0 的无意义条目 // 跳过 output_tokens 为 0 的无意义条目
if msg.output_tokens == 0 { if msg.output_tokens == 0 {
@@ -383,7 +379,6 @@ fn insert_session_log_entry(
cache_read_tokens: msg.cache_read_tokens, cache_read_tokens: msg.cache_read_tokens,
cache_creation_tokens: msg.cache_creation_tokens, cache_creation_tokens: msg.cache_creation_tokens,
model: Some(msg.model.clone()), model: Some(msg.model.clone()),
message_id: None,
}; };
let pricing = find_model_pricing_for_session(&conn, &msg.model); let pricing = find_model_pricing_for_session(&conn, &msg.model);
@@ -474,7 +474,6 @@ fn insert_codex_session_entry(
cache_read_tokens: delta.cached_input, cache_read_tokens: delta.cached_input,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model: Some(model.to_string()), model: Some(model.to_string()),
message_id: None,
}; };
let pricing = find_codex_pricing(&conn, model); let pricing = find_codex_pricing(&conn, model);
@@ -261,7 +261,6 @@ fn insert_gemini_session_entry(
cache_read_tokens: tokens.cached, cache_read_tokens: tokens.cached,
cache_creation_tokens: 0, cache_creation_tokens: 0,
model: Some(model.to_string()), model: Some(model.to_string()),
message_id: None,
}; };
let pricing = find_gemini_pricing(&conn, model); let pricing = find_gemini_pricing(&conn, model);
-7
View File
@@ -680,13 +680,6 @@ impl SkillService {
found.display() found.display()
); );
source = found; source = found;
} else if temp_dir.join("SKILL.md").exists() {
// 根级 Skill:仓库本身就是 skillSKILL.md 直接在解压根目录
log::info!(
"Skill directory '{}' not found, but SKILL.md exists at root, using temp_dir",
target_name,
);
source = temp_dir.clone();
} else { } else {
let _ = fs::remove_dir_all(&temp_dir); let _ = fs::remove_dir_all(&temp_dir);
return Err(anyhow!(format_skill_error( return Err(anyhow!(format_skill_error(
+44 -60
View File
@@ -218,8 +218,9 @@ impl StreamCheckService {
.or_else(|| adapter.extract_auth(provider)) .or_else(|| adapter.extract_auth(provider))
.ok_or_else(|| AppError::Message("API Key not found".to_string()))?; .ok_or_else(|| AppError::Message("API Key not found".to_string()))?;
// 获取 HTTP 客户端 // 获取 HTTP 客户端:优先使用供应商单独代理配置,否则使用全局客户端
let client = crate::proxy::http_client::get(); let proxy_config = provider.meta.as_ref().and_then(|m| m.proxy_config.as_ref());
let client = crate::proxy::http_client::get_for_provider(proxy_config);
let request_timeout = std::time::Duration::from_secs(config.timeout_secs); let request_timeout = std::time::Duration::from_secs(config.timeout_secs);
let model_to_test = Self::resolve_test_model(app_type, provider, config); let model_to_test = Self::resolve_test_model(app_type, provider, config);
@@ -271,11 +272,34 @@ impl StreamCheckService {
}; };
let response_time = start.elapsed().as_millis() as u64; let response_time = start.elapsed().as_millis() as u64;
Ok(Self::build_stream_check_result( let tested_at = chrono::Utc::now().timestamp();
result,
response_time, match result {
config.degraded_threshold_ms, Ok((status_code, model)) => {
)) let health_status =
Self::determine_status(response_time, config.degraded_threshold_ms);
Ok(StreamCheckResult {
status: health_status,
success: true,
message: "Check succeeded".to_string(),
response_time_ms: Some(response_time),
http_status: Some(status_code),
model_used: model,
tested_at,
retry_count: 0,
})
}
Err(e) => Ok(StreamCheckResult {
status: HealthStatus::Failed,
success: false,
message: e.to_string(),
response_time_ms: Some(response_time),
http_status: None,
model_used: String::new(),
tested_at,
retry_count: 0,
}),
}
} }
/// Claude 流式检查 /// Claude 流式检查
@@ -348,7 +372,7 @@ impl StreamCheckService {
anthropic_to_responses(anthropic_body, Some(&provider.id), is_codex_oauth) anthropic_to_responses(anthropic_body, Some(&provider.id), is_codex_oauth)
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))? .map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
} else if is_openai_chat { } else if is_openai_chat {
anthropic_to_openai(anthropic_body) anthropic_to_openai(anthropic_body, Some(&provider.id))
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))? .map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
} else { } else {
anthropic_body anthropic_body
@@ -428,7 +452,8 @@ impl StreamCheckService {
.header("x-stainless-retry-count", "0") .header("x-stainless-retry-count", "0")
.header("x-stainless-timeout", "600") .header("x-stainless-timeout", "600")
// Other headers // Other headers
.header("sec-fetch-mode", "cors"); .header("sec-fetch-mode", "cors")
.header("connection", "keep-alive");
} }
// 供应商自定义 headers 最后追加,允许覆盖内置默认值(例如 user-agent // 供应商自定义 headers 最后追加,允许覆盖内置默认值(例如 user-agent
@@ -451,7 +476,7 @@ impl StreamCheckService {
if !response.status().is_success() { if !response.status().is_success() {
let error_text = response.text().await.unwrap_or_default(); let error_text = response.text().await.unwrap_or_default();
return Err(Self::http_status_error(status, error_text)); return Err(AppError::Message(format!("HTTP {status}: {error_text}")));
} }
// 流式读取:只需首个 chunk // 流式读取:只需首个 chunk
@@ -531,7 +556,7 @@ impl StreamCheckService {
if i == 0 && status == 404 && urls.len() > 1 { if i == 0 && status == 404 && urls.len() > 1 {
continue; continue;
} }
return Err(Self::http_status_error(status, error_text)); return Err(AppError::Message(format!("HTTP {status}: {error_text}")));
} }
let mut stream = response.bytes_stream(); let mut stream = response.bytes_stream();
@@ -606,7 +631,7 @@ impl StreamCheckService {
if !response.status().is_success() { if !response.status().is_success() {
let error_text = response.text().await.unwrap_or_default(); let error_text = response.text().await.unwrap_or_default();
return Err(Self::http_status_error(status, error_text)); return Err(AppError::Message(format!("HTTP {status}: {error_text}")));
} }
let mut stream = response.bytes_stream(); let mut stream = response.bytes_stream();
@@ -634,8 +659,9 @@ impl StreamCheckService {
config: &StreamCheckConfig, config: &StreamCheckConfig,
start: Instant, start: Instant,
) -> Result<StreamCheckResult, AppError> { ) -> Result<StreamCheckResult, AppError> {
// 获取 HTTP 客户端 // 获取 HTTP 客户端:优先使用供应商单独代理配置,否则使用全局客户端
let client = crate::proxy::http_client::get(); let proxy_config = provider.meta.as_ref().and_then(|m| m.proxy_config.as_ref());
let client = crate::proxy::http_client::get_for_provider(proxy_config);
let request_timeout = std::time::Duration::from_secs(config.timeout_secs); let request_timeout = std::time::Duration::from_secs(config.timeout_secs);
let model_to_test = Self::resolve_test_model(app_type, provider, config); let model_to_test = Self::resolve_test_model(app_type, provider, config);
@@ -693,25 +719,16 @@ impl StreamCheckService {
tested_at, tested_at,
retry_count: 0, retry_count: 0,
}, },
Err(e) => { Err(e) => StreamCheckResult {
let (http_status, message) = match &e {
AppError::HttpStatus { status, .. } => (
Some(*status),
Self::classify_http_status(*status).to_string(),
),
_ => (None, e.to_string()),
};
StreamCheckResult {
status: HealthStatus::Failed, status: HealthStatus::Failed,
success: false, success: false,
message, message: e.to_string(),
response_time_ms: Some(response_time), response_time_ms: Some(response_time),
http_status, http_status: None,
model_used: String::new(), model_used: String::new(),
tested_at, tested_at,
retry_count: 0, retry_count: 0,
} },
}
} }
} }
@@ -1109,39 +1126,6 @@ impl StreamCheckService {
} }
} }
/// 构造 HTTP 状态码错误,截断过长的响应体
fn http_status_error(status: u16, body: String) -> AppError {
let body = if body.len() > 200 {
// 安全截断:找到 200 字节内最近的 char 边界
let mut end = 200;
while end > 0 && !body.is_char_boundary(end) {
end -= 1;
}
format!("{}", &body[..end])
} else {
body
};
AppError::HttpStatus { status, body }
}
/// 将 HTTP 状态码映射为简短的分类标签
pub(crate) fn classify_http_status(status: u16) -> &'static str {
match status {
400 => "Bad request (400)",
401 => "Auth rejected (401)",
402 => "Payment required (402)",
403 => "Access denied (403)",
404 => "Not found (404)",
429 => "Rate limited (429)",
500 => "Internal server error (500)",
502 => "Bad gateway (502)",
503 => "Service unavailable (503)",
504 => "Gateway timeout (504)",
s if (500..600).contains(&s) => "Server error",
_ => "HTTP error",
}
}
fn resolve_test_model( fn resolve_test_model(
app_type: &AppType, app_type: &AppType,
provider: &Provider, provider: &Provider,
+32 -167
View File
@@ -275,9 +275,14 @@ impl Database {
let mut bucket_count: i64 = if duration <= 0 { let mut bucket_count: i64 = if duration <= 0 {
1 1
} else { } else {
(duration + bucket_seconds - 1) / bucket_seconds ((duration as f64) / bucket_seconds as f64).ceil() as i64
}; };
// 固定 24 小时窗口为 24 个小时桶,避免浮点误差
if bucket_seconds == 60 * 60 {
bucket_count = 24;
}
if bucket_count < 1 { if bucket_count < 1 {
bucket_count = 1; bucket_count = 1;
} }
@@ -448,50 +453,14 @@ impl Database {
/// 获取 Provider 统计 /// 获取 Provider 统计
pub fn get_provider_stats( pub fn get_provider_stats(
&self, &self,
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<&str>, app_type: Option<&str>,
) -> Result<Vec<ProviderStats>, AppError> { ) -> Result<Vec<ProviderStats>, AppError> {
let conn = lock_conn!(self.conn); let conn = lock_conn!(self.conn);
let mut detail_conditions = Vec::new(); let (detail_where, rollup_where) = if app_type.is_some() {
let mut detail_params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new(); ("WHERE l.app_type = ?1", "WHERE r.app_type = ?2")
if let Some(start) = start_date {
detail_conditions.push("l.created_at >= ?");
detail_params.push(Box::new(start));
}
if let Some(end) = end_date {
detail_conditions.push("l.created_at <= ?");
detail_params.push(Box::new(end));
}
if let Some(at) = app_type {
detail_conditions.push("l.app_type = ?");
detail_params.push(Box::new(at.to_string()));
}
let detail_where = if detail_conditions.is_empty() {
String::new()
} else { } else {
format!("WHERE {}", detail_conditions.join(" AND ")) ("", "")
};
let mut rollup_conditions = Vec::new();
let mut rollup_params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
if let Some(start) = start_date {
rollup_conditions.push("r.date >= date(?, 'unixepoch', 'localtime')".to_string());
rollup_params.push(Box::new(start));
}
if let Some(end) = end_date {
rollup_conditions.push("r.date <= date(?, 'unixepoch', 'localtime')".to_string());
rollup_params.push(Box::new(end));
}
if let Some(at) = app_type {
rollup_conditions.push("r.app_type = ?".to_string());
rollup_params.push(Box::new(at.to_string()));
}
let rollup_where = if rollup_conditions.is_empty() {
String::new()
} else {
format!("WHERE {}", rollup_conditions.join(" AND "))
}; };
// UNION detail logs + rollup data, then aggregate // UNION detail logs + rollup data, then aggregate
@@ -537,9 +506,6 @@ impl Database {
); );
let mut stmt = conn.prepare(&sql)?; let mut stmt = conn.prepare(&sql)?;
let mut params: Vec<Box<dyn rusqlite::ToSql>> = detail_params;
params.extend(rollup_params);
let param_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
let row_mapper = |row: &rusqlite::Row| { let row_mapper = |row: &rusqlite::Row| {
let request_count: i64 = row.get(3)?; let request_count: i64 = row.get(3)?;
let success_count: i64 = row.get(6)?; let success_count: i64 = row.get(6)?;
@@ -560,7 +526,11 @@ impl Database {
}) })
}; };
let rows = stmt.query_map(param_refs.as_slice(), row_mapper)?; let rows = if let Some(at) = app_type {
stmt.query_map(params![at, at], row_mapper)?
} else {
stmt.query_map([], row_mapper)?
};
let mut stats = Vec::new(); let mut stats = Vec::new();
for row in rows { for row in rows {
@@ -571,52 +541,13 @@ impl Database {
} }
/// 获取模型统计 /// 获取模型统计
pub fn get_model_stats( pub fn get_model_stats(&self, app_type: Option<&str>) -> Result<Vec<ModelStats>, AppError> {
&self,
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<&str>,
) -> Result<Vec<ModelStats>, AppError> {
let conn = lock_conn!(self.conn); let conn = lock_conn!(self.conn);
let mut detail_conditions = Vec::new(); let (detail_where, rollup_where) = if app_type.is_some() {
let mut detail_params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new(); ("WHERE app_type = ?1", "WHERE app_type = ?2")
if let Some(start) = start_date {
detail_conditions.push("l.created_at >= ?");
detail_params.push(Box::new(start));
}
if let Some(end) = end_date {
detail_conditions.push("l.created_at <= ?");
detail_params.push(Box::new(end));
}
if let Some(at) = app_type {
detail_conditions.push("l.app_type = ?");
detail_params.push(Box::new(at.to_string()));
}
let detail_where = if detail_conditions.is_empty() {
String::new()
} else { } else {
format!("WHERE {}", detail_conditions.join(" AND ")) ("", "")
};
let mut rollup_conditions = Vec::new();
let mut rollup_params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
if let Some(start) = start_date {
rollup_conditions.push("r.date >= date(?, 'unixepoch', 'localtime')".to_string());
rollup_params.push(Box::new(start));
}
if let Some(end) = end_date {
rollup_conditions.push("r.date <= date(?, 'unixepoch', 'localtime')".to_string());
rollup_params.push(Box::new(end));
}
if let Some(at) = app_type {
rollup_conditions.push("r.app_type = ?".to_string());
rollup_params.push(Box::new(at.to_string()));
}
let rollup_where = if rollup_conditions.is_empty() {
String::new()
} else {
format!("WHERE {}", rollup_conditions.join(" AND "))
}; };
// UNION detail logs + rollup data // UNION detail logs + rollup data
@@ -627,30 +558,27 @@ impl Database {
SUM(total_tokens) as total_tokens, SUM(total_tokens) as total_tokens,
SUM(total_cost) as total_cost SUM(total_cost) as total_cost
FROM ( FROM (
SELECT l.model, SELECT model,
COUNT(*) as request_count, COUNT(*) as request_count,
COALESCE(SUM(l.input_tokens + l.output_tokens), 0) as total_tokens, COALESCE(SUM(input_tokens + output_tokens), 0) as total_tokens,
COALESCE(SUM(CAST(l.total_cost_usd AS REAL)), 0) as total_cost COALESCE(SUM(CAST(total_cost_usd AS REAL)), 0) as total_cost
FROM proxy_request_logs l FROM proxy_request_logs
{detail_where} {detail_where}
GROUP BY l.model GROUP BY model
UNION ALL UNION ALL
SELECT r.model, SELECT model,
COALESCE(SUM(request_count), 0), COALESCE(SUM(request_count), 0),
COALESCE(SUM(input_tokens + output_tokens), 0), COALESCE(SUM(input_tokens + output_tokens), 0),
COALESCE(SUM(CAST(total_cost_usd AS REAL)), 0) COALESCE(SUM(CAST(total_cost_usd AS REAL)), 0)
FROM usage_daily_rollups r FROM usage_daily_rollups
{rollup_where} {rollup_where}
GROUP BY r.model GROUP BY model
) )
GROUP BY model GROUP BY model
ORDER BY total_cost DESC" ORDER BY total_cost DESC"
); );
let mut stmt = conn.prepare(&sql)?; let mut stmt = conn.prepare(&sql)?;
let mut params: Vec<Box<dyn rusqlite::ToSql>> = detail_params;
params.extend(rollup_params);
let param_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
let row_mapper = |row: &rusqlite::Row| { let row_mapper = |row: &rusqlite::Row| {
let request_count: i64 = row.get(1)?; let request_count: i64 = row.get(1)?;
let total_cost: f64 = row.get(3)?; let total_cost: f64 = row.get(3)?;
@@ -669,7 +597,11 @@ impl Database {
}) })
}; };
let rows = stmt.query_map(param_refs.as_slice(), row_mapper)?; let rows = if let Some(at) = app_type {
stmt.query_map(params![at, at], row_mapper)?
} else {
stmt.query_map([], row_mapper)?
};
let mut stats = Vec::new(); let mut stats = Vec::new();
for row in rows { for row in rows {
@@ -1236,7 +1168,7 @@ mod tests {
)?; )?;
} }
let stats = db.get_model_stats(None, None, None)?; let stats = db.get_model_stats(None)?;
assert_eq!(stats.len(), 1); assert_eq!(stats.len(), 1);
assert_eq!(stats[0].model, "claude-3-sonnet"); assert_eq!(stats[0].model, "claude-3-sonnet");
assert_eq!(stats[0].request_count, 1); assert_eq!(stats[0].request_count, 1);
@@ -1244,73 +1176,6 @@ mod tests {
Ok(()) Ok(())
} }
#[test]
fn test_get_provider_stats_with_time_filter() -> Result<(), AppError> {
let db = Database::memory()?;
{
let conn = lock_conn!(db.conn);
conn.execute(
"INSERT INTO proxy_request_logs (
request_id, provider_id, app_type, model,
input_tokens, output_tokens, total_cost_usd,
latency_ms, status_code, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
params!["old", "p1", "claude", "claude-3", 100, 50, "0.01", 100, 200, 1000],
)?;
conn.execute(
"INSERT INTO proxy_request_logs (
request_id, provider_id, app_type, model,
input_tokens, output_tokens, total_cost_usd,
latency_ms, status_code, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
params!["new", "p1", "claude", "claude-3", 200, 75, "0.02", 120, 200, 2000],
)?;
}
let stats = db.get_provider_stats(Some(1500), Some(2500), Some("claude"))?;
assert_eq!(stats.len(), 1);
assert_eq!(stats[0].provider_id, "p1");
assert_eq!(stats[0].request_count, 1);
assert_eq!(stats[0].total_tokens, 275);
Ok(())
}
#[test]
fn test_get_daily_trends_respects_shorter_than_24_hours() -> Result<(), AppError> {
let db = Database::memory()?;
{
let conn = lock_conn!(db.conn);
conn.execute(
"INSERT INTO proxy_request_logs (
request_id, provider_id, app_type, model,
input_tokens, output_tokens, total_cost_usd,
latency_ms, status_code, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
params![
"req-short",
"p1",
"claude",
"claude-3",
100,
50,
"0.01",
100,
200,
10_800
],
)?;
}
let stats = db.get_daily_trends(Some(0), Some(15 * 60 * 60), Some("claude"))?;
assert_eq!(stats.len(), 15);
assert_eq!(stats[3].request_count, 1);
Ok(())
}
#[test] #[test]
fn test_model_pricing_matching() -> Result<(), AppError> { fn test_model_pricing_matching() -> Result<(), AppError> {
let db = Database::memory()?; let db = Database::memory()?;
@@ -9,10 +9,10 @@ use crate::session_manager::{SessionMessage, SessionMeta};
use super::utils::{ use super::utils::{
extract_text, parse_timestamp_to_ms, path_basename, read_head_tail_lines, truncate_summary, extract_text, parse_timestamp_to_ms, path_basename, read_head_tail_lines, truncate_summary,
TITLE_MAX_CHARS,
}; };
const PROVIDER_ID: &str = "claude"; const PROVIDER_ID: &str = "claude";
const TITLE_MAX_CHARS: usize = 80;
pub fn scan_sessions() -> Vec<SessionMeta> { pub fn scan_sessions() -> Vec<SessionMeta> {
let root = get_claude_config_dir().join("projects"); let root = get_claude_config_dir().join("projects");
@@ -11,7 +11,6 @@ use crate::session_manager::{SessionMessage, SessionMeta};
use super::utils::{ use super::utils::{
extract_text, parse_timestamp_to_ms, path_basename, read_head_tail_lines, truncate_summary, extract_text, parse_timestamp_to_ms, path_basename, read_head_tail_lines, truncate_summary,
TITLE_MAX_CHARS,
}; };
const PROVIDER_ID: &str = "codex"; const PROVIDER_ID: &str = "codex";
@@ -130,9 +129,8 @@ fn parse_session(path: &Path) -> Option<SessionMeta> {
let mut session_id: Option<String> = None; let mut session_id: Option<String> = None;
let mut project_dir: Option<String> = None; let mut project_dir: Option<String> = None;
let mut created_at: Option<i64> = None; let mut created_at: Option<i64> = None;
let mut first_user_message: Option<String> = None;
// Extract metadata and first user message from head lines // Extract metadata from head lines
for line in &head { for line in &head {
let value: Value = match serde_json::from_str(line) { let value: Value = match serde_json::from_str(line) {
Ok(parsed) => parsed, Ok(parsed) => parsed,
@@ -160,29 +158,6 @@ fn parse_session(path: &Path) -> Option<SessionMeta> {
} }
} }
} }
// Extract first user message as title candidate
if first_user_message.is_none()
&& value.get("type").and_then(Value::as_str) == Some("response_item")
{
if let Some(payload) = value.get("payload") {
if payload.get("type").and_then(Value::as_str) == Some("message")
&& payload.get("role").and_then(Value::as_str) == Some("user")
{
let text = payload.get("content").map(extract_text).unwrap_or_default();
let trimmed = text.trim();
if !trimmed.is_empty() && !trimmed.starts_with("# AGENTS.md") {
first_user_message = Some(trimmed.to_string());
}
}
}
}
if session_id.is_some()
&& project_dir.is_some()
&& created_at.is_some()
&& first_user_message.is_some()
{
break;
}
} }
// Extract last_active_at and summary from tail lines (reverse order) // Extract last_active_at and summary from tail lines (reverse order)
@@ -215,14 +190,10 @@ fn parse_session(path: &Path) -> Option<SessionMeta> {
let session_id = session_id.or_else(|| infer_session_id_from_filename(path)); let session_id = session_id.or_else(|| infer_session_id_from_filename(path));
let session_id = session_id?; let session_id = session_id?;
let title = first_user_message let title = project_dir
.map(|t| truncate_summary(&t, TITLE_MAX_CHARS))
.or_else(|| {
project_dir
.as_deref() .as_deref()
.and_then(path_basename) .and_then(path_basename)
.map(|v| v.to_string()) .map(|value| value.to_string());
});
let summary = summary.map(|text| truncate_summary(&text, 160)); let summary = summary.map(|text| truncate_summary(&text, 160));
@@ -290,82 +261,6 @@ mod tests {
assert!(!path.exists()); assert!(!path.exists());
} }
#[test]
fn parse_session_uses_first_user_message_as_title() {
let temp = tempdir().expect("tempdir");
let path = temp.path().join("session.jsonl");
std::fs::write(
&path,
concat!(
"{\"timestamp\":\"2026-03-06T21:50:12Z\",\"type\":\"session_meta\",\"payload\":{\"id\":\"test-id\",\"cwd\":\"/tmp/project\"}}\n",
"{\"timestamp\":\"2026-03-06T21:50:13Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"user\",\"content\":\"How do I deploy?\"}}\n",
"{\"timestamp\":\"2026-03-06T21:50:14Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"assistant\",\"content\":\"Here is how...\"}}\n"
),
)
.expect("write");
let meta = parse_session(&path).unwrap();
assert_eq!(meta.title.as_deref(), Some("How do I deploy?"));
}
#[test]
fn parse_session_skips_agents_md_injection() {
let temp = tempdir().expect("tempdir");
let path = temp.path().join("session.jsonl");
std::fs::write(
&path,
concat!(
"{\"timestamp\":\"2026-03-06T21:50:12Z\",\"type\":\"session_meta\",\"payload\":{\"id\":\"test-id\",\"cwd\":\"/tmp/project\"}}\n",
"{\"timestamp\":\"2026-03-06T21:50:13Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"developer\",\"content\":\"<permissions>\"}}\n",
"{\"timestamp\":\"2026-03-06T21:50:13Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"user\",\"content\":\"# AGENTS.md instructions for /tmp/project\\n<INSTRUCTIONS>Do stuff</INSTRUCTIONS>\"}}\n",
"{\"timestamp\":\"2026-03-06T21:50:14Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"user\",\"content\":\"Fix the login bug\"}}\n"
),
)
.expect("write");
let meta = parse_session(&path).unwrap();
// Should skip AGENTS.md injection and use the real user message
assert_eq!(meta.title.as_deref(), Some("Fix the login bug"));
}
#[test]
fn parse_session_falls_back_to_dir_basename() {
let temp = tempdir().expect("tempdir");
let path = temp.path().join("session.jsonl");
std::fs::write(
&path,
concat!(
"{\"timestamp\":\"2026-03-06T21:50:12Z\",\"type\":\"session_meta\",\"payload\":{\"id\":\"test-id\",\"cwd\":\"/tmp/my-project\"}}\n",
"{\"timestamp\":\"2026-03-06T21:50:13Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"assistant\",\"content\":\"Hello\"}}\n"
),
)
.expect("write");
let meta = parse_session(&path).unwrap();
// No user message → falls back to dir basename
assert_eq!(meta.title.as_deref(), Some("my-project"));
}
#[test]
fn parse_session_truncates_long_title() {
let temp = tempdir().expect("tempdir");
let path = temp.path().join("session.jsonl");
let long_msg = "a".repeat(200);
std::fs::write(
&path,
format!(
"{{\"timestamp\":\"2026-03-06T21:50:12Z\",\"type\":\"session_meta\",\"payload\":{{\"id\":\"test-id\",\"cwd\":\"/tmp/p\"}}}}\n\
{{\"timestamp\":\"2026-03-06T21:50:13Z\",\"type\":\"response_item\",\"payload\":{{\"type\":\"message\",\"role\":\"user\",\"content\":\"{long_msg}\"}}}}\n",
),
)
.expect("write");
let meta = parse_session(&path).unwrap();
let title = meta.title.unwrap();
assert!(title.len() <= TITLE_MAX_CHARS + 3); // +3 for "..."
assert!(title.ends_with("..."));
}
#[test] #[test]
fn load_messages_includes_function_call_and_output() { fn load_messages_includes_function_call_and_output() {
let temp = tempdir().expect("tempdir"); let temp = tempdir().expect("tempdir");
@@ -1,4 +1,3 @@
use std::collections::HashMap;
use std::fs::File; use std::fs::File;
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
use std::path::Path; use std::path::Path;
@@ -13,20 +12,10 @@ use crate::{
use super::utils::{ use super::utils::{
extract_text, parse_timestamp_to_ms, path_basename, read_head_tail_lines, truncate_summary, extract_text, parse_timestamp_to_ms, path_basename, read_head_tail_lines, truncate_summary,
TITLE_MAX_CHARS,
}; };
const PROVIDER_ID: &str = "openclaw"; const PROVIDER_ID: &str = "openclaw";
/// Strip trailing `\n[message_id: ...]` metadata injected by OpenClaw gateway.
fn strip_message_id_suffix(text: &str) -> &str {
if let Some(pos) = text.rfind("\n[message_id:") {
text[..pos].trim_end()
} else {
text
}
}
pub fn scan_sessions() -> Vec<SessionMeta> { pub fn scan_sessions() -> Vec<SessionMeta> {
let agents_dir = get_openclaw_dir().join("agents"); let agents_dir = get_openclaw_dir().join("agents");
if !agents_dir.exists() { if !agents_dir.exists() {
@@ -57,15 +46,22 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
Err(_) => continue, Err(_) => continue,
}; };
let display_names = load_display_names(&sessions_dir);
for entry in session_entries.flatten() { for entry in session_entries.flatten() {
let path = entry.path(); let path = entry.path();
if path.extension().and_then(|ext| ext.to_str()) != Some("jsonl") { if path.extension().and_then(|ext| ext.to_str()) != Some("jsonl") {
continue; continue;
} }
// Skip sessions.json index file
if path
.file_name()
.and_then(|n| n.to_str())
.map(|n| n == "sessions.json")
.unwrap_or(false)
{
continue;
}
if let Some(meta) = parse_session(&path, Some(&display_names)) { if let Some(meta) = parse_session(&path) {
sessions.push(meta); sessions.push(meta);
} }
} }
@@ -123,7 +119,7 @@ pub fn load_messages(path: &Path) -> Result<Vec<SessionMessage>, String> {
} }
pub fn delete_session(_root: &Path, path: &Path, session_id: &str) -> Result<bool, String> { pub fn delete_session(_root: &Path, path: &Path, session_id: &str) -> Result<bool, String> {
let meta = parse_session(path, None).ok_or_else(|| { let meta = parse_session(path).ok_or_else(|| {
format!( format!(
"Failed to parse OpenClaw session metadata: {}", "Failed to parse OpenClaw session metadata: {}",
path.display() path.display()
@@ -153,46 +149,15 @@ pub fn delete_session(_root: &Path, path: &Path, session_id: &str) -> Result<boo
Ok(true) Ok(true)
} }
/// Read `sessions.json` index and build a sessionId → displayName lookup map. fn parse_session(path: &Path) -> Option<SessionMeta> {
/// Returns an empty map if the file does not exist or cannot be parsed.
fn load_display_names(sessions_dir: &Path) -> HashMap<String, String> {
let index_path = sessions_dir.join("sessions.json");
let content = match std::fs::read_to_string(&index_path) {
Ok(c) => c,
Err(_) => return HashMap::new(),
};
let index: serde_json::Map<String, Value> = match serde_json::from_str(&content) {
Ok(m) => m,
Err(_) => return HashMap::new(),
};
let mut map = HashMap::new();
for (_key, entry) in &index {
if let (Some(id), Some(name)) = (
entry.get("sessionId").and_then(Value::as_str),
entry.get("displayName").and_then(Value::as_str),
) {
if !name.is_empty() {
map.insert(id.to_string(), name.to_string());
}
}
}
map
}
fn parse_session(
path: &Path,
display_names: Option<&HashMap<String, String>>,
) -> Option<SessionMeta> {
let (head, tail) = read_head_tail_lines(path, 10, 30).ok()?; let (head, tail) = read_head_tail_lines(path, 10, 30).ok()?;
let mut session_id: Option<String> = None; let mut session_id: Option<String> = None;
let mut cwd: Option<String> = None; let mut cwd: Option<String> = None;
let mut created_at: Option<i64> = None; let mut created_at: Option<i64> = None;
let mut summary: Option<String> = None; let mut summary: Option<String> = None;
let mut first_user_message: Option<String> = None;
// Extract metadata, summary, and first user message from head lines // Extract metadata and first message summary from head lines
for line in &head { for line in &head {
let value: Value = match serde_json::from_str(line) { let value: Value = match serde_json::from_str(line) {
Ok(parsed) => parsed, Ok(parsed) => parsed,
@@ -224,33 +189,17 @@ fn parse_session(
continue; continue;
} }
if event_type == "message" { // OpenClaw summary is the first message content
if event_type == "message" && summary.is_none() {
if let Some(message) = value.get("message") { if let Some(message) = value.get("message") {
let text = message.get("content").map(extract_text).unwrap_or_default(); let text = message.get("content").map(extract_text).unwrap_or_default();
let cleaned = strip_message_id_suffix(&text); if !text.trim().is_empty() {
if !cleaned.trim().is_empty() { summary = Some(text);
if first_user_message.is_none()
&& message.get("role").and_then(Value::as_str) == Some("user")
{
first_user_message = Some(cleaned.trim().to_string());
}
if summary.is_none() {
summary = Some(cleaned.trim().to_string());
} }
} }
} }
} }
if session_id.is_some()
&& cwd.is_some()
&& created_at.is_some()
&& summary.is_some()
&& first_user_message.is_some()
{
break;
}
}
// Extract last_active_at from tail lines (reverse order) // Extract last_active_at from tail lines (reverse order)
let mut last_active_at: Option<i64> = None; let mut last_active_at: Option<i64> = None;
for line in tail.iter().rev() { for line in tail.iter().rev() {
@@ -272,17 +221,10 @@ fn parse_session(
}); });
let session_id = session_id?; let session_id = session_id?;
// Title priority: displayName (from sessions.json) > first user message > dir basename let title = cwd
let title = display_names .as_deref()
.and_then(|m| m.get(&session_id))
.filter(|s| !s.is_empty())
.map(|t| truncate_summary(t, TITLE_MAX_CHARS))
.or_else(|| first_user_message.map(|t| truncate_summary(&t, TITLE_MAX_CHARS)))
.or_else(|| {
cwd.as_deref()
.and_then(path_basename) .and_then(path_basename)
.map(|s| s.to_string()) .map(|s| s.to_string());
});
let summary = summary.map(|text| truncate_summary(&text, 160)); let summary = summary.map(|text| truncate_summary(&text, 160));
@@ -342,93 +284,6 @@ mod tests {
use super::*; use super::*;
use tempfile::tempdir; use tempfile::tempdir;
#[test]
fn parse_session_uses_first_user_message_as_title() {
let temp = tempdir().expect("tempdir");
let path = temp.path().join("session-abc.jsonl");
std::fs::write(
&path,
concat!(
"{\"type\":\"session\",\"id\":\"session-abc\",\"cwd\":\"/tmp/project\",\"timestamp\":\"2026-03-06T10:00:00Z\"}\n",
"{\"type\":\"message\",\"message\":{\"role\":\"user\",\"content\":\"How do I deploy?\"},\"timestamp\":\"2026-03-06T10:01:00Z\"}\n",
"{\"type\":\"message\",\"message\":{\"role\":\"assistant\",\"content\":\"Here is how...\"},\"timestamp\":\"2026-03-06T10:02:00Z\"}\n"
),
)
.expect("write");
let meta = parse_session(&path, None).unwrap();
assert_eq!(meta.title.as_deref(), Some("How do I deploy?"));
}
#[test]
fn parse_session_display_name_overrides_user_message() {
let temp = tempdir().expect("tempdir");
let sessions_dir = temp.path();
let path = sessions_dir.join("session-abc.jsonl");
std::fs::write(
&path,
concat!(
"{\"type\":\"session\",\"id\":\"session-abc\",\"cwd\":\"/tmp/project\",\"timestamp\":\"2026-03-06T10:00:00Z\"}\n",
"{\"type\":\"message\",\"message\":{\"role\":\"user\",\"content\":\"fix something\"},\"timestamp\":\"2026-03-06T10:01:00Z\"}\n"
),
)
.expect("write session");
std::fs::write(
sessions_dir.join("sessions.json"),
r#"{
"agent:main:main": {
"sessionId": "session-abc",
"displayName": "重构登录模块"
}
}"#,
)
.expect("write index");
let display_names = load_display_names(sessions_dir);
let meta = parse_session(&path, Some(&display_names)).unwrap();
assert_eq!(meta.title.as_deref(), Some("重构登录模块"));
}
#[test]
fn parse_session_falls_back_to_dir_basename() {
let temp = tempdir().expect("tempdir");
let path = temp.path().join("session-def.jsonl");
std::fs::write(
&path,
concat!(
"{\"type\":\"session\",\"id\":\"session-def\",\"cwd\":\"/tmp/my-project\",\"timestamp\":\"2026-03-06T10:00:00Z\"}\n",
"{\"type\":\"message\",\"message\":{\"role\":\"assistant\",\"content\":\"Hello\"},\"timestamp\":\"2026-03-06T10:01:00Z\"}\n"
),
)
.expect("write");
let meta = parse_session(&path, None).unwrap();
// No user message and no displayName → falls back to dir basename
assert_eq!(meta.title.as_deref(), Some("my-project"));
}
#[test]
fn parse_session_truncates_long_title() {
let temp = tempdir().expect("tempdir");
let path = temp.path().join("session-trunc.jsonl");
let long_msg = "a".repeat(200);
std::fs::write(
&path,
format!(
"{{\"type\":\"session\",\"id\":\"session-trunc\",\"cwd\":\"/tmp/p\",\"timestamp\":\"2026-03-06T10:00:00Z\"}}\n\
{{\"type\":\"message\",\"message\":{{\"role\":\"user\",\"content\":\"{long_msg}\"}},\"timestamp\":\"2026-03-06T10:01:00Z\"}}\n",
),
)
.expect("write");
let meta = parse_session(&path, None).unwrap();
let title = meta.title.unwrap();
assert!(title.len() <= TITLE_MAX_CHARS + 3); // +3 for "..."
assert!(title.ends_with("..."));
}
#[test] #[test]
fn delete_session_updates_index_and_removes_jsonl() { fn delete_session_updates_index_and_removes_jsonl() {
let temp = tempdir().expect("tempdir"); let temp = tempdir().expect("tempdir");
@@ -5,9 +5,6 @@ use std::path::Path;
use chrono::{DateTime, FixedOffset}; use chrono::{DateTime, FixedOffset};
use serde_json::Value; use serde_json::Value;
/// Maximum number of characters for session titles (shared across providers).
pub const TITLE_MAX_CHARS: usize = 80;
/// Read the first `head_n` lines and last `tail_n` lines from a file. /// Read the first `head_n` lines and last `tail_n` lines from a file.
/// For small files (< 16 KB), reads all lines once to avoid unnecessary seeking. /// For small files (< 16 KB), reads all lines once to avoid unnecessary seeking.
pub fn read_head_tail_lines( pub fn read_head_tail_lines(
-3
View File
@@ -175,8 +175,6 @@ pub struct AppSettings {
pub show_in_tray: bool, pub show_in_tray: bool,
#[serde(default = "default_minimize_to_tray_on_close")] #[serde(default = "default_minimize_to_tray_on_close")]
pub minimize_to_tray_on_close: bool, pub minimize_to_tray_on_close: bool,
#[serde(default)]
pub use_app_window_controls: bool,
/// 是否启用 Claude 插件联动 /// 是否启用 Claude 插件联动
#[serde(default)] #[serde(default)]
pub enable_claude_plugin_integration: bool, pub enable_claude_plugin_integration: bool,
@@ -295,7 +293,6 @@ impl Default for AppSettings {
Self { Self {
show_in_tray: true, show_in_tray: true,
minimize_to_tray_on_close: true, minimize_to_tray_on_close: true,
use_app_window_controls: false,
enable_claude_plugin_integration: false, enable_claude_plugin_integration: false,
skip_claude_onboarding: false, skip_claude_onboarding: false,
launch_on_startup: false, launch_on_startup: false,
+2 -22
View File
@@ -297,9 +297,6 @@ pub fn create_tray_menu(
.map_err(|e| AppError::Message(format!("创建打开主界面菜单失败: {e}")))?; .map_err(|e| AppError::Message(format!("创建打开主界面菜单失败: {e}")))?;
menu_builder = menu_builder.item(&show_main_item).separator(); menu_builder = menu_builder.item(&show_main_item).separator();
// Pre-compute proxy running state (used to disable official providers in tray menu)
let is_proxy_running = futures::executor::block_on(app_state.proxy_service.is_running());
// 每个应用类型折叠为子菜单,避免供应商过多时菜单过长 // 每个应用类型折叠为子菜单,避免供应商过多时菜单过长
for section in TRAY_SECTIONS.iter() { for section in TRAY_SECTIONS.iter() {
if !visible_apps.is_visible(&section.app_type) { if !visible_apps.is_visible(&section.app_type) {
@@ -330,32 +327,15 @@ pub fn create_tray_menu(
}; };
let submenu_id = format!("submenu_{}", app_type_str); let submenu_id = format!("submenu_{}", app_type_str);
// Check if this app is under proxy takeover (for disabling official providers)
let is_app_taken_over = is_proxy_running
&& (futures::executor::block_on(app_state.db.get_live_backup(app_type_str))
.ok()
.flatten()
.is_some()
|| app_state
.proxy_service
.detect_takeover_in_live_config_for_app(&section.app_type));
let mut submenu_builder = SubmenuBuilder::with_id(app, &submenu_id, &submenu_label); let mut submenu_builder = SubmenuBuilder::with_id(app, &submenu_id, &submenu_label);
for (id, provider) in sort_providers(&providers) { for (id, provider) in sort_providers(&providers) {
let is_current = current_id == *id; let is_current = current_id == *id;
let is_official_blocked =
is_app_taken_over && provider.category.as_deref() == Some("official");
let label = if is_official_blocked {
format!("{} \u{26D4}", &provider.name) // ⛔ emoji
} else {
provider.name.clone()
};
let item = CheckMenuItem::with_id( let item = CheckMenuItem::with_id(
app, app,
format!("{}{}", section.prefix, id), format!("{}{}", section.prefix, id),
&label, &provider.name,
!is_official_blocked, // disabled when blocked true,
is_current, is_current,
None::<&str>, None::<&str>,
) )
+254 -2
View File
@@ -104,7 +104,8 @@ pub async fn execute_usage_script(
) )
})?; })?;
// 5. 验证请求 URLHTTPS 强制 + 同源检查 // 5. 验证请求 URL 是否安全(防止 SSRF
// 如果提供了 base_url,则验证同源;否则只做基本安全检查
validate_request_url(&request.url, base_url, is_custom_template)?; validate_request_url(&request.url, base_url, is_custom_template)?;
// 6. 发送 HTTP 请求 // 6. 发送 HTTP 请求
@@ -467,10 +468,19 @@ fn validate_base_url(base_url: &str) -> Result<(), AppError> {
)); ));
} }
// 检查是否为明显的私有IP(但在 base_url 阶段不过于严格,主要在 request_url 阶段检查)
if is_suspicious_hostname(hostname) {
return Err(AppError::localized(
"usage_script.base_url_suspicious",
"base_url 包含可疑的主机名",
"base_url contains a suspicious hostname",
));
}
Ok(()) Ok(())
} }
/// 验证请求 URL 是否安全(HTTPS 强制 + 同源检查 /// 验证请求 URL 是否安全(防止 SSRF
fn validate_request_url( fn validate_request_url(
request_url: &str, request_url: &str,
base_url: &str, base_url: &str,
@@ -551,11 +561,151 @@ fn validate_request_url(
)); ));
} }
} }
// 禁止私有 IP 地址访问(除非 base_url 本身就是私有地址,用于开发环境)
if let Some(host) = parsed_request.host_str() {
let base_host = parsed_base.host_str().unwrap_or("");
// 如果 base_url 不是私有地址,则禁止访问私有IP
if !is_private_ip(base_host) && is_private_ip(host) {
return Err(AppError::localized(
"usage_script.private_ip_blocked",
"禁止访问私有 IP 地址",
"Access to private IP addresses is blocked",
));
}
}
} else {
// 自定义模板模式:没有 base_url,需要额外的安全检查
// 禁止访问私有 IP 地址(SSRF 防护)
if let Some(host) = parsed_request.host_str() {
if is_private_ip(host) && !is_request_loopback {
return Err(AppError::localized(
"usage_script.private_ip_blocked",
"禁止访问私有 IP 地址(localhost 除外)",
"Access to private IP addresses is blocked (localhost allowed)",
));
}
}
} }
Ok(()) Ok(())
} }
/// 检查是否为私有 IP 地址
fn is_private_ip(host: &str) -> bool {
// localhost 检查
if host.eq_ignore_ascii_case("localhost") {
return true;
}
// 尝试解析为IP地址
if let Ok(ip_addr) = host.parse::<std::net::IpAddr>() {
return is_private_ip_addr(ip_addr);
}
// 如果不是IP地址,不是私有IP
false
}
/// 使用标准库API检查IP地址是否为私有地址
fn is_private_ip_addr(ip: std::net::IpAddr) -> bool {
match ip {
std::net::IpAddr::V4(ipv4) => {
let octets = ipv4.octets();
// 0.0.0.0/8 (包括未指定地址)
if octets[0] == 0 {
return true;
}
// RFC1918 私有地址范围
// 10.0.0.0/8
if octets[0] == 10 {
return true;
}
// 172.16.0.0/12 (172.16.0.0 - 172.31.255.255)
if octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31 {
return true;
}
// 192.168.0.0/16
if octets[0] == 192 && octets[1] == 168 {
return true;
}
// 其他特殊地址
// 169.254.0.0/16 (链路本地地址)
if octets[0] == 169 && octets[1] == 254 {
return true;
}
// 127.0.0.0/8 (环回地址)
if octets[0] == 127 {
return true;
}
false
}
std::net::IpAddr::V6(ipv6) => {
// IPv6 私有地址检查 - 使用标准库方法
// ::1 (环回地址)
if ipv6.is_loopback() {
return true;
}
// 唯一本地地址 (fc00::/7)
// Rust 1.70+ 可以使用 ipv6.is_unique_local()
// 但为了兼容性,我们手动检查
let first_segment = ipv6.segments()[0];
if (first_segment & 0xfe00) == 0xfc00 {
return true;
}
// 链路本地地址 (fe80::/10)
if (first_segment & 0xffc0) == 0xfe80 {
return true;
}
// 未指定地址 ::
if ipv6.is_unspecified() {
return true;
}
false
}
}
}
/// 检查是否为可疑的主机名(只检查明显不安全的模式)
fn is_suspicious_hostname(hostname: &str) -> bool {
// 空主机名
if hostname.is_empty() {
return true;
}
// 检查明显的主机名格式问题
if hostname.contains("..") || hostname.starts_with(".") || hostname.ends_with(".") {
return true;
}
// 检查是否为纯IP地址但没有合理格式(过于宽松的检查在这里可能不够,但主要依赖后续的同源检查)
if hostname.parse::<std::net::IpAddr>().is_ok() {
// IP地址格式的,在这里不直接拒绝,让同源检查来处理
return false;
}
// 检查是否包含明显不当的字符
let suspicious_chars = ['<', '>', '"', '\'', '\n', '\r', '\t', '\0'];
if hostname.chars().any(|c| suspicious_chars.contains(&c)) {
return true;
}
false
}
/// 判断 URL 是否指向本机(localhost / loopback /// 判断 URL 是否指向本机(localhost / loopback
fn is_loopback_host(url: &Url) -> bool { fn is_loopback_host(url: &Url) -> bool {
match url.host() { match url.host() {
@@ -570,6 +720,77 @@ fn is_loopback_host(url: &Url) -> bool {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn test_private_ip_validation() {
// 测试IPv4私网地址
// RFC1918私网地址 - 应该返回true
assert!(is_private_ip("10.0.0.1"));
assert!(is_private_ip("10.255.255.254"));
assert!(is_private_ip("172.16.0.1"));
assert!(is_private_ip("172.31.255.255"));
assert!(is_private_ip("192.168.0.1"));
assert!(is_private_ip("192.168.255.255"));
// 链路本地地址 - 应该返回true
assert!(is_private_ip("169.254.0.1"));
assert!(is_private_ip("169.254.255.255"));
// 环回地址 - 应该返回true
assert!(is_private_ip("127.0.0.1"));
assert!(is_private_ip("localhost"));
// 公网172.x.x.x地址 - 应该返回false(这是修复的重点)
assert!(!is_private_ip("172.0.0.1"));
assert!(!is_private_ip("172.15.255.255"));
assert!(!is_private_ip("172.32.0.1"));
assert!(!is_private_ip("172.64.0.1"));
assert!(!is_private_ip("172.67.0.1")); // Cloudflare CDN
assert!(!is_private_ip("172.68.0.1"));
assert!(!is_private_ip("172.100.50.25"));
assert!(!is_private_ip("172.255.255.255"));
// 其他公网地址 - 应该返回false
assert!(!is_private_ip("8.8.8.8")); // Google DNS
assert!(!is_private_ip("1.1.1.1")); // Cloudflare DNS
assert!(!is_private_ip("208.67.222.222")); // OpenDNS
assert!(!is_private_ip("180.76.76.76")); // Baidu DNS
// 域名 - 应该返回false
assert!(!is_private_ip("api.example.com"));
assert!(!is_private_ip("www.google.com"));
}
#[test]
fn test_ipv6_private_validation() {
// IPv6私网地址
assert!(is_private_ip("::1")); // 环回地址
assert!(is_private_ip("fc00::1")); // 唯一本地地址
assert!(is_private_ip("fd00::1")); // 唯一本地地址
assert!(is_private_ip("fe80::1")); // 链路本地地址
assert!(is_private_ip("::")); // 未指定地址
// IPv6公网地址 - 应该返回false(修复的重点)
assert!(!is_private_ip("2001:4860:4860::8888")); // Google DNS IPv6
assert!(!is_private_ip("2606:4700:4700::1111")); // Cloudflare DNS IPv6
assert!(!is_private_ip("2404:6800:4001:c01::67")); // Google DNS IPv6 (其他格式)
assert!(!is_private_ip("2001:db8::1")); // 文档地址(非私网)
// 测试包含 ::1 子串但不是环回地址的公网地址
assert!(!is_private_ip("2001:db8::1abc")); // 包含 ::1abc 但不是环回
assert!(!is_private_ip("2606:4700::1")); // 包含 ::1 但不是环回
}
#[test]
fn test_hostname_bypass_prevention() {
// 看起来像本地,但实际是域名
assert!(!is_private_ip("127.0.0.1.evil.com"));
assert!(!is_private_ip("localhost.evil.com"));
// 0.0.0.0 应该被视为本地/阻断
assert!(is_private_ip("0.0.0.0"));
}
#[test] #[test]
fn test_https_bypass_prevention() { fn test_https_bypass_prevention() {
// 非本地域名的 HTTP 应该被拒绝 // 非本地域名的 HTTP 应该被拒绝
@@ -580,6 +801,37 @@ mod tests {
); );
} }
#[test]
fn test_edge_cases() {
// 边界情况测试
assert!(is_private_ip("172.16.0.0")); // RFC1918起始
assert!(is_private_ip("172.31.255.255")); // RFC1918结束
assert!(is_private_ip("10.0.0.0")); // 10.0.0.0/8起始
assert!(is_private_ip("10.255.255.255")); // 10.0.0.0/8结束
assert!(is_private_ip("192.168.0.0")); // 192.168.0.0/16起始
assert!(is_private_ip("192.168.255.255")); // 192.168.0.0/16结束
// 紧邻RFC1918的公网地址 - 应该返回false
assert!(!is_private_ip("172.15.255.255")); // 172.16.0.0的前一个
assert!(!is_private_ip("172.32.0.0")); // 172.31.255.255的后一个
}
#[test]
fn test_ip_addr_parsing() {
// 测试IP地址解析功能
let ipv4_private = "10.0.0.1".parse::<std::net::IpAddr>().unwrap();
assert!(is_private_ip_addr(ipv4_private));
let ipv4_public = "172.67.0.1".parse::<std::net::IpAddr>().unwrap();
assert!(!is_private_ip_addr(ipv4_public));
let ipv6_private = "fc00::1".parse::<std::net::IpAddr>().unwrap();
assert!(is_private_ip_addr(ipv6_private));
let ipv6_public = "2001:4860:4860::8888".parse::<std::net::IpAddr>().unwrap();
assert!(!is_private_ip_addr(ipv6_public));
}
#[test] #[test]
fn test_port_comparison() { fn test_port_comparison() {
// 测试端口比较逻辑是否正确处理默认端口和显式端口 // 测试端口比较逻辑是否正确处理默认端口和显式端口
+10 -19
View File
@@ -525,7 +525,7 @@ fn packycode_partner_meta_triggers_security_flag_even_without_keywords() {
} }
#[test] #[test]
fn switch_google_official_gemini_preserves_env_vars() { fn switch_google_official_gemini_sets_oauth_security() {
let _guard = test_mutex().lock().expect("acquire test mutex"); let _guard = test_mutex().lock().expect("acquire test mutex");
reset_test_fs(); reset_test_fs();
let home = ensure_test_home(); let home = ensure_test_home();
@@ -540,9 +540,7 @@ fn switch_google_official_gemini_preserves_env_vars() {
"google-official".to_string(), "google-official".to_string(),
"Google".to_string(), "Google".to_string(),
json!({ json!({
"env": { "env": {}
"GEMINI_MODEL": "gemini-2.5-pro"
}
}), }),
Some("https://ai.google.dev".to_string()), Some("https://ai.google.dev".to_string()),
); );
@@ -560,30 +558,23 @@ fn switch_google_official_gemini_preserves_env_vars() {
ProviderService::switch(&state, AppType::Gemini, "google-official") ProviderService::switch(&state, AppType::Gemini, "google-official")
.expect("switching to Google official Gemini should succeed"); .expect("switching to Google official Gemini should succeed");
// Verify env vars are preserved in ~/.gemini/.env // Gemini security settings are written to ~/.gemini/settings.json, not ~/.cc-switch/settings.json
let env_path = home.join(".gemini").join(".env");
assert!(
env_path.exists(),
"Gemini .env should exist at {}",
env_path.display()
);
let env_content = std::fs::read_to_string(&env_path).expect("read gemini .env");
assert!(
env_content.contains("GEMINI_MODEL=gemini-2.5-pro"),
"GEMINI_MODEL should be preserved in .env, got: {env_content}"
);
// Verify OAuth security flag is still set correctly
let gemini_settings = home.join(".gemini").join("settings.json"); let gemini_settings = home.join(".gemini").join("settings.json");
assert!(
gemini_settings.exists(),
"Gemini settings.json should exist at {}",
gemini_settings.display()
);
let gemini_raw = std::fs::read_to_string(&gemini_settings).expect("read gemini settings"); let gemini_raw = std::fs::read_to_string(&gemini_settings).expect("read gemini settings");
let gemini_value: serde_json::Value = let gemini_value: serde_json::Value =
serde_json::from_str(&gemini_raw).expect("parse gemini settings"); serde_json::from_str(&gemini_raw).expect("parse gemini settings");
assert_eq!( assert_eq!(
gemini_value gemini_value
.pointer("/security/auth/selectedType") .pointer("/security/auth/selectedType")
.and_then(|v| v.as_str()), .and_then(|v| v.as_str()),
Some("oauth-personal"), Some("oauth-personal"),
"OAuth security flag should still be set" "Gemini settings json should reflect oauth-personal for Google Official"
); );
} }
+9 -174
View File
@@ -9,10 +9,6 @@ import {
Plus, Plus,
Settings, Settings,
ArrowLeft, ArrowLeft,
Minus,
Maximize2,
Minimize2,
X,
Book, Book,
Wrench, Wrench,
RefreshCw, RefreshCw,
@@ -26,7 +22,6 @@ import {
Shield, Shield,
Cpu, Cpu,
} from "lucide-react"; } from "lucide-react";
import { getCurrentWindow } from "@tauri-apps/api/window";
import type { Provider, VisibleApps } from "@/types"; import type { Provider, VisibleApps } from "@/types";
import type { EnvConflict } from "@/types/env"; import type { EnvConflict } from "@/types/env";
import { useProvidersQuery, useSettingsQuery } from "@/lib/query"; import { useProvidersQuery, useSettingsQuery } from "@/lib/query";
@@ -104,8 +99,9 @@ interface WebDavSyncStatusUpdatedPayload {
error?: string; error?: string;
} }
const DEFAULT_DRAG_BAR_HEIGHT = isWindows() || isLinux() ? 0 : 28; // px const DRAG_BAR_HEIGHT = isWindows() || isLinux() ? 0 : 28; // px
const HEADER_HEIGHT = 64; // px const HEADER_HEIGHT = 64; // px
const CONTENT_TOP_OFFSET = DRAG_BAR_HEIGHT + HEADER_HEIGHT;
const STORAGE_KEY = "cc-switch-last-app"; const STORAGE_KEY = "cc-switch-last-app";
const VALID_APPS: AppId[] = [ const VALID_APPS: AppId[] = [
@@ -157,17 +153,12 @@ function App() {
const [currentView, setCurrentView] = useState<View>(getInitialView); const [currentView, setCurrentView] = useState<View>(getInitialView);
const [settingsDefaultTab, setSettingsDefaultTab] = useState("general"); const [settingsDefaultTab, setSettingsDefaultTab] = useState("general");
const [isAddOpen, setIsAddOpen] = useState(false); const [isAddOpen, setIsAddOpen] = useState(false);
const [isWindowMaximized, setIsWindowMaximized] = useState(false);
useEffect(() => { useEffect(() => {
localStorage.setItem(VIEW_STORAGE_KEY, currentView); localStorage.setItem(VIEW_STORAGE_KEY, currentView);
}, [currentView]); }, [currentView]);
const { data: settingsData } = useSettingsQuery(); const { data: settingsData } = useSettingsQuery();
const useAppWindowControls =
isLinux() && (settingsData?.useAppWindowControls ?? false);
const dragBarHeight = useAppWindowControls ? 32 : DEFAULT_DRAG_BAR_HEIGHT;
const contentTopOffset = dragBarHeight + HEADER_HEIGHT;
const visibleApps: VisibleApps = settingsData?.visibleApps ?? { const visibleApps: VisibleApps = settingsData?.visibleApps ?? {
claude: true, claude: true,
codex: true, codex: true,
@@ -270,11 +261,7 @@ function App() {
deleteProvider, deleteProvider,
saveUsageScript, saveUsageScript,
setAsDefaultModel, setAsDefaultModel,
} = useProviderActions( } = useProviderActions(activeApp, isProxyRunning);
activeApp,
isProxyRunning,
isProxyRunning && isCurrentAppTakeoverActive,
);
const disableOmoMutation = useDisableCurrentOmo(); const disableOmoMutation = useDisableCurrentOmo();
const handleDisableOmo = () => { const handleDisableOmo = () => {
@@ -405,77 +392,6 @@ function App() {
}; };
}, [queryClient, t]); }, [queryClient, t]);
// Listen for proxy-official-warning: warn when takeover is enabled with an official provider
useEffect(() => {
let unsubscribe: (() => void) | undefined;
const setup = async () => {
unsubscribe = await listen("proxy-official-warning", (event) => {
const { providerName } = event.payload as {
appType: string;
providerName: string;
};
toast.warning(
t("notifications.proxyOfficialWarning", {
name: providerName,
defaultValue: `当前供应商 ${providerName} 是官方供应商,建议切换到第三方供应商后再使用代理接管`,
}),
{ duration: 8000 },
);
});
};
void setup();
return () => {
unsubscribe?.();
};
}, [t]);
useEffect(() => {
let active = true;
let unlistenResize: (() => void) | undefined;
const setupWindowStateSync = async () => {
try {
const currentWindow = getCurrentWindow();
const syncWindowMaximizedState = async () => {
const maximized = await currentWindow.isMaximized();
if (active) {
setIsWindowMaximized(maximized);
}
};
await syncWindowMaximizedState();
unlistenResize = await currentWindow.onResized(() => {
void syncWindowMaximizedState();
});
} catch (error) {
console.error("[App] Failed to sync window maximized state", error);
}
};
void setupWindowStateSync();
return () => {
active = false;
unlistenResize?.();
};
}, []);
useEffect(() => {
// settingsData 未加载时跳过,避免用 fallback false 覆盖 Rust 侧已设好的装饰状态
if (!settingsData) return;
const syncWindowDecorations = async () => {
try {
await getCurrentWindow().setDecorations(!useAppWindowControls);
} catch (error) {
console.error("[App] Failed to update window decorations", error);
}
};
void syncWindowDecorations();
}, [useAppWindowControls, settingsData]);
useEffect(() => { useEffect(() => {
const checkEnvOnStartup = async () => { const checkEnvOnStartup = async () => {
try { try {
@@ -818,44 +734,6 @@ function App() {
} }
}; };
const notifyWindowControlError = (error: unknown) => {
toast.error(
t("notifications.windowControlFailed", {
defaultValue: "窗口控制失败:{{error}}",
error: extractErrorMessage(error),
}),
);
};
const handleWindowMinimize = async () => {
try {
await getCurrentWindow().minimize();
} catch (error) {
console.error("[App] Failed to minimize window", error);
notifyWindowControlError(error);
}
};
const handleWindowToggleMaximize = async () => {
try {
const currentWindow = getCurrentWindow();
await currentWindow.toggleMaximize();
setIsWindowMaximized(await currentWindow.isMaximized());
} catch (error) {
console.error("[App] Failed to toggle maximize", error);
notifyWindowControlError(error);
}
};
const handleWindowClose = async () => {
try {
await getCurrentWindow().close();
} catch (error) {
console.error("[App] Failed to close window", error);
notifyWindowControlError(error);
}
};
const renderContent = () => { const renderContent = () => {
const content = (() => { const content = (() => {
switch (currentView) { switch (currentView) {
@@ -1002,57 +880,14 @@ function App() {
return ( return (
<div <div
className="flex flex-col h-screen overflow-hidden bg-background text-foreground selection:bg-primary/30" className="flex flex-col h-screen overflow-hidden bg-background text-foreground selection:bg-primary/30"
style={{ overflowX: "hidden", paddingTop: contentTopOffset }} style={{ overflowX: "hidden", paddingTop: CONTENT_TOP_OFFSET }}
> >
{(dragBarHeight > 0 || useAppWindowControls) && ( {DRAG_BAR_HEIGHT > 0 && (
<div <div
className="fixed top-0 left-0 right-0 z-[70] flex items-center justify-end px-2" className="fixed top-0 left-0 right-0 z-[60]"
data-tauri-drag-region data-tauri-drag-region
style={{ WebkitAppRegion: "drag", height: dragBarHeight } as any} style={{ WebkitAppRegion: "drag", height: DRAG_BAR_HEIGHT } as any}
> />
{useAppWindowControls && (
<div
className="flex items-center gap-1"
style={{ WebkitAppRegion: "no-drag" } as any}
>
<Button
variant="ghost"
size="icon"
onClick={() => void handleWindowMinimize()}
title={t("header.windowMinimize")}
className="h-7 w-7"
>
<Minus className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => void handleWindowToggleMaximize()}
title={
isWindowMaximized
? t("header.windowRestore")
: t("header.windowMaximize")
}
className="h-7 w-7"
>
{isWindowMaximized ? (
<Minimize2 className="w-4 h-4" />
) : (
<Maximize2 className="w-4 h-4" />
)}
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => void handleWindowClose()}
title={t("header.windowClose")}
className="h-7 w-7 hover:bg-red-500/15 hover:text-red-500"
>
<X className="w-4 h-4" />
</Button>
</div>
)}
</div>
)} )}
{showEnvBanner && envConflicts.length > 0 && ( {showEnvBanner && envConflicts.length > 0 && (
<EnvWarningBanner <EnvWarningBanner
@@ -1085,7 +920,7 @@ function App() {
style={ style={
{ {
...DRAG_REGION_STYLE, ...DRAG_REGION_STYLE,
top: dragBarHeight, top: DRAG_BAR_HEIGHT,
height: HEADER_HEIGHT, height: HEADER_HEIGHT,
} as any } as any
} }
@@ -154,7 +154,7 @@ export function EditProviderDialog({
}, [ }, [
open, // 修复:编辑保存后再次打开显示旧数据,依赖 open 确保每次打开时重新读取最新 provider 数据 open, // 修复:编辑保存后再次打开显示旧数据,依赖 open 确保每次打开时重新读取最新 provider 数据
provider?.id, // 只依赖 ID,provider 对象更新不会触发重新计算 provider?.id, // 只依赖 ID,provider 对象更新不会触发重新计算
provider?.meta, // 需要依赖 meta 以便正确初始化 testConfig provider?.meta, // 需要依赖 meta 以便正确初始化 testConfig 和 proxyConfig
initialSettingsConfig, initialSettingsConfig,
]); ]);
@@ -7,7 +7,6 @@ import {
Minus, Minus,
Play, Play,
Plus, Plus,
ShieldAlert,
Terminal, Terminal,
TestTube2, TestTube2,
Trash2, Trash2,
@@ -37,7 +36,6 @@ interface ProviderActionsProps {
isAutoFailoverEnabled?: boolean; isAutoFailoverEnabled?: boolean;
isInFailoverQueue?: boolean; isInFailoverQueue?: boolean;
onToggleFailover?: (enabled: boolean) => void; onToggleFailover?: (enabled: boolean) => void;
isOfficialBlockedByProxy?: boolean;
// OpenClaw: default model // OpenClaw: default model
isDefaultModel?: boolean; isDefaultModel?: boolean;
onSetAsDefault?: () => void; onSetAsDefault?: () => void;
@@ -62,7 +60,6 @@ export function ProviderActions({
isAutoFailoverEnabled = false, isAutoFailoverEnabled = false,
isInFailoverQueue = false, isInFailoverQueue = false,
onToggleFailover, onToggleFailover,
isOfficialBlockedByProxy = false,
// OpenClaw: default model // OpenClaw: default model
isDefaultModel = false, isDefaultModel = false,
onSetAsDefault, onSetAsDefault,
@@ -169,16 +166,6 @@ export function ProviderActions({
}; };
} }
if (isOfficialBlockedByProxy) {
return {
disabled: true,
variant: "secondary" as const,
className: "opacity-40 cursor-not-allowed",
icon: <ShieldAlert className="h-4 w-4" />,
text: t("provider.blockedByProxy", { defaultValue: "已拦截" }),
};
}
if (isCurrent) { if (isCurrent) {
return { return {
disabled: true, disabled: true,
@@ -175,8 +175,6 @@ export function ProviderCard({
const usageEnabled = provider.meta?.usage_script?.enabled ?? false; const usageEnabled = provider.meta?.usage_script?.enabled ?? false;
const isOfficial = isOfficialProvider(provider, appId); const isOfficial = isOfficialProvider(provider, appId);
const isOfficialBlockedByProxy =
isProxyTakeover && (provider.category === "official" || isOfficial);
const isCopilot = const isCopilot =
provider.meta?.providerType === PROVIDER_TYPES.GITHUB_COPILOT || provider.meta?.providerType === PROVIDER_TYPES.GITHUB_COPILOT ||
provider.meta?.usage_script?.templateType === "github_copilot"; provider.meta?.usage_script?.templateType === "github_copilot";
@@ -426,7 +424,6 @@ export function ProviderCard({
isInConfig={isInConfig} isInConfig={isInConfig}
isTesting={isTesting} isTesting={isTesting}
isProxyTakeover={isProxyTakeover} isProxyTakeover={isProxyTakeover}
isOfficialBlockedByProxy={isOfficialBlockedByProxy}
isOmo={isAnyOmo} isOmo={isAnyOmo}
onSwitch={() => onSwitch(provider)} onSwitch={() => onSwitch(provider)}
onEdit={() => onEdit(provider)} onEdit={() => onEdit(provider)}
@@ -1,9 +1,19 @@
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { ChevronDown, ChevronRight, FlaskConical, Coins } from "lucide-react"; import {
ChevronDown,
ChevronRight,
FlaskConical,
Globe,
Coins,
Eye,
EyeOff,
X,
} from "lucide-react";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { import {
Select, Select,
SelectContent, SelectContent,
@@ -12,7 +22,7 @@ import {
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { ProviderTestConfig } from "@/types"; import type { ProviderTestConfig, ProviderProxyConfig } from "@/types";
export type PricingModelSourceOption = "inherit" | "request" | "response"; export type PricingModelSourceOption = "inherit" | "request" | "response";
@@ -24,31 +34,136 @@ interface ProviderPricingConfig {
interface ProviderAdvancedConfigProps { interface ProviderAdvancedConfigProps {
testConfig: ProviderTestConfig; testConfig: ProviderTestConfig;
proxyConfig: ProviderProxyConfig;
pricingConfig: ProviderPricingConfig; pricingConfig: ProviderPricingConfig;
onTestConfigChange: (config: ProviderTestConfig) => void; onTestConfigChange: (config: ProviderTestConfig) => void;
onProxyConfigChange: (config: ProviderProxyConfig) => void;
onPricingConfigChange: (config: ProviderPricingConfig) => void; onPricingConfigChange: (config: ProviderPricingConfig) => void;
} }
/** 从 ProviderProxyConfig 构建完整 URL */
function buildProxyUrl(config: ProviderProxyConfig): string {
if (!config.proxyHost) return "";
const protocol = config.proxyType || "http";
const host = config.proxyHost;
const port = config.proxyPort || (protocol === "socks5" ? 1080 : 7890);
return `${protocol}://${host}:${port}`;
}
/** 从完整 URL 解析为 ProviderProxyConfig */
function parseProxyUrl(url: string): Partial<ProviderProxyConfig> {
if (!url.trim()) {
return { proxyHost: undefined, proxyPort: undefined, proxyType: undefined };
}
try {
const parsed = new URL(url);
const protocol = parsed.protocol.replace(":", "") as
| "http"
| "https"
| "socks5";
const host = parsed.hostname;
const port = parsed.port ? parseInt(parsed.port, 10) : undefined;
return {
proxyType: protocol,
proxyHost: host || undefined,
proxyPort: port,
};
} catch {
// 尝试简单解析(不是标准 URL 格式)
const match = url.match(/^(?:(\w+):\/\/)?([^:]+)(?::(\d+))?$/);
if (match) {
return {
proxyType: (match[1] as "http" | "https" | "socks5") || "http",
proxyHost: match[2] || undefined,
proxyPort: match[3] ? parseInt(match[3], 10) : undefined,
};
}
return {};
}
}
export function ProviderAdvancedConfig({ export function ProviderAdvancedConfig({
testConfig, testConfig,
proxyConfig,
pricingConfig, pricingConfig,
onTestConfigChange, onTestConfigChange,
onProxyConfigChange,
onPricingConfigChange, onPricingConfigChange,
}: ProviderAdvancedConfigProps) { }: ProviderAdvancedConfigProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [isTestConfigOpen, setIsTestConfigOpen] = useState(testConfig.enabled); const [isTestConfigOpen, setIsTestConfigOpen] = useState(testConfig.enabled);
const [isProxyConfigOpen, setIsProxyConfigOpen] = useState(
proxyConfig.enabled,
);
const [isPricingConfigOpen, setIsPricingConfigOpen] = useState( const [isPricingConfigOpen, setIsPricingConfigOpen] = useState(
pricingConfig.enabled, pricingConfig.enabled,
); );
const [showPassword, setShowPassword] = useState(false);
// 代理 URL 输入状态(仅在初始化时从 proxyConfig 构建)
const [proxyUrl, setProxyUrl] = useState(() => buildProxyUrl(proxyConfig));
// 标记是否为用户主动输入(用于区分外部更新和用户输入)
const [isUserTyping, setIsUserTyping] = useState(false);
useEffect(() => { useEffect(() => {
setIsTestConfigOpen(testConfig.enabled); setIsTestConfigOpen(testConfig.enabled);
}, [testConfig.enabled]); }, [testConfig.enabled]);
// 同步外部 proxyConfig.enabled 变化到展开状态
useEffect(() => {
setIsProxyConfigOpen(proxyConfig.enabled);
}, [proxyConfig.enabled]);
// 同步外部 pricingConfig.enabled 变化到展开状态
useEffect(() => { useEffect(() => {
setIsPricingConfigOpen(pricingConfig.enabled); setIsPricingConfigOpen(pricingConfig.enabled);
}, [pricingConfig.enabled]); }, [pricingConfig.enabled]);
// 仅在外部 proxyConfig 变化且非用户输入时同步(如:重置表单、加载数据)
useEffect(() => {
if (!isUserTyping) {
const newUrl = buildProxyUrl(proxyConfig);
if (newUrl !== proxyUrl) {
setProxyUrl(newUrl);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [proxyConfig.proxyType, proxyConfig.proxyHost, proxyConfig.proxyPort]);
// 处理代理 URL 变化(用户输入时不触发 URL 重建)
const handleProxyUrlChange = (value: string) => {
setIsUserTyping(true);
setProxyUrl(value);
const parsed = parseProxyUrl(value);
onProxyConfigChange({
...proxyConfig,
...parsed,
});
};
// 输入框失焦时结束用户输入状态
const handleProxyUrlBlur = () => {
setIsUserTyping(false);
};
// 清除代理配置
const handleClearProxy = () => {
setProxyUrl("");
onProxyConfigChange({
...proxyConfig,
proxyType: undefined,
proxyHost: undefined,
proxyPort: undefined,
proxyUsername: undefined,
proxyPassword: undefined,
});
};
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<div className="rounded-lg border border-border/50 bg-muted/20"> <div className="rounded-lg border border-border/50 bg-muted/20">
@@ -227,6 +342,141 @@ export function ProviderAdvancedConfig({
</div> </div>
</div> </div>
{/* 代理配置 */}
<div className="rounded-lg border border-border/50 bg-muted/20">
<button
type="button"
className="flex w-full items-center justify-between p-4 hover:bg-muted/30 transition-colors"
onClick={() => setIsProxyConfigOpen(!isProxyConfigOpen)}
>
<div className="flex items-center gap-3">
<Globe className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">
{t("providerAdvanced.proxyConfig", {
defaultValue: "代理配置",
})}
</span>
</div>
<div className="flex items-center gap-3">
<div
className="flex items-center gap-2"
onClick={(e) => e.stopPropagation()}
>
<Label
htmlFor="proxy-config-enabled"
className="text-sm text-muted-foreground"
>
{t("providerAdvanced.useCustomProxy", {
defaultValue: "使用单独代理",
})}
</Label>
<Switch
id="proxy-config-enabled"
checked={proxyConfig.enabled}
onCheckedChange={(checked) => {
onProxyConfigChange({ ...proxyConfig, enabled: checked });
if (checked) setIsProxyConfigOpen(true);
}}
/>
</div>
{isProxyConfigOpen ? (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronRight className="h-4 w-4 text-muted-foreground" />
)}
</div>
</button>
<div
className={cn(
"overflow-hidden transition-all duration-200",
isProxyConfigOpen
? "max-h-[500px] opacity-100"
: "max-h-0 opacity-0",
)}
>
<div className="border-t border-border/50 p-4 space-y-3">
<p className="text-sm text-muted-foreground">
{t("providerAdvanced.proxyConfigDesc", {
defaultValue:
"为此供应商配置单独的网络代理,不启用时使用系统代理或全局设置。",
})}
</p>
{/* 代理地址输入框(仿照全局代理样式) */}
<div className="flex gap-2">
<Input
placeholder="http://127.0.0.1:7890 / socks5://127.0.0.1:1080"
value={proxyUrl}
onChange={(e) => handleProxyUrlChange(e.target.value)}
onBlur={handleProxyUrlBlur}
className="font-mono text-sm flex-1"
disabled={!proxyConfig.enabled}
/>
<Button
type="button"
variant="outline"
size="icon"
disabled={!proxyConfig.enabled || !proxyUrl}
onClick={handleClearProxy}
title={t("common.clear", { defaultValue: "清除" })}
>
<X className="h-4 w-4" />
</Button>
</div>
{/* 认证信息:用户名 + 密码(可选) */}
<div className="flex gap-2">
<Input
placeholder={t("providerAdvanced.proxyUsername", {
defaultValue: "用户名(可选)",
})}
value={proxyConfig.proxyUsername || ""}
onChange={(e) =>
onProxyConfigChange({
...proxyConfig,
proxyUsername: e.target.value || undefined,
})
}
className="font-mono text-sm flex-1"
disabled={!proxyConfig.enabled}
/>
<div className="relative flex-1">
<Input
type={showPassword ? "text" : "password"}
placeholder={t("providerAdvanced.proxyPassword", {
defaultValue: "密码(可选)",
})}
value={proxyConfig.proxyPassword || ""}
onChange={(e) =>
onProxyConfigChange({
...proxyConfig,
proxyPassword: e.target.value || undefined,
})
}
className="font-mono text-sm pr-10"
disabled={!proxyConfig.enabled}
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
onClick={() => setShowPassword(!showPassword)}
tabIndex={-1}
disabled={!proxyConfig.enabled}
>
{showPassword ? (
<EyeOff className="h-4 w-4 text-muted-foreground" />
) : (
<Eye className="h-4 w-4 text-muted-foreground" />
)}
</Button>
</div>
</div>
</div>
</div>
</div>
{/* 计费配置 */} {/* 计费配置 */}
<div className="rounded-lg border border-border/50 bg-muted/20"> <div className="rounded-lg border border-border/50 bg-muted/20">
<button <button
@@ -13,6 +13,7 @@ import type {
ProviderCategory, ProviderCategory,
ProviderMeta, ProviderMeta,
ProviderTestConfig, ProviderTestConfig,
ProviderProxyConfig,
ClaudeApiFormat, ClaudeApiFormat,
ClaudeApiKeyField, ClaudeApiKeyField,
} from "@/types"; } from "@/types";
@@ -191,6 +192,9 @@ export function ProviderForm({
const [testConfig, setTestConfig] = useState<ProviderTestConfig>( const [testConfig, setTestConfig] = useState<ProviderTestConfig>(
() => initialData?.meta?.testConfig ?? { enabled: false }, () => initialData?.meta?.testConfig ?? { enabled: false },
); );
const [proxyConfig, setProxyConfig] = useState<ProviderProxyConfig>(
() => initialData?.meta?.proxyConfig ?? { enabled: false },
);
const [pricingConfig, setPricingConfig] = useState<{ const [pricingConfig, setPricingConfig] = useState<{
enabled: boolean; enabled: boolean;
costMultiplier?: string; costMultiplier?: string;
@@ -227,6 +231,7 @@ export function ProviderForm({
supportsFullUrl ? (initialData?.meta?.isFullUrl ?? false) : false, supportsFullUrl ? (initialData?.meta?.isFullUrl ?? false) : false,
); );
setTestConfig(initialData?.meta?.testConfig ?? { enabled: false }); setTestConfig(initialData?.meta?.testConfig ?? { enabled: false });
setProxyConfig(initialData?.meta?.proxyConfig ?? { enabled: false });
setPricingConfig({ setPricingConfig({
enabled: enabled:
initialData?.meta?.costMultiplier !== undefined || initialData?.meta?.costMultiplier !== undefined ||
@@ -1070,6 +1075,7 @@ export function ProviderForm({
? selectedGitHubAccountId ? selectedGitHubAccountId
: undefined, : undefined,
testConfig: testConfig.enabled ? testConfig : undefined, testConfig: testConfig.enabled ? testConfig : undefined,
proxyConfig: proxyConfig.enabled ? proxyConfig : undefined,
costMultiplier: pricingConfig.enabled costMultiplier: pricingConfig.enabled
? pricingConfig.costMultiplier ? pricingConfig.costMultiplier
: undefined, : undefined,
@@ -1841,8 +1847,10 @@ export function ProviderForm({
appId !== "openclaw" && ( appId !== "openclaw" && (
<ProviderAdvancedConfig <ProviderAdvancedConfig
testConfig={testConfig} testConfig={testConfig}
proxyConfig={proxyConfig}
pricingConfig={pricingConfig} pricingConfig={pricingConfig}
onTestConfigChange={setTestConfig} onTestConfigChange={setTestConfig}
onProxyConfigChange={setProxyConfig}
onPricingConfigChange={setPricingConfig} onPricingConfigChange={setPricingConfig}
/> />
)} )}
+1 -1
View File
@@ -85,7 +85,7 @@ export function SessionItem({
{getProviderLabel(session.providerId, t)} {getProviderLabel(session.providerId, t)}
</TooltipContent> </TooltipContent>
</Tooltip> </Tooltip>
<span className="text-sm font-medium line-clamp-2 flex-1"> <span className="text-sm font-medium truncate flex-1">
{searchQuery ? highlightText(title, searchQuery) : title} {searchQuery ? highlightText(title, searchQuery) : title}
</span> </span>
<ChevronRight <ChevronRight
+44 -70
View File
@@ -1,7 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { useSessionSearch } from "@/hooks/useSessionSearch"; import { useSessionSearch } from "@/hooks/useSessionSearch";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useVirtualizer } from "@tanstack/react-virtual";
import { toast } from "sonner"; import { toast } from "sonner";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import { import {
@@ -70,7 +69,8 @@ export function SessionManagerPage({ appId }: { appId: string }) {
const { data, isLoading, refetch } = useSessionsQuery(); const { data, isLoading, refetch } = useSessionsQuery();
const sessions = data ?? []; const sessions = data ?? [];
const detailRef = useRef<HTMLDivElement | null>(null); const detailRef = useRef<HTMLDivElement | null>(null);
const scrollContainerRef = useRef<HTMLDivElement | null>(null); const messagesEndRef = useRef<HTMLDivElement | null>(null);
const messageRefs = useRef<Map<number, HTMLDivElement>>(new Map());
const [activeMessageIndex, setActiveMessageIndex] = useState<number | null>( const [activeMessageIndex, setActiveMessageIndex] = useState<number | null>(
null, null,
); );
@@ -134,20 +134,6 @@ export function SessionManagerPage({ appId }: { appId: string }) {
const deleteSessionMutation = useDeleteSessionMutation(); const deleteSessionMutation = useDeleteSessionMutation();
const isDeleting = deleteSessionMutation.isPending || isBatchDeleting; const isDeleting = deleteSessionMutation.isPending || isBatchDeleting;
const virtualizer = useVirtualizer({
count: messages.length,
getScrollElement: () => scrollContainerRef.current,
estimateSize: () => 120,
overscan: 5,
gap: 12,
});
useEffect(() => {
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTop = 0;
}
}, [selectedKey]);
useEffect(() => { useEffect(() => {
const validKeys = new Set( const validKeys = new Set(
sessions.map((session) => getSessionKey(session)), sessions.map((session) => getSessionKey(session)),
@@ -180,14 +166,27 @@ export function SessionManagerPage({ appId }: { appId: string }) {
}, [messages]); }, [messages]);
const scrollToMessage = (index: number) => { const scrollToMessage = (index: number) => {
virtualizer.scrollToIndex(index, { align: "center", behavior: "smooth" }); const el = messageRefs.current.get(index);
if (el) {
el.scrollIntoView({ behavior: "smooth", block: "center" });
setActiveMessageIndex(index); setActiveMessageIndex(index);
setTocDialogOpen(false); setTocDialogOpen(false); // 关闭弹窗
// 清除高亮状态
setTimeout(() => setActiveMessageIndex(null), 2000); setTimeout(() => setActiveMessageIndex(null), 2000);
}
}; };
const handleCopy = useCallback( // 清理定时器
async (text: string, successMessage: string) => { useEffect(() => {
return () => {
// 这里的 setTimeout 其实无法直接清理,因为它在函数闭包里。
// 如果要严格清理,需要用 useRef 存 timer id。
// 但对于 2秒的高亮清除,通常不清理也没大问题。
// 为了代码规范,我们在组件卸载时将 activeMessageIndex 重置 (虽然 React 会处理)
};
}, []);
const handleCopy = async (text: string, successMessage: string) => {
try { try {
await navigator.clipboard.writeText(text); await navigator.clipboard.writeText(text);
toast.success(successMessage); toast.success(successMessage);
@@ -197,19 +196,7 @@ export function SessionManagerPage({ appId }: { appId: string }) {
t("common.error", { defaultValue: "Copy failed" }), t("common.error", { defaultValue: "Copy failed" }),
); );
} }
}, };
[t],
);
const handleMessageCopy = useCallback(
(content: string) => {
void handleCopy(
content,
t("sessionManager.messageCopied", { defaultValue: "已复制消息内容" }),
);
},
[handleCopy, t],
);
const handleResume = async () => { const handleResume = async () => {
if (!selectedSession?.resumeCommand) return; if (!selectedSession?.resumeCommand) return;
@@ -986,9 +973,9 @@ export function SessionManagerPage({ appId }: { appId: string }) {
<CardContent className="flex-1 min-h-0 p-0"> <CardContent className="flex-1 min-h-0 p-0">
<div className="flex h-full min-w-0"> <div className="flex h-full min-w-0">
{/* 消息列表 */} {/* 消息列表 */}
<div className="flex-1 min-w-0 flex flex-col"> <ScrollArea className="flex-1 min-w-0">
<div className="px-4 pt-4 pb-2 min-w-0"> <div className="p-4 min-w-0">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2 mb-3">
<MessageSquare className="size-4 text-muted-foreground" /> <MessageSquare className="size-4 text-muted-foreground" />
<span className="text-sm font-medium"> <span className="text-sm font-medium">
{t("sessionManager.conversationHistory", { {t("sessionManager.conversationHistory", {
@@ -999,11 +986,7 @@ export function SessionManagerPage({ appId }: { appId: string }) {
{messages.length} {messages.length}
</Badge> </Badge>
</div> </div>
</div>
<div
ref={scrollContainerRef}
className="flex-1 overflow-y-auto px-4 pb-4 min-w-0"
>
{isLoadingMessages ? ( {isLoadingMessages ? (
<div className="flex items-center justify-center py-12"> <div className="flex items-center justify-center py-12">
<RefreshCw className="size-5 animate-spin text-muted-foreground" /> <RefreshCw className="size-5 animate-spin text-muted-foreground" />
@@ -1016,41 +999,32 @@ export function SessionManagerPage({ appId }: { appId: string }) {
</p> </p>
</div> </div>
) : ( ) : (
<div <div className="space-y-3">
style={{ {messages.map((message, index) => (
height: virtualizer.getTotalSize(),
position: "relative",
}}
>
{virtualizer
.getVirtualItems()
.map((virtualRow) => (
<div
key={virtualRow.key}
data-index={virtualRow.index}
ref={virtualizer.measureElement}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${virtualRow.start}px)`,
}}
>
<SessionMessageItem <SessionMessageItem
message={messages[virtualRow.index]} key={`${message.role}-${index}`}
isActive={ message={message}
activeMessageIndex === virtualRow.index index={index}
} isActive={activeMessageIndex === index}
searchQuery={search} searchQuery={search}
onCopy={handleMessageCopy} setRef={(el) => {
if (el) messageRefs.current.set(index, el);
}}
onCopy={(content) =>
handleCopy(
content,
t("sessionManager.messageCopied", {
defaultValue: "已复制消息内容",
}),
)
}
/> />
</div>
))} ))}
<div ref={messagesEndRef} />
</div> </div>
)} )}
</div> </div>
</div> </ScrollArea>
{/* 右侧目录 - 类似少数派 (大屏幕) */} {/* 右侧目录 - 类似少数派 (大屏幕) */}
<SessionTocSidebar <SessionTocSidebar
+10 -49
View File
@@ -1,5 +1,4 @@
import { memo, useState } from "react"; import { Copy } from "lucide-react";
import { ChevronDown, ChevronUp, Copy } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -17,40 +16,29 @@ import {
highlightText, highlightText,
} from "./utils"; } from "./utils";
const COLLAPSE_THRESHOLD = 3000;
const COLLAPSED_LENGTH = 1500;
interface SessionMessageItemProps { interface SessionMessageItemProps {
message: SessionMessage; message: SessionMessage;
index: number;
isActive: boolean; isActive: boolean;
searchQuery?: string; searchQuery?: string;
setRef: (el: HTMLDivElement | null) => void;
onCopy: (content: string) => void; onCopy: (content: string) => void;
} }
export const SessionMessageItem = memo(function SessionMessageItem({ export function SessionMessageItem({
message, message,
isActive, isActive,
searchQuery, searchQuery,
setRef,
onCopy, onCopy,
}: SessionMessageItemProps) { }: SessionMessageItemProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
const isLong = message.content.length > COLLAPSE_THRESHOLD;
const hasSearchMatch =
isLong &&
!expanded &&
!!searchQuery &&
message.content.toLowerCase().includes(searchQuery.toLowerCase());
const collapsed = isLong && !expanded && !hasSearchMatch;
const displayContent = collapsed
? message.content.slice(0, COLLAPSED_LENGTH) + "…"
: message.content;
return ( return (
<div <div
ref={setRef}
className={cn( className={cn(
"rounded-lg border px-3 py-2.5 relative group transition-shadow min-w-0", "rounded-lg border px-3 py-2.5 relative group transition-all min-w-0",
message.role.toLowerCase() === "user" message.role.toLowerCase() === "user"
? "bg-primary/5 border-primary/20 ml-8" ? "bg-primary/5 border-primary/20 ml-8"
: message.role.toLowerCase() === "assistant" : message.role.toLowerCase() === "assistant"
@@ -88,36 +76,9 @@ export const SessionMessageItem = memo(function SessionMessageItem({
</div> </div>
<div className="whitespace-pre-wrap break-words [overflow-wrap:anywhere] text-sm leading-relaxed min-w-0"> <div className="whitespace-pre-wrap break-words [overflow-wrap:anywhere] text-sm leading-relaxed min-w-0">
{searchQuery {searchQuery
? highlightText(displayContent, searchQuery) ? highlightText(message.content, searchQuery)
: displayContent} : message.content}
</div> </div>
{isLong && !hasSearchMatch && (
<button
type="button"
aria-expanded={expanded}
onClick={() => setExpanded((v) => !v)}
className="flex items-center gap-1 mt-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{expanded ? (
<>
<ChevronUp className="size-3" />
{t("sessionManager.collapseContent", {
defaultValue: "收起",
})}
</>
) : (
<>
<ChevronDown className="size-3" />
{t("sessionManager.expandContent", {
defaultValue: "展开完整内容",
})}
<span className="text-muted-foreground/60">
({Math.round(message.content.length / 1000)}k)
</span>
</>
)}
</button>
)}
</div> </div>
); );
}); }
@@ -3,7 +3,6 @@ import type { SettingsFormState } from "@/hooks/useSettings";
import { AppWindow, MonitorUp, Power, EyeOff } from "lucide-react"; import { AppWindow, MonitorUp, Power, EyeOff } from "lucide-react";
import { ToggleRow } from "@/components/ui/toggle-row"; import { ToggleRow } from "@/components/ui/toggle-row";
import { AnimatePresence, motion } from "framer-motion"; import { AnimatePresence, motion } from "framer-motion";
import { isLinux } from "@/lib/platform";
interface WindowSettingsProps { interface WindowSettingsProps {
settings: SettingsFormState; settings: SettingsFormState;
@@ -76,18 +75,6 @@ export function WindowSettings({ settings, onChange }: WindowSettingsProps) {
onChange({ minimizeToTrayOnClose: value }) onChange({ minimizeToTrayOnClose: value })
} }
/> />
{isLinux() && (
<ToggleRow
icon={<AppWindow className="h-4 w-4 text-amber-500" />}
title={t("settings.useAppWindowControls")}
description={t("settings.useAppWindowControlsDescription")}
checked={!!settings.useAppWindowControls}
onCheckedChange={(value) =>
onChange({ useAppWindowControls: value })
}
/>
)}
</div> </div>
</section> </section>
); );
+1 -4
View File
@@ -9,21 +9,18 @@ import {
} from "@/components/ui/table"; } from "@/components/ui/table";
import { useModelStats } from "@/lib/query/usage"; import { useModelStats } from "@/lib/query/usage";
import { fmtUsd } from "./format"; import { fmtUsd } from "./format";
import type { UsageRangeSelection } from "@/types/usage";
interface ModelStatsTableProps { interface ModelStatsTableProps {
range: UsageRangeSelection;
appType?: string; appType?: string;
refreshIntervalMs: number; refreshIntervalMs: number;
} }
export function ModelStatsTable({ export function ModelStatsTable({
range,
appType, appType,
refreshIntervalMs, refreshIntervalMs,
}: ModelStatsTableProps) { }: ModelStatsTableProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: stats, isLoading } = useModelStats(range, appType, { const { data: stats, isLoading } = useModelStats(appType, {
refetchInterval: refreshIntervalMs > 0 ? refreshIntervalMs : false, refetchInterval: refreshIntervalMs > 0 ? refreshIntervalMs : false,
}); });
+1 -4
View File
@@ -9,21 +9,18 @@ import {
} from "@/components/ui/table"; } from "@/components/ui/table";
import { useProviderStats } from "@/lib/query/usage"; import { useProviderStats } from "@/lib/query/usage";
import { fmtUsd } from "./format"; import { fmtUsd } from "./format";
import type { UsageRangeSelection } from "@/types/usage";
interface ProviderStatsTableProps { interface ProviderStatsTableProps {
range: UsageRangeSelection;
appType?: string; appType?: string;
refreshIntervalMs: number; refreshIntervalMs: number;
} }
export function ProviderStatsTable({ export function ProviderStatsTable({
range,
appType, appType,
refreshIntervalMs, refreshIntervalMs,
}: ProviderStatsTableProps) { }: ProviderStatsTableProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: stats, isLoading } = useProviderStats(range, appType, { const { data: stats, isLoading } = useProviderStats(appType, {
refetchInterval: refreshIntervalMs > 0 ? refreshIntervalMs : false, refetchInterval: refreshIntervalMs > 0 ? refreshIntervalMs : false,
}); });
+343 -186
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react"; import { useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
Table, Table,
@@ -17,9 +17,10 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { useRequestLogs } from "@/lib/query/usage"; import { useRequestLogs, usageKeys } from "@/lib/query/usage";
import type { LogFilters, UsageRangeSelection } from "@/types/usage"; import { useQueryClient } from "@tanstack/react-query";
import { Calendar, ChevronLeft, ChevronRight, Search, X } from "lucide-react"; import type { LogFilters } from "@/types/usage";
import { ChevronLeft, ChevronRight, RefreshCw, Search, X } from "lucide-react";
import { import {
fmtInt, fmtInt,
fmtUsd, fmtUsd,
@@ -28,30 +29,36 @@ import {
} from "./format"; } from "./format";
interface RequestLogTableProps { interface RequestLogTableProps {
range: UsageRangeSelection;
rangeLabel: string;
appType?: string; appType?: string;
refreshIntervalMs: number; refreshIntervalMs: number;
} }
const ONE_DAY_SECONDS = 24 * 60 * 60;
const MAX_FIXED_RANGE_SECONDS = 30 * ONE_DAY_SECONDS;
type TimeMode = "rolling" | "fixed";
export function RequestLogTable({ export function RequestLogTable({
range,
rangeLabel,
appType: dashboardAppType, appType: dashboardAppType,
refreshIntervalMs, refreshIntervalMs,
}: RequestLogTableProps) { }: RequestLogTableProps) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const queryClient = useQueryClient();
const getRollingRange = () => {
const now = Math.floor(Date.now() / 1000);
const oneDayAgo = now - ONE_DAY_SECONDS;
return { startDate: oneDayAgo, endDate: now };
};
const [appliedTimeMode, setAppliedTimeMode] = useState<TimeMode>("rolling");
const [draftTimeMode, setDraftTimeMode] = useState<TimeMode>("rolling");
const [appliedFilters, setAppliedFilters] = useState<LogFilters>({}); const [appliedFilters, setAppliedFilters] = useState<LogFilters>({});
const [draftFilters, setDraftFilters] = useState<LogFilters>({}); const [draftFilters, setDraftFilters] = useState<LogFilters>({});
const [page, setPage] = useState(0); const [page, setPage] = useState(0);
const [pageInput, setPageInput] = useState("");
const pageSize = 20; const pageSize = 20;
const [validationError, setValidationError] = useState<string | null>(null);
// Reset page when the dashboard range changes
useEffect(() => {
setPage(0);
}, [range.preset, range.customStartDate, range.customEndDate]);
// When dashboard-level app filter is active (not "all"), override the local appType filter // When dashboard-level app filter is active (not "all"), override the local appType filter
const dashboardAppTypeActive = dashboardAppType && dashboardAppType !== "all"; const dashboardAppTypeActive = dashboardAppType && dashboardAppType !== "all";
@@ -61,7 +68,8 @@ export function RequestLogTable({
const { data: result, isLoading } = useRequestLogs({ const { data: result, isLoading } = useRequestLogs({
filters: effectiveFilters, filters: effectiveFilters,
range, timeMode: appliedTimeMode,
rollingWindowSeconds: ONE_DAY_SECONDS,
page, page,
pageSize, pageSize,
options: { options: {
@@ -74,52 +82,122 @@ export function RequestLogTable({
const totalPages = Math.ceil(total / pageSize); const totalPages = Math.ceil(total / pageSize);
const handleSearch = () => { const handleSearch = () => {
setAppliedFilters(draftFilters); setValidationError(null);
if (draftTimeMode === "fixed") {
const start = draftFilters.startDate;
const end = draftFilters.endDate;
if (typeof start !== "number" || typeof end !== "number") {
setValidationError(
t("usage.invalidTimeRange", "请选择完整的开始/结束时间"),
);
return;
}
if (start > end) {
setValidationError(
t("usage.invalidTimeRangeOrder", "开始时间不能晚于结束时间"),
);
return;
}
if (end - start > MAX_FIXED_RANGE_SECONDS) {
setValidationError(
t("usage.timeRangeTooLarge", "时间范围过大,请缩小范围"),
);
return;
}
}
setAppliedTimeMode(draftTimeMode);
setAppliedFilters((prev) => {
const next = { ...prev, ...draftFilters };
if (draftTimeMode === "rolling") {
delete next.startDate;
delete next.endDate;
}
return next;
});
setPage(0); setPage(0);
}; };
const handleReset = () => { const handleReset = () => {
setValidationError(null);
setAppliedTimeMode("rolling");
setDraftTimeMode("rolling");
setDraftFilters({}); setDraftFilters({});
setAppliedFilters({}); setAppliedFilters({});
setPage(0); setPage(0);
}; };
const handleGoToPage = () => { const handleRefresh = () => {
const trimmed = pageInput.trim(); const key = {
if (!/^\d+$/.test(trimmed)) return; timeMode: appliedTimeMode,
const parsed = Number(trimmed); rollingWindowSeconds:
if (parsed < 1 || parsed > totalPages) return; appliedTimeMode === "rolling" ? ONE_DAY_SECONDS : undefined,
setPage(parsed - 1); appType: appliedFilters.appType,
setPageInput(""); providerName: appliedFilters.providerName,
model: appliedFilters.model,
statusCode: appliedFilters.statusCode,
startDate:
appliedTimeMode === "fixed" ? appliedFilters.startDate : undefined,
endDate: appliedTimeMode === "fixed" ? appliedFilters.endDate : undefined,
};
queryClient.invalidateQueries({
queryKey: usageKeys.logs(key, page, pageSize),
});
};
// 将 Unix 时间戳转换为本地时间的 datetime-local 格式
const timestampToLocalDatetime = (timestamp: number): string => {
const date = new Date(timestamp * 1000);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
return `${year}-${month}-${day}T${hours}:${minutes}`;
};
// 将 datetime-local 格式转换为 Unix 时间戳
const localDatetimeToTimestamp = (datetime: string): number | undefined => {
if (!datetime) return undefined;
// 验证格式是否完整 (YYYY-MM-DDTHH:mm)
if (datetime.length < 16) return undefined;
const timestamp = new Date(datetime).getTime();
// 验证是否为有效日期
if (isNaN(timestamp)) return undefined;
return Math.floor(timestamp / 1000);
}; };
const language = i18n.resolvedLanguage || i18n.language || "en"; const language = i18n.resolvedLanguage || i18n.language || "en";
const locale = getLocaleFromLanguage(language); const locale = getLocaleFromLanguage(language);
const rollingRangeForDisplay =
draftTimeMode === "rolling" ? getRollingRange() : null;
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<div className="rounded-lg border bg-card/50 p-2 backdrop-blur-sm"> {/* 筛选栏 */}
<div className="flex flex-wrap items-center gap-1.5"> <div className="flex flex-col gap-4 rounded-lg border bg-card/50 p-4 backdrop-blur-sm">
{/* App type */} <div className="flex flex-wrap items-center gap-3">
{/* App type */}
<Select <Select
value={ value={
dashboardAppTypeActive dashboardAppTypeActive
? dashboardAppType ? dashboardAppType
: draftFilters.appType || "all" : draftFilters.appType || "all"
} }
onValueChange={(v) => { onValueChange={(v) =>
const next = { setDraftFilters({
...draftFilters, ...draftFilters,
appType: v === "all" ? undefined : v, appType: v === "all" ? undefined : v,
}; })
setDraftFilters(next); }
setAppliedFilters(next);
setPage(0);
}}
disabled={!!dashboardAppTypeActive} disabled={!!dashboardAppTypeActive}
> >
<SelectTrigger className="h-8 w-[110px] bg-background text-xs"> <SelectTrigger className="w-[130px] bg-background">
<SelectValue placeholder={t("usage.appType")} /> <SelectValue placeholder={t("usage.appType")} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@@ -130,11 +208,10 @@ export function RequestLogTable({
</SelectContent> </SelectContent>
</Select> </Select>
{/* Status code */}
<Select <Select
value={draftFilters.statusCode?.toString() || "all"} value={draftFilters.statusCode?.toString() || "all"}
onValueChange={(v) => { onValueChange={(v) =>
const next = { setDraftFilters({
...draftFilters, ...draftFilters,
statusCode: statusCode:
v === "all" v === "all"
@@ -142,31 +219,28 @@ export function RequestLogTable({
: Number.isFinite(Number.parseInt(v, 10)) : Number.isFinite(Number.parseInt(v, 10))
? Number.parseInt(v, 10) ? Number.parseInt(v, 10)
: undefined, : undefined,
}; })
setDraftFilters(next); }
setAppliedFilters(next);
setPage(0);
}}
> >
<SelectTrigger className="h-8 w-[100px] bg-background text-xs"> <SelectTrigger className="w-[130px] bg-background">
<SelectValue placeholder={t("usage.statusCode")} /> <SelectValue placeholder={t("usage.statusCode")} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="all">{t("common.all")}</SelectItem> <SelectItem value="all">{t("common.all")}</SelectItem>
<SelectItem value="200">200 OK</SelectItem> <SelectItem value="200">200 OK</SelectItem>
<SelectItem value="400">400</SelectItem> <SelectItem value="400">400 Bad Request</SelectItem>
<SelectItem value="401">401</SelectItem> <SelectItem value="401">401 Unauthorized</SelectItem>
<SelectItem value="429">429</SelectItem> <SelectItem value="429">429 Rate Limit</SelectItem>
<SelectItem value="500">500</SelectItem> <SelectItem value="500">500 Server Error</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
{/* Provider search */} <div className="flex items-center gap-2 flex-1 min-w-[300px]">
<div className="relative min-w-[140px] flex-1"> <div className="relative flex-1">
<Search className="absolute left-2 top-2 h-3.5 w-3.5 text-muted-foreground" /> <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input <Input
placeholder={t("usage.searchProviderPlaceholder")} placeholder={t("usage.searchProviderPlaceholder")}
className="h-8 bg-background pl-7 text-xs" className="pl-9 bg-background"
value={draftFilters.providerName || ""} value={draftFilters.providerName || ""}
onChange={(e) => onChange={(e) =>
setDraftFilters({ setDraftFilters({
@@ -174,17 +248,11 @@ export function RequestLogTable({
providerName: e.target.value || undefined, providerName: e.target.value || undefined,
}) })
} }
onKeyDown={(e) => {
if (e.key === "Enter") handleSearch();
}}
/> />
</div> </div>
{/* Model search */}
<div className="relative min-w-[120px] flex-1">
<Input <Input
placeholder={t("usage.searchModelPlaceholder")} placeholder={t("usage.searchModelPlaceholder")}
className="h-8 bg-background text-xs" className="w-[180px] bg-background"
value={draftFilters.model || ""} value={draftFilters.model || ""}
onChange={(e) => onChange={(e) =>
setDraftFilters({ setDraftFilters({
@@ -192,42 +260,91 @@ export function RequestLogTable({
model: e.target.value || undefined, model: e.target.value || undefined,
}) })
} }
onKeyDown={(e) => { />
if (e.key === "Enter") handleSearch(); </div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span className="whitespace-nowrap">{t("usage.timeRange")}:</span>
<Input
type="datetime-local"
className="h-8 w-[200px] bg-background"
value={
(rollingRangeForDisplay?.startDate ?? draftFilters.startDate)
? timestampToLocalDatetime(
(rollingRangeForDisplay?.startDate ??
draftFilters.startDate) as number,
)
: ""
}
onChange={(e) => {
const timestamp = localDatetimeToTimestamp(e.target.value);
setDraftTimeMode("fixed");
setDraftFilters({
...draftFilters,
startDate: timestamp,
});
}}
/>
<span>-</span>
<Input
type="datetime-local"
className="h-8 w-[200px] bg-background"
value={
(rollingRangeForDisplay?.endDate ?? draftFilters.endDate)
? timestampToLocalDatetime(
(rollingRangeForDisplay?.endDate ??
draftFilters.endDate) as number,
)
: ""
}
onChange={(e) => {
const timestamp = localDatetimeToTimestamp(e.target.value);
setDraftTimeMode("fixed");
setDraftFilters({
...draftFilters,
endDate: timestamp,
});
}} }}
/> />
</div> </div>
{/* Time range badge */} <div className="flex items-center gap-2 ml-auto">
<div className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border/60 bg-background px-2 text-xs text-muted-foreground">
<Calendar className="h-3.5 w-3.5 shrink-0" />
<span className="max-w-[180px] truncate text-foreground">
{rangeLabel}
</span>
</div>
{/* Search & Reset (icon-only) */}
<Button <Button
size="icon" size="sm"
variant="default" variant="default"
onClick={handleSearch} onClick={handleSearch}
className="h-8 w-8" className="h-8"
title={t("common.search")}
> >
<Search className="h-3.5 w-3.5" /> <Search className="mr-2 h-3.5 w-3.5" />
{t("common.search")}
</Button> </Button>
<Button <Button
size="icon" size="sm"
variant="outline" variant="outline"
onClick={handleReset} onClick={handleReset}
className="h-8 w-8" className="h-8"
title={t("common.reset")}
> >
<X className="h-3.5 w-3.5" /> <X className="mr-2 h-3.5 w-3.5" />
{t("common.reset")}
</Button>
<Button
size="sm"
variant="ghost"
onClick={handleRefresh}
className="h-8 px-2"
>
<RefreshCw className="h-4 w-4" />
</Button> </Button>
</div> </div>
</div> </div>
{validationError && (
<div className="text-sm text-red-600">{validationError}</div>
)}
</div>
{isLoading ? ( {isLoading ? (
<div className="h-[400px] animate-pulse rounded bg-gray-100" /> <div className="h-[400px] animate-pulse rounded bg-gray-100" />
) : ( ) : (
@@ -236,31 +353,40 @@ export function RequestLogTable({
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead className="text-center whitespace-nowrap"> <TableHead className="whitespace-nowrap">
{t("usage.time")} {t("usage.time")}
</TableHead> </TableHead>
<TableHead className="text-center whitespace-nowrap"> <TableHead className="whitespace-nowrap">
{t("usage.provider")} {t("usage.provider")}
</TableHead> </TableHead>
<TableHead className="text-center whitespace-nowrap"> <TableHead className="min-w-[200px] whitespace-nowrap">
{t("usage.billingModel")} {t("usage.billingModel")}
</TableHead> </TableHead>
<TableHead className="text-center whitespace-nowrap"> <TableHead className="text-right whitespace-nowrap">
{t("usage.inputTokens")} {t("usage.inputTokens")}
</TableHead> </TableHead>
<TableHead className="text-center whitespace-nowrap"> <TableHead className="text-right whitespace-nowrap">
{t("usage.outputTokens")} {t("usage.outputTokens")}
</TableHead> </TableHead>
<TableHead className="text-center whitespace-nowrap"> <TableHead className="text-right min-w-[90px] whitespace-nowrap">
{t("usage.cacheReadTokens")}
</TableHead>
<TableHead className="text-right min-w-[90px] whitespace-nowrap">
{t("usage.cacheCreationTokens")}
</TableHead>
<TableHead className="text-right whitespace-nowrap">
{t("usage.multiplier")}
</TableHead>
<TableHead className="text-right whitespace-nowrap">
{t("usage.totalCost")} {t("usage.totalCost")}
</TableHead> </TableHead>
<TableHead className="text-center whitespace-nowrap"> <TableHead className="text-center min-w-[140px] whitespace-nowrap">
{t("usage.timingInfo")} {t("usage.timingInfo")}
</TableHead> </TableHead>
<TableHead className="text-center whitespace-nowrap"> <TableHead className="whitespace-nowrap">
{t("usage.status")} {t("usage.status")}
</TableHead> </TableHead>
<TableHead className="text-center whitespace-nowrap"> <TableHead className="whitespace-nowrap">
{t("usage.source", { defaultValue: "Source" })} {t("usage.source", { defaultValue: "Source" })}
</TableHead> </TableHead>
</TableRow> </TableRow>
@@ -269,7 +395,7 @@ export function RequestLogTable({
{logs.length === 0 ? ( {logs.length === 0 ? (
<TableRow> <TableRow>
<TableCell <TableCell
colSpan={9} colSpan={12}
className="text-center text-muted-foreground" className="text-center text-muted-foreground"
> >
{t("usage.noData")} {t("usage.noData")}
@@ -278,96 +404,140 @@ export function RequestLogTable({
) : ( ) : (
logs.map((log) => ( logs.map((log) => (
<TableRow key={log.requestId}> <TableRow key={log.requestId}>
<TableCell className="text-center whitespace-nowrap text-xs px-1.5"> <TableCell>
{new Date(log.createdAt * 1000).toLocaleString(locale, { {new Date(log.createdAt * 1000).toLocaleString(locale)}
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
})}
</TableCell> </TableCell>
<TableCell className="text-center"> <TableCell>
{log.providerName || t("usage.unknownProvider")} {log.providerName || t("usage.unknownProvider")}
</TableCell> </TableCell>
<TableCell className="text-center font-mono text-xs max-w-[200px]"> <TableCell className="font-mono text-xs max-w-[200px]">
<div <div
className="truncate" className="truncate"
title={ title={
log.requestModel && log.requestModel !== log.model log.requestModel && log.requestModel !== log.model
? `${log.requestModel} ${log.model}` ? `${t("usage.requestModel")}: ${log.requestModel}\n${t("usage.responseModel")}: ${log.model}`
: log.model : log.model
} }
> >
{log.requestModel &&
log.requestModel !== log.model ? (
<span>
{log.requestModel}
<span className="text-muted-foreground">
{" → "}
{log.model} {log.model}
</span>
</span>
) : (
log.model
)}
</div> </div>
{log.requestModel && log.requestModel !== log.model && (
<div
className="truncate text-muted-foreground text-[10px]"
title={log.requestModel}
>
{log.requestModel}
</div>
)}
</TableCell> </TableCell>
<TableCell className="text-center px-1.5"> <TableCell className="text-right">
<div className="tabular-nums">
{fmtInt(log.inputTokens, locale)} {fmtInt(log.inputTokens, locale)}
</div>
{(log.cacheReadTokens > 0 ||
log.cacheCreationTokens > 0) && (
<div className="text-[10px] text-muted-foreground whitespace-nowrap">
{[
log.cacheReadTokens > 0 &&
`R${fmtInt(log.cacheReadTokens, locale)}`,
log.cacheCreationTokens > 0 &&
`W${fmtInt(log.cacheCreationTokens, locale)}`,
]
.filter(Boolean)
.join("·")}
</div>
)}
</TableCell> </TableCell>
<TableCell className="text-center"> <TableCell className="text-right">
{fmtInt(log.outputTokens, locale)} {fmtInt(log.outputTokens, locale)}
</TableCell> </TableCell>
<TableCell className="text-center px-1.5"> <TableCell className="text-right">
<div className="font-medium tabular-nums"> {fmtInt(log.cacheReadTokens, locale)}
{fmtUsd(log.totalCostUsd, 4)}
</div>
{parseFiniteNumber(log.costMultiplier) != null &&
parseFiniteNumber(log.costMultiplier) !== 1 && (
<div className="text-[11px] text-muted-foreground">
×
{parseFiniteNumber(log.costMultiplier)?.toFixed(
2,
)}
</div>
)}
</TableCell> </TableCell>
<TableCell className="text-center whitespace-nowrap text-xs tabular-nums"> <TableCell className="text-right">
{(log.latencyMs / 1000).toFixed(1)}s {fmtInt(log.cacheCreationTokens, locale)}
{log.firstTokenMs != null && ( </TableCell>
<span className="text-muted-foreground"> <TableCell className="text-right font-mono text-xs">
/{(log.firstTokenMs / 1000).toFixed(1)}s {(parseFiniteNumber(log.costMultiplier) ?? 1) !== 1 ? (
<span className="text-orange-600">
×{log.costMultiplier}
</span> </span>
) : (
<span className="text-muted-foreground">×1</span>
)} )}
</TableCell> </TableCell>
<TableCell className="text-center"> <TableCell className="text-right">
{fmtUsd(log.totalCostUsd, 6)}
</TableCell>
<TableCell>
<div className="flex items-center justify-center gap-1">
{(() => {
const durationMs =
typeof log.durationMs === "number"
? log.durationMs
: log.latencyMs;
const durationSec = durationMs / 1000;
const durationColor = Number.isFinite(durationSec)
? durationSec <= 5
? "bg-green-100 text-green-800"
: durationSec <= 120
? "bg-orange-100 text-orange-800"
: "bg-red-200 text-red-900"
: "bg-gray-100 text-gray-700";
return (
<span <span
className={ className={`inline-flex items-center justify-center rounded-full px-2 py-0.5 text-xs ${durationColor}`}
>
{Number.isFinite(durationSec)
? `${Math.round(durationSec)}s`
: "--"}
</span>
);
})()}
{log.isStreaming &&
log.firstTokenMs != null &&
(() => {
const firstSec = log.firstTokenMs / 1000;
const firstColor = Number.isFinite(firstSec)
? firstSec <= 5
? "bg-green-100 text-green-800"
: firstSec <= 120
? "bg-orange-100 text-orange-800"
: "bg-red-200 text-red-900"
: "bg-gray-100 text-gray-700";
return (
<span
className={`inline-flex items-center justify-center rounded-full px-2 py-0.5 text-xs ${firstColor}`}
>
{Number.isFinite(firstSec)
? `${firstSec.toFixed(1)}s`
: "--"}
</span>
);
})()}
<span
className={`inline-flex items-center justify-center rounded-full px-2 py-0.5 text-xs ${
log.isStreaming
? "bg-blue-100 text-blue-800"
: "bg-purple-100 text-purple-800"
}`}
>
{log.isStreaming
? t("usage.stream")
: t("usage.nonStream")}
</span>
</div>
</TableCell>
<TableCell>
<span
className={`inline-flex rounded-full px-2 py-1 text-xs ${
log.statusCode >= 200 && log.statusCode < 300 log.statusCode >= 200 && log.statusCode < 300
? "text-green-600" ? "bg-green-100 text-green-800"
: "text-red-600" : "bg-red-100 text-red-800"
} }`}
> >
{log.statusCode} {log.statusCode}
</span> </span>
</TableCell> </TableCell>
<TableCell className="text-center text-xs text-muted-foreground"> <TableCell>
{log.dataSource || "proxy"} {log.dataSource && log.dataSource !== "proxy" ? (
<span className="inline-flex rounded-full px-2 py-0.5 text-[10px] bg-indigo-100 text-indigo-800">
{t(`usage.dataSource.${log.dataSource}`, {
defaultValue: log.dataSource,
})}
</span>
) : (
<span className="inline-flex rounded-full px-2 py-0.5 text-[10px] bg-gray-100 text-gray-600">
{t("usage.dataSource.proxy", {
defaultValue: "Proxy",
})}
</span>
)}
</TableCell> </TableCell>
</TableRow> </TableRow>
)) ))
@@ -376,8 +546,12 @@ export function RequestLogTable({
</Table> </Table>
</div> </div>
<div className="flex items-center justify-between text-sm text-muted-foreground"> {/* 分页控件 */}
<span>{t("usage.totalRecords", { total })}</span> {total > 0 && (
<div className="flex items-center justify-between px-2">
<span className="text-sm text-muted-foreground">
{t("usage.totalRecords", { total })}
</span>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<Button <Button
variant="outline" variant="outline"
@@ -387,33 +561,30 @@ export function RequestLogTable({
> >
<ChevronLeft className="h-4 w-4" /> <ChevronLeft className="h-4 w-4" />
</Button> </Button>
{/* 页码按钮 */}
{(() => { {(() => {
const pages: (number | string)[] = []; const pages: (number | string)[] = [];
// 3 head + 3 tail + 3 neighborhood = 9 max distinct pages if (totalPages <= 7) {
if (totalPages <= 9) {
for (let i = 0; i < totalPages; i++) pages.push(i); for (let i = 0; i < totalPages; i++) pages.push(i);
} else { } else {
const pageSet = new Set<number>(); pages.push(0);
for (let i = 0; i < 3; i++) pageSet.add(i); if (page > 2) pages.push("...");
for (let i = totalPages - 3; i < totalPages; i++)
pageSet.add(i);
for ( for (
let i = Math.max(0, page - 1); let i = Math.max(1, page - 1);
i <= Math.min(totalPages - 1, page + 1); i <= Math.min(totalPages - 2, page + 1);
i++ i++
) ) {
pageSet.add(i); pages.push(i);
const sorted = Array.from(pageSet).sort((a, b) => a - b);
for (let i = 0; i < sorted.length; i++) {
if (i > 0 && sorted[i] - sorted[i - 1] > 1) {
pages.push(`ellipsis-${i}`);
} }
pages.push(sorted[i]); if (page < totalPages - 3) pages.push("...");
pages.push(totalPages - 1);
} }
} return pages.map((p, idx) =>
return pages.map((p) =>
typeof p === "string" ? ( typeof p === "string" ? (
<span key={p} className="px-2 text-muted-foreground"> <span
key={`ellipsis-${idx}`}
className="px-2 text-muted-foreground"
>
... ...
</span> </span>
) : ( ) : (
@@ -437,23 +608,9 @@ export function RequestLogTable({
> >
<ChevronRight className="h-4 w-4" /> <ChevronRight className="h-4 w-4" />
</Button> </Button>
<div className="flex items-center gap-1 ml-2">
<Input
type="text"
value={pageInput}
onChange={(e) => setPageInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleGoToPage();
}}
placeholder={t("usage.pageInputPlaceholder")}
className="h-8 w-16 text-center text-xs"
/>
<Button variant="outline" size="sm" onClick={handleGoToPage}>
{t("usage.goToPage")}
</Button>
</div>
</div> </div>
</div> </div>
)}
</> </>
)} )}
</div> </div>
+58 -100
View File
@@ -1,15 +1,12 @@
import { useMemo, useState } from "react"; import { useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { UsageSummaryCards } from "./UsageSummaryCards"; import { UsageSummaryCards } from "./UsageSummaryCards";
import { UsageTrendChart } from "./UsageTrendChart"; import { UsageTrendChart } from "./UsageTrendChart";
import { RequestLogTable } from "./RequestLogTable"; import { RequestLogTable } from "./RequestLogTable";
import { ProviderStatsTable } from "./ProviderStatsTable"; import { ProviderStatsTable } from "./ProviderStatsTable";
import { ModelStatsTable } from "./ModelStatsTable"; import { ModelStatsTable } from "./ModelStatsTable";
import type { import type { AppTypeFilter, TimeRange } from "@/types/usage";
AppTypeFilter,
UsageRangePreset,
UsageRangeSelection,
} from "@/types/usage";
import { useUsageSummary } from "@/lib/query/usage"; import { useUsageSummary } from "@/lib/query/usage";
import { motion } from "framer-motion"; import { motion } from "framer-motion";
import { import {
@@ -30,10 +27,7 @@ import {
} from "@/components/ui/accordion"; } from "@/components/ui/accordion";
import { PricingConfigPanel } from "@/components/usage/PricingConfigPanel"; import { PricingConfigPanel } from "@/components/usage/PricingConfigPanel";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { fmtUsd, getLocaleFromLanguage, parseFiniteNumber } from "./format"; import { fmtUsd, parseFiniteNumber } from "./format";
import { resolveUsageRange } from "@/lib/usageRange";
import { UsageDateRangePicker } from "./UsageDateRangePicker";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
const APP_FILTER_OPTIONS: AppTypeFilter[] = [ const APP_FILTER_OPTIONS: AppTypeFilter[] = [
"all", "all",
@@ -42,32 +36,10 @@ const APP_FILTER_OPTIONS: AppTypeFilter[] = [
"gemini", "gemini",
]; ];
const RANGE_PRESETS: UsageRangePreset[] = ["today", "1d", "7d", "14d", "30d"];
function getPresetLabel(
preset: UsageRangePreset,
t: (key: string, options?: { defaultValue?: string }) => string,
): string {
switch (preset) {
case "today":
return t("usage.presetToday", { defaultValue: "当天" });
case "1d":
return t("usage.preset1d", { defaultValue: "1d" });
case "7d":
return t("usage.preset7d", { defaultValue: "7d" });
case "14d":
return t("usage.preset14d", { defaultValue: "14d" });
case "30d":
return t("usage.preset30d", { defaultValue: "30d" });
case "custom":
return t("usage.customRange", { defaultValue: "日历筛选" });
}
}
export function UsageDashboard() { export function UsageDashboard() {
const { t, i18n } = useTranslation(); const { t } = useTranslation();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [range, setRange] = useState<UsageRangeSelection>({ preset: "today" }); const [timeRange, setTimeRange] = useState<TimeRange>("1d");
const [appType, setAppType] = useState<AppTypeFilter>("all"); const [appType, setAppType] = useState<AppTypeFilter>("all");
const [refreshIntervalMs, setRefreshIntervalMs] = useState(30000); const [refreshIntervalMs, setRefreshIntervalMs] = useState(30000);
@@ -76,27 +48,17 @@ export function UsageDashboard() {
const currentIndex = refreshIntervalOptionsMs.indexOf( const currentIndex = refreshIntervalOptionsMs.indexOf(
refreshIntervalMs as (typeof refreshIntervalOptionsMs)[number], refreshIntervalMs as (typeof refreshIntervalOptionsMs)[number],
); );
const safeIndex = currentIndex >= 0 ? currentIndex : 3; const safeIndex = currentIndex >= 0 ? currentIndex : 3; // default 30s
const nextIndex = (safeIndex + 1) % refreshIntervalOptionsMs.length; const nextIndex = (safeIndex + 1) % refreshIntervalOptionsMs.length;
const next = refreshIntervalOptionsMs[nextIndex]; const next = refreshIntervalOptionsMs[nextIndex];
setRefreshIntervalMs(next); setRefreshIntervalMs(next);
queryClient.invalidateQueries({ queryKey: usageKeys.all }); queryClient.invalidateQueries({ queryKey: usageKeys.all });
}; };
const language = i18n.resolvedLanguage || i18n.language || "en"; const days = timeRange === "1d" ? 1 : timeRange === "7d" ? 7 : 30;
const locale = getLocaleFromLanguage(language);
const resolvedRange = useMemo(() => resolveUsageRange(range), [range]);
const rangeLabel = useMemo(() => {
if (range.preset !== "custom") {
return getPresetLabel(range.preset, t);
}
return `${new Date(resolvedRange.startDate * 1000).toLocaleString(locale)} - ${new Date( // Summary data for the app filter bar
resolvedRange.endDate * 1000, const { data: summaryData } = useUsageSummary(days, appType, {
).toLocaleString(locale)}`;
}, [locale, range, resolvedRange.endDate, resolvedRange.startDate, t]);
const { data: summaryData } = useUsageSummary(range, appType, {
refetchInterval: refreshIntervalMs > 0 ? refreshIntervalMs : false, refetchInterval: refreshIntervalMs > 0 ? refreshIntervalMs : false,
}); });
@@ -107,18 +69,55 @@ export function UsageDashboard() {
transition={{ duration: 0.4 }} transition={{ duration: 0.4 }}
className="space-y-8 pb-8" className="space-y-8 pb-8"
> >
<div className="flex flex-col gap-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4"> <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
<h2 className="text-2xl font-bold">{t("usage.title")}</h2> <h2 className="text-2xl font-bold">{t("usage.title")}</h2>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">{t("usage.subtitle")}</p>
{t("usage.subtitle")}
</p>
</div>
</div> </div>
<div className="rounded-xl border border-border/50 bg-card/40 backdrop-blur-sm p-4 space-y-4"> <Tabs
<div className="flex flex-wrap items-center gap-3"> value={timeRange}
onValueChange={(v) => setTimeRange(v as TimeRange)}
className="w-full sm:w-auto"
>
<div className="flex w-full sm:w-auto items-center gap-1">
<Button
type="button"
variant="ghost"
size="sm"
className="h-10 px-2 text-xs text-muted-foreground"
title={t("common.refresh", "刷新")}
onClick={changeRefreshInterval}
>
<RefreshCw className="mr-1 h-3.5 w-3.5" />
{refreshIntervalMs > 0 ? `${refreshIntervalMs / 1000}s` : "--"}
</Button>
<TabsList className="flex w-full sm:w-auto bg-card/60 border border-border/50 backdrop-blur-sm shadow-sm h-10 p-1">
<TabsTrigger
value="1d"
className="flex-1 sm:flex-none sm:px-6 data-[state=active]:bg-primary/10 data-[state=active]:text-primary hover:text-primary transition-colors"
>
{t("usage.today")}
</TabsTrigger>
<TabsTrigger
value="7d"
className="flex-1 sm:flex-none sm:px-6 data-[state=active]:bg-primary/10 data-[state=active]:text-primary hover:text-primary transition-colors"
>
{t("usage.last7days")}
</TabsTrigger>
<TabsTrigger
value="30d"
className="flex-1 sm:flex-none sm:px-6 data-[state=active]:bg-primary/10 data-[state=active]:text-primary hover:text-primary transition-colors"
>
{t("usage.last30days")}
</TabsTrigger>
</TabsList>
</div>
</Tabs>
</div>
{/* App type filter bar (replaces DataSourceBar) */}
<div className="rounded-xl border border-border/50 bg-card/40 backdrop-blur-sm p-4 space-y-3">
<div className="flex flex-wrap items-center gap-1.5"> <div className="flex flex-wrap items-center gap-1.5">
{APP_FILTER_OPTIONS.map((type) => ( {APP_FILTER_OPTIONS.map((type) => (
<button <button
@@ -136,43 +135,7 @@ export function UsageDashboard() {
</button> </button>
))} ))}
</div> </div>
<div className="flex items-center gap-4 text-sm text-muted-foreground">
<div className="ml-auto flex flex-wrap items-center justify-end gap-2">
<Button
type="button"
variant="ghost"
size="sm"
className="h-9 px-2 text-xs text-muted-foreground"
title={t("common.refresh", "刷新")}
onClick={changeRefreshInterval}
>
<RefreshCw className="mr-1 h-3.5 w-3.5" />
{refreshIntervalMs > 0 ? `${refreshIntervalMs / 1000}s` : "--"}
</Button>
{RANGE_PRESETS.map((preset) => (
<Button
key={preset}
type="button"
size="sm"
variant={range.preset === preset ? "default" : "outline"}
onClick={() => setRange({ preset })}
>
{getPresetLabel(preset, t)}
</Button>
))}
<UsageDateRangePicker
selection={range}
triggerLabel={rangeLabel}
onApply={(nextRange) => setRange(nextRange)}
/>
</div>
</div>
<div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
<span className="font-medium text-foreground">{rangeLabel}</span>
<span className="text-border">|</span>
<span> <span>
{(summaryData?.totalRequests ?? 0).toLocaleString()}{" "} {(summaryData?.totalRequests ?? 0).toLocaleString()}{" "}
{t("usage.requestsLabel")} {t("usage.requestsLabel")}
@@ -184,17 +147,15 @@ export function UsageDashboard() {
</span> </span>
</div> </div>
</div> </div>
</div>
<UsageSummaryCards <UsageSummaryCards
range={range} days={days}
appType={appType} appType={appType}
refreshIntervalMs={refreshIntervalMs} refreshIntervalMs={refreshIntervalMs}
/> />
<UsageTrendChart <UsageTrendChart
range={range} days={days}
rangeLabel={rangeLabel}
appType={appType} appType={appType}
refreshIntervalMs={refreshIntervalMs} refreshIntervalMs={refreshIntervalMs}
/> />
@@ -225,8 +186,6 @@ export function UsageDashboard() {
> >
<TabsContent value="logs" className="mt-0"> <TabsContent value="logs" className="mt-0">
<RequestLogTable <RequestLogTable
range={range}
rangeLabel={rangeLabel}
appType={appType} appType={appType}
refreshIntervalMs={refreshIntervalMs} refreshIntervalMs={refreshIntervalMs}
/> />
@@ -234,7 +193,6 @@ export function UsageDashboard() {
<TabsContent value="providers" className="mt-0"> <TabsContent value="providers" className="mt-0">
<ProviderStatsTable <ProviderStatsTable
range={range}
appType={appType} appType={appType}
refreshIntervalMs={refreshIntervalMs} refreshIntervalMs={refreshIntervalMs}
/> />
@@ -242,7 +200,6 @@ export function UsageDashboard() {
<TabsContent value="models" className="mt-0"> <TabsContent value="models" className="mt-0">
<ModelStatsTable <ModelStatsTable
range={range}
appType={appType} appType={appType}
refreshIntervalMs={refreshIntervalMs} refreshIntervalMs={refreshIntervalMs}
/> />
@@ -251,6 +208,7 @@ export function UsageDashboard() {
</Tabs> </Tabs>
</div> </div>
{/* Pricing Configuration */}
<Accordion type="multiple" defaultValue={[]} className="w-full space-y-4"> <Accordion type="multiple" defaultValue={[]} className="w-full space-y-4">
<AccordionItem <AccordionItem
value="pricing" value="pricing"
@@ -1,415 +0,0 @@
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { CalendarDays, ChevronLeft, ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { resolveUsageRange } from "@/lib/usageRange";
import { getLocaleFromLanguage } from "./format";
import type { UsageRangeSelection } from "@/types/usage";
type DraftField = "start" | "end";
interface UsageDateRangePickerProps {
selection: UsageRangeSelection;
onApply: (selection: UsageRangeSelection) => void;
triggerLabel: string;
}
/* ── helpers ── */
function startOfDay(d: Date): Date {
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}
function isSameDay(a: Date, b: Date): boolean {
return (
a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate() === b.getDate()
);
}
function toTs(d: Date): number {
return Math.floor(d.getTime() / 1000);
}
function fromTs(ts: number): Date {
return new Date(ts * 1000);
}
function fmtDate(ts: number): string {
const d = fromTs(ts);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}
function fmtTime(ts: number): string {
const d = fromTs(ts);
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
}
function parseDateInput(ts: number, value: string): number {
const [y, m, d] = value.split("-").map(Number);
if (!Number.isFinite(y) || !Number.isFinite(m) || !Number.isFinite(d))
return ts;
const base = fromTs(ts);
return toTs(new Date(y, m - 1, d, base.getHours(), base.getMinutes()));
}
function parseTimeInput(ts: number, value: string): number {
const [h, min] = value.split(":").map(Number);
if (!Number.isFinite(h) || !Number.isFinite(min)) return ts;
const base = fromTs(ts);
return toTs(
new Date(base.getFullYear(), base.getMonth(), base.getDate(), h, min),
);
}
function setDateKeepTime(ts: number, day: Date): number {
const base = fromTs(ts);
return toTs(
new Date(
day.getFullYear(),
day.getMonth(),
day.getDate(),
base.getHours(),
base.getMinutes(),
),
);
}
function getCalendarDays(month: Date): Date[] {
const first = new Date(month.getFullYear(), month.getMonth(), 1);
const gridStart = new Date(first);
gridStart.setDate(first.getDate() - first.getDay());
return Array.from({ length: 42 }, (_, i) => {
const d = new Date(gridStart);
d.setDate(gridStart.getDate() + i);
return d;
});
}
/* ── component ── */
export function UsageDateRangePicker({
selection,
onApply,
triggerLabel,
}: UsageDateRangePickerProps) {
const { t, i18n } = useTranslation();
const [open, setOpen] = useState(false);
const [activeField, setActiveField] = useState<DraftField>("start");
const resolvedRange = useMemo(
() => resolveUsageRange(selection),
[selection],
);
const [draftStart, setDraftStart] = useState(resolvedRange.startDate);
const [draftEnd, setDraftEnd] = useState(resolvedRange.endDate);
const [displayMonth, setDisplayMonth] = useState(
() =>
new Date(
fromTs(resolvedRange.startDate).getFullYear(),
fromTs(resolvedRange.startDate).getMonth(),
1,
),
);
const [error, setError] = useState<string | null>(null);
const language = i18n.resolvedLanguage || i18n.language || "en";
const locale = getLocaleFromLanguage(language);
// Reset draft when popover opens
useEffect(() => {
if (!open) return;
const r = resolveUsageRange(selection);
setDraftStart(r.startDate);
setDraftEnd(r.endDate);
setDisplayMonth(
new Date(
fromTs(r.startDate).getFullYear(),
fromTs(r.startDate).getMonth(),
1,
),
);
setActiveField("start");
setError(null);
}, [open, selection]);
const calendarDays = useMemo(
() => getCalendarDays(displayMonth),
[displayMonth],
);
const weekdayLabels = useMemo(
() =>
Array.from({ length: 7 }, (_, i) =>
new Intl.DateTimeFormat(locale, { weekday: "narrow" }).format(
new Date(2024, 0, 7 + i),
),
),
[locale],
);
const startDay = fromTs(draftStart);
const endDay = fromTs(draftEnd);
const today = new Date();
/* Pick a date from the calendar */
const handleDatePick = (day: Date) => {
setError(null);
const nextTs = setDateKeepTime(
activeField === "start" ? draftStart : draftEnd,
day,
);
if (activeField === "start") {
setDraftStart(nextTs);
// Auto-swap if start > end
if (nextTs > draftEnd) {
setDraftEnd(nextTs);
}
// Auto-advance to end field
setActiveField("end");
} else {
// If picked end < start, treat as new start and auto-advance
if (nextTs < draftStart) {
setDraftStart(nextTs);
setActiveField("end");
} else {
setDraftEnd(nextTs);
}
}
// Navigate calendar if the day is outside the displayed month
if (
day.getMonth() !== displayMonth.getMonth() ||
day.getFullYear() !== displayMonth.getFullYear()
) {
setDisplayMonth(new Date(day.getFullYear(), day.getMonth(), 1));
}
};
const handleApply = () => {
setError(null);
if (draftStart > draftEnd) {
setError(t("usage.invalidTimeRangeOrder", "开始时间不能晚于结束时间"));
return;
}
onApply({
preset: "custom",
customStartDate: draftStart,
customEndDate: draftEnd,
});
setOpen(false);
};
const goToToday = () => {
setDisplayMonth(new Date(today.getFullYear(), today.getMonth(), 1));
};
/* ── Field card (start / end) ── */
const renderField = (field: DraftField) => {
const isActive = activeField === field;
const ts = field === "start" ? draftStart : draftEnd;
const setTs = field === "start" ? setDraftStart : setDraftEnd;
const label =
field === "start"
? t("usage.startTime", "开始时间")
: t("usage.endTime", "结束时间");
return (
<div
className={cn(
"rounded-lg border px-3 py-2 cursor-pointer transition-all",
isActive
? "border-primary ring-1 ring-primary/30 bg-primary/5"
: "border-border/50 hover:border-border",
)}
onClick={() => setActiveField(field)}
>
<div className="mb-1.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
{label}
</div>
<div className="flex items-center gap-1.5">
<Input
type="date"
className="h-7 flex-1 border-0 bg-transparent p-0 text-sm shadow-none focus-visible:ring-0"
value={fmtDate(ts)}
onChange={(e) => {
const next = parseDateInput(ts, e.target.value);
setTs(next);
const d = fromTs(next);
setDisplayMonth(new Date(d.getFullYear(), d.getMonth(), 1));
setError(null);
}}
onFocus={() => setActiveField(field)}
/>
<Input
type="time"
step={60}
className="h-7 w-[90px] flex-none border-0 bg-transparent p-0 text-sm shadow-none focus-visible:ring-0"
value={fmtTime(ts)}
onChange={(e) => {
setTs(parseTimeInput(ts, e.target.value));
setError(null);
}}
onFocus={() => setActiveField(field)}
/>
</div>
</div>
);
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant={selection.preset === "custom" ? "default" : "outline"}
className="justify-start gap-2"
>
<CalendarDays className="h-4 w-4" />
<span className="truncate">{triggerLabel}</span>
</Button>
</PopoverTrigger>
<PopoverContent
className="w-[340px] max-w-[calc(100vw-2rem)] p-3 sm:w-[620px]"
align="end"
>
<div className="flex flex-col gap-3 sm:flex-row">
{/* Left: date fields */}
<div className="space-y-2 sm:w-[250px] sm:flex-none">
<p className="text-xs text-muted-foreground">
{t("usage.customRangeHint", "支持日期与时间,最长 30 天")}
</p>
{renderField("start")}
{renderField("end")}
{error && <p className="text-xs text-destructive">{error}</p>}
<div className="flex gap-2 pt-1">
<Button
type="button"
variant="ghost"
size="sm"
className="flex-1"
onClick={() => setOpen(false)}
>
{t("common.cancel")}
</Button>
<Button
type="button"
size="sm"
className="flex-1"
onClick={handleApply}
>
{t("common.confirm")}
</Button>
</div>
</div>
{/* Right: calendar */}
<div className="rounded-lg border border-border/50 bg-muted/30 p-2.5 sm:min-w-0 sm:flex-1">
{/* Month navigation */}
<div className="flex items-center justify-between mb-1.5">
<Button
type="button"
size="icon"
variant="ghost"
className="h-7 w-7"
onClick={() =>
setDisplayMonth(
new Date(
displayMonth.getFullYear(),
displayMonth.getMonth() - 1,
1,
),
)
}
>
<ChevronLeft className="h-3.5 w-3.5" />
</Button>
<button
type="button"
className="text-sm font-medium hover:text-primary transition-colors"
onClick={goToToday}
title={t("usage.presetToday", { defaultValue: "当天" })}
>
{displayMonth.toLocaleDateString(locale, {
year: "numeric",
month: "long",
})}
</button>
<Button
type="button"
size="icon"
variant="ghost"
className="h-7 w-7"
onClick={() =>
setDisplayMonth(
new Date(
displayMonth.getFullYear(),
displayMonth.getMonth() + 1,
1,
),
)
}
>
<ChevronRight className="h-3.5 w-3.5" />
</Button>
</div>
{/* Weekday headers */}
<div className="grid grid-cols-7 text-center text-[11px] text-muted-foreground mb-0.5">
{weekdayLabels.map((label, i) => (
<div key={i} className="py-0.5">
{label}
</div>
))}
</div>
{/* Day grid */}
<div className="grid grid-cols-7 gap-px">
{calendarDays.map((day) => {
const isCurrentMonth =
day.getMonth() === displayMonth.getMonth();
const isToday = isSameDay(day, today);
const isStart = isSameDay(day, startDay);
const isEnd = isSameDay(day, endDay);
const dayStart = startOfDay(day);
const inRange =
dayStart >= startOfDay(startDay) &&
dayStart <= startOfDay(endDay);
const isEndpoint = isStart || isEnd;
return (
<button
key={day.toISOString()}
type="button"
className={cn(
"relative h-7 rounded text-xs transition-colors",
!isCurrentMonth && "text-muted-foreground/30",
isCurrentMonth && !inRange && "hover:bg-muted",
inRange && !isEndpoint && "bg-primary/10 text-primary",
isEndpoint &&
"bg-primary text-primary-foreground font-medium",
isToday && !isEndpoint && "ring-1 ring-primary/40",
)}
onClick={() => handleDatePick(day)}
>
{day.getDate()}
</button>
);
})}
</div>
</div>
</div>
</PopoverContent>
</Popover>
);
}
+3 -4
View File
@@ -5,22 +5,21 @@ import { useUsageSummary } from "@/lib/query/usage";
import { Activity, DollarSign, Layers, Database, Loader2 } from "lucide-react"; import { Activity, DollarSign, Layers, Database, Loader2 } from "lucide-react";
import { motion } from "framer-motion"; import { motion } from "framer-motion";
import { fmtUsd, parseFiniteNumber } from "./format"; import { fmtUsd, parseFiniteNumber } from "./format";
import type { UsageRangeSelection } from "@/types/usage";
interface UsageSummaryCardsProps { interface UsageSummaryCardsProps {
range: UsageRangeSelection; days: number;
appType?: string; appType?: string;
refreshIntervalMs: number; refreshIntervalMs: number;
} }
export function UsageSummaryCards({ export function UsageSummaryCards({
range, days,
appType, appType,
refreshIntervalMs, refreshIntervalMs,
}: UsageSummaryCardsProps) { }: UsageSummaryCardsProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: summary, isLoading } = useUsageSummary(range, appType, { const { data: summary, isLoading } = useUsageSummary(days, appType, {
refetchInterval: refreshIntervalMs > 0 ? refreshIntervalMs : false, refetchInterval: refreshIntervalMs > 0 ? refreshIntervalMs : false,
}); });
+12 -12
View File
@@ -17,25 +17,20 @@ import {
getLocaleFromLanguage, getLocaleFromLanguage,
parseFiniteNumber, parseFiniteNumber,
} from "./format"; } from "./format";
import { resolveUsageRange } from "@/lib/usageRange";
import type { UsageRangeSelection } from "@/types/usage";
interface UsageTrendChartProps { interface UsageTrendChartProps {
range: UsageRangeSelection; days: number;
rangeLabel: string;
appType?: string; appType?: string;
refreshIntervalMs: number; refreshIntervalMs: number;
} }
export function UsageTrendChart({ export function UsageTrendChart({
range, days,
rangeLabel,
appType, appType,
refreshIntervalMs, refreshIntervalMs,
}: UsageTrendChartProps) { }: UsageTrendChartProps) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const { startDate, endDate } = resolveUsageRange(range); const { data: trends, isLoading } = useUsageTrends(days, appType, {
const { data: trends, isLoading } = useUsageTrends(range, appType, {
refetchInterval: refreshIntervalMs > 0 ? refreshIntervalMs : false, refetchInterval: refreshIntervalMs > 0 ? refreshIntervalMs : false,
}); });
@@ -47,8 +42,7 @@ export function UsageTrendChart({
); );
} }
const durationSeconds = Math.max(endDate - startDate, 0); const isToday = days === 1;
const isHourly = durationSeconds <= 24 * 60 * 60;
const language = i18n.resolvedLanguage || i18n.language || "en"; const language = i18n.resolvedLanguage || i18n.language || "en";
const dateLocale = getLocaleFromLanguage(language); const dateLocale = getLocaleFromLanguage(language);
const chartData = const chartData =
@@ -57,7 +51,7 @@ export function UsageTrendChart({
const cost = parseFiniteNumber(stat.totalCost); const cost = parseFiniteNumber(stat.totalCost);
return { return {
rawDate: stat.date, rawDate: stat.date,
label: isHourly label: isToday
? pointDate.toLocaleString(dateLocale, { ? pointDate.toLocaleString(dateLocale, {
month: "2-digit", month: "2-digit",
day: "2-digit", day: "2-digit",
@@ -114,7 +108,13 @@ export function UsageTrendChart({
<h3 className="text-lg font-semibold"> <h3 className="text-lg font-semibold">
{t("usage.trends", "使用趋势")} {t("usage.trends", "使用趋势")}
</h3> </h3>
<p className="text-sm text-muted-foreground">{rangeLabel}</p> <p className="text-sm text-muted-foreground">
{isToday
? t("usage.rangeToday", "今天 (按小时)")
: days === 7
? t("usage.rangeLast7Days", "过去 7 天")
: t("usage.rangeLast30Days", "过去 30 天")}
</p>
</div> </div>
<div className="h-[350px] w-full"> <div className="h-[350px] w-full">
+18 -1
View File
@@ -636,6 +636,23 @@ export const providerPresets: ProviderPreset[] = [
icon: "micu", icon: "micu",
iconColor: "#000000", iconColor: "#000000",
}, },
{
name: "X-Code API",
websiteUrl: "https://x-code.cc",
apiKeyUrl: "https://x-code.cc",
settingsConfig: {
env: {
ANTHROPIC_BASE_URL: "https://x-code.cc",
ANTHROPIC_AUTH_TOKEN: "",
},
},
endpointCandidates: ["https://x-code.cc"],
category: "third_party",
isPartner: true, // 合作伙伴
partnerPromotionKey: "x-code", // 促销信息 i18n key
icon: "xcode",
iconColor: "#000000",
},
{ {
name: "CTok.ai", name: "CTok.ai",
websiteUrl: "https://ctok.ai", websiteUrl: "https://ctok.ai",
@@ -820,7 +837,7 @@ export const providerPresets: ProviderPreset[] = [
}, },
{ {
name: "PIPELLM", name: "PIPELLM",
websiteUrl: "https://code.pipellm.ai", websiteUrl: "https://www.pipellm.ai",
apiKeyUrl: "https://code.pipellm.ai/login?ref=uvw650za", apiKeyUrl: "https://code.pipellm.ai/login?ref=uvw650za",
settingsConfig: { settingsConfig: {
env: { env: {
+18 -1
View File
@@ -333,6 +333,23 @@ requires_openai_auth = true`,
icon: "micu", icon: "micu",
iconColor: "#000000", iconColor: "#000000",
}, },
{
name: "X-Code API",
websiteUrl: "https://x-code.cc",
apiKeyUrl: "https://x-code.cc",
auth: generateThirdPartyAuth(""),
config: generateThirdPartyConfig(
"x-code",
"https://x-code.cc/v1",
"gpt-5.4",
),
endpointCandidates: ["https://x-code.cc/v1"],
category: "third_party",
isPartner: true, // 合作伙伴
partnerPromotionKey: "x-code", // 促销信息 i18n key
icon: "xcode",
iconColor: "#000000",
},
{ {
name: "CTok.ai", name: "CTok.ai",
websiteUrl: "https://ctok.ai", websiteUrl: "https://ctok.ai",
@@ -391,7 +408,7 @@ model_auto_compact_token_limit = 9000000`,
}, },
{ {
name: "PIPELLM", name: "PIPELLM",
websiteUrl: "https://code.pipellm.ai", websiteUrl: "https://www.pipellm.ai",
apiKeyUrl: "https://code.pipellm.ai/login?ref=uvw650za", apiKeyUrl: "https://code.pipellm.ai/login?ref=uvw650za",
auth: { auth: {
OPENAI_API_KEY: "", OPENAI_API_KEY: "",
+1 -1
View File
@@ -1009,7 +1009,7 @@ export const openclawProviderPresets: OpenClawProviderPreset[] = [
}, },
{ {
name: "PIPELLM", name: "PIPELLM",
websiteUrl: "https://code.pipellm.ai", websiteUrl: "https://www.pipellm.ai",
apiKeyUrl: "https://code.pipellm.ai/login?ref=uvw650za", apiKeyUrl: "https://code.pipellm.ai/login?ref=uvw650za",
settingsConfig: { settingsConfig: {
baseUrl: "https://cc-api.pipellm.ai", baseUrl: "https://cc-api.pipellm.ai",
+31 -1
View File
@@ -996,7 +996,7 @@ export const opencodeProviderPresets: OpenCodeProviderPreset[] = [
}, },
{ {
name: "PIPELLM", name: "PIPELLM",
websiteUrl: "https://code.pipellm.ai", websiteUrl: "https://www.pipellm.ai",
apiKeyUrl: "https://code.pipellm.ai/login?ref=uvw650za", apiKeyUrl: "https://code.pipellm.ai/login?ref=uvw650za",
settingsConfig: { settingsConfig: {
npm: "@ai-sdk/anthropic", npm: "@ai-sdk/anthropic",
@@ -1291,6 +1291,36 @@ export const opencodeProviderPresets: OpenCodeProviderPreset[] = [
}, },
}, },
}, },
{
name: "X-Code API",
websiteUrl: "https://x-code.cc",
apiKeyUrl: "https://x-code.cc",
settingsConfig: {
npm: "@ai-sdk/anthropic",
name: "X-Code API",
options: {
baseURL: "https://x-code.cc/v1",
apiKey: "",
setCacheKey: true,
},
models: {
"claude-opus-4-6": { name: "Claude Opus 4.6" },
"claude-sonnet-4-6": { name: "Claude Sonnet 4.6" },
},
},
category: "third_party",
isPartner: true,
partnerPromotionKey: "x-code",
icon: "xcode",
iconColor: "#000000",
templateValues: {
apiKey: {
label: "API Key",
placeholder: "",
editorValue: "",
},
},
},
{ {
name: "CTok.ai", name: "CTok.ai",
websiteUrl: "https://ctok.ai", websiteUrl: "https://ctok.ai",
+2 -25
View File
@@ -23,11 +23,7 @@ import { openclawKeys } from "@/hooks/useOpenClaw";
* Hook for managing provider actions (add, update, delete, switch) * Hook for managing provider actions (add, update, delete, switch)
* Extracts business logic from App.tsx * Extracts business logic from App.tsx
*/ */
export function useProviderActions( export function useProviderActions(activeApp: AppId, isProxyRunning?: boolean) {
activeApp: AppId,
isProxyRunning?: boolean,
isProxyTakeover?: boolean,
) {
const { t } = useTranslation(); const { t } = useTranslation();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@@ -189,18 +185,6 @@ export function useProviderActions(
); );
} }
// Block official providers when proxy takeover is active
if (isProxyTakeover && provider.category === "official") {
toast.error(
t("notifications.officialBlockedByProxy", {
defaultValue:
"代理接管模式下不能切换到官方供应商,使用代理访问官方 API 可能导致账号被封禁",
}),
{ duration: 6000 },
);
return;
}
try { try {
const result = await switchProviderMutation.mutateAsync(provider.id); const result = await switchProviderMutation.mutateAsync(provider.id);
await syncClaudePlugin(provider); await syncClaudePlugin(provider);
@@ -236,14 +220,7 @@ export function useProviderActions(
// 错误提示由 mutation 处理 // 错误提示由 mutation 处理
} }
}, },
[ [switchProviderMutation, syncClaudePlugin, activeApp, isProxyRunning, t],
switchProviderMutation,
syncClaudePlugin,
activeApp,
isProxyRunning,
isProxyTakeover,
t,
],
); );
// 删除供应商 // 删除供应商
-3
View File
@@ -81,7 +81,6 @@ export function useSettingsForm(): UseSettingsFormResult {
...data, ...data,
showInTray: data.showInTray ?? true, showInTray: data.showInTray ?? true,
minimizeToTrayOnClose: data.minimizeToTrayOnClose ?? true, minimizeToTrayOnClose: data.minimizeToTrayOnClose ?? true,
useAppWindowControls: data.useAppWindowControls ?? false,
enableClaudePluginIntegration: enableClaudePluginIntegration:
data.enableClaudePluginIntegration ?? false, data.enableClaudePluginIntegration ?? false,
silentStartup: data.silentStartup ?? false, silentStartup: data.silentStartup ?? false,
@@ -106,7 +105,6 @@ export function useSettingsForm(): UseSettingsFormResult {
({ ({
showInTray: true, showInTray: true,
minimizeToTrayOnClose: true, minimizeToTrayOnClose: true,
useAppWindowControls: false,
enableClaudePluginIntegration: false, enableClaudePluginIntegration: false,
skipClaudeOnboarding: false, skipClaudeOnboarding: false,
language: readPersistedLanguage(), language: readPersistedLanguage(),
@@ -141,7 +139,6 @@ export function useSettingsForm(): UseSettingsFormResult {
...serverData, ...serverData,
showInTray: serverData.showInTray ?? true, showInTray: serverData.showInTray ?? true,
minimizeToTrayOnClose: serverData.minimizeToTrayOnClose ?? true, minimizeToTrayOnClose: serverData.minimizeToTrayOnClose ?? true,
useAppWindowControls: serverData.useAppWindowControls ?? false,
enableClaudePluginIntegration: enableClaudePluginIntegration:
serverData.enableClaudePluginIntegration ?? false, serverData.enableClaudePluginIntegration ?? false,
silentStartup: serverData.silentStartup ?? false, silentStartup: serverData.silentStartup ?? false,
-24
View File
@@ -46,28 +46,6 @@ export function useStreamCheck(appId: AppId) {
// 降级状态也重置熔断器,因为至少能通信 // 降级状态也重置熔断器,因为至少能通信
resetCircuitBreaker.mutate({ providerId, appType: appId }); resetCircuitBreaker.mutate({ providerId, appType: appId });
} else {
const httpStatus = result.httpStatus;
const hintKey = httpStatus
? `streamCheck.httpHint.${httpStatus >= 500 ? "5xx" : httpStatus}`
: null;
const description =
(hintKey ? t(hintKey, { defaultValue: "" }) : "") || undefined;
// 401/403/400 = 检查被拒(供应商可能正常);429/5xx = 临时问题
const isProbeRejection =
httpStatus != null &&
([401, 403, 400, 429].includes(httpStatus) || httpStatus >= 500);
if (isProbeRejection) {
toast.warning(
t("streamCheck.rejected", {
providerName: providerName,
message: result.message,
defaultValue: `${providerName} 检查被拒: ${result.message}`,
}),
{ description, duration: 8000, closeButton: true },
);
} else { } else {
toast.error( toast.error(
t("streamCheck.failed", { t("streamCheck.failed", {
@@ -75,10 +53,8 @@ export function useStreamCheck(appId: AppId) {
message: result.message, message: result.message,
defaultValue: `${providerName} 检查失败: ${result.message}`, defaultValue: `${providerName} 检查失败: ${result.message}`,
}), }),
{ description, duration: 8000, closeButton: true },
); );
} }
}
return result; return result;
} catch (e) { } catch (e) {
+50 -79
View File
@@ -91,11 +91,7 @@
"switchToChinese": "Switch to Chinese", "switchToChinese": "Switch to Chinese",
"switchToEnglish": "Switch to English", "switchToEnglish": "Switch to English",
"enterEditMode": "Enter Edit Mode", "enterEditMode": "Enter Edit Mode",
"exitEditMode": "Exit Edit Mode", "exitEditMode": "Exit Edit Mode"
"windowMinimize": "Minimize window",
"windowMaximize": "Maximize window",
"windowRestore": "Restore window",
"windowClose": "Close window"
}, },
"provider": { "provider": {
"tabProvider": "Provider", "tabProvider": "Provider",
@@ -108,7 +104,6 @@
"currentlyUsing": "Currently Using", "currentlyUsing": "Currently Using",
"enable": "Enable", "enable": "Enable",
"inUse": "In Use", "inUse": "In Use",
"blockedByProxy": "Blocked",
"editProvider": "Edit Provider", "editProvider": "Edit Provider",
"editProviderHint": "Configuration will be applied to the current provider immediately after update.", "editProviderHint": "Configuration will be applied to the current provider immediately after update.",
"deleteProvider": "Delete Provider", "deleteProvider": "Delete Provider",
@@ -194,22 +189,19 @@
"deleteFailed": "Failed to delete provider: {{error}}", "deleteFailed": "Failed to delete provider: {{error}}",
"settingsSaved": "Settings saved", "settingsSaved": "Settings saved",
"settingsSaveFailed": "Failed to save settings: {{error}}", "settingsSaveFailed": "Failed to save settings: {{error}}",
"proxyRequiredForSwitch": "This provider {{reason}}, requires the routing service to work properly. Start routing first.", "proxyRequiredForSwitch": "This provider {{reason}}, requires the proxy service to work properly. Start the proxy first.",
"proxyReasonCopilot": "uses GitHub Copilot as a Claude provider", "proxyReasonCopilot": "uses GitHub Copilot as a Claude provider",
"proxyReasonOpenAIChat": "uses OpenAI Chat API format", "proxyReasonOpenAIChat": "uses OpenAI Chat API format",
"proxyReasonOpenAIResponses": "uses OpenAI Responses API format", "proxyReasonOpenAIResponses": "uses OpenAI Responses API format",
"proxyReasonFullUrl": "has full URL connection mode enabled", "proxyReasonFullUrl": "has full URL connection mode enabled",
"openAIFormatHint": "This provider uses OpenAI-compatible format and requires the routing service to be enabled", "openAIFormatHint": "This provider uses OpenAI-compatible format and requires the proxy service to be enabled",
"copilotProxyHint": "GitHub Copilot as a Claude provider always requires local routing; routing automatically selects Chat Completions or Responses based on the current model.", "copilotProxyHint": "GitHub Copilot as a Claude provider always requires the local proxy; the proxy automatically selects Chat Completions or Responses based on the current model.",
"openLinkFailed": "Failed to open link", "openLinkFailed": "Failed to open link",
"openclawModelsRegistered": "Models have been registered to /model list", "openclawModelsRegistered": "Models have been registered to /model list",
"openclawDefaultModelSet": "Set as default model", "openclawDefaultModelSet": "Set as default model",
"openclawDefaultModelSetFailed": "Failed to set default model", "openclawDefaultModelSetFailed": "Failed to set default model",
"openclawNoModels": "No models configured", "openclawNoModels": "No models configured",
"backfillWarning": "Switched successfully, but failed to save changes back to the previous provider", "backfillWarning": "Switched successfully, but failed to save changes back to the previous provider"
"windowControlFailed": "Window control failed: {{error}}",
"officialBlockedByProxy": "Cannot switch to official provider while local routing is active. Using routing with official APIs may cause account bans.",
"proxyOfficialWarning": "Current provider {{name}} is official. Consider switching to a third-party provider before using local routing."
}, },
"confirm": { "confirm": {
"deleteProvider": "Delete Provider", "deleteProvider": "Delete Provider",
@@ -217,8 +209,8 @@
"removeProvider": "Remove Provider", "removeProvider": "Remove Provider",
"removeProviderMessage": "Are you sure you want to remove provider \"{{name}}\" from the configuration?\n\nAfter removal, this provider will no longer be active, but the configuration data will be retained in CC Switch. You can re-add it at any time.", "removeProviderMessage": "Are you sure you want to remove provider \"{{name}}\" from the configuration?\n\nAfter removal, this provider will no longer be active, but the configuration data will be retained in CC Switch. You can re-add it at any time.",
"proxy": { "proxy": {
"title": "Enable Local Routing", "title": "Enable Local Proxy",
"message": "Local routing is an advanced feature. Please make sure you understand how it works before enabling.\n\nWe recommend consulting the relevant documentation or your provider for proper configuration.", "message": "Local proxy is an advanced feature. Please make sure you understand how it works before enabling.\n\nWe recommend consulting the relevant documentation or your provider for proper configuration.",
"confirm": "I understand, enable" "confirm": "I understand, enable"
}, },
"failover": { "failover": {
@@ -253,7 +245,7 @@
"tabGeneral": "General", "tabGeneral": "General",
"tabAuth": "Auth", "tabAuth": "Auth",
"tabAdvanced": "Advanced", "tabAdvanced": "Advanced",
"tabProxy": "Routing", "tabProxy": "Proxy",
"authCenter": { "authCenter": {
"title": "OAuth Authentication Center", "title": "OAuth Authentication Center",
"description": "Use your other subscriptions in Claude Code — please be mindful of compliance risks.", "description": "Use your other subscriptions in Claude Code — please be mindful of compliance risks.",
@@ -267,10 +259,10 @@
"description": "Manage storage paths for Claude, Codex and Gemini configurations" "description": "Manage storage paths for Claude, Codex and Gemini configurations"
}, },
"proxy": { "proxy": {
"title": "Local Routing", "title": "Local Proxy",
"description": "Control routing service toggle, view status and port info", "description": "Control proxy service toggle, view status and port info",
"enableFeature": "Show Routing Toggle on Main Page", "enableFeature": "Show Proxy Toggle on Main Page",
"enableFeatureDescription": "When enabled, the routing and failover toggles will appear at the top of the main page", "enableFeatureDescription": "When enabled, the proxy and failover toggles will appear at the top of the main page",
"enableFailoverToggle": "Show Failover Toggle on Main Page", "enableFailoverToggle": "Show Failover Toggle on Main Page",
"enableFailoverToggleDescription": "When enabled, the failover toggle will appear independently at the top of the main page", "enableFailoverToggleDescription": "When enabled, the failover toggle will appear independently at the top of the main page",
"running": "Running", "running": "Running",
@@ -502,8 +494,6 @@
"autoLaunchFailed": "Failed to set auto-launch", "autoLaunchFailed": "Failed to set auto-launch",
"minimizeToTray": "Minimize to tray on close", "minimizeToTray": "Minimize to tray on close",
"minimizeToTrayDescription": "When checked, clicking the close button will hide to system tray, otherwise the app will exit directly.", "minimizeToTrayDescription": "When checked, clicking the close button will hide to system tray, otherwise the app will exit directly.",
"useAppWindowControls": "Enable app-level window controls",
"useAppWindowControlsDescription": "Use built-in minimize, maximize/restore, and close buttons in the app header.",
"enableClaudePluginIntegration": "Apply to Claude Code extension", "enableClaudePluginIntegration": "Apply to Claude Code extension",
"enableClaudePluginIntegrationDescription": "When enabled, the VS Code Claude Code extension provider will switch with this app", "enableClaudePluginIntegrationDescription": "When enabled, the VS Code Claude Code extension provider will switch with this app",
"skipClaudeOnboarding": "Skip Claude Code first-run confirmation", "skipClaudeOnboarding": "Skip Claude Code first-run confirmation",
@@ -622,7 +612,7 @@
"saving": "Saving...", "saving": "Saving...",
"globalProxy": { "globalProxy": {
"label": "Global Proxy", "label": "Global Proxy",
"hint": "Proxy all requests (API, Skills download, etc.). When local routing is enabled, app traffic is also routed through this proxy. Leave empty for direct connection.", "hint": "Proxy all requests (API, Skills download, etc.). Leave empty for direct connection.",
"username": "Username (optional)", "username": "Username (optional)",
"password": "Password (optional)", "password": "Password (optional)",
"test": "Test Connection", "test": "Test Connection",
@@ -725,9 +715,7 @@
"copyCommand": "Copy Command", "copyCommand": "Copy Command",
"copyMessage": "Copy Message", "copyMessage": "Copy Message",
"messageCopied": "Message copied", "messageCopied": "Message copied",
"conversationHistory": "Conversation History", "conversationHistory": "Conversation History"
"expandContent": "Expand full content",
"collapseContent": "Collapse"
}, },
"console": { "console": {
"providerSwitchReceived": "Received provider switch event:", "providerSwitchReceived": "Received provider switch event:",
@@ -785,6 +773,7 @@
"siliconflow": "SiliconFlow is an official partner of CC Switch", "siliconflow": "SiliconFlow is an official partner of CC Switch",
"ucloud": "Compshare offers an exclusive bonus for CC Switch users — register via this link to get ¥5 platform trial credit!", "ucloud": "Compshare offers an exclusive bonus for CC Switch users — register via this link to get ¥5 platform trial credit!",
"micu": "Micu is an official partner of CC Switch", "micu": "Micu is an official partner of CC Switch",
"x-code": "XCodeAPI offers a special bonus for CC Switch users — register via this link and get 10% extra credit on your first order (contact admin to claim)",
"ctok": "Join the CTok community on the official website and subscribe to a plan.", "ctok": "Join the CTok community on the official website and subscribe to a plan.",
"ddshub": "DDSHub offers a special bonus for CC Switch users — register via this link and get 10% extra credit on your first top-up (contact group admin to claim)!", "ddshub": "DDSHub offers a special bonus for CC Switch users — register via this link and get 10% extra credit on your first top-up (contact group admin to claim)!",
"lionccapi": "LionCCAPI offers exclusive benefits for CC Switch users. After registration, add WeChat HSQBJ088888888 and mention 'cc-switch' to receive $10 free credits!", "lionccapi": "LionCCAPI offers exclusive benefits for CC Switch users. After registration, add WeChat HSQBJ088888888 and mention 'cc-switch' to receive $10 free credits!",
@@ -822,10 +811,10 @@
"fullUrlLabel": "Full URL", "fullUrlLabel": "Full URL",
"fullUrlEnabled": "Full URL Mode", "fullUrlEnabled": "Full URL Mode",
"fullUrlDisabled": "Mark as Full URL", "fullUrlDisabled": "Mark as Full URL",
"fullUrlHint": "💡 Enter the full request URL. This mode requires routing to be enabled, and routing will use the URL as-is without appending a path", "fullUrlHint": "💡 Enter the full request URL. This mode requires the proxy to be enabled, and the proxy will use the URL as-is without appending a path",
"apiFormatAnthropic": "Anthropic Messages (Native)", "apiFormatAnthropic": "Anthropic Messages (Native)",
"apiFormatOpenAIChat": "OpenAI Chat Completions (Requires routing)", "apiFormatOpenAIChat": "OpenAI Chat Completions (Requires proxy)",
"apiFormatOpenAIResponses": "OpenAI Responses API (Requires routing)", "apiFormatOpenAIResponses": "OpenAI Responses API (Requires proxy)",
"authField": "Auth Field", "authField": "Auth Field",
"authFieldAuthToken": "ANTHROPIC_AUTH_TOKEN (Default)", "authFieldAuthToken": "ANTHROPIC_AUTH_TOKEN (Default)",
"authFieldApiKey": "ANTHROPIC_API_KEY", "authFieldApiKey": "ANTHROPIC_API_KEY",
@@ -945,6 +934,11 @@
"testPrompt": "Test Prompt", "testPrompt": "Test Prompt",
"degradedThreshold": "Degraded Threshold (ms)", "degradedThreshold": "Degraded Threshold (ms)",
"maxRetries": "Max Retries", "maxRetries": "Max Retries",
"proxyConfig": "Proxy Config",
"useCustomProxy": "Use separate proxy",
"proxyConfigDesc": "Configure separate network proxy for this provider. Uses system proxy or global settings when disabled.",
"proxyUsername": "Username (optional)",
"proxyPassword": "Password (optional)",
"pricingConfig": "Pricing Config", "pricingConfig": "Pricing Config",
"useCustomPricing": "Use separate config", "useCustomPricing": "Use separate config",
"pricingConfigDesc": "Configure separate pricing parameters for this provider. Uses global defaults when disabled.", "pricingConfigDesc": "Configure separate pricing parameters for this provider. Uses global defaults when disabled.",
@@ -1048,11 +1042,6 @@
"today": "24 Hours", "today": "24 Hours",
"last7days": "7 Days", "last7days": "7 Days",
"last30days": "30 Days", "last30days": "30 Days",
"presetToday": "Today",
"preset1d": "1d",
"preset7d": "7d",
"preset14d": "14d",
"preset30d": "30d",
"totalRequests": "Total Requests", "totalRequests": "Total Requests",
"totalCost": "Total Cost", "totalCost": "Total Cost",
"cost": "Cost", "cost": "Cost",
@@ -1073,8 +1062,6 @@
"outputTokens": "Output", "outputTokens": "Output",
"cacheReadTokens": "Cache Hit", "cacheReadTokens": "Cache Hit",
"cacheCreationTokens": "Cache Creation", "cacheCreationTokens": "Cache Creation",
"cacheReadShort": "Cache Read",
"cacheWriteShort": "Write",
"timingInfo": "Duration/TTFT", "timingInfo": "Duration/TTFT",
"status": "Status", "status": "Status",
"multiplier": "Multiplier", "multiplier": "Multiplier",
@@ -1095,7 +1082,7 @@
}, },
"dataSources": "Data Sources", "dataSources": "Data Sources",
"dataSource": { "dataSource": {
"proxy": "Routing", "proxy": "Proxy",
"session_log": "Session Log", "session_log": "Session Log",
"codex_db": "Codex DB", "codex_db": "Codex DB",
"codex_session": "Codex Session", "codex_session": "Codex Session",
@@ -1110,8 +1097,6 @@
"failed": "Session sync failed" "failed": "Session sync failed"
}, },
"totalRecords": "{{total}} records total", "totalRecords": "{{total}} records total",
"goToPage": "Go",
"pageInputPlaceholder": "Page",
"modelPricing": "Model Pricing", "modelPricing": "Model Pricing",
"loadPricingError": "Failed to load pricing data", "loadPricingError": "Failed to load pricing data",
"modelPricingDesc": "Configure token costs for each model", "modelPricingDesc": "Configure token costs for each model",
@@ -1146,10 +1131,6 @@
"searchProviderPlaceholder": "Search provider...", "searchProviderPlaceholder": "Search provider...",
"searchModelPlaceholder": "Search model...", "searchModelPlaceholder": "Search model...",
"timeRange": "Time Range", "timeRange": "Time Range",
"customRange": "Calendar Filter",
"customRangeHint": "Supports both date and time, up to 30 days",
"startTime": "Start Time",
"endTime": "End Time",
"input": "Input", "input": "Input",
"output": "Output", "output": "Output",
"cacheWrite": "Creation", "cacheWrite": "Creation",
@@ -1951,9 +1932,9 @@
"addressCopied": "Address copied", "addressCopied": "Address copied",
"currentProvider": "Current Provider:", "currentProvider": "Current Provider:",
"waitingFirstRequest": "Current Provider: Waiting for first request...", "waitingFirstRequest": "Current Provider: Waiting for first request...",
"stoppedTitle": "Routing Service Stopped", "stoppedTitle": "Proxy Service Stopped",
"stoppedDescription": "Use the toggle above to start the service", "stoppedDescription": "Use the toggle above to start the service",
"openSettings": "Configure Routing Service", "openSettings": "Configure Proxy Service",
"stats": { "stats": {
"activeConnections": "Active Connections", "activeConnections": "Active Connections",
"totalRequests": "Total Requests", "totalRequests": "Total Requests",
@@ -1962,14 +1943,14 @@
} }
}, },
"settings": { "settings": {
"title": "Routing Service Settings", "title": "Proxy Service Settings",
"description": "Configure local routing server listening address, port and runtime parameters. Changes take effect immediately after saving.", "description": "Configure local proxy server listening address, port and runtime parameters. Changes take effect immediately after saving.",
"alert": { "alert": {
"autoApply": "Changes will be automatically synced to the running routing service without manual restart." "autoApply": "Changes will be automatically synced to the running proxy service without manual restart."
}, },
"basic": { "basic": {
"title": "Basic Settings", "title": "Basic Settings",
"description": "Configure routing service listening address and port." "description": "Configure proxy service listening address and port."
}, },
"advanced": { "advanced": {
"title": "Advanced Parameters", "title": "Advanced Parameters",
@@ -1983,12 +1964,12 @@
"listenAddress": { "listenAddress": {
"label": "Listen Address", "label": "Listen Address",
"placeholder": "127.0.0.1", "placeholder": "127.0.0.1",
"description": "IP address the routing server listens on (recommended: 127.0.0.1)" "description": "IP address the proxy server listens on (recommended: 127.0.0.1)"
}, },
"listenPort": { "listenPort": {
"label": "Listen Port", "label": "Listen Port",
"placeholder": "15721", "placeholder": "15721",
"description": "Port number the routing server listens on (1024 ~ 65535)" "description": "Port number the proxy server listens on (1024 ~ 65535)"
}, },
"maxRetries": { "maxRetries": {
"label": "Max Retries", "label": "Max Retries",
@@ -2002,7 +1983,7 @@
}, },
"enableLogging": { "enableLogging": {
"label": "Enable Logging", "label": "Enable Logging",
"description": "Log all routing requests for troubleshooting" "description": "Log all proxy requests for troubleshooting"
}, },
"streamingFirstByteTimeout": { "streamingFirstByteTimeout": {
"label": "Streaming First Byte Timeout (sec)", "label": "Streaming First Byte Timeout (sec)",
@@ -2033,29 +2014,29 @@
"save": "Save Configuration" "save": "Save Configuration"
}, },
"toast": { "toast": {
"saved": "Routing configuration saved", "saved": "Proxy configuration saved",
"saveFailed": "Save failed: {{error}}" "saveFailed": "Save failed: {{error}}"
}, },
"invalidPort": "Invalid port, please enter a number between 1024-65535", "invalidPort": "Invalid port, please enter a number between 1024-65535",
"invalidAddress": "Invalid address, please enter a valid IP address (e.g. 127.0.0.1) or localhost", "invalidAddress": "Invalid address, please enter a valid IP address (e.g. 127.0.0.1) or localhost",
"configSaved": "Routing configuration saved", "configSaved": "Proxy configuration saved",
"configSaveFailed": "Failed to save configuration", "configSaveFailed": "Failed to save configuration",
"restartRequired": "Restart routing service for address or port changes to take effect" "restartRequired": "Restart proxy service for address or port changes to take effect"
}, },
"switchFailed": "Switch failed: {{error}}", "switchFailed": "Switch failed: {{error}}",
"takeover": { "takeover": {
"hint": "Select apps to route — once enabled, requests from that app will go through local routing", "hint": "Select apps to take over — once enabled, requests from that app will be routed through the local proxy",
"enabled": "{{app}} routing enabled", "enabled": "{{app}} takeover enabled",
"disabled": "{{app}} routing disabled", "disabled": "{{app}} takeover disabled",
"failed": "Failed to toggle routing", "failed": "Failed to toggle takeover",
"tooltip": { "tooltip": {
"active": "{{appLabel}} is routing - {{address}}:{{port}}\nSwitch provider for hot switching", "active": "{{appLabel}} is intercepting - {{address}}:{{port}}\nSwitch provider for hot switching",
"broken": "{{appLabel}} is routing, but routing service is not running", "broken": "{{appLabel}} is intercepting, but proxy service is not running",
"inactive": "Route {{appLabel}}'s requests through local routing" "inactive": "Intercept {{appLabel}}'s live config to route requests through local proxy"
} }
}, },
"failover": { "failover": {
"proxyRequired": "Routing service must be started to configure failover", "proxyRequired": "Proxy service must be started to configure failover",
"autoSwitch": "Auto Failover", "autoSwitch": "Auto Failover",
"autoSwitchDescription": "When enabled, switches to queue P1 immediately and automatically tries the next provider in the queue on failures" "autoSwitchDescription": "When enabled, switches to queue P1 immediately and automatically tries the next provider in the queue on failures"
}, },
@@ -2119,10 +2100,10 @@
"failed": "Failed to toggle logging" "failed": "Failed to toggle logging"
}, },
"server": { "server": {
"started": "Routing service started - {{address}}:{{port}}", "started": "Proxy service started - {{address}}:{{port}}",
"startFailed": "Failed to start routing service: {{detail}}" "startFailed": "Failed to start proxy service: {{detail}}"
}, },
"stoppedWithRestore": "Routing service stopped, all routing configs restored", "stoppedWithRestore": "Proxy service stopped, all takeover configs restored",
"stopWithRestoreFailed": "Stop failed: {{detail}}" "stopWithRestoreFailed": "Stop failed: {{detail}}"
}, },
"streamCheck": { "streamCheck": {
@@ -2140,21 +2121,11 @@
"operational": "{{providerName}} is operational ({{responseTimeMs}}ms)", "operational": "{{providerName}} is operational ({{responseTimeMs}}ms)",
"degraded": "{{providerName}} is slow ({{responseTimeMs}}ms)", "degraded": "{{providerName}} is slow ({{responseTimeMs}}ms)",
"failed": "{{providerName}} check failed: {{message}}", "failed": "{{providerName}} check failed: {{message}}",
"rejected": "{{providerName}} check rejected: {{message}}", "error": "{{providerName}} check error: {{error}}"
"error": "{{providerName}} check error: {{error}}",
"httpHint": {
"400": "Provider rejected request format. Health check probe may differ from actual usage.",
"401": "API key may be invalid, or provider uses OAuth auth. Check failure doesn't mean it's unusable.",
"402": "Account quota or billing issue.",
"403": "Provider blocked this request. Some verify client identity; may work fine in actual use.",
"404": "Endpoint not found. Check base URL and API path.",
"429": "Too many requests. Try again later.",
"5xx": "Provider internal error. Likely temporary."
}
}, },
"proxyConfig": { "proxyConfig": {
"proxyEnabled": "Routing Master Switch", "proxyEnabled": "Proxy Enabled",
"appTakeover": "Routing Enabled", "appTakeover": "Proxy Enabled",
"perAppConfig": "Per-App Config", "perAppConfig": "Per-App Config",
"circuitBreaker": "Circuit Breaker", "circuitBreaker": "Circuit Breaker",
"circuitBreakerSettings": "Circuit Breaker Settings", "circuitBreakerSettings": "Circuit Breaker Settings",
+51 -80
View File
@@ -91,11 +91,7 @@
"switchToChinese": "中国語に切り替え", "switchToChinese": "中国語に切り替え",
"switchToEnglish": "英語に切り替え", "switchToEnglish": "英語に切り替え",
"enterEditMode": "編集モードに入る", "enterEditMode": "編集モードに入る",
"exitEditMode": "編集モードを終了", "exitEditMode": "編集モードを終了"
"windowMinimize": "ウィンドウを最小化",
"windowMaximize": "ウィンドウを最大化",
"windowRestore": "ウィンドウを元に戻す",
"windowClose": "ウィンドウを閉じる"
}, },
"provider": { "provider": {
"tabProvider": "プロバイダー", "tabProvider": "プロバイダー",
@@ -108,7 +104,6 @@
"currentlyUsing": "現在使用中", "currentlyUsing": "現在使用中",
"enable": "有効化", "enable": "有効化",
"inUse": "使用中", "inUse": "使用中",
"blockedByProxy": "ブロック",
"editProvider": "プロバイダーを編集", "editProvider": "プロバイダーを編集",
"editProviderHint": "保存すると現在のプロバイダーにすぐ反映されます。", "editProviderHint": "保存すると現在のプロバイダーにすぐ反映されます。",
"deleteProvider": "プロバイダーを削除", "deleteProvider": "プロバイダーを削除",
@@ -194,22 +189,19 @@
"deleteFailed": "プロバイダーの削除に失敗しました: {{error}}", "deleteFailed": "プロバイダーの削除に失敗しました: {{error}}",
"settingsSaved": "設定を保存しました", "settingsSaved": "設定を保存しました",
"settingsSaveFailed": "設定の保存に失敗しました: {{error}}", "settingsSaveFailed": "設定の保存に失敗しました: {{error}}",
"proxyRequiredForSwitch": "このプロバイダーは{{reason}}、ルーティングサービスが必要です。先にルーティングを起動してください", "proxyRequiredForSwitch": "このプロバイダーは{{reason}}、プロキシサービスが必要です。先にプロキシを起動してください",
"proxyReasonCopilot": "GitHub Copilot を Claude プロバイダーとして使用しており", "proxyReasonCopilot": "GitHub Copilot を Claude プロバイダーとして使用しており",
"proxyReasonOpenAIChat": "OpenAI Chat API フォーマットを使用しており", "proxyReasonOpenAIChat": "OpenAI Chat API フォーマットを使用しており",
"proxyReasonOpenAIResponses": "OpenAI Responses API フォーマットを使用しており", "proxyReasonOpenAIResponses": "OpenAI Responses API フォーマットを使用しており",
"proxyReasonFullUrl": "完全 URL 接続モードが有効になっており", "proxyReasonFullUrl": "完全 URL 接続モードが有効になっており",
"openAIFormatHint": "このプロバイダーは OpenAI 互換フォーマットを使用しており、ルーティングサービスの有効化が必要です", "openAIFormatHint": "このプロバイダーは OpenAI 互換フォーマットを使用しており、プロキシサービスの有効化が必要です",
"copilotProxyHint": "GitHub Copilot を Claude プロバイダーとして使用する場合、ローカルルーティングが常に必要です。ルーティングは現在のモデルに応じて Chat Completions または Responses を自動的に選択します。", "copilotProxyHint": "GitHub Copilot を Claude プロバイダーとして使用する場合、ローカルプロキシが常に必要です。プロキシは現在のモデルに応じて Chat Completions または Responses を自動的に選択します。",
"openLinkFailed": "リンクを開けませんでした", "openLinkFailed": "リンクを開けませんでした",
"openclawModelsRegistered": "モデルが /model リストに登録されました", "openclawModelsRegistered": "モデルが /model リストに登録されました",
"openclawDefaultModelSet": "デフォルトモデルに設定しました", "openclawDefaultModelSet": "デフォルトモデルに設定しました",
"openclawDefaultModelSetFailed": "デフォルトモデルの設定に失敗しました", "openclawDefaultModelSetFailed": "デフォルトモデルの設定に失敗しました",
"openclawNoModels": "モデルが設定されていません", "openclawNoModels": "モデルが設定されていません",
"backfillWarning": "切り替え成功しましたが、前のプロバイダーへの設定保存に失敗しました", "backfillWarning": "切り替え成功しましたが、前のプロバイダーへの設定保存に失敗しました"
"windowControlFailed": "ウィンドウ操作に失敗しました: {{error}}",
"officialBlockedByProxy": "ローカルルーティングモード中は公式プロバイダーに切り替えできません。ルーティング経由で公式 API にアクセスするとアカウントが停止される可能性があります。",
"proxyOfficialWarning": "現在のプロバイダー {{name}} は公式です。ローカルルーティングを使用する前にサードパーティプロバイダーに切り替えてください。"
}, },
"confirm": { "confirm": {
"deleteProvider": "プロバイダーを削除", "deleteProvider": "プロバイダーを削除",
@@ -217,8 +209,8 @@
"removeProvider": "プロバイダーを解除", "removeProvider": "プロバイダーを解除",
"removeProviderMessage": "プロバイダー「{{name}}」を設定から解除してもよろしいですか?\n\n解除後、このプロバイダーは無効になりますが、設定データは CC Switch に保持されます。いつでも再追加できます。", "removeProviderMessage": "プロバイダー「{{name}}」を設定から解除してもよろしいですか?\n\n解除後、このプロバイダーは無効になりますが、設定データは CC Switch に保持されます。いつでも再追加できます。",
"proxy": { "proxy": {
"title": "ローカルルーティングの有効化", "title": "ローカルプロキシの有効化",
"message": "ローカルルーティングは上級機能です。有効にする前に、その仕組みを理解していることをご確認ください。\n\n適切な設定方法については、関連ドキュメントまたはプロバイダーにご相談ください。", "message": "ローカルプロキシは上級機能です。有効にする前に、その仕組みを理解していることをご確認ください。\n\n適切な設定方法については、関連ドキュメントまたはプロバイダーにご相談ください。",
"confirm": "理解しました、有効にする" "confirm": "理解しました、有効にする"
}, },
"failover": { "failover": {
@@ -253,7 +245,7 @@
"tabGeneral": "一般", "tabGeneral": "一般",
"tabAuth": "認証", "tabAuth": "認証",
"tabAdvanced": "詳細", "tabAdvanced": "詳細",
"tabProxy": "ルーティング", "tabProxy": "プロキシ",
"authCenter": { "authCenter": {
"title": "OAuth 認証センター", "title": "OAuth 認証センター",
"description": "Claude Code で他のサブスクリプションをご利用いただけます。コンプライアンスリスクにご注意ください。", "description": "Claude Code で他のサブスクリプションをご利用いただけます。コンプライアンスリスクにご注意ください。",
@@ -267,10 +259,10 @@
"description": "Claude、Codex、Gemini の設定保存パスを管理" "description": "Claude、Codex、Gemini の設定保存パスを管理"
}, },
"proxy": { "proxy": {
"title": "ローカルルーティング", "title": "ローカルプロキシ",
"description": "ルーティングサービスの切り替え、ステータスとポート情報を表示", "description": "プロキシサービスの切り替え、ステータスとポート情報を表示",
"enableFeature": "メインページにルーティング切り替えを表示", "enableFeature": "メインページにプロキシ切り替えを表示",
"enableFeatureDescription": "有効にすると、メインページ上部にルーティングとフェイルオーバーの切り替えが表示されます", "enableFeatureDescription": "有効にすると、メインページ上部にプロキシとフェイルオーバーの切り替えが表示されます",
"enableFailoverToggle": "メインページにフェイルオーバー切り替えを表示", "enableFailoverToggle": "メインページにフェイルオーバー切り替えを表示",
"enableFailoverToggleDescription": "有効にすると、メインページ上部にフェイルオーバー切り替えが独立して表示されます", "enableFailoverToggleDescription": "有効にすると、メインページ上部にフェイルオーバー切り替えが独立して表示されます",
"running": "実行中", "running": "実行中",
@@ -502,8 +494,6 @@
"autoLaunchFailed": "自動起動の設定に失敗しました", "autoLaunchFailed": "自動起動の設定に失敗しました",
"minimizeToTray": "閉じるときトレイへ最小化", "minimizeToTray": "閉じるときトレイへ最小化",
"minimizeToTrayDescription": "チェックすると閉じるボタンでトレイに隠し、オフならアプリを終了します。", "minimizeToTrayDescription": "チェックすると閉じるボタンでトレイに隠し、オフならアプリを終了します。",
"useAppWindowControls": "アプリ内ウィンドウボタンを有効化",
"useAppWindowControlsDescription": "有効にすると、アプリヘッダーに最小化・最大化/復元・閉じるボタンを表示します。",
"enableClaudePluginIntegration": "Claude Code 拡張に適用", "enableClaudePluginIntegration": "Claude Code 拡張に適用",
"enableClaudePluginIntegrationDescription": "オンにすると VS Code の Claude Code 拡張のプロバイダーも同期します", "enableClaudePluginIntegrationDescription": "オンにすると VS Code の Claude Code 拡張のプロバイダーも同期します",
"skipClaudeOnboarding": "Claude Code の初回確認をスキップ", "skipClaudeOnboarding": "Claude Code の初回確認をスキップ",
@@ -622,14 +612,14 @@
"saving": "保存中...", "saving": "保存中...",
"globalProxy": { "globalProxy": {
"label": "グローバルプロキシ", "label": "グローバルプロキシ",
"hint": "すべてのリクエスト(API、Skills ダウンロードなど)をプロキシ経由で送信します。ローカルルーティング有効時、アプリのリクエストもこのプロキシを経由します。空欄で直接接続。", "hint": "すべてのリクエスト(API、Skills ダウンロードなど)をプロキシ経由で送信します。空欄で直接接続。",
"username": "ユーザー名(任意)", "username": "ユーザー名(任意)",
"password": "パスワード(任意)", "password": "パスワード(任意)",
"test": "接続テスト", "test": "接続テスト",
"scan": "ローカルプロキシをスキャン", "scan": "ローカルプロキシをスキャン",
"clear": "クリア", "clear": "クリア",
"scanFailed": "スキャンに失敗しました: {{error}}", "scanFailed": "スキャンに失敗しました: {{error}}",
"saved": "ルーティング設定を保存しました", "saved": "プロキシ設定を保存しました",
"saveFailed": "保存に失敗しました: {{error}}", "saveFailed": "保存に失敗しました: {{error}}",
"testSuccess": "接続成功!遅延 {{latency}}ms", "testSuccess": "接続成功!遅延 {{latency}}ms",
"testFailed": "接続に失敗しました: {{error}}", "testFailed": "接続に失敗しました: {{error}}",
@@ -725,9 +715,7 @@
"copyCommand": "コマンドをコピー", "copyCommand": "コマンドをコピー",
"copyMessage": "メッセージをコピー", "copyMessage": "メッセージをコピー",
"messageCopied": "メッセージがコピーされました", "messageCopied": "メッセージがコピーされました",
"conversationHistory": "会話履歴", "conversationHistory": "会話履歴"
"expandContent": "全文を表示",
"collapseContent": "折りたたむ"
}, },
"console": { "console": {
"providerSwitchReceived": "プロバイダー切り替えイベントを受信:", "providerSwitchReceived": "プロバイダー切り替えイベントを受信:",
@@ -785,6 +773,7 @@
"siliconflow": "SiliconFlow は CC Switch の公式パートナーです", "siliconflow": "SiliconFlow は CC Switch の公式パートナーです",
"ucloud": "Compshare は CC Switch ユーザー向けに特別ボーナスを提供しています。このリンクから登録すると、5元のプラットフォーム体験クレジットがもらえます!", "ucloud": "Compshare は CC Switch ユーザー向けに特別ボーナスを提供しています。このリンクから登録すると、5元のプラットフォーム体験クレジットがもらえます!",
"micu": "Micu は CC Switch の公式パートナーです", "micu": "Micu は CC Switch の公式パートナーです",
"x-code": "XCodeAPI は CC Switch ユーザー向けに特別ボーナスを提供しています。このリンクから登録すると、初回注文で 10% の追加クレジットがもらえます(管理者に連絡して受け取り)",
"ctok": "公式サイトで CTok コミュニティに参加し、プランを購読してください。", "ctok": "公式サイトで CTok コミュニティに参加し、プランを購読してください。",
"ddshub": "DDSHub は CC Switch ユーザー向けに特別ボーナスを提供しています。このリンクから登録すると、初回チャージで 10% の追加クレジットがもらえます(グループ管理者に連絡して受け取り)!", "ddshub": "DDSHub は CC Switch ユーザー向けに特別ボーナスを提供しています。このリンクから登録すると、初回チャージで 10% の追加クレジットがもらえます(グループ管理者に連絡して受け取り)!",
"lionccapi": "LionCCAPIはCC Switchユーザーに特別特典を提供しています。登録後、WeChat HSQBJ088888888を追加し、「cc-switch」と伝えると$10分のクレジットがもらえます!", "lionccapi": "LionCCAPIはCC Switchユーザーに特別特典を提供しています。登録後、WeChat HSQBJ088888888を追加し、「cc-switch」と伝えると$10分のクレジットがもらえます!",
@@ -822,10 +811,10 @@
"fullUrlLabel": "フル URL", "fullUrlLabel": "フル URL",
"fullUrlEnabled": "フル URL モード", "fullUrlEnabled": "フル URL モード",
"fullUrlDisabled": "フル URL として設定", "fullUrlDisabled": "フル URL として設定",
"fullUrlHint": "💡 完全なリクエスト URL を入力してください。このモードはルーティングを有効にして使用する必要があり、ルーティングはこの URL をそのまま使用し、パスを追加しません", "fullUrlHint": "💡 完全なリクエスト URL を入力してください。このモードはプロキシを有効にして使用する必要があり、プロキシはこの URL をそのまま使用し、パスを追加しません",
"apiFormatAnthropic": "Anthropic Messages(ネイティブ)", "apiFormatAnthropic": "Anthropic Messages(ネイティブ)",
"apiFormatOpenAIChat": "OpenAI Chat Completionsルーティングが必要)", "apiFormatOpenAIChat": "OpenAI Chat Completionsプロキシが必要)",
"apiFormatOpenAIResponses": "OpenAI Responses APIルーティングが必要)", "apiFormatOpenAIResponses": "OpenAI Responses APIプロキシが必要)",
"authField": "認証フィールド", "authField": "認証フィールド",
"authFieldAuthToken": "ANTHROPIC_AUTH_TOKEN(デフォルト)", "authFieldAuthToken": "ANTHROPIC_AUTH_TOKEN(デフォルト)",
"authFieldApiKey": "ANTHROPIC_API_KEY", "authFieldApiKey": "ANTHROPIC_API_KEY",
@@ -945,6 +934,11 @@
"testPrompt": "テストプロンプト", "testPrompt": "テストプロンプト",
"degradedThreshold": "低下閾値(ミリ秒)", "degradedThreshold": "低下閾値(ミリ秒)",
"maxRetries": "最大リトライ回数", "maxRetries": "最大リトライ回数",
"proxyConfig": "プロキシ設定",
"useCustomProxy": "個別プロキシを使用",
"proxyConfigDesc": "このプロバイダーに個別のネットワークプロキシを設定します。無効の場合はシステムプロキシまたはグローバル設定を使用します。",
"proxyUsername": "ユーザー名(任意)",
"proxyPassword": "パスワード(任意)",
"pricingConfig": "課金設定", "pricingConfig": "課金設定",
"useCustomPricing": "個別設定を使用", "useCustomPricing": "個別設定を使用",
"pricingConfigDesc": "このプロバイダーに個別の課金パラメータを設定します。無効の場合はグローバル設定を使用します。", "pricingConfigDesc": "このプロバイダーに個別の課金パラメータを設定します。無効の場合はグローバル設定を使用します。",
@@ -1048,11 +1042,6 @@
"today": "24時間", "today": "24時間",
"last7days": "7日間", "last7days": "7日間",
"last30days": "30日間", "last30days": "30日間",
"presetToday": "当日",
"preset1d": "1d",
"preset7d": "7d",
"preset14d": "14d",
"preset30d": "30d",
"totalRequests": "総リクエスト数", "totalRequests": "総リクエスト数",
"totalCost": "総コスト", "totalCost": "総コスト",
"cost": "コスト", "cost": "コスト",
@@ -1073,8 +1062,6 @@
"outputTokens": "出力", "outputTokens": "出力",
"cacheReadTokens": "キャッシュヒット", "cacheReadTokens": "キャッシュヒット",
"cacheCreationTokens": "キャッシュ作成", "cacheCreationTokens": "キャッシュ作成",
"cacheReadShort": "キャッシュ読",
"cacheWriteShort": "書",
"timingInfo": "応答時間/TTFT", "timingInfo": "応答時間/TTFT",
"status": "ステータス", "status": "ステータス",
"multiplier": "倍率", "multiplier": "倍率",
@@ -1095,7 +1082,7 @@
}, },
"dataSources": "データソース", "dataSources": "データソース",
"dataSource": { "dataSource": {
"proxy": "ルーティング", "proxy": "プロキシ",
"session_log": "セッションログ", "session_log": "セッションログ",
"codex_db": "Codex DB", "codex_db": "Codex DB",
"codex_session": "Codex セッション", "codex_session": "Codex セッション",
@@ -1110,8 +1097,6 @@
"failed": "セッション同期に失敗しました" "failed": "セッション同期に失敗しました"
}, },
"totalRecords": "全 {{total}} 件", "totalRecords": "全 {{total}} 件",
"goToPage": "移動",
"pageInputPlaceholder": "ページ",
"modelPricing": "モデル料金", "modelPricing": "モデル料金",
"loadPricingError": "料金データの読み込みに失敗しました", "loadPricingError": "料金データの読み込みに失敗しました",
"modelPricingDesc": "各モデルのトークンコストを設定", "modelPricingDesc": "各モデルのトークンコストを設定",
@@ -1146,10 +1131,6 @@
"searchProviderPlaceholder": "プロバイダーを検索...", "searchProviderPlaceholder": "プロバイダーを検索...",
"searchModelPlaceholder": "モデルを検索...", "searchModelPlaceholder": "モデルを検索...",
"timeRange": "期間", "timeRange": "期間",
"customRange": "カレンダーフィルター",
"customRangeHint": "日付と時刻の両方に対応、最大 30 日",
"startTime": "開始時刻",
"endTime": "終了時刻",
"input": "Input", "input": "Input",
"output": "Output", "output": "Output",
"cacheWrite": "作成", "cacheWrite": "作成",
@@ -1951,9 +1932,9 @@
"addressCopied": "アドレスをコピーしました", "addressCopied": "アドレスをコピーしました",
"currentProvider": "現在のプロバイダー:", "currentProvider": "現在のプロバイダー:",
"waitingFirstRequest": "現在のプロバイダー: 最初のリクエスト待ち...", "waitingFirstRequest": "現在のプロバイダー: 最初のリクエスト待ち...",
"stoppedTitle": "ルーティングサービス停止中", "stoppedTitle": "プロキシサービス停止中",
"stoppedDescription": "上のトグルでサービスを開始できます", "stoppedDescription": "上のトグルでサービスを開始できます",
"openSettings": "ルーティングサービスを設定", "openSettings": "プロキシサービスを設定",
"stats": { "stats": {
"activeConnections": "アクティブ接続", "activeConnections": "アクティブ接続",
"totalRequests": "総リクエスト数", "totalRequests": "総リクエスト数",
@@ -1962,14 +1943,14 @@
} }
}, },
"settings": { "settings": {
"title": "ルーティングサービス設定", "title": "プロキシサービス設定",
"description": "ローカルルーティングサーバーのリッスンアドレス、ポート、実行パラメータを設定します。保存後すぐに反映されます。", "description": "ローカルプロキシサーバーのリッスンアドレス、ポート、実行パラメータを設定します。保存後すぐに反映されます。",
"alert": { "alert": {
"autoApply": "変更は実行中のルーティングサービスに自動的に同期され、手動での再起動は不要です。" "autoApply": "変更は実行中のプロキシサービスに自動的に同期され、手動での再起動は不要です。"
}, },
"basic": { "basic": {
"title": "基本設定", "title": "基本設定",
"description": "ルーティングサービスのリッスンアドレスとポートを設定します。" "description": "プロキシサービスのリッスンアドレスとポートを設定します。"
}, },
"advanced": { "advanced": {
"title": "詳細パラメータ", "title": "詳細パラメータ",
@@ -1983,12 +1964,12 @@
"listenAddress": { "listenAddress": {
"label": "リッスンアドレス", "label": "リッスンアドレス",
"placeholder": "127.0.0.1", "placeholder": "127.0.0.1",
"description": "ルーティングサーバーがリッスンするIPアドレス(推奨: 127.0.0.1" "description": "プロキシサーバーがリッスンするIPアドレス(推奨: 127.0.0.1"
}, },
"listenPort": { "listenPort": {
"label": "リッスンポート", "label": "リッスンポート",
"placeholder": "15721", "placeholder": "15721",
"description": "ルーティングサーバーがリッスンするポート番号(1024 ~ 65535" "description": "プロキシサーバーがリッスンするポート番号(1024 ~ 65535"
}, },
"maxRetries": { "maxRetries": {
"label": "最大リトライ回数", "label": "最大リトライ回数",
@@ -2002,7 +1983,7 @@
}, },
"enableLogging": { "enableLogging": {
"label": "ログ記録を有効化", "label": "ログ記録を有効化",
"description": "トラブルシューティングのためにすべてのルーティングリクエストを記録" "description": "トラブルシューティングのためにすべてのプロキシリクエストを記録"
}, },
"streamingFirstByteTimeout": { "streamingFirstByteTimeout": {
"label": "ストリーミング初回バイトタイムアウト(秒)", "label": "ストリーミング初回バイトタイムアウト(秒)",
@@ -2033,29 +2014,29 @@
"save": "設定を保存" "save": "設定を保存"
}, },
"toast": { "toast": {
"saved": "ルーティング設定を保存しました", "saved": "プロキシ設定を保存しました",
"saveFailed": "保存に失敗しました: {{error}}" "saveFailed": "保存に失敗しました: {{error}}"
}, },
"invalidPort": "無効なポートです。1024〜65535 の数値を入力してください", "invalidPort": "無効なポートです。1024〜65535 の数値を入力してください",
"invalidAddress": "無効なアドレスです。有効な IP アドレス(例: 127.0.0.1)または localhost を入力してください", "invalidAddress": "無効なアドレスです。有効な IP アドレス(例: 127.0.0.1)または localhost を入力してください",
"configSaved": "ルーティング設定を保存しました", "configSaved": "プロキシ設定を保存しました",
"configSaveFailed": "設定の保存に失敗しました", "configSaveFailed": "設定の保存に失敗しました",
"restartRequired": "アドレスまたはポートの変更を反映するにはルーティングサービスの再起動が必要です" "restartRequired": "アドレスまたはポートの変更を反映するにはプロキシサービスの再起動が必要です"
}, },
"switchFailed": "切り替えに失敗しました: {{error}}", "switchFailed": "切り替えに失敗しました: {{error}}",
"takeover": { "takeover": {
"hint": "ルーティングするアプリを選択します。有効にすると、そのアプリのリクエストはローカルルーティング経由で転送されます", "hint": "テイクオーバーするアプリを選択します。有効にすると、そのアプリのリクエストはローカルプロキシ経由で転送されます",
"enabled": "{{app}} ルーティング有効", "enabled": "{{app}} テイクオーバー有効",
"disabled": "{{app}} ルーティング無効", "disabled": "{{app}} テイクオーバー無効",
"failed": "ルーティングの切り替えに失敗しました", "failed": "テイクオーバーの切り替えに失敗しました",
"tooltip": { "tooltip": {
"active": "{{appLabel}} がルーティング中 - {{address}}:{{port}}\nホットスイッチングのためプロバイダを切り替え", "active": "{{appLabel}} がインターセプト中 - {{address}}:{{port}}\nホットスイッチングのためプロバイダを切り替え",
"broken": "{{appLabel}} がルーティング中ですが、ルーティングサービスが実行されていません", "broken": "{{appLabel}} がインターセプト中ですが、プロキシサービスが実行されていません",
"inactive": "{{appLabel}} のリクエストをローカルルーティング経由でルーティング" "inactive": "{{appLabel}} のライブ設定をインターセプトしてリクエストをローカルプロキシ経由でルーティング"
} }
}, },
"failover": { "failover": {
"proxyRequired": "フェイルオーバーを設定するには、ルーティングサービスを先に起動する必要があります", "proxyRequired": "フェイルオーバーを設定するには、プロキシサービスを先に起動する必要があります",
"autoSwitch": "自動フェイルオーバー", "autoSwitch": "自動フェイルオーバー",
"autoSwitchDescription": "有効にするとキューの P1 に即時切り替え、リクエスト失敗時はキュー内の次のプロバイダーを自動で試行します" "autoSwitchDescription": "有効にするとキューの P1 に即時切り替え、リクエスト失敗時はキュー内の次のプロバイダーを自動で試行します"
}, },
@@ -2119,10 +2100,10 @@
"failed": "ログ状態の切り替えに失敗しました" "failed": "ログ状態の切り替えに失敗しました"
}, },
"server": { "server": {
"started": "ルーティングサービスが開始されました - {{address}}:{{port}}", "started": "プロキシサービスが開始されました - {{address}}:{{port}}",
"startFailed": "ルーティングサービスの開始に失敗しました: {{detail}}" "startFailed": "プロキシサービスの開始に失敗しました: {{detail}}"
}, },
"stoppedWithRestore": "ルーティングサービスが停止し、すべてのルーティング設定が復元されました", "stoppedWithRestore": "プロキシサービスが停止し、すべてのテイクオーバー設定が復元されました",
"stopWithRestoreFailed": "停止に失敗しました: {{detail}}" "stopWithRestoreFailed": "停止に失敗しました: {{detail}}"
}, },
"streamCheck": { "streamCheck": {
@@ -2140,21 +2121,11 @@
"operational": "{{providerName}} は正常に動作しています ({{responseTimeMs}}ms)", "operational": "{{providerName}} は正常に動作しています ({{responseTimeMs}}ms)",
"degraded": "{{providerName}} の応答が遅いです ({{responseTimeMs}}ms)", "degraded": "{{providerName}} の応答が遅いです ({{responseTimeMs}}ms)",
"failed": "{{providerName}} のチェックに失敗しました: {{message}}", "failed": "{{providerName}} のチェックに失敗しました: {{message}}",
"rejected": "{{providerName}} のチェックが拒否されました: {{message}}", "error": "{{providerName}} のチェックでエラーが発生しました: {{error}}"
"error": "{{providerName}} のチェックでエラーが発生しました: {{error}}",
"httpHint": {
"400": "リクエスト形式が拒否されました。ヘルスチェックの形式は実際の使用と異なる場合があります。",
"401": "APIキーが無効か、OAuthなどの認証方式を使用しています。チェック失敗は実際に使えないことを意味しません。",
"402": "アカウントの利用枠または請求の問題です。",
"403": "プロバイダーがリクエストを拒否しました。実際の使用では正常に動作する場合があります。",
"404": "エンドポイントが見つかりません。Base URLとAPIパスを確認してください。",
"429": "リクエストが多すぎます。しばらくしてからお試しください。",
"5xx": "プロバイダーの内部エラーです。一時的な問題の可能性が高いです。"
}
}, },
"proxyConfig": { "proxyConfig": {
"proxyEnabled": "ルーティング総スイッチ", "proxyEnabled": "プロキシ有効",
"appTakeover": "ルーティング有効", "appTakeover": "プロキシ有効",
"perAppConfig": "アプリ別設定", "perAppConfig": "アプリ別設定",
"circuitBreaker": "サーキットブレーカー", "circuitBreaker": "サーキットブレーカー",
"circuitBreakerSettings": "サーキットブレーカー設定", "circuitBreakerSettings": "サーキットブレーカー設定",
+50 -79
View File
@@ -91,11 +91,7 @@
"switchToChinese": "切换到中文", "switchToChinese": "切换到中文",
"switchToEnglish": "切换到英文", "switchToEnglish": "切换到英文",
"enterEditMode": "进入编辑模式", "enterEditMode": "进入编辑模式",
"exitEditMode": "退出编辑模式", "exitEditMode": "退出编辑模式"
"windowMinimize": "最小化窗口",
"windowMaximize": "最大化窗口",
"windowRestore": "还原窗口",
"windowClose": "关闭窗口"
}, },
"provider": { "provider": {
"tabProvider": "供应商", "tabProvider": "供应商",
@@ -108,7 +104,6 @@
"currentlyUsing": "当前使用", "currentlyUsing": "当前使用",
"enable": "启用", "enable": "启用",
"inUse": "使用中", "inUse": "使用中",
"blockedByProxy": "已拦截",
"editProvider": "编辑供应商", "editProvider": "编辑供应商",
"editProviderHint": "更新配置后将立即应用到当前供应商。", "editProviderHint": "更新配置后将立即应用到当前供应商。",
"deleteProvider": "删除供应商", "deleteProvider": "删除供应商",
@@ -194,22 +189,19 @@
"deleteFailed": "删除供应商失败:{{error}}", "deleteFailed": "删除供应商失败:{{error}}",
"settingsSaved": "设置已保存", "settingsSaved": "设置已保存",
"settingsSaveFailed": "保存设置失败:{{error}}", "settingsSaveFailed": "保存设置失败:{{error}}",
"proxyRequiredForSwitch": "此供应商{{reason}},需要路由服务才能正常使用,请先启动路由", "proxyRequiredForSwitch": "此供应商{{reason}},需要代理服务才能正常使用,请先启动代理",
"proxyReasonCopilot": "使用 GitHub Copilot 作为 Claude 供应商", "proxyReasonCopilot": "使用 GitHub Copilot 作为 Claude 供应商",
"proxyReasonOpenAIChat": "使用 OpenAI Chat 接口格式", "proxyReasonOpenAIChat": "使用 OpenAI Chat 接口格式",
"proxyReasonOpenAIResponses": "使用 OpenAI Responses 接口格式", "proxyReasonOpenAIResponses": "使用 OpenAI Responses 接口格式",
"proxyReasonFullUrl": "开启了完整 URL 连接模式", "proxyReasonFullUrl": "开启了完整 URL 连接模式",
"openAIFormatHint": "此供应商使用 OpenAI 兼容格式,需要开启路由服务才能正常使用", "openAIFormatHint": "此供应商使用 OpenAI 兼容格式,需要开启代理服务才能正常使用",
"copilotProxyHint": "GitHub Copilot 作为 Claude 供应商时始终需要本地路由;路由会根据当前模型自动选择 Chat Completions 或 Responses。", "copilotProxyHint": "GitHub Copilot 作为 Claude 供应商时始终需要本地代理;代理会根据当前模型自动选择 Chat Completions 或 Responses。",
"openLinkFailed": "链接打开失败", "openLinkFailed": "链接打开失败",
"openclawModelsRegistered": "模型已注册到 /model 列表", "openclawModelsRegistered": "模型已注册到 /model 列表",
"openclawDefaultModelSet": "已设为默认模型", "openclawDefaultModelSet": "已设为默认模型",
"openclawDefaultModelSetFailed": "设置默认模型失败", "openclawDefaultModelSetFailed": "设置默认模型失败",
"openclawNoModels": "该供应商没有配置模型", "openclawNoModels": "该供应商没有配置模型",
"backfillWarning": "切换成功,但旧供应商配置回填失败,您手动修改的配置可能未保存", "backfillWarning": "切换成功,但旧供应商配置回填失败,您手动修改的配置可能未保存"
"windowControlFailed": "窗口控制失败:{{error}}",
"officialBlockedByProxy": "本地路由模式下不能切换到官方供应商,使用路由访问官方 API 可能导致账号被封禁",
"proxyOfficialWarning": "当前供应商 {{name}} 是官方供应商,建议切换到第三方供应商后再使用本地路由"
}, },
"confirm": { "confirm": {
"deleteProvider": "删除供应商", "deleteProvider": "删除供应商",
@@ -217,8 +209,8 @@
"removeProvider": "移除供应商", "removeProvider": "移除供应商",
"removeProviderMessage": "确定要从配置中移除供应商 \"{{name}}\" 吗?\n\n移除后该供应商将不再生效,但配置数据会保留在 CC Switch 中,您可以随时重新添加。", "removeProviderMessage": "确定要从配置中移除供应商 \"{{name}}\" 吗?\n\n移除后该供应商将不再生效,但配置数据会保留在 CC Switch 中,您可以随时重新添加。",
"proxy": { "proxy": {
"title": "启用本地路由服务", "title": "启用本地代理服务",
"message": "本地路由是一项高级功能,启用前请确保您已了解其工作原理。\n\n建议先查阅相关文档或咨询您的供应商,以获取正确的配置方式。", "message": "本地代理是一项高级功能,启用前请确保您已了解其工作原理。\n\n建议先查阅相关文档或咨询您的供应商,以获取正确的配置方式。",
"confirm": "我已了解,继续启用" "confirm": "我已了解,继续启用"
}, },
"failover": { "failover": {
@@ -253,7 +245,7 @@
"tabGeneral": "通用", "tabGeneral": "通用",
"tabAuth": "认证", "tabAuth": "认证",
"tabAdvanced": "高级", "tabAdvanced": "高级",
"tabProxy": "路由", "tabProxy": "代理",
"authCenter": { "authCenter": {
"title": "OAuth 认证中心", "title": "OAuth 认证中心",
"description": "在 Claude Code 中使用您的其他订阅,请注意合规风险。", "description": "在 Claude Code 中使用您的其他订阅,请注意合规风险。",
@@ -267,10 +259,10 @@
"description": "管理 Claude、Codex 和 Gemini 的配置存储路径" "description": "管理 Claude、Codex 和 Gemini 的配置存储路径"
}, },
"proxy": { "proxy": {
"title": "本地路由", "title": "本地代理",
"description": "控制路由服务开关、查看状态与端口信息", "description": "控制代理服务开关、查看状态与端口信息",
"enableFeature": "在主页面显示本地路由开关", "enableFeature": "在主页面显示本地代理开关",
"enableFeatureDescription": "开启后,主页面顶部将显示路由和故障转移开关", "enableFeatureDescription": "开启后,主页面顶部将显示代理和故障转移开关",
"enableFailoverToggle": "在主页面显示故障转移开关", "enableFailoverToggle": "在主页面显示故障转移开关",
"enableFailoverToggleDescription": "开启后,主页面顶部将独立显示故障转移开关", "enableFailoverToggleDescription": "开启后,主页面顶部将独立显示故障转移开关",
"running": "运行中", "running": "运行中",
@@ -502,8 +494,6 @@
"autoLaunchFailed": "设置开机自启失败", "autoLaunchFailed": "设置开机自启失败",
"minimizeToTray": "关闭时最小化到托盘", "minimizeToTray": "关闭时最小化到托盘",
"minimizeToTrayDescription": "勾选后点击关闭按钮会隐藏到系统托盘,取消则直接退出应用。", "minimizeToTrayDescription": "勾选后点击关闭按钮会隐藏到系统托盘,取消则直接退出应用。",
"useAppWindowControls": "启用应用级窗口按钮",
"useAppWindowControlsDescription": "开启后使用应用自建的最小化、最大化/还原、关闭按钮;关闭后沿用系统窗口模式。",
"enableClaudePluginIntegration": "应用到 Claude Code 插件", "enableClaudePluginIntegration": "应用到 Claude Code 插件",
"enableClaudePluginIntegrationDescription": "开启后 Vscode Claude Code 插件的供应商将随本软件切换", "enableClaudePluginIntegrationDescription": "开启后 Vscode Claude Code 插件的供应商将随本软件切换",
"skipClaudeOnboarding": "跳过 Claude Code 初次安装确认", "skipClaudeOnboarding": "跳过 Claude Code 初次安装确认",
@@ -622,7 +612,7 @@
"saving": "正在保存...", "saving": "正在保存...",
"globalProxy": { "globalProxy": {
"label": "全局代理", "label": "全局代理",
"hint": "代理所有请求(API、Skills 下载等)。开启本地路由时,应用的请求也会经过此代理。留空表示直连。", "hint": "代理所有请求(API、Skills 下载等)。留空表示直连。",
"username": "用户名(可选)", "username": "用户名(可选)",
"password": "密码(可选)", "password": "密码(可选)",
"test": "测试连接", "test": "测试连接",
@@ -725,9 +715,7 @@
"copyCommand": "复制命令", "copyCommand": "复制命令",
"copyMessage": "复制消息", "copyMessage": "复制消息",
"messageCopied": "已复制消息内容", "messageCopied": "已复制消息内容",
"conversationHistory": "对话记录", "conversationHistory": "对话记录"
"expandContent": "展开完整内容",
"collapseContent": "收起"
}, },
"console": { "console": {
"providerSwitchReceived": "收到供应商切换事件:", "providerSwitchReceived": "收到供应商切换事件:",
@@ -785,6 +773,7 @@
"siliconflow": "硅基流动是 CC Switch 的官方合作伙伴", "siliconflow": "硅基流动是 CC Switch 的官方合作伙伴",
"ucloud": "优云智算为CC Switch 的用户提供了特殊优惠,通过此链接注册,可以获得五元平台体验金!", "ucloud": "优云智算为CC Switch 的用户提供了特殊优惠,通过此链接注册,可以获得五元平台体验金!",
"micu": "Micu 是 CC Switch 的官方合作伙伴", "micu": "Micu 是 CC Switch 的官方合作伙伴",
"x-code": "XCodeAPI 为CC Switch 的用户提供特别福利,使用此链接注册后首单加赠10%的额度(联系站长领取)",
"ctok": "官网加入CTok社群,订阅套餐。", "ctok": "官网加入CTok社群,订阅套餐。",
"ddshub": "呆呆兽为CC Switch 的用户提供了特别福利,通过此链接注册后,首单充值可额外赠送 10% 额度(联系群主领取)!", "ddshub": "呆呆兽为CC Switch 的用户提供了特别福利,通过此链接注册后,首单充值可额外赠送 10% 额度(联系群主领取)!",
"lionccapi": "LionCCAPI 为 CC Switch 的用户提供了特别福利,注册后添加客服微信HSQBJ088888888,发暗号cc-switch备注即可送10美金额度!", "lionccapi": "LionCCAPI 为 CC Switch 的用户提供了特别福利,注册后添加客服微信HSQBJ088888888,发暗号cc-switch备注即可送10美金额度!",
@@ -823,10 +812,10 @@
"fullUrlLabel": "完整 URL", "fullUrlLabel": "完整 URL",
"fullUrlEnabled": "完整 URL 模式", "fullUrlEnabled": "完整 URL 模式",
"fullUrlDisabled": "标记为完整 URL", "fullUrlDisabled": "标记为完整 URL",
"fullUrlHint": "💡 请填写完整请求 URL,并且必须开启路由后使用;路由将直接使用此 URL,不拼接路径", "fullUrlHint": "💡 请填写完整请求 URL,并且必须开启代理后使用;代理将直接使用此 URL,不拼接路径",
"apiFormatAnthropic": "Anthropic Messages (原生)", "apiFormatAnthropic": "Anthropic Messages (原生)",
"apiFormatOpenAIChat": "OpenAI Chat Completions (需开启路由)", "apiFormatOpenAIChat": "OpenAI Chat Completions (需开启代理)",
"apiFormatOpenAIResponses": "OpenAI Responses API (需开启路由)", "apiFormatOpenAIResponses": "OpenAI Responses API (需开启代理)",
"authField": "认证字段", "authField": "认证字段",
"authFieldAuthToken": "ANTHROPIC_AUTH_TOKEN(默认)", "authFieldAuthToken": "ANTHROPIC_AUTH_TOKEN(默认)",
"authFieldApiKey": "ANTHROPIC_API_KEY", "authFieldApiKey": "ANTHROPIC_API_KEY",
@@ -946,6 +935,11 @@
"testPrompt": "测试提示词", "testPrompt": "测试提示词",
"degradedThreshold": "降级阈值(毫秒)", "degradedThreshold": "降级阈值(毫秒)",
"maxRetries": "最大重试次数", "maxRetries": "最大重试次数",
"proxyConfig": "代理配置",
"useCustomProxy": "使用单独代理",
"proxyConfigDesc": "为此供应商配置单独的网络代理,不启用时使用系统代理或全局设置。",
"proxyUsername": "用户名(可选)",
"proxyPassword": "密码(可选)",
"pricingConfig": "计费配置", "pricingConfig": "计费配置",
"useCustomPricing": "使用单独配置", "useCustomPricing": "使用单独配置",
"pricingConfigDesc": "为此供应商配置单独的计费参数,不启用时使用全局默认配置。", "pricingConfigDesc": "为此供应商配置单独的计费参数,不启用时使用全局默认配置。",
@@ -1049,11 +1043,6 @@
"today": "24小时", "today": "24小时",
"last7days": "7天", "last7days": "7天",
"last30days": "30天", "last30days": "30天",
"presetToday": "当天",
"preset1d": "1d",
"preset7d": "7d",
"preset14d": "14d",
"preset30d": "30d",
"totalRequests": "总请求数", "totalRequests": "总请求数",
"totalCost": "总成本", "totalCost": "总成本",
"cost": "成本", "cost": "成本",
@@ -1074,8 +1063,6 @@
"outputTokens": "输出", "outputTokens": "输出",
"cacheReadTokens": "缓存命中", "cacheReadTokens": "缓存命中",
"cacheCreationTokens": "缓存创建", "cacheCreationTokens": "缓存创建",
"cacheReadShort": "缓存读",
"cacheWriteShort": "写",
"timingInfo": "用时/首字", "timingInfo": "用时/首字",
"status": "状态", "status": "状态",
"multiplier": "倍率", "multiplier": "倍率",
@@ -1096,7 +1083,7 @@
}, },
"dataSources": "数据来源", "dataSources": "数据来源",
"dataSource": { "dataSource": {
"proxy": "路由", "proxy": "代理",
"session_log": "会话日志", "session_log": "会话日志",
"codex_db": "Codex 数据库", "codex_db": "Codex 数据库",
"codex_session": "Codex 会话日志", "codex_session": "Codex 会话日志",
@@ -1111,8 +1098,6 @@
"failed": "会话同步失败" "failed": "会话同步失败"
}, },
"totalRecords": "共 {{total}} 条记录", "totalRecords": "共 {{total}} 条记录",
"goToPage": "跳转",
"pageInputPlaceholder": "页码",
"modelPricing": "模型定价", "modelPricing": "模型定价",
"loadPricingError": "加载定价数据失败", "loadPricingError": "加载定价数据失败",
"modelPricingDesc": "配置各模型的 Token 成本", "modelPricingDesc": "配置各模型的 Token 成本",
@@ -1147,10 +1132,6 @@
"searchProviderPlaceholder": "搜索供应商...", "searchProviderPlaceholder": "搜索供应商...",
"searchModelPlaceholder": "搜索模型...", "searchModelPlaceholder": "搜索模型...",
"timeRange": "时间范围", "timeRange": "时间范围",
"customRange": "日历筛选",
"customRangeHint": "支持日期与时间,最长 30 天",
"startTime": "开始时间",
"endTime": "结束时间",
"input": "Input", "input": "Input",
"output": "Output", "output": "Output",
"cacheWrite": "创建", "cacheWrite": "创建",
@@ -1952,9 +1933,9 @@
"addressCopied": "地址已复制", "addressCopied": "地址已复制",
"currentProvider": "当前 Provider", "currentProvider": "当前 Provider",
"waitingFirstRequest": "当前 Provider:等待首次请求…", "waitingFirstRequest": "当前 Provider:等待首次请求…",
"stoppedTitle": "路由服务已停止", "stoppedTitle": "代理服务已停止",
"stoppedDescription": "使用上方开关即可启动服务", "stoppedDescription": "使用上方开关即可启动服务",
"openSettings": "配置路由服务", "openSettings": "配置代理服务",
"stats": { "stats": {
"activeConnections": "活跃连接", "activeConnections": "活跃连接",
"totalRequests": "总请求数", "totalRequests": "总请求数",
@@ -1963,14 +1944,14 @@
} }
}, },
"settings": { "settings": {
"title": "路由服务设置", "title": "代理服务设置",
"description": "配置本地路由服务器的监听地址、端口和运行参数,保存后立即生效。", "description": "配置本地代理服务器的监听地址、端口和运行参数,保存后立即生效。",
"alert": { "alert": {
"autoApply": "保存后将自动同步到正在运行的路由服务,无需手动重启。" "autoApply": "保存后将自动同步到正在运行的代理服务,无需手动重启。"
}, },
"basic": { "basic": {
"title": "基础设置", "title": "基础设置",
"description": "配置路由服务监听的地址与端口。" "description": "配置代理服务监听的地址与端口。"
}, },
"advanced": { "advanced": {
"title": "高级参数", "title": "高级参数",
@@ -1984,12 +1965,12 @@
"listenAddress": { "listenAddress": {
"label": "监听地址", "label": "监听地址",
"placeholder": "127.0.0.1", "placeholder": "127.0.0.1",
"description": "路由服务器监听的 IP 地址(推荐 127.0.0.1" "description": "代理服务器监听的 IP 地址(推荐 127.0.0.1"
}, },
"listenPort": { "listenPort": {
"label": "监听端口", "label": "监听端口",
"placeholder": "15721", "placeholder": "15721",
"description": "路由服务器监听的端口号(1024 ~ 65535" "description": "代理服务器监听的端口号(1024 ~ 65535"
}, },
"maxRetries": { "maxRetries": {
"label": "最大重试次数", "label": "最大重试次数",
@@ -2003,7 +1984,7 @@
}, },
"enableLogging": { "enableLogging": {
"label": "启用日志记录", "label": "启用日志记录",
"description": "记录所有路由请求,便于排查问题" "description": "记录所有代理请求,便于排查问题"
}, },
"streamingFirstByteTimeout": { "streamingFirstByteTimeout": {
"label": "流式首字超时(秒)", "label": "流式首字超时(秒)",
@@ -2034,29 +2015,29 @@
"save": "保存配置" "save": "保存配置"
}, },
"toast": { "toast": {
"saved": "路由配置已保存", "saved": "代理配置已保存",
"saveFailed": "保存失败: {{error}}" "saveFailed": "保存失败: {{error}}"
}, },
"invalidPort": "端口无效,请输入 1024-65535 之间的数字", "invalidPort": "端口无效,请输入 1024-65535 之间的数字",
"invalidAddress": "地址无效,请输入有效的 IP 地址(如 127.0.0.1)或 localhost", "invalidAddress": "地址无效,请输入有效的 IP 地址(如 127.0.0.1)或 localhost",
"configSaved": "路由配置已保存", "configSaved": "代理配置已保存",
"configSaveFailed": "保存配置失败", "configSaveFailed": "保存配置失败",
"restartRequired": "修改地址或端口后需要重启路由服务才能生效" "restartRequired": "修改地址或端口后需要重启代理服务才能生效"
}, },
"switchFailed": "切换失败: {{error}}", "switchFailed": "切换失败: {{error}}",
"takeover": { "takeover": {
"hint": "选择要路由的应用,启用后该应用的请求将通过本地路由转发", "hint": "选择要接管的应用,启用后该应用的请求将通过本地代理转发",
"enabled": "{{app}} 路由已启用", "enabled": "{{app}} 接管已启用",
"disabled": "{{app}} 路由已关闭", "disabled": "{{app}} 接管已关闭",
"failed": "切换路由状态失败", "failed": "切换接管状态失败",
"tooltip": { "tooltip": {
"active": "{{appLabel}} 路由中 - {{address}}:{{port}}\n切换该应用供应商为热切换", "active": "{{appLabel}} 已接管 - {{address}}:{{port}}\n切换该应用供应商为热切换",
"broken": "{{appLabel}} 路由中,但路由服务未运行", "broken": "{{appLabel}} 已接管,但代理服务未运行",
"inactive": "路由 {{appLabel}} 的请求,让该应用请求走本地路由" "inactive": "接管 {{appLabel}} 的 Live 配置,让该应用请求走本地代理"
} }
}, },
"failover": { "failover": {
"proxyRequired": "需要先启动路由服务才能配置故障转移", "proxyRequired": "需要先启动代理服务才能配置故障转移",
"autoSwitch": "自动故障转移", "autoSwitch": "自动故障转移",
"autoSwitchDescription": "开启后将立即切换到队列 P1,并在请求失败时自动切换到队列中的下一个供应商" "autoSwitchDescription": "开启后将立即切换到队列 P1,并在请求失败时自动切换到队列中的下一个供应商"
}, },
@@ -2120,10 +2101,10 @@
"failed": "切换日志状态失败" "failed": "切换日志状态失败"
}, },
"server": { "server": {
"started": "路由服务已启动 - {{address}}:{{port}}", "started": "代理服务已启动 - {{address}}:{{port}}",
"startFailed": "启动路由服务失败: {{detail}}" "startFailed": "启动代理服务失败: {{detail}}"
}, },
"stoppedWithRestore": "路由服务已关闭,已恢复所有路由配置", "stoppedWithRestore": "代理服务已关闭,已恢复所有接管配置",
"stopWithRestoreFailed": "停止失败: {{detail}}" "stopWithRestoreFailed": "停止失败: {{detail}}"
}, },
"streamCheck": { "streamCheck": {
@@ -2141,21 +2122,11 @@
"operational": "{{providerName}} 运行正常 ({{responseTimeMs}}ms)", "operational": "{{providerName}} 运行正常 ({{responseTimeMs}}ms)",
"degraded": "{{providerName}} 响应较慢 ({{responseTimeMs}}ms)", "degraded": "{{providerName}} 响应较慢 ({{responseTimeMs}}ms)",
"failed": "{{providerName}} 检查失败: {{message}}", "failed": "{{providerName}} 检查失败: {{message}}",
"rejected": "{{providerName}} 检查被拒: {{message}}", "error": "{{providerName}} 检查出错: {{error}}"
"error": "{{providerName}} 检查出错: {{error}}",
"httpHint": {
"400": "供应商拒绝了请求格式。健康检查的探测格式可能与实际使用不同。",
"401": "API Key 可能无效,或供应商使用 OAuth 等认证方式。检查失败不代表实际不可用。",
"402": "账户配额或计费问题。",
"403": "供应商拒绝了此请求。部分供应商会校验客户端身份,检查失败但实际使用可能正常。",
"404": "接口地址不存在,请检查 Base URL 和 API 路径。",
"429": "请求频率过高,请稍后重试。",
"5xx": "供应商内部错误,通常是临时问题。"
}
}, },
"proxyConfig": { "proxyConfig": {
"proxyEnabled": "路由总开关", "proxyEnabled": "代理总开关",
"appTakeover": "路由启用", "appTakeover": "代理启用",
"perAppConfig": "应用配置", "perAppConfig": "应用配置",
"circuitBreaker": "熔断器配置", "circuitBreaker": "熔断器配置",
"circuitBreakerSettings": "熔断器设置", "circuitBreakerSettings": "熔断器设置",
+2
View File
@@ -5,6 +5,7 @@ import _dds from "./dds.svg?url";
import _eflowcode from "./eflowcode.png"; import _eflowcode from "./eflowcode.png";
import _pipellm from "./pipellm.png"; import _pipellm from "./pipellm.png";
import _shengsuanyun from "./shengsuanyun.svg?url"; import _shengsuanyun from "./shengsuanyun.svg?url";
import _xcode from "./xcode.svg?url";
export const icons: Record<string, string> = { export const icons: Record<string, string> = {
aicodemirror: `<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" style="flex:none;line-height:1" viewBox="0 0 1017.97 1056.47"><title>AICodeMirror</title><path fill="#E4906E" fill-rule="nonzero" d="M944.92 1014.53c-17.29,-9.23 -33.98,-19.28 -50.08,-30.16 -5.39,-3.65 -14.99,-11.7 -28.81,-24.16 -6.06,-5.47 -14.07,-13.51 -24.03,-24.13 -15.15,-16.17 -29.61,-29.9 -41.69,-40.4 -3.98,-3.46 -14.2,-11.02 -30.68,-22.69 -6.24,-4.42 -12.88,-12.15 -18.63,-19.09 -23.98,-29.04 -49.53,-58.44 -76.66,-88.19 -11.93,-13.1 -25.64,-26.11 -35.61,-36.5 -28.72,-29.92 -51.92,-51.96 -78.23,-79.66 -11.24,-11.83 -20.52,-21.3 -27.85,-28.41 -0.56,-0.53 -1.3,-0.84 -2.08,-0.84 -0.51,0 -1.02,0.14 -1.47,0.39 -9.76,5.54 -17.53,14.33 -24.91,23.31 -10.71,13.01 -21.86,26.65 -33.44,40.91 -4.37,5.38 -7.9,9.46 -10.56,12.24 -5.43,5.67 -9.83,10.88 -15.08,15.39 -9.57,8.23 -19.57,16.01 -29.98,23.31 -14.73,10.32 -29.07,20.29 -43.04,29.9 -5.22,3.61 -13.68,9.81 -20.14,15.41 -25.71,22.32 -53.59,46.12 -83.65,71.41 -9.46,7.95 -19.65,16.88 -34.02,29.22 -25.66,22.03 -52.94,40.06 -81.67,55.65 -7.71,4.19 -14.15,8.2 -19.32,12.01 -19.3,14.23 -33.84,25.65 -43.62,34.28 -25.99,22.91 -43.04,37.82 -51.16,44.73 -9.19,7.8 -18.6,17.05 -28.42,25.54 -2.71,2.35 -5.7,3.03 -8.96,2.01 -0.78,-0.24 -1.25,-1.02 -1.1,-1.82 0.36,-2 1.19,-4.1 2.47,-6.32 6.86,-11.81 14.46,-23.09 19.95,-36.03 3.48,-8.23 7.87,-16.52 13.18,-24.89 2.03,-3.19 4.73,-8.77 8.11,-16.74 2.98,-7.02 7.34,-15.05 13.07,-24.12 5.79,-9.14 16,-23.36 30.63,-42.67 7.66,-10.11 19.49,-23.6 35.49,-40.47 4.9,-5.16 12.21,-11.87 21.92,-20.14 12.12,-10.31 23.53,-21.19 34.23,-32.65 11.73,-12.54 16.99,-22.33 27.39,-40.8 2.37,-4.19 6.49,-9.43 12.37,-15.71 8.27,-8.82 17,-17.23 26.21,-25.23 30.11,-26.18 55.17,-47.43 75.17,-63.76 8.66,-7.08 26.42,-21.39 39.65,-30.77 17.11,-12.13 28.62,-20.44 34.53,-24.91 4.5,-3.4 8.93,-6.6 13.3,-10.56 26.03,-23.54 51.66,-45.71 77.28,-70.7 0.42,-0.41 0.51,-1.06 0.21,-1.58 -6.8,-11.78 -12.84,-21.8 -18.11,-30.06 -10.22,-15.99 -22.07,-29.65 -35.57,-40.99 -7.56,-6.36 -18.41,-13.85 -28.65,-20.43 -15.08,-9.66 -30.62,-21.97 -46.63,-36.9 -35.08,-32.73 -67.65,-71.22 -85.32,-115.42 -5.53,-13.85 -10.8,-29.31 -15.8,-46.37 -5.89,-20.13 -12.37,-35.63 -23.22,-51.27 -8.93,-12.9 -15.77,-21.94 -19.58,-35.93 -1.27,-4.67 -2.93,-12.75 -4.99,-24.23 -2.07,-11.54 -6.54,-22.62 -13.41,-33.25 -7.54,-11.68 -13.66,-21.04 -18.33,-28.08 -3.68,-5.53 -7.02,-12.39 -9.63,-18.53 -3.9,-9.18 -8.14,-15.7 -13.6,-23.37 -3.94,-5.53 -5.07,-12.75 0,-18.32 4.14,-4.57 17.49,-3.02 21.56,-1.13 3.86,1.81 8.1,5.13 12.71,9.94 16.16,16.88 26.41,27.77 30.74,32.66 4.69,5.31 11.21,13.79 16.69,19.94 20.19,22.63 36.17,39.74 47.36,59.71 10.46,18.66 16.41,30.42 29.84,44.67 9.32,9.92 17.94,19.33 25.85,28.23 9.01,10.15 19.25,22.95 30.72,38.39 7.54,10.17 13.89,20.11 19.05,29.84 6.39,12.05 10.8,30.19 15.13,41.41 4.88,12.67 12.52,23.25 22.92,31.75 0.58,0.47 6.79,5.44 18.62,14.89 13.54,10.82 23.74,23.47 30.61,37.96 4.55,9.58 7.82,16.16 9.8,19.74 6.62,11.85 14.64,22.05 24.07,30.59 8.99,8.14 17.47,13.2 31.06,22.64 4.28,2.96 6.68,5.98 10.65,2.54 7.08,-6.11 13.73,-10.71 17.96,-14.53 6.12,-5.54 11.71,-11.84 16.79,-18.92 3.5,-4.88 8.77,-10.16 15.19,-14.42 22.77,-15.02 38.17,-31.11 63.32,-55.15 22.13,-21.17 46.22,-47.56 69.25,-66.8 32.17,-26.89 54.99,-45.9 68.46,-57.01 17.15,-14.15 35.82,-30.97 56.02,-50.46 16.06,-15.5 29.25,-27.72 39.57,-36.66 9.78,-8.47 17.55,-14.8 23.31,-18.98 8.52,-6.2 18.55,-10.61 30.56,-15.03 12.34,-4.55 23.44,-11.06 35.67,-17.61 9.07,-4.85 19.76,-9.89 30.05,-8.84 0.5,0.06 0.97,0.32 1.3,0.72 0.85,1.07 1.01,2.48 0.48,4.23 -2.1,6.99 -5.15,13.55 -9.66,20.87 -6.42,10.42 -11.51,19.46 -15.29,27.11 -6.09,12.35 -9.66,19.49 -10.69,21.43 -7.78,14.65 -17.56,27.97 -29.34,39.97 -4.8,4.89 -12.93,12.92 -24.37,24.07 -14.23,13.87 -25.02,30.77 -37.12,50.78 -15.21,25.13 -29.56,48.47 -43.06,70.01 -5.21,8.29 -13.68,15.13 -21.58,21.47 -25.71,20.7 -46.75,41.48 -70.98,64.67 -1.97,1.88 -4.98,4.47 -9.03,7.76 -22.62,18.36 -45.88,35.93 -69.78,52.74 -5.96,4.2 -13.77,11.24 -23.42,21.11 -17.12,17.5 -25.93,26.56 -26.42,27.19 -1.22,1.54 -1.08,3.09 0.41,4.67 14.11,14.81 34.25,37.65 60.42,68.51 11.89,14.01 24.87,27.08 36.03,39.46 8.75,9.7 16.81,22.11 31.82,42.59 2.69,3.68 13.53,16.07 32.5,37.17 5.17,5.76 11.64,14.47 19.4,26.12 16.37,24.6 36.28,56.2 59.73,94.79 4.2,6.92 7.74,12.33 10.62,16.21 5.41,7.29 10.37,13.74 14.92,20.97 6.26,9.94 11.3,19.92 15.11,29.92 4.29,11.27 7.73,19.49 10.32,24.69 7.21,14.5 14.81,28.41 22.8,41.73 3.44,5.75 6.78,13.03 6.11,20.05 -0.07,0.76 -0.71,1.34 -1.48,1.34 -0.25,0 -0.49,-0.06 -0.71,-0.18l0 0.01z"/></svg>`, aicodemirror: `<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" style="flex:none;line-height:1" viewBox="0 0 1017.97 1056.47"><title>AICodeMirror</title><path fill="#E4906E" fill-rule="nonzero" d="M944.92 1014.53c-17.29,-9.23 -33.98,-19.28 -50.08,-30.16 -5.39,-3.65 -14.99,-11.7 -28.81,-24.16 -6.06,-5.47 -14.07,-13.51 -24.03,-24.13 -15.15,-16.17 -29.61,-29.9 -41.69,-40.4 -3.98,-3.46 -14.2,-11.02 -30.68,-22.69 -6.24,-4.42 -12.88,-12.15 -18.63,-19.09 -23.98,-29.04 -49.53,-58.44 -76.66,-88.19 -11.93,-13.1 -25.64,-26.11 -35.61,-36.5 -28.72,-29.92 -51.92,-51.96 -78.23,-79.66 -11.24,-11.83 -20.52,-21.3 -27.85,-28.41 -0.56,-0.53 -1.3,-0.84 -2.08,-0.84 -0.51,0 -1.02,0.14 -1.47,0.39 -9.76,5.54 -17.53,14.33 -24.91,23.31 -10.71,13.01 -21.86,26.65 -33.44,40.91 -4.37,5.38 -7.9,9.46 -10.56,12.24 -5.43,5.67 -9.83,10.88 -15.08,15.39 -9.57,8.23 -19.57,16.01 -29.98,23.31 -14.73,10.32 -29.07,20.29 -43.04,29.9 -5.22,3.61 -13.68,9.81 -20.14,15.41 -25.71,22.32 -53.59,46.12 -83.65,71.41 -9.46,7.95 -19.65,16.88 -34.02,29.22 -25.66,22.03 -52.94,40.06 -81.67,55.65 -7.71,4.19 -14.15,8.2 -19.32,12.01 -19.3,14.23 -33.84,25.65 -43.62,34.28 -25.99,22.91 -43.04,37.82 -51.16,44.73 -9.19,7.8 -18.6,17.05 -28.42,25.54 -2.71,2.35 -5.7,3.03 -8.96,2.01 -0.78,-0.24 -1.25,-1.02 -1.1,-1.82 0.36,-2 1.19,-4.1 2.47,-6.32 6.86,-11.81 14.46,-23.09 19.95,-36.03 3.48,-8.23 7.87,-16.52 13.18,-24.89 2.03,-3.19 4.73,-8.77 8.11,-16.74 2.98,-7.02 7.34,-15.05 13.07,-24.12 5.79,-9.14 16,-23.36 30.63,-42.67 7.66,-10.11 19.49,-23.6 35.49,-40.47 4.9,-5.16 12.21,-11.87 21.92,-20.14 12.12,-10.31 23.53,-21.19 34.23,-32.65 11.73,-12.54 16.99,-22.33 27.39,-40.8 2.37,-4.19 6.49,-9.43 12.37,-15.71 8.27,-8.82 17,-17.23 26.21,-25.23 30.11,-26.18 55.17,-47.43 75.17,-63.76 8.66,-7.08 26.42,-21.39 39.65,-30.77 17.11,-12.13 28.62,-20.44 34.53,-24.91 4.5,-3.4 8.93,-6.6 13.3,-10.56 26.03,-23.54 51.66,-45.71 77.28,-70.7 0.42,-0.41 0.51,-1.06 0.21,-1.58 -6.8,-11.78 -12.84,-21.8 -18.11,-30.06 -10.22,-15.99 -22.07,-29.65 -35.57,-40.99 -7.56,-6.36 -18.41,-13.85 -28.65,-20.43 -15.08,-9.66 -30.62,-21.97 -46.63,-36.9 -35.08,-32.73 -67.65,-71.22 -85.32,-115.42 -5.53,-13.85 -10.8,-29.31 -15.8,-46.37 -5.89,-20.13 -12.37,-35.63 -23.22,-51.27 -8.93,-12.9 -15.77,-21.94 -19.58,-35.93 -1.27,-4.67 -2.93,-12.75 -4.99,-24.23 -2.07,-11.54 -6.54,-22.62 -13.41,-33.25 -7.54,-11.68 -13.66,-21.04 -18.33,-28.08 -3.68,-5.53 -7.02,-12.39 -9.63,-18.53 -3.9,-9.18 -8.14,-15.7 -13.6,-23.37 -3.94,-5.53 -5.07,-12.75 0,-18.32 4.14,-4.57 17.49,-3.02 21.56,-1.13 3.86,1.81 8.1,5.13 12.71,9.94 16.16,16.88 26.41,27.77 30.74,32.66 4.69,5.31 11.21,13.79 16.69,19.94 20.19,22.63 36.17,39.74 47.36,59.71 10.46,18.66 16.41,30.42 29.84,44.67 9.32,9.92 17.94,19.33 25.85,28.23 9.01,10.15 19.25,22.95 30.72,38.39 7.54,10.17 13.89,20.11 19.05,29.84 6.39,12.05 10.8,30.19 15.13,41.41 4.88,12.67 12.52,23.25 22.92,31.75 0.58,0.47 6.79,5.44 18.62,14.89 13.54,10.82 23.74,23.47 30.61,37.96 4.55,9.58 7.82,16.16 9.8,19.74 6.62,11.85 14.64,22.05 24.07,30.59 8.99,8.14 17.47,13.2 31.06,22.64 4.28,2.96 6.68,5.98 10.65,2.54 7.08,-6.11 13.73,-10.71 17.96,-14.53 6.12,-5.54 11.71,-11.84 16.79,-18.92 3.5,-4.88 8.77,-10.16 15.19,-14.42 22.77,-15.02 38.17,-31.11 63.32,-55.15 22.13,-21.17 46.22,-47.56 69.25,-66.8 32.17,-26.89 54.99,-45.9 68.46,-57.01 17.15,-14.15 35.82,-30.97 56.02,-50.46 16.06,-15.5 29.25,-27.72 39.57,-36.66 9.78,-8.47 17.55,-14.8 23.31,-18.98 8.52,-6.2 18.55,-10.61 30.56,-15.03 12.34,-4.55 23.44,-11.06 35.67,-17.61 9.07,-4.85 19.76,-9.89 30.05,-8.84 0.5,0.06 0.97,0.32 1.3,0.72 0.85,1.07 1.01,2.48 0.48,4.23 -2.1,6.99 -5.15,13.55 -9.66,20.87 -6.42,10.42 -11.51,19.46 -15.29,27.11 -6.09,12.35 -9.66,19.49 -10.69,21.43 -7.78,14.65 -17.56,27.97 -29.34,39.97 -4.8,4.89 -12.93,12.92 -24.37,24.07 -14.23,13.87 -25.02,30.77 -37.12,50.78 -15.21,25.13 -29.56,48.47 -43.06,70.01 -5.21,8.29 -13.68,15.13 -21.58,21.47 -25.71,20.7 -46.75,41.48 -70.98,64.67 -1.97,1.88 -4.98,4.47 -9.03,7.76 -22.62,18.36 -45.88,35.93 -69.78,52.74 -5.96,4.2 -13.77,11.24 -23.42,21.11 -17.12,17.5 -25.93,26.56 -26.42,27.19 -1.22,1.54 -1.08,3.09 0.41,4.67 14.11,14.81 34.25,37.65 60.42,68.51 11.89,14.01 24.87,27.08 36.03,39.46 8.75,9.7 16.81,22.11 31.82,42.59 2.69,3.68 13.53,16.07 32.5,37.17 5.17,5.76 11.64,14.47 19.4,26.12 16.37,24.6 36.28,56.2 59.73,94.79 4.2,6.92 7.74,12.33 10.62,16.21 5.41,7.29 10.37,13.74 14.92,20.97 6.26,9.94 11.3,19.92 15.11,29.92 4.29,11.27 7.73,19.49 10.32,24.69 7.21,14.5 14.81,28.41 22.8,41.73 3.44,5.75 6.78,13.03 6.11,20.05 -0.07,0.76 -0.71,1.34 -1.48,1.34 -0.25,0 -0.49,-0.06 -0.71,-0.18l0 0.01z"/></svg>`,
@@ -83,6 +84,7 @@ export const iconUrls: Record<string, string> = {
eflowcode: _eflowcode, eflowcode: _eflowcode,
pipellm: _pipellm, pipellm: _pipellm,
shengsuanyun: _shengsuanyun, shengsuanyun: _shengsuanyun,
xcode: _xcode,
}; };
export const iconList = [ export const iconList = [
+7
View File
@@ -345,6 +345,13 @@ export const iconMetadata: Record<string, IconMetadata> = {
keywords: [], keywords: [],
defaultColor: "currentColor", defaultColor: "currentColor",
}, },
xcode: {
name: "xcode",
displayName: "Xcode",
category: "tool",
keywords: ["apple", "xcode", "ide"],
defaultColor: "currentColor",
},
zhipu: { zhipu: {
name: "zhipu", name: "zhipu",
displayName: "Zhipu AI", displayName: "Zhipu AI",
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 286 KiB

+4 -12
View File
@@ -63,20 +63,12 @@ export const usageApi = {
return invoke("get_usage_trends", { startDate, endDate, appType }); return invoke("get_usage_trends", { startDate, endDate, appType });
}, },
getProviderStats: async ( getProviderStats: async (appType?: string): Promise<ProviderStats[]> => {
startDate?: number, return invoke("get_provider_stats", { appType });
endDate?: number,
appType?: string,
): Promise<ProviderStats[]> => {
return invoke("get_provider_stats", { startDate, endDate, appType });
}, },
getModelStats: async ( getModelStats: async (appType?: string): Promise<ModelStats[]> => {
startDate?: number, return invoke("get_model_stats", { appType });
endDate?: number,
appType?: string,
): Promise<ModelStats[]> => {
return invoke("get_model_stats", { startDate, endDate, appType });
}, },
getRequestLogs: async ( getRequestLogs: async (
+55 -112
View File
@@ -1,7 +1,6 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { usageApi } from "@/lib/api/usage"; import { usageApi } from "@/lib/api/usage";
import { resolveUsageRange } from "@/lib/usageRange"; import type { LogFilters } from "@/types/usage";
import type { LogFilters, UsageRangeSelection } from "@/types/usage";
const DEFAULT_REFETCH_INTERVAL_MS = 30000; const DEFAULT_REFETCH_INTERVAL_MS = 30000;
@@ -10,94 +9,51 @@ type UsageQueryOptions = {
refetchIntervalInBackground?: boolean; refetchIntervalInBackground?: boolean;
}; };
type RequestLogsTimeMode = "rolling" | "fixed";
type RequestLogsQueryArgs = { type RequestLogsQueryArgs = {
filters: LogFilters; filters: LogFilters;
range: UsageRangeSelection; timeMode: RequestLogsTimeMode;
page?: number; page?: number;
pageSize?: number; pageSize?: number;
rollingWindowSeconds?: number;
options?: UsageQueryOptions; options?: UsageQueryOptions;
}; };
type RequestLogsKey = { type RequestLogsKey = {
preset: UsageRangeSelection["preset"]; timeMode: RequestLogsTimeMode;
customStartDate?: number; rollingWindowSeconds?: number;
customEndDate?: number;
appType?: string; appType?: string;
providerName?: string; providerName?: string;
model?: string; model?: string;
statusCode?: number; statusCode?: number;
startDate?: number;
endDate?: number;
}; };
// Query keys // Query keys
export const usageKeys = { export const usageKeys = {
all: ["usage"] as const, all: ["usage"] as const,
summary: ( summary: (days: number, appType?: string) =>
preset: UsageRangeSelection["preset"], [...usageKeys.all, "summary", days, appType ?? "all"] as const,
customStartDate: number | undefined, trends: (days: number, appType?: string) =>
customEndDate: number | undefined, [...usageKeys.all, "trends", days, appType ?? "all"] as const,
appType?: string, providerStats: (appType?: string) =>
) => [...usageKeys.all, "provider-stats", appType ?? "all"] as const,
[ modelStats: (appType?: string) =>
...usageKeys.all, [...usageKeys.all, "model-stats", appType ?? "all"] as const,
"summary",
preset,
customStartDate ?? 0,
customEndDate ?? 0,
appType ?? "all",
] as const,
trends: (
preset: UsageRangeSelection["preset"],
customStartDate: number | undefined,
customEndDate: number | undefined,
appType?: string,
) =>
[
...usageKeys.all,
"trends",
preset,
customStartDate ?? 0,
customEndDate ?? 0,
appType ?? "all",
] as const,
providerStats: (
preset: UsageRangeSelection["preset"],
customStartDate: number | undefined,
customEndDate: number | undefined,
appType?: string,
) =>
[
...usageKeys.all,
"provider-stats",
preset,
customStartDate ?? 0,
customEndDate ?? 0,
appType ?? "all",
] as const,
modelStats: (
preset: UsageRangeSelection["preset"],
customStartDate: number | undefined,
customEndDate: number | undefined,
appType?: string,
) =>
[
...usageKeys.all,
"model-stats",
preset,
customStartDate ?? 0,
customEndDate ?? 0,
appType ?? "all",
] as const,
logs: (key: RequestLogsKey, page: number, pageSize: number) => logs: (key: RequestLogsKey, page: number, pageSize: number) =>
[ [
...usageKeys.all, ...usageKeys.all,
"logs", "logs",
key.preset, key.timeMode,
key.customStartDate ?? 0, key.rollingWindowSeconds ?? 0,
key.customEndDate ?? 0,
key.appType ?? "", key.appType ?? "",
key.providerName ?? "", key.providerName ?? "",
key.model ?? "", key.model ?? "",
key.statusCode ?? -1, key.statusCode ?? -1,
key.startDate ?? 0,
key.endDate ?? 0,
page, page,
pageSize, pageSize,
] as const, ] as const,
@@ -108,22 +64,23 @@ export const usageKeys = {
[...usageKeys.all, "limits", providerId, appType] as const, [...usageKeys.all, "limits", providerId, appType] as const,
}; };
const getWindow = (days: number) => {
const endDate = Math.floor(Date.now() / 1000);
const startDate = endDate - days * 24 * 60 * 60;
return { startDate, endDate };
};
// Hooks // Hooks
export function useUsageSummary( export function useUsageSummary(
range: UsageRangeSelection, days: number,
appType?: string, appType?: string,
options?: UsageQueryOptions, options?: UsageQueryOptions,
) { ) {
const effectiveAppType = appType === "all" ? undefined : appType; const effectiveAppType = appType === "all" ? undefined : appType;
return useQuery({ return useQuery({
queryKey: usageKeys.summary( queryKey: usageKeys.summary(days, appType),
range.preset,
range.customStartDate,
range.customEndDate,
appType,
),
queryFn: () => { queryFn: () => {
const { startDate, endDate } = resolveUsageRange(range); const { startDate, endDate } = getWindow(days);
return usageApi.getUsageSummary(startDate, endDate, effectiveAppType); return usageApi.getUsageSummary(startDate, endDate, effectiveAppType);
}, },
refetchInterval: options?.refetchInterval ?? DEFAULT_REFETCH_INTERVAL_MS, refetchInterval: options?.refetchInterval ?? DEFAULT_REFETCH_INTERVAL_MS,
@@ -132,20 +89,15 @@ export function useUsageSummary(
} }
export function useUsageTrends( export function useUsageTrends(
range: UsageRangeSelection, days: number,
appType?: string, appType?: string,
options?: UsageQueryOptions, options?: UsageQueryOptions,
) { ) {
const effectiveAppType = appType === "all" ? undefined : appType; const effectiveAppType = appType === "all" ? undefined : appType;
return useQuery({ return useQuery({
queryKey: usageKeys.trends( queryKey: usageKeys.trends(days, appType),
range.preset,
range.customStartDate,
range.customEndDate,
appType,
),
queryFn: () => { queryFn: () => {
const { startDate, endDate } = resolveUsageRange(range); const { startDate, endDate } = getWindow(days);
return usageApi.getUsageTrends(startDate, endDate, effectiveAppType); return usageApi.getUsageTrends(startDate, endDate, effectiveAppType);
}, },
refetchInterval: options?.refetchInterval ?? DEFAULT_REFETCH_INTERVAL_MS, refetchInterval: options?.refetchInterval ?? DEFAULT_REFETCH_INTERVAL_MS,
@@ -154,70 +106,61 @@ export function useUsageTrends(
} }
export function useProviderStats( export function useProviderStats(
range: UsageRangeSelection,
appType?: string, appType?: string,
options?: UsageQueryOptions, options?: UsageQueryOptions,
) { ) {
const effectiveAppType = appType === "all" ? undefined : appType; const effectiveAppType = appType === "all" ? undefined : appType;
return useQuery({ return useQuery({
queryKey: usageKeys.providerStats( queryKey: usageKeys.providerStats(appType),
range.preset, queryFn: () => usageApi.getProviderStats(effectiveAppType),
range.customStartDate,
range.customEndDate,
appType,
),
queryFn: () => {
const { startDate, endDate } = resolveUsageRange(range);
return usageApi.getProviderStats(startDate, endDate, effectiveAppType);
},
refetchInterval: options?.refetchInterval ?? DEFAULT_REFETCH_INTERVAL_MS, refetchInterval: options?.refetchInterval ?? DEFAULT_REFETCH_INTERVAL_MS,
refetchIntervalInBackground: options?.refetchIntervalInBackground ?? false, refetchIntervalInBackground: options?.refetchIntervalInBackground ?? false,
}); });
} }
export function useModelStats( export function useModelStats(appType?: string, options?: UsageQueryOptions) {
range: UsageRangeSelection,
appType?: string,
options?: UsageQueryOptions,
) {
const effectiveAppType = appType === "all" ? undefined : appType; const effectiveAppType = appType === "all" ? undefined : appType;
return useQuery({ return useQuery({
queryKey: usageKeys.modelStats( queryKey: usageKeys.modelStats(appType),
range.preset, queryFn: () => usageApi.getModelStats(effectiveAppType),
range.customStartDate,
range.customEndDate,
appType,
),
queryFn: () => {
const { startDate, endDate } = resolveUsageRange(range);
return usageApi.getModelStats(startDate, endDate, effectiveAppType);
},
refetchInterval: options?.refetchInterval ?? DEFAULT_REFETCH_INTERVAL_MS, refetchInterval: options?.refetchInterval ?? DEFAULT_REFETCH_INTERVAL_MS,
refetchIntervalInBackground: options?.refetchIntervalInBackground ?? false, refetchIntervalInBackground: options?.refetchIntervalInBackground ?? false,
}); });
} }
const getRollingRange = (windowSeconds: number) => {
const endDate = Math.floor(Date.now() / 1000);
const startDate = endDate - windowSeconds;
return { startDate, endDate };
};
export function useRequestLogs({ export function useRequestLogs({
filters, filters,
range, timeMode,
page = 0, page = 0,
pageSize = 20, pageSize = 20,
rollingWindowSeconds = 24 * 60 * 60,
options, options,
}: RequestLogsQueryArgs) { }: RequestLogsQueryArgs) {
const key: RequestLogsKey = { const key: RequestLogsKey = {
preset: range.preset, timeMode,
customStartDate: range.customStartDate, rollingWindowSeconds:
customEndDate: range.customEndDate, timeMode === "rolling" ? rollingWindowSeconds : undefined,
appType: filters.appType, appType: filters.appType,
providerName: filters.providerName, providerName: filters.providerName,
model: filters.model, model: filters.model,
statusCode: filters.statusCode, statusCode: filters.statusCode,
startDate: timeMode === "fixed" ? filters.startDate : undefined,
endDate: timeMode === "fixed" ? filters.endDate : undefined,
}; };
return useQuery({ return useQuery({
queryKey: usageKeys.logs(key, page, pageSize), queryKey: usageKeys.logs(key, page, pageSize),
queryFn: () => { queryFn: () => {
const effectiveFilters = { ...filters, ...resolveUsageRange(range) }; const effectiveFilters =
timeMode === "rolling"
? { ...filters, ...getRollingRange(rollingWindowSeconds) }
: filters;
return usageApi.getRequestLogs(effectiveFilters, page, pageSize); return usageApi.getRequestLogs(effectiveFilters, page, pageSize);
}, },
refetchInterval: options?.refetchInterval ?? DEFAULT_REFETCH_INTERVAL_MS, // 每30秒自动刷新 refetchInterval: options?.refetchInterval ?? DEFAULT_REFETCH_INTERVAL_MS, // 每30秒自动刷新
-84
View File
@@ -1,84 +0,0 @@
import type { UsageRangePreset, UsageRangeSelection } from "@/types/usage";
const DAY_SECONDS = 24 * 60 * 60;
const DAY_MS = DAY_SECONDS * 1000;
export const MAX_CUSTOM_USAGE_RANGE_SECONDS = 30 * DAY_SECONDS;
export interface ResolvedUsageRange {
startDate: number;
endDate: number;
}
function getStartOfLocalDayDate(nowMs: number): Date {
const date = new Date(nowMs);
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}
function getPresetLookbackStart(
preset: Exclude<UsageRangePreset, "today" | "1d" | "custom">,
nowMs: number,
): number {
const dayCount = preset === "7d" ? 7 : preset === "14d" ? 14 : 30;
return Math.floor(
getStartOfLocalDayDate(nowMs - (dayCount - 1) * DAY_MS).getTime() / 1000,
);
}
export function resolveUsageRange(
selection: UsageRangeSelection,
nowMs: number = Date.now(),
): ResolvedUsageRange {
const endDate = Math.floor(nowMs / 1000);
switch (selection.preset) {
case "today":
return {
startDate: Math.floor(getStartOfLocalDayDate(nowMs).getTime() / 1000),
endDate,
};
case "1d":
return {
startDate: endDate - DAY_SECONDS,
endDate,
};
case "7d":
case "14d":
case "30d":
return {
startDate: getPresetLookbackStart(selection.preset, nowMs),
endDate,
};
case "custom": {
const startDate = selection.customStartDate ?? endDate - DAY_SECONDS;
const customEndDate = selection.customEndDate ?? endDate;
return {
startDate,
endDate: customEndDate,
};
}
}
}
export function timestampToLocalDatetime(timestamp: number): string {
const date = new Date(timestamp * 1000);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
return `${year}-${month}-${day}T${hours}:${minutes}`;
}
export function localDatetimeToTimestamp(datetime: string): number | undefined {
if (!datetime || datetime.length < 16) {
return undefined;
}
const timestamp = new Date(datetime).getTime();
if (Number.isNaN(timestamp)) {
return undefined;
}
return Math.floor(timestamp / 1000);
}
+19 -3
View File
@@ -109,6 +109,22 @@ export interface ProviderTestConfig {
maxRetries?: number; maxRetries?: number;
} }
// 供应商单独的代理配置
export interface ProviderProxyConfig {
// 是否启用单独配置(false 时使用全局/系统代理)
enabled: boolean;
// 代理类型:http, https, socks5
proxyType?: "http" | "https" | "socks5";
// 代理主机
proxyHost?: string;
// 代理端口
proxyPort?: number;
// 代理用户名(可选)
proxyUsername?: string;
// 代理密码(可选)
proxyPassword?: string;
}
export type AuthBindingSource = "provider_config" | "managed_account"; export type AuthBindingSource = "provider_config" | "managed_account";
export interface AuthBinding { export interface AuthBinding {
@@ -133,6 +149,8 @@ export interface ProviderMeta {
partnerPromotionKey?: string; partnerPromotionKey?: string;
// 供应商单独的模型测试配置 // 供应商单独的模型测试配置
testConfig?: ProviderTestConfig; testConfig?: ProviderTestConfig;
// 供应商单独的代理配置
proxyConfig?: ProviderProxyConfig;
// 供应商成本倍率 // 供应商成本倍率
costMultiplier?: string; costMultiplier?: string;
// 供应商计费模式来源 // 供应商计费模式来源
@@ -148,7 +166,7 @@ export interface ProviderMeta {
apiKeyField?: ClaudeApiKeyField; apiKeyField?: ClaudeApiKeyField;
// 是否将 base_url 视为完整 API 端点(代理直接使用此 URL,不拼接路径) // 是否将 base_url 视为完整 API 端点(代理直接使用此 URL,不拼接路径)
isFullUrl?: boolean; isFullUrl?: boolean;
// Prompt cache key for OpenAI Responses-compatible endpoints (improves cache hit rate) // Prompt cache key for OpenAI-compatible endpoints (improves cache hit rate)
promptCacheKey?: string; promptCacheKey?: string;
// 供应商类型(用于识别 Copilot 等特殊供应商) // 供应商类型(用于识别 Copilot 等特殊供应商)
providerType?: string; providerType?: string;
@@ -226,8 +244,6 @@ export interface Settings {
showInTray: boolean; showInTray: boolean;
// 点击关闭按钮时是否最小化到托盘而不是关闭应用 // 点击关闭按钮时是否最小化到托盘而不是关闭应用
minimizeToTrayOnClose: boolean; minimizeToTrayOnClose: boolean;
// 是否启用应用级窗口控制按钮(最小化/最大化/关闭)
useAppWindowControls?: boolean;
// 启用 Claude 插件联动(写入 ~/.claude/config.json 的 primaryApiKey // 启用 Claude 插件联动(写入 ~/.claude/config.json 的 primaryApiKey
enableClaudePluginIntegration?: boolean; enableClaudePluginIntegration?: boolean;
// 跳过 Claude Code 初次安装确认(写入 ~/.claude.json 的 hasCompletedOnboarding // 跳过 Claude Code 初次安装确认(写入 ~/.claude.json 的 hasCompletedOnboarding
+2 -8
View File
@@ -121,18 +121,12 @@ export interface ProviderLimitStatus {
monthlyExceeded: boolean; monthlyExceeded: boolean;
} }
export type UsageRangePreset = "today" | "1d" | "7d" | "14d" | "30d" | "custom"; export type TimeRange = "1d" | "7d" | "30d";
export interface UsageRangeSelection {
preset: UsageRangePreset;
customStartDate?: number;
customEndDate?: number;
}
export type AppTypeFilter = "all" | "claude" | "codex" | "gemini"; export type AppTypeFilter = "all" | "claude" | "codex" | "gemini";
export interface StatsFilters { export interface StatsFilters {
timeRange: UsageRangePreset; timeRange: TimeRange;
providerId?: string; providerId?: string;
appType?: string; appType?: string;
} }