Compare commits

...

104 Commits

Author SHA1 Message Date
Jason 21e695f68a chore(release): prepare v3.16.3
- Bump version to 3.16.3 (package.json, tauri.conf.json, Cargo.toml, Cargo.lock)
- Add CHANGELOG entry for v3.16.3 (59 commits since v3.16.2)
- Add trilingual release notes (zh / en / ja) under docs/release-notes/
2026-06-15 00:08:21 +08:00
Jason c678374c59 chore(presets): update Volcengine Ark Coding Plan invite link and promo copy
- Replace activity/agentplan links with the new codingplan invite URL
  (ac=MMAP8JTTCAQ2, rc=6J6FV5N2) across all 6 app presets
- Refresh partnerPromotion copy in all 4 locales: two-month 75% off plus
  invite code 6J6FV5N2; correct product name from Agent Plan to Coding Plan
- README: swap the CN-mainland redirect link in EN/DE, refresh the ZH promo
  copy, and add the redirect link to the JA BytePlus entry
2026-06-14 23:03:31 +08:00
Jason d307df92e9 chore(presets): drop isPartner flag from MiniMax presets across all apps
Remove the gold star badge and the partner promotion banner for MiniMax by
deleting the isPartner flag from all 12 MiniMax presets (cn + en) across
claude, claude-desktop, codex, opencode, openclaw, and hermes.

Both the preset-selector star (gated on isPartner) and the API-key promotion
banner (gated on isPartner && partnerPromotionKey) disappear as a result.
The partnerPromotionKey and the minimax_cn/minimax_en i18n copy are kept
dormant so the partnership can be re-enabled with a single line if needed.
MiniMax stays as a regular cn_official provider, keeping its icon and theme.
2026-06-14 21:47:46 +08:00
Jason 5092fe51ce fix(updater): prevent codex self-update from breaking npm platform-dispatch installs
Codex ships as an npm platform-dispatch package (JS launcher @openai/codex + per-platform binary optional deps like @openai/codex-darwin-arm64). The upgrade chain ran `<bin>/codex update || <bin>/npm i -g @openai/codex@latest`, which can leave codex throwing "Missing optional dependency @openai/codex-darwin-arm64":

- `codex update` on an npm install is a bare `npm install -g @openai/codex` that prints success and exits 0 even when the platform binary fails to land, short-circuiting the `||` npm fallback.

- The npm fallback is a no-op when version==latest and only targets the main package, so it can never re-land the missing platform binary.

Fixes: (1) remove codex from prefers_official_update (Posix+Windows) so npm-managed codex no longer runs the false-success `codex update`; (2) add a runnable=false gate in installs_anchored_command emitting an uninstall+install self-heal — the only repair that re-lands the platform binary; (3) narrow by source/real to npm-managed sources (nvm/fnm/mise/homebrew, non-brew-formula) so broken brew-formula/volta/bun installs fall back to their own anchored commands instead of being mis-repaired with npm. Reuses the existing enumerate runnable signal; no new FS probing.
2026-06-14 21:21:45 +08:00
Jason 34001aaffc perf(about): cache tool version probes across tab switches with a TTL
Settings uses Radix tabs, which unmount inactive tab content. Every time
the About tab was reopened, AboutSection remounted and its mount effect
re-ran all six tool version probes (a `--version` subprocess plus an
npm/github/pypi request each) -- wasteful, since versions rarely change
within a session and a manual Refresh already exists.

Add a module-scoped cache (lives for the app session, survives
unmount/remount) with a 10-minute TTL:

- on remount within the TTL the cached results are reused, skipping all
  probes; state is lazily initialized from the cache so the first paint
  shows the values with no loading flash
- a stale cache shows the old values immediately and revalidates per
  tool in the background (stale-while-revalidate)
- the Refresh button forces a re-probe; single-tool refreshes (shell
  change / post-update) update cached data without resetting the TTL
- cold-cache entries start at at=0 (a "not yet fully loaded" sentinel)
  so a partial cache left by a mid-probe tab switch is treated as stale
  and re-fetched rather than served as if complete; the real timestamp
  is only stamped once a full load finishes

The app's own version is cached too, purely to avoid a loading flash on
remount.
2026-06-14 21:21:45 +08:00
Jason 780acfa7de fix(about): decouple app version badge from tool version probes
getVersion() is a local, millisecond call but was awaited together with
loadAllToolVersions() in a single Promise.all, so setVersion and
setIsLoadingVersion only fired after all six tool checks finished. The
version badge under the app icon therefore waited for the whole batch.

Split the mount effect into two independent chains: loadAppVersion sets
the app version (and clears its loading flag) the moment getVersion()
resolves, while loadAllToolVersions runs its own progressive fan-out.
The two no longer block each other.
2026-06-14 21:21:45 +08:00
Jason 6bda3b0131 feat(about): render tool version checks progressively per tool
Fan out the six tool version probes concurrently instead of awaiting
one sequential batch, so each tool card updates the moment its own
check finishes rather than waiting for the slowest one.

- loadAllToolVersions now calls refreshToolVersions per tool via
  Promise.all, reusing the existing per-name merge and per-tool
  loading flags
- card loading derives from per-tool state
  (loadingTools[t] || (isLoadingTools && !resolved)) so a resolved
  card leaves loading independently while the batch is still in flight
- WSL shell/flag selects reuse the per-card loading flag, matching the
  install/update buttons' early-enable behavior

This also drops total wall time from the sum of six sequential probes
to the slowest single probe. get_single_tool_version_impl is already
isolated and read-only (shared HTTP client, spawn_blocking subprocess,
no shared state), so concurrent probes are safe.
2026-06-14 21:21:45 +08:00
Jason 89ff2d58d1 fix(usage): improve usage-query resilience and error surfacing
- useUsageQuery: retry once + keep-last-good — show the last successful
  result for up to 10min when a query fails transiently (network/timeout/
  HTTP 5xx), so a single blip no longer flips the card to red. Deterministic
  failures (auth, empty key, unknown provider, 4xx) surface immediately and
  clear the snapshot so a stale quota can't resurface after credentials change.
- bump native balance/coding-plan/subscription request timeouts 10s -> 15s
  for slow cross-border endpoints.
- coding_plan: return explicit errors ("API key is empty" / "Unknown coding
  plan provider") instead of a blank failure, mirroring balance.
- add unit tests for keep-last-good and transient/deterministic classification.
2026-06-14 21:21:45 +08:00
Jason 9a3d6a4e84 feat(about): add Fable 5 Verified banner to About section
Display the Fable 5 Verified banner to the right of the app name and version block on the settings About page, marking this as a special build. Center the version badge under the app name so the two rows share a common axis.

The app-side asset lives at src/assets/fable5-verified.png (imported via the @ alias and bundled by Vite); the original source banner is kept under assets/partners/banners/ alongside the other partner banners.
2026-06-14 21:21:45 +08:00
Jason fee354d09e fix(health-check): disable connectivity check for official providers, restore 6s degraded threshold
Official providers (Claude/Codex/Gemini/Claude Desktop) use OAuth with an intentionally empty base_url and connect via the client's default endpoint, so cc-switch has no reliable reachability target. Probing a guessed endpoint either hits the wrong target or returns a meaningless green light. Hide the connectivity button for category === 'official'; reachability stays available for copilot/codex-oauth/third-party/custom providers, which is where the old real-request probe produced false negatives. Revert the official base_url fallback added earlier — resolve_base_url is back to extract-or-error.

The 1500ms degraded threshold was too strict; normal ~1s probe latencies showed as 'slow'. Restore the original 6000ms scale (default + config panel + per-provider range). Keep the reachability-appropriate 8s timeout / 1 retry.
2026-06-14 21:21:45 +08:00
Jason a5903d8600 feat(health-check): replace real-LLM probe with HTTP reachability check
The provider panel health check sent a real streaming model request, which many third-party providers block (401/403/WAF), causing false negatives while only stable official endpoints passed. Replace it with a lightweight reachability probe: GET the provider base_url and treat any HTTP response (200/4xx/5xx) as reachable; only DNS/connect/TLS/timeout count as failure. Latency is the probe's TTFB.

Backend (services/stream_check.rs): rewrite ~2200 -> ~350 lines, dropping real-request building, format conversion, auth and API-path resolution while keeping per-app base_url extraction. Defaults: 8s timeout, 1 retry, 1500ms degraded threshold.

Failover invariant: the reachability check must never reset the circuit breaker (reachable != usable; a 403 host is reachable but broken for real traffic). Remove the resetCircuitBreaker call from useStreamCheck; failover failure detection stays driven solely by real proxy traffic (forwarder/circuit_breaker untouched). useResetCircuitBreaker is kept dormant for a future manual-recovery entry.

Open the check to all providers: drop the official/copilot/codex-oauth/third-party gating and the 'sends a real request' confirm dialog. For official providers whose base_url is intentionally empty, fall back to the endpoint the client actually uses (Claude -> api.anthropic.com, Codex -> chatgpt.com/backend-api/codex, Gemini -> generativelanguage). Non-official providers with a missing base_url still error to avoid a false green light. Claude Desktop Official is native 1P mode (talks to claude.ai, cc-switch not in the request path, no reliable endpoint) so its button stays hidden.

Slim StreamCheckConfig and per-provider testConfig to timeout/threshold/retries (drop test model + prompt); sync zh/en/ja/zh-TW. Retain the now-unused anthropic_to_openai/anthropic_to_gemini transform utilities and their test suites.
2026-06-14 21:21:45 +08:00
WangJiati b7ad1c4bf8 调整预设供应商按钮外观与搜索框位置 (#4183)
* 调整预设供应商按钮外观与搜索框位置

1. 调整预设供应商按钮外观,显示默认图标,大小统一;
2. 调整预设供应商搜索框位置。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(provider): 新增预设按钮外观与 inline 搜索的单元测试

覆盖:
1. 所有预设按钮固定 200px 宽度,视觉对齐一致
2. preset.icon 存在时按钮内渲染 ProviderIcon
3. preset 无 icon 且无 theme.icon 时渲染占位元素保持文字对齐
4. 点击放大镜 inline 切换搜索输入框可见性,ESC 收起并清空

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(provider-preset): responsive grid layout and search polish

- Replace fixed-width preset buttons with a responsive CSS grid (auto-fill, 150px min column)
- Add a leading placeholder to the custom button so its label aligns with iconed presets
- Close the inline search box on outside click, restoring the old Popover behavior
- Span the empty-state hint across the full grid row
- Update component tests for the new layout and behaviors

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-06-14 18:18:43 +08:00
thisTom 0c46efe1be fix(macos): prevent duplicate provider terminal sessions (#4156)
* fix(macos): prevent duplicate provider terminals

* fix(macos): keep Ghostty fallback on AppleScript failure

---------

Co-authored-by: thisTom <19346741+thisTom@users.noreply.github.com>
2026-06-14 16:55:23 +08:00
Jason 11572b1337 feat(codex): restore Kimi For Coding preset with thinking on by default
The Kimi For Coding preset was removed (74104946) because the coding
endpoint (api.kimi.com/coding/v1) enforces a User-Agent whitelist that
rejects Codex's default codex-cli UA with 403. The provider-level custom
User-Agent feature now lets users override the UA (to claude-cli/*) under
proxy takeover, so the preset can be restored.

- Re-add the Codex Kimi For Coding preset (openai_chat, kimi-for-coding,
  256K context) in the same position it was removed from.
- Enable thinking mode by default via codexChatReasoning (supportsThinking
  true, thinkingParam "thinking"), mirroring the general Kimi preset since
  both target the same Moonshot model family. The proxy injects
  thinking:{type:enabled} when Codex requests reasoning.
- Restore the trilingual user-manual row to "Kimi / Kimi For Coding".

Note: this preset requires proxy takeover and a whitelisted custom
User-Agent to work; the default codex-cli UA still gets 403.
2026-06-13 23:47:27 +08:00
Jason 3bb17434fb test: align preset tests with Kimi K2.7 and Fable model tiers
Update the Codex chat preset test's Kimi expectation (kimi-k2.6 -> kimi-k2.7-code) after the Kimi K2.7 upgrade, update the Claude Desktop form test for the four-tier (Sonnet/Opus/Fable/Haiku) routes, and reformat UsageDateRangePicker imports (prettier).
2026-06-13 23:16:11 +08:00
Jason efbb52a3fc feat(presets): add GLM 5.1 context window for AtlasCloud Codex preset
Declare the 200000-token context window for zai-org/glm-5.1, matching the other GLM 5.1 preset entries.
2026-06-13 23:16:11 +08:00
Jason b37a9e8f60 chore: remove stray nested preset file accidentally committed in #667
cc-switch-main/src/config/universalProviderPresets.ts was an outdated duplicate of the real preset file, introduced by mistake in #667 and referenced by no code. Remove the orphaned nested directory.
2026-06-13 23:16:11 +08:00
Jason 1992d6be72 feat: add Kimi K2.7 Code model and upgrade official Kimi presets
Add kimi-k2.7-code pricing seed (in $0.95 / out $4.00 / cache-read $0.19
per 1M tokens, 256K context) and point all six official Moonshot Kimi
presets (Claude Code, Codex, Claude Desktop, Hermes, OpenCode, OpenClaw)
at the new model. Rename the version-tagged OpenCode/OpenClaw presets to
"Kimi K2.7 Code" and correct the OpenClaw context window to 262144.

The seed is applied via the idempotent INSERT OR IGNORE path that runs on
every startup, so existing users pick up the new pricing without a schema
migration. Kimi For Coding and Nvidia presets are intentionally untouched.
2026-06-13 22:26:36 +08:00
Jason 276b2572a3 fix(providers): scope preset search to provider names only
The preset search text also included websiteUrl and the shared category label, producing imprecise matches: a single category term matched the whole group, and URL fragments like "com"/"api" matched nearly everything. Restrict the search text to the display name and raw name; category labels are still used for rendering.
2026-06-13 22:15:32 +08:00
Jason cd8252c7d9 fix(ui): raise popover/tooltip z-index above fullscreen panels
PopoverContent and TooltipContent used z-50, below FullScreenPanel's z-[60] opaque overlay. Popovers such as the provider preset search therefore rendered behind the panel and looked unresponsive on click. Bump both to z-[100], matching the select dropdown: above fullscreen panels, below modal dialogs (z-[110]).
2026-06-13 22:15:31 +08:00
Jason 526bb60f5c fix(ui): make Claude Desktop model-mapping placeholders role-consistent
The menu display name and request model columns used mismatched example
brands (DeepSeek vs Kimi), implying a display name maps to an unrelated
request model. Derive both placeholders from the row role so each row
stays brand-consistent, and route the lightweight Haiku tier to a flash
example (deepseek-v4-flash) while other tiers use deepseek-v4-pro.
2026-06-13 20:16:09 +08:00
Jason 4f8a79c273 feat: add Claude Fable 5 model mapping across Claude Code and Desktop
- Wire claude-fable-5 as a fourth tier on both proxy paths, with a
  fable -> opus -> default fallback mirroring the official downgrade.
- Whitelist the fable- prefix for the Desktop 1.12603.1+ validator.
- Clarify fallbackModelHint (zh/en/ja/zh-TW): a blank tier on
  third-party endpoints forwards the literal model name and 404s.

Refs #3980, #4026, #4049.
2026-06-13 19:12:34 +08:00
Jason 6e519a7496 fix(usage): compact toolbar controls and unify visual style
- Reduce all four filter controls to w-[100px] h-9
- Add ChevronDown icon to date picker trigger for consistency
- Suppress focus border highlight on select triggers after close
2026-06-12 23:48:41 +08:00
Jason a95b22dd79 fix(ui): keep ToggleRow icon from shrinking next to long descriptions 2026-06-12 23:35:07 +08:00
Jason eab6bfd20c feat(codex): add opt-in migration and ledger-based restore for unified session history
- Enable dialog gains a checkbox (default off) to migrate existing
  official sessions from the built-in "openai" bucket into the shared
  "custom" bucket, with per-generation backups; failed migrations retry
  at startup
- Disable dialog offers a precise restore driven by the backup ledger:
  only sessions recorded as "openai" in backups are flipped back, and
  sessions created while the toggle was on are never touched
- Completion marker and backup generations are bound to the canonical
  Codex config dir; migrate/restore serialize on an op lock and the
  marker is written conditionally inside the settings write lock
- save_settings rolls back the toggle and fails the save when the live
  rewrite fails; migration additionally requires the live config to
  actually route to the shared bucket (skips with live_not_unified so
  refused injection or proxy takeover can't split history)
- Restore refuses to run while the toggle is (re-)enabled and reports
  nothing_to_restore instead of a zero-count success; local migration
  markers are now backend-owned in merge_settings_for_save so stale
  frontend payloads can't resurrect them
- Settings autosave reverts optimistic form state on failure so a
  failed toggle change can't be replayed by an unrelated save
- ConfirmDialog supports an optional checkbox; all four locales updated
2026-06-12 23:35:01 +08:00
Jason 948d762792 feat(codex): add unified session history toggle for official providers
Codex buckets resume history by the model_provider id recorded in each
session: official runs (no key, built-in "openai") and cc-switch
third-party runs (shared "custom") are mutually invisible in the resume
picker. Add an opt-in setting that runs official providers under the
shared "custom" id so future official sessions land in the same history
bucket as third-party ones. Forward-only by design: existing sessions
are not migrated.

When enabled, official live config.toml gets model_provider = "custom"
plus a [model_providers.custom] entry that mirrors the built-in openai
provider (requires_openai_auth routes auth to the ChatGPT login in
auth.json, name "OpenAI" keeps is_openai() feature gates, explicit
supports_websockets/wire_api restore built-in defaults). auth.json is
untouched.

Key invariants:
- Injection lives only in the live config: switch-away backfill strips
  the exact injected shape, so stored provider configs stay clean and
  turning the toggle off fully reverts on the next write.
- Toggle changes apply immediately via a takeover-aware reapply: when
  the proxy owns the live config (backup/placeholder present), only the
  live backup is updated, mirroring the provider-switch path.
- The takeover backup path runs the same injection so a takeover
  release restores a config that still carries the unified routing.
- Injection refuses to activate a foreign [model_providers.custom]
  table (e.g. stale entry with a third-party base_url) to avoid routing
  ChatGPT OAuth traffic to an unknown backend.

The toggle lives under Settings → Codex App Enhancements; the
description warns that resuming old sessions across providers may fail
because encrypted_content reasoning only decrypts on the backend that
created it (upstream treats cross-provider resume as unsupported).
2026-06-12 10:40:51 +08:00
Jason 4f355970e1 chore(presets): remove LemonData provider and demote SudoCode to regular provider
- LemonData: delete the provider preset from all apps (claude, claude-desktop,
  codex, gemini, hermes, opencode, openclaw), remove partner promotion copy
  (zh/en/ja/zh-TW), icon index/metadata entries, sponsor ads in all READMEs,
  and the logo/icon PNG assets.
- SudoCode: drop the isPartner flag and partnerPromotionKey across all app
  presets and remove the now-orphaned partner promotion copy; it stays as a
  regular third_party provider, keeping its icon.
2026-06-11 23:15:11 +08:00
Jason 22ecd2d611 feat(usage): turn refresh interval into a select and align control widths
Replace the click-to-cycle refresh button with a Select matching the
source/model filters. The "off" option now shows a localized label
(zh/en/ja/zh-TW) instead of the cryptic "--", and changing the interval
still invalidates all usage queries for an immediate refresh.

Align the top-bar controls into two width groups: source and model
selects at 120px, refresh select and date range trigger at 150px. The
date range button moves from auto width to fixed, so its long custom
range label gets truncate + hover title, and the calendar icon is
shrink-proofed.
2026-06-11 22:42:26 +08:00
Jason a75f479576 feat(usage): lift provider/model filters to dashboard-wide scope
The provider/model filters only lived inside the request-log table, so
there was no way to see "how much did app X spend on source Y" across
the whole dashboard. Promote them to the top bar next to the app
filter, applying globally to the hero summary, trend chart, request
logs, and both stats tabs.

Backend: the five stats queries (summary, summary-by-app, trends,
provider stats, model stats) accept optional provider_name/model
filters, applied to both the detail and daily-rollup branches (the
rollup PK already carries provider_id/model/pricing_model). Sources
match by exact display name via provider_name_coalesce, so session
placeholder rows like "Claude (Session)" are selectable; models match
by effective pricing model (pricing_model falling back to model), the
same grouping key the model-stats tab uses. Request-log filtering
switches from LIKE to these exact semantics.

Frontend: two truncating dropdowns list only sources/models that have
data in the current range, with the model list cascading from the
selected source. Dynamic option values are prefix-encoded so a source
literally named "all" cannot collide with the sentinel, query keys
fall back to null instead of "all", and the option queries follow the
dashboard refresh interval (otherwise their default 30s polling drags
same-key stats queries along even with refresh disabled). The
request-log filter bar keeps only the log-specific status-code select.
Labels read "sources" rather than "providers" because direct-connect
session buckets sit alongside real providers. i18n updated across
zh/en/ja/zh-TW.
2026-06-11 22:42:26 +08:00
Jason c701068f0c feat(usage): replace app filter text labels with app icons
The text tabs (All / Claude Code / Codex / Gemini / OpenCode) wrapped
awkwardly in narrow windows. Render app icons via ProviderIcon instead,
mirroring AppSwitcher's icon mapping (codex reuses the openai icon),
with a LayoutGrid icon for "all". Localized labels are kept as
title/aria-label on each button.
2026-06-11 22:42:26 +08:00
Jason c7efa77ad9 refactor(usage): fold claude-desktop into claude in the dashboard
The Desktop gateway's proxy traffic is still recorded under its own
app_type for route-takeover billing audit (the request detail panel
shows the real value), but the dashboard now folds it into `claude`
for display. A standalone "Claude Desktop" bucket only ever showed a
partial number: Desktop chat usage never passes through the proxy and
has no scannable local source, while its Code-tab sessions are just the
embedded Claude Code runtime writing into the shared ~/.claude/projects
tree — so a separate bucket misled users into reading it as Desktop's
full usage.

Backend: new `folded_app_type_sql` helper wraps the app_type column in
every dashboard read path (10 filter sites + the by-app projection) so
`= 'claude'` also matches claude-desktop and GROUP BY merges the two,
without changing bound-param counts. Dedup matching and provider-limit
checks keep exact comparison; get_request_logs folds only the WHERE
filter and keeps the raw app_type in its row projection.

Frontend: drop claude-desktop from the dashboard AppType/KNOWN_APP_TYPES
filter list, the UsageHero theme, and the now-dead appFilter locale key
in all four languages (the managed-app apps.claude-desktop label stays).

Adds test_claude_desktop_folds_into_claude_for_display.
2026-06-11 22:42:26 +08:00
codeasier 2d64d8c619 fix(proxy): preserve Codex OAuth auth token on takeover (#3789)
* fix(proxy): preserve Codex OAuth auth token on takeover

* style(proxy): format Codex OAuth takeover fix

* fix(proxy): unconditionally inject AUTH_TOKEN placeholder for codex takeover

The preserve-if-exists condition left #3784 unfixed on three paths:
hot-switch passes the provider's settings (presets carry no
ANTHROPIC_AUTH_TOKEN key), fresh installs never had the key, and live
configs already stripped by older releases stay stripped.

- Fold the bool parameter into the policy enum as
  ManagedAccount { keep_auth_token } so every construction site
  declares intent
- Decide via !is_github_copilot() within the managed branch so
  URL-only codex providers (no provider_type meta) are covered,
  matching the predicate family used for policy selection
- Inject the placeholder unconditionally instead of only when the
  key pre-exists; Copilot behavior is unchanged (API_KEY only)
- Pin the previously uncovered cases with tests: codex without a
  pre-existing key, URL-only codex, and Copilot removing a stale
  AUTH_TOKEN

---------

Co-authored-by: codeasier <liuyekang@huawei.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-06-11 22:21:42 +08:00
osscv d70e3828fe Add claude-mythos-5 model to schema (#4077)
Insert a new 'claude-mythos-5' model tuple into src-tauri/src/database/schema.rs. The tuple ("claude-mythos-5", "Claude Mythos 5", "10", "50", "1.00", "12.50") is added to the models list (placed before the Claude 4.8 series) to register the Mythos 5 model with the Database schema.
2026-06-11 21:53:11 +08:00
Jason Young 7bb59fa5a6 fix(proxy): harden takeover-residue recovery across config-dir switches (#4076)
Changing app_config_dir relocates the SQLite database, so a restart
triggered while proxy takeover is active used to strand the live
configs: the new instance reads a fresh DB with no live backups, the
first-run import then persisted the PROXY_MANAGED placeholder as the
`default` provider, and the no-backup recovery path wrote that
placeholder right back to the live files — leaving Claude/Codex/Gemini
pointed at a dead local proxy with no automatic way out.

Three orthogonal fixes, defense in depth:

- restart_app now awaits cleanup_before_exit() before app.restart().
  Since #4069 the ExitRequested handler intentionally defers restart
  requests to Tauri's default re-exec without custom cleanup, which is
  correct for same-DB restarts but not for this command's dir-change
  use case: only the old instance holds the backups needed to restore
  the taken-over live files, so it must restore them while its event
  loop is still alive.
- import_default_config refuses to import a live config that is under
  proxy takeover (placeholder detected), instead of persisting it as
  the current provider.
- restore_live_from_ssot_for_app validates that the current provider's
  settings_config does not itself contain takeover placeholders before
  writing it back; polluted SSOT now falls through to the placeholder
  cleanup fallback.

Regression tests cover the import guard and the no-backup recovery
path (the latter fails before this change by writing PROXY_MANAGED
back to live).
2026-06-11 21:32:24 +08:00
Jason Young 4f3e85fcd1 fix(updater): drive download/install/restart from backend to avoid hang (#4074)
* fix(updater): drive download/install/restart from backend to avoid hang

The 3.16/3.16.1 update flow was frontend-driven: downloadAndInstall()
then relaunchApp(). relaunch() routed through AppHandle::restart(), and
the old WebView had to keep running JS after the .app bundle was already
swapped — an unstable window that could hang the update or leave the old
version running until a manual restart.

Move the whole download -> install -> cleanup -> restart chain into a new
backend command install_update_and_restart, so it no longer depends on the
old WebView running JS after the bundle is swapped.

Platform-aware install ordering (install() behaves differently per OS):
- Windows: install() launches the external installer and exits the process
  internally, so cleanup + single-instance destroy must run before install.
  Surface a recovery hint on failure since the proxy may already be stopped.
- macOS/Linux: install() returns, so install first then cleanup — an install
  failure no longer wrongly stops the proxy / reverts takeover.

Eliminate the restart vs single-instance race: restart_process() destroys
the single-instance lock (remove socket on macOS, ReleaseMutex on Windows)
before tauri::process::restart(), so the freshly spawned process can't
connect to the old listener and exit itself.

Also remove the now-dead frontend update plumbing (relaunchApp,
UpdateHandle, mapUpdateHandle) and surface backend errors in the toast.

Adapted from the original af4271f4 while rebasing onto #4069: the
ExitRequested handler changes were dropped entirely — the classifier from
#4069 already routes RESTART_EXIT_CODE to Tauri's default restart flow,
and the original should_restart branch (prevent_exit + async cleanup)
would have reintroduced the window-state deadlock that #4069 fixed.
install_update_and_restart bypasses ExitRequested entirely, so the two
fixes compose cleanly.

* fix(updater): clear tray icon on the direct-restart update path

restart_process re-execs via tauri::process::restart (spawn + exit(0)),
which skips Tauri's internal cleanup_before_exit and all RunEvent::Exit
plugin hooks. Window state, proxy/live restore and the single-instance
lock were already compensated explicitly; the tray icon was not.

On macOS/Linux the OS drops the status item when the process dies, so
the gap there was cosmetic at most. The real residue risk is the
Windows branch, which never reaches restart_process at all:
update.install() exits the process inside the updater plugin
(std::process::exit(0)), bypassing TrayIcon::drop — no NIM_DELETE is
sent and a stale icon lingers in the shell until hovered, the same
failure remove_tray_icon_before_exit was originally added for on the
quit path.

Call remove_tray_icon_before_exit (set_visible(false), proxied to the
main thread via run_item_main_thread) in restart_process and before
the Windows install. Deliberately not AppHandle::cleanup_before_exit():
it drops tray icons on the calling thread, which is not safe off the
main thread on macOS (NSStatusItem).
2026-06-11 21:30:02 +08:00
thisTom a3598fd976 fix: prevent deadlock when relaunching after in-app update (#4069)
The updater's relaunch() (and app.restart()) triggers ExitRequested
with code RESTART_EXIT_CODE, which the handler treated as a regular
exit: it called api.prevent_exit() and spawned an async cleanup task.

However Tauri silently ignores prevent_exit() for restart requests
(see ExitRequestApi::prevent_exit docs), so the event loop keeps
shutting down regardless and fires every plugin's RunEvent::Exit hook.
Two threads then deadlock:

- the spawned cleanup task runs save_window_state on a tokio worker,
  holding the window-state plugin's internal mutex while querying
  window geometry, which dispatches to the main thread and blocks;
- the main thread, already inside the plugin's own RunEvent::Exit
  hook, blocks on that same mutex.

The app freezes forever on the restarting screen with the update
already installed; force-quit + reopen comes back on the new version
(#3998). Confirmed on macOS by sampling the frozen process: main
thread parked in tauri_plugin_window_state save_window_state mutex
lock, tokio worker parked in is_maximized -> mpsc recv.

Fix: classify exit requests (None / restart / user exit) and let
restart requests fall through untouched to Tauri's default restart
flow (RunEvent::Exit -> re-exec). On that path window state is saved
by the plugin's exit hook on the main thread, the tray icon is
cleaned up by Tauri's internal cleanup_before_exit, and proxy/live
config restore is unnecessary because the new instance takes over
immediately. The regular exit path (tray quit) is unchanged.

With the fix, a simulated updater relaunch (request_restart) re-execs
the new process in under 200ms, 3/3 runs; normal quit still performs
full cleanup.

Co-authored-by: thisTom <19346741+thisTom@users.noreply.github.com>
2026-06-11 17:24:06 +08:00
Peng Steam c1aa6c3917 feat(providers): add preset search and sorting (#3975) 2026-06-11 17:14:53 +08:00
Jason daa5595f36 feat(presets): add Unity2.ai partner provider across seven apps
Add Unity2.ai, a high-performance AI API relay partner, as a preset for
Claude, Codex, Gemini, OpenCode, OpenClaw, Claude Desktop, and Hermes.
Each preset carries the referral signup link as apiKeyUrl.

- Register the unity2 icon via iconUrls (PNG URL import) + metadata
- Add partnerPromotion copy in zh/en/ja/zh-TW; backfill the missing
  zh-TW ccsub entry
- List Unity2.ai in the sponsor section of all README locales
- Codex uses the bare base URL (gateway exposes /responses at root);
  OpenCode/OpenClaw/Hermes use the /v1 chat-completions endpoint with
  gpt-5.5 as the only preset model
- Trim CCSub OpenCode/OpenClaw/Hermes model lists to gpt-5.5 to match
- Normalize unity2/ccsub banners to the standard 2.41 aspect ratio
2026-06-11 11:05:32 +08:00
Jason 819c2e5dfe chore: ignore AGENTS.md alongside CLAUDE.md
Suggested in #4015.
2026-06-11 08:43:33 +08:00
Jason a6d718d0fc fix(proxy): aggregate mislabeled SSE bodies in transform fallback (#2234)
The Claude/Codex format-transform non-stream branch returned an opaque 422
"Failed to parse upstream response" whenever a 2xx upstream body was not
valid JSON. The common case: MaaS gateways force-stream a stream:false
request and return an SSE body with a non-SSE Content-Type, defeating the
header-only is_sse() check.

On serde failure, sniff for SSE and aggregate the chunks into a single
JSON, then run the existing converter so clients still receive a valid
non-stream response.

- chat_sse_to_response_value: aggregate chat.completion.chunk SSE
  (content / reasoning / refusal / tool_calls / legacy function_call),
  tool_calls index-keyed via BTreeMap to avoid unbounded densification,
  first-wins finish_reason, message-snapshot override, completeness and
  error-event guards; synthesize an id when the upstream omits one
- responses_sse_to_response_value: process the residual trailing block,
  tolerating truncation and skipping it once a completed event was seen
- enrich remaining parse failures with content-type / content-encoding /
  body-snippet diagnostics
- deflate: try zlib (RFC 9110) before raw; keep the content-encoding
  header for unsupported encodings
- gate zero-usage rows on the Claude transform path
2026-06-11 08:29:29 +08:00
Jason e776160912 feat(provider-form): consolidate codex form into advanced options section
- Fold local routing toggle, model mapping, reasoning overrides and custom
  User-Agent into a single collapsible advanced section, mirroring the
  Claude form (auto-expands when UA is set or local routing is enabled)
- Custom User-Agent becomes configurable for native Responses providers;
  it was previously reachable only when openai_chat routing was on
- Collapsed hint names local routing as the entry point for Chat
  Completions / non-GPT providers
- Backfill all missing codexConfig keys in zh-TW locale
2026-06-11 08:29:29 +08:00
Jason 596019505f feat(provider-form): custom User-Agent presets dropdown in advanced settings
Polish the provider-level User-Agent override UI on the Claude and Codex forms.

- Add a shared CustomUserAgentField (label + input + preset dropdown + live
  validation) so both forms stay in sync.
- Provide curated UA presets (Claude Code / Kilo Code families that pass
  coding-plan UA whitelists per #3671); the first is Claude Code's real
  `claude-cli/x (external, cli)` format. Whitelists gate on the name prefix,
  not the version, so static values stay valid across upgrades.
- Expose presets via a dropdown to the right of the input (z-[200] so it
  renders above the dialog layers) instead of inline chips.
- Move the field into the existing advanced/reasoning collapsibles.
- userAgent.ts mirrors the backend byte rule (reject only control chars;
  non-ASCII is allowed) for a non-blocking inline hint.
- i18n for all four locales (zh/en/ja/zh-TW).
2026-06-11 08:29:29 +08:00
Jason 8b925c2f2f feat(proxy): honor custom User-Agent across stream check and model fetch
Extract a shared `parse_custom_user_agent` helper in provider.rs returning
`Result<Option<HeaderValue>>`, and reuse it in the forwarder, stream check,
and model fetch paths so detection, forwarding, and model listing all apply
the same provider-level User-Agent. Previously only the forwarder honored it,
so stream check could fail (or model listing 403) on UA-gated upstreams that
the proxy itself handled fine.

- stream_check injects the provider's custom UA on the claude/codex paths and
  still skips the GitHub Copilot fingerprint UA.
- model_fetch service + command and the model-fetch.ts wrapper thread an
  optional UA through to GET /v1/models.
- runtime callers silently ignore invalid values via `.ok().flatten()`
  (no save-time block, so deeplink imports stay lenient).
2026-06-11 08:29:29 +08:00
RoromoriYuzu 25983f3420 fix: omit customUserAgent when provider category is official
Stale custom UA values from non-official presets were persisted even
after switching to an official preset, silently altering request headers.
2026-06-11 08:29:29 +08:00
RoromoriYuzu ff706e9e96 feat: add provider user agent override 2026-06-11 08:29:29 +08:00
Jason e8b07cb2a5 feat(usage): claude-desktop filter and pricing-model audit display
- add claude-desktop to AppType/KNOWN_APP_TYPES and the dashboard app
  filter; it was hidden because its rows looked like pure failure
  noise, which was the app_type attribution bug fixed on the backend
- request detail panel now shows the requested model and the pricing
  model when they differ from the response model, making route-takeover
  bills auditable from the UI
- locale keys added for zh/en/ja/zh-TW
2026-06-11 08:29:29 +08:00
Jason feea81e5bb fix(proxy): bill route-takeover traffic by the real upstream model
The model mapped for takeover (env mapping, Claude Desktop routes,
Copilot normalization, Codex chat override) was discarded inside the
forwarder, so usage attribution depended entirely on the upstream
echoing it back. When the upstream omitted the model or mirrored the
client alias, kimi/glm tokens were recorded and priced as claude-*
(roughly 5-25x overstatement).

- capture the final outbound model in forward(), return it via
  ForwardResult, and store it on the request context
- attribution fallback order is now: upstream echo (empty string
  treated as missing) -> outbound model -> client-requested model
- 'request' pricing mode anchors to the outbound model instead of the
  pre-mapping client alias; unchanged when no mapping applies
- persist the resolved pricing_model on every usage row
- Claude Desktop rows now log app_type "claude-desktop" on streaming
  and transform paths too (was hardcoded "claude", silently dropping
  desktop provider pricing overrides and splitting the cost basis by
  the stream flag); its global pricing defaults inherit the claude
  config since proxy_config only allows claude/codex/gemini rows
2026-06-11 08:29:29 +08:00
Jason 4282856683 feat(usage): persist pricing basis and takeover dimensions in storage (schema v11)
- proxy_request_logs: add pricing_model column recording the basis actually
  used at write time (NULL = pre-v11 rows, '' = unpriced error rows)
- cost backfill recomputes strictly by the persisted basis; the
  request_model fallback now only applies to placeholder models, so
  real-but-unpriced takeover rows stay at zero cost until pricing is
  added instead of being permanently frozen at the alias's price
- backfill_missing_usage_costs_for_model can locate rows by pricing_model
- usage_daily_rollups: rebuild with request_model + pricing_model in the
  primary key so the alias-to-real-model mapping and the pricing basis
  survive the 30-day prune; legacy rows migrate with ''
- rollup_and_prune backfills costs before pruning: prune is irreversible
  and used to run before the startup backfill, permanently booking
  then-unpriced rows as zero
- get_model_stats groups by the effective pricing model
  (COALESCE(NULLIF(pricing_model,''), model)) so costs aggregate under
  the model whose prices produced them; response-mode behavior unchanged
2026-06-11 08:29:29 +08:00
Jason 65d6929993 fix(coding-plan): classify Zhipu quota windows by unit field instead of reset-time order (#3036)
The Zhipu quota API returns two TOKENS_LIMIT entries whose identity was
inferred by sorting nextResetTime ascending (nearest = five_hour). In the
last hours of each weekly cycle the weekly window resets sooner than the
current 5-hour session window, so the two buckets were swapped exactly
when users check their weekly quota most.

Classify by the explicit unit field instead (3 = hour window -> five_hour,
6 = week window -> weekly_limit; same shape on bigmodel.cn and api.z.ai,
weekly observed with number 7 and 1 so only unit is matched), falling back
to the old reset-time heuristic when the field is missing.
2026-06-11 08:29:29 +08:00
Jason 1ca01bcd10 feat(usage): refresh model pricing seed — add Fable 5 + 8 models, fix 28 prices
Full audit of seed_model_pricing against current official vendor pricing.

New models: claude-fable-5 (10/50), grok-4.3, step-3.7-flash,
mistral-medium-3.5, mistral-small-4, devstral-small-2-2512, magistral-small,
qwen3.7-max, qwen3.7-plus.

Price fixes (Chinese vendors standardized on official list price, CNY/~7.14):
- GLM 4.6/4.7 -> Z.ai official 0.6/2.2/0.11 (were reseller/OpenRouter rates)
- Grok 4.20 reasoning/non-reasoning -> 1.25/2.50 (xAI price cut)
- MiMo v2.5 / v2.5-pro / v2-pro -> post-2026-05-27 rates + cache
- Doubao Seed 2.0 lite corrected + cache-hit prices across the family
- Kimi k2.5 output 3.00, MiniMax m2.5 input 0.15, Mistral devstral-2 output 2
- Qwen 3.5/3.6-plus + coder-plus/flash cache_read (official 20%-of-input rule)

Each fix updates the seed value (fresh installs) and adds an old->new guard to
repair_current_model_pricing (existing DBs; won't clobber user-edited rows).
2026-06-11 08:29:29 +08:00
Jason bc01f44514 feat(usage): app-aware hero icon and neutral Codex theme
- Replace the fixed Zap glyph in the usage hero with the selected app's
  brand icon via a new AppGlyph component, reusing APP_ICON_MAP
  (cloneElement scales 14px -> 20px); falls back to Zap for the "all" view.
- Recolor the Codex title theme from emerald to neutral gray to match
  OpenAI's monochrome branding. neutral-500/10 stays visible in both
  light and dark modes, unlike a flat black tint.
2026-06-11 08:29:29 +08:00
Jason 3390fe7ea0 fix(proxy): extend image rectifier to Codex /responses text-only path
Codex /responses requests routed to text-only OpenAI-chat upstreams
(e.g. DeepSeek deepseek-v4-flash) failed with HTTP 400 "unknown variant
image_url" when images were sent: the responses->chat conversion turns
input_image items into image_url blocks the model rejects. The media
rectifier previously covered only the Claude adapter, so neither the
proactive strip nor the reactive retry fired for Codex.

- media_retry_should_trigger: accept "Codex" adapter, not just "Claude"
- contains_image_blocks / replace_images: also scan responses `input`
  (input_image) in addition to chat `messages`
- is_image_block_type: match image | image_url | input_image
- is_unsupported_image_error: add "unknown variant" hint for the
  deserialize error
- forward(): proactively run apply_media_prevention for Codex after the
  responses->chat conversion

Proactively strips images for known text-only models (heuristic on by
default) and reactively retries with images replaced on upstream
image-unsupported errors. Adds tests for chat image_url, codex
input_image, the reactive trigger, and the deserialize error match.
2026-06-11 08:29:29 +08:00
Jason cb01593f7d fix(proxy): exclude cache_read and cache_creation from input on Claude←OpenAI paths
Builds on #2774 (which fixed cache_read for the streaming openai_chat path).
Two gaps remained, both double-counting cache tokens when a Claude client
meters as app_type="claude" (input_includes_cache_read=false):

1. cache_read was still added to input on the non-streaming openai_chat path
   (transform.rs openai_to_anthropic) and the whole openai_responses family
   (transform_responses.rs build_anthropic_usage_from_responses, covering the
   non-streaming call site and both streaming_responses call sites).

2. cache_creation was never subtracted on any converted path, including the
   streaming openai_chat path #2774 had already touched. Claude billing treats
   cache_creation as a separate bucket, so an inclusive upstream carrying a
   direct cache_creation_input_tokens field billed it twice.

All four metering points now compute:
  input = prompt_tokens - cache_read - cache_creation
restoring the invariant input + cache_read + cache_creation == prompt_tokens.
Pure OpenAI upstreams are unaffected (no cache_creation concept/field).

Tests: update direct-cache assertions (40->20), add a streaming conservation
regression test, and pin prompt<cache underflow (saturating clamp to 0) for all
three metering functions. cargo test 1573 pass, clippy clean.

Note: fix is forward-only; historical rows are not recomputed (cost is frozen at
log time and app_type="claude" mixes native + converted rows).
2026-06-11 08:29:29 +08:00
Jason 36a103bbe4 fix(proxy): correct usage accounting on format-conversion paths
Audited all proxy format-conversion paths (Chat<->Message, Chat<->Response,
Gemini<->Message) for usage/cache metering. Five issues found and fixed.
The dedup mechanism (request_id PK, proxy/session source isolation) is
untouched, so no double-counting is introduced.

- A (Claude + openai_chat, streaming): inject stream_options.include_usage
  so OpenAI-compatible upstreams emit usage in the SSE tail. Without it the
  converted Anthropic message_delta was all-zero and the whole request's
  input/output/cache was dropped. Same root cause as the already-fixed
  Codex Chat path; the injection is extracted into a shared helper
  (transform::inject_openai_stream_include_usage) reused by both paths.

- C (Claude + gemini_native): subtract cachedContentTokenCount from
  input_tokens in build_anthropic_usage so input becomes fresh input
  (Anthropic semantics). Previously the cache-hit tokens were billed twice
  because this path meters as app_type="claude" (input_includes_cache_read
  = false) while Gemini's promptTokenCount includes the cache.

- D (Codex + openai_chat, streaming): gate log_usage on
  has_billable_tokens() to skip the synthetic all-zero usage the converter
  emits when a non-compliant upstream omits usage, preventing empty-row
  request-count inflation.

- P2 (from_claude_stream_events): use has_billable_tokens() for the return
  gate instead of input>0||output>0, so a fully-cached streamed request
  (cache_read>0, input==output==0) is still recorded. Affects all
  Claude-streaming paths, not just Gemini.

- P3 (Codex Chat->Responses, non-streaming): apply the same
  has_billable_tokens() filter the streaming branch got, since the
  synthesized all-zero usage makes from_codex_response return Some and
  bypass the `if let Some` guard.

Add TokenUsage::has_billable_tokens() as the unified predicate. New tests
cover include_usage injection, gemini input subtraction, the gate itself,
cache-only stream recording, and synthetic all-zero codex usage.
Full lib suite: 1569 passed.
2026-06-11 08:29:29 +08:00
Jason 05bc14e82b fix(usage): import billable session messages without stop_reason
The local session-log scanner dropped any assistant message that lacked
a stop_reason or had output_tokens==0. Claude Code Workflow / sub-agent
fan-out frequently produces messages that only wrote a message_start
snapshot (output=1, stop_reason=None) without a final block, yet their
input + cache_read + cache_creation tokens are already billed by
Anthropic (charged once the request is accepted). Dropping them
under-counted usage by ~4.1% overall, 92% concentrated in
workflow/subagent transcripts.

Replace the stop_reason/output gate with a billable-token check (any of
input/output/cache_read/cache_creation > 0). The per-message-id dedup
selection is unchanged, and request_id = "session:"+msg_id PRIMARY KEY
with INSERT OR IGNORE keeps each message single-inserted, so relaxing
the gate cannot double-count. Add a regression test covering a
stop_reason-less message with real cache cost plus an all-zero skip.

This is the parser-layer half of the Workflow under-counting fixed at
the collector layer in 8d332925.
2026-06-11 08:29:29 +08:00
Jason 0396cd5491 fix(usage): count Claude Code Workflow sub-agent token usage
collect_jsonl_files only walked <project>/<session>/subagents/*.jsonl,
so it missed Workflow sub-agent transcripts which live one level deeper
at subagents/workflows/wf_*/agent-*.jsonl. As a result all Workflow
token usage was invisible to the no-proxy session-log accounting.

Descend into subagents/workflows/wf_*/ as well, via a new
push_jsonl_children helper that keeps the fixed-depth, no-recursion
design. journal.jsonl carries no assistant rows so it is skipped at
parse time and needs no filename special-casing. Existing dedup
(request_id PK + INSERT OR IGNORE + should_skip_session_insert) keeps
the next sync's backfill idempotent.

Add test_collect_jsonl_files_includes_workflow_subagents.
2026-06-11 08:29:29 +08:00
Jason f97347fe6e docs(release): restore contributor mentions in release notes 2026-06-11 08:29:29 +08:00
pa001024 9ea303b224 fix: usage script provider credential resolution (#1479)
The JS-script usage path resolved {{apiKey}}/{{baseUrl}} with env-only
field guessing, so apps that store credentials elsewhere (Codex:
auth.OPENAI_API_KEY + config.toml base_url) always got empty values and
custom-template queries failed despite a fully configured provider.

- query_usage / test_usage_script now delegate to
  Provider::resolve_usage_credentials, the same per-app resolver used by
  the native balance/coding-plan path and mirrored by the frontend
  getProviderCredentials; explicit non-empty script values still win
- test_usage_script loads the provider and applies the same fallback,
  so testing matches what a saved script does
- the custom-template variable preview shows the effective values
  (script overrides first, then provider config) instead of always
  showing provider credentials
- extract_codex_base_url documents and test-locks the frontend-mirror
  invariant: non-active [model_providers.*] sections are never read

Reworked from the original patch to reuse the existing resolver instead
of duplicating per-app extraction.

Co-authored-by: Jason <farion1231@gmail.com>
2026-06-10 22:57:27 +08:00
que3sui 4f911727d2 fix: prevent duplicate YAML keys in Hermes config (#3267)
* fix: prevent duplicate YAML keys in Hermes config

Three changes in hermes_config.rs:
1. deduplicate_top_level_keys() - scan and remove duplicate top-level
   keys before YAML parsing, preventing "duplicate entry" parse errors
2. remove_all_sections() - helper to strip all occurrences of a given
   top-level key from raw YAML text
3. replace_yaml_section() now calls remove_all_sections() on the
   remainder after replacing the primary occurrence, preventing
   duplicate sections from accumulating on repeated writes

Fixes the issue where mcp_servers (or any top-level key) gets
duplicated in config.yaml, causing "Failed to parse Hermes config
as YAML: duplicate entry with key" errors.

Co-Authored-By: que3sui <204201112+que3sui@users.noreply.github.com>

* fix: handle CRLF and LF line endings in top-level key deduplication

is_top_level_key_line only accepted empty, space, or tab after the colon,
but deduplicate_top_level_keys uses split_inclusive('\n'), so lines end
with \n (LF) or \r\n (CRLF). Without accepting \r and \n as valid
post-colon characters, the dedup safety net never activates.

Add \r and \n checks to is_top_level_key_line, and three tests covering
LF, CRLF, and first-occurrence preservation.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(hermes): keep last occurrence when healing duplicate YAML keys

Reworks the healing layers on top of the CRLF root-cause fix:

- deduplicate_top_level_keys: keep the LAST occurrence of each duplicated
  key instead of the first. Duplicates come from section replacement
  degrading into appends (#3633), so the last block is the newest data --
  and Hermes itself reads the config with PyYAML, whose duplicate-key
  semantics are last-wins. Keeping the first occurrence would silently
  roll users back to stale config and diverge from what Hermes runs with.
  Healthy files take a fast path and are returned untouched.
- Drop the unused dup_key variable (fails cargo clippy -- -D warnings,
  which CI enforces).
- replace_yaml_section: clean residual duplicate sections from the
  remainder via remove_all_sections; values come from the keep-last
  healed read, so dropping all stale on-disk copies loses nothing.
- Add regression tests for the actual root cause (find/replace on CRLF
  input must replace in place, not append), keep-last semantics,
  identity on healthy files, end-to-end heal-then-parse, and duplicate
  cleanup on write.

Fixes #3633 #2973 #2529 #3310 #3762

---------

Co-authored-by: que3sui <204201112+que3sui@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-06-10 21:42:54 +08:00
LaoYueHanNi edc597ab23 修复 Completions转Anthropic时不记录实际返回模型、Input token记录错误问题 (#2774)
* fix(proxy): 修复completions转claude格式流式响应未记录实际命中模型

* style: cargo fmt fix

* fix(proxy): 修复completions转claude格式时input与cache_read重复计费

* fix(proxy): 修复完全缓存命中时input_tokens计算错误

* test: 更新input_tokens期望值匹配去重逻辑
2026-06-09 20:30:05 +08:00
oriengy 955ea26da9 fix(presets): add Kimi affiliate links (#3809)
Problem: Kimi and Moonshot preset links were user-clickable without the cc-switch affiliate query.\n\nDecision: Update only UI-facing preset website/API-key links and leave API request endpoints untouched.\n\nChange: Add aff=cc-switch to Kimi/Moonshot websiteUrl values and Codex/OpenCode API-key links.

Co-authored-by: xumingyuan <xumingyuan@msh.team>
2026-06-08 23:25:28 +08:00
Jason 5beb63e67d refactor(presets): align CCSub to end of partner block across apps
Move the CCSub preset to sit right after DouBaoSeed, at the end of the
partner block and before the first non-partner provider, so its position
is consistent across all six apps:

- Codex / OpenCode: moved up from the 2nd slot (between Shengsuanyun and
  the next partner) to the block tail
- OpenClaw / Hermes: moved up from the aggregator section to the block tail
- Claude / Claude Desktop: already at the block tail

Also add the missing CHANGELOG entry for the CCSub preset, and drop the
provider preset order test that enforced a now-unneeded ordering invariant.
2026-06-08 23:07:50 +08:00
Jason fa17194d84 feat(presets): add CCSub provider across six apps
Add CCSub, a multi-model aggregator partner, as a preset for Claude, Codex, OpenCode, OpenClaw, Claude Desktop, and Hermes. Each preset carries the referral signup link as apiKeyUrl.

- Register the ccsub icon via iconUrls (1.1MB SVG URL import) + metadata
- Add partnerPromotion copy in zh/en/ja
- List CCSub in the sponsor section of all README locales
- Use gpt-5.5 and gemini-3.1-pro as the OpenAI/Gemini model ids
2026-06-08 22:04:16 +08:00
Jason f1118d370f chore(release): prepare v3.16.2
Add the v3.16.2 CHANGELOG entry covering the 41 commits since v3.16.1,
bump the version across package.json, tauri.conf.json, Cargo.toml, and
Cargo.lock, and add trilingual (zh/en/ja) release notes.
2026-06-08 12:39:50 +08:00
cc10143 4f5250fc4d fix(proxy): strip cache_control from OpenAI format conversion (#3841)
* fix(proxy): strip cache_control from OpenAI format conversion (#3805)

- Remove cache_control passthrough from system messages, text blocks,
  and tools to prevent 400 errors on strict OpenAI-compatible endpoints
- Always simplify single text block content to plain string format
- Fixes two format conversion bugs reported in issue #3805

* fix(proxy): apply cargo fmt to fix CI formatting check
2026-06-08 12:38:39 +08:00
Jason 5c36ae066b fix(providers): only block explicit official providers under proxy takeover
The proxy-takeover block previously fell back to the isOfficial heuristic
(empty base_url / missing key) when category was absent. That misjudged
custom providers whose endpoint lives in meta or whose fields are simply
unfilled: their switch button got disabled, making users think the config
was broken. That extra UI block was also "virtual" — the executor in
useProviderActions only ever honored category === "official", so the
front end blocked more than the backend would enforce.

Gate the block solely on explicit category === "official", matching the
executor and unifying both verdicts on a single source of truth.

Also rework the blocked-state UI:
- drop the red "blocked" badge for a plain disabled Enable button
- move title/cursor onto a wrapper span (disabled buttons set
  pointer-events:none, so an on-button title/cursor never fired)
- replace the account-ban warning tooltip with a lighter hint
  (provider.blockedByProxyHint), four locales kept in sync
2026-06-07 20:56:35 +08:00
Jason f59fab6c24 feat(proxy): map input_file and input_audio content parts to chat
Convert Responses input_file (requiring file_id or file_data, never file_url which Chat file parts do not support) and input_audio parts into their Chat Completions equivalents, and handle top-level input_* items that previously fell through and were dropped, clearing stale pending reasoning for non-assistant messages.
2026-06-07 20:56:35 +08:00
Jason 6940a4b208 fix(proxy): distinguish truncated chat streams from normal completion
Replace the unconditional finalize at chat-to-responses stream end with a three-way guard: complete normally when finish_reason or [DONE] arrived, emit an incomplete response when substantive output exists without a finish_reason, and emit a failed (stream_truncated) event for empty truncation instead of masking it as completed. Also propagate late-arriving reasoning_content onto still-active tool-call items.
2026-06-07 20:56:35 +08:00
Jason ea6123adf7 fix(proxy): cache reasoning across turns for custom_tool_call and tool_search_call
Generalize the cross-turn reasoning cache in codex chat history from function_call only to the full tool-call triad (function_call, custom_tool_call, tool_search_call) and their *_output counterparts, so apply_patch and tool-search calls keep their reasoning_content when restored via previous_response_id.
2026-06-07 20:56:35 +08:00
Jason e96eab5278 chore(presets): update SSSAiCode domain and endpoint nodes
Switch website/apiKey URLs to sssaicodeapi.com and replace base URL
nodes with node-hk.sssaicodeapi.com (default), node-hk.sssaiapi.com,
and node-cf.sssaicodeapi.com across all 7 app presets.
2026-06-07 20:56:35 +08:00
Jason 2985ad2c14 fix(proxy): resolve actual port for ephemeral (port 0) listen config
When listen_port is 0 the OS assigns the port at bind time, so the
configured value can no longer be trusted for building takeover URLs.

- server: read listener.local_addr() after bind and propagate the
  actual port to the global proxy port, status, and ProxyServerInfo
- services: start the proxy before takeover when port is 0 so live
  configs get the real port instead of :0, and persist the resolved
  port back to the DB for DB-only URL paths; stop the pre-started
  server on any takeover failure
- claude_desktop: reject an unresolved :0 port instead of emitting a
  broken gateway URL
- build_proxy_urls: prefer the running server's port and error out if
  the port is still 0

Add tests for takeover with an ephemeral port and the claude_desktop
:0 rejection; switch existing codex takeover tests to an ephemeral
port for isolation.
2026-06-07 20:56:35 +08:00
Alexlangl aa09c9cb62 fix: normalize localhost listen address (#3016) 2026-06-07 20:40:14 +08:00
CSberlin 27c41f7416 feat(proxy): add GET /v1/models endpoint for Codex CLI reachability check (#3818)
* feat(proxy): add GET /v1/models endpoint for Codex CLI reachability check

Codex CLI probes GET /v1/models at startup. Without this endpoint the proxy
returns 404, causing Codex to fail before any request reaches the upstream
LLM.

Return an OpenAI-compatible model list derived from the cc-switch–managed
model catalog file.

Fixes #3812

* fix(proxy): return Codex catalog schema from /v1/models

Codex deserializes the response as a catalog with a top-level `models`
field, not the OpenAI `{"object":"list","data":[...]}` envelope.
Return the catalog file content directly so the format matches what
Codex expects.

Co-authored-by: Codex review bot

* fix(proxy): guard /v1/models against serving stale catalog

Only return the model catalog when config.toml still references it via
`model_catalog_json`.  After switching to a provider without a custom
catalog, the old file lingers on disk — serving it unconditionally
would advertise the previous provider's models to Codex.

Co-authored-by: Codex review bot

* fix(proxy): match relative model_catalog_json in stale-guard

cc-switch writes `model_catalog_json = "cc-switch-model-catalog.json"`
(relative) via set_codex_model_catalog_json_field.  Match on the
filename constant rather than the absolute path so the guard works
with both relative and absolute paths.

Co-authored-by: Codex review bot

* fix(proxy): parse model_catalog_json field instead of substring match

Replace raw config_text.contains() with proper TOML field parsing so
commented-out lines and stray mentions of the filename in other fields
don't defeat the stale guard.  Also switch from contains() to exact
filename match (Path::new(val).file_name() == Some(...)) to stay
consistent with resolve_cc_switch_catalog_path in codex_config.rs.

Add log::debug! when the guard blocks serving so the operator can
distinguish "no models configured" from "guard blocked stale catalog".

* refactor(proxy): reuse resolve_cc_switch_catalog_path in handle_models

Replace the inline config.toml parsing and filename match in
handle_models with the existing resolve_cc_switch_catalog_path helper
(now pub(crate)). This removes the duplicated stale-guard logic, keeps
a single source of truth for catalog-path ownership, and makes the
handler honor absolute model_catalog_json paths the same way Codex
live-setting import does.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-06-07 20:26:44 +08:00
ayxwi 6716a4c408 [codex] Fix VS Code session previews (#3593)
* Fix Codex VS Code session previews

* fix(codex): use last IDE request heading for session previews

A markdown heading inside the active selection / open file could precede the real injected request, so matching the first "## My request for Codex:" heading picked selection content instead of the user prompt. Scan for the last matching heading (the IDE injects the real request as the final section) on both the Rust title path and the frontend TOC preview path.

Add regression tests for the selection-heading case, and pin the known best-effort limitation when the request body itself repeats the heading.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-06-07 19:23:24 +08:00
c9 2626eeebe6 fix: normalize path separators in scan_dir_recursive for Windows (#3430)
On Windows, Path::strip_prefix produces backslash-separated relative
paths. The update-check matching logic uses rsplit('/') to extract the
install name, so subdirectory skills (e.g. skills/my-skill) never
matched and updates were silently skipped. Replace backslashes with
forward slashes when building the directory string.
2026-06-07 17:57:37 +08:00
阿珏 ab6266f745 fix: 修复Windows退出托盘图标残留问题 (#3797) 2026-06-06 22:27:39 +08:00
lucas 1392ef6238 docs(readme): fix release note links and sponsor markup (#3772) 2026-06-05 22:58:07 +08:00
Dearli666 3cd9a0dec5 fix(proxy): 规范化 Anthropic system 消息 (#3775) 2026-06-05 22:50:49 +08:00
Jason 8e0e9ac319 fix(usage): correct inflated input_tokens in Claude stream parsing
Some Anthropic-compatible SSE providers (e.g. qwen, minimax) report the
full context (fresh + cached) as input_tokens in message_start, double
counting the cached portion that is also reported in
cache_read_input_tokens. This inflated the cacheable-input denominator
and pushed the displayed cache hit rate artificially low.

When a message_delta carries a smaller positive input_tokens, prefer it
over the message_start value and adopt the cache counts from the same
usage block to avoid double counting; fall back to the start cache
values when the delta omits them. Native Claude (no input in delta) and
OpenRouter-converted (input only in delta) paths are unchanged.

Refs #3580
2026-06-05 21:45:34 +08:00
Jason bda625a4f1 fix(opencode): use OpenAI-compatible SDK for APINebula preset
APINebula is an OpenAI-compatible relay (its base URL ends in /v1, matching
its Codex/OpenClaw/Hermes presets), but the OpenCode preset loaded the
@ai-sdk/openai package, which targets the OpenAI Responses API and fails
against chat-completions-only upstreams. Switch the npm field to
@ai-sdk/openai-compatible so requests use the OpenAI Chat Completions format.
2026-06-05 20:13:33 +08:00
Jason 473f21971d feat(usage): add official subscription quota template with unified tier rendering
Changes:
- Add official_subscription template type for Claude/Codex/Gemini
- Replace implicit 'category=official auto-query' with explicit opt-in template
- Default disabled; users enable via usage script modal with configurable interval
- Unify tier→label mapping across subscription and script paths via labeled_tier_parts()
- Fix tray rendering: week aliases (seven_day/opus/sonnet) now use highest utilization
- Add depth guard: official_subscription checks enabled flag in query_provider_usage_inner
- Add cache invalidation symmetry: invalidate_subscription() for disabled providers
- i18n: add templateOfficialSubscription + hint in zh/en/ja/zh-TW

Backend (Rust):
- provider.rs: add TEMPLATE_TYPE_OFFICIAL_SUBSCRIPTION branch, flatten SubscriptionQuota→UsageData
- tray.rs: extract labeled_tier_parts() shared by both summary functions, use max_by for multi-alias groups
- usage_cache.rs: add invalidate_subscription() method
- Test coverage: add week-alias highest-utilization tests for both paths

Frontend (TypeScript):
- UsageScriptModal: add official_subscription to templates, auto-detect for official providers
- ProviderCard: gate useUsageQuery with !isOfficialSubscriptionUsage, pass autoQueryInterval to footer
- SubscriptionQuotaFooter: accept autoQueryInterval prop, default 0 (disabled)
- constants.ts: add TEMPLATE_TYPES.OFFICIAL_SUBSCRIPTION

Fixes tier rendering regression where:
- Claude/Codex: seven_day was missed (only weekly_limit matched) → lost 7-day window in tray
- Gemini: gemini_pro/flash/flash_lite fell through to fallback → leaked machine names
- Multi-window (opus+sonnet): find() took first, not worst → underestimated utilization and emoji color

All tests pass (cargo test + cargo clippy clean).
2026-06-05 19:03:40 +08:00
Allen Xu 03a9296c1f fix: polish usage statistics ui (#3426)
* fix: improve usage statistics ui

* chore: remove unused token suffix translation

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-06-05 08:12:17 +08:00
阿南 8e7d167ace 修复任务栏图标 (#3457) 2026-06-04 23:32:32 +08:00
ZHLH dadefdee77 fix: disable auto-capitalize on Input component for macOS (#3626)
Add autoComplete, autoCorrect, autoCapitalize, and spellCheck attributes
to prevent macOS from auto-capitalizing the first letter in input fields.
2026-06-04 23:11:23 +08:00
Yongmao Luo ad030da3b1 fix(coding-plan): route Zhipu quota query to the user's configured base URL (#3702)
Fixes #3701.

`query_zhipu` was hard-coded to `https://api.z.ai`, so a user who
configured the mainland China preset (`Zhipu GLM` on
`open.bigmodel.cn`) could not retrieve usage once the international
endpoint became unreachable from their network (or vice versa).

The two endpoints share the same quota path (`/api/monitor/usage/quota/limit`)
and return JSON in the same shape, and — crucially — each user only
ever uses one of them: the quota host is the same host they're already
running coding on. So we can route by the configured `base_url` and
skip the cross-host fallback entirely.

What this PR changes
--------------------

A single helper that maps the user's `base_url` to the matching quota
host, and `query_zhipu` rebuilt to take `base_url` and pick the right
host:

    fn zhipu_quota_base(base_url: &str) -> &'static str {
        if base_url.contains("bigmodel.cn") {
            "https://open.bigmodel.cn"
        } else {
            "https://api.z.ai"
        }
    }

    async fn query_zhipu(base_url: &str, api_key: &str) -> SubscriptionQuota {
        let url = format!(
            "{}/api/monitor/usage/quota/limit",
            zhipu_quota_base(base_url),
        );
        // ... original 401/403 -> Expired / make_error / parse path, unchanged
    }

The dispatcher already distinguishes `ZhipuCn` from `ZhipuEn` via
`detect_provider()` and routes the call through
`query_zhipu(base_url, api_key)` in the same match arm.

Why no cross-host fallback
--------------------------

Farion's review pointed out that adding a fallback would be
over-engineered and actively harmful:

1. Reachability is determined by the preset the user chose. Their
   configured host is the host they are already using to run coding;
   if it were unreachable, the user could not have reached the
   "query usage" step at all.

2. The fallback path required distinguishing "both 401/403" (genuine
   bad key) from "one 401/403 + one network error" (regional block),
   which silently misclassified the second case as a generic query
   failure and hid the upstream "Session expired" UX for invalid
   keys.

3. It also cost the worst-case ~10s+10s≈20s serial timeout for users
   on a working primary.

With the URL-based routing in place, 401/403 returns to the original
`CredentialStatus::Expired` semantics — same UX as `query_kimi` and
`query_minimax`.

Files changed
-------------

- `src-tauri/src/services/coding_plan.rs` — 1 file, +35 / -20

Testing
-------

- 3 new `zhipu_quota_base_*` routing tests
- 15 existing `coding_plan` parser tests still pass
- `cargo fmt --check` clean
- `cargo clippy --lib --no-deps -- -D warnings` clean

Co-authored-by: Yongmao Luo <yongmao.luo@columbia.edu>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-04 23:10:45 +08:00
Yongmao Luo 8047f95416 fix(proxy): skip backup/restore when Live is already a proxy placeholder (#3689)
When previous stop_with_restore() failed to restore the user's original
Live (e.g. app crash mid-stop, settings.json unwritable, or any pre-existing
state where Live carries the proxy placeholders), the next
start_with_takeover would read the still-placeholder Live and overwrite the
good backup row with the proxy config itself. After that, every subsequent
stop would restore the proxy placeholder back to Live — making the proxy
toggle a no-op and leaving the client pinned at http://127.0.0.1:15721.

Fix: in both backup write paths (`backup_live_configs` and
`backup_live_config_strict`) detect that Live is already a proxy
placeholder and skip the save, preserving any existing good backup. In
`restore_live_config_for_app_with_fallback_inner`, detect the same
condition in the parsed backup and fall through to the existing
SSOT (current provider DB) path that was added in c3d810a.

Both sides share a new `live_has_proxy_placeholder_for_app` dispatch
helper so the placeholder check stays in lockstep with the existing
per-app detection functions.

Co-authored-by: Yongmao Luo <yongmao.luo@columbia.edu>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-04 22:54:56 +08:00
@nothingness0db nothingness0db 0527002cca feat(usage): add OpenCode session usage sync (#3215)
* feat(usage): add OpenCode session usage sync

Add OpenCode as a fourth app type in the usage statistics system.
Reads per-message token data from opencode's local SQLite database
(~/.local/share/opencode/opencode.db) and imports into proxy_request_logs.

- New session_usage_opencode.rs module following Codex/Gemini pattern
- Parses assistant message.data JSON for tokens, cost, model
- Adds "opencode" to AppType union and filter tabs
- Updates dedup filters to include opencode_session data_source
- Adds i18n keys for all 4 locales

* fix(usage): add opencode to UsageHero title themes

* fix: respect XDG_DATA_HOME and platform defaults for OpenCode DB path

- Support OPENCODE_DB env var override (absolute and relative paths)
- Use ~/Library/Application Support/opencode/ on macOS
- Use XDG_DATA_HOME/opencode/ when set
- Fall back to ~/.local/share/opencode/ on Linux
- Rename misleading test to test_parse_message_data_ignores_role

* fix(usage): use ~/.local/share/opencode on all platforms

OpenCode relies on xdg-basedir, which ignores macOS/Windows conventions,
so its DB always lives at ~/.local/share/opencode. The previous macOS
default pointed at ~/Library/Application Support/opencode, which does not
exist, making the sync a silent no-op for macOS users without
XDG_DATA_HOME set.

* fix(usage): include opencode -wal mtime in freshness check

OpenCode runs its SQLite DB in WAL mode; new commits land in the -wal
file and the main DB file's mtime only advances on checkpoint. Keying
the freshness gate solely on opencode.db could skip newly written
sessions until a checkpoint occurred. Take the max of the db and -wal
mtimes instead.

* style(usage): apply cargo fmt to opencode session sync

Fixes Backend Checks cargo fmt --check failure.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(usage): ignore empty OPENCODE_DB and XDG_DATA_HOME env vars

An empty OPENCODE_DB collapsed the path to the data dir (dropping the opencode.db filename); an empty XDG_DATA_HOME produced a relative "opencode" path. Treat empty strings as unset, per the XDG spec.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(usage): harden OpenCode session sync error handling and labeling

- Map '_opencode_session' provider_id to 'OpenCode (Session)' display name
- Return accurate inserted flag from insert_opencode_message (was always true)
- Do not advance file/session sync_state when a session errors, so failed
  inserts are retried next run instead of being permanently skipped
- Surface per-message insert failures into the sync result errors
- Add opencode_session data-source icon and i18n labels (zh/zh-TW/en/ja)
- Add provider-stats labeling test for opencode session rows

* fix(usage): only import finalized OpenCode messages

An in-progress assistant message holds partial tokens; OpenCode updates the same message_id with final values later. Since request_id is fixed and the insert uses INSERT OR IGNORE, a partial row could never be corrected. Skip messages without time.completed so each turn is imported once with final usage.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(usage): keep OpenCode incomplete sessions retryable

---------

Co-authored-by: Eira Hazel <kip3vx9ma@mozmail.com>
Co-authored-by: Eria hazel <git config --global user.email your@email.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-06-04 22:26:24 +08:00
Keith Yu 2a24da517f feat: 新增 S3 兼容云存储同步 (#1351)
* Add S3 Cloud Sync design document

Design for adding AWS S3 as a new Cloud Sync backend alongside WebDAV.
Hybrid approach: extract shared sync protocol, add independent S3 transport.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add S3 cloud sync implementation design (reqwest + Sig V4)

Updated design based on 2026-03-06 draft: switches from rust-s3 crate
to hand-rolled AWS Sig V4 on existing reqwest for broader S3-compatible
service support (AWS, MinIO, R2, Alibaba OSS, Tencent COS, Huawei OBS).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add S3 cloud sync implementation plan (11 tasks, TDD)

Detailed step-by-step plan covering: sync_protocol extraction, S3 Sig V4
transport, settings, sync/auto-sync modules, Tauri commands, frontend
presets/dynamic form, and i18n.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* deps: add hmac crate for S3 Sig V4 signing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: extract sync_protocol.rs from webdav_sync.rs for shared use

Move transport-agnostic sync protocol logic (constants, types, snapshot
building, manifest validation, artifact verification, snapshot application,
utilities) into a new shared sync_protocol module so both WebDAV and the
upcoming S3 transport can reuse it.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use transport-neutral error keys in sync_protocol

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add S3 transport layer with AWS Sig V4 signing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add S3SyncSettings to AppSettings

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add S3 sync module with upload/download/fetch

Implements the S3 sync protocol layer (s3_sync.rs) that combines the
shared sync_protocol with the S3 transport. Mirrors the WebDAV sync
module structure with independent sync mutex, connection check,
upload, download, fetch_remote_info, and sync status persistence.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add S3 auto sync worker with debounce

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add S3 sync Tauri commands and auto sync worker startup

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add S3 sync TypeScript types and API layer

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add S3 sync i18n translations (en/zh/ja)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add S3 sync presets and dynamic form to sync settings

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: preserve HTTP scheme for S3 custom endpoints (MinIO support)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* test: add live S3 integration tests (env-var driven, --ignored)

Run with: S3_TEST_AK=... S3_TEST_SK=... S3_TEST_BUCKET=... cargo test --lib services::s3::integration_tests -- --ignored

Verifies test_connection, put_object, get_object, head_object, and 404
handling against a real S3 bucket using the project's own Sig V4 signing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: remove internal design docs before PR

* fix: wire S3 auto-sync to DB hook & sync UI state on async load

- P1: Add s3_auto_sync::notify_db_changed call in SQLite update_hook
  so S3 auto-sync worker receives DB change signals (was only wired
  for WebDAV, leaving S3 worker idle)

- P2: Add useEffect to update syncType selector when s3Config loads
  asynchronously, preventing stale "webdav" default for S3 users

* fix: satisfy clippy for s3 sync

* fix: address s3 sync review feedback

---------

Co-authored-by: Keith (via OpenClaw) <keithyt06@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-06-04 22:18:51 +08:00
oasis ea95f39adf fix(codex): drop tool_choice when tools is empty in Responses→Chat conversion (#3640)
Strict OpenAI-compatible upstreams (vLLM, enterprise gateways) reject
requests that carry tool_choice or parallel_tool_calls without a
non-empty tools array, returning 503/400 with:
  "When using `tool_choice`, `tools` must be set."

The Responses→Chat Completions converter unconditionally forwarded
tool_choice and parallel_tool_calls even when tools ended up absent
or empty after conversion. This commit adds a guard that removes both
fields when the resulting tools array is missing or empty.

Added 9 regression tests covering:
- tool_choice dropped when tools absent
- tool_choice dropped when tools is empty array
- parallel_tool_calls dropped when tools absent
- tool_choice dropped when all tools filtered (e.g., missing name)
- tool_choice preserved when tools present (auto + function type)
- clean output when neither tool_choice nor tools present
- tool_choice 'none' dropped when no tools
- tool_search_output providing tools keeps tool_choice

Refs #3557

Co-authored-by: yueqi.guo <guo_yueqi@qq.com>
2026-06-04 15:20:04 +08:00
Jason f5acef32fd fix(proxy): clarify Codex 413 error as upstream limit, not local proxy
An upstream gateway (e.g. nginx client_max_body_size) rejecting an oversized request body with HTTP 413 was wrapped as "CC Switch local proxy failed ..." with the full nginx HTML page echoed as the cause. This misled users into thinking CC Switch imposed the limit, when the local DefaultBodyLimit is already 200MB and the real cap lives on the provider's server.

413 now gets a dedicated message that points at the upstream gateway, states it is the provider's server-side limit (not CC Switch), and gives actionable recovery steps (/compact, drop large logs/images, ask the provider to raise its limit). Structured fields (upstream_status, provider, model, endpoint) are preserved; other error paths are unchanged.

Refs #666
2026-06-04 11:40:16 +08:00
Jason 084857ce25 fix(claude-desktop): strip [1m] suffix before proxy route lookup
Claude Desktop appends a local [1m] marker to the model name when the
1M-context beta is active (e.g. claude-opus-4-8[1m]). The proxy route
matcher compared this raw name against clean route IDs, so every match
tier failed and the is_claude_safe_model_id guard also blocked the role
keyword fallback, surfacing as route_unknown (HTTP 400) when switching
to a 1M-capable model mid-conversation.

Strip the [1m] suffix inside map_proxy_request_model before lookup so
exact/alias/legacy/role matching all see the clean ID, while keeping the
original name in the route_unknown error for diagnostics. The upstream
request still carries the mapped real model; 1M capability is negotiated
via the anthropic-beta header, not the model-name suffix.

Fixes #3588
2026-06-04 11:40:16 +08:00
Jason 6692343d1e Add media fallback rectifier for text-only models
Replace unsupported Anthropic image blocks with an [Unsupported Image] marker when routed models are text-only or upstream rejects image input.

Add rectifier settings for media fallback and heuristic model detection, wire the controls into the settings UI, and cover the sanitizer and forwarder gates with regression tests.
2026-06-04 11:40:16 +08:00
Cherilyn Buren 33eafbad51 fix(copilot): 调高无限空白检测阈值 20 → 500 (#2647)
* fix(copilot): raise infinite-whitespace threshold from 20 to 500

The previous threshold of 20 falsely aborted legitimate tool calls whose
arguments contain indented code (write_file / edit_file with 4-8 levels
of indentation in Python / YAML / Rust / Markdown easily exceed 20
consecutive whitespace chars, especially when newlines are counted).

The real infinite-whitespace bug emits hundreds to thousands of
consecutive whitespace characters, so 500 keeps the safety net while
drastically reducing false positives.

Refs #2646

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: clarify whitespace threshold comment

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-06-04 11:29:25 +08:00
Cao Xin c2337d6857 fix(codex): preserve custom tool metadata in chat routing (#3644)
* fix(codex): preserve custom tool metadata in chat routing

* fix(codex): reduce custom tool metadata description overhead

* fix(codex): stabilize custom tool metadata descriptions

* refactor(codex): remove unreachable custom tool description fallback
2026-06-04 08:33:53 +08:00
lzcndm ce538265cb fix: improve error message display in proxy panel (#3656) 2026-06-03 23:03:12 +08:00
zhibisora e458e77e30 feat: add CherryIN preset provider for Claude Code and Codex (#3643)
* feat: add CherryIN preset provider for Claude Code and Codex

CherryIN (open.cherryin.net) is an API aggregator gateway. Add it as a quick-config preset for both Claude Code (Anthropic format) and Codex (OpenAI-compatible), placed next to AiHubMix, with the official brand icon. Endpoints and model IDs verified against CherryIN's live pricing API.

* feat: add CherryIN preset to Gemini, Claude Desktop, OpenCode, OpenClaw, Hermes

Extend CherryIN coverage to all remaining apps, each placed next to AiHubMix. Anthropic-native (open.cherryin.net) for Claude Desktop/OpenClaw/Hermes, @ai-sdk/anthropic (/v1) for OpenCode, Gemini-compatible endpoint for Gemini CLI. Model IDs verified against CherryIN's live pricing API.
2026-06-03 22:56:31 +08:00
makoMakoGo ae90b53454 fix(tests): isolate deeplink prompt import home (#3662) 2026-06-03 22:50:36 +08:00
makoMakoGo e891f5c876 [codex] fix Zhipu coding plan presets (#3524)
* fix(presets): update Zhipu coding plan endpoints

* fix(model-fetch): probe /models on versioned /vN base URLs

The model-list probe assumed any base URL not ending in /v1 needs /v1/models appended. For providers whose base URL already ends in a version segment like /v4 (Zhipu/Z.AI GLM Coding Plan at .../api/coding/paas/v4), this produced .../v4/v1/models which 404s, so the "Fetch models" button always failed.

Detect a trailing /v{N} version segment and probe {base}/models first, keeping /v1/models as a fallback candidate for non-/v1 versions. Fixes Codex/OpenCode/OpenClaw/Hermes GLM presets and any other vN-style endpoint, with no behavior change for /v1 or non-versioned URLs.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-06-03 15:53:57 +08:00
Sleepwf 73073454cd fix(i18n): align Chinese VS Code wording with English and Japanese (#3228) 2026-06-03 15:10:06 +08:00
step 7811383b59 fix(codex): use relative filename for model_catalog_json (#3614)
* fix(codex): use relative filename for model_catalog_json

Instead of writing an absolute path (which breaks on WSL/symlink setups),
write only the filename "cc-switch-model-catalog.json" to config.toml.
Codex CLI resolves relative paths from the config directory, and both
files always reside in the same directory (~/.codex/).

This eliminates the need for UNC-to-Linux path translation and makes
the config portable across Windows, WSL, and symlinked directories.

Also simplifies ownership checks in resolve_cc_switch_catalog_path()
and set_codex_model_catalog_json_field() by removing dead string-equality
comparisons that never matched on WSL.

Closes farion1231/cc-switch#3573
Related: farion1231/cc-switch#3569

* style(codex): fix rustfmt violations in model_catalog tests

Wrap a >100-col UNC-path line and remove a trailing blank line that broke 'cargo fmt --check' in Backend CI. Style-only, no logic change.

---------

Co-authored-by: steponeerror <huxaio0207@qq.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-06-03 14:52:57 +08:00
Eter c1dff06625 feat: 新增 ZenMux Token Plan 供应商,支持手动凭证与 USD 额度富展示 (#2709)
* feat(Token plan): 增加 ZenMux 支持

* chore: format code with prettier

* chore: format code with cargo fmt

---------

Co-authored-by: 明桓 <jihaodong.jhd@oceanbase.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-06-03 14:45:49 +08:00
LaoYueHanNi 43ae1e5f2c fix(coding-plan): 适配 MiniMax 余额查询新接口 + 默认定价 (#3518)
* fix(coding-plan): 适配 MiniMax 余额查询新接口 + 默认定价

## 余额查询修复

/v1/api/openplatform/coding_plan/remains 新接口不再返回
current_*_total_count / current_*_usage_count(恒为 0),
改为返回 current_*_remaining_percent(剩余百分比)。
旧代码会因守卫失败导致 tiers 为空,tray 不再显示用量。

- 切换数据源到 *_remaining_percent,反转为已用百分比
- 过滤 model_name == "general",跳过 video 等非编程模型
- 提取 parse_minimax_tiers 纯函数,便于无 mock 单元测试
- 复用 TIER_FIVE_HOUR / TIER_WEEKLY_LIMIT 常量
- 新增 6 个单元测试覆盖主路径与边界

## 默认定价新增
按 2026-06-01 上线的人民币价格 (CNY/7.0 汇率,口径与 M2.7 反推一致)
换算为 USD,在 seed_model_pricing 数组中追加 minimax-m3:
| model_id     | display_name | input | output | cache_read | cache_creation |
|--------------|--------------|-------|--------|------------|----------------|
| minimax-m3   | MiniMax M3   | 0.60  | 2.40   | 0.12       | 0              |
不取512K上下文定价(参照当前模型标准)

* fix(coding-plan): MiniMax 兼容无周限额套餐 (current_weekly_status=3)
2026-06-03 14:28:05 +08:00
Yeeyzy b4f262c7bd fix(codex): always include output_tokens_details.reasoning_tokens in … (#3514)
* fix(codex): always include output_tokens_details.reasoning_tokens in chat→responses transform

Codex CLI strictly requires reasoning_tokens in the response.completed
usage object. Custom providers using /chat/completions often omit
completion_tokens_details, causing repeated parse failures and retries.

* fix(codex): guard non-object completion_tokens_details before insertion

---------

Co-authored-by: yeeyzy <yeeyzy@yangzhiying05@gmail.com>
2026-06-03 14:10:28 +08:00
makoMakoGo 693c3872f0 docs: refresh user manual for current app support (#3411)
* docs(usage): document pricing model matching rules

* docs: refresh user manual for current app support

* docs: clarify Hermes configuration files

* docs: align feature docs with visible app support
2026-06-02 22:17:42 +08:00
215 changed files with 23042 additions and 5849 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ release/
*.tsbuildinfo
.npmrc
CLAUDE.md
# AGENTS.md
AGENTS.md
GEMINI.md
/.claude
/.codex
+116
View File
@@ -5,6 +5,122 @@ 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).
## [3.16.3] - 2026-06-14
Development since v3.16.2 focuses on getting usage accounting right end-to-end — billing route-takeover and format-conversion traffic by the real upstream model and pricing basis (schema v11), counting Claude Code Workflow sub-agent sessions, folding Claude Desktop into the Claude view, refreshing the model pricing seed, and reworking the usage dashboard with global provider/model filters, brand-icon toolbars, and far more resilient quota queries — while hardening the proxy (mislabeled SSE bodies, Codex image rectification, OAuth token and takeover-residue recovery, Hermes duplicate YAML keys), reworking provider configuration (a custom User-Agent override, a unified Codex advanced section, searchable preset selection, a Fable 5 tier, and refreshed Kimi/Unity2/Volcengine/MiniMax presets), and smoothing the update, About-panel, and provider-health experiences.
**Stats**: 59 commits | 130 files changed | +10,223 insertions | -4,232 deletions
### Added
- **Custom User-Agent Override**: Provider configs can now set a custom User-Agent that the proxy applies consistently across request forwarding, stream check, and model listing (`GET /v1/models`), so coding-plan upstreams that gate on UA no longer fail detection or return 403 while the proxy itself works. The Claude and Codex forms expose it in advanced settings with a curated presets dropdown (Claude Code / Kilo Code families that pass UA whitelists) and live non-blocking validation; stale custom UAs are dropped when switching to an official preset to avoid silently altering headers (#3671).
- **Unified Codex Session History**: Official Codex sessions can now share a single resume-history bucket with cc-switch third-party sessions via an opt-in toggle under Settings → Codex App Enhancements, so the resume picker no longer hides them from each other. When enabled, the live `config.toml` routes official runs through a shared `custom` model_provider that mirrors the built-in OpenAI provider (`auth.json` is untouched); the toggle is forward-only by default but the enable dialog offers a checkbox to migrate existing official sessions (with per-generation backups), and the disable dialog offers a precise ledger-based restore that only reverts sessions originally recorded as `openai` while leaving sessions created during the toggle untouched.
- **Dashboard-Wide Provider/Model Filters**: The provider and model filters move from inside the request-log table up to the top bar, applying globally to the hero summary, trend chart, request logs, and both stats tabs so you can scope the whole dashboard to a given source and model. Sources match by exact display name (so session placeholder rows like "Claude (Session)" are selectable) and models match by effective pricing model, with the model dropdown cascading from the selected source and both lists showing only options that have data in the current range.
- **Refreshed Model Pricing Seed**: Added pricing for 9 models including Claude Fable 5, Grok 4.3, Mistral Medium 3.5 / Small 4, and Qwen 3.7 Max/Plus, and corrected 28 existing prices against current official vendor list pricing (GLM, Grok, MiMo, Doubao, Kimi, MiniMax, Mistral, Qwen) so usage cost estimates are accurate. Each change updates the seed for fresh installs and adds a guarded repair for existing databases without clobbering user-edited rows.
- **Claude Fable 5 Model Tier**: Provider forms now expose `claude-fable-5` as a fourth model-mapping tier on both the Claude Code and Claude Desktop proxy paths, with a fable → opus → default fallback mirroring the official downgrade and the `fable-` prefix whitelisted for the Desktop 1.12603.1+ validator. A clarified four-language fallback hint warns that leaving a tier blank on third-party endpoints forwards the literal model name and 404s (#3980, #4026, #4049).
- **Unity2.ai Partner Provider**: Added Unity2.ai, an AI API relay partner, as a preset across all seven managed apps (Claude Code, Codex, Gemini, OpenCode, OpenClaw, Claude Desktop, Hermes), each carrying the referral signup link and partner promotion copy in all four locales. Codex uses the bare base URL (the gateway exposes `/responses` at root) while OpenCode / OpenClaw / Hermes use the `/v1` chat-completions endpoint with `gpt-5.5`.
- **Kimi K2.7 Code Model**: Added the `kimi-k2.7-code` model (in $0.95 / out $4.00 / cache-read $0.19 per 1M tokens, 256K context) and pointed all six official Moonshot Kimi presets (Claude Code, Codex, Claude Desktop, Hermes, OpenCode, OpenClaw) at it, renaming the OpenCode / OpenClaw presets to "Kimi K2.7 Code". The pricing seed applies on startup via the idempotent insert path, so existing users pick up the new pricing without a migration.
- **Codex "Kimi For Coding" Preset Restored**: Re-added the Codex "Kimi For Coding" preset (`openai_chat`, `kimi-for-coding`, 256K context) with thinking mode enabled by default; it was previously removed because the coding endpoint rejects Codex's default `codex-cli` User-Agent with 403. It now works via proxy takeover combined with the custom User-Agent override (set to a whitelisted UA such as `claude-cli/*`).
- **Pricing-Model Audit in Request Detail**: The request detail panel now shows the requested model and the pricing model when they differ from the response model, making route-takeover bills auditable directly from the usage UI.
- **Preset Provider Search & Sorting**: The provider preset selector gains a searchable, sorted list with an inline search box (toggled via a magnifier icon, dismissed on ESC or outside click). Buttons use a responsive grid with consistent sizing and default icons, and search matches only provider display/raw names so URL fragments and shared category labels no longer produce noisy matches (#3975, #4183).
- **Claude Mythos 5 Pricing**: Registered the `claude-mythos-5` model in the bundled model/pricing table (in $10 / out $50 per 1M tokens, cache read $1.00, cache write $12.50), so usage metering prices and displays it correctly (#4077).
- **Fable 5 Verified Banner**: The Settings About page now displays a Fable 5 Verified banner beside the app name and version, marking this as a special build, with the version badge centered under the app name.
### Changed
- **Claude Desktop Usage Folded Into Claude**: The dashboard no longer shows a standalone "Claude Desktop" bucket, which only ever displayed a partial number (Desktop chat usage never passes through the proxy and its Code-tab sessions write into the shared `~/.claude/projects` tree). Desktop proxy traffic is now folded into the `claude` view for display while still recorded under its own `app_type` for route-takeover billing audit, with the real value visible in the request detail panel.
- **Lightweight Provider Health Check**: The provider health check no longer sends a real streaming model request (which many third-party providers blocked with 401/403/WAF, causing false negatives); it now performs a lightweight HTTP reachability probe of the provider `base_url`, treating any HTTP response as reachable and counting only DNS/connect/TLS/timeout as failure. The connectivity button is hidden for official providers (which use OAuth with an empty base URL and no reliable reachability target), the real-request confirmation dialog and test model/prompt fields are removed, and the degraded-latency threshold is set to 6s with an 8s timeout. The reachability check never resets the circuit breaker, so failover detection stays driven solely by real proxy traffic.
- **Codex Advanced Options Section**: The Codex provider form now folds local routing, model mapping, reasoning overrides, and custom User-Agent into a single collapsible advanced section mirroring the Claude form (auto-expanding when a UA is set or local routing is on). Custom User-Agent is now also configurable for native Responses providers, where it was previously reachable only with `openai_chat` routing enabled.
- **Usage Toolbar Refresh and Layout**: The app filter now renders brand icons (via ProviderIcon, with a grid icon for "All") instead of text tabs that wrapped awkwardly in narrow windows, and the usage hero shows the selected app's brand icon with Codex recolored to a neutral gray matching OpenAI's monochrome branding. The click-to-cycle refresh button becomes a Select with a localized "off" label, and the top-bar controls are compacted and aligned into consistent width groups with truncated long date-range labels.
- **Faster About Panel Loading**: The Settings About panel now loads progressively: the app version badge appears the instant it resolves instead of waiting for tool probes, each tool card updates the moment its own version check finishes (probes run concurrently rather than sequentially), and results are cached for the app session with a 10-minute TTL so reopening the About tab reuses cached values and revalidates stale ones in the background instead of re-probing all six tools every time.
- **Volcengine Ark Coding Plan Promo**: Updated the Volcengine Ark preset across all six apps with the new Coding Plan invite link (replacing the old Agent Plan / activity links) and refreshed the partner promotion copy in all four locales (two-month 75% off plus invite code 6J6FV5N2), correcting the product name from Agent Plan to Coding Plan.
- **MiniMax Demoted to Regular Provider**: Removed the gold partner star badge and the API-key promotion banner for MiniMax by dropping the `isPartner` flag from all its presets; it stays as a regular `cn_official` provider keeping its icon and theme. The promotion copy is kept dormant so the partnership can be re-enabled with a single line.
- **LemonData Removed, SudoCode Demoted**: Removed the LemonData provider preset entirely from all apps along with its promotion copy, icons, and sponsor listings, and demoted SudoCode from a partner to a regular `third_party` provider by dropping its `isPartner` flag and promotion copy (it keeps its icon).
- **AtlasCloud Codex GLM 5.1 Context Window**: Declared the 200,000-token context window for the `zai-org/glm-5.1` model in the AtlasCloud Codex preset, matching the other GLM 5.1 preset entries.
### Fixed
- **Route-Takeover Traffic Billed by the Real Upstream Model**: When a request was routed to a different upstream (env model mapping, Claude Desktop routes, Copilot normalization, Codex chat override), the proxy used to attribute and price usage by whatever model the upstream echoed back, recording kimi/glm tokens as `claude-*` and overstating cost roughly 525×. The forwarder now captures the real outbound model, attributes usage by upstream-echo then outbound then client alias, persists the actual pricing basis on every row (schema v11), and keeps that basis through cost backfill and 30-day rollup pruning; Claude Desktop traffic is now logged under its own `app_type` so its pricing overrides apply.
- **Usage Metering on Format-Conversion Proxy Paths**: Audited and fixed token/cache accounting across the proxy's format-conversion paths (Chat, Responses, and Gemini converted to Anthropic). The proxy now records the actually returned model, injects `stream_options.include_usage` so OpenAI-compatible upstreams emit usage in streaming, excludes `cache_read` and `cache_creation` from input on Claude←OpenAI paths to stop double-billing cache tokens, subtracts cached Gemini prompt tokens, still records fully-cached requests, and skips synthetic all-zero usage that previously inflated request counts (#2774).
- **In-App Update No Longer Hangs on Restart**: Installing an update from within the app no longer freezes on the "restarting" screen, leaving the new version installed but requiring a manual force-quit. The download-install-restart chain now runs entirely in the backend (a new `install_update_and_restart` command) with platform-aware install ordering and single-instance-lock teardown before re-exec, instead of depending on the old WebView to keep running JS after the app bundle was already swapped; exit requests are also classified so restart requests fall through to Tauri's default flow rather than deadlocking on the window-state plugin mutex (#4069, #4074).
- **Codex Upgrade No Longer Breaks the Install**: Upgrading Codex from the Settings "About" tab no longer leaves it throwing "Missing optional dependency @openai/codex-…" errors. The upgrade chain previously ran `codex update` first, which on an npm install is a bare reinstall that reports success even when the per-platform binary fails to land; Codex is now removed from the self-update-first path and a runnable check triggers an uninstall+reinstall self-heal (scoped to npm-managed installs) that actually re-lands the missing platform binary.
- **Codex OAuth Auth Token Preserved on Proxy Takeover**: Enabling proxy takeover for a Codex provider no longer strips the `ANTHROPIC_AUTH_TOKEN` placeholder, which previously broke Claude Code's login on hot-switches, fresh installs, and configs already stripped by older releases. The placeholder is now injected unconditionally for managed (non-Copilot) Codex providers, including URL-only ones; GitHub Copilot behavior (API_KEY only) is unchanged (#3789, #3784).
- **Takeover-Residue Recovery Across Config-Dir Switches**: Restarting the app after changing the config directory while proxy takeover is active no longer leaves Claude/Codex/Gemini pointed at a dead local proxy. The old instance now restores the taken-over live files before restarting, the first-run import refuses to persist a takeover placeholder as a provider, and SSOT restore validates that the current provider's config is free of placeholders before writing it back (#4076).
- **Mislabeled SSE Bodies in Format-Transform Fallback**: Requests routed through Claude/Codex format conversion no longer fail with an opaque 422 "Failed to parse upstream response" when a MaaS gateway force-streams a `stream:false` request and returns an SSE body under a non-SSE Content-Type. The proxy now sniffs for SSE on parse failure, aggregates the chunks into a single JSON, and runs the existing converter so clients still get a valid non-stream response; remaining parse failures are enriched with content-type, encoding, and body-snippet diagnostics, and deflate decoding now tries zlib before raw (#2234).
- **Duplicate YAML Keys in Hermes Config**: Hermes config writes no longer accumulate duplicate top-level keys (e.g. `mcp_servers`) that caused "Failed to parse Hermes config as YAML: duplicate entry with key" errors. Section replacement now strips all stale occurrences from the remainder instead of degrading into appends, the dedup safety net handles both LF and CRLF line endings, and healing keeps the last (newest) occurrence to match Hermes's own last-wins PyYAML semantics (#3267, #3633, #2973, #2529, #3310, #3762).
- **Usage Query Resilience and Error Clarity**: Usage cards no longer flip to red on a single transient blip: queries now retry once and keep showing the last successful result for up to 10 minutes on network/timeout/5xx failures, while deterministic failures (auth, empty key, unknown provider, 4xx) surface immediately and clear the snapshot so a stale quota can't resurface after credentials change. Native balance/coding-plan/subscription timeouts were raised from 10s to 15s for slow cross-border endpoints, and coding-plan now returns explicit "API key is empty" / "Unknown coding plan provider" errors instead of a blank failure.
- **Usage Script Provider Credential Resolution**: Custom JS-script usage queries resolved `{{apiKey}}` / `{{baseUrl}}` by guessing env fields only, so providers that store credentials elsewhere (e.g. Codex's `auth.OPENAI_API_KEY` plus `config.toml` base_url) always got empty values and failed despite being fully configured. Script queries and the test/preview now reuse the same per-app credential resolver as the native balance path, with explicit non-empty script values still taking precedence (#1479).
- **Claude Code Workflow Sub-Agent Usage Counted**: Local (no-proxy) session-log usage accounting missed Claude Code Workflow sub-agent traffic, under-counting overall usage by roughly 4.1% (concentrated in workflow/subagent transcripts). The scanner now descends into the deeper `subagents/workflows/wf_*/` transcript directories, and the parser no longer drops billable assistant messages that lack a `stop_reason` but already incurred input/cache token cost; dedup is unchanged so no usage is double-counted.
- **Codex Image Rectifier for /responses Text-Only Upstreams**: Codex `/responses` requests carrying images and routed to text-only OpenAI-chat models (e.g. DeepSeek `deepseek-v4-flash`) no longer fail with HTTP 400 "unknown variant `image_url`". The media rectifier now also covers the Codex adapter, scanning the responses `input` for `input_image` blocks so it can proactively strip images for known text-only models and reactively retry with images replaced on upstream image-unsupported errors.
- **Zhipu Coding-Plan Quota Window Mislabeling**: The Zhipu coding-plan view no longer swaps the 5-hour and weekly quota buckets in the final hours of each weekly cycle. The two windows are now classified by the explicit `unit` field (3 = 5-hour, 6 = weekly) instead of by sorting reset-time ascending, which mislabeled them exactly when users check their weekly quota most; the old reset-time heuristic remains as a fallback (#3036).
- **Duplicate Provider Terminal Sessions on macOS**: Launching a provider terminal on macOS no longer opens an extra empty window alongside the command session; Terminal.app uses `launch` (not `activate`) on cold start and Ghostty uses an initial-command so a single session opens, with a fallback retained if the AppleScript path fails (#4156).
- **Claude Desktop Model-Mapping Placeholders**: The Claude Desktop model-mapping form previously showed mismatched example brands across the menu display name and request model columns (DeepSeek vs Kimi), implying a display name maps to an unrelated model. Both placeholders are now derived from each row's role so they stay brand-consistent, with the lightweight Haiku tier using a flash example.
- **Popovers Behind Fullscreen Panels**: Popovers and tooltips such as the provider preset search no longer render behind fullscreen panels and appear unresponsive on click; their z-index is raised above the fullscreen overlay while staying below modal dialogs.
- **ToggleRow Icon Shrinking**: Toggle row icons no longer shrink or distort when paired with long descriptions, keeping the icon at a fixed size next to multi-line text.
### Docs
- **Release Notes Contributor Mentions**: Restored contributor mentions in the v3.16.1 and v3.16.2 release notes across all three locales.
## [3.16.2] - 2026-06-07
Development since v3.16.1 focuses on broadening data portability and usage observability — S3-compatible cloud sync, OpenCode session usage import, and an opt-in official-subscription quota template — while hardening Codex Chat Completions routing (stream truncation, `tool_choice` / custom-tool / reasoning-token edge cases, file and audio attachments, and a Codex CLI models endpoint), strengthening proxy robustness (ephemeral ports, takeover/placeholder restore, system-message normalization, clearer upstream errors, and a text-only image fallback), fixing coding-plan quota lookups (Zhipu, MiniMax) and several Windows/macOS issues, adding the CherryIN and ZenMux providers, and refreshing the user manual.
**Stats**: 41 commits | 132 files changed | +11,116 insertions | -1,636 deletions
### Added
- **S3-Compatible Cloud Sync**: Cloud Sync now supports S3-compatible object storage as a second backend alongside WebDAV, using hand-rolled AWS Signature V4 signing for broad compatibility. The settings panel offers one-click presets for AWS S3, MinIO, Cloudflare R2, Alibaba Cloud OSS, Tencent Cloud COS, and Huawei OBS plus a custom endpoint, with connection testing, manual upload/download, and auto-sync on configuration changes (provider, endpoint, MCP, prompt, skill, settings, and proxy tables — not high-frequency data like usage logs); enabling S3 sync disables active WebDAV sync and vice versa (#1351).
- **OpenCode Session Usage Sync**: Added OpenCode as a usage-statistics source that imports per-message token, cost, and model data from OpenCode's local SQLite database, with a new "OpenCode" app filter tab and an "OpenCode Session" data-source label. The database path respects `OPENCODE_DB` and `XDG_DATA_HOME` (defaulting to `~/.local/share/opencode` on all platforms), only finalized messages are imported, and the freshness check accounts for the WAL file so newly written sessions are not skipped (#3215).
- **Official Subscription Quota Template**: Added an explicit, opt-in "official subscription" usage template for Claude, Codex, and Gemini official providers that queries plan quota via CLI/OAuth credentials, replacing the previous implicit auto-query. It is disabled by default and enabled from the usage-script modal with a configurable refresh interval.
- **Unsupported Image Fallback Rectifier**: Added a proxy rectifier that replaces Anthropic image blocks with an `[Unsupported Image]` marker when the routed model is text-only (declared, or detected via a built-in model-name heuristic) or when the upstream rejects image input, so conversations are not interrupted. A new Settings toggle controls the fallback, with a separate toggle for the heuristic detection.
- **ZenMux Token Plan Provider**: Added ZenMux as a Token Plan coding-plan provider that accepts a manually entered API key and base URL in the usage-script modal and renders its quota with USD-denominated used / limit values (#2709).
- **CherryIN Preset**: Added the CherryIN aggregator gateway as a quick-config preset across all seven supported apps — Anthropic-format endpoint for Claude Code / Claude Desktop / OpenClaw / Hermes, `@ai-sdk/anthropic` for OpenCode, the OpenAI-compatible endpoint for Codex, and the Gemini-compatible endpoint for Gemini CLI — with the official brand icon, placed next to AiHubMix (#3643).
- **CCSub Preset**: Added CCSub, a multi-model aggregator partner, as a quick-config preset across six apps — Claude Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes — with the official brand icon and the partner referral link prefilled as the API-key signup URL (`gpt-5.5` for the OpenAI-compatible Codex and OpenCode endpoints).
- **Codex CLI Models Endpoint**: The local proxy now answers `GET /v1/models`, which Codex CLI probes at startup, returning the cc-switch-managed Codex model catalog. A stale-catalog guard parses the live `config.toml` and only serves the catalog when `model_catalog_json` still references the cc-switch-owned file, so a leftover catalog from a previous provider is not advertised (#3818).
- **Codex Chat File and Audio Attachments**: The Codex Responses-to-Chat converter now maps `input_file` parts (carrying `file_id` or inline `file_data`) and `input_audio` parts into their Chat Completions equivalents, and emits top-level `input_*` items that were previously dropped, so file and audio attachments reach Chat-only Codex upstreams.
### Changed
- **Usage Dashboard Hero Redesign**: Restructured the Usage Dashboard hero and summary cards into a more compact layout, consolidating the real-token total, request count, and cost into a single top row (#3426).
- **SSSAiCode Endpoint Refresh**: Updated the SSSAiCode preset's website, signup, and API base URLs to the `sssaicodeapi.com` domain and refreshed its endpoint nodes (default `node-hk.sssaicodeapi.com`, plus `node-hk.sssaiapi.com` and `node-cf.sssaicodeapi.com`) across all seven app presets.
### Fixed
- **Codex Chat Truncated Stream Detection**: When a Chat Completions upstream ends a stream without a `finish_reason` or `[DONE]`, CC Switch no longer reports it as a normal completion — it finalizes normally only when the stream truly finished, emits an incomplete (`max_output_tokens`) response when partial output was produced, and emits a failed `stream_truncated` event when nothing was produced. Late-arriving reasoning is also attached to still-active streamed tool calls.
- **Codex Chat `tool_choice` Without Tools**: The Responses-to-Chat converter now drops `tool_choice` and `parallel_tool_calls` whenever the resulting tools array is absent or empty, so strict OpenAI-compatible upstreams (vLLM, enterprise gateways) no longer reject the request with "When using `tool_choice`, `tools` must be set." (#3640).
- **Codex Custom Tool Metadata Over Chat Routing**: Custom Codex tools (such as the freeform `apply_patch` tool) now preserve their full original definition — including format and grammar metadata — as a compact, order-stable JSON block in the generated Chat function description instead of a generic placeholder, keeping them usable on Chat Completions upstreams (#3644).
- **Codex Chat `reasoning_tokens` in Usage**: The Chat-to-Responses usage conversion now always includes `output_tokens_details.reasoning_tokens` (defaulting to 0), even when a provider omits `completion_tokens_details` or returns it as a non-object, satisfying the Codex CLI's strict requirement and avoiding repeated parse failures and retries (#3514).
- **Codex Cross-Turn Reasoning for Custom and Search Tools**: The cross-turn reasoning cache in Codex Chat history now covers the full tool-call set (`function_call`, `custom_tool_call`, `tool_search_call`) and their outputs, so `apply_patch` and tool-search calls keep their `reasoning_content` when restored via `previous_response_id`.
- **Ephemeral Proxy Port Resolution**: When the proxy listens on port 0 (OS-assigned), takeover now starts the proxy first to learn the real port and writes it into the Live configs and database, so client URLs no longer point at a broken `:0` address; the Claude Desktop gateway URL is rejected if no concrete port has been resolved.
- **Proxy Placeholder Backup/Restore Loop**: If a previous proxy stop left the proxy placeholders in Live, taking over again no longer overwrites a good backup with the proxy config, and restore no longer writes the placeholder back to Live — both paths detect the placeholder state and rebuild Live from the current provider, fixing cases where the proxy toggle became a no-op and clients stayed pinned to the local proxy (#3689).
- **Official Provider Block Under Proxy Takeover**: While Local Routing takeover is active, only providers explicitly categorized as official are blocked from switching, instead of also disabling custom providers whose endpoint lives in metadata or whose fields are unfilled. The disabled Enable button now shows a lighter hint tooltip in place of the red "Blocked" badge.
- **Localhost Listen Address Normalization**: Saving the proxy with a listen address of `localhost` now normalizes it to `127.0.0.1` before persisting, avoiding binding inconsistencies (#3016).
- **Anthropic System Message Normalization**: For Anthropic-format providers, system-role entries inside the `messages` array are collapsed and merged into the top-level `system` field (preserving order and any existing top-level system), preventing strict upstreams from rejecting non-leading system messages; OpenAI Chat routing is untouched (#3775).
- **Claude Desktop 1M-Context Model Routing**: Claude Desktop appends a `[1m]` marker to the model name when the 1M-context beta is active (e.g. `claude-opus-4-8[1m]`). The proxy now strips that suffix before route lookup so exact, alias, legacy, and role-keyword matching resolve correctly, fixing `route_unknown` (HTTP 400) failures when switching to a 1M-capable model mid-conversation.
- **Codex 413 Error Clarity**: When a Codex upstream gateway rejects an oversized request with HTTP 413, the proxy now returns a dedicated message identifying it as the provider's server-side body-size limit (not a CC Switch limit) with recovery steps (run `/compact`, drop large logs or inline images, or ask the provider to raise its limit), instead of echoing the raw upstream HTML page.
- **Proxy Panel Error Detail**: When toggling proxy takeover fails, the proxy panel toast now includes the underlying backend error detail instead of only a generic failure message (#3656).
- **Copilot Infinite-Whitespace Threshold**: Raised the streaming infinite-whitespace abort threshold from 20 to 500 consecutive whitespace characters, so legitimate tool calls with deeply indented code arguments are no longer falsely aborted while still catching the real Copilot infinite-whitespace bug (#2647).
- **Subscription Tier Tray Rendering**: Fixed tray and quota rendering for official subscription tiers via a unified tier-to-label mapping: Claude/Codex no longer drop the seven-day window, Gemini Pro/Flash/Flash-Lite tiers no longer leak raw machine names, and multi-window plans (e.g. Opus + Sonnet) now display the worst utilization instead of the first match.
- **Inflated Claude Stream Input Tokens**: Some Anthropic-compatible streaming providers (e.g. Qwen, MiniMax) report the full context as `input_tokens` in `message_start`, double-counting the cached portion and artificially lowering the displayed cache hit rate. The parser now prefers a smaller positive `input_tokens` from `message_delta` and adopts the paired cache counts from the same usage block; native Claude and OpenRouter-converted paths are unchanged.
- **Zhipu Quota Query Endpoint Routing**: The Zhipu coding-plan quota lookup was hard-coded to `api.z.ai`, so users on the mainland China preset (`open.bigmodel.cn`) could not retrieve usage when the international endpoint was unreachable. The quota request now routes to the host matching the user's configured base URL (#3702).
- **MiniMax Balance API and Pricing**: Adapted MiniMax coding-plan quota to its new balance API (which returns remaining-percent fields instead of usage counts that broke the old parser and left the tray blank), filtered out non-coding models (e.g. video), handled plans without a weekly limit, and seeded default pricing for MiniMax M3 (#3518).
- **GLM Coding Plan Endpoints and Model Fetch**: Corrected the ZhiPu / Z.AI GLM Coding Plan presets to the `/api/coding/paas/v4` endpoints across Codex, OpenCode, OpenClaw, and Hermes, and taught the model-list probe to query `{base}/models` for base URLs that already end in a `/v{N}` segment (keeping `/v1/models` as a fallback), so the Fetch Models button no longer 404s on versioned endpoints (#3524).
- **Codex Model Catalog Path Portability**: Codex now writes only the relative filename `cc-switch-model-catalog.json` to `config.toml` instead of an absolute path (Codex CLI resolves it from the config directory), fixing the model catalog breaking on WSL and symlinked setups where the absolute path could not be translated (#3614).
- **APINebula OpenCode SDK**: The APINebula OpenCode preset now loads `@ai-sdk/openai-compatible` instead of `@ai-sdk/openai`, so requests use the OpenAI Chat Completions format the relay expects rather than the Responses API.
- **Windows Tray Icon Residue on Exit**: Quitting CC Switch on Windows could leave a dead tray icon until hovered; the app now removes the tray icon before exiting so it disappears cleanly (#3797).
- **Windows Taskbar Icon**: Set an explicit Windows AppUserModelID at runtime and stamped the installer's desktop and start-menu shortcuts with the same ID and product icon, so CC Switch shows the correct icon and groups properly in the taskbar (#3457).
- **Windows Subdirectory Skill Updates**: Normalized backslash path separators to forward slashes when scanning installed skills on Windows, so skills nested in subdirectories (e.g. `skills/my-skill`) are matched by the update check instead of being silently skipped (#3430).
- **macOS Input Auto-Capitalization**: Disabled autocomplete, autocorrect, autocapitalize, and spellcheck on the shared text Input component so macOS no longer auto-capitalizes or auto-corrects the first letter typed into configuration fields (#3626).
- **Codex VS Code Session Previews**: Codex session previews for requests sent from VS Code could show selection or open-file content instead of the prompt when a markdown heading preceded the injected request. Both the backend title and frontend preview now match the last "## My request for Codex:" heading (the IDE injects the real request as the final section) (#3593).
- **VS Code Wording in Chinese UI**: Corrected the "Apply to Claude Code plugin" description in the Simplified and Traditional Chinese locales to write "VS Code" properly instead of "Vscode", aligning with the English and Japanese strings (#3228).
### Docs
- **User Manual Refresh**: Refreshed the README locales and the en / zh / ja user manuals to reflect all seven supported apps (adding Claude Desktop and Hermes), corrected the OpenCode config path to `~/.config/opencode/` (`opencode.json`), documented Hermes configuration files, updated the language docs to four languages, revised per-app MCP / Prompts / Skills availability, noted that export produces a timestamped SQL backup including usage logs, and documented the pricing model-ID matching rules (#3411).
- **Codex Official Auth Preservation Guide**: Added a trilingual (en / zh / ja) guide explaining how to keep Codex official remote control and plugins working while routing model traffic to third-party APIs, and linked it from the v3.16.1 release notes.
- **README Release-Note Links and Sponsor Markup**: Updated the Release Notes links in all README locales to point at v3.16.1 and fixed broken smart-quote characters in the README_ZH sponsor blocks so their HTML attributes render correctly (#3772).
## [3.16.1] - 2026-06-01
Development since v3.16.0 focuses on hardening Codex provider switching and Local Routing takeover: preserving official OAuth auth and model catalogs across normal switches, hot-switches, backup restore, and edit flows; restoring Codex Chat tool/plugin compatibility over Chat Completions upstreams; improving Codex proxy diagnostics and CLI discovery; and documenting DeepSeek routing.
+28 -23
View File
@@ -2,7 +2,7 @@
# CC Switch
### The All-in-One Manager for Claude Code, Codex, Gemini CLI, OpenCode, OpenClaw & Hermes Agent
### The All-in-One Manager for Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw & Hermes Agent
[![Version](https://img.shields.io/github/v/release/farion1231/cc-switch?color=blue&label=version)](https://github.com/farion1231/cc-switch/releases)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)](https://github.com/farion1231/cc-switch/releases)
@@ -63,7 +63,7 @@ Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this lin
<tr>
<td width="180"><a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
<td>Thanks to Dola seed for sponsoring this project! Dola Seed 2.0 is a fullmodal general large model independently developed by ByteDance for the global market. Built on a unified multimodal architecture, it supports joint understanding and generation of text, images, audio, and video. It natively enables agent collaboration, with strong reasoning, longtask execution, tool integration, and coding capabilities. It is widely applicable to smart cockpits, personal assistants, education, customer support, marketing, retail, and other scenarios. It excels in multimodal perception, endtoend complex task delivery, stable interaction, and data security, and is readily accessible and deployable via the ModelArk platform.Register via <a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">this link</a> to get 500,000 tokens of free inference quota per model.<a href="https://www.volcengine.com/activity/agentplan?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
<td>Thanks to Dola seed for sponsoring this project! Dola Seed 2.0 is a fullmodal general large model independently developed by ByteDance for the global market. Built on a unified multimodal architecture, it supports joint understanding and generation of text, images, audio, and video. It natively enables agent collaboration, with strong reasoning, longtask execution, tool integration, and coding capabilities. It is widely applicable to smart cockpits, personal assistants, education, customer support, marketing, retail, and other scenarios. It excels in multimodal perception, endtoend complex task delivery, stable interaction, and data security, and is readily accessible and deployable via the ModelArk platform.Register via <a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">this link</a> to get 500,000 tokens of free inference quota per model.<a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=6J6FV5N2&utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
</tr>
<tr>
@@ -106,11 +106,6 @@ Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this lin
<td>Thanks to Micu API for sponsoring this project! Micu API is a global LLM relay service provider dedicated to delivering the best cost-performance ratio with high stability. Backed by a registered enterprise for core assurance, eliminating any risk of service discontinuation, with fast official invoicing support! We champion "zero cost to try": top up from as low as ¥1 with no minimum, and get fee-free refunds anytime! Micu API offers an exclusive deal for CC Switch users: register via <a href="https://www.micuapi.ai/register?aff=aOYQ">this link</a> and enter promo code "ccswitch" when topping up to enjoy a <strong>10% discount</strong>!</td>
</tr>
<tr>
<td width="180"><a href="https://lemondata.cc/r/FFX1ZDUP"><img src="assets/partners/logos/lemondata.png" alt="LemonData" width="150"></a></td>
<td>Thanks to LemonData for sponsoring this project! LemonData is a high-performance AI API aggregation platform — one API key for 300+ models including GPT, Claude, Gemini, DeepSeek, and more. All models priced 3070% below official rates with auto-failover, smart routing, and unlimited concurrency. New users get $1 free credit instantly upon registration — sign up via <a href="https://lemondata.cc/r/FFX1ZDUP">this link</a>to claim your bonus and start building right away</strong>!</td>
</tr>
<tr>
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
<td>Thanks to CTok.ai for sponsoring this project! CTok.ai is dedicated to building a one-stop AI programming tool service platform. We offer professional Claude Code packages and technical community services, with support for Google Gemini and OpenAI Codex. Through carefully designed plans and a professional tech community, we provide developers with reliable service guarantees and continuous technical support, making AI-assisted programming a true productivity tool. Click <a href="https://ctok.ai">here</a> to register!</td>
@@ -146,19 +141,29 @@ Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this lin
<td>Atlas Cloud is a full-modal AI inference platform that gives developers a single AI API to access video generation, image generation, and LLM APIs. Instead of managing multiple vendor integrations, you connect once and get unified access to 300+ curated models across all modalities. Check out Atlas Cloud's new <a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch">coding plan</a> promotion for more budget-friendly API access!</td>
</tr>
<tr>
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
<td>Thanks to CCSub for sponsoring this project! CCSub is a stable, affordable AI API relay platform — your drop-in replacement for a Claude.ai subscription. One API key gives you access to Claude Opus 4.8, Sonnet, Haiku, GPT-5, Gemini, and DeepSeek at roughly 30% of direct API cost, with no VPN required from anywhere in the world. Compatible with Claude Code, Codex, Cursor, Cline, Continue, Windsurf, and all major AI coding tools. Register via <a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">this link</a> and get $5 free credit on sign-up.</td>
</tr>
<tr>
<td width="180"><a href="https://unity2.ai/register?source=ccs"><img src="assets/partners/logos/unity2.jpg" alt="Unity2.ai" width="150"></a></td>
<td>Thanks to Unity2.ai for sponsoring this project! Unity2.ai is a high-performance AI model API relay platform for individual developers, teams, and enterprises. Long trusted by leading companies in China, it serves over 30 billion tokens per day and supports high concurrency at the 5,000 RPM level. It offers balance-based billing, first top-up bonuses, bundle subscriptions, corporate invoicing, and dedicated support. Register via <a href="https://unity2.ai/register?source=ccs">this link</a> to get $2 in credits, plus another $10 for joining the official group — up to $12 in free credits!</td>
</tr>
</table>
</details>
## Why CC Switch?
Modern AI-powered coding relies on CLI tools like Claude Code, Codex, Gemini CLI, OpenCode, and OpenClaw — but each has its own configuration format. Switching API providers means manually editing JSON, TOML, or `.env` files, and there is no unified way to manage MCP and Skills across multiple tools.
Modern AI-powered coding relies on tools like Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw, and Hermes — but each has its own configuration format. Switching API providers means manually editing JSON, TOML, or `.env` files, and there is no unified way to manage MCP and Skills across multiple tools.
**CC Switch** gives you a single desktop app to manage all five CLI tools. Instead of editing config files by hand, you get a visual interface to import providers with one click, switch between them instantly, with 50+ built-in provider presets, unified MCP and Skills management, and system tray quick switching — all backed by a reliable SQLite database with atomic writes that protect your configs from corruption.
**CC Switch** gives you a single desktop app to manage all supported AI tools. Instead of editing config files by hand, you get a visual interface to import providers with one click, switch between them instantly, with 50+ built-in provider presets, unified MCP and Skills management, and system tray quick switching — all backed by a reliable SQLite database with atomic writes that protect your configs from corruption.
- **One App, Five CLI Tools** — Manage Claude Code, Codex, Gemini CLI, OpenCode, and OpenClaw from a single interface
- **One App, Seven Tools** — Manage Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw, and Hermes from a single interface
- **No More Manual Editing** — 50+ provider presets including AWS Bedrock, NVIDIA NIM, and community relays; just pick and switch
- **Unified MCP & Skills Management** — One panel to manage MCP servers and Skills across four apps with bidirectional sync
- **Unified MCP & Skills Management** — One panel to manage MCP servers and Skills across Claude, Codex, Gemini, OpenCode, and Hermes with bidirectional sync
- **System Tray Quick Switch** — Switch providers instantly from the tray menu, no need to open the full app
- **Cloud Sync** — Sync provider data across devices via Dropbox, OneDrive, iCloud, or WebDAV servers
- **Cross-Platform** — Native desktop app for Windows, macOS, and Linux, built with Tauri 2
@@ -172,12 +177,12 @@ Modern AI-powered coding relies on CLI tools like Claude Code, Codex, Gemini CLI
## Features
[Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.15.0-en.md)
[Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.16.1-en.md)
### Provider Management
- **5 CLI tools, 50+ presets** — Claude Code, Codex, Gemini CLI, OpenCode, OpenClaw; copy your key and import with one click
- **Universal providers** — One config syncs to multiple apps (OpenCode, OpenClaw)
- **7 supported tools, 50+ presets** — Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw, Hermes; copy your key and import with one click
- **Universal providers** — One config syncs to Claude Code, Codex, and Gemini CLI
- One-click switching, system tray quick access, drag-and-drop sorting, import/export
### Proxy & Failover
@@ -187,7 +192,7 @@ Modern AI-powered coding relies on CLI tools like Claude Code, Codex, Gemini CLI
### MCP, Prompts & Skills
- **Unified MCP panel** — Manage MCP servers across 4 apps with bidirectional sync and Deep Link import
- **Unified MCP panel** — Manage MCP servers across Claude, Codex, Gemini, OpenCode, and Hermes with bidirectional sync and Deep Link import
- **Prompts** — Markdown editor with cross-app sync (CLAUDE.md / AGENTS.md / GEMINI.md) and backfill protection
- **Skills** — One-click install from GitHub repos or ZIP files, custom repository management, with symlink and file copy support
@@ -197,21 +202,21 @@ Modern AI-powered coding relies on CLI tools like Claude Code, Codex, Gemini CLI
### Session Manager & Workspace
- Browse, search, and restore conversation history across all apps
- Browse, search, and restore conversation history across supported session sources
- **Workspace editor** (OpenClaw) — Edit agent files (AGENTS.md, SOUL.md, etc.) with Markdown preview
### System & Platform
- **Cloud sync** — Custom config directory (Dropbox, OneDrive, iCloud, NAS) and WebDAV server sync
- **Deep Link** (`ccswitch://`) — Import providers, MCP servers, prompts, and skills via URL
- Dark / Light / System theme, auto-launch, auto-updater, atomic writes, auto-backups, i18n (zh/en/ja)
- Dark / Light / System theme, auto-launch, auto-updater, atomic writes, auto-backups, i18n (zh/zh-TW/en/ja)
## FAQ
<details>
<summary><strong>Which AI CLI tools does CC Switch support?</strong></summary>
<summary><strong>Which AI tools does CC Switch support?</strong></summary>
CC Switch supports five tools: **Claude Code**, **Codex**, **Gemini CLI**, **OpenCode**, and **OpenClaw**. Each tool has dedicated provider presets and configuration management.
CC Switch supports seven tools: **Claude Code**, **Claude Desktop**, **Codex**, **Gemini CLI**, **OpenCode**, **OpenClaw**, and **Hermes**. Each tool has dedicated provider presets and configuration management.
</details>
@@ -280,8 +285,8 @@ For detailed guides on every feature, check out the **[User Manual](docs/user-ma
- **MCP**: Click the "MCP" button → Add servers via templates or custom config → Toggle per-app sync
- **Prompts**: Click "Prompts" → Create presets with Markdown editor → Activate to sync to live files
- **Skills**: Click "Skills" → Browse GitHub repos → One-click install to all apps
- **Sessions**: Click "Sessions" → Browse, search, and restore conversation history across all apps
- **Skills**: Click "Skills" → Browse GitHub repos → One-click install to supported apps
- **Sessions**: Click "Sessions" → Browse, search, and restore conversation history across supported session sources
> **Note**: On first launch, you can manually import existing CLI tool configs as the default provider.
@@ -372,7 +377,7 @@ Download the latest Linux build from the [Releases](../../releases) page:
- **ProviderService**: Provider CRUD, switching, backfill, sorting
- **McpService**: MCP server management, import/export, live file sync
- **ProxyService**: Local proxy mode with hot-switching and format conversion
- **SessionManager**: Conversation history browsing across all supported apps
- **SessionManager**: Conversation history browsing across supported session sources
- **ConfigService**: Config import/export, backup rotation
- **SpeedtestService**: API endpoint latency measurement
@@ -494,7 +499,7 @@ pnpm test:unit --coverage
│ ├── lib/
│ │ ├── api/ # Tauri API wrapper (type-safe)
│ │ └── query/ # TanStack Query config
│ ├── locales/ # Translations (zh/en/ja)
│ ├── locales/ # Translations (zh/zh-TW/en/ja)
│ ├── config/ # Presets (providers/mcp)
│ └── types/ # TypeScript definitions
├── src-tauri/ # Backend (Rust)
+27 -22
View File
@@ -2,7 +2,7 @@
# CC Switch
### Der All-in-One-Manager für Claude Code, Codex, Gemini CLI, OpenCode, OpenClaw & Hermes Agent
### Der All-in-One-Manager für Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw & Hermes Agent
[![Version](https://img.shields.io/github/v/release/farion1231/cc-switch?color=blue&label=version)](https://github.com/farion1231/cc-switch/releases)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)](https://github.com/farion1231/cc-switch/releases)
@@ -63,7 +63,7 @@ Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6
<tr>
<td width="180"><a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
<td>Danke an Dola seed für die Unterstützung dieses Projekts! Dola Seed 2.0 ist ein voll-modales Allzweck-Großmodell, das von ByteDance eigenständig für den globalen Markt entwickelt wurde. Aufbauend auf einer einheitlichen multimodalen Architektur unterstützt es das gemeinsame Verstehen und Generieren von Text, Bildern, Audio und Video. Es ermöglicht von Haus aus die Zusammenarbeit von Agenten und verfügt über starke Fähigkeiten in den Bereichen Schlussfolgern, Ausführung langer Aufgaben, Werkzeugintegration und Programmierung. Es ist breit einsetzbar — etwa für intelligente Cockpits, persönliche Assistenten, Bildung, Kundensupport, Marketing, Einzelhandel und weitere Szenarien. Es überzeugt bei multimodaler Wahrnehmung, der Ende-zu-Ende-Bewältigung komplexer Aufgaben, stabiler Interaktion und Datensicherheit und ist über die ModelArk-Plattform einfach zugänglich und bereitstellbar. Registrieren Sie sich über <a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">diesen Link</a> und erhalten Sie pro Modell ein kostenloses Inferenzkontingent von 500.000 Token.<a href="https://www.volcengine.com/activity/agentplan?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
<td>Danke an Dola seed für die Unterstützung dieses Projekts! Dola Seed 2.0 ist ein voll-modales Allzweck-Großmodell, das von ByteDance eigenständig für den globalen Markt entwickelt wurde. Aufbauend auf einer einheitlichen multimodalen Architektur unterstützt es das gemeinsame Verstehen und Generieren von Text, Bildern, Audio und Video. Es ermöglicht von Haus aus die Zusammenarbeit von Agenten und verfügt über starke Fähigkeiten in den Bereichen Schlussfolgern, Ausführung langer Aufgaben, Werkzeugintegration und Programmierung. Es ist breit einsetzbar — etwa für intelligente Cockpits, persönliche Assistenten, Bildung, Kundensupport, Marketing, Einzelhandel und weitere Szenarien. Es überzeugt bei multimodaler Wahrnehmung, der Ende-zu-Ende-Bewältigung komplexer Aufgaben, stabiler Interaktion und Datensicherheit und ist über die ModelArk-Plattform einfach zugänglich und bereitstellbar. Registrieren Sie sich über <a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">diesen Link</a> und erhalten Sie pro Modell ein kostenloses Inferenzkontingent von 500.000 Token.<a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=6J6FV5N2&utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
</tr>
<tr>
@@ -106,11 +106,6 @@ Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6
<td>Danke an Micu API für die Unterstützung dieses Projekts! Micu API ist ein globaler LLM-Relay-Anbieter, der sich der Bereitstellung des besten Preis-Leistungs-Verhältnisses bei hoher Stabilität widmet. Gestützt auf ein eingetragenes Unternehmen als Kernabsicherung wird jedes Risiko einer Diensteinstellung ausgeschlossen, mit schneller offizieller Rechnungsstellung! Wir stehen für „kostenloses Ausprobieren": Aufladungen sind schon ab ¥1 ohne Mindestbetrag möglich, und gebührenfreie Rückerstattungen sind jederzeit möglich! Micu API bietet ein exklusives Angebot für CC-Switch-Nutzer: Registrieren Sie sich über <a href="https://www.micuapi.ai/register?aff=aOYQ">diesen Link</a> und geben Sie beim Aufladen den Gutscheincode „ccswitch" ein, um <strong>10 % Rabatt</strong> zu erhalten!</td>
</tr>
<tr>
<td width="180"><a href="https://lemondata.cc/r/FFX1ZDUP"><img src="assets/partners/logos/lemondata.png" alt="LemonData" width="150"></a></td>
<td>Danke an LemonData für die Unterstützung dieses Projekts! LemonData ist eine leistungsstarke KI-API-Aggregationsplattform — ein API-Schlüssel für mehr als 300 Modelle, darunter GPT, Claude, Gemini, DeepSeek und weitere. Alle Modelle zu Preisen 3070 % unter den offiziellen Tarifen, mit automatischem Failover, intelligentem Routing und unbegrenzter Nebenläufigkeit. Neukunden erhalten bei der Registrierung sofort 1 $ Gratisguthaben — registrieren Sie sich über <a href="https://lemondata.cc/r/FFX1ZDUP">diesen Link</a>, um Ihren Bonus einzulösen und sofort mit dem Entwickeln zu beginnen</strong>!</td>
</tr>
<tr>
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
<td>Danke an CTok.ai für die Unterstützung dieses Projekts! CTok.ai widmet sich dem Aufbau einer Komplettlösung für KI-Programmierwerkzeuge. Wir bieten professionelle Claude-Code-Pakete und Dienste einer technischen Community, mit Unterstützung für Google Gemini und OpenAI Codex. Durch sorgfältig gestaltete Pläne und eine professionelle Tech-Community geben wir Entwicklern verlässliche Servicegarantien und kontinuierlichen technischen Support an die Hand und machen KI-gestützte Programmierung zu einem echten Produktivitätswerkzeug. Klicken Sie <a href="https://ctok.ai">hier</a>, um sich zu registrieren!</td>
@@ -146,19 +141,29 @@ Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6
<td>Atlas Cloud ist eine vollmodale KI-Inferenzplattform, die Entwicklern über eine einzige KI-API Zugriff auf Videogenerierung, Bildgenerierung und LLM-APIs bietet. Statt mehrere Anbieterintegrationen zu verwalten, verbinden Sie sich einmal und erhalten einheitlichen Zugriff auf mehr als 300 kuratierte Modelle über alle Modalitäten hinweg. Sehen Sie sich die neue <a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch">Coding-Plan</a>-Aktion von Atlas Cloud für kostengünstigeren API-Zugang an!</td>
</tr>
<tr>
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
<td>Danke an CCSub für die Unterstützung dieses Projekts! CCSub ist eine zuverlässige und kostengünstige AI-API-Relay-Plattform — Ihr direkter Ersatz für ein Claude.ai-Abonnement. Mit einem einzigen API-Schlüssel erhalten Sie Zugriff auf Claude Opus 4.8, Sonnet, Haiku, GPT-5, Gemini und DeepSeek zu etwa 30 % der Kosten der direkten API-Nutzung — ohne VPN, weltweit nutzbar. Kompatibel mit Claude Code, Codex, Cursor, Cline, Continue, Windsurf und allen gängigen AI-Coding-Tools. Registrieren Sie sich über <a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">diesen Link</a> und erhalten Sie $5 Startguthaben bei der Anmeldung.</td>
</tr>
<tr>
<td width="180"><a href="https://unity2.ai/register?source=ccs"><img src="assets/partners/logos/unity2.jpg" alt="Unity2.ai" width="150"></a></td>
<td>Danke an Unity2.ai für die Unterstützung dieses Projekts! Unity2.ai ist eine leistungsstarke AI-Modell-API-Relay-Plattform für Einzelentwickler, Teams und Unternehmen. Sie wird seit Langem von führenden Unternehmen in China genutzt, verarbeitet täglich über 30 Milliarden Tokens und unterstützt hohe Parallelität auf 5.000-RPM-Niveau. Geboten werden Guthaben-Abrechnung, Ersteinzahlungsbonus, Kombi-Abonnements, Firmenrechnungen und persönliche Betreuung. Registrieren Sie sich über <a href="https://unity2.ai/register?source=ccs">diesen Link</a> und erhalten Sie $2 Guthaben, plus weitere $10 für den Beitritt zur offiziellen Gruppe — bis zu $12 Gratis-Guthaben!</td>
</tr>
</table>
</details>
## Warum CC Switch?
Modernes KI-gestütztes Programmieren stützt sich auf CLI-Werkzeuge wie Claude Code, Codex, Gemini CLI, OpenCode und OpenClaw — doch jedes hat sein eigenes Konfigurationsformat. Der Wechsel des API-Anbieters bedeutet, JSON-, TOML- oder `.env`-Dateien von Hand zu bearbeiten, und es gibt keine einheitliche Möglichkeit, MCP und Skills über mehrere Werkzeuge hinweg zu verwalten.
Modernes KI-gestütztes Programmieren stützt sich auf Werkzeuge wie Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw und Hermes — doch jedes hat sein eigenes Konfigurationsformat. Der Wechsel des API-Anbieters bedeutet, JSON-, TOML- oder `.env`-Dateien von Hand zu bearbeiten, und es gibt keine einheitliche Möglichkeit, MCP und Skills über mehrere Werkzeuge hinweg zu verwalten.
**CC Switch** gibt Ihnen eine einzige Desktop-App, um alle fünf CLI-Werkzeuge zu verwalten. Statt Konfigurationsdateien von Hand zu bearbeiten, erhalten Sie eine visuelle Oberfläche, um Anbieter mit einem Klick zu importieren und sofort zwischen ihnen zu wechseln — mit 50+ integrierten Anbieter-Presets, einheitlicher MCP- und Skills-Verwaltung und schnellem Umschalten über das System-Tray. Das Ganze gestützt auf eine zuverlässige SQLite-Datenbank mit atomaren Schreibvorgängen, die Ihre Konfigurationen vor Beschädigung schützen.
**CC Switch** gibt Ihnen eine einzige Desktop-App, um alle unterstützten KI-Werkzeuge zu verwalten. Statt Konfigurationsdateien von Hand zu bearbeiten, erhalten Sie eine visuelle Oberfläche, um Anbieter mit einem Klick zu importieren und sofort zwischen ihnen zu wechseln — mit 50+ integrierten Anbieter-Presets, einheitlicher MCP- und Skills-Verwaltung und schnellem Umschalten über das System-Tray. Das Ganze gestützt auf eine zuverlässige SQLite-Datenbank mit atomaren Schreibvorgängen, die Ihre Konfigurationen vor Beschädigung schützen.
- **Eine App, fünf CLI-Werkzeuge** — Verwalten Sie Claude Code, Codex, Gemini CLI, OpenCode und OpenClaw über eine einzige Oberfläche
- **Eine App, sieben Werkzeuge** — Verwalten Sie Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw und Hermes über eine einzige Oberfläche
- **Kein manuelles Bearbeiten mehr** — 50+ Anbieter-Presets einschließlich AWS Bedrock, NVIDIA NIM und Community-Relays; einfach auswählen und umschalten
- **Einheitliche MCP- & Skills-Verwaltung** — Ein Panel zur Verwaltung von MCP-Servern und Skills über vier Apps hinweg mit bidirektionaler Synchronisierung
- **Einheitliche MCP- & Skills-Verwaltung** — Ein Panel zur Verwaltung von MCP-Servern und Skills für Claude, Codex, Gemini, OpenCode und Hermes mit bidirektionaler Synchronisierung
- **Schnellumschaltung über System-Tray** — Wechseln Sie Anbieter sofort über das Tray-Menü, ohne die vollständige App öffnen zu müssen
- **Cloud-Synchronisierung** — Synchronisieren Sie Anbieterdaten geräteübergreifend über Dropbox, OneDrive, iCloud oder WebDAV-Server
- **Plattformübergreifend** — Native Desktop-App für Windows, macOS und Linux, gebaut mit Tauri 2
@@ -172,12 +177,12 @@ Modernes KI-gestütztes Programmieren stützt sich auf CLI-Werkzeuge wie Claude
## Funktionen
[Vollständiges Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.15.0-en.md)
[Vollständiges Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.16.1-en.md)
### Anbieterverwaltung
- **5 CLI-Werkzeuge, 50+ Presets** — Claude Code, Codex, Gemini CLI, OpenCode, OpenClaw; Schlüssel kopieren und mit einem Klick importieren
- **Universelle Anbieter** — Eine Konfiguration synchronisiert sich mit mehreren Apps (OpenCode, OpenClaw)
- **7 unterstützte Werkzeuge, 50+ Presets** — Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw, Hermes; Schlüssel kopieren und mit einem Klick importieren
- **Universelle Anbieter** — Eine Konfiguration synchronisiert sich mit Claude Code, Codex und Gemini CLI
- Umschaltung mit einem Klick, Schnellzugriff über System-Tray, Sortierung per Drag-and-drop, Import/Export
### Proxy & Failover
@@ -187,7 +192,7 @@ Modernes KI-gestütztes Programmieren stützt sich auf CLI-Werkzeuge wie Claude
### MCP, Prompts & Skills
- **Einheitliches MCP-Panel** — Verwalten Sie MCP-Server über 4 Apps hinweg mit bidirektionaler Synchronisierung und Deep-Link-Import
- **Einheitliches MCP-Panel** — Verwalten Sie MCP-Server für Claude, Codex, Gemini, OpenCode und Hermes mit bidirektionaler Synchronisierung und Deep-Link-Import
- **Prompts** — Markdown-Editor mit App-übergreifender Synchronisierung (CLAUDE.md / AGENTS.md / GEMINI.md) und Backfill-Schutz
- **Skills** — Installation mit einem Klick aus GitHub-Repositorys oder ZIP-Dateien, Verwaltung eigener Repositorys, mit Unterstützung für Symlinks und Dateikopien
@@ -197,21 +202,21 @@ Modernes KI-gestütztes Programmieren stützt sich auf CLI-Werkzeuge wie Claude
### Session Manager & Workspace
- Durchsuchen, suchen und stellen Sie den Gesprächsverlauf über alle Apps hinweg wieder her
- Gesprächsverlauf aus unterstützten Sitzungsquellen durchsuchen, suchen und wiederherstellen
- **Workspace-Editor** (OpenClaw) — Bearbeiten Sie Agent-Dateien (AGENTS.md, SOUL.md usw.) mit Markdown-Vorschau
### System & Plattform
- **Cloud-Synchronisierung** — Eigenes Konfigurationsverzeichnis (Dropbox, OneDrive, iCloud, NAS) und WebDAV-Server-Synchronisierung
- **Deep Link** (`ccswitch://`) — Importieren Sie Anbieter, MCP-Server, Prompts und Skills per URL
- Dunkles / Helles / System-Theme, automatischer Start, automatischer Updater, atomare Schreibvorgänge, automatische Backups, i18n (zh/en/ja)
- Dunkles / Helles / System-Theme, automatischer Start, automatischer Updater, atomare Schreibvorgänge, automatische Backups, i18n (zh/zh-TW/en/ja)
## FAQ
<details>
<summary><strong>Welche KI-CLI-Werkzeuge unterstützt CC Switch?</strong></summary>
<summary><strong>Welche KI-Werkzeuge unterstützt CC Switch?</strong></summary>
CC Switch unterstützt fünf Werkzeuge: **Claude Code**, **Codex**, **Gemini CLI**, **OpenCode** und **OpenClaw**. Jedes Werkzeug verfügt über dedizierte Anbieter-Presets und Konfigurationsverwaltung.
CC Switch unterstützt sieben Werkzeuge: **Claude Code**, **Claude Desktop**, **Codex**, **Gemini CLI**, **OpenCode**, **OpenClaw** und **Hermes**. Jedes Werkzeug verfügt über dedizierte Anbieter-Presets und Konfigurationsverwaltung.
</details>
@@ -280,8 +285,8 @@ Ausführliche Anleitungen zu jeder Funktion finden Sie im **[Benutzerhandbuch](d
- **MCP**: Klicken Sie auf die Schaltfläche „MCP" → Server über Vorlagen oder eigene Konfiguration hinzufügen → Synchronisierung pro App umschalten
- **Prompts**: Klicken Sie auf „Prompts" → Presets mit dem Markdown-Editor erstellen → Aktivieren, um mit den Live-Dateien zu synchronisieren
- **Skills**: Klicken Sie auf „Skills" → GitHub-Repositorys durchsuchen → mit einem Klick in allen Apps installieren
- **Sessions**: Klicken Sie auf „Sessions" → Gesprächsverlauf über alle Apps hinweg durchsuchen, suchen und wiederherstellen
- **Skills**: Klicken Sie auf „Skills" → GitHub-Repositorys durchsuchen → mit einem Klick in unterstützte Apps installieren
- **Sessions**: Klicken Sie auf „Sessions" → Gesprächsverlauf aus unterstützten Sitzungsquellen durchsuchen, suchen und wiederherstellen
> **Hinweis**: Beim Erststart können Sie bestehende CLI-Werkzeug-Konfigurationen manuell als Standardanbieter importieren.
@@ -494,7 +499,7 @@ pnpm test:unit --coverage
│ ├── lib/
│ │ ├── api/ # Tauri-API-Wrapper (typsicher)
│ │ └── query/ # TanStack-Query-Konfiguration
│ ├── locales/ # Übersetzungen (zh/en/ja)
│ ├── locales/ # Übersetzungen (zh/zh-TW/en/ja)
│ ├── config/ # Presets (providers/mcp)
│ └── types/ # TypeScript-Definitionen
├── src-tauri/ # Backend (Rust)
+27 -21
View File
@@ -2,7 +2,7 @@
# CC Switch
### Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes Agent のオールインワン管理ツール
### Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes Agent のオールインワン管理ツール
[![Version](https://img.shields.io/github/v/release/farion1231/cc-switch?color=blue&label=version)](https://github.com/farion1231/cc-switch/releases)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)](https://github.com/farion1231/cc-switch/releases)
@@ -63,7 +63,7 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
<tr>
<td width="180"><a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
<td>Dola seed のご支援に感謝します!Dola Seed 2.0 は ByteDance がグローバル市場向けに独自開発したフルモーダル汎用大規模モデルです。統一されたマルチモーダルアーキテクチャを基盤に、テキスト・画像・音声・動画の統合的な理解と生成をサポートします。エージェント連携をネイティブに実現し、強力な推論、長時間タスクの実行、ツール統合、コーディング能力を備えています。スマートコックピット、パーソナルアシスタント、教育、カスタマーサポート、マーケティング、リテールなど幅広いシナリオに適用可能で、マルチモーダル認識、エンドツーエンドの複雑なタスク遂行、安定したインタラクション、データセキュリティに優れ、ModelArk プラットフォームを通じて手軽に利用・デプロイできます。<a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">このリンク</a>からご登録いただくと、モデルごとに 500,000 トークンの無料推論クォータを進呈します。</td>
<td>Dola seed のご支援に感謝します!Dola Seed 2.0 は ByteDance がグローバル市場向けに独自開発したフルモーダル汎用大規模モデルです。統一されたマルチモーダルアーキテクチャを基盤に、テキスト・画像・音声・動画の統合的な理解と生成をサポートします。エージェント連携をネイティブに実現し、強力な推論、長時間タスクの実行、ツール統合、コーディング能力を備えています。スマートコックピット、パーソナルアシスタント、教育、カスタマーサポート、マーケティング、リテールなど幅広いシナリオに適用可能で、マルチモーダル認識、エンドツーエンドの複雑なタスク遂行、安定したインタラクション、データセキュリティに優れ、ModelArk プラットフォームを通じて手軽に利用・デプロイできます。<a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">このリンク</a>からご登録いただくと、モデルごとに 500,000 トークンの無料推論クォータを進呈します。<a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=6J6FV5N2&utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
</tr>
<tr>
@@ -105,10 +105,6 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
<td width="180"><a href="https://www.micuapi.ai/register?aff=aOYQ"><img src="assets/partners/logos/mikubanner.svg" alt="Micu" width="150"></a></td>
<td>Micu API のご支援に感謝します!Micu API は、最高のコストパフォーマンスと高い安定性を追求するグローバル大規模言語モデル中継サービスプロバイダーです。法人企業がバックアップしており、サービス停止のリスクを排除、迅速な正規請求書発行に対応!「試行コストゼロ」をモットーに、最低 1 元からチャージ可能で手数料無料、いつでも返金可能!CC Switch ユーザー向けの限定特典:<a href="https://www.micuapi.ai/register?aff=aOYQ">こちらのリンク</a>から登録し、チャージ時にプロモコード「ccswitch」を入力すると <strong>10% 割引</strong> が適用されます!</td>
</tr>
<tr>
<td width="180"><a href="https://lemondata.cc/r/FFX1ZDUP"><img src="assets/partners/logos/lemondata.png" alt="LemonData" width="150"></a></td>
<td>LemonData のご支援に感謝します!LemonData は高性能 AI API アグリゲーションプラットフォームで、GPT、Claude、Gemini、DeepSeek など 300 以上のモデルに 1 つの API キーでアクセス可能。全モデルが公式価格の 30〜70% オフで自動フェイルオーバー、スマートルーティング、無制限同時接続に対応。新規ユーザーは登録だけで即座に $1 の無料クレジットを獲得 — <a href="https://lemondata.cc/r/FFX1ZDUP">こちらのリンク</a>から登録してボーナスを獲得し、すぐに開発を始めましょう!</td>
</tr>
<tr>
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
@@ -145,19 +141,29 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
<td>Atlas Cloud は、1 つの API で動画・画像生成や LLM(大規模言語モデル)を利用できる全モーダル対応の AI 推論プラットフォームです。複数のベンダーを個別に管理する手間を省き、一度の接続で 300 以上の厳選されたマルチモーダルモデルにアクセスできます。より低コストで API を利用できる、開発者向けの新しい<a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch">「コーディングプラン」</a>プロモーションをぜひチェックしてください!</td>
</tr>
<tr>
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
<td>CCSub のご支援に感謝します!CCSub は安定した低価格の AI API リレープラットフォームで、Claude Code 公式サブスクリプションの強力な代替です。1 つの API キーで Claude Opus 4.8、Sonnet 4.6、Haiku 4.5、GPT-5、Gemini、DeepSeek の全モデルを公式直接利用の約 1/3 のコストでご利用いただけます。VPN 不要で世界中から直接接続可能。Claude Code、Codex、Cursor、Cline、Continue、Windsurf など主要な AI コーディングツールすべてに対応しています。<a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">こちらのリンク</a>から登録すると $5 の無料クレジットがもらえます。</td>
</tr>
<tr>
<td width="180"><a href="https://unity2.ai/register?source=ccs"><img src="assets/partners/logos/unity2.jpg" alt="Unity2.ai" width="150"></a></td>
<td>Unity2.ai のご支援に感謝します!Unity2.ai は個人開発者・チーム・企業向けの高性能 AI モデル API リレープラットフォームです。中国の大手企業に長年利用されており、1 日 300 億トークン以上を処理し、5000 RPM クラスの高並列に対応しています。残高課金、初回チャージボーナス、組み合わせサブスクリプション、企業向け請求書発行、専任サポートを提供。<a href="https://unity2.ai/register?source=ccs">こちらのリンク</a>から登録すると $2 のクレジット、公式グループへの参加でさらに $10、最大 $12 の無料クレジットがもらえます!</td>
</tr>
</table>
</details>
## CC Switch を選ぶ理由
最新の AI コーディングは Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw などの CLI ツールに依存していますが、各ツールの設定形式はバラバラです。API プロバイダを切り替えるたびに JSON、TOML、`.env` ファイルを手動で編集する必要があり、複数ツール間で MCP や Skills を統一的に管理する手段もありません。
最新の AI コーディングは Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes などのツールに依存していますが、各ツールの設定形式はバラバラです。API プロバイダを切り替えるたびに JSON、TOML、`.env` ファイルを手動で編集する必要があり、複数ツール間で MCP や Skills を統一的に管理する手段もありません。
**CC Switch** は、5 つの CLI ツールを 1 つのデスクトップアプリで一元管理できます。設定ファイルを手作業で編集する代わりに、ワンクリックでプロバイダをインポートし、瞬時に切り替えられるビジュアルインターフェースを提供します。50 以上の組み込みプリセット、統一 MCP・Skills 管理、システムトレイからの即時切り替え機能を搭載。すべてはアトミック書き込みによる信頼性の高い SQLite データベースに支えられており、設定の破損を防ぎます。
**CC Switch** は、対応する AI ツールを 1 つのデスクトップアプリで一元管理できます。設定ファイルを手作業で編集する代わりに、ワンクリックでプロバイダをインポートし、瞬時に切り替えられるビジュアルインターフェースを提供します。50 以上の組み込みプリセット、統一 MCP・Skills 管理、システムトレイからの即時切り替え機能を搭載。すべてはアトミック書き込みによる信頼性の高い SQLite データベースに支えられており、設定の破損を防ぎます。
- **1 つのアプリで 5 つの CLI ツール** -- Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw を単一インターフェースで管理
- **1 つのアプリで 7 つのツール** -- Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes を単一インターフェースで管理
- **手動編集は不要** -- AWS Bedrock、NVIDIA NIM、コミュニティリレーなど 50 以上のプロバイダプリセットを内蔵。選んで切り替えるだけ
- **統一 MCP・Skills 管理** -- 1 つのパネルで 4 つのアプリの MCP サーバーと Skills を双方向同期で管理
- **統一 MCP・Skills 管理** -- 1 つのパネルで Claude、Codex、Gemini、OpenCode、Hermes の MCP サーバーと Skills を双方向同期で管理
- **システムトレイでクイック切り替え** -- トレイメニューから即座にプロバイダを切り替え。アプリを開く必要なし
- **クラウド同期** -- Dropbox、OneDrive、iCloud、または WebDAV サーバー経由でデバイス間のプロバイダデータを同期
- **クロスプラットフォーム** -- Tauri 2 で構築された Windows、macOS、Linux 対応のネイティブデスクトップアプリ
@@ -171,12 +177,12 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
## 特長
[完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-notes/v3.15.0-ja.md)
[完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-notes/v3.16.1-ja.md)
### プロバイダ管理
- **5 つの CLI ツール、50 以上のプリセット** -- Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw。キーをコピーしてワンクリックでインポート
- **ユニバーサルプロバイダ** -- 1 つの設定を複数アプリに同期(OpenCode、OpenClaw
- **7 つの対応ツール、50 以上のプリセット** -- Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes。キーをコピーしてワンクリックでインポート
- **ユニバーサルプロバイダ** -- 1 つの設定を Claude Code、Codex、Gemini CLI に同期
- ワンクリック切り替え、システムトレイクイックアクセス、ドラッグ&ドロップ並び替え、インポート/エクスポート
### プロキシ & フェイルオーバー
@@ -186,7 +192,7 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
### MCP、Prompts & Skills
- **統一 MCP パネル** -- 4 つのアプリの MCP サーバーを管理、双方向同期、Deep Link インポート対応
- **統一 MCP パネル** -- Claude、Codex、Gemini、OpenCode、Hermes の MCP サーバーを管理、双方向同期、Deep Link インポート対応
- **Prompts** -- Markdown エディタ、クロスアプリ同期(CLAUDE.md / AGENTS.md / GEMINI.md)、バックフィル保護
- **Skills** -- GitHub リポジトリまたは ZIP ファイルからワンクリックインストール、カスタムリポジトリ管理、シンボリックリンクとファイルコピーに対応
@@ -196,21 +202,21 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
### Session Manager & ワークスペース
- すべてのアプリの会話履歴を閲覧・検索・復元
- 対応するセッションソースの会話履歴を閲覧・検索・復元
- **ワークスペースエディタ**(OpenClaw)-- エージェントファイル(AGENTS.md、SOUL.md など)を Markdown プレビュー付きで編集
### システム & プラットフォーム
- **クラウド同期** -- カスタム設定ディレクトリ(Dropbox、OneDrive、iCloud、NAS)および WebDAV サーバー同期
- **Deep Link** (`ccswitch://`) -- URL 経由でプロバイダ、MCP サーバー、Prompts、Skills をワンクリックインポート
- ダーク / ライト / システムテーマ、自動起動、自動アップデーター、アトミック書き込み、自動バックアップ、多言語対応(/英/日)
- ダーク / ライト / システムテーマ、自動起動、自動アップデーター、アトミック書き込み、自動バックアップ、多言語対応(簡体中文/繁體中文/英/日)
## よくある質問
<details>
<summary><strong>CC Switch はどの AI CLI ツールに対応していますか?</strong></summary>
<summary><strong>CC Switch はどの AI ツールに対応していますか?</strong></summary>
CC Switch は **Claude Code**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw** の 5 つのツールに対応しています。各ツールに専用のプロバイダプリセットと設定管理が用意されています。
CC Switch は **Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw**、**Hermes**7 つのツールに対応しています。各ツールに専用のプロバイダプリセットと設定管理が用意されています。
</details>
@@ -279,8 +285,8 @@ CC Switch は「最小限の介入」という設計原則に従っています
- **MCP**: 「MCP」ボタンをクリック → テンプレートまたはカスタム設定でサーバーを追加 → アプリごとの同期をトグルで切り替え
- **Prompts**: 「Prompts」をクリック → Markdown エディタでプリセットを作成 → 有効化してライブファイルに同期
- **Skills**: 「Skills」をクリック → GitHub リポジトリを閲覧 → ワンクリックですべてのアプリにインストール
- **Sessions**: 「Sessions」をクリック → すべてのアプリの会話履歴を閲覧・検索・復元
- **Skills**: 「Skills」をクリック → GitHub リポジトリを閲覧 → 対応アプリへワンクリックでインストール
- **Sessions**: 「Sessions」をクリック → 対応するセッションソースの会話履歴を閲覧・検索・復元
> **補足**: 初回起動時に、既存の CLI ツール設定を手動でインポートしてデフォルトプロバイダとして使用できます。
@@ -493,7 +499,7 @@ pnpm test:unit --coverage
│ ├── lib/
│ │ ├── api/ # Tauri API ラッパー(型安全)
│ │ └── query/ # TanStack Query 設定
│ ├── locales/ # 翻訳 (zh/en/ja)
│ ├── locales/ # 翻訳 (zh/zh-TW/en/ja)
│ ├── config/ # プリセット (providers/mcp)
│ └── types/ # TypeScript 型定義
├── src-tauri/ # バックエンド (Rust)
+33 -27
View File
@@ -2,7 +2,7 @@
# CC Switch
### Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw 和 Hermes Agent 的全方位管理工具
### Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw 和 Hermes Agent 的全方位管理工具
[![Version](https://img.shields.io/github/v/release/farion1231/cc-switch?color=blue&label=version)](https://github.com/farion1231/cc-switch/releases)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)](https://github.com/farion1231/cc-switch/releases)
@@ -62,8 +62,8 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
</tr>
<tr>
<td width="180"><a href="https://www.volcengine.com/activity/agentplan?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/huoshan.png" alt="HuoShan" width="150"></a></td>
<td>感谢火山方舟Agent Plan 模型赞助了本项目!方舟Agent Plan 模型订阅套餐集成了包含Doubao-Seed、Doubao-Seedance、Doubao-Seedream等在内的字节跳动自研SOTA级模型,覆盖文本、代码、图像、视频等多模态任务。同时支持一站式接入DeepSeek V4、GLM 5.1等主流大模型。超全模态模型与 Harness 升级一步到位,深度支持 Agent 框架与 AI 编程工具。方舟 Agent Plan 为 CC Switch 的用户提供了专属福利:通过<a href="https://www.volcengine.com/activity/agentplan?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">此链接</a>订阅方舟AgentPlan,新客户首月40元起<a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">>>For developers outside Mainland China, please click here</a></td>
<td width="180"><a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=6J6FV5N2&utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/huoshan.png" alt="HuoShan" width="150"></a></td>
<td>感谢火山方舟 Agent Plan 模型赞助了本项目!方舟 Agent Plan 模型订阅套餐集成了包含 Doubao-Seed、Doubao-Seedance、Doubao-Seedream 等在内的字节跳动自研 SOTA 级模型,覆盖文本、代码、图像、视频等多模态任务。最新支持 MiniMax-M3、DeepSeek-V4 系列、GLM-5.1、Doubao-Seed-2.0 系列、Kimi-K2.6 等模型,工具不限。超全模态模型与 Harness 升级一步到位,深度支持 Agent 框架与 AI 编程工具。一次订阅,可以为不同任务切换合适的 AI 引擎。方舟 Coding Plan 为 CC Switch 的用户提供了专属福利:通过<a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=6J6FV5N2&utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">此链接</a>订阅方舟 Coding Plan,新客户首两个月享 2.5 折优惠,再用专属邀请码 6J6FV5N2 领取奖励叠加 9.5 折,低至 9.4 元/月!<a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">>>For developers outside Mainland China, please click here</a></td>
</tr>
<tr>
@@ -106,19 +106,15 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
<td width="180"><a href="https://www.micuapi.ai/register?aff=aOYQ"><img src="assets/partners/logos/mikubanner.svg" alt="Micu" width="150"></a></td>
<td>感谢 米醋API 赞助了本项目!米醋API 是一家致力于提供极致性价比与高稳定性的全球大模型中转服务商。米醋API 背后有实体企业做核心保障,杜绝跑路风险,支持极速正规开票!我们主打“试错零成本”:1 元起充低门槛,0 手续费随时退款!米醋API 为本软件的用户提供了特别优惠,使用<a href="https://www.micuapi.ai/register?aff=aOYQ">此链接</a>注册并在充值时填写"ccswitch"优惠码可享九折优惠!</td>
</tr>
<tr>
<td width="180"><a href="https://lemondata.cc/r/FFX1ZDUP"><img src="assets/partners/logos/lemondata.png" alt="LemonData" width="150"></a></td>
<td>感谢 LemonData 赞助了本项目!LemonData 是一个高性能 AI API 聚合平台——一个 API Key 即可访问 GPT、Claude、Gemini、DeepSeek 等 300+ 模型。所有模型定价为官方价格的 30%-70%,支持自动故障转移、智能路由和无限并发。新用户注册即获 $1 免费额度——通过<a href="https://lemondata.cc/r/FFX1ZDUP">此链接</a>注册即可领取奖励,立即开始开发</td>
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
<td>感谢 CTok.ai 赞助了本项目!CTok.ai 致力于打造一站式 AI 编程工具服务平台。我们提供 Claude Code 专业套餐及技术社群服务,同时支持 Google Gemini 和 OpenAI Codex。通过精心设计的套餐方案和专业的技术社群,为开发者提供稳定的服务保障和持续的技术支持,让 AI 辅助编程真正成为开发者的生产力工具。点击<a href="https://ctok.ai">这里</a>注册</td>
</tr>
<tr>
<td width=180><a href=https://ctok.ai”><img src=assets/partners/logos/ctok.png alt=”CTok” width=150></a></td>
<td>感谢 CTok.ai 赞助了本项目!CTok.ai 致力于打造一站式 AI 编程工具服务平台。我们提供 Claude Code 专业套餐及技术社群服务,同时支持 Google Gemini 和 OpenAI Codex。通过精心设计的套餐方案和专业的技术社群,为开发者提供稳定的服务保障和持续的技术支持,让 AI 辅助编程真正成为开发者的生产力工具。点击<a href=https://ctok.ai”>这里</a>注册!</td>
</tr>
<tr>
<td width=”180”><a href=”https://console.claudeapi.com/register?aff=pCLD”><img src=”assets/partners/logos/claudeapi.png” alt=”ClaudeAPI” width=”150”></a></td>
<td>本项目由 <a href=”https://console.claudeapi.com/register?aff=pCLD”>Claude API</a> 赞助。Claude API 直连,三分钟接入 Claude Code 与 Agent 应用 新用户可领取测试额度。基于 Anthropic 官方 Key + AWS Bedrock 官方渠道,非逆向、非降智,支持 Opus / Sonnet / Haiku 全系列模型,保留 Tool Use、1M 上下文等官方能力。适合 Claude Code 深度用户、Agent 工程师与企业技术团队,支持开票和团队对接。点击<a href=”https://console.claudeapi.com/register?aff=pCLD”>这里</a>注册!</td>
<td width="180"><a href="https://console.claudeapi.com/register?aff=pCLD"><img src="assets/partners/logos/claudeapi.png" alt="ClaudeAPI" width="150"></a></td>
<td>本项目由 <a href="https://console.claudeapi.com/register?aff=pCLD">Claude API</a> 赞助。Claude API 直连,三分钟接入 Claude Code 与 Agent 应用 新用户可领取测试额度。基于 Anthropic 官方 Key + AWS Bedrock 官方渠道,非逆向、非降智,支持 Opus / Sonnet / Haiku 全系列模型,保留 Tool Use、1M 上下文等官方能力。适合 Claude Code 深度用户、Agent 工程师与企业技术团队,支持开票和团队对接。点击<a href="https://console.claudeapi.com/register?aff=pCLD">这里</a>注册!</td>
</tr>
<tr>
@@ -146,19 +142,29 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
<td>Atlas Cloud 是一个全模态 AI 推理平台,通过单一 API 为开发者提供视频生成、图像生成及 LLM 接入。免去繁琐的多供应商对接,一次连接即可调用 300+ 款全模态精选模型。立即查看 Atlas Cloud 全新<a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch">“编程计划”</a>优惠,获取更具性价比的 API 接入!</td>
</tr>
<tr>
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
<td>感谢 CCSub 赞助本项目!CCSub 是稳定、实惠的 AI API 中转平台,是 Claude Code 官方订阅的超强平替。一个 API Key 即可调用 Claude Opus 4.8、Sonnet 4.6、Haiku 4.5、GPT-5、Gemini、DeepSeek 全系列模型,价格约为官方直连的 1/3,全球直连无需梯子。兼容 Claude Code、Codex、Cursor、Cline、Continue、Windsurf 等所有主流 AI 编程工具。通过<a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">此链接</a>注册即送 $5 体验额度!</td>
</tr>
<tr>
<td width="180"><a href="https://unity2.ai/register?source=ccs"><img src="assets/partners/logos/unity2.jpg" alt="Unity2.ai" width="150"></a></td>
<td>感谢 Unity2.ai 赞助了本项目!Unity2.ai 是面向个人开发者、团队和企业的高性能 AI 模型 API 中转平台,长期服务国内头部企业,日均承载超 300 亿 token 调用,支持 5000 RPM 级高并发。支持余额计费、首充赠额、组合订阅、企业开票和专属对接。通过<a href="https://unity2.ai/register?source=ccs">此链接</a>注册可领取 $2 余额,加入官方群再送 $10 余额,最高可领 $12 免费额度!</td>
</tr>
</table>
</details>
## 为什么选择 CC Switch
现代 AI 编程依赖于 Claude Code、Codex、Gemini CLI、OpenCodeOpenClaw 等 CLI 工具——但每个工具都有自己的配置格式。切换 API 供应商意味着手动编辑 JSON、TOML 或 `.env` 文件,而在多个工具之间缺乏一个统一管理 MCP, SKILLS 的方式。
现代 AI 编程依赖于 Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCodeOpenClaw 和 Hermes 等工具——但每个工具都有自己的配置格式。切换 API 供应商意味着手动编辑 JSON、TOML 或 `.env` 文件,而在多个工具之间缺乏一个统一管理 MCP, SKILLS 的方式。
**CC Switch** 为你提供一个桌面应用来管理所有五个 CLI 工具。无需手动编辑配置文件,你将获得一个可视化界面,一键将供应商导入应用,一键在不同的供应商之间进行切换,内置 50+ 供应商预设、统一的 MCP, SKILLS 管理以及系统托盘即时切换功能——所有操作都基于可靠的 SQLite 数据库和原子写入机制,保护你的配置不被损坏。
**CC Switch** 为你提供一个桌面应用来管理所有支持的 AI 工具。无需手动编辑配置文件,你将获得一个可视化界面,一键将供应商导入应用,一键在不同的供应商之间进行切换,内置 50+ 供应商预设、统一的 MCP, SKILLS 管理以及系统托盘即时切换功能——所有操作都基于可靠的 SQLite 数据库和原子写入机制,保护你的配置不被损坏。
- **一个应用,五个 CLI 工具** — 在单一界面中管理 Claude Code、Codex、Gemini CLI、OpenCodeOpenClaw
- **一个应用,七个工具** — 在单一界面中管理 Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCodeOpenClaw 和 Hermes
- **告别手动编辑** — 50+ 供应商预设,包括 AWS Bedrock、NVIDIA NIM 和社区中转服务;一键即可切换
- **统一 MCP, SKILLS 管理** — 一个面板管理四个应用的 MCP, SKILLS, 支持双向同步
- **统一 MCP, SKILLS 管理** — 一个面板管理 Claude、Codex、Gemini、OpenCode 和 Hermes 的 MCP, SKILLS, 支持双向同步
- **系统托盘快速切换** — 从托盘菜单即时切换供应商,无需打开完整应用
- **云同步** — 通过 Dropbox、OneDrive、iCloud 或 WebDAV 服务器在不同设备之间同步供应商数据
- **跨平台** — 基于 Tauri 2 构建的原生桌面应用,支持 Windows、macOS 和 Linux
@@ -172,12 +178,12 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
## 功能特性
[完整更新日志](CHANGELOG.md) | [发布说明](docs/release-notes/v3.15.0-zh.md)
[完整更新日志](CHANGELOG.md) | [发布说明](docs/release-notes/v3.16.1-zh.md)
### 供应商管理
- **5 CLI 工具,50+ 预设** — Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw;复制 key 即可一键导入
- **通用供应商** — 一份配置同步到多个应用(OpenCode、OpenClaw
- **7支持工具,50+ 预设** — Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes;复制 key 即可一键导入
- **通用供应商** — 一份配置同步到 Claude Code、Codex 和 Gemini CLI
- 一键切换、系统托盘快速访问、拖拽排序、导入导出
### 代理与故障转移
@@ -187,7 +193,7 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
### MCP、Prompts 与 Skills
- **统一 MCP 面板** — 管理 4 个应用的 MCP 服务器,双向同步,支持 Deep Link 导入
- **统一 MCP 面板** — 管理 Claude、Codex、Gemini、OpenCode 和 Hermes 的 MCP 服务器,双向同步,支持 Deep Link 导入
- **Prompts** — Markdown 编辑器,跨应用同步(CLAUDE.md / AGENTS.md / GEMINI.md),回填保护
- **Skills** — 从 GitHub 仓库或 ZIP 文件一键安装,自定义仓库管理,支持软连接和文件复制
@@ -197,21 +203,21 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
### 会话管理器与工作区
- 浏览、搜索和恢复全部应用对话历史
- 浏览、搜索和恢复支持的会话来源
- **工作区编辑器**OpenClaw)— 编辑 Agent 文件(AGENTS.md、SOUL.md 等),支持 Markdown 预览
### 系统与平台
- **云同步** — 自定义配置目录(Dropbox、OneDrive、iCloud、坚果云、NAS)及 WebDAV 服务器同步
- **Deep Link** (`ccswitch://`) — 通过 URL 一键导入供应商、MCP 服务器、提示词和技能
- 深色 / 浅色 / 跟随系统主题、开机自启、自动更新、原子写入、自动备份、国际化(中/英/日)
- 深色 / 浅色 / 跟随系统主题、开机自启、自动更新、原子写入、自动备份、国际化(简中/繁中/英/日)
## 常见问题
<details>
<summary><strong>CC Switch 支持哪些 AI CLI 工具?</strong></summary>
<summary><strong>CC Switch 支持哪些 AI 工具?</strong></summary>
CC Switch 支持个工具:**Claude Code**、**Codex**、**Gemini CLI**、**OpenCode****OpenClaw**。每个工具都有专属的供应商预设和配置管理。
CC Switch 支持个工具:**Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode****OpenClaw** 和 **Hermes**。每个工具都有专属的供应商预设和配置管理。
</details>
@@ -282,8 +288,8 @@ CC Switch macOS 版本已通过 Apple 代码签名和公证,可直接下载安
- **MCP**:点击"MCP"按钮 → 通过模板或自定义配置添加服务器 → 切换各应用同步开关
- **Prompts**:点击"Prompts" → 使用 Markdown 编辑器创建预设 → 激活后同步到 live 文件
- **Skills**:点击"Skills" → 浏览 GitHub 仓库 → 一键安装到全部应用
- **会话**:点击"Sessions" → 浏览搜索和恢复全部应用对话历史
- **Skills**:点击"Skills" → 浏览 GitHub 仓库 → 一键安装到支持的应用
- **会话**:点击"Sessions" → 浏览搜索和恢复支持的会话来源
> **注意**:首次启动可以手动导入现有 CLI 工具配置作为默认供应商。
@@ -496,7 +502,7 @@ pnpm test:unit --coverage
│ ├── lib/
│ │ ├── api/ # Tauri API 封装(类型安全)
│ │ └── query/ # TanStack Query 配置
│ ├── locales/ # 翻译 (zh/en/ja)
│ ├── locales/ # 翻译 (zh/zh-TW/en/ja)
│ ├── config/ # 预设 (providers/mcp)
│ └── types/ # TypeScript 类型定义
├── src-tauri/ # 后端 (Rust)
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

@@ -1,162 +0,0 @@
/**
* 统一供应商(Universal Provider)预设配置
*
* 统一供应商是跨应用共享的配置,修改后会自动同步到 Claude、Codex、Gemini 三个应用。
* 适用于 NewAPI 等支持多种协议的 API 网关。
*/
import type {
UniversalProvider,
UniversalProviderApps,
UniversalProviderModels,
} from "@/types";
/**
* 统一供应商预设接口
*/
export interface UniversalProviderPreset {
/** 预设名称 */
name: string;
/** 供应商类型标识 */
providerType: string;
/** 默认启用的应用 */
defaultApps: UniversalProviderApps;
/** 默认模型配置 */
defaultModels: UniversalProviderModels;
/** 网站链接 */
websiteUrl?: string;
/** 图标名称 */
icon?: string;
/** 图标颜色 */
iconColor?: string;
/** 描述 */
description?: string;
/** 是否为自定义模板(允许用户完全自定义) */
isCustomTemplate?: boolean;
}
/**
* NewAPI 默认模型配置
*/
const NEWAPI_DEFAULT_MODELS: UniversalProviderModels = {
claude: {
model: "claude-sonnet-4-20250514",
haikuModel: "claude-haiku-4-20250514",
sonnetModel: "claude-sonnet-4-20250514",
opusModel: "claude-sonnet-4-20250514",
},
codex: {
model: "gpt-4o",
reasoningEffort: "high",
},
gemini: {
model: "gemini-2.5-pro",
},
};
const N1N_DEFAULT_MODELS: UniversalProviderModels = {
claude: {
model: "claude-3-5-sonnet-20240620",
haikuModel: "claude-3-haiku-20240307",
sonnetModel: "claude-3-5-sonnet-20240620",
opusModel: "claude-3-opus-20240229",
},
codex: {
model: "gpt-4o",
reasoningEffort: "high",
},
gemini: {
model: "gemini-1.5-pro-latest",
},
};
/**
* 统一供应商预设列表
*/
export const universalProviderPresets: UniversalProviderPreset[] = [
{
name: "n1n.ai",
providerType: "n1n",
defaultApps: {
claude: true,
codex: true,
gemini: true,
},
defaultModels: N1N_DEFAULT_MODELS,
websiteUrl: "https://n1n.ai",
icon: "openai",
iconColor: "#000000",
description:
"n1n.ai - 聚合 OpenAI, Anthropic, Google 等主流大模型的一站式 AI 服务平台",
},
{
name: "NewAPI",
providerType: "newapi",
defaultApps: {
claude: true,
codex: true,
gemini: true,
},
defaultModels: NEWAPI_DEFAULT_MODELS,
websiteUrl: "https://www.newapi.pro",
icon: "newapi",
iconColor: "#00A67E",
description:
"NewAPI 是一个可自部署的 API 网关,支持 Anthropic、OpenAI、Gemini 等多种协议",
},
{
name: "自定义网关",
providerType: "custom_gateway",
defaultApps: {
claude: true,
codex: true,
gemini: true,
},
defaultModels: NEWAPI_DEFAULT_MODELS,
icon: "openai",
iconColor: "#6366F1",
description: "自定义配置的 API 网关",
isCustomTemplate: true,
},
];
/**
* 根据预设创建统一供应商
*/
export function createUniversalProviderFromPreset(
preset: UniversalProviderPreset,
id: string,
baseUrl: string,
apiKey: string,
customName?: string,
): UniversalProvider {
return {
id,
name: customName || preset.name,
providerType: preset.providerType,
apps: { ...preset.defaultApps },
baseUrl,
apiKey,
models: JSON.parse(JSON.stringify(preset.defaultModels)), // Deep copy
websiteUrl: preset.websiteUrl,
icon: preset.icon,
iconColor: preset.iconColor,
createdAt: Date.now(),
};
}
/**
* 获取预设的显示名称(用于 UI)
*/
export function getPresetDisplayName(preset: UniversalProviderPreset): string {
return preset.name;
}
/**
* 根据类型查找预设
*/
export function findPresetByType(
providerType: string,
): UniversalProviderPreset | undefined {
return universalProviderPresets.find((p) => p.providerType === providerType);
}
+10 -10
View File
@@ -105,7 +105,7 @@ Fixed multiple preserve-mode takeover paths that could clear or overwrite offici
Fixed cases where `modelCatalog` could be cleared during live backfill, active-provider editing, provider switching, and takeover shutdown restore. Snapshot backups preserve existing `model_catalog_json` pointers; backups rebuilt from providers regenerate catalog projections from the database source of truth; editing the active provider now prefers the database model catalog instead of trusting a live reverse-parse result that may have lost its projection.
Provider switching also now always refreshes the generated Codex model catalog JSON ([#3360](https://github.com/farion1231/cc-switch/pull/3360), thanks [@Postroggy](https://github.com/Postroggy)).
Provider switching also now always refreshes the generated Codex model catalog JSON ([#3360](https://github.com/farion1231/cc-switch/pull/3360), thanks @Postroggy).
### Codex Chat Tools, Plugins, and Custom Tools Restored
@@ -117,19 +117,19 @@ When Codex forwarding fails, CC Switch now returns JSON errors that include prov
### Codex Native Balance / Coding Plan Credential Lookup
Fixed native balance and Coding Plan queries using credentials from the wrong app. Each app now resolves its own provider credentials instead of carrying authentication assumptions from another app surface into the query flow ([#3355](https://github.com/farion1231/cc-switch/pull/3355), thanks [@SiskonEmilia](https://github.com/SiskonEmilia)).
Fixed native balance and Coding Plan queries using credentials from the wrong app. Each app now resolves its own provider credentials instead of carrying authentication assumptions from another app surface into the query flow ([#3355](https://github.com/farion1231/cc-switch/pull/3355), thanks @SiskonEmilia).
### Codex CLI Discovery and Model Catalog Template Fallback
Fixed a too-narrow Codex CLI discovery path for third-party Codex model catalog projection. The backend now searches common Codex CLI install locations across platforms, and falls back to a built-in GPT-5.5 model catalog template if no template can be found ([#3382](https://github.com/farion1231/cc-switch/pull/3382), thanks [@chofuhoyu](https://github.com/chofuhoyu)).
Fixed a too-narrow Codex CLI discovery path for third-party Codex model catalog projection. The backend now searches common Codex CLI install locations across platforms, and falls back to a built-in GPT-5.5 model catalog template if no template can be found ([#3382](https://github.com/farion1231/cc-switch/pull/3382), thanks @chofuhoyu).
### Claude Desktop Official Provider Add Failure
Fixed an error when adding the Claude Desktop Official provider ([#3405](https://github.com/farion1231/cc-switch/pull/3405), thanks [@Eunknight](https://github.com/Eunknight)).
Fixed an error when adding the Claude Desktop Official provider ([#3405](https://github.com/farion1231/cc-switch/pull/3405), thanks @Eunknight).
### Kimi / Moonshot Tool-Thinking History Normalization
Added Kimi / Moonshot to the Anthropic-compatible tool-thinking history normalizer. Later turns can now correctly replay reasoning and tool-call context, avoiding failures caused by history messages that do not match upstream requirements ([#3377](https://github.com/farion1231/cc-switch/pull/3377), thanks [@Neon-Wang](https://github.com/Neon-Wang)).
Added Kimi / Moonshot to the Anthropic-compatible tool-thinking history normalizer. Later turns can now correctly replay reasoning and tool-call context, avoiding failures caused by history messages that do not match upstream requirements ([#3377](https://github.com/farion1231/cc-switch/pull/3377), thanks @Neon-Wang).
### Windows Tool Version Detection
@@ -171,11 +171,11 @@ By enabling these features, users accept the related risks. CC Switch is not res
Thanks to the following contributors for fixes in v3.16.1:
- [#3360](https://github.com/farion1231/cc-switch/pull/3360): always update Codex model catalog JSON when switching providers, thanks [@Postroggy](https://github.com/Postroggy).
- [#3355](https://github.com/farion1231/cc-switch/pull/3355): resolve native balance / Coding Plan credentials per app, thanks [@SiskonEmilia](https://github.com/SiskonEmilia).
- [#3405](https://github.com/farion1231/cc-switch/pull/3405): fix Claude Desktop Official provider add failure, thanks [@Eunknight](https://github.com/Eunknight).
- [#3382](https://github.com/farion1231/cc-switch/pull/3382): Codex CLI multi-platform discovery and GPT-5.5 model template fallback, thanks [@chofuhoyu](https://github.com/chofuhoyu).
- [#3377](https://github.com/farion1231/cc-switch/pull/3377): Kimi / Moonshot tool-thinking history normalization, thanks [@Neon-Wang](https://github.com/Neon-Wang).
- [#3360](https://github.com/farion1231/cc-switch/pull/3360): always update Codex model catalog JSON when switching providers, thanks @Postroggy.
- [#3355](https://github.com/farion1231/cc-switch/pull/3355): resolve native balance / Coding Plan credentials per app, thanks @SiskonEmilia.
- [#3405](https://github.com/farion1231/cc-switch/pull/3405): fix Claude Desktop Official provider add failure, thanks @Eunknight.
- [#3382](https://github.com/farion1231/cc-switch/pull/3382): Codex CLI multi-platform discovery and GPT-5.5 model template fallback, thanks @chofuhoyu.
- [#3377](https://github.com/farion1231/cc-switch/pull/3377): Kimi / Moonshot tool-thinking history normalization, thanks @Neon-Wang.
Thanks also to everyone who reported Codex OAuth, model catalog, local routing takeover, and Chat Completions tool-call issues after v3.16.0. Many of these fixes came directly from real-world reproduction details.
+10 -10
View File
@@ -105,7 +105,7 @@ Codex がローカルルーティングのテイクオーバー状態にある
live バックフィル、現在のプロバイダー編集、プロバイダー切り替え、テイクオーバー解除時の復元などで `modelCatalog` が空になる問題を修正しました。スナップショットバックアップは既存の `model_catalog_json` ポインターを保持します。プロバイダーから再構築されるバックアップは、データベースの信頼できる情報源からカタログ投影を再生成します。現在のプロバイダー編集時は、投影を失っている可能性のある live の逆解析結果ではなく、データベース内のモデルカタログを優先します。
また、プロバイダー切り替え時には生成済みの Codex モデルカタログ JSON を常に更新するようになりました([#3360](https://github.com/farion1231/cc-switch/pull/3360)、[@Postroggy](https://github.com/Postroggy) に感謝)。
また、プロバイダー切り替え時には生成済みの Codex モデルカタログ JSON を常に更新するようになりました([#3360](https://github.com/farion1231/cc-switch/pull/3360)、@Postroggy に感謝)。
### Codex Chat ツール、プラグイン、カスタムツールの復元
@@ -117,19 +117,19 @@ Codex の転送に失敗したとき、provider、model、endpoint、上流 HTTP
### Codex ネイティブ残高 / Coding Plan の認証情報検索
ネイティブ残高と Coding Plan の照会時に、別アプリの認証情報を誤って使う問題を修正しました。各 app は自分自身のプロバイダー認証情報を解析し、別のアプリ面の認証前提を照会フローへ持ち込まなくなりました([#3355](https://github.com/farion1231/cc-switch/pull/3355)、[@SiskonEmilia](https://github.com/SiskonEmilia) に感謝)。
ネイティブ残高と Coding Plan の照会時に、別アプリの認証情報を誤って使う問題を修正しました。各 app は自分自身のプロバイダー認証情報を解析し、別のアプリ面の認証前提を照会フローへ持ち込まなくなりました([#3355](https://github.com/farion1231/cc-switch/pull/3355)、@SiskonEmilia に感謝)。
### Codex CLI 探索とモデルカタログテンプレートのフォールバック
サードパーティ Codex モデルカタログ投影における Codex CLI の探索パスが狭すぎる問題を修正しました。バックエンドは複数プラットフォームの一般的な Codex CLI インストール場所を探し、それでもテンプレートが見つからない場合は内蔵の GPT-5.5 モデルカタログテンプレートへフォールバックします([#3382](https://github.com/farion1231/cc-switch/pull/3382)、[@chofuhoyu](https://github.com/chofuhoyu) に感謝)。
サードパーティ Codex モデルカタログ投影における Codex CLI の探索パスが狭すぎる問題を修正しました。バックエンドは複数プラットフォームの一般的な Codex CLI インストール場所を探し、それでもテンプレートが見つからない場合は内蔵の GPT-5.5 モデルカタログテンプレートへフォールバックします([#3382](https://github.com/farion1231/cc-switch/pull/3382)、@chofuhoyu に感謝)。
### Claude Desktop Official プロバイダー追加失敗
Claude Desktop Official プロバイダー追加時のエラーを修正しました([#3405](https://github.com/farion1231/cc-switch/pull/3405)、[@Eunknight](https://github.com/Eunknight) に感謝)。
Claude Desktop Official プロバイダー追加時のエラーを修正しました([#3405](https://github.com/farion1231/cc-switch/pull/3405)、@Eunknight に感謝)。
### Kimi / Moonshot ツール思考履歴の正規化
Kimi / Moonshot を Anthropic 互換ツール思考履歴 normalizer に追加しました。後続ターンで reasoning と tool-call コンテキストを正しく再生できるようになり、履歴メッセージの形が上流要件に合わず失敗する問題を避けます([#3377](https://github.com/farion1231/cc-switch/pull/3377)、[@Neon-Wang](https://github.com/Neon-Wang) に感謝)。
Kimi / Moonshot を Anthropic 互換ツール思考履歴 normalizer に追加しました。後続ターンで reasoning と tool-call コンテキストを正しく再生できるようになり、履歴メッセージの形が上流要件に合わず失敗する問題を避けます([#3377](https://github.com/farion1231/cc-switch/pull/3377)、@Neon-Wang に感謝)。
### Windows ツールバージョン検出
@@ -171,11 +171,11 @@ Codex は起動時に `model_catalog_json` を読み込みます。v3.16.1 で
v3.16.1 で修正を届けてくださった以下のコントリビューターに感謝します:
- [#3360](https://github.com/farion1231/cc-switch/pull/3360): Codex プロバイダー切り替え時にモデルカタログ JSON を常に更新、[@Postroggy](https://github.com/Postroggy) に感謝。
- [#3355](https://github.com/farion1231/cc-switch/pull/3355): ネイティブ残高 / Coding Plan 照会の認証情報を app ごとに解析、[@SiskonEmilia](https://github.com/SiskonEmilia) に感謝。
- [#3405](https://github.com/farion1231/cc-switch/pull/3405): Claude Desktop Official プロバイダー追加エラーを修正、[@Eunknight](https://github.com/Eunknight) に感謝。
- [#3382](https://github.com/farion1231/cc-switch/pull/3382): Codex CLI の複数プラットフォーム探索と GPT-5.5 モデルテンプレートフォールバック、[@chofuhoyu](https://github.com/chofuhoyu) に感謝。
- [#3377](https://github.com/farion1231/cc-switch/pull/3377): Kimi / Moonshot ツール思考履歴の正規化、[@Neon-Wang](https://github.com/Neon-Wang) に感謝。
- [#3360](https://github.com/farion1231/cc-switch/pull/3360): Codex プロバイダー切り替え時にモデルカタログ JSON を常に更新、@Postroggy に感謝。
- [#3355](https://github.com/farion1231/cc-switch/pull/3355): ネイティブ残高 / Coding Plan 照会の認証情報を app ごとに解析、@SiskonEmilia に感謝。
- [#3405](https://github.com/farion1231/cc-switch/pull/3405): Claude Desktop Official プロバイダー追加エラーを修正、@Eunknight に感謝。
- [#3382](https://github.com/farion1231/cc-switch/pull/3382): Codex CLI の複数プラットフォーム探索と GPT-5.5 モデルテンプレートフォールバック、@chofuhoyu に感謝。
- [#3377](https://github.com/farion1231/cc-switch/pull/3377): Kimi / Moonshot ツール思考履歴の正規化、@Neon-Wang に感謝。
v3.16.0 リリース後に Codex OAuth、モデルカタログ、ローカルルーティングのテイクオーバー、Chat Completions ツール呼び出しの問題を報告してくださったすべてのユーザーにも感謝します。今回の多くの修正は、実際の利用シーンから得られた再現情報に基づいています。
+10 -10
View File
@@ -105,7 +105,7 @@ Codex / Claude / Gemini 的供应商切换与本地路由接管开关现在共
修复 `modelCatalog` 在 live 回填、当前供应商编辑弹窗、供应商切换、关闭接管恢复等场景被清空的问题。快照备份会保留已有 `model_catalog_json` 指针;由供应商重建的备份会从数据库真相来源重新生成目录投影;编辑当前供应商时会优先使用数据库里的模型目录,而不是信任可能已经丢失投影的 live 反解结果。
同时,供应商切换现在会始终刷新生成的 Codex 模型目录 JSON[#3360](https://github.com/farion1231/cc-switch/pull/3360),感谢 [@Postroggy](https://github.com/Postroggy))。
同时,供应商切换现在会始终刷新生成的 Codex 模型目录 JSON[#3360](https://github.com/farion1231/cc-switch/pull/3360),感谢 @Postroggy)。
### Codex Chat 工具、插件和自定义工具恢复
@@ -117,19 +117,19 @@ Codex 转发失败时,现在返回包含 provider、model、endpoint、上游
### Codex 原生余额 / Coding Plan 查询凭据
修复原生余额与 Coding Plan 查询时跨 app 错用凭据的问题。现在每个 app 会解析自己的供应商凭据,不再把其他应用面的认证假设带进查询流程([#3355](https://github.com/farion1231/cc-switch/pull/3355),感谢 [@SiskonEmilia](https://github.com/SiskonEmilia))。
修复原生余额与 Coding Plan 查询时跨 app 错用凭据的问题。现在每个 app 会解析自己的供应商凭据,不再把其他应用面的认证假设带进查询流程([#3355](https://github.com/farion1231/cc-switch/pull/3355),感谢 @SiskonEmilia)。
### Codex CLI 发现与模型目录模板兜底
修复第三方 Codex 模型目录投影对 Codex CLI 发现路径过窄的问题。现在后端会在多平台常见安装位置寻找 Codex CLI,并在仍找不到模板时使用内置 GPT-5.5 模型目录模板兜底([#3382](https://github.com/farion1231/cc-switch/pull/3382),感谢 [@chofuhoyu](https://github.com/chofuhoyu))。
修复第三方 Codex 模型目录投影对 Codex CLI 发现路径过窄的问题。现在后端会在多平台常见安装位置寻找 Codex CLI,并在仍找不到模板时使用内置 GPT-5.5 模型目录模板兜底([#3382](https://github.com/farion1231/cc-switch/pull/3382),感谢 @chofuhoyu)。
### Claude Desktop 官方供应商添加失败
修复添加 Claude Desktop 官方供应商时报错的问题([#3405](https://github.com/farion1231/cc-switch/pull/3405),感谢 [@Eunknight](https://github.com/Eunknight))。
修复添加 Claude Desktop 官方供应商时报错的问题([#3405](https://github.com/farion1231/cc-switch/pull/3405),感谢 @Eunknight)。
### Kimi / Moonshot 工具思考历史规范化
把 Kimi / Moonshot 加入 Anthropic 兼容工具思考历史 normalizer。后续轮次现在能正确重放 reasoning 与 tool-call 上下文,避免因为历史消息形态不符合上游要求而失败([#3377](https://github.com/farion1231/cc-switch/pull/3377),感谢 [@Neon-Wang](https://github.com/Neon-Wang))。
把 Kimi / Moonshot 加入 Anthropic 兼容工具思考历史 normalizer。后续轮次现在能正确重放 reasoning 与 tool-call 上下文,避免因为历史消息形态不符合上游要求而失败([#3377](https://github.com/farion1231/cc-switch/pull/3377),感谢 @Neon-Wang)。
### Windows 工具版本探测
@@ -171,11 +171,11 @@ Codex 在启动时读取 `model_catalog_json`。因此即使 v3.16.1 已修复
感谢以下贡献者在 v3.16.1 中提交修复:
- [#3360](https://github.com/farion1231/cc-switch/pull/3360):Codex 供应商切换时始终更新模型目录 JSON,感谢 [@Postroggy](https://github.com/Postroggy)
- [#3355](https://github.com/farion1231/cc-switch/pull/3355):原生余额 / Coding Plan 查询按 app 解析凭据,感谢 [@SiskonEmilia](https://github.com/SiskonEmilia)
- [#3405](https://github.com/farion1231/cc-switch/pull/3405):修复 Claude Desktop 官方供应商添加报错,感谢 [@Eunknight](https://github.com/Eunknight)
- [#3382](https://github.com/farion1231/cc-switch/pull/3382)Codex CLI 多平台发现与 GPT-5.5 模型模板兜底,感谢 [@chofuhoyu](https://github.com/chofuhoyu)
- [#3377](https://github.com/farion1231/cc-switch/pull/3377)Kimi / Moonshot 工具思考历史规范化,感谢 [@Neon-Wang](https://github.com/Neon-Wang)
- [#3360](https://github.com/farion1231/cc-switch/pull/3360):Codex 供应商切换时始终更新模型目录 JSON,感谢 @Postroggy
- [#3355](https://github.com/farion1231/cc-switch/pull/3355):原生余额 / Coding Plan 查询按 app 解析凭据,感谢 @SiskonEmilia
- [#3405](https://github.com/farion1231/cc-switch/pull/3405):修复 Claude Desktop 官方供应商添加报错,感谢 @Eunknight
- [#3382](https://github.com/farion1231/cc-switch/pull/3382)Codex CLI 多平台发现与 GPT-5.5 模型模板兜底,感谢 @chofuhoyu
- [#3377](https://github.com/farion1231/cc-switch/pull/3377)Kimi / Moonshot 工具思考历史规范化,感谢 @Neon-Wang。
也感谢所有在 v3.16.0 发布后反馈 Codex OAuth、模型目录、本地路由接管和 Chat Completions 工具调用问题的用户。很多补丁都来自这些真实使用场景里的复现线索。
+347
View File
@@ -0,0 +1,347 @@
# CC Switch v3.16.2
> Following the v3.16.1 Codex stability patch, this release mainly broadens data portability and usage observability — adding S3-compatible cloud sync, OpenCode session usage sync, and an official-subscription quota template — while continuing to harden Codex's Chat Completions routing for third-party providers, fixing a batch of Windows / macOS platform issues, adding the CherryIN and ZenMux providers, and fully refreshing the trilingual user manual.
**[中文版 →](v3.16.2-zh.md) | [日本語版 →](v3.16.2-ja.md)**
---
## Usage Guides
This release adds an S3 backend for cloud sync and more usage data sources. If you want to use them, start with these docs:
- **[Settings](../user-manual/en/1-getting-started/1.5-settings.md)**: configure cloud sync (WebDAV / S3-compatible storage) on the settings page to back up and restore providers, MCP, prompts, skills, and other config across multiple devices.
- **[Usage Statistics](../user-manual/en/4-proxy/4.4-usage.md)**: understand the Usage Dashboard's data sources (proxy logs, Codex / Gemini / OpenCode session sync) and how the statistics are counted.
---
> [!WARNING]
>
> ## Only Official Channels (Please Read)
>
> CC Switch is a **fully free and open-source** desktop app, and we **do not charge users any fees**. Please only obtain the software through the official channels listed below:
>
> | Channel | Only Official |
> | ------------------ | ------------------------------------------------------------------------------ |
> | Website | **[ccswitch.io](https://ccswitch.io)** |
> | Source | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
> | Downloads | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
> | Author | **[@farion1231](https://github.com/farion1231)** |
> | Report an Imposter | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
>
> **Any "CC Switch" website or client that asks you for payment, top-ups, or login credentials is fake.** If you have been tricked into paying, stop the transaction immediately and file a report through GitHub Issues.
---
## Overview
CC Switch v3.16.2 is a maintenance update following v3.16.1. After the previous release focused on the security of Codex official authentication and local routing takeover, this release concentrates on two things. First, broadening data portability and usage observability — adding S3-compatible cloud sync (a second cloud-backup backend alongside WebDAV), OpenCode session usage sync, and a quota-statistics template for official subscriptions. Second, continuing to polish the edges exposed when Codex routes third-party providers through Chat Completions — stream-truncation detection, `tool_choice` when tools is empty, custom-tool metadata, reasoning-token statistics, file / audio attachment conversion, and more.
This release also fixes a batch of local proxy robustness issues (ephemeral port resolution, the takeover placeholder restore loop, Anthropic `system` message normalization, the upstream 413 message, and Claude Desktop's `[1m]` model routing), addresses several Windows / macOS platform experience issues, adds the CherryIN and ZenMux providers, and fully refreshes the trilingual user manual.
**Release date**: 2026-06-07
**Stats**: 41 commits | 132 files changed | +11,116 / -1,636 lines
---
## Highlights
- **S3-compatible cloud sync**: adds S3-compatible object storage as a second cloud-backup backend alongside WebDAV, with one-click presets for AWS S3, MinIO, Cloudflare R2, Alibaba Cloud OSS, Tencent Cloud COS, Huawei OBS, and more.
- **More usage data sources**: added OpenCode session usage sync, plus an official-subscription quota template for Claude / Codex / Gemini official providers (explicit toggle, off by default).
- **Continued Codex Chat Completions routing hardening**: fixed stream-truncation misdetection, `tool_choice` rejection when tools is empty, custom-tool metadata loss, and missing reasoning-token stats, and added file / audio attachment conversion plus a `/v1/models` reachability endpoint.
- **A more robust local proxy**: fixed ephemeral port (port 0) resolution, the takeover placeholder restore loop, Anthropic `system` message normalization, the upstream 413 message, and Claude Desktop 1M-context model routing.
- **Platform and providers**: fixed Windows tray / taskbar icons, subdirectory skill updates, and macOS input auto-capitalization, and added the CherryIN and ZenMux providers.
---
## Added
### S3-Compatible Cloud Sync
Cloud Sync now supports S3-compatible object storage as a second backend alongside WebDAV, signing requests with a self-implemented AWS Signature V4 for the broadest possible compatibility. The settings page offers one-click presets for AWS S3, MinIO, Cloudflare R2, Alibaba Cloud OSS, Tencent Cloud COS, Huawei OBS, and a custom endpoint, with connection testing, manual upload / download, and auto-sync on configuration changes (the providers, endpoint, MCP, prompt, skill, settings, and proxy tables — **not** high-frequency data like usage logs). Enabling S3 sync disables a running WebDAV sync and vice versa (#1351).
### OpenCode Session Usage Sync
Added OpenCode as a usage-statistics source that reads per-message token, cost, and model data from OpenCode's local SQLite database and imports it into the usage records, with a dedicated "OpenCode" app filter tab and an "OpenCode Session" data-source label. The database path respects `OPENCODE_DB` and `XDG_DATA_HOME` (defaulting to `~/.local/share/opencode` on all platforms), only finalized messages are imported, and the freshness check includes the WAL file so just-written sessions are not skipped (#3215).
### Official Subscription Quota Template
Because some users were concerned that the IP issuing the usage query could differ from the IP issuing in-app requests, risking an account ban, the official-subscription usage template for Claude / Codex / Gemini official providers is now an explicit, opt-in template that queries plan quota via CLI / OAuth credentials, replacing the previous implicit auto-query for official providers. The template is off by default, is enabled from the usage-script modal, and supports a configurable refresh interval. When using this feature, enabling the proxy's TUN mode is recommended.
### Text-Only Model Image Fallback Rectifier
Added a proxy rectifier that replaces Anthropic image blocks with an `[Unsupported Image]` placeholder when the routed model is text-only (declared, or detected by a built-in model-name heuristic) or the upstream rejects image input, so conversations are not interrupted. The settings page provides a toggle for this fallback, plus a separate toggle for the heuristic detection (which can be turned off to avoid misjudging multimodal models).
### ZenMux Token Plan Provider
Added ZenMux as a Token Plan Coding Plan provider. You can manually enter its API key and base URL in the usage-script modal, and it renders used / quota in USD (#2709).
### CherryIN Preset
Added the CherryIN aggregator gateway as a quick-config preset across all 7 managed apps — Claude Code / Claude Desktop / OpenClaw / Hermes use the Anthropic-format endpoint (open.cherryin.net), OpenCode uses `@ai-sdk/anthropic` (`/v1`), Codex uses the OpenAI-compatible endpoint, and Gemini CLI uses the Gemini-compatible endpoint — with the official brand icon, placed next to AiHubMix (#3643).
### Codex CLI Reachability Endpoint `/v1/models`
The local proxy now responds to `GET /v1/models`, which Codex CLI probes at startup, returning the CC Switch-managed Codex model catalog. A stale-catalog guard was added: it parses the live `config.toml` and only serves the catalog when `model_catalog_json` still points at the CC Switch-owned catalog file, avoiding exposing a previous provider's leftover catalog to Codex (#3818).
### Codex Chat File and Audio Attachments
Codex's Responses→Chat conversion now maps `input_file` parts (carrying `file_id` or inline `file_data`) and `input_audio` parts into their Chat Completions equivalents, and emits top-level `input_*` items that were previously dropped, so file and audio attachments reach Chat-only Codex upstreams.
---
## Changed
### Usage Dashboard Hero Redesign
Rearranged the Usage Dashboard hero and summary cards into a more compact layout, consolidating the real-token total, request count, and cost into a single top row (#3426).
### SSSAiCode Endpoint Refresh
Updated the SSSAiCode preset's website, signup, and API base URLs to the `sssaicodeapi.com` domain, and refreshed its candidate endpoint nodes (default `node-hk.sssaicodeapi.com`, plus `node-hk.sssaiapi.com` and `node-cf.sssaicodeapi.com`) across all 7 app presets.
---
## Fixed
### Codex Chat Stream Truncation Detection
When a Chat Completions upstream ends a stream without a `finish_reason` or `[DONE]`, CC Switch no longer treats it as a normal completion: it finalizes normally only when the stream truly ended; emits an incomplete (`max_output_tokens`) response when partial output was produced; and emits a failed `stream_truncated` event when nothing was produced. Late-arriving reasoning is also backfilled onto still-active streaming tool calls.
### Codex Chat `tool_choice` Without Tools
The Responses→Chat conversion now drops `tool_choice` and `parallel_tool_calls` when the final tools array is missing or empty (including when all tools are filtered out), avoiding 503/400 errors from strict OpenAI-compatible upstreams (vLLM, enterprise gateways) with "When using `tool_choice`, `tools` must be set." (#3640).
### Codex Custom Tool Metadata Preserved
Custom Codex tools (such as the freeform `apply_patch` tool) now embed their full original definition — including format and grammar metadata — as a compact, order-stable JSON block in the generated Chat function description, instead of being replaced with a generic placeholder, so they remain usable on Chat Completions upstreams (#3644).
### Codex Chat Usage Missing `reasoning_tokens`
The Chat→Responses usage conversion now always includes `output_tokens_details.reasoning_tokens` (defaulting to 0), even when a provider omits `completion_tokens_details` or returns a non-object, satisfying Codex CLI's strict requirement and avoiding repeated response-parse failures and retries (#3514).
### Cross-Turn Reasoning for Codex Custom / Search Tools
The cross-turn reasoning cache in Codex Chat history now covers the full tool-call set (`function_call`, `custom_tool_call`, `tool_search_call`) and their outputs, not just plain function calls, so `apply_patch` and tool-search calls keep their own `reasoning_content` when restored via `previous_response_id`.
### Ephemeral Port (port 0) Resolution
When the proxy is configured to listen on port 0 (OS-assigned), takeover now starts the proxy first to obtain the real port before writing live configs and the database, avoiding client URLs pointing at an invalid `:0` address; if no concrete port has been resolved yet, the Claude Desktop gateway URL is rejected outright.
### Proxy Placeholder Backup / Restore Loop
If a previous proxy stop failed to restore the original live config and left proxy placeholders in live, taking over again no longer overwrites the good backup with the proxy config, and restore no longer writes the placeholder back to live: both paths detect the placeholder state and rebuild live from the current provider as the source of truth, fixing cases where the proxy toggle became a no-op and the client was pinned to the local proxy address (#3689).
### Provider Switching Wrongly Blocked During Proxy Takeover
During local routing takeover, only providers explicitly classified as official are now blocked from switching, instead of also disabling custom providers whose endpoint lives in meta or whose fields are simply unfilled. The disabled "Enable" button now shows a lighter hint tooltip instead of the previous red "Blocked" badge.
### localhost Listen Address Normalization
When saving the proxy with a listen address of `localhost`, it is now normalized to `127.0.0.1` before persisting, avoiding binding inconsistencies (#3016).
### Anthropic `system` Message Normalization
For Anthropic-format providers, system-role entries inside the `messages` array are now collapsed and merged into the top-level `system` field (preserving original order and any existing top-level system), avoiding strict upstreams rejecting non-leading system messages; OpenAI Chat routing is unaffected (#3775).
### Claude Desktop 1M-Context Model Routing
Claude Desktop appends a `[1m]` marker to the model name when the 1M-context beta is active (e.g. `claude-opus-4-8[1m]`). The proxy now strips that suffix before route matching so exact, alias, legacy, and role-keyword matching all resolve correctly, fixing `route_unknown` (HTTP 400) failures when switching to a 1M model mid-conversation; the original model name is still kept in the `route_unknown` error for diagnostics.
### Codex 413 Error Message
When a Codex upstream gateway rejects an oversized request body with HTTP 413, the proxy now returns a dedicated message explaining that this is the provider's server-side body-size limit (not a CC Switch local limit), with actionable recovery steps (run `/compact`, remove large logs or inline images, or ask the provider to raise the limit), instead of echoing the upstream's raw HTML error page.
### Proxy Panel Error Detail
When toggling proxy takeover fails, the proxy panel toast now includes the specific error detail returned by the backend, instead of only a generic failure message (#3656).
### Copilot Infinite-Whitespace Threshold
Raised the streaming infinite-whitespace abort threshold from 20 to 500 consecutive whitespace characters, avoiding false aborts of legitimate tool calls whose arguments contain deeply indented code (Python, YAML, Rust, Markdown), while still catching the real Copilot infinite-whitespace bug (#2647).
### Subscription Tier Tray Rendering
Via a unified tier-to-label mapping, fixed rendering of official subscription tiers in the tray and quota display: Claude / Codex no longer drop the 7-day window, Gemini Pro / Flash / Flash-Lite tiers no longer leak raw machine names, and multi-window plans (e.g. Opus + Sonnet) now show the worst utilization instead of the first match.
### Inflated Claude Stream input_tokens
Some Anthropic-compatible streaming providers (e.g. Qwen, MiniMax) report the full context as `input_tokens` in `message_start`, double-counting the cached portion already reported separately and artificially lowering the displayed cache hit rate. The parser now prefers the smaller positive `input_tokens` from `message_delta` and adopts the paired cache counts from the same usage block; native Claude and OpenRouter-converted paths are unchanged.
### Zhipu Quota Query Endpoint Routing
The Zhipu Coding Plan quota query was hard-coded to `api.z.ai`, so users on the mainland preset (`open.bigmodel.cn`) could not retrieve usage when the international endpoint was unreachable. The quota request now routes to the host matching the user's configured base URL (#3702).
### MiniMax Balance API and Pricing
Adapted MiniMax Coding Plan quota to its new balance API (which returns remaining-percent fields instead of the usage counts the old parser relied on, which left tiers empty and the tray showing no usage), filtered out non-coding models (such as video), handled plans without a weekly limit, and added default pricing for the MiniMax M3 model (#3518).
### GLM Coding Plan Endpoints and Model Fetch
Fixed the Zhipu / Z.AI GLM Coding Plan presets to the `/api/coding/paas/v4` endpoints (covering Codex, OpenCode, OpenClaw, Hermes), and made the model-list probe query `{base}/models` first for base URLs that already end in a `/v{N}` version segment (keeping `/v1/models` as a fallback), so the "Fetch models" button no longer 404s on versioned endpoints (#3524).
### Codex Model Catalog Path Portability
Codex now writes only the relative filename `cc-switch-model-catalog.json` to `config.toml` instead of an absolute path (Codex CLI resolves it from the config directory), fixing the model catalog breaking on WSL and symlinked setups where the absolute path could not be translated (#3614).
### APINebula's OpenCode SDK
The APINebula OpenCode preset now loads `@ai-sdk/openai-compatible` instead of `@ai-sdk/openai`, so requests use the OpenAI Chat Completions format the relay expects, rather than the Responses API that fails against chat-completions-only upstreams.
### Windows Tray Icon Residue After Exit
On Windows, quitting CC Switch could leave a dead tray icon behind until the mouse passed over it. The app now explicitly removes the tray icon before exiting, so it disappears cleanly when the process ends (#3797).
### Windows Taskbar Icon
Sets an explicit Windows AppUserModelID at runtime and writes the same ID and product icon onto the installer's desktop and start-menu shortcuts, so CC Switch shows the correct icon and groups properly in the taskbar (#3457).
### Windows Update Check for Subdirectory Skills
When scanning installed skills on Windows, backslash path separators are now normalized to forward slashes, so skills nested in subdirectories (e.g. `skills/my-skill`) are matched by the update check instead of being silently skipped (#3430).
### macOS Input Auto-Capitalization
Disabled autocomplete, autocorrect, autocapitalize, and spellcheck on the shared text Input component, so macOS no longer auto-capitalizes or auto-corrects the first letter typed into configuration fields (#3626).
### Codex VS Code Session Previews
For Codex requests sent from VS Code, the session preview could show selection or open-file content instead of the real prompt when a markdown heading preceded the injected request. The backend title and frontend preview now both match the last "## My request for Codex:" heading (the IDE injects the real request as the final section), so the preview reflects the user's prompt (#3593).
### VS Code Wording in the Chinese UI
Corrected the "Apply to Claude Code plugin" description in Simplified and Traditional Chinese to write "VS Code" properly instead of "Vscode", aligning with the English and Japanese strings (#3228).
---
## Documentation
### User Manual Refresh
Refreshed the README localizations and the en / zh / ja user manuals to reflect all 7 managed apps (adding Claude Desktop and Hermes to the intro and overview copy), corrected the OpenCode config path to `~/.config/opencode/` (`opencode.json`), documented Hermes config files, updated the language docs to four languages, corrected per-app MCP / prompt / skill support, noted that export now produces a timestamped SQL backup that includes usage logs, and documented the pricing model-ID matching rules (#3411).
### Codex Official Auth Preservation Guide
Added a Chinese / English / Japanese guide explaining how to keep Codex official remote control and official plugins working while routing model traffic to third-party APIs, and linked it from the v3.16.1 release notes.
### README Links and Sponsor Markup
Updated the Release Notes links in each language README to v3.16.1, and fixed broken curly-quote characters in the README_ZH sponsor blocks so their HTML attributes render correctly (#3772).
---
## Upgrade Notes
### S3 and WebDAV Cloud Sync Are Mutually Exclusive
Cloud Sync runs only one backend at a time. Enabling S3 auto-sync disables a running WebDAV auto-sync and vice versa. If you previously used WebDAV, make sure both ends are aligned before switching to S3, so you don't assume the old backend is still backing up.
### Restart Codex After Editing Model Mappings
Codex reads `model_catalog_json` at startup. Even though this release rewrites the model catalog to a relative path and adds the `/v1/models` reachability endpoint, you still need to restart Codex after editing the model mapping table for the `/model` menu to refresh.
---
## Risk Notice
This release continues the risk notices from previous versions for reverse-proxy-style features.
**Codex OAuth reverse proxy**: using a ChatGPT subscription's Codex OAuth through a reverse proxy may violate OpenAI's terms of service. See the [v3.13.0 release notes](v3.13.0-en.md#-risk-notice) for details.
**Codex third-party provider Chat routing**: when CC Switch local proxy converts and forwards Codex requests to third-party providers, each provider may have different requirements for billing, compliance, and data retention. Read the target provider's terms before use.
**Claude Desktop third-party provider proxy switching**: when CC Switch's built-in proxy gateway forwards Claude Desktop requests to third-party providers, you must also follow the target provider's billing, compliance, and data-retention terms.
By enabling these features, users accept the related risks. CC Switch is not responsible for account restrictions, warnings, or service suspensions caused by using these features.
---
## Thanks
Thanks to the following contributors for the features and fixes in v3.16.2:
- [#1351](https://github.com/farion1231/cc-switch/pull/1351): add S3-compatible cloud storage sync, thanks @keithyt06.
- [#3215](https://github.com/farion1231/cc-switch/pull/3215): add OpenCode session usage sync, thanks @nothingness0db.
- [#2709](https://github.com/farion1231/cc-switch/pull/2709): add the ZenMux Token Plan provider, thanks @Eter365.
- [#3643](https://github.com/farion1231/cc-switch/pull/3643): add the CherryIN preset provider, thanks @zhibisora.
- [#3818](https://github.com/farion1231/cc-switch/pull/3818): add the Codex CLI reachability `GET /v1/models` endpoint, thanks @CSberlin.
- [#3426](https://github.com/farion1231/cc-switch/pull/3426): Usage Dashboard hero redesign, thanks @allenxu09.
- [#3640](https://github.com/farion1231/cc-switch/pull/3640): drop `tool_choice` when tools is empty, thanks @Postroggy.
- [#3644](https://github.com/farion1231/cc-switch/pull/3644): preserve Codex custom tool metadata in chat routing, thanks @LanternCX.
- [#3514](https://github.com/farion1231/cc-switch/pull/3514): always include `reasoning_tokens` in Chat→Responses, thanks @yeeyzy.
- [#3689](https://github.com/farion1231/cc-switch/pull/3689): skip backup / restore when live is already a proxy placeholder, thanks @YongmaoLuo.
- [#3016](https://github.com/farion1231/cc-switch/pull/3016): normalize the localhost listen address, thanks @Alexlangl.
- [#3775](https://github.com/farion1231/cc-switch/pull/3775): normalize Anthropic `system` messages, thanks @Dearli666.
- [#3656](https://github.com/farion1231/cc-switch/pull/3656): improve error message display in the proxy panel, thanks @lzcndm.
- [#2647](https://github.com/farion1231/cc-switch/pull/2647): raise the infinite-whitespace threshold 20 → 500, thanks @NiuBlibing.
- [#3702](https://github.com/farion1231/cc-switch/pull/3702): route the Zhipu quota query to the configured base URL, thanks @YongmaoLuo.
- [#3518](https://github.com/farion1231/cc-switch/pull/3518): adapt to the MiniMax new balance API and default pricing, thanks @LaoYueHanNi.
- [#3524](https://github.com/farion1231/cc-switch/pull/3524): fix the Zhipu Coding Plan presets and model probing for versioned endpoints, thanks @makoMakoGo.
- [#3614](https://github.com/farion1231/cc-switch/pull/3614): use a relative filename for the model catalog, thanks @steponeerror.
- [#3797](https://github.com/farion1231/cc-switch/pull/3797): fix the Windows tray icon residue after exit, thanks @iAJue.
- [#3457](https://github.com/farion1231/cc-switch/pull/3457): fix the Windows taskbar icon, thanks @ZhangNanNan1018.
- [#3430](https://github.com/farion1231/cc-switch/pull/3430): normalize Windows path separators to match subdirectory skill updates, thanks @Ninthless.
- [#3626](https://github.com/farion1231/cc-switch/pull/3626): disable macOS input auto-capitalization, thanks @ZHLHZHU.
- [#3593](https://github.com/farion1231/cc-switch/pull/3593): fix Codex VS Code session previews, thanks @xwil1.
- [#3228](https://github.com/farion1231/cc-switch/pull/3228): align the VS Code wording in the Chinese UI, thanks @Games55k.
- [#3411](https://github.com/farion1231/cc-switch/pull/3411): refresh the user manual to reflect current app support, thanks @makoMakoGo.
- [#3772](https://github.com/farion1231/cc-switch/pull/3772): fix README release-note links and sponsor markup, thanks @null-easy.
Thanks also to everyone who reported Codex Chat routing, local proxy takeover, usage statistics, and platform compatibility issues after v3.16.1. Many of these fixes came directly from real-world reproduction details.
---
## Download & Install
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) and download the build for your system.
### System Requirements
| System | Minimum Version | Architecture |
| ------- | ------------------------ | ----------------------------------- |
| Windows | Windows 10 and later | x64 |
| macOS | macOS 12 (Monterey)+ | Intel (x64) / Apple Silicon (arm64) |
| Linux | See table below | x64 / ARM64 |
### Windows
| File | Description |
| ---------------------------------------- | ------------------------------------------------ |
| `CC-Switch-v3.16.2-Windows.msi` | **Recommended** - MSI installer with auto-update |
| `CC-Switch-v3.16.2-Windows-Portable.zip` | Portable build, unzip and run |
### macOS
| File | Description |
| -------------------------------- | ----------------------------------------------------- |
| `CC-Switch-v3.16.2-macOS.dmg` | **Recommended** - DMG installer, drag to Applications |
| `CC-Switch-v3.16.2-macOS.zip` | Unzip and drag to Applications, Universal Binary |
| `CC-Switch-v3.16.2-macOS.tar.gz` | For Homebrew install and auto-update |
Homebrew install:
```bash
brew install --cask cc-switch
```
Upgrade:
```bash
brew upgrade --cask cc-switch
```
### Linux
Linux assets are available for both **x86_64** and **ARM64** (`aarch64`). Choose the file whose architecture tag matches your machine's `uname -m` output:
- `CC-Switch-v3.16.2-Linux-x86_64.AppImage` / `.deb` / `.rpm`
- `CC-Switch-v3.16.2-Linux-arm64.AppImage` / `.deb` / `.rpm`
| Distribution | Recommended Format | Install Command |
| --------------------------------------- | ------------------ | --------------------------------------------------------------------- |
| 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` | Make executable and run directly, or use AUR |
| Other distributions / unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+347
View File
@@ -0,0 +1,347 @@
# CC Switch v3.16.2
> v3.16.1 の Codex 安定性パッチに続き、本リリースはデータの可搬性と用量の可観測性の拡張を主眼としています。S3 互換クラウド同期、OpenCode セッション用量同期、公式サブスクリプション残量テンプレートを追加し、Codex がサードパーティプロバイダーを Chat Completions ルーティングする際の堅牢性を引き続き強化しました。あわせて Windows / macOS のプラットフォーム問題を一括修正し、CherryIN・ZenMux プロバイダーを追加し、3 言語のユーザーマニュアルを全面的に刷新しました。
**[English →](v3.16.2-en.md) | [中文 →](v3.16.2-zh.md)**
---
## 利用ガイド
本リリースではクラウド同期の S3 バックエンドと、より多くの用量統計ソースを追加しました。利用したい場合は、まず以下のドキュメントをご覧ください:
- **[設定](../user-manual/ja/1-getting-started/1.5-settings.md)**: 設定ページでクラウド同期(WebDAV / S3 互換ストレージ)を構成し、プロバイダー、MCP、プロンプト、スキルなどの設定を複数デバイス間でバックアップ・復元します。
- **[用量統計](../user-manual/ja/4-proxy/4.4-usage.md)**: 用量ダッシュボードのデータソース(プロキシログ、Codex / Gemini / OpenCode セッション同期)と統計の数え方を確認できます。
---
> [!WARNING]
>
> ## 唯一の公式チャネル(必ずお読みください)
>
> CC Switch は**完全に無料・オープンソース**のデスクトップアプリで、**ユーザーから料金を徴収することはありません**。本ソフトウェアは下記の公式チャネルからのみ入手してください:
>
> | チャネル | 唯一の公式 |
> | ------------ | ------------------------------------------------------------------------------ |
> | 公式サイト | **[ccswitch.io](https://ccswitch.io)** |
> | ソースコード | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
> | ダウンロード | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
> | 偽サイト通報 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
>
> **料金請求・チャージ・認証情報の提供を求める「CC Switch」サイトやクライアントはすべて偽物です。** 支払いを誘導された場合は直ちに操作を中止し、GitHub Issues からご報告ください。
---
## 概要
CC Switch v3.16.2 は v3.16.1 に続くメンテナンスアップデートです。前リリースでは Codex 公式認証とローカルルーティングのテイクオーバーのセキュリティ問題に集中しましたが、本リリースは 2 点に重きを置いています。1 つ目はデータの可搬性と用量の可観測性の拡張で、S3 互換クラウド同期(WebDAV に並ぶ 2 つ目のクラウドバックアップバックエンド)、OpenCode セッション用量同期、公式サブスクリプション向けの残量統計テンプレートを追加しました。2 つ目は、Codex がサードパーティプロバイダーを Chat Completions ルーティングする際に露呈したエッジケースの継続的な改善で、ストリーム切断の判定、tools が空のときの `tool_choice`、カスタムツールのメタデータ、推論トークン統計、ファイル / 音声添付の変換などです。
本リリースではローカルプロキシの堅牢性に関する問題(一時ポートの解決、テイクオーバーのプレースホルダー復元ループ、Anthropic `system` メッセージの正規化、上流 413 の文言、Claude Desktop の `[1m]` モデルルーティング)を一括修正し、いくつかの Windows / macOS のプラットフォーム体験の問題に対処し、CherryIN・ZenMux の 2 プロバイダーを追加し、3 言語のユーザーマニュアルを全面的に刷新しました。
**リリース日**: 2026-06-07
**Stats**: 41 commits | 132 files changed | +11,116 / -1,636 lines
---
## ハイライト
- **S3 互換クラウド同期**: WebDAV に並ぶ 2 つ目のクラウドバックアップバックエンドとして S3 互換オブジェクトストレージを追加。AWS S3、MinIO、Cloudflare R2、Alibaba Cloud OSS、Tencent Cloud COS、Huawei OBS などのワンクリックプリセットを内蔵します。
- **より多くの用量データソース**: OpenCode セッション用量同期と、Claude / Codex / Gemini 公式プロバイダー向けの公式サブスクリプション残量テンプレート(明示的なトグル、デフォルトでオフ)を追加しました。
- **Codex Chat Completions ルーティングの継続的な強化**: ストリーム切断の誤判定、tools が空のときの `tool_choice` 拒否、カスタムツールメタデータの欠落、推論トークン統計の欠落を修正し、ファイル / 音声添付の変換と `/v1/models` 到達性エンドポイントを追加しました。
- **より堅牢なローカルプロキシ**: 一時ポート(port 0)の解決、テイクオーバーのプレースホルダー復元ループ、Anthropic `system` メッセージの正規化、上流 413 の文言、Claude Desktop の 1M コンテキストモデルルーティングを修正しました。
- **プラットフォームとプロバイダー**: Windows のトレイ / タスクバーアイコン、サブディレクトリスキルの更新、macOS の入力自動大文字化を修正し、CherryIN・ZenMux プロバイダーを追加しました。
---
## 追加機能
### S3 互換クラウド同期
クラウド同期は WebDAV に並ぶ 2 つ目のバックエンドとして S3 互換オブジェクトストレージに対応しました。署名は自前実装の AWS Signature V4 を用い、できるだけ多くのサービスと互換性を持たせています。設定ページでは AWS S3、MinIO、Cloudflare R2、Alibaba Cloud OSS、Tencent Cloud COS、Huawei OBS、およびカスタム endpoint のワンクリックプリセットを提供し、接続テスト、手動アップロード / ダウンロード、設定変更時の自動同期(providers、endpoint、MCP、プロンプト、スキル、設定、プロキシなどの設定テーブル。用量ログのような高頻度書き込みデータは**含みません**)に対応します。S3 同期を有効化すると、実行中の WebDAV 同期は停止し、その逆も同様です(#1351)。
### OpenCode セッション用量同期
OpenCode を用量統計のソースとして追加しました。OpenCode のローカル SQLite データベースからメッセージごとの token、コスト、モデルのデータを読み取り、用量レコードへインポートします。専用の「OpenCode」アプリフィルタタブと「OpenCode Session」データソースラベルを備えます。データベースパスは `OPENCODE_DB``XDG_DATA_HOME` を尊重し(全プラットフォームで既定は `~/.local/share/opencode`)、完了済みのメッセージのみをインポートし、新鮮度判定で WAL ファイルも含めるため、書き込み直後のセッションがスキップされません(#3215)。
### 公式サブスクリプション残量テンプレート
用量照会を発行する IP とアプリ内リクエストを発行する IP が異なるとアカウント停止のリスクがある、という一部ユーザーの懸念を受けて、Claude / Codex / Gemini 公式プロバイダー向けに、CLI / OAuth 認証情報でプラン残量を照会する明示的・任意の「公式サブスクリプション」用量テンプレートを追加し、これまでの公式プロバイダーに対する暗黙の自動照会を置き換えました。このテンプレートはデフォルトでオフで、用量スクリプトのモーダルから有効化でき、更新間隔を設定できます。本機能を利用する際は、プロキシの TUN モードを有効化することを推奨します。
### テキスト専用モデルの画像フォールバック整流器
ルーティング先のモデルがテキスト専用(明示的な宣言、または内蔵のモデル名ヒューリスティックで判定)の場合、または上流が画像入力を拒否する場合に、Anthropic の画像ブロックを `[Unsupported Image]` プレースホルダーへ置き換えるプロキシ整流器を追加し、会話の中断を防ぎます。設定ページにこのフォールバックのトグルを用意し、さらにヒューリスティック検出を制御する別のトグル(マルチモーダルモデルの誤判定を避けるためオフにできます)を用意しました。
### ZenMux Token Plan プロバイダー
ZenMux を Token Plan 系の Coding Plan プロバイダーとして追加しました。用量スクリプトのモーダルで API key と base URL を手動入力でき、使用量 / 残量を米ドル建てでリッチに表示します(#2709)。
### CherryIN プリセット
CherryIN アグリゲーターゲートウェイをクイック設定プリセットとして、受管 7 アプリすべてに追加しました。Claude Code / Claude Desktop / OpenClaw / Hermes は Anthropic 形式の endpointopen.cherryin.net)、OpenCode は `@ai-sdk/anthropic``/v1`)、Codex は OpenAI 互換 endpoint、Gemini CLI は Gemini 互換 endpoint を使用します。公式ブランドアイコン付きで、AiHubMix の隣に配置されます(#3643)。
### Codex CLI 到達性エンドポイント `/v1/models`
ローカルプロキシは、Codex CLI が起動時にプローブする `GET /v1/models` に応答し、CC Switch が管理する Codex モデルカタログを返すようになりました。あわせて古いカタログのガードを追加: live の `config.toml` を解析し、`model_catalog_json` が CC Switch 所有のカタログファイルを指している場合のみ提供することで、前のプロバイダーが残したカタログを Codex に見せてしまうことを防ぎます(#3818)。
### Codex Chat のファイル・音声添付
Codex の Responses→Chat 変換は、`input_file``file_id` またはインライン `file_data` を持つ)と `input_audio` のコンテンツ部分を Chat Completions の対応形態へマッピングし、これまで破棄されていたトップレベルの `input_*` 項目も出力するようになりました。これにより、ファイルと音声の添付が Chat のみ対応の Codex 上流へ届きます。
---
## 変更
### 用量ダッシュボードのヒーロー再設計
用量ダッシュボードのヒーロー領域とサマリーカードをよりコンパクトなレイアウトに再構成し、実トークン総量、リクエスト数、コストを最上部の 1 行にまとめました(#3426)。
### SSSAiCode エンドポイント刷新
SSSAiCode プリセットの公式サイト、登録、API base URL を `sssaicodeapi.com` ドメインへ更新し、endpoint 候補ノード(既定 `node-hk.sssaicodeapi.com`、ほかに `node-hk.sssaiapi.com``node-cf.sssaicodeapi.com`)を全 7 アプリのプリセットで刷新しました。
---
## 修正
### Codex Chat ストリーム切断の判定
Chat Completions 上流が `finish_reason``[DONE]` もなくストリームを終了した場合、CC Switch はこれを正常完了として扱わなくなりました: 本当に終了したときのみ正常に締め、部分的な出力があった場合は incomplete(`max_output_tokens`)レスポンスを、何も出力されなかった場合は失敗 `stream_truncated` イベントを発行します。遅れて届いた推論も、まだアクティブなストリーミングのツール呼び出しへバックフィルされます。
### tools が空のときの Codex Chat `tool_choice`
Responses→Chat 変換は、最終的な tools 配列が欠落または空(すべてのツールがフィルタで除外された場合を含む)のときに `tool_choice``parallel_tool_calls` を破棄するようになりました。これにより、厳格な OpenAI 互換上流(vLLM、エンタープライズゲートウェイ)が「When using `tool_choice`, `tools` must be set.」で 503/400 を返すことを避けます(#3640)。
### Codex カスタムツールメタデータの保持
カスタム Codex ツール(自由形式の `apply_patch` ツールなど)は、汎用プレースホルダーへ置き換えられる代わりに、format と grammar のメタデータを含む完全な元定義を、生成される Chat 関数の説明にコンパクトで順序の安定した JSON ブロックとして埋め込むようになりました。これにより Chat Completions 上流でも引き続き利用できます(#3644)。
### Codex Chat 用量の `reasoning_tokens` 欠落
Chat→Responses の用量変換は、プロバイダーが `completion_tokens_details` を省略したり非オブジェクトを返したりしても、常に `output_tokens_details.reasoning_tokens`(既定 0)を含めるようになりました。これにより Codex CLI の厳格な要件を満たし、レスポンス解析の失敗と再試行の繰り返しを避けます(#3514)。
### Codex カスタム / 検索ツールのターン跨ぎ推論
Codex Chat 履歴のターン跨ぎ推論キャッシュが、通常の関数呼び出しだけでなく、ツール呼び出しの全集合(`function_call``custom_tool_call``tool_search_call`)とその出力をカバーするようになりました。これにより `apply_patch` とツール検索の呼び出しは、`previous_response_id` で復元されるときにそれぞれの `reasoning_content` を保持します。
### 一時ポート(port 0)の解決
プロキシが port 0(OS 割り当て)でリッスンするよう構成されている場合、テイクオーバーはまずプロキシを起動して実際のポートを取得してから live 設定とデータベースへ書き込むようになり、クライアント URL が無効な `:0` アドレスを指すことを避けます。具体的なポートがまだ解決されていない場合、Claude Desktop のゲートウェイ URL は拒否されます。
### プロキシプレースホルダーのバックアップ / 復元ループ
前回プロキシ停止時に元の live 設定の復元に失敗し、プロキシプレースホルダーが live に残ってしまった場合でも、再度テイクオーバーする際に正常なバックアップをプロキシ設定で上書きすることはなくなり、復元時にプレースホルダーを live へ書き戻すこともなくなりました: いずれの経路もプレースホルダー状態を検知し、現在のプロバイダーを信頼できる情報源として live を再構築します。これにより、プロキシのトグルが何もしない状態になり、クライアントがローカルプロキシアドレスに固定されてしまう問題を修正しました(#3689)。
### プロキシテイクオーバー中のプロバイダー切り替え誤ブロック
ローカルルーティングのテイクオーバー中、明示的に official と分類されたプロバイダーのみが切り替えをブロックされるようになり、endpoint が meta に存在する、またはフィールドが未入力なだけのカスタムプロバイダーまで無効化することはなくなりました。無効化された「有効化」ボタンは、以前の赤い「ブロック済み」バッジの代わりに、より軽いヒントのツールチップを表示します。
### localhost リッスンアドレスの正規化
プロキシのリッスンアドレスを `localhost` で保存した場合、永続化前に `127.0.0.1` へ正規化されるようになり、バインドの不整合を避けます(#3016)。
### Anthropic `system` メッセージの正規化
Anthropic 形式のプロバイダーでは、`messages` 配列内の system ロールのエントリを折りたたんでトップレベルの `system` フィールドへマージするようになり(元の順序と既存のトップレベル system を保持)、厳格な上流が先頭以外の system メッセージを拒否することを避けます。OpenAI Chat ルーティングは影響を受けません(#3775)。
### Claude Desktop 1M コンテキストモデルルーティング
Claude Desktop は 1M コンテキスト beta が有効なとき、モデル名に `[1m]` マーカーを付加します(例: `claude-opus-4-8[1m]`)。プロキシはルーティング照合の前にこの接尾辞を除去するようになり、完全一致・エイリアス・旧名・ロールキーワードの照合がすべて正しく解決されます。これにより、会話の途中で 1M モデルへ切り替えたときの `route_unknown`(HTTP 400)の失敗を修正しました。診断用に、`route_unknown` エラーには元のモデル名を引き続き保持します。
### Codex 413 エラーの文言
Codex 上流ゲートウェイが過大なリクエストボディを HTTP 413 で拒否したとき、プロキシはこれが CC Switch のローカル制限ではなくプロバイダーのサーバー側ボディサイズ制限であることを説明する専用メッセージを返し、実行可能な回復手順(`/compact` の実行、大きなログやインライン画像の削除、プロバイダーへの上限引き上げ依頼)を提示するようになりました。上流の生の HTML エラーページをそのまま返すことはなくなりました。
### プロキシパネルのエラー詳細
プロキシのテイクオーバー切り替えに失敗したとき、プロキシパネルのトーストは、汎用の失敗メッセージだけでなく、バックエンドが返す具体的なエラー詳細を含めるようになりました(#3656)。
### Copilot 無限空白検出のしきい値
ストリーミングの無限空白の中断しきい値を、連続する空白文字 20 から 500 へ引き上げました。これにより、引数に深くインデントされたコード(Python、YAML、Rust、Markdown)を含む正当なツール呼び出しが誤って中断されることを避けつつ、本物の Copilot 無限空白バグは引き続き捕捉します(#2647)。
### サブスクリプション階層のトレイ表示
統一された階層→ラベルのマッピングにより、トレイと残量表示における公式サブスクリプション階層の表示を修正しました: Claude / Codex は 7 日ウィンドウを取りこぼさなくなり、Gemini Pro / Flash / Flash-Lite の階層は生のマシン名を漏らさなくなり、複数ウィンドウのプラン(Opus + Sonnet など)は最初の一致ではなく最悪の利用率を表示するようになりました。
### Claude ストリームの input_tokens 過大計上
一部の Anthropic 互換ストリーミングプロバイダー(Qwen、MiniMax など)は `message_start` で完全なコンテキストを `input_tokens` として報告し、別途報告済みのキャッシュ分を二重計上して、表示上のキャッシュヒット率を不当に低下させていました。パーサーは `message_delta` のより小さい正の `input_tokens` を優先し、同じ usage ブロックのキャッシュカウントを採用するようになりました。ネイティブ Claude と OpenRouter 変換の経路は変更ありません。
### 智譜(Zhipu)残量照会の endpoint ルーティング
智譜 Coding Plan の残量照会は `api.z.ai` にハードコードされていたため、本土プリセット(`open.bigmodel.cn`)のユーザーは国際 endpoint が到達不能なときに用量を取得できませんでした。残量リクエストは、ユーザーが構成した base URL に一致するホストへルーティングされるようになりました(#3702)。
### MiniMax 残量 API と価格
MiniMax Coding Plan の残量を新しい残量 API に対応させました(新 API は、旧パーサーが依存していた用量カウント(階層が空になりトレイに用量が表示されなくなる)の代わりに、残り割合のフィールドを返します)。非コーディングモデル(動画など)を除外し、週次上限のないプランに対応し、MiniMax M3 モデルの既定価格を追加しました(#3518)。
### GLM Coding Plan の endpoint とモデル取得
智譜 / Z.AI の GLM Coding Plan プリセットを `/api/coding/paas/v4` endpoint に修正し(Codex、OpenCode、OpenClaw、Hermes をカバー)、すでに `/v{N}` のバージョンセグメントで終わる base URL については、モデル一覧プローブが `{base}/models` を先に照会するようにしました(`/v1/models` はフォールバックとして保持)。これにより「モデル取得」ボタンがバージョン付き endpoint で 404 にならなくなりました(#3524)。
### Codex モデルカタログパスの可搬性
Codex は `config.toml` に絶対パスではなく相対ファイル名 `cc-switch-model-catalog.json` のみを書き込むようになりました(Codex CLI は設定ディレクトリから解決します)。これにより、絶対パスを変換できない WSL やシンボリックリンク環境でモデルカタログが壊れる問題を修正しました(#3614)。
### APINebula の OpenCode SDK
APINebula の OpenCode プリセットは `@ai-sdk/openai` ではなく `@ai-sdk/openai-compatible` を読み込むようになり、chat-completions のみ対応の上流で失敗する Responses API ではなく、このリレーが期待する OpenAI Chat Completions 形式でリクエストを行います。
### Windows 終了後のトレイアイコン残留
Windows では CC Switch を終了すると、マウスを重ねるまで無効なトレイアイコンが残ることがありました。アプリは終了前にトレイアイコンを明示的に削除するようになり、プロセス終了とともにきれいに消えます(#3797)。
### Windows タスクバーアイコン
実行時に Windows AppUserModelID を明示的に設定し、インストーラーが生成するデスクトップとスタートメニューのショートカットに同じ ID と製品アイコンを書き込みます。これにより CC Switch がタスクバーで正しいアイコンを表示し、正しくグループ化されます(#3457)。
### Windows サブディレクトリスキルの更新チェック
Windows でインストール済みスキルをスキャンする際、バックスラッシュのパス区切りをスラッシュへ正規化するようになり、サブディレクトリにネストされたスキル(`skills/my-skill` など)が静かにスキップされず、更新チェックで一致するようになりました(#3430)。
### macOS の入力自動大文字化
共有のテキスト Input コンポーネントで autocomplete、autocorrect、autocapitalize、spellcheck を無効化し、macOS が設定フィールドに入力された最初の文字を自動で大文字化・自動修正しないようにしました(#3626)。
### Codex VS Code セッションプレビュー
VS Code から送信された Codex リクエストでは、注入されたリクエストの前に markdown 見出しがあると、セッションプレビューが本当のプロンプトではなく選択範囲や開いているファイルの内容を表示することがありました。バックエンドのタイトルとフロントエンドのプレビューはいずれも、最後の「## My request for Codex:」見出しに一致するようになり(IDE は本当のリクエストを最後のセクションとして注入します)、プレビューがユーザーのプロンプトを反映します(#3593)。
### 中国語 UI の VS Code 表記
簡体字・繁体字中国語の「Claude Code プラグインに適用」の説明を、「Vscode」ではなく正しく「VS Code」と表記するよう修正し、英語・日本語の文言と揃えました(#3228)。
---
## ドキュメント
### ユーザーマニュアル刷新
README の各言語版と en / zh / ja のユーザーマニュアルを刷新し、受管 7 アプリすべてを反映(紹介と概要の文面に Claude Desktop と Hermes を追加)、OpenCode の設定パスを `~/.config/opencode/``opencode.json`)に修正、Hermes の設定ファイルの説明を追加、言語ドキュメントを 4 言語に更新、アプリごとの MCP / プロンプト / スキルの対応状況を訂正、エクスポートがタイムスタンプ付きで用量ログを含む SQL バックアップを生成することを記載、価格モデル ID のマッチングルールを追記しました(#3411)。
### Codex 公式認証保持ガイド
モデル通信をサードパーティ API へ切り替えつつ、Codex の公式リモート操作と公式プラグインを動作させ続ける方法を説明する中国語 / 英語 / 日本語のガイドを追加し、v3.16.1 のリリースノートからリンクしました。
### README リンクとスポンサー表記
各言語の README のリリースノートリンクを v3.16.1 に更新し、README_ZH のスポンサーブロックで壊れていた曲線引用符文字を修正して、HTML 属性が正しくレンダリングされるようにしました(#3772)。
---
## アップグレード時の注意
### S3 と WebDAV のクラウド同期は排他
クラウド同期は同時に 1 つのバックエンドのみを実行します。S3 自動同期を有効化すると、実行中の WebDAV 自動同期は停止し、その逆も同様です。以前 WebDAV を使っていた場合は、S3 へ切り替える前に両端のデータが揃っていることを確認し、旧バックエンドがまだバックアップしていると誤解しないようにしてください。
### モデルマッピング変更後は Codex の再起動が必要
Codex は起動時に `model_catalog_json` を読み込みます。本リリースでモデルカタログを相対パスへ書き換え、`/v1/models` 到達性エンドポイントを追加しましたが、モデルマッピングテーブルを変更した後は、`/model` メニューを更新するために Codex の再起動が必要です。
---
## リスク通知
本リリースは、リバースプロキシ系機能に関する以前のリスク通知を引き続き適用します。
**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションの Codex OAuth をリバースプロキシ経由で使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 release notes](v3.13.0-ja.md#-リスクに関する注意事項) を参照してください。
**Codex サードパーティプロバイダー Chat ルーティング**: CC Switch ローカルプロキシで Codex リクエストを変換し、サードパーティプロバイダーへ転送する場合、課金、コンプライアンス、データ保持に関する制約はプロバイダーごとに異なります。利用前に対象プロバイダーの利用規約を確認してください。
**Claude Desktop サードパーティプロバイダープロキシ切り替え**: CC Switch 内蔵のプロキシゲートウェイで Claude Desktop のリクエストをサードパーティプロバイダーへ転送する場合も、対象プロバイダーの課金、コンプライアンス、データ保持に関する規約に従う必要があります。
上記機能を有効化したユーザーは、関連するリスクを自ら負うものとします。CC Switch は、これらの機能の利用によって発生したアカウント制限、警告、サービス停止について責任を負いません。
---
## 謝辞
v3.16.2 で機能と修正を届けてくださった以下のコントリビューターに感謝します:
- [#1351](https://github.com/farion1231/cc-switch/pull/1351): S3 互換クラウドストレージ同期を追加、@keithyt06 に感謝。
- [#3215](https://github.com/farion1231/cc-switch/pull/3215): OpenCode セッション用量同期を追加、@nothingness0db に感謝。
- [#2709](https://github.com/farion1231/cc-switch/pull/2709): ZenMux Token Plan プロバイダーを追加、@Eter365 に感謝。
- [#3643](https://github.com/farion1231/cc-switch/pull/3643): CherryIN プリセットプロバイダーを追加、@zhibisora に感謝。
- [#3818](https://github.com/farion1231/cc-switch/pull/3818): Codex CLI 到達性確認用の `GET /v1/models` エンドポイントを追加、@CSberlin に感謝。
- [#3426](https://github.com/farion1231/cc-switch/pull/3426): 用量ダッシュボードのヒーロー再設計、@allenxu09 に感謝。
- [#3640](https://github.com/farion1231/cc-switch/pull/3640): tools が空のとき `tool_choice` を破棄、@Postroggy に感謝。
- [#3644](https://github.com/farion1231/cc-switch/pull/3644): Chat ルーティングで Codex カスタムツールメタデータを保持、@LanternCX に感謝。
- [#3514](https://github.com/farion1231/cc-switch/pull/3514): Chat→Responses で常に `reasoning_tokens` を含める、@yeeyzy に感謝。
- [#3689](https://github.com/farion1231/cc-switch/pull/3689): live がすでにプロキシプレースホルダーのときバックアップ / 復元をスキップ、@YongmaoLuo に感謝。
- [#3016](https://github.com/farion1231/cc-switch/pull/3016): localhost リッスンアドレスを正規化、@Alexlangl に感謝。
- [#3775](https://github.com/farion1231/cc-switch/pull/3775): Anthropic `system` メッセージを正規化、@Dearli666 に感謝。
- [#3656](https://github.com/farion1231/cc-switch/pull/3656): プロキシパネルのエラー表示を改善、@lzcndm に感謝。
- [#2647](https://github.com/farion1231/cc-switch/pull/2647): 無限空白検出のしきい値を 20 → 500 へ引き上げ、@NiuBlibing に感謝。
- [#3702](https://github.com/farion1231/cc-switch/pull/3702): 智譜の残量照会を構成済み base URL へルーティング、@YongmaoLuo に感謝。
- [#3518](https://github.com/farion1231/cc-switch/pull/3518): MiniMax の新残量 API と既定価格に対応、@LaoYueHanNi に感謝。
- [#3524](https://github.com/farion1231/cc-switch/pull/3524): 智譜 Coding Plan プリセットとバージョン付き endpoint のモデル探索を修正、@makoMakoGo に感謝。
- [#3614](https://github.com/farion1231/cc-switch/pull/3614): モデルカタログを相対ファイル名に変更、@steponeerror に感謝。
- [#3797](https://github.com/farion1231/cc-switch/pull/3797): Windows 終了後のトレイアイコン残留を修正、@iAJue に感謝。
- [#3457](https://github.com/farion1231/cc-switch/pull/3457): Windows タスクバーアイコンを修正、@ZhangNanNan1018 に感謝。
- [#3430](https://github.com/farion1231/cc-switch/pull/3430): Windows のパス区切りを正規化してサブディレクトリスキルの更新に対応、@Ninthless に感謝。
- [#3626](https://github.com/farion1231/cc-switch/pull/3626): macOS の入力自動大文字化を無効化、@ZHLHZHU に感謝。
- [#3593](https://github.com/farion1231/cc-switch/pull/3593): Codex VS Code セッションプレビューを修正、@xwil1 に感謝。
- [#3228](https://github.com/farion1231/cc-switch/pull/3228): 中国語 UI の VS Code 表記を揃える、@Games55k に感謝。
- [#3411](https://github.com/farion1231/cc-switch/pull/3411): 現行のアプリ対応を反映してユーザーマニュアルを刷新、@makoMakoGo に感謝。
- [#3772](https://github.com/farion1231/cc-switch/pull/3772): README のリリースノートリンクとスポンサー表記を修正、@null-easy に感謝。
v3.16.1 リリース後に Codex Chat ルーティング、ローカルプロキシのテイクオーバー、用量統計、プラットフォーム互換性の問題を報告してくださったすべてのユーザーにも感謝します。今回の多くの修正は、実際の利用シーンから得られた再現情報に基づいています。
---
## ダウンロードとインストール
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から、お使いのシステムに対応するビルドをダウンロードしてください。
### システム要件
| システム | 最低バージョン | アーキテクチャ |
| -------- | ------------------------ | ----------------------------------- |
| Windows | Windows 10 以降 | x64 |
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 下表を参照 | x64 / ARM64 |
### Windows
| ファイル | 説明 |
| ---------------------------------------- | ------------------------------------------ |
| `CC-Switch-v3.16.2-Windows.msi` | **推奨** - 自動更新対応の MSI インストーラー |
| `CC-Switch-v3.16.2-Windows-Portable.zip` | ポータブル版、展開してそのまま実行できます |
### macOS
| ファイル | 説明 |
| -------------------------------- | ------------------------------------------------------ |
| `CC-Switch-v3.16.2-macOS.dmg` | **推奨** - DMG インストーラー、Applications へドラッグ |
| `CC-Switch-v3.16.2-macOS.zip` | 展開して Applications へドラッグ、Universal Binary |
| `CC-Switch-v3.16.2-macOS.tar.gz` | Homebrew インストールと自動更新用 |
Homebrew インストール:
```bash
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
Linux アセットは **x86_64****ARM64**`aarch64`)の両方を提供します。ファイル名にアーキテクチャ識別子が含まれているため、マシンの `uname -m` 出力に合わせて選択してください:
- `CC-Switch-v3.16.2-Linux-x86_64.AppImage` / `.deb` / `.rpm`
- `CC-Switch-v3.16.2-Linux-arm64.AppImage` / `.deb` / `.rpm`
| ディストリビューション | 推奨形式 | インストール方法 |
| --------------------------------------- | ----------- | ------------------------------------------------------------------------- |
| 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` |
+347
View File
@@ -0,0 +1,347 @@
# CC Switch v3.16.2
> 在 v3.16.1 的 Codex 稳定性补丁之后,这一版主要拓宽了数据的可携带性与用量观测能力——新增 S3 兼容云同步、OpenCode 会话用量同步、官方订阅额度模板——并继续加固 Codex 通过 Chat Completions 路由第三方供应商的稳健性,同时修复了一批 Windows / macOS 平台问题,新增 CherryIN、ZenMux 供应商,并全面刷新了三语用户手册。
**[English →](v3.16.2-en.md) | [日本語版 →](v3.16.2-ja.md)**
---
## 使用攻略
这一版新增了云同步的 S3 后端和更多用量统计来源,如果你想用上,可以先看这些文档:
- **[设置](../user-manual/zh/1-getting-started/1.5-settings.md)**:在设置页配置云同步(WebDAV / S3 兼容存储),用于在多台设备间备份和恢复供应商、MCP、提示词、技能等配置。
- **[用量统计](../user-manual/zh/4-proxy/4.4-usage.md)**:了解用量看板的数据来源(代理日志、Codex / Gemini / OpenCode 会话同步)与统计口径。
---
> [!WARNING]
>
> ## 唯一官方渠道声明(请务必阅读)
>
> CC Switch 是**完全免费、开源**的桌面应用,**不会向用户收取任何费用**。请仅通过下列官方渠道获取本软件:
>
> | 类别 | 唯一官方 |
> | -------- | ------------------------------------------------------------------------------ |
> | 官网 | **[ccswitch.io](https://ccswitch.io)** |
> | 源码 | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
> | 下载 | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
> | 举报山寨 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
>
> **任何向你收费、要求充值、或索取登录凭据的"CC Switch"网站或客户端均为假冒**。如果你被诱导支付了费用,请立即停止操作并通过 GitHub Issues 反馈。
---
## 概览
CC Switch v3.16.2 是 v3.16.1 之后的一版维护更新。在上一版集中处理 Codex 官方鉴权与本地路由接管的安全问题之后,这一版把重心放在两件事上:一是拓宽数据的可携带性和用量观测——新增 S3 兼容云同步(WebDAV 之外的第二套云备份后端)、OpenCode 会话用量同步,以及面向官方订阅的额度统计模板;二是继续打磨 Codex 通过 Chat Completions 路由第三方供应商时暴露出来的边角问题——流式截断判定、空 tools 下的 `tool_choice`、自定义工具元数据、推理 token 统计、文件 / 音频附件转换等。
此外,本版还修复了一批本地代理的稳健性问题(临时端口解析、接管占位符还原死循环、Anthropic `system` 消息归一化、上游 413 文案、Claude Desktop 的 `[1m]` 模型路由),处理了若干 Windows / macOS 平台体验问题,并新增 CherryIN、ZenMux 两个供应商,同时全面刷新了三语用户手册。
**发布日期**2026-06-07
**更新规模**41 commits | 132 files changed | +11,116 / -1,636 lines
---
## 重点内容
- **S3 兼容云同步**:在 WebDAV 之外新增 S3 兼容对象存储作为第二套云备份后端,内置 AWS S3、MinIO、Cloudflare R2、阿里云 OSS、腾讯云 COS、华为 OBS 等一键预设。
- **更多用量统计来源**:新增 OpenCode 会话用量同步,以及面向 Claude / Codex / Gemini 官方订阅的额度统计模板(显式开关、默认关闭)。
- **Codex Chat Completions 路由继续加固**:修复流式截断误判、空 tools 下 `tool_choice` 被拒、自定义工具元数据丢失、推理 token 统计缺失,并支持文件 / 音频附件转换与 `/v1/models` 探活端点。
- **本地代理更稳**:修复临时端口(port 0)解析、接管占位符还原死循环、Anthropic `system` 消息归一化、上游 413 文案,以及 Claude Desktop 1M 上下文模型路由。
- **平台与供应商**:修复 Windows 托盘 / 任务栏图标、子目录技能更新、macOS 输入自动大写等问题,并新增 CherryIN、ZenMux 供应商。
---
## 新功能
### S3 兼容云同步
云同步现在支持 S3 兼容对象存储作为 WebDAV 之外的第二套后端,签名采用自实现的 AWS Signature V4,以兼容尽可能多的服务。设置页提供 AWS S3、MinIO、Cloudflare R2、阿里云 OSS、腾讯云 COS、华为 OBS 以及自定义 endpoint 的一键预设,支持连接测试、手动上传 / 下载,以及在配置变更时自动同步(providers、endpoint、MCP、提示词、技能、设置、代理等配置表,**不含**用量日志这类高频写入数据)。开启 S3 同步会停用正在运行的 WebDAV 同步,反之亦然([#1351](https://github.com/farion1231/cc-switch/pull/1351))。
### OpenCode 会话用量同步
新增 OpenCode 作为用量统计来源,从 OpenCode 本地 SQLite 数据库读取每条消息的 token、成本和模型数据并导入用量记录,并提供独立的「OpenCode」应用筛选页签和「OpenCode Session」数据来源标签。数据库路径会遵循 `OPENCODE_DB``XDG_DATA_HOME`(在所有平台默认 `~/.local/share/opencode`),只导入已完成的消息,并在判断新鲜度时把 WAL 文件一并计入,避免刚写入的会话被跳过([#3215](https://github.com/farion1231/cc-switch/pull/3215))。
### 官方订阅额度模板
由于部分用户担心发起用量查询的 IP 和发起应用内请求的不一致导致封号风险,因此为 Claude / Codex / Gemini 官方供应商新增一个显式、可选的「官方订阅」用量模板,通过 CLI / OAuth 凭据查询套餐额度,替代此前对官方供应商的隐式自动查询。该模板默认关闭,需要在用量脚本弹窗里开启,并可配置刷新间隔。使用此功能建议开启代理的 TUN 模式。
### 文本模型图片回退整流器
新增一个代理整流器:当路由到的模型仅支持文本(显式声明,或由内置的模型名启发式判定),或上游拒绝图片输入时,会把 Anthropic 图片块替换为 `[Unsupported Image]` 占位标记,避免对话被中断。设置页提供该回退功能的开关,并单独提供一个开关控制启发式检测(可关闭以避免误判多模态模型)。
### ZenMux Token Plan 供应商
新增 ZenMux 作为 Token Plan 类的 Coding Plan 供应商,可在用量脚本弹窗里手动填写 API key 和 base URL,并以美元口径富展示已用 / 额度([#2709](https://github.com/farion1231/cc-switch/pull/2709))。
### CherryIN 预设
新增 CherryIN 聚合网关作为快捷配置预设,覆盖全部 7 个受管应用——Claude Code / Claude Desktop / OpenClaw / Hermes 使用 Anthropic 格式端点(open.cherryin.net),OpenCode 使用 `@ai-sdk/anthropic``/v1`),Codex 使用 OpenAI 兼容端点,Gemini CLI 使用 Gemini 兼容端点,附带官方品牌图标,位置紧挨 AiHubMix([#3643](https://github.com/farion1231/cc-switch/pull/3643))。
### Codex CLI 模型探活端点 `/v1/models`
本地代理现在会响应 Codex CLI 启动时探测的 `GET /v1/models`,返回 CC Switch 托管的 Codex 模型目录。同时加入了过期目录守卫:解析 live 的 `config.toml`,仅当 `model_catalog_json` 仍指向 CC Switch 持有的目录文件时才提供,避免把上一个供应商遗留的目录暴露给 Codex([#3818](https://github.com/farion1231/cc-switch/pull/3818))。
### Codex Chat 文件与音频附件
Codex 的 Responses→Chat 转换现在会把 `input_file`(携带 `file_id` 或内联 `file_data`)和 `input_audio` 内容部分映射为 Chat Completions 的对应形态,并补发此前会被丢弃的顶层 `input_*` 项,让文件和音频附件能够送达只支持 Chat 的 Codex 上游。
---
## 变更
### 用量看板 Hero 重新设计
把用量看板的 Hero 区与汇总卡片重排为更紧凑的布局,将真实 token 总量、请求数和成本合并到顶部一行展示([#3426](https://github.com/farion1231/cc-switch/pull/3426))。
### SSSAiCode 端点刷新
把 SSSAiCode 预设的官网、注册和 API base URL 更新到 `sssaicodeapi.com` 域名,并刷新其端点候选节点(默认 `node-hk.sssaicodeapi.com`,另含 `node-hk.sssaiapi.com``node-cf.sssaicodeapi.com`),覆盖全部 7 个应用预设。
---
## 修复
### Codex Chat 流式截断判定
当 Chat Completions 上游在没有 `finish_reason``[DONE]` 的情况下结束流时,CC Switch 不再把它当作正常完成:只有流真正结束才正常收尾;已产出部分内容时发出 incomplete(`max_output_tokens`)响应;完全没有产出时发出失败的 `stream_truncated` 事件。晚到的推理内容也会回填到仍在进行的流式工具调用上。
### Codex Chat 空 tools 下的 `tool_choice`
Responses→Chat 转换现在会在最终 tools 数组缺失或为空(包括所有工具被过滤掉)时一并丢弃 `tool_choice``parallel_tool_calls`,避免严格的 OpenAI 兼容上游(vLLM、企业网关)以"When using `tool_choice`, `tools` must be set."报 503/400[#3640](https://github.com/farion1231/cc-switch/pull/3640))。
### Codex 自定义工具元数据保留
自定义 Codex 工具(如自由格式的 `apply_patch` 工具)现在会把完整的原始定义——包括 format 和 grammar 元数据——以紧凑、顺序稳定的 JSON 块嵌入生成的 Chat 函数描述中,而不是替换成通用占位符,从而在 Chat Completions 上游上仍可正常使用([#3644](https://github.com/farion1231/cc-switch/pull/3644))。
### Codex Chat 用量缺少 `reasoning_tokens`
Chat→Responses 的用量转换现在总会包含 `output_tokens_details.reasoning_tokens`(默认 0),即使供应商省略 `completion_tokens_details` 或返回非对象也是如此,满足 Codex CLI 的严格要求,避免反复的响应解析失败和重试([#3514](https://github.com/farion1231/cc-switch/pull/3514))。
### Codex 自定义工具 / 搜索工具的跨轮推理
Codex Chat 历史里的跨轮推理缓存现在覆盖完整的工具调用集合(`function_call``custom_tool_call``tool_search_call`)及其输出,而不再仅限普通函数调用,因此 `apply_patch` 和工具搜索调用在通过 `previous_response_id` 恢复时能保留各自的 `reasoning_content`
### 临时端口(port 0)解析
当代理被配置为监听 0 端口(由系统分配)时,接管流程现在会先启动代理以拿到真实端口,再写入 live 配置和数据库,避免客户端 URL 指向无效的 `:0` 地址;若还没解析出具体端口,Claude Desktop 的网关 URL 会被直接拒绝。
### 代理占位符备份 / 恢复死循环
如果上一次停止代理时未能还原原始 live 配置、把代理占位符遗留在了 live 中,再次接管时不会再用代理配置覆盖掉正常备份,恢复时也不会把占位符写回 live:两条路径都会识别占位符状态并以当前供应商为真相来源重建 live,修复了代理开关变成空操作、客户端被钉死在本地代理地址的问题([#3689](https://github.com/farion1231/cc-switch/pull/3689))。
### 代理接管期间误拦截供应商切换
在本地路由接管期间,现在只有显式归类为官方的供应商会被禁止切换,而不会再把端点存在 meta 里、或字段尚未填写的自定义供应商一并禁用。被禁用的「启用」按钮现在以更轻量的提示气泡替代原先的红色「已拦截」标记。
### localhost 监听地址归一化
保存代理时如果监听地址填的是 `localhost`,现在会先归一化为 `127.0.0.1` 再持久化,避免绑定不一致([#3016](https://github.com/farion1231/cc-switch/pull/3016))。
### Anthropic `system` 消息归一化
对 Anthropic 格式的供应商,`messages` 数组里的 system 角色条目现在会被折叠并合并到顶层 `system` 字段(保留原顺序以及已有的顶层 system),避免严格上游拒绝非首位的 system 消息;OpenAI Chat 路由不受影响([#3775](https://github.com/farion1231/cc-switch/pull/3775))。
### Claude Desktop 1M 上下文模型路由
Claude Desktop 在 1M 上下文 beta 激活时会给模型名追加 `[1m]` 标记(如 `claude-opus-4-8[1m]`)。代理现在会在路由匹配前先剥掉该后缀,让精确、别名、旧名和角色关键词匹配都能正确命中,修复了对话中途切换到 1M 模型时的 `route_unknown`HTTP 400)失败;诊断用的 `route_unknown` 错误里仍保留原始模型名。
### Codex 413 错误文案
当 Codex 上游网关以 HTTP 413 拒绝过大的请求体时,代理现在返回专门的提示,说明这是供应商服务端的请求体大小限制(而非 CC Switch 本地限制),并给出可操作的恢复步骤(运行 `/compact`、移除大段日志或内联图片,或请供应商调高限制),不再原样回显上游的 HTML 错误页。
### 代理面板错误详情
切换代理接管失败时,代理面板的提示现在会带上后端返回的具体错误详情,而不是只显示一句笼统的失败信息([#3656](https://github.com/farion1231/cc-switch/pull/3656))。
### Copilot 无限空白检测阈值
把流式无限空白的中断阈值从 20 调高到 500 个连续空白字符,避免参数里含深层缩进代码(Python、YAML、Rust、Markdown)的正常工具调用被误判中断,同时仍能捕获真正的 Copilot 无限空白 bug[#2647](https://github.com/farion1231/cc-switch/pull/2647))。
### 订阅档位托盘渲染
通过统一的档位到标签映射,修复官方订阅档位在托盘和额度展示上的渲染问题:Claude / Codex 不再漏掉 7 天窗口,Gemini Pro / Flash / Flash-Lite 档位不再泄露原始机器名,多窗口套餐(如 Opus + Sonnet)现在按最差利用率展示而非取第一个匹配。
### Claude 流式 input_tokens 虚高
部分 Anthropic 兼容的流式供应商(如 Qwen、MiniMax)会在 `message_start` 里把完整上下文当作 `input_tokens` 上报,重复计入了已经单独统计的缓存部分,导致显示的缓存命中率被人为拉低。现在解析器会优先采用 `message_delta` 中更小的正 `input_tokens`,并采用同一 usage 块里配套的缓存计数;原生 Claude 和 OpenRouter 转换路径不变。
### 智谱配额查询端点路由
智谱 Coding Plan 的配额查询此前被硬编码到 `api.z.ai`,导致使用大陆预设(`open.bigmodel.cn`)的用户在国际端点不可达时查不到用量。现在配额请求会路由到与用户所配 base URL 匹配的主机([#3702](https://github.com/farion1231/cc-switch/pull/3702))。
### MiniMax 余额接口与定价
适配 MiniMax Coding Plan 配额的新余额接口(新接口返回剩余百分比字段,而非旧解析器依赖、会导致档位为空、托盘不再显示用量的用量计数),过滤掉非编程模型(如视频),兼容无周限额的套餐,并为 MiniMax M3 模型补充了默认定价([#3518](https://github.com/farion1231/cc-switch/pull/3518))。
### GLM Coding Plan 端点与模型拉取
把智谱 / Z.AI 的 GLM Coding Plan 预设修正到 `/api/coding/paas/v4` 端点(覆盖 Codex、OpenCode、OpenClaw、Hermes),并让模型列表探测对已经以 `/v{N}` 版本段结尾的 base URL 改为先查 `{base}/models`(保留 `/v1/models` 作为兜底),让「拉取模型」按钮不再在带版本号的端点上 404([#3524](https://github.com/farion1231/cc-switch/pull/3524))。
### Codex 模型目录路径可移植性
Codex 现在只把相对文件名 `cc-switch-model-catalog.json` 写入 `config.toml`,而不是绝对路径(Codex CLI 会从配置目录解析它),修复了在 WSL 和符号链接环境下绝对路径无法转换、导致模型目录失效的问题([#3614](https://github.com/farion1231/cc-switch/pull/3614))。
### APINebula 的 OpenCode SDK
APINebula 的 OpenCode 预设现在加载 `@ai-sdk/openai-compatible` 而非 `@ai-sdk/openai`,让请求使用该中转期望的 OpenAI Chat Completions 格式,而不是只支持 chat-completions 的上游会失败的 Responses API。
### Windows 退出后托盘图标残留
在 Windows 上退出 CC Switch 可能会留下一个失效的托盘图标,直到鼠标划过才消失。现在应用会在退出前显式移除托盘图标,让它随进程结束干净消失([#3797](https://github.com/farion1231/cc-switch/pull/3797))。
### Windows 任务栏图标
在运行时显式设置 Windows AppUserModelID,并给安装器生成的桌面和开始菜单快捷方式写入相同的 ID 和产品图标,让 CC Switch 在任务栏上显示正确图标并正确归组([#3457](https://github.com/farion1231/cc-switch/pull/3457))。
### Windows 子目录技能的更新检查
在 Windows 上扫描已安装技能时,把反斜杠路径分隔符归一化为正斜杠,让嵌套在子目录里的技能(如 `skills/my-skill`)能被更新检查匹配到,而不是被静默跳过([#3430](https://github.com/farion1231/cc-switch/pull/3430))。
### macOS 输入自动大写
为共享的文本 Input 组件关闭自动完成、自动纠错、自动大写和拼写检查,让 macOS 不再对配置字段里输入的首字母自动大写或自动纠正([#3626](https://github.com/farion1231/cc-switch/pull/3626))。
### Codex VS Code 会话预览
从 VS Code 发起的 Codex 请求,其会话预览在注入请求前存在 markdown 标题时,可能显示选区或打开文件的内容而非真实提示。现在后端标题和前端预览都会匹配最后一个「## My request for Codex:」标题(IDE 把真实请求作为最后一节注入),让预览反映用户的提示([#3593](https://github.com/farion1231/cc-switch/pull/3593))。
### 中文界面 VS Code 文案
把简体和繁体中文里「应用到 Claude Code 插件」的描述改为正确书写「VS Code」而非「Vscode」,与英文、日文文案对齐([#3228](https://github.com/farion1231/cc-switch/pull/3228))。
---
## 文档
### 用户手册刷新
刷新了 README 各语言版本以及 en / zh / ja 用户手册,使其反映全部 7 个受管应用(在介绍和总览文案里补上 Claude Desktop 与 Hermes),把 OpenCode 配置路径修正为 `~/.config/opencode/``opencode.json`),补充了 Hermes 配置文件说明,把语言文档更新为四种语言,订正各应用 MCP / 提示词 / 技能的支持情况,说明导出现在会生成带时间戳、含用量日志的 SQL 备份,并补充了定价模型 ID 匹配规则([#3411](https://github.com/farion1231/cc-switch/pull/3411))。
### Codex 官方认证保留指南
新增中 / 英 / 日三语指南,说明如何在把模型流量切到第三方 API 的同时,保留 Codex 官方远程操作和官方插件的可用性,并从 v3.16.1 release notes 链接到该指南。
### README 链接与赞助商标记
把各语言 README 里的 Release Notes 链接更新到 v3.16.1,并修复 README_ZH 赞助商区块里损坏的弯引号字符,让其 HTML 属性能正确渲染([#3772](https://github.com/farion1231/cc-switch/pull/3772))。
---
## 升级提醒
### S3 与 WebDAV 云同步互斥
云同步同一时间只会运行一套后端。开启 S3 自动同步会停用正在运行的 WebDAV 自动同步,反之亦然。如果你之前用的是 WebDAV,切到 S3 前请确认两端数据已对齐,避免误以为旧后端仍在备份。
### 修改模型映射后仍需重启 Codex
Codex 在启动时读取 `model_catalog_json`。即使本版已把模型目录改写为相对路径并新增了 `/v1/models` 探活端点,只要你修改了模型映射表,仍然需要重启 Codex 才能让 `/model` 菜单刷新。
---
## 风险提示
本版本继续沿用此前版本对反向代理类功能的风险提示。
**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#-风险提示)。
**Codex 第三方供应商 Chat 路由**:通过 CC Switch 本地代理把 Codex 请求转换并转发到第三方供应商时,各供应商对计费、合规与数据留存的约束不同,请在使用前阅读目标供应商的服务条款。
**Claude Desktop 第三方供应商代理切换**:通过 CC Switch 内置代理网关把 Claude Desktop 的请求转到第三方供应商时,同样需要遵守目标供应商的计费、合规与数据留存约束。
用户启用上述功能即表示自行承担相关风险。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
---
## 致谢
感谢以下贡献者在 v3.16.2 中提交的功能与修复:
- [#1351](https://github.com/farion1231/cc-switch/pull/1351):新增 S3 兼容云存储同步,感谢 @keithyt06
- [#3215](https://github.com/farion1231/cc-switch/pull/3215):新增 OpenCode 会话用量同步,感谢 @nothingness0db
- [#2709](https://github.com/farion1231/cc-switch/pull/2709):新增 ZenMux Token Plan 供应商,感谢 @Eter365
- [#3643](https://github.com/farion1231/cc-switch/pull/3643):新增 CherryIN 预设供应商,感谢 @zhibisora
- [#3818](https://github.com/farion1231/cc-switch/pull/3818):新增 Codex CLI 探活用的 `GET /v1/models` 端点,感谢 @CSberlin
- [#3426](https://github.com/farion1231/cc-switch/pull/3426):用量看板 Hero 重新设计,感谢 @allenxu09
- [#3640](https://github.com/farion1231/cc-switch/pull/3640):空 tools 时丢弃 `tool_choice`,感谢 @Postroggy
- [#3644](https://github.com/farion1231/cc-switch/pull/3644)Chat 路由保留 Codex 自定义工具元数据,感谢 @LanternCX
- [#3514](https://github.com/farion1231/cc-switch/pull/3514)Chat→Responses 始终包含 `reasoning_tokens`,感谢 @yeeyzy
- [#3689](https://github.com/farion1231/cc-switch/pull/3689):live 已是代理占位符时跳过备份 / 恢复,感谢 @YongmaoLuo
- [#3016](https://github.com/farion1231/cc-switch/pull/3016):归一化 localhost 监听地址,感谢 @Alexlangl
- [#3775](https://github.com/farion1231/cc-switch/pull/3775):规范化 Anthropic `system` 消息,感谢 @Dearli666
- [#3656](https://github.com/farion1231/cc-switch/pull/3656):改进代理面板错误信息展示,感谢 @lzcndm
- [#2647](https://github.com/farion1231/cc-switch/pull/2647):调高无限空白检测阈值 20 → 500,感谢 @NiuBlibing
- [#3702](https://github.com/farion1231/cc-switch/pull/3702):智谱配额查询按所配 base URL 路由,感谢 @YongmaoLuo
- [#3518](https://github.com/farion1231/cc-switch/pull/3518):适配 MiniMax 余额查询新接口与默认定价,感谢 @LaoYueHanNi
- [#3524](https://github.com/farion1231/cc-switch/pull/3524):修复智谱 Coding Plan 预设与带版本号端点的模型探测,感谢 @makoMakoGo
- [#3614](https://github.com/farion1231/cc-switch/pull/3614):模型目录改用相对文件名,感谢 @steponeerror
- [#3797](https://github.com/farion1231/cc-switch/pull/3797):修复 Windows 退出后托盘图标残留,感谢 @iAJue
- [#3457](https://github.com/farion1231/cc-switch/pull/3457):修复 Windows 任务栏图标,感谢 @ZhangNanNan1018
- [#3430](https://github.com/farion1231/cc-switch/pull/3430):归一化 Windows 路径分隔符以匹配子目录技能更新,感谢 @Ninthless
- [#3626](https://github.com/farion1231/cc-switch/pull/3626):关闭 macOS 输入框自动大写,感谢 @ZHLHZHU
- [#3593](https://github.com/farion1231/cc-switch/pull/3593):修复 Codex VS Code 会话预览,感谢 @xwil1
- [#3228](https://github.com/farion1231/cc-switch/pull/3228):对齐中文界面 VS Code 文案,感谢 @Games55k
- [#3411](https://github.com/farion1231/cc-switch/pull/3411):刷新用户手册以反映当前应用支持,感谢 @makoMakoGo
- [#3772](https://github.com/farion1231/cc-switch/pull/3772):修复 README release note 链接与赞助商标记,感谢 @null-easy。
也感谢所有在 v3.16.1 发布后反馈 Codex Chat 路由、本地代理接管、用量统计和平台兼容性问题的用户,很多补丁都来自这些真实使用场景里的复现线索。
---
## 下载与安装
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
### 系统要求
| 系统 | 最低版本 | 架构 |
| ------- | -------------------------- | ----------------------------------- |
| Windows | Windows 10 及以上 | x64 |
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 见下表 | x64 / ARM64 |
### Windows
| 文件 | 说明 |
| ---------------------------------------- | ----------------------------------- |
| `CC-Switch-v3.16.2-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
| `CC-Switch-v3.16.2-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
### macOS
| 文件 | 说明 |
| -------------------------------- | --------------------------------------------- |
| `CC-Switch-v3.16.2-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
| `CC-Switch-v3.16.2-macOS.zip` | 解压后拖入 ApplicationsUniversal Binary |
| `CC-Switch-v3.16.2-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
Homebrew 安装:
```bash
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
Linux 资产同时提供 **x86_64****ARM64**`aarch64`)两种架构。资产文件名中包含架构标识,请按你机器的 `uname -m` 输出选择对应版本:
- `CC-Switch-v3.16.2-Linux-x86_64.AppImage` / `.deb` / `.rpm`
- `CC-Switch-v3.16.2-Linux-arm64.AppImage` / `.deb` / `.rpm`
| 发行版 | 推荐格式 | 安装方式 |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| 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` |
+339
View File
@@ -0,0 +1,339 @@
# CC Switch v3.16.3
> 🎉 **CC Switch has passed 100,000 Stars!**
> Thank you to every user, contributor, and Star — you are the reason it has come this far. 🙏
> 💎 **This release was developed with help from the Claude Fable 5 model** — it helped untangle several critical, error-prone pieces of logic: the attribution chain that bills route-takeover traffic by the real upstream model, the metering and de-duplication of cache tokens on format-conversion paths, the in-app update restart deadlock, and the migration / restore invariants of Codex unified session history. This is also why this release adds a **Fable 5 Verified** badge to the About page.
> After v3.16.2 broadened data portability and usage observability, this release puts the focus on "making usage billing truly accurate" — billing by the real upstream model, fixing cache double-counting on format-conversion paths, counting Claude Code Workflow sub-agent usage (schema v11), and a round of redesign for the usage dashboard (dashboard-wide provider / model filters, a brand-icon toolbar, and more resilient quota queries) — while also hardening a batch of local proxy and platform issues, adding a custom User-Agent override, a Codex unified session history toggle, and a Claude Fable 5 tier.
**[中文版 →](v3.16.3-zh.md) | [日本語版 →](v3.16.3-ja.md)**
---
## Usage Guides
This release changes how usage is counted and reworks the dashboard quite a bit, so it is worth starting here:
- **[Usage Statistics](../user-manual/en/4-proxy/4.4-usage.md)**: understand the Usage Dashboard's data sources (proxy logs, session sync) and how the statistics are counted. This release adds dashboard-wide provider / model filters and surfaces the real pricing model for route-takeover traffic.
- **[Settings](../user-manual/en/1-getting-started/1.5-settings.md)**: the custom User-Agent override, the Codex unified session history toggle, and other switches live in the provider form's advanced options and on the settings page.
---
> [!WARNING]
>
> ## Only Official Channels (Please Read)
>
> CC Switch is a **fully free and open-source** desktop app, and we **do not charge users any fees**. Please only obtain the software through the official channels listed below:
>
> | Channel | Only Official |
> | ------------------ | ------------------------------------------------------------------------------ |
> | Website | **[ccswitch.io](https://ccswitch.io)** |
> | Source | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
> | Downloads | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
> | Author | **[@farion1231](https://github.com/farion1231)** |
> | Report an Imposter | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
>
> **Any "CC Switch" website or client that asks you for payment, top-ups, or login credentials is fake.** If you have been tricked into paying, stop the transaction immediately and file a report through GitHub Issues.
---
## Overview
CC Switch v3.16.3 is a maintenance update following v3.16.2. After the previous release concentrated on broadening data portability and usage observability, this release puts the focus on "making usage billing truly accurate" — billing by the real upstream model rather than whatever the upstream echoes back, fixing the cache-token double-counting on format-conversion paths (Chat / Responses / Gemini converted to Anthropic), folding Claude Code Workflow sub-agent usage into the local statistics, and persisting the actual pricing basis used by each record as schema v11. The usage dashboard was reworked along with it, adding dashboard-wide provider / model filters, a brand-icon toolbar, and more resilient quota queries (retry on failure plus keeping the last successful result).
In addition, this release hardens a batch of local proxy robustness issues (aggregating SSE responses returned under a mislabeled Content-Type, Codex `/responses` image rectification for text-only models, recovery of Codex OAuth credentials and takeover residue, duplicate YAML keys in Hermes config), reworks the provider configuration experience (a custom User-Agent override, a unified Codex advanced section, searchable and sortable presets, a Claude Fable 5 tier), adds a Codex unified session history toggle, and fixes the in-app update hang, the Codex upgrade that broke the install, duplicate macOS terminal windows, and more.
**Release date**: 2026-06-14
**Stats**: 59 commits | 130 files changed | +10,223 / -4,232 lines
---
## Highlights
- **More accurate usage billing**: route-takeover traffic is now billed by the real upstream model (not the alias the upstream echoes back), format-conversion paths no longer count cache tokens into input twice, and Claude Code Workflow sub-agent usage is now counted — with the pricing basis persisted as schema v11.
- **Usage dashboard redesign**: provider / model filters are promoted from inside the request-log table up to dashboard-wide filters, the app filter switches to brand icons, and quota queries gain retry-on-failure plus "keep the last successful result" so a single network blip no longer turns cards red.
- **Custom User-Agent override**: providers can set a custom UA that applies consistently across forwarding, connectivity detection, and model listing, getting past coding-plan upstreams that gate on a UA whitelist (which is how the Codex "Kimi For Coding" preset was restored).
- **Codex unified session history**: a new opt-in toggle lets official Codex sessions share a single resume-history bucket with third-party sessions, with optional migration of existing sessions and precise ledger-based restore.
- **Proxy and platform hardening**: aggregating mislabeled SSE responses, Codex image rectification, takeover-residue recovery, Hermes YAML de-duplication; in-app updates no longer hang on "restarting", and Codex upgrades no longer break the install.
---
## Added
### Custom User-Agent Override
Provider configs can now set a custom User-Agent that the proxy applies consistently across request forwarding, stream check, and model listing (`GET /v1/models`), so coding-plan upstreams that gate on UA no longer fail detection or return 403 while the proxy itself works. The Claude and Codex forms expose it in advanced settings with a curated presets dropdown (Claude Code / Kilo Code families that pass UA whitelists) and live non-blocking validation; stale custom UAs are dropped when switching to an official preset to avoid silently altering headers (#3671).
### Unified Codex Session History
Official Codex sessions can now share a single resume-history bucket with cc-switch third-party sessions via an opt-in toggle under Settings → Codex App Enhancements, so the resume picker no longer hides them from each other. When enabled, the live `config.toml` routes official runs through a shared `custom` model_provider that mirrors the built-in OpenAI provider (`auth.json` is untouched); the toggle is forward-only by default but the enable dialog offers a checkbox to migrate existing official sessions (with per-generation backups), and the disable dialog offers a precise ledger-based restore that only reverts sessions originally recorded as `openai` while leaving sessions created during the toggle untouched.
### Dashboard-Wide Provider / Model Filters
The provider and model filters move from inside the request-log table up to the top bar, applying globally to the hero summary, trend chart, request logs, and both stats tabs so you can scope the whole dashboard to a given source and model. Sources match by exact display name (so session placeholder rows like "Claude (Session)" are selectable) and models match by effective pricing model, with the model dropdown cascading from the selected source and both lists showing only options that have data in the current range.
### Refreshed Model Pricing Seed
Added pricing for 9 models including Claude Fable 5, Grok 4.3, Mistral Medium 3.5 / Small 4, and Qwen 3.7 Max/Plus, and corrected 28 existing prices against current official vendor list pricing (GLM, Grok, MiMo, Doubao, Kimi, MiniMax, Mistral, Qwen) so usage cost estimates are accurate. Each change updates the seed for fresh installs and adds a guarded repair for existing databases without clobbering user-edited rows.
### Claude Fable 5 Model Tier
Provider forms now expose `claude-fable-5` as a fourth model-mapping tier on both the Claude Code and Claude Desktop proxy paths, with a fable → opus → default fallback mirroring the official downgrade and the `fable-` prefix whitelisted for the Desktop 1.12603.1+ validator. A clarified four-language fallback hint warns that leaving a tier blank on third-party endpoints forwards the literal model name and 404s (#3980, #4026, #4049).
### Unity2.ai Partner Provider
Added Unity2.ai, an AI API relay partner, as a preset across all seven managed apps (Claude Code, Codex, Gemini, OpenCode, OpenClaw, Claude Desktop, Hermes), each carrying the referral signup link and partner promotion copy in all four locales. Codex uses the bare base URL (the gateway exposes `/responses` at root) while OpenCode / OpenClaw / Hermes use the `/v1` chat-completions endpoint with `gpt-5.5`.
### Kimi K2.7 Code Model
Added the `kimi-k2.7-code` model (in $0.95 / out $4.00 / cache-read $0.19 per 1M tokens, 256K context) and pointed all six official Moonshot Kimi presets (Claude Code, Codex, Claude Desktop, Hermes, OpenCode, OpenClaw) at it, renaming the OpenCode / OpenClaw presets to "Kimi K2.7 Code". The pricing seed applies on startup via the idempotent insert path, so existing users pick up the new pricing without a migration.
### Codex "Kimi For Coding" Preset Restored
Re-added the Codex "Kimi For Coding" preset (`openai_chat`, `kimi-for-coding`, 256K context) with thinking mode enabled by default; it was previously removed because the coding endpoint rejects Codex's default `codex-cli` User-Agent with 403. It now works via proxy takeover combined with the custom User-Agent override (set to a whitelisted UA such as `claude-cli/*`).
### Pricing-Model Audit in Request Detail
The request detail panel now shows the requested model and the pricing model when they differ from the response model, making route-takeover bills auditable directly from the usage UI.
### Preset Provider Search & Sorting
The provider preset selector gains a searchable, sorted list with an inline search box (toggled via a magnifier icon, dismissed on ESC or outside click). Buttons use a responsive grid with consistent sizing and default icons, and search matches only provider display/raw names so URL fragments and shared category labels no longer produce noisy matches (#3975, #4183).
### Claude Mythos 5 Pricing
Registered the `claude-mythos-5` model in the bundled model/pricing table (in $10 / out $50 per 1M tokens, cache read $1.00, cache write $12.50), so usage metering prices and displays it correctly (#4077).
### Fable 5 Verified Banner
The Settings About page now displays a Fable 5 Verified banner beside the app name and version, marking this as a special build, with the version badge centered under the app name.
---
## Changed
### Claude Desktop Usage Folded Into Claude
The dashboard no longer shows a standalone "Claude Desktop" bucket, which only ever displayed a partial number (Desktop chat usage never passes through the proxy and its Code-tab sessions write into the shared `~/.claude/projects` tree). Desktop proxy traffic is now folded into the `claude` view for display while still recorded under its own `app_type` for route-takeover billing audit, with the real value visible in the request detail panel.
### Lightweight Provider Health Check
The provider health check no longer sends a real streaming model request (which many third-party providers blocked with 401/403/WAF, causing false negatives); it now performs a lightweight HTTP reachability probe of the provider `base_url`, treating any HTTP response as reachable and counting only DNS/connect/TLS/timeout as failure. The connectivity button is hidden for official providers (which use OAuth with an empty base URL and no reliable reachability target), the real-request confirmation dialog and test model/prompt fields are removed, and the degraded-latency threshold is set to 6s with an 8s timeout. The reachability check never resets the circuit breaker, so failover detection stays driven solely by real proxy traffic.
### Codex Advanced Options Section
The Codex provider form now folds local routing, model mapping, reasoning overrides, and custom User-Agent into a single collapsible advanced section mirroring the Claude form (auto-expanding when a UA is set or local routing is on). Custom User-Agent is now also configurable for native Responses providers, where it was previously reachable only with `openai_chat` routing enabled.
### Usage Toolbar Refresh and Layout
The app filter now renders brand icons (via ProviderIcon, with a grid icon for "All") instead of text tabs that wrapped awkwardly in narrow windows, and the usage hero shows the selected app's brand icon with Codex recolored to a neutral gray matching OpenAI's monochrome branding. The click-to-cycle refresh button becomes a Select with a localized "off" label, and the top-bar controls are compacted and aligned into consistent width groups with truncated long date-range labels.
### Faster About Panel Loading
The Settings About panel now loads progressively: the app version badge appears the instant it resolves instead of waiting for tool probes, each tool card updates the moment its own version check finishes (probes run concurrently rather than sequentially), and results are cached for the app session with a 10-minute TTL so reopening the About tab reuses cached values and revalidates stale ones in the background instead of re-probing all six tools every time.
### Volcengine Ark Coding Plan Promo
Updated the Volcengine Ark preset across all six apps with the new Coding Plan invite link (replacing the old Agent Plan / activity links) and refreshed the partner promotion copy in all four locales (two-month 75% off plus invite code 6J6FV5N2), correcting the product name from Agent Plan to Coding Plan.
### MiniMax Demoted to Regular Provider
Removed the gold partner star badge and the API-key promotion banner for MiniMax by dropping the `isPartner` flag from all its presets; it stays as a regular `cn_official` provider keeping its icon and theme. The promotion copy is kept dormant so the partnership can be re-enabled with a single line.
### LemonData Removed, SudoCode Demoted
Removed the LemonData provider preset entirely from all apps along with its promotion copy, icons, and sponsor listings, and demoted SudoCode from a partner to a regular `third_party` provider by dropping its `isPartner` flag and promotion copy (it keeps its icon).
### AtlasCloud Codex GLM 5.1 Context Window
Declared the 200,000-token context window for the `zai-org/glm-5.1` model in the AtlasCloud Codex preset, matching the other GLM 5.1 preset entries.
---
## Fixed
### Route-Takeover Traffic Billed by the Real Upstream Model
When a request was routed to a different upstream (env model mapping, Claude Desktop routes, Copilot normalization, Codex chat override), the proxy used to attribute and price usage by whatever model the upstream echoed back, recording kimi/glm tokens as `claude-*` and overstating cost roughly 525×. The forwarder now captures the real outbound model, attributes usage by upstream-echo then outbound then client alias, persists the actual pricing basis on every row (schema v11), and keeps that basis through cost backfill and 30-day rollup pruning; Claude Desktop traffic is now logged under its own `app_type` so its pricing overrides apply.
### Usage Metering on Format-Conversion Proxy Paths
Audited and fixed token/cache accounting across the proxy's format-conversion paths (Chat, Responses, and Gemini converted to Anthropic). The proxy now records the actually returned model, injects `stream_options.include_usage` so OpenAI-compatible upstreams emit usage in streaming, excludes `cache_read` and `cache_creation` from input on Claude←OpenAI paths to stop double-billing cache tokens, subtracts cached Gemini prompt tokens, still records fully-cached requests, and skips synthetic all-zero usage that previously inflated request counts (#2774).
### In-App Update No Longer Hangs on Restart
Installing an update from within the app no longer freezes on the "restarting" screen, leaving the new version installed but requiring a manual force-quit. The download-install-restart chain now runs entirely in the backend (a new `install_update_and_restart` command) with platform-aware install ordering and single-instance-lock teardown before re-exec, instead of depending on the old WebView to keep running JS after the app bundle was already swapped; exit requests are also classified so restart requests fall through to Tauri's default flow rather than deadlocking on the window-state plugin mutex (#4069, #4074).
### Codex Upgrade No Longer Breaks the Install
Upgrading Codex from the Settings "About" tab no longer leaves it throwing "Missing optional dependency @openai/codex-…" errors. The upgrade chain previously ran `codex update` first, which on an npm install is a bare reinstall that reports success even when the per-platform binary fails to land; Codex is now removed from the self-update-first path and a runnable check triggers an uninstall+reinstall self-heal (scoped to npm-managed installs) that actually re-lands the missing platform binary.
### Codex OAuth Auth Token Preserved on Proxy Takeover
Enabling proxy takeover for a Codex provider no longer strips the `ANTHROPIC_AUTH_TOKEN` placeholder, which previously broke Claude Code's login on hot-switches, fresh installs, and configs already stripped by older releases. The placeholder is now injected unconditionally for managed (non-Copilot) Codex providers, including URL-only ones; GitHub Copilot behavior (API_KEY only) is unchanged (#3789, #3784).
### Takeover-Residue Recovery Across Config-Dir Switches
Restarting the app after changing the config directory while proxy takeover is active no longer leaves Claude/Codex/Gemini pointed at a dead local proxy. The old instance now restores the taken-over live files before restarting, the first-run import refuses to persist a takeover placeholder as a provider, and SSOT restore validates that the current provider's config is free of placeholders before writing it back (#4076).
### Mislabeled SSE Bodies in Format-Transform Fallback
Requests routed through Claude/Codex format conversion no longer fail with an opaque 422 "Failed to parse upstream response" when a MaaS gateway force-streams a `stream:false` request and returns an SSE body under a non-SSE Content-Type. The proxy now sniffs for SSE on parse failure, aggregates the chunks into a single JSON, and runs the existing converter so clients still get a valid non-stream response; remaining parse failures are enriched with content-type, encoding, and body-snippet diagnostics, and deflate decoding now tries zlib before raw (#2234).
### Duplicate YAML Keys in Hermes Config
Hermes config writes no longer accumulate duplicate top-level keys (e.g. `mcp_servers`) that caused "Failed to parse Hermes config as YAML: duplicate entry with key" errors. Section replacement now strips all stale occurrences from the remainder instead of degrading into appends, the dedup safety net handles both LF and CRLF line endings, and healing keeps the last (newest) occurrence to match Hermes's own last-wins PyYAML semantics (#3267, #3633, #2973, #2529, #3310, #3762).
### Usage Query Resilience and Error Clarity
Usage cards no longer flip to red on a single transient blip: queries now retry once and keep showing the last successful result for up to 10 minutes on network/timeout/5xx failures, while deterministic failures (auth, empty key, unknown provider, 4xx) surface immediately and clear the snapshot so a stale quota can't resurface after credentials change. Native balance/coding-plan/subscription timeouts were raised from 10s to 15s for slow cross-border endpoints, and coding-plan now returns explicit "API key is empty" / "Unknown coding plan provider" errors instead of a blank failure.
### Usage Script Provider Credential Resolution
Custom JS-script usage queries resolved `{{apiKey}}` / `{{baseUrl}}` by guessing env fields only, so providers that store credentials elsewhere (e.g. Codex's `auth.OPENAI_API_KEY` plus `config.toml` base_url) always got empty values and failed despite being fully configured. Script queries and the test/preview now reuse the same per-app credential resolver as the native balance path, with explicit non-empty script values still taking precedence (#1479).
### Claude Code Workflow Sub-Agent Usage Counted
Local (no-proxy) session-log usage accounting missed Claude Code Workflow sub-agent traffic, under-counting overall usage by roughly 4.1% (concentrated in workflow/subagent transcripts). The scanner now descends into the deeper `subagents/workflows/wf_*/` transcript directories, and the parser no longer drops billable assistant messages that lack a `stop_reason` but already incurred input/cache token cost; dedup is unchanged so no usage is double-counted.
### Codex Image Rectifier for /responses Text-Only Upstreams
Codex `/responses` requests carrying images and routed to text-only OpenAI-chat models (e.g. DeepSeek `deepseek-v4-flash`) no longer fail with HTTP 400 "unknown variant `image_url`". The media rectifier now also covers the Codex adapter, scanning the responses `input` for `input_image` blocks so it can proactively strip images for known text-only models and reactively retry with images replaced on upstream image-unsupported errors.
### Zhipu Coding-Plan Quota Window Mislabeling
The Zhipu coding-plan view no longer swaps the 5-hour and weekly quota buckets in the final hours of each weekly cycle. The two windows are now classified by the explicit `unit` field (3 = 5-hour, 6 = weekly) instead of by sorting reset-time ascending, which mislabeled them exactly when users check their weekly quota most; the old reset-time heuristic remains as a fallback (#3036).
### Duplicate Provider Terminal Sessions on macOS
Launching a provider terminal on macOS no longer opens an extra empty window alongside the command session; Terminal.app uses `launch` (not `activate`) on cold start and Ghostty uses an initial-command so a single session opens, with a fallback retained if the AppleScript path fails (#4156).
### Claude Desktop Model-Mapping Placeholders
The Claude Desktop model-mapping form previously showed mismatched example brands across the menu display name and request model columns (DeepSeek vs Kimi), implying a display name maps to an unrelated model. Both placeholders are now derived from each row's role so they stay brand-consistent, with the lightweight Haiku tier using a flash example.
### Popovers Behind Fullscreen Panels
Popovers and tooltips such as the provider preset search no longer render behind fullscreen panels and appear unresponsive on click; their z-index is raised above the fullscreen overlay while staying below modal dialogs.
### ToggleRow Icon Shrinking
Toggle row icons no longer shrink or distort when paired with long descriptions, keeping the icon at a fixed size next to multi-line text.
---
## Documentation
### Release Notes Contributor Mentions
Restored contributor mentions in the v3.16.1 and v3.16.2 release notes across all three locales.
---
## Upgrade Notes
### Pricing Database schema v11 Auto-Migration
This release adds a `pricing_model` column to `proxy_request_logs` and rebuilds the rollup by `request_model` + `pricing_model`, migrating automatically on startup with no manual action required. Historical rows have their cost frozen at write time and are not recalculated (rows with `app_type="claude"` mix native and converted sources); only real but previously un-priced takeover rows stay at zero cost until pricing is supplied and then backfilled.
### Model Mapping Adds a Fourth Tier (Fable 5)
The Claude Code and Claude Desktop model mappings now have four tiers (Sonnet / Opus / Fable / Haiku). Older three-tier providers pick up the `claude-fable-5` tier after being reopened and saved; leaving that tier blank means it inherits Sonnet. Note: leaving any tier blank on third-party endpoints forwards the literal model name of that tier and may 404, so fill it in as needed.
### The "Kimi For Coding" Preset Needs Proxy Takeover + a Whitelisted UA
The restored Codex "Kimi For Coding" preset is still rejected with 403 if used with the default `codex-cli` User-Agent. To use it, enable proxy takeover and set the custom User-Agent in the provider's advanced options to a whitelisted UA (such as `claude-cli/*`).
### Provider Health Check Semantics Changed
The health check changed from "send a real model request" to "HTTP reachability probe". Note that reachable ≠ usable: a host that returns 403 is reachable but may be broken for real traffic. Failover decisions remain driven solely by real proxy traffic and are unaffected by the health check.
---
## Risk Notice
This release continues the risk notices from previous versions for reverse-proxy-style features.
**Codex OAuth reverse proxy**: using a ChatGPT subscription's Codex OAuth through a reverse proxy may violate OpenAI's terms of service. See the [v3.13.0 release notes](v3.13.0-en.md#-risk-notice) for details.
**Codex third-party provider Chat routing**: when CC Switch local proxy converts and forwards Codex requests to third-party providers, each provider may have different requirements for billing, compliance, and data retention. Read the target provider's terms before use.
**Claude Desktop third-party provider proxy switching**: when CC Switch's built-in proxy gateway forwards Claude Desktop requests to third-party providers, you must also follow the target provider's billing, compliance, and data-retention terms.
By enabling these features, users accept the related risks. CC Switch is not responsible for account restrictions, warnings, or service suspensions caused by using these features.
---
## Thanks
Thanks to the following contributors for the features and fixes in v3.16.3:
- [#3789](https://github.com/farion1231/cc-switch/pull/3789): preserve Codex OAuth auth token on takeover, thanks @codeasier.
- [#2774](https://github.com/farion1231/cc-switch/pull/2774): fix model / input-token recording on Completions→Anthropic, thanks @LaoYueHanNi.
- [#4069](https://github.com/farion1231/cc-switch/pull/4069): fix the deadlock on relaunch after an in-app update, thanks @thisTom.
- [#4156](https://github.com/farion1231/cc-switch/pull/4156): fix duplicate provider terminal sessions on macOS, thanks @thisTom.
- [#3267](https://github.com/farion1231/cc-switch/pull/3267): fix duplicate YAML keys in the Hermes config, thanks @que3sui.
- [#1479](https://github.com/farion1231/cc-switch/pull/1479): fix usage script provider credential resolution, thanks @pa001024.
- [#3975](https://github.com/farion1231/cc-switch/pull/3975): add preset search and sorting, thanks @Nastem.
- [#4183](https://github.com/farion1231/cc-switch/pull/4183): adjust the preset-provider button appearance and search-box position, thanks @WangJiati.
- [#4077](https://github.com/farion1231/cc-switch/pull/4077): add claude-mythos-5 model pricing, thanks @osscv.
Thanks also to everyone who reported usage billing, local proxy robustness, Codex upgrade, and platform compatibility issues after v3.16.2. Many of these fixes came directly from real-world reproduction details.
---
## Download & Install
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) and download the build for your system.
### System Requirements
| System | Minimum Version | Architecture |
| ------- | ------------------------ | ----------------------------------- |
| Windows | Windows 10 and later | x64 |
| macOS | macOS 12 (Monterey)+ | Intel (x64) / Apple Silicon (arm64) |
| Linux | See table below | x64 / ARM64 |
### Windows
| File | Description |
| ---------------------------------------- | ------------------------------------------------ |
| `CC-Switch-v3.16.3-Windows.msi` | **Recommended** - MSI installer with auto-update |
| `CC-Switch-v3.16.3-Windows-Portable.zip` | Portable build, unzip and run |
### macOS
| File | Description |
| -------------------------------- | ----------------------------------------------------- |
| `CC-Switch-v3.16.3-macOS.dmg` | **Recommended** - DMG installer, drag to Applications |
| `CC-Switch-v3.16.3-macOS.zip` | Unzip and drag to Applications, Universal Binary |
| `CC-Switch-v3.16.3-macOS.tar.gz` | For Homebrew install and auto-update |
Homebrew install:
```bash
brew install --cask cc-switch
```
Upgrade:
```bash
brew upgrade --cask cc-switch
```
### Linux
Linux assets are available for both **x86_64** and **ARM64** (`aarch64`). Choose the file whose architecture tag matches your machine's `uname -m` output:
- `CC-Switch-v3.16.3-Linux-x86_64.AppImage` / `.deb` / `.rpm`
- `CC-Switch-v3.16.3-Linux-arm64.AppImage` / `.deb` / `.rpm`
| Distribution | Recommended Format | Install Command |
| --------------------------------------- | ------------------ | --------------------------------------------------------------------- |
| 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` | Make executable and run directly, or use AUR |
| Other distributions / unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+339
View File
@@ -0,0 +1,339 @@
# CC Switch v3.16.3
> 🎉 **CC Switch が 100,000 Star を突破しました!**
> すべてのユーザー・コントリビューター・Star をくださった方々に感謝します —— 皆さんのおかげでここまで来ました。🙏
> 💎 **本リリースは Claude Fable 5 モデルの協力のもとで開発されました**——重要かつ間違えやすいロジックの整理を手伝ってくれました: ルーティングテイクオーバー時に本物の上流モデルで課金する帰属チェーン、形式変換経路でのキャッシュ token の計上と重複排除、アプリ内更新の再起動デッドロック、そして Codex 統一セッション履歴の移行 / 復元の不変条件です。本リリースの「バージョン情報」ページに **Fable 5 Verified** バッジを新設したのもこのためです。
> v3.16.2 でデータの可搬性と使用量の可観測性を広げたのに続き、本リリースは「使用量の課金を本当に正確にする」ことに重きを置いています——本物の上流モデルで課金し、形式変換経路でのキャッシュの二重計上を修正し、Claude Code Workflow のサブ agent の使用量を統計に取り込み(schema v11)、使用量ダッシュボードを一通り刷新しました(全体に効くプロバイダー / モデルフィルタ、ブランドアイコンのツールバー、より安定した残量照会)。あわせて一連のローカルプロキシとプラットフォームの問題を補強し、カスタム User-Agent オーバーライド、Codex 統一セッション履歴のトグル、Claude Fable 5 階層を新設しました。
**[English →](v3.16.3-en.md) | [中文版 →](v3.16.3-zh.md)**
---
## 利用ガイド
本リリースでは使用量統計の数え方とダッシュボードに多くの調整を加えたため、まず以下をご覧ください:
- **[使用量統計](../user-manual/ja/4-proxy/4.4-usage.md)**: 使用量ダッシュボードのデータソース(プロキシログ、セッション同期)と集計の仕組みを確認できます。本リリースで全体に効くプロバイダー / モデルフィルタを追加し、ルーティングテイクオーバー時の本物の課金モデルを表示するようにしました。
- **[設定](../user-manual/ja/1-getting-started/1.5-settings.md)**: カスタム User-Agent オーバーライド、Codex 統一セッション履歴などのトグルは、プロバイダーフォームの高度なオプションと設定ページにあります。
---
> [!WARNING]
>
> ## 唯一の公式チャネル(必ずお読みください)
>
> CC Switch は**完全に無料・オープンソース**のデスクトップアプリで、**ユーザーから料金を徴収することはありません**。本ソフトウェアは下記の公式チャネルからのみ入手してください:
>
> | チャネル | 唯一の公式 |
> | ------------ | ------------------------------------------------------------------------------ |
> | 公式サイト | **[ccswitch.io](https://ccswitch.io)** |
> | ソースコード | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
> | ダウンロード | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
> | 偽サイト通報 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
>
> **料金請求・チャージ・認証情報の提供を求める「CC Switch」サイトやクライアントはすべて偽物です。** 支払いを誘導された場合は直ちに操作を中止し、GitHub Issues からご報告ください。
---
## 概要
CC Switch v3.16.3 は v3.16.2 に続くメンテナンスアップデートです。前リリースではデータの可搬性と使用量の可観測性の拡張に集中しましたが、本リリースは「使用量の課金を本当に正確にする」ことに重きを置いています——上流が返すエイリアスではなく本物の上流モデルで課金し、形式変換(Chat / Responses / Gemini を Anthropic へ)経路でのキャッシュ token の二重計上を修正し、Claude Code Workflow のサブ agent の使用量をローカル統計に取り込み、schema v11 で各レコードが実際に使用した課金根拠を永続化しました。使用量ダッシュボードもこれにあわせて一通り刷新し、全体に効くプロバイダー / モデルフィルタ、ブランドアイコンのツールバー、より安定した残量照会(失敗時の再試行 + 前回成功した結果の保持)を追加しました。
さらに本リリースでは、一連のローカルプロキシの堅牢性に関する問題(Content-Type が誤ってラベル付けされた SSE レスポンスの集約、Codex `/responses` のテキスト専用モデル向け画像整流、Codex OAuth 認証情報とテイクオーバー残留の復元、Hermes 設定の重複 YAML キー)を補強し、プロバイダー設定まわりを作り直し(カスタム User-Agent オーバーライド、Codex フォームの高度なオプションへの統合、プリセット検索とソート、Claude Fable 5 階層)、Codex 統一セッション履歴のトグルを新設し、アプリ内更新のハング、Codex のアップグレードによるインストール破損、macOS の重複ターミナルウィンドウなどの問題を修正しました。
**リリース日**: 2026-06-14
**Stats**: 59 commits | 130 files changed | +10,223 / -4,232 lines
---
## ハイライト
- **使用量の課金がより正確に**: ルーティングテイクオーバーのトラフィックを本物の上流モデルで課金するようになり(上流が返すエイリアスではなく)、形式変換経路でキャッシュ token を input に二重計上しなくなり、Claude Code Workflow のサブ agent の使用量も統計に取り込みました——schema v11 で課金根拠を永続化します。
- **使用量ダッシュボードの刷新**: プロバイダー / モデルフィルタをリクエストログテーブルから全体フィルタへ引き上げ、アプリフィルタをブランドアイコンに変更し、残量照会に失敗時の再試行と「前回成功した結果の保持」を追加して、一度のネットワークのゆらぎでカードが赤くならないようにしました。
- **カスタム User-Agent オーバーライド**: プロバイダーにカスタム UA を設定でき、転送・接続性チェック・モデル一覧の 3 か所で一貫して有効になり、UA ホワイトリストで制限する Coding Plan 上流を通過できます(これにより Codex「Kimi For Coding」プリセットを復活させました)。
- **Codex 統一セッション履歴**: 公式 Codex セッションとサードパーティセッションが同じ resume 履歴バケットを共有できる任意のトグルを新設し、既存セッションの任意移行と台帳に基づく精密な復元を備えます。
- **プロキシとプラットフォームの補強**: 誤ラベルの SSE レスポンスの集約、Codex 画像整流、テイクオーバー残留の復元、Hermes YAML 重複排除。アプリ内更新が「再起動中」でハングしなくなり、Codex のアップグレードでインストールを壊さなくなりました。
---
## 追加機能
### カスタム User-Agent オーバーライド
プロバイダー設定でカスタム User-Agent を設定できるようになり、プロキシがリクエスト転送、接続性チェック、モデル一覧(`GET /v1/models`)の 3 つの経路で一貫して適用します。これにより、UA ホワイトリストで制限する Coding Plan 上流で「検出は失敗 / モデル一覧は 403 なのにプロキシ本体は正常に動く」という不整合が起きなくなります。Claude と Codex のフォームはいずれも高度なオプションでこのフィールドを公開し、厳選した UA プリセットのドロップダウン(Claude Code / Kilo Code など UA ホワイトリストを通過できるファミリー)とリアルタイムで非ブロッキングな形式検証を備えます。公式プリセットへ切り替えると残っていたカスタム UA は破棄され、リクエストヘッダーを密かに変更しないようにします([#3671](https://github.com/farion1231/cc-switch/pull/3671))。
### Codex 統一セッション履歴
任意のトグル(設定 → Codex アプリ拡張)を新設し、公式 Codex セッションと CC Switch のサードパーティセッションが同じ resume 履歴バケットを共有できるようにしました。resume セレクタが両者を互いに隠さなくなります。有効化すると、live の `config.toml` は公式の実行を、内蔵 OpenAI プロバイダーをミラーした共有 `custom` model_provider へルーティングします(`auth.json` は変更しません)。デフォルトでは今後のセッションにのみ有効です。有効化ダイアログには既存の公式セッションを共有バケットへ移行できるチェックボックスがあり(世代ごとのバックアップ付き)、無効化ダイアログにはバックアップ台帳に基づく精密な復元が用意されています——バックアップ内で `openai` として記録されたセッションのみを巻き戻し、有効化中に新規作成されたセッションは決して変更しません。
### 使用量ダッシュボードの全体プロバイダー / モデルフィルタ
プロバイダーフィルタとモデルフィルタを、リクエストログテーブルの内部からトップバーへ引き上げ、Hero サマリー、トレンドグラフ、リクエストログ、2 つの統計タブ全体に効くようにしました。ダッシュボード全体を特定のソースとモデルで絞り込めます。ソースは表示名で厳密に一致するため「Claude (Session)」のようなセッションのプレースホルダー行も選択でき、モデルは有効な課金モデルで一致し、モデルのドロップダウンは選択したソースに応じてカスケードし、どちらの一覧も現在の期間にデータがある選択肢のみを表示します。
### モデル価格シードの刷新
`seed_model_pricing` の全件価格点検を実施しました: 9 個のモデルの価格を新規追加し(Claude Fable 5、Grok 4.3、Mistral Medium 3.5 / Small 4、Qwen 3.7 Max/Plus などを含む)、各ベンダー公式の定価に合わせて既存価格 28 か所を訂正し(GLM、Grok、MiMo、Doubao、Kimi、MiniMax、Mistral、Qwen)、使用量コストの見積りをより正確にしました。各変更はシード(新規インストールに影響)を更新すると同時に、`repair_current_model_pricing` に旧→新のガードを 1 件追加します(既存データベースを修復し、ユーザーが手動で編集した行は上書きしません)。
### Claude Fable 5 モデル階層
プロバイダーフォームは、Claude Code と Claude Desktop の両プロキシ経路で `claude-fable-5` を 4 つ目のモデルマッピング階層として公開するようになりました。フォールバックチェーンは fable → opus → default で、公式の降格と一致し、Claude Desktop 1.12603.1+ の検証器で `fable-` プレフィックスを許可しました。4 言語のフォールバックヒントも明確化しました: サードパーティの endpoint である階層を空のままにすると、その階層のモデル名がそのまま透過されて 404 になります([#3980](https://github.com/farion1231/cc-switch/issues/3980)、[#4026](https://github.com/farion1231/cc-switch/issues/4026)、[#4049](https://github.com/farion1231/cc-switch/issues/4049))。
### Unity2.ai パートナープロバイダー
Unity2.aiAI API 中継のパートナー)をプリセットとして追加し、管理対象の 7 アプリすべて(Claude Code、Codex、Gemini、OpenCode、OpenClaw、Claude Desktop、Hermes)をカバーしました。各プリセットには紹介登録リンクを付け、4 言語でパートナー宣伝文を補いました。Codex は素の base URL を使用し(このゲートウェイはルートパスに `/responses` を公開)、OpenCode / OpenClaw / Hermes は `/v1` chat-completions の endpoint を使用し、`gpt-5.5` を既定モデルとします。
### Kimi K2.7 Code モデル
`kimi-k2.7-code` モデル(入力 $0.95 / 出力 $4.00 / キャッシュ読み取り $0.19、100 万 token あたり、256K コンテキスト)を新規追加し、6 つの公式 Moonshot Kimi プリセットすべて(Claude Code、Codex、Claude Desktop、Hermes、OpenCode、OpenClaw)をこれに向けました。OpenCode / OpenClaw のプリセットは「Kimi K2.7 Code」へ改名しました。価格シードは起動時の冪等な挿入経路で有効になるため、既存ユーザーは移行なしで新価格を取得できます。
### Codex「Kimi For Coding」プリセットの復活
Codex「Kimi For Coding」プリセット(`openai_chat``kimi-for-coding`、256K コンテキスト)を再追加し、思考モードをデフォルトで有効にしました。以前これを削除したのは、このコーディング endpoint が Codex 既定の `codex-cli` User-Agent を 403 で拒否するためでしたが、現在はプロキシテイクオーバー + カスタム User-Agent オーバーライド(ホワイトリストの UA、例 `claude-cli/*` に設定)を使えば正常に使えます。
### リクエスト詳細での課金モデル監査
リクエスト詳細パネルは、「リクエストされたモデル」「課金モデル」がレスポンスのモデルと一致しないときにそれらをすべて表示するようになり、ルーティングテイクオーバーが生む請求を使用量画面から直接照合できます。
### プリセットプロバイダーの検索とソート
プリセットプロバイダーのセレクタが、検索・ソート可能な一覧になり、インライン検索ボックスを備えました(虫眼鏡アイコンで切り替え、ESC または外側クリックで畳む)。ボタンはレスポンシブグリッドに変わってサイズが統一され、既定アイコンを表示します。検索はプロバイダーの表示名 / 生の名前のみに一致するため、URL の断片や共有のカテゴリラベルがノイズ一致を生まなくなります([#3975](https://github.com/farion1231/cc-switch/pull/3975)、[#4183](https://github.com/farion1231/cc-switch/pull/4183))。
### Claude Mythos 5 の価格
内蔵のモデル / 価格表に `claude-mythos-5` モデル(入力 $10 / 出力 $50、100 万 token あたり;キャッシュ読み取り $1.00、キャッシュ書き込み $12.50)を登録し、使用量統計が正しく課金・表示できるようにしました([#4077](https://github.com/farion1231/cc-switch/pull/4077))。
### Fable 5 Verified バッジ
設定の「バージョン情報」ページが、アプリ名とバージョンの隣に Fable 5 Verified バッジを表示し、これが特別ビルドであることを示すようになりました。バージョンバッジもアプリ名の下に中央揃えしました。
---
## 変更
### Claude Desktop の使用量を Claude に折りたたみ
ダッシュボードは独立した「Claude Desktop」バケットを表示しなくなりました——これは常に不完全な数字しか表示できませんでした(Desktop のチャット使用量はそもそもプロキシを経由せず、その Code タブのセッションは内蔵の Claude Code ランタイムが共有の `~/.claude/projects` ディレクトリへ書き込んでいるだけです)。Desktop のプロキシトラフィックは表示上 `claude` に折りたたまれますが、記帳層はルーティングテイクオーバー課金の監査のために引き続き自身の `app_type` で記録し、本物の値はリクエスト詳細パネルで確認できます。
### 軽量化したプロバイダーヘルスチェック
プロバイダーヘルスチェックは、本物のストリーミングモデルリクエストを送らなくなりました(多くのサードパーティプロバイダーが 401/403/WAF でブロックし、利用不可の誤検知を生むため)。代わりにプロバイダーの `base_url` へ軽量な HTTP 到達性プローブを 1 回行います: あらゆる HTTP レスポンスを到達可能とみなし、DNS / 接続 / TLS / タイムアウトのみを失敗とします。公式プロバイダー(OAuth を使用し、base_url が意図的に空で、信頼できる到達性ターゲットがない)は接続性チェックのボタンを隠します。従来の「本物のリクエストを送る」確認ダイアログ、テストモデル / プロンプトのフィールドは削除し、劣化レイテンシのしきい値を 6s、タイムアウトを 8s としました。この到達性チェックは決してサーキットブレーカーをリセットしません——到達可能 ≠ 利用可能(403 を返す host は到達可能でも、本物のトラフィックには壊れています)。フェイルオーバーの判定は引き続き本物のプロキシトラフィックのみで駆動されます。
### Codex の高度なオプション領域の統合
Codex プロバイダーフォームは、ローカルルーティング、モデルマッピング、推論オーバーライド、カスタム User-Agent を展開可能な高度なオプション領域に折りたたみ、Claude フォームと揃えました(UA が設定されているか、ローカルルーティングが有効なときは自動展開)。カスタム User-Agent はネイティブ Responses プロバイダーでも設定できるようになりました。以前は `openai_chat` ルーティングを有効にしたときにしか触れられませんでした。
### 使用量ツールバーとレイアウトの刷新
アプリフィルタはブランドアイコン(ProviderIcon 経由、「すべて」はグリッドアイコン)で描画するように変更し、狭いウィンドウで折り返すと見栄えの悪かったテキストタブを置き換えました。使用量 Hero も選択したアプリのブランドアイコンを表示し、Codex のテーマ色をエメラルドからニュートラルグレーへ変更して、OpenAI のモノクロブランドに合わせました。クリックで循環切り替えしていた更新ボタンは、ローカライズした「オフ」ラベルを持つドロップダウン選択に変更し、トップバーのコントロールも圧縮して幅のグループを揃え、長すぎる日付範囲のラベルは省略表示するようにしました。
### バージョン情報パネルの読み込みを高速化
設定の「バージョン情報」パネルが段階的に読み込むようになりました: アプリのバージョンバッジは解決した瞬間に表示され、ツールのプローブを待たなくなります。各ツールカードは自身のバージョン検出が完了した時点で即座に更新されます(プローブは直列ではなく並行に実行)。プローブ結果はアプリのセッション中、10 分の TTL 付きでキャッシュされるため、「バージョン情報」タブを再度開くとキャッシュ値を再利用し、期限切れの項目だけをバックグラウンドで再検証します。毎回 6 つのツールすべてを再プローブすることはなくなりました。
### 火山方舟 Coding Plan の宣伝更新
火山方舟(Volcengine Ark)プリセットを 6 アプリすべてで新しい Coding Plan 招待リンクへ更新し(旧 Agent Plan / キャンペーンリンクを置き換え)、4 言語でパートナー宣伝文を刷新しました(2 か月 75% 割引 + 招待コード 6J6FV5N2)。製品名も Agent Plan から Coding Plan へ訂正しました。
### MiniMax を通常プロバイダーへ降格
MiniMax の金色のパートナースター印と API key 宣伝バナーを削除し(全プリセットから `isPartner` フラグを除去)、引き続き通常の `cn_official` プロバイダーとしてアイコンとテーマを保持します。宣伝文は休眠状態のまま残し、必要であれば 1 行で提携関係を再有効化できます。
### LemonData を削除、SudoCode を降格
LemonData プロバイダープリセットを完全に削除し(宣伝文、アイコン、スポンサー項目もあわせて)、SudoCode をパートナーから通常の `third_party` プロバイダーへ降格しました(`isPartner` フラグと宣伝文を外し、アイコンは保持)。
### AtlasCloud Codex GLM 5.1 のコンテキストウィンドウ
AtlasCloud Codex プリセットの `zai-org/glm-5.1` モデルに 200,000 token のコンテキストウィンドウを宣言し、ほかの GLM 5.1 プリセット項目に揃えました。
---
## 修正
### ルーティングテイクオーバーのトラフィックを本物の上流モデルで課金
リクエストが別の上流へルーティングされた場合(env モデルマッピング、Claude Desktop ルーティング、Copilot 正規化、Codex chat オーバーライド)、プロキシは以前、上流が返したモデルで帰属・課金していたため、kimi / glm の token を `claude-*` として記録・課金し、コストが約 5〜25 倍に過大評価されていました。現在は転送器が本物のアウトバウンドモデルを捕捉し、「上流が返した値 → アウトバウンドモデル → クライアントのエイリアス」の順で帰属し、各行に実際に使用した課金根拠を永続化します(schema v11)。この根拠はコストのバックフィルと 30 日 rollup のプルーニングまで一貫して使われます。Claude Desktop のトラフィックも自身の `app_type` で記録されるようになり、その価格オーバーライドが正しく効くようになりました。
### 形式変換経路での使用量計上
プロキシの各形式変換経路(Chat、Responses、Gemini を Anthropic へ)での token / キャッシュの計上を監査・修正しました。プロキシは実際に返ったモデルを記録し、`stream_options.include_usage` を注入して OpenAI 互換の上流がストリーミング時に usage を吐くようにし、Claude←OpenAI 経路では `cache_read``cache_creation` を input から除外してキャッシュ token の二重計上を防ぎ、Gemini のキャッシュ済みプロンプト token を差し引き、完全にキャッシュヒットしたリクエストも引き続き記録し、過去にリクエスト数を水増ししていた合成の全ゼロ usage をスキップするようになりました([#2774](https://github.com/farion1231/cc-switch/pull/2774))。
### アプリ内更新がハングしなくなった
アプリ内から更新をインストールするとき、「再起動中」の画面でハングしなくなりました——以前は新版がインストール済みなのに、手動で強制終了せざるを得ない状況が起きていました。ダウンロード—インストール—再起動の一連の流れは、完全にバックエンドで実行するようになり(`install_update_and_restart` コマンドを新設)、プラットフォームごとにインストール順序を決め、再実行の前にまず単一インスタンスロックを破棄します。アプリパッケージがすでに置き換えられた後に古い WebView が JS を走らせ続けることに依存しなくなりました。終了リクエストも分類して、再起動リクエストが Tauri の既定フローに落ちるようにし、ウィンドウ状態プラグインのミューテックスでデッドロックしないようにしました([#4069](https://github.com/farion1231/cc-switch/pull/4069)、[#4074](https://github.com/farion1231/cc-switch/pull/4074))。
### Codex のアップグレードがインストールを壊さなくなった
設定の「バージョン情報」ページから Codex をアップグレードしても、「Missing optional dependency @openai/codex-…」エラーを投げなくなりました。アップグレードのチェーンは以前まず `codex update` を実行しますが、これは npm インストール下では実質的に素の再インストールであり、対応するプラットフォームのバイナリがインストールされていなくても成功を報告していました。現在は Codex を「self-update 優先」経路から除外し、runnable 検出が「アンインストール + 再インストール」の自己修復を駆動するようにしました(npm 管理のインストールに限定)。これが、欠けたプラットフォームバイナリを本当に補える唯一の修正です。
### テイクオーバー時に Codex OAuth 認証情報を保持
Codex プロバイダーでプロキシテイクオーバーを有効にするとき、`ANTHROPIC_AUTH_TOKEN` プレースホルダーを剥がさなくなりました——以前これはホットスイッチ、新規インストール、そして旧バージョンがすでに剥がしてしまった live 設定で、Claude Code のログインを壊していました。現在は管理対象(非 Copilot)の Codex プロバイダーに対して、URL のみのプロバイダーを含め無条件にこのプレースホルダーを注入します。GitHub Copilot の挙動(API_KEY のみ)は変わりません([#3789](https://github.com/farion1231/cc-switch/pull/3789)、[#3784](https://github.com/farion1231/cc-switch/issues/3784))。
### 設定ディレクトリをまたぐ切り替えでのテイクオーバー残留の復元
プロキシテイクオーバーが有効なときに設定ディレクトリを変更してアプリを再起動しても、Claude / Codex / Gemini を失効したローカルプロキシに向けたままにしなくなりました。現在は旧インスタンスが再起動の前にテイクオーバーされた live ファイルを先に復元し、初回実行のインポートはテイクオーバープレースホルダーをプロバイダーとして永続化することを拒否し、SSOT の復元も書き戻す前に、現在のプロバイダーの設定にプレースホルダーが含まれないことを検証します([#4076](https://github.com/farion1231/cc-switch/pull/4076))。
### 形式変換フォールバックでの誤ラベル SSE レスポンスの集約
Claude / Codex の形式変換を経たリクエストで、MaaS ゲートウェイが `stream:false` のリクエストを強制的にストリーミングし、非 SSE の Content-Type で SSE レスポンスボディを返したとき、難解な 422「Failed to parse upstream response」で失敗しなくなりました。プロキシは解析失敗時に SSE かどうかを検出し、チャンクを単一の JSON に集約してから既存の変換器を走らせ、クライアントが引き続き有効な非ストリーミングレスポンスを受け取れるようにします。残った解析失敗には content-type、エンコーディング、レスポンスボディの抜粋などの診断情報を付け、deflate のデコードも先に zlib を、次に素のストリームを試すように変更しました([#2234](https://github.com/farion1231/cc-switch/pull/2234))。
### Hermes 設定の重複 YAML キー
Hermes 設定の書き込みは、重複したトップレベルキー(`mcp_servers` など)を累積しなくなりました。これは「Failed to parse Hermes config as YAML: duplicate entry with key」エラーを引き起こしていました。セクションの置換は、追加へ退化する代わりに、残りのテキストから古いコピーをすべて取り除くようになりました。重複排除のセーフティネットは LF と CRLF の行末を両方処理します。修復時には最後(最新)のコピーを保持し、Hermes 自身の PyYAML ベースの「後勝ち」セマンティクスに揃えます([#3267](https://github.com/farion1231/cc-switch/pull/3267)、[#3633](https://github.com/farion1231/cc-switch/issues/3633)、[#2973](https://github.com/farion1231/cc-switch/issues/2973)、[#2529](https://github.com/farion1231/cc-switch/issues/2529)、[#3310](https://github.com/farion1231/cc-switch/issues/3310)、[#3762](https://github.com/farion1231/cc-switch/issues/3762))。
### 使用量照会の堅牢性とエラーの明確さ
使用量カードは、一度の瞬間的なゆらぎだけで赤くならなくなりました: 照会は一度再試行し、ネットワーク / タイムアウト / 5xx のような一時的な失敗下では前回成功した結果を最大 10 分間表示し続けます。一方、確定的な失敗(認証、空の key、未知のプロバイダー、4xx)は即座に表面化してスナップショットをクリアし、認証情報の変更後に古い残量が再び現れるのを防ぎます。ネイティブ残量 / Coding Plan / サブスクリプション照会のタイムアウトは、応答の遅い国際 endpoint に合わせて 10s から 15s へ引き上げました。Coding Plan も空白の失敗ではなく、明確な「API key is empty」/「Unknown coding plan provider」エラーを返すようになりました。
### 使用量スクリプトのプロバイダー認証情報の解決
カスタム JS スクリプトの使用量照会は、以前 env フィールドを推測して `{{apiKey}}` / `{{baseUrl}}` を解決していたため、認証情報を別の場所に置くアプリ(Codex の `auth.OPENAI_API_KEY` に加え `config.toml` の base_url など)は、プロバイダーが完全に設定されていても常に空の値となり失敗していました。スクリプト照会とそのテスト / プレビューは、ネイティブ残量経路と同じアプリごとの認証情報リゾルバを再利用するようになり、スクリプト内で明示的に記入した非空の値は引き続き優先されます([#1479](https://github.com/farion1231/cc-switch/pull/1479))。
### Claude Code Workflow サブ agent の使用量集計
ローカル(プロキシなし)のセッションログ使用量集計は、以前 Claude Code Workflow のサブ agent のトラフィックを取りこぼしており、全体の使用量が約 4.1% 過小評価されていました(workflow / subagent のセッションレコードに集中)。スキャナーはさらに一段深い `subagents/workflows/wf_*/` のレコードディレクトリまで掘り下げるようになり、パーサーも `stop_reason` を欠いているがすでに input / キャッシュ token のコストを生んだ assistant メッセージを捨てなくなりました。重複排除のロジックは変わらないため、重複計上はしません。
### Codex `/responses` のテキスト専用モデル向け画像整流
画像を伴い、テキストのみ対応の OpenAI-chat モデル(DeepSeek `deepseek-v4-flash` など)へルーティングされた Codex `/responses` リクエストが、HTTP 400「unknown variant `image_url`」で失敗しなくなりました。メディア整流器が Codex アダプターもカバーするようになり、responses の `input` 内の `input_image` ブロックをスキャンします。これにより、既知のテキスト専用モデルに対しては画像をプロアクティブに剥がし、上流が「画像非対応」を報告したときにも画像を置き換えて再試行できます。
### 智譜 Coding Plan のクォータウィンドウの誤ラベル
智譜 Coding Plan ビューは、各週周期の最後の数時間で 5 時間ウィンドウと週ウィンドウを取り違えてラベル付けしなくなりました。両ウィンドウは今や明示的な `unit` フィールドで分類され(3 = 5 時間、6 = 週)、リセット時刻の昇順ソートに頼らなくなりました——後者はユーザーが週クォータを最も照会するタイミングで、ちょうど両者を取り違えてラベル付けしていました。フィールドが欠けているときは引き続き従来のリセット時刻ヒューリスティックへフォールバックします([#3036](https://github.com/farion1231/cc-switch/pull/3036))。
### macOS の重複プロバイダーターミナルウィンドウ
macOS でプロバイダーターミナルを起動するとき、コマンドセッションの隣に空のウィンドウをもう 1 つ開かなくなりました。Terminal.app はコールドスタート時に `activate` ではなく `launch` を使い、Ghostty は初期コマンドを使うことで、単一のセッションだけを開きます。AppleScript 経路が失敗したときのフォールバックも残してあります([#4156](https://github.com/farion1231/cc-switch/pull/4156))。
### Claude Desktop モデルマッピングのプレースホルダー
Claude Desktop モデルマッピングフォームは、以前「メニュー表示名」と「リクエストモデル」の 2 列で一貫しないブランド例(DeepSeek vs Kimi)を使い、ある表示名が無関係なモデルへマッピングされるかのように見せていました。現在は両方のプレースホルダーが各行のロールから導かれ、ブランドの一貫性を保ち、軽量な Haiku 階層は flash の例を使います。
### ポップオーバーが全画面パネルに隠れる
プロバイダープリセット検索のようなポップオーバーやツールチップが、全画面パネルの後ろに描画されてクリックが効かないように見える問題がなくなりました。これらの z-index を全画面オーバーレイの上に引き上げつつ、モーダルダイアログよりは低く保ちました。
### ToggleRow アイコンの縮み
トグル行のアイコンは、長い説明と並んでも縮んだり歪んだりしなくなり、複数行のテキストの隣でアイコンが固定サイズを保ちます。
---
## ドキュメント
### Release Notes の貢献者謝辞の復元
v3.16.1 と v3.16.2 の release notes の貢献者謝辞を 3 言語で復元しました。
---
## アップグレード時の注意
### 価格ライブラリ schema v11 の自動移行
本リリースは `proxy_request_logs``pricing_model` 列を新設し、`request_model` + `pricing_model` で rollup を再構築しました。起動時に自動移行し、手動操作は不要です。過去の行のコストは書き込み時に確定済みで再計算されません(`app_type="claude"` の行はネイティブと変換の 2 種類のソースが混在しています)。本物だが当時課金されなかったテイクオーバー行のみがゼロコストのまま残り、価格が補われた後にバックフィルされます。
### モデルマッピングに 4 つ目の階層(Fable 5)を追加
Claude Code と Claude Desktop のモデルマッピングは 4 階層(Sonnet / Opus / Fable / Haiku)になりました。従来の 3 階層プロバイダーは、再度開いて保存すると `claude-fable-5` 階層が補われます。この階層を空のままにすると Sonnet を継承します。注意: サードパーティの endpoint でいずれかの階層を空のままにすると、その階層のモデル名がそのまま透過されて 404 になる可能性があるため、必要に応じて記入してください。
### 「Kimi For Coding」プリセットはプロキシテイクオーバー + ホワイトリスト UA が必要
復活した Codex「Kimi For Coding」プリセットは、既定の `codex-cli` User-Agent をそのまま使うと依然 403 になります。利用するには、プロキシテイクオーバーを有効にし、プロバイダーの高度なオプションでカスタム User-Agent をホワイトリストの UA(`claude-cli/*` など)に設定してください。
### プロバイダーヘルスチェックのセマンティクス変更
ヘルスチェックは「本物のモデルリクエストを送る」から「HTTP 到達性プローブ」へ変わりました。到達可能 ≠ 利用可能であることにご注意ください: 403 を返す host は到達可能でも、本物のトラフィックには壊れている可能性があります。フェイルオーバーの判定は引き続き本物のプロキシトラフィックのみで駆動され、ヘルスチェックの影響を受けません。
---
## リスク通知
本リリースは、リバースプロキシ系機能に関する以前のリスク通知を引き続き適用します。
**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションの Codex OAuth をリバースプロキシ経由で使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 release notes](v3.13.0-ja.md#-リスクに関する注意事項) を参照してください。
**Codex サードパーティプロバイダー Chat ルーティング**: CC Switch ローカルプロキシで Codex リクエストを変換し、サードパーティプロバイダーへ転送する場合、課金・コンプライアンス・データ保持に関する制約はプロバイダーごとに異なります。利用前に対象プロバイダーの利用規約を確認してください。
**Claude Desktop サードパーティプロバイダープロキシ切り替え**: CC Switch 内蔵のプロキシゲートウェイで Claude Desktop のリクエストをサードパーティプロバイダーへ転送する場合も、対象プロバイダーの課金・コンプライアンス・データ保持に関する規約に従う必要があります。
上記機能を有効化したユーザーは、関連するリスクを自ら負うものとします。CC Switch は、これらの機能の利用によって発生したアカウント制限、警告、サービス停止について責任を負いません。
---
## 謝辞
v3.16.3 で機能と修正を届けてくださった以下のコントリビューターに感謝します:
- [#3789](https://github.com/farion1231/cc-switch/pull/3789): テイクオーバー時に Codex OAuth 認証情報を保持、@codeasier に感謝。
- [#2774](https://github.com/farion1231/cc-switch/pull/2774): Completions を Anthropic へ変換する際に実際に返ったモデルを記録せず input token の計算が誤っていた問題を修正、@LaoYueHanNi に感謝。
- [#4069](https://github.com/farion1231/cc-switch/pull/4069): アプリ内更新後の再起動デッドロックを修正、@thisTom に感謝。
- [#4156](https://github.com/farion1231/cc-switch/pull/4156): macOS の重複プロバイダーターミナルウィンドウを修正、@thisTom に感謝。
- [#3267](https://github.com/farion1231/cc-switch/pull/3267): Hermes 設定の重複 YAML キーを修正、@que3sui に感謝。
- [#1479](https://github.com/farion1231/cc-switch/pull/1479): 使用量スクリプトのプロバイダー認証情報の解決を修正、@pa001024 に感謝。
- [#3975](https://github.com/farion1231/cc-switch/pull/3975): プリセットプロバイダーの検索とソートを追加、@Nastem に感謝。
- [#4183](https://github.com/farion1231/cc-switch/pull/4183): プリセットプロバイダーボタンの外観と検索ボックスの位置を調整、@WangJiati に感謝。
- [#4077](https://github.com/farion1231/cc-switch/pull/4077): claude-mythos-5 モデルの価格を追加、@osscv に感謝。
v3.16.2 リリース後に使用量の課金、ローカルプロキシの堅牢性、Codex のアップグレード、プラットフォーム互換性の問題を報告してくださったすべてのユーザーにも感謝します。今回の多くの修正は、実際の利用シーンから得られた再現情報に基づいています。
---
## ダウンロードとインストール
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から、お使いのシステムに対応するビルドをダウンロードしてください。
### システム要件
| システム | 最低バージョン | アーキテクチャ |
| -------- | ------------------------ | ----------------------------------- |
| Windows | Windows 10 以降 | x64 |
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 下表を参照 | x64 / ARM64 |
### Windows
| ファイル | 説明 |
| ---------------------------------------- | -------------------------------------------- |
| `CC-Switch-v3.16.3-Windows.msi` | **推奨** - 自動更新対応の MSI インストーラー |
| `CC-Switch-v3.16.3-Windows-Portable.zip` | ポータブル版、展開してそのまま実行できます |
### macOS
| ファイル | 説明 |
| -------------------------------- | ------------------------------------------------------ |
| `CC-Switch-v3.16.3-macOS.dmg` | **推奨** - DMG インストーラー、Applications へドラッグ |
| `CC-Switch-v3.16.3-macOS.zip` | 展開して Applications へドラッグ、Universal Binary |
| `CC-Switch-v3.16.3-macOS.tar.gz` | Homebrew インストールと自動更新用 |
Homebrew インストール:
```bash
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
Linux アセットは **x86_64****ARM64**`aarch64`)の両方を提供します。ファイル名にアーキテクチャ識別子が含まれているため、マシンの `uname -m` 出力に合わせて選択してください:
- `CC-Switch-v3.16.3-Linux-x86_64.AppImage` / `.deb` / `.rpm`
- `CC-Switch-v3.16.3-Linux-arm64.AppImage` / `.deb` / `.rpm`
| ディストリビューション | 推奨形式 | インストール方法 |
| --------------------------------------- | ----------- | ------------------------------------------------------------------------- |
| 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` |
+339
View File
@@ -0,0 +1,339 @@
# CC Switch v3.16.3
> 🎉 **CC Switch 突破 100,000 Star**
> 感谢每一位用户、贡献者与 Star —— 是你们让它走到这里。🙏
> 💎 **本版由 Claude Fable 5 模型协助开发**——它帮忙梳理清楚了多处关键且容易出错的逻辑:路由接管时按真实上游模型计费的归因链、格式转换路径上缓存 token 的计量与去重、应用内更新的重启死锁,以及 Codex 统一会话历史的迁移 / 还原不变量。这也是本版在「关于」页新增 **Fable 5 Verified** 标识的由来。
> 在 v3.16.2 拓宽数据可携带性与用量观测之后,这一版把重心放在「让用量计费真正准确」——按真实上游模型计费、修正格式转换路径上的缓存双算、把 Claude Code Workflow 子 agent 的用量纳入统计(schema v11),并对用量看板做了一轮改版(全局供应商 / 模型筛选、品牌图标工具栏、更稳的额度查询);同时加固了一批本地代理与平台问题,新增自定义 User-Agent 覆盖、Codex 统一会话历史开关与 Claude Fable 5 档位。
**[English →](v3.16.3-en.md) | [日本語版 →](v3.16.3-ja.md)**
---
## 使用攻略
这一版用量统计的口径和看板做了较多调整,建议先看:
- **[用量统计](../user-manual/zh/4-proxy/4.4-usage.md)**:了解用量看板的数据来源(代理日志、会话同步)与统计口径,本版新增了全局的供应商 / 模型筛选,并把路由接管的真实计价模型展示了出来。
- **[设置](../user-manual/zh/1-getting-started/1.5-settings.md)**:自定义 User-Agent 覆盖、Codex 统一会话历史等开关都在供应商表单的高级选项与设置页里。
---
> [!WARNING]
>
> ## 唯一官方渠道声明(请务必阅读)
>
> CC Switch 是**完全免费、开源**的桌面应用,**不会向用户收取任何费用**。请仅通过下列官方渠道获取本软件:
>
> | 类别 | 唯一官方 |
> | -------- | ------------------------------------------------------------------------------ |
> | 官网 | **[ccswitch.io](https://ccswitch.io)** |
> | 源码 | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
> | 下载 | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
> | 举报山寨 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
>
> **任何向你收费、要求充值、或索取登录凭据的"CC Switch"网站或客户端均为假冒**。如果你被诱导支付了费用,请立即停止操作并通过 GitHub Issues 反馈。
---
## 概览
CC Switch v3.16.3 是 v3.16.2 之后的一版维护更新。在上一版集中拓宽数据可携带性与用量观测之后,这一版把重心放在「让用量计费真正准确」这件事上——按真实上游模型计费而非上游回显、修正格式转换(Chat / Responses / Gemini 转 Anthropic)路径上的缓存 token 双算、把 Claude Code Workflow 子 agent 的用量纳入本地统计,并以 schema v11 持久化每条记录实际使用的定价依据;用量看板也随之做了一轮改版,新增全局的供应商 / 模型筛选、品牌图标工具栏,以及更稳的额度查询(失败重试 + 保留上次成功结果)。
此外,本版还加固了一批本地代理的稳健性问题(错标 Content-Type 的 SSE 响应聚合、Codex `/responses` 文本模型图像整流、Codex OAuth 凭据与接管残留的恢复、Hermes 配置重复 YAML 键),重做了供应商配置体验(自定义 User-Agent 覆盖、Codex 表单统一进高级选项、预设搜索与排序、Claude Fable 5 档位),新增 Codex 统一会话历史开关,并修复了应用内更新卡死、Codex 升级损坏安装、macOS 重复终端窗口等问题。
**发布日期**2026-06-14
**更新规模**59 commits | 130 files changed | +10,223 / -4,232 lines
---
## 重点内容
- **用量计费更准**:路由接管的流量现在按真实上游模型计费(而非上游回显的别名),格式转换路径不再把缓存 token 重复计入 inputClaude Code Workflow 子 agent 的用量也纳入了统计——以 schema v11 持久化定价依据。
- **用量看板改版**:供应商 / 模型筛选从请求日志表提升为全局筛选,应用筛选改用品牌图标,额度查询加入失败重试与「保留上次成功结果」,单次网络抖动不再让卡片变红。
- **自定义 User-Agent 覆盖**:供应商可设置自定义 UA,并在转发、连通性检测、模型列表三处一致生效,绕过按 UA 白名单放行的 Coding Plan 上游(借此恢复了 Codex「Kimi For Coding」预设)。
- **Codex 统一会话历史**:新增可选开关,让官方 Codex 会话与第三方会话共享同一份 resume 历史桶,附带可选的存量迁移与按账本精确还原。
- **代理与平台加固**:错标 SSE 响应聚合、Codex 图像整流、接管残留恢复、Hermes YAML 去重;应用内更新不再卡在「重启中」,Codex 升级不再把安装弄坏。
---
## 新功能
### 自定义 User-Agent 覆盖
供应商配置现在可以设置自定义 User-Agent,并由代理在请求转发、连通性检测和模型列表(`GET /v1/models`)三条路径上一致应用,因此按 UA 白名单放行的 Coding Plan 上游不会再出现「检测失败 / 模型列表 403、但代理本身却能正常工作」的不一致。Claude 和 Codex 表单都在高级选项里暴露该字段,配有精选的 UA 预设下拉(Claude Code / Kilo Code 等能通过 UA 白名单的家族)和实时、非阻塞的格式校验;切换到官方预设时会丢弃残留的自定义 UA,避免悄悄改动请求头([#3671](https://github.com/farion1231/cc-switch/pull/3671))。
### Codex 统一会话历史
新增一个可选开关(设置 → Codex 应用增强),让官方 Codex 会话与 CC Switch 的第三方会话共享同一份 resume 历史桶,resume 选择器不再把两者互相隐藏。开启后,live 的 `config.toml` 会把官方运行路由到一个镜像内建 OpenAI 供应商的共享 `custom` model_provider`auth.json` 不动)。默认只对未来会话生效;开启弹窗提供一个勾选项,可把已有官方会话迁入共享桶(含逐代备份),关闭弹窗则提供按备份账本精确还原——只回退备份中记录为 `openai` 的会话,开启期间新建的会话永不被改动。
### 用量看板全局供应商 / 模型筛选
供应商和模型筛选从请求日志表内部提升到了顶栏,对 Hero 汇总、趋势图、请求日志和两个统计页签全局生效,可以把整个看板按某个来源和模型缩小范围。来源按展示名精确匹配(因此像「Claude (Session)」这样的会话占位行也可选),模型按有效计价模型匹配,模型下拉会随所选来源级联,且两个列表只列出当前时间范围内有数据的选项。
### 模型定价种子刷新
`seed_model_pricing` 做了一次全量核价:新增 9 个模型的定价(含 Claude Fable 5、Grok 4.3、Mistral Medium 3.5 / Small 4、Qwen 3.7 Max/Plus 等),并按各厂商官方 list 价订正了 28 处既有价格(GLM、Grok、MiMo、Doubao、Kimi、MiniMax、Mistral、Qwen),让用量成本估算更准确。每处改动都同时更新种子(影响全新安装)并向 `repair_current_model_pricing` 加一条旧→新守卫(修复存量数据库,且不覆盖用户手改过的行)。
### Claude Fable 5 模型档位
供应商表单现在在 Claude Code 和 Claude Desktop 两条代理路径上都暴露 `claude-fable-5` 作为第四个模型映射档位,回落链为 fable → opus → default,与官方降级一致,并为 Claude Desktop 1.12603.1+ 的校验器放行了 `fable-` 前缀。四语回落提示也做了澄清:在第三方端点上把某一档留空,会原样透传该档的字面模型名并 404([#3980](https://github.com/farion1231/cc-switch/issues/3980)、[#4026](https://github.com/farion1231/cc-switch/issues/4026)、[#4049](https://github.com/farion1231/cc-switch/issues/4049))。
### Unity2.ai 合作伙伴供应商
新增 Unity2.ai(一个 AI API 中转合作伙伴)作为预设,覆盖全部 7 个受管应用(Claude Code、Codex、Gemini、OpenCode、OpenClaw、Claude Desktop、Hermes),每个预设都带上推广注册链接,并在四种语言里补充了合作伙伴推广文案。Codex 使用裸 base URL(该网关在根路径暴露 `/responses`),OpenCode / OpenClaw / Hermes 使用 `/v1` chat-completions 端点并以 `gpt-5.5` 为预设模型。
### Kimi K2.7 Code 模型
新增 `kimi-k2.7-code` 模型(输入 $0.95 / 输出 $4.00 / 缓存读取 $0.19,每百万 token,256K 上下文),并把全部 6 个官方 Moonshot Kimi 预设(Claude Code、Codex、Claude Desktop、Hermes、OpenCode、OpenClaw)指向它,OpenCode / OpenClaw 预设更名为「Kimi K2.7 Code」。定价种子通过启动时的幂等插入路径生效,存量用户无需迁移即可获得新价。
### 恢复 Codex「Kimi For Coding」预设
重新加入 Codex「Kimi For Coding」预设(`openai_chat``kimi-for-coding`、256K 上下文),默认开启思考模式。此前它被移除是因为该编程端点会以 403 拒绝 Codex 默认的 `codex-cli` User-Agent;现在借助代理接管 + 自定义 User-Agent 覆盖(设为 `claude-cli/*` 等白名单 UA)即可正常使用。
### 请求详情的计价模型审计
请求详情面板现在会在「请求的模型」「计价模型」与响应模型不一致时把它们都显示出来,让路由接管产生的账单可以直接在用量界面里核对。
### 预设供应商搜索与排序
预设供应商选择器现在是一个可搜索、可排序的列表,配有内联搜索框(点放大镜图标切换,按 ESC 或点击外部收起)。按钮改为响应式网格、尺寸统一并显示默认图标,搜索只匹配供应商的展示名 / 原始名,因此 URL 片段和共享的分类标签不会再产生噪声匹配([#3975](https://github.com/farion1231/cc-switch/pull/3975)、[#4183](https://github.com/farion1231/cc-switch/pull/4183))。
### Claude Mythos 5 定价
在内置模型 / 定价表里登记 `claude-mythos-5` 模型(输入 $10 / 输出 $50,每百万 token;缓存读取 $1.00、缓存写入 $12.50),让用量统计能正确计价并展示([#4077](https://github.com/farion1231/cc-switch/pull/4077))。
### Fable 5 Verified 标识
设置「关于」页现在会在应用名与版本旁展示 Fable 5 Verified 标识,标明这是一个特别构建,版本徽标也居中到了应用名下方。
---
## 变更
### Claude Desktop 用量折叠进 Claude
看板不再展示独立的「Claude Desktop」分桶——它一直只能显示一个不完整的数字(Desktop 聊天用量根本不经过代理,而其 Code 页签的会话只是内嵌的 Claude Code 运行时写进共享的 `~/.claude/projects` 目录)。Desktop 的代理流量现在在展示上折叠进 `claude`,但记账层仍按它自己的 `app_type` 记录以便路由接管计费审计,真实值可在请求详情面板看到。
### 轻量化供应商健康检查
供应商健康检查不再发送真实的流式模型请求(很多第三方供应商会以 401/403/WAF 拦截,造成误报不可用),改为对供应商 `base_url` 做一次轻量的 HTTP 可达性探测:任何 HTTP 响应都视为可达,只有 DNS / 连接 / TLS / 超时才算失败。官方供应商(使用 OAuth、base_url 故意为空、没有可靠的可达性目标)会隐藏连通性按钮,原先「发送真实请求」的确认弹窗以及测试模型 / 提示词字段都被移除,降级延迟阈值设为 6s、超时 8s。该可达性检查永不重置熔断器——可达不等于可用(403 的 host 可达,但对真实流量是坏的),失败转移仍只由真实代理流量驱动。
### Codex 高级选项区整合
Codex 供应商表单现在把本地路由、模型映射、推理覆盖和自定义 User-Agent 折叠进一个可展开的高级选项区,与 Claude 表单一致(设置了 UA 或开启本地路由时自动展开)。自定义 User-Agent 现在对原生 Responses 供应商也可配置,此前它只有在开启 `openai_chat` 路由时才能触及。
### 用量工具栏与布局刷新
应用筛选改用品牌图标(经 ProviderIcon,「全部」用网格图标)渲染,取代在窄窗口下换行难看的文字页签;用量 Hero 也会显示所选应用的品牌图标,并把 Codex 的主题色从翠绿改为中性灰,贴合 OpenAI 的单色品牌。点击循环切换的刷新按钮改成了带本地化「关闭」标签的下拉选择,顶栏控件也压缩并对齐成统一的宽度分组,过长的日期范围标签做了截断处理。
### 关于面板加载更快
设置「关于」面板现在渐进式加载:应用版本徽标在解析完成的瞬间就显示,不再等待工具探测;每张工具卡片在自己的版本检测完成时立即更新(探测并发执行而非串行);探测结果在应用会话期内缓存并带 10 分钟 TTL,因此再次打开「关于」页签会复用缓存值、并在后台对过期项重新校验,而不是每次都把 6 个工具全部重探一遍。
### 火山方舟 Coding Plan 推广更新
把火山方舟(Volcengine Ark)预设在全部 6 个应用里更新到新的 Coding Plan 邀请链接(替换旧的 Agent Plan / 活动链接),并在四种语言里刷新了合作伙伴推广文案(两个月 75% 折扣 + 邀请码 6J6FV5N2),把产品名从 Agent Plan 订正为 Coding Plan。
### MiniMax 降为普通供应商
移除 MiniMax 的金色合作伙伴星标和 API key 推广横幅(从所有预设里删掉 `isPartner` 标志),它继续作为常规 `cn_official` 供应商保留图标与主题。推广文案保持休眠状态,必要时一行即可重新启用合作关系。
### 移除 LemonData、SudoCode 降级
彻底移除 LemonData 供应商预设(连同其推广文案、图标和赞助商条目),并把 SudoCode 从合作伙伴降为常规 `third_party` 供应商(去掉 `isPartner` 标志和推广文案,保留图标)。
### AtlasCloud Codex GLM 5.1 上下文窗口
为 AtlasCloud Codex 预设里的 `zai-org/glm-5.1` 模型声明 200,000 token 的上下文窗口,与其他 GLM 5.1 预设条目对齐。
---
## 修复
### 路由接管流量按真实上游模型计费
当请求被路由到了不同的上游(env 模型映射、Claude Desktop 路由、Copilot 归一化、Codex chat 覆盖)时,代理过去会按上游回显的模型来归因和计价,把 kimi / glm 的 token 记成、并按 `claude-*` 计价,成本被高估约 5–25 倍。现在转发器会捕获真实的出站模型,按「上游回显 → 出站模型 → 客户端别名」的顺序归因,并在每行持久化实际使用的定价依据(schema v11),该依据会贯穿成本回填和 30 天 rollup 裁剪;Claude Desktop 流量现在也记在它自己的 `app_type` 下,使其定价覆盖能正确生效。
### 格式转换路径的用量计量
审计并修复了代理各条格式转换路径(Chat、Responses、Gemini 转 Anthropic)上的 token / 缓存计量。代理现在会记录实际返回的模型,注入 `stream_options.include_usage` 让 OpenAI 兼容上游在流式时吐出 usage,在 Claude←OpenAI 路径上把 `cache_read``cache_creation` 从 input 中排除以阻止缓存 token 双计费,扣减 Gemini 的缓存提示 token,仍记录完全命中缓存的请求,并跳过过去会虚增请求数的合成全零 usage([#2774](https://github.com/farion1231/cc-switch/pull/2774))。
### 应用内更新不再卡死
从应用内安装更新时不再卡在「重启中」界面——过去会出现新版已装好、却必须手动强制退出的情况。下载—安装—重启整条链路现在完全在后端执行(新增 `install_update_and_restart` 命令),按平台决定安装顺序,并在重新执行前先销毁单实例锁,而不再依赖旧 WebView 在应用包已被替换之后继续跑 JS;退出请求也做了分类,让重启请求落到 Tauri 默认流程,而不是在窗口状态插件的互斥锁上死锁([#4069](https://github.com/farion1231/cc-switch/pull/4069)、[#4074](https://github.com/farion1231/cc-switch/pull/4074))。
### Codex 升级不再损坏安装
从设置「关于」页升级 Codex 不再让它抛出「Missing optional dependency @openai/codex-…」错误。升级链此前会先跑 `codex update`,而它在 npm 安装下其实是一次裸的重装、即便对应平台的二进制没装上也会报告成功;现在 Codex 已从「优先 self-update」路径里移除,并由一个 runnable 检测触发「卸载 + 重装」自愈(仅限 npm 管理的安装),这是唯一能真正补回缺失平台二进制的修复。
### 接管时保留 Codex OAuth 凭据
为 Codex 供应商开启代理接管时不再剥掉 `ANTHROPIC_AUTH_TOKEN` 占位符——此前这会在热切换、全新安装、以及被旧版本已剥过的 live 配置上破坏 Claude Code 的登录。现在对受管(非 Copilot)的 Codex 供应商无条件注入该占位符,包括只有 URL 的供应商;GitHub Copilot 的行为(仅 API_KEY)不变([#3789](https://github.com/farion1231/cc-switch/pull/3789)、[#3784](https://github.com/farion1231/cc-switch/issues/3784))。
### 跨配置目录切换的接管残留恢复
在代理接管激活时更改配置目录后重启应用,不再把 Claude / Codex / Gemini 留在指向已失效的本地代理上。现在旧实例会在重启前先还原被接管的 live 文件,首次运行的导入会拒绝把接管占位符当作供应商持久化,SSOT 还原也会在写回前校验当前供应商的配置里不含占位符([#4076](https://github.com/farion1231/cc-switch/pull/4076))。
### 格式转换兜底里错标的 SSE 响应聚合
经 Claude / Codex 格式转换的请求,当 MaaS 网关把一个 `stream:false` 的请求强制流式、并以非 SSE 的 Content-Type 返回 SSE 响应体时,不再以一句晦涩的 422「Failed to parse upstream response」失败。代理现在会在解析失败时嗅探 SSE、把分片聚合成单个 JSON 再跑既有转换器,让客户端仍能拿到有效的非流式响应;剩余的解析失败会附带 content-type、编码和响应体片段等诊断信息,deflate 解码也改为先尝试 zlib 再尝试裸流([#2234](https://github.com/farion1231/cc-switch/pull/2234))。
### Hermes 配置重复 YAML 键
Hermes 配置写入不再累积重复的顶层键(如 `mcp_servers`),那会导致「Failed to parse Hermes config as YAML: duplicate entry with key」错误。区段替换现在会从剩余文本里清除所有过期副本,而不是退化成追加;去重保护层同时处理 LF 和 CRLF 行尾;修复时保留最后(最新)的那份副本,与 Hermes 自身基于 PyYAML 的「后者胜」语义一致([#3267](https://github.com/farion1231/cc-switch/pull/3267)、[#3633](https://github.com/farion1231/cc-switch/issues/3633)、[#2973](https://github.com/farion1231/cc-switch/issues/2973)、[#2529](https://github.com/farion1231/cc-switch/issues/2529)、[#3310](https://github.com/farion1231/cc-switch/issues/3310)、[#3762](https://github.com/farion1231/cc-switch/issues/3762))。
### 用量查询韧性与错误清晰度
用量卡片不再因为单次瞬时抖动就变红:查询现在会重试一次,并在网络 / 超时 / 5xx 这类瞬时失败下继续展示上次成功的结果最多 10 分钟;而确定性失败(鉴权、空 key、未知供应商、4xx)会立即暴露并清空快照,避免凭据变更后陈旧额度又冒出来。原生余额 / Coding Plan / 订阅查询的超时从 10s 提高到 15s 以适配跨境慢端点,Coding Plan 也会返回明确的「API key is empty」/「Unknown coding plan provider」错误,而不是一句空白的失败。
### 用量脚本供应商凭据解析
自定义 JS 脚本的用量查询此前只靠猜测 env 字段来解析 `{{apiKey}}` / `{{baseUrl}}`,因此凭据存放在别处的应用(如 Codex 的 `auth.OPENAI_API_KEY``config.toml` 里的 base_url)总是拿到空值、即便供应商已完整配置也会失败。脚本查询及其测试 / 预览现在复用与原生余额路径相同的按应用凭据解析器,脚本里显式填写的非空值仍然优先([#1479](https://github.com/farion1231/cc-switch/pull/1479))。
### Claude Code Workflow 子 agent 用量统计
本地(无代理)的会话日志用量统计此前漏掉了 Claude Code Workflow 子 agent 的流量,整体用量被低估约 4.1%(集中在 workflow / subagent 的会话记录里)。扫描器现在会深入更深一层的 `subagents/workflows/wf_*/` 记录目录,解析器也不再丢弃那些缺少 `stop_reason`、但已经产生 input / 缓存 token 成本的 assistant 消息;去重逻辑不变,因此不会重复计数。
### Codex `/responses` 文本模型图像整流
携带图片、且被路由到只支持文本的 OpenAI-chat 模型(如 DeepSeek `deepseek-v4-flash`)的 Codex `/responses` 请求,不再以 HTTP 400「unknown variant `image_url`」失败。媒体整流器现在也覆盖 Codex 适配器,会扫描 responses 的 `input` 里的 `input_image` 块,从而既能为已知的纯文本模型主动剥掉图片,也能在上游报「不支持图片」时把图片替换后重试。
### 智谱 Coding Plan 配额窗口误标
智谱 Coding Plan 视图不再在每个周周期的最后几个小时把 5 小时窗口和周窗口标反。两个窗口现在按显式的 `unit` 字段分类(3 = 5 小时、6 = 周),而不再靠按重置时间升序排序——后者恰好在用户最常查周额度的时候把两者标反;当字段缺失时仍回退到旧的重置时间启发式([#3036](https://github.com/farion1231/cc-switch/pull/3036))。
### macOS 重复供应商终端窗口
在 macOS 上启动供应商终端时不再在命令会话旁多开一个空窗口;Terminal.app 在冷启动时改用 `launch`(而非 `activate`),Ghostty 使用初始命令,从而只打开单个会话,并在 AppleScript 路径失败时保留回退方案([#4156](https://github.com/farion1231/cc-switch/pull/4156))。
### Claude Desktop 模型映射占位符
Claude Desktop 模型映射表单此前在「菜单展示名」和「请求模型」两列用了不一致的示例品牌(DeepSeek vs Kimi),暗示一个展示名会映射到不相关的模型。现在两个占位符都由每行的角色派生,从而保持品牌一致,轻量的 Haiku 档使用 flash 示例。
### 弹层被全屏面板遮挡
像供应商预设搜索这样的弹层和提示气泡不再渲染到全屏面板后面、看起来点了没反应;它们的 z-index 被提到全屏遮罩之上,同时仍低于模态对话框。
### ToggleRow 图标被挤压
开关行的图标在配上长描述时不再被压缩或变形,让图标在多行文字旁保持固定大小。
---
## 文档
### Release Notes 贡献者致谢恢复
恢复了 v3.16.1 与 v3.16.2 release notes 在三种语言里的贡献者致谢。
---
## 升级提醒
### 定价库 schema v11 自动迁移
本版给 `proxy_request_logs` 新增了 `pricing_model` 列、并按 `request_model` + `pricing_model` 重建了 rollup,启动时自动迁移、无需手动操作。历史行的成本在写入时已冻结、不会重算(`app_type="claude"` 的行混合了原生与转换两类来源);只有真实但当时未计价的接管行会保持零成本、待定价补齐后再回填。
### 模型映射新增第四档(Fable 5)
Claude Code 与 Claude Desktop 的模型映射现在是四档(Sonnet / Opus / Fable / Haiku)。老的三档供应商在重新打开并保存后会补上 `claude-fable-5` 档;该档留空表示继承 Sonnet。注意:在第三方端点上把任意一档留空,会原样透传该档的字面模型名并可能 404,请按需填写。
### 「Kimi For Coding」预设需要代理接管 + 白名单 UA
恢复的 Codex「Kimi For Coding」预设直接用默认的 `codex-cli` User-Agent 仍会被 403。要使用它,请开启代理接管,并在供应商高级选项里把自定义 User-Agent 设为白名单 UA(如 `claude-cli/*`)。
### 供应商健康检查语义变化
健康检查从「发送真实模型请求」改为「HTTP 可达性探测」。请注意可达 ≠ 可用:一个返回 403 的 host 是可达的,但对真实流量可能是坏的。失败转移的判定仍只由真实代理流量驱动,不受健康检查影响。
---
## 风险提示
本版本继续沿用此前版本对反向代理类功能的风险提示。
**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#-风险提示)。
**Codex 第三方供应商 Chat 路由**:通过 CC Switch 本地代理把 Codex 请求转换并转发到第三方供应商时,各供应商对计费、合规与数据留存的约束不同,请在使用前阅读目标供应商的服务条款。
**Claude Desktop 第三方供应商代理切换**:通过 CC Switch 内置代理网关把 Claude Desktop 的请求转到第三方供应商时,同样需要遵守目标供应商的计费、合规与数据留存约束。
用户启用上述功能即表示自行承担相关风险。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
---
## 致谢
感谢以下贡献者在 v3.16.3 中提交的功能与修复:
- [#3789](https://github.com/farion1231/cc-switch/pull/3789):接管时保留 Codex OAuth 凭据,感谢 @codeasier
- [#2774](https://github.com/farion1231/cc-switch/pull/2774):修复 Completions 转 Anthropic 时不记录实际返回模型、input token 计算错误,感谢 @LaoYueHanNi
- [#4069](https://github.com/farion1231/cc-switch/pull/4069):修复应用内更新后重启死锁,感谢 @thisTom
- [#4156](https://github.com/farion1231/cc-switch/pull/4156):修复 macOS 重复供应商终端窗口,感谢 @thisTom
- [#3267](https://github.com/farion1231/cc-switch/pull/3267):修复 Hermes 配置重复 YAML 键,感谢 @que3sui
- [#1479](https://github.com/farion1231/cc-switch/pull/1479):修复用量脚本供应商凭据解析,感谢 @pa001024
- [#3975](https://github.com/farion1231/cc-switch/pull/3975):新增预设供应商搜索与排序,感谢 @Nastem
- [#4183](https://github.com/farion1231/cc-switch/pull/4183):调整预设供应商按钮外观与搜索框位置,感谢 @WangJiati
- [#4077](https://github.com/farion1231/cc-switch/pull/4077):新增 claude-mythos-5 模型定价,感谢 @osscv
也感谢所有在 v3.16.2 发布后反馈用量计费、本地代理稳健性、Codex 升级与平台兼容性问题的用户,很多补丁都来自这些真实使用场景里的复现线索。
---
## 下载与安装
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
### 系统要求
| 系统 | 最低版本 | 架构 |
| ------- | -------------------------- | ----------------------------------- |
| Windows | Windows 10 及以上 | x64 |
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 见下表 | x64 / ARM64 |
### Windows
| 文件 | 说明 |
| ---------------------------------------- | ----------------------------------- |
| `CC-Switch-v3.16.3-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
| `CC-Switch-v3.16.3-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
### macOS
| 文件 | 说明 |
| -------------------------------- | --------------------------------------------- |
| `CC-Switch-v3.16.3-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
| `CC-Switch-v3.16.3-macOS.zip` | 解压后拖入 ApplicationsUniversal Binary |
| `CC-Switch-v3.16.3-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
Homebrew 安装:
```bash
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
Linux 资产同时提供 **x86_64****ARM64**`aarch64`)两种架构。资产文件名中包含架构标识,请按你机器的 `uname -m` 输出选择对应版本:
- `CC-Switch-v3.16.3-Linux-x86_64.AppImage` / `.deb` / `.rpm`
- `CC-Switch-v3.16.3-Linux-arm64.AppImage` / `.deb` / `.rpm`
| 发行版 | 推荐格式 | 安装方式 |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| 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` |
+4 -4
View File
@@ -1,6 +1,6 @@
# CC Switch User Manual / 用户手册 / ユーザーマニュアル
> Claude Code / Codex / Gemini CLI / OpenCode / OpenClaw
> Claude Code / Claude Desktop / Codex / Gemini CLI / OpenCode / OpenClaw / Hermes
## Language / 语言 / 言語
@@ -12,9 +12,9 @@
## Version / 版本 / バージョン
- Documentation version: v3.15.0
- Last updated: 2026-05-16
- Compatible with CC Switch v3.15.0+
- Documentation version: v3.16.0
- Last updated: 2026-05-29
- Compatible with CC Switch v3.16.0+
## Links
@@ -2,7 +2,7 @@
## What is CC Switch
CC Switch is a cross-platform desktop application designed for developers who use AI coding tools. It helps you centrally manage configurations for **Claude Code**, **Claude Desktop**, **Codex**, **Gemini CLI**, **OpenCode**, **OpenClaw**, and **Hermes**.
CC Switch is a cross-platform desktop application designed for developers who use AI tools. It helps you centrally manage configurations for **Claude Code**, **Claude Desktop**, **Codex**, **Gemini CLI**, **OpenCode**, **OpenClaw**, and **Hermes**.
## What Problems Does It Solve
@@ -45,7 +45,7 @@ CC Switch solves these problems through a unified interface.
| **Codex** | OpenAI's code generation tool |
| **Gemini CLI** | Google's AI command-line tool |
| **OpenCode** | Open-source AI coding terminal tool |
| **OpenClaw** | Open-source AI coding assistant (multi-provider gateway) |
| **OpenClaw** | Open-source AI assistant (multi-provider gateway) |
| **Hermes** | Hermes Agent provider, MCP, Skills, and Memory management |
## Supported Platforms
@@ -12,7 +12,7 @@
| 2 | Settings Button | Open the settings page (shortcut `Cmd/Ctrl + ,`) |
| 3 | Proxy Toggle | Start/stop the local proxy service |
| 4 | App Switcher | Switch between Claude / Claude Desktop / Codex / Gemini / OpenCode / OpenClaw / Hermes |
| 5 | Feature Area | Skills / Prompts / MCP entry points |
| 5 | Feature Area | App-specific feature entry points |
| 6 | Add Button | Add a new provider |
### App Switcher
@@ -33,9 +33,9 @@ After switching, the provider list displays the configurations for the selected
| Button | Function | Visibility |
|--------|----------|------------|
| Skills | Skill extension management | Always visible |
| Prompts | System prompt management | Always visible |
| MCP | MCP server management | Always visible |
| Skills | Skill extension management | Claude / Codex / Gemini / OpenCode / Hermes |
| Prompts | System prompt management | Claude / Codex / Gemini / OpenCode |
| MCP | MCP server management | Claude / Codex / Gemini / OpenCode / Hermes |
## Provider Cards
@@ -113,13 +113,14 @@ CC Switch displays an icon in the system tray, providing quick access to operati
### Multi-language Support
The tray menu supports three languages, automatically switching based on settings:
The tray menu supports four languages, automatically switching based on settings:
| Language | Open Main Window | Quit |
|----------|-----------------|------|
| Chinese | Open Main Window | Quit |
| Simplified Chinese | 打开主界面 | 退出 |
| Traditional Chinese | 開啟主介面 | 退出 |
| English | Open main window | Quit |
| Japanese | Open main window | Quit |
| Japanese | メインウィンドウを開く | 終了 |
### Lightweight Mode
@@ -147,7 +148,7 @@ The settings page is divided into multiple tabs:
### General Tab
- Language settings (Chinese/English/Japanese)
- Language settings (Simplified Chinese/Traditional Chinese/English/Japanese)
- Theme settings (System/Light/Dark)
- Window behavior (launch on startup, close behavior)
@@ -9,11 +9,12 @@ This section describes how to configure CC Switch according to your preferences.
## Language Settings
CC Switch supports three languages:
CC Switch supports four languages:
| Language | Description |
|----------|-------------|
| Simplified Chinese | Default language |
| Traditional Chinese | Traditional Chinese interface |
| English | English interface |
| Japanese | Japanese interface |
@@ -124,8 +125,9 @@ You can customize each CLI tool's configuration directory:
| Claude Directory | `~/.claude/` | Claude Code configuration directory |
| Codex Directory | `~/.codex/` | Codex configuration directory |
| Gemini Directory | `~/.gemini/` | Gemini CLI configuration directory |
| OpenCode Directory | `~/.opencode/` | OpenCode configuration directory |
| OpenCode Directory | `~/.config/opencode/` | OpenCode configuration directory |
| OpenClaw Directory | `~/.openclaw/` | OpenClaw configuration directory |
| Hermes Directory | `~/.hermes/` | Hermes configuration directory |
> **Note**: After changing directories, the app must be restarted, and the corresponding CLI tools must also be configured to use the same directory.
@@ -133,14 +135,15 @@ You can customize each CLI tool's configuration directory:
### Export Configuration
Click the "Export" button to save a backup file containing:
Click the "Export" button to save a SQL backup file containing:
- All provider configurations
- MCP server configurations
- Prompt presets
- Usage logs
- App settings
The backup file is in JSON format and can be viewed with a text editor.
The exported file name format is `cc-switch-export-{timestamp}.sql`.
### Import Configuration
+1 -1
View File
@@ -88,7 +88,7 @@ Codex presets fall into two groups by upstream protocol.
|-------------|-------------|
| DeepSeek | DeepSeek models |
| Zhipu GLM / GLM en | Zhipu AI GLM models |
| Kimi | Moonshot Kimi models |
| Kimi / Kimi For Coding | Moonshot Kimi models |
| MiniMax / MiniMax en | MiniMax models |
| StepFun / StepFun en | StepFun Step models |
| Baidu Qianfan Coding Plan | Baidu Qianfan coding plan |
+7 -5
View File
@@ -103,15 +103,16 @@ Each MCP server can independently control which apps it is enabled for.
| Claude | Sync to Claude Code | `~/.claude.json`'s `mcpServers` |
| Codex | Sync to Codex | `~/.codex/config.toml`'s `[mcp_servers]` |
| Gemini | Sync to Gemini CLI | `~/.gemini/settings.json`'s `mcpServers` |
| OpenCode | Sync to OpenCode | `~/.opencode/config.json`'s `mcpServers` |
| OpenCode | Sync to OpenCode | `~/.config/opencode/opencode.json`'s `mcp` |
| Hermes | Sync to Hermes | `~/.hermes/config.yaml`'s `mcp_servers` |
> **Note**: OpenClaw does not currently support MCP server management. MCP functionality is currently only supported for Claude, Codex, Gemini, and OpenCode.
> **Note**: OpenClaw and Claude Desktop do not currently support CC Switch MCP sync. MCP functionality is supported for Claude, Codex, Gemini, OpenCode, and Hermes.
### Toggle Implementation
When enabling an app's toggle, CC Switch will:
1. **Update database**: Set the server's `apps.claude/codex/gemini/opencode` status to `true`
1. **Update database**: Set the server's `apps.claude/codex/gemini/opencode/hermes` status to `true`
2. **Sync to live configuration**: Write the server configuration to the corresponding app's configuration file
3. **Take effect immediately**: The new MCP server is automatically loaded the next time the CLI tool starts
@@ -128,7 +129,8 @@ MCP server sync only executes when the corresponding app is installed:
- **Claude**: Requires `~/.claude/` directory or `~/.claude.json` file to exist
- **Codex**: Requires `~/.codex/` directory to exist
- **Gemini**: Requires `~/.gemini/` directory to exist
- **OpenCode**: Requires `~/.opencode/` directory to exist
- **OpenCode**: Requires `~/.config/opencode/` directory to exist
- **Hermes**: Requires `~/.hermes/` directory to exist
> **Tip**: If a CLI tool is not installed, enabling its toggle will not cause an error, but the configuration will not be written.
@@ -154,7 +156,7 @@ After deletion, the configuration is removed from all app configuration files.
If you have already configured MCP servers in CLI tools, you can import them into CC Switch:
1. Click the "Import" button
2. Select the app to import from (Claude/Codex/Gemini/OpenCode)
2. Select the app to import from (Claude/Codex/Gemini/OpenCode/Hermes)
3. CC Switch reads the existing configuration and imports it
## Configuration File Formats
@@ -81,8 +81,7 @@ After activation, the prompt is written to the corresponding app's file:
| Claude | `~/.claude/CLAUDE.md` |
| Codex | `~/.codex/AGENTS.md` |
| Gemini | `~/.gemini/GEMINI.md` |
| OpenCode | `~/.opencode/AGENTS.md` |
| OpenClaw | `~/.openclaw/AGENTS.md` |
| OpenCode | `~/.config/opencode/AGENTS.md` |
## Edit a Preset
@@ -141,7 +140,6 @@ Prompts are managed separately per app:
- When switched to Codex, Codex's presets are shown
- When switched to Gemini, Gemini's presets are shown
- When switched to OpenCode, OpenCode's presets are shown
- When switched to OpenClaw, OpenClaw's presets are shown
To use the same prompt across multiple apps, you need to create them separately.
@@ -12,18 +12,17 @@ Skills exist as folders containing:
## Supported Applications
Skills are supported across all four applications:
Skills are supported across five applications:
- **Claude Code**
- **Codex**
- **Gemini CLI**
- **OpenCode**
- **Hermes**
## Open the Skills Page
Click the **Skills** button in the top navigation bar.
> Note: The Skills button is visible in all app modes.
Click the **Skills** button in the top navigation bar when the selected app supports Skills.
## Page Overview
@@ -93,7 +92,8 @@ Click the "Refresh" button to re-scan repositories for the latest skills.
| Claude | `~/.claude/skills/` |
| Codex | `~/.codex/skills/` |
| Gemini | `~/.gemini/skills/` |
| OpenCode | `~/.opencode/skills/` |
| OpenCode | `~/.config/opencode/skills/` |
| Hermes | `~/.hermes/skills/` |
### Installation Contents
@@ -119,7 +119,7 @@ Installation copies the skill folder to your local machine:
### Uninstall Effect
- **Automatic backup**: Before deletion, the skill is backed up to `~/.cc-switch/skill-backups/`
- Removes the skill from all app directories (Claude, Codex, Gemini, OpenCode)
- Removes the skill from all app directories (Claude, Codex, Gemini, OpenCode, Hermes)
- Removes the skill from the SSOT directory (`~/.cc-switch/skills/`)
- Deletes the skill record from the database
+8 -2
View File
@@ -215,9 +215,11 @@ Set prices for each model (per million tokens):
Before matching pricing, CC Switch normalizes the requested model ID:
- Remove everything before the last `/`
- Remove everything after `:`
- Remove everything before the last `/` and convert to lowercase
- Remove everything after `:` and trim a trailing `[1m]`
- Replace `@` with `-`
- Remove common wrapper prefixes, version suffixes, and date suffixes (`-YYYY-MM-DD`, `-YYYYMMDD`)
- Some model families can match a short ID to a versioned pricing entry
When adding pricing entries, enter the normalized Model ID rather than the full raw model name from the request.
@@ -226,6 +228,10 @@ When adding pricing entries, enter the normalized Model ID rather than the full
| `stepfun-ai/step-3.5-flash` | `step-3.5-flash` | Removes the provider prefix |
| `moonshotai/kimi-k2-0905:exa` | `kimi-k2-0905` | Removes the prefix and the `:` suffix |
| `gpt-5.2-codex@low` | `gpt-5.2-codex-low` | Replaces `@` with `-` |
| `OpenAI/GPT-5.5-2026-05-14` | `gpt-5.5` | Removes the prefix and date suffix |
| `anthropic/claude-opus-4.8` | `claude-opus-4-8` | Removes the prefix and matches dotted format |
| `global.anthropic.claude-opus-4-8-v1:0` | `claude-opus-4-8` | Removes wrapper prefix, version suffix, and `:` suffix |
| `claude-haiku-4-5` | `claude-haiku-4-5-20251001` | Matches a short ID to versioned pricing |
### Operations
+35 -12
View File
@@ -16,7 +16,7 @@ Customizable location in settings (for cloud sync).
├── settings.json # Device-level settings
├── skills/ # Skill SSOT directory
├── skill-backups/ # Skill backups (created on uninstall)
└── db_backup_*.db # Database backups
└── backups/ # Database backups
```
### Database Contents
@@ -51,7 +51,8 @@ Customizable location in settings (for cloud sync).
"codexConfigDir": null,
"geminiConfigDir": null,
"opencodeConfigDir": null,
"openclawConfigDir": null
"openclawConfigDir": null,
"hermesConfigDir": null
}
```
@@ -196,17 +197,41 @@ GEMINI_MODEL=gemini-pro
### Configuration Directory
Default: `~/.opencode/`
Default: `~/.config/opencode/`
### Key Files
```
~/.opencode/
├── config.json # Main configuration file
~/.config/opencode/
├── opencode.json # Main configuration file
├── AGENTS.md # System prompt
└── skills/ # Skills directory
└── ...
```
## Hermes Configuration
### Configuration Directory
Default: `~/.hermes/`
### Key Files
```
~/.hermes/
├── config.yaml # Main settings, providers, and MCP configuration
├── .env # API keys and secrets
├── SOUL.md # Profile identity/persona
├── memories/
│ ├── MEMORY.md # Agent memory
│ └── USER.md # User profile memory
├── skills/ # Active skills directory
├── state.db # SQLite session database
└── sessions/ # Gateway transcripts and optional JSON snapshots
```
### config.yaml
Hermes uses YAML configuration. CC Switch writes MCP servers to `mcp_servers`, writes editable provider entries to `custom_providers`, reads read-only entries from Hermes' `providers` dict, and updates `model.provider` / `model.default` when switching providers.
## OpenClaw Configuration
@@ -219,7 +244,6 @@ Default: `~/.openclaw/`
```
~/.openclaw/
├── openclaw.json # Main configuration file (JSON5 format)
├── AGENTS.md # System prompt
└── skills/ # Skills directory
└── ...
```
@@ -246,18 +270,17 @@ OpenClaw uses a JSON5 format configuration file with the following main sections
env: {
ANTHROPIC_API_KEY: "sk-..."
},
// Agent default model configuration
// Agent default configuration
agents: {
defaults: {
model: {
primary: "provider/model"
}
},
workspace: "~/.openclaw/workspace"
}
},
// Tool configuration
tools: {},
// Workspace file configuration
workspace: {}
tools: {}
}
```
@@ -267,7 +290,7 @@ OpenClaw uses a JSON5 format configuration file with the following main sections
| `env` | Environment variable configuration |
| `agents.defaults` | Agent default model settings |
| `tools` | Tool configuration |
| `workspace` | Workspace file management |
| `agents.defaults.workspace` | Workspace directory path |
## Configuration Priority
+8 -8
View File
@@ -106,15 +106,15 @@ CC Switch User Manual
## Version Information
- Documentation version: v3.15.0
- Last updated: 2026-05-16
- Applicable to CC Switch v3.15.0+
- Documentation version: v3.16.0
- Last updated: 2026-05-29
- Applicable to CC Switch v3.16.0+
### v3.15.0 Highlights
### v3.16.0 Highlights
- **First-class Claude Desktop panel**: supports third-party providers, direct / model mapping modes, Copilot / Codex OAuth reuse, and 3P profile writing. See [2.6 Claude Desktop](./2-providers/2.6-claude-desktop.md)
- **Role-based model mapping**: adapts Claude Desktop model validation with Sonnet / Opus / Haiku routes and `supports1m`
- **Claude Desktop local routing**: provides a local gateway at `127.0.0.1:15721/claude-desktop` for providers that need conversion
- **Codex Chat Completions routing**: route Chat-only providers such as DeepSeek, Kimi, GLM, and MiniMax through Codex. See [2.1 Add Provider](./2-providers/2.1-add.md)
- **Managed CLI tool lifecycle**: install, update, update all, and diagnose Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes from Settings / About. See [1.5 Personalization](./1-getting-started/1.5-settings.md)
- **Provider and model refresh**: new partner presets, refreshed default models and pricing, Claude Opus 4.8 defaults, and GPT 5.5 defaults where applicable
- **Routing support badges**: Claude Code / Codex provider cards indicate whether a provider can be served through Local Routing
- **Codex OAuth live model discovery**: ChatGPT Codex providers fetch available models from the ChatGPT backend on demand
- **Filter-driven Usage Hero**: shows cache-normalized real total tokens and cache hit rate, updating with date / provider / model filters — see [4.4 Usage Statistics](./4-proxy/4.4-usage.md)
@@ -124,7 +124,7 @@ CC Switch User Manual
- **Per-App Tray Submenus**: Claude / Codex / Gemini submenus show the current provider and available usage summaries — see [2.2 Switch Provider](./2-providers/2.2-switch.md)
- **Skills Discovery & Batch Updates**: SHA-256 update detection, batch updates, skills.sh public registry search — see [3.3 Skills Management](./3-extensions/3.3-skills.md)
- **Full URL Endpoint Mode**: Advanced option to treat `base_url` as the full upstream endpoint — see [2.1 Add Provider](./2-providers/2.1-add.md)
- **OpenCode / OpenClaw Stream Check Coverage**: Stream Check covers Claude / Codex / Gemini / OpenCode / OpenClaw — see [4.5 Model Test](./4-proxy/4.5-model-test.md)
- **OpenCode / OpenClaw / Hermes Stream Check Coverage**: Stream Check covers Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes — see [4.5 Model Test](./4-proxy/4.5-model-test.md)
## Contributing
@@ -2,7 +2,7 @@
## CC Switch とは
CC Switch はクロスプラットフォームのデスクトップアプリケーションで、AI プログラミングツールを使用する開発者向けに設計されています。**Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw**、**Hermes** などの管理対象アプリの設定を統一的に管理できます。
CC Switch はクロスプラットフォームのデスクトップアプリケーションで、AI ツールを使用する開発者向けに設計されています。**Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw**、**Hermes** などの管理対象アプリの設定を統一的に管理できます。
## どのような問題を解決するか
@@ -45,7 +45,7 @@ CC Switch は統一されたインターフェースでこれらの問題を解
| **Codex** | OpenAI のコード生成ツール |
| **Gemini CLI** | Google の AI コマンドラインツール |
| **OpenCode** | オープンソース AI プログラミングターミナルツール |
| **OpenClaw** | オープンソース AI プログラミングアシスタント(マルチプロバイダーゲートウェイ) |
| **OpenClaw** | オープンソース AI アシスタント(マルチプロバイダーゲートウェイ) |
| **Hermes** | Hermes Agent のプロバイダー、MCP、Skills、Memory 管理 |
## 対応プラットフォーム
@@ -12,7 +12,7 @@
| ② | 設定ボタン | 設定ページを開く(ショートカット `Cmd/Ctrl + ,` |
| ③ | プロキシスイッチ | ローカルプロキシサービスの起動/停止 |
| ④ | アプリ切り替え | Claude / Claude Desktop / Codex / Gemini / OpenCode / OpenClaw / Hermes を切り替え |
| ⑤ | 機能エリア | Skills / Prompts / MCP の入口 |
| ⑤ | 機能エリア | 現在のアプリで利用できる機能入口 |
| ⑥ | 追加ボタン | 新しいプロバイダーを追加 |
### アプリ切り替え
@@ -33,9 +33,9 @@
| ボタン | 機能 | 表示条件 |
|------|------|----------|
| Skills | スキル拡張管理 | 常に表示 |
| Prompts | システムプロンプト管理 | 常に表示 |
| MCP | MCP サーバー管理 | 常に表示 |
| Skills | スキル拡張管理 | Claude / Codex / Gemini / OpenCode / Hermes |
| Prompts | システムプロンプト管理 | Claude / Codex / Gemini / OpenCode |
| MCP | MCP サーバー管理 | Claude / Codex / Gemini / OpenCode / Hermes |
## プロバイダーカード
@@ -113,11 +113,12 @@ CC Switch はシステムトレイにアイコンを表示し、クイック操
### 多言語対応
トレイメニューは 3 つの言語に対応し、設定に応じて自動的に切り替わります:
トレイメニューは 4 つの言語に対応し、設定に応じて自動的に切り替わります:
| 言語 | メインウィンドウを開く | 終了 |
|------|-----------|------|
| 中文 | 打开主界面 | 退出 |
| 簡体中文 | 打开主界面 | 退出 |
| 繁體中文 | 開啟主介面 | 退出 |
| English | Open main window | Quit |
| 日本語 | メインウィンドウを開く | 終了 |
@@ -147,7 +148,7 @@ CC Switch はシステムトレイにアイコンを表示し、クイック操
### 一般タブ
- 言語設定(中文/English/日本語)
- 言語設定(簡体中文/繁體中文/English/日本語)
- テーマ設定(システムに合わせる/ライト/ダーク)
- ウィンドウ動作(起動時に自動実行、閉じる動作)
@@ -9,11 +9,12 @@
## 言語設定
CC Switch は 3 つの言語に対応しています:
CC Switch は 4 つの言語に対応しています:
| 言語 | 説明 |
| -------- | -------- |
| 簡体中文 | デフォルト言語 |
| 繁體中文 | 繁体字中国語インターフェース |
| English | 英語インターフェース |
| 日本語 | 日本語インターフェース |
@@ -124,8 +125,9 @@ CC Switch 自体のデータの保存場所で、デフォルトは `~/.cc-switc
| Claude ディレクトリ | `~/.claude/` | Claude Code 設定ディレクトリ |
| Codex ディレクトリ | `~/.codex/` | Codex 設定ディレクトリ |
| Gemini ディレクトリ | `~/.gemini/` | Gemini CLI 設定ディレクトリ |
| OpenCode ディレクトリ | `~/.opencode/` | OpenCode 設定ディレクトリ |
| OpenCode ディレクトリ | `~/.config/opencode/` | OpenCode 設定ディレクトリ |
| OpenClaw ディレクトリ | `~/.openclaw/` | OpenClaw 設定ディレクトリ |
| Hermes ディレクトリ | `~/.hermes/` | Hermes 設定ディレクトリ |
> **注意**:ディレクトリを変更した後はアプリの再起動が必要で、対応する CLI ツールも同じディレクトリを設定する必要があります。
@@ -133,14 +135,15 @@ CC Switch 自体のデータの保存場所で、デフォルトは `~/.cc-switc
### 設定のエクスポート
「エクスポート」ボタンをクリックして、以下の内容を含むバックアップファイルを保存します:
「エクスポート」ボタンをクリックして、以下の内容を含む SQL バックアップファイルを保存します:
- すべてのプロバイダー設定
- MCP サーバー設定
- Prompts プリセット
- 使用量ログ
- アプリ設定
バックアップファイルは JSON 形式で、テキストエディタで確認できます。
エクスポートされるファイル名の形式は `cc-switch-export-{timestamp}.sql`す。
### 設定のインポート
+1 -1
View File
@@ -88,7 +88,7 @@ Codex プリセットは上流プロトコルにより 2 種類に分かれま
|----------|------|
| DeepSeek | DeepSeek モデル |
| Zhipu GLM / GLM en | Zhipu AI の GLM モデル |
| Kimi | Moonshot Kimi モデル |
| Kimi / Kimi For Coding | Moonshot Kimi モデル |
| MiniMax / MiniMax en | MiniMax モデル |
| StepFun / StepFun en | StepFun Step モデル |
| Baidu Qianfan Coding Plan | 百度千帆コーディングプラン |
+7 -5
View File
@@ -103,15 +103,16 @@ SSE プロトコルでサーバーと通信し、リアルタイムプッシュ
| Claude | Claude Code に同期 | `~/.claude.json``mcpServers` |
| Codex | Codex に同期 | `~/.codex/config.toml``[mcp_servers]` |
| Gemini | Gemini CLI に同期 | `~/.gemini/settings.json``mcpServers` |
| OpenCode | OpenCode に同期 | `~/.opencode/config.json``mcpServers` |
| OpenCode | OpenCode に同期 | `~/.config/opencode/opencode.json``mcp` |
| Hermes | Hermes に同期 | `~/.hermes/config.yaml``mcp_servers` |
> **注意**OpenClaw は現在 MCP サーバー管理に対応していません。MCP 機能は現在 Claude、Codex、Gemini、OpenCode の 4 つのアプリのみサポートしています。
> **注意**OpenClaw と Claude Desktop は現在 CC Switch MCP 同期に対応していません。MCP 機能は Claude、Codex、Gemini、OpenCode、Hermes に対応しています。
### スイッチの動作
あるアプリのスイッチをオンにすると、CC Switch は以下を実行します:
1. **データベースの更新**:サーバーの `apps.claude/codex/gemini/opencode` のステータスを `true` に設定
1. **データベースの更新**:サーバーの `apps.claude/codex/gemini/opencode/hermes` のステータスを `true` に設定
2. **Live 設定に同期**:サーバー設定を対応アプリの設定ファイルに書き込み
3. **即時反映**:次回 CLI ツール起動時に新しい MCP サーバーが自動的にロード
@@ -128,7 +129,8 @@ MCP サーバーの同期は、対応アプリがインストールされてい
- **Claude**`~/.claude/` ディレクトリまたは `~/.claude.json` ファイルが存在する必要あり
- **Codex**`~/.codex/` ディレクトリが存在する必要あり
- **Gemini**`~/.gemini/` ディレクトリが存在する必要あり
- **OpenCode**`~/.opencode/` ディレクトリが存在する必要あり
- **OpenCode**`~/.config/opencode/` ディレクトリが存在する必要あり
- **Hermes**`~/.hermes/` ディレクトリが存在する必要あり
> **ヒント**:CLI ツールがインストールされていない場合、対応するスイッチをオンにしてもエラーにはなりませんが、設定は書き込まれません。
@@ -154,7 +156,7 @@ MCP サーバーの同期は、対応アプリがインストールされてい
CLI ツールで既に MCP サーバーを設定している場合、CC Switch にインポートできます:
1. 「インポート」ボタンをクリック
2. インポートするアプリを選択(Claude/Codex/Gemini/OpenCode
2. インポートするアプリを選択(Claude/Codex/Gemini/OpenCode/Hermes
3. CC Switch が既存の設定を読み取ってインポート
## 設定ファイル形式
@@ -81,8 +81,7 @@ CC Switch を使用すると:
| Claude | `~/.claude/CLAUDE.md` |
| Codex | `~/.codex/AGENTS.md` |
| Gemini | `~/.gemini/GEMINI.md` |
| OpenCode | `~/.opencode/AGENTS.md` |
| OpenClaw | `~/.openclaw/AGENTS.md` |
| OpenCode | `~/.config/opencode/AGENTS.md` |
## プリセットの編集
@@ -141,7 +140,6 @@ Prompts はアプリごとに個別に管理されます:
- Codex に切り替えると、Codex のプリセットが表示
- Gemini に切り替えると、Gemini のプリセットが表示
- OpenCode に切り替えると、OpenCode のプリセットが表示
- OpenClaw に切り替えると、OpenClaw のプリセットが表示
複数のアプリで同じプロンプトを使用する場合は、それぞれで作成する必要があります。
@@ -12,18 +12,17 @@ Skills は再利用可能な機能拡張で、AI ツールに特定分野の専
## 対応アプリ
Skills 機能は以下の 4 つのアプリに対応しています:
Skills 機能は以下の 5 つのアプリに対応しています:
- **Claude Code**
- **Codex**
- **Gemini CLI**
- **OpenCode**
- **Hermes**
## Skills ページを開く
上部ナビゲーションバーの **Skills** ボタンをクリックします。
> 注意:Skills ボタンはすべてのアプリモードで表示されます。
選択中のアプリが Skills に対応している場合、上部ナビゲーションバーの **Skills** ボタンをクリックします。
## ページ概要
@@ -93,7 +92,8 @@ CC Switch は強力な検索とフィルタリング機能を提供していま
| Claude | `~/.claude/skills/` |
| Codex | `~/.codex/skills/` |
| Gemini | `~/.gemini/skills/` |
| OpenCode | `~/.opencode/skills/` |
| OpenCode | `~/.config/opencode/skills/` |
| Hermes | `~/.hermes/skills/` |
### インストール内容
@@ -119,7 +119,7 @@ CC Switch は強力な検索とフィルタリング機能を提供していま
### アンインストールの効果
- **自動バックアップ**:削除前にスキルが `~/.cc-switch/skill-backups/` にバックアップされる
- すべてのアプリディレクトリ(Claude、Codex、Gemini、OpenCode)からスキルを削除
- すべてのアプリディレクトリ(Claude、Codex、Gemini、OpenCode、Hermes)からスキルを削除
- SSOT ディレクトリ(`~/.cc-switch/skills/`)からスキルを削除
- データベースからスキルレコードを削除
+8 -2
View File
@@ -215,9 +215,11 @@ Token 使用量の変化を表示:
料金を照合する前に、CC Switch はリクエスト内のモデル ID を正規化します:
- 最後の `/` より前の接頭辞を削除
- `:` 以降の接尾辞を削除
- 最後の `/` より前の接頭辞を削除し、小文字に変換
- `:` 以降の接尾辞を削除し、末尾の `[1m]` を削除
- `@``-` に置換
- 一般的なラッパー接頭辞、バージョン接尾辞、日付接尾辞(`-YYYY-MM-DD``-YYYYMMDD`)を削除
- 一部のモデルファミリーでは、短い ID からバージョン付き価格エントリに照合できます
料金設定では、リクエスト内の完全な元のモデル名ではなく、正規化後のモデル ID を入力してください。
@@ -226,6 +228,10 @@ Token 使用量の変化を表示:
| `stepfun-ai/step-3.5-flash` | `step-3.5-flash` | プロバイダー接頭辞を削除 |
| `moonshotai/kimi-k2-0905:exa` | `kimi-k2-0905` | 接頭辞と `:` 以降を削除 |
| `gpt-5.2-codex@low` | `gpt-5.2-codex-low` | `@``-` に置換 |
| `OpenAI/GPT-5.5-2026-05-14` | `gpt-5.5` | 接頭辞と日付接尾辞を削除 |
| `anthropic/claude-opus-4.8` | `claude-opus-4-8` | 接頭辞を削除し、ドット形式に照合 |
| `global.anthropic.claude-opus-4-8-v1:0` | `claude-opus-4-8` | ラッパー接頭辞、バージョン接尾辞、`:` 以降を削除 |
| `claude-haiku-4-5` | `claude-haiku-4-5-20251001` | 短い ID からバージョン付き価格に照合 |
### 操作
+35 -12
View File
@@ -16,7 +16,7 @@
├── settings.json # デバイスレベルの設定
├── skills/ # スキル SSOT ディレクトリ
├── skill-backups/ # スキルバックアップ(アンインストール時に作成)
└── db_backup_*.db # データベースバックアップ
└── backups/ # データベースバックアップ
```
### データベースの内容
@@ -51,7 +51,8 @@
"codexConfigDir": null,
"geminiConfigDir": null,
"opencodeConfigDir": null,
"openclawConfigDir": null
"openclawConfigDir": null,
"hermesConfigDir": null
}
```
@@ -196,17 +197,41 @@ GEMINI_MODEL=gemini-pro
### 設定ディレクトリ
デフォルト:`~/.opencode/`
デフォルト:`~/.config/opencode/`
### 主要ファイル
```
~/.opencode/
├── config.json # メイン設定ファイル
~/.config/opencode/
├── opencode.json # メイン設定ファイル
├── AGENTS.md # システムプロンプト
└── skills/ # スキルディレクトリ
└── ...
```
## Hermes の設定
### 設定ディレクトリ
デフォルト:`~/.hermes/`
### 主要ファイル
```
~/.hermes/
├── config.yaml # メイン設定、プロバイダー、MCP 設定
├── .env # API キーとシークレット
├── SOUL.md # Profile identity/persona
├── memories/
│ ├── MEMORY.md # エージェント記憶
│ └── USER.md # ユーザープロファイル記憶
├── skills/ # 有効なスキルディレクトリ
├── state.db # SQLite セッションデータベース
└── sessions/ # Gateway transcript と任意の JSON snapshot
```
### config.yaml
Hermes は YAML 設定を使用します。CC Switch は MCP サーバーを `mcp_servers` に書き込み、編集可能なプロバイダーエントリを `custom_providers` に書き込み、Hermes の `providers` dict にある読み取り専用エントリを読み取り、プロバイダー切り替え時に `model.provider` / `model.default` を更新します。
## OpenClaw の設定
@@ -219,7 +244,6 @@ GEMINI_MODEL=gemini-pro
```
~/.openclaw/
├── openclaw.json # メイン設定ファイル(JSON5 形式)
├── AGENTS.md # システムプロンプト
└── skills/ # スキルディレクトリ
└── ...
```
@@ -246,18 +270,17 @@ OpenClaw は JSON5 形式の設定ファイルを使用し、主に以下のセ
env: {
ANTHROPIC_API_KEY: "sk-..."
},
// Agent デフォルトモデル設定
// Agent デフォルト設定
agents: {
defaults: {
model: {
primary: "provider/model"
}
},
workspace: "~/.openclaw/workspace"
}
},
// ツール設定
tools: {},
// ワークスペースファイル設定
workspace: {}
tools: {}
}
```
@@ -267,7 +290,7 @@ OpenClaw は JSON5 形式の設定ファイルを使用し、主に以下のセ
| `env` | 環境変数設定 |
| `agents.defaults` | Agent デフォルトモデル設定 |
| `tools` | ツール設定 |
| `workspace` | ワークスペースファイル管理 |
| `agents.defaults.workspace` | ワークスペースディレクトリパス |
## 設定の優先順位
+1 -1
View File
@@ -144,7 +144,7 @@ chmod +x CC-Switch-*.AppImage
- バージョンの非互換性
**解決方法**
1. ファイルが CC Switch からエクスポートされた JSON ファイルであることを確認
1. ファイルが CC Switch からエクスポートされた SQL バックアップファイルであることを確認
2. ファイル内容が完全であるか確認
3. テキストエディタで開いてフォーマットを確認
+8 -8
View File
@@ -106,15 +106,15 @@ CC Switch ユーザーマニュアル
## バージョン情報
- ドキュメントバージョン:v3.15.0
- 最終更新:2026-05-16
- CC Switch v3.15.0+ 対応
- ドキュメントバージョン:v3.16.0
- 最終更新:2026-05-29
- CC Switch v3.16.0+ 対応
### v3.15.0 の注目機能
### v3.16.0 の注目機能
- **Claude Desktop の一等管理パネル**:サードパーティプロバイダー、直結 / モデルマッピングの 2 モード、Copilot / Codex OAuth 再利用、3P profile 書き込みに対応 — 詳細は [2.6 Claude Desktop](./2-providers/2.6-claude-desktop.md)
- **役割別モデルマッピング**Sonnet / Opus / Haiku ルートと `supports1m` フラグで Claude Desktop のモデル検証に対応
- **Claude Desktop ローカルルーティング**:変換が必要なプロバイダー向けに `127.0.0.1:15721/claude-desktop` のローカルゲートウェイを提供
- **Codex Chat Completions ルーティング**DeepSeek、Kimi、GLM、MiniMax など Chat 専用プロバイダーを Codex で利用可能 — 詳細は [2.1 プロバイダーの追加](./2-providers/2.1-add.md)
- **管理対象 CLI ツールのライフサイクル**:設定 / About で Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes のインストール、更新、一括更新、診断に対応 — 詳細は [1.5 個人設定](./1-getting-started/1.5-settings.md)
- **プロバイダーとモデルマトリクス更新**:提携プリセットを追加し、既定モデルと価格表を更新。Claude Opus は 4.8、該当する GPT 既定値は 5.5 に更新
- **ルーティング対応バッジ**Claude Code / Codex のプロバイダーカードで Local Routing 対応可否を確認可能
- **Codex OAuth ライブモデル検出**ChatGPT Codex 系プロバイダーは必要に応じて ChatGPT バックエンドから利用可能モデルを取得
- **フィルター連動 Usage Hero**:キャッシュ正規化後の実消費 Token とキャッシュヒット率を表示し、日付 / プロバイダー / モデルフィルターに追従 — 詳細は [4.4 使用量統計](./4-proxy/4.4-usage.md)
@@ -124,7 +124,7 @@ CC Switch ユーザーマニュアル
- **アプリ別トレイサブメニュー**Claude / Codex / Gemini のサブメニューで現在のプロバイダーと使用量サマリーを確認可能 — 詳細は [2.2 プロバイダーの切り替え](./2-providers/2.2-switch.md)
- **Skills の発見と一括更新**:SHA-256 ハッシュによる更新検出、一括更新、skills.sh 公式レジストリ検索 — 詳細は [3.3 Skills スキル管理](./3-extensions/3.3-skills.md)
- **完全URLエンドポイントモード**:高度なオプションで `base_url` を完全なアップストリームエンドポイントとして扱う — 詳細は [2.1 プロバイダーの追加](./2-providers/2.1-add.md)
- **OpenCode / OpenClaw ストリームチェック対応**Stream Check は Claude / Codex / Gemini / OpenCode / OpenClaw をカバー — 詳細は [4.5 モデルテスト](./4-proxy/4.5-model-test.md)
- **OpenCode / OpenClaw / Hermes ストリームチェック対応**Stream Check は Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes をカバー — 詳細は [4.5 モデルテスト](./4-proxy/4.5-model-test.md)
## コントリビュート
@@ -2,7 +2,7 @@
## 什么是 CC Switch
CC Switch 是一款跨平台桌面应用,专为使用 AI 编程工具的开发者设计。它帮助你统一管理 **Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw** 和 **Hermes** 等受管应用的配置。
CC Switch 是一款跨平台桌面应用,专为使用 AI 工具的开发者设计。它帮助你统一管理 **Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw** 和 **Hermes** 等受管应用的配置。
## 解决什么问题
@@ -45,7 +45,7 @@ CC Switch 通过统一的界面解决这些问题。
| **Codex** | OpenAI 的代码生成工具 |
| **Gemini CLI** | Google 的 AI 命令行工具 |
| **OpenCode** | 开源 AI 编程终端工具 |
| **OpenClaw** | 开源 AI 编程助手(多供应商网关) |
| **OpenClaw** | 开源 AI 助手(多供应商网关) |
| **Hermes** | Hermes Agent,支持供应商、MCP、Skills 和 Memory 管理 |
## 支持的平台
@@ -12,7 +12,7 @@
| ② | 设置按钮 | 打开设置页面(快捷键 `Cmd/Ctrl + ,` |
| ③ | 代理开关 | 启动/停止本地代理服务 |
| ④ | 应用切换器 | 切换 Claude / Claude Desktop / Codex / Gemini / OpenCode / OpenClaw / Hermes |
| ⑤ | 功能区 | Skills / Prompts / MCP 入口 |
| ⑤ | 功能区 | 当前应用支持的功能入口 |
| ⑥ | 添加按钮 | 添加新供应商 |
### 应用切换器
@@ -33,9 +33,9 @@
| 按钮 | 功能 | 可见条件 |
|------|------|----------|
| Skills | 技能扩展管理 | 始终可见 |
| Prompts | 系统提示词管理 | 始终可见 |
| MCP | MCP 服务器管理 | 始终可见 |
| Skills | 技能扩展管理 | Claude / Codex / Gemini / OpenCode / Hermes |
| Prompts | 系统提示词管理 | Claude / Codex / Gemini / OpenCode |
| MCP | MCP 服务器管理 | Claude / Codex / Gemini / OpenCode / Hermes |
## 供应商卡片
@@ -113,11 +113,12 @@ CC Switch 在系统托盘显示图标,提供快速操作入口。
### 多语言支持
托盘菜单支持种语言,根据设置自动切换:
托盘菜单支持种语言,根据设置自动切换:
| 语言 | 打开主界面 | 退出 |
|------|-----------|------|
| 中文 | 打开主界面 | 退出 |
| 简体中文 | 打开主界面 | 退出 |
| 繁體中文 | 開啟主介面 | 退出 |
| English | Open main window | Quit |
| 日本語 | メインウィンドウを開く | 終了 |
@@ -147,7 +148,7 @@ CC Switch 在系统托盘显示图标,提供快速操作入口。
### 通用 Tab
- 语言设置(中文/English/日本語)
- 语言设置(简体中文/繁體中文/English/日本語)
- 主题设置(跟随系统/浅色/深色)
- 窗口行为(开机自启、关闭行为)
@@ -9,11 +9,12 @@
## 语言设置
CC Switch 支持种语言:
CC Switch 支持种语言:
| 语言 | 说明 |
| -------- | -------- |
| 简体中文 | 默认语言 |
| 繁體中文 | 繁体中文界面 |
| English | 英文界面 |
| 日本語 | 日文界面 |
@@ -124,8 +125,9 @@ CC Switch 自身数据的存储位置,默认为 `~/.cc-switch/`。
| Claude 目录 | `~/.claude/` | Claude Code 配置目录 |
| Codex 目录 | `~/.codex/` | Codex 配置目录 |
| Gemini 目录 | `~/.gemini/` | Gemini CLI 配置目录 |
| OpenCode 目录 | `~/.opencode/` | OpenCode 配置目录 |
| OpenCode 目录 | `~/.config/opencode/` | OpenCode 配置目录 |
| OpenClaw 目录 | `~/.openclaw/` | OpenClaw 配置目录 |
| Hermes 目录 | `~/.hermes/` | Hermes 配置目录 |
> ⚠️ **注意**:修改目录后需要重启应用,且对应的 CLI 工具也需要配置相同的目录。
@@ -133,14 +135,15 @@ CC Switch 自身数据的存储位置,默认为 `~/.cc-switch/`。
### 导出配置
点击「导出」按钮,保存包含以下内容的备份文件:
点击「导出」按钮,保存包含以下内容的 SQL 备份文件:
- 所有供应商配置
- MCP 服务器配置
- Prompts 预设
- 用量日志
- 应用设置
备份文件格式为 JSON,可以用文本编辑器查看
导出文件格式为 `cc-switch-export-{timestamp}.sql`
### 导入配置
+1 -1
View File
@@ -88,7 +88,7 @@ Codex 预设按上游协议分两类。
|----------|------|
| DeepSeek | DeepSeek 模型 |
| 智谱 GLM / GLM en | 智谱 AI 的 GLM 模型 |
| Kimi | Moonshot Kimi 模型 |
| Kimi / Kimi For Coding | Moonshot Kimi 模型 |
| MiniMax / MiniMax en | MiniMax 模型 |
| StepFun / StepFun en | 阶跃星辰 Step 模型 |
| 百度千帆 Coding Plan | 百度千帆编程套餐 |
+7 -5
View File
@@ -103,15 +103,16 @@ MCP (Model Context Protocol) 是一种协议,允许 AI 工具访问外部数
| Claude | 同步到 Claude Code | `~/.claude.json``mcpServers` |
| Codex | 同步到 Codex | `~/.codex/config.toml``[mcp_servers]` |
| Gemini | 同步到 Gemini CLI | `~/.gemini/settings.json``mcpServers` |
| OpenCode | 同步到 OpenCode | `~/.opencode/config.json``mcpServers` |
| OpenCode | 同步到 OpenCode | `~/.config/opencode/opencode.json``mcp` |
| Hermes | 同步到 Hermes | `~/.hermes/config.yaml``mcp_servers` |
> ⚠️ **注意**OpenClaw 暂不支持 MCP 服务器管理。MCP 功能目前仅支持 Claude、Codex、GeminiOpenCode 四个应用
> ⚠️ **注意**OpenClaw 和 Claude Desktop 暂不支持 CC Switch MCP 同步。MCP 功能支持 Claude、Codex、GeminiOpenCode 和 Hermes
### 开关实现机制
当开启某个应用的开关时,CC Switch 会:
1. **更新数据库**:将服务器的 `apps.claude/codex/gemini/opencode` 状态设为 `true`
1. **更新数据库**:将服务器的 `apps.claude/codex/gemini/opencode/hermes` 状态设为 `true`
2. **同步到 Live 配置**:将服务器配置写入对应应用的配置文件
3. **即时生效**:下次启动 CLI 工具时自动加载新的 MCP 服务器
@@ -128,7 +129,8 @@ MCP 服务器同步仅在对应应用已安装时执行:
- **Claude**:需存在 `~/.claude/` 目录或 `~/.claude.json` 文件
- **Codex**:需存在 `~/.codex/` 目录
- **Gemini**:需存在 `~/.gemini/` 目录
- **OpenCode**:需存在 `~/.opencode/` 目录
- **OpenCode**:需存在 `~/.config/opencode/` 目录
- **Hermes**:需存在 `~/.hermes/` 目录
> 💡 **提示**:如果某个 CLI 工具未安装,开启对应开关不会报错,但配置不会写入。
@@ -154,7 +156,7 @@ MCP 服务器同步仅在对应应用已安装时执行:
如果你已经在 CLI 工具中配置了 MCP 服务器,可以导入到 CC Switch:
1. 点击「导入」按钮
2. 选择要导入的应用(Claude/Codex/Gemini/OpenCode
2. 选择要导入的应用(Claude/Codex/Gemini/OpenCode/Hermes
3. CC Switch 会读取现有配置并导入
## 配置文件格式
@@ -81,8 +81,7 @@ Prompts 功能用于管理系统提示词预设。系统提示词会影响 AI
| Claude | `~/.claude/CLAUDE.md` |
| Codex | `~/.codex/AGENTS.md` |
| Gemini | `~/.gemini/GEMINI.md` |
| OpenCode | `~/.opencode/AGENTS.md` |
| OpenClaw | `~/.openclaw/AGENTS.md` |
| OpenCode | `~/.config/opencode/AGENTS.md` |
## 编辑预设
@@ -141,7 +140,6 @@ Prompts 是按应用分开管理的:
- 切换到 Codex 时,显示 Codex 的预设
- 切换到 Gemini 时,显示 Gemini 的预设
- 切换到 OpenCode 时,显示 OpenCode 的预设
- 切换到 OpenClaw 时,显示 OpenClaw 的预设
如需在多个应用使用相同的提示词,需要分别创建。
@@ -12,18 +12,17 @@ Skills 是可复用的能力扩展,让 AI 工具获得特定领域的专业能
## 支持的应用
Skills 功能支持所有四种应用:
Skills 功能支持种应用:
- **Claude Code**
- **Codex**
- **Gemini CLI**
- **OpenCode**
- **Hermes**
## 打开 Skills 页面
点击顶部导航栏的 **Skills** 按钮。
> 注意:Skills 按钮在所有应用模式下均可见。
当当前应用支持 Skills 时,点击顶部导航栏的 **Skills** 按钮。
## 页面概览
@@ -93,7 +92,8 @@ CC Switch 提供强大的搜索和过滤功能:
| Claude | `~/.claude/skills/` |
| Codex | `~/.codex/skills/` |
| Gemini | `~/.gemini/skills/` |
| OpenCode | `~/.opencode/skills/` |
| OpenCode | `~/.config/opencode/skills/` |
| Hermes | `~/.hermes/skills/` |
### 安装内容
@@ -119,7 +119,7 @@ CC Switch 提供强大的搜索和过滤功能:
### 卸载效果
- **自动备份**:删除前,技能会被备份到 `~/.cc-switch/skill-backups/`
- 从所有应用目录(Claude、Codex、Gemini、OpenCode)移除技能
- 从所有应用目录(Claude、Codex、Gemini、OpenCode、Hermes)移除技能
- 从 SSOT 目录(`~/.cc-switch/skills/`)移除技能
- 从数据库删除技能记录
+8 -2
View File
@@ -215,9 +215,11 @@ v3.15.0 起,用量页顶部改为筛选驱动的 Hero 卡。切换日期范围
在匹配定价前,CC Switch 会先对请求中的模型 ID 做标准化处理:
- 去掉最后一个 `/` 之前的前缀
- 去掉 `:` 之后的后缀
- 去掉最后一个 `/` 之前的前缀,并转成小写
- 去掉 `:` 之后的后缀,去掉末尾的 `[1m]`
- 将 `@` 替换为 `-`
- 去掉常见包装前缀、版本后缀、日期后缀(`-YYYY-MM-DD``-YYYYMMDD`
- 部分模型族支持短 ID 匹配带版本的定价项
因此,在定价配置中请填写清洗后的模型 ID,而不是请求里的完整原始模型名。
@@ -226,6 +228,10 @@ v3.15.0 起,用量页顶部改为筛选驱动的 Hero 卡。切换日期范围
| `stepfun-ai/step-3.5-flash` | `step-3.5-flash` | 去掉供应商前缀 |
| `moonshotai/kimi-k2-0905:exa` | `kimi-k2-0905` | 去掉前缀和 `:` 后缀 |
| `gpt-5.2-codex@low` | `gpt-5.2-codex-low` | 将 `@` 替换为 `-` |
| `OpenAI/GPT-5.5-2026-05-14` | `gpt-5.5` | 去掉前缀和日期后缀 |
| `anthropic/claude-opus-4.8` | `claude-opus-4-8` | 去掉前缀并匹配点号格式 |
| `global.anthropic.claude-opus-4-8-v1:0` | `claude-opus-4-8` | 去掉包装前缀、版本后缀和 `:` 后缀 |
| `claude-haiku-4-5` | `claude-haiku-4-5-20251001` | 短 ID 匹配带版本定价 |
### 操作
+35 -12
View File
@@ -16,7 +16,7 @@
├── settings.json # 设备级设置
├── skills/ # 技能 SSOT 目录
├── skill-backups/ # 技能备份(卸载时创建)
└── db_backup_*.db # 数据库备份
└── backups/ # 数据库备份
```
### 数据库内容
@@ -51,7 +51,8 @@
"codexConfigDir": null,
"geminiConfigDir": null,
"opencodeConfigDir": null,
"openclawConfigDir": null
"openclawConfigDir": null,
"hermesConfigDir": null
}
```
@@ -196,17 +197,41 @@ GEMINI_MODEL=gemini-pro
### 配置目录
默认:`~/.opencode/`
默认:`~/.config/opencode/`
### 主要文件
```
~/.opencode/
├── config.json # 主配置文件
~/.config/opencode/
├── opencode.json # 主配置文件
├── AGENTS.md # 系统提示词
└── skills/ # 技能目录
└── ...
```
## Hermes 配置
### 配置目录
默认:`~/.hermes/`
### 主要文件
```
~/.hermes/
├── config.yaml # 主设置、供应商与 MCP 配置
├── .env # API keys 与 secrets
├── SOUL.md # Profile 身份/人格
├── memories/
│ ├── MEMORY.md # Agent 记忆
│ └── USER.md # 用户画像记忆
├── skills/ # 活跃技能目录
├── state.db # SQLite 会话数据库
└── sessions/ # Gateway 转录与可选 JSON 快照
```
### config.yaml
Hermes 使用 YAML 配置。CC Switch 将 MCP 服务器写入 `mcp_servers`,将可编辑的供应商条目写入 `custom_providers`,读取 Hermes `providers` 字典中的只读条目,并在切换供应商时更新 `model.provider` / `model.default`
## OpenClaw 配置
@@ -219,7 +244,6 @@ GEMINI_MODEL=gemini-pro
```
~/.openclaw/
├── openclaw.json # 主配置文件(JSON5 格式)
├── AGENTS.md # 系统提示词
└── skills/ # 技能目录
└── ...
```
@@ -246,18 +270,17 @@ OpenClaw 使用 JSON5 格式配置文件,主要包含以下部分:
env: {
ANTHROPIC_API_KEY: "sk-..."
},
// Agent 默认模型配置
// Agent 默认配置
agents: {
defaults: {
model: {
primary: "provider/model"
}
},
workspace: "~/.openclaw/workspace"
}
},
// 工具配置
tools: {},
// 工作区文件配置
workspace: {}
tools: {}
}
```
@@ -267,7 +290,7 @@ OpenClaw 使用 JSON5 格式配置文件,主要包含以下部分:
| `env` | 环境变量配置 |
| `agents.defaults` | Agent 默认模型设置 |
| `tools` | 工具配置 |
| `workspace` | 工作区文件管理 |
| `agents.defaults.workspace` | 工作区目录路径 |
## 配置优先级
+1 -1
View File
@@ -144,7 +144,7 @@ chmod +x CC-Switch-*.AppImage
- 版本不兼容
**解决方法**
1. 确认文件是 CC Switch 导出的 JSON 文件
1. 确认文件是 CC Switch 导出的 SQL 备份文件
2. 检查文件内容是否完整
3. 尝试用文本编辑器打开检查格式
+8 -8
View File
@@ -106,15 +106,15 @@
## 版本信息
- 文档版本:v3.15.0
- 最后更新:2026-05-16
- 适用于 CC Switch v3.15.0+
- 文档版本:v3.16.0
- 最后更新:2026-05-29
- 适用于 CC Switch v3.16.0+
### v3.15.0 亮点
### v3.16.0 亮点
- **Claude Desktop 一等管理面板**:支持第三方供应商、直连 / 模型映射两种模式、Copilot / Codex OAuth 复用与 3P profile 写入 — 详见 [2.6 Claude Desktop](./2-providers/2.6-claude-desktop.md)
- **按角色的模型映射**:用 Sonnet / Opus / Haiku 路由和 `supports1m` 标志适配 Claude Desktop 的模型校验
- **Claude Desktop 本地路由**:通过 `127.0.0.1:15721/claude-desktop` 为需要转换的供应商提供本地网关
- **Codex Chat Completions 路由**DeepSeek、Kimi、GLM、MiniMax 等仅支持 Chat 协议的供应商可通过 Codex 使用 — 详见 [2.1 添加供应商](./2-providers/2.1-add.md)
- **托管 CLI 工具生命周期**:在设置 / 关于页安装、升级、全部升级并诊断 Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes — 详见 [1.5 个性化配置](./1-getting-started/1.5-settings.md)
- **供应商与模型矩阵刷新**:新增合作方预设,刷新默认模型与计费矩阵,Claude Opus 默认升级到 4.8,适用场景下 GPT 默认升级到 5.5
- **路由支持徽章**Claude Code / Codex 供应商卡片会标明是否支持 Local Routing,便于选择可代理的供应商
- **Codex OAuth 实时模型发现**ChatGPT Codex 类供应商按需从 ChatGPT 后端拉取最新模型列表
- **用量看板筛选驱动 Hero**:展示缓存归一化后的真实总 token 与缓存命中率,并跟随日期 / 供应商 / 模型筛选实时更新 — 详见 [4.4 用量统计](./4-proxy/4.4-usage.md)
@@ -124,7 +124,7 @@
- **托盘按应用分级菜单**Claude / Codex / Gemini 独立子菜单,标题展示当前供应商与可用用量摘要 — 详见 [2.2 切换供应商](./2-providers/2.2-switch.md)
- **Skills 发现与批量更新**:SHA-256 更新检测、批量更新、skills.sh 公共注册表搜索 — 详见 [3.3 Skills 技能管理](./3-extensions/3.3-skills.md)
- **完整 URL 端点模式**:高级选项支持将 base_url 视作完整上游端点 — 详见 [2.1 添加供应商](./2-providers/2.1-add.md)
- **OpenCode / OpenClaw 流式检测覆盖**Stream Check 面板覆盖 Claude / Codex / Gemini / OpenCode / OpenClaw — 详见 [4.5 模型检查](./4-proxy/4.5-model-test.md)
- **OpenCode / OpenClaw / Hermes 流式检测覆盖**Stream Check 面板覆盖 Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes — 详见 [4.5 模型检查](./4-proxy/4.5-model-test.md)
## 贡献
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cc-switch",
"version": "3.16.1",
"version": "3.16.3",
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
"type": "module",
"scripts": {
+2 -1
View File
@@ -735,7 +735,7 @@ dependencies = [
[[package]]
name = "cc-switch"
version = "3.16.1"
version = "3.16.3"
dependencies = [
"anyhow",
"arboard",
@@ -749,6 +749,7 @@ dependencies = [
"dirs 5.0.1",
"flate2",
"futures",
"hmac",
"http",
"http-body",
"http-body-util",
+3 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "cc-switch"
version = "3.16.1"
version = "3.16.3"
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
authors = ["Jason Young"]
license = "MIT"
@@ -77,6 +77,7 @@ indexmap = { version = "2", features = ["serde"] }
rust_decimal = "1.33"
uuid = { version = "1.11", features = ["v4"] }
sha2 = "0.10"
hmac = "0.12"
json5 = "0.4"
json-five = "0.3.1"
@@ -88,7 +89,7 @@ webkit2gtk = { version = "2.0.1", features = ["v2_16"] }
[target.'cfg(target_os = "windows")'.dependencies]
winreg = "0.52"
windows-sys = { version = "0.61", features = ["Win32_Globalization"] }
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_UI_Shell"] }
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.5"
+243 -22
View File
@@ -60,6 +60,16 @@ pub const DEFAULT_PROXY_ROUTES: &[ClaudeDesktopDefaultRoute] = &[
env_key: "ANTHROPIC_DEFAULT_HAIKU_MODEL",
supports_1m: true,
},
// fable 置于末尾:next_catalog_safe_route_id 给非安全品牌 route 借用合法
// 角色名时仍按 sonnet→opus→haiku 顺序分配(向后兼容既有 catalog),不会把
// 无关品牌模型借用成 fable 顶配档名。UI 行序由前端 ROLE_ORDER 独立控制为
// Sonnet/Opus/Fable/Haiku(所有 proxy 路径都经 normalizeProxyRows 重排),
// 与此处物理顺序无关。
ClaudeDesktopDefaultRoute {
route_id: "claude-fable-5",
env_key: "ANTHROPIC_DEFAULT_FABLE_MODEL",
supports_1m: true,
},
];
#[derive(Debug, Clone)]
@@ -238,11 +248,16 @@ pub fn is_claude_safe_model_id(model: &str) -> bool {
// 角色前缀后必须还有实际模型标识,拒绝 claude-sonnet- 这类退化值
// (否则会写入 profile 并触发 Claude Desktop fail-all 拒收整组)。
["sonnet-", "opus-", "haiku-"].iter().any(|prefix| {
route_tail
.strip_prefix(prefix)
.is_some_and(|rest| !rest.is_empty())
})
// Claude Desktop 1.12603.1+ 的 fail-all validator 角色白名单已纳入 fable
// app.asar 内 ["sonnet","opus","haiku","fable","mythos"]),故 claude-fable-*
// 可安全写入 profile。mythos 官方未公开发布,暂不暴露给用户。
["sonnet-", "opus-", "haiku-", "fable-"]
.iter()
.any(|prefix| {
route_tail
.strip_prefix(prefix)
.is_some_and(|rest| !rest.is_empty())
})
}
fn inference_model_json(spec: &InferenceModelSpec) -> Value {
@@ -664,7 +679,7 @@ pub fn model_list_response(provider: &Provider) -> Result<Value, AppError> {
}
pub fn map_proxy_request_model(mut body: Value, provider: &Provider) -> Result<Value, AppError> {
let requested = body
let requested_raw = body
.get("model")
.and_then(Value::as_str)
.map(str::trim)
@@ -677,6 +692,7 @@ pub fn map_proxy_request_model(mut body: Value, provider: &Provider) -> Result<V
"Claude Desktop request is missing the model field",
)
})?;
let requested = strip_one_m_suffix_for_route_lookup(&requested_raw);
let routes = proxy_model_routes(provider)?;
let upstream_model = routes
@@ -685,30 +701,43 @@ pub fn map_proxy_request_model(mut body: Value, provider: &Provider) -> Result<V
.or_else(|| {
routes
.iter()
.find(|r| is_compatible_opus_route_alias(&r.route_id, &requested))
.find(|r| is_compatible_opus_route_alias(&r.route_id, requested))
})
.map(|route| route.upstream_model.clone())
.or_else(|| legacy_raw_route_upstream_model(provider, &requested))
.or_else(|| legacy_raw_route_upstream_model(provider, requested))
.or_else(|| {
// 角色关键词回落:Claude Desktop 的部分调用(如子 agent)会请求带发布
// 日期后缀的完整官方名(claude-haiku-4-5-20251001),与 manifest 暴露的
// 简短 route_id(claude-haiku-4-5)不精确相等。按 opus/haiku/sonnet 归类
// 到同档已配置路由,对齐 Claude Code model_mapper 的宽松匹配。
// 仅对 Claude Desktop 认可的安全模型名回落(排除 [1m] 标记等非法形式)。
if !is_claude_safe_model_id(&requested) {
// 简短 route_id(claude-haiku-4-5)不精确相等。按 opus/haiku/fable/sonnet
// 归类到同档已配置路由,对齐 Claude Code model_mapper 的宽松匹配。
// 匹配前已剥离本地 [1m] 标记;这里仍只对 Claude Desktop 认可的
// 安全模型名回落,避免非 Claude route 被误映射。
if !is_claude_safe_model_id(requested) {
return None;
}
let role = claude_role_keyword(&requested)?;
let role = claude_role_keyword(requested)?;
routes
.iter()
.find(|route| claude_role_keyword(&route.route_id) == Some(role))
// 老用户只配了 Sonnet/Opus/Haiku 三档时,fable 请求降级到 opus 档,
// 与官方安全分类器的降级方向一致,避免 route_unknown 硬错误。
// 用户一旦显式配置 fable 档,上面的精确角色匹配会优先命中。
.or_else(|| {
(role == "fable")
.then(|| {
routes
.iter()
.find(|route| claude_role_keyword(&route.route_id) == Some("opus"))
})
.flatten()
})
.map(|route| route.upstream_model.clone())
})
.ok_or_else(|| {
AppError::localized(
"claude_desktop.provider.route_unknown",
format!("Claude Desktop 模型路由未配置: {requested}"),
format!("Claude Desktop model route is not configured: {requested}"),
format!("Claude Desktop 模型路由未配置: {requested_raw}"),
format!("Claude Desktop model route is not configured: {requested_raw}"),
)
})?;
@@ -719,6 +748,18 @@ pub fn map_proxy_request_model(mut body: Value, provider: &Provider) -> Result<V
Ok(body)
}
fn strip_one_m_suffix_for_route_lookup(model: &str) -> &str {
let trimmed = model.trim();
let marker = ONE_M_CONTEXT_MARKER.as_bytes();
let bytes = trimmed.as_bytes();
if bytes.len() >= marker.len()
&& bytes[bytes.len() - marker.len()..].eq_ignore_ascii_case(marker)
{
return trimmed[..trimmed.len() - marker.len()].trim_end();
}
trimmed
}
fn legacy_raw_route_upstream_model(provider: &Provider, requested: &str) -> Option<String> {
provider
.meta
@@ -740,15 +781,17 @@ fn is_compatible_opus_route_alias(route_id: &str, requested: &str) -> bool {
)
}
/// 按角色关键词(opus / haiku / sonnet)归类一个 Claude 模型名/route_id。
/// 按角色关键词(opus / haiku / fable / sonnet)归类一个 Claude 模型名/route_id。
/// 仅在命中明确角色词时返回 Some,未知模型返回 None(不回落,保持精确报错语义)。
/// 与前端 `routeRoleFromId` 同序(opus → haiku → sonnet)。
/// 与前端 `routeRoleFromId` 同序(opus → haiku → fable → sonnet)。
fn claude_role_keyword(model: &str) -> Option<&'static str> {
let normalized = model.to_ascii_lowercase();
if normalized.contains("opus") {
Some("opus")
} else if normalized.contains("haiku") {
Some("haiku")
} else if normalized.contains("fable") {
Some("fable")
} else if normalized.contains("sonnet") {
Some("sonnet")
} else {
@@ -873,6 +916,11 @@ pub fn proxy_gateway_base_url_from_db(db: &Database) -> Result<String, AppError>
// get_proxy_config is async-tagged but its body is fully synchronous (rusqlite
// under a Mutex), so block_on cannot deadlock the calling thread.
let config = futures::executor::block_on(db.get_proxy_config())?;
if config.listen_port == 0 {
return Err(AppError::Config(
"Claude Desktop 代理地址需要真实监听端口;请先启动本地代理或使用固定端口".to_string(),
));
}
Ok(format!(
"{}{}",
proxy_origin_from_parts(&config.listen_address, config.listen_port),
@@ -1290,6 +1338,12 @@ mod tests {
Database::memory().expect("memory db")
}
fn set_proxy_port(db: &Database, port: u16) {
let mut config = crate::proxy::types::ProxyConfig::default();
config.listen_port = port;
futures::executor::block_on(db.update_proxy_config(config)).expect("update proxy config");
}
fn direct_provider(id: &str) -> Provider {
let mut provider = Provider::with_id(
id.to_string(),
@@ -1310,6 +1364,19 @@ mod tests {
provider
}
#[test]
fn proxy_gateway_base_url_rejects_unresolved_ephemeral_port() {
let db = test_db();
set_proxy_port(&db, 0);
let err = proxy_gateway_base_url_from_db(&db)
.expect_err("unresolved ephemeral port should not produce a :0 URL");
assert!(
err.to_string().contains("真实监听端口"),
"unexpected error: {err}"
);
}
fn official_provider() -> Provider {
let mut provider = Provider::with_id(
CLAUDE_DESKTOP_OFFICIAL_PROVIDER_ID.to_string(),
@@ -1612,6 +1679,127 @@ mod tests {
assert!(err.to_string().contains("gpt-5"));
}
#[test]
fn claude_desktop_proxy_maps_fable_to_opus_tier() {
// issue #4026/#4049:老用户只配 Sonnet/Opus/Haiku 三档、未显式配置
// fable 档时,fable 请求按官方分类器降级方向回落到 opus 档兜底。
let mut provider = proxy_provider("proxy");
provider
.meta
.as_mut()
.expect("meta")
.claude_desktop_model_routes = std::collections::HashMap::from([
(
"claude-opus-4-8".to_string(),
ClaudeDesktopModelRoute {
model: "upstream-opus".to_string(),
label_override: None,
supports_1m: Some(true),
},
),
(
"claude-sonnet-4-6".to_string(),
ClaudeDesktopModelRoute {
model: "upstream-sonnet".to_string(),
label_override: None,
supports_1m: Some(true),
},
),
]);
let mapped = map_proxy_request_model(
json!({"model": "claude-fable-5", "messages": []}),
&provider,
)
.expect("fable should fall back to the opus tier");
assert_eq!(mapped["model"], json!("upstream-opus"));
// 带 [1m] 标记与日期后缀的形态也应命中同一回落。
let mapped_one_m = map_proxy_request_model(
json!({"model": "claude-fable-5[1m]", "messages": []}),
&provider,
)
.expect("fable with [1m] marker should fall back to the opus tier");
assert_eq!(mapped_one_m["model"], json!("upstream-opus"));
let mapped_dated = map_proxy_request_model(
json!({"model": "claude-fable-5-20260609", "messages": []}),
&provider,
)
.expect("dated fable alias should fall back to the opus tier");
assert_eq!(mapped_dated["model"], json!("upstream-opus"));
}
#[test]
fn claude_desktop_proxy_fable_without_opus_route_still_errors() {
// 没有 opus 档可回落时保持精确报错语义,不静默落到其他档。
let mut provider = proxy_provider("proxy");
provider
.meta
.as_mut()
.expect("meta")
.claude_desktop_model_routes = std::collections::HashMap::from([(
"claude-sonnet-4-6".to_string(),
ClaudeDesktopModelRoute {
model: "upstream-sonnet".to_string(),
label_override: None,
supports_1m: Some(true),
},
)]);
let err = map_proxy_request_model(
json!({"model": "claude-fable-5", "messages": []}),
&provider,
)
.expect_err("fable without an opus route should fail");
assert!(err.to_string().contains("claude-fable-5"));
}
#[test]
fn claude_desktop_proxy_maps_fable_to_dedicated_route() {
// Desktop 1.12603.1+ fail-all 校验已放行 claude-fable-5,用户可显式配置
// 独立 fable 档;此时 fable 请求精确命中 fable 档,不再降级到 opus。
let mut provider = proxy_provider("proxy");
provider
.meta
.as_mut()
.expect("meta")
.claude_desktop_model_routes = std::collections::HashMap::from([
(
"claude-opus-4-8".to_string(),
ClaudeDesktopModelRoute {
model: "upstream-opus".to_string(),
label_override: None,
supports_1m: Some(true),
},
),
(
"claude-fable-5".to_string(),
ClaudeDesktopModelRoute {
model: "upstream-fable".to_string(),
label_override: None,
supports_1m: Some(true),
},
),
]);
// 精确匹配优先命中 fable 档
let mapped = map_proxy_request_model(
json!({"model": "claude-fable-5", "messages": []}),
&provider,
)
.expect("explicit fable route should match");
assert_eq!(mapped["model"], json!("upstream-fable"));
// 带日期后缀经角色关键词回落仍归 fable 档,而非降级 opus
let mapped_dated = map_proxy_request_model(
json!({"model": "claude-fable-5-20260609", "messages": []}),
&provider,
)
.expect("dated fable alias should map via fable role keyword");
assert_eq!(mapped_dated["model"], json!("upstream-fable"));
}
#[test]
fn claude_desktop_proxy_accepts_opus_4_7_4_8_alias_during_rollout() {
let mut provider = proxy_provider("proxy");
@@ -1820,15 +2008,48 @@ mod tests {
}
#[test]
fn claude_desktop_proxy_rejects_1m_suffix_route() {
let provider = proxy_provider("proxy");
fn claude_desktop_proxy_strips_1m_suffix_before_route_lookup() {
let mut provider = proxy_provider("proxy");
provider
.meta
.as_mut()
.expect("meta")
.claude_desktop_model_routes = std::collections::HashMap::from([
(
"claude-sonnet-4-6".to_string(),
ClaudeDesktopModelRoute {
model: "upstream-sonnet".to_string(),
label_override: None,
supports_1m: Some(true),
},
),
(
"claude-opus-4-8".to_string(),
ClaudeDesktopModelRoute {
model: "upstream-opus".to_string(),
label_override: None,
supports_1m: Some(true),
},
),
]);
let err = map_proxy_request_model(
let mapped = map_proxy_request_model(
json!({"model": "claude-opus-4-8[1m]", "messages": []}),
&provider,
)
.expect("compact 1M suffix should map to Opus route");
assert_eq!(mapped["model"], json!("upstream-opus"));
let mapped = map_proxy_request_model(
json!({"model": "claude-sonnet-4-6 [1M]", "messages": []}),
&provider,
)
.expect_err("1M suffix route should not be accepted");
assert!(err.to_string().contains("claude-sonnet-4-6 [1M]"));
.expect("spaced uppercase 1M suffix should map to Sonnet route");
assert_eq!(mapped["model"], json!("upstream-sonnet"));
let err = map_proxy_request_model(json!({"model": "gpt-5[1m]", "messages": []}), &provider)
.expect_err("non-Claude route should still fail after stripping 1M suffix");
assert!(err.to_string().contains("gpt-5[1m]"));
}
#[test]
+450 -13
View File
@@ -208,7 +208,10 @@ pub fn extract_codex_api_key(auth: Option<&Value>, config_text: Option<&str>) ->
/// Extract the upstream base URL from a Codex `config.toml` string.
///
/// Prefers the active `[model_providers.<model_provider>].base_url`, falling
/// back to a top-level `base_url` when no model provider is selected.
/// back to a top-level `base_url`. Deliberately never reads a non-active
/// `[model_providers.*]` section — the frontend `extractCodexBaseUrl`
/// (`getRecoverableBaseUrlAssignments`) excludes those too, and a leftover
/// section unrelated to the active provider must not leak into `{{baseUrl}}`.
pub fn extract_codex_base_url(config_text: &str) -> Option<String> {
let doc = config_text.parse::<toml::Value>().ok()?;
@@ -682,20 +685,18 @@ fn set_codex_model_catalog_json_field(
let mut doc = config_text
.parse::<DocumentMut>()
.map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
let generated_path = get_codex_model_catalog_path();
match catalog_path {
Some(path) => {
doc["model_catalog_json"] = toml_edit::value(path.to_string_lossy().as_ref());
Some(_) => {
doc["model_catalog_json"] = toml_edit::value(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME);
}
None => {
let should_remove = doc
.get("model_catalog_json")
.and_then(|item| item.as_str())
.map(|path| {
path == generated_path.to_string_lossy().as_ref()
|| Path::new(path).file_name().and_then(|name| name.to_str())
== Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME)
Path::new(path).file_name().and_then(|name| name.to_str())
== Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME)
})
.unwrap_or(false);
if should_remove {
@@ -768,7 +769,10 @@ pub fn read_codex_model_catalog_simplified_from_live() -> Result<Option<Value>,
/// Given `config.toml` text, resolve the on-disk path of the cc-switchowned
/// catalog file (returns `None` if `model_catalog_json` is absent or points at
/// a file we don't own). Relative paths fall back to `generated_path`.
fn resolve_cc_switch_catalog_path(config_text: &str, generated_path: &Path) -> Option<PathBuf> {
pub(crate) fn resolve_cc_switch_catalog_path(
config_text: &str,
generated_path: &Path,
) -> Option<PathBuf> {
if config_text.trim().is_empty() {
return None;
}
@@ -780,9 +784,8 @@ fn resolve_cc_switch_catalog_path(config_text: &str, generated_path: &Path) -> O
.filter(|s| !s.is_empty())?;
let referenced_path = Path::new(catalog_path_str);
let is_cc_switch_owned = catalog_path_str == generated_path.to_string_lossy().as_ref()
|| referenced_path.file_name().and_then(|name| name.to_str())
== Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME);
let is_cc_switch_owned = referenced_path.file_name().and_then(|name| name.to_str())
== Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME);
if !is_cc_switch_owned {
return None;
}
@@ -1040,16 +1043,197 @@ pub fn read_codex_live_settings() -> Result<Value, AppError> {
Ok(json!({ "auth": auth, "config": cfg_text }))
}
/// `[model_providers.custom]` entry that makes an official (ChatGPT OAuth)
/// provider behave like Codex's built-in `openai` entry while running under
/// the shared custom id: `requires_openai_auth` routes auth to the ChatGPT
/// login in `auth.json` (base_url then defaults to the official Codex
/// backend), `name = "OpenAI"` keeps Codex's `is_openai()` feature gates
/// (web search, remote compaction), and `supports_websockets` restores the
/// built-in default that custom entries otherwise lose.
fn codex_unified_official_provider_table() -> toml_edit::Table {
let mut table = toml_edit::Table::new();
table["name"] = toml_edit::value("OpenAI");
table["requires_openai_auth"] = toml_edit::value(true);
table["supports_websockets"] = toml_edit::value(true);
table["wire_api"] = toml_edit::value("responses");
table
}
fn table_matches_codex_unified_official_provider(table: &toml_edit::Table) -> bool {
table.len() == 4
&& table.get("name").and_then(|item| item.as_str()) == Some("OpenAI")
&& table
.get("requires_openai_auth")
.and_then(|item| item.as_bool())
== Some(true)
&& table
.get("supports_websockets")
.and_then(|item| item.as_bool())
== Some(true)
&& table.get("wire_api").and_then(|item| item.as_str()) == Some("responses")
}
/// 统一 Codex 会话历史:把官方供应商的 live 配置改写为以共享的
/// `custom` model_provider 标识运行(认证仍走 `auth.json` 的 ChatGPT 登录),
/// 使开关开启后创建的官方会话与第三方会话共用同一个 resume 历史桶。
///
/// 两种情况拒绝注入、原样返回:
/// - 配置已有显式 `model_provider`:用户手工指定的路由不被覆盖;
/// - 配置已有形态不同的 `[model_providers.custom]` 表:设置 `model_provider`
/// 会激活这张我们不认识的表(可能带第三方 base_url/token,会把 ChatGPT
/// OAuth 流量路由到错误后端),宁可让开关对该配置不生效。
pub fn inject_codex_unified_session_bucket(config_text: &str) -> Result<String, AppError> {
let mut doc = config_text
.parse::<DocumentMut>()
.map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
if doc.get("model_provider").is_some() {
return Ok(config_text.to_string());
}
let existing_custom_conflicts = doc
.get("model_providers")
.and_then(|item| item.as_table())
.and_then(|providers| providers.get(CC_SWITCH_CODEX_MODEL_PROVIDER_ID))
.and_then(|item| item.as_table())
.is_some_and(|table| !table_matches_codex_unified_official_provider(table));
if existing_custom_conflicts {
log::warn!(
"官方 Codex 配置已存在自定义 [model_providers.custom],跳过统一会话路由注入以避免激活未知路由"
);
return Ok(config_text.to_string());
}
doc["model_provider"] = toml_edit::value(CC_SWITCH_CODEX_MODEL_PROVIDER_ID);
if doc.get("model_providers").is_none() {
let mut parent = toml_edit::Table::new();
parent.set_implicit(true);
doc["model_providers"] = toml_edit::Item::Table(parent);
}
if let Some(providers) = doc["model_providers"].as_table_mut() {
if !providers.contains_key(CC_SWITCH_CODEX_MODEL_PROVIDER_ID) {
providers.insert(
CC_SWITCH_CODEX_MODEL_PROVIDER_ID,
toml_edit::Item::Table(codex_unified_official_provider_table()),
);
}
}
Ok(doc.to_string())
}
/// `inject_codex_unified_session_bucket` 的反向操作:从配置文本里剥掉注入的
/// 统一会话路由,保证切换回填不会把它带进数据库的存储配置(关闭开关后
/// 切换即可完全还原)。仅当形态与注入产物完全一致时才剥离;第三方模板和
/// 用户自定义的 `custom` 条目(带 base_url 等差异字段)原样保留。
pub fn strip_codex_unified_session_bucket(config_text: &str) -> Result<String, AppError> {
if !config_text.contains("model_provider") {
return Ok(config_text.to_string());
}
let mut doc = config_text
.parse::<DocumentMut>()
.map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
if doc.get("model_provider").and_then(|item| item.as_str())
!= Some(CC_SWITCH_CODEX_MODEL_PROVIDER_ID)
{
return Ok(config_text.to_string());
}
let matches_injected = doc
.get("model_providers")
.and_then(|item| item.as_table())
.and_then(|providers| providers.get(CC_SWITCH_CODEX_MODEL_PROVIDER_ID))
.and_then(|item| item.as_table())
.is_some_and(table_matches_codex_unified_official_provider);
if !matches_injected {
return Ok(config_text.to_string());
}
doc.as_table_mut().remove("model_provider");
let providers_empty = doc["model_providers"]
.as_table_mut()
.map(|providers| {
providers.remove(CC_SWITCH_CODEX_MODEL_PROVIDER_ID);
providers.is_empty()
})
.unwrap_or(false);
if providers_empty {
doc.as_table_mut().remove("model_providers");
}
Ok(doc.to_string())
}
/// 统一会话开关开启时,把官方供应商 `{ auth, config }` 设置对象中的
/// config 文本注入共享 custom 路由;开关关闭或非官方供应商时不做改动。
///
/// 普通 live 写入(`write_codex_live_for_provider`)与代理接管备份
/// `update_live_backup_from_provider`)两条落盘路径共用:接管期间
/// live 归代理所有,注入必须进备份,接管释放恢复的 live 才带统一路由。
pub fn apply_codex_unified_session_bucket_to_settings(
category: Option<&str>,
settings: &mut Value,
) -> Result<(), AppError> {
if category != Some("official") || !crate::settings::unify_codex_session_history() {
return Ok(());
}
let config_text = settings
.get("config")
.and_then(|value| value.as_str())
.unwrap_or("")
.to_string();
let injected = inject_codex_unified_session_bucket(&config_text)?;
if injected != config_text {
if let Some(obj) = settings.as_object_mut() {
obj.insert("config".to_string(), Value::String(injected));
}
}
Ok(())
}
/// Backfill helper: strip the unified-session injection from a live
/// `{ auth, config }` settings object before it is stored back to the DB.
pub fn strip_codex_unified_session_bucket_from_settings(
settings: &mut Value,
) -> Result<(), AppError> {
let Some(config_text) = settings
.get("config")
.and_then(|value| value.as_str())
.map(str::to_string)
else {
return Ok(());
};
let stripped = strip_codex_unified_session_bucket(&config_text)?;
if stripped != config_text {
if let Some(obj) = settings.as_object_mut() {
obj.insert("config".to_string(), Value::String(stripped));
}
}
Ok(())
}
/// Route a Codex live write between full auth+config or config-only.
///
/// Official providers with usable login material own `auth.json`. Third-party
/// providers only touch `config.toml` when the compatibility setting is enabled
/// so the user's ChatGPT login cache survives provider switches.
///
/// 统一会话开关开启时,官方配置在落盘前注入共享的 `custom` 路由
/// (见 `inject_codex_unified_session_bucket`)。
pub fn write_codex_live_for_provider(
category: Option<&str>,
auth: &Value,
config_text: Option<&str>,
) -> Result<(), AppError> {
let unified_official_config =
if category == Some("official") && crate::settings::unify_codex_session_history() {
Some(inject_codex_unified_session_bucket(
config_text.unwrap_or(""),
)?)
} else {
None
};
let config_text = unified_official_config.as_deref().or(config_text);
let should_write_auth = (category == Some("official") && codex_auth_has_login_material(auth))
|| (category != Some("official")
&& !crate::settings::preserve_codex_official_auth_on_switch());
@@ -1254,6 +1438,153 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn unified_session_bucket_injects_for_empty_official_config() {
let injected = inject_codex_unified_session_bucket("").expect("inject");
let doc: toml::Table = toml::from_str(&injected).expect("parse injected config");
assert_eq!(
doc.get("model_provider").and_then(|v| v.as_str()),
Some(CC_SWITCH_CODEX_MODEL_PROVIDER_ID)
);
let custom = doc["model_providers"][CC_SWITCH_CODEX_MODEL_PROVIDER_ID]
.as_table()
.expect("custom provider table");
assert_eq!(custom.get("name").and_then(|v| v.as_str()), Some("OpenAI"));
assert_eq!(
custom.get("requires_openai_auth").and_then(|v| v.as_bool()),
Some(true)
);
assert_eq!(
custom.get("supports_websockets").and_then(|v| v.as_bool()),
Some(true)
);
assert_eq!(
custom.get("wire_api").and_then(|v| v.as_str()),
Some("responses")
);
}
#[test]
fn unified_session_bucket_preserves_other_keys_and_explicit_routing() {
let with_catalog = "model_catalog_json = \"cc-switch-model-catalog.json\"\n";
let injected = inject_codex_unified_session_bucket(with_catalog).expect("inject");
assert!(injected.contains("model_catalog_json"));
assert!(injected.contains("model_provider = \"custom\""));
// 用户显式指定过 model_provider 的官方配置不被覆盖
let explicit = "model_provider = \"openai_https\"\n";
let unchanged = inject_codex_unified_session_bucket(explicit).expect("inject");
assert_eq!(unchanged, explicit);
}
#[test]
fn unified_session_bucket_skips_conflicting_custom_table() {
// 残留的非注入形态 custom 表:设置 model_provider 会把官方流量
// 路由到表里的第三方端点,必须整体拒绝注入。
let stale = r#"[model_providers.custom]
name = "Relay"
base_url = "https://relay.example/v1"
"#;
let unchanged = inject_codex_unified_session_bucket(stale).expect("inject");
assert_eq!(unchanged, stale);
// 已是注入形态的 custom 表(如重复注入)则照常补上 model_provider
let injected_once = inject_codex_unified_session_bucket("").expect("inject");
let reinjected = inject_codex_unified_session_bucket(&injected_once).expect("re-inject");
assert_eq!(reinjected, injected_once);
}
#[test]
fn unified_session_bucket_strip_round_trips_injection() {
let injected = inject_codex_unified_session_bucket("").expect("inject");
let stripped = strip_codex_unified_session_bucket(&injected).expect("strip");
assert_eq!(stripped.trim(), "");
let with_catalog = "model_catalog_json = \"cc-switch-model-catalog.json\"\n";
let injected = inject_codex_unified_session_bucket(with_catalog).expect("inject");
let stripped = strip_codex_unified_session_bucket(&injected).expect("strip");
assert_eq!(stripped, with_catalog);
}
#[test]
fn unified_session_bucket_strip_keeps_third_party_custom_entry() {
// 第三方模板同样用 custom 路由,但条目带 base_url 等差异字段,
// 形态不等于注入产物,必须原样保留。
let third_party = r#"model_provider = "custom"
[model_providers.custom]
name = "Relay"
base_url = "https://relay.example/v1"
wire_api = "responses"
requires_openai_auth = true
"#;
let untouched = strip_codex_unified_session_bucket(third_party).expect("strip");
assert_eq!(untouched, third_party);
}
#[test]
fn unified_session_bucket_strip_from_settings_only_touches_config() {
let injected = inject_codex_unified_session_bucket("").expect("inject");
let mut settings = json!({
"auth": { "tokens": { "access_token": "secret" } },
"config": injected,
});
strip_codex_unified_session_bucket_from_settings(&mut settings).expect("strip settings");
assert_eq!(
settings
.get("config")
.and_then(|v| v.as_str())
.map(str::trim),
Some("")
);
assert!(settings.pointer("/auth/tokens/access_token").is_some());
}
#[test]
fn extract_base_url_prefers_active_provider_section() {
let input = r#"model_provider = "azure"
[model_providers.azure]
base_url = "https://azure.example.com/v1"
[model_providers.other]
base_url = "https://other.example.com/v1"
"#;
assert_eq!(
extract_codex_base_url(input).as_deref(),
Some("https://azure.example.com/v1")
);
}
#[test]
fn extract_base_url_falls_back_to_top_level_only() {
let top_level = r#"base_url = "https://top-level.example.com/v1""#;
assert_eq!(
extract_codex_base_url(top_level).as_deref(),
Some("https://top-level.example.com/v1")
);
}
// Mirrors the frontend extractCodexBaseUrl: a non-active provider section
// is never a credential source, whether the active provider points
// elsewhere (e.g. the built-in "openai") or none is selected at all.
#[test]
fn extract_base_url_ignores_non_active_provider_sections() {
let mismatched = r#"model_provider = "openai"
[model_providers.custom]
base_url = "https://leftover.example.com/v1"
"#;
assert_eq!(extract_codex_base_url(mismatched), None);
let no_active = r#"[model_providers.any]
base_url = "https://single.example.com/v1"
"#;
assert_eq!(extract_codex_base_url(no_active), None);
}
#[test]
fn prepare_provider_live_config_rejects_key_without_config() {
let err = prepare_codex_provider_live_config(&json!({"OPENAI_API_KEY": "sk-test"}), "")
@@ -1791,7 +2122,7 @@ base_url = "https://production.api/v1"
}
#[test]
fn model_catalog_json_field_operates_on_top_level() {
fn model_catalog_json_field_writes_relative_filename() {
let input = r#"model_provider = "any"
[model_providers.any]
@@ -1805,7 +2136,7 @@ name = "any"
parsed
.get("model_catalog_json")
.and_then(|value| value.as_str()),
Some("/tmp/cc-switch-model-catalog.json")
Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME)
);
assert!(
parsed
@@ -2026,4 +2357,110 @@ name = "any"
);
}
}
#[test]
#[cfg(target_os = "windows")]
fn set_catalog_json_field_writes_filename_ignoring_unc_path() {
let input = r#"model_provider = "custom"
model = "glm-5"
"#;
// Simulate a WSL UNC path as cc-switch would see it on Windows;
// the function now writes just the relative filename.
let unc_path =
Path::new(r"\\wsl.localhost\Ubuntu\home\user\.codex\cc-switch-model-catalog.json");
let result = set_codex_model_catalog_json_field(input, Some(unc_path)).unwrap();
let parsed: toml::Value = toml::from_str(&result).unwrap();
let written_path = parsed
.get("model_catalog_json")
.and_then(|v| v.as_str())
.expect("model_catalog_json should be set");
assert_eq!(
written_path, CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME,
"should write only the relative filename, not the UNC path"
);
}
#[test]
fn set_catalog_json_field_writes_filename_for_any_path() {
let input = r#"model_provider = "custom"
model = "glm-5"
"#;
let regular_path = Path::new("/home/user/.codex/cc-switch-model-catalog.json");
let result = set_codex_model_catalog_json_field(input, Some(regular_path)).unwrap();
let parsed: toml::Value = toml::from_str(&result).unwrap();
assert_eq!(
parsed.get("model_catalog_json").and_then(|v| v.as_str()),
Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME),
"should write only the relative filename, not the full path"
);
}
#[test]
fn set_catalog_json_none_removes_cc_switch_owned_by_filename() {
// After the WSL fix, TOML may contain a Linux-style path.
// The None arm must still remove it (file_name match catches any format).
let input = r#"model_catalog_json = "/home/user/.codex/cc-switch-model-catalog.json"
"#;
let result = set_codex_model_catalog_json_field(input, None).unwrap();
let parsed: toml::Value = toml::from_str(&result).unwrap();
assert!(
parsed.get("model_catalog_json").is_none(),
"None arm should remove cc-switch-owned field regardless of path format"
);
}
#[test]
fn set_catalog_json_none_preserves_user_owned_catalog() {
let input = r#"model_catalog_json = "/Users/me/.codex/my-custom-catalog.json"
"#;
let result = set_codex_model_catalog_json_field(input, None).unwrap();
let parsed: toml::Value = toml::from_str(&result).unwrap();
assert_eq!(
parsed.get("model_catalog_json").and_then(|v| v.as_str()),
Some("/Users/me/.codex/my-custom-catalog.json"),
"None arm should NOT remove user-owned catalog"
);
}
#[test]
fn resolve_catalog_finds_relative_filename() {
let config_text = r#"model_provider = "custom"
model_catalog_json = "cc-switch-model-catalog.json"
"#;
let generated_path = PathBuf::from("/home/user/.codex/cc-switch-model-catalog.json");
let result = resolve_cc_switch_catalog_path(config_text, &generated_path);
assert_eq!(
result,
Some(generated_path),
"relative filename should resolve to generated_path for file I/O"
);
}
#[test]
fn resolve_catalog_ignores_user_owned_relative() {
let config_text = r#"model_catalog_json = "my-custom-catalog.json"
"#;
let generated_path = PathBuf::from("/home/user/.codex/cc-switch-model-catalog.json");
let result = resolve_cc_switch_catalog_path(config_text, &generated_path);
assert_eq!(
result, None,
"user-owned catalog should not be claimed by cc-switch"
);
}
#[test]
fn set_catalog_json_none_removes_relative_path() {
let input = r#"model_catalog_json = "cc-switch-model-catalog.json"
"#;
let result = set_codex_model_catalog_json_field(input, None).unwrap();
let parsed: toml::Value = toml::from_str(&result).unwrap();
assert!(
parsed.get("model_catalog_json").is_none(),
"None arm should remove relative cc-switch-owned field"
);
}
}
+865 -6
View File
@@ -10,7 +10,8 @@ use crate::config::{atomic_write, copy_file, get_app_config_dir};
use crate::database::{is_official_seed_id, Database};
use crate::error::AppError;
use crate::settings::{
CodexProviderTemplateMigration, CodexThirdPartyHistoryProviderBucketMigration,
CodexOfficialHistoryUnifyMigration, CodexProviderTemplateMigration,
CodexThirdPartyHistoryProviderBucketMigration,
};
use chrono::{Local, Utc};
use rusqlite::{backup::Backup, params_from_iter, Connection};
@@ -24,7 +25,25 @@ use std::time::{Duration, SystemTime};
use toml_edit::DocumentMut;
const MIGRATION_NAME: &str = "codex-history-provider-migration-v1";
const OFFICIAL_UNIFY_MIGRATION_NAME: &str = "codex-official-history-unify-v1";
/// 还原操作自身的备份目录(与迁移备份分开,保持迁移账本目录纯净)。
const OFFICIAL_UNIFY_RESTORE_BACKUP_NAME: &str = "codex-official-history-unify-restore-v1";
const CODEX_STATE_DB_FILENAME: &str = "state_5.sqlite";
/// SQLite 变量上限保守值,IN 列表按此分块。
const STATE_DB_ID_CHUNK: usize = 500;
/// 串行化官方历史的迁移与还原:开启迁移(启动重试 + 设置保存后台任务)和
/// 关闭还原可能在毫秒级先后被触发,对同一批 jsonl / state DB 双向改写。
static CODEX_OFFICIAL_HISTORY_OP_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn lock_codex_official_history_op() -> std::sync::MutexGuard<'static, ()> {
CODEX_OFFICIAL_HISTORY_OP_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// Codex 内建默认 provider idconfig.toml 没有 `model_provider` 键时会话归入此桶。
/// 官方订阅(ChatGPT OAuth / OpenAI API key)的历史会话都记录这个 id。
const OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID: &str = "openai";
const LEGACY_CC_SWITCH_CODEX_MODEL_PROVIDER_ID: &str = "ccswitch";
// If a Codex preset ever used a temporary routing key, keep that old key here
// so local history can be bucketed under the current custom provider id.
@@ -120,7 +139,7 @@ pub fn maybe_migrate_codex_third_party_history_provider_bucket(
});
}
let backup_root = migration_backup_root();
let backup_root = migration_backup_root(MIGRATION_NAME);
let codex_dir = get_codex_config_dir();
let migrated_jsonl_files =
migrate_codex_jsonl_files(&codex_dir, &source_provider_ids, &backup_root)?;
@@ -157,7 +176,7 @@ pub fn maybe_migrate_codex_provider_template_bucket(
});
}
let backup_root = migration_backup_root();
let backup_root = migration_backup_root(MIGRATION_NAME);
let outcome = migrate_codex_provider_templates_to_custom(db, &backup_root)?;
crate::settings::mark_codex_provider_template_migrated(CodexProviderTemplateMigration {
completed_at: Utc::now().to_rfc3339(),
@@ -167,6 +186,475 @@ pub fn maybe_migrate_codex_provider_template_bucket(
Ok(outcome)
}
/// 统一会话开关的存量迁移:把官方会话(内建 "openai" 桶)迁入共享 "custom" 桶。
///
/// 仅当用户在开启弹窗里勾选了"迁入既有官方会话"`unify_codex_migrate_existing`
/// 且本轮未完成时执行;开关关闭时标记与勾选意愿都会被清除(见 `save_settings`),
/// 重新开启并再次勾选即可补迁关闭期间产生的官方会话。
/// custom 桶里官方与第三方会话无法区分,自动逻辑绝不反向搬回;
/// 用户可在关闭开关时选择按备份账本精确还原(见 `restore_codex_official_history_from_backups`)。
/// 迁移前 jsonl / state DB 均备份到 `~/.cc-switch/backups/codex-official-history-unify-v1/`。
pub fn maybe_migrate_codex_official_history_to_unified_bucket(
) -> Result<CodexHistoryProviderBucketMigrationOutcome, AppError> {
if !crate::settings::unify_codex_session_history() {
return Ok(CodexHistoryProviderBucketMigrationOutcome {
skipped_reason: Some("unify_toggle_off".to_string()),
..Default::default()
});
}
if !crate::settings::unify_codex_migrate_existing_requested() {
return Ok(CodexHistoryProviderBucketMigrationOutcome {
skipped_reason: Some("stock_migration_not_requested".to_string()),
..Default::default()
});
}
let _op_guard = lock_codex_official_history_op();
let codex_dir = get_codex_config_dir();
// marker 绑定迁移时的 Codex 目录:切换 codex_config_dir 后旧 marker 不再
// 挡住新目录的迁移(迁移幂等,重跑无害)。
let codex_dir_key = canonical_dir_string(&codex_dir);
if crate::settings::is_codex_official_history_unify_migrated_for_dir(&codex_dir_key) {
return Ok(CodexHistoryProviderBucketMigrationOutcome {
skipped_reason: Some("already_migrated".to_string()),
..Default::default()
});
}
// live 必须已实际路由到共享 custom 桶才允许迁移:官方配置的注入可能被拒
// (已有显式 model_provider / 形态冲突的 custom 表,见
// `inject_codex_unified_session_bucket`),代理接管期间的 live 也不带统一
// 路由(注入只进备份)。这些状态下新会话仍落 "openai" 桶,迁移只会把
// 历史搬进当前 live 看不见的桶里。开关与迁移意愿保持不动,待 live 真正
// 统一后(下次切换 / 接管释放后的启动重试)再迁。
if !codex_config_text_routes_custom(&read_codex_config_text().unwrap_or_default()) {
return Ok(CodexHistoryProviderBucketMigrationOutcome {
skipped_reason: Some("live_not_unified".to_string()),
..Default::default()
});
}
let source_provider_ids: BTreeSet<String> =
std::iter::once(OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID.to_string()).collect();
let backup_root = migration_backup_root(OFFICIAL_UNIFY_MIGRATION_NAME);
let migrated_jsonl_files =
migrate_codex_jsonl_files(&codex_dir, &source_provider_ids, &backup_root)?;
let migrated_state_rows =
migrate_codex_state_dbs(&codex_dir, &source_provider_ids, &backup_root)?;
// 备份代际记录来源目录,restore 据此只取当前目录的账本。
write_backup_generation_meta(&backup_root, &codex_dir_key)?;
let outcome = CodexHistoryProviderBucketMigrationOutcome {
source_provider_ids: source_provider_ids.into_iter().collect(),
migrated_jsonl_files,
migrated_state_rows,
skipped_reason: None,
};
// 条件写入在 settings 写锁内原子完成:"迁移期间开关被关掉"时不写完成标记,
// 避免下一次开启被标记挡住而漏迁"关闭期间"新产生的 openai 桶会话。
// 与关闭路径(update_settings + 清标记)共用同一把锁,无检查-写入窗口。
let marker_written = crate::settings::mark_codex_official_history_unify_migrated_if_enabled(
CodexOfficialHistoryUnifyMigration {
completed_at: Utc::now().to_rfc3339(),
target_provider_id: CC_SWITCH_CODEX_MODEL_PROVIDER_ID.to_string(),
migrated_jsonl_files,
migrated_state_rows,
codex_config_dir: Some(codex_dir_key),
},
)?;
if !marker_written {
return Ok(CodexHistoryProviderBucketMigrationOutcome {
skipped_reason: Some("toggle_disabled_during_migration".to_string()),
..outcome
});
}
Ok(outcome)
}
/// live config.toml 是否路由到共享 custom 桶(会话分桶只看这个实态:
/// base_url / 接管与否都不影响 session_meta 记录的 model_provider)。
fn codex_config_text_routes_custom(config_text: &str) -> bool {
config_text
.parse::<DocumentMut>()
.ok()
.and_then(|doc| {
doc.get("model_provider")
.and_then(|item| item.as_str())
.map(|id| id.trim() == CC_SWITCH_CODEX_MODEL_PROVIDER_ID)
})
.unwrap_or(false)
}
/// 目录的规范化字符串形式,用作 marker / 备份代际的目录身份。
/// canonicalize 失败(目录尚不存在等)时退回原始路径字符串。
fn canonical_dir_string(dir: &Path) -> String {
fs::canonicalize(dir)
.unwrap_or_else(|_| dir.to_path_buf())
.to_string_lossy()
.to_string()
}
/// 在备份代际根目录写入 meta.json,记录这批备份来自哪个 Codex 目录。
/// 代际目录不存在(本轮没有任何文件被迁移)时跳过。
fn write_backup_generation_meta(backup_root: &Path, codex_dir_key: &str) -> Result<(), AppError> {
if !backup_root.exists() {
return Ok(());
}
let payload = serde_json::json!({ "codexConfigDir": codex_dir_key });
let bytes =
serde_json::to_vec_pretty(&payload).map_err(|e| AppError::JsonSerialize { source: e })?;
atomic_write(&backup_root.join("meta.json"), &bytes)
}
#[derive(Debug, Clone, Default)]
pub struct CodexOfficialHistoryRestoreOutcome {
pub restored_jsonl_files: usize,
pub restored_state_rows: usize,
pub skipped_reason: Option<String>,
}
/// 统一会话开关迁移备份的父目录(其下每次迁移一个时间戳代际目录)。
fn official_history_unify_backup_parent() -> PathBuf {
get_app_config_dir()
.join("backups")
.join(OFFICIAL_UNIFY_MIGRATION_NAME)
}
/// 是否存在可用于还原的迁移备份(给前端决定要不要显示"恢复备份"勾选)。
/// 与 restore 的账本收集共用同一目录匹配口径:只认属于当前 Codex 目录的
/// 代际,避免切换 codex_config_dir 后弹出注定空跑的勾选。
/// 精确账本内容仍在真正还原时才解析。
pub fn has_codex_official_history_unify_backup() -> bool {
has_official_history_unify_backup_for_dir(
&official_history_unify_backup_parent(),
&canonical_dir_string(&get_codex_config_dir()),
)
}
fn has_official_history_unify_backup_for_dir(ledger_parent: &Path, codex_dir_key: &str) -> bool {
let Ok(entries) = fs::read_dir(ledger_parent) else {
return false;
};
entries.flatten().any(|entry| {
let generation = entry.path();
generation.is_dir() && backup_generation_matches_dir(&generation, codex_dir_key)
})
}
/// 关闭统一会话开关时的可选还原:按迁移备份账本,把当时迁入共享 custom 桶的
/// 官方会话精确翻回 "openai" 桶。
///
/// 备份是唯一可信的归属证据:备份里 model_provider=="openai" 的会话必定源自
/// 官方桶。开启期间新产生的会话不在任何备份里,**永不触碰**——它们可能来自
/// 第三方,方向无法判定(产品决策:宁可留在第三方历史)。
/// 扫描全部备份代际取并集,多次开关循环后仍能还原早期迁入的会话;
/// 还原前改动目标先备份到独立的 restore 目录(保持迁移账本目录纯净),
/// 且只改写当前仍为 custom 的目标,重复执行无害。
pub fn restore_codex_official_history_from_backups(
) -> Result<CodexOfficialHistoryRestoreOutcome, AppError> {
let _op_guard = lock_codex_official_history_op();
// 开关已(重新)开启时拒绝还原:live 正路由 custom,把账本会话翻回
// openai 桶等于亲手制造分裂。覆盖"关闭保存成功后用户立刻重新开启,
// 还原排在重开迁移之后才拿到 op lock"的时序。
if crate::settings::unify_codex_session_history() {
return Ok(CodexOfficialHistoryRestoreOutcome {
skipped_reason: Some("unify_toggle_on".to_string()),
..Default::default()
});
}
let config_text = read_codex_config_text().unwrap_or_default();
restore_codex_official_history_inner(
&get_codex_config_dir(),
&official_history_unify_backup_parent(),
&migration_backup_root(OFFICIAL_UNIFY_RESTORE_BACKUP_NAME),
&config_text,
)
}
fn restore_codex_official_history_inner(
codex_dir: &Path,
ledger_parent: &Path,
restore_backup_root: &Path,
config_text: &str,
) -> Result<CodexOfficialHistoryRestoreOutcome, AppError> {
let codex_dir_key = canonical_dir_string(codex_dir);
let (official_session_ids, official_thread_ids) =
collect_official_ledger(ledger_parent, &codex_dir_key)?;
if official_session_ids.is_empty() && official_thread_ids.is_empty() {
return Ok(CodexOfficialHistoryRestoreOutcome {
skipped_reason: Some("no_backup_ledger".to_string()),
..Default::default()
});
}
let mut files = Vec::new();
collect_jsonl_files(&codex_dir.join("sessions"), &mut files, 0, 8);
collect_jsonl_files(&codex_dir.join("archived_sessions"), &mut files, 0, 4);
let mut restored_jsonl_files = 0;
for file_path in files {
if rewrite_codex_session_file_lines(&file_path, codex_dir, restore_backup_root, |line| {
rewrite_codex_session_meta_line_for_restore(line, &official_session_ids)
})? {
restored_jsonl_files += 1;
}
}
let mut restored_state_rows = 0;
for db_path in codex_state_db_paths(codex_dir, config_text) {
restored_state_rows += restore_codex_state_db_official_threads(
&db_path,
codex_dir,
&official_thread_ids,
restore_backup_root,
)?;
}
if restored_jsonl_files == 0 && restored_state_rows == 0 {
// 账本非空但没有任何"当前仍为 custom"的目标(如重复还原):
// 以 reason 告知前端,避免误报"已还原 0 项"为成功。
return Ok(CodexOfficialHistoryRestoreOutcome {
skipped_reason: Some("nothing_to_restore".to_string()),
..Default::default()
});
}
Ok(CodexOfficialHistoryRestoreOutcome {
restored_jsonl_files,
restored_state_rows,
skipped_reason: None,
})
}
/// 从备份代际收集官方会话账本:jsonl 备份里 session_meta 为 "openai" 的
/// 会话 id + state DB 备份里 model_provider 为 "openai" 的 thread id。
/// 只采纳 meta.json 目录与当前 Codex 目录一致的代际,避免切换
/// codex_config_dir 后拿旧目录的账本作用到新目录。
/// 还原操作自身的备份(restore 目录)天然不会混入:那些副本里的 id 都是
/// custom,解析后贡献为空。
fn collect_official_ledger(
ledger_parent: &Path,
codex_dir_key: &str,
) -> Result<(HashSet<String>, BTreeSet<String>), AppError> {
let mut session_ids = HashSet::new();
let mut thread_ids = BTreeSet::new();
let entries = match fs::read_dir(ledger_parent) {
Ok(entries) => entries,
Err(_) => return Ok((session_ids, thread_ids)),
};
for entry in entries.flatten() {
let generation = entry.path();
if !generation.is_dir() {
continue;
}
if !backup_generation_matches_dir(&generation, codex_dir_key) {
continue;
}
let mut backup_files = Vec::new();
collect_jsonl_files(&generation.join("jsonl"), &mut backup_files, 0, 10);
for backup_file in backup_files {
collect_official_session_ids_from_backup(&backup_file, &mut session_ids);
}
let mut backup_dbs = Vec::new();
collect_files_with_extension(&generation.join("state"), "sqlite", &mut backup_dbs, 0, 4);
for backup_db in backup_dbs {
collect_official_thread_ids_from_backup(&backup_db, &mut thread_ids);
}
}
Ok((session_ids, thread_ids))
}
/// 备份代际是否属于指定 Codex 目录。无 meta.json 或解析失败时宽容接受:
/// 早期版本的备份没有 meta,而那个时期不存在切目录场景;误纳的代价也被
/// "按会话 id 精确匹配 + 仅改写 custom"双重条件兜底。
fn backup_generation_matches_dir(generation: &Path, codex_dir_key: &str) -> bool {
let Ok(text) = fs::read_to_string(generation.join("meta.json")) else {
return true;
};
serde_json::from_str::<Value>(&text)
.ok()
.and_then(|value| {
value
.get("codexConfigDir")
.and_then(Value::as_str)
.map(|dir| dir == codex_dir_key)
})
.unwrap_or(true)
}
fn collect_official_session_ids_from_backup(path: &Path, session_ids: &mut HashSet<String>) {
let Ok(content) = fs::read_to_string(path) else {
log::debug!("Failed to read unify backup file {}", path.display());
return;
};
for line in content.lines() {
if !line.contains("\"session_meta\"") || !line.contains("\"model_provider\"") {
continue;
}
let Ok(value) = serde_json::from_str::<Value>(line) else {
continue;
};
if value.get("type").and_then(Value::as_str) != Some("session_meta") {
continue;
}
let Some(payload) = value.get("payload") else {
continue;
};
if payload.get("model_provider").and_then(Value::as_str)
!= Some(OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID)
{
continue;
}
if let Some(session_id) = payload.get("id").and_then(Value::as_str) {
session_ids.insert(session_id.to_string());
}
}
}
fn collect_official_thread_ids_from_backup(db_path: &Path, thread_ids: &mut BTreeSet<String>) {
let conn =
match Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) {
Ok(conn) => conn,
Err(err) => {
log::debug!(
"Failed to open unify backup state DB {}: {err}",
db_path.display()
);
return;
}
};
let has_threads = Database::table_exists(&conn, "threads").unwrap_or(false)
&& Database::has_column(&conn, "threads", "model_provider").unwrap_or(false);
if !has_threads {
return;
}
let Ok(mut stmt) = conn.prepare("SELECT id FROM threads WHERE model_provider = ?1") else {
return;
};
let Ok(rows) = stmt.query_map([OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID], |row| {
row.get::<_, String>(0)
}) else {
return;
};
for thread_id in rows.flatten() {
thread_ids.insert(thread_id);
}
}
fn collect_files_with_extension(
dir: &Path,
extension: &str,
files: &mut Vec<PathBuf>,
depth: u8,
max_depth: u8,
) {
if depth > max_depth || !dir.is_dir() {
return;
}
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_files_with_extension(&path, extension, files, depth + 1, max_depth);
} else if path.extension().and_then(|ext| ext.to_str()) == Some(extension) {
files.push(path);
}
}
}
fn rewrite_codex_session_meta_line_for_restore(
line: &str,
official_session_ids: &HashSet<String>,
) -> Option<String> {
if !line.contains("\"session_meta\"") || !line.contains("\"model_provider\"") {
return None;
}
let mut value: Value = serde_json::from_str(line).ok()?;
if value.get("type").and_then(Value::as_str) != Some("session_meta") {
return None;
}
let payload = value.get_mut("payload")?.as_object_mut()?;
if payload.get("model_provider")?.as_str()? != CC_SWITCH_CODEX_MODEL_PROVIDER_ID {
return None;
}
let session_id = payload.get("id")?.as_str()?;
if !official_session_ids.contains(session_id) {
return None;
}
payload.insert(
"model_provider".to_string(),
Value::String(OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID.to_string()),
);
serde_json::to_string(&value).ok()
}
fn restore_codex_state_db_official_threads(
db_path: &Path,
codex_dir: &Path,
official_thread_ids: &BTreeSet<String>,
backup_root: &Path,
) -> Result<usize, AppError> {
if !db_path.exists() || official_thread_ids.is_empty() {
return Ok(0);
}
let mut conn = Connection::open(db_path)
.map_err(|e| AppError::Database(format!("打开 Codex state DB 失败: {e}")))?;
conn.busy_timeout(Duration::from_secs(5))
.map_err(|e| AppError::Database(format!("设置 Codex state DB busy_timeout 失败: {e}")))?;
if !Database::table_exists(&conn, "threads")?
|| !Database::has_column(&conn, "threads", "model_provider")?
{
return Ok(0);
}
let ids: Vec<&String> = official_thread_ids.iter().collect();
let mut matching_rows: i64 = 0;
for chunk in ids.chunks(STATE_DB_ID_CHUNK) {
let placeholders = placeholders(chunk.len());
let count_sql = format!(
"SELECT COUNT(*) FROM threads WHERE model_provider = ? AND id IN ({placeholders})"
);
let mut values = Vec::with_capacity(chunk.len() + 1);
values.push(CC_SWITCH_CODEX_MODEL_PROVIDER_ID.to_string());
values.extend(chunk.iter().map(|id| (*id).clone()));
let count: i64 = conn
.query_row(&count_sql, params_from_iter(values.iter()), |row| {
row.get(0)
})
.map_err(|e| AppError::Database(format!("统计 Codex state DB 待还原行失败: {e}")))?;
matching_rows += count;
}
if matching_rows == 0 {
return Ok(0);
}
backup_codex_state_db(db_path, codex_dir, backup_root, &conn)?;
let tx = conn
.transaction()
.map_err(|e| AppError::Database(format!("开启 Codex state DB 还原事务失败: {e}")))?;
let mut changed = 0;
for chunk in ids.chunks(STATE_DB_ID_CHUNK) {
let placeholders = placeholders(chunk.len());
let update_sql = format!(
"UPDATE threads SET model_provider = ? WHERE model_provider = ? AND id IN ({placeholders})"
);
let mut values = Vec::with_capacity(chunk.len() + 2);
values.push(OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID.to_string());
values.push(CC_SWITCH_CODEX_MODEL_PROVIDER_ID.to_string());
values.extend(chunk.iter().map(|id| (*id).clone()));
changed += tx
.execute(&update_sql, params_from_iter(values.iter()))
.map_err(|e| AppError::Database(format!("还原 Codex state DB provider 失败: {e}")))?;
}
tx.commit()
.map_err(|e| AppError::Database(format!("提交 Codex state DB 还原事务失败: {e}")))?;
Ok(changed)
}
fn migrate_codex_provider_templates_to_custom(
db: &Database,
backup_root: &Path,
@@ -257,10 +745,10 @@ fn insert_known_cc_switch_legacy_source_id(ids: &mut BTreeSet<String>, provider_
}
}
fn migration_backup_root() -> PathBuf {
fn migration_backup_root(migration_name: &str) -> PathBuf {
get_app_config_dir()
.join("backups")
.join(MIGRATION_NAME)
.join(migration_name)
.join(Local::now().format("%Y%m%d_%H%M%S").to_string())
}
@@ -524,6 +1012,17 @@ fn rewrite_codex_session_file_for_provider_bucket(
codex_dir: &Path,
source_provider_ids: &HashSet<String>,
backup_root: &Path,
) -> Result<bool, AppError> {
rewrite_codex_session_file_lines(path, codex_dir, backup_root, |line| {
rewrite_codex_session_meta_line(line, source_provider_ids)
})
}
fn rewrite_codex_session_file_lines(
path: &Path,
codex_dir: &Path,
backup_root: &Path,
rewrite_line: impl Fn(&str) -> Option<String>,
) -> Result<bool, AppError> {
let metadata_before = fs::metadata(path).map_err(|e| AppError::io(path, e))?;
let modified_before = metadata_before.modified().ok();
@@ -537,7 +1036,7 @@ fn rewrite_codex_session_file_for_provider_bucket(
.strip_suffix('\n')
.map(|line| (line, "\n"))
.unwrap_or((segment, ""));
if let Some(next_line) = rewrite_codex_session_meta_line(line, source_provider_ids) {
if let Some(next_line) = rewrite_line(line) {
rewritten.push_str(&next_line);
changed = true;
} else {
@@ -820,6 +1319,39 @@ mod tests {
values.iter().map(|value| value.to_string()).collect()
}
#[test]
fn detects_custom_routed_codex_config_for_unify_gate() {
// 注入产物(官方 + 统一开关)
assert!(codex_config_text_routes_custom(
r#"model_provider = "custom"
[model_providers.custom]
name = "OpenAI"
requires_openai_auth = true
supports_websockets = true
wire_api = "responses"
"#
));
// 第三方供应商的常规 custom 路由(带 base_url)同样算已统一
assert!(codex_config_text_routes_custom(
r#"model_provider = "custom"
[model_providers.custom]
name = "AIHubMix"
base_url = "https://aihubmix.example/v1"
"#
));
// 注入被拒的形态:显式 openai 路由 / 无 model_provider(接管期间、空配置)
assert!(!codex_config_text_routes_custom(
"model_provider = \"openai\"\n"
));
assert!(!codex_config_text_routes_custom(
"base_url = \"http://127.0.0.1:15721/codex\"\n"
));
assert!(!codex_config_text_routes_custom(""));
assert!(!codex_config_text_routes_custom("not toml ["));
}
fn migrate_provider_templates_for_test(
db: &Database,
) -> (
@@ -1092,6 +1624,333 @@ base_url = "https://proxy.example/v1"
);
}
#[test]
fn simulates_official_history_unify_migration_end_to_end() {
let dir = tempdir().expect("tempdir");
let codex_dir = dir.path().join(".codex");
let backup_root = dir.path().join("backup");
fs::create_dir_all(&codex_dir).expect("create codex dir");
let source_provider_ids = source_ids(&[OFFICIAL_OPENAI_CODEX_MODEL_PROVIDER_ID]);
let session_dir = codex_dir.join("sessions/2026/06/12");
fs::create_dir_all(&session_dir).expect("create session dir");
let session_path = session_dir.join("official-sim.jsonl");
fs::write(
&session_path,
concat!(
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"openai\"}}\n",
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s2\",\"model_provider\":\"custom\"}}\n",
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s3\",\"model_provider\":\"my-private-relay\"}}\n",
"{\"type\":\"response_item\",\"payload\":{\"text\":\"openai\"}}\n",
),
)
.expect("write session");
let migrated_jsonl =
migrate_codex_jsonl_files(&codex_dir, &source_provider_ids, &backup_root)
.expect("migrate jsonl");
assert_eq!(migrated_jsonl, 1);
let session_text = fs::read_to_string(&session_path).expect("read session");
assert_eq!(
session_text
.matches("\"model_provider\":\"custom\"")
.count(),
2
);
assert!(!session_text.contains("\"model_provider\":\"openai\""));
assert!(session_text.contains("\"model_provider\":\"my-private-relay\""));
assert!(
session_text.contains("{\"type\":\"response_item\",\"payload\":{\"text\":\"openai\"}}")
);
assert!(backup_root
.join("jsonl/sessions/2026/06/12/official-sim.jsonl")
.exists());
// 第二次执行应当无事可做(幂等)
let rerun = migrate_codex_jsonl_files(&codex_dir, &source_provider_ids, &backup_root)
.expect("rerun migrate jsonl");
assert_eq!(rerun, 0);
let state_db_path = codex_dir.join(CODEX_STATE_DB_FILENAME);
let conn = Connection::open(&state_db_path).expect("open state db");
conn.execute_batch(
"CREATE TABLE threads (
id TEXT PRIMARY KEY,
model_provider TEXT NOT NULL
);
INSERT INTO threads (id, model_provider) VALUES
('openai-thread', 'openai'),
('custom-thread', 'custom'),
('manual-thread', 'my-private-relay');",
)
.expect("seed state db");
drop(conn);
let migrated_state_rows = migrate_codex_state_db_provider_bucket(
&state_db_path,
&codex_dir,
&source_provider_ids,
&backup_root,
)
.expect("migrate state db");
assert_eq!(migrated_state_rows, 1);
let conn = Connection::open(&state_db_path).expect("reopen state db");
let count_provider = |provider_id: &str| -> i64 {
conn.query_row(
"SELECT COUNT(*) FROM threads WHERE model_provider = ?1",
[provider_id],
|row| row.get(0),
)
.expect("count provider")
};
assert_eq!(count_provider("custom"), 2);
assert_eq!(count_provider("openai"), 0);
assert_eq!(count_provider("my-private-relay"), 1);
}
#[test]
fn restores_only_ledgered_official_sessions_from_backups() {
let dir = tempdir().expect("tempdir");
let codex_dir = dir.path().join(".codex");
let ledger_parent = dir.path().join("ledger");
let restore_backup_root = dir.path().join("restore-backup");
// 备份账本:一个代际,jsonl 备份里 s1 是 openaistate 备份里 t1 是 openai
let generation = ledger_parent.join("20260612_010101");
let backup_session_dir = generation.join("jsonl/sessions/2026/06/01");
fs::create_dir_all(&backup_session_dir).expect("create backup session dir");
fs::write(
backup_session_dir.join("official.jsonl"),
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"openai\"}}\n",
)
.expect("write backup session");
let backup_state_dir = generation.join("state");
fs::create_dir_all(&backup_state_dir).expect("create backup state dir");
let backup_db = Connection::open(backup_state_dir.join(CODEX_STATE_DB_FILENAME))
.expect("open backup db");
backup_db
.execute_batch(
"CREATE TABLE threads (id TEXT PRIMARY KEY, model_provider TEXT NOT NULL);
INSERT INTO threads (id, model_provider) VALUES ('t1', 'openai');",
)
.expect("seed backup db");
drop(backup_db);
// 当前数据:s1(账本内,custom)应还原;s2(开启期间新会话,不在账本)
// 与 s3(手工 relay)必须原样保留
let session_dir = codex_dir.join("sessions/2026/06/01");
fs::create_dir_all(&session_dir).expect("create session dir");
let official_path = session_dir.join("official.jsonl");
fs::write(
&official_path,
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"custom\"}}\n",
)
.expect("write official session");
let on_period_dir = codex_dir.join("sessions/2026/06/12");
fs::create_dir_all(&on_period_dir).expect("create on-period dir");
let on_period_path = on_period_dir.join("on-period.jsonl");
fs::write(
&on_period_path,
concat!(
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s2\",\"model_provider\":\"custom\"}}\n",
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s3\",\"model_provider\":\"my-private-relay\"}}\n",
),
)
.expect("write on-period session");
let state_db_path = codex_dir.join(CODEX_STATE_DB_FILENAME);
let conn = Connection::open(&state_db_path).expect("open state db");
conn.execute_batch(
"CREATE TABLE threads (id TEXT PRIMARY KEY, model_provider TEXT NOT NULL);
INSERT INTO threads (id, model_provider) VALUES
('t1', 'custom'),
('t2', 'custom'),
('t3', 'openai');",
)
.expect("seed state db");
drop(conn);
// 代际 meta 指向当前 Codex 目录:精确匹配分支生效(而非无 meta 的宽容分支)
fs::write(
generation.join("meta.json"),
serde_json::to_vec_pretty(&serde_json::json!({
"codexConfigDir": canonical_dir_string(&codex_dir)
}))
.expect("serialize meta"),
)
.expect("write meta");
let outcome = restore_codex_official_history_inner(
&codex_dir,
&ledger_parent,
&restore_backup_root,
"",
)
.expect("restore");
assert_eq!(outcome.restored_jsonl_files, 1);
assert_eq!(outcome.restored_state_rows, 1);
assert!(outcome.skipped_reason.is_none());
let official_text = fs::read_to_string(&official_path).expect("read official");
assert!(official_text.contains("\"model_provider\":\"openai\""));
let on_period_text = fs::read_to_string(&on_period_path).expect("read on-period");
assert!(on_period_text.contains("\"id\":\"s2\",\"model_provider\":\"custom\""));
assert!(on_period_text.contains("\"model_provider\":\"my-private-relay\""));
let conn = Connection::open(&state_db_path).expect("reopen state db");
let provider_of = |thread_id: &str| -> String {
conn.query_row(
"SELECT model_provider FROM threads WHERE id = ?1",
[thread_id],
|row| row.get(0),
)
.expect("thread provider")
};
assert_eq!(provider_of("t1"), "openai");
assert_eq!(provider_of("t2"), "custom");
assert_eq!(provider_of("t3"), "openai");
drop(conn);
// 还原前的现场已备份到独立目录
assert!(restore_backup_root
.join("jsonl/sessions/2026/06/01/official.jsonl")
.exists());
assert!(restore_backup_root
.join("state")
.join(CODEX_STATE_DB_FILENAME)
.exists());
// 幂等:第二次还原无事可做
let rerun = restore_codex_official_history_inner(
&codex_dir,
&ledger_parent,
&dir.path().join("restore-backup-2"),
"",
)
.expect("rerun restore");
assert_eq!(rerun.restored_jsonl_files, 0);
assert_eq!(rerun.restored_state_rows, 0);
assert_eq!(rerun.skipped_reason.as_deref(), Some("nothing_to_restore"));
}
#[test]
fn restore_ignores_backup_generations_from_other_codex_dirs() {
let dir = tempdir().expect("tempdir");
let codex_dir = dir.path().join(".codex");
let ledger_parent = dir.path().join("ledger");
// 账本代际属于另一个 Codex 目录
let generation = ledger_parent.join("20260612_010101");
let backup_session_dir = generation.join("jsonl/sessions/2026/06/01");
fs::create_dir_all(&backup_session_dir).expect("create backup session dir");
fs::write(
backup_session_dir.join("official.jsonl"),
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"openai\"}}\n",
)
.expect("write backup session");
fs::write(
generation.join("meta.json"),
"{\n \"codexConfigDir\": \"/some/other/codex-dir\"\n}",
)
.expect("write meta");
let session_dir = codex_dir.join("sessions/2026/06/01");
fs::create_dir_all(&session_dir).expect("create session dir");
let session_path = session_dir.join("official.jsonl");
fs::write(
&session_path,
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"custom\"}}\n",
)
.expect("write session");
let outcome = restore_codex_official_history_inner(
&codex_dir,
&ledger_parent,
&dir.path().join("restore-backup"),
"",
)
.expect("restore");
assert_eq!(outcome.skipped_reason.as_deref(), Some("no_backup_ledger"));
let text = fs::read_to_string(&session_path).expect("read session");
assert!(text.contains("\"model_provider\":\"custom\""));
}
#[test]
fn backup_probe_only_counts_generations_for_current_dir() {
let dir = tempdir().expect("tempdir");
let ledger_parent = dir.path().join("ledger");
let codex_dir_key = "/current/codex-dir";
// 空父目录 / 父目录不存在:无备份
assert!(!has_official_history_unify_backup_for_dir(
&ledger_parent,
codex_dir_key
));
// 只有其他目录的代际:不算有备份
let other = ledger_parent.join("20260612_010101");
fs::create_dir_all(&other).expect("create generation");
fs::write(
other.join("meta.json"),
"{\n \"codexConfigDir\": \"/some/other/codex-dir\"\n}",
)
.expect("write meta");
assert!(!has_official_history_unify_backup_for_dir(
&ledger_parent,
codex_dir_key
));
// 无 meta 的早期代际:宽容接受(与 restore 的账本口径一致)
fs::create_dir_all(ledger_parent.join("20260612_020202")).expect("create legacy gen");
assert!(has_official_history_unify_backup_for_dir(
&ledger_parent,
codex_dir_key
));
// 精确匹配当前目录的代际
fs::remove_dir_all(ledger_parent.join("20260612_020202")).expect("remove legacy gen");
let matched = ledger_parent.join("20260612_030303");
fs::create_dir_all(&matched).expect("create matched gen");
fs::write(
matched.join("meta.json"),
format!("{{\n \"codexConfigDir\": \"{codex_dir_key}\"\n}}"),
)
.expect("write matched meta");
assert!(has_official_history_unify_backup_for_dir(
&ledger_parent,
codex_dir_key
));
}
#[test]
fn restore_skips_when_no_backup_ledger_exists() {
let dir = tempdir().expect("tempdir");
let codex_dir = dir.path().join(".codex");
let session_dir = codex_dir.join("sessions/2026/06/01");
fs::create_dir_all(&session_dir).expect("create session dir");
fs::write(
session_dir.join("session.jsonl"),
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s1\",\"model_provider\":\"custom\"}}\n",
)
.expect("write session");
let outcome = restore_codex_official_history_inner(
&codex_dir,
&dir.path().join("missing-ledger"),
&dir.path().join("restore-backup"),
"",
)
.expect("restore");
assert_eq!(outcome.skipped_reason.as_deref(), Some("no_backup_ledger"));
assert_eq!(outcome.restored_jsonl_files, 0);
assert_eq!(outcome.restored_state_rows, 0);
let text = fs::read_to_string(session_dir.join("session.jsonl")).expect("read session");
assert!(text.contains("\"model_provider\":\"custom\""));
}
#[test]
fn rewrites_only_codex_session_meta_provider_ids() {
let dir = tempdir().expect("tempdir");
+389 -70
View File
@@ -1985,10 +1985,19 @@ fn anchored_official_update_command(tool: &str, bin_path: &str) -> Option<String
official_update_args(tool).map(|args| format!("{} {args}", win_quote_path_for_batch(bin_path)))
}
/// 哪些工具的"官方 self-update"优先于包管理器升级(生成 `<tool> update || <pkg-mgr>`)。
///
/// **codex 刻意不在此列**`codex update` 在 npm 安装上只是裸 `npm install -g
/// @openai/codex`(无 `@latest` / `--include=optional` / 不先卸载),却只检查 exit code、
/// 无条件打印 “Update ran successfully”。当 npm 把平台二进制 optional 依赖
/// `@openai/codex-<triple>` 漏装时它仍 **exit 0 假成功**,使外层 `||` 兜底被短路、损坏被
/// 成功 toast 掩盖(用户报告的 “Missing optional dependency” 即源于此)。因此 codex 一律走
/// npm 锚定升级;真正损坏(`runnable=false`)时由 `installs_anchored_command` 的门控改用
/// `codex_repair_command` 的 uninstall+install 自愈,而非交给 codex 自身的 self-update。
fn prefers_official_update(tool: &str, shell: LifecycleCommandShell) -> bool {
match shell {
LifecycleCommandShell::Posix => {
matches!(tool, "claude" | "codex" | "opencode" | "openclaw")
matches!(tool, "claude" | "opencode" | "openclaw")
}
LifecycleCommandShell::WindowsBatch => {
matches!(
@@ -1997,12 +2006,66 @@ fn prefers_official_update(tool: &str, shell: LifecycleCommandShell) -> bool {
// 安装方式探测失败弹交互 promptspawn npm.cmd 没传 shell:true);静默
// lifecycle 没有 stdin 会挂死,Windows 先锚到包管理器路径,等上游修了
// 再把 opencode 加回这里。
"claude" | "codex" | "openclaw"
"claude" | "openclaw"
)
}
}
}
/// Codex 平台分发包损坏的自愈命令。Codex 的 npm 包是「主包 `@openai/codex`(纯 JS
/// launcher+ 平台二进制 optional 依赖 `@openai/codex-<triple>`」的分发模式(同 esbuild/swc)。
/// 当平台二进制缺失时 codex 跑不起来——`enumerate_tool_installations` 跑 `--version` 会拿到
/// “Missing optional dependency” 的非 0 退出,标记 `runnable=false`。此状态下普通
/// `npm i -g @pkg@latest` 是 **no-op**npm 视 optional 依赖缺失为非致命,reify 又认为主包已是
/// 最新(外加半损坏留下的空 nested `node_modules` 残骸强化「tree 已满足」判断),不会补回平台
/// 二进制。唯一实测可靠的修复是先 `uninstall` 清掉残骸、再 `install` 装回完整的主包 + 平台二进制
/// (实测输出 `added 2 packages`)。
///
/// 锚定到与 codex 入口同目录的 npm(与升级路径一致,不依赖 GUI 非登录进程的 PATH)。`|| true`
/// 让 uninstall 失败(如 nvm 上对半损坏包静默返回非 0)不触发外层 `set -e` 中止,但随后的
/// install 若失败仍会被 `set -e` 捕获并上报给前端 toast。
///
/// **仅对会锚定到 sibling npm 的 node 管理器来源(nvm/fnm/mise/homebrew npm)生效**
/// `runnable=false` 是宽信号(权限 / node 版本 / 任意 `--version` 失败皆可触发),非 npm
/// 全局安装各有自己的二进制分发与修复方式,无脑套 npm uninstall+install 会出错——Homebrew
/// formulareal 在 `Cellar/`)本应 `brew upgrade codex`npm 够不到它反而旁路装第二份 npm
/// 全局 codexVolta/Bun 本应 `volta install`/`bun add`,且 `~/.bun/bin` 下没有 npm、
/// `sibling_bin` 会拼出不存在的路径;system/未知来源无可靠 sibling npm。这些来源一律返回
/// None,让上游继续走 source-specific 的 `anchored_command_from_paths`。白名单与
/// `package_manager_anchored_command_from_paths` 的 sibling-npm 分支对齐。
/// 刻意**不**额外用 `inst.error` 文本确认「确系缺二进制」:enumerate 只保留 stderr 末尾 4 行,
/// 而 codex.js 抛错的 "Missing optional dependency" 行会被尾部 node stack `at ...` 行挤出窗口
/// (实测用户原始错误即如此),强加该条件反而漏修真实缺包;对 npm 全局安装,uninstall+install
/// 对各类损坏都是合理且不会更糟的修复。
#[cfg(not(target_os = "windows"))]
fn codex_repair_command(bin_path: &str, real: &str) -> Option<String> {
// brew formulareal 在 Cellar)→ 不归 npm 管,交回 anchored 走 brew upgrade。
if brew_formula_from_path(real).is_some() {
return None;
}
// 只认会落到 sibling npm 的 node 管理器来源;volta/bun/system/未知交回 anchored。
if !matches!(
infer_install_source(Path::new(bin_path)),
"nvm" | "fnm" | "mise" | "homebrew"
) {
return None;
}
let npm = sibling_bin(bin_path, "npm")?;
let npm = quote_path_if_spaced(&npm);
let pkg = "@openai/codex";
Some(format!(
"{npm} uninstall -g {pkg} || true; {npm} i -g {pkg}@latest"
))
}
/// Windows 暂不做平台分发自愈:Windows 上 codex 的破坏模式不同(EPERM 文件锁 / 版本 bump
/// 残留,见 openai/codex#21872、#19824),且 `.bat` 链的错误处理与 POSIX `set -e` 语义不同,
/// 需要单独设计;先在本问题实际发生的 POSIX 平台落地。返回 None → 上游走正常锚定命令。
#[cfg(target_os = "windows")]
fn codex_repair_command(_bin_path: &str, _real: &str) -> Option<String> {
None
}
#[cfg(not(target_os = "windows"))]
fn package_manager_anchored_command_from_paths(
tool: &str,
@@ -2190,6 +2253,17 @@ fn default_install(installs: &[ToolInstallation]) -> Option<&ToolInstallation> {
fn installs_anchored_command(tool: &str, installs: &[ToolInstallation]) -> Option<String> {
let inst = default_install(installs)?;
let real = inst.real.to_string_lossy();
// Codex 平台分发包损坏自愈:主包在但平台二进制缺失时 codex 跑不起来
// runnable=false),此时正常锚定的 `npm i -g @latest` 是 no-op 修不好——改用
// uninstall+install 重装补回平台二进制。**但仅限会锚定到 sibling npm 的 node 管理器
// 来源**codex_repair_command 内按 source/real 收窄,brew/volta/bun/system 交回下方
// source-specific 锚定,避免误用 npm 重装)。runnable=true 的正常升级也走下方普通锚定
// 路径(且因 codex 不在 prefers_official_update,不会再跑会假成功掩盖损坏的 `codex update`)。
if tool == "codex" && !inst.runnable {
if let Some(cmd) = codex_repair_command(&inst.path, &real) {
return Some(cmd);
}
}
anchored_command_from_paths(tool, &inst.path, &real)
}
@@ -2620,29 +2694,58 @@ exec bash --norc --noprofile
result
}
/// macOS: Terminal.app
/// Escape a value as an AppleScript string literal.
#[cfg(target_os = "macos")]
fn launch_macos_terminal_app(script_file: &std::path::Path) -> Result<(), String> {
use std::process::Command;
fn applescript_string_literal(value: &str) -> String {
format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
}
let applescript = format!(
r#"tell application "Terminal"
activate
do script "bash '{}'"
/// Build the launcher command literal used by AppleScript.
#[cfg(target_os = "macos")]
fn applescript_launcher_command(script_file: &std::path::Path) -> String {
applescript_string_literal(&format!(
"bash {}",
shell_single_quote(&script_file.to_string_lossy())
))
}
/// macOS: Terminal.app AppleScript.
/// A cold `activate` creates a default empty window before `do script` opens the command session.
/// Use `launch` for cold starts so `do script` can create the only new session without reusing restored windows.
#[cfg(target_os = "macos")]
fn build_macos_terminal_applescript(script_file: &std::path::Path) -> String {
format!(
r#"set launcher_script to {launcher}
set was_running to application "Terminal" is running
tell application "Terminal"
if was_running then
activate
do script launcher_script
else
launch
do script launcher_script
activate
end if
end tell"#,
script_file.display()
);
launcher = applescript_launcher_command(script_file)
)
}
/// Run AppleScript through `osascript -e` with shared error handling.
#[cfg(target_os = "macos")]
fn run_terminal_osascript(applescript: &str, terminal_label: &str) -> Result<(), String> {
use std::process::Command;
let output = Command::new("osascript")
.arg("-e")
.arg(&applescript)
.arg(applescript)
.output()
.map_err(|e| format!("执行 osascript 失败: {e}"))?;
if !output.status.success() {
let stderr = decode_command_output(&output.stderr);
return Err(format!(
"Terminal.app 执行失败 (exit code: {:?}): {}",
"{terminal_label} 执行失败 (exit code: {:?}): {}",
output.status.code(),
stderr
));
@@ -2651,11 +2754,20 @@ end tell"#,
Ok(())
}
/// macOS: Terminal.app
#[cfg(target_os = "macos")]
fn launch_macos_terminal_app(script_file: &std::path::Path) -> Result<(), String> {
run_terminal_osascript(
&build_macos_terminal_applescript(script_file),
"Terminal.app",
)
}
/// macOS: iTerm2
#[cfg(target_os = "macos")]
fn build_macos_iterm2_applescript(script_file: &std::path::Path) -> String {
format!(
r#"set launcher_script to "bash '{}'"
r#"set launcher_script to {launcher}
set was_running to application "iTerm" is running
tell application "iTerm"
if was_running then
@@ -2683,63 +2795,59 @@ tell application "iTerm"
write text launcher_script
end tell
end tell"#,
script_file.display()
launcher = applescript_launcher_command(script_file)
)
}
/// macOS: iTerm2
#[cfg(target_os = "macos")]
fn launch_macos_iterm2(script_file: &std::path::Path) -> Result<(), String> {
use std::process::Command;
let applescript = build_macos_iterm2_applescript(script_file);
let output = Command::new("osascript")
.arg("-e")
.arg(&applescript)
.output()
.map_err(|e| format!("执行 osascript 失败: {e}"))?;
if !output.status.success() {
let stderr = decode_command_output(&output.stderr);
return Err(format!(
"iTerm2 执行失败 (exit code: {:?}): {}",
output.status.code(),
stderr
));
}
Ok(())
run_terminal_osascript(&build_macos_iterm2_applescript(script_file), "iTerm2")
}
/// macOS: Ghostty — use --quit-after-last-window-closed to avoid cloning existing tabs
/// Keep the launcher path inside a `bash -c` string.
/// A bare `.sh` passed through `open --args` may also be opened as a document.
#[cfg(target_os = "macos")]
fn build_macos_dash_c_command(script_file: &std::path::Path) -> String {
format!(
"exec bash {}",
shell_single_quote(&script_file.to_string_lossy())
)
}
/// macOS: Ghostty.
/// Warm starts use AppleScript to create one command window.
/// Cold starts use `initial-command` so the first default surface runs the launcher.
/// Do not use `initial-window=false` plus `new window`: cold launch can still create the default window first.
#[cfg(target_os = "macos")]
fn build_macos_ghostty_applescript(script_file: &std::path::Path) -> String {
format!(
r#"set launcher_command to {launcher}
set was_running to application "Ghostty" is running
if was_running then
tell application "Ghostty"
new window with configuration {{command:launcher_command}}
end tell
else
do shell script "open -na Ghostty --args --quit-after-last-window-closed=true " & quoted form of ("--initial-command=" & launcher_command)
end if
"#,
launcher = applescript_launcher_command(script_file)
)
}
/// macOS: Ghostty
#[cfg(target_os = "macos")]
fn launch_macos_ghostty(script_file: &std::path::Path) -> Result<(), String> {
use std::process::Command;
let output = Command::new("open")
.args([
"-na",
"Ghostty",
"--args",
"--quit-after-last-window-closed=true",
"-e",
"bash",
])
.arg(script_file)
.output()
.map_err(|e| format!("启动 Ghostty 失败: {e}"))?;
if !output.status.success() {
let stderr = decode_command_output(&output.stderr);
return Err(format!(
"Ghostty 启动失败 (exit code: {:?}): {}",
output.status.code(),
stderr
));
match run_terminal_osascript(&build_macos_ghostty_applescript(script_file), "Ghostty") {
Ok(()) => Ok(()),
Err(applescript_error) => {
log::warn!(
"Ghostty AppleScript launch failed, falling back to open -na: {applescript_error}"
);
launch_macos_open_app("Ghostty", script_file, true)
}
}
Ok(())
}
/// macOS: 使用 open -na 启动支持 --args 参数的终端(Alacritty/Kitty/WezTerm/Kaku
@@ -2757,7 +2865,10 @@ fn launch_macos_open_app(
if use_e_flag {
cmd.arg("-e");
}
cmd.arg("bash").arg(script_file);
// Keep the script path inside `bash -c`; a trailing bare `.sh` can be opened as a document.
cmd.arg("bash")
.arg("-c")
.arg(build_macos_dash_c_command(script_file));
let output = cmd
.output()
@@ -4009,8 +4120,9 @@ mod tests {
#[test]
fn codex_nvm_anchors_to_that_npm() {
// Codex 官方 self-update 只在支持的 release 上生效;失败时仍写回同一个
// node 的 npm,而非 PATH 第一个 npm。
// Codex 不走 self-update`codex update` 在 npm 安装上只是裸 `npm install -g`
// 却会假成功掩盖平台二进制漏装)——直接锚定到同一个 node 的 npm,而非 PATH
// 第一个 npm。损坏时的 uninstall+install 自愈见 codex_missing_platform_binary_*。
let cmd = anchored_command_from_paths(
"codex",
"/Users/me/.nvm/versions/node/v22.14.0/bin/codex",
@@ -4018,7 +4130,7 @@ mod tests {
);
assert_eq!(
cmd.as_deref(),
Some("/Users/me/.nvm/versions/node/v22.14.0/bin/codex update || /Users/me/.nvm/versions/node/v22.14.0/bin/npm i -g @openai/codex@latest")
Some("/Users/me/.nvm/versions/node/v22.14.0/bin/npm i -g @openai/codex@latest")
);
}
@@ -4038,9 +4150,25 @@ mod tests {
}
#[test]
fn volta_uses_volta_install() {
fn volta_self_update_chain_anchors_to_volta() {
// `~/.volta/bin` 通常不在 GUI 非登录 `bash -c` 的 PATH 里,且用户可能
// PATH 上还有另一份 volta → 必须绝对路径锚定到命令行命中的这一份。
// 用 openclaw(仍在 prefers_official_update)覆盖 volta 分支的 self-update 链;
// codex 已改为不 self-update(见 codex_volta_anchors_to_volta_install)。
let cmd = anchored_command_from_paths(
"openclaw",
"/Users/me/.volta/bin/openclaw",
"/Users/me/.volta/tools/image/packages/openclaw/lib/node_modules/openclaw",
);
assert_eq!(
cmd.as_deref(),
Some("/Users/me/.volta/bin/openclaw update --yes || /Users/me/.volta/bin/volta install openclaw")
);
}
#[test]
fn codex_volta_anchors_to_volta_install() {
// codex 锚定到命令行命中的那份 volta,但不 self-update:纯 `volta install`。
let cmd = anchored_command_from_paths(
"codex",
"/Users/me/.volta/bin/codex",
@@ -4048,7 +4176,7 @@ mod tests {
);
assert_eq!(
cmd.as_deref(),
Some("/Users/me/.volta/bin/codex update || /Users/me/.volta/bin/volta install @openai/codex")
Some("/Users/me/.volta/bin/volta install @openai/codex")
);
}
@@ -4076,7 +4204,7 @@ mod tests {
);
assert_eq!(
cmd.as_deref(),
Some("'/Users/my name/.volta/bin/codex' update || '/Users/my name/.volta/bin/volta' install @openai/codex")
Some("'/Users/my name/.volta/bin/volta' install @openai/codex")
);
}
@@ -4144,7 +4272,7 @@ mod tests {
assert_eq!(
cmd.as_deref(),
Some(
"/Users/me/.local/share/fnm_multishells/12345_abc/bin/codex update || /Users/me/.local/share/fnm_multishells/12345_abc/bin/npm i -g @openai/codex@latest"
"/Users/me/.local/share/fnm_multishells/12345_abc/bin/npm i -g @openai/codex@latest"
)
);
}
@@ -4158,7 +4286,7 @@ mod tests {
);
assert_eq!(
cmd.as_deref(),
Some("'/Users/my name/.nvm/versions/node/v22/bin/codex' update || '/Users/my name/.nvm/versions/node/v22/bin/npm' i -g @openai/codex@latest")
Some("'/Users/my name/.nvm/versions/node/v22/bin/npm' i -g @openai/codex@latest")
);
}
@@ -4255,6 +4383,78 @@ mod tests {
assert!(default_install(&installs).is_none());
}
#[test]
fn codex_missing_platform_binary_self_heals_via_uninstall_install() {
// 平台二进制缺失 → `codex --version` 报 "Missing optional dependency" 退出非 0
// → enumerate 标记 runnable=false。此状态下普通 `npm i -g @latest` 是 no-op 修不好,
// 升级路径改用 uninstall+install 重装补回平台二进制(`|| true` 让 uninstall 在
// set -e 下对半损坏包返回非 0 时仍继续 install)。
let mut broken = inst("/Users/me/.nvm/versions/node/v22.14.0/bin/codex", true);
broken.runnable = false;
assert_eq!(
installs_anchored_command("codex", &[broken]).as_deref(),
Some("/Users/me/.nvm/versions/node/v22.14.0/bin/npm uninstall -g @openai/codex || true; /Users/me/.nvm/versions/node/v22.14.0/bin/npm i -g @openai/codex@latest")
);
}
#[test]
fn codex_runnable_uses_plain_npm_not_self_heal() {
// 正常(runnable=true)的 codex 升级:锚定 npm,既不重装、也不跑会假成功
// 掩盖损坏的 `codex update`。
let healthy = inst("/Users/me/.nvm/versions/node/v22.14.0/bin/codex", true);
let cmd = installs_anchored_command("codex", &[healthy]);
assert_eq!(
cmd.as_deref(),
Some("/Users/me/.nvm/versions/node/v22.14.0/bin/npm i -g @openai/codex@latest")
);
assert!(!cmd.unwrap().contains("uninstall"));
}
#[test]
fn codex_broken_homebrew_formula_uses_brew_not_npm_repair() {
// brew formula 装的坏 codexreal 在 Cellar):自愈门控必须收窄放行,回落到
// `brew upgrade codex`——若误走 npm 重装,npm 够不到 Cellar 那份、反而旁路
// 装第二份 npm 全局 codex 制造双安装。
let broken = ToolInstallation {
path: "/opt/homebrew/bin/codex".to_string(),
version: None,
runnable: false,
error: None,
source: "homebrew".to_string(),
is_path_default: true,
real: std::path::PathBuf::from("/opt/homebrew/Cellar/codex/1.2.3/bin/codex"),
};
assert_eq!(
installs_anchored_command("codex", &[broken]).as_deref(),
Some("/opt/homebrew/bin/brew upgrade codex")
);
}
#[test]
fn codex_broken_volta_uses_volta_install_not_npm_repair() {
// volta 装的坏 codex:回落到 `volta install`,不走 npm 重装。
let mut broken = inst("/Users/me/.volta/bin/codex", true);
broken.runnable = false;
assert_eq!(
installs_anchored_command("codex", &[broken]).as_deref(),
Some("/Users/me/.volta/bin/volta install @openai/codex")
);
}
#[test]
fn codex_broken_bun_uses_bun_add_not_phantom_npm() {
// bun 装的坏 codex:回落到 `bun add`,且**绝不**拼出 `~/.bun/bin/npm`
// (bun 目录下没有 npm,那条路径不存在、执行会直接失败)。
let mut broken = inst("/Users/me/.bun/bin/codex", true);
broken.runnable = false;
let cmd = installs_anchored_command("codex", &[broken]);
assert_eq!(
cmd.as_deref(),
Some("/Users/me/.bun/bin/bun add -g @openai/codex@latest")
);
assert!(!cmd.unwrap().contains("npm"));
}
#[test]
fn first_abs_path_line_skips_shell_noise() {
// 交互式 .zshrc 先打印欢迎语(如 powerlevel10k / 自定义提示),
@@ -4382,8 +4582,9 @@ mod tests {
);
assert_eq!(
static_fallback_command("codex"),
"codex update || npm i -g @openai/codex@latest"
"npm i -g @openai/codex@latest"
);
assert!(!static_fallback_command("codex").contains("codex update"));
assert_eq!(
static_fallback_command("gemini"),
"npm i -g @google/gemini-cli@latest"
@@ -4693,6 +4894,124 @@ mod tests {
assert!(running_branch.contains("create tab with default profile"));
}
/// Terminal `activate` creates a default empty window on cold start; `launch` does not.
#[cfg(target_os = "macos")]
#[test]
fn terminal_applescript_cold_start_uses_launch_before_do_script() {
let script = build_macos_terminal_applescript(Path::new("/tmp/cc_switch_launcher.sh"));
assert!(
script.contains(r#"set was_running to application "Terminal" is running"#),
"missing was_running detection:\n{script}"
);
// Cold launches avoid `activate` until after `do script`, so no default empty window is created first.
assert!(
script.contains(
"else\n launch\n do script launcher_script\n activate"
),
"cold start should launch before activating:\n{script}"
);
// Already-running launches should create a fresh session.
assert!(
script.contains(
"if was_running then\n activate\n do script launcher_script\n"
),
"already-running branch should use bare do script:\n{script}"
);
}
/// Restored windows should not receive the launcher command.
#[cfg(target_os = "macos")]
#[test]
fn terminal_applescript_does_not_hijack_restored_windows() {
let script = build_macos_terminal_applescript(Path::new("/tmp/cc_switch_launcher.sh"));
assert!(
!script.contains(" in window 1"),
"should not inject into an existing/restored Terminal window:\n{script}"
);
assert!(
!script.contains("count of windows"),
"should not infer restored-window safety from window count:\n{script}"
);
}
/// Ghostty cold starts use `initial-command`; warm starts use the scripting dictionary.
#[cfg(target_os = "macos")]
#[test]
fn ghostty_applescript_cold_start_uses_initial_command() {
let script = build_macos_ghostty_applescript(Path::new("/tmp/cc_switch_launcher.sh"));
// Warm launches execute through the AppleScript command property, not `open -na ... -e`.
assert!(
script.contains(r#"set launcher_command to "bash '/tmp/cc_switch_launcher.sh'""#),
"missing launcher_command:\n{script}"
);
assert!(script.contains("if was_running then"));
assert!(script.contains("new window with configuration {command:launcher_command}"));
assert!(
!script.contains(" --args -e"),
"should not execute through open -na -e:\n{script}"
);
// Cold launches make Ghostty's first default surface execute the launcher.
assert!(script.contains(r#"set was_running to application "Ghostty" is running"#));
assert!(
script.contains(
r#"do shell script "open -na Ghostty --args --quit-after-last-window-closed=true " & quoted form of ("--initial-command=" & launcher_command)"#
),
"cold start should use initial-command:\n{script}"
);
assert!(
!script.contains("--initial-window=false"),
"should not rely on initial-window=false:\n{script}"
);
assert!(
!script.contains("delay 0.5"),
"should not rely on a fixed delay:\n{script}"
);
assert!(
!script.contains("old_ids"),
"should not track default windows for closing:\n{script}"
);
assert!(
!script.contains("close window"),
"should not close a default window:\n{script}"
);
}
#[cfg(target_os = "macos")]
#[test]
fn dash_c_command_wraps_script_path_inside_quoted_arg() {
// The script path must stay inside the `-c` string, not as a bare argv.
let s = build_macos_dash_c_command(Path::new("/tmp/cc_switch_launcher_1.sh"));
assert_eq!(s, "exec bash '/tmp/cc_switch_launcher_1.sh'");
// Spaces and single quotes must stay shell-safe too.
let s2 = build_macos_dash_c_command(Path::new("/Users/me/it's dir/x.sh"));
assert_eq!(s2, r#"exec bash '/Users/me/it'"'"'s dir/x.sh'"#);
}
/// AppleScript launchers need both shell-path quoting and AppleScript string quoting.
#[cfg(target_os = "macos")]
#[test]
fn applescript_builders_safely_quote_special_paths() {
// First shell-quote the path, then wrap the whole command as an AppleScript string.
let expected = r#""bash '/Users/me/it'\"'\"'s dir/x.sh'""#;
let p = Path::new("/Users/me/it's dir/x.sh");
assert_eq!(applescript_launcher_command(p), expected);
assert!(
build_macos_terminal_applescript(p).contains(expected),
"Terminal did not quote safely"
);
assert!(
build_macos_iterm2_applescript(p).contains(expected),
"iTerm2 did not quote safely"
);
assert!(
build_macos_ghostty_applescript(p).contains(expected),
"Ghostty did not quote safely"
);
}
#[test]
fn build_windows_cwd_command_str_uses_cd_for_drive_paths() {
let command = build_windows_cwd_command_str(r"C:\work\repo");
+2
View File
@@ -29,6 +29,7 @@ mod subscription;
mod sync_support;
mod lightweight;
mod s3_sync;
mod usage;
mod webdav_sync;
mod workspace;
@@ -61,6 +62,7 @@ pub use stream_check::*;
pub use subscription::*;
pub use lightweight::*;
pub use s3_sync::*;
pub use usage::*;
pub use webdav_sync::*;
pub use workspace::*;
+6
View File
@@ -14,12 +14,18 @@ pub async fn fetch_models_for_config(
api_key: String,
is_full_url: Option<bool>,
models_url: Option<String>,
custom_user_agent: Option<String>,
) -> Result<Vec<FetchedModel>, String> {
// 与转发 / 检测路径共用 parse_custom_user_agent:非法 UA 静默忽略(不阻断取模型)。
let user_agent = crate::provider::parse_custom_user_agent(custom_user_agent.as_deref())
.ok()
.flatten();
model_fetch::fetch_models(
&base_url,
&api_key,
is_full_url.unwrap_or(false),
models_url.as_deref(),
user_agent,
)
.await
}
+187 -5
View File
@@ -15,6 +15,7 @@ use std::str::FromStr;
const TEMPLATE_TYPE_GITHUB_COPILOT: &str = "github_copilot";
const TEMPLATE_TYPE_TOKEN_PLAN: &str = "token_plan";
const TEMPLATE_TYPE_BALANCE: &str = "balance";
const TEMPLATE_TYPE_OFFICIAL_SUBSCRIPTION: &str = "official_subscription";
const COPILOT_UNIT_PREMIUM: &str = "requests";
/// 获取所有供应商
@@ -417,6 +418,42 @@ fn resolve_native_credentials(app_type: &AppType, provider: Option<&Provider>) -
.unwrap_or_default()
}
fn resolve_coding_plan_credentials(
app_type: &AppType,
provider: Option<&Provider>,
usage_script: Option<&crate::provider::UsageScript>,
) -> (String, String) {
let is_zenmux = usage_script
.and_then(|s| s.coding_plan_provider.as_deref())
.map(|provider| provider.eq_ignore_ascii_case("zenmux"))
.unwrap_or(false);
if !is_zenmux {
return resolve_native_credentials(app_type, provider);
}
let script_base_url = usage_script
.and_then(|s| s.base_url.as_deref())
.unwrap_or("")
.trim_end_matches('/')
.to_string();
let script_api_key = usage_script
.and_then(|s| s.api_key.as_deref())
.unwrap_or("")
.to_string();
if !script_base_url.is_empty() && !script_api_key.is_empty() {
return (script_base_url, script_api_key);
}
let native = resolve_native_credentials(app_type, provider);
if !native.0.is_empty() && !native.1.is_empty() {
native
} else {
(script_base_url, script_api_key)
}
}
async fn query_provider_usage_inner(
state: &AppState,
copilot_state: &CopilotAuthState,
@@ -474,8 +511,8 @@ async fn query_provider_usage_inner(
// ── Coding Plan 专用路径 ──
if template_type == TEMPLATE_TYPE_TOKEN_PLAN {
// 从供应商配置中提取 API Key 和 Base URL(按 app 区分存储格式)
let (base_url, api_key) = resolve_native_credentials(&app_type, provider);
let (base_url, api_key) =
resolve_coding_plan_credentials(&app_type, provider, usage_script);
let quota = crate::services::coding_plan::get_coding_plan_quota(&base_url, &api_key)
.await
@@ -490,6 +527,19 @@ async fn query_provider_usage_inner(
});
}
// ZenMux 的 tier 携带 USD 额度信息,需要编码为 JSON extra
let has_usd = quota
.tiers
.first()
.map(|t| t.used_value_usd.is_some())
.unwrap_or(false);
let plan_label = quota
.credential_message
.as_deref()
.and_then(|msg| msg.split(' ').next())
.map(|tier| format!("ZenMux·{}", tier.to_uppercase()));
let mut first_tier = true;
let data: Vec<crate::provider::UsageData> = quota
.tiers
.iter()
@@ -497,6 +547,26 @@ async fn query_provider_usage_inner(
let total = 100.0;
let used = tier.utilization;
let remaining = total - used;
let extra = if has_usd {
let mut extra_json = serde_json::json!({
"resetsAt": tier.resets_at,
});
if let Some(v) = tier.used_value_usd {
extra_json["usedValueUsd"] = serde_json::json!(v);
}
if let Some(v) = tier.max_value_usd {
extra_json["maxValueUsd"] = serde_json::json!(v);
}
if first_tier {
if let Some(ref label) = plan_label {
extra_json["planLabel"] = serde_json::json!(label);
}
first_tier = false;
}
Some(extra_json.to_string())
} else {
tier.resets_at.clone()
};
crate::provider::UsageData {
plan_name: Some(tier.name.clone()),
remaining: Some(remaining),
@@ -505,7 +575,7 @@ async fn query_provider_usage_inner(
unit: Some("%".to_string()),
is_valid: Some(true),
invalid_message: None,
extra: tier.resets_at.clone(),
extra,
}
})
.collect();
@@ -527,6 +597,50 @@ async fn query_provider_usage_inner(
.map_err(|e| format!("Failed to query balance: {e}"));
}
// ── 官方订阅额度查询路径 ──
if template_type == TEMPLATE_TYPE_OFFICIAL_SUBSCRIPTION {
if !usage_script.map(|s| s.enabled).unwrap_or(false) {
return Ok(crate::provider::UsageResult {
success: false,
data: None,
error: Some("Usage query is disabled".to_string()),
});
}
let quota = crate::services::subscription::get_subscription_quota(app_type.as_str())
.await
.map_err(|e| format!("Failed to query subscription quota: {e}"))?;
if !quota.success {
return Ok(crate::provider::UsageResult {
success: false,
data: None,
error: quota.error.or(quota.credential_message),
});
}
let data: Vec<crate::provider::UsageData> = quota
.tiers
.iter()
.map(|tier| crate::provider::UsageData {
plan_name: Some(tier.name.clone()),
remaining: Some(100.0 - tier.utilization),
total: Some(100.0),
used: Some(tier.utilization),
unit: Some("%".to_string()),
is_valid: Some(true),
invalid_message: None,
extra: tier.resets_at.clone(),
})
.collect();
return Ok(crate::provider::UsageResult {
success: true,
data: if data.is_empty() { None } else { Some(data) },
error: None,
});
}
// ── 通用 JS 脚本路径 ──
ProviderService::query_usage(state, app_type, provider_id)
.await
@@ -950,11 +1064,31 @@ mod import_claude_desktop_tests {
#[cfg(test)]
mod native_query_credentials_tests {
use super::resolve_native_credentials;
use super::{resolve_coding_plan_credentials, resolve_native_credentials};
use crate::app_config::AppType;
use crate::provider::Provider;
use crate::provider::{Provider, UsageScript};
use serde_json::json;
fn usage_script(
coding_plan_provider: Option<&str>,
base_url: Option<&str>,
api_key: Option<&str>,
) -> UsageScript {
UsageScript {
enabled: true,
language: "javascript".to_string(),
code: String::new(),
timeout: Some(10),
api_key: api_key.map(str::to_string),
base_url: base_url.map(str::to_string),
access_token: None,
user_id: None,
template_type: Some("token_plan".to_string()),
auto_query_interval: None,
coding_plan_provider: coding_plan_provider.map(str::to_string),
}
}
#[test]
fn delegates_to_provider_for_codex() {
let provider = Provider::with_id(
@@ -979,4 +1113,52 @@ mod native_query_credentials_tests {
assert!(base_url.is_empty());
assert!(api_key.is_empty());
}
#[test]
fn zenmux_coding_plan_uses_script_credentials_first() {
let provider = Provider::with_id(
"test".to_string(),
"Test".to_string(),
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://provider.zenmux.example/v1",
"ANTHROPIC_AUTH_TOKEN": "sk-provider"
}
}),
None,
);
let script = usage_script(
Some("zenmux"),
Some("https://script.zenmux.example/api/usage/"),
Some("sk-script"),
);
let (base_url, api_key) =
resolve_coding_plan_credentials(&AppType::Claude, Some(&provider), Some(&script));
assert_eq!(base_url, "https://script.zenmux.example/api/usage");
assert_eq!(api_key, "sk-script");
}
#[test]
fn zenmux_coding_plan_falls_back_to_provider_credentials() {
let provider = Provider::with_id(
"test".to_string(),
"Test".to_string(),
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://provider.zenmux.example/v1",
"ANTHROPIC_AUTH_TOKEN": "sk-provider"
}
}),
None,
);
let script = usage_script(Some("zenmux"), Some("https://script.zenmux.example"), None);
let (base_url, api_key) =
resolve_coding_plan_credentials(&AppType::Claude, Some(&provider), Some(&script));
assert_eq!(base_url, "https://provider.zenmux.example/v1");
assert_eq!(api_key, "sk-provider");
}
}
+352
View File
@@ -0,0 +1,352 @@
#![allow(non_snake_case)]
use serde_json::{json, Value};
use tauri::State;
use crate::commands::sync_support::{
attach_warning, post_sync_warning_from_result, run_post_import_sync,
};
use crate::error::AppError;
use crate::services::s3_sync as s3_sync_service;
use crate::settings::{self, S3SyncSettings};
use crate::store::AppState;
fn persist_sync_error(settings: &mut S3SyncSettings, error: &AppError, source: &str) {
settings.status.last_error = Some(error.to_string());
settings.status.last_error_source = Some(source.to_string());
let _ = settings::update_s3_sync_status(settings.status.clone());
}
fn s3_not_configured_error() -> String {
AppError::localized(
"s3.sync.not_configured",
"未配置 S3 同步",
"S3 sync is not configured.",
)
.to_string()
}
fn s3_sync_disabled_error() -> String {
AppError::localized("s3.sync.disabled", "S3 同步未启用", "S3 sync is disabled.").to_string()
}
fn require_enabled_s3_settings() -> Result<S3SyncSettings, String> {
let settings = settings::get_s3_sync_settings().ok_or_else(s3_not_configured_error)?;
if !settings.enabled {
return Err(s3_sync_disabled_error());
}
Ok(settings)
}
fn resolve_secret_for_request(
mut incoming: S3SyncSettings,
existing: Option<S3SyncSettings>,
preserve_empty_secret: bool,
) -> S3SyncSettings {
if let Some(existing_settings) = existing {
if preserve_empty_secret && incoming.secret_access_key.is_empty() {
incoming.secret_access_key = existing_settings.secret_access_key;
}
}
incoming
}
#[cfg(test)]
fn s3_sync_mutex() -> &'static tokio::sync::Mutex<()> {
s3_sync_service::sync_mutex()
}
async fn run_with_s3_lock<T, Fut>(operation: Fut) -> Result<T, AppError>
where
Fut: std::future::Future<Output = Result<T, AppError>>,
{
s3_sync_service::run_with_sync_lock(operation).await
}
fn map_sync_result<T, F>(result: Result<T, AppError>, on_error: F) -> Result<T, String>
where
F: FnOnce(&AppError),
{
match result {
Ok(value) => Ok(value),
Err(err) => {
on_error(&err);
Err(err.to_string())
}
}
}
#[tauri::command]
pub async fn s3_test_connection(
settings: S3SyncSettings,
#[allow(non_snake_case)] preserveEmptyPassword: Option<bool>,
) -> Result<Value, String> {
let preserve_empty = preserveEmptyPassword.unwrap_or(true);
let resolved =
resolve_secret_for_request(settings, settings::get_s3_sync_settings(), preserve_empty);
s3_sync_service::check_connection(&resolved)
.await
.map_err(|e| e.to_string())?;
Ok(json!({
"success": true,
"message": "S3 connection ok"
}))
}
#[tauri::command]
pub async fn s3_sync_upload(state: State<'_, AppState>) -> Result<Value, String> {
let db = state.db.clone();
let mut settings = require_enabled_s3_settings()?;
let result = run_with_s3_lock(s3_sync_service::upload(&db, &mut settings)).await;
map_sync_result(result, |error| {
persist_sync_error(&mut settings, error, "manual")
})
}
#[tauri::command]
pub async fn s3_sync_download(state: State<'_, AppState>) -> Result<Value, String> {
let db = state.db.clone();
let db_for_sync = db.clone();
let mut settings = require_enabled_s3_settings()?;
let _auto_sync_suppression = crate::services::s3_auto_sync::AutoSyncSuppressionGuard::new();
let sync_result = run_with_s3_lock(s3_sync_service::download(&db, &mut settings)).await;
let mut result = map_sync_result(sync_result, |error| {
persist_sync_error(&mut settings, error, "manual")
})?;
// Post-download sync is best-effort: snapshot restore has already succeeded.
let warning = post_sync_warning_from_result(
tauri::async_runtime::spawn_blocking(move || run_post_import_sync(db_for_sync))
.await
.map_err(|e| e.to_string()),
);
if let Some(msg) = warning.as_ref() {
log::warn!("[S3] post-download sync warning: {msg}");
}
result = attach_warning(result, warning);
Ok(result)
}
#[tauri::command]
pub async fn s3_sync_save_settings(
settings: S3SyncSettings,
#[allow(non_snake_case)] passwordTouched: Option<bool>,
) -> Result<Value, String> {
let password_touched = passwordTouched.unwrap_or(false);
let existing = settings::get_s3_sync_settings();
let mut sync_settings =
resolve_secret_for_request(settings, existing.clone(), !password_touched);
// Preserve server-owned fields that the frontend does not manage
if let Some(existing_settings) = existing {
sync_settings.status = existing_settings.status;
}
sync_settings.normalize();
sync_settings.validate().map_err(|e| e.to_string())?;
settings::set_s3_sync_settings(Some(sync_settings)).map_err(|e| e.to_string())?;
Ok(json!({ "success": true }))
}
#[tauri::command]
pub async fn s3_sync_fetch_remote_info() -> Result<Value, String> {
let settings = require_enabled_s3_settings()?;
let info = s3_sync_service::fetch_remote_info(&settings)
.await
.map_err(|e| e.to_string())?;
Ok(info.unwrap_or(json!({ "empty": true })))
}
#[cfg(test)]
mod tests {
use super::{
map_sync_result, persist_sync_error, require_enabled_s3_settings,
resolve_secret_for_request, run_with_s3_lock, s3_sync_mutex,
};
use crate::error::AppError;
use crate::settings::{AppSettings, S3SyncSettings};
use serial_test::serial;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
#[tokio::test]
async fn s3_sync_mutex_is_singleton() {
let a = s3_sync_mutex() as *const _;
let b = s3_sync_mutex() as *const _;
assert_eq!(a, b);
}
#[tokio::test]
#[serial]
async fn s3_sync_mutex_serializes_concurrent_access() {
let guard = s3_sync_mutex().lock().await;
let acquired = Arc::new(AtomicBool::new(false));
let acquired_bg = Arc::clone(&acquired);
let waiter = tokio::spawn(async move {
let _inner_guard = s3_sync_mutex().lock().await;
acquired_bg.store(true, Ordering::SeqCst);
});
tokio::time::sleep(Duration::from_millis(40)).await;
assert!(!acquired.load(Ordering::SeqCst));
drop(guard);
tokio::time::timeout(Duration::from_secs(1), waiter)
.await
.expect("background task should complete after lock release")
.expect("background task should not panic");
assert!(acquired.load(Ordering::SeqCst));
}
#[tokio::test]
#[serial]
async fn map_sync_result_runs_error_handler_after_lock_release() {
let result =
run_with_s3_lock(async { Err::<(), AppError>(AppError::Config("boom".to_string())) })
.await;
let mut lock_released = false;
let mapped = map_sync_result(result, |_| {
lock_released = s3_sync_mutex().try_lock().is_ok();
});
assert!(mapped.is_err());
assert!(lock_released);
}
#[test]
fn resolve_secret_for_request_preserves_existing_when_requested() {
let incoming = S3SyncSettings {
region: "us-east-1".to_string(),
bucket: "my-bucket".to_string(),
access_key_id: "AKID".to_string(),
secret_access_key: String::new(),
..S3SyncSettings::default()
};
let existing = Some(S3SyncSettings {
secret_access_key: "SECRET".to_string(),
..S3SyncSettings::default()
});
let resolved = resolve_secret_for_request(incoming, existing, true);
assert_eq!(resolved.secret_access_key, "SECRET");
}
#[test]
fn resolve_secret_for_request_allows_explicit_empty_secret() {
let incoming = S3SyncSettings {
region: "us-east-1".to_string(),
bucket: "my-bucket".to_string(),
access_key_id: "AKID".to_string(),
secret_access_key: String::new(),
..S3SyncSettings::default()
};
let existing = Some(S3SyncSettings {
secret_access_key: "SECRET".to_string(),
..S3SyncSettings::default()
});
let resolved = resolve_secret_for_request(incoming, existing, false);
assert!(resolved.secret_access_key.is_empty());
}
#[test]
#[serial]
fn persist_sync_error_updates_status_without_overwriting_credentials() {
let test_home = std::env::temp_dir().join("cc-switch-s3-sync-error-status-test");
let _ = std::fs::remove_dir_all(&test_home);
std::fs::create_dir_all(&test_home).expect("create test home");
std::env::set_var("CC_SWITCH_TEST_HOME", &test_home);
crate::settings::update_settings(AppSettings::default()).expect("reset settings");
let mut current = S3SyncSettings {
enabled: true,
region: "us-east-1".to_string(),
bucket: "my-bucket".to_string(),
access_key_id: "AKID".to_string(),
secret_access_key: "SECRET".to_string(),
remote_root: "cc-switch-sync".to_string(),
profile: "default".to_string(),
..S3SyncSettings::default()
};
crate::settings::set_s3_sync_settings(Some(current.clone())).expect("seed s3 settings");
persist_sync_error(
&mut current,
&crate::error::AppError::Config("boom".to_string()),
"manual",
);
let after = crate::settings::get_s3_sync_settings().expect("read s3 settings");
assert_eq!(after.region, "us-east-1");
assert_eq!(after.bucket, "my-bucket");
assert_eq!(after.access_key_id, "AKID");
assert_eq!(after.secret_access_key, "SECRET");
assert_eq!(after.remote_root, "cc-switch-sync");
assert_eq!(after.profile, "default");
assert!(
after
.status
.last_error
.as_deref()
.unwrap_or_default()
.contains("boom"),
"status error should be updated"
);
assert_eq!(after.status.last_error_source.as_deref(), Some("manual"));
}
#[test]
#[serial]
fn require_enabled_s3_settings_rejects_disabled_config() {
let test_home = std::env::temp_dir().join("cc-switch-s3-sync-enabled-disabled-test");
let _ = std::fs::remove_dir_all(&test_home);
std::fs::create_dir_all(&test_home).expect("create test home");
std::env::set_var("CC_SWITCH_TEST_HOME", &test_home);
crate::settings::update_settings(AppSettings::default()).expect("reset settings");
crate::settings::set_s3_sync_settings(Some(S3SyncSettings {
enabled: false,
region: "us-east-1".to_string(),
bucket: "my-bucket".to_string(),
access_key_id: "AKID".to_string(),
secret_access_key: "SECRET".to_string(),
..S3SyncSettings::default()
}))
.expect("seed disabled s3 settings");
let err = require_enabled_s3_settings().expect_err("disabled settings should fail");
assert!(
err.contains("disabled") || err.contains("未启用"),
"unexpected error: {err}"
);
}
#[test]
#[serial]
fn require_enabled_s3_settings_returns_settings_when_enabled() {
let test_home = std::env::temp_dir().join("cc-switch-s3-sync-enabled-ok-test");
let _ = std::fs::remove_dir_all(&test_home);
std::fs::create_dir_all(&test_home).expect("create test home");
std::env::set_var("CC_SWITCH_TEST_HOME", &test_home);
crate::settings::update_settings(AppSettings::default()).expect("reset settings");
crate::settings::set_s3_sync_settings(Some(S3SyncSettings {
enabled: true,
region: "us-east-1".to_string(),
bucket: "my-bucket".to_string(),
access_key_id: "AKID".to_string(),
secret_access_key: "SECRET".to_string(),
..S3SyncSettings::default()
}))
.expect("seed enabled s3 settings");
let settings = require_enabled_s3_settings().expect("enabled settings should be accepted");
assert!(settings.enabled);
assert_eq!(settings.region, "us-east-1");
}
}
+323 -18
View File
@@ -1,6 +1,7 @@
#![allow(non_snake_case)]
use tauri::AppHandle;
use tauri_plugin_updater::UpdaterExt;
fn merge_settings_for_save(
mut incoming: crate::settings::AppSettings,
@@ -21,24 +22,25 @@ fn merge_settings_for_save(
}
_ => {}
}
if incoming.local_migrations.is_none() {
incoming.local_migrations = existing.local_migrations.clone();
} else if let (Some(incoming_migrations), Some(existing_migrations)) =
(&mut incoming.local_migrations, &existing.local_migrations)
{
if incoming_migrations
.codex_third_party_history_provider_bucket_v1
.is_none()
match (&mut incoming.s3_sync, &existing.s3_sync) {
// incoming 没有 s3 → 保留现有
(None, _) => {
incoming.s3_sync = existing.s3_sync.clone();
}
// incoming 有 s3 但密钥为空,且现有有密钥 → 填回现有密钥
(Some(incoming_sync), Some(existing_sync))
if incoming_sync.secret_access_key.is_empty()
&& !existing_sync.secret_access_key.is_empty() =>
{
incoming_migrations.codex_third_party_history_provider_bucket_v1 = existing_migrations
.codex_third_party_history_provider_bucket_v1
.clone();
}
if incoming_migrations.codex_provider_template_v1.is_none() {
incoming_migrations.codex_provider_template_v1 =
existing_migrations.codex_provider_template_v1.clone();
incoming_sync.secret_access_key = existing_sync.secret_access_key.clone();
}
_ => {}
}
// local_migrations 是纯后端状态(迁移完成标记),前端没有合法的修改场景,
// 无条件取现有值。若按 incoming 透传:后端清掉 marker(如关闭统一会话
// 开关)后、前端 query 缓存刷新前的一次全量保存会把旧 marker 重放回来,
// 重新开启时被"复活"的标记挡住而漏迁。
incoming.local_migrations = existing.local_migrations.clone();
incoming
}
@@ -50,13 +52,117 @@ pub async fn get_settings() -> Result<crate::settings::AppSettings, String> {
/// 保存设置
#[tauri::command]
pub async fn save_settings(settings: crate::settings::AppSettings) -> Result<bool, String> {
pub async fn save_settings(
state: tauri::State<'_, crate::store::AppState>,
settings: crate::settings::AppSettings,
) -> Result<bool, String> {
let existing = crate::settings::get_settings();
let merged = merge_settings_for_save(settings, &existing);
let unify_codex_changed =
merged.unify_codex_session_history != existing.unify_codex_session_history;
let unify_codex_enabled = merged.unify_codex_session_history;
crate::settings::update_settings(merged).map_err(|e| e.to_string())?;
// 统一会话开关变更时立即重写当前官方 Codex 供应商的 live 配置,
// 不必等下一次切换才生效。
if unify_codex_changed {
// live 重写失败时回滚设置并把保存整体报失败:若设置保持已切换状态,
// live 仍跑旧桶,后续的历史迁移/还原会让会话再次分裂(开启=历史
// 迁走而新会话仍写 openai 桶;关闭=会话还原而 live 仍写 custom)。
// 报错让前端 saved=false 短路还原;回滚是整次保存的事务语义
// (本开关的保存只携带开关相关字段)。
if let Err(err) =
crate::services::provider::reapply_current_codex_official_live(state.inner())
{
log::warn!("统一 Codex 会话历史开关变更后重写 live 配置失败,回滚设置: {err}");
if let Err(rollback_err) = crate::settings::update_settings(existing) {
log::error!("回滚统一会话开关设置失败: {rollback_err}");
}
return Err(format!(
"统一 Codex 会话历史开关未生效(live 配置重写失败): {err}"
));
}
if unify_codex_enabled {
// 后台执行存量迁移(openai 桶 → custom 桶;仅当用户勾选了迁入既有
// 会话,函数内部自门控)。大会话目录可能要读数秒,不能阻塞设置保存;
// 失败时不写完成标记,下次启动自动重试。
tauri::async_runtime::spawn_blocking(|| {
match crate::codex_history_migration::maybe_migrate_codex_official_history_to_unified_bucket() {
Ok(outcome) => {
if let Some(reason) = outcome.skipped_reason {
log::debug!("○ Codex official history unify migration skipped: {reason}");
} else {
log::info!(
"✓ Codex official history unify migration completed: jsonl_files={}, state_rows={}",
outcome.migrated_jsonl_files,
outcome.migrated_state_rows
);
}
}
Err(e) => {
log::warn!("✗ Codex official history unify migration failed: {e}");
}
}
});
} else {
// 清除标记与迁移意愿,让重新开启并再次勾选时能补迁
// 关闭期间落入 openai 桶的官方会话。
if let Err(err) = crate::settings::clear_codex_official_history_unify_migration() {
log::warn!("清除统一会话迁移标记失败: {err}");
}
if let Err(err) = crate::settings::clear_codex_unify_migrate_existing() {
log::warn!("清除统一会话迁移意愿失败: {err}");
}
}
}
Ok(true)
}
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CodexUnifyHistoryRestoreResult {
pub restored_jsonl_files: usize,
pub restored_state_rows: usize,
/// 还原被跳过的原因(如当前目录没有账本),前端据此提示而非报"成功 0 项"。
#[serde(skip_serializing_if = "Option::is_none")]
pub skipped_reason: Option<String>,
}
/// 是否存在统一会话开关的迁移备份(决定关闭弹窗里是否显示"恢复备份"勾选)。
#[tauri::command]
pub async fn has_codex_unify_history_backup() -> Result<bool, String> {
Ok(crate::codex_history_migration::has_codex_official_history_unify_backup())
}
/// 按迁移备份账本把当时迁入共享桶的官方会话还原回 "openai" 桶。
/// 由关闭统一会话开关的确认弹窗触发;幂等,可安全重试。
#[tauri::command]
pub async fn restore_codex_unified_history() -> Result<CodexUnifyHistoryRestoreResult, String> {
let outcome = tauri::async_runtime::spawn_blocking(|| {
crate::codex_history_migration::restore_codex_official_history_from_backups()
})
.await
.map_err(|e| e.to_string())?
.map_err(|e| e.to_string())?;
if let Some(reason) = &outcome.skipped_reason {
log::debug!("○ Codex official history restore skipped: {reason}");
} else {
log::info!(
"✓ Codex official history restored from backups: jsonl_files={}, state_rows={}",
outcome.restored_jsonl_files,
outcome.restored_state_rows
);
}
Ok(CodexUnifyHistoryRestoreResult {
restored_jsonl_files: outcome.restored_jsonl_files,
restored_state_rows: outcome.restored_state_rows,
skipped_reason: outcome.skipped_reason,
})
}
/// 重启应用程序(当 app_config_dir 变更后使用)
#[tauri::command]
pub async fn restart_app(app: AppHandle) -> Result<bool, String> {
@@ -65,11 +171,80 @@ pub async fn restart_app(app: AppHandle) -> Result<bool, String> {
// 在后台延迟重启,让函数有时间返回响应
tauri::async_runtime::spawn(async move {
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
// app.restart() 走 RESTART_EXIT_CODE 路径,ExitRequested 处理器会直接
// 放行给 Tauri 默认 re-exec,不执行代理/Live 清理。但本命令用于
// app_config_dir 变更后的重启:新实例会切到新数据库,拿不到旧库里的
// Live 备份,无法恢复被接管的 Live 配置。因此必须趁旧实例的事件循环
// 仍存活,在这里同步完成恢复(保留代理状态,新实例启动时自动重新接管)。
crate::cleanup_before_exit(&app).await;
app.restart();
});
Ok(true)
}
/// 下载并安装应用更新,然后由后端直接重启应用。
///
/// macOS 更新会原地替换 `.app` bundle。如果先返回前端、再让旧 WebView 调
/// `process.relaunch()`,旧进程可能已经处在 bundle 被替换后的不稳定窗口期。
/// 这里把退出清理、安装和重启串在同一个后端流程中,避免依赖旧前端继续执行。
#[tauri::command]
pub async fn install_update_and_restart(app: AppHandle) -> Result<bool, String> {
let updater = app
.updater_builder()
.build()
.map_err(|e| format!("初始化更新器失败: {e}"))?;
let Some(update) = updater
.check()
.await
.map_err(|e| format!("检查更新失败: {e}"))?
else {
return Ok(false);
};
log::info!("开始下载应用更新: {}", update.version);
let bytes = update
.download(|_, _| {}, || {})
.await
.map_err(|e| format!("下载更新失败: {e}"))?;
log::info!("开始安装应用更新: {}", update.version);
#[cfg(target_os = "windows")]
{
// Windows updater 会在 install() 内启动安装器并直接退出当前进程
// (插件内部 std::process::exit(0),绕过 TrayIcon::drop、不发
// NIM_DELETE,会残留死图标——与托盘"退出"路径相同的问题)。
// 因此清理只能放在 install 前执行,且必须显式移除托盘图标。
crate::save_window_state_before_exit(&app);
crate::cleanup_before_exit(&app).await;
crate::remove_tray_icon_before_exit(&app);
crate::destroy_single_instance_lock(&app);
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
update.install(bytes).map_err(|e| {
format!(
"Windows 更新安装失败: {e}。已执行退出前清理,代理或 Live 接管可能已暂停;请重启应用或重新开启代理后再试。"
)
})?;
return Ok(true);
}
#[cfg(not(target_os = "windows"))]
{
// macOS/Linux install() 会返回;先安装,避免安装失败时误停代理/撤回接管。
update
.install(bytes)
.map_err(|e| format!("安装更新失败: {e}"))?;
crate::save_window_state_before_exit(&app);
crate::cleanup_before_exit(&app).await;
log::info!("应用更新安装完成,正在重启应用");
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
crate::restart_process(&app);
}
}
/// 获取 app_config_dir 覆盖配置 (从 Store)
#[tauri::command]
pub async fn get_app_config_dir_override(app: AppHandle) -> Result<Option<String>, String> {
@@ -102,8 +277,9 @@ pub async fn set_auto_launch(enabled: bool) -> Result<bool, String> {
mod tests {
use super::merge_settings_for_save;
use crate::settings::{
AppSettings, CodexProviderTemplateMigration, CodexThirdPartyHistoryProviderBucketMigration,
LocalMigrations, WebDavSyncSettings,
AppSettings, CodexOfficialHistoryUnifyMigration, CodexProviderTemplateMigration,
CodexThirdPartyHistoryProviderBucketMigration, LocalMigrations, S3SyncSettings,
WebDavSyncSettings,
};
#[test]
@@ -226,6 +402,64 @@ mod tests {
);
}
#[test]
fn save_settings_should_preserve_existing_s3_when_payload_omits_it() {
let existing = AppSettings {
s3_sync: Some(S3SyncSettings {
bucket: "bucket".to_string(),
access_key_id: "ak".to_string(),
secret_access_key: "secret".to_string(),
..S3SyncSettings::default()
}),
..AppSettings::default()
};
let incoming = AppSettings::default();
let merged = merge_settings_for_save(incoming, &existing);
assert!(merged.s3_sync.is_some());
assert_eq!(
merged
.s3_sync
.as_ref()
.map(|v| v.secret_access_key.as_str()),
Some("secret")
);
}
#[test]
fn save_settings_should_preserve_s3_secret_when_incoming_has_empty_secret() {
let existing = AppSettings {
s3_sync: Some(S3SyncSettings {
bucket: "bucket".to_string(),
access_key_id: "ak".to_string(),
secret_access_key: "secret".to_string(),
..S3SyncSettings::default()
}),
..AppSettings::default()
};
let incoming = AppSettings {
s3_sync: Some(S3SyncSettings {
bucket: "bucket".to_string(),
access_key_id: "ak".to_string(),
secret_access_key: "".to_string(),
..S3SyncSettings::default()
}),
..AppSettings::default()
};
let merged = merge_settings_for_save(incoming, &existing);
assert_eq!(
merged
.s3_sync
.as_ref()
.map(|v| v.secret_access_key.as_str()),
Some("secret")
);
}
#[test]
fn save_settings_should_preserve_local_migrations_when_payload_omits_it() {
let existing = AppSettings {
@@ -244,6 +478,13 @@ mod tests {
completed_at: "2026-05-20T00:01:00Z".to_string(),
migrated_provider_ids: vec!["legacy".to_string()],
}),
codex_official_history_unify_v1: Some(CodexOfficialHistoryUnifyMigration {
completed_at: "2026-06-12T00:00:00Z".to_string(),
target_provider_id: "custom".to_string(),
migrated_jsonl_files: 5,
migrated_state_rows: 7,
codex_config_dir: None,
}),
}),
..AppSettings::default()
};
@@ -273,6 +514,70 @@ mod tests {
template_migration.migrated_provider_ids,
vec!["legacy".to_string()]
);
let unify_migration = merged
.local_migrations
.as_ref()
.and_then(|migrations| migrations.codex_official_history_unify_v1.as_ref())
.expect("official unify migration marker should be preserved");
assert_eq!(unify_migration.migrated_jsonl_files, 5);
assert_eq!(unify_migration.migrated_state_rows, 7);
}
/// incoming 带有 local_migrations(哪怕是空的)也不能覆盖后端维护的标记。
#[test]
fn save_settings_should_keep_backend_migration_markers_over_incoming() {
let existing = AppSettings {
local_migrations: Some(LocalMigrations {
codex_third_party_history_provider_bucket_v1: None,
codex_provider_template_v1: None,
codex_official_history_unify_v1: Some(CodexOfficialHistoryUnifyMigration {
completed_at: "2026-06-12T00:00:00Z".to_string(),
target_provider_id: "custom".to_string(),
migrated_jsonl_files: 1,
migrated_state_rows: 2,
codex_config_dir: None,
}),
}),
..AppSettings::default()
};
let incoming = AppSettings {
local_migrations: Some(LocalMigrations::default()),
..AppSettings::default()
};
let merged = merge_settings_for_save(incoming, &existing);
assert!(merged
.local_migrations
.as_ref()
.and_then(|migrations| migrations.codex_official_history_unify_v1.as_ref())
.is_some());
}
/// 后端清掉 marker 后(如关闭统一会话开关)、前端缓存刷新前的全量保存
/// 会携带旧 markermerge 必须忽略它,否则被"复活"的标记会让重新开启
/// 时误判已迁移而漏迁。
#[test]
fn save_settings_should_ignore_stale_incoming_migration_markers() {
let existing = AppSettings::default();
let incoming = AppSettings {
local_migrations: Some(LocalMigrations {
codex_official_history_unify_v1: Some(CodexOfficialHistoryUnifyMigration {
completed_at: "2026-06-12T00:00:00Z".to_string(),
target_provider_id: "custom".to_string(),
migrated_jsonl_files: 1,
migrated_state_rows: 2,
codex_config_dir: None,
}),
..LocalMigrations::default()
}),
..AppSettings::default()
};
let merged = merge_settings_for_save(incoming, &existing);
assert!(merged.local_migrations.is_none());
}
}
+30 -151
View File
@@ -1,4 +1,7 @@
//! 流式健康检查命令
//! 供应商连通性检查命令
//!
//! 注意:本检查只探测 base_url 是否可达,不发真实大模型请求,也不触碰故障转移
//! 熔断器(熔断器由真实转发流量驱动)。详见 `services::stream_check`。
use crate::app_config::AppType;
use crate::commands::copilot::CopilotAuthState;
@@ -10,7 +13,7 @@ use crate::store::AppState;
use std::collections::HashSet;
use tauri::State;
/// 流式健康检查(单个供应商)
/// 连通性检查(单个供应商)
#[tauri::command]
pub async fn stream_check_provider(
state: State<'_, AppState>,
@@ -25,25 +28,12 @@ pub async fn stream_check_provider(
.get(&provider_id)
.ok_or_else(|| AppError::Message(format!("供应商 {provider_id} 不存在")))?;
let auth_override = resolve_copilot_auth_override(provider, &copilot_state).await?;
// Copilot 端点是动态的(随 OAuth token 解析),需预先取出 host 再探测;
// 其余供应商传 None,由服务层从 settings_config 提取 base_url。无需鉴权。
let base_url_override = resolve_copilot_base_url_override(provider, &copilot_state).await?;
let claude_api_format_override = resolve_claude_api_format_override(
&app_type,
provider,
&config,
&copilot_state,
auth_override.as_ref(),
)
.await?;
let result = StreamCheckService::check_with_retry(
&app_type,
provider,
&config,
auth_override,
base_url_override,
claude_api_format_override,
)
.await?;
let result =
StreamCheckService::check_with_retry(&app_type, provider, &config, base_url_override)
.await?;
// 记录日志
let _ =
@@ -54,7 +44,7 @@ pub async fn stream_check_provider(
Ok(result)
}
/// 批量流式健康检查
/// 批量连通性检查
#[tauri::command]
pub async fn stream_check_all_providers(
state: State<'_, AppState>,
@@ -65,7 +55,6 @@ pub async fn stream_check_all_providers(
let config = state.db.get_stream_check_config()?;
let providers = state.db.get_all_providers(app_type.as_str())?;
let mut results = Vec::new();
let allowed_ids: Option<HashSet<String>> = if proxy_targets_only {
let mut ids = HashSet::new();
if let Ok(Some(current_id)) = state.db.get_current_provider(app_type.as_str()) {
@@ -81,6 +70,7 @@ pub async fn stream_check_all_providers(
None
};
let mut results = Vec::new();
for (id, provider) in providers {
if let Some(ids) = &allowed_ids {
if !ids.contains(&id) {
@@ -88,54 +78,22 @@ pub async fn stream_check_all_providers(
}
}
let auth_override = resolve_copilot_auth_override(&provider, &copilot_state).await?;
let base_url_override =
resolve_copilot_base_url_override(&provider, &copilot_state).await?;
let claude_api_format_override = resolve_claude_api_format_override(
&app_type,
&provider,
&config,
&copilot_state,
auth_override.as_ref(),
)
.await
.unwrap_or_else(|e| {
log::warn!(
"[StreamCheck] Failed to resolve Claude API format override for {}: {}",
provider.id,
e
);
None
});
let result = StreamCheckService::check_with_retry(
&app_type,
&provider,
&config,
auth_override,
base_url_override,
claude_api_format_override,
)
.await
.unwrap_or_else(|e| {
let (http_status, message) = match &e {
crate::error::AppError::HttpStatus { status, .. } => (
Some(*status),
StreamCheckService::classify_http_status(*status).to_string(),
),
_ => (None, e.to_string()),
};
StreamCheckResult {
status: HealthStatus::Failed,
success: false,
message,
response_time_ms: None,
http_status,
model_used: String::new(),
tested_at: chrono::Utc::now().timestamp(),
retry_count: 0,
error_category: None,
}
});
let result =
StreamCheckService::check_with_retry(&app_type, &provider, &config, base_url_override)
.await
.unwrap_or_else(|e| StreamCheckResult {
status: HealthStatus::Failed,
success: false,
message: e.to_string(),
response_time_ms: None,
http_status: None,
model_used: String::new(),
tested_at: chrono::Utc::now().timestamp(),
retry_count: 0,
error_category: None,
});
let _ = state
.db
@@ -147,13 +105,13 @@ pub async fn stream_check_all_providers(
Ok(results)
}
/// 获取流式检查配置
/// 获取连通性检查配置
#[tauri::command]
pub fn get_stream_check_config(state: State<'_, AppState>) -> Result<StreamCheckConfig, AppError> {
state.db.get_stream_check_config()
}
/// 保存流式检查配置
/// 保存连通性检查配置
#[tauri::command]
pub fn save_stream_check_config(
state: State<'_, AppState>,
@@ -162,39 +120,8 @@ pub fn save_stream_check_config(
state.db.save_stream_check_config(&config)
}
async fn resolve_copilot_auth_override(
provider: &crate::provider::Provider,
copilot_state: &State<'_, CopilotAuthState>,
) -> Result<Option<crate::proxy::providers::AuthInfo>, AppError> {
let is_copilot = is_copilot_provider(provider);
if !is_copilot {
return Ok(None);
}
let auth_manager = copilot_state.0.read().await;
let account_id = provider
.meta
.as_ref()
.and_then(|meta| meta.managed_account_id_for("github_copilot"));
let token = match account_id.as_deref() {
Some(id) => auth_manager
.get_valid_token_for_account(id)
.await
.map_err(|e| AppError::Message(format!("GitHub Copilot 认证失败: {e}")))?,
None => auth_manager
.get_valid_token()
.await
.map_err(|e| AppError::Message(format!("GitHub Copilot 认证失败: {e}")))?,
};
Ok(Some(crate::proxy::providers::AuthInfo::new(
token,
crate::proxy::providers::AuthStrategy::GitHubCopilot,
)))
}
/// Copilot 供应商的 base_url 需要从 OAuth 管理器动态解析(按账号或默认端点)。
/// `is_full_url` 的供应商已是完整地址,无需解析。
async fn resolve_copilot_base_url_override(
provider: &crate::provider::Provider,
copilot_state: &State<'_, CopilotAuthState>,
@@ -238,54 +165,6 @@ fn is_copilot_provider(provider: &crate::provider::Provider) -> bool {
.unwrap_or(false)
}
async fn resolve_claude_api_format_override(
app_type: &AppType,
provider: &crate::provider::Provider,
config: &StreamCheckConfig,
copilot_state: &State<'_, CopilotAuthState>,
auth_override: Option<&crate::proxy::providers::AuthInfo>,
) -> Result<Option<String>, AppError> {
if *app_type != AppType::Claude {
return Ok(None);
}
let is_copilot = auth_override
.map(|auth| auth.strategy == crate::proxy::providers::AuthStrategy::GitHubCopilot)
.unwrap_or(false);
if !is_copilot {
return Ok(None);
}
let model_id = StreamCheckService::resolve_effective_test_model(app_type, provider, config);
let auth_manager = copilot_state.0.read().await;
let account_id = provider
.meta
.as_ref()
.and_then(|meta| meta.managed_account_id_for("github_copilot"));
let vendor_result = match account_id.as_deref() {
Some(id) => {
auth_manager
.get_model_vendor_for_account(id, &model_id)
.await
}
None => auth_manager.get_model_vendor(&model_id).await,
};
let api_format = match vendor_result {
Ok(Some(vendor)) if vendor.eq_ignore_ascii_case("openai") => "openai_responses",
Ok(Some(_)) | Ok(None) => "openai_chat",
Err(err) => {
log::warn!(
"[StreamCheck] Failed to resolve Copilot model vendor for {model_id}: {err}. Falling back to chat/completions"
);
"openai_chat"
}
};
Ok(Some(api_format.to_string()))
}
#[cfg(test)]
mod tests {
use super::is_copilot_provider;
+57 -13
View File
@@ -14,10 +14,16 @@ pub fn get_usage_summary(
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<String>,
provider_name: Option<String>,
model: Option<String>,
) -> Result<UsageSummary, AppError> {
state
.db
.get_usage_summary(start_date, end_date, app_type.as_deref())
state.db.get_usage_summary(
start_date,
end_date,
app_type.as_deref(),
provider_name.as_deref(),
model.as_deref(),
)
}
/// 获取按 app_type 拆分的使用量汇总
@@ -26,8 +32,15 @@ pub fn get_usage_summary_by_app(
state: State<'_, AppState>,
start_date: Option<i64>,
end_date: Option<i64>,
provider_name: Option<String>,
model: Option<String>,
) -> Result<Vec<UsageSummaryByApp>, AppError> {
state.db.get_usage_summary_by_app(start_date, end_date)
state.db.get_usage_summary_by_app(
start_date,
end_date,
provider_name.as_deref(),
model.as_deref(),
)
}
/// 获取每日趋势
@@ -37,10 +50,16 @@ pub fn get_usage_trends(
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<String>,
provider_name: Option<String>,
model: Option<String>,
) -> Result<Vec<DailyStats>, AppError> {
state
.db
.get_daily_trends(start_date, end_date, app_type.as_deref())
state.db.get_daily_trends(
start_date,
end_date,
app_type.as_deref(),
provider_name.as_deref(),
model.as_deref(),
)
}
/// 获取 Provider 统计
@@ -50,10 +69,16 @@ pub fn get_provider_stats(
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<String>,
provider_name: Option<String>,
model: Option<String>,
) -> Result<Vec<ProviderStats>, AppError> {
state
.db
.get_provider_stats(start_date, end_date, app_type.as_deref())
state.db.get_provider_stats(
start_date,
end_date,
app_type.as_deref(),
provider_name.as_deref(),
model.as_deref(),
)
}
/// 获取模型统计
@@ -63,10 +88,16 @@ pub fn get_model_stats(
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<String>,
provider_name: Option<String>,
model: Option<String>,
) -> Result<Vec<ModelStats>, AppError> {
state
.db
.get_model_stats(start_date, end_date, app_type.as_deref())
state.db.get_model_stats(
start_date,
end_date,
app_type.as_deref(),
provider_name.as_deref(),
model.as_deref(),
)
}
/// 获取请求日志列表
@@ -276,6 +307,19 @@ pub fn sync_session_usage(
}
}
// 同步 OpenCode 使用数据
match crate::services::session_usage_opencode::sync_opencode_usage(&state.db) {
Ok(opencode_result) => {
result.imported += opencode_result.imported;
result.skipped += opencode_result.skipped;
result.files_scanned += opencode_result.files_scanned;
result.errors.extend(opencode_result.errors);
}
Err(e) => {
result.errors.push(format!("OpenCode 同步失败: {e}"));
}
}
Ok(result)
}
+157 -4
View File
@@ -75,6 +75,15 @@ impl Database {
return Ok(0);
}
// 剪枝是不可逆的:明细一旦汇总删除,0 成本行就永远失去按 pricing_model
// 补价重算的机会(启动序列里 seed 定价先于 rollup、但启动回填在 rollup
// 之后;周期任务同理)。所以剪枝前先尽力回填一次。失败仅告警不阻断——
// 否则一行损坏的定价数据会永久卡死日志清理。
// 注意必须在 SAVEPOINT 之外调用:回填内部自己开顶层事务。
if let Err(e) = Self::backfill_missing_usage_costs_on_conn(&conn, None) {
log::warn!("Pre-prune cost backfill failed, pruning anyway: {e}");
}
// Use a savepoint for atomicity
conn.execute("SAVEPOINT rollup_prune;", [])
.map_err(|e| AppError::Database(e.to_string()))?;
@@ -106,15 +115,18 @@ impl Database {
fn do_rollup_and_prune(conn: &rusqlite::Connection, cutoff: i64) -> Result<u64, AppError> {
// Aggregate old logs, merging with any pre-existing rollup rows via LEFT JOIN.
let effective_filter = effective_usage_log_filter("l");
// request_model 维度保留路由接管的「客户端别名 → 真实模型」映射,
// pricing_model 维度保留写入时的计价基准(request 计价模式下与 model 分叉);
// 明细行的这两列可能为 NULL(历史/手工数据),归一为 ''。
let aggregation_sql = format!(
"INSERT OR REPLACE INTO usage_daily_rollups
(date, app_type, provider_id, model,
(date, app_type, provider_id, model, request_model, pricing_model,
request_count, success_count,
input_tokens, output_tokens,
cache_read_tokens, cache_creation_tokens,
total_cost_usd, avg_latency_ms)
SELECT
d, a, p, m,
d, a, p, m, rm, pm,
COALESCE(old.request_count, 0) + new_req,
COALESCE(old.success_count, 0) + new_succ,
COALESCE(old.input_tokens, 0) + new_in,
@@ -131,6 +143,8 @@ impl Database {
SELECT
date(l.created_at, 'unixepoch', 'localtime') as d,
l.app_type as a, l.provider_id as p, l.model as m,
COALESCE(l.request_model, '') as rm,
COALESCE(l.pricing_model, '') as pm,
COUNT(*) as new_req,
SUM(CASE WHEN l.status_code >= 200 AND l.status_code < 300 THEN 1 ELSE 0 END) as new_succ,
COALESCE(SUM(l.input_tokens), 0) as new_in,
@@ -141,11 +155,12 @@ impl Database {
COALESCE(AVG(l.latency_ms), 0) as new_lat
FROM proxy_request_logs l
WHERE l.created_at < ?1 AND {effective_filter}
GROUP BY d, a, p, m
GROUP BY d, a, p, m, rm, pm
) agg
LEFT JOIN usage_daily_rollups old
ON old.date = agg.d AND old.app_type = agg.a
AND old.provider_id = agg.p AND old.model = agg.m"
AND old.provider_id = agg.p AND old.model = agg.m
AND old.request_model = agg.rm AND old.pricing_model = agg.pm"
);
conn.execute(&aggregation_sql, [cutoff])
@@ -325,6 +340,144 @@ mod tests {
Ok(())
}
#[test]
fn test_rollup_preserves_request_model_dimension() -> Result<(), AppError> {
let db = Database::memory()?;
let now = chrono::Utc::now().timestamp();
let old_ts = now - 40 * 86400;
{
let conn = crate::database::lock_conn!(db.conn);
// 路由接管行:model 是真实上游模型,request_model 是客户端别名。
// 同 model 下两个不同别名必须各自成行,prune 后映射关系仍可审计。
for (i, request_model) in [
("a", "claude-sonnet-4-6"),
("b", "claude-sonnet-4-6"),
("c", "claude-haiku-4-5"),
] {
conn.execute(
"INSERT INTO proxy_request_logs (
request_id, provider_id, app_type, model, request_model,
input_tokens, output_tokens, total_cost_usd,
latency_ms, status_code, created_at
) VALUES (?1, 'p1', 'claude', 'kimi-k2', ?2, 100, 50, '0.01', 100, 200, ?3)",
rusqlite::params![format!("takeover-{i}"), request_model, old_ts],
)?;
}
}
let deleted = db.rollup_and_prune(30)?;
assert_eq!(deleted, 3);
let conn = crate::database::lock_conn!(db.conn);
let mut stmt = conn.prepare(
"SELECT request_model, request_count FROM usage_daily_rollups
WHERE model = 'kimi-k2' ORDER BY request_model",
)?;
let rows = stmt
.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
})?
.collect::<Result<Vec<_>, _>>()?;
assert_eq!(
rows,
vec![
("claude-haiku-4-5".to_string(), 1),
("claude-sonnet-4-6".to_string(), 2),
]
);
Ok(())
}
#[test]
fn test_rollup_preserves_pricing_model_dimension() -> Result<(), AppError> {
let db = Database::memory()?;
let now = chrono::Utc::now().timestamp();
let old_ts = now - 40 * 86400;
{
let conn = crate::database::lock_conn!(db.conn);
// request 计价模式下 pricing_model 与 model 分叉,必须各自成行
conn.execute(
"INSERT INTO proxy_request_logs (
request_id, provider_id, app_type, model, request_model, pricing_model,
input_tokens, output_tokens, total_cost_usd,
latency_ms, status_code, created_at
) VALUES ('pm-a', 'p1', 'claude', 'kimi-k2', 'claude-sonnet-4-6', 'kimi-k2',
100, 50, '0.01', 100, 200, ?1)",
rusqlite::params![old_ts],
)?;
conn.execute(
"INSERT INTO proxy_request_logs (
request_id, provider_id, app_type, model, request_model, pricing_model,
input_tokens, output_tokens, total_cost_usd,
latency_ms, status_code, created_at
) VALUES ('pm-b', 'p1', 'claude', 'kimi-k2', 'claude-sonnet-4-6', 'claude-sonnet-4-6',
100, 50, '0.30', 100, 200, ?1)",
rusqlite::params![old_ts],
)?;
}
let deleted = db.rollup_and_prune(30)?;
assert_eq!(deleted, 2);
let conn = crate::database::lock_conn!(db.conn);
let mut stmt = conn.prepare(
"SELECT pricing_model, total_cost_usd FROM usage_daily_rollups
WHERE model = 'kimi-k2' ORDER BY pricing_model",
)?;
let rows = stmt
.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?
.collect::<Result<Vec<_>, _>>()?;
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].0, "claude-sonnet-4-6");
assert_eq!(rows[1].0, "kimi-k2");
Ok(())
}
#[test]
fn test_rollup_backfills_costs_before_pruning() -> Result<(), AppError> {
let db = Database::memory()?;
let now = chrono::Utc::now().timestamp();
let old_ts = now - 40 * 86400;
{
let conn = crate::database::lock_conn!(db.conn);
// >30 天的 0 成本行:pricing_modelgpt-5.5)在 seed 定价表中有价。
// 剪枝是不可逆的,rollup 必须先回填再汇总,否则按 0 永久入账。
conn.execute(
"INSERT INTO proxy_request_logs (
request_id, provider_id, app_type, model, request_model, pricing_model,
input_tokens, output_tokens, total_cost_usd,
latency_ms, status_code, created_at
) VALUES ('prune-backfill', 'p1', 'codex', 'gpt-5.5', 'gpt-5.5', 'gpt-5.5',
1000000, 0, '0', 100, 200, ?1)",
rusqlite::params![old_ts],
)?;
}
let deleted = db.rollup_and_prune(30)?;
assert_eq!(deleted, 1);
let conn = crate::database::lock_conn!(db.conn);
let total_cost: f64 = conn.query_row(
"SELECT CAST(total_cost_usd AS REAL) FROM usage_daily_rollups
WHERE model = 'gpt-5.5'",
[],
|row| row.get(0),
)?;
// gpt-5.5 input $5/M × 1M tokens,回填后再汇总
assert!(
(total_cost - 5.0).abs() < 1e-6,
"expected backfilled cost 5.0, got {total_cost}"
);
Ok(())
}
#[test]
fn test_rollup_noop_when_no_old_data() -> Result<(), AppError> {
let db = Database::memory()?;
+2 -1
View File
@@ -49,7 +49,7 @@ use std::sync::Mutex;
/// 当前 Schema 版本号
/// 每次修改表结构时递增,并在 schema.rs 中添加相应的迁移逻辑
pub(crate) const SCHEMA_VERSION: i32 = 10;
pub(crate) const SCHEMA_VERSION: i32 = 11;
/// 安全地序列化 JSON,避免 unwrap panic
pub(crate) fn to_json_string<T: Serialize>(value: &T) -> Result<String, AppError> {
@@ -82,6 +82,7 @@ fn register_db_change_hook(conn: &Connection) {
|action: Action, _database: &str, table: &str, _row_id: i64| match action {
Action::SQLITE_INSERT | Action::SQLITE_UPDATE | Action::SQLITE_DELETE => {
crate::services::webdav_auto_sync::notify_db_changed(table);
crate::services::s3_auto_sync::notify_db_changed(table);
}
_ => {}
},
+396 -24
View File
@@ -181,9 +181,12 @@ impl Database {
)", []).map_err(|e| AppError::Database(e.to_string()))?;
// 10. Proxy Request Logs 表
// pricing_model = 写入时实际用于计价的模型名(pricing_model_source 解析结果),
// 回填按它重算;NULL 表示 v11 之前的历史行,'' 表示未计价的错误行。
conn.execute("CREATE TABLE IF NOT EXISTS proxy_request_logs (
request_id TEXT PRIMARY KEY, provider_id TEXT NOT NULL, app_type TEXT NOT NULL, model TEXT NOT NULL,
request_model TEXT,
pricing_model TEXT,
input_tokens INTEGER NOT NULL DEFAULT 0, output_tokens INTEGER NOT NULL DEFAULT 0,
cache_read_tokens INTEGER NOT NULL DEFAULT 0, cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
input_cost_usd TEXT NOT NULL DEFAULT '0', output_cost_usd TEXT NOT NULL DEFAULT '0',
@@ -255,12 +258,17 @@ impl Database {
.map_err(|e| AppError::Database(e.to_string()))?;
// 17. Usage Daily Rollups 表 (日聚合统计)
// request_model 保留路由接管的「客户端别名 → 真实模型」映射维度,
// pricing_model 保留写入时的计价基准(request 计价模式下与 model 分叉),
// 否则明细被 prune 后接管计费不可审计;历史行迁移时填 ''(未知)。
conn.execute(
"CREATE TABLE IF NOT EXISTS usage_daily_rollups (
date TEXT NOT NULL,
app_type TEXT NOT NULL,
provider_id TEXT NOT NULL,
model TEXT NOT NULL,
request_model TEXT NOT NULL DEFAULT '',
pricing_model TEXT NOT NULL DEFAULT '',
request_count INTEGER NOT NULL DEFAULT 0,
success_count INTEGER NOT NULL DEFAULT 0,
input_tokens INTEGER NOT NULL DEFAULT 0,
@@ -269,7 +277,7 @@ impl Database {
cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
total_cost_usd TEXT NOT NULL DEFAULT '0',
avg_latency_ms INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (date, app_type, provider_id, model)
PRIMARY KEY (date, app_type, provider_id, model, request_model, pricing_model)
)",
[],
)
@@ -431,6 +439,11 @@ impl Database {
Self::migrate_v9_to_v10(conn)?;
Self::set_user_version(conn, 10)?;
}
10 => {
log::info!("迁移数据库从 v10 到 v11usage_daily_rollups 保留 request_model 维度)");
Self::migrate_v10_to_v11(conn)?;
Self::set_user_version(conn, 11)?;
}
_ => {
return Err(AppError::Database(format!(
"未知的数据库版本 {version},无法迁移到 {SCHEMA_VERSION}"
@@ -1200,11 +1213,85 @@ impl Database {
Ok(())
}
/// v10 -> v11usage_daily_rollups 增加 request_model 维度(进入主键),
/// proxy_request_logs 增加 pricing_model 列(写入时的计价基准,回填依据)。
///
/// 路由接管下 model(真实上游模型)≠ request_model(客户端别名),
/// 旧 rollup 只按 model 聚合,明细 prune 后映射关系永久丢失、计费不可审计。
/// SQLite 改主键必须重建表;历史行的 request_model 已不可知,填 ''。
fn migrate_v10_to_v11(conn: &Connection) -> Result<(), AppError> {
// proxy_request_logs.pricing_modelNULL = v11 前的历史行(回填走
// model → 占位符回退 request_model 的旧逻辑),'' = 未计价的错误行
if Self::table_exists(conn, "proxy_request_logs")? {
Self::add_column_if_missing(conn, "proxy_request_logs", "pricing_model", "TEXT")?;
}
if !Self::table_exists(conn, "usage_daily_rollups")? {
log::info!("v10 -> v11usage_daily_rollups 不存在,跳过重建");
return Ok(());
}
conn.execute_batch(
"ALTER TABLE usage_daily_rollups RENAME TO usage_daily_rollups_v10;
CREATE TABLE usage_daily_rollups (
date TEXT NOT NULL,
app_type TEXT NOT NULL,
provider_id TEXT NOT NULL,
model TEXT NOT NULL,
request_model TEXT NOT NULL DEFAULT '',
pricing_model TEXT NOT NULL DEFAULT '',
request_count INTEGER NOT NULL DEFAULT 0,
success_count INTEGER NOT NULL DEFAULT 0,
input_tokens INTEGER NOT NULL DEFAULT 0,
output_tokens INTEGER NOT NULL DEFAULT 0,
cache_read_tokens INTEGER NOT NULL DEFAULT 0,
cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
total_cost_usd TEXT NOT NULL DEFAULT '0',
avg_latency_ms INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (date, app_type, provider_id, model, request_model, pricing_model)
);
INSERT INTO usage_daily_rollups
(date, app_type, provider_id, model, request_model, pricing_model,
request_count, success_count, input_tokens, output_tokens,
cache_read_tokens, cache_creation_tokens, total_cost_usd, avg_latency_ms)
SELECT date, app_type, provider_id, model, '', '',
request_count, success_count, input_tokens, output_tokens,
cache_read_tokens, cache_creation_tokens, total_cost_usd, avg_latency_ms
FROM usage_daily_rollups_v10;
DROP TABLE usage_daily_rollups_v10;",
)
.map_err(|e| {
AppError::Database(format!("v10 -> v11 重建 usage_daily_rollups 失败: {e}"))
})?;
log::info!(
"v10 -> v11 迁移完成:usage_daily_rollups 已保留 request_model/pricing_model 维度"
);
Ok(())
}
/// 插入默认模型定价数据
/// 格式: (model_id, display_name, input, output, cache_read, cache_creation)
/// 注意: model_id 使用短横线格式(如 claude-haiku-4-5),与 API 返回的模型名称标准化后一致
fn seed_model_pricing(conn: &Connection) -> Result<(), AppError> {
let pricing_data = [
// Claude Fable 5Opus 之上的新档)
(
"claude-fable-5",
"Claude Fable 5",
"10",
"50",
"1.00",
"12.50",
),
(
"claude-mythos-5",
"Claude Mythos 5",
"10",
"50",
"1.00",
"12.50",
),
// Claude 4.8 系列
(
"claude-opus-4-8",
@@ -1571,6 +1658,14 @@ impl Database {
"0",
),
// StepFun 系列
(
"step-3.7-flash",
"Step 3.7 Flash",
"0.19",
"1.13",
"0.04",
"0",
),
(
"step-3.5-flash",
"Step 3.5 Flash",
@@ -1602,7 +1697,7 @@ impl Database {
"Doubao Seed 2.0 Pro",
"0.47",
"2.37",
"0",
"0.09",
"0",
),
(
@@ -1610,7 +1705,7 @@ impl Database {
"Doubao Seed 2.0 Code",
"0.47",
"2.37",
"0",
"0.09",
"0",
),
(
@@ -1618,15 +1713,15 @@ impl Database {
"Doubao Seed 2.0 Code Preview",
"0.47",
"2.37",
"0",
"0.09",
"0",
),
(
"doubao-seed-2-0-lite",
"Doubao Seed 2.0 Lite",
"0.25",
"2",
"0",
"0.08",
"0.50",
"0.017",
"0",
),
(
@@ -1634,7 +1729,7 @@ impl Database {
"Doubao Seed 2.0 Mini",
"0.03",
"0.31",
"0",
"0.0056",
"0",
),
// DeepSeek 系列
@@ -1706,8 +1801,16 @@ impl Database {
"0.14",
"0",
),
("kimi-k2.5", "Kimi K2.5", "0.60", "2.50", "0.10", "0"),
("kimi-k2.5", "Kimi K2.5", "0.60", "3.00", "0.10", "0"),
("kimi-k2.6", "Kimi K2.6", "0.95", "4.00", "0.16", "0"),
(
"kimi-k2.7-code",
"Kimi K2.7 Code",
"0.95",
"4.00",
"0.19",
"0",
),
// MiniMax 系列
("minimax-m2.1", "MiniMax M2.1", "0.27", "0.95", "0.03", "0"),
(
@@ -1719,7 +1822,7 @@ impl Database {
"0",
),
("minimax-m2", "MiniMax M2", "0.27", "0.95", "0.03", "0"),
("minimax-m2.5", "MiniMax M2.5", "0.12", "0.95", "0.03", "0"),
("minimax-m2.5", "MiniMax M2.5", "0.15", "0.95", "0.03", "0"),
(
"minimax-m2.5-lightning",
"MiniMax M2.5 Lightning",
@@ -1744,9 +1847,10 @@ impl Database {
"0.06",
"0.375",
),
("minimax-m3", "MiniMax M3", "0.60", "2.40", "0.12", "0"),
// GLM (智谱)
("glm-4.7", "GLM-4.7", "0.39", "1.75", "0.04", "0"),
("glm-4.6", "GLM-4.6", "0.28", "1.11", "0.03", "0"),
("glm-4.7", "GLM-4.7", "0.6", "2.2", "0.11", "0"),
("glm-4.6", "GLM-4.6", "0.6", "2.2", "0.11", "0"),
("glm-5", "GLM-5", "1", "3.2", "0.2", "0"),
("glm-5.1", "GLM-5.1", "1.4", "4.4", "0.26", "0"),
// MiMo (小米)
@@ -1758,12 +1862,28 @@ impl Database {
"0.009",
"0",
),
("mimo-v2-pro", "MiMo V2 Pro", "1", "3", "0", "0"),
("mimo-v2.5", "MiMo V2.5", "0.09", "0.29", "0.009", "0"),
("mimo-v2.5-pro", "MiMo V2.5 Pro", "1", "3", "0", "0"),
("mimo-v2-pro", "MiMo V2 Pro", "0.435", "0.87", "0.0036", "0"),
("mimo-v2.5", "MiMo V2.5", "0.14", "0.29", "0.0028", "0"),
(
"mimo-v2.5-pro",
"MiMo V2.5 Pro",
"0.435",
"0.87",
"0.0036",
"0",
),
// Qwen 系列 (阿里巴巴)
("qwen3.6-plus", "Qwen3.6 Plus", "0.325", "1.95", "0", "0"),
("qwen3.5-plus", "Qwen3.5 Plus", "0.26", "1.56", "0", "0"),
("qwen3.7-max", "Qwen3.7 Max", "2.50", "7.50", "0.25", "0"),
("qwen3.7-plus", "Qwen3.7 Plus", "0.40", "1.60", "0.08", "0"),
(
"qwen3.6-plus",
"Qwen3.6 Plus",
"0.325",
"1.95",
"0.065",
"0",
),
("qwen3.5-plus", "Qwen3.5 Plus", "0.26", "1.56", "0.052", "0"),
("qwen3-max", "Qwen3 Max", "0.78", "3.90", "0", "0"),
(
"qwen3-235b-a22b",
@@ -1778,7 +1898,7 @@ impl Database {
"Qwen3 Coder Plus",
"0.65",
"3.25",
"0",
"0.13",
"0",
),
(
@@ -1802,7 +1922,7 @@ impl Database {
"Qwen3 Coder Flash",
"0.195",
"0.975",
"0",
"0.039",
"0",
),
(
@@ -1817,19 +1937,20 @@ impl Database {
("qwq-32b", "QwQ 32B", "0.20", "0.60", "0", "0"),
("qwen3-32b", "Qwen3 32B", "0.16", "0.64", "0", "0"),
// Grok 系列 (xAI)
("grok-4.3", "Grok 4.3", "1.25", "2.50", "0.20", "0"),
(
"grok-4.20-0309-reasoning",
"Grok 4.20 Reasoning",
"2",
"6",
"1.25",
"2.50",
"0.20",
"0",
),
(
"grok-4.20-0309-non-reasoning",
"Grok 4.20",
"2",
"6",
"1.25",
"2.50",
"0.20",
"0",
),
@@ -1862,6 +1983,38 @@ impl Database {
("grok-3", "Grok 3", "3", "15", "0.75", "0"),
("grok-3-mini", "Grok 3 Mini", "0.25", "0.50", "0.075", "0"),
// Mistral 系列
(
"mistral-medium-3.5",
"Mistral Medium 3.5",
"1.50",
"7.50",
"0",
"0",
),
(
"mistral-small-4",
"Mistral Small 4",
"0.10",
"0.30",
"0.01",
"0",
),
(
"devstral-small-2-2512",
"Devstral Small 2",
"0.10",
"0.30",
"0.01",
"0",
),
(
"magistral-small",
"Magistral Small",
"0.50",
"1.50",
"0",
"0",
),
("codestral-2508", "Codestral", "0.30", "0.90", "0.03", "0"),
(
"devstral-small-1.1",
@@ -1871,7 +2024,7 @@ impl Database {
"0.01",
"0",
),
("devstral-2-2512", "Devstral 2", "0.40", "0.90", "0.04", "0"),
("devstral-2-2512", "Devstral 2", "0.40", "2", "0.04", "0"),
(
"devstral-medium",
"Devstral Medium",
@@ -1952,6 +2105,225 @@ impl Database {
fn repair_current_model_pricing(conn: &Connection) -> Result<(), AppError> {
let pricing_fixes = [
// 2026-06-10 全量核价(厂商官方 list 价;CNY 按 ~7.14 折算)
// GLM 4.6/4.7:旧值是中转/OpenRouter 折扣价,统一到 Z.ai 官方(与 glm-5/5.1 一致)
(
"glm-4.7", "GLM-4.7", "0.6", "2.2", "0.11", "0", "0.39", "1.75", "0.04", "0",
),
(
"glm-4.6", "GLM-4.6", "0.6", "2.2", "0.11", "0", "0.28", "1.11", "0.03", "0",
),
// Grok 4.20xAI 已降价 2/6 → 1.25/2.50
(
"grok-4.20-0309-reasoning",
"Grok 4.20 Reasoning",
"1.25",
"2.50",
"0.20",
"0",
"2",
"6",
"0.20",
"0",
),
(
"grok-4.20-0309-non-reasoning",
"Grok 4.20",
"1.25",
"2.50",
"0.20",
"0",
"2",
"6",
"0.20",
"0",
),
// Kimi K2.5 官方 output 3.00
(
"kimi-k2.5",
"Kimi K2.5",
"0.60",
"3.00",
"0.10",
"0",
"0.60",
"2.50",
"0.10",
"0",
),
// MiniMax M2.5 input 0.15
(
"minimax-m2.5",
"MiniMax M2.5",
"0.15",
"0.95",
"0.03",
"0",
"0.12",
"0.95",
"0.03",
"0",
),
// Mistral Devstral 2 output 0.90 → 2(与同表 devstral-medium 一致)
(
"devstral-2-2512",
"Devstral 2",
"0.40",
"2",
"0.04",
"0",
"0.40",
"0.90",
"0.04",
"0",
),
// Doubao Seed 2.0lite 旧价贵 3-4 倍 + 全系补 cache 命中价
(
"doubao-seed-2-0-lite",
"Doubao Seed 2.0 Lite",
"0.08",
"0.50",
"0.017",
"0",
"0.25",
"2",
"0",
"0",
),
(
"doubao-seed-2-0-pro",
"Doubao Seed 2.0 Pro",
"0.47",
"2.37",
"0.09",
"0",
"0.47",
"2.37",
"0",
"0",
),
(
"doubao-seed-2-0-code",
"Doubao Seed 2.0 Code",
"0.47",
"2.37",
"0.09",
"0",
"0.47",
"2.37",
"0",
"0",
),
(
"doubao-seed-2-0-code-preview-latest",
"Doubao Seed 2.0 Code Preview",
"0.47",
"2.37",
"0.09",
"0",
"0.47",
"2.37",
"0",
"0",
),
(
"doubao-seed-2-0-mini",
"Doubao Seed 2.0 Mini",
"0.03",
"0.31",
"0.0056",
"0",
"0.03",
"0.31",
"0",
"0",
),
// MiMo:5/27 永久降价,旧值是旧价
(
"mimo-v2-pro",
"MiMo V2 Pro",
"0.435",
"0.87",
"0.0036",
"0",
"1",
"3",
"0",
"0",
),
(
"mimo-v2.5",
"MiMo V2.5",
"0.14",
"0.29",
"0.0028",
"0",
"0.09",
"0.29",
"0.009",
"0",
),
(
"mimo-v2.5-pro",
"MiMo V2.5 Pro",
"0.435",
"0.87",
"0.0036",
"0",
"1",
"3",
"0",
"0",
),
// Qwen:官方"隐式缓存 = 输入 20%"补 cache 命中价
(
"qwen3.6-plus",
"Qwen3.6 Plus",
"0.325",
"1.95",
"0.065",
"0",
"0.325",
"1.95",
"0",
"0",
),
(
"qwen3.5-plus",
"Qwen3.5 Plus",
"0.26",
"1.56",
"0.052",
"0",
"0.26",
"1.56",
"0",
"0",
),
(
"qwen3-coder-plus",
"Qwen3 Coder Plus",
"0.65",
"3.25",
"0.13",
"0",
"0.65",
"3.25",
"0",
"0",
),
(
"qwen3-coder-flash",
"Qwen3 Coder Flash",
"0.195",
"0.975",
"0.039",
"0",
"0.195",
"0.975",
"0",
"0",
),
(
"deepseek-v4-flash",
"DeepSeek V4 Flash",
+81
View File
@@ -345,6 +345,87 @@ fn schema_migration_v4_adds_pricing_model_columns() {
);
}
#[test]
fn migration_v10_to_v11_rebuilds_rollups_with_request_model_dimension() {
let conn = Connection::open_in_memory().expect("open memory db");
// 模拟 v10 形状的 rollup 表(主键不含 request_model)+ 一行历史聚合数据,
// 以及 v10 形状的明细表(无 pricing_model 列)
conn.execute_batch(
r#"
CREATE TABLE proxy_request_logs (
request_id TEXT PRIMARY KEY,
model TEXT NOT NULL,
request_model TEXT
);
CREATE TABLE usage_daily_rollups (
date TEXT NOT NULL,
app_type TEXT NOT NULL,
provider_id TEXT NOT NULL,
model TEXT NOT NULL,
request_count INTEGER NOT NULL DEFAULT 0,
success_count INTEGER NOT NULL DEFAULT 0,
input_tokens INTEGER NOT NULL DEFAULT 0,
output_tokens INTEGER NOT NULL DEFAULT 0,
cache_read_tokens INTEGER NOT NULL DEFAULT 0,
cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
total_cost_usd TEXT NOT NULL DEFAULT '0',
avg_latency_ms INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (date, app_type, provider_id, model)
);
INSERT INTO usage_daily_rollups
(date, app_type, provider_id, model, request_count, success_count,
input_tokens, output_tokens, total_cost_usd, avg_latency_ms)
VALUES ('2026-05-01', 'claude', 'p1', 'kimi-k2', 7, 7, 1000, 500, '0.07', 120);
"#,
)
.expect("seed v10 rollup table");
Database::set_user_version(&conn, 10).expect("set user_version=10");
Database::apply_schema_migrations_on_conn(&conn).expect("apply migrations");
// 新列存在且 NOT NULL DEFAULT ''
let request_model = get_column_info(&conn, "usage_daily_rollups", "request_model");
assert_eq!(request_model.r#type, "TEXT");
assert_eq!(request_model.notnull, 1);
let rollup_pricing_model = get_column_info(&conn, "usage_daily_rollups", "pricing_model");
assert_eq!(rollup_pricing_model.r#type, "TEXT");
assert_eq!(rollup_pricing_model.notnull, 1);
// 明细表补上 pricing_model 列(可空,历史行 NULL
let pricing_model = get_column_info(&conn, "proxy_request_logs", "pricing_model");
assert_eq!(pricing_model.r#type, "TEXT");
assert_eq!(pricing_model.notnull, 0);
// 历史行保留,request_model 填 ''(未知)
let (rm, count, input, cost): (String, i64, i64, String) = conn
.query_row(
"SELECT request_model, request_count, input_tokens, total_cost_usd
FROM usage_daily_rollups WHERE model = 'kimi-k2'",
[],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
)
.expect("migrated row");
assert_eq!(rm, "");
assert_eq!(count, 7);
assert_eq!(input, 1000);
assert_eq!(cost, "0.07");
// 主键包含 request_model:同 model 不同别名可共存
conn.execute(
"INSERT INTO usage_daily_rollups
(date, app_type, provider_id, model, request_model, request_count)
VALUES ('2026-05-01', 'claude', 'p1', 'kimi-k2', 'claude-sonnet-4-6', 1)",
[],
)
.expect("insert row with same model but different request_model");
assert_eq!(
Database::get_user_version(&conn).expect("version after migration"),
SCHEMA_VERSION
);
}
#[test]
fn schema_create_tables_repairs_legacy_proxy_config_singleton_to_per_app() {
let conn = Connection::open_in_memory().expect("open memory db");
+49 -1
View File
@@ -9,7 +9,51 @@ use super::DeepLinkImportRequest;
use crate::AppType;
use crate::{store::AppState, Database};
use base64::prelude::*;
use std::sync::Arc;
use std::{env, ffi::OsString, sync::Arc};
struct TestHomeGuard {
_dir: tempfile::TempDir,
original_home: Option<OsString>,
original_userprofile: Option<OsString>,
original_test_home: Option<OsString>,
}
impl TestHomeGuard {
fn new() -> Self {
let dir = tempfile::tempdir().expect("create isolated test home");
let original_home = env::var_os("HOME");
let original_userprofile = env::var_os("USERPROFILE");
let original_test_home = env::var_os("CC_SWITCH_TEST_HOME");
env::set_var("HOME", dir.path());
env::set_var("USERPROFILE", dir.path());
env::set_var("CC_SWITCH_TEST_HOME", dir.path());
Self {
_dir: dir,
original_home,
original_userprofile,
original_test_home,
}
}
}
impl Drop for TestHomeGuard {
fn drop(&mut self) {
match &self.original_test_home {
Some(value) => env::set_var("CC_SWITCH_TEST_HOME", value),
None => env::remove_var("CC_SWITCH_TEST_HOME"),
}
match &self.original_userprofile {
Some(value) => env::set_var("USERPROFILE", value),
None => env::remove_var("USERPROFILE"),
}
match &self.original_home {
Some(value) => env::set_var("HOME", value),
None => env::remove_var("HOME"),
}
}
}
// =============================================================================
// Parser Tests
@@ -477,8 +521,12 @@ fn test_build_claude_provider_without_config_unchanged() {
// Prompt Tests
// =============================================================================
// Integration-style unit test: prompt import reaches PromptService and resolves
// live config file paths, so HOME must be isolated before it runs.
#[test]
#[serial_test::serial]
fn test_import_prompt_allows_space_in_base64_content() {
let _test_home = TestHomeGuard::new();
let url = "ccswitch://v1/import?resource=prompt&app=codex&name=PromptPlus&content=Pj4+";
let request = parse_deeplink_url(url).unwrap();
+253 -4
View File
@@ -116,10 +116,76 @@ pub fn read_hermes_config() -> Result<serde_yaml::Value, AppError> {
return Ok(serde_yaml::Value::Mapping(serde_yaml::Mapping::new()));
}
serde_yaml::from_str(&content)
// Heal duplicate top-level keys left behind by the pre-CRLF-fix append
// bug (#3633); serde_yaml rejects them outright, which bricked the panel.
let deduped = deduplicate_top_level_keys(&content);
serde_yaml::from_str(&deduped)
.map_err(|e| AppError::Config(format!("Failed to parse Hermes config as YAML: {e}")))
}
/// Remove duplicate top-level YAML sections, keeping the LAST occurrence of
/// each key.
///
/// Keep-last is deliberate, not arbitrary: the duplicates come from section
/// replacement degrading into appends (#3633), so the last block is the
/// newest data — and Hermes itself reads the file with PyYAML, whose
/// duplicate-key semantics are last-wins. Keeping the first occurrence would
/// silently roll the user back to stale config and diverge from what Hermes
/// actually runs with.
fn deduplicate_top_level_keys(raw: &str) -> String {
use std::collections::HashMap;
// Pass 1: locate every top-level key line as (key, byte offset).
let mut sections: Vec<(&str, usize)> = Vec::new();
let mut offset = 0;
for line in raw.split('\n') {
if is_top_level_key_line(line) {
if let Some(colon_pos) = line.find(':') {
sections.push((&line[..colon_pos], offset));
}
}
offset += line.len() + 1;
}
let mut remaining: HashMap<&str, usize> = HashMap::new();
for (key, _) in &sections {
*remaining.entry(key).or_insert(0) += 1;
}
if remaining.values().all(|&count| count <= 1) {
return raw.to_string();
}
// Pass 2: re-emit, dropping every section that has a later occurrence of
// the same key. A section spans from its key line to the next top-level
// key line (or EOF), matching find_yaml_section_range. Content before the
// first section (comments, document markers) is always kept.
let mut result = String::with_capacity(raw.len());
let head_end = sections
.first()
.map(|&(_, start)| start)
.unwrap_or(raw.len());
result.push_str(&raw[..head_end]);
for (i, &(key, start)) in sections.iter().enumerate() {
let end = sections
.get(i + 1)
.map(|&(_, next_start)| next_start)
.unwrap_or(raw.len());
let count = remaining.get_mut(key).expect("key collected in pass 1");
*count -= 1;
if *count > 0 {
log::warn!(
"Hermes config: dropped duplicate top-level section '{key}' (keeping the last occurrence)"
);
continue;
}
result.push_str(&raw[start..end]);
}
result
}
// ============================================================================
// YAML Section-Level Replacement
// ============================================================================
@@ -132,6 +198,11 @@ pub fn read_hermes_config() -> Result<serde_yaml::Value, AppError> {
/// - Not be a comment (starting with `#`)
/// - Not be a sequence item (starting with `-`)
/// - Contain `:` followed by space, tab, newline, or end-of-line
///
/// Lines may carry a trailing `\r` (CRLF files split on `\n`) or `\n`
/// (callers using `split_inclusive`); both count as end-of-line after the
/// colon. Rejecting `\r` here used to make every section lookup miss on
/// CRLF configs, turning section replacement into endless appends (#3633).
fn is_top_level_key_line(line: &str) -> bool {
if line.is_empty() {
return false;
@@ -142,7 +213,7 @@ fn is_top_level_key_line(line: &str) -> bool {
}
if let Some(colon_pos) = line.find(':') {
let after_colon = &line[colon_pos + 1..];
after_colon.is_empty() || after_colon.starts_with(' ') || after_colon.starts_with('\t')
after_colon.is_empty() || after_colon.starts_with([' ', '\t', '\r', '\n'])
} else {
false
}
@@ -196,6 +267,21 @@ fn serialize_yaml_section(key: &str, value: &serde_yaml::Value) -> Result<String
Ok(yaml_str)
}
/// Remove every top-level section with the given key from raw YAML text.
/// Used to clean residual duplicates of a key after replacing its first
/// occurrence; safe values come from the keep-last healed read, so dropping
/// all on-disk copies here loses nothing.
fn remove_all_sections(raw: &str, section_key: &str) -> String {
let mut result = String::with_capacity(raw.len());
let mut rest = raw;
while let Some((start, end)) = find_yaml_section_range(rest, section_key) {
result.push_str(&rest[..start]);
rest = &rest[end..];
}
result.push_str(rest);
result
}
/// Replace a YAML section in raw text, or append it if not found.
fn replace_yaml_section(
raw: &str,
@@ -208,12 +294,14 @@ fn replace_yaml_section(
let mut result = String::with_capacity(raw.len());
result.push_str(&raw[..start]);
result.push_str(&serialized);
// Drop duplicate sections of this key from the remainder — configs
// written before the CRLF fix may carry several appended copies.
let remainder = remove_all_sections(&raw[end..], section_key);
// Ensure proper separation between sections
let remainder = &raw[end..];
if !serialized.ends_with('\n') && !remainder.is_empty() && !remainder.starts_with('\n') {
result.push('\n');
}
result.push_str(remainder);
result.push_str(&remainder);
Ok(result)
} else {
// Section not found — append at end
@@ -1204,6 +1292,111 @@ model:
assert!(!section.starts_with("model_extra:"));
}
#[test]
fn find_section_handles_crlf() {
// Regression for #3633: CRLF line endings must not hide sections.
let yaml = "model:\r\n default: gpt-4\r\nagent:\r\n max_turns: 10\r\n";
let (start, end) = find_yaml_section_range(yaml, "model").unwrap();
let section = &yaml[start..end];
assert!(section.starts_with("model:"));
assert!(section.contains("default: gpt-4"));
assert!(!section.contains("agent:"));
}
// ---- deduplicate_top_level_keys tests ----
#[test]
fn dedup_keeps_last_occurrence() {
// Duplicates come from replace-degraded-to-append, so the last block
// is the newest data and must win (PyYAML last-wins, like Hermes).
let yaml = "\
model:
default: gpt-4
agent:
max_turns: 10
model:
default: claude-opus-4-8
";
let result = deduplicate_top_level_keys(yaml);
assert_eq!(
result.lines().filter(|l| *l == "model:").count(),
1,
"duplicate model: section was not removed"
);
assert!(result.contains("claude-opus-4-8"));
assert!(!result.contains("gpt-4"));
assert!(result.contains("max_turns"));
}
#[test]
fn dedup_handles_crlf() {
let yaml = "model:\r\n default: gpt-4\r\nagent:\r\n max_turns: 10\r\nmodel:\r\n default: claude\r\n";
let result = deduplicate_top_level_keys(yaml);
assert_eq!(result.lines().filter(|l| l.trim() == "model:").count(), 1);
assert!(result.contains("default: claude"));
assert!(!result.contains("gpt-4"));
}
#[test]
fn dedup_is_identity_without_duplicates() {
let yaml = "\
# Hermes config
model:
default: gpt-4
agent:
max_turns: 10
";
assert_eq!(deduplicate_top_level_keys(yaml), yaml);
}
#[test]
fn dedup_result_parses_with_last_value() {
// End-to-end: a config that serde_yaml rejects today must parse after
// healing, and expose the newest (last) value.
let yaml = "\
custom_providers:
- name: old-provider
model:
default: gpt-4
custom_providers:
- name: old-provider
- name: new-provider
";
let healed = deduplicate_top_level_keys(yaml);
let value: serde_yaml::Value = serde_yaml::from_str(&healed).unwrap();
let providers = value
.get("custom_providers")
.unwrap()
.as_sequence()
.unwrap();
assert_eq!(providers.len(), 2);
assert_eq!(
providers[1].get("name").unwrap().as_str().unwrap(),
"new-provider"
);
}
// ---- remove_all_sections tests ----
#[test]
fn remove_all_sections_strips_every_occurrence() {
let yaml = "\
model:
default: gpt-4
agent:
max_turns: 10
model:
default: claude
model:
default: gemini
";
let result = remove_all_sections(yaml, "model");
assert!(!result.contains("model:"));
assert!(result.contains("agent:"));
assert!(result.contains("max_turns"));
}
// ---- replace_yaml_section tests ----
#[test]
@@ -1239,6 +1432,62 @@ agent:
assert!(!result.contains("openai"));
}
#[test]
fn replace_section_in_crlf_config_replaces_in_place() {
// Regression for #3633: on CRLF configs every "replace" used to
// degrade into an append, piling up duplicate sections.
let yaml = "model:\r\n default: gpt-4\r\nagent:\r\n max_turns: 10\r\n";
let new_model = serde_yaml::Value::Mapping({
let mut m = serde_yaml::Mapping::new();
m.insert(
serde_yaml::Value::String("default".to_string()),
serde_yaml::Value::String("claude-opus-4-8".to_string()),
);
m
});
let result = replace_yaml_section(yaml, "model", &new_model).unwrap();
assert_eq!(
result.lines().filter(|l| l.trim() == "model:").count(),
1,
"model: must be replaced in place, not appended"
);
assert!(result.contains("claude-opus-4-8"));
assert!(!result.contains("gpt-4"));
assert!(result.contains("max_turns"));
}
#[test]
fn replace_section_removes_residual_duplicates() {
// A config already broken by the append bug: replacing the section
// must also clean the stale duplicate copies after it.
let yaml = "\
model:
default: gpt-4
agent:
max_turns: 10
model:
default: stale-copy
";
let new_model = serde_yaml::Value::Mapping({
let mut m = serde_yaml::Mapping::new();
m.insert(
serde_yaml::Value::String("default".to_string()),
serde_yaml::Value::String("claude-opus-4-8".to_string()),
);
m
});
let result = replace_yaml_section(yaml, "model", &new_model).unwrap();
assert_eq!(result.lines().filter(|l| *l == "model:").count(), 1);
assert!(result.contains("claude-opus-4-8"));
assert!(!result.contains("stale-copy"));
assert!(result.contains("agent:"));
// The healed output must be valid YAML again
let parsed: Result<serde_yaml::Value, _> = serde_yaml::from_str(&result);
assert!(parsed.is_ok());
}
#[test]
fn append_new_section() {
let yaml = "\
+199 -8
View File
@@ -69,6 +69,22 @@ use tauri::RunEvent;
use tauri::{Emitter, Manager};
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
#[cfg(target_os = "windows")]
fn set_windows_app_user_model_id(app: &tauri::AppHandle) {
let app_id = app.config().identifier.clone();
let wide_app_id: Vec<u16> = app_id.encode_utf16().chain(std::iter::once(0)).collect();
let result = unsafe {
windows_sys::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID(wide_app_id.as_ptr())
};
if result < 0 {
log::warn!("设置 Windows AppUserModelID 失败: 0x{result:08X}");
} else {
log::debug!("Windows AppUserModelID 已设置为 {app_id}");
}
}
fn redact_url_for_log(url_str: &str) -> String {
match url::Url::parse(url_str) {
Ok(url) => {
@@ -288,6 +304,8 @@ pub fn run() {
// 预先刷新 Store 覆盖配置,确保后续路径读取正确(日志/数据库等)
app_store::refresh_app_config_dir_override(app.handle());
panic_hook::init_app_config_dir(crate::config::get_app_config_dir());
#[cfg(target_os = "windows")]
set_windows_app_user_model_id(app.handle());
// 注册 Updater 插件(桌面端)
#[cfg(desktop)]
@@ -582,6 +600,25 @@ pub fn run() {
log::warn!("✗ Codex provider template bucket migration failed: {e}");
}
}
// 统一会话开关的官方历史迁移:开关开启但上次未完成(如文件被占用
// 中途失败)时在启动期重试;函数内部自门控,开关关闭时直接跳过。
match crate::codex_history_migration::maybe_migrate_codex_official_history_to_unified_bucket() {
Ok(outcome) => {
if let Some(reason) = outcome.skipped_reason {
log::debug!("○ Codex official history unify migration skipped: {reason}");
} else {
log::info!(
"✓ Codex official history unify migration completed: jsonl_files={}, state_rows={}",
outcome.migrated_jsonl_files,
outcome.migrated_state_rows
);
}
}
Err(e) => {
log::warn!("✗ Codex official history unify migration failed: {e}");
}
}
});
}
@@ -865,6 +902,10 @@ pub fn run() {
app_state.db.clone(),
app.handle().clone(),
);
crate::services::s3_auto_sync::start_worker(
app_state.db.clone(),
app.handle().clone(),
);
// 将同一个实例注入到全局状态,避免重复创建导致的不一致
app.manage(app_state);
@@ -1021,6 +1062,10 @@ pub fn run() {
"Gemini usage initial sync",
crate::services::session_usage_gemini::sync_gemini_usage(db),
);
run_step(
"OpenCode usage initial sync",
crate::services::session_usage_opencode::sync_opencode_usage(db),
);
// 定期同步
let mut interval = tokio::time::interval(std::time::Duration::from_secs(
@@ -1041,6 +1086,10 @@ pub fn run() {
"Gemini usage periodic sync",
crate::services::session_usage_gemini::sync_gemini_usage(db),
);
run_step(
"OpenCode usage periodic sync",
crate::services::session_usage_opencode::sync_opencode_usage(db),
);
}
});
});
@@ -1126,6 +1175,8 @@ pub fn run() {
commands::read_live_provider_settings,
commands::get_settings,
commands::save_settings,
commands::has_codex_unify_history_backup,
commands::restore_codex_unified_history,
commands::get_rectifier_config,
commands::set_rectifier_config,
commands::get_optimizer_config,
@@ -1135,6 +1186,7 @@ pub fn run() {
commands::get_log_config,
commands::set_log_config,
commands::restart_app,
commands::install_update_and_restart,
commands::check_for_updates,
commands::is_portable_mode,
commands::copy_text_to_clipboard,
@@ -1198,6 +1250,11 @@ pub fn run() {
commands::webdav_sync_download,
commands::webdav_sync_save_settings,
commands::webdav_sync_fetch_remote_info,
commands::s3_test_connection,
commands::s3_sync_upload,
commands::s3_sync_download,
commands::s3_sync_save_settings,
commands::s3_sync_fetch_remote_info,
commands::save_file_dialog,
commands::open_file_dialog,
commands::open_zip_file_dialog,
@@ -1408,14 +1465,37 @@ pub fn run() {
app.run(|app_handle, event| {
// 处理退出请求(所有平台)
if let RunEvent::ExitRequested { api, code, .. } = &event {
// code 为 None 表示运行时自动触发(如隐藏窗口的 WebView 被回收导致无存活窗口),
// 此时应仅阻止退出、保持托盘后台运行;
// code 为 Some(_) 表示用户主动调用 app.exit() 退出(如托盘菜单"退出"),
// 此时执行清理后退出。
if code.is_none() {
log::info!("运行时触发退出请求(无存活窗口),阻止退出以保持托盘后台运行");
api.prevent_exit();
return;
match classify_exit_request(*code) {
// code 为 None 表示运行时自动触发(如隐藏窗口的 WebView 被回收导致无存活窗口),
// 此时应仅阻止退出、保持托盘后台运行。
ExitRequestAction::StayInTray => {
log::info!("运行时触发退出请求(无存活窗口),阻止退出以保持托盘后台运行");
api.prevent_exit();
return;
}
// code 为 RESTART_EXIT_CODEapp.restart() / 自更新 relaunch 发起的重启。
// 这条路径上 prevent_exit() 会被 Tauri 忽略,事件循环必定退出,随后由
// Tauri 在 RunEvent::Exit 后用新二进制 re-execmacOS 会按更新后的
// Info.plist 解析可执行名)。
//
// 绝不能复用下面的异步清理任务:该任务在 tokio 线程调 save_window_state
// 持有 window-state 插件锁的同时向主线程查询窗口几何;而主线程此刻正在
// 退出事件循环,并在插件自带的 RunEvent::Exit 钩子里等待同一把锁——双方
// 互等造成进程永久卡死(更新已安装但应用冻结、不再重启,见 #3998)。
//
// 重启路径交还 Tauri 默认流程即可:
// - 窗口状态:插件 Exit 钩子在主线程保存(同线程读取窗口几何,无死锁)
// - 托盘图标:Tauri 内部 cleanup_before_exit 清理,正常走 Drop
// - 代理/Live 配置:无需恢复,重启后新实例立即接管并恢复代理状态
// - 100ms 落盘等待:重启前的 DB 写入均为命令驱动、此刻已完成,
// 与所有 Tauri 应用默认重启路径的行为一致,无需额外等待
ExitRequestAction::DeferToTauriRestart => {
log::info!("收到重启请求 (code={code:?}),交由 Tauri 默认重启流程 re-exec");
return;
}
// 其它 Some(_):用户主动调用 app.exit() 退出(如托盘菜单"退出"),
// 此时执行清理后退出。
ExitRequestAction::CleanupAndExit => {}
}
log::info!("收到用户主动退出请求 (code={code:?}),开始清理...");
@@ -1425,6 +1505,11 @@ pub fn run() {
tauri::async_runtime::spawn(async move {
save_window_state_before_exit(&app_handle);
cleanup_before_exit(&app_handle).await;
// 先于 std::process::exit 显式移除托盘图标。
// 进程直接退出时 Tauri 运行时不走正常 Drop 流程,
// 不会向 Windows Shell 发送 NIM_DELETE,导致已退出的进程
// 注册的图标仍残留在系统托盘(鼠标悬停 Shell 才会重绘发现进程已死)。
remove_tray_icon_before_exit(&app_handle);
log::info!("清理完成,退出应用");
// 短暂等待确保所有 I/O 操作(如数据库写入)刷新到磁盘
@@ -1572,6 +1657,26 @@ pub async fn cleanup_before_exit(app_handle: &tauri::AppHandle) {
}
}
/// 主动从系统托盘移除托盘图标。
///
/// `std::process::exit` 会绕过 Tauri 运行时,触发不了 `TrayIcon::drop()`
/// 也就不会向 Windows Shell 发 `NIM_DELETE`。结果是进程退出后托盘里
/// 仍保留一个死图标的缓存占位(Shell 不会主动重绘,需要鼠标悬停才刷新)。
///
/// 通过 `set_visible(false)` 走 `WM_USER_HIDE_TRAYICON` 消息路径,
/// 触发 tray-icon 内部的 `remove_tray_icon` → `Shell_NotifyIconW(NIM_DELETE)`
/// 在进程结束前干净地把图标摘掉。其它平台 `set_visible(false)` 也是
/// 正常的隐藏/移除语义,作为跨平台兜底也安全。
pub(crate) fn remove_tray_icon_before_exit(app_handle: &tauri::AppHandle) {
if let Some(tray) = app_handle.tray_by_id(tray::TRAY_ID) {
if let Err(e) = tray.set_visible(false) {
log::warn!("退出时移除托盘图标失败: {e}");
} else {
log::info!("已显式从系统托盘移除图标");
}
}
}
// ============================================================
// 启动时恢复代理状态
// ============================================================
@@ -1831,6 +1936,36 @@ fn show_database_init_error_dialog(
.blocking_show()
}
// ============================================================
// 退出请求分类
// ============================================================
/// `RunEvent::ExitRequested` 的三类来源,处理方式必须区分。
///
/// 关键约束:重启请求(`code == RESTART_EXIT_CODE`)上 `prevent_exit()` 会被
/// Tauri 静默忽略(见 `ExitRequestApi::prevent_exit` 文档),事件循环必定继续
/// 退出并触发各插件的 `RunEvent::Exit` 钩子;任何与之并发的自定义清理任务都
/// 可能与插件退出钩子争用同一状态而死锁。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExitRequestAction {
/// `code` 为 `None`:运行时自动触发(如隐藏窗口的 WebView 被回收导致无存活
/// 窗口),阻止退出、保持托盘后台运行。
StayInTray,
/// `code` 为 `RESTART_EXIT_CODE``app.restart()` / 自更新 relaunch 发起的
/// 重启,不拦截、不做自定义清理,交还 Tauri 默认 re-exec 流程。
DeferToTauriRestart,
/// 其它 `Some(_)`:用户主动退出(托盘「退出」等),执行完整异步清理后结束进程。
CleanupAndExit,
}
fn classify_exit_request(code: Option<i32>) -> ExitRequestAction {
match code {
None => ExitRequestAction::StayInTray,
Some(tauri::RESTART_EXIT_CODE) => ExitRequestAction::DeferToTauriRestart,
Some(_) => ExitRequestAction::CleanupAndExit,
}
}
// ============================================================
// 在应用主动退出前显式持久化窗口状态
// ============================================================
@@ -1848,3 +1983,59 @@ pub fn save_window_state_before_exit(app_handle: &tauri::AppHandle) {
log::info!("已在退出前保存窗口状态");
}
}
/// 主动释放 single-instance 锁。
///
/// macOS single-instance 使用 `/tmp/{identifier}.sock`。我们有若干路径会直接
/// `std::process::exit(0)`,不会触发插件挂在 `RunEvent::Exit` 上的清理钩子。
/// 重启前主动 destroy 可以避免新进程误连旧 listener 后自行退出。
pub fn destroy_single_instance_lock(app_handle: &tauri::AppHandle) {
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
tauri_plugin_single_instance::destroy(app_handle);
}
/// 清理托盘图标、释放 single-instance 锁后重启当前应用。
///
/// 直接走 `tauri::process::restart`spawn 新进程 + `exit(0)`),不经过事件
/// 循环退出,因此 Tauri 内部的 `cleanup_before_exit` 和各插件的
/// `RunEvent::Exit` 钩子都不会执行。需要的清理由调用方与本函数显式补偿:
/// 窗口状态、代理/Live 恢复(调用方);托盘图标、single-instance 锁(本函数)。
///
/// 有意不调 `AppHandle::cleanup_before_exit()`:它会在调用线程上 Drop 托盘
/// 图标,而 macOS 的 NSStatusItem 操作要求主线程;`set_visible(false)` 走
/// `run_item_main_thread` 代理,跨线程安全(见 `remove_tray_icon_before_exit`)。
pub fn restart_process(app_handle: &tauri::AppHandle) -> ! {
remove_tray_icon_before_exit(app_handle);
destroy_single_instance_lock(app_handle);
tauri::process::restart(&app_handle.env());
}
#[cfg(test)]
mod tests {
use super::{classify_exit_request, ExitRequestAction};
#[test]
fn no_code_keeps_app_alive_in_tray() {
assert_eq!(classify_exit_request(None), ExitRequestAction::StayInTray);
}
#[test]
fn restart_exit_code_defers_to_tauri_default_restart() {
assert_eq!(
classify_exit_request(Some(tauri::RESTART_EXIT_CODE)),
ExitRequestAction::DeferToTauriRestart
);
}
#[test]
fn user_exit_codes_run_cleanup_then_exit() {
assert_eq!(
classify_exit_request(Some(0)),
ExitRequestAction::CleanupAndExit
);
assert_eq!(
classify_exit_request(Some(1)),
ExitRequestAction::CleanupAndExit
);
}
}
+34
View File
@@ -46,6 +46,40 @@ pub fn get_opencode_config_path() -> PathBuf {
get_opencode_dir().join("opencode.json")
}
/// 获取 OpenCode SQLite 数据库路径
/// 优先级: OPENCODE_DB 环境变量 > XDG_DATA_HOME > ~/.local/share/opencode
pub fn get_opencode_db_path() -> PathBuf {
// 支持 OPENCODE_DB 环境变量覆盖(忽略空字符串)
if let Ok(custom_path) = std::env::var("OPENCODE_DB") {
if !custom_path.is_empty() {
let path = PathBuf::from(&custom_path);
if path.is_absolute() {
return path;
}
// 相对路径基于数据目录
return get_opencode_data_dir().join(path);
}
}
get_opencode_data_dir().join("opencode.db")
}
fn get_opencode_data_dir() -> PathBuf {
// 尊重 XDG_DATA_HOME(按 XDG 规范,空字符串视为未设置)
if let Ok(xdg_data) = std::env::var("XDG_DATA_HOME") {
if !xdg_data.is_empty() {
return PathBuf::from(xdg_data).join("opencode");
}
}
// OpenCode 使用 xdg-basedir,不遵守 macOS/Windows 平台约定,
// 所有平台默认都落在 ~/.local/share/opencode
crate::config::get_home_dir()
.join(".local")
.join("share")
.join("opencode")
}
#[allow(dead_code)]
pub fn get_opencode_env_path() -> PathBuf {
get_opencode_dir().join(".env")
+37 -14
View File
@@ -1,3 +1,4 @@
use http::header::{HeaderValue, InvalidHeaderValue};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -108,17 +109,13 @@ impl Provider {
.unwrap_or(false)
}
/// Resolve `(base_url, api_key)` for native usage queries (balance /
/// coding-plan) from the stored provider config.
/// Resolve `(base_url, api_key)` for usage queries (native balance /
/// coding-plan and the JS-script `{{apiKey}}`/`{{baseUrl}}` fallback)
/// from the stored provider config.
///
/// Each app persists credentials in a different shape, so callers must pass
/// the owning app type. This mirrors the frontend `getProviderCredentials`
/// in `UsageScriptModal.tsx`.
///
/// TODO: the env-only helpers in `services/provider/usage.rs`
/// (`extract_api_key_from_provider` / `extract_base_url_from_provider`)
/// duplicate this per-app logic on the JS-script path and could delegate
/// here in a follow-up to remove the remaining copy.
pub fn resolve_usage_credentials(
&self,
app_type: &crate::app_config::AppType,
@@ -290,21 +287,15 @@ pub struct UsageResult {
pub error: Option<String>,
}
/// 供应商单独的模型测试配置
/// 供应商单独的连通检测配置
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProviderTestConfig {
/// 是否启用单独配置(false 时使用全局配置)
#[serde(default)]
pub enabled: bool,
/// 测试用的模型名称(覆盖全局配置)
#[serde(rename = "testModel", skip_serializing_if = "Option::is_none")]
pub test_model: Option<String>,
/// 超时时间(秒)
#[serde(rename = "timeoutSecs", skip_serializing_if = "Option::is_none")]
pub timeout_secs: Option<u64>,
/// 测试提示词
#[serde(rename = "testPrompt", skip_serializing_if = "Option::is_none")]
pub test_prompt: Option<String>,
/// 降级阈值(毫秒)
#[serde(
rename = "degradedThresholdMs",
@@ -464,6 +455,9 @@ pub struct ProviderMeta {
/// Codex Responses -> Chat Completions reasoning capability metadata.
#[serde(rename = "codexChatReasoning", skip_serializing_if = "Option::is_none")]
pub codex_chat_reasoning: Option<CodexChatReasoningConfig>,
/// Custom User-Agent for local proxy routing.
#[serde(rename = "customUserAgent", skip_serializing_if = "Option::is_none")]
pub custom_user_agent: Option<String>,
/// 累加模式应用中,该 provider 是否已写入 live config。
/// `None` 表示旧数据/未知状态,`Some(false)` 表示明确仅存在于数据库中。
#[serde(rename = "liveConfigManaged", skip_serializing_if = "Option::is_none")]
@@ -478,6 +472,30 @@ pub struct ProviderMeta {
pub github_account_id: Option<String>,
}
/// 解析 Provider 级自定义 User-Agent 字符串(单一真理来源)。
///
/// 转发(forwarder)、流式检测(stream_check)、获取模型列表(model_fetch)三条路径
/// 共用同一口径,避免出现"某条路径用了 UA、另一条没用 / 报错"的不一致。
///
/// 合法性由 `http::HeaderValue::from_str` 按**字节**判定(`b >= 32 && b != 127 || b == '\t'`),
/// 与前端 `src/lib/userAgent.ts::isValidUserAgentHeader` 严格一致:
/// - `Ok(None)`:未设置或纯空白(trim 后为空)。
/// - `Ok(Some(hv))`:合法。制表符、可见 ASCII(0x20–0x7E)、以及任意非 ASCII 字符
/// UTF-8 字节均 ≥ 0x80)都合法。
/// - `Err(_)`:仅含控制字符时——除 `\t` 外的 0x000x1F(含换行)与 0x7FDEL)。
///
/// 非法值的处理:三条运行时路径**均静默忽略**`.ok().flatten()`,绝不让某条路径报错而
/// 另一条放行);前端在输入框处给出非阻断提示。当前**不在保存时阻断**——deeplink 导入等
/// 非表单路径应宽容,运行时静默忽略即为安全网。
pub fn parse_custom_user_agent(
raw: Option<&str>,
) -> Result<Option<HeaderValue>, InvalidHeaderValue> {
match raw.map(str::trim).filter(|s| !s.is_empty()) {
Some(ua) => HeaderValue::from_str(ua).map(Some),
None => Ok(None),
}
}
impl ProviderMeta {
/// Codex OAuth FAST mode 是否启用。默认关闭,因为 `service_tier="priority"`
/// 会按更高速率消耗 ChatGPT 订阅配额,用户需显式开启以换取更低延迟。
@@ -485,6 +503,11 @@ impl ProviderMeta {
self.codex_fast_mode.unwrap_or(false)
}
/// 经校验的 Provider 级自定义 User-Agent。见 [`parse_custom_user_agent`]。
pub fn custom_user_agent_header(&self) -> Result<Option<HeaderValue>, InvalidHeaderValue> {
parse_custom_user_agent(self.custom_user_agent.as_deref())
}
/// 解析指定托管认证供应商绑定的账号 ID。
///
/// 新版优先读取 authBinding,旧版继续兼容 githubAccountId。
+419 -7
View File
@@ -38,6 +38,11 @@ pub struct ForwardResult {
pub response: ProxyResponse,
pub provider: Provider,
pub claude_api_format: Option<String>,
/// 实际发往上游的模型名(路由接管/模型映射后的真值)。
///
/// usage 归因不能依赖 ctx.request_model(映射前的客户端别名):上游响应
/// 缺失 model 或回显别名时,接管流量会被记成 claude-* 并按其定价计费。
pub outbound_model: Option<String>,
/// 活跃连接 RAII guard:随响应一起流转到 response_processor / handle_claude_transform
/// 最终被 move 进流式 body future(或非流式响应作用域),覆盖整个响应生命周期。
pub(crate) connection_guard: Option<ActiveConnectionGuard>,
@@ -122,6 +127,51 @@ pub struct RequestForwarder {
}
impl RequestForwarder {
/// 预防式 media 降级:发送前对 text-only 模型把图片块替换为标记。
///
/// 受 `enabled && request_media_fallback` 管辖;其中"启发式模型名单预测"
/// 再受 `request_media_heuristic` 单独管辖(显式声明 text-only 始终生效)。
/// 返回被替换的图片块数量(0 = 未触发或开关关闭)。
fn apply_media_prevention(&self, body: &mut Value, provider: &Provider) -> usize {
if !(self.rectifier_config.enabled && self.rectifier_config.request_media_fallback) {
return 0;
}
let replaced_images = super::media_sanitizer::replace_images_for_text_only_model(
body,
provider,
self.rectifier_config.request_media_heuristic,
);
if replaced_images > 0 {
let model = body.get("model").and_then(Value::as_str).unwrap_or("");
log::info!(
"[Media] Replaced {replaced_images} image block(s) with {} for text-only provider={}, model={}",
super::media_sanitizer::UNSUPPORTED_IMAGE_MARKER,
provider.id,
model
);
}
replaced_images
}
/// 反应式 media 重试判定:上游因图片输入报错后,是否应替换图片块并对同一供应商重试一次。
///
/// 受 `enabled && request_media_fallback` 管辖;不涉及 `request_media_heuristic`——
/// 这里是上游"实测"错误后的纯恢复,不是预测,故启发式开关与它无关。
fn media_retry_should_trigger(
&self,
adapter_name: &str,
already_retried: bool,
provider_body: &Value,
error: &ProxyError,
) -> bool {
matches!(adapter_name, "Claude" | "Codex")
&& self.rectifier_config.enabled
&& self.rectifier_config.request_media_fallback
&& !already_retried
&& super::media_sanitizer::contains_image_blocks(provider_body)
&& super::media_sanitizer::is_unsupported_image_error(error)
}
#[allow(clippy::too_many_arguments)]
pub fn new(
router: Arc<ProviderRouter>,
@@ -346,6 +396,7 @@ impl RequestForwarder {
// —— 首家 provider 整流后被 5xx/timeout 击落时,下家仍能用整流后的请求体走整流流程
let mut rectifier_retried = false;
let mut budget_rectifier_retried = false;
let mut media_rectifier_retried = false;
// 上限检查:尊重用户在 AppProxyConfig.max_retries 上配置的「重试次数」。
// 放在熔断器 allow 检查之前,避免在已经超限时还占用 HalfOpen 探测名额。
@@ -417,7 +468,7 @@ impl RequestForwarder {
)
.await
{
Ok((response, claude_api_format)) => {
Ok((response, claude_api_format, outbound_model)) => {
// 成功:普通闭合熔断状态异步记录,避免阻塞流式首包返回;
// HalfOpen 探测仍同步等待,保证 permit 与熔断状态及时释放。
self.record_success_result(&provider.id, app_type_str, used_half_open_permit)
@@ -465,6 +516,7 @@ impl RequestForwarder {
response,
provider: provider.clone(),
claude_api_format,
outbound_model,
connection_guard: None,
});
}
@@ -477,6 +529,124 @@ impl RequestForwarder {
);
let mut signature_rectifier_non_retryable_client_error = false;
if self.media_retry_should_trigger(
adapter.name(),
media_rectifier_retried,
&provider_body,
&e,
) {
let mut media_body = provider_body.clone();
let replaced_images =
super::media_sanitizer::replace_image_blocks_with_marker(
&mut media_body,
);
if replaced_images > 0 {
let _ = std::mem::replace(&mut media_rectifier_retried, true);
let model = media_body
.get("model")
.and_then(Value::as_str)
.unwrap_or("");
log::info!(
"[{app_type_str}] [Media] Upstream rejected image input; retrying provider={} model={} with {replaced_images} image block(s) replaced by {}",
provider.id,
model,
super::media_sanitizer::UNSUPPORTED_IMAGE_MARKER
);
match self
.forward(
app_type,
&method,
provider,
endpoint,
&media_body,
&headers,
&extensions,
adapter.as_ref(),
)
.await
{
Ok((response, claude_api_format, outbound_model)) => {
log::info!(
"[{app_type_str}] [Media] Unsupported-image retry succeeded"
);
self.record_success_result(
&provider.id,
app_type_str,
used_half_open_permit,
)
.await;
{
let mut current_providers =
self.current_providers.write().await;
current_providers.insert(
app_type_str.to_string(),
(provider.id.clone(), provider.name.clone()),
);
}
{
let mut status = self.status.write().await;
status.success_requests += 1;
status.last_error = None;
let should_switch =
self.current_provider_id_at_start.as_str()
!= provider.id.as_str();
if should_switch {
status.failover_count += 1;
let fm = self.failover_manager.clone();
let ah = self.app_handle.clone();
let pid = provider.id.clone();
let pname = provider.name.clone();
let at = app_type_str.to_string();
tokio::spawn(async move {
let _ = fm
.try_switch(ah.as_ref(), &at, &pid, &pname)
.await;
});
}
if status.total_requests > 0 {
status.success_rate = (status.success_requests as f32
/ status.total_requests as f32)
* 100.0;
}
}
return Ok(ForwardResult {
response,
provider: provider.clone(),
claude_api_format,
outbound_model,
connection_guard: None,
});
}
Err(retry_err) => {
log::warn!(
"[{app_type_str}] [Media] Unsupported-image retry still failed: {retry_err}"
);
if let Some(err) = self
.handle_rectifier_retry_failure(
retry_err,
provider,
app_type_str,
used_half_open_permit,
"media 降级",
&mut last_error,
&mut last_provider,
)
.await
{
return Err(err);
}
continue;
}
}
}
}
if is_anthropic_provider {
let error_message = extract_error_message(&e);
if should_rectify_thinking_signature(
@@ -543,7 +713,7 @@ impl RequestForwarder {
)
.await
{
Ok((response, claude_api_format)) => {
Ok((response, claude_api_format, outbound_model)) => {
log::info!("[{app_type_str}] [RECT-002] 整流重试成功");
self.record_success_result(
&provider.id,
@@ -598,6 +768,7 @@ impl RequestForwarder {
response,
provider: provider.clone(),
claude_api_format,
outbound_model,
connection_guard: None,
});
}
@@ -708,7 +879,7 @@ impl RequestForwarder {
)
.await
{
Ok((response, claude_api_format)) => {
Ok((response, claude_api_format, outbound_model)) => {
log::info!("[{app_type_str}] [RECT-011] budget 整流重试成功");
self.record_success_result(
&provider.id,
@@ -757,6 +928,7 @@ impl RequestForwarder {
response,
provider: provider.clone(),
claude_api_format,
outbound_model,
connection_guard: None,
});
}
@@ -914,6 +1086,9 @@ impl RequestForwarder {
}
/// 转发单个请求(使用适配器)
///
/// 成功时返回 `(response, claude_api_format, outbound_model)`,其中
/// `outbound_model` 是最终发往上游的模型名(所有映射/改写之后)。
#[allow(clippy::too_many_arguments)]
async fn forward(
&self,
@@ -925,7 +1100,7 @@ impl RequestForwarder {
headers: &axum::http::HeaderMap,
extensions: &Extensions,
adapter: &dyn ProviderAdapter,
) -> Result<(ProxyResponse, Option<String>), ProxyError> {
) -> Result<(ProxyResponse, Option<String>, Option<String>), ProxyError> {
// 使用适配器提取 base_url
let mut base_url = adapter.extract_base_url(provider)?;
@@ -1109,11 +1284,12 @@ impl RequestForwarder {
};
if adapter.name() == "Claude" {
if let Some(api_format) = resolved_claude_api_format.as_deref() {
super::providers::normalize_anthropic_tool_thinking_history_for_provider(
super::providers::normalize_anthropic_messages_for_provider(
&mut mapped_body,
provider,
api_format,
);
self.apply_media_prevention(&mut mapped_body, provider);
}
}
let needs_transform = match resolved_claude_api_format.as_deref() {
@@ -1156,8 +1332,17 @@ impl RequestForwarder {
adapter.build_url(&base_url, &effective_endpoint)
};
// 记录映射后的出站模型名(此时 mapped_body 已完成接管映射 / [1m] 剥离 /
// Copilot 归一化)。格式转换后若 body 仍带 model 字段会在下方刷新覆盖;
// gemini_native 等模型在 URL 中的格式则保留此处的转换前真值。
let mut outbound_model = mapped_body
.get("model")
.and_then(|m| m.as_str())
.filter(|m| !m.is_empty())
.map(str::to_string);
// 转换请求体(如果需要)
let request_body = if codex_responses_to_chat {
let mut request_body = if codex_responses_to_chat {
let mut mapped_body = mapped_body;
let restored = self
.codex_chat_history
@@ -1195,9 +1380,21 @@ impl RequestForwarder {
mapped_body
};
if matches!(app_type, AppType::Codex) {
self.apply_media_prevention(&mut request_body, provider);
}
// 过滤私有参数(以 `_` 开头的字段),防止内部信息泄露到上游
// 默认使用空白名单,过滤所有 _ 前缀字段
let filtered_body = prepare_upstream_request_body(request_body);
// 出站 body 定稿后刷新真值(覆盖 Codex chat 上游模型覆写、转换层模型改写)
if let Some(m) = filtered_body
.get("model")
.and_then(|m| m.as_str())
.filter(|m| !m.is_empty())
{
outbound_model = Some(m.to_string());
}
log_prompt_cache_trace(
app_type,
provider,
@@ -1340,6 +1537,18 @@ impl RequestForwarder {
Vec::new()
};
// 自定义 User-Agent:与 stream_check / model_fetch 共用 parse_custom_user_agent
// 运行时静默忽略非法值(前端在输入处给非阻断提示,不在保存时阻断)。
// Copilot 指纹 UA 不可覆盖。
let custom_user_agent = if is_copilot {
None
} else {
provider
.meta
.as_ref()
.and_then(|meta| meta.custom_user_agent_header().ok().flatten())
};
// --- Copilot 优化器:动态 header 注入 ---
if let Some((ref classification, ref det_request_id, ref interaction_id)) =
copilot_optimization
@@ -1434,6 +1643,7 @@ impl RequestForwarder {
let mut ordered_headers = http::HeaderMap::new();
let mut saw_auth = false;
let mut saw_accept_encoding = false;
let mut saw_user_agent = false;
let mut saw_anthropic_beta = false;
let mut saw_anthropic_version = false;
@@ -1514,6 +1724,19 @@ impl RequestForwarder {
continue;
}
// --- user-agent: provider-level override for local proxy routing ---
if !is_copilot && key_str.eq_ignore_ascii_case("user-agent") {
if !saw_user_agent {
saw_user_agent = true;
if let Some(ref ua) = custom_user_agent {
ordered_headers.append(http::header::USER_AGENT, ua.clone());
} else {
ordered_headers.append(key.clone(), value.clone());
}
}
continue;
}
// --- anthropic-beta — 用重建值替换(确保含 claude-code 标记) ---
if key_str.eq_ignore_ascii_case("anthropic-beta") {
if !saw_anthropic_beta {
@@ -1563,6 +1786,12 @@ impl RequestForwarder {
);
}
if !saw_user_agent {
if let Some(ref ua) = custom_user_agent {
ordered_headers.append(http::header::USER_AGENT, ua.clone());
}
}
// 如果原始请求中没有 anthropic-beta 且有值需要添加,追加
if !saw_anthropic_beta {
if let Some(ref beta_val) = anthropic_beta_value {
@@ -1710,7 +1939,7 @@ impl RequestForwarder {
let response = self
.prepare_success_response_for_failover(response, request_is_streaming)
.await?;
Ok((response, resolved_claude_api_format))
Ok((response, resolved_claude_api_format, outbound_model))
} else {
let status_code = status.as_u16();
let body_text = String::from_utf8(response.bytes().await?.to_vec()).ok();
@@ -3106,4 +3335,187 @@ mod tests {
assert_eq!(will_replace, should_replace, "{desc}");
}
}
// ===== P3: forwarder 层 media 开关回归测试 =====
// 验证 gate 在 forwarder 这一层的"接线",而非 media_sanitizer 纯函数本身。
fn forwarder_with_rectifier(config: RectifierConfig) -> RequestForwarder {
let mut fwd = test_forwarder(Duration::from_secs(1), Duration::from_secs(1));
fwd.rectifier_config = config;
fwd
}
fn provider_with_settings(settings_config: Value) -> Provider {
let mut p = test_provider_with_type(Some("anthropic"));
p.settings_config = settings_config;
p
}
fn body_with_image(model: &str) -> Value {
json!({
"model": model,
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
})
}
fn body_with_codex_input_image(model: &str) -> Value {
json!({
"model": model,
"input": [{
"role": "user",
"content": [
{ "type": "input_image", "image_url": "data:image/png;base64,abc" }
]
}]
})
}
fn image_unsupported_error() -> ProxyError {
ProxyError::UpstreamError {
status: 400,
body: Some(
r#"{"error":{"message":"This model does not support image input"}}"#.to_string(),
),
}
}
#[test]
fn prevention_replaces_when_all_switches_on_and_model_in_heuristic_list() {
let fwd = forwarder_with_rectifier(RectifierConfig::default());
let provider = provider_with_settings(json!({}));
let mut body = body_with_image("deepseek-v4-pro");
let replaced = fwd.apply_media_prevention(&mut body, &provider);
assert_eq!(replaced, 1, "默认全开 + 名单内模型应预替换");
assert_eq!(body["messages"][0]["content"][0]["type"], "text");
}
#[test]
fn prevention_skipped_when_media_fallback_off() {
// 关闭 request_media_fallback:即使名单命中也不预替换。
let fwd = forwarder_with_rectifier(RectifierConfig {
request_media_fallback: false,
..RectifierConfig::default()
});
let provider = provider_with_settings(json!({}));
let mut body = body_with_image("deepseek-v4-pro");
let replaced = fwd.apply_media_prevention(&mut body, &provider);
assert_eq!(replaced, 0);
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
}
#[test]
fn prevention_skipped_when_master_switch_off() {
let fwd = forwarder_with_rectifier(RectifierConfig {
enabled: false,
..RectifierConfig::default()
});
let provider = provider_with_settings(json!({}));
let mut body = body_with_image("deepseek-v4-pro");
assert_eq!(fwd.apply_media_prevention(&mut body, &provider), 0);
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
}
#[test]
fn prevention_heuristic_off_skips_list_but_keeps_explicit_text_only() {
// 关闭 request_media_heuristic:名单预测失效,但显式声明 text-only 仍预替换。
let fwd = forwarder_with_rectifier(RectifierConfig {
request_media_heuristic: false,
..RectifierConfig::default()
});
// (a) 名单内模型、无显式声明 → 不再预替换
let bare_provider = provider_with_settings(json!({}));
let mut list_body = body_with_image("deepseek-v4-pro");
assert_eq!(
fwd.apply_media_prevention(&mut list_body, &bare_provider),
0,
"heuristic 关闭后名单模型不应被预替换"
);
assert_eq!(list_body["messages"][0]["content"][0]["type"], "image");
// (b) 显式声明 text-only → 仍预替换(声明驱动,不受 heuristic 开关影响)
let declared_provider = provider_with_settings(json!({
"models": [ { "id": "some-text-model", "input": ["text"] } ]
}));
let mut declared_body = body_with_image("some-text-model");
assert_eq!(
fwd.apply_media_prevention(&mut declared_body, &declared_provider),
1,
"显式 text-only 即使关闭 heuristic 也应预替换"
);
assert_eq!(declared_body["messages"][0]["content"][0]["type"], "text");
}
#[test]
fn reactive_triggers_when_all_switches_on() {
let fwd = forwarder_with_rectifier(RectifierConfig::default());
let body = body_with_image("any-model");
assert!(fwd.media_retry_should_trigger("Claude", false, &body, &image_unsupported_error()));
}
#[test]
fn reactive_triggers_for_codex_image_url_deserialize_errors() {
let fwd = forwarder_with_rectifier(RectifierConfig::default());
let body = body_with_codex_input_image("deepseek-v4-flash");
let error = ProxyError::UpstreamError {
status: 400,
body: Some(
r#"{"error":{"message":"Failed to deserialize the JSON body into the target type: messages[11]: unknown variant image_url, expected text"}}"#
.to_string(),
),
};
assert!(fwd.media_retry_should_trigger("Codex", false, &body, &error));
}
#[test]
fn reactive_skipped_when_media_fallback_off() {
// 关闭 request_media_fallback:上游报图片错误也不触发兜底重试。
let fwd = forwarder_with_rectifier(RectifierConfig {
request_media_fallback: false,
..RectifierConfig::default()
});
let body = body_with_image("any-model");
assert!(!fwd.media_retry_should_trigger(
"Claude",
false,
&body,
&image_unsupported_error()
));
}
#[test]
fn reactive_skipped_when_master_switch_off() {
let fwd = forwarder_with_rectifier(RectifierConfig {
enabled: false,
..RectifierConfig::default()
});
let body = body_with_image("any-model");
assert!(!fwd.media_retry_should_trigger(
"Claude",
false,
&body,
&image_unsupported_error()
));
}
#[test]
fn reactive_unaffected_by_heuristic_switch() {
// 关闭 request_media_heuristic 不影响反应式兜底——它是上游实测错误后的恢复,不是预测。
let fwd = forwarder_with_rectifier(RectifierConfig {
request_media_heuristic: false,
..RectifierConfig::default()
});
let body = body_with_image("any-model");
assert!(fwd.media_retry_should_trigger("Claude", false, &body, &image_unsupported_error()));
}
}
+23 -15
View File
@@ -60,37 +60,40 @@ fn gemini_stream_usage_event_filter(data: &str) -> bool {
// ============================================================================
/// Claude 流式响应模型提取(优先使用 usage.model
fn claude_model_extractor(events: &[Value], request_model: &str) -> String {
///
/// 空字符串模型名视为缺失(转换层对无回显上游会合成 model:""),
/// 落到 fallback_model(映射后的出站模型或客户端请求模型)。
fn claude_model_extractor(events: &[Value], fallback_model: &str) -> String {
// 首先尝试从解析的 usage 中获取模型
if let Some(usage) = TokenUsage::from_claude_stream_events(events) {
if let Some(model) = usage.model {
if let Some(model) = usage.model.filter(|m| !m.is_empty()) {
return model;
}
}
request_model.to_string()
fallback_model.to_string()
}
/// OpenAI Chat Completions 流式响应模型提取(优先使用 usage.model
fn openai_model_extractor(events: &[Value], request_model: &str) -> String {
fn openai_model_extractor(events: &[Value], fallback_model: &str) -> String {
// 首先尝试从解析的 usage 中获取模型
if let Some(usage) = TokenUsage::from_openai_stream_events(events) {
if let Some(model) = usage.model {
if let Some(model) = usage.model.filter(|m| !m.is_empty()) {
return model;
}
}
// 回退:从事件中直接提取
events
.iter()
.find_map(|e| e.get("model")?.as_str())
.unwrap_or(request_model)
.find_map(|e| e.get("model")?.as_str().filter(|m| !m.is_empty()))
.unwrap_or(fallback_model)
.to_string()
}
/// Codex 智能流式响应模型提取(自动检测格式)
fn codex_auto_model_extractor(events: &[Value], request_model: &str) -> String {
fn codex_auto_model_extractor(events: &[Value], fallback_model: &str) -> String {
// 首先尝试从解析的 usage 中获取模型
if let Some(usage) = TokenUsage::from_codex_stream_events_auto(events) {
if let Some(model) = usage.model {
if let Some(model) = usage.model.filter(|m| !m.is_empty()) {
return model;
}
}
@@ -99,28 +102,33 @@ fn codex_auto_model_extractor(events: &[Value], request_model: &str) -> String {
.iter()
.find_map(|e| {
if e.get("type")?.as_str()? == "response.completed" {
e.get("response")?.get("model")?.as_str()
e.get("response")?
.get("model")?
.as_str()
.filter(|m| !m.is_empty())
} else {
None
}
})
.or_else(|| {
// 再回退:从 OpenAI 格式事件中提取
events.iter().find_map(|e| e.get("model")?.as_str())
events
.iter()
.find_map(|e| e.get("model")?.as_str().filter(|m| !m.is_empty()))
})
.unwrap_or(request_model)
.unwrap_or(fallback_model)
.to_string()
}
/// Gemini 流式响应模型提取(优先使用 usage.model
fn gemini_model_extractor(events: &[Value], request_model: &str) -> String {
fn gemini_model_extractor(events: &[Value], fallback_model: &str) -> String {
// 首先尝试从解析的 usage 中获取模型
if let Some(usage) = TokenUsage::from_gemini_stream_chunks(events) {
if let Some(model) = usage.model {
if let Some(model) = usage.model.filter(|m| !m.is_empty()) {
return model;
}
}
request_model.to_string()
fallback_model.to_string()
}
// ============================================================================
+6
View File
@@ -48,6 +48,11 @@ pub struct RequestContext {
pub current_provider_id: String,
/// 请求中的模型名称
pub request_model: String,
/// 实际发往上游的模型名(路由接管/模型映射后的真值,forward 成功后回填)。
///
/// usage 归因的兜底顺序:上游响应回显 → outbound_model → request_model。
/// 不能直接用 request_model 兜底:接管场景下它是映射前的客户端别名。
pub outbound_model: Option<String>,
/// 日志标签(如 "Claude"、"Codex"、"Gemini"
pub tag: &'static str,
/// 应用类型字符串(如 "claude"、"codex"、"gemini"
@@ -159,6 +164,7 @@ impl RequestContext {
providers,
current_provider_id,
request_model,
outbound_model: None,
tag,
app_type_str,
app_type,
File diff suppressed because it is too large Load Diff
+831
View File
@@ -0,0 +1,831 @@
use crate::provider::Provider;
use crate::proxy::error::ProxyError;
use serde_json::{json, Value};
pub const UNSUPPORTED_IMAGE_MARKER: &str = "[Unsupported Image]";
/// Replace image blocks before sending when the routed model is text-only.
///
/// Two paths, both reached only when the caller's media-fallback switch is on:
/// - explicit capability from the provider config (modelCatalog / modalities) is
/// always trusted — it is declaration-driven, never a guess;
/// - the curated `known_text_only_model` list is a heuristic *prediction* and only
/// runs when `allow_heuristic` is true, so a mislabeled multimodal model cannot
/// have its images silently stripped when the user opts out.
pub fn replace_images_for_text_only_model(
body: &mut Value,
provider: &Provider,
allow_heuristic: bool,
) -> usize {
if !contains_image_blocks(body) {
return 0;
}
let model = body
.get("model")
.and_then(Value::as_str)
.map(str::trim)
.unwrap_or("");
match explicit_model_image_support(provider, model) {
Some(true) => return 0,
Some(false) => return replace_images_in_body(body),
None => {}
}
if !allow_heuristic || !known_text_only_model(model) {
return 0;
}
replace_images_in_body(body)
}
pub fn contains_image_blocks(body: &Value) -> bool {
messages_have_image_blocks(body) || responses_input_has_image_blocks(body.get("input"))
}
pub fn replace_image_blocks_with_marker(body: &mut Value) -> usize {
replace_images_in_body(body)
}
pub fn is_unsupported_image_error(error: &ProxyError) -> bool {
let ProxyError::UpstreamError { status, body } = error else {
return false;
};
if !matches!(*status, 400 | 415 | 422 | 501) {
return false;
}
let Some(body) = body.as_deref() else {
return false;
};
let message = extract_error_text(body);
let message = message.to_ascii_lowercase();
let mentions_image = message.contains("image")
|| message.contains("vision")
|| message.contains("multimodal")
|| message.contains("multi-modal")
|| message.contains("modality")
|| message.contains("modalities")
|| message.contains("media")
|| message.contains("attachment");
if !mentions_image {
return false;
}
const UNSUPPORTED_HINTS: &[&str] = &[
"unsupported",
"not supported",
"does not support",
"doesn't support",
"do not support",
"don't support",
"only supports text",
"text only",
"text-only",
"invalid content type",
"invalid message content",
"unknown variant",
"unknown content type",
"unrecognized content type",
"cannot process",
"cannot handle",
"can't process",
"can't handle",
"unable to process",
];
UNSUPPORTED_HINTS.iter().any(|hint| message.contains(hint))
}
fn content_has_image_blocks(content: &Value) -> bool {
let Some(blocks) = content.as_array() else {
return false;
};
blocks.iter().any(|block| {
is_image_block_type(block.get("type").and_then(Value::as_str))
|| block.get("content").is_some_and(content_has_image_blocks)
})
}
fn replace_images_in_body(body: &mut Value) -> usize {
let message_replacements = body
.get_mut("messages")
.and_then(Value::as_array_mut)
.map(|messages| {
messages
.iter_mut()
.filter_map(|message| message.get_mut("content"))
.map(replace_images_in_content)
.sum()
})
.unwrap_or(0);
message_replacements
+ body
.get_mut("input")
.map(replace_images_in_responses_input)
.unwrap_or(0)
}
fn replace_images_in_content(content: &mut Value) -> usize {
replace_images_in_content_with_text_type(content, "text")
}
fn replace_images_in_content_with_text_type(content: &mut Value, text_type: &str) -> usize {
let Some(blocks) = content.as_array_mut() else {
return 0;
};
let mut replaced = 0usize;
for block in blocks {
if is_image_block_type(block.get("type").and_then(Value::as_str)) {
replace_image_block_with_text_marker(block, text_type);
replaced += 1;
continue;
}
if let Some(nested_content) = block.get_mut("content") {
replaced += replace_images_in_content_with_text_type(nested_content, text_type);
}
}
replaced
}
fn messages_have_image_blocks(body: &Value) -> bool {
body.get("messages")
.and_then(Value::as_array)
.is_some_and(|messages| {
messages
.iter()
.filter_map(|message| message.get("content"))
.any(content_has_image_blocks)
})
}
fn responses_input_has_image_blocks(input: Option<&Value>) -> bool {
match input {
Some(Value::Array(items)) => items.iter().any(responses_input_item_has_image_blocks),
Some(item @ Value::Object(_)) => responses_input_item_has_image_blocks(item),
_ => false,
}
}
fn responses_input_item_has_image_blocks(item: &Value) -> bool {
if item.get("type").and_then(Value::as_str) == Some("input_image") {
return true;
}
item.get("content").is_some_and(content_has_image_blocks)
}
fn replace_images_in_responses_input(input: &mut Value) -> usize {
match input {
Value::Array(items) => items
.iter_mut()
.map(replace_images_in_responses_input_item)
.sum(),
Value::Object(_) => replace_images_in_responses_input_item(input),
_ => 0,
}
}
fn replace_images_in_responses_input_item(item: &mut Value) -> usize {
let mut replaced = 0usize;
if item.get("type").and_then(Value::as_str) == Some("input_image") {
replace_image_block_with_text_marker(item, "input_text");
replaced += 1;
}
if let Some(content) = item.get_mut("content") {
replaced += replace_images_in_content_with_text_type(content, "input_text");
}
replaced
}
fn is_image_block_type(block_type: Option<&str>) -> bool {
matches!(block_type, Some("image" | "image_url" | "input_image"))
}
fn replace_image_block_with_text_marker(block: &mut Value, text_type: &str) {
let cache_control = block.get("cache_control").cloned();
*block = json!({
"type": text_type,
"text": UNSUPPORTED_IMAGE_MARKER
});
if let (Some(cache_control), Some(object)) = (cache_control, block.as_object_mut()) {
object.insert("cache_control".to_string(), cache_control);
}
}
fn explicit_model_image_support(provider: &Provider, model: &str) -> Option<bool> {
let settings = &provider.settings_config;
[
settings
.get("modelCatalog")
.and_then(|catalog| catalog.get("models")),
settings.get("modelCatalog"),
settings.get("models"),
]
.into_iter()
.flatten()
.find_map(|value| explicit_model_image_support_in_value(value, model))
}
fn known_text_only_model(model: &str) -> bool {
let normalized = normalize_model_id(model);
let tail = normalized.rsplit('/').next().unwrap_or(normalized.as_str());
const EXACT_TAILS: &[&str] = &[
"ark-code-latest",
"deepseek-chat",
"deepseek-reasoner",
"deepseek-v4-flash",
"deepseek-v4-pro",
"glm-5.1",
"kat-coder",
"kat-coder-pro",
"kat-coder-pro v1",
"kat-coder-pro v2",
"kat-coder-pro-v1",
"kat-coder-pro-v2",
"ling-2.5-1t",
"longcat-flash-chat",
"mimo-v2.5-pro",
"us.deepseek.r1-v1",
];
const TAIL_PREFIXES: &[&str] = &["minimax-m2.7", "qwen3-coder", "step-3.5-flash"];
EXACT_TAILS.contains(&tail) || TAIL_PREFIXES.iter().any(|prefix| tail.starts_with(prefix))
}
fn explicit_model_image_support_in_value(value: &Value, model: &str) -> Option<bool> {
if let Some(models) = value.as_array() {
return models.iter().find_map(|entry| {
model_entry_matches(entry, None, model).then(|| explicit_image_support(entry))?
});
}
let object = value.as_object()?;
object.iter().find_map(|(key, entry)| {
model_entry_matches(entry, Some(key), model).then(|| explicit_image_support(entry))?
})
}
fn explicit_image_support(entry: &Value) -> Option<bool> {
if let Some(value) = entry
.get("supportsImage")
.or_else(|| entry.get("supports_image"))
.or_else(|| entry.get("vision"))
.and_then(Value::as_bool)
{
return Some(value);
}
[
entry.get("input"),
entry.pointer("/modalities/input"),
entry.get("input_modalities"),
entry.get("inputModalities"),
]
.into_iter()
.flatten()
.find_map(input_modalities_support_image)
}
fn input_modalities_support_image(value: &Value) -> Option<bool> {
let modalities = value.as_array()?;
Some(modalities.iter().any(|item| {
item.as_str()
.map(str::trim)
.is_some_and(|item| item.eq_ignore_ascii_case("image"))
}))
}
fn extract_error_text(body: &str) -> String {
if let Ok(value) = serde_json::from_str::<Value>(body) {
let candidates = [
value.pointer("/error/message"),
value.pointer("/message"),
value.pointer("/detail"),
value.pointer("/error"),
];
if let Some(message) = candidates
.into_iter()
.flatten()
.find_map(|value| value.as_str())
{
return message.to_string();
}
if let Ok(compact) = serde_json::to_string(&value) {
return compact;
}
}
body.to_string()
}
fn model_entry_matches(entry: &Value, key: Option<&str>, model: &str) -> bool {
key.is_some_and(|key| model_ids_match(key, model))
|| ["model", "id", "name"]
.into_iter()
.filter_map(|field| entry.get(field).and_then(Value::as_str))
.any(|candidate| model_ids_match(candidate, model))
}
fn model_ids_match(candidate: &str, model: &str) -> bool {
let candidate = normalize_model_id(candidate);
let model = normalize_model_id(model);
if candidate.is_empty() || model.is_empty() {
return false;
}
if candidate == model {
return true;
}
let candidate_tail = candidate.rsplit('/').next().unwrap_or(candidate.as_str());
let model_tail = model.rsplit('/').next().unwrap_or(model.as_str());
candidate_tail == model_tail || candidate == model_tail || candidate_tail == model
}
fn normalize_model_id(value: &str) -> String {
let mut normalized = value
.trim()
.trim_start_matches("models/")
.trim()
.to_ascii_lowercase();
if let Some(stripped) =
normalized.strip_suffix(crate::claude_desktop_config::ONE_M_CONTEXT_MARKER)
{
normalized = stripped.trim().to_string();
}
normalized
}
#[cfg(test)]
mod tests {
use super::*;
use crate::provider::Provider;
use serde_json::json;
fn provider(settings_config: Value) -> Provider {
Provider {
id: "test".to_string(),
name: "Test".to_string(),
settings_config,
website_url: None,
category: None,
created_at: None,
sort_index: None,
notes: None,
meta: None,
icon: None,
icon_color: None,
in_failover_queue: false,
}
}
#[test]
fn keeps_images_when_model_capability_is_unknown() {
let provider = provider(json!({}));
let mut body = json!({
"model": "unknown-model",
"messages": [{
"role": "user",
"content": [
{ "type": "text", "text": "look" },
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, true);
assert_eq!(count, 0);
assert_eq!(body["messages"][0]["content"][1]["type"], "image");
}
#[test]
fn known_text_only_models_replace_images_before_send() {
let provider = provider(json!({}));
let mut body = json!({
"model": "deepseek/deepseek-v4-pro",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, true);
assert_eq!(count, 1);
assert_eq!(
body["messages"][0]["content"][0]["text"],
UNSUPPORTED_IMAGE_MARKER
);
}
#[test]
fn known_text_only_models_replace_chat_image_url_before_send() {
let provider = provider(json!({}));
let mut body = json!({
"model": "deepseek-v4-flash",
"messages": [{
"role": "user",
"content": [
{ "type": "text", "text": "look" },
{ "type": "image_url", "image_url": { "url": "data:image/png;base64,abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, true);
assert_eq!(count, 1);
assert_eq!(body["messages"][0]["content"][1]["type"], "text");
assert_eq!(
body["messages"][0]["content"][1]["text"],
UNSUPPORTED_IMAGE_MARKER
);
}
#[test]
fn known_text_only_models_replace_codex_input_image_before_send() {
let provider = provider(json!({}));
let mut body = json!({
"model": "deepseek-v4-flash",
"input": [{
"role": "user",
"content": [
{ "type": "input_text", "text": "look" },
{ "type": "input_image", "image_url": "data:image/png;base64,abc" }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, true);
assert_eq!(count, 1);
assert_eq!(body["input"][0]["content"][1]["type"], "input_text");
assert_eq!(
body["input"][0]["content"][1]["text"],
UNSUPPORTED_IMAGE_MARKER
);
}
#[test]
fn explicit_text_modalities_replace_images_before_send() {
let provider = provider(json!({
"models": [
{ "id": "deepseek-v4-pro", "input": ["text"] }
]
}));
let mut body = json!({
"model": "deepseek-v4-pro",
"messages": [{
"role": "user",
"content": [
{ "type": "text", "text": "look" },
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, true);
assert_eq!(count, 1);
assert_eq!(body["messages"][0]["content"][0]["text"], "look");
assert_eq!(body["messages"][0]["content"][1]["type"], "text");
assert_eq!(
body["messages"][0]["content"][1]["text"],
UNSUPPORTED_IMAGE_MARKER
);
}
#[test]
fn preserves_images_without_explicit_capability_even_for_unknown_models() {
let provider = provider(json!({}));
let mut body = json!({
"model": "unknown-model",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, true);
assert_eq!(count, 0);
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
}
#[test]
fn explicit_text_modalities_can_override_visual_model_ids() {
let provider = provider(json!({
"models": [
{ "id": "gpt-4o", "input": ["text"] }
]
}));
let mut body = json!({
"model": "gpt-4o",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, true);
assert_eq!(count, 1);
assert_eq!(
body["messages"][0]["content"][0]["text"],
UNSUPPORTED_IMAGE_MARKER
);
}
#[test]
fn explicit_image_modalities_preserve_model_images() {
let provider = provider(json!({
"modelCatalog": {
"models": [
{ "model": "deepseek-v4-pro", "modalities": { "input": ["text", "image"] } }
]
}
}));
let mut body = json!({
"model": "deepseek-v4-pro",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, true);
assert_eq!(count, 0);
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
}
#[test]
fn known_mimo_pro_replaces_but_mimo_multimodal_preserves() {
let provider = provider(json!({}));
let mut pro_body = json!({
"model": "xiaomi-mimo-token-plan/mimo-v2.5-pro",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let mut multimodal_body = json!({
"model": "xiaomi-mimo-token-plan/mimo-v2.5",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let pro_count = replace_images_for_text_only_model(&mut pro_body, &provider, true);
let multimodal_count =
replace_images_for_text_only_model(&mut multimodal_body, &provider, true);
assert_eq!(pro_count, 1);
assert_eq!(multimodal_count, 0);
assert_eq!(
multimodal_body["messages"][0]["content"][0]["type"],
"image"
);
}
#[test]
fn multimodal_kimi_model_is_not_on_text_only_list() {
let provider = provider(json!({}));
let mut body = json!({
"model": "kimi/kimi-k2.6",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, true);
assert_eq!(count, 0);
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
}
#[test]
fn known_text_only_prefixes_replace_images_before_send() {
let provider = provider(json!({}));
let mut body = json!({
"model": "therouter/qwen/qwen3-coder-480b",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, true);
assert_eq!(count, 1);
assert_eq!(
body["messages"][0]["content"][0]["text"],
UNSUPPORTED_IMAGE_MARKER
);
}
#[test]
fn unconditional_marker_replacement_handles_retry_path() {
let mut body = json!({
"model": "xiaomi-mimo-token-plan/mimo-v2.5-pro",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
assert!(contains_image_blocks(&body));
let count = replace_image_blocks_with_marker(&mut body);
assert_eq!(count, 1);
assert_eq!(
body["messages"][0]["content"][0]["text"],
UNSUPPORTED_IMAGE_MARKER
);
}
#[test]
fn replaces_nested_tool_result_image_blocks() {
let mut body = json!({
"model": "deepseek-v4-pro",
"messages": [{
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": "toolu_1",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
}]
});
let count = replace_image_blocks_with_marker(&mut body);
assert_eq!(count, 1);
assert_eq!(
body["messages"][0]["content"][0]["content"][0]["text"],
UNSUPPORTED_IMAGE_MARKER
);
}
#[test]
fn detects_unsupported_image_errors() {
let error = ProxyError::UpstreamError {
status: 400,
body: Some(
r#"{"error":{"message":"This model does not support image input"}}"#.to_string(),
),
};
assert!(is_unsupported_image_error(&error));
}
#[test]
fn ignores_non_image_errors() {
let error = ProxyError::UpstreamError {
status: 400,
body: Some(r#"{"error":{"message":"Invalid API key"}}"#.to_string()),
};
assert!(!is_unsupported_image_error(&error));
}
#[test]
fn preserves_cache_control_when_replacing_image() {
// image block 可能承载 prompt cache 断点;替换成标记时必须把
// cache_control 迁移到新的 text block,否则会断掉缓存命中。
let mut body = json!({
"model": "deepseek-v4-pro",
"messages": [{
"role": "user",
"content": [{
"type": "image",
"source": { "type": "base64", "media_type": "image/png", "data": "abc" },
"cache_control": { "type": "ephemeral" }
}]
}]
});
let count = replace_image_blocks_with_marker(&mut body);
assert_eq!(count, 1);
let block = &body["messages"][0]["content"][0];
assert_eq!(block["type"], "text");
assert_eq!(block["text"], UNSUPPORTED_IMAGE_MARKER);
assert_eq!(block["cache_control"]["type"], "ephemeral");
}
#[test]
fn detects_media_and_attachment_error_phrasings() {
let media_error = ProxyError::UpstreamError {
status: 400,
body: Some(
r#"{"error":{"message":"This model cannot process media inputs"}}"#.to_string(),
),
};
assert!(is_unsupported_image_error(&media_error));
let attachment_error = ProxyError::UpstreamError {
status: 422,
body: Some(r#"{"message":"attachments are not supported by this model"}"#.to_string()),
};
assert!(is_unsupported_image_error(&attachment_error));
}
#[test]
fn detects_chat_content_unknown_variant_image_url_errors() {
let error = ProxyError::UpstreamError {
status: 400,
body: Some(
r#"{"error":{"message":"Failed to deserialize the JSON body into the target type: messages[11]: unknown variant image_url, expected text"}}"#
.to_string(),
),
};
assert!(is_unsupported_image_error(&error));
}
#[test]
fn heuristic_disabled_keeps_images_for_listed_text_only_models() {
// allow_heuristic = false:内置列表不再预测性剥图,避免误判多模态模型时静默丢图。
let provider = provider(json!({}));
let mut body = json!({
"model": "deepseek/deepseek-v4-pro",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, false);
assert_eq!(count, 0);
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
}
#[test]
fn explicit_text_capability_replaces_even_when_heuristic_disabled() {
// 显式声明 text-only 是声明驱动、零误判,即使关掉启发式也应生效。
let provider = provider(json!({
"models": [
{ "id": "deepseek-v4-pro", "input": ["text"] }
]
}));
let mut body = json!({
"model": "deepseek-v4-pro",
"messages": [{
"role": "user",
"content": [
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
]
}]
});
let count = replace_images_for_text_only_model(&mut body, &provider, false);
assert_eq!(count, 1);
assert_eq!(
body["messages"][0]["content"][0]["text"],
UNSUPPORTED_IMAGE_MARKER
);
}
}
+1
View File
@@ -19,6 +19,7 @@ pub mod http_client;
pub mod hyper_client;
pub(crate) mod json_canonical;
pub mod log_codes;
pub mod media_sanitizer;
pub mod model_mapper;
pub mod provider_router;
pub mod providers;
+67 -1
View File
@@ -11,6 +11,7 @@ pub struct ModelMapping {
pub haiku_model: Option<String>,
pub sonnet_model: Option<String>,
pub opus_model: Option<String>,
pub fable_model: Option<String>,
pub default_model: Option<String>,
}
@@ -35,6 +36,11 @@ impl ModelMapping {
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(String::from),
fable_model: env
.and_then(|e| e.get("ANTHROPIC_DEFAULT_FABLE_MODEL"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(String::from),
default_model: env
.and_then(|e| e.get("ANTHROPIC_MODEL"))
.and_then(|v| v.as_str())
@@ -48,6 +54,7 @@ impl ModelMapping {
self.haiku_model.is_some()
|| self.sonnet_model.is_some()
|| self.opus_model.is_some()
|| self.fable_model.is_some()
|| self.default_model.is_some()
}
@@ -56,6 +63,16 @@ impl ModelMapping {
let model_lower = original_model.to_lowercase();
// 1. 按模型类型匹配
if model_lower.contains("fable") {
if let Some(ref m) = self.fable_model {
return m.clone();
}
// 未单独配置 fable 档时归入 opus 档,与 Claude Code 官方
// 分类器降级方向一致(fable→opus),避免落到 default 失去层级。
if let Some(ref m) = self.opus_model {
return m.clone();
}
}
if model_lower.contains("haiku") {
if let Some(ref m) = self.haiku_model {
return m.clone();
@@ -154,7 +171,8 @@ mod tests {
"ANTHROPIC_MODEL": "default-model",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "haiku-mapped",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "sonnet-mapped",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped"
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped",
"ANTHROPIC_DEFAULT_FABLE_MODEL": "fable-mapped"
}
}),
website_url: None,
@@ -214,6 +232,54 @@ mod tests {
assert_eq!(mapped, Some("opus-mapped".to_string()));
}
#[test]
fn test_fable_mapping() {
let provider = create_provider_with_mapping();
let body = json!({"model": "claude-fable-5"});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "fable-mapped");
assert_eq!(mapped, Some("fable-mapped".to_string()));
}
#[test]
fn test_fable_with_one_m_suffix_mapping() {
// Claude Code 实际会发 claude-fable-5[1m] 形态(issue #3980
let provider = create_provider_with_mapping();
let body = json!({"model": "claude-fable-5[1m]"});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "fable-mapped");
assert_eq!(mapped, Some("fable-mapped".to_string()));
}
#[test]
fn test_fable_falls_back_to_opus_when_unset() {
let mut provider = create_provider_with_mapping();
provider.settings_config = json!({
"env": {
"ANTHROPIC_MODEL": "default-model",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped"
}
});
let body = json!({"model": "claude-fable-5"});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "opus-mapped");
assert_eq!(mapped, Some("opus-mapped".to_string()));
}
#[test]
fn test_fable_falls_back_to_default_without_opus() {
let mut provider = create_provider_with_mapping();
provider.settings_config = json!({
"env": {
"ANTHROPIC_MODEL": "default-model"
}
});
let body = json!({"model": "claude-fable-5"});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "default-model");
assert_eq!(mapped, Some("default-model".to_string()));
}
#[test]
fn test_thinking_does_not_affect_model_mapping() {
// Issue #2081: thinking 参数不应影响模型映射
+179
View File
@@ -145,6 +145,86 @@ pub fn normalize_anthropic_tool_thinking_history_for_provider(
normalize_anthropic_tool_thinking_history(body)
}
pub fn normalize_anthropic_messages_for_provider(
body: &mut Value,
provider: &Provider,
api_format: &str,
) -> bool {
if api_format.trim() != "anthropic" {
return false;
}
let mut changed = normalize_anthropic_system_role_messages(body);
changed |= normalize_anthropic_tool_thinking_history_for_provider(body, provider, api_format);
changed
}
fn normalize_anthropic_system_role_messages(body: &mut Value) -> bool {
let mut system_parts = Vec::new();
let changed = {
let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
return false;
};
let original_len = messages.len();
let mut kept_messages = Vec::with_capacity(messages.len());
for message in std::mem::take(messages) {
if message.get("role").and_then(Value::as_str) == Some("system") {
if let Some(content) = message.get("content") {
append_anthropic_system_parts(content, &mut system_parts);
}
} else {
kept_messages.push(message);
}
}
let changed = kept_messages.len() != original_len;
*messages = kept_messages;
changed
};
if !changed || system_parts.is_empty() {
return changed;
}
let mut merged_parts = Vec::new();
if let Some(existing) = body.get("system") {
append_anthropic_system_parts(existing, &mut merged_parts);
}
merged_parts.extend(system_parts);
if !merged_parts.is_empty() {
body["system"] = Value::Array(merged_parts);
}
true
}
fn append_anthropic_system_parts(content: &Value, parts: &mut Vec<Value>) {
match content {
Value::String(text) if !text.trim().is_empty() => {
parts.push(json!({
"type": "text",
"text": text
}));
}
Value::Array(items) => {
for item in items {
append_anthropic_system_parts(item, parts);
}
}
Value::Object(obj)
if obj
.get("text")
.and_then(Value::as_str)
.is_some_and(|text| !text.trim().is_empty()) =>
{
parts.push(Value::Object(obj.clone()));
}
_ => {}
}
}
fn normalize_anthropic_tool_thinking_history(body: &mut Value) -> bool {
let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
return false;
@@ -329,6 +409,10 @@ pub fn transform_claude_request_for_api_format(
{
result["prompt_cache_key"] = serde_json::json!(key);
}
// 流式请求必须注入 stream_options.include_usage,否则 OpenAI 兼容上游
// 不在 SSE 末尾吐 usage → 转换出的 Anthropic message_delta 全 0 →
// 整笔 input/output/cache 漏记(与 Codex Responses→Chat 路径同源)。
super::transform::inject_openai_stream_include_usage(&mut result);
Ok(result)
}
"gemini_native" => super::transform_gemini::anthropic_to_gemini_with_shadow(
@@ -1537,6 +1621,43 @@ mod tests {
assert!(transformed.get("max_output_tokens").is_some());
}
#[test]
fn test_transform_claude_request_openai_chat_streaming_injects_include_usage() {
let provider = create_provider(json!({
"env": { "ANTHROPIC_BASE_URL": "https://openrouter.ai/api/v1" }
}));
// 流式请求必须注入 stream_options.include_usage,否则 OpenAI 兼容上游不在
// SSE 末尾吐 usage → 转换出的 Anthropic message_delta 全 0 → 整笔 usage 漏记。
let body = json!({
"model": "moonshotai/kimi-k2",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 128,
"stream": true
});
let transformed =
transform_claude_request_for_api_format(body, &provider, "openai_chat", None, None)
.unwrap();
assert_eq!(transformed["stream"], true);
assert_eq!(transformed["stream_options"]["include_usage"], true);
}
#[test]
fn test_transform_claude_request_openai_chat_non_streaming_omits_stream_options() {
let provider = create_provider(json!({
"env": { "ANTHROPIC_BASE_URL": "https://openrouter.ai/api/v1" }
}));
// 非流式请求不应注入 stream_optionsusage 在非流式响应体里恒有)。
let body = json!({
"model": "moonshotai/kimi-k2",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 128
});
let transformed =
transform_claude_request_for_api_format(body, &provider, "openai_chat", None, None)
.unwrap();
assert!(transformed.get("stream_options").is_none());
}
#[test]
fn test_transform_claude_request_for_codex_oauth_uses_session_cache_key() {
let provider = create_provider_with_meta(
@@ -1995,6 +2116,64 @@ mod tests {
assert_eq!(content[2]["type"], "tool_use");
}
#[test]
fn test_anthropic_system_role_messages_move_to_top_level_system() {
let provider = create_provider(json!({
"env": {
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
"ANTHROPIC_API_KEY": "test-key"
}
}));
let mut body = json!({
"system": "Existing top-level system.",
"model": "deepseek-v4-pro",
"messages": [
{ "role": "system", "content": "Message system one." },
{ "role": "user", "content": "hello" },
{
"role": "system",
"content": [{ "type": "text", "text": "Message system two." }]
}
]
});
let changed = normalize_anthropic_messages_for_provider(&mut body, &provider, "anthropic");
assert!(changed);
let messages = body["messages"].as_array().unwrap();
assert_eq!(messages.len(), 1);
assert_eq!(messages[0]["role"], "user");
let system = body["system"].as_array().unwrap();
assert_eq!(system[0]["text"], "Existing top-level system.");
assert_eq!(system[1]["text"], "Message system one.");
assert_eq!(system[2]["text"], "Message system two.");
}
#[test]
fn test_anthropic_system_role_messages_skip_non_anthropic_format() {
let provider = create_provider(json!({
"env": {
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/v1",
"ANTHROPIC_API_KEY": "test-key"
}
}));
let mut body = json!({
"model": "deepseek-v4-pro",
"messages": [
{ "role": "system", "content": "Keep in messages." },
{ "role": "user", "content": "hello" }
]
});
let changed =
normalize_anthropic_messages_for_provider(&mut body, &provider, "openai_chat");
assert!(!changed);
assert!(body.get("system").is_none());
assert_eq!(body["messages"][0]["role"], "system");
}
#[test]
fn test_kimi_anthropic_tool_history_injects_missing_thinking() {
let provider = create_provider(json!({
@@ -60,7 +60,7 @@ impl CodexChatHistoryStore {
.map(|items| {
items
.iter()
.filter_map(cached_function_call)
.filter_map(cached_call_item)
.collect::<Vec<_>>()
})
.unwrap_or_default();
@@ -73,8 +73,8 @@ impl CodexChatHistoryStore {
inner.insert_calls(response_id, calls)
}
async fn record_function_call(&self, response_id: Option<&str>, item: &Value) -> bool {
let Some(call) = cached_function_call(item) else {
async fn record_call_item(&self, response_id: Option<&str>, item: &Value) -> bool {
let Some(call) = cached_call_item(item) else {
return false;
};
@@ -110,14 +110,18 @@ impl CodexChatHistoryStore {
let output_call_ids = items
.iter()
.filter(|item| {
item.get("type").and_then(|value| value.as_str()) == Some("function_call_output")
item.get("type")
.and_then(|value| value.as_str())
.is_some_and(is_call_output_item_type)
})
.filter_map(response_item_call_id)
.collect::<HashSet<_>>();
let existing_call_ids = items
.iter()
.filter(|item| {
item.get("type").and_then(|value| value.as_str()) == Some("function_call")
item.get("type")
.and_then(|value| value.as_str())
.is_some_and(is_call_item_type)
})
.filter_map(response_item_call_id)
.collect::<HashSet<_>>();
@@ -143,10 +147,10 @@ impl CodexChatHistoryStore {
for mut item in items {
match item.get("type").and_then(|value| value.as_str()) {
Some("function_call") => {
Some(item_type) if is_call_item_type(item_type) => {
if let Some(call_id) = response_item_call_id(&item) {
if let Some(cached) = lookup.call(&call_id) {
if enrich_function_call_reasoning(&mut item, cached) {
if enrich_call_item_reasoning(&mut item, cached) {
enriched += 1;
}
}
@@ -154,7 +158,7 @@ impl CodexChatHistoryStore {
}
new_items.push(item);
}
Some("function_call_output") => {
Some(item_type) if is_call_output_item_type(item_type) => {
if let Some(group) = restore_group.take().filter(|group| !group.is_empty()) {
for (call_id, cached_item) in group {
seen_call_ids.insert(call_id);
@@ -423,7 +427,7 @@ async fn inspect_sse_block(
Some("response.output_item.done") => {
if let Some(item) = value.get("item") {
history
.record_function_call(current_response_id.as_deref(), item)
.record_call_item(current_response_id.as_deref(), item)
.await;
}
}
@@ -436,15 +440,33 @@ async fn inspect_sse_block(
}
}
fn cached_function_call(item: &Value) -> Option<(String, Value)> {
if item.get("type").and_then(|value| value.as_str()) != Some("function_call") {
fn cached_call_item(item: &Value) -> Option<(String, Value)> {
if !item
.get("type")
.and_then(|value| value.as_str())
.is_some_and(is_call_item_type)
{
return None;
}
let call_id = response_item_call_id(item)?;
Some((call_id, item.clone()))
}
fn enrich_function_call_reasoning(item: &mut Value, cached: &Value) -> bool {
fn is_call_item_type(item_type: &str) -> bool {
matches!(
item_type,
"function_call" | "custom_tool_call" | "tool_search_call"
)
}
fn is_call_output_item_type(item_type: &str) -> bool {
matches!(
item_type,
"function_call_output" | "custom_tool_call_output" | "tool_search_output"
)
}
fn enrich_call_item_reasoning(item: &mut Value, cached: &Value) -> bool {
let mut changed = false;
for key in ["reasoning_content", "reasoning"] {
if item.get(key).is_some_and(|value| !is_empty_value(value)) {
@@ -704,6 +726,58 @@ mod tests {
assert_eq!(input[3]["type"], "function_call_output");
}
#[tokio::test]
async fn restores_custom_and_tool_search_calls_from_previous_response() {
let history = CodexChatHistoryStore::default();
history
.record_response(&json!({
"id": "resp_1",
"output": [
{
"type": "custom_tool_call",
"call_id": "call_patch",
"name": "apply_patch",
"input": "*** Begin Patch\n*** End Patch",
"reasoning_content": "Need to patch the file."
},
{
"type": "tool_search_call",
"call_id": "call_search",
"status": "completed",
"execution": "client",
"arguments": {"query": "Gmail tools"},
"reasoning_content": "Need to discover tools."
}
]
}))
.await;
let mut request = json!({
"previous_response_id": "resp_1",
"input": [
{
"type": "custom_tool_call_output",
"call_id": "call_patch",
"output": "patched"
},
{
"type": "tool_search_output",
"call_id": "call_search",
"tools": []
}
]
});
assert_eq!(history.enrich_request(&mut request).await, 2);
let input = request["input"].as_array().unwrap();
assert_eq!(input[0]["type"], "custom_tool_call");
assert_eq!(input[0]["call_id"], "call_patch");
assert_eq!(input[1]["type"], "tool_search_call");
assert_eq!(input[1]["call_id"], "call_search");
assert_eq!(input[2]["type"], "custom_tool_call_output");
assert_eq!(input[3]["type"], "tool_search_output");
}
#[tokio::test]
async fn records_streamed_function_call_done_items() {
let history = Arc::new(CodexChatHistoryStore::default());
+3 -4
View File
@@ -42,14 +42,13 @@ pub use adapter::ProviderAdapter;
pub use auth::{AuthInfo, AuthStrategy};
pub use claude::{
claude_api_format_needs_transform, get_claude_api_format,
normalize_anthropic_tool_thinking_history_for_provider,
transform_claude_request_for_api_format, ClaudeAdapter,
normalize_anthropic_messages_for_provider, transform_claude_request_for_api_format,
ClaudeAdapter,
};
pub use codex::CodexAdapter;
pub use codex::{
apply_codex_chat_upstream_model, codex_provider_upstream_model,
codex_provider_uses_chat_completions, is_origin_only_url, resolve_codex_chat_reasoning_config,
should_convert_codex_responses_to_chat,
resolve_codex_chat_reasoning_config, should_convert_codex_responses_to_chat,
};
pub use gemini::GeminiAdapter;
+102 -11
View File
@@ -90,25 +90,33 @@ struct ToolBlockState {
started: bool,
pending_args: String,
/// 连续空白字符计数 — 用于检测 Copilot 无限换行 bug
/// 当 function call 参数中出现连续 20+ 空白字符时,强制终止流
/// 当 function call 参数中的连续空白字符达到阈值时,强制终止流
consecutive_whitespace: usize,
/// 是否已因无限空白 bug 被中止
aborted: bool,
}
/// 无限空白 bug 的连续空白字符阈值
const INFINITE_WHITESPACE_THRESHOLD: usize = 20;
const INFINITE_WHITESPACE_THRESHOLD: usize = 500;
fn build_anthropic_usage_json(usage: &Usage) -> Value {
// OpenAI prompt_tokens 含缓存,Anthropic input_tokens 不含,需减去 cache_read 与 cache_creation
// (三桶互斥,恒等 input + cache_read + cache_creation == prompt_tokens)。
let cached = extract_cache_read_tokens(usage).unwrap_or(0);
let cache_creation = usage.cache_creation_input_tokens.unwrap_or(0);
let input_tokens = usage
.prompt_tokens
.saturating_sub(cached)
.saturating_sub(cache_creation);
let mut usage_json = json!({
"input_tokens": usage.prompt_tokens,
"input_tokens": input_tokens,
"output_tokens": usage.completion_tokens
});
if let Some(cached) = extract_cache_read_tokens(usage) {
if cached > 0 {
usage_json["cache_read_input_tokens"] = json!(cached);
}
if let Some(created) = usage.cache_creation_input_tokens {
usage_json["cache_creation_input_tokens"] = json!(created);
if cache_creation > 0 {
usage_json["cache_creation_input_tokens"] = json!(cache_creation);
}
usage_json
}
@@ -223,12 +231,20 @@ pub fn create_anthropic_sse_stream<E: std::error::Error + Send + 'static>(
"output_tokens": 0
});
if let Some(u) = &chunk.usage {
start_usage["input_tokens"] = json!(u.prompt_tokens);
if let Some(cached) = extract_cache_read_tokens(u) {
let cached = extract_cache_read_tokens(u).unwrap_or(0);
let cache_creation =
u.cache_creation_input_tokens.unwrap_or(0);
let input = u
.prompt_tokens
.saturating_sub(cached)
.saturating_sub(cache_creation);
start_usage["input_tokens"] = json!(input);
if cached > 0 {
start_usage["cache_read_input_tokens"] = json!(cached);
}
if let Some(created) = u.cache_creation_input_tokens {
start_usage["cache_creation_input_tokens"] = json!(created);
if cache_creation > 0 {
start_usage["cache_creation_input_tokens"] =
json!(cache_creation);
}
}
@@ -1022,7 +1038,7 @@ mod tests {
message_delta
.pointer("/usage/input_tokens")
.and_then(|v| v.as_u64()),
Some(13312)
Some(13212)
);
assert_eq!(
message_delta
@@ -1038,6 +1054,81 @@ mod tests {
);
}
#[tokio::test]
async fn test_usage_chunk_subtracts_cache_read_and_creation_from_input() {
// prompt_tokens(1000) 含 cache_read(600) 与 cache_creation(300);转 Anthropic 后
// input 应为 fresh,守恒:input(100) + cache_read(600) + cache_creation(300) == prompt(1000)。
let input = concat!(
"data: {\"id\":\"chatcmpl_cc\",\"model\":\"glm-5.1\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"tool-1\",\"type\":\"function\",\"function\":{\"name\":\"Bash\",\"arguments\":\"{\\\"command\\\":\\\"pwd\\\"}\"}}]}}]}\n\n",
"data: {\"id\":\"chatcmpl_cc\",\"model\":\"glm-5.1\",\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
"data: {\"choices\":[],\"usage\":{\"prompt_tokens\":1000,\"completion_tokens\":50,\"prompt_tokens_details\":{\"cached_tokens\":600},\"cache_creation_input_tokens\":300}}\n\n",
"data: [DONE]\n\n"
);
let events = collect_anthropic_events(input).await;
let message_delta = events
.iter()
.find(|event| event_type(event) == Some("message_delta"))
.expect("should emit message_delta with usage");
// fresh input = 1000 - 600 - 300 = 100
assert_eq!(
message_delta
.pointer("/usage/input_tokens")
.and_then(|v| v.as_u64()),
Some(100)
);
assert_eq!(
message_delta
.pointer("/usage/cache_read_input_tokens")
.and_then(|v| v.as_u64()),
Some(600)
);
assert_eq!(
message_delta
.pointer("/usage/cache_creation_input_tokens")
.and_then(|v| v.as_u64()),
Some(300)
);
}
#[tokio::test]
async fn test_usage_chunk_clamps_input_to_zero_when_cache_exceeds_prompt() {
// prompt(100) < cache_read(80)+cache_creation(50)=130saturating 钳到 0,防下溢。
// 钉桩:阻止未来把 saturating_sub 误改成普通减法(debug panic / release wrap)。
let input = concat!(
"data: {\"id\":\"chatcmpl_uf\",\"model\":\"glm-5.1\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"tool-1\",\"type\":\"function\",\"function\":{\"name\":\"Bash\",\"arguments\":\"{\\\"command\\\":\\\"pwd\\\"}\"}}]}}]}\n\n",
"data: {\"id\":\"chatcmpl_uf\",\"model\":\"glm-5.1\",\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
"data: {\"choices\":[],\"usage\":{\"prompt_tokens\":100,\"completion_tokens\":50,\"prompt_tokens_details\":{\"cached_tokens\":80},\"cache_creation_input_tokens\":50}}\n\n",
"data: [DONE]\n\n"
);
let events = collect_anthropic_events(input).await;
let message_delta = events
.iter()
.find(|event| event_type(event) == Some("message_delta"))
.expect("should emit message_delta with usage");
assert_eq!(
message_delta
.pointer("/usage/input_tokens")
.and_then(|v| v.as_u64()),
Some(0)
);
assert_eq!(
message_delta
.pointer("/usage/cache_read_input_tokens")
.and_then(|v| v.as_u64()),
Some(80)
);
assert_eq!(
message_delta
.pointer("/usage/cache_creation_input_tokens")
.and_then(|v| v.as_u64()),
Some(50)
);
}
#[tokio::test]
async fn test_message_delta_includes_zero_usage_when_stream_has_no_usage() {
let input = concat!(
@@ -141,6 +141,7 @@ impl ChatToResponsesState {
if let Some(delta) = choice.get("delta") {
if let Some(reasoning) = chat_delta_reasoning_text(delta) {
events.extend(self.push_reasoning_delta(&reasoning));
self.append_reasoning_to_active_tools(&reasoning);
}
if let Some(content) = delta.get("content").and_then(|v| v.as_str()) {
@@ -522,6 +523,34 @@ impl ChatToResponsesState {
events
}
fn append_reasoning_to_active_tools(&mut self, delta: &str) {
if delta.trim().is_empty() {
return;
}
for state in self.tools.values_mut().filter(|state| !state.done) {
if state.reasoning_content.is_empty() {
state.reasoning_content = delta.trim_start().to_string();
} else {
state.reasoning_content.push_str(delta);
}
}
}
fn has_substantive_output(&self) -> bool {
!self.text.text.trim().is_empty()
|| !self.reasoning.text.trim().is_empty()
|| !self.inline_think.buffer.trim().is_empty()
|| !self.output_items.is_empty()
|| self.tools.values().any(|state| {
state.added
|| !state.call_id.trim().is_empty()
|| !state.name.trim().is_empty()
|| !state.arguments.trim().is_empty()
|| !state.reasoning_content.trim().is_empty()
})
}
fn finalize(&mut self) -> Vec<Bytes> {
if self.completed {
return Vec::new();
@@ -801,7 +830,8 @@ impl ChatToResponsesState {
json!({
"input_tokens": 0,
"output_tokens": 0,
"total_tokens": 0
"total_tokens": 0,
"output_tokens_details": { "reasoning_tokens": 0 }
})
})
})
@@ -948,8 +978,20 @@ pub fn create_responses_sse_stream_from_chat_with_context<E: std::error::Error +
}
if !stream_failed {
for event in state.finalize() {
yield Ok(event);
if state.completed || state.finish_reason.is_some() {
for event in state.finalize() {
yield Ok(event);
}
} else if state.has_substantive_output() {
state.finish_reason = Some("length".to_string());
for event in state.finalize() {
yield Ok(event);
}
} else {
yield Ok(state.failed_event(
"Upstream Chat Completions stream ended before sending finish_reason".to_string(),
Some("stream_truncated".to_string()),
));
}
}
}
@@ -1133,6 +1175,22 @@ mod tests {
assert!(output.contains("\"reasoning_content\":\"Need file.\""));
}
#[tokio::test]
async fn preserves_late_reasoning_content_on_streamed_tool_call_items() {
let output = collect(vec![
"data: {\"id\":\"chatcmpl_tool_late_reasoning\",\"model\":\"deepseek-v4-flash\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"read_file\"}}]}}]}\n\n",
"data: {\"id\":\"chatcmpl_tool_late_reasoning\",\"model\":\"deepseek-v4-flash\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\"path\\\":\\\"README.md\\\"}\"}}]}}]}\n\n",
"data: {\"id\":\"chatcmpl_tool_late_reasoning\",\"model\":\"deepseek-v4-flash\",\"choices\":[{\"delta\":{\"reasoning_content\":\"Need file.\"}}]}\n\n",
"data: {\"id\":\"chatcmpl_tool_late_reasoning\",\"model\":\"deepseek-v4-flash\",\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
"data: [DONE]\n\n",
])
.await;
assert!(output.contains("event: response.output_item.done"));
assert!(output.contains("\"type\":\"function_call\""));
assert!(output.contains("\"reasoning_content\":\"Need file.\""));
}
#[tokio::test]
async fn restores_namespace_on_streamed_tool_call_items() {
let request = json!({
@@ -1208,6 +1266,31 @@ mod tests {
assert!(!output.contains("event: response.completed"));
}
#[tokio::test]
async fn stream_end_with_output_without_finish_reason_emits_incomplete_without_failed() {
let output = collect(vec![
"data: {\"id\":\"chatcmpl_truncated\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n",
])
.await;
assert!(output.contains("event: response.completed"));
assert!(output.contains("\"status\":\"incomplete\""));
assert!(output.contains("\"incomplete_details\":{\"reason\":\"max_output_tokens\"}"));
assert!(!output.contains("event: response.failed"));
}
#[tokio::test]
async fn stream_end_without_output_or_finish_reason_emits_failed_without_completed() {
let output = collect(vec![
"data: {\"id\":\"chatcmpl_truncated\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{}}]}\n\n",
])
.await;
assert!(output.contains("event: response.failed"));
assert!(output.contains("stream_truncated"));
assert!(!output.contains("event: response.completed"));
}
#[tokio::test]
async fn chat_sse_error_event_emits_failed_without_completed() {
let output = collect(vec![
+180 -76
View File
@@ -112,6 +112,10 @@ pub fn resolve_reasoning_effort(body: &Value) -> Option<&'static str> {
}
/// Anthropic 请求 → OpenAI Chat Completions 请求
///
/// 转换工具库 API:当前无生产调用方(连通性检查不再发真实请求,曾是其唯一 crate 内
/// 消费者),但保留其转换逻辑与下方测试套件,供代理转换路径复用 / 未来接线。
#[allow(dead_code)]
pub fn anthropic_to_openai(body: Value) -> Result<Value, ProxyError> {
anthropic_to_openai_with_reasoning_content(body, false)
}
@@ -142,18 +146,13 @@ pub fn anthropic_to_openai_with_reasoning_content(
messages.push(json!({"role": "system", "content": text}));
}
} else if let Some(arr) = system.as_array() {
// 多个 system message — preserve cache_control for compatible proxies
for msg in arr {
if let Some(text) = msg.get("text").and_then(|t| t.as_str()) {
let text = strip_leading_anthropic_billing_header(text);
if text.is_empty() {
continue;
}
let mut sys_msg = json!({"role": "system", "content": text});
if let Some(cc) = msg.get("cache_control") {
sys_msg["cache_control"] = cc.clone();
}
messages.push(sys_msg);
messages.push(json!({"role": "system", "content": text}));
}
}
}
@@ -207,18 +206,14 @@ pub fn anthropic_to_openai_with_reasoning_content(
.iter()
.filter(|t| t.get("type").and_then(|v| v.as_str()) != Some("BatchTool"))
.map(|t| {
let mut tool = json!({
json!({
"type": "function",
"function": {
"name": t.get("name").and_then(|n| n.as_str()).unwrap_or(""),
"description": t.get("description"),
"parameters": clean_schema(t.get("input_schema").cloned().unwrap_or(json!({})))
}
});
if let Some(cc) = t.get("cache_control") {
tool["cache_control"] = cc.clone();
}
tool
})
})
.collect();
@@ -234,6 +229,33 @@ pub fn anthropic_to_openai_with_reasoning_content(
Ok(result)
}
/// 为 OpenAI Chat Completions 流式请求注入 `stream_options.include_usage`。
///
/// OpenAI 兼容上游在流式下默认不在 SSE 里返回 usage,必须显式声明 include_usage
/// 才会在末尾吐 usage chunk。缺这一注入会导致流式请求的 token/成本/缓存全部漏记
/// input/output/cache 全为 0)。保留客户端可能透传的其它 stream_options 字段,
/// 仅补 include_usage;非流式请求不动。
///
/// 由 Claude→openai_chatclaude.rs)与 Codex Responses→Chattransform_codex_chat.rs
/// 两条转换路径共用,确保两个客户端方向行为一致。
pub(crate) fn inject_openai_stream_include_usage(result: &mut Value) {
let is_stream = result
.get("stream")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if !is_stream {
return;
}
match result.get_mut("stream_options") {
Some(Value::Object(opts)) => {
opts.insert("include_usage".to_string(), json!(true));
}
_ => {
result["stream_options"] = json!({ "include_usage": true });
}
}
}
/// Translate an Anthropic `tool_choice` into the OpenAI Chat Completions form.
///
/// Anthropic forms:
@@ -294,10 +316,6 @@ fn normalize_openai_system_messages(messages: &mut Vec<Value>) {
}
let mut parts = Vec::new();
let mut inherited_cache_control: Option<Value> = None;
let mut cache_control_conflict = false;
let mut saw_cache_control = false;
let mut saw_missing_cache_control = false;
messages.retain(|message| {
if message.get("role").and_then(|value| value.as_str()) != Some("system") {
return true;
@@ -318,28 +336,11 @@ fn normalize_openai_system_messages(messages: &mut Vec<Value>) {
_ => {}
}
if let Some(cache_control) = message.get("cache_control") {
saw_cache_control = true;
match &inherited_cache_control {
None => inherited_cache_control = Some(cache_control.clone()),
Some(existing) if existing == cache_control => {}
Some(_) => cache_control_conflict = true,
}
} else {
saw_missing_cache_control = true;
}
false
});
if !parts.is_empty() {
let mut merged = json!({"role": "system", "content": parts.join("\n")});
if !(cache_control_conflict || (saw_cache_control && saw_missing_cache_control)) {
if let Some(cache_control) = inherited_cache_control {
merged["cache_control"] = cache_control;
}
}
messages.insert(0, merged);
messages.insert(0, json!({"role": "system", "content": parts.join("\n")}));
}
}
@@ -379,11 +380,7 @@ fn convert_message_to_openai(
match block_type {
"text" => {
if let Some(text) = block.get("text").and_then(|t| t.as_str()) {
let mut part = json!({"type": "text", "text": text});
if let Some(cc) = block.get("cache_control") {
part["cache_control"] = cc.clone();
}
content_parts.push(part);
content_parts.push(json!({"type": "text", "text": text}));
}
}
"image" => {
@@ -458,14 +455,9 @@ fn convert_message_to_openai(
if content_parts.is_empty() {
msg["content"] = Value::Null;
} else if content_parts.len() == 1 {
// When cache_control is present, keep array format to preserve it
let has_cache_control = content_parts[0].get("cache_control").is_some();
if !has_cache_control {
if let Some(text) = content_parts[0].get("text") {
msg["content"] = text.clone();
} else {
msg["content"] = json!(content_parts);
}
// 单 text block 简化为纯字符串
if let Some(text) = content_parts[0].get("text") {
msg["content"] = text.clone();
} else {
msg["content"] = json!(content_parts);
}
@@ -656,10 +648,31 @@ pub fn openai_to_anthropic(body: Value) -> Result<Value, ProxyError> {
// usage — map cache tokens from OpenAI format to Anthropic format
let usage = body.get("usage").cloned().unwrap_or(json!({}));
// OpenAI prompt_tokens 含缓存命中,Anthropic input_tokens 不含 → 减去 cache_read 与
// cache_creation,使 input 成为 fresh input。本路径以 app_type="claude" 记账(calculator
// 不再扣减),若不减则缓存会被计入 input 与各 cache 桶两次。三桶互斥,恒等:
// input + cache_read + cache_creation == prompt_tokensinclusive 上游)。
// 与流式 build_anthropic_usage_json (#2774) 及 transform_gemini 的 saturating_sub 对称。
// 最终 cache_read:直传字段优先于 nestedcache_creation 仅来自直传字段(OpenAI 无此概念)。
let cached = usage
.get("cache_read_input_tokens")
.and_then(|v| v.as_u64())
.or_else(|| {
usage
.pointer("/prompt_tokens_details/cached_tokens")
.and_then(|v| v.as_u64())
})
.unwrap_or(0);
let cache_creation = usage
.get("cache_creation_input_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(0);
let input_tokens = usage
.get("prompt_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(0) as u32;
.unwrap_or(0)
.saturating_sub(cached)
.saturating_sub(cache_creation) as u32;
let output_tokens = usage
.get("completion_tokens")
.and_then(|v| v.as_u64())
@@ -670,19 +683,11 @@ pub fn openai_to_anthropic(body: Value) -> Result<Value, ProxyError> {
"output_tokens": output_tokens
});
// OpenAI standard: prompt_tokens_details.cached_tokens
if let Some(cached) = usage
.pointer("/prompt_tokens_details/cached_tokens")
.and_then(|v| v.as_u64())
{
if cached > 0 {
usage_json["cache_read_input_tokens"] = json!(cached);
}
// Some compatible servers return these fields directly
if let Some(v) = usage.get("cache_read_input_tokens") {
usage_json["cache_read_input_tokens"] = v.clone();
}
if let Some(v) = usage.get("cache_creation_input_tokens") {
usage_json["cache_creation_input_tokens"] = v.clone();
if cache_creation > 0 {
usage_json["cache_creation_input_tokens"] = json!(cache_creation);
}
let result = json!({
@@ -829,7 +834,7 @@ mod tests {
}
#[test]
fn test_anthropic_to_openai_preserves_matching_system_cache_control_when_merging() {
fn test_anthropic_to_openai_strips_cache_control_from_merged_system() {
let input = json!({
"model": "claude-3-sonnet",
"max_tokens": 1024,
@@ -847,12 +852,12 @@ mod tests {
result["messages"][0]["content"],
"You are Claude Code.\nBe concise."
);
assert_eq!(result["messages"][0]["cache_control"]["type"], "ephemeral");
assert!(result["messages"][0].get("cache_control").is_none());
assert_eq!(result["messages"][1]["role"], "user");
}
#[test]
fn test_anthropic_to_openai_drops_mixed_present_absent_system_cache_control_when_merging() {
fn test_anthropic_to_openai_strips_cache_control_from_mixed_system() {
let input = json!({
"model": "claude-3-sonnet",
"max_tokens": 1024,
@@ -873,7 +878,7 @@ mod tests {
}
#[test]
fn test_anthropic_to_openai_drops_conflicting_system_cache_control_when_merging() {
fn test_anthropic_to_openai_strips_cache_control_from_conflicting_system() {
let input = json!({
"model": "claude-3-sonnet",
"max_tokens": 1024,
@@ -1199,7 +1204,7 @@ mod tests {
}
#[test]
fn test_anthropic_to_openai_cache_control_preserved() {
fn test_anthropic_to_openai_strips_all_cache_control() {
let input = json!({
"model": "claude-3-opus",
"max_tokens": 1024,
@@ -1221,19 +1226,89 @@ mod tests {
});
let result = anthropic_to_openai(input).unwrap();
// System message cache_control preserved
assert_eq!(result["messages"][0]["cache_control"]["type"], "ephemeral");
// Text block cache_control preserved
assert_eq!(
result["messages"][1]["content"][0]["cache_control"]["type"],
"ephemeral"
// System message: no cache_control
assert!(result["messages"][0].get("cache_control").is_none());
// User message: content simplified to string (no cache_control → flat string)
assert_eq!(result["messages"][1]["content"], "Hello");
// Tool: no cache_control
assert!(result["tools"][0].get("cache_control").is_none());
}
/// 精确复现 Issue #3805 报告的 400 错误场景:
/// GLM/Qwen 等严格校验模型拒绝 cache_control 和 content 数组格式
#[test]
fn test_regression_gh3805_no_cache_control_leak_to_openai() {
let input = json!({
"model": "glm-5.1",
"max_tokens": 1024,
"system": [
{"type": "text", "text": "You are helpful.", "cache_control": {"type": "ephemeral"}}
],
"messages": [
{"role": "user", "content": [
{"type": "text", "text": "Hello", "cache_control": {"type": "ephemeral"}}
]}
],
"tools": [{
"name": "search",
"description": "Search the web",
"input_schema": {"type": "object"},
"cache_control": {"type": "ephemeral"}
}]
});
let result = anthropic_to_openai(input).unwrap();
// 验证: messages 中不存在 cache_control
for (i, msg) in result["messages"].as_array().unwrap().iter().enumerate() {
assert!(
msg.get("cache_control").is_none(),
"messages[{i}] must not have cache_control"
);
}
// 验证: content 中没有 cache_control
for (i, msg) in result["messages"].as_array().unwrap().iter().enumerate() {
if let Some(content) = msg.get("content") {
assert!(
!content.is_array()
|| content
.as_array()
.unwrap()
.iter()
.all(|part| part.get("cache_control").is_none()),
"messages[{i}] content parts must not have cache_control"
);
}
}
// 验证: system content 为纯字符串格式(不是数组)
let sys_msg = &result["messages"][0];
assert_eq!(sys_msg["role"], "system");
assert!(
sys_msg["content"].is_string(),
"system content must be string, got: {}",
sys_msg["content"]
);
assert_eq!(
result["messages"][1]["content"][0]["cache_control"]["ttl"],
"5m"
// 验证: user content 为纯字符串格式(不是数组)
let user_msg = &result["messages"][1];
assert_eq!(user_msg["role"], "user");
assert!(
user_msg["content"].is_string(),
"user content must be string, got: {}",
user_msg["content"]
);
// Tool cache_control preserved
assert_eq!(result["tools"][0]["cache_control"]["type"], "ephemeral");
// 验证: tools 中不存在 cache_control
if let Some(tools) = result["tools"].as_array() {
for (i, tool) in tools.iter().enumerate() {
assert!(
tool.get("cache_control").is_none(),
"tools[{i}] must not have cache_control"
);
}
}
}
#[test]
@@ -1256,7 +1331,8 @@ mod tests {
});
let result = openai_to_anthropic(input).unwrap();
assert_eq!(result["usage"]["input_tokens"], 100);
// prompt_tokens(100) 含 cached(80),转换后 input 应为 fresh = 100 - 80 = 20
assert_eq!(result["usage"]["input_tokens"], 20);
assert_eq!(result["usage"]["output_tokens"], 50);
assert_eq!(result["usage"]["cache_read_input_tokens"], 80);
}
@@ -1280,10 +1356,38 @@ mod tests {
});
let result = openai_to_anthropic(input).unwrap();
// cache_read(60)+cache_creation(20) 均从 prompt(100) 扣除,fresh = 100 - 60 - 20 = 20
// 守恒:input(20) + cache_read(60) + cache_creation(20) == prompt(100)
assert_eq!(result["usage"]["input_tokens"], 20);
assert_eq!(result["usage"]["cache_read_input_tokens"], 60);
assert_eq!(result["usage"]["cache_creation_input_tokens"], 20);
}
#[test]
fn test_openai_to_anthropic_clamps_input_when_cache_exceeds_prompt() {
// prompt(100) < cache_read(60)+cache_creation(50)=110saturating 钳到 0,防下溢。
// 钉桩:阻止未来把 saturating_sub 误改成普通减法(debug panic / release wrap)。
let input = json!({
"id": "chatcmpl-uf",
"model": "gpt-4",
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": "x"},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 100,
"completion_tokens": 10,
"cache_read_input_tokens": 60,
"cache_creation_input_tokens": 50
}
});
let result = openai_to_anthropic(input).unwrap();
assert_eq!(result["usage"]["input_tokens"], 0);
assert_eq!(result["usage"]["cache_read_input_tokens"], 60);
assert_eq!(result["usage"]["cache_creation_input_tokens"], 50);
}
#[test]
fn test_openai_to_anthropic_finish_reason_content_filter_maps_end_turn() {
let input = json!({
@@ -40,6 +40,8 @@ const EXTRA_CHAT_PASSTHROUGH_FIELDS: &[&str] = &[
const TOOL_SEARCH_PROXY_NAME: &str = "tool_search";
const CUSTOM_TOOL_INPUT_FIELD: &str = "input";
const CHAT_TOOL_NAME_MAX_LEN: usize = 64;
const CUSTOM_TOOL_INPUT_DESCRIPTION: &str = "Raw string input for the original custom tool. Preserve formatting exactly and follow the original tool definition embedded in the description.";
const CUSTOM_TOOL_PRESERVED_METADATA_HEADING: &str = "Original tool definition:";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CodexToolKind {
@@ -132,10 +134,7 @@ impl CodexToolContext {
let Some(name) = responses_tool_name(tool) else {
return;
};
let description = tool
.get("description")
.cloned()
.unwrap_or_else(|| json!("Custom Codex tool."));
let description = json!(responses_custom_tool_description(tool));
let chat_tool = json!({
"type": "function",
"function": {
@@ -146,7 +145,7 @@ impl CodexToolContext {
"properties": {
CUSTOM_TOOL_INPUT_FIELD: {
"type": "string",
"description": "Input to pass to the custom Codex tool."
"description": CUSTOM_TOOL_INPUT_DESCRIPTION
}
},
"required": [CUSTOM_TOOL_INPUT_FIELD]
@@ -320,25 +319,25 @@ pub fn responses_to_chat_completions_with_reasoning(
}
}
// Strict OpenAI-compatible upstreams (vLLM, enterprise gateways) reject
// requests that carry tool_choice or parallel_tool_calls without a non-empty
// tools array. Drop both fields when tools ended up absent or empty after
// conversion to avoid 503/400 from such providers.
let has_tools = result
.get("tools")
.is_some_and(|v| v.as_array().is_some_and(|a| !a.is_empty()));
if !has_tools {
if let Some(obj) = result.as_object_mut() {
obj.remove("tool_choice");
obj.remove("parallel_tool_calls");
}
}
// OpenAI 兼容上游在流式下默认不在 SSE 里返回 usage,必须显式声明
// include_usage 才会在末尾吐 usage chunk。Codex CLI 用 Responses 协议、
// 自身不带 stream_options,缺这一注入会导致 kimi/MiniMax 等第三方流式请求的
// token/成本/缓存命中率全部漏记(input/output/cache 全为 0)。
let is_stream = result
.get("stream")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if is_stream {
match result.get_mut("stream_options") {
// 保留客户端可能透传的其它 stream_options 字段,仅补 include_usage。
Some(Value::Object(opts)) => {
opts.insert("include_usage".to_string(), json!(true));
}
_ => {
result["stream_options"] = json!({ "include_usage": true });
}
}
}
// 与 Claude→openai_chat 路径共用同一 helper,保证两个客户端方向一致。
super::transform::inject_openai_stream_include_usage(&mut result);
Ok(result)
}
@@ -654,6 +653,34 @@ fn append_responses_item_as_chat_message(
append_pending_reasoning(pending_reasoning, reasoning);
}
}
Some("input_text" | "input_image" | "input_file" | "input_audio") => {
flush_pending_tool_calls(
messages,
pending_tool_calls,
pending_reasoning,
last_assistant_index,
);
let role = item
.get("role")
.and_then(|v| v.as_str())
.map(responses_role_to_chat_role)
.unwrap_or("user");
let message = json!({
"role": role,
"content": responses_content_to_chat_content(role, &Value::Array(vec![item.clone()]))
});
if role == "assistant" {
let mut message = message;
attach_pending_reasoning_to_assistant(&mut message, pending_reasoning);
update_last_assistant_index(messages, &message, last_assistant_index);
messages.push(message);
return Ok(());
} else if pending_reasoning.is_some() {
pending_reasoning.take();
}
update_last_assistant_index(messages, &message, last_assistant_index);
messages.push(message);
}
Some("message") | None => {
flush_pending_tool_calls(
messages,
@@ -947,6 +974,24 @@ fn responses_content_to_chat_content(_role: &str, content: &Value) -> Value {
has_non_text_part = true;
}
}
"input_file" => {
if let Some(file) = responses_input_file_to_chat_file(part) {
chat_parts.push(json!({
"type": "file",
"file": file
}));
has_non_text_part = true;
}
}
"input_audio" => {
if let Some(input_audio) = part.get("input_audio") {
chat_parts.push(json!({
"type": "input_audio",
"input_audio": input_audio.clone()
}));
has_non_text_part = true;
}
}
_ => {}
}
}
@@ -964,6 +1009,21 @@ fn responses_content_to_chat_content(_role: &str, content: &Value) -> Value {
Value::Array(chat_parts)
}
fn responses_input_file_to_chat_file(part: &Value) -> Option<Value> {
let mut file = serde_json::Map::new();
let has_supported_file_ref = part.get("file_id").is_some() || part.get("file_data").is_some();
if !has_supported_file_ref {
return None;
}
for key in ["file_id", "file_data", "filename"] {
if let Some(value) = part.get(key) {
file.insert(key.to_string(), value.clone());
}
}
Some(Value::Object(file))
}
fn collect_tool_search_output_tools(value: &Value, context: &mut CodexToolContext) {
match value {
Value::Array(items) => {
@@ -1016,6 +1076,22 @@ fn responses_tool_name(tool: &Value) -> Option<String> {
.map(ToString::to_string)
}
fn responses_custom_tool_description(tool: &Value) -> String {
let mut description = String::new();
description.push_str(CUSTOM_TOOL_PRESERVED_METADATA_HEADING);
description.push_str("\n```json\n");
description.push_str(&serialize_tool_definition_for_description(tool));
description.push_str("\n```");
description
}
fn serialize_tool_definition_for_description(tool: &Value) -> String {
// Keep the embedded definition compact to reduce tool-description token
// overhead for chat-only upstreams, while remaining stable across map
// storage order.
canonical_json_string(tool)
}
fn responses_function_tool_to_chat_tool(tool: &Value, chat_name: &str) -> Option<Value> {
if tool.get("type").and_then(|v| v.as_str()) != Some("function") {
return None;
@@ -1507,7 +1583,8 @@ pub(crate) fn chat_usage_to_responses_usage(usage: Option<&Value>) -> Value {
return json!({
"input_tokens": 0,
"output_tokens": 0,
"total_tokens": 0
"total_tokens": 0,
"output_tokens_details": { "reasoning_tokens": 0 }
});
};
@@ -1540,8 +1617,17 @@ pub(crate) fn chat_usage_to_responses_usage(usage: Option<&Value>) -> Value {
result["input_tokens_details"] = json!({ "cached_tokens": cached });
}
if let Some(details) = usage.get("completion_tokens_details") {
result["output_tokens_details"] = details.clone();
if let Some(details) = usage
.get("completion_tokens_details")
.filter(|v| v.is_object())
{
let mut details = details.clone();
if details.get("reasoning_tokens").is_none() {
details["reasoning_tokens"] = json!(0);
}
result["output_tokens_details"] = details;
} else {
result["output_tokens_details"] = json!({ "reasoning_tokens": 0 });
}
if let Some(cache_read) = usage.get("cache_read_input_tokens") {
@@ -1690,6 +1776,122 @@ mod tests {
assert_eq!(result["stream_options"]["continuous_usage_stats"], true);
}
#[test]
fn responses_request_maps_input_file_content_parts() {
let input = json!({
"model": "gpt-5.4",
"input": [{
"role": "user",
"content": [
{"type": "input_text", "text": "Summarize this."},
{
"type": "input_file",
"file_id": "file_123",
"file_url": "https://example.com/spec.pdf",
"filename": "spec.pdf"
},
{
"type": "input_audio",
"input_audio": {
"data": "UklGRg==",
"format": "wav"
}
}
]
}]
});
let result = responses_to_chat_completions(input).unwrap();
let content = result["messages"][0]["content"].as_array().unwrap();
assert_eq!(content[0]["type"], "text");
assert_eq!(content[1]["type"], "file");
assert_eq!(content[1]["file"]["file_id"], "file_123");
assert!(content[1]["file"].get("file_url").is_none());
assert_eq!(content[1]["file"]["filename"], "spec.pdf");
assert_eq!(content[2]["type"], "input_audio");
assert_eq!(content[2]["input_audio"]["format"], "wav");
}
#[test]
fn responses_request_does_not_emit_chat_file_for_url_only_input_file() {
let input = json!({
"model": "gpt-5.4",
"input": [{
"role": "user",
"content": [
{"type": "input_text", "text": "Summarize this URL file."},
{
"type": "input_file",
"file_url": "https://example.com/spec.pdf"
}
]
}]
});
let result = responses_to_chat_completions(input).unwrap();
assert_eq!(result["messages"][0]["content"], "Summarize this URL file.");
}
#[test]
fn responses_request_maps_top_level_input_file_item() {
let input = json!({
"model": "gpt-5.4",
"input": [
{
"type": "input_file",
"file_id": "file_top",
"filename": "top.pdf"
}
]
});
let result = responses_to_chat_completions(input).unwrap();
let content = result["messages"][0]["content"].as_array().unwrap();
assert_eq!(result["messages"][0]["role"], "user");
assert_eq!(content[0]["type"], "file");
assert_eq!(content[0]["file"]["file_id"], "file_top");
assert_eq!(content[0]["file"]["filename"], "top.pdf");
}
#[test]
fn top_level_user_content_part_clears_pending_reasoning() {
let input = json!({
"model": "gpt-5.4",
"input": [
{
"type": "reasoning",
"summary": [{"text": "stale reasoning"}]
},
{
"type": "input_text",
"text": "Please run the tool."
},
{
"type": "function_call",
"call_id": "call_1",
"name": "lookup",
"arguments": "{}"
}
],
"tools": [{
"type": "function",
"name": "lookup",
"parameters": {"type": "object"}
}]
});
let result = responses_to_chat_completions(input).unwrap();
let messages = result["messages"].as_array().unwrap();
assert_eq!(messages[0]["role"], "user");
assert_eq!(messages[0]["content"], "Please run the tool.");
assert_eq!(messages[1]["role"], "assistant");
assert_eq!(messages[1]["reasoning_content"], "tool call");
}
#[test]
fn responses_request_to_chat_maps_messages_tools_and_limits() {
let input = json!({
@@ -1847,6 +2049,34 @@ mod tests {
);
}
#[test]
fn responses_request_to_chat_preserves_custom_tool_metadata_in_description() {
let input = json!({
"model": "gpt-5.4",
"tools": [{
"type": "custom",
"name": "apply_patch",
"description": "Use the `apply_patch` tool to edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.",
"format": {
"type": "grammar",
"syntax": "lark",
"definition": "start: begin_patch hunk+ end_patch"
}
}]
});
let result = responses_to_chat_completions(input).unwrap();
let description = result["tools"][0]["function"]["description"]
.as_str()
.unwrap();
assert!(description.starts_with("Original tool definition:"));
assert!(!description.contains("Original Codex tool definition"));
assert!(description.contains("\"type\":\"custom\""));
assert!(description.contains("\"format\":"));
assert!(description.contains("\"syntax\":\"lark\""));
}
#[test]
fn responses_request_to_chat_uses_provider_reasoning_effort_for_deepseek_model() {
let input = json!({
@@ -2815,4 +3045,238 @@ mod tests {
assert_eq!(result["error"]["message"], "rate limit exceeded");
assert_eq!(result["error"]["type"], "upstream_error");
}
// Regression tests for tool_choice without tools guard
// https://github.com/farion1231/cc-switch/issues/3557
#[test]
fn responses_request_to_chat_drops_tool_choice_when_no_tools() {
// When tools is absent from the request, tool_choice must be dropped
// to avoid 503/400 from strict OpenAI-compatible upstreams.
let input = json!({
"model": "qwen3-7-max",
"tool_choice": "auto",
"input": "hi"
});
let result = responses_to_chat_completions(input).unwrap();
assert!(
result.get("tool_choice").is_none(),
"tool_choice should be dropped when tools is absent"
);
assert!(result.get("tools").is_none(), "tools should be absent");
assert_eq!(result["model"], "qwen3-7-max");
}
#[test]
fn responses_request_to_chat_drops_tool_choice_when_tools_empty_array() {
// When tools is an empty array, tool_choice must be dropped.
let input = json!({
"model": "gpt-5.4",
"tools": [],
"tool_choice": "auto",
"input": "hi"
});
let result = responses_to_chat_completions(input).unwrap();
assert!(
result.get("tool_choice").is_none(),
"tool_choice should be dropped when tools is empty"
);
assert!(
result.get("tools").is_none(),
"tools should be absent when input tools was empty"
);
}
#[test]
fn responses_request_to_chat_drops_parallel_tool_calls_when_no_tools() {
// parallel_tool_calls must also be dropped when tools is absent,
// as it is part of EXTRA_CHAT_PASSTHROUGH_FIELDS.
let input = json!({
"model": "gpt-5.4",
"tool_choice": "auto",
"parallel_tool_calls": true,
"input": "hi"
});
let result = responses_to_chat_completions(input).unwrap();
assert!(
result.get("tool_choice").is_none(),
"tool_choice should be dropped"
);
assert!(
result.get("parallel_tool_calls").is_none(),
"parallel_tool_calls should be dropped"
);
assert!(result.get("tools").is_none(), "tools should be absent");
}
#[test]
fn responses_request_to_chat_drops_tool_choice_when_all_tools_filtered() {
// When all tools are filtered out (e.g., missing name), tool_choice must be dropped.
let input = json!({
"model": "gpt-5.4",
"tools": [
{"type": "function"}
],
"tool_choice": "auto",
"input": "hi"
});
let result = responses_to_chat_completions(input).unwrap();
assert!(
result.get("tool_choice").is_none(),
"tool_choice should be dropped when all tools filtered"
);
assert!(
result.get("tools").is_none(),
"tools should be absent when all filtered"
);
}
#[test]
fn responses_request_to_chat_keeps_tool_choice_when_tools_present() {
// When tools is present and non-empty, tool_choice must be preserved.
let input = json!({
"model": "gpt-5.4",
"tools": [{
"type": "function",
"name": "get_weather",
"description": "Get weather",
"parameters": {"type": "object"}
}],
"tool_choice": "auto",
"parallel_tool_calls": true,
"input": "hi"
});
let result = responses_to_chat_completions(input).unwrap();
assert!(
result.get("tool_choice").is_some(),
"tool_choice should be kept when tools present"
);
assert_eq!(result["tool_choice"], "auto");
assert!(
result.get("parallel_tool_calls").is_some(),
"parallel_tool_calls should be kept"
);
assert_eq!(result["parallel_tool_calls"], true);
assert!(
result
.get("tools")
.is_some_and(|v| v.as_array().is_some_and(|a| !a.is_empty())),
"tools should be present"
);
assert_eq!(result["tools"][0]["function"]["name"], "get_weather");
}
#[test]
fn responses_request_to_chat_keeps_tool_choice_function_when_tools_present() {
// When tools is present, function-type tool_choice must be preserved and mapped.
let input = json!({
"model": "gpt-5.4",
"tools": [{
"type": "function",
"name": "get_weather",
"description": "Get weather",
"parameters": {"type": "object"}
}],
"tool_choice": {"type": "function", "name": "get_weather"},
"input": "hi"
});
let result = responses_to_chat_completions(input).unwrap();
assert!(
result.get("tool_choice").is_some(),
"tool_choice should be kept"
);
assert_eq!(result["tool_choice"]["type"], "function");
assert_eq!(result["tool_choice"]["function"]["name"], "get_weather");
}
#[test]
fn responses_request_to_chat_no_tool_choice_no_tools_stays_clean() {
// When neither tool_choice nor tools are present, the output should be clean.
let input = json!({
"model": "gpt-5.4",
"input": "hi"
});
let result = responses_to_chat_completions(input).unwrap();
assert!(
result.get("tool_choice").is_none(),
"tool_choice should be absent"
);
assert!(result.get("tools").is_none(), "tools should be absent");
assert!(
result.get("parallel_tool_calls").is_none(),
"parallel_tool_calls should be absent"
);
}
#[test]
fn responses_request_to_chat_tool_choice_none_dropped_when_no_tools() {
// Even tool_choice: "none" should be dropped when tools is absent,
// because strict upstreams reject the combination regardless of value.
let input = json!({
"model": "gpt-5.4",
"tool_choice": "none",
"input": "hi"
});
let result = responses_to_chat_completions(input).unwrap();
assert!(
result.get("tool_choice").is_none(),
"tool_choice 'none' should be dropped when no tools"
);
}
#[test]
fn responses_request_to_chat_tool_search_output_provides_tools_keeps_tool_choice() {
// When tool_search_output in input provides tools, tool_choice should be kept.
let input = json!({
"model": "gpt-5.4",
"tool_choice": "auto",
"input": [{
"type": "tool_search_output",
"call_id": "call_ts_1",
"status": "completed",
"execution": "client",
"tools": [{
"type": "function",
"name": "search_docs",
"description": "Search documentation.",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"}
}
}
}]
}]
});
let result = responses_to_chat_completions(input).unwrap();
assert!(
result.get("tool_choice").is_some(),
"tool_choice should be kept when tool_search_output provides tools"
);
assert_eq!(result["tool_choice"], "auto");
assert!(
result
.get("tools")
.is_some_and(|v| v.as_array().is_some_and(|a| !a.is_empty())),
"tools should be present from tool_search_output"
);
assert_eq!(result["tools"][0]["function"]["name"], "search_docs");
}
}
@@ -39,6 +39,11 @@ pub(crate) fn is_synthesized_tool_call_id(id: &str) -> bool {
id.starts_with(SYNTHESIZED_ID_PREFIX)
}
/// Anthropic 请求 → Gemini 原生请求。
///
/// 转换工具库 API:当前无生产调用方(连通性检查不再发真实请求,曾是其唯一 crate 内
/// 消费者),但保留其转换逻辑与下方测试套件,供代理转换路径复用 / 未来接线。
#[allow(dead_code)]
pub fn anthropic_to_gemini(body: Value) -> Result<Value, ProxyError> {
anthropic_to_gemini_with_shadow(body, None, None, None)
}
@@ -1101,7 +1106,7 @@ pub(crate) fn build_anthropic_usage(usage: Option<&Value>) -> Value {
});
};
let input_tokens = usage
let prompt_tokens = usage
.get("promptTokenCount")
.and_then(|value| value.as_u64())
.unwrap_or(0);
@@ -1109,18 +1114,26 @@ pub(crate) fn build_anthropic_usage(usage: Option<&Value>) -> Value {
.get("totalTokenCount")
.and_then(|value| value.as_u64())
.unwrap_or(0);
let output_tokens = total_tokens.saturating_sub(input_tokens);
let cached_tokens = usage
.get("cachedContentTokenCount")
.and_then(|value| value.as_u64())
.unwrap_or(0);
// Gemini 的 promptTokenCount 含缓存命中(cachedContentTokenCount);而 Anthropic
// 语义下 input_tokens 必须是不含 cache 的 fresh input、cache_read 单列。本路径转成
// Anthropic 后以 app_type=claude 记账,calculator 对 claude 设 input_includes_cache_read
// =false 不再从 input 扣 cache,因此这里必须先扣减,否则缓存 token 会被双重计费
// (一次按完整 input 价、一次按 cache_read 价)。output 仍按 total-prompt 计算
// (prompt 是总输入,扣减只作用于 input/cache 的拆分,不影响 output)。
let input_tokens = prompt_tokens.saturating_sub(cached_tokens);
let output_tokens = total_tokens.saturating_sub(prompt_tokens);
let mut result = json!({
"input_tokens": input_tokens,
"output_tokens": output_tokens
});
if let Some(cached) = usage
.get("cachedContentTokenCount")
.and_then(|value| value.as_u64())
{
result["cache_read_input_tokens"] = json!(cached);
if cached_tokens > 0 {
result["cache_read_input_tokens"] = json!(cached_tokens);
}
result
@@ -1370,7 +1383,11 @@ mod tests {
assert_eq!(result["content"][0]["type"], "text");
assert_eq!(result["content"][0]["text"], "Hello from Gemini");
assert_eq!(result["stop_reason"], "end_turn");
assert_eq!(result["usage"]["input_tokens"], 12);
// input_tokens = promptTokenCount(12) - cachedContentTokenCount(3) = 9fresh input)。
// Gemini 的 promptTokenCount 含缓存命中,但 Anthropic 语义要求 input 不含 cache、
// cache_read 单列;二者相加(9+3)=总输入 12。扣减避免本路径以 app_type=claude
// 记账时把缓存 token 双重计费。
assert_eq!(result["usage"]["input_tokens"], 9);
assert_eq!(result["usage"]["output_tokens"], 8);
assert_eq!(result["usage"]["cache_read_input_tokens"], 3);
}
@@ -355,6 +355,23 @@ pub(crate) fn build_anthropic_usage_from_responses(usage: Option<&Value>) -> Val
result["cache_creation_input_tokens"] = v.clone();
}
// OpenAI/Responses 的 input(prompt_tokens/input_tokens)含缓存命中,Anthropic input_tokens 不含
// → 减去 cache_read 与 cache_creation,使其成为 fresh input。本函数在计量意义上是 claude 专属
// Codex Responses 透传走 from_codex_response_*,不调用本函数),故可安全在此扣减。三桶互斥,
// 恒等:input + cache_read + cache_creation == 上游 input(inclusive)。与 build_anthropic_usage_json
// (#2774) 及 transform_gemini 的 saturating_sub 对称;一处同时覆盖非流式与流式(streaming_responses)。
let cached = result
.get("cache_read_input_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(0);
let cache_creation = result
.get("cache_creation_input_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(0);
if cached > 0 || cache_creation > 0 {
result["input_tokens"] = json!(input.saturating_sub(cached).saturating_sub(cache_creation));
}
result
}
@@ -1156,7 +1173,8 @@ mod tests {
});
let result = responses_to_anthropic(input).unwrap();
assert_eq!(result["usage"]["input_tokens"], 100);
// input_tokens(100) 含 cached(80),转换后 input 应为 fresh = 100 - 80 = 20
assert_eq!(result["usage"]["input_tokens"], 20);
assert_eq!(result["usage"]["output_tokens"], 50);
assert_eq!(result["usage"]["cache_read_input_tokens"], 80);
}
@@ -1180,6 +1198,9 @@ mod tests {
});
let result = responses_to_anthropic(input).unwrap();
// cache_read(60)+cache_creation(20) 均从 input(100) 扣除,fresh = 100 - 60 - 20 = 20
// 守恒:input(20) + cache_read(60) + cache_creation(20) == 上游 input(100)
assert_eq!(result["usage"]["input_tokens"], 20);
assert_eq!(result["usage"]["cache_read_input_tokens"], 60);
assert_eq!(result["usage"]["cache_creation_input_tokens"], 20);
}
@@ -1642,7 +1663,8 @@ mod tests {
"cached_tokens": 80
}
})));
assert_eq!(result["input_tokens"], json!(100));
// input_tokens(100) 含 nested cached(80),转换后 input 应为 fresh = 100 - 80 = 20
assert_eq!(result["input_tokens"], json!(20));
assert_eq!(result["output_tokens"], json!(50));
assert_eq!(result["cache_read_input_tokens"], json!(80));
}
@@ -1657,9 +1679,26 @@ mod tests {
},
"cache_read_input_tokens": 100
})));
// 直传 cache_read(100) 优先于 nested(80)input(100) - 100 = 0fresh
assert_eq!(result["input_tokens"], json!(0));
assert_eq!(result["cache_read_input_tokens"], json!(100)); // Direct field overrides nested
}
#[test]
fn test_build_usage_clamps_input_when_cache_exceeds_input() {
// input(100) < cache_read(60)+cache_creation(50)=110saturating 钳到 0,防下溢。
// 钉桩:阻止未来把 saturating_sub 误改成普通减法(debug panic / release wrap)。
let result = build_anthropic_usage_from_responses(Some(&json!({
"input_tokens": 100,
"output_tokens": 10,
"cache_read_input_tokens": 60,
"cache_creation_input_tokens": 50
})));
assert_eq!(result["input_tokens"], json!(0));
assert_eq!(result["cache_read_input_tokens"], json!(60));
assert_eq!(result["cache_creation_input_tokens"], json!(50));
}
#[test]
fn test_build_usage_cache_tokens_without_input_output() {
let result = build_anthropic_usage_from_responses(Some(&json!({
+198 -23
View File
@@ -35,28 +35,41 @@ use tokio::sync::Mutex;
/// 根据 content-encoding 解压响应体字节
///
/// reqwest 自动解压已禁用(为了透传 accept-encoding),需要手动解压。
fn decompress_body(content_encoding: &str, body: &[u8]) -> Result<Vec<u8>, std::io::Error> {
/// 返回 `Ok(None)` 表示编码不受支持、原样透传——此时调用方必须保留
/// content-encoding 头,否则下游(诊断/客户端)会把压缩字节误当明文。
fn decompress_body(content_encoding: &str, body: &[u8]) -> Result<Option<Vec<u8>>, std::io::Error> {
match content_encoding {
"gzip" | "x-gzip" => {
let mut decoder = flate2::read::GzDecoder::new(body);
let mut decompressed = Vec::new();
decoder.read_to_end(&mut decompressed)?;
Ok(decompressed)
Ok(Some(decompressed))
}
"deflate" => {
let mut decoder = flate2::read::DeflateDecoder::new(body);
// RFC 9110: deflate 指 zlib 包裹格式;但部分上游发 raw deflate 流。
// 先按规范尝试 zlib,失败再回退 raw —— 否则合规上游必然解压失败,
// 原始压缩字节会被 fail-open 透传给 JSON 解析(#2234 形态 C 之一)。
let mut decompressed = Vec::new();
decoder.read_to_end(&mut decompressed)?;
Ok(decompressed)
let mut zlib = flate2::read::ZlibDecoder::new(body);
match zlib.read_to_end(&mut decompressed) {
Ok(_) => Ok(Some(decompressed)),
Err(zlib_err) => {
log::debug!("deflate 按 zlib 解压失败({zlib_err}),回退 raw deflate");
let mut decompressed = Vec::new();
let mut raw = flate2::read::DeflateDecoder::new(body);
raw.read_to_end(&mut decompressed)?;
Ok(Some(decompressed))
}
}
}
"br" => {
let mut decompressed = Vec::new();
brotli::BrotliDecompress(&mut std::io::Cursor::new(body), &mut decompressed)?;
Ok(decompressed)
Ok(Some(decompressed))
}
_ => {
log::warn!("未知的 content-encoding: {content_encoding},跳过解压");
Ok(body.to_vec())
Ok(None)
}
}
}
@@ -150,10 +163,13 @@ pub(crate) async fn read_decoded_body(
if let Some(encoding) = get_content_encoding(&headers) {
log::debug!("[{tag}] 解压非流式响应: content-encoding={encoding}");
match decompress_body(&encoding, &raw_bytes) {
Ok(decompressed) => {
Ok(Some(decompressed)) => {
body_bytes = Bytes::from(decompressed);
decoded = true;
}
// 不支持的编码:原样透传且保留 content-encoding 头,
// 让下游诊断/客户端知道这仍是压缩字节
Ok(None) => {}
Err(e) => {
log::warn!("[{tag}] 解压失败 ({encoding}): {e},使用原始数据");
}
@@ -270,14 +286,21 @@ pub async fn handle_non_streaming(
if let Ok(json_value) = serde_json::from_slice::<Value>(&body_bytes) {
// 解析使用量
if let Some(usage) = (parser_config.response_parser)(&json_value) {
// 优先使用 usage 解析出的模型名称,其次使用响应中的 model 字段,最后回退到请求模型
let model = if let Some(ref m) = usage.model {
m.clone()
} else if let Some(m) = json_value.get("model").and_then(|m| m.as_str()) {
m.to_string()
} else {
ctx.request_model.clone()
};
// 归因优先级:usage 解析出的模型 → 响应 model 字段 → 映射后的出站
// 模型(路由接管真值)→ 客户端请求模型。空字符串视为缺失。
let model = usage
.model
.clone()
.filter(|m| !m.is_empty())
.or_else(|| {
json_value
.get("model")
.and_then(|m| m.as_str())
.filter(|m| !m.is_empty())
.map(str::to_string)
})
.or_else(|| ctx.outbound_model.clone())
.unwrap_or_else(|| ctx.request_model.clone());
spawn_log_usage(
state,
@@ -292,8 +315,10 @@ pub async fn handle_non_streaming(
let model = json_value
.get("model")
.and_then(|m| m.as_str())
.unwrap_or(&ctx.request_model)
.to_string();
.filter(|m| !m.is_empty())
.map(str::to_string)
.or_else(|| ctx.outbound_model.clone())
.unwrap_or_else(|| ctx.request_model.clone());
spawn_log_usage(
state,
ctx,
@@ -318,7 +343,7 @@ pub async fn handle_non_streaming(
state,
ctx,
TokenUsage::default(),
&ctx.request_model,
ctx.outbound_model.as_deref().unwrap_or(&ctx.request_model),
&ctx.request_model,
status.as_u16(),
false,
@@ -500,7 +525,16 @@ fn create_usage_collector(
let state = state.clone();
let provider_id = ctx.provider.id.clone();
let request_model = ctx.request_model.clone();
let app_type_str = parser_config.app_type_str;
// 流式事件缺失模型名时的归因兜底:映射后的出站模型(路由接管真值)优先,
// 其次才是客户端请求别名
let fallback_model = ctx
.outbound_model
.clone()
.unwrap_or_else(|| ctx.request_model.clone());
// 用 ctx 的 app_type 而不是 parser_config 的:Claude Desktop 流式透传复用
// CLAUDE_PARSER_CONFIGapp_type_str="claude"),按 parser_config 记账会把
// claude-desktop 的行错记到 claude 名下,导致供应商计价覆盖解析不到。
let app_type_str = ctx.app_type_str;
let tag = ctx.tag;
let start_time = ctx.start_time;
let stream_parser = parser_config.stream_parser;
@@ -512,13 +546,14 @@ fn create_usage_collector(
parser_config.stream_event_filter,
move |events, first_token_ms| {
if let Some(usage) = stream_parser(&events) {
let model = model_extractor(&events, &request_model);
let model = model_extractor(&events, &fallback_model);
let latency_ms = start_time.elapsed().as_millis() as u64;
let state = state.clone();
let provider_id = provider_id.clone();
let session_id = session_id.clone();
let request_model = request_model.clone();
let outbound_model = fallback_model.clone();
tokio::spawn(async move {
log_usage_internal(
@@ -527,6 +562,7 @@ fn create_usage_collector(
app_type_str,
&model,
&request_model,
&outbound_model,
usage,
latency_ms,
first_token_ms,
@@ -537,12 +573,13 @@ fn create_usage_collector(
.await;
});
} else {
let model = model_extractor(&events, &request_model);
let model = model_extractor(&events, &fallback_model);
let latency_ms = start_time.elapsed().as_millis() as u64;
let state = state.clone();
let provider_id = provider_id.clone();
let session_id = session_id.clone();
let request_model = request_model.clone();
let outbound_model = fallback_model.clone();
tokio::spawn(async move {
log_usage_internal(
@@ -551,6 +588,7 @@ fn create_usage_collector(
app_type_str,
&model,
&request_model,
&outbound_model,
TokenUsage::default(),
latency_ms,
first_token_ms,
@@ -588,6 +626,11 @@ fn spawn_log_usage(
let app_type_str = ctx.app_type_str.to_string();
let model = model.to_string();
let request_model = request_model.to_string();
// 「按请求计价」模式的锚点:映射后的出站模型,无映射时等于 request_model
let outbound_model = ctx
.outbound_model
.clone()
.unwrap_or_else(|| ctx.request_model.clone());
let latency_ms = ctx.latency_ms();
let session_id = ctx.session_id.clone();
@@ -598,6 +641,7 @@ fn spawn_log_usage(
&app_type_str,
&model,
&request_model,
&outbound_model,
usage,
latency_ms,
None,
@@ -618,6 +662,11 @@ pub(crate) fn usage_logging_enabled(state: &ProxyState) -> bool {
}
/// 内部使用量记录函数
///
/// `outbound_model` 是「按请求计价」模式的锚点:实际发往上游的模型
/// (路由接管映射后的真值,无映射时等于 request_model)。该模式的语义是
/// 「按代理发出的请求计价、不信任上游回显」,接管场景下发出的请求模型是
/// 映射后的 Y 而非客户端别名 X,按 X 计价会用错定价表行。
#[allow(clippy::too_many_arguments)]
async fn log_usage_internal(
state: &ProxyState,
@@ -625,6 +674,7 @@ async fn log_usage_internal(
app_type: &str,
model: &str,
request_model: &str,
outbound_model: &str,
usage: TokenUsage,
latency_ms: u64,
first_token_ms: Option<u64>,
@@ -638,7 +688,7 @@ async fn log_usage_internal(
let (multiplier, pricing_model_source) =
logger.resolve_pricing_config(provider_id, app_type).await;
let pricing_model = if pricing_model_source == PRICING_SOURCE_REQUEST {
request_model
outbound_model
} else {
model
};
@@ -828,6 +878,40 @@ mod tests {
use std::sync::Arc;
use tokio::sync::RwLock;
#[test]
fn decompress_body_deflate_handles_zlib_wrapped_per_rfc9110() {
// RFC 9110 规范的 deflate = zlib 包裹格式(合规上游发的就是这个)
let payload = br#"{"ok":true}"#;
let mut encoder =
flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
std::io::Write::write_all(&mut encoder, payload).unwrap();
let compressed = encoder.finish().unwrap();
let decompressed = decompress_body("deflate", &compressed).unwrap().unwrap();
assert_eq!(decompressed, payload);
}
#[test]
fn decompress_body_deflate_falls_back_to_raw_stream() {
// 部分上游违规发 raw deflate 流,保持兼容
let payload = br#"{"ok":true}"#;
let mut encoder =
flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
std::io::Write::write_all(&mut encoder, payload).unwrap();
let compressed = encoder.finish().unwrap();
let decompressed = decompress_body("deflate", &compressed).unwrap().unwrap();
assert_eq!(decompressed, payload);
}
#[test]
fn decompress_body_unknown_encoding_returns_none_to_keep_headers() {
// 未知编码必须返回 None(而非伪装成"已解码"),否则 content-encoding
// 头被剥掉,下游诊断会把压缩字节误报成明文
let result = decompress_body("zstd", b"\x28\xb5\x2f\xfd").unwrap();
assert!(result.is_none());
}
#[test]
fn test_strip_sse_field_accepts_optional_space() {
assert_eq!(
@@ -1015,6 +1099,7 @@ mod tests {
app_type,
"resp-model",
"req-model",
"req-model",
usage,
10,
None,
@@ -1047,6 +1132,95 @@ mod tests {
Ok(())
}
#[tokio::test]
async fn test_request_pricing_mode_anchors_to_outbound_model() -> Result<(), AppError> {
let db = Arc::new(Database::memory()?);
let app_type = "claude";
db.set_pricing_model_source(app_type, "request").await?;
seed_pricing(&db)?;
{
let conn = crate::database::lock_conn!(db.conn);
conn.execute(
"INSERT OR REPLACE INTO model_pricing (model_id, display_name, input_cost_per_million, output_cost_per_million)
VALUES ('outbound-model', 'Outbound Model', '4.0', '0')",
[],
)
.map_err(|e| AppError::Database(e.to_string()))?;
}
insert_provider(&db, "provider-3", app_type, ProviderMeta::default())?;
let state = build_state(db.clone());
let usage = TokenUsage {
input_tokens: 1_000_000,
output_tokens: 0,
cache_read_tokens: 0,
cache_creation_tokens: 0,
model: None,
message_id: None,
};
// 路由接管场景:客户端请求 req-model($2/M),代理实际发出 outbound-model
// $4/M),上游回显 resp-model。「按请求计价」必须锚定实际发出的模型。
log_usage_internal(
&state,
"provider-3",
app_type,
"resp-model",
"req-model",
"outbound-model",
usage,
10,
None,
false,
200,
None,
)
.await;
let conn = crate::database::lock_conn!(db.conn);
let (model, request_model, total_cost): (String, String, String) = conn
.query_row(
"SELECT model, request_model, total_cost_usd
FROM proxy_request_logs WHERE provider_id = ?1",
["provider-3"],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
)
.map_err(|e| AppError::Database(e.to_string()))?;
// model / request_model 列不受计价锚点影响
assert_eq!(model, "resp-model");
assert_eq!(request_model, "req-model");
// 按 outbound-model$4/M)计价,而不是 req-model$2/M)或 resp-model$1/M
assert_eq!(
Decimal::from_str(&total_cost).unwrap(),
Decimal::from_str("4").unwrap()
);
Ok(())
}
#[tokio::test]
async fn test_claude_desktop_inherits_claude_global_defaults() -> Result<(), AppError> {
use crate::proxy::usage::logger::UsageLogger;
let db = Arc::new(Database::memory()?);
// 全局计费配置只有 claude/codex/gemini 三行;claude-desktop 的
// 全局默认必须继承 claude,而不是静默落回工厂默认(1 / response
db.set_default_cost_multiplier("claude", "1.5").await?;
db.set_pricing_model_source("claude", "request").await?;
let logger = UsageLogger::new(&db);
let (multiplier, source) = logger
.resolve_pricing_config("nonexistent-provider", "claude-desktop")
.await;
assert_eq!(multiplier, Decimal::from_str("1.5").unwrap());
assert_eq!(source, "request");
Ok(())
}
#[tokio::test]
async fn test_log_usage_falls_back_to_global_defaults() -> Result<(), AppError> {
let db = Arc::new(Database::memory()?);
@@ -1075,6 +1249,7 @@ mod tests {
app_type,
"resp-model",
"req-model",
"req-model",
usage,
10,
None,
+11 -4
View File
@@ -112,11 +112,15 @@ impl ProxyServer {
let listener = tokio::net::TcpListener::bind(&addr)
.await
.map_err(|e| ProxyError::BindFailed(e.to_string()))?;
let local_addr = listener
.local_addr()
.map_err(|e| ProxyError::BindFailed(e.to_string()))?;
let actual_port = local_addr.port();
log::info!("[{}] 代理服务器启动于 {addr}", log_srv::STARTED);
log::info!("[{}] 代理服务器启动于 {local_addr}", log_srv::STARTED);
// 更新全局代理端口,用于系统代理检测
crate::proxy::http_client::set_proxy_port(self.config.listen_port);
crate::proxy::http_client::set_proxy_port(actual_port);
// 保存关闭句柄
*self.shutdown_tx.write().await = Some(shutdown_tx);
@@ -125,7 +129,7 @@ impl ProxyServer {
let mut status = self.state.status.write().await;
status.running = true;
status.address = self.config.listen_address.clone();
status.port = self.config.listen_port;
status.port = actual_port;
drop(status);
// 记录启动时间
@@ -213,7 +217,7 @@ impl ProxyServer {
Ok(ProxyServerInfo {
address: self.config.listen_address.clone(),
port: self.config.listen_port,
port: actual_port,
started_at: chrono::Utc::now().to_rfc3339(),
})
}
@@ -315,6 +319,9 @@ impl ProxyServer {
"/codex/v1/chat/completions",
post(handlers::handle_chat_completions),
)
// OpenAI Models API (Codex CLI reachability check)
.route("/models", get(handlers::handle_models))
.route("/v1/models", get(handlers::handle_models))
// OpenAI Responses API (Codex CLI,支持带前缀和不带前缀)
.route("/responses", post(handlers::handle_responses))
.route("/v1/responses", post(handlers::handle_responses))
@@ -148,6 +148,8 @@ mod tests {
enabled: true,
request_thinking_signature: true,
request_thinking_budget: true,
request_media_fallback: true,
request_media_heuristic: true,
}
}
@@ -156,6 +158,8 @@ mod tests {
enabled: true,
request_thinking_signature: true,
request_thinking_budget: false,
request_media_fallback: true,
request_media_heuristic: true,
}
}
@@ -164,6 +168,8 @@ mod tests {
enabled: false,
request_thinking_signature: true,
request_thinking_budget: true,
request_media_fallback: true,
request_media_heuristic: true,
}
}
@@ -251,6 +251,8 @@ mod tests {
enabled: true,
request_thinking_signature: true,
request_thinking_budget: true,
request_media_fallback: true,
request_media_heuristic: true,
}
}
@@ -259,6 +261,8 @@ mod tests {
enabled: true,
request_thinking_signature: false,
request_thinking_budget: false,
request_media_fallback: true,
request_media_heuristic: true,
}
}
@@ -267,6 +271,8 @@ mod tests {
enabled: false,
request_thinking_signature: true,
request_thinking_budget: true,
request_media_fallback: true,
request_media_heuristic: true,
}
}
+44
View File
@@ -213,6 +213,19 @@ pub struct RectifierConfig {
/// 处理错误:budget_tokens + thinking 相关约束
#[serde(default = "default_true")]
pub request_thinking_budget: bool,
/// 请求整流:不支持的图片降级(默认开启)
///
/// 上游拒绝图片输入时,把图片块替换为 [Unsupported Image] 标记,
/// 让对话不中断。总开关,管辖「显式声明 text-only」与「上游报错后兜底」两条事实驱动路径。
#[serde(default = "default_true")]
pub request_media_fallback: bool,
/// 请求整流:启发式 text-only 模型名匹配(默认开启)
///
/// 在模型未声明能力时,按内置模型名列表预测性地剥离图片(发送前)。
/// 受 request_media_fallback 管辖;单独关闭后仅保留「显式声明」与「上游兜底」,
/// 避免内置列表把多模态模型误判成 text-only 而静默剥图。
#[serde(default = "default_true")]
pub request_media_heuristic: bool,
}
fn default_true() -> bool {
@@ -229,6 +242,8 @@ impl Default for RectifierConfig {
enabled: true,
request_thinking_signature: true,
request_thinking_budget: true,
request_media_fallback: true,
request_media_heuristic: true,
}
}
}
@@ -386,6 +401,14 @@ mod tests {
config.request_thinking_budget,
"thinking budget 整流器默认应为 true"
);
assert!(
config.request_media_fallback,
"media 降级总开关默认应为 true"
);
assert!(
config.request_media_heuristic,
"启发式 text-only 模型识别默认应为 true"
);
}
#[test]
@@ -396,6 +419,14 @@ mod tests {
assert!(config.enabled);
assert!(config.request_thinking_signature);
assert!(config.request_thinking_budget);
assert!(
config.request_media_fallback,
"缺 requestMediaFallback 时应回退默认值 true"
);
assert!(
config.request_media_heuristic,
"缺 requestMediaHeuristic 时应回退默认值 true"
);
}
#[test]
@@ -419,6 +450,19 @@ mod tests {
assert!(config.request_thinking_budget);
}
#[test]
fn test_rectifier_config_serde_media_explicit_false() {
// 验证 media 两字段显式 false 时被如实反序列化(用户主动关闭须生效,不能被默认值覆盖)
let json = r#"{"requestMediaFallback": false, "requestMediaHeuristic": false}"#;
let config: RectifierConfig = serde_json::from_str(json).unwrap();
assert!(!config.request_media_fallback);
assert!(!config.request_media_heuristic);
// 其余字段仍走默认 true
assert!(config.enabled);
assert!(config.request_thinking_signature);
assert!(config.request_thinking_budget);
}
#[test]
fn test_log_config_default() {
let config = LogConfig::default();
+36 -15
View File
@@ -16,6 +16,11 @@ pub struct RequestLog {
pub app_type: String,
pub model: String,
pub request_model: String,
/// 写入时实际用于计价的模型名(pricing_model_source 解析后的结果)。
/// 落库供回填使用:缺价行补价后必须按写入时的基准重算,而不是
/// 用 model/request_model 猜——路由接管下三者可能各不相同。
/// 错误行(未计价)为空字符串。
pub pricing_model: String,
pub usage: TokenUsage,
pub cost: Option<CostBreakdown>,
pub latency_ms: u64,
@@ -68,18 +73,19 @@ impl<'a> UsageLogger<'a> {
conn.execute(
"INSERT OR REPLACE INTO proxy_request_logs (
request_id, provider_id, app_type, model, request_model,
request_id, provider_id, app_type, model, request_model, pricing_model,
input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens,
input_cost_usd, output_cost_usd, cache_read_cost_usd, cache_creation_cost_usd, total_cost_usd,
latency_ms, first_token_ms, status_code, error_message, session_id,
provider_type, is_streaming, cost_multiplier, created_at
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23)",
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24)",
rusqlite::params![
log.request_id,
log.provider_id,
log.app_type,
log.model,
log.request_model,
log.pricing_model,
log.usage.input_tokens,
log.usage.output_tokens,
log.usage.cache_read_tokens,
@@ -129,6 +135,8 @@ impl<'a> UsageLogger<'a> {
app_type,
model,
request_model,
// 错误行未经过计价,留空(回填的 has_usage 闸门也不会碰全 0 行)
pricing_model: String::new(),
usage: TokenUsage::default(),
cost: None,
latency_ms,
@@ -168,6 +176,8 @@ impl<'a> UsageLogger<'a> {
app_type,
model,
request_model,
// 错误行未经过计价,留空(回填的 has_usage 闸门也不会碰全 0 行)
pricing_model: String::new(),
usage: TokenUsage::default(),
cost: None,
latency_ms,
@@ -203,13 +213,22 @@ impl<'a> UsageLogger<'a> {
provider_id: &str,
app_type: &str,
) -> (Decimal, String) {
let default_multiplier_raw = match self.db.get_default_cost_multiplier(app_type).await {
Ok(value) => value,
Err(e) => {
log::warn!("[USG-003] 获取默认倍率失败 (app_type={app_type}): {e}");
"1".to_string()
}
// Claude Desktop 网关没有独立的全局计费配置(proxy_config 的 CHECK 仅
// 允许 claude/codex/gemini,前端也只暴露三项),全局默认继承 claude;
// 供应商级 meta 覆盖仍按 claude-desktop 查找(providers 表按该 app_type 存)。
let default_app_type = if app_type == "claude-desktop" {
"claude"
} else {
app_type
};
let default_multiplier_raw =
match self.db.get_default_cost_multiplier(default_app_type).await {
Ok(value) => value,
Err(e) => {
log::warn!("[USG-003] 获取默认倍率失败 (app_type={app_type}): {e}");
"1".to_string()
}
};
let default_multiplier = match Decimal::from_str(&default_multiplier_raw) {
Ok(value) => value,
Err(e) => {
@@ -220,13 +239,14 @@ impl<'a> UsageLogger<'a> {
}
};
let default_pricing_source_raw = match self.db.get_pricing_model_source(app_type).await {
Ok(value) => value,
Err(e) => {
log::warn!("[USG-003] 获取默认计费模式失败 (app_type={app_type}): {e}");
PRICING_SOURCE_RESPONSE.to_string()
}
};
let default_pricing_source_raw =
match self.db.get_pricing_model_source(default_app_type).await {
Ok(value) => value,
Err(e) => {
log::warn!("[USG-003] 获取默认计费模式失败 (app_type={app_type}): {e}");
PRICING_SOURCE_RESPONSE.to_string()
}
};
let default_pricing_source = if default_pricing_source_raw == PRICING_SOURCE_RESPONSE
|| default_pricing_source_raw == PRICING_SOURCE_REQUEST
{
@@ -325,6 +345,7 @@ impl<'a> UsageLogger<'a> {
app_type,
model,
request_model,
pricing_model,
usage,
cost,
latency_ms,
+229 -18
View File
@@ -37,6 +37,18 @@ impl TokenUsage {
.map(|mid| format!("{SESSION_REQUEST_ID_PREFIX}{mid}"))
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string())
}
/// 是否产生了任一计费维度的 token。
///
/// 用于在写入前过滤全 0 的空 usage:当 OpenAI 兼容上游在流式下省略 usage 时,
/// 转换器会合成一个全 0 的终止事件,若无 message_id 则 `dedup_request_id`
/// 退化为随机 UUID,导致每笔请求插入一条无意义的空行、虚增请求数。
pub fn has_billable_tokens(&self) -> bool {
self.input_tokens > 0
|| self.output_tokens > 0
|| self.cache_read_tokens > 0
|| self.cache_creation_tokens > 0
}
}
/// API 类型
@@ -85,6 +97,7 @@ impl TokenUsage {
let mut usage = Self::default();
let mut model: Option<String> = None;
let mut message_id: Option<String> = None;
let mut input_from_delta = false;
for event in events {
if let Some(event_type) = event.get("type").and_then(|v| v.as_str()) {
@@ -129,32 +142,52 @@ impl TokenUsage {
{
usage.output_tokens = output as u32;
}
// OpenRouter 转换后的流式响应:input_tokens 也在 message_delta 中
// 如果 message_start 中没有 input_tokens,则从 message_delta 获取
if usage.input_tokens == 0 {
if let Some(input) =
delta_usage.get("input_tokens").and_then(|v| v.as_u64())
{
usage.input_tokens = input as u32;
let delta_input = delta_usage
.get("input_tokens")
.and_then(|v| v.as_u64())
.map(|v| v as u32);
let delta_cache_read = delta_usage
.get("cache_read_input_tokens")
.and_then(|v| v.as_u64())
.map(|v| v as u32);
let delta_cache_creation = delta_usage
.get("cache_creation_input_tokens")
.and_then(|v| v.as_u64())
.map(|v| v as u32);
// 部分 Anthropic-compatible SSE provider 会在 message_start 上报完整上下文,
// 但在 message_delta 上报修正后的 fresh input。遇到更小的正数 delta input
// 时采用 delta;若同一 usage 块带有缓存计数,也同步采用以避免重复计数。
// 若 delta 缺少缓存字段,则保留 start 中已有的缓存值作为 best-effort fallback。
if let Some(input) = delta_input {
let should_use_delta_input = input > 0
&& (usage.input_tokens == 0
|| input < usage.input_tokens
|| (input_from_delta && input <= usage.input_tokens));
if should_use_delta_input {
usage.input_tokens = input;
input_from_delta = true;
if let Some(cache_read) = delta_cache_read {
usage.cache_read_tokens = cache_read;
}
if let Some(cache_creation) = delta_cache_creation {
usage.cache_creation_tokens = cache_creation;
}
}
}
// 从 message_delta 中处理缓存命中(cache_read_input_tokens)
if usage.cache_read_tokens == 0 {
if let Some(cache_read) = delta_usage
.get("cache_read_input_tokens")
.and_then(|v| v.as_u64())
{
usage.cache_read_tokens = cache_read as u32;
if let Some(cache_read) = delta_cache_read {
usage.cache_read_tokens = cache_read;
}
}
// 从 message_delta 中处理缓存创建(cache_creation_input_tokens)
// 注: 现在 zhipu 没有返回 cache_creation_input_tokens 字段
if usage.cache_creation_tokens == 0 {
if let Some(cache_creation) = delta_usage
.get("cache_creation_input_tokens")
.and_then(|v| v.as_u64())
{
usage.cache_creation_tokens = cache_creation as u32;
if let Some(cache_creation) = delta_cache_creation {
usage.cache_creation_tokens = cache_creation;
}
}
}
@@ -164,7 +197,11 @@ impl TokenUsage {
}
}
if usage.input_tokens > 0 || usage.output_tokens > 0 {
// 用 has_billable_tokens 而非仅看 input/output:完全缓存命中、无输出的流式请求
// input==0 && output==0 但 cache_read>0)是真实的 cache-read 计费,必须保留。
// Gemini→Anthropic 路径在 input 改为 fresh(promptTokenCount - cachedContentTokenCount)
// 后尤其会出现这种全缓存场景;旧 gate 会把它当成"无 usage"丢弃。
if usage.has_billable_tokens() {
usage.model = model;
usage.message_id = message_id;
Some(usage)
@@ -501,6 +538,71 @@ mod tests {
assert_eq!(usage.model, Some("claude-sonnet-4-20250514".to_string()));
}
#[test]
fn test_has_billable_tokens_gates_empty_usage() {
// 全 0 usage(如上游省略 usage 时合成的全 0 终止事件)不应计费——
// 这是 Codex 流式空行多记修复(D)的闸门依据。
assert!(!TokenUsage::default().has_billable_tokens());
// 仅有 cache_read 也属于真实计费 token,必须计入。
let only_cache = TokenUsage {
cache_read_tokens: 100,
..Default::default()
};
assert!(only_cache.has_billable_tokens());
let normal = TokenUsage {
input_tokens: 10,
output_tokens: 5,
..Default::default()
};
assert!(normal.has_billable_tokens());
}
#[test]
fn test_claude_stream_cache_only_request_is_recorded() {
// P2 回归:完全缓存命中、无输出的流式请求(input==0 && output==0 但 cache_read>0
// 是真实计费,必须保留——旧 gate `input>0 || output>0` 会把它丢弃。
let events = vec![
json!({
"type": "message_start",
"message": {
"id": "msg_cacheonly",
"model": "claude-opus-4-8",
"usage": {
"input_tokens": 0,
"cache_read_input_tokens": 50000,
"cache_creation_input_tokens": 0
}
}
}),
json!({
"type": "message_delta",
"usage": { "output_tokens": 0 }
}),
];
let usage = TokenUsage::from_claude_stream_events(&events)
.expect("cache-only 流式请求必须被记录,不能被 input/output gate 丢弃");
assert_eq!(usage.input_tokens, 0);
assert_eq!(usage.output_tokens, 0);
assert_eq!(usage.cache_read_tokens, 50000);
assert_eq!(usage.message_id, Some("msg_cacheonly".to_string()));
}
#[test]
fn test_codex_response_auto_returns_some_for_synthetic_all_zero() {
// P3 回归:上游非流式 Chat 省略 usage 时转换器合成的全 0 usagefrom_codex_response_auto
// 仍返回 Some(字段存在、无 positivity check)——证明 handlers 必须用 has_billable_tokens
// 闸门才能挡住空行,单靠 `if let Some` 不够。
let synthetic = json!({
"usage": { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0 }
});
let usage = TokenUsage::from_codex_response_auto(&synthetic)
.expect("全 0 usage 字段存在时 from_codex_response_auto 返回 Some");
assert!(
!usage.has_billable_tokens(),
"全 0 usage 必须被 has_billable_tokens 判为非计费,由 handlers 闸门跳过"
);
}
#[test]
fn test_claude_response_parsing_no_model() {
let response = json!({
@@ -798,6 +900,115 @@ mod tests {
assert_eq!(usage.model, Some("claude-sonnet-4-20250514".to_string()));
}
#[test]
fn test_claude_stream_prefers_smaller_delta_input_and_cache_pair() {
// 部分 Anthropic-compatible provider 会在 message_start 给出包含缓存的总上下文,
// 再在 message_delta 给出修正后的 fresh input,需要以 delta usage 为准。
let events = vec![
json!({
"type": "message_start",
"message": {
"model": "qwen-max",
"usage": {
"input_tokens": 200_000,
"cache_read_input_tokens": 180_000,
"cache_creation_input_tokens": 2_000
}
}
}),
json!({
"type": "message_delta",
"usage": {
"input_tokens": 80_000,
"output_tokens": 1_000,
"cache_read_input_tokens": 120_000,
"cache_creation_input_tokens": 500
}
}),
];
let usage = TokenUsage::from_claude_stream_events(&events).unwrap();
assert_eq!(usage.input_tokens, 80_000);
assert_eq!(usage.output_tokens, 1_000);
assert_eq!(usage.cache_read_tokens, 120_000);
assert_eq!(usage.cache_creation_tokens, 500);
assert_eq!(usage.model, Some("qwen-max".to_string()));
}
#[test]
fn test_claude_stream_updates_cache_pair_from_later_delta_input() {
// 有些 provider 会多次发送带 input 的 message_delta;一旦采用过 delta input
// 后续相同/更小 input 的 delta 应继续更新同一块里的缓存计数。
let events = vec![
json!({
"type": "message_start",
"message": {
"model": "qwen-max",
"usage": {
"input_tokens": 200_000,
"cache_read_input_tokens": 180_000,
"cache_creation_input_tokens": 2_000
}
}
}),
json!({
"type": "message_delta",
"usage": {
"input_tokens": 80_000,
"output_tokens": 100,
"cache_read_input_tokens": 110_000,
"cache_creation_input_tokens": 300
}
}),
json!({
"type": "message_delta",
"usage": {
"input_tokens": 80_000,
"output_tokens": 1_000,
"cache_read_input_tokens": 120_000,
"cache_creation_input_tokens": 500
}
}),
];
let usage = TokenUsage::from_claude_stream_events(&events).unwrap();
assert_eq!(usage.input_tokens, 80_000);
assert_eq!(usage.output_tokens, 1_000);
assert_eq!(usage.cache_read_tokens, 120_000);
assert_eq!(usage.cache_creation_tokens, 500);
assert_eq!(usage.model, Some("qwen-max".to_string()));
}
#[test]
fn test_claude_stream_keeps_start_when_delta_input_is_larger() {
// 正常 Anthropic 语义下,message_start 的 input_tokens 已经可信;
// 如果 delta input 变大,不应覆盖 start input/cache。
let events = vec![
json!({
"type": "message_start",
"message": {
"usage": {
"input_tokens": 100,
"cache_read_input_tokens": 20
}
}
}),
json!({
"type": "message_delta",
"usage": {
"input_tokens": 150,
"output_tokens": 75,
"cache_read_input_tokens": 30
}
}),
];
let usage = TokenUsage::from_claude_stream_events(&events).unwrap();
assert_eq!(usage.input_tokens, 100);
assert_eq!(usage.output_tokens, 75);
assert_eq!(usage.cache_read_tokens, 20);
}
#[test]
fn test_native_claude_stream_parsing() {
// 测试原生 Claude API 流式响应解析
+5 -5
View File
@@ -72,7 +72,7 @@ async fn query_deepseek(api_key: &str) -> UsageResult {
.get("https://api.deepseek.com/user/balance")
.header("Authorization", format!("Bearer {api_key}"))
.header("Accept", "application/json")
.timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(15))
.send()
.await;
@@ -144,7 +144,7 @@ async fn query_stepfun(api_key: &str) -> UsageResult {
.get("https://api.stepfun.com/v1/accounts")
.header("Authorization", format!("Bearer {api_key}"))
.header("Accept", "application/json")
.timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(15))
.send()
.await;
@@ -203,7 +203,7 @@ async fn query_siliconflow(api_key: &str, is_cn: bool) -> UsageResult {
.get(&url)
.header("Authorization", format!("Bearer {api_key}"))
.header("Accept", "application/json")
.timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(15))
.send()
.await;
@@ -267,7 +267,7 @@ async fn query_openrouter(api_key: &str) -> UsageResult {
.get("https://openrouter.ai/api/v1/credits")
.header("Authorization", format!("Bearer {api_key}"))
.header("Accept", "application/json")
.timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(15))
.send()
.await;
@@ -327,7 +327,7 @@ async fn query_novita(api_key: &str) -> UsageResult {
.get("https://api.novita.ai/v3/user/balance")
.header("Authorization", format!("Bearer {api_key}"))
.header("Accept", "application/json")
.timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(15))
.send()
.await;

Some files were not shown because too many files have changed in this diff Show More