Compare commits

..

1431 Commits

Author SHA1 Message Date
Jason 878c26f31e feat(proxy): extend tool-result media handling to all conversion bridges
Generalize the Codex Responses-to-Chat tool media mechanism from 6c9d444c
to the remaining protocol bridges, so image-bearing tool results are never
tokenized as base64 text on any conversion path:

- Claude-to-Chat: tool_result images become native image_url parts,
  batched into one synthetic user message after the tool message batch.
- Claude-to-Responses: JSON-string, MCP, and nested variants are restored
  as native input_image parts inside function_call_output.
- Codex/GrokBuild-to-Anthropic: non-standard tool images are restored as
  Anthropic image blocks (case-insensitive data:/http prefix parsing).
- Claude-to-Gemini: Gemini 3 uses multimodal functionResponse.parts;
  older models get inlineData parts in the same user turn. The new
  InlineImagesOnly scope keeps remote URLs and malformed data URLs in the
  legacy text form instead of emitting fileData the API would reject.

Shared changes in tool_media:

- Centralize the plan/queue/flush helpers used by both Chat bridges.
- strip_and_clamp_media_from_tool_value clamps residual base64 inside
  parsed JSON strings at any nesting depth before re-serialization.
- Emitted Chat parts no longer carry cache_control or
  prompt_cache_breakpoint, preserving the strip-all-cache_control
  contract that strict upstreams (GLM/Qwen) depend on.
- Media detection now requires full convertibility, keeping detection
  and extraction symmetric by construction.

The media sanitizer detects and strips the new shapes symmetrically
(Chat string tool results, Anthropic string tool results, Gemini
inlineData/fileData and functionResponse.parts); the legacy typed-block
replacement runs first so replacement stays a superset of detection and
cache_control survives on replaced Anthropic blocks.

No-media tool outputs keep byte-identical legacy representations on all
bridges to protect prompt-cache prefixes.
2026-07-24 12:12:22 +08:00
Jason 6c9d444c8a fix(proxy): move Codex tool-result media out of stringified tool text
The Responses->Chat conversion serialized image-bearing *_output items
into role:"tool" text via canonical_json_string, so view_image results
were tokenized as base64 text (~9000x inflation). Codex replays full
history every turn, so sessions hit context-limit 400s and wedged
(#4465, #5663).

- add proxy/tool_media: shared detection/strip/clamp walker for tool
  output media (typed input_image / image_url / input_file /
  input_audio, Anthropic source and MCP data+mimeType image shapes,
  untyped data: image_url, whole-string bare data URLs)
- transform_codex_chat: replace media blocks in place with marker text
  so tool content stays a plain string, and flush the extracted media
  as one synthetic role:"user" message after each consecutive tool
  batch; media-free traffic stays byte-identical to keep prompt-cache
  prefixes stable
- media_sanitizer: detect and strip tool-output media symmetrically
  (including JSON-string outputs) so reactive image stripping can heal
  upstream modality rejections
- forwarder: regression tests pinning the reactive trigger and the
  context-limit-400 non-trigger

E2E against Kimi K3 through the proxy: the replayed turn stays ~12k
input tokens with 99% cache hit, versus ~85k+ of base64 text per
replay before.
2026-07-24 10:16:57 +08:00
Jason 34cbb375f0 feat(usage): surface Grok Build session source in usage UI
Add the grok_session icon to DataSourceBar and the Grok Build labels
for the app filter and data-source breakdown in all four locales
(zh/en/ja/zh-TW).
2026-07-23 17:00:09 +08:00
Jason cd161f4401 feat(usage): import Grok Build official-mode usage from session logs
Grok CLI's official OAuth mode cannot be routed through the local proxy
(empty config is the mode switch, so there is no injection point), which
left official-mode usage invisible. Add session_usage_grokbuild to
import usage from ~/.grok/sessions updates.jsonl:

- Only turn_completed events carry usage; each event is the independent
  per-turn total (accumulated across inference loops within one prompt),
  so events are imported at face value. Do not reintroduce differencing
  of adjacent events: counters reset every turn and differencing would
  massively under-record.
- Cost priority: reported costUsdTicks (1 tick = 1e-10 USD) wins when
  complete, because the backfill only repairs rows with total <= 0 and
  can never correct a positive mispriced value; local pricing fills the
  breakdown and raises a drift warning above max(1% of reported, 1e-6).
  costIsPartial marks the reported value a lower bound: prefer a full
  local recompute when the model is priced, else record the lower bound.
- Idempotency key grok_session:{session}:{prompt_id}:{model} anchors on
  the upstream per-turn UUID (index fallback only when prompt_id is
  empty), so rewind truncation cannot shift keys and double count;
  orphan rows from truncated turns are kept since the tokens were spent.
- Anti double-count vs proxy takeover: 10min settle window plus a
  time-window guard over recent grokbuild proxy activity; guarded skips
  never mark files as synced.
- Seed grok-4.5-build pricing 2/6/0.30, back-derived from exact
  costUsdTicks samples (cache read bills at 0.30, not the listed 0.50).
- Map _grok_session to a friendly provider display name and refresh the
  takeover-capability comment in services/proxy.rs.
2026-07-23 17:00:03 +08:00
Jason 3cf84ca362 fix(usage): centralize cache-inclusive app set and cover grokbuild in cost backfill
The cost backfill hardcoded codex|gemini as cache-inclusive apps, so
grokbuild TOTAL-semantics rows were priced on full input tokens with
cache reads double-counted. Converge the writer (proxy logger and
calculator) and the backfill recompute onto a single
sql_helpers::is_cache_inclusive_app predicate backed by the existing
CACHE_INCLUSIVE_APP_TYPES constant, and add a regression test for the
grokbuild backfill path.
2026-07-23 16:59:41 +08:00
Jason 15d5dbe065 feat: add Grok official subscription quota query
Add SuperGrok subscription usage display, following the existing
Claude Code / Codex official-subscription pattern (protocol ported
from steipete/CodexBar):

- New subscription_grok service: reads Grok CLI credentials from
  ~/.grok/auth.json, calls the grok.com GrokBuildBilling gRPC-web
  endpoint, and parses the response via heuristic protobuf scanning
  (used percent, reset time, zero-usage special case)
- Transient failures (network errors, HTTP 408, gRPC deadline/
  cancelled) propagate as Err so the frontend retries and keeps the
  last good value; auth failures map to Expired with a re-login hint
- Tier naming by reset distance: weekly limit, monthly, or a new
  "credits" tier (i18n added for zh/en/ja/zh-TW; tray shows "c")
- New get_xai_oauth_quota command: xai_oauth providers (managed
  SuperGrok OAuth accounts) query the same billing endpoint with
  their bound account token; ProviderCard auto-renders the quota
  footer for them and hides the usage-script entry, and the tray /
  usage-script path routes xai_oauth providers to the managed
  account instead of the host app's CLI credentials
- UsageScriptModal: drop the config-content heuristic for official
  detection; category === "official" is the single source of truth

Claude-Session: https://claude.ai/code/session_01LSNvhEfuoJHaQLZcYQgBU5
2026-07-23 11:13:07 +08:00
Jason a377d79303 docs: sync v3.18.0 release notes and guide cross-links to new guide titles 2026-07-22 12:58:11 +08:00
Jason 846fbdd1c0 docs(guides): retitle Codex Claude guide to match 2026-07-22 12:13:57 +08:00
Jason 3a9fb13a0b docs(guides): add en/ja translations for Claude Code GPT guide and retitle 2026-07-22 12:13:57 +08:00
Jason 606e7bbe75 docs(release): add v3.18.0 release notes 2026-07-21 23:14:45 +08:00
Jason df1751a893 chore(release): v3.18.0 2026-07-21 22:23:17 +08:00
Jason f3108bf754 feat(providers): group presets into sponsors and non-sponsors
- Original sort mode now shows official > prime partner > sponsors
  (preset file order, aligned with the README sponsor table) >
  non-sponsors sorted by display name
- Physically reorder sponsor entries in all 8 preset files to match
  the README sponsor table order; add group marker comments
- Drop stale section comments in openclaw/hermes preset files
- Update ProviderPresetSelector tests for the new ordering
2026-07-21 21:10:54 +08:00
Jason b3f3aee3ee docs(readme): move Unity2.ai sponsor row ahead of Shengsuanyun 2026-07-21 21:10:54 +08:00
Jason 2bfca54801 docs(readme): reorder sponsors and refresh RunAPI benefit copy
- Reorder the sponsor table into the new priority order across all four
  locale READMEs (en/zh/ja/de).
- Update RunAPI's benefit line to a 10% first-top-up discount (was
  "contact support for a ¥14 credit").
2026-07-21 20:11:06 +08:00
Jason 107eade30e chore(presets): add RunAPI referral link runapi.co/register
Point the RunAPI invite link at https://runapi.co/register?aff=iOKB
across all 7 app presets (apiKeyUrl) and the four README sponsor rows
(banner + CTA), which previously used the bare runapi.co homepage with
no referral tag. The websiteUrl and runapi.co API endpoints stay bare,
so the aff code never enters a request URL.
2026-07-21 18:41:08 +08:00
Jason 3537076af2 chore(presets): update ClaudeCN referral link to claudecn.ai/register
Move the ClaudeCN invite link to https://claudecn.ai/register?aff=HEL9
across all 7 app presets (apiKeyUrl) and the four README sponsor rows
(banner + CTA, which previously pointed at the bare .top domain with no
referral tag). The websiteUrl and claudecn.top API endpoints are kept
unchanged, so only the registration/referral link moves to the new
domain and code.
2026-07-21 18:39:39 +08:00
Jason 72efd64a3d docs(readme): serve Kimi sponsor banners from Moonshot CDN
Point the pinned Kimi K2.7 Code banner at the Moonshot growth CDN
(kimi-zh.png for the ZH README, kimi-en.png for en/ja/de) instead of
the in-repo assets. Alt text and the aff=cc-switch links are unchanged.
2026-07-21 18:22:00 +08:00
Jason f0b7b81c11 chore(presets): update ZetaAPI referral link to go/u117
Refresh the ZetaAPI invite link from /go/ccs to /go/u117 across all
7 app presets (apiKeyUrl) and the four README locales. The historical
CHANGELOG entry and the api.zetaapi.ai endpoints / bare websiteUrl are
left untouched so the referral code stays out of request URLs.
2026-07-21 18:19:51 +08:00
Jason b660061b8a chore(presets): update APINebula referral link to VjM74M
Refresh the APINebula invite link from /02rw5X to /VjM74M across all
8 app presets (apiKeyUrl) and the four README locales. Bare-domain
websiteUrl and /v1 API endpoints are left untouched so the referral
code never leaks into request URLs.
2026-07-21 18:14:03 +08:00
Jason 200aa14295 style(providers): fix prettier formatting in ProviderForm 2026-07-21 17:20:45 +08:00
Jason bc8001238a docs(readme): update pinned Kimi sponsor copy to K3 2026-07-21 16:39:34 +08:00
Jason 325ba48486 feat(grokbuild): curate standalone provider presets
Grok Build previously reused the whole Codex preset list, leaking
cn_official providers and Codex default models into the Grok CLI form.
Replace the inline filter with a standalone, independently maintained
preset module (no data linkage to codexProviderPresets):

- drop cn_official direct providers and open-source-only hosts
  (SiliconFlow/ModelScope/Novita/Nvidia/AtlasCloud/OpenCode Go) that
  have no Grok models upstream
- keep aggregators and third-party relays with grok-4.5 as the default
  model (x-ai/grok-4.5 for OpenRouter-style namespaced routers)
- move the Grok Official seed entry into the presets module
- add standalone integrity tests; retarget the form's chat-mapping test
  since no openai_chat preset remains in the list
2026-07-21 16:39:34 +08:00
Jason a8daf7daad fix(codex): add missing AiHubMix preset icon
Every other app's AiHubMix preset already sets icon "aihubmix" with
iconColor #006FFB; the Codex entry was the only one missing it.
2026-07-21 16:39:34 +08:00
Jason f733def452 feat(grokbuild): add Grok Official provider with official-state import
Add a "Grok Official" preset and seed (grokbuild-official) whose empty
config represents the official login state: no custom [model.*] tables
are written, so Grok CLI falls back to its built-in xAI OAuth login and
cc-switch never touches those credentials.

Backend:
- Seed entry in OFFICIAL_SEEDS plus ensure_grokbuild_official_provider
  command for on-demand repair (the one-shot master seeding flag is
  already set for existing databases).
- Split validation into syntax-only (empty allowed) for live reads,
  writes and official snapshots, keeping the full custom-model shape
  check for non-official provider writes and imports. Backup/restore
  can now round-trip an official-state live file.
- Manual import (command layer only) recognizes an official-state live
  config and imports it as the official entry set as current, matching
  the Codex official-login import outcome. Startup auto-import keeps
  rejecting official-state live so a deleted official entry is never
  resurrected on launch: startup import only captures real user data
  as "default" and never manufactures official entries.
- Manual import also ensures the official entry before importing
  (claude-desktop precedent) and after a successful custom import, so
  first-time users end up with default + official like other apps.
- Proxy takeover guards skip or reject official-state live configs in
  all three takeover paths, consistent with the official-provider
  takeover ban.

Frontend:
- Grok Official preset entry in the GrokBuild form: official category
  hides connection fields and passes the raw config through untouched.
- Filter managed-OAuth presets out of the GrokBuild preset list; they
  were never wired for this app and produced keyless broken configs.

Tests cover seed presence, official round-trip, ensure-after-deletion,
and the four import scenarios including startup non-resurrection.
2026-07-21 16:39:34 +08:00
Jason a5aa1fd82b fix(providers): surface import errors and refresh list on failed import
Tauri invoke rejects with the backend's serialized error string, not an
Error object, so reading `.message` produced an empty toast for every
failed live-config import. Route the rejection through
extractErrorMessage with a generic i18n fallback.

Also invalidate the providers query on import failure: the import
command can have visible side effects before erroring (e.g. GrokBuild
ensures its official entry prior to a failing import), and the list
must reflect them without a manual refresh.
2026-07-21 16:39:34 +08:00
Jason 6428e993a3 feat(proxy): flag managed-OAuth providers as routing-required
Managed-OAuth providers (github_copilot / codex_oauth / xai_oauth) need
proxy takeover to inject credentials, but the "needs routing" badge and
the switch-time warning only keyed off apiFormat — missing OAuth providers
whose upstream format is native (e.g. the new Codex xAI Grok OAuth preset
on openai_responses).

- Add isOAuthProviderType / OAUTH_PROVIDER_TYPES as the SSOT for OAuth types
- Extract providerNeedsRouting() as the authoritative predicate: managed
  OAuth always needs routing (the backend rejects these accounts' direct
  connection) regardless of apiFormat or Claude Desktop mode
- ProviderCard badges (claude / codex / claude-desktop) and the switch
  warning consume the shared predicate instead of raw apiFormat
- Gate the warning on per-app routing readiness: claude-desktop uses
  isProxyRunning (backend takeover status has no such field), other apps
  use isProxyTakeover — fixes false warnings on Desktop and missing
  warnings when the proxy runs but the app isn't taken over
- Force proxy mode for all managed-OAuth providers in the Claude Desktop
  form (lock the mode toggle), not only xai_oauth
- Add unit tests for providerNeedsRouting, the switch routing gate, and
  Desktop OAuth preset enforcement
- i18n(zh/en/ja/zh-TW): add notifications.proxyReasonManagedOAuth
2026-07-21 16:39:34 +08:00
Jason dbb5bd1537 feat(codex): xAI (Grok) OAuth managed provider with native Responses compat
Add a managed "xAI (Grok) OAuth" Codex provider that routes through the
local proxy to api.x.ai via the shared Grok CLI OAuth identity, plus the
native-Responses compatibility layer that makes Codex 0.142+ traffic work
against xAI's strict upstream serde parser.

Provider:
- codex.rs: recognize the xai_oauth placeholder in extract_auth, hard-pin
  the base URL to api.x.ai and the tool profile to native Responses
- forwarder.rs: treat xAI OAuth auth failures as non-retryable
- presets + ProviderForm/CodexFormFields: managed OAuth preset that hides
  the api key/endpoint fields and derives the provider type across apps

Native Responses compatibility (gated on is_xai_oauth, so no other
provider is affected):
- transform_codex_responses_namespace: flatten Codex's private
  namespace/plugin tool declarations into top-level function tools on the
  request; restore the flat function_call names back to {name, namespace}
  on the response (streaming and non-streaming) so the client matches its
  own namespaced tool registry
- transform_codex_responses_xai_sanitize: strip the OpenAI-backend-private
  fields xAI rejects (external_web_access, prompt_cache_retention,
  safety_identifier, the additional_tools carrier, tool_search, ...) with
  deterministic removals that keep the prompt-cache prefix stable
- wire both into the native passthrough after the request transform;
  response restore runs in a dedicated handler so the generic passthrough
  hot path is untouched

Ports the proven approach of sub2api's Grok Responses gateway. Verified
with a 4-round codex -> xAI OAuth workload: all tasks green, zero upstream
errors.
2026-07-21 16:39:34 +08:00
Jason 8dcedbc062 feat(tools): prefer xAI native Grok installer with npm fallback
Treat Grok like Claude/OpenCode: install via the official xAI installer
(POSIX shell / Windows PowerShell), keep npm as fallback, discover
~/.grok/bin, and anchor updates to `grok update` only for native installs.
2026-07-21 16:39:34 +08:00
Jason eccb296afe docs(changelog): expand unreleased Codex usage fix notes to house style 2026-07-21 16:39:34 +08:00
Jason eff1e0ccfc feat(db): rebuild Codex usage on upgrade and via maintenance action
Schema v16 wipes codex_session detail rows, _codex_session rollups and
Codex rollout cursors inside the migration savepoint (cursor deletion
uses pure shape matching so CODEX_HOME drift cannot orphan cursors);
the next session sync re-imports history from source JSONL under the
corrected importer. Fresh installs traverse the same branch as a no-op.

Add a manual "Rebuild Codex usage" maintenance action (single-flight,
hard-fail backup before reset, unconditional refresh notification even
when reimport is empty or fails after reset) with a destructive confirm
dialog, result toast and four-locale strings. Historical proxy-side
duplicate rows are intentionally left untouched; history whose source
JSONL was already deleted cannot be reconstructed.
2026-07-21 16:39:34 +08:00
Jason c9ac6efd69 fix(proxy): add stable usage keys and idempotent raw-response logging
Derive request ids from upstream envelope ids (Codex/OpenAI top-level
id, Gemini responseId, Claude message id with non-empty filtering)
scoped as session:{app_type}:{provider_id}:{id} for non-Claude sources;
Claude keeps bare session:{id} to preserve session-log convergence.

The logger now queries and conditionally writes under a single
connection guard: identical semantic replays return without writing or
notifying, session_log rows may be upgraded by proxy, and same-id
different-semantic responses land on a deterministic SHA-256 collision
fallback key instead of being overwritten. Fixes the random-UUID
INSERT OR REPLACE duplication behind #5496.
2026-07-21 16:39:34 +08:00
Jason df3e07edbb fix(codex): strip forked history via parent-rollout token-prefix alignment
Rewrite the Codex session importer: identify forks by forked_from_id or
subagent thread_spawn.parent_thread_id (conflicts defer), anchor thread
identity to the rollout filename UUID, and align child token_count
signatures against the parent rollout as a strict prefix so replayed
parent history only establishes the cumulative baseline and is never
imported as child usage. Ambiguous alignments defer without advancing
the cursor and recover once the parent appears; parent signatures are
cached per (path, cutoff).

Fixes the 3x-20x double counting behind #5335/#5433 while keeping
reference-type subagents fully counted (#5381).
2026-07-21 16:39:34 +08:00
Jason a10b569a53 feat(usage): add suspected-duplicate probe for Codex session imports
Detect codex_session rows sharing the same model/token fingerprint
within the dedup window under a different request_id. Predicates reuse
the COALESCE(data_source,'proxy') shape so the existing expression
index serves the lookup. Wired up by the Codex importer rewrite.
2026-07-21 16:39:34 +08:00
Jason eb105eae76 perf(usage): coalesce session-sync notifications and serialize sync execution
Replace per-insert usage notifications with a single notification per
sync pass, guard all sync entry points (startup backfill, 60s loop,
manual sync) behind a process-wide single-flight tokio mutex, and move
blocking file/DB work onto spawn_blocking with MissedTickBehavior::Skip.

Extend SessionSyncResult with deferredFiles/suspectedDuplicates
observability fields (saturating aggregation) and add a test seam that
counts notifications even without an injected AppHandle.
2026-07-21 16:39:34 +08:00
Jason 01fca69641 test(updater): align grok npm anchor expectation with PATH prefix
bf047990 prefixed anchored npm invocations with their sibling bin
directory but missed updating the grok test expectation.
2026-07-21 16:39:34 +08:00
Jason db44484726 feat(codex): add xAI (Grok) native Responses preset
API-key preset pointing at https://api.x.ai/v1 with wire_api =
"responses": xAI serves the Responses API natively, so no route
takeover conversion is needed. Ships a grok-4.5 catalog entry
(500K context, parallel tools, text+image) so the model shows up
under Codex's strict catalog parsing. This is deliberately not a
managed-account preset: providerType stays absent, pinned by a
regression test alongside the Claude-side xAI OAuth presets.
2026-07-21 16:39:34 +08:00
Jason cdf0ee3491 fix(pricing): add missing grok-4.5 pricing row to seed
grok-4.5 is the default model of the xAI presets but had no pricing
row, so usage dashboards recorded zero cost for it. Official list
price: $2 input / $6 output / $0.50 cached read per 1M tokens.
Seed-only change: the startup INSERT OR IGNORE backfills existing
databases; no repair entry needed for a missing row.
2026-07-21 16:39:34 +08:00
Jason 09101e2a2d docs(xai): document Grok OAuth setup and disclose client identity reuse
Document the xAI OAuth flow (discovery, device, token, and API endpoints)
in the zh/en/ja manuals. State explicitly that the integration reuses the
public OAuth client identity and scopes registered for the official Grok
CLI rather than a CC Switch registration, and strengthen the shared
account-backed proxy note back to an explicit warning covering account
restriction and suspension risk.
2026-07-21 16:39:34 +08:00
Jason e9317f476e feat(xai): add Grok account management UI with four-locale strings
Add XaiOAuthSection (device-code login, account list, default selection)
backed by the generalized useManagedAuth hook, wire it into the Auth
Center and both Claude provider forms, and expose model fetching for
signed-in accounts.

- Accounts requiring re-auth stay visible in the account selector as
  disabled items with an expired badge instead of silently vanishing.
- Auth status refetches periodically so a revoked refresh token surfaces
  without reloading the panel.
- All strings ship in zh/en/ja/zh-TW; a locale coverage test pins every
  required key in all four locales.
2026-07-21 16:39:34 +08:00
Jason 615c99c62b feat(xai): add Grok OAuth presets for Claude and Claude Desktop
Register the xai_oauth provider type constant and add xAI (Grok) presets
targeting grok-4.5. The Desktop preset routes branded claude-* model IDs
to grok-4.5 upstream so it passes Desktop's third-party model validation.
2026-07-21 16:39:34 +08:00
Jason a35209a6e7 feat(xai): add Grok OAuth device-flow backend and proxy routing
Add an xAI OAuth manager using the OAuth 2.0 Device Authorization Grant
with endpoints resolved from xAI's OIDC discovery document. All HTTP goes
through the app-managed proxy client.

- Managed provider kind xai_oauth: forced openai_responses wire format,
  pinned api.x.ai base URL, bearer injection gated to the xAI origin,
  tokens registered for log redaction, single-auth-key takeover policy.
- Token cache cannot bypass account state: cache hits re-validate account
  usability, refresh commits run under the mutation lock with a
  refresh-token CAS check, and pending logins are re-checked before an
  account is persisted.
- Refresh classification: 401/403 with any body and 400 with a non-JSON
  body mark the account for re-auth; 429/5xx stay transient.
- Shared auth_* commands dispatch to xAI with guard types mirroring the
  Copilot/Codex branches.
2026-07-21 16:39:33 +08:00
Jason c4795e98ff fix(codex): backfill parser-required catalog fields from static template
Codex >= 0.144.5 requires supports_reasoning_summaries in every external
model catalog entry and rejects the whole file at startup when it is
missing, which bricks both the CLI and the desktop app.

The ProxyChat catalog template is cloned from dynamic sources first
(models_cache.json, then `codex debug models --bundled`). models_cache.json
is shared by every Codex install on the machine and each version serializes
its own ModelInfo shape, so the cache's field set follows whichever process
wrote it last and cannot be assumed to satisfy the current external-catalog
schema. Deleting the generated catalog never helped: any provider save or
switch regenerated it from the same stale template.

Backfill parser-required fields (explicit whitelist, currently only
supports_reasoning_summaries) from the bundled static template when the
dynamic template lacks them. Optional capability fields are deliberately
NOT backfilled so their missing-means-parser-default semantics survive,
and existing values always win.
2026-07-21 16:39:33 +08:00
Jason 6fddcaa97c feat(pricing): add bare k3 alias for Kimi For Coding plan
The Kimi For Coding subscription reports its K3 model under the short
id `k3` (no `kimi-` prefix), whereas the regular Moonshot API still uses
the full `kimi-k3`. Seed a `k3` alias row right after `kimi-k3` at the
same official list price ($3/M in, $15/M out, $0.30/M cache read) so
coding-plan usage is priced correctly. Mirrors the existing
hunyuan-hy3/hy3 bare-alias precedent.

Pricing is matched by exact model id, so this does not touch the
`kimi-for-coding` endpoint alias (intentionally unpriced, subscription
semantics) nor risk prefix mismatches. Seed-only, no schema bump.
2026-07-21 16:39:33 +08:00
Jason aa0e441d07 docs: add Claude Code Codex routing guide
Document API key and ChatGPT OAuth routing flows for using Codex models in Claude Code, including configuration screenshots and troubleshooting guidance.
2026-07-21 16:39:33 +08:00
Jason 17b053ed94 fix(updater): resolve Node for anchored npm commands
Prefix anchored npm invocations with their sibling bin directory so env-based Node shebangs work under a minimal GUI PATH. Cover Codex repair commands and add a regression test.
2026-07-21 16:39:33 +08:00
Jason e356fc6efc fix(openclaw): price preset models at official list prices in $/M
The cost field on OpenClaw preset models is denominated in USD per
million tokens (as the Claude entries already were), but 15 entries
carried $/1K-style decimals or stale values. Reprice everything at the
model's official list price, mirroring the built-in pricing table, so
usage is always valued at standard rates regardless of channel:

- glm-5.1 (Zhipu CN/EN, ModelScope): 1.4/4.4, cache read 0.26
- qwen3.5-plus: 0.26/1.56, cache read 0.052
- kimi-k2.7-code and the kimi-for-coding alias (K2.7 Code per official
  docs): 0.95/4, cache read 0.19
- MiniMax-M2.7 (official + SiliconFlow): 0.3/1.2, cache read 0.06,
  cache write 0.375
- KAT-Coder-Pro: 0.3/1.2, cache read 0.06
- LongCat-2.0: 0.75/2.95, cache read 0.015
- Ling-2.5-1T: 0.56/2.24 (official CNY 4/16 at ~7.14)
- deepseek-v4-pro: 0.435/0.87 (old 1.68/3.36 was CNY 12/24 left
  unconverted), cache read 0.003625
- kimi-k2.5 (Nvidia NIM): 0.6/3, cache read 0.1

Subscription-plan endpoints and free-tier hosts intentionally show
list prices too, so plan users can see the standard value of their
usage.
2026-07-21 16:39:33 +08:00
Jason f20458229d feat(presets): add Kimi K3 to Kimi open-platform presets
Add kimi-k3 (1M context, 131K max output) to the Kimi provider preset
model lists for Codex, Hermes, OpenClaw, and OpenCode, appended after
kimi-k2.7-code so the catalog-first-row default backfill is unchanged.
The Kimi For Coding plan presets keep the kimi-for-coding endpoint
alias and are intentionally untouched.
2026-07-21 16:39:33 +08:00
Jason 2bfecead4f feat(pricing): add Kimi K3 to built-in model pricing table
Seed kimi-k3 at the official list price ($3/M input, $15/M output,
$0.30/M cache read; released 2026-07-16 with a 1M context window).
Cross-checked against the Moonshot pricing docs, OpenRouter, and
models.dev. Seed-only change: ensure_model_pricing_seeded picks it up
on next launch, no schema version bump needed.
2026-07-21 16:39:33 +08:00
Jason 6274705848 feat(logging): capture frontend errors to disk with structured redaction
Frontend half of the logging overhaul.

Capture:
- Add a global error boundary plus window error/unhandledrejection
  handlers that persist renderer errors via tauri-plugin-log (new
  @tauri-apps/plugin-log dependency + log:default capability), so a
  white-screen crash leaves a trace.

Redaction (two layers over every logged value):
- Structured serializer: redact by sensitive property name (arrays and
  nested values included) and by opaque value shape.
- Text layer, the universal final pass: redact URL credentials/query,
  auth schemes, known secret shapes, and named-key array/object values.
  The container rule closes prefix+JSON, double-encoded, and POJO-error
  bypasses regardless of which entrypoint the structured data came from.
- Render Errors as redacted message + native stack across V8 and WebKit
  (macOS/Linux) without depending on a single stack format.
- Bound all inputs and drop oversized JSON to keep the UI responsive.

i18n:
- zh / en / ja / zh-TW for the new log settings and error text.
2026-07-21 16:39:33 +08:00
Jason 22d2872c33 feat(logging): persist diagnostics across restarts and redact secrets
Backend half of the logging overhaul.

Retention:
- Keep the last 4 rotated files at 20MB each and stop deleting logs on
  startup, so a crash's prior-run logs survive a restart.
- Apply the persisted log level right after plugin registration instead
  of at the end of setup.
- Bound crash.log with size-based rotation (5MB x 2).

Secret redaction on every log path:
- Proxy: strip userinfo/query from upstream URLs (keep path for
  diagnostics), exact-match redact known auth.api_key/access_token,
  classify request/response bodies instead of logging them, header
  allowlist.
- Redact the Gemini `?key=` in cache-trace endpoints.
- Omit MCP custom-field values (headers may carry tokens).
- Redact deeplink and model-fetch URLs before logging.

Docs:
- FAQ points users to the persistent crash.log for support workflows.
2026-07-21 16:39:33 +08:00
Jason 7f028632b5 feat(presets): restore SudoCode.us to coexist with SudoCode.chat sponsor
The legacy sudocode.us provider was replaced in place by the sudocode.chat
sponsor (618723b4) because the two unrelated companies share the SudoCode
name. Bring the legacy provider back and distinguish the two by their
domain suffix.

- Rename the sponsor preset to "SudoCode.chat" across its six clients;
  partner status, promotion copy (key "sudocode"), and icon unchanged
- Re-add "SudoCode.us" across all seven clients (including the previously
  removed Gemini entry) with its pre-replacement config: gpt-5.5,
  sudocode.us endpoints, sudocode.run fallback candidates
- Mark SudoCode.us as partner (isPartner) without a partnerPromotionKey:
  promo copy is pending, and the promo box only renders when a key exists
- Give the SudoCode.us Hermes entry a distinct slug (sudocode_us) so both
  providers can coexist in the additive ~/.hermes/config.yaml
- Restore the legacy logo from git history as sudocode-us.png and register
  it in the hand-maintained icon index and metadata
2026-07-21 16:39:33 +08:00
Jason 3bc828aecc fix(windows): eliminate console flash and UI freeze on provider switch
Switching providers or toggling proxy takeover on Windows flashed a
transient cmd window and froze the UI for up to a couple of seconds.
Three fixes:

- Spawn `codex debug models --bundled` with CREATE_NO_WINDOW so the
  console child of the GUI-subsystem app (npm's codex.cmd runs via
  cmd.exe) no longer opens a visible window.
- Cache the ProxyChat model catalog template in a process-wide OnceCell:
  only successful loads are cached, failures stay retryable, so the
  Codex CLI starts at most once per app run instead of on every switch.
- Run switch_provider via spawn_blocking: sync Tauri commands execute on
  the main thread, so the blocking catalog generation (and the
  block_on'd per-app switch lock) froze the UI. Concurrency is already
  serialized by ProxyService::lock_switch_for_app.
2026-07-21 16:39:33 +08:00
Komi 08710d51fc fix(proxy): default Codex tool parameters to object schema (#5315)
Normalize function tool parameters on the Codex Responses -> Chat Completions bridge: default null/missing parameters (direct and nested function forms) to {"type":"object","properties":{}}, coerce explicit type:null, and add a root type for top-level oneOf schemas so strict OpenAI-compatible upstreams (DeepSeek etc.) no longer reject built-in Codex tools like codex_app__automation_update. Also hardens the Codex -> Anthropic tool path with the same object-type guarantee and adds regression coverage for all reported shapes.
2026-07-21 10:13:00 +08:00
ka79376046 613fef70bc fix(codex-chat): attach reasoning forward for responses bridge (#5508)
* fix(codex-chat): attach reasoning forward for responses bridge

* fix(codex-chat): preserve tail reasoning after embedded reasoning

* docs(codex-chat): align trailing reasoning comments
2026-07-19 11:39:29 +08:00
滅ü 997be22bfa fix(tray): detect system locale for first-run language instead of hardcoding zh (#4355)
The tray menu used a hardcoded zh (Simplified Chinese) fallback whenever
settings.language was unset (i.e. first install). On systems whose UI language
resolves to Traditional Chinese / Japanese / English via the frontend's
navigator-based detection, the tray therefore showed Simplified Chinese until
the user manually switched language once.

Detect the OS locale via the sys-locale crate and map it to a supported tray
language, mirroring the frontend getInitialLanguage precedence
(zh-TW/HK/MO/Hant -> zh-TW, other zh -> zh, ja -> ja, en -> en, otherwise zh).
This keeps the tray consistent with the UI from the first launch with no timing
window. An explicitly stored settings.language still takes precedence, so user
choices are never overridden. Adds unit tests for the locale mapping.

Co-authored-by: LaiYueTing <LaiYueTing@users.noreply.github.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-07-17 21:35:10 +08:00
Allen Xu edea624a27 fix(skills): preserve deleted default repositories (#5356)
* fix(skills): preserve deleted default repositories

* fix(skills): persist default repo initialization state
2026-07-17 15:51:29 +08:00
Thefool 1c0ee0c58a feat(grokbuild): add first-class Grok Build support (#5453)
* feat(grokbuild): add backend integration

* feat(grokbuild): add provider and management UI

* test(grokbuild): cover configuration and integrations

* fix(grokbuild): address backend review feedback

* fix(grokbuild): complete UI review feedback

* feat(grokbuild): add CLI lifecycle management

* fix(grokbuild): align provider icon fallback

* test(grokbuild): cover provider icon persistence
2026-07-17 15:50:50 +08:00
zayoka f6e37ed994 fix(ci): run backend checks on Windows/macOS and repair platform-gated tests (#5138)
* fix(ci): run backend checks on Windows/macOS and repair platform-gated tests

The backend CI job ran only on ubuntu-22.04, so every #[cfg(target_os =
"windows")] / macOS path — tests and clippy lints alike — was never
compiled or run. As a result main shipped 8 failing Windows unit tests and
a hard `cargo clippy -- -D warnings` failure on Windows, all invisible to
CI because it only builds and tests Linux.

Changes:

- ci: run the backend job on a {ubuntu-22.04, windows-latest, macos-latest}
  matrix (fail-fast: false); gate the apt install step on runner.os ==
  'Linux' and use `shell: bash` for the dist placeholder so it works on all
  three runners.

- misc.rs: fix 6 stale `anchored_upgrade_windows` tests. Commit 5092fe51
  removed codex from `prefers_official_update`, so codex now anchors to the
  package manager with no `codex update ||` prefix; update the five
  package-manager expectations accordingly, and retarget the no-sibling
  "official-update-without-fallback" test to `claude` (still in the list) so
  that branch stays covered instead of being silently dropped.

- codex_state_db.rs / codex_history_migration.rs: the two sqlite_home tests
  built TOML basic strings from Windows paths, whose backslashes are invalid
  escape sequences and made the override fail to parse; switch to TOML
  literal (single-quoted) strings so the path is taken verbatim.

- clippy (13 Windows-only warnings): move `use std::io::Write` into the
  #[cfg(unix)] block that actually uses it; convert 3 unneeded `return`s in
  Windows-gated tail positions to expressions; mark 9 POSIX-shell helpers
  #[cfg_attr(windows, allow(dead_code))] since they are used only by the
  macOS/Linux terminal launchers.

Verified locally (Windows 11, Rust 1.95.0):
  cargo test --lib                        → 1748 passed; 0 failed (was 1740/8)
  cargo clippy -- -D warnings             → clean (was 13 errors)
  cargo fmt --check                       → clean

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

* fix(skills): resolve home via get_home_dir so tests isolate on Windows

services/skill.rs called dirs::home_dir() directly in five places. On
Windows dirs::home_dir() resolves through the Known Folder API and
ignores HOME/USERPROFILE, so the CC_SWITCH_TEST_HOME override set by the
test harness never applied: the skill_sync integration tests scanned the
runner's real user profile, found no skills, and failed (the first panic
then poisoned the shared test mutex, cascading to all seven). On Unix
the harness also sets HOME, which dirs::home_dir() honors, so the suite
passed there by accident.

Route all five call sites through crate::config::get_home_dir(), the
crate-wide home resolver that prefers CC_SWITCH_TEST_HOME. The three
now-unreachable GET_HOME_DIR_FAILED error branches are dropped:
get_home_dir() is infallible, matching every other config-dir resolver.
Production behavior is unchanged (CC_SWITCH_TEST_HOME is unset outside
tests, so get_home_dir falls through to dirs::home_dir).

Add a regression test that discriminates on every platform by pointing
CC_SWITCH_TEST_HOME at a temp dir different from $HOME; it is marked
#[serial_test::serial] to stay mutually exclusive with the other tests
mutating the same process-global variable. Verified the test fails
against the old code on macOS with the same failure mode as Windows CI.

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-07-15 10:33:22 +08:00
Jason 1cc52c7e73 docs(readme): add SubRouter sponsor entry across four locales 2026-07-14 22:46:19 +08:00
SaladDay 6d316c0bda fix(codex): preserve streamed tool call identity and order (#5310)
Keep non-empty call IDs across continuation deltas and release parallel tool calls in Chat index order when identity fields arrive late. Preserve valid sparse and later calls during finalization.
2026-07-14 20:01:10 +08:00
Ryan2128 9ca1a41f58 fix: normalize function parameters type to "object" for strict OpenAI-compatible providers (#4706)
* fix: normalize function parameters type to "object" for strict OpenAI-compatible providers

Some Responses tools carry parameters with `type: null` (e.g.
codex_app__automation_update), causing HTTP 400 from strict
OpenAI-compatible providers like DeepSeek that require
`{"type": "object", "properties": {...}}`.

This adds normalize_function_parameters() to ensure the type
field is always "object" in both branches of
responses_function_tool_to_chat_tool.

Closes #4705

* style: fix cargo fmt issues

* fix: handle null function parameters
2026-07-14 19:23:41 +08:00
Jason c8b0d60c2d docs(guides): add Codex + Claude local routing guide in three languages
Step-by-step guide for the v3.17.0 native Anthropic Messages upstream:
add a custom Codex provider pointed at a Claude-family /v1/messages
gateway, pick the anthropic upstream format, enable local routing, and
verify the chain. Covers the auth-field choice (Bearer vs x-api-key),
the Claude Code impersonation toggle, the 8192 max-output fallback, and
a FAQ entry for gateways that restrict keys to Claude Code only.

Includes four UI screenshots captured from the real 3.17.0 app with
sample data, and links the guide from the v3.17.0 release notes in all
three languages.
2026-07-14 11:53:55 +08:00
Jason 7e73a1ffb2 fix(i18n): add missing proxyReasonAnthropicMessages key across locales
The routing-required toast for Anthropic-format Codex providers only had
a Chinese defaultValue in code; non-Chinese locales showed a mixed-language
message. Add the reason string to zh/en/ja/zh-TW following the phrasing of
the sibling proxyReason* keys.
2026-07-14 11:53:39 +08:00
Jason 3d176b98cc docs(release): add v3.17.0 release notes 2026-07-13 23:41:54 +08:00
Jason c154d30b7a chore(release): v3.17.0 2026-07-13 21:24:58 +08:00
Jason 6eb217b242 revert(proxy): drop the 1-hour cache TTL option and TTL-bucketed write accounting
The forced 1-hour cache_control TTL (schema v14) was a mistake. Injected
breakpoints return to Anthropic's standard 5-minute TTL, caller-owned
markers are preserved verbatim instead of having their TTLs rewritten,
and the 5m/1h cache-write buckets are removed from usage parsing and
pricing (back to the single aggregate cache-creation rate). The cache
TTL selector is removed from the rectifier settings panel along with its
i18n keys in all four locales.

SCHEMA_VERSION returns to 13: the unreleased cache_creation_1h_tokens
column and the v13->v14 migration are removed. The feature never shipped
in a release and the introducing commit was never pushed, so no
databases were stamped v14 outside this machine (local DB verified at
user_version 13).
2026-07-13 17:55:33 +08:00
Jason ac52c851bf fix(codex): infer image capability for generated catalogs and resync takeover live on save
Mapped GPT models were rejected by Codex clients with "model does not
support image inputs". Two root causes:

- Catalog entries for native-Responses/Anthropic providers cloned a
  template whose input_modalities defaulted to ["text"], so every mapped
  model was advertised text-only. model_catalog_json replaces Codex's
  built-in model table wholesale, and both the TUI and the IDE extension
  block images pre-send when the current model is found without "image".
- Editing the current Codex provider during proxy takeover only refreshed
  the DB backup, so removing the mapping left a stale model_catalog_json
  pointer (and its text-only catalog file) active in live config.

Changes:

- New shared model_capabilities module: explicit row declaration first,
  then a confirmed text-only registry (exact tail match only — prefix
  matching removed, variants enumerated so future -vl/-vision models fail
  open), everything else unknown.
- Catalog generation writes input_modalities from that inference for all
  tool profiles: unknown models fail open to ["text","image"]; only
  confirmed text-only models are advertised as ["text"], giving users a
  clear client-side prompt instead of silent image stripping.
- Live catalog reverse-import collapses modalities that match current
  inference, so registry corrections are not frozen into hidden row
  overrides and the rectifier's heuristic opt-out keeps working.
- Saving the current Codex provider while takeover owns live now
  re-projects the live config (mirrors the hot-switch path), so mapping
  edits and removals take effect immediately.
- Media rectifier delegates to the shared module; its preflight toggle is
  documented (4 locales) as proxy-request-only, never affecting catalog
  capability declarations.
2026-07-13 16:48:22 +08:00
Jason 618723b42f feat(presets): promote SudoCode to paid sponsor across six clients
Replace the legacy sudocode.us provider (a name collision) with the new
paid sponsor SudoCode on sudocode.chat, updated in place across six
clients: Claude Code, Codex, Claude Desktop, OpenCode, OpenClaw, Hermes.

- Switch endpoints to api.sudocode.chat, add isPartner +
  partnerPromotionKey, and add four-locale partnerPromotion copy
- Claude Code / Desktop use direct passthrough (no model mapping)
- Codex / OpenCode / OpenClaw / Hermes use gpt-5.6-sol
- Remove the Gemini entry (outside sponsor scope)
- Replace the provider icon with the new brand PNG
2026-07-13 16:48:22 +08:00
Jason af58740bcd fix(proxy): align Codex OAuth client identity
ChatGPT's Codex backend routes model availability by the originator and version header pair. Requests identifying as cc-switch without a version were assigned to a cohort where gpt-5.6-luna resolved to an unavailable internal engine, resulting in a misleading 404 Model not found response.

Identify takeover requests as codex_cli_rs and send version 0.144.1, satisfying luna's minimal_client_version requirement of 0.144.0. A direct HTTP A/B test confirmed the existing headers returned 404 while the aligned identity completed successfully, so no WebSocket transport workaround is required.
2026-07-13 16:48:22 +08:00
Jason 99573d2242 refactor(presets): pin context window values instead of form fields
Drop the Max Context Tokens / Auto Compact Window template inputs from
the Codex and Kimi For Coding presets and hardcode the values in the
preset env (372000 / 262144). The rare user who wants different numbers
can edit them directly in the JSON editor.

Both keys stay on purpose: the compact window resolves as
min(model window, value), so matching the window is behavior-neutral
today, but the explicit env pins compaction locally against
remote-config experiments dialing it down.
2026-07-13 16:48:21 +08:00
Jason 940ddd332b feat(kimi): declare the 256K context window for Kimi For Coding
Claude Code caps unknown model ids at 200K, so the preset's standalone
CLAUDE_CODE_AUTO_COMPACT_WINDOW=262144 was clamped by min(window, value)
and never took effect. Pair it with CLAUDE_CODE_MAX_CONTEXT_TOKENS and
route the endpoint's kimi-for-coding alias on every tier, since both
context envs are ignored for claude-* prefixed model ids.

Saved providers get the same context defaults injected into effective
live settings at switch time, with a mirror-inverse strip on backfill so
injected values never harden into provider config. Explicit user values
always win over the injected defaults.
2026-07-13 16:48:21 +08:00
Jason 31ee42854a feat(pricing): seed gpt-5.6 alias rows and 1.25x cache-write rates
- Add the bare gpt-5.6 row (official Sol alias) plus effort-suffix variants
  mirroring the gpt-5.5 accounting shape, priced at Sol rates
- The GPT-5.6 family charges cache writes at 1.25x the uncached input rate
  (new for OpenAI; earlier GPT models keep their correct zero): set
  6.25 / 3.125 / 1.25 for Sol / Terra / Luna across seed rows
- Repair earlier zero-value gpt-5.6 tier seeds in existing databases,
  matching only untouched rows so user-customized prices survive
2026-07-13 16:48:21 +08:00
Jason 5c39dfbfbe feat(codex): declare gpt-5.6 context window for Claude Code takeover
- Update Codex OAuth presets to the gpt-5.6 family (haiku -> gpt-5.6-luna)
  and bump the custom Codex template default model
- Inject CLAUDE_CODE_MAX_CONTEXT_TOKENS / CLAUDE_CODE_AUTO_COMPACT_WINDOW
  (372000, the ChatGPT Codex catalog window with a ~353K effective budget,
  openai/codex#31860) into effective live settings so Claude Code stops
  assuming a 200K window and compacts before the upstream rejects the prompt
- Gate the injected defaults on every configured model being gpt-5.6*:
  gpt-5.5's upstream catalog oscillates between 272K and 372K and must not
  inherit them; explicit user values always win
- Strip the injected values on switch-away backfill (mirror-inverse of the
  injection conditions) so program defaults never harden into per-provider
  explicit values, and keep both keys out of the shared common-config snippet
2026-07-13 16:48:21 +08:00
Jason f15184edb0 feat(codex): expose official routing and restore the built-in provider
Let users switch between the built-in OpenAI provider and third-party Codex providers directly from the provider panel while takeover mode remains active.

Centralize the frontend capability predicate so only the fixed codex-official seed receives native-login routing support, and keep copied UUID-based official entries clearly marked as unsupported.

Add an idempotent backend command that recreates the deleted official seed, wire it into the add-provider flow, refresh localized guidance, and add mutation and provider-action regression coverage.
2026-07-13 16:48:21 +08:00
Jason f2c6d48e19 fix(providers): skip reachability probes for official OAuth entries
Do not derive unauthenticated health-check targets from runtime adapter defaults for official providers. Batch checks now skip official entries, and direct base-URL resolution fails explicitly instead of probing first-party endpoints without credentials.

Cover the Codex official provider in the stream-check regression tests so future adapter changes cannot silently reintroduce these probes.
2026-07-13 16:48:21 +08:00
Jason 51d6c458ff feat(codex): route native ChatGPT sessions through proxy takeover
Allow the built-in Codex official provider to participate in takeover mode while preserving Codex's native OAuth or API-key credentials instead of persisting them into provider records.

Project official routing into a dedicated TOML provider, normalize inline tables, clean stale managed placeholders, and fail closed when the live configuration cannot be transformed safely.

Validate forwarded authorization, make official 401/403 responses non-retryable, avoid circuit-breaker pollution, and share the first-party ChatGPT endpoint across the Codex and Claude adapters.
2026-07-13 16:48:21 +08:00
Jason 13e7c1fcc4 fix(usage): account for Anthropic cache write TTLs
Parse and retain Anthropic's ephemeral 5-minute and 1-hour cache-creation token buckets while preserving the existing aggregate cache-write metric for compatibility.

Price 1-hour writes at the documented premium relative to the configured 5-minute write rate, clamp inconsistent provider details safely, and include TTL buckets in usage diagnostics.

Persist 1-hour cache-write tokens with schema version 14 so zero-cost backfills and later pricing updates retain the original TTL semantics. Keep session import paths compatible through zero-valued detail fields.
2026-07-13 16:48:21 +08:00
Jason b9263a8040 fix(cache): strengthen prompt cache breakpoint injection
Honor both the optimizer master switch and the cache-injection sub-switch before mutating native optimizer requests.

Use the available four-breakpoint budget across tools, system content, the latest cacheable message, and an older user anchor for long tool-heavy conversations.

Preserve caller-owned breakpoint limits, avoid thinking blocks as cache targets, normalize configured TTLs, and add regression coverage for disabled optimization and long histories.
2026-07-13 16:48:21 +08:00
Jason 650905af2c fix(proxy): harden Responses and Anthropic protocol bridges
Fail closed on HTTP 2xx failure envelopes and pre-output SSE failures so semantic upstream errors can trigger failover instead of becoming empty successful replies.

Finalize incomplete and truncated streams explicitly, handle clean EOF and whole JSON responses, and keep tool-call stop reasons and terminal event ordering consistent.

Preserve structured tool results, URL images, documents, system roles, and signed thinking across both conversion directions. Drop incomplete historical tool calls safely and classify malformed completed arguments as non-retryable client requests.

Keep Codex-to-Anthropic prompt caching enabled by default while honoring the dedicated cache-injection switch.
2026-07-13 16:48:21 +08:00
Jason a078b4b207 feat(proxy): session-based prompt_cache_key routing for Codex Chat bridge
Codex always sends prompt_cache_key in its Responses requests, but the
Responses -> Chat Completions conversion dropped it, breaking session
cache affinity on upstreams that route by key (e.g. Kimi Coding).

- Re-inject prompt_cache_key after conversion in the forwarder: an
  explicit client key wins, otherwise a client-provided session ID;
  generated per-request UUIDs are never sent upstream.
- Provider-aware gating: "auto" enables only known-compatible upstreams
  (api.openai.com, api.kimi.com/coding) because strict gateways reject
  unknown fields with HTTP 400 (e.g. Fireworks); an advanced
  Auto/Enabled/Disabled override is available on the Codex form in all
  four locales.
- Kimi For Coding preset opts in explicitly.
2026-07-13 16:48:21 +08:00
Jason 0e563b50c5 fix(cache): surface unsupported breakpoint counts
Warn when caller-provided cache breakpoints already exceed the supported total of four while preserving the original markers and upgrading their TTLs.

Clarify that automatic injection is governed by the remaining breakpoint budget, and add regression coverage proving excess caller markers are never deleted or reordered.
2026-07-13 16:48:21 +08:00
Jason 27ce0a519c fix(proxy): harden Responses reasoning and tool-call conversion
Round-trip encrypted Responses reasoning items through bridge-owned Anthropic thinking blocks, discard orphaned reasoning-only history, and consume the official reasoning text event vocabulary.

Track concurrent streaming items by stable IDs and output indexes, reuse a dedicated fallback block for keyless legacy reasoning, recover tool arguments from done events, and close blocks in protocol order.

Normalize empty or incomplete non-streaming tool arguments, reject malformed completed calls, and persist upstream usage before returning terminal conversion errors.
2026-07-13 16:48:21 +08:00
Jason f991726ff0 fix(usage): account for cache-write tokens across schema versions
Parse cache_write_tokens from OpenAI usage details and preserve cache creation data across Chat, Responses, and Anthropic conversion paths.

Add explicit input-token semantics to request logs and rollups so legacy rows subtract cache reads only while new total-inclusive rows subtract both cache reads and writes. Migrate v12 databases, normalize rollups to fresh input, and cover historical backfill behavior with regression tests.
2026-07-13 16:48:21 +08:00
Jason 06039540ff refactor(health-check): remove per-provider test config 2026-07-13 16:48:21 +08:00
Jason 442799879d feat(profiles): add setting to toggle project switcher on main page
Add a show/hide toggle for the header project profile switcher under
the Homepage Display section in settings. Defaults to visible so
existing users keep the current behavior.
2026-07-13 16:48:21 +08:00
Jason 7479d10db7 feat(codex): add default model field to provider form
Expose the top-level `model` key of config.toml as an editable field in
the Codex provider form, so users can switch to newly released models
(e.g. gpt-5.6) without waiting for a preset update — preset updates only
affect newly added providers, existing ones keep their saved TOML.

The field syncs bidirectionally with the TOML editor (mirroring the
base-URL pattern), suggests models from the mapping catalog plus the
provider's /models endpoint, and offers a one-click "add to mapping"
action when the value is outside a non-empty catalog. Hidden for
official providers.

Details:

- Save-time catalog sync now only backfills the first mapping row into
  the top-level model when the field was left empty, so the explicit
  field wins over the implicit row-0 sync
- Escape model names (and base_url) with TOML basic-string escaping and
  strip control characters from field input: /models ids are remote
  data and unescaped interpolation could inject config.toml lines
  (e.g. a forged [mcp_servers.*] command)
- The strict model-line matcher now recognizes escaped output, empty
  strings and single-quoted literals, keeping extract/set round-trips
  stable; deliberately no key-only loose matching (it would misfire on
  assignment-looking text inside multiline strings)
- Invalidate the fetched model list whenever the request identity
  changes (base URL, full-URL toggle, API key, custom UA) and discard
  in-flight responses via a sequence guard, so the dropdown never shows
  a previous provider's models
- i18n for zh/en/ja/zh-TW
2026-07-13 16:48:21 +08:00
Jason 62e44c4838 feat(pricing): seed Tencent Hunyuan Hy3 pricing
Add Hunyuan Hy3 (released 2026-07-06, 256K context) to seed_model_pricing
under both the hunyuan-hy3 and hy3 ids, since the upstream billing id isn't
yet confirmed and one of the two should match logged usage.

Prices come from Tencent's launch-day list price (CNY 1 / 4 / 0.25 per 1M
input / output / cache-hit), converted at 1 USD ~= 7.14: 0.14 / 0.56 / 0.035.
cache_write is "0" (no published write rate). Hy3 actually uses input-length
tiered billing (<16K / 16-32K / >=32K); the single-price table holds the
lowest tier, so long-context requests are under-billed until this is revisited
against the official billing page. New model, so seed only.
2026-07-13 16:48:21 +08:00
Jason a7b4dd9405 feat(pricing): seed GPT-5.6 Sol/Terra/Luna pricing
Add the three GPT-5.6 tiers to seed_model_pricing, cross-checked against
OpenAI's official pricing page and OpenRouter:

  gpt-5.6-sol    5 / 30 / 0.50 (cache read)
  gpt-5.6-terra  2.50 / 15 / 0.25
  gpt-5.6-luna   1 / 6 / 0.10

cache_write is "0": OpenAI publishes only a cached-input (read) rate and no
separate cache-write price, matching the gpt-5.x family convention. Base ids
only for now — effort-suffix variants are deferred until the upstream logging
suffix set for 5.6 is confirmed. New model, so seed only (no repair branch,
no SCHEMA_VERSION bump).
2026-07-13 16:48:21 +08:00
风少1227 c6197ae324 fix(proxy): inject a single auth placeholder on managed Claude takeover (#5095)
Switching the Claude provider from a third-party (DeepSeek/MiMo/...) to a
managed Codex provider wrote both ANTHROPIC_API_KEY and
ANTHROPIC_AUTH_TOKEN as PROXY_MANAGED into ~/.claude/settings.json,
making Claude Code warn "Both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY
set - auth may not work as expected" on every run.

The double key is an accretion artifact: the ManagedAccount takeover
policy originally injected only ANTHROPIC_API_KEY (Copilot, #1049), and
the Codex fix that preserved ANTHROPIC_AUTH_TOKEN to avoid the login
prompt (#3784 / PR #3789) added the token on top without removing the
API key insert.

Inject exactly one placeholder instead: AUTH_TOKEN for Codex-managed
providers (keeps the #3784 fix), API_KEY for Copilot (keeps the #1049
behavior). Local-proxy auth is unaffected - the forwarder resolves the
PROXY_MANAGED placeholder from either header.

Updates the three Codex takeover tests to assert API_KEY is absent and
adds a regression test for the exact third-party -> Codex switch from
the report.

Fixes #4919
2026-07-12 21:47:45 +08:00
白喵喵喵喵 f39d463c44 fix(usage): 修复 Codex 子代理使用量未计入统计 (#5187)
* fix(usage): count Codex subagent session tokens

* fix(usage): address Codex subagent review feedback

* fix(usage): preserve Codex migration history

* fix(usage): harden Codex subagent migration

* fix(usage): reimport late Codex subagents

* fix(usage): guard late Codex rollup reimport

* refactor(usage): simplify Codex subagent accounting fix
2026-07-11 20:11:14 +08:00
Komi ded0b63a8e fix: handle missing provider keys and tool schema types (#5069)
* fix: handle missing api keys and tool schema types

* fix: preserve nested tool schemas

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-07-11 16:57:46 +08:00
v2v 6245caa6c5 Fix/opencode known field editors (#2907)
* fix: add opencode model limit editor

* fix: add opencode headers editor

* style: refine opencode advanced field layout

* fix: preserve valid opencode headers

* fix: preserve opencode extra options and sync translations

---------

Co-authored-by: wzk <wx13571681304@outlook.com>
Co-authored-by: Jason Young <44939412+farion1231@users.noreply.github.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-07-11 16:38:00 +08:00
Dawn 50270d5e42 fix: exclude Fable model env from Claude common config (#4272) (#5206)
* Add test for Fable model env key exclusion

Add regression test to ensure Fable model env keys are excluded from common config.

* Add Fable model to CLAUDE_MODEL_OVERRIDE_ENV_KEYS

* Add files via upload

* Delete .github/workflows/build-windows-unsigned.yml
2026-07-11 10:11:57 +08:00
Yeeyzy 99e11e0851 feat(codex): support native Anthropic Messages protocol as upstream (#5071)
* feat(codex): support native Anthropic Messages protocol as upstream

Allow gateways that only expose the native Anthropic Messages protocol
(/v1/messages) to be used by Codex: the local proxy performs bidirectional
request/response/streaming conversion between Responses and Anthropic.

Backend:
- Add two conversion modules: transform_codex_anthropic / streaming_codex_anthropic
- codex.rs: add routing detection and auth: ANTHROPIC_AUTH_TOKEN→Bearer (default),
  ANTHROPIC_API_KEY→x-api-key, mutually exclusive
- handlers.rs: add handle_codex_anthropic_to_responses_transform
- forwarder.rs: support optional Claude Code client fingerprint impersonation
  (User-Agent / anthropic-beta / x-app / system prompt first-line injection)
  and /responses→/v1/messages rewriting
- codex_config: the anthropic format reuses the NativeResponses profile to strip
  custom tools
- ProviderMeta: add impersonateClaudeCode

Frontend:
- CodexApiFormat: add "anthropic"; the form adds auth field selection and an
  impersonation toggle
- Add en/ja/zh/zh-TW copy

Robustness:
- Downgrade when tool history / forced tool_choice conflicts with extended
  thinking, avoiding upstream 400s
- Emit cache_creation_input_tokens in usage and use saturating_add to guard
  against overflow
- Append a unique suffix to non-streaming/streaming output-item ids to avoid
  multi-segment text/thinking overwriting each other

* fix(codex): harden Anthropic bridge against empty text blocks and truncated streams

- Drop empty/whitespace-only text content blocks when rebuilding Anthropic
  messages from Responses history; Anthropic 400s on empty text blocks (e.g. an
  empty assistant text emitted alongside a tool_use), which broke follow-up and
  tool-result requests. Also drop messages left without content.
- Do not report a truncated Anthropic stream as completed: when the SSE
  connection ends before message_stop with no stop_reason, emit an incomplete
  response if partial output exists, or a failed (stream_truncated) response
  otherwise, mirroring the chat converter's EOF handling.

* fix(codex): resolve Anthropic-bridge review findings

Blocking:
1. Defer stripping the [1m] long-context marker until after catalog matching and model write-back, re-stripping it on the final Codex→Anthropic body and setting a flag to emit the context-1m-2025-08-07 beta header, so the marker is no longer lost or overridden by the default model.
2. Gate Anthropic thinking on the trailing turn only (via trailing_turn_allows_thinking) instead of scanning full history, so a Codex session that resends history each round no longer permanently loses thinking after the first tool call.
3. Inject 5m ephemeral cache_control on the Codex→Anthropic body by reusing cache_injector (handling the system string→array conversion), so system/tools/history are cached instead of re-sent at full price every round.
4. Add a shared base_url_is_full_endpoint helper (normalizing whitespace/query/fragment/trailing slash) used by both the Anthropic and Chat paths, so a base URL already ending in /v1/messages is treated as a full endpoint instead of double-appending to /v1/messages/v1/messages.
5. Align the catalog tool-profile predicate with the routing predicate so resolve_codex_catalog_tool_profile returns the Anthropic profile whenever the request converts to Anthropic, preventing freeform tools like apply_patch from being silently filtered by a ProxyChat catalog.
6. Explicitly disable native web_search for the Anthropic profile (including the no-catalog branch) via set_codex_native_web_search_field, so Codex no longer treats it as available while the transform silently drops it.
7. Only forward tool_choice when tools survive filtering, dropping it otherwise, to avoid a non-retryable 400 from upstream when tool_choice is sent with no tools.
8. Lower the fallback default to max_tokens=8192 (only when max_output_tokens is omitted) and clamp the thinking budget to max_tokens/2, disabling thinking below the 1024 floor, to avoid hard 400s on low-output-ceiling models/gateways.

Minor:
9. Centralize the Codex/OpenAI fingerprint-header denylist in is_codex_client_fingerprint_header so impersonating Claude Code uniformly drops originator/session_id/conversation_id/chatgpt-account-id/x-client-request-id/openai-* and the x-stainless-*/x-codex-* prefixes.
10. Retain content_block_start.input as start_input and fall back to it at block close when no input_json_delta arrived, so a gateway that carries the full tool input on the start event no longer yields empty tool arguments.
11. Extract a shared codex_responses_sse module as the single Responses SSE envelope builder that both the chat and anthropic streaming emitters delegate to, with byte-for-byte-unchanged wire output, so future event-format fixes touch one place instead of two.

* fix(codex): add per-provider max_output_tokens override for Codex→Anthropic path

Codex does not forward model_max_output_tokens in the request body,
causing the proxy to fall back to a conservative 8192 default. This
truncates long or thinking-heavy responses (stop_reason=max_tokens).

- Add maxOutputTokens field to ProviderMeta (Rust + TypeScript)
- Inject the value into the Anthropic request body before transform,
  taking precedence over request-supplied and default values
- Add numeric input in Codex form fields (Anthropic format only)
- Add i18n entries for label, placeholder, and hint (en/zh/zh-TW/ja)
- Include roundtrip and omission unit tests for the new field

* fix(codex): harden Anthropic protocol bridge

* fix(codex): address Anthropic bridge review

* fix(codex): preserve flattened Anthropic inputs

* fix(codex): harden Anthropic recovery paths

* fix(ci): satisfy Rust clippy

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-07-10 23:06:30 +08:00
makoMakoGo 98ccde0050 fix(usage): persist dashboard refresh interval (#5057) 2026-07-09 10:02:23 +08:00
zhanxin.xu 95c917b337 feat(provider): add Zhipu team plan quota query support (#5128)
智谱团队套餐(Team Plan)的额度查询与个人版不同:同一 quota 端点加
`?type=2`,需额外 `bigmodel-organization` / `bigmodel-project` 请求头
(api_key + 组织 ID + 项目 ID 三者缺一不可),且仅存在于国内站
open.bigmodel.cn。参考 token-monitor/src/shared/zaiTeamLimits.js 实现。

- Backend (services/coding_plan.rs): 新增 query_zhipu_team(固定 CN 站、
  ?type=2、org/project 头);抽出 zhipu_quota_from_body 与个人版共用解析;
  入口 get_coding_plan_quota 靠显式 coding_plan_provider == "zhipu_team"
  路由(base_url 与个人版智谱相同,detect_provider 无法区分)。新字段经
  UsageScript、IPC 命令、后台查询路径(query_provider_usage_inner)透传。
- Frontend: UsageScriptModal 新增「Zhipu GLM Team」选项 + 组织/项目 ID
  输入;模板切换时保留 team 字段;测试与保存逻辑按 team 传参。
- i18n: en/zh/zh-TW/ja 四个 locale 更新。
- Tests: 凭据校验/路由(缺任一凭据 → NotFound,标识大小写不敏感)+ 本地
  server 验证 ?type=2 与 org/project 请求头形状。

Co-authored-by: XuZhanXin <1239576606@qq.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 09:21:10 +08:00
Salar 3538b39246 feat(claude): add 1M checkbox to fallback model field (#5124)
The fallback model (ANTHROPIC_MODEL) field was missing the 1M checkbox
that the role-specific model rows already have. Added the checkbox with
the same strip/set marker logic used by role rows.

Fixes #3679
2026-07-09 08:36:54 +08:00
Jason ba531ca222 docs(readme): add new-api as a sponsor
Add the open-source AI infrastructure project new-api as the latest
sponsor entry, appended to the end of the sponsor table across all four
localized READMEs (en/zh/ja/de). Includes the banner asset.
2026-07-08 22:46:09 +08:00
Jason 88d5ffba44 fix(codex): move common-config TOML merge off smol-toml to backend toml_edit
updateTomlCommonConfigSnippet re-serialized the whole document through
smol-toml (parse -> deepMerge -> stringify): comments dropped, keys
reordered, and empty parent table headers synthesized -- the
long-standing "config.toml keeps getting reordered" symptom (audit C5,
introduced in 083e48bf).

Replace it with a backend command backed by the same
merge_toml_table_like / remove_toml_table_like used when writing live
configs, so the form preview and the live write share one merge
semantic and user formatting survives edit-time merges. The frontend
sync helper is deleted outright to keep the pattern from coming back.

Making the form operations async exposes them to interleaving, so a
result is discarded unless it is still current when it lands:

- a per-hook sequence number (last operation wins) covers rapid
  toggle/save races where an earlier merge resolves after a later
  removal and would flip the switch back;
- a config-baseline check covers the user hand-editing the TOML while
  a merge is in flight -- the stale result must not clobber their edit.
  The checkbox state self-heals via the existing inference effect.

Regression tests pin both by resolving a suspended merge after a newer
operation / an external edit, plus backend tests locking comment and
key-order preservation, scalar override, and value-matched removal.
2026-07-08 22:46:09 +08:00
Jason 94fc1cc064 fix(mcp): surface per-app failures when importing MCP servers from apps
import_mcp_from_apps swallowed every importer error with unwrap_or(0),
so a corrupt config.toml surfaced as "imported 0 servers" with no hint
that anything went wrong.

Move the aggregation into McpService::import_from_all_apps: each app
imports best-effort (one bad file doesn't block the rest), and failures
are collected into a single error naming the failing apps alongside the
count that did import. The frontend now refreshes the server list on
settle rather than success, since a partial failure still means new
servers were persisted.
2026-07-08 22:46:09 +08:00
Jason 11c173c730 fix(mcp): stop cross-app failures from blocking MCP re-projection
sync_all_enabled iterated AppType::all() with `?`, so one app's corrupt
live file (e.g. a broken ~/.claude.json, which passes the existence
gate but fails to parse) blocked every app behind it in the iteration
order -- and bubbled the error into whatever operation triggered the
sync:

- switch/save had just rewritten only the target app's live file, yet a
  broken unrelated file failed the whole operation after DB and live
  were already updated, reporting a false "switch failed" to the user.
  Both now project only the target app (sync_enabled_for_app) and
  degrade projection failure to a warning: the primary operation has
  already taken effect, and the projection self-heals on the next
  switch or MCP toggle.
- sync_current_provider_for_app_to_live syncs a single app; it now
  projects that app only, keeping failures (which can only concern the
  target app) as errors.
- sync_current_to_live (config import / cloud-sync restore) keeps the
  all-apps sweep, but sync_all_enabled is now best-effort: it projects
  every app, collects failures, and reports them aggregated. Its error
  is held until after skill sync so an MCP failure no longer skips it.
2026-07-08 22:46:09 +08:00
Jason 1f36f0cfed feat(provider): extend switch-time common-config autosync to Codex
Claude already re-extracts the live config into the shared common-config
snippet right before switching away, so shared tweaks (plugins,
preferences) made in live propagate to all opted-in providers. Codex was
gated out because its TOML pipeline leaked provider-specific and
injected content into the snippet.

With the extractor now stripping all injection artifacts and routing
fields, and backfill stripping the MCP projection, open the gate to
Claude + Codex. The autosync-before-strip ordering also self-heals
stale snippet values previously baked into provider snapshots: the
re-extracted snippet matches the live values, so the value-match strip
removes them on the same switch.

End-to-end tests cover: new shared keys captured, deletions synced,
secrets/injected artifacts never entering the snippet, and provider A's
key not leaking into provider B's live.
2026-07-08 22:46:09 +08:00
Jason 6d2ee2472f fix(provider): re-project Codex MCP after unified-session toggle rewrites live config
Toggling unify_codex_session_history rewrites the current official
provider's live config.toml in full (intended design), which drops the
[mcp_servers] projection -- and nothing put it back, so enabled MCP
servers silently vanished until the next provider switch (#C2).

Re-project after the rewrite, with two deliberate choices:

- Project Codex only (new McpService::sync_enabled_for_app) instead of
  sync_all_enabled: the all-apps sync short-circuits in AppType::all()
  order, so a corrupt ~/.claude.json would error before Codex is ever
  reached and the freshly wiped [mcp_servers] would stay missing. Only
  Codex's live file was rewritten here, so only Codex needs
  re-projection.
- Degrade projection failure to a warning: by this point the live file
  already carries the new bucket state, so the toggle has taken effect.
  Propagating the error would make save_settings roll back the setting,
  creating the exact "setting=old, live=new bucket" session split the
  rollback exists to prevent. The projection self-heals on the next
  switch or any MCP toggle.
2026-07-08 22:46:09 +08:00
Jason 473c2aaa9f fix(provider): exclude injected artifacts and routing fields from Codex common-config extraction
extract_codex_common_config kept several fields in the shared snippet
that must never cross providers:

- [mcp_servers] and the legacy [mcp.servers] form: owned by the DB
  mcp_servers table; once in the snippet they get merged into every
  opted-in provider and no sync path can ever clean them up.
- top-level experimental_bearer_token: normally lives inside
  [model_providers.<id>] (stripped with the whole table), but three
  fallbacks write it at top level -- leaking the API key into the
  shared snippet.
- model_catalog_json: per-provider catalog projection pointer.
- web_search, only when it equals the injected "disabled" sentinel;
  a user-set value remains a shareable preference.
- top-level wire_api: same provider-routing semantics as top-level
  base_url (the fallback target when no model_provider is set); leaking
  it would rewrite the next provider's protocol selection.

This makes the extractor safe as the source for switch-time
common-config autosync.
2026-07-08 22:46:09 +08:00
Jason 93f56198da fix(codex): strip synced [mcp_servers] from provider snapshots on backfill
MCP servers are owned by the DB mcp_servers table; the [mcp_servers]
section in live config.toml is only a projection re-synced after every
live write. When switching away baked that projection into the stored
provider snapshot, servers deleted in the app were resurrected the next
time that provider was activated -- per-entry reconcile only knows rows
that still exist in the DB, so it can never clean up such orphans.

Strip [mcp_servers] (and the legacy [mcp.servers] form) from the live
settings during switch-away backfill. Previously polluted snapshots
self-heal the next time the user switches away from them.
2026-07-08 22:46:09 +08:00
Jason 8b1ce764f1 fix(mcp): fail closed when Codex config.toml is unparseable during MCP sync
sync_single_server_to_codex silently fell back to an empty DocumentMut
when the existing config.toml failed to parse, then wrote the whole file
back -- wiping every other section (model, model_providers, comments)
and leaving only the single synced [mcp_servers.<id>] entry. Introduced
by 3a548152, which fixed the removal path but left the destructive
fallback on the sync path.

Now the sync path returns an McpValidation error and leaves the file
untouched, matching the fail-closed behavior of the read/validate path.
2026-07-08 22:46:09 +08:00
Jason fad5b4c094 Revert "fix(presets): point Volcengine/Doubao/BytePlus website links to official sites"
The websiteUrl for 火山Agentplan, DouBaoSeed and BytePlus is intentionally the ccswitch-attributed apiKeyUrl link, per the Volcengine partner's request. Restore the invite/attribution links across all six app preset files.

This reverts the websiteUrl changes from 56248087; apiKeyUrl was already left intact there.
2026-07-08 22:46:09 +08:00
Jason bad3610d93 refactor(presets): drop redundant 'OpenAI Compatible' preset
Remove the 'OpenAI Compatible' custom-template preset from the OpenCode
and OpenClaw preset lists. It was a duplicate entry point: the built-in
'custom' provider flow already exposes an interface-format selector whose
default (@ai-sdk/openai-compatible / openai-completions) produces a
byte-identical starting config. Having both left two list items pointing
to the same place.

Existing providers are unaffected — presets only seed form defaults on
creation; saved providers store concrete npm/baseUrl/apiKey/models values.

The '@ai-sdk/openai-compatible' dropdown label is intentionally kept; it
is the format option users pick in the custom flow, not the deleted preset.
2026-07-08 22:46:09 +08:00
Allen Xu e78aa8a7c3 fix: sync openclaw and hermes live provider updates (#5098)
* fix: sync openclaw live provider updates

* fix: sync hermes live provider updates

* fix test: hermes live import stores models as array after denormalize

The test import_hermes_providers_from_live_updates_existing_provider_from_live
seeded models as a dict, but import_hermes_providers_from_live reads via
get_providers() which calls denormalize_provider_models_for_read(), converting
models from YAML dict to UI-friendly array. The test assertion accessed models
as dict -> Null -> assertion failure.

Fix: access models as array by index, matching the actual storage format after
live import. Also verify the id field is preserved in the denormalized output.
2026-07-08 12:09:56 +08:00
Allen Xu e191af4aa1 fix: OpenCode live provider import updates (#4712)
* fix: sync existing opencode providers from live config

* fix: preserve OpenCode provider display names

* docs: update comments and log messages to reflect new update behavior

- fix stale comment in lib.rs that said existing providers are skipped
- change log message from 'Imported' to 'Synced' since count now
  includes both new imports and updates
2026-07-08 10:34:49 +08:00
Jason d271d60cf9 docs: add Codex Kimi routing guides 2026-07-08 00:00:56 +08:00
Jason 358bf1e2b7 chore(pnpm): settle build-script approvals for esbuild and msw
pnpm 10.13+ appends "set this to true or false" allowBuilds
placeholders to pnpm-workspace.yaml on every install for unreviewed
dependencies with lifecycle scripts. Approve esbuild (postinstall
ensures the platform binary) and ignore msw (postinstall only prints
an integration notice) so the file stops mutating itself.
2026-07-07 21:03:20 +08:00
Jason 2df2212ceb fix(usage): reject transient transport failures so retry and keep-last-good work
Usage/quota queries frequently showed spurious "query failed" states that
manual refresh could not clear (#3820). Root cause: all transport-level
failures were folded into Ok(success:false), so react-query's retry never
fired and the failure body poisoned the cache as regular data.

Backend:
- balance/coding_plan/subscription services now return Err for send
  failures and body-read failures (read body via bytes() before
  serde_json::from_slice; reqwest's json() wraps read errors as Decode,
  making error-kind checks on it dead code). Auth/4xx/parse errors stay
  Ok(success:false) and surface immediately.
- Script path maps transient AppError keys (request_failed /
  read_response_failed) to Err; Volcengine adds a Transient call variant.
- Command layer skips snapshot persistence, usage-cache-updated emit and
  tray refresh on Err so the cache bridge cannot overwrite retained data.
- Expired-credential retry propagates transient errors instead of
  rewriting them as "OAuth token has expired".

Frontend:
- resolveDisplayUsage generalized to subscription quotas; 5th param is now
  an options object with a `rejected` flag: stale success data retained by
  react-query across rejections is re-anchored to dataUpdatedAt and expires
  through the same 10-minute keep-last-good window instead of being shown
  indefinitely (a total outage used to mask longer than a single 5xx).
- useSubscriptionQuota / useCodexOauthQuota gain keep-last-good with
  per-scope snapshot reset; rejected queries with no displayable value
  synthesize a failure placeholder carrying the real error message so
  footers keep rendering a retry entry point.
- HTTP 429 is classified transient (retry-later) alongside 5xx.
- UsageScriptModal surfaces string rejections via extractErrorMessage.

Tests: 6 backend behavior tests drive real HTTP against a local listener
to pin the Err/Ok channel semantics; frontend suite extends
keepLastGoodUsage coverage (405 passing).
2026-07-07 20:05:29 +08:00
Jason 468c93d409 ci: harden release supply chain
- Add CODEOWNERS so PRs to main require owner review (closes the gap
  where two collaborators could approve each other's changes).
- Gate the release job behind a 'release' environment, so signing
  secrets are only unlocked after manual approval.
- Stop ignoring the whole .github directory; this had been silently
  swallowing labeler.yml and workflows/labeler.yml, which are now tracked.

Paired with a tag ruleset (created out-of-band) that restricts creation
of v* tags to admins, this prevents a write collaborator from pushing a
tag to trigger a signed release build.
2026-07-07 16:02:16 +08:00
Jason 525346188b fix(proxy): close media fallback gaps for Volcano GLM 5.2 image 400s
Fixes #5025. The rectifier's media fallback missed Volcano Coding Plan's
GLM 5.2 on both paths:

- Preventive: known_text_only_model had glm-5.1 but not glm-5.2, so image
  blocks were forwarded verbatim. Added glm-5.2 as an exact tail match
  (not a prefix, to avoid stripping images from a future glm-5.2v
  multimodal variant following Zhipu's 4v/5v naming).
- Reactive: the upstream error "Model only support text input" never
  mentions image/media, so the mentions_image gate rejected it before
  hints ran; and the existing "only supports text" hint misses the
  gateway's missing third-person "s". Added a self-evident phrase list
  ("only support text" / "only supports text") that asserts a modality
  rejection on its own and bypasses the image-mention gate.

Includes regression tests using the verbatim #5025 error body and the
glm-5.2[1M] mapped-model form, plus a glm-5.2v negative assertion.
2026-07-07 12:57:11 +08:00
Jason afabe80167 test(profiles): gate desktop-scope assertion by platform in profile roundtrip
The desktop switch to d2 is cfg-gated to macOS/Windows, but the assertion
expecting d2 was not, so on Linux CI the desktop provider stays at the seeded
d1 and the assertion panics — poisoning the shared test mutex and cascading
into two more failures. Expect d1 on non-desktop platforms.
2026-07-07 11:57:26 +08:00
Jason 7fada72dd4 chore(code0): update partner invite link to agent register URL
Replace the ?source=ccswitch referral with the new agent register invite
link (https://code0.ai/agent/register/B2XHxGjGmRvqgznY) on code0's
apiKeyUrl across all seven presets and the sponsor rows in all four
READMEs. API endpoints stay bare per the referral red-line.
2026-07-07 10:49:32 +08:00
Jason 9f7642e29c refactor(profiles): drop manual snapshot update now that switching autosaves
Since switching projects automatically saves the current configuration
back to the project being left, the per-project "update from current"
button is redundant and even harmful: it allowed overwriting another
project's snapshot with the current state, breaking the invariant that
a project holds the state you last left it in.

- Remove the resnapshot button and confirm dialog from the manage
  dialog; drop the now-unused scope prop and PROFILE_SCOPE_LABELS
- Add a footer Close button to the manage dialog (overlay click is
  disabled app-wide, so it previously could only be closed via Esc)
- Update manageDescription in all four locales to describe the
  autosave behavior; remove the two dead i18n keys
- Fix a shadowed `warnings` vec in ProfileService::apply that silently
  dropped autosave-failure warnings before they reached the frontend
- Mention auto-capture on next switch in the "no snapshot for this
  scope yet" warning and doc comments

The backend update command keeps its resnapshot parameter; it is now
only exercised by the pre-switch autosave path.
2026-07-07 10:49:32 +08:00
Jason 22159430c6 fix(profiles): use camelCase keys for current profile ids in frontend 2026-07-07 10:49:32 +08:00
Jason 754af2cc31 feat(profiles): split Claude Desktop into independent profile scope 2026-07-07 10:49:32 +08:00
Jason 3ec83578f6 fix(profiles): stop proxy server when profile switch leaves no takeovers active 2026-07-07 10:49:32 +08:00
Jason f05ed3dbac fix(ui): invalidate proxy takeover status after profile switch 2026-07-07 10:49:32 +08:00
Jason 4f45601f9f feat(profiles): unconditionally disable proxy takeover before applying profile 2026-07-07 10:49:32 +08:00
Jason 4cf6f175a7 feat(profiles): autosave previous profile state on switch
When switching to a different project, the current configuration of the
previously active project is automatically captured into that project's
snapshot before the target project's snapshot is applied. Scope is limited
to the active group (Claude/Codex); autosave failures are collected as
warnings and do not block the switch.

- Move autosave logic into ProfileService::apply for consistent behavior
  across UI, tray, and tests
- Add integration test covering bidirectional autosave roundtrip

Refs: profile switch B方案
2026-07-07 10:49:32 +08:00
Jason dbb5999d1e refactor(profiles): shared project entity with per-scope switching
Projects are now global shared entities; Claude and Codex groups switch
independently via scoped current pointers and scoped payload slots.

- Remove scope column from profiles; keep current_profile_id_<scope>
- Use Option<Vec<String>> for mcp/skills to distinguish 'never captured'
  from 'captured empty', preventing cross-side accidental disable
- Update/apply operations scoped to the active group via merge_scope_from
- Tray menu nests same shared list under Claude Code/Codex groups
- Add i18n for per-scope tooltips and 'not saved for this side' hint

Refs: profile P1 shared-entity redesign
2026-07-07 10:49:32 +08:00
Jason 65a5464fcc feat(profiles): include Claude Desktop provider in project profiles
Claude Desktop's only dimension managed by cc-switch is its provider
(MCP/Skills are hardcoded unsupported and prompts have no live file),
so snapshots capture just the current desktop provider while the empty
MCP/Skills sets and None prompt make apply a natural no-op for the
other dimensions - no per-dimension special casing needed.

- Add claude-desktop slot to PROFILE_APPS and PerApp (serde key uses
  the hyphenated app id); old payloads without the key deserialize to
  None and leave Claude Desktop untouched on apply
- Gate the tray Projects submenu by iterating PROFILE_APPS instead of
  hardcoding Claude/Codex visibility
- Show the profile switcher on the Claude Desktop tab, mirror the
  PerApp type, invalidate the claude-desktop providers cache on apply,
  and extend the switcher tooltip in all four locales
- Extend the roundtrip integration test with the desktop provider
  dimension; the desktop switch is cfg-gated to macOS/Windows because
  desktop live writes error on Linux where CI runs cargo test
2026-07-07 10:49:32 +08:00
Jason 6179c18805 fix(profiles): scope switcher to supported app tabs and relocate it
- Render the profile switcher only when the active tab is Claude or
  Codex (frontend mirror of backend PROFILE_APPS), so viewing an
  unsupported app no longer suggests its config was switched
- Move the switcher from beside the logo to the right of the route
  toggles, where the flexible spacer absorbs its appearance and other
  header controls no longer shift when switching tabs
2026-07-07 10:49:32 +08:00
Jason 8f018a2d45 feat: add project profiles for snapshot-based config switching
Add a profile feature that captures the current provider, MCP,
skills and prompt state for Claude Code and Codex as a named
snapshot, and re-applies it in one click from the header switcher
or the tray Projects submenu.

- New profiles table (schema v12) with current marker in settings
- ProfileService orchestrates the four existing switch primitives
  (provider first, then MCP diff, skills diff, prompt enable)
- Best-effort apply: dangling references become warnings, no rollback
- Header combobox switcher + snapshot-style manage dialog
- Tray Projects submenu shared with the UI apply/event pipeline
- i18n for zh/en/ja/zh-TW under the new profiles domain
- Integration tests covering roundtrip, dangling refs and clear
2026-07-07 10:49:32 +08:00
秋澪Akimio b3e5e32c89 feat: add Claude subagent model config (#4830)
* feat: add Claude subagent takeover config

* feat: add Claude subagent model field

* i18n: add Claude subagent model labels

* fix(proxy): preserve configured subagent model mapping

* fix(providers): exclude subagent model from Claude common config

* style: format rust code
2026-07-07 10:28:36 +08:00
makoMakoGo e606adfae7 fix(codex): display renamed session titles (#4927)
* fix(codex): display renamed session titles

* fix(codex): resolve custom state db for titles

* refactor(codex): dedupe state-db resolution and harden title lookup

- Extract a shared `codex_state_db` module for `state_5.sqlite` path
  resolution (config `sqlite_home` / `CODEX_SQLITE_HOME`), previously
  copy-pasted verbatim between codex_history_migration and the codex
  session provider. `state_5.sqlite` is now a single source of truth.
- Add `busy_timeout` to the read-only title query; without it a read
  during a concurrent Codex write fails immediately (SQLITE_BUSY) and
  renamed titles silently fall back to the first user message.
- Push the `title == first_user_message` comparison into the SQL WHERE
  clause (NULL-safe, aligning with Codex's `distinct_thread_metadata_title`
  semantics) and stop SELECTing `first_user_message`, which can hold
  large values (openai/codex#29007) — the comparison belongs in SQL
  anyway, so the column no longer needs to cross into Rust.
2026-07-06 09:11:55 +08:00
SaladDay 7a7d41c873 fix(subscription): display Codex free-plan 30-day quota window (#3651) (#4886)
* fix(subscription): display Codex free-plan 30-day quota window (#3651)

Codex free accounts are metered on a rolling 30-day secondary window
(limit_window_seconds = 2,592,000) instead of the weekly window used by
paid plans. The backend already maps this correctly to the tier name
"30_day", but the frontend TIER_I18N_KEYS whitelist had no entry for it,
so SubscriptionQuotaView filtered the tier out. When that was the only
surviving tier (as happens for free accounts), the whole quota footer
rendered nothing — free accounts showed no remaining quota or reset time
while paid accounts worked.

- Add "30_day" -> subscription.thirtyDay to TIER_I18N_KEYS
- Add the thirtyDay label to all four locales (zh/en/ja/zh-TW)
- Add a unit test locking in window_seconds_to_tier_name mappings,
  including the 30-day case

Fixes #3651

* fix(tray): render Codex free-plan 30-day window in tray menu

The tray keeps its own tier-name whitelist (TIER_LABEL_GROUPS) independent
of the frontend TIER_I18N_KEYS. Its month group only listed "monthly", so a
free Codex account whose only tier is "30_day" produced empty labeled parts
→ format_subscription_summary returned None → the tray showed no quota, even
though the footer now does. That breaks the invariant the existing
gemini_summary_lite_only_still_renders test guards: any tier visible in the
footer must not leave the tray blank.

- Add TIER_THIRTY_DAY ("30_day") constant so the string is single-sourced
  across backend mapping, tray grouping, and the frontend whitelist
- Map 2_592_000s explicitly to it in window_seconds_to_tier_name
- Add TIER_THIRTY_DAY to the tray month ("m") group
- Add codex_summary_thirty_day_only_still_renders regression test

Follow-up to the review on #3651 / PR for the 30-day footer fix.
2026-07-05 22:54:20 +08:00
Butui Hu ffc22ea714 feat(universal-provider): Auto-sync after adding and drop unused addSuccess i18n key (#2811)
* feat(universal-provider): Auto-sync after adding and drop unused addSuccess i18n key

Signed-off-by: Hu Butui <hot123tea123@gmail.com>

* fix(i18n): sync zh-TW universal provider strings

---------

Signed-off-by: Hu Butui <hot123tea123@gmail.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-07-05 22:41:05 +08:00
Cheng Zi Feng 7a8b956253 Update Longcat presets to LongCat-2.0 (#4838)
* Update Longcat presets to LongCat-2.0

* fix(proxy): classify LongCat-2.0 as text-only for media sanitizer

The Longcat presets now use LongCat-2.0, but the known_text_only_model
allowlist still only matched the retired longcat-flash-chat tail. Without
this, images pasted into a text-only LongCat-2.0 session are forwarded
upstream instead of being replaced with the unsupported-image marker,
causing a hard rejection. Add longcat-2.0 (keeping the retired name for
saved configs) and a regression test.

---------

Co-authored-by: chengzifeng <chengzifeng@meituan.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-07-04 16:38:35 +08:00
makoMakoGo 0cda8d46c7 fix: 更新 OpenCode 会话恢复命令 (#2359) 2026-07-02 22:14:43 +08:00
Jason 8d1b3306d0 chore(release): v3.16.5 2026-07-01 23:55:55 +08:00
Jason 6d84082d27 docs(release-notes): add v3.16.5 notes (zh/en/ja) 2026-07-01 23:55:55 +08:00
Jason 76b8620ffe fix(tests): align Sonnet tier expectations with claude-sonnet-5
The default Sonnet tier was bumped to claude-sonnet-5, but the TheRouter preset tests and ClaudeDesktopProviderForm tests still asserted claude-sonnet-4.6/4-6. Update the expected values to match the presets; input fixtures are left as-is to keep exercising legacy-route migration.
2026-07-01 23:55:55 +08:00
Jason 9079935d72 feat(presets): add NekoCode partner preset for 6 apps
Partner aggregator (New API gateway) across Claude Code, Claude Desktop,
Codex, OpenCode, OpenClaw, and Hermes -- no Gemini, since its /v1beta
surface falls through to the web app. Claude Code and Claude Desktop use
the bare host https://nekocode.ai; Codex, OpenCode, OpenClaw, and Hermes
use /v1 with gpt-5.5.

Marks isPartner with the ?aff=CCSWITCH referral on apiKeyUrl only (the
website URL and every API endpoint stay bare, so the attribution param
never rides on a real request). Adds the partnerPromotion blurb in all
four locales and a sponsor row appended to the end of all four READMEs,
surfacing the CC Switch offer: 10% off top-ups with promo code cc-switch.
Registers the logo-derived nekocode-icon.png via URL import; the README
banner is normalized to the standard 1920x798 aspect ratio.
2026-07-01 22:27:10 +08:00
Jason a8657d229a feat(presets): add Code0.ai partner preset for 7 apps
Partner aggregator (New API gateway) across Claude Code, Claude Desktop,
Codex, Gemini, OpenCode, OpenClaw, and Hermes. Claude Code, Claude
Desktop, and Gemini use the bare host (gemini-3.1-pro-preview for
Gemini); Codex, OpenCode, OpenClaw, and Hermes use /v1 with gpt-5.5.

Marks isPartner with ?source=ccswitch attribution on apiKeyUrl only
(website URL stays clean). Adds the partnerPromotion blurb in all four
locales and a sponsor row in all four READMEs. Positioned after
ClaudeAPI in the Claude Code and Claude Desktop lists (the two apps
that carry a ClaudeAPI preset). Registers the favicon-derived code0.png
icon via URL import; the README banner is normalized to the standard
1920x798 aspect ratio.
2026-07-01 22:27:10 +08:00
Jason cd9e025b5a feat(presets): switch Claude Sonnet tier default to Sonnet 5
Bump every claude-sonnet-4-6/claude-sonnet-4.6 default pin to claude-sonnet-5 across all provider presets (claude, claudeDesktop, hermes, openclaw, opencode, universal NEWAPI_DEFAULT_MODELS) and the Claude Desktop DEFAULT_PROXY_ROUTES sonnet route id. Update route-derivation test expectations accordingly. Non-Anthropic pins (gpt/gemini/glm/sonnet-4-5) left untouched.
2026-07-01 22:27:10 +08:00
Jason 778d5b9268 feat(pricing): add Claude Sonnet 5 model pricing
Seed claude-sonnet-5 at Anthropic list price ($3/$15 in/out, $0.30/$3.75 cache read/write per Mtok, matching Sonnet 4.6). The introductory $2/$10 promo through 2026-08-31 is intentionally not seeded. Applied on next app start via ensure_model_pricing_seeded; no SCHEMA_VERSION bump.
2026-07-01 22:27:10 +08:00
Jason 97512cabbd docs: document CC_SWITCH_GDK_BACKEND Linux Wayland escape hatch
Document the opt-in CC_SWITCH_GDK_BACKEND environment variable (added in
#4351) that overrides the AppImage's hardcoded GDK_BACKEND=x11, letting
Wayland+NVIDIA users switch back to native Wayland when the webview goes
click-dead and black-screens on resize. The override is generic, so
tiling-Wayland users can set it to x11 for the inverse input bug.

- CHANGELOG.md: new Unreleased/Fixed entry (#4351, fixes #4350)
- README.md / README_ZH / README_JA / README_DE: FAQ entry across all locales
- docs/user-manual/{zh,en,ja}/5-faq/5.2-questions.md: Linux troubleshooting entry
2026-07-01 22:27:10 +08:00
Jason 332a3c16a8 feat(presets): add Amux provider preset for 6 apps
Non-partner aggregator across Claude Code, Claude Desktop, Codex,
OpenCode, OpenClaw, and Hermes. Claude Code uses bare host
api.amux.ai; Codex uses /v1 native Responses; the other three apps
default to gpt-5.5. No Gemini preset. Registers the amux inline icon
(currentColor) in the icon index and metadata.
2026-07-01 22:27:10 +08:00
SaladDay 586fb46b10 fix(usage): keep date-range picker calendar on-screen in narrow popovers (#4860)
The custom date-range picker switched to its two-column layout (date
fields | calendar) based on the viewport width via Tailwind `sm:`
(640px). But the popover is clamped to `100vw - 2rem` and anchored to
its trigger with `align="end"`, so its actual available width is not the
viewport width. On narrow windows the wide two-column layout could
activate while the popover only had room for one column, pushing the
calendar column off the right edge of the window where it was clipped
and unusable (month header and 4 of 7 weekday columns cut off).

Gate the two-column layout on the popover's own inline size via a CSS
container query instead of the viewport, and let the popover width
shrink to fit the viewport. When the popover is genuinely wide it shows
two columns; when it is clamped narrow it stacks vertically so the
calendar stays fully visible. The base stacked layout is the safe
fallback for engines without container-query support.

Closes #4669
2026-07-01 16:33:07 +08:00
Nothing 251b13e5d2 feat(sessions): 新增会话分类视图与分组管理 (#4776)
* feat(sessions): 新增会话分类查看方式

* test(sessions): 补充会话分类视图覆盖

* feat(sessions): 适配分类视图批量管理

* test(sessions): 补充分类批量选择覆盖

* feat(sessions): 新增分类视图收起状态控制

* test(sessions): 补充分类收起状态覆盖
2026-07-01 12:23:46 +08:00
Arc f21d6f7a42 fix(i18n): rename "Write Common Config" checkbox to "Apply Common Config" (#4829)
* fix(i18n): rename "Write Common Config" checkbox to "Apply Common Config"

The original label "Write Common Config" (写入通用配置) was ambiguous
about data flow direction — it read as "write current config INTO the
common config" when the actual behavior is the reverse: merge the
saved common config snippet INTO this provider's config.

Rename to "Apply Common Config" across zh/zh-TW/en/ja, including all
hint/guide/notice references and component defaultValue fallbacks, to
make the action unambiguous. Also aligns the Gemini hint wording with
the claude/codex "when checked" phrasing.

* docs(ja): sync Japanese docs with renamed 'Apply Common Config' label

Codex review on #4829 pointed out the Japanese user manual and README
still referenced the old checkbox label after the rename.

- docs/user-manual/ja/2-providers/2.1-add.md: 共通設定を書き込み → 共通設定を適用
- README_JA.md: 共有設定を書き込む → 共有設定を適用
2026-07-01 11:58:31 +08:00
ayxwi ab3e628bad Fix scroll bounds for long select dropdowns (#4798)
Co-authored-by: Xvvln <180168103+Xvvln@users.noreply.github.com>
2026-07-01 11:57:17 +08:00
迷渡 8f484c54ce fix(detect): dedupe Windows Codex npm shims (#4782) 2026-07-01 11:33:40 +08:00
Bone 5546815441 fix(linux): allow overriding AppImage's forced GDK_BACKEND=x11 via CC_SWITCH_GDK_BACKEND (#4351)
The AppImage GTK hook (linuxdeploy-plugin-gtk.sh) hardcodes
`export GDK_BACKEND=x11`, forcing XWayland to avoid a historical Wayland crash
(tauri-apps/tauri#8541). On modern Wayland + NVIDIA setups this forced XWayland
instead makes the WebKitGTK webview unable to receive pointer events (GTK
titlebar clickable, web content completely dead) and black-screens on resize.

Read an opt-in CC_SWITCH_GDK_BACKEND var before GTK init (the hook does not
touch it) so affected users can switch back to native Wayland without unpacking
the AppImage. Default behavior is unchanged when the var is unset.

Refs #4350

Co-authored-by: BoneLiu <bone_liu@sina.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-30 23:26:51 +08:00
Jason 01bf003783 feat(presets): add TeamoRouter provider preset for 6 apps
Add TeamoRouter (enterprise Agentic LLM gateway) as a sponsor partner
across Claude Code, Claude Desktop, Codex, OpenCode, OpenClaw and Hermes.

- Claude Code uses bare host https://api.teamorouter.com; Codex uses
  https://api.teamorouter.com/v1 (native Responses); OpenCode/OpenClaw/
  Hermes use gpt-5.5 over the OpenAI-compatible /v1 endpoint. No Gemini.
- apiKeyUrl uses the English referral link with UTM params (in-app stays
  English; README links are per-language).
- Add localized in-app promo blurb (zh/en/ja/zh-TW).
- Add README sponsor rows below PatewayAI in all four READMEs.
- Register the teamorouter provider icon and pad the README banner to the
  standard 2.40 aspect ratio.
2026-06-30 23:01:49 +08:00
Jason e1e3dadf89 chore(icons): remove unused dds.svg orphan
dds.svg (1.4MB genuine vector, 2222 paths) was not imported in index.ts
nor referenced anywhere in src/, so it never shipped in the app or
appeared in the icon system — it only bloated the repo. Remove it.
2026-06-30 17:02:19 +08:00
Jason ba87e8f69d perf(icons): downscale hermes, claudecn and atlascloud icons to 256px
All three shipped well above their ~32px render size (hermes/claudecn at
512x512, atlascloud at 3525x3300). Downscale to a 256px max dimension:
hermes 125KB->38KB, claudecn 109KB->46KB, atlascloud 105KB->9KB. Same
filenames, no code change.
2026-06-30 17:02:19 +08:00
Jason 37f2e248dc perf(icons): shrink ccsub and shengsuanyun embedded-image SVGs
Both were "fake vector" SVGs wrapping a single oversized base64 PNG
(ccsub embedded 1446x1328 / 1.16MB, shengsuanyun 720x720 / 212KB),
rendered at ~32px. Downscale the embedded bitmap to a 256px max dimension
and re-embed, keeping the SVG wrapper, filename, and import unchanged
(no code change). Result: ccsub 1.16MB -> 60KB, shengsuanyun 212KB -> 51KB.
2026-06-30 17:00:53 +08:00
Jason 6f8e12a1ac perf(icons): downscale relaxcode and sudocode icons to 256px
Both shipped far larger than their on-screen render size: relaxcode was
1462x1076 / 1.16MB and sudocode 2048x2048 / 432KB. Downscale to a 256px
max dimension (aspect ratio preserved; ProviderIcon renders via <img>
object-contain), cutting them to ~41KB and ~36KB. Same filenames.
2026-06-30 16:50:38 +08:00
Jason 8fb6ebb6bd perf(icons): downscale ZetaAPI provider icon to 256px
The ZetaAPI icon shipped as a 1254x1254 / 940KB PNG, roughly 30x larger
than its on-screen render size (~32px in ProviderIcon). Downscale to
256x256, cutting it to ~40KB (-96%) so it no longer bloats the bundle.
Same filename, so no import/code change.
2026-06-30 16:49:35 +08:00
Jason e54a342301 feat(presets): add ZetaAPI provider preset for 6 apps
Add ZetaAPI (api.zetaapi.ai) as a partner aggregator preset across Claude
Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes (Gemini not
supported). ZetaAPI relays native Claude/GPT, so Claude Code/Codex pass
through native models; the OpenAI-compatible apps default to gpt-5.5.

- Claude / Claude Desktop: Anthropic-compatible bare host (api.zetaapi.ai)
- Codex: native Responses at api.zetaapi.ai/v1, gpt-5.5
- OpenCode / OpenClaw / Hermes: gpt-5.5 over api.zetaapi.ai/v1
- Partner referral link (zetaapi.ai/go/ccs) as apiKeyUrl + short
  partner-promotion blurb in zh/en/ja/zh-TW
- Add ZetaAPI sponsor entry to all four READMEs (zetaapi-banner.png),
  first-recharge 10% off with promo code CC-SWITCH
- Register zetaapi-icon.png icon (URL import + iconUrls + metadata)
2026-06-30 16:39:32 +08:00
Jason 997bad94f0 docs(kimi): point overseas READMEs to platform.kimi.ai and add Coding Plan link 2026-06-30 09:53:02 +08:00
Jason d4feaa4e53 chore(kimi): update referral links to new platform.kimi.com domain
Moonshot rebranded its console to Kimi, so refresh all Kimi sponsor
referral links across provider presets and READMEs:

- API (domestic): platform.moonshot.cn/console -> platform.kimi.com
- API key page: platform.moonshot.cn/console/api-keys -> platform.kimi.com/console/api-keys
- Coding Plan: www.kimi.com/code/docs/ -> www.kimi.com/code/

Also add the missing ?aff=cc-switch param to the codex and openclaw
entries that previously had no referral attribution. API endpoints
(api.moonshot.cn, api.kimi.com/coding) are intentionally left unchanged.
The overseas link (platform.kimi.ai) is not wired up yet since there is
no overseas API preset.
2026-06-30 09:15:04 +08:00
Jason 16f988bd1a feat(providers): auto-sync Claude common config from live on switch
When switching away from a Claude provider that opted into common config, re-extract the shareable portion of its live settings.json and replace the stored snippet. This captures config the user added directly in the app (plugins/hooks/shared prefs) so it isn't lost on switch, and propagates deletions so a removed key isn't re-injected on the next switch.

Scoped to Claude providers with common_config_enabled, skipped when the snippet was explicitly cleared. All failures are non-fatal (warn only) and never block the switch.

Also harden extract_claude_common_config to strip ALL credential-like keys via pattern match (*_API_KEY / *_AUTH_TOKEN / secret / token / etc.), not just ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN. Claude providers legitimately use OPENROUTER_API_KEY / GOOGLE_API_KEY (and may carry OpenAI/Gemini/AWS Bedrock/Vertex creds), which previously could leak into the shared snippet and be injected into other providers. This also fixes the pre-existing leak in the manual Extract and one-time auto-extract paths. Plural _TOKENS (e.g. MAX_OUTPUT_TOKENS) is preserved as shareable.

Tests: 4 integration (capture / delete-sync / opt-out / cleared) + 1 unit (credential stripping).
2026-06-29 23:30:58 +08:00
Jason 36e0378e78 feat(providers): show API key link in Claude Desktop, OpenClaw and Hermes forms
The "Get API Key" link (and partner promotion) below the API key input was
only wired for claude/codex/gemini/opencode. Claude Desktop uses a separate
form that never rendered it, and OpenClaw/Hermes were blocked by two gaps:

- useApiKeyLink whitelisted only 4 app ids, so the link was suppressed for
  claude-desktop/openclaw/hermes even when a preset carried apiKeyUrl.
- useProviderCategory only parsed claude/codex/gemini/opencode preset ids, so
  OpenClaw/Hermes category stayed undefined and the link condition
  (cn_official/aggregator/third_party) never held.

Changes:
- ClaudeDesktopProviderForm: call useApiKeyLink and replace the bare API key
  Input with the shared ApiKeySection.
- useApiKeyLink: add claude-desktop/openclaw/hermes to the whitelist and add
  ClaudeDesktopProviderPreset to the PresetEntry union.
- useProviderCategory: parse and resolve openclaw/hermes preset categories.
- Hermes/OpenClaw form fields: don't let an "official" category disable the
  API key input, since these apps have no OAuth-only official providers
  (e.g. Hermes' Nous Research is "official" but still needs a user key).
2026-06-29 23:30:58 +08:00
Jason 238cd5d7c9 feat(presets): add FennoAI provider preset for 6 apps
Add FennoAI (api.fenno.ai) as a partner aggregator preset across Claude
Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes (Gemini not
supported). FennoAI relays native Claude/GPT, so Claude Code/Codex pass
through native models; the OpenAI-compatible apps default to gpt-5.5.

- Claude / Claude Desktop: Anthropic-compatible bare host (api.fenno.ai)
- Codex: native Responses at api.fenno.ai, gpt-5.5
- OpenCode / OpenClaw / Hermes: gpt-5.5 over api.fenno.ai/v1
- Partner referral link as apiKeyUrl + short partner-promotion blurb in
  zh/en/ja/zh-TW
- Add FennoAI sponsor entry to all four READMEs (fenno-banner.png)
- Register fenno-icon.webp icon (URL import + iconUrls + metadata)
2026-06-29 23:30:58 +08:00
Jason 3476707321 feat(presets): add Qiniu (七牛云) provider preset for all apps
Add the Qiniu Cloud AI gateway (api.qnaigc.com primary, api.modelink.ai
overseas mirror) as a partner aggregator preset across Claude Code, Claude
Desktop, Codex, Gemini, OpenCode, OpenClaw, and Hermes.

Qiniu relays native Claude/GPT/Gemini, so Claude Code/Codex pass through
native models (no domestic-model pinning); the OpenAI-compatible apps
default to gpt-5.5.

- Claude / Claude Desktop: Anthropic-compatible bare host, native passthrough
- Codex: native Responses at /bypass/openai/v1, gpt-5.5
- Gemini: gemini-3.1-pro-preview via /bypass/vertex
- OpenCode / OpenClaw / Hermes: gpt-5.5 over OpenAI-compatible /v1
- Localized display name via nameKey + partner promotion blurb in zh/en/ja/zh-TW
- Register qiniu.png icon (URL import + iconUrls + metadata)
2026-06-29 23:30:58 +08:00
Jason 64a94ba3f7 chore(presets): update SiliconFlow referral link
Replace the SiliconFlow invite code drGuwc9k with YflgU2Ve across all
README locales and provider presets (claude, claude-desktop, codex,
hermes, openclaw).
2026-06-29 23:30:58 +08:00
Jason d916b4e12d fix(openclaw): sync Doubao context window to 262144
The OpenClaw DouBaoSeed preset hard-coded contextWindow 128000 while the
Codex preset/catalog uses 262144 for the same model, giving OpenClaw users
a too-small window that could compress or truncate long context early.
Align to 262144 and add a cross-preset consistency test asserting the
OpenClaw and Codex Doubao context windows stay equal, so neither side can
drift again.
2026-06-29 23:30:58 +08:00
Jason 7f83feb222 fix(presets): use dated Doubao model id and price 6-digit dated models
Volcengine Ark rejects the bare model name doubao-seed-2-1-pro with a 404
("model does not exist or you do not have access to it") even after the
model is activated; the API requires the full dated id
doubao-seed-2-1-pro-260628. Update the Doubao preset model id across all
apps (config default, generated catalog, and OpenClaw namespaced refs).

Pricing lookup only stripped 8-digit (YYYYMMDD) and ISO date suffixes, not
the 6-digit YYMMDD format Volcengine uses (-260628, -250615), so real
Doubao usage never matched the bare-name pricing seed and showed $0 cost.
Extend strip_model_date_suffix to also strip 6-digit YYMMDD (with
month/day validation to avoid eating non-date version suffixes), keeping
the bare-name pricing seed as the canonical identity. This also fixes
pricing for every other Volcengine Doubao model. Add unit and end-to-end
regression tests.
2026-06-29 23:30:58 +08:00
Jason 562480870d fix(presets): point Volcengine/Doubao/BytePlus website links to official sites
The websiteUrl for the 火山Agentplan, BytePlus and DouBaoSeed presets was
accidentally set to the same invite/console link as apiKeyUrl, so the
"visit official site" button took users to the referral/API-key page
instead of the product homepage. Restore clean official homepages across
all six app preset files; the apiKeyUrl referral links are kept intact.

- 火山Agentplan -> https://www.volcengine.com/product/ark
- DouBaoSeed    -> https://www.volcengine.com/product/doubao
- BytePlus      -> https://www.byteplus.com/en/product/modelark (drop utm)
2026-06-29 23:30:58 +08:00
Jason 85b38c1bed refactor(codex): decouple model mapping from local-routing toggle
Align the Codex provider form with Claude Code. Model mapping (the
catalog) is independent from route takeover: native Responses providers
(MiMo, Doubao, MiniMax) need it for direct connect with no proxy, while
Chat providers use the proxy regardless of any per-provider flag.

- Remove the "Needs Local Routing" toggle. It had no backend field and
  only gated catalog/reasoning persistence, which is equivalent to
  "is the mapping filled".
- Always show model mapping for non-official providers; persist when the
  list is non-empty (backend already keys off modelCatalog.models).
- Gate reasoning visibility/persistence on Chat format, not the toggle.
- Mark the Chat upstream-format option "routing required" and refresh the
  advanced-section hint (zh/en/ja/zh-TW); drop dead localRouting* keys.
- Move the model-mapping block above the custom User-Agent block.

fix(codex): preserve native-profile hidden catalog fields on edit

useCodexConfigState dropped supportsParallelToolCalls / inputModalities /
baseInstructions when loading a saved provider, so editing and saving a
native Responses provider lost parallel tools, image input and the
official base instructions from the generated catalog. Preserve them on
load (camelCase + snake_case) and compare them in the row sync. Add a
regression test.
2026-06-29 23:30:58 +08:00
Jason 26f0d221c0 fix(codex): reject web_search for Qwen3-Coder and correct LongCat context window
- Add `qwen3-coder` to the web_search reject model-prefix blacklist so the
  native qwen3-coder-plus direct-connect preset suppresses the built-in tool
  (百炼 rejects it for the coder series), while general Qwen models sharing the
  DashScope host keep web_search enabled. Matched on the model axis, not host.
- Correct LongCat-2.0-Preview context window from 128K to its real 1M
  (1048576), aligning with the MiMo/Qwen 2^20 convention.
- Tighten native Responses preset tests to assert exact model→contextWindow
  catalogs instead of only checking catalog presence.
2026-06-29 23:30:58 +08:00
Jason d380b410af fix(codex): disable web_search for native gateways that reject it
Some native /responses gateways whose first-party models lack OpenAI's
hosted web_search tool (MiMo, LongCat, MiniMax) reject a web_search tool
with "tool type 'web_search' is not supported by this gateway phase".
Codex sends the tool by default (config-driven, not gated by the catalog's
supports_search_tool), so cc-switch now writes the top-level
`web_search = "disabled"` line per those vendors' official Codex docs.

Scope is a blacklist (default-on): only providers matched by base_url host
or model brand prefix are disabled; relays serving real GPT, DouBao, Qwen,
and any unknown provider keep Codex's default. Matching by model brand (not
just host) also catches aggregators (e.g. SiliconFlow) fronting a reject
vendor's model. The field is injected alongside model_catalog_json at
switch time and removed via an ownership sentinel, so existing providers
need no re-save and switching back re-enables web search.
2026-06-29 23:30:58 +08:00
Jason 15e712e779 feat(codex): support native Responses direct-connect with generated model catalog
Codex providers can now run in two modes per provider:

- Proxy-Chat (route takeover): apiFormat=openai_chat, existing Responses<->Chat conversion. Unchanged.

- Native-Responses (direct): apiFormat=openai_responses, no proxy. cc-switch generates ~/.codex/cc-switch-model-catalog.json so Codex shows the custom models and tools work without the freeform apply_patch (type=custom) tool that native gateways like MiMo reject; editing falls back to shell_command.

Catalog generation is keyed on apiFormat (CodexCatalogToolProfile), decoupled from the takeover toggle, so native providers persist a catalog without enabling local route mapping.

Codex's catalog parser requires base_instructions on every entry; the native template carries a neutral default and per-vendor official text overrides it (MiMo, MiniMax). Synthesized catalogs for Qwen/Doubao/LongCat use the neutral default.

Existing native providers must be re-saved once to regenerate a valid catalog (no DB migration).
2026-06-29 23:30:58 +08:00
thisTom 61d7ac01fb fix(hermes): Windows 上 Hermes 供应商配置不生效 (#4680)
* fix(hermes): resolve config dir via HERMES_HOME and platform defaults

On Windows, CC Switch hardcoded `~/.hermes` as the Hermes config directory,
but Hermes resolves it through `get_hermes_home()`: `HERMES_HOME` env var,
then a platform default (Windows `%LOCALAPPDATA%\hermes`, mac/Linux
`~/.hermes`). So CC Switch wrote configs where Hermes never reads them and
provider changes had no effect (refs #3178).

`get_hermes_dir()` now mirrors Hermes' own resolution order:
  1. `settings.hermes_config_dir` — CC Switch explicit override
  2. `HERMES_HOME` env var — trimmed, non-empty, taken as-is (no `~`
     expansion, matching Hermes' `Path(val)`)
  3. platform default — Windows reads the `LOCALAPPDATA` env var (the exact
     value Hermes reads, not a re-derived Known-Folder path) and falls back
     to `~\AppData\Local\hermes`; mac/Linux keep `~/.hermes`

Relation to #3470: that PR dropped `HERMES_HOME` for "consistency with
Codex/Claude". But unlike those tools Hermes treats `HERMES_HOME` as a
first-class mechanism (its own Windows installer sets it), so ignoring it
reintroduces the same mismatch for relocated installs. This keeps it.

Tests cover HERMES_HOME precedence, settings-override > HERMES_HOME, blank
HERMES_HOME fall-through, the platform-correct default, and a pure
`windows_local_hermes_dir` helper exercising the LOCALAPPDATA-set and
LOCALAPPDATA-empty fallback paths on every host.

* test(hermes): isolate config-dir tests from ambient HERMES_HOME/LOCALAPPDATA

`get_hermes_dir()` now consults `HERMES_HOME` (all platforms) and `LOCALAPPDATA`
(Windows). The `with_test_home` helper only neutralized `CC_SWITCH_TEST_HOME`,
so an ambient `HERMES_HOME` — which Hermes' own Windows installer sets — would
make tests that write `get_hermes_config_path()` escape the temp home and touch
a real Hermes config (and the same hazard exists via `LOCALAPPDATA` on Windows).

Clear and restore both env vars in `with_test_home`. This is safe: only this
module reads those env vars, and `dirs` uses the Known-Folder API rather than the
env var. Adds a test asserting both are neutralized inside `with_test_home`.

Addresses the Codex review comment on #4680.

* fix(hermes): trim LOCALAPPDATA to match Hermes' .strip()

`windows_local_hermes_dir` checked `OsStr::is_empty()` on the raw value, but
Hermes does `os.environ.get("LOCALAPPDATA", "").strip()`. A whitespace/padded
`LOCALAPPDATA` would make CC Switch write under the literal padded path while
Hermes trims and falls back, hiding the config from Hermes. Trim before the
empty check, matching the existing `HERMES_HOME` handling. Adds
`windows_local_hermes_dir_trims_localappdata`.

Addresses the Codex review comment on #4680.

---------

Co-authored-by: thisTom <19346741+thisTom@users.noreply.github.com>
2026-06-28 17:49:52 +08:00
yyhhyyyyyy d1f6c74be8 fix(usage): treat usage_script credentials as explicit overrides (#4654)
* fix(usage): treat usage_script credentials as explicit overrides

* fix: treat usage script credentials as explicit overrides
2026-06-28 17:37:58 +08:00
Jason eb847642d0 docs(release-notes): add GitHub global top-100 milestone banner to v3.16.4 notes 2026-06-27 13:32:18 +08:00
Jason e50fc0eb28 docs: add v3.16.4 trilingual release notes and Codex custom-model FAQ
- Add v3.16.4 release notes in zh/en/ja.
- Add a trilingual FAQ explaining why custom models don't show in the Codex desktop model picker (upstream Codex Desktop login-identity gating, not a cc-switch bug) and the keep-official-login mitigation; cross-linked both ways with the official-auth preservation guide.
- Align the CHANGELOG 3.16.4 release date to 2026-06-27.
2026-06-27 11:57:20 +08:00
Jason f9547da930 chore(release): bump version to 3.16.4 2026-06-27 10:52:21 +08:00
Jason 844bbcf8c4 docs(changelog): record Fable 5 banner removal, refresh 3.16.4 stats
Add a Changed entry for the removed Fable 5 Verified commemorative banner (16922917) and refresh the stats line to the content-scoped count (53 commits | 126 files | +8,149 / -1,016), excluding the changelog meta commits.
2026-06-27 10:46:17 +08:00
Jason 16922917fb chore(about): remove Fable 5 verified commemorative banner 2026-06-27 10:34:14 +08:00
Jason 88f1a78e3a docs(changelog): add 3.16.4 release notes
Summarize the commits since v3.16.3 across Added/Changed/Fixed/Docs: the SubRouter and OpenCode Go partner presets, native Codex Responses migration for CN providers, proxy hardening (zstd decompression, OAuth-over-proxy, DeepSeek effort strip), and usage/pricing tooling (Volcengine Ark AK/SK queries, models.dev import, live date ranges, GLM-5.2/Doubao pricing).
2026-06-27 00:21:25 +08:00
Jason 90bc37449c fix(presets): sync OpenCode Go referral link and promo to Claude Desktop
The Claude Desktop OpenCode Go preset was missed by the referral/promo update that landed for Claude Code / Codex / OpenCode, so its websiteUrl pointed at the bare opencode.ai domain with no apiKeyUrl or partnerPromotionKey. Align it with the other three: websiteUrl -> /go, apiKeyUrl -> the ref=2YTRG2NGTX referral link, and partnerPromotionKey "opencode_go" so the in-app promo banner shows. All four OpenCode Go presets now carry the referral link and promo copy.
2026-06-27 00:21:19 +08:00
Jason de386b297f feat(presets): point SubRouter apiKeyUrl to aff referral link
Swap the SubRouter apiKeyUrl across all 7 client presets from the
neutral console/token page to the affiliate registration link
(?aff=l3ri), matching the project's referral-link convention.
Sync the preset test constant accordingly.
2026-06-26 23:49:08 +08:00
Jason e6d40d0a93 feat(presets): add OpenCode Go referral link and promo copy without partner badge
Decouple the in-app promotion banner from isPartner so a preset can show a
promo phrase plus referral link without earning the paid-partner star.

- ApiKeySection: gate the banner on partnerPromotionKey alone; the star is
  still driven solely by isPartner. This also un-suppresses the existing
  MiniMax cn/en promos, which already carried copy without isPartner.
- OpenCode Go (claude/codex/opencode): point apiKeyUrl at the referral
  link and add partnerPromotionKey "opencode_go" (no isPartner set).
- i18n: add the opencode_go promo string across zh/en/ja/zh-TW.
2026-06-26 23:39:18 +08:00
Jason dd6a951c34 feat(presets): add OpenCode Go subscription preset for Codex and OpenCode
Add OpenCode Go (opencode.ai/zen/go) provider presets across clients:

- Codex: openai_chat conversion with model catalog (GLM/Kimi/DeepSeek/MiMo), no static codexChatReasoning so per-model capability is inferred

- OpenCode: @ai-sdk/openai-compatible against /zen/go/v1

- Claude: add apiKeyUrl (opencode.ai/auth) and align websiteUrl to /go

Auth is a plain pasteable API key (no OAuth). Go splits wire format by model: OpenAI /chat/completions for GLM/Kimi/DeepSeek/MiMo, Anthropic /messages for MiniMax/Qwen; these presets target the chat-format models.
2026-06-26 23:39:18 +08:00
abing|web3.club 430ddf92bd Add SubRouter provider presets (#4522)
Co-authored-by: abingyyds <abingyyds@gmail.com>
2026-06-26 23:30:52 +08:00
Jason 8a91428b71 docs(readme): update Kimi sponsor copy to K2.7 Code
Refresh the Kimi sponsor blurb to the K2.7 Code release (coding-focused
agentic model, ~30% lower thinking-token usage vs K2.6) and bump the
banner alt text from K2.6 to K2.7 Code. EN/ZH copy provided by the
vendor; JA/DE translated to match.
2026-06-26 15:55:56 +08:00
Jason 6180c4ba12 docs(readme): add star-history global rank badge beside Trendshift 2026-06-26 11:26:59 +08:00
Jason f8768c5885 test(codex): sync chat preset snapshot after native Responses migration
Commit 273cc48c migrated 7 CN providers from openai_chat to native
openai_responses and refreshed model ids on the remaining chat-only
providers, but the codexChatProviderPresets snapshot was not updated,
breaking the unit tests on main.

Drop the migrated providers (DouBaoSeed, Bailian, Longcat, MiniMax,
MiniMax en, Xiaomi MiMo x2) from the chat list, sync GLM/StepFun/Ling
model ids, and add a test locking the migrated presets to
openai_responses with no modelCatalog (so the local route-mapping
toggle stays unchecked).
2026-06-26 09:43:33 +08:00
Jason 7d74d2449a docs(readme): replace Kimi sponsor banner with local images
Switch the Kimi K2.6 sponsor banner from the Moonshot CDN URL to
in-repo assets. Chinese README uses kimi-banner-zh.png; English,
Japanese and German use kimi-banner-en.png.
2026-06-26 09:15:51 +08:00
Jason 273cc48c57 feat(codex): use native Responses API for CN providers that support it
Several Chinese providers now expose a native OpenAI Responses API
endpoint, so Codex can reach them directly without the Responses->Chat
route-takeover conversion. Switch these presets to apiFormat
"openai_responses" and drop the now-unused codexChatReasoning and
modelCatalog (removing modelCatalog also keeps the "local route mapping"
toggle unchecked by default):

- Qwen / DashScope Bailian (/compatible-mode/v1/responses)
- Xiaomi MiMo + Token Plan (api.xiaomimimo.com/v1)
- Volcengine Doubao (/api/v3/responses)
- Meituan LongCat (/openai/v1)
- MiniMax CN + intl (/v1/responses, confirmed in the official API reference)

SiliconFlow-hosted MiniMax stays openai_chat (third-party endpoint, not
MiniMax's own base_url).

Also refresh stale model ids on the remaining chat-only providers:
GLM 5.1->5.2, StepFun 3.5-flash-2603->3.7-flash, Ling 2.5-1T->2.6-1T.
2026-06-26 09:15:51 +08:00
Jason f1328d89fc feat(skills): flag unmanaged skills with a green dot on the Import button
- Add an optional `enabled` flag to useScanUnmanagedSkills; the Skills panel
  scans once on mount (enabled:true), with 30s staleTime + keepPreviousData to
  dedupe disk IO across navigations.
- App subscribes to the shared query (enabled:false) and renders a green dot +
  tooltip on the top-bar Import button when unmanaged skills are available.
2026-06-26 09:15:51 +08:00
Jason a4eb5f3778 feat(codex): decouple upstream format selector from model-mapping toggle
The Codex provider form tied Chat-format conversion and route takeover (model
mapping) to one toggle, so a provider serving a native Responses API could not
use model mapping without forcing Chat Completions conversion.

- Promote the upstream format (Chat Completions / Responses) to an independent,
  always-visible selector that triggers no sub-menus on its own.
- The local-routing toggle now solely gates the advanced sub-sections: model
  mapping catalog, plus reasoning capability when the format is Chat.
- Persist modelCatalog / codexChatReasoning based on the takeover toggle and
  derive its initial state from saved catalog presence (no new persisted field).
- Refresh codexConfig i18n (zh/en/ja/zh-TW): add upstreamFormat* keys and reword
  the routing/advanced hints to reflect the decoupling.
- Fix codexChatProviderPresets test expectation for the Doubao Seed 2.1 Pro rename.
2026-06-26 09:15:51 +08:00
Jason 213f55a6d2 feat(usage): show direct Volcengine key console link in usage panel
The account-level AccessKey is buried in the Volcengine console menus,
so surface a clickable, visible link to the IAM key management page
(https://console.volcengine.com/iam/keymanage) right under the AK/SK
hint. Opens via settingsApi.openExternal; adds the volcengineKeyConsoleLink
label across all four locales.
2026-06-26 09:14:10 +08:00
Jason fdf538e52d feat(providers): upgrade DouBaoSeed preset to Doubao Seed 2.1 Pro
Point DouBaoSeed at doubao-seed-2-1-pro across all six clients (claude, claude-desktop, codex, opencode, openclaw, hermes), replacing doubao-seed-2-0-code-preview-latest. Sync display names to "Doubao Seed 2.1 Pro" and correct the openclaw cost field (0.002/0.006 -> 0.84/4.2 USD/1M) to match the new model.
2026-06-26 09:14:10 +08:00
Jason 2e547c98b1 feat(pricing): add Doubao Seed 2.1 Pro/Turbo model pricing
Volcengine official list price (CNY converted at ~7.14, USD/1M): pro input 0.84 / output 4.2 / cache-hit 0.17; turbo input 0.42 / output 2.1 / cache-hit 0.08. cache_creation kept 0 (Doubao bills cache storage by time, not per-token writes). Appended via INSERT OR IGNORE; 2.0 rows retained for historical usage accounting.
2026-06-26 09:14:10 +08:00
Chenx Dust 1a0e8c7a44 fix: decompress body before forward and support zstd (#3817)
* fix(proxy): decompress Codex request body before forward, support zstd

Codex Desktop sends zstd-compressed request bodies when authenticated
against the Codex backend, which broke local proxy routing because the
handlers parsed the raw bytes with serde_json directly.

Reworked on top of current main so it preserves the response_processor
behavior that landed after this PR was first opened:

- Extract content-encoding helpers into a shared proxy::content_encoding
  module. decompress_body keeps returning Option<Vec<u8>> so unknown
  encodings stay pass-through with their content-encoding header intact,
  and keeps the deflate zlib-then-raw fallback (RFC 9110).
- Add zstd/zst support (zstd 0.13) and disable reqwest's auto zstd
  decompression via .no_zstd() for parity with gzip/br/deflate.
- Decompress the request body before JSON parsing in the three Codex
  handlers (chat_completions / responses / responses_compact) and strip
  the stale content-encoding / content-length / transfer-encoding headers
  so the forwarder regenerates them.
- Support stacked codings (e.g. "gzip, zstd") by decoding in reverse
  order and merge repeated Content-Encoding headers via get_all.

Fixes #3764
Fixes #3696

Co-authored-by: chenx-dust <16610294+chenx-dust@users.noreply.github.com>

* fix(proxy): decompress upstream error bodies before reading them

The forwarder error branch consumes non-2xx responses via String::from_utf8
directly, bypassing read_decoded_body. reqwest has no auto-decompression
feature enabled, so a compressed error body (gzip/br/deflate/zstd) arrives
as raw bytes, fails from_utf8, and gets dropped, hiding upstream rate-limit
and auth details from the client.

Decode the error body with the shared proxy::content_encoding helper,
mirroring the success path. Falls back to the raw bytes when the encoding is
unsupported or decoding fails.

Co-authored-by: chenx-dust <16610294+chenx-dust@users.noreply.github.com>

---------

Co-authored-by: Jason <farion1231@gmail.com>
Co-authored-by: chenx-dust <16610294+chenx-dust@users.noreply.github.com>
2026-06-26 08:50:59 +08:00
zhaoyuan 524b9d9825 fix(proxy): 修复 Copilot/Codex OAuth 模块绕过全局代理导致 Claude 模型 400 错误 (#4583)
* fix(copilot): 修复 GitHub Copilot 出站请求不走全局代理导致 model not supported

* fix(proxy): 修复全局代理客户端配置未被应用到 Copilot/Codex OAuth 模块

两个关键问题:

1. CopilotAuthManager 在构造时写死 Client::new(),使得拉取 /models 列表、
   换取 token 等认证流程无视全局代理配置(global_proxy_url),直连目标服务。
   结果:直连时 /models 返回 0 个 Claude 模型 → live resolution 失效 →
   模型 ID 无法正确归一化/匹配 → Copilot 上游返回 400 model_not_supported。

2. CodexOAuthManager 也有完全相同的问题,导致 Codex OAuth 认证请求绕过代理。

改动:删除两个模块的自持 http_client 字段,改为每次请求时从全局客户端现取
(crate::proxy::http_client::get())。这样:
- 遵循全局代理 URL 配置
- 支持运行时热更新代理设置
- 符合代码库设计意图(http_client.rs 注释明确说"所有 HTTP 请求应使用此模块")

修复覆盖范围:
- copilot_auth.rs: 7 处调用(token 获取、/models 拉取、model vendor 判断)
- codex_oauth_auth.rs: 4 处调用(device code、OAuth token 刷新)

Fixes #2016 #2931
2026-06-25 16:05:23 +08:00
Jianfeng Mei 6fd4e6f462 feat(proxy): 添加本地代理请求覆盖功能,支持自定义请求头和请求体 (#4589)
* feat(proxy): 添加本地代理请求覆盖功能,支持自定义请求头和请求体

* fix(proxy): harden local request overrides validation

* feat(proxy): 添加受保护的本地代理请求头名称验证功能

* fix(i18n): 更新本地代理请求覆盖的错误提示信息格式

---------

Co-authored-by: jason.mei <jason.mei@ucloud.cn>
2026-06-24 22:19:01 +08:00
SaladDay edeee25fae feat(db): in-app recovery screen with upgrade button when DB version is too new (#4575)
* feat(db): in-app recovery screen with upgrade button when DB version is too new

When the SQLite user_version is newer than the app supports (SCHEMA_VERSION),
Database::init() fails and previously dead-ended in a native Retry/Exit dialog
(Retry just fails again). The app now boots a dedicated recovery screen instead.

- Detect the recoverable "version too new" case and surface it via init_status
  (kind="db_version_too_new" + db_version/supported_version); force-show the main
  window and skip normal AppState boot (recovery commands need only AppHandle).
- The recovery screen first checks for an available update:
  - update available  -> "Upgrade app" runs the updater (download + install +
    restart) with a download progress bar.
  - no update (already latest) -> warns that the DB is too new even for the latest
    build (likely a third-party client), so upgrading cannot help.
- install_update_and_restart now emits `update-download-progress` events; new
  `check_app_update_available` command.
- i18n: en / ja / zh / zh-TW.

Verified: pnpm typecheck + format:check + test:unit (351) green; cross-model
review of Rust correctness and recovery-mode safety (no AppState panic).

* fix(db): pre-check too-new DB before schema writes; exit on close in recovery mode

Addresses review feedback on the too-new-DB recovery flow.

- P1: stored_user_version_exceeds_supported() is now checked BEFORE
  Database::init(), so create_tables()'s DDL (incl. the unconditional
  DROP INDEX/DROP TABLE IF EXISTS failover_queue) never runs against a
  database whose user_version we cannot understand. The earlier
  post-init-failure recovery branch is removed; the pre-check is the
  single authoritative guard, so "don't write to a DB we can't read"
  now holds from the very first DB access.

- P2: the window CloseRequested handler now detects recovery mode
  (init_error kind = db_version_too_new) and exits the app instead of
  honoring minimize_to_tray_on_close. Recovery mode returns before the
  tray is created, so hiding the window would leave the app running with
  no tray to bring it back; native-close now quits cleanly.

Verified: cargo fmt --check clean; cross-model Rust review of both fixes
(compile-correctness + no normal-startup/close regression).
2026-06-24 15:07:42 +08:00
Tan Kimzeg 55abd1822c feat(ui): 为多处 JsonEditor 组件接入暗色模式 (#4556)
在为 UsageScriptModal、ProviderForm、UniversalProviderFormModal 中
的 JsonEditor CodeMirror 编辑器添加 darkMode 支持,使用 useDarkMode()
hook 监听 App 主题,自动切换 oneDark 编辑器主题。
2026-06-23 23:30:01 +08:00
Arc 9171ad752c feat(usage): add live end time option for custom date range (#4438)
* add glm-5.2 pricing

* feat(usage): add live end time option for custom date range

Add a "End time follows current time" checkbox in the custom date range
picker. When enabled, the end time becomes read-only and automatically
tracks the current moment, so usage data always reflects up-to-the-second
consumption from the chosen start time.

This is especially useful under the Coding Plan 5-hour quota window —
users can set the start time to when their 5h window began and keep
the end time live to monitor real-time token consumption.

* style(usage): fix prettier formatting for UsageDashboard

* fix(usage): include liveEndTime in React Query cache keys

Without liveEndTime in the query key, a live custom range and a fixed
custom range with the same stored endpoints share the same cache entry.
After the live range refreshes (endDate = now), switching to the fixed
range shows stale data fetched through "now" instead of the original
end time.
2026-06-23 23:04:00 +08:00
MoonDreamStars 2db3163cf2 ci: add Windows ARM64 release support (#3950)
* ci: add Windows ARM64 release artifacts

* ci: keep release matrix jobs independent

* ci: fix pnpm cache path on Windows runners

* ci: setup pnpm with corepack on Windows ARM64

* ci: fix Windows ARM64 release build

* ci: retry transient release bundler downloads

* ci: remove non-minimal release workflow changes

* ci: keep release matrix jobs independent

macOS signing fails in forks without Apple secrets and, with default
matrix fail-fast, cancels the sibling jobs (including Windows ARM64)
before they finish. Disable fail-fast so each platform runs to completion.

---------

Co-authored-by: MoonDreamStars <moondreamstar1@gmail.com>
2026-06-23 17:30:41 +08:00
Chen Yijun 169d58ac6f feat(provider): add CLAUDE_CODE_AUTO_COMPACT_WINDOW for Kimi For Coding preset (#4401)
Set the default Claude Code auto-compact window to 262144 for the
Kimi For Coding provider preset, matching the official Kimi docs:
https://www.kimi.com/code/docs/en/third-party-tools/other-coding-agents.html

Use templateValues so users can customize the value (e.g. for future
models or performance tuning) while keeping 262144 as the default.
2026-06-23 10:17:40 +08:00
thisTom 2781d40e82 fix(ui): 修复 Skills 管理与模型配置交互展示问题 (#4323)
* fix(ui): improve skills and provider interactions

* fix(skills): keep repo manager available on skills.sh

* test(skills): cover repo switch after refresh

* fix(skills): keep refresh available for empty repo results

---------

Co-authored-by: thisTom <19346741+thisTom@users.noreply.github.com>
2026-06-23 10:07:14 +08:00
makoMakoGo 2d478876fa fix: align Claude MCP path for custom config dirs (#3431)
* fix claude mcp path for custom config dir

* fix claude mcp custom profile isolation

* fix claude mcp override path edges

* fix ci test isolation
2026-06-23 09:00:56 +08:00
Jason 895d7af3eb docs(readme): add Kimi sponsor call-to-action link
Append a clickable CTA hook to the end of the Kimi K2.6 slogan in all
four README locales (en/zh/ja/de), pointing to the existing
aff=cc-switch Moonshot console link.
2026-06-22 17:59:06 +08:00
Jason 92930461b7 style(proxy): apply rustfmt wrapping to legacy function_call branch
CI cargo fmt --check failed on transform_codex_chat.rs (the wrapping
introduced upstream did not match rustfmt 1.95.0). Apply cargo fmt so the
chat_legacy_function_call_to_response_item call uses the expected layout.
2026-06-22 10:59:09 +08:00
Jason c797b2a3fb test(providers): align preset selector tests with official-first ordering
The official-first/prime-partner sort changed Original mode order, but the
selector tests still asserted the old raw array order. Update the three
stale assertions and add a dedicated case covering the prime-partner group
and the exclusivity rule (an official preset also flagged primePartner
stays only in the official group).
2026-06-22 10:53:00 +08:00
Jason c4630b5c26 feat(providers): add Volcengine Ark usage query with AK/SK signing
Query coding-plan / agent-plan usage for Volcengine Ark via the
control-plane OpenAPI (open.volcengineapi.com), which requires
account-level AccessKey signing rather than the inference API key.

- Implement Volcengine Signature V4 (an AWS SigV4 variant: fixed
  canonical header order, "HMAC-SHA256" algorithm without the AWS4
  prefix, scope ending in "request", service "ark") in
  services/coding_plan.rs
- Auto-detect the plan by probing GetAFPUsage (Agent Plan, AFP
  five-hour/weekly/monthly quotas) first, falling back to
  GetCodingPlanUsage (Coding Plan, session/weekly/monthly percentages);
  a single credential covers whichever plan the account holds
- Parse the real response shape: the window label lives in the `Level`
  field; guard ResetTimestamp <= 0 (session returns -1)
- Store account-level credentials on UsageScript (accessKeyId /
  secretAccessKey), threaded through both the test command and the
  TOKEN_PLAN auto-refresh path
- Add an independent AK/SK input block with a detailed hint pointing to
  the Volcengine console -> API Access Keys
- Add the `monthly` tier label (frontend TIER_I18N_KEYS + tray
  TIER_LABEL_GROUPS + subscription service)
- Sync zh / en / ja / zh-TW locales and the usage-query docs
2026-06-22 10:28:10 +08:00
Jason a3b3a06f5e feat(providers): tighten Add Provider header spacing and add footer hint
- Reduce title->tabs and tabs->card vertical gaps from 24px to 12px
- Add an always-visible footer hint guiding users to fill the fields
  below after choosing a preset (pinned footer, never scrolls off)
- FullScreenPanel: add optional contentClassName prop to scope content
  padding overrides without affecting the other panels that share it
- i18n: add provider.addFooterHint in zh/en/ja/zh-TW
2026-06-22 10:28:10 +08:00
Jason e648b7425e fix(providers): rename OpenCode/OpenClaw Kimi preset to "Kimi"
The OpenCode and OpenClaw presets were labeled "Kimi K2.7 Code", unlike
the plain "Kimi" used by the other apps. Rename the preset (and the
OpenCode provider display name) to "Kimi" for consistency; the model
label stays "Kimi K2.7 Code" since it describes the actual model.
2026-06-22 10:28:10 +08:00
Jason c26d867f79 feat(providers): order preset selector — official first, prime partner next
In the default (Original) sort mode, float official-category presets to
the very top, followed by prime partners (Kimi), then the rest in their
original array order. Implemented as a three-way partition+concat so each
group keeps its internal order and no preset is listed twice.
2026-06-22 10:28:10 +08:00
Jason 26be9324dd feat(icons): refresh Kimi logo, K adapts to theme via currentColor
Replace the inline Kimi placeholder mark with the vendor's refreshed
logo. The K glyph uses `currentColor` so it follows the theme text color
(dark in light mode, white in dark mode), while the brand accent dot is
pinned to the new #1783FF. Align the metadata fallback color accordingly.
2026-06-22 10:28:10 +08:00
Jason 142c8c1da7 feat(providers): rebrand CTok to ETok across presets, icons, and docs
The vendor renamed its domain, API endpoints, and trademark from CTok to
ETok. Update all user-facing branding accordingly:

- Presets (claude, claude-desktop, codex, gemini, hermes, openclaw,
  opencode): ctok.ai -> etok.ai, api.ctok.ai -> api.etok.ai, internal
  provider id ctok -> etok, display name CTok.ai -> ETok.ai
- Icons: replace inline placeholder SVG with the new ETok brand PNG,
  moved from `icons` to `iconUrls`; key ctok -> etok; banner logo
  ctok.png -> etok.png
- README (en/zh/ja/de) partner banner: new logo, links, and copy
- i18n (en/ja/zh/zh-TW): partnerPromotion key ctok -> etok

Keep "ctok" in the Codex history-migration whitelist as a legacy id and
add "etok", so existing users' local session history stays correctly
bucketed after the rename.
2026-06-22 10:28:10 +08:00
PENG 6ec86cff46 docs: remove deprecated Homebrew tap step (#4319) 2026-06-22 09:55:51 +08:00
Huei Feng 455556380b Chat API: skip tool calls with missing function names (#4159)
* Chat API: skip tool calls with missing function names

Some providers send empty or absent function names in streaming
tool call deltas. Previously these produced invalid output items.

- Don't overwrite accumulated state.name with empty deltas
- Skip tool calls that never received a valid name (instead of
  falling back to 'unknown_tool')
- Apply the same defensive guard in finalize_tools and the
  non-streaming path

* Address review: defer empty-name skip to finalization

Require both call_id and name before triggering should_add,
instead of skipping eagerly when name is absent in the first
delta.  This handles providers that send id before name,
as suggested in the Codex review.

* Guard legacy function_call against empty name

Return Option<Value> from chat_legacy_function_call_to_response_item,
returning None when function_call.name is missing or empty. This covers
the legacy message.function_call path that the original guard missed.

* Remove unreachable unknown_tool fallback

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-06-19 23:38:25 +08:00
Arc 510aa250c5 add glm-5.2 pricing (#4385) 2026-06-18 23:24:20 +08:00
Jason d1b5df9a7b docs(partners): point Volcengine Coding Plan link to ai618 campaign 2026-06-18 17:43:11 +08:00
Jason dfa03b746a feat(providers): add prime-partner heart badge for Kimi presets
Introduce an optional primePartner flag on all provider preset interfaces.
Regular partners keep the gold star badge; prime partners render a solid
gold heart (no badge frame). Mark the first-party Moonshot Kimi presets
(Kimi / Kimi For Coding / Kimi K2.7 Code) across claude, codex, claude
desktop, opencode, openclaw and hermes as prime partners.
2026-06-17 13:04:23 +08:00
Jason 3d30dc03e8 docs(partners): swap pinned banner from MiniMax to Kimi K2.6 2026-06-17 11:54:36 +08:00
Jason 95495ad19e docs(partners): swap CCSub banner to high-res SVG, aligned aspect ratio
Replace the low-res ccsub.jpg with a vector SVG. Letterbox it from
2046x648 (3.157:1) to 2046x850 (~2.406:1) so it matches the other
sponsor-table banners and renders at the same height (62px @ width=150).
Point all four README locales at the new asset.
2026-06-17 11:10:39 +08:00
Jason b724f5dde9 revert(proxy): drop Anthropic system-message hoisting (#3775)
The unrelated Windows test fixes from #3775 are kept; tool-thinking-history normalization is unchanged.

Refs #4297
2026-06-16 22:39:27 +08:00
Jason 69341db284 fix(codex): probe CODEX_SQLITE_HOME when locating state DB for history migration
The session-history migration only scanned ~/.codex/state_5.sqlite and the
config.toml `sqlite_home` location. When Codex's SQLite state is relocated via
the CODEX_SQLITE_HOME env var, the state DB was never scanned and its threads
kept their old provider bucket. Add a CODEX_SQLITE_HOME fallback (config
`sqlite_home` still takes precedence) in the shared codex_state_db_paths helper
used by both the third-party and unified-session history migrations, plus serial
env tests.
2026-06-16 22:34:00 +08:00
Xinyu Kuo 0bb3b7515a feat(usage): support importing model pricing from models.dev (#4079)
* feat(usage): support importing model pricing from models.dev

Add an "Import from models.dev" button to the Add Pricing panel that
fetches https://models.dev/api.json, lists priced models sorted by
release date (newest 50 by default, full-text search across ~4800),
and bulk-imports the selected entries through the same
update_model_pricing command as manual entry.

- Normalize imported model IDs to match the backend's
  clean_model_id_for_pricing rules (strip vendor prefix, lowercase,
  truncate ':' suffix, map '@' to '-', drop the [1m] marker) so the
  stored rows actually match cost-attribution lookups
- Dedupe selections that collapse to the same model_id and report
  skipped duplicates in the success toast
- Invalidate usage queries on settled (not just success) so partial
  import failures still refresh the pricing list
- Keep ESC inside the picker's search input from closing the dialog
  and discarding the selection
- Add i18n keys for zh/en/zh-TW/ja and unit tests for the
  normalization, price formatting and flattening logic

Fixes #4017

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(usage): match scoped cost backfill against raw model aliases

The scoped backfill selected zero-cost rows via exact SQL string match,
but log columns store raw model strings (route prefixes, :free variants,
date suffixes), so alias rows were skipped until the next full backfill
on startup. Filter rows in Rust with the same model_pricing_candidates
normalization used by the pricing lookup; pricing decision logic is
untouched. Pre-existing gap from schema v11, surfaced by bulk import.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(usage): restrict models.dev pricing import to a single model

Each update_model_pricing call triggers a backfill pass that loads
every zero-cost usage row before filtering by model, so bulk-importing
N entries scaled as selectedModels x allZeroCostLogs full scans.
Re-importing pricing is rare, so drop the batch path instead of
optimizing it: the picker is now single-select, one import runs exactly
one update_model_pricing call and one backfill pass. This also removes
the normalized-ID dedup logic and the useImportModelPricing hook in
favor of the existing useUpdateModelPricing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 22:01:56 +08:00
Ruixe Wolf 81d6002ace 修复 添加供应商页面 搜索预设后无法点击选中搜索结果 (#4315)
* fix(provider-preset-selector): after searching presets, it is impossible to select search results.
feat(provider-preset-selector): add keyboard shortcut for search input and improve focus handling.

* fix(provider-list): prevent keydown event from triggering when default is prevented

* fix(provider-preset): keep preset clickable after search and restore keyboard UX

- ProviderList: scope the typing guard to the Ctrl/Cmd+F branch so Escape
  still closes the search panel (the top-level early return swallowed it);
  reuse isTextEditableTarget instead of re-implementing the check.
- ProviderPresetSelector: drop the rAF select() that raced with typing and
  ate the first character (gateway -> ateway), and restore the input
  autoFocus for the open-by-click path; refocus via rAF when Ctrl/Cmd+F is
  pressed while the box is already open so focus returns to the input.
- Add a regression test for the re-focus-on-shortcut behavior.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-06-16 17:51:23 +08:00
Sean Wang caa912e3a3 fix: prevent duplicate codex base_url entries (#4316) 2026-06-16 17:01:01 +08:00
Zhou Kai 1042fb2a32 fix(terminal): respect user shell for provider terminals (#4140)
* fix(terminal): detect user default shell instead of hardcoded bash

All macOS/Linux terminal launch functions in misc.rs hardcoded `bash` as
the execution shell, causing zsh users' .zshrc to not load. Now detect
the user's default shell via $SHELL (macOS fallback /bin/zsh, Linux
fallback /bin/bash) and use it consistently across shebang, AppleScript,
spawn args, and interactive shell flags.

- Add get_user_shell(), get_shell_name(), interactive_flags_for_shell()
- Replace 10 hardcoded bash locations with dynamic shell detection
- zsh gets --norcs --no-globalrcs, bash keeps --norc --noprofile
- run_tool_lifecycle_silently unchanged (bash-specific syntax)
- Fixes #1546, Related #2385

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

* fix(terminal): use POSIX sh for script execution, user shell for interactive session

Address code review issues:
1. Replace shell-specific `read -n 1 -s`/`read -k 1 -s` with POSIX `read -r _`
   (press Enter to close) — ensures portability across bash/zsh/fish/dash
2. Unify AppleScript to use `sh` consistently (not mixing shell/shell_name)
3. Protect fish users: scripts always interpreted by POSIX sh, not fish
   (fish doesn't support trap/exec). exec line switches to user's shell.
4. Use build_exec_line to avoid trailing space when interactive_flags is empty

All terminal launchers now execute scripts via `sh`. Script shebangs are
`#!/bin/sh`. The exec line at script end switches to the user's detected
shell with appropriate clean-start flags. Terminal launcher functions no
longer need shell/shell_name parameters — simplified signatures.

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

* fix: validate user shell for terminal launch

* fix: load user shell config after terminal command

* test: align terminal shell exec expectations

* refactor(terminal): remove dead code, quote Warp path, unify shebangs

- Remove `interactive_flags_for_shell` (always returned "") and
  `get_shell_name` (no longer needed after removing flags); simplify
  `build_exec_line` to single-arg form
- Quote the Warp launcher script path with `shell_single_quote` for
  consistency with the main launcher scripts
- Unify all script shebangs to `#!/usr/bin/env sh` for better
  portability (e.g. NixOS where /bin/sh may not exist)

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

* fix(terminal): fix linux shell exec helper call

* fix(terminal): run provider command through user shell

* fix(terminal): validate user shell executable

* fix(terminal): avoid interactive provider shell job

* fix(terminal): harden user shell launcher

Load zsh provider commands through the user's login and interactive environment, preserve launch cwd handling, and replace Terminal/iTerm launcher shells so the final user shell is restored cleanly.

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-16 16:54:25 +08:00
Xu Song de0a149df5 feat(session-manager): show source file name in session detail header (#4113)
* feat(session-manager): show source file name in session detail header

Display the session log file name (with full path on hover) alongside
the project directory, so users can locate and copy the underlying
JSONL file directly from the UI.

* fix(session-manager): truncate long source file name in detail header

Long, space-less JSONL basenames (e.g. Codex rollout files at ~70 chars)
overflowed the flex meta row and bled into the action-button area on
narrow windows. Mirror the sibling project-dir span by capping the
filename at max-w-[200px] with truncation; the full path stays available
via the hover tooltip and click-to-copy.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-06-16 12:08:48 +08:00
chen-985211 36b557b2e6 fix(codex): restore cached tool call fields (#4160)
* fix(codex): restore cached tool call fields

* refactor(codex): merge duplicate enrich loops in chat history

enrich_call_item_from_cache copied the fill-if-empty loop for
reasoning_content/reasoning. The two loops are identical and key
order is irrelevant, so fold both key sets into a single loop.

Pure refactor, no behavior change; codex_chat_history tests pass.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-06-16 10:59:16 +08:00
Mask 3e38889ccc feat(proxy): strip effort params when thinking:disabled for DeepSeek endpoint (#4239)
DeepSeek's Anthropic-compatible endpoint rejects requests where
thinking.type=disabled coexists with effort parameters, returning
HTTP 400. This breaks Claude Code 2.1.166+ sub-agents (Workflow/Dynamic
Workflow), which hardcode thinking:disabled.

Rather than overriding thinking:disabled, remove the conflicting effort
parameters (output_config.effort / reasoning_effort) to respect Claude
Code's intent — sub-agents don't need to display reasoning.

Fixes: https://github.com/deepseek-ai/DeepSeek-V3/issues/1397

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 10:23:16 +08:00
muleizh 12567b3229 fix(settings): reset scroll on tab switch (#4165) 2026-06-16 08:29:36 +08:00
Jason c548e7fcba docs(guides): add trilingual Codex unified session-history guide
New zh/en/ja guide for the unified Codex session-history toggle: what opt-in migration (on enable) and ledger-based restore (on disable) actually do, why session data is never truly deleted (tag-only rewrite + automatic backups), and how to verify files on disk versus just being filed under another provider drawer. Includes a symptom reference table for the common "my sessions are gone" misunderstanding and on-disk verification commands for macOS/Linux/Windows.

Link the guide as the lead item in the "Usage Guides" section of the v3.16.3 release notes (zh/en/ja).
2026-06-15 10:17:25 +08:00
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
Jason c67494bafc docs: clarify Codex guide usage in release notes 2026-06-01 22:11:33 +08:00
Jason 256b04999c docs: add Codex official auth preservation guide 2026-06-01 22:01:35 +08:00
Jason 25951d8132 chore(release): bump version to 3.16.1 and add release notes 2026-06-01 17:55:55 +08:00
Jason d66030bee6 Stream Codex custom tools with native input events
Custom (freeform) Codex tools are bridged through Chat Completions as
JSON `{"input": "..."}` functions, but the Chat->Responses stream still
re-emitted them via `response.function_call_arguments.*`, leaking the
JSON wrapper and using event types the Codex client does not route for
freeform tools.

Emit `response.custom_tool_call_input.delta`/`.done` (with the unwrapped
input text) for custom tool calls instead, suppressing the intermediate
function-argument deltas since a partial `{"input":` fragment cannot be
safely unwrapped mid-stream. Custom tool call items now use a `ctc_`
item-id prefix (matching the input events' item_id) consistently across
the streaming and non-streaming paths via a shared
response_tool_call_item_id_from_chat_name helper.

Covered by new streaming and non-streaming custom-tool tests.
2026-06-01 17:01:00 +08:00
Jason 5968336364 Restore Codex tool plugins over Chat Completions third-party proxy
When proxying Codex Responses requests through the Chat Completions
format (api_format=openai_chat), the request transform only forwarded
plain `function` tools and silently dropped `tool_search`, `namespace`
(MCP), and `custom` tools, so third-party APIs never saw the official
Codex plugins and could not call them.

Introduce CodexToolContext, built from the original Responses request,
which flattens all four tool kinds into Chat functions and keeps a
chat_name -> CodexToolSpec map. The response path (streaming and
non-streaming) looks names up in this map to restore the original
tool_search_call / custom_tool_call / namespaced function_call items
instead of reparsing the flattened name. Long namespaced names are
truncated with a sha256 suffix to fit the 64-char Chat tool-name limit.

Covered by new round-trip tests for all four tool kinds across both
streaming and non-streaming paths.
2026-06-01 16:29:23 +08:00
Jason b7499fc871 Refresh Codex provider label on proxy takeover hot-switch
During proxy takeover, switching third-party Codex providers left the
client-visible provider name stale: sync_codex_live_from_provider_while_proxy_active
based the live config on the existing live file and only patched
base_url/wire_api/model, never refreshing model_provider or
model_providers.<id>.name. The Codex app kept showing the previous
provider in its bottom-right label.

Rebuild the effective settings from the DB for the selected provider so
the live config carries the correct provider key and display name, then
merge MCP servers back from the existing live config. base_url stays
pointed at the local proxy, and official OAuth in auth.json is untouched
(takeover writes config.toml only when auth preservation is enabled).

Generalize preserve_codex_mcp_servers_in_backup ->
preserve_codex_mcp_servers_from_existing_config since it now serves both
the backup and live-sync paths.
2026-06-01 15:16:13 +08:00
Jason aeaa016cae Simplify Codex takeover notice copy and match hint styling
Restyle the proxy-takeover notice in the Codex editor from the boxed
Alert to the amber inline-hint style used by the endpoint hints, and drop
implementation jargon (127.0.0.1 / PROXY_MANAGED) that users could not
interpret. The notice and the auth/config hints now simply state that the
form shows the stored provider config rather than the proxy-managed live
config. i18n synced across en/zh/ja/zh-TW.
2026-06-01 11:41:05 +08:00
Jason 2a131a5572 Harden Codex takeover ownership signaling and serialize switch/takeover
Gate provider sync and switching on the restore backup / live placeholder
("is this live file owned by takeover?") instead of the lagging
proxy_config.enabled and proxy-running flags. The backup is created
before enabled=true is committed, so during that activation window the
old guards were blind and a concurrent sync/switch could rewrite the
taken-over live file, clearing Codex auth.json for a mis-categorized
provider.

Acquire a per-app switch lock around both set_takeover_for_app and
provider switching so the two cannot interleave, splitting the locking
entry points into outer (lock) / inner (no-lock) pairs to stay
deadlock-free. Preserve the official OAuth auth in provider-rebuilt
restore backups by routing the provider token into config.toml. Refine
takeover idempotency to require the live config to point at the current
proxy URL, rebuilding from backup when it does not.

Add unit and integration tests covering the official -> DeepSeek ->
takeover on/off lifecycle and the stopped-proxy switch path.
2026-06-01 11:41:05 +08:00
Jason a04e72a267 Fix Codex edit dialog masking live OAuth during proxy takeover
The reported "OAuth access token disappears when enabling Codex proxy
takeover" was a display artifact, not data loss: auth.json on disk kept
the OAuth login the whole time. During takeover the edit dialog falls
back to the stored provider config (so it does not surface the proxy
placeholder), which for a third-party provider shows that provider's own
key instead of the live auth.json, making the OAuth token look gone.

Thread an isProxyTakeover flag from App through ProviderForm into the
Codex editor and show an explicit notice plus storage-aware auth/config
hints clarifying that the form displays the stored provider config while
the live config is temporarily managed by the proxy. Drop the
proxy-running condition so the notice shows whenever takeover is active,
even with the proxy stopped.

Add a regression test asserting the dialog does not read live settings
during takeover and renders the database config. i18n synced across
en/zh/ja/zh-TW.
2026-06-01 11:41:05 +08:00
Jason ce993baefa Fix Codex OAuth auth cleared on takeover when provider mis-categorized
Preserve-mode takeover routes the PROXY_MANAGED placeholder into
config.toml and must leave auth.json (the ChatGPT OAuth login) intact.
c9cadd6e covered only the None-provider write branch; the
Some(provider) branch still ran the category-based auth decision in
codex_config::write_codex_live_for_provider, whose first clause
(category == "official" && has_login_material) ignores the preserve
flag entirely. Because takeover stamps OPENAI_API_KEY = PROXY_MANAGED
into auth, codex_auth_has_login_material returns true, so a provider
stored with a stale/mis-classified "official" category (e.g. DeepSeek)
had its real auth.json overwritten with the placeholder — the access
token vanished on takeover and reappeared on cleanup.

Fix at the takeover entry instead of patching the fragile category
logic: add write_codex_takeover_live_for_provider, which under
preservation detects the PROXY_MANAGED placeholder in auth and writes
only config.toml (bearer token + catalog projection), never touching
auth.json. Gating on the placeholder is orthogonal to category, so any
mis-classification is handled. All four takeover sites
(sync-while-active, takeover_live_configs, _strict, _best_effort) now
route through it; restore (verbatim) and non-takeover provider writes
are unchanged.

Also projects the model catalog via
prepare_codex_live_config_text_with_optional_catalog, so the
model_catalog_json pointer survives takeover too.

Add a regression test: official-category provider + preserve enabled +
proxy takeover must keep auth.json byte-identical while moving the
placeholder into config.toml.
2026-06-01 11:41:05 +08:00
Jason d5328e5290 Fix Codex model catalog lost on proxy takeover-off restore
Turning proxy takeover off restores Live from a stored backup via
write_codex_live_verbatim. That path mishandled the Codex model catalog
for two backup shapes that need opposite treatment:

- Snapshot backup (read_codex_live_settings -> {auth, config}): no inline
  modelCatalog, but the config.toml text already carries the live
  model_catalog_json pointer. The old code ran catalog projection, which
  saw no specs and stripped the pointer.
- Provider-rebuilt backup (update_live_backup_from_provider): inline
  modelCatalog (DB SSOT) with a pointer-less config text. A pure verbatim
  write ignored the inline catalog and never regenerated the pointer.

The projection decision is orthogonal to auth: a provider-rebuilt backup
can pair an inline modelCatalog with empty auth.json ({}) when the API key
lives in the config's experimental_bearer_token. The empty-auth branch
raw-wrote config and skipped projection entirely, so that shape lost its
mapping too.

Decide the config.toml text once, before splitting on auth, via the new
prepare_codex_live_config_text_with_optional_catalog helper: project only
when an inline modelCatalog is present, else keep the text raw (preserving
any existing pointer). Every config-writing branch (write-auth,
delete-auth, no-auth) now applies it consistently. Add regression tests
covering all three shapes.
2026-06-01 11:41:05 +08:00
Jason 0fbba4267c Fix Codex model catalog being wiped by live-config backfill
`modelCatalog` is a cc-switch-private field whose SSOT is the database; Live's
config.toml only carries a lossy `model_catalog_json` projection. Proxy
takeover/restore cycles and the official Codex.app rewriting config.toml can
drop that projection, so `read_live_settings` reconstructs an empty catalog.
Two paths then overwrote the stored mapping with that empty Live snapshot:

- Switch-away backfill (`switch_normal` -> `restore_live_settings_for_provider_backfill`):
  now overlays the DB provider's `modelCatalog`, falling back to the
  Live-reconstructed one only when the DB has none.
- Edit dialog (`EditProviderDialog`): when editing the active Codex provider it
  preferred Live over the DB SSOT; now keeps the DB `modelCatalog` so opening +
  saving no longer clears the mapping table.

Add Rust backfill tests (preserve DB catalog when Live lacks it; keep Live
catalog when DB has none) and a frontend regression test for the edit dialog.
2026-06-01 11:39:22 +08:00
oasis 8bf1660237 fix(codex): always update model catalog JSON on provider switch (#3360)
* fix(codex): always update model catalog JSON on provider switch

Without this fix, the cc-switch-model-catalog.json file and the
model_catalog_json field in config.toml were only regenerated when
should_sync_backup was true (proxy active or backup exists). Switching
providers while the proxy was idle left the catalog pointing at the
previous provider's models, requiring a full restart to take effect.

After the existing should_sync_backup block, unconditionally call
write_codex_provider_live_with_catalog when switching a Codex provider
and the proxy is not currently active (live_taken_over == false). This
mirrors what live.rs already does during a normal provider apply.

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

* fix(codex): refresh catalog on restored hot switch

---------

Co-authored-by: yueqi.guo <guo_yueqi@qq.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-06-01 11:38:07 +08:00
Siskon afa09e127e fix(usage): resolve per-app credentials for native balance/coding-plan queries (#3355)
* fix(usage): resolve per-app credentials for native balance/coding-plan queries

The native usage-query paths (balance + coding_plan) in
`query_provider_usage_inner` read credentials only from `env.ANTHROPIC_*`.
That matches Claude providers, but Codex stores its key in
`auth.OPENAI_API_KEY` with the base URL inside a TOML `config` string,
Hermes/OpenClaw flatten them at the top level, and OpenCode nests them under
`options`. So the card "refresh usage" / auto-query returned empty
credentials and failed ("查询失败") for those apps, even though the
config-page "Test" button worked (the frontend extracts per-app correctly).

Introduce a single per-app resolver `Provider::resolve_usage_credentials`
that mirrors the frontend `getProviderCredentials`, and route both native
branches through it. Add `extract_codex_base_url` to `codex_config` as the
canonical Codex TOML base-URL parser and make the proxy adapter delegate to
it (removing a duplicate copy). Align the frontend `getProviderCredentials`
to cover OpenCode and Claude Desktop and to use the same OpenRouter/Google
key fallbacks as the backend.

Fixes #3158
Fixes #3100
Fixes #2625

* refactor(usage): explicit AppType arms + frontend trailing-slash trim

Address two review nits on the per-app credential resolver:

- provider.rs: replace the catch-all `_` arm in resolve_usage_credentials with an explicit `AppType::Claude | AppType::ClaudeDesktop` arm, so a new AppType variant fails to compile here instead of silently defaulting to the Anthropic env shape.
- UsageScriptModal.tsx: normalize getProviderCredentials baseUrl through a single trailing-slash trim so the frontend 'Test' path matches the backend resolver (trim_end_matches), keeping front/back truly in lockstep.

No behavior change for well-formed configs; tests/typecheck/fmt/clippy clean.

* fix(usage): skip empty primary credential fields in fallback chain

`obj.get(key)` returns `Some` for a present-but-empty field, so the
`.or_else()` fallback chains for the Claude/ClaudeDesktop and Gemini api-key
lookups only skipped *absent* keys, not empty ones. Presets seed fields like
`ANTHROPIC_AUTH_TOKEN` as present-but-empty placeholders, so a provider whose
real key lives in a fallback field (`ANTHROPIC_API_KEY` / `OPENROUTER_API_KEY`
/ `GOOGLE_API_KEY`, or `GOOGLE_API_KEY` for Gemini) resolved to an empty key on
the native balance/coding-plan path — while the frontend `a || b` (which skips
empty strings) still found it, reproducing the same Test-works / refresh-fails
divergence this PR removes.

Add a `first_non_empty` helper that skips present-but-empty values, matching
the frontend `||` semantics, and use it for both fallback chains. Tests cover
empty primary + populated fallback for Claude and Gemini.
2026-06-01 08:43:40 +08:00
Eunknight 0960fd7179 fix: Claude Desktop 官方供应商添加报错 #3402 (#3405)
* fix: Claude Desktop 官方供应商添加时缺少 ANTHROPIC_BASE_URL 报错

根因:前端 mutation 为 claude-desktop 生成随机 UUID 作为 provider id,
后端 is_official_provider 通过 id 匹配跳过校验,随机 UUID 不匹配导致
走入普通 direct 模式校验并要求 ANTHROPIC_BASE_URL。

修复:
- 前端:claude-desktop + category=official 时使用固定 id "claude-desktop-official"
- 后端:validate_provider / validate_direct_provider / validate_proxy_provider /
  apply_provider_to_paths 增加 category=="official" 兜底检查

Fixes #3402

* fix: restrict Claude Desktop official provider detection

* fix: add Claude Desktop official provider via seed

---------

Co-authored-by: 金恩光 <enguang.jin@gmail.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-05-31 23:37:31 +08:00
Zhiqi Yao 5ef72a2030 fix(codex): add multi-platform CLI discovery and static gpt-5.5 template fallback (#3382)
* fix(codex): add multi-platform CLI discovery and static gpt-5.5 template fallback for model catalog generation

When cc-switch generates a Codex model catalog for third-party providers,
it needs the gpt-5.5 model definition as a template. Previously it relied
on either ~/.codex/models_cache.json (only exists when Codex has connected
to OpenAI) or running 'codex debug models --bundled' (fails when codex
is not on the Tauri app's PATH, common in macOS GUI environments).

This commit adds a three-tier fallback:
1. Try 'codex' from PATH, then platform-specific common paths
   (/opt/homebrew/bin/codex, /usr/local/bin/codex, etc.)
2. If all CLI attempts fail, use a compile-time embedded gpt-5.5
   template (extracted from codex 0.135.0 bundled models)

Also adds tests for the static template validity and CLI candidates.

* fix(codex): discover user node codex installs

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-05-31 22:48:27 +08:00
Haoyu Wang e02a2763c2 fix: add kimi/moonshot to Anthropic tool thinking history normalizer (#3377)
* fix: add kimi/moonshot to Anthropic tool thinking history normalizer

Kimi's Anthropic-compatible endpoint requires reasoning_content in
assistant tool call messages when thinking is enabled, same as DeepSeek.
The is_reasoning_content_compatible_identifier already included kimi/moonshot
but is_anthropic_tool_thinking_history_identifier was missing them, causing
400 errors on multi-turn conversations with tool calls.

Closes #3351

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

* refactor: unify reasoning vendor hints into a single SSOT list

Replace the two separately-maintained vendor identifier lists with one
shared REASONING_VENDOR_HINTS constant and a single
is_reasoning_vendor_identifier predicate. The Anthropic
tool-thinking-history matcher and the openai_chat reasoning_content
matcher previously kept independent lists, which is exactly how
kimi/moonshot ended up in one but not the other (#3351). A single source
of truth keeps the two from drifting apart again.

Also add a Kimi regression test for the Anthropic tool-history
normalization path.

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-05-31 20:10:02 +08:00
Jason c9cadd6e09 Fix Codex OAuth auth being cleared during preserve-mode takeover
When "preserve official auth on switch" is enabled, proxy takeover routes
the PROXY_MANAGED placeholder into config.toml's experimental_bearer_token
and leaves auth.json (the ChatGPT OAuth login) untouched. Takeover detection
only inspected auth.json's OPENAI_API_KEY, so it never recognized this state
and returned a false negative, which led downstream paths to clobber the
preserved OAuth login.

- Detection: is_codex_live_taken_over now also matches a config.toml
  experimental_bearer_token equal to the placeholder, fixing detect/cleanup/
  restore/startup-recovery in one place.
- Cleanup: remove the config.toml bearer token only when it equals the
  placeholder (new remove_codex_experimental_bearer_token_if predicate), so a
  real third-party key is never stripped.
- Write: under preservation, the None-provider takeover path writes only
  config.toml and keeps auth.json intact, matching the provider path.
- Settings: rename the section to "Codex App Enhancements" and reword the
  description across all four locales.
- Add tests covering OAuth preservation on takeover and placeholder-only
  cleanup.
2026-05-30 22:56:36 +08:00
Jason 60a9b330e5 Refactor Codex live-write routing and cover default auth overwrite
Collapse the two duplicated write_codex_live_atomic branches in
write_codex_live_for_provider into a single should_write_auth guard.
This is behavior-preserving: `if A {X} else if B {X} else {Y}` becomes
`if A || B {X} else {Y}`.

Adapt the Codex switch tests to the new opt-in default for
preserve_codex_official_auth_on_switch (flipped off in 3f59ab37):
add an enable_codex_official_auth_preservation() test helper for the
cases that assert the auth-preserving path, and tag the official login
provider with category="official" so it routes through the official
branch rather than relying on the global preservation flag.

Add a regression test locking the default (preservation off) behavior:
switching to a third-party provider rewrites auth.json with the new
API key and discards the existing ChatGPT OAuth login. This is the
dual of the existing preserve-and-backfill test, which only covered
the opt-in path.
2026-05-30 22:09:28 +08:00
Jason f4e2c28a2b Enrich Codex proxy forwarding-error responses with context
When forward_with_retry fails for Codex endpoints (/chat/completions, /responses, /responses/compact), the handlers previously returned the bare ProxyError, surfacing a terse body to the client. Build a richer JSON error instead: the message embeds provider, model, endpoint and upstream status, and the error object carries those as structured fields alongside a stable cc_switch_* code.

Align map_proxy_error_to_status with ProxyError::into_response so the manually built responses use the canonical status codes (AuthError->401, Config/InvalidRequest->400, TransformError->422, StreamIdleTimeout->504, AlreadyRunning->409, NotRunning->503); previously these forwarder-level errors collapsed to 500.
2026-05-30 21:42:16 +08:00
Jason 0e6f2b395f Swap Shengsuanyun and AICodeMirror sponsor ads 2026-05-30 21:23:50 +08:00
Jason 41433cfab2 Add Codex restart hint after provider switch 2026-05-30 21:19:30 +08:00
Jason 3f59ab3746 Default Codex auth preservation to off (opt-in)
Flip preserve_codex_official_auth_on_switch from true to false so
third-party Codex switches overwrite auth.json by default, matching the
expectation that switching providers also swaps credentials. Users who
rely on keeping the ChatGPT login in auth.json while on a third-party
provider (for official plugins / remote login) can enable it in
Settings -> Codex Authentication.

The toggle field ships for the first time here (it is not in v3.16.0),
so no existing settings.json holds an explicit value -- every user lands
on the new default and no migration is required.

Also set the flag explicitly in the preservation unit test instead of
relying on the global default, keeping it valid now that the default is
false.
2026-05-30 21:04:23 +08:00
Jason ee69c83687 Fix garbled output and false "not runnable" in Windows version probe
The version probe ran `cmd /C "\"{path}\" --version"` on Windows. Rust's
own arg quoting plus the manual quotes produced nested quotes that cmd
(without /S) misparsed, so it reported even working tools as an
unrecognized command -> non-zero exit -> shown as "installed but not
runnable". cmd's error is emitted in the OEM code page (e.g. GBK on
zh-CN) and was decoded as UTF-8, turning it into mojibake.

- Add decode_command_output: try strict UTF-8, then OEM (GetOEMCP), then
  ANSI (GetACP) code page via MultiByteToWideChar; route all command
  output decoding through it (probes, lifecycle output, osascript,
  terminal launchers).
- Add run_windows_tool_version_command: run .exe directly (no cmd);
  invoke .cmd/.bat via `cmd /D /S /C call <quoted> --version` with
  raw_arg to bypass Rust's quoting and keep deterministic quote handling.
- Add windows-sys Win32_Globalization dependency.
2026-05-30 17:46:35 +08:00
Jason 2683af57cb Add Codex auth preservation setting 2026-05-30 14:13:58 +08:00
Jason 8f83fa2063 docs: add Codex DeepSeek routing guides 2026-05-30 11:49:50 +08:00
Jason 47232cb05d chore(release): bump version to 3.16.0 and add release notes
- Bump version to 3.16.0 in package.json, Cargo.toml, tauri.conf.json, and Cargo.lock
- Add v3.16.0 release notes (zh/en/ja) with contributor credits
2026-05-30 00:00:15 +08:00
Jason fe3eb7e6a6 docs(changelog): add 3.16.0 release notes 2026-05-29 23:17:44 +08:00
Jason d905ed1609 Add UTM params to Atlas Cloud partner link across all locales 2026-05-29 22:52:25 +08:00
Jason 94cc3d103a Align Claude Desktop model mapping with Claude Code three-role tiers
Claude Desktop's 3P validation only accepts claude-{sonnet,opus,haiku}-*
role IDs, so providers must map every tier. Bring the Desktop mapping flow
in line with Claude Code and fix the fallout that broke sub-agent Haiku calls.

- Proxy form: replace the dynamic route list with fixed Sonnet/Opus/Haiku
  tiers; blank tiers backfill from the first filled tier (Sonnet first) on
  submit and inherit its supports1m flag
- Backend: add a role-keyword fallback in map_proxy_request_model so dated
  official names (e.g. claude-haiku-4-5-20251001) resolve to the right tier,
  guarded by is_claude_safe_model_id so [1m]-suffixed IDs stay rejected
- Tighten is_claude_safe_model_id / isClaudeSafeRoute to reject degenerate
  role IDs like "claude-sonnet-"
- Fix the seed-effect race where normalizing empty routes to three blank
  tiers blocked the default-route backfill
- Sync switch hints, placeholders, and the zh/en/ja/zh-TW locales to the
  three-role-ID rule
- Update zh/en/ja user manual (2.1, 2.6), calling out legacy Claude IDs
  (claude-3-5-sonnet-...) as a rejected example

Tests: 282 frontend + 34 backend claude_desktop; typecheck, clippy, fmt clean.
2026-05-29 22:52:25 +08:00
Jason 058c9fb8e5 Rename OpenCode Go preset to drop model suffix
Simplify the display name from "OpenCode Go (DeepSeek V4 Flash)" to
"OpenCode Go" in both the Claude Code and Claude Desktop preset lists.
2026-05-29 22:52:25 +08:00
Jason 85552cf40a Add referral param to ShengSuanYun website links
The websiteUrl for ShengSuanYun presets pointed at the bare domain while
only apiKeyUrl carried the from=CH_4HHXMRYF referral code. Append the same
referral param to websiteUrl across all provider presets so the in-app
'open website' jump is also attributed to the channel.
2026-05-29 22:52:25 +08:00
Jason 3a15420770 Update default models and pricing across presets
Bump default model names project-wide: gpt-5.4 -> gpt-5.5,
gemini-3.x -> gemini-3.5-flash, glm-5 -> glm-5.1, and
grok-code-fast-1 -> grok-build-0.1 across all provider presets
(claude, codex, gemini, hermes, openclaw, opencode, universal),
Gemini config, and stream check defaults.

Pricing:
- Seed gemini-3.5-flash, gemini-3.1-flash-lite, step-3.5-flash-2603,
  doubao-seed-2.0-code, mimo-v2.5(/pro), qwen3-coder-480b, grok-build-0.1.
- Correct deepseek-v4-flash/pro, glm-5/5.1, grok pricing.
- Add repair_current_model_pricing: idempotent pass that fixes only
  rows still equal to the outdated built-in values, preserving any
  user-customized prices (seed uses INSERT OR IGNORE and cannot update
  existing rows).

Fixes from review:
- opencode: drop duplicate gemini-3.5-flash variant (unreachable via
  .find), keep the entry with the full minimal/low/medium/high set.
- Align stale display names/costs to gemini-3.5-flash (hermes, openclaw,
  opencode); openclaw cost -> {1.5, 9, 0.15} to match seed.
- i18n (zh/en/ja/zh-TW): refresh OMO category tooltips for new model
  names; fix writing tooltip to Kimi K2.5 to match its recommended.

Update tests accordingly and add a regression test asserting unique
model ids in the Google opencode preset variants.
2026-05-29 22:52:25 +08:00
Jason 2b6ede1431 Update Codex provider migration test expectations 2026-05-29 22:52:25 +08:00
Jason 0877b9e35d Upgrade default Claude Opus model to 4.8
Bump the default Opus route/model from claude-opus-4-7 to claude-opus-4-8
across provider presets (claude, claudeDesktop, hermes, openclaw, opencode,
universal), i18n locales (zh/en/ja/zh-TW), pricing seed data, and the
user-manual docs.

- Add claude-opus-4-8 pricing row ($5/$25/$0.50/$6.25); keep the 4-7 row
  for historical usage stats (seeded via INSERT OR IGNORE).
- Claude Desktop proxy: accept bidirectional opus 4-7 <-> 4-8 route alias
  during rollout so previously saved routes keep resolving.
- thinking_optimizer: route opus-4-8 through adaptive thinking and normalize
  dotted model ids (also fixes dotted 4-6/4-7 falling back to legacy).
- usage_stats: normalize Bedrock/Vertex/aggregator opus-4-8 ids to base
  pricing.

Also merge role:"system" messages into the Gemini systemInstruction in the
Anthropic->Gemini transform.
2026-05-29 22:52:25 +08:00
Q3yp 554e3b4875 fix(proxy): normalize DeepSeek Anthropic tool thinking history (#3203)
Fixes #3200
2026-05-29 22:51:12 +08:00
lipeng e605eba292 fix(deeplink): preserve custom env fields when importing Claude providers (#2928)
When importing a Claude provider via deep link, the preview dialog
correctly shows every env field carried in the `config` payload — but
on confirmation `build_claude_settings` only persisted the standard
fields mapped from URL params (`apiKey`, `endpoint`, `model`,
`haiku/sonnet/opusModel`). Any non-standard env keys such as
`ANTHROPIC_CUSTOM_HEADERS`, `API_TIMEOUT_MS`, or
`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` were silently dropped,
making the preview and the actual write diverge.

Start the env map from the inline `config` payload (best-effort
decode via the new `extract_claude_config_env` helper) and then
overlay the URL-param-derived standard fields on top, so:

- URL params remain authoritative for standard fields (unchanged)
- Custom env keys present in `config` survive the import
- Deep links without a `config` payload behave exactly as before

Adds two regression tests:
- `test_build_claude_provider_preserves_custom_env_fields` proves
  custom fields are kept and URL params override same-named config
  fields.
- `test_build_claude_provider_without_config_unchanged` guards the
  backward-compatible path (no `config` → only standard env keys).

Closes #2927

Co-authored-by: lipeng31 <lipeng31@tanyang.co>
2026-05-29 22:49:02 +08:00
in30mn1a bc1467db8d feat(usage): real-time stats refresh + fix codex sync panic on non-ASCII model names (#3027)
The usage dashboard previously only refreshed on app restart for users
who don't route through the cc-switch proxy. Two issues were involved:

1. The session-sync background task panicked when a Codex model name
   contained non-ASCII characters (e.g. `【官】glm-5.1`), because
   `normalize_codex_model` sliced `&name[name.len() - 11..]` without
   verifying char boundaries. Once the task panicked, no session logs
   were imported until the app was restarted (where startup-time
   `rollup_and_prune` happened to flush pending data).

2. Even with sync working, the dashboard only polled every 30s and
   skipped polling when the window was unfocused, so freshly-imported
   data was invisible until the next poll or window refocus.

Fixes
-----

* `normalize_codex_model`: guard the 11-byte ISO-date suffix slice with
  `is_char_boundary` + `is_ascii` checks. ASCII-only suffix means the
  date-stripping logic is correct, and non-ASCII names (which can never
  be valid date suffixes anyway) now bypass the slice safely.

* New `usage_events` module that emits `usage-log-recorded` to the
  frontend whenever `proxy_request_logs` actually gains a new row.
  Sources covered: proxy `log_request`, Claude/Codex/Gemini session
  sync, and startup `rollup_and_prune`. Notifications use a global
  `OnceLock<AppHandle>` so call sites that don't already hold an
  `AppHandle` (e.g. `UsageLogger`) can notify without signature churn.

* 200ms debounce in `notify_log_recorded` collapses bursts (a single
  Codex sync importing 3000+ entries triggers ~2 emits, not 3000) so
  the frontend's `invalidateQueries` is never spammed.

* Frontend `useUsageEventBridge` listens for the event and invalidates
  `usageKeys.all`. Hook is mounted only on `UsageDashboard`, so the
  listener is unsubscribed automatically when the user navigates away.

Verification
------------

* `cargo check` passes (existing 25 dead-code warnings in
  `commands/misc.rs` are pre-existing and unrelated).
* `tsc --noEmit` passes.
* Manually verified end-to-end: a Codex sync run that imported 3145
  entries produced 2 debounced emits, both logged as `emit
  usage-log-recorded 成功`, and the dashboard updated within ~200ms.

Behaviour notes
---------------

* `INSERT OR IGNORE` paths (Claude/Codex session sync) only notify when
  the row is actually inserted, so dedup-skipped writes don't trigger
  empty refreshes.
* Gemini's `INSERT … ON CONFLICT … DO UPDATE` path reuses the existing
  `conn.changes() > 0` check and only notifies when token counts truly
  changed.
* `rollup_and_prune` notifies once per pruning cycle (at most once per
  app start) so the dashboard reflects the new aggregate state.

Co-authored-by: in30mn1a <in30mn1a@users.noreply.github.com>
2026-05-29 22:47:51 +08:00
Jason e71b90916b Add SudoCode partner provider presets 2026-05-29 11:11:46 +08:00
Jason 32b30e43c0 Add AtlasCloud partner provider presets 2026-05-29 09:46:00 +08:00
Jason 9ef141902e Add APINebula partner provider presets 2026-05-29 09:18:59 +08:00
Jason d7a34f4247 fix(about): handle prerelease tools in version check
Use semver comparison instead of string inequality so locally-ahead prerelease builds aren't misreported as outdated; backend now fetches the full npm dist-tags and, when the local version leads latest, surfaces the tool's prerelease channel (claude=next) as latest.
2026-05-29 08:47:54 +08:00
Jason 8302f1e36c Add APIKEY.FUN partner provider presets 2026-05-28 23:43:48 +08:00
Jason 4bb4e994af Fix Shengsuanyun prefixed model IDs for Claude Code and upgrade GPT to 5.5 2026-05-28 21:48:22 +08:00
Jason fc0433f2f4 refactor(codex): unify custom model_provider routing key to "custom"
- Always emit `model_provider = "custom"` from deep link, UniversalProvider, and the universal form modal so future writes share one stable routing key.
- Add `codex_provider_template_v1` local migration that rewrites legacy keys (aihubmix/ccswitch/...) under `[model_providers.custom]`, updates profile refs, and backs up the original settings_config under `~/.cc-switch/backups/<timestamp>/providers/`.
- Tighten history migration source detection to a whitelist plus `[model_providers.<id>]` existence check so user-authored keys are never rewritten in jsonl/state DB.
- Encode deep link name/model/endpoint through `toml_edit::Value` so display names containing quotes or backslashes no longer break the generated config.toml.
- Stabilize provider settings backup filename hash with Sha256 (was process-random SipHash).
2026-05-28 17:30:44 +08:00
Jason 3d6fb894b5 Fix Shengsuanyun prefixed model IDs 2026-05-28 13:16:44 +08:00
Jason af60c7ed2c feat(codex): add remote compaction toggle for third-party providers
Write model_providers name as "OpenAI" to let Codex attempt remote
compaction through compatible endpoints. Hidden for official providers.
2026-05-28 11:57:54 +08:00
Jason a2ac21d0a6 refactor(codex): stop force-rewriting user's model_provider field in live config
The one-time history migration already consolidates legacy provider IDs
into a single bucket; there is no need to normalize on every write.
This preserves user-chosen provider identities through the full
write/backup/restore cycle.
2026-05-28 11:39:54 +08:00
Jason 6b0dd3c4e9 fix(omo): sync recommended models with upstream and improve Fill Recommended feedback
The Fill Recommended button was misleading — it showed toast.success even
when most slots couldn't be filled due to model ID mismatches with the
user's configured providers.

Changes:
- Sync OMO_BUILTIN_AGENTS/CATEGORIES recommended fields with upstream
  oh-my-openagent model-requirements (gpt-5.4→5.5, kimi-k2.5→claude-sonnet-4-6, etc.)
- Add toast.warning tier when unmatched >= filled, showing slot:model pairs
  (e.g. "Sisyphus: claude-opus-4-7") so users know exactly what to configure
- Upgrade fillRecommendedNoMatch to also show examples
- Add fillRecommendedMostlyUnmatched i18n key (zh/en/ja/zh-TW)
2026-05-27 23:08:11 +08:00
Kairos Duan 3c3d417457 Enable Codex goals in provider templates (#3089)
* Enable Codex goals in provider templates

* feat: add Codex goal mode toggle

- Remove forced goals=true from Codex provider presets and custom templates.
- Add a Codex provider editor switch that updates [features].goals on demand.
- Update docs, i18n, and regression coverage for the optional Goal mode flow.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-05-27 11:31:31 +08:00
nanmen2 e9d84af500 fix(session): include Codex archived sessions (#2861)
Scan Codex archived_sessions alongside active sessions so archived conversations appear in the session manager.

Allow deletion from any validated Codex session root while keeping path safety checks in place.
2026-05-27 11:16:50 +08:00
Zihao Han 8e21b061cf Fix custom usage script summaries (#3129)
Co-authored-by: Zihao Han <hanhan3344@users.noreply.github.com>
2026-05-27 10:50:29 +08:00
zhizhuowq 9c2add9a09 fix(proxy): 修复 Claude 兼容模式下流式响应因空 tool_calls 数组导致 block 状态重置 (#2915)
问题:OpenAI 兼容 Provider(如 MiniMax)在发送 reasoning_content 流时,
      每个 chunk 包含 "tool_calls": [] 空数组,导致每个字符被当作独立 block 处理

根因:streaming.rs:343 的 if let Some(tool_calls) 匹配空数组进入处理分支,
      发送 content_block_stop 并重置 current_non_tool_block_type 为 None

修改:在 tool_calls 处理前添加 if !tool_calls.is_empty() 判断

示例输入:
```jsonl
{"delta": {"content": null, "reasoning_content": "用户", "role": "assistant", "tool_calls": []}}
{"delta": {"content": null, "reasoning_content": "用", "role": "assistant", "tool_calls": []}}
{"delta": {"content": null, "reasoning_content": "中文", "role": "assistant", "tool_calls": []}}
...
```
示例错误输出:
```text
event: content_block_start → index 0, type thinking
event: content_block_delta → thinking "用户"
event: content_block_stop → index 0
event: content_block_start → index 1, type thinking
event: content_block_delta → thinking "用"
event: content_block_stop → index 1
event: content_block_start → index 2, type thinking
event: content_block_delta → thinking "中文"
event: content_block_stop → index 2
...
```

Co-authored-by: WangQiang <wangqiang75@huawei.com>
2026-05-27 10:49:41 +08:00
Sphaela 864593bb09 Fix Claude Desktop Cowork egress profile (#3172) 2026-05-27 10:49:08 +08:00
滅ü 5fd3ec0d6a feat(i18n): add Traditional Chinese localization (#3093)
* Add Traditional Chinese localization

* fix: address zh-TW formatting and token units

- Format `zh-TW.json` with Prettier.
- Use Traditional Chinese `萬` and `億` units for zh-TW token summaries.
- Add usage formatting coverage for Traditional Chinese locale aliases.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-05-27 00:05:03 +08:00
zcb 8cdaf90d8d refactor: replace JSON deep copy with deepClone helper and extract useTauriEvent hook (#3140)
* refactor: replace JSON.parse(JSON.stringify()) with structuredClone and extract useTauriEvent hook

Replace all `JSON.parse(JSON.stringify())` deep copy patterns with native
`structuredClone()` across production source (9 occurrences), tests (11
occurrences), and a hand-rolled `deepClone` utility in providerConfigUtils.ts.
Add "ES2022" to tsconfig lib for type support.

Extract a `useTauriEvent` hook to eliminate the repeated Tauri event listener
boilerplate (`useEffect` + `active/disposed` flag + async `listen`) that was
duplicated across App.tsx (3 listeners) and useUsageCacheBridge.ts. The hook
handles async registration, race-condition guards, and cleanup automatically.

* fix: add compatible deepClone helper

- Add a shared deepClone helper with a structuredClone runtime guard and fallback.
- Route clone call sites through the helper.
- Preserve universal-provider-synced listener ordering and drop the dead-directory diff.

* fix: harden Tauri event handling

- Guard WebDAV sync status events against missing payloads.
- Preserve settings query invalidation ordering before showing auto-sync errors.
- Simplify useTauriEvent subscriptions to avoid dependency-driven re-listens.

---------

Co-authored-by: zcb <zhangchongbiao@qiyuanlab.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-05-26 23:39:16 +08:00
MelorTang 05ba28016c fix: sync Claude Desktop profile during proxy takeover (#3157)
* fix: sync Claude Desktop profile during proxy takeover

* fix(provider): skip Claude Desktop backup refresh during takeover

- Route Claude Desktop takeover updates directly through the 3P profile writer.
- Keep takeover startup backup state unchanged when provider metadata changes.
- Narrow platform-specific test helpers and environment setup with cfg gates.

* fix(provider): restore PathBuf import for CI tests

- Restore an unconditional PathBuf import for provider tests.

- Keep Linux cargo test builds compiling while preserving Claude Desktop cfg-gated helpers.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-05-26 23:01:33 +08:00
zhangyapu1 707a5593e5 feat: add MiMo reasoning_content support for Claude Code proxy (#2990)
* feat: add MiMo reasoning_content support for Claude Code proxy

MiMo requires reasoning_content to be passed back in multi-turn
conversations with tool calls. Add "mimo" and "xiaomimimo" to the
preserve_reasoning_content whitelist so thinking blocks are converted
to reasoning_content when proxying Claude Code → MiMo.

Also handle redacted_thinking blocks (encrypted by Claude Code across
turns) by injecting a placeholder to prevent MiMo 400 errors.

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

* fix: support MiMo reasoning histories

- Fix the PR CI clippy failure for redacted thinking handling.
- Preserve MiMo reasoning content on the OpenAI Chat proxy path.
- Normalize Claude Desktop Anthropic thinking history for MiMo local routes.
- Reject unsupported Claude Desktop direct model remaps.

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-05-26 22:55:36 +08:00
Martin Klein 48473a5ca3 docs: add German README translation (README_DE.md) (#2994)
* docs: add German README translation (README_DE.md)

Adds README_DE.md, a full German translation modelled on README_JA.md,
and extends the language switcher in README.md, README_ZH.md and
README_JA.md with a Deutsch link.

* docs: remove outdated German sponsor entry

- Remove the AICoding.sh sponsor block from README_DE.md.
- Keep the German README aligned with the current sponsor list.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-05-26 22:09:25 +08:00
Loocor 62928c62bc fix(ui): remove fixed width constraint on AppSwitcher text to prevent clipping (#3161)
* fix(ui): remove fixed width constraint on AppSwitcher text to prevent clipping

App names like "Claude Desktop" were being clipped by the max-w-[90px]
constraint on the text label. Changed to max-w-none so text adapts to
content width. Also removed overflow-x-hidden from the parent toolbar
container to prevent clipping of the wider content.

Fixes text truncation in the top-right app switcher segmented control.

* - fix(ui): preserve AppSwitcher compact overflow behavior

- Restore toolbar overflow clipping required by useAutoCompact.

- Cap expanded AppSwitcher labels at 120px so Claude Desktop fits while compact animation remains smooth.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-05-26 17:35:13 +08:00
Jason 910ca3b40e chore(sponsors): drop AICoding partner from README, presets and i18n
Remove AICoding (aicoding.sh) sponsor entry from the three README files
and the provider preset across all seven app_types (claude, codex,
gemini, hermes, opencode, openclaw, claudeDesktop). Also drop the
matching partner_promotion.aicoding string in zh/en/ja locales.

The icon (src/icons/extracted/index.ts) and the legacy provider id in
codex_history_migration.rs are kept intentionally: the former for
possible later re-use, the latter so existing users' Codex history
still gets bucketed into "custom" on upgrade.
2026-05-25 22:20:34 +08:00
Jason d8a4292091 chore: satisfy clippy::nonminimal_bool and prettier to unblock CI
- codex_config: rewrite `!(A && !B)` as `!A || B` (De Morgan-
  equivalent) — also reads more directly as "no OAuth, or
  already has provider API key".
- UsageScriptModal: reflow conditional onto one line per prettier.
2026-05-25 22:20:34 +08:00
Jason b15d9dfa11 feat(codex): migrate third-party history provider bucket to unified "custom" ID
Codex CLI filters conversations by model_provider — after normalizing
all third-party providers to "custom", old sessions with their original
provider IDs become invisible. This migration rewrites JSONL session
files and state_5.sqlite threads to use the unified ID.

Uses a three-tier trust model for source ID collection:
- Known legacy preset whitelist (46 IDs, case-insensitive)
- cc-switch-created custom providers (identified by created_at)
- User-maintained custom providers are explicitly skipped

Adds scanned_history_files flag to prevent stale v1 markers from
blocking re-runs with the improved source ID collection logic.
2026-05-25 22:20:34 +08:00
Jason 177eef6682 fix(quota): sort ZhiPu tiers so missing nextResetTime maps to five_hour bucket
When the 5-hour bucket is at 0% utilization, ZhiPu's API omits
nextResetTime. The old i64::MAX sentinel sorted these entries last,
causing the weekly bucket to incorrectly claim the five_hour slot.
2026-05-25 22:20:34 +08:00
Jason 95f2dd4126 feat(codex): preserve OAuth login state during third-party provider switching
Codex provider switches now only write config.toml for third-party providers,
injecting the API key as experimental_bearer_token. The user's auth.json
(ChatGPT OAuth tokens) is preserved. Official providers with login material
still write auth.json normally. Backfill restores bearer tokens into stored
provider auth.OPENAI_API_KEY to maintain canonical shape.
2026-05-25 22:20:34 +08:00
Jason 88ba908bc4 feat(settings): unify unix installers on mktemp+bash, fix WSL install missing native installer
Extend the mktemp+bash installer pattern from hermes (commit 20d943be) to
claude and opencode, and remove the cfg gate that locked install_command_for
to non-Windows targets — Windows host + WSL tools now correctly route
through the POSIX install priority instead of falling back to bare npm.
Frontend "one-click install commands" displayed in the About section now
diverge per platform to match what the backend actually runs.

Backend (src-tauri/src/commands/misc.rs):
- New CLAUDE_INSTALL_UNIX and OPENCODE_INSTALL_UNIX constants use the same
  `bash -c 'tmp=$(mktemp) && curl -fsSL .../install.sh -o $tmp && bash
  $tmp; status=$?; rm -f $tmp; exit $status'` shape as HERMES_INSTALL_UNIX.
  The shared comment about why we avoid `curl | bash` is now hoisted to the
  top of all three constants — the constraint (WSL `sh -c` sub-shells
  don't inherit outer pipefail; default shell may be dash/ash) applies to
  every shell installer, not just Hermes.
- New installer_with_npm_fallback helper deduplicates the
  "official installer || npm fallback" chain construction; reuses
  chain_update_commands(LifecycleCommandShell::Posix) so the wiring matches
  the update-chain logic.
- install_command_for split into cross-platform posix_install_command_for
  + thin #[cfg(not(target_os = "windows"))] wrapper. The cfg gate had
  been hiding a real bug: on Windows hosts, the WSL branch called
  wsl_tool_action_shell_command which forwarded install actions to the
  Windows-target tool_action_shell_command, yielding bare `npm i -g` for
  claude/opencode even though they have working native POSIX installers.
- wsl_tool_action_shell_command now branches on action: Install dispatches
  to posix_install_command_for (native installer || npm chain); Update
  keeps the existing behavior. Empty install commands collapse to None so
  callers error on unsupported tools instead of running an empty command.
- build_tool_lifecycle_command pipefail comment updated: the original
  justification (covering install's `curl | bash` path) no longer applies
  to any current command, but the directive stays as defense-in-depth for
  future pipe additions.
- build_tool_action_line WSL branch comment updated to reflect the
  install/update split.

Frontend (src/components/settings/AboutSection.tsx):
- New posixScriptInstallCommand(url) helper builds the same mktemp+bash
  string template the backend uses.
- New powershellEncodedCommand(script) mirrors the backend's UTF-16 LE +
  base64 encoder (charCodeAt + String.fromCharCode(lo, hi) + btoa) so the
  PowerShell EncodedCommand shown to users matches what the backend
  executes.
- ONE_CLICK_INSTALL_COMMANDS split into POSIX_ONE_CLICK_INSTALL_COMMANDS
  and WINDOWS_ONE_CLICK_INSTALL_COMMANDS, selected by isWindows():
  POSIX shows claude/opencode/hermes with the mktemp+bash installer;
  Windows shows claude/codex/gemini/opencode/openclaw with npm (matching
  backend static_fallback_command on Windows) and hermes with the
  PowerShell EncodedCommand. Display now mirrors backend execution
  per platform, removing the show-vs-run mismatch.
- Stale comment in the probe-concurrency note mentioning "curl | bash"
  updated to "官方 installer".

Tests (src-tauri/src/commands/misc.rs):
- New wsl_install_uses_posix_install_priority covers three
  representatives: claude (positive: native installer with npm fallback),
  opencode (positive), codex (negative: no native installer so falls back
  to bare `npm i -g`). Reverse-asserts !contains("| bash") to lock out
  the old pipe form.
- claude_install_chains_native_then_npm and
  opencode_install_chains_native_then_npm strengthened with
  !parts[0].contains('|') so the native installer portion stays
  pipe-free even if future edits to the template sneak a pipe back in.

Validated:
- cargo check --tests: clean
- cargo test --lib commands::misc:: : 59 passed, 0 failed
- pnpm typecheck: 0 errors
- cargo fmt: clean
- pnpm format: clean (no files changed)
2026-05-25 22:20:34 +08:00
Jason 5de0a0dc8d feat(settings): self-update first chain, switch hermes to native installer
Promote anchored upgrades to "<bin> update || <package fallback>" for the
tools whose CLI knows how to self-update safely, and replace pip-based
hermes install/update with the official NousResearch installer scripts.
Frontend learns to detect "update reported success but version did not
change" so silent upstream no-ops surface as a soft warning.

Backend (src-tauri/src/commands/misc.rs):
- New prefers_official_update(tool, shell) per-platform allow-list:
  POSIX {claude, codex, opencode, openclaw}. Windows drops opencode
  pending anomalyco/opencode#17295 (its silent `upgrade` may prompt for
  install-source detection and deadlock our lifecycle). gemini is absent
  from both because `gemini update` is not implemented upstream
  (google-gemini/gemini-cli#18618 / #16122 OPEN).
- New chain_update_commands joins primary/fallback per shell: POSIX
  `||`, Windows `|| call` — batch transfers control to the `||` RHS
  without `call`, skipping subsequent tools in multi-tool actions.
- New LifecycleCommandShell {Posix, WindowsBatch} threads the target
  shell through tool_action_shell_command_for_shell, replacing the old
  hermes-only WSL substitution hack with a uniform mechanism.
- anchored_command_from_paths refactored: hermes anchors to
  `<bin> update`; tools in prefers_official_update chain self-update
  with the package-manager command as fallback; brew formulae remain
  brew-managed (never self-update what Homebrew owns); others use the
  prior npm/volta/bun/pnpm anchoring unchanged. Mirror on Windows.
- Hermes commands switch from pip to the official scripts. POSIX/WSL
  runs `bash -c 'tmp=\$(mktemp) && curl -fsSL .../install.sh -o \$tmp
  && bash \$tmp; status=\$?; rm -f \$tmp; exit \$status'`. The mktemp +
  two-step download avoids `curl | bash` because WSL sub-shells inherit
  neither outer `set -o pipefail` nor a guaranteed bash (default may be
  dash/ash). Windows uses `powershell -NoProfile -ExecutionPolicy Bypass
  -EncodedCommand <b64>` with a hand-rolled UTF-16 LE base64 encoder
  for `irm .../install.ps1 | iex`, hiding the PowerShell pipe from
  cmd.exe. Pip is abandoned because macOS system python3 is often 3.9
  while hermes-agent requires >=3.11, and the pyenv `python` shim may
  not exist — pip errors then misclassify as "command not found".

Frontend (src/components/settings/AboutSection.tsx):
- New versionUnchangedAfterUpdate four-AND short-circuit detects when
  the upgrade command succeeded, the tool still reports a version, but
  that version equals the pre-upgrade version while a different
  latest_version is known. Guards against upstream no-op updaters that
  return exit 0 without applying anything (openai/codex#21897).
- Soft-failure shape gains kind?: "notRunnable" | "versionUnchanged"
  so the warning toast title can disambiguate the two cases.
- Hermes install command snippet swapped from `python3 -m pip ...` to
  the official curl-bash one-liner shown to users.

i18n (zh / en / ja):
- New settings.toolActionVersionUnchangedTitle and
  settings.toolActionVersionUnchanged, synchronized across all locales.

Tests (src-tauri/src/commands/misc.rs):
- Anchored upgrade assertions updated to `<bin> update || <pkg>` shape
  across nvm / volta / bun / homebrew-npm-global / spaces / fnm
  branches; brew formula explicitly does NOT chain self-update.
- New hermes anchor tests replace hermes_has_no_npm_anchor on both
  POSIX and Windows. WSL hermes tests rewritten for the mktemp+bash
  flow with `hermes update` fallback.
- Reverse-lock tests: gemini static fallback must NOT contain
  `gemini update`; opencode Windows static fallback must NOT contain
  `opencode upgrade`; hermes commands must NOT contain
  `python`/`pip`/`powershell`/forbidden pipes.

Validated:
- cargo check --tests: clean
- pnpm typecheck: 0 errors
- cargo fmt: clean
2026-05-25 22:20:34 +08:00
Jason 7cad61be27 refactor(settings): drop CLI uninstall command hints, keep conflict diagnostics
The uninstall hint feature added in f6bdd4bb / 89e2339b printed a
copy-pasteable shell command (e.g. `brew uninstall <formula>`,
`<sibling-npm> rm -g <pkg>; [ -e bin ] && rm -f bin && rm -rf pkg_dir`)
under each detected install in the multi-install conflict panel. Even
with copy-only-never-execute UX, putting destructive commands one
button away from the user is risk we don't want to ship — `rm -rf`
under a misclassified path would be unrecoverable.

Conflict diagnostics themselves are kept: users still see the warning
banner + per-install row (source / path / version / Default badge), so
the "you have multiple installs and the upgrade only touches one"
signal survives. They just don't get a one-click destructive command.

Backend (src-tauri/src/commands/misc.rs):
- Remove `uninstall_command_from_paths` (POSIX + Windows pair).
- Remove `posix_quote_for_user_shell` and `win_quote_path_for_user_shell`
  — both were uninstall-only quoters (whitelist + cmd-only forms).
  `win_quote_path_for_batch` and `shell_single_quote` stay because the
  anchored upgrade path and `build_shell_cd_command` still use them.
- Remove `quoted_sibling_or_bare` and `quoted_sibling_or_bare_with_ext`
  thin wrappers (only callers were uninstall branches).
- Drop `uninstall_command` and `uninstall_command_needs_cmd_hint` from
  `ToolInstallation`. Drop the eager `infer_install_source` ->
  `uninstall_command_from_paths` call in `enumerate_tool_installations`
  (saves ~16μs per probe but the real point is fewer surprises).
- Remove 14 `#[test]` cases for uninstall command shape (brew /
  homebrew-npm-global / nvm / npm-fallback quoting / pnpm / volta / bun /
  hermes / system / Windows percent-path) plus 4 `win_quote_path_for_user_shell`
  helper tests and the `expect_user_shell_quoted_path` test mirror.
- Drop the `src()` test helper that was only used to feed the deleted
  uninstall tests (`infer_install_source` is still called directly by
  surviving tests).
- Cross-references in `anchored_command_from_paths` doc to its now-gone
  uninstall "dual" are stripped.

Frontend (src/components/settings/AboutSection.tsx):
- Conflicts `<ul>` keeps the diagnostic header + per-install `ToolInstallRow`
  but loses the inline command box, the trash + copy icons, the per-row
  PowerShell-call-operator hint, and the `handleCopyCommand` callback.
- Remove the `Trash2` lucide import; `Copy` stays (the install-commands
  copy button at line 1100 still uses it).

API (src/lib/api/settings.ts):
- Drop `uninstall_command` and `uninstall_command_needs_cmd_hint` from
  the `ToolInstallation` TS interface (matches the Rust struct change).

i18n (zh / en / ja):
- Drop `settings.toolUninstallCopyHint`, `settings.toolUninstallCopied`,
  `settings.toolUninstallPwshHint`. Other `tool*` and `skills.uninstall*`
  keys are untouched (Skill uninstall is a separate, non-destructive
  feature for managing the Skills repo and is unaffected).

Stats: 858 deletions, 5 insertions across 6 files.

Validated:
- cargo test --lib: 1322 passed, 0 failed
- cargo fmt --check: clean
- cargo build: clean
- cargo check --tests: clean
- pnpm typecheck: 0 errors
- JSON.parse on all three locale files: clean
2026-05-25 22:20:34 +08:00
Jason 3a77861dd9 feat(settings): backend-generated source-aware uninstall command hints
Move uninstall hint command generation from frontend (which used a lossy
`source` string and couldn't tell brew formula from homebrew-npm-global apart)
into the Rust backend, where `brew_formula_from_path` + `infer_install_source`
together produce correct commands for each install. Conflict UI now reads
`inst.uninstall_command` directly.

Backend (src-tauri/src/commands/misc.rs):
- New `uninstall_command_from_paths` (POSIX + Windows) mirrors the
  `anchored_command_from_paths` family. POSIX branches on brew formula /
  volta / bun / pnpm / nvm|fnm|mise|homebrew / system. Windows branches on
  volta / pnpm / npm.
- New `quoted_sibling_or_bare` (POSIX) + `quoted_sibling_or_bare_with_ext`
  (Windows) deduplicate the `sibling_bin().map(quote).unwrap_or_else(bare)`
  pattern across all uninstall branches.
- New `posix_quote_for_user_shell` whitelists `[A-Za-z0-9._/+=:@-]`; any
  other character routes through `shell_single_quote`. Replaces
  `quote_path_if_spaced` on the uninstall side because the fallback chain
  is destructive (`rm -rf <pkg_dir>`), so a `;` / `$` / backtick in the
  home dir would have let the chain inject extra commands.
- New `win_quote_path_for_user_shell` (no `%` 4x escape) splits from
  `win_quote_path_for_batch`. Uninstall hints are copy-paste targets, not
  `.bat + call` payloads, so the two-round percent expansion that
  motivates the 4x escape doesn't apply.
- POSIX `nvm|fnm|mise|homebrew` branch appends physical-delete fallback
  `; [ -e <bin> ] && rm -f <bin> && rm -rf <pkg_dir>` because nvm v18.20.8
  was observed to silently no-op `npm rm -g` (exit 0 with `up to date`
  message, no filesystem change). Anchored `<node_root>/{bin,lib}` layout
  assumption documented as branch-specific.
- `ToolInstallation` gains `uninstall_command: String` and
  `uninstall_command_needs_cmd_hint: bool`. The bool is computed as
  `cfg!(target_os = "windows") && uninstall_command.contains('"')` — a
  compile-time platform gate avoids false positives from POSIX
  `shell_single_quote`'s `'"'"'` escape form, which also contains `"`.
- `enumerate_tool_installations` computes `source` once and threads it
  into `uninstall_command_from_paths`, removing a redundant
  `infer_install_source` call (review N1).

Frontend (src/components/settings/AboutSection.tsx + src/lib/api/settings.ts):
- Remove the JS helpers `buildUninstallCommand`, `dirOfPath`,
  `isWindowsPath`, `shellQuote`, `TOOL_NPM_PACKAGES`. Conflict rows now
  read `inst.uninstall_command` directly.
- Render a PowerShell-call-operator hint when
  `inst.uninstall_command_needs_cmd_hint` is true. Avoids string-match
  inference from the command (which fails on macOS user names containing
  `'`, e.g. `o'leary`, because `shell_single_quote`'s escape contains `"`).
- `ToolInstallation` TS interface gains the two new fields.

i18n (zh/en/ja):
- New key `settings.toolUninstallPwshHint` documents the PowerShell
  `&` (call operator) requirement for quoted paths.

Tests: 30 new cases under `commands::misc::tests::anchored_upgrade` cover
each POSIX branch (brew formula extraction, npm anchored with fallback,
pnpm, volta, bun, hermes), strong-quoting under `;` / `'` paths, the
fallback-only-for-anchored-branches inverse guard, plus mirror Windows
helpers for the user-shell quoter and a `path%foo%` integration case
demonstrating the literal `%` preservation contract. Total
`commands::misc` test count: 68.
2026-05-25 22:20:34 +08:00
Jason 671859748d feat(settings): extend anchored tool upgrades to Windows native paths
Apply macOS-side anchored upgrades (9984eccb) to Windows. Six tools now
upgrade via an absolute path derived from the install actually hit by the
command line, instead of bare `npm i -g` landing on PATH-first npm. WSL
tools explicitly bypass anchoring (Windows-host paths invalid in distro).

Scope: 7+ Windows package managers compress to 3 idioms in practice
(Scoop/Chocolatey/winget/nvm-windows/MS Store all just install node; the
global-package layer is still npm):
- volta  -> <sibling>\volta.exe install <pkg>
- pnpm   -> <sibling>\pnpm.cmd add -g <pkg>@latest
- others -> <sibling>\npm.cmd i -g <pkg>@latest

Cross-platform:
- infer_install_source: add /volta/ (no dot) and /pnpm/ matches so
  %LOCALAPPDATA%\{Volta,pnpm} route correctly.
- parent_dir: recognize both \ and /, take rightmost (Option<usize>
  Ord lets None<Some, so rfind('\\').max(rfind('/')) auto-picks).
- npm_package_for, default_install, installs_anchored_command:
  promoted from cfg(not(windows)) to all-platforms.
- plan_command_for: merged the two cfg branches; Windows+WSL short-
  circuits to wsl_tool_action_shell_command (not static_fallback) so
  the command shown to the user matches what build_tool_action_line
  actually runs.
- ToolInstallation: add #[serde(skip)] real: PathBuf, populated by
  enumerate, read by installs_anchored_command — no more double
  canonicalize, and closes a TOCTOU window between enumerate and anchor.

Windows-only helpers (#[cfg(target_os = "windows")]):
- sibling_bin_with_ext reads fs to pick .cmd vs .exe (Node installer
  drops .cmd, Volta drops .exe; pure string can't disambiguate).
- win_double_quote shared primitive; win_quote_path_for_batch handles
  cmd token-boundary chars (space, &, (, ), ^, ;, <, >, |, ,) by
  wrapping in quotes, and handles `%` via 4x escape (%%%%) to survive
  both .bat parser expansion AND `call`'s own second percent-expansion
  pass (Microsoft `call /?`: "percent (%) expansion is performed on
  each parameter").
- wsl_tool_action_shell_command wraps tool_action_shell_command so
  hermes inside WSL gets python3||python instead of Windows-target
  py||python (py launcher is Windows-only, missing in WSL distros).

Wire-up:
- build_tool_action_line Windows: WSL -> wsl_tool_action_shell_command
  + wsl.exe wrap; native update -> enumerate + anchored + static
  fallback. Everything gets `call ` prefix (.bat needs it for .cmd
  without replacing the current script; harmless for .exe).

Tests: 33 new — 10 platform-agnostic (install_source_classification,
parent_dir_cases) + 23 cfg-gated Windows-only (anchored_upgrade_windows,
windows_helpers). Anchored expected values use a small expect_quoted_path
mirror in the test mod so assertions stay correct on Windows hosts whose
%TEMP% itself contains spaces/special chars (e.g. user accounts named
"John Doe"); the 7 hardcoded-literal win_quote_* unit tests independently
lock the quoting rules themselves, so mirror drift would be caught by
either side.

Limitation: Windows cfg-gated tests don't run on macOS cargo test.
Validated on macOS host: cargo fmt clean, clippy --all-targets 0
warnings, cargo test --lib 1322 passed. Windows CI runs only on release
tag (release.yml has windows-2022); production validation needs cargo
test on a Windows machine before broad rollout.
2026-05-25 22:20:34 +08:00
Jason c6fd2415c3 fix(settings): enforce absolute paths for all anchored upgrade branches
- misc: extend sibling_bin derivation to claude/brew/volta/bun in addition
  to npm. Return Option<String> so the anchored-path invariant cannot be
  silently violated — when bin_path has no parent directory, propagate
  None and fall back to the static command at the call site instead of
  emitting a bare command that depends on the GUI process PATH.
- misc: factor out quote_path_if_spaced to keep all five anchored
  branches consistent when the resolved path contains spaces.
- AboutSection: add preflightTools lock + try/finally around
  probeToolInstallations so fast double-clicks cannot race two probe
  rounds into concurrent executeRun calls or duplicate confirm dialogs.
- Tests: cover sibling_bin None branch and space-quoting for every
  anchored branch (claude/brew/volta/bun).
2026-05-25 22:20:34 +08:00
Jason 108dda1772 feat(settings): prefer official installer for tool install with npm fallback
Bare `npm i -g <pkg>` was the install command for every managed tool, but
Anthropic and SST now both recommend their native installers over npm. The
update path already anchors to native installs (`claude update` and friends),
so install was the last place still forcing npm — even when the user's
intent was clearly to get the upstream-recommended install.

- New `install_command_for(tool)` (non-Windows only): claude and opencode
  now run the upstream installer with a `|| npm i -g ...@latest` POSIX
  short-circuit fallback, so the tool still installs if the URL is
  unreachable.
- codex / gemini / openclaw / hermes pass through to the original static
  command — they have no independent official installer today.
- `build_tool_lifecycle_command` now opens `set -o pipefail` alongside
  `set -e`: without it, `curl ... | bash` where curl fails would have bash
  exit 0 on empty stdin, silently masking the failure and skipping the
  `||` fallback.
- 6 new `install_strategy` unit tests pin the per-tool install command
  shape, mirroring the existing anchored_upgrade regression suite.

Update routing and Windows install behavior are unchanged.
2026-05-25 22:20:34 +08:00
Jason e25682d345 fix(proxy): source takeover model fields from target provider on managed accounts
When a managed-account provider (GitHub Copilot or Codex OAuth) is taken
over by the local proxy, the *_MODEL_NAME entries written to Claude live
config used to be snapshotted from the live file on disk, which still
held the *previous* provider's values during a switch. The result was a
stale display name lingering after the switch.

Read the model snapshot from the target provider's effective settings
(common-config merged) when the provider uses managed-account auth;
preserve the existing behavior of reading from the live config for
normal providers. The three takeover entry points now resolve the
effective provider up front so common-config writes flow through.
2026-05-25 22:20:34 +08:00
Jason 014c82d28b feat(settings): anchor tool upgrades to the actual install
Rework the About tool-upgrade flow so upgrades target the install the
command line is actually using, instead of running bare `npm i -g` and
landing on PATH's first npm — which used to move upgrades to the wrong
location or fail outright when the resolved bin had no sibling npm.

Anchored upgrade command (update path, non-Windows):
- claude native installer (~/.local/share/claude/versions/) -> `claude update`
- Homebrew formula (canonical path under /Cellar/) -> `brew upgrade <formula>`
- volta / bun -> `volta install` / `bun add -g`
- Node managers with sibling npm (nvm/fnm/mise/homebrew-npm) -> that
  directory's npm with `i -g <pkg>@latest`
- system / unknown sources (e.g. opencode install.sh under ~/.opencode/bin,
  ~/go/bin) -> fall back to the bare command, surfaced as anchored=false
  so the UI shows an honest "default entry not determinable" hint instead
  of pretending the upgrade is targeted.

Multi-install confirmation:
- When the probe finds >=2 installs, pop ToolUpgradeConfirmDialog showing
  each install (source badge + path + version + Default badge) and the
  resolved command before executing. Top-level text only asserts what is
  universally true ("won't update all of them; see each tool below");
  per-card text adapts to anchored vs unanchored.
- Pending upgrade state stores the full upgrade set; the dialog only
  shows the subset that needs confirmation, so non-conflicting tools in
  a batch still get upgraded after confirm.

Unified probe command:
- Merge the previous diagnose_tool_installations and plan_tool_upgrades
  into a single probe_tool_installations returning installs + is_conflict
  + needs_confirmation + command + anchored. Diagnose button, post-upgrade
  auto-diagnose, and pre-upgrade confirmation all share one IPC. The
  diagnose button's previous Promise.all of 6 IPCs is now a single call.

resolve_path_default robustness:
- The previous lines().next() was poisoned by interactive .zshrc output
  (welcome banners, p10k instant prompts, etc.), causing default-install
  detection to fail and dropping multi-install scenarios into the
  unanchored fallback even when one install was clearly the native one.
- Replaced with first_abs_path_line that scans for the first
  absolute-path line and ignores noise, mirroring how try_get_version
  already tolerates banner noise via a regex.

Diagnostic staleness fix:
- diagnoseToolSilently now clears stale diagnostics in the else branch
  when the conflict no longer holds (previously only wrote on conflict,
  never cleared, so externally resolving a conflict left the card stuck
  on a stale list until the user clicked Diagnose).
- Auto-diagnose now triggers after any successful update, not only when
  the version didn't change, so the card reflects the latest conflict
  state even when an anchored upgrade succeeds while another install
  remains.

Other:
- Shared ToolInstallRow between the conflict list and the confirmation
  dialog removes the duplicated per-install row JSX.
- Drop the new shell_quote_path helper in favor of reusing the file's
  existing POSIX-correct shell_single_quote, gated on whitespace.
- Collapse displayName lookup into a stable module-level helper to remove
  the `as ToolName` cast and avoid recreating the closure each render.
- 17 backend unit tests covering anchored command generation across each
  source, brew formula extraction, is_conflicting thresholds, default
  install resolution, and the welcome-banner scenario.
- i18n (zh/en/ja): new keys for confirmation dialog
  title/hint/will-run/confirm-button and the unanchored hint.
2026-05-25 22:20:34 +08:00
Jason ce232a1452 feat(settings): diagnose conflicting tool installations with uninstall hints
Add a "Diagnose installs" action to the About section that enumerates every
installation of each managed CLI, flags real conflicts (diverging versions
or mixed runnable state), and lists them under the affected tool card.

- backend: enumerate_tool_installations + diagnose_tool_installations command,
  sharing build_tool_search_paths with the single-probe scan; resolve the PATH
  default via the same login shell as version probing so the "Default" marker
  matches what the command line (and an upgrade) actually targets
- frontend: global diagnose button left of Refresh, per-card conflict list,
  and a copy-only uninstall command per install -- source-aware (npm/volta/
  bun/pip) and anchored to that install's own npm to avoid removing the wrong
  node version; marked with a red trash icon, never executed
- auto-diagnose silently after an upgrade that leaves the version unchanged
  or installs something that can't run
- i18n: zh/en/ja
2026-05-25 22:20:34 +08:00
Jason ea604a1827 fix(settings): surface "installed but not runnable" state in tool cards
After an install/update command succeeds, re-probe the tool version: if it
still can't be detected the tool is installed-but-unrunnable (e.g. Node too
old), so report a warning toast and show "installed · can't run" with the
cause, instead of a misleading "success" plus a stale version number.

Read the backend `installed_but_broken` flag rather than matching error
text; the card's current-version line, action button (no useless "install"
for a broken tool), and a "check environment" hint all key off it. Drop the
now-redundant version-clearing setState (the refresh merge already nulls it),
flatten the action ternary, and use extractErrorMessage in the catch path.

Adds toolNotRunnable / toolActionInstalledNotRunnable / installedNotRunnable
/ toolCheckEnv i18n keys (zh/en/ja).
2026-05-25 22:20:34 +08:00
Jason 768c5f9f39 fix(misc): probe tool versions faithfully instead of masking unrunnable installs
Unify the three probe paths (try_get_version / try_get_version_wsl /
scan_cli_version) on a cross-platform ShellProbe enum that distinguishes
"not installed" (shell exit 127) from "installed but --version failed"
(e.g. Node too old to run the freshly-upgraded CLI).

The found-but-broken case is now reported as-is and no longer falls back to
scan_cli_version. Previously the fallback surfaced a stale runnable copy
installed elsewhere (e.g. a Homebrew node vs the nvm node the upgrade wrote
to), making an upgrade look like it had no effect ("succeeded but version
unchanged").

Expose the state via a structured `installed_but_broken` flag on ToolVersion
so the frontend no longer infers it by string-matching the error text. Also
fixes a WSL path that could mislabel a genuinely-missing tool as broken, and
extracts the NOT_INSTALLED constant.
2026-05-25 22:20:34 +08:00
Jason f8b4d67b21 fix(settings): run batch updates per-tool and lock actions while busy
Update All previously sent every tool to the backend as one script, where
set -e (or errorlevel on Windows) aborts the whole batch on the first
failure, skipping the rest and not refreshing versions for tools that did
succeed. Run each tool as its own call instead: failures are isolated,
each tool's version refreshes as soon as it finishes, and the result is
summarized in a toast (success / partial / failure) listing which tools
failed.

Also derive an isAnyBusy flag and disable all install/update buttons,
the refresh button and the WSL shell selectors while any action is
running, so users can't trigger concurrent global npm/pip writes.

Add the toolActionPartial i18n key (zh/en/ja).
2026-05-25 22:20:34 +08:00
Jason 820c4db1b0 feat(misc): broaden CLI version detection to PATH and Windows managers
Extend scan_cli_version search paths with the PATH environment variable
and common Windows Node/version-manager locations (pnpm, Volta, nvm,
Scoop, Yarn). Entries from PATH are skipped when they point at the
Microsoft\WindowsApps App Execution Alias directory, which is what
previously caused bogus launches on Windows.

Add unit tests for PATH dedup, child-dir suffix expansion, and the
WindowsApps alias skip.
2026-05-25 22:20:34 +08:00
Jason d7ede24838 docs: update settings manual for tool management and Hermes
Add Hermes to the environment-check table and app-switcher list, fix the
OpenCode install command (opencode-ai), and describe the new update/install
flow. Align with the final implementation: drop the removed Install Missing
action, note that installs run silently with in-button progress, and rename
the section to Manual Install Commands (now collapsible).
2026-05-25 22:20:34 +08:00
Jason e3df86587d feat(settings): expand About page into a tool management panel
List all managed apps with current/latest versions, with per-tool install
and update buttons plus an Update All action. Installs and updates now run
silently: the button shows a spinner for the full duration, versions refresh
automatically when done, and failures surface the backend error detail in a
toast.

While loading, the button keeps its label and only swaps the icon for a
spinner, so width stays constant across zh/en/ja instead of jumping when the
text changes (e.g. Update -> Updating...).

Also collapses and renames the install-commands area to Manual Install
Commands, and removes the managed-apps badge row and the Install Missing
batch button.
2026-05-25 22:20:34 +08:00
Jason ee2d634d89 feat: add silent install/update lifecycle for managed CLI tools
Expand tool version detection to all six managed apps (including Hermes
via PyPI), and add a run_tool_lifecycle_action command that installs or
updates CLI tools silently: it captures the subprocess output and blocks
until the command actually finishes instead of popping a terminal window
(Windows uses CREATE_NO_WINDOW). On failure the last lines of stderr are
returned so the UI can surface a useful message.

Also restores the Windows version-detection path by gating try_get_version
behind cfg(not(windows)) so it no longer risks triggering the App
Execution Alias / protocol handler that previously disabled Windows.
2026-05-25 22:20:34 +08:00
Jason c12d20efd0 refactor(proxy): replace panic-prone unwrap/expect with safe patterns
Harden the proxy module against panics by removing optimistic
unwrap()/expect() calls in favor of pattern matching and graceful
fallbacks:

- copilot_optimizer/cache_injector: bind Value::Array/String directly
  instead of is_array()+as_array().unwrap(); use is_none_or and in-place
  string mutation
- hyper_client: gate the raw-write path with if-let + filter instead of
  has_cases + unwrap()
- gemini_shadow: recover poisoned RwLock via into_inner() rather than
  panicking, with warn logging
- streaming_codex_chat: replace expect("tool state exists") with
  let-else (return/continue)
- merge_tool_results: early-return when messages is absent
- sse: fall back to from_utf8_lossy on the UTF-8 boundary slice

No behavior change on the happy path; all proxy tests pass.
2026-05-25 22:20:34 +08:00
Jason 279b9eabde test: align stale tests with merged Codex preset and bucket changes
CI on main was red because two tests did not follow intentional changes
that were already merged into the codebase:

- codexChatProviderPresets.test.ts still expected the "Kimi For Coding"
  preset, which was removed in 16c3ef3f. Drop the corresponding entry
  from the expected presets map.
- import_export_sync.rs still asserted the legacy per-provider
  model_provider id ("rightcode"), but 9fac15b8 unified Codex
  third-party providers into the stable "custom" history bucket. Mirror
  the assertion update already applied to provider_service.rs.

No production code changed; both fixes only update test expectations.
2026-05-25 22:20:34 +08:00
Jason f9db9913a0 fix: coerce empty tool-call arguments to {} in Codex Chat transform
No-argument tool calls produced empty argument strings that passed
through both the streaming response path and the request transform
verbatim. Strict OpenAI-compatible upstreams (e.g. Minimax) reject
`arguments: ""` with a 400 "invalid function arguments json string",
while lenient ones (OpenAI, Kimi) silently treat it as an empty object.

Add canonicalize_tool_arguments / canonicalize_tool_arguments_str helpers
that coerce empty/whitespace arguments to "{}" and apply them at the four
tool-call argument sites (streaming finalize + three request/response
transform paths). Leave function_call_output content untouched, where an
empty string is valid.
2026-05-25 22:20:34 +08:00
Jason 11edc96a15 docs: document Codex Chat reasoning auto-detection
Add a "Reasoning Auto-Detection" subsection to the Codex local-routing
manual (zh/en/ja) with the provider capability matrix, and record the
feature plus the streaming-usage and tool-call reasoning backfill fixes
in the changelog. Drop the removed Kimi For Coding preset from the
changelog's Codex Chat preset list.
2026-05-25 22:20:34 +08:00
Jason 44d9aabbf3 feat: adaptive reasoning detection for Codex Chat providers
Auto-detect each Chat-routed Codex provider's reasoning interface from
its name, base URL, and model, then inject the matching thinking
parameter without manual configuration:

- Platform-first inference (OpenRouter, SiliconFlow) overrides model
  rules, since the same model exposes different reasoning controls
  depending on the hosting platform.
- Effort tiers are forwarded only to providers that support them
  (DeepSeek, OpenRouter, and StepFun's step-3.5-flash-2603); on/off-only
  providers (Kimi, GLM, Qwen, MiniMax, MiMo, SiliconFlow) drop the level
  instead of sending a field the upstream rejects.
- OpenRouter uses the native reasoning:{effort} object, clamps max to
  xhigh (its enum has no max), and forwards an explicit effort:"none" so
  reasoning can be turned off.
- StepFun falls back to inference so per-model effort support is honored
  (the static preset would have forced effort on step-3.5-flash too).

Includes the Codex provider-form reasoning controls, i18n strings
(zh/en/ja), and response-side reasoning extraction.
2026-05-25 22:20:33 +08:00
Jason 5048ed632d fix: inject stream_options.include_usage for Codex Chat streaming
Responses-to-Chat conversion did not set stream_options.include_usage,
so OpenAI-compatible upstreams (kimi/MiniMax, etc.) omitted the trailing
usage chunk in streaming mode. This caused token/cost/cache stats to be
recorded as zero for third-party streaming requests routed through the
Codex Chat path.

Inject include_usage when the request is streaming, merging into any
client-provided stream_options instead of overwriting it. Add tests for
the streaming, non-streaming, and merge cases.
2026-05-25 22:20:33 +08:00
Jason 7410494645 feat: remove Kimi For Coding preset from Codex
The Kimi For Coding preset pins users to a single coding-only model
(kimi-for-coding), restricting model selection. Drop it from the Codex
presets and trim the corresponding row in the trilingual user manual.
The general Kimi preset (Moonshot platform) is kept, and presets for
other apps are unchanged.
2026-05-25 22:20:33 +08:00
Jason b710c6549e fix: backfill placeholder reasoning_content for bare tool-call messages
Thinking models like kimi/Moonshot and DeepSeek reject any assistant
message carrying tool_calls without a non-empty reasoning_content. When
cross-turn history recovery misses (proxy restart drops the in-memory
cache, ambiguous call_id, or a turn produced no reasoning upstream), the
converted assistant message has none and the whole request fails with
'reasoning_content is missing in assistant tool call message'.

Add a final-stage backfill that runs after all input items are
processed, so genuine trailing reasoning items still attach first and a
placeholder is only injected when none remains. Mirrors the placeholder
behavior in transform::anthropic_to_openai_with_reasoning_content.
2026-05-25 22:20:33 +08:00
Jason 184cbcdc47 fix: reclassify ClaudeAPI as aggregator to re-enable model test
ClaudeAPI supports the health/stream check, but the third_party
category triggers the isClaudeThirdParty gate in ProviderCard that
disables the model test button for third-party Claude providers.
Recategorizing as aggregator restores the test action; the partner
star is unaffected since it is driven by isPartner, not category.

Applied to both the Claude Code and Claude Desktop presets.
2026-05-25 22:20:33 +08:00
Jason 04af87bc7b docs: document Codex Chat provider support in changelog and manual
Backfill the empty [Unreleased] CHANGELOG section with the Codex Chat
Completions feature (Chat-to-Responses bridge, 23 third-party presets,
model mapping table, Stream Check routing, error-envelope conversion,
"custom" history bucket) plus the community fixes landed since v3.15.0.

Update the zh/en/ja user manual: split the Codex preset tables by
upstream protocol (native Responses vs Chat Completions), add a "Codex
Local Routing and Model Mapping" section covering the Needs Local
Routing toggle and the model catalog, and note Chat-format probing in
the Stream Check guide. Manual wording matches the live UI strings.
2026-05-25 22:20:33 +08:00
Jason ead9e22b21 feat: convert Codex Chat error responses to Responses envelope
The Codex Chat-to-Responses bridge already rewrites successful upstream
responses to the Responses shape, but the error branch in
handle_codex_chat_to_responses_transform passed Chat-shaped error bodies
through untouched (MiniMax base_resp, raw OpenAI Chat error, text/plain
"Unauthorized" pages, etc.), leaving Codex clients unable to recognize the
error.

Add chat_error_to_response_error in transform_codex_chat to regularize all
upstream error shapes into the standard {error: {message, type, code, param}}
envelope, then wire it through a new handle_codex_chat_error_response that
preserves the original HTTP status code. Non-JSON error bodies (HTML, plain
text) are wrapped as Value::String and truncated to 1KB at a UTF-8 char
boundary to keep diagnostic context without flooding the response.

Also fix a pre-existing append-vs-insert pitfall in three rebuilt-body
branches (Claude transform, Codex Chat normal, Codex Chat error): http
Builder::header is append, so leaking the upstream Content-Type produced
two Content-Type headers when the rewritten body was JSON. Remove the
upstream value before writing application/json.
2026-05-25 22:20:33 +08:00
Jason 72bc912e0d feat: route Codex Chat providers through Stream Check
Codex Chat providers (apiFormat=openai_chat, e.g. DeepSeek, MiniMax, Kimi)
were incorrectly probed via /v1/responses by Stream Check, which the upstream
rejects. Detect chat routing via codex_provider_uses_chat_completions and
issue the probe against /chat/completions with a Chat-shaped body.

Also align URL fallback order with the production CodexAdapter::build_url:
origin-only base URLs (https://api.deepseek.com) must hit /v1/<endpoint>
first; bare /<endpoint> only as a fallback. The previous order made any
non-404 error on the bare path (401/400/405) flag the provider as down even
though /v1/<endpoint> would have succeeded.

- Lift origin-only detection into proxy::providers::is_origin_only_url so
  both build_url and Stream Check share a single source of truth.
- Collapse resolve_codex_stream_urls and resolve_codex_chat_stream_urls into
  a generic resolve_codex_endpoint_urls(base_url, is_full_url, endpoint),
  which also gives the Responses path a symmetric "full endpoint without
  is_full_url flag" fallback for free.
- Restrict reasoning_effort propagation in the Chat branch to OpenAI o-series
  models, mirroring transform_codex_chat's runtime check.
2026-05-25 22:20:33 +08:00
Jason 955904f719 refactor: rewrite Codex local routing toggle hints for clarity
Reframe OFF/ON hints as action guidance (when to enable) rather than
scenario descriptions, mirroring the Claude Desktop model mapping copy
style. Synced across zh/en/ja locales and the component-level
defaultValue fallback. The switch label "Needs Local Routing" is kept
unchanged to preserve the routing-layer semantics specific to Codex.
2026-05-25 22:20:33 +08:00
Jason 9d35709805 fix: collapse mid-stream system messages in Codex Responses to Chat conversion
MiniMax's OpenAI-compatible chat endpoint strict-rejects any non-leading
role=system message with "invalid params, chat content has invalid message
role: system (2013)". The Codex client uses role=developer (and occasionally
role=system) to inject collaboration_mode / permissions / skills blocks
mid-conversation, and responses_role_to_chat_role maps both to chat's
system role. The converted messages array therefore frequently contained
system entries past index 0, which DeepSeek and OpenAI tolerate but MiniMax
flags as 2013.

Collapse all system messages into a single leading system message before
returning the chat request. The rewrite preserves every system fragment
(joined by "\n\n" in original order) and leaves non-system messages
untouched, so it is lossless for permissive backends as well.

- Add collapse_system_messages_to_head in transform_codex_chat.rs.
- Run it on the messages vector at the end of responses_to_chat_completions
  before serializing.
- Cover the new path with two unit tests: one repros the MiniMax-shaped
  input (developer items between users) and asserts no system role past
  index 0; the other verifies non-system order is preserved and content
  is joined with "\n\n".
2026-05-25 22:20:33 +08:00
Jason f2935a3db9 feat: add Chat Completions routing for 22 Codex third-party presets
Enable openai_chat routing with explicit model catalogs across the major
Chinese/Asian providers (DeepSeek, Zhipu GLM, Kimi, MiniMax, Baidu Qianfan,
Bailian, StepFun, Volcengine Agent Plan, BytePlus, DouBaoSeed, ModelScope,
Longcat, BaiLing, Xiaomi MiMo, SiliconFlow, Novita AI, Nvidia, etc.). Each
preset declares its context window so the UI can size catalog rows when the
preset is picked.

Also lands two consistency fixes uncovered along the way:
- Include setCodexCatalogModels in resetCodexConfig's useCallback deps to
  match the new third parameter it consumes.
- Realign TheRouter Codex test to the "custom" model_provider bucket
  established by the recent third-party unification; the previous assertion
  predated that refactor and had been failing on HEAD.
2026-05-25 22:20:33 +08:00
Jason ad8bdf16ae fix: preserve Codex model catalog on live read of active provider
Editing the currently active Codex provider triggered `read_live_settings`,
which returned only { auth, config }, omitting `modelCatalog`. The form's
mapping table then initialized to empty, and a subsequent save wiped the
DB's `modelCatalog` field — silently destroying user-configured model
mappings after every CC Switch restart.

The mappings already live on disk as a projection in
`~/.codex/cc-switch-model-catalog.json` (pointed at by `config.toml`'s
`model_catalog_json`). Reverse-parse that file so live reads return the
same shape the save path writes.

- Add `read_codex_model_catalog_simplified_from_live` to recover
  `{ model, displayName?, contextWindow? }` entries from the catalog file.
- Skip user-managed external catalogs (filename != cc-switch-model-catalog.json)
  so we don't downgrade their richer structure to the simplified table.
- Squash display_name == slug and context_window == default (config's
  `model_context_window`, or 128_000 fallback) so blank inputs round-trip
  back to blank instead of materializing fallback values in the UI.
- Collapse all failure modes (missing file, parse error, no matching
  field) to Ok(None) so the editor stays openable when the projection
  file is absent or corrupt.
- Wire the new function into `read_live_settings`'s Codex branch.
- Cover the new pure helpers with 7 unit tests in codex_config::tests.
2026-05-25 22:20:33 +08:00
Jason b44f83f7c5 feat: unify Codex third-party providers into stable "custom" history bucket
Codex filters resume history by `model_provider`, so switching between
provider-specific ids like `rightcode` and `aihubmix` made past sessions
appear to vanish. Collapse all third-party providers into a single
stable bucket so cross-switch history stays visible.

- Normalize live `model_provider` to "custom" on every Codex write
  (reserved built-in ids like openai/ollama are preserved).
- Add device-level one-shot migration that rewrites historical JSONL
  session files and the `state_5.sqlite` threads table from legacy
  provider ids into the "custom" bucket. Backs up originals under
  `~/.cc-switch/backups/codex-history-provider-migration-v1/` and uses
  the SQLite Backup API for the state DB.
- Record completion in `settings.json` under `localMigrations` so the
  migration is strictly idempotent across launches.
- Update Codex provider preset templates to emit `model_provider = "custom"`
  out of the box.
2026-05-25 22:20:33 +08:00
Jason 2a4651a21e feat: preserve user-selected catalog model in Codex Chat requests
When Codex client sends a model from the catalog (e.g., user selected via /model),
preserve that choice instead of always replacing with config.toml's default model.

- Check if request model exists in modelCatalog before falling back to config model
- Remove CODEX_CHAT_CLIENT_MODEL constant (no longer needed)
- Add test coverage for catalog model preservation
2026-05-25 22:20:33 +08:00
Jason 9b9578206b fix: prevent infinite render loop in Codex model catalog
Break bidirectional sync cycle between catalogRows (child) and catalogModels (parent):
- Remove catalogModels from child→parent effect dependencies
- Track last sent data in ref to avoid redundant callbacks
- Sync ref when parent pushes new data to prevent false positives

Fixes severe UI jittering when adding/editing catalog entries.
2026-05-25 22:20:33 +08:00
Jason 791ced0034 fix: Codex model catalog WYSIWYG and config consolidation
- Remove mergeCodexDefaultCatalogModelForSave implicit injection (P1)
  The model mapping table is now the single source of truth; no hidden
  entries are prepended on save.

- Sync first catalog row model into config.toml on save
  Ensures Codex default request model matches the table's first entry
  instead of retaining a stale template value.

- Remove API Format selector from CodexFormFields (P3)
  wire_api is always 'responses'; the selector confused users into
  thinking they were changing the upstream protocol. Only the 'Needs
  Local Routing' toggle remains.

- Add restart hint to model mapping i18n text (P2)
  model_catalog_json is loaded at Codex startup; users are now informed
  that a restart is needed after changes.

- Unify write_codex_live_with_catalog helper (P4)
  Replaces three scattered prepare+write call sites in config.rs,
  provider/live.rs, and proxy.rs with a single entry point.

- Clean up useCodexConfigState dead state (P3 follow-up)
  Remove codexModelName, codexContextWindow, codexAutoCompactLimit and
  their handlers/effects since no component consumes them after the UI
  consolidation.
2026-05-25 22:20:33 +08:00
Jason 90b7f25111 - Restore Codex Chat reasoning fallback
- Add unique call-id fallback when Codex omits or rewrites previous_response_id.

- Keep ambiguous call ids unresolved to avoid cross-request history leaks.

- Cover fallback and ambiguity behavior with regression tests.
2026-05-25 22:20:33 +08:00
Jason 22fbe6f11a - Optimize Codex Chat cache stability
- Stop deriving Codex session/cache identity from `previous_response_id`.
  - Canonicalize parseable JSON string payloads in Chat and Responses tool conversions.
  - Add regression coverage for cache-sensitive conversion behavior.
2026-05-25 22:20:33 +08:00
Jason 74acf1e387 Add Codex Chat-to-Responses bridge
- Add Codex provider API format selection and model mapping for Chat-only upstreams.
- Convert Codex Responses requests to Chat Completions and rebuild Chat responses as Responses output.
- Preserve reasoning_content across non-streaming, streaming, tool calls, and previous_response_id follow-ups.
- Add a bounded Codex Chat history cache for restoring tool calls before tool outputs.
- Cover Chat bridge, compact routing, streaming, and history recovery with focused tests.
2026-05-25 22:20:33 +08:00
狂飙 5315fa284b Update 1.2-installation.md (#2949)
增加 Windows 运行后无提示的修复方法
2026-05-20 15:04:56 +08:00
Jason 00b6cc6809 fix: format providerConfigUtils.ts to pass CI checks 2026-05-19 16:40:19 +08:00
Jason 398f40dacb docs: recommend official Homebrew cask installation
- Remove personal tap requirement from all READMEs (en/zh/ja)
- Update v3.15.0 release notes to highlight official cask availability
- Add celebration banner noting Homebrew official repository inclusion
- Simplify installation to single command: brew install --cask cc-switch
2026-05-19 16:14:56 +08:00
Jason 09f67c1b38 Handle inline thinking in Codex Chat conversion
- Split leading <think> blocks from Chat content into Responses reasoning output.
- Keep assistant text output free of inline thinking tags.
- Support streamed inline thinking blocks before normal text deltas.
- Add regression coverage for MiniMax-style inline thinking responses.
2026-05-19 11:06:12 +08:00
Jason 79d6486e16 Improve Codex Chat reasoning conversion
- Convert Chat reasoning_content and reasoning fields into Responses reasoning output items.
- Emit Responses reasoning summary SSE events for streamed Chat reasoning deltas.
- Preserve output ordering when reasoning, text, and tool calls are streamed together.
- Add regression coverage for data-only Chat SSE errors, multiple tool calls, and compact routing.
2026-05-19 10:33:24 +08:00
Jason 1c82b8a3fa Add Chat Completions routing for Codex providers
- Add a Codex API format selector and routing badge for Chat Completions providers.
- Convert Codex Responses requests to upstream Chat Completions when routing is required.
- Convert Chat Completions JSON and SSE responses back to Responses format.
- Keep generated Codex wire_api values on Responses for Codex compatibility.
- Add i18n labels, provider metadata handling, and focused conversion tests.
2026-05-19 10:23:48 +08:00
Jason 61e68d754c fix(proxy): inject only ANTHROPIC_API_KEY for managed-account Claude takeover
- Provider: add uses_managed_account_auth / is_github_copilot helpers
  to identify managed-account providers (GitHub Copilot / Codex OAuth)
- ProxyService: choose auth policy by provider type when taking over
  Claude Live config. Managed accounts drop token env keys and write
  only the ANTHROPIC_API_KEY placeholder; other providers keep the
  existing ANTHROPIC_AUTH_TOKEN fallback behavior
- Forwarder: add outbound guard that refuses to send the PROXY_MANAGED
  placeholder upstream to *.githubcopilot.com and chatgpt.com
  /backend-api/codex
- Add unit tests covering detection, injection, and the outbound guard
2026-05-18 22:46:18 +08:00
Jason 76b4c8b509 chore: remove LionCC sponsor and presets
- Remove LionCC sponsor entry from all README files (en/zh/ja)
- Remove LionCCAPI presets from all provider configs
- Remove lionccapi i18n keys from all locales
- Keep lioncc.png icon file as requested
2026-05-18 16:59:13 +08:00
Jason ddde7f13b3 - docs: update user manual for v3.15.0
- Sync zh/en/ja manuals with Claude Desktop and Hermes support

- Update install requirements, official channels, and release asset guidance

- Document Usage Hero, Codex OAuth live models, Save Anyway, Hermes sessions, and Warp launch

- Correct tray and app-scope descriptions to match current implementation
2026-05-18 16:59:13 +08:00
mrzhao c9efec294b fix(skills): install correct skill from skills.sh search results (#2784)
* fix(skills): install correct skill from skills.sh search results

When multiple skills share the same directory name across different repos,
SkillCard was passing directory to onInstall/onUninstall, causing handleInstall
to always match the first result. Switch to using the unique key field
(directory:repoOwner:repoName) for precise identification.

* test(skills): add regression test for skills.sh install by key

Verifies that clicking install on the second card when two skills share
the same directory name correctly installs the second skill, not the first.

---------

Co-authored-by: mrzhao <mrzhao@iflytek.com>
2026-05-18 11:45:54 +08:00
Roger Deng 0977dcd1c1 fix skill sync copy fallback (#2791) 2026-05-18 11:40:45 +08:00
Roger Deng 6e8ee094f1 fix(usage): reduce price input step to 0.0001 for sub-cent precision (#2793)
The step was 0.01, preventing input of prices like DeepSeek's cache read
cost ($0.0028/million tokens). Extract step value to a constant and apply
to all four price fields.

Closes #2503
2026-05-18 11:38:32 +08:00
luw2007 5ae9c2605d fix(terminal): Ghostty opens clean window instead of cloning existing tabs (#2801)
When Ghostty is already running, `open -a` silently ignores `--args`,
and `open -na` clones all existing tabs into the new instance.

Add a dedicated `launch_macos_ghostty` that uses
`--quit-after-last-window-closed=true` and `-e bash <script>` to spawn
a single clean window running claude.

Also change `launch_macos_open_app` from `open -a` to `open -na` so
other terminals (Alacritty/Kitty/WezTerm/Kaku) correctly open a new
window when already running.

Closes #2798
2026-05-18 11:37:27 +08:00
BlueOcean 0fb7fd12e5 feat: add Xiaomi MiMo Token Plan presets (#2803)
* feat: add Xiaomi MiMo token plan presets

* fix: update Xiaomi MiMo provider presets

* fix: align MiMo V2.5 model specs with official documentation

- Update maxTokens from 32000 to 131072 (128K) for mimo-v2.5-pro and mimo-v2.5
- Update contextWindow from 262144 to 1048576 (1M) for mimo-v2.5
- Aligns with official specs from Xiaomi MiMo documentation
- Ensures consistency between OpenClaw and OpenCode presets

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-05-18 10:38:03 +08:00
Tiancrimson 5c79cf64a4 fix(gemini-native): resolve functionResponse.name and replay thought_signature for synthesized tool call IDs (#2814)
* fix(gemini-native): resolve functionResponse.name and thought_signature replay for synthesized tool call IDs

Two related bugs in the Gemini Native format conversion layer:

1. **functionResponse.name resolution** (422 error): When Gemini's parallel
   function calls omit the id field, cc-switch synthesizes gemini_synth_*
   IDs. These are stored in the shadow store but can be lost in long sessions,
   causing subsequent tool_result blocks to fail. Fix: pre-scan all assistant
   messages in the request body to seed the tool_name_by_id map, and add a
   last-resort fallback that scans the current content array for matching
   tool_use blocks.

2. **thought_signature replay** (400 error): The Anthropic Messages format
   strips thoughtSignature from tool_use blocks, but Gemini requires it on
   every functionCall in multi-turn tool-use exchanges. Fix: build a
   thought_signature_by_id map from shadow turns and attach thoughtSignature
   when converting tool_use back to functionCall.

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

* style: run cargo fmt on transform_gemini.rs

---------

Co-authored-by: Tiancrimson <tiancrimson@gmail.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-05-18 10:25:35 +08:00
LaoYueHanNi bbce75fcda fix(session): 修复session log模式下子Agent token统计遗漏 (#2821)
* fix(session): 修复session log模式下子Agent token统计遗漏

collect_jsonl_files() 只扫描了两层目录,遗漏了子Agent的JSONL日志文件,
导致子Agent的独立token使用数据完全未统计到session费用中。
(仅影响session log模式,proxy代理模式不受影响)

* refactor(session): optimize collect_jsonl_files logic

- Replace two independent if statements with if-else for mutually exclusive conditions
- Remove unnecessary clone() when pushing file paths
- Add clarifying comments for main session vs subagent files
- Apply cargo fmt for consistent formatting

Performance improvement: Eliminates redundant clone() operations when
processing .jsonl files, as a path cannot be both a file and a directory.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-05-18 10:00:57 +08:00
iamryan ed33990b9c fix-codex-mise-detection (#2822) 2026-05-18 09:38:08 +08:00
Zylo 8786f44c5a Fix race condition in useEffect hooks and type assertion bug (#2827)
- Add active flag pattern to 3 useEffect hooks in App.tsx to prevent
  event listener leaks when component unmounts before async setup completes
- Add guard check in useSettings.ts to prevent undefined from being
  stored in localStorage when payload.language is missing

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 09:36:44 +08:00
Jason 4f0f103a8a Add Claude Desktop user guide docs
- Add the Claude Desktop provider guide in English, Chinese, and Japanese.
- Add localized screenshots for import, provider setup, model mapping, and local routing.
- Link the guide from the v3.15.0 release notes and user manual indexes.
2026-05-16 20:18:49 +08:00
Jason c460a404dc Add Claude Desktop official preset
- Add Claude Desktop Official to the Claude Desktop preset list.
- Treat selected official presets as official mode in the form.
- Cover the official preset with a preset-order regression test.
2026-05-16 19:49:59 +08:00
Jason 6172bfd549 docs(release-notes): soften imposter warning wording in en/ja notes 2026-05-16 13:26:53 +08:00
Jason 1232b49b74 docs(release-notes): soften imposter warning wording in zh notes 2026-05-16 13:25:09 +08:00
Jason 3640a4e27d docs(release-notes): remove emoji from imposter site warning 2026-05-16 13:21:44 +08:00
Jason fed892d307 docs(release-notes): add imposter site warning to v3.15.0 notes 2026-05-16 13:19:33 +08:00
Jason 9e3f168903 chore(release): bump version to 3.15.0 2026-05-16 11:21:18 +08:00
Jason 9e6a7a0d81 - Fix proxy test helper clippy warning
- Mark `should_force_identity_encoding` as test-only.

- Keep runtime forwarding behavior unchanged.

- Verified with local CI checks and no-bundle Tauri build.
2026-05-15 23:45:26 +08:00
Jason 4a631b28c7 chore(i18n): simplify modelMappingOffHint to action-oriented copy 2026-05-15 23:33:48 +08:00
Jason ec8afd63ea refactor(presets): render presets in array order and prioritize partners
Remove the category-based grouping logic from ProviderPresetSelector,
letting the array position in each preset config file be the single
source of truth for display order. Move partner presets (PatewayAI,
火山Agentplan, BytePlus, DouBaoSeed) right after Shengsuanyun across
all 6 config files so they appear earlier in the UI.
2026-05-15 23:28:59 +08:00
Jason 9050442b65 feat(presets): add BytePlus provider preset as partner
Add BytePlus (international Volcengine) to Claude, Claude Desktop,
Hermes, OpenCode, and OpenClaw with byteplus icon, 256K context window,
and trilingual promotion text.
2026-05-15 22:45:04 +08:00
Jason d94eb6729b feat(presets): add 火山Agentplan provider preset as partner
Add Volcengine Ark Agentplan to Claude, Claude Desktop, Hermes,
OpenCode, and OpenClaw with huoshan icon and trilingual promotion.
2026-05-15 22:28:26 +08:00
Jason a0131c9a2b chore(presets): update DouBaoSeed endpoint, links, and add as partner
Switch Anthropic-format base URL from /api/coding to /api/compatible,
update website/apiKey URLs to Volcengine console with tracking params,
and promote DouBaoSeed to partner with trilingual promotion text.
2026-05-15 22:00:55 +08:00
Jason 58cd5302ae chore(presets): switch RelaxyCode icon to custom relaxcode.png
Replace the generic claude icon with a dedicated relaxcode.png icon
for the RelaxyCode provider presets.
2026-05-15 17:55:47 +08:00
Jason 3fd38b0a3d feat(presets): add RelaxyCode provider presets
Add RelaxyCode as a new third-party provider with support for:
- Claude Code preset (Anthropic native protocol)
- Codex preset (gpt-5.5 model)
- Claude Desktop preset (direct mode with passthrough routes)

RelaxyCode is an enterprise-grade AI programming platform providing
unified access to Claude Code, Codex, and Gemini CLI models.
2026-05-15 17:38:26 +08:00
Jason 18ffddbfa5 feat(presets): add RunAPI provider presets
Add RunAPI as a new partner provider with support for:
- Claude Code preset (Anthropic native protocol)
- Codex preset (gpt-5.5 model)
- Claude Desktop preset (direct mode with passthrough routes)
- OpenCode preset (@ai-sdk/anthropic)
- OpenClaw preset (anthropic-messages protocol)
- Hermes preset (anthropic_messages mode)
- Icon configuration (runapi.jpg)
- i18n support (zh/en/ja) with ¥14 free credit promotion

RunAPI is a high-performance AI model API gateway supporting 150+
mainstream models (OpenAI, Claude, Gemini, DeepSeek, Grok) with
prices as low as 10% of official rates.
2026-05-15 17:20:46 +08:00
Jason d6bbbf72f0 feat(presets): add ClaudeCN provider presets
Add ClaudeCN as a new partner provider with support for:
- Claude Code preset (Anthropic native protocol)
- Codex preset (gpt-5.5 model)
- Claude Desktop preset (direct mode with passthrough routes)
- OpenCode preset (@ai-sdk/anthropic)
- OpenClaw preset (anthropic-messages protocol)
- Hermes preset (anthropic_messages mode)
- Icon configuration (claudecn.png)
- i18n support (zh/en/ja) with enterprise service promotion

ClaudeCN is an enterprise-grade AI gateway operated by a registered
company, supporting enterprise procurement processes with corporate
payments, contracts, and compliance guarantees.
2026-05-14 23:28:07 +08:00
Jason df11df4d9c feat(presets): add ClaudeAPI provider presets
Add ClaudeAPI as a new partner provider with support for:
- Claude Code preset (using ANTHROPIC_AUTH_TOKEN field)
- Claude Desktop preset (direct mode with passthrough routes)
- Icon configuration (ClaudeApi.png)
- i18n support (zh/en/ja) with test credit promotion

ClaudeAPI provides official Anthropic API keys and AWS Bedrock
routing with support for Tool Use and 1M context.
2026-05-14 23:07:49 +08:00
Jason 4eb5543d9f refactor(presets): switch 20 Claude Desktop providers from proxy to direct mode
- Change mode from "proxy" to "direct" for 20 third-party/aggregator providers
- Simplify PipeLLM from mappedRoutes to passthroughRoutes for consistency
- Reduces unnecessary proxy layer overhead for providers that support direct API calls

Affected providers: ShengSuanYun, AIHubMix, DMXAPI, PackyAPI, PatewayAI,
Cubence, AIGoCode, RightCodes, AICodeMirror, AICoding, CrazyRouter,
SSSAICode, ModelVerse, CompShare, MicuAPI, CTOK, E-FlowCode,
VibeCodingAPI, LemonData, PipeLLM
2026-05-14 22:52:54 +08:00
Jason 08cd5ab56e feat(presets): add PatewayAI provider presets
Add PatewayAI as a new partner provider with support for:
- Claude Code preset (using ANTHROPIC_API_KEY field)
- Codex preset (gpt-5.5 model)
- Claude Desktop preset (proxy mode with passthrough routes)
- Icon configuration (pateway.jpg)
- i18n support (zh/en/ja) with $3 registration bonus promotion

PatewayAI provides reliable API routing services for Claude Code,
Codex, and Gemini models.
2026-05-14 22:36:45 +08:00
Jason b642ef0633 fix(failover): patch P1-P3 reliability gaps surfaced by team review
- Forwarder buffers non-streaming bodies and primes streaming first
  chunk before signaling success, so body timeouts and SSE first-chunk
  failures route through the circuit breaker instead of being recorded
  as success on response-header arrival
- Atomic enable-failover: switch to P1 before persisting the flag, and
  roll back auto-added queue entries when the switch is rejected
  (e.g. official providers)
- Hot-reload circuit breaker config on per-app proxy config change
  instead of waiting for a proxy restart
- FailoverToggle / FailoverQueueManager / AutoFailoverConfigPanel
  require proxy takeover for the active app; the backend command also
  rejects enabling when takeover is off
- ProviderHealthBadge consumes the backend is_healthy flag instead of
  hardcoding the 5-failure threshold

Cleanup:
- impl From<&AppProxyConfig> for CircuitBreakerConfig and use it from
  the command layer
- Collapse three identical TabsContent blocks into a single map
2026-05-14 21:35:02 +08:00
Jason 940161fb0e feat(providers): add routing support badges for Claude Code and Codex
Add visual indicators for routing capabilities on provider cards:
- Claude Code: "Needs Routing" badge for non-official providers with non-anthropic API formats
- Claude Code: "No Routing Support" badge for official providers
- Codex: "No Routing Support" badge for official providers

The badges help users understand which providers support format conversion through routing.
2026-05-14 17:51:42 +08:00
Jason 0d09555503 chore(partners): cross-link BytePlus/Volcengine entries in READMEs 2026-05-14 16:13:35 +08:00
Jason cb45c22b63 chore(presets): migrate OpenClaudeCode to MicuAPI domain
Replace all openclaudecode.cn URLs with micuapi.ai across all
provider presets (Claude, Codex, Hermes, OpenClaw, OpenCode,
Claude Desktop). This includes website URLs, API key URLs, and
base URLs.
2026-05-14 15:41:52 +08:00
Jason 8dabb9fab9 chore(presets): update CrazyRouter API endpoints to cn subdomain
Update all CrazyRouter baseURL configurations from crazyrouter.com
to cn.crazyrouter.com across all supported applications (Claude,
Codex, Gemini, Hermes, OpenClaw, OpenCode, Claude Desktop).

Website and registration URLs remain unchanged.
2026-05-14 15:40:41 +08:00
Jason 99304ffcfd chore(partners): remove DDSHub partner integration
Remove DDSHub from all provider presets (Claude, Claude Desktop, Codex, Hermes),
i18n files (zh/en/ja), README docs, and icon system. Physical assets retained for
potential future restoration.
2026-05-14 15:35:35 +08:00
Jason 543e057e20 fix(providers): disable model test for third-party Claude providers
Most third-party Claude Code providers now reject requests from
non-official clients, so the model test button would just produce
noisy failures (or worse, trigger risk controls on the provider
side). Treat third-party Claude providers the same way as official /
Copilot / Codex OAuth: pass onTest=undefined so ProviderActions
renders the test button in its existing disabled visual state.
2026-05-14 15:26:54 +08:00
Jason 73bc4eb65d feat(codex-oauth): fetch model list from ChatGPT backend on demand
- Add `get_codex_oauth_models` Tauri command reusing the managed OAuth
  access token to hit `chatgpt.com/backend-api/codex/models`; HTTP and
  multi-shape JSON parsing live in `services::codex_oauth_models` so the
  command stays thin.
- Unify the Claude form's "fetch models" button across normal / Copilot /
  Codex OAuth presets, drop the auto-load effect for Copilot in favor of
  explicit clicks, and guard against stale responses with a requestId ref.
- Add Vitest coverage for both Copilot and Codex OAuth paths asserting no
  request on mount and the correct account id on click; add Rust unit
  tests for the four model-list payload shapes.
2026-05-14 15:03:31 +08:00
Jason f93b935d5f fix(proxy): expose real provider model names in Claude Code menu under takeover
When proxy takeover is active, write per-role *_MODEL aliases for routing
and *_MODEL_NAME with the upstream provider's real model name so the
Claude Code model menu reflects the active provider instead of stale
display names from a previous switch. Preserves the [1M] capability marker
for Sonnet/Opus, and strips it from implicit display names.
2026-05-14 12:16:00 +08:00
Jason 402570ce31 fix(usage): pricing routing, SSE lifecycle, and validation hardening
* model pricing routing: extend prefix-match families (gpt-/o1-o5/
  gemini-/deepseek-/qwen-/glm-/kimi-/minimax-) with per-family dash
  thresholds so short base IDs like gpt-5 no longer mis-match
  gpt-5-mini; strip ISO and 8-digit date suffixes via UTF-8-safe
  byte matching so claude-haiku-4-5-20251001 falls back to
  claude-haiku-4-5 pricing
* SSE collector: SseUsageFinishGuard (RAII) guarantees finish() on
  early return or panic; AtomicBool fast path lets push() skip the
  Mutex once first-event time is recorded
* validation: shared validate_cost_multiplier / validate_pricing_source
  helpers across DAO and service layers; PRICING_SOURCE_RESPONSE /
  PRICING_SOURCE_REQUEST constants replace string literals; price
  fields in update_model_pricing now reject empty / non-decimal /
  negative input before INSERT
* backfill: add backfill_missing_usage_costs_for_model so a single
  price edit only scans matching rows instead of the full log table;
  startup backfill remains full-scan
* session_usage{,_codex,_gemini}: share find_model_pricing helper from
  usage_stats; metadata_modified_nanos centralizes mtime precision
* frontend: NON_NEGATIVE_DECIMAL_REGEX + isNonNegativeDecimalString
  replace three copies of the same multiplier regex; isUnpricedUsage
  surfaces zero-cost rows that have usage tokens (cached per row to
  avoid double evaluation); invalidate usageKeys.all on pricing mutate
  so backfilled rows refresh
2026-05-14 11:53:51 +08:00
Jason 206125b4e3 fix(proxy): patch P0-P3 routing/lifecycle issues across forwarder paths
* stream_check: thread Result from get_auth_headers via map_err so
  the workspace builds again
* forwarder: scope rectifier / budget-rectifier flags per-provider so
  failover can still apply rectification on the next attempt
* forwarder: categorize before record_result; route NonRetryable and
  ClientAbort through release_permit_neutral so client-side failures
  don't pollute circuit breaker or DB health
* handler_context: parse Gemini model from uri.path() and strip both
  ?query and :action verb defensively in extract_gemini_model_from_path
* forwarder + response_processor + handlers: introduce
  ActiveConnectionGuard (RAII) so active_connections decrement covers
  the full streaming body lifetime, not just response headers
* claude_desktop_config: use sort_by_key to clear the clippy gate
2026-05-14 09:23:21 +08:00
Jason 85131d37d8 refactor(proxy): extract handle_rectifier_retry_failure helper
The signature (RECT-003) and budget (RECT-012) rectifier branches each
carried ~50 lines of identical "provider error -> record + continue /
client error -> release permit + return" handling. The only piece that
varied between them was a log label ("整流" vs "budget 整流").

Move the shared logic into RequestForwarder::handle_rectifier_retry_failure
that returns Option<ForwardError> — None means "continue to the next
provider", Some(err) means "terminal failure, return to the client".
Each call site shrinks from ~50 lines to ~17, drops one level of
indentation, and the two branches now provably cannot drift apart.

forwarder.rs nets ~40 lines smaller.
2026-05-14 08:22:07 +08:00
Jason 039784af73 refactor(proxy): share auth_header_value helper across provider adapters
claude.rs and gemini.rs each defined an identical `hv` closure that wrapped
`HeaderValue::from_str` into a ProxyError::AuthError result, and codex.rs
spelled the same conversion out inline. /simplify reviewers flagged this
as drift-prone copy-paste.

Move the conversion into a single `pub fn auth_header_value` in
providers/adapter.rs and have the three adapters import it locally. Same
error wording everywhere, one place to update if HeaderValue semantics
ever change.
2026-05-14 08:21:53 +08:00
Jason 3c35972548 fix(proxy-ui): accept IPv6 listen addresses in ProxyPanel validation
The backend already understands `::` -> `::1` and wraps IPv6 literals
in brackets (services/proxy.rs), but the panel's save-time validator
only accepted localhost, 0.0.0.0, and IPv4 dotted-quads. Users who
wanted to listen on an IPv6 loopback had to bypass the UI and edit
config directly.

Add an isValidIpv6 helper that requires at least one ':' and round-trips
through `new URL('http://[<addr>]/')` so the platform's built-in IPv6
parser does the heavy lifting (covers compressed `::`, full 8-group
form, zone IDs). Update the invalidAddress copy in zh / en / ja so the
error message reflects the new accepted set.
2026-05-13 23:36:44 +08:00
Jason 5d3d9067af feat(proxy): forward client HTTP method instead of hard-coding POST
The forwarder used to call client.post(&url) / http::Method::POST in
both the reqwest and hyper paths, and the Gemini route table only
registered POST /v1beta/*. As a result anything the Gemini SDK / CLI
sent as GET (models list, models/<id> info) hit a 404 at the router
and bypassed the local proxy's stats, rectifiers, and failover.

Thread the request method end-to-end:

- ProviderAdapter forwarder API now takes the http::Method by reference
  per attempt and dispatches client.request(method, &url) for reqwest
  and method.clone() for the hyper raw path.
- All five callers in handlers.rs (handle_messages_for_app for Claude /
  Claude Desktop, handle_chat_completions, handle_responses,
  handle_responses_compact, handle_gemini) pull the method out of the
  incoming axum::extract::Request and pass it on.
- handle_gemini tolerates an empty body (GET endpoints have none) and
  the forwarder skips serializing / sending a body for GET / HEAD —
  attaching JSON to a GET makes Gemini reject the request.
- server.rs swaps the Gemini routes to any(handle_gemini) so the same
  handler handles GET / POST / PUT / DELETE, and adds /gemini/v1/*
  for the GA path version.
2026-05-13 23:36:36 +08:00
Jason f2ae9823cb fix(proxy): move client-request counters out of per-attempt loop
Three statistics-shape issues fixed together so the dashboard reflects
client requests, not provider attempts:

1. active_connections never moved off zero — the field had no caller in
   the entire crate. Wrap forward_with_retry into a thin entry point
   that saturating_add(1) on enter and saturating_sub(1) on exit; every
   inner return path is covered automatically.

2. total_requests counted attempts, not requests. A single client call
   that failed over P1 -> P2 -> success was recorded as
   total=2 / success=1 -> 50% success rate. Move the increment and the
   last_request_at refresh into the wrapper so they fire once per
   client request regardless of how many providers were tried.

3. current_provider / current_provider_id stay inside the inner loop
   because they are intentionally per-attempt ("what am I trying right
   now?") — moving them would break the live-failover indicator.

Refactor: split forward_with_retry into a public wrapper + private
forward_with_retry_inner. Every existing `return Err(...)` inside inner
remains correct because the wrapper always runs the decrement on its
return.
2026-05-13 23:28:16 +08:00
Jason b06e0fa538 fix(proxy): wire AppProxyConfig.max_retries into request forwarder
The UI has exposed "请求失败时的重试次数 (0-10, default 3)" since the
auto-failover panel was added, but the value was silently dropped —
RequestForwarder never received it and the per-provider loop walked the
whole list regardless. From the user's perspective the setting was
inert.

Thread AppProxyConfig.max_retries through create_forwarder into
RequestForwarder, derive max_attempts = max_retries + 1 (so max_retries=0
matches the UI copy "0 retries" = single attempt), and break the loop
once attempts hit the cap. The check is placed before the circuit
breaker allow-permit so an over-cap iteration does not waste a HalfOpen
probe slot.

When auto-failover is disabled we also force max_retries to 0, mirroring
how timeouts already bypass in that mode — "no failover" should mean
"one provider, one try", not "limited retries against the same list".
2026-05-13 23:25:15 +08:00
Jason 84aa87c3dd fix(proxy): map Anthropic tool_choice to OpenAI Chat nested form
The Chat-Completions transformer used to forward tool_choice verbatim,
but the two APIs disagree on shape:

  Anthropic   "any" | {"type":"tool","name":"X"}
  OpenAI Chat "required" | {"type":"function","function":{"name":"X"}}

Pass-through made the upstream return 400 for any tool-forcing client
(Claude Code, Copilot, etc.). The Responses-API transformer already had
the equivalent map_tool_choice_to_responses helper; this commit adds a
sibling map_tool_choice_to_chat with the chat-specific *nested* function
selector and five regression tests covering string / object × any /
auto / none / tool.

The two helpers are intentionally not merged: the difference between
flat and nested function selectors is exactly what the original bug
was, so keeping them as separate self-documenting functions reduces the
chance of the same regression returning.
2026-05-13 23:20:55 +08:00
Jason cb4ecd3951 fix(proxy): refine failover decisions in forwarder
Two related changes to make per-provider failover behave correctly.

1. Bucket UpstreamError by status code in categorize_proxy_error.

   The old "every UpstreamError is Retryable" rule meant a malformed
   client request (400 / 422) would be replayed against every provider
   in the queue: errors amplified N-fold, the circuit breaker accrued
   unwarranted failure counts, and quota was burned. Now
   400 / 405 / 406 / 413 / 414 / 415 / 422 / 501 are NonRetryable since
   the request itself is wrong and no provider will accept it.
   401 / 403 / 404 / 408 / 409 / 429 / 451 and all 5xx remain Retryable
   because the next provider may carry a different key, quota, region,
   or model mapping.

2. Make the rectifier-retry path participate in failover.

   Both the signature (RECT-003) and budget (RECT-012) rectifier branches
   used to "return Err(...)" after the retry failed, short-circuiting the
   per-provider loop. A provider-side failure (5xx / Timeout /
   ForwardFailed) now records the circuit breaker, accumulates into
   last_error / last_provider, and "continue"s to the next provider —
   matching the normal Retryable arm. Client-side failures still return
   immediately since a different provider cannot fix a malformed payload.
2026-05-13 23:20:45 +08:00
Jason c3d810a22b fix(proxy): tighten takeover detection and use fallback restore on disable
Two related drift bugs in the takeover state machine:

1. The "already taken over?" guard used has_backup OR live_taken_over, so
   either condition alone would short-circuit. After a user or anomalous
   flow restores Live manually the backup row still made set_takeover
   return success, leaving the UI claiming takeover while requests bypass
   the local proxy. Tighten to AND so the rebuild branch repairs the two
   "split brain" states (backup-only and placeholder-only).

2. Disabling takeover called the bare restore_live_config_for_app, which
   silently Ok()s when the backup is missing. If the backup was lost while
   Live still held proxy placeholders (PROXY_MANAGED token / local proxy
   URL), the client config was left broken with no error surfaced. Route
   the disable path through the already-existing
   restore_live_config_for_app_with_fallback (backup → SSOT → cleanup).
   The line 354 takeover-failure rollback intentionally keeps the bare
   variant since that path must preserve the backup for retry.
2026-05-13 23:12:15 +08:00
Jason 9a8f52021d fix(proxy): extract Gemini request model from URI path correctly
split('/') strips the slashes, so find(|s| s.starts_with("models/")) never
matched any segment and request_model fell through to "unknown" for every
Gemini call, poisoning usage records, per-request billing, and logs.

Match the literal "models" segment and take the next one, stripping any
:action suffix and query string. The extraction is now a pub(crate) free
function so it can be unit-tested directly; seven regression tests cover
action suffixes, dotted versions, the /gemini/ proxy prefix, query
strings, the bare list endpoint, and missing-segment paths.
2026-05-13 23:12:06 +08:00
Jason c9a6afc0b7 fix(proxy): return Result from get_auth_headers to avoid panic on bad credentials
User-pasted API keys can contain control chars or CR/LF that make
HeaderValue::from_str return Err; the previous unwrap inside every
adapter turned such input into a process-wide panic instead of a request
error. The trait now returns Result<_, ProxyError>; Claude/Codex/Gemini
impls propagate ProxyError::AuthError so the client sees a 401 with the
underlying parse error instead of a crash. Adds a regression test that
pastes a CRLF-containing key and asserts AuthError.
2026-05-13 23:12:00 +08:00
Jason 58648a9c53 chore: drop trailing blank line in sql_helpers tests
Rustfmt cleanup, no behavioral change.
2026-05-13 23:11:52 +08:00
Jason aa5e58d060 fix(usage): correct cache cost semantics and silence pricing warn storm
- Split CostCalculator into per-app cache semantics: Anthropic's
  input_tokens is already fresh input, while Codex/Gemini include
  cached tokens in their prompt count. The old shared formula
  double-subtracted cache_read for Claude, under-billing input cost.
- Backfill now reads cost_multiplier from the per-log snapshot column
  instead of re-querying providers.meta, so historical rows are no
  longer rewritten with the current multiplier.
- Move the "pricing not found" warn out of find_model_pricing_row;
  emit it only when a brand new log is written, and skip placeholder
  models (unknown / empty / null / none) entirely.
- Broaden model id normalization: strip namespace prefixes
  (anthropic./openai./global./bedrock.), bedrock-style -vN suffixes,
  reasoning effort suffixes (-low/-medium/-high/-xhigh/-minimal),
  Claude Desktop's claude-<non-anthropic> wrapper, dot-to-dash for
  Claude, and try a LIKE prefix match for Claude short route ids
  (e.g. claude-haiku-4-5 -> claude-haiku-4-5-20251001).
- Fall back to request_model when the stored model is missing, so
  early Codex session rows with model=unknown can still be priced.
2026-05-13 17:51:35 +08:00
Jason 4b57f7e113 feat(claude-code): role-based model mapping with display names and 1M flag
- Replace the four flat env inputs with a Sonnet/Opus/Haiku role table.
  Each row exposes ANTHROPIC_DEFAULT_*_MODEL plus a new display name
  field ANTHROPIC_DEFAULT_*_MODEL_NAME, and Sonnet/Opus gain a
  "Declare 1M" checkbox that toggles the [1M] suffix.
- Strip the [1M] context-capability marker before forwarding non-Copilot
  requests upstream. Copilot keeps its existing [1m]->-1m normalization.
- Claude Desktop import now consumes ANTHROPIC_DEFAULT_*_MODEL_NAME as
  label_override, closing the Claude Code -> Claude Desktop displayName
  pipeline; add_route's merge logic is shared between hashmap branches.
- Unify the [1M] marker as ONE_M_CONTEXT_MARKER across
  claude_desktop_config and proxy::model_mapper; rename the strip
  helper to strip_one_m_suffix_for_upstream.
- Collapse useModelState's seven duplicated useState initializers and
  the useEffect parse block into a single parseModelsFromConfig call.
- Add tests/hooks/useModelState.test.tsx and a Claude Desktop import
  test covering Kimi K2 -> label_override. i18n (en/ja/zh) updated.
2026-05-13 17:06:05 +08:00
Jason 84bac6dce6 refactor(claude-desktop): lock route IDs to sonnet/opus/haiku roles
Adapt to Claude Desktop 1.6259.1+ fail-all validation which only
accepts claude-(sonnet|opus|haiku)-* route IDs. Branded model names
(DeepSeek, Kimi, GLM, etc.) now live in a new labelOverride field
instead of being embedded in route IDs.

- Backend auto-repairs legacy unsafe routes to the next free
  sonnet/opus/haiku slot instead of erroring
- Frontend swaps the free-form route input for a role dropdown plus
  menu display name field
- Add CLAUDE_DESKTOP_ROLE_ROUTE_IDS as the single source of truth
  for role-to-route mapping; presets and form both consume it
- Drop the dead displayName alias on ClaudeDesktopModelRoute and the
  ineffective /v1/models display_name injection (UI ignores it)
- Update i18n (en/ja/zh) and form focus test for the new fields
2026-05-13 15:22:23 +08:00
Jason edf28b6422 feat(usage): filter-driven Hero with cache-normalized totals
- Normalize OpenAI/Gemini input_tokens semantics in SQL via the new
  fresh_input_sql helper (cache_read subtracted at query time, no data
  migration). Recovers correct cache hit rates for Codex/Gemini.
- Add get_usage_summary_by_app endpoint for per-app split (single
  UNION ALL + GROUP BY, avoids N+1).
- Replace UsageSummaryCards + AppBreakdownRail with a single
  filter-driven UsageHero card; clicking a filter button now truly
  changes the displayed numbers and the title accent color.
- Tighten KNOWN_APP_TYPES to the 3 app_types whose token data is
  reliably collected (claude/codex/gemini); hide claude-desktop,
  hermes, opencode, openclaw filter buttons and i18n keys.
- Flag cache_creation as N/A for OpenAI-style protocols (Codex,
  Gemini); show a "partial" tooltip when the All view mixes both
  protocol families.
2026-05-13 10:27:29 +08:00
Jason c12364a940 feat(claude-desktop): rework Claude Code import flow
- Derive route keys from the upstream model name (pass-through style)
  instead of fixed Claude aliases, and translate the legacy [1M] suffix
  into the supports1m field at the import boundary. Three Claude aliases
  mapped to the same upstream now collapse to a single route (e.g.
  MiniMax-M2 across SONNET/OPUS/HAIKU env produces one
  claude-MiniMax-M2 -> MiniMax-M2 row), with [1M] OR-aggregated.
- Add an import-time safety net that rebuilds claude-desktop-official
  when missing, so users who deleted it can recover via the normal
  import button without losing customizations on other providers.
- Hide API key and endpoint URL inputs in the official provider edit
  form to mirror Claude Code's behavior and prevent user confusion.
- Reword the empty-state import button label for clarity.
2026-05-12 21:31:30 +08:00
Jason 60a3628360 refactor(claude-desktop): replace [1M] suffix with supports1m field
inferenceModels entries now emit {name, supports1m: true} objects when
1M is enabled (plain strings otherwise), instead of appending a " [1M]"
suffix to model IDs. Route IDs and upstream model IDs are stored
verbatim; the suffix is rejected on input rather than silently stripped,
and proxy request mapping now requires an exact route_id match.
2026-05-12 17:40:32 +08:00
Jason ea4cdaad27 fix(ui): center Monitor badge icon in app switcher
The Monitor glyph's visual weight skews upward (screen rect dominates
while the stand is two thin lines), making it appear off-center inside
the 11px Claude Desktop badge. Add a per-badge offsetY config and
apply translateY(0.5px) to compensate.
2026-05-12 16:43:03 +08:00
Jason 44d4ea81af - 修复 Claude Desktop 模型输入框失焦
- 为动态模型行添加稳定 rowId,避免编辑模型 ID 时重挂载

- 增加模型映射和直连模型列表焦点保持回归测试
2026-05-12 11:47:45 +08:00
Jason 270f49a4a6 - 恢复 Claude Desktop 共享功能入口
- 将 Claude Desktop 的 Prompts、Skills、Sessions 映射到 Claude Code 配置

- 恢复 Claude Desktop 顶部功能按钮组

- 继续复用统一 MCP 面板入口
2026-05-12 11:36:57 +08:00
Jason 6a3c2fe0ba - 支持 Claude Desktop 使用 Copilot/Codex OAuth 供应商
- 放开本地路由托管 OAuth 供应商校验,允许动态 Token
- 新增 Claude Desktop Copilot/Codex 预设与账号选择
- 添加 OAuth proxy 回归测试
2026-05-12 11:30:11 +08:00
Jason 953b7cdcf9 refactor(claude-desktop): drop displayName from model route schema
Claude Desktop's new model menu reads model IDs directly and ignores the
display_name field, so a separate displayName slot added UI noise without
any product value. Collapse the routeId / model / displayName tuple down
to routeId / model, and let the route ID carry the user-visible name
through a non-editable claude- prefix rendered next to the input.

Drop display_name from ClaudeDesktopModelRoute, ClaudeDesktopDefaultRoute,
and ResolvedModelRoute on the Rust side plus the matching TS interfaces,
stop emitting it in /v1/models responses, derive route IDs from upstream
model IDs when picked via the model dropdown, and update zh/en/ja copy to
describe the new two-field layout.
2026-05-12 10:46:35 +08:00
Jason 417ad8149d fix(ui): hide empty toolbar capsule when Claude Desktop is active
Claude Desktop disables Skills, Prompts, Sessions, and MCP, which left
the secondary toolbar capsule next to the app switcher completely empty
but still rendered as a grey rounded pill. Wrap the capsule in an
activeApp !== "claude-desktop" guard so it disappears entirely, and
drop the two inner guards that this outer check makes redundant.
2026-05-11 23:15:57 +08:00
Jason 968c75bdbe feat(ui): use "Claude Code" label in app visibility settings
The app visibility section in Settings showed "Claude" for the first
entry, identical to "Claude Desktop" at a glance. Add a dedicated
i18n key apps.claudeCode and point the settings panel at it, while
leaving apps.claude untouched so other panels (MCP, Skills, Usage,
etc.) keep their shorter "Claude" label.
2026-05-11 23:15:30 +08:00
Jason ed41a7a7b9 feat(ui): distinguish Claude Code vs Claude Desktop in app switcher
The two Claude entries shared the same orange logo, making them hard to
tell apart at a glance. Rename the first entry to "Claude Code" and
overlay a Terminal badge on its logo; overlay a Monitor badge on the
Claude Desktop logo. Changes are scoped to AppSwitcher only; other
panels (MCP, Skills, Usage, etc.) continue to show "Claude".
2026-05-11 22:56:53 +08:00
Jason 7685ab7049 chore(release): surface ccswitch.io in release notes template
Each tagged release now leads with the canonical official website
in three languages, ensuring every Release page (which is indexed
independently by Google) becomes a dofollow backlink to ccswitch.io.
2026-05-11 15:49:36 +08:00
Jason deeeca1920 docs: add Hermes Agent to README subtitles (en/zh/ja)
Aligns README subtitles with the GitHub repo description that
now lists Hermes Agent as a managed application.
2026-05-11 15:32:23 +08:00
Jason 2fc6753e42 chore(brand): surface ccswitch.io as the sole official website
Add an "Only Official Website" header to the three READMEs, an
About panel button, and a tray menu entry — all pointing to
ccswitch.io. Consolidates brand and SEO signals on the canonical
domain across docs, GUI, and system tray.
2026-05-11 15:25:48 +08:00
Jason 4b384dfe55 perf(proxy): trim per-request hot-path work and db wait
- Guard debug body serialization with `log::log_enabled!`; previously
  serialized the filtered body to a throwaway String on every forward,
  even with debug logging off.
- Skip SSE parse + UTF-8 buffer loop when no usage collector and debug
  is off; the per-chunk `serde_json::from_str::<Value>` ran even in
  pure passthrough mode.
- Add cheap per-app SSE event pre-filter (string `contains`) so usage
  collectors only parse events that could contain usage (e.g. Claude
  `message_start` / `message_delta`).
- Skip non-streaming response body JSON parse when usage logging is
  disabled.
- Move `ProviderRouter::record_result` off the success response path
  via `tokio::spawn` for non-HalfOpen state; that call internally does
  `get_proxy_config_for_app` + `update_provider_health`, two SQLite
  ops that previously blocked TTFB.

Also: dedupe `usage_logging_enabled` (was duplicated in handlers.rs)
and merge `SseUsageCollector::{new, new_filtered}` into a single
constructor that takes `Option<StreamUsageEventFilter>`.
2026-05-11 15:25:48 +08:00
Jason 00a789e7a3 fix(proxy): improve cache hit rate for Codex/Responses requests
prompt_cache_key was falling back to provider.id when the client did not
supply a session, which collapsed every conversation onto a single key
and defeated upstream prefix caching. Only emit the key when a real
client-provided session/thread identity is available; otherwise let the
upstream use its default matching behaviour.

Additional fixes that affect cache stability:
- Canonicalise (sort) JSON keys in outgoing request bodies and in
  tool_call arguments / tool_result content so semantically identical
  requests produce identical byte sequences for upstream prefix caches.
- Exempt JSON Schema property maps (properties, patternProperties,
  definitions, \$defs) from the underscore-prefix filter so user-defined
  schema keys like _id and _meta survive.
- Add a [CacheTrace] debug log with stable hashes for instructions,
  tools, input and include to help diagnose cache misses.
- Thread session_id into the usage logger for request correlation.
2026-05-11 15:25:48 +08:00
Kwensiu aec055a1d1 fix(proxy): drop empty pages from Read tool input (#2472)
* fix(proxy): drop empty pages from Read tool input

* fix(proxy): preserve Read args across duplicate tool starts
2026-05-11 11:32:52 +08:00
Jason e45470cd91 - fix(ci): restore frontend formatting and Linux clippy
- Format Claude Desktop provider presets with Prettier

- Gate platform-specific Claude Desktop path helpers behind cfg
2026-05-10 22:31:47 +08:00
Jason 50a873ca24 chore(icons): add ClaudeCN and RunAPI raster icons
Resized to 512x512 to match the existing extracted-icons size convention
(hermes.png / lemondata.png). Source uploads were oversized (7.3 MB
8635x8635 for ClaudeCN; 800x800 for RunAPI) and would have bloated the
bundle if imported as-is.

Note: not yet wired into index.ts / metadata.ts; register there when
they need to surface in the app UI.
2026-05-10 22:12:57 +08:00
Jason 2ac5e053b4 docs: add RunAPI sponsor entry to README (en/zh/ja)
Insert sponsor row in all three README locales linking to runapi.co.
EN/JA copy adapted from the Chinese original. Banner center-cropped to
the project standard 1920x798 aspect ratio (preserves the logo and
slogan, trims the decorative top/bottom padding) and saved as JPEG to
keep file size reasonable (1.3 MB PNG -> 206 KB JPEG).
2026-05-10 22:06:41 +08:00
Jason a7dd7117e7 docs: add ClaudeCN sponsor entry to README (en/zh/ja)
Insert sponsor row in all three README locales linking to claudecn.top.
EN/JA copy adapted from the Chinese original. Banner normalized to the
project standard sponsor image spec (1920x798 RGB on white background)
and recompressed; alt text unified to "ClaudeCN" across all three files.
2026-05-10 21:49:08 +08:00
Jason b016a17783 docs: use Volcengine logo for Chinese README sponsor entry
Replace byteplus.png with localized huoshan.png (Volcengine/火山引擎)
in README_ZH.md so Chinese readers see the regional brand. EN/JA
README continue to use the BytePlus logo and link to byteplus.com.

The new logo is normalized to the project's standard sponsor image
spec: 1920x798 RGB on a white background.
2026-05-10 16:59:42 +08:00
Jason 10c874afdc docs: add BytePlus sponsor entry to README (en/zh/ja)
Insert sponsor row in all three README locales. EN/JA point to
byteplus.com/modelark; ZH points to volcengine.com/agentplan
(Volcengine being the China-region counterpart). Logo normalized
to the project-standard 1920x798 RGB white background and
recompressed (432K -> 84K).
2026-05-09 23:03:08 +08:00
Jason 5bbd83f7ca feat(claude-desktop): add 44 provider presets translated from Claude Code
- New src/config/claudeDesktopProviderPresets.ts with the Claude Code
  preset list re-shaped into Desktop's three-segment route format
  (routeId / upstreamModel / displayName); excludes OAuth providers,
  AWS Bedrock (no SigV4 support) and KAT-Coder (placeholder URL).
- Non-Claude upstream presets show upstream model id as displayName
  (e.g. deepseek-v4-pro) so the Desktop model list reflects what is
  actually being requested. OpenRouter/TheRouter/PIPELLM keep
  Sonnet/Opus/Haiku since their upstream really is Anthropic Claude.
- Wire ProviderPresetSelector into ClaudeDesktopProviderForm so
  selecting a preset back-fills baseUrl, mode, routes and apiFormat.
- Drop the hard-coded ANTHROPIC_AUTH_TOKEN write in handleSubmit so
  ANTHROPIC_API_KEY presets (LemonData / AiHubMix / Gemini Native)
  save under the correct env key, and clear the opposite key on switch.
- Hide the universal-providers tab for claude-desktop because its
  meta-driven routing has no analogue in the universal flat-env shape.
- Add apps."claude-desktop" i18n key (zh/en/ja) so the dialog tab
  label resolves instead of showing the literal key.
2026-05-09 17:19:09 +08:00
Jason 292c117509 chore(backend): satisfy cargo fmt and clippy --all-targets
- Apply rustfmt diffs in claude_desktop_config.rs
- Allow needless_return on current_platform_paths (cfg-mirrored arms)
- Allow too_many_arguments on RequestForwarder::forward
- Replace `let mut + reassign` with struct literals in tests
  (settings, backup, provider, response_processor)
- Use Path::new instead of PathBuf::from to fix cmp_owned in misc tests
- Replace 3.14 with 3.5 in config test to avoid approx_constant lint
2026-05-09 09:04:01 +08:00
Jason f526d01578 docs: update Micu API links to micuapi.ai 2026-05-08 23:27:41 +08:00
Jason 3cd74400dc docs: update Right Code sponsor description 2026-05-08 23:17:49 +08:00
Jason 950b7dd35f docs: update sponsor logos and listings
- Add ClaudeAPI as new sponsor (all 3 languages)
- Remove ChefShop sponsor entry (all 3 languages)
- Convert shengsuanyun logo from SVG to PNG
- Standardize partner logos to 1920x798 canvas
- Fix ClaudeAPI alt text typo and spacing
- Sync sponsor order across zh/en/ja READMEs
2026-05-08 23:05:13 +08:00
Jason 309f7609a5 refactor(claude-desktop): show badge only for providers requiring routing
Direct-mode providers no longer display a badge since routing is
optional for them. Proxy-mode providers now show "需要路由" / "Requires
routing" to clarify that local routing must be active.
2026-05-08 22:34:46 +08:00
Jason 1fa019026e fix(claude-desktop): match proxy model route without [1M] suffix
Claude Desktop strips the [1M] suffix from model IDs when sending
requests, causing route lookup to fail with "model route is not
configured". Fall back to base-name comparison when exact match misses.
2026-05-08 22:34:46 +08:00
Jason 21b9eb0430 refactor(claude-desktop): simplify model mapping UX
- Remove "Import from Claude" button from main provider list (keep in empty state)
- Remove "Desktop model" column from proxy mode mapping table; route names are now auto-generated
- Rename "upstream model" label to "requested model" and equalize column widths
- Rewrite model mapping hint and toggle description for end-user clarity
- Update validation messages and remove dead i18n keys (routeModelLabel)
2026-05-08 22:34:46 +08:00
Jason 2deee1097b refactor(claude-desktop): align provider form UI with Claude Code
- Rename field labels: "Gateway Base URL" → "API Endpoint", "Bearer Token" → "API Key"
- Change layout from 2-column grid to vertical sections matching Claude Code
- Reuse shared EndpointField component with format-aware amber hint box
- Replace native <datalist> with vendor-grouped ModelDropdown (OpenCode pattern)
- Move Fetch/Add buttons to section headers with compact sm styling
- Extract ModelDropdown to shared module, deduplicate from OpenCodeFormFields
- Extract renderActionButtons helper to eliminate proxy/direct button duplication
- Remove dead i18n keys (gatewayBaseUrl, bearerToken) from all 3 locales
2026-05-08 22:34:46 +08:00
Jason 34698723e3 fix(claude-desktop): remove proxy-stopped status alert
The route toggle in the top-right corner already communicates proxy
state; the extra warning banner was redundant and inconsistent with
other managed apps.
2026-05-08 22:34:46 +08:00
Jason 83f4e1d0ad refactor(claude-desktop): trim duplication in proxy and switch flows
- services/proxy.rs: collapse 10 repeated `OpenCode | OpenClaw | Hermes |
  ClaudeDesktop` match arms into `_` fallthroughs.
- claude_desktop_config.rs: extract a `with_rollback` closure shared by
  apply_provider_to_paths and restore_official_at_paths.
- useProviderActions.ts: replace the triple-nested ternary picking the
  switch-success toast message with a flat let/if/else block.

Net -36 lines. No behavior change; cargo test and pnpm typecheck pass.
2026-05-08 22:34:46 +08:00
Jason 8b3ad9caf9 feat(claude-desktop): add 3P provider switching with proxy gateway
Adds a new ClaudeDesktop AppType that writes Claude Desktop's third-party
inference profile under configLibrary/, sharing _meta.json with other
launchers (Ollama-compatible) so cc-switch can coexist with them.

Two switch modes:
- direct: provider already exposes claude-* / anthropic/claude-* model
  ids on Anthropic Messages, Claude Desktop connects to it directly.
- proxy: cc-switch's local proxy acts as the inference gateway,
  presenting only claude-* route names to Claude Desktop and mapping
  them to real upstream models. Required after Anthropic restricted
  Claude Desktop to claude-family ids.

Backend:
- New module claude_desktop_config with snapshot/rollback, official seed
  bypass, /claude-desktop/v1/{models,messages} routes, and a single
  source of truth for default proxy routes.
- Gateway token persisted in SQLite, validated on every proxied request.
- get_claude_desktop_status surfaces drift signals (stale models,
  missing routes, proxy stopped, base URL mismatch, missing token).

Frontend:
- Slim ClaudeDesktopProviderForm independent from ProviderForm,
  controlled by a top-level appId guard.
- ProviderList banner consumes the status query (5s polling) and
  renders actionable diagnostics.
- ClaudeDesktopRouteToggle in the header to start/stop the local
  gateway without touching takeover state.
- Three-locale i18n synchronised.
2026-05-08 22:34:46 +08:00
Jason e15bfbfe7a fix(proxy): reuse pooled HTTPS connections for non-Anthropic backends
The hyper raw-write path preserves original header casing but rebuilds
TCP+TLS on every request — there is no connection pool — which was the
root cause of slow reverse-proxy throughput.

Only Anthropic-native requests actually need exact header-case
preservation. Route OpenAI/Copilot/Codex/Gemini/codex_oauth requests
through the pooled reqwest client (pool_max_idle_per_host=10,
tcp_keepalive=60s) instead, so warm connections get reused.

Streaming requests get a precise first-byte timeout via
tokio::time::timeout around reqwest's send() (which resolves on
response headers), with the body phase handed off to response_processor.
The streaming-detection helper now also covers Gemini SSE endpoints
and Accept: text/event-stream, not just body.stream.
2026-05-08 22:34:46 +08:00
Dhruv_S b05be92aa1 Fix Codex startup live import duplication (#2590)
* Fix Codex startup live import duplication

* Fix: Prevent duplicate Codex default provider on restart & add startup import tests
2026-05-08 08:41:50 +08:00
bling-yshs f5fbcd0493 feat: return reasoning_content with tool_calls for DeepSeek models (#2543)
* feat: return reasoning_content with tool_calls for DeepSeek models

* fix: correct reasoning_content handling for DeepSeek tool_calls

* test: cover DeepSeek reasoning content round trip

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-05-07 23:03:07 +08:00
Butui Hu 1d44b1ba41 feat(universal-provider): add duplicate action for universal providers (#2416)
Signed-off-by: Hu Butui <hot123tea123@gmail.com>
2026-05-02 21:36:07 +08:00
Jason ddc7b4567e fix(ci): pin Claude review checkout to PR head sha
Prevents `git fetch origin pull/<N>/head:main` failures on fork PRs
whose head branch is also named `main` — using a SHA puts the runner
in detached HEAD so the main ref is free for the action's internal fetch.
2026-05-02 20:33:54 +08:00
Jason 8e59a634fd refactor(theme): drop unused MouseEvent param from setTheme
Now that the view transition animation is gone, setTheme no longer
needs click coordinates. Reduce the API surface to (theme: Theme) =>
void and simplify the call sites in mode-toggle and ThemeSettings.
2026-05-02 20:33:54 +08:00
Jason bc1f9341f4 refactor(theme): remove circular reveal animation for theme switching
The View Transitions API used here crashes WebKitGTK with SIGSEGV on
Linux. Rather than gating document.startViewTransition per platform
(see PR #2502), drop the animation entirely — it's a low-value visual
flourish on a low-frequency action that doesn't justify a permanent
platform branch.

Removes the ::view-transition-* CSS block and the coordinate plumbing
in setTheme. The optional event parameter is kept on the API surface
to keep call sites compiling; they'll be cleaned up in a follow-up
commit.
2026-05-02 20:33:54 +08:00
Probe 72ab8a5cfd fix(proxy): include zero usage in final message delta (#2485) 2026-05-02 17:27:52 +08:00
Yuxuan Sun b61dad4b43 fix(frontend): prevent selecting theme from causing segfault on Linux (#2502) 2026-05-02 17:27:11 +08:00
Jason faa6021c6f fix(ci): drop --max-turns 5 from Claude review args
Cap was too tight — review tasks need 8-15 turns to read files, analyze,
and post results. The first run after the previous prompt change failed
with error_max_turns at turn 6. The disallowedTools list already keeps
the agent in read-only mode, so an explicit turn cap is redundant.
2026-05-02 10:28:47 +08:00
Jason 79d6ede7ae chore(ci): tune Claude review prompt to reduce nitpick noise
Previous prompt produced 5-10 findings per PR including dead-code/style
nits mixed with real bugs. New prompt adds severity tiering, an 80
confidence threshold, an explicit anti-pattern list, a 5-nit cap, and
permits zero-comment LGTM as a valid outcome. Calibration follows
Anthropic Code Review docs and the claude-plugins-official prompt.
2026-05-02 10:26:36 +08:00
dependabot[bot] c2714774b9 chore(deps): bump actions/stale from 9 to 10 (#2520)
Bumps [actions/stale](https://github.com/actions/stale) from 9 to 10.
- [Release notes](https://github.com/actions/stale/releases)
- [Changelog](https://github.com/actions/stale/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/stale/compare/v9...v10)

---
updated-dependencies:
- dependency-name: actions/stale
  dependency-version: '10'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-02 09:44:36 +08:00
dependabot[bot] 026b5dbcb5 chore(deps): bump softprops/action-gh-release from 2 to 3 (#2519)
Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 2 to 3.
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v2...v3)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-version: '3'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-02 09:44:32 +08:00
dependabot[bot] 59f7105cbc chore(deps): bump pnpm/action-setup from 5 to 6 (#2518)
Bumps [pnpm/action-setup](https://github.com/pnpm/action-setup) from 5 to 6.
- [Release notes](https://github.com/pnpm/action-setup/releases)
- [Commits](https://github.com/pnpm/action-setup/compare/v5...v6)

---
updated-dependencies:
- dependency-name: pnpm/action-setup
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-02 09:44:28 +08:00
dependabot[bot] 586450a372 chore(deps): bump actions/checkout from 4 to 6 (#2517)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-02 09:43:44 +08:00
Jason 7621b645d1 chore(ci): upgrade Claude review model to Opus 4.7 2026-05-01 23:47:51 +08:00
Jason d75e4e7eb3 fix(ci): add id-token:write permission required by claude-code-action v1 2026-05-01 23:19:22 +08:00
Jason adc7ffefa4 chore(ci): add Claude Code Action for review-only @claude mentions
- Restrict to repo collaborators via author_association check
- Use OAuth token for subscription billing
- Disable Edit/Write tools and set contents:read permission to enforce review-only
2026-05-01 23:07:46 +08:00
Jason bdc4c1e8b8 fix(proxy): derive Claude auth strategy from ANTHROPIC env var name
Anthropic SDK assigns distinct semantics to the two env vars:

- ANTHROPIC_API_KEY    -> x-api-key
- ANTHROPIC_AUTH_TOKEN -> Authorization: Bearer

The Claude adapter previously collapsed both into AuthStrategy::Anthropic
and then emitted Authorization: Bearer regardless, breaking strict
Anthropic-protocol endpoints (Anthropic official, Cloudflare AI Gateway,
OpenCode Go, DashScope) and silently overriding the user's intended auth
scheme.

- claude::extract_auth: infer strategy from env var name
  (ANTHROPIC_AUTH_TOKEN -> ClaudeAuth, ANTHROPIC_API_KEY -> Anthropic),
  matching the precedence already used by extract_key.
- claude::get_auth_headers: split the Anthropic arm so it emits
  x-api-key, while ClaudeAuth and Bearer continue to use Bearer.
- stream_check: reuse ClaudeAdapter::get_auth_headers as the single
  source of truth, replacing the prior "always Bearer + maybe x-api-key"
  double injection that produced auth conflicts and false-negative
  health checks.
- Cover each strategy -> header mapping and env-var precedence with
  new unit tests in claude.rs.

Refs #2368, #2380
2026-05-01 23:07:46 +08:00
Jason 35bce24633 fix(proxy): strip leading billing header from system content (#2350)
Claude Code injects a dynamic `x-anthropic-billing-header` line at the
start of `system` content. Its rotating `cch=` token was forwarded into
OpenAI Responses `instructions` and Chat system messages, which broke
upstream prefix prompt cache reuse — a stable ~95k-token prefix was
getting re-charged on every request.

Strip only the leading occurrence in both anthropic_to_openai and
anthropic_to_responses; later occurrences are preserved so user-authored
prompt text containing the same string is not lost.
2026-05-01 23:07:46 +08:00
Jason 518d945eb8 chore(usage): drop Hermes Agent tracking integration
Hermes aggregates all in-process API calls into a single sessions row
with the `model` field locked to the initial model, so the usage
dashboard cannot cleanly surface per-call billing context. Two rounds
of UI workarounds (raw mapping, then `<model> @ <host>` display) did
not resolve the user-facing confusion, so the whole tracking
integration is dropped for now.

Removes session_usage_hermes service (and its 17 tests), sync wiring
in commands/usage.rs and lib.rs, _hermes_session/hermes_session
entries in usage_stats SQL (provider_name_coalesce CASE and
effective_usage_log_filter IN clause), frontend Tab/banner/dropdown/
icon entries, and four i18n keys per locale.

Hermes app integration outside usage tracking (proxy routing,
session manager, config) is preserved. Pre-existing hermes rows in
proxy_request_logs are left as orphans — filtered out by the
updated SQL and never surfaced in the UI.
2026-05-01 23:07:46 +08:00
BillSaul 7b667f7a44 feat: persist Tauri window state (#2377)
Add the window-state plugin and explicitly save size and position across app exit, restart, and lightweight-mode transitions.
2026-05-01 17:51:25 +08:00
xpfo 295dd9a944 fix(proxy): preserve Vertex AI full URLs (#2415) 2026-05-01 17:46:10 +08:00
makoMakoGo 064b339bab fix(claude): persist max effort via env (#2493) 2026-05-01 17:41:32 +08:00
jimmy db66348ff8 feat(providers): add Baidu Qianfan Coding Plan for Claude Code (#2322)
* feat(providers): add baidu qianfan coding plan presets

* refactor(providers): align qianfan presets with existing format

* chore(providers): narrow qianfan coding plan scope
2026-05-01 17:35:18 +08:00
Coconut-Fish 7f0c7b11e5 feat(tray): add tooltip to tray icon for better user experience (#2417)
Co-authored-by: Copilot <copilot@github.com>
2026-04-30 22:41:54 +08:00
涂瑜 fafc122d82 fix(coding-plan): correct zhipu weekly tier name by reset time (#2420)
Zhipu's `data.limits[]` returns 1 entry for legacy plans (subscribed
before 2026-02-12) and 2 entries for current plans. Previously every
TOKENS_LIMIT entry was hardcoded as `five_hour`, so the weekly bucket
was rendered with the 5-hour i18n label.

Sort TOKENS_LIMIT entries by nextResetTime ascending and assign
`five_hour` to index 0, `weekly_limit` to index 1. Legacy plans
naturally degrade to a single five_hour tier.

Also harden the parser: case-insensitive type match (defends against
upstream casing changes), reuse TIER_FIVE_HOUR/TIER_WEEKLY_LIMIT
constants, and add 8 unit tests covering both plan shapes plus
defensive edge cases.
2026-04-30 22:38:34 +08:00
magucas 693c36a12a fix(dashscope): enhance usage parsing robustness to prevent VSCode cr… (#2425)
* fix(dashscope): enhance usage parsing robustness to prevent VSCode crashes

Enhanced build_anthropic_usage_from_responses() to handle null, missing, empty,
and partial usage fields gracefully. This prevents VSCode Extension crashes with
"Cannot read properties of null (reading 'output_tokens')" when connecting to
DashScope (Alibaba Cloud Bailian) models.

Changes:
- Added defensive null checks and empty object detection
- Implemented OpenAI field name fallbacks (prompt_tokens/completion_tokens)
- Added comprehensive logging for malformed usage scenarios
- Fixed streaming SSE event handlers with null-safe usage access
- Preserved cache token fields even when input/output tokens are missing

This ensures the proxy never crashes on malformed Responses API usage objects,
returning valid Anthropic-compatible usage structures (input_tokens/output_tokens)
in all cases.

* fix(proxy): tighten Responses API usage fix per review

- Drop redundant fallback in streaming.rs Chat Completions path; the
  existing if-let-Some guard already prevents usage:null, so the extra
  layer was dead code and caused a fmt-breaking indentation issue.
- Demote partial-usage warn to debug. Streaming chunks legitimately
  arrive with partial token counts and the warn-level log was noisy.
- Rewrite CHANGELOG entry: reference #2422, broaden scope from
  DashScope-only to all api_format=openai_responses users (Codex OAuth
  is the strongest signal; DashScope compatible-mode/v1/responses is
  the original report).
- cargo fmt to clear 12 formatting differences vs main.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-30 22:37:54 +08:00
ayxwi 7965862e66 Make import existing side-effect free (#2429)
Co-authored-by: Xvvln <3369759202@qq.com>
2026-04-30 21:59:47 +08:00
eclipsehx 1c69269405 fix(codex): skip environment_context injection when extracting session title (#2439)
Co-authored-by: xiaohan1 <xiaohan1@chinaums.com>
2026-04-30 12:45:42 +08:00
Cao Xin 15497b0e41 fix(session): hide Codex subagent sessions (#2445) 2026-04-30 12:22:21 +08:00
Hulk 7c8720bd3f fix(terminal): prevent iTerm fallback on cold launch (#2448) 2026-04-30 12:03:46 +08:00
Chris Chen 8084bfafa8 fix(config): sort JSON keys alphabetically for deterministic output (#2469)
* fix(config): sort JSON keys alphabetically for deterministic output

Ensures settings.json keys are written in sorted order, preventing
non-deterministic git diffs when switching configs.

* test(config): add unit tests for sort_json_keys and fix formatting

Cover top-level sort, nested recursion, array order preservation,
primitive pass-through, empty collections, and the core determinism
guarantee (different insertion orders must yield identical output).

Also fix line-length in write_json_file flagged by `cargo fmt --check`.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-30 11:53:32 +08:00
tison 151af0ffa3 Fix log message for session usage codex (#2473)
* Fix log message for session usage codex

* Fix comments in session_usage_codex.rs
2026-04-30 11:07:06 +08:00
tison 608ee35ecd feat: support launch warp and execute session (#2466)
* feat: support launch warp and execute session

Signed-off-by: tison <wander4096@gmail.com>

* other wires

Signed-off-by: tison <wander4096@gmail.com>

* for launch with provider

Signed-off-by: tison <wander4096@gmail.com>

* fixup indirection

Signed-off-by: tison <wander4096@gmail.com>

* clippy

Signed-off-by: tison <wander4096@gmail.com>

* address comments

Signed-off-by: tison <wander4096@gmail.com>

---------

Signed-off-by: tison <wander4096@gmail.com>
2026-04-30 10:33:50 +08:00
SaladDay a1e6c3b65d 修复 Codex 切换供应商后历史记录变化 (#2349)
* Keep Codex history stable across provider switches

* Restore template Codex provider id when backfilling live config

Backfill writes the current Codex live config back to the previous
provider's stored template after a switch. Because the live file now
carries a normalized stable model_provider id, the previous provider's
template would lose its own provider-specific id (and any matching
[profiles.*] references) on every subsequent switch.

Reverse the normalization at backfill time by rewriting model_provider,
the active model_providers section, and matching profile references back
to the template's original id.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-30 09:54:25 +08:00
Jason eb304232b3 docs(readme): add PatewayAI sponsor across zh/en/ja
Also clean up a dangling <tr> tag in README_JA.md.
2026-04-29 22:57:23 +08:00
Jason f061b777b7 feat(usage): add Hermes Agent tracking + fix zero-cost bug + perf
Hermes:
- Parse ~/.hermes/state.db sessions (incl. profiles/*/state.db) into
  proxy_request_logs with data_source='hermes_session', WAL-aware
  incremental sync, Hermes-reported cost preferred over model_pricing
  fallback

Zero-cost bug (dashboard showed \$0 totals):
- GPT-5.5 family default pricing (~83% of affected rows used GPT-5.5)
- find_model_pricing_row: ASCII-lowercase normalization so
  "OpenAI/GPT-5.5@HIGH" matches seeded "gpt-5.5"
- Startup cost backfill in async task: scan rows where total_cost <= 0
  but tokens > 0, recompute via model_pricing in a single transaction

Performance:
- Add (app_type, created_at DESC) covering index for dashboard range
  queries
- Add expression index on COALESCE(data_source, 'proxy') so dedup EXISTS
  subqueries use index lookup instead of full scan; drop superseded
  idx_request_logs_dedup_lookup

Refactor:
- row_to_request_log_detail helper (3-way de-dup; fixes cost_multiplier
  \"1\" vs \"1.0\" drift between callers)
- Promote get_sync_state/update_sync_state to shared session_usage
  module (4 copies -> 1)
- run_step helper in lib.rs replaces 9 if-let-Err blocks
- maybe_backfill_log_costs returns bool to skip duplicate total_cost
  parsing in caller
2026-04-29 22:41:46 +08:00
Jason 2ee7cb4101 fix(usage): prevent double-counting between proxy and session-log sources
Proxy writes and session-log sync wrote to proxy_request_logs with
mismatched request_ids: only Claude on a native Anthropic backend used the
shared `session:{message_id}` key. Codex/Gemini and Claude-through-OpenAI
providers always produced distinct ids, so primary-key dedup never fired
and every real request was recorded twice.

Adds a 7-dim fingerprint dedup (app_type, 4 token counts, 2xx status,
model with case-insensitive match, ±10min window) wired into three layers:

- Write path: should_skip_session_insert() blocks duplicate session rows
  before INSERT, unifying the previously-divergent Claude/Codex/Gemini
  paths through a single DedupKey-based helper.
- Read path: effective_usage_log_filter() excludes already-covered session
  rows from every aggregation query.
- Rollup path: same filter applied so usage_daily_rollups never absorbs
  duplicates.

Also adds a covering index (idx_request_logs_dedup_lookup) so the EXISTS
subquery stays index-only, and a transform.rs regression test that pins
openai_to_anthropic id preservation - the missing piece that lets
Claude+OpenAI-compatible providers reuse the session: id scheme.
2026-04-29 22:41:46 +08:00
Jason bcf8434c1f chore(kimi): update Kimi For Coding website URL to /code/docs/
Sync the preset's websiteUrl from the legacy /coding/docs/ path to
the current /code/docs/ path across all four app presets (claude,
hermes, openclaw, opencode).
2026-04-29 22:41:46 +08:00
Jason d2556be5b9 fix(balance): show USD on SiliconFlow international site (was CNY)
The query_siliconflow function received an is_cn flag that only switched
the request domain (.cn vs .com) but the response builder hardcoded
unit="CNY" for both sites. International users at api.siliconflow.com
saw their USD balance labelled as CNY. Now unit and plan_name follow
is_cn, so the EN site shows USD and "SiliconFlow (EN)".
2026-04-29 22:41:46 +08:00
Jason 5b6339d78c chore(codex): hide 1M context window toggle in provider edit form
Codex models no longer accept model_context_window=1000000, so the
toggle and its paired auto-compact-limit input are commented out in
the provider edit form. State hooks, helper imports, and i18n keys
are preserved so the UI can be restored in one batch if upstream
support returns. The TOML editor remains visible, allowing manual
edits if needed.
2026-04-29 22:41:46 +08:00
codeasier 21e2d68d76 fix(proxy): preserve scoped reasoning_content for tool calls (#2367)
- Preserve `reasoning_content` for Kimi/Moonshot OpenAI Chat compatibility paths.
- Keep generic OpenAI-compatible requests free of non-standard `reasoning_content` fields.
- Continue skipping thinking-only assistant messages.
- Add regressions for generic skip and Kimi/Moonshot preservation behavior.
2026-04-28 17:08:59 +08:00
codeasier 6441bc5c01 fix(proxy): dedupe streaming message_delta (#2366)
- Deduplicate repeated upstream `finish_reason` chunks so only one Anthropic `message_delta` is emitted.
- Preserve late `choices: []` usage-only chunks before sending the final `message_delta`.
- Keep stream error paths from emitting successful terminal events.
- Add regressions for duplicate finish reasons, usage-only chunks, missing `[DONE]`, and truncated streams.
2026-04-28 17:08:43 +08:00
tison 4536b95ac9 refactor: prefer default shell in commands::try_get_version (#2286)
Signed-off-by: tison <wander4096@gmail.com>
2026-04-25 17:00:36 +08:00
allen_xln 85f0be9e1d feat(provider-form): soften validation with "save anyway" prompt (#2307)
* feat(provider-form): soften business-rule validation with "save anyway" prompt

Refactor handleSubmit so empty-field / missing-item validations (provider
name, endpoint, API key, opencode model, template variables, provider key
required) no longer hard-reject with toast.error. Instead they are collected
into an issues list and presented via a ConfirmDialog; the user can cancel
or choose "Save anyway" to proceed.

Integrity constraints stay as hard rejections:
- providerKey regex / duplicate (would corrupt other providers)
- Copilot / Codex OAuth not authenticated (no token, cannot establish)
- omo Other Fields JSON not an object / parse failure

This aligns the frontend with the backend's existing "relaxed save / strict
switch" split (see gemini_config.rs: validate_gemini_settings vs
validate_gemini_settings_strict) and unblocks legitimate configs such as
AWS Bedrock, Vertex AI, and custom Gemini base URLs that the UI previously
refused to save.

Refs: #2196, #1204

* fix(provider-form): address review feedback on soft-validation

P1: move empty providerKey back to hard rejection for OpenCode / OpenClaw /
Hermes. Since providerKey is the primary identity for these apps and the
mutations layer throws "Provider key is required" when absent, letting users
click "save anyway" would surface a generic error toast instead of a
precise, actionable one. Treat empty providerKey as an integrity constraint
alongside regex / duplicate checks.

P2: give the soft-confirm submit path its own submitting state. The
confirm-dialog path bypassed react-hook-form's isSubmitting lifecycle, so
slow or failing saves left the outer submit button responsive and could
spawn unhandled rejections. Now the confirm handler awaits performSubmit
inside try/catch/finally, uses an isConfirmSubmitting flag to gate both
confirm and cancel clicks, and folds the flag into the outer disabled
state and onSubmittingChange callback.

Refs: #2307 review comments

* chore(clippy): use push for single char '…' in truncate_body

Clippy 1.95 added single_char_add_str which flagged the push_str("…")
in truncate_body. Rebased onto latest upstream/main and applied the
suggested fix so the Backend Checks clippy job passes.

Unrelated to this PR's core changes; bundled in so the PR is mergeable
without waiting for a separate upstream fix.

---------

Co-authored-by: Allen <allen@AllenMacBook-M4-Pro.local>
2026-04-25 09:28:28 +08:00
Jason 08e2b29b8a feat(compshare): add Coding Plan preset across claude/codex/hermes/openclaw
Introduce a dedicated "Compshare Coding Plan" variant pointing to
https://cp.compshare.cn (with /v1 for OpenAI-compatible apps). Reuses
the existing ucloud icon and promotion copy, while adding a new
providerForm.presets.ucloudCoding key in zh/en/ja.
2026-04-24 23:57:04 +08:00
Jason 948fa87ae3 docs(readme): update Crazyrouter $2 credit claim flow across zh/en/ja
The $2 sign-up credit is no longer granted automatically — users now
need to contact Crazyrouter's customer support after registering to
claim it. Sync all three README variants and drop the outdated
"instantly / 即時進呈" wording. Also fix a stray double space in the
English sentence.
2026-04-24 23:38:55 +08:00
Jason 4833d24d83 docs(readme): refresh Compshare sponsor blurb across zh/en/ja
Update the Compshare entry to describe the new offering: per-use
domestic-model Coding Plan packages with officially-relayed overseas
models, replacing the outdated "60-80% off" discount wording. Keep all
three README variants in sync.
2026-04-24 23:34:46 +08:00
Jason 221af57a49 fix(readme): flatten LionCC logo onto white background
The original lioncc.png had a transparent background, which made the
black "LionCC" wordmark blend into GitHub's dark-mode page and become
hard to read. Composite the artwork onto solid white so the logo stays
legible in every theme without changing any markup.
2026-04-24 23:30:25 +08:00
Jason b1f9ce4653 feat(deepseek): switch presets to V4 (flash/pro) and add pricing
DeepSeek released V4 flash/pro; legacy IDs deepseek-chat / deepseek-reasoner
now alias to deepseek-v4-flash and will be deprecated.

- Update claude/hermes/opencode/openclaw presets to v4-pro / v4-flash,
  context 128K -> 1M; Claude Anthropic-compat endpoint routes OPUS/SONNET
  to v4-pro and HAIKU to v4-flash, plus an explicit modelsUrl override.
- Seed deepseek-v4-flash ($0.14/$0.28 per 1M) and deepseek-v4-pro
  ($1.68/$3.36 per 1M) into model_pricing; older v3.x / chat / reasoner
  rows kept for historical usage stats (INSERT OR IGNORE).
- Refresh user-manual (zh/en/ja) pricing table and note that legacy model
  IDs are billed at v4-flash rates.
2026-04-24 23:24:37 +08:00
Jason 67dbfc0a8c fix(model-fetch): support /models for Anthropic-compat subpath providers
Providers like DeepSeek, Kimi, Zhipu GLM and MiniMax expose the
Anthropic-compatible API on a subpath (e.g. /anthropic) while the
OpenAI-style /models endpoint lives at the API root. The previous
heuristic blindly appended /v1/models to the Base URL, so every such
provider returned 404 and the UI mislabeled it as "provider does not
support fetching models".

Backend now generates a candidate list and tries them in order:
preset override -> baseURL /v1/models -> stripped-subpath /v1/models ->
stripped-subpath /models. Non-404/405 responses (auth, network) stop
immediately so we never retry against hostile status codes. Known
compat suffixes are kept in a length-descending constant so the
longest match wins; response bodies are truncated to 512 chars to
avoid HTML 404 pages bloating the error string.

Preset type gains an optional modelsUrl (DeepSeek points at
https://api.deepseek.com/models). Frontend threads the override
through fetchModelsForConfig when the current Base URL still matches
the preset default. A new fetchModelsEndpointNotFound i18n key
replaces the misleading "not supported" toast for exhausted-candidate
and 404/405 cases (zh/en/ja).
2026-04-24 23:20:10 +08:00
Jason fcd83ee30d fix(copilot): resolve Claude model IDs against live /models list
Copilot upstream returns model_not_supported when the client sends
dash-form Claude IDs (claude-sonnet-4-6, claude-sonnet-4-6[1m]) while
/models only accepts dot form (claude-sonnet-4.6, -1m suffix).

- Add copilot_model_map: syntax normalize (dash->dot, [1m]->-1m) plus
  live /models exact match and family-version fallback, reusing the
  existing 5 min auth cache. Returns None when the whole family is
  absent so upstream surfaces an explicit error instead of silently
  switching families.
- Wire into forwarder Copilot hook; runs before anthropic_to_openai
  conversion.
- Default Opus slot in the Copilot preset maps to Sonnet 4.6: Pro
  dropped all Opus on 2026-04-20 and Pro+ bills Opus 4.7 at 7.5x.
  Users who want real Opus can switch manually in the UI.

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

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

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

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

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

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

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

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

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

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

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

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

Closes #2178.

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

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

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

Address P2 findings from automated review on #2184:

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

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

* refactor: consolidate codex provider helpers and fix test semantics

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

* style: apply cargo fmt

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

---------

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

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

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

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

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

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

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

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

---------

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

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

Fixes #2222

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

* style(App): 调整底部内边距以改善布局
2026-04-23 08:56:57 +08:00
tison e7ff2ee47d fix: gemini cli resume session can have project_dir (#2240)
Signed-off-by: tison <wander4096@gmail.com>
2026-04-23 08:55:11 +08:00
xpfo 7ddf7ffd66 fix(proxy): handle Codex OAuth responses as streaming (#2235) 2026-04-23 08:54:31 +08:00
tison 1b3c53d235 fix: always show name on hover (#2237)
Signed-off-by: tison <wander4096@gmail.com>
2026-04-22 23:19:52 +08:00
Jason c7ba3cf51d fix(pricing): correct Kimi K2.6 seed prices to match official rates
Moonshot's official USD pricing for kimi-k2.6 is $0.95 input /
$4.00 output / $0.16 cache-hit per 1M tokens (~58-60% higher than
K2.5). The previous commit copied K2.5's $0.60/$2.50/$0.10, which
would have under-billed K2.6 traffic in the usage dashboard.

No migration needed since this version is unreleased; INSERT OR
IGNORE will write the correct values on first launch.
2026-04-22 14:32:03 +08:00
Jason 85295cf23f chore(release): bump version to 3.14.0 2026-04-22 12:29:27 +08:00
Jason 1f25411524 feat(presets): upgrade Kimi K2.5 to K2.6 in direct Moonshot configs
Bump model id and display name from K2.5 to K2.6 in Hermes, OpenClaw,
OpenCode, and Claude (direct api.moonshot.cn) presets. Pricing,
context window, and base URL are unchanged.

Add kimi-k2.6 row to model_pricing seed; no migration needed since
seed_model_pricing uses INSERT OR IGNORE and runs on every startup
via ensure_model_pricing_seeded. Old kimi-k2.5 row is kept to
preserve historical usage stats.

Nvidia aggregator forwards (moonshotai/kimi-k2.5) intentionally keep
the K2.5 SKU until Nvidia's catalog confirms K2.6.
2026-04-22 12:17:19 +08:00
Jason 6495da03b7 docs(release-notes): add v3.14.0 release notes (en/zh/ja)
Cover Hermes Agent onboarding (6th managed app), Claude Opus 4.7
rollout, Gemini Native API proxy, "Local Routing" rename,
application-level window controls, Copilot premium consumption
deep optimization, session list virtualization, Usage date range
picker, Stream Check error classification, pricing v8->v9 reseed,
and related breaking changes.

18 external PR contributions credited in all three locales.
2026-04-22 11:51:32 +08:00
Jason 95b21ff27e docs(changelog): extend v3.14.0 entries with late additions
Fold six late commits into the v3.14.0 section (Added / Changed / Fixed)
and refresh the stats header against the actual v3.13.0..HEAD diff:
100 commits | 219 files | +20,548 / -3,569.

Late additions covered: Hermes dashboard toolbar launch, LemonData
preset across all six apps, DDSHub Codex endpoint, Hermes toolbar
icon + MCP reorder, Hermes health-check schema fix, Usage modal
support for Hermes/OpenClaw.
2026-04-22 11:51:25 +08:00
Jason ae1fd2b662 feat(presets): add DDSHub Codex preset
DDSHub now exposes a Codex-compatible endpoint at the same host as
its Claude service. Base URL omits the /v1 suffix since the gateway
auto-routes OpenAI SDK paths.
2026-04-22 10:42:24 +08:00
Jason f4a9021461 feat(presets): add LemonData provider across all six apps
Register LemonData (third-party partner) preset for Claude, Codex,
Gemini, OpenCode, OpenClaw, and Hermes, plus icon assets and i18n
partner promotion copy (zh/en/ja). Claude preset uses
ANTHROPIC_API_KEY auth; OpenAI-compatible apps target gpt-5.4.
2026-04-22 10:39:17 +08:00
Jason 2274da0b8e style(hermes): use dashboard icon and move MCP to toolbar end
Swap ExternalLink for LayoutDashboard on the Hermes Web UI button —
clicking it may launch `hermes dashboard` rather than just open a URL,
so a panel-style glyph reads truer than a generic external-link icon.
Also reorder the toolbar so MCP sits in the final slot, matching the
claude/codex/gemini/opencode layout.
2026-04-21 23:05:52 +08:00
Jason 7ac822d241 fix(hermes): stop health check from borrowing OpenClaw schema
Hermes providers were routed through check_additive_app_stream, the
OpenClaw dispatcher, which reads camelCase fields (baseUrl/apiKey/api)
and emits "OpenClaw is missing ..." errors. Hermes stores snake_case
fields (base_url/api_key/api_mode) with different protocol tags, so
users saw "OpenClaw provider is missing baseUrl" even after filling in
every Hermes field correctly.

Introduce check_hermes_stream with Hermes-specific extractors. Route
api_mode (chat_completions / anthropic_messages / codex_responses) to
the matching check_claude_stream api_format, and return bedrock_converse
as unsupported. Resolve api_mode before extracting URL/API key so users
who picked bedrock_converse see the real cause first rather than a
misleading "missing base_url" message.
2026-04-21 23:00:37 +08:00
Jason 4dd11ab427 fix(usage): support Hermes and OpenClaw in usage query modal
Extend getProviderCredentials to read flat settingsConfig fields for
Hermes (snake_case base_url / api_key) and OpenClaw (camelCase baseUrl
/ apiKey), so the "official balance" template auto-selects for matching
providers like SiliconFlow.

Also refactor the BALANCE and TOKEN_PLAN test paths in handleTest to
reuse the precomputed providerCredentials instead of re-reading
env.ANTHROPIC_* directly, which previously caused empty key errors for
non-Claude apps even when the key was configured.
2026-04-21 22:40:53 +08:00
Jason 8e9452b7ec feat(hermes): launch dashboard from toolbar when Web UI is offline
When the Hermes Web UI probe fails, the toolbar entry now opens an info
confirm dialog offering to run `hermes dashboard` in the user's preferred
terminal. Accepting spawns it via a temp bash/batch script; `hermes
dashboard` itself opens the browser once ready, so we do not poll.
The Memory panel and Health banner keep the existing toast behavior.

Also corrects the stale `hermes web` hint in the offline toast (the real
command is `hermes dashboard`) and reorders Linux terminal detection to
try `which` before stat'ing /usr/bin, /bin, /usr/local/bin.
2026-04-21 21:11:15 +08:00
Jason 38709c94db docs(changelog): add v3.14.0 release notes
Summarize the 94 commits since v3.13.0 (216 files, +19,923 / -3,554)
into Keep-a-Changelog entries: Hermes Agent as the 6th managed app,
Claude Opus 4.7 rollout, Gemini Native API proxy, Copilot GHES,
session list virtualization, usage date range picker, and the
"Local Proxy Takeover" -> "Local Routing" rename.

Breaking changes collected in a dedicated section: explicit Hermes
api_mode, ANTHROPIC_REASONING_MODEL removal, per-provider proxy
removal, schema bumps (v8->v9 pricing reseed, v9->v10 Hermes columns),
and XCodeAPI preset removal.
2026-04-21 17:32:53 +08:00
Jason db92f2b3b0 style(providers): apply prettier to common-config hooks
Reformat three hooks brought in from upstream #2191 so that
format:check passes in CI.
2026-04-21 12:05:48 +08:00
Jason eb1cd17ab2 fix(header): stop auto-compact from latching after maximize
useAutoCompact cached normalWidthRef = el.scrollWidth on every
non-compact resize, but per DOM spec scrollWidth === clientWidth
when content fits. Maximizing the window (content no longer
overflows) therefore wrote the container width into
normalWidthRef, making it impossible to re-enter compact when
the window was restored to its original size.

Move the assignment inside the overflow branch so the cache is
only written at the actual compact threshold, where scrollWidth
reflects the real content width.
2026-04-21 11:57:07 +08:00
Jason 29a28d2a74 style(header): unify toolbar icon button width across apps
Normalize all icon-only ghost buttons in the header toolbar to
32x32 (w-8 px-2). Previously Hermes/OpenClaw used default sm
padding (~40px) while Claude's Skills/Sessions used w-8 px-2,
so switching apps caused a width jump and put useAutoCompact's
cached normalWidthRef out of sync across apps.
2026-04-21 11:57:07 +08:00
Jason 1227e29d8b feat(skills): enable Hermes in unified Skills management
Wire hermes through SkillApps struct, DAO SQL, command parser, and
SKILLS_APP_IDS. Add a Skills entry to the Hermes toolbar. Simplify
skill_sync test fixtures to use SkillApps::default().
2026-04-21 11:57:07 +08:00
Jason 0be75668cc feat(hermes): align provider schema with Hermes Agent 0.10.0
Hermes 0.10.0 tightened custom_providers validation (commit 2cdae233):
invalid base_urls are rejected, unknown fields produce warnings, and
new fields (rate_limit_delay, bedrock_converse, key_env) landed.

- Add bedrock_converse to the api_mode selector (and i18n labels)
- Expose rate_limit_delay in a provider-level advanced panel
- Validate base_url client-side (URL shape, template-token friendly)
- Drop per-model max_tokens — not in _VALID_CUSTOM_PROVIDER_FIELDS
- Round-trip test asserts set_provider preserves rate_limit_delay /
  key_env / any unknown forward-compat field
2026-04-21 11:57:07 +08:00
Jason 111ddf8d73 style: apply prettier and rustfmt
No behavior changes. Brings three files back in line with the project
formatters (CI runs `pnpm format:check` and `cargo fmt --check`).
2026-04-21 11:57:07 +08:00
Jason 08727528aa test: sync stale fixtures and isolate openclaw env tests
Three unrelated test failures surfaced after rebase:

- McpFormModal expected the apps boolean set without `hermes`; Hermes MCP
  support is now wired, so the fixture must include `hermes: false`.
- therouter Gemini preset was bumped to `gemini-3.1-pro` in a later
  commit; update the assertions to match current config.
- openclaw_config tests mutate process-level `CC_SWITCH_TEST_HOME` and
  `HOME` inside a module-local Mutex, but hermes_config does the same
  under its own separate Mutex. Running both modules in parallel let the
  env races corrupt hermes_config's `with_test_home`. Tag the four
  env-mutating openclaw tests with `#[serial]` so they serialize across
  modules via serial_test's process-wide default key.
2026-04-21 11:57:07 +08:00
Jason c8d91298c7 fix(providers): drop legacy ANTHROPIC_REASONING_MODEL from Claude quick-set
The model-mapping quick-set button referenced an undefined `reasoningModel`
prop and wrote `ANTHROPIC_REASONING_MODEL`, which the backend explicitly
marks as deprecated legacy (see services/provider/mod.rs and
services/proxy.rs). Remove all three references so typecheck passes and
the button matches the provider model schema.
2026-04-21 11:57:07 +08:00
Jason 21a1518f9f refactor(hermes): drop "Auto" api_mode and require explicit protocol
Hermes' built-in api_mode detection only matches a handful of official
endpoints (api.openai.com, api.anthropic.com, api.x.ai, AWS Bedrock);
third-party / proxy endpoints silently fall back to chat_completions,
which causes opaque 401/404s on Anthropic-protocol or Codex-Responses
providers. The "Auto" option was misleading for the common third-party
case.

- Drop the "Auto" option from the API Mode dropdown; remove the
  HermesApiModeChoice sentinel type so writes always emit api_mode.
- Default new providers and legacy entries lacking api_mode to
  chat_completions (only persisted on user save).
- Deeplink imports now write api_mode: chat_completions explicitly
  instead of relying on URL heuristics; test renamed accordingly.
- Rename the "Codex Responses (Copilot / OpenCode)" label to
  "OpenAI Responses" to match OpenAI's /v1/responses naming.
2026-04-21 11:57:07 +08:00
Jason a9461ad52f docs(readme): update SiliconFlow signup bonus to ¥16
Sync the bonus credit amount across en/zh/ja README files to reflect
the current SiliconFlow sponsor offer.
2026-04-21 11:57:07 +08:00
Jason f57edfd697 refactor(hermes): share provider-source marker constants and write guard
After /simplify review of the P1-3 second wave, two small cleanups:

- Lift the `_cc_source` / `providers_dict` magic strings out of
  ProviderCard into a shared helper (`isHermesReadOnlyProvider`) and
  named constants in hermesProviderPresets.ts. Front-end and back-end
  now document the same marker contract in two mirrored places
  instead of drifting strings.

- Replace the duplicate `is_dict_only_provider` + `format!` branches
  at the top of `set_provider` / `remove_provider` with a single
  `ensure_provider_writable(config, name, verb)` guard. Future error
  copy tweaks only have to happen once.

No behaviour change; all 52 hermes_config tests stay green.
2026-04-21 11:57:07 +08:00
Jason abb305a82f feat(hermes): render providers: dict overlays as read-only cards
ProviderCard now detects Hermes provider entries sourced from the
v12+ `providers:` dict via the `_cc_source` marker that the backend
injects, and renders a "Hermes Managed" badge beside the title.
ProviderActions receives an `isReadOnly` prop that disables the Edit
and Delete buttons (with a tooltip pointing the user at Hermes Web
UI) while keeping Switch and Duplicate enabled — switching only
touches `model.*`, and duplicate lets users fork the overlay into
their own `custom_providers:` list.

Three-locale i18n keys `provider.managedByHermes` /
`provider.managedByHermesHint` added.
2026-04-21 11:57:07 +08:00
Jason 3f4739365e feat(hermes): surface providers: dict entries read-only
Hermes v12+ migrated some provider entries from the `custom_providers:`
list into a `providers:` dict (keyed by id). CC Switch previously
ignored that source entirely, leaving users blind to providers they had
configured via Hermes' own Web UI; the only feedback was a generic
migration warning in the health banner.

`get_providers()` now unions both sources, matching upstream
`get_compatible_custom_providers` dedup order (list wins on name
collision). Entries coming from the dict carry a `_cc_source =
"providers_dict"` marker plus the original `provider_key`, which the
UI layer will use to render them read-only. `set_provider` and
`remove_provider` now refuse to touch dict-only entries, steering the
user to Hermes Web UI. `sanitize_hermes_provider_keys` strips the UI
markers on write so they never reach YAML.

The `schema_migrated_v12` health warning copy reframes the situation:
entries are shown read-only in CC Switch rather than invisible.
2026-04-21 11:57:07 +08:00
Jason e10a300c80 fix(hermes): prevent YAML pollution and drop of OAuth mcp auth
DeepLink Hermes import was emitting camelCase (baseUrl / apiKey /
apiMode) that the Hermes runtime does not recognise, poisoning
`custom_providers:` entries on activation. The MCP sync path was
also stripping `auth: oauth` on round-trip, silently downgrading
OAuth-type servers to unauthenticated calls.

The Hermes deeplink branch now emits snake_case via a dedicated
builder; `sanitize_hermes_provider_keys` runs on both `set_provider`
and `get_providers` so legacy DB records heal on next access.
`HERMES_EXTRA_FIELDS` preserves `auth`. The `api_mode` dropdown gains
`codex_responses` (Copilot / OpenCode), and the schema-migrated
warning copy no longer hard-codes "v12" (upstream `_config_version`
is now 19).
2026-04-21 11:57:07 +08:00
Jason 185ac2be9b feat(hermes): memory enable switch + clearer migration warning copy
Replaces the greyed-out "Memory is disabled" banner with a real Switch
at the top of each memory tab. Users can now toggle Hermes' memory/user
blobs without leaving CC Switch; the underlying write goes through the
merge-aware `set_memory_enabled`, so budgets and external-provider
settings survive toggle operations. The new `useToggleHermesMemoryEnabled`
mutation invalidates the limits query so the Switch state and the
amber disabled-hint update in lockstep.

Reworks the `schema_migrated_v12` health banner copy to match the
simplified "CC Switch only manages custom_providers" posture — it now
tells users to reconcile migrated dict entries via Hermes Web UI,
instead of the earlier (and now inaccurate) "CC Switch reads both".
2026-04-21 11:57:07 +08:00
Jason b8a3534cb5 feat(settings): add Hermes config dir override with data-driven dispatch
Adds a dedicated Hermes row to the directory-override settings so users
can point CC Switch at alternate Hermes config locations (e.g. a second
profile directory for work/personal split). `get_config_dir` on the
Rust side already supports hermes; this just wires up the frontend row.

Wiring it through `useDirectorySettings` revealed a scaling problem:
every supported app required five parallel ternary chains across
`computeDefaultConfigDir`, `updateDirectory`, `browseDirectory`,
`resetDirectory`, and `updateDirectoryState`. Replaces those with two
lookup tables (`APP_DIRECTORY_META`, `DIRECTORY_KEY_TO_SETTINGS_FIELD`)
so adding the next app is two entries, not fifteen edit sites.

Drive-by cleanup from the same touch:
* `resetAllDirectories` takes a `ResolvedAppDirectoryOverrides` object
  instead of five positional optional strings.
* `setResolvedDirs` returns the same reference when the sanitized
  value is unchanged, so no-op edits don't cascade renders.

Also lands all i18n updates for this series (`hermesConfigDir` and
placeholder, Memory section's enable/disable/toggleFailed copy, and
the reworded `schemaMigratedV12` warning) in zh/en/ja together.
2026-04-21 11:57:07 +08:00
Jason 31fb998575 refactor(hermes): simplify schema handling + preserve unknown provider fields
Drops the v11→v12 providers-dict compat layer: CC Switch now only
reads/writes `custom_providers:`, leaving migrated `providers:` dict
entries to Hermes Web UI for reconciliation (Hermes' runtime already
merges both shapes via `get_compatible_custom_providers`). The
`schema_migrated_v12` health warning now points users there when a
dict-migrated config is detected.

Adds forward-compat merge to `set_provider`: when updating an existing
entry, on-disk fields the UI payload didn't submit (e.g. Hermes-only
`request_timeout_seconds`, `key_env`) are carried over. Without this,
editing one field via CC Switch would silently strip the rest.

Adds `set_memory_enabled` + `set_hermes_memory_enabled` Tauri command
for the upcoming memory-switch UI. Writes go through a merge-aware
section replacement so character budgets and external-provider fields
survive toggle operations.

Removes four dict-only helpers (`normalize_providers_dict_entry_for_read`,
`rename_alias_key`, `json_obj_non_empty_str`,
`resolve_provider_name_from_yaml_entry`) and the multi-section write
helper. Simplifies `get_providers` / `remove_provider` / health scan
back to list-only. Replaces nine obsolete dict-related tests with
`set_provider_preserves_unknown_fields_on_update` and
`set_memory_enabled_preserves_other_fields`.
2026-04-21 11:57:07 +08:00
Jason acc6d795e4 feat(hermes): replace Prompts entry with Memory panel
Hermes has no slash-prompt concept (templates live as Skills), so the
Prompts tab for the Hermes app was always empty. Swap the toolbar Book
button for a Brain button that opens a new Memory panel editing
~/.hermes/memories/{MEMORY,USER}.md — Hermes' first-class memory store
which its Web UI exposes only as on/off toggles, never as an editor.

The panel shows each file in its own tab with a character-budget bar
read from config.yaml's nested memory.* section (memory_char_limit /
user_char_limit, default 2200 / 1375). Edits are written atomically;
Hermes picks them up on the next session start per MemoryStore.

Also extract useDarkMode to src/hooks/useDarkMode.ts — the codebase
already repeats the same MutationObserver pattern in 12+ places; this
PR introduces the shared hook and uses it once, leaving the migration
of the other copies to a follow-up.
2026-04-21 11:57:07 +08:00
Jason 088b47b08a refactor(hermes): delegate deep config to Hermes Web UI
Slim the Hermes surface in CC Switch to match its core positioning —
cross-client provider switching and shared MCP/prompts/skills — and
delegate deep configuration (model, agent, env, skills, cron, logs)
to the Hermes Web UI at http://127.0.0.1:9119.

- Drop AgentPanel/EnvPanel/ModelPanel and their mutation commands,
  hooks, types, and i18n keys across zh/en/ja.
- Add open_hermes_web_ui Tauri command that probes /api/status and
  launches the URL in the system browser. Hermes injects its own
  session token into the returned HTML, so CC Switch doesn't need
  to touch auth.
- Surface the launcher from the Hermes toolbar and the health banner
  via a shared useOpenHermesWebUI() hook; the offline error code is
  defined once per side and referenced across the contract.
- Keep read-only access to model.provider so ProviderList can still
  highlight the active supplier; apply_switch_defaults continues to
  write the top-level model section when switching providers.

Net diff: +152 / -1253.
2026-04-21 11:57:06 +08:00
Jason 041f74db18 fix(presets): refresh stale context windows for DeepSeek and Claude 1M
- DeepSeek V3.2 / R1 (Hermes, OpenClaw): 64K → 128K context
- DeepSeek R1 max output: 8K → 64K (includes CoT tokens)
- Claude Opus 4.7 / Sonnet 4.6 via OpenRouter: 200K → 1M context
2026-04-21 11:57:06 +08:00
Jason ce5c3e5c6a fix(presets): refresh stale model IDs and backfill Hermes model lists
- Bump NewAPI universal preset to Claude 4.7 / Sonnet 4.6 / Haiku 4.5 and
  Gemini 3.1; fix opusModel mistakenly pointing to Sonnet
- Bump Gemini Native (Claude preset) to gemini-3.1-pro / gemini-3-flash
- Bump TheRouter Gemini preset to gemini-3.1-pro
- Backfill models[] + suggestedDefaults for 15 Hermes anthropic_messages
  presets:
    * Bailian For Coding: qwen3-coder-plus / qwen3-max
    * Kimi For Coding: kimi-for-coding
    * 13 third-party Claude proxies: claude-opus-4-7 / sonnet-4-6 /
      haiku-4-5-20251001
- Add Claude Haiku 4.5 entry to Hermes OpenRouter model list
2026-04-21 11:57:06 +08:00
Jason 3255b17185 feat(hermes): switch eligible presets to chat_completions + GPT-5.4
Migrate 18 Hermes provider presets from anthropic_messages to
chat_completions to sidestep known upstream Hermes bugs (model-name
dot-mangling in normalize_model_name, api_mode drop after v11->v12
migration, and auxiliary_client OpenAI hardcode).

Native providers now target each vendor's official OpenAI-compatible
endpoint with correct model IDs: Kimi (kimi-k2.5-preview on /v1),
Bailian (compatible-mode/v1 with Qwen3 defaults), Xiaomi MiMo, Longcat
(/openai/v1), Zhipu GLM (/api/paas/v4), ModelScope, MiniMax, SiliconFlow,
and Novita (/v3/openai).

Aggregators (Shengsuanyun, AiHubMix, DMXAPI, Compshare, TheRouter)
default to GPT-5.4 on chat_completions, mirroring the Codex preset
lineup. TheRouter omits gpt-5.4-pro since that variant is Responses-only
and Hermes implements only chat_completions. OpenRouter's existing
openai/gpt-5 entry is bumped to openai/gpt-5.4.

Claude-only proxies are left on anthropic_messages; their Codex
counterparts use wire_api=responses, so there is no evidence their
chat_completions endpoints serve OpenAI models.
2026-04-21 11:57:06 +08:00
Jason b4e29be8a0 chore(hermes): prune unused official presets and fix Nous endpoint
Remove the Anthropic, OpenAI, and Google AI presets from the Hermes
preset list. They were placeholder samples introduced when the Hermes
module first landed and do not match the actual user paths in
CC Switch (Claude / Codex go through OAuth, Gemini Native is its own
adapter), and the upstream endpoints are not reachable for most of
the target users anyway.

Fix the Nous Research preset: its base_url was a fabricated domain
(inference.nous.hermes.dev) that has never resolved. Point it at the
real Nous Portal endpoint (inference-api.nousresearch.com/v1) and
add apiKeyUrl so users can jump straight to portal.nousresearch.com
to provision a key.

Drop the now-orphan providerForm.presets.{anthropic,openai,googleai}
i18n keys from zh / en / ja since no preset references them anymore.
2026-04-21 11:57:06 +08:00
Jason 8d6353699c feat(presets): sync Claude provider presets to Hermes
Import 38 Claude presets into Hermes by mapping env-style
ANTHROPIC_BASE_URL/AUTH_TOKEN to flat base_url/api_key, deriving
api_mode from apiFormat (anthropic_messages or chat_completions),
deduping ANTHROPIC_*_MODEL into models[], and pointing
suggestedDefaults at ANTHROPIC_MODEL. Skip OAuth-only presets
(Codex, Copilot), Bedrock SigV4, Gemini Native, and the three
already shipped on the Hermes side (OpenRouter, Anthropic,
DeepSeek). Place Shengsuanyun at the head of the Hermes array so
the partner shows first in the preset panel.

In the Claude preset list, restore Shengsuanyun back ahead of
Gemini Native. The Gemini Native preset (#1918) was inserted
between Claude Official and Shengsuanyun, which made the
third_party category register first in the reduce-based grouping
and pushed the aggregator block (and Shengsuanyun) behind it.

Backfill the missing providerForm.presets translations across zh,
en, and ja (openrouter, anthropic, openai, googleai, deepseek,
together; plus shengsuanyun for en and ja) so existing Hermes
preset names no longer render literal i18n keys.
2026-04-21 11:57:06 +08:00
Jason 828ec2ce07 fix(hermes): show active provider and wire add/enable/remove actions
Switching a Hermes provider previously only fired a toast because the frontend treated Hermes as non-additive (unlike backend AppType::is_additive_mode, which lists OpenCode | OpenClaw | Hermes) and relied on the unused is_current DB flag for highlighting. Align the UI model with the backend:

- Include Hermes in ProviderActions' isAdditiveMode so the main button switches between "Add" and "Remove".
- Drive the "current" highlight from model.provider (via useHermesModelConfig) instead of the DB is_current field; model.provider is Hermes's real SSOT for the active provider.
- Reuse OpenClaw's set-as-default button slot to expose an "Enable" action on Hermes that calls switchProvider, so providers already in config can be activated without re-adding. switch_normal + apply_switch_defaults already atomically update custom_providers and model.provider, so no backend change is needed.
- Invalidate liveProviderIds + modelConfig + health in parallel after add/update/delete/switch via a new invalidateHermesProviderCaches helper, replacing four copies of three sequential awaits.
2026-04-21 11:57:06 +08:00
Jason 5056978d80 fix(hermes): persist providers under custom_providers so api_mode/model survive
Writing to the v12+ `providers:` dict broke every anthropic_messages
provider. Hermes `runtime_provider.py::_get_named_custom_provider` has a
bug in its `providers:` branch: the returned entry drops `api_mode`,
`transport`, `models`, and singular `model:`, and
`_resolve_named_custom_runtime` then falls back to `chat_completions` —
so an Anthropic-format endpoint receives OpenAI-format requests and
returns 404.

Keep using the legacy `custom_providers:` list; its normalization path
(`_normalize_custom_provider_entry`) preserves every field. In addition,
write a singular `model:` alongside the plural `models:` dict so the
Hermes runtime and `/model` picker see the default model id.

Also keep the `apply_switch_defaults` fix from the prior attempt:
`model.provider` is always updated, and `model.default` is only
overwritten when the new provider declares at least one model — so
switching to an incomplete provider no longer silently no-ops.
2026-04-21 11:57:06 +08:00
Jason 497a543c1b feat(hermes): add API mode dropdown and per-provider model editor in form
The Hermes provider form previously only exposed Base URL and API Key,
forcing users to drop into the Model panel to hand-edit model IDs after
adding a provider. Following OpenClaw's shape, the form now carries:

- An API Mode selector (auto-detect / chat_completions / anthropic_messages).
  "auto" is a UI-only sentinel — selecting it deletes api_mode from the
  config so the YAML doesn't leak a redundant field.
- A model list editor where the first row is badged as the default and
  each row has a collapsible Advanced panel for context_length and
  max_tokens. Adding/removing rows uses a UUID-keyed ref so typing in
  one input doesn't drop focus when another row is added.
- A Fetch Models button that pulls /v1/models from the configured
  endpoint and exposes the catalog in a per-row dropdown, identical to
  OpenClaw's flow. The vendor grouping is memoized so keystrokes don't
  trigger a reduce+sort per model row — Radix DropdownMenuContent does
  not lazy-mount, so the inner JSX evaluates on every render regardless
  of whether the menu is open.

Three-locale i18n keys are added together (zh/en/ja).
2026-04-21 11:57:06 +08:00
Jason f935bac633 feat(hermes): bind per-provider models to top-level model: on switch
Hermes custom_providers entries now carry an ordered models array
(id / context_length / max_tokens) plus suggestedDefaults. The backend
serializes the array to the YAML dict shape Hermes expects on write and
inverts it on read, preserving insertion order via the preserve_order
feature on serde_json.

When a user switches providers, switch_normal calls apply_switch_defaults
so the top-level model.default / model.provider follow the selected
provider's first model. Previously switching a Hermes provider only
shuffled custom_providers[] and left Hermes pointing at whatever
model.provider was set before.

Seven existing Hermes presets now ship with a curated models list so
switching lands on a working default without a detour through the
Model panel.
2026-04-21 11:57:06 +08:00
Jason 63aa310576 feat(copilot): strip thinking blocks before forwarding to save premium quota
Copilot routes through OpenAI-compatible endpoints that reject Anthropic's
thinking and redacted_thinking blocks. Previously the request would fail
upstream, burning one premium interaction, and only then trigger
thinking_rectifier to retry. This adds a proactive strip_thinking_blocks
pass in the Copilot optimization pipeline (step 3.5, after tool_result
merging). Signature fields and top-level thinking are left alone — those
are the reactive rectifier's job on the error path.

Also fixes a default-value inconsistency where CopilotOptimizerConfig's
Default impl used "gpt-4o-mini" while the serde default function returned
"gpt-5-mini" (aligned to gpt-5-mini, matching the reference implementation).

Aligned with yuegongzi/copilot-api's /v1/messages handler behavior.
2026-04-21 11:57:06 +08:00
Jason 615c430dd3 docs(readme): trim SSSAiCode sponsor blurb and sync across locales
Drop the ¥0.5/$ pricing claim and monthly/paygo line from the SSSAiCode
entry in all three READMEs, keeping only the fast-invoicing mention.
Also collapse a duplicate blank line after the LemonData row in the JA
README to match the ZH version.
2026-04-21 11:57:06 +08:00
Jason 5d3cd7eb85 fix(icons): replace placeholder Hermes icon with Nous brand artwork
The previous Hermes icon was an inline purple "H" SVG unrelated to the
real Hermes Agent brand. Replace it with the official Nous Research
avatar sourced from hermes-agent/landingpage/icon-512.png, routed
through iconUrls as a Vite URL import. The PNG is post-processed to
strip the 4px black rectangle border (cropped inward by 6px and pasted
back onto a 512x512 transparent canvas). Also switch defaultColor to
black to match the monochrome artwork when the asset falls back to an
initial glyph.
2026-04-21 11:57:06 +08:00
Jason 1684cb3233 feat(presets): migrate all aggregator and Bedrock presets to Claude Opus 4.7
- OpenClaw: replace opus-4-6 with opus-4-7 across 17 aggregator presets
  (id, name, primary, modelCatalog); AWS Bedrock entry rewritten to new
  SKU anthropic.claude-opus-4-7 (drops -v1 and dated suffix per official
  4.7 model card) and pricing corrected to $5/$25/$0.50/$6.25 during the
  SKU swap, aligning with schema.rs source of truth
- OpenCode: same replacement for 13 aggregators plus
  OPENCODE_PRESET_MODEL_VARIANTS entries for @ai-sdk/amazon-bedrock and
  @ai-sdk/anthropic, plus AWS Bedrock provider models map
- OpenRouter / TheRouter / GitHub Copilot in claudeProviderPresets use
  dot-style id; update to anthropic/claude-opus-4.7 (missed by 509d2250)
- omo: switch agent/category recommended to opus-4-7; replace key in
  OMO_BACKGROUND_TASK_PLACEHOLDER priority map
- hermes_config.rs: update doc comments and test fixtures to opus-4-7;
  Hermes ModelPanel placeholder and i18n defaultHint examples follow
- i18n unspecifiedHigh category description bumped to 'Claude Opus 4.7
  max variant' to match omo recommended
- Test fixtures updated: therouter preset assertion and opencode Bedrock
  variant lookup now check for opus-4-7
- Sonnet 4.6 / Haiku 4.5 untouched - no official 4.7 release for them
2026-04-21 11:57:06 +08:00
Jason 83c3c3b494 feat(pricing): add Claude Opus 4.7 with adaptive thinking and Bedrock SKU
- Seed claude-opus-4-7 pricing (same tier as 4.6: $5 / $25 / $0.50 /
  $6.25 per million tokens). Relies on incremental INSERT OR IGNORE
  seeding; no SCHEMA_VERSION bump needed.
- Whitelist opus-4-7 in thinking optimizer so it uses adaptive
  thinking + max effort + 1M context beta, matching 4.6 behavior.
- Bump default OPUS model in PIPELLM and AWS Bedrock (AKSK / API Key)
  presets to 4.7. Bedrock SKU drops the -v1 suffix per the official
  4.7 model card (anthropic.claude-opus-4-7 and
  global.anthropic.claude-opus-4-7).
2026-04-21 11:57:06 +08:00
Jason 50431b7ec9 feat(usage-script): add User-Agent header to New API template
Align the New API usage query template with the GENERAL template by
including "User-Agent: cc-switch/1.0" in its request headers, so
cc-switch requests are identifiable in provider server logs and less
likely to be blocked by UA-based rate limiting on some New API
deployments.
2026-04-21 11:57:06 +08:00
Jason 8b65a31c7c feat(claude): upgrade effort toggle from "high" to "max"
Per Anthropic's effort parameter docs, "high" is the API default and
setting effortLevel="high" is equivalent to omitting the field entirely.
The toggle previously produced no effect.

Claude Opus 4.6, Sonnet 4.6, and Opus 4.7 now support a "max" level
that enables unconstrained reasoning. Rename the checkbox (effortHigh
-> effortMax) and write effortLevel="max" when toggled on. Existing
"high" values in user configs are left untouched.

Updates zh/en/ja locales and user-manual entries accordingly.
2026-04-21 11:57:06 +08:00
Jason d03e6f9951 chore(lint): pin Rust toolchain to 1.95 and adopt clippy 1.95 suggestions
- Add rust-toolchain.toml to align local and CI Rust versions, eliminating
  clippy roulette caused by `dtolnay/rust-toolchain@stable` drift.
- Fix 9 clippy 1.95 findings introduced by Hermes Phase 4-8 modules:
  * 4x unnecessary_sort_by  -> sort_by_key (with Reverse for desc)
  * 3x collapsible_match    -> match guards
  * 1x while_let_loop       -> while let
  * 1x useless_conversion   -> drop redundant .into_iter()
2026-04-21 11:57:06 +08:00
Jason 0ca36b9d51 fix: address Hermes review findings (5 medium issues)
- Add missing Hermes MCP import on first launch (lib.rs)
- Add Hermes branch in ProviderForm defaultValues fallback
- Include Hermes in session manager subtitle (zh/en/ja)
- Rename check_openclaw_stream to check_additive_app_stream
- Cache parsed HERMES_DEFAULT_CONFIG to avoid repeated JSON.parse
2026-04-21 11:57:06 +08:00
Jason e8953c286f feat: implement Hermes session manager with SQLite + JSONL support (Phase 6)
- Add hermes.rs session provider with dual-source scanning:
  SQLite (state.db) as primary, JSONL transcripts as fallback
- Dynamic schema discovery via PRAGMA table_info for SQLite resilience
- Use read_head_tail_lines for efficient JSONL metadata extraction
  (head 30 lines for metadata, tail 10 for last_active_at)
- Support both flat and nested JSONL message formats
- Add SQLite session loading and transactional deletion
- Register hermes in parallel session scan (thread::scope)
- Add "hermes" to frontend ProviderFilter type
- 7 unit tests covering JSONL parsing, SQLite source parsing, deletion
2026-04-21 11:57:06 +08:00
Jason 240969d8c7 feat: add Hermes UI components, presets, and config panels (Phase 8)
- Add 7 provider presets (OpenRouter, Anthropic, OpenAI, Google, DeepSeek, Together, Nous)
- Create HermesFormFields + useHermesFormState for provider form integration
- Create Model/Agent/Env config panels with save/load functionality
- Create HermesHealthBanner for config warnings
- Add hermes icon (violet winged H) to icon system
- Integrate into App.tsx: 3 new view types (hermesModel/hermesAgent/hermesEnv),
  sidebar buttons (Brain/Bot/KeyRound), health banner, session support
- Integrate into ProviderForm: presets, form state, key validation, rendering
- Integrate into AddProviderDialog: universal tab exclusion, providerKey, base_url extraction
- Add i18n keys for all Hermes UI (zh/en/ja)
2026-04-21 11:57:06 +08:00
Jason a0b585992a feat: add Hermes frontend types, API layer, and hooks (Phase 7)
- Add "hermes" to AppId union type and all exhaustive Record<AppId>
- Add HermesModelConfig, HermesAgentConfig, HermesEnvConfig types
- Add hermes field to VisibleApps, McpApps, ProxyTakeoverStatus
- Create src/lib/api/hermes.ts with Tauri invoke wrappers
- Create src/hooks/useHermes.ts with 5 query + 3 mutation hooks
- Register hermes in APP_IDS, APP_ICON_MAP (violet color scheme)
- Split MCP_SKILLS_APP_IDS into MCP_APP_IDS (includes hermes) and
  SKILLS_APP_IDS (excludes hermes, since Hermes has no Skills support)
- Wire hermes additive-mode into App.tsx (remove/duplicate handlers),
  ProviderList.tsx (live provider ID query + In Config badge),
  mutations.ts (cache invalidation on switch/add/delete)
- Add Hermes checkbox to McpFormModal
- Add basic hermes i18n keys (en/zh/ja)
2026-04-21 11:57:06 +08:00
Jason 576ff53a75 feat: implement Hermes MCP sync module (Phase 4)
Add mcp/hermes.rs with bidirectional MCP format conversion:
- convert_to_hermes_format: strip type field, infer from command/url
- convert_from_hermes_format: infer type, strip Hermes-specific fields
- Merge-on-write: existing Hermes fields (tools, sampling, timeout,
  roots, enabled) preserved when user has customized them
- update_mcp_servers_yaml: closure-based read-modify-write under write
  lock to prevent TOCTOU races in concurrent sync operations
- 9 unit tests for format conversion and merge logic

Wire up all MCP service dispatch:
- Replace Hermes TODO stubs with real sync/remove calls
- Remove Hermes from sync_all_enabled skip list
- Enable deep link hermes MCP flag (apps.hermes = true)
- Add Hermes import to import_mcp_from_apps command
2026-04-21 11:57:06 +08:00
Jason 6d0e9f4c74 feat: implement Hermes config module and commands (Phase 3)
Add hermes_config.rs (~1190 lines) with YAML section-level replacement
that preserves comments and formatting in unmanaged sections:
- Type definitions: HermesModelConfig, HermesAgentConfig, HermesEnvConfig
- YAML section finder (find_yaml_section_range) with column-0 key detection
- Provider CRUD on custom_providers array (indexed by name field)
- Model/Agent config get/set via yaml<->json conversion
- .env dotenv read/write preserving comments and line ordering
- Health check, backup with rotation, write lock (OnceLock<Mutex>)
- MCP section access stubs for Phase 4
- 19 unit tests

Add commands/hermes.rs with 10 Tauri commands registered in lib.rs.
Replace all Hermes TODO stubs in services/provider/live.rs with real
implementations (import, remove, write-to-live, read-live-settings).
2026-04-21 11:57:06 +08:00
Jason a2e9e1938b feat: add database migration v9→v10 for Hermes support (Phase 2)
- Bump SCHEMA_VERSION from 9 to 10
- Add enabled_hermes column to mcp_servers and skills tables
- Add migrate_v9_to_v10 with table_exists guard for skills (may not
  exist in databases migrated from very old versions)
- Update dao/mcp.rs to fully read/write enabled_hermes in all queries
- Update dao/skills.rs: don't SELECT enabled_hermes (Hermes doesn't
  support Skills yet), keep column indices clean
2026-04-21 11:57:06 +08:00
Jason 81af0a57f9 feat: add Hermes Agent as 6th supported app type (Phase 1)
Register AppType::Hermes across the entire Rust backend:
- Add Hermes variant to AppType enum with additive mode and MCP support
- Add hermes field to McpApps, SkillApps, CommonConfigSnippets, and all
  per-app structs (McpRoot, PromptRoot, VisibleApps, AppSettings)
- Create minimal hermes_config.rs with get_hermes_dir() respecting
  settings override, matching the pattern of other app config modules
- Update all match arms in commands, services, deeplink, proxy, mcp,
  session_manager, and test files
- Extract shared build_additive_app_settings() to eliminate duplication
  between OpenClaw and Hermes deep link handling
- Combine identical OpenClaw/Hermes proxy match arms into unified arms
2026-04-21 11:57:06 +08:00
Jason 701e7d9581 fix: surface backend error details in proxy toast messages
The takeover.failed i18n template lacked the {{detail}} placeholder
and three useProxyStatus onError callbacks omitted the detail variable,
so proxy start/stop/takeover failures all displayed a generic message
regardless of the underlying cause.
2026-04-21 11:57:06 +08:00
Jason e4c34b34e7 fix: remove ANTHROPIC_REASONING_MODEL to decouple thinking from model selection (#2081)
ANTHROPIC_REASONING_MODEL was a non-official env var that forced all
requests with thinking params to use a single "reasoning model",
overriding the user's /model selection. Since new Claude Code versions
send adaptive thinking by default, this caused /model to silently fail.

- Remove reasoning_model field and has_thinking_enabled() from model_mapper
- Simplify map_model() to pure type-based matching (haiku/sonnet/opus)
- Remove reasoning model UI field from provider form
- Retain ANTHROPIC_REASONING_MODEL in ENV_EXCLUDES and override-key
  cleanup lists so legacy configs don't leak into common config
2026-04-21 11:57:06 +08:00
Jason eab0a69d2c fix: unify weekly_limit tier label to match official 7-day naming 2026-04-21 11:57:06 +08:00
Jason 4e790ac059 fix: hide unknown subscription quota tiers from provider card UI 2026-04-21 11:57:06 +08:00
chengww c5b15dd25e fix(claude-plugin): sync current provider config to settings.json (#1905)
* fix(claude-plugin): sync current provider config to settings.json on toggle enable

- Extract syncClaudePluginIfChanged to share logic between autoSaveSettings and saveSettings
- Fix P1: enableClaudePluginIntegration toggle in General tab now actually syncs ~/.claude/settings.json
- Fix P2: check syncCurrentProvidersLiveSafe() return value and show toast on failure
- Fix P3: sync providers on both enable and disable, not just enable
- Fix P4: avoid double syncCurrentProvidersLiveSafe when plugin toggle + dir change happen together
- Remove duplicate comment
- Add missing providersApi.getCurrent/getAll mocks in tests

* style: reformat after rebase onto main

Prettier flagged a line-break introduced by the openclaw directory
change (from main) after rebase.

* fix(claude-plugin): read prev enabled state from live cache to avoid stale closure

syncClaudePluginIfChanged compared enabled against data?.enableClaudePluginIntegration
captured in a useCallback closure. After invalidateQueries + refetch, the React
Query cache is up to date, but the consuming hook's closure does not see the new
value until React re-renders. Quick on->off toggles could therefore skip
applyClaudePluginConfig, leaving ~/.claude/config.json in the previously enabled
state even though settings.json was persisted as disabled.

Read the previous value synchronously from queryClient.getQueryData(["settings"])
before saveMutation.mutateAsync(), then pass it to the helper as prevEnabled.
getQueryData bypasses the closure and reflects the live cache at call time.

Test covers the race: closure data stays at false while the cache reports true;
the helper must still call applyClaudePluginConfig({ official: true }).

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-21 11:56:13 +08:00
zxZeng cc77a040e2 fix: common config checkbox state not persisting for Codex/Claude/Gemini (#2191)
修复:Codex/Claude/Gemini 通用配置勾选状态无法正确保存的问题

Co-authored-by: 曾兴 <zengx@gantsoftware.com>
2026-04-21 11:04:31 +08:00
hengm3467 1b345fbefb Add StepFun and StepFun en Step Plan presets (#2155)
* Add StepFun CN and EN presets

* Add StepFun 2603 model presets

* Make StepFun 2603 the default model

* Revert StepFun branding assets
2026-04-21 10:46:26 +08:00
Li Yang 61bfc29d82 fix(tray): use an app-specific tray id (#1978)
Co-authored-by: liyang <liyang25@pku.edu.cn>
2026-04-21 10:42:59 +08:00
Suda202 2c9252dec5 Fix Ghostty session restore launch path (#1976)
* fix: launch Ghostty via shell command

Use Ghostty's shell execution path instead of injecting raw terminal input so Claude resume commands run reliably when opening a session terminal.

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

* fix(ghostty): pass cwd via --working-directory instead of shell string

Use Ghostty's native --working-directory flag to set the working
directory, matching the pattern used by Alacritty. This avoids shell
expansion of special characters (e.g. $VAR, spaces) in project paths.

The command is now passed directly to -c without a cd prefix.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-20 12:42:00 +08:00
Franklin 34349a2743 Add OpenClaw config directory settings (#1518)
Co-authored-by: 张斌 <zhangbin25@xiaomi.com>
2026-04-20 08:44:38 +08:00
King 8ba92b5470 feat(ui): add quick-set button for model mapping fields (#2179)
* feat(ui): add quick-set button for model mapping fields

Add a "一键设置" (Quick Set) button in the model mapping section to
simplify provider configuration. When users enter a model name in any
of the five model fields, they can now click this button to populate
all fields with that same value.

This addresses the UX friction of manually filling all five model
mapping fields (主模型, 推理模型, Haiku, Sonnet, Opus) when the
provider uses the same model name across all request types.

Implementation:
- Add Wand2 icon import from lucide-react
- Insert quick-set button alongside existing fetch-models button
- Logic picks first non-empty model value and applies to all fields
- Show success toast after applying
- Disabled state when all model fields are empty
- Add i18n strings for zh, en, ja locales

Relates to user feedback about tedious model configuration workflow.

* style(ui): format ClaudeFormFields component code

Apply consistent code formatting to ClaudeFormFields.tsx following
project linting rules. Includes multi-line import statements and
improved readability for conditional expressions.
2026-04-19 21:42:17 +08:00
hotelbe 87635e7fc6 feat(copilot): add GitHub Enterprise Server support (#2175)
* feat(copilot): add GitHub Enterprise Server support

* fix(copilot): address GHES PR review findings (P1 + 2×P2)

- P1: Use composite account ID (domain:user_id) for GHES to prevent
  cross-instance ID collisions; github.com keeps plain numeric ID for
  backward compatibilit
- P2-a: Use get_api_endpoint() for model list URL with automatic
  fallback to static URL when dynamic endpoint resolution fails
- P2-b: Add normalize_github_domain() as backend SSOT for domain
  normalization (lowercase, strip protocol/path/query, reject userinfo)

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 20:29:46 +08:00
YaoguoHH 9871d3d1eb fix(skills): sync imported skills to app directories after import (#2101)
`import_from_apps()` saves skills to the database but does not create
symlinks/copies in the target app directories (e.g. `~/.claude/skills/`).
This causes skills to appear as "installed" in the UI while the actual
files are missing from the app directories.

Add `sync_to_app_dir()` calls after `db.save_skill()` in the import
loop, matching the pattern used by `install()` and `toggle_app()`.
2026-04-19 15:25:25 +08:00
Coconut-Fish 1126c7459d Style/add provider.notes (#2138)
* style(FailoverQueueManager): 显示供应商备注信息

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

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

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

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

* style(FailoverQueueItem): 添加条件序列化以优化供应商备注字段
2026-04-18 17:48:58 +08:00
Dex Miller 03a0f9661b feat(proxy): Gemini Native API proxy integration (#1918)
* refactor(proxy): extract take_sse_block helper with CRLF delimiter support

Replace inline `buffer.find("\n\n")` SSE splitting logic across streaming,
streaming_responses, response_handler, and response_processor with a shared
`take_sse_block` function that handles both `\n\n` and `\r\n\r\n` delimiters.

* feat(proxy): add Gemini Native URL builder and full-URL resolver

Introduce gemini_url module that normalizes legacy Gemini/OpenAI-compatible
base URLs into canonical models/*:generateContent endpoints. Supports both
structured Gemini URLs (auto-normalized) and opaque relay URLs (pass-through
with query params only).

* feat(proxy): add Gemini Native schema, shadow store, transform, and streaming

- gemini_schema: Gemini generateContent request/response type definitions
- gemini_shadow: session-scoped shadow store for thinking signature and
  tool-call state replay across streaming chunks
- transform_gemini: bidirectional Anthropic Messages ↔ Gemini Native
  request/response conversion with thinking block and tool-use support
- streaming_gemini: Gemini SSE → Anthropic SSE streaming adapter with
  incremental thinking/text/tool_use delta emission

* feat(proxy): wire Gemini Native format into proxy core and Claude adapter

Integrate gemini_native api_format throughout the proxy pipeline:
- ClaudeAdapter: detect Gemini provider type, Google/GoogleOAuth auth
  strategies, and suppress Anthropic-specific headers for Gemini targets
- Forwarder: Gemini URL resolution, shadow store threading, endpoint
  rewriting to models/*:generateContent with stream/non-stream variants
- Handlers: route Gemini streaming through streaming_gemini adapter and
  non-streaming through transform_gemini converter
- Server/State: add GeminiShadowStore to shared ProxyState
- StreamCheck: support gemini_native health check with proper auth headers

* feat(ui): add Gemini Native provider preset and api format option

- Add gemini_native to ClaudeApiFormat type and ProviderMeta.apiFormat
- Add "Gemini Native" provider preset with default Google AI endpoints
- Show Gemini-specific endpoint hints and full-URL mode guidance
- Add gemini_native option to API format selector in ClaudeFormFields
- Add i18n strings for zh/en/ja

* feat(proxy): add Gemini Native tool argument rectification

* feat(proxy): update Gemini streaming and transformation logic

* fix(proxy): align shadow turns to tail on client history truncation

* fix: revert unrelated cache_key change in claude proxy transform

Restore .unwrap_or(&provider.id) fallback for cache_key to match main
branch behavior. Only gemini_native related changes should be in this branch.

* Prevent Gemini review regressions in streaming and tool rectification

PR #1918 review feedback exposed two correctness issues in the Gemini Native adapter path. Gemini SSE buffering was still using lossy UTF-8 decoding, which could corrupt split multibyte payloads and drop streamed output. Tool arg rectification also removed top-level parameters eagerly, which broke tools that legitimately define a parameters field.

This change moves Gemini SSE buffering onto the existing append_utf8_safe path and makes parameters flattening conditional on the schema actually expecting nested extraction. The old Skill rectification path stays intact, and new regression tests cover both the preserved parameters case and UTF-8-split JSON payloads.

Constraint: Existing PR #1918 review feedback must be fixed without staging unrelated local docs and artifact files
Rejected: Keep String::from_utf8_lossy in Gemini SSE buffering | corrupts split multibyte payloads and can drop JSON chunks
Rejected: Always preserve the parameters wrapper | regresses the existing nested-parameters rectification path for Skill-style tools
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep Gemini SSE buffering on the UTF-8-safe accumulator path and only unwrap parameters when the target schema does not declare it as a legitimate field
Tested: cargo fmt --manifest-path src-tauri/Cargo.toml --all; cargo test --manifest-path src-tauri/Cargo.toml preserves_utf8_boundaries_when_json_payload_spans_chunks; cargo test --manifest-path src-tauri/Cargo.toml gemini_to_anthropic_rectifies_tool_args_from_schema_hints; cargo test --manifest-path src-tauri/Cargo.toml rectifies_streamed_skill_args_from_nested_parameters; cargo test --manifest-path src-tauri/Cargo.toml gemini_to_anthropic_preserves_legitimate_parameters_arg
Not-tested: Full src-tauri test suite; live end-to-end Gemini relay traffic against upstream services

* Keep Gemini tool replay stable across Claude request boundaries

Claude Code follow-up requests were still falling back to locally reconstructed functionCall parts, which dropped Gemini thought signatures and triggered INVALID_ARGUMENT errors from the official Gemini API. The replay path needed to survive real Claude request boundaries, not just idealized in-process test flows.

This change makes Claude requests reuse X-Claude-Code-Session-Id as the shadow session key, records streamed Gemini tool turns before tool_use events are fully drained, and matches assistant tool_use turns to shadow state by tool_use id and normalized tool name before positional fallback. Together these fixes keep thoughtSignature-bearing Gemini tool calls available for the next request in the loop.

Constraint: Claude Code sends a stable X-Claude-Code-Session-Id header while metadata.session_id may be absent on follow-up requests
Rejected: Rely on metadata-only Claude session extraction | generated fresh session ids and broke cross-request shadow replay
Rejected: Record Gemini shadow only after streaming completes | loses the race when the client sends the next request immediately after tool_use
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Preserve Gemini shadow continuity across requests by keying Claude sessions from the header first and persisting tool-call shadow before yielding tool_use events downstream
Tested: cargo fmt --manifest-path src-tauri/Cargo.toml --all; cargo test --manifest-path src-tauri/Cargo.toml test_extract_session_from_claude_header; cargo test --manifest-path src-tauri/Cargo.toml test_extract_session_from_claude_header_precedes_metadata; cargo test --manifest-path src-tauri/Cargo.toml stores_tool_shadow_before_tool_use_events_are_fully_drained; cargo test --manifest-path src-tauri/Cargo.toml shadow_replay_matches_tool_use_turn_by_id_when_position_drifts; cargo test --manifest-path src-tauri/Cargo.toml shadow_replay_aligns_to_latest_turns_after_client_truncation
Not-tested: Full src-tauri test suite without test filters; live end-to-end Gemini relay after this exact commit hash

* style: apply cargo fmt to pass Backend Checks CI

Wrap prompt_cache_key chained call across lines per rustfmt default
formatting. Pure formatting change, no behavior difference.

* fix(proxy/gemini): synthesize unique ids for no-id tool calls + enforce object params schema

P1 — Parallel tool calls without Gemini-assigned ids no longer collapse.
Gemini 2.x native parallel `functionCall` entries may omit the `id` field.
The previous `merge_tool_call_snapshots` fell back to matching by `name`,
which silently merged two parallel calls to the same function into one
entry — dropping the first call's args. The non-streaming path and shadow
store further bottlenecked on empty-string ids: multiple `tool_use` blocks
shared the same id, and `tool_name_by_id.get("")` could only return one
mapping, causing later `tool_result` round-trips to fail with
`Unable to resolve Gemini functionResponse.name` or bind to the wrong tool.

Fix: introduce `synthesize_tool_call_id()` producing `gemini_synth_<uuid>`.
Both streaming and non-streaming response paths now guarantee every
Anthropic-visible tool_use carries a unique id. `merge_tool_call_snapshots`
matches by id first, falling back to the `parts` array position (for the
cumulative-streaming case) while preserving the synthesized id across
chunks. `convert_message_content_to_parts` detects the synthetic prefix
and strips the id from outbound `functionCall`/`functionResponse` so the
internal identifier never leaks upstream. `shadow_parts` performs the
same strip when replaying a recorded assistant turn.

P2 — Vertex AI rejects empty `parameters` schemas. When an Anthropic tool
arrives with missing or empty `input_schema`, the proxy used to emit
`"parameters": {}` (no `type`), which fails Vertex AI validation with
`functionDeclaration parameters schema should be of type OBJECT`.
Contrary to the automated-review suggestion, the fix is not to omit
`parameters` (that too is rejected) but to normalize to the canonical
empty-object form `{type: "object", properties: {}}`.
Refs: google-gemini/generative-ai-python#423, BerriAI/litellm#5055.

Fix: new `ensure_object_schema` helper in `gemini_schema` promotes
missing `type` to `"object"` and adds empty `properties` when absent,
while leaving atomic (non-object) schemas untouched.

Tests: seven new regressions covering parallel no-id calls, cumulative
chunk id reuse, synthetic-id round-trip both directions, shadow replay
id stripping, and the three Vertex-AI schema shapes.

The two existing wrapper functions (`gemini_to_anthropic` and
`gemini_to_anthropic_with_shadow`) gain `#[allow(dead_code)]` to clear
a pre-existing clippy -D warnings failure — they are part of the public
transform API surface and intentionally kept for future callers.

Addresses Codex review P1/P2 on #1918.

* fix(proxy/gemini): narrow URL normalization + guard empty OAuth access_token

P2a — Preserve opaque relay URLs that contain `/v1/models/` prefixes.

`should_normalize_gemini_full_url` previously flagged any full URL whose
path merely contained `/v1beta/models/` or `/v1/models/` as a structured
Gemini endpoint, forcing rewrite to `.../v1beta/models/{model}:method`.
This silently dropped legitimate relay route segments (e.g.
`https://relay.example/v1/models/invoke` → `.../v1beta/models/...:generateContent`,
losing `/invoke`) and sent traffic to the wrong upstream path.

Replace the bare `contains(...)` checks with
`matches_structured_gemini_models_path`, which requires the
`/models/` segment to be followed by a canonical Gemini method call
(`*:generateContent` or `*:streamGenerateContent`). The
`matches_bare_gemini_models_path` helper is generalized (and renamed) to
handle both `/v1beta/models/` and `/v1/models/` alongside the original
bare `/models/` shape.

P2b — Reject empty Gemini OAuth access_tokens before they reach the
bearer header.

`GeminiAdapter::parse_oauth_credentials` accepts refresh-token-only JSON
(and surfaces `{"access_token": "", ...}` for expired credentials) with
`access_token` defaulting to `""`. The Claude adapter's GeminiCli branch
then called `AuthInfo::with_access_token(key, creds.access_token)`
unconditionally, so the bearer-header builder at
`AuthStrategy::GoogleOAuth` resolved to `Authorization: Bearer ` — a
deterministic 401 from upstream.

CC Switch does not currently exchange the refresh_token for a fresh
access_token (`OAuthCredentials::needs_refresh` / `can_refresh` are
annotated `#[allow(dead_code)]`). Until that exists, only attach
`access_token` when it is non-empty; fall back to plain GoogleOAuth
strategy with the raw key and log a warn pointing users at
`~/.gemini/oauth_creds.json` so the failure mode is observable.

Tests:
- gemini_url.rs: three new regressions — opaque `/v1/models/invoke`,
  opaque `/v1beta/models/route`, and the positive counter-case where a
  structured `/v1/models/...:generateContent` path still normalizes.
- claude.rs: three new `test_extract_auth_gemini_cli_*` tests covering
  refresh-only JSON, empty-string access_token JSON, and the valid-JSON
  pass-through.

All 839 lib tests pass; cargo fmt + clippy -D warnings clean.

Addresses Codex review P2 findings on #1918.

* fix(proxy/gemini): treat empty-string functionCall id as missing in streaming path

Follow-up to the earlier P1 fix: some Gemini relays serialize an absent
functionCall id as `"id": ""` instead of omitting the field. The
non-streaming `extract_tool_call_meta` already filters these via
`.filter(|s| !s.is_empty())`, but the streaming counterpart
`extract_tool_calls` passed the empty string straight through
`function_call.get("id").and_then(|v| v.as_str())` into
`GeminiToolCallMeta::new`, producing a `Some("")` id.

Downstream, `merge_tool_call_snapshots` would then match two parallel
no-id calls against each other on their shared empty-string id,
collapsing them into a single snapshot (silent data loss for the first
call) and emitting an Anthropic `tool_use.id: ""` that breaks tool_result
correlation on the Claude Code client.

Fix:
- `extract_tool_calls`: apply the same `filter(|s| !s.is_empty())` guard
  used in the non-streaming path so empty strings become `None` before
  reaching the shadow meta.
- `merge_tool_call_snapshots`: defensively collapse any incoming
  `Some("")` to `None` up front — keeps the "missing vs present" invariant
  local to the merge step for future callers that might build
  `GeminiToolCallMeta` by hand.

Tests (2 new, both in streaming_gemini):
- `parallel_empty_string_id_calls_are_treated_as_missing_and_preserved`
  covers two parallel calls with explicit `"id": ""` — asserts both
  surface, no empty tool_use id leaks, and each gets a unique
  `gemini_synth_` id.
- `single_empty_string_id_tool_call_gets_synthesized_id` covers the
  non-parallel degraded-relay case.

All 841 lib tests pass; cargo fmt + clippy -D warnings clean.

Addresses Codex follow-up P1 on #1918.

* fix(proxy/gemini): gate generic REST path suffixes behind Google host whitelist

`should_normalize_gemini_full_url` previously treated any full URL whose
path ends with `/v1`, `/v1/models`, `/models`, `/v1/openai`, or `/openai`
as a structured Gemini endpoint and rewrote it to
`/v1beta/models/{model}:generateContent`. These are ubiquitous REST
conventions — opaque relays such as `https://relay.example/custom/v1`
legitimately use them for fixed endpoints — so the rewrite silently
routed traffic to the wrong upstream path.

Split the predicate into two layers:

- **Unconditional**: `matches_structured_gemini_models_path` (i.e. a
  `/models/...:generateContent` method call anywhere in the path), the
  Google-specific `/v1beta*` family, and the deep OpenAI-compat paths
  (`/v1beta/openai/chat/completions`, `/openai/chat/completions`, and
  their `responses` siblings). These remain host-agnostic because the
  path grammar itself is Gemini-specific.
- **Google-host gated**: `/v1`, `/v1/models`, `/models`, `/v1/openai`,
  `/openai`. Only normalized when the host is one of
  `generativelanguage.googleapis.com`, `aiplatform.googleapis.com`, or a
  real `*-aiplatform.googleapis.com` Vertex regional endpoint. The match
  is exact/suffix (not `contains`), so lookalike hosts like
  `aiplatform.example.com` are correctly treated as opaque relays.

Tests (8 new in `gemini_url::tests`):
- Four opaque-relay cases: `/custom/v1`, `/custom/models`,
  `/custom/v1/models`, `/custom/openai` — all preserved as-is.
- Three Google-host counter-cases: `/v1`, `/models`, and
  `us-central1-aiplatform.googleapis.com/v1` still normalize.
- One lookalike safety case: `aiplatform.example.com/v1` is NOT
  treated as Google.

All 849 lib tests pass; cargo fmt + clippy -D warnings clean.

Addresses Codex review P2 on #1918.

* fix(proxy/gemini): align shadow id with client-visible id in non-streaming path

When Gemini returns a `functionCall` without an id (common in 2.x
parallel calls), `gemini_to_anthropic_with_shadow_and_hints` previously
generated TWO independent synthesized UUIDs:

  1. Line 186-197 — synthesized id `A` used for the Anthropic-visible
     `content[tool_use].id` returned to the client.
  2. Line 850-881 — `extract_tool_call_meta` independently synthesized
     id `B ≠ A`, which populated `shadow_turn.tool_calls[i].id`.

`shadow_content` (line 225-228, cloned from `rectified_parts`) retained
the original missing/empty id. Result: the client sees id `A`, the
shadow store holds id `B`.

On the next turn, `convert_messages_to_contents` builds
`tool_name_by_id` from `build_tool_name_map_from_shadow_turns`, which
uses `tool_calls[i].id` — so the map contains `B → name` but not
`A → name`. When the client sends back `tool_result(tool_use_id=A)`,
resolution fails with:

  Unable to resolve Gemini functionResponse.name for tool_use_id `A`

This affects both truncated histories (client sends only the
tool_result) and full histories (shadow-replay branch at line 342-354
skips `convert_message_content_to_parts`, so the assistant tool_use
block never registers id `A` itself).

Fix: make `rectified_parts` the single source of truth. After
`rectify_tool_call_parts`, run a pre-pass that writes
`synthesize_tool_call_id()` back into any `functionCall` that lacks a
non-empty id. All three readers — the content builder (186-197), the
shadow_content clone (225-228), and `extract_tool_call_meta` — then
observe the same id. `shadow_parts()` already strips synthesized ids on
replay (line 616-628), so the internal identifier never leaks to
Gemini upstream.

This mirrors the streaming path, which already has single-source-of-
truth semantics via `tool_call_snapshots` in `streaming_gemini.rs` —
no change needed there.

Tests (5 new in `transform_gemini::tests`):
- `non_stream_shadow_id_matches_client_visible_id`: asserts
  `response.content[0].id == shadow.tool_calls[0].id ==
  shadow.assistant_content.parts[0].functionCall.id`.
- `non_stream_missing_id_scenario_a_truncated_history_resolves`: turn 2
  sends only `[tool_result(id=A)]`; resolution must succeed.
- `non_stream_missing_id_scenario_b_full_history_replay_resolves`: turn 2
  sends `[assistant(tool_use=A), tool_result(A)]`; shadow-replay branch
  strips the synth id from outgoing `functionCall` while still
  resolving the subsequent `tool_result`.
- `non_stream_preserves_original_gemini_id_when_present`: regression —
  genuine Gemini ids flow through unchanged.
- `non_stream_synthesized_id_not_leaked_to_gemini_via_shadow_replay`:
  defensive — shadow-replay path must strip synth ids from both
  `functionCall.id` and `functionResponse.id`.

All 854 lib tests pass; cargo fmt + clippy -D warnings clean.

Addresses Codex follow-up P1 on #1918.

* refactor(proxy/gemini): share build_anthropic_usage between stream and non-stream paths

`streaming_gemini::anthropic_usage_from_gemini` and
`transform_gemini::build_anthropic_usage` were byte-for-byte identical
(32 lines each) — both converting Gemini `usageMetadata` into the
Anthropic `usage` shape including `cache_read_input_tokens` mapping.

Promote the non-streaming version to `pub(crate)` and reuse it from the
streaming SSE converter. Removes ~30 lines of duplication and guarantees
the two paths cannot drift apart.

No behavioral change; all 854 lib tests pass; cargo fmt + clippy -D
warnings clean.

* fix(proxy/gemini): gate /v1beta behind Google host + normalize models/ model id prefix

Two related P2 corrections to the Gemini Native URL surface, both
folding into the existing Google-host-whitelist architecture.

## P2a — `/v1beta` suffix should not unconditionally trigger rewrite

`should_normalize_gemini_full_url` placed `/v1beta` and `/v1beta/models`
in the unconditional layer on the reasoning that `/v1beta` is
Google-specific. In practice an opaque relay fronting a non-Gemini
service at `https://relay.example/custom/v1beta` would still be
silently rewritten to `/v1beta/models/{model}:generateContent`,
breaking the deployment.

Move `/v1beta`, `/v1beta/models`, and `/v1beta/openai` into the
Google-host gated layer alongside `/v1`, `/models`, and friends. The
unconditional layer now only accepts paths whose grammar is
intrinsically Gemini — `/models/...:generateContent` method calls and
the deep OpenAI-compat endpoints like `/openai/chat/completions` and
`/openai/responses`. Pasted AI-Studio URLs such as
`https://generativelanguage.googleapis.com/v1beta` still normalize
because the host matches the whitelist.

## P2b — `model: "models/gemini-2.5-pro"` produced doubled path prefix

Gemini SDKs (and the official `list_models` response) commonly surface
model ids in resource-name form `models/gemini-2.5-pro`. Raw
interpolation into `format!("/v1beta/models/{model}:...")` produced
`/v1beta/models/models/gemini-2.5-pro:streamGenerateContent` which
upstream rejects — yielding false-negative health checks for otherwise
valid provider configs.

Introduce `normalize_gemini_model_id(&str) -> &str` in `gemini_url`
as the single source of truth: strips an optional leading `/` then an
optional `models/` prefix, leaving bare ids untouched. Apply in the
three call sites that build a Gemini method URL:
- `services/stream_check.rs::resolve_claude_stream_url` (unified path)
- `services/stream_check.rs::check_gemini_stream` (Gemini-only path)
- `proxy/forwarder.rs::rewrite_claude_transform_endpoint` (production)

Tests (9 new):
- `gemini_url`: 3 regressions for opaque vs Google-host `/v1beta*`
  handling + 5 unit tests pinning `normalize_gemini_model_id` behavior
  (strip prefix, leave bare id, preserve nested slashes past the one
  stripped prefix, tolerate leading slash, pass through empty input).
- `stream_check`: one end-to-end regression confirming
  `models/gemini-2.5-pro` collapses to the expected single-prefix URL.
- `forwarder`: one end-to-end regression on the production rewrite
  path.

All 864 lib tests pass; cargo fmt + clippy -D warnings clean.

Addresses Codex P2 feedback on #1918.

* fix(proxy/gemini): trim API key before provider-type detection and OAuth parsing

Leading whitespace on a copied oauth_creds.json (e.g. trailing newline
when the user copies the file content as-is) would slip past the
`starts_with("ya29.") || starts_with('{')` prefix check in
`ClaudeAdapter::provider_type`, causing the provider to be misclassified
as raw-API-key Gemini and fall back to `x-goog-api-key` with the raw
JSON as the key — which upstream rejects with 401.

The frontend's `handleApiKeyChange` already trims on keystrokes but
deep-link imports, the JSON editor, and live-config backfill all bypass
that path. Trim at every backend extraction point so the coverage is
uniform:

- `ClaudeAdapter::extract_key` (5 env / fallback branches) gets
  `.map(str::trim)` before `.filter(|s| !s.is_empty())` so that
  whitespace-only values are also treated as missing.
- `GeminiAdapter::extract_key_raw` gets the same chain (including
  the `.filter` it was missing before).
- `GeminiAdapter::parse_oauth_credentials` gets a defensive
  `let key = key.trim();` at the entry as a belt-and-suspenders guard.

Adds two regression tests covering JSON and bare `ya29.` keys with
leading newline/space.

* fix(proxy/gemini): gate generic REST suffix stripping behind Google host in non-full-URL mode

`build_gemini_native_url` unconditionally stripped `/v1`, `/v1beta`,
`/models`, and `/openai` suffixes from the base path regardless of
host. This worked for Google's own endpoints but silently rewrote
third-party relay URLs like `https://relay.example/custom/v1` to
`.../custom/v1beta/models/...`, breaking any relay that mounts its
Gemini-compatible namespace under a versioned prefix.

The result was also asymmetric with the previously-fixed full-URL
branch: toggling the "full URL" switch changed the outbound URL for
the same base_url, which is exactly the kind of invisible behavior
that makes debugging proxy deployments painful.

Align `normalize_gemini_base_path` with
`should_normalize_gemini_full_url`'s layered model:

- Unconditional: `/models/...:method` structured paths and deep
  OpenAI-compat endpoints (`/openai/chat/completions`,
  `/openai/responses` and their versioned variants) — these are
  unambiguous Gemini-specific grammar on any host.
- Google-host gated: generic `/v1`, `/v1beta`, `/models`, `/openai`
  suffixes only get stripped on `generativelanguage.googleapis.com`,
  `aiplatform.googleapis.com`, or `*-aiplatform.googleapis.com`.
  Other hosts preserve the prefix verbatim so relays keep their
  intended routing.

Adds seven regression tests for the non-full-URL flow: opaque relay
preservation (v1 / v1beta / models / openai suffix variants), Google
host normalization (counter-case), and boundary cases (structured
method path and deep OpenAI-compat endpoint stripped regardless of
host).

Test count: 864 -> 873.

* Revert "fix(proxy/gemini): gate generic REST suffix stripping behind Google host in non-full-URL mode"

This reverts commit d19ff09cb7.

* test(proxy/gemini): pin non-full-URL versioned relay base stripping

Adds two regression tests that lock in the intentional asymmetry
between full-URL and non-full-URL modes:

- Full-URL mode: opaque base path (e.g. `https://relay.example/custom/v1beta`)
  is preserved verbatim. Already covered by
  `preserves_opaque_full_url_with_bare_v1beta_suffix`.
- Non-full-URL mode: base path MUST strip `/v1`, `/v1beta`, etc. so the
  standard `/v1beta/models/{model}:method` endpoint can be appended
  without producing a doubled `/v1beta/v1beta/models/...` path.

The non-full-URL contract is "base URL + cc-switch appends the
canonical Gemini endpoint". A user who needs a relay's custom
namespace (e.g. `/v1/models/...`) must use full-URL mode and paste
the complete method path. This commit adds regression coverage so a
future attempt to mirror full-URL's host-whitelist gating into
`normalize_gemini_base_path` will fail the test suite immediately.

* chore(lint): address clippy 1.95 findings in existing modules

CI upgraded to Rust 1.95 and flagged ten pre-existing warnings that
older toolchains did not enforce. None relate to the Gemini proxy
integration PR itself but they block CI on the feature branch, so
clean them up here as a separate commit for easy review:

collapsible_match:
- proxy/providers/gemini_schema.rs: `"items" if value.is_object()`
  match guard instead of nested if.
- proxy/providers/transform_responses.rs: fold
  `map_responses_stop_reason`'s `"completed"` / `"incomplete"` arms
  into match guards, relying on the existing `_ => "end_turn"` fall-
  through for non-matching guard conditions (semantics preserved).
- services/session_usage_codex.rs: fold
  `"session_meta" if state.session_id.is_none()` guard, relying on
  the existing `_ => {}` fall-through.

unnecessary_sort_by:
- services/provider/endpoints.rs: `sort_by_key(|ep| Reverse(ep.added_at))`.
- services/skill.rs (backup list): same Reverse idiom on `created_at`.
- services/skill.rs (skill listings x2): `sort_by_key(|s| s.name.to_lowercase())`.

useless_conversion:
- services/skill.rs: drop the explicit `.into_iter()` on `zip`'s argument.

while_let_loop:
- services/webdav_auto_sync.rs: `while let Some(wait_for) = ...`
  instead of `loop { let Some(...) = ... else { break }; ... }`.

All changes are mechanical and preserve behavior. `cargo test --lib`
remains green (868 passed).

* fix(proxy/gemini): reconcile synthesized tool-call ids with later real ids + preserve thoughtSignature

Three related findings on `streaming_gemini.rs` for Gemini's cumulative
`streamGenerateContent` stream, all centered on `merge_tool_call_snapshots`:

1. (P1) Match upgraded tool-call IDs by position.
   When Gemini delivers a `functionCall` without an id on chunk 1
   (cc-switch synthesizes `gemini_synth_*`) and then upgrades it to a
   real id on chunk 2, the `Some(incoming_id)` branch only matched by
   id and missed the existing synthesized snapshot. A second entry
   would be pushed, yielding duplicate `tool_use` content blocks at
   stream end — one with the synthesized id, one with the real id —
   which could trigger duplicate tool execution and break tool_result
   correlation. Add a positional fallback: when no id match exists but
   the same-position slot holds a synthesized id, merge into it.
   `or(preserved_id)` already lets the real id win the merge.

2. (P2) Preserve prior thoughtSignature when merging snapshots.
   `tool_call_snapshots[index] = tool_call` overwrote the slot
   entirely, dropping any `thoughtSignature` captured on an earlier
   chunk if the current cumulative snapshot omitted it. Since
   `build_shadow_assistant_parts` writes `thoughtSignature` into the
   shadow turn from `tool_call.thought_signature`, a dropped signature
   would cause later replay requests to Gemini to be rejected with
   invalid-signature errors. Preserve the existing signature when the
   incoming chunk does not carry one.

3. (P2) Document the part-order streaming trade-off.
   All `tool_use` content blocks are emitted after the final text
   `content_block_stop`, so interleaved [text, functionCall, text,
   functionCall] parts arrive at the Anthropic client as [text(concat),
   tool_use, tool_use] — different from the non-streaming transformer,
   which preserves part order. This is intentional given the cumulative
   snapshot model and the consumers we target (claude-code-like clients
   don't depend on strict interleaving for tool execution correctness).
   Add a block comment at the flush site describing the trade-off and
   what a strict-order fix would entail, so this isn't rediscovered as
   a bug later.

Regression tests:
- upgraded_real_id_merges_into_existing_synthesized_snapshot
- thought_signature_preserved_when_later_chunk_omits_it

Test count: 868 -> 870. clippy 1.95 clean. fmt clean.

* fix(proxy/gemini): prefer exact tool-call id over normalized-name fallback

The shadow-turn matcher used a three-branch `||` chain (id / full name /
normalized name). When two tools share a suffix (e.g. `server_a:search`
and `server_b:search`), the normalized-name clause could short-circuit
on an earlier turn whose id is actually wrong for the incoming tool_use,
mis-routing replay state (functionCall id / thoughtSignature) for later
tool_result resolution.

Split matching into two layers: when the incoming message carries any
tool_use ids, run id-based lookup first and return on the earliest hit.
Only fall back to full-name / normalized-name matching when the incoming
ids are absent or none of them resolve.

Add two regressions:

- shadow_replay_prefers_exact_id_match_over_normalized_name_collision
  Two shadow turns with colliding normalized names and two assistant
  messages whose ids cross the positional order; asserts each message
  replays the id-correct shadow turn (including thoughtSignature).

- shadow_replay_falls_back_to_name_when_ids_absent
  Shadow turn with no id and incoming tool_use with an empty id;
  asserts the name fallback still populates the replayed part.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-16 22:42:49 +08:00
Dex Miller de23216e49 feat(usage): refine usage dashboard UI and date range picker (#2002)
* feat(usage): enhance usage stats backend and query hooks

* feat(usage): redesign calendar date range picker with auto-switch and simplified layout

* refactor(usage): streamline dashboard layout and stats components

* refactor(usage): compact request log table with merged cache/multiplier columns and centered layout

* feat(i18n): add cache short labels and usage stats translations for zh/en/ja

* Align usage dashboard stats with range boundaries

The usage dashboard mixed second-precision detail rows with day-level rollups, which caused custom half-day ranges to overcount historical rollup data and left the request log paginator on stale pages after top-level filter changes.

This change limits rollups to fully covered local days, aligns multi-day trend buckets with natural local days, and resets request log pagination when the dashboard range or app filter changes.

Constraint: usage_daily_rollups stores only daily aggregates after pruning old detail rows
Rejected: Include partial boundary rollups proportionally | historical intra-day detail is unavailable after pruning
Rejected: Force RequestLogTable remount on range change | would discard local draft filters unnecessarily
Confidence: high
Scope-risk: moderate
Reversibility: clean
Directive: Keep summary, trends, provider stats, and model stats on the same rollup-boundary rules
Tested: cargo test --manifest-path src-tauri/Cargo.toml usage_stats
Tested: pnpm exec vitest run tests/components/RequestLogTable.test.tsx
Tested: pnpm typecheck
Not-tested: Manual UI validation in the Tauri app

* Preserve full-day usage filters at minute precision

The latest review surfaced two interaction bugs in the usage dashboard: rollup-backed stats undercounted end days selected via the minute-precision picker, and immediate select changes accidentally applied unsubmitted text drafts from the request log filters.

This change treats 23:59 as a fully selected local end day for rollup inclusion and narrows select-side state syncing so app/status updates do not commit provider/model drafts.

Constraint: The custom range picker emits minute-precision timestamps, while rollups are stored at day granularity
Rejected: Require exact 23:59:59 end timestamps | unreachable from the current picker UI
Rejected: Rebuild applied filters from the full draft state on select changes | silently commits unsaved text input
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep request-log text fields on explicit apply semantics even when select filters remain immediate
Tested: cargo test --manifest-path src-tauri/Cargo.toml usage_stats
Tested: pnpm exec vitest run tests/components/RequestLogTable.test.tsx
Tested: pnpm typecheck
Not-tested: Manual Tauri dashboard interaction

* refactor(usage): move range presets into date picker, single-row layout

- UsageDateRangePicker: add preset shortcuts (今天/1d/7d/14d/30d) inside
  popover top; clicking a preset applies immediately and closes popover
- UsageDashboard: collapse to single row (app filters + refresh + picker);
  remove standalone preset buttons and summary stats bar
- RequestLogTable: replace static Calendar badge with interactive
  UsageDateRangePicker via onRangeChange prop; single filter row

* Keep usage pagination regression coverage aligned with the rendered UI

The new regression test was asserting a non-existent pagination label and page summary text, so it failed before it could verify the real page-reset behavior. This commit switches the assertions to the numbered pagination buttons that the component actually renders and validates the reset through the query hook arguments.

Constraint: RequestLogTable exposes numbered pagination buttons, not a "Next page" label or "2 / 6" summary text
Rejected: Add synthetic pagination labels solely for the test | would couple production markup to a test-only assumption
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Prefer pagination assertions that follow the rendered controls or hook inputs instead of invented summary text
Tested: pnpm vitest run tests/components/RequestLogTable.test.tsx; pnpm typecheck; pnpm test:unit

* refactor(usage): clean up dead code and polish date range picker

- Remove unused exports MAX_CUSTOM_USAGE_RANGE_SECONDS,
  timestampToLocalDatetime, and localDatetimeToTimestamp from
  usageRange.ts (replaced by the calendar picker)
- Deduplicate getPresetLabel from UsageDashboard and
  UsageDateRangePicker into shared getUsageRangePresetLabel helper
- Add aria-label, aria-current and aria-pressed to calendar day
  buttons so screen readers can disambiguate same-numbered days
  across adjacent months
- Drop unused cacheReadShort and cacheWriteShort i18n keys (zh/en/ja);
  the request log table renders R/W prefixes inline
- Align customRangeHint copy with the removed 30-day limit by
  dropping "up to 30 days" wording (zh/en/ja)

* fix(usage): align rollup cutoff to local midnight to keep days complete

`rollup_and_prune` previously used `Utc::now() - retain_days * 86400`
as the cutoff. Because rollups are bucketed by *local* date and detail
rows below the cutoff are pruned, an unaligned cutoff left the youngest
rolled-up day half-rolled-up and half-pruned. Combined with the new
`compute_rollup_date_bounds` boundary trimming (which excludes any
rollup day not fully covered by the requested range), custom range
queries that touch that day silently under-count summary, trend,
provider, and model stats.

Fix the invariant at the source: snap the cutoff to the next local
midnight after `(now - retain_days)`. Every rollup row now reflects a
complete local day, so the boundary trimmer's all-or-nothing assumption
holds.

Includes unit tests for the cutoff math (typical case + already-on-
midnight case). DST gap is handled defensively by bumping forward by
an hour.

Addresses Codex P2 review finding on PR #2002.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-16 17:00:28 +08:00
Jason Young 507bf038a9 feat(stream-check): refresh default models and detect model-not-found errors (#2099)
* chore(stream-check): update default health check models to latest

Replaces deprecated gpt-5.1-codex@low with gpt-5.4@low and switches
the Gemini default from gemini-3-pro-preview to gemini-3-flash-preview
to pick the lightest variant of the latest series for fast, low-cost
health checks.

https://claude.ai/code/session_01NGWLchcTP76rJHjiP5Ehte

* feat(stream-check): detect model-not-found errors with dedicated toast

Health check previously classified failures purely by HTTP status code,
which meant deprecated/invalid models showed up as a generic "Not found
(404)" error pointing users to check the Base URL — misleading when the
URL is fine and only the test model is wrong (e.g. gpt-5.1-codex after
it was retired).

Backend: add detect_error_category() that inspects 4xx response bodies
for model-not-found indicators (model_not_found, does not exist,
invalid model, not_found_error, etc.) and returns a "modelNotFound"
category. Thread the resolved test model through build_stream_check_result
so the failed result carries it in model_used. Add StreamCheckResult
.error_category field (serde-skipped when None).

Frontend: useStreamCheck branches on errorCategory === "modelNotFound"
before the HTTP-status fallback and renders a toast.error with the model
name and a description pointing to Model Test Config. Add i18n keys
(modelNotFound / modelNotFoundHint) for zh/en/ja.

Tests: unit-test detect_error_category against real OpenAI/Anthropic
error shapes, 5xx false-positive avoidance, and plain 401 auth errors.

https://claude.ai/code/session_01NGWLchcTP76rJHjiP5Ehte

* fix(stream-check): add missing error_category field in fallback

The error_category field was added to StreamCheckResult in this branch
but the fallback constructor in stream_check_all_providers was not
updated, which broke cargo build.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-15 15:25:32 +08:00
Dex Miller ef41e4da46 fix(proxy): strip hop-by-hop response headers per RFC 7230 (#2060) 2026-04-15 11:28:56 +08:00
wwminger 78198e262b fix(opencode): use json5 parser for trailing comma tolerance (#2023)
* fix(opencode): use json5 parser for trailing comma tolerance

OpenCode CLI writes opencode.json with trailing commas (valid JSONC),
but CC Switch parsed it with serde_json (strict JSON), causing errors
like 'trailing comma at line 35 column 3'.

Switch to json5::from_str which accepts both JSON and JSONC. The json5
crate is already a project dependency. Change error type from
AppError::json() to AppError::Config() since json5::Error differs from
serde_json::Error.

* style(opencode): apply rustfmt to satisfy cargo fmt --check

The previous commit's .map_err(...) chain exceeded rustfmt's default
100-char max_width, breaking CI's `cargo fmt --check`. Let rustfmt
wrap the closure body as a multi-line block. No behavior change.

---------

Co-authored-by: 18067889926 <ming.flute@outlook.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-04-15 11:11:48 +08:00
Jason 79eb773195 fix: remove unused mut to pass clippy -D warnings 2026-04-15 09:16:22 +08:00
Jason 6092a87b40 fix: preserve env vars when saving Google Official Gemini provider (#2087)
write_gemini_live() unconditionally cleared env_map for GoogleOfficial
auth type, discarding user-configured env vars (e.g. GEMINI_MODEL).
Remove the env_map.clear() call so the user's settings_config.env is
written as-is, and merge identical Packycode/Generic match arms.
2026-04-15 09:05:45 +08:00
Jason 689ca08409 feat: classify stream check errors with color-coded toasts
Distinguish between "provider rejects probe" (yellow warning) and
"genuinely broken" (red error) in health check results.

Backend: add AppError::HttpStatus variant to carry structured HTTP
status codes, populate http_status on error results, classify codes
into short labels (e.g. "Auth rejected (401)"), and truncate overly
long response bodies.

Frontend: route 401/403/400/429/5xx to toast.warning with localized
hints explaining the error may not indicate actual unusability; route
404/402/connection errors to toast.error. Add i18n keys for all three
locales (zh/en/ja).

Also deduplicate check_once by reusing build_stream_check_result.
2026-04-14 17:11:13 +08:00
Jason 8b851dc602 fix: auto-expand collapsed messages when search matches hidden content
When a search query matches text beyond the collapse point, the message
automatically expands to show the highlighted match. Also adds
aria-expanded for accessibility.
2026-04-14 16:50:22 +08:00
Jason 0383c13e66 perf: collapse long session messages to reduce text layout cost
Messages over 3000 characters are now truncated to 1500 characters by
default, with an expand/collapse toggle. This avoids expensive browser
text layout for large AI responses containing code or tool output.
2026-04-14 16:16:57 +08:00
Jason 7ae89e9106 perf: virtualize session message list for long conversations
Replace full DOM rendering with @tanstack/react-virtual to only render
visible messages (~25 DOM nodes instead of N). Wrap SessionMessageItem
in React.memo to prevent unnecessary re-renders on state changes.
2026-04-14 16:12:48 +08:00
Jason 04508801ef fix: handle root-level skill repos during installation
When a repo itself is a single skill (SKILL.md at repo root), the
discovery phase sets directory to the repo name, but after ZIP
extraction (which strips the root folder), no matching subdirectory
exists. Add a fallback to check if SKILL.md exists directly in the
extracted temp directory before reporting SKILL_DIR_NOT_FOUND.

Fixes installation of repos like zlbigger/Google-SEOs.skill.
2026-04-14 15:56:31 +08:00
Jason 57343432da fix: remove duplicate usage summary from app filter bar
The request count and total cost were displayed both in the app filter
bar and in the UsageSummaryCards below it. Remove the redundant inline
summary and its unused imports.
2026-04-14 15:47:55 +08:00
Jason 5e412d2c30 refactor: remove per-provider proxy config feature
Replace all remaining "代理服务/Proxy Service/プロキシサービス" references
in the local routing feature context with "路由服务/Routing Service/
ルーティングサービス". This covers service settings, status messages,
tooltips, field descriptions, and tab labels.

Global Proxy, HTTP proxy hints, and AI Agent references are unchanged.
2026-04-14 15:39:23 +08:00
Jason 36f2d6cccb docs: clarify global proxy hint about local routing across all locales 2026-04-14 15:26:08 +08:00
Jason 989c445828 docs: rename takeover docs to routing across all languages
Rename 4.2-takeover.md to 4.2-routing.md in zh/en/ja user manuals,
replacing all "接管/takeover" terminology with "路由/routing" to match
the rebranded feature name. Update README index links accordingly.
2026-04-14 15:15:39 +08:00
Jason 7ec92c32a5 rename: rebrand "Local Proxy Takeover" to "Local Routing" in all locales
Replace all user-facing references to "本地代理接管/Local Proxy/Takeover"
with "本地路由/Local Routing/ローカルルーティング" across zh/en/ja to
eliminate naming confusion with the separate "Global Proxy" feature.

Only i18n string values are changed; keys, code identifiers, and
database schema remain untouched.
2026-04-14 15:13:59 +08:00
Jason 4a0b5c3dec refactor: remove per-provider proxy config feature
The per-provider proxy configuration (meta.proxyConfig) is removed
because its scope is too narrow and covered by global proxy settings
and proxy takeover mode. Users can achieve the same result via the
global proxy panel.

Changes:
- Remove ProviderProxyConfig type (frontend TS + backend Rust)
- Remove ProviderAdvancedConfig proxy UI block, keep testConfig/pricingConfig
- Simplify http_client: delete build_proxy_url_from_config,
  build_client_for_provider, get_for_provider
- Simplify forwarder/stream_check/model_fetch to use global client
- Remove i18n keys (en/zh/ja)
- Fix pre-existing test bug in transform.rs (extra None arg)
2026-04-14 14:26:55 +08:00
Jason 449a171238 Add LemonData sponsor and update partner logo formats
Add new sponsor LemonData to partner section. Update Crazyrouter logo
from JPG to PNG format.
2026-04-14 11:15:25 +08:00
Jason c60f204808 Update partner logos and sync across languages
Synchronize Crazyrouter logo format and partner section updates across
EN/JA/ZH README files.
2026-04-14 10:58:36 +08:00
Jason d13a8d7353 fix(clippy): remove redundant closure in session ID parsing
Replace `|uid| parse_session_from_user_id(uid)` with direct
function reference to satisfy clippy::redundant_closure.
2026-04-14 10:34:58 +08:00
Jason 0739b60341 fix(proxy): reduce unnecessary Copilot premium interaction consumption
- Fix request classification: treat messages containing tool_result as
  agent continuation instead of user-initiated, preventing false premium
  charges on every tool call
- Add subagent detection via __SUBAGENT_MARKER__ and metadata._agent_
  fallback, setting x-interaction-type=conversation-subagent
- Add deterministic x-interaction-id derived from session ID to group
  requests into a single billing interaction
- Add orphan tool_result sanitization to prevent upstream API errors
  that could cause retries and duplicate billing
- Reorder pipeline: classify (on original body) → sanitize → merge →
  warmup, ensuring classification sees raw tool_result semantics
- Enable warmup downgrade by default with gpt-5-mini model
- Enhance session ID extraction priority chain for Copilot cache keys
- Detect infinite whitespace bug in streaming tool call arguments
2026-04-14 10:34:58 +08:00
Jason c01338ac33 fix(usage): remove unnecessary private IP restrictions from usage script
SSRF protection (private IP blocking, suspicious hostname detection) was
originally added for web-server threat models but is unnecessary for a
local desktop app where the user already has full network access. This
removal unblocks legitimate use cases like enterprise intranet APIs,
Docker container addresses, and self-hosted services.

Retained: HTTPS enforcement and same-origin checks which still provide
meaningful security (protecting API keys in transit and preventing
scripts from leaking keys to unrelated domains).
2026-04-14 10:33:41 +08:00
Jason 8c94c23c3c chore: update PIPELLM website URL to code.pipellm.ai 2026-04-14 10:33:41 +08:00
Jason d6fa611833 chore: remove X-Code API (XCodeAPI) provider preset and sponsorship 2026-04-14 10:33:41 +08:00
Jason 5c1b457520 fix(usage): sync request log time range with dashboard 1d/7d/30d selector
The RequestLogTable had a hardcoded 24-hour rolling window, ignoring the
dashboard's time range selector. Now it accepts a timeRange prop and
dynamically adjusts the query window, so users can view logs beyond just
the last day.
2026-04-14 10:33:41 +08:00
Jason 3c8f9d1287 feat(usage): improve pagination with first/last 3 pages and page jump input
Show first 3 and last 3 page buttons instead of just first/last, with
Set-based deduplication for clean edge merging. Add a page number input
field with Go button for direct page navigation.
2026-04-14 10:33:41 +08:00
Jason 420f4c8c23 fix(sessions): strip OpenClaw message_id suffix and allow 2-line titles
OpenClaw gateway injects `[message_id: UUID]` metadata at the end of
every message, wasting display space. Strip this suffix from both title
and summary fields.

Also change session title display from single-line truncate to
line-clamp-2, so longer titles (e.g. OpenClaw's timestamp-prefixed
messages) can show more meaningful content across two lines.
2026-04-14 10:33:41 +08:00
Jason ed269cc20e feat(sessions): extract meaningful titles for Codex and OpenClaw sessions
Previously Codex and OpenClaw sessions only showed the working directory
basename as the title, making it hard to distinguish sessions in the same
project. Now both providers extract the first real user message as the
session title, matching the existing Claude Code behavior.

- Codex: first user message → dir basename (skips AGENTS.md injection)
- OpenClaw: displayName (sessions.json) → first user message → dir basename
- Move TITLE_MAX_CHARS constant to shared utils.rs
- Use Option<&HashMap> for OpenClaw parse_session to avoid leaky abstraction
2026-04-14 10:33:41 +08:00
Jason 8669b408e9 fix(usage): deduplicate proxy and session log usage records
Extract message_id from Claude API responses (msg_xxx) and use it to
generate a shared request_id format (session:{msg_xxx}) between the
proxy logger and session log sync. When session sync encounters the
same request_id via INSERT OR IGNORE, it skips the duplicate.

- Add message_id field to TokenUsage, extracted from Claude responses
- Add TokenUsage::dedup_request_id() to generate shared request IDs
- Define SESSION_REQUEST_ID_PREFIX constant to eliminate magic strings
- Change proxy logger to INSERT OR REPLACE for richer-data-wins semantics
2026-04-14 10:33:41 +08:00
Jason bb7c83c214 feat(pricing): add ~50 new model pricing entries and fix outdated prices
Add pricing data for 4 new providers (Qwen, xAI Grok, Mistral, Cohere)
and supplement existing providers (MiniMax M2.5/M2.7, GLM-5/5.1,
Doubao Seed 2.0, MiMo V2 Pro, OpenAI o1/o3/codex-mini/gpt-5-mini/nano).

Fix outdated prices for deepseek-chat, deepseek-reasoner, and kimi-k2.5.
Fix display_name casing "Mimo" → "MiMo" for consistency.

Use prepared statement in seed_model_pricing() to avoid recompiling SQL
on each of ~130 INSERT iterations.

Schema migration v8→v9: DELETE + re-seed model_pricing for existing users.
2026-04-14 10:33:41 +08:00
Jason a514f27937 feat: block official provider switching during proxy takeover
Prevent users from switching to official providers (Anthropic/OpenAI/Google)
when proxy takeover is active, as using a proxy with official APIs may cause
account bans.

Defense-in-depth across 4 layers:
- Backend: ProviderService::switch(), hot_switch_provider(), switch_proxy_provider command
- Frontend: useProviderActions soft guard with error toast
- UI: ProviderActions button disabled with ShieldAlert icon
- Tray menu: official provider items disabled with  indicator

Also warns when enabling proxy takeover while current provider is official.
2026-04-14 10:33:41 +08:00
zerone0x 2937eb6766 fix(proxy): remove permissive CORS layer (#1915) 2026-04-13 12:26:19 +08:00
Dex Miller 313a6e3f6c [codex] Preserve cache_control when merging system prompts (#1946)
* Preserve cache hints when collapsing system prompts

Strict OpenAI-compatible chat backends still need fragmented Claude\nsystem prompts collapsed into one leading system message, but that\nnormalization should not silently drop stable cache hints. Preserve\nmessage-level cache_control when the merged system fragments agree,\nand fall back to omitting it when the fragments conflict.\n\nConstraint: Must keep single-system normalization for Nvidia/Qwen-style chat backends\nRejected: Always copy the first cache_control | could misrepresent conflicting cache boundaries\nConfidence: high\nScope-risk: narrow\nReversibility: clean\nDirective: If system prompt merging changes again, preserve cache_control whenever the merged metadata is unambiguous\nTested: cargo test proxy::providers::transform --manifest-path src-tauri/Cargo.toml\nNot-tested: End-to-end prompt caching behavior against cache-aware OpenAI-compatible upstreams\nRelated: #1881

* Tighten cache hint inheritance for merged system prompts

The follow-up cache hint fix still treated mixed present/absent\ncache_control across fragmented system prompts as inheritable, which\nexpanded the cache scope after prompt collapse. Treat that mix as\nambiguous and only preserve cache_control when every merged fragment\nexplicitly agrees on the same value.\n\nConstraint: Must preserve strict-backend system prompt normalization from #1942\nRejected: Inherit first present cache_control | widens cache scope when later fragments were intentionally uncached\nConfidence: high\nScope-risk: narrow\nReversibility: clean\nDirective: Any future merged-system cache hint logic should treat missing cache_control as semantically significant\nTested: cargo test proxy::providers::transform --manifest-path src-tauri/Cargo.toml\nNot-tested: End-to-end upstream caching behavior against cache-aware relays\nRelated: #1881\nRelated: #1946

* Keep cache-control merge regressions easy to review

Reflow the two long cache-control regression assertions in transform.rs so the neighboring merge cases stay rustfmt-aligned and easier to scan.

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

Constraint: Exclude Markdown design files from the commit while preserving the local code change
Rejected: Include docs in the same commit | user explicitly asked to leave Markdown files out
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Treat this as a readability-only test change; do not infer runtime behavior changes from it
Tested: cargo test --manifest-path src-tauri/Cargo.toml test_anthropic_to_openai_drops_ --lib
Tested: cargo check --manifest-path src-tauri/Cargo.toml --tests
Tested: pnpm format:check
Tested: pnpm typecheck
Not-tested: Full application integration and manual flows
2026-04-13 10:42:29 +08:00
Dex Miller 5566be2b4b Stop sending prompt cache keys on Claude chat conversions (#2003)
Responses conversions still use promptCacheKey, but chat completions now stay a pure shape transform. This keeps Claude -> chat requests aligned with providers that do not understand the field and keeps stream checks consistent with production behavior.

Constraint: Issue #1919 requires removing prompt_cache_key from Claude -> OpenAI Chat requests
Rejected: Add a runtime toggle for chat injection | requested behavior is unconditional removal
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep promptCacheKey limited to Claude -> Responses conversions unless a provider-specific contract is proven
Tested: cargo test anthropic_to_openai
Tested: cargo test anthropic_to_responses_with_cache_key
Tested: cargo test transform_claude_request_for_api_format_responses
Not-tested: Full src-tauri test suite
Related: #1919
2026-04-13 10:22:55 +08:00
v2v cfcf9452d0 添加应用级别窗口按钮,以改善linux wayland下系统窗口按钮失效的问题 (#1119)
* feat(window): add app-level window controls with settings toggle

Add a persistent settings toggle to enable app-level minimize/maximize/close controls and hide system decorations when enabled, providing a Wayland-friendly fallback for broken native titlebar interactions.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(window): restrict app-level window controls to Linux only and fix startup flicker

- Guard useAppWindowControls with isLinux() in App.tsx so it's always
  false on macOS/Windows even if persisted as true
- Wrap set_decorations call in lib.rs with #[cfg(target_os = "linux")]
- Only show the toggle in WindowSettings on Linux
- Skip setDecorations effect while settingsData is still loading to
  prevent the Rust-side decoration state from being overridden by the
  undefined->false fallback, which caused a brief title bar flicker

---------

Co-authored-by: wzk <wx13571681304@outlook.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-04-12 20:59:04 +08:00
Jason df01755328 docs(release-notes): sync user edits across en/zh/ja and add PR credits
- Simplify "ChatGPT Plus / Pro" → "ChatGPT" across all three languages
- Clarify Codex OAuth description to highlight Claude Code usage
- Add "requires manual activation" note for Token Plan and third-party balances
- Add Copilot API consumption caveat to the interaction optimizer section
- Update overview with skills.sh search, usage tracking, and onboarding mentions
- Add PR credits for TheRouter (@cmzz), Kaku/OMO Slim/Thinking fallback/auth tab (@yovinchen)
2026-04-10 23:44:06 +08:00
Jason 74b9f52d90 chore(release): bump version to v3.13.0 and sync changelog/release notes
Backfill post-draft changes into CHANGELOG and three-language release
notes (en/zh/ja): 16 new Added entries, 6 Fixed entries, 1 Docs entry,
and updated header stats (139 commits, 280 files, +31627/-3042).
2026-04-10 23:20:57 +08:00
Jason 8838317087 chore: simplify Codex provider preset name 2026-04-10 22:40:29 +08:00
Jason 4d570691e1 chore: add missing Shengsuanyun icon SVG file 2026-04-10 22:40:29 +08:00
Jason 337224546c feat: update PIPELLM preset with full config, add Codex support and icon
Update base URL to cc-api.pipellm.ai, add complete model definitions
(Opus/Sonnet/Haiku), add Codex preset with custom TOML config, add
pipellm PNG icon, and set apiKeyUrl to referral link.
2026-04-10 22:40:29 +08:00
Jason 7d21663e6d feat: add E-FlowCode provider preset across all five apps
Multi-protocol provider: Anthropic for Claude, OpenAI Responses for
Codex/OpenClaw, OpenAI for OpenCode, custom Gemini config. Includes
PNG icon via URL import and provider-specific settings like effortLevel,
enabledPlugins, and custom TOML config for Codex.
2026-04-10 22:40:29 +08:00
Jason 926e69b8c9 feat: add PIPELLM provider preset for Claude, OpenCode, and OpenClaw 2026-04-10 22:40:29 +08:00
Jason a03ad4f47f feat: add Shengsuanyun provider preset with partner promotion
Add Shengsuanyun (胜算云) as an aggregator partner across all five apps,
positioned right after official providers. Uses anthropic-messages
protocol for OpenCode/OpenClaw. Includes URL-based icon import (217KB
SVG), partner promotion i18n for zh/en/ja, and localized display name.
2026-04-10 22:40:29 +08:00
Jason c38bef517a fix: capitalize DDSHub provider display name 2026-04-10 22:40:29 +08:00
Jason 7526a031a7 chore: remove generate-icon-index.js to prevent accidental regeneration
The icon index (index.ts) is hand-curated with optimized SVG content
and custom name mappings. Running the generation script destroys these
optimizations. Remove the script entirely to eliminate the risk.
2026-04-10 22:40:29 +08:00
Jason 84bc98cf83 feat: add LionCCAPI provider preset with partner promotion
Add LionCCAPI as a third-party partner provider across all five apps
(Claude, Codex, Gemini, OpenCode, OpenClaw) with anthropic-messages
protocol for OpenCode and OpenClaw. Include partner promotion i18n
entries for zh/en/ja locales and lioncc icon.
2026-04-10 22:40:29 +08:00
Jason af679cda25 fix: map adaptive thinking to xhigh reasoning_effort instead of high
When thinking.type is "adaptive" (Claude's maximum thinking mode) and
output_config.effort is absent, resolve_reasoning_effort() incorrectly
mapped it to "high" instead of "xhigh" in OpenAI format conversions.
2026-04-10 22:40:29 +08:00
Jason a83bd90fa9 feat: replace x-code icon with high-res xcode icon via URL import
Replace the old low-res x-code inline SVG (7.6KB) with a new high-res
xcode.svg (286KB) loaded via Vite URL import. Update all three provider
preset files to reference the new icon name.
2026-04-10 22:40:29 +08:00
Jason 794795cad4 feat: support URL-based icons for large SVGs and raster images
Add dual rendering mode to the icon system: small optimized SVGs
continue to be inlined via dangerouslySetInnerHTML, while large SVGs
and raster images (png/jpg/webp/etc) use Vite URL imports rendered
as <img> tags. Added dds.svg (1.4MB) as the first URL-based icon.

Updated generate-icon-index.js to support multi-format icons with
a manual URL_ICONS control list. Updated ProviderIcon to handle
both inline SVG and URL-based rendering paths.
2026-04-10 22:40:29 +08:00
Jason eff85dc66d feat: add ddshub provider preset with partner promotion
Add ddshub as a third-party partner provider for Claude, including
SVG icon and i18n promotion text in zh/en/ja locales.
2026-04-10 22:40:29 +08:00
Dex Miller 3aef5217cb Restore first-class OMO Slim council support (#1981) (#1982)
cc-switch could already persist arbitrary OMO Slim agent keys and top-level fields, but the built-in metadata and UI copy still reflected the pre-council agent set. This made the upstream council feature look unsupported and pushed users toward manual JSON-only setup.

Promote council to a built-in OMO Slim agent, add copy that points top-level plugin settings at Other Fields, and lock the behavior with regression tests.

Constraint: oh-my-opencode-slim exposes council through both agents.council and top-level council config
Rejected: Add a dedicated council editor UI now | too much surface area for issue #1981
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep OMO Slim built-in agent metadata aligned with upstream agent additions before shipping UI support
Tested: pnpm exec vitest run tests/utils/omoConfig.test.ts tests/components/OmoFormFields.mergeCustomModelsIntoStore.test.ts
Tested: pnpm typecheck
Not-tested: End-to-end validation against a live oh-my-opencode-slim installation
Related: farion1231/cc-switch#1981
2026-04-10 22:36:32 +08:00
Dex Miller e4b58c7206 Let Kaku users launch sessions from their chosen terminal (#1954) (#1983)
Kaku is a WezTerm-derived macOS terminal, so reusing the existing WezTerm-compatible launch path keeps the change small while making it selectable in settings and session resume flows.

Constraint: Kaku support should stay macOS-only and avoid introducing a separate launcher model
Rejected: Treat Kaku as a silent WezTerm fallback | users could not explicitly choose it in settings
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep Kaku on the shared WezTerm-compatible launch path unless upstream drops the start-compatible CLI
Tested: pnpm typecheck; pnpm format:check; cargo check --manifest-path src-tauri/Cargo.toml; cargo fmt --manifest-path src-tauri/Cargo.toml --check; cargo test --manifest-path src-tauri/Cargo.toml --lib session_manager::terminal::tests
Not-tested: End-to-end launch against a locally installed Kaku.app
Related: #1954
2026-04-10 22:35:16 +08:00
Dex Miller 8c32610a7d Align Thinking fallback with main-model-only Claude mappings (#1984)
The Claude provider form reopened with an empty Thinking model after users saved only a main model. This updates model-state hydration to mirror the existing Haiku-style fallback semantics: read ANTHROPIC_REASONING_MODEL when present, otherwise display ANTHROPIC_MODEL, without writing a synthetic reasoning field back into config.

Constraint: Existing Haiku, Sonnet, and Opus selectors already rely on read-time fallback behavior
Rejected: Persist ANTHROPIC_REASONING_MODEL from ANTHROPIC_MODEL automatically | would diverge from Haiku behavior and silently rewrite saved config
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep Thinking fallback read-only unless all model-mapping fields are intentionally migrated to write-through semantics
Tested: pnpm typecheck
Tested: pnpm test:unit (1 unrelated pre-existing failure in tests/components/UnifiedSkillsPanel.test.tsx mock setup)
Not-tested: Manual add-provider reopen flow in the desktop UI
2026-04-10 22:34:18 +08:00
Dex Miller afdda27bd5 Restore auth tab localization in settings (#1985)
The settings page already routes the auth tab label through the shared i18n key, but the locale bundles never defined that key. Adding the missing entries fixes the label with the same simple pattern used by the other tabs.

Constraint: Keep the fix aligned with the existing settings-tab i18n flow
Rejected: Add component-level bilingual rendering | unnecessary for a missing translation key
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: When adding settings tabs, define locale keys in every bundled language before relying on fallback text
Tested: pnpm format:check; pnpm typecheck
Not-tested: Manual verification in the desktop UI
2026-04-10 22:24:25 +08:00
Max 7f1963ab49 feat(provider): add TheRouter presets for Claude, Codex, and Gemini (#1891)
* feat(provider): add TheRouter presets for Claude and Codex

* feat(provider): add TheRouter Gemini preset

---------

Co-authored-by: max <me19@qq.com>
2026-04-10 21:48:14 +08:00
Max 68df60bd4a feat(provider): add TheRouter presets for OpenCode and OpenClaw (#1892)
Co-authored-by: max <me19@qq.com>
2026-04-10 21:47:18 +08:00
Jason 489c7c75ea style: apply cargo fmt to schema migration code 2026-04-10 11:23:08 +08:00
Jason b85e449949 fix: guard migrations against missing tables and fix highlighted text assertion
- Make migrate_v6_to_v7 check skills table existence before ALTER
- Make migrate_v7_to_v8 check model_pricing table existence before UPDATE
- Fix SessionManagerPage test: use getByRole heading instead of getAllByText
  which breaks when highlightText splits text across <mark> elements
2026-04-10 11:20:47 +08:00
Jason c4458cf280 fix: update tests for InstalledSkill new fields and missing hook mocks
- Add content_hash and updated_at fields to 4 InstalledSkill literals in skill_sync.rs
- Add useCheckSkillUpdates and useUpdateSkill to UnifiedSkillsPanel test mock
- Suppress unused import warning in auto_launch.rs test module
2026-04-10 11:08:09 +08:00
Jason cc1530f997 docs: add working directory feature implementation plan
Design document for per-directory state switching (providers, MCP,
skills, prompts). Not yet implemented - saved for future reference.
2026-04-10 08:33:13 +08:00
Jason f9fb9085ac feat(session-manager): highlight search keywords in session titles and messages 2026-04-10 08:30:37 +08:00
Jason 308314baac fix(session-manager): improve session search accuracy and Chinese support
- Pre-filter sessions by provider before indexing to prevent result
  truncation when FlexSearch limit cuts across providers
- Switch tokenizer from "forward" to "full" for Chinese substring matching
- Preserve FlexSearch relevance ranking when search query is present
2026-04-10 00:14:50 +08:00
Jason 5ac6fb5315 feat(session-manager): extract meaningful titles for Claude sessions
Instead of showing directory basenames for all Claude sessions, extract
titles from JSONL content with a priority chain:
1. custom-title metadata (set via /rename in Claude Code)
2. First real user message (skipping /clear, /compact caveats)
3. Directory basename (fallback)
2026-04-09 23:18:06 +08:00
Jason a5a5207f74 style: fix prettier formatting in ProviderCard and ProviderForm 2026-04-09 21:13:32 +08:00
Jason accdacf94d docs: add DDS as sponsor in all README languages 2026-04-09 17:40:46 +08:00
Jason 97152c0f21 docs: add LionCC as sponsor in all README languages 2026-04-09 17:25:15 +08:00
Jason 129b1b45b0 docs: add Shengsuanyun as sponsor in all README languages 2026-04-09 17:13:19 +08:00
Jason fa4297f4d3 feat(common-config): show first-run notice dialog when editing providers
Display a one-time informational dialog explaining the Common Config
Snippet feature when users first open the add/edit provider form.
Uses a derived isOpen state from settings to avoid race conditions.
Adds commonConfigConfirmed flag to both TS and Rust settings types.
2026-04-09 16:49:14 +08:00
Jason ecb1fed5db feat(common-config): add guide info and empty state to common config editor
Add an informational alert block at the top of the common config snippet
editor modal (Claude/Codex/Gemini) explaining what the feature is, why
it exists, and how to use it. Also add an empty state prompt when no
snippet has been extracted yet, guiding users to click "Extract from
Editor". Includes i18n support for zh/en/ja.
2026-04-09 16:49:14 +08:00
Jason 521571c4ca fix(usage): only show CLI subscription quota for active provider
CLI-credential-based subscriptions (Claude/Codex/Gemini) read from a
single global credential file, so the quota always reflects the last
CLI login rather than a specific provider. Showing it on non-current
cards is misleading when multiple official subscriptions exist.

Apply the same isCurrent + autoQuery pattern already used by Copilot
and Codex OAuth: only query and render the quota footer when the
provider is the currently active one.
2026-04-09 16:49:14 +08:00
Jason bafe9e820d fix(notifications): remove duplicate toast when switching to proxy providers
When switching to Copilot/ChatGPT/OpenAI-format providers with the proxy
not running, two toasts appeared: a "proxy required" warning followed by
a "switch success" toast. Unify the post-switch toast logic so that all
provider types show a single success toast, and skip it entirely when
a proxy-required warning was already shown.
2026-04-09 16:49:14 +08:00
Jason 8669879ad0 feat(welcome): show first-run welcome dialog on fresh install
Introduce a one-time welcome dialog that explains CC Switch's workflow
to new users: how their existing config is preserved as a "default"
provider and how the bundled "Official" preset enables one-click revert.
Upgrade users are excluded by checking is_providers_empty() at startup
and never see the dialog.

Persistence follows the existing *_confirmed convention in AppSettings
(proxy/usage/stream_check/failover), stored in settings.json. The field
is only written when the user explicitly clicks the confirm button,
keeping its semantics strictly about user acknowledgement.

Also adds two reusable DAO helpers:
- Database::is_providers_empty for fresh-install detection, using
  EXISTS(SELECT 1) for a short-circuit query.
- Database::get_bool_flag accepting "true" | "1", with
  init_default_official_providers migrated to use it.

Dialog copy in zh/en/ja uses conditional phrasing so it stays
accurate whether or not existing live config was found.
2026-04-09 16:49:14 +08:00
Jason a058ebeafc docs(user-manual): update to v3.13.0 across en/zh/ja
Refresh the user manual to cover the v3.13.0 feature set so users can
discover and correctly use new functionality without cross-referencing
the release notes. All three language versions are updated
line-by-line symmetric.

Highlights:

- Lightweight Mode: tray-only running state added in 1.5-settings,
  with a comparison table against "Minimize to tray" and a new OAuth
  Auth Center (Beta) section
- Quota & Balance display restructured in 2.5-usage-query: split into
  auto-query (Claude/Codex/Gemini official, Copilot, Codex OAuth) vs
  manual-enable (Token Plan, third-party balances). Explains why
  manual enabling is required: the same API URL may expose both
  plan-quota and balance query modes
- Codex OAuth reverse proxy: full usage guide in 2.1-add with two
  entry points (Add Provider panel / OAuth Auth Center), Device Code
  login flow, token auto-refresh, multi-account management, quota
  display, common failures, and risk notice
- Full URL Endpoint Mode: new advanced option in 2.1-add
- Per-app tray submenus: 2.2-switch refactored to reflect the 5-app
  submenu structure and cross-link to Lightweight Mode
- Skills workflow: remove obsolete "automatic update not supported"
  section in 3.3-skills, add SHA-256 update detection, single/batch
  update, storage location switch, and skills.sh registry search
- Directory picker for Claude terminal resume in 3.4-sessions
- Usage stats in 4.4-usage: document the new CLI session log source
  (no proxy required) and per-app filtering for Claude/Codex/Gemini;
  note CNY->USD pricing corrections and MiniMax quota fixes
- Stream Check coverage extended to OpenCode/OpenClaw in 4.5-model-test
- New FAQs in 5.2-questions: quota visibility (auto vs manual),
  Codex OAuth risks and login flow, deep link wake in Lightweight Mode
- v3.13.0 highlights navigation block added to top-level README and
  each per-language README; version bumped to v3.13.0 / 2026-04-08
2026-04-09 16:49:14 +08:00
Jason 24bf3e810b feat(providers): auto-import OpenCode/OpenClaw live providers on startup
Drops the friction of clicking the manual "Import current config" button
for OpenCode and OpenClaw — they now match the auto-import behavior the
previous commit added for Claude/Codex/Gemini.

- New "1.6." startup block in lib.rs runs both
  import_opencode_providers_from_live and import_openclaw_providers_from_live
  on every launch. The functions are id-keyed and idempotent, so re-running
  just picks up new providers added externally to the live JSON files.
- Both functions now use a new Database::get_provider_ids() helper
  (HashSet<String> from a single SELECT id-only query) instead of
  get_all_providers(), avoiding the N+1 endpoint sub-queries that would
  otherwise hit the startup hot path on every launch.
2026-04-09 16:49:14 +08:00
Jason 5dbea70eb1 feat(providers): seed an official preset on startup for Claude/Codex/Gemini
New and existing users now see a built-in "Claude Official" / "OpenAI
Official" / "Google Official" entry in their provider list, so switching
back to the official endpoint is one click away instead of buried in the
README.

- New providers_seed.rs holds the three seeds (id, name, settings_config,
  icon) keyed by AppType, with a single is_official_seed_id() helper that
  scans OFFICIAL_SEEDS so the id list has one source of truth.
- Database::init_default_official_providers() runs once per database
  (gated by an official_providers_seeded setting flag), appends each seed
  to the end of the sort order, and never touches is_current.
- Startup also auto-imports the live config (settings.json / auth.json /
  .env) as a "default" provider before seeding, so users with an existing
  manual config don't lose it when they click the official preset.
- Database::has_non_official_seed_provider() replaces the get_all_providers
  call in import_default_config's gating check with an id-only scan,
  dropping the N+1 endpoint sub-queries from every startup.
2026-04-09 16:49:14 +08:00
Jason df5cb6d771 fix(usage): only auto-poll Copilot/ChatGPT quota for current provider
CopilotQuotaFooter and CodexOauthQuotaFooter called their hooks with a
hardcoded `enabled: true` plus an unconditional 5-minute refetch and
refetchOnWindowFocus, so non-current reverse-proxy cards kept polling
in violation of the project's "only the active provider auto-queries
on cooldown" rule. With multiple Copilot or ChatGPT accounts bound to
different cards, every card kept hitting its own usage endpoint.

Adopt the same pattern as useUsageQuery: keep `enabled` independent of
isCurrent so first-fetch and manual refresh still work, but gate
refetchInterval / refetchIntervalInBackground / refetchOnWindowFocus on
a new `autoQuery` option, and thread `isCurrent` from ProviderCard
through the footers into the hooks.
2026-04-09 16:49:14 +08:00
Jason 62fc1d9151 docs(release-notes): add v3.13.0 release notes (en/zh/ja)
Draft trilingual release notes for the upcoming v3.13.0 feature release
covering lightweight mode, quota and balance visibility, provider model
auto-fetch, Codex OAuth reverse proxy, tray per-app submenus, the
Hyper-based proxy forwarding stack, Skills discovery and batch updates,
session workflow upgrades, OpenCode/OpenClaw Stream Check coverage, the
full URL endpoint mode, and the Copilot interaction optimizer, plus the
accompanying Copilot auth, UTF-8 streaming boundary, system prompt
normalization, WebDAV password, and Linux startup fixes. Contributor
attribution follows industry convention using ASCII punctuation inside
PR references across all three locales, and the Codex OAuth reverse
proxy carries its own risk notice alongside a backward link to the
v3.12.3 Copilot risk notice.
2026-04-09 16:49:14 +08:00
Jason 87b1792eba docs(changelog): cover UTF-8 boundary and system prompt fixes
Document two additional Fixed entries for the Unreleased section after
rebasing onto the latest origin/main: the SSE streaming UTF-8 chunk
boundary fix that prevents U+FFFD replacement characters in multi-byte
output via the Copilot reverse proxy, and the OpenAI-compatible chat
transform fix that normalizes fragmented Claude system prompts into a
single leading system message for strict backends like Nvidia and
Qwen-style providers.
2026-04-09 16:49:14 +08:00
Jason 16ed738048 docs(changelog): add Unreleased section for upcoming release
Catalog all user-visible changes since v3.12.3: lightweight mode,
provider model auto-fetch, quota and balance visibility, skills
discovery and batch updates, session workflow upgrades, Codex OAuth
reverse proxy, OpenCode/OpenClaw stream check coverage, tray submenus,
Hyper-based proxy stack, provider key lifecycle, OAuth Auth Center UI
polish, and the accompanying Copilot auth, WebDAV, usage pricing,
Linux UI, and Skills i18n fixes.
2026-04-09 16:49:14 +08:00
Jason 50cbb3be12 refactor(stream-check): rename helper and drop phase markers
Post-merge cleanup from a simplify review pass on the phase 1-4
OpenCode/OpenClaw changes.

- Rename check_once_opencode_like → check_once_without_adapter. The
  new name directly expresses the intent (bypass get_adapter) instead
  of suggesting the function is somehow "like" OpenCode.
- Drop two "Phase 4 会美化错误消息" phase-history markers from
  docstrings; git history is the right place for them.
- Document in resolve_opencode_base_url why its default endpoints
  cannot be merged with ProviderType::default_endpoint(): the former
  encode AI SDK package defaults (e.g. @ai-sdk/openai ships with the
  /v1 suffix) while the latter encode proxy upstream hosts. They
  happen to overlap but are two independent truth sources.
2026-04-09 16:49:14 +08:00
Jason 5a61f01cfc feat(stream-check): handle edge cases for OpenCode/OpenClaw
Phase 4: polish the four remaining edge cases uncovered by Phase 1-3.

Custom headers passthrough
- check_claude_stream and check_gemini_stream now accept an optional
  extra_headers map which is appended after all built-in headers so it
  can override defaults (e.g. a custom User-Agent).
- OpenClaw reads from settings_config.headers.
- OpenCode reads from settings_config.options.headers.
- All pre-existing Claude/Codex/Gemini call sites pass None.

OpenClaw custom auth header (Longcat-style)
- When settings_config.authHeader is true, the provider expects a
  custom auth header whose name is only known to the OpenClaw gateway
  itself. Return a dedicated openclaw_auth_header_not_supported error
  so the user sees a meaningful explanation instead of a 401.

Bedrock error polish
- The bedrock-converse-stream (OpenClaw) and @ai-sdk/amazon-bedrock
  (OpenCode) branches now explain why (SigV4 signing) and point to
  the official consoles as an alternative test path.

OpenCode baseURL fallback
- resolve_opencode_base_url: when options.baseURL is empty and the
  npm package has a canonical default endpoint (@ai-sdk/openai,
  @ai-sdk/anthropic, @ai-sdk/google), fall back to that endpoint.
  @ai-sdk/openai-compatible still requires an explicit baseURL
  because its whole purpose is to point at a custom OpenAI clone.

Tests
- 8 new unit tests covering authHeader detection, baseURL resolution
  (explicit / fallback / error), and header map extraction on both
  apps. Total stream_check tests: 18 → 26.
2026-04-09 16:49:14 +08:00
Jason c02b8c58cb feat(stream-check): support OpenCode via npm package mapping
Phase 3: implement stream check for OpenCode providers by mapping the
`settings_config.npm` (AI SDK package name) to the corresponding API
protocol and delegating to the existing stream checkers.

Package mapping:
- @ai-sdk/openai-compatible → openai_chat
- @ai-sdk/openai            → openai_responses
- @ai-sdk/anthropic         → anthropic (ClaudeAuth strategy)
- @ai-sdk/google            → gemini (Google strategy)
- @ai-sdk/amazon-bedrock    → not supported (phase 4 message polish)

Note: OpenCode nests baseURL/apiKey under `settings_config.options`
(different from OpenClaw's root-level fields) and uses `baseURL` with
a capital L. Three new extractors (base_url / api_key / npm) encode
these shape differences so check_opencode_stream stays symmetric with
check_openclaw_stream.

Frontend: drop the remaining `appId !== "opencode"` filter in
ProviderList.tsx — both apps can now test providers.
2026-04-09 16:49:14 +08:00
Jason 7b3cfc683a feat(stream-check): support remaining 3 OpenClaw protocols
Phase 2: extend check_openclaw_stream to cover the full non-Bedrock
protocol set declared by openclawApiProtocols.

- openai-responses   → check_claude_stream(api_format="openai_responses")
- anthropic-messages → check_claude_stream(api_format="anthropic"),
  using AuthStrategy::ClaudeAuth (Bearer-only) so Claude relay
  services that reject a simultaneous x-api-key still work. Official
  Anthropic also accepts pure Bearer on /v1/messages.
- google-generative-ai → check_gemini_stream with AuthStrategy::Google.

bedrock-converse-stream still errors out but with a dedicated
openclaw_bedrock_not_supported key; its user-facing message will be
polished in phase 4.

Each protocol now builds its own AuthInfo inside the match arm because
the auth strategy is protocol-specific.
2026-04-09 16:49:13 +08:00
Jason 516fcdf6bf feat(stream-check): support OpenClaw openai-completions protocol
Phase 1 of extending stream health check to OpenCode/OpenClaw apps.

- Add early-dispatch path for OpenCode/OpenClaw in check_once so they
  bypass the adapter layer (which only knows Claude/Codex/Gemini
  settings_config shapes).
- Introduce check_openclaw_stream dispatcher that reads the `api` field
  from settings_config and routes to the existing check_claude_stream
  with api_format="openai_chat" for "openai-completions". Other
  protocols return localized errors to be lit up in phases 2 and 4.
- Extract build_stream_check_result helper to avoid duplicating the
  StreamCheckResult construction logic between the two code paths.
- Unblock the test button for OpenClaw providers in ProviderList.tsx.

OpenCode still returns the "not yet supported" error; it will be
enabled in phase 3.
2026-04-09 16:49:13 +08:00
Jason 34c6696baa fix(providers): disable test/usage buttons for Copilot and Codex OAuth cards
These OAuth providers ship with non-empty ANTHROPIC_BASE_URL, so the
isOfficialProvider() heuristic (which checks for a missing base URL)
returned false and left the health-check and usage-config buttons
enabled — inconsistent with other official OAuth cards. Extend the
button disabling logic at the call site with isCopilot / isCodexOauth,
matching the pattern already used for the quota footer branch above.
2026-04-09 16:49:13 +08:00
Jason 641c2fc2c7 chore(presets): bump Codex OAuth preset to GPT-5.4 family
Update the "Codex (ChatGPT Plus/Pro)" entry in Claude Code presets to
the new GPT-5.4 naming, which drops the legacy `-codex` suffix. Map the
Haiku tier to `gpt-5.4-mini` for lower-cost lightweight calls while
keeping Sonnet/Opus on the standard `gpt-5.4`.
2026-04-09 16:49:13 +08:00
Jason 64c068415e fix(linux): repair unresponsive UI on startup and full-screen panels
Linux users reported the window UI (including native title bar buttons)
couldn't receive clicks until manually maximizing and restoring the
window. Root causes: (1) Tauri webview did not acquire focus on startup
so first clicks were consumed by X11/Wayland click-to-activate
(Tauri #10746, wry #637); (2) GTK surface input region failed to
renegotiate on the visible:false + show() path under some
WebKitGTK/compositor combinations.

- Add linux_fix::nudge_main_window helper that performs set_focus plus
  a ±1px no-op resize after window show, with a 500ms reconciliation
  readback to compensate for dropped resize requests on slow
  compositors.
- Wire the helper into every window re-show path: normal startup,
  deeplink, single_instance, tray show_main, and lightweight exit.
- Set WEBKIT_DISABLE_COMPOSITING_MODE=1 at startup to avoid resize
  crashes and Wayland surface negotiation issues.
- Remove data-tauri-drag-region on Linux from App.tsx header and the
  shared FullScreenPanel (used by all provider/MCP/workspace forms)
  to avoid Tauri #13440 in Wayland sessions. Extract drag-region
  constants to src/lib/platform.ts for reuse.

All Rust changes are gated by #[cfg(target_os = "linux")]; frontend
changes preserve macOS/Windows behavior via runtime isLinux() checks.
Known limitation: tiling Wayland compositors ignore set_size, so
GDK_BACKEND=x11 remains the user-side workaround.
2026-04-09 16:49:13 +08:00
Jason 3a16462261 i18n(zh): unify Skills terminology in settings labels
Use "Skills" consistently in skillStorage title/description and
skillSync title to match the upstream Agent Skills wording and the
existing English label style used elsewhere on the settings page.
2026-04-09 16:49:13 +08:00
Jason 5288238694 refactor: tighten OAuth Auth Center copy, layout, and icon
- Trim Auth Center section descriptions to focus on user intent
- Remove duplicate outer heading on the auth settings tab
- Swap Sparkles glyph for CodexIcon on the ChatGPT card
- Generalize codexOauth.authStatus to a neutral "Auth status"
- Register settings.authCenter.* keys across zh/en/ja locales
2026-04-09 16:49:13 +08:00
Jason d164191bd1 feat: display subscription quota for Codex OAuth provider cards
Codex OAuth (ChatGPT Plus/Pro) providers previously fell through to the
default UsageFooter branch and showed no quota at all, while Copilot and
official Codex providers already had a wham/usage-backed quota footer.

This wires up the same five-hour / seven-day tier badges for codex_oauth
provider cards by reusing the existing query_codex_quota function and
SubscriptionQuotaFooter rendering, parameterized to keep both the CLI
credential path ("codex") and the cc-switch managed OAuth path
("codex_oauth") working from a single source of truth.

- Parameterize services::subscription::query_codex_quota with tool_label
  and expired_message; promote SubscriptionQuota constructors to
  pub(crate). The CLI path keeps its existing "codex" label and the
  "re-login with Codex CLI" message; the new path passes "codex_oauth"
  and a cc-switch-specific re-login hint.
- Add a new get_codex_oauth_quota Tauri command in commands/codex_oauth.rs
  that resolves the ChatGPT account (explicit binding > default account
  > not_found), pulls a valid access_token from CodexOAuthManager
  (auto-refresh handled), and delegates to query_codex_quota.
- Extract SubscriptionQuotaFooter's render body into a pure
  SubscriptionQuotaView component (props: quota / loading / refetch /
  appIdForExpiredHint / inline). The existing SubscriptionQuotaFooter
  becomes a thin wrapper with identical props and behavior, so
  CopilotQuotaFooter and the official Claude/Codex/Gemini paths are
  untouched. This avoids duplicating ~280 lines of five-state rendering.
- Add CodexOauthQuotaFooter, a 38-line wrapper that calls the new
  useCodexOauthQuota hook and forwards to SubscriptionQuotaView.
- ProviderCard inserts an isCodexOauth branch between isCopilot and
  isOfficial, keyed off PROVIDER_TYPES.CODEX_OAUTH (newly added to
  config/constants.ts to centralize the previously scattered string).
- Frontend hook caches per (codex_oauth, accountId) so multiple cards
  bound to the same ChatGPT account share one fetch via react-query
  dedup; cards bound to different accounts get independent fetches.
- No new i18n keys: existing subscription.fiveHour / sevenDay / expired /
  refresh / queryFailed / expiredHint are reused.
2026-04-09 16:49:13 +08:00
Jason 6a34253934 feat: add Codex OAuth (ChatGPT Plus/Pro) reverse proxy support
Adds a new managed OAuth provider that lets Claude Code route requests
through a user's ChatGPT Plus/Pro subscription via the chatgpt.com
backend-api/codex endpoint.

- CodexOAuthManager: OpenAI Device Code flow with multi-account support,
  JWT-based account identification, and automatic access_token refresh.
- Reuses the generic managed-auth command surface (auth_start_login,
  auth_poll_for_account, etc.) via provider dispatch in commands/auth.rs.
- ClaudeAdapter detects codex_oauth providers, forces the base URL to
  the ChatGPT backend, pins api_format to openai_responses, and emits
  Authorization + originator headers; the forwarder injects the dynamic
  access_token and ChatGPT-Account-Id per request.
- transform_responses gains an is_codex_oauth path that aligns the body
  with OpenAI's codex-rs ResponsesApiRequest contract: sets store:false,
  appends reasoning.encrypted_content to include, strips max_output_tokens
  / temperature / top_p, injects default instructions/tools/parallel_tool_calls,
  and forces stream:true. Covered by 9 new unit tests plus regression
  guards for the non-Codex path.
- Stream check reuses the same transform flag so detection matches the
  production request shape.
- Frontend adds CodexOAuthSection + useCodexOauth hook, integrates it
  into ClaudeFormFields / ProviderForm / AuthCenterPanel, ships a new
  "Codex (ChatGPT Plus/Pro)" preset, and adds zh/en/ja i18n strings.
2026-04-09 16:49:13 +08:00
Jason 697d0dd6e1 fix: resolve rustfmt formatting and clippy warnings
- Apply cargo fmt across schema.rs, session_usage*.rs, skill.rs, usage_stats.rs
- Fix clippy::for_kv_map: use messages.values() instead of (_, msg) pattern
- Suppress clippy::only_used_in_recursion for intentional recursive base path
- Fix prettier formatting in UsageScriptModal.tsx
2026-04-09 16:49:13 +08:00
Jason d33d63e4df feat: display Copilot premium interactions quota on provider card
Copilot usage query API was implemented but never surfaced on the main
provider list. Add CopilotQuotaFooter component that auto-detects
github_copilot providers and displays premium interaction utilization
inline, reusing the existing TierBadge UI from SubscriptionQuotaFooter.
2026-04-09 16:49:13 +08:00
Jason eb41e1052c fix: resolve session-based usage showing as unknown provider
Session logs use placeholder provider_ids (_session, _codex_session,
_gemini_session) that don't exist in the providers table, causing LEFT
JOIN to return NULL and display "Unknown". Add COALESCE fallback in all
4 usage queries to show meaningful names like "Claude (Session)".
2026-04-09 16:49:13 +08:00
Jason 687ffc237d feat: add per-app usage filtering (Claude/Codex/Gemini)
Add dashboard-level app type filter to usage statistics, replacing the
DataSourceBar with a more useful segmented control. All components
(summary cards, trend chart, provider stats, model stats, request logs)
now respond to the selected app filter.

Backend: add optional app_type parameter to get_usage_summary,
get_daily_trends, get_provider_stats, and get_model_stats queries.
Frontend: new AppTypeFilter type, updated query keys with appType
dimension for proper cache separation, and RequestLogTable local
filter auto-locks when dashboard filter is active.
2026-04-09 16:49:13 +08:00
Jason c0bcd19d44 fix: correct Gemini session sync accuracy issues
- Use UPSERT with WHERE guard instead of INSERT OR IGNORE, so updated
  token values on existing messages are properly synced without
  unnecessary rewrites of unchanged rows
- Include cached tokens in the skip-zero filter to stop silently
  discarding pure cache-hit records
- Restrict file collection to session-*.json to match documented scope
  and prevent ingesting non-session JSON files
2026-04-09 16:49:13 +08:00
Jason f5d7064d57 feat: add Gemini CLI session log usage tracking
Parse ~/.gemini/tmp/*/chats/session-*.json for precise per-message
token data (input/output/cached/thoughts). Integrates with existing
background sync and manual sync button alongside Claude and Codex.
2026-04-09 16:49:13 +08:00
Jason 8ad1bb7924 feat: add Codex model name normalization for consistent pricing lookup
Normalize model names from JSONL session logs before storage and pricing
lookup: lowercase, strip provider prefix (openai/), strip date suffixes
(-YYYY-MM-DD, -YYYYMMDD). Also clamp cached tokens to not exceed input.
2026-04-09 16:49:13 +08:00
Jason 2ea6a307fc feat: replace Codex estimated usage with precise JSONL session log parsing
Replace the 70/30 input/output token estimation from state_5.sqlite
with precise parsing of Codex CLI JSONL session logs (~/.codex/sessions/).

- Parse event_msg (token_count), turn_context, and session_meta events
- Compute exact input/output/cached token deltas from cumulative totals
- Reuse session_log_sync table for incremental file scanning
- Pre-filter lines with string contains() before JSON deserialization
- Add codex_session data source to DataSourceBar with i18n (zh/en/ja)
2026-04-09 16:49:13 +08:00
Jason 46051317da fix: correct model pricing CNY→USD and add missing models
- Fix 13 Chinese model prices that were stored as CNY values in USD
  fields (DeepSeek, Kimi, MiniMax, GLM, Doubao, Mimo)
- Add 12 new models: GPT-5.4/mini/nano, o3, o4-mini, GPT-4.1/mini/nano,
  Gemini 3.1 Pro/Flash Lite, Gemini 2.5 Flash Lite, Gemini 2.0 Flash,
  DeepSeek Chat/Reasoner, Kimi K2.5
- Merge pricing migration into existing v7→v8 to avoid extra version bump
2026-04-09 16:49:13 +08:00
Jason 154342ca00 feat: add session log usage tracking without proxy
Parse Claude Code JSONL session files (~/.claude/projects/) and Codex
SQLite database (~/.codex/state_5.sqlite) to track API usage without
requiring proxy interception. This enables usage statistics for users
who don't use the proxy feature.

Key changes:
- Add session_usage.rs: incremental JSONL parser with message.id dedup
- Add session_usage_codex.rs: import thread-level token data from Codex
- Add data_source column to proxy_request_logs (proxy/session_log/codex_db)
- Add session_log_sync table for tracking parse offsets
- Background sync every 60s + manual sync via DataSourceBar UI
- Schema migration v7→v8
- i18n support for zh/en/ja
2026-04-09 16:49:13 +08:00
Jason 2d581bce91 fix: hide empty description and fix broken skill link for skills.sh results
- Hide "暂无描述" text when skill has no description (skills.sh API
  doesn't return descriptions), show empty spacer instead
- Change skills.sh result link from guessed subdirectory path to repo
  root URL, since skillId doesn't reflect the actual nested path
2026-04-09 16:49:13 +08:00
Jason d51e774b20 feat: integrate skills.sh search for discovering skills from public registry
Add skills.sh API integration allowing users to search and install from
a catalog of 91K+ agent skills directly within CC Switch. The search
results are converted to DiscoverableSkill objects and reuse the existing
install pipeline. Includes fallback directory search for repos where
skills are nested in subdirectories, and filters out non-GitHub sources.
2026-04-09 16:49:13 +08:00
Jason 33f5d56afd fix: move skill settings above window settings in general tab 2026-04-09 16:49:13 +08:00
Jason 8cfce8abfc feat: add skill storage location toggle between CC Switch and ~/.agents/skills
Allow users to choose between storing skills in CC Switch's managed
directory (~/.cc-switch/skills/) or the Agent Skills open standard
directory (~/.agents/skills/). Includes migration logic that safely
moves files before updating settings, with confirmation dialog for
non-empty installations.
2026-04-09 16:49:13 +08:00
Jason 6d220b2528 fix: animate "Update All" button sliding in from the left of "Check Updates"
Use max-width + opacity CSS transition so the button smoothly expands
into view instead of popping in abruptly.
2026-04-09 16:49:13 +08:00
Jason b7e99014c9 feat: add "Update All" button for batch skill updates
Show an "Update All (N)" button next to "Check Updates" when updates
are available. Sequentially updates each skill and reports results.
2026-04-09 16:49:13 +08:00
Jason e3179ad9e4 feat: add skill update detection via SHA-256 content hashing
- Add content_hash and updated_at fields to skills table (DB migration v6→v7)
- Compute directory content hash on install/import/restore for version tracking
- Add check_updates command: downloads repos, compares hashes, returns update list
- Add update_skill command: backs up old files, re-downloads and replaces SSOT
- Backfill content_hash for existing skills on first update check
- Add "Check Updates" button and per-skill update badge/button in UnifiedSkillsPanel
- Add i18n keys for zh/en/ja
2026-04-09 16:49:13 +08:00
Jason 46488ecd93 fix: set default auto-query interval to 5min and fix number input clearing
- Change default autoQueryInterval from 0 (disabled) to 5 minutes for
  new usage scripts (Token Plan, Balance, and general templates)
- Fix controlled number inputs (timeout & interval) that couldn't be
  cleared: defer validation to onBlur so users can delete and retype
2026-04-09 16:49:13 +08:00
Jason 9192b6f988 fix: align usage display across provider cards by always rendering action buttons
Test and ConfigureUsage buttons are now always rendered instead of
conditionally, with a disabled style for providers that don't support
them (e.g. official subscriptions). This ensures consistent button
container width so the usage display aligns uniformly across all cards.
2026-04-09 16:49:13 +08:00
Jason f1fb3351c1 feat: add official balance query for DeepSeek, StepFun, SiliconFlow, OpenRouter, Novita AI
Add a new "Official" (官方) template type in the usage query panel that
queries account balance via each provider's native API endpoint.
Follows the same zero-script pattern as Token Plan — Rust handles the
HTTP call, frontend auto-detects the provider from base URL.

Supported providers and endpoints:
- DeepSeek: GET /user/balance
- StepFun: GET /v1/accounts
- SiliconFlow: GET /v1/user/info (cn + com)
- OpenRouter: GET /api/v1/credits
- Novita AI: GET /v3/user/balance
2026-04-09 16:49:13 +08:00
Satoru 24555275bb fix: add padding to toolbar container to prevent add button shadow clipping (#1951)
The orange add button's circular shadow appeared square because the
parent overflow-x-hidden container was clipping it at the edges.
2026-04-08 21:17:19 +08:00
Cod1ng dc4524e960 fix: handle UTF-8 multi-byte characters split across stream chunk boundaries (#1923)
* fix: handle UTF-8 multi-byte characters split across stream chunk boundaries

Replace String::from_utf8_lossy with append_utf8_safe in all four SSE
streaming paths. When a multi-byte UTF-8 character (e.g. Chinese, emoji)
is split across TCP chunk boundaries, from_utf8_lossy silently replaces
the incomplete halves with U+FFFD (�). This caused intermittent garbled
output in Claude Code when using the Copilot reverse proxy, because the
format conversion streams reconstruct SSE events from the corrupted buffer.

The new append_utf8_safe function preserves incomplete trailing bytes in
a remainder buffer and merges them with the next chunk before decoding,
ensuring characters are never split during UTF-8 conversion.

Fixes: intermittent U+FFFD replacement characters in Claude Code output
via Copilot proxy (not reproducible with direct Copilot connections like
opencode because they pass through raw bytes without format conversion).

* style: fix cargo fmt formatting in UTF-8 boundary tests

---------

Co-authored-by: Cod1ng <codingts@gmail.com>
Co-authored-by: encodets <encodets@gmail.com>
2026-04-08 10:02:35 +08:00
Dex Miller 34f16886a2 Normalize fragmented system prompts for strict chat backends (#1942)
Some OpenAI-compatible chat providers reject requests when Claude-side\nsystem fragments arrive as multiple system messages. Normalize the\nconverted OpenAI chat payload so system content becomes a single\nleading system message while leaving the rest of the message stream\nunchanged.\n\nConstraint: Nvidia/Qwen-style chat completions require a single leading system prompt\nRejected: Reorder system messages only | still leaves fragmented system prompts for strict backends\nConfidence: high\nScope-risk: narrow\nReversibility: clean\nDirective: Keep OpenAI chat system prompts normalized unless a provider explicitly requires fragmented system messages\nTested: cargo test proxy::providers::transform --manifest-path src-tauri/Cargo.toml\nNot-tested: Full end-to-end proxy capture against Nvidia upstream in this session\nRelated: #1881
2026-04-08 09:41:20 +08:00
Jason 602c5717b2 fix: gate parse_gemini_keychain_json with cfg(target_os = "macos")
The function is only called from read_gemini_credentials_from_keychain
which is already macOS-only. Without the gate, non-macOS CI fails with
dead-code error due to -D warnings.
2026-04-05 16:04:20 +08:00
Jason 4685e5b597 fix: invert MiniMax usage_count to match 0%→100% convention
usage_count is remaining quota (starts at total, decreases to 0),
not used count. Invert calculation so all providers consistently
show 0% when fresh and 100% when exhausted.
2026-04-05 13:41:52 +08:00
Jason ca6a187745 fix: correct MiniMax quota calculation and improve Token Plan display
- Fix MiniMax usage_count being treated as remaining (was inverted)
- Add MiniMax weekly quota tier extraction
- Remove Zhipu TIME_LIMIT (tools usage), keep only TOKENS_LIMIT
- Improve Kimi parsing with extract_reset_time and parse_f64 helpers
- Reuse TierBadge for Token Plan inline rendering
- Clean up unused i18n keys and debug println
2026-04-05 13:35:54 +08:00
Jason bfdac2a22a feat: add Token Plan quota query for Kimi, Zhipu GLM, and MiniMax
Add a new "Token Plan" template type in the usage query panel that
natively queries quota/usage from Chinese coding plan providers
(Kimi For Coding, Zhipu GLM, MiniMax) without requiring custom scripts.

- Rust backend: new coding_plan service with provider-specific API
  queries (Kimi /v1/usages, Zhipu /api/monitor/usage/quota/limit,
  MiniMax /coding_plan/remains) normalized into UsageResult
- Frontend: Token Plan template in UsageScriptModal with auto-detection
  of provider based on ANTHROPIC_BASE_URL pattern matching
- Follows the same pattern as GitHub Copilot template (dedicated API
  path in queryProviderUsage, no JS script needed)
2026-04-05 11:39:29 +08:00
Jason 8d38f0ee4f fix: allow provider switch without proxy, show warning instead of blocking
Remove the hard block that prevented switching to providers requiring
proxy (OpenAI format, Copilot, full URL mode) when the proxy is not
running. Now the switch proceeds with a warning toast. Also deduplicate
the proxy hint info toast so it doesn't appear alongside the warning.
2026-04-05 09:39:51 +08:00
Jason 159279bf44 feat: restore Copilot preset and auth center tab in settings
Re-enable GitHub Copilot provider preset and the OAuth auth center tab
that were temporarily hidden due to abnormal consumption rates. The
Copilot optimizer introduced in the previous commit addresses the
underlying issue.
2026-04-05 08:34:16 +08:00
Jason 2513687184 feat: add Copilot optimizer to reduce premium interaction consumption
Implement request classification, tool result merging, compact detection,
deterministic request IDs, and warmup downgrade for Copilot proxy.

The root cause was x-initiator being hardcoded to "user", making Copilot
count every API request (including tool callbacks and agent continuations)
as a separate premium interaction. The optimizer dynamically classifies
requests as "user" or "agent" based on message content analysis.

Closes #1813
2026-04-05 08:34:10 +08:00
Jason bcc14bd07d fix: remove hover push animation on provider cards
Keep usage display fixed in place and show action buttons with
a simple opacity fade instead of sliding in and pushing content.
2026-04-04 22:53:20 +08:00
Jason b31bf43e15 fix: hide usage config and health check buttons for official providers
Official providers use built-in subscription quota display instead of
custom usage scripts, and stream check is not applicable. Hide both
action buttons when isOfficialProvider is true.
2026-04-04 22:53:20 +08:00
Jason 98230c3970 feat: add official subscription quota display for Gemini
- Read Gemini OAuth credentials from macOS Keychain (gemini-cli-oauth)
  or legacy file (~/.gemini/oauth_creds.json)
- Auto-refresh expired access tokens using refresh_token (Google OAuth
  tokens expire in ~1h, unlike Claude/Codex)
- Two-step API: loadCodeAssist for project ID, then retrieveUserQuota
  for per-model quota buckets
- Classify models into Pro/Flash/Flash Lite categories, show min
  remaining fraction as utilization percentage
- Extend isOfficialProvider() for Gemini (no API key + no base URL)
- Parameterize expiredHint i18n key with tool name for all three apps
2026-04-04 22:53:20 +08:00
Jason 0200fe79ae feat: add official subscription quota display for Codex
Read Codex OAuth credentials from ~/.codex/auth.json (with macOS
Keychain fallback) and query chatgpt.com/backend-api/wham/usage to
show rate limit utilization on official Codex provider cards. Reuses
the same tier naming (five_hour, seven_day) for frontend i18n compat.
2026-04-04 22:53:20 +08:00
Jason b30f3c27ad feat: display official subscription quota on Claude provider cards
Read Claude OAuth credentials from macOS Keychain (with file fallback)
and query the Anthropic usage API to show quota utilization inline on
official provider cards. Includes compact countdown timer for reset
windows and hides the rarely-used seven_day_sonnet tier in inline mode.
2026-04-04 22:53:20 +08:00
Jason d9c0e4c452 docs: update user manual to v3.12.3 with new features coverage (en/zh/ja)
Add documentation for features introduced since v3.12.0:

New docs:
- 3.4 Session Manager: browse, search, resume, delete sessions
- 3.5 Workspace & Daily Memory: OpenClaw workspace file editing

Updated docs:
- Add Lightweight Mode to interface overview and FAQ
- Add tray submenu structure (providers grouped by app)
- Add API Format selection (Anthropic/OpenAI Chat/OpenAI Responses)
- Add Auto-Fetch Models button documentation
- Add Claude Common Config quick toggles
- Add Codex 1M Context Window toggle
- Add Skill backup/restore lifecycle
- Expand Backup Management panel documentation
- Update WebDAV sync to v2 protocol with dual-layer versioning
- Add OpenCode/OpenClaw to quickstart activation table
- Update README version to v3.12.3

All changes synced across en, zh, and ja locales.
2026-04-04 22:53:20 +08:00
Jason fe525891d4 feat(tray): collapse providers into submenus to prevent menu overflow
Each app type (Claude/Codex/Gemini) now renders as a submenu instead
of flat items, keeping the top-level tray menu compact regardless of
provider count. The submenu label shows the current provider name
(e.g. "Claude · OpenRouter") for at-a-glance visibility.
2026-04-04 22:53:20 +08:00
Jason 84998aa217 feat: differentiate fetch models error messages by failure type
Distinguish between missing API key, missing endpoint, auth failure,
unsupported provider (404/405), and timeout errors instead of showing
a generic failure toast for all cases.
2026-04-04 22:53:20 +08:00
Jason f200feebe4 fix(i18n): move fetchModels keys from copilot to providerForm namespace 2026-04-04 22:53:20 +08:00
Jason 5017002938 feat: add auto-fetch models from provider's /v1/models endpoint
Add ability to fetch available models from third-party aggregation
providers (SiliconFlow, OpenRouter, etc.) via OpenAI-compatible
GET /v1/models endpoint. Users can click "Fetch Models" button in
the provider form, then select models from a dropdown on each
model input field.

- Backend: new model_fetch service + Tauri command (Rust)
- Frontend: ModelInputWithFetch shared component
- Integrated into all 5 app forms (Claude/Codex/Gemini/OpenCode/OpenClaw)
- i18n support for zh/en/ja
2026-04-04 22:53:20 +08:00
Zhou Mengze de49f6fbbe fix(copilot): 修复 GitHub Copilot 认证和代理问题 (#1854)
* fix(copilot): 修复 GitHub Copilot 400 认证错误

问题:使用 GitHub Copilot provider 时报错 400 bad request

根因:与 copilot-api 项目对比发现多处差异

修复内容:
- 更新版本号 0.26.7 到 0.38.2
- 更新 API 版本 2025-04-01 到 2025-10-01
- 添加缺失的关键 headers
- 修正 openai-intent 值
- 添加动态 API endpoint 支持
- 同步更新 stream_check.rs headers

Closes #1777

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix: flush stream after write_all in hyper_client proxy

Add explicit flush() calls after write_all() for TLS stream, plain TCP
stream, and CONNECT tunnel requests to ensure buffered data is sent
immediately, preventing connection hangs in Copilot auth header flow.

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

* 修复登录时的剪切板在mac与linux端可能没复制验证码

* fix: flush stream after write_all in hyper_client proxy

Add explicit flush() calls after write_all() for TLS stream, plain TCP
stream, and CONNECT tunnel requests to ensure buffered data is sent
immediately, preventing connection hangs in Copilot auth header flow.

* 修复登录时的剪切板在mac与linux端可能没复制验证码

* 1、修复不同类型的个人商业等不同类型的copilot账号问题
2、将验证码复制改为异步操作

* fix: address PR review comments for Copilot auth                                                      │
│                                                                                                                      │
│ - Fix clipboard blocking by using spawn_blocking for arboard ops                                                     │
│ - Implement dynamic endpoint routing for enterprise Copilot users                                                    │
│ - Add api_endpoints cache cleanup in remove_account() and clear_auth()                                               │
│ - Change API endpoint log level from info to debug                                                                   │
│ - Fix clear_auth() to continue cleanup even if file deletion fails                                                   │
│ - Add 9 unit tests for Copilot detection and api_endpoints cachin

* style: fix cargo fmt formatting

* Fix Copilot dynamic endpoint handling

* fix: restore clear_auth() memory-first cleanup order and fix cache leaks

- Restore clear_auth() to clean memory state before deleting the storage
  file. The previous order (file deletion first) caused a regression where
  users could get stuck in a "cannot log out" state if file removal failed.

- Add missing copilot_models.clear() in clear_auth() — this cache was
  cleaned in remove_account() but never in the full clear path.

- Add endpoint_locks cleanup in both remove_account() and clear_auth()
  to prevent minor in-process memory leaks.

- Update test to assert the correct behavior: memory should be cleaned
  even when file deletion fails.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: 周梦泽 <mengze.zhou@dafeng-tech.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-04-04 22:52:23 +08:00
Jason Young e4fe2763cd chore(deps): bump actions/cache from 4 to 5 in ci.yml (#1860)
Sync ci.yml with release.yml after dependabot updates.
2026-04-03 16:24:55 +08:00
dependabot[bot] 3e1de466db chore(deps): bump actions/download-artifact from 4 to 8
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 4 to 8.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v4...v8)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '8'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-03 08:40:29 +08:00
dependabot[bot] 1abe474e75 chore(deps): bump actions/upload-artifact from 4 to 7
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 7.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4...v7)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-03 08:40:22 +08:00
dependabot[bot] 74d7e86b7a chore(deps): bump pnpm/action-setup from 2 to 5
Bumps [pnpm/action-setup](https://github.com/pnpm/action-setup) from 2 to 5.
- [Release notes](https://github.com/pnpm/action-setup/releases)
- [Commits](https://github.com/pnpm/action-setup/compare/v2...v5)

---
updated-dependencies:
- dependency-name: pnpm/action-setup
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-03 08:40:14 +08:00
dependabot[bot] b9297e42f5 chore(deps): bump actions/setup-node from 4 to 6
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 4 to 6.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-03 08:40:09 +08:00
dependabot[bot] 7de2db9ee8 chore(deps): bump actions/cache from 4 to 5
Bumps [actions/cache](https://github.com/actions/cache) from 4 to 5.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-03 08:32:17 +08:00
Jason 1b4c3cbcaa ci: add stale bot to auto-close inactive issues after 60 days
- Mark issues as stale after 60 days of inactivity
- Auto-close after 14 more days without response
- Bilingual (zh/en) stale and close messages
- Exempt security and performance labeled issues
- Runs daily at UTC 00:00, processes up to 100 issues per run
- Only affects issues, not pull requests
2026-04-03 00:01:13 +08:00
Jason 2b9b5b0bc3 docs: fix outdated README content and sync across languages
- Fix JA README macOS FAQ still claiming app is unsigned (now code-signed & notarized)
- Update SessionManager description from "Claude Code only" to "all supported apps" (EN/ZH/JA)
- Replace non-existent Flatpak download entry with self-build reference (EN/ZH/JA)
- Add OpenCode and OpenClaw filesystem paths to Flatpak minimal permissions
- Bump user manual version to v3.12.3
2026-04-02 22:38:42 +08:00
Jason 2af38a63b5 docs: point FUNDING.yml to Chinese README sponsor section 2026-04-02 22:22:12 +08:00
Jason 3388cba1dc docs: add sponsor call-to-action to READMEs and fix FUNDING.yml 2026-04-02 22:15:49 +08:00
Jason 8b44d9f54d fix(test): resolve HOME env race condition in parallel tests
- Use get_home_dir() instead of dirs::home_dir() in get_opencode_dir()
  and get_openclaw_dir() to respect CC_SWITCH_TEST_HOME override
- Add CC_SWITCH_TEST_HOME to all TempHome implementations
- Add #[serial] to all with_test_home tests to share serialization
  with other env-mutating tests
- Remove --test-threads=1 workaround from CI
2026-04-02 22:08:12 +08:00
Jason 8cdc07c860 ci: run cargo tests single-threaded to fix HOME env race 2026-04-02 20:38:31 +08:00
Jason 9a44245b73 style: use to_vec() instead of iter().copied().collect() 2026-04-02 17:46:14 +08:00
Jason 1b2885c335 style: use iter().copied() instead of iter().map(|s| *s) 2026-04-02 17:37:04 +08:00
Jason 447a1da7b2 ci: remove nonexistent pnpm lint step 2026-04-02 17:36:26 +08:00
Jason bfe238f301 style: fix formatting issues caught by CI 2026-04-02 17:32:33 +08:00
Jason 0c9a20ca68 ci: add PR and push quality checks workflow 2026-04-02 17:28:01 +08:00
Jason fee8577032 feat: hide GitHub Copilot provider preset and auth tab
Users reported that Copilot support causes excessively fast token
consumption. Temporarily hide the feature by adding a `hidden` field
to ProviderPreset interface and commenting out the auth center tab
in settings. Existing Copilot providers in DB still work via proxy.
2026-04-02 17:15:11 +08:00
Jason bae369b0dc docs: add SUPPORT.md and FUNDING.yml 2026-04-02 16:51:33 +08:00
Jason 6e2baaefa6 docs: add CONTRIBUTING.md, SECURITY.md, and CODE_OF_CONDUCT.md
Add three community health files with bilingual (EN/ZH) support:
- CODE_OF_CONDUCT.md: Contributor Covenant v2.1 with official Chinese translation
- SECURITY.md: security policy pointing to GitHub Security Advisories
- CONTRIBUTING.md: contribution guide with dev setup, code style, PR guidelines,
  i18n rules, and AI-assisted contribution policy
2026-04-02 16:26:26 +08:00
Jason 0001438586 ci: add emoji to issue template names 2026-04-02 15:44:01 +08:00
Jason 6e9e47ceb9 ci: add issue and PR templates with bilingual support
Add GitHub issue templates (bug report, feature request, documentation
issue, question) and PR template. All templates use bilingual format
(English + Chinese) to support the international community.
2026-04-02 15:40:06 +08:00
Bengbengbalabalabeng 14a3799f41 ci: add dependabot.yml config (#1829)
* ci: add dependabot.yml config

* chore: replace `rust` label with `backend` and fix missing newline

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-02 11:10:06 +08:00
ifNil 2f5bf1cea9 fix: avoid resetting usage query fields when editing extractor code (#1771) 2026-04-02 09:25:33 +08:00
Roy Li ba0b57f014 fix(claude): sync takeover live config during provider changes (#1828)
Keep Claude's live settings aligned with the latest provider state while proxy takeover is active, without breaking takeover fields or restore behavior.

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-01 22:21:59 +08:00
Dex Miller 3553d05bf0 feat(provider): additive provider key lifecycle & fix openclaw serializer panic (#1724)
* feat(provider): support additive provider key lifecycle management

Add `addToLive` parameter to add_provider so callers can opt out of
writing to the live config (e.g. when duplicating an inactive provider).
Add `originalId` parameter to update_provider to support provider key
renames — the old key is removed from live config before the new one
is written.

Frontend: ProviderForm now exposes provider-key input for openclaw app
type, and EditProviderDialog forwards originalId on save. Deep-link
import passes addToLive=true to preserve existing behavior.

* test(provider): add integration tests for additive provider key flows

Cover openclaw provider duplication scenario to verify that a generated
provider key is assigned automatically. Add MSW handlers for
get_openclaw_live_provider_ids, get_openclaw_default_model,
scan_openclaw_config_health, and check_env_conflicts endpoints.
Update EditProviderDialog mock to pass originalId alongside provider.

* fix(openclaw): replace json-five serializer to prevent panic on empty collections

json-five 0.3.1 panics when pretty-printing nested empty maps/arrays.
Switch value_to_rt_value() to serde_json::to_string_pretty() which
produces valid JSON5 output without the panic. Add regression test for
removing the last provider (empty providers map).

* style: apply rustfmt formatting to proxy and provider modules

Reformat chained .header() calls in ClaudeAdapter and StreamCheckService
for consistent alignment. Reorder imports alphabetically in stream_check.
Fix trailing whitespace in transform.rs and merge import lines in
provider/mod.rs.

* style: fix clippy warnings in live.rs and tray.rs

* refactor(provider): simplify live_config_managed and deduplicate tolerant live config checks

- Change live_config_managed from Option<bool> to bool with #[serde(default)]
- Extract repeated tolerant live config query into check_live_config_exists helper
- Fix duplicate key generation to also check live-only provider IDs
- Fix updateProvider test to match new { provider, originalId } call signature
- Add streaming_responses test type annotation for compiler inference

* fix(provider): distinguish legacy providers from db-only when tolerating live config errors

Change `ProviderMeta.live_config_managed` from `bool` to `Option<bool>`
to introduce a three-state semantic:
- `Some(true)`: provider has been written to live config
- `Some(false)`: explicitly db-only, never written to live config
- `None`: legacy data or unknown state (pre-existing providers)

Previously, legacy providers defaulted to `live_config_managed = false`
via `#[serde(default)]`, which silently swallowed live config parse
errors. This could mask genuine configuration issues for providers that
had actually been synced to live config before the field was introduced.

Now, only providers with an explicit `Some(false)` marker tolerate parse
errors; legacy `None` providers surface errors as before, preserving
safety for already-managed configurations.

Also wrap the `ensureQueryData` call for live provider IDs during
duplication in a try/catch so that a malformed config file shows a
user-facing toast instead of silently failing.

Add tests for both the legacy error propagation path and the frontend
duplication failure scenario.

* refactor(provider): unify OMO variant updates with atomic file-then-db writes and rollback

Consolidate the duplicated omo/omo-slim update branches into a single
match on the variant. Write the OMO config file from the in-memory
provider state *before* persisting to the database, so a file-write or
plugin-sync failure leaves the database unchanged. If `add_plugin`
fails after the config file is already written, roll back to the
previous on-disk contents via snapshot/restore.

Also:
- `sync_all_providers_to_live` now skips db-only providers
  (`live_config_managed == Some(false)`) instead of attempting to write
  them to live config.
- `import_{opencode,openclaw}_providers_from_live` mark imported
  providers as `live_config_managed: Some(true)` so they are correctly
  recognized during subsequent syncs.
- Extract OmoService helpers: `profile_data_from_provider`,
  `snapshot_config_file`, `restore_config_file`, `write_profile_config`,
  and the new public `write_provider_config_to_file`.
- Add 9 new tests covering sync skip, legacy restore, import marking,
  OMO persistence, file-write failure, and plugin-sync rollback.

* fix(provider): fix additive provider delete/switch regressions and redundancy

- fix(delete): replace stale live_config_managed flag check with
  check_live_config_exists so providers written to live before the
  flag-flip logic was introduced are still cleaned up on delete
- fix(switch): make write_live_with_common_config return Err instead of
  silently returning Ok when config structure is invalid, preventing
  live_config_managed from being incorrectly flipped to true
- fix(update): block provider key rename for OMO/OMO Slim categories to
  prevent orphaned current-state markers breaking OMO file syncs
- fix(switch): flip live_config_managed to true after successful live
  write for DB-only additive providers so sync_all_providers_to_live
  includes them on future syncs; roll back live write if DB update fails
- refactor(delete): merge symmetric OMO/OMO-Slim blocks into single
  match-on-variant path; hoist DB read to top of additive branch
- refactor(remove_from_live_config): merge OMO/OMO-Slim if/else-if
  into single match-on-variant path
- refactor(switch_normal): merge two OMO/OMO-Slim if blocks into one
  OpenCode guard with (enable, disable) variant pair
- fix(update): remove redundant duplicate return Ok(true) after OMO
  current-state write

* fix(test): use preferred_filename after OMO field rename

The merge from main brought in #1746 which renamed
OmoVariant.filename → preferred_filename, but the test helper
omo_config_path() was not updated, breaking compilation of all
new provider tests.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-01 21:16:41 +08:00
Bengbengbalabalabeng 72f3610ac0 docs(readme): use dynamic badges (#1806) 2026-04-01 16:09:19 +08:00
Jason 854266e3c4 docs: add ChefShop AI sponsor to all README versions
Add ChefShop AI as a new sponsor with logo and descriptions in Chinese, English, and Japanese README files.
2026-03-31 23:07:51 +08:00
Jason af8f907467 fix(proxy): serialize per-app provider switches to prevent state corruption
Concurrent failover switches for the same app could cause is_current,
local settings, and Live backup to point at different providers.

- Add SwitchLockManager with per-app mutexes (different apps still parallel)
- Unify scattered switch logic into ProxyService::hot_switch_provider
- Fix TOCTOU in set_current_provider via mutate_settings
- Add logical_target_changed to skip redundant UI refreshes
- Add tests for serialization and restore-waits-for-switch scenarios
2026-03-31 22:46:42 +08:00
Dex Miller 6a083cdd1c fix(omo): adapt to oh-my-openagent rename with backward compatibility (#1746)
* fix(omo): adapt to oh-my-openagent rename with backward compatibility

Closes https://github.com/farion1231/cc-switch/issues/1733

* fix(omo): prioritize oh-my-openagent config over legacy oh-my-opencode
2026-03-31 16:32:49 +08:00
Dex Miller c68476d0ea fix(provider): show persistent config highlight for additive-mode providers (#1747)
* fix(provider): show persistent config highlight for additive-mode providers

Closes https://github.com/farion1231/cc-switch/issues/1692

* fix(provider): limit persistent config highlight to opencode only
2026-03-31 16:21:04 +08:00
Dex Miller 96a0a37331 feat(terminal): add directory picker before launching Claude terminal (#1752)
* Add directory picker before launching Claude terminal

* fix(terminal): preserve cwd path and strip Windows verbatim prefix

- Stop trimming non-empty paths so directories with leading/trailing
  spaces on Unix are handled correctly
- Strip \\?\ extended-length prefix from canonicalized paths on Windows
  to prevent batch script cd failures

* fix(terminal): restore UNC paths when stripping Windows verbatim prefix

Handle \\?\UNC\server\share form separately from regular \\?\ prefix,
converting it back to \\server\share so network/WSL directory paths
remain valid in batch cd commands.

* fix(terminal): use pushd for UNC paths in Windows batch launcher

`cmd.exe` cannot set a UNC path (e.g. `\\wsl$\...`) as the current
directory via `cd /d`; it errors with "CMD does not support UNC paths
as current directories". Switch to `pushd` which temporarily maps the
UNC share to a drive letter.

Rename `build_windows_cd_command` → `build_windows_cwd_command` to
reflect the broader semantics. Extract `build_windows_cwd_command_str`
and `is_windows_unc_path` helpers for testability, and add unit tests
covering drive paths, UNC paths, and batch metacharacter escaping.

Also fix minor style issues: sort mod declarations alphabetically,
add missing EOF newline in lightweight.rs, add explicit type annotation
in streaming_responses test, and reformat tray menu builder chain.
2026-03-31 15:10:08 +08:00
Alexlangl 8e2ffbc845 feat: add bulk delete for session manager (#1693)
* feat: add bulk delete for session manager

* fix: address batch delete review issues

* fix: keep session list in sync after batch delete
2026-03-30 22:15:57 +08:00
Alexlangl 4f7ea76347 fix: preserve WebDAV password display and validate MKCOL 405 (#1685)
* fix: preserve WebDAV password display and validate MKCOL 405

* fix: scope WebDAV password preservation to post-save refresh
2026-03-30 22:13:21 +08:00
Dex Miller 67e074c0a7 refactor(proxy): transparent header forwarding via hyper client (#1714)
* style(frontend): reformat provider forms, constants and hooks

Apply prettier formatting across 5 frontend files. No logic changes.

Changed files:
- AddProviderDialog.tsx: reformat generic type annotation and callback
- ClaudeFormFields.tsx: consolidate multi-line useState and Collapsible props
- CodexConfigSections.tsx: expand single-line React imports to multi-line,
  collapse removeCodexTopLevelField() call
- constants.ts: merge TemplateType into single line
- useSkills.ts: expand single-line TanStack Query imports to multi-line,
  reformat uninstallSkill mutationFn chain

* deps(proxy): add hyper ecosystem crates and manual decompression libs

reqwest internally normalizes all header names to lowercase and does not
preserve insertion order, causing proxied requests to differ from the
original client requests. To achieve transparent header forwarding with
original casing and order, introduce lower-level hyper HTTP client libs.

New dependencies:
- hyper-util 0.1: TokioExecutor + legacy Client with
  preserve_header_case support for HTTP/1.1
- hyper-rustls 0.27: rustls-based TLS connector for hyper
- http 1 / http-body 1 / http-body-util 0.1: HTTP type crates for
  hyper 1.x request/response construction
- flate2 1: manual gzip/deflate decompression (replaces reqwest auto)
- brotli 7: manual brotli decompression

Changed dependencies:
- serde_json: enable preserve_order feature to keep JSON field order
- reqwest: drop gzip feature to prevent reqwest from overriding the
  client's original accept-encoding header

* refactor(proxy): use hyper client for header-case preserving forwarding

Previously the proxy used reqwest for all upstream requests. reqwest
normalizes header names to lowercase and reorders them internally,
making proxied requests distinguishable from direct CLI requests.
Some upstream providers are sensitive to these differences.

This commit replaces reqwest with a hyper-based HTTP client on the
default (non-proxy) path, achieving wire-level header fidelity:

Server layer (server.rs):
- Replace axum::serve with a manual hyper HTTP/1.1 accept loop
- Enable preserve_header_case(true) so incoming header casing is
  captured in a HeaderCaseMap extension on each request
- Bridge hyper requests to axum Router via tower::Service

New hyper client module (hyper_client.rs):
- Lazy-initialized hyper-util Client with preserve_header_case
- ProxyResponse enum wrapping both hyper::Response and reqwest::Response
  behind a unified interface (status, headers, bytes, bytes_stream)
- send_request() builds requests with ordered HeaderMap + case map

Request handlers (handlers.rs):
- Switch from (HeaderMap, Json<Value>) extractors to raw
  axum::extract::Request to preserve Extensions (containing the
  HeaderCaseMap from the accept loop)
- Pass extensions through the forwarding chain

Forwarder (forwarder.rs):
- Remove HEADER_BLACKLIST array; replace with ordered header iteration
  that preserves original header sequence and casing
- Build ordered_headers by iterating client headers, skipping only
  auth/host/content-length, and inserting auth headers at the original
  authorization position to maintain order
- Handle anthropic-beta (ensure claude-code-20250219 tag) and
  anthropic-version (passthrough or default) inline during iteration
- Remove should_force_identity_encoding() — accept-encoding is now
  transparently forwarded to upstream
- Use hyper client by default; fall back to reqwest only when an
  HTTP/SOCKS5 proxy tunnel is configured

Provider adapters (adapter.rs, claude.rs, codex.rs, gemini.rs):
- Replace add_auth_headers(RequestBuilder) -> RequestBuilder with
  get_auth_headers(AuthInfo) -> Vec<(HeaderName, HeaderValue)>
- Adapters now return header pairs instead of mutating a reqwest builder
- Claude adapter: merge Anthropic/ClaudeAuth/Bearer into single branch;
  move Copilot fingerprint headers into get_auth_headers

Response processing (response_processor.rs):
- Add manual decompression (gzip/deflate/brotli via flate2 + brotli)
  for non-streaming responses, since reqwest auto-decompression is now
  disabled to allow accept-encoding passthrough
- Add compressed-SSE warning log for streaming responses
- Accept ProxyResponse instead of reqwest::Response

HTTP client (http_client.rs):
- Disable reqwest auto-decompression (.no_gzip/.no_brotli/.no_deflate)
  on both global and per-provider clients

Streaming adapters (streaming.rs, streaming_responses.rs):
- Generalize stream error type from reqwest::Error to generic E: Error

Misc:
- log_codes.rs: add SRV-005 (ACCEPT_ERR) and SRV-006 (CONN_ERR)
- stream_check.rs: reformat copilot header lines
- transform.rs: fix trailing whitespace alignment

* fix(lint): resolve 35 clippy warnings across Rust codebase

Fix all clippy warnings reported by `cargo clippy --lib`:

- codex_config.rs: fix doc_overindented_list_items (3 spaces -> 2)
- commands/copilot.rs: inline format args in 2 log::error! calls
- commands/provider.rs: inline format args in 3 map_err closures
- proxy/hyper_client.rs: inline format arg in log::debug! call
- proxy/providers/copilot_auth.rs: inline format args in 16 locations
  (log macros, format! in headers, error constructors)
- proxy/thinking_optimizer.rs: inline format args in 2 log::info! calls
- services/skill.rs: inline format args in log::debug! call
- services/webdav_sync.rs: inline format args in 6 format! calls
  (version compat messages, download limit messages)
- services/webdav_sync/archive.rs: inline format args in 2 format! calls
- session_manager/providers/opencode.rs: inline format args in
  source_path format!

All fixes use the clippy::uninlined_format_args suggestion pattern:
  format!("msg: {}", var)  ->  format!("msg: {var}")

* deps(proxy): add raw HTTP write and native TLS cert dependencies

Add crates required for the raw TCP/TLS write path that bypasses
hyper's header encoder to preserve original header name casing:

- httparse: parse raw TCP peek bytes to capture header casings
- tokio-rustls + rustls: direct TLS connections for raw write path
- webpki-roots: Mozilla CA bundle baseline
- rustls-native-certs: load system keychain CAs (trusts proxy MITM
  certificates from Clash, mitmproxy, etc.)

* fix(proxy): address code review feedback on response handling

Fixes from PR #1714 code review:

- Extract `read_decoded_body()` and `strip_entity_headers_for_rebuilt_body()`
  in response_processor to properly clean content-encoding/content-length
  headers after decompression
- Reuse `read_decoded_body()` in handlers.rs for Claude transform path,
  ensuring compressed responses are decoded before format conversion
- Make `build_proxy_url_from_config()` public so forwarder can pass proxy
  URL to the hyper raw write path
- Add `has_system_proxy_env()` utility with test coverage
- Add 50ms backoff after accept() failures in server.rs to prevent
  tight-loop CPU spin on transient socket errors

* feat(proxy): implement raw TCP/TLS write with HTTP CONNECT tunnel

Rewrite hyper_client with a two-tier strategy for header case preservation:

Primary path (raw write):
- Peek raw TCP bytes in server.rs to capture OriginalHeaderCases before
  hyper lowercases them
- Build raw HTTP/1.1 request bytes with exact original header name casing
- Write directly to TLS stream, then use WriteFilter to let hyper parse
  the response while discarding its duplicate request writes
- Support HTTP CONNECT tunneling through upstream proxies, so header case
  is preserved even when a proxy (Clash, V2Ray) is configured

Fallback path (hyper-util Client):
- Used when OriginalHeaderCases is empty or raw write fails
- Configured with title_case_headers(true) for best-effort casing

TLS improvements:
- Load native system certificates alongside webpki roots so proxy MITM
  CAs (installed in system keychain) are trusted through CONNECT tunnels

Key types added:
- OriginalHeaderCases: maps lowercase name → original wire-casing bytes
- WriteFilter<S>: AsyncRead+AsyncWrite wrapper that discards writes
- connect_via_proxy(): HTTP CONNECT tunnel establishment
- ExtensionDebugMarker: diagnostic marker for extension chain debugging

* refactor(proxy): route requests through hyper with proxy-aware forwarding

Rework forwarder request dispatch to always prefer the hyper raw write
path (header case preservation) over reqwest:

Request routing:
- HTTP/HTTPS proxy: hyper raw write through CONNECT tunnel (case preserved)
- SOCKS5 proxy: reqwest fallback (CONNECT not supported for SOCKS5)
- No proxy: hyper raw write direct connection

Header handling improvements:
- Replace host header in-place at original position instead of
  skip-and-append, preserving client's header ordering
- Preserve client's original accept-encoding for transparent passthrough;
  only force identity encoding when transform path needs decompression
- Add should_force_identity_encoding() to centralize the decision
- Remove hardcoded 'br, gzip, deflate' override that masked client values

Proxy URL resolution (priority order):
1. Provider-specific proxy config (if enabled)
2. Global proxy URL configured in CC Switch
3. Direct connection (no proxy)

* chore(proxy): remove dead code, redundant tests and debug scaffolding

- Inline should_force_identity_encoding() (was just `needs_transform`)
  and delete its 5 test cases
- Remove ExtensionDebugMarker diagnostic type
- Remove unused has_system_proxy_env() and its test
- Remove strip_entity_headers test
- Simplify hyper path: remove redundant is_socks_proxy ternary
- Update hyper_client module doc to reflect CONNECT tunnel support

* fix(proxy): block direct-connect fallback and complete CONNECT tunnel support

* feat(hooks): improve proxy requirement warnings with specific reasons

- Remove redundant OpenAI format hint toast messages
- Add detailed reason detection for proxy requirements (OpenAI Chat, OpenAI Responses, full URL mode)
- Update i18n files with new reason-specific keys

* style(*): format code with prettier

- Remove extra whitespace in http_client.rs
- Fix formatting issues in useProviderActions.ts

* fix(proxy): post-merge fixes for forward return type and clippy warnings

- Restore forward() return type to (ProxyResponse, Option<String>)
  to pass claude_api_format through to callers
- Inline format args in log::warn! macro (clippy::uninlined_format_args)
- Suppress too_many_arguments for check_claude_stream

* refactor(proxy): preserve original header wire order and add non-streaming body timeout

- Rewrite build_raw_request to emit headers in original
  client-sent sequence instead of hash-map order
- Remove unused OriginalHeaderCases::get_all method
- Add body_timeout to read_decoded_body to prevent
  requests hanging when upstream stalls after headers
2026-03-29 20:26:15 +08:00
ruokeqx b1c7fe5563 feat: add lightweight mode (#1739) 2026-03-29 18:35:23 +08:00
makoMakoGo 210bff96c2 fix(env): detect bun global bin paths in CLI scan (#1742) 2026-03-29 15:52:37 +08:00
makoMakoGo 3b33e6921b fix: correct opencode kimi-for-coding preset (#1738) 2026-03-29 10:31:23 +08:00
Zhou Mengze 8d5f72757e fix: 修复 Copilot 作为 Claude 时 OpenAI 模型的 Responses 分流 (#1735)
* fix: route copilot claude openai models to responses

* fix(i18n): add copilotProxyHint translation key for all locales

The copilotProxyHint message was using inline defaultValue with Chinese
text, which would show Chinese to English and Japanese users. Added
proper translation keys in zh/en/ja locale files and removed the
hardcoded defaultValue fallback.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-03-29 10:29:54 +08:00
Dex Miller 8cae7b7b73 feat(proxy): add full URL mode and refactor endpoint rewriting (#1561)
* feat(proxy): add full URL mode and refactor endpoint rewriting

- Add `isFullUrl` provider meta to treat base_url as complete API endpoint
- Remove hardcoded `?beta=true` from Claude adapter, pass through from client
- Refactor forwarder endpoint rewriting with proper query string handling
- Block provider switching when proxy is required but not running
- Add full URL toggle UI in endpoint field with i18n (zh/en/ja)

* refactor(proxy): remove beta query handling

* fix(proxy): strip beta query when rewriting Claude endpoints

* feat(codex): complete full URL support

* refactor(ui): refine full URL endpoint hint
2026-03-28 15:52:02 +08:00
tgbdhs eaf83f4fbe fix(proxy): parse SSE fields with optional spaces in streaming handlers (#1664)
* fix(proxy): handle SSE fields with or without spaces

* refactor(proxy): deduplicate SSE field parsing
2026-03-25 22:06:21 +08:00
Sky 90812e7f3a feat(opencode): add StepFun Step Plan provider preset (#1668)
Add StepFun Step Plan (阶跃星辰编程计划) as an OpenCode provider preset.

StepFun Step Plan is a subscription-based coding AI service that uses a
dedicated API endpoint separate from the standard StepFun provider.

- Base URL: https://api.stepfun.com/step_plan/v1
- Model: step-3.5-flash (196B MoE, optimized for agent and coding tasks)
- Category: cn_official
- Supports tool_call, reasoning, temperature control

Ref: https://platform.stepfun.com/docs/zh/step-plan/overview
Made-with: Cursor

Co-authored-by: sky-wang-salvation <sky-wang-salvation@users.noreply.github.com>
2026-03-25 21:22:05 +08:00
Jason 8c42ec48ef docs(release): add risk notice anchor links in v3.12.3 highlights section 2026-03-24 17:53:07 +08:00
Jason 761038f0ea docs(release): add Copilot reverse proxy risk notice to v3.12.3 release notes
Add risk disclaimer section in all three languages (EN/ZH/JA) warning
users about potential GitHub ToS violations, account suspension risks,
and no long-term availability guarantee for the Copilot reverse proxy.
2026-03-24 17:46:32 +08:00
Jason 155a226e6a chore(release): consolidate v3.12.3 release notes, changelog and test fixes
Merge previously unreleased v3.12.4 content into v3.12.3:
- CHANGELOG: combine [Unreleased] into [3.12.3], clear [Unreleased]
- Release notes (zh/en/ja): add Copilot proxy, macOS signing,
  Reasoning Effort, OpenCode SQLite, Codex 1M toggle, Disable
  Auto-Upgrade toggle, and contributor thanks
- Fix test mocks for skill backup/restore hooks
- Fix schema migration test missing providers table
- Fix TempHome to save/restore CC_SWITCH_TEST_HOME env var
2026-03-24 15:26:17 +08:00
Jason 10be929f33 feat(claude): add "Disable Auto-Upgrade" checkbox to provider config editor
Add a toggle for DISABLE_AUTOUPDATER env var in CommonConfigEditor,
following the same pattern as the existing Teammates mode toggle.
2026-03-24 15:17:09 +08:00
Jason 141010332b feat(dmg): use create-dmg for styled macOS DMG installer
Tauri's built-in DMG styling relies on AppleScript/Finder access which
silently fails on CI (tauri-apps/tauri#1731). Switch to create-dmg tool
which works on GitHub Actions macOS runners.

- Replace Tauri DMG with create-dmg: background image, icon positions,
  app-drop-link, codesign, hide-extension
- Regenerate background image at 2x Retina resolution (1320x800)
- Revert tauri.conf.json dmg config (ineffective on CI)
- Reorder steps: Prepare → Notarize DMG → Verify
- Notarize and Verify now use release-assets/ path for DMG
2026-03-24 10:33:18 +08:00
Jason 15989effb4 feat(dmg): customize macOS DMG installer appearance
- Add DMG background image with drag-to-install arrow guide
- Configure window size (660x400), app and Applications icon positions
- Center icons horizontally with visual arrow between them
2026-03-24 09:51:23 +08:00
Jason d4edf30747 fix(ci): add separate DMG notarization step and build retry for macOS
Tauri only notarizes the .app bundle, not the DMG container. This caused
stapler staple to fail with "Record not found" for the DMG.

- Add "Notarize macOS DMG" step using xcrun notarytool with retry logic
- Add retry logic (3 attempts) to macOS build step for transient network failures
- Add hdiutil verify before DMG notarization submission
2026-03-24 08:45:56 +08:00
Jason 44b6eacf87 feat(ci): add macOS code signing and Apple notarization to release workflow
- Import Developer ID Application certificate into temporary keychain
- Inject APPLE_SIGNING_IDENTITY/APPLE_ID/APPLE_PASSWORD/APPLE_TEAM_ID
  into Tauri build step for automatic signing and notarization
- Staple notarization tickets to both .app and .dmg (hard-fail)
- Add verification step: codesign --verify + spctl -a + stapler validate
  for both .app and .dmg, gating the release on success
- Collect .dmg alongside .tar.gz and .zip in release assets
- Clean up temporary keychain with original default restored
- Update release notes to recommend .dmg and note Apple notarization
- Remove all xattr workarounds and "unidentified developer" warnings
  from README, README_ZH, installation guides, and FAQ (EN/ZH/JA)
2026-03-23 22:43:41 +08:00
Jason 0a301a497c fix: prevent WebDAV password from being silently cleared by unrelated saves
Two components (ProviderList, UsageScriptModal) directly spread the full
settings object from the query into settingsApi.save(), which includes
webdavSync with an empty password (cleared by get_settings_for_frontend
for security). The backend merge_settings_for_save only preserved
existing WebDAV config when the incoming field was None, not when it was
present with an empty password.

Frontend fix: strip webdavSync before saving in both components, matching
the pattern already used by useSettings hook.

Backend defense-in-depth: merge_settings_for_save now backfills the
existing password when the incoming one is empty, preventing future
regressions from similar oversights.
2026-03-23 16:47:17 +08:00
TangZhiZzz 8aa6ec784b feat(skills): 优化技能安装/卸载的缓存更新策略 (#1573)
- 修改安装、卸载、导入、ZIP安装等操作的缓存更新逻辑,从invalidateQueries改为直接setQueryData
- 为已安装和可发现技能查询添加keepPreviousData和staleTime: Infinity配置
- 修复会话管理页面布局滚动问题,添加min-h-0防止内容溢出
2026-03-23 16:05:13 +08:00
BlueOcean bd3cfb7741 fix: parse tool_use/tool_result messages and add OpenCode SQLite backend (#1401)
* fix: parse tool_use/tool_result messages and add OpenCode SQLite backend

  - Claude: reclassify user messages containing tool_result as "tool" role
  - Codex: handle function_call and function_call_output payload types
  - Gemini: support array content and toolCalls extraction, filter info/error types
  - OpenCode: add SQLite session scan, load and delete alongside legacy JSON
  - utils: extend parse_timestamp_to_ms for integer timestamps, extract tool_use/tool_result in shared extract_text

* fix: address remaining issues from tool_use/tool_result parsing commit
  - Claude: fix role misclassification for mixed user+tool_result messages (any → all)
  - OpenCode: extract duplicate part text logic into extract_part_text()
  - OpenCode: add path validation for SQLite delete to prevent foreign DB access
  - OpenCode: wrap SQLite deletion in transaction for atomicity
  - openclaw_config: remove redundant as_deref() on Option<&str>
2026-03-22 22:02:35 +08:00
makoMakoGo 117dbf1386 docs(usage): clarify pricing model ID normalization rules (#1591) 2026-03-21 22:59:28 +08:00
Jianan 72f570b99e fix: change darkMode selector to use .dark class (#1596) 2026-03-21 22:55:21 +08:00
Jason 2296c41497 chore: update MiniMax partner description from M2.5 to M2.7 2026-03-21 09:18:53 +08:00
Jason fe3f9b60de feat(proxy): resolve reasoning_effort from explicit effort with budget fallback
Replace map_thinking_to_reasoning_effort() with resolve_reasoning_effort()
that uses a two-tier priority system:

1. Explicit output_config.effort: low/medium/high map 1:1, max → xhigh
2. Fallback: thinking.type + budget_tokens thresholds (<4k → low,
   4k-16k → medium, ≥16k → high, adaptive → high)

Both Chat Completions and Responses API paths share the same helper,
ensuring consistent mapping across all OpenAI-compatible endpoints.
2026-03-20 23:36:47 +08:00
Jason 3e78fe8305 chore: update MiniMax preset model from M2.5 to M2.7 2026-03-20 21:05:56 +08:00
Jason 6f170305b8 chore: update Claude 4.6 context window to 1M (GA)
Claude Opus 4.6 and Sonnet 4.6 1M context window is now GA and no
longer requires a beta header. Update contextWindow from 200k to 1M
for all OpenClaw/OpenCode presets (27 entries in OpenClaw, 1 in
OpenCode Bedrock). Also add claude-sonnet-4-6 model pricing seed.
2026-03-20 21:00:22 +08:00
Jason 552f7abee4 refactor(ui): remove duplicate OAuth tab from AddProviderDialog
- Remove AuthCenterPanel import and OAuth TabsContent
- Narrow activeTab type from three values to "app-specific" | "universal"
- Simplify footer by removing oauth branch, reducing to two-way conditional
- Change TabsList from grid-cols-3 to grid-cols-2
- OAuth authentication remains available in settings page and CopilotAuthSection
2026-03-20 15:23:18 +08:00
Jason fd2b232f1c chore: update Xiaomi MiMo preset model from mimo-v2-flash to mimo-v2-pro 2026-03-20 08:59:41 +08:00
Jason 82c75de51c fix(copilot): unify request fingerprint across all Copilot API calls
- Make header constants in copilot_auth.rs public, add COPILOT_INTEGRATION_ID
- Unify User-Agent across 4 internal methods (eliminate "CC-Switch" leakage) and version string
- claude.rs add_auth_headers now references shared constants, adds user-agent / api-version / openai-intent
- forwarder.rs filters all 6 fixed fingerprint headers for Copilot requests to prevent reqwest append duplication
- stream_check.rs health check pipeline aligned with new fingerprint
2026-03-19 17:29:04 +08:00
Zhou Mengze 8ccfbd36d6 feat(copilot): add GitHub Copilot reverse proxy support (#930)
* refactor(toolsearch): replace binary patch with ENABLE_TOOL_SEARCH env var toggle

- Remove toolsearch_patch.rs binary patching mechanism (~590 lines)
  - Delete `toolsearch_patch.rs` and `commands/toolsearch.rs`
  - Remove auto-patch startup logic and command registration from lib.rs
  - Remove `tool_search_bypass` field from settings.rs
  - Remove frontend settings ToggleRow, useSettings hook sync logic, and API methods
  - Clean up zh/en/ja i18n keys (notifications + settings)

- Add ENABLE_TOOL_SEARCH toggle to Claude provider form
  - Add checkbox in CommonConfigEditor.tsx (alongside teammates toggle)
  - When enabled, writes `"env": { "ENABLE_TOOL_SEARCH": "true" }`
  - When disabled, removes the key; takes effect on provider switch
  - Add zh/en/ja i18n key: `claudeConfig.enableToolSearch`

Claude Code 2.1.76+ natively supports this env var, eliminating the need for binary patching.

* feat(claude): add effortLevel high toggle to provider form

- Add "high-effort thinking" checkbox to Claude provider config form
- When checked, writes `"effortLevel": "high"`; when unchecked, removes the field
- Add zh/en/ja i18n translations

* refactor(claude): remove deprecated alwaysThinking toggle

- Claude Code now enables extended thinking by default; alwaysThinkingEnabled is a no-op
- Thinking control is now handled via effortLevel (added in prior commit)
- Remove state, switch case, and checkbox UI from CommonConfigEditor
- Clean up alwaysThinking i18n keys across zh/en/ja locales

* feat(opencode): add setCacheKey: true to all provider presets

- Add setCacheKey: true to options in all 33 regular presets
- Add setCacheKey: true to OPENCODE_DEFAULT_CONFIG for custom providers
- Exclude 2 OMO presets (Oh My OpenCode / Slim) which have their own config mechanism

Closes #1523

* fix(codex): resolve 1M context window toggle causing MCP editor flicker

- Add localValueRef to short-circuit duplicate CodeMirror updateListener callbacks,
  breaking the React state → CodeMirror → stale onChange → React state feedback loop
- Use localValueRef.current in handleContextWindowToggle and handleCompactLimitChange
  to avoid stale closure reads
- Change compact limit input from type="number" to type="text" with inputMode="numeric"
  to remove unnecessary spinner buttons

* feat(codex): add 1M context window toggle utilities and i18n keys

- Add extractCodexTopLevelInt, setCodexTopLevelInt, removeCodexTopLevelField
  TOML helpers in providerConfigUtils.ts
- Add i18n keys for contextWindow1M, autoCompactLimit in zh/en/ja locales

* feat(claude): collapse model mapping fields by default

- Wrap 5 model mapping inputs in a Collapsible, collapsed by default
- Auto-expand when any model value is present (including preset-filled)
- Show hint text when collapsed explaining most users need no config
- Add zh/en/ja i18n keys for toggle label and collapsed hint
- Use variant={null} to avoid ghost button hover style clash in dark mode

* feat(claude): merge advanced fields into single collapsible section

- Merge API format, auth field, and model mapping into a unified "Advanced Options" collapsible
- Extend smart-expand logic to detect non-default values across all advanced fields
- Preserve model mapping sub-header and hint with a separator line
- Update zh/en/ja i18n keys (advancedOptionsToggle, advancedOptionsHint, modelMappingLabel, modelMappingHint)

* feat(copilot): add GitHub Copilot reverse proxy support

Add GitHub Copilot as a Claude provider variant with OAuth device code
authentication and Anthropic ↔ OpenAI format transformation.

Backend:
- Add CopilotAuthManager for GitHub OAuth device code flow
- Implement Copilot token auto-refresh (60s before expiry)
- Persist GitHub token to ~/.cc-switch/copilot_auth.json
- Add ProviderType::GitHubCopilot and AuthStrategy::GitHubCopilot
- Modify forwarder to use /chat/completions for Copilot
- Add Copilot-specific headers (Editor-Version, Editor-Plugin-Version)

Frontend:
- Add CopilotAuthSection component for OAuth UI
- Add useCopilotAuth hook for OAuth state management
- Auto-copy user code to clipboard and open browser
- Use 8-second polling interval to avoid GitHub rate limits
- Skip API Key validation for Copilot providers
- Add GitHub Copilot preset with claude-sonnet-4 model

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* fix(copilot): remove is_expired() calls from tests

Remove references to deleted is_expired() method in test code.
Only is_expiring_soon() is needed for token refresh logic.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* feat(copilot): add real-time model listing from Copilot API

- Add fetch_models() to CopilotAuthManager calling GET /models endpoint
- Add copilot_get_models Tauri command
- Add copilotGetModels() frontend API wrapper
- Modify ClaudeFormFields to show model dropdown for Copilot providers
  - Fetches available models on component mount when isCopilotPreset
  - Groups models by vendor (Anthropic, OpenAI, Google, etc.)
  - Input + dropdown button combo allows both manual entry and selection
  - Non-Copilot providers keep original plain Input behavior

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

* feat(copilot): add usage query integration

- Add Copilot usage API integration (fetch_usage method)
- Add copilot_get_usage Tauri command
- Add GitHub Copilot template in usage query modal
- Unify naming: copilot → github_copilot
- Add constants management (TEMPLATE_TYPES, PROVIDER_TYPES)
- Improve error handling with detailed error messages
- Add database migration (v5 → v6) for template type update
- Add i18n translations (zh, en, ja)
- Improve type safety with TemplateType
- Apply code formatting (cargo fmt, prettier)

* 修复github 登录和注销问题 ,模型选择问题

* feat(copilot): add multi-account support for GitHub Copilot

- Add multi-account storage structure with v1 to v2 migration
- Add per-account token caching and auto-refresh
- Add new Tauri commands for account management
- Integrate account selection in Proxy forwarder
- Add account selection UI in CopilotAuthSection
- Save githubAccountId to ProviderMeta
- Add i18n translations for multi-account features (zh/en/ja)

* 修复用量查询Reset字段出现多余字符

* refactor(auth-binding): introduce generic provider auth binding primitives

- add shared authBinding types in Rust and TypeScript while keeping githubAccountId as a compatibility field\n- resolve Copilot token, models, and usage through provider-bound account lookup instead of only the implicit default account\n- fix the Unix build regression in settings.rs by restoring std::io::Write for write_all()\n- remove the accidental .github ignore entry and drop leftover Copilot form debug logs\n- keep the first migration step non-breaking by writing both authBinding and the legacy githubAccountId field from the form

* refactor(auth-service): add managed auth command surface and explicit default account state

- introduce generic managed auth commands and frontend auth API wrappers for provider-scoped login, status, account listing, removal, logout, and default-account selection\n- store an explicit Copilot default_account_id instead of relying on HashMap iteration order, and use it consistently for fallback token/model/usage resolution\n- sort managed accounts deterministically and surface default-account state to the UI\n- refactor the Copilot form hook to wrap a generic useManagedAuth implementation while preserving the existing component contract\n- add default-account controls to the Copilot auth section and extend Copilot auth status serialization/tests for the new state

* feat(auth-center): add a dedicated settings entrypoint for managed OAuth accounts

- add an Auth Center tab to Settings so managed OAuth accounts are no longer hidden inside individual provider forms\n- introduce a first AuthCenterPanel that hosts GitHub Copilot account management as the initial managed auth provider\n- keep the provider form experience intact while establishing a global account-management surface for future providers such as OpenAI\n- validate that the new settings tab works cleanly with the generic managed auth hook and existing Copilot account controls

* feat(add-provider): expose managed OAuth sources alongside universal providers

- add an OAuth tab to the Add Provider flow so managed auth sources sit beside app-specific and universal providers\n- reuse the new Auth Center panel inside the dialog, keeping account management discoverable during provider creation\n- make the dialog footer adapt to the OAuth tab so account setup does not pretend to create a provider directly\n- align the add-provider UX with the new architecture where OAuth accounts are global assets and providers bind to them later

* fix(auth-reliability): harden managed auth persistence and refresh behavior

- replace direct Copilot auth store writes with private temp-file writes and atomic rename semantics, and document the local token storage limitation\n- add per-account refresh locks plus a double-check path so concurrent requests do not stampede GitHub token refresh\n- surface legacy migration failures through auth status, expose them in the UI, and add translated copy for the new account-state labels\n- stop writing the legacy githubAccountId field from the provider form while keeping compatibility reads in place\n- add logout error recovery and Copilot model-load toasts so auth failures are no longer silently swallowed

* refactor(copilot-detection): prefer provider type before URL fallbacks

- update forwarder endpoint rewriting to treat providerType as the primary GitHub Copilot signal\n- keep githubcopilot.com string matching only as a compatibility fallback for older provider records without providerType\n- reduce one more path where Copilot behavior depended purely on URL heuristics

* fix(copilot-auth): add cancel button to error state in CopilotAuthSection

- 错误状态下仅有"重试"按钮,用户无法退出(如不可恢复的 403 未订阅错误)
- 新增"取消"按钮,复用已有的 cancelAuth 逻辑重置为 idle 状态

* 修复打包后github账号头像显示异常

* 修复github copilot 来源的模型测试报错

* feat(copilot-preset): add default model presets for GitHub Copilot

- 补充 Copilot 预设的默认模型配置,用户选完预设即可直接使用
- ANTHROPIC_MODEL: claude-opus-4.6
- ANTHROPIC_DEFAULT_HAIKU_MODEL: claude-haiku-4.5
- ANTHROPIC_DEFAULT_SONNET_MODEL: claude-sonnet-4.6
- ANTHROPIC_DEFAULT_OPUS_MODEL: claude-opus-4.6

---------

Co-authored-by: Jason <farion1231@gmail.com>
Co-authored-by: 周梦泽 <mengze.zhou@dafeng-tech.com>
Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
2026-03-17 23:57:58 +08:00
Jason 36bbdc36f5 chore(release): update release notes, changelog and macOS minimum version for v3.12.3
Update CHANGELOG.md with full v3.12.3 entry, create release notes in
three languages (en/zh/ja), bump macOS minimumSystemVersion from 10.15
to 12.0 (Monterey) to match actual runtime requirements, and update
README version badges and links.
2026-03-16 08:32:05 +08:00
Jason fc08a5d364 fix(ui): replace hardcoded height calc with flex-1 to eliminate bottom blank area
All content panels used h-[calc(100vh-8rem)] which didn't match the
actual available space (CONTENT_TOP_OFFSET is 92px on Mac, 64px on
Win/Linux, not 128px), causing a visible gap at the bottom.

Replace with flex-1 min-h-0 to let panels fill the remaining space
after <main> and any sibling elements (e.g. OpenClaw health banner).
2026-03-16 00:19:29 +08:00
Jason 333c9f277b feat(skills): add restore and delete for skill backups
Introduce list/restore/delete commands for skill backups created during
uninstall. Restore copies files back to SSOT, saves the DB record, and
syncs to the current app with rollback on failure. Delete removes the
backup directory after a confirmation dialog. ConfirmDialog gains a
configurable zIndex prop to support nested dialog stacking.
2026-03-16 00:00:31 +08:00
Jason 9336001746 feat(skills): auto-backup skill files before uninstall
Create a local backup under ~/.cc-switch/skill-backups/ before removing
skill directories. The backup includes all skill files and a meta.json
with original skill metadata. Old backups are pruned to keep at most 20.
The backup path is returned to the frontend and shown in the success
toast. Bump version to 3.12.3.
2026-03-15 23:26:50 +08:00
Jason 04254d6ffe fix(skills): add missing TooltipProvider in ImportSkillsDialog to prevent white screen
The AppToggleGroup component added in 7097a0d7 uses Radix UI Tooltip
which requires a TooltipProvider context. Without it, opening the
import dialog crashes with a runtime error and renders a blank page.
2026-03-15 23:02:54 +08:00
Jason 28afbea917 fix(proxy): enable gzip compression for non-streaming proxy requests
Non-streaming requests were forced to use `Accept-Encoding: identity`,
preventing upstream response compression and increasing bandwidth usage.

Now only streaming requests conservatively keep `identity` to avoid
decompression errors on interrupted SSE streams. Non-streaming requests
let reqwest auto-negotiate gzip and transparently decompress responses.
2026-03-15 22:01:57 +08:00
Jason 81897ac17e fix: revert incorrect o-series max_completion_tokens in Responses API path
Responses API uses max_output_tokens for all models including o-series.
The o-series max_completion_tokens fix should only apply to Chat Completions API.
2026-03-15 21:06:08 +08:00
Jason bb23ab918b fix: place OpenCode model variants at top level instead of inside options (#1317)
Split the expanded model panel into two editing areas:
- "Model Properties" for top-level fields (variants, cost, etc.)
- "SDK Options" for model.options fields (provider routing, etc.)

Also guard against renaming extra fields to reserved keys (name, limit,
options) or duplicate names, and fix ModelOptionKeyInput blur desync when
a rename is rejected by the parent handler.
2026-03-15 21:06:08 +08:00
Hemilt0n f38facd430 fix(proxy): use max_completion_tokens for o1/o3 series models (#1451)
* fix(proxy): use max_completion_tokens for o1/o3 series models

When converting Anthropic requests to OpenAI format for o1/o3 series
models (like o1-mini, o3-mini), use max_completion_tokens instead of
max_tokens to avoid unsupported_parameter errors.

Fixes #1448

* fix: revert incorrect o-series max_completion_tokens in Responses API path

Responses API uses max_output_tokens for all models including o-series.
The o-series max_completion_tokens fix should only apply to Chat Completions API.

---------

Co-authored-by: Hajen Teowideo <hajen.teowideo@example.com>
Co-authored-by: Jason Young <44939412+farion1231@users.noreply.github.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-03-15 20:39:17 +08:00
Hexi 5c03de53f7 fix(provider-form): prevent duplicate submissions on rapid button clicks (#1352)
Make ProviderForm.handleSubmit async and await onSubmit so react-hook-form's
isSubmitting state is tracked. Disable submit buttons in AddProviderDialog and
EditProviderDialog while submission is in flight via onSubmittingChange callback.
2026-03-15 15:24:17 +08:00
osehun d8a7bc32db fix: restore Claude sessions in Ghostty (#1506)
Co-authored-by: SEHUN <canyonsehun@gmail.com>
2026-03-15 11:23:15 +08:00
Jason f1cad25777 chore: touch config files to normalize commit messages 2026-03-15 00:15:07 +08:00
Jason 9439153f05 feat: add Tool Search domain restriction bypass with active-installation patching
Resolve the active `claude` command from PATH and apply an equal-length
byte patch to remove the domain whitelist check. Backups are stored in
~/.cc-switch/toolsearch-backups/ (SHA-256 of path) so they survive
Claude Code version upgrades. The patch auto-reapplies on app startup
when the setting is enabled.

Frontend checks PatchResult.success and rolls back the setting on failure.
2026-03-14 23:41:36 +08:00
Jason 7097a0d710 fix: replace implicit app inference with explicit selection for Skills import and sync
Skills import previously inferred app enablement from filesystem presence,
causing incorrect multi-app activation when the same skill directory existed
under multiple app paths. Now the frontend submits explicit app selections
via ImportSkillSelection, and schema migration preserves a snapshot of
legacy app mappings to avoid lossy reconstruction.

Also adds reconciliation to sync_to_app (removes disabled/orphaned symlinks)
and MCP sync_all_enabled (removes disabled servers from live config).
2026-03-14 23:41:36 +08:00
Dex Miller f1d2c6045b fix(skill): support .skill file extension in ZIP import dialog (#1240) (#1455) 2026-03-14 22:47:07 +08:00
funnytime 9e5a3b2dc9 fix: highlight active OpenClaw provider card (#1419)
closes #1414
2026-03-14 22:45:24 +08:00
King 2466873db3 chore: remove packageManager field from package.json (#1470) 2026-03-14 22:20:41 +08:00
李悠然 3c902b4599 fix: improve the responsive design when toc title exists (#1491) 2026-03-14 21:56:37 +08:00
Jason 1582d33705 chore: bump version to v3.12.2 and add release notes 2026-03-12 23:50:33 +08:00
Jason 305c0f2e08 feat: improve empty state guidance for first-run experience
Show detailed import instructions and conditionally display common
config snippet hint for Claude/Codex/Gemini (not OpenCode/OpenClaw).
2026-03-12 23:42:15 +08:00
Jason 8e1204b1ee fix: merge Codex MCP restore backup entries during takeover
When proxy takeover is active, update_live_backup_from_provider rebuilds the Codex restore snapshot from the current provider and common-config state. We were then replacing the new mcp_servers table with the previous backup's table wholesale, which meant stopping takeover could restore stale MCP entries and silently discard MCP changes made through provider/common-config updates.

Change the backup preservation step to merge MCP entries by server id instead of replacing the entire table. New provider/common-config MCP definitions now win on conflict, while backup-only servers are retained so live-only MCP state still survives a hot-switch.

Add regression coverage for the existing preservation case and for the conflict case where both the old backup and the new provider define the same MCP server.
2026-03-12 23:15:40 +08:00
Jason 3568c98f57 fix: make Codex TOML base_url editing section-aware
Rewrite setCodexBaseUrl/extractCodexBaseUrl to understand TOML section
boundaries, ensuring base_url is written into the correct
[model_providers.<name>] section instead of being appended to file end.

- Add section-aware TOML helpers in providerConfigUtils.ts
- Extract shared update_codex_toml_field/remove_codex_toml_base_url_if
  in codex_config.rs, deduplicate proxy.rs TOML editing logic
- Replace scattered inline base_url regexes with extractCodexBaseUrl()
- Add comprehensive tests for both Rust and TypeScript implementations
2026-03-12 22:20:59 +08:00
Jason 7ca33ff901 fix: prevent common config loss during proxy takeover and stabilize snippet lifecycle
- Make sync_current_provider_for_app takeover-aware: update restore
  backup instead of overwriting live config when proxy is active
- Introduce explicit "cleared" flag for common config snippets to
  prevent auto-extraction from resurrecting user-cleared snippets
- Reorder startup: extract snippets from clean live files before
  restoring proxy takeover state
- Add one-time migration flag to skip legacy commonConfigEnabled
  migration on subsequent startups
- Add regression tests for takeover backup preservation, explicit
  clear semantics, and migration flag roundtrip
2026-03-12 17:16:22 +08:00
Jason e561084f62 Preserve common config during proxy takeover
Update takeover backup generation to rebuild effective provider settings with common config applied before saving restore snapshots.

Keep Codex mcp_servers entries when hot-switching providers under takeover so restore does not drop live-only MCP config.

Migrate legacy providers with inferred common-config usage to explicit commonConfigEnabled=true markers during startup and default imports, and cover the new behavior with proxy and provider regression tests.
2026-03-12 16:06:07 +08:00
Jason 3dad255a2a chore: bump version to v3.12.1 and add release notes 2026-03-12 00:15:05 +08:00
Jason 51825dac20 feat: add authHeader field to OpenClawProviderConfig and reuse type in form state
Add optional `authHeader` boolean to support vendor-specific auth headers
(e.g. Longcat). Refactor `resetOpenclawState` to use the shared
`OpenClawProviderConfig` type instead of an inline duplicate definition.
2026-03-11 23:56:41 +08:00
Jason ce985763f0 fix: rename OpenCode API format label from "OpenAI" to "OpenAI Responses" 2026-03-11 23:51:11 +08:00
Jason 19dca7cd2b feat: add CTok as sponsor and upgrade Gemini model to 3.1-pro 2026-03-11 23:47:08 +08:00
Jason 70632249a8 feat: add SiliconFlow as sponsor and update affiliate links
Replace SDS logos with SiliconFlow logos, add SiliconFlow sponsor entries
to all three README files (en/zh/ja), fix incorrect alt attribute, and
update all SiliconFlow provider preset apiKeyUrl to affiliate link.
2026-03-11 16:25:38 +08:00
Jason 55210d90d2 fix: update Compshare sponsor registration links to coding-plan page 2026-03-11 15:23:04 +08:00
Jason 239c6fb2d7 fix: prevent common config modal infinite reopen loop and add draft editing
The auto-open useEffect in CodexConfigEditor and GeminiConfigEditor
created an inescapable loop: commonConfigError triggered modal open,
closing the modal didn't clear the error, so the effect immediately
reopened it — locking the entire UI.

- Remove auto-open useEffect from both Codex and Gemini config editors
- Convert common config modals to draft editing (edit locally, validate
  before save) instead of persisting on every keystroke
- Add TOML/JSON pre-validation via parseCommonConfigSnippet before any
  merge operation to prevent invalid content from being persisted
- Expose clearCommonConfigError so editors can clear stale errors on
  modal close
2026-03-11 14:40:14 +08:00
Jason 4ac7e28b10 feat: add XCodeAPI as sponsor and fix incorrect alt attributes
- Add XCodeAPI sponsor entry to all three READMEs (zh, en, ja)
- Fix XCodeAPI logo alt from "Micu" to "XCodeAPI" in README_ZH.md
- Fix Crazyrouter logo alt from "AICoding" to "Crazyrouter" in all READMEs
2026-03-11 11:12:29 +08:00
Jason 47e956bb63 feat: add Micu API as sponsor and update affiliate links
Add Micu (米醋API) sponsor entry to all three README files (EN/ZH/JA)
with logo and description. Update apiKeyUrl for Micu provider presets
across claude, codex, opencode, and openclaw to use affiliate
registration link.
2026-03-11 00:14:40 +08:00
Jason 0bcbffb8a0 feat: rename UCloud provider to Compshare/优云智算 with i18n support
Add optional `nameKey` field to all preset interfaces for localized
display names. The preset selector and form now resolve `nameKey` via
i18next, falling back to `name` when unset.

- zh: 优云智算 / en+ja: Compshare
- Update model ID prefix ucloud/ → compshare/ in OpenClaw presets
- Update partner promotion copy and README sponsor descriptions
2026-03-10 23:43:23 +08:00
Jason 273a756869 fix: sync session search index with query data to refresh list after deletion
Replace useRef+useEffect async index rebuild with useMemo so the
FlexSearch index and the sessions array always reference the same data.
This ensures filtered search results update immediately when a session
is deleted via TanStack Query setQueryData.
2026-03-10 23:06:45 +08:00
Jason c2b60623a6 fix: avoid FK constraint failure when restoring provider_health during WebDAV sync
Split LOCAL_ONLY_TABLES into SYNC_SKIP_TABLES (export) and
SYNC_PRESERVE_TABLES (import). provider_health is skipped on export
but no longer restored on import, since it has a foreign key on
providers(id, app_type) that may not match the remote dataset.
Health data is ephemeral and rebuilds automatically at runtime.
2026-03-10 23:06:45 +08:00
Jason f4ad17d314 fix: align stream check toast i18n interpolation keys with translation placeholders 2026-03-10 23:06:45 +08:00
Jason 236f96b583 fix: correct X-Code API URL from www.x-code.cn to x-code.cc 2026-03-10 23:06:45 +08:00
Zhou Mengze 75b4ef2299 fix: interpolate proxy startup toast address and port (#1399)
Co-authored-by: 周梦泽 <mengze.zhou@dafeng-tech.com>
2026-03-10 21:02:13 +08:00
bigsong fab9874b2c fix: align OpenClaw tool permission profiles with upstream schema (#1355)
* fix: align OpenClaw tool permission profiles with upstream schema

* fix: remove dead i18n keys and save-blocking validation

- Remove unused `profiles.*` nested i18n keys (dead code, ToolsPanel uses flat `profileMinimal` etc.)
- Remove `invalidProfile` i18n key no longer referenced
- Remove handleSave validation that blocked saving allow/deny when legacy profile exists
- Keep the profile destructuring cleanup from the original PR

---------

Co-authored-by: Your Name <your.email@example.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-03-10 17:53:44 +08:00
liuxxxu 84668e2307 feat(openClaw form): add input type selection for models Advanced Options / 为模型高级选项添加输入类型选择 (#1368)
* feat(openClaw form): add input type selection for models Advanced Options / 为模型高级选项添加输入类型选择

* fix(i18n): add missing openclaw.inputTypes key to all locales

The new inputTypes field in OpenClawFormFields used defaultValue fallback,
causing English and Japanese users to see Chinese text.

---------

Co-authored-by: xu.liu2 <xu.liu2@brgroup.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-03-10 16:53:40 +08:00
wavever b4033fdd29 fix: add missing authHeader: true to Longcat provider preset (#1377)
Fixes issue where Longcat models were failing with 404 error due to missing
authHeader configuration. According to Longcat API documentation, this
setting is required for proper authentication.

Closes: #1376
2026-03-10 16:14:08 +08:00
hengm3467 471c0d9990 feat: add StepFun provider presets and step-3.5-flash (#1369)
* feat: add StepFun provider presets

* docs: regroup StepFun pricing entry

* docs: tweak StepFun zh label

* style: apply prettier fixes

* Revert "style: apply prettier fixes"

This reverts commit cff7bf2e65.
2026-03-10 10:27:50 +08:00
zuoliangyu a9c36381fc fix: toolbar compact mode not triggering on Windows due to left-side overflow (#1375)
The toolbar container used `justify-end` which caused content to overflow
to the left side. Browser `scrollWidth` does not account for left-side
overflow, so `useAutoCompact` could never detect it and compact mode
never activated — resulting in clipped tab labels (e.g. "aude" instead
of "Claude") at minimum window width.

Fix: remove `justify-end` from the toolbar container and use `ml-auto`
on the child element instead. This keeps the right-aligned appearance
but makes overflow go rightward, where `scrollWidth` correctly detects
it and triggers compact mode.

Co-authored-by: zuolan <zuolan1102@qq.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 09:30:52 +08:00
Jason 5c32ec58be chore: upgrade all GPT model references to gpt-5.4
GPT no longer has separate codex variants (gpt-5.x-codex), unified as
gpt-5.4. Updated ~26 references across 8 files:

- Codex provider presets: default param + 12 vendor configs
- Codex custom template default model
- Universal provider default Codex model (gpt-4o → gpt-5.4)
- OpenCode @ai-sdk/openai: consolidated 7 old models into single gpt-5.4
- OpenCode RightCode: removed gpt-5.2-codex entry
- OMO agent/category recommended models (7 references)
- Stream check default Codex model
- Universal form fallback and placeholder
- Codex form placeholder text
2026-03-09 21:26:51 +08:00
Jason 625dea9c62 test: wait for auto-sync toggle state after confirmation dialog 2026-03-09 21:11:31 +08:00
Jason 333b82b4c4 chore: bump version to v3.12.0 and update release references 2026-03-09 21:05:27 +08:00
Jason 92f62e884c docs: add v3.12.0 CHANGELOG and release notes (zh/en/ja) 2026-03-09 21:03:52 +08:00
Jason 44096b0e44 refactor: remove backup path display from OpenClaw save toasts
Backup paths are internal implementation details not actionable by users.
Simplify toast notifications to show only success/failure messages.
2026-03-09 15:00:30 +08:00
Jason 99ef870077 perf: skip backup and atomic write when OpenClaw config is unchanged 2026-03-09 12:27:32 +08:00
Jason 82438decf6 feat: add endpointCandidates for Ucloud/X-Code Claude presets and unify Ucloud apiKeyUrl 2026-03-09 11:44:42 +08:00
Jason e5838e0a10 feat: update Ucloud presets and add OpenClaw defaults for Ucloud/Micu
- Update Ucloud links to coding-plan page across READMEs
- Remove hardcoded model overrides from Claude preset
- Switch Codex model from zai-org/glm-5 to gpt-5.4
- Replace GLM-5/MiniMax models with claude-opus-4-6 in OpenClaw preset
- Add templateValues and suggestedDefaults for Ucloud and Micu OpenClaw presets
2026-03-09 11:37:23 +08:00
Jason cc15d7b1e3 feat: add OpenClaw User-Agent toggle, default off
Add a switch in the OpenClaw provider form to optionally send a browser
User-Agent header. The toggle defaults to off — only providers that
explicitly include headers in their preset or config will have it enabled.

Remove the previous auto-injection logic that force-added User-Agent on
every preset load and new provider creation.
2026-03-09 10:36:11 +08:00
Jason dd971246be feat: restore Claude provider auth field selector (AUTH_TOKEN / API_KEY) 2026-03-09 08:56:58 +08:00
Jason 55509286eb fix: rename X-Code provider to X-Code API 2026-03-09 00:10:01 +08:00
Jason 5014c2a744 feat: add X-Code partner provider preset for Claude, Codex and OpenCode
- Add X-Code provider presets with x-code.cn endpoint
- Fix ANTHROPIC_API_KEY to ANTHROPIC_AUTH_TOKEN in Claude preset
- Register x-code icon SVG in icon index
- Add partnerPromotion.x-code i18n keys for zh, en, ja locales
2026-03-09 00:06:48 +08:00
Jason 9084e1ecc8 feat: add Micu partner provider preset for Claude, Codex, OpenClaw and OpenCode
- Add Micu provider presets with openclaudecode.cn endpoint
- Register micu icon SVG in icon index with namespaced CSS classes
- Rename miku.svg to micu.svg to match icon key
- Add partnerPromotion.micu i18n keys for zh, en, ja locales
2026-03-08 23:27:23 +08:00
Jason 02669cfbac feat: add Ucloud partner provider preset for Claude, Codex and OpenClaw
- Add Ucloud provider presets with modelverse.cn API endpoint
- Register ucloud icon SVG in icon index with namespaced gradient IDs
- Add partnerPromotion.ucloud i18n keys for zh, en, ja locales
2026-03-08 23:01:35 +08:00
Jason 9092e97bc2 style: format Rust code with cargo fmt 2026-03-08 22:27:53 +08:00
Jason 032a8203fd feat: show failover toggle independently on main page with confirm dialog
Add enableFailoverToggle setting to control failover toggle visibility
on the main page, decoupled from proxy takeover state. First-time
enable shows a ConfirmDialog (same pattern as proxy toggle). The toggle
row is placed in the Auto Failover accordion section in settings.
2026-03-08 22:25:48 +08:00
Jason 6d078e7f33 feat: apply common config as runtime overlay instead of materialized merge
Common config snippets are now dynamically overlaid when writing live
files, rather than being pre-merged into provider snapshots at edit time.
This ensures that updating a snippet immediately takes effect for the
current provider and automatically propagates to other providers on
their next switch.

Key changes:
- Add write_live_with_common_config() overlay pipeline
- Strip common config from live before backfilling provider snapshots
- Normalize provider snapshots on save to keep them snippet-free
- Add explicit commonConfigEnabled flag in ProviderMeta (Option<bool>)
- Migrate legacy providers on snippet save (infer flag from subset check)
- Add Codex TOML snippet validation in set_common_config_snippet
- Stabilize onConfigChange callbacks with useCallback in ProviderForm
2026-03-08 21:45:20 +08:00
Jason fc6f2af4c6 style: format code with prettier 2026-03-08 21:45:05 +08:00
Jason c54515742f fix: comprehensive i18n audit - add 69 missing keys and fix hardcoded Chinese
- Add 69 missing translation keys to zh/en/ja (usage, proxy, sessionManager,
  deeplink, codexConfig, openclaw, circuitBreaker, streamCheck, etc.)
- Replace 15 hardcoded Chinese strings in CircuitBreakerConfigPanel with t() calls
- Fix ColorPicker component to use i18n for default label
- Add i18n interpolation params to ProxyToggle tooltip translations
- All three language files synchronized at 1838 keys
2026-03-08 20:41:44 +08:00
Jason 7dbceeafe6 feat: add confirmation dialog for WebDAV auto-sync toggle
Show a one-time traffic warning when users first enable auto-sync,
persisted via autoSyncConfirmed flag in settings.
2026-03-08 20:10:45 +08:00
Jason 31bfecde39 fix: correct i18n key paths for model test panel title and description 2026-03-08 19:54:46 +08:00
Jason 41c3f845cb refactor: consolidate periodic maintenance timer and add vacuum/rollup
Change periodic timer from hourly backup-only to daily maintenance that
includes backup, incremental auto-vacuum, and usage rollup in a single
pass.
2026-03-08 19:42:18 +08:00
Jason c0737f2cfe feat: add dual-layer versioning to WebDAV sync (protocol v2 + db-v6)
Separate protocol version from database compatibility version in WebDAV
sync paths. Upload writes to v2/db-v6/<profile>, download falls back to
legacy v2/<profile> when current path has no data. Extend manifest with
optional dbCompatVersion field and add legacy layout detection to UI.
2026-03-08 19:42:18 +08:00
Jason bf40b0138c feat: add usage daily rollups, incremental auto-vacuum, and sync-aware backup
- Add usage_daily_rollups table (schema v6) to aggregate proxy request
  logs into daily summaries, reducing query overhead for statistics
- Add rollup_and_prune DAO that aggregates old detail logs (>N days)
  into rollup rows and deletes the originals
- Update all usage stats queries to UNION detail logs with rollup data
- Introduce incremental auto-vacuum for SQLite, with startup and
  periodic cleanup of old stream_check_logs and request log rollups
- Split backup export/import into full vs sync variants: WebDAV sync
  now skips local-only table data (proxy_request_logs,
  stream_check_logs, provider_health, proxy_live_backup,
  usage_daily_rollups) while preserving them on import
- Add enable_logging guard to skip request log writes when disabled
- Apply cargo fmt formatting fixes across multiple modules
2026-03-08 19:42:18 +08:00
Jason 3f711d6504 fix: add missing /v1 path to SSSAiCode default endpoint for Codex and OpenCode 2026-03-08 19:42:18 +08:00
Jason 8c3f18a9bd feat: add session deletion with per-provider cleanup and path safety
Add delete_session Tauri command dispatching to provider-specific deletion
logic for all 5 providers (Claude, Codex, Gemini, OpenCode, OpenClaw).
Includes path traversal protection via canonicalize + starts_with validation,
session ID verification against file contents, frontend confirmation dialog
with optimistic cache updates, i18n keys (zh/en/ja), and component tests.
2026-03-08 19:42:18 +08:00
Jason e18db31752 feat: add partner badge for SiliconFlow provider presets 2026-03-08 19:42:18 +08:00
Jason c0fe0d6e07 fix: normalize JSON5 slash escaping and add i18n for OpenClaw panels
- Fix json-five output unescaping forward slashes (\/ → /)
- Add structured error codes for env validation (EMPTY, INVALID_JSON, OBJECT_REQUIRED)
- Add i18n keys (zh/en/ja) for health warnings, tool profiles, env editor hints,
  and agents legacy timeout migration
- Update env validation test to match new error codes
2026-03-08 19:42:18 +08:00
Jason 7e6f803035 feat: overhaul OpenClaw config panels with JSON5 round-trip write engine
- Add json-five crate for JSON5 serialization preserving comments and formatting
- Rewrite openclaw_config.rs with comment-preserving JSON5 read/write engine
- Add Tauri commands: get_openclaw_live_provider, write_openclaw_config_section
- Redesign EnvPanel as full JSON editor with structured error handling
- Add tools.profile selection (minimal/coding/messaging/full) to ToolsPanel
- Add legacy timeout migration support to AgentsDefaultsPanel
- Add OpenClawHealthBanner component for config validation warnings
- Add supporting hooks, mutations, utility functions, and unit tests
2026-03-08 19:42:18 +08:00
Jason b4fdd5fc0d fix: remove www prefix from aicoding.sh provider URLs 2026-03-08 19:42:18 +08:00
Jason 1573474e3a Fix proxy forwarder failure logs 2026-03-08 19:42:18 +08:00
Jason 50a2bd29e6 fix: correct OpenAI ChatCompletion to Anthropic Messages streaming conversion
Rewrite tool call handling in streaming format conversion to properly
track multiple concurrent tool blocks with independent Anthropic content
indices. Fix block interleaving (thinking/text/tool_use) with correct
content_block_start/stop events, buffer tool arguments until both id and
name are available, and add tool result message conversion in transform.
2026-03-08 19:41:29 +08:00
Jason 11f70f676e refactor: deduplicate and improve OpenAI Responses API conversion
- Extract shared map_responses_stop_reason and build_anthropic_usage_from_responses into transform_responses.rs as pub(crate)
- Align cache token extraction priority: OpenAI nested details as fallback, direct Anthropic fields as override
- Extract resolve_content_index helper to eliminate 3x copy-paste in streaming_responses.rs
- Add streaming reasoning/thinking event handlers (response.reasoning.delta/done)
- Add explanatory comment to transform_response heuristic detection
- Add openai_responses to api_format doc comment and needs_transform test
- Add explicit no-op match arms for lifecycle events
- Add promptCacheKey to TS ProviderMeta type
- Update toast i18n key to be generic for both OpenAI formats (zh/en/ja)
2026-03-08 19:41:29 +08:00
Jason a30e2096bb feat: add OpenAI Responses API format conversion (api_format = "openai_responses")
Support Anthropic ↔ OpenAI Responses API format conversion alongside existing
Chat Completions conversion. The Responses API uses a flat input/output structure
with lifted function_call/function_call_output items and named SSE lifecycle events.
2026-03-08 19:41:29 +08:00
wugeer fb8996d19c fix:Add a new vendor page, API endpoint, and model name. (#1155)
* fix:Add a new vendor page, API endpoint, and model name. Fix the bug where, after entering characters, line breaks cannot be fully deleted.

* fix: add missing i18n key codexConfig.modelNameHint for zh/en/ja

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-03-07 22:53:44 +08:00
Fan 33d5f6985d fix: skills count not displaying when adding (#1295)
* fix: skills count not displaying when adding

* fix: get real skill count by awaiting discovery after adding repo

The previous approach computed count before discovery, so it was always 0.
Now we await refetchDiscoverable() after the mutation, then filter the
fresh skills list to get the actual count for the toast message.

Also reverts the SkillRepo.count field — keep the interface clean since
count is a transient UI concern, not a data model property.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-03-07 21:59:33 +08:00
Sube 95a74020e1 fix: align outline button text tone with usage refresh control (#1222)
Co-authored-by: zhangluguang <z397503810@gmail.com>
2026-03-07 21:17:33 +08:00
Bowen Han 078a81b867 feat: add extra field display in UsageFooter component for normal mode (#1137) 2026-03-07 21:16:43 +08:00
Mr.XYS a89f433dde fix: fix the issue of missing token statistics for cache hits in streaming responses (#1244) 2026-03-07 21:15:48 +08:00
Keith Yu 8217bfff50 feat: add Bedrock request optimizer (PRE-SEND thinking + cache injection) (#1301)
* feat: add Bedrock request optimizer (PRE-SEND thinking + cache injection)

Add a PRE-SEND request optimizer that enhances Bedrock API requests
before forwarding, complementing the existing POST-ERROR rectifier system.

New modules:
- thinking_optimizer: 3-path model detection (adaptive/legacy/skip)
  - Opus 4.6/Sonnet 4.6: adaptive thinking + effort max + 1M context beta
  - Legacy models: inject extended thinking with max budget
  - Haiku: skip (no modification)
- cache_injector: auto-inject cache_control breakpoints (max 4)
  - Injects at tools/system/assistant message positions
  - TTL upgrade for existing breakpoints (5m → 1h)

Gate: only activates for Bedrock providers (CLAUDE_CODE_USE_BEDROCK=1)
Config: stored in SQLite settings table, default OFF, user opt-in
UI: new Optimizer section in RectifierConfigPanel with 3 toggles + TTL

18 unit tests covering all paths. Verified against live Bedrock API.

* chore: remove docs/plans directory

* fix: address code review findings for Bedrock request optimizer

P0 fixes:
- Replace hardcoded Chinese with i18n t() calls in optimizer panel,
  add translation keys to zh/en/ja locale files
- Fix u64 underflow: max_tokens - 1 → max_tokens.saturating_sub(1)
- Move optimizer from before retry loop to per-provider with body
  cloning, preventing Bedrock fields leaking to non-Bedrock providers

P1 fixes:
- Replace .map() side-effect pattern with idiomatic if-let (clippy)
- Fix module alphabetical ordering in mod.rs
- Add cache_ttl whitelist validation in set_optimizer_config
- Remove #[allow(unused_assignments)] and dead budget decrement

---------

Co-authored-by: Keith (via OpenClaw) <keithyt06@users.noreply.github.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-03-07 18:57:21 +08:00
Suki 27d21c23ac Add Bailian For Coding preset configuration (#1263)
问题描述
bailian 模块使用的请求地址  https://dashscope.aliyuncs.com/apps/anthropic  仅适用于普通订阅用户,订阅 code 的用户调用该地址会无法正常使用

修改内容
增加bailian For Coding模块提供给 code 订阅用户:
正确地址:  https://coding.dashscope.aliyuncs.com/apps/anthropic 

测试验证
测试环境:本地搭建 ccswitch 运行环境,使用 code 订阅的阿里云 DashScope 账号
测试步骤:
  1. 修改地址前:调用 bailian 接口提示请求失败/无权限
  2. 修改地址后:成功调用接口,返回正常响应结果
影响范围:仅增加bailian For Coding模块,未改动其他逻辑,不影响非 code 订阅用户的使用
2026-03-04 23:49:14 +08:00
Tsukumi 0135abde1c fix: support codex /responses/compact route (#1194) 2026-03-04 23:47:38 +08:00
Jason 3d33f299a8 docs: add UCloud CompShare as sponsor partner 2026-03-04 23:23:27 +08:00
Jason 083e48bf8c fix: use structural TOML merge/subset for Codex common config snippet
The text-based approach (string append + substring matching) failed to
detect already-merged snippets when config.toml was reformatted by
external tools (MCP sync, Codex CLI). Replace with smol-toml parse/
stringify + existing deepMerge/isSubset/deepRemove for correct
structural operations. Falls back to text matching on parse failure.
2026-03-04 23:01:40 +08:00
Jason d35c2962b9 style: format ProviderList.tsx 2026-03-04 23:01:40 +08:00
Jason 4e0f9d9552 feat: replace text inputs with dropdown selects for OpenClaw agent model config
- Add useOpenClawModelOptions hook to aggregate models from all configured OpenClaw providers
- Replace read-only primary model display with a searchable Select dropdown
- Replace comma-separated fallback text input with add/remove Select rows
- Filter out already-selected models from fallback options
- Show "(not configured)" marker for values whose provider has been deleted
- Unify terminology: rename "主模型/Primary Model" to "默认模型/Default Model"
2026-03-04 23:01:40 +08:00
Jason 7d4ffa9872 feat: add model role badges and reorder presets to prioritize Opus
- Add Primary/Fallback badge to each model card in OpenClaw form
- Update modelsHint to explain model ordering semantics
- Reorder 11 aggregator/third-party presets to put Opus first
2026-03-04 23:01:40 +08:00
Jason b3dda16b3a fix: remove HTTP status code display from endpoint speed test
The status code from a simple GET request reflects route matching,
not actual endpoint availability. Users only need latency and
reachability info, which the latency number already conveys.
2026-03-04 23:01:40 +08:00
Jason 07568286fc feat: add first-run confirmation dialog for stream check
Show an informational dialog when users first click the health check
button, explaining its limitations (OAuth providers, relay services,
Bedrock). The dialog persists the confirmation in settings so it only
appears once per device.
2026-03-04 23:01:40 +08:00
Jason 377c736aad fix: support openai_chat api_format in stream check
Stream Check always used Anthropic Messages API format, causing false
failures for providers with api_format="openai_chat" (e.g. NVIDIA).
Now detects api_format from provider meta/settings_config and uses
the correct endpoint (/v1/chat/completions) and headers accordingly.
2026-03-04 23:01:40 +08:00
Jason 2dcec4178d feat: restore model health check (stream check) UI
Re-enable the stream check feature that was hidden in v3.11.0.
All backend code, database schema, and i18n keys were preserved;
only the frontend UI needed uncommenting across 4 files.
OpenCode and OpenClaw are excluded as the backend does not support them.
2026-03-04 23:01:40 +08:00
Alex b05234c6df feat(providers): add Novita presets and icon across supported apps (#1192) 2026-03-04 22:57:12 +08:00
YewFence af68d4549b fix: 修复最小化到托盘后应用过一段时间自动退出的问题 (#1245)
ExitRequested 事件处理器无条件执行清理并调用 std::process::exit(0),
导致 api.prevent_exit() 被完全抵消。当隐藏窗口的 WebView 被 Windows
后台优化策略回收、窗口对象销毁后,Tauri 运行时检测到无存活窗口自动
触发 ExitRequested,应用随即退出。

通过 ExitRequested 的 code 字段区分两种场景:
- code 为 None(运行时自动触发):仅 prevent_exit(),保持托盘后台运行
- code 为 Some(_)(用户主动 app.exit()):执行清理后退出

Closes #728
2026-03-03 16:14:50 +08:00
Jason c772874dcb docs: reorganize docs directory structure
- Delete 9 completed planning/roadmap documents
- Move 23 release notes into docs/release-notes/ with simplified filenames
- Update all cross-references in READMEs, CHANGELOG, and release notes
- Remove dangling doc reference in deeplink/mod.rs
2026-03-03 09:28:48 +08:00
Jason d5d7b3190d docs: remove cross-language links from user manual sections in READMEs 2026-03-03 08:48:52 +08:00
Jason 0c78b38295 docs: add user manual links to all three README files 2026-03-03 08:43:57 +08:00
Jason bbed2a1fe1 docs: restructure user manual for i18n and add EN/JA translations
Reorganize docs/user-manual/ from flat structure to language subdirectories
(zh/, en/, ja/) with shared assets/. Move existing Chinese docs into zh/,
fix image paths, add multilingual navigation README, and translate all 23
markdown files (~4500 lines each) to English and Japanese.
2026-03-03 08:40:52 +08:00
Jason ce9c23833a docs: add OpenClaw coverage and complete settings docs for user manual
- Add OpenClaw as the 5th supported app across all doc chapters (1-3, 5)
- Add OpenClaw provider presets table to 2.1-add.md (30 presets)
- Add OpenClaw config section to 5.1-config-files.md (JSON5 format)
- Complete 1.5-settings.md with missing sections: app visibility,
  skill sync method, terminal settings, proxy tab, WebDAV cloud sync,
  backup/restore, and log configuration
- Fix deeplink parser.rs to accept 'opencode' and 'openclaw' app types
- Update 5.3-deeplink.md with new app type parameters
- Remove incorrect OpenCode references from proxy docs (4.1-4.4)
2026-03-02 23:16:58 +08:00
Jason 2eca90e43a feat: auto-extract common config snippets from live files on first run
During app startup, iterate all app types and extract non-provider-specific
config fields from live configuration files into the database. This runs
only when no snippet exists yet for a given app type, enabling incremental
extraction as new apps are configured.
2026-03-02 11:47:36 +08:00
Jason 4b0f14e2e6 docs: sync README features across EN/ZH/JA
Add format conversion, per-provider proxy granularity, and
symlink/file-copy support to EN and JA to match ZH updates.
2026-03-02 11:30:04 +08:00
Jason 83fe3402c2 chore: bump version to v3.11.1 and add release notes 2026-02-28 16:12:50 +08:00
Jason c75311e14e fix: pass app interpolation param to proxy takeover toast messages
The i18next t() calls for proxy.takeover.enabled/disabled were missing
the `app` interpolation parameter, causing {{app}} placeholders in
translation strings to render literally instead of showing the app name.
2026-02-28 15:47:08 +08:00
Jason 35a4a15898 fix: restore flex-1 on toolbarRef to fix compact mode exit
After moving ProxyToggle/FailoverToggle outside toolbarRef, the flex-1
class was accidentally left only on the outer wrapper. Without flex-1,
toolbarRef.clientWidth reflects content width instead of available space,
causing useAutoCompact's exit condition to never trigger.
2026-02-28 15:33:15 +08:00
Jason fd836ce70d fix: let "follow system" theme auto-update by delegating to Tauri's native theme tracking
Pass "system" to set_window_theme instead of explicitly detecting dark/light,
so Tauri uses window.set_theme(None) and the WebView's prefers-color-scheme
media query stays in sync with the real OS theme.
2026-02-28 14:50:51 +08:00
Jason d5e4e8d133 refactor: move proxy toggle into panel and surface app takeover options
Move the proxy on/off switch from the accordion header into the panel
content area, placing it right above the app takeover section. This
ensures users see the takeover options immediately after enabling the
proxy, preventing the common pitfall of running the proxy without
actually taking over any app.

- Simplify accordion trigger to standard style with Badge only
- Add AnimatePresence animation for takeover section reveal
- Remove duplicate takeover switches from running info card
- Update stoppedDescription i18n to reference "above toggle"
- Add proxy.takeover.hint key in zh/en/ja
2026-02-28 09:13:32 +08:00
Jason f8c1f1736e fix: disable env check and one-click install on Windows to prevent protocol handler side effects 2026-02-28 00:12:12 +08:00
Jason 859f413756 revert: restore full config overwrite + Common Config Snippet (revert 992dda5c)
Revert the partial key-field merging refactoring introduced in 992dda5c,
along with two dependent commits (24fa8a18, 87604b18) that referenced
the now-removed ClaudeQuickToggles component.

The whitelist-based partial merge approach had critical issues:
- Non-whitelisted custom fields were lost during provider switching
- Backfill permanently stripped non-key fields from the database
- Whitelist required constant maintenance to track upstream changes

This restores the proven "full config overwrite + Common Config Snippet"
architecture where each provider stores its complete configuration and
shared settings are managed via a separate snippet mechanism.

Reverted commits:
- 24fa8a18: context-aware JSON editor hint + hide quick toggles
- 87604b18: hide ClaudeQuickToggles when creating
- 992dda5c: partial key-field merging refactoring

Restored:
- Full config snapshot write (write_live_snapshot) for Claude/Codex/Gemini
- Full config backfill (settings_config = live_config)
- Common Config Snippet UI and backend commands
- 6 frontend components/hooks for common config editing
- configApi barrel export and DB snippet methods

Removed:
- ClaudeQuickToggles component
- write_live_partial / backfill_key_fields / patch_claude_live
- All KEY_FIELDS constants
2026-02-27 23:12:34 +08:00
Jason b2b20dadd7 fix: add import button for OpenCode/OpenClaw empty state and remove auto-import on startup
Previously OpenCode and OpenClaw auto-imported providers from live config
on app startup, which could confuse users. Now they follow the same
pattern as Claude/Codex/Gemini: manual import via the empty state button.
2026-02-27 11:50:38 +08:00
Jason 3bd0a7c02c docs: highlight Common Config Snippet removal as breaking change in release notes
Expand the partial key-field merging section with Before/After explanation
and migration guide. Mark it as a breaking change in Highlights and Notes
sections across all three languages (zh/en/ja) and CHANGELOG.md.
2026-02-27 00:03:22 +08:00
Jason ac23328119 chore: bump version to v3.11.0 and add release notes
- Update version numbers in package.json, Cargo.toml, tauri.conf.json
- Add CHANGELOG.md entry for v3.11.0
- Add trilingual release notes (zh/en/ja)
- Update user manual version info
2026-02-26 23:13:59 +08:00
Jason 0c4a8d0569 fix: use local time instead of UTC for backup file names 2026-02-26 22:14:37 +08:00
Jason 01cc766a05 feat: add delete backup functionality with confirmation dialog 2026-02-26 22:06:10 +08:00
Jason 3590df68b8 fix: treat missing db file as error in manual backup to prevent false success toast
backup_database_file() returning Ok(None) was silently resolved as null
on the frontend, bypassing try/catch and showing a success toast without
actually creating a backup file. Now None is converted to an explicit
Err so the frontend correctly displays an error toast.
2026-02-26 21:53:59 +08:00
Jason 54876612b3 feat: show silent startup option only when launch on startup is enabled
Add conditional rendering with animated transition for the silent startup
toggle, so it only appears when the launch on startup option is checked.
2026-02-26 21:25:14 +08:00
Jason 3348b39089 fix: restore API Key input visibility when creating new Claude providers
The hasApiKeyField() gate added for Bedrock AKSK/API Key distinction
was incorrectly hiding the API Key input for all new providers with
empty env config. Scope the gate to cloud_provider category only.
2026-02-26 21:19:49 +08:00
Jason 99e392518a fix: remove outdated partner status from Zhipu GLM presets 2026-02-26 21:04:53 +08:00
Jason 201527c9d9 fix: merge duplicate openclaw i18n keys to restore provider form translations
JSON does not support duplicate keys — the second `openclaw` object was
silently overwriting the first, causing all provider form field translations
(providerKey, apiProtocol, baseUrl, models, etc.) to be lost at runtime.
2026-02-26 20:43:39 +08:00
Jason 924f38ebe1 fix: remove last-provider deletion restriction for OMO/OMO Slim plugins
OMO and OMO Slim are OpenCode plugins, not standalone apps — users
should be able to fully remove them. Remove the count-based guard that
prevented deleting the last active provider, and clean up the now-unused
provider-count API surface across the full stack.
2026-02-26 20:27:04 +08:00
Jason e7766d4d22 refactor: remove OMO common config two-layer merge system
Each OMO provider now stores its complete configuration directly in
settings_config.otherFields instead of relying on a shared OmoGlobalConfig
merged at write time. This simplifies the data flow from a 4-tuple
(agents, categories, otherFields, useCommonConfig) to a 3-tuple and
eliminates an entire DB table, two Tauri commands, and ~1700 lines of
merge/sync code across frontend and backend.

Backend:
- Delete database/dao/omo.rs (OmoGlobalConfig struct + get/save methods)
- Remove get/set_config_snippet from settings DAO
- Remove get/set_common_config_snippet Tauri commands
- Replace merge_config() with build_config() in services/omo.rs
- Simplify OmoVariant (remove config_key, known_keys)
- Simplify import_from_local and build_local_file_data
- Rewrite all OMO service tests

Frontend:
- Delete OmoCommonConfigEditor.tsx and OmoGlobalConfigFields.tsx
- Delete src/lib/api/config.ts
- Remove OmoGlobalConfig type and merge preview functions
- Remove useGlobalConfig/useSaveGlobalConfig query hooks
- Simplify useOmoDraftState (remove all common config state)
- Replace OmoCommonConfigEditor with read-only JsonEditor preview
- Clean i18n keys (zh/en/ja)
2026-02-26 19:31:43 +08:00
Jason 3e9815f5d2 chore: add .worktrees/ to .gitignore 2026-02-26 19:15:54 +08:00
Jason 082cb0327d fix: enforce OMO ↔ OMO Slim cross-category mutual exclusion
When activating an OMO provider, deactivate all OMO Slim providers
in the same transaction and delete the Slim config file, and vice
versa. This prevents both plugin variants from being active
simultaneously.
2026-02-26 18:08:46 +08:00
Jason 55e21c3c19 fix: invalidate OMO Slim query cache after provider mutations
OMO Slim queries (["omo-slim", ...]) were not invalidated alongside
OMO queries, causing stale UI state when switching/adding/deleting
OMO Slim providers.
2026-02-26 17:51:50 +08:00
Jason 3e2c8c12a5 fix: sync OMO agent/category recommended models with upstream sources
Regular agents & categories: align with oh-my-opencode model-requirements.ts
fallback chains (oracle→gpt-5.2, librarian→gemini-3-flash, etc.)

Slim agents: derive from Regular's design philosophy — match each agent
to its functional counterpart's first-choice model instead of using
the outdated Slim defaults. Also fix provider/model format to pure
model IDs for suffix matching compatibility.
2026-02-26 17:39:08 +08:00
Jason 90cb8db16b fix: add toast feedback for OMO "Fill Recommended" button silent failures 2026-02-26 16:02:18 +08:00
Jason 2b30819510 chore: pre-release cleanup — remove debug logs, fix clippy warning, add missing ja translations, and format code
- Remove 2 console.log statements from DeepLinkImportDialog
- Fix clippy unnecessary_map_or: use is_some_and in live.rs
- Add 17 missing Japanese i18n keys (skills, proxy, circuitBreaker, universalProvider)
- Run prettier and cargo fmt to fix pre-existing formatting drift
2026-02-26 15:11:13 +08:00
Jason 434392a669 perf: optimize session panel loading with parallel scan and head-tail JSONL reading
- Parallelize 5 provider scans using std::thread::scope
- Add read_head_tail_lines() to read only first 10 + last 30 lines from JSONL files, skipping potentially large middle sections
- Cache Codex UUID regex with LazyLock to avoid repeated compilation
- Skip expensive I/O in OpenCode when session title is already available
2026-02-26 11:16:04 +08:00
Jason 24fa8a18ef fix: show context-aware JSON editor hint and hide quick toggles for non-active providers
The hint text and ClaudeQuickToggles were misleading when editing
non-current providers or creating new ones, since the editor only
contains a config snippet rather than the full live settings.json.
2026-02-26 09:55:09 +08:00
Jason 87604b1809 fix: hide ClaudeQuickToggles when creating a new provider
The quick toggles (hide AI attribution, extended thinking, teammates
mode) patch the live config of the currently active provider, which
is incorrect during provider creation. Only show them in edit mode.
2026-02-26 09:32:51 +08:00
Jason 47435bd647 chore: update Claude model references from 4.5 to 4.6 in provider presets
Update Sonnet and Opus model IDs/names to 4.6 across Claude, OpenClaw,
and OpenCode provider preset configurations. OPENCODE_PRESET_MODEL_VARIANTS
(SDK model catalog) is intentionally left unchanged.
2026-02-25 23:25:41 +08:00
Jason 73ca8340bb feat: add SSAI Code partner provider presets, i18n, icon, and fix models
Add SSAI Code as a partner provider across all five apps with endpoint,
API key URL, and partner promotion config. Rename brand from SSSAiCode
to SSAI Code. Rename sssaicoding.svg to sssaicode.svg and register icon.
Add trilingual promotion text for $10 bonus credit. Add missing models
arrays in OpenClaw presets for CrazyRouter and SSAI Code.
2026-02-25 22:21:15 +08:00
Jason 31712f076f feat: add CrazyRouter partner provider presets, i18n, and register icons
Add CrazyRouter as a partner provider across all five apps with endpoint,
API key URL, and partner promotion config. Add trilingual promotion text
for the 30% bonus credit offer. Register aicoding and crazyrouter icons
in the icon index. Fix indentation in openclawProviderPresets.
2026-02-25 15:39:50 +08:00
Jason a254304a00 feat: add AICoding partner provider presets and i18n promotion text
Add AICoding as a partner provider across all five apps (Claude, Codex,
Gemini, OpenClaw, OpenCode) with endpoint, API key URL, and partner
promotion configuration. Add trilingual (zh/en/ja) promotion text for
the first top-up discount.
2026-02-24 23:08:22 +08:00
Jason e516f83c19 fix(test): add ResizeObserver polyfill and fix WebDAV accordion target in settings test 2026-02-24 22:28:41 +08:00
Jason b98c3ddb29 fix: add #[cfg(target_os = "windows")] to WSL helper functions to eliminate dead_code warnings 2026-02-24 22:28:41 +08:00
Jason bb3130cbe0 fix(opencode): add missing omo-slim category checks across add/form/mutation paths
Several code paths only checked for "omo" category but missed "omo-slim",
causing OMO Slim providers to be treated as regular OpenCode providers
(triggering invalid write_live_snapshot, requiring manual provider key,
and showing wrong form fields).
2026-02-24 22:28:41 +08:00
Keith Yu 8ea9638b9d feat: Add AWS Bedrock Provider Support (AKSK & API Key) (#1047)
* Add AWS Bedrock provider integration design document

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

* Add AWS Bedrock provider implementation plan

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

* Update implementation plan: add OpenCode Bedrock support

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

* feat: add cloud_provider category to ProviderCategory type

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

* feat: add AWS Bedrock (AKSK) Claude Code provider preset with tests

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

* feat: add AWS Bedrock (API Key) Claude Code provider preset with tests

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

* feat: add AWS Bedrock OpenCode provider preset with @ai-sdk/amazon-bedrock

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

* docs: add AWS Bedrock provider feature summary for PR

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

* chore: remove internal planning documents

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

* docs: add AWS Bedrock support to README (EN/ZH/JA)

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

* Add AWS Bedrock UI merge design document

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

* Add AWS Bedrock UI merge implementation plan

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

* feat: skip optional template values in validation

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

* feat: support isSecret template fields and hide base URL for Bedrock

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

* feat: add Bedrock validation, cleanup, and isBedrock prop in ProviderForm

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

* feat: extend TemplateValueConfig and merge Bedrock presets

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

* fix: mask Bedrock API Key as secret and support GovCloud regions

- Add isSecret: true to BEDROCK_API_KEY template value
- Update region regex to support multi-segment regions (us-gov-west-1)

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

* style: replace AWS icon with updated logo

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

* style: replace AWS icon with updated logo

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

* style: replace AWS icon with new PNG image

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

* fix: address code review findings

- Fix AWS icon: use SVG with embedded <image> instead of raw <img> tag
- Hide duplicate ApiKeySection for Bedrock (auth via template fields only)
- Guard settingsConfig cleanup against unresolved template placeholders

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

* chore: remove planning documents

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

* refactor: address PR review - split Bedrock into two presets, restore SVG icon

Based on maintainer review feedback on PR #1047:

1. Split merged "AWS Bedrock" back into two separate presets:
   - "AWS Bedrock (AKSK)": uses AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY
   - "AWS Bedrock (API Key)": uses top-level apiKey field via standard UI input

2. Restore aws.svg to pure vector SVG (was PNG-in-SVG)

3. Remove all Bedrock-specific logic from shared components:
   - Remove isBedrock prop from ClaudeFormFields
   - Remove Bedrock validation/cleanup blocks from ProviderForm
   - Remove optional/isSecret from TemplateValueConfig
   - Remove optional skip from useTemplateValues

4. Add cloud_provider category handling:
   - Skip API Key/Base URL required validation
   - Hide Speed Test and Base URL for cloud_provider
   - Hide API format selector for cloud_provider (always Anthropic)
   - Show API Key input only when config has apiKey field

5. Fix providerConfigUtils to support top-level apiKey:
   - getApiKeyFromConfig: check config.apiKey before env fields
   - setApiKeyInConfig: write to config.apiKey when present
   - hasApiKeyField: detect top-level apiKey property

6. Add OpenClaw Bedrock preset (bedrock-converse-stream protocol)

7. Update model IDs:
   - Sonnet: global.anthropic.claude-sonnet-4-6
   - Opus: global.anthropic.claude-opus-4-6-v1
   - Haiku: global.anthropic.claude-haiku-4-5-20251001-v1:0

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

* fix(test): align Bedrock API Key test assertions with preset implementation

The API Key preset was refactored to use standard UI input (apiKey: "")
instead of template variables, but the tests were not updated accordingly.

---------

Co-authored-by: root <root@ip-10-0-11-189.ap-northeast-1.compute.internal>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-02-24 21:11:18 +08:00
Jason e1e2bdef2a fix(about): show update badge instead of green check when newer version available 2026-02-24 10:23:18 +08:00
Jason c380528a27 feat(workspace): make directory paths clickable and rename "Today's Note" to "Add Memory"
Add open_workspace_directory Tauri command to open workspace/memory dirs
in the system file manager. Rename dailyMemory.createToday across all locales.
2026-02-24 09:45:10 +08:00
Jason a8dbea1398 feat(workspace): add full-text search for daily memory files
Add backend search command that performs case-insensitive matching
across all daily memory files, supporting both date and content queries.
Frontend includes animated search bar (⌘F), debounced input, snippet
display with match count badge, and search state preservation across
edits.
2026-02-24 09:03:30 +08:00
Jason 7138aca310 feat(preset): update domestic model providers to latest versions
- MiniMax: M2.1 → M2.5
- Zhipu GLM: glm-4.7 → glm-5
- BaiLing: Ling-1T → Ling-2.5-1T
- DouBaoSeed: doubao-seed-code-preview-latest → doubao-seed-2-0-code-preview-latest
- Qwen (Bailian): qwen3-max → qwen3.5-plus
2026-02-23 22:39:42 +08:00
Jason Young 992dda5c5c refactor(provider): switch from full config overwrite to partial key-field merging (#1098)
* refactor(provider): switch from full config overwrite to partial key-field merging

Replace the provider switching mechanism for Claude/Codex/Gemini from
full settings_config overwrite to partial key-field replacement, preserving
user's non-provider settings (plugins, MCP, permissions, etc.) across switches.

- Add write_live_partial() with per-app implementations for Claude (JSON env
  merge), Codex (auth replace + TOML partial merge), and Gemini (env merge)
- Add backfill_key_fields() to extract only provider-specific fields when
  saving live config back to provider entries
- Update switch_normal, sync_current_to_live, add, update to use partial merge
- Remove common config snippet feature for Claude/Codex/Gemini (no longer
  needed with partial merging); preserve OMO common config
- Delete 6 frontend files (3 components + 3 hooks), clean up 11 modified files
- Remove backend extract_common_config_* methods, 3 Tauri commands,
  CommonConfigSnippets struct, and related migration code
- Update integration tests to validate key-field-only backfill behavior

* refactor(cleanup): remove dead code and redundant MCP sync after partial-merge refactor

- Remove ConfigService legacy full-overwrite sync methods (~150 lines)
- Remove redundant McpService::sync_all_enabled from switch_normal
- Switch proxy fallback recovery from write_live_snapshot to write_live_partial
- Remove dead ProviderService::write_gemini_live wrapper
- Update tests to reflect partial-merge behavior (MCP preserved, not re-synced)

* feat(claude): add Quick Toggles for common Claude Code preferences

Add checkbox toggles for hideAttribution, alwaysThinking, and
enableTeammates that write directly to the live settings file via
RFC 7396 JSON Merge Patch. Mirror changes to the form editor using
form.watch for reactive updates.

* fix(provider): add missing key fields to partial-merge constants

Add provider-specific fields verified against official docs to prevent
key residue or loss during provider switching:

- Claude: CLAUDE_CODE_SUBAGENT_MODEL (env), model (top-level)
- Codex: review_model, plan_mode_reasoning_effort
- Gemini: GOOGLE_API_KEY (official alternative to GEMINI_API_KEY)

* fix(provider): expand partial-merge key fields for Bedrock, Vertex, Foundry and behavior settings

Add missing env/top-level fields to CLAUDE_KEY_ENV_FIELDS and
CLAUDE_KEY_TOP_LEVEL so that provider switching correctly replaces
(and clears) credentials and flags for AWS Bedrock, Google Vertex AI,
Microsoft Foundry, and provider behavior overrides like max output
tokens and prompt caching.

* feat(provider): add auth field selector for Claude providers (AUTH_TOKEN / API_KEY)

Allow users to choose between ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY
when creating or editing custom Claude providers, persisted in meta.apiKeyField.

* refactor(preset): remove AiHubMix hardcoded API_KEY in favor of generic auth selector

AiHubMix was the only preset that hardcoded ANTHROPIC_API_KEY before the
generic auth field selector was introduced. Now that users can freely
choose between AUTH_TOKEN and API_KEY via the UI, remove the special-case
and default AiHubMix to the standard ANTHROPIC_AUTH_TOKEN.
2026-02-23 21:57:04 +08:00
Jason 1b20b7ff88 feat(backup): add hourly periodic backup timer during runtime
Previously periodic backup only checked on startup. Now spawns a
tokio interval task that checks every hour while the app is running.
2026-02-23 11:27:28 +08:00
Jason f8820aa22c feat(backup): add independent backup panel, configurable policy, and rename support
Extract backup & restore into a standalone AccordionItem in Advanced settings.
Add configurable auto-backup interval (disabled/6h/12h/24h/48h/7d) and retention
count (3-50) via settings. Add per-backup rename with inline editing UI.
2026-02-23 11:27:28 +08:00
Jason 3afec8a10f feat(backup): add pre-migration backup, periodic backup, backfill warning, and backup management UI
Four improvements to the database backup mechanism:

1. Auto backup before schema migration - creates a snapshot when
   upgrading from an older database version, providing a safety net
   beyond the existing SAVEPOINT rollback mechanism.

2. Periodic startup backup - checks on app launch whether the latest
   backup is older than 24 hours and creates a new one if needed,
   ensuring all users have recent backups regardless of usage patterns.

3. Backfill failure notification - switch now returns SwitchResult with
   warnings instead of silently ignoring backfill errors, so users are
   informed when their manual config changes may not have been saved.

4. Backup management UI - new BackupListSection in Settings > Data
   Management showing all backup snapshots with restore capability,
   including a confirmation dialog and automatic safety backup before
   restore.
2026-02-23 11:27:28 +08:00
Jason 5ebc879f09 feat(settings): add first-run confirmation dialogs for proxy and usage features
Prevent accidental activation of advanced features by showing a one-time
info dialog. Once confirmed, the flag is persisted in settings.json and
the dialog never appears again.

- Proxy: confirmation when toggling proxy server ON for the first time
- Usage: confirmation when enabling usage query inside UsageScriptModal
- Enhanced ConfirmDialog with "info" variant (blue icon + default button)
- Added i18n translations for zh, en, ja
2026-02-23 11:27:28 +08:00
Jason 6b4ba64bbd feat(toolbar): add smooth transition animation for AppSwitcher compact toggle
Replace conditional rendering with always-rendered span driven by CSS
max-width + opacity animation. Add time-lock in useAutoCompact to prevent
ResizeObserver flicker during expand animation.
2026-02-23 11:27:28 +08:00
Jason 5763b9094b fix(toolbar): remove height constraint that clipped AppSwitcher
The toolbar wrapper's fixed h-[32px] was smaller than AppSwitcher's
natural 40px height (32px buttons + 8px padding), causing visual
clipping. Removed the constraint and let flex layout handle sizing
within the 64px header.
2026-02-23 11:27:28 +08:00
Jason ce92f37ef0 feat(toolbar): auto-compact AppSwitcher based on available width
Replace hardcoded app count threshold with ResizeObserver-based
detection. Uses a two-layer layout (overflow-hidden outer + shrink-0
inner) to avoid the compact/normal oscillation problem.
2026-02-23 11:27:28 +08:00
Jason 2e676e5f53 feat(sessions): add session browsing for Gemini CLI 2026-02-23 11:27:28 +08:00
Jason c3f29a62d1 feat(sessions): default filter to current app when entering session page
Navigate directly to the active app's sessions instead of showing all.
2026-02-23 11:27:28 +08:00
Jason 165af5eec4 feat(sessions): add session browsing for OpenCode and OpenClaw
Add two new session providers following the existing convention-based
pattern. OpenCode reads three-layer JSON storage, OpenClaw parses JSONL
event streams. Wire up backend dispatch, frontend filter dropdown, icon
mappings, toolbar button for OpenClaw, and i18n subtitle updates.
2026-02-23 11:27:28 +08:00
Jason 8b9c09d994 feat(toolbar): add fade transition when switching between OpenClaw and other apps 2026-02-23 11:27:28 +08:00
Jason a8d391bd74 refactor(settings): split Data accordion into Import/Export and Cloud Sync 2026-02-23 11:27:28 +08:00
Jason 7d9b20721e refactor(settings): split Advanced tab into Proxy tab and move Pricing to Usage
Extract proxy-related accordion items (Local Proxy, Failover, Rectifier,
Global Outbound Proxy) into a dedicated Proxy tab via ProxyTabContent
component. Move Pricing config panel to UsageDashboard as a collapsible
accordion. This reduces SettingsPage from ~716 to ~426 lines and improves
settings discoverability with a 5-tab layout: General | Proxy | Advanced |
Usage | About.
2026-02-23 11:27:28 +08:00
Kelvin Chiu d11df17b5d feat: more granular local environment checks (#870)
* feat: more granular local environment checks

* refactor: improve PR #870 with i18n, shadcn Select, and testable helpers

- Extract is_valid_shell, is_valid_shell_flag, default_flag_for_shell
  to module-level #[cfg(windows)] functions for testability
- Add unit tests for extracted helper functions
- Replace native <select> with shadcn/ui Select components
- Extract env badge ternary to ENV_BADGE_CONFIG Record lookup
- Add i18n keys for env badges and WSL selectors (zh/en/ja)
- Unify initial useEffect load path with loadAllToolVersions()

* fix: prevent useEffect re-firing on wslShellByTool changes

The useEffect that loads initial tool versions depended on
loadAllToolVersions, which in turn depended on wslShellByTool.
This caused a full re-fetch of all 4 tools every time the user
changed a WSL shell or flag, racing with the single-tool refresh.

Fix: use empty deps [] since this is a mount-only effect. The
refresh button and shell/flag handlers cover subsequent updates.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-02-23 11:26:23 +08:00
Jason 4c88174cb0 refactor(provider): replace startup auto-import with manual import button
Remove the startup loop in lib.rs that auto-imported default providers
for Claude/Codex/Gemini. Move config snippet extraction logic into the
import_default_config command so it works when triggered manually.

Add an "Import Current Config" button to ProviderEmptyState, wired via
useMutation in ProviderList (shown only for standard apps). Update i18n
keys (zh/en/ja) with new button labels and revised empty state text.
2026-02-20 22:01:18 +08:00
Jason 5a72888852 fix(query): remove auto-import side effect from useProvidersQuery queryFn
Users now trigger provider import manually via the empty state button,
keeping queryFn pure and preventing unintended imports on mount/refocus.
2026-02-20 21:57:45 +08:00
Jason 54f1bfb5d0 chore(tray): hide Auto Failover shortcut from tray menu
The Auto (Failover) toggle in the system tray is no longer shown.
The feature remains fully functional via the Settings page.
All related backend code (handle_auto_click, AUTO_SUFFIX, etc.)
is preserved for easy re-enablement.
2026-02-20 20:08:54 +08:00
Jason 4efab15174 refactor(openclaw): make primary model read-only in Agents panel
The primary model field in the Agents defaults panel now displays as
read-only, eliminating the duplicate edit entry with the "Set as Default
Model" button on provider cards. Fallback models and runtime parameters
remain editable.
2026-02-20 16:46:02 +08:00
Jason 357d32c17e fix(i18n): clarify OpenClaw default model button labels
Rename "Enable/Default" to "Set Default/Current Default" across
zh/en/ja locales and widen button to fit longer text.
2026-02-20 11:11:10 +08:00
Jason 7532308519 fix(workspace): sort daily memory by date and inline into file grid
- Sort daily memory list by filename (YYYY-MM-DD.md) instead of mtime
  so editing an older file no longer bumps it to the top
- Move daily memory card inline with workspace MD file buttons
- Shorten card description across all locales
- Defer file creation until user actually saves (no empty file on create)
2026-02-20 10:40:58 +08:00
Jason 4440a14082 chore(ui): exclude OpenClaw from MCP & Skills app toggle lists 2026-02-20 10:40:48 +08:00
Jason d1bb4480db feat(workspace): add daily memory file management for OpenClaw
Add browse, edit, create and delete support for daily memory files
(~/.openclaw/workspace/memory/YYYY-MM-DD.md) in the Workspace panel.
2026-02-20 08:54:53 +08:00
Jason d04c279890 chore(ui): hide proxy/pricing config for OpenCode/OpenClaw providers 2026-02-19 23:34:20 +08:00
Jason 3125b5419c chore(ui): hide stream check / model test config panels
The stream check feature is unreliable due to diverse provider request
formats. Comment out the model test config UI in settings page, provider
advanced config, and the test button in provider actions. Backend code
and i18n keys are preserved for future restoration.
2026-02-19 23:19:44 +08:00
Jason 0fa6b33b5e feat(settings): add enableLocalProxy toggle to gate main page proxy UI
New users often accidentally trigger ProxyToggle/FailoverToggle on the
main page. Add a settings toggle (default off) so the proxy controls
only appear when explicitly enabled. The proxy service start/stop in
settings remains independent of this visibility flag.
2026-02-19 23:06:22 +08:00
Jason 1b71dc721c refactor(omo): deduplicate OMO/OMO Slim via OmoVariant parameterization
Introduce OmoVariant struct with STANDARD/SLIM constants to eliminate
~250 lines of copy-pasted code across DAO, service, commands, and
frontend layers. Adding a new OMO variant now requires only a single
const declaration instead of duplicating ~400 lines.
2026-02-19 21:11:58 +08:00
Jason 8e219b5eb1 feat(omo): add OMO Slim (oh-my-opencode-slim) support
Implement full OMO Slim profile management to align with ai-toolbox:
- Backend: Slim service methods, DAO, Tauri commands, plugin conflict handling
- Frontend: types, API, query hooks, form integration with isSlim parameterization
- Slim variant: 6 agents (no categories), separate config file and plugin name
- Mutual exclusion: standard OMO and Slim cannot coexist as plugins
- i18n: zh/en/ja translations for all Slim agent descriptions
2026-02-19 20:47:55 +08:00
Jason 51476953ae style: apply prettier formatting to App, SettingsPage, useSettings 2026-02-18 23:40:31 +08:00
Jason 0f4ce74916 refactor(forms): extract OpenCode/OMO/OpenClaw state from ProviderForm into dedicated hooks
Split ProviderForm.tsx (2227 → 1526 lines) by extracting:
- opencodeFormUtils.ts: pure functions and default config constants
- useOmoModelSource: OMO model source collection from OpenCode providers
- useOpencodeFormState: OpenCode provider form state and handlers
- useOmoDraftState: OMO profile draft editing state
- useOpenclawFormState: OpenClaw provider form state and handlers
2026-02-18 23:36:36 +08:00
SaladDay 9514d08ef6 fix(settings): normalize SQL import/export dark-mode card (#1067) 2026-02-17 22:52:00 +08:00
Jason adaef3522d fix(ui): add vertical spacing between directory settings sections
Replace React Fragment with a div using space-y-6 to add proper
vertical spacing between the app config directory and directory
override sections in Settings > Advanced > Directory Settings.
2026-02-17 21:55:10 +08:00
Jim Northrup 4c8334c6fd fix: Don't add ?beta=true to OpenAI Chat Completions endpoints (#1052)
Fixes Nvidia provider and other providers using apiFormat="openai_chat".

The ClaudeAdapter::build_url() method was incorrectly adding ?beta=true
to both /v1/messages and /v1/chat/completions endpoints. This caused
the Nvidia provider to fail because:

1. Nvidia uses apiFormat="openai_chat"
2. Requests are transformed to OpenAI format and sent to /v1/chat/completions
3. The URL gets ?beta=true appended (Anthropic-specific parameter)
4. Nvidia's API rejects requests with this parameter

Fix:
- Only add ?beta=true to /v1/messages endpoint
- Exclude /v1/chat/completions from getting this parameter

Tested:
- Anthropic /v1/messages still gets ?beta=true ✓
- OpenAI Chat Completions /v1/chat/completions does NOT get ?beta=true ✓
- All 13 Claude adapter tests pass ✓

Co-authored-by: jnorthrup <jnorthrup@example.com>
2026-02-16 22:53:08 +08:00
Jason 6caf843843 docs: sync SSSAiCode sponsor update across all README languages 2026-02-16 21:34:43 +08:00
Jason 6c38a8fd24 docs: add SSSAiCode sponsor across all README languages 2026-02-16 00:10:38 +08:00
Jason 977813f725 docs: sync Crazyrouter sponsor update across all README languages 2026-02-15 23:47:40 +08:00
JIA-ss 11f1ef33e4 feat(ui): add quick config toggles to Claude config editor (#1012)
Add 3 quick-toggle checkboxes above the JSON editor in Claude provider settings:
- Hide AI Attribution (sets attribution.commit/pr to empty string)
- Extended Thinking (sets alwaysThinkingEnabled to true)
- Teammates Mode (sets env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS to "1")

Uses local state to keep toggles and JsonEditor in sync without
triggering ProviderForm re-renders. Includes i18n for zh/en/ja.

Co-authored-by: Jason <farion1231@gmail.com>
2026-02-15 22:10:40 +08:00
SaladDay 20f62bf4f8 feat(webdav): follow-up 补齐自动同步与大文件防护 (#1043)
* feat(webdav): add robust auto sync with failure feedback

(cherry picked from commit bb6760124a62a964b36902c004e173534910728f)

* fix(webdav): enforce bounded download and extraction size

(cherry picked from commit 7777d6ec2b9bba07c8bbba9b04fe3ea6b15e0e79)

* fix(webdav): only show auto-sync callout for auto-source errors

* refactor(webdav): remove services->commands auto-sync dependency
2026-02-15 20:58:17 +08:00
Dex Miller 508aa6070c Fix/skill zip symlink resolution (#1040)
* fix(skill): resolve symlinks in ZIP extraction for GitHub repos (#1001)

- detect symlink entries via is_symlink() during ZIP extraction and collect target paths

- add resolve_symlinks_in_dir() to copy symlink target content into link location

- canonicalize base_dir to fix macOS /tmp → /private/tmp path comparison issue

- add path traversal safety check to block symlinks pointing outside repo boundary

- apply symlink resolution to both download_and_extract and extract_local_zip paths

Closes https://github.com/farion1231/cc-switch/issues/1001

* fix(skill): change search to match name and repo instead of description

* feat(skill): support importing skills from ~/.agents/skills/ directory

- Scan ~/.agents/skills/ in scan_unmanaged() for skill discovery
- Parse ~/.agents/.skill-lock.json to extract repo owner/name metadata
- Auto-add discovered repos to skill_repos management on import
- Add path field to UnmanagedSkill to show discovered location in UI

Closes #980

* fix(skill): use metadata name or ZIP filename for root-level SKILL.md imports (#1000)

When a ZIP contains SKILL.md at the root without a wrapper directory,
the install name was derived from the temp directory name (e.g. .tmpDZKGpF).
Now falls back to SKILL.md frontmatter name, then ZIP filename stem.

* feat(skill): scan ~/.cc-switch/skills/ for unmanaged skill discovery and import

* refactor(skill): unify scan/import logic with lock file skillPath and repo saving

- Deduplicate scan_unmanaged and import_from_apps using shared source list
- Replace hand-written AppType match with as_str() and AppType::all()
- Extract read_skill_name_desc, build_repo_info_from_lock, save_repos_from_lock helpers
- Add SkillApps::from_labels for building enable state from source labels
- Parse skillPath from .skill-lock.json for correct readme URLs
- Save skill repos to skill_repos table in both import and migration paths

* fix(skill): resolve symlink and path traversal issues in ZIP skill import

* fix(skill): separate source path validation and add canonicalization for symlink safety
2026-02-15 20:57:14 +08:00
makoMako 7b20c17ea4 fix(opencode): 补齐 install.sh 安装路径检测 (#988)
补齐 OpenCode 路径扫描来源(按官方 install.sh 优先级):
  OPENCODE_INSTALL_DIR > XDG_BIN_DIR > ~/bin > ~/.opencode/bin
保留并增强 Go 安装路径扫描(~/go/bin、GOPATH/*/bin)。

区分单值环境变量(push_env_single_dir)与 path-list 环境变量
(extend_from_path_list),避免对 OPENCODE_INSTALL_DIR 等单值
变量误用 split_paths。

增加路径去重逻辑(push_unique_path),避免重复扫描。

增加跨平台可执行候选逻辑(tool_executable_candidates):
  Windows: .cmd / .exe / 裸命令
  Unix:    裸命令

将 PATH 拼接提至外层循环,减少重复 syscall。

增加单元测试覆盖路径拼装、去重及 Windows 候选顺序。

Closes #958

Co-authored-by: Warp <agent@warp.dev>
2026-02-14 22:35:20 +08:00
Jason 5a17a67b8b fix: deduplicate OpenCodeModel import after rebase 2026-02-14 15:32:17 +08:00
Jason dca12b9f7d feat(openclaw): add 13 new provider presets
Migrate missing providers from Claude/Codex/Gemini/OpenCode presets:

Tier 1 Partners:
- RightCode (anthropic-messages)
- AICodeMirror (anthropic-messages)
- Zhipu GLM en (openai-completions, international)
- MiniMax en (openai-completions, international)

Tier 2 Chinese Officials:
- Kimi For Coding, KAT-Coder, Longcat, DouBaoSeed,
  BaiLing, Xiaomi MiMo

Tier 3 Aggregators:
- SiliconFlow, SiliconFlow en, Nvidia
2026-02-14 15:32:17 +08:00
Jason f974d203a8 fix(openclaw): remove /v1 from anthropic-messages provider baseUrls
Anthropic SDK auto-appends /v1 to baseUrl, so including it in the
preset causes double-path (/v1/v1/messages). Affects AiHubMix, DMXAPI,
PackyCode, Cubence, and AIGoCode.
2026-02-14 15:32:17 +08:00
Jason 44ba9468b5 refactor(openclaw): move model detail fields into advanced options
Keep only model ID and display name visible by default,
collapse context window, max tokens, reasoning, and cost
fields into the advanced options section.
2026-02-14 15:32:17 +08:00
Jason 5081206176 fix(openclaw): address code review findings across P0-P3 issues
- Add 25 missing i18n keys for OpenClawFormFields in all 3 locales (P0)
- Replace key={index} with stable crypto.randomUUID() keys in EnvPanel,
  ToolsPanel, and OpenClawFormFields to prevent list state bugs (P1)
- Exclude openclaw from ProxyToggle/FailoverToggle in App.tsx (P1)
- Add merge_additive_config() for openclaw/opencode deep link imports (P1)
- Normalize serde(flatten) field naming to `extra` + HashMap (P2)
- Add directory existence check in remove_openclaw_provider_from_live (P2)
- Remove dead code in import_default_config and openclaw API methods (P2)
- Add duplicate key validation in EnvPanel before save (P2)
- Add openclawConfigDir to Settings type (P2)
- Add staleTime to OpenClaw query hooks (P3)
- Fix type-unsafe delete via destructuring in mutations.ts (P3)
2026-02-14 15:32:17 +08:00
Jason 00b424628f refactor(openclaw): migrate config panels to TanStack Query hooks
Centralize query keys and extract reusable hooks (useOpenClaw.ts),
replacing manual useState/useEffect load/save patterns in Env, Tools,
and AgentsDefaults panels for consistency with MCP/Skills modules.
2026-02-14 15:32:17 +08:00
Jason bc87f9d9eb fix(openclaw): address code review findings for robustness
- Fix EnvPanel visibleKeys using entry key name instead of array index
  to prevent visibility state corruption after deletion
- Add NaN guard in AgentsDefaultsPanel numeric field parsing
- Validate provider id and models before importing from live config
- Upgrade import failure log level from debug to warn for OpenCode/OpenClaw
2026-02-14 15:32:17 +08:00
Jason eccb95b83d fix(openclaw): enable scrolling on config panels
Add overflow-y-auto to main content area so OpenClaw panels
(Env, Tools, Agents) can scroll when content exceeds viewport.
2026-02-14 15:32:17 +08:00
Jason 2b1f0f0f7e feat(openclaw): add Env/Tools/Agents config panels
- Migrate OpenClaw commands from provider.rs to dedicated commands/openclaw.rs
- Add backend types and read/write for env, tools, agents.defaults sections
- Create EnvPanel (API key + custom vars KV editor)
- Create ToolsPanel (profile selector + allow/deny lists)
- Create AgentsDefaultsPanel (default model + runtime parameters)
- Extend App.tsx menu bar with Env/Tools/Agents buttons
- Remove Prompts button for OpenClaw (overlaps with Workspace AGENTS.md)
2026-02-14 15:32:17 +08:00
Jason 9035784aa4 feat(openclaw): extend workspace files with HEARTBEAT/BOOTSTRAP/BOOT
Add 3 new markdown files to the workspace whitelist and frontend grid:
- HEARTBEAT.md: activity runlist
- BOOTSTRAP.md: first-run ritual
- BOOT.md: gateway restart checklist

Update i18n for all 3 locales (zh, en, ja).
2026-02-14 15:32:17 +08:00
Jason a61892e46a style: format appConfig array to multi-line 2026-02-14 15:32:17 +08:00
Jason 4f2812f472 feat(openclaw): show only Workspace button in menu bar
Hide Skills, Prompts, Sessions, and MCP buttons when OpenClaw is active,
as it only needs Workspace file management functionality.
2026-02-14 15:32:17 +08:00
Jason 705cc8a5af feat(openclaw): add Workspace Files panel for managing bootstrap md files
Add a dedicated panel to read/write OpenClaw's 6 workspace bootstrap files
(AGENTS.md, SOUL.md, USER.md, IDENTITY.md, TOOLS.md, MEMORY.md) directly
from ~/.openclaw/workspace/, with a whitelist-secured backend and Markdown
editor UI. Also fix prompt auto-import missing OpenCode/OpenClaw and the
PromptFormPanel filenameMap type exclusion.
2026-02-14 15:32:17 +08:00
Jason 182015264c fix(openclaw): add openclaw to all Record<AppId, T> usages
Expand McpApps interface, APP_IDS, APP_ICON_MAP, enabledCounts
initializers, and test mock data to include the openclaw key,
resolving TypeScript errors after AppId union was extended.
2026-02-14 15:31:59 +08:00
Jason a33f8fe973 perf: remove unnecessary query cache for Tauri local IPC
Tauri IPC calls are in-process (microsecond latency), so the 5-minute
staleTime and disabled refetchOnWindowFocus from web app templates are
counterproductive. Set staleTime to 0 and enable refetchOnWindowFocus
so external config changes are reflected immediately.
2026-02-14 15:31:59 +08:00
Jason f1fbe324d1 feat(openclaw): add default model button and fix sessionsApi export
- Add "Enable as Default" button to OpenClaw provider cards
- Place enable button before add/remove button for better UX
- Disable remove button when provider is set as default
- Add sessionsApi re-export from api barrel file to fix white screen
- Add i18n keys for default model feature (zh/en/ja)
2026-02-14 15:31:59 +08:00
Jason 26a2fc4fe0 fix(openclaw,opencode): correct Opus pricing and upgrade to Opus 4.6
- Fix Opus pricing from $15/$75 (Opus 4 price) to $5/$25 in openclaw presets
- Upgrade model ID from claude-opus-4-5-20251101 to claude-opus-4-6
- Update all suggestedDefaults references (fallbacks + modelCatalog)
- Apply same model upgrade in opencode presets (7 providers)
2026-02-14 15:31:59 +08:00
Jason 02f9f2e3b8 feat(openclaw): register suggested models to allowlist on provider add
When adding an OpenClaw provider with suggestedDefaults, automatically
merge its model catalog into the allowlist and set the default model
if not already configured.
2026-02-14 15:31:58 +08:00
Jason c431a86064 fix(openclaw): update button state and toast message after switch
Add cache invalidation for openclawLiveProviderIds in useSwitchProviderMutation
to ensure button state updates correctly after adding/removing providers.

Also fix toast message to show "已添加到配置" for OpenClaw (same as OpenCode).
2026-02-14 15:31:58 +08:00
Jason 46ab15f9f6 style: apply code formatting 2026-02-14 15:31:58 +08:00
Jason 7b2cf66812 feat(openclaw): add providerKey input field with validation
- Add providerKey input field in ProviderForm for OpenClaw
- Implement duplicate key detection by querying existing providers
- Add format validation (lowercase letters, numbers, hyphens only)
- Disable field in edit mode (key cannot be changed after creation)
- Update mutations.ts to support OpenClaw providerKey
- Add i18n translations for zh/en/ja
2026-02-14 15:31:58 +08:00
Jason 227f08e910 fix(openclaw): pass providerKey in AddProviderDialog submit handler
The providerKey was only being passed for opencode, causing openclaw
provider creation to fail with "Provider key is required" error.
2026-02-14 15:31:58 +08:00
Jason 392344e1e9 fix(openclaw): prevent creating default provider on first launch
Add additive mode guard in import_default_config() to skip OpenCode
and OpenClaw apps, which should use their dedicated import functions.
2026-02-14 15:31:58 +08:00
Jason 3e58e65284 fix(openclaw): update API protocol values in provider presets
Update anthropic -> anthropic-messages to match OpenClaw gateway config
2026-02-14 15:31:58 +08:00
Jason 512f22e83a feat(openclaw): add provider form fields and UI components
- Add OpenClawFormFields component for provider configuration
- Add Collapsible UI component (radix-ui dependency)
- Update ProviderForm with OpenClaw-specific handlers and preset logic
- Extend OpenClawModel type with reasoning, input, maxTokens fields
- Exclude OpenClaw from universal provider tab in AddProviderDialog
2026-02-14 15:31:58 +08:00
Jason 715e9e89c4 feat(openclaw): add additive mode frontend support
- Add getOpenClawLiveProviderIds() API for querying live config
- Update ProviderList to query OpenClaw live IDs
- Rename isOpenCodeMode to isAdditiveMode (covers OpenCode + OpenClaw)
- Update ProviderCard shouldAutoQuery and isActiveProvider logic
- Update App.tsx onRemoveFromConfig and invalidateQueries for OpenClaw
2026-02-14 15:31:58 +08:00
Jason 47f2c47a2f feat(openclaw): add agents.defaults config support
- Add types for default model config (primary + fallbacks)
- Add types for model catalog/allowlist with aliases
- Extend OpenClawModelEntry with cost and contextWindow fields
- Add Tauri commands: get/set_openclaw_default_model, get/set_openclaw_model_catalog
- Create frontend API (src/lib/api/openclaw.ts)
- Add suggestedDefaults to provider presets with model metadata
- Add i18n translations (zh/en/ja) for openclawConfig.*
2026-02-14 15:31:58 +08:00
Jason 52db7941ea fix(ui): update OpenClaw icon in icon index
Replace old pixel-art style icon with new gradient lobster icon
to match the SVG added in 2dad4729.
2026-02-14 15:31:58 +08:00
Jason 27bcfcb2b8 fix(ui): add OpenClaw to app switcher
Add "openclaw" to ALL_APPS array so OpenClaw appears in the main
interface app switcher when enabled in visibility settings.
2026-02-14 15:31:58 +08:00
Jason 9bbb6c51ff feat(ui): add OpenClaw brand icon and component 2026-02-14 15:31:58 +08:00
Jason 5c62c47878 chore(openclaw): remove dead code functions from openclaw_config
Remove 6 unused functions marked with #[allow(dead_code)]:
- get_openclaw_skills_dir: Skills not supported
- get_env_vars/set_env_var: Environment vars unused
- get_mcp_servers/set_mcp_server/remove_mcp_server: MCP not supported

OpenClaw integration only requires provider management functionality.
2026-02-14 15:31:58 +08:00
Jason 95391f19ac fix(tests): add mcp_servers table to v4 migration test fixture
Also includes OpenClaw icon that was added in previous commits.
2026-02-14 15:31:58 +08:00
Jason 28b125b34f fix(openclaw): remove MCP/Skills/Prompts support from OpenClaw
OpenClaw only needs provider management functionality, not MCP, Skills,
or Prompts features. This commit removes the incorrectly added support:

- Revert SCHEMA_VERSION from 6 to 5 (remove v5->v6 migration)
- Remove enabled_openclaw field from mcp_servers and skills tables
- Remove openclaw field from McpApps and SkillApps structs
- Update DAO queries to exclude enabled_openclaw column
- Fix frontend components and types to exclude openclaw from MCP/Prompts
- Update all related test files
2026-02-14 15:31:58 +08:00
Jason d56e0b0344 feat(i18n): add OpenClaw translations
- Add "openclaw": "OpenClaw" to apps translations in zh.json
- Add "openclaw": "OpenClaw" to apps translations in en.json
- Add "openclaw": "OpenClaw" to apps translations in ja.json
2026-02-14 15:31:58 +08:00
Jason fedb08e846 feat(ui): add OpenClaw support to frontend components
- Update App.tsx with openclaw visibility and skills fallback
- Add OpenClaw to AppSwitcher icon and display name maps
- Update McpFormModal with openclaw in enabled apps
- Update PromptFormModal/Panel with openclaw filename map
- Update EndpointSpeedTest with openclaw timeout
- Update AppVisibilitySettings with openclaw toggle
- Update test state with openclaw defaults
2026-02-14 15:31:58 +08:00
Jason 545be56698 feat(presets): add OpenClaw provider presets
- Create openclawProviderPresets.ts with provider templates
- Include Chinese officials (DeepSeek, Zhipu, Qwen, Kimi, MiniMax)
- Include aggregators (AiHubMix, DMXAPI, OpenRouter, ModelScope)
- Include third party partners (PackyCode, Cubence, AIGoCode)
- Include OpenAI Compatible custom template
2026-02-14 15:31:58 +08:00
Jason 31ec5d73a6 feat(types): add OpenClaw TypeScript type definitions
- Add OpenClawProviderConfig and OpenClawModel interfaces
- Add openclaw to McpApps, VisibleApps, ProxyTakeoverStatus
- Add "openclaw" to AppId union type
- Add openclaw to SkillApps interface
2026-02-14 15:31:58 +08:00
Jason 6952360f70 feat(backend): add OpenClaw support to commands and deeplinks
- Register openclaw_config module in lib.rs
- Add OpenClaw commands and provider import on startup
- Add OpenClaw branches to config and provider commands
- Add build_openclaw_settings() for deeplink imports
- Update MCP handlers with openclaw field in McpApps
- Add OpenClaw prompt file path
2026-02-14 15:31:58 +08:00
Jason e85878e95a feat(services): add OpenClaw branches to backend services
- Add OpenClaw branches to proxy service (not supported)
- Add OpenClaw to MCP service (skip sync, MCP still in development)
- Add OpenClaw skills directory path
- Update ProxyTakeoverStatus with openclaw field
- Add OpenClaw to stream check (not supported)
2026-02-14 15:31:58 +08:00
Jason 433c86b2d3 feat(provider): add OpenClaw provider service support
- Add import_openclaw_providers_from_live() function
- Add remove_openclaw_provider_from_live() function
- Update write_live_snapshot() for OpenClaw
- Add openclaw fields to VisibleApps and AppSettings
- Add get_openclaw_override_dir() function
2026-02-14 15:31:58 +08:00
Jason 63fafd6608 feat(openclaw): add OpenClaw configuration module
- Create openclaw_config.rs for reading/writing OpenClaw config
- Support JSON5 format (~/.openclaw/openclaw.json)
- Implement provider CRUD operations for additive mode
- Add json5 dependency to Cargo.toml
2026-02-14 15:31:58 +08:00
Jason 7f46a0b910 feat(core): add OpenClaw to AppType enum and database schema
- Add OpenClaw variant to AppType enum
- Update is_additive_mode() to return true for OpenClaw
- Update McpApps, SkillApps, McpRoot, PromptRoot structs
- Add database migration v5 to v6 for enabled_openclaw columns
- Update mcp_servers and skills table definitions
2026-02-14 15:31:38 +08:00
Dex Miller 9c34d04def fix(mcp): add missing OpenCode checkbox in MCP add/edit form (#1026)
Fixes https://github.com/farion1231/cc-switch/issues/1020
2026-02-14 15:29:54 +08:00
clx 6098fa7536 Webdav (#923)
* feat: WebDAV backup/restore

- Add WebDAV test/backup/restore commands and settings\n- Fix ja i18n missing keys; decode PROPFIND href as UTF-8\n- Stabilize Windows prompt auto-import tests via CC_SWITCH_TEST_HOME

* chore: format and minor cleanups

* fix: update build config

* feat(webdav): unify sync UX and hardening fixes

* fix(webdav): harden sync flow and stabilize sync UX/tests

* fix(webdav): add resource limits to skills.zip extraction

Prevent zip bomb / resource exhaustion by enforcing:
- MAX_EXTRACT_ENTRIES (10,000 files)
- MAX_EXTRACT_BYTES (512 MB cumulative)

* refactor(webdav): drop deviceId and display deviceName only

---------

Co-authored-by: small-lovely-cat <77799160+small-lovely-cat@users.noreply.github.com>
Co-authored-by: saladday <1203511142@qq.com>
2026-02-14 15:24:24 +08:00
Jason 721771bfe5 docs: add Crazyrouter as sponsor across all READMEs 2026-02-13 23:13:33 +08:00
Jason 1ecc0fff30 docs: update MiniMax sponsor to M2.5 across all READMEs 2026-02-13 22:47:26 +08:00
Jason b0a177725d fix: remove partner status from Zhipu GLM presets 2026-02-13 22:22:24 +08:00
ThendCN 2edee31638 fix(linux): disable WebKitGTK hardware acceleration to prevent white screen (#986)
On some Linux systems with AMD GPUs (e.g., AMD Cezanne/Radeon Vega),
WebKitGTK's GPU process fails to initialize EGL, causing the app to
show a white screen on startup.

Root cause: `amdgpu_query_info(ACCEL_WORKING)` returns EACCES (-13),
which causes EGL display creation to fail with EGL_BAD_PARAMETER,
crashing the GPU process.

Fix: Use WebKitGTK's `set_hardware_acceleration_policy(Never)` API to
disable GPU acceleration on Linux, falling back to software rendering.
This is applied at startup via Tauri's `with_webview` API.

Co-authored-by: Naozhong AI <oursnoah@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 22:53:33 +08:00
Dex Miller 62fa5213bf feat(proxy): fix thinking rectifiers and resolve clippy warnings (#1005)
* feat(proxy): align thinking rectifiers and resolve clippy warnings

- add thinking budget rectifier flow with single retry on anthropic budget errors

- align thinking signature rectification behavior with adaptive-safe handling

- expose requestThinkingBudget in settings/ui/i18n and default rectifier config to disabled

- fix clippy warnings in model_mapper format args and RectifierConfig default derive

* fix(proxy): thinking rectifiers
2026-02-12 22:28:05 +08:00
Dex Miller caba5f51ec feat(omo): improve agent model selection UX and fix lowercase keys (#1004)
* fix(omo): use lowercase keys for builtin agent definitions

OMO config schema expects all agent keys to be lowercase.
Updated OMO_BUILTIN_AGENTS keys (Sisyphus → sisyphus, Hephaestus →
hephaestus, etc.) and aligned Rust test fixtures accordingly.

* feat(omo): add i18n support and tooltips for agent/category descriptions

* feat(omo): add preset model variants for thinking level support

Add OPENCODE_PRESET_MODEL_VARIANTS constant with variant definitions
for Google, OpenAI, and Anthropic models. The omoModelVariantsMap
builder now falls back to presets when config-defined variants are
absent, enabling the variant selector for supported models.

* feat(omo): replace model select with searchable combobox and improve fallback handling

* feat(omo): enrich preset model defaults and metadata fallback

* fix(omo): preserve custom fields and align otherFields import/validation

* fix: resolve omo clippy warnings and include app update
2026-02-12 21:30:59 +08:00
Jason e349012abc docs: add Right Code as sponsor across all READMEs 2026-02-09 22:48:32 +08:00
Jason 594e0d52f7 docs: update sponsor from Zhipu GLM to MiniMax across all READMEs 2026-02-09 22:31:56 +08:00
Jason 11404d4d96 fix(ui): only show session manager button for Claude and Codex apps
Session manager backend only supports Claude and Codex providers.
Hide the nav button for Gemini/OpenCode with animated transition,
and auto-fallback to providers view when switching apps.
2026-02-09 22:12:54 +08:00
Dex Miller 0fcb1b01e2 docs: add user manual documentation (#979)
* docs: add user manual documentation

Add comprehensive user manual covering getting started, provider management,
extensions (MCP/prompts/skills), proxy configuration, and FAQ sections.
Includes screenshots and a README index.

* fix(docs): align user manual with v3.10.3 codebase

- Add OpenCode as 4th supported app throughout all docs
- Fix proxy default port 15762 → 15721
- Update Claude presets (9 → 26), Codex (3 → 10), Gemini (3 → 7)
- Add OpenCode presets (25 entries)
- Fix timeout defaults and ranges (stream first byte 60s/90s, etc.)
- Fix circuit breaker defaults with per-app values (Claude vs general)
- Fix Skills support: all 4 apps, not just Claude/Codex
- Remove non-existent Gemini authMode field
- Fix prompt deletion behavior: enabled prompts cannot be deleted
- Remove non-existent Legacy deeplink protocol, use V1 only
- Fix DB table names (usage_logs → proxy_request_logs) and add missing tables
- Fix migration version v3.8.0 → v3.7.0
- Add missing V1 deeplink parameters (config, configFormat, etc.)
- Update doc version v3.9.1 → v3.10.3
- Add claude-opus-4-1 to pricing table
- Fix recovery wait time range 10-300 → 0-300

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-02-09 15:01:15 +08:00
Dex Miller ea20b0aec2 fix(skill): correct skill doc URL branch and path resolution (#977)
Use the actual branch returned by download_repo instead of the
configured branch, fixing 404s when repos default to master but
the URL was hardcoded to main. Also switch URL format from /tree/
to /blob/ and always point to the SKILL.md file.

Closes farion1231/cc-switch#968
2026-02-09 12:30:17 +08:00
Dex Miller ed47480fc7 feat(omo): integrate Oh My OpenCode profile management (#972)
* feat(omo): integrate Oh My OpenCode profile management into Provider system

Adds full-stack OMO support: backend config read/write/import, OMO-specific
provider CRUD with exclusive switching, frontend profile editor with
agent/category/model configuration, global config management, and i18n support.

* feat(omo): add model/variant dropdowns from enabled providers

Replace model text inputs with Select dropdowns sourced from enabled
OpenCode providers, add thinking-level variant selection, and prevent
auto-enabling newly added OMO providers.

* fix(omo): use standard provider action styles for OMO switch button

* fix(omo): replace hardcoded isZh strings with proper i18n t() calls
2026-02-09 12:18:20 +08:00
makoMako 5502c74a79 feat: rename Qwen Coder preset to Bailian (#965)
- replace Qwen Coder preset with Bailian for Claude and OpenCode
- add Bailian icon asset and metadata mapping
- remove Bailian preset default model values
- rename Claude preset Kimi k2 to Kimi
2026-02-08 23:32:40 +08:00
myjustify fa7c9514cc feat(env): add Volta package manager path detection (#969)
Add ~/.volta/bin to CLI version scanning paths to support tools
installed via Volta (claude, codex, gemini, etc.).
2026-02-08 23:30:53 +08:00
Dex Miller d82027f107 feat(pricing): add claude-opus-4-6 and gpt-5.3-codex models, use incremental seeding (#943)
- Add claude-opus-4-6-20260206 pricing (same as opus-4-5)
- Add gpt-5.3-codex series pricing (same as gpt-5.2-codex)
- Change seed_model_pricing to INSERT OR IGNORE for incremental upsert
- Remove count==0 guard in ensure_model_pricing_seeded so new models
  are appended on every startup without overwriting user customizations
2026-02-07 11:06:48 +08:00
Jason ded9980fbf fix(provider): remove /v1 suffix from AIGoCode OpenCode base URL 2026-02-06 22:39:07 +08:00
Jason 3d91c381d9 fix(provider): unify AIGoCode API base URLs to https://api.aigocode.com 2026-02-06 22:39:07 +08:00
funnytime b8538a6996 feat: circular reveal animation for theme switching (#905) 2026-02-06 22:14:29 +08:00
Dex Miller 87b80c66b2 feat(usage): enhance dashboard with auto-refresh control and robust formatting (#942)
* style: format code and apply clippy lint fixes

* feat(usage): enhance dashboard with auto-refresh control and robust formatting

- Add configurable auto-refresh interval toggle (off/5s/10s/30s/60s) to usage dashboard
- Extract shared format utilities (fmtUsd, fmtInt, parseFiniteNumber, getLocaleFromLanguage)
- Refactor request log time filtering to rolling vs fixed mode with validation
- Use stable serializable query keys instead of filter objects
- Handle NaN/Infinity safely in number formatting across all usage components
- Use RFC 3339 date format in backend trend data
2026-02-06 22:00:33 +08:00
Dex Miller 14fa749ca9 fix(opencode): reject save when no models configured (#932)
Add validation to require at least one model before saving an OpenCode
provider. Shows a localized toast error when models are empty.
2026-02-06 16:03:39 +08:00
Dex Miller 95bc0e38df style: format code and apply clippy lint fixes (#941) 2026-02-06 16:02:57 +08:00
Jason 92785a8078 docs: add AICoding.sh sponsor to README files
Add AICoding.sh as a new sponsor with translations for all three
language versions (EN, ZH, JA).
2026-02-04 21:49:00 +08:00
Jason 1d97570a94 refactor(terminal): unify terminal selection using global settings
- Remove terminal selector from Session Manager page
- Backend now reads terminal preference from global settings
- Add terminal name mapping (iterm2 → iterm) for compatibility
- Add WezTerm support to macOS terminal options
- Add WezTerm translations for zh/en/ja
2026-02-04 11:03:44 +08:00
Jason d98183f3da fix(i18n): replace hardcoded Chinese strings in Session Manager
- Add i18n keys for relative time (justNow, minutesAgo, hoursAgo, daysAgo)
- Add i18n keys for role labels (roleUser, roleSystem, roleTool)
- Add i18n keys for UI elements (tocTitle, searchSessions, clickToCopyPath)
- Update formatRelativeTime and getRoleLabel to accept t function
- Add useTranslation hook to SessionToc component
2026-02-04 11:03:43 +08:00
Jason 68a0c304d8 feat(ui): hide provider test button
Provider request formats are complex and varied, making it difficult
to create a unified test mechanism. Users may incorrectly assume
request format issues indicate provider unavailability.

Code is commented out (not deleted) for easy restoration if needed.
2026-02-04 11:03:43 +08:00
Jason 60007ee4e8 fix(windows): restore default home dir resolution to prevent data loss
v3.10.3 introduced HOME env priority on Windows for test isolation,
which caused database path to change when HOME differs from USERPROFILE
(common in Git/MSYS environments), making providers appear to disappear.

Changes:
- Use CC_SWITCH_TEST_HOME for test isolation instead of HOME
- Add legacy fallback to detect v3.10.3 database location on Windows
- Add logging for legacy path detection to aid debugging
2026-02-04 11:03:43 +08:00
funnytime 7bd29d721e fix: prevent window flicker on silent startup (#901)
Closes #892
2026-02-04 10:37:54 +08:00
funnytime c153e7104e fix: titlebar does not follow theme in dark mode (#903) 2026-02-04 10:37:14 +08:00
PeanutSplash e65360e68a refactor(ui): extract shared components and deduplicate MCP/Skills panels (#897)
* refactor(ui): add tooltips and icons to MCP and Skills panels

* refactor: deduplicate UnifiedSkillsPanel and UnifiedMcpPanel shared code
2026-02-04 10:10:45 +08:00
TinsFox f0e8ba1d8f feat: session manger (#867)
* feat: init session manger

* feat: persist selected app to localStorage

- Save app selection when switching providers
- Restore last selected app on page load

* feat: persist current view to localStorage

- Save view selection when switching tabs
- Restore last selected view on page load

* styles: update ui

* feat: Improve macOS Terminal activation and refactor Kitty launch to use  command with user's default shell.

* fix: session view

* feat: toc

* feat: Implement FlexSearch for improved session search functionality.

* feat: Redesign session manager search and filter UI for a more compact and dynamic experience.

* refactor: modularize session manager by extracting components and utility functions into dedicated files.

* feat: Enhance session terminal launching with support for iTerm2, Ghostty, WezTerm, and Alacritty, including UI and custom configuration options.

* feat: Conditionally render terminal selection and resume session buttons only on macOS.
2026-02-02 11:12:30 +08:00
Jassy930 58153333ce fix(stream_check): respect auth_mode for Claude health checks (#824)
Previously, check_claude_stream always added the x-api-key header,
ignoring the provider's auth_mode setting. This caused health check
failures for proxy services that only support Bearer authentication.

Now the function respects the auth.strategy field:
- AuthStrategy::Anthropic: Authorization Bearer + x-api-key
- AuthStrategy::ClaudeAuth: Authorization Bearer only
- AuthStrategy::Bearer: Authorization Bearer only

This aligns with the behavior of ClaudeAdapter::add_auth_headers
and fixes health checks for proxy providers with auth_mode="bearer_only".

Changes:
- Modified check_claude_stream to conditionally add x-api-key header
- Added AuthStrategy import
- Added test_auth_strategy_imports unit test

Tests: All passing (7/7 for stream_check module)

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-02 09:28:04 +08:00
stmoonar d098ecad64 fix(skills): handle Windows path separator in installed status matching (#868)
* fix(skills): handle Windows path separator in installed status matching

Use regex to split directory path by both / and \ to correctly extract
the install name on Windows, fixing the issue where installed skills
were not showing as installed in the discovery page filter.

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

* feat(skills): add repository filter to skills discovery page

- Add dropdown to filter skills by repository (owner/name)
- Extract unique repos from discoverable skills list
- Add truncate style for long repo names with hover title
- Add i18n translations for zh/en/ja

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-02 09:05:05 +08:00
makoMako 809a1fcf84 feat(ui): dynamic endpoint hint based on API format selection (#860)
- Add apiHintOAI i18n key for OpenAI Chat Completions format hint
- Update ClaudeFormFields to show format-specific endpoint hints
- When API format is "openai_chat", show OAI-specific hint
- Maintains consistency between hint and selected API format

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-01 11:21:43 +08:00
Jason e5fea048a1 fix(ci): add xdg-utils for ARM64 AppImage and suppress dead_code warnings
- Add xdg-utils dependency for xdg-mime binary required by AppImage bundler
- Remove unused McpStatus struct from gemini_mcp.rs (duplicate of claude_mcp.rs)
- Add #![allow(dead_code)] to proxy models reserved for future type-safe API
2026-01-31 21:26:24 +08:00
Jason b8bd1d30d9 docs(changelog): add Linux ARM64 and error display fix to v3.10.3 2026-01-31 20:46:20 +08:00
Jason 4abf259a6d feat(ci): add Linux ARM64 build support
- Add ubuntu-22.04-arm runner to build matrix
- Rename Linux artifacts with architecture suffix (x86_64/arm64)
- Update pnpm cache key with runner.arch to avoid cross-arch pollution
- Add linux-aarch64 platform to latest.json for Tauri updater
2026-01-31 20:38:18 +08:00
Jason faa82a5b86 fix(mutations): use extractErrorMessage for complete error display
Provider add/update/delete mutations were using error.message directly,
which doesn't extract Tauri invoke errors properly. Now using the same
extractErrorMessage pattern as the rest of the codebase.
2026-01-31 20:15:39 +08:00
Jason b5b45c2703 chore: bump version to 3.10.3
- Update version in package.json, Cargo.toml, and tauri.conf.json
- Add missing changelog entries for OpenCode API key link and AICodeMirror preset
- Fix Prettier formatting for new hook files
2026-01-31 17:29:09 +08:00
Jason bd8a323600 feat(opencode): add API key link support for OpenCode provider form
Enable API key link feature for OpenCode app, allowing users to access
provider websites for key registration directly from the form.
2026-01-31 17:16:36 +08:00
Jason 151e43a808 feat(providers): add AICodeMirror partner preset for all apps
Register AICodeMirror icon, add i18n partner promotion texts (zh/en/ja),
and fix trailing whitespace in codexProviderPresets.
2026-01-31 16:05:50 +08:00
Jason 9d2bf08fe0 docs(changelog): release v3.10.3
Add changelog entry for v3.10.3 feature release including:
- API format selector and presets
- Pricing config enhancement
- Skills ZIP install
- Preferred terminal selection
- Silent startup option
- OpenCode environment check and directory sync
- NVIDIA NIM and n1n.ai presets
- Multiple bug fixes for Codex, proxy URL, tray menu, etc.
2026-01-30 23:18:22 +08:00
Jason 05c21e016f feat(settings): add OpenCode support to environment check and one-click install
- Add OpenCode version detection with Go path scanning
- Add GitHub Releases API for fetching latest OpenCode version
- Add OpenCode install command to one-click install section
- Update i18n hints to include OpenCode across all locales
- Fix SettingsPage indentation formatting
2026-01-30 22:23:18 +08:00
Jason 57713dd336 feat(claude): show proxy hint when switching to OpenAI Chat format provider
Display an info toast when switching to a provider that uses OpenAI Chat
format (apiFormat === "openai_chat"), reminding users to enable the proxy
service. Move toast logic from mutation to useProviderActions for better
control over notification content based on provider properties.
2026-01-30 16:40:41 +08:00
Jason 1ed122a8bd refactor(proxy): remove DeepSeek max_tokens clamp from transform layer
The max_tokens restriction was too aggressive and should be handled
upstream or by the provider itself. Simplify anthropic_to_openai by
removing provider parameter since model mapping is already done by
proxy::model_mapper.
2026-01-30 16:40:41 +08:00
Jason 78e341ccb9 feat(providers): add NVIDIA NIM preset for Claude and OpenCode
- Add NVIDIA NIM provider preset with API configuration
- Add nvidia.svg icon and register in icon system
- Add nvidia metadata with keywords and default color (#74B71B)
2026-01-30 16:40:41 +08:00
Jason 162800e18e feat(claude): add apiFormat support for provider presets
Allow preset providers to specify API format (anthropic or openai_chat),
enabling third-party proxy services that use OpenAI Chat Completions format.
2026-01-30 16:40:41 +08:00
Jason 065d5db843 fix(proxy): improve URL building and remove redundant model mapping
- Add model parameter to request logs for better debugging
- Fix duplicate /v1/v1 in URL when both base_url and endpoint have version
- Extend ?beta=true parameter to /v1/chat/completions endpoint
- Remove model mapping from transform layer (now handled by model_mapper)
- Add DeepSeek max_tokens clamping (1-8192 range)
2026-01-30 16:40:41 +08:00
Jason 70a18c1141 refactor(claude): migrate api_format from settings_config to meta
Move api_format storage from settings_config to ProviderMeta to prevent
polluting ~/.claude/settings.json when switching providers.

- Add api_format field to ProviderMeta (Rust + TypeScript)
- Update ProviderForm to read/write apiFormat from meta
- Maintain backward compatibility for legacy settings_config.api_format
  and openrouter_compat_mode fields (read-only fallback)
- Strip api_format from settings_config before writing to live config
2026-01-30 16:40:41 +08:00
Jason 964767ebaf fix(i18n): update apiFormatOpenAIChat label to mention proxy requirement
Change label from "Requires conversion" to "Requires proxy" for clarity:
- zh: "需转换" → "需开启代理"
- en: "Requires conversion" → "Requires proxy"
- ja: "変換が必要" → "プロキシが必要"
2026-01-30 16:40:41 +08:00
Jason 0c25687e09 fix(claude): improve backward compatibility for openrouter_compat_mode
Extend backward compatibility support for legacy openrouter_compat_mode field:
- Support number type (1 = enabled, 0 = disabled)
- Support string type ("true"/"1" = enabled)
- Add corresponding test cases for number and string types
2026-01-30 16:40:41 +08:00
Jason 81b975c47c feat(claude): add API format selector for third-party providers
Replace the OpenRouter-specific compatibility toggle with a generic
API format selector that allows all Claude providers to choose between:

- Anthropic Messages (native): Direct passthrough, no conversion
- OpenAI Chat Completions: Enables Anthropic ↔ OpenAI format conversion

Changes:
- Add ClaudeApiFormat type ("anthropic" | "openai_chat") to types.ts
- Replace openRouterCompatToggle with apiFormat dropdown in ClaudeFormFields
- Update ProviderForm to manage apiFormat state via settingsConfig.api_format
- Refactor claude.rs: add get_api_format() method, update needs_transform()
- Maintain backward compatibility with legacy openrouter_compat_mode field
- Update i18n translations (zh, en, ja)
2026-01-30 16:40:41 +08:00
n1n.ai e44423c307 feat: add n1n.ai provider preset (#667)
Co-authored-by: n1n <team@n1n.ai>
2026-01-30 12:45:01 +08:00
Jason 08d9bb4cab style(dao): format proxy tests with cargo fmt 2026-01-29 10:09:45 +08:00
Jason 987fc46e06 feat(skills): add install from ZIP file feature
- Add open_zip_file_dialog command for selecting ZIP files
- Add install_from_zip service method with recursive skill scanning
- Add install_skills_from_zip Tauri command
- Add frontend API methods and useInstallSkillsFromZip hook
- Add "Install from ZIP" button in Skills management page
- Support local skill ID format: local:{directory}
- Add i18n translations for new feature and error messages
2026-01-29 10:09:45 +08:00
Jason e3d335be2d feat(settings): prioritize native install path for Claude Code detection
- Move ~/.local/bin to first position in version scan search paths
- Update one-click install commands to use official native installation
  (curl script) instead of npm for Claude Code
2026-01-29 10:09:45 +08:00
Andrew Leng 0dd823ae3a fix(codex): fix 404 errors and connection timeout with custom base_url (#760)
* fix(proxy): fix Codex 404 errors with custom base_url prefixes

- handlers.rs:268: Remove hardcoded /v1 prefix in Codex forwarding
- codex.rs:140: Only add /v1 for origin-only base_urls, dedupe /v1/v1
- stream_check.rs:364: Try /responses first, fallback to /v1/responses
- provider.rs:427: Don't force /v1 for custom prefix base_urls

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

* fix(codex): always add /v1 for custom prefix base_urls

Changed logic to always add /v1 prefix unless base_url already ends with /v1.
This fixes 504 timeout errors with relay services that expect /v1 in the path.

- Most relay services follow OpenAI standard format: /v1/responses
- Users can opt-out by adding /v1 to their base_url configuration
- Updated test case to reflect new behavior

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

* fix(proxy): allow system proxy on localhost with different ports

- Only bypass system proxy if it points to CC Switch's own port (15721)
- Allow other localhost proxies (e.g., Clash on 7890) to be used
- Add INFO level logging for request URLs to aid debugging

This fixes connection timeout issues when using local proxy tools.

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

* fix(codex): don't add /v1 for custom prefix base_urls

Reverted logic to not add /v1 for base_urls with custom prefixes.
Many relay services use custom paths without /v1.

- Pure origin (e.g., https://api.openai.com) → adds /v1
- With /v1 (e.g., https://api.openai.com/v1) → no change
- Custom prefix (e.g., https://example.com/openai) → no /v1

This fixes 404 errors with relay services that don't use /v1 in their paths.

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

* fix(proxy): use dynamic port for system proxy detection

Instead of hardcoding port 15721, now uses the actual configured
listen_port from proxy settings.

- Added set_proxy_port() to update the port when proxy server starts
- Added get_proxy_port() to retrieve current port for detection
- Updated server.rs to call set_proxy_port() on startup
- Updated tests to reflect new behavior

This allows users to change the proxy port in settings without
breaking the system proxy detection logic.

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

* fix(proxy): change default proxy port from 15721 to 5000

Update the default fallback port in get_proxy_port() from 15721 to 5000
to match the project's standard default port configuration.

Also updated test cases to use port 5000 consistently.

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

* fix(proxy): revert default port back to 15721

Revert the default fallback port in get_proxy_port() from 5000 back to 15721
to align with the project's updated default port configuration.

Also updated test cases to use port 15721 consistently.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

---------

Co-authored-by: ozbombor <ozbombor@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 09:10:17 +08:00
方程 164635f638 style(tray): 简化标题标签并优化菜单分隔符 (#796)
Co-authored-by: franco <1787003204@q.comq>
2026-01-28 22:53:38 +08:00
makoMako fcb5163710 fix(settings): correct Gemini default visibility to true (#818)
Frontend fallback value for visibleApps had gemini: false, which was
inconsistent with backend default (gemini: true). This caused Gemini
to be hidden by default on first install.

Fixes #817

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 21:35:10 +08:00
Jason 3095bf8e5c chore(presets): upgrade Kimi/Moonshot providers to k2.5 model
- Update Moonshot preset models from kimi-k2-thinking to kimi-k2.5
- Update OpenCode Kimi preset name and model to k2.5
- Remove explicit model config from Kimi preset (use API defaults)
2026-01-27 23:38:34 +08:00
Jason a48502235c docs(sponsors): add AICodeMirror and reorder sponsor list
- Add AICodeMirror as new sponsor with logo
- Sync changes across all README languages (EN/ZH/JA)
2026-01-27 22:51:22 +08:00
Jason c74f801d66 fix(settings): correct footer layout in advanced settings tab
- Establish proper flexbox height chain from App to SettingsPage
- Move save button to fixed footer outside scrollable area
- Align footer styling with FullScreenPanel for consistency
2026-01-27 10:46:27 +08:00
Dex Miller 785e1b5add Feat/pricing config enhancement (#781)
* feat(db): add pricing config fields to proxy_config table

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

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

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

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

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

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

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

* feat(i18n): add pricing config translations

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

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

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

* style: format code with cargo fmt and prettier

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

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

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-01-27 10:43:05 +08:00
Jason c00f431d67 feat(opencode): sync all providers to live config on directory change
Add additive mode support for OpenCode in sync_current_to_live:
- Add AppType::is_additive_mode() to distinguish switch vs additive mode
- Add AppType::all() iterator to avoid hardcoding app lists
- Add sync_all_providers_to_live() for additive mode apps
- Refactor sync_current_to_live to handle both modes

Frontend changes (directory settings):
- Track opencodeDirChanged in useDirectorySettings
- Trigger syncCurrentProvidersLiveSafe when OpenCode dir changes
- Add i18n strings for OpenCode directory settings
2026-01-26 15:46:51 +08:00
Jason 29a0643d74 refactor(config): consolidate get_home_dir into single public function
Follow-up to #644: Extract duplicate get_home_dir() implementations
into a single pub fn in config.rs, reducing code duplication across
codex_config.rs, gemini_config.rs, and settings.rs.

Also adds documentation comments to build.rs explaining the Windows
manifest workaround for test binaries.
2026-01-26 11:24:28 +08:00
Jason 5e92111771 feat(settings): add preferred terminal selection
Allow users to choose their preferred terminal app for opening
provider terminals. Supports platform-specific options:
- macOS: Terminal.app, iTerm2, Alacritty, Kitty, Ghostty
- Windows: cmd, PowerShell, Windows Terminal
- Linux: GNOME Terminal, Konsole, Xfce4, Alacritty, Kitty, Ghostty

Falls back to system default if selected terminal is unavailable.
2026-01-26 11:20:33 +08:00
Jason beebd9847f refactor(terminal): consolidate redundant terminal launch functions
Merge macOS Alacritty/Kitty/Ghostty launchers into a single generic
`launch_macos_open_app` function with a `use_e_flag` parameter.
Replace Windows cmd/PowerShell/wt launchers with a shared
`run_windows_start_command` helper. Reduces ~98 lines of duplicate code.
2026-01-26 11:20:33 +08:00
Xyfer d99a3c2fee fix(windows): stabilize test environment (#644)
* fix(windows): embed common-controls manifest

* fix(windows): prefer HOME for config paths

* test(windows): fix export_sql invalid path

* fix(windows): remove unused env import in config.rs
2026-01-26 11:18:14 +08:00
funnytime a0ca8c2517 feat: add silent startup option to prevent window popup on launch (issue #708) (#713) 2026-01-26 10:54:59 +08:00
Dex Miller 3434dcb87c fix(skills): prevent duplicate skill installation from different repos (#778)
- Add directory conflict detection before installation
- Fix installed status check to match repo owner and name
- Add i18n translations for conflict error messages
2026-01-25 23:35:04 +08:00
Jason 1c6689a0bc chore: update Cargo.lock version to 3.10.2 2026-01-24 23:49:06 +08:00
Jason 9404341f14 feat(ui): replace update badge dot with ArrowUpCircle icon
- Replace blue dot indicator with lucide ArrowUpCircle icon
- Change color scheme from blue to green for better visibility
- Enlarge button (h-8 w-8) and icon (h-5 w-5) for better UX
- Move UpdateBadge from title area to after settings icon
2026-01-24 23:32:05 +08:00
Jason 53dd0a90f3 chore: release v3.10.2 2026-01-24 22:15:21 +08:00
Jason 779fefd86d feat(skills): add skill sync method setting (symlink/copy)
- Add SyncMethod enum (Auto/Symlink/Copy) in Rust backend
- Implement sync_to_app_dir with symlink support (cross-platform)
- Add SkillSyncMethodSettings UI component (simplified 2-button selector)
- Add i18n support for zh/en/ja
- Replace copy_to_app with configurable sync_to_app_dir
- Add skill_sync_method field to AppSettings

User can now choose between symlink (disk space saving) or copy (best compatibility) in Settings > General.
2026-01-24 18:24:05 +08:00
Jason 096c1d57c4 feat(partner): add RightCode as official partner
Update RightCode referral link to use CCSWITCH affiliate code and mark
as official partner with promotional messages in all supported languages.
2026-01-23 22:59:48 +08:00
Jason adb868d0cf fix(prompt): clear prompt file when all prompts are disabled
When disabling a prompt, check if any other prompts remain enabled.
If all prompts are disabled, clear the prompt file to ensure UI state
matches the actual configuration that Claude Code reads.
2026-01-23 22:43:07 +08:00
Jason a6ad896db0 fix(opencode): preserve extra model fields during serialization
Add `extra` field with serde flatten to OpenCodeModel struct to capture
custom fields like cost, modalities, thinking, and variants that were
previously lost during save operations.
2026-01-23 20:42:50 +08:00
Jason d6cf4390ac fix(form): backfill model fields when editing Claude provider
Use lazy initialization in useState to parse model values from config
on first render, matching the pattern used in useApiKeyState. This
fixes an issue where model fields were not populated in edit mode.
2026-01-23 19:13:38 +08:00
Jason 0ef670325b chore: release v3.10.1
- Bump version to 3.10.1 across all config files
- Update CHANGELOG with all fixes since v3.10.0
- Fix Rust Clippy warning by using derive(Default)
- Apply code formatting
2026-01-23 10:41:38 +08:00
Jason 07fc6b175e fix(proxy): change rectifier default state to disabled
Change the default state of the rectifier from enabled to disabled.
This allows users to opt-in to the rectifier feature rather than having it enabled by default.

Changes:
- Set RectifierConfig::default() enabled and request_thinking_signature to false
- Update serde default attributes from default_true to default
- Update unit tests to reflect new default behavior
2026-01-23 09:45:57 +08:00
Jason 79d3ecc1b8 feat(icons): update RightCode provider icon
- Import new detailed RC icon from rc.svg (128x128 viewBox)
- Add icon configuration to Claude provider preset
- Remove duplicate old RC icon definition to fix TS1117 error
2026-01-23 09:25:09 +08:00
Jason 9c249d9486 fix(ui): increase app icon collapse threshold from 3 to 4
Improve readability by keeping app names visible when 3 apps are shown.
Icons now only collapse to compact mode when 4 or more apps are visible.
2026-01-23 00:12:33 +08:00
Jason 15f60e8ce2 fix(ui): improve ProviderIcon color validation to prevent black icons
Enhance the effectiveColor logic in ProviderIcon to properly validate
the color prop before using it. Now only uses color when it's a valid
non-empty string, otherwise falls back to icon metadata defaultColor.

This fixes the issue where Gemini icons would turn black when selected
in ProviderCard due to null/undefined/empty string color values being
passed through.
2026-01-23 00:02:11 +08:00
Jason 3d733a3b80 fix(ui): unify layout padding across all panels
Remove max-width constraints and standardize padding to px-6 for consistent full-width layout across header and all content panels.
2026-01-22 23:55:19 +08:00
Jason cfb113ac8d fix(settings): reorder window settings and change default values
Move "minimize to tray on close" to the bottom of window settings.
Change skipClaudeOnboarding default to false.
2026-01-22 23:35:41 +08:00
Jason 62a4ab2ad3 fix(terminal): keep Windows terminal window open after execution
Use /K instead of /C flag to prevent cmd window from closing
immediately after batch file execution. Also remove the buggy
errorlevel check that was checking del command's return value
instead of claude's.

Fixes #726
2026-01-22 23:04:18 +08:00
Jason aa0f191420 fix(config): correct OpenCode config path on Windows
OpenCode uses ~/.config/opencode on all platforms, not %APPDATA%\opencode
on Windows. Remove the platform-specific path handling to use unified
~/.config/opencode path across all operating systems.
2026-01-22 17:09:45 +08:00
Jason b8305f281b fix(ui): align panel content with header constraints
Add max-w-[56rem] and mx-auto to Skills, MCP, and Prompts panels
to match the header layout constraints, ensuring the back button
and action buttons align with the content area.
2026-01-22 12:41:06 +08:00
Jason b3af191fab docs: add v3.10.0 release notes in zh/en/ja 2026-01-22 11:58:25 +08:00
Jason e6b6bc18a9 feat(config): add RightCode provider and rename Z.ai GLM
- Add RightCode provider preset with GPT-5.2 models
- Rename "Z.ai GLM" to "Zhipu GLM en" for clarity
2026-01-22 10:35:43 +08:00
Jason b1f7ff4768 fix(config): remove icon config from provider preset
Remove unused icon and iconColor fields from Requesty Cloud preset
2026-01-22 00:07:35 +08:00
Jason 09d8c27972 feat(icons): replace MCP button icon with official MCP logo
Use inline SVG for MCP icon to support currentColor inheritance,
enabling proper hover color transitions.
2026-01-22 00:01:32 +08:00
Jason 9736861ace feat(icons): add new provider icons and fix SiliconFlow iconColor
- Add rc.svg for RightCode (optimized from 96KB to 581 bytes)
- Add catcoder.svg for KAT-Coder (快手)
- Add mcp.svg for Model Context Protocol
- Add siliconflow.svg for SiliconFlow
- Register all new icons in index.ts
- Add icon config for RightCode in claude/codex presets
- Add icon config for KAT-Coder in claude/opencode presets
- Fix SiliconFlow iconColor from #000000 to #6E29F6
2026-01-21 23:36:18 +08:00
Jason fef750bb4c chore: release v3.10.0 2026-01-21 20:01:29 +08:00
Jason 3677bb61f5 refactor(settings): move rectifier section below failover in advanced settings 2026-01-21 18:02:21 +08:00
Jason 2d17bde790 feat(skills): add baoyu-skills preset repo and auto-supplement missing defaults
- Add JimLiu/baoyu-skills to default skill repositories
- Change init_default_skill_repos() from "first-run only" to "supplement missing"
- New preset repos will now auto-appear for existing users on upgrade
2026-01-21 16:20:28 +08:00
Jason dc865fbbbf fix(icon): auto-apply default color from metadata when color prop is not provided
When ProviderIcon is used without a color prop, it now automatically
fetches the defaultColor from icon metadata. This fixes the issue where
Gemini app icon turns black when selected in AppSwitcher, because the
component was inheriting the parent's text-foreground color.
2026-01-21 15:46:54 +08:00
Jason a187380d6f fix(failover): switch to P1 immediately when enabling auto failover
Previously, enabling auto failover kept using the current provider until
the first failure, causing inconsistency when the current provider was
not in the failover queue. When stopping proxy, the restored config
would not match user expectations.

New behavior:
- Enable auto failover = immediately switch to queue P1
- Subsequent routing follows queue order (P1→P2→...)
- Auto-add current provider to queue if queue is empty

Changes:
- Add switch_proxy_target() for hot-switching during proxy mode
- Update provider_router to use queue order when failover enabled
- Sync tray menu Auto click with the same logic
- Update UI tooltips to reflect new semantics
- Add tests for queue-only routing scenario
2026-01-21 11:27:44 +08:00
Jason b993b1f664 chore: fix code formatting and test setup
- Format Rust code with rustfmt (misc.rs, types.rs)
- Format TypeScript/React code with Prettier (4 files)
- Fix ProviderList test by wrapping with QueryClientProvider
2026-01-20 23:40:33 +08:00
Jason 00168877d9 fix(terminal): use temp script files to avoid escaping issues on all platforms
- macOS: Replace inline AppleScript commands with temp .sh script file
- Linux: Use temp .sh script file instead of inline bash -c command
- Windows: Add proper error capturing with output() instead of spawn()
- Remove unused escape_shell_path and generate_wrapper_script functions
- Unified approach across platforms for better maintainability
2026-01-20 22:21:01 +08:00
Jason 4496110dd8 feat(app-switcher): add compact mode for takeover with 3+ visible apps 2026-01-20 22:02:13 +08:00
Jason c9e85e8cac feat(tray): sync tray menu with app visibility settings
Apply visibleApps setting to filter tray menu sections, so hidden apps
no longer appear in the system tray menu.
2026-01-20 21:05:06 +08:00
Jason eab1d08527 feat(settings): add app visibility settings
Allow users to choose which apps (Claude, Codex, Gemini, OpenCode) to display on the homepage.

- Add VisibleApps type and settings field in both frontend and backend
- Refactor AppSwitcher to render apps dynamically based on visibility
- Extract ToggleRow component for reuse
- Add i18n support for app visibility settings
2026-01-20 21:05:06 +08:00
Jason 30009ad5f1 feat(settings): set Gemini visibility to false by default
New users will see Claude, Codex, and OpenCode by default, with Gemini hidden.
2026-01-20 21:05:06 +08:00
Dex Miller e7badb1a24 Feat/provider individual config (#663)
* refactor(ui): simplify UpdateBadge to minimal dot indicator

* feat(provider): add individual test and proxy config for providers

Add support for provider-specific model test and proxy configurations:

- Add ProviderTestConfig and ProviderProxyConfig types in Rust and TypeScript
- Create ProviderAdvancedConfig component with collapsible panels
- Update stream_check service to merge provider config with global config
- Proxy config UI follows global proxy style (single URL input)

Provider-level configs stored in meta field, no database schema changes needed.

* feat(ui): add failover toggle and improve proxy controls

- Add FailoverToggle component with slide animation
- Simplify ProxyToggle style to match FailoverToggle
- Add usage statistics button when proxy is active
- Fix i18n parameter passing for failover messages
- Add missing failover translation keys (inQueue, addQueue, priority)
- Replace AboutSection icon with app logo

* fix(proxy): support system proxy fallback and provider-level proxy config

- Remove no_proxy() calls in http_client.rs to allow system proxy fallback
- Add get_for_provider() to build HTTP client with provider-specific proxy
- Update forwarder.rs and stream_check.rs to use provider proxy config
- Fix EditProviderDialog.tsx to include provider.meta in useMemo deps
- Add useEffect in ProviderAdvancedConfig.tsx to sync expand state

Fixes #636
Fixes #583

* fix(ui): sync toast theme with app setting

* feat(settings): add log config management

Fixes #612
Fixes #514

* fix(proxy): increase request body size limit to 200MB

Fixes #666

* docs(proxy): update timeout config descriptions and defaults

Fixes #612

* fix(proxy): filter x-goog-api-key header to prevent duplication

* fix(proxy): prevent proxy recursion when system proxy points to localhost

Detect if HTTP_PROXY, HTTPS_PROXY, or ALL_PROXY environment variables
point to loopback addresses (localhost, 127.0.0.1), and bypass system
proxy in such cases to avoid infinite request loops.

* fix(i18n): add providerAdvanced i18n keys and fix failover toast parameter

- Add providerAdvanced.* i18n keys to en.json, zh.json, and ja.json
- Fix failover toggleFailed toast to pass detail parameter
- Remove Chinese fallback text from UI for English/Japanese users

* fix(tray): restore tray-provider events and enable Auto failover properly

- Emit provider-switched event on tray provider click (backward compatibility)
- Auto button now: starts proxy, takes over live config, enables failover

* fix(log): enable dynamic log level and single file mode

- Initialize log at Trace level for dynamic adjustment
- Change rotation strategy to KeepSome(1) for single file
- Set max file size to 1GB
- Delete old log file on startup for clean start

* fix(tray): fix clippy uninlined format args warning

Use inline format arguments: {app_type_str} instead of {}

* fix(provider): allow typing :// in endpoint URL inputs

Change input type from "url" to "text" to prevent browser
URL validation from blocking :// input.

Closes #681

* fix(stream-check): use Gemini native streaming API format

- Change endpoint from OpenAI-compatible to native streamGenerateContent
- Add alt=sse parameter for SSE format response
- Use x-goog-api-key header instead of Bearer token
- Convert request body to Gemini contents/parts format

* feat(proxy): add request logging for debugging

Add debug logs for outgoing requests including URL and body content
with byte size, matching the existing response logging format.

* fix(log): prevent usize underflow in KeepSome rotation strategy

KeepSome(n) internally computes n-2, so n=1 causes underflow.
Use KeepSome(2) as the minimum safe value.
2026-01-20 21:02:44 +08:00
咸蛋黄 7bb458eecb feat: 添加 ESC 键快捷返回功能 (#670)
* feat: 添加 ESC 键快捷返回功能

- FullScreenPanel 组件支持 ESC 键关闭
- App.tsx 主页面支持 ESC 键返回主界面
- 优化键盘事件处理,合并多个监听器
- 使用事件捕获阶段避免冲突
- 适用于所有子页面:MCP、设置、Prompts、Skills 等
- 跨平台兼容:macOS、Windows、Linux

* perf: 优化 ESC 键处理逻辑

- 使用 useRef 避免闭包陷阱,提升性能
- 修复输入框中按 ESC 会关闭面板的问题
- 检测焦点元素,不干扰输入框的 ESC 行为
- 改进用户体验,避免意外关闭导致数据丢失

* fix: enhance global keyboard shortcuts and improve useModelState sync

- App & FullScreenPanel: Use `isTextEditableTarget` to prevent shortcuts (ESC, etc.) from triggering while editing text.
- useModelState: Prevent overwriting user input during config synchronization.
- App: Add `Cmd/Ctrl + ,` shortcut to open settings.
- Add `isTextEditableTarget` utility.
2026-01-20 16:33:50 +08:00
kkkman22 76897e2b97 <feat>: 添加 fnm 路径支持 (#564)
Co-authored-by: Gruby Wang <gruby.wang@shijigroup.com>
2026-01-20 10:32:35 +08:00
杨永安 fb9e7dee50 fix(provider): fix stale data shown when reopening edit dialog after save (#654)
Add `open` to initialData useMemo dependencies to ensure latest provider
data is read each time the dialog opens.
2026-01-20 10:31:35 +08:00
Jason Young e1d4dd7f55 Merge pull request #695 from farion1231/feat/opencode-support
feat: add OpenCode as the fourth managed CLI application
2026-01-19 20:25:39 +08:00
Jason c847fff768 feat(provider): update OpenCode presets with Claude 4.5 models and SDK changes 2026-01-19 16:35:39 +08:00
Jason 1eb0a0d7ac fix(opencode): move model options add button to bottom 2026-01-19 15:32:56 +08:00
Jason 3bd3845ec0 feat(opencode): add model-level options editor
Add support for configuring per-model options like provider routing.
Each model row now has an expand/collapse toggle to show a key-value
editor for model-specific options (e.g., provider order, fallbacks).

- Add options field to OpenCodeModel in Rust and TypeScript
- Add expandable key-value editor UI for each model
- Use local state pattern for option key input to prevent focus loss
- Add i18n translations for zh/en/ja
2026-01-19 15:05:01 +08:00
Jason b0d0a2c466 feat(opencode): add extra options editor for SDK configuration
Add key-value pair editor for configuring additional SDK options like
timeout, setCacheKey, etc. Values are automatically parsed to appropriate
types (number, boolean, object) on save.

- Add `extra` field with serde flatten in Rust backend
- Add index signature to OpenCodeProviderOptions type
- Create ExtraOptionKeyInput component with local state pattern
- Place extra options section above models configuration
2026-01-19 11:42:24 +08:00
Jason 73013c10af feat(opencode): add column headers for model configuration 2026-01-18 21:57:36 +08:00
Jason 1a0872c153 fix(opencode): prevent model ID input focus loss on keystroke
Use local state + onBlur pattern for ModelIdInput to keep React key
stable during editing. Previously, each keystroke changed the object
key, causing React to unmount/remount the input and lose focus.
2026-01-18 21:52:44 +08:00
Jason 255a7f570a fix(opencode): use AGENTS.md as prompt filename
OpenCode follows the same convention as Codex, using AGENTS.md
instead of OPENCODE.md for the system prompt file.
2026-01-17 23:36:51 +08:00
Jason fb44fb136f fix(opencode): hide test model button for unsupported adapter
OpenCode lacks a dedicated adapter and falls back to Codex adapter,
which has incompatible config structure. Hide the test button in UI
to prevent users from triggering unsupported operations.
2026-01-17 22:42:56 +08:00
Jason 58d3bb89d2 fix(opencode): generate unique provider key when duplicating
OpenCode uses user-provided provider keys as IDs instead of random UUIDs.
When duplicating a provider, generate a unique key by appending "-copy"
suffix (or "-copy-2", "-copy-3", etc. if already exists).
2026-01-17 22:10:08 +08:00
Jason 403227c901 feat(opencode): import providers and MCP on first launch
Add startup import logic for OpenCode providers and MCP servers.
Unlike other apps that use replacement mode, OpenCode uses additive
mode where multiple providers can coexist in the config file.
2026-01-17 21:15:16 +08:00
Jason 5bcf5bf382 feat(opencode): add manual provider key input with duplicate check
- Add Provider Key input field for OpenCode providers (between icon and name)
- User must manually enter a unique key instead of auto-generating from name
- Real-time validation: format check and duplicate detection
- Key is immutable after creation (disabled in edit mode)
- Remove slugify auto-generation logic from mutations
- Add beforeNameSlot prop to BasicFormFields for extensibility
- Add i18n translations for zh/en/ja
2026-01-17 20:28:11 +08:00
WuLiang 6ce6f16a99 fix(docs): change 'ArchLinux 用户' to 'ArchLinux Users' in README (#671) 2026-01-17 19:06:56 +08:00
Jason ad6f5b388b fix(opencode): fix add/remove provider flow and toast messages
- Create separate removeFromLiveConfig API for additive mode apps
  (remove only removes from live config, not database)
- Fix useSwitchProviderMutation to invalidate opencodeLiveProviderIds
  cache so button state updates correctly after add operation
- Show appropriate toast messages:
  - Add: "已添加到配置" / "Added to config"
  - Remove: "已从配置移除" / "Removed from config"
- Add i18n texts for addToConfigSuccess and removeFromConfigSuccess
2026-01-17 17:51:32 +08:00
Jason 2844f7c557 fix(opencode): distinguish remove and delete confirmation dialogs
Separate the confirmation dialogs for "remove from config" and "delete
provider" operations in OpenCode mode to help users understand the
different impacts of each action.
2026-01-17 16:45:31 +08:00
Jason 882c73234f fix(opencode): enable usage auto-query for providers in config
For OpenCode (additive mode), use isInConfig instead of isCurrent to
determine whether to enable usage auto-query. This allows providers
that have been added to the config to have their usage queried
automatically.
2026-01-17 15:48:44 +08:00
Jason b70de25de4 fix(opencode): allow delete button for all providers in additive mode
OpenCode uses additive mode where the main "Remove" button removes from
live config, while the delete button should delete from database. The
delete button should always be enabled for OpenCode providers.
2026-01-17 15:29:02 +08:00
Jason 88dbeb5335 fix(opencode): remove current provider concept for additive mode
OpenCode uses additive mode where all providers coexist in config file,
so there's no "current" provider concept. This commit:

- Skip setting is_current in switch_normal for OpenCode
- Return empty string from ProviderService::current for OpenCode
- Disable active provider highlight in ProviderCard for OpenCode
2026-01-17 15:24:09 +08:00
Jason 966d7b5782 fix(opencode): show Base URL field for all SDK types
Previously Base URL was only shown for @ai-sdk/openai-compatible.
Now it's always visible to support proxy scenarios for official SDKs
like DeepSeek, Anthropic, etc.
2026-01-17 11:46:50 +08:00
Jason 42a92c712a fix(opencode): skip reading live config when editing provider
OpenCode's read_live_settings returns the full opencode.json file
instead of just the provider fragment. This caused the edit dialog
to save the complete config structure as settingsConfig, creating
nested provider configurations.

For OpenCode's additive mode, use DB config directly since each
provider's config is stored independently.
2026-01-17 11:34:39 +08:00
Jason 2f0998c6c8 fix(opencode): prevent config nesting and use slugified provider IDs
- Skip backfill logic for OpenCode (additive mode doesn't need it)
- Add defensive check in write_live_snapshot to extract provider fragment
- Use slugified name as provider ID for readable config keys
2026-01-17 11:16:58 +08:00
Jason 938e2eb563 feat(opencode): add provider presets and fix preset selection handler
- Add 19 new provider presets for OpenCode (cn_official, aggregator, third_party)
- Add OpenCode handling branch in handlePresetChange to properly populate
  form fields (baseURL, apiKey, npm, models) when selecting a preset
- Add OpenCode reset logic in custom mode branch
2026-01-16 22:33:04 +08:00
Jason 2cc36b3950 fix(opencode): add OpenCode support to skills functionality
Add missing OpenCode branch in parse_app_type() and include OpenCode
in all app iteration loops for skills operations (uninstall, scan,
import, migrate).
2026-01-16 21:23:54 +08:00
Jason e06c6176d9 fix(opencode): hide common config snippet UI and prevent auto-merge
- Add `enabled` parameter to useCommonConfigSnippet hook
- Skip all loading and auto-merge logic when enabled=false
- Replace CommonConfigEditor with simplified JsonEditor for OpenCode
- Prevent Claude's common config snippet from being injected into OpenCode
2026-01-16 21:03:33 +08:00
Jason 9b4485e111 refactor(opencode): simplify API format selector
- Reduce npm package options from 10 to 4 core API formats (OpenAI, OpenAI Compatible, Anthropic, Google)
- Rename "AI SDK Package" to "API Format" in i18n (zh/en/ja)
- Remove check icon from Select dropdown items for cleaner UI
2026-01-16 20:29:12 +08:00
Jason f349d85e85 fix(ui): resolve Select dropdown not appearing in FullScreenPanel
- Increase SelectContent z-index from z-50 to z-[100] to appear above FullScreenPanel (z-[60])
- Replace form.watch() with form.getValues() in useCallback handlers for correct react-hook-form usage
- Remove max-w-[56rem] constraints from various panels for consistent full-width layout
2026-01-16 20:21:00 +08:00
Jason 58a13cc69a feat(provider): hide universal tab for OpenCode
OpenCode doesn't support universal providers, so the tab is
hidden to avoid confusion for users.
2026-01-16 16:09:43 +08:00
Jason d765364a18 chore(opencode): remove unused functions and legacy code
Remove dead code that was never called after v3.7.0 architecture change:
- mcp/opencode.rs: sync_enabled_to_opencode, collect_enabled_servers
- opencode_config.rs: 8 unused utility functions
- provider.rs: OpenCodeProviderConfig impl block (4 methods)

These functions were designed for batch operations but McpService uses
per-server sync pattern instead. No functionality affected.
2026-01-16 15:56:03 +08:00
Jason 5c6956b6e2 feat(opencode): add OpenCode toggle switches to MCP and Skills panels
- Add opencode to AppType and SkillApps interfaces in skills.ts
- Add OpenCode Switch component to UnifiedMcpPanel list items
- Add OpenCode Switch component to UnifiedSkillsPanel list items
- Include OpenCode in enabled counts and header statistics for both panels
2026-01-16 15:40:33 +08:00
Jason cb1b45ae4e feat(opencode): add OpenCode icon to icon system
Register OpenCode SVG icon in the icons index so AppSwitcher displays
the proper logo instead of fallback initials.
2026-01-16 13:03:21 +08:00
Jason e4df1a32a5 feat(opencode): implement isInConfig semantics for additive provider management
OpenCode uses additive provider management where providers can exist in
the database but not necessarily in the live opencode.json config. This
commit implements proper isInConfig state:

Backend:
- Add get_opencode_live_provider_ids command to query live config

Frontend:
- Add getOpenCodeLiveProviderIds API method
- ProviderList queries live provider IDs and computes isInConfig
- ProviderCard receives and passes isInConfig to ProviderActions
- ProviderActions already handles the add/remove button logic
2026-01-15 19:37:35 +08:00
Jason 2494eaaa32 feat(opencode): hide proxy UI for OpenCode
OpenCode uses additive provider management (multiple providers coexist),
so proxy/failover features are not applicable. This commit:
- Conditionally renders ProxyToggle only for non-OpenCode apps
- Fixes toast message label to properly handle opencode app type
2026-01-15 19:32:34 +08:00
Jason 45b9cf1df0 feat(opencode): add OpenCode button to AppSwitcher
Add the fourth tab button for OpenCode in the app switcher component,
making the OpenCode providers page accessible from the main navigation.
2026-01-15 19:31:44 +08:00
Jason de3a22535d fix(opencode): address issues found during OpenCode integration review
- Fix MCP server not removed from opencode.json when unchecked in edit modal
- Fix Windows atomic write failure when opencode.json already exists
- Fix i18n keys mismatch in OpenCodeFormFields (use opencode.* namespace)
- Fix unit test missing apps.opencode field assertion
2026-01-15 19:07:49 +08:00
Jason 36d6d48002 feat(opencode): Phase 10 - Internationalization for OpenCode
Update i18n translation files (zh.json, en.json, ja.json):

- Add "opencode" to apps section: "OpenCode"
- Add provider section keys:
  - addOpenCodeProvider: Add OpenCode Provider
  - addToConfig: Add (for additive mode button)
  - removeFromConfig: Remove
  - inConfig: Added
- Add new "opencode" section with UI labels:
  - npmPackage: AI SDK Package
  - npmPackageHint: Package selection hint
  - baseUrl, baseUrlHint: Base URL configuration
  - models, modelsHint: Model configuration
  - addModel, modelId, modelName: Model editor labels
  - noModels: Empty state message
- Add "opencode" to mcp.unifiedPanel.apps section
- Add "opencode" to skills.apps section
2026-01-15 16:42:15 +08:00
Jason 864884926a feat(opencode): Phase 9 - Frontend UI components for OpenCode
- Create OpenCodeFormFields.tsx with:
  - NPM package selector (from AI SDK ecosystem)
  - API Key input using shared ApiKeySection component
  - Base URL input (shown for openai-compatible)
  - Dynamic models editor (add/remove models)

- Update ProviderForm.tsx:
  - Import OpenCode presets and form fields
  - Add OPENCODE_DEFAULT_CONFIG constant
  - Add OpenCode to PresetEntry type union
  - Add OpenCode preset entries in useMemo
  - Add OpenCode state hooks (npm, apiKey, baseUrl, models)
  - Add OpenCode change handlers syncing to form
  - Add OpenCodeFormFields rendering section
  - Add OpenCode config editor using CommonConfigEditor

- Update ProviderActions.tsx for OpenCode additive mode:
  - Add appId and isInConfig props
  - Implement "Add to Config" / "Remove from Config" buttons
  - Disable failover mode for OpenCode
  - Update delete button logic for additive mode

- Update ProviderCard.tsx:
  - Pass appId and isInConfig to ProviderActions

- Update AddProviderDialog.tsx:
  - Add OpenCode base URL extraction from options.baseURL
2026-01-15 16:38:26 +08:00
Jason 093ff0ba29 feat(opencode): Phase 8 - OpenCode provider presets configuration
- Create src/config/opencodeProviderPresets.ts with:
  - OpenCodeProviderPreset interface for preset structure
  - opencodeNpmPackages: AI SDK npm package options
  - Provider presets: OpenAI, Anthropic, Google, DeepSeek, Mistral, Groq
  - OpenAI Compatible custom template for third-party providers
- Each preset uses OpenCodeProviderConfig with npm, options, models structure
- Includes apiKeyUrl for quick access to API key pages
- Template values for dynamic API key input
2026-01-15 16:26:46 +08:00
Jason 21754a7349 feat(opencode): Phase 7 - Frontend TypeScript type definitions
- Add "opencode" to AppId type in lib/api/types.ts
- Extend McpApps interface with opencode field in types.ts
- Add OpenCode-specific types: OpenCodeModel, OpenCodeProviderOptions,
  OpenCodeProviderConfig, OpenCodeMcpServerSpec
- Add opencodeConfigDir to Settings interface
- Add importOpenCodeFromLive() to providersApi
- Fix type errors across components:
  - AppSwitcher: add opencode to icon/name mappings
  - McpFormModal: add opencode to enabledApps state
  - PromptFormModal/Panel: add opencode filename mapping
  - EndpointSpeedTest: add opencode timeout config
  - useBaseUrlState: add opencode to appType union
  - ProxyToggle: add opencode label
  - App.tsx: handle opencode fallback for SkillsPage
- Update ProxyTakeoverStatus with opencode field (always false)
- Fix test mocks in tests/msw/state.ts
2026-01-15 16:25:14 +08:00
Jason 7997b2c7b3 feat(opencode): Phase 6 - Tauri command extensions for OpenCode
- Add import_opencode_providers_from_live command to provider.rs
- Register new command in lib.rs invoke_handler
- Update commands/mcp.rs: include OpenCode in sync_other_side logic
- Add McpService::import_from_opencode to import_mcp_from_apps
- Implement MCP sync/remove for OpenCode in services/mcp.rs
  - sync_server_to_app_no_config now calls sync_single_server_to_opencode
  - remove_server_from_app now calls remove_server_from_opencode
2026-01-15 16:20:03 +08:00
Jason b8538b211d feat(opencode): complete Phase 5 - provider service layer
Implement OpenCode-specific provider service logic with additive mode:
- add(): Always write to live config (no is_current check needed)
- update(): Always sync changes to live config
- delete(): Remove from both DB and live config (no is_current check)

New helper functions in live.rs:
- write_live_snapshot(): Write provider to opencode.json provider section
- remove_opencode_provider_from_live(): Remove provider from live config
- import_opencode_providers_from_live(): Import existing providers from
  ~/.config/opencode/opencode.json into CC Switch database

Key design: OpenCode uses additive mode where all providers coexist
in the config file, unlike Claude/Codex/Gemini which use replacement
mode with a single active provider.
2026-01-15 16:15:01 +08:00
Jason 7ea2c3452b feat(opencode): complete Phase 4 - MCP sync module
Add mcp/opencode.rs with format conversion between CC Switch and OpenCode:
- stdio ↔ local type conversion
- command+args ↔ command array format
- env ↔ environment field mapping
- sse/http ↔ remote type conversion

Public API:
- sync_enabled_to_opencode: Batch sync all enabled servers
- sync_single_server_to_opencode: Sync individual server
- remove_server_from_opencode: Remove from live config
- import_from_opencode: Import servers from OpenCode config

Also fix test files to include new opencode field in McpApps struct.
All 4 unit tests pass for format conversion.
2026-01-15 16:11:25 +08:00
Jason a30d72bb68 feat(opencode): complete Phase 3 - enhanced config read/write module
Add typed provider functions and utilities to opencode_config.rs:
- Typed provider operations (get_typed_providers, get_typed_provider,
  set_typed_provider, set_providers_batch)
- MCP batch operations (set_mcp_servers_batch, clear_mcp_servers)
- Utility functions (create_provider_config, validate_provider_config,
  provider_to_opencode_config, opencode_config_to_provider)
- Enhanced module documentation with config file format examples

The typed API layer provides type-safe access to OpenCode provider
configurations while the untyped layer allows raw JSON operations
when needed.
2026-01-15 16:07:14 +08:00
Jason 58ecc44ee6 feat(opencode): Phase 2 - Add OpenCode provider data structures
Add OpenCode-specific configuration structures for the AI SDK format:

- OpenCodeProviderConfig: Main config with npm package, options, and models
- OpenCodeProviderOptions: baseURL, apiKey, and headers support
- OpenCodeModel: Model definition with name and token limits
- OpenCodeModelLimit: Context and output token limits

Key features:
- Supports environment variable references (e.g., "{env:API_KEY}")
- Custom headers support for specialized providers
- Model-level token limits for context management
- Helper methods for parsing and validation
2026-01-15 15:59:44 +08:00
Jason 5658d93924 feat(opencode): Phase 1 - Backend data structure expansion for OpenCode support
Add OpenCode as the 4th supported application with additive provider management:

- Add OpenCode variant to AppType enum with all related match statements
- Add enabled_opencode field to McpApps and SkillApps structures
- Add opencode field to McpRoot and PromptRoot
- Add database schema migration v3→v4 with enabled_opencode columns
- Add settings.rs support for opencode_config_dir and current_provider_opencode
- Create opencode_config.rs module for config file I/O operations
- Update all services (proxy, mcp, skill, provider, stream_check) for OpenCode
- Add OpenCode support to deeplink provider and MCP parsing
- Update commands/config.rs for OpenCode config status and paths

Key design decisions:
- OpenCode uses additive mode (no is_current needed, no proxy support)
- Config path: ~/.config/opencode/opencode.json
- MCP format: stdio→local, sse/http→remote conversion planned
- Stream check returns error (not yet implemented for OpenCode)
2026-01-15 15:54:29 +08:00
Jason e4d24f2df9 docs: add OpenCode implementation plan
Add comprehensive implementation plan for OpenCode (4th app) support:
- Additive provider management (vs. replacement model)
- MCP format conversion (stdio<->local, sse<->remote)
- Config file: ~/.config/opencode/opencode.json
- No proxy/failover support (OpenCode handles internally)
2026-01-15 15:31:38 +08:00
杨永安 07d022ba9f feat(usage): improve custom template system with variable hints and validation fixes (#628)
* feat(usage): improve custom template with variables display and explicit type detection

Combine two feature improvements:
1. Display supported variables ({{baseUrl}}, {{apiKey}}) with actual values in custom template mode
2. Add explicit templateType field for accurate template mode detection

## Changes

### Frontend
- Display template variables with actual values extracted from provider settings
- Add templateType field to UsageScript for explicit mode detection
- Support template mode persistence across sessions

### Backend
- Add template_type field to UsageScript struct
- Improve validation logic based on explicit template type
- Maintain backward compatibility with type inference

### I18n
- Add "Supported Variables" section translation (zh/en/ja)

### Benefits
- More accurate template mode detection (no more guessing)
- Better user experience with variable hints
- Clearer validation rules per template type

* fix(usage): resolve custom template cache and validation issues

Combine three bug fixes to make custom template mode work correctly:

1. **Update cache after test**: Testing usage script successfully now updates the main list cache immediately
2. **Fix same-origin check**: Custom template mode can now access different domains (SSRF protection still active)
3. **Fix field naming**: Unified to use autoQueryInterval consistently between frontend and backend

## Problems Solved

- Main provider list showing "Query failed" after successful test
- Custom templates blocked by overly strict same-origin validation
- Auto-query intervals not saved correctly due to inconsistent naming

## Changes

### Frontend (UsageScriptModal)
- Import useQueryClient and update cache after successful test
- Invalidate usage cache when saving script configuration
- Use standardized autoQueryInterval field name

### Backend (usage_script.rs)
- Allow custom template mode to bypass same-origin checks
- Maintain SSRF protection for all modes

### Hooks (useProviderActions)
- Invalidate usage query cache when saving script

## Impact

Users can now use custom templates freely while security validations remain intact for general templates.

* fix(usage): correct provider credential field names

- Claude: support both ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN
- Gemini: use GEMINI_API_KEY instead of GOOGLE_GEMINI_API_KEY
- Codex: use OPENAI_API_KEY and parse base_url from TOML config string

Addresses review feedback from PR #628

* style: format code

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-01-14 15:42:05 +08:00
Dex Miller f3343992f2 feat(proxy): add thinking signature rectifier for Claude API (#595)
* feat(proxy): add thinking signature rectifier for Claude API

Add automatic request rectification when Anthropic API returns signature
validation errors. This improves compatibility when switching between
different Claude providers or when historical messages contain incompatible
thinking block signatures.

- Add thinking_rectifier.rs module with trigger detection and rectification
- Integrate rectifier into forwarder error handling flow
- Remove thinking/redacted_thinking blocks and signature fields on retry
- Delete top-level thinking field when assistant message lacks thinking prefix

* fix(proxy): complete rectifier retry path with failover switch and chain continuation

- Add failover switch trigger on rectifier retry success when provider differs from start
- Replace direct error return with error categorization on rectifier retry failure
- Continue failover chain for retryable errors instead of terminating early

* feat(proxy): add rectifier config with master switch

- Add RectifierConfig struct with enabled and requestThinkingSignature fields
- Update should_rectify_thinking_signature to check master switch first
- Add tests for master switch functionality

* feat(db): add rectifier config storage in settings table

Store rectifier config as JSON in single key for extensibility

* feat(commands): add get/set rectifier config commands

* feat(ui): add rectifier config panel in advanced settings

- Add RectifierConfigPanel component with master switch and thinking signature toggle
- Add API wrapper for rectifier config
- Add i18n translations for zh/en/ja

* feat(proxy): integrate rectifier config into request forwarding

- Load rectifier config from database in RequestContext
- Pass config to RequestForwarder for runtime checking
- Use should_rectify_thinking_signature with config parameter

* test(proxy): add nested JSON error detection test for thinking rectifier

* fix(proxy): resolve HalfOpen permit leak and RectifierConfig default values

- Fix RectifierConfig::default() to return enabled=true (was false due to derive)
- Add release_permit_neutral() for releasing permits without affecting health stats
- Fix 3 permit leak points in rectifier retry branches
- Add unit tests for default values and permit release

* style(ui): format ProviderCard style attribute

* fix(rectifier): add detection for signature field required error

Add support for detecting "signature: Field required" error pattern
in the thinking signature rectifier. This enables automatic request
rectification when upstream API returns this specific validation error.
2026-01-14 00:12:13 +08:00
Jason 53f40b2d7a refactor(ui): unify pricing edit modal with FullScreenPanel
Replace Dialog component with FullScreenPanel in PricingEditModal
to match the UI style of other edit dialogs (provider, MCP).

Changes:
- Switch from small centered Dialog to full-screen panel
- Add back button in header and fixed footer for actions
- Add Save/Plus icons to submit button
2026-01-13 15:13:33 +08:00
Dex Miller 1393f89797 feat(misc): add WSL tool version detection with security hardening (#… (#627)
* feat(misc): add WSL tool version detection with security hardening (#608)

- Add WSL distro detection from UNC path (wsl$/wsl.localhost)
- Add distro name validation to prevent command injection
- Add defensive assertion for tool parameter
- Unify cfg macros to target_os = "windows"
- Standardize error message format to [WSL:{distro}]

Closes #608

* fix(misc): add CREATE_NO_WINDOW flag and unify error messages to English

- Add CREATE_NO_WINDOW flag to wsl.exe command to prevent console window flash
- Standardize error messages from Chinese to English for consistency

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-01-13 12:11:54 +08:00
Dex Miller f9d80b8dc3 feat(stream-check): enhance health check with configurable prompt and CLI-compatible requests (#623)
- Add configurable test prompt field to StreamCheckConfig
- Implement Claude CLI-compatible request format with proper headers:
  - Authorization + x-api-key dual auth
  - anthropic-beta, anthropic-version headers
  - x-stainless-* SDK headers with dynamic OS/arch detection
  - URL with ?beta=true parameter
- Implement Codex CLI-compatible Responses API format:
  - /v1/responses endpoint
  - input array format with reasoning effort support
  - codex_cli_rs user-agent and originator headers
- Add dynamic OS name and CPU architecture detection
- Internationalize error messages (Chinese -> English)
- Add test prompt Textarea UI component with i18n support
- Remove obsolete testPromptDesc translation key
2026-01-13 11:36:19 +08:00
Dex Miller 8b92982112 Feature/global proxy (#596)
* refactor(proxy): simplify logging for better readability

- Delete 17 verbose debug logs from handlers, streaming, and response_processor
- Convert excessive INFO logs to DEBUG level for internal processing details
- Add 2 critical INFO logs in forwarder.rs for failover scenarios:
  - Log when switching to next provider after failure
  - Log when all providers have been exhausted
- Fix clippy uninlined_format_args warning

This reduces log noise while maintaining visibility into key user-facing decisions.

* fix: replace unsafe unwrap() calls with proper error handling

- database/dao/mcp.rs: Use map_err for serde_json serialization
- database/dao/providers.rs: Use map_err for settings_config and meta serialization
- commands/misc.rs: Use expect() for compile-time regex pattern
- services/prompt.rs: Use unwrap_or_default() for SystemTime
- deeplink/provider.rs: Replace unwrap() with is_none_or pattern for Option checks

Reduces potential panic points from 26 to 1 (static regex init, safe).

* refactor(proxy): simplify verbose logging output

- Remove response JSON full output logging in response_processor
- Remove per-request INFO logs in provider_router (failover status, provider selection)
- Change model mapping log from INFO to DEBUG
- Change usage logging failure from INFO to WARN
- Remove redundant debug logs for circuit breaker operations

Reduces log noise significantly while preserving important warnings and errors.

* feat(proxy): add structured log codes for i18n support

Add error code system to proxy module logs for multi-language support:

- CB-001~006: Circuit breaker state transitions and triggers
- SRV-001~004: Proxy server lifecycle events
- FWD-001~002: Request forwarding and failover
- FO-001~005: Failover switch operations
- USG-001~002: Usage logging errors

Log format: [CODE] Chinese message
Frontend/log tools can map codes to any language.

New file: src/proxy/log_codes.rs - centralized code definitions

* chore: bump version to 3.9.1

* style: format code with prettier and rustfmt

* fix(ui): allow number inputs to be fully cleared before saving

- Convert numeric state to string type for controlled inputs
- Use isNaN() check instead of || fallback to allow 0 values
- Apply fix to ProxyPanel, CircuitBreakerConfigPanel,
  AutoFailoverConfigPanel, and ModelTestConfigPanel

* feat(pricing): support @ separator in model name matching

- Refactor model name cleaning into chained method calls
- Add @ to - replacement (e.g., gpt-5.2-codex@low → gpt-5.2-codex-low)
- Add test case for @ separator matching

* feat(proxy): add global proxy settings support

Add ability to configure a global HTTP/HTTPS proxy for all outbound
requests including provider API calls, speed tests, and stream checks.

* fix(proxy): improve validation and error handling in proxy config panels

- Add StopTimeout/StopFailed error types for proper stop() error reporting
- Replace silent clamp with validation-and-block in config panels
- Add listenAddress format validation in ProxyPanel
- Use log_codes constants instead of hardcoded strings
- Use once_cell::Lazy for regex precompilation

* fix(proxy): harden error handling and input validation

- Handle RwLock poisoning in settings.rs with unwrap_or_else
- Add fallback for dirs::home_dir() in config modules
- Normalize localhost to 127.0.0.1 in ProxyPanel
- Format IPv6 addresses with brackets for valid URLs
- Strict port validation with pure digit regex
- Treat NaN as validation failure in config panels
- Log warning on cost_multiplier parse failure
- Align timeoutSeconds range to [0, 300] across all panels

* feat(proxy): add local proxy auto-scan and fix hot-reload

- Add scan_local_proxies command to detect common proxy ports
- Fix SkillService not using updated proxy after hot-reload
- Move global proxy settings to advanced tab
- Add error handling for scan failures

* fix(proxy): allow localhost input in proxy address field

* fix(proxy): restore request timeout and fix proxy hot-reload issues

- Add URL scheme validation in build_client (http/https/socks5/socks5h)
- Restore per-request timeout for speedtest, stream_check, usage_script, forwarder
- Fix set_global_proxy_url to validate before persisting to DB
- Mask proxy credentials in all log outputs
- Fix forwarder hot-reload by fetching client on each request

* style: format code with prettier

* fix(proxy): improve global proxy stability and error handling

- Fix RwLock silent failures with explicit error propagation
- Handle init() duplicate calls gracefully with warning log
- Align fallback client config with build_client settings
- Make scan_local_proxies async to avoid UI blocking
- Add mixed mode support for Clash 7890 port (http+socks5)
- Use multiple test targets for better proxy connectivity test
- Clear invalid proxy config on init failure
- Restore timeout constraints in usage_script
- Fix mask_url output for URLs without port
- Add structured error codes [GP-001 to GP-009]

* feat(proxy): add username/password authentication support

- Add separate username and password input fields
- Implement password visibility toggle with eye icon
- Add clear button to reset all proxy fields
- Auto-extract auth info from saved URL and merge on save
- Update i18n translations (zh/en/ja)

* fix(proxy): fix double encoding issue in proxy auth and add debug logs

- Remove encodeURIComponent in mergeAuth() since URL object's
  username/password setters already do percent-encoding automatically
- Add GP-010 debug log for database read operations
- Add GP-011 debug log to track incoming URL info (length, has_auth)
- Fix username.trim() in fallback branch for consistent behavior
2026-01-13 10:55:53 +08:00
Dex Miller 74b4d4ecbb fix(ui): auto-adapt usage block offset based on action buttons width (#613) 2026-01-12 23:07:02 +08:00
Dex Miller 99c910e58e fix(provider): persist endpoint auto-select state (#611)
- Add endpointAutoSelect field to ProviderMeta for persistence
- Lift autoSelect state from EndpointSpeedTest to ProviderForm
- Save auto-select preference when provider is saved
- Restore preference when editing existing provider

Fixes https://github.com/farion1231/cc-switch/issues/589
2026-01-12 16:26:17 +08:00
Dex Miller 8f7423f011 Feat/deeplink multi endpoints (#597)
* feat(deeplink): support comma-separated multiple endpoints in URL

Allow importing multiple API endpoints via single endpoint parameter.
First URL becomes primary endpoint, rest are added as custom endpoints.

* feat(deeplink): add usage query fields to deeplink generator

Add form fields for usage query configuration in deeplink HTML generator:
- usageEnabled, usageBaseUrl, usageApiKey
- usageScript, usageAutoInterval
- usageAccessToken, usageUserId

* fix(deeplink): auto-infer homepage and improve multi-endpoint display

- Auto-infer homepage from primary endpoint when not provided
- Display multiple endpoints as list in import dialog (primary marked)
- Update deeplink parser in deplink.html to show multi-endpoint info
- Add test for homepage inference from endpoint
- Minor log format fix in live.rs

* fix(deeplink): use primary endpoint for usage script base_url

- Fix usage_script.base_url getting comma-separated string when multiple endpoints
- Add i18n support for primary endpoint label in DeepLinkImportDialog
2026-01-12 15:57:45 +08:00
Jason c56523c9c0 Merge tianrking/main: feat: add provider-specific terminal button
Merged PR #452 which adds:
- Terminal button for Claude providers to launch with provider-specific config
- Cross-platform support (macOS/Linux/Windows)
- Auto-cleanup of temporary config files
2026-01-12 09:13:24 +08:00
Jason 6aef472fd2 fix(deeplink): prioritize GOOGLE_GEMINI_BASE_URL over GEMINI_BASE_URL
When merging Gemini config from local env file during deeplink import,
check GOOGLE_GEMINI_BASE_URL first (official variable name) before
falling back to GEMINI_BASE_URL.
2026-01-11 23:24:06 +08:00
Xyfer 4a8883ecc3 fix(mcp): skip cmd /c wrapper for WSL target paths (#592)
* fix(mcp): skip cmd /c wrapper for WSL target paths

When the Claude config directory is set to a WSL network path
(e.g., \wsl$\Ubuntu\home\user\.claude), the MCP export should
not wrap npx/npm commands with cmd /c since WSL runs Linux.

- Add is_wsl_path() to detect \wsl$\ and \wsl.localhost\ paths
- Skip wrap_command_for_windows() when target is WSL path
- Add comprehensive tests for various WSL distributions

* chore(mcp): add debug log for WSL path detection

* refactor(mcp): optimize is_wsl_path with next() and rename variable
2026-01-11 20:51:56 +08:00
Dex Miller 6dd809701b Refactor/simplify proxy logs (#585)
* refactor(proxy): simplify logging for better readability

- Delete 17 verbose debug logs from handlers, streaming, and response_processor
- Convert excessive INFO logs to DEBUG level for internal processing details
- Add 2 critical INFO logs in forwarder.rs for failover scenarios:
  - Log when switching to next provider after failure
  - Log when all providers have been exhausted
- Fix clippy uninlined_format_args warning

This reduces log noise while maintaining visibility into key user-facing decisions.

* fix: replace unsafe unwrap() calls with proper error handling

- database/dao/mcp.rs: Use map_err for serde_json serialization
- database/dao/providers.rs: Use map_err for settings_config and meta serialization
- commands/misc.rs: Use expect() for compile-time regex pattern
- services/prompt.rs: Use unwrap_or_default() for SystemTime
- deeplink/provider.rs: Replace unwrap() with is_none_or pattern for Option checks

Reduces potential panic points from 26 to 1 (static regex init, safe).

* refactor(proxy): simplify verbose logging output

- Remove response JSON full output logging in response_processor
- Remove per-request INFO logs in provider_router (failover status, provider selection)
- Change model mapping log from INFO to DEBUG
- Change usage logging failure from INFO to WARN
- Remove redundant debug logs for circuit breaker operations

Reduces log noise significantly while preserving important warnings and errors.

* feat(proxy): add structured log codes for i18n support

Add error code system to proxy module logs for multi-language support:

- CB-001~006: Circuit breaker state transitions and triggers
- SRV-001~004: Proxy server lifecycle events
- FWD-001~002: Request forwarding and failover
- FO-001~005: Failover switch operations
- USG-001~002: Usage logging errors

Log format: [CODE] Chinese message
Frontend/log tools can map codes to any language.

New file: src/proxy/log_codes.rs - centralized code definitions

* chore: bump version to 3.9.1

* style: format code with prettier and rustfmt

* fix(ui): allow number inputs to be fully cleared before saving

- Convert numeric state to string type for controlled inputs
- Use isNaN() check instead of || fallback to allow 0 values
- Apply fix to ProxyPanel, CircuitBreakerConfigPanel,
  AutoFailoverConfigPanel, and ModelTestConfigPanel

* feat(pricing): support @ separator in model name matching

- Refactor model name cleaning into chained method calls
- Add @ to - replacement (e.g., gpt-5.2-codex@low → gpt-5.2-codex-low)
- Add test case for @ separator matching

* fix(proxy): improve validation and error handling in proxy config panels

- Add StopTimeout/StopFailed error types for proper stop() error reporting
- Replace silent clamp with validation-and-block in config panels
- Add listenAddress format validation in ProxyPanel
- Use log_codes constants instead of hardcoded strings
- Use once_cell::Lazy for regex precompilation

* fix(proxy): harden error handling and input validation

- Handle RwLock poisoning in settings.rs with unwrap_or_else
- Add fallback for dirs::home_dir() in config modules
- Normalize localhost to 127.0.0.1 in ProxyPanel
- Format IPv6 addresses with brackets for valid URLs
- Strict port validation with pure digit regex
- Treat NaN as validation failure in config panels
- Log warning on cost_multiplier parse failure
- Align timeoutSeconds range to [0, 300] across all panels
2026-01-11 20:50:54 +08:00
Jason 76fa830688 fix(live): sync skills to app directories on config path change
When users change app config directories (claudeConfigDir, codexConfigDir,
geminiConfigDir), MCP servers were being synced to the new paths but Skills
were not. This adds Skill synchronization to sync_current_to_live() to ensure
installed Skills are also copied to the new app directories.
2026-01-11 16:39:50 +08:00
Jason c9a4938866 fix(provider-form): reset baseUrl and apiKey states when switching presets
Fix state synchronization in useBaseUrlState and useApiKeyState hooks
to properly clear values when config is reset. Previously, when switching
from a preset to "custom", the baseUrl and apiKey states would retain
their old values because the sync logic only updated when new values
existed, not when they were cleared.

Changes:
- useBaseUrlState: Always sync baseUrl to config value (empty if undefined)
- useApiKeyState: Remove hasApiKeyField check that prevented clearing
2026-01-11 16:39:50 +08:00
Jason 95ed6d6903 fix(usage): prevent usage script config from leaking between providers
Add key prop to UsageScriptModal to ensure component remounts when
switching between different providers. This fixes issue #569 where
configuring usage query for one provider would incorrectly apply
the same configuration to all providers.

The root cause was that useState initialization only runs on first
mount, and due to useLastValidValue hook keeping the modal rendered
during close animation, the component might not fully unmount when
switching providers rapidly.

Closes #569
2026-01-11 16:39:50 +08:00
Jason 83db457b10 refactor(proxy): disable OpenRouter compat mode by default and hide UI toggle
OpenRouter now natively supports Claude Code compatible API (/v1/messages),
so format transformation (Anthropic ↔ OpenAI) is no longer needed by default.

- Change default value from `true` to `false` in both frontend and backend
- Hide the "OpenRouter Compatibility Mode" toggle in provider form
- Users can still enable it manually by adding `"openrouter_compat_mode": true` in config JSON
- Update unit tests to reflect new default behavior
2026-01-11 16:39:50 +08:00
Xyfer 392756e373 fix(gemini): convert timeout params to Gemini CLI format (#580)
Claude Code/Codex uses startup_timeout_sec and tool_timeout_sec,
but Gemini CLI only supports a single timeout param in milliseconds.

- Collect startup and tool timeout separately with defaults
  - startup_timeout_sec default: 10s
  - tool_timeout_sec default: 60s
- Take max of both values as final timeout
- Support both sec and ms variants
- Remove original fields and insert Gemini-compatible timeout
2026-01-11 10:42:44 +08:00
Jason 6021274b82 fix(ci): temporarily remove Flatpak build
Flatpak build has persistent issues with libdbusmenu dependencies.
Removing it for now to allow release. Can be re-added later with
proper libayatana dependency configuration.
2026-01-09 22:01:33 +08:00
Jason b7fd70075c fix(flatpak): remove --enable-tests=no to fix HAVE_VALGRIND error
libdbusmenu's configure.ac has a bug where AM_CONDITIONAL([HAVE_VALGRIND])
is only defined when tests are enabled. Removing --enable-tests=no allows
the conditional to be properly defined.

Ref: https://bugs.launchpad.net/ubuntu/+source/libdbusmenu/+bug/1708938
2026-01-09 21:47:59 +08:00
Jason eeb6afef01 fix(flatpak): bundle intltool for libdbusmenu build
intltool was removed from org.gnome.Sdk in 2019. libdbusmenu's configure
script requires it even with --disable-nls. Using cleanup: ["*"] ensures
intltool is only used at build time.
2026-01-09 21:26:53 +08:00
Jason d3074eadb5 fix(flatpak): disable NLS for libdbusmenu-gtk3
The Flatpak SDK lacks intltool, causing libdbusmenu-gtk3 configure to
fail. Disabling NLS avoids this dependency.
2026-01-09 21:07:38 +08:00
Jason 31d34a4512 fix(ci): add elfutils for Flatpak build
The libayatana modules added in 2923627b require eu-strip to strip
debug symbols during flatpak-builder execution.
2026-01-09 20:44:23 +08:00
Jason 3ef86bdb99 chore: bump version to v3.9.1
- Update version in package.json, tauri.conf.json, Cargo.toml
- Update version badges and current version in README files
- Add v3.9.1 changelog entry with bug fixes and improvements
2026-01-09 20:19:38 +08:00
Jason df3f8a05c4 fix(presets): rename AiGoCode to AIGoCode
Update the display name casing for AIGoCode across all provider presets
and i18n files to match their official branding.
2026-01-09 20:03:24 +08:00
Jason 8e6fad7af2 fix(windows): correct window title and remove extra titlebar spacing
- Add missing "title" field to tauri.windows.conf.json to display
  "CC Switch" instead of default "Tauri app"
- Make DRAG_BAR_HEIGHT platform-aware: 0px on Windows/Linux (native
  titlebar), 28px on macOS (Overlay mode needs traffic light space)
- Apply same fix to FullScreenPanel component for consistency

Fixes the issue where Windows showed wrong title and had ~28px extra
blank space below the native titlebar introduced in v3.9.0.
2026-01-09 19:45:36 +08:00
Jason f22000a4df feat(presets): add AiGoCode icon and partner promotion
- Add AiGoCode colored icon (blue body #5B7FFF, purple star #7C6AEF)
- Add original SVG source file for reference
- Add icon metadata with keywords and default color
- Add iconColor to AiGoCode presets for Claude, Codex, and Gemini
- Add partner promotion messages in zh/en/ja locales
2026-01-09 16:29:13 +08:00
Dex Miller 412906fb09 feat(logging): add crash logging and improve log management (#562)
* feat(logging): add crash logging and improve log management

- Add panic hook to capture crash info to ~/.cc-switch/crash.log
  - Records timestamp, app version, OS/arch, thread info
  - Full stack trace with force_capture for release builds
  - Safe error handling (no nested panics)

- Enable logging for both Debug and Release builds
  - Info level for all builds
  - Output to console and ~/.cc-switch/logs/
  - 5MB max file size with rotation

- Add log cleanup on startup
  - Keep only 2 most recent log files
  - Works on all platforms

- Change panic strategy from "abort" to "unwind"
  - Required for backtrace capture in release builds

* fix(logging): use OnceLock for config dir and add URL redaction

- Use OnceLock to support custom config directory override for crash.log
- Add redact_url_for_log() to protect sensitive URL parameters in logs
- Change verbose deep link logs from info to debug level
- Move Store refresh before panic_hook init to ensure correct path

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-01-09 16:23:59 +08:00
Jason Young a268127f1f Fix/Resolve panic issues in proxy-related code (#560)
* fix(proxy): change default port from 5000 to 15721

Port 5000 conflicts with AirPlay Receiver on macOS 12+.
Also adds error handling for proxy toggle and i18n placeholder updates.

* fix(proxy): replace unwrap/expect with graceful error handling

- Handle HTTP client initialization failure with no_proxy fallback
- Fix potential panic on Unicode slicing in API key preview
- Add proper error handling for response body builder
- Handle edge case where SystemTime is before UNIX_EPOCH

* fix(proxy): handle UTF-8 char boundary when truncating request body log

Rust strings are UTF-8 encoded, slicing at a fixed byte index may cut
in the middle of a multi-byte character (e.g., Chinese, emoji), causing
a panic. Use is_char_boundary() to find the nearest safe cut point.

* fix(proxy): improve robustness and prevent panics

- Add reqwest socks feature to support SOCKS proxy environments
- Fix UTF-8 safety in masked_key/masked_access_token (use chars() instead of byte slicing)
- Fix UTF-8 boundary check in usage_script HTTP response truncation
- Add defensive checks for JSON operations in proxy service
- Remove verbose debug logs that could trigger panic-prone code paths
2026-01-09 13:09:19 +08:00
sada-dev 2923627b76 fix(flatpak): bundle libayatana-appindicator for tray icon support (#556)
The Flatpak was failing to load because libayatana-appindicator3 is not
included in org.gnome.Platform runtime. This adds the required modules:
- libayatana-ido
- libdbusmenu-gtk3
- libayatana-indicator
- libayatana-appindicator

Fixes panic: 'Failed to load ayatana-appindicator3 or appindicator3 dynamic library'

Co-authored-by: Said John <said.john@gmail.com>
2026-01-09 12:20:16 +08:00
Jason 48db113b37 docs: update v3.9.0 release notes with acknowledgments and improved macOS instructions
- Add special thanks section for contributors @xunyu @deijing @su-fen
- Update macOS tip: replace xattr command with System Settings GUI guidance
- Reformat markdown tables with aligned columns
- Move Linux section after Homebrew section
2026-01-08 16:36:45 +08:00
Jason e9fc56525d docs: enhance download section with detailed installation guide for v3.9.0
- Convert system requirements to table format with architecture info
- Add Windows/macOS file descriptions with recommended options
- Replace Linux section with comprehensive distro-based table
- Include complete installation commands for deb/rpm/AppImage/flatpak
- Add helpful tips for macOS Gatekeeper and AppImage usage
2026-01-08 15:37:07 +08:00
苏风 75d512b36c docs: add download options for each system version in 3.9.0 release note (#547)
* docs: add download options for each system version in 3.9.0 release note.

* docs: add download options for each system version in 3.9.0 release note.
2026-01-08 15:04:27 +08:00
Jason 157ebaaad2 fix(ci): add --user flag to flatpak remote-add command 2026-01-08 12:49:28 +08:00
Jason 42d9afa3e2 fix(ci): remove extra '--' from Linux build command 2026-01-08 12:36:32 +08:00
Jason a0b5e3b808 chore(release): prepare v3.9.0 stable release
- Bump version from 3.9.0-3 to 3.9.0 across all config files
- Add comprehensive release notes in English, Chinese, and Japanese
- Update CHANGELOG with v3.9.0 stable and v3.9.0-2 entries
- Update README badges and release note links to v3.9.0
2026-01-08 11:24:07 +08:00
Jason effb931a1b feat(presets): add Cubence as partner provider
- Add Cubence provider presets for Claude, Codex, and Gemini
- Add Cubence icon to icon system
- Add partner promotion text in zh/en/ja
2026-01-08 11:24:07 +08:00
Jason 0456255625 docs: add Cubence as sponsor partner
Add Cubence sponsor information to README in all three languages
(English, Chinese, Japanese).
2026-01-08 11:24:07 +08:00
Dex Miller 847f1c5377 Feat/proxy header improvements (#538)
* fix(proxy): improve header handling for Claude API compatibility

- Streamline header blacklist by removing overly aggressive filtering
  (browser-specific headers like sec-fetch-*, accept-language)
- Ensure anthropic-beta header always includes 'claude-code-20250219'
  marker required by upstream services for request validation
- Centralize anthropic-version header handling in forwarder to prevent
  duplicate headers across different auth strategies
- Add ?beta=true query parameter to /v1/messages endpoint for
  compatibility with certain upstream services (e.g., DuckCoding)
- Remove redundant anthropic-version from ClaudeAdapter auth headers
  as it's now managed exclusively by the forwarder

This improves proxy reliability with various Claude API endpoints
and third-party services that have specific header requirements.

* style(services): use inline format arguments in format strings

Apply Rust 1.58+ format string syntax across provider and skill
services. This replaces format!("msg {}", var) with format!("msg {var}")
for improved readability and consistency with modern Rust idioms.

Changed files:
- services/provider/mod.rs: 1 format string
- services/skill.rs: 10 format strings (error messages, log statements)

No functional changes, purely stylistic improvement.

* fix(proxy): restrict Anthropic headers to Claude adapter only

- Move anthropic-beta and anthropic-version header handling inside
  Claude-specific condition to avoid sending unnecessary headers
  to Codex and Gemini APIs
- Update test cases to reflect ?beta=true query parameter behavior
- Add edge case tests for non-messages endpoints and existing queries
2026-01-08 11:04:42 +08:00
Jason 24a36df140 chore(presets): update model versions for provider presets
Claude presets:
- Zhipu GLM: glm-4.6 → glm-4.7
- Z.ai GLM: glm-4.6 → glm-4.7
- ModelScope: GLM-4.6 → GLM-4.7
- MiniMax: MiniMax-M2 → MiniMax-M2.1

Codex presets:
- Azure, AiHubMix, DMXAPI, PackyCode: gpt-5.1-codex → gpt-5.2
- Custom template: gpt-5-codex → gpt-5.2
2026-01-06 23:05:22 +08:00
Jason 2c4c2ce83d fix(settings): navigate to About tab when clicking update badge
- Add defaultTab prop to SettingsPage for external tab control
- UpdateBadge click now opens settings directly to About tab
- Settings button still opens to General tab (default behavior)
- Change update badge text from version number to "Update available"
2026-01-06 11:27:32 +08:00
Jason 0020889a8f fix(prompts): allow saving prompts with empty content
Remove content validation requirement to allow users to save prompts
with empty content for placeholder or draft purposes.
2026-01-05 23:30:03 +08:00
Jason 671cda60d9 fix(database): show error dialog on initialization failure with retry option
- Add user-friendly dialog when database init or schema migration fails
- Support retry mechanism instead of crashing the app
- Include bilingual (Chinese/English) error messages with troubleshooting tips
- Add comprehensive test for v3.8 → current schema migration path
2026-01-05 22:39:39 +08:00
Jason efa653809b style: format code with Prettier 2026-01-05 21:53:01 +08:00
Jason 5aa35906d8 feat(release): add RPM and Flatpak packaging support for Linux
- Add RPM bundle to Linux build targets in CI workflow
- Add Flatpak manifest, desktop entry, and AppStream metainfo
- Update release workflow to build and publish .rpm and .flatpak artifacts
- Update README docs with new Linux package formats and installation instructions
- Add .gitignore rules for Flatpak build artifacts
2026-01-05 16:35:36 +08:00
Jason 4777c99b38 refactor(settings): reorder advanced tab items for better UX
Move Auto Failover section directly after Proxy section since they are
functionally related (failover depends on proxy service).
2026-01-05 16:35:36 +08:00
duskzhen 8912216cb2 fix(common): improve window dragging area in FullScreenPanel (#525)
Add data-tauri-drag-region and WebkitAppRegion styles to header area to match	App.tsx behavior, ensuring proper window dragging on macOS.
2026-01-05 16:25:38 +08:00
Jason 32149b1eeb chore(proxy): remove unused body filter helper
Remove unused `filter_recursive` function from body_filter.rs to fix
`dead-code` warning from `cargo clippy -- -D warnings`.
2026-01-04 23:00:13 +08:00
Jason 8979d964d6 fix(proxy): clean up model override env vars when switching providers in takeover mode
When proxy takeover is enabled, switching providers no longer writes to
the Live config. However, if model override fields (ANTHROPIC_MODEL,
ANTHROPIC_REASONING_MODEL, etc.) remain in the Live config, Claude Code
continues sending requests with the old model name, causing failures
when the new provider doesn't support that model.

This fix:
- Removes model override env keys from Claude Live config during takeover
- Adds cleanup when switching providers in takeover mode
- Fixes has_mapping() to include reasoning_model in the check
- Adds test coverage for reasoning-only model mapping scenarios
2026-01-04 16:09:37 +08:00
Jason 37396b9c70 fix(common-config): reset initialization flag when preset changes
The common config checkbox was only auto-enabled for the first preset
(custom) because hasInitializedNewMode ref was permanently locked to
true after first initialization.

Add selectedPresetId parameter to all three common config hooks and
reset the initialization flag when preset changes, allowing the
initialization logic to re-run for each preset switch.
2026-01-04 12:27:22 +08:00
Jason 2c35372ca0 fix(codex): remove entire model_providers table from common config extraction
Previously only removed base_url from model_providers.* tables. Now removes
the entire model_providers section since all its fields (name, base_url,
wire_api, requires_openai_auth) are provider-specific configuration.

MCP servers configuration remains preserved as it's provider-agnostic.
2026-01-04 12:27:22 +08:00
Jason 63bb673bf2 refactor(common-config): extract snippet from editor content instead of active provider
- Change extraction source from current active provider to editor's live content
- Add i18n support for JSON parse error messages via invalid_json_format_error()
- Simplify API by removing unused providerId parameter
- Update button labels and error messages in zh/en/ja locales
2026-01-04 12:27:22 +08:00
Jason 058f86aff3 fix(codex): prevent extract_common_config from removing MCP servers' base_url
- Replace regex patterns with toml_edit for precise field removal
- Only remove top-level model/model_provider/base_url fields
- Only remove base_url from [model_providers.*] tables
- Add regression test to ensure [mcp_servers.*] base_url is preserved
2026-01-04 12:27:22 +08:00
Jason 188c94f2e3 feat(common-config): add extract from current provider functionality
- Add backend command to extract common config snippet from current provider
- Automatically extract common config on first run after importing default provider
- Auto-enable common config checkbox in new provider mode when snippet exists
- Refactor Gemini common config to operate on .env instead of config.json
- Add "Extract from Current" button to all three common config modals
- Update i18n translations for new extraction feature
2026-01-04 12:27:22 +08:00
Dex Miller c049c5f2bb feat(proxy): update failover timeout and circuit breaker defaults (#521)
- Double all timeout values (streaming/non-streaming)
- Codex/Gemini: circuit_failure_threshold 5→4, error_rate 0.5→0.6
- Claude: circuit_error_rate_threshold 0.6→0.7
2026-01-04 11:52:12 +08:00
jwaterwater c71b030662 feat: change the default Qwen BaseUrl (#517) 2026-01-04 10:54:36 +08:00
w0x7ce f363bb1dd0 Merge origin/main into main
Resolved conflict in src-tauri/src/commands/misc.rs by combining imports from both sides.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-04 09:12:12 +08:00
Jason 2105f2d05b fix(i18n): remove hardcoded defaultValue and unused placeholder for reasoning model 2026-01-03 12:04:34 +08:00
Jason 0a9de282a3 fix(skills): skip hidden directories when scanning for skills
Filter out directories starting with '.' (e.g., .system) during skill
scanning to avoid exposing internal system directories from Codex.
2026-01-03 11:42:10 +08:00
Jason 0e085aa01a fix(prompts): change toggle color from blue to emerald
Align with the app-wide Switch component color scheme for
visual consistency across all toggle elements.
2026-01-03 10:15:28 +08:00
Jason 2c95f697cd fix(prompts): unify add button style with other panels
Replace circular orange icon button with ghost text button
to match Skills and MCP panel styling.
2026-01-03 10:13:32 +08:00
Jason ba97a5f373 fix(mcp): unify header buttons style with skills panel
Changed MCP panel buttons to match Skills panel styling:
- Replace circular orange icon button with ghost text button
- Update button labels: "Import" → "Import Existing", add "Add MCP"
2026-01-03 10:11:26 +08:00
Jason 86e802bd4b feat(mcp): add import button to import MCP servers from apps
- Add import_mcp_from_apps command that reuses existing import logic
- Add Import button in MCP panel header (consistent with Skills)
- Fix import count to only return truly new servers (not already in DB)
- Update translations for import success/no-import messages (zh/en/ja)
2026-01-03 10:04:46 +08:00
Jason 6460c1d5dd fix(skills): move import button to header for better discoverability
- Add import button next to discover button in skills page header
- Expose openImport method via UnifiedSkillsPanel ref
- Show toast instead of dialog when no unmanaged skills found
- Remove redundant buttons from empty state view
2026-01-03 09:21:15 +08:00
Jason 6b73e55bfe fix(ui): remove hover scale effect from skill cards
The hover:scale-[1.01] effect caused cards to overflow their container
boundaries. Keeping only hover:shadow-lg provides sufficient visual
feedback without the overflow issue.
2026-01-02 23:57:22 +08:00
Jason 47aa4c6bee fix(skills): show loading indicator when refreshing discovery list
Use isFetching instead of just isLoading to show the loading spinner.
isLoading is only true on initial load, while isFetching is true
during any fetch operation including refetch.
2026-01-02 23:51:03 +08:00
Jason 4dc59dff21 fix(skills): remove refresh button from installed skills panel
The refresh button is only needed in the discovery panel (to fetch
latest skills from GitHub). The installed skills panel uses local
database which auto-updates on install/uninstall operations.
2026-01-02 23:41:28 +08:00
Jason c8750f5550 fix(i18n): rename Skills title to be app-agnostic
- Remove "Claude" prefix from Skills management title
- Update descriptions to include Gemini alongside Claude Code/Codex
- Applied to all three locales: zh, en, ja
2026-01-02 23:15:22 +08:00
Jason 22460de976 perf(skills): use infinite cache for discoverable skills
Change staleTime from 5 minutes to Infinity. Cache is still properly
invalidated when repos are added/removed or skills are installed/uninstalled.
2026-01-02 23:04:40 +08:00
Jason e69c1bd8aa fix(ui): align FullScreenPanel header with App.tsx layout
- Use same DRAG_BAR_HEIGHT (28px) and HEADER_HEIGHT (64px) as App.tsx
- Remove border-b divider line from header
- Add rounded-lg class to back button for consistency
2026-01-02 22:35:33 +08:00
Jason a17fa8098b fix(skills): remove redundant navigation buttons in skills pages
- Remove duplicate "Repo Manager" button from installed skills view
  (should only appear in discovery view)
- Remove redundant back button from SkillsPage component
  (header already provides unified navigation)
- Clean up unused openRepoManagerOnDiscovery state and related useEffect
- Remove unused onClose prop and ArrowLeft import from SkillsPage
2026-01-02 22:33:33 +08:00
Jason ff03ca1e63 feat(skills): unified management architecture with SSOT and React Query
- Introduce SSOT (Single Source of Truth) at ~/.cc-switch/skills/
- Add three-app toggle support (Claude/Codex/Gemini) for each skill
- Refactor frontend to use TanStack Query hooks instead of manual state
- Add UnifiedSkillsPanel for managing installed skills with app toggles
- Add useSkills.ts with declarative data fetching hooks
- Extend skills.ts API with unified install/uninstall/toggle methods
- Support importing unmanaged skills from app directories
- Add v2→v3 database migration for new skills table structure
2026-01-02 22:04:02 +08:00
Jason cce6ae86a5 fix: prevent env check card border overflow on hover
Add horizontal padding to the grid container to accommodate the scale
transform effect when hovering over environment check cards.
2025-12-31 22:58:03 +08:00
Dex Miller 5376ea042b Feat/usage improvements (#508)
* i18n: update cache terminology across all languages

- Change 'Cache Read' to 'Cache Hit' in all languages
- Change 'Cache Write' to 'Cache Creation' in all languages
- Update zh: 缓存读取 → 缓存命中, 缓存写入 → 缓存创建
- Update en: Cache Read → Cache Hit, Cache Write → Cache Creation
- Update ja: キャッシュ読取 → キャッシュヒット, キャッシュ書込 → キャッシュ作成

Affected keys: cacheReadTokens, cacheCreationTokens, cacheReadCost,
cacheWriteCost, cacheRead, cacheWrite

* feat(usage): add cache metrics to trend chart

- Add cache creation tokens visualization (orange line)
- Add cache hit tokens visualization (purple line)
- Add gradient definitions for new cache metrics
- Include cache data in hourly aggregation
- Display cache metrics alongside input/output tokens

This provides better visibility into cache usage patterns over time.

* fix(usage): fix timezone handling in datetime picker

- Add timestampToLocalDatetime() to convert Unix timestamp to local datetime
- Add localDatetimeToTimestamp() with validation for incomplete input
- Fix issue where typing hours/minutes would jump to previous day
- Validate datetime format completeness before conversion
- Use local timezone instead of UTC for datetime-local input

This resolves the issue where users couldn't fine-tune time selection
and the input would jump unexpectedly when editing hours or minutes.

* feat(usage): add auto-refresh for usage statistics

- Add 30-second auto-refresh interval for all usage queries
- Disable background refresh to save resources
- Apply to: summary, trends, provider stats, model stats, request logs
- Queries automatically update when tab is active
- Pause refresh when user switches to another tab

This keeps usage data fresh without manual refresh.

* fix(proxy): improve usage logging and cache token parsing

- Log requests even when usage parsing fails (with default values)
- Add detailed debug logging for usage metrics
- Support cache_read_input_tokens field in Codex responses
- Fallback to input_tokens_details.cached_tokens if needed
- Add test case for cached_tokens in input_tokens_details
- Ensure all requests are tracked in database for analytics

This fixes missing request logs when API responses lack usage data
and improves cache token detection across different response formats.

* style(rust): use inline format args in format! macros

- Replace format!("...", var) with format!("...{var}")
- Update universal provider ID formatting
- Update error message formatting
- Update config.toml generation in Codex provider

Fixes clippy::uninlined_format_args warnings.

* feat(proxy): enhance provider router logging

- Add debug logs for failover queue provider count
- Log circuit breaker state for each provider check
- Add logs for missing current provider scenarios
- Log when no current provider is configured
- Use inline format args for better readability

This improves debugging of provider selection and failover behavior.

* feat(database): update model pricing data

- Update Claude models to full version format (e.g. claude-opus-4-5-20251101)
- Add GPT-5.2 series model pricing (10 models)
- Add GPT-5.1 series model pricing (10 models)
- Add GPT-5 series model pricing (12 models)
- Add Gemini 3 series model pricing (2 models)
- Update Gemini 2.5 series model ID format (use dot separator)
- Unify display names by removing thinking level suffixes

* fix(usage): correct Gemini output token calculation

Fix Gemini API output token parsing to use totalTokenCount - promptTokenCount
instead of candidatesTokenCount alone. This ensures thoughtsTokenCount is
included in output statistics.

- Update from_gemini_response to calculate output from total - input
- Update from_gemini_stream_chunks with same logic for consistency
- Fix from_codex_stream_events to use adjusted token calculation
- Add test case for responses with thoughtsTokenCount
- Update existing tests to match new calculation logic

* fix(usage): correct cache token billing and add Codex format auto-detection

- Avoid double-billing cache tokens by subtracting from input before calculation
- Add smart Codex parser that auto-detects OpenAI vs Codex API format
- Extract model name from Codex responses for accurate tracking

* fix(proxy): improve takeover detection with live config check

- Add live config takeover detection for hot-switch decision
- Rebuild takeover when backup is missing or placeholder remains
- Make detect_takeover_in_live_config_for_app public
- Fix is_takeover_active to use actual takeover status

* refactor(usage): simplify model pricing lookup by removing suffix fallback

Replace complex suffix-stripping fallback with direct prefix/suffix cleanup.
Model IDs are now cleaned by removing vendor prefix (before /) and colon
suffix (after :), then matched exactly against pricing table.

* feat(database): add Chinese AI model pricing data

Add pricing for domestic AI models (CNY/1M tokens):
- Doubao-Seed-Code (ByteDance)
- DeepSeek V3/V3.1/V3.2
- Kimi K2/K2-Thinking/K2-Turbo (Moonshot)
- MiniMax M2/M2.1/M2.1-Lightning
- GLM-4.6/4.7 (Zhipu)
- Mimo V2 Flash (Xiaomi)

Also fix test case to use correct model ID and remove invalid currency column.

* refactor(proxy): improve header forwarding with blacklist approach

Change from whitelist to blacklist mode for request header forwarding.
Only skip headers that will be overridden (auth, host, content-length).
This preserves client's original headers and improves compatibility.

* fix(proxy): bypass timeout and retry configs when failover is disabled

When auto_failover_enabled is false, timeout and retry configurations
should not affect normal request flow. This change ensures:

- create_forwarder: passes 0 for all timeout/retry params when failover
  is disabled, effectively bypassing these checks
- streaming_timeout_config: returns 0 for both first_byte_timeout and
  idle_timeout when failover is disabled

This prevents unnecessary timeout errors and retry attempts when users
have explicitly disabled the failover feature.

* fix(proxy): handle zero value input in failover config fields

* refactor(proxy): remove retry logic and add enabled check for failover

* refactor(proxy): distinguish circuit-open from no-provider errors

* Align usage stats to sliding windows

* feat(proxy): add body and header filtering for upstream requests

* feat(proxy): enable transparent passthrough for headers

- Passthrough anthropic-beta header as-is from client
- Passthrough anthropic-version header from client
- Passthrough client IP headers (x-forwarded-for, x-real-ip) by default
- Filter private params (underscore-prefixed fields) from request body
- No database changes required

* feat(proxy): extract session ID from client requests for logging

- Add SessionIdExtractor to parse session ID from Claude/Codex requests
- Support extraction from metadata.user_id, headers, previous_response_id
- Pass session_id through RequestContext to usage logger
- Enable request correlation by session in proxy_request_logs
2025-12-31 22:57:00 +08:00
w0x7ce a2becf0917 refactor(commands): improve terminal launch code structure and fix env vars
重构 open_provider_terminal 相关代码,提升可维护性和可读性。

主要改进:
- 将 launch_terminal_with_env 拆分为多个职责单一的小函数
  * write_claude_config: 写入配置文件
  * escape_shell_path: 转义 shell 路径
  * generate_wrapper_script: 生成包装脚本
  * launch_macos_terminal / launch_linux_terminal / launch_windows_terminal: 平台特定启动逻辑
- 使用 let Some else 提前返回模式,减少嵌套
- 修复 Gemini 环境变量名为 GEMINI_API_KEY(而非 GOOGLE_API_KEY)
- 完善临时文件清理逻辑:
  * macOS/Linux: 使用 trap EXIT 自动清理
  * Windows: 批处理文件自删除
- 代码格式化和 import 排序优化

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-31 09:17:36 +08:00
Kjasn d0431b66ae fix wrong skill repo branch (#505)
Co-authored-by: yrs <yuruosheng@17paipai.cn>
2025-12-30 15:38:19 +08:00
Jason eaddcbedd7 chore: bump version to 3.9.0-3 2025-12-30 09:03:53 +08:00
Jason 83a5597756 fix: resolve test failures and clippy warnings
- tests/App.test.tsx: remove outdated SettingsPage mock, use dynamic import
- database/tests.rs: remove unused field, use struct init syntax
- deeplink/tests.rs: use idiomatic assert!() instead of assert_eq!(true)
- support.rs: add #[allow(dead_code)] for test utilities
- usage_stats.rs: code formatting
2025-12-30 08:54:48 +08:00
tianrking debe4232bc Update misc.rs 2025-12-29 23:47:30 +08:00
Dex Miller bcfc22514c fix: use local timezone and robust DST handling in usage stats (#500)
- Change from UTC to local timezone for daily/hourly trends
- Use SQLite 'localtime' modifier for date grouping
- Replace single().unwrap() with earliest().unwrap_or_else()
  to handle DST transition edge cases gracefully
2025-12-29 23:46:26 +08:00
Jason 443e23c77e fix(windows): wrap npx/npm commands with cmd /c for MCP export
On Windows, npx, npm, yarn, pnpm, node, bun, and deno are actually
.cmd batch files that require cmd /c wrapper to execute properly.
This fixes the Claude Code /doctor warning:
"Windows requires 'cmd /c' wrapper to execute npx"

The transformation is applied when exporting MCP config to ~/.claude.json:
- Before: {"command": "npx", "args": ["-y", "foo"]}
- After:  {"command": "cmd", "args": ["/c", "npx", "-y", "foo"]}

Uses conditional compilation (#[cfg(windows)]) for zero overhead on
other platforms.

Closes #453
2025-12-29 23:20:32 +08:00
Jason f26a01137d fix(windows): prevent terminal windows from appearing during version check
On Windows, opening the Settings > About section would spawn three
terminal windows when checking CLI tool versions (claude, codex, gemini).

Root cause:
- scan_cli_version() directly executed .cmd files, but child processes
  (node.exe) spawned by these batch scripts didn't inherit CREATE_NO_WINDOW
- PATH separator used Unix-style ":" instead of Windows ";"

Fix:
- Wrap command execution with `cmd /C` to ensure all child processes
  run within the same hidden console session
- Use platform-specific PATH separators via conditional compilation
2025-12-29 22:28:59 +08:00
Jason 1be9c56ec5 fix(ui): resolve Dialog/Modal not opening on first click
Two bugs were caused by ref synchronization race condition in commit 7d495aa:
- EditProviderDialog: provider prop was null on first render
- UsageScriptModal: conditional render guard was false on first click

Root cause: useEffect updates ref asynchronously, but render happens before
effect runs. On first click, ref is still null causing components to fail.

Solution: Create useLastValidValue hook that updates ref synchronously during
render phase instead of in useEffect. This ensures ref is always in sync with
state, eliminating the race condition.

Changes:
- Add useLastValidValue hook for preserving last valid value during animations
- Replace manual ref + useEffect pattern with the new hook
- Remove non-null assertions (!) that were needed as workaround
2025-12-29 22:14:34 +08:00
Dex Miller 2651b65b10 fix(schema): add missing base columns migration for proxy_config (#492)
* fix(schema): add missing base columns migration for proxy_config

Add compatibility migration for older databases that may be missing
the basic proxy_config columns (proxy_enabled, listen_address,
listen_port, enable_logging) before adding newer timeout fields.

* fix: add proxy_config base column patches for v3.9.0-2 upgrade

Add base config column patches in create_tables_on_conn():
- proxy_enabled
- listen_address
- listen_port
- enable_logging

Ensures v3.9.0-2 users (user_version=2 but missing columns)
can properly upgrade with all required fields added.

* fix: migrate proxy_config singleton to per-app on startup for v2 databases

Add startup migration for legacy proxy_config tables that still have
singleton structure (no app_type column) even with user_version=2.

This fixes the issue where v3.9.0-2 databases with v2 schema but legacy
proxy_config structure would fail with "no such column: app_type" error.

- Call migrate_proxy_config_to_per_app in create_tables_on_conn
- Add regression test to verify the fix

* style: cargo fmt

---------

Co-authored-by: Jason <farion1231@gmail.com>
2025-12-29 17:25:25 +08:00
w0x7ce 49a2e52b20 fix(ui): only show terminal button for Claude Code providers
open_provider_terminal 功能仅支持 Claude Code,因此只在 Claude 应用中显示终端按钮。

修改内容:
- 在 ProviderList 组件调用时,根据 activeApp 条件传递 onOpenTerminal
- 仅当 activeApp === "claude" 时传递 handleOpenTerminal 回调
- Codex 和 Gemini 不会显示终端按钮(onOpenTerminal 为 undefined)

影响范围:
- src/App.tsx

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-29 10:05:52 +08:00
w0x7ce ed9d9b5436 fix(commands): add auto-cleanup for temp config files when terminal closes
在 open_provider_terminal 功能中添加了临时配置文件的自动清理逻辑,
确保在用户关闭终端窗口时自动删除创建的临时配置文件。

修改内容:
- Linux: 使用 bash -c 嵌套包装脚本,通过 trap EXIT 信号在 shell 退出时清理配置文件
- macOS: 同样使用嵌套 bash + trap 机制来处理清理
- Windows: 保持原有的批处理文件自删除逻辑(del 命令)

技术细节:
- 之前使用 sh -c "...; exec $SHELL" 会导致 trap 失效
- 现在使用 bash -c 'trap ... EXIT; ...; exec bash --norc --noprofile'
- exec 会替换进程但保留 trap 信号处理器
- 当用户关闭终端时,EXIT 信号触发清理操作

影响范围:
- src-tauri/src/commands/misc.rs (launch_terminal_with_env 函数)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-29 09:36:55 +08:00
w0x7ce 390839a8d5 Merge upstream/main into main
Resolved conflicts in src-tauri/src/lib.rs:
- Kept both: open_provider_terminal (my feature) and universal provider commands (upstream)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-29 09:14:42 +08:00
TinsFox 7fdaeacb5b feat: open settings via command comma (#436) 2025-12-28 22:52:51 +08:00
TinsFox 9716eb797f chore: 更新 vite 版本 && 使用 code-inspector-plugin 方便从前端定位到代码位置 (#430)
* chore: 更新 vite 版本 && 使用 code-inspector-plugin 方便从前端定位到代码位置

* fix: update tailwind config path and conditionally load code-inspector-plugin

- Update components.json to reference tailwind.config.cjs instead of deleted tailwind.config.js
- Load codeInspectorPlugin only in dev mode to avoid unnecessary code in production builds

---------

Co-authored-by: Jason <farion1231@gmail.com>
2025-12-28 21:34:41 +08:00
lif 91deaf094e fix: 移除已废弃的 sync_enabled_to_codex 调用 (#460)
* fix(mcp): 移除同步Codex Provider时的旧MCP同步调用

sync_enabled_to_codex使用旧的config.mcp.codex结构,
在v3.7.0统一结构中该字段为空,导致MCP配置被错误清除。
MCP同步应通过McpService进行。

Fixes #403

* test(mcp): update test to reflect new MCP sync architecture

Remove MCP-related assertions from sync_codex_provider_writes_auth_and_config
test since provider switching no longer triggers MCP sync in v3.7.0+.

MCP synchronization is now handled independently by McpService,
not as part of the provider switch flow.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2025-12-27 21:12:07 +08:00
lif 3a548152a9 fix: MCP同步时优雅处理无效的Codex config.toml (#461)
* fix(mcp): 移除同步Codex Provider时的旧MCP同步调用

sync_enabled_to_codex使用旧的config.mcp.codex结构,
在v3.7.0统一结构中该字段为空,导致MCP配置被错误清除。
MCP同步应通过McpService进行。

Fixes #403

* fix(mcp): 优雅处理Codex配置文件解析失败的情况

当~/.codex/config.toml存在但内容无效时,MCP同步操作会失败,
导致后续provider切换等操作也失败。

修改sync_single_server_to_codex和remove_server_from_codex函数,
在配置文件解析失败时进行容错处理而不是返回错误。

Fixes #393
2025-12-27 18:05:58 +08:00
lif a8f7cda167 fix(macos): use .app bundle path for autostart to prevent terminal window (#462)
On macOS, the auto-launch library requires the .app bundle path (e.g.,
/Applications/CC Switch.app) rather than the binary path inside the bundle
(e.g., .app/Contents/MacOS/CC Switch). Using the binary path directly
causes AppleScript login items to open a terminal window.

This fix extracts the .app bundle path from current_exe() on macOS,
ensuring proper integration with macOS login items.

Closes #375
2025-12-27 16:45:17 +08:00
Calcium-Ion 8fe5c1041a feat: add Universal Provider feature (#348)
* feat: add Universal Provider feature

- Add Universal Provider data structures and type definitions
- Implement backend CRUD operations and sync functionality
- Add frontend UI components (UniversalProviderPanel, Card, FormModal)
- Add NewAPI icon and preset configuration
- Support cross-app (Claude/Codex/Gemini) configuration sync
- Add website URL field for providers
- Implement real-time refresh via event notifications
- Add i18n support (Chinese/English/Japanese)

* feat: integrate universal provider presets into add provider dialog

- Add universal provider presets (NewAPI, Custom Gateway) to preset selector
- Show universal presets with Layers icon badge in preset selector
- Open UniversalProviderFormModal when universal preset is clicked
- Pass initialPreset to auto-fill form when opened from add dialog
- Add i18n keys for addSuccess/addFailed messages
- Keep separate universal provider panel for management

* refactor: move universal provider management to add dialog

- Remove Layers button from main navigation header
- Add 'Manage' button next to universal provider presets
- Open UniversalProviderPanel from within add provider dialog
- Add i18n keys for 'manage' in all locales

* style: display universal provider presets on separate line

- Move universal provider section to a new row with border separator
- Add label '统一供应商:' to clarify the section

* style: unify universal provider label style with preset label

- Use FormLabel component for consistent styling
- Add background to 'Manage' button matching preset buttons
- Update icon size and button padding for consistency

* feat: add sync functionality and JSON preview for Universal Provider

* fix: add missing in_failover_queue field to Provider structs

After rebasing to main, the Provider struct gained a new
`in_failover_queue` field. This fix adds the missing field
to the three to_*_provider() methods in UniversalProvider.

* refactor: redesign AddProviderDialog with tab-based layout

- Add tabs to separate app-specific providers and universal providers
- Move "Add Universal Provider" button from panel header to footer
- Remove unused handleAdd callback and clean up imports
- Update emptyHint i18n text to reference the footer button

* fix: append /v1 suffix to Codex base_url in Universal Provider

Codex uses OpenAI-compatible API which requires the /v1 endpoint suffix.
The Universal Provider now automatically appends /v1 to base_url when
generating Codex provider config if not already present.

- Handle trailing slashes to avoid double slashes
- Apply fix to both backend (to_codex_provider) and frontend preview

* feat: auto-sync universal provider to apps on creation

Previously, users had to manually click sync after adding a universal
provider. Now it automatically syncs to Claude/Codex/Gemini on creation,
providing a smoother user experience.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2025-12-26 22:47:24 +08:00
Jason a24753f074 fix(i18n): add missing translations for reasoning model and OpenRouter compat mode
Add missing i18n keys introduced in commit e6f18ba:
- providerForm.anthropicReasoningModel
- providerForm.reasoningModelPlaceholder
- providerForm.openrouterCompatMode
- providerForm.openrouterCompatModeHint
- proxy.failover.proxyRequired
2025-12-26 00:01:59 +08:00
Jason 079ee687a8 docs: make sponsor logos clickable and update sponsor list
- Make all sponsor logos clickable links in README files (EN/ZH/JA)
- Replace ShanDianShuo with DMXAPI sponsor
- Add DMXAPI logo images (dmx-en.jpg, dmx-zh.jpeg)
- Unify sponsor list across all language versions
2025-12-25 23:30:45 +08:00
Jason e08c67b88f chore: update GLM partner banner images 2025-12-25 22:53:32 +08:00
Jason bb2756d0fb fix(ui): improve dark mode text contrast for form labels
Replace hardcoded Tailwind color classes with design system CSS variables
to improve text visibility in dark mode:

- text-gray-900 dark:text-gray-100 → text-foreground
- text-gray-500/600 dark:text-gray-400 → text-muted-foreground
- bg-white dark:bg-gray-800 → bg-background
2025-12-25 17:37:11 +08:00
Weiyi Xu c87bb43aaa feat: add xiaomi mimo icon and claude provider configuration (#470) 2025-12-25 17:30:29 +08:00
Jason 8f58c08d0d fix(database): add backward compatibility check for proxy_config seed insert
Add has_column check before inserting seed data into proxy_config table.
This prevents SQL errors when upgrading from older databases where
proxy_config was a singleton table without the app_type column.

The migration function will handle the table structure upgrade and
insert the three rows after converting to the new schema.
2025-12-25 16:04:34 +08:00
YoVinchen e6f18ba801 Feat/usage model extraction (#455)
* feat(proxy): extract model name from API response for accurate usage tracking

- Add model field extraction in TokenUsage parsing for Claude, OpenAI, and Codex
- Prioritize response model over request model in usage logging
- Update model extractors to use parsed usage.model first
- Add tests for model extraction in stream and non-stream responses

* feat(proxy): implement streaming timeout control with validation

- Add first byte timeout (0 or 1-180s) for streaming requests
- Add idle timeout (0 or 60-600s) for streaming data gaps
- Add non-streaming timeout (0 or 60-1800s) for total request
- Implement timeout logic in response processor
- Add 1800s global timeout fallback when disabled
- Add database schema migration for timeout fields
- Add i18n translations for timeout settings

* feat(proxy): add model mapping module for provider-based model substitution

- Add model_mapper.rs with ModelMapping struct to extract model configs from Provider
- Support ANTHROPIC_MODEL, ANTHROPIC_REASONING_MODEL, and default models for haiku/sonnet/opus
- Implement thinking mode detection for reasoning model priority
- Include comprehensive unit tests for all mapping scenarios

* fix(proxy): bypass circuit breaker for single provider scenario

When failover is disabled (single provider), circuit breaker open state
would block all requests causing poor UX. Now bypasses circuit breaker
check in this scenario. Also integrates model mapping into request flow.

* feat(ui): add reasoning model field to Claude provider form

Add ANTHROPIC_REASONING_MODEL configuration field for Claude providers,
allowing users to specify a dedicated model for thinking/reasoning tasks.

* feat(proxy): add openrouter_compat_mode for optional format conversion

Add configurable OpenRouter compatibility mode that enables Anthropic to
OpenAI format conversion. When enabled, rewrites endpoint to /v1/chat/completions
and transforms request/response formats. Defaults to enabled for OpenRouter.

* feat(ui): add OpenRouter compatibility mode toggle

Add UI toggle for OpenRouter providers to enable/disable compatibility
mode which uses OpenAI Chat Completions format with SSE conversion.

* feat(stream-check): use provider-configured model for health checks

Extract model from provider's settings_config (ANTHROPIC_MODEL, GEMINI_MODEL,
or Codex config.toml) instead of always using default test models.

* refactor(ui): remove timeout settings from AutoFailoverConfigPanel

Remove streaming/non-streaming timeout configuration from failover panel
as these settings have been moved to a dedicated location.

* refactor(database): migrate proxy_config to per-app three-row structure

Replace singleton proxy_config table with app_type primary key structure,
allowing independent proxy settings for Claude, Codex, and Gemini.
Add GlobalProxyConfig queries and per-app config management in DAO layer.

* feat(proxy): add GlobalProxyConfig and AppProxyConfig types

Add new type definitions for the refactored proxy configuration:
- GlobalProxyConfig: shared settings (enabled, address, port, logging)
- AppProxyConfig: per-app settings (failover, timeouts, circuit breaker)

* refactor(proxy): update service layer for per-app config structure

Adapt proxy service, handler context, and provider router to use
the new per-app configuration model. Read enabled/timeout settings
from proxy_config table instead of settings table.

* feat(commands): add global and per-app proxy config commands

Add new Tauri commands for the refactored proxy configuration:
- get_global_proxy_config / update_global_proxy_config
- get_proxy_config_for_app / update_proxy_config_for_app
Update startup restore logic to read from proxy_config table.

* feat(api): add frontend API and Query hooks for proxy config

Add TypeScript wrappers and TanStack Query hooks for:
- Global proxy config (address, port, logging)
- Per-app proxy config (failover, timeouts, circuit breaker)
- Proxy takeover status management

* refactor(ui): redesign proxy panel with inline config controls

Replace ProxySettingsDialog with inline controls in ProxyPanel.
Add per-app takeover switches and global address/port settings.
Simplify AutoFailoverConfigPanel by removing timeout settings.

* feat(i18n): add proxy takeover translations and update types

Add i18n strings for proxy takeover status in zh/en/ja.
Update TypeScript types for GlobalProxyConfig and AppProxyConfig.

* refactor(proxy): load circuit breaker config per-app instead of globally

Extract app_type from router key and read circuit breaker settings
from the corresponding proxy_config row for each application.
2025-12-25 10:40:11 +08:00
w0x7ce 3dcbe313be feat: add provider-specific terminal button
Add a terminal button next to each provider card that opens a new terminal
window with that provider's specific API configuration. This allows using
different providers independently without changing the global setting.

Changes:
- Backend: Add `open_provider_terminal` command that extracts provider
  config and creates a temporary claude settings file
- Frontend: Add terminal button to provider cards with proper callback
  propagation through component hierarchy
- Support macOS (Terminal.app), Linux (gnome-terminal, konsole, etc.),
  and Windows (cmd)

Each provider gets a unique config file named `claude_<providerId>_<pid>.json`
in the temp directory, containing the provider's API configuration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-23 17:11:20 +08:00
Jason 7d495aa772 feat(ui): add exit animation to FullScreenPanel dialogs
- Wrap FullScreenPanel content with AnimatePresence for exit animation
- Add exit={{ opacity: 0 }} to enable fade-out on close
- Use useRef + useEffect to preserve provider data during exit animation
- Follow React best practices by updating refs in useEffect instead of render

Affected components:
- EditProviderDialog
- UsageScriptModal
- AddProviderDialog
- McpFormModal
- ProxySettingsDialog
2025-12-23 16:18:28 +08:00
Jason db8180aa31 fix(ui): reduce header spacing and fix layout shift on view switch
- Change right-side button container from min-h-[40px] to h-[32px]
  for more compact header layout
- Remove conditional padding (pt-6/pt-4) from main content area
  to eliminate layout jump during view transitions
2025-12-23 16:18:28 +08:00
YoVinchen 1586451862 Feat/auto failover switch (#440)
* feat(failover): add auto-failover master switch with proxy integration

- Add persistent auto_failover_enabled setting in database
- Add get/set_auto_failover_enabled commands
- Provider router respects master switch state
- Proxy shutdown automatically disables failover
- Enabling failover auto-starts proxy server
- Optimistic updates for failover queue toggle

* feat(proxy): persist proxy takeover state across app restarts

- Add proxy_takeover_{app_type} settings for per-app state tracking
- Restore proxy takeover state automatically on app startup
- Preserve state on normal exit, clear on manual stop
- Add stop_with_restore_keep_state method for graceful shutdown

* fix(proxy): set takeover state for all apps in start_with_takeover

* fix(windows): hide console window when checking CLI versions

Add CREATE_NO_WINDOW flag to prevent command prompt from flashing
when detecting claude/codex/gemini CLI versions on Windows.

* refactor(failover): make auto-failover toggle per-app independent

- Change setting key from 'auto_failover_enabled' to 'auto_failover_enabled_{app_type}'
- Update provider_router to check per-app failover setting
- When failover disabled, use current provider only; when enabled, use queue order
- Add unit tests for failover enabled/disabled behavior

* feat(failover): auto-switch to higher priority provider on recovery

- After circuit breaker reset, check if recovered provider has higher priority
- Automatically switch back if queue_order is lower (higher priority)
- Stream health check now resets circuit breaker on success/degraded

* chore: remove unused start_proxy_with_takeover command

- Remove command registration from lib.rs
- Add comment clarifying failover queue is preserved on proxy stop

* feat(ui): integrate failover controls into provider cards

- Add failover toggle button to provider card actions
- Show priority badge (P1, P2, ...) for queued providers
- Highlight active provider with green border in failover mode
- Sync drag-drop order with failover queue
- Move per-app failover toggle to FailoverQueueManager
- Simplify SettingsPage failover section

* test(providers): add mocks for failover hooks in ProviderList tests

* refactor(failover): merge failover_queue table into providers

- Add in_failover_queue field to providers table
- Remove standalone failover_queue table and related indexes
- Simplify queue ordering by reusing sort_index field
- Remove reorder_failover_queue and set_failover_item_enabled commands
- Update frontend to use simplified FailoverQueueItem type

* fix(database): ensure in_failover_queue column exists for v2 databases

Add column check in create_tables to handle existing v2 databases
that were created before the failover queue refactor.

* fix(ui): differentiate active provider border color by proxy mode

- Use green border/gradient when proxy takeover is active
- Use blue border/gradient in normal mode (no proxy)
- Improves visual distinction between proxy and non-proxy states

* fix(database): clear provider health record when removing from failover queue

When a provider is removed from the failover queue, its health monitoring
is no longer needed. This change ensures the health record is also deleted
from the database to prevent stale data.

* fix(failover): improve cache cleanup for provider health and circuit breaker

- Use removeQueries instead of invalidateQueries when stopping proxy to
  completely clear health and circuit breaker caches
- Clear provider health and circuit breaker caches when removing from
  failover queue
- Refresh failover queue after drag-sort since queue order depends on
  sort_index
- Only show health badge when provider is in failover queue

* style: apply prettier formatting to App.tsx and ProviderList.tsx

* fix(proxy): handle missing health records and clear health on proxy stop

- Return default healthy state when provider health record not found
- Add clear_provider_health_for_app to clear health for specific app
- Clear app health records when stopping proxy takeover

* fix(proxy): track actual provider used in forwarding for accurate logging

Introduce ForwardResult and ForwardError structs to return the actual
provider that handled the request. This ensures usage statistics and
error logs reflect the correct provider after failover.
2025-12-23 12:37:36 +08:00
Jason bf570b6d2a fix(ui): prevent header layout shift when switching views
Add min-height to right-side button container and ml-auto to add buttons
in MCP/Prompts views to maintain consistent header height and button
position across all views.
2025-12-22 16:54:49 +08:00
Jason 26c3f05daf feat(ui): add fade transition for view and panel switching
Add smooth fade animations when navigating between views (Settings,
MCP, Skills, Prompts) and opening full-screen panels (Add/Edit Provider).
2025-12-22 16:54:49 +08:00
TinsFox d303706d51 feat: add provider search filter (#435)
* feat: add provider search filter

* feat: add provider search overlay
2025-12-22 15:46:11 +08:00
TinsFox 97495d1550 Remove macOS titlebar tint and align custom header (#438) 2025-12-22 15:43:28 +08:00
YoVinchen a1537807eb feat(failover): add auto-failover master switch with proxy integration (#427)
* feat(failover): add auto-failover master switch with proxy integration

- Add persistent auto_failover_enabled setting in database
- Add get/set_auto_failover_enabled commands
- Provider router respects master switch state
- Proxy shutdown automatically disables failover
- Enabling failover auto-starts proxy server
- Optimistic updates for failover queue toggle

* feat(proxy): persist proxy takeover state across app restarts

- Add proxy_takeover_{app_type} settings for per-app state tracking
- Restore proxy takeover state automatically on app startup
- Preserve state on normal exit, clear on manual stop
- Add stop_with_restore_keep_state method for graceful shutdown

* fix(proxy): set takeover state for all apps in start_with_takeover
2025-12-21 22:39:50 +08:00
TinsFox f047960a33 Use macOS tray template icon (#434) 2025-12-21 21:10:00 +08:00
TinsFox ace9b38cee style: remove shadow (#431) 2025-12-21 21:09:37 +08:00
Jason b67cdbb18c feat(ui): add fade transition for app switching
- Add AnimatePresence + motion.div wrapper for provider list
- Use key={activeApp} to trigger enter/exit animations on app switch
- Remove redundant animate-slide-up from ProviderList to prevent
  animation conflicts and visual jitter
2025-12-21 10:27:56 +08:00
Jason c4f1e90893 style(settings): unify tab transition animations
Add framer-motion fade-in and slide-up animations to General and
Advanced tabs, matching the existing Usage and About tab animations.
2025-12-21 09:29:14 +08:00
Jason ddbff070d5 feat(settings): add option to skip Claude Code first-run confirmation
Add a new setting to automatically skip Claude Code's onboarding screen
by writing hasCompletedOnboarding=true to ~/.claude.json. The setting
defaults to enabled for better user experience.

- Add set/clear_has_completed_onboarding functions in claude_mcp.rs
- Add Tauri commands and frontend API integration
- Add toggle in WindowSettings with i18n support (en/zh/ja)
- Fix hardcoded Chinese text in tests to use i18n keys
2025-12-20 23:55:10 +08:00
Jason ca7cb398c2 i18n: complete usage panel and settings internationalization
- Add missing i18n keys for usage statistics panel (trends, cost, perMillion, etc.)
- Add i18n keys for settings advanced section (configDir, proxy, modelTest, etc.)
- Add streamCheck i18n keys for health check configuration
- Remove hardcoded Chinese fallback values from t() calls
- Add common keys (all, search, reset, actions, deleting)
2025-12-20 22:29:39 +08:00
Jason 2fb3b5405a i18n: complete internationalization for v3.8+ features
- Add health status translations (operational, degraded, failed, circuitOpen)
- Add proxy panel translations (serviceAddress, stats, stopped state)
- Add usage filter translations (appType, statusCode, searchPlaceholder)
- Add providerIcon click hints (clickToChange, clickToSelect)
- Add config load error translations for main.tsx
- Complete Japanese proxy section (failoverQueue, autoFailover)
- Fix date/time locale in usage charts and tables
- Use t() function in all hardcoded UI strings
2025-12-20 21:38:37 +08:00
Jason ec649e7718 style(switch): improve dark mode appearance
- Track (unchecked): lighten in light mode (gray-300 → gray-200),
  darken in dark mode (gray-700 → gray-900) to blend with background
- Thumb: soften in dark mode (white → gray-400) to reduce glare
2025-12-20 19:18:29 +08:00
Jason 3da5525c79 fix(ui): improve text visibility in dark mode
Replace hardcoded gray color classes with semantic color classes
to fix poor text contrast in dark mode:

- MCP panel: server names, descriptions, tags, app labels
- Prompt panel: prompt names, descriptions, empty states
- Usage footer: timestamps, refresh buttons
- Update badge: close button icon
- API key input: disabled state text
- Env warning banner: source info text

Changes:
- `text-gray-400 dark:text-gray-500` → `text-muted-foreground`
  (fixes reversed dark mode logic)
- `text-gray-500 dark:text-gray-400` → `text-muted-foreground`
- `bg-gray-100 dark:bg-gray-800` → `bg-muted`
2025-12-20 18:57:36 +08:00
Jason 44ca688253 chore: bump version to 3.9.0-2 for second test release
- Update version in package.json, Cargo.toml, tauri.conf.json
- Fix clippy too_many_arguments warning in forwarder.rs
2025-12-20 18:10:45 +08:00
Jason 5fe5ed98be style(header): unify height and styling of header toolbar sections
- Use consistent h-8 fixed height for all inner elements
- Standardize border-radius to rounded-xl across all sections
- Remove background from ProxyToggle for cleaner appearance
- Simplify ProxyToggle structure with nested container
2025-12-20 16:24:25 +08:00
Jason b2a9e91d70 feat(providers): add DMXAPI as official partner
Mark DMXAPI as partner in both Claude and Codex presets with promotion
message for their Claude Code exclusive model 66% OFF offer.
2025-12-20 13:23:15 +08:00
Jason 4a1a997935 feat(icons): add provider icons for OpenRouter, LongCat, ModelScope, AiHubMix
- Add SVG icons for OpenRouter, LongCat, ModelScope, and AiHubMix
- Register icons in index.ts and metadata.ts with search keywords
- Link icons to corresponding provider presets in claudeProviderPresets.ts
2025-12-20 12:43:59 +08:00
Jason c4535c894a refactor(proxy): switch OpenRouter to passthrough mode for native Claude API
OpenRouter now supports Claude Code compatible endpoint (/v1/messages),
eliminating the need for Anthropic ↔ OpenAI format conversion.

- Disable format transformation for OpenRouter (keep old logic as fallback)
- Pass through original endpoint instead of redirecting to /v1/chat/completions
- Add anthropic-version header for ClaudeAuth and Bearer strategies
- Update tests to reflect new passthrough behavior
2025-12-20 12:13:39 +08:00
Jason 64e0cabaa7 fix(window): add minWidth/minHeight to Windows platform config
Tauri 2.0 platform config merging is shallow, not deep. The Windows
config only specified titleBarStyle, causing minWidth/minHeight to
be missing on Windows. This allowed users to resize the window below
900px, causing header elements to misalign.
2025-12-20 11:19:26 +08:00
Jason 8ecb41d25e fix(proxy): respect existing token field when syncing Claude config
- Add support for ANTHROPIC_API_KEY in Claude auth extraction
- Only update existing token fields during sync, avoid adding fields
  that weren't originally configured by the user
- Add tests for both scenarios
2025-12-20 11:04:07 +08:00
Jason 3e8f84481d fix(proxy): add fallback recovery for orphaned takeover state
- Detect takeover residue in Live configs even when proxy is not running
- Implement 3-tier fallback: backup → SSOT → cleanup placeholders
- Only delete backup after successful restore to prevent data loss
- Fix EditProviderDialog to check current app's takeover status only
2025-12-20 10:07:04 +08:00
Jason ba59483b33 refactor(proxy): remove global auto-start flag
- Remove global proxy auto-start flag from config and UI.
- Simplify per-app takeover start/stop and stop server when the last takeover is disabled.
- Restore live takeover detection used for crash recovery.
- Keep proxy_config.enabled column but always write 0 for compatibility.
- Tests: not run (not requested).
2025-12-20 08:48:59 +08:00
Jason b6ff721d67 fix(import): refresh all providers immediately after SQL import
- Remove setTimeout delay that could be cancelled on component unmount
- Invalidate all providers cache (not just current app) since import affects all apps
- Call onImportSuccess before sync to ensure UI refresh even if sync fails
- Update i18n: "Data refreshed" (past tense, reflecting immediate action)
2025-12-19 20:48:15 +08:00
Jason 1706c9a26f fix(backup): restrict SQL import to CC Switch exported backups only
- Add validation to reject SQL files without CC Switch export header
- Remove redundant sanitize_import_sql (sqlite_* objects already excluded at export time)
- Fix backup filename collision by appending counter suffix
- Update i18n hints to clarify import restriction
2025-12-19 20:48:15 +08:00
YoVinchen 5bce6d6020 Fix/about section UI (#419)
* fix(ui): improve AboutSection styling and version detection

- Add framer-motion animations for smooth page transitions
- Unify button sizes and add icons for consistency
- Add gradient backgrounds and hover effects to cards
- Add notInstalled i18n translations (zh/en/ja)
- Fix version detection when stdout/stderr is empty

* fix(proxy): persist per-app takeover state across app restarts

- Fix proxy toggle color to reflect current app's takeover state only
- Restore proxy service on startup if Live config is still in takeover state
- Preserve per-app backup records instead of clearing all on restart
- Only recover Live config when proxy service fails to start
2025-12-19 20:40:11 +08:00
Jason 6bdbb4df23 chore: update Cargo.lock for version 3.9.0-1 2025-12-18 23:41:45 +08:00
Jason 256903ee70 chore: rename version to 3.9.0-1 for MSI compatibility
MSI installer requires numeric-only pre-release identifiers.
Changed from 3.9.0-beta.1 to 3.9.0-1.
2025-12-18 22:02:41 +08:00
Jason f42f73ebb0 fix: import RunEvent for all platforms
The #[cfg(target_os = "macos")] restriction was a historical artifact
from when RunEvent was only used for macOS-specific events (Reopen, Opened).
After c9ea13a added ExitRequested handling for all platforms, the import
should have been updated but was overlooked.
2025-12-18 21:32:17 +08:00
Jason ec6e113cf2 chore: bump version to 3.9.0-beta.1
- Update version in package.json, Cargo.toml, tauri.conf.json
- Add CHANGELOG entry for v3.9.0-beta.1 with:
  - Local Proxy Server feature
  - Auto Failover with circuit breaker
  - Skills multi-app support
  - Provider icon colors
  - 25+ bug fixes
- Add proxy feature guide documentation (Chinese)
2025-12-18 20:53:02 +08:00
Jason ae837ade02 fix(ui): restore fade transition for Skills button
The Skills button transition was accidentally removed in commit 1fb2d5e
when adding multi-app support. This restores the smooth fade-in/out
animation when switching between apps that support Skills (Claude/Codex)
and those that don't (Gemini).
2025-12-18 17:34:16 +08:00
Jason a8fd1f0dd2 fix(mcp): skip sync when target CLI app is not installed
Add guard functions to check if Claude/Codex/Gemini CLI has been
initialized before attempting to sync MCP configurations. This prevents
creating unwanted config files in directories that don't exist.

- Claude: check ~/.claude dir OR ~/.claude.json file exists
- Codex: check ~/.codex dir exists
- Gemini: check ~/.gemini dir exists

When the target app is not installed, sync operations now silently
succeed without writing any files, allowing users to manage MCP servers
for apps they actually use without side effects on others.
2025-12-18 16:08:10 +08:00
Jason fa33330b3b fix(mcp): improve upsert and import robustness
- Remove server from live config when app is disabled during upsert
- Merge enabled flags instead of overwriting when importing from multiple apps
- Normalize Gemini MCP type field (url-only → sse, command → stdio)
- Use atomic write for Codex config updates
- Add tests for disable-removal, multi-app merge, and Gemini SSE import
2025-12-18 15:14:37 +08:00
Jason 18207771ad feat(proxy): implement per-app takeover mode
Replace global live takeover with granular per-app control:
- Add start_proxy_server command (start without takeover)
- Add get_proxy_takeover_status to query each app's state
- Add set_proxy_takeover_for_app for individual app control
- Use live backup existence as SSOT for takeover state
- Refactor sync_live_to_provider to eliminate code duplication
- Update ProxyToggle to show status per active app
2025-12-18 11:28:10 +08:00
Jason 0cd7d0756c fix(proxy): takeover Codex base_url via model_provider
- Update Codex `model_providers.<model_provider>.base_url` to the proxy origin with `/v1`
- Add route fallbacks for `/responses` and `/chat/completions` (plus double-`/v1` safeguard)
- Add unit tests for the TOML base_url takeover logic
2025-12-17 22:53:32 +08:00
Jason bca0997afa fix(proxy): harden crash recovery with fallback detection
- Set takeover flag before writing proxy config to fix race condition
  where crash during takeover left Live configs corrupted but flag unset
- Add fallback detection by checking for placeholder tokens in Live
  configs when backups exist but flag is false (handles legacy/edge cases)
- Improve error handling with proper rollback at each stage of startup
- Clean up stale backups when Live configs are not in takeover state
  to avoid long-term storage of sensitive tokens
2025-12-17 11:03:49 +08:00
Jason 0ef8a4153f fix(proxy): sync UI when active provider differs from current setting
Previously, UI sync was triggered only when failover happened (retry count > 1).
This missed cases where the first provider in the failover queue succeeded but
was different from the user's selected provider in settings.

Now we capture the current provider ID at request start and compare it with
the actually used provider. This ensures UI/tray always reflects the real
provider handling requests.
2025-12-17 10:22:02 +08:00
Jason 1b73b26c0e fix(proxy): resolve circuit breaker race condition and error classification
This commit addresses two critical issues in the proxy failover logic:

1. Circuit Breaker HalfOpen Concurrency Bug:
   - Introduced `AllowResult` struct to track half-open permit usage
   - Added state guard in `transition_to_half_open()` to prevent duplicate resets
   - Replaced `fetch_sub` with CAS loop in `release_half_open_permit()` to prevent underflow
   - Separated `is_available()` (routing) from `allow_request()` (permit acquisition)

2. Error Classification Conflation:
   - Split retry logic into `should_retry_same_provider()` and `categorize_proxy_error()`
   - Same-provider retry: only for transient errors (timeout, 429, 5xx)
   - Cross-provider failover: now includes ConfigError, TransformError, AuthError
   - 4xx errors (401/403) no longer waste retries on the same provider
2025-12-17 09:36:17 +08:00
Jason 3d514c8250 fix(proxy): stabilize live takeover and provider editing
- Skip live writes when takeover is active and proxy is running
- Refresh live backups from provider edits during takeover
- Sync live tokens to DB without clobbering real keys with placeholders
- Avoid injecting extra placeholder keys into Claude live env
- Reapply takeover after proxy listen address/port changes
- In takeover mode, edit dialog uses DB config and keeps API key state in sync
2025-12-17 09:36:17 +08:00
TinsFox 18e973b920 fix: azure website link (#407) 2025-12-17 08:43:55 +08:00
YoVinchen ec20ff4d8c Feature/error request logging (#401)
* feat(proxy): add error mapper for HTTP status code mapping

- Add error_mapper.rs module to map ProxyError to HTTP status codes
- Implement map_proxy_error_to_status() for error classification
- Implement get_error_message() for user-friendly error messages
- Support all error types: upstream, timeout, connection, provider failures
- Include comprehensive unit tests for all mappings

* feat(proxy): enhance error logging with context support

- Add log_error_with_context() method for detailed error recording
- Support streaming flag, session_id, and provider_type fields
- Remove dead_code warning from log_error() method
- Enable comprehensive error request tracking in database

* feat(proxy): implement error capture and logging in all handlers

- Capture and log all failed requests in handle_messages (Claude)
- Capture and log all failed requests in handle_gemini (Gemini)
- Capture and log all failed requests in handle_responses (Codex)
- Capture and log all failed requests in handle_chat_completions (Codex)
- Record error status codes, messages, and latency for all failures
- Generate unique session_id for each request
- Support both streaming and non-streaming error scenarios

* style: fix clippy warnings and typescript errors

- Add allow(dead_code) for CircuitBreaker::get_state (reserved for future)
- Fix all uninlined format string warnings (27 instances)
- Use inline format syntax for better readability
- Fix unused import and parameter warnings in ProviderActions.tsx
- Achieve zero warnings in both Rust and TypeScript

* style: apply code formatting

- Remove trailing whitespace in misc.rs
- Add trailing comma in App.tsx
- Format multi-line className in ProviderCard.tsx

* feat(proxy): add settings button to proxy panel

Add configuration buttons in both running and stopped states to
provide easy access to proxy settings dialog.

* fix(speedtest): skip client build for invalid inputs

* chore(clippy): fix uninlined format args

* Merge branch 'main' into feature/error-request-logging
2025-12-16 21:02:08 +08:00
Jason e6654bd7f9 refactor(proxy): remove is_proxy_target in favor of failover_queue
- Remove `is_proxy_target` field from Provider struct (Rust & TypeScript)
- Remove related DAO methods: get_proxy_target_provider, set_proxy_target
- Remove deprecated Tauri commands: get_proxy_targets, set_proxy_target
- Add `is_available()` method to CircuitBreaker for availability checks
  without consuming HalfOpen probe permits (used in select_providers)
- Keep `allow_request()` for actual request gating with permit tracking
- Update stream_check to use failover_queue instead of is_proxy_target
- Clean up commented-out reset circuit breaker button in ProviderActions
- Remove unused useProxyTargets and useSetProxyTarget hooks
2025-12-16 15:45:15 +08:00
Jason d4f33224c6 fix(ui): add close button to all success toasts 2025-12-16 10:56:39 +08:00
Jason 510a013449 chore(i18n): remove restart prompt from provider switch notification
Claude Code now supports hot reload, so users no longer need to restart
the terminal after switching providers. Also removes unused `restartClaude`
i18n string.
2025-12-16 10:11:29 +08:00
Jason 1e5bab1cb6 fix(proxy): invalidate health cache when proxy stops
The previous fix (e081c75) only cleared the database records but
didn't invalidate the React Query cache. This caused stale health
badges to appear when restarting the proxy.

Now invalidates all providerHealth queries on stop, ensuring the
frontend fetches fresh data from the database.
2025-12-15 23:12:26 +08:00
Jason 6dcf268317 chore: update aigocode partner logo 2025-12-15 23:12:16 +08:00
Jason 5efc0cdd5e fix(ui): prevent card jitter when health badge appears
Increase min-height of the name row from 20px to 28px (min-h-7)
to accommodate the health badge height, preventing layout shift
when the badge dynamically appears.
2025-12-15 22:57:41 +08:00
Jason e081c7560c fix(proxy): reset health badges when proxy stops
Clear all provider_health records when stopping the proxy server,
ensuring health badges reset to "healthy" state. This fixes the
inconsistency where circuit breakers (in memory) would reset on
stop but health badges (in database) would retain stale state.
2025-12-15 22:52:58 +08:00
Jason 007813e09e fix(proxy): retry failover for all HTTP errors including 4xx
Previously, only 429, 408, and 5xx errors triggered failover to the next
provider. Other 4xx errors (like 400) were considered non-retryable and
caused immediate disconnection.

This was problematic because different providers have different restrictions
(e.g., "Do not use this API outside Claude Code CLI"), and a 400 error from
one provider doesn't mean other providers will fail.

Now all upstream HTTP errors trigger failover, allowing the system to try
all configured providers before giving up.
2025-12-15 17:12:36 +08:00
Jason 9196d07925 feat(proxy): sync UI when failover succeeds
Add FailoverSwitchManager to handle provider switching after successful
failover. This ensures the UI reflects the actual provider in use:

- Create failover_switch.rs with deduplication and async switching logic
- Pass AppHandle through ProxyService -> ProxyServer -> RequestForwarder
- Update is_current in database when failover succeeds
- Emit provider-switched event for frontend refresh
- Update tray menu and live backup synchronously

The switching runs asynchronously via tokio::spawn to avoid blocking
API responses while still providing immediate UI feedback.
2025-12-15 17:12:36 +08:00
Sirhexs 1172209f49 fix(usage): add fallback to provider config for usage credentials (#360)
- Make usage script credential fields optional with provider config fallback
- Optimize multi-plan card display: show plan count by default, expandable for details
- Add hint text to explain credential fallback mechanism
2025-12-15 17:09:46 +08:00
千羽 c49cfa5ac5 feat(deeplink): 深链支持用量查询配置 (#400)
## 新增功能
- 深链导入支持用量查询配置参数:
  - `usageEnabled`: 是否启用用量查询
  - `usageScript`: Base64 编码的用量查询脚本
  - `usageApiKey`: 用量查询专用 API Key
  - `usageBaseUrl`: 用量查询专用 Base URL
  - `usageAccessToken`: 访问令牌(NewAPI 模板)
  - `usageUserId`: 用户 ID(NewAPI 模板)
  - `usageAutoInterval`: 自动查询间隔(分钟)

## 修改文件
- **mod.rs**: DeepLinkImportRequest 结构体添加用量查询字段
- **parser.rs**: 解析 URL 中的用量查询参数
- **provider.rs**: 构建 ProviderMeta 包含 UsageScript 配置
- **deeplink.ts**: 添加 TypeScript 类型定义
- **DeepLinkImportDialog.tsx**: 确认对话框显示用量查询配置

## Bug 修复
- **formatters.ts**: 修复 formatJSON() 格式化时删除 "env" 键的问题

## 深链格式示例
```
ccswitch://v1/import?resource=provider&app=claude&name=xxx&usageEnabled=true&usageScript={base64}&usageAutoInterval=30
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-14 21:52:13 +08:00
Jason bfe9bb6a0c fix(proxy): resolve HalfOpen counter underflow and config field inconsistencies
- Fix HalfOpen counter underflow: increment half_open_requests when
  transitioning from Open to HalfOpen to prevent underflow in
  record_success/record_failure

- Fix Gemini config field names: unify to GEMINI_API_KEY and
  GOOGLE_GEMINI_BASE_URL (removed GOOGLE_API_KEY and GEMINI_API_BASE)

- Fix Codex proxy takeover: write base_url to config.toml instead of
  OPENAI_BASE_URL in auth.json (Codex CLI reads from config.toml)
2025-12-14 20:38:04 +08:00
Jason 5a5ca2a989 fix(proxy): resolve circuit breaker state persistence and HalfOpen deadlock
This commit addresses several critical issues in the failover system:

**Circuit breaker state persistence (previous fix)**
- Promote ProviderRouter to ProxyState for cross-request state sharing
- Remove redundant router.rs module
- Fix 429 errors to be retryable (rate limiting should try other providers)

**Hot-update circuit breaker config**
- Add update_circuit_breaker_configs() to ProxyServer and ProxyService
- Connect update_circuit_breaker_config command to running circuit breakers
- Add reset_provider_circuit_breaker() for manual breaker reset

**Fix HalfOpen deadlock bug**
- Change half_open_requests from cumulative count to in-flight count
- Release quota in record_success()/record_failure() when in HalfOpen state
- Prevents permanent deadlock when success_threshold > 1

**Fix duplicate select_providers() call**
- Store providers list in RequestContext, pass to forward_with_retry()
- Avoid consuming HalfOpen quota twice per request
- Single call to select_providers() per request lifecycle

**Add per-provider retry with exponential backoff**
- Implement forward_with_provider_retry() with configurable max_retries
- Backoff delays: 100ms, 200ms, 400ms, etc.
2025-12-13 22:47:49 +08:00
Jason 5d424b1383 feat(proxy): implement independent failover queue management
Add a new failover queue system that operates independently from provider
sortIndex, allowing users to configure failover order per app type.

Backend changes:
- Add failover_queue table to schema.rs for persistent storage
- Create dao/failover.rs with CRUD operations for queue management
- Add Tauri commands for queue operations (get, add, remove, reorder, toggle)
- Refactor provider_router.rs select_providers() to use failover queue:
  - Current provider always takes first priority
  - Queue providers ordered by queue_order as fallback
  - Only providers with open circuit breakers are included

Frontend changes:
- Add FailoverQueueItem type to proxy.ts
- Extend failover.ts API with queue management methods
- Add React Query hooks for queue data fetching and mutations
- Create FailoverQueueManager component with drag-and-drop reordering
- Integrate queue management into SettingsPage under "Auto Failover"
- Add i18n translations for zh and en locales
2025-12-12 16:13:07 +08:00
Jason c42a0dccaf fix(proxy): auto-recover live config after abnormal exit
When the app crashes or is force-killed while proxy mode is active,
the live config files remain pointing to the dead proxy server with
placeholder tokens, causing CLI tools to fail.

This change adds startup detection:
- Check `live_takeover_active` flag on app launch
- If flag is true but proxy is not running → abnormal exit detected
- Automatically restore live configs from database backup
- Clear takeover flag and delete backups

The recovery runs before auto-start, ensuring correct sequence even
when proxy auto-start is enabled.
2025-12-12 10:43:01 +08:00
Jason ebe2a665ae refactor(proxy): modularize handlers.rs to reduce code duplication
Extract common request handling logic into dedicated modules:
- handler_config.rs: Usage parser configurations for each API type
- handler_context.rs: Request lifecycle context management
- response_processor.rs: Unified streaming/non-streaming response handling

Reduces handlers.rs from ~1130 lines to ~418 lines (-63%), eliminating
repeated initialization and response processing patterns across the
four API handlers (Claude, Codex Chat, Codex Responses, Gemini).
2025-12-11 23:22:05 +08:00
Jason 1926af4988 fix(proxy): update live backup when hot-switching provider in proxy mode
When proxy is active, switching providers only updated the database flags
but not the live backup. This caused the wrong provider config to be
restored when stopping the proxy.

Added `update_live_backup_from_provider()` method to ProxyService that
generates backup from provider's settings_config instead of reading from
live files (which are already taken over by proxy).
2025-12-11 21:14:22 +08:00
Jason 1e3a978ecb fix(proxy): wait for server shutdown before exiting app
The previous cleanup logic only sent a shutdown signal but didn't wait
for the proxy server to actually stop. This caused a race condition
where the app would exit before cleanup completed, leaving Live configs
in an inconsistent state.

Changes:
- Add `server_handle` field to ProxyServer to track the spawned task
- Modify `stop()` to wait for server task completion (5s timeout)
- Add 100ms delay before process exit to ensure I/O flush
- Export ProxyService and fix test files that were missing proxy_service field
2025-12-11 20:10:21 +08:00
YoVinchen 395783e22a Feat/provider icon color (#385)
* feat(ui): add color prop support to ProviderIcon component

* feat(health): add stream check core functionality

Add new stream-based health check module to replace model_test:
- Add stream_check command layer with single and batch provider checks
- Add stream_check DAO layer for config and log persistence
- Add stream_check service layer with retry mechanism and health status evaluation
- Add frontend HealthStatusIndicator component
- Add frontend useStreamCheck hook

This provides more comprehensive health checking capabilities.

* refactor(health): replace model_test with stream_check

Replace model_test module with stream_check across the codebase:
- Remove model_test command and service modules
- Update command registry in lib.rs to use stream_check commands
- Update module exports in commands/mod.rs and services/mod.rs
- Remove frontend useModelTest hook
- Update stream_check command implementation

This refactoring provides clearer naming and better separation of concerns.

* refactor(db): clean up unused database tables and optimize schema

Remove deprecated and unused database tables:
- Remove proxy_usage table (replaced by proxy_request_logs)
- Remove usage_daily_stats table (aggregation done on-the-fly)
- Rename model_test_logs to stream_check_logs with updated schema
- Remove related DAO methods for proxy_usage
- Update usage_stats service to use proxy_request_logs only
- Refactor usage_script to work with new schema

This simplifies the database schema and removes redundant data storage.

* refactor(ui): update frontend components for stream check

Update frontend components to use stream check API:
- Refactor ModelTestConfigPanel to use stream check config
- Update API layer to use stream_check commands
- Add HealthStatus type and StreamCheckResult interface
- Update ProviderList to use new health check integration
- Update AutoFailoverConfigPanel with stream check references
- Improve UI layout and configuration options

This completes the frontend migration from model_test to stream_check.

* feat(health): add configurable test models and reasoning effort support

Enhance stream check service with configurable test models:
- Add claude_model, codex_model, gemini_model to StreamCheckConfig
- Support reasoning effort syntax (model@level or model#level)
- Parse and apply reasoning_effort for OpenAI-compatible models
- Remove hardcoded model names from check functions
- Add unit tests for model parsing logic
- Remove obsolete model_test source files

This allows users to customize which models are used for health checks.
2025-12-11 17:20:44 +08:00
YoVinchen 038b74b844 Fix/misc updates (#387)
* fix(misc): improve CLI version detection with path scanning

- Extract version helper to parse semver from raw output
- Add fallback path scanning when direct execution fails
- Scan common npm global paths: .npm-global, .local/bin, homebrew
- Support nvm by scanning all node versions under ~/.nvm/versions/node
- Add platform-specific paths for macOS, Linux, and Windows
- Ensure node is in PATH when executing CLI tools from scanned paths

* fix(ui): use semantic color tokens for text foreground

- Replace hardcoded gray-900/gray-100 with text-foreground in EndpointSpeedTest
- Add text-foreground class to Input component for consistent theming
- Ensures proper text color in both light and dark modes
2025-12-11 17:02:04 +08:00
Jason f1e5afdae2 update readme 2025-12-11 16:51:20 +08:00
Jason c9ea13a7ce feat(proxy): cleanup proxy server on app exit and remove unused non-takeover mode
- Add cleanup_before_exit() to gracefully stop proxy and restore live configs
- Handle ExitRequested event to catch Cmd+Q, Alt+F4, and tray quit
- Use std::process::exit(0) after cleanup to avoid infinite loop
- Remove unused start_proxy_server and stop_proxy_server commands
- Remove unused startMutation and stopMutation from useProxyStatus hook
- Simplify API to only expose takeover mode (start_proxy_with_takeover/stop_proxy_with_restore)
2025-12-11 16:21:14 +08:00
Jason 404ab5a1ae fix(proxy): disable auto-start on app launch by resetting enabled flag on stop
Previously, when proxy was started, the enabled flag was set to true and
persisted to database. However, stopping the proxy didn't reset this flag,
causing the proxy to auto-start on every subsequent app launch.

Now the enabled flag is set to false when proxy stops, ensuring the proxy
remains off after restart unless explicitly started by the user.
2025-12-11 12:32:02 +08:00
Jason 9a8f12a490 style(rust): apply cargo fmt formatting 2025-12-11 12:13:27 +08:00
Jason 6a7c2df2d2 fix(proxy): sync live config tokens to database before takeover
When proxy takeover is activated, tokens are replaced with placeholders
in live config files. However, the proxy reads tokens from the database,
not from live files. If the user's token only exists in the live config
(e.g., manually added), the database won't have it, causing auth failures.

Changes:
- Add sync_live_to_providers() to sync tokens from live configs to DB
- Add update_provider_settings_config() DAO method for partial updates
- Use "PROXY_MANAGED" placeholder instead of empty string to avoid
  "missing API key" warnings in Claude Code status bar
- Integrate sync step into start_with_takeover() flow before clearing tokens

The new takeover flow:
1. setup_proxy_targets()
2. backup_live_configs()
3. sync_live_to_providers() <- NEW
4. takeover_live_configs()
5. Start proxy server
2025-12-11 11:57:53 +08:00
Jason 735b3b7d39 style(ui): improve provider card hover animation and layout
- Increase translate offset for usage footer to prevent overlap with action buttons
- Add ease-out timing function and extend duration to 300ms for smoother animation
- Temporarily disable circuit breaker reset button to reduce button clutter
2025-12-11 10:51:25 +08:00
Jason cbc23764c0 style(ui): apply emerald theme when proxy takeover is active
- Change provider card gradient background from hover to selected state
- Use emerald color for card hover border, selected border, and gradient
  when proxy takeover mode is active
- Update "CC Switch" title to emerald when proxy is running
- Update "Enable" button to emerald in proxy takeover mode
2025-12-11 10:21:33 +08:00
Jason 2a541cfda4 refactor(proxy): simplify provider selection to use is_current directly
Changes:
- Modify provider_router to select provider based on is_current flag
  instead of is_proxy_target queue
- Remove proxy target toggle UI from ProviderCard
- Remove proxyPriority and allProviders props from ProviderList
- Remove isProxyTarget prop from ProviderHealthBadge
- Use start_with_takeover() for auto-start to ensure proper setup

This simplifies the proxy architecture by directly using the current
provider for proxying, eliminating the need for separate proxy target
management. Switching providers now immediately takes effect in proxy
mode.
2025-12-10 21:08:41 +08:00
Jason 5cc864c6aa fix(proxy): resolve 404 error and auto-setup proxy targets
Issues fixed:
1. Route prefix mismatch - Live config was set to use /claude, /codex,
   /gemini prefixes but server only had routes without prefixes
2. Proxy targets not auto-configured - start_with_takeover only modified
   Live config but didn't set is_proxy_target=true for current providers

Changes:
- Add prefixed routes (/claude/v1/messages, /codex/v1/*, /gemini/v1beta/*)
  to server.rs for backward compatibility
- Remove URL prefixes from takeover_live_configs() - server can route
  by API endpoint path alone (/v1/messages=Claude, /v1/chat/completions=Codex)
- Add setup_proxy_targets() method that automatically sets current providers
  as proxy targets when starting proxy with takeover
- Unify proxy toggle in SettingsPage to use takeover mode (same as main UI)
- Fix error message extraction in useProxyStatus hooks
- Fix provider switch logic to check both takeover flag AND proxy running state
2025-12-10 19:58:43 +08:00
YoVinchen 3cdce2eced feat(ui): add color prop support to ProviderIcon component (#384) 2025-12-10 15:20:10 +08:00
luo jiyin 8876d67807 Security fixes javascript executor and usage script (#151)
* dependencies: url

* fix: comprehensive security improvements for usage script execution

🛡️ Security Fixes:
- Implement robust SSRF protection with same-origin URL validation
- Add precise IP address validation for IPv4/IPv6 private networks
- Fix port comparison to handle default ports correctly (443/80)
- Remove hardcoded domain whitelist, support custom domains flexibly
- Add comprehensive input validation and hostname security checks

🔧 Technical Improvements:
- Replace string-based IP checks with proper IpAddr parsing
- Use port_or_known_default() for accurate port validation
- Add comprehensive unit tests covering edge cases
- Implement CIDR-compliant private IP detection (RFC1918)
- Fix IPv6 address validation to prevent false positives

📊 Fixed Issues:
- Prevent access to private IP addresses while allowing public services
- Support Cloudflare (172.67.x.x) and other public 172.x.x.x ranges
- Fix port matching between explicit (e.g., :443) and implicit (default) ports
- Resolve IPv6 false positives for addresses containing ::1 substrings
- Maintain backward compatibility with existing script usage patterns

 Testing:
- Add comprehensive test suite for IP validation (IPv4/IPv6)
- Add port comparison tests for various scenarios
- Add edge case tests for CIDR boundaries
- All tests passing, ensuring no regressions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* fix: add is_loopback_host for proper localhost validation

* fix: use Database::memory() in tests

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-09 19:57:02 +08:00
YoVinchen 493b154a9d Feat/skill multi app migration (#378)
* feat(skill): add database migration and Gemini support for multi-app skills

- Refactor skills table from single key to (directory, app_type) composite primary key
- Add migration logic to convert existing skill records
- Support skill installation/uninstallation for Claude/Codex/Gemini independently
- Add new Tauri commands: get_skills_for_app, install_skill_for_app, uninstall_skill_for_app
- Update frontend API and components to support app-specific skill operations

* fix(usage): correct cache token column order in request log table

- Swap cache read and cache creation columns to match data binding
- Add whitespace-nowrap to all table headers for better display
2025-12-09 19:39:31 +08:00
Jason 56b40bdad2 fix(misc): use correct npm package for Codex CLI version check
- Change Codex version source from GitHub `openai/openai-python` to npm `@openai/codex`
- Remove unused `fetch_github_latest_release` helper function
- All three tools (Claude, Codex, Gemini) now consistently use npm registry
2025-12-09 10:14:46 +08:00
YoVinchen 41267135f5 Feat/auto failover (#367)
* feat(db): add circuit breaker config table and provider proxy target APIs

Add database support for auto-failover feature:

- Add circuit_breaker_config table for storing failover thresholds
- Add get/update_circuit_breaker_config methods in proxy DAO
- Add reset_provider_health method for manual recovery
- Add set_proxy_target and get_proxy_targets methods in providers DAO
  for managing multi-provider failover configuration

* feat(proxy): implement circuit breaker and provider router for auto-failover

Add core failover logic:

- CircuitBreaker: Tracks provider health with three states:
  - Closed: Normal operation, requests pass through
  - Open: Circuit broken after consecutive failures, skip provider
  - HalfOpen: Testing recovery with limited requests
- ProviderRouter: Routes requests across multiple providers with:
  - Health tracking and automatic failover
  - Configurable failure/success thresholds
  - Auto-disable proxy target after reaching failure threshold
  - Support for manual circuit breaker reset
- Export new types in proxy module

* feat(proxy): add failover Tauri commands and integrate with forwarder

Expose failover functionality to frontend:

- Add Tauri commands: get_proxy_targets, set_proxy_target,
  get_provider_health, reset_circuit_breaker,
  get/update_circuit_breaker_config, get_circuit_breaker_stats
- Register all new commands in lib.rs invoke handler
- Update forwarder with improved error handling and logging
- Integrate ProviderRouter with proxy server startup
- Add provider health tracking in request handlers

* feat(frontend): add failover API layer and TanStack Query hooks

Add frontend data layer for failover management:

- Add failover.ts API: Tauri invoke wrappers for all failover commands
- Add failover.ts query hooks: TanStack Query mutations and queries
  - useProxyTargets, useProviderHealth queries
  - useSetProxyTarget, useResetCircuitBreaker mutations
  - useCircuitBreakerConfig query and mutation
- Update queries.ts with provider health query key
- Update mutations.ts to invalidate health on provider changes
- Add CircuitBreakerConfig and ProviderHealth types

* feat(ui): add auto-failover configuration UI and provider health display

Add comprehensive UI for failover management:

Components:
- ProviderHealthBadge: Display provider health status with color coding
- CircuitBreakerConfigPanel: Configure failure/success thresholds,
  timeout duration, and error rate limits
- AutoFailoverConfigPanel: Manage proxy targets with drag-and-drop
  priority ordering and individual enable/disable controls
- ProxyPanel: Integrate failover tabs for unified proxy management

Provider enhancements:
- ProviderCard: Show health badge and proxy target indicator
- ProviderActions: Add "Set as Proxy Target" action
- EditProviderDialog: Add is_proxy_target toggle
- ProviderList: Support proxy target filtering mode

Other:
- Update App.tsx routing for settings integration
- Update useProviderActions hook with proxy target mutation
- Fix ProviderList tests for updated component API

* fix(usage): stabilize date range to prevent infinite re-renders

* feat(backend): add tool version check command

Add get_tool_versions command to check local and latest versions of
Claude, Codex, and Gemini CLI tools:

- Detect local installed versions via command line execution
- Fetch latest versions from npm registry (Claude, Gemini)
  and GitHub releases API (Codex)
- Return comprehensive version info including error details
  for uninstalled tools
- Register command in Tauri invoke handler

* style(ui): format accordion component code style

Apply consistent code formatting to accordion component:
- Convert double quotes to semicolons at line endings
- Adjust indentation to 2-space standard
- Align with project code style conventions

* refactor(providers): update provider card styling to use theme tokens

Replace hardcoded color classes with semantic design tokens:
- Use bg-card, border-border, text-card-foreground instead of glass-card
- Replace gray/white color literals with muted/foreground tokens
- Change proxy target indicator color from purple to green
- Improve hover states with border-border-active
- Ensure consistent dark mode support via CSS variables

* refactor(proxy): simplify auto-failover config panel structure

Restructure AutoFailoverConfigPanel for better integration:
- Remove internal Card wrapper and expansion toggle (now handled by parent)
- Extract enabled state to props for external control
- Simplify loading state display
- Clean up redundant CardHeader/CardContent wrappers
- ProxyPanel: reduce complexity by delegating to parent components

* feat(settings): enhance settings page with accordion layout and tool versions

Major settings page improvements:

AboutSection:
- Add local tool version detection (Claude, Codex, Gemini)
- Display installed vs latest version comparison with visual indicators
- Show update availability badges and environment check cards

SettingsPage:
- Reorganize advanced settings into collapsible accordion sections
- Add proxy control panel with inline status toggle
- Integrate auto-failover configuration with accordion UI
- Add database and cost calculation config sections

DirectorySettings & WindowSettings:
- Minor styling adjustments for consistency

settings.ts API:
- Add getToolVersions() wrapper for new backend command

* refactor(usage): restructure usage dashboard components

Comprehensive usage statistics panel refactoring:

UsageDashboard:
- Reorganize layout with improved section headers
- Add better loading states and empty state handling

ModelStatsTable & ProviderStatsTable:
- Minor styling updates for consistency

ModelTestConfigPanel & PricingConfigPanel:
- Simplify component structure
- Remove redundant Card wrappers
- Improve form field organization

RequestLogTable:
- Enhance table layout with better column sizing
- Improve pagination controls

UsageSummaryCards:
- Update card styling with semantic tokens
- Better responsive grid layout

UsageTrendChart:
- Refine chart container styling
- Improve legend and tooltip display

* chore(deps): add accordion and animation dependencies

Package updates:
- Add @radix-ui/react-accordion for collapsible sections
- Add cmdk for command palette support
- Add framer-motion for enhanced animations

Tailwind config:
- Add accordion-up/accordion-down animations
- Update darkMode config to support both selector and class
- Reorganize color and keyframe definitions for clarity

* style(app): update header and app switcher styling

App.tsx:
- Replace glass-header with explicit bg-background/80 backdrop-blur
- Update navigation button container to use bg-muted

AppSwitcher:
- Replace hardcoded gray colors with semantic muted/foreground tokens
- Ensure consistent dark mode support via CSS variables
- Add group class for better hover state transitions
2025-12-08 21:14:06 +08:00
YoVinchen 1fb2d5ed44 feat(skill): add multi-app skill support for Claude/Codex (#365)
* feat(skill): add multi-app skill support for Claude/Codex/Gemini

- Add app-specific skill management with AppType prefix in skill keys
- Implement per-app skill tracking in database schema
- Add get_skills_for_app command to retrieve skills by application
- Update SkillsPage to support app-specific skill loading with initialApp prop
- Parse app parameter and validate against supported app types
- Maintain backward compatibility with default claude app

* fix(usage): reorder cache columns and prevent header text wrapping

- Swap cache read and cache write columns order
- Add whitespace-nowrap to all table headers to prevent text wrapping
- Improves table readability and layout consistency
2025-12-08 20:54:17 +08:00
983 changed files with 276319 additions and 18730 deletions
+14
View File
@@ -0,0 +1,14 @@
# Code owners for cc-switch
#
# Branch protection on `main` has "Require review from Code Owners" enabled.
# With this file present, a PR cannot merge to `main` without an approval from
# the owner below. This closes the gap where two collaborators could approve
# each other's malicious PRs (a single non-owner approval is no longer enough).
# Global fallback: every PR needs owner approval before merging to main.
* @farion1231
# Most sensitive paths — CI/signing/release and the Rust backend. Listed
# explicitly so they stay locked even if the global rule above is relaxed later.
/.github/ @farion1231
/src-tauri/ @farion1231
+2
View File
@@ -0,0 +1,2 @@
custom:
- https://github.com/farion1231/cc-switch/blob/main/README_ZH.md#%E2%9D%A4%EF%B8%8F%E8%B5%9E%E5%8A%A9%E5%95%86
+97
View File
@@ -0,0 +1,97 @@
name: "🐛 Bug Report / Bug 报告"
description: |
Report errors or unexpected behavior.
报告错误或异常行为。
labels:
- bug
body:
- type: checkboxes
attributes:
label: Self Checks / 自检
options:
- label: |
I have read the [FAQ](https://github.com/farion1231/cc-switch#faq) section in README.
我已阅读 README 中的[常见问题](https://github.com/farion1231/cc-switch#常见问题)。
required: true
- label: |
I have searched for [existing issues](https://github.com/farion1231/cc-switch/issues), including closed ones.
我已搜索过[已有的 Issue](https://github.com/farion1231/cc-switch/issues),包括已关闭的。
required: true
- type: input
attributes:
label: CC Switch Version / 版本号
description: |
See the Settings page in the app.
查看应用设置页面中的版本号。
placeholder: "e.g. 3.11.1"
validations:
required: true
- type: dropdown
attributes:
label: Operating System / 操作系统
multiple: false
options:
- Windows
- macOS
- Linux
validations:
required: true
- type: dropdown
attributes:
label: Related App / 涉及应用
description: |
Which app is affected?
涉及哪个应用?
multiple: true
options:
- Claude Code
- Codex
- Gemini CLI
- OpenCode
- OpenClaw
- Other / 其他
validations:
required: true
- type: textarea
attributes:
label: Steps to Reproduce / 重现步骤
description: |
Please describe the steps to reproduce the bug. Screenshots and logs are helpful.
请描述重现步骤。截图和日志会很有帮助。
placeholder: |
1. Go to ...
2. Click on ...
3. See error ...
validations:
required: true
- type: textarea
attributes:
label: Expected Behavior / 期望行为
description: |
What did you expect to happen?
你期望发生什么?
validations:
required: true
- type: textarea
attributes:
label: Actual Behavior / 实际行为
description: |
What actually happened?
实际发生了什么?
validations:
required: false
- type: textarea
attributes:
label: Additional Context / 补充信息
description: |
Any other information, screenshots, or logs.
其他信息、截图或日志。
validations:
required: false
+12
View File
@@ -0,0 +1,12 @@
blank_issues_enabled: false
contact_links:
- name: "Security Vulnerabilities / 安全漏洞"
url: "https://github.com/farion1231/cc-switch/security/advisories/new"
about: |
Report security vulnerabilities through GitHub Security Advisories.
请通过 GitHub 安全公告报告安全漏洞。
- name: "Discussions / 讨论区"
url: "https://github.com/farion1231/cc-switch/discussions"
about: |
General discussions and community help.
一般讨论和社区帮助。
+60
View File
@@ -0,0 +1,60 @@
name: "📖 Documentation Issue / 文档问题"
description: |
Report documentation errors, outdated content, or missing information.
报告文档错误、过时内容或缺失信息。
labels:
- documentation
body:
- type: checkboxes
attributes:
label: Self Checks / 自检
options:
- label: |
I have searched for [existing issues](https://github.com/farion1231/cc-switch/issues), including closed ones.
我已搜索过[已有的 Issue](https://github.com/farion1231/cc-switch/issues),包括已关闭的。
required: true
- type: dropdown
attributes:
label: Language / 语言
description: |
Which language version of the docs?
涉及哪个语言版本的文档?
multiple: true
options:
- English
- 中文
- 日本語
validations:
required: true
- type: input
attributes:
label: Document Location / 文档位置
description: |
Which file or section is affected? Provide a link or file path.
涉及哪个文件或章节?请提供链接或文件路径。
placeholder: "e.g. README.md#faq or docs/user-manual/zh/..."
validations:
required: true
- type: dropdown
attributes:
label: Issue Type / 问题类型
options:
- "Typo or grammar / 拼写或语法错误"
- "Outdated content / 内容过时"
- "Missing information / 信息缺失"
- "Translation issue / 翻译问题"
- "Other / 其他"
validations:
required: true
- type: textarea
attributes:
label: Description / 描述
description: |
Describe the documentation issue.
描述文档问题。
validations:
required: true
@@ -0,0 +1,75 @@
name: "✨ Feature Request / 功能请求"
description: |
Propose a new feature or improvement.
提出新功能或改进建议。
labels:
- enhancement
body:
- type: checkboxes
attributes:
label: Self Checks / 自检
options:
- label: |
I have read the [FAQ](https://github.com/farion1231/cc-switch#faq) section in README.
我已阅读 README 中的[常见问题](https://github.com/farion1231/cc-switch#常见问题)。
required: true
- label: |
I have searched for [existing issues](https://github.com/farion1231/cc-switch/issues), including closed ones.
我已搜索过[已有的 Issue](https://github.com/farion1231/cc-switch/issues),包括已关闭的。
required: true
- type: dropdown
attributes:
label: Related App / 涉及应用
description: |
Which app is this feature for?
该功能涉及哪个应用?
multiple: true
options:
- Claude Code
- Codex
- Gemini CLI
- OpenCode
- OpenClaw
- General / 通用
validations:
required: true
- type: textarea
attributes:
label: Problem or Motivation / 问题或动机
description: |
Is this request related to a problem? Describe the scenario.
这个请求是否与某个问题相关?请描述使用场景。
placeholder: |
I was trying to ... and found that ...
我在尝试……的时候,发现……
validations:
required: true
- type: textarea
attributes:
label: Proposed Solution / 建议方案
description: |
Describe the solution you'd like.
描述你希望的解决方案。
validations:
required: false
- type: textarea
attributes:
label: Additional Context / 补充信息
description: |
Any other context, mockups, or screenshots.
其他背景信息、设计稿或截图。
validations:
required: false
- type: checkboxes
attributes:
label: Contribution / 参与贡献
options:
- label: |
I am interested in contributing to this feature.
我有兴趣参与开发此功能。
required: false
+64
View File
@@ -0,0 +1,64 @@
name: "❓ Question / 提问"
description: |
Ask a question about usage or configuration.
询问使用或配置相关问题。
labels:
- question
body:
- type: checkboxes
attributes:
label: Self Checks / 自检
options:
- label: |
I have read the [FAQ](https://github.com/farion1231/cc-switch#faq) section in README.
我已阅读 README 中的[常见问题](https://github.com/farion1231/cc-switch#常见问题)。
required: true
- label: |
I have searched for [existing issues](https://github.com/farion1231/cc-switch/issues), including closed ones.
我已搜索过[已有的 Issue](https://github.com/farion1231/cc-switch/issues),包括已关闭的。
required: true
- type: dropdown
attributes:
label: Related App / 涉及应用
description: |
Which app is your question about?
你的问题涉及哪个应用?
multiple: true
options:
- Claude Code
- Codex
- Gemini CLI
- OpenCode
- OpenClaw
- General / 通用
validations:
required: true
- type: textarea
attributes:
label: Your Question / 你的问题
description: |
Describe your question clearly.
请清晰地描述你的问题。
validations:
required: true
- type: textarea
attributes:
label: What Have You Tried / 你已经尝试过什么
description: |
Describe what you've already tried or researched.
描述你已经尝试过或查阅过的内容。
validations:
required: false
- type: textarea
attributes:
label: Environment / 环境信息
description: |
OS, CC Switch version, and any relevant details.
操作系统、CC Switch 版本及其他相关信息。
placeholder: "e.g. macOS 15.4, CC Switch 3.11.1"
validations:
required: false
+39
View File
@@ -0,0 +1,39 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
labels:
- "dependencies"
- "frontend"
commit-message:
prefix: "chore(deps)"
groups:
frontend-deps:
patterns:
- "*"
- package-ecosystem: "cargo"
directory: "/src-tauri"
schedule:
interval: "weekly"
labels:
- "dependencies"
- "backend"
commit-message:
prefix: "chore(deps)"
groups:
cargo-deps:
patterns:
- "*"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"
labels:
- "dependencies"
- "actions"
commit-message:
prefix: "chore(deps)"
+74
View File
@@ -0,0 +1,74 @@
# Configuration for actions/labeler v5
# Automatically labels PRs based on changed file paths
frontend:
- changed-files:
- any-glob-to-any-file:
- "src/**"
- "index.html"
- "vite.config.ts"
- "vitest.config.ts"
- "tailwind.config.cjs"
- "postcss.config.cjs"
- "tsconfig.json"
- "tsconfig.node.json"
- "components.json"
- "tests/**"
backend:
- changed-files:
- any-glob-to-any-file:
- "src-tauri/**"
i18n:
- changed-files:
- any-glob-to-any-file:
- "src/locales/**"
actions:
- changed-files:
- any-glob-to-any-file:
- ".github/**"
dependencies:
- changed-files:
- any-glob-to-any-file:
- "package.json"
- "pnpm-lock.yaml"
- "pnpm-workspace.yaml"
- "src-tauri/Cargo.toml"
- "src-tauri/Cargo.lock"
documentation:
- changed-files:
- any-glob-to-any-file:
- "*.md"
- "docs/**"
- "LICENSE"
mcp:
- changed-files:
- any-glob-to-any-file:
- "src/components/mcp/**"
- "src/lib/api/mcp.ts"
- "src-tauri/src/mcp/**"
- "src-tauri/src/claude_mcp.rs"
- "src-tauri/src/gemini_mcp.rs"
- "src-tauri/src/commands/mcp.rs"
skills:
- changed-files:
- any-glob-to-any-file:
- "src/components/skills/**"
- "src/lib/api/skills.ts"
- "src-tauri/src/commands/skill.rs"
- "src-tauri/src/services/skill.rs"
- "src-tauri/src/database/dao/skills.rs"
proxy:
- changed-files:
- any-glob-to-any-file:
- "src/components/proxy/**"
- "src/lib/api/proxy.ts"
- "src-tauri/src/proxy/**"
- "src-tauri/src/commands/proxy.rs"
+25
View File
@@ -0,0 +1,25 @@
## Summary / 概述
<!-- Briefly describe what this PR does and why. / 简要描述这个 PR 做了什么以及为什么。 -->
## Related Issue / 关联 Issue
<!-- Link the related issue. Use "Fixes #123" to auto-close it when merged. -->
<!-- 关联相关 Issue。使用 "Fixes #123" 可在合并时自动关闭。 -->
Fixes #
## Screenshots / 截图
<!-- If applicable, add before/after screenshots. / 如有需要,请添加修改前后的截图。 -->
| Before / 修改前 | After / 修改后 |
|-----------------|---------------|
| | |
## Checklist / 检查清单
- [ ] `pnpm typecheck` passes / 通过 TypeScript 类型检查
- [ ] `pnpm format:check` passes / 通过代码格式检查
- [ ] `cargo clippy` passes (if Rust code changed) / 通过 Clippy 检查(如修改了 Rust 代码)
- [ ] Updated i18n files if user-facing text changed / 如修改了用户可见文本,已更新国际化文件
+105
View File
@@ -0,0 +1,105 @@
name: CI
on:
pull_request:
branches: [main]
push:
branches: [main]
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
frontend:
name: Frontend Checks
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: "20"
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.12.3
run_install: false
- name: Get pnpm store directory
id: pnpm-store
shell: bash
run: echo "path=$(pnpm store path --silent)" >> $GITHUB_OUTPUT
- name: Cache pnpm store
uses: actions/cache@v5
with:
path: ${{ steps.pnpm-store.outputs.path }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: ${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: TypeScript type check
run: pnpm typecheck
- name: Check formatting
run: pnpm format:check
- name: Unit tests
run: pnpm test:unit
backend:
name: Backend Checks
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-22.04, windows-latest, macos-latest]
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Install Linux system deps
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
build-essential pkg-config libssl-dev \
libgtk-3-dev librsvg2-dev libayatana-appindicator3-dev
sudo apt-get install -y --no-install-recommends libwebkit2gtk-4.1-dev \
|| sudo apt-get install -y --no-install-recommends libwebkit2gtk-4.0-dev
sudo apt-get install -y --no-install-recommends libsoup-3.0-dev \
|| sudo apt-get install -y --no-install-recommends libsoup2.4-dev
- name: Cache Cargo registry and build
uses: actions/cache@v5
with:
path: |
~/.cargo/registry
~/.cargo/git
src-tauri/target
key: ${{ runner.os }}-cargo-${{ hashFiles('src-tauri/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-
- name: Create frontend dist placeholder
shell: bash
run: mkdir -p dist
- name: Check Rust formatting
run: cargo fmt --check --manifest-path src-tauri/Cargo.toml
- name: Clippy
run: cargo clippy --manifest-path src-tauri/Cargo.toml -- -D warnings
- name: Run tests
run: cargo test --manifest-path src-tauri/Cargo.toml
+61
View File
@@ -0,0 +1,61 @@
name: Claude
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
pull_request_review:
types: [submitted]
issues:
types: [opened, assigned]
jobs:
claude:
if: |
((github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude') &&
(github.event.comment.author_association == 'OWNER' ||
github.event.comment.author_association == 'MEMBER' ||
github.event.comment.author_association == 'COLLABORATOR'))
||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude') &&
(github.event.comment.author_association == 'OWNER' ||
github.event.comment.author_association == 'MEMBER' ||
github.event.comment.author_association == 'COLLABORATOR'))
||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude') &&
(github.event.review.author_association == 'OWNER' ||
github.event.review.author_association == 'MEMBER' ||
github.event.review.author_association == 'COLLABORATOR'))
||
(github.event_name == 'issues' &&
(contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')) &&
(github.event.issue.author_association == 'OWNER' ||
github.event.issue.author_association == 'MEMBER' ||
github.event.issue.author_association == 'COLLABORATOR')))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
issues: write
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 1
ref: ${{ github.event.pull_request.head.sha || github.sha }}
- name: Run Claude (review only)
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
claude_args: >-
--model claude-opus-4-7
--disallowedTools Edit,Write,MultiEdit,NotebookEdit
--append-system-prompt "You are reviewing PRs for cc-switch — a small open-source Tauri 2.0 + React + TypeScript desktop app maintained by a single developer who values pragmatism over perfection.
ONLY flag HIGH SIGNAL issues. An issue qualifies only if it meets at least one of: code that fails to compile/parse/run; code that will definitely produce wrong results; a security vulnerability with a concrete trigger (SSRF, injection, unsafe deserialization, credential or data leaks); database/migration correctness (schema mismatch, data loss on upgrade, broken SCHEMA_VERSION transition); cross-platform breakage (Windows/macOS/Linux specific); clear, quotable violations of CLAUDE.md.
Each finding must include a confidence score from 0 to 100. Do NOT post any finding scored below 80. Each finding must carry a severity tag — Important (bug that should be fixed before merge), Nit (minor, worth fixing but not blocking), or Pre-existing (exists already, not introduced by this PR).
DO NOT flag any of the following: pedantic nitpicks a senior engineer would not raise; anything a linter, typechecker, pnpm format, or cargo fmt would catch; missing test coverage unless CLAUDE.md explicitly mandates it; style, naming, or 'could be more idiomatic' suggestions; speculative future-proofing ('what if X is added later'); issues on lines the PR did not modify; potential bugs for which you cannot construct a concrete failure scenario; positive feedback or 'what is well done' sections.
OUTPUT RULES: Cap Nit-level findings at 5 per review. If you found more nits, append 'plus N similar nits' to the summary instead of listing them inline. If only nits were found, lead the review with 'No blocking issues.' If nothing material is wrong, say 'LGTM' explicitly and stop — approval with zero comments is a valid and expected outcome for most PRs. Do NOT post a final APPROVE or REQUEST CHANGES verdict; leave the merge decision to the maintainer.
Never modify files, push commits, or create PRs."
+17
View File
@@ -0,0 +1,17 @@
name: Label PRs
on:
pull_request_target:
types: [opened, synchronize, reopened]
permissions:
contents: read
pull-requests: write
jobs:
label:
runs-on: ubuntu-latest
steps:
- uses: actions/labeler@v5
with:
sync-labels: true
+406 -71
View File
@@ -15,25 +15,36 @@ concurrency:
jobs:
release:
runs-on: ${{ matrix.os }}
environment: release
strategy:
fail-fast: false
matrix:
include:
- os: windows-2022
- os: windows-11-arm
arch: arm64
- os: ubuntu-22.04
- os: ubuntu-22.04-arm
arch: arm64
- os: macos-14
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: '20'
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Add Windows ARM64 target
if: runner.os == 'Windows' && matrix.arch == 'arm64'
shell: pwsh
run: rustup target add aarch64-pc-windows-msvc
- name: Add macOS targets
if: runner.os == 'macOS'
run: |
@@ -53,7 +64,12 @@ jobs:
wget \
file \
patchelf \
libssl-dev
libssl-dev \
rpm \
flatpak \
flatpak-builder \
elfutils \
xdg-utils
# GTK/GLib stack for gdk-3.0, glib-2.0, gio-2.0
sudo apt-get install -y --no-install-recommends \
libgtk-3-dev \
@@ -67,22 +83,49 @@ jobs:
|| sudo apt-get install -y --no-install-recommends libsoup2.4-dev
- name: Setup pnpm
uses: pnpm/action-setup@v2
if: runner.os != 'Windows' || matrix.arch != 'arm64'
uses: pnpm/action-setup@v6
with:
version: 10.12.3
run_install: false
- name: Setup pnpm (Windows ARM64)
if: runner.os == 'Windows' && matrix.arch == 'arm64'
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
corepack enable
corepack prepare pnpm@10.12.3 --activate
node --version
pnpm --version
- name: Get pnpm store directory
if: runner.os != 'Windows' || matrix.arch != 'arm64'
id: pnpm-store
shell: bash
run: echo "path=$(pnpm store path --silent)" >> $GITHUB_OUTPUT
- name: Setup pnpm cache
uses: actions/cache@v4
if: runner.os != 'Windows' || matrix.arch != 'arm64'
uses: actions/cache@v5
with:
path: ${{ steps.pnpm-store.outputs.path }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: ${{ runner.os }}-pnpm-store-
key: ${{ runner.os }}-${{ runner.arch }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: ${{ runner.os }}-${{ runner.arch }}-pnpm-store-
- name: Setup LLVM for Windows ARM64
if: runner.os == 'Windows' && matrix.arch == 'arm64'
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$llvmRoot = 'C:\Program Files\LLVM'
if (-not (Test-Path $llvmRoot)) {
throw "LLVM not found at $llvmRoot"
}
$llvmBin = Join-Path $llvmRoot 'bin'
"LIBCLANG_PATH=$llvmBin" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
"CLANG_PATH=$(Join-Path $llvmBin 'clang.exe')" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
$llvmBin | Out-File -FilePath $env:GITHUB_PATH -Append -Encoding utf8
- name: Install frontend deps
run: pnpm install --frozen-lockfile
@@ -143,17 +186,93 @@ jobs:
fi
echo "✅ Tauri signing key prepared"
- name: Import Apple signing certificate
if: runner.os == 'macOS'
shell: bash
run: |
set -euo pipefail
# Decode .p12 certificate from base64
CERT_PATH="$RUNNER_TEMP/certificate.p12"
printf '%s' "${{ secrets.APPLE_CERTIFICATE }}" | (base64 --decode 2>/dev/null || base64 -D) > "$CERT_PATH"
# Save original default keychain for cleanup
ORIGINAL_DEFAULT_KEYCHAIN=$(security default-keychain -d user | tr -d '"' | xargs)
echo "ORIGINAL_DEFAULT_KEYCHAIN=$ORIGINAL_DEFAULT_KEYCHAIN" >> "$GITHUB_ENV"
# Create temporary keychain
KEYCHAIN_PATH="$RUNNER_TEMP/build.keychain-db"
security create-keychain -p "${{ secrets.KEYCHAIN_PASSWORD }}" "$KEYCHAIN_PATH"
security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
security default-keychain -s "$KEYCHAIN_PATH"
security unlock-keychain -p "${{ secrets.KEYCHAIN_PASSWORD }}" "$KEYCHAIN_PATH"
# Import certificate
security import "$CERT_PATH" \
-k "$KEYCHAIN_PATH" \
-P "${{ secrets.APPLE_CERTIFICATE_PASSWORD }}" \
-T /usr/bin/codesign \
-T /usr/bin/security
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${{ secrets.KEYCHAIN_PASSWORD }}" "$KEYCHAIN_PATH"
# Dynamically resolve signing identity (must be "Developer ID Application")
IDENTITY=$(security find-identity -v -p codesigning "$KEYCHAIN_PATH" \
| grep "Developer ID Application" | grep -oE '"[^"]+"' | head -1 | tr -d '"')
if [ -z "$IDENTITY" ]; then
echo "❌ No 'Developer ID Application' identity found — listing all identities:" >&2
security find-identity -v -p codesigning "$KEYCHAIN_PATH"
exit 1
fi
echo "✅ Signing identity: $IDENTITY"
echo "APPLE_SIGNING_IDENTITY=$IDENTITY" >> "$GITHUB_ENV"
# Cleanup certificate file
rm -f "$CERT_PATH"
- name: Build Tauri App (macOS)
if: runner.os == 'macOS'
run: pnpm tauri build --target universal-apple-darwin
shell: bash
timeout-minutes: 60
env:
APPLE_SIGNING_IDENTITY: ${{ env.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
set -euo pipefail
max_attempts=3
for attempt in $(seq 1 "$max_attempts"); do
echo "=== macOS build/notarization attempt ${attempt}/${max_attempts} ==="
if pnpm tauri build --target universal-apple-darwin; then
echo "✅ macOS build/notarization succeeded"
exit 0
fi
if [ "$attempt" -eq "$max_attempts" ]; then
echo "❌ macOS build/notarization failed after ${max_attempts} attempts" >&2
exit 1
fi
sleep_seconds=$((attempt * 60))
echo "⚠️ macOS build/notarization failed, retrying in ${sleep_seconds}s..."
sleep "$sleep_seconds"
done
- name: Build Tauri App (Windows)
if: runner.os == 'Windows'
run: pnpm tauri build
shell: pwsh
env:
WINDOWS_RELEASE_ARCH: ${{ matrix.arch || 'x86_64' }}
run: |
$ErrorActionPreference = 'Stop'
if ($env:WINDOWS_RELEASE_ARCH -eq 'arm64') {
pnpm tauri build --target aarch64-pc-windows-msvc --bundles msi
} else {
pnpm tauri build
}
- name: Build Tauri App (Linux)
if: runner.os == 'Linux'
run: pnpm tauri build
run: pnpm tauri build --bundles appimage,deb,rpm
- name: Prepare macOS Assets
if: runner.os == 'macOS'
@@ -162,7 +281,8 @@ jobs:
set -euxo pipefail
mkdir -p release-assets
VERSION="${GITHUB_REF_NAME}" # e.g., v3.5.0
echo "Looking for updater artifact (.tar.gz) and .app for zip..."
# Locate bundle artifacts
TAR_GZ=""; APP_PATH=""
for path in \
"src-tauri/target/universal-apple-darwin/release/bundle/macos" \
@@ -170,77 +290,224 @@ jobs:
"src-tauri/target/x86_64-apple-darwin/release/bundle/macos" \
"src-tauri/target/release/bundle/macos"; do
if [ -d "$path" ]; then
[ -z "$TAR_GZ" ] && TAR_GZ=$(find "$path" -maxdepth 1 -name "*.tar.gz" -type f | head -1 || true)
[ -z "$TAR_GZ" ] && TAR_GZ=$(find "$path" -maxdepth 1 -name "*.tar.gz" -type f | head -1 || true)
[ -z "$APP_PATH" ] && APP_PATH=$(find "$path" -maxdepth 1 -name "*.app" -type d | head -1 || true)
fi
done
if [ -z "$TAR_GZ" ]; then
echo "No macOS .tar.gz updater artifact found" >&2
echo "No macOS .tar.gz updater artifact found" >&2
exit 1
fi
# 重命名 tar.gz 为统一格式
if [ -z "$APP_PATH" ]; then
echo "❌ No .app found" >&2
exit 1
fi
# Staple notarization ticket to .app (Tauri already notarized it)
xcrun stapler staple "$APP_PATH"
echo "✅ .app stapled"
# 1) Collect .tar.gz (updater artifact)
NEW_TAR_GZ="CC-Switch-${VERSION}-macOS.tar.gz"
cp "$TAR_GZ" "release-assets/$NEW_TAR_GZ"
[ -f "$TAR_GZ.sig" ] && cp "$TAR_GZ.sig" "release-assets/$NEW_TAR_GZ.sig" || echo ".sig for macOS not found yet"
echo "macOS updater artifact copied: $NEW_TAR_GZ"
if [ -n "$APP_PATH" ]; then
APP_DIR=$(dirname "$APP_PATH"); APP_NAME=$(basename "$APP_PATH")
NEW_ZIP="CC-Switch-${VERSION}-macOS.zip"
cd "$APP_DIR"
ditto -c -k --sequesterRsrc --keepParent "$APP_NAME" "$NEW_ZIP"
mv "$NEW_ZIP" "$GITHUB_WORKSPACE/release-assets/"
echo "macOS zip ready: $NEW_ZIP"
# 2) Collect .app as zip
NEW_ZIP="CC-Switch-${VERSION}-macOS.zip"
ditto -c -k --sequesterRsrc --keepParent "$APP_PATH" "release-assets/$NEW_ZIP"
echo "macOS zip ready: $NEW_ZIP"
# 3) Create styled DMG with create-dmg (Tauri's built-in DMG styling doesn't work on CI)
if [ -z "${APPLE_SIGNING_IDENTITY:-}" ]; then
echo "❌ APPLE_SIGNING_IDENTITY is missing before DMG creation" >&2
exit 1
fi
HOMEBREW_NO_AUTO_UPDATE=1 brew install create-dmg
NEW_DMG="CC-Switch-${VERSION}-macOS.dmg"
DMG_STAGE_DIR="$RUNNER_TEMP/dmg-stage"
rm -rf "$DMG_STAGE_DIR"
mkdir -p "$DMG_STAGE_DIR"
ditto "$APP_PATH" "$DMG_STAGE_DIR/CC Switch.app"
create-dmg \
--volname "CC Switch" \
--background "src-tauri/icons/dmg-background.png" \
--window-size 660 400 \
--window-pos 200 120 \
--icon-size 80 \
--icon "CC Switch.app" 180 220 \
--hide-extension "CC Switch.app" \
--app-drop-link 480 220 \
--codesign "$APPLE_SIGNING_IDENTITY" \
--no-internet-enable \
"release-assets/$NEW_DMG" \
"$DMG_STAGE_DIR"
rm -rf "$DMG_STAGE_DIR"
echo "✅ Styled DMG created: $NEW_DMG"
- name: Notarize macOS DMG
if: runner.os == 'macOS'
shell: bash
timeout-minutes: 30
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
set -euo pipefail
DMG_PATH=$(find release-assets -maxdepth 1 -name "*.dmg" -type f | head -1 || true)
if [ -z "$DMG_PATH" ]; then
echo "❌ No .dmg found in release-assets/ to notarize" >&2
exit 1
fi
echo "=== Notarizing DMG: $DMG_PATH ==="
max_attempts=3
for attempt in $(seq 1 "$max_attempts"); do
echo "=== DMG notarization attempt ${attempt}/${max_attempts} ==="
if xcrun notarytool submit "$DMG_PATH" \
--apple-id "$APPLE_ID" \
--password "$APPLE_PASSWORD" \
--team-id "$APPLE_TEAM_ID" \
--wait; then
echo "✅ DMG notarization succeeded"
xcrun stapler staple "$DMG_PATH"
echo "✅ DMG stapled"
break
fi
if [ "$attempt" -eq "$max_attempts" ]; then
echo "❌ DMG notarization failed after ${max_attempts} attempts" >&2
exit 1
fi
sleep_seconds=$((attempt * 60))
echo "⚠️ DMG notarization failed, retrying in ${sleep_seconds}s..."
sleep "$sleep_seconds"
done
- name: Verify macOS code signing and notarization
if: runner.os == 'macOS'
shell: bash
run: |
set -euo pipefail
# Verify .app (from Tauri bundle)
APP_PATH=""
for path in \
"src-tauri/target/universal-apple-darwin/release/bundle/macos" \
"src-tauri/target/aarch64-apple-darwin/release/bundle/macos" \
"src-tauri/target/x86_64-apple-darwin/release/bundle/macos" \
"src-tauri/target/release/bundle/macos"; do
if [ -d "$path" ]; then
[ -z "$APP_PATH" ] && APP_PATH=$(find "$path" -maxdepth 1 -name "*.app" -type d | head -1 || true)
fi
done
if [ -z "$APP_PATH" ]; then
echo "❌ No .app found for verification" >&2
exit 1
fi
echo "=== Verifying .app: $APP_PATH ==="
codesign --verify --deep --strict --verbose=2 "$APP_PATH"
echo "✅ codesign verification passed"
spctl -a -t exec -vv "$APP_PATH"
echo "✅ spctl assessment passed"
xcrun stapler validate "$APP_PATH"
echo "✅ .app stapler validation passed"
# Verify .dmg (from release-assets/, created by create-dmg + notarized)
DMG_PATH=$(find release-assets -maxdepth 1 -name "*.dmg" -type f | head -1 || true)
if [ -n "$DMG_PATH" ]; then
echo "=== Verifying .dmg: $DMG_PATH ==="
codesign --verify --verbose=2 "$DMG_PATH"
echo "✅ .dmg codesign verification passed"
spctl -a -t open --context context:primary-signature -vv "$DMG_PATH"
echo "✅ .dmg spctl assessment passed"
xcrun stapler validate "$DMG_PATH"
echo "✅ .dmg stapler validation passed"
else
echo "No .app found to zip (optional)" >&2
echo "No .dmg found for verification — release would ship without verified DMG" >&2
exit 1
fi
- name: Prepare Windows Assets
if: runner.os == 'Windows'
shell: pwsh
env:
WINDOWS_RELEASE_ARCH: ${{ matrix.arch || 'x86_64' }}
run: |
$ErrorActionPreference = 'Stop'
New-Item -ItemType Directory -Force -Path release-assets | Out-Null
$VERSION = $env:GITHUB_REF_NAME # e.g., v3.5.0
$isArm64 = $env:WINDOWS_RELEASE_ARCH -eq 'arm64'
$targetRoot = if ($isArm64) { 'src-tauri/target/aarch64-pc-windows-msvc/release' } else { 'src-tauri/target/release' }
$assetSuffix = if ($isArm64) { '-arm64' } else { '' }
# 仅打包 MSI 安装器 + .sig(用于 Updater
$msi = Get-ChildItem -Path 'src-tauri/target/release/bundle/msi' -Recurse -Include *.msi -ErrorAction SilentlyContinue | Select-Object -First 1
$msi = Get-ChildItem -Path (Join-Path $targetRoot 'bundle/msi') -Recurse -Include *.msi -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -eq $msi) {
# 兜底:全局搜索 .msi
$msi = Get-ChildItem -Path 'src-tauri/target/release/bundle' -Recurse -Include *.msi -ErrorAction SilentlyContinue | Select-Object -First 1
$msi = Get-ChildItem -Path (Join-Path $targetRoot 'bundle') -Recurse -Include *.msi -ErrorAction SilentlyContinue | Select-Object -First 1
}
if ($null -ne $msi) {
$dest = "CC-Switch-$VERSION-Windows.msi"
$dest = "CC-Switch-$VERSION-Windows$assetSuffix.msi"
Copy-Item $msi.FullName (Join-Path release-assets $dest)
Write-Host "Installer copied: $dest"
$sigPath = "$($msi.FullName).sig"
if (Test-Path $sigPath) {
Copy-Item $sigPath (Join-Path release-assets ("$dest.sig"))
Write-Host "Signature copied: $dest.sig"
} elseif ($isArm64) {
throw "Signature not found for $($msi.Name)"
} else {
Write-Warning "Signature not found for $($msi.Name)"
}
} elseif ($isArm64) {
throw 'No Windows ARM64 MSI installer found'
} else {
Write-Warning 'No Windows MSI installer found'
}
# 绿色版(portable):仅可执行文件打 zip(不参与 Updater
$exeCandidates = @(
'src-tauri/target/release/cc-switch.exe',
'src-tauri/target/x86_64-pc-windows-msvc/release/cc-switch.exe'
)
$exeCandidates = if ($isArm64) {
@('src-tauri/target/aarch64-pc-windows-msvc/release/cc-switch.exe')
} else {
@(
'src-tauri/target/release/cc-switch.exe',
'src-tauri/target/x86_64-pc-windows-msvc/release/cc-switch.exe'
)
}
$exePath = $exeCandidates | Where-Object { Test-Path $_ } | Select-Object -First 1
if ($null -ne $exePath) {
$portableDir = 'release-assets/CC-Switch-Portable'
New-Item -ItemType Directory -Force -Path $portableDir | Out-Null
Copy-Item $exePath $portableDir
$portableIniPath = Join-Path $portableDir 'portable.ini'
$portableContent = @(
'# CC Switch portable build marker',
'portable=true'
)
$portableContent = if ($isArm64) {
@(
'# CC Switch portable ARM64 build marker',
'portable=true',
'arch=arm64'
)
} else {
@(
'# CC Switch portable build marker',
'portable=true'
)
}
$portableContent | Set-Content -Path $portableIniPath -Encoding UTF8
$portableZip = "release-assets/CC-Switch-$VERSION-Windows-Portable.zip"
$portableZip = "release-assets/CC-Switch-$VERSION-Windows$assetSuffix-Portable.zip"
Compress-Archive -Path "$portableDir/*" -DestinationPath $portableZip -Force
Remove-Item -Recurse -Force $portableDir
Write-Host "Windows portable zip created: CC-Switch-$VERSION-Windows-Portable.zip"
Write-Host "Windows portable zip created: CC-Switch-$VERSION-Windows$assetSuffix-Portable.zip"
} elseif ($isArm64) {
throw 'Portable ARM64 exe not found'
} else {
Write-Warning 'Portable exe not found'
}
@@ -252,10 +519,11 @@ jobs:
set -euxo pipefail
mkdir -p release-assets
VERSION="${GITHUB_REF_NAME}" # e.g., v3.5.0
ARCH="${{ matrix.arch || 'x86_64' }}"
# Updater artifact: AppImage(含对应 .sig
APPIMAGE=$(find src-tauri/target/release/bundle -name "*.AppImage" | head -1 || true)
if [ -n "$APPIMAGE" ]; then
NEW_APPIMAGE="CC-Switch-${VERSION}-Linux.AppImage"
NEW_APPIMAGE="CC-Switch-${VERSION}-Linux-${ARCH}.AppImage"
cp "$APPIMAGE" "release-assets/$NEW_APPIMAGE"
[ -f "$APPIMAGE.sig" ] && cp "$APPIMAGE.sig" "release-assets/$NEW_APPIMAGE.sig" || echo ".sig for AppImage not found"
echo "AppImage copied: $NEW_APPIMAGE"
@@ -265,12 +533,19 @@ jobs:
# 额外上传 .deb(用于手动安装,不参与 Updater)
DEB=$(find src-tauri/target/release/bundle -name "*.deb" | head -1 || true)
if [ -n "$DEB" ]; then
NEW_DEB="CC-Switch-${VERSION}-Linux.deb"
cp "$DEB" "release-assets/$NEW_DEB"
echo "Deb package copied: $NEW_DEB"
cp "$DEB" "release-assets/CC-Switch-${VERSION}-Linux-${ARCH}.deb"
echo "Deb package copied: CC-Switch-${VERSION}-Linux-${ARCH}.deb"
else
echo "No .deb found (optional)"
fi
# 额外上传 .rpm(用于 Fedora/RHEL/openSUSE 等,不参与 Updater
RPM=$(find src-tauri/target/release/bundle -name "*.rpm" | head -1 || true)
if [ -n "$RPM" ]; then
cp "$RPM" "release-assets/CC-Switch-${VERSION}-Linux-${ARCH}.rpm"
echo "RPM package copied: CC-Switch-${VERSION}-Linux-${ARCH}.rpm"
else
echo "No .rpm found (optional)"
fi
- name: List prepared assets
shell: bash
@@ -284,28 +559,12 @@ jobs:
echo "Collected signatures (if any alongside artifacts):"
ls -la release-assets/*.sig || echo "No signatures found"
- name: Upload Release Assets
uses: softprops/action-gh-release@v2
- name: Upload release artifacts to workflow
uses: actions/upload-artifact@v7
with:
tag_name: ${{ github.ref_name }}
name: CC Switch ${{ github.ref_name }}
prerelease: true
body: |
## CC Switch ${{ github.ref_name }}
Claude Code 供应商切换工具
### 下载
- **macOS**: `CC-Switch-${{ github.ref_name }}-macOS.zip`(解压即用)或 `CC-Switch-${{ github.ref_name }}-macOS.tar.gz`Homebrew
- **Windows**: `CC-Switch-${{ github.ref_name }}-Windows.msi`(安装版)或 `CC-Switch-${{ github.ref_name }}-Windows-Portable.zip`(绿色版)
- **Linux**: `CC-Switch-${{ github.ref_name }}-Linux.AppImage`AppImage)或 `CC-Switch-${{ github.ref_name }}-Linux.deb`Debian/Ubuntu
---
提示:macOS 如遇"已损坏"提示,可在终端执行:`xattr -cr "/Applications/CC Switch.app"`
files: release-assets/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
name: release-assets-${{ runner.os }}-${{ matrix.arch || runner.arch }}
path: release-assets/*
if-no-files-found: error
- name: List generated bundles (debug)
if: always()
@@ -314,10 +573,70 @@ jobs:
echo "Listing bundles in src-tauri/target..."
find src-tauri/target -maxdepth 4 -type f -name "*.*" 2>/dev/null || true
- name: Clean up Apple signing keychain
if: runner.os == 'macOS' && always()
shell: bash
run: |
if [ -n "${ORIGINAL_DEFAULT_KEYCHAIN:-}" ]; then
security default-keychain -s "$ORIGINAL_DEFAULT_KEYCHAIN" || true
fi
if [ -f "$RUNNER_TEMP/build.keychain-db" ]; then
security delete-keychain "$RUNNER_TEMP/build.keychain-db" || true
fi
publish-release:
name: Publish GitHub Release
runs-on: ubuntu-22.04
needs: release
permissions:
contents: write
steps:
- name: Download built release artifacts
uses: actions/download-artifact@v8
with:
pattern: release-assets-*
path: release-assets
merge-multiple: true
- name: List downloaded release artifacts
shell: bash
run: |
set -euo pipefail
ls -la release-assets
- name: Upload Release Assets
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ github.ref_name }}
name: CC Switch ${{ github.ref_name }}
prerelease: true
body: |
## CC Switch ${{ github.ref_name }}
🌐 **Only Official Website / 唯一官方网站 / 唯一の公式サイト**: [ccswitch.io](https://ccswitch.io)
Claude Code 供应商切换工具
### 下载
- **macOS**: `CC-Switch-${{ github.ref_name }}-macOS.dmg`(推荐)或 `CC-Switch-${{ github.ref_name }}-macOS.zip`(解压即用)
- **Windows (x86_64)**: `CC-Switch-${{ github.ref_name }}-Windows.msi`(安装版)或 `CC-Switch-${{ github.ref_name }}-Windows-Portable.zip`(绿色版)
- **Windows (ARM64)**: `CC-Switch-${{ github.ref_name }}-Windows-arm64.msi`(安装版)或 `CC-Switch-${{ github.ref_name }}-Windows-arm64-Portable.zip`(绿色版)
- **Linux (x86_64)**: `CC-Switch-${{ github.ref_name }}-Linux-x86_64.AppImage` / `.deb` / `.rpm`
- **Linux (ARM64)**: `CC-Switch-${{ github.ref_name }}-Linux-arm64.AppImage` / `.deb` / `.rpm`
> `.tar.gz` 为 Tauri updater 自动更新专用,无需手动下载。
---
macOS 版本已通过 Apple 代码签名和公证,可直接安装使用。
files: release-assets/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
assemble-latest-json:
name: Assemble latest.json
runs-on: ubuntu-22.04
needs: release
needs: publish-release
permissions:
contents: write
steps:
@@ -346,8 +665,10 @@ jobs:
base_url="https://github.com/$REPO/releases/download/$TAG"
# 初始化空平台映射
mac_url=""; mac_sig=""
win_url=""; win_sig=""
linux_url=""; linux_sig=""
win_x64_url=""; win_x64_sig=""
win_arm64_url=""; win_arm64_sig=""
linux_x64_url=""; linux_x64_sig=""
linux_arm64_url=""; linux_arm64_sig=""
shopt -s nullglob
for sig in dl/*.sig; do
base=${sig%.sig}
@@ -358,10 +679,14 @@ jobs:
*.tar.gz)
# 视为 macOS updater artifact
mac_url="$url"; mac_sig="$sig_content";;
*.AppImage|*.appimage)
linux_url="$url"; linux_sig="$sig_content";;
*.msi|*.exe)
win_url="$url"; win_sig="$sig_content";;
*-Windows-arm64.msi)
win_arm64_url="$url"; win_arm64_sig="$sig_content";;
*-Windows.msi)
win_x64_url="$url"; win_x64_sig="$sig_content";;
*-Linux-arm64.AppImage|*-Linux-arm64.appimage)
linux_arm64_url="$url"; linux_arm64_sig="$sig_content";;
*-Linux-x86_64.AppImage|*-Linux-x86_64.appimage)
linux_x64_url="$url"; linux_x64_sig="$sig_content";;
esac
done
# 构造 JSON(仅包含存在的目标)
@@ -381,14 +706,24 @@ jobs:
first=0
done
fi
if [ -n "$win_url" ] && [ -n "$win_sig" ]; then
if [ -n "$win_x64_url" ] && [ -n "$win_x64_sig" ]; then
[ $first -eq 0 ] && echo ','
echo " \"windows-x86_64\": {\"signature\": \"$win_sig\", \"url\": \"$win_url\"}"
echo " \"windows-x86_64\": {\"signature\": \"$win_x64_sig\", \"url\": \"$win_x64_url\"}"
first=0
fi
if [ -n "$linux_url" ] && [ -n "$linux_sig" ]; then
if [ -n "$win_arm64_url" ] && [ -n "$win_arm64_sig" ]; then
[ $first -eq 0 ] && echo ','
echo " \"linux-x86_64\": {\"signature\": \"$linux_sig\", \"url\": \"$linux_url\"}"
echo " \"windows-aarch64\": {\"signature\": \"$win_arm64_sig\", \"url\": \"$win_arm64_url\"}"
first=0
fi
if [ -n "$linux_x64_url" ] && [ -n "$linux_x64_sig" ]; then
[ $first -eq 0 ] && echo ','
echo " \"linux-x86_64\": {\"signature\": \"$linux_x64_sig\", \"url\": \"$linux_x64_url\"}"
first=0
fi
if [ -n "$linux_arm64_url" ] && [ -n "$linux_arm64_sig" ]; then
[ $first -eq 0 ] && echo ','
echo " \"linux-aarch64\": {\"signature\": \"$linux_arm64_sig\", \"url\": \"$linux_arm64_url\"}"
first=0
fi
echo ' }'
+49
View File
@@ -0,0 +1,49 @@
name: Close Stale Issues
on:
schedule:
# Run daily at 00:00 UTC
- cron: '0 0 * * *'
workflow_dispatch: # Allow manual trigger
permissions:
issues: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v10
with:
# --- Timing ---
days-before-stale: 60
days-before-close: 14
# --- Stale label ---
stale-issue-label: 'stale'
# --- Messages (bilingual) ---
stale-issue-message: |
此 issue 已超过 60 天没有活动,已被标记为 `stale`。
如果此问题仍然存在,请回复以保持 issue 打开状态,否则将在 14 天后自动关闭。
This issue has been automatically marked as `stale` because it has not had activity for 60 days.
Please reply to keep it open, otherwise it will be automatically closed in 14 days.
close-issue-message: |
此 issue 因长时间无活动已被自动关闭。如果问题仍然存在,欢迎重新打开。
This issue has been automatically closed due to inactivity. If the problem persists, feel free to reopen it.
# --- Exemptions ---
# Issues with these labels will NEVER be marked stale
exempt-issue-labels: 'security,performance'
# Issues with 3+ reactions are likely popular requests, exempt them
exempt-issue-created-after: '2020-01-01'
# --- Processing limits ---
# Process up to 100 issues per run to avoid API rate limits
operations-per-run: 100
# --- Only issues, not PRs ---
days-before-pr-stale: -1
days-before-pr-close: -1
+11
View File
@@ -18,3 +18,14 @@ GEMINI.md
/.vscode
vitest-report.json
nul
# Flatpak build artifacts
flatpak/cc-switch.deb
flatpak-build/
flatpak-repo/
.worktrees/
.spec-workflow/
copilot-api
.history
CODEBUDDY.md
mainWindow.js
+1 -1
View File
@@ -1 +1 @@
v22.4.1
22.12.0
+1673 -40
View File
File diff suppressed because it is too large Load Diff
+175
View File
@@ -0,0 +1,175 @@
# Contributor Covenant Code of Conduct
> [中文版本](#贡献者公约行为准则)
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at **farion1231@gmail.com**. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
---
# 贡献者公约行为准则
> [English Version](#contributor-covenant-code-of-conduct)
## 我们的承诺
身为社区成员、贡献者和领袖,我们承诺使社区参与者不受骚扰,无论其年龄、体型、可见或不可见的缺陷、族裔、性征、性别认同和表达、经验水平、教育程度、社会与经济地位、国籍、相貌、种族、种姓、肤色、宗教信仰、性倾向或性取向如何。
我们承诺以有助于建立开放、友善、多样化、包容、健康社区的方式行事和互动。
## 我们的准则
有助于为我们的社区创造积极环境的行为例子包括但不限于:
- 表现出对他人的同情和善意
- 尊重不同的主张、观点和感受
- 提出和大方接受建设性意见
- 承担责任并向受我们错误影响的人道歉
- 注重社区共同诉求,而非个人得失
不当行为例子包括:
- 使用情色化的语言或图像,及性引诱或挑逗
- 嘲弄、侮辱或诋毁性评论,以及人身或政治攻击
- 公开或私下的骚扰行为
- 未经他人明确许可,公布他人的私人信息,如物理或电子邮件地址
- 其他有理由认定为违反职业操守的不当行为
## 责任和权力
社区领袖有责任解释和落实我们所认可的行为准则,并妥善公正地对他们认为不当、威胁、冒犯或有害的任何行为采取纠正措施。
社区领袖有权力和责任删除、编辑或拒绝与本行为准则不相符的评论(comment)、提交(able)、代码、维基(wiki)编辑、议题(able)或其他贡献,并在适当时告知采取措施的理由。
## 适用范围
本行为准则适用于所有社区场合,也适用于在公共场所代表社区时的个人。
代表社区的情形包括使用官方电子邮件地址、通过官方社交媒体帐户发帖或在线上或线下活动中担任指定代表。
## 监督
辱骂、骚扰或其他不可接受的行为可通过 **farion1231@gmail.com** 向负责监督的社区领袖报告。所有投诉都将得到及时和公平的审查和调查。
所有社区领袖都有义务尊重任何事件报告者的隐私和安全。
## 处理方针
社区领袖将遵循下列社区处理方针来明确他们所认定违反本行为准则的行为的处理方式:
### 1. 纠正
**社区影响**:使用不恰当的语言或其他在社区中被认定为不符合职业道德或不受欢迎的行为。
**处理意见**:由社区领袖发出非公开的书面警告,明确说明违规行为的性质,并解释举止如何不妥。或将要求公开道歉。
### 2. 警告
**社区影响**:单个或一系列违规行为。
**处理意见**:警告并对连续性行为进行处理。在指定时间内,不得与相关人员互动,包括主动与行为准则执行者互动。这包括避免在社区场所和外部渠道中的互动。违反这些条款可能会导致临时或永久封禁。
### 3. 临时封禁
**社区影响**:严重违反社区准则,包括持续的不当行为。
**处理意见**:在指定时间内,暂时禁止与社区进行任何形式的互动或公开交流。在此期间,不得与相关人员进行公开或私下互动,包括主动与行为准则执行者互动。违反这些条款可能会导致永久封禁。
### 4. 永久封禁
**社区影响**:行为模式表现出违反社区准则,包括持续的不当行为、骚扰个人或攻击或贬低某个类别的个体。
**处理意见**:永久禁止在社区内进行任何形式的公开互动。
## 参见
本行为准则改编自 [Contributor Covenant][homepage] 2.1 版,参见 [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]。
社区处理方针灵感来源于 [Mozilla 的行为准则执行阶梯][Mozilla CoC]。
有关本行为准则的常见问题的答案,参见 [https://www.contributor-covenant.org/faq][FAQ]。其他语言翻译参见 [https://www.contributor-covenant.org/translations][translations]。
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
+253
View File
@@ -0,0 +1,253 @@
# Contributing to CC Switch
> [中文版本](#贡献指南)
Thank you for your interest in contributing to CC Switch! Please read our [Code of Conduct](./CODE_OF_CONDUCT.md) before participating.
## How to Contribute
There are many ways to contribute:
- **Report bugs** — Found something broken? [Open a bug report](https://github.com/farion1231/cc-switch/issues/new?template=bug_report.yml).
- **Suggest features** — Have an idea? [Submit a feature request](https://github.com/farion1231/cc-switch/issues/new?template=feature_request.yml).
- **Improve docs** — Spot a typo or missing info? [Report a doc issue](https://github.com/farion1231/cc-switch/issues/new?template=doc_issue.yml).
- **Contribute code** — Fix bugs or implement features via pull requests.
- **Translate** — Help us improve translations for English, Chinese, and Japanese.
> **Security vulnerabilities**: Please do NOT use public issues. See our [Security Policy](./SECURITY.md) instead.
## Development Setup
### Prerequisites
- Node.js 18+ and pnpm 8+
- Rust 1.85+ and Cargo
- [Tauri 2.0 prerequisites](https://v2.tauri.app/start/prerequisites/)
### Quick Start
```bash
# Install dependencies
pnpm install
# Start development server with hot reload
pnpm dev
```
### Useful Commands
| Command | Description |
|---------|-------------|
| `pnpm dev` | Start dev server (hot reload) |
| `pnpm build` | Production build |
| `pnpm typecheck` | TypeScript type checking |
| `pnpm test:unit` | Run unit tests |
| `pnpm lint` | ESLint check |
| `pnpm format` | Format code (Prettier) |
| `pnpm format:check` | Check code formatting |
For Rust backend:
```bash
cd src-tauri
cargo fmt # Format Rust code
cargo clippy # Run linter
cargo test # Run tests
```
## Code Style
- **Frontend**: Prettier for formatting, ESLint for linting, strict TypeScript (`pnpm typecheck`)
- **Backend**: `cargo fmt` for formatting, `cargo clippy` for linting
- **Tauri 2.0**: Command names must use camelCase
Run all checks before submitting:
```bash
pnpm typecheck && pnpm format:check && pnpm test:unit
cd src-tauri && cargo fmt --check && cargo clippy && cargo test
```
## Pull Request Guidelines
1. **Open an issue first** for new features — PRs for features that are not a good fit may be closed.
2. **Fork and branch** — Create a feature branch from `main` (e.g., `feat/my-feature` or `fix/issue-123`).
3. **Keep PRs focused** — One feature or fix per PR. Avoid unrelated changes.
4. **Follow the PR template** — Fill in the summary, related issue, and checklist.
### PR Checklist
- [ ] `pnpm typecheck` passes
- [ ] `pnpm format:check` passes
- [ ] `cargo clippy` passes (if Rust code changed)
- [ ] Updated i18n files if user-facing text changed
### Commit Convention
We use [Conventional Commits](https://www.conventionalcommits.org/):
```
feat(provider): add support for new provider
fix(tray): resolve menu not updating after switch
docs(readme): update installation instructions
ci: add format check workflow
chore(deps): update dependencies
```
## AI-Assisted Contributions
We welcome AI-assisted contributions, but **the responsibility stays with you**. AI tools lower the cost of writing code — they do not lower the cost of reviewing it. Maintainers are not obligated to clean up AI-generated output.
By submitting a PR, you agree to the following:
1. **You have read and understood your code.** You must be able to explain any line in your PR. If you cannot, it is not ready for review.
2. **You have tested it yourself.** Every change must be verified locally — not just "it looks right." Do not submit code for platforms or features you cannot test.
3. **PRs must be small and focused.** One issue, one PR. Large, sprawling, multi-topic PRs will be closed.
4. **Open an issue first.** Drive-by PRs with no prior discussion — especially AI-generated ones — may be closed without review.
5. **Maintainers may close without explanation.** PRs that appear to be unreviewed AI output — hallucinated fixes, unnecessary refactors, bulk changes with no context — may be closed at the maintainer's discretion.
**In short**: AI is a tool, not a substitute for understanding. Use it to help you contribute better, not to shift work onto maintainers.
## Internationalization (i18n)
CC Switch supports three languages. When modifying user-facing text:
1. Update **all three** locale files:
- `src/locales/en/translation.json`
- `src/locales/zh/translation.json`
- `src/locales/ja/translation.json`
2. Use the `t()` function from i18next for all UI text.
3. Never hardcode user-facing strings.
## Questions?
- [Open a question](https://github.com/farion1231/cc-switch/issues/new?template=question.yml)
- [GitHub Discussions](https://github.com/farion1231/cc-switch/discussions)
---
# 贡献指南
> [English Version](#contributing-to-cc-switch)
感谢你对 CC Switch 的贡献兴趣!参与之前请阅读我们的[行为准则](./CODE_OF_CONDUCT.md)。
## 如何贡献
你可以通过多种方式参与贡献:
- **报告 Bug** — 发现问题?[提交 Bug 报告](https://github.com/farion1231/cc-switch/issues/new?template=bug_report.yml)。
- **建议功能** — 有想法?[提交功能请求](https://github.com/farion1231/cc-switch/issues/new?template=feature_request.yml)。
- **改进文档** — 发现错误或缺失?[报告文档问题](https://github.com/farion1231/cc-switch/issues/new?template=doc_issue.yml)。
- **贡献代码** — 通过 Pull Request 修复 Bug 或实现新功能。
- **翻译** — 帮助改进英文、中文和日文的翻译。
> **安全漏洞**:请不要使用公开 Issue 报告。请参阅我们的[安全策略](./SECURITY.md)。
## 开发环境搭建
### 前提条件
- Node.js 18+ 和 pnpm 8+
- Rust 1.85+ 和 Cargo
- [Tauri 2.0 开发环境](https://v2.tauri.app/start/prerequisites/)
### 快速开始
```bash
# 安装依赖
pnpm install
# 启动开发服务器(热重载)
pnpm dev
```
### 常用命令
| 命令 | 说明 |
|------|------|
| `pnpm dev` | 启动开发服务器(热重载) |
| `pnpm build` | 构建生产版本 |
| `pnpm typecheck` | TypeScript 类型检查 |
| `pnpm test:unit` | 运行单元测试 |
| `pnpm lint` | ESLint 检查 |
| `pnpm format` | 格式化代码(Prettier |
| `pnpm format:check` | 检查代码格式 |
Rust 后端命令:
```bash
cd src-tauri
cargo fmt # 格式化 Rust 代码
cargo clippy # 运行 Clippy 检查
cargo test # 运行测试
```
## 代码规范
- **前端**:使用 Prettier 格式化、ESLint 检查、严格 TypeScript`pnpm typecheck`
- **后端**:使用 `cargo fmt` 格式化、`cargo clippy` 检查
- **Tauri 2.0**:命令名必须使用 camelCase
提交前运行所有检查:
```bash
pnpm typecheck && pnpm format:check && pnpm test:unit
cd src-tauri && cargo fmt --check && cargo clippy && cargo test
```
## Pull Request 指南
1. **先开 Issue 讨论** — 新功能请先开 Issue,不适合项目方向的 PR 可能会被关闭。
2. **Fork 并创建分支** — 从 `main` 创建功能分支(如 `feat/my-feature``fix/issue-123`)。
3. **保持 PR 专注** — 每个 PR 只做一件事,避免无关改动。
4. **遵循 PR 模板** — 填写概述、关联 Issue 和检查清单。
### PR 检查清单
- [ ] `pnpm typecheck` 通过
- [ ] `pnpm format:check` 通过
- [ ] `cargo clippy` 通过(如修改了 Rust 代码)
- [ ] 如修改了用户可见文本,已更新国际化文件
### 提交信息规范
我们使用 [Conventional Commits](https://www.conventionalcommits.org/)
```
feat(provider): add support for new provider
fix(tray): resolve menu not updating after switch
docs(readme): update installation instructions
ci: add format check workflow
chore(deps): update dependencies
```
## AI 辅助贡献
我们欢迎 AI 辅助的贡献,但**责任始终在你身上**。AI 工具降低了写代码的成本,但并没有降低 review 的成本。维护者没有义务替你清理 AI 的产出。
提交 PR 即表示你同意以下规则:
1. **你已阅读并理解了你的代码。** 你必须能解释 PR 中的每一行。如果做不到,说明还没准备好提交 review。
2. **你已亲自测试过。** 每个改动都必须在本地验证——而不是"看起来对"。不要提交你自己无法测试的平台或功能的代码。
3. **PR 必须小而聚焦。** 一个 Issue 对应一个 PR。大而散、跨多个主题的 PR 会被直接关闭。
4. **先开 Issue 讨论。** 没有事先讨论的"路过式 PR"——尤其是 AI 生成的——可能会被直接关闭。
5. **维护者可以直接关闭。** 看起来是未经审阅的 AI 产出的 PR——虚构的修复、不必要的重构、缺乏上下文的批量改动——维护者可自行决定关闭。
**一句话总结**:AI 是工具,不是理解力的替代品。用它来帮助你更好地贡献,而不是把工作转移给维护者。
## 国际化(i18n
CC Switch 支持三种语言。修改用户可见文本时:
1. **同时更新三个**语言文件:
- `src/locales/en/translation.json`
- `src/locales/zh/translation.json`
- `src/locales/ja/translation.json`
2. 所有 UI 文本使用 i18next 的 `t()` 函数。
3. 不要硬编码用户可见的字符串。
## 有疑问?
- [提问](https://github.com/farion1231/cc-switch/issues/new?template=question.yml)
- [GitHub 讨论区](https://github.com/farion1231/cc-switch/discussions)
+340 -227
View File
@@ -1,48 +1,212 @@
<div align="center">
# All-in-One Assistant for Claude Code, Codex & Gemini CLI
# CC Switch
[![Version](https://img.shields.io/badge/version-3.8.2-blue.svg)](https://github.com/farion1231/cc-switch/releases)
[![Trending](https://img.shields.io/badge/🔥_TypeScript_Trending-Daily%20%7C%20Weekly%20%7C%20Monthly-ff6b6b.svg)](https://github.com/trending/typescript)
### The All-in-One Manager for Claude Code, Claude Desktop, Codex, Gemini CLI, Grok Build, 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)
[![Built with Tauri](https://img.shields.io/badge/built%20with-Tauri%202-orange.svg)](https://tauri.app/)
[![Downloads](https://img.shields.io/endpoint?url=https://api.pinstudios.net/api/badges/downloads/farion1231/cc-switch/total)](https://github.com/farion1231/cc-switch/releases/latest)
[![Downloads](https://img.shields.io/github/downloads/farion1231/cc-switch/total)](https://github.com/farion1231/cc-switch/releases/latest)
<a href="https://trendshift.io/repositories/15372" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15372" alt="farion1231%2Fcc-switch | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
<a href="https://www.star-history.com/#farion1231/cc-switch&Date"><picture><source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=farion1231/cc-switch&theme=dark" /><img alt="Star History Rank" src="https://api.star-history.com/badge?repo=farion1231/cc-switch" width="196" height="55" /></picture></a>
English | [中文](README_ZH.md) | [日本語](README_JA.md) | [Changelog](CHANGELOG.md)
### 🌐 The Only Official Website: **[ccswitch.io](https://ccswitch.io)**
**From Provider Switcher to All-in-One AI CLI Management Platform**
Unified management for Claude Code, Codex & Gemini CLI provider configurations, MCP servers, Skills extensions, and system prompts.
English | [中文](README_ZH.md) | [日本語](README_JA.md) | [Deutsch](README_DE.md) | [Changelog](CHANGELOG.md)
</div>
## ❤️Sponsor
![Zhipu GLM](assets/partners/banners/glm-en.jpg)
> [Want to appear here?](mailto:farion1231@gmail.com)
This project is sponsored by Z.ai, supporting us with their GLM CODING PLAN.
<details open>
<summary>Click to collapse</summary>
GLM CODING PLAN is a subscription service designed for AI coding, starting at just $3/month. It provides access to their flagship GLM-4.6 model across 10+ popular AI coding tools (Claude Code, Cline, Roo Code, etc.), offering developers top-tier, fast, and stable coding experiences.
[![Kimi K2.7 Code](https://gcdn.moonshot.cn/growth-cdn/sponsor/kimi-en.png)](https://platform.kimi.ai?aff=cc-switch)
Get 10% OFF the GLM CODING PLAN with [this link](https://z.ai/subscribe?ic=8JVLJQFSKB)!
Kimi K3 is Moonshot AI's most capable model and the world's first open 3T-class model. With 2.8 trillion parameters, native vision, and a 1-million-token context window, K3 delivers frontier performance across long-horizon coding, knowledge work, and reasoning. CC Switch makes it easy to configure and switch to Kimi across agentic tools. **[Click here to start using Kimi](https://platform.kimi.ai?aff=cc-switch)**
Doing mostly coding work? Try the **[Kimi Code subscription](https://www.kimi.com/code/?aff=cc-switch)**.
---
<table>
<tr>
<td width="180"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></td>
<td>Thanks to PackyCode for sponsoring this project! PackyCode is a reliable and efficient API relay service provider, offering relay services for Claude Code, Codex, Gemini, and more. PackyCode provides special discounts for our software users: register using <a href="https://www.packyapi.com/register?aff=cc-switch">this link</a> and enter the "cc-switch" promo code during recharge to get 10% off.</td>
<td width="180"><a href="https://www.packyapi.com/register?aff=cc-switch"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></a></td>
<td>Thanks to PackyCode for sponsoring this project! PackyCode is a reliable and efficient API relay service provider, offering relay services for Claude Code, Codex, Gemini, and more. PackyCode provides special discounts for our software users: register using <a href="https://www.packyapi.com/register?aff=cc-switch">this link</a> and enter the "cc-switch" promo code during first recharge to get 10% off.</td>
</tr>
<tr>
<td width="180"><img src="assets/partners/logos/sds-en.png" alt="ShanDianShuo" width="150"></td>
<td>Thanks to ShanDianShuo for sponsoring this project! ShanDianShuo is a local-first AI voice input: Millisecond latency, data stays on device, 4x faster than typing, AI-powered correction, Privacy-first, completely free. Doubles your coding efficiency with Claude Code! <a href="https://www.shandianshuo.cn">Free download</a> for Mac/Win</td>
<td width="180"><a href="https://zetaapi.ai/go/u117"><img src="assets/partners/logos/zetaapi-banner.png" alt="ZetaAPI" width="150"></a></td>
<td>Thanks to ZetaAPI for sponsoring this project! ZetaAPI focuses on real model fidelity, no watered-down responses, no quality degradation, and pricing as low as 35% of official rates. The platform does not mix traffic, secretly replace models with lower-quality alternatives, or use fake model routing. It supports Claude Code, Codex, Gemini, ChatGPT, and other mainstream AI models, helping users significantly reduce API costs while maintaining reliable model quality. At the same time, ZetaAPI provides enterprise-grade SLA-backed stability, standard API compatibility, one API key for multiple models, fast integration, and pay-as-you-go billing, making it suitable for AI products, coding agents, internal business tools, customer service systems, content generation, and automation workflows. If any model is verified to be inconsistent with its stated quality, ZetaAPI backs it with a 10x compensation guarantee, giving users a more stable, transparent, and trustworthy experience. Register via <a href="https://zetaapi.ai/go/u117">this link</a> and use the promo code CC-SWITCH during your first recharge to enjoy an exclusive 10% discount on your first top-up, just for CC Switch users!</td>
</tr>
<tr>
<td width="180"><a href="https://apinebula.com/VjM74M"><img src="assets/partners/logos/apinebula_banner.png" alt="APINebula" width="150"></a></td>
<td>Thanks to APINEBULA for sponsoring this project! APINEBULA, an enterprise-grade AI aggregation platform under Galaxy Video Bureau, leverages extensive platform resources to provide developers, teams, and enterprises with stable, cost-effective access to large language model APIs. The platform integrates leading, full-powered models like Claude, GPT, and Gemini, allowing you to connect to the world's top AI models through a single API, with prices starting as low as 10% of the original cost. Designed for AI programming, Agent development, and business system integration, APINEBULA supports enterprise-grade high concurrency, formal contracts, corporate bank transfers, and invoicing services. APINEBULA provides special discounts for our software users: register using <a href="https://apinebula.com/VjM74M">this link</a> and enter the <strong>"ccswitch"</strong> promo code during your first recharge to get <strong>10% off</strong>.</td>
</tr>
<tr>
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=9915W3"><img src="assets/partners/logos/aicodemirror.jpg" alt="AICodeMirror" width="150"></a></td>
<td>Thanks to AICodeMirror for sponsoring this project! AICodeMirror provides official high-stability relay services for Claude Code / Codex / Gemini CLI, with enterprise-grade concurrency, fast invoicing, and 24/7 dedicated technical support.
Claude Code / Codex / Gemini official channels at 38% / 2% / 9% of original price, with extra discounts on top-ups! AICodeMirror offers special benefits for CC Switch users: register via <a href="https://www.aicodemirror.com/register?invitecode=9915W3">this link</a> to enjoy 20% off your first top-up, and enterprise customers can get up to 25% off!</td>
</tr>
<tr>
<td width="180"><a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/"><img src="assets/partners/logos/pateway.png" alt="PatewayAI" width="150"></a></td>
<td>Thanks to PatewayAI for sponsoring this project! PatewayAI is an API relay service provider built for heavy AI developers, focused on directly relaying official high-quality model APIs. It offers the full Claude lineup and the Codex series, 100% sourced from official channels — no dilution, no fakes, verification welcome. Billing is transparent and every token-level invoice can be audited line by line.
It also supports enterprise-grade concurrency and provides a dedicated management platform for enterprise customers — formal contracts and invoicing are available; visit the official website for contact details.
Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this link</a> to receive $3 in trial credit. Top-ups go as low as 60% of the original price, with a two-way referral bonus of up to $150!</td>
</tr>
<tr>
<td width="180"><a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL"><img src="assets/partners/logos/fenno-banner.png" alt="Fenno.ai" width="150"></a></td>
<td>Thanks to Fenno.ai for sponsoring this project! Fenno.ai is a stable and efficient API relay service provider, currently focused on Codex relay. It is compatible with the OpenAI and Anthropic protocols and can be flexibly used from Codex, Claude Code, OpenCode, and other mainstream coding tools. It reliably supports enterprise-grade workloads of hundreds of billions of tokens per day, with corporate (B2B) settlement and invoicing for both domestic and overseas entities. Fenno.ai offers an exclusive benefit for CC Switch users: subscribe via <a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL">this link</a> to the incredible ¥9.9 Coding Plan worth $150 in credits, and earn up to 20% in referral rewards — invite more, earn more!</td>
</tr>
<tr>
<td width="180"><a href="https://runapi.co/register?aff=iOKB"><img src="assets/partners/logos/runapi.jpg" alt="RunAPI" width="150"></a></td>
<td>Thanks to RunAPI for sponsoring this project! RunAPI is a high-performance and reliable AI model API gateway — one API key gives you access to 150+ mainstream models including OpenAI, Claude, Gemini, DeepSeek, and Grok, with prices as low as 10% of the official rate and excellent stability. It works seamlessly with Claude Code, OpenClaw, and other tools. Exclusive benefit for CC Switch users: register via <a href="https://runapi.co/register?aff=iOKB">this link</a> and enjoy a 10% discount on your first top-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>
<tr>
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
<td>Thanks to Shengsuanyun for sponsoring this project! Shengsuanyun is a super factory serving AI Native Teams — an industrial-grade AI task parallel execution platform. Its model marketplace aggregates Claude, ChatGPT, Gemini, and other domestic and international LLM and multimedia model capabilities with direct supply. Absolutely no reverse engineering or dilution — platform-wide model SLA availability reaches 99.7%, with <a href="https://watch.shengsuanyun.com/status/shengsuanyun">monitoring dashboards</a> showing green across the board. It also offers enterprise-grade custom gateways for fine-grained team cost and permission management, smart routing, security protection, and BYOK (Bring Your Own Key) hosting. The platform charges on a pay-per-use and tokens plan (coming soon) basis, with invoicing available. Register via <a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">this link</a> as a new user to receive ¥10 in credits plus a 10% bonus on your first top-up.</td>
</tr>
<tr>
<td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for CC Switch users: if you register via <a href="https://aigocode.com/invite/CC-SWITCH">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td>
</tr>
<tr>
<td width="180"><a href="https://subrouter.ai/register?aff=l3ri"><img src="assets/partners/logos/subrouter-banner.png" alt="SubRouter" width="150"></a></td>
<td>Thanks to SubRouter for sponsoring this project! SubRouter is a marketplace and smart routing platform for AI service operators. Merchants can launch operating sites, publish packages, manage users, models, and pricing, while users discover services and access reliable AI models through one unified API. Register via <a href="https://subrouter.ai/register?aff=l3ri">this link</a>!</td>
</tr>
<tr>
<td width="180"><a href="https://apikey.fun/register?aff=CCSwitch"><img src="assets/partners/logos/apikey_banner.png" alt="APIKEY.FUN" width="150"></a></td>
<td>Thanks to APIKEY.FUN for sponsoring this project! APIKEY.FUN is a professional enterprise-grade AI relay platform dedicated to providing stable, efficient, and low-cost AI model API access for enterprises and individual developers. The platform supports popular mainstream models such as Claude, OpenAI, and Gemini, with prices as low as 7% of official rates. Register through this project's <a href="https://apikey.fun/register?aff=CCSwitch">exclusive link</a> to enjoy an exclusive offer of up to <strong>permanent 5% off top-ups</strong>.</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>This project is sponsored by <a href="https://console.claudeapi.com/register?aff=pCLD">Claude API</a>. Direct Claude API access — connect Claude Code and Agent apps in 3 minutes. New users can claim a free trial credit.Powered by official Anthropic API keys + AWS Bedrock official channels. No reverse engineering, no model degradation. Full support for Opus / Sonnet / Haiku model lineup, with official capabilities preserved including Tool Use, 1M context window, and more. Built for Claude Code power users, Agent engineers, and enterprise engineering teams. Invoicing and dedicated team support available. Click <a href="https://console.claudeapi.com/register?aff=pCLD">here</a> to register!</td>
</tr>
<tr>
<td width="180"><a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
<td>Thanks to <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai</a> for sponsoring this project! code0.ai is an AI coding service platform built for developers, supporting Claude Code, Codex, Gemini, and other mainstream AI coding capabilities. It helps individual developers and teams use AI Agents more stably and efficiently for coding, debugging, refactoring, and automation workflows. ccswitch users can contact customer support via the <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai website</a> to claim test credits and experience a reliable AI coding service.</td>
</tr>
<tr>
<td width="180"><a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory"><img src="assets/partners/logos/TeamoRouter-banner.png" alt="TeamoRouter" width="150"></a></td>
<td>Thanks to TeamoRouter for sponsoring this project! TeamoRouter is an enterprise-grade Agentic LLM gateway built for developers, AI teams, and businesses. Without requiring any subscriptions, it lets you access Claude Code, Codex, Gemini CLI, OpenAI Codex, and other popular AI agents through a single unified API, while offering API pricing at discounts of up to 90%.
Unlike typical API relay services, TeamoRouter aggregates hundreds of official model providers and trusted infrastructure partners, including OpenAI, Anthropic, Vertex, Azure, and AWS bedrock. Every provider is verified for 100% Agent protocol compatibility, cache performance, and request traceability, ensuring stable quality instead of reverse-engineered or diluted endpoints. The platform delivers near-official TTFT, 99.6% SLA, enterprise-scale throughput up to 5,000 QPM, and industry-leading cache hit rates that dramatically reduce token costs for long-running agent workflows.
TeamoRouter also offers enterprise features including centralized billing, team management, BYOK, smart routing, usage analytics, dynamic provider optimization, and dedicated support. For an even simpler experience, Teamo Desktop lets you use Claude Code, Codex, Gemini CLI, and other popular AI agents with one-click setup—no API key management or manual gateway configuration required. Register via <a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory">this link</a> as a new user to receive 10% off your first top-up.</td>
</tr>
<tr>
<td width="180"><a href="https://www.newapi.ai/"><img src="assets/partners/logos/newapi-banner.png" alt="new-api" width="150"></a></td>
<td>Thanks to the open-source AI infrastructure project <a href="https://www.newapi.ai/">new-api</a> for its strong support of this project! new-api is an open-source AI infrastructure project from QuantumNous and one of the leading unified LLM access-and-distribution projects by activity and adoption, focused on helping developers, teams, and enterprises build manageable, scalable AI service platforms at lower cost. As a fellow project rooted in the open-source ecosystem, new-api hopes to sponsor and support the continued growth of more outstanding open-source projects. 🌟 Star new-api to show your support: <a href="https://github.com/QuantumNous/new-api">https://github.com/QuantumNous/new-api</a>. Website: <a href="https://www.newapi.ai/">https://www.newapi.ai/</a>.</td>
</tr>
<tr>
<td width="180"><a href="https://claudecn.ai/register?aff=HEL9"><img src="assets/partners/logos/claudecn.jpg" alt="ClaudeCN" width="150"></a></td>
<td>Thanks to ClaudeCN for sponsoring this project! ClaudeCN is an enterprise-grade AI gateway platform operated by a registered company. It delivers high-availability commercial API access to popular models including Claude, GPT, and DeepSeek, and is built around formal enterprise procurement workflows — corporate bank transfers, signed contracts, and full compliance. Register via <a href="https://claudecn.ai/register?aff=HEL9">this link</a>!</td>
</tr>
<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/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
</tr>
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/YflgU2Ve"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/YflgU2Ve">this link</a> and complete real-name verification to receive ¥16 in bonus credit, usable across models on the platform. SiliconFlow is also now compatible with OpenClaw, allowing users to connect a SiliconFlow API key and call major AI models for free.</td>
</tr>
<tr>
<td width="180"><a href="https://nekocode.ai?aff=CCSWITCH"><img src="assets/partners/logos/nekocode-banner.png" alt="NekoCode" width="150"></a></td>
<td>Thanks to <a href="https://nekocode.ai?aff=CCSWITCH">NekoCode</a> for sponsoring this project! NekoCode provides developers with a stable, efficient, and reliable API relay service for Claude, Codex, and other AI models. With transparent pricing and flexible pay-as-you-go billing, it offers a simple and cost-effective way to access AI models. CC Switch users can enjoy an exclusive 10% discount: register via <a href="https://nekocode.ai?aff=CCSWITCH">this link</a> and enter promo code <code>cc-switch</code> during recharge to receive 10% off your top-up!</td>
</tr>
<tr>
<td width="180"><a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch"><img src="assets/partners/logos/atlascloud_banner.png" alt="Atlas Cloud" width="150"></a></td>
<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.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch"><img src="assets/partners/logos/ucloud.png" alt="Compshare" width="150"></a></td>
<td>Thanks to Compshare for sponsoring this project! Compshare is UCloud's AI cloud platform, providing stable and comprehensive domestic and international model APIs with just one key. Featuring cost-effective monthly and per-use domestic-model Coding Plan packages, alongside stable officially-relayed overseas models. Supports Claude Code, Codex, and API access. Enterprise-grade high concurrency, 24/7 technical support, and self-service invoicing. Users who register via <a href="https://www.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch">this link</a> will receive a free 5 CNY platform trial credit!</td>
</tr>
<tr>
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.svg" 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://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
<td>Thanks to SSSAiCode for sponsoring this project! SSSAiCode is a stable and reliable API relay service, dedicated to providing stable, reliable, and affordable Claude and Codex model services, with same-day fast invoicing. SSSAiCode offers a special deal for CC Switch users: register via <a href="https://www.sssaicode.com/register?ref=DCP0SM">this link</a> to enjoy $10 extra credit on every top-up!</td>
</tr>
<tr>
<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>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://www.right.codes/register?aff=CCSWITCH"><img src="assets/partners/logos/rightcode.jpg" alt="RightCode" width="150"></a></td>
<td>Thank you to Right Code for sponsoring this project! Right Code reliably provides routing services for models such as Claude Code, Codex, and Gemini, with both pay-as-you-go and monthly subscription billing options available. Invoices are available upon top-up, and enterprise and team users can receive dedicated one-on-one support. Right Code also offers an exclusive discount for CC Switch users: register via <a href="https://www.right.codes/register?aff=CCSWITCH">this link</a>, and with every top-up you will receive pay-as-you-go credit equivalent to 5% of the amount paid.</td>
</tr>
<tr>
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
<td>Thanks to ETok.ai for sponsoring this project! ETok.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://etok.ai">here</a> to register!</td>
</tr>
<tr>
<td width="180"><a href="https://cubence.com/signup?code=CCSWITCH&source=ccs"><img src="assets/partners/logos/cubence.png" alt="Cubence" width="150"></a></td>
<td>Thanks to Cubence for sponsoring this project! Cubence is a reliable and efficient API relay service provider, offering relay services for Claude Code, Codex, Gemini, and more with flexible billing options including pay-as-you-go and monthly plans. Cubence provides special discounts for CC Switch users: register using <a href="https://cubence.com/signup?code=CCSWITCH&source=ccs">this link</a> and enter the "CCSWITCH" promo code during recharge to get 10% off every top-up!</td>
</tr>
<tr>
<td width="180"><a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch"><img src="assets/partners/logos/crazyrouter.png" alt="Crazyrouter" width="150"></a></td>
<td>Thanks to Crazyrouter for sponsoring this project! Crazyrouter is a high-performance AI API aggregation platform — one API key for 300+ models including Claude Code, Codex, Gemini CLI, and more. All models at 55% of official pricing with auto-failover, smart routing, and unlimited concurrency. Crazyrouter offers an exclusive deal for CC Switch users: register via <a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch">this link</a> and contact customer support to claim <strong>$2 free credit</strong>, plus enter promo code `CCSWITCH` on your first top-up for an extra <strong>30% bonus credit</strong>! </td>
</tr>
<tr>
<td width="180"><a href="https://www.dmxapi.cn/register?aff=bUHu"><img src="assets/partners/logos/dmx-en.jpg" alt="DMXAPI" width="150"></a></td>
<td>Thanks to DMXAPI for sponsoring this project! DMXAPI provides global large model API services to 200+ enterprise users. One API key for all global models. Features include: instant invoicing, unlimited concurrency, starting from $0.15, 24/7 technical support. GPT/Claude/Gemini all at 32% off, domestic models 20-50% off, Claude Code exclusive models at 66% off! <a href="https://www.dmxapi.cn/register?aff=bUHu">Register here</a></td>
</tr>
</table>
</details>
## Why CC Switch?
Modern AI-powered coding relies on tools like Claude Code, Claude Desktop, Codex, Gemini CLI, Grok Build, 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 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, Eight Tools** — Manage Claude Code, Claude Desktop, Codex, Gemini CLI, Grok Build, 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 Claude, Codex, Gemini, Grok Build, 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
- **Built-in Utilities** — Includes various utilities for first-launch login confirmation, signature bypass, plugin extension sync, and more
## Screenshots
| Main Interface | Add Provider |
@@ -51,108 +215,138 @@ Get 10% OFF the GLM CODING PLAN with [this link](https://z.ai/subscribe?ic=8JVLJ
## Features
### Current Version: v3.8.2 | [Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-note-v3.8.0-en.md)
[Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.16.1-en.md)
**v3.8.0 Major Update (2025-11-28)**
### Provider Management
**Persistence Architecture Upgrade & Brand New UI**
- **8 supported tools, 50+ presets** — Claude Code, Claude Desktop, Codex, Gemini CLI, Grok Build, 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
- **SQLite + JSON Dual-layer Architecture**
- Migrated from JSON file storage to SQLite + JSON dual-layer structure
- Syncable data (providers, MCP, Prompts, Skills) stored in SQLite
- Device-level data (window state, local paths) stored in JSON
- Lays the foundation for future cloud sync functionality
- Schema version management for database migrations
### Proxy & Failover
- **Brand New User Interface**
- Completely redesigned interface layout
- Unified component styles and smoother animations
- Optimized visual hierarchy
- Tailwind CSS downgraded from v4 to v3.4 for better browser compatibility
- **Local proxy with hot-switching** — Format conversion, auto-failover, circuit breaker, provider health monitoring, and request rectifier
- **App-level takeover** — Independently proxy Claude, Codex, Gemini, or Grok Build, down to individual providers
- **Japanese Language Support**
- Added Japanese interface support (now supports Chinese/English/Japanese)
### MCP, Prompts & Skills
- **Auto Launch on Startup**
- One-click enable/disable in settings
- Platform-native APIs (Registry/LaunchAgent/XDG autostart)
- **Unified MCP panel** — Manage MCP servers across Claude, Codex, Gemini, Grok Build, 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
- **Skills Recursive Scanning**
- Support for multi-level directory structures
- Allow same-named skills from different repositories
### Usage & Cost Tracking
- **Critical Bug Fixes**
- Fixed custom endpoints lost when updating providers
- Fixed Gemini configuration write issues
- Fixed Linux WebKitGTK rendering issues
- **Usage dashboard** — Track spending, requests, and tokens with trend charts, detailed request logs, and custom per-model pricing
**v3.7.0 Highlights**
### Session Manager & Workspace
**Six Core Features, 18,000+ Lines of New Code**
- Browse, search, and restore conversation history across supported session sources
- **Workspace editor** (OpenClaw) — Edit agent files (AGENTS.md, SOUL.md, etc.) with Markdown preview
- **Gemini CLI Integration**
- Third supported AI CLI (Claude Code / Codex / Gemini)
- Dual-file configuration support (`.env` + `settings.json`)
- Complete MCP server management
- Presets: Google Official (OAuth) / PackyCode / Custom
### System & Platform
- **Claude Skills Management System**
- Auto-scan skills from GitHub repositories (3 pre-configured curated repos)
- One-click install/uninstall to `~/.claude/skills/`
- Custom repository support + subdirectory scanning
- Complete lifecycle management (discover/install/update)
- **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/zh-TW/en/ja)
- **Prompts Management System**
- Multi-preset system prompt management (unlimited presets, quick switching)
- Cross-app support (Claude: `CLAUDE.md` / Codex: `AGENTS.md` / Gemini: `GEMINI.md`)
- Markdown editor (CodeMirror 6 + real-time preview)
- Smart backfill protection, preserves manual modifications
## FAQ
- **MCP v3.7.0 Unified Architecture**
- Single panel manages MCP servers across three applications
- New SSE (Server-Sent Events) transport type
- Smart JSON parser + Codex TOML format auto-correction
- Unified import/export + bidirectional sync
<details>
<summary><strong>Which AI tools does CC Switch support?</strong></summary>
- **Deep Link Protocol**
- `ccswitch://` protocol registration (all platforms)
- One-click import provider configs via shared links
- Security validation + lifecycle integration
CC Switch supports eight tools: **Claude Code**, **Claude Desktop**, **Codex**, **Gemini CLI**, **Grok Build**, **OpenCode**, **OpenClaw**, and **Hermes**. Each tool has dedicated provider presets and configuration management.
- **Environment Variable Conflict Detection**
- Auto-detect cross-app configuration conflicts (Claude/Codex/Gemini/MCP)
- Visual conflict indicators + resolution suggestions
- Override warnings + backup before changes
</details>
**Core Capabilities**
<details>
<summary><strong>Do I need to restart the terminal after switching providers?</strong></summary>
- **Provider Management**: One-click switching between Claude Code, Codex, and Gemini API configurations
- **Speed Testing**: Measure API endpoint latency with visual quality indicators
- **Import/Export**: Backup and restore configs with auto-rotation (keep 10 most recent)
- **i18n Support**: Complete Chinese/English localization (UI, errors, tray)
- **Claude Plugin Sync**: One-click apply/restore Claude plugin configurations
For most tools, yes — restart your terminal or the CLI tool for changes to take effect. The exception is **Claude Code**, which currently supports hot-switching of provider data without a restart.
**v3.6 Highlights**
</details>
- Provider duplication & drag-and-drop sorting
- Multi-endpoint management & custom config directory (cloud sync ready)
- Granular model configuration (4-tier: Haiku/Sonnet/Opus/Custom)
- WSL environment support with auto-sync on directory change
- 100% hooks test coverage & complete architecture refactoring
<details>
<summary><strong>My plugin configuration disappeared after switching providers — what happened?</strong></summary>
**System Features**
CC Switch provides a "Shared Config Snippet" feature to pass common data (beyond API keys and endpoints) between providers. Go to "Edit Provider" → "Shared Config Panel" → click "Extract from Current Provider" to save all common data. When creating a new provider, check "Write Shared Config" (enabled by default) to include plugin data in the new provider. All your configuration items are preserved in the default provider imported when you first launched the app.
- System tray with quick switching
- Single instance daemon
- Built-in auto-updater
- Atomic writes with rollback protection
</details>
<details>
<summary><strong>macOS installation</strong></summary>
CC Switch for macOS is code-signed and notarized by Apple. You can download and install it directly — no extra steps needed. We recommend using the `.dmg` installer.
</details>
<details>
<summary><strong>Why can't I delete the currently active provider?</strong></summary>
CC Switch follows a "minimal intrusion" design principle — even if you uninstall the app, your CLI tools will continue to work normally. The system always keeps one active configuration, because deleting all configurations would make the corresponding CLI tool unusable. If you rarely use a specific CLI tool, you can hide it in Settings. To switch back to official login, see the next question.
</details>
<details>
<summary><strong>How do I switch back to official login?</strong></summary>
Add an official provider from the preset list. After switching to it, run the Log out / Log in flow, and then you can freely switch between the official provider and third-party providers. Codex supports switching between different official providers, making it easy to switch between multiple Plus or Team accounts.
</details>
<details>
<summary><strong>Where is my data stored?</strong></summary>
- **Database**: `~/.cc-switch/cc-switch.db` (SQLite — providers, MCP, prompts, skills)
- **Local settings**: `~/.cc-switch/settings.json` (device-level UI preferences)
- **Backups**: `~/.cc-switch/backups/` (auto-rotated, keeps 10 most recent)
- **Skills**: `~/.cc-switch/skills/` (symlinked to corresponding apps by default)
- **Skill Backups**: `~/.cc-switch/skill-backups/` (created automatically before uninstall, keeps 20 most recent)
</details>
<details>
<summary><strong>Linux (Wayland + NVIDIA): clicks don't register and the window black-screens on resize</strong></summary>
The AppImage forces `GDK_BACKEND=x11` (XWayland) to avoid a historical native-Wayland crash. On newer Wayland + NVIDIA setups this can leave the web content area unclickable (the title-bar buttons still work) and black-screen on resize. Launch with the opt-in escape hatch to switch back to native Wayland:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
If you launch from a desktop icon, add it to the `.desktop` `Exec=` line (e.g. `env CC_SWITCH_GDK_BACKEND=wayland /path/to/AppImage`) or set it in your session environment. The variable is generic: on tiling Wayland compositors (sway/Hyprland) where clicks don't register, try `CC_SWITCH_GDK_BACKEND=x11` instead. Leaving it unset keeps the default behavior.
</details>
## Documentation
For detailed guides on every feature, check out the **[User Manual](docs/user-manual/en/README.md)** — covering provider management, MCP/Prompts/Skills, proxy & failover, and more.
## Quick Start
### Basic Usage
1. **Add Provider**: Click "Add Provider" → Choose a preset or create custom configuration
2. **Switch Provider**:
- Main UI: Select provider → Click "Enable"
- System Tray: Click provider name directly (instant effect)
3. **Takes Effect**: Restart your terminal or the corresponding CLI tool to apply changes (Claude Code does not require a restart)
4. **Back to Official**: Add an "Official Login" preset, restart the CLI tool, then follow its login/OAuth flow
### MCP, Prompts, Skills & Sessions
- **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 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.
## Download & Installation
### System Requirements
- **Windows**: Windows 10 and above
- **macOS**: macOS 10.15 (Catalina) and above
- **macOS**: macOS 12 (Monterey) and above
- **Linux**: Ubuntu 22.04+ / Debian 11+ / Fedora 34+ and other mainstream distributions
### Windows Users
@@ -164,7 +358,6 @@ Download the latest `CC-Switch-v{version}-Windows.msi` installer or `CC-Switch-v
**Method 1: Install via Homebrew (Recommended)**
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
@@ -176,11 +369,11 @@ brew upgrade --cask cc-switch
**Method 2: Manual Download**
Download `CC-Switch-v{version}-macOS.zip` from the [Releases](../../releases) page and extract to use.
Download `CC-Switch-v{version}-macOS.dmg` (recommended) or `.zip` from the [Releases](../../releases) page.
> **Note**: Since the author doesn't have an Apple Developer account, you may see an "unidentified developer" warning on first launch. Please close it first, then go to "System Settings" → "Privacy & Security" → click "Open Anyway", and you'll be able to open it normally afterwards.
> **Note**: CC Switch for macOS is code-signed and notarized by Apple. You can install and open it directly.
### ArchLinux 用户
### Arch Linux Users
**Install via paru (Recommended)**
@@ -190,91 +383,16 @@ paru -S cc-switch-bin
### Linux Users
Download the latest `CC-Switch-v{version}-Linux.deb` package or `CC-Switch-v{version}-Linux.AppImage` from the [Releases](../../releases) page.
Download the latest Linux build from the [Releases](../../releases) page:
## Quick Start
- `CC-Switch-v{version}-Linux.deb` (Debian/Ubuntu)
- `CC-Switch-v{version}-Linux.rpm` (Fedora/RHEL/openSUSE)
- `CC-Switch-v{version}-Linux.AppImage` (Universal)
### Basic Usage
> **Flatpak**: Not included in official releases. You can build it yourself from the `.deb` — see [`flatpak/README.md`](flatpak/README.md) for instructions.
1. **Add Provider**: Click "Add Provider" → Choose preset or create custom configuration
2. **Switch Provider**:
- Main UI: Select provider → Click "Enable"
- System Tray: Click provider name directly (instant effect)
3. **Takes Effect**: Restart your terminal or Claude Code / Codex / Gemini clients to apply changes
4. **Back to Official**: Select the "Official Login" preset (Claude/Codex) or "Google Official" preset (Gemini), restart the corresponding client, then follow its login/OAuth flow
### MCP Management
- **Location**: Click "MCP" button in top-right corner
- **Add Server**:
- Use built-in templates (mcp-fetch, mcp-filesystem, etc.)
- Support stdio / http / sse transport types
- Configure independent MCP servers for different apps
- **Enable/Disable**: Toggle switches to control which servers sync to live config
- **Sync**: Enabled servers auto-sync to each app's live files
- **Import/Export**: Import existing MCP servers from Claude/Codex/Gemini config files
### Skills Management (v3.7.0 New)
- **Location**: Click "Skills" button in top-right corner
- **Discover Skills**:
- Auto-scan pre-configured GitHub repositories (Anthropic official, ComposioHQ, community, etc.)
- Add custom repositories (supports subdirectory scanning)
- **Install Skills**: Click "Install" to one-click install to `~/.claude/skills/`
- **Uninstall Skills**: Click "Uninstall" to safely remove and clean up state
- **Manage Repositories**: Add/remove custom GitHub repositories
### Prompts Management (v3.7.0 New)
- **Location**: Click "Prompts" button in top-right corner
- **Create Presets**:
- Create unlimited system prompt presets
- Use Markdown editor to write prompts (syntax highlighting + real-time preview)
- **Switch Presets**: Select preset → Click "Activate" to apply immediately
- **Sync Mechanism**:
- Claude: `~/.claude/CLAUDE.md`
- Codex: `~/.codex/AGENTS.md`
- Gemini: `~/.gemini/GEMINI.md`
- **Protection Mechanism**: Auto-save current prompt content before switching, preserves manual modifications
### Configuration Files
**Claude Code**
- Live config: `~/.claude/settings.json` (or `claude.json`)
- API key field: `env.ANTHROPIC_AUTH_TOKEN` or `env.ANTHROPIC_API_KEY`
- MCP servers: `~/.claude.json``mcpServers`
**Codex**
- Live config: `~/.codex/auth.json` (required) + `config.toml` (optional)
- API key field: `OPENAI_API_KEY` in `auth.json`
- MCP servers: `~/.codex/config.toml``[mcp_servers]` tables
**Gemini**
- Live config: `~/.gemini/.env` (API key) + `~/.gemini/settings.json` (auth mode)
- API key field: `GEMINI_API_KEY` or `GOOGLE_GEMINI_API_KEY` in `.env`
- Environment variables: Support `GOOGLE_GEMINI_BASE_URL`, `GEMINI_MODEL`, etc.
- MCP servers: `~/.gemini/settings.json``mcpServers`
- Tray quick switch: Each provider switch rewrites `~/.gemini/.env`, no need to restart Gemini CLI
**CC Switch Storage (v3.8.0 New Architecture)**
- Database (SSOT): `~/.cc-switch/cc-switch.db` (SQLite, stores providers, MCP, Prompts, Skills)
- Local settings: `~/.cc-switch/settings.json` (device-level settings)
- Backups: `~/.cc-switch/backups/` (auto-rotate, keep 10)
### Cloud Sync Setup
1. Go to Settings → "Custom Configuration Directory"
2. Choose your cloud sync folder (Dropbox, OneDrive, iCloud, etc.)
3. Restart app to apply
4. Repeat on other devices to enable cross-device sync
> **Note**: First launch auto-imports existing Claude/Codex configs as default provider.
## Architecture Overview
<details>
<summary><strong>Architecture Overview</strong></summary>
### Design Principles
@@ -309,16 +427,15 @@ Download the latest `CC-Switch-v{version}-Linux.deb` package or `CC-Switch-v{ver
- **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 supported session sources
- **ConfigService**: Config import/export, backup rotation
- **SpeedtestService**: API endpoint latency measurement
**v3.6 Refactoring**
</details>
- Backend: 5-phase refactoring (error handling → command split → tests → services → concurrency)
- Frontend: 4-stage refactoring (test infra → hooks → components → cleanup)
- Testing: 100% hooks coverage + integration tests (vitest + MSW)
## Development
<details>
<summary><strong>Development Guide</strong></summary>
### Environment Requirements
@@ -379,7 +496,7 @@ cargo test test_name
cargo test --features test-hooks
```
### Testing Guide (v3.6 New)
### Testing Guide
**Frontend Testing**:
@@ -387,18 +504,6 @@ cargo test --features test-hooks
- Uses **MSW (Mock Service Worker)** to mock Tauri API calls
- Uses **@testing-library/react** for component testing
**Test Coverage**:
- Hooks unit tests (100% coverage)
- `useProviderActions` - Provider operations
- `useMcpActions` - MCP management
- `useSettings` series - Settings management
- `useImportExport` - Import/export
- Integration tests
- App main application flow
- SettingsDialog complete interaction
- MCP panel functionality
**Running Tests**:
```bash
@@ -412,49 +517,56 @@ pnpm test:unit:watch
pnpm test:unit --coverage
```
## Tech Stack
### Tech Stack
**Frontend**: React 18 · TypeScript · Vite · TailwindCSS 4 · TanStack Query v5 · react-i18next · react-hook-form · zod · shadcn/ui · @dnd-kit
**Frontend**: React 18 · TypeScript · Vite · TailwindCSS 3.4 · TanStack Query v5 · react-i18next · react-hook-form · zod · shadcn/ui · @dnd-kit
**Backend**: Tauri 2.8 · Rust · serde · tokio · thiserror · tauri-plugin-updater/process/dialog/store/log
**Testing**: vitest · MSW · @testing-library/react
## Project Structure
</details>
<details>
<summary><strong>Project Structure</strong></summary>
```
├── src/ # Frontend (React + TypeScript)
│ ├── components/ # UI components (providers/settings/mcp/ui)
│ ├── hooks/ # Custom hooks (business logic)
├── src/ # Frontend (React + TypeScript)
│ ├── components/
│ ├── providers/ # Provider management
│ │ ├── mcp/ # MCP panel
│ │ ├── prompts/ # Prompts management
│ │ ├── skills/ # Skills management
│ │ ├── sessions/ # Session Manager
│ │ ├── proxy/ # Proxy mode panel
│ │ ├── openclaw/ # OpenClaw config panels
│ │ ├── settings/ # Settings (Terminal/Backup/About)
│ │ ├── deeplink/ # Deep Link import
│ │ ├── env/ # Environment variable management
│ │ ├── universal/ # Cross-app configuration
│ │ ├── usage/ # Usage statistics
│ │ └── ui/ # shadcn/ui component library
│ ├── hooks/ # Custom hooks (business logic)
│ ├── lib/
│ │ ├── api/ # Tauri API wrapper (type-safe)
│ │ └── query/ # TanStack Query config
│ ├── i18n/locales/ # Translations (zh/en)
│ ├── config/ # Presets (providers/mcp)
│ └── types/ # TypeScript definitions
├── src-tauri/ # Backend (Rust)
│ │ ├── api/ # Tauri API wrapper (type-safe)
│ │ └── query/ # TanStack Query config
│ ├── locales/ # Translations (zh/zh-TW/en/ja)
│ ├── config/ # Presets (providers/mcp)
│ └── types/ # TypeScript definitions
├── src-tauri/ # Backend (Rust)
│ └── src/
│ ├── commands/ # Tauri command layer (by domain)
│ ├── services/ # Business logic layer
│ ├── app_config.rs # Config data models
│ ├── provider.rs # Provider domain models
│ ├── mcp.rs # MCP sync & validation
── lib.rs # App entry & tray menu
├── tests/ # Frontend tests
│ ├── hooks/ # Unit tests
│ └── components/ # Integration tests
└── assets/ # Screenshots & partner resources
│ ├── commands/ # Tauri command layer (by domain)
│ ├── services/ # Business logic layer
│ ├── database/ # SQLite DAO layer
│ ├── proxy/ # Proxy module
│ ├── session_manager/ # Session management
── deeplink/ # Deep Link handling
│ └── mcp/ # MCP sync module
├── tests/ # Frontend tests
└── assets/ # Screenshots & partner resources
```
## Changelog
See [CHANGELOG.md](CHANGELOG.md) for version update details.
## Legacy Electron Version
[Releases](../../releases) retains v2.0.3 legacy Electron version
If you need legacy Electron code, you can pull the electron-legacy branch
</details>
## Contributing
@@ -465,7 +577,8 @@ Before submitting PRs, please ensure:
- Pass type check: `pnpm typecheck`
- Pass format check: `pnpm format:check`
- Pass unit tests: `pnpm test:unit`
- 💡 For new features, please open an issue for discussion before submitting a PR
For new features, please open an issue for discussion before submitting a PR. PRs for features that are not a good fit for the project may be closed.
## Star History
+589
View File
@@ -0,0 +1,589 @@
<div align="center">
# CC Switch
### Der All-in-One-Manager für Claude Code, Claude Desktop, Codex, Gemini CLI, Grok Build, 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)
[![Built with Tauri](https://img.shields.io/badge/built%20with-Tauri%202-orange.svg)](https://tauri.app/)
[![Downloads](https://img.shields.io/github/downloads/farion1231/cc-switch/total)](https://github.com/farion1231/cc-switch/releases/latest)
<a href="https://trendshift.io/repositories/15372" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15372" alt="farion1231%2Fcc-switch | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
<a href="https://www.star-history.com/#farion1231/cc-switch&Date"><picture><source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=farion1231/cc-switch&theme=dark" /><img alt="Star History Rank" src="https://api.star-history.com/badge?repo=farion1231/cc-switch" width="196" height="55" /></picture></a>
### 🌐 Die einzige offizielle Website: **[ccswitch.io](https://ccswitch.io)**
[English](README.md) | [中文](README_ZH.md) | [日本語](README_JA.md) | Deutsch | [Changelog](CHANGELOG.md)
</div>
## ❤️Sponsoren
> [Möchten Sie hier erscheinen?](mailto:farion1231@gmail.com)
<details open>
<summary>Zum Einklappen klicken</summary>
[![Kimi K2.7 Code](https://gcdn.moonshot.cn/growth-cdn/sponsor/kimi-en.png)](https://platform.kimi.ai?aff=cc-switch)
Kimi K3 ist das bislang leistungsstärkste Modell von Moonshot AI und das weltweit erste offene Modell der 3T-Klasse. Mit 2,8 Billionen Parametern, nativen visuellen Fähigkeiten und einem Kontextfenster von 1 Million Token liefert K3 Spitzenleistung bei langfristigen Programmieraufgaben, Wissensarbeit und Reasoning. Mit CC Switch lässt sich Kimi in den verschiedensten Agenten-Tools bequem konfigurieren und umschalten. **[Hier klicken, um Kimi zu nutzen](https://platform.kimi.ai?aff=cc-switch)**
Hauptsächlich mit Programmierung beschäftigt? Probieren Sie das **[Kimi-Code-Abo](https://www.kimi.com/code/?aff=cc-switch)** aus!
---
<table>
<tr>
<td width="180"><a href="https://www.packyapi.com/register?aff=cc-switch"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></a></td>
<td>Danke an PackyCode für die Unterstützung dieses Projekts! PackyCode ist ein zuverlässiger und effizienter API-Relay-Anbieter, der Relay-Dienste für Claude Code, Codex, Gemini und mehr bereitstellt. PackyCode bietet Sonderrabatte für Nutzer unserer Software: Registrieren Sie sich über <a href="https://www.packyapi.com/register?aff=cc-switch">diesen Link</a> und geben Sie beim ersten Aufladen den Gutscheincode „cc-switch" ein, um 10 % Rabatt zu erhalten.</td>
</tr>
<tr>
<td width="180"><a href="https://zetaapi.ai/go/u117"><img src="assets/partners/logos/zetaapi-banner.png" alt="ZetaAPI" width="150"></a></td>
<td>Danke an ZetaAPI für die Unterstützung dieses Projekts! ZetaAPI legt den Fokus auf echte Modelltreue — keine verwässerten Antworten, keine Qualitätsminderung — und Preise von nur 35 % der offiziellen Tarife. Die Plattform mischt keinen Traffic, ersetzt Modelle nicht heimlich durch minderwertige Alternativen und nutzt kein gefälschtes Modell-Routing. Sie unterstützt Claude Code, Codex, Gemini, ChatGPT und weitere gängige KI-Modelle und hilft Nutzern, die API-Kosten deutlich zu senken und gleichzeitig eine zuverlässige Modellqualität zu gewährleisten. Gleichzeitig bietet ZetaAPI eine SLA-gestützte Stabilität auf Unternehmensniveau, Standard-API-Kompatibilität, einen API-Key für mehrere Modelle, schnelle Integration und nutzungsbasierte Abrechnung — geeignet für KI-Produkte, Coding-Agents, interne Unternehmenstools, Kundenservice-Systeme, Content-Erstellung und Automatisierungs-Workflows. Falls bei einem Modell nachgewiesen wird, dass es nicht der angegebenen Qualität entspricht, sichert ZetaAPI dies mit einer 10-fachen Entschädigungsgarantie ab und bietet Nutzern ein stabileres, transparenteres und vertrauenswürdigeres Erlebnis. Registrieren Sie sich über <a href="https://zetaapi.ai/go/u117">diesen Link</a> und verwenden Sie bei Ihrer ersten Aufladung den Promo-Code CC-SWITCH, um als CC-Switch-Nutzer einen exklusiven Rabatt von 10 % auf Ihre erste Aufladung zu erhalten!</td>
</tr>
<tr>
<td width="180"><a href="https://apinebula.com/VjM74M"><img src="assets/partners/logos/apinebula_banner.png" alt="APINebula" width="150"></a></td>
<td>Danke an APINEBULA für die Unterstützung dieses Projekts! APINEBULA ist eine Enterprise-KI-Aggregationsplattform unter Galaxy Video Bureau und nutzt umfangreiche Plattformressourcen, um Entwicklern, Teams und Unternehmen stabilen und kosteneffizienten Zugang zu APIs großer Sprachmodelle zu bieten. Die Plattform bündelt führende vollwertige Modelle wie Claude, GPT und Gemini. Über eine einzige API erhalten Sie Zugriff auf weltweit führende KI-Modelle, mit Preisen ab 10 % des Originalpreises. APINEBULA ist für KI-Programmierung, Agent-Entwicklung und Integration in Geschäftssysteme ausgelegt und unterstützt enterprise-grade hohe Parallelität, formale Verträge, Firmenüberweisungen und Rechnungsstellung. APINEBULA bietet Nutzern dieser Software besondere Rabatte: Registrieren Sie sich über <a href="https://apinebula.com/VjM74M">diesen Link</a> und geben Sie beim ersten Aufladen den Aktionscode <strong>"ccswitch"</strong> ein, um <strong>10 % Rabatt</strong> zu erhalten.</td>
</tr>
<tr>
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=9915W3"><img src="assets/partners/logos/aicodemirror.jpg" alt="AICodeMirror" width="150"></a></td>
<td>Danke an AICodeMirror für die Unterstützung dieses Projekts! AICodeMirror stellt offizielle, hochstabile Relay-Dienste für Claude Code / Codex / Gemini CLI bereit, mit unternehmensgerechter Nebenläufigkeit, schneller Rechnungsstellung und rund um die Uhr verfügbarem dediziertem technischem Support.
Offizielle Kanäle von Claude Code / Codex / Gemini zu 38 % / 2 % / 9 % des Originalpreises, mit zusätzlichen Rabatten beim Aufladen! AICodeMirror bietet besondere Vorteile für CC-Switch-Nutzer: Registrieren Sie sich über <a href="https://www.aicodemirror.com/register?invitecode=9915W3">diesen Link</a> und erhalten Sie 20 % Rabatt auf Ihre erste Aufladung; Unternehmenskunden erhalten bis zu 25 % Rabatt!</td>
</tr>
<tr>
<td width="180"><a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/"><img src="assets/partners/logos/pateway.png" alt="PatewayAI" width="150"></a></td>
<td>Danke an PatewayAI für die Unterstützung dieses Projekts! PatewayAI ist ein API-Relay-Anbieter für anspruchsvolle KI-Entwickler, der sich auf das direkte Relayen offizieller hochwertiger Modell-APIs konzentriert. Er bietet die komplette Claude-Reihe und die Codex-Serie, zu 100 % aus offiziellen Kanälen bezogen — keine Verwässerung, keine Fälschungen, Überprüfung ausdrücklich erwünscht. Die Abrechnung ist transparent, und jede Rechnung auf Token-Ebene lässt sich Zeile für Zeile prüfen.
Er unterstützt zudem unternehmensgerechte Nebenläufigkeit und stellt Unternehmenskunden eine dedizierte Verwaltungsplattform bereit — formelle Verträge und Rechnungsstellung sind verfügbar; Kontaktdaten finden Sie auf der offiziellen Website.
Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">diesen Link</a> und erhalten Sie ein Testguthaben von 3 $. Aufladungen sind ab 60 % des Originalpreises möglich, mit einem beidseitigen Empfehlungsbonus von bis zu 150 $!</td>
</tr>
<tr>
<td width="180"><a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL"><img src="assets/partners/logos/fenno-banner.png" alt="Fenno.ai" width="150"></a></td>
<td>Danke an Fenno.ai für die Unterstützung dieses Projekts! Fenno.ai ist ein stabiler und effizienter API-Relay-Dienstleister, der sich derzeit hauptsächlich auf Codex-Relay konzentriert. Er ist mit den OpenAI- und Anthropic-Protokollen kompatibel und lässt sich flexibel mit Codex, Claude Code, OpenCode und anderen gängigen Coding-Tools nutzen. Er unterstützt zuverlässig Workloads auf Unternehmensniveau von Hunderten Milliarden Tokens pro Tag und bietet B2B-Abrechnung sowie Rechnungsstellung für Unternehmen im In- und Ausland. Fenno.ai bietet einen exklusiven Vorteil für CC-Switch-Nutzer: Abonnieren Sie über <a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL">diesen Link</a> den unschlagbaren ¥9,9-Coding-Plan im Wert von $150 Guthaben und erhalten Sie bis zu 20% Empfehlungsprämien — je mehr Einladungen, desto mehr Belohnung!</td>
</tr>
<tr>
<td width="180"><a href="https://runapi.co/register?aff=iOKB"><img src="assets/partners/logos/runapi.jpg" alt="RunAPI" width="150"></a></td>
<td>Danke an RunAPI für die Unterstützung dieses Projekts! RunAPI ist ein leistungsstarkes und zuverlässiges KI-Modell-API-Gateway — ein API-Schlüssel gibt Ihnen Zugriff auf mehr als 150 gängige Modelle, darunter OpenAI, Claude, Gemini, DeepSeek und Grok, zu Preisen ab 10 % des offiziellen Tarifs und mit ausgezeichneter Stabilität. Es arbeitet nahtlos mit Claude Code, OpenClaw und weiteren Werkzeugen zusammen. Exklusiver Vorteil für CC-Switch-Nutzer: Registrieren Sie sich über <a href="https://runapi.co/register?aff=iOKB">diesen Link</a> und erhalten Sie 10 % Rabatt auf Ihre erste Aufladung!</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>
<tr>
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
<td>Danke an Shengsuanyun für die Unterstützung dieses Projekts! Shengsuanyun ist eine Superfabrik für KI-native Teams — eine Plattform zur parallelen Ausführung von KI-Aufgaben in industrieller Qualität. Ihr Modellmarktplatz bündelt die Fähigkeiten von Claude, ChatGPT, Gemini und weiteren in- und ausländischen LLM- und Multimedia-Modellen mit Direktbezug. Absolut kein Reverse Engineering und keine Verwässerung — die plattformweite Modell-SLA-Verfügbarkeit erreicht 99,7 %, und die <a href="https://watch.shengsuanyun.com/status/shengsuanyun">Monitoring-Dashboards</a> zeigen durchgehend grün an. Es bietet außerdem unternehmensgerechte, anpassbare Gateways für fein abgestufte Kosten- und Berechtigungsverwaltung im Team, intelligentes Routing, Sicherheitsschutz und BYOK-Hosting (Bring Your Own Key). Die Plattform rechnet nach Nutzung sowie über einen Token-Plan (in Kürze verfügbar) ab, und Rechnungsstellung ist möglich. Registrieren Sie sich über <a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">diesen Link</a> als Neukunde und erhalten Sie ein Guthaben von ¥10 sowie 10 % Bonus auf Ihre erste Aufladung.</td>
</tr>
<tr>
<td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>Danke an AIGoCode für die Unterstützung dieses Projekts! AIGoCode ist eine All-in-One-Plattform, die Claude Code, Codex und die neuesten Gemini-Modelle integriert und Ihnen stabile, effiziente und äußerst kostengünstige KI-Coding-Dienste bietet. Die Plattform stellt flexible Abonnementpläne bereit, birgt kein Risiko einer Kontosperrung, ermöglicht Direktzugriff ohne VPN und reagiert blitzschnell. AIGoCode hat ein besonderes Angebot für CC-Switch-Nutzer vorbereitet: Wenn Sie sich über <a href="https://aigocode.com/invite/CC-SWITCH">diesen Link</a> registrieren, erhalten Sie bei Ihrer ersten Aufladung zusätzliche 10 % Bonusguthaben!</td>
</tr>
<tr>
<td width="180"><a href="https://subrouter.ai/register?aff=l3ri"><img src="assets/partners/logos/subrouter-banner.png" alt="SubRouter" width="150"></a></td>
<td>Danke an SubRouter für die Unterstützung dieses Projekts! SubRouter ist ein Marktplatz und eine intelligente Routing-Plattform für Betreiber von KI-Diensten. Händler können eigene Betriebsseiten starten, Pakete veröffentlichen sowie Nutzer, Modelle und Preise verwalten, während Nutzer im Marktplatz Dienste entdecken und über eine einzige einheitliche API zuverlässige und effiziente Modellaufrufe nutzen. Registrieren Sie sich über <a href="https://subrouter.ai/register?aff=l3ri">diesen Link</a>!</td>
</tr>
<tr>
<td width="180"><a href="https://apikey.fun/register?aff=CCSwitch"><img src="assets/partners/logos/apikey_banner.png" alt="APIKEY.FUN" width="150"></a></td>
<td>Danke an APIKEY.FUN für die Unterstützung dieses Projekts! APIKEY.FUN ist eine professionelle KI-Relay-Plattform auf Enterprise-Niveau, die Unternehmen und einzelnen Entwicklern stabilen, effizienten und kostengünstigen Zugriff auf KI-Modell-APIs bietet. Die Plattform unterstützt beliebte Mainstream-Modelle wie Claude, OpenAI und Gemini, mit Preisen ab 7 % der offiziellen Tarife. Wer sich über den <a href="https://apikey.fun/register?aff=CCSwitch">exklusiven Link</a> dieses Projekts registriert, kann ein exklusives Angebot von bis zu <strong>dauerhaft 5 % Rabatt auf Aufladungen</strong> erhalten.</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>Dieses Projekt wird von <a href="https://console.claudeapi.com/register?aff=pCLD">Claude API</a> gesponsert. Direkter Claude-API-Zugriff — verbinden Sie Claude Code und Agent-Apps in 3 Minuten. Neukunden können ein kostenloses Testguthaben einlösen. Betrieben mit offiziellen Anthropic-API-Schlüsseln + offiziellen AWS-Bedrock-Kanälen. Kein Reverse Engineering, keine Modellverschlechterung. Volle Unterstützung der Modellreihe Opus / Sonnet / Haiku, mit erhaltenen offiziellen Fähigkeiten einschließlich Tool Use, 1M-Kontextfenster und mehr. Entwickelt für Claude-Code-Power-User, Agent-Ingenieure und technische Unternehmensteams. Rechnungsstellung und dedizierter Team-Support verfügbar. Klicken Sie <a href="https://console.claudeapi.com/register?aff=pCLD">hier</a>, um sich zu registrieren!</td>
</tr>
<tr>
<td width="180"><a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
<td>Vielen Dank an <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai</a> für die Unterstützung dieses Projekts! code0.ai ist eine für Entwickler entwickelte AI-Coding-Service-Plattform, die Claude Code, Codex, Gemini und weitere gängige AI-Coding-Funktionen unterstützt. Sie hilft einzelnen Entwicklern und Teams, AI-Agents stabiler und effizienter für Programmierung, Debugging, Refactoring und Automatisierungs-Workflows zu nutzen. ccswitch-Nutzer können über die <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai-Website</a> den Kundensupport kontaktieren, um Testguthaben zu erhalten und einen zuverlässigen AI-Coding-Service zu erleben.</td>
</tr>
<tr>
<td width="180"><a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory"><img src="assets/partners/logos/TeamoRouter-banner.png" alt="TeamoRouter" width="150"></a></td>
<td>Danke an TeamoRouter für die Unterstützung dieses Projekts! TeamoRouter ist ein Agentic-LLM-Gateway in Enterprise-Qualität, das für Entwickler, KI-Teams und Unternehmen entwickelt wurde. Ganz ohne Abonnement können Sie über eine einzige einheitliche API auf Claude Code, Codex, Gemini CLI, OpenAI Codex und weitere beliebte KI-Agenten zugreifen — bei API-Preisen mit Rabatten von bis zu 90 %.
Anders als typische API-Relay-Dienste bündelt TeamoRouter Hunderte offizieller Modellanbieter und vertrauenswürdiger Infrastrukturpartner, darunter OpenAI, Anthropic, Vertex, Azure und AWS Bedrock. Jeder Anbieter wird auf 100%ige Kompatibilität mit dem Agent-Protokoll, Cache-Performance und Nachverfolgbarkeit von Anfragen geprüft und liefert so stabile Qualität statt reverse-engineerter oder verwässerter Endpunkte. Die Plattform bietet nahezu offizielle TTFT, 99,6 % SLA, Durchsatz in Unternehmensgröße von bis zu 5.000 QPM und branchenführende Cache-Trefferquoten, die die Token-Kosten für langlaufende Agent-Workflows drastisch senken.
TeamoRouter bietet außerdem Enterprise-Funktionen wie zentrale Abrechnung, Team-Verwaltung, BYOK, intelligentes Routing, Nutzungsanalysen, dynamische Anbieter-Optimierung und dedizierten Support. Für ein noch einfacheres Erlebnis können Sie mit Teamo Desktop Claude Code, Codex, Gemini CLI und weitere beliebte KI-Agenten per Ein-Klick-Einrichtung nutzen — ohne Verwaltung von API-Schlüsseln oder manuelle Gateway-Konfiguration. Registrieren Sie sich als neuer Nutzer über <a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory">diesen Link</a> und erhalten Sie 10 % Rabatt auf Ihre erste Aufladung.</td>
</tr>
<tr>
<td width="180"><a href="https://www.newapi.ai/"><img src="assets/partners/logos/newapi-banner.png" alt="new-api" width="150"></a></td>
<td>Vielen Dank an das Open-Source-KI-Infrastrukturprojekt <a href="https://www.newapi.ai/">new-api</a> für die tatkräftige Unterstützung dieses Projekts! new-api ist ein Open-Source-KI-Infrastrukturprojekt von QuantumNous und eines der nach Aktivität und Verbreitung führenden Projekte für den einheitlichen Zugang zu und die Verteilung von LLMs, das sich darauf konzentriert, Entwicklern, Teams und Unternehmen beim Aufbau verwaltbarer und skalierbarer KI-Serviceplattformen zu geringeren Kosten zu helfen. Als ein ebenfalls im Open-Source-Ökosystem verwurzeltes Projekt möchte new-api durch Sponsoring die kontinuierliche Weiterentwicklung weiterer herausragender Open-Source-Projekte unterstützen. 🌟 Unterstützen Sie new-api mit einem Star: <a href="https://github.com/QuantumNous/new-api">https://github.com/QuantumNous/new-api</a>. Website: <a href="https://www.newapi.ai/">https://www.newapi.ai/</a>.</td>
</tr>
<tr>
<td width="180"><a href="https://claudecn.ai/register?aff=HEL9"><img src="assets/partners/logos/claudecn.jpg" alt="ClaudeCN" width="150"></a></td>
<td>Danke an ClaudeCN für die Unterstützung dieses Projekts! ClaudeCN ist eine unternehmensgerechte KI-Gateway-Plattform, die von einem eingetragenen Unternehmen betrieben wird. Sie bietet hochverfügbaren kommerziellen API-Zugriff auf beliebte Modelle wie Claude, GPT und DeepSeek und ist auf formelle Unternehmensbeschaffungsprozesse ausgerichtet — Banküberweisungen von Firmen, unterzeichnete Verträge und volle Compliance. Registrieren Sie sich über <a href="https://claudecn.ai/register?aff=HEL9">diesen Link</a>!</td>
</tr>
<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/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
</tr>
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/YflgU2Ve"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>Danke an SiliconFlow für die Unterstützung dieses Projekts! SiliconFlow ist eine leistungsstarke KI-Infrastruktur- und Modell-API-Plattform, die schnellen und zuverlässigen Zugriff auf Sprach-, Audio-, Bild- und Videomodelle an einem Ort bietet. Mit nutzungsbasierter Abrechnung, breiter Unterstützung multimodaler Modelle, Hochgeschwindigkeitsinferenz und unternehmensgerechter Stabilität hilft SiliconFlow Entwicklern und Teams, KI-Anwendungen effizienter zu erstellen und zu skalieren. Registrieren Sie sich über <a href="https://cloud.siliconflow.cn/i/YflgU2Ve">diesen Link</a> und schließen Sie die Identitätsverifizierung ab, um ein Bonusguthaben von ¥16 zu erhalten, das für alle Modelle der Plattform nutzbar ist. SiliconFlow ist zudem nun mit OpenClaw kompatibel, sodass Nutzer einen SiliconFlow-API-Schlüssel verbinden und große KI-Modelle kostenlos aufrufen können.</td>
</tr>
<tr>
<td width="180"><a href="https://nekocode.ai?aff=CCSWITCH"><img src="assets/partners/logos/nekocode-banner.png" alt="NekoCode" width="150"></a></td>
<td>Vielen Dank an <a href="https://nekocode.ai?aff=CCSWITCH">NekoCode</a> für die Unterstützung dieses Projekts! NekoCode bietet Entwicklern einen stabilen, effizienten und zuverlässigen API-Relay-Dienst für Claude, Codex und weitere KI-Modelle. Mit transparenter Preisgestaltung und flexibler nutzungsbasierter Abrechnung bietet es einen einfachen und kostengünstigen Zugang zu KI-Modellen. CC-Switch-Nutzer erhalten einen exklusiven Rabatt von 10 %: Registrieren Sie sich über <a href="https://nekocode.ai?aff=CCSWITCH">diesen Link</a> und geben Sie beim Aufladen den Gutscheincode <code>cc-switch</code> ein, um 10 % Rabatt auf Ihre Aufladung zu erhalten!</td>
</tr>
<tr>
<td width="180"><a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch"><img src="assets/partners/logos/atlascloud_banner.png" alt="Atlas Cloud" width="150"></a></td>
<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.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch"><img src="assets/partners/logos/ucloud.png" alt="Compshare" width="150"></a></td>
<td>Danke an Compshare für die Unterstützung dieses Projekts! Compshare ist die KI-Cloud-Plattform von UCloud, die mit nur einem Schlüssel stabile und umfassende in- und ausländische Modell-APIs bereitstellt. Sie bietet kostengünstige Coding-Plan-Pakete für inländische Modelle mit monatlicher und nutzungsbasierter Abrechnung sowie stabile, offiziell gerelayte ausländische Modelle. Unterstützt Claude Code, Codex und API-Zugriff. Unternehmensgerechte hohe Nebenläufigkeit, technischer Support rund um die Uhr und Self-Service-Rechnungsstellung. Wer sich über <a href="https://www.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch">diesen Link</a> registriert, erhält ein kostenloses Plattform-Testguthaben von 5 CNY!</td>
</tr>
<tr>
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.svg" 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://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
<td>Danke an SSSAiCode für die Unterstützung dieses Projekts! SSSAiCode ist ein stabiler und zuverlässiger API-Relay-Dienst, der sich der Bereitstellung stabiler, zuverlässiger und erschwinglicher Claude- und Codex-Modelldienste widmet, mit schneller Rechnungsstellung am selben Tag. SSSAiCode bietet ein besonderes Angebot für CC-Switch-Nutzer: Registrieren Sie sich über <a href="https://www.sssaicode.com/register?ref=DCP0SM">diesen Link</a> und erhalten Sie bei jeder Aufladung 10 $ zusätzliches Guthaben!</td>
</tr>
<tr>
<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>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://www.right.codes/register?aff=CCSWITCH"><img src="assets/partners/logos/rightcode.jpg" alt="RightCode" width="150"></a></td>
<td>Danke an Right Code für die Unterstützung dieses Projekts! Right Code stellt zuverlässig Routing-Dienste für Modelle wie Claude Code, Codex und Gemini bereit, wahlweise mit nutzungsbasierter Abrechnung oder monatlichem Abonnement. Rechnungen sind beim Aufladen verfügbar, und Unternehmens- sowie Teamkunden erhalten dedizierten Einzelsupport. Right Code bietet außerdem einen exklusiven Rabatt für CC-Switch-Nutzer: Registrieren Sie sich über <a href="https://www.right.codes/register?aff=CCSWITCH">diesen Link</a> und erhalten Sie bei jeder Aufladung nutzungsbasiertes Guthaben in Höhe von 5 % des gezahlten Betrags.</td>
</tr>
<tr>
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
<td>Danke an ETok.ai für die Unterstützung dieses Projekts! ETok.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://etok.ai">hier</a>, um sich zu registrieren!</td>
</tr>
<tr>
<td width="180"><a href="https://cubence.com/signup?code=CCSWITCH&source=ccs"><img src="assets/partners/logos/cubence.png" alt="Cubence" width="150"></a></td>
<td>Danke an Cubence für die Unterstützung dieses Projekts! Cubence ist ein zuverlässiger und effizienter API-Relay-Anbieter, der Relay-Dienste für Claude Code, Codex, Gemini und mehr mit flexiblen Abrechnungsoptionen einschließlich nutzungsbasierter und monatlicher Pläne bereitstellt. Cubence bietet Sonderrabatte für CC-Switch-Nutzer: Registrieren Sie sich über <a href="https://cubence.com/signup?code=CCSWITCH&source=ccs">diesen Link</a> und geben Sie beim Aufladen den Gutscheincode „CCSWITCH" ein, um bei jeder Aufladung 10 % Rabatt zu erhalten!</td>
</tr>
<tr>
<td width="180"><a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch"><img src="assets/partners/logos/crazyrouter.png" alt="Crazyrouter" width="150"></a></td>
<td>Danke an Crazyrouter für die Unterstützung dieses Projekts! Crazyrouter ist eine leistungsstarke KI-API-Aggregationsplattform — ein API-Schlüssel für mehr als 300 Modelle, darunter Claude Code, Codex, Gemini CLI und weitere. Alle Modelle zu 55 % des offiziellen Preises, mit automatischem Failover, intelligentem Routing und unbegrenzter Nebenläufigkeit. Crazyrouter bietet ein exklusives Angebot für CC-Switch-Nutzer: Registrieren Sie sich über <a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch">diesen Link</a> und kontaktieren Sie den Kundensupport, um <strong>2 $ Gratisguthaben</strong> zu erhalten; geben Sie zusätzlich bei Ihrer ersten Aufladung den Gutscheincode `CCSWITCH` ein, um <strong>30 % Bonusguthaben</strong> zu bekommen! </td>
</tr>
<tr>
<td width="180"><a href="https://www.dmxapi.cn/register?aff=bUHu"><img src="assets/partners/logos/dmx-en.jpg" alt="DMXAPI" width="150"></a></td>
<td>Danke an DMXAPI für die Unterstützung dieses Projekts! DMXAPI stellt mehr als 200 Unternehmenskunden globale Großmodell-API-Dienste bereit. Ein API-Schlüssel für alle Modelle weltweit. Zu den Funktionen gehören: sofortige Rechnungsstellung, unbegrenzte Nebenläufigkeit, ab 0,15 $, technischer Support rund um die Uhr. GPT/Claude/Gemini durchgehend zu 32 % Rabatt, inländische Modelle 2050 % Rabatt, exklusive Claude-Code-Modelle zu 66 % Rabatt! <a href="https://www.dmxapi.cn/register?aff=bUHu">Hier registrieren</a></td>
</tr>
</table>
</details>
## Warum CC Switch?
Modernes KI-gestütztes Programmieren stützt sich auf Werkzeuge wie Claude Code, Claude Desktop, Codex, Gemini CLI, Grok Build, 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 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, acht Werkzeuge** — Verwalten Sie Claude Code, Claude Desktop, Codex, Gemini CLI, Grok Build, 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 für Claude, Codex, Gemini, Grok Build, 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
- **Integrierte Hilfsprogramme** — Enthält diverse Hilfsprogramme für die Login-Bestätigung beim Erststart, das Umgehen von Signaturen, die Synchronisierung von Plugin-Erweiterungen und mehr
## Screenshots
| Hauptoberfläche | Anbieter hinzufügen |
| :-----------------------------------------------: | :--------------------------------------------: |
| ![Hauptoberfläche](assets/screenshots/main-en.png) | ![Anbieter hinzufügen](assets/screenshots/add-en.png) |
## Funktionen
[Vollständiges Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.16.1-en.md)
### Anbieterverwaltung
- **8 unterstützte Werkzeuge, 50+ Presets** — Claude Code, Claude Desktop, Codex, Gemini CLI, Grok Build, 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
- **Lokaler Proxy mit Hot-Switching** — Formatkonvertierung, automatisches Failover, Circuit Breaker, Anbieter-Health-Monitoring und Request-Rectifier
- **Übernahme auf App-Ebene** — Claude, Codex, Gemini oder Grok Build unabhängig über den Proxy leiten, bis hinunter auf einzelne Anbieter
### MCP, Prompts & Skills
- **Einheitliches MCP-Panel** — Verwalten Sie MCP-Server für Claude, Codex, Gemini, Grok Build, 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
### Nutzungs- & Kostenverfolgung
- **Nutzungs-Dashboard** — Verfolgen Sie Ausgaben, Anfragen und Token mit Trenddiagrammen, detaillierten Anfrageprotokollen und eigener Preisgestaltung pro Modell
### Session Manager & Workspace
- 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/zh-TW/en/ja)
## FAQ
<details>
<summary><strong>Welche KI-Werkzeuge unterstützt CC Switch?</strong></summary>
CC Switch unterstützt acht Werkzeuge: **Claude Code**, **Claude Desktop**, **Codex**, **Gemini CLI**, **Grok Build**, **OpenCode**, **OpenClaw** und **Hermes**. Jedes Werkzeug verfügt über dedizierte Anbieter-Presets und Konfigurationsverwaltung.
</details>
<details>
<summary><strong>Muss ich das Terminal nach einem Anbieterwechsel neu starten?</strong></summary>
Bei den meisten Werkzeugen ja — starten Sie Ihr Terminal oder das CLI-Werkzeug neu, damit die Änderungen wirksam werden. Die Ausnahme ist **Claude Code**, das derzeit das Hot-Switching von Anbieterdaten ohne Neustart unterstützt.
</details>
<details>
<summary><strong>Meine Plugin-Konfiguration ist nach einem Anbieterwechsel verschwunden — was ist passiert?</strong></summary>
CC Switch bietet eine Funktion „Gemeinsames Konfigurations-Snippet", um gemeinsame Daten (über API-Schlüssel und Endpunkte hinaus) zwischen Anbietern weiterzugeben. Gehen Sie zu „Anbieter bearbeiten" → „Panel für gemeinsame Konfiguration" → klicken Sie auf „Aus aktuellem Anbieter extrahieren", um alle gemeinsamen Daten zu speichern. Aktivieren Sie beim Anlegen eines neuen Anbieters die Option „Gemeinsame Konfiguration schreiben" (standardmäßig aktiviert), um die Plugin-Daten in den neuen Anbieter aufzunehmen. Alle Ihre Konfigurationspunkte bleiben im Standardanbieter erhalten, der beim ersten Start der App importiert wurde.
</details>
<details>
<summary><strong>Installation unter macOS</strong></summary>
CC Switch für macOS ist von Apple code-signiert und notarisiert. Sie können es direkt herunterladen und installieren — es sind keine zusätzlichen Schritte erforderlich. Wir empfehlen die Verwendung des `.dmg`-Installationsprogramms.
</details>
<details>
<summary><strong>Warum kann ich den aktuell aktiven Anbieter nicht löschen?</strong></summary>
CC Switch folgt dem Designprinzip der „minimalen Eingriffstiefe" — selbst wenn Sie die App deinstallieren, funktionieren Ihre CLI-Werkzeuge weiterhin normal. Das System behält immer eine aktive Konfiguration bei, da das Löschen aller Konfigurationen das entsprechende CLI-Werkzeug unbrauchbar machen würde. Wenn Sie ein bestimmtes CLI-Werkzeug selten verwenden, können Sie es in den Einstellungen ausblenden. Wie Sie zurück zum offiziellen Login wechseln, erfahren Sie in der nächsten Frage.
</details>
<details>
<summary><strong>Wie wechsle ich zurück zum offiziellen Login?</strong></summary>
Fügen Sie einen offiziellen Anbieter aus der Preset-Liste hinzu. Führen Sie nach dem Wechsel den Abmelde-/Anmelde-Vorgang aus; anschließend können Sie frei zwischen dem offiziellen Anbieter und Drittanbietern wechseln. Codex unterstützt den Wechsel zwischen verschiedenen offiziellen Anbietern, was das Umschalten zwischen mehreren Plus- oder Team-Konten erleichtert.
</details>
<details>
<summary><strong>Wo werden meine Daten gespeichert?</strong></summary>
- **Datenbank**: `~/.cc-switch/cc-switch.db` (SQLite — Anbieter, MCP, Prompts, Skills)
- **Lokale Einstellungen**: `~/.cc-switch/settings.json` (gerätebezogene UI-Einstellungen)
- **Backups**: `~/.cc-switch/backups/` (automatisch rotiert, behält die 10 neuesten)
- **Skills**: `~/.cc-switch/skills/` (standardmäßig per Symlink mit den entsprechenden Apps verbunden)
- **Skill-Backups**: `~/.cc-switch/skill-backups/` (vor der Deinstallation automatisch erstellt, behält die 20 neuesten)
</details>
<details>
<summary><strong>Linux (Wayland + NVIDIA): Klicks im Webinhalt reagieren nicht, schwarzer Bildschirm beim Größenändern</strong></summary>
Das AppImage erzwingt `GDK_BACKEND=x11` (XWayland), um einen historischen nativen Wayland-Absturz zu vermeiden. Auf neueren Wayland-+-NVIDIA-Systemen kann das dazu führen, dass der Webinhalt nicht anklickbar ist (die Titelleisten-Schaltflächen funktionieren weiterhin) und das Fenster beim Größenändern schwarz wird. Starten Sie mit dem optionalen Notausgang, um zu nativem Wayland zu wechseln:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
Wenn Sie über ein Desktop-Symbol starten, fügen Sie es der `Exec=`-Zeile der `.desktop`-Datei hinzu (z. B. `env CC_SWITCH_GDK_BACKEND=wayland /pfad/zum/AppImage`) oder setzen Sie es in Ihrer Sitzungsumgebung. Die Variable ist generisch: Auf Tiling-Wayland-Compositors (sway/Hyprland), bei denen Klicks nicht reagieren, versuchen Sie umgekehrt `CC_SWITCH_GDK_BACKEND=x11`. Bleibt sie ungesetzt, bleibt das Standardverhalten erhalten.
</details>
## Dokumentation
Ausführliche Anleitungen zu jeder Funktion finden Sie im **[Benutzerhandbuch](docs/user-manual/en/README.md)** — es deckt Anbieterverwaltung, MCP/Prompts/Skills, Proxy & Failover und mehr ab.
## Schnellstart
### Grundlegende Verwendung
1. **Anbieter hinzufügen**: Klicken Sie auf „Add Provider" → Wählen Sie ein Preset oder erstellen Sie eine eigene Konfiguration
2. **Anbieter wechseln**:
- Hauptoberfläche: Anbieter auswählen → auf „Enable" klicken
- System-Tray: Anbietername direkt anklicken (sofort wirksam)
3. **Wirksam werden**: Starten Sie Ihr Terminal oder das entsprechende CLI-Werkzeug neu, um die Änderungen anzuwenden (Claude Code erfordert keinen Neustart)
4. **Zurück zum Offiziellen**: Fügen Sie ein „Official Login"-Preset hinzu, starten Sie das CLI-Werkzeug neu und folgen Sie dann seinem Login-/OAuth-Vorgang
### MCP, Prompts, Skills & Sessions
- **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 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.
## Download & Installation
### Systemanforderungen
- **Windows**: Windows 10 und höher
- **macOS**: macOS 12 (Monterey) und höher
- **Linux**: Ubuntu 22.04+ / Debian 11+ / Fedora 34+ und andere gängige Distributionen
### Windows-Nutzer
Laden Sie das neueste Installationsprogramm `CC-Switch-v{version}-Windows.msi` oder die portable Version `CC-Switch-v{version}-Windows-Portable.zip` von der Seite [Releases](../../releases) herunter.
### macOS-Nutzer
**Methode 1: Installation über Homebrew (empfohlen)**
```bash
brew install --cask cc-switch
```
Aktualisieren:
```bash
brew upgrade --cask cc-switch
```
**Methode 2: Manueller Download**
Laden Sie `CC-Switch-v{version}-macOS.dmg` (empfohlen) oder `.zip` von der Seite [Releases](../../releases) herunter.
> **Hinweis**: CC Switch für macOS ist von Apple code-signiert und notarisiert. Sie können es direkt installieren und öffnen.
### Arch-Linux-Nutzer
**Installation über paru (empfohlen)**
```bash
paru -S cc-switch-bin
```
### Linux-Nutzer
Laden Sie den neuesten Linux-Build von der Seite [Releases](../../releases) herunter:
- `CC-Switch-v{version}-Linux.deb` (Debian/Ubuntu)
- `CC-Switch-v{version}-Linux.rpm` (Fedora/RHEL/openSUSE)
- `CC-Switch-v{version}-Linux.AppImage` (universell)
> **Flatpak**: Nicht in den offiziellen Releases enthalten. Sie können es selbst aus dem `.deb` bauen — eine Anleitung finden Sie unter [`flatpak/README.md`](flatpak/README.md).
<details>
<summary><strong>Architekturüberblick</strong></summary>
### Designprinzipien
```
┌─────────────────────────────────────────────────────────────┐
│ Frontend (React + TS) │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Components │ │ Hooks │ │ TanStack Query │ │
│ │ (UI) │──│ (Bus. Logic) │──│ (Cache/Sync) │ │
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
└────────────────────────┬────────────────────────────────────┘
│ Tauri IPC
┌────────────────────────▼────────────────────────────────────┐
│ Backend (Tauri + Rust) │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Commands │ │ Services │ │ Models/Config │ │
│ │ (API Layer) │──│ (Bus. Layer) │──│ (Data) │ │
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
**Kern-Designmuster**
- **SSOT** (Single Source of Truth): Alle Daten werden in `~/.cc-switch/cc-switch.db` (SQLite) gespeichert
- **Zweischichtiger Speicher**: SQLite für synchronisierbare Daten, JSON für gerätebezogene Einstellungen
- **Bidirektionale Synchronisierung**: Schreiben in Live-Dateien beim Umschalten, Backfill aus den Live-Dateien beim Bearbeiten des aktiven Anbieters
- **Atomare Schreibvorgänge**: Das Muster aus temporärer Datei + Umbenennen verhindert die Beschädigung von Konfigurationen
- **Nebenläufigkeitssicher**: Eine durch Mutex geschützte Datenbankverbindung vermeidet Race Conditions
- **Geschichtete Architektur**: Klare Trennung (Commands → Services → DAO → Database)
**Schlüsselkomponenten**
- **ProviderService**: Anbieter-CRUD, Umschaltung, Backfill, Sortierung
- **McpService**: Verwaltung von MCP-Servern, Import/Export, Synchronisierung von Live-Dateien
- **ProxyService**: Lokaler Proxy-Modus mit Hot-Switching und Formatkonvertierung
- **SessionManager**: Durchsuchen des Gesprächsverlaufs über alle unterstützten Apps hinweg
- **ConfigService**: Konfigurations-Import/-Export, Backup-Rotation
- **SpeedtestService**: Messung der Latenz von API-Endpunkten
</details>
<details>
<summary><strong>Entwicklungsleitfaden</strong></summary>
### Umgebungsanforderungen
- Node.js 18+
- pnpm 8+
- Rust 1.85+
- Tauri CLI 2.8+
### Entwicklungsbefehle
```bash
# Abhängigkeiten installieren
pnpm install
# Entwicklungsmodus (Hot Reload)
pnpm dev
# Typprüfung
pnpm typecheck
# Code formatieren
pnpm format
# Codeformatierung prüfen
pnpm format:check
# Frontend-Unit-Tests ausführen
pnpm test:unit
# Tests im Watch-Modus ausführen (für die Entwicklung empfohlen)
pnpm test:unit:watch
# Anwendung bauen
pnpm build
# Debug-Version bauen
pnpm tauri build --debug
```
### Entwicklung des Rust-Backends
```bash
cd src-tauri
# Rust-Code formatieren
cargo fmt
# Clippy-Prüfungen ausführen
cargo clippy
# Backend-Tests ausführen
cargo test
# Bestimmte Tests ausführen
cargo test test_name
# Tests mit dem Feature test-hooks ausführen
cargo test --features test-hooks
```
### Testleitfaden
**Frontend-Tests**:
- Verwendet **vitest** als Test-Framework
- Verwendet **MSW (Mock Service Worker)**, um Tauri-API-Aufrufe zu mocken
- Verwendet **@testing-library/react** für Komponententests
**Tests ausführen**:
```bash
# Alle Tests ausführen
pnpm test:unit
# Watch-Modus (automatische erneute Ausführung)
pnpm test:unit:watch
# Mit Coverage-Bericht
pnpm test:unit --coverage
```
### Tech-Stack
**Frontend**: React 18 · TypeScript · Vite · TailwindCSS 3.4 · TanStack Query v5 · react-i18next · react-hook-form · zod · shadcn/ui · @dnd-kit
**Backend**: Tauri 2.8 · Rust · serde · tokio · thiserror · tauri-plugin-updater/process/dialog/store/log
**Testing**: vitest · MSW · @testing-library/react
</details>
<details>
<summary><strong>Projektstruktur</strong></summary>
```
├── src/ # Frontend (React + TypeScript)
│ ├── components/
│ │ ├── providers/ # Anbieterverwaltung
│ │ ├── mcp/ # MCP-Panel
│ │ ├── prompts/ # Prompts-Verwaltung
│ │ ├── skills/ # Skills-Verwaltung
│ │ ├── sessions/ # Session Manager
│ │ ├── proxy/ # Proxy-Modus-Panel
│ │ ├── openclaw/ # OpenClaw-Konfigurationspanels
│ │ ├── settings/ # Einstellungen (Terminal/Backup/About)
│ │ ├── deeplink/ # Deep-Link-Import
│ │ ├── env/ # Verwaltung von Umgebungsvariablen
│ │ ├── universal/ # App-übergreifende Konfiguration
│ │ ├── usage/ # Nutzungsstatistik
│ │ └── ui/ # shadcn/ui-Komponentenbibliothek
│ ├── hooks/ # Eigene Hooks (Geschäftslogik)
│ ├── lib/
│ │ ├── api/ # Tauri-API-Wrapper (typsicher)
│ │ └── query/ # TanStack-Query-Konfiguration
│ ├── locales/ # Übersetzungen (zh/zh-TW/en/ja)
│ ├── config/ # Presets (providers/mcp)
│ └── types/ # TypeScript-Definitionen
├── src-tauri/ # Backend (Rust)
│ └── src/
│ ├── commands/ # Tauri-Befehlsschicht (nach Domäne)
│ ├── services/ # Geschäftslogikschicht
│ ├── database/ # SQLite-DAO-Schicht
│ ├── proxy/ # Proxy-Modul
│ ├── session_manager/ # Sitzungsverwaltung
│ ├── deeplink/ # Deep-Link-Verarbeitung
│ └── mcp/ # MCP-Synchronisierungsmodul
├── tests/ # Frontend-Tests
└── assets/ # Screenshots & Partnerressourcen
```
</details>
## Mitwirken
Issues und Vorschläge sind willkommen!
Bitte stellen Sie vor dem Einreichen von PRs Folgendes sicher:
- Typprüfung besteht: `pnpm typecheck`
- Formatprüfung besteht: `pnpm format:check`
- Unit-Tests bestehen: `pnpm test:unit`
Eröffnen Sie für neue Funktionen bitte vor dem Einreichen eines PR ein Issue zur Diskussion. PRs für Funktionen, die nicht gut zum Projekt passen, können geschlossen werden.
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=farion1231/cc-switch&type=Date)](https://www.star-history.com/#farion1231/cc-switch&Date)
## Lizenz
MIT © Jason Young
+339 -226
View File
@@ -1,48 +1,212 @@
<div align="center">
# Claude Code / Codex / Gemini CLI オールインワン・アシスタント
# CC Switch
[![Version](https://img.shields.io/badge/version-3.8.2-blue.svg)](https://github.com/farion1231/cc-switch/releases)
[![Trending](https://img.shields.io/badge/🔥_TypeScript_Trending-Daily%20%7C%20Weekly%20%7C%20Monthly-ff6b6b.svg)](https://github.com/trending/typescript)
### Claude Code、Claude Desktop、Codex、Gemini CLI、Grok Build、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)
[![Built with Tauri](https://img.shields.io/badge/built%20with-Tauri%202-orange.svg)](https://tauri.app/)
[![Downloads](https://img.shields.io/endpoint?url=https://api.pinstudios.net/api/badges/downloads/farion1231/cc-switch/total)](https://github.com/farion1231/cc-switch/releases/latest)
[![Downloads](https://img.shields.io/github/downloads/farion1231/cc-switch/total)](https://github.com/farion1231/cc-switch/releases/latest)
<a href="https://trendshift.io/repositories/15372" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15372" alt="farion1231%2Fcc-switch | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
<a href="https://www.star-history.com/#farion1231/cc-switch&Date"><picture><source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=farion1231/cc-switch&theme=dark" /><img alt="Star History Rank" src="https://api.star-history.com/badge?repo=farion1231/cc-switch" width="196" height="55" /></picture></a>
[English](README.md) | [中文](README_ZH.md) | 日本語 | [Changelog](CHANGELOG.md) | [v3.8.0 リリースノート](docs/release-note-v3.8.0-en.md)
### 🌐 唯一の公式サイト:**[ccswitch.io](https://ccswitch.io)**
**プロバイダスイッチャーから AI CLI 一体型管理プラットフォームへ**
Claude Code・Codex・Gemini CLI のプロバイダ設定、MCP サーバー、Skills 拡張、システムプロンプトを統合管理。
[English](README.md) | [中文](README_ZH.md) | 日本語 | [Deutsch](README_DE.md) | [Changelog](CHANGELOG.md)
</div>
## ❤️スポンサー
![Zhipu GLM](assets/partners/banners/glm-en.jpg)
> [ここに掲載しませんか?](mailto:farion1231@gmail.com)
本プロジェクトは Z.ai の GLM CODING PLAN による支援を受けています。
<details open>
<summary>クリックで折りたたむ</summary>
GLM CODING PLAN は AI コーディング向けのサブスクリプションで、月額わずか 3 ドルから。Claude Code、Cline、Roo Code など 10 以上の人気 AI コーディングツールでフラッグシップモデル GLM-4.6 を利用でき、速く安定した開発体験を提供します。
[![Kimi K2.7 Code](https://gcdn.moonshot.cn/growth-cdn/sponsor/kimi-en.png)](https://platform.kimi.ai?aff=cc-switch)
[このリンク](https://z.ai/subscribe?ic=8JVLJQFSKB) から申し込むと 10% オフになります!
Kimi K3 は Moonshot AI がこれまでに開発した中で最も高性能なモデルであり、世界初のオープンソース 3T クラスモデルです。2.8 兆パラメータ、ネイティブな視覚能力、100 万トークンのコンテキストウィンドウを備え、長期にわたるコーディング、ナレッジワーク、推論タスクにおいてフロンティア級の性能を発揮します。CC Switch を使えば、さまざまなエージェントツールで Kimi を手軽に設定・切り替えできます。**[ここをクリックして Kimi を使い始める](https://platform.kimi.ai?aff=cc-switch)**
コーディング作業がメインですか?**[Kimi Code サブスクリプション](https://www.kimi.com/code/?aff=cc-switch)** をぜひお試しください!
---
<table>
<tr>
<td width="180"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></td>
<td width="180"><a href="https://www.packyapi.com/register?aff=cc-switch"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></a></td>
<td>PackyCode のご支援に感謝します!PackyCode は Claude Code、Codex、Gemini などのリレーサービスを提供する信頼性の高い API 中継プラットフォームです。本ソフト利用者向けに特別割引があります:<a href="https://www.packyapi.com/register?aff=cc-switch">このリンク</a>で登録し、チャージ時に「cc-switch」クーポンを入力すると 10% オフになります。</td>
</tr>
<tr>
<td width="180"><img src="assets/partners/logos/sds-en.png" alt="ShanDianShuo" width="150"></td>
<td>ShanDianShuo のご支援に感謝します!ShanDianShuo はローカルファーストの音声入力ツールで、ミリ秒遅延・データは端末から外に出ず・キーボード入力の 4 倍の速度・AI 自動補正・プライバシー優先で完全無料。Claude Code と組み合わせればコーディング効率が倍増します。<a href="https://www.shandianshuo.cn">Mac/Win 版を無料ダウンロード</a></td>
<td width="180"><a href="https://zetaapi.ai/go/u117"><img src="assets/partners/logos/zetaapi-banner.png" alt="ZetaAPI" width="150"></a></td>
<td>本プロジェクトをご支援いただいている ZetaAPI に感謝します!ZetaAPI は、モデル品質の忠実性、水増しなし、性能劣化なし、公式価格の 35% から利用できる低価格を主な特徴としています。プラットフォームはトラフィックの混在、低品質モデルへの密かな切り替え、虚偽のモデルルーティングを行わず、Claude Code、Codex、Gemini、ChatGPT などの主要 AI モデルに対応しており、モデル品質を維持しながら API 利用コストを大幅に削減できます。同時に、ZetaAPI はエンタープライズ級の SLA 安定性保証、標準 API 互換、1つの Key による複数モデル接続、迅速な導入、従量課金などの機能を提供し、AI プロダクト、コード生成、企業内ツール、カスタマーサポート、コンテンツ生成、自動化ワークフローなどの用途に適しています。万が一、モデル品質が表記内容と一致しないことが確認された場合、ZetaAPI は 10 倍補償保証を提供し、ユーザーがより安定して、透明性高く、安心して利用できる環境を実現します。<a href="https://zetaapi.ai/go/u117">こちらのリンク</a>から登録し、初回チャージ時にプロモコード CC-SWITCH を使用すると、CC Switch ユーザー限定の初回チャージ 10% オフ特典をご利用いただけます!</td>
</tr>
<tr>
<td width="180"><a href="https://apinebula.com/VjM74M"><img src="assets/partners/logos/apinebula_banner.png" alt="APINebula" width="150"></a></td>
<td>本プロジェクトは「APINEBULA」のスポンサーシップにより運営されています!APINEBULA は、「銀河録像局」傘下のエンタープライズ向け AI 統合プラットフォームです。大手の豊富なリソースを背景に、開発者、チーム、そして企業ユーザーの皆様へ、安定性とコストパフォーマンスに優れた大規模言語モデル(LLM)の API 連携サービスを提供しています。Claude、GPT、Gemini をはじめとする世界中の主要なフルスペック(満血)モデルを 1 つの API に集約。世界トップクラスの AI モデルを、<strong>最大 90% OFF(元の価格の 1 割〜)</strong>という圧倒的な低価格でご利用いただけます。また、企業向けの高度な並行処理(高コンカレンシー)、正式な契約締結、法人口座振り込み、請求書・領収書発行など、ビジネス利用に必要なサポートも万全です。AI プログラミング、AI エージェント開発、業務システムへの統合など、様々なシーンに最適です。<a href="https://apinebula.com/VjM74M">こちらのリンク</a>から登録し、チャージ時にプロモコード <strong>「ccswitch」を入力すると、さらに 10% OFF</strong> の割引特典が適用されます!</td>
</tr>
<tr>
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=9915W3"><img src="assets/partners/logos/aicodemirror.jpg" alt="AICodeMirror" width="150"></a></td>
<td>AICodeMirror のご支援に感謝します!AICodeMirror は Claude Code / Codex / Gemini CLI の公式高安定リレーサービスを提供しており、エンタープライズ級の同時接続、迅速な請求書発行、24時間年中無休の専用テクニカルサポートを備えています。
Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% / 2% / 9%、チャージ時にはさらに割引!AICodeMirror は CC Switch ユーザー向けに特別特典を用意:<a href="https://www.aicodemirror.com/register?invitecode=9915W3">このリンク</a>から登録すると初回チャージ 20% オフ、法人のお客様は最大 25% オフ!</td>
</tr>
<tr>
<td width="180"><a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/"><img src="assets/partners/logos/pateway.png" alt="PatewayAI" width="150"></a></td>
<td>PatewayAI のご支援に感謝します!PatewayAI はヘビーな AI 開発者向けに、公式直結の高品質モデル API 中継サービスを専門に提供するプロバイダーです。Claude シリーズ全モデルおよび Codex シリーズに対応し、100% 公式ソースから直接提供。混ぜ物・水増しは一切なく、検証も歓迎します。課金は透明で、トークン単位の請求書を 1 件ずつ照合可能です。
エンタープライズ級の高同時接続にも対応し、法人のお客様には専用の管理プラットフォームを提供。正式契約および請求書発行に対応しており、詳細は公式サイトの連絡先よりお問い合わせください。
現在、<a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">このリンク</a>からご登録いただくと $3 のトライアルクレジットを進呈。チャージは最安で元価格の 60%、友達紹介は双方にボーナスが付与され、紹介報酬は最大 $150!</td>
</tr>
<tr>
<td width="180"><a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL"><img src="assets/partners/logos/fenno-banner.png" alt="Fenno.ai" width="150"></a></td>
<td>Fenno.ai のご支援に感謝します!Fenno.ai は安定かつ高効率な API 中継サービスプロバイダーで、現在は主に Codex の中継を提供しています。OpenAI および Anthropic プロトコルに対応し、Codex・Claude Code・OpenCode などの主要なコーディングツールから柔軟に利用できます。1 日あたり数千億トークンというエンタープライズ級の呼び出し需要を安定して支え、国内外の法人による B2B 決済・請求書発行に対応しています。Fenno.ai は CC Switch 利用者限定の特典を用意しています:<a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL">こちらのリンク</a>から 9.9 元(150 ドル相当)のお得な Coding Plan を購入でき、友達紹介で最大 20% の特典がもらえます。紹介すればするほどお得です!</td>
</tr>
<tr>
<td width="180"><a href="https://runapi.co/register?aff=iOKB"><img src="assets/partners/logos/runapi.jpg" alt="RunAPI" width="150"></a></td>
<td>本プロジェクトのスポンサーである RunAPI に感謝いたします!RunAPI は高効率で安定した AI モデル API ゲートウェイです。一つの API Key で、OpenAI、Claude、Gemini、DeepSeek、Grok など 150 種類以上の主要モデルにアクセス可能。料金は公式価格の最大 10%、安定性にも優れ、Claude Code や OpenClaw などのツールとシームレスに連携できます。CC Switch ユーザー限定特典:<a href="https://runapi.co/register?aff=iOKB">こちらのリンク</a>から登録し、初回チャージで 10% オフの割引をお楽しみいただけます!</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>
<tr>
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
<td>胜算雲(Shengsuanyun)のご支援に感謝します!胜算雲は AI ネイティブチーム向けのスーパーファクトリーであり、産業グレードの AI タスク並列実行プラットフォームです。モデルマーケットプレイスでは Claude、ChatGPT、Gemini をはじめとする国内外の LLM およびマルチメディアモデルの計算リソースを集約・直接提供。リバースエンジニアリングや品質低下は一切なく、プラットフォーム全体のモデル SLA 可用性は 99.7% に達し、<a href="https://watch.shengsuanyun.com/status/shengsuanyun">監視ダッシュボード</a>は常時グリーン表示です。さらにエンタープライズ向けカスタムゲートウェイを提供し、チームのきめ細かなコスト・権限管理、スマートルーティング、セキュリティ保護、BYOK(自社キー持ち込み)ホスティングを実現します。従量課金およびトークンプラン(近日公開)対応で、請求書発行にも対応。<a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">このリンク</a>から新規登録すると 10 元分のクレジットと初回チャージ 10% ボーナスが付与されます。</td>
</tr>
<tr>
<td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>本プロジェクトは AIGoCode のスポンサー提供でお届けしています。AIGoCode は、Claude Code・Codex・最新の Gemini モデルを統合したオールインワンのAIコーディングプラットフォームで、安定性・高速性・コストパフォーマンスに優れた開発サービスを提供します。柔軟なサブスクリプションプランを備え、レスポンスも非常に高速です。さらに、CC Switch ユーザー向けの特典として、<a href="https://aigocode.com/invite/CC-SWITCH">このリンク</a>から登録すると、初回チャージ時に10%分のボーナスクレジットが付与されます!</td>
</tr>
<tr>
<td width="180"><a href="https://subrouter.ai/register?aff=l3ri"><img src="assets/partners/logos/subrouter-banner.png" alt="SubRouter" width="150"></a></td>
<td>本プロジェクトをご支援いただいている SubRouter に感謝します!SubRouter は、AI サービス事業者向けのマーケットプレイス兼スマートルーティングプラットフォームです。事業者は独立した運営サイトを立ち上げ、プランを公開し、ユーザー・モデル・価格を管理でき、ユーザーはマーケットでサービスを見つけ、統一された API を通じて安定かつ高効率なモデル呼び出しを利用できます。<a href="https://subrouter.ai/register?aff=l3ri">こちらのリンク</a>から登録してください!</td>
</tr>
<tr>
<td width="180"><a href="https://apikey.fun/register?aff=CCSwitch"><img src="assets/partners/logos/apikey_banner.png" alt="APIKEY.FUN" width="150"></a></td>
<td>APIKEY.FUN のご支援に感謝します!APIKEY.FUN は、企業および個人開発者向けに安定・高効率・低コストな AI モデル API 接続サービスを提供する、プロフェッショナルなエンタープライズ級 AI リレープラットフォームです。Claude、OpenAI、Gemini などの主要人気モデルに対応し、料金は公式価格の 7% から利用できます。本プロジェクトの<a href="https://apikey.fun/register?aff=CCSwitch">専用リンク</a>から登録すると、最大で<strong>チャージ永久 5% オフ</strong>の特別優待も受けられます。</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 直結 — わずか 3 分で Claude Code や Agent アプリに接続可能。新規ユーザーにはテストクレジットを提供しています。Anthropic 公式キーおよび AWS Bedrock 公式チャネルに基づいており、リバースエンジニアリングや性能劣化はありません。Opus / Sonnet / Haiku の全モデルラインナップをサポートし、Tool Use や 1M コンテキストなどの公式機能をすべて保持しています。Claude Code ヘビーユーザー、Agent エンジニア、企業技術チームに最適です。請求書発行およびチーム対応が可能です。<a href="https://console.claudeapi.com/register?aff=pCLD">こちら</a>から登録してください!</td>
</tr>
<tr>
<td width="180"><a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
<td>本プロジェクトをご支援いただいている <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai</a> に感謝します!code0.ai は開発者向けの AI コーディングサービスプラットフォームで、Claude Code、Codex、Gemini などの主要な AI コーディング機能に対応しています。個人開発者やチームが、コーディング、デバッグ、リファクタリング、自動化ワークフローで AI Agent をより安定かつ効率的に活用できるよう支援します。ccswitch ユーザーは <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai 公式サイト</a> からカスタマーサポートに連絡することで、テストクレジットを受け取り、信頼性の高い AI コーディングサービスを体験できます。</td>
</tr>
<tr>
<td width="180"><a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory"><img src="assets/partners/logos/TeamoRouter-banner.png" alt="TeamoRouter" width="150"></a></td>
<td>このプロジェクトをご支援いただいている TeamoRouter に感謝します!TeamoRouter は、開発者、AI チーム、企業向けに構築されたエンタープライズグレードの Agentic LLM ゲートウェイです。サブスクリプション不要で、単一の統合 API を通じて Claude Code、Codex、Gemini CLI、OpenAI Codex、その他の人気 AI エージェントにアクセスでき、API 料金は最大 90% オフで利用できます。
一般的な API リレーサービスとは異なり、TeamoRouter は OpenAI、Anthropic、Vertex、Azure、AWS Bedrock など、数百の公式モデルプロバイダーと信頼できるインフラパートナーを集約しています。各プロバイダーは、Agent プロトコルとの 100% 互換性、キャッシュ性能、リクエストの追跡可能性について検証されており、リバースエンジニアリングされたものや品質が薄められたエンドポイントではなく、安定した品質を提供します。プラットフォームは公式に近い TTFT、99.6% の SLA、最大 5,000 QPM のエンタープライズ規模のスループット、そして業界トップクラスのキャッシュヒット率を提供し、長時間稼働するエージェントワークフローのトークンコストを大幅に削減します。
TeamoRouter は、集中請求、チーム管理、BYOK、スマートルーティング、利用状況分析、動的なプロバイダー最適化、専任サポートなどのエンタープライズ機能も提供しています。さらにシンプルな体験を求める場合は、Teamo Desktop を使うことで、Claude Code、Codex、Gemini CLI、その他の人気 AI エージェントをワンクリックで利用できます。API キー管理や手動のゲートウェイ設定は不要です。新規ユーザーとして<a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory">こちらのリンク</a>から登録すると、初回チャージが 10% オフになります。</td>
</tr>
<tr>
<td width="180"><a href="https://www.newapi.ai/"><img src="assets/partners/logos/newapi-banner.png" alt="new-api" width="150"></a></td>
<td>オープンソースの AI インフラプロジェクト <a href="https://www.newapi.ai/">new-api</a> による本プロジェクトへの多大なご支援に感謝します!new-api は QuantumNous(锟腾科技)が開発したオープンソースの AI インフラプロジェクトであり、活発さと利用規模の面でリードする LLM 統合アクセス・配信プロジェクトの一つで、開発者・チーム・企業がより低コストで管理・拡張可能な AI サービスプラットフォームを構築できるよう支援することに注力しています。同じくオープンソースエコシステムに根ざすプロジェクトとして、new-api はスポンサーシップを通じて、より多くの優れたオープンソースプロジェクトの継続的な発展を支援したいと考えています。🌟 new-api への Star で応援をお願いします:<a href="https://github.com/QuantumNous/new-api">https://github.com/QuantumNous/new-api</a>。公式サイト:<a href="https://www.newapi.ai/">https://www.newapi.ai/</a>。</td>
</tr>
<tr>
<td width="180"><a href="https://claudecn.ai/register?aff=HEL9"><img src="assets/partners/logos/claudecn.jpg" alt="ClaudeCN" width="150"></a></td>
<td>本プロジェクトのスポンサーである ClaudeCN に感謝いたします!ClaudeCN は、実体のある企業によって運営されるエンタープライズ向け AI ゲートウェイプラットフォームです。Claude、GPT、DeepSeek など主要モデルへの高可用な商用 API アクセスを提供し、企業の調達プロセスにも対応 — 法人振込や正式契約に対応し、コンプライアンス面でも安心してご利用いただけます。<a href="https://claudecn.ai/register?aff=HEL9">こちら</a>からご登録ください!</td>
</tr>
<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 トークンの無料推論クォータを進呈します。<a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
</tr>
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/YflgU2Ve"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/YflgU2Ve">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥16 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td>
</tr>
<tr>
<td width="180"><a href="https://nekocode.ai?aff=CCSWITCH"><img src="assets/partners/logos/nekocode-banner.png" alt="NekoCode" width="150"></a></td>
<td>本プロジェクトをご支援いただいている <a href="https://nekocode.ai?aff=CCSWITCH">NekoCode</a> に感謝します!NekoCode は、Claude や Codex などの AI モデルに対応した、安定性・効率性・信頼性に優れた API 中継サービスを提供しています。料金体系は明瞭で、柔軟な従量課金にも対応しています。CC Switch ユーザー限定の 10%オフ特典:<a href="https://nekocode.ai?aff=CCSWITCH">こちらのリンク</a> から登録し、チャージ時にクーポンコード <code>cc-switch</code> を入力すると、チャージが 10%オフになります!</td>
</tr>
<tr>
<td width="180"><a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch"><img src="assets/partners/logos/atlascloud_banner.png" alt="Atlas Cloud" width="150"></a></td>
<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.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch"><img src="assets/partners/logos/ucloud.png" alt="Compshare" width="150"></a></td>
<td>Compshare のご支援に感謝します!Compshare は UCloud 傘下の AI クラウドプラットフォームで、国内外の安定した包括的なモデル API を 1 つのキーだけで利用可能。月額・都度課金のコストパフォーマンスに優れた国内モデル Coding Plan パッケージを提供し、公式リレーによる安定した海外モデルも利用できます。Claude Code、Codex および API アクセスに対応。エンタープライズ級の高同時接続、24 時間年中無休のテクニカルサポート、セルフサービス請求書発行に対応。<a href="https://www.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch">こちらのリンク</a>から登録すると、無料で 5 元分のプラットフォーム体験クレジットがもらえます!</td>
</tr>
<tr>
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.svg" 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://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
<td>SSSAiCode のご支援に感謝します!SSSAiCode は安定性と信頼性に優れた API 中継サービスで、安定的で信頼性が高く、手頃な価格の Claude・Codex モデルサービスを提供しています。当日の迅速な請求書発行をサポート。CC Switch ユーザー向けの特別特典:<a href="https://www.sssaicode.com/register?ref=DCP0SM">こちらのリンク</a>から登録すると、毎回のチャージで $10 の追加ボーナスを受けられます!</td>
</tr>
<tr>
<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://www.right.codes/register?aff=CCSWITCH"><img src="assets/partners/logos/rightcode.jpg" alt="RightCode" width="150"></a></td>
<td>本プロジェクトへのご支援として、Right Code にご協賛いただき誠にありがとうございます。Right Code は、Claude Code、Codex、Gemini などのモデル向け中継サービスを安定して提供しており、従量課金と月額プランの 2 つの料金体系から選択できます。チャージ後に請求書の発行が可能で、法人・チームのお客様には専任担当による個別対応も行っています。さらに、CC Switch ユーザー向けの特別優待として、<a href="https://www.right.codes/register?aff=CCSWITCH">こちらのリンク</a>から登録すると、チャージのたびに実際の支払額の 5% 相当の従量課金クレジットが付与されます。</td>
</tr>
<tr>
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
<td>ETok.ai のご支援に感謝します!ETok.ai はワンストップ AI プログラミングツールサービスプラットフォームの構築に取り組んでいます。Claude Code のプロフェッショナルプランと技術コミュニティサービスを提供し、Google Gemini や OpenAI Codex にも対応しています。丁寧に設計されたプランと専門的な技術コミュニティを通じて、開発者に安定したサービス保証と継続的な技術サポートを提供し、AI アシストプログラミングを真の生産性ツールにします。<a href="https://etok.ai">こちら</a>から登録してください!</td>
</tr>
<tr>
<td width="180"><a href="https://cubence.com/signup?code=CCSWITCH&source=ccs"><img src="assets/partners/logos/cubence.png" alt="Cubence" width="150"></a></td>
<td>Cubence のご支援に感謝します!Cubence は Claude Code、Codex、Gemini などのリレーサービスを提供する信頼性の高い API 中継プラットフォームで、従量課金や月額プランなど柔軟な料金体系を提供しています。CC Switch ユーザー向けの特別割引:<a href="https://cubence.com/signup?code=CCSWITCH&source=ccs">このリンク</a>で登録し、チャージ時に「CCSWITCH」クーポンを入力すると、毎回 10% オフになります!</td>
</tr>
<tr>
<td width="180"><a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch"><img src="assets/partners/logos/crazyrouter.png" alt="Crazyrouter" width="150"></a></td>
<td>Crazyrouter のご支援に感謝します!Crazyrouter は高性能 AI API アグリゲーションプラットフォームです。1 つの API キーで Claude Code、Codex、Gemini CLI など 300 以上のモデルにアクセス可能。全モデルが公式価格の 55% で利用でき、自動フェイルオーバー、スマートルーティング、無制限同時接続に対応。CC Switch ユーザー向けの限定特典:<a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch">こちらのリンク</a>から登録後、カスタマーサポートまでご連絡いただくと <strong>$2 の無料クレジット</strong> を受け取れます。さらに初回チャージ時にプロモコード `CCSWITCH` を入力すると <strong>30% のボーナスクレジット</strong> が追加されます!</td>
</tr>
<tr>
<td width="180"><a href="https://www.dmxapi.cn/register?aff=bUHu"><img src="assets/partners/logos/dmx-en.jpg" alt="DMXAPI" width="150"></a></td>
<td>DMXAPI のご支援に感謝します!DMXAPI は 200 社以上の企業ユーザーにグローバル大規模モデル API サービスを提供しています。1 つの API キーで全世界のモデルにアクセス可能。即時請求書発行、同時接続数無制限、最低 $0.15 から、24 時間年中無休のテクニカルサポート。GPT/Claude/Gemini が全て 32% オフ、国内モデルは 20〜50% オフ、Claude Code 専用モデルは 66% オフ実施中!<a href="https://www.dmxapi.cn/register?aff=bUHu">登録はこちら</a></td>
</tr>
</table>
</details>
## CC Switch を選ぶ理由
最新の AI コーディングは Claude Code、Claude Desktop、Codex、Gemini CLI、Grok Build、OpenCode、OpenClaw、Hermes などのツールに依存していますが、各ツールの設定形式はバラバラです。API プロバイダを切り替えるたびに JSON、TOML、`.env` ファイルを手動で編集する必要があり、複数ツール間で MCP や Skills を統一的に管理する手段もありません。
**CC Switch** は、対応する AI ツールを 1 つのデスクトップアプリで一元管理できます。設定ファイルを手作業で編集する代わりに、ワンクリックでプロバイダをインポートし、瞬時に切り替えられるビジュアルインターフェースを提供します。50 以上の組み込みプリセット、統一 MCP・Skills 管理、システムトレイからの即時切り替え機能を搭載。すべてはアトミック書き込みによる信頼性の高い SQLite データベースに支えられており、設定の破損を防ぎます。
- **1 つのアプリで 8 つのツール** -- Claude Code、Claude Desktop、Codex、Gemini CLI、Grok Build、OpenCode、OpenClaw、Hermes を単一インターフェースで管理
- **手動編集は不要** -- AWS Bedrock、NVIDIA NIM、コミュニティリレーなど 50 以上のプロバイダプリセットを内蔵。選んで切り替えるだけ
- **統一 MCP・Skills 管理** -- 1 つのパネルで Claude、Codex、Gemini、Grok Build、OpenCode、Hermes の MCP サーバーと Skills を双方向同期で管理
- **システムトレイでクイック切り替え** -- トレイメニューから即座にプロバイダを切り替え。アプリを開く必要なし
- **クラウド同期** -- Dropbox、OneDrive、iCloud、または WebDAV サーバー経由でデバイス間のプロバイダデータを同期
- **クロスプラットフォーム** -- Tauri 2 で構築された Windows、macOS、Linux 対応のネイティブデスクトップアプリ
- **便利ツール内蔵** -- 初回起動時のログイン確認、署名バイパス、プラグイン拡張の同期など、さまざまなユーティリティを搭載
## スクリーンショット
| メイン画面 | プロバイダ追加 |
@@ -51,108 +215,138 @@ GLM CODING PLAN は AI コーディング向けのサブスクリプションで
## 特長
### 現在のバージョン:v3.8.2 | [完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-note-v3.8.0-en.md)
[完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-notes/v3.16.1-ja.md)
**v3.8.0 メジャーアップデート (2025-11-28)**
### プロバイダ管理
**永続化アーキテクチャ刷新 & 新 UI**
- **8 つの対応ツール、50 以上のプリセット** -- Claude Code、Claude Desktop、Codex、Gemini CLI、Grok Build、OpenCode、OpenClaw、Hermes。キーをコピーしてワンクリックでインポート
- **ユニバーサルプロバイダ** -- 1 つの設定を Claude Code、Codex、Gemini CLI に同期
- ワンクリック切り替え、システムトレイクイックアクセス、ドラッグ&ドロップ並び替え、インポート/エクスポート
- **SQLite + JSON 二層構造**
- JSON 単独保存から SQLite + JSON の二層構造へ移行
- 同期対象データ(プロバイダ、MCP、Prompts、Skills)は SQLite に保存
- デバイス固有データ(ウィンドウ状態、ローカルパス)は JSON に保存
- 将来のクラウド同期の土台を用意
- DB マイグレーション用にスキーマバージョンを管理
### プロキシ & フェイルオーバー
- **新しいユーザーインターフェース**
- レイアウトを全面再設計
- コンポーネントスタイルとアニメーションを統一
- 視覚的な階層を最適化
- ブラウザ互換性向上のため Tailwind CSS を v4 から v3.4 にダウングレード
- **ローカルプロキシのホットスイッチ** -- フォーマット変換、自動フェイルオーバー、サーキットブレーカー、プロバイダヘルスモニタリング、リクエストレクティファイア
- **アプリレベルのテイクオーバー** -- Claude、Codex、Gemini、Grok Build を個別にプロキシ経由でルーティング、プロバイダ単位で設定可能
- **日本語対応**
- UI が中国語/英語/日本語の 3 言語対応に
### MCP、Prompts & Skills
- **自動起動**
- 設定画面でワンクリック ON/OFF
- プラットフォームネイティブ APIRegistry/LaunchAgent/XDG autostart)を使用
- **統一 MCP パネル** -- Claude、Codex、Gemini、Grok Build、OpenCode、Hermes の MCP サーバーを管理、双方向同期、Deep Link インポート対応
- **Prompts** -- Markdown エディタ、クロスアプリ同期(CLAUDE.md / AGENTS.md / GEMINI.md)、バックフィル保護
- **Skills** -- GitHub リポジトリまたは ZIP ファイルからワンクリックインストール、カスタムリポジトリ管理、シンボリックリンクとファイルコピーに対応
- **Skills 再帰スキャン**
- 多階層ディレクトリをサポート
- リポジトリが異なる同名スキルを許可
### 使用量 & コストトラッキング
- **重要なバグ修正**
- プロバイダ更新時にカスタムエンドポイントが失われる問題を修正
- Gemini 設定の書き込み問題を修正
- Linux WebKitGTK の描画問題を修正
- **使用量ダッシュボード** -- プロバイダ横断で支出・リクエスト数・トークン使用量を追跡、トレンドチャート、詳細リクエストログ、カスタムモデル価格設定
**v3.7.0 ハイライト**
### Session Manager & ワークスペース
**6 つのコア機能、18,000 行超の新コード**
- 対応するセッションソースの会話履歴を閲覧・検索・復元
- **ワークスペースエディタ**(OpenClaw)-- エージェントファイル(AGENTS.md、SOUL.md など)を Markdown プレビュー付きで編集
- **Gemini CLI 統合**
- Claude Code / Codex / Gemini の 3 番目のサポート AI CLI
- 2 つの設定ファイル(`.env` + `settings.json`)に対応
- MCP サーバー管理を完備
- プリセット:Google 公式(OAuth/ PackyCode / カスタム
### システム & プラットフォーム
- **Claude Skills 管理システム**
- GitHub リポジトリを自動スキャン(3 つのキュレーション済みリポジトリを同梱)
- `~/.claude/skills/` へワンクリックでインストール/アンインストール
- カスタムリポジトリ + サブディレクトリスキャンをサポート
- ライフサイクル管理(検出/インストール/更新)を完備
- **クラウド同期** -- カスタム設定ディレクトリ(Dropbox、OneDrive、iCloud、NAS)および WebDAV サーバー同期
- **Deep Link** (`ccswitch://`) -- URL 経由でプロバイダ、MCP サーバー、Prompts、Skills をワンクリックインポート
- ダーク / ライト / システムテーマ、自動起動、自動アップデーター、アトミック書き込み、自動バックアップ、多言語対応(簡体中文/繁體中文/英/日)
- **Prompts 管理システム**
- 無制限のシステムプロンプトプリセットを作成
- Markdown エディタ(CodeMirror 6 + リアルタイムプレビュー)付き
- スマートなバックフィル保護で手動変更を保持
- 複数アプリに同時対応(Claude: `CLAUDE.md` / Codex: `AGENTS.md` / Gemini: `GEMINI.md`
## よくある質問
- **MCP v3.7.0 統合アーキテクチャ**
- 1 つのパネルで 3 アプリの MCP を管理
- 新たに SSEServer-Sent Events)トランスポートを追加
- スマート JSON パーサー + Codex TOML 自動修正
- 双方向のインポート/エクスポート + 双方向同期
<details>
<summary><strong>CC Switch はどの AI ツールに対応していますか?</strong></summary>
- **ディープリンクプロトコル**
- `ccswitch://` を全プラットフォームで登録
- 共有リンクからプロバイダ設定をワンクリックでインポート
- セキュリティ検証 + ライフサイクル統合
CC Switch は **Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**Grok Build**、**OpenCode**、**OpenClaw**、**Hermes** の 8 つのツールに対応しています。各ツールに専用のプロバイダプリセットと設定管理が用意されています。
- **環境変数の競合検知**
- Claude/Codex/Gemini/MCP 間の設定競合を自動検出
- 競合表示 + 解決ガイド
- 上書き前の警告 + バックアップ
</details>
**コア機能**
<details>
<summary><strong>プロバイダを切り替えた後、ターミナルの再起動は必要ですか?</strong></summary>
- **プロバイダ管理**Claude Code、Codex、Gemini の API 設定をワンクリックで切り替え
- **速度テスト**:エンドポイント遅延を計測し、品質を可視化
- **インポート/エクスポート**:設定をバックアップ・復元(最新 10 件を自動ローテーション)
- **多言語対応**:UI/エラー/トレイを含む中国語・英語・日本語ローカライズ
- **Claude プラグイン同期**:Claude プラグイン設定をワンクリックで適用/復元
ほとんどのツールでは、はい。変更を反映するにはターミナルまたは CLI ツールを再起動してください。ただし **Claude Code** は例外で、現在プロバイダデータのホットスイッチに対応しており、再起動は不要です。
**v3.6 ハイライト**
</details>
- プロバイダの複製とドラッグ&ドロップ並び替え
- 複数エンドポイント管理とカスタム設定ディレクトリ(クラウド同期準備済み)
- 4 階層のモデル設定(Haiku/Sonnet/Opus/Custom
- WSL 環境をサポートし、ディレクトリ変更時に自動同期
- Hooks テスト 100% カバレッジ + アーキテクチャ全面リファクタ
<details>
<summary><strong>プロバイダを切り替えた後、プラグイン設定が消えてしまいました。どうすればよいですか?</strong></summary>
**システム機能**
CC Switch には「共有設定スニペット」機能があり、APIキーやエンドポイント以外の共通データをプロバイダ間で引き継ぐことができます。「プロバイダ編集」→「共有設定パネル」→「現在のプロバイダから抽出」をクリックして、すべての共通データを保存してください。新しいプロバイダを作成する際に「共有設定を適用」にチェック(デフォルトで有効)を入れれば、プラグインなどのデータが新しいプロバイダ設定に含まれます。すべての設定項目は、アプリ初回起動時にインポートされたデフォルトプロバイダに保存されており、失われることはありません。
- クイックスイッチ付きシステムトレイ
- シングルインスタンス常駐
- ビルトイン自動アップデータ
- ロールバック保護付きのアトミック書き込み
</details>
<details>
<summary><strong>macOS のインストールについて</strong></summary>
CC Switch の macOS 版は Apple によるコード署名と公証が完了しています。直接ダウンロードしてインストールできます — 追加の手順は不要です。`.dmg` インストーラの使用を推奨します。
</details>
<details>
<summary><strong>現在アクティブなプロバイダを削除できないのはなぜですか?</strong></summary>
CC Switch は「最小限の介入」という設計原則に従っています。アプリをアンインストールしても、CLI ツールは正常に動作し続けます。すべての設定を削除すると対応する CLI ツールが使用できなくなるため、システムは常にアクティブな設定を 1 つ保持します。特定の CLI ツールをあまり使用しない場合は、設定で非表示にできます。公式ログインに戻す方法は、次の質問をご覧ください。
</details>
<details>
<summary><strong>公式ログインに戻すにはどうすればよいですか?</strong></summary>
プリセットリストから公式プロバイダを追加してください。切り替え後、ログアウト/ログインのフローを実行すれば、以降は公式プロバイダとサードパーティプロバイダを自由に切り替えられます。Codex では異なる公式プロバイダ間の切り替えに対応しており、複数の Plus アカウントや Team アカウントの切り替えに便利です。
</details>
<details>
<summary><strong>データはどこに保存されますか?</strong></summary>
- **データベース**: `~/.cc-switch/cc-switch.db`SQLite -- プロバイダ、MCP、Prompts、Skills
- **ローカル設定**: `~/.cc-switch/settings.json`(デバイスレベルの UI 設定)
- **バックアップ**: `~/.cc-switch/backups/`(自動ローテーション、最新 10 件を保持)
- **Skills**: `~/.cc-switch/skills/`(デフォルトでシンボリックリンクにより対応アプリに接続)
- **Skill バックアップ**: `~/.cc-switch/skill-backups/`(アンインストール前に自動作成、最新 20 件を保持)
</details>
<details>
<summary><strong>LinuxWayland + NVIDIA):Web コンテンツがクリックできない・リサイズで黒画面になる</strong></summary>
AppImage は過去のネイティブ Wayland クラッシュを避けるため `GDK_BACKEND=x11`(XWayland)を強制します。新しい Wayland + NVIDIA 環境ではこれが原因で Web コンテンツ領域がクリックできなくなり(タイトルバーのボタンは動作します)、リサイズ時に黒画面になることがあります。内蔵のエスケープハッチでネイティブ Wayland に戻せます:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
デスクトップアイコンから起動する場合は、`.desktop``Exec=` 行に追記するか(例:`env CC_SWITCH_GDK_BACKEND=wayland /path/to/AppImage`)、セッション環境で設定してください。この変数は汎用です:タイル型 Wayland コンポジタ(sway/Hyprland)でクリックが効かない場合は、逆に `CC_SWITCH_GDK_BACKEND=x11` を試してください。未設定の場合は既定の動作のままです。
</details>
## ドキュメント
各機能の詳しい使い方については、**[ユーザーマニュアル](docs/user-manual/ja/README.md)** をご覧ください。プロバイダ管理、MCP/Prompts/Skills、プロキシとフェイルオーバーなど、すべての機能を網羅しています。
## クイックスタート
### 基本的な使い方
1. **プロバイダ追加**: 「Add Provider」をクリック → プリセットを選ぶかカスタム設定を作成
2. **プロバイダ切り替え**:
- メイン UI: プロバイダを選択 → 「Enable」をクリック
- システムトレイ: プロバイダ名をクリック(即時反映)
3. **反映**: ターミナルまたは対応する CLI ツールを再起動して適用(Claude Code は再起動不要)
4. **公式設定に戻す**: 「Official Login」プリセットを追加し、CLI ツールを再起動してログイン/OAuth フローを実行
### MCP、Prompts、Skills & Sessions
- **MCP**: 「MCP」ボタンをクリック → テンプレートまたはカスタム設定でサーバーを追加 → アプリごとの同期をトグルで切り替え
- **Prompts**: 「Prompts」をクリック → Markdown エディタでプリセットを作成 → 有効化してライブファイルに同期
- **Skills**: 「Skills」をクリック → GitHub リポジトリを閲覧 → 対応アプリへワンクリックでインストール
- **Sessions**: 「Sessions」をクリック → 対応するセッションソースの会話履歴を閲覧・検索・復元
> **補足**: 初回起動時に、既存の CLI ツール設定を手動でインポートしてデフォルトプロバイダとして使用できます。
## ダウンロード & インストール
### システム要件
- **Windows**: Windows 10 以上
- **macOS**: macOS 10.15 (Catalina) 以上
- **macOS**: macOS 12 (Monterey) 以上
- **Linux**: Ubuntu 22.04+ / Debian 11+ / Fedora 34+ など主要ディストリビューション
### Windows ユーザー
@@ -164,7 +358,6 @@ GLM CODING PLAN は AI コーディング向けのサブスクリプションで
**方法 1: Homebrew でインストール(推奨)**
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
@@ -180,7 +373,7 @@ brew upgrade --cask cc-switch
> **注意**: 開発者アカウント未登録のため、初回起動時に「開発元を確認できません」と表示される場合があります。一度閉じてから「システム設定」→「プライバシーとセキュリティ」→「このまま開く」をクリックしてください。以降は通常通り起動できます。
### ArchLinux ユーザー
### Arch Linux ユーザー
**paru でインストール(推奨)**
@@ -190,91 +383,16 @@ paru -S cc-switch-bin
### Linux ユーザー
[Releases](../../releases) から最新版の `CC-Switch-v{version}-Linux.deb` または `CC-Switch-v{version}-Linux.AppImage` をダウンロード
[Releases](../../releases) から最新版の Linux ビルドをダウンロード
## クイックスタート
- `CC-Switch-v{version}-Linux.deb`Debian/Ubuntu
- `CC-Switch-v{version}-Linux.rpm`Fedora/RHEL/openSUSE
- `CC-Switch-v{version}-Linux.AppImage`(汎用)
### 基本的な使い方
> **Flatpak**:公式リリースには含まれていません。`.deb` から自分でビルドできます — 手順は [`flatpak/README.md`](flatpak/README.md) を参照してください。
1. **プロバイダ追加**:「Add Provider」をクリック → プリセットを選ぶかカスタム設定を作成
2. **プロバイダ切り替え**:
- メイン UI: プロバイダを選択 → 「Enable」をクリック
- システムトレイ: プロバイダ名をクリック(即時反映)
3. **反映**: ターミナルや Claude Code / Codex / Gemini クライアントを再起動して適用
4. **公式設定に戻す**: 「Official Login」プリセット(Claude/Codex)または「Google Official」プリセット(Gemini)を選び、対応クライアントを再起動してログイン/OAuth を実行
### MCP 管理
- **入口**: 右上の「MCP」ボタンをクリック
- **サーバー追加**:
- 組み込みテンプレート(mcp-fetch、mcp-filesystem など)を使用
- stdio / http / sse の各トランスポートをサポート
- アプリごとに独立した MCP を設定可能
- **有効/無効**: トグルでライブ設定への同期を切り替え
- **同期**: 有効なサーバーは各アプリのライブファイルへ自動同期
- **インポート/エクスポート**: Claude/Codex/Gemini の設定ファイルから既存 MCP を取り込み
### Skills 管理 (v3.7.0 新機能)
- **入口**: 右上の「Skills」ボタンをクリック
- **スキル探索**:
- 事前設定済みの GitHub リポジトリを自動スキャン(Anthropic 公式、ComposioHQ、コミュニティなど)
- カスタムリポジトリを追加(サブディレクトリスキャン対応)
- **インストール**: 「Install」を押すだけで `~/.claude/skills/` に配置
- **アンインストール**: 「Uninstall」で安全に削除と状態クリーンアップ
- **リポジトリ管理**: カスタム GitHub リポジトリを追加/削除
### Prompts 管理 (v3.7.0 新機能)
- **入口**: 右上の「Prompts」ボタンをクリック
- **プリセット作成**:
- 無制限のシステムプロンプトプリセットを作成
- Markdown エディタで記述(シンタックスハイライト + リアルタイムプレビュー)
- **プリセット切り替え**: プリセットを選択 → 「Activate」で即適用
- **同期先**:
- Claude: `~/.claude/CLAUDE.md`
- Codex: `~/.codex/AGENTS.md`
- Gemini: `~/.gemini/GEMINI.md`
- **保護機構**: 切り替え前に現在の内容を自動保存し、手動変更を保持
### 設定ファイルパス
**Claude Code**
- ライブ設定: `~/.claude/settings.json`(または `claude.json`
- API キーフィールド: `env.ANTHROPIC_AUTH_TOKEN` または `env.ANTHROPIC_API_KEY`
- MCP サーバー: `~/.claude.json``mcpServers`
**Codex**
- ライブ設定: `~/.codex/auth.json`(必須)+ `config.toml`(任意)
- API キーフィールド: `auth.json` 内の `OPENAI_API_KEY`
- MCP サーバー: `~/.codex/config.toml``[mcp_servers]` テーブル
**Gemini**
- ライブ設定: `~/.gemini/.env`API キー)+ `~/.gemini/settings.json`(認証モード)
- API キーフィールド: `.env` 内の `GEMINI_API_KEY` または `GOOGLE_GEMINI_API_KEY`
- 環境変数: `GOOGLE_GEMINI_BASE_URL``GEMINI_MODEL` などをサポート
- MCP サーバー: `~/.gemini/settings.json``mcpServers`
- トレイでのクイックスイッチ: プロバイダ切り替えごとに `~/.gemini/.env` を書き換えるため Gemini CLI の再起動は不要
**CC Switch 保存先 (v3.8.0 新アーキテクチャ)**
- データベース (SSOT): `~/.cc-switch/cc-switch.db`SQLite。プロバイダ、MCP、Prompts、Skills を保存)
- ローカル設定: `~/.cc-switch/settings.json`(デバイスレベル設定)
- バックアップ: `~/.cc-switch/backups/`(自動ローテーション、最新 10 件を保持)
### クラウド同期の設定
1. 設定 → 「Custom Configuration Directory」へ進む
2. クラウド同期フォルダ(Dropbox、OneDrive、iCloud など)を選択
3. アプリを再起動して反映
4. 他のデバイスでも同じフォルダを指定すればクロスデバイス同期が有効に
> **補足**: 初回起動時に既存の Claude/Codex 設定をデフォルトプロバイダとして自動インポートします。
## アーキテクチャ概要
<details>
<summary><strong>アーキテクチャ概要</strong></summary>
### 設計原則
@@ -302,23 +420,22 @@ paru -S cc-switch-bin
- **二層ストレージ**: 同期データは SQLite、デバイスデータは JSON
- **双方向同期**: 切り替え時はライブファイルへ書き込み、編集時はアクティブプロバイダから逆同期
- **アトミック書き込み**: 一時ファイル + rename パターンで設定破損を防止
- **並行安全**: Mutex で保護された DB 接続でレースを防
- **並行安全**: Mutex で保護された DB 接続でレースコンディションを防
- **レイヤードアーキテクチャ**: Commands → Services → DAO → Database を明確に分離
**主要コンポーネント**
- **ProviderService**: プロバイダの CRUD、切り替え、バックフィル、ソート
- **McpService**: MCP サーバー管理、インポート/エクスポート、ライブファイル同期
- **ProxyService**: ローカル Proxy モードのホットスイッチとフォーマット変換
- **SessionManager**: 対応する全アプリの会話履歴閲覧
- **ConfigService**: 設定のインポート/エクスポート、バックアップローテーション
- **SpeedtestService**: API エンドポイントの遅延計測
**v3.6 リファクタリング**
</details>
- バックエンド: エラーハンドリング → コマンド分割 → テスト → サービス層 → 並行性の 5 フェーズ
- フロントエンド: テスト基盤 → hooks → コンポーネント → クリーンアップの 4 ステージ
- テスト: hooks 100% カバレッジ + 統合テスト(vitest + MSW
## 開発
<details>
<summary><strong>開発ガイド</strong></summary>
### 開発環境
@@ -379,7 +496,7 @@ cargo test test_name
cargo test --features test-hooks
```
### テストガイド (v3.6)
### テストガイド
**フロントエンドテスト**:
@@ -387,18 +504,6 @@ cargo test --features test-hooks
- **MSW (Mock Service Worker)** で Tauri API 呼び出しをモック
- コンポーネントテストに **@testing-library/react** を採用
**テストカバレッジ**:
- Hooks の単体テスト(100% カバレッジ)
- `useProviderActions` - プロバイダ操作
- `useMcpActions` - MCP 管理
- `useSettings` 系 - 設定管理
- `useImportExport` - インポート/エクスポート
- 統合テスト
- アプリのメインフロー
- SettingsDialog の一連操作
- MCP パネルの機能
**テスト実行**:
```bash
@@ -412,60 +517,68 @@ pnpm test:unit:watch
pnpm test:unit --coverage
```
## 技術スタック
### 技術スタック
**フロントエンド**: React 18 · TypeScript · Vite · TailwindCSS 4 · TanStack Query v5 · react-i18next · react-hook-form · zod · shadcn/ui · @dnd-kit
**フロントエンド**: React 18 · TypeScript · Vite · TailwindCSS 3.4 · TanStack Query v5 · react-i18next · react-hook-form · zod · shadcn/ui · @dnd-kit
**バックエンド**: Tauri 2.8 · Rust · serde · tokio · thiserror · tauri-plugin-updater/process/dialog/store/log
**テスト**: vitest · MSW · @testing-library/react
## プロジェクト構成
</details>
<details>
<summary><strong>プロジェクト構成</strong></summary>
```
├── src/ # フロントエンド (React + TypeScript)
│ ├── components/ # UI コンポーネント (providers/settings/mcp/ui)
│ ├── hooks/ # ビジネスロジック用カスタムフック
├── src/ # フロントエンド (React + TypeScript)
│ ├── components/
│ ├── providers/ # プロバイダ管理
│ │ ├── mcp/ # MCP パネル
│ │ ├── prompts/ # Prompts 管理
│ │ ├── skills/ # Skills 管理
│ │ ├── sessions/ # Session Manager
│ │ ├── proxy/ # Proxy モードパネル
│ │ ├── openclaw/ # OpenClaw 設定パネル
│ │ ├── settings/ # 設定 (Terminal/Backup/About)
│ │ ├── deeplink/ # Deep Link インポート
│ │ ├── env/ # 環境変数管理
│ │ ├── universal/ # クロスアプリ設定
│ │ ├── usage/ # 使用量統計
│ │ └── ui/ # shadcn/ui コンポーネントライブラリ
│ ├── hooks/ # カスタムフック(ビジネスロジック)
│ ├── lib/
│ │ ├── api/ # Tauri API ラッパー (型安全)
│ │ └── query/ # TanStack Query 設定
│ ├── i18n/locales/ # 翻訳 (zh/en)
│ ├── config/ # プリセット (providers/mcp)
│ └── types/ # TypeScript 型定義
├── src-tauri/ # バックエンド (Rust)
│ │ ├── api/ # Tauri API ラッパー型安全
│ │ └── query/ # TanStack Query 設定
│ ├── locales/ # 翻訳 (zh/zh-TW/en/ja)
│ ├── config/ # プリセット (providers/mcp)
│ └── types/ # TypeScript 型定義
├── src-tauri/ # バックエンド (Rust)
│ └── src/
│ ├── commands/ # Tauri コマンド層 (ドメイン別)
│ ├── services/ # ビジネスロジック層
│ ├── app_config.rs # 設定モデル
│ ├── provider.rs # プロバイダドメインモデ
│ ├── mcp.rs # MCP 同期 & 検証
── lib.rs # アプリエントリ & トレイメニュー
├── tests/ # フロントエンドテスト
│ ├── hooks/ # 単体テスト
│ └── components/ # 統合テスト
└── assets/ # スクリーンショット & スポンサーリソース
│ ├── commands/ # Tauri コマンド層ドメイン別
│ ├── services/ # ビジネスロジック層
│ ├── database/ # SQLite DAO 層
│ ├── proxy/ # Proxy モジュー
│ ├── session_manager/ # セッション管理
── deeplink/ # Deep Link 処理
│ └── mcp/ # MCP 同期モジュール
├── tests/ # フロントエンドテスト
└── assets/ # スクリーンショット & パートナーリソース
```
## 更新履歴
詳細は [CHANGELOG.md](CHANGELOG.md) をご覧ください。
## 旧 Electron 版
[Releases](../../releases) に v2.0.3 の Electron 旧版を残しています。
旧版コードが必要な場合は `electron-legacy` ブランチを取得してください。
</details>
## 貢献
Issue や提案を歓迎します!
PR を送る前に以下をご確認ください:
PR を送る前に以下をご確認ください
- 型チェック: `pnpm typecheck`
- フォーマットチェック: `pnpm format:check`
- 単体テスト: `pnpm test:unit`
- 💡 新機能の場合は、事前に Issue でディスカッションしていただけると助かります
新機能の場合は、PR を送る前に Issue でディスカッションしてください。プロジェクトに合わない機能の PR はクローズされる場合があります。
## Star History
+346 -230
View File
@@ -1,48 +1,213 @@
<div align="center">
# Claude Code / Codex / Gemini CLI 全方位辅助工具
# CC Switch
[![Version](https://img.shields.io/badge/version-3.8.2-blue.svg)](https://github.com/farion1231/cc-switch/releases)
[![Trending](https://img.shields.io/badge/🔥_TypeScript_Trending-Daily%20%7C%20Weekly%20%7C%20Monthly-ff6b6b.svg)](https://github.com/trending/typescript)
### Claude Code、Claude Desktop、Codex、Gemini CLI、Grok Build、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)
[![Built with Tauri](https://img.shields.io/badge/built%20with-Tauri%202-orange.svg)](https://tauri.app/)
[![Downloads](https://img.shields.io/endpoint?url=https://api.pinstudios.net/api/badges/downloads/farion1231/cc-switch/total)](https://github.com/farion1231/cc-switch/releases/latest)
[![Downloads](https://img.shields.io/github/downloads/farion1231/cc-switch/total)](https://github.com/farion1231/cc-switch/releases/latest)
<a href="https://trendshift.io/repositories/15372" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15372" alt="farion1231%2Fcc-switch | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
<a href="https://www.star-history.com/#farion1231/cc-switch&Date"><picture><source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=farion1231/cc-switch&theme=dark" /><img alt="Star History Rank" src="https://api.star-history.com/badge?repo=farion1231/cc-switch" width="196" height="55" /></picture></a>
[English](README.md) | 中文 | [日本語](README_JA.md) | [更新日志](CHANGELOG.md) | [v3.8.0 发布说明](docs/release-note-v3.8.0-zh.md)
### 🌐 唯一官方网站:**[ccswitch.io](https://ccswitch.io)**
**从供应商切换器到 AI CLI 一体化管理平台**
统一管理 Claude Code、Codex 与 Gemini CLI 的供应商配置、MCP 服务器、Skills 扩展和系统提示词。
[English](README.md) | 中文 | [日本語](README_JA.md) | [Deutsch](README_DE.md) | [更新日志](CHANGELOG.md)
</div>
## ❤️赞助商
![智谱 GLM](assets/partners/banners/glm-zh.jpg)
> [想出现在这里?](mailto:farion1231@gmail.com)
感谢智谱AI的 GLM CODING PLAN 赞助了本项目!
<details open>
<summary>点击折叠</summary>
GLM CODING PLAN 是专为AI编码打造的订阅套餐,每月最低仅需20元,即可在十余款主流AI编码工具如 Claude Code、Cline 中畅享智谱旗舰模型 GLM-4.6,为开发者提供顶尖、高速、稳定的编码体验。
[![Kimi K2.7 Code](https://gcdn.moonshot.cn/growth-cdn/sponsor/kimi-zh.png)](https://platform.kimi.com?aff=cc-switch)
CC Switch 已经预设了智谱GLM,只需要填写 key 即可一键导入编程工具。智谱AI为本软件的用户提供了特别优惠,使用[此链接](https://www.bigmodel.cn/claude-code?ic=RRVJPB5SII)购买可以享受九折优惠。
Kimi K3 是 Moonshot AI 迄今能力最强的模型,也是全球首个开源 3T 级模型。K3 拥有 2.8T 参数、原生视觉能力与 100 万 Token 上下文,在长程编码、知识工作和推理任务中展现前沿性能。使用 CC Switch,可以在各类 Agent 工具中便捷配置和切换 Kimi。**[点击此处开始使用 Kimi](https://platform.kimi.com?aff=cc-switch)**
主要进行编程工作?可以试试 **[Kimi Code 订阅](https://www.kimi.com/code/?aff=cc-switch)**。
---
<table>
<tr>
<td width="180"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></td>
<td>感谢 PackyCode 赞助了本项目!PackyCode 是一家稳定、高效的API中转服务商,提供 Claude Code、Codex、Gemini 等多种中转服务。PackyCode 为本软件的用户提供了特别优惠,使用<a href="https://www.packyapi.com/register?aff=cc-switch">此链接</a>注册并在充值时填写"cc-switch"优惠码,可以享受9折优惠</td>
<td width="180"><a href="https://www.packyapi.com/register?aff=cc-switch"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></a></td>
<td>感谢 PackyCode 赞助了本项目!PackyCode 是一家稳定、高效的API中转服务商,提供 Claude Code、Codex、Gemini 等多种中转服务。PackyCode 为本软件的用户提供了特别优惠,使用<a href="https://www.packyapi.com/register?aff=cc-switch">此链接</a>注册并在充值时填写"cc-switch"优惠码,首次充值可以享受9折优惠</td>
</tr>
<tr>
<td width="180"><img src="assets/partners/logos/sds-zh.png" alt="ShanDianShuo" width="150"></td>
<td>感谢闪电说赞助本项目!闪电说是本地优先的 AI 语音输入法:毫秒级响应,数据不离设备;打字速度提升 4 倍,AI 智能纠错;绝对隐私安全,完全免费,配合 Claude Code 写代码效率翻倍!支持 Mac/Win 双平台,<a href="https://www.shandianshuo.cn">免费下载</a></td>
<td width="180"><a href="https://zetaapi.ai/go/u117"><img src="assets/partners/logos/zetaapi-banner.png" alt="ZetaAPI" width="150"></a></td>
<td>感谢 ZetaAPI 赞助本项目!ZetaAPI 主打模型不掺水、保真不降智、价格低至官方价 35 折,平台不混量、不暗中替换低质量模型、不做虚假路由,支持 Claude Code、Codex、Gemini、ChatGPT 等主流模型接入,帮助用户在保证模型质量的同时大幅降低 API 使用成本。同时,ZetaAPI 提供企业级 SLA 稳定性保障、标准接口兼容、一个 Key 接入多模型、快速集成、按量计费等能力,适用于 AI 产品、代码生成、企业内部工具、客服系统、内容生产和自动化流程等场景。若经验证发现模型质量与标称不符,ZetaAPI 承诺假一赔十,让用户用得更稳定、更透明、更放心。通过<a href="https://zetaapi.ai/go/u117">此链接</a>注册,并在首次充值时使用优惠码 CC-SWITCH,即可享受 CC Switch 用户专属的首次充值九折优惠!</td>
</tr>
<tr>
<td width="180"><a href="https://apinebula.com/VjM74M"><img src="assets/partners/logos/apinebula_banner.png" alt="APINebula" width="150"></a></td>
<td>感谢 APINEBULA 赞助本项目!APINEBULA 是银河录像局旗下的企业级 AI 聚合平台,背靠大平台资源,面向开发者、团队与企业用户提供稳定、高性价比的大模型 API 接入服务。平台聚合 Claude、GPT、Gemini 等主流满血模型,一个接口,接入全球顶尖 AI 大模型,各大模型价格低至 1 折起,支持企业级高并发、正式合同、对公打款与开票服务,适合 AI 编程、Agent 开发、业务系统集成等多种场景!使用<a href="https://apinebula.com/VjM74M">此链接</a>注册并在充值时填写 <strong>"ccswitch"</strong> 优惠码可享<strong>九折优惠</strong></td>
</tr>
<tr>
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=9915W3"><img src="assets/partners/logos/aicodemirror.jpg" alt="AICodeMirror" width="150"></a></td>
<td>感谢 AICodeMirror 赞助了本项目!AICodeMirror 提供 Claude Code / Codex / Gemini CLI 官方高稳定中转服务,支持企业级高并发、极速开票、7×24 专属技术支持。
Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更有折上折!AICodeMirror 为 CCSwitch 的用户提供了特别福利,通过<a href="https://www.aicodemirror.com/register?invitecode=9915W3">此链接</a>注册的用户,可享受首充8折,企业客户最高可享 7.5 折!</td>
</tr>
<tr>
<td width="180"><a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/"><img src="assets/partners/logos/pateway.png" alt="PatewayAI" width="150"></a></td>
<td>感谢 PatewayAI 赞助了本项目!PatewayAI 是一家面向重度 AI 开发者、专注官方直连高品质模型 API 中转服务商。提供 Claude 全系列与 Codex 系列模型,100% 官方源直供,不掺假不注水,欢迎检验。计费透明,Token 级账单可逐笔核验。
同时支持企业级高并发,并为企业客户提供了专业的管理平台,企业客户可签订正式合同并开具发票,更多详情进入官网获取联系方式。
现在通过<a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">此链接</a>注册即送 $3 试用额度,用户充值低至 6 折,邀请好友双向赠送,邀请奖励可达 $150!</td>
</tr>
<tr>
<td width="180"><a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL"><img src="assets/partners/logos/fenno-banner.png" alt="Fenno.ai" width="150"></a></td>
<td>感谢 Fenno.ai 赞助了本项目!Fenno.ai 是一家稳定、高效的 API 中转服务商,目前主要提供 Codex 中转服务,兼容 OpenAI 及 Anthropic 协议,可灵活接入 Codex、Claude Code、OpenCode 等主流编程工具,可稳定支撑千亿 Token/日的企业级调用需求,支持国内及海外主体公对公结算、开票。Fenno.ai 为 CC Switch 的用户提供了专属福利:通过<a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL">此链接</a>即可订阅 9.9 元/150 刀额度的超值 Coding Plan,邀请好友最高可享 20% 奖励,多邀多得!</td>
</tr>
<tr>
<td width="180"><a href="https://runapi.co/register?aff=iOKB"><img src="assets/partners/logos/runapi.jpg" alt="RunAPI" width="150"></a></td>
<td>感谢 RunAPI 赞助本项目!RunAPI 是高效稳定的 AI 模型 API 中转平台,一个 API Key 即可访问 OpenAI、Claude、Gemini、DeepSeek、Grok 等 150+ 主流模型,低至 1 折,极其稳定,可以无缝兼容 Claude Code、OpenClaw 等工具。RunAPI为CC switch的用户提供了特别福利,使用<a href="https://runapi.co/register?aff=iOKB">此链接</a>注册并首次充值即可享受10%的优惠折扣!</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>
<tr>
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
<td>感谢胜算云赞助了本项目!胜算云是专为AI Native Teams服务的超级工厂,工业级AI任务并行执行平台,模型商城集采直供聚合接入了Claude、Chatgpt、Gemini等海内外LLM及图片视频多媒体模型算力,绝无逆向掺水、全站模型SLA可用性高达99.7%、<a href="https://watch.shengsuanyun.com/status/shengsuanyun">监测接口</a>日常全绿。更有企业级专属定制网关,实现团队精细化成本与权限管控,智能路由+安全防护+BYOK企业自带密钥托管。平台按量及tokens plan(即将上线)计费,可开票,使用<a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">此链接</a>注册新用户可获10元模力及首充10%赠送。</td>
</tr>
<tr>
<td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一个集成了 Claude Code、Codex 以及 Gemini 最新模型的一站式平台,为你提供稳定、高效且高性价比的AI编程服务。本站提供灵活的订阅计划,零封号风险,国内直连,无需魔法,极速响应。AIGoCode 为 CC Switch 的用户提供了特别福利,通过<a href="https://aigocode.com/invite/CC-SWITCH">此链接</a>注册的用户首次充值可以获得额外10%奖励额度!</td>
</tr>
<tr>
<td width="180"><a href="https://subrouter.ai/register?aff=l3ri"><img src="assets/partners/logos/subrouter-banner.png" alt="SubRouter" width="150"></a></td>
<td>感谢 SubRouter 赞助本项目!SubRouter 是面向 AI 服务经营者的公开市场与智能路由平台。商家可快速开通独立经营站,发布套餐、管理用户与模型价格;用户可在市场发现服务,并通过统一 API 获得稳定高效的模型调用。通过<a href="https://subrouter.ai/register?aff=l3ri">此链接</a>注册!</td>
</tr>
<tr>
<td width="180"><a href="https://apikey.fun/register?aff=CCSwitch"><img src="assets/partners/logos/apikey_banner.png" alt="APIKEY.FUN" width="150"></a></td>
<td>感谢 APIKEY.FUN 赞助本项目!APIKEY.FUN 是一家专业的企业级 AI 中转站,致力于为企业和个人开发者提供稳定、高效、低成本的 AI 模型 API 接入服务。平台支持 Claude、OpenAI、Gemini 等主流热门模型,价格低至官方原价的 7%。通过本项目<a href="https://apikey.fun/register?aff=CCSwitch">专属链接</a>注册,还可享受最高 <strong>充值永久 95 折</strong> 专属优惠。</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>
</tr>
<tr>
<td width="180"><a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
<td>感谢 <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai</a> 赞助本项目!code0.ai 是专为开发者打造的 AI 编程服务平台,支持 Claude Code、Codex、Gemini 等主流 AI 编程能力,帮助个人开发者和团队更稳定、更高效地使用 AI Agent 完成代码开发、调试与自动化任务。ccswitch 用户可通过 <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai 官网</a> 联系客服领取测试额度,体验高效稳定的 AI 编程服务!</td>
</tr>
<tr>
<td width="180"><a href="https://teamorouter.com/zh?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory"><img src="assets/partners/logos/TeamoRouter-banner.png" alt="TeamoRouter" width="150"></a></td>
<td>感谢 TeamoRouter 赞助本项目!TeamoRouter 是一款面向开发者、AI 团队和企业的企业级 Agentic LLM 网关。无需任何订阅,你就可以通过一个统一 API 访问 Claude Code、Codex、Gemini CLI、OpenAI Codex 以及其他热门 AI Agent,同时享受最高可达 90% 折扣的 API 价格。
不同于常见的 API 中转服务,TeamoRouter 聚合了数百家官方模型提供商和可信基础设施合作伙伴,包括 OpenAI、Anthropic、Vertex、Azure 和 AWS Bedrock。每个提供商都经过验证,确保 100% 兼容 Agent 协议,并具备可靠的缓存性能和请求可追踪性,从而提供稳定质量,而不是反向工程或缩水后的接口。平台提供接近官方水平的 TTFT、99.6% SLA、最高 5,000 QPM 的企业级吞吐量,以及行业领先的缓存命中率,可大幅降低长时间运行的 Agent 工作流中的 token 成本。
TeamoRouter 还提供企业级功能,包括集中账单、团队管理、BYOK、智能路由、用量分析、动态提供商优化和专属支持。为了获得更简单的使用体验,Teamo Desktop 支持你一键使用 Claude Code、Codex、Gemini CLI 和其他热门 AI Agent,无需管理 API Key,也无需手动配置网关。新用户通过<a href="https://teamorouter.com/zh?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory">此链接</a>注册,首次充值可享受 10% 折扣。</td>
</tr>
<tr>
<td width="180"><a href="https://www.newapi.ai/"><img src="assets/partners/logos/newapi-banner.png" alt="new-api" width="150"></a></td>
<td>感谢开源 AI 基础设施项目 <a href="https://www.newapi.ai/">new-api</a> 对本项目的鼎力支持!new-api 是由 QuantumNous(锟腾科技)推出的开源 AI 基础设施项目,也是活跃度与使用规模领先的大模型统一接入与分发项目之一,专注于帮助开发者、团队和企业以更低成本构建可管理、可扩展的 AI 服务平台。作为同样扎根开源生态的项目,new-api 希望通过赞助支持更多优秀开源项目持续发展。🌟 欢迎 Star 支持 new-api<a href="https://github.com/QuantumNous/new-api">https://github.com/QuantumNous/new-api</a>,官网:<a href="https://www.newapi.ai/">https://www.newapi.ai/</a>。</td>
</tr>
<tr>
<td width="180"><a href="https://claudecn.ai/register?aff=HEL9"><img src="assets/partners/logos/claudecn.jpg" alt="ClaudeCN" width="150"></a></td>
<td>感谢 ClaudeCN 赞助本项目!ClaudeCN 由是一家实体企业运营的企业级AI中转平台。平台可提供高可用性的商用API服务,提供Claude、GPT、Deepseek等热门模型,支持企业采购流程,可对公打款、签约,服务合规有保障。点击<a href="https://claudecn.ai/register?aff=HEL9">此链接</a>注册!</td>
</tr>
<tr>
<td width="180"><a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&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/ai618?utm_campaign=hw&utm_content=hw&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>
<td width="180"><a href="https://cloud.siliconflow.cn/i/YflgU2Ve"><img src="assets/partners/logos/silicon_zh.jpg" alt="SiliconFlow" width="150"></a></td>
<td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/YflgU2Ve">此链接</a>注册并完成实名认证,即可获得 ¥16 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td>
</tr>
<tr>
<td width="180"><a href="https://nekocode.ai?aff=CCSWITCH"><img src="assets/partners/logos/nekocode-banner.png" alt="NekoCode" width="150"></a></td>
<td>感谢 <a href="https://nekocode.ai?aff=CCSWITCH">NekoCode</a> 赞助本项目!NekoCode 为开发者提供稳定、高效、可靠的 Claude、Codex 等 AI 模型 API 中转服务,价格透明,接入便捷,支持灵活的按量计费。CC Switch 用户专享 9 折福利:通过 <a href="https://nekocode.ai?aff=CCSWITCH">此链接</a> 注册,并在充值时输入优惠码 <code>cc-switch</code>,即可享受充值 9 折优惠!</td>
</tr>
<tr>
<td width="180"><a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch"><img src="assets/partners/logos/atlascloud_banner.png" alt="Atlas Cloud" width="150"></a></td>
<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.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch"><img src="assets/partners/logos/ucloud.png" alt="优云智算" width="150"></a></td>
<td>感谢优云智算赞助了本项目!优云智算是UCloud旗下AI云平台,提供稳定、全面的国内外模型API,仅一个key即可调用。主打包月、按次的高性价比 国模Coding Plan套餐,同时提供官转稳定海外模型。支持接入 Claude Code、Codex 及 API 调用。支持企业高并发、7*24技术支持、自助开票。通过<a href="https://www.compshare.cn/coding-plan?ytag=GPU_YY_YX_git_cc-switch">此链接</a>注册的用户,可得免费5元平台体验金!</td>
</tr>
<tr>
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.svg" 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://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
<td>感谢 SSSAiCode 赞助了本项目!SSSAiCode 是一家稳定可靠的API中转站,致力于提供稳定、可靠、平价的Claude、CodeX模型服务,支持当日快速开票,SSSAiCode为本软件的用户提供特别优惠,使用<a href="https://www.sssaicode.com/register?ref=DCP0SM">此链接</a>注册每次充值均可享受10$的额外奖励!</td>
</tr>
<tr>
<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://www.right.codes/register?aff=CCSWITCH"><img src="assets/partners/logos/rightcode.jpg" alt="RightCode" width="150"></a></td>
<td>感谢 Right Code 赞助了本项目!Right Code 稳定提供 Claude Code、Codex、Gemini 等模型的中转服务,并可选按量、包月两种计费模式。充值即可开票,企业、团队用户一对一对接。同时为 CC Switch 的用户提供了特别优惠:通过<a href="https://www.right.codes/register?aff=CCSWITCH">此链接</a>注册,每次充值均可获得实付金额5%的按量额度!</td>
</tr>
<tr>
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
<td>感谢 ETok.ai 赞助了本项目!ETok.ai 致力于打造一站式 AI 编程工具服务平台。我们提供 Claude Code 专业套餐及技术社群服务,同时支持 Google Gemini 和 OpenAI Codex。通过精心设计的套餐方案和专业的技术社群,为开发者提供稳定的服务保障和持续的技术支持,让 AI 辅助编程真正成为开发者的生产力工具。点击<a href="https://etok.ai">这里</a>注册!</td>
</tr>
<tr>
<td width="180"><a href="https://cubence.com/signup?code=CCSWITCH&source=ccs"><img src="assets/partners/logos/cubence.png" alt="Cubence" width="150"></a></td>
<td>感谢 Cubence 赞助本项目!Cubence 是一家可靠高效的 API 中继服务提供商,提供对 Claude Code、Codex、Gemini 等模型的中继服务,并提供按量、包月等灵活的计费方式。Cubence 为 CC Switch 的用户提供了特别优惠:使用 <a href="https://cubence.com/signup?code=CCSWITCH&source=ccs">此链接</a> 注册,并在充值时输入 "CCSWITCH" 优惠码,每次充值均可享受九折优惠!</td>
</tr>
<tr>
<td width="180"><a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch"><img src="assets/partners/logos/crazyrouter.png" alt="Crazyrouter" width="150"></a></td>
<td>感谢 Crazyrouter 赞助了本项目!Crazyrouter 是一个高性能 AI API 聚合平台——一个 API Key 即可访问 300+ 模型,包括 Claude Code、Codex、Gemini CLI 等。全部模型低至官方定价的 55%,支持自动故障转移、智能路由和无限并发。Crazyrouter 为 CC Switch 用户提供了专属优惠:通过<a href="https://crazyrouter.com/register?aff=OZcm&ref=cc-switch">此链接</a>注册后联系客服即可领取 <strong>$2 免费额度</strong>,首次充值时输入优惠码 `CCSWITCH` 还可获得额外 <strong>30% 奖励额度</strong></td>
</tr>
<tr>
<td width="180"><a href="https://www.dmxapi.cn/register?aff=bUHu"><img src="assets/partners/logos/dmx-zh.jpeg" alt="DMXAPI" width="150"></a></td>
<td>感谢 DMXAPI(大模型API)赞助了本项目! DMXAPI,一个Key用全球大模型。
为200多家企业用户提供全球大模型API服务。· 充值即开票 ·当天开票 ·并发不限制 ·1元起充 · 7x24 在线技术辅导,GPT/Claude/Gemini全部6.8折,国内模型5~8折,Claude Code 专属模型3.4折进行中!<a href="https://www.dmxapi.cn/register?aff=bUHu">点击这里注册</a></td>
</tr>
</table>
</details>
## 为什么选择 CC Switch
现代 AI 编程依赖于 Claude Code、Claude Desktop、Codex、Gemini CLI、Grok Build、OpenCode、OpenClaw 和 Hermes 等工具——但每个工具都有自己的配置格式。切换 API 供应商意味着手动编辑 JSON、TOML 或 `.env` 文件,而在多个工具之间缺乏一个统一管理 MCP, SKILLS 的方式。
**CC Switch** 为你提供一个桌面应用来管理所有支持的 AI 工具。无需手动编辑配置文件,你将获得一个可视化界面,一键将供应商导入应用,一键在不同的供应商之间进行切换,内置 50+ 供应商预设、统一的 MCP, SKILLS 管理以及系统托盘即时切换功能——所有操作都基于可靠的 SQLite 数据库和原子写入机制,保护你的配置不被损坏。
- **一个应用,八个工具** — 在单一界面中管理 Claude Code、Claude Desktop、Codex、Gemini CLI、Grok Build、OpenCode、OpenClaw 和 Hermes
- **告别手动编辑** — 50+ 供应商预设,包括 AWS Bedrock、NVIDIA NIM 和社区中转服务;一键即可切换
- **统一 MCP, SKILLS 管理** — 一个面板管理 Claude、Codex、Gemini、Grok Build、OpenCode 和 Hermes 的 MCP, SKILLS, 支持双向同步
- **系统托盘快速切换** — 从托盘菜单即时切换供应商,无需打开完整应用
- **云同步** — 通过 Dropbox、OneDrive、iCloud 或 WebDAV 服务器在不同设备之间同步供应商数据
- **跨平台** — 基于 Tauri 2 构建的原生桌面应用,支持 Windows、macOS 和 Linux
- **小工具** - 内置了多种小工具来解决首次安装登录确认、禁止签名、插件拓展同步等多种功能
## 界面预览
| 主界面 | 添加供应商 |
@@ -51,120 +216,151 @@ CC Switch 已经预设了智谱GLM,只需要填写 key 即可一键导入编
## 功能特性
### 当前版本:v3.8.2 | [完整更新日志](CHANGELOG.md)
[完整更新日志](CHANGELOG.md) | [发布说明](docs/release-notes/v3.16.1-zh.md)
**v3.8.0 重大更新(2025-11-28**
### 供应商管理
**持久化架构升级 & 全新用户界面**
- **8 个支持工具,50+ 预设** — Claude Code、Claude Desktop、Codex、Gemini CLI、Grok Build、OpenCode、OpenClaw、Hermes;复制 key 即可一键导入
- **通用供应商** — 一份配置同步到 Claude Code、Codex 和 Gemini CLI
- 一键切换、系统托盘快速访问、拖拽排序、导入导出
- **SQLite + JSON 双层架构**
- 从 JSON 文件存储迁移到 SQLite + JSON 双层结构
- 可同步数据(供应商、MCP、Prompts、Skills)存入 SQLite
- 设备级数据(窗口状态、本地路径)保留在 JSON
- 为未来云同步功能奠定基础
- Schema 版本管理支持数据库迁移
### 代理与故障转移
- **全新用户界面**
- 完全重新设计的界面布局
- 统一的组件样式和更流畅的动画
- 优化的视觉层次
- Tailwind CSS 从 v4 降级到 v3.4 以提升浏览器兼容性
- **本地代理热切换** — 格式转换、自动故障转移、熔断器、供应商健康监控和整流器
- **应用级代理接管** — 独立为 Claude、Codex、Gemini 或 Grok Build 配置代理,具体到单个供应商
- **日语支持**
- 新增日语界面支持(现支持中文/英文/日语)
### MCP、Prompts 与 Skills
- **开机自启**
- 在设置中一键开启/关闭
- 使用平台原生 API(注册表/LaunchAgent/XDG autostart
- **统一 MCP 面板** — 管理 Claude、Codex、Gemini、Grok Build、OpenCode 和 Hermes 的 MCP 服务器,双向同步,支持 Deep Link 导入
- **Prompts** — Markdown 编辑器,跨应用同步(CLAUDE.md / AGENTS.md / GEMINI.md),回填保护
- **Skills** — 从 GitHub 仓库或 ZIP 文件一键安装,自定义仓库管理,支持软连接和文件复制
- **Skills 递归扫描**
- 支持多层目录结构
- 允许不同仓库的同名技能
### 用量与成本追踪
- **关键 Bug 修复**
- 修复更新供应商时自定义端点丢失问题
- 修复 Gemini 配置写入问题
- 修复 Linux WebKitGTK 渲染问题
- **用量仪表盘** — 跨供应商追踪支出、请求数和 Token 用量,趋势图表、详细请求日志和自定义模型定价
**v3.7.0 亮点**
### 会话管理器与工作区
**六大核心功能,18,000+ 行新增代码**
- 浏览、搜索和恢复支持的会话来源
- **工作区编辑器**OpenClaw)— 编辑 Agent 文件(AGENTS.md、SOUL.md 等),支持 Markdown 预览
- **Gemini CLI 集成**
- 第三个支持的 AI CLIClaude Code / Codex / Gemini
- 双文件配置支持(`.env` + `settings.json`
- 完整 MCP 服务器管理
- 预设:Google Official (OAuth) / PackyCode / 自定义
### 系统与平台
- **Claude Skills 管理系统**
- 从 GitHub 仓库自动扫描技能(预配置 3 个精选仓库)
- 一键安装/卸载到 `~/.claude/skills/`
- 自定义仓库支持 + 子目录扫描
- 完整生命周期管理(发现/安装/更新)
- **云同步** — 自定义配置目录(Dropbox、OneDrive、iCloud、坚果云、NAS)及 WebDAV 服务器同步
- **Deep Link** (`ccswitch://`) — 通过 URL 一键导入供应商、MCP 服务器、提示词和技能
- 深色 / 浅色 / 跟随系统主题、开机自启、自动更新、原子写入、自动备份、国际化(简中/繁中/英/日)
- **Prompts 管理系统**
- 多预设系统提示词管理(无限数量,快速切换)
- 跨应用支持(Claude: `CLAUDE.md` / Codex: `AGENTS.md` / Gemini: `GEMINI.md`
- Markdown 编辑器(CodeMirror 6 + 实时预览)
- 智能回填保护,保留手动修改
## 常见问题
- **MCP v3.7.0 统一架构**
- 单一面板管理三个应用的 MCP 服务器
- 新增 SSE (Server-Sent Events) 传输类型
- 智能 JSON 解析器 + Codex TOML 格式自动修正
- 统一导入/导出 + 双向同步
<details>
<summary><strong>CC Switch 支持哪些 AI 工具?</strong></summary>
- **深度链接协议**
- `ccswitch://` 协议注册(全平台)
- 通过共享链接一键导入供应商配置
- 安全验证 + 生命周期集成
CC Switch 支持八个工具:**Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**Grok Build**、**OpenCode**、**OpenClaw** 和 **Hermes**。每个工具都有专属的供应商预设和配置管理。
- **环境变量冲突检测**
- 自动检测跨应用配置冲突(Claude/Codex/Gemini/MCP
- 可视化冲突指示器 + 解决建议
- 覆盖警告 + 更改前备份
</details>
**核心功能**
<details>
<summary><strong>切换供应商后需要重启终端吗?</strong></summary>
- **供应商管理**:一键切换 Claude Code、Codex 与 Gemini 的 API 配置
- **速度测试**:测量 API 端点延迟,可视化连接质量指示器
- **导入导出**:备份和恢复配置,自动轮换(保留最近 10 个)
- **国际化支持**:完整的中英文本地化(UI、错误、托盘)
- **Claude 插件同步**:一键应用或恢复 Claude 插件配置
大多数工具需要重启终端或 CLI 工具才能使更改生效。例外的是 **Claude Code**,它目前支持供应商数据的热切换,无需重启。
**v3.6 亮点**
</details>
- 供应商复制 & 拖拽排序
- 多端点管理 & 自定义配置目录(支持云同步)
- 细粒度模型配置(四层:Haiku/Sonnet/Opus/自定义)
- WSL 环境支持,配置目录切换自动同步
- 100% hooks 测试覆盖 & 完整架构重构
<details>
<summary><strong>切换供应商之后我的插件配置怎么不见了?</strong></summary>
**系统功能**
CC Switch 使用“通用配置片段”功能,在不同的供应商之间传递 Key 和请求地址之外的通用数据,您可以在“编辑供应商”菜单的“通用配置面板”里,点击“从当前供应商提取”,把所有的通用数据提取到通用配置中,之后在新建“供应商”的时候,只要勾选“应用通用配置”(默认勾选),就会把插件等数据写入到新的供应商配置中。您的所有配置项都会保存在运行本软件的时候,第一次导入的默认供应商里面,不会丢失。
- 系统托盘快速切换
- 单实例守护
- 内置自动更新器
- 原子写入与回滚保护
</details>
<details>
<summary><strong>macOS 安装</strong></summary>
CC Switch macOS 版本已通过 Apple 代码签名和公证,可直接下载安装,无需额外操作。推荐使用 `.dmg` 安装包。
</details>
<details>
<summary><strong>为什么总有一个正在激活中的供应商无法删除?</strong></summary>
本软件的设计原则是“最小侵入性”,即使卸载本软件,也不会影响应用的正常使用。
所以系统总会保留一个正在激活中的配置,因为如果将所有配置全部删除,该应用将无法正常使用。如果你不经常使用某个对应的应用,可以在设置中关掉该应用的显示。如果你想切换回官方登录,可以参考下条。
</details>
<details>
<summary><strong>如何切换回官方登录?</strong></summary>
可以在预设供应商里面添加一个官方供应商。切换过去之后,执行一遍 Log out / Log in 流程,之后便可以在官方供应商和第三方供应商之间随意切换。CodeX 可以在不同官方供应商之间进行切换,方便多个 Plus 或者 Team 账号之间切换。
</details>
<details>
<summary><strong>我的数据存储在哪里?</strong></summary>
- **数据库**`~/.cc-switch/cc-switch.db`(SQLite — 供应商、MCP、提示词、技能)
- **本地设置**`~/.cc-switch/settings.json`(设备级 UI 偏好设置)
- **备份**`~/.cc-switch/backups/`(自动轮换,保留最近 10 个)
- **SKILLS**`~/.cc-switch/skills/`(默认通过软链接连接到对应应用)
- **技能备份**`~/.cc-switch/skill-backups/`(卸载前自动创建,保留最近 20 个)
</details>
<details>
<summary><strong>LinuxWayland + NVIDIA):网页内容点不动、缩放后黑屏</strong></summary>
AppImage 会强制 `GDK_BACKEND=x11`(走 XWayland)以规避历史上的原生 Wayland 崩溃。但在较新的 Wayland + NVIDIA 环境下,这会导致网页内容区点不动(标题栏按钮仍可点)、窗口缩放后黑屏。可用内置的逃生开关切回原生 Wayland:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
如果你是从桌面图标启动的,请把它写进 `.desktop``Exec=` 行(如 `env CC_SWITCH_GDK_BACKEND=wayland /path/to/AppImage`),或在会话环境中设置。该变量是通用的:在 tiling Wayland 合成器(sway/Hyprland)下若出现点击失效,可反过来设 `CC_SWITCH_GDK_BACKEND=x11`。不设置则保持默认行为。
</details>
## 文档
如需了解各项功能的详细使用方法,请查阅 **[用户手册](docs/user-manual/zh/README.md)** — 涵盖供应商管理、MCP/Prompts/Skills、代理与故障转移等全部功能。
## 快速开始
### 基本使用
1. **添加供应商**:点击"添加供应商" → 选择预设或创建自定义配置
2. **切换供应商**
- 主界面:选择供应商 → 点击"启用"
- 系统托盘:直接点击供应商名称(立即生效)
3. **生效方式**:重启终端或对应的 CLI 工具以应用更改(CLaude Code 无需重启)
4. **恢复官方登录**:添加"官方登录"预设,重启 CLI 工具后按照其登录/OAuth 流程操作
### MCP、Prompts、Skills 与会话
- **MCP**:点击"MCP"按钮 → 通过模板或自定义配置添加服务器 → 切换各应用同步开关
- **Prompts**:点击"Prompts" → 使用 Markdown 编辑器创建预设 → 激活后同步到 live 文件
- **Skills**:点击"Skills" → 浏览 GitHub 仓库 → 一键安装到支持的应用
- **会话**:点击"Sessions" → 浏览、搜索和恢复支持的会话来源
> **注意**:首次启动可以手动导入现有 CLI 工具配置作为默认供应商。
## 下载安装
### 系统要求
- **Windows**: Windows 10 及以上
- **macOS**: macOS 10.15 (Catalina) 及以上
- **Linux**: Ubuntu 22.04+ / Debian 11+ / Fedora 34+ 等主流发行版
- **Windows**Windows 10 及以上
- **macOS**macOS 12 (Monterey) 及以上
- **Linux**Ubuntu 22.04+ / Debian 11+ / Fedora 34+ 等主流发行版
### Windows 用户
从 [Releases](../../releases) 页面下载最新版本的 `CC-Switch-v{版本号}-Windows.msi` 安装包或 `CC-Switch-v{版本号}-Windows-Portable.zip` 绿色版。
从 [Releases](../../releases) 页面下载最新版本的 `CC-Switch-v{版本号}-Windows.msi` 安装包或 `CC-Switch-v{版本号}-Windows-Portable.zip` 绿色版。
### macOS 用户
**方式一:通过 Homebrew 安装(推荐)**
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
@@ -176,11 +372,11 @@ brew upgrade --cask cc-switch
**方式二:手动下载**
从 [Releases](../../releases) 页面下载 `CC-Switch-v{版本号}-macOS.zip` 解压使用
从 [Releases](../../releases) 页面下载 `CC-Switch-v{版本号}-macOS.dmg`(推荐)或 `.zip`
> **注意**由于作者没有苹果开发者账号,首次打开可能出现"未知开发者"警告,请先关闭,然后前往"系统设置" → "隐私与安全性" → 点击"仍要打开",之后便可以正常打开
> **注意**CC Switch macOS 版本已通过 Apple 代码签名和公证,可直接安装打开
### ArchLinux 用户
### Arch Linux 用户
**通过 paru 安装(推荐)**
@@ -190,91 +386,16 @@ paru -S cc-switch-bin
### Linux 用户
从 [Releases](../../releases) 页面下载最新版本的 `CC-Switch-v{版本号}-Linux.deb` 包或者 `CC-Switch-v{版本号}-Linux.AppImage` 安装包
从 [Releases](../../releases) 页面下载最新版本的 Linux 安装包
## 快速开始
- `CC-Switch-v{版本号}-Linux.deb`Debian/Ubuntu
- `CC-Switch-v{版本号}-Linux.rpm`Fedora/RHEL/openSUSE
- `CC-Switch-v{版本号}-Linux.AppImage`(通用)
### 基本使用
> **Flatpak**:官方 Release 不包含 Flatpak 包。如需使用,可从 `.deb` 自行构建 — 参见 [`flatpak/README.md`](flatpak/README.md)。
1. **添加供应商**:点击"添加供应商" → 选择预设或创建自定义配置
2. **切换供应商**
- 主界面:选择供应商 → 点击"启用"
- 系统托盘:直接点击供应商名称(立即生效)
3. **生效方式**:重启终端或 Claude Code / Codex / Gemini 客户端以应用更改
4. **恢复官方登录**:选择"官方登录"预设(Claude/Codex)或"Google 官方"预设(Gemini),重启对应客户端后按照其登录/OAuth 流程操作
### MCP 管理
- **位置**:点击右上角"MCP"按钮
- **添加服务器**
- 使用内置模板(mcp-fetch、mcp-filesystem 等)
- 支持 stdio / http / sse 三种传输类型
- 为不同应用配置独立的 MCP 服务器
- **启用/禁用**:切换开关以控制哪些服务器同步到 live 配置
- **同步**:启用的服务器自动同步到各应用的 live 文件
- **导入/导出**:支持从 Claude/Codex/Gemini 配置文件导入现有 MCP 服务器
### Skills 管理(v3.7.0 新增)
- **位置**:点击右上角"Skills"按钮
- **发现技能**
- 自动扫描预配置的 GitHub 仓库(Anthropic 官方、ComposioHQ、社区等)
- 添加自定义仓库(支持子目录扫描)
- **安装技能**:点击"安装"一键安装到 `~/.claude/skills/`
- **卸载技能**:点击"卸载"安全移除并清理状态
- **管理仓库**:添加/删除自定义 GitHub 仓库
### Prompts 管理(v3.7.0 新增)
- **位置**:点击右上角"Prompts"按钮
- **创建预设**
- 创建无限数量的系统提示词预设
- 使用 Markdown 编辑器编写提示词(语法高亮 + 实时预览)
- **切换预设**:选择预设 → 点击"激活"立即应用
- **同步机制**
- Claude: `~/.claude/CLAUDE.md`
- Codex: `~/.codex/AGENTS.md`
- Gemini: `~/.gemini/GEMINI.md`
- **保护机制**:切换前自动保存当前提示词内容,保留手动修改
### 配置文件
**Claude Code**
- Live 配置:`~/.claude/settings.json`(或 `claude.json`
- API key 字段:`env.ANTHROPIC_AUTH_TOKEN``env.ANTHROPIC_API_KEY`
- MCP 服务器:`~/.claude.json``mcpServers`
**Codex**
- Live 配置:`~/.codex/auth.json`(必需)+ `config.toml`(可选)
- API key 字段:`auth.json` 中的 `OPENAI_API_KEY`
- MCP 服务器:`~/.codex/config.toml``[mcp_servers]`
**Gemini**
- Live 配置:`~/.gemini/.env`API Key+ `~/.gemini/settings.json`(保存认证模式)
- API key 字段:`.env` 文件中的 `GEMINI_API_KEY``GOOGLE_GEMINI_API_KEY`
- 环境变量:支持 `GOOGLE_GEMINI_BASE_URL``GEMINI_MODEL` 等自定义变量
- MCP 服务器:`~/.gemini/settings.json``mcpServers`
- 托盘快速切换:每次切换供应商都会重写 `~/.gemini/.env`,无需重启 Gemini CLI 即可生效
**CC Switch 存储(v3.8.0 新架构)**
- 数据库(SSOT):`~/.cc-switch/cc-switch.db`SQLite,存储供应商、MCP、Prompts、Skills
- 本地设置:`~/.cc-switch/settings.json`(设备级设置)
- 备份:`~/.cc-switch/backups/`(自动轮换,保留 10 个)
### 云同步设置
1. 前往设置 → "自定义配置目录"
2. 选择您的云同步文件夹(Dropbox、OneDrive、iCloud、坚果云等)
3. 重启应用以应用
4. 在其他设备上重复操作以启用跨设备同步
> **注意**:首次启动会自动导入现有 Claude/Codex 配置作为默认供应商。
## 架构总览
<details>
<summary><strong>架构总览</strong></summary>
### 设计原则
@@ -309,16 +430,15 @@ paru -S cc-switch-bin
- **ProviderService**:供应商增删改查、切换、回填、排序
- **McpService**MCP 服务器管理、导入导出、live 文件同步
- **ProxyService**:本地 Proxy 模式,支持热切换和格式转换
- **SessionManager**:全应用会话历史浏览
- **ConfigService**:配置导入导出、备份轮换
- **SpeedtestService**API 端点延迟测量
**v3.6 重构**
</details>
- 后端:5 阶段重构(错误处理 → 命令拆分 → 测试 → 服务 → 并发)
- 前端:4 阶段重构(测试基础 → hooks → 组件 → 清理)
- 测试:100% hooks 覆盖 + 集成测试(vitest + MSW
## 开发
<details>
<summary><strong>开发指南</strong></summary>
### 环境要求
@@ -379,7 +499,7 @@ cargo test test_name
cargo test --features test-hooks
```
### 测试说明v3.6 新增)
### 测试说明
**前端测试**
@@ -387,18 +507,6 @@ cargo test --features test-hooks
- 使用 **MSW (Mock Service Worker)** 模拟 Tauri API 调用
- 使用 **@testing-library/react** 进行组件测试
**测试覆盖**
- Hooks 单元测试(100% 覆盖)
- `useProviderActions` - 供应商操作
- `useMcpActions` - MCP 管理
- `useSettings` 系列 - 设置管理
- `useImportExport` - 导入导出
- 集成测试
- App 主应用流程
- SettingsDialog 完整交互
- MCP 面板功能
**运行测试**
```bash
@@ -412,49 +520,56 @@ pnpm test:unit:watch
pnpm test:unit --coverage
```
## 技术栈
### 技术栈
**前端**React 18 · TypeScript · Vite · TailwindCSS 4 · TanStack Query v5 · react-i18next · react-hook-form · zod · shadcn/ui · @dnd-kit
**前端**React 18 · TypeScript · Vite · TailwindCSS 3.4 · TanStack Query v5 · react-i18next · react-hook-form · zod · shadcn/ui · @dnd-kit
**后端**Tauri 2.8 · Rust · serde · tokio · thiserror · tauri-plugin-updater/process/dialog/store/log
**测试**vitest · MSW · @testing-library/react
## 项目结构
</details>
<details>
<summary><strong>项目结构</strong></summary>
```
├── src/ # 前端 (React + TypeScript)
│ ├── components/ # UI 组件 (providers/settings/mcp/ui)
│ ├── hooks/ # 自定义 hooks (业务逻辑)
├── src/ # 前端 (React + TypeScript)
│ ├── components/
│ ├── providers/ # 供应商管理
│ │ ├── mcp/ # MCP 面板
│ │ ├── prompts/ # Prompts 管理
│ │ ├── skills/ # Skills 管理
│ │ ├── sessions/ # 会话管理器
│ │ ├── proxy/ # Proxy 模式面板
│ │ ├── openclaw/ # OpenClaw 配置面板
│ │ ├── settings/ # 设置(终端/备份/关于)
│ │ ├── deeplink/ # Deep Link 导入
│ │ ├── env/ # 环境变量管理
│ │ ├── universal/ # 跨应用配置
│ │ ├── usage/ # 用量统计
│ │ └── ui/ # shadcn/ui 组件库
│ ├── hooks/ # 自定义 hooks(业务逻辑)
│ ├── lib/
│ │ ├── api/ # Tauri API 封装(类型安全)
│ │ └── query/ # TanStack Query 配置
│ ├── i18n/locales/ # 翻译 (zh/en)
│ ├── config/ # 预设 (providers/mcp)
│ └── types/ # TypeScript 类型定义
├── src-tauri/ # 后端 (Rust)
│ │ ├── api/ # Tauri API 封装(类型安全)
│ │ └── query/ # TanStack Query 配置
│ ├── locales/ # 翻译 (zh/zh-TW/en/ja)
│ ├── config/ # 预设 (providers/mcp)
│ └── types/ # TypeScript 类型定义
├── src-tauri/ # 后端 (Rust)
│ └── src/
│ ├── commands/ # Tauri 命令层(按领域)
│ ├── services/ # 业务逻辑层
│ ├── app_config.rs # 配置数据模型
│ ├── provider.rs # 供应商领域模型
│ ├── mcp.rs # MCP 同步与校验
── lib.rs # 应用入口 & 托盘菜单
├── tests/ # 前端测试
│ ├── hooks/ # 单元测试
│ └── components/ # 集成测试
└── assets/ # 截图 & 合作商资源
│ ├── commands/ # Tauri 命令层(按领域)
│ ├── services/ # 业务逻辑层
│ ├── database/ # SQLite DAO 层
│ ├── proxy/ # Proxy 模块
│ ├── session_manager/ # 会话管理
── deeplink/ # Deep Link 处理
│ └── mcp/ # MCP 同步模块
├── tests/ # 前端测试
└── assets/ # 截图 & 合作商资源
```
## 更新日志
查看 [CHANGELOG.md](CHANGELOG.md) 了解版本更新详情。
## Electron 旧版
[Releases](../../releases) 里保留 v2.0.3 Electron 旧版
如果需要旧版 Electron 代码,可以拉取 electron-legacy 分支
</details>
## 贡献
@@ -465,7 +580,8 @@ pnpm test:unit --coverage
- 通过类型检查:`pnpm typecheck`
- 通过格式检查:`pnpm format:check`
- 通过单元测试:`pnpm test:unit`
- 💡 新功能开发前,欢迎先开 issue 讨论实现方案
新功能开发前,欢迎先开 Issue 讨论实现方案,不适合项目的功能性 PR 有可能会被关闭。
## Star History
+58
View File
@@ -0,0 +1,58 @@
# Security Policy / 安全策略
## Supported Versions / 支持的版本
Only the latest release of CC Switch receives security updates.
仅最新版本的 CC Switch 会收到安全更新。
| Version / 版本 | Supported / 是否支持 |
|----------------|---------------------|
| Latest 3.x | ✅ Yes / 是 |
| < 3.0 | ❌ No / 否 |
## Reporting a Vulnerability / 报告漏洞
**Please do NOT report security vulnerabilities through public GitHub issues.**
**请不要通过公开的 GitHub Issue 报告安全漏洞。**
Instead, please report them through [GitHub Security Advisories](https://github.com/farion1231/cc-switch/security/advisories/new).
请通过 [GitHub 安全公告](https://github.com/farion1231/cc-switch/security/advisories/new) 进行报告。
When reporting, please include:
报告时请包含以下信息:
- A description of the vulnerability / 漏洞描述
- Steps to reproduce / 复现步骤
- Potential impact / 潜在影响
- Affected versions / 受影响版本
## Response Timeline / 响应时间
- **Acknowledgment / 确认**: within 48 hours / 48 小时内
- **Initial assessment / 初步评估**: within 7 days / 7 天内
- **Fix for critical issues / 关键问题修复**: within 14 days / 14 天内
## Disclosure Policy / 披露政策
We follow a coordinated disclosure process:
我们遵循协调披露流程:
1. The reporter submits the vulnerability privately. / 报告者私下提交漏洞。
2. We confirm and work on a fix. / 我们确认并修复漏洞。
3. A patch release is published. / 发布修复版本。
4. The vulnerability is publicly disclosed. / 公开披露漏洞详情。
Reporters will be credited in the release notes unless they prefer to remain anonymous.
除非报告者希望匿名,否则将在发布说明中致谢。
## Security Updates / 安全更新
Security fixes are released as patch versions and announced via [GitHub Releases](https://github.com/farion1231/cc-switch/releases). We recommend always updating to the latest version.
安全修复通过补丁版本发布,并通过 [GitHub Releases](https://github.com/farion1231/cc-switch/releases) 通知。建议始终更新到最新版本。
+59
View File
@@ -0,0 +1,59 @@
# Support / 获取帮助
> [中文版本](#获取帮助)
## How to Get Help
CC Switch is an open-source project maintained by volunteers. We're happy to help, but please use the right channel so we can respond efficiently.
### Before Asking
1. **Read the [FAQ](https://github.com/farion1231/cc-switch#faq)** — most common questions are answered there.
2. **Search [existing issues](https://github.com/farion1231/cc-switch/issues)** (including closed ones) — someone may have had the same question.
### Asking a Question
- **Usage or configuration questions**: [Open a Question issue](https://github.com/farion1231/cc-switch/issues/new?template=question.yml)
- **General discussion**: [GitHub Discussions](https://github.com/farion1231/cc-switch/discussions)
### Reporting Problems
- **Bug reports**: [Open a Bug Report](https://github.com/farion1231/cc-switch/issues/new?template=bug_report.yml)
- **Documentation issues**: [Open a Doc Issue](https://github.com/farion1231/cc-switch/issues/new?template=doc_issue.yml)
- **Security vulnerabilities**: Please do NOT use public issues. See our [Security Policy](./SECURITY.md).
### Feature Requests
- [Submit a Feature Request](https://github.com/farion1231/cc-switch/issues/new?template=feature_request.yml)
- Please open an issue for discussion before submitting a PR for new features.
---
# 获取帮助
> [English Version](#support--获取帮助)
## 如何获取帮助
CC Switch 是一个由志愿者维护的开源项目。我们很乐意提供帮助,但请使用合适的渠道,以便我们高效响应。
### 提问之前
1. **阅读 [常见问题](https://github.com/farion1231/cc-switch#常见问题)** — 大多数常见问题都已在其中解答。
2. **搜索 [已有的 Issue](https://github.com/farion1231/cc-switch/issues)**(包括已关闭的) — 可能已经有人问过相同的问题。
### 提问
- **使用或配置问题**[提交问题 Issue](https://github.com/farion1231/cc-switch/issues/new?template=question.yml)
- **一般讨论**[GitHub 讨论区](https://github.com/farion1231/cc-switch/discussions)
### 报告问题
- **Bug 报告**[提交 Bug 报告](https://github.com/farion1231/cc-switch/issues/new?template=bug_report.yml)
- **文档问题**[提交文档问题](https://github.com/farion1231/cc-switch/issues/new?template=doc_issue.yml)
- **安全漏洞**:请不要使用公开 Issue。请参阅我们的[安全策略](./SECURITY.md)。
### 功能请求
- [提交功能请求](https://github.com/farion1231/cc-switch/issues/new?template=feature_request.yml)
- 提交新功能的 PR 之前,请先开 Issue 讨论。
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

After

Width:  |  Height:  |  Size: 264 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

After

Width:  |  Height:  |  Size: 299 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 902 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 895 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 415 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

+63
View File
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="_图层_2" data-name="图层 2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1075.78 240.6">
<defs>
<style>
.cls-1 {
fill: #068cde;
}
.cls-2 {
fill: #02a4fd;
}
.cls-3 {
fill: #fff;
}
.cls-4 {
fill: #02a6ff;
}
</style>
</defs>
<g id="_图层_1-2" data-name="图层 1">
<path class="cls-1" d="M226.14,157.63c-3.62,0-7.24,0-10.95,0v-24.96c5.2,0,10.17,0,15.13,0,5.55-.01,8.52-4.01,10.18-8.16,1.34-3.37,1.36-7.51-1.34-11.1-3.16-4.2-7.23-5.72-12.25-5.63-3.87.07-7.74.01-11.66.01v-24.79c6.56-.43,12.93.45,19.3-1.13.4-.42.85-1.05,1.44-1.49,4.61-3.47,6.48-9.22,4.67-14.51-1.63-4.76-6.67-8.03-12.22-7.99-4.37.03-8.74,0-13.42,0,0-5.79.1-11.16-.04-16.54-.08-3.23-1.09-6.23-3.22-8.79-7.6-9.17-17.84-6.02-28.13-6.29-.39-.23-.63-1.14-.45-2.35.73-4.72.37-9.44-.24-14.13-.51-3.95-5.79-9.24-9.1-9.56-10.42-1-15.88,5.21-15.83,14.89.02,3.54,0,7.08,0,10.92h-24.44c-.76-1.03-.45-2.13-.42-3.19.15-5.2.71-10.35-1.11-15.5-2.15-6.08-11.68-9.27-17.05-5.79-5.27,3.41-7.22,7.95-6.99,13.99.14,3.56.53,7.22-.44,10.6h-23.98c-.22-.38-.37-.51-.37-.66-.05-4.56,0-9.12-.14-13.68-.15-5.18-4.72-10.76-9.31-11.57-8.81-1.55-15.64,4.23-15.64,13.24,0,4.11,0,8.21,0,12.61-4.92,0-9.32.08-13.72-.02-10.41-.22-18.81,7.79-17.84,18.57.39,4.32.06,8.7.06,13.34-5.17,0-9.9-.05-14.63.01-5.36.07-11.08,5.57-11.83,10.1-1.39,8.44,6.23,15.25,14.55,14.78,3.86-.22,7.74-.04,11.75-.04v24.92c-4.45,0-8.67-.07-12.89.02-3.2.07-6.5.62-8.75,2.93-3.6,3.69-6.1,8.11-4.12,13.5,2.13,5.8,6.42,8.43,12.98,8.43,4.21,0,8.42,0,12.83,0v24.95c-3.48,0-6.79-.12-10.08.03-3.74.18-7.43.36-10.78,2.69-4.11,2.87-6.48,8.21-5.32,12.83,1.1,4.36,7.17,9.83,11.59,9.41,4.82-.46,9.72-.1,14.69-.1,0,5.18.51,9.88-.1,14.44-1.36,10,8.64,18.06,17.22,17.5,4.62-.3,9.28-.05,14.15-.05,1.26,9.11-3.28,19.95,9.5,25.9,10.27,1.43,15.74-3.33,15.75-15.14,0-3.45,0-6.9,0-10.55h24.94c0,3.39,0,6.6,0,9.8,0,3.81.26,7.41,2.73,10.76,3.09,4.2,8.64,6.68,14,4.87,3.62-1.22,8.31-5.43,8.3-10.7,0-4.85,0-9.7,0-14.7h24.92c0,3.98-.14,7.7.03,11.41.22,4.83,1.4,9.35,5.68,12.32,5.16,3.59,12.81,2.96,17.28-2.41,3.93-7.43,2.05-14.57,2.39-21.58,5.71,0,11.1.03,16.49-.02,1.98-.02,4.05-.06,5.8-1.09,6.78-3.99,9.8-9.94,9.36-17.81-.23-4.18-.04-8.39-.04-12.56,8.59-1.68,18.23,2.96,24.73-6.3.08-.31.31-1.1.5-1.9.97-4.19,1.82-8.06-1.59-12.01-3.49-4.05-7.66-5.05-12.52-5.04ZM168.3,160.54c0,3.41-1.48,4.58-4.69,4.49-4.41-.12-8.82-.09-13.23-.05-3.15.03-4.43-1.39-4.41-4.56.06-16.85.02-33.69-.03-50.54,0-.99.44-2.13-.73-3.15-4.49,13.97-8.94,27.8-13.44,41.79h-21.8c-4.39-13.78-8.8-27.62-13.55-42.54-.15,1.94-.29,2.89-.29,3.84-.01,16.68-.08,33.36.04,50.04.03,3.7-1.18,5.38-5.05,5.16-5.51-.31-11.08.38-16.22-.44-1.24-1.59-1.21-2.95-1.21-4.26.07-27.3.18-54.6.22-81.9,0-2.16.89-3.46,2.97-3.48,9.9-.06,19.8,0,29.7.05.31,0,.63.19,1.39.44,4.22,14.29,8.51,28.79,12.8,43.3.29.05.58.1.87.15,4.53-14.59,9.07-29.17,13.66-43.95,10.35,0,20.48-.03,30.62.03,1.76.01,2.38,1.37,2.42,2.92.08,2.57.1,5.14.1,7.71-.06,24.98-.16,49.95-.15,74.93Z"/>
<rect class="cls-4" x="48.86" y="48.46" width="143.67" height="143.67" rx="10.57" ry="10.57"/>
<path class="cls-3" d="M165.55,75.28c-10.14-.06-20.27-.03-30.62-.03-4.59,14.78-9.12,29.36-13.66,43.95-.29-.05-.58-.1-.87-.15-4.29-14.51-8.58-29.01-12.8-43.3-.77-.25-1.08-.44-1.39-.44-9.9-.04-19.8-.1-29.7-.05-2.08.01-2.96,1.32-2.97,3.48-.04,27.3-.15,54.6-.22,81.9,0,1.31-.03,2.67,1.21,4.26,5.13.82,10.7.13,16.22.44,3.87.22,5.07-1.46,5.05-5.16-.12-16.68-.06-33.36-.04-50.04,0-.95.14-1.9.29-3.84,4.75,14.91,9.16,28.76,13.55,42.54h21.8c4.5-13.99,8.94-27.82,13.44-41.79,1.18,1.01.73,2.16.73,3.15.04,16.85.09,33.69.03,50.54-.01,3.17,1.26,4.59,4.41,4.56,4.41-.04,8.82-.07,13.23.05,3.21.09,4.69-1.08,4.69-4.49-.01-24.98.09-49.95.15-74.93,0-2.57-.02-5.14-.1-7.71-.05-1.55-.67-2.91-2.42-2.92Z"/>
<g>
<path class="cls-2" d="M372.64,135.48c-.13-.49-.54-.78-.71-.89-7.15-4.87-14.15-9.95-21.35-14.75-4.85-3.24-7.95-5.93-8.98-6.85-3.54-3.13-6.16-6.05-7.88-8.11,18.27.05,31.65-.03,32.44-.05.12,0,.6-.03.98-.42.22-.22.31-.45.35-.59.02-4.96.04-9.91.06-14.87,0-.78-.62-1.42-1.39-1.42-8.12.04-16.23.08-24.35.12,4.03-4.67,7.45-8.18,9.86-10.55,2.43-2.39,4.46-5.14,6.77-7.64,1.93-2.09,4.11-4.37,3.5-6.38-.2-.66-.63-1.08-.87-1.29-3.46-2.9-6.93-5.8-10.39-8.7-.41-.25-1.2-.63-2.04-.42-.82.21-1.3.88-1.47,1.12-3.4,4.75-5.17,7.07-5.2,7.12,0,0-1.32,2.51-13.36,16.27-.12.14-.48.54-.48,1.08,0,.5.31.88.49,1.07,2.96,2.73,5.93,5.46,8.89,8.2h-10.94v-37.5c0-.78-.62-1.42-1.39-1.42h-15.19c-.77,0-1.39.64-1.39,1.42v37.5h-13.87l10.91-9.45c.55-.48.65-1.31.23-1.91-1.08-1.54-2.47-3.35-4.11-5.37-1.64-2.02-3.6-4.28-5.8-6.7-2.13-2.43-4.13-4.59-5.93-6.43-1.8-1.83-3.5-3.43-5.06-4.75-.53-.45-1.31-.43-1.82.04l-10.51,9.67c-.29.27-.46.65-.46,1.05s.17.78.46,1.05c.96.88,2.1,2.06,3.39,3.49,1.33,1.47,2.71,3.04,4.15,4.7,1.44,1.66,2.87,3.36,4.26,5.04,1.41,1.71,2.71,3.27,3.89,4.68,1.17,1.39,2.11,2.54,2.83,3.44.86,1.09,1.04,1.35,1.04,1.35.02.03.03.06.05.09h-23.14c-.77,0-1.39.64-1.39,1.42v14.45c0,.78.62,1.42,1.39,1.42,10.73.14,21.47.29,32.2.43-3.44,3.44-6.64,6.34-9.41,8.73-4.74,4.08-8.53,6.9-9.53,7.64-5.15,3.8-7.72,5.7-9.46,6.47,0,0-1.99,2.06-9.47,6.03-.37.2-.63.55-.72.96-.09.41.01.84.27,1.18,3.31,4.84,6.62,9.68,9.93,14.51,2.17-1.39,5.05-3.3,8.34-5.71,1.13-.83,4.24-3.11,8.34-6.5,6.58-5.43,8.21-7.48,15.62-13.59,1.43-1.18,2.61-2.13,3.36-2.73v32.48c0,.78.62,1.42,1.39,1.42h15.19c.77,0,1.39-.64,1.39-1.42v-32.91c2.78,2.65,6.21,5.83,10.21,9.33,10.52,9.2,9.2,6.82,12.78,10.6,0,0,7.52,6.23,12.33,9.29.65.41,1.5.21,1.91-.45l8.68-14c.21-.34.27-.75.17-1.13Z"/>
<g>
<path class="cls-2" d="M481.65,98.3h-43.96c-.78,0-1.42.63-1.42,1.42v51.72c0,.78.63,1.42,1.42,1.42h43.96c.78,0,1.42-.63,1.42-1.42v-51.72c0-.78-.63-1.42-1.42-1.42ZM467.34,137.4h-15.33v-4.1h15.33v4.1ZM467.34,118.08h-15.33v-4.1h15.33v4.1Z"/>
<path class="cls-2" d="M485.91,80.91h-8.67v-6.03h6.54c.78,0,1.42-.63,1.42-1.42v-13.3c0-.78-.63-1.42-1.42-1.42h-6.54v-9.15c0-.78-.63-1.42-1.42-1.42h-12.56c-.78,0-1.42.63-1.42,1.42v9.15h-4.46v-9.15c0-.78-.63-1.42-1.42-1.42h-12.45c-.78,0-1.42.63-1.42,1.42v9.15h-5.54c-.56,0-1.04.32-1.27.79v-5.86c0-.78-.63-1.42-1.42-1.42h-48.55c-.78,0-1.42.63-1.42,1.42v12.96c0,.78.63,1.42,1.42,1.42h11.48v5.24h-9.91c-.78,0-1.42.63-1.42,1.42v76.27c0,.78.63,1.42,1.42,1.42h46.2c.78,0,1.42-.63,1.42-1.42v-54.75c.26.29.63.46,1.05.46h50.35c.78,0,1.42-.63,1.42-1.42v-12.96c0-.78-.63-1.42-1.42-1.42ZM421.7,136.6h-23.18v-3.98h23.18v3.98ZM421.7,117.28h-19.16c1.54-2.24,2.74-4.23,3.57-5.91.83-1.69,1.57-3.33,2.19-4.91,1.19-3.22,1.77-7.95,1.77-14.47v-3.02h.08v13.36c0,3.98.93,7.04,2.78,9.08,1.84,2.04,4.77,3.29,8.61,3.69l.17.03v2.16ZM442.11,80.91h-6.54c-.42,0-.79.18-1.05.46v-6.66c0-.78-.63-1.42-1.42-1.42h-9.57v-5.24h10.36c.56,0,1.04-.32,1.27-.79v6.2c0,.78.63,1.42,1.42,1.42h5.54v6.03ZM461.85,80.91h-4.46v-6.03h4.46v6.03Z"/>
</g>
<path class="cls-2" d="M608.47,127.84c-4.56-1.17-9.11-2.33-13.67-3.5-.16-20.74-.33-41.47-.49-62.21,0-.79-.63-1.43-1.42-1.43h-34.31v-10.58c0-.79-.63-1.43-1.42-1.43h-14.6c-.78,0-1.42.64-1.42,1.43v10.58h-32.96c-.78,0-1.42.64-1.42,1.43v66c0,.79.63,1.43,1.42,1.43h32.96v6.12c0,3.15.28,5.89.83,8.12.57,2.35,1.57,4.34,2.95,5.92,1.39,1.59,3.28,2.81,5.6,3.61,2.2.76,4.97,1.27,8.25,1.51,1.43.07,3.35.15,5.76.23,2.44.08,4.95.11,7.46.11s5-.02,7.33-.06c2.4-.04,4.24-.14,5.62-.29,3.19-.31,5.93-.72,8.16-1.23,3.05-.7,5.13-2.13,5.99-2.65,1.51-.92,3.64-2.22,5.55-4.66,1.81-2.3,2.48-4.4,3.28-6.89.81-2.52,1.79-5.71,1.06-9.61-.15-.82-.35-1.48-.5-1.94ZM541.15,112.97h-17.16v-9.73h17.16v9.73ZM541.15,87.12h-17.16v-9.84h17.16v9.84ZM558.59,77.28h18.51v9.84h-18.51v-9.84ZM558.59,103.24h18.51v9.73h-18.51v-9.73ZM590.3,133.5c-.06.19-.43,1.31-.83,1.94-1.12,1.76-3.83,1.83-12.61,1.89-7.06.05-.21-.03-7.33-.06-5.89-.02-7.51.05-8.56-1.22-1.02-1.24-1.31-3.54-1.44-4.56-.1-.8-.12-1.48-.11-1.95,10.48.04,20.96.08,31.44.12.02.9-.05,2.27-.56,3.83Z"/>
<path class="cls-2" d="M721.16,93.62h-39.92v-.2c6.24-3.1,12.4-6.63,18.31-10.49,6.14-4.01,12.31-8.35,18.34-12.9.35-.27.56-.69.56-1.13v-14.44c0-.78-.63-1.42-1.42-1.42h-87.02c-.78,0-1.42.63-1.42,1.42v14.32c0,.78.63,1.42,1.42,1.42h54.17c-.81.75-2.1,1.91-3.75,3.22-3.49,2.77-5.95,4.13-9.75,6.58-1.85,1.19-4.54,2.98-7.75,5.33-.03,2.76-.06,5.52-.1,8.29h-41.41c-.78,0-1.41.63-1.41,1.42v15c0,.78.63,1.42,1.41,1.42h41.41v21.77c0,1.22-.04,2.25-.11,3.05-.05.57-.06,1.11-.42,1.34-.35.22-.82.04-1.08-.04-1.08-.36-2.28-.11-3.42-.17-2.27-.12-2.51.11-5,.04-2.39-.07-4.79.16-7.17-.08-.27-.03-.93-.1-1.29.29-.44.48-.17,1.38-.04,1.75,1.43,4.35,2.86,8.69,4.29,13.04.11.5.34,1.22.92,1.83,1.16,1.24,2.98,1.26,4.12,1.25,9.2-.06,11.21-.21,11.21-.21,4.83-.36,5.78-.39,7.58-.96,1.76-.56,3.69-1.19,5.38-2.95,1.68-1.74,2.36-3.6,2.76-5.45.44-2.03.66-4.52.66-7.4v-27.11h39.92c.78,0,1.41-.63,1.41-1.42v-15c0-.78-.63-1.42-1.41-1.42Z"/>
<path class="cls-2" d="M839.47,131.72h-40.52v-59.68h33.89c.78,0,1.42-.63,1.42-1.42v-15.57c0-.78-.63-1.42-1.42-1.42h-86.74c-.78,0-1.42.63-1.42,1.42v15.57c0,.78.63,1.42,1.42,1.42h33.55v59.68h-40.41c-.78,0-1.42.63-1.42,1.42v15.35c0,.78.63,1.42,1.42,1.42h100.22c.78,0,1.42-.63,1.42-1.42v-15.35c0-.78-.63-1.42-1.42-1.42Z"/>
<path class="cls-2" d="M955.36,61.13h-39.83c.46-1.11.9-2.22,1.3-3.32.65-1.74,1.31-3.52,2-5.34.14-.37.12-.79-.06-1.14-.18-.35-.5-.62-.88-.72l-14.29-3.98c-.73-.2-1.49.2-1.73.93-2.48,7.62-5.66,15.09-9.45,22.22-3,5.64-6.11,10.87-9.28,15.62v-12.58c1.19-3.03,2.37-6.23,3.52-9.52,1.16-3.3,2.38-6.9,3.73-10.99.12-.36.09-.76-.09-1.1-.18-.34-.48-.59-.85-.7l-13.84-4.21c-.36-.11-.76-.07-1.09.11-.33.18-.58.49-.68.86-1.13,4.04-2.62,8.43-4.42,13.05-1.81,4.65-3.82,9.34-5.97,13.95-2.16,4.62-4.45,9.15-6.82,13.44-2.37,4.3-4.71,8.14-6.96,11.42-.42.61-.3,1.43.27,1.9l11.21,9.21c.31.26.72.37,1.12.31.4-.06.75-.29.97-.63l1.97-3.03v46.25c0,.78.63,1.42,1.42,1.42h15.09c.78,0,1.42-.63,1.42-1.42v-57.07l8.02,6.03c.62.47,1.5.35,1.98-.27,2.9-3.8,5.62-7.74,8.08-11.71,2.03-3.29,3.95-6.68,5.73-10.12v73.83c0,.78.63,1.42,1.42,1.42h14.98c.78,0,1.42-.63,1.42-1.42v-20.29h27.52c.78,0,1.42-.63,1.42-1.42v-15.12c0-.78-.63-1.42-1.42-1.42h-27.52v-10.01h25.11c.78,0,1.42-.63,1.42-1.42v-14.89c0-.78-.63-1.42-1.42-1.42h-25.11v-9.21h30.6c.78,0,1.42-.63,1.42-1.42v-14.66c0-.78-.63-1.42-1.42-1.42Z"/>
<path class="cls-2" d="M1074.36,137.97h-41.39v-4.55h31.04c.78,0,1.42-.63,1.42-1.42v-13.19c0-.78-.63-1.42-1.42-1.42h-2.25l8.41-9.22c.49-.53.5-1.35.02-1.89-2.83-3.22-6.98-7.17-12.38-11.75l-3.96-3.29h9.69c.78,0,1.42-.63,1.42-1.42v-10.52h8.59c.78,0,1.42-.63,1.42-1.42v-19.1c0-.78-.63-1.42-1.42-1.42h-39.96l-2.28-8.83c-.17-.67-.81-1.12-1.49-1.06l-16.17,1.36c-.42.04-.8.25-1.04.59-.24.34-.32.77-.21,1.18.61,2.31,1.17,4.58,1.68,6.75h-39.86c-.78,0-1.42.63-1.42,1.42v19.1c0,.78.63,1.42,1.42,1.42h8.47v10.52c0,.78.63,1.42,1.42,1.42h11.51c-1.07.86-2.12,1.69-3.13,2.46-1.91,1.47-3.64,2.66-5.15,3.54-1.12.66-2.24,1.28-3.31,1.84-.94.49-1.91.8-2.9.93-.38.05-.71.25-.94.55-.23.3-.33.68-.28,1.06l1.63,11.71c.1.69.68,1.21,1.38,1.22,5.55.08,11.18.06,16.74-.06,5.06-.1,10.15-.22,15.25-.36v3.26h-31.39c-.78,0-1.42.63-1.42,1.42v13.19c0,.78.63,1.42,1.42,1.42h31.39v4.55h-41.86c-.78,0-1.42.63-1.42,1.42v12.62c0,.78.63,1.42,1.42,1.42h101.32c.78,0,1.42-.63,1.42-1.42v-12.62c0-.78-.63-1.42-1.42-1.42ZM1055.75,115.62c.57.62,1.11,1.21,1.64,1.77h-24.42v-3.81c3.26-.13,6.47-.27,9.64-.4,3.37-.14,6.82-.32,10.27-.53,1.04,1.03,2.01,2.03,2.87,2.97ZM990.4,76.13v-3.3h66.73v3.3h-66.73ZM1009.78,99.75c1.14-.79,2.29-1.62,3.43-2.48,2.38-1.78,4.82-3.8,7.26-6.03h15.11l-2.47,2.47c-.29.29-.44.7-.41,1.11s.24.79.58,1.03c.92.68,1.91,1.41,2.95,2.2.21.16.43.33.66.51-5.44.39-10.57.68-15.27.87-4.02.16-7.98.26-11.83.31Z"/>
</g>
<g>
<polygon class="cls-2" points="700.41 193.09 700.29 193.09 695.84 175.52 688.42 175.52 688.42 199.6 692.65 199.6 692.65 179.03 692.76 178.9 698.35 199.6 702.12 199.6 708.05 178.9 708.05 179.03 708.05 199.6 712.28 199.6 712.28 175.52 705.2 175.52 700.41 193.09"/>
<path class="cls-2" d="M727.36,178.51c3.04.09,4.65,1.61,4.83,4.56h5.64c-.36-5.47-3.85-8.24-10.47-8.33-6.62.26-10.07,4.47-10.33,12.63.18,7.98,3.62,12.06,10.33,12.23,6.71-.09,10.2-2.78,10.47-8.07h-5.64c-.09,2.95-1.7,4.47-4.83,4.56-2.95-.17-4.52-3.08-4.7-8.72.18-5.73,1.75-8.68,4.7-8.85Z"/>
<path class="cls-2" d="M756.74,188.14c.08,2.86-.24,4.82-.98,5.86-.73,1.22-2.03,1.82-3.9,1.82s-3.21-.61-4.02-1.82c-.73-1.04-1.06-2.99-.97-5.86v-13.15h-4.87v15.1c.16,5.99,3.45,9.07,9.87,9.24,6.25-.17,9.5-3.25,9.75-9.24v-15.1h-4.87v13.15Z"/>
<polygon class="cls-2" points="782.14 188.79 792.21 188.79 792.21 184.76 782.14 184.76 782.14 179.16 792.98 179.16 792.98 175.13 776.98 175.13 776.98 199.2 793.37 199.2 793.37 195.17 782.14 195.17 782.14 188.79"/>
<rect class="cls-2" x="797.64" y="174.74" width="4.33" height="24.08"/>
<path class="cls-2" d="M822.27,188.31c-.09-1.04-.4-2.04-.94-2.99-1.34-2.6-3.8-3.9-7.38-3.9-5.19.26-7.92,3.21-8.19,8.85-.09,5.81,2.64,8.68,8.19,8.59,4.83,0,7.47-1.73,7.92-5.21h-4.7c-.45,1.48-1.52,2.17-3.22,2.08-2.06.09-3.04-1.3-2.95-4.17h11.41c0-1.13-.05-2.21-.13-3.25ZM810.99,188.18c.09-2.34,1.07-3.51,2.95-3.51,2.06,0,3.09,1.17,3.09,3.51h-6.04Z"/>
<path class="cls-2" d="M831.26,189.46c.28-3.34,1.07-5.01,2.37-5.01,1.67,0,2.6,1.08,2.79,3.25h5.3c-.19-4.24-2.84-6.45-7.96-6.63-4.93.36-7.63,3.43-8.1,9.2.37,5.78,3.07,8.75,8.1,8.93,5.02,0,7.68-2.21,7.96-6.63h-5.3c-.09,2.26-.98,3.38-2.65,3.38-1.49,0-2.33-1.8-2.51-5.41v-1.08Z"/>
<path class="cls-2" d="M927.16,189.69c.28-3.34,1.07-5.01,2.37-5.01,1.67,0,2.6,1.08,2.79,3.25h5.3c-.19-4.24-2.84-6.45-7.96-6.63-4.93.36-7.63,3.43-8.1,9.2.37,5.78,3.07,8.75,8.1,8.93,5.02,0,7.68-2.21,7.96-6.63h-5.3c-.09,2.26-.98,3.38-2.65,3.38-1.49,0-2.33-1.8-2.51-5.41v-1.08Z"/>
<path class="cls-2" d="M854.41,195.73c-1.36.26-1.97-.65-1.8-2.73v-7.81h3.37v-3.38h-3.37v-5.08c-1.56,0-3.12,0-4.69,0,0,1.69,0,3.39,0,5.08h-3.13v3.38h3.13c0,3.23-.02,6.45-.03,9.68.03.49.17,2.15,1.47,3.24.82.7,1.73.84,2.75,1,.82.13,2.18.24,3.88-.17,0-1.11,0-2.23-.01-3.34-.48.09-1,.13-1.56.13Z"/>
<path class="cls-2" d="M999.9,195.61c-1.36.26-1.97-.65-1.8-2.73v-7.81h3.37v-3.38h-3.37v-5.08c-1.56,0-3.12,0-4.69,0,0,1.69,0,3.39,0,5.08h-3.13v3.38h3.13l-.03,9.68c.03.49.17,2.15,1.47,3.24.82.7,1.73.84,2.75,1,.82.13,2.18.24,3.88-.17v-3.34c-.5.09-1.02.13-1.58.13Z"/>
<path class="cls-2" d="M863.85,184.64h-.13v-3.25h-4.7c0,.54.04,1.31.13,2.3v15.17h5.1v-9.21c.18-1.08.4-1.94.67-2.57.45-.54,1.3-.95,2.55-1.22h2.28v-4.6c-2.95-.18-4.92.95-5.91,3.39Z"/>
<path class="cls-2" d="M881.19,181.41c-5.4.26-8.23,3.21-8.49,8.85.25,5.55,3.08,8.42,8.49,8.59,5.4-.17,8.23-3.04,8.49-8.59-.25-5.64-3.08-8.59-8.49-8.85ZM881.19,195.73c-2.28,0-3.42-1.82-3.42-5.47s1.14-5.6,3.42-5.6c2.45,0,3.63,1.87,3.55,5.6,0,3.64-1.18,5.47-3.55,5.47Z"/>
<path class="cls-2" d="M908.77,185.85c-.08-.78-.14-1.32-.38-1.9-.5-1.26-1.5-1.96-1.82-2.16-1.45-.93-2.93-.77-3.33-.71-.79-.01-2.53.08-4.12,1.26-.46.34-.82.71-1.1,1.06,0-.67,0-1.34-.01-2h-5.1v17.48h5.1v-10.43c.27-2.53,1.3-3.88,3.09-4.07,2.06,0,3.09,1.36,3.09,4.07v10.43c1.56,0,3.12,0,4.68.01,0-3.79-.02-7.57-.03-11.36.01-.42,0-.99-.07-1.67Z"/>
<rect class="cls-2" x="913.06" y="174.68" width="4.81" height="4.29"/>
<rect class="cls-2" x="913.18" y="181.97" width="4.58" height="16.79"/>
<path class="cls-2" d="M950.52,188.05c-2.08-.52-3.12-1.13-3.12-1.82,0-1.04.62-1.56,1.87-1.56,1.33.09,2.04.65,2.12,1.69h4.37c-.25-3.3-2.41-4.95-6.49-4.95-4.41.35-6.7,2-6.86,4.95-.17,2.86,1.79,4.69,5.86,5.47,2.08.44,3.16,1.13,3.24,2.08,0,1.22-.75,1.82-2.24,1.82-1.58-.09-2.45-.74-2.62-1.95h-4.49c.17,3.3,2.54,4.99,7.11,5.08,4.57-.35,6.99-2.08,7.24-5.21-.67-3.47-2.66-5.34-5.99-5.6Z"/>
<path class="cls-2" d="M980.42,184.99c-.32-.09-.51-.13-.59-.13-2.84-.43-4.18-1.56-4.02-3.38.08-1.91,1.26-2.95,3.55-3.12,2.29,0,3.47,1.22,3.55,3.64h4.5c-.24-4.69-2.72-7.16-7.45-7.42-5.84.35-8.87,2.99-9.11,7.94,0,3.21,2.4,5.42,7.22,6.64.16.09.43.17.83.26,2.76.61,4.14,1.74,4.14,3.38-.08,2-1.54,3.04-4.38,3.12-2.45-.17-3.67-1.65-3.67-4.43h-4.73c-.08,5.29,2.72,7.94,8.4,7.94,6.15-.17,9.26-2.78,9.34-7.81.08-3.3-2.45-5.51-7.57-6.64Z"/>
<path class="cls-2" d="M1020.78,181.81h-3.98c0,3.43.01,6.87.02,10.3,0,.19-.07,2.13-1.58,3.1-.96.62-2.02.54-2.38.52-.37-.03-1.06-.05-1.65-.47-.81-.57-1.24-1.68-1.29-3.31v-10.15h-4.23c-.01,3.67-.03,7.34-.04,11.01-.01.42.01,1.04.21,1.75.62,2.23,2.61,4.11,4.98,4.62,2.07.45,3.82-.28,4.27-.48.4-.17.72-.36.95-.5,0,.34,0,.68.01,1.02,1.58-.01,3.15-.03,4.73-.04,0-1.2-.01-2.39-.02-3.59v-13.8Z"/>
<path class="cls-2" d="M1042.61,174.52h-4.95v9.24c-1.1-1.47-2.58-2.26-4.44-2.34-4.74.26-7.27,3.21-7.61,8.85.34,5.55,2.71,8.42,7.1,8.59,2.37,0,4.01-.87,4.95-2.6,0,.26.04.65.13,1.17v1.17h4.95c-.09-1.04-.13-2.17-.13-3.38v-20.69ZM1034.24,195.73c-2.45,0-3.64-1.82-3.55-5.47-.09-3.73,1.1-5.6,3.55-5.6,2.11.17,3.25,2.04,3.42,5.6-.17,3.47-1.31,5.29-3.42,5.47Z"/>
<rect class="cls-2" x="1046.8" y="174.52" width="4.96" height="4.29"/>
<rect class="cls-2" x="1046.92" y="181.81" width="4.71" height="16.79"/>
<path class="cls-2" d="M1063.98,181.41c-5.35.26-8.14,3.21-8.39,8.85.25,5.55,3.05,8.42,8.39,8.59,5.34-.17,8.14-3.04,8.39-8.59-.25-5.64-3.05-8.59-8.39-8.85ZM1063.98,195.73c-2.25,0-3.38-1.82-3.38-5.47s1.13-5.6,3.38-5.6c2.42,0,3.59,1.87,3.51,5.6,0,3.64-1.17,5.47-3.51,5.47Z"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 424 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 400 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 861 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+2 -1
View File
@@ -4,7 +4,7 @@
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"config": "tailwind.config.cjs",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
@@ -19,3 +19,4 @@
"hooks": "@/hooks"
}
}
+239 -776
View File
File diff suppressed because it is too large Load Diff
-169
View File
@@ -1,169 +0,0 @@
# CC Switch Rust 后端重构方案
## 目录
- [背景与现状](#背景与现状)
- [问题确认](#问题确认)
- [方案评估](#方案评估)
- [渐进式重构路线](#渐进式重构路线)
- [测试策略](#测试策略)
- [风险与对策](#风险与对策)
- [总结](#总结)
## 背景与现状
- 前端已完成重构,后端 (Tauri + Rust) 仍维持历史结构。
- 核心文件集中在 `src-tauri/src/commands.rs``lib.rs` 等超大文件中,业务逻辑与界面事件耦合严重。
- 测试覆盖率低,只有零散单元测试,缺乏集成验证。
## 问题确认
| 提案问题 | 实际情况 | 严重程度 |
| --- | --- | --- |
| `commands.rs` 过长 | ✅ 1526 行,包含 32 个命令,职责混杂 | 🔴 高 |
| `lib.rs` 缺少服务层 | ✅ 541 行,托盘/事件/业务逻辑耦合 | 🟡 中 |
| `Result<T, String>` 泛滥 | ✅ 118 处,错误上下文丢失 | 🟡 中 |
| 全局 `Mutex` 阻塞 | ✅ 31 处 `.lock()` 调用,读写不分离 | 🟡 中 |
| 配置逻辑分散 | ✅ 分布在 5 个文件 (`config`/`app_config`/`app_store`/`settings`/`codex_config`) | 🟢 低 |
代码规模分布(约 5.4k SLOC):
- `commands.rs`: 1526 行(28%)→ 第一优先级 🎯
- `lib.rs`: 541 行(10%)→ 托盘逻辑与业务耦合
- `mcp.rs`: 732 行(14%)→ 相对清晰
- `migration.rs`: 431 行(8%)→ 一次性逻辑
- 其他文件合计:2156 行(40%)
## 方案评估
### ✅ 优点
1. **分层架构清晰**
- `commands/`Tauri 命令薄层
- `services/`:业务流程,如供应商切换、MCP 同步
- `infrastructure/`:配置读写、外设交互
- `domain/`:数据模型 (`Provider`, `AppType` 等)
→ 提升可测试性、降低耦合度、方便团队协作。
2. **统一错误处理**
- 引入 `AppError``thiserror`),保留错误链和上下文。
- Tauri 命令仍返回 `Result<T, String>`,通过 `From<AppError>` 自动转换。
- 改善日志可读性,利于排查。
3. **并发优化**
- `AppState` 切换为 `RwLock<MultiAppConfig>`
- 读多写少的场景提升吞吐(如频繁查询供应商列表)。
### ⚠️ 风险
1. **过度设计**
- 完整 DDD 四层在 5k 行项目中会增加 30-50% 维护成本。
- Rust trait + repository 样板较多,收益不足。
- 推荐“轻量分层”而非正统 DDD。
2. **迁移成本高**
- `commands.rs` 拆分、错误统一、锁改造触及多文件。
- 测试缺失导致重构风险高,需先补测试。
- 估算完整改造需 5-6 周;建议分阶段输出可落地价值。
3. **技术选型需谨慎**
- `parking_lot` 相比标准库 `RwLock` 提升有限,不必引入。
- `spawn_blocking` 仅用于 >100ms 的阻塞任务,避免滥用。
- 以现有依赖为主,控制复杂度。
## 实施进度
- **阶段 1:统一错误处理 ✅**
- 引入 `thiserror` 并在 `src-tauri/src/error.rs` 定义 `AppError`,提供常用构造函数和 `From<AppError> for String`,保留错误链路。
- 配置、存储、同步等核心模块(`config.rs``app_config.rs``app_store.rs``store.rs``codex_config.rs``claude_mcp.rs``claude_plugin.rs``import_export.rs``mcp.rs``migration.rs``speedtest.rs``usage_script.rs``settings.rs``lib.rs` 等)已统一返回 `Result<_, AppError>`,避免字符串错误丢失上下文。
- Tauri 命令层继续返回 `Result<_, String>`,通过 `?` + `Into<String>` 统一转换,前端无需调整。
- `cargo check` 通过,`rg "Result<[^>]+, String"` 巡检确认除命令层外已无字符串错误返回。
- **阶段 2:拆分命令层 ✅**
- 已将单一 `src-tauri/src/commands.rs` 拆分为 `commands/{provider,mcp,config,settings,misc,plugin}.rs` 并通过 `commands/mod.rs` 统一导出,保持对外 API 不变。
- 每个文件聚焦单一功能域(供应商、MCP、配置、设置、杂项、插件),命令函数平均 150-250 行,可读性与后续维护性显著提升。
- 相关依赖调整后 `cargo check` 通过,静态巡检确认无重复定义或未注册命令。
- **阶段 3:补充测试 ✅**
- `tests/import_export_sync.rs` 集成测试涵盖配置备份、Claude/Codex live 同步、MCP 投影与 Codex/Claude 双向导入流程,并新增启用项清理、非法 TOML 抛错等失败场景验证;统一使用隔离 HOME 目录避免污染真实用户环境。
- 扩展 `lib.rs` re-export,暴露 `AppType``MultiAppConfig``AppError`、配置 IO 以及 Codex/Claude MCP 路径与同步函数,方便服务层及测试直接复用核心逻辑。
- 新增负向测试验证 Codex 供应商缺少 `auth` 字段时的错误返回,并补充备份数量上限测试;顺带修复 `create_backup` 采用内存读写避免拷贝继承旧的修改时间,确保最新备份不会在清理阶段被误删。
- 针对 `codex_config::write_codex_live_atomic` 补充成功与失败场景测试,覆盖 auth/config 原子写入与失败回滚逻辑(模拟目标路径为目录时的 rename 失败),降低 Codex live 写入回归风险。
- 新增 `tests/provider_commands.rs` 覆盖 `switch_provider` 的 Codex 正常流程与供应商缺失分支,并抽取 `switch_provider_internal` 以复用 `AppError`,通过 `switch_provider_test_hook` 暴露测试入口;同时共享 `tests/support.rs` 提供隔离 HOME / 互斥工具函数。
- 补充 Claude 切换集成测试,验证 live `settings.json` 覆写、新旧供应商快照回填以及 `.cc-switch/config.json` 持久化结果,确保阶段四提取服务层时拥有可回归的用例。
- 增加 Codex 缺失 `auth` 场景测试,确认 `switch_provider_internal` 在关键字段缺失时返回带上下文的 `AppError`,同时保持内存状态未被污染。
- 为配置导入命令抽取复用逻辑 `import_config_from_path` 并补充成功/失败集成测试,校验备份生成、状态同步、JSON 解析与文件缺失等错误回退路径;`export_config_to_file` 亦具备成功/缺失源文件的命令级回归。
- 新增 `tests/mcp_commands.rs`,通过测试钩子覆盖 `import_default_config``import_mcp_from_claude``set_mcp_enabled` 等命令层行为,验证缺失文件/非法 JSON 的错误回滚以及成功路径落盘效果;阶段三目标达成,命令层关键边界已具备回归保障。
- **阶段 4:服务层抽象 🚧(进行中)**
- 新增 `services/provider.rs` 并实现 `ProviderService::switch` / `delete`,集中处理供应商切换、回填、MCP 同步等核心业务;命令层改为薄封装并在 `tests/provider_service.rs``tests/provider_commands.rs` 中完成成功与失败路径的集成验证。
- 新增 `services/mcp.rs` 提供 `McpService`,封装 MCP 服务器的查询、增删改、启用同步与导入流程;命令层改为参数解析 + 调用服务,`tests/mcp_commands.rs` 直接使用 `McpService` 验证成功与失败路径,阶段三测试继续适配。
- `McpService` 在内部先复制内存快照、释放写锁,再执行文件同步,避免阶段五升级后的 `RwLock` 在 I/O 场景被长时间占用;`upsert/delete/set_enabled/sync_enabled` 均已修正。
- 新增 `services/config.rs` 提供 `ConfigService`,统一处理配置导入导出、备份与 live 同步;命令层迁移至 `commands/import_export.rs`,在落盘操作前释放锁并复用现有集成测试。
- 新增 `services/speedtest.rs` 并实现 `SpeedtestService::test_endpoints`,将 URL 校验、超时裁剪与网络请求封装在服务层,命令改为薄封装;补充单元测试覆盖空列表与非法 URL 分支。
- 后续可选:应用设置(Store)命令仍较薄,可按需评估是否抽象;当前阶段四核心服务已基本齐备。
- **阶段 5:锁与阻塞优化 ✅(首轮)**
- `AppState` 已由 `Mutex<MultiAppConfig>` 切换为 `RwLock<MultiAppConfig>`,托盘、命令与测试均按读写语义区分 `read()` / `write()``cargo test` 全量通过验证并未破坏现有流程。
- 针对高开销 IO 的配置导入/导出命令提取 `load_config_for_import`,并通过 `tauri::async_runtime::spawn_blocking` 将文件读写与备份迁至阻塞线程,保持命令处理线程轻量。
- 其余命令梳理后确认仍属轻量同步操作,暂不额外引入 `spawn_blocking`;若后续出现新的长耗时流程,再按同一模式扩展。
## 渐进式重构路线
### 阶段 1:统一错误处理(高收益 / 低风险)
- 新增 `src-tauri/src/error.rs`,定义 `AppError`
- 底层文件 IO、配置解析等函数返回 `Result<T, AppError>`
- 命令层通过 `?` 自动传播,最终 `.map_err(Into::into)`
- 预估 3-5 天,立即启动。
### 阶段 2:拆分 `commands.rs`(高收益 / 中风险)
- 按业务拆分为 `commands/provider.rs``commands/mcp.rs``commands/config.rs``commands/settings.rs``commands/misc.rs`
- `commands/mod.rs` 统一导出和注册。
- 文件行数降低到 200-300 行/文件,职责单一。
- 预估 5-7 天,可并行进行部分重构。
### 阶段 3:补充测试(中收益 / 中风险)
- 引入 `tests/``src-tauri/tests/` 集成测试,覆盖供应商切换、MCP 同步、配置迁移。
- 使用 `tempfile`/`tempdir` 隔离文件系统,组合少量回归脚本。
- 预估 5-7 天,为后续重构提供安全网。
### 阶段 4:提取轻量服务层(中收益 / 中风险)
- 新增 `services/provider_service.rs``services/mcp_service.rs`
- 不强制使用 trait;直接以自由函数/结构体实现业务流程。
```rust
pub struct ProviderService;
impl ProviderService {
pub fn switch(config: &mut MultiAppConfig, app: AppType, id: &str) -> Result<(), AppError> {
// 业务流程:验证、回填、落盘、更新 current、触发事件
}
}
```
- 命令层负责参数解析,服务层处理业务逻辑,托盘逻辑重用同一接口。
- 预估 7-10 天,可在测试补齐后执行。
### 阶段 5:锁与阻塞优化(低收益 / 低风险)
- ✅ `AppState` 已从 `Mutex` 切换为 `RwLock`,命令与托盘读写按需区分,现有测试全部通过。
- ✅ 配置导入/导出命令通过 `spawn_blocking` 处理高开销文件 IO;其他命令维持同步执行以避免不必要调度。
- 🔄 持续监控:若后续引入新的批量迁移或耗时任务,再按相同模式扩展到阻塞线程;观察运行时锁竞争情况,必要时考虑进一步拆分状态或引入缓存。
## 测试策略
- **优先覆盖场景**
- 供应商切换:状态更新 + live 配置同步
- MCP 同步:enabled 服务器快照与落盘
- 配置迁移:归档、备份与版本升级
- **推荐结构**
```rust
#[cfg(test)]
mod integration {
use super::*;
#[test]
fn switch_provider_updates_live_config() { /* ... */ }
#[test]
fn sync_mcp_to_codex_updates_claude_config() { /* ... */ }
#[test]
fn migration_preserves_backup() { /* ... */ }
}
```
- 目标覆盖率:关键路径 >80%,文件 IO/迁移 >70%。
## 风险与对策
- **测试不足** → 阶段 3 强制补齐,建立基础集成测试。
- **重构跨度大** → 按阶段在独立分支推进(如 `refactor/backend-step1` 等)。
- **回滚困难** → 每阶段结束打 tag(如 `v3.6.0-backend-step1`),保留回滚点。
- **功能回归** → 重构后执行手动冒烟流程:供应商切换、托盘操作、MCP 同步、配置导入导出。
## 总结
- 当前规模下不建议整体引入完整 DDD/四层架构,避免过度设计。
- 建议遵循“错误统一 → 命令拆分 → 补测试 → 服务层抽象 → 锁优化”的渐进式策略。
- 完成阶段 1-3 后即可显著提升可维护性与可靠性;阶段 4-5 可根据资源灵活安排。
- 重构过程中同步维护文档与测试,确保团队成员对架构演进保持一致认知。
File diff suppressed because it is too large Load Diff
-490
View File
@@ -1,490 +0,0 @@
# CC Switch 重构实施清单
> 用于跟踪重构进度的详细检查清单
**开始日期**: ___________
**预计完成**: ___________
**当前阶段**: ___________
---
## 📋 阶段 0: 准备阶段 (预计 1 天)
### 环境准备
- [ ] 创建新分支 `refactor/modernization`
- [ ] 创建备份标签 `git tag backup-before-refactor`
- [ ] 备份用户配置文件 `~/.cc-switch/config.json`
- [ ] 通知团队成员重构开始
### 依赖安装
```bash
pnpm add @tanstack/react-query
pnpm add react-hook-form @hookform/resolvers
pnpm add zod
pnpm add sonner
pnpm add next-themes
pnpm add @radix-ui/react-dialog @radix-ui/react-dropdown-menu
pnpm add @radix-ui/react-label @radix-ui/react-select
pnpm add @radix-ui/react-slot @radix-ui/react-switch @radix-ui/react-tabs
pnpm add class-variance-authority clsx tailwind-merge tailwindcss-animate
```
- [ ] 安装核心依赖 (上述命令)
- [ ] 验证依赖安装成功 `pnpm install`
- [ ] 验证编译通过 `pnpm typecheck`
### 配置文件
- [ ] 创建 `components.json`
- [ ] 更新 `tsconfig.json` 添加路径别名
- [ ] 更新 `vite.config.mts` 添加路径解析
- [ ] 验证开发服务器启动 `pnpm dev`
**完成时间**: ___________
**遇到的问题**: ___________
---
## 📋 阶段 1: 基础设施 (预计 2-3 天)
### 1.1 工具函数和基础组件
- [ ] 创建 `src/lib/utils.ts` (cn 函数)
- [ ] 创建 `src/components/ui/button.tsx`
- [ ] 创建 `src/components/ui/dialog.tsx`
- [ ] 创建 `src/components/ui/input.tsx`
- [ ] 创建 `src/components/ui/label.tsx`
- [ ] 创建 `src/components/ui/textarea.tsx`
- [ ] 创建 `src/components/ui/select.tsx`
- [ ] 创建 `src/components/ui/switch.tsx`
- [ ] 创建 `src/components/ui/tabs.tsx`
- [ ] 创建 `src/components/ui/sonner.tsx`
- [ ] 创建 `src/components/ui/form.tsx`
**测试**:
- [ ] 验证所有 UI 组件可以正常导入
- [ ] 创建一个测试页面验证组件样式
### 1.2 Query Client 设置
- [ ] 创建 `src/lib/query/queryClient.ts`
- [ ] 配置默认选项 (retry, staleTime 等)
- [ ] 导出 queryClient 实例
### 1.3 API 层
- [ ] 创建 `src/lib/api/providers.ts`
- [ ] getAll
- [ ] getCurrent
- [ ] add
- [ ] update
- [ ] delete
- [ ] switch
- [ ] importDefault
- [ ] updateTrayMenu
- [ ] 创建 `src/lib/api/settings.ts`
- [ ] get
- [ ] save
- [ ] 创建 `src/lib/api/mcp.ts`
- [ ] getConfig
- [ ] upsertServer
- [ ] deleteServer
- [ ] 创建 `src/lib/api/index.ts` (聚合导出)
**测试**:
- [ ] 验证 API 调用不会出现运行时错误
- [ ] 确认类型定义正确
### 1.4 Query Hooks
- [ ] 创建 `src/lib/query/queries.ts`
- [ ] useProvidersQuery
- [ ] useSettingsQuery
- [ ] useMcpConfigQuery
- [ ] 创建 `src/lib/query/mutations.ts`
- [ ] useAddProviderMutation
- [ ] useSwitchProviderMutation
- [ ] useDeleteProviderMutation
- [ ] useUpdateProviderMutation
- [ ] useSaveSettingsMutation
- [ ] 创建 `src/lib/query/index.ts` (聚合导出)
**测试**:
- [ ] 在临时组件中测试每个 hook
- [ ] 验证 loading/error 状态正确
- [ ] 验证缓存和自动刷新工作
**完成时间**: ___________
**遇到的问题**: ___________
---
## 📋 阶段 2: 核心功能重构 (预计 3-4 天)
### 2.1 主题系统
- [ ] 创建 `src/components/theme-provider.tsx`
- [ ] 创建 `src/components/mode-toggle.tsx`
- [ ] 更新 `src/index.css` 添加主题变量
- [ ] 删除 `src/hooks/useDarkMode.ts`
- [ ] 更新所有组件使用新的主题系统
**测试**:
- [ ] 验证主题切换正常工作
- [ ] 验证系统主题跟随功能
- [ ] 验证主题持久化
### 2.2 更新 main.tsx
- [ ] 引入 QueryClientProvider
- [ ] 引入 ThemeProvider
- [ ] 添加 Toaster 组件
- [ ] 移除旧的 API 导入
**测试**:
- [ ] 验证应用可以正常启动
- [ ] 验证 Context 正确传递
### 2.3 重构 App.tsx
- [ ] 使用 useProvidersQuery 替代手动状态管理
- [ ] 移除所有 loadProviders 相关代码
- [ ] 移除手动 notification 状态
- [ ] 简化事件监听逻辑
- [ ] 更新对话框为新的 Dialog 组件
**目标**: 将 412 行代码减少到 ~100 行
**测试**:
- [ ] 验证供应商列表正常加载
- [ ] 验证切换 Claude/Codex 正常工作
- [ ] 验证事件监听正常工作
### 2.4 重构 ProviderList
- [ ] 创建 `src/components/providers/ProviderList.tsx`
- [ ] 使用 mutation hooks 处理操作
- [ ] 移除 onNotify prop
- [ ] 移除手动状态管理
**测试**:
- [ ] 验证供应商列表渲染
- [ ] 验证切换操作
- [ ] 验证删除操作
### 2.5 重构表单系统
- [ ] 创建 `src/lib/schemas/provider.ts` (Zod schema)
- [ ] 创建 `src/components/providers/ProviderForm.tsx`
- [ ] 使用 react-hook-form
- [ ] 使用 zodResolver
- [ ] 字段级验证
- [ ] 创建 `src/components/providers/AddProviderDialog.tsx`
- [ ] 使用新的 Dialog 组件
- [ ] 集成 ProviderForm
- [ ] 使用 useAddProviderMutation
- [ ] 创建 `src/components/providers/EditProviderDialog.tsx`
- [ ] 使用新的 Dialog 组件
- [ ] 集成 ProviderForm
- [ ] 使用 useUpdateProviderMutation
**测试**:
- [ ] 验证表单验证正常工作
- [ ] 验证错误提示显示正确
- [ ] 验证提交操作成功
- [ ] 验证表单重置功能
### 2.6 清理旧组件
- [x] 删除 `src/components/AddProviderModal.tsx`
- [x] 删除 `src/components/EditProviderModal.tsx`
- [x] 更新所有引用这些组件的地方
- [x] 删除 `src/components/ProviderForm.tsx``src/components/ProviderForm/`
**完成时间**: ___________
**遇到的问题**: ___________
---
## 📋 阶段 3: 设置和辅助功能 (预计 2-3 天)
### 3.1 重构 SettingsDialog
- [ ] 创建 `src/components/settings/SettingsDialog.tsx`
- [ ] 使用 Tabs 组件
- [ ] 集成各个设置子组件
- [ ] 创建 `src/components/settings/GeneralSettings.tsx`
- [ ] 语言设置
- [ ] 配置目录设置
- [ ] 其他通用设置
- [ ] 创建 `src/components/settings/AboutSection.tsx`
- [ ] 版本信息
- [ ] 更新检查
- [ ] 链接
- [ ] 创建 `src/components/settings/ImportExportSection.tsx`
- [ ] 导入功能
- [ ] 导出功能
**目标**: 将 643 行拆分为 4-5 个小组件,每个 100-150 行
**测试**:
- [ ] 验证设置保存功能
- [ ] 验证导入导出功能
- [ ] 验证更新检查功能
### 3.2 重构通知系统
- [ ] 在所有 mutations 中使用 `toast` 替代 `showNotification`
- [ ] 移除 App.tsx 中的 notification 状态
- [ ] 移除自定义通知组件
**测试**:
- [ ] 验证成功通知显示
- [ ] 验证错误通知显示
- [ ] 验证通知自动消失
### 3.3 重构确认对话框
- [ ] 更新 `src/components/ConfirmDialog.tsx` 使用新的 Dialog
- [ ] 或者直接使用 shadcn/ui 的 AlertDialog
**测试**:
- [ ] 验证删除确认对话框
- [ ] 验证其他确认场景
**完成时间**: ___________
**遇到的问题**: ___________
---
## 📋 阶段 4: 清理和优化 (预计 1-2 天)
### 4.1 移除旧代码
- [x] 删除 `src/lib/styles.ts`
- [x]`src/lib/tauri-api.ts` 移除 `window.api` 绑定
- [x] 精简 `src/lib/tauri-api.ts`,只保留事件监听相关
- [x] 删除或更新 `src/vite-env.d.ts` 中的过时类型
### 4.2 代码审查
- [ ] 检查所有 TODO 注释
- [x] 检查是否还有 `window.api` 调用
- [ ] 检查是否还有手动状态管理
- [x] 统一代码风格
### 4.3 类型检查
- [x] 运行 `pnpm typecheck` 确保无错误
- [x] 修复所有类型错误
- [x] 更新类型定义
### 4.4 性能优化
- [ ] 检查是否有不必要的重渲染
- [ ] 添加必要的 React.memo
- [ ] 优化 Query 缓存配置
**完成时间**: ___________
**遇到的问题**: ___________
---
## 📋 阶段 5: 测试和修复 (预计 2-3 天)
### 5.1 功能测试
#### 供应商管理
- [ ] 添加供应商 (Claude)
- [ ] 添加供应商 (Codex)
- [ ] 编辑供应商
- [ ] 删除供应商
- [ ] 切换供应商
- [ ] 导入默认配置
#### 应用切换
- [ ] Claude <-> Codex 切换
- [ ] 切换后数据正确加载
- [ ] 切换后托盘菜单更新
#### 设置
- [ ] 保存通用设置
- [ ] 切换语言
- [ ] 配置目录选择
- [ ] 导入配置
- [ ] 导出配置
#### UI 交互
- [ ] 主题切换 (亮色/暗色)
- [ ] 对话框打开/关闭
- [ ] 表单验证
- [ ] Toast 通知
#### MCP 管理
- [ ] 列表显示
- [ ] 添加 MCP
- [ ] 编辑 MCP
- [ ] 删除 MCP
- [ ] 启用/禁用 MCP
### 5.2 边界情况测试
- [ ] 空供应商列表
- [ ] 无效配置文件
- [ ] 网络错误
- [ ] 后端错误响应
- [ ] 并发操作
- [ ] 表单输入边界值
### 5.3 兼容性测试
- [ ] Windows 测试
- [ ] macOS 测试
- [ ] Linux 测试
### 5.4 性能测试
- [ ] 100+ 供应商加载速度
- [ ] 快速切换供应商
- [ ] 内存使用情况
- [ ] CPU 使用情况
### 5.5 Bug 修复
**Bug 列表** (发现后记录):
1. ___________
- [ ] 已修复
- [ ] 已验证
2. ___________
- [ ] 已修复
- [ ] 已验证
**完成时间**: ___________
**遇到的问题**: ___________
---
## 📋 最终检查
### 代码质量
- [ ] 所有 TypeScript 错误已修复
- [ ] 运行 `pnpm format` 格式化代码
- [ ] 运行 `pnpm typecheck` 通过
- [ ] 代码审查完成
### 文档更新
- [ ] 更新 `CLAUDE.md` 反映新架构
- [ ] 更新 `README.md` (如有必要)
- [ ] 添加 Migration Guide (可选)
### 性能基准
记录性能数据:
**旧版本**:
- 启动时间: _____ms
- 供应商加载: _____ms
- 内存占用: _____MB
**新版本**:
- 启动时间: _____ms
- 供应商加载: _____ms
- 内存占用: _____MB
### 代码统计
**代码行数对比**:
| 文件 | 旧版本 | 新版本 | 减少 |
|------|--------|--------|------|
| App.tsx | 412 | ~100 | -76% |
| tauri-api.ts | 712 | ~50 | -93% |
| ProviderForm.tsx | 271 | ~150 | -45% |
| settings 模块 | 1046 | ~470 (拆分) | -55% |
| **总计** | 2038 | ~700 | **-66%** |
---
## 📦 发布准备
### Pre-release 测试
- [ ] 创建 beta 版本 `v4.0.0-beta.1`
- [ ] 在测试环境验证
- [ ] 收集用户反馈
### 正式发布
- [ ] 合并到 main 分支
- [ ] 创建 Release Tag `v4.0.0`
- [ ] 更新 Changelog
- [ ] 发布 GitHub Release
- [ ] 通知用户更新
---
## 🚨 回滚触发条件
如果出现以下情况,考虑回滚:
- [ ] 重大功能无法使用
- [ ] 用户数据丢失
- [ ] 严重性能问题
- [ ] 无法修复的兼容性问题
**回滚命令**:
```bash
git reset --hard backup-before-refactor
# 或
git revert <commit-range>
```
---
## 📝 总结报告
### 成功指标
- [ ] 所有现有功能正常工作
- [ ] 代码量减少 40%+
- [ ] 无用户数据丢失
- [ ] 性能未下降
### 经验教训
**遇到的主要挑战**:
1. ___________
2. ___________
3. ___________
**解决方案**:
1. ___________
2. ___________
3. ___________
**未来改进**:
1. ___________
2. ___________
3. ___________
---
**重构完成日期**: ___________
**总耗时**: _____
**参与人员**: ___________
File diff suppressed because it is too large Load Diff
-834
View File
@@ -1,834 +0,0 @@
# 重构快速参考指南
> 常见模式和代码示例的速查表
---
## 📑 目录
1. [React Query 使用](#react-query-使用)
2. [react-hook-form 使用](#react-hook-form-使用)
3. [shadcn/ui 组件使用](#shadcnui-组件使用)
4. [代码迁移示例](#代码迁移示例)
---
## React Query 使用
### 基础查询
```typescript
// 定义查询 Hook
export const useProvidersQuery = (appId: AppId) => {
return useQuery({
queryKey: ['providers', appId],
queryFn: async () => {
const data = await providersApi.getAll(appId)
return data
},
})
}
// 在组件中使用
function MyComponent() {
const { data, isLoading, error } = useProvidersQuery('claude')
if (isLoading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>
return <div>{/* 使用 data */}</div>
}
```
### Mutation (变更操作)
```typescript
// 定义 Mutation Hook
export const useAddProviderMutation = (appId: AppId) => {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (provider: Provider) => {
return await providersApi.add(provider, appId)
},
onSuccess: () => {
// 重新获取数据
queryClient.invalidateQueries({ queryKey: ['providers', appId] })
toast.success('添加成功')
},
onError: (error: Error) => {
toast.error(`添加失败: ${error.message}`)
},
})
}
// 在组件中使用
function AddProviderDialog() {
const mutation = useAddProviderMutation('claude')
const handleSubmit = (data: Provider) => {
mutation.mutate(data)
}
return (
<button
onClick={() => handleSubmit(formData)}
disabled={mutation.isPending}
>
{mutation.isPending ? '添加中...' : '添加'}
</button>
)
}
```
### 乐观更新
```typescript
export const useSwitchProviderMutation = (appId: AppId) => {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (providerId: string) => {
return await providersApi.switch(providerId, appId)
},
// 乐观更新: 在请求发送前立即更新 UI
onMutate: async (providerId) => {
// 取消正在进行的查询
await queryClient.cancelQueries({ queryKey: ['providers', appId] })
// 保存当前数据(以便回滚)
const previousData = queryClient.getQueryData(['providers', appId])
// 乐观更新
queryClient.setQueryData(['providers', appId], (old: any) => ({
...old,
currentProviderId: providerId,
}))
return { previousData }
},
// 如果失败,回滚
onError: (err, providerId, context) => {
queryClient.setQueryData(['providers', appId], context?.previousData)
toast.error('切换失败')
},
// 无论成功失败,都重新获取数据
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['providers', appId] })
},
})
}
```
### 依赖查询
```typescript
// 第二个查询依赖第一个查询的结果
const { data: providers } = useProvidersQuery(appId)
const currentProviderId = providers?.currentProviderId
const { data: currentProvider } = useQuery({
queryKey: ['provider', currentProviderId],
queryFn: () => providersApi.getById(currentProviderId!),
enabled: !!currentProviderId, // 只有当 ID 存在时才执行
})
```
---
## react-hook-form 使用
### 基础表单
```typescript
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
// 定义验证 schema
const schema = z.object({
name: z.string().min(1, '请输入名称'),
email: z.string().email('邮箱格式不正确'),
age: z.number().min(18, '年龄必须大于18'),
})
type FormData = z.infer<typeof schema>
function MyForm() {
const form = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
name: '',
email: '',
age: 0,
},
})
const onSubmit = (data: FormData) => {
console.log(data)
}
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
<input {...form.register('name')} />
{form.formState.errors.name && (
<span>{form.formState.errors.name.message}</span>
)}
<button type="submit"></button>
</form>
)
}
```
### 使用 shadcn/ui Form 组件
```typescript
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
function MyForm() {
const form = useForm<FormData>({
resolver: zodResolver(schema),
})
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input placeholder="请输入名称" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit"></Button>
</form>
</Form>
)
}
```
### 动态表单验证
```typescript
// 根据条件动态验证
const schema = z.object({
type: z.enum(['official', 'custom']),
apiKey: z.string().optional(),
baseUrl: z.string().optional(),
}).refine(
(data) => {
// 如果是自定义供应商,必须填写 baseUrl
if (data.type === 'custom') {
return !!data.baseUrl
}
return true
},
{
message: '自定义供应商必须填写 Base URL',
path: ['baseUrl'],
}
)
```
### 手动触发验证
```typescript
function MyForm() {
const form = useForm<FormData>()
const handleBlur = async () => {
// 验证单个字段
await form.trigger('name')
// 验证多个字段
await form.trigger(['name', 'email'])
// 验证所有字段
const isValid = await form.trigger()
}
return <form>...</form>
}
```
---
## shadcn/ui 组件使用
### Dialog (对话框)
```typescript
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
function MyDialog() {
const [open, setOpen] = useState(false)
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
{/* 内容 */}
<div></div>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)}>
</Button>
<Button onClick={handleConfirm}></Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
```
### Select (选择器)
```typescript
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
function MySelect() {
const [value, setValue] = useState('')
return (
<Select value={value} onValueChange={setValue}>
<SelectTrigger>
<SelectValue placeholder="请选择" />
</SelectTrigger>
<SelectContent>
<SelectItem value="option1">1</SelectItem>
<SelectItem value="option2">2</SelectItem>
<SelectItem value="option3">3</SelectItem>
</SelectContent>
</Select>
)
}
```
### Tabs (标签页)
```typescript
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
function MyTabs() {
return (
<Tabs defaultValue="tab1">
<TabsList>
<TabsTrigger value="tab1">1</TabsTrigger>
<TabsTrigger value="tab2">2</TabsTrigger>
<TabsTrigger value="tab3">3</TabsTrigger>
</TabsList>
<TabsContent value="tab1">
<div>1</div>
</TabsContent>
<TabsContent value="tab2">
<div>2</div>
</TabsContent>
<TabsContent value="tab3">
<div>3</div>
</TabsContent>
</Tabs>
)
}
```
### Toast 通知 (Sonner)
```typescript
import { toast } from 'sonner'
// 成功通知
toast.success('操作成功')
// 错误通知
toast.error('操作失败')
// 加载中
const toastId = toast.loading('处理中...')
// 完成后更新
toast.success('处理完成', { id: toastId })
// 或
toast.dismiss(toastId)
// 自定义持续时间
toast.success('消息', { duration: 5000 })
// 带操作按钮
toast('确认删除?', {
action: {
label: '删除',
onClick: () => handleDelete(),
},
})
```
---
## 代码迁移示例
### 示例 1: 状态管理迁移
**旧代码** (手动状态管理):
```typescript
const [providers, setProviders] = useState<Record<string, Provider>>({})
const [currentProviderId, setCurrentProviderId] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState<Error | null>(null)
useEffect(() => {
const load = async () => {
setLoading(true)
setError(null)
try {
const data = await window.api.getProviders(appType)
const currentId = await window.api.getCurrentProvider(appType)
setProviders(data)
setCurrentProviderId(currentId)
} catch (err) {
setError(err as Error)
} finally {
setLoading(false)
}
}
load()
}, [appId])
```
**新代码** (React Query):
```typescript
const { data, isLoading, error } = useProvidersQuery(appId)
const providers = data?.providers || {}
const currentProviderId = data?.currentProviderId || ''
```
**减少**: 从 20+ 行到 3 行
---
### 示例 2: 表单验证迁移
**旧代码** (手动验证):
```typescript
const [name, setName] = useState('')
const [nameError, setNameError] = useState('')
const [apiKey, setApiKey] = useState('')
const [apiKeyError, setApiKeyError] = useState('')
const validate = () => {
let valid = true
if (!name.trim()) {
setNameError('请输入名称')
valid = false
} else {
setNameError('')
}
if (!apiKey.trim()) {
setApiKeyError('请输入 API Key')
valid = false
} else if (apiKey.length < 10) {
setApiKeyError('API Key 长度不足')
valid = false
} else {
setApiKeyError('')
}
return valid
}
const handleSubmit = () => {
if (validate()) {
// 提交
}
}
return (
<form>
<input value={name} onChange={e => setName(e.target.value)} />
{nameError && <span>{nameError}</span>}
<input value={apiKey} onChange={e => setApiKey(e.target.value)} />
{apiKeyError && <span>{apiKeyError}</span>}
<button onClick={handleSubmit}></button>
</form>
)
```
**新代码** (react-hook-form + zod):
```typescript
const schema = z.object({
name: z.string().min(1, '请输入名称'),
apiKey: z.string().min(10, 'API Key 长度不足'),
})
const form = useForm({
resolver: zodResolver(schema),
})
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="apiKey"
render={({ field }) => (
<FormItem>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit"></Button>
</form>
</Form>
)
```
**减少**: 从 40+ 行到 30 行,且更健壮
---
### 示例 3: 通知系统迁移
**旧代码** (自定义通知):
```typescript
const [notification, setNotification] = useState<{
message: string
type: 'success' | 'error'
} | null>(null)
const [isVisible, setIsVisible] = useState(false)
const showNotification = (message: string, type: 'success' | 'error') => {
setNotification({ message, type })
setIsVisible(true)
setTimeout(() => {
setIsVisible(false)
setTimeout(() => setNotification(null), 300)
}, 3000)
}
return (
<>
{notification && (
<div className={`notification ${isVisible ? 'visible' : ''} ${notification.type}`}>
{notification.message}
</div>
)}
{/* 其他内容 */}
</>
)
```
**新代码** (Sonner):
```typescript
import { toast } from 'sonner'
// 在需要的地方直接调用
toast.success('操作成功')
toast.error('操作失败')
// 在 main.tsx 中只需添加一次
import { Toaster } from '@/components/ui/sonner'
<Toaster />
```
**减少**: 从 20+ 行到 1 行调用
---
### 示例 4: 对话框迁移
**旧代码** (自定义 Modal):
```typescript
const [isOpen, setIsOpen] = useState(false)
return (
<>
<button onClick={() => setIsOpen(true)}></button>
{isOpen && (
<div className="modal-backdrop" onClick={() => setIsOpen(false)}>
<div className="modal-content" onClick={e => e.stopPropagation()}>
<div className="modal-header">
<h2></h2>
<button onClick={() => setIsOpen(false)}>×</button>
</div>
<div className="modal-body">
{/* 内容 */}
</div>
<div className="modal-footer">
<button onClick={() => setIsOpen(false)}></button>
<button onClick={handleConfirm}></button>
</div>
</div>
</div>
)}
</>
)
```
**新代码** (shadcn/ui Dialog):
```typescript
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
const [isOpen, setIsOpen] = useState(false)
return (
<>
<Button onClick={() => setIsOpen(true)}></Button>
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
{/* 内容 */}
<DialogFooter>
<Button variant="outline" onClick={() => setIsOpen(false)}></Button>
<Button onClick={handleConfirm}></Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)
```
**优势**:
- 无需自定义样式
- 内置无障碍支持
- 自动管理焦点和 ESC 键
---
### 示例 5: API 调用迁移
**旧代码** (window.api):
```typescript
// 添加供应商
const handleAdd = async (provider: Provider) => {
try {
await window.api.addProvider(provider, appType)
await loadProviders()
showNotification('添加成功', 'success')
} catch (error) {
showNotification('添加失败', 'error')
}
}
```
**新代码** (React Query Mutation):
```typescript
// 在组件中
const addMutation = useAddProviderMutation(appId)
const handleAdd = (provider: Provider) => {
addMutation.mutate(provider)
// 成功和错误处理已在 mutation 定义中处理
}
```
**优势**:
- 自动处理 loading 状态
- 统一的错误处理
- 自动刷新数据
- 更少的样板代码
---
## 常见问题
### Q: 如何在 mutation 成功后关闭对话框?
```typescript
const mutation = useAddProviderMutation(appId)
const handleSubmit = (data: Provider) => {
mutation.mutate(data, {
onSuccess: () => {
setIsOpen(false) // 关闭对话框
},
})
}
```
### Q: 如何在表单中使用异步验证?
```typescript
const schema = z.object({
name: z.string().refine(
async (name) => {
// 检查名称是否已存在
const exists = await checkNameExists(name)
return !exists
},
{ message: '名称已存在' }
),
})
```
### Q: 如何手动刷新 Query 数据?
```typescript
const queryClient = useQueryClient()
// 方式1: 使缓存失效,触发重新获取
queryClient.invalidateQueries({ queryKey: ['providers', appId] })
// 方式2: 直接刷新
queryClient.refetchQueries({ queryKey: ['providers', appId] })
// 方式3: 更新缓存数据
queryClient.setQueryData(['providers', appId], newData)
```
### Q: 如何在组件外部使用 toast?
```typescript
// 直接导入并使用即可
import { toast } from 'sonner'
export const someUtil = () => {
toast.success('工具函数中的通知')
}
```
---
## 调试技巧
### React Query DevTools
```typescript
// 在 main.tsx 中添加
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
<QueryClientProvider client={queryClient}>
<App />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
```
### 查看表单状态
```typescript
const form = useForm()
// 在开发模式下打印表单状态
console.log('Form values:', form.watch())
console.log('Form errors:', form.formState.errors)
console.log('Is valid:', form.formState.isValid)
```
---
## 性能优化建议
### 1. 避免不必要的重渲染
```typescript
// 使用 React.memo
export const ProviderCard = React.memo(({ provider, onEdit }: Props) => {
// ...
})
// 或使用 useMemo
const sortedProviders = useMemo(
() => Object.values(providers).sort(...),
[providers]
)
```
### 2. Query 配置优化
```typescript
const { data } = useQuery({
queryKey: ['providers', appId],
queryFn: fetchProviders,
staleTime: 1000 * 60 * 5, // 5分钟内不重新获取
gcTime: 1000 * 60 * 10, // 10分钟后清除缓存
})
```
### 3. 表单性能优化
```typescript
// 使用 mode 控制验证时机
const form = useForm({
mode: 'onBlur', // 失去焦点时验证
// mode: 'onChange', // 每次输入都验证(较慢)
// mode: 'onSubmit', // 提交时验证(最快)
})
```
---
**提示**: 将此文档保存在浏览器书签或编辑器中,方便随时查阅!
-73
View File
@@ -1,73 +0,0 @@
# 前端测试开发计划
## 1. 背景与目标
- **背景**:v3.5.0 起前端功能快速扩张(供应商管理、MCP、导入导出、端点测速、国际化),缺失系统化测试导致回归风险与人工验证成本攀升。
- **目标**:在 3 个迭代内建立覆盖关键业务的自动化测试体系,形成稳定的手动冒烟流程,并将测试执行纳入 CI/CD。
## 2. 范围与优先级
| 范围 | 内容 | 优先级 |
| --- | --- | --- |
| 供应商管理 | 列表、排序、预设/自定义表单、切换、复制、删除 | P0 |
| 配置导入导出 | JSON 校验、备份、进度反馈、失败回滚 | P0 |
| MCP 管理 | 列表、启停、模板、命令校验 | P1 |
| 设置面板 | 主题/语言切换、目录设置、关于、更新检查 | P1 |
| 端点速度测试 & 使用脚本 | 启动测试、状态指示、脚本保存 | P2 |
| 国际化 | 中英切换、缺省文案回退 | P2 |
## 3. 测试分层策略
- **单元测试(Vitest**:纯函数与 Hook`useProviderActions``useSettingsForm``useDragSort``useImportExport` 等)验证数据处理、错误分支、排序逻辑。
- **组件测试(React Testing Library**:关键组件(`ProviderList``AddProviderDialog``SettingsDialog``McpPanel`)模拟交互、校验、提示;结合 MSW 模拟 API。
- **集成测试(App 级别)**:挂载 `App.tsx`,覆盖应用切换、编辑模式、导入导出回调、语言切换,验证状态同步与 toast 提示。
- **端到端测试(Playwright**:依赖 `pnpm dev:renderer`,串联供应商 CRUD、排序拖拽、MCP 启停、语言切换即时刷新、更新检查跳转。
- **手动冒烟**Tauri 桌面包 + dev server 双通道,验证托盘、系统权限、真实文件写入。
## 4. 环境与工具
- 依赖:Node 18+、pnpm 8+、Vitest、React Testing Library、MSW、Playwright、Testing Library User Event、Playwright Trace Viewer。
- 配置要点:
-`tsconfig` 中共享别名,Vitest 配合 `vite.config.mts`
- `setupTests.ts` 统一注册 MSW/RTL、自定义 matcher。
- Playwright 使用多浏览器矩阵(Chromium 必选,WebKit 可选),并共享 `.env.test`
- Mock `@tauri-apps/api``providersApi`/`settingsApi`,隔离 Rust 层。
## 5. 自动化建设里程碑
| 周期 | 目标 | 交付 |
| --- | --- | --- |
| Sprint 1 | Vitest 基础设施、核心 Hook 单测(P0) | `pnpm test:unit`、覆盖率报告、10+ 用例 |
| Sprint 2 | 组件/集成测试、MSW Mock 层 | `pnpm test:component`、App 主流程用例 |
| Sprint 3 | Playwright E2E、CI 接入 | `pnpm test:e2e`、CI job、冒烟脚本 |
| 持续 | 回归用例补齐、视觉比对探索 | Playwright Trace、截图基线 |
## 6. 用例规划概览
- **供应商管理**:新增(预设+自定义)、编辑校验、复制排序、切换失败回退、删除确认、使用脚本保存。
- **导入导出**:成功、重复导入、校验失败、备份失败提示、导入后托盘刷新。
- **MCP**:模板应用、协议切换(stdio/http)、命令校验、启停状态持久化。
- **设置**:主题/语言即时生效、目录路径更新、更新检查按钮外链、关于信息渲染。
- **端点速度测试**:触发测试、loading/成功/失败状态、指示器颜色、测速数据排序。
- **国际化**:默认中文、切换英文后主界面/对话框文案变化、缺失 key fallback。
## 7. 数据与 Mock 策略
-`tests/fixtures/` 维护标准供应商、MCP、设置数据集。
- 使用 MSW 拦截 `providersApi``settingsApi``providersApi.onSwitched` 等调用;提供延迟/错误注入接口以覆盖异常分支。
- Playwright 端提供临时用户目录(`TMP_CC_SWITCH_HOME`)+ 伪配置文件,以验证真实文件交互路径。
## 8. 质量门禁与指标
- 覆盖率目标:单元 ≥75%,分支 ≥70%,逐步提升至 80%+。
- CI 阶段:`pnpm typecheck``pnpm format:check``pnpm test:unit``pnpm test:component``pnpm test:e2e`(可在 nightly 执行)。
- 缺陷处理:修复前补充最小复现测试;E2E 冒烟必须陪跑重大功能发布。
## 9. 工作流与职责
- **测试负责人**:前端工程师轮值;负责测试计划维护、PR 流水线健康。
- **开发者职责**:提交功能需附新增/更新测试、列出手动验证步骤、如涉及 UI 提交截图。
- **Code Review 检查**:测试覆盖说明、mock 合理性、易读性。
## 10. 风险与缓解
| 风险 | 影响 | 缓解 |
| --- | --- | --- |
| Tauri API Mock 难度高 | 单测无法稳定 | 抽象 API 适配层 + MSW 统一模拟 |
| Playwright 运行时间长 | CI 变慢 | 拆分冒烟/完整版,冒烟只跑关键路径 |
| 国际化文案频繁变化 | 用例脆弱 | 优先断言 data-testid/结构,文案使用翻译 key |
## 11. 输出与维护
- 文档维护者:前端团队;每个版本更新后检查测试覆盖清单。
- 交付物:测试报告(CI artifact)、Playwright Trace、覆盖率摘要。
- 复盘:每次发布后召开 30 分钟测试复盘,记录缺陷、补齐用例。
@@ -0,0 +1,141 @@
# Using GPT Models in Claude Code with CC Switch
> Applies to CC Switch 3.17.0 and later. (Both integration methods in this guide existed in earlier versions, but the gpt-5.6 preset and the client-identity fix landed in 3.17.0; on older versions, requesting new models like `gpt-5.6-luna` falsely returns 404.) This guide is compiled from the repository's documentation and code, and all sample data has been de-identified.
## Why local routing is needed
Claude Code targets the Anthropic Messages protocol — that is, `/v1/messages` — whereas the upstreams for Codex-family models, whether the OpenAI Responses API exposed by a third-party gateway or the Codex service behind a ChatGPT subscription, all speak the Responses protocol. The two protocols use completely different request bodies, streaming events, and response structures, so putting such an endpoint directly into Claude Code's config leaves the upstream receiving a `/v1/messages` request it doesn't recognize — which can only fail.
CC Switch's approach is to keep Claude Code always connected to the local route and still sending requests as Anthropic Messages; once the route detects that the active provider is Responses-format, it converts the request into Responses for the upstream, then converts the response back into the Messages shape it returns to Claude Code — tool calls, images, PDFs, and thinking configuration are all within the conversion scope.
This guide covers both integration methods:
- **Method 1 (API Key)**: you have a gateway endpoint and key compatible with the OpenAI Responses API, and you want to run the GPT-family models behind it inside Claude Code.
- **Method 2 (ChatGPT subscription)**: you have a ChatGPT Plus/Pro subscription and use its quota directly by signing in through Codex OAuth — no API key needed at any point.
The chain has four main steps:
1. When Claude Code is taken over, `ANTHROPIC_BASE_URL` in `~/.claude/settings.json` is written as the local route address (default `http://127.0.0.1:15721`), the auth entry keeps only a placeholder, and real credentials never enter the live config.
2. The provider's `API Format` is set to OpenAI Responses, telling the route that the real upstream speaks the Responses protocol.
3. The route converts the `/v1/messages` request into a Responses request body for the upstream; Method 2 additionally carries the OAuth token and the official client identity to reach ChatGPT's Codex service.
4. After the upstream responds, the route converts the Responses JSON/SSE back into the Messages shape Claude Code understands.
![The Needs Routing marker on a GPT provider in the Claude provider list](../images/claude-codex-routing/01-claude-providers-require-routing.png)
## Prerequisites
- CC Switch installed and able to start (3.17.0 or later; see the version note at the top for why).
- Claude Code installed and run at least once.
- For Method 1: a service endpoint compatible with the OpenAI Responses API and its API Key; follow the gateway's documentation for the endpoint and model names. Note it's the **Responses API**, not Chat Completions; a gateway that only offers the Chat format still works — see the `API Format` note in Step 1.
- For Method 2: a ChatGPT Plus/Pro subscription account.
## Step 1: Add a provider
### Method 1: Third-party Responses gateway (API Key)
Open CC Switch, switch to the top-level `Claude Code` tab, click the plus button in the upper-right corner to add a provider, keep the default `Custom Configuration`, then fill in:
- **Provider Name**: anything you like, e.g. `GPT Gateway`.
- **API Key**: your gateway key. The real key is stored only in CC Switch and injected by the local route when forwarding.
- **API Endpoint**: just the gateway's service root, e.g. `https://gpt-gateway.example.com`, without a trailing slash — the route sends requests to the gateway's Responses endpoint (`/v1/responses`) automatically. When the gateway path is unusual, turn on the `Full URL` toggle next to it and paste the complete endpoint verbatim.
Then expand `Advanced Options`:
- **API Format**: change from the default `Anthropic Messages (Native)` to **`OpenAI Responses API (Requires routing)`**. If the gateway only offers the Chat Completions protocol, choose `OpenAI Chat Completions (Requires routing)` here instead; every other step is identical.
- **Auth Field**: keep the default `ANTHROPIC_AUTH_TOKEN (Default)`; the route sends `Authorization: Bearer <key>` to the upstream — exactly the auth header an OpenAI-compatible gateway expects. Unless the gateway's documentation explicitly requires `x-api-key`, don't switch to `ANTHROPIC_API_KEY`; the wrong choice typically shows up as 401/403.
- **Model Mapping**: map Claude Code's model roles to the real models the gateway recognizes. **At minimum, fill in the `Default fallback model`** (e.g. `gpt-5.6`, per the gateway's documentation) — if left empty, unmatched requests pass through to the upstream under the original Claude model name and error out, while roles you haven't configured individually fall back to it. For finer control, specify per row: put your main model in `Sonnet`/`Opus`, and a cheap, fast model in `Haiku` (Claude Code's background sub-tasks use this tier). The `Display name` only affects what shows in the `/model` menu; leave it empty to show the real model name directly.
- **Declare 1M**: the `1M` checkbox on each model-mapping row declares to Claude Code that the tier supports a 1M context. Check it only when the gateway truly serves that model with a window of one million tokens or more (e.g. a gateway offering gpt-5.6 at its API spec); otherwise long conversations will error out at the upstream's real ceiling.
![Method 1: in Advanced Options, set API Format to OpenAI Responses, keep the default auth field, and map to the upstream's real models](../images/claude-codex-routing/02-responses-provider-form.png)
After saving, a `Needs Routing` marker appears on the card — providers like this only work while local routing is running.
### Method 2: ChatGPT subscription (Codex OAuth)
Again on the `Claude Code` tab, click the plus button and pick the **`Codex`** preset with the OpenAI icon from the preset list — it appearing under the Claude Code tab is not a mistake; this preset is built precisely for "using a ChatGPT subscription inside Claude Code":
- **No API Key and no address needed** — requests always go to ChatGPT's Codex service, so the address field in the form needs no changes.
- Click **`Sign in with ChatGPT`**. This is a device-code flow: CC Switch opens the browser automatically and copies the verification code to the clipboard; paste the code on the browser page to complete authorization, while the app shows `Waiting for authorization...`.
- After a successful sign-in, `Auth status` shows the signed-in account (email). Multiple accounts are supported: you can `Add another account`, `Set as default`, or pin a specific account to this provider; day-to-day management can also go through `Settings``OAuth Authentication Center`.
- **FAST mode**: an optional toggle; when on, requests carry `service_tier="priority"` for lower latency but consume ChatGPT quota at a higher rate. Keep it off by default.
- The model tiers are pre-filled: `Sonnet`/`Opus` map to `gpt-5.6`, and `Haiku` maps to `gpt-5.6-luna` (used for background sub-tasks — faster and lighter on quota).
![Method 2: ChatGPT login status and account management in the Codex preset](../images/claude-codex-routing/03-codex-oauth-form.png)
The login credentials are stored in `~/.cc-switch/codex_oauth_auth.json` (not `~/.codex/`), independent of the Codex CLI's own login; the token refreshes automatically before it expires.
## Step 2: Enable local routing and take over Claude Code
Go to the `Routing` page in Settings, expand `Local Routing`, and complete two toggles:
1. Turn on the `Routing Master Switch` to start the local service (the first time you enable it, an explanatory confirmation dialog appears). The default address is `127.0.0.1:15721`.
2. Turn on `Claude Code` under `Routing Enabled`. If you only want Claude Code to use routing, leave the other apps off.
After takeover, CC Switch points Claude Code's live config at the local route, with only a placeholder in the auth entry; both Method 1's gateway key and Method 2's OAuth token are injected by the local route on forward.
> **Note**: the live config is read when the Claude Code process starts. After you first enable takeover (or disable it to restore a direct connection), if Claude Code is already running, open a new terminal session. Afterward, switching providers in routing mode is a hot switch and needs no further restart.
## Step 3: Switch providers and verify
Return to the Claude Code provider list and click `Enable` on the target provider. If routing isn't running, CC Switch shows "This provider uses OpenAI Responses API format, requires the routing service to work properly. Start routing first." — this notice doesn't block the switch, but with routing off the request is bound to fail, so go back to Step 2 and turn it on.
Inside Claude Code you can verify step by step:
- Open a new session and use `/model` to view the model menu: each tier shows the display name from the model mapping (by default, Method 2 shows `gpt-5.6` and `gpt-5.6-luna`). A few spots in the UI may still show Claude-family model names — those are the internal role aliases the routing takeover uses; this is normal, and the `/model` menu and usage dashboard are authoritative.
- Send a small question and watch the `Current Provider` on the Settings → Routing page change to your provider and `Total Requests` start to climb.
- In the usage dashboard, these requests show under the upstream's real models: a tier mapped to `gpt-5.6` resolves to the Sol tier and displays as `GPT-5.6 Sol`, while `gpt-5.6-luna` displays as `GPT-5.6 Luna`; you can filter by provider to reconcile token usage.
- The Method 2 provider card also shows subscription quota: utilization and reset countdowns for the 5-hour and 7-day windows, drawn from the ChatGPT account itself and shared with the official Codex client.
## Capabilities and known limitations
- **Prompt caching is automatic**: the route injects a stable `prompt_cache_key` per session, and together with OpenAI's automatic prefix caching, long conversations don't resend everything at full price each turn — no configuration needed.
- **Thinking is mapped to reasoning effort**: Claude Code's thinking toggle and thinking level are mapped to GPT's `reasoning.effort` (low/medium/high); GPT's reasoning content round-trips across turns intact in encrypted form, so multi-turn reasoning coherence is unaffected by the conversion. Method 2 also accesses in stateless mode (`store:false`), leaving no conversation stored on OpenAI's servers.
- **Tools and multimodal are fully converted**: multi-turn tool calls, image inputs, and PDF inputs are all fully converted.
- **Context is managed against a 200K window**: Claude Code auto-compacts routed providers against a default 200K window. When the upstream's real window is larger (e.g. gpt-5.6 on ChatGPT's Codex service is 372K), anything beyond 200K currently goes unused — compaction triggers early, which is conservative but safe. The only switch to push past 200K today is the `1M` checkbox in the model mapping (a strict 1M declaration), for use only with Method 1 and only when the upstream truly serves the model at 1M or more; Method 2's upstream ceiling is 372K, short of 1M, so checking it would instead make long conversations error out at the upstream's real ceiling — keep it at the default.
- **Output ceiling**: for Method 2, the output ceiling is controlled by the ChatGPT server (the `max_tokens` in Claude Code's request is not sent downstream); for Method 1, Claude Code's `max_tokens` is passed through as-is — no configuration needed.
- **Web search is unavailable**: Claude Code's WebSearch relies on Anthropic's servers to run, which the GPT upstream can't take on, so for tasks involving web search, switch back to a Claude-family provider. Locally executed WebFetch is unaffected.
- **Dashboard dollar amounts are for reference**: token counts are accurate, but the dollar figures are estimates converted at public API prices — Method 2's subscription traffic is estimated at GPT-5.6's public price, and Method 1's third-party gateways bill at their own rates, so both may differ from what you're actually charged and serve only for comparison. For Method 2, treat the window utilization on the provider card as authoritative for quota consumption.
## FAQ
**The upstream returns 401 or 403 (Method 1)**
First confirm the `Auth Field` in Advanced Options is the default `ANTHROPIC_AUTH_TOKEN (Default)` — switching to `ANTHROPIC_API_KEY` sends `x-api-key`, which the vast majority of OpenAI-compatible gateways don't accept. Then confirm the key itself is valid and has balance.
**Requesting new models like `gpt-5.6-luna` returns 404 Model not found (Method 2)**
Upgrade to CC Switch 3.17.0 or later. On older versions the client identity wasn't aligned with the official Codex client, so the ChatGPT server resolves new models to a nonexistent engine.
**The switch didn't take effect, or the `/model` menu still shows old names**
Both the model menu and the route address are read when Claude Code starts: after first enabling takeover you must open a new terminal session; switching between providers is a hot switch, but the display names in the menu only refresh in a new session.
**Claude Code reports "Codex OAuth authentication failed", or the card shows "Session expired" (Method 2)**
The login credentials have expired. Go back to the provider form or `Settings``OAuth Authentication Center` and run through `Sign in with ChatGPT` again; no command-line steps are needed.
**The conversation auto-compacts partway through**
See "Capabilities and known limitations": routed providers are managed against a 200K window, so the compaction threshold comes early — this is expected behavior.
**Restoring the official Claude setup**
Switch back to an official provider, or turn off the `Claude Code` routing toggle on the Routing page — CC Switch restores the pre-takeover live config, and the official login credentials are unaffected throughout. After restoring, you'll again need to open a new terminal session.
**Should you enable FAST mode? (Method 2)**
Leaving it off is fine. Turn it on only if you're especially latency-sensitive and willing to accept faster quota consumption; if the ChatGPT server rejects the parameter, turning the toggle off restores things.
## Compliance note
Method 2 uses ChatGPT subscription quota outside the official Codex client, and this isn't a gray-area hack: Thibault Sottiaux (@thsottiaux), the OpenAI Codex lead, has publicly demonstrated and encouraged pointing Claude Code (the "orange crab", as he jokingly calls it) at GPT-5.6 Sol — using exactly a "local proxy + model alias" approach, the same category as Method 2 here. As the lead of the Codex product line, his active encouragement to use their own model inside a competitor's client shows that running GPT-family models in Claude Code on a subscription is a use the vendor welcomes and encourages people to try.
Two practical reminders are still worth noting: first, this traffic is counted against the same subscription quota as the official Codex client, so heavy use hits the cap sooner; second, CC Switch's authentication center keeps a compliance notice out of caution ("Use your other subscriptions in Claude Code — please be mindful of compliance risks."), and whether this fits the terms that apply to your account is for you to check. When using a third-party gateway in Method 1, separately read the target gateway's terms on billing, compliance, and data retention.
## References
- [CC Switch User Manual: Add a Provider (incl. Codex OAuth reverse proxy and API formats)](../user-manual/en/2-providers/2.1-add.md)
- [CC Switch User Manual: Proxy Service](../user-manual/en/4-proxy/4.1-service.md)
- [CC Switch User Manual: App Routing](../user-manual/en/4-proxy/4.2-routing.md)
- [CC Switch v3.17.0 Release Notes](../release-notes/v3.17.0-en.md)
- Reverse guide: [Using Claude Models in Codex](./codex-claude-routing-guide-en.md)
@@ -0,0 +1,141 @@
# CC Switch を使って Claude Code で GPT モデルを利用する
> 対象バージョン: CC Switch 3.17.0 以降(本記事の 2 つの接続方法自体はより古いバージョンにもありますが、gpt-5.6 プリセットとクライアントアイデンティティの修正は 3.17.0 から導入されたため、古いバージョンで `gpt-5.6-luna` のような新しいモデルをリクエストすると 404 が誤って返ることがあります)。本記事はリポジトリ内のドキュメントとコードをもとに整理し、サンプルデータはすべて匿名化しています。
## ローカルルーティングが必要な理由
Claude Code が前提としているのは Anthropic Messages プロトコル、つまり `/v1/messages` です。一方で Codex 系モデルの上流——サードパーティゲートウェイが公開している OpenAI Responses API であれ、ChatGPT サブスクリプションの背後にある Codex サービスであれ——が話すのはすべて Responses プロトコルです。この 2 つのプロトコルは、リクエストボディ、ストリーミングイベント、レスポンス構造がまったく異なります。この種のアドレスをそのまま Claude Code の設定に入れても、上流が受け取るのは自分の知らない `/v1/messages` リクエストであり、結果は失敗にしかなりません。
CC Switch では、Claude Code が常にローカルルートへ接続し、Anthropic Messages のままリクエストを送るようにします。ルートは現在のプロバイダーが Responses 形式だと判定すると、リクエストを Responses に変換して上流へ送り、最後にレスポンスを Messages 形式へ戻して Claude Code に返します——ツール呼び出し、画像、PDF、思考設定もすべて変換の対象です。
対応する 2 つの接続方法を、本記事はどちらもカバーします:
- **方式 1API Key**: OpenAI Responses API 互換のゲートウェイエンドポイントと Key を持っていて、その背後の GPT 系モデルを Claude Code で動かしたい場合。
- **方式 2(ChatGPT サブスクリプション)**: ChatGPT Plus/Pro のサブスクリプションを持っていて、Codex OAuth ログインでサブスクリプション枠を直接使いたい場合。全工程で API Key は不要です。
この経路は主に 4 つのステップに分かれます:
1. Claude Code を引き継ぐと、`~/.claude/settings.json``ANTHROPIC_BASE_URL` がローカルルートのアドレス(デフォルトは `http://127.0.0.1:15721`)に書き換えられ、認証項目にはプレースホルダーだけが残り、実際の認証情報は live 設定には入りません。
2. プロバイダーの `API フォーマット` を OpenAI Responses に設定し、実際の上流は Responses プロトコルだとルートに伝えます。
3. ルートは `/v1/messages` リクエストを Responses のリクエストボディへ変換して上流へ送ります。方式 2 ではさらに OAuth token と公式クライアントのアイデンティティを付けて ChatGPT の Codex サービスにアクセスします。
4. 上流から返ってきた後、ルートは Responses の JSON/SSE を Claude Code が理解できる Messages 形式へ変換して返します。
![Claude プロバイダー一覧の GPT プロバイダーに付く「ルーティングが必要」マーク](../images/claude-codex-routing/01-claude-providers-require-routing.png)
## 事前準備
- インストール済みで起動できる CC Switch(3.17.0 以降、理由は冒頭のバージョン説明を参照)。
- インストール済みで、少なくとも 1 回は実行したことのある Claude Code。
- 方式 1 に必要なもの: OpenAI Responses API 互換のサービスエンドポイントと対応する API Key。エンドポイントアドレスとモデル名はゲートウェイのドキュメントに従ってください。注意すべきは **Responses API** であって Chat Completions ではないという点です。ゲートウェイが Chat 形式しか提供していない場合でも動作します。Step 1 の「API フォーマット」の説明を参照してください。
- 方式 2 に必要なもの: ChatGPT Plus/Pro のサブスクリプションアカウント。
## Step 1: プロバイダーを追加する
### 方式 1: サードパーティ Responses ゲートウェイ(API Key
CC Switch を開き、上部の `Claude Code` タブへ切り替え、右上のプラスボタンからプロバイダーを追加します。デフォルトの `カスタム設定` のまま、次の項目を入力します:
- **プロバイダー名**: 任意です。たとえば `GPT Gateway`
- **API Key**: あなたのゲートウェイの Key。実際の Key は CC Switch 内にのみ保存され、ローカルルートが転送時に注入します。
- **API エンドポイント**: ゲートウェイのサービスルートアドレスを入力すれば十分です。たとえば `https://gpt-gateway.example.com`。末尾にスラッシュを付けないでください。ルートが自動的にそのゲートウェイの Responses エンドポイント(`/v1/responses`)へリクエストを送ります。ゲートウェイのパスが特殊な場合は、隣の `フル URL` スイッチをオンにして、完全なエンドポイントをそのまま貼り付けてください。
続いて `高級オプション` を展開します:
- **API フォーマット**: デフォルトの `Anthropic Messages(ネイティブ)` から **`OpenAI Responses API(ルーティングが必要)`** に変更します。ゲートウェイが Chat Completions プロトコルしか提供していない場合は、ここで `OpenAI Chat Completions(ルーティングが必要)` を選びます。その他のステップはまったく同じです。
- **認証フィールド**: デフォルトの `ANTHROPIC_AUTH_TOKEN(デフォルト)` のままにします。ルートは `Authorization: Bearer <key>` を上流へ送ります——これはまさに OpenAI 互換ゲートウェイが期待する認証ヘッダーです。ゲートウェイのドキュメントが明確に `x-api-key` を要求している場合を除き、`ANTHROPIC_API_KEY` に変更しないでください。誤って変更した場合の典型的な症状は 401/403 です。
- **モデルマッピング**: Claude Code のモデル役割を、ゲートウェイが認識する実際のモデルへマッピングします。**少なくとも `既定フォールバックモデル` は入力してください**(たとえば `gpt-5.6`。ゲートウェイのドキュメントに従ってください)——空欄のままだと、一致しなかったリクエストは元の Claude モデル名のまま上流へ転送されてエラーになります。個別に設定していない役割はこのフォールバックへ回帰します。より細かく設定するには、行ごとに指定します:`Sonnet`/`Opus` に主力モデル、`Haiku` に安価で高速なモデル(Claude Code のバックグラウンド小タスクがこの区分を使います)。`表示名``/model` メニューでの表示にのみ影響し、空欄なら実際のモデル名がそのまま表示されます。
- **1M 対応を宣言**: モデルマッピングの各行にある `1M` チェックボックスは、その区分が 1M コンテキストに対応していることを Claude Code に宣言します。ゲートウェイが実際に 100 万トークン以上のウィンドウでそのモデルを提供している場合(たとえば API 仕様どおりに gpt-5.6 を提供するゲートウェイ)にのみチェックしてください。そうでないと、長い対話が上流の実際の上限で直接エラーになります。
![方式 1: 高級オプションで API フォーマットを OpenAI Responses に設定し、認証フィールドはデフォルトのまま、上流の実際のモデルへマッピングする](../images/claude-codex-routing/02-responses-provider-form.png)
保存すると、カードに `ルーティングが必要` のマークが表示されます——この種のプロバイダーは、ローカルルーティングが実行中でなければ正しく動作しません。
### 方式 2: ChatGPT サブスクリプション(Codex OAuth
同じく `Claude Code` タブでプラスボタンを押し、プリセット一覧で OpenAI アイコンの付いた **`Codex`** プリセットを選びます——これが Claude Code タブの下に出ていても選択ミスではありません。このプリセットはまさに「Claude Code で ChatGPT サブスクリプションを使う」ために用意されたものです:
- **API Key もアドレスの入力も不要です**——リクエストは常に ChatGPT の Codex サービスへ送られるため、フォームのアドレス項目は変更する必要がありません。
- **`ChatGPT でログイン`** をクリックします。これはデバイスコードフローです:CC Switch が自動的にブラウザを開き、認証コードをクリップボードにコピーします。ブラウザのページで認証コードを貼り付けて認可を完了させてください。その間、アプリ内には `認証を待機中...` と表示されます。
- ログインに成功すると、`認証状態` にログイン済みアカウント(メールアドレス)が表示されます。複数アカウントに対応しています:`別のアカウントを追加``デフォルトに設定`、またはこのプロバイダーで特定のアカウントを指定できます。日常的な管理は `設定``OAuth 認証センター` からも行えます。
- **FAST モード**: 任意のスイッチです。オンにするとリクエストが `service_tier="priority"` を伴い、より低い遅延と引き換えに、より高いレートで ChatGPT のクォータを消費します。デフォルトはオフのままにしてください。
- モデル区分はあらかじめ入力済みです:`Sonnet`/`Opus``gpt-5.6` に、`Haiku``gpt-5.6-luna` に対応します(バックグラウンドの小タスクがこれを使い、より速く、より枠を節約します)。
![方式 2: Codex プリセットの ChatGPT ログイン状態とアカウント管理](../images/claude-codex-routing/03-codex-oauth-form.png)
ログイン認証情報は `~/.cc-switch/codex_oauth_auth.json``~/.codex/` ではありません)に保存され、Codex CLI 自身のログインとは互いに影響しません。token は有効期限前に自動的に更新されます。
## Step 2: ローカルルーティングを有効にして Claude Code をルーティングする
設定の `ルーティング` ページに入り、`ローカルルーティング` を展開して、2 つのスイッチを設定します:
1. `ルーティング総スイッチ` をオンにしてローカルサービスを起動します(初回起動時は説明の確認ダイアログが表示されます)。デフォルトアドレスは `127.0.0.1:15721` です。
2. `ルーティング有効``Claude Code` をオンにします。Claude Code だけをルーティングしたい場合は、その他のアプリはオフのままで構いません。
引き継ぎ後、CC Switch は Claude Code の live 設定をローカルルートへ向け、認証項目にはプレースホルダーだけが入ります。方式 1 のゲートウェイ Key も方式 2 の OAuth token も、いずれもローカルルートが転送時に注入します。
> **注意**: live 設定は Claude Code プロセスの起動時に読み込まれます。初回の引き継ぎを有効にした後(または引き継ぎをオフにして直結に戻した後)、Claude Code が実行中の場合は、ターミナルセッションを開き直してください。その後、ルーティングモードでのプロバイダー切り替えはホットスワップになり、再起動は不要です。
## Step 3: プロバイダーを切り替えて確認する
Claude Code のプロバイダー一覧に戻り、目的のプロバイダーの `有効化` をクリックします。ルーティングが実行されていない場合、CC Switch は「このプロバイダーは OpenAI Responses API フォーマットを使用しており、ルーティングサービスが必要です。先にルーティングを起動してください」と表示します——この表示は切り替えを妨げませんが、ルーティングが未起動のままではリクエストは必ず失敗します。Step 2 に戻ってオンにすれば解決します。
Claude Code に入ったら、段階的に確認できます:
- 新しいセッションを開き、`/model` でモデルメニューを確認します:各区分にはモデルマッピングの表示名が表示されます(方式 2 のデフォルトは `gpt-5.6``gpt-5.6-luna`)。画面の一部の箇所には Claude 系のモデル名が現れることがあります——それはルーティング引き継ぎが使う内部の役割エイリアスであり、正常な現象です。`/model` メニューと使用量ダッシュボードを基準にしてください。
- 小さな質問を 1 つ送り、設定 → ルーティングページの「現在のプロバイダー」があなたのプロバイダーに変わり、「総リクエスト数」が増え始めるのを確認します。
- 使用量ダッシュボードでは、これらのリクエストが上流の実際のモデルで表示されます:`gpt-5.6` にマッピングされた区分は Sol 区分として解析され `GPT-5.6 Sol` と表示され、`gpt-5.6-luna``GPT-5.6 Luna` と表示されます。プロバイダーで絞り込んで token 使用量を照合できます。
- 方式 2 のプロバイダーカードには、さらにサブスクリプション枠が表示されます:5 時間ウィンドウと 7 日ウィンドウの利用率とリセットまでのカウントダウンです。データは ChatGPT アカウント自体から取得され、公式 Codex クライアントと同じ枠を共有します。
## 機能の範囲と既知の制限
- **プロンプトキャッシュが自動で有効**: ルートは各セッションに安定した `prompt_cache_key` を注入し、OpenAI 側の自動プレフィックスキャッシュと組み合わせます。長い対話でも毎回全額で再送されることはなく、設定は不要です。
- **思考を reasoning effort に換算**: Claude Code の思考スイッチと思考レベルは GPT の `reasoning.effort`low/medium/high)へ換算されます。GPT の推論内容は暗号化された形態でターンをまたいで完全に再生され、複数ターンの推論の一貫性は変換の影響を受けません。方式 2 は同時にステルスモード(`store:false`)でアクセスし、OpenAI サーバー側にはセッションを残しません。
- **ツールとマルチモーダルを完全変換**: 複数ターンのツール呼び出し、画像、PDF 入力はすべて完全に変換されます。
- **コンテキストは 200K ウィンドウで管理**: Claude Code はルーティングプロバイダーに対して、デフォルトの 200K ウィンドウで自動圧縮を行います。上流の実際のウィンドウがより大きい場合(たとえば ChatGPT Codex サービスの gpt-5.6 は 372K)でも、200K を超える部分は現状では使われません——圧縮が早めにトリガーされ、保守的ですが安全です。200K を突破したい場合、現在唯一のスイッチはモデルマッピングの `1M` チェックボックス(厳密に 1M を宣言)で、方式 1 に限り、かつ上流が実際に 1M 以上でそのモデルを提供している場合にのみ使用します。方式 2 の上流上限は 372K で 1M には届かないため、チェックするとかえって長い対話が上流の実際の上限でエラーになります。デフォルトのままにしてください。
- **出力上限**: 方式 2 の出力上限は ChatGPT サーバー側が制御します(Claude Code のリクエスト内の `max_tokens` は下流に送られません)。方式 1 は Claude Code の `max_tokens` をそのまま透過するため、設定は不要です。
- **Web 検索は利用不可**: Claude Code の WebSearch は Anthropic サーバー側での実行に依存しており、GPT 上流では引き受けられません。Web 検索を伴うタスクは Claude 系プロバイダーへ切り替えることをおすすめします。ローカルで実行される WebFetch は影響を受けません。
- **使用量ダッシュボードの金額は参考値**: token カウントは正確ですが、ドル金額は公開 API 価格に基づく概算です——方式 2 のサブスクリプショントラフィックは GPT-5.6 の公開価格で換算され、方式 1 のサードパーティゲートウェイはそれぞれのレートで課金されます。どちらも実際の請求額と一致しない可能性があり、比較用途に留めてください。方式 2 の枠の消費は、プロバイダーカード上のウィンドウ利用率を基準にしてください。
## よくある質問
**上流が 401 または 403 を返す(方式 1)**
まず高級オプションの `認証フィールド` がデフォルトの `ANTHROPIC_AUTH_TOKEN(デフォルト)` になっているか確認してください——`ANTHROPIC_API_KEY` に変更すると `x-api-key` で送信され、大多数の OpenAI 互換ゲートウェイはこれを受け付けません。あわせて、Key 自体が有効で残高があることも確認してください。
**`gpt-5.6-luna` などの新しいモデルをリクエストすると 404 Model not found が出る(方式 2**
CC Switch 3.17.0 以降にアップグレードしてください。古いバージョンではクライアントアイデンティティが公式 Codex クライアントに揃っておらず、ChatGPT サーバー側が新しいモデルを存在しないエンジンへ解決してしまいます。
**切り替えても反映されない、または `/model` メニューが古い名前のまま**
モデルメニューもルーティングアドレスも、Claude Code の起動時に読み込まれます:初回の引き継ぎを有効にした後は必ずターミナルセッションを開き直してください。プロバイダー間の切り替えはホットスワップですが、メニューの表示名は新しいセッションでなければ更新されません。
**Claude Code に「Codex OAuth 認証に失敗しました」と出る、またはカードに「セッションが期限切れです」と表示される(方式 2)**
ログイン認証情報が失効しています。プロバイダーフォーム、または `設定``OAuth 認証センター` に戻り、`ChatGPT でログイン` をもう一度実行してください。コマンドライン操作は一切不要です。
**対話の途中で自動的に圧縮されてしまう**
「機能の範囲」を参照してください:ルーティングプロバイダーは 200K ウィンドウで管理され、圧縮のしきい値もそれに合わせて早まります。想定どおりの動作です。
**公式の Claude の使い方に戻したい**
公式プロバイダーに切り替えるか、ルーティングページで `Claude Code` のルーティングスイッチをオフにしてください——CC Switch は引き継ぎ前の live 設定に戻し、公式ログインの認証情報は全工程を通じて影響を受けません。戻した後も同様にターミナルセッションを開き直す必要があります。
**FAST モードをオンにすべきか(方式 2)**
デフォルトのオフのままで構いません。遅延に特に敏感で、かつクォータのより速い消費を受け入れられる場合にのみオンにしてください。ChatGPT サーバー側がこのパラメータを拒否する場合は、スイッチをオフにすれば復旧します。
## コンプライアンスに関する注意
方式 2 は ChatGPT サブスクリプション枠を公式 Codex クライアント以外で使うものですが、これはグレーな手法ではありません:OpenAI Codex の責任者である Thibault Sottiaux@thsottiaux)自身が、Claude Code(彼が「orange crab」と呼ぶもの)を GPT-5.6 Sol に向けて使うことを公開でデモし、推奨しています——用いているのはまさに「ローカルプロキシ + モデルエイリアス」であり、本記事の方式 2 と同じ類の手法です。Codex という製品ラインの責任者が、競合クライアントで自社モデルを使うことを自ら奨励しているのですから、サブスクリプションで Claude Code に GPT 系モデルを動かすことは、公式が歓迎し、試すことを推奨している使い方だと分かります。
とはいえ、実務上の 2 点は依然として留意する価値があります:1 つは、この部分のトラフィックが公式 Codex クライアントと同じサブスクリプション枠に合算されるため、ヘビーユースではより速く上限に達すること。もう 1 つは、CC Switch の認証センターが念のためコンプライアンス上の注意(「Claude Code で他のサブスクリプションをご利用いただけます。コンプライアンスリスクにご注意ください。」)を残していることです。あなたのアカウントに適用される規約に沿うかどうかは、各自でご確認ください。方式 1 でサードパーティゲートウェイを使う場合は、対象ゲートウェイの課金・コンプライアンス・データ保持に関する規約を別途お読みください。
## 参考リンク
- [CC Switch ユーザーマニュアル: プロバイダーを追加(Codex OAuth リバースプロキシと API フォーマットを含む)](../user-manual/ja/2-providers/2.1-add.md)
- [CC Switch ユーザーマニュアル: プロキシサービス](../user-manual/ja/4-proxy/4.1-service.md)
- [CC Switch ユーザーマニュアル: アプリケーションルーティング](../user-manual/ja/4-proxy/4.2-routing.md)
- [CC Switch v3.17.0 リリースノート](../release-notes/v3.17.0-ja.md)
- 逆方向のガイド: [Codex で Claude モデルを使う](./codex-claude-routing-guide-ja.md)
@@ -0,0 +1,141 @@
# 通过 CC Switch 在 Claude Code 中使用 GPT 模型
> 适用版本:CC Switch 3.17.0 及以上(更早版本已具备本文两种接入方式,但 gpt-5.6 预设与客户端身份修复自 3.17.0 落地,低版本请求 `gpt-5.6-luna` 这类新模型会误报 404)。本文根据仓库内文档与代码整理,示例数据均已去敏。
## 为什么需要本地路由
Claude Code 面向的是 Anthropic Messages 协议,也就是 `/v1/messages`;而 Codex 系模型的上游——无论是第三方网关暴露的 OpenAI Responses API,还是 ChatGPT 订阅背后的 Codex 服务——说的都是 Responses 协议。两种协议的请求体、流式事件和返回结构完全不同,把这类地址直接填进 Claude Code 的配置里,上游收到的是它不认识的 `/v1/messages` 请求,结果只能是失败。
CC Switch 的做法是让 Claude Code 始终连本机路由,仍以 Anthropic Messages 发送请求;路由识别当前供应商是 Responses 格式后,把请求转换成 Responses 发给上游,再把响应转换回 Messages 形态返回给 Claude Code——工具调用、图片、PDF、思考配置都在转换范围内。
对应两种接入方式,本文都会覆盖:
- **方式一(API Key**:你手里有某个兼容 OpenAI Responses API 的网关端点和 Key,想在 Claude Code 里跑它背后的 GPT 系模型。
- **方式二(ChatGPT 订阅)**:你有 ChatGPT Plus/Pro 订阅,通过 Codex OAuth 登录直接使用订阅额度,全程不需要 API Key。
这条链路主要分成四步:
1. 接管 Claude Code 后,`~/.claude/settings.json` 里的 `ANTHROPIC_BASE_URL` 会被写成本机路由地址(默认 `http://127.0.0.1:15721`),认证项只留占位符,真实凭据不进 live 配置。
2. 供应商的 `API 格式` 设为 OpenAI Responses,告诉路由:真实上游说的是 Responses 协议。
3. 路由把 `/v1/messages` 请求转换成 Responses 请求体发给上游;方式二还会带上 OAuth token 与官方客户端身份访问 ChatGPT 的 Codex 服务。
4. 上游返回后,路由再把 Responses 的 JSON/SSE 转回 Claude Code 能理解的 Messages 形态。
![Claude 供应商列表里 GPT 供应商的「需要路由」标记](../images/claude-codex-routing/01-claude-providers-require-routing.png)
## 准备工作
- 已安装并能启动的 CC Switch(3.17.0 及以上,原因见开头的版本说明)。
- 已安装 Claude Code,并至少运行过一次。
- 方式一需要:一个兼容 OpenAI Responses API 的服务端点和对应的 API Key,端点地址与模型名以网关文档为准。注意是 **Responses API**,不是 Chat Completions;网关只提供 Chat 格式时也能走通,见第一步「API 格式」处的说明。
- 方式二需要:一个 ChatGPT Plus/Pro 订阅账号。
## 第一步:添加供应商
### 方式一:第三方 Responses 网关(API Key
打开 CC Switch,切到顶部的 `Claude Code` 标签,点击右上角加号添加供应商,保持默认的 `自定义配置`,然后填写:
- **供应商名称**:随意,例如 `GPT Gateway`
- **API Key**:你的网关 Key。真实 Key 只保存在 CC Switch 里,由本地路由转发时注入。
- **请求地址**:填网关服务根地址即可,例如 `https://gpt-gateway.example.com`,不要以斜杠结尾,路由会自动把请求打到该网关的 Responses 端点(`/v1/responses`)。网关路径特殊时,打开旁边的 `完整 URL` 开关原样粘贴完整端点。
然后展开 `高级选项`
- **API 格式**:从默认的 `Anthropic Messages (原生)` 改成 **`OpenAI Responses API (需开启路由)`**。如果网关只提供 Chat Completions 协议,这里改选 `OpenAI Chat Completions (需开启路由)`,其余步骤完全相同。
- **认证字段**:保持默认的 `ANTHROPIC_AUTH_TOKEN(默认)`,路由会以 `Authorization: Bearer <key>` 发给上游——这正是 OpenAI 兼容网关期望的认证头。除非网关文档明确要求 `x-api-key`,否则不要改成 `ANTHROPIC_API_KEY`,改错的典型表现是 401/403。
- **模型映射**:把 Claude Code 的模型角色映射到网关认识的真实模型。**至少要填 `默认兜底模型`**(例如 `gpt-5.6`,以网关文档为准)——留空时未匹配的请求会以原始 Claude 模型名透传给上游而报错,未单独配置的角色则会回落到它。更精细的做法是按行指定:`Sonnet`/`Opus` 填主力模型,`Haiku` 填一个便宜快速的模型(Claude Code 的后台小任务走这一档)。`显示名称` 只影响 `/model` 菜单里的展示,留空则直接显示真实模型名。
- **声明支持 1M**:模型映射每行的 `1M` 复选框会向 Claude Code 声明该档支持 1M 上下文。仅当网关确实以 100 万 token 及以上的窗口服务该模型时才勾选(例如按 API 规格提供 gpt-5.6 的网关),否则长对话会在上游真实上限处直接报错。
![方式一:高级选项里把 API 格式设为 OpenAI Responses,认证字段保持默认,并映射到上游真实模型](../images/claude-codex-routing/02-responses-provider-form.png)
保存后,卡片上会出现 `需要路由` 标记——这类供应商必须在本地路由运行时才能正常工作。
### 方式二:ChatGPT 订阅(Codex OAuth
同样在 `Claude Code` 标签点加号,在预设列表里选择带 OpenAI 图标的 **`Codex`** 预设——它出现在 Claude Code 标签下没有选错,这个预设就是为「在 Claude Code 里用 ChatGPT 订阅」准备的:
- **不需要 API Key,也不需要填地址**——请求固定发往 ChatGPT 的 Codex 服务,表单里的地址项无需改动。
- 点击 **`使用 ChatGPT 登录`**。这是设备码流程:CC Switch 会自动打开浏览器并把验证码复制到剪贴板,在浏览器页面粘贴验证码完成授权即可,期间应用内显示 `等待授权中...`
- 登录成功后,`认证状态` 显示已登录账号(邮箱)。支持多账号:可 `添加其他账号``设为默认`,或在这个供应商上指定使用某个账号;日常管理也可以走 `设置``OAuth 认证中心`
- **FAST 模式**:可选开关,开启后请求携带 `service_tier="priority"` 换取更低延迟,但会按更高速率消耗 ChatGPT 配额,默认保持关闭。
- 模型档位已预填好:`Sonnet`/`Opus` 对应 `gpt-5.6``Haiku` 对应 `gpt-5.6-luna`(后台小任务走它,更快更省额度)。
![方式二:Codex 预设的 ChatGPT 登录状态与账号管理](../images/claude-codex-routing/03-codex-oauth-form.png)
登录凭据保存在 `~/.cc-switch/codex_oauth_auth.json`(不是 `~/.codex/`),与 Codex CLI 自己的登录互不影响;token 会在到期前自动刷新。
## 第二步:开启本地路由并接管 Claude Code
进入设置里的 `路由` 页面,展开 `本地路由`,完成两个开关:
1. 打开 `路由总开关`,启动本地服务(首次开启会弹出说明确认框)。默认地址是 `127.0.0.1:15721`
2.`路由启用` 中打开 `Claude Code`。只想让 Claude Code 走路由的话,其余应用保持关闭。
接管后,CC Switch 会把 Claude Code 的 live 配置指向本机路由,认证项只有占位符;方式一的网关 Key 和方式二的 OAuth token 都由本地路由在转发时注入。
> **注意**live 配置是 Claude Code 进程启动时读取的。首次开启接管(或关闭接管恢复直连)后,如果 Claude Code 正在运行,请重开一个终端会话。之后在路由模式下切换供应商就是热切换,无需再重启。
## 第三步:切换供应商并验证
回到 Claude Code 供应商列表,点击目标供应商的 `启用`。如果路由没有在运行,CC Switch 会提示「此供应商使用 OpenAI Responses 接口格式,需要路由服务才能正常使用,请先启动路由」——这个提示不会拦截切换,但路由未开时请求必然失败,回到第二步打开即可。
进入 Claude Code 后可以逐级验证:
- 新开会话,用 `/model` 查看模型菜单:各档显示的是模型映射里的显示名称(方式二默认即 `gpt-5.6``gpt-5.6-luna`)。界面个别位置仍可能出现 Claude 系的模型字样——那是路由接管使用的内部角色别名,属正常现象,以 `/model` 菜单和用量看板为准。
- 发一个小问题,观察设置 → 路由页面的「当前 Provider」变成你的供应商、「总请求数」开始增长。
- 用量看板里,这些请求会按上游真实模型显示:映射到 `gpt-5.6` 的档位解析为 Sol 档、显示为 `GPT-5.6 Sol``gpt-5.6-luna` 显示为 `GPT-5.6 Luna`,可按供应商筛选核对 token 用量。
- 方式二的供应商卡片还会显示订阅额度:5 小时与 7 天窗口的利用率和重置倒计时,数据来自 ChatGPT 账号本身,与官方 Codex 客户端共用同一份额度。
## 能力边界与已知限制
- **提示缓存自动生效**:路由会为每个会话注入稳定的 `prompt_cache_key`,配合 OpenAI 侧的自动前缀缓存,长对话不会每轮全价重发,无需任何配置。
- **思考折算为 reasoning effort**Claude Code 的思考开关与思考等级会被折算成 GPT 的 `reasoning.effort`low/medium/high);GPT 的推理内容以加密形态跨轮完整回放,多轮推理连贯性不受转换影响。方式二同时以无痕模式(`store:false`)访问,不在 OpenAI 服务端留存会话。
- **工具与多模态完整转换**:多轮工具调用、图片与 PDF 输入都被完整转换。
- **上下文按 200K 窗口管理**Claude Code 对路由供应商按默认 200K 窗口做自动压缩。上游实际窗口更大时(如 ChatGPT Codex 服务的 gpt-5.6 为 372K),超出 200K 的部分当前不会被用到——压缩会提前触发,保守但安全。想突破 200K,目前唯一的开关是模型映射里的 `1M` 复选框(严格声明 1M),仅限方式一且上游真按 1M 及以上服务该模型时使用;方式二的上游上限是 372K、够不到 1M,勾选反而会让长对话在上游真实上限处报错,请维持默认。
- **输出上限**:方式二的输出上限由 ChatGPT 服务端控制(Claude Code 请求里的 `max_tokens` 不会下发);方式一则原样透传 Claude Code 的 `max_tokens`,无需配置。
- **联网搜索不可用**Claude Code 的 WebSearch 依赖 Anthropic 服务端执行,GPT 上游无法承接,涉及联网搜索的任务建议切回 Claude 系供应商。本地执行的 WebFetch 不受影响。
- **用量看板金额是参考值**:token 计数准确,但美元金额是按公开 API 价折算的估算——方式二订阅流量按 GPT-5.6 公开价折算,方式一的第三方网关按各自费率计费,两者都可能与真实扣费不符,仅供对比。方式二的额度消耗以供应商卡片上的窗口利用率为准。
## 常见问题
**上游返回 401 或 403(方式一)**
先确认高级选项里的 `认证字段` 是默认的 `ANTHROPIC_AUTH_TOKEN(默认)`——改成 `ANTHROPIC_API_KEY` 会以 `x-api-key` 发送,绝大多数 OpenAI 兼容网关不接受。再确认 Key 本身有效、有余额。
**请求 `gpt-5.6-luna` 等新模型报 404 Model not found(方式二)**
升级到 CC Switch 3.17.0 及以上。旧版本的客户端身份未对齐官方 Codex 客户端,ChatGPT 服务端会把新模型解析到不存在的引擎。
**切换后没生效,或 `/model` 菜单还是旧名字**
模型菜单和路由地址都是 Claude Code 启动时读取的:首次开启接管后必须重开终端会话;供应商之间切换虽然是热切换,但菜单里的显示名称要新会话才刷新。
**Claude Code 报「Codex OAuth 认证失败」或卡片显示「会话已过期」(方式二)**
登录凭据已失效。回到供应商表单或 `设置``OAuth 认证中心`,重新走一遍 `使用 ChatGPT 登录` 即可;无需运行任何命令行操作。
**对话进行到一半就自动压缩了**
见「能力边界」:路由供应商按 200K 窗口管理,压缩阈值随之提前,属预期行为。
**想恢复官方 Claude 用法**
切回官方供应商,或在路由页面关闭 `Claude Code` 的路由开关——CC Switch 会恢复接管前的 live 配置,官方登录凭据全程不受影响。恢复后同样需要重开终端会话。
**FAST 模式要不要开(方式二)**
默认关闭即可。只有当你对延迟特别敏感、且愿意接受配额更快消耗时再打开;如果 ChatGPT 服务端拒绝该参数,关掉开关即可恢复。
## 合规提示
方式二把 ChatGPT 订阅额度用在官方 Codex 客户端之外,这并不是灰色玩法:OpenAI Codex 负责人 Thibault Sottiaux@thsottiaux)就公开演示并鼓励过把 Claude Code(他戏称的「orange crab」)指向 GPT-5.6 Sol 使用——用的正是「本地代理 + 模型别名」,和本文方式二属于同一类做法。作为 Codex 这条产品线的负责人,他主动鼓励大家在竞品客户端里用自家模型,可见用订阅在 Claude Code 里跑 GPT 系模型,是官方乐见并鼓励尝试的用法。
两点实务提醒仍值得留意:一是这部分流量与官方 Codex 客户端合并计入同一份订阅额度,重度使用会更快触顶;二是 CC Switch 认证中心出于稳妥保留了合规提示(「在 Claude Code 中使用您的其他订阅,请注意合规风险。」),是否符合你账号所适用的条款可自行留意。方式一使用第三方网关时,请另行阅读目标网关关于计费、合规与数据留存的条款。
## 参考链接
- [CC Switch 用户手册:添加供应商(含 Codex OAuth 反向代理与 API 格式)](../user-manual/zh/2-providers/2.1-add.md)
- [CC Switch 用户手册:代理服务](../user-manual/zh/4-proxy/4.1-service.md)
- [CC Switch 用户手册:应用路由](../user-manual/zh/4-proxy/4.2-routing.md)
- [CC Switch v3.17.0 发布说明](../release-notes/v3.17.0-zh.md)
- 反方向攻略:[在 Codex 中使用 Claude 模型](./codex-claude-routing-guide-zh.md)
@@ -0,0 +1,129 @@
# Using Claude Models in Codex with CC Switch
> Applies to CC Switch 3.17.0 and later (the Anthropic Messages upstream was introduced in 3.17.0). This guide is based on the repository documentation and code, and uses a Claude-family relay gateway as the example. Screenshots are generated from the current frontend UI with de-identified sample data to avoid exposing a real API key.
## Why local routing is needed
The newer Codex CLI targets the OpenAI Responses API, while the various Claude-family relay gateways and internal enterprise gateways expose the Anthropic Messages protocol — that is, `/v1/messages`. These two protocols use completely different request bodies, streaming events, and response structures, so putting such a gateway's endpoint directly into Codex configuration can only result in a request to `/responses` coming back 404.
This feature targets the scenario where all you have is a `/v1/messages` endpoint: you have a key for some Claude-family relay gateway and want to run Claude-family models with Codex's interaction style; or your company has banned the Claude Code client for compliance reasons and kept only an approved Claude-family gateway — the model itself is available, and all that's missing is a permitted client, which Codex can now fill.
CC Switch's approach is to keep Codex always talking to the local route and still sending Responses API requests; once the route detects that the active provider is Anthropic-format, it converts the request into Anthropic Messages for the upstream, then converts the response back into the Responses shape it returns to Codex.
![Needs routing marker in the Codex provider list](../images/codex-claude-routing/01-codex-providers-require-routing.png)
The chain has four main steps:
1. When Codex is taken over, the local configuration is written as `http://127.0.0.1:15721/v1`, and `wire_api = "responses"` is forcibly kept in place.
2. The provider's `anthropic` upstream format tells the route that the real upstream speaks the Anthropic Messages protocol.
3. The route rewrites `/responses` to `/v1/messages` and converts the Responses request body into an Anthropic request body.
4. After the upstream responds, the route converts the Anthropic JSON or SSE back into the Responses JSON/SSE that Codex understands — reasoning content, tool calls, and images are all within the conversion scope.
## Prerequisites
Prepare these three things first:
- CC Switch installed and able to start (3.17.0 or later).
- Codex CLI installed and run at least once, so the `~/.codex/` directory structure exists.
- An API key that can reach an Anthropic Messages protocol endpoint (`/v1/messages`) — from some Claude-family relay gateway, or an internal enterprise Claude gateway; follow the gateway's documentation for its endpoint and auth method. Note: some providers restrict their Claude API to Claude Code only, so such a key may error out when used through Codex — if you're unsure, check with your provider first.
The Codex tab currently has no built-in Anthropic preset, so the steps below use the `Custom Configuration` path — just four or five fields from start to finish.
## Step 1: Add a Codex provider
Open CC Switch, switch to the top-level `Codex` tab, click the plus button in the upper-right corner to add a provider, keep the default `Custom Configuration`, then fill in:
- **Provider Name**: anything you like, e.g. `Claude Gateway`.
- **API Key**: your gateway key. The real key is stored only in CC Switch and injected by the local route when forwarding, so it never enters Codex's live config.
- **API Request URL**: just the gateway's service root, e.g. `https://claude-gateway.example.com`. It works with or without a trailing `/v1` — the route sends requests to `/v1/messages` automatically; don't assemble `/v1/messages` yourself (if your gateway documentation gives you a complete messages URL, you can turn on the `Full URL` toggle next to it and paste it verbatim). The yellow hint below the address bar, "compatible with OpenAI Response format", is generic copy written for the direct Responses scenario; when you choose the Anthropic format, just fill it in as this guide describes.
- **Default Model**: enter a Claude model id the gateway recognizes, e.g. `claude-sonnet-5`; follow the model names in the gateway's documentation.
Then expand `Advanced Options` and change `Upstream Format` from the default `Responses (native)` to **`Anthropic Messages (routing required)`**.
![Codex provider form for a Claude gateway](../images/codex-claude-routing/02-claude-codex-provider-form.png)
After selecting Anthropic Messages, three supporting fields appear below:
![Advanced options for the Anthropic upstream](../images/codex-claude-routing/03-anthropic-advanced-options.png)
- **Auth field**: determines which header carries the API key to the upstream; only one of the two is sent — choose per your gateway's documentation.
- `ANTHROPIC_AUTH_TOKEN (Authorization)`: sends `Authorization: Bearer <key>`. This is the default, and most Claude-family relay gateways use it.
- `ANTHROPIC_API_KEY (x-api-key)`: sends `x-api-key: <key>`. Some gateways that follow Anthropic's native header convention require this. Picking the wrong one usually shows up as 401 / 403.
- **Emulate Claude Code client**: off by default. Turn it on only when the gateway or its upstream restricts usage to "Claude Code only"; when enabled, it spoofs the User-Agent, `anthropic-beta`, and `x-app` headers and injects the Claude Code identity as the first line of the system prompt. Ordinary gateways don't need it; if you're still rejected after enabling it, see "FAQ".
- **Max output tokens**: the Anthropic protocol's `max_tokens` is required, and when a Codex request carries no output ceiling the route falls back to a conservative 8192, which may truncate long answers or deep reasoning (showing up as an incomplete reply, `stop_reason=max_tokens`). If you hit truncation, raise this to the model's real ceiling here — but don't exceed it, or the upstream will 400 outright.
The `Model Mapping` in the same area is optional: add model ids like `claude-opus-4-8`, `claude-sonnet-5`, and `claude-haiku-4-5-20251001` (use the names your upstream recognizes) one per row, and CC Switch generates a model catalog so Codex's `/model` menu can list them; you can also leave it empty, in which case Codex just requests the default model.
After you save the provider, a `Needs Routing` marker appears on the card — providers like this only work while local routing is running.
## Step 2: Enable local routing and take over Codex
Go to the `Routing` page in Settings, expand `Local Routing`, and complete two toggles:
1. Turn on the `Routing Master Switch` to start the local service (the first time you enable it, an explanatory confirmation dialog appears). The default address is `127.0.0.1:15721`.
2. Turn on `Codex` under `Routing Enabled`. If you only want Codex to use routing, you can leave Claude and Gemini off.
![Enabling Codex takeover on the local routing page](../images/codex-claude-routing/04-local-route-codex-takeover.png)
After takeover, CC Switch points Codex's live config at the local route (`base_url = http://127.0.0.1:15721/v1`), with only a placeholder in `auth.json`. The real Claude key stays in the CC Switch provider config and is injected by the local route on forward, using the auth field you selected.
## Step 3: Switch providers and restart Codex
Return to the Codex provider list and click `Enable` on the Claude provider. If routing isn't running, CC Switch shows "This provider uses Anthropic Messages API format, requires the routing service to work properly. Start routing first." — just go back to Step 2 and turn it on.
After switching, restart the current Codex terminal session: `config.toml` and the model catalog are read when the Codex process starts, and a running process isn't guaranteed to hot-load them.
Inside Codex you can verify step by step:
- If you configured model mapping, use `/model` to check whether the Claude models now appear in the menu; without a mapping, Codex just uses the default model.
- Send a small question and watch the "Current Provider" on the Settings → Routing page change from "Waiting for first request..." to your Claude provider, with "Total Requests" starting to climb.
- In the usage dashboard, these requests show their model names faithfully as `claude-*`, and you can filter by provider to reconcile token usage.
## Capabilities and known limitations
- **Prompt caching is automatic**: the conversion bridge injects standard 5-minute prompt-cache markers (system prompt, tool definitions, and conversation history) per Anthropic's convention, so long conversations don't resend everything at full price each turn — no configuration needed.
- **Reasoning and tools are lossless**: extended thinking content round-trips across the bridge intact, and multi-turn tool calls, image inputs, and PDF inputs are all fully converted.
- **Supports the `[1m]` long-context marker**: when the default model or a model id in the mapping ends with `[1m]` (e.g. `claude-sonnet-5[1m]`), the route strips the marker and automatically adds the corresponding 1M-context beta header, provided the gateway supports that capability.
- **Web search is unavailable**: in Anthropic upstream mode, Codex's built-in `web_search` is deliberately disabled — the conversion layer can't translate it for the Anthropic endpoint, and disabling it avoids presenting the model with a tool that's guaranteed to fail.
- **Truncation is reported faithfully**: when the upstream stops at the output ceiling or the stream is cut off, Codex sees "incomplete" rather than a disguised success, making it easy to notice and raise the max output tokens.
## FAQ
**The upstream returns 401 or 403**
Nine times out of ten the auth field doesn't match what the gateway wants: switch between `ANTHROPIC_AUTH_TOKEN (Authorization)` and `ANTHROPIC_API_KEY (x-api-key)` per your gateway's documentation and try again (most gateways use the default Bearer). Also confirm the key itself is valid and has balance.
**Codex reports 404 or cannot find `/responses`**
Usually Codex routing takeover isn't enabled, or you manually wrote the gateway's address directly into Codex — an Anthropic-protocol upstream has no `/responses` endpoint, so that always 404s. Check whether the current provider's `base_url` in `~/.codex/config.toml` points to `http://127.0.0.1:15721/v1`.
**The upstream returns 404 (routing already enabled)**
Check the API Request URL: it should be the gateway's service root, not an address carrying another protocol's path such as `/chat/completions`. When the gateway path is unusual, use the `Full URL` toggle to paste the complete messages endpoint directly.
**Replies often get cut off mid-way**
This is the default 8192 output ceiling showing up. Raise it in `Max output tokens` under the provider form's Advanced Options (don't exceed the model's/gateway's real ceiling), save, and retry.
**`/model` doesn't show the Claude models**
Confirm you've added entries to the model mapping, then restart Codex after saving the provider — the model catalog isn't hot-loaded by a running process. When the default model isn't in the mapping, the menu won't list it, but a direct request still works.
**Web search doesn't work**
By design; see "Capabilities and known limitations". For tasks that need web search, switch back to a Responses/Chat-format provider.
**An error says usage is restricted to Claude Code**
Some providers restrict their Claude API to the Claude Code client, so it gets rejected when going through this guide's chain via Codex. Try turning on the `Emulate Claude Code client` toggle in Advanced Options; if it still errors after that, the restriction is enforced on the provider's side — check with your provider whether your key can be used outside Claude Code. Keep this toggle off for ordinary gateways.
## Compliance note
Before using this in the "company bans the client but keeps only the gateway" scenario, it's worth confirming that doing so complies with your organization's specific policy — whether what's banned is a specific client or a manner of use differs from one place to the next. When using a third-party relay gateway, read the target gateway's terms on billing, compliance, and data retention.
## References
- [CC Switch User Manual: Proxy Service](../user-manual/en/4-proxy/4.1-service.md)
- [CC Switch User Manual: App Routing](../user-manual/en/4-proxy/4.2-routing.md)
- [CC Switch v3.17.0 Release Notes](../release-notes/v3.17.0-en.md)
- This feature comes from community contribution [#5071](https://github.com/farion1231/cc-switch/pull/5071); thanks @yeeyzy.
@@ -0,0 +1,129 @@
# CC Switch を使って Codex で Claude モデルを利用する
> 対象バージョン: CC Switch 3.17.0 以降(「Anthropic Messages 上流」は 3.17.0 から導入)。本記事はリポジトリ内のドキュメントとコードをもとに整理し、Claude 系中継ゲートウェイを例に説明します。スクリーンショットは現在のフロントエンド UI から、実際の API Key が漏れないよう匿名化したサンプルデータで生成しています。
## ローカルルーティングが必要な理由
新しい Codex CLI は OpenAI Responses API を前提にしています。一方で各種 Claude 系中継ゲートウェイや企業内部ゲートウェイが公開しているのは Anthropic Messages プロトコル、つまり `/v1/messages` です。この 2 つのプロトコルは、リクエストボディ、ストリーミングイベント、レスポンス構造がまったく異なります。この種のゲートウェイのエンドポイントをそのまま Codex 設定に入れても、`/responses` へのリクエストが 404 になるだけです。
この機能は「手元にあるのが `/v1/messages` エンドポイントだけ」という場面のためのものです。ある Claude 系中継ゲートウェイの Key を持っていて、Codex の操作感で Claude 系モデルを使いたい。あるいは会社がコンプライアンス方針で Claude Code クライアントを禁止し、承認済みの Claude 系ゲートウェイだけを残している——モデル自体は利用できるのに、許可されたクライアントがないだけです。その空白を Codex で埋められます。
CC Switch では、Codex が常にローカルルートへ接続し、Responses API のままリクエストを送るようにします。ルートは現在のプロバイダーが Anthropic 形式だと判定すると、リクエストを Anthropic Messages に変換して上流へ送り、最後にレスポンスを Responses 形式へ戻して Codex に返します。
![Codex プロバイダー一覧の「ルーティングが必要」マーク](../images/codex-claude-routing/01-codex-providers-require-routing.png)
この経路は主に 4 つのステップに分かれます:
1. Codex を引き継ぐと、ローカル設定は `http://127.0.0.1:15721/v1` に書き換えられ、`wire_api = "responses"` が強制的に維持されます。
2. プロバイダーの上流フォーマット `anthropic` が、実際の上流は Anthropic Messages プロトコルだとルートに伝えます。
3. ルートは `/responses``/v1/messages` に書き換え、Responses のリクエストボディを Anthropic のリクエストボディへ変換します。
4. 上流から返ってきた後、ルートは Anthropic の JSON または SSE を Codex が理解できる Responses JSON/SSE へ変換して返します——推論内容、ツール呼び出し、画像もすべて変換対象です。
## 事前準備
先に次の 3 つを用意してください:
- インストール済みで起動できる CC Switch(3.17.0 以降)。
- インストール済みの Codex CLI。少なくとも 1 回は実行し、`~/.codex/` のディレクトリ構造が存在していること。
- Anthropic Messages プロトコルのエンドポイント(`/v1/messages`)へアクセスできる API Key——ある Claude 系中継ゲートウェイ、または企業内部の Claude ゲートウェイのもの。エンドポイントと認証方式はゲートウェイのドキュメントに従ってください。注意:一部のプロバイダーは Claude API を Claude Code 内でのみ利用できるよう制限しており、この種の Key を Codex で使うとエラーになることがあります。判断がつかない場合は、先にプロバイダーへ問い合わせてください。
Codex タブには現時点で Anthropic の内蔵プリセットがないため、以下では「カスタム設定」の手順で進めます。入力する項目は全体でも 4〜5 個です。
## Step 1: Codex プロバイダーを追加する
CC Switch を開き、上部の `Codex` タブへ切り替え、右上のプラスボタンからプロバイダーを追加します。デフォルトの `カスタム設定` のまま、次の項目を入力します:
- **プロバイダー名**: 任意です。たとえば `Claude Gateway`
- **API Key**: あなたのゲートウェイの Key。実際の Key は CC Switch 内にのみ保存され、ローカルルートが転送時に注入するため、Codex の live 設定には入りません。
- **API エンドポイント**: ゲートウェイのルートアドレスを入力すれば十分です。たとえば `https://claude-gateway.example.com``/v1` は付けても付けなくても正しく処理され、ルートが自動的に `/v1/messages` へリクエストを送ります。自分で `/v1/messages` を組み立てないでください(ゲートウェイのドキュメントが完全な messages URL を指定している場合は、隣の `フル URL` スイッチをオンにしてそのまま貼り付けても構いません)。アドレス欄の下に表示される「OpenAI Response 互換」という黄色のヒントは Responses 直結向けの汎用文言です。Anthropic フォーマットを選ぶ場合は本記事のとおりに入力してください。
- **デフォルトモデル**: ゲートウェイが認識する Claude モデル ID を入力します。たとえば `claude-sonnet-5`。ゲートウェイのドキュメントにあるモデル名に従ってください。
続いて `高級オプション` を展開し、`上流フォーマット` をデフォルトの `Responses(ネイティブ)` から **`Anthropic Messages(ルーティング必須)`** に変更します。
![Claude ゲートウェイの Codex プロバイダーフォーム](../images/codex-claude-routing/02-claude-codex-provider-form.png)
Anthropic Messages を選ぶと、下に 3 つの関連フィールドが追加で表示されます:
![Anthropic 上流の高級オプション](../images/codex-claude-routing/03-anthropic-advanced-options.png)
- **認証フィールド**: API Key をどのヘッダーで上流へ送るかを決めます。送信されるのはどちらか一方のみで、ゲートウェイのドキュメントに従って選びます。
- `ANTHROPIC_AUTH_TOKENAuthorization`: `Authorization: Bearer <key>` を送信します。デフォルト値で、多くの Claude 系中継ゲートウェイがこの方式を使います。
- `ANTHROPIC_API_KEYx-api-key`: `x-api-key: <key>` を送信します。Anthropic ネイティブのヘッダー規約を踏襲する一部のゲートウェイはこちらを要求します。選択を誤ると、通常 401 / 403 という形で現れます。
- **Claude Code クライアントを模倣**: デフォルトはオフです。ゲートウェイ(またはその上流)が「Claude Code からのみ利用可能」と制限している場合にのみオンにします。オンにすると User-Agent・`anthropic-beta``x-app` ヘッダーを偽装し、システムプロンプトの先頭行に Claude Code のアイデンティティを注入します。通常のゲートウェイでは不要です。オンにしても拒否される場合の対処は「よくある質問」を参照してください。
- **最大出力トークン**: Anthropic プロトコルの `max_tokens` は必須項目です。Codex のリクエストが出力上限を含まない場合、ルートは保守的に 8192 で補います。長い回答や深い思考では切り詰められることがあります(回答が不完全になる、`stop_reason=max_tokens` になる、といった形で現れます)。切り詰められたら、ここでモデルの実際の上限に合わせて引き上げてください。ただし超えないように——超えると上流が直接 400 を返します。
同じエリアの `モデルマッピング` は任意です。`claude-opus-4-8``claude-sonnet-5``claude-haiku-4-5-20251001` のようなモデル ID(上流が認識する名前に従ってください)を 1 行ずつ追加すると、CC Switch がモデルカタログを生成し、Codex の `/model` メニューに一覧表示できるようになります。入力しなくても利用でき、その場合 Codex はデフォルトモデルを直接リクエストします。
プロバイダーを保存すると、カードに `ルーティングが必要` のマークが表示されます——この種のプロバイダーは、ローカルルーティングが実行中でなければ正しく動作しません。
## Step 2: ローカルルーティングを有効にして Codex をルーティングする
設定の `ルーティング` ページに入り、`ローカルルーティング` を展開して、2 つのスイッチを設定します:
1. `ルーティング総スイッチ` をオンにしてローカルサービスを起動します(初回起動時は説明の確認ダイアログが表示されます)。デフォルトアドレスは `127.0.0.1:15721` です。
2. `ルーティング有効``Codex` をオンにします。Codex だけをルーティングしたい場合は、Claude と Gemini はオフのままで構いません。
![ローカルルーティング画面で Codex のルーティングを有効化](../images/codex-claude-routing/04-local-route-codex-takeover.png)
引き継ぎ後、CC Switch は Codex の live 設定をローカルルートへ向け(`base_url = http://127.0.0.1:15721/v1`)、`auth.json` にはプレースホルダーだけが入ります。実際の Claude Key は CC Switch のプロバイダー設定内に残り、ローカルルートが転送時に、あなたが選んだ認証フィールドに従って注入します。
## Step 3: プロバイダーを切り替えて Codex を再起動する
Codex プロバイダー一覧に戻り、Claude プロバイダーの `有効化` をクリックします。ルーティングが実行されていない場合、CC Switch は「このプロバイダーは Anthropic Messages API フォーマットを使用しており、ルーティングサービスが必要です。先にルーティングを起動してください」と表示します——Step 2 に戻ってオンにすれば解決します。
切り替え後は、現在の Codex ターミナルセッションを再起動することをおすすめします。`config.toml` とモデルカタログは Codex プロセスの起動時に読み込まれるため、実行中のプロセスがホットロードするとは限りません。
Codex に入ったら、段階的に確認できます:
- モデルマッピングを設定している場合は、`/model` で Claude モデルがメニューに表示されているか確認します。マッピングを設定していない場合、Codex はデフォルトモデルを直接使います。
- 小さな質問を 1 つ送り、設定 → ルーティングページの「現在のプロバイダー」が「最初のリクエスト待ち」からあなたの Claude プロバイダーに変わり、「総リクエスト数」が増え始めるのを確認します。
- 使用量ダッシュボードでは、これらのリクエストのモデル名が `claude-*` としてそのまま表示され、プロバイダーで絞り込んで token 使用量を照合できます。
## 機能の範囲と既知の制限
- **プロンプトキャッシュが自動で有効**: 変換ブリッジは Anthropic 標準に従って 5 分のプロンプトキャッシュマーカー(システムプロンプト、ツール定義、対話履歴)を注入します。長い対話でも毎回全額で再送されることはなく、設定は不要です。
- **推論とツールを無損失で往復**: extended thinking の内容はブリッジをまたいで往復しても保持され、複数ターンのツール呼び出し、画像、PDF 入力も完全に変換されます。
- **`[1m]` 長コンテキストマーカーに対応**: デフォルトモデルやモデルマッピングのモデル ID が `[1m]` で終わる場合(例:`claude-sonnet-5[1m]`)、ルートはマーカーを取り除き、対応する 1M コンテキストの beta ヘッダーを自動で補います。ただし、ゲートウェイがその機能に対応していることが前提です。
- **Web 検索は利用不可**: Anthropic 上流モードでは Codex の内蔵 `web_search` が意図的に無効化されます——変換層が Anthropic エンドポイントへ翻訳できないためで、必ず失敗するツールをモデルに提示しないための措置です。
- **切り詰めをそのまま報告**: 上流が出力上限で止まったりストリームが切断されたりすると、Codex は偽装された成功ではなく「未完了」を受け取ります。これにより気づきやすくなり、最大出力トークンを引き上げる判断ができます。
## よくある質問
**上流が 401 または 403 を返す**
ほとんどの場合、認証フィールドがゲートウェイの要求と一致していません。`ANTHROPIC_AUTH_TOKENAuthorization``ANTHROPIC_API_KEYx-api-key` を、ゲートウェイのドキュメントに従って切り替えて再試行してください(多くのゲートウェイはデフォルトの Bearer です)。あわせて、Key 自体が有効で残高があることも確認してください。
**Codex が 404 を返す、または `/responses` が見つからない**
多くの場合、Codex のルーティング引き継ぎが有効になっていないか、ゲートウェイのエンドポイントを手動で Codex に直接書いています——Anthropic プロトコルの上流には `/responses` エンドポイントが存在しないため、必ず 404 になります。`~/.codex/config.toml` の現在の provider の `base_url``http://127.0.0.1:15721/v1` を指しているか確認してください。
**上流が 404 を返す(ルーティングは有効)**
API エンドポイントを確認してください。ゲートウェイのルートアドレスであるべきで、`/chat/completions` のような別プロトコルのパスが付いたアドレスではいけません。ゲートウェイのパスが特殊な場合は、`フル URL` スイッチを使って完全な messages エンドポイントをそのまま貼り付けてください。
**回答が途中で切り詰められることが多い**
これはデフォルトの 8192 出力上限の現れです。プロバイダーフォームの高級オプションにある `最大出力トークン` で引き上げ(モデル / ゲートウェイの実際の上限を超えないように)、保存してから再試行してください。
**`/model` に Claude モデルが表示されない**
モデルマッピングにエントリが追加されていることを確認し、プロバイダーを保存してから Codex を再起動してください——モデルカタログは実行中のプロセスにはホットロードされません。デフォルトモデルがマッピングに含まれていない場合、メニューには表示されませんが、直接リクエストは有効です。
**Web 検索が使えない**
仕様どおりです。「機能の範囲と既知の制限」を参照してください。Web 検索が必要なタスクは、Responses / Chat フォーマットのプロバイダーへ切り替えることをおすすめします。
**Claude Code でしか使えないというエラーが出る**
一部のプロバイダーは、その Claude API を Claude Code クライアント内でのみ利用できるよう制限しており、本ガイドの経路で Codex から使うと拒否されます。高級オプションの `Claude Code クライアントを模倣` スイッチをオンにして試すことはできますが、それでもエラーになる場合、制限はプロバイダーのサーバー側にあります。その Key を Claude Code 以外で使えるかどうか、プロバイダーへ問い合わせて確認してください。通常のゲートウェイでは、このスイッチはオフのままにしてください。
## コンプライアンスに関する注意
「会社がクライアントを禁止し、ゲートウェイだけを残している」という場面で使う前に、この使い方が所属組織の具体的な方針に沿っているかを確認することをおすすめします——禁止されているのが特定のクライアントなのか、それともある種の利用方法なのかは、組織によって解釈が異なります。サードパーティ中継ゲートウェイを使う場合は、対象ゲートウェイの課金・コンプライアンス・データ保持に関する規約を必ずお読みください。
## 参考リンク
- [CC Switch ユーザーマニュアル: プロキシサービス](../user-manual/ja/4-proxy/4.1-service.md)
- [CC Switch ユーザーマニュアル: アプリケーションルーティング](../user-manual/ja/4-proxy/4.2-routing.md)
- [CC Switch v3.17.0 リリースノート](../release-notes/v3.17.0-ja.md)
- この機能はコミュニティからの貢献 [#5071](https://github.com/farion1231/cc-switch/pull/5071) によるものです。@yeeyzy に感謝します。
@@ -0,0 +1,129 @@
# 通过 CC Switch 在 Codex 中使用 Claude 模型
> 适用版本:CC Switch 3.17.0 及以上(「Anthropic Messages 上游」自 3.17.0 引入)。本文根据仓库内文档与代码整理,以 Claude 系中转网关为例演示。截图来自当前前端界面,使用去敏示例数据生成,避免泄露真实 API Key。
## 为什么需要本地路由
新版 Codex CLI 面向的是 OpenAI Responses API,而各类 Claude 系中转网关、企业内部网关暴露的是 Anthropic Messages 协议,也就是 `/v1/messages`。这两种协议的请求体、流式事件和返回结构完全不同,把这类网关的接口地址直接填进 Codex 配置里,结果只能是请求 `/responses` 返回 404。
这个功能面向的就是「手里只有 `/v1/messages` 端点」的场景:你有某个 Claude 系中转网关的 Key,想用 Codex 的交互习惯跑 Claude 系列模型;或者公司出于合规策略禁用了 Claude Code 客户端、只保留了经批准的 Claude 系网关——模型本身可用,缺的只是一个被允许的客户端,现在 Codex 可以补上这个位置。
CC Switch 的做法是让 Codex 始终连本机路由,仍以 Responses API 发送请求;路由识别当前供应商是 Anthropic 格式后,把请求转换成 Anthropic Messages 发给上游,再把响应转换回 Responses 形态返回给 Codex。
![Codex 供应商列表里的需要路由标记](../images/codex-claude-routing/01-codex-providers-require-routing.png)
这条链路主要分成四步:
1. Codex 接管时,本地配置会被写成 `http://127.0.0.1:15721/v1`,并强制保持 `wire_api = "responses"`
2. 供应商的上游格式 `anthropic` 会告诉路由:真实上游说的是 Anthropic Messages 协议。
3. 路由把 `/responses` 改写到 `/v1/messages`,并把 Responses 请求体转换成 Anthropic 请求体。
4. 上游返回后,路由再把 Anthropic 的 JSON 或 SSE 转回 Codex 能理解的 Responses JSON/SSE——推理内容、工具调用、图片都在转换范围内。
## 准备工作
你需要先准备好三样东西:
- 已安装并能启动的 CC Switch3.17.0 及以上)。
- 已安装 Codex CLI,并至少运行过一次,让 `~/.codex/` 目录结构存在。
- 一个能访问 Anthropic Messages 协议端点(`/v1/messages`)的 API Key——来自某个 Claude 系中转网关,或企业内部的 Claude 网关;端点地址和认证方式以网关文档为准。注意:部分供应商会限制其 Claude API 只能在 Claude Code 中使用,这类 Key 走 Codex 可能会报错,拿不准就先咨询供应商。
Codex 页签目前没有 Anthropic 内置预设,下面走「自定义配置」路径,全程也就四五个字段。
## 第一步:添加 Codex 供应商
打开 CC Switch,切到顶部的 `Codex` 标签,点击右上角的加号添加供应商,保持默认的 `自定义配置`,然后填写:
- **供应商名称**:随意,例如 `Claude Gateway`
- **API Key**:你的网关 Key。真实 Key 只保存在 CC Switch 里,由本地路由转发时注入,不会进入 Codex 的 live 配置。
- **API 请求地址**:填网关服务根地址即可,例如 `https://claude-gateway.example.com`。带不带 `/v1` 都能被正确处理,路由会自动把请求打到 `/v1/messages`;不要自己拼 `/v1/messages`(如果网关文档给的就是完整 messages URL,打开旁边的 `完整 URL` 开关原样粘贴也可以)。地址栏下方那句「兼容 OpenAI Response 格式」的黄色提示是为 Responses 直连场景写的通用文案,选 Anthropic 格式时按本文填写即可。
- **默认模型**:填网关认识的 Claude 模型 id,例如 `claude-sonnet-5`,以网关文档给出的模型名为准。
然后展开 `高级选项`,把 `上游格式` 从默认的 `Responses(原生)` 改成 **`Anthropic Messages(需开启路由)`**。
![Claude 网关的 Codex 供应商表单](../images/codex-claude-routing/02-claude-codex-provider-form.png)
选中 Anthropic Messages 后,下方会多出三个配套字段:
![Anthropic 上游的高级选项](../images/codex-claude-routing/03-anthropic-advanced-options.png)
- **认证字段**:决定 API Key 以哪个请求头发给上游,两者只发其一,按网关文档选择。
- `ANTHROPIC_AUTH_TOKENAuthorization`:发 `Authorization: Bearer <key>`,是默认值,多数 Claude 系中转网关用这种。
- `ANTHROPIC_API_KEYx-api-key`:发 `x-api-key: <key>`,部分沿用 Anthropic 原生请求头约定的网关要求这种。选错通常表现为 401 / 403。
- **模拟 Claude Code 客户端**:默认关闭。仅当网关或其上游限制「只能通过 Claude Code 使用」时才打开,开启后会伪装 User-Agent、`anthropic-beta``x-app` 请求头,并在系统提示首行注入 Claude Code 身份。普通网关不需要开;开启后仍被拒的处理见「常见问题」。
- **最大输出 tokens**Anthropic 协议的 `max_tokens` 是必填项,而 Codex 请求未携带输出上限时,路由按保守的 8192 兜底,长回答或深度思考可能被截断(表现为回复不完整、`stop_reason=max_tokens`)。遇到截断就在这里按模型真实上限调高,但不要超过——超了上游会直接 400。
同区的 `模型映射` 是可选项:把 `claude-opus-4-8``claude-sonnet-5``claude-haiku-4-5-20251001` 这类模型 id(以你上游认识的名字为准)逐行加进去,CC Switch 会生成模型目录让 Codex 的 `/model` 菜单能列出它们;不填也能用,Codex 会直接请求默认模型。
保存供应商后,卡片上会出现 `需要路由` 标记——这类供应商必须在本地路由运行时才能正常工作。
## 第二步:开启本地路由并接管 Codex
进入设置里的 `路由` 页面,展开 `本地路由`,完成两个开关:
1. 打开 `路由总开关`,启动本地服务(首次开启会弹出一个说明确认框)。默认地址是 `127.0.0.1:15721`
2.`路由启用` 中打开 `Codex`。如果只想让 Codex 走路由,可以保持 Claude、Gemini 关闭。
![本地路由页面中启用 Codex 接管](../images/codex-claude-routing/04-local-route-codex-takeover.png)
接管后,CC Switch 会把 Codex 的 live 配置指向本机路由(`base_url = http://127.0.0.1:15721/v1`),`auth.json` 里只有占位符。真实 Claude Key 仍保存在 CC Switch 的供应商配置里,由本地路由在转发时按你选的认证字段注入。
## 第三步:切换供应商并重启 Codex
回到 Codex 供应商列表,点击 Claude 供应商的 `启用`。如果路由没有在运行,CC Switch 会提示「此供应商使用 Anthropic Messages 接口格式,需要路由服务才能正常使用,请先启动路由」——回到第二步打开即可。
切换后建议重启当前 Codex 终端会话:`config.toml` 和模型目录是 Codex 进程启动时读取的,运行中的进程不保证热加载。
进入 Codex 后可以逐级验证:
- 配置了模型映射的话,用 `/model` 查看 Claude 模型是否已出现在菜单里;没配映射时 Codex 直接用默认模型。
- 发一个小问题,观察设置 → 路由页面的「当前 Provider」从「等待首次请求」变成你的 Claude 供应商、「总请求数」开始增长。
- 用量看板里,这些请求的模型名会如实显示为 `claude-*`,可按供应商筛选核对 token 用量。
## 能力边界与已知限制
- **提示缓存自动生效**:转换桥会按 Anthropic 标准注入 5 分钟提示缓存标记(系统提示、工具定义与对话历史),长对话不会每轮全价重发,无需任何配置。
- **推理与工具无损**extended thinking 内容跨桥往返保留,多轮工具调用、图片与 PDF 输入都被完整转换。
- **支持 `[1m]` 长上下文标记**:默认模型或模型映射里的模型 id 以 `[1m]` 结尾(如 `claude-sonnet-5[1m]`)时,路由会剥掉标记并自动补发对应的 1M 上下文 beta 头,前提是网关支持该能力。
- **联网搜索不可用**Anthropic 上游模式下 Codex 的内置 `web_search` 会被主动禁用——转换层无法把它翻译给 Anthropic 端点,禁用是为了不给模型呈现一个必然失败的工具。
- **截断如实上报**:上游停在输出上限或流被掐断时,Codex 会看到「未完成」而不是被伪装的成功,方便你察觉并调高最大输出 tokens。
## 常见问题
**上游返回 401 或 403**
十有八九是认证字段与网关要求不符:在 `ANTHROPIC_AUTH_TOKENAuthorization``ANTHROPIC_API_KEYx-api-key` 之间按网关文档换一个再试(多数网关用默认的 Bearer)。另外确认 Key 本身有效、有余额。
**Codex 报 404 或找不到 `/responses`**
通常是没有开启 Codex 路由接管,或者你手动把网关的地址直接写给了 Codex——Anthropic 协议的上游没有 `/responses` 端点,这样一定 404。检查 `~/.codex/config.toml` 里当前 provider 的 `base_url` 是否指向 `http://127.0.0.1:15721/v1`
**上游返回 404(路由已开启)**
检查 API 请求地址:应该是网关的服务根地址,而不是带 `/chat/completions` 之类其它协议路径的地址。网关路径特殊时,用 `完整 URL` 开关直接粘贴完整的 messages 端点。
**回复经常中途截断**
这是默认 8192 输出上限的表现。在供应商表单高级选项的 `最大输出 tokens` 里调高(不要超过模型/网关真实上限),保存后重试。
**`/model` 看不到 Claude 模型**
确认模型映射里已添加条目,保存供应商后重启 Codex——模型目录不会被运行中的进程热加载。默认模型不在映射里时菜单不会列出它,但直接请求仍然有效。
**联网搜索用不了**
设计如此,见「能力边界」。需要联网搜索的任务建议切回 Responses/Chat 格式的供应商。
**报错提示只能在 Claude Code 中使用**
部分供应商会限制其 Claude API 只能在 Claude Code 客户端中使用,经 Codex 走本攻略的链路时会被拒绝。可以尝试打开高级选项里的 `模拟 Claude Code 客户端` 开关;若开启后仍然报错,说明限制在供应商服务端,请咨询供应商确认你的 Key 能否在 Claude Code 之外使用。普通网关请保持该开关关闭。
## 合规提示
在「公司禁客户端、只留网关」的场景下使用前,建议确认这样做符合你所在组织的具体政策——被禁的是特定客户端还是某种使用方式,各家口径不同。使用第三方中转网关时,请阅读目标网关关于计费、合规与数据留存的条款。
## 参考链接
- [CC Switch 用户手册:代理服务](../user-manual/zh/4-proxy/4.1-service.md)
- [CC Switch 用户手册:应用路由](../user-manual/zh/4-proxy/4.2-routing.md)
- [CC Switch v3.17.0 发布说明](../release-notes/v3.17.0-zh.md)
- 功能来自社区贡献 [#5071](https://github.com/farion1231/cc-switch/pull/5071),感谢 @yeeyzy
@@ -0,0 +1,101 @@
# Using DeepSeek-Style Chat APIs in Codex: CC Switch Local Routing Guide
> Applies to CC Switch 3.16.0 and nearby versions. This guide is based on the repository documentation and code, and uses DeepSeek as an example of an OpenAI Chat Completions-compatible API. Screenshots are generated from the current frontend UI with de-identified sample data to avoid exposing a real API key or account balance.
## Why local routing is needed
The newer Codex CLI targets the OpenAI Responses API, while DeepSeek, Kimi, MiniMax, SiliconFlow, and many other providers expose the OpenAI Chat Completions shape, usually `/chat/completions`. These two protocols use different request bodies, streaming events, and response structures. If you put a Chat endpoint directly into Codex configuration, common results include an incorrect model list, 404/400 requests, or streaming responses that Codex cannot parse correctly.
CC Switch solves this by making Codex always talk to a local route and continue sending Responses API requests. The route detects whether the active provider is Chat-format, rewrites the request into Chat Completions for the upstream provider, and finally converts the Chat response back into the Responses shape that Codex understands.
![Needs routing marker in the Codex provider list](../images/codex-deepseek-routing/01-codex-providers-require-routing.png)
The chain has four main steps:
1. When Codex routing is enabled, the local configuration is written as `http://127.0.0.1:15721/v1`, while `wire_api = "responses"` is kept in place.
2. The provider's `meta.apiFormat = "openai_chat"` tells the route that the real upstream is Chat Completions.
3. The route rewrites `/responses` or `/v1/responses` to `/chat/completions`, and converts the Responses request body into a Chat request body.
4. After the upstream responds, the route converts the Chat JSON or SSE stream back into Responses JSON/SSE.
## Prerequisites
Prepare these three things first:
- CC Switch installed and able to start.
- Codex CLI installed and run at least once, so the `~/.codex/config.toml` directory structure exists.
- An API key from DeepSeek or another Chat Completions provider.
DeepSeek's official documentation currently lists the OpenAI-compatible base URL as `https://api.deepseek.com` (other providers often use a base URL with a `/v1` suffix), and the Chat API path as `/chat/completions`. CC Switch's DeepSeek preset already contains these details, so prefer the preset and do not manually assemble the endpoint path.
## Step 1: Add a Codex provider
Open CC Switch, switch to the top-level `Codex` tab, and click the plus button in the upper-right corner to add a provider.
Choose the built-in `DeepSeek` preset. You only need to do two things:
- Enter your DeepSeek API key.
- Save the provider.
![Local routing mapping in the DeepSeek Codex provider form](../images/codex-deepseek-routing/02-deepseek-codex-routing-form.png)
The preset already includes DeepSeek's request base URL, default model, model menu, thinking/reasoning parameters, and automatically enables `Needs Local Routing`. You can adjust the default model or model display names if needed; the protocol conversion is handled by the routing layer.
## Step 2: Enable local routing and route Codex
Go to the `Routing` page in Settings, expand `Local Routing`, and complete two toggles:
1. Turn on the main routing switch to start the local service. The default address is `127.0.0.1:15721`.
2. Turn on `Codex` under `Routing Enabled`. If you only want Codex to use local routing, you can leave Claude and Gemini off.
![Enabling Codex routing on the local routing page](../images/codex-deepseek-routing/03-local-route-codex-takeover.png)
After routing is enabled, CC Switch points Codex's live configuration to the local route and manages authentication with a placeholder. The real DeepSeek key stays in the CC Switch provider configuration and is injected by the local route while forwarding requests, so you do not need to expose the key in Codex's live configuration.
## Step 3: Switch providers and restart Codex
Return to the Codex provider list and click `Enable` on the DeepSeek provider. If you see the `Needs Routing` marker, that provider must be used while routing is running; when the route is not started, CC Switch shows a prompt saying the routing service is required.
After switching, restart the current Codex terminal session. This is recommended because:
- The Codex process may already have read the old `config.toml`.
- After `model_catalog_json` is generated, the `/model` menu usually needs a fresh process before it refreshes.
Inside Codex, use `/model` to check whether the current model comes from the DeepSeek preset, such as `DeepSeek V4 Flash`. The Codex app currently does not support multi-model selection, so it defaults to the first configured model. Then send a small test prompt and confirm that the request count increases in the routing panel, or that a Codex request appears in usage/request logs.
## How to handle other Chat providers
DeepSeek, Kimi, MiniMax, SiliconFlow, and other common Chat-format providers already have presets in CC Switch, so use presets first. Only choose custom configuration for providers that are not covered by presets; in that case, fill in the API key, base URL, and models according to the provider's documentation, and set `API Format` to `OpenAI Chat Completions (requires routing)`.
If the upstream provider directly supports the OpenAI Responses API, you do not need to enable `Needs Local Routing`; CC Switch can connect through Responses directly without Chat conversion.
## FAQ
**Codex reports 404 or cannot find `/responses`**
Usually Codex routing is not enabled, or the upstream Chat base URL was written directly into Codex manually. Check whether `~/.codex/config.toml` points to `http://127.0.0.1:15721/v1`.
**DeepSeek upstream reports 404**
If you are using the built-in DeepSeek preset, first confirm that the active provider really comes from the preset and that Codex routing is enabled. Only custom providers require extra base URL checks: the base URL should be the service root, not the full endpoint path with `/chat/completions`.
**`/model` does not show DeepSeek models**
Restart Codex after saving the provider. CC Switch generates `cc-switch-model-catalog.json` and writes its path to `model_catalog_json`, but a running Codex process may not hot-load the model catalog.
The Codex app currently does not support multi-model selection, so it uses the first configured model by default.
**Routing is enabled, but requests still go to the wrong provider**
Confirm that all three states match: the current provider under the Codex tab is DeepSeek; the local routing service is running; and the Codex toggle is enabled under `Routing Enabled`.
**Can I use an official OpenAI Codex account through local routing?**
Not recommended. CC Switch blocks switching to official providers while local routing takeover is enabled, because accessing official APIs through a proxy may create account risk. Routing is mainly intended for third-party, aggregator, or protocol-conversion scenarios.
## References
- [CC Switch User Manual: Add Provider](../user-manual/en/2-providers/2.1-add.md)
- [CC Switch User Manual: Proxy Service](../user-manual/en/4-proxy/4.1-service.md)
- [CC Switch User Manual: App Routing](../user-manual/en/4-proxy/4.2-routing.md)
- [DeepSeek API Docs: Your First API Call](https://api-docs.deepseek.com/)
- [DeepSeek API Docs: Create Chat Completion](https://api-docs.deepseek.com/api/create-chat-completion)
- [DeepSeek API Docs: Multi-round Conversation](https://api-docs.deepseek.com/guides/multi_round_chat)
@@ -0,0 +1,101 @@
# Codex で DeepSeek などの Chat 形式 API を使う: CC Switch ローカルルーティングガイド
> 対象バージョン: CC Switch 3.16.0 およびその前後のバージョン。本記事はリポジトリ内のドキュメントとコードをもとに整理し、OpenAI Chat Completions 互換 API の例として DeepSeek を使用します。スクリーンショットは現在のフロントエンド UI から、実際の API Key やアカウント残高が漏れないよう匿名化したサンプルデータで生成しています。
## ローカルルーティングが必要な理由
新しい Codex CLI は OpenAI Responses API を前提にしています。一方で DeepSeek、Kimi、MiniMax、SiliconFlow など多くのプロバイダーが実際に公開しているのは OpenAI Chat Completions 形式、つまり `/chat/completions` です。この 2 つのプロトコルは、リクエストボディ、ストリーミングイベント、レスポンス構造が異なります。Chat エンドポイントをそのまま Codex 設定に入れると、モデル一覧が合わない、リクエストが 404/400 になる、ストリーミングレスポンスを Codex が正しく解析できない、といった問題が起きがちです。
CC Switch では、Codex が常にローカルルートへ接続し、Responses API のままリクエストを送るようにします。ルート内部で現在のプロバイダーが Chat 形式かどうかを判定し、必要ならリクエストを Chat Completions に書き換えて上流へ送り、最後に Chat レスポンスを Codex が理解できる Responses 形式へ戻します。
![Codex プロバイダー一覧のローカルルーティング必須マーク](../images/codex-deepseek-routing/01-codex-providers-require-routing.png)
この経路は主に 4 つのステップに分かれます:
1. Codex ルーティングを有効にすると、ローカル設定は `http://127.0.0.1:15721/v1` に書き換えられ、`wire_api = "responses"` は維持されます。
2. Provider の `meta.apiFormat = "openai_chat"` が、実際の上流は Chat Completions だとルートに伝えます。
3. ルートは `/responses` または `/v1/responses``/chat/completions` に書き換え、Responses のリクエストボディを Chat のリクエストボディへ変換します。
4. 上流から返ってきた後、ルートは Chat の JSON または SSE ストリームを Responses JSON/SSE へ変換して返します。
## 事前準備
先に次の 3 つを用意してください:
- インストール済みで起動できる CC Switch。
- インストール済みの Codex CLI。少なくとも 1 回は実行し、`~/.codex/config.toml` のディレクトリ構造が存在していること。
- DeepSeek または同種の Chat Completions プロバイダーの API Key。
DeepSeek 公式ドキュメントでは、OpenAI 互換 base URL は現在 `https://api.deepseek.com`(他のプロバイダーでは `/v1` 付きの base URL もよくあります)、Chat API のパスは `/chat/completions` と記載されています。CC Switch の DeepSeek プリセットにはこれらの情報がすでに入っているため、まずはプリセットを使い、エンドポイントパスを手で組み立てる必要はありません。
## Step 1: Codex プロバイダーを追加する
CC Switch を開き、上部の `Codex` タブへ切り替え、右上のプラスボタンからプロバイダーを追加します。
内蔵プリセットの `DeepSeek` を選びます。必要なのは次の 2 つだけです:
- DeepSeek API Key を入力する。
- プロバイダーを保存する。
![DeepSeek Codex プロバイダーフォームのローカルルーティング設定](../images/codex-deepseek-routing/02-deepseek-codex-routing-form.png)
プリセットには DeepSeek のリクエスト先、デフォルトモデル、モデルメニュー、thinking/reasoning パラメータがすでに含まれており、`ローカルルーティングが必要` も自動的に有効になります。必要に応じてデフォルトモデルやモデル表示名を調整できますが、プロトコル変換はルーティング層に任せれば十分です。
## Step 2: ローカルルーティングを有効にして Codex をルーティングする
設定の `ルーティング` ページに入り、`ローカルルーティング` を展開して、次の 2 つのスイッチを設定します:
1. `ルーティング総スイッチ` をオンにしてローカルサービスを起動します。デフォルトアドレスは `127.0.0.1:15721` です。
2. `ルーティング有効``Codex` をオンにします。Codex だけをルーティングしたい場合は、Claude と Gemini はオフのままで構いません。
![ローカルルーティング画面で Codex ルーティングを有効化](../images/codex-deepseek-routing/03-local-route-codex-takeover.png)
ルーティングを有効にすると、CC Switch は Codex の live 設定をローカルルートへ向け、認証はプレースホルダーで管理します。実際の DeepSeek Key は CC Switch の Provider 設定内に残り、ローカルルートが転送時に注入します。そのため、Codex の live 設定に Key を露出させる必要はありません。
## Step 3: プロバイダーを切り替えて Codex を再起動する
Codex プロバイダー一覧に戻り、DeepSeek プロバイダーの `有効化` をクリックします。`ルーティングが必要` の表示が見える場合、そのプロバイダーはルーティング実行中に使う必要があります。ルーティングが起動していない場合、CC Switch は「ルーティングサービスが必要」という趣旨のメッセージを表示します。
切り替え後は、現在の Codex ターミナルセッションを再起動することをおすすめします。理由は次のとおりです:
- Codex プロセスがすでに古い `config.toml` を読み込んでいる可能性があります。
- `model_catalog_json` の生成後、`/model` メニューの更新には通常、新しいプロセスが必要です。
Codex に入ったら、`/model` で現在のモデルが DeepSeek プリセット由来かどうかを確認します。たとえば `DeepSeek V4 Flash` などです。現在の Codex app は複数モデル選択に対応していないため、設定内の最初のモデルをデフォルトで使用します。その後、小さな質問を 1 つ送って、ルーティングパネルのリクエスト数が増えるか、usage / リクエストログに Codex リクエストが出るかを確認します。
## 他の Chat プロバイダーの場合
DeepSeek、Kimi、MiniMax、SiliconFlow など一般的な Chat 形式プロバイダーは CC Switch にプリセットがあるため、まずはプリセットを使ってください。プリセットにないプロバイダーだけ、カスタム設定を選びます。その場合は相手側のドキュメントに従って API Key、base URL、モデルを入力し、`API 形式``OpenAI Chat Completions (ルーティングが必要)` に設定します。
上流が OpenAI Responses API を直接サポートしている場合は、`ローカルルーティングが必要` を有効にする必要はありません。その場合、CC Switch は Responses のまま直結でき、Chat 変換は行いません。
## よくある質問
**Codex が 404 を返す、または `/responses` が見つからない**
多くの場合、Codex ルーティングが有効になっていないか、上流 Chat base URL を手動で Codex に直接書いています。`~/.codex/config.toml``http://127.0.0.1:15721/v1` を指しているか確認してください。
**DeepSeek 上流が 404 を返す**
内蔵 DeepSeek プリセットを使っている場合は、まず現在のプロバイダーが本当にプリセット由来であること、そして Codex ルーティングが有効であることを確認してください。カスタムプロバイダーを使っている場合だけ、base URL を追加で確認します。base URL はサービスのルートであり、`/chat/completions` 付きの完全なエンドポイントパスではありません。
**`/model` に DeepSeek モデルが表示されない**
プロバイダーを保存した後、Codex を再起動してください。CC Switch は `cc-switch-model-catalog.json` を生成し、そのパスを `model_catalog_json` に書き込みますが、実行中の Codex プロセスがモデルカタログをホットロードするとは限りません。
現在の Codex app は複数モデル選択に対応していないため、設定内の最初のモデルをデフォルトで使用します。
**ルーティングを有効にしたのに、リクエストが別のプロバイダーへ行く**
次の 3 つの状態が一致しているか確認してください:Codex タブの現在のプロバイダーが DeepSeek であること、ローカルルーティングサービスが実行中であること、`ルーティング有効` で Codex スイッチがオンであること。
**公式 OpenAI Codex アカウントをローカルルーティング経由で使えますか**
おすすめしません。CC Switch はローカルルーティング有効中、公式プロバイダーへの切り替えをブロックします。プロキシ経由で公式 API にアクセスすると、アカウントリスクが発生する可能性があるためです。ルーティングは主にサードパーティ、集約サービス、またはプロトコル変換のための機能です。
## 参考リンク
- [CC Switch ユーザーマニュアル: プロバイダーの追加](../user-manual/ja/2-providers/2.1-add.md)
- [CC Switch ユーザーマニュアル: プロキシサービス](../user-manual/ja/4-proxy/4.1-service.md)
- [CC Switch ユーザーマニュアル: アプリケーションルーティング](../user-manual/ja/4-proxy/4.2-routing.md)
- [DeepSeek API Docs: Your First API Call](https://api-docs.deepseek.com/)
- [DeepSeek API Docs: Create Chat Completion](https://api-docs.deepseek.com/api/create-chat-completion)
- [DeepSeek API Docs: Multi-round Conversation](https://api-docs.deepseek.com/guides/multi_round_chat)
@@ -0,0 +1,101 @@
# 在 Codex 中用 DeepSeek 这类 Chat 格式 APICC Switch 本地路由攻略
> 适用版本:CC Switch 3.16.0 及附近版本。本文根据仓库内文档与代码整理,并用 DeepSeek 作为 OpenAI Chat Completions 兼容接口的示例。截图来自当前前端界面,使用去敏示例数据生成,避免泄露真实 API Key 或账户余额。
## 为什么需要本地路由
新版 Codex CLI 面向的是 OpenAI Responses API,而 DeepSeek、Kimi、MiniMax、SiliconFlow 等很多供应商实际暴露的是 OpenAI Chat Completions 形态,也就是 `/chat/completions`。这两种协议的请求体、流式事件和返回结构不同,直接把 Chat 接口填进 Codex 配置里,常见结果就是模型列表不对、请求 404/400,或者流式响应无法被 Codex 正确解析。
CC Switch 的做法是让 Codex 始终连本机路由,仍以 Responses API 发送请求;路由在内部识别当前供应商是否是 Chat 格式,再把请求改写成 Chat Completions 发给上游,最后把 Chat 响应转换回 Responses 形态返回给 Codex。
![Codex 供应商列表里的需要路由标记](../images/codex-deepseek-routing/01-codex-providers-require-routing.png)
这条链路主要分成四步:
1. Codex 接管时,本地配置会被写成 `http://127.0.0.1:15721/v1`,并强制保持 `wire_api = "responses"`
2. Provider 的 `meta.apiFormat = "openai_chat"` 会告诉路由:真实上游是 Chat Completions。
3. 路由把 `/responses``/v1/responses` 改写到 `/chat/completions`,并把 Responses 请求体转换成 Chat 请求体。
4. 上游返回后,路由再把 Chat 的 JSON 或 SSE 转回 Codex 能理解的 Responses JSON/SSE。
## 准备工作
你需要先准备好三样东西:
- 已安装并能启动的 CC Switch。
- 已安装 Codex CLI,并至少运行过一次,让 `~/.codex/config.toml` 目录结构存在。
- DeepSeek 或同类 Chat Completions 供应商的 API Key。
DeepSeek 官方文档目前写明 OpenAI 兼容 base URL 是 `https://api.deepseek.com`(其他供应商常见的是带 `/v1` 后缀的 base URL),Chat API 路径是 `/chat/completions`CC Switch 的 DeepSeek 预设已经按这些信息配好,请优先使用预设,不需要手动拼接口路径。
## 第一步:添加 Codex 供应商
打开 CC Switch,切到顶部的 `Codex` 标签,点击右上角的加号添加供应商。
选择内置预设里的 `DeepSeek`,只需要做两件事:
- 填入 DeepSeek API Key。
- 保存供应商。
![DeepSeek Codex 供应商表单中的本地路由映射](../images/codex-deepseek-routing/02-deepseek-codex-routing-form.png)
预设已经内置 DeepSeek 的请求地址、默认模型、模型菜单、thinking/reasoning 参数,并会自动打开 `需要本地路由映射`。你可以按需调整默认模型或模型显示名;协议转换交给路由层完成即可。
## 第二步:开启本地路由并接管 Codex
进入设置里的 `路由` 页面,展开 `本地路由`,完成两个开关:
1. 打开 `路由总开关`,启动本地服务。默认地址是 `127.0.0.1:15721`
2.`路由启用` 中打开 `Codex`。如果只想让 Codex 走路由,可以保持 Claude、Gemini 关闭。
![本地路由页面中启用 Codex 接管](../images/codex-deepseek-routing/03-local-route-codex-takeover.png)
接管后,CC Switch 会把 Codex 的 live 配置指向本机路由,并用占位符管理认证。真实 DeepSeek Key 仍保存在 CC Switch 的 Provider 配置里,由本地路由在转发时注入,不需要你把 Key 暴露给 Codex live 配置。
## 第三步:切换供应商并重启 Codex
回到 Codex 供应商列表,点击 DeepSeek 供应商的 `启用`。如果看到 `需要路由` 标记,说明这个供应商必须在路由运行时使用;没有启动路由时,CC Switch 会弹出“需要路由服务才能正常使用”的提示。
切换后建议重启当前 Codex 终端会话。原因是:
- Codex 进程可能已经读取过旧的 `config.toml`
- `model_catalog_json` 生成后,`/model` 菜单通常需要新进程才能刷新。
进入 Codex 后,可以用 `/model` 查看当前模型是否来自 DeepSeek 预设,例如 `DeepSeek V4 Flash`。目前 Codex app 不支持多模型选择时,会默认使用配置里的第一个模型。随后发一个小问题,确认路由面板的请求数增长,或者在用量/请求日志里看到 Codex 请求即可。
## 其它 Chat 供应商怎么处理
DeepSeek、Kimi、MiniMax、SiliconFlow 等常见 Chat 格式供应商在 CC Switch 里已有预设,优先用预设即可。只有预设里没有的供应商,才需要选择自定义配置;这时按对方文档填 API Key、base URL 和模型,并把 `API 格式` 选为 `OpenAI Chat Completions (需开启路由)`
如果上游直接支持 OpenAI Responses API,就不需要打开 `需要本地路由映射`;这时 CC Switch 可以按 Responses 直连,不做 Chat 转换。
## 常见问题
**Codex 报 404 或找不到 `/responses`**
通常是没有开启 Codex 接管,或者你手动把上游 Chat base URL 直接写给了 Codex。检查 `~/.codex/config.toml` 是否指向 `http://127.0.0.1:15721/v1`
**DeepSeek 上游报 404**
如果用的是内置 DeepSeek 预设,先确认当前供应商确实来自预设,并且 Codex 路由已启用。只有在使用自定义供应商时,才需要额外检查 base URL:它应该是服务根地址,而不是带 `/chat/completions` 的完整接口路径。
**`/model` 看不到 DeepSeek 模型**
保存供应商后重启 Codex。CC Switch 会生成 `cc-switch-model-catalog.json` 并把路径写入 `model_catalog_json`,但正在运行的 Codex 进程不一定会热加载模型目录。
目前 Codex app 不支持多模型选择,默认使用配置的第一个模型。
**开了路由但请求仍走错供应商**
确认三处状态一致:Codex 标签下当前供应商是 DeepSeek;本地路由服务正在运行;`路由启用` 里 Codex 开关已打开。
**可以用官方 OpenAI Codex 账号走本地路由吗**
不建议。CC Switch 会在本地路由接管模式下阻止切到官方供应商,因为用代理访问官方 API 可能带来账号风险。路由主要用于第三方、聚合或协议转换场景。
## 参考链接
- [CC Switch 用户手册:添加供应商](../user-manual/zh/2-providers/2.1-add.md)
- [CC Switch 用户手册:代理服务](../user-manual/zh/4-proxy/4.1-service.md)
- [CC Switch 用户手册:应用路由](../user-manual/zh/4-proxy/4.2-routing.md)
- [DeepSeek API 文档:Your First API Call](https://api-docs.deepseek.com/)
- [DeepSeek API 文档:Create Chat Completion](https://api-docs.deepseek.com/api/create-chat-completion)
- [DeepSeek API 文档:Multi-round Conversation](https://api-docs.deepseek.com/guides/multi_round_chat)
@@ -0,0 +1,46 @@
# Can't See Custom Models in the Codex Desktop App? (FAQ)
> Applies to CC Switch v3.16.1 and later. This article explains "why the Codex desktop app can't see custom models" and the available mitigation; for the detailed step-by-step setup with screenshots, see [Keep Codex Remote Control and Official Plugins While Using Third-Party APIs](./codex-official-auth-preservation-guide-en.md).
## Symptom
After you switch Codex to a third-party / custom model in CC Switch (DeepSeek, Kimi, GLM, MiniMax, an aggregator, etc.):
- The model picker in the **Codex desktop app** doesn't show these custom models — often only the official default model remains, and the reasoning level falls back to the official default;
- but everything works fine in the **command-line `codex`** `/model` menu.
Many users have run into this. Here's why, and what you can do about it.
## Why this happens
This is **not a CC Switch local-config problem and not a CC Switch bug** — it is the **Codex desktop app's (the upstream closed-source client's) own model-gating behavior**.
The Codex desktop app's model picker decides which models to allow based on your **current login identity**: when it can't detect an official ChatGPT / Codex login state, it forces the picker back to the official default model and hides the custom models you configured through `config.toml` (the reasoning level falls back to the official default too). The upstream has marked "exposing custom-provider models in the desktop GUI" as not planned, so CC Switch cannot fully fix this at the desktop-GUI level.
The command-line `codex` `/model` menu and request routing both recognize the custom providers in `config.toml` correctly — **only the desktop GUI picker is constrained by this gating layer**.
## Mitigation: keep the official login
The workaround is to **keep the official login state** so the desktop app's gating allows your custom models through. The key points are below (the full step-by-step setup with screenshots is in the linked guide):
1. Log in once with an official ChatGPT / Codex account in Codex (a Free subscription is enough) to keep the official login state.
2. In CC Switch, enable `Settings -> General -> Codex App Enhancements -> Keep official login when switching third-party providers` (**off by default**).
3. Enable local routing and route Codex through it for this third-party provider (required for Chat Completions providers such as DeepSeek / Kimi / MiniMax).
4. Fully quit and restart Codex.
Once enabled, CC Switch preserves the official login state in `~/.codex/auth.json` when switching to a third-party provider and writes the third-party key into `config.toml`, so the desktop app still recognizes the official login identity, the gating lets your models through, and the custom models you configured reappear in the picker. **The preserved official token is never sent to the third party** — third-party model requests still use the key you configured, forwarded through the local route.
> 📖 Detailed step-by-step setup: [Keep Codex Remote Control and Official Plugins While Using Third-Party APIs](./codex-official-auth-preservation-guide-en.md)
## Still can't see them?
- **Confirm the toggle is on**: this toggle is off by default, and many people overwrite the official login state the first time they switch to a third-party provider, which is exactly why the models disappear — enable it as above.
- **The official login state expires**: if you haven't used the official login for several days, the picker may go empty again once the token expires — log in to the official account once more to restore it.
- **Command-line fallback diagnosis**: run `codex debug models` to list the models actually available on the CLI side and confirm the model itself is configured correctly (the CLI is unaffected by this gating).
- Individual Codex desktop versions may behave slightly differently; this is in the upstream client's domain, and no CC Switch version can fully fix it at the desktop-GUI level.
## References
- [Keep Codex Remote Control and Official Plugins While Using Third-Party APIs](./codex-official-auth-preservation-guide-en.md)
- [Codex DeepSeek local routing hands-on guide](./codex-deepseek-routing-guide-en.md)
- [Local Routing](../user-manual/en/4-proxy/4.2-routing.md)
@@ -0,0 +1,47 @@
# Codex デスクトップアプリでカスタムモデルが見えない?(よくある質問)
> 対象バージョン: CC Switch v3.16.1 以降。本記事は「なぜ Codex デスクトップアプリでカスタムモデルが見えないのか」と、使える緩和策を解説します。図入りの詳細な設定手順は [サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する](./codex-official-auth-preservation-guide-ja.md) を参照してください。
## 現象
CC Switch で Codex をサードパーティ / カスタムモデル(DeepSeek、Kimi、GLM、MiniMax、中継サービスなど)へ切り替えた後:
- **Codex デスクトップアプリ**のモデルセレクタにこれらのカスタムモデルが表示されず、多くの場合は公式の既定モデルだけが残り、思考レベルも公式の既定へ戻ってしまう。
- 一方で**コマンドライン `codex`** の `/model` ではすべて正常に表示される。
多くのユーザーがこの現象に遭遇しています。以下で原因と対処を解説します。
## なぜこうなるのか
これは **CC Switch のローカル設定の問題でも、CC Switch のバグでもありません**。**Codex デスクトップアプリ(上流のクローズドソースクライアント)自身のモデルゲーティング挙動**です。
Codex デスクトップアプリのモデルセレクタは、あなたの**現在のログイン ID** に応じてどのモデルを通すかを決めます。公式 ChatGPT / Codex のログイン状態を検出できないとき、セレクタを公式の既定モデルへ強制的に戻し、`config.toml` で設定したカスタムモデルを隠します(思考レベルもあわせて公式の既定へ戻ります)。公式は「デスクトップ GUI でカスタムプロバイダーのモデルを公開する」ことを not planned としてマークしているため、CC Switch がデスクトップ GUI のレベルでこれを根本的に修正することはできません。
コマンドライン `codex``/model` とリクエストルーティングは `config.toml` 内のカスタムプロバイダーを正常に認識できます。**デスクトップ GUI のセレクタだけがこのゲーティングの制限を受けます**。
## 緩和策: 公式ログインを保持する
対処は**公式ログイン状態を保持する**ことで、デスクトップアプリのゲーティングにあなたのカスタムモデルを通させます。要点は次のとおりです(完全な図入り手順は下のリンク先のガイドを参照してください):
1. まず Codex で公式 ChatGPT / Codex に一度ログインし(Free サブスクリプションで構いません)、公式ログイン状態を保持する。
2. CC Switch で `設定 → 一般 → Codex アプリ拡張 → サードパーティ切替時に公式ログインを保持` をオンにする(**デフォルトはオフ**)。
3. そのサードパーティプロバイダーでローカルルーティングを有効化し、Codex のルーティングをオンにする(DeepSeek / Kimi / MiniMax など Chat Completions プロトコルのプロバイダーでは必須)。
4. Codex を完全に終了して再起動する。
オンにすると、CC Switch はサードパーティプロバイダーへ切り替える際に `~/.codex/auth.json` 内の公式ログイン状態を保持し、サードパーティの Key を `config.toml` へ書き込みます。これにより、デスクトップアプリは引き続き公式ログイン ID を認識してゲーティングを通すため、設定したカスタムモデルがセレクタに再び表示されます。**保持された公式 Token がサードパーティへ送られることはありません**——サードパーティのモデルリクエストは引き続き、設定した Key でローカルルーティング経由で転送されます。
> 📖 詳細な図入り手順: [サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する](./codex-official-auth-preservation-guide-ja.md)
## それでも見えない場合は
- **スイッチがオンか確認する**: このスイッチはデフォルトでオフです。多くの人は初めてサードパーティへ切り替えたときに公式ログイン状態を上書きしてしまい、その結果見えなくなっています——上記の手順でオンにしてください。
- **公式ログイン状態は期限切れになる**: 数日間公式ログインを使わないと、Token が失効した後にセレクタが再び空になることがあります——公式に一度ログインし直せば回復します。
- **コマンドラインでの確認**: `codex debug models` を使うと CLI 側で実際に利用可能なモデルを一覧でき、モデル自体が正しく設定されていることを確認できます(CLI はこのゲーティングの影響を受けません)。
- 個々の Codex デスクトップ版で挙動が多少異なる場合があります。これは上流クライアントの範疇であり、CC Switch のどのバージョンでもデスクトップ GUI のレベルで根本解決することはできません。
## 参考リンク
- [サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する](./codex-official-auth-preservation-guide-ja.md)
- [Codex DeepSeek ローカルルーティング実践ガイド](./codex-deepseek-routing-guide-ja.md)
- [ローカルルーティング](../user-manual/ja/4-proxy/4.2-routing.md)
</content>
@@ -0,0 +1,46 @@
# Codex 桌面应用里看不到自定义模型?(常见问题)
> 适用版本:CC Switch v3.16.1 及以上。本文解释「为什么 Codex 桌面应用看不到自定义模型」以及可用的缓解办法;详细的图文配置步骤见 [使用第三方 API 时保留 Codex 远程操作和官方插件](./codex-official-auth-preservation-guide-zh.md)。
## 现象
在 CC Switch 里把 Codex 切换到第三方 / 自定义模型(DeepSeek、Kimi、GLM、MiniMax、中转站等)后:
- **Codex 桌面应用**的模型选择器里看不到这些自定义模型,往往只剩官方默认模型,思考等级也回落到官方默认;
- 但**命令行 `codex`** 的 `/model` 里一切正常。
很多用户都遇到过这个现象,下面解释原因与办法。
## 为什么会这样
这**不是 CC Switch 的本地配置问题,也不是 CC Switch 的 bug**,而是 **Codex 桌面应用(上游闭源客户端)自身的模型门控行为**
Codex 桌面应用的模型选择器会按你**当前的登录身份**来决定放行哪些模型:当它检测不到官方 ChatGPT / Codex 登录态时,会把选择器强制回落到官方默认模型,把你通过 `config.toml` 配置的自定义模型藏起来(思考等级也会一并回落到官方默认)。官方已把「在桌面 GUI 里暴露自定义供应商模型」标记为 not planned,因此 CC Switch 无法从桌面 GUI 层面彻底修复它。
命令行 `codex``/model` 与请求路由都能正常识别 `config.toml` 里的自定义供应商,**唯独桌面 GUI 的选择器受这层门控限制**。
## 怎么缓解:保留官方登录
办法是**保留官方登录态**,让桌面应用的门控放行你的自定义模型。要点如下(完整图文步骤见下方链接的攻略):
1. 先在 Codex 里登录一次官方 ChatGPT / Codex(Free 订阅即可),保留官方登录态。
2. 在 CC Switch 开启 `设置 → 通用 → Codex 应用增强 → 切换第三方时保留官方登录`**默认关闭**)。
3. 为该第三方供应商开启本地路由并接管 CodexChat Completions 协议的供应商如 DeepSeek / Kimi / MiniMax 必须开启)。
4. 完全退出并重启 Codex。
开启后,CC Switch 在切换第三方供应商时会保留 `~/.codex/auth.json` 里的官方登录态、把第三方 Key 写进 `config.toml`,于是桌面应用仍识别官方登录身份、门控放行,你配置的自定义模型就会重新出现在选择器里。**保留的官方 Token 不会被发往第三方**——第三方模型请求仍用你配置的 Key 经本地路由转发。
> 📖 详细图文步骤:[使用第三方 API 时保留 Codex 远程操作和官方插件](./codex-official-auth-preservation-guide-zh.md)
## 仍然看不到怎么办
- **确认开关已开**:该开关默认关闭,很多人第一次切到第三方就把官方登录态覆盖掉了,所以才看不到——按上面开启即可。
- **官方登录态会过期**:如果连续几天没用过官方登录,Token 失效后选择器可能又变空——重新登录一次官方即可恢复。
- **命令行兜底诊断**:用 `codex debug models` 可以列出 CLI 端实际可用的模型,确认模型本身已正确配置(CLI 不受此门控影响)。
- 个别 Codex 桌面版本的行为可能略有差异;这属于上游客户端范畴,CC Switch 各版本都无法从桌面 GUI 层根治。
## 参考链接
- [使用第三方 API 时保留 Codex 远程操作和官方插件](./codex-official-auth-preservation-guide-zh.md)
- [Codex DeepSeek 本地路由实战攻略](./codex-deepseek-routing-guide-zh.md)
- [本地路由](../user-manual/zh/4-proxy/4.2-routing.md)
+112
View File
@@ -0,0 +1,112 @@
# Using Kimi in Codex: CC Switch Local Routing Guide
> Applies to CC Switch 3.16.5 and nearby versions. This guide is based on the repository documentation and code, and uses Kimi as an example of an OpenAI Chat Completions-compatible API. Screenshots are generated from the current frontend UI with de-identified sample data to avoid exposing a real API key or account balance.
## Why local routing is needed
The newer Codex CLI targets the OpenAI Responses API, while both the Kimi Open Platform and Kimi For Coding expose the OpenAI Chat Completions shape, `/chat/completions`. These two protocols use different request bodies, streaming events, and response structures. If you put a Kimi endpoint directly into Codex configuration, the usual result is a 404 on `/responses`, or streaming responses that Codex cannot parse correctly.
The third-party tools officially supported by Kimi For Coding are Anthropic-compatible coding agents such as Claude Code and Roo Code — Codex is not on the list. To use Kimi inside Codex, you need a protocol conversion layer, and that is exactly what CC Switch Local Routing does.
CC Switch solves this by making Codex always talk to a local route and continue sending Responses API requests. The route detects whether the active provider is Chat-format, rewrites the request into Chat Completions for the upstream provider, and finally converts the Chat response back into the Responses shape that Codex understands.
![Needs routing marker in the Codex provider list](../images/codex-kimi-routing/01-codex-providers-require-routing.png)
The chain has four main steps:
1. When Codex routing is enabled, the local configuration is written as `http://127.0.0.1:15721/v1`, while `wire_api = "responses"` is kept in place.
2. The provider's `meta.apiFormat = "openai_chat"` tells the route that the real upstream is Chat Completions.
3. The route rewrites `/responses` or `/v1/responses` to `/chat/completions`, and converts the Responses request body into a Chat request body.
4. After the upstream responds, the route converts the Chat JSON or SSE stream back into Responses JSON/SSE.
## Prerequisites
Prepare these three things first:
- CC Switch installed and able to start.
- Codex CLI installed and run at least once, so the `~/.codex/config.toml` directory structure exists.
- A Kimi API key.
Kimi API keys come from two different places, matching two different built-in presets in CC Switch:
- **Kimi Open Platform** (platform.kimi.com): pay-as-you-go API keys billed by token usage, matching the `Kimi` preset. The OpenAI-compatible base URL is `https://api.moonshot.cn/v1` and the default model is `kimi-k2.7-code`.
- **Kimi For Coding** (kimi.com/code): a dedicated key generated from the Kimi Code membership benefits, matching the `Kimi For Coding` preset. The base URL is `https://api.kimi.com/coding/v1` and the unified model is `kimi-for-coding`.
Both presets already contain the correct endpoint and model details, so prefer the presets and do not manually assemble the endpoint path.
## Step 1: Add a Codex provider
Open CC Switch, switch to the top-level `Codex` tab, and click the plus button in the upper-right corner to add a provider.
Depending on which kind of key you have, choose the built-in `Kimi` preset (Open Platform, pay-as-you-go) or `Kimi For Coding` preset (membership subscription). You only need to do two things:
- Enter the matching Kimi API key.
- Save the provider.
![Upstream format in the Kimi Codex provider form](../images/codex-kimi-routing/02-kimi-codex-routing-form.png)
The preset already includes Kimi's request base URL, default model, model menu, thinking/reasoning parameters, and presets `Upstream Format` under `Advanced Options` to `Chat Completions (routing required)`. You can adjust the default model or model display names if needed — for example, the Open Platform preset defaults to `kimi-k2.7-code`, and you can switch to `kimi-k2.7-code-highspeed` following the official documentation. The protocol conversion is handled by the routing layer.
## Step 2: Enable local routing and route Codex
Go to the `Routing` page in Settings, expand `Local Routing`, and complete two toggles:
1. Turn on the main routing switch to start the local service. The default address is `127.0.0.1:15721`.
2. Turn on `Codex` under `Routing Enabled`. If you only want Codex to use local routing, you can leave Claude and Gemini off.
![Enabling Codex routing on the local routing page](../images/codex-kimi-routing/03-local-route-codex-takeover.png)
After routing is enabled, CC Switch points Codex's live configuration to the local route and manages authentication with a placeholder. The real Kimi key stays in the CC Switch provider configuration and is injected by the local route while forwarding requests, so you do not need to expose the key in Codex's live configuration.
## Step 3: Switch providers and restart Codex
Return to the Codex provider list and click `Enable` on the Kimi provider. If you see the `Needs Routing` marker, that provider must be used while routing is running; when the route is not started, CC Switch shows a prompt saying the routing service is required.
After switching, restart the current Codex terminal session. This is recommended because:
- The Codex process may already have read the old `config.toml`.
- After `model_catalog_json` is generated, the `/model` menu usually needs a fresh process before it refreshes.
Inside Codex, use `/model` to check whether the current model comes from the Kimi preset, such as `Kimi K2.7 Code` or `Kimi For Coding`. The Codex app currently does not support multi-model selection, so it defaults to the first configured model. Then send a small test prompt and confirm that the request count increases in the routing panel, or that a Codex request appears in usage/request logs.
## How to handle other Chat providers
Kimi, DeepSeek, MiniMax, SiliconFlow, and other common Chat-format providers already have presets in CC Switch, so use presets first. Only choose custom configuration for providers that are not covered by presets; in that case, fill in the API key, base URL, and models according to the provider's documentation, and set `Upstream Format` under `Advanced Options` to `Chat Completions (routing required)`.
If the upstream provider directly supports the OpenAI Responses API, set `Upstream Format` to `Responses`; CC Switch then connects through Responses directly without Chat conversion.
## FAQ
**Codex reports 404 or cannot find `/responses`**
Usually Codex routing is not enabled, or the Kimi Chat base URL was written directly into Codex manually — the Kimi upstream has no `/responses` endpoint, so that always 404s. Check whether `~/.codex/config.toml` points to `http://127.0.0.1:15721/v1`.
**Kimi upstream reports 401 or 403**
First confirm the key matches the preset: Open Platform keys only work with the `Kimi` preset, and Kimi Code membership keys only work with the `Kimi For Coding` preset. The two key families are not interchangeable.
**Kimi upstream reports 404**
If you are using a built-in Kimi preset, first confirm that the active provider really comes from the preset and that Codex routing is enabled. Only custom providers require extra base URL checks: the base URL should be the service root, not the full endpoint path with `/chat/completions`.
**`/model` does not show Kimi models**
Restart Codex after saving the provider. CC Switch generates `cc-switch-model-catalog.json` and writes its path to `model_catalog_json`, but a running Codex process may not hot-load the model catalog.
The Codex app currently does not support multi-model selection, so it uses the first configured model by default.
**Routing is enabled, but requests still go to the wrong provider**
Confirm that all three states match: the current provider under the Codex tab is Kimi; the local routing service is running; and the Codex toggle is enabled under `Routing Enabled`.
**Can I use an official OpenAI Codex account through local routing?**
Not recommended. CC Switch blocks switching to official providers while local routing takeover is enabled, because accessing official APIs through a proxy may create account risk. Routing is mainly intended for third-party, aggregator, or protocol-conversion scenarios.
## References
- [CC Switch User Manual: Add Provider](../user-manual/en/2-providers/2.1-add.md)
- [CC Switch User Manual: Proxy Service](../user-manual/en/4-proxy/4.1-service.md)
- [CC Switch User Manual: App Routing](../user-manual/en/4-proxy/4.2-routing.md)
- [Kimi Open Platform: Using Kimi K2.7 Code in coding tools](https://platform.kimi.com/docs/guide/agent-support)
- [Kimi Code Docs: Overview](https://www.kimi.com/code/docs/)
- [Kimi Code Docs: Using with third-party coding agents](https://www.kimi.com/code/docs/third-party-tools/other-coding-agents.html)
+112
View File
@@ -0,0 +1,112 @@
# Codex で Kimi を使う: CC Switch ローカルルーティングガイド
> 対象バージョン: CC Switch 3.16.5 およびその前後のバージョン。本記事はリポジトリ内のドキュメントとコードをもとに整理し、OpenAI Chat Completions 互換 API の例として Kimi を使用します。スクリーンショットは現在のフロントエンド UI から、実際の API Key やアカウント残高が漏れないよう匿名化したサンプルデータで生成しています。
## ローカルルーティングが必要な理由
新しい Codex CLI は OpenAI Responses API を前提にしています。一方で Kimi オープンプラットフォームと Kimi For Coding が実際に公開しているのは、いずれも OpenAI Chat Completions 形式、つまり `/chat/completions` です。この 2 つのプロトコルは、リクエストボディ、ストリーミングイベント、レスポンス構造が異なります。Kimi のエンドポイントをそのまま Codex 設定に入れると、`/responses` へのリクエストが 404 になる、ストリーミングレスポンスを Codex が正しく解析できない、といった問題が起きがちです。
Kimi For Coding が公式にサポートするサードパーティツールは、Claude Code や Roo Code など Anthropic 互換のコーディング Agent であり、Codex はリストに含まれていません。Codex で Kimi を使うにはプロトコル変換レイヤーが必要で、それこそが CC Switch のローカルルーティングの役割です。
CC Switch では、Codex が常にローカルルートへ接続し、Responses API のままリクエストを送るようにします。ルート内部で現在のプロバイダーが Chat 形式かどうかを判定し、必要ならリクエストを Chat Completions に書き換えて上流へ送り、最後に Chat レスポンスを Codex が理解できる Responses 形式へ戻します。
![Codex プロバイダー一覧のローカルルーティング必須マーク](../images/codex-kimi-routing/01-codex-providers-require-routing.png)
この経路は主に 4 つのステップに分かれます:
1. Codex ルーティングを有効にすると、ローカル設定は `http://127.0.0.1:15721/v1` に書き換えられ、`wire_api = "responses"` は維持されます。
2. Provider の `meta.apiFormat = "openai_chat"` が、実際の上流は Chat Completions だとルートに伝えます。
3. ルートは `/responses` または `/v1/responses``/chat/completions` に書き換え、Responses のリクエストボディを Chat のリクエストボディへ変換します。
4. 上流から返ってきた後、ルートは Chat の JSON または SSE ストリームを Responses JSON/SSE へ変換して返します。
## 事前準備
先に次の 3 つを用意してください:
- インストール済みで起動できる CC Switch。
- インストール済みの Codex CLI。少なくとも 1 回は実行し、`~/.codex/config.toml` のディレクトリ構造が存在していること。
- Kimi の API Key。
Kimi の API Key には 2 つの取得元があり、CC Switch の 2 つの内蔵プリセットに対応します:
- **Kimi オープンプラットフォーム**platform.kimi.com: トークン使用量に応じた従量課金の API Key。プリセット `Kimi` に対応し、OpenAI 互換 base URL は `https://api.moonshot.cn/v1`、デフォルトモデルは `kimi-k2.7-code` です。
- **Kimi For Coding**kimi.com/code: Kimi メンバーシップの Kimi Code 特典から生成する専用 Key。プリセット `Kimi For Coding` に対応し、base URL は `https://api.kimi.com/coding/v1`、モデルは `kimi-for-coding` に統一されています。
どちらのプリセットにも公式情報に基づくエンドポイントとモデルがすでに設定されているため、まずはプリセットを使い、エンドポイントパスを手で組み立てる必要はありません。
## Step 1: Codex プロバイダーを追加する
CC Switch を開き、上部の `Codex` タブへ切り替え、右上のプラスボタンからプロバイダーを追加します。
手元の Key の種類に応じて、内蔵プリセットの `Kimi`(オープンプラットフォーム・従量課金)または `Kimi For Coding`(メンバーシップ)を選びます。必要なのは次の 2 つだけです:
- 対応する Kimi API Key を入力する。
- プロバイダーを保存する。
![Kimi Codex プロバイダーフォームの上流フォーマット設定](../images/codex-kimi-routing/02-kimi-codex-routing-form.png)
プリセットには Kimi のリクエスト先、デフォルトモデル、モデルメニュー、thinking/reasoning パラメータがすでに含まれており、`高級オプション``上流フォーマット``Chat Completions(ルーティング必須)` にプリセットされています。必要に応じてデフォルトモデルやモデル表示名を調整できます。たとえばオープンプラットフォームのプリセットはデフォルトが `kimi-k2.7-code` で、公式ドキュメントに従って `kimi-k2.7-code-highspeed` に変更することもできます。プロトコル変換はルーティング層に任せれば十分です。
## Step 2: ローカルルーティングを有効にして Codex をルーティングする
設定の `ルーティング` ページに入り、`ローカルルーティング` を展開して、次の 2 つのスイッチを設定します:
1. `ルーティング総スイッチ` をオンにしてローカルサービスを起動します。デフォルトアドレスは `127.0.0.1:15721` です。
2. `ルーティング有効``Codex` をオンにします。Codex だけをルーティングしたい場合は、Claude と Gemini はオフのままで構いません。
![ローカルルーティング画面で Codex ルーティングを有効化](../images/codex-kimi-routing/03-local-route-codex-takeover.png)
ルーティングを有効にすると、CC Switch は Codex の live 設定をローカルルートへ向け、認証はプレースホルダーで管理します。実際の Kimi Key は CC Switch の Provider 設定内に残り、ローカルルートが転送時に注入します。そのため、Codex の live 設定に Key を露出させる必要はありません。
## Step 3: プロバイダーを切り替えて Codex を再起動する
Codex プロバイダー一覧に戻り、Kimi プロバイダーの `有効化` をクリックします。`ルーティングが必要` の表示が見える場合、そのプロバイダーはルーティング実行中に使う必要があります。ルーティングが起動していない場合、CC Switch は「ルーティングサービスが必要」という趣旨のメッセージを表示します。
切り替え後は、現在の Codex ターミナルセッションを再起動することをおすすめします。理由は次のとおりです:
- Codex プロセスがすでに古い `config.toml` を読み込んでいる可能性があります。
- `model_catalog_json` の生成後、`/model` メニューの更新には通常、新しいプロセスが必要です。
Codex に入ったら、`/model` で現在のモデルが Kimi プリセット由来かどうかを確認します。たとえば `Kimi K2.7 Code``Kimi For Coding` などです。現在の Codex app は複数モデル選択に対応していないため、設定内の最初のモデルをデフォルトで使用します。その後、小さな質問を 1 つ送って、ルーティングパネルのリクエスト数が増えるか、usage / リクエストログに Codex リクエストが出るかを確認します。
## 他の Chat プロバイダーの場合
Kimi、DeepSeek、MiniMax、SiliconFlow など一般的な Chat 形式プロバイダーは CC Switch にプリセットがあるため、まずはプリセットを使ってください。プリセットにないプロバイダーだけ、カスタム設定を選びます。その場合は相手側のドキュメントに従って API Key、base URL、モデルを入力し、`高級オプション``上流フォーマット``Chat Completions(ルーティング必須)` に設定します。
上流が OpenAI Responses API を直接サポートしている場合は、`上流フォーマット``Responses` にすれば、CC Switch は Responses のまま直結でき、Chat 変換は行いません。
## よくある質問
**Codex が 404 を返す、または `/responses` が見つからない**
多くの場合、Codex ルーティングが有効になっていないか、Kimi の Chat base URL を手動で Codex に直接書いています。Kimi の上流には `/responses` エンドポイントが存在しないため、必ず 404 になります。`~/.codex/config.toml``http://127.0.0.1:15721/v1` を指しているか確認してください。
**Kimi 上流が 401 または 403 を返す**
まず Key とプリセットの組み合わせを確認してください。オープンプラットフォームの Key はプリセット `Kimi` 専用、Kimi Code 特典の Key はプリセット `Kimi For Coding` 専用で、2 種類の Key は相互に使えません。
**Kimi 上流が 404 を返す**
内蔵 Kimi プリセットを使っている場合は、まず現在のプロバイダーが本当にプリセット由来であること、そして Codex ルーティングが有効であることを確認してください。カスタムプロバイダーを使っている場合だけ、base URL を追加で確認します。base URL はサービスのルートであり、`/chat/completions` 付きの完全なエンドポイントパスではありません。
**`/model` に Kimi モデルが表示されない**
プロバイダーを保存した後、Codex を再起動してください。CC Switch は `cc-switch-model-catalog.json` を生成し、そのパスを `model_catalog_json` に書き込みますが、実行中の Codex プロセスがモデルカタログをホットロードするとは限りません。
現在の Codex app は複数モデル選択に対応していないため、設定内の最初のモデルをデフォルトで使用します。
**ルーティングを有効にしたのに、リクエストが別のプロバイダーへ行く**
次の 3 つの状態が一致しているか確認してください:Codex タブの現在のプロバイダーが Kimi であること、ローカルルーティングサービスが実行中であること、`ルーティング有効` で Codex スイッチがオンであること。
**公式 OpenAI Codex アカウントをローカルルーティング経由で使えますか**
おすすめしません。CC Switch はローカルルーティング有効中、公式プロバイダーへの切り替えをブロックします。プロキシ経由で公式 API にアクセスすると、アカウントリスクが発生する可能性があるためです。ルーティングは主にサードパーティ、集約サービス、またはプロトコル変換のための機能です。
## 参考リンク
- [CC Switch ユーザーマニュアル: プロバイダーの追加](../user-manual/ja/2-providers/2.1-add.md)
- [CC Switch ユーザーマニュアル: プロキシサービス](../user-manual/ja/4-proxy/4.1-service.md)
- [CC Switch ユーザーマニュアル: アプリケーションルーティング](../user-manual/ja/4-proxy/4.2-routing.md)
- [Kimi オープンプラットフォーム: コーディングツールで Kimi K2.7 Code を使う](https://platform.kimi.com/docs/guide/agent-support)
- [Kimi Code ドキュメント: 概要](https://www.kimi.com/code/docs/)
- [Kimi Code ドキュメント: サードパーティ Coding Agent での利用](https://www.kimi.com/code/docs/third-party-tools/other-coding-agents.html)
+112
View File
@@ -0,0 +1,112 @@
# 在 Codex 中用 KimiCC Switch 本地路由攻略
> 适用版本:CC Switch 3.16.5 及附近版本。本文根据仓库内文档与代码整理,并用 Kimi 作为 OpenAI Chat Completions 兼容接口的示例。截图来自当前前端界面,使用去敏示例数据生成,避免泄露真实 API Key 或账户余额。
## 为什么需要本地路由
新版 Codex CLI 面向的是 OpenAI Responses API,而 Kimi 开放平台和 Kimi For Coding 实际暴露的都是 OpenAI Chat Completions 形态,也就是 `/chat/completions`。这两种协议的请求体、流式事件和返回结构不同,直接把 Kimi 的接口地址填进 Codex 配置里,常见结果就是请求 `/responses` 返回 404,或者流式响应无法被 Codex 正确解析。
Kimi For Coding 官方目前支持的第三方工具是 Claude Code、Roo Code 这类兼容 Anthropic 协议的编程 Agent,并没有覆盖 Codex。所以想在 Codex 里用 Kimi,需要一层协议转换——这正是 CC Switch 本地路由做的事。
CC Switch 的做法是让 Codex 始终连本机路由,仍以 Responses API 发送请求;路由在内部识别当前供应商是否是 Chat 格式,再把请求改写成 Chat Completions 发给上游,最后把 Chat 响应转换回 Responses 形态返回给 Codex。
![Codex 供应商列表里的需要路由标记](../images/codex-kimi-routing/01-codex-providers-require-routing.png)
这条链路主要分成四步:
1. Codex 接管时,本地配置会被写成 `http://127.0.0.1:15721/v1`,并强制保持 `wire_api = "responses"`
2. Provider 的 `meta.apiFormat = "openai_chat"` 会告诉路由:真实上游是 Chat Completions。
3. 路由把 `/responses``/v1/responses` 改写到 `/chat/completions`,并把 Responses 请求体转换成 Chat 请求体。
4. 上游返回后,路由再把 Chat 的 JSON 或 SSE 转回 Codex 能理解的 Responses JSON/SSE。
## 准备工作
你需要先准备好三样东西:
- 已安装并能启动的 CC Switch。
- 已安装 Codex CLI,并至少运行过一次,让 `~/.codex/config.toml` 目录结构存在。
- 一个 Kimi API Key。
Kimi 的 API Key 有两个来源,对应 CC Switch 里两个不同的内置预设:
- **Kimi 开放平台**platform.kimi.com):按 token 用量计费的 API Key,对应预设 `Kimi`OpenAI 兼容 base URL 是 `https://api.moonshot.cn/v1`,默认模型 `kimi-k2.7-code`
- **Kimi For Coding**kimi.com/code):Kimi 会员 Kimi Code 权益生成的专用 Key,对应预设 `Kimi For Coding`base URL 是 `https://api.kimi.com/coding/v1`,模型统一为 `kimi-for-coding`
两个预设都已经按官方信息配好接口地址和模型,请优先使用预设,不需要手动拼接口路径。
## 第一步:添加 Codex 供应商
打开 CC Switch,切到顶部的 `Codex` 标签,点击右上角的加号添加供应商。
按你手里 Key 的类型,在内置预设里选择 `Kimi`(开放平台按量计费)或 `Kimi For Coding`(会员订阅),然后只需要做两件事:
- 填入对应的 Kimi API Key。
- 保存供应商。
![Kimi Codex 供应商表单中的上游格式设置](../images/codex-kimi-routing/02-kimi-codex-routing-form.png)
预设已经内置 Kimi 的请求地址、默认模型、模型菜单、thinking/reasoning 参数,并把 `高级选项` 里的 `上游格式` 预设为 `Chat Completions(需开启路由)`。你可以按需调整默认模型或模型显示名——例如开放平台预设默认是 `kimi-k2.7-code`,也可以按官方文档换成 `kimi-k2.7-code-highspeed`;协议转换交给路由层完成即可。
## 第二步:开启本地路由并接管 Codex
进入设置里的 `路由` 页面,展开 `本地路由`,完成两个开关:
1. 打开 `路由总开关`,启动本地服务。默认地址是 `127.0.0.1:15721`
2.`路由启用` 中打开 `Codex`。如果只想让 Codex 走路由,可以保持 Claude、Gemini 关闭。
![本地路由页面中启用 Codex 接管](../images/codex-kimi-routing/03-local-route-codex-takeover.png)
接管后,CC Switch 会把 Codex 的 live 配置指向本机路由,并用占位符管理认证。真实 Kimi Key 仍保存在 CC Switch 的 Provider 配置里,由本地路由在转发时注入,不需要你把 Key 暴露给 Codex live 配置。
## 第三步:切换供应商并重启 Codex
回到 Codex 供应商列表,点击 Kimi 供应商的 `启用`。如果看到 `需要路由` 标记,说明这个供应商必须在路由运行时使用;没有启动路由时,CC Switch 会弹出“需要路由服务才能正常使用”的提示。
切换后建议重启当前 Codex 终端会话。原因是:
- Codex 进程可能已经读取过旧的 `config.toml`
- `model_catalog_json` 生成后,`/model` 菜单通常需要新进程才能刷新。
进入 Codex 后,可以用 `/model` 查看当前模型是否来自 Kimi 预设,例如 `Kimi K2.7 Code``Kimi For Coding`。目前 Codex app 不支持多模型选择时,会默认使用配置里的第一个模型。随后发一个小问题,确认路由面板的请求数增长,或者在用量/请求日志里看到 Codex 请求即可。
## 其它 Chat 供应商怎么处理
Kimi、DeepSeek、MiniMax、SiliconFlow 等常见 Chat 格式供应商在 CC Switch 里已有预设,优先用预设即可。只有预设里没有的供应商,才需要选择自定义配置;这时按对方文档填 API Key、base URL 和模型,并把 `高级选项` 里的 `上游格式` 选为 `Chat Completions(需开启路由)`
如果上游直接支持 OpenAI Responses API,把 `上游格式` 选为 `Responses` 即可;这时 CC Switch 按 Responses 直连,不做 Chat 转换。
## 常见问题
**Codex 报 404 或找不到 `/responses`**
通常是没有开启 Codex 接管,或者你手动把 Kimi 的 Chat base URL 直接写给了 Codex——Kimi 上游没有 `/responses` 端点,这样一定会 404。检查 `~/.codex/config.toml` 是否指向 `http://127.0.0.1:15721/v1`
**Kimi 上游报 401 或 403**
先确认 Key 和预设是否匹配:开放平台的 Key 只能配 `Kimi` 预设,Kimi Code 会员权益的 Key 只能配 `Kimi For Coding` 预设,两套 Key 不能混用。
**Kimi 上游报 404**
如果用的是内置 Kimi 预设,先确认当前供应商确实来自预设,并且 Codex 路由已启用。只有在使用自定义供应商时,才需要额外检查 base URL:它应该是服务根地址,而不是带 `/chat/completions` 的完整接口路径。
**`/model` 看不到 Kimi 模型**
保存供应商后重启 Codex。CC Switch 会生成 `cc-switch-model-catalog.json` 并把路径写入 `model_catalog_json`,但正在运行的 Codex 进程不一定会热加载模型目录。
目前 Codex app 不支持多模型选择,默认使用配置的第一个模型。
**开了路由但请求仍走错供应商**
确认三处状态一致:Codex 标签下当前供应商是 Kimi;本地路由服务正在运行;`路由启用` 里 Codex 开关已打开。
**可以用官方 OpenAI Codex 账号走本地路由吗**
不建议。CC Switch 会在本地路由接管模式下阻止切到官方供应商,因为用代理访问官方 API 可能带来账号风险。路由主要用于第三方、聚合或协议转换场景。
## 参考链接
- [CC Switch 用户手册:添加供应商](../user-manual/zh/2-providers/2.1-add.md)
- [CC Switch 用户手册:代理服务](../user-manual/zh/4-proxy/4.1-service.md)
- [CC Switch 用户手册:应用路由](../user-manual/zh/4-proxy/4.2-routing.md)
- [Kimi 开放平台:在编程工具中使用 Kimi K2.7 Code 模型](https://platform.kimi.com/docs/guide/agent-support)
- [Kimi Code 文档:概览](https://www.kimi.com/code/docs/)
- [Kimi Code 文档:在第三方 Coding Agent 中使用](https://www.kimi.com/code/docs/third-party-tools/other-coding-agents.html)
@@ -0,0 +1,210 @@
# Keep Codex Remote Control and Official Plugins While Using Third-Party APIs: CC Switch Setup Guide
> Applies to CC Switch v3.16.1 and later. This guide is based on the current code, user manual, and v3.16.1 release notes. Screenshots use de-identified sample data and do not include real Access Tokens or API keys.
## What this guide solves
Many Codex users want both of these at the same time:
1. Use models from DeepSeek, Kimi, GLM, MiniMax, SiliconFlow, or other third-party APIs, or use GPT models through an aggregator.
2. Keep Codex official-app capabilities such as mobile remote control and official plugins.
Previously, when switching to a third-party provider, the old behavior wrote the third-party API key into Codex `auth.json`, which could overwrite the original official ChatGPT / Codex login cache. The third-party model worked, but features that depend on the official login state disappeared.
The **Codex App Enhancements** switch added in v3.16.1 solves this conflict: the official Access Token stays in `auth.json`, while third-party provider information is written to `config.toml`. Codex App can still see an official account, but actual model requests follow the third-party provider currently selected in CC Switch.
This behavior already existed in v3.16.0 and was enabled by default. After some users reported that they did not want this behavior, v3.16.1 turned it into an explicit switch.
## Quick answer
Recommended order:
1. In the CC Switch Codex panel, switch to `OpenAI Official`.
2. Start Codex and log in once with an official ChatGPT / Codex account. A Free subscription is enough.
3. Return to CC Switch and enable `Settings -> General -> Codex App Enhancements -> Keep official login when switching third-party providers`.
4. Add or switch to a third-party Codex provider.
5. If the provider uses the Chat Completions protocol, such as DeepSeek / Kimi / MiniMax, also enable local routing and route Codex through it.
6. Restart Codex so `config.toml` and the model catalog are reloaded.
![Codex App Enhancements switch in Settings](../images/codex-official-auth-preservation/01-codex-app-enhancement-setting.png)
## Prerequisites
Prepare the following:
- CC Switch v3.16.1 or later.
- Codex installed and able to start. Installing both the app and CLI is recommended.
- An official ChatGPT / Codex account that can log in to Codex. A Free subscription is enough.
- A third-party API key, such as DeepSeek, Kimi, GLM, MiniMax, OpenRouter, SiliconFlow, or similar.
Do not manually copy or share the contents of `~/.codex/auth.json`. It stores official login cache and Access Tokens, so it is sensitive.
## Step 1: Switch back to OpenAI Official and complete official login
Open CC Switch and switch to the top-level `Codex` tab. First select the `OpenAI Official` provider, or add it from the preset providers if it is missing, and make it the current provider.
![OpenAI Official and third-party providers in the Codex provider list](../images/codex-deepseek-routing/01-codex-providers-require-routing.png)
Then start Codex, preferably the CLI, and follow the official login flow to sign in with your ChatGPT / Codex account. This account can be on the Free plan. In this setup, it mainly preserves the official identity required by Codex App, and does not pay for third-party model usage.
After login, Codex stores the official login cache in `~/.codex/auth.json`. The key point for the following steps is: do not let third-party provider switching overwrite this file again.
## Step 2: Enable Codex App Enhancements
Return to CC Switch and open:
```text
Settings -> General -> Codex App Enhancements
```
Enable:
```text
Keep official login when switching third-party providers
```
This switch is off by default because some users do not want this behavior. Enable it only when you explicitly want "third-party API + official remote control / official plugins" at the same time.
After it is enabled, backend switching for third-party Codex providers uses a config-only write path:
- `auth.json`: keeps the official ChatGPT / Codex login cache.
- `config.toml`: stores the active third-party provider's model, endpoint, `model_provider`, and provider-scoped `experimental_bearer_token`.
## Step 3: Add a third-party Codex provider
Return to the Codex panel and click the plus button in the upper-right corner to add a provider. Prefer built-in presets such as DeepSeek, Kimi, MiniMax, GLM, or SiliconFlow.
Using DeepSeek as an example, after selecting the preset, you only need to enter the API key. The preset automatically configures the base URL, default model, model mapping table, and "Needs Local Routing" flag.
![DeepSeek Codex provider form](../images/codex-deepseek-routing/02-deepseek-codex-routing-form.png)
If your third-party provider natively supports the OpenAI Responses API, such as an aggregator that offers GPT models, local routing may not be needed.
If it only supports OpenAI Chat Completions, which is common for DeepSeek / Kimi / MiniMax paths, local routing must be enabled so CC Switch can convert Codex Responses requests into Chat Completions requests.
## Step 4: Enable local routing and route Codex when needed
Open:
```text
Settings -> Routing -> Local Routing
```
Complete two actions:
1. Turn on the main routing switch to start the local service. The default address is usually `127.0.0.1:15721`.
2. Under `Routing Enabled`, turn on `Codex`.
![Enabling Codex takeover on the local routing page](../images/codex-deepseek-routing/03-local-route-codex-takeover.png)
After takeover, Codex's live `config.toml` temporarily points to the CC Switch local route. The real third-party API key remains in the CC Switch provider configuration, and is projected into the `experimental_bearer_token` in `config.toml` when providers are switched.
## Step 5: Switch to the third-party provider and restart Codex
Return to the Codex provider list and enable the third-party provider you just added. After switching, restarting Codex is recommended for two reasons:
- Codex reads `config.toml` at startup.
- The Codex `/model` menu usually needs a restart before it reloads `model_catalog_json`.
After restart, you can run a quick verification:
- In Codex App, the account information still shows the official account. This is expected.
- In CC Switch, the current Codex provider is the third-party provider.
- If local routing is enabled, request logs or routing stats show Codex requests going through the local route.
- The third-party provider dashboard or balance records show actual model requests.
## How it works
Codex mainly uses two configuration files:
```text
~/.codex/auth.json
~/.codex/config.toml
```
They have different responsibilities:
- `auth.json` stores the official ChatGPT / Codex login cache, which Codex App needs to identify the official account and enable remote control and official plugins.
- `config.toml` stores runtime configuration such as the current model provider, base URL, model, model catalog, and provider-scoped token.
After `Keep official login when switching third-party providers` is enabled, CC Switch takes the third-party provider API key from the provider configuration and writes it under the current provider in `config.toml`:
```toml
model_provider = "custom"
[model_providers.custom]
name = "DeepSeek"
base_url = "https://api.deepseek.com"
wire_api = "responses"
experimental_bearer_token = "sk-..."
```
At the same time, `auth.json` keeps the official login cache unchanged. Codex App can still identify the official account, while model requests follow the current provider and base URL in `config.toml`.
If the provider uses the Chat Completions protocol, CC Switch local routing adds another conversion layer:
```text
Codex Responses request
|
CC Switch local route
|
Third-party Chat Completions API
|
Converted back to Codex Responses response
```
This is why you can keep using official plugins / mobile remote control while moving model traffic to a third-party API.
## Side effects to understand
### Codex still shows the official account
This is the easiest part to misunderstand. After this capability is enabled, Codex App reads the official login state from `auth.json`, so it continues to display the official account.
That does not mean model requests are still going to official OpenAI. Actual traffic is determined by the current Codex provider in CC Switch, `config.toml`, and local routing logs.
### Do not use the Codex account display to judge billing
If you switch to DeepSeek, Codex can still display the official account, while model requests go to the DeepSeek API. Billing, quota, error codes, and data policy should all be understood according to the third-party provider. You can inspect specific request details in the usage panel.
### Restart Codex after changing model mappings
Codex reads the model catalog at startup. Even if CC Switch has generated a new model catalog, a running Codex process may not hot-load it, so restart Codex after editing model mappings.
### Turning the switch off returns to the old behavior
If `Keep official login when switching third-party providers` is turned off, third-party provider switching uses the compatibility behavior from older versions and may write `auth.json` again. If your goal is to keep official remote control and official plugins long term, keep this switch enabled.
## FAQ
**I switched to a third-party API. Why does Codex still show the official account?**
This is expected. Official account information comes from `auth.json`; the actual model provider comes from `config.toml` and the current provider in CC Switch.
**Is a Free subscription really enough?**
Yes. The official account is mainly used to obtain and preserve the official login state required by Codex App. Third-party model requests use the third-party API key configured in CC Switch.
**What should I do if official plugins or mobile remote control still do not work?**
Switch back to `OpenAI Official`, restart Codex, and complete official login once. Then confirm `Settings -> General -> Codex App Enhancements -> Keep official login when switching third-party providers` is enabled in CC Switch before switching back to the third-party provider.
**What if third-party requests return 404, the model list is wrong, or streaming responses are broken?**
If the provider uses Chat Completions, confirm that the provider form has `Needs Local Routing` enabled, and that `Settings -> Routing` has both the main routing switch and Codex takeover enabled.
**Can I switch back to OpenAI Official while local routing is enabled?**
Not recommended. CC Switch tries to prevent switching to official providers while local routing takeover is active, because accessing official APIs through a proxy may create account risk. Use official login only to preserve `auth.json`, and route model traffic to third-party providers.
**Why is this flow so complex? Can it be simplified?**
Because Codex App Enhancements and routing takeover can create unnecessary trouble for users who do not need them, these features are explicit switches instead of always-on behavior.
## References
- [Can't see custom models in the Codex desktop app? (FAQ)](./codex-desktop-custom-model-visibility-en.md)
- [Codex DeepSeek local routing hands-on guide](./codex-deepseek-routing-guide-en.md)
- [Add a Codex provider: Chat Completions routing and model mapping](../user-manual/en/2-providers/2.1-add.md)
- [Local Proxy Service](../user-manual/en/4-proxy/4.1-service.md)
- [Local Routing](../user-manual/en/4-proxy/4.2-routing.md)
- [CC Switch v3.16.1 Release Note](../release-notes/v3.16.1-en.md)
@@ -0,0 +1,210 @@
# サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する: CC Switch 設定ガイド
> 対象バージョン: CC Switch v3.16.1 以降。本記事は現在のコード、ユーザーマニュアル、v3.16.1 Release Note をもとに整理しています。スクリーンショットは匿名化したサンプルデータを使用しており、実際の Access Token や API Key は含まれていません。
## このガイドで解決すること
Codex を使うとき、多くのユーザーには次の 2 つの要望があります。
1. DeepSeek、Kimi、GLM、MiniMax、SiliconFlow などのサードパーティ API、または中継サービス上の GPT モデルを使いたい。
2. Codex 公式アプリのモバイルリモート操作、公式プラグインなどの機能は残したい。
以前は、サードパーティプロバイダーへ切り替えると、旧動作ではサードパーティ API Key が Codex の `auth.json` に書き込まれ、元の公式 ChatGPT / Codex ログインキャッシュを上書きする可能性がありました。これによりサードパーティモデルは使えるものの、公式ログイン状態に依存する機能が消えてしまうことがありました。
v3.16.1 で追加された **Codex アプリ拡張** スイッチは、この矛盾を解決するためのものです。公式 Access Token は `auth.json` に残し、サードパーティプロバイダー情報は `config.toml` に書き込みます。これにより Codex App は引き続き公式アカウントでログインしていると認識しつつ、実際のモデルリクエストは CC Switch で現在選択されているサードパーティプロバイダーへ流れます。
この機能自体は v3.16.0 から存在し、当時はデフォルトで有効でした。ただし一部のユーザーから不要というフィードバックがあったため、v3.16.1 で明示的なスイッチになりました。
## まず結論
おすすめの手順は次のとおりです。
1. CC Switch の Codex パネルで `OpenAI Official` に切り替える。
2. Codex を起動し、公式 ChatGPT / Codex アカウントで一度ログインする。Free サブスクリプションでも構いません。
3. CC Switch に戻り、`設定 → 一般 → Codex アプリ拡張 → サードパーティ切替時に公式ログインを保持` をオンにする。
4. サードパーティ Codex プロバイダーを追加、または切り替える。
5. そのプロバイダーが DeepSeek / Kimi / MiniMax などの Chat Completions プロトコルの場合は、ローカルルーティングも有効化し、Codex のルーティングをオンにする。
6. Codex を再起動し、`config.toml` とモデルカタログを再読み込みさせる。
![設定内の Codex アプリ拡張スイッチ](../images/codex-official-auth-preservation/01-codex-app-enhancement-setting.png)
## 事前準備
次のものを用意してください。
- CC Switch v3.16.1 以降。
- インストール済みで起動できる Codex。app と CLI の両方を入れておくことをおすすめします。
- Codex にログインできる公式 ChatGPT / Codex アカウント。Free サブスクリプションで構いません。
- DeepSeek、Kimi、GLM、MiniMax、OpenRouter、SiliconFlow などのサードパーティ API Key。
`~/.codex/auth.json` の内容を手動でコピーしたり共有したりしないでください。このファイルには公式ログインキャッシュと Access Token が保存されており、機密情報です。
## Step 1: OpenAI Official に戻して公式ログインを完了する
CC Switch を開き、上部の `Codex` タブへ切り替えます。まず `OpenAI Official` プロバイダーを選択します。存在しない場合は、プリセットプロバイダーから追加して現在のプロバイダーにしてください。
![Codex プロバイダー一覧内の OpenAI Official とサードパーティプロバイダー](../images/codex-deepseek-routing/01-codex-providers-require-routing.png)
次に Codex を起動します。CLI の起動がおすすめです。Codex の公式ログインフローに従い、ChatGPT / Codex アカウントでログインします。このアカウントは Free プランでも問題ありません。この構成では、主に Codex App が必要とする公式ログイン ID を保持する役割であり、サードパーティモデルの課金には使いません。
ログイン後、Codex は `~/.codex/auth.json` に公式ログインキャッシュを保存します。以降の重要なポイントは、サードパーティプロバイダー切り替えでこのファイルを上書きさせないことです。
## Step 2: Codex アプリ拡張を有効化する
CC Switch に戻り、次を開きます。
```text
設定 → 一般 → Codex アプリ拡張
```
次のスイッチをオンにします。
```text
サードパーティ切替時に公式ログインを保持
```
このスイッチはデフォルトでオフです。一部のユーザーはこの機能を必要としていないためです。「サードパーティ API + 公式リモート操作 / 公式プラグイン」を同時に使いたい場合だけ有効化してください。
有効化すると、バックエンドで Codex サードパーティプロバイダーを切り替えるときに config-only の書き込み経路が使われます。
- `auth.json`: 公式 ChatGPT / Codex ログインキャッシュを保持します。
- `config.toml`: 現在のサードパーティプロバイダーのモデル、endpoint、`model_provider`、provider-scoped `experimental_bearer_token` を書き込みます。
## Step 3: サードパーティ Codex プロバイダーを追加する
Codex パネルに戻り、右上のプラスボタンからプロバイダーを追加します。DeepSeek、Kimi、MiniMax、GLM、SiliconFlow などの内蔵プリセットを優先して使うのがおすすめです。
DeepSeek を例にすると、プリセットを選んだ後は API Key を入力するだけです。プリセットは base URL、デフォルトモデル、モデルマッピングテーブル、「ローカルルーティングが必要」設定を自動で構成します。
![DeepSeek Codex プロバイダーフォーム](../images/codex-deepseek-routing/02-deepseek-codex-routing-form.png)
サードパーティプロバイダーが OpenAI Responses API をネイティブにサポートしている場合、たとえば GPT モデルを提供する中継サービスであれば、ローカルルーティングは不要なことがあります。
一方で DeepSeek / Kimi / MiniMax のように OpenAI Chat Completions だけをサポートする場合は、CC Switch が Codex の Responses リクエストを Chat Completions リクエストへ変換する必要があるため、ローカルルーティングを有効化してください。
## Step 4: 必要に応じてローカルルーティングと Codex ルーティングを有効化する
次を開きます。
```text
設定 → ルーティング → ローカルルーティング
```
次の 2 つを行います。
1. `ルーティング総スイッチ` をオンにし、ローカルサービスを起動する。デフォルトアドレスは通常 `127.0.0.1:15721` です。
2. `ルーティング有効``Codex` をオンにする。
![ローカルルーティング画面で Codex ルーティングを有効化](../images/codex-deepseek-routing/03-local-route-codex-takeover.png)
ルーティング有効化後、Codex の live `config.toml` は一時的に CC Switch のローカルルートを指します。実際のサードパーティ API Key は CC Switch のプロバイダー設定内に残り、プロバイダー切り替え時に `config.toml``experimental_bearer_token` へ投影されます。
## Step 5: サードパーティプロバイダーへ切り替えて Codex を再起動する
Codex プロバイダー一覧に戻り、先ほど追加したサードパーティプロバイダーを有効化します。切り替え後は Codex の再起動をおすすめします。理由は 2 つあります。
- Codex は起動時に `config.toml` を読み込みます。
- Codex の `/model` メニューは通常、再起動後に `model_catalog_json` を再読み込みします。
再起動後、簡単に確認できます。
- Codex App ではアカウント情報が引き続き公式アカウントとして表示される。これは期待される動作です。
- CC Switch では現在の Codex プロバイダーがサードパーティプロバイダーになっている。
- ローカルルーティングを有効化している場合、リクエストログまたはルーティング統計で Codex リクエストがローカルルートを通っていることを確認できる。
- サードパーティプロバイダー側のダッシュボードや残高記録に実際のモデルリクエストが表示される。
## 仕組み
Codex の設定は主に 2 つのファイルに分かれています。
```text
~/.codex/auth.json
~/.codex/config.toml
```
この 2 つは役割が異なります。
- `auth.json` は公式 ChatGPT / Codex ログインキャッシュを保存します。Codex App が公式アカウント、リモート操作、公式プラグインを認識するために必要なログイン材料です。
- `config.toml` は現在のモデルプロバイダー、base URL、モデル、モデルカタログ、provider-scoped token などの実行時設定を保存します。
`サードパーティ切替時に公式ログインを保持` を有効化すると、CC Switch はサードパーティプロバイダー API Key をプロバイダー設定から取り出し、`config.toml` の現在の provider 配下へ書き込みます。
```toml
model_provider = "custom"
[model_providers.custom]
name = "DeepSeek"
base_url = "https://api.deepseek.com"
wire_api = "responses"
experimental_bearer_token = "sk-..."
```
同時に、`auth.json` は公式ログインキャッシュを保持したままです。そのため Codex App 側では公式アカウントを認識でき、モデルリクエストは `config.toml` の現在の provider と base URL に従ってサードパーティ API へ向かいます。
プロバイダーが Chat Completions プロトコルの場合、CC Switch のローカルルーティングがさらに変換層になります。
```text
Codex Responses リクエスト
|
CC Switch ローカルルート
|
サードパーティ Chat Completions API
|
Codex Responses レスポンスへ変換
```
これにより、公式プラグイン / モバイルリモート操作を使い続けながら、モデル通信だけをサードパーティ API に切り替えられます。
## 理解しておくべき副作用
### Codex 内の表示アカウントは公式アカウントのまま
ここが最も誤解されやすい点です。この機能を有効化すると、Codex App は `auth.json` 内の公式ログイン状態を見るため、公式アカウント情報を表示し続けます。
ただし、これはモデルリクエストが公式 OpenAI に流れているという意味ではありません。実際の通信先は、CC Switch の現在の Codex プロバイダー、`config.toml`、ローカルルーティングログで判断してください。
### Codex のアカウント表示で課金先を判断しない
DeepSeek に切り替えた場合でも、Codex には公式アカウントが表示されます。しかしモデルリクエストは DeepSeek API へ送られます。課金、上限、エラーコード、データポリシーはサードパーティプロバイダー側の仕様として理解してください。具体的なリクエスト情報は使用量パネルで確認できます。
### モデルマッピングを変更したら Codex を再起動する
Codex のモデルカタログは起動時に読み込まれます。CC Switch が新しいモデルカタログを生成していても、実行中の Codex がホットロードするとは限りません。モデルマッピングを変更した後は Codex を再起動してください。
### スイッチをオフにすると旧動作に戻る
`サードパーティ切替時に公式ログインを保持` をオフにすると、サードパーティプロバイダー切り替えは旧バージョン互換の動作になり、`auth.json` が再度書き込まれる可能性があります。公式リモート操作と公式プラグインを長期的に保持したい場合は、このスイッチをオンのままにすることをおすすめします。
## よくある質問
**サードパーティ API に切り替えたのに、なぜ Codex はまだ公式アカウントを表示しますか?**
これは期待される動作です。公式アカウント情報は `auth.json` から取得され、実際のモデルプロバイダーは `config.toml` と CC Switch の現在のプロバイダーで決まります。
**Free サブスクリプションで本当に大丈夫ですか?**
大丈夫です。ここでの公式アカウントは、Codex App が必要とする公式ログイン状態を取得・保持するために使います。サードパーティモデルリクエストは、CC Switch に設定したサードパーティ API Key を使います。
**有効化しても公式プラグインやモバイルリモート操作が使えない場合は?**
まず `OpenAI Official` に戻し、Codex を再起動して一度公式ログインを完了してください。その後、CC Switch の `設定 → 一般 → Codex アプリ拡張 → サードパーティ切替時に公式ログインを保持` がオンになっていることを確認し、再度サードパーティプロバイダーへ切り替えてください。
**サードパーティリクエストが 404 になる、モデル一覧が違う、ストリーミング応答がおかしい場合は?**
そのプロバイダーが Chat Completions プロトコルの場合、プロバイダーフォームで `ローカルルーティングが必要` が有効になっていること、さらに `設定 → ルーティング` でルーティング総スイッチと Codex ルーティングがオンになっていることを確認してください。
**ローカルルーティング中に OpenAI Official へ戻せますか?**
おすすめしません。CC Switch は、ローカルルーティングで Codex を管理している間に公式プロバイダーへ切り替えることをできるだけ防ぎます。プロキシ経由で公式 API にアクセスすると、アカウントリスクが発生する可能性があるためです。公式ログインは `auth.json` を保持するために使い、モデル通信はサードパーティプロバイダーへ切り替えるのがおすすめです。
**なぜ手順がこんなに複雑なのですか?もっと簡単にできますか?**
Codex アプリ拡張やルーティング管理は、必要ないユーザーにとっては余計なトラブルになり得るため、常時有効ではなく明示的なスイッチになっています。
## 参考リンク
- [Codex デスクトップアプリでカスタムモデルが見えない?(よくある質問)](./codex-desktop-custom-model-visibility-ja.md)
- [Codex DeepSeek ローカルルーティング実践ガイド](./codex-deepseek-routing-guide-ja.md)
- [Codex プロバイダーの追加: Chat Completions ルーティングとモデルマッピング](../user-manual/ja/2-providers/2.1-add.md)
- [ローカルプロキシサービス](../user-manual/ja/4-proxy/4.1-service.md)
- [ローカルルーティング](../user-manual/ja/4-proxy/4.2-routing.md)
- [CC Switch v3.16.1 Release Note](../release-notes/v3.16.1-ja.md)
@@ -0,0 +1,210 @@
# 使用第三方 API 时保留 Codex 远程操作和官方插件:CC Switch 配置攻略
> 适用版本:CC Switch v3.16.1 及以上。本文根据当前代码、用户手册和 v3.16.1 Release Note 整理,截图使用去敏示例数据,不包含真实 Access Token 或 API Key。
## 这篇攻略解决什么问题
很多人使用 Codex 时有两个需求:
1. 模型使用 DeepSeek、Kimi、GLM、MiniMax、硅基流动等第三方 API,或者在中转站使用 gpt 模型。
2. 保留 Codex 官方 App 的手机远程操作、官方插件等能力。
之前切换第三方供应商时,旧行为会把第三方 API Key 写进 Codex 的 `auth.json`,从而覆盖原来的官方 ChatGPT / Codex 登录缓存。这样第三方模型能用了,但依赖官方登录态的功能会消失。
v3.16.1 新增的 **Codex 应用增强**开关就是为了解决这个矛盾:让官方 Access Token 继续留在 `auth.json`,而第三方供应商信息写入 `config.toml`。这样 Codex App 仍然认为你登录的是官方账号,但实际模型请求会走 CC Switch 当前选中的第三方供应商。
v3.16.0 就有这个功能,并且默认开启,但是部分用户反映并不想要这个功能,所以在 v3.16.1 中把这个功能做成了开关。
## 先看结论
推荐顺序是:
1. 在 CC Switch 的 Codex 面板切换到 `OpenAI Official`
2. 启动 Codex,并用官方 ChatGPT / Codex 账号登录一次,Free 订阅也可以。
3. 回到 CC Switch,打开 `设置 → 通用 → Codex 应用增强 → 切换第三方时保留官方登录`
4. 添加或切换到第三方 Codex 供应商。
5. 如果该供应商是 Chat Completions 协议,例如 DeepSeek / Kimi / MiniMax,需要同时开启本地路由并启用 Codex 接管。
6. 重启 Codex,让 `config.toml` 和模型目录重新加载。
![设置里的 Codex 应用增强开关](../images/codex-official-auth-preservation/01-codex-app-enhancement-setting.png)
## 准备工作
你需要准备:
- CC Switch v3.16.1 或更新版本。
- 已安装并能启动的 Codex(建议 app 和 cli 都安装)。
- 一个可以登录 Codex 的官方 ChatGPT / Codex 账号,Free 订阅即可。
- 一个第三方 API Key,例如 DeepSeek、Kimi、GLM、MiniMax、OpenRouter、硅基流动等。
请不要手动复制或分享 `~/.codex/auth.json` 的内容。里面保存的是官方登录缓存和 Access Token,属于敏感信息。
## 第一步:先切回 OpenAI Official 并完成官方登录
打开 CC Switch,切到顶部的 `Codex` 标签页。先选择 `OpenAI Official` 供应商(如果没有的话,就在预设供应商当中添加一个),并把它设为当前供应商。
![Codex 供应商列表中的 OpenAI Official 与第三方供应商](../images/codex-deepseek-routing/01-codex-providers-require-routing.png)
接着启动 Codex(建议启动 cli),按 Codex 的官方登录流程登录你的 ChatGPT / Codex 账号。这个账号可以是 Free 订阅;在这个方案里,它主要负责保留 Codex 官方 App 需要识别的登录身份,不负责第三方模型的计费。
登录完成后,Codex 会在 `~/.codex/auth.json` 中保存官方登录缓存。后面的关键点就是:不要再让第三方供应商切换覆盖这个文件。
## 第二步:开启 Codex 应用增强
回到 CC Switch,进入:
```text
设置 → 通用 → Codex 应用增强
```
打开:
```text
切换第三方时保留官方登录
```
这个开关默认关闭,是因为部分用户并不想要这个功能。只有在你明确需要“第三方 API + 官方远程操作 / 官方插件”同时存在时,才需要开启它。
开启后,后端切换 Codex 第三方供应商时会走 config-only 写入路径:
- `auth.json`:继续保留官方 ChatGPT / Codex 登录缓存。
- `config.toml`:写入当前第三方供应商的模型、endpoint、`model_provider` 和 provider-scoped `experimental_bearer_token`
## 第三步:添加第三方 Codex 供应商
回到 Codex 面板,点击右上角的加号添加供应商。推荐优先使用内置预设,例如 DeepSeek、Kimi、MiniMax、GLM、SiliconFlow 等。
以 DeepSeek 为例,选择预设后只需要填 API Key。预设会自动配置 base URL、默认模型、模型映射表和“需要本地路由映射”。
![DeepSeek Codex 供应商表单](../images/codex-deepseek-routing/02-deepseek-codex-routing-form.png)
如果你的第三方供应商原生支持 OpenAI Responses API(比如提供 gpt 模型的中转站),可以不启用本地路由。
如果它只支持 OpenAI Chat Completions,例如常见的 DeepSeek / Kimi / MiniMax 路径,就必须启用本地路由,让 CC Switch 把 Codex 的 Responses 请求转换成 Chat Completions 请求。
## 第四步:需要时开启本地路由并接管 Codex
进入:
```text
设置 → 路由 → 本地路由
```
完成两件事:
1. 打开 `路由总开关`,启动本地服务。默认地址通常是 `127.0.0.1:15721`
2.`路由启用` 中打开 `Codex`
![本地路由页面中启用 Codex 接管](../images/codex-deepseek-routing/03-local-route-codex-takeover.png)
接管后,Codex 的 live `config.toml` 会临时指向 CC Switch 本地路由。真实第三方 API Key 仍然存储在 CC Switch 的供应商配置中,切换供应商时再投影到 `config.toml``experimental_bearer_token`
## 第五步:切换第三方供应商并重启 Codex
回到 Codex 供应商列表,启用你刚添加的第三方供应商。切换完成后建议重启 Codex,原因有两个:
- Codex 在启动时读取 `config.toml`
- Codex 的 `/model` 菜单通常需要重启后才会重新加载 `model_catalog_json`
重启后,你可以做一个简单验证:
- 在 Codex App 里,账号信息仍然显示官方账号,这是预期行为。
- 在 CC Switch 里,当前 Codex 供应商显示为第三方供应商。
- 如果开启了本地路由,请求日志或路由统计会看到 Codex 请求经过本地路由。
- 第三方供应商后台或余额记录会出现实际模型请求。
## 背后的原理
Codex 的配置主要分成两个文件:
```text
~/.codex/auth.json
~/.codex/config.toml
```
这两个文件承担的职责不同:
- `auth.json` 保存官方 ChatGPT / Codex 登录缓存,也就是 Codex App 识别官方账号、远程操作和官方插件所需的登录材料。
- `config.toml` 保存当前模型供应商、base URL、模型、模型目录和 provider-scoped token 等运行配置。
开启 `切换第三方时保留官方登录` 后,CC Switch 的切换逻辑会把第三方供应商 API Key 从供应商配置中取出,写到 `config.toml` 的当前 provider 下:
```toml
model_provider = "custom"
[model_providers.custom]
name = "DeepSeek"
base_url = "https://api.deepseek.com"
wire_api = "responses"
experimental_bearer_token = "sk-..."
```
同时,`auth.json` 保持官方登录缓存不变。于是 Codex App 侧依然能识别官方账号;而模型请求会根据 `config.toml` 的当前 provider 和 base URL 走第三方 API。
如果供应商是 Chat Completions 协议,CC Switch 本地路由会再做一层转换:
```text
Codex Responses 请求
CC Switch 本地路由
第三方 Chat Completions API
转换回 Codex Responses 响应
```
这就是为什么你既能继续使用官方插件 / 手机远程操作,又能把模型流量切到第三方 API。
## 需要理解的副作用
### Codex 里显示的账号始终是官方账号
这是最容易误解的一点。开启该能力后,Codex App 看到的是 `auth.json` 里的官方登录态,所以它会继续显示官方账号信息。
但这不代表模型请求还在走官方 OpenAI。实际流量以 CC Switch 当前 Codex 供应商、`config.toml` 和本地路由日志为准。
### 不要用 Codex 账号信息判断计费方
如果你切到 DeepSeek,Codex 里仍然显示官方账号,但模型请求会走 DeepSeek API。计费、限额、错误码和数据策略都应按第三方供应商理解。可以查看设置用量面板里的具体请求信息。
### 修改模型映射后要重启 Codex
Codex 的模型目录是启动时读取的。即使 CC Switch 已经生成了新的模型目录,正在运行的 Codex 也不一定会热加载,所以修改模型映射后请重启 Codex。
### 关闭开关会回到旧行为
如果关闭 `切换第三方时保留官方登录`,第三方供应商切换会沿用兼容旧版本的行为,可能重新写入 `auth.json`。如果你的目标是长期保留官方远程操作和官方插件,建议保持该开关开启。
## 常见问题
**我已经切到第三方 API,为什么 Codex 还显示官方账号?**
这是预期行为。官方账号信息来自 `auth.json`,模型请求的实际供应商来自 `config.toml` 和 CC Switch 当前供应商。
**Free 订阅真的可以吗?**
可以。这里的官方账号主要用于获取并保留 Codex App 需要的官方登录态。第三方模型请求使用的是你在 CC Switch 里配置的第三方 API Key。
**开启后官方插件或手机远程操作还是不可用怎么办?**
先切回 `OpenAI Official`,重新启动 Codex 并完成一次官方登录;然后确认 CC Switch 的 `设置 → 通用 → Codex 应用增强 → 切换第三方时保留官方登录` 已开启,再切回第三方供应商。
**第三方请求 404、模型列表不对或流式响应异常怎么办?**
如果该供应商是 Chat Completions 协议,请确认供应商表单里开启了 `需要本地路由映射`,并且 `设置 → 路由` 里已经启动路由总开关、启用 Codex 接管。
**可以在本地路由模式下切回 OpenAI Official 吗?**
不建议。CC Switch 会尽量阻止在本地路由接管模式下切到官方供应商,因为用代理访问官方 API 可能带来账号风险。建议官方登录只用于保留 `auth.json`,模型流量则切到第三方供应商。
**为什么流程做的这么复杂?可以简化吗?**
因为 Codex 增强开关和路由接管等一系列功能,如果用户并不需要的话,默认打开会带来不必要的麻烦,所以都做成了开关形式。
## 参考链接
- [Codex 桌面应用里看不到自定义模型?(常见问题)](./codex-desktop-custom-model-visibility-zh.md)
- [Codex DeepSeek 本地路由实战攻略](./codex-deepseek-routing-guide-zh.md)
- [添加 Codex 供应商:Chat Completions 路由与模型映射](../user-manual/zh/2-providers/2.1-add.md)
- [本地代理服务](../user-manual/zh/4-proxy/4.1-service.md)
- [本地路由](../user-manual/zh/4-proxy/4.2-routing.md)
- [CC Switch v3.16.1 Release Note](../release-notes/v3.16.1-zh.md)

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