Compare commits

...

14 Commits

Author SHA1 Message Date
Jason c002688a84 chore(release): bump version to 3.14.1
- Add v3.14.1 release notes (en/zh/ja) covering tray usage visibility,
  Codex OAuth stability fixes, Skills import/install reliability, and
  removal of the Hermes config health scanner
- Cut [Unreleased] into [3.14.1] in CHANGELOG with PR references
- Bump version in package.json, Cargo.toml, Cargo.lock, tauri.conf.json
2026-04-23 21:17:30 +08:00
Jason 4737158439 feat(tray): show coding-plan usage for Kimi / Zhipu / MiniMax
dc04165f surfaced tray usage badges for Claude/Codex/Gemini official
OAuth only. Chinese coding-plan providers already expose 5h + weekly
windows through coding_plan::get_coding_plan_quota, but two gaps kept
the tray from rendering them.

- format_script_summary read only data.first(), truncating the tier-
  flattened UsageResult to a single window. Detect plan_name matching
  TIER_FIVE_HOUR / TIER_WEEKLY_LIMIT and emit the "🟢 h12% w80%" layout
  used by format_subscription_summary; worst utilization drives the
  emoji. Copilot / balance / custom scripts keep the legacy single-
  bucket output via fallback.

- usage_script previously required manual activation through
  UsageScriptModal. Auto-inject meta.usage_script on Claude provider
  creation when ANTHROPIC_BASE_URL matches a known coding plan, so the
  tray lights up without the user opening the modal. Does not overwrite
  existing usage_script on update.

Extract the URL route table out of UsageScriptModal into a shared
codingPlanProviders module so the modal, the creation hook, and the
Rust coding_plan::detect_provider mirror all agree on one list.
Add TIER_WEEKLY_LIMIT alongside TIER_FIVE_HOUR and a createUsageScript()
factory to collapse the duplicated default fields across four call
sites and drop the remaining stringly-typed tier names.
2026-04-23 17:34:39 +08:00
Jason cdcc423122 refactor(hermes): drop config health check scanner
The Hermes config.yaml schema has stabilized and users have migrated to
the current provider fields, so the value of scanning for model.provider
dangling references, custom_providers shape errors, v12 migration residue
etc. no longer justifies the maintenance surface — and the scan produces
false positives when users keep some providers under Hermes' v12+
providers: dict (Hermes' runtime merges both shapes, but CC Switch's
scanner only looked at the list form).

Removes the whole HermesHealthWarning type, scan_hermes_config_health
command, HermesHealthBanner React component, useHermesHealth hook,
warnings field on HermesWriteOutcome, and the three helper functions
(yaml_as_non_empty_str, collect_mapping_string_keys, hermes_warning)
that only served the scanner. Drops the matching i18n keys in
zh/en/ja and the fixInWebUI button label that only the banner used.
2026-04-23 16:18:38 +08:00
涂瑜 dc04165f18 feat(tray): show cached provider usage in the system tray menu (#2184)
* feat: add Rust-side write-through usage cache

Introduce an in-memory UsageCache on AppState that the existing usage
query commands populate on success. The cache is read-only to the rest
of the app today; the next commit consumes it from the tray menu.

- New services::usage_cache module with split maps: subscription keyed
  by AppType, script keyed by (AppType, provider_id).
- AppType gains Eq + Hash so it can be used as a HashMap key.
- commands::subscription::get_subscription_quota now takes State<AppState>
  and writes through on success (signature change is invisible to the
  frontend — Tauri injects State automatically).
- commands::provider::queryProviderUsage body extracted into an inner
  async fn; the public command wraps it with write-through, covering
  Copilot, coding-plan, balance, and generic script paths uniformly.

Cache is in-memory only; auto-query interval and the upcoming tray
refresh action rebuild it after restarts.

* feat(tray): surface cached usage in the system tray menu

Read UsageCache populated by the previous commit and render it in three
places, scoped to whatever TRAY_SECTIONS covers (Claude/Codex/Gemini):

1. Inline suffix on each provider submenu item
   "AnyProvider  · 🟢 5h 18% / 7d 23%"
2. Disabled summary row per visible app under "Show Main"
   "Claude · Anthropic Official · 🟢 5h 18% / 7d 23%"
3. "Refresh all usage" menu item that triggers get_subscription_quota +
   queryProviderUsage for every applicable provider, then rebuilds the
   tray menu via the existing refresh_tray_menu path.

Color encoding uses emoji (🟢 <70% / 🟠 70-89% / 🔴 ≥90%) since Tauri 2
tray labels are plain text. Missing cache entry leaves the label
unchanged — tray never issues network requests when opened. Three new
i18n-ready strings live in TrayTexts (en/zh/ja), following the existing
pattern for tray text.

Closes #2178.

* feat(usage): bridge tray UsageCache writes to frontend React Query

Why: tray hover triggers backend-only refresh that wrote to UsageCache but
never notified the frontend, leaving main UI stale while tray showed fresh
numbers. Emit a payload-carrying event after each cache write so React Query
can setQueryData directly, keeping both views in sync without duplicate fetches.

* fix(tray): skip hidden apps on hover refresh and drop stale disabled-script cache

Address P2 findings from automated review on #2184:

1. refresh_all_usage_in_tray now filters TRAY_SECTIONS by settings.visible_apps
   before scheduling subscription/script queries, matching create_tray_menu and
   preventing wasted external API calls (and rate-limit/auth-error log noise)
   for apps the user has hidden.

2. format_usage_suffix only trusts the script cache when provider.meta.usage_script
   is still enabled; when a script is disabled/removed the cached suffix is now
   invalidated so the tray label no longer shows stale data indefinitely.

* refactor: consolidate codex provider helpers and fix test semantics

- Add Provider::is_codex_oauth() and Provider::codex_fast_mode_enabled()
  to eliminate duplicated meta extraction in claude.rs and stream_check.rs
- Fix non-codex-oauth tests to pass codex_fast_mode=false (was true, harmless
  but semantically misleading)
- Remove redundant is_dir() guard after resolve_skill_source_dir already
  guarantees the returned path is a directory

* style: apply cargo fmt

* fix(tray): reflect failed refreshes in cache and support Gemini flash-lite

Follow-up to the tray usage-display feature addressing review feedback:

- Write snapshots for both Ok(success:false) and Err paths in
  queryProviderUsage / get_subscription_quota so stale success data
  no longer persists across failed refreshes; the original Err is
  still returned to the frontend onError handler.
- Include gemini_flash_lite tier in the tray summary with label "l".
  Matches the frontend SubscriptionQuotaFooter and keeps the worst
  emoji correct when lite is the highest utilization.
- Add TIER_GEMINI_PRO / _FLASH / _FLASH_LITE constants in
  services/subscription.rs and reuse them in classify_gemini_model
  and sort_order.
- Extract Provider::has_usage_script_enabled() to remove the
  duplicated meta.usage_script chain at two call sites.
- Use db.get_provider_by_id in refresh_all_usage_in_tray instead of
  materialising the full provider map, and parallelise subscription
  and script futures via futures::future::join.
- Narrow refresh_all_usage_in_tray to each section's effective
  current provider (script if enabled, else subscription when the
  provider is official). Hover refreshes now issue at most
  TRAY_SECTIONS.len() outbound requests.
- Add 10 unit tests in tray::tests covering Claude/Codex h/w dispatch,
  Gemini p/f/l dispatch (including lite-only and lite-worst cases),
  and success/failure guards.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-23 16:17:15 +08:00
Coconut-Fish 010b163430 Fix/一键配置失效 (#2249)
* style(FailoverQueueManager): 显示供应商备注信息

* style(FailoverQueueItem): 添加供应商备注字段以支持备注信息显示

* style(FailoverQueueManager): 显示供应商备注信息

* style(FailoverQueueItem): 添加供应商备注字段以支持备注信息显示

* style(FailoverQueueManager): 更新供应商备注信息的显示样式

* style(FailoverQueueItem): 添加条件序列化以优化供应商备注字段

* fix: 优化模型状态管理,确保配置更新时正确引用最新设置

* fix(skill): improve error handling for skill source directory resolution

Co-authored-by: Copilot <copilot@github.com>

* fix(gemini): simplify project directory retrieval in scan_sessions function

* fix(useModelState): optimize latestConfigRef assignment in useModelState hook

* fix(useModelState): remove unnecessary blank line in useModelState hook

---------

Co-authored-by: Copilot <copilot@github.com>
2026-04-23 15:36:03 +08:00
santugege 59735f976b fix(skill): resolve root-level repo skills consistently (#2231)
Co-authored-by: luoyaoqi <luoyaoqi@robam.com>
2026-04-23 12:21:47 +08:00
Jesus Díaz Rivas 10e0772d8c feat: Add Codex OAuth FAST mode toggle (#2210)
* Add Codex OAuth FAST mode toggle

* fix(codex-oauth): default FAST mode to off to avoid surprise quota burn

service_tier="priority" consumes ChatGPT subscription quota at a higher
rate. Users must now opt in explicitly rather than inherit FAST mode
silently when this feature ships.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-23 12:05:17 +08:00
lif 444c123ad0 [codex] Stabilize Codex OAuth cache routing (#2218)
* Stabilize Codex OAuth cache routing

Codex OAuth-backed Claude proxy requests now reuse a client-provided session identity for prompt cache routing and send Codex-like session headers when that identity exists. Generated proxy UUIDs are intentionally excluded so they do not fragment cache locality.\n\nThe same path exposed two runtime issues during validation: rustls needed an explicit process crypto provider, and Codex OAuth can return Responses SSE even when the original Claude request is non-streaming. Those are handled so cache-routed requests can complete instead of panicking or being parsed as JSON.\n\nConstraint: Official Codex uses conversation identity and Responses session headers for prompt cache routing.\nRejected: Always use generated proxy session IDs | generated IDs change per request and reduce cache reuse.\nConfidence: medium\nScope-risk: moderate\nDirective: Do not remove the client-provided-session guard unless generated session IDs become stable per conversation.\nTested: cargo test codex_oauth\nTested: Local dev app health check on 127.0.0.1:15721\nTested: Local proxy logs showed cache_read_tokens after restart\nNot-tested: Full cargo test without local cc-switch port conflict\nRelated: #2217

* feat(proxy): aggregate forced Codex OAuth SSE into JSON for non-streaming clients

Narrow override on top of #2235's streaming fallback.

Codex OAuth always forces upstream openai_responses into SSE, even
when the original Claude request is stream:false. #2235 handles this
by routing such responses through the streaming transform so the
client receives text/event-stream — that avoids the 422 that JSON
parsing would produce, and it also protects any other provider that
unexpectedly returns SSE (the response.is_sse() guard).

But for Claude SDK callers that sent stream:false, returning SSE
still violates the Anthropic non-streaming contract. This commit
adds an override on exactly one combination — non-streaming client
+ codex_oauth + openai_responses — to aggregate the upstream
Responses SSE into a synthetic Responses JSON and then run the
regular responses_to_anthropic non-streaming transform. All other
paths, including the generic response.is_sse() fallback, remain
on the streaming path from #2235.

The aggregator reuses proxy::sse::take_sse_block / strip_sse_field,
which support both \n\n and \r\n\r\n delimiters; a hand-rolled
split("\n\n") would silently fail on real HTTPS upstreams.

Tests cover the happy path, CRLF delimiters, response.failed
errors, and the missing response.completed defensive branch.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-23 11:15:01 +08:00
nmsn 3ad7d0b1cc fix: use TOML parser instead of regex for Codex model extraction (#2222) (#2227)
* fix(codex): use TOML parser instead of regex for model extraction

Regex only matched model=... on first line, TOML parser handles
multiline TOML correctly.

Fixes #2222

* fix(stream_check): drop unused regex::Regex import

The previous commit replaced the only Regex usage in stream_check.rs
with toml::Table parsing, leaving `use regex::Regex;` orphaned.
Without this removal, `cargo clippy -- -D warnings` (run in CI)
fails with `unused import: regex::Regex`.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-23 10:38:08 +08:00
涂瑜 29e87487a1 fix(skills): prevent duplicate imports when import button is double-clicked (#2211)
Closes #2139

Two related defects let the installed-skills count balloon when users
tap the import confirm button multiple times — either deliberately or
because the button is still clickable while a slow import is in flight:

- The confirm button only disabled itself while `selected.size === 0`,
  so it stayed clickable during a pending mutation. Each extra click
  triggered another `importFromApps` mutation.
- `useImportSkillsFromApps` appended the server response to the
  installed cache without deduping, so re-firing the mutation stacked
  the same skills into the list again.

Disable the confirm (and cancel) buttons while the mutation is pending
— matching the `isRestoring` / `isDeleting` pattern already used by
`RestoreSkillsDialog` — and merge success payloads by
`InstalledSkill.id` so repeated results overwrite rather than
accumulate.

The merge is extracted as a pure `mergeImportedSkills` reducer to make
the behaviour unit-testable and to short-circuit on an empty payload,
returning the existing reference so React Query does not notify
subscribers about a no-op cache update.
2026-04-23 10:25:01 +08:00
Coconut-Fish 7bfe2609db Style/session manager list UI (#2201)
* style(FailoverQueueManager): 显示供应商备注信息

* style(FailoverQueueItem): 添加供应商备注字段以支持备注信息显示

* style(FailoverQueueManager): 显示供应商备注信息

* style(FailoverQueueItem): 添加供应商备注字段以支持备注信息显示

* style(FailoverQueueManager): 更新供应商备注信息的显示样式

* style(FailoverQueueItem): 添加条件序列化以优化供应商备注字段

* style(App, SettingsPage, ScrollArea): 调整组件样式以改善布局和视觉效果

* style(App, SettingsPage, ScrollArea): 调整组件样式以改善布局和视觉效果

* style(SettingsPage, useSettings): 统一代码格式,调整样式和变量声明

* style(App): 调整底部内边距以改善布局
2026-04-23 08:56:57 +08:00
tison e7ff2ee47d fix: gemini cli resume session can have project_dir (#2240)
Signed-off-by: tison <wander4096@gmail.com>
2026-04-23 08:55:11 +08:00
xpfo 7ddf7ffd66 fix(proxy): handle Codex OAuth responses as streaming (#2235) 2026-04-23 08:54:31 +08:00
tison 1b3c53d235 fix: always show name on hover (#2237)
Signed-off-by: tison <wander4096@gmail.com>
2026-04-22 23:19:52 +08:00
56 changed files with 2476 additions and 812 deletions
+34
View File
@@ -5,6 +5,40 @@ All notable changes to CC Switch will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [3.14.1] - 2026-04-23
Development since v3.14.0 focuses on Codex OAuth stability, tray usage visibility, Skills import/install reliability, Gemini session restore paths, and simplifying Hermes configuration health handling.
**Stats**: 13 commits | 48 files changed | +1,883 insertions | -808 deletions
### Added
- **Tray Usage Visibility**: System tray submenus now show cached usage for the current Claude / Codex / Gemini provider, including subscription and script-based usage summaries with utilization color markers. Tray-triggered refreshes are throttled, limited to visible apps, and synchronized back into React Query so the main window and tray share fresh usage data (#2184).
- **Tray Coding-Plan Usage (Kimi / Zhipu / MiniMax)**: System tray now renders 5-hour + weekly window usage for Chinese coding-plan providers using the same `🟢 h12% w80%` two-window layout as official subscription badges (worst utilization drives the emoji). Creating a Claude provider whose `ANTHROPIC_BASE_URL` matches a known coding-plan host now auto-injects `meta.usage_script`, so the tray lights up without opening the Usage Script modal. Existing `usage_script` values are preserved on update.
- **Codex OAuth FAST Mode**: Added an explicit FAST mode toggle for Codex OAuth-backed Claude providers. When enabled, converted Responses requests send `service_tier="priority"` for lower latency; the toggle stays off by default to avoid unexpectedly increasing ChatGPT quota consumption (#2210).
### Changed
- **Session and Settings Layout Polish**: Hardened the scroll-area viewport with width containment to fix horizontal overflow, and tightened app bottom spacing plus settings footer spacing so long session/settings views fit more cleanly (#2201).
### Removed
- **Hermes Config Health Scanner**: Removed the in-app Hermes config health scanner, warning banner, `scan_hermes_config_health` command, `HermesHealthWarning` type, and `HermesWriteOutcome.warnings` payload. CC Switch now keeps the Hermes surface focused on active provider display, provider switching defaults, memory editing, and launching the Hermes Web UI for deep configuration.
### Fixed
- **Codex OAuth Cache Routing**: Stabilized ChatGPT Codex reverse-proxy cache identity by using client-provided session IDs for `prompt_cache_key` and Codex session headers, preserving explicit cache keys, and avoiding generated UUID cache churn (#2218).
- **Codex OAuth Responses SSE Aggregation**: Non-streaming Anthropic clients now receive JSON even when the ChatGPT Codex upstream forces OpenAI Responses SSE; CC Switch aggregates the upstream SSE events before running the non-streaming transform (#2235).
- **Codex OAuth Stream Check Parity**: Stream checks now build Codex OAuth test requests with the same `store: false`, encrypted reasoning include, and provider FAST mode setting as production proxy requests (#2210).
- **Codex Model Extraction**: Replaced first-line regex matching with TOML parsing when reading Codex config models, so multiline TOML is handled correctly (#2227).
- **Model Quick-Set / One-Click Config**: Model quick-set updates now apply against the latest provider form config, preventing stale state from making one-click configuration fail (#2249).
- **Skills Import Duplicates**: The Skills import dialog disables actions while import is pending and the installed-skills cache deduplicates imported results by ID, preventing double-clicks from adding duplicate installed entries (#2139, #2211).
- **Root-Level Skill Repos**: Skill install and update flows now consistently resolve three source patterns: direct nested paths, install-name recursive search, and repository-root `SKILL.md` sources (#2231).
- **Gemini Session Restore Paths**: Gemini session scanning now reads `.project_root` metadata so restore flows can pass the original project directory when available (#2240).
- **Provider Hover Names**: Provider icons now expose the provider name on hover for inline SVG, image URL, and fallback initials render paths (#2237).
## [3.14.0] - 2026-04-21
Development since v3.13.0 focuses on onboarding Hermes Agent as a first-class managed app, rolling out Claude Opus 4.7 across the preset matrix, adding a Gemini Native API proxy, and sharpening session, usage, and proxy workflows.
+185
View File
@@ -0,0 +1,185 @@
# CC Switch v3.14.1
> Tray usage visibility, Codex OAuth stability fixes, Skills import/install reliability, and removal of the Hermes config health scanner
**[中文版 →](v3.14.1-zh.md) | [日本語版 →](v3.14.1-ja.md)**
---
## Overview
CC Switch v3.14.1 is a patch release following v3.14.0, focused on **Codex OAuth reverse-proxy stability**, **tray usage visibility**, **Skills import / install reliability**, **Gemini session restore paths**, and **simplifying Hermes configuration health handling**.
For the first time, the system tray surfaces **cached usage** for the current Claude / Codex / Gemini provider directly in its submenus — including subscription summaries and usage-script summaries with color-coded utilization markers. For Chinese coding-plan providers like Kimi / Zhipu / MiniMax, the tray additionally renders a **5-hour + weekly window** layout in the `🟢 h12% w80%` style (worst utilization drives the emoji), semantically identical to the official subscription badges. Creating a Claude provider whose `ANTHROPIC_BASE_URL` matches a known coding-plan host now auto-injects `meta.usage_script` so the tray lights up without opening the Usage Script modal.
Several Codex OAuth reverse-proxy stability issues are addressed this release: client-provided session IDs are now used as both `prompt_cache_key` and the Codex session header to avoid UUID-driven cache churn; non-streaming Anthropic clients receive proper JSON responses even when the ChatGPT Codex upstream forces OpenAI Responses SSE; and Stream Check now builds probes with the same `store: false`, encrypted reasoning include, and provider FAST mode setting as production requests, eliminating the "check fails but it actually works" mismatch. Paired with a new explicit **FAST mode toggle**, users can now opt into `service_tier="priority"` on Codex OAuth-backed Claude providers, trading latency against ChatGPT quota consumption on their own terms.
Additionally, the in-app **Hermes config health scanner** and its warning banner are removed (along with the `scan_hermes_config_health` command, `HermesHealthWarning` type, and `HermesWriteOutcome.warnings` payload), refocusing the Hermes surface on active provider display, switching defaults, memory editing, and launching the Hermes Web UI — deep configuration health is now Hermes's own responsibility.
**Release Date**: 2026-04-23
**Update Scale**: 13 commits | 48 files changed | +1,883 / -808 lines
---
## Highlights
- **Tray Usage Visibility**: Claude / Codex / Gemini tray submenus show cached usage for the current provider, including subscription and script-based summaries with color markers; refreshes are throttled, limited to visible apps, and synchronized back into React Query (#2184, thanks @TuYv)
- **Tray Coding-Plan Usage (Kimi / Zhipu / MiniMax)**: The tray renders 5-hour + weekly window usage using the `🟢 h12% w80%` layout; Claude providers whose base URL matches a known host auto-inject `meta.usage_script`
- **Codex OAuth FAST Mode**: New explicit FAST mode toggle for Codex OAuth-backed Claude providers; when enabled, converted Responses requests send `service_tier="priority"`. Off by default (#2210, thanks @JesusDR01)
- **Codex OAuth Stability**: Fixed reverse-proxy cache routing (#2218, thanks @majiayu000), Responses SSE aggregation (#2235, thanks @xpfo-go), and Stream Check parity with production (#2210, thanks @JesusDR01)
- **Hermes Config Health Scanner Removed**: Refocuses the Hermes surface on provider management, memory editing, and launching the Web UI — no longer duplicates deep configuration health judgments
- **Skills Import / Install Reliability**: Import dialog disables actions while pending and deduplicates results by ID (#2211, thanks @TuYv); model quick-set / one-click config applies against the latest form state (#2249, thanks @Coconut-Fish); root-level `SKILL.md` repo installs are stable (#2231, thanks @santugege)
- **Gemini Session Restore Paths**: Session scanning reads `.project_root` metadata and passes the original project directory back into restore flows (#2240, thanks @tisonkun)
- **Session / Settings Layout Polish**: Hardened the scroll-area viewport with width containment to fix horizontal overflow; tightened app bottom and settings footer spacing (#2201, thanks @Coconut-Fish)
---
## Added
### Tray Usage Visibility
- System tray submenus now show **cached usage** for the current Claude / Codex / Gemini provider (#2184, thanks @TuYv)
- Includes subscription quota summaries and usage-script summaries with color-coded utilization markers
- Tray-triggered refreshes are **throttled**, **limited to visible apps**, and synchronized back into React Query so the main window and tray share the same usage data
### Tray Coding-Plan Usage (Kimi / Zhipu / MiniMax)
- The tray renders **5-hour + weekly window** usage for Chinese coding-plan providers
- Uses the same `🟢 h12% w80%` two-window layout as official subscription badges (worst utilization drives the emoji color)
- Creating a Claude provider whose `ANTHROPIC_BASE_URL` matches a known coding-plan host **auto-injects** `meta.usage_script`, so the tray lights up without opening the Usage Script modal
- Existing `usage_script` values are **preserved on update**, never clobbering user customizations
### Codex OAuth FAST Mode
- New explicit FAST mode toggle for Codex OAuth-backed Claude providers (#2210, thanks @JesusDR01)
- When enabled, converted Responses requests send `service_tier="priority"` for lower latency
- Off by default to avoid unexpectedly increasing ChatGPT quota consumption
---
## Changed
### Session and Settings Layout Polish
- Hardened the scroll-area viewport with width containment to fix horizontal overflow (#2201, thanks @Coconut-Fish)
- Tightened app bottom and settings footer spacing so long session / settings views fit more cleanly
---
## Removed
### Hermes Config Health Scanner
- Removed the in-app Hermes config health scanner and its warning banner
- Removed the `scan_hermes_config_health` command, `HermesHealthWarning` type, and `HermesWriteOutcome.warnings` payload
- The CC Switch Hermes surface now focuses on its core job: active provider display, default provider switching, memory editing, and launching the Hermes Web UI for deep configuration
---
## Fixed
### Codex OAuth Cache Routing
- Use the client-provided session ID as both `prompt_cache_key` and the Codex session header, preserving explicit cache keys (#2218, thanks @majiayu000)
- Stop generating UUIDs that caused cache-identity churn, stabilizing the ChatGPT Codex reverse-proxy cache identity
### Codex OAuth Responses SSE Aggregation
- Non-streaming Anthropic clients now receive proper JSON even when the ChatGPT Codex upstream forces OpenAI Responses SSE (#2235, thanks @xpfo-go)
- CC Switch aggregates the upstream SSE events before running the non-streaming transform
### Codex OAuth Stream Check Parity
- Stream Check now builds Codex OAuth probe requests with the same `store: false`, encrypted reasoning include, and provider FAST mode setting as production proxy traffic (#2210, thanks @JesusDR01)
- Eliminates the "check fails but it actually works" mismatch
### Codex Model Extraction
- Reading the `model` field from Codex config now uses TOML parsing instead of first-line regex matching (#2227, thanks @nmsn)
- Multiline TOML is handled correctly
### Model Quick-Set / One-Click Config
- Model quick-set now applies against the **latest** provider form config (#2249, thanks @Coconut-Fish)
- Fixes stale form state preventing one-click configuration from succeeding
### Skills Import Duplicates
- The Skills import dialog disables actions while import is pending (#2211, thanks @TuYv)
- The installed-skills cache deduplicates imported results by ID, preventing double-clicks from adding duplicate installed entries (#2139)
### Root-Level Skill Repos
- Skill install and update flows now consistently resolve three source patterns: direct nested paths, install-name recursive search, and repository-root `SKILL.md` sources (#2231, thanks @santugege)
### Gemini Session Restore Paths
- Gemini session scanning now reads `.project_root` metadata (#2240, thanks @tisonkun)
- Restore flows can pass the original project directory when available
### Provider Hover Names
- Provider icons now expose the provider name on hover for inline SVG, image URL, and fallback initials render paths (#2237, thanks @tisonkun)
---
## Notes & Caveats
- **Hermes Health Scanner Removed**: If you were relying on CC Switch to surface deep Hermes YAML configuration issues, switch to the "Launch Hermes Web UI" toolbar button and inspect them in Hermes's own panel. Day-to-day provider management, switching, memory editing, and MCP / Skills sync continue to be handled by CC Switch.
- **Codex OAuth FAST Mode Off by Default**: Only turn it on if you accept potentially increased ChatGPT quota consumption in exchange for lower latency.
- **Tray Cached Usage**: Refreshes are throttled and limited to the currently visible app to avoid unnecessary upstream API calls; values are synchronized into React Query so the main window and tray stay in sync.
---
## Download & Installation
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) to download the appropriate version.
### System Requirements
| OS | Minimum Version | Architecture |
| ------- | ---------------------------- | ----------------------------------- |
| Windows | Windows 10 or later | x64 |
| macOS | macOS 12 (Monterey) or later | Intel (x64) / Apple Silicon (arm64) |
| Linux | See table below | x64 |
### Windows
| File | Description |
| ---------------------------------------- | ----------------------------------------------------- |
| `CC-Switch-v3.14.1-Windows.msi` | **Recommended** - MSI installer, supports auto-update |
| `CC-Switch-v3.14.1-Windows-Portable.zip` | Portable, extract and run, no registry writes |
### macOS
| File | Description |
| -------------------------------- | ------------------------------------------------------- |
| `CC-Switch-v3.14.1-macOS.dmg` | **Recommended** - DMG installer, drag into Applications |
| `CC-Switch-v3.14.1-macOS.zip` | Extract and drag into Applications, Universal Binary |
| `CC-Switch-v3.14.1-macOS.tar.gz` | For Homebrew installation and auto-update |
> macOS builds are Apple code-signed and notarized — install directly.
### Homebrew (macOS)
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
Update:
```bash
brew upgrade --cask cc-switch
```
### Linux
| Distribution | Recommended | Installation |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | Add execute permission and run, or use AUR |
| Other distros / not sure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+185
View File
@@ -0,0 +1,185 @@
# CC Switch v3.14.1
> トレイでの用量可視化、Codex OAuth の複数の安定性修正、Skills インポート/インストールの信頼性向上、Hermes 設定ヘルススキャナーの削除
**[中文版 →](v3.14.1-zh.md) | [English →](v3.14.1-en.md)**
---
## 概要
CC Switch v3.14.1 は v3.14.0 に続くパッチリリースで、**Codex OAuth リバースプロキシの安定性**、**トレイでの用量可視化**、**Skills インポート / インストールの信頼性**、**Gemini セッション復元パス**、および **Hermes 設定ヘルス処理の簡素化**を中心に据えています。
システムトレイは初めて、現在の Claude / Codex / Gemini プロバイダーの**キャッシュ済み用量**をサブメニューに直接表示するようになりました — サブスクリプション要約と用量スクリプト要約を、使用率に応じた色分けマーカーとともに表示します。Kimi / Zhipu / MiniMax のような中国系コーディングプランプロバイダーには、公式サブスクリプションバッジと同じ `🟢 h12% w80%` スタイルで **5 時間 + 週次ウィンドウ**の 2 ウィンドウレイアウトを追加描画します(より厳しい方の使用率が絵文字色を決定)。`ANTHROPIC_BASE_URL` が既知のコーディングプランホストに一致する Claude プロバイダーを作成すると、`meta.usage_script` が自動注入されるため、Usage Script モーダルを開かなくてもトレイが点灯します。
Codex OAuth 側では、複数のリバースプロキシ安定性の問題を修正しました: クライアント提供の session ID を `prompt_cache_key` と Codex session ヘッダーの両方に使用し、UUID 生成によるキャッシュ揺らぎを回避。ChatGPT Codex 上流が OpenAI Responses SSE を強制する場合でも、非ストリーミングの Anthropic クライアントが適切な JSON レスポンスを受け取れるようになりました。Stream Check は、本番環境と同じ `store: false`、暗号化 reasoning include、およびプロバイダーの FAST モード設定でプローブを構築するようになり、「検出は失敗するのに実際は動く」というズレが解消されました。新しい明示的な **FAST モードトグル**と組み合わせることで、ユーザーは Codex OAuth バックの Claude プロバイダーで `service_tier="priority"` を選択的に送信でき、レイテンシと ChatGPT 配額消費の間で自分で選べるようになりました。
さらに、CC Switch 内蔵の **Hermes 設定ヘルススキャナー**と警告バナー(および対応する `scan_hermes_config_health` コマンド、`HermesHealthWarning` 型、`HermesWriteOutcome.warnings` ペイロード)を削除し、Hermes サーフェスをアクティブプロバイダー表示、デフォルト切り替え、Memory 編集、および Hermes Web UI の起動に再フォーカスしました — 深い設定ヘルスは Hermes 自身の責任になります。
**リリース日**: 2026-04-23
**更新規模**: 13 commits | 48 files changed | +1,883 / -808 lines
---
## ハイライト
- **トレイでの用量可視化**: Claude / Codex / Gemini のトレイサブメニューに、現在のプロバイダーのキャッシュ済み用量(サブスクリプション要約とスクリプト要約、色分けマーカー付き)を表示。リフレッシュはスロットル、可視アプリに限定、React Query に同期 (#2184, 感謝 @TuYv)
- **トレイのコーディングプラン用量(Kimi / Zhipu / MiniMax**: トレイが 5 時間 + 週次ウィンドウの用量を `🟢 h12% w80%` レイアウトで描画。既知のホストにマッチする Claude プロバイダーは `meta.usage_script` を自動注入
- **Codex OAuth FAST モード**: Codex OAuth バックの Claude プロバイダーに明示的な FAST モードトグルを追加。有効時は変換された Responses リクエストに `service_tier="priority"` を送信、デフォルトは OFF (#2210, 感謝 @JesusDR01)
- **Codex OAuth 安定性**: リバースプロキシのキャッシュルーティング (#2218, 感謝 @majiayu000)、Responses SSE 集約 (#2235, 感謝 @xpfo-go)、Stream Check と本番の一致性 (#2210, 感謝 @JesusDR01) を修正
- **Hermes 設定ヘルススキャナー削除**: Hermes サーフェスをプロバイダー管理、Memory 編集、Web UI 起動に再フォーカス。深い設定ヘルス判定を重複して担わなくなる
- **Skills インポート / インストールの信頼性**: インポート中はダイアログのアクションを無効化し、結果を ID で重複排除 (#2211, 感謝 @TuYv); ワンクリック設定は最新のフォーム状態に基づいて適用 (#2249, 感謝 @Coconut-Fish); ルートレベルの `SKILL.md` リポジトリインストールが安定 (#2231, 感謝 @santugege)
- **Gemini セッション復元パス**: セッションスキャン時に `.project_root` メタデータを読み、元のプロジェクトディレクトリを復元フローに渡す (#2240, 感謝 @tisonkun)
- **セッション / 設定レイアウトの磨き込み**: スクロールエリアビューポートに幅制約を追加して横方向のはみ出しを修正。アプリ下部と設定フッター間隔をよりタイトに (#2201, 感謝 @Coconut-Fish)
---
## 新機能
### トレイでの用量可視化
- システムトレイサブメニューに、現在の Claude / Codex / Gemini プロバイダーの**キャッシュ済み用量**を表示 (#2184, 感謝 @TuYv)
- サブスクリプション配額要約と用量スクリプト要約を含み、使用率に応じた色分けマーカー付き
- トレイ起因のリフレッシュは**スロットル**、**可視アプリに限定**、React Query に同期されるため、メインウィンドウとトレイが同じ用量データを共有
### トレイのコーディングプラン用量(Kimi / Zhipu / MiniMax
- 中国系コーディングプランプロバイダー向けに、トレイが **5 時間 + 週次ウィンドウ**の用量を描画
- 公式サブスクリプションバッジと同じ `🟢 h12% w80%` の 2 ウィンドウレイアウトを使用(より厳しい使用率が絵文字色を決定)
- `ANTHROPIC_BASE_URL` が既知のコーディングプランホストにマッチする Claude プロバイダーを作成すると、`meta.usage_script` が**自動注入**され、Usage Script モーダルを開かなくてもトレイが点灯
- 更新時は既存の `usage_script` 値を**保持**し、ユーザーカスタマイズを上書きしない
### Codex OAuth FAST モード
- Codex OAuth バックの Claude プロバイダーに明示的な FAST モードトグルを追加 (#2210, 感謝 @JesusDR01)
- 有効時は変換された Responses リクエストに `service_tier="priority"` を送信してレイテンシを低減
- 予期せぬ ChatGPT 配額消費の増加を避けるため、デフォルトは OFF
---
## 変更
### セッション・設定レイアウトの磨き込み
- スクロールエリアビューポートに幅制約を追加して横方向のはみ出しを修正 (#2201, 感謝 @Coconut-Fish)
- アプリ下部と設定フッター間隔をよりタイトにし、長いセッション / 設定ビューをすっきり表示
---
## 削除
### Hermes 設定ヘルススキャナー
- アプリ内の Hermes 設定ヘルススキャナーと警告バナーを削除
- `scan_hermes_config_health` コマンド、`HermesHealthWarning` 型、`HermesWriteOutcome.warnings` ペイロードを削除
- CC Switch の Hermes サーフェスは本来の役割に回帰: アクティブプロバイダー表示、デフォルトプロバイダー切り替え、Memory 編集、および深い設定用の Hermes Web UI 起動
---
## バグ修正
### Codex OAuth キャッシュルーティング
- クライアント提供の session ID を `prompt_cache_key` と Codex session ヘッダーの両方に使用し、明示的なキャッシュキーを保持 (#2218, 感謝 @majiayu000)
- キャッシュアイデンティティの揺らぎを引き起こしていた UUID 生成を停止し、ChatGPT Codex リバースプロキシのキャッシュアイデンティティを安定化
### Codex OAuth Responses SSE 集約
- ChatGPT Codex 上流が OpenAI Responses SSE を強制する場合でも、非ストリーミングの Anthropic クライアントが適切な JSON を受け取れるように修正 (#2235, 感謝 @xpfo-go)
- CC Switch が非ストリーミング変換を実行する前に上流 SSE イベントを集約
### Codex OAuth Stream Check の一致性
- Stream Check が構築する Codex OAuth プローブリクエストは、本番プロキシと同じ `store: false`、暗号化 reasoning include、プロバイダー FAST モード設定を使用するように修正 (#2210, 感謝 @JesusDR01)
- 「検出は失敗するのに実際は動く」ズレを解消
### Codex モデル抽出
- Codex 設定の `model` フィールドを読む際、先頭行の正規表現マッチではなく TOML パーサーを使用するように変更 (#2227, 感謝 @nmsn)
- 複数行 TOML も正しく処理
### モデルのクイック入力 / ワンクリック設定
- モデルクイック入力は**最新の**プロバイダーフォーム設定に対して適用されるように修正 (#2249, 感謝 @Coconut-Fish)
- 古いフォーム状態によってワンクリック設定が失敗する問題を修正
### Skills インポートの重複排除
- Skills インポートダイアログは、インポート中にすべてのアクションボタンを無効化 (#2211, 感謝 @TuYv)
- インストール済み Skills のキャッシュを ID で重複排除し、ダブルクリックによる重複したインストール済みエントリを防止 (#2139)
### ルートレベルの Skill リポジトリ
- Skill のインストールと更新フローが 3 つのソースパターンを一貫して解決: 直接ネストパス、install-name の再帰検索、およびリポジトリルートの `SKILL.md` ソース (#2231, 感謝 @santugege)
### Gemini セッション復元パス
- Gemini セッションスキャンが `.project_root` メタデータを読み取るように修正 (#2240, 感謝 @tisonkun)
- 復元フローは利用可能な場合に元のプロジェクトディレクトリを渡せる
### プロバイダー名のホバー表示
- プロバイダーアイコンは、inline SVG、画像 URL、およびフォールバックの頭文字レンダリングパスで、ホバー時にプロバイダー名を表示 (#2237, 感謝 @tisonkun)
---
## 備考・注意事項
- **Hermes ヘルススキャナー削除済み**: Hermes YAML の深い設定の問題提示を CC Switch に頼っていた場合は、ツールバーの「Hermes Web UI を起動」ボタンから Hermes 自身のパネルで確認してください。日常のプロバイダー管理、切り替え、Memory 編集、MCP / Skills 同期は引き続き CC Switch が担います。
- **Codex OAuth FAST モードはデフォルト OFF**: レイテンシ低減と引き換えに ChatGPT 配額消費が増える可能性を許容する場合にのみ有効化してください。
- **トレイのキャッシュ用量**: リフレッシュはスロットル済み、かつ現在可視のアプリに限定されており、不要な上流 API 呼び出しを回避します。値は React Query に同期されるため、メインウィンドウとトレイで同じ値が見えます。
---
## ダウンロード・インストール
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から対応バージョンをダウンロードしてください。
### システム要件
| OS | 最小バージョン | アーキテクチャ |
| ------- | ------------------------ | ----------------------------------- |
| Windows | Windows 10 以降 | x64 |
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 下表参照 | x64 |
### Windows
| ファイル | 説明 |
| ---------------------------------------- | ------------------------------------------- |
| `CC-Switch-v3.14.1-Windows.msi` | **推奨** - MSI インストーラー、自動更新対応 |
| `CC-Switch-v3.14.1-Windows-Portable.zip` | ポータブル版、解凍して実行、レジストリ不要 |
### macOS
| ファイル | 説明 |
| -------------------------------- | ------------------------------------------------------ |
| `CC-Switch-v3.14.1-macOS.dmg` | **推奨** - DMG インストーラー、Applications にドラッグ |
| `CC-Switch-v3.14.1-macOS.zip` | 解凍して Applications にドラッグ、Universal Binary |
| `CC-Switch-v3.14.1-macOS.tar.gz` | Homebrew インストールと自動更新用 |
> macOS 版は Apple のコード署名および公証済みで、直接インストールして使用できます。
### HomebrewmacOS
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
| ディストリビューション | 推奨形式 | インストール方法 |
| --------------------------------------- | ----------- | -------------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | 実行権限を付与して実行、または AUR を使用 |
| その他のディストリビューション / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+185
View File
@@ -0,0 +1,185 @@
# CC Switch v3.14.1
> 托盘用量可见化、Codex OAuth 多项稳定性修复、Skills 导入/安装可靠性提升、Hermes 配置健康扫描器移除
**[English →](v3.14.1-en.md) | [日本語版 →](v3.14.1-ja.md)**
---
## 概览
CC Switch v3.14.1 是 v3.14.0 之后的一次补丁版本,围绕 **Codex OAuth 反代稳定性**、**托盘用量可见化**、**Skills 导入 / 安装可靠性**、**Gemini 会话恢复路径**,以及**简化 Hermes 配置健康处理**展开。
系统托盘第一次把当前 Claude / Codex / Gemini 供应商的**缓存用量**直接呈现在子菜单里——包含订阅额度摘要和用量脚本摘要,并用颜色标记利用率;针对 Kimi / 智谱 / MiniMax 这类中国编码套餐供应商,托盘还会额外渲染 `🟢 h12% w80%` 风格的 **5 小时 + 周窗口**双窗口排版,语义与官方订阅徽章完全一致(取更紧的那个驱动 emoji)。创建 Claude 供应商时,如果 `ANTHROPIC_BASE_URL` 命中已知的编码套餐 host,会自动注入 `meta.usage_script`,托盘可以不打开 Usage Script 模态框就直接点亮。
Codex OAuth 侧修复了多项反代稳定性问题:使用客户端自带的 session ID 作为 `prompt_cache_key` 和 Codex session 头,避免生成 UUID 造成缓存抖动,显著提高缓存命中率;非流式 Anthropic 客户端在 ChatGPT Codex 上游强制 OpenAI Responses SSE 时也能正确拿到 JSON 响应;Stream Check 现在会以和生产一致的 `store: false`、encrypted reasoning include 以及供应商 FAST 模式构造探测请求,避免出现"检测失败但实际能用"的错位。配合新增的 **FAST 模式显式开关**,让用户可以在 Codex OAuth 型 Claude 供应商上按需发 `service_tier="priority"`,在延迟和 ChatGPT 配额消耗之间自己选。
另外,移除了 CC Switch 内置的 **Hermes 配置健康扫描器**及其警告横幅(以及对应的 `scan_hermes_config_health` 命令、`HermesHealthWarning` 类型和 `HermesWriteOutcome.warnings` 载荷),把 Hermes 面板聚焦回当前供应商展示、默认切换、Memory 编辑和启动 Hermes Web UI,深度配置健康度由 Hermes 自己负责。
**发布日期**2026-04-23
**更新规模**13 commits | 48 files changed | +1,883 / -808 lines
---
## 重点内容
- **托盘用量可见化**Claude / Codex / Gemini 托盘子菜单展示当前供应商缓存用量,含订阅与脚本摘要及颜色标记;刷新带节流、仅针对可见应用、并回写到 React Query (#2184, 感谢 @TuYv)
- **托盘编码套餐用量(Kimi / 智谱 / MiniMax**:托盘渲染 5 小时 + 周窗口双窗口用量,沿用 `🟢 h12% w80%` 排版;命中已知 host 的 Claude 供应商自动注入 `meta.usage_script`
- **Codex OAuth FAST 模式**:为 Codex OAuth 型 Claude 供应商新增显式 FAST 开关,开启后转换后的 Responses 请求发 `service_tier="priority"`,默认关闭 (#2210, 感谢 @JesusDR01)
- **Codex OAuth 稳定性**:修复反代缓存路由 (#2218, 感谢 @majiayu000)、Responses SSE 聚合 (#2235, 感谢 @xpfo-go)、Stream Check 与生产一致性 (#2210, 感谢 @JesusDR01)
- **Hermes 配置健康扫描器移除**:把 Hermes 面板聚焦回供应商管理、Memory 编辑和 Web UI 启动,不再重复承担深度配置健康判断
- **Skills 导入 / 安装可靠性**:导入过程中禁用操作按钮、结果按 ID 去重 (#2211, 感谢 @TuYv);一键配置基于最新表单状态 (#2249, 感谢 @Coconut-Fish);根级 `SKILL.md` 仓库安装稳定 (#2231, 感谢 @santugege)
- **Gemini 会话恢复路径**:扫描会话时读取 `.project_root` 元数据,把原始项目目录带回恢复流程 (#2240, 感谢 @tisonkun)
- **Session / 设置布局打磨**:滚动区域视口加宽度约束修复横向溢出,应用底部和设置页底部间距更紧凑 (#2201, 感谢 @Coconut-Fish)
---
## 新功能
### 托盘用量可见化
- 系统托盘子菜单新增当前 Claude / Codex / Gemini 供应商的**缓存用量**展示 (#2184, 感谢 @TuYv)
- 包含订阅额度摘要和用量脚本摘要,并用颜色标记利用率
- 托盘触发的刷新**带节流**、**只覆盖可见应用**,并同步回 React Query,主窗口和托盘共享同一份用量数据
### 托盘编码套餐用量(Kimi / 智谱 / MiniMax
- 托盘为中国编码套餐供应商渲染 **5 小时 + 周窗口**双窗口用量
- 使用与官方订阅徽章一致的 `🟢 h12% w80%` 两窗口排版,取更紧的那个利用率驱动 emoji 颜色
- 创建 Claude 供应商时,如果 `ANTHROPIC_BASE_URL` 匹配已知编码套餐 host,会**自动注入** `meta.usage_script`,托盘不打开 Usage Script 模态框也能直接点亮
- 更新时会**保留已有** `usage_script` 值,不覆盖用户自定义
### Codex OAuth FAST 模式
- 为 Codex OAuth 型 Claude 供应商新增显式 FAST 模式开关 (#2210, 感谢 @JesusDR01)
- 开启时,转换后的 Responses 请求会发 `service_tier="priority"` 以降低延迟
- 默认关闭,避免意外增加 ChatGPT 配额消耗
---
## 变更
### Session 与设置布局打磨
- 滚动区域视口加上宽度约束,修复横向溢出 (#2201, 感谢 @Coconut-Fish)
- 应用底部和设置页底部间距更紧凑,让长 Session / 设置视图看起来更干净
---
## 移除
### Hermes 配置健康扫描器
- 移除应用内的 Hermes 配置健康扫描器和警告横幅
- 移除 `scan_hermes_config_health` 命令、`HermesHealthWarning` 类型以及 `HermesWriteOutcome.warnings` 载荷
- CC Switch 的 Hermes 面板回归核心职责:当前供应商展示、切换默认供应商、Memory 编辑、以及启动 Hermes Web UI 处理深度配置
---
## 修复
### Codex OAuth 缓存路由
- 使用客户端自带的 session ID 作为 `prompt_cache_key` 和 Codex session 头,保留显式缓存 key (#2218, 感谢 @majiayu000)
- 停止生成 UUID 导致的缓存抖动,让 ChatGPT Codex 反代的缓存身份更稳定
### Codex OAuth Responses SSE 聚合
- ChatGPT Codex 上游强制 OpenAI Responses SSE 时,非流式 Anthropic 客户端也能正确拿到 JSON (#2235, 感谢 @xpfo-go)
- CC Switch 会在非流式转换之前先聚合上游 SSE 事件
### Codex OAuth Stream Check 对齐
- Stream Check 构造的 Codex OAuth 测试请求现在与生产代理一致,使用相同的 `store: false`、加密 reasoning include 和供应商 FAST 模式设置 (#2210, 感谢 @JesusDR01)
- 避免"检测失败但实际能用"的错位
### Codex 模型提取
- 读取 Codex 配置的 `model` 字段时,改用 TOML 解析替代首行正则匹配 (#2227, 感谢 @nmsn)
- 多行 TOML 也能正确处理
### 模型快速填入 / 一键配置
- 模型快速填入现在基于**最新的**供应商表单配置应用 (#2249, 感谢 @Coconut-Fish)
- 修复陈旧表单状态导致一键配置失败的问题
### Skills 导入去重
- Skills 导入对话框在导入进行时禁用所有操作按钮 (#2211, 感谢 @TuYv)
- 已安装 Skills 的缓存按 ID 去重,避免双击造成重复的已安装条目 (#2139)
### 根级 Skill 仓库
- Skill 的安装与更新流程现在能一致地识别三种源路径:直接嵌套路径、按 install-name 递归搜索、以及仓库根的 `SKILL.md` 源 (#2231, 感谢 @santugege)
### Gemini 会话恢复路径
- Gemini 会话扫描时读取 `.project_root` 元数据 (#2240, 感谢 @tisonkun)
- 恢复流程可以在可用时把原始项目目录传回
### 供应商名悬浮提示
- 供应商图标在 inline SVG、图像 URL、以及首字母回退渲染路径下都会在 hover 时展示供应商名称 (#2237, 感谢 @tisonkun)
---
## 说明与注意事项
- **Hermes 健康扫描器已移除**:如果你依赖 CC Switch 提示 Hermes YAML 的深度配置问题,请改为通过工具栏的"启动 Hermes Web UI"按钮在 Hermes 原生面板里查看。日常供应商管理、切换、Memory 编辑、MCP 与 Skills 同步仍然由 CC Switch 负责。
- **Codex OAuth FAST 模式默认关闭**:只有在你接受可能增加 ChatGPT 配额消耗换取更低延迟时,才需要打开。
- **托盘缓存用量**:刷新带节流,只覆盖当前显示的应用,避免无必要的上游 API 调用;数据会回写到 React Query,因此主窗口和托盘看到的值一致。
---
## 下载与安装
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
### 系统要求
| 系统 | 最低版本 | 架构 |
| ------- | -------------------------- | ----------------------------------- |
| Windows | Windows 10 及以上 | x64 |
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 见下表 | x64 |
### Windows
| 文件 | 说明 |
| ---------------------------------------- | ----------------------------------- |
| `CC-Switch-v3.14.1-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
| `CC-Switch-v3.14.1-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
### macOS
| 文件 | 说明 |
| -------------------------------- | --------------------------------------------- |
| `CC-Switch-v3.14.1-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
| `CC-Switch-v3.14.1-macOS.zip` | 解压后拖入 ApplicationsUniversal Binary |
| `CC-Switch-v3.14.1-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
> macOS 版本已通过 Apple 代码签名和公证,可直接安装使用。
### HomebrewmacOS
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
| 发行版 | 推荐格式 | 安装方式 |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb``sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm``sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cc-switch",
"version": "3.14.0",
"version": "3.14.1",
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
"type": "module",
"scripts": {
+1 -1
View File
@@ -735,7 +735,7 @@ dependencies = [
[[package]]
name = "cc-switch"
version = "3.14.0"
version = "3.14.1"
dependencies = [
"anyhow",
"arboard",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "cc-switch"
version = "3.14.0"
version = "3.14.1"
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
authors = ["Jason Young"]
license = "MIT"
+1 -1
View File
@@ -316,7 +316,7 @@ use crate::prompt_files::prompt_file_path;
use crate::provider::ProviderManager;
/// 应用类型
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AppType {
Claude,
-6
View File
@@ -40,12 +40,6 @@ pub fn get_hermes_live_provider(
hermes_config::get_provider(&providerId).map_err(|e| e.to_string())
}
/// Scan config.yaml for known configuration hazards.
#[tauri::command]
pub fn scan_hermes_config_health() -> Result<Vec<hermes_config::HermesHealthWarning>, String> {
hermes_config::scan_hermes_config_health().map_err(|e| e.to_string())
}
// ============================================================================
// Model Configuration Commands
// ============================================================================
+40 -4
View File
@@ -1,5 +1,5 @@
use indexmap::IndexMap;
use tauri::State;
use tauri::{Emitter, State};
use crate::app_config::AppType;
use crate::commands::copilot::CopilotAuthState;
@@ -153,19 +153,55 @@ pub fn import_default_config(state: State<'_, AppState>, app: String) -> Result<
#[allow(non_snake_case)]
#[tauri::command]
pub async fn queryProviderUsage(
app_handle: tauri::AppHandle,
state: State<'_, AppState>,
copilot_state: State<'_, CopilotAuthState>,
#[allow(non_snake_case)] providerId: String, // 使用 camelCase 匹配前端
app: String,
) -> Result<crate::provider::UsageResult, String> {
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
// inner 可能以两种形式失败:
// 1) 返回 Ok(UsageResult { success: false, .. }) —— 业务失败(401、脚本报错等)
// 2) 返回 Err(String) —— RPC/DB/Copilot fetch_usage 等 transport 层失败
// 两种都要把"失败"写进 UsageCache 并刷新托盘,让 format_script_summary 的
// success 守卫生效、suffix 自然消失,避免旧 success 快照长期滞留。
// 同时保持原始 Err 返回给前端 React Query 的 onError 回调,不吞错误。
let inner =
query_provider_usage_inner(&state, &copilot_state, app_type.clone(), &providerId).await;
let snapshot = match &inner {
Ok(r) => r.clone(),
Err(err_msg) => crate::provider::UsageResult {
success: false,
data: None,
error: Some(err_msg.clone()),
},
};
let payload = serde_json::json!({
"kind": "script",
"appType": app_type.as_str(),
"providerId": &providerId,
"data": &snapshot,
});
if let Err(e) = app_handle.emit("usage-cache-updated", payload) {
log::error!("emit usage-cache-updated (script) 失败: {e}");
}
state.usage_cache.put_script(app_type, providerId, snapshot);
crate::tray::schedule_tray_refresh(&app_handle);
inner
}
async fn query_provider_usage_inner(
state: &AppState,
copilot_state: &CopilotAuthState,
app_type: AppType,
provider_id: &str,
) -> Result<crate::provider::UsageResult, String> {
// 从数据库读取供应商信息,检查特殊模板类型
let providers = state
.db
.get_all_providers(app_type.as_str())
.map_err(|e| format!("Failed to get providers: {e}"))?;
let provider = providers.get(&providerId);
let provider = providers.get(provider_id);
let usage_script = provider
.and_then(|p| p.meta.as_ref())
.and_then(|m| m.usage_script.as_ref());
@@ -294,7 +330,7 @@ pub async fn queryProviderUsage(
}
// ── 通用 JS 脚本路径 ──
ProviderService::query_usage(state.inner(), app_type, &providerId)
ProviderService::query_usage(state, app_type, provider_id)
.await
.map_err(|e| e.to_string())
}
@@ -406,7 +442,7 @@ pub fn update_providers_sort_order(
use crate::provider::UniversalProvider;
use std::collections::HashMap;
use tauri::{AppHandle, Emitter};
use tauri::AppHandle;
#[derive(Clone, serde::Serialize)]
pub struct UniversalProviderSyncedEvent {
+35 -4
View File
@@ -1,10 +1,41 @@
use crate::services::subscription::SubscriptionQuota;
use std::str::FromStr;
use tauri::{Emitter, State};
use crate::app_config::AppType;
use crate::services::subscription::{CredentialStatus, SubscriptionQuota};
use crate::store::AppState;
/// 查询官方订阅额度
///
/// 读取 CLI 工具已有的 OAuth 凭据并调用官方 API 获取使用额度。
/// 不需要 AppState(不访问数据库),直接读文件 + 发 HTTP。
/// 结果(无论业务失败还是 transport 层 Err)都会写入 `UsageCache`、通知托盘
/// 刷新,并 emit `usage-cache-updated`,让前端 React Query 与托盘共享同一份
/// 最新数据。失败快照写入后 `format_subscription_summary` 会通过 `success=false`
/// 守卫返回 `None`,托盘 suffix 自然消失,避免长期滞留旧配额数字。
/// Err 原样向前端返回,React Query 的 onError 不会被吞掉。
#[tauri::command]
pub async fn get_subscription_quota(tool: String) -> Result<SubscriptionQuota, String> {
crate::services::subscription::get_subscription_quota(&tool).await
pub async fn get_subscription_quota(
app: tauri::AppHandle,
state: State<'_, AppState>,
tool: String,
) -> Result<SubscriptionQuota, String> {
let inner = crate::services::subscription::get_subscription_quota(&tool).await;
let snapshot = match &inner {
Ok(q) => q.clone(),
// transport 层 Err —— 凭据状态不明,用 Valid 表达"凭据没问题,是通信/parse 出错"。
Err(err_msg) => SubscriptionQuota::error(&tool, CredentialStatus::Valid, err_msg.clone()),
};
if let Ok(app_type) = AppType::from_str(&tool) {
let payload = serde_json::json!({
"kind": "subscription",
"appType": app_type.as_str(),
"data": &snapshot,
});
if let Err(e) = app.emit("usage-cache-updated", payload) {
log::error!("emit usage-cache-updated (subscription) 失败: {e}");
}
state.usage_cache.put_subscription(app_type, snapshot);
crate::tray::schedule_tray_refresh(&app);
}
inner
}
-341
View File
@@ -72,24 +72,12 @@ fn hermes_write_lock() -> &'static Mutex<()> {
// Type Definitions
// ============================================================================
/// Hermes 健康检查警告
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct HermesHealthWarning {
pub code: String,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
}
/// Hermes 写入结果
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct HermesWriteOutcome {
#[serde(skip_serializing_if = "Option::is_none")]
pub backup_path: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<HermesHealthWarning>,
}
/// Hermes model section config
@@ -343,8 +331,6 @@ fn write_yaml_section_to_config_locked(
atomic_write(&config_path, new_raw.as_bytes())?;
let warnings = scan_hermes_health_internal(&new_raw);
log::debug!(
"Hermes config section '{}' written to {:?}",
section_key,
@@ -352,7 +338,6 @@ fn write_yaml_section_to_config_locked(
);
Ok(HermesWriteOutcome {
backup_path: backup_path.map(|p| p.display().to_string()),
warnings,
})
}
@@ -486,28 +471,6 @@ fn denormalize_provider_models_for_read(config: &mut serde_json::Value) {
}
}
/// Borrow a YAML scalar as a non-empty trimmed `&str`, or `None` when the
/// value is absent, non-string, or blank after trimming.
fn yaml_as_non_empty_str(v: &serde_yaml::Value) -> Option<&str> {
v.as_str().map(str::trim).filter(|s| !s.is_empty())
}
/// Extract string keys from a YAML mapping as owned strings, dropping non-string keys.
fn collect_mapping_string_keys(m: &serde_yaml::Mapping) -> Vec<String> {
m.iter()
.filter_map(|(k, _)| k.as_str().map(str::to_string))
.collect()
}
/// Boilerplate-free constructor for [`HermesHealthWarning`].
fn hermes_warning(code: &str, message: String, path: &str) -> HermesHealthWarning {
HermesHealthWarning {
code: code.to_string(),
message,
path: Some(path.to_string()),
}
}
/// Marker field injected on provider payloads sourced from Hermes v12+
/// `providers:` dict. CC Switch treats those as read-only — writes have to
/// go through Hermes' own Web UI to keep its overlay semantics intact.
@@ -856,160 +819,6 @@ pub fn apply_switch_defaults(
set_model_config(&merged)
}
// ============================================================================
// Health Check
// ============================================================================
/// Scan Hermes config for known configuration hazards.
///
/// Parse failures are reported as warnings (not errors) so the UI can
/// display them without blocking.
pub fn scan_hermes_config_health() -> Result<Vec<HermesHealthWarning>, AppError> {
let path = get_hermes_config_path();
if !path.exists() {
return Ok(Vec::new());
}
let content = fs::read_to_string(&path).map_err(|e| AppError::io(&path, e))?;
Ok(scan_hermes_health_internal(&content))
}
fn scan_hermes_health_internal(content: &str) -> Vec<HermesHealthWarning> {
let mut warnings = Vec::new();
if content.trim().is_empty() {
return warnings;
}
let config = match serde_yaml::from_str::<serde_yaml::Value>(content) {
Ok(cfg) => cfg,
Err(err) => {
warnings.push(hermes_warning(
"config_parse_failed",
format!("Hermes config could not be parsed as YAML: {err}"),
&get_hermes_config_path().display().to_string(),
));
return warnings;
}
};
if let Some(model) = config.get("model") {
if model.get("default").is_none() && model.get("provider").is_none() {
warnings.push(hermes_warning(
"model_no_default",
"No default model or provider configured in 'model' section".to_string(),
"model",
));
}
}
let cp_is_mapping = config
.get("custom_providers")
.map(|v| v.is_mapping())
.unwrap_or(false);
if cp_is_mapping {
warnings.push(hermes_warning(
"custom_providers_not_list",
"custom_providers should be a YAML list (sequence), not a mapping".to_string(),
"custom_providers",
));
}
let mut provider_models: HashMap<String, Vec<String>> = HashMap::new();
let mut name_counts: HashMap<String, usize> = HashMap::new();
let mut base_url_counts: HashMap<String, usize> = HashMap::new();
if let Some(seq) = config.get("custom_providers").and_then(|v| v.as_sequence()) {
for item in seq {
if let Some(name) = item.get("name").and_then(yaml_as_non_empty_str) {
*name_counts.entry(name.to_string()).or_insert(0) += 1;
if let Some(models) = item.get("models").and_then(|m| m.as_mapping()) {
provider_models
.entry(name.to_string())
.or_insert_with(|| collect_mapping_string_keys(models));
}
}
if let Some(url) = item
.get("base_url")
.and_then(|n| n.as_str())
.map(|s| s.trim().trim_end_matches('/').to_lowercase())
.filter(|s| !s.is_empty())
{
*base_url_counts.entry(url).or_insert(0) += 1;
}
}
}
// name_counts keys are unique by construction, so iterating it already
// reports each duplicate name exactly once — no extra dedupe set needed.
for (name, count) in &name_counts {
if *count > 1 {
warnings.push(hermes_warning(
"duplicate_provider_name",
format!(
"Duplicate provider name '{name}' in custom_providers — only one entry will be used"
),
"custom_providers",
));
}
}
for (url, count) in &base_url_counts {
if *count > 1 {
warnings.push(hermes_warning(
"duplicate_provider_base_url",
format!(
"Duplicate base_url '{url}' in custom_providers — possible accidental copy"
),
"custom_providers",
));
}
}
if let Some(model) = config.get("model") {
if let Some(provider_ref) = model.get("provider").and_then(yaml_as_non_empty_str) {
if !name_counts.contains_key(provider_ref) {
warnings.push(hermes_warning(
"model_provider_unknown",
format!(
"model.provider '{provider_ref}' does not match any configured provider"
),
"model.provider",
));
} else if let Some(default) = model.get("default").and_then(yaml_as_non_empty_str) {
if let Some(ids) = provider_models.get(provider_ref) {
if !ids.is_empty() && !ids.iter().any(|id| id == default) {
warnings.push(hermes_warning(
"model_default_not_in_provider",
format!(
"model.default '{default}' is not in provider '{provider_ref}' models list"
),
"model.default",
));
}
}
}
}
}
let version = config
.get("_config_version")
.and_then(|v| v.as_u64())
.unwrap_or(0);
let providers_dict_populated = config
.get("providers")
.and_then(|v| v.as_mapping())
.map(|m| !m.is_empty())
.unwrap_or(false);
if version >= 12 && providers_dict_populated {
warnings.push(hermes_warning(
"schema_migrated_v12",
"Hermes' newer schema moved some entries into the 'providers:' dict. They are shown read-only in CC Switch — edit or remove those entries via Hermes Web UI.".to_string(),
"providers",
));
}
warnings
}
// ============================================================================
// MCP Section Access (for mcp/hermes.rs to use in Phase 4)
// ============================================================================
@@ -1727,45 +1536,6 @@ custom_providers:
});
}
// ---- Health check tests ----
#[test]
fn health_check_on_invalid_yaml() {
let warnings = scan_hermes_health_internal("not: valid: yaml: [");
assert!(!warnings.is_empty());
assert_eq!(warnings[0].code, "config_parse_failed");
}
#[test]
fn health_check_model_no_default() {
let yaml = "model:\n context_length: 200000\n";
let warnings = scan_hermes_health_internal(yaml);
assert!(warnings.iter().any(|w| w.code == "model_no_default"));
}
#[test]
fn health_check_custom_providers_not_list() {
let yaml = "custom_providers:\n foo:\n base_url: http://localhost\n";
let warnings = scan_hermes_health_internal(yaml);
assert!(warnings
.iter()
.any(|w| w.code == "custom_providers_not_list"));
}
#[test]
fn health_check_valid_config() {
let yaml = "\
model:
default: gpt-4
provider: openrouter
custom_providers:
- name: openrouter
base_url: https://openrouter.ai/api/v1
";
let warnings = scan_hermes_health_internal(yaml);
assert!(warnings.is_empty());
}
// ---- yaml_to_json / json_to_yaml ----
#[test]
@@ -2174,115 +1944,4 @@ user_profile_enabled: false
assert_eq!(user, MemoryKind::User);
assert!(serde_json::from_str::<MemoryKind>("\"bogus\"").is_err());
}
// ---- Extended health scan rules ----
#[test]
fn health_check_model_provider_unknown() {
let yaml = "\
model:
default: gpt-4
provider: ghost
custom_providers:
- name: real
base_url: https://real.example.com
";
let warnings = scan_hermes_health_internal(yaml);
assert!(warnings.iter().any(|w| w.code == "model_provider_unknown"));
}
#[test]
fn health_check_model_default_not_in_provider() {
let yaml = "\
model:
default: missing-model
provider: real
custom_providers:
- name: real
base_url: https://real.example.com
models:
present-model: {}
";
let warnings = scan_hermes_health_internal(yaml);
assert!(warnings
.iter()
.any(|w| w.code == "model_default_not_in_provider"));
}
#[test]
fn health_check_duplicate_provider_name() {
let yaml = "\
custom_providers:
- name: twin
base_url: https://a.example.com
- name: twin
base_url: https://b.example.com
";
let warnings = scan_hermes_health_internal(yaml);
let dup_count = warnings
.iter()
.filter(|w| w.code == "duplicate_provider_name")
.count();
assert_eq!(dup_count, 1, "each duplicate name should be reported once");
}
#[test]
fn health_check_duplicate_provider_base_url() {
let yaml = "\
custom_providers:
- name: a
base_url: https://same.example.com/
- name: b
base_url: https://SAME.example.com
";
let warnings = scan_hermes_health_internal(yaml);
assert!(warnings
.iter()
.any(|w| w.code == "duplicate_provider_base_url"));
}
#[test]
fn health_check_schema_migrated_v12_warning() {
let yaml = "\
_config_version: 19
providers:
ds-1:
base_url: https://api.deepseek.com
";
let warnings = scan_hermes_health_internal(yaml);
assert!(warnings.iter().any(|w| w.code == "schema_migrated_v12"));
}
#[test]
fn health_check_schema_migrated_not_reported_when_dict_empty() {
// v19 with empty providers: {} should NOT surface the migration warning —
// otherwise fresh installs would see it spuriously.
let yaml = "\
_config_version: 19
providers: {}
";
let warnings = scan_hermes_health_internal(yaml);
assert!(!warnings.iter().any(|w| w.code == "schema_migrated_v12"));
}
#[test]
fn health_check_valid_config_with_matching_model_and_provider() {
// Regression guard: none of the new rules should fire on a well-formed config.
let yaml = "\
model:
default: gpt-4
provider: openrouter
custom_providers:
- name: openrouter
base_url: https://openrouter.ai/api/v1
models:
gpt-4: {}
";
let warnings = scan_hermes_health_internal(yaml);
assert!(
warnings.is_empty(),
"expected no warnings, got: {:?}",
warnings
);
}
}
+12 -4
View File
@@ -273,6 +273,8 @@ pub fn run() {
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_store::Builder::new().build())
.setup(|app| {
let _ = rustls::crypto::ring::default_provider().install_default();
// 预先刷新 Store 覆盖配置,确保后续路径读取正确(日志/数据库等)
app_store::refresh_app_config_dir_override(app.handle());
panic_hook::init_app_config_dir(crate::config::get_app_config_dir());
@@ -746,9 +748,16 @@ pub fn run() {
// 构建托盘
let mut tray_builder = TrayIconBuilder::with_id(tray::TRAY_ID)
.on_tray_icon_event(|_tray, event| match event {
// 左键点击已通过 show_menu_on_left_click(true) 打开菜单,这里不再额外处理
TrayIconEvent::Click { .. } => {}
.on_tray_icon_event(|tray, event| match event {
// 鼠标悬停/点击到托盘图标时,后台异步刷新用量缓存,
// 让用户下一次(或快速打开菜单的那一刻)看到较新的数字。
// refresh_all_usage_in_tray 内部有 10 秒防抖。
TrayIconEvent::Enter { .. } | TrayIconEvent::Click { .. } => {
let app = tray.app_handle().clone();
tauri::async_runtime::spawn(async move {
crate::tray::refresh_all_usage_in_tray(&app).await;
});
}
_ => log::debug!("unhandled event {event:?}"),
})
.menu(&menu)
@@ -1255,7 +1264,6 @@ pub fn run() {
commands::import_hermes_providers_from_live,
commands::get_hermes_live_provider_ids,
commands::get_hermes_live_provider,
commands::scan_hermes_config_health,
commands::get_hermes_model_config,
commands::open_hermes_web_ui,
commands::launch_hermes_dashboard,
+30 -1
View File
@@ -65,6 +65,25 @@ impl Provider {
in_failover_queue: false,
}
}
pub fn is_codex_oauth(&self) -> bool {
self.meta.as_ref().and_then(|m| m.provider_type.as_deref()) == Some("codex_oauth")
}
pub fn codex_fast_mode_enabled(&self) -> bool {
self.meta
.as_ref()
.map(|m| m.codex_fast_mode_enabled())
.unwrap_or(false)
}
pub fn has_usage_script_enabled(&self) -> bool {
self.meta
.as_ref()
.and_then(|m| m.usage_script.as_ref())
.map(|s| s.enabled)
.unwrap_or(false)
}
}
/// 供应商管理器
@@ -258,9 +277,13 @@ pub struct ProviderMeta {
pub is_full_url: Option<bool>,
/// Prompt cache key for OpenAI Responses-compatible endpoints.
/// When set, injected into converted Responses requests to improve cache hit rate.
/// If not set, provider ID is used automatically during Claude -> Responses conversion.
/// If not set, Codex OAuth uses the current session ID; other Claude -> Responses
/// conversions fall back to provider ID.
#[serde(rename = "promptCacheKey", skip_serializing_if = "Option::is_none")]
pub prompt_cache_key: Option<String>,
/// Codex OAuth FAST mode: inject `service_tier = "priority"` for ChatGPT Codex requests.
#[serde(rename = "codexFastMode", skip_serializing_if = "Option::is_none")]
pub codex_fast_mode: Option<bool>,
/// 累加模式应用中,该 provider 是否已写入 live config。
/// `None` 表示旧数据/未知状态,`Some(false)` 表示明确仅存在于数据库中。
#[serde(rename = "liveConfigManaged", skip_serializing_if = "Option::is_none")]
@@ -276,6 +299,12 @@ pub struct ProviderMeta {
}
impl ProviderMeta {
/// Codex OAuth FAST mode 是否启用。默认关闭,因为 `service_tier="priority"`
/// 会按更高速率消耗 ChatGPT 订阅配额,用户需显式开启以换取更低延迟。
pub fn codex_fast_mode_enabled(&self) -> bool {
self.codex_fast_mode.unwrap_or(false)
}
/// 解析指定托管认证供应商绑定的账号 ID。
///
/// 新版优先读取 authBinding,旧版继续兼容 githubAccountId。
+65 -1
View File
@@ -55,6 +55,8 @@ pub struct RequestForwarder {
current_provider_id_at_start: String,
/// 代理会话 ID(用于 Gemini Native shadow replay
session_id: String,
/// Session ID 是否由客户端提供;生成值不能作为上游缓存身份。
session_client_provided: bool,
/// 整流器配置
rectifier_config: RectifierConfig,
/// 优化器配置
@@ -77,6 +79,7 @@ impl RequestForwarder {
app_handle: Option<tauri::AppHandle>,
current_provider_id_at_start: String,
session_id: String,
session_client_provided: bool,
_streaming_first_byte_timeout: u64,
_streaming_idle_timeout: u64,
rectifier_config: RectifierConfig,
@@ -92,6 +95,7 @@ impl RequestForwarder {
app_handle,
current_provider_id_at_start,
session_id,
session_client_provided,
rectifier_config,
optimizer_config,
copilot_optimizer_config,
@@ -966,7 +970,8 @@ impl RequestForwarder {
mapped_body,
provider,
api_format,
Some(&self.session_id),
self.session_client_provided
.then_some(self.session_id.as_str()),
Some(self.gemini_shadow.as_ref()),
)?
} else {
@@ -984,6 +989,7 @@ impl RequestForwarder {
// Codex OAuth 需要注入的 ChatGPT-Account-Id(在动态 token 获取期间填充)
let mut codex_oauth_account_id: Option<String> = None;
let mut should_send_codex_oauth_session_headers = false;
// 获取认证头(提前准备,用于内联替换)
let mut auth_headers = if let Some(mut auth) = adapter.extract_auth(provider) {
@@ -1065,6 +1071,7 @@ impl RequestForwarder {
match token_result {
Ok(token) => {
auth = AuthInfo::new(token, AuthStrategy::CodexOAuth);
should_send_codex_oauth_session_headers = true;
// 解析使用的 account_id(用于注入 ChatGPT-Account-Id header
codex_oauth_account_id = match account_id {
Some(id) => Some(id),
@@ -1102,6 +1109,13 @@ impl RequestForwarder {
}
}
let codex_oauth_session_headers =
if should_send_codex_oauth_session_headers && self.session_client_provided {
build_codex_oauth_session_headers(&self.session_id)
} else {
Vec::new()
};
// --- Copilot 优化器:动态 header 注入 ---
if let Some((ref classification, ref det_request_id, ref interaction_id)) =
copilot_optimization
@@ -1342,6 +1356,12 @@ impl RequestForwarder {
);
}
// Codex OAuth 反代尽量对齐官方 Codex CLI 的会话路由信号。
// 只发送客户端提供的 session_id;生成的 UUID 每次不同,反而会破坏前缀缓存。
for (name, value) in codex_oauth_session_headers {
ordered_headers.insert(name, value);
}
// 序列化请求体
let body_bytes = serde_json::to_vec(&filtered_body)
.map_err(|e| ProxyError::Internal(format!("Failed to serialize request body: {e}")))?;
@@ -1773,6 +1793,28 @@ fn append_query_to_full_url(base_url: &str, query: Option<&str>) -> String {
}
}
fn build_codex_oauth_session_headers(
session_id: &str,
) -> Vec<(http::HeaderName, http::HeaderValue)> {
let session_id = session_id.trim();
if session_id.is_empty() {
return Vec::new();
}
let mut headers = Vec::new();
if let Ok(value) = http::HeaderValue::from_str(session_id) {
headers.push((http::HeaderName::from_static("session_id"), value.clone()));
headers.push((http::HeaderName::from_static("x-client-request-id"), value));
}
let window_id = format!("{session_id}:0");
if let Ok(value) = http::HeaderValue::from_str(&window_id) {
headers.push((http::HeaderName::from_static("x-codex-window-id"), value));
}
headers
}
fn should_force_identity_encoding(
endpoint: &str,
body: &Value,
@@ -1882,6 +1924,28 @@ mod tests {
assert_eq!(summary, "line1 line2...");
}
#[test]
fn codex_oauth_session_headers_match_codex_cache_identity() {
let headers = build_codex_oauth_session_headers("session-123");
let mut map = HeaderMap::new();
for (name, value) in headers {
map.insert(name, value);
}
assert_eq!(
map.get("session_id"),
Some(&HeaderValue::from_static("session-123"))
);
assert_eq!(
map.get("x-client-request-id"),
Some(&HeaderValue::from_static("session-123"))
);
assert_eq!(
map.get("x-codex-window-id"),
Some(&HeaderValue::from_static("session-123:0"))
);
}
#[test]
fn rewrite_claude_transform_endpoint_strips_beta_for_chat_completions() {
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
+4
View File
@@ -57,6 +57,8 @@ pub struct RequestContext {
pub app_type: AppType,
/// Session ID(从客户端请求提取或新生成)
pub session_id: String,
/// Session ID 是否由客户端提供。生成的 UUID 不能作为上游缓存 key,否则每个请求都会换 key。
pub session_client_provided: bool,
/// 整流器配置
pub rectifier_config: RectifierConfig,
/// 优化器配置
@@ -161,6 +163,7 @@ impl RequestContext {
app_type_str,
app_type,
session_id,
session_client_provided: session_result.client_provided,
rectifier_config,
optimizer_config,
copilot_optimizer_config,
@@ -223,6 +226,7 @@ impl RequestContext {
state.app_handle.clone(),
self.current_provider_id.clone(),
self.session_id.clone(),
self.session_client_provided,
first_byte_timeout,
idle_timeout,
self.rectifier_config.clone(),
+205 -5
View File
@@ -25,6 +25,7 @@ use super::{
SseUsageCollector,
},
server::ProxyState,
sse::{strip_sse_field, take_sse_block},
types::*,
usage::parser::TokenUsage,
ProxyError,
@@ -151,10 +152,33 @@ async fn handle_claude_transform(
api_format: &str,
) -> Result<axum::response::Response, ProxyError> {
let status = response.status();
let is_codex_oauth = ctx
.provider
.meta
.as_ref()
.and_then(|meta| meta.provider_type.as_deref())
== Some("codex_oauth");
// Codex OAuth 会把 openai_responses 响应强制升级为 SSE,即使客户端发的是 stream:false。
// should_use_claude_transform_streaming 默认会把这个组合路由到流式转换器——虽然能避免
// JSON parse 报 422,但会让非流客户端收到 text/event-stream,违反 Anthropic 非流语义。
// 这里为这个特定组合打开 override:把上游 SSE 聚合成 Anthropic JSON 回给客户端,其它
// 场景(任意上游 is_sse、非 Codex OAuth 等)仍沿用原有流式兜底。
let aggregate_codex_oauth_responses_sse =
!is_stream && is_codex_oauth && api_format == "openai_responses";
let use_streaming = if aggregate_codex_oauth_responses_sse {
false
} else {
should_use_claude_transform_streaming(
is_stream,
response.is_sse(),
api_format,
is_codex_oauth,
)
};
let tool_schema_hints = transform_gemini::extract_anthropic_tool_schema_hints(original_body);
let tool_schema_hints = (!tool_schema_hints.is_empty()).then_some(tool_schema_hints);
if is_stream {
if use_streaming {
// 根据 api_format 选择流式转换器
let stream = response.bytes_stream();
let sse_stream: Box<
@@ -245,10 +269,14 @@ async fn handle_claude_transform(
let body_str = String::from_utf8_lossy(&body_bytes);
let upstream_response: Value = serde_json::from_slice(&body_bytes).map_err(|e| {
log::error!("[Claude] 解析上游响应失败: {e}, body: {body_str}");
ProxyError::TransformError(format!("Failed to parse upstream response: {e}"))
})?;
let upstream_response: Value = if aggregate_codex_oauth_responses_sse {
responses_sse_to_response_value(&body_str)?
} else {
serde_json::from_slice(&body_bytes).map_err(|e| {
log::error!("[Claude] 解析上游响应失败: {e}, body: {body_str}");
ProxyError::TransformError(format!("Failed to parse upstream response: {e}"))
})?
};
// 根据 api_format 选择非流式转换器
let anthropic_response = if api_format == "openai_responses" {
@@ -561,6 +589,87 @@ pub async fn handle_gemini(
process_response(response, &ctx, &state, &GEMINI_PARSER_CONFIG).await
}
fn should_use_claude_transform_streaming(
requested_streaming: bool,
upstream_is_sse: bool,
api_format: &str,
is_codex_oauth: bool,
) -> bool {
requested_streaming || upstream_is_sse || (is_codex_oauth && api_format == "openai_responses")
}
/// 把 OpenAI Responses SSE 流聚合成一个完整的 Responses JSON 对象,供下游转成 Anthropic
/// 非流响应。仅在 Codex OAuth 把 `stream:false` 强制升级为 SSE 的场景下调用。
///
/// 复用 `proxy::sse` 的 `take_sse_block`/`strip_sse_field``take_sse_block` 同时支持
/// `\n\n` 与 `\r\n\r\n` 两种分隔符,`strip_sse_field` 兼容带/不带空格的字段写法。
fn responses_sse_to_response_value(body: &str) -> Result<Value, ProxyError> {
let mut buffer = body.to_string();
let mut completed_response: Option<Value> = None;
let mut output_items = Vec::new();
while let Some(block) = take_sse_block(&mut buffer) {
let mut event_name = "";
let mut data_lines: Vec<&str> = Vec::new();
for line in block.lines() {
if let Some(evt) = strip_sse_field(line, "event") {
event_name = evt.trim();
} else if let Some(d) = strip_sse_field(line, "data") {
data_lines.push(d);
}
}
if data_lines.is_empty() {
continue;
}
let data_str = data_lines.join("\n");
if data_str.trim() == "[DONE]" {
continue;
}
let data: Value = serde_json::from_str(&data_str).map_err(|e| {
ProxyError::TransformError(format!("Failed to parse upstream SSE event: {e}"))
})?;
match event_name {
"response.output_item.done" => {
if let Some(item) = data.get("item") {
output_items.push(item.clone());
}
}
"response.completed" => {
completed_response = Some(data.get("response").cloned().unwrap_or(data));
}
"response.failed" => {
let message = data
.pointer("/response/error/message")
.and_then(|v| v.as_str())
.unwrap_or("response.failed event received");
return Err(ProxyError::TransformError(message.to_string()));
}
_ => {}
}
}
let mut response = completed_response.ok_or_else(|| {
ProxyError::TransformError("No response.completed event in upstream SSE".to_string())
})?;
if !output_items.is_empty() {
if let Some(obj) = response.as_object_mut() {
obj.insert("output".to_string(), Value::Array(output_items));
} else {
return Err(ProxyError::TransformError(
"response.completed payload is not an object".to_string(),
));
}
}
Ok(response)
}
// ============================================================================
// 使用量记录(保留用于 Claude 转换逻辑)
// ============================================================================
@@ -641,3 +750,94 @@ async fn log_usage(
log::warn!("[USG-001] 记录使用量失败: {e}");
}
}
#[cfg(test)]
mod tests {
use super::{responses_sse_to_response_value, should_use_claude_transform_streaming};
use crate::proxy::ProxyError;
#[test]
fn codex_oauth_responses_force_streaming_even_if_client_sent_false() {
assert!(should_use_claude_transform_streaming(
false,
false,
"openai_responses",
true,
));
}
#[test]
fn upstream_sse_response_always_uses_streaming_path() {
assert!(should_use_claude_transform_streaming(
false,
true,
"openai_chat",
false,
));
}
#[test]
fn non_streaming_response_stays_non_streaming_for_regular_openai_responses() {
assert!(!should_use_claude_transform_streaming(
false,
false,
"openai_responses",
false,
));
}
#[test]
fn responses_sse_to_response_value_collects_output_items() {
let sse = r#"event: response.output_item.done
data: {"type":"response.output_item.done","item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hello"}]}}
event: response.completed
data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","model":"gpt-5.4","output":[],"usage":{"input_tokens":10,"output_tokens":2}}}
"#;
let response = responses_sse_to_response_value(sse).unwrap();
assert_eq!(response["id"], "resp_1");
assert_eq!(response["output"][0]["type"], "message");
assert_eq!(response["output"][0]["content"][0]["text"], "hello");
}
#[test]
fn responses_sse_to_response_value_handles_crlf_delimiters() {
// 真实 HTTP SSE 按规范使用 \r\n\r\n 分隔事件;take_sse_block 必须同时处理两种分隔符,
// 否则此路径在任何标准上游(含 Codex OAuth HTTPS 后端)下都会 TransformError。
let sse = "event: response.output_item.done\r\n\
data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"hi\"}]}}\r\n\
\r\n\
event: response.completed\r\n\
data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_crlf\",\"status\":\"completed\",\"model\":\"gpt-5.4\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":1}}}\r\n\
\r\n";
let response = responses_sse_to_response_value(sse).unwrap();
assert_eq!(response["id"], "resp_crlf");
assert_eq!(response["output"][0]["type"], "message");
assert_eq!(response["output"][0]["content"][0]["text"], "hi");
}
#[test]
fn responses_sse_to_response_value_returns_err_on_response_failed() {
let sse = "event: response.failed\n\
data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"message\":\"upstream blew up\"}}}\n\n";
let err = responses_sse_to_response_value(sse).unwrap_err();
match err {
ProxyError::TransformError(msg) => assert!(msg.contains("upstream blew up")),
other => panic!("expected TransformError, got {other:?}"),
}
}
#[test]
fn responses_sse_to_response_value_errors_when_no_completed_event() {
let sse = "event: response.output_item.done\n\
data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"message\"}}\n\n";
assert!(responses_sse_to_response_value(sse).is_err());
}
}
+157 -14
View File
@@ -89,6 +89,8 @@ pub fn transform_claude_request_for_api_format(
session_id: Option<&str>,
shadow_store: Option<&super::gemini_shadow::GeminiShadowStore>,
) -> Result<serde_json::Value, ProxyError> {
let is_codex_oauth = provider.is_codex_oauth();
// Copilot 场景:优先从 metadata.user_id 提取 session ID 作为 cache key
// 格式: "uuid_sessionId" → 提取 "_" 后面的部分作为 session 标识
// 同一会话的请求共享 cache key,提升 Copilot 缓存命中率
@@ -118,32 +120,39 @@ pub fn transform_claude_request_for_api_format(
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
})
} else if is_codex_oauth {
session_id
.map(str::trim)
.filter(|s| !s.is_empty())
.map(ToString::to_string)
} else {
None
};
let cache_key = session_cache_key
.as_deref()
.or_else(|| {
provider
.meta
.as_ref()
.and_then(|m| m.prompt_cache_key.as_deref())
})
.unwrap_or(&provider.id);
let explicit_cache_key = provider
.meta
.as_ref()
.and_then(|m| m.prompt_cache_key.as_deref());
let cache_key = if is_codex_oauth {
explicit_cache_key
.or(session_cache_key.as_deref())
.unwrap_or(&provider.id)
} else {
session_cache_key
.as_deref()
.or(explicit_cache_key)
.unwrap_or(&provider.id)
};
match api_format {
"openai_responses" => {
// Codex OAuth (ChatGPT Plus/Pro 反代) 需要在请求体里强制 store: false
// + include: ["reasoning.encrypted_content"],由 transform 层统一处理。
let is_codex_oauth = provider
.meta
.as_ref()
.and_then(|m| m.provider_type.as_deref())
== Some("codex_oauth");
let codex_fast_mode = provider.codex_fast_mode_enabled();
super::transform_responses::anthropic_to_responses(
body,
Some(cache_key),
is_codex_oauth,
codex_fast_mode,
)
}
"openai_chat" => {
@@ -1222,6 +1231,140 @@ mod tests {
assert!(transformed.get("max_output_tokens").is_some());
}
#[test]
fn test_transform_claude_request_for_codex_oauth_uses_session_cache_key() {
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://chatgpt.com/backend-api/codex"
}
}),
ProviderMeta {
api_format: Some("openai_responses".to_string()),
provider_type: Some("codex_oauth".to_string()),
..ProviderMeta::default()
},
);
let body = json!({
"model": "gpt-5.4",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 128
});
let transformed = transform_claude_request_for_api_format(
body,
&provider,
"openai_responses",
Some("session-123"),
None,
)
.unwrap();
assert_eq!(transformed["prompt_cache_key"], "session-123");
}
#[test]
fn test_transform_claude_request_for_codex_oauth_without_session_falls_back_to_provider_id() {
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://chatgpt.com/backend-api/codex"
}
}),
ProviderMeta {
api_format: Some("openai_responses".to_string()),
provider_type: Some("codex_oauth".to_string()),
..ProviderMeta::default()
},
);
let body = json!({
"model": "gpt-5.4",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 128
});
let transformed = transform_claude_request_for_api_format(
body,
&provider,
"openai_responses",
None,
None,
)
.unwrap();
assert_eq!(transformed["prompt_cache_key"], provider.id);
}
#[test]
fn test_transform_claude_request_for_codex_oauth_keeps_explicit_cache_key() {
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://chatgpt.com/backend-api/codex"
}
}),
ProviderMeta {
api_format: Some("openai_responses".to_string()),
provider_type: Some("codex_oauth".to_string()),
prompt_cache_key: Some("explicit-cache-key".to_string()),
..ProviderMeta::default()
},
);
let body = json!({
"model": "gpt-5.4",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 128
});
let transformed = transform_claude_request_for_api_format(
body,
&provider,
"openai_responses",
Some("session-123"),
None,
)
.unwrap();
assert_eq!(transformed["prompt_cache_key"], "explicit-cache-key");
}
#[test]
fn test_transform_claude_request_for_api_format_codex_oauth_fast_mode_off() {
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://chatgpt.com/backend-api/codex"
}
}),
ProviderMeta {
provider_type: Some("codex_oauth".to_string()),
codex_fast_mode: Some(false),
..ProviderMeta::default()
},
);
let body = json!({
"model": "gpt-5.4",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 128
});
let transformed = transform_claude_request_for_api_format(
body,
&provider,
"openai_responses",
None,
None,
)
.unwrap();
assert_eq!(transformed["store"], json!(false));
assert!(transformed.get("service_tier").is_none());
assert_eq!(
transformed["include"],
json!(["reasoning.encrypted_content"])
);
}
#[test]
fn test_transform_claude_request_for_api_format_gemini_native() {
let provider = create_provider_with_meta(
@@ -17,10 +17,13 @@ use serde_json::{json, Value};
/// `is_codex_oauth`: 当目标后端是 ChatGPT Plus/Pro 反代 (`chatgpt.com/backend-api/codex`) 时为 true。
/// 该后端强制要求 `store: false`,并要求 `include` 包含 `reasoning.encrypted_content`
/// 以便在无服务端状态下保持多轮 reasoning 上下文。
/// `codex_fast_mode`: 仅在 `is_codex_oauth` 为 true 时生效,控制是否注入
/// `service_tier = "priority"`。
pub fn anthropic_to_responses(
body: Value,
cache_key: Option<&str>,
is_codex_oauth: bool,
codex_fast_mode: bool,
) -> Result<Value, ProxyError> {
let mut result = json!({});
@@ -125,10 +128,15 @@ pub fn anthropic_to_responses(
// (codex-rs 结构体根本没有这三个字段,OpenAI 自己的客户端不发它们)
// - instructions / tools / parallel_tool_calls: 必填字段,缺则兜底默认值
// cc-switch 的 transform 当前是"条件写入",可能产生缺失)
// - service_tier: 仅在 FAST mode 开启时写入 "priority"
// (与 OpenAI 官方 codex-rs 当前请求结构保持一致)
// - stream: 必须永远 truecodex-rs 硬编码 true,且 cc-switch 的
// SSE 解析层只处理流式响应,强制覆盖避免客户端误传 false)
if is_codex_oauth {
result["store"] = json!(false);
if codex_fast_mode {
result["service_tier"] = json!("priority");
}
const REASONING_MARKER: &str = "reasoning.encrypted_content";
let mut includes: Vec<Value> = body
@@ -520,7 +528,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["model"], "gpt-4o");
assert_eq!(result["max_output_tokens"], 1024);
assert_eq!(result["input"][0]["role"], "user");
@@ -539,7 +547,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["instructions"], "You are a helpful assistant.");
// system should not appear in input
assert_eq!(result["input"].as_array().unwrap().len(), 1);
@@ -557,7 +565,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["instructions"], "Part 1\n\nPart 2");
}
@@ -574,7 +582,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["tools"][0]["type"], "function");
assert_eq!(result["tools"][0]["name"], "get_weather");
assert!(result["tools"][0].get("parameters").is_some());
@@ -591,7 +599,7 @@ mod tests {
"tool_choice": {"type": "any"}
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["tool_choice"], "required");
}
@@ -604,7 +612,7 @@ mod tests {
"tool_choice": {"type": "tool", "name": "get_weather"}
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["tool_choice"]["type"], "function");
assert_eq!(result["tool_choice"]["name"], "get_weather");
}
@@ -623,7 +631,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
let input_arr = result["input"].as_array().unwrap();
// Should produce: assistant message (text) + function_call item
@@ -653,7 +661,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
let input_arr = result["input"].as_array().unwrap();
// Should produce: function_call_output item (lifted)
@@ -677,7 +685,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
let input_arr = result["input"].as_array().unwrap();
// thinking should be discarded, only text remains
@@ -700,7 +708,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
let content = result["input"][0]["content"].as_array().unwrap();
assert_eq!(content[0]["type"], "input_text");
@@ -858,7 +866,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["model"], "o3-mini");
}
@@ -870,7 +878,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, Some("my-provider-id"), false).unwrap();
let result = anthropic_to_responses(input, Some("my-provider-id"), false, false).unwrap();
assert_eq!(result["prompt_cache_key"], "my-provider-id");
}
@@ -888,7 +896,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert!(result["tools"][0].get("cache_control").is_none());
}
@@ -905,7 +913,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert!(result["input"][0]["content"][0]
.get("cache_control")
.is_none());
@@ -967,7 +975,7 @@ mod tests {
"max_tokens": 4096,
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["max_output_tokens"], 4096);
assert!(result.get("max_completion_tokens").is_none());
}
@@ -981,7 +989,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "xhigh");
}
@@ -995,7 +1003,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "low");
}
@@ -1008,7 +1016,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "low");
}
@@ -1021,7 +1029,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "medium");
}
@@ -1034,7 +1042,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "high");
}
@@ -1047,7 +1055,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "xhigh");
}
@@ -1060,7 +1068,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert!(result.get("reasoning").is_none());
}
@@ -1074,10 +1082,11 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
// store 必须显式为 falseChatGPT 后端拒绝 true
assert_eq!(result["store"], json!(false));
assert_eq!(result["service_tier"], json!("priority"));
// include 必须包含 reasoning.encrypted_content(无服务端状态下保持多轮 reasoning)
assert_eq!(result["include"], json!(["reasoning.encrypted_content"]));
@@ -1093,9 +1102,10 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert!(result.get("store").is_none());
assert!(result.get("service_tier").is_none());
assert!(result.get("include").is_none());
}
@@ -1109,7 +1119,7 @@ mod tests {
"include": ["something.else", "reasoning.encrypted_content"]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
let includes = result["include"]
.as_array()
.expect("include should be array");
@@ -1130,6 +1140,21 @@ mod tests {
assert_eq!(marker_count, 1, "marker 不应被重复添加(idempotent 失败)");
}
#[test]
fn test_anthropic_to_responses_codex_oauth_fast_mode_can_be_disabled() {
let input = json!({
"model": "gpt-5-codex",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true, false).unwrap();
assert_eq!(result["store"], json!(false));
assert!(result.get("service_tier").is_none());
assert_eq!(result["include"], json!(["reasoning.encrypted_content"]));
}
#[test]
fn test_anthropic_to_responses_codex_oauth_strips_max_output_tokens() {
// ChatGPT Plus/Pro 反代不接受 max_output_tokensOpenAI 官方 codex-rs 的
@@ -1141,7 +1166,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert!(
result.get("max_output_tokens").is_none(),
@@ -1159,7 +1184,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["max_output_tokens"], json!(1024));
}
@@ -1177,7 +1202,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert!(
result.get("temperature").is_none(),
@@ -1195,7 +1220,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert!(
result.get("top_p").is_none(),
@@ -1212,7 +1237,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert_eq!(
result["instructions"],
@@ -1246,7 +1271,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert_eq!(
result["instructions"],
@@ -1270,7 +1295,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert_eq!(
result["stream"],
@@ -1291,7 +1316,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["temperature"], json!(0.7));
assert_eq!(result["top_p"], json!(0.9));
@@ -1307,7 +1332,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert!(
result.get("parallel_tool_calls").is_none(),
+2
View File
@@ -16,6 +16,7 @@ pub mod skill;
pub mod speedtest;
pub mod stream_check;
pub mod subscription;
pub mod usage_cache;
pub mod usage_stats;
pub mod webdav;
pub mod webdav_auto_sync;
@@ -30,6 +31,7 @@ pub use proxy::ProxyService;
#[allow(unused_imports)]
pub use skill::{DiscoverableSkill, Skill, SkillRepo, SkillService};
pub use speedtest::{EndpointLatency, SpeedtestService};
pub use usage_cache::UsageCache;
#[allow(unused_imports)]
pub use usage_stats::{
DailyStats, LogFilters, ModelStats, PaginatedLogs, ProviderLimitStatus, ProviderStats,
+105 -41
View File
@@ -672,36 +672,16 @@ impl SkillService {
repo_branch = used_branch;
// 复制到 SSOT
let mut source = temp_dir.join(&source_rel);
if !source.exists() {
// 回退:在 temp_dir 中递归查找名称匹配的目录(含 SKILL.md)
let target_name = source_rel
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
if let Some(found) = Self::find_skill_dir_by_name(&temp_dir, &target_name) {
log::info!(
"Skill directory '{}' not found at direct path, using fallback: {}",
target_name,
found.display()
);
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 {
let source =
Self::resolve_skill_source_dir(&temp_dir, &skill.directory).ok_or_else(|| {
let missing = temp_dir.join(&source_rel).display().to_string();
let _ = fs::remove_dir_all(&temp_dir);
return Err(anyhow!(format_skill_error(
anyhow!(format_skill_error(
"SKILL_DIR_NOT_FOUND",
&[("path", &source.display().to_string())],
&[("path", &missing)],
Some("checkRepoUrl"),
)));
}
}
))
})?;
let canonical_temp = temp_dir.canonicalize().unwrap_or_else(|_| temp_dir.clone());
let canonical_source = source.canonicalize().map_err(|_| {
@@ -954,14 +934,13 @@ impl SkillService {
});
let remote_skill_dir = match remote_match {
Some(rs) => temp_dir.join(&rs.directory),
Some(rs) => match Self::resolve_skill_source_dir(&temp_dir, &rs.directory) {
Some(path) => path,
None => continue,
},
None => continue,
};
if !remote_skill_dir.exists() {
continue;
}
let remote_hash = match Self::compute_dir_hash(&remote_skill_dir) {
Ok(h) => h,
Err(e) => {
@@ -1065,15 +1044,16 @@ impl SkillService {
))
})?;
let source = temp_dir.join(&remote_match.directory);
if !source.exists() {
let _ = fs::remove_dir_all(&temp_dir);
return Err(anyhow!(format_skill_error(
"SKILL_DIR_NOT_FOUND",
&[("path", &source.display().to_string())],
Some("checkRepoUrl"),
)));
}
let source = Self::resolve_skill_source_dir(&temp_dir, &remote_match.directory)
.ok_or_else(|| {
let missing = temp_dir.join(&remote_match.directory).display().to_string();
let _ = fs::remove_dir_all(&temp_dir);
anyhow!(format_skill_error(
"SKILL_DIR_NOT_FOUND",
&[("path", &missing)],
Some("checkRepoUrl"),
))
})?;
// 备份旧文件
let _ = Self::create_uninstall_backup(&skill);
@@ -2108,6 +2088,40 @@ impl SkillService {
walk(root, target_name, 0)
}
/// 将 discoverable skill 的目录信息重新解析为解压目录中的真实源目录。
///
/// 兼容三种情况:
/// 1. `skills/foo` 这类直接相对路径;
/// 2. 仅持有安装名 `foo`,需要在仓库中递归查找真实目录;
/// 3. 仓库根目录本身就是 skill,此时回退到解压根目录。
fn resolve_skill_source_dir(root: &Path, raw_directory: &str) -> Option<PathBuf> {
let source_rel = Self::sanitize_skill_source_path(raw_directory)?;
let direct = root.join(&source_rel);
if direct.is_dir() {
return Some(direct);
}
let target_name = source_rel.file_name()?.to_string_lossy().to_string();
if let Some(found) = Self::find_skill_dir_by_name(root, &target_name) {
log::info!(
"Skill directory '{}' not found at direct path, using fallback: {}",
target_name,
found.display()
);
return Some(found);
}
if root.is_dir() && root.join("SKILL.md").exists() {
log::info!(
"Skill directory '{}' not found, but SKILL.md exists at root, using repo root",
target_name,
);
return Some(root.to_path_buf());
}
None
}
/// 去重技能列表(基于完整 key,不同仓库的同名 skill 分开显示)
fn deduplicate_discoverable_skills(skills: &mut Vec<DiscoverableSkill>) {
let mut seen = HashMap::new();
@@ -2975,3 +2989,53 @@ pub fn migrate_skills_to_ssot(db: &Arc<Database>) -> Result<usize> {
Ok(count)
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
fn write_skill(dir: &Path, name: &str) {
fs::create_dir_all(dir).expect("create skill dir");
fs::write(
dir.join("SKILL.md"),
format!("---\nname: {name}\ndescription: Test skill\n---\n"),
)
.expect("write SKILL.md");
}
#[test]
fn resolve_skill_source_dir_returns_repo_root_for_root_level_skill() {
let temp = tempdir().expect("tempdir");
write_skill(temp.path(), "Root Skill");
let resolved = SkillService::resolve_skill_source_dir(temp.path(), "last30days-skill-cn")
.expect("root-level skill should resolve to the extracted repo root");
assert_eq!(resolved, temp.path());
}
#[test]
fn resolve_skill_source_dir_returns_direct_nested_directory_when_present() {
let temp = tempdir().expect("tempdir");
let nested = temp.path().join("skills").join("nested-skill");
write_skill(&nested, "Nested Skill");
let resolved = SkillService::resolve_skill_source_dir(temp.path(), "skills/nested-skill")
.expect("nested skill should resolve from its relative source path");
assert_eq!(resolved, nested);
}
#[test]
fn resolve_skill_source_dir_falls_back_to_matching_install_name() {
let temp = tempdir().expect("tempdir");
let nested = temp.path().join("skills").join("nested-skill");
write_skill(&nested, "Nested Skill");
let resolved = SkillService::resolve_skill_source_dir(temp.path(), "nested-skill")
.expect("install name should fall back to the matching discovered skill directory");
assert_eq!(resolved, nested);
}
}
+14 -12
View File
@@ -3,7 +3,6 @@
//! 使用流式 API 进行快速健康检查,只需接收首个 chunk 即判定成功。
use futures::StreamExt;
use regex::Regex;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -356,15 +355,17 @@ impl StreamCheckService {
});
// Codex OAuth (ChatGPT Plus/Pro 反代) 需要 store:false + include 标记,
// 否则 Stream Check 会和生产路径一样被服务端 400 拒绝。
let is_codex_oauth = provider
.meta
.as_ref()
.and_then(|m| m.provider_type.as_deref())
== Some("codex_oauth");
let is_codex_oauth = provider.is_codex_oauth();
let codex_fast_mode = provider.codex_fast_mode_enabled();
let body = if is_openai_responses {
anthropic_to_responses(anthropic_body, Some(&provider.id), is_codex_oauth)
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
anthropic_to_responses(
anthropic_body,
Some(&provider.id),
is_codex_oauth,
codex_fast_mode,
)
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
} else if is_gemini_native {
anthropic_to_gemini(anthropic_body)
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
@@ -1412,10 +1413,11 @@ impl StreamCheckService {
return None;
}
let re = Regex::new(r#"^model\s*=\s*["']([^"']+)["']"#).ok()?;
re.captures(config_text)
.and_then(|caps| caps.get(1))
.map(|m| m.as_str().trim().to_string())
let table = toml::from_str::<toml::Table>(config_text).ok()?;
table
.get("model")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|value| !value.is_empty())
}
+25 -11
View File
@@ -291,12 +291,26 @@ struct ApiExtraUsage {
currency: Option<String>,
}
/// 已知的 Claude 用量窗口名称
/// 已知的 Claude 用量窗口名称。`QuotaTier::name` 会是其中之一。
pub const TIER_FIVE_HOUR: &str = "five_hour";
pub const TIER_SEVEN_DAY: &str = "seven_day";
pub const TIER_SEVEN_DAY_OPUS: &str = "seven_day_opus";
pub const TIER_SEVEN_DAY_SONNET: &str = "seven_day_sonnet";
/// Coding PlanKimi / MiniMax)的周窗口 tier 名。与 `coding_plan::query_*`
/// 写入、tray 渲染、commands::provider 扁平化三处共用同一标识。
pub const TIER_WEEKLY_LIMIT: &str = "weekly_limit";
/// Gemini 用量分组名称(按模型而非时间窗口)。`classify_gemini_model` 输出。
pub const TIER_GEMINI_PRO: &str = "gemini_pro";
pub const TIER_GEMINI_FLASH: &str = "gemini_flash";
pub const TIER_GEMINI_FLASH_LITE: &str = "gemini_flash_lite";
const KNOWN_TIERS: &[&str] = &[
"five_hour",
"seven_day",
"seven_day_opus",
"seven_day_sonnet",
TIER_FIVE_HOUR,
TIER_SEVEN_DAY,
TIER_SEVEN_DAY_OPUS,
TIER_SEVEN_DAY_SONNET,
];
/// 查询 Claude 官方订阅额度
@@ -993,11 +1007,11 @@ fn extract_project_id(value: &serde_json::Value) -> Option<String> {
/// 将 Gemini 模型 ID 分类为 Pro / Flash / Flash Lite
fn classify_gemini_model(model_id: &str) -> &str {
if model_id.contains("flash-lite") {
"gemini_flash_lite"
TIER_GEMINI_FLASH_LITE
} else if model_id.contains("flash") {
"gemini_flash"
TIER_GEMINI_FLASH
} else if model_id.contains("pro") {
"gemini_pro"
TIER_GEMINI_PRO
} else {
model_id
}
@@ -1152,9 +1166,9 @@ async fn query_gemini_quota(access_token: &str) -> SubscriptionQuota {
// 转换为 tiersremainingFraction → utilization: 已用百分比)
let sort_order = |name: &str| -> usize {
match name {
"gemini_pro" => 0,
"gemini_flash" => 1,
"gemini_flash_lite" => 2,
TIER_GEMINI_PRO => 0,
TIER_GEMINI_FLASH => 1,
TIER_GEMINI_FLASH_LITE => 2,
_ => 3,
}
};
+143
View File
@@ -0,0 +1,143 @@
//! 托盘展示用的用量缓存(进程内、写穿式)。
//!
//! 各 usage 查询命令成功时写入;系统托盘构建菜单时读取。不持久化,
//! 进程重启即空,由下一次自动查询或托盘悬停触发的刷新重新填充。
use std::collections::HashMap;
use std::sync::RwLock;
use crate::app_config::AppType;
use crate::provider::UsageResult;
use crate::services::subscription::SubscriptionQuota;
#[derive(Default)]
pub struct UsageCache {
subscription: RwLock<HashMap<AppType, SubscriptionQuota>>,
script: RwLock<HashMap<(AppType, String), UsageResult>>,
}
impl UsageCache {
pub fn new() -> Self {
Self::default()
}
pub fn put_subscription(&self, app_type: AppType, quota: SubscriptionQuota) {
if let Ok(mut w) = self.subscription.write() {
w.insert(app_type, quota);
}
}
pub fn put_script(&self, app_type: AppType, provider_id: String, result: UsageResult) {
if let Ok(mut w) = self.script.write() {
w.insert((app_type, provider_id), result);
}
}
/// 以借用形式暴露订阅快照,避免托盘每次重建时深拷贝整个 `SubscriptionQuota`。
pub fn with_subscription<R>(
&self,
app_type: &AppType,
f: impl FnOnce(&SubscriptionQuota) -> R,
) -> Option<R> {
self.subscription
.read()
.ok()
.and_then(|r| r.get(app_type).map(f))
}
/// 以借用形式暴露脚本型用量结果,同上。
pub fn with_script<R>(
&self,
app_type: &AppType,
provider_id: &str,
f: impl FnOnce(&UsageResult) -> R,
) -> Option<R> {
self.script
.read()
.ok()
.and_then(|r| r.get(&(app_type.clone(), provider_id.to_string())).map(f))
}
pub fn invalidate_script(&self, app_type: &AppType, provider_id: &str) {
// 热路径会对每个禁用脚本的 provider 在托盘重建时调用一次:先走读锁
// `contains_key` 快速放行"本来就不在缓存里"的常见情况,避免无谓的写锁升级。
let key = (app_type.clone(), provider_id.to_string());
if !self.script.read().is_ok_and(|r| r.contains_key(&key)) {
return;
}
if let Ok(mut w) = self.script.write() {
w.remove(&key);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::services::subscription::CredentialStatus;
fn fake_quota() -> SubscriptionQuota {
SubscriptionQuota {
tool: "claude".to_string(),
credential_status: CredentialStatus::Valid,
credential_message: None,
success: true,
tiers: vec![],
extra_usage: None,
error: None,
queried_at: Some(0),
}
}
fn fake_result() -> UsageResult {
UsageResult {
success: true,
data: None,
error: None,
}
}
#[test]
fn subscription_round_trip() {
let cache = UsageCache::new();
assert!(cache
.with_subscription(&AppType::Claude, |q| q.success)
.is_none());
cache.put_subscription(AppType::Claude, fake_quota());
let got = cache
.with_subscription(&AppType::Claude, |q| q.success)
.unwrap();
assert!(got);
assert!(cache
.with_subscription(&AppType::Codex, |q| q.success)
.is_none());
}
#[test]
fn script_round_trip_and_invalidate() {
let cache = UsageCache::new();
assert!(cache
.with_script(&AppType::Codex, "pid", |r| r.success)
.is_none());
cache.put_script(AppType::Codex, "pid".to_string(), fake_result());
assert!(cache
.with_script(&AppType::Codex, "pid", |r| r.success)
.is_some());
cache.invalidate_script(&AppType::Codex, "pid");
assert!(cache
.with_script(&AppType::Codex, "pid", |r| r.success)
.is_none());
}
#[test]
fn script_keys_isolated_by_app_type() {
let cache = UsageCache::new();
cache.put_script(AppType::Claude, "same".to_string(), fake_result());
assert!(cache
.with_script(&AppType::Claude, "same", |r| r.success)
.is_some());
assert!(cache
.with_script(&AppType::Codex, "same", |r| r.success)
.is_none());
}
}
@@ -17,7 +17,7 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
let mut sessions = Vec::new();
// Iterate over project hash directories: tmp/<project_hash>/chats/session-*.json
// Iterate over project directories: tmp/<project_name>/chats/session-*.json
let project_dirs = match std::fs::read_dir(&tmp_dir) {
Ok(entries) => entries,
Err(_) => return Vec::new(),
@@ -34,13 +34,19 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
Err(_) => continue,
};
let project_root_file = entry.path().join(".project_root");
let project_dir = std::fs::read_to_string(project_root_file).ok();
for file_entry in chat_files.flatten() {
let path = file_entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
if let Some(meta) = parse_session(&path) {
sessions.push(meta);
sessions.push(SessionMeta {
project_dir: project_dir.clone(),
..meta
});
}
}
}
@@ -159,7 +165,7 @@ fn parse_session(path: &Path) -> Option<SessionMeta> {
session_id: session_id.clone(),
title: title.clone(),
summary: title,
project_dir: None, // project hash is not reversible
project_dir: None, // (optionally) populated later
created_at,
last_active_at: last_active_at.or(created_at),
source_path: Some(source_path),
+7 -2
View File
@@ -1,11 +1,12 @@
use crate::database::Database;
use crate::services::ProxyService;
use crate::services::{ProxyService, UsageCache};
use std::sync::Arc;
/// 全局应用状态
pub struct AppState {
pub db: Arc<Database>,
pub proxy_service: ProxyService,
pub usage_cache: Arc<UsageCache>,
}
impl AppState {
@@ -13,6 +14,10 @@ impl AppState {
pub fn new(db: Arc<Database>) -> Self {
let proxy_service = ProxyService::new(db.clone());
Self { db, proxy_service }
Self {
db,
proxy_service,
usage_cache: Arc::new(UsageCache::new()),
}
}
}
+605 -18
View File
@@ -2,13 +2,20 @@
//!
//! 负责系统托盘图标和菜单的创建、更新和事件处理。
use tauri::menu::{CheckMenuItem, Menu, MenuBuilder, MenuItem, SubmenuBuilder};
use once_cell::sync::Lazy;
use tauri::menu::{CheckMenuItem, Menu, MenuBuilder, MenuItem, Submenu, SubmenuBuilder};
use tauri::{Emitter, Manager};
use crate::app_config::AppType;
use crate::error::AppError;
use crate::store::AppState;
/// 每个 app 分区的子菜单句柄,用于 usage 更新时就地改 label 而非整菜单重建。
/// `create_tray_menu` 每次重建都会整表覆盖写入,保证句柄始终指向当前活跃菜单。
static TRAY_SECTION_SUBMENUS: Lazy<
std::sync::Mutex<std::collections::HashMap<AppType, Submenu<tauri::Wry>>>,
> = Lazy::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
/// 托盘菜单文本(国际化)
#[derive(Clone, Copy)]
pub struct TrayTexts {
@@ -84,6 +91,182 @@ pub const TRAY_SECTIONS: [TrayAppSection; 3] = [
},
];
/// 配色阈值(与前端 `utilizationColor` 语义一致)。
const UTIL_WARN_PCT: f64 = 70.0;
const UTIL_DANGER_PCT: f64 = 90.0;
fn emoji_for_utilization(pct: f64) -> &'static str {
if pct >= UTIL_DANGER_PCT {
"\u{1F534}" // 🔴
} else if pct >= UTIL_WARN_PCT {
"\u{1F7E0}" // 🟠
} else {
"\u{1F7E2}" // 🟢
}
}
fn format_subscription_summary(
quota: &crate::services::subscription::SubscriptionQuota,
) -> Option<String> {
use crate::services::subscription::{
TIER_FIVE_HOUR, TIER_GEMINI_FLASH, TIER_GEMINI_FLASH_LITE, TIER_GEMINI_PRO, TIER_SEVEN_DAY,
};
if !quota.success {
return None;
}
// 按 tool 选取主卡槽 tier 并映射到短 label
// Claude / Codex 沿用时间窗口(h=5 小时,w=7 天);
// Gemini 用模型维度(p=prof=flashl=flash-lite)——Gemini 后端 tier
// 命名是 gemini_pro / gemini_flash / gemini_flash_lite,与时间窗口不同命名空间。
// flash_lite 必须纳入:否则 lite 利用率最高时色标偏低,与前端 footer 行为不一致。
let parts: Vec<(&'static str, f64)> = match quota.tool.as_str() {
"gemini" => {
let mut v = Vec::new();
if let Some(t) = quota.tiers.iter().find(|t| t.name == TIER_GEMINI_PRO) {
v.push(("p", t.utilization));
}
if let Some(t) = quota.tiers.iter().find(|t| t.name == TIER_GEMINI_FLASH) {
v.push(("f", t.utilization));
}
if let Some(t) = quota
.tiers
.iter()
.find(|t| t.name == TIER_GEMINI_FLASH_LITE)
{
v.push(("l", t.utilization));
}
v
}
_ => {
let mut v = Vec::new();
if let Some(t) = quota.tiers.iter().find(|t| t.name == TIER_FIVE_HOUR) {
v.push(("h", t.utilization));
}
if let Some(t) = quota.tiers.iter().find(|t| t.name == TIER_SEVEN_DAY) {
v.push(("w", t.utilization));
}
v
}
};
if parts.is_empty() {
return None;
}
// 色标取所有已选 tier 里最高的利用率——用户更关心"离上限多近"。
let worst = parts
.iter()
.map(|(_, u)| *u)
.fold(f64::NEG_INFINITY, f64::max);
if !worst.is_finite() {
return None;
}
let emoji = emoji_for_utilization(worst);
let body = parts
.iter()
.map(|(label, u)| format!("{label}{}%", u.round() as i64))
.collect::<Vec<_>>()
.join(" ");
Some(format!("{emoji} {body}"))
}
fn tier_pct(data: &crate::provider::UsageData) -> Option<f64> {
match (data.used, data.total) {
(Some(used), Some(total)) if total > 0.0 => Some(used / total * 100.0),
_ => None,
}
}
fn format_script_summary(result: &crate::provider::UsageResult) -> Option<String> {
use crate::services::subscription::{TIER_FIVE_HOUR, TIER_WEEKLY_LIMIT};
if !result.success {
return None;
}
let data = result.data.as_ref()?;
if data.is_empty() {
return None;
}
// commands::provider 的 token_plan 分支把 SubscriptionQuota 的每个 tier
// 扁平化为一条 UsageDataplan_name 承载 tier 名),所以这里按 plan_name
// 识别双桶形态,其余 usage 结果(Copilot / balance / 自定义脚本)走 fallback。
const TOKEN_PLAN_LABELS: &[(&str, &str)] = &[(TIER_FIVE_HOUR, "h"), (TIER_WEEKLY_LIMIT, "w")];
let mut parts: Vec<(&'static str, f64)> = Vec::new();
for &(tier_name, label) in TOKEN_PLAN_LABELS {
let Some(d) = data
.iter()
.find(|d| d.plan_name.as_deref() == Some(tier_name))
else {
continue;
};
if let Some(u) = tier_pct(d) {
parts.push((label, u));
}
}
if !parts.is_empty() {
let worst = parts
.iter()
.map(|(_, u)| *u)
.fold(f64::NEG_INFINITY, f64::max);
let emoji = emoji_for_utilization(worst);
let body = parts
.iter()
.map(|(label, u)| format!("{label}{}%", u.round() as i64))
.collect::<Vec<_>>()
.join(" ");
return Some(format!("{emoji} {body}"));
}
let first = data.first()?;
let pct = tier_pct(first)?;
let emoji = emoji_for_utilization(pct);
let plan = first.plan_name.as_deref().unwrap_or("");
let rounded = pct.round() as i64;
if plan.is_empty() {
Some(format!("{} {}%", emoji, rounded))
} else {
Some(format!("{} {} {}%", emoji, plan, rounded))
}
}
fn format_usage_suffix(
app_state: &AppState,
app_type: &AppType,
provider: &crate::provider::Provider,
provider_id: &str,
) -> Option<String> {
// 当前脚本是否启用:禁用/删除时不再沿用旧 UsageCache 结果,
// 并顺手 invalidate,防止后续重建继续命中过期数据。
if provider.has_usage_script_enabled() {
// 脚本缓存优先(覆盖 Copilot/coding_plan/balance/自定义脚本),借用访问避免克隆整条 UsageResult。
if let Some(Some(s)) =
app_state
.usage_cache
.with_script(app_type, provider_id, format_script_summary)
{
return Some(format!(" · {s}"));
}
} else {
app_state
.usage_cache
.invalidate_script(app_type, provider_id);
}
if provider.category.as_deref() == Some("official") {
if let Some(Some(s)) = app_state
.usage_cache
.with_subscription(app_type, format_subscription_summary)
{
return Some(format!(" · {s}"));
}
}
None
}
/// 对供应商列表排序:sort_index → created_at → name
fn sort_providers(
providers: &indexmap::IndexMap<String, crate::provider::Provider>,
@@ -291,6 +474,8 @@ pub fn create_tray_menu(
let visible_apps = app_settings.visible_apps.unwrap_or_default();
let mut menu_builder = MenuBuilder::new(app);
let mut section_handles: std::collections::HashMap<AppType, Submenu<tauri::Wry>> =
std::collections::HashMap::new();
// 顶部:打开主界面
let show_main_item =
@@ -323,10 +508,13 @@ pub fn create_tray_menu(
})?;
menu_builder = menu_builder.item(&empty_item);
} else {
// 有供应商:构建子菜单
let current_name = providers.get(&current_id).map(|p| p.name.as_str());
let submenu_label = match current_name {
Some(name) => format!("{} · {}", section.header_label, name),
let current_provider = providers.get(&current_id);
let submenu_label = match current_provider {
Some(p) => {
let suffix = format_usage_suffix(app_state, &section.app_type, p, &current_id)
.unwrap_or_default();
format!("{} · {}{}", section.header_label, p.name, suffix)
}
None => section.header_label.to_string(),
};
let submenu_id = format!("submenu_{}", app_type_str);
@@ -369,6 +557,7 @@ pub fn create_tray_menu(
let submenu = submenu_builder.build().map_err(|e| {
AppError::Message(format!("构建{}子菜单失败: {e}", section.log_name))
})?;
section_handles.insert(section.app_type.clone(), submenu.clone());
menu_builder = menu_builder.item(&submenu);
}
@@ -393,9 +582,51 @@ pub fn create_tray_menu(
menu_builder = menu_builder.item(&quit_item);
menu_builder
let menu = menu_builder
.build()
.map_err(|e| AppError::Message(format!("构建菜单失败: {e}")))
.map_err(|e| AppError::Message(format!("构建菜单失败: {e}")))?;
*TRAY_SECTION_SUBMENUS
.lock()
.unwrap_or_else(|p| p.into_inner()) = section_handles;
Ok(menu)
}
/// 就地更新各 app 分区子菜单的标题(usage 后缀变化时走这条),
/// 避免 `set_menu` 导致用户打开中的菜单被关闭。
/// 句柄由上一次 `create_tray_menu` 填充;为空(从未构建过菜单)时无事发生。
fn update_tray_usage_labels(app: &tauri::AppHandle) {
let Some(app_state) = app.try_state::<AppState>() else {
return;
};
let handles = match TRAY_SECTION_SUBMENUS.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
for section in TRAY_SECTIONS.iter() {
let Some(submenu) = handles.get(&section.app_type) else {
continue;
};
let Ok(providers) = app_state.db.get_all_providers(section.app_type.as_str()) else {
continue;
};
let Ok(Some(current_id)) =
crate::settings::get_effective_current_provider(&app_state.db, &section.app_type)
else {
continue;
};
let Some(provider) = providers.get(&current_id) else {
continue;
};
let suffix = format_usage_suffix(&app_state, &section.app_type, provider, &current_id)
.unwrap_or_default();
let new_label = format!("{} · {}{}", section.header_label, provider.name, suffix);
if let Err(e) = submenu.set_text(&new_label) {
log::debug!("[Tray] 更新{}子菜单标题失败: {e}", section.log_name);
}
}
}
pub fn refresh_tray_menu(app: &tauri::AppHandle) {
@@ -412,17 +643,6 @@ pub fn refresh_tray_menu(app: &tauri::AppHandle) {
}
}
#[cfg(test)]
mod tests {
use super::TRAY_ID;
#[test]
fn tray_id_is_unique_to_app() {
assert_eq!(TRAY_ID, "cc-switch");
assert_ne!(TRAY_ID, "main");
}
}
#[cfg(target_os = "macos")]
pub fn apply_tray_policy(app: &tauri::AppHandle, dock_visible: bool) {
use tauri::ActivationPolicy;
@@ -491,3 +711,370 @@ pub fn handle_tray_menu_event(app: &tauri::AppHandle, event_id: &str) {
}
}
}
static LAST_TRAY_USAGE_REFRESH: std::sync::Mutex<Option<std::time::Instant>> =
std::sync::Mutex::new(None);
const MIN_TRAY_USAGE_REFRESH_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10);
/// 合并多次快速触发的"usage 标题软更新":批量刷新期间多个 usage 命令
/// 同时成功时,只会产生一次就地 `set_text` 批量调用。走软更新而不是
/// `refresh_tray_menu` 整建,避免用户打开中的菜单被 macOS 系统关闭。
static TRAY_REBUILD_SCHEDULED: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
pub fn schedule_tray_refresh(app: &tauri::AppHandle) {
use std::sync::atomic::Ordering;
if TRAY_REBUILD_SCHEDULED.swap(true, Ordering::AcqRel) {
return;
}
let app = app.clone();
tauri::async_runtime::spawn_blocking(move || {
// 50ms 合窗:让同一轮 React Query / 托盘批量刷新触发的多个写入
// 共享一次标题更新。
std::thread::sleep(std::time::Duration::from_millis(50));
TRAY_REBUILD_SCHEDULED.store(false, Ordering::Release);
update_tray_usage_labels(&app);
});
}
/// 并行刷新每个可见 app "当前 provider" 的用量;成功 / 失败结果都通过各
/// command 的 write-through 逻辑写入 `UsageCache`,单次重建菜单由
/// `schedule_tray_refresh` 做合并。内部 10 秒节流防止鼠标悬停反复进出时
/// 雪崩请求;互斥锁被毒化时以上次状态为准继续推进,不会永久阻塞。
///
/// 刷新面与 `format_usage_suffix` 的展示面严格对齐 —— 每次悬停最多发
/// `TRAY_SECTIONS.len()` 次外部请求,script 优先(覆盖 coding_plan / balance /
/// Copilot / 自定义脚本),否则当前 provider 必须是 `official` 才查订阅。
pub(crate) async fn refresh_all_usage_in_tray(app: &tauri::AppHandle) {
use crate::commands::CopilotAuthState;
use futures::future::join_all;
{
let mut guard = LAST_TRAY_USAGE_REFRESH
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let now = std::time::Instant::now();
if let Some(last) = *guard {
if now.duration_since(last) < MIN_TRAY_USAGE_REFRESH_INTERVAL {
return;
}
}
*guard = Some(now);
}
let Some(app_state) = app.try_state::<AppState>() else {
return;
};
// 与 `create_tray_menu` 保持一致:用户隐藏的 app 不参与外部 API 查询,
// 避免在未使用的 app 上浪费请求、撞 rate limit 或反复触发鉴权失败日志。
let visible_apps = crate::settings::get_settings()
.visible_apps
.unwrap_or_default();
let mut subscription_futures = Vec::new();
let mut script_futures = Vec::new();
for section in TRAY_SECTIONS.iter() {
if !visible_apps.is_visible(&section.app_type) {
continue;
}
let app_type_str = section.app_type.as_str();
let log_name = section.log_name;
// 解析 effective current provider;未设置 / 出错都静默跳过,
// 与 create_tray_menu 的行为保持一致。
let current_id =
match crate::settings::get_effective_current_provider(&app_state.db, &section.app_type)
{
Ok(Some(id)) => id,
Ok(None) => continue,
Err(e) => {
log::warn!("[Tray] 读取{log_name}当前供应商失败: {e}");
continue;
}
};
// 只需当前 provider —— by-id 查询避免把整个 app 的 provider 列表加载
// 进内存(每次悬停 × 3 sections 的热路径)。
let current = match app_state.db.get_provider_by_id(&current_id, app_type_str) {
Ok(Some(p)) => p,
Ok(None) => continue,
Err(e) => {
log::warn!("[Tray] 读取{log_name}当前供应商失败: {e}");
continue;
}
};
// 与 format_usage_suffix 同一优先级:脚本启用 → 查脚本;
// 否则当前 provider 是 official → 查订阅;其它情况不发请求。
if current.has_usage_script_enabled() {
let app_clone = app.clone();
let state = app.state::<AppState>();
let copilot_state = app.state::<CopilotAuthState>();
let provider_id = current_id.clone();
let app_str = app_type_str.to_string();
script_futures.push(async move {
if let Err(e) = crate::commands::queryProviderUsage(
app_clone,
state,
copilot_state,
provider_id.clone(),
app_str,
)
.await
{
log::debug!("[Tray] 刷新{log_name}供应商 {provider_id} 用量失败: {e}");
}
});
} else if current.category.as_deref() == Some("official") {
let app_clone = app.clone();
let state = app.state::<AppState>();
let tool = app_type_str.to_string();
subscription_futures.push(async move {
if let Err(e) =
crate::commands::get_subscription_quota(app_clone, state, tool).await
{
log::debug!("[Tray] 刷新{log_name}订阅用量失败(可能未登录): {e}");
}
});
}
}
// 两组并行启动,整体等待 —— 订阅/脚本互不依赖,没必要串行。
futures::future::join(join_all(subscription_futures), join_all(script_futures)).await;
}
#[cfg(test)]
mod tests {
use super::{format_script_summary, format_subscription_summary, TRAY_ID};
use crate::provider::{UsageData, UsageResult};
use crate::services::subscription::{
CredentialStatus, QuotaTier, SubscriptionQuota, TIER_FIVE_HOUR, TIER_WEEKLY_LIMIT,
};
#[test]
fn tray_id_is_unique_to_app() {
assert_eq!(TRAY_ID, "cc-switch");
assert_ne!(TRAY_ID, "main");
}
fn make_quota(tool: &str, success: bool, tiers: Vec<QuotaTier>) -> SubscriptionQuota {
SubscriptionQuota {
tool: tool.to_string(),
credential_status: CredentialStatus::Valid,
credential_message: None,
success,
tiers,
extra_usage: None,
error: None,
queried_at: Some(0),
}
}
fn tier(name: &str, utilization: f64) -> QuotaTier {
QuotaTier {
name: name.to_string(),
utilization,
resets_at: None,
}
}
#[test]
fn claude_summary_uses_h_and_w_labels() {
let quota = make_quota(
"claude",
true,
vec![tier("five_hour", 9.0), tier("seven_day", 27.0)],
);
let s = format_subscription_summary(&quota).expect("should format");
assert!(s.contains("h9%"), "expected h9% in {s}");
assert!(s.contains("w27%"), "expected w27% in {s}");
}
#[test]
fn gemini_summary_uses_p_and_f_labels() {
let quota = make_quota(
"gemini",
true,
vec![tier("gemini_pro", 15.0), tier("gemini_flash", 42.0)],
);
let s = format_subscription_summary(&quota).expect("should format");
assert!(s.contains("p15%"), "expected p15% in {s}");
assert!(s.contains("f42%"), "expected f42% in {s}");
}
#[test]
fn gemini_summary_includes_all_three_tiers() {
let quota = make_quota(
"gemini",
true,
vec![
tier("gemini_pro", 5.0),
tier("gemini_flash", 42.0),
tier("gemini_flash_lite", 80.0),
],
);
let s = format_subscription_summary(&quota).expect("should format");
assert!(s.contains("p5%"), "expected p5% in {s}");
assert!(s.contains("f42%"), "expected f42% in {s}");
assert!(s.contains("l80%"), "expected l80% in {s}");
}
#[test]
fn gemini_summary_lite_only_still_renders() {
// flash_lite 如果是 API 返回的唯一 tier,仍应显示(避免前端 footer 能看到、
// 托盘空白的不对称)。
let quota = make_quota("gemini", true, vec![tier("gemini_flash_lite", 80.0)]);
let s = format_subscription_summary(&quota).expect("should format");
assert!(s.contains("l80%"), "expected l80% in {s}");
}
#[test]
fn gemini_summary_emoji_reflects_highest_tier_including_lite() {
// lite 是利用率最高的那条 → emoji 必须是红色,不能被 pro/flash 掩盖。
let quota = make_quota(
"gemini",
true,
vec![
tier("gemini_pro", 10.0),
tier("gemini_flash", 20.0),
tier("gemini_flash_lite", 95.0),
],
);
let s = format_subscription_summary(&quota).unwrap();
assert!(
s.starts_with("\u{1F534}"),
"expected red emoji (lite worst) in {s}"
);
}
#[test]
fn worst_emoji_reflects_highest_utilization() {
// 🔴 = \u{1F534}; 任一 tier ≥ 90% 时预期显示红色。
let quota = make_quota(
"claude",
true,
vec![tier("five_hour", 10.0), tier("seven_day", 95.0)],
);
let s = format_subscription_summary(&quota).unwrap();
assert!(s.starts_with("\u{1F534}"), "expected red emoji in {s}");
}
#[test]
fn failure_quota_returns_none() {
let quota = make_quota("claude", false, vec![tier("five_hour", 50.0)]);
assert!(format_subscription_summary(&quota).is_none());
}
#[test]
fn unknown_tiers_return_none() {
let quota = make_quota("claude", true, vec![tier("one_hour", 80.0)]);
assert!(format_subscription_summary(&quota).is_none());
}
#[test]
fn gemini_without_any_known_tiers_returns_none() {
// 完全没有 pro/flash/flash_lite 三种 tier 的退化响应 → None。
let quota = make_quota("gemini", true, vec![tier("some_future_tier", 80.0)]);
assert!(format_subscription_summary(&quota).is_none());
}
fn usage_data(plan_name: Option<&str>, utilization: f64) -> UsageData {
UsageData {
plan_name: plan_name.map(String::from),
extra: None,
is_valid: Some(true),
invalid_message: None,
total: Some(100.0),
used: Some(utilization),
remaining: Some(100.0 - utilization),
unit: Some("%".to_string()),
}
}
fn usage_result(success: bool, data: Vec<UsageData>) -> UsageResult {
UsageResult {
success,
data: if data.is_empty() { None } else { Some(data) },
error: None,
}
}
#[test]
fn script_summary_token_plan_two_tiers() {
let r = usage_result(
true,
vec![
usage_data(Some(TIER_FIVE_HOUR), 12.0),
usage_data(Some(TIER_WEEKLY_LIMIT), 80.0),
],
);
let s = format_script_summary(&r).expect("should format");
assert!(s.contains("h12%"), "expected h12% in {s}");
assert!(s.contains("w80%"), "expected w80% in {s}");
assert!(s.starts_with("\u{1F7E0}"), "expected orange emoji in {s}");
}
#[test]
fn script_summary_token_plan_worst_drives_emoji() {
let r = usage_result(
true,
vec![
usage_data(Some(TIER_FIVE_HOUR), 20.0),
usage_data(Some(TIER_WEEKLY_LIMIT), 95.0),
],
);
let s = format_script_summary(&r).unwrap();
assert!(s.starts_with("\u{1F534}"), "expected red emoji in {s}");
}
#[test]
fn script_summary_token_plan_five_hour_only() {
let r = usage_result(true, vec![usage_data(Some(TIER_FIVE_HOUR), 8.0)]);
let s = format_script_summary(&r).expect("should format");
assert!(s.contains("h8%"), "expected h8% in {s}");
assert!(
!s.contains("plan_name"),
"plan_name should not leak into label: {s}"
);
}
#[test]
fn script_summary_token_plan_weekly_only() {
let r = usage_result(true, vec![usage_data(Some(TIER_WEEKLY_LIMIT), 50.0)]);
let s = format_script_summary(&r).expect("should format");
assert!(s.contains("w50%"), "expected w50% in {s}");
}
#[test]
fn script_summary_single_bucket_fallback_with_plan_name() {
let r = usage_result(true, vec![usage_data(Some("Copilot Pro"), 40.0)]);
let s = format_script_summary(&r).expect("should format");
assert!(s.contains("Copilot Pro"), "expected plan name in {s}");
assert!(s.contains("40%"), "expected 40% in {s}");
assert!(
!s.contains("h40%"),
"must not relabel non-token-plan data as h: {s}"
);
}
#[test]
fn script_summary_single_bucket_fallback_without_plan_name() {
let r = usage_result(true, vec![usage_data(None, 15.0)]);
let s = format_script_summary(&r).expect("should format");
assert_eq!(s, "\u{1F7E2} 15%", "expected emoji + pct only, got {s}");
}
#[test]
fn script_summary_failure_returns_none() {
let r = usage_result(false, vec![usage_data(Some(TIER_FIVE_HOUR), 12.0)]);
assert!(format_script_summary(&r).is_none());
}
#[test]
fn script_summary_empty_data_returns_none() {
let r = usage_result(true, vec![]);
assert!(format_script_summary(&r).is_none());
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "CC Switch",
"version": "3.14.0",
"version": "3.14.1",
"identifier": "com.ccswitch.desktop",
"build": {
"frontendDist": "../dist",
+3 -13
View File
@@ -1,8 +1,6 @@
use std::sync::Arc;
use cc_switch_lib::{
import_provider_from_deeplink, parse_deeplink_url, AppState, Database, ProxyService,
};
use cc_switch_lib::{import_provider_from_deeplink, parse_deeplink_url, AppState, Database};
#[path = "support.rs"]
mod support;
@@ -18,11 +16,7 @@ fn deeplink_import_claude_provider_persists_to_db() {
let request = parse_deeplink_url(url).expect("parse deeplink url");
let db = Arc::new(Database::memory().expect("create memory db"));
let proxy_service = ProxyService::new(db.clone());
let state = AppState {
db: db.clone(),
proxy_service,
};
let state = AppState::new(db.clone());
let provider_id = import_provider_from_deeplink(&state, request.clone())
.expect("import provider from deeplink");
@@ -58,11 +52,7 @@ fn deeplink_import_codex_provider_builds_auth_and_config() {
let request = parse_deeplink_url(url).expect("parse deeplink url");
let db = Arc::new(Database::memory().expect("create memory db"));
let proxy_service = ProxyService::new(db.clone());
let state = AppState {
db: db.clone(),
proxy_service,
};
let state = AppState::new(db.clone());
let provider_id = import_provider_from_deeplink(&state, request.clone())
.expect("import provider from deeplink");
+3 -7
View File
@@ -1,9 +1,7 @@
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use cc_switch_lib::{
update_settings, AppSettings, AppState, Database, MultiAppConfig, ProxyService,
};
use cc_switch_lib::{update_settings, AppSettings, AppState, Database, MultiAppConfig};
/// 为测试设置隔离的 HOME 目录,避免污染真实用户数据。
pub fn ensure_test_home() -> &'static Path {
@@ -62,8 +60,7 @@ pub fn test_mutex() -> &'static Mutex<()> {
#[allow(dead_code)]
pub fn create_test_state() -> Result<AppState, Box<dyn std::error::Error>> {
let db = Arc::new(Database::init()?);
let proxy_service = ProxyService::new(db.clone());
Ok(AppState { db, proxy_service })
Ok(AppState::new(db))
}
/// 创建测试用的 AppState,并从 MultiAppConfig 迁移数据
@@ -73,6 +70,5 @@ pub fn create_test_state_with_config(
) -> Result<AppState, Box<dyn std::error::Error>> {
let db = Arc::new(Database::init()?);
db.migrate_from_json(config)?;
let proxy_service = ProxyService::new(db.clone());
Ok(AppState { db, proxy_service })
Ok(AppState::new(db))
}
+5 -15
View File
@@ -41,14 +41,11 @@ import {
import { checkAllEnvConflicts, checkEnvConflicts } from "@/lib/api/env";
import { useProviderActions } from "@/hooks/useProviderActions";
import { openclawKeys, useOpenClawHealth } from "@/hooks/useOpenClaw";
import {
hermesKeys,
useHermesHealth,
useOpenHermesWebUI,
} from "@/hooks/useHermes";
import { hermesKeys, useOpenHermesWebUI } from "@/hooks/useHermes";
import { hermesApi } from "@/lib/api/hermes";
import { useProxyStatus } from "@/hooks/useProxyStatus";
import { useAutoCompact } from "@/hooks/useAutoCompact";
import { useUsageCacheBridge } from "@/hooks/useUsageCacheBridge";
import { useLastValidValue } from "@/hooks/useLastValidValue";
import { extractErrorMessage } from "@/utils/errorUtils";
import { isTextEditableTarget } from "@/utils/domUtils";
@@ -90,7 +87,6 @@ import EnvPanel from "@/components/openclaw/EnvPanel";
import ToolsPanel from "@/components/openclaw/ToolsPanel";
import AgentsDefaultsPanel from "@/components/openclaw/AgentsDefaultsPanel";
import OpenClawHealthBanner from "@/components/openclaw/OpenClawHealthBanner";
import HermesHealthBanner from "@/components/hermes/HermesHealthBanner";
import HermesMemoryPanel from "@/components/hermes/HermesMemoryPanel";
type View =
@@ -236,6 +232,8 @@ function App() {
const toolbarRef = useRef<HTMLDivElement>(null);
const isToolbarCompact = useAutoCompact(toolbarRef);
useUsageCacheBridge();
const promptPanelRef = useRef<any>(null);
const mcpPanelRef = useRef<any>(null);
const skillsPageRef = useRef<any>(null);
@@ -271,8 +269,6 @@ function App() {
currentView === "openclawAgents");
const { data: openclawHealthWarnings = [] } =
useOpenClawHealth(isOpenClawView);
const isHermesView = activeApp === "hermes" && currentView === "providers";
const { data: hermesHealthWarnings = [] } = useHermesHealth(isHermesView);
const hasSkillsSupport = true;
const hasSessionSupport =
activeApp === "claude" ||
@@ -682,9 +678,6 @@ function App() {
await queryClient.invalidateQueries({
queryKey: hermesKeys.liveProviderIds,
});
await queryClient.invalidateQueries({
queryKey: hermesKeys.health,
});
}
toast.success(
t("notifications.removeFromConfigSuccess", {
@@ -1049,7 +1042,7 @@ function App() {
return (
<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 pb-4"
style={{ overflowX: "hidden", paddingTop: contentTopOffset }}
>
{(dragBarHeight > 0 || useAppWindowControls) && (
@@ -1552,9 +1545,6 @@ function App() {
{isOpenClawView && openclawHealthWarnings.length > 0 && (
<OpenClawHealthBanner warnings={openclawHealthWarnings} />
)}
{isHermesView && hermesHealthWarnings.length > 0 && (
<HermesHealthBanner warnings={hermesHealthWarnings} />
)}
{renderContent()}
</main>
+3
View File
@@ -74,6 +74,7 @@ export const ProviderIcon: React.FC<ProviderIconProps> = ({
"inline-flex items-center justify-center flex-shrink-0",
className,
)}
title={name}
style={{ ...sizeStyle, color: effectiveColor }}
dangerouslySetInnerHTML={{ __html: iconSvg }}
/>
@@ -86,6 +87,7 @@ export const ProviderIcon: React.FC<ProviderIconProps> = ({
<img
src={iconUrl}
alt={name}
title={name}
className={cn(
"inline-flex items-center justify-center flex-shrink-0 object-contain",
className,
@@ -113,6 +115,7 @@ export const ProviderIcon: React.FC<ProviderIconProps> = ({
"bg-muted text-muted-foreground font-semibold",
className,
)}
title={name}
style={sizeStyle}
>
<span
+14 -53
View File
@@ -3,7 +3,7 @@ import { Play, Wand2, Eye, EyeOff, Save } from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { Provider, UsageScript, UsageData } from "@/types";
import { Provider, UsageScript, UsageData, createUsageScript } from "@/types";
import { usageApi, settingsApi, type AppId } from "@/lib/api";
import { copilotGetUsage, copilotGetUsageForAccount } from "@/lib/api/copilot";
import { useSettingsQuery } from "@/lib/query";
@@ -21,6 +21,10 @@ import { FullScreenPanel } from "@/components/common/FullScreenPanel";
import { ConfirmDialog } from "@/components/ConfirmDialog";
import { cn } from "@/lib/utils";
import { TEMPLATE_TYPES, PROVIDER_TYPES } from "@/config/constants";
import {
CODING_PLAN_PROVIDERS,
detectCodingPlanProvider,
} from "@/config/codingPlanProviders";
interface UsageScriptModalProps {
provider: Provider;
@@ -114,21 +118,6 @@ const TEMPLATE_NAME_KEYS: Record<string, string> = {
[TEMPLATE_TYPES.BALANCE]: "usageScript.templateBalance",
};
/** Coding Plan 供应商选项 */
const TOKEN_PLAN_PROVIDERS = [
{ id: "kimi", label: "Kimi For Coding", pattern: /api\.kimi\.com\/coding/i },
{
id: "zhipu",
label: "Zhipu GLM (智谱)",
pattern: /bigmodel\.cn|api\.z\.ai/i,
},
{
id: "minimax",
label: "MiniMax",
pattern: /api\.minimaxi?\.com|api\.minimax\.io/i,
},
] as const;
/** 官方余额查询供应商检测 */
const BALANCE_PROVIDERS = [
{ id: "deepseek", label: "DeepSeek", pattern: /api\.deepseek\.com/i },
@@ -148,15 +137,6 @@ function detectBalanceProvider(baseUrl: string | undefined): boolean {
return BALANCE_PROVIDERS.some((bp) => bp.pattern.test(baseUrl));
}
/** 根据 Base URL 自动检测 Coding Plan 供应商 */
function detectTokenPlanProvider(baseUrl: string | undefined): string | null {
if (!baseUrl) return null;
for (const cp of TOKEN_PLAN_PROVIDERS) {
if (cp.pattern.test(baseUrl)) return cp.id;
}
return null;
}
const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
provider,
appId,
@@ -237,43 +217,24 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
return {
...savedScript,
codingPlanProvider:
detectTokenPlanProvider(providerCredentials.baseUrl) || "kimi",
detectCodingPlanProvider(providerCredentials.baseUrl) || "kimi",
};
}
return savedScript;
}
// 新配置:如果 URL 匹配 Coding Plan,自动初始化
const autoDetected = detectTokenPlanProvider(providerCredentials.baseUrl);
const autoDetected = detectCodingPlanProvider(providerCredentials.baseUrl);
if (autoDetected) {
return {
enabled: false,
language: "javascript" as const,
code: "",
timeout: 10,
autoQueryInterval: 5,
codingPlanProvider: autoDetected,
};
return createUsageScript({ codingPlanProvider: autoDetected });
}
// 新配置:如果 URL 匹配官方余额查询供应商,自动初始化
if (detectBalanceProvider(providerCredentials.baseUrl)) {
return {
enabled: false,
language: "javascript" as const,
code: "",
timeout: 10,
autoQueryInterval: 5,
};
return createUsageScript();
}
return {
enabled: false,
language: "javascript" as const,
return createUsageScript({
code: PRESET_TEMPLATES[TEMPLATE_TYPES.GENERAL],
timeout: 10,
autoQueryInterval: 5,
};
});
});
const [testing, setTesting] = useState(false);
@@ -346,7 +307,7 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
return TEMPLATE_TYPES.GENERAL;
}
// 新配置:如果 URL 匹配 Coding Plan 供应商,自动选择 Coding Plan 模板
if (detectTokenPlanProvider(providerCredentials.baseUrl)) {
if (detectCodingPlanProvider(providerCredentials.baseUrl)) {
return TEMPLATE_TYPES.TOKEN_PLAN;
}
// 新配置:如果 URL 匹配官方余额查询供应商,自动选择 Balance 模板
@@ -623,7 +584,7 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
});
} else if (presetName === TEMPLATE_TYPES.TOKEN_PLAN) {
// Coding Plan 模板不需要脚本,使用 Rust 原生查询
const autoDetected = detectTokenPlanProvider(
const autoDetected = detectCodingPlanProvider(
providerCredentials.baseUrl,
);
setScript({
@@ -862,7 +823,7 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
{t("usageScript.tokenPlanHint")}
</p>
<div className="flex gap-2 flex-wrap">
{TOKEN_PLAN_PROVIDERS.map((cp) => (
{CODING_PLAN_PROVIDERS.map((cp) => (
<Button
key={cp.id}
type="button"
@@ -1,127 +0,0 @@
import React, { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { ExternalLink, TriangleAlert } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { useOpenHermesWebUI } from "@/hooks/useHermes";
import type { HermesHealthWarning } from "@/types";
interface HermesHealthBannerProps {
warnings: HermesHealthWarning[];
}
function getWarningText(
code: string,
fallback: string,
t: ReturnType<typeof useTranslation>["t"],
) {
switch (code) {
case "config_parse_failed":
return t("hermes.health.parseFailed", {
defaultValue:
"config.yaml could not be parsed as valid YAML. Fix the file before editing it here.",
});
case "config_not_found":
return t("hermes.health.configNotFound", {
defaultValue:
"Hermes config.yaml not found. Create it at ~/.hermes/config.yaml or configure the path in settings.",
});
case "env_parse_failed":
return t("hermes.health.envParseFailed", {
defaultValue: "The .env file could not be parsed.",
});
case "model_no_default":
return t("hermes.health.modelNoDefault", {
defaultValue:
"No default model or provider is configured in the 'model' section.",
});
case "custom_providers_not_list":
return t("hermes.health.customProvidersNotList", {
defaultValue:
"custom_providers should be a YAML list (items prefixed with '-'), not a mapping.",
});
case "model_provider_unknown":
return t("hermes.health.modelProviderUnknown", {
defaultValue:
"model.provider references a provider that is not configured.",
});
case "model_default_not_in_provider":
return t("hermes.health.modelDefaultNotInProvider", {
defaultValue:
"model.default is not in the selected provider's models list.",
});
case "duplicate_provider_name":
return t("hermes.health.duplicateProviderName", {
defaultValue:
"custom_providers contains duplicate provider names — only one entry will be used.",
});
case "duplicate_provider_base_url":
return t("hermes.health.duplicateProviderBaseUrl", {
defaultValue:
"custom_providers contains duplicate base_urls — possible accidental copy.",
});
case "schema_migrated_v12":
return t("hermes.health.schemaMigratedV12", {
defaultValue:
"Hermes' newer schema moved some providers into the 'providers:' dict. They are shown read-only in CC Switch — edit or remove those entries via Hermes Web UI.",
});
default:
return fallback;
}
}
const HermesHealthBanner: React.FC<HermesHealthBannerProps> = ({
warnings,
}) => {
const { t } = useTranslation();
const openHermesWebUI = useOpenHermesWebUI();
const items = useMemo(
() =>
warnings.map((warning) => ({
...warning,
text: getWarningText(warning.code, warning.message, t),
})),
[t, warnings],
);
if (warnings.length === 0) {
return null;
}
return (
<div className="px-6 pt-4">
<Alert className="border-amber-500/30 bg-amber-500/5">
<TriangleAlert className="h-4 w-4" />
<AlertTitle className="flex items-center justify-between gap-2">
<span>
{t("hermes.health.title", {
defaultValue: "Hermes config warnings detected",
})}
</span>
<Button
variant="outline"
size="sm"
onClick={() => void openHermesWebUI("/config")}
className="shrink-0"
>
<ExternalLink className="w-3.5 h-3.5 mr-1" />
{t("hermes.webui.fixInWebUI")}
</Button>
</AlertTitle>
<AlertDescription>
<ul className="list-disc space-y-1 pl-5">
{items.map((warning) => (
<li key={`${warning.code}:${warning.path ?? warning.message}`}>
{warning.text}
{warning.path ? ` (${warning.path})` : ""}
</li>
))}
</ul>
</AlertDescription>
</Alert>
</div>
);
};
export default HermesHealthBanner;
@@ -82,6 +82,8 @@ interface ClaudeFormFieldsProps {
isCodexOauthAuthenticated?: boolean;
selectedCodexAccountId?: string | null;
onCodexAccountSelect?: (accountId: string | null) => void;
codexFastMode?: boolean;
onCodexFastModeChange?: (enabled: boolean) => void;
// Template Values
templateValueEntries: Array<[string, TemplateValueConfig]>;
@@ -148,6 +150,8 @@ export function ClaudeFormFields({
isCodexOauthPreset,
selectedCodexAccountId,
onCodexAccountSelect,
codexFastMode,
onCodexFastModeChange,
templateValueEntries,
templateValues,
templatePresetName,
@@ -374,6 +378,8 @@ export function ClaudeFormFields({
<CodexOAuthSection
selectedAccountId={selectedCodexAccountId}
onAccountSelect={onCodexAccountSelect}
fastModeEnabled={codexFastMode}
onFastModeChange={onCodexFastModeChange}
/>
)}
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
Select,
SelectContent,
@@ -30,6 +31,10 @@ interface CodexOAuthSectionProps {
selectedAccountId?: string | null;
/** 账号选择回调 */
onAccountSelect?: (accountId: string | null) => void;
/** 是否开启 Codex FAST mode */
fastModeEnabled?: boolean;
/** FAST mode 切换回调 */
onFastModeChange?: (enabled: boolean) => void;
}
/**
@@ -42,6 +47,8 @@ export const CodexOAuthSection: React.FC<CodexOAuthSectionProps> = ({
className,
selectedAccountId,
onAccountSelect,
fastModeEnabled = false,
onFastModeChange,
}) => {
const { t } = useTranslation();
const [copied, setCopied] = React.useState(false);
@@ -140,6 +147,27 @@ export const CodexOAuthSection: React.FC<CodexOAuthSectionProps> = ({
</div>
)}
{onFastModeChange && (
<div className="flex items-center justify-between rounded-md border bg-muted/30 p-3">
<div className="space-y-1 pr-4">
<Label className="text-sm font-medium">
{t("codexOauth.fastMode", "FAST mode")}
</Label>
<p className="text-xs text-muted-foreground">
{t("codexOauth.fastModeDescription", {
defaultValue:
'Send service_tier="priority" for lower latency. Turn it off if the ChatGPT Codex backend rejects the parameter.',
})}
</p>
</div>
<Switch
checked={fastModeEnabled}
onCheckedChange={onFastModeChange}
aria-label={t("codexOauth.fastMode", "FAST mode")}
/>
</div>
)}
{/* 已登录账号列表 */}
{hasAnyAccount && (
<div className="space-y-2">
@@ -382,6 +382,9 @@ export function ProviderForm({
const [selectedCodexAccountId, setSelectedCodexAccountId] = useState<
string | null
>(() => resolveManagedAccountId(initialData?.meta, "codex_oauth"));
const [codexFastMode, setCodexFastMode] = useState<boolean>(
() => initialData?.meta?.codexFastMode ?? false,
);
const {
codexAuth,
@@ -1115,7 +1118,7 @@ export function ProviderForm({
const providerType =
templatePreset?.providerType || initialData?.meta?.providerType;
payload.meta = {
const nextMeta: ProviderMeta = {
...(baseMeta ?? {}),
commonConfigEnabled:
appId === "claude"
@@ -1146,6 +1149,7 @@ export function ProviderForm({
isCopilotProvider && selectedGitHubAccountId
? selectedGitHubAccountId
: undefined,
codexFastMode: isCodexOauthProvider ? codexFastMode : undefined,
testConfig: testConfig.enabled ? testConfig : undefined,
costMultiplier: pricingConfig.enabled
? pricingConfig.costMultiplier
@@ -1170,6 +1174,12 @@ export function ProviderForm({
: undefined,
};
if (!isCodexOauthProvider && "codexFastMode" in nextMeta) {
delete nextMeta.codexFastMode;
}
payload.meta = nextMeta;
await onSubmit(payload);
};
@@ -1735,6 +1745,8 @@ export function ProviderForm({
isCodexOauthAuthenticated={isCodexOauthAuthenticated}
selectedCodexAccountId={selectedCodexAccountId}
onCodexAccountSelect={setSelectedCodexAccountId}
codexFastMode={codexFastMode}
onCodexFastModeChange={setCodexFastMode}
templateValueEntries={templateValueEntries}
templateValues={templateValues}
templatePresetName={templatePreset?.name || ""}
@@ -61,6 +61,9 @@ export function useModelState({
const isUserEditingRef = useRef(false);
const lastConfigRef = useRef(settingsConfig);
const latestConfigRef = useRef(settingsConfig);
latestConfigRef.current = settingsConfig;
// 初始化读取:读新键;若缺失,按兼容优先级回退
// Haiku: DEFAULT_HAIKU || SMALL_FAST || MODEL
@@ -130,8 +133,8 @@ export function useModelState({
if (field === "ANTHROPIC_DEFAULT_OPUS_MODEL") setDefaultOpusModel(value);
try {
const currentConfig = settingsConfig
? JSON.parse(settingsConfig)
const currentConfig = latestConfigRef.current
? JSON.parse(latestConfigRef.current)
: { env: {} };
if (!currentConfig.env) currentConfig.env = {};
const env = currentConfig.env as Record<string, unknown>;
@@ -146,12 +149,14 @@ export function useModelState({
// 删除旧键
delete env["ANTHROPIC_SMALL_FAST_MODEL"];
onConfigChange(JSON.stringify(currentConfig, null, 2));
const updatedConfig = JSON.stringify(currentConfig, null, 2);
latestConfigRef.current = updatedConfig;
onConfigChange(updatedConfig);
} catch (err) {
console.error("Failed to update model config:", err);
}
},
[settingsConfig, onConfigChange],
[onConfigChange],
);
return {
+1 -1
View File
@@ -475,7 +475,7 @@ export function SettingsPage({
{activeTab === "advanced" && settings && (
<div
className="flex-shrink-0 py-4 border-t border-border-default"
className="flex-shrink-0 pt-4 border-t border-border-default"
style={{ backgroundColor: "hsl(var(--background))" }}
>
<div className="px-6 flex items-center justify-end gap-3">
+8 -2
View File
@@ -454,6 +454,7 @@ const UnifiedSkillsPanel = React.forwardRef<
{importDialogOpen && unmanagedSkills && (
<ImportSkillsDialog
skills={unmanagedSkills}
isImporting={importMutation.isPending}
onImport={handleImport}
onClose={() => setImportDialogOpen(false)}
/>
@@ -600,6 +601,7 @@ interface ImportSkillsDialogProps {
foundIn: string[];
path: string;
}>;
isImporting: boolean;
onImport: (imports: ImportSkillSelection[]) => void;
onClose: () => void;
}
@@ -724,6 +726,7 @@ const RestoreSkillsDialog: React.FC<RestoreSkillsDialogProps> = ({
const ImportSkillsDialog: React.FC<ImportSkillsDialogProps> = ({
skills,
isImporting,
onImport,
onClose,
}) => {
@@ -846,10 +849,13 @@ const ImportSkillsDialog: React.FC<ImportSkillsDialogProps> = ({
</div>
<div className="flex justify-end gap-3">
<Button variant="outline" onClick={onClose}>
<Button variant="outline" onClick={onClose} disabled={isImporting}>
{t("common.cancel")}
</Button>
<Button onClick={handleImport} disabled={selected.size === 0}>
<Button
onClick={handleImport}
disabled={selected.size === 0 || isImporting}
>
{t("skills.importSelected", { count: selected.size })}
</Button>
</div>
+1 -1
View File
@@ -14,7 +14,7 @@ const ScrollArea = React.forwardRef<
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit] [&>div]:!block [&>div]:!min-w-0 [&>div]:!w-full">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
+81
View File
@@ -0,0 +1,81 @@
/**
* Coding Plan base_url
*
* `src-tauri/src/services/coding_plan.rs::detect_provider`
* `url.contains(...)` RegExp
* UsageScriptModal + useProviderActions
* +
*/
import { createUsageScript } from "@/types";
import { TEMPLATE_TYPES } from "@/config/constants";
export interface CodingPlanProviderEntry {
/** 与后端 QuotaTier 的 `codingPlanProvider` 取值对齐 */
id: "kimi" | "zhipu" | "minimax";
/** UsageScriptModal 下拉显示用 */
label: string;
/** base_url 匹配规则 */
pattern: RegExp;
}
export const CODING_PLAN_PROVIDERS: readonly CodingPlanProviderEntry[] = [
{ id: "kimi", label: "Kimi For Coding", pattern: /api\.kimi\.com\/coding/i },
{
id: "zhipu",
label: "Zhipu GLM (智谱)",
pattern: /bigmodel\.cn|api\.z\.ai/i,
},
{
id: "minimax",
label: "MiniMax",
pattern: /api\.minimaxi?\.com|api\.minimax\.io/i,
},
] as const;
/** 根据 Base URL 自动检测 Coding Plan 供应商;未命中返回 null */
export function detectCodingPlanProvider(
baseUrl: string | undefined | null,
): CodingPlanProviderEntry["id"] | null {
if (!baseUrl) return null;
for (const cp of CODING_PLAN_PROVIDERS) {
if (cp.pattern.test(baseUrl)) return cp.id;
}
return null;
}
/**
* Claude `ANTHROPIC_BASE_URL` Coding Plan
* `meta.usage_script` token_plan
*
* - `meta.usage_script` /UsageScriptModal
* - Claude app `commands/provider.rs` token_plan Claude
* supplier `settings_config.env.ANTHROPIC_BASE_URL`
* - code Rust `coding_plan::get_coding_plan_quota` JS
*/
export function injectCodingPlanUsageScript<
T extends {
settingsConfig?: Record<string, any>;
meta?: Record<string, any>;
},
>(appId: string, provider: T): T {
if (appId !== "claude") return provider;
if (provider.meta?.usage_script) return provider;
const baseUrl = provider.settingsConfig?.env?.ANTHROPIC_BASE_URL;
const codingPlanProvider = detectCodingPlanProvider(
typeof baseUrl === "string" ? baseUrl : null,
);
if (!codingPlanProvider) return provider;
return {
...provider,
meta: {
...(provider.meta ?? {}),
usage_script: createUsageScript({
enabled: true,
templateType: TEMPLATE_TYPES.TOKEN_PLAN,
codingPlanProvider,
}),
},
};
}
-11
View File
@@ -27,7 +27,6 @@ export const hermesKeys = {
all: ["hermes"] as const,
liveProviderIds: ["hermes", "liveProviderIds"] as const,
modelConfig: ["hermes", "modelConfig"] as const,
health: ["hermes", "health"] as const,
memory: (kind: HermesMemoryKind) => ["hermes", "memory", kind] as const,
memoryLimits: ["hermes", "memoryLimits"] as const,
};
@@ -41,7 +40,6 @@ export function invalidateHermesProviderCaches(queryClient: QueryClient) {
return Promise.all([
queryClient.invalidateQueries({ queryKey: hermesKeys.liveProviderIds }),
queryClient.invalidateQueries({ queryKey: hermesKeys.modelConfig }),
queryClient.invalidateQueries({ queryKey: hermesKeys.health }),
]);
}
@@ -65,15 +63,6 @@ export function useHermesModelConfig(enabled: boolean) {
});
}
export function useHermesHealth(enabled: boolean) {
return useQuery({
queryKey: hermesKeys.health,
queryFn: () => hermesApi.scanHealth(),
staleTime: 30_000,
enabled,
});
}
export function useHermesMemory(kind: HermesMemoryKind, enabled: boolean) {
return useQuery({
queryKey: hermesKeys.memory(kind),
+3 -1
View File
@@ -10,6 +10,7 @@ import type {
OpenClawDefaultModel,
} from "@/types";
import type { OpenClawSuggestedDefaults } from "@/config/openclawProviderPresets";
import { injectCodingPlanUsageScript } from "@/config/codingPlanProviders";
import {
useAddProviderMutation,
useUpdateProviderMutation,
@@ -72,7 +73,8 @@ export function useProviderActions(
addToLive?: boolean;
},
) => {
await addProviderMutation.mutateAsync(provider);
const enhanced = injectCodingPlanUsageScript(activeApp, provider);
await addProviderMutation.mutateAsync(enhanced);
// OpenClaw: register models to allowlist after adding provider
if (activeApp === "openclaw" && provider.suggestedDefaults) {
+19
View File
@@ -0,0 +1,19 @@
import type { InstalledSkill } from "@/lib/api/skills";
/**
* id
*
* mutation
* installed imported
* React Query
*/
export function mergeImportedSkills(
existing: InstalledSkill[] | undefined,
imported: InstalledSkill[],
): InstalledSkill[] {
if (!existing) return imported;
if (imported.length === 0) return existing;
const importedIds = new Set(imported.map((s) => s.id));
const preserved = existing.filter((s) => !importedIds.has(s.id));
return [...preserved, ...imported];
}
+2 -4
View File
@@ -14,6 +14,7 @@ import {
type SkillsShSearchResult,
} from "@/lib/api/skills";
import type { AppId } from "@/lib/api/types";
import { mergeImportedSkills } from "@/hooks/useSkills.helpers";
/**
* Skills
@@ -208,10 +209,7 @@ export function useImportSkillsFromApps() {
// 直接更新 installed 缓存
queryClient.setQueryData<InstalledSkill[]>(
["skills", "installed"],
(oldData) => {
if (!oldData) return importedSkills;
return [...oldData, ...importedSkills];
},
(oldData) => mergeImportedSkills(oldData, importedSkills),
);
// 刷新 unmanaged 列表(已被导入的应该移除)
queryClient.invalidateQueries({ queryKey: ["skills", "unmanaged"] });
+66
View File
@@ -0,0 +1,66 @@
import { useEffect } from "react";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { useQueryClient } from "@tanstack/react-query";
import type { AppId } from "@/lib/api/types";
import type { UsageResult } from "@/types";
import type { SubscriptionQuota } from "@/types/subscription";
import { usageKeys } from "@/lib/query/usage";
import { subscriptionKeys } from "@/lib/query/subscription";
type UsageCacheUpdatedPayload =
| {
kind: "script";
appType: AppId;
providerId: string;
data: UsageResult;
}
| {
kind: "subscription";
appType: AppId;
data: SubscriptionQuota;
};
/**
* `UsageCache` emit `usage-cache-updated` hook payload
* React Query
* React Query Rust
*/
export function useUsageCacheBridge() {
const queryClient = useQueryClient();
useEffect(() => {
let unlisten: UnlistenFn | undefined;
let disposed = false;
(async () => {
const off = await listen<UsageCacheUpdatedPayload>(
"usage-cache-updated",
(event) => {
const payload = event.payload;
if (payload.kind === "script") {
queryClient.setQueryData<UsageResult>(
usageKeys.script(payload.providerId, payload.appType),
payload.data,
);
} else if (payload.kind === "subscription") {
queryClient.setQueryData<SubscriptionQuota>(
subscriptionKeys.quota(payload.appType),
payload.data,
);
}
},
);
if (disposed) {
off();
} else {
unlisten = off;
}
})();
return () => {
disposed = true;
unlisten?.();
};
}, [queryClient]);
}
+3 -15
View File
@@ -929,7 +929,9 @@
"addAnotherAccount": "Add another account",
"logoutAll": "Logout all accounts",
"retry": "Retry",
"copyCode": "Copy code"
"copyCode": "Copy code",
"fastMode": "FAST mode",
"fastModeDescription": "Send service_tier=\"priority\" for lower latency. Off by default — enabling it consumes your ChatGPT quota at a higher rate."
},
"endpointTest": {
"title": "API Endpoint Management",
@@ -1680,26 +1682,12 @@
"open": "Open Hermes Web UI",
"offline": "Hermes Web UI is not running. Start it with `hermes dashboard` first.",
"openFailed": "Failed to open Hermes Web UI",
"fixInWebUI": "Fix in Hermes Web UI",
"launchConfirmTitle": "Hermes Dashboard is not running",
"launchConfirmMessage": "Open a terminal and start it now with `hermes dashboard`?\n\nThe browser will open automatically once startup completes.\n\nIf the terminal reports that `hermes` cannot be found or the web extras are missing, run first:\npip install hermes-agent[web]",
"launchConfirmAction": "Open terminal & launch",
"launching": "Started `hermes dashboard` in a terminal.",
"launchFailed": "Failed to open terminal"
},
"health": {
"title": "Hermes config warnings detected",
"parseFailed": "config.yaml could not be parsed as valid YAML. Fix the file before editing it here.",
"configNotFound": "Hermes config.yaml not found. Create it at ~/.hermes/config.yaml or configure the path in settings.",
"envParseFailed": "The .env file could not be parsed.",
"modelNoDefault": "No default model or provider is configured in the 'model' section.",
"customProvidersNotList": "custom_providers should be a YAML list (items prefixed with '-'), not a mapping.",
"modelProviderUnknown": "model.provider references a provider that is not configured.",
"modelDefaultNotInProvider": "model.default is not in the selected provider's models list.",
"duplicateProviderName": "custom_providers contains duplicate provider names — only one entry will be used.",
"duplicateProviderBaseUrl": "custom_providers contains duplicate base_urls — possible accidental copy.",
"schemaMigratedV12": "Hermes' newer schema moved some providers into the 'providers:' dict. They are shown read-only in CC Switch — edit or remove those entries via Hermes Web UI."
},
"memory": {
"title": "Memory",
"agentTab": "Agent Memory (MEMORY.md)",
+3 -15
View File
@@ -929,7 +929,9 @@
"addAnotherAccount": "別のアカウントを追加",
"logoutAll": "すべてのアカウントをログアウト",
"retry": "再試行",
"copyCode": "コードをコピー"
"copyCode": "コードをコピー",
"fastMode": "FAST モード",
"fastModeDescription": "低遅延のため service_tier=\"priority\" を送信します。既定ではオフ——オンにすると ChatGPT のクォータがより速く消費されます。"
},
"endpointTest": {
"title": "API エンドポイント管理",
@@ -1680,26 +1682,12 @@
"open": "Hermes Web UI を開く",
"offline": "Hermes Web UI が起動していません。まず `hermes dashboard` を実行してください。",
"openFailed": "Hermes Web UI を開けませんでした",
"fixInWebUI": "Hermes Web UI で修正",
"launchConfirmTitle": "Hermes Dashboard が起動していません",
"launchConfirmMessage": "ターミナルを開いて `hermes dashboard` を実行しますか?\n\n起動完了後、ブラウザが自動的に開きます。\n\nターミナルに `hermes` が見つからない、または web 依存が不足するというエラーが表示される場合は、まず次を実行してください:\npip install hermes-agent[web]",
"launchConfirmAction": "ターミナルを開いて起動",
"launching": "ターミナルで hermes dashboard を起動しました。",
"launchFailed": "ターミナルを開けませんでした"
},
"health": {
"title": "Hermes 設定の警告を検出",
"parseFailed": "config.yaml を有効な YAML として解析できません。ここで編集する前にファイルを修正してください。",
"configNotFound": "Hermes config.yaml が見つかりません。~/.hermes/config.yaml に作成するか、設定でパスを構成してください。",
"envParseFailed": ".env ファイルを解析できません。",
"modelNoDefault": "'model' セクションに既定モデルまたはプロバイダーが設定されていません。",
"customProvidersNotList": "custom_providers はマッピングではなく、YAML リスト('-' で始まる項目)である必要があります。",
"modelProviderUnknown": "model.provider が指すプロバイダーは設定に存在しません。",
"modelDefaultNotInProvider": "model.default は選択中のプロバイダーのモデル一覧に含まれていません。",
"duplicateProviderName": "custom_providers にプロバイダー名の重複があります。1 件のみ有効になります。",
"duplicateProviderBaseUrl": "custom_providers に重複した base_url があります。誤ってコピーされた可能性があります。",
"schemaMigratedV12": "Hermes の新しいスキーマでは一部のプロバイダーが 'providers:' dict に移動しました。CC Switch では読み取り専用で表示されます。編集・削除は Hermes Web UI から行ってください。"
},
"memory": {
"title": "メモリ",
"agentTab": "エージェント記憶 (MEMORY.md)",
+3 -15
View File
@@ -929,7 +929,9 @@
"addAnotherAccount": "添加其他账号",
"logoutAll": "注销所有账号",
"retry": "重试",
"copyCode": "复制代码"
"copyCode": "复制代码",
"fastMode": "FAST 模式",
"fastModeDescription": "发送 service_tier=\"priority\" 换取更低延迟。默认关闭——开启后会按更高速率消耗 ChatGPT 配额。"
},
"endpointTest": {
"title": "请求地址管理",
@@ -1680,26 +1682,12 @@
"open": "打开 Hermes Web UI",
"offline": "Hermes Web UI 未启动,请先运行 `hermes dashboard` 启动服务。",
"openFailed": "打开 Hermes Web UI 失败",
"fixInWebUI": "在 Hermes Web UI 修复",
"launchConfirmTitle": "Hermes Dashboard 未启动",
"launchConfirmMessage": "是否打开终端并运行 `hermes dashboard` 启动服务?\n\n启动完成后会自动打开浏览器。\n\n若终端提示找不到 hermes 或缺少 web 依赖,请先运行:\npip install hermes-agent[web]",
"launchConfirmAction": "打开终端并启动",
"launching": "已在终端启动 hermes dashboard",
"launchFailed": "打开终端失败"
},
"health": {
"title": "检测到 Hermes 配置警告",
"parseFailed": "config.yaml 无法解析为有效 YAML。请先修复文件再在此编辑。",
"configNotFound": "未找到 Hermes config.yaml。请在 ~/.hermes/config.yaml 创建或在设置中配置路径。",
"envParseFailed": ".env 文件无法解析。",
"modelNoDefault": "model 段未设置默认模型或供应商。",
"customProvidersNotList": "custom_providers 应为 YAML 列表(以 `-` 开头),而不是映射。",
"modelProviderUnknown": "model.provider 指向的供应商未在配置中找到。",
"modelDefaultNotInProvider": "model.default 指向的模型不在所选供应商的模型列表中。",
"duplicateProviderName": "custom_providers 中存在重复的供应商名,只会有一条生效。",
"duplicateProviderBaseUrl": "custom_providers 中存在重复的 base_url,可能是意外复制。",
"schemaMigratedV12": "Hermes 新版 schema 把部分供应商移到了 'providers:' dict。CC Switch 中以只读方式显示,编辑或删除请通过 Hermes Web UI 操作。"
},
"memory": {
"title": "记忆管理",
"agentTab": "Agent 记忆 (MEMORY.md)",
+3 -8
View File
@@ -1,6 +1,5 @@
import { invoke } from "@tauri-apps/api/core";
import type {
HermesHealthWarning,
HermesMemoryKind,
HermesMemoryLimits,
HermesModelConfig,
@@ -12,19 +11,15 @@ import type {
* CC Switch intentionally keeps its Hermes surface minimal deep configuration
* (model, agent behavior, env vars, skills, cron, logs, analytics) lives in
* the Hermes Web UI at http://127.0.0.1:9119. CC Switch only reads the `model`
* section to highlight the active provider, scans config health, and launches
* the Hermes Web UI for everything else. Writes to `model` happen implicitly
* via `apply_switch_defaults` when the user switches providers.
* section to highlight the active provider and launches the Hermes Web UI for
* everything else. Writes to `model` happen implicitly via
* `apply_switch_defaults` when the user switches providers.
*/
export const hermesApi = {
async getModelConfig(): Promise<HermesModelConfig | null> {
return await invoke("get_hermes_model_config");
},
async scanHealth(): Promise<HermesHealthWarning[]> {
return await invoke("scan_hermes_config_health");
},
/**
* Probe the local Hermes Web UI and open it in the system browser.
* Optional `path` lets callers deep-link to specific pages like `/config`.
+2 -1
View File
@@ -17,6 +17,7 @@ import type {
SessionMeta,
SessionMessage,
} from "@/types";
import { usageKeys } from "@/lib/query/usage";
const sortProviders = (
providers: Record<string, Provider>,
@@ -113,7 +114,7 @@ export const useUsageQuery = (
: 5 * 60 * 1000; // 默认 5 分钟
const query = useQuery<UsageResult>({
queryKey: ["usage", providerId, appId],
queryKey: usageKeys.script(providerId, appId),
queryFn: async () => usageApi.query(providerId, appId),
enabled: enabled && !!providerId,
refetchInterval:
+6 -1
View File
@@ -7,13 +7,18 @@ import { PROVIDER_TYPES } from "@/config/constants";
const REFETCH_INTERVAL = 5 * 60 * 1000; // 5 minutes
export const subscriptionKeys = {
all: ["subscription"] as const,
quota: (appId: AppId) => [...subscriptionKeys.all, "quota", appId] as const,
};
export function useSubscriptionQuota(
appId: AppId,
enabled: boolean,
autoQuery = false,
) {
return useQuery({
queryKey: ["subscription", "quota", appId],
queryKey: subscriptionKeys.quota(appId),
queryFn: () => subscriptionApi.getQuota(appId),
enabled: enabled && ["claude", "codex", "gemini"].includes(appId),
refetchInterval: autoQuery ? REFETCH_INTERVAL : false,
+2
View File
@@ -106,6 +106,8 @@ export const usageKeys = {
pricing: () => [...usageKeys.all, "pricing"] as const,
limits: (providerId: string, appType: string) =>
[...usageKeys.all, "limits", providerId, appType] as const,
script: (providerId: string, appType: string) =>
[...usageKeys.all, providerId, appType] as const,
};
// Hooks
+16 -11
View File
@@ -74,6 +74,20 @@ export interface UsageScript {
};
}
const DEFAULT_USAGE_SCRIPT: UsageScript = {
enabled: false,
language: "javascript",
code: "",
timeout: 10,
autoQueryInterval: 5,
};
export function createUsageScript(
overrides?: Partial<UsageScript>,
): UsageScript {
return { ...DEFAULT_USAGE_SCRIPT, ...overrides };
}
// 单个套餐用量数据
export interface UsageData {
planName?: string; // 套餐名称(可选)
@@ -155,6 +169,8 @@ export interface ProviderMeta {
isFullUrl?: boolean;
// Prompt cache key for OpenAI Responses-compatible endpoints (improves cache hit rate)
promptCacheKey?: string;
// Codex OAuth FAST mode: injects service_tier="priority" on ChatGPT Codex requests
codexFastMode?: boolean;
// 供应商类型(用于识别 Copilot 等特殊供应商)
providerType?: string;
// GitHub Copilot 关联账号 ID(旧字段,保留兼容读取)
@@ -587,17 +603,6 @@ export interface HermesModelConfig {
[key: string]: unknown;
}
export interface HermesHealthWarning {
code: string;
message: string;
path?: string;
}
export interface HermesWriteOutcome {
backupPath?: string;
warnings: HermesHealthWarning[];
}
export type HermesMemoryKind = "memory" | "user";
export interface HermesMemoryLimits {
@@ -0,0 +1,62 @@
import { describe, it, expect } from "vitest";
import { mergeImportedSkills } from "@/hooks/useSkills.helpers";
import type { InstalledSkill } from "@/lib/api/skills";
function makeSkill(overrides: Partial<InstalledSkill> = {}): InstalledSkill {
return {
id: "skill-a",
name: "Skill A",
directory: "skill-a",
apps: {
claude: true,
codex: false,
gemini: false,
opencode: false,
openclaw: false,
hermes: false,
},
installedAt: 0,
updatedAt: 0,
...overrides,
};
}
// Regression coverage for issue #2139: when a user double-clicks the import
// button (or the mutation otherwise fires twice with the same payload), the
// installed cache must not accumulate duplicate entries for the same skill.
describe("mergeImportedSkills", () => {
it("returns the imported list as-is when no cache exists yet", () => {
const imported = [makeSkill()];
expect(mergeImportedSkills(undefined, imported)).toEqual(imported);
});
it("dedupes by id when the same skill is imported twice in a row", () => {
const existing = [makeSkill()];
const secondImport = [makeSkill()];
const merged = mergeImportedSkills(existing, secondImport);
expect(merged).toHaveLength(1);
expect(merged[0]).toBe(secondImport[0]);
});
it("replaces stale cache entries with fresh imports for the same id", () => {
const stale = [makeSkill({ name: "Stale Name" })];
const fresh = [makeSkill({ name: "Fresh Name" })];
const merged = mergeImportedSkills(stale, fresh);
expect(merged).toHaveLength(1);
expect(merged[0].name).toBe("Fresh Name");
});
it("returns the existing reference unchanged when the imported list is empty", () => {
const existing = [makeSkill()];
expect(mergeImportedSkills(existing, [])).toBe(existing);
});
it("appends newly imported skills without dropping existing unrelated ones", () => {
const existing = [makeSkill({ id: "skill-a", directory: "skill-a" })];
const imported = [
makeSkill({ id: "skill-b", directory: "skill-b", name: "Skill B" }),
];
const merged = mergeImportedSkills(existing, imported);
expect(merged.map((s) => s.id).sort()).toEqual(["skill-a", "skill-b"]);
});
});