Compare commits

..

30 Commits

Author SHA1 Message Date
Jason 6cf49ee032 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.
2026-04-16 22:31:49 +08:00
Jason 06ff5e211a 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.
2026-04-16 22:02:10 +08:00
Jason 1b0e259492 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).
2026-04-16 21:37:02 +08:00
Jason 6b2e5e07cc 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.
2026-04-16 21:36:48 +08:00
Jason 3349189864 Revert "fix(proxy/gemini): gate generic REST suffix stripping behind Google host in non-full-URL mode"
This reverts commit d19ff09cb7.
2026-04-16 21:32:04 +08:00
Jason d19ff09cb7 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.
2026-04-16 21:20:59 +08:00
Jason 6ef8d2f56a 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.
2026-04-16 21:20:51 +08:00
Jason 7a5c3725b0 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.
2026-04-16 20:50:07 +08:00
Jason 1e04f68745 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.
2026-04-16 17:50:58 +08:00
Jason b02b8f3b1b 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.
2026-04-16 17:38:07 +08:00
Jason 1f3ebe9c62 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.
2026-04-16 17:35:11 +08:00
Jason baaefcc2fc 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.
2026-04-16 17:14:22 +08:00
Jason 8b65488a89 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.
2026-04-16 16:55:11 +08:00
Jason 128d431084 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.
2026-04-16 16:22:52 +08:00
Jason 2f4a680d70 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.
2026-04-16 13:11:33 +08:00
YoVinchen 2309b49ed5 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
2026-04-16 11:31:23 +08:00
YoVinchen 8bdc4d6326 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
2026-04-16 10:57:54 +08:00
YoVinchen a186f6baca Merge branch 'main' into feat/gemini-proxy-integration 2026-04-15 17:01:21 +08:00
YoVinchen 32e3cad141 Merge branch 'main' into feat/gemini-proxy-integration
# Conflicts:
#	src-tauri/src/proxy/providers/claude.rs
#	src/i18n/locales/en.json
#	src/i18n/locales/ja.json
#	src/i18n/locales/zh.json
2026-04-15 16:58:26 +08:00
YoVinchen 9bbc8bb789 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.
2026-04-11 16:22:07 +08:00
YoVinchen d52a811016 Merge branch 'main' into feat/gemini-proxy-integration
Resolve conflict in claudeProviderPresets.ts: keep both Gemini Native
and Shengsuanyun presets.
2026-04-11 15:50:48 +08:00
YoVinchen 92668f610e Merge branch 'main' into feat/gemini-proxy-integration
# Conflicts:
#	src-tauri/src/proxy/providers/claude.rs
#	src-tauri/src/proxy/sse.rs
#	src-tauri/src/services/stream_check.rs
2026-04-10 09:08:39 +08:00
YoVinchen 44ac926210 fix(proxy): align shadow turns to tail on client history truncation 2026-04-06 23:42:47 +08:00
YoVinchen 7cf554c011 feat(proxy): update Gemini streaming and transformation logic 2026-04-06 12:23:19 +08:00
YoVinchen 8f300f4591 feat(proxy): add Gemini Native tool argument rectification 2026-04-06 11:53:06 +08:00
YoVinchen 70886d9847 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
2026-04-06 11:12:41 +08:00
YoVinchen 8603d4a373 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
2026-04-06 11:12:11 +08:00
YoVinchen 8c09d8c7d3 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
2026-04-06 11:11:30 +08:00
YoVinchen 3ce8245f2d 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).
2026-04-06 11:10:42 +08:00
YoVinchen abbf43ea6f 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.
2026-04-06 11:09:23 +08:00
161 changed files with 1683 additions and 13403 deletions
-96
View File
@@ -5,102 +5,6 @@ All notable changes to CC Switch will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [3.14.0] - 2026-04-21
Development since v3.13.0 focuses on onboarding Hermes Agent as a first-class managed app, rolling out Claude Opus 4.7 across the preset matrix, adding a Gemini Native API proxy, and sharpening session, usage, and proxy workflows.
**Stats**: 100 commits | 219 files changed | +20,548 insertions | -3,569 deletions
### Added
- **Hermes Agent Support (6th Managed App)**: Added Hermes Agent as a first-class managed app with database migration v9→v10, full Rust command surface, YAML-backed `~/.hermes/config.yaml` read/write with atomic backups, MCP sync, Skills sync, session manager with SQLite + JSONL support, and dedicated frontend panels. Supports four API protocols (`chat_completions`, `anthropic_messages`, `codex_responses`, `bedrock_converse`) aligned with Hermes Agent 0.10.0 schema. Read-only rendering for providers owned by the user-authored `providers:` dict, with deep configuration delegated to the Hermes Web UI.
- **Hermes Memory Panel**: Added a Memory panel for editing `MEMORY.md` and `USER.md` directly from CC Switch, with an enable switch, character-count limits, and a live save flow. Replaces the Prompts entry for Hermes.
- **Hermes Provider Presets**: Added ~50 Hermes provider presets spanning Nous Research, Shengsuanyun, OpenRouter, DeepSeek, Together AI, StepFun, Zhipu GLM, Bailian, Kimi, MiniMax, DouBao, BaiLing, ModelScope, KAT-Coder, PackyCode, Cubence, AIGoCode, RightCode, AICodeMirror, AICoding, CrazyRouter, SSSAiCode, Micu, CTok.ai, DDSHub, E-FlowCode, LionCCAPI, PIPELLM, Compshare, SiliconFlow, AiHubMix, DMXAPI, TheRouter, Novita, Nvidia, and Xiaomi MiMo.
- **Claude Opus 4.7 Support**: Added Claude Opus 4.7 with adaptive thinking whitelisting, per-million pricing seed, and Bedrock SKU (`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`, dropping the legacy `-v1` suffix). Migrated all aggregator and Bedrock presets to Opus 4.7 as the default Opus model.
- **Claude `max` Effort Tier**: Upgraded the Claude effort dropdown from `high` to `max` for extended reasoning capacity.
- **Gemini Native API Proxy**: Added `api_format = "gemini_native"` so the proxy can forward to Google's `generateContent` API with full streaming, schema conversion, and shadow request support. Adds `gemini_url.rs`, `gemini_schema.rs`, `gemini_shadow.rs`, `streaming_gemini.rs`, and `transform_gemini.rs` under the proxy providers module.
- **GitHub Copilot Enterprise Server**: Added GHES authentication and endpoint configuration for Copilot-backed Claude providers, plus thinking-block stripping before upstream to preserve premium interaction quota.
- **Session List Virtualization**: Virtualized the session list via `@tanstack/react-virtual` so long conversations (thousands of records) scroll smoothly; long session messages are now collapsed by default to reduce text layout cost.
- **Codex / OpenClaw Session Title Extraction**: Added meaningful title auto-extraction for Codex and OpenClaw sessions with 2-line display; strips OpenClaw `message_id` suffix noise.
- **Usage Date Range Picker**: Added a date range selector to the usage dashboard with preset tabs (Today / 1d / 7d / 14d / 30d), a custom date + time calendar picker, and a page-jump input on paginated lists.
- **Model Mapping Quick-Set**: Added a quick-set button next to model mapping fields in provider forms for faster edits.
- **Stream Check Error Classification**: Classified Stream Check errors and surfaced them as color-coded toasts; refreshed default probe models and added explicit detection for "model not found" responses.
- **Block Official Provider Switching During Local Routing**: Blocks switching to official providers while Local Routing is active, since routing official API traffic through the local proxy carries account-suspension risk. A warning toast surfaces the block.
- **Pricing Database Refresh (v8 → v9)**: Added ~50 new model pricing entries and corrected stale prices via a reseed-on-migration step, including Claude 4.7, Opus 4.7 Adaptive Thinking, Grok 4, Qwen 3.5/3.6, MiniMax M2.5/M2.7, Doubao Seed 2.0 series, and GLM-5/5.1. DeepSeek and Kimi K2.5 prices updated.
- **Application-Level Window Controls**: Added an opt-in setting to render CC Switch's own minimize / toggle-maximize / close buttons instead of the system decorations, materially improving the experience on Linux Wayland where compositor-drawn buttons can become inert.
- **Hermes in Unified Skills Management**: Added Hermes to the unified Skills surface; skill install, enable, and filter now cover the Hermes app alongside Claude / Codex / Gemini / OpenCode / OpenClaw.
- **OpenClaw Config Directory Override**: Added a settings option to point CC Switch at a custom `openclaw.json` location.
- **Hermes Config Directory Override**: Added a settings option to point CC Switch at a custom `~/.hermes/config.yaml` location, backed by data-driven dispatch.
- **StepFun Step Plan Preset**: Added StepFun Step Plan (EN/ZH) provider presets.
- **New API Usage Script Template**: Added a User-Agent header to the New API usage script template for better upstream compatibility.
- **Launch Hermes Dashboard from Toolbar**: When the Hermes Web UI probe fails, the toolbar entry now offers to run `hermes dashboard` in the user's preferred terminal via a temp bash/batch script. `hermes dashboard` opens the browser itself once ready, so no polling is required. 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`.
- **LemonData Provider Preset (All Six Apps)**: Registered LemonData as a third-party partner preset across Claude, Codex, Gemini, OpenCode, OpenClaw, and Hermes, with icon assets and zh/en/ja partner-promotion copy. Claude uses `ANTHROPIC_API_KEY` auth; OpenAI-compatible apps target `gpt-5.4`.
- **DDSHub Codex Preset**: Added a Codex-compatible endpoint for DDSHub at the same host as its Claude service; base URL omits the `/v1` suffix because the gateway auto-routes OpenAI SDK paths.
### Changed
- **"Local Proxy Takeover" → "Local Routing"**: Unified terminology across UI copy, README, and docs in all three locales. Functional behavior is unchanged.
- **Hermes `Auto` api_mode Removed**: Users must now pick an explicit protocol; new deeplinks default to `chat_completions`. Eliminates URL-based heuristic surprises.
- **Hermes Provider Form**: Added an API mode dropdown and per-provider model editor; bound per-provider models to the top-level `model:` when switching active providers.
- **Hermes Deep Config Delegation**: Deep YAML knobs are now delegated to the Hermes Web UI via a direct launch action, rather than duplicated in the CC Switch form.
- **`ANTHROPIC_REASONING_MODEL` Removed from Claude Quick-Set**: Decoupled the reasoning capability from model selection; the legacy field is no longer surfaced in the quick-set form.
- **Per-Provider Proxy Config Removed**: Consolidated into global Local Routing; the provider-level proxy toggle and associated storage are gone.
- **Unified Toolbar Icon Button Width**: Normalized icon-button widths across Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes panels for a consistent header look.
- **Rust Toolchain Pinned to 1.95**: Adopted clippy 1.95 suggestions across the workspace and pinned the toolchain to prevent nightly drift.
- **Tray Menu ID Constant**: The tray identifier moved from the hardcoded string `"main"` to a `TRAY_ID` constant (`"cc-switch"`) across all call sites.
- **Copilot Request Classification**: Refined request routing inside the Copilot optimizer to further reduce unnecessary premium interaction consumption.
- **Usage Script Intranet Support**: Removed private-IP / suspicious-hostname blocking from usage scripts, unblocking enterprise intranet, Docker, and self-hosted API endpoints. Built-in templates still enforce HTTPS (except localhost) and same-origin checks; custom templates remain user-controlled with those request-URL checks skipped.
- **Failover Queue Notes**: Provider notes now appear in failover queue selectors and queue rows for easier identification across multi-provider queues.
- **Hermes Toolbar Layout**: Swapped the Hermes Web UI button from `ExternalLink` to `LayoutDashboard` (clicking may spawn `hermes dashboard` rather than just opening a URL), and moved MCP to the final toolbar slot so Hermes matches the Claude / Codex / Gemini / OpenCode layout.
### Fixed
- **Header Auto-Compact Latching After Maximize**: The toolbar no longer stays compacted after maximize/restore; compaction now reevaluates on size changes.
- **Hermes YAML Pollution & OAuth MCP Auth Drop**: Round-tripping through CC Switch no longer drops OAuth MCP `auth` blocks or pollutes unrelated YAML keys; guard tests added via `tests/hermes_roundtrip.rs`.
- **Hermes Active Provider Display**: Hermes UI now correctly surfaces the active provider and wires add / enable / remove actions.
- **Hermes Provider Persistence**: Providers persist under `custom_providers:` so `api_mode` and `model` survive restarts and config reloads.
- **Codex `cache_control` Preservation**: Preserve `cache_control` when merging system prompts during Codex format conversion (#1946).
- **Claude Prompt Cache Key Leak**: Stopped sending prompt cache keys during Claude chat conversions (#2003).
- **Proxy Hop-by-Hop Header Stripping**: Strip hop-by-hop response headers (Connection, Keep-Alive, Transfer-Encoding, etc.) per RFC 7230.
- **Permissive Proxy CORS Removed**: Removed the permissive CORS layer from the proxy (#1915).
- **Copilot Premium Consumption**: Further reduced unnecessary Copilot premium interaction consumption during pass-through traffic.
- **Backend Error Details in Proxy Toast**: Surface backend error payload details in proxy-related toast messages instead of a generic failure string.
- **Usage Log Deduplication**: Deduplicated proxy and session-log usage records so the same request is no longer double-counted; synced the request log time range with the dashboard's 1d / 7d / 30d selector.
- **Common Config Checkbox Persistence**: Checkbox state for Claude / Codex / Gemini common-config toggles now persists correctly across reopens.
- **Claude Plugin `settings.json` Sync**: Editing the current provider now syncs back to `settings.json` for the Claude plugin path.
- **Google Official Gemini Env Preservation**: Saving the Google Official Gemini provider no longer clobbers the `env` block.
- **OpenCode JSON5 Parser for Trailing Commas**: OpenCode config reads now tolerate trailing commas via a JSON5 parser.
- **Preset Refreshes**: Refreshed stale context windows for DeepSeek and Claude 1M; refreshed stale model IDs; backfilled Hermes model lists; fixed the Nous endpoint and replaced the Hermes placeholder icon with Nous brand artwork; pruned unused official Hermes presets.
- **Auto-Expand Collapsed Messages on Search Hit**: Collapsed messages now auto-expand when a search match lands inside hidden content.
- **Unknown Subscription Quota Tiers Hidden**: Provider cards no longer render unknown subscription quota tiers.
- **Weekly Limit Label Unified**: Aligned the weekly_limit tier label with the official 7-day naming across locales.
- **Root-Level Skill Repo Install**: Fixed skill installation when the repository root itself is a skill.
- **Session ID Parsing Clippy**: Removed a redundant closure in session ID parsing (clippy warning).
- **Usage Log Stat Dedup**: Deduplicated proxy-sourced and session-log-sourced usage records for accurate totals.
- **Stream Check Default Models Refresh**: Updated stream-check default probe models to match each vendor's current lineup.
- **Skills Import Sync**: Imported Skills are now immediately synced into enabled app directories instead of only being recorded in the database, so the UI no longer shows "installed" while the target app directory is missing the skill.
- **Ghostty Session Restore**: Fixed Ghostty session restore launch by using shell execution with `--working-directory`, avoiding `cwd` escaping issues when the path contains spaces or special characters.
- **Hermes Health Check Borrowing OpenClaw Schema**: Hermes providers were routed through `check_additive_app_stream` (the OpenClaw dispatcher), which reads camelCase `baseUrl` / `apiKey` / `api` and surfaced "OpenClaw provider is missing baseUrl" even when every Hermes field was filled. Introduced `check_hermes_stream` with Hermes-specific extractors that map `api_mode` (`chat_completions` / `anthropic_messages` / `codex_responses`) to the matching `check_claude_stream` `api_format`, and returns `bedrock_converse` as unsupported. `api_mode` is now resolved before URL / API key extraction, so `bedrock_converse` users see the real cause rather than a misleading "missing base_url".
- **Usage Query Modal for Hermes & OpenClaw**: `getProviderCredentials` now reads 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 refactored the BALANCE and TOKEN_PLAN test paths to reuse the precomputed `providerCredentials` instead of re-reading `env.ANTHROPIC_*` directly, fixing the "empty key" error for non-Claude apps even when the key was configured.
### Docs
- **README Sponsor Updates**: Updated SiliconFlow signup bonus to ¥16, trimmed the SSSAiCode sponsor blurb, updated partner logos, and added LemonData as a new sponsor.
- **Global Proxy Hint Clarified**: Clarified the global proxy hint about local routing across all three locales.
- **Takeover → Routing Rename**: Renamed takeover docs to routing and updated anchors across all languages.
- **PIPELLM Website URL**: Updated the PIPELLM sponsor website URL to `code.pipellm.ai`.
### Breaking
- **Hermes requires explicit `api_mode`**: The `Auto` mode is gone; imported or deeplinked providers default to `chat_completions`. Users with prior `Auto` configs will be prompted to pick a protocol.
- **`ANTHROPIC_REASONING_MODEL` removed from Claude quick-set**: The legacy field is no longer exposed; existing settings are cleaned up automatically.
- **Per-provider proxy configuration removed**: Migrate to the global Local Routing setting. Existing per-provider proxy values are ignored.
- **Database schema bumped v9 → v10**: Adds `enabled_hermes` columns to `mcp_servers` and `skills` (auto-migrated with `DEFAULT 0`; no data loss).
- **Pricing table reseeded (v8 → v9)**: The `model_pricing` table is cleared and reseeded on first launch to pick up new models and corrected prices.
- **XCodeAPI preset removed**: Users of the XCodeAPI preset should switch to another provider.
---
## [3.13.0] - 2026-04-10
Development since v3.12.3 focuses on quota visibility, provider workflow upgrades, stronger proxy compatibility, and lower-overhead tray / session workflows.
+2 -2
View File
@@ -48,7 +48,7 @@ MiniMax-M2.7 is a next-generation large language model designed for autonomous e
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/drGuwc9k">this link</a> and complete real-name verification to receive ¥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>
<td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/drGuwc9k">this link</a> and complete real-name verification to receive ¥20 in bonus credit, usable across models on the platform. SiliconFlow is also now compatible with OpenClaw, allowing users to connect a SiliconFlow API key and call major AI models for free.</td>
</tr>
<tr>
@@ -89,7 +89,7 @@ Claude Code / Codex / Gemini official channels at 38% / 2% / 9% of original pric
<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>
<td>Thanks to SSSAiCode for sponsoring this project! SSSAiCode is a stable and reliable API relay service, dedicated to providing stable, reliable, and affordable Claude and Codex model services, <strong>offering high cost-effective official Claude service at just ¥0.5/$ equivalent</strong>, supporting monthly and pay-as-you-go billing plans with same-day fast invoicing. SSSAiCode offers a special deal for CC Switch users: register via <a href="https://www.sssaicode.com/register?ref=DCP0SM">this link</a> to enjoy $10 extra credit on every top-up!</td>
</tr>
<tr>
+3 -2
View File
@@ -48,7 +48,7 @@ MiniMax-M2.7 は、自律的進化と実世界の生産性向上のために設
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/drGuwc9k">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥16 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td>
<td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/drGuwc9k">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥20 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td>
</tr>
<tr>
@@ -91,7 +91,7 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
<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>
<td>SSSAiCode のご支援に感謝します!SSSAiCode は安定性と信頼性に優れた API 中継サービスで、安定的で信頼性が高く、手頃な価格の Claude・Codex モデルサービスを提供しています。<strong>高コストパフォーマンスの公式 Claude サービスを 0.5¥/$ 換算で提供</strong>、月額制・Paygo など多様な課金方式に対応し、当日の迅速な請求書発行をサポート。CC Switch ユーザー向けの特別特典:<a href="https://www.sssaicode.com/register?ref=DCP0SM">こちらのリンク</a>から登録すると、毎回のチャージで $10 の追加ボーナスを受けられます!</td>
</tr>
<tr>
@@ -103,6 +103,7 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
<td>LemonData のご支援に感謝します!LemonData は高性能 AI API アグリゲーションプラットフォームで、GPT、Claude、Gemini、DeepSeek など 300 以上のモデルに 1 つの API キーでアクセス可能。全モデルが公式価格の 30〜70% オフで自動フェイルオーバー、スマートルーティング、無制限同時接続に対応。新規ユーザーは登録だけで即座に $1 の無料クレジットを獲得 — <a href="https://lemondata.cc/r/FFX1ZDUP">こちらのリンク</a>から登録してボーナスを獲得し、すぐに開発を始めましょう!</td>
</tr>
<tr>
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
<td>CTok.ai のご支援に感謝します!CTok.ai はワンストップ AI プログラミングツールサービスプラットフォームの構築に取り組んでいます。Claude Code のプロフェッショナルプランと技術コミュニティサービスを提供し、Google Gemini や OpenAI Codex にも対応しています。丁寧に設計されたプランと専門的な技術コミュニティを通じて、開発者に安定したサービス保証と継続的な技術サポートを提供し、AI アシストプログラミングを真の生産性ツールにします。<a href="https://ctok.ai">こちら</a>から登録してください!</td>
+3 -2
View File
@@ -48,7 +48,7 @@ MiniMax M2.7 是 MiniMax 首个深度参与自我迭代的模型,可自主构
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_zh.jpg" alt="SiliconFlow" width="150"></a></td>
<td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/drGuwc9k">此链接</a>注册并完成实名认证,即可获得 ¥16 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td>
<td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/drGuwc9k">此链接</a>注册并完成实名认证,即可获得 ¥20 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td>
</tr>
<tr>
@@ -90,7 +90,7 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
<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>
<td>感谢 SSSAiCode 赞助了本项目!SSSAiCode 是一家稳定可靠的API中转站,致力于提供稳定、可靠、平价的Claude、CodeX模型服务,<strong>提供高性价比折合0.5¥/$的官方Claude服务</strong>,支持包月、Paygo多种计费方式、支持当日快速开票,SSSAiCode为本软件的用户提供特别优惠,使用<a href="https://www.sssaicode.com/register?ref=DCP0SM">此链接</a>注册每次充值均可享受10$的额外奖励!</td>
</tr>
<tr>
@@ -102,6 +102,7 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
<td>感谢 LemonData 赞助了本项目!LemonData 是一个高性能 AI API 聚合平台——一个 API Key 即可访问 GPT、Claude、Gemini、DeepSeek 等 300+ 模型。所有模型定价为官方价格的 30%-70%,支持自动故障转移、智能路由和无限并发。新用户注册即获 $1 免费额度——通过<a href="https://lemondata.cc/r/FFX1ZDUP">此链接</a>注册即可领取奖励,立即开始开发!</td>
</tr>
<tr>
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
<td>感谢 CTok.ai 赞助了本项目!CTok.ai 致力于打造一站式 AI 编程工具服务平台。我们提供 Claude Code 专业套餐及技术社群服务,同时支持 Google Gemini 和 OpenAI Codex。通过精心设计的套餐方案和专业的技术社群,为开发者提供稳定的服务保障和持续的技术支持,让 AI 辅助编程真正成为开发者的生产力工具。点击<a href="https://ctok.ai">这里</a>注册!</td>
-469
View File
@@ -1,469 +0,0 @@
# CC Switch v3.14.0
> Hermes Agent becomes the 6th managed app, Claude Opus 4.7 rolls out across the preset matrix, Gemini Native API proxy, "Local Routing" rename, and application-level window controls
**[中文版 →](v3.14.0-zh.md) | [日本語版 →](v3.14.0-ja.md)**
---
## Overview
CC Switch v3.14.0 is a major release centered on onboarding **Hermes Agent as the 6th first-class managed app** and rolling out **Claude Opus 4.7** across the full aggregator and Bedrock preset matrix. Hermes support covers a database v9 → v10 migration, a complete Rust command surface, YAML-backed `~/.hermes/config.yaml` read/write with atomic backups, MCP sync, Skills sync, SQLite + JSONL session management, and dedicated frontend panels including a Memory editor. All four API protocols aligned with Hermes Agent 0.10.0 (`chat_completions`, `anthropic_messages`, `codex_responses`, `bedrock_converse`) are selectable. Providers owned by the user-authored `providers:` dict are rendered as read-only cards, and deep YAML configuration is delegated directly to the Hermes Web UI.
Beyond Hermes, this release adds a **Gemini Native API proxy** (`api_format = "gemini_native"`) so the proxy can forward directly to Google's `generateContent` endpoint with full streaming, schema conversion, and shadow request support; renames the legacy "Local Proxy Takeover" to **Local Routing** across UI copy, README, and docs in all three locales; introduces **application-level window controls**, an opt-in setting that materially improves the experience on Linux Wayland where compositor-drawn buttons can become inert; and bundles late additions for launching `hermes dashboard` from the toolbar, a LemonData preset across all six apps, a DDSHub Codex endpoint, plus several Hermes health-check and Usage modal fixes.
On the session side, the message list is **virtualized** via `@tanstack/react-virtual` so conversations with thousands of records scroll smoothly and long messages collapse by default; the Usage dashboard adds a **date range picker** (Today / 1d / 7d / 14d / 30d + custom date-time calendar) and a page-jump input; **Stream Check error classification** now surfaces color-coded toasts with refreshed default probe models and an explicit "model not found" branch; and switching to official providers is **blocked while Local Routing is active** to avoid account-suspension risk. The pricing database is reseeded from v8 → v9 with ~50 new model entries (Claude 4.7, Opus 4.7 Adaptive Thinking, Grok 4, Qwen 3.5/3.6, MiniMax M2.5/M2.7, Doubao Seed 2.0 series, GLM-5/5.1 and others) and corrected stale prices.
**Release Date**: 2026-04-21
**Update Scale**: 100 commits | 219 files changed | +20,548 / -3,569 lines
---
## Highlights
- **Hermes Agent Support (6th Managed App)**: Database v9 → v10 migration, full Rust command surface, YAML read/write with atomic backups, MCP sync, Skills sync, SQLite + JSONL session management, dedicated frontend panels, and four API protocols (`chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`)
- **Claude Opus 4.7 Rollout**: Adaptive thinking whitelisting, per-million pricing seed, Bedrock SKU (`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`, dropping the legacy `-v1` suffix); all aggregator and Bedrock presets migrated to Opus 4.7 as the default Opus model
- **Claude `max` Effort Tier**: Effort dropdown upgraded from `high` to `max`
- **Gemini Native API Proxy**: New `api_format = "gemini_native"` forwards directly to Google's `generateContent` with full streaming / schema conversion / shadow request support
- **GitHub Copilot Enterprise Server**: GHES authentication and endpoint configuration for Copilot-backed Claude providers
- **Copilot Premium Consumption Deep Optimization**: Proactive thinking-block stripping before forwarding, `tool_result` classification fix, subagent detection, `x-interaction-id` billing merge, orphan `tool_result` sanitization, and default warmup downgrade — a systematic reduction in premium interaction consumption
- **Session List Virtualization**: Long conversations scroll smoothly and long messages collapse by default to reduce text layout cost
- **Codex / OpenClaw Session Title Extraction**: Meaningful title extraction with 2-line display; strips OpenClaw `message_id` suffix noise
- **Usage Date Range Picker**: Today / 1d / 7d / 14d / 30d preset tabs + custom date-time calendar; page-jump input on paginated lists
- **Stream Check Error Classification**: Color-coded error toasts; refreshed default probe models; explicit "model not found" detection
- **Block Official Provider Switching During Local Routing**: Routing official API traffic through the local proxy carries account-suspension risk — switches are blocked with a warning toast
- **Pricing Database Refresh (v8 → v9)**: ~50 new model entries and corrected stale prices
- **Application-Level Window Controls**: Opt-in setting to render CC Switch's own min/max/close buttons, materially improving Linux Wayland experience
- **Hermes in Unified Skills Management**: Skill install, enable, and filter now cover Hermes
- **Hermes / OpenClaw Config Directory Override**: Point CC Switch at a custom `~/.hermes/config.yaml` or `openclaw.json` location
- **Launch Hermes Dashboard from Toolbar**: When the Hermes Web UI probe fails, the toolbar entry offers to run `hermes dashboard` in the user's preferred terminal
- **New Partner Presets**: LemonData across all six apps; DDSHub Codex endpoint; StepFun Step Plan
---
## Added
### Hermes Agent Support (6th Managed App)
CC Switch now treats Hermes Agent as a first-class managed app alongside Claude / Codex / Gemini / OpenCode / OpenClaw.
- **Database Migration v9 → v10**: Adds `enabled_hermes` columns to `mcp_servers` and `skills` tables (`DEFAULT 0`, auto-migrated, no data loss)
- **YAML Configuration Read/Write**: `~/.hermes/config.yaml` read/write with atomic backups; `tests/hermes_roundtrip.rs` guards against dropped OAuth MCP `auth` blocks or pollution of unrelated YAML keys
- **Four API Protocols**: Aligned with Hermes Agent 0.10.0 — `chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`; new deeplinks default to `chat_completions`
- **User `providers:` Dict Read-Only Rendering**: User-authored providers in the YAML appear as read-only cards in CC Switch; deep configuration delegates to the Hermes Web UI
- **Additive Switching**: Unlike Claude / Codex's "override" style, all Hermes providers coexist in the same YAML
### Hermes Memory Panel
- New Memory panel for editing `MEMORY.md` / `USER.md` directly, with an enable switch, character-count limits, and a live save flow
- Replaces the Prompts entry for Hermes
### Hermes Provider Presets (~50)
- Covers Nous Research, Shengsuanyun, OpenRouter, DeepSeek, Together AI, StepFun, Zhipu GLM, Bailian, Kimi, MiniMax, DouBao, BaiLing, ModelScope, KAT-Coder, PackyCode, Cubence, AIGoCode, RightCode, AICodeMirror, AICoding, CrazyRouter, SSSAiCode, Micu, CTok.ai, DDSHub, E-FlowCode, LionCCAPI, PIPELLM, Compshare, SiliconFlow, AiHubMix, DMXAPI, TheRouter, Novita, Nvidia, and Xiaomi MiMo
### Launch Hermes Dashboard from Toolbar
- When the Hermes Web UI probe fails, the toolbar entry opens a confirm dialog offering to run `hermes dashboard` in the user's preferred terminal
- Spawned via a temp bash / batch script; `hermes dashboard` opens the browser itself once ready, so no polling is required
- 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`)
- Linux terminal detection reordered to try `which` before stat'ing `/usr/bin`, `/bin`, `/usr/local/bin`
### Claude Opus 4.7 Support
- New Claude Opus 4.7 with adaptive thinking whitelisting, per-million pricing seed, and Bedrock SKU (`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`, dropping the legacy `-v1` suffix)
- All aggregator and Bedrock presets migrated to Opus 4.7 as the default Opus model
### Claude `max` Effort Tier
- Claude effort dropdown upgraded from `high` to `max` for extended reasoning capacity
### Gemini Native API Proxy
- New `api_format = "gemini_native"` so the proxy can forward directly to Google's `generateContent` API (#1918, thanks @yovinchen)
- Full streaming, schema conversion, and shadow request support
- Adds `gemini_url.rs`, `gemini_schema.rs`, `gemini_shadow.rs`, `streaming_gemini.rs`, and `transform_gemini.rs` under the proxy providers module
### GitHub Copilot Enterprise Server (GHES)
- GHES authentication and endpoint configuration for Copilot-backed Claude providers (#2175, thanks @hotelbe)
### Session List Virtualization
- Virtualized the session list via `@tanstack/react-virtual` so long conversations (thousands of records) scroll smoothly
- Long session messages are collapsed by default to reduce text layout cost
### Codex / OpenClaw Session Title Extraction
- Meaningful title auto-extraction for Codex and OpenClaw sessions with 2-line display
- Strips OpenClaw `message_id` suffix noise
### Usage Date Range Picker
- New date range selector on the usage dashboard with preset tabs (Today / 1d / 7d / 14d / 30d) + custom date + time calendar (#2002, thanks @yovinchen)
- Page-jump input added on paginated lists
### Model Mapping Quick-Set
- New quick-set button next to model mapping fields in provider forms for faster edits (#2179, thanks @lispking)
### Stream Check Error Classification
- Stream Check errors are classified and surfaced as color-coded toasts
- Refreshed default probe models to match each vendor's current lineup
- Explicit detection for "model not found" responses
### Block Official Provider Switching During Local Routing
- Switching to official providers is blocked while Local Routing is active, with a warning toast
- Reason: routing official API traffic through the local proxy carries account-suspension risk
### Pricing Database Refresh (v8 → v9)
- Reseed-on-migration pricing table
- ~50 new model pricing entries including Claude 4.7, Opus 4.7 Adaptive Thinking, Grok 4, Qwen 3.5/3.6, MiniMax M2.5/M2.7, Doubao Seed 2.0 series, GLM-5/5.1
- Corrected stale prices for DeepSeek, Kimi K2.5, and others
### Application-Level Window Controls
- Opt-in setting to render CC Switch's own minimize / toggle-maximize / close buttons instead of system decorations (#1119, thanks @git1677967754)
- Materially improves the experience on Linux Wayland where compositor-drawn buttons can become inert
### Hermes in Unified Skills Management
- Hermes is added to the unified Skills surface
- Skill install, enable, and filter now cover the Hermes app alongside Claude / Codex / Gemini / OpenCode / OpenClaw
### OpenClaw Config Directory Override
- New settings option to point CC Switch at a custom `openclaw.json` location (#1518, thanks @mrFranklin)
### Hermes Config Directory Override
- New settings option to point CC Switch at a custom `~/.hermes/config.yaml` location, backed by data-driven dispatch
### StepFun Step Plan Preset
- StepFun Step Plan (EN / ZH) provider presets (#2155, thanks @hengm3467)
### New API Usage Script Template
- Added a User-Agent header to the New API usage script template for better upstream compatibility
### LemonData Provider Preset (All Six Apps)
- LemonData registered as a third-party partner preset across Claude, Codex, Gemini, OpenCode, OpenClaw, and Hermes
- Icon assets and zh / en / ja partner-promotion copy
- Claude preset uses `ANTHROPIC_API_KEY` auth; OpenAI-compatible apps target `gpt-5.4`
### DDSHub Codex Preset
- Added a Codex-compatible endpoint for DDSHub at the same host as its Claude service
- Base URL omits the `/v1` suffix because the gateway auto-routes OpenAI SDK paths
---
## Changed
### "Local Proxy Takeover" → "Local Routing"
- Unified the terminology across UI copy, README, and docs in all three locales
- Functional behavior is unchanged
### Hermes `Auto` api_mode Removed
- Users must pick an explicit protocol; new deeplinks default to `chat_completions`
- Eliminates URL-based heuristic surprises
### Hermes Provider Form
- Added an API mode dropdown and per-provider model editor
- Binds per-provider models to the top-level `model:` when switching active providers
### Hermes Deep Config Delegation
- Deep YAML knobs are no longer duplicated in the CC Switch form — they are delegated to the Hermes Web UI via a direct launch action
### Hermes Toolbar Layout
- Swapped the Hermes Web UI button from `ExternalLink` to `LayoutDashboard` (clicking may spawn `hermes dashboard` rather than just opening a URL)
- Moved MCP to the final toolbar slot so Hermes matches the Claude / Codex / Gemini / OpenCode layout
### `ANTHROPIC_REASONING_MODEL` Removed from Claude Quick-Set
- Decoupled the reasoning capability from model selection; the legacy field is no longer surfaced in the quick-set form
### Per-Provider Proxy Config Removed
- Consolidated into global Local Routing
- Provider-level proxy toggle and associated storage are gone
### Unified Toolbar Icon Button Width
- Normalized icon-button widths across Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes panels for a consistent header look
### Rust Toolchain Pinned to 1.95
- Adopted clippy 1.95 suggestions across the workspace and pinned the toolchain to prevent nightly drift
### Tray Menu ID Constant
- The tray identifier moved from the hardcoded string `"main"` to a `TRAY_ID` constant (`"cc-switch"`) across all call sites (#1978, thanks @lidaxian121)
### Copilot Premium Consumption Deep Optimization
A systematic overhaul to reduce Copilot reverse-proxy premium interaction consumption across multiple dimensions:
- **Proactive Thinking Block Stripping Before Forwarding**: Anthropic's `thinking` / `redacted_thinking` blocks are rejected by OpenAI-compatible endpoints. Previously, the request failed upstream, burning one premium interaction before the `thinking_rectifier` could retry. A new proactive strip step (Copilot optimization pipeline step 3.5, after `tool_result` merging) eliminates that wasted interaction
- **Request Classification Fix**: Messages containing `tool_result` are now classified as agent continuation instead of user-initiated, preventing every tool call from being falsely counted as a premium interaction
- **Subagent Detection**: Identifies subagents via `__SUBAGENT_MARKER__` with `metadata._agent_` fallback, setting `x-interaction-type=conversation-subagent`
- **Deterministic `x-interaction-id` Billing Merge**: Derives `x-interaction-id` from the session ID so multiple requests within the same session collapse into a single billing interaction
- **Orphan `tool_result` Sanitization**: Cleans up orphan `tool_result` entries to prevent upstream errors that would trigger retries and duplicate billing
- **Warmup Downgrade Enabled by Default**: Uses `gpt-5-mini` as the default downgrade model
- **Optimization Pipeline Reorder**: classify → sanitize → merge → warmup, so classification sees raw `tool_result` semantics
- Fixed a `CopilotOptimizerConfig` default-value inconsistency (unified to `gpt-5-mini`)
### Usage Script Intranet Support
- Removed private-IP / suspicious-hostname blocking from usage scripts, unblocking enterprise intranet, Docker, and self-hosted API endpoints
- Built-in templates still enforce HTTPS (except localhost) and same-origin checks; custom templates remain user-controlled with those request-URL checks skipped
### Failover Queue Notes
- Provider notes now appear in failover queue selectors and queue rows for easier identification across multi-provider queues (#2138, thanks @Coconut-Fish)
---
## Fixed
### Header Auto-Compact Latching After Maximize
- The toolbar no longer stays compacted after maximize/restore; compaction now reevaluates on size changes
### Hermes YAML Pollution & OAuth MCP `auth` Drop
- Round-tripping through CC Switch no longer drops OAuth MCP `auth` blocks or pollutes unrelated YAML keys
- Guard tests added via `tests/hermes_roundtrip.rs`
### Hermes Active Provider Display
- Hermes UI now correctly surfaces the active provider and wires add / enable / remove actions
### Hermes Provider Persistence
- Providers persist under `custom_providers:` so `api_mode` and `model` survive restarts and config reloads
### Hermes Health Check Borrowing OpenClaw Schema
- Hermes providers were routed through `check_additive_app_stream` (the OpenClaw dispatcher), which reads camelCase `baseUrl` / `apiKey` / `api` and surfaced "OpenClaw provider is missing baseUrl" even when every Hermes field was filled
- Introduced `check_hermes_stream` with Hermes-specific extractors that map `api_mode` (`chat_completions` / `anthropic_messages` / `codex_responses`) to the matching `check_claude_stream` `api_format`; `bedrock_converse` returns as unsupported
- `api_mode` is now resolved before URL / API key extraction, so `bedrock_converse` users see the real cause rather than a misleading "missing base_url"
### Usage Query Modal for Hermes & OpenClaw
- `getProviderCredentials` now reads 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
- Refactored the BALANCE and TOKEN_PLAN test paths to reuse the precomputed `providerCredentials` instead of re-reading `env.ANTHROPIC_*` directly, fixing the "empty key" error for non-Claude apps even when the key was configured
### Codex `cache_control` Preservation
- Preserve `cache_control` when merging system prompts during Codex format conversion (#1946, thanks @yovinchen)
### Claude Prompt Cache Key Leak
- Stopped sending prompt cache keys during Claude chat conversions (#2003, thanks @yovinchen)
### Proxy Hop-by-Hop Header Stripping
- Strip hop-by-hop response headers (Connection, Keep-Alive, Transfer-Encoding, etc.) per RFC 7230 (#2060, thanks @yovinchen)
### Permissive Proxy CORS Removed
- Removed the permissive CORS layer from the proxy (#1915, thanks @zerone0x)
### Backend Error Details in Proxy Toast
- Surface backend error payload details in proxy-related toast messages instead of a generic failure string
### Usage Log Deduplication
- Deduplicated proxy and session-log usage records so the same request is no longer double-counted
- Synced the request log time range with the dashboard's 1d / 7d / 30d selector
### Common Config Checkbox Persistence
- Checkbox state for Claude / Codex / Gemini common-config toggles now persists correctly across reopens (#2191, thanks @zxZeng)
### Claude Plugin `settings.json` Sync
- Editing the current provider now syncs back to `settings.json` for the Claude plugin path (#1905, thanks @chengww5217)
### Google Official Gemini Env Preservation
- Saving the Google Official Gemini provider no longer clobbers the `env` block
### OpenCode JSON5 Parser for Trailing Commas
- OpenCode config reads now tolerate trailing commas via a JSON5 parser (#2023, thanks @wwminger)
### Preset Refreshes
- Refreshed stale context windows for DeepSeek and Claude 1M
- Refreshed stale model IDs; backfilled Hermes model lists
- Fixed the Nous endpoint and replaced the Hermes placeholder icon with Nous brand artwork
- Pruned unused official Hermes presets
### Auto-Expand Collapsed Messages on Search Hit
- Collapsed messages now auto-expand when a search match lands inside hidden content
### Unknown Subscription Quota Tiers Hidden
- Provider cards no longer render unknown subscription quota tiers
### Weekly Limit Label Unified
- Aligned the `weekly_limit` tier label with the official 7-day naming across locales
### Root-Level Skill Repo Install
- Fixed skill installation when the repository root itself is a skill
### Session ID Parsing Clippy
- Removed a redundant closure in session ID parsing (clippy warning)
### Stream Check Default Models Refresh
- Updated stream-check default probe models to match each vendor's current lineup
### Skills Import Sync
- Imported Skills are now immediately synced into enabled app directories instead of only being recorded in the database (#2101, thanks @yaoguohh)
- The UI no longer shows "installed" while the target app directory is missing the skill
### Ghostty Session Restore
- Fixed Ghostty session restore launch by using shell execution with `--working-directory` (#1976, thanks @Suda202)
- Avoids `cwd` escaping issues when the path contains spaces or special characters
---
## Docs
### README Sponsor Updates
- Updated SiliconFlow signup bonus to ¥16
- Trimmed the SSSAiCode sponsor blurb
- Updated partner logos
- Added LemonData as a new sponsor
### Global Proxy Hint Clarified
- Clarified the global proxy hint about local routing across all three locales
### Takeover → Routing Rename
- Renamed takeover docs to routing and updated anchors across all languages
### PIPELLM Website URL
- Updated the PIPELLM sponsor website URL to `code.pipellm.ai`
---
## ⚠️ Breaking Changes
### Hermes requires explicit `api_mode`
- The `Auto` mode is gone; imported or deeplinked providers default to `chat_completions`
- Users with prior `Auto` configs will be prompted to pick a protocol
### `ANTHROPIC_REASONING_MODEL` removed from Claude quick-set
- The legacy field is no longer exposed; existing settings are cleaned up automatically
### Per-provider proxy configuration removed
- Migrate to the global Local Routing setting
- Existing per-provider proxy values are ignored
### Database schema v9 → v10
- Adds `enabled_hermes` columns to `mcp_servers` and `skills`
- Auto-migrated with `DEFAULT 0`; no data loss
### Pricing table reseeded (v8 → v9)
- The `model_pricing` table is cleared and reseeded on first launch to pick up new models and corrected prices
### XCodeAPI preset removed
- Users of the XCodeAPI preset should switch to another provider
---
## ⚠️ Risk Notice
This release inherits the risk notices originally introduced in v3.12.3 / v3.13.0 for reverse-proxy-style features.
**GitHub Copilot Reverse Proxy**: Using Copilot's reverse-proxy path may violate GitHub / Microsoft's terms of service. See [v3.12.3 release notes](v3.12.3-en.md#-risk-notice).
**Codex OAuth Reverse Proxy**: Using the Codex OAuth reverse proxy with a ChatGPT subscription may violate OpenAI's terms of service. See [v3.13.0 release notes](v3.13.0-en.md#-risk-notice).
By enabling these features, users **accept all associated risks**. CC Switch is not responsible for any account restrictions, warnings, or service suspensions that result from using these features.
---
## Download & Installation
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) to download the appropriate version.
### System Requirements
| OS | Minimum Version | Architecture |
| ------- | ----------------------- | ----------------------------------- |
| Windows | Windows 10 or later | x64 |
| macOS | macOS 12 (Monterey) or later | Intel (x64) / Apple Silicon (arm64) |
| Linux | See table below | x64 |
### Windows
| File | Description |
| ---------------------------------------- | ----------------------------------------------- |
| `CC-Switch-v3.14.0-Windows.msi` | **Recommended** - MSI installer, supports auto-update |
| `CC-Switch-v3.14.0-Windows-Portable.zip` | Portable, extract and run, no registry writes |
### macOS
| File | Description |
| -------------------------------- | -------------------------------------------------------- |
| `CC-Switch-v3.14.0-macOS.dmg` | **Recommended** - DMG installer, drag into Applications |
| `CC-Switch-v3.14.0-macOS.zip` | Extract and drag into Applications, Universal Binary |
| `CC-Switch-v3.14.0-macOS.tar.gz` | For Homebrew installation and auto-update |
> macOS builds are Apple code-signed and notarized — install directly.
### Homebrew (macOS)
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
Update:
```bash
brew upgrade --cask cc-switch
```
### Linux
| Distribution | Recommended | Installation |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | Add execute permission and run, or use AUR |
| Other distros / not sure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
-469
View File
@@ -1,469 +0,0 @@
# CC Switch v3.14.0
> Hermes Agent が 6 番目の管理対象アプリに、Claude Opus 4.7 をプリセットマトリクス全体へ展開、Gemini Native API プロキシ、「Local Routing」への名称統一、アプリケーションレベルのウィンドウコントロール
**[中文版 →](v3.14.0-zh.md) | [English →](v3.14.0-en.md)**
---
## 概要
CC Switch v3.14.0 は、**Hermes Agent を 6 番目の一等管理対象アプリケーション**として CC Switch に取り込み、**Claude Opus 4.7** をアグリゲーターおよび Bedrock プリセットのマトリクス全体に展開することを中心に据えた大型リリースです。Hermes サポートは、データベース v9 → v10 マイグレーション、完全な Rust コマンド面、アトミックバックアップ付きの YAML ベースな `~/.hermes/config.yaml` 読み書き、MCP 同期、Skills 同期、SQLite + JSONL セッション管理、および Memory エディターを含む専用のフロントエンドパネルをカバーします。Hermes Agent 0.10.0 スキーマに整合する 4 つの API プロトコル(`chat_completions``anthropic_messages``codex_responses``bedrock_converse`)すべてを選択可能です。ユーザーが直接記述した `providers:` dict のエントリは読み取り専用カードとして表示され、深い YAML 設定は Hermes Web UI に委譲されます。
Hermes に加えて、本リリースでは **Gemini Native API プロキシ**`api_format = "gemini_native"`)を追加し、プロキシがリクエストを Google の `generateContent` エンドポイントに直接転送できるようにしました(完全なストリーミング、スキーマ変換、シャドウリクエストをサポート)。また、旧「Local Proxy Takeover」を三言語の UI / README / ドキュメント全体で **Local Routing** に統一リネームし、コンポジターが描画するボタンが無反応になり得る Linux Wayland などのシーンで、CC Switch が自前で最小化 / 最大化 / 閉じるボタンを描画できるオプション「**アプリケーションレベルのウィンドウコントロール**」を導入しました。さらにリリース直前に、ツールバーからの `hermes dashboard` 直接起動、LemonData の全アプリプリセット、DDSHub の Codex エンドポイント、および複数の Hermes ヘルスチェックと Usage モーダルの修正が追加されました。
セッション側では、`@tanstack/react-virtual` によるセッションリストの**仮想化**で数千件のレコードを持つ長い会話も滑らかにスクロールでき、長いメッセージはデフォルトで折り畳まれます。Usage ダッシュボードには**日付範囲ピッカー**(今日 / 1d / 7d / 14d / 30d + カスタム日時カレンダー)とページジャンプ入力が追加され、**Stream Check エラー分類**は色分けされたトーストで提示され、デフォルトの探索モデルが更新され、「モデルが見つからない」レスポンスを個別に識別するようになりました。また、Local Routing が有効な間に公式プロバイダーへの切り替えを**強制的にブロック**する保護を追加し、公式 API トラフィックがローカルプロキシを経由することによるアカウント停止リスクを防ぎます。Pricing データベースは v8 → v9 で再シードされ、約 50 件の新しいモデルエントリ(Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1 など)を追加し、いくつかの古い価格を修正しました。
**リリース日**: 2026-04-21
**更新規模**: 100 commits | 219 files changed | +20,548 / -3,569 lines
---
## ハイライト
- **Hermes Agent サポート(6 番目の管理対象アプリ)**: データベース v9 → v10 マイグレーション、完全な Rust コマンド面、アトミックバックアップ付き YAML 読み書き、MCP 同期、Skills 同期、SQLite + JSONL セッション管理、専用フロントエンドパネル、4 つの API プロトコル(`chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`
- **Claude Opus 4.7 の全面展開**: 適応的思考のホワイトリスト、百万トークン単位の価格シード、Bedrock SKU(`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`、旧 `-v1` サフィックスを廃止)、全アグリゲーター / Bedrock プリセットを Opus 4.7 をデフォルト Opus モデルに移行
- **Claude `max` エフォートティア**: エフォートのドロップダウンを `high` から `max` に引き上げ
- **Gemini Native API プロキシ**: 新しい `api_format = "gemini_native"` により、プロキシが Google の `generateContent` に直接転送可能に(完全なストリーミング / スキーマ変換 / シャドウリクエスト対応)
- **GitHub Copilot Enterprise Server**: Copilot ベースの Claude プロバイダーに GHES 認証とエンドポイント設定を追加
- **Copilot 交互消費の大幅最適化**: 転送前の thinking ブロック主動削除、`tool_result` メッセージ分類修正、subagent 検出、`x-interaction-id` 課金マージ、孤立 `tool_result` のサニタイズ、Warmup ダウングレードのデフォルト有効化など、premium 交互消費を系統的に削減
- **セッションリスト仮想化**: 長い会話が滑らかにスクロール。長いメッセージはデフォルトで折り畳まれ、テキストレイアウトコストを削減
- **Codex / OpenClaw セッションタイトル抽出**: 意味のあるタイトルを自動抽出(2 行表示)、OpenClaw の `message_id` 末尾ノイズを除去
- **Usage 日付範囲ピッカー**: Today / 1d / 7d / 14d / 30d プリセットタブ + カスタム日時カレンダー。ページネーションリストにページジャンプ入力
- **Stream Check エラー分類**: エラーを分類し色分けトーストで提示。デフォルト探索モデル更新。「モデルが見つからない」レスポンスを明示的に検出
- **Local Routing 有効時の公式プロバイダー切り替えブロック**: 公式 API トラフィックをローカルプロキシ経由で流すとアカウント停止のリスクがあるため、切り替えを強制ブロックして警告トーストを表示
- **Pricing データベース刷新(v8 → v9)**: 約 50 件の新しいモデルエントリを追加し、古い価格を修正
- **アプリケーションレベルのウィンドウコントロール**: CC Switch が自前で最小化 / 最大化トグル / 閉じるボタンを描画するオプション設定。Linux Wayland での体験を大きく改善
- **統一 Skills 管理への Hermes 追加**: Skill のインストール / 有効化 / フィルターが Hermes をカバー
- **Hermes / OpenClaw 設定ディレクトリのカスタマイズ**: 設定で `~/.hermes/config.yaml``openclaw.json` のカスタム位置を指定可能
- **ツールバーからの Hermes Dashboard 起動**: Hermes Web UI のプローブに失敗した際、ツールバーエントリからユーザーの優先ターミナルで `hermes dashboard` を実行可能
- **新パートナープリセット**: LemonData を全 6 アプリにわたって追加、DDSHub の Codex エンドポイント、StepFun Step Plan
---
## 新機能
### Hermes Agent サポート(6 番目の管理対象アプリ)
CC Switch は Hermes Agent を Claude / Codex / Gemini / OpenCode / OpenClaw と並ぶ一等の管理対象アプリとして初めてサポートします。
- **データベースマイグレーション v9 → v10**: `mcp_servers``skills` テーブルに `enabled_hermes` カラムを追加(`DEFAULT 0`、自動マイグレーション、データ損失なし)
- **YAML 設定の読み書き**: `~/.hermes/config.yaml` をアトミックバックアップ付きで読み書き。`tests/hermes_roundtrip.rs` が OAuth MCP `auth` ブロックの消失や無関係なキーの汚染を防止
- **4 つの API プロトコル**: Hermes Agent 0.10.0 と整合する `chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`。新しいディープリンクはデフォルトで `chat_completions`
- **ユーザー `providers:` dict の読み取り専用表示**: YAML に手書きされたプロバイダーエントリは CC Switch で読み取り専用カードとして表示され、深い設定は Hermes Web UI に委譲
- **加算的な切り替え**: Claude / Codex の「上書き」型切り替えと異なり、Hermes ではすべてのプロバイダーが同じ YAML に共存
### Hermes Memory パネル
- `MEMORY.md` / `USER.md` を直接編集できる Memory パネルを追加(有効化スイッチ、文字数制限、ライブ保存フロー付き)
- Hermes の Prompts エントリを置き換え
### Hermes プロバイダープリセット(約 50 個)
- Nous Research、Shengsuanyun(胜算云)、OpenRouter、DeepSeek、Together AI、StepFun、Zhipu GLM、Bailian(百炼)、Kimi、MiniMax、DouBao(豆包)、BaiLing(百灵)、ModelScope(魔搭)、KAT-Coder、PackyCode、Cubence、AIGoCode、RightCode、AICodeMirror、AICoding、CrazyRouter、SSSAiCode、Micu、CTok.ai、DDSHub、E-FlowCode、LionCCAPI、PIPELLM、Compshare、SiliconFlow、AiHubMix、DMXAPI、TheRouter、Novita、Nvidia、Xiaomi MiMo をカバー
### ツールバーからの Hermes Dashboard 起動
- Hermes Web UI のプローブに失敗した際、ツールバーエントリがユーザーの優先ターミナルで `hermes dashboard` を実行する確認ダイアログを表示
- 一時 bash / batch スクリプト経由で起動。`hermes dashboard` 自身が準備完了後にブラウザを開くため、ポーリングは不要
- Memory パネルと Health バナーは既存のトースト動作を維持
- オフラインのトーストにあった古い `hermes web` のヒントも修正(正しいコマンドは `hermes dashboard`
- Linux ターミナル検出の順序を変更し、`/usr/bin``/bin``/usr/local/bin` を stat する前に `which` を試すように
### Claude Opus 4.7 サポート
- Claude Opus 4.7 を追加。適応的思考のホワイトリスト、百万トークン単位の価格シード、Bedrock SKU(`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`、旧 `-v1` サフィックスを廃止)
- 全アグリゲーター / Bedrock プリセットをデフォルト Opus モデルとして Opus 4.7 に移行
### Claude `max` エフォートティア
- Claude エフォートドロップダウンを `high` から `max` に引き上げ、より強力な推論容量を解放
### Gemini Native API プロキシ
- 新しい `api_format = "gemini_native"` により、プロキシが Google の `generateContent` API に直接転送可能 (#1918, 感謝 @yovinchen)
- 完全なストリーミング、スキーマ変換、シャドウリクエストに対応
- proxy providers モジュール下に `gemini_url.rs``gemini_schema.rs``gemini_shadow.rs``streaming_gemini.rs``transform_gemini.rs` を追加
### GitHub Copilot Enterprise ServerGHES
- Copilot ベースの Claude プロバイダーに GHES 認証とエンドポイント設定を追加 (#2175, 感謝 @hotelbe)
### セッションリスト仮想化
- `@tanstack/react-virtual` によりセッションリストを仮想化。数千件のレコードを持つ長い会話も滑らかにスクロール
- 長いセッションメッセージはデフォルトで折り畳まれ、テキストレイアウトコストを削減
### Codex / OpenClaw セッションタイトル抽出
- Codex と OpenClaw セッションから意味のあるタイトルを自動抽出し、2 行表示
- OpenClaw の `message_id` 末尾ノイズを除去
### Usage 日付範囲ピッカー
- Usage ダッシュボードに日付範囲セレクターを追加。プリセットタブ(Today / 1d / 7d / 14d / 30d+ カスタム日時カレンダー (#2002, 感謝 @yovinchen)
- ページネーションリストにページジャンプ入力を追加
### モデルマッピングのクイック入力
- プロバイダーフォームのモデルマッピングフィールドの横にクイック入力ボタンを追加し、編集を高速化 (#2179, 感謝 @lispking)
### Stream Check エラー分類
- Stream Check エラーを分類し、色分けトーストとして提示
- デフォルトの探索モデルを各ベンダーの現行ラインナップに合わせて更新
- 「モデルが見つからない」レスポンスを明示的に検出
### Local Routing 有効時の公式プロバイダー切り替えブロック
- Local Routing が有効な状態で公式プロバイダーに切り替えようとすると、強制的にブロックされ警告トーストが表示される
- 理由: 公式 API トラフィックをローカルプロキシ経由で流すとアカウント停止のリスクがあるため
### Pricing データベース刷新(v8 → v9)
- マイグレーション時に定価テーブルを再シード
- Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1 などを含む約 50 件の新しいモデルエントリを追加
- DeepSeek、Kimi K2.5 などの古い価格を修正
### アプリケーションレベルのウィンドウコントロール
- CC Switch が自前で最小化 / 最大化トグル / 閉じるボタンを描画するオプション設定を追加。システム装飾の代わりに使用 (#1119, 感謝 @git1677967754)
- コンポジター描画ボタンが無反応になり得る Linux Wayland での体験を大きく改善
### 統一 Skills 管理への Hermes 追加
- 統一 Skills サーフェスに Hermes を追加
- Skill のインストール / 有効化 / フィルターが、Claude / Codex / Gemini / OpenCode / OpenClaw と並んで Hermes アプリをカバー
### OpenClaw 設定ディレクトリのカスタマイズ
- CC Switch が参照する `openclaw.json` のカスタム位置を設定できるオプションを追加 (#1518, 感謝 @mrFranklin)
### Hermes 設定ディレクトリのカスタマイズ
- CC Switch が参照する `~/.hermes/config.yaml` のカスタム位置を設定できるオプションを追加。データ駆動 dispatch でサポート
### StepFun Step Plan プリセット
- StepFun Step PlanEN / ZH)プロバイダープリセットを追加 (#2155, 感謝 @hengm3467)
### New API 用量スクリプトテンプレート
- New API の用量スクリプトテンプレートに User-Agent ヘッダーを追加し、上流互換性を向上
### LemonData プロバイダープリセット(全 6 アプリ)
- LemonData をサードパーティパートナープリセットとして Claude、Codex、Gemini、OpenCode、OpenClaw、Hermes の全 6 アプリに登録
- アイコンアセットと zh / en / ja 三言語のパートナー推奨文面を追加
- Claude プリセットは `ANTHROPIC_API_KEY` 認証を使用。OpenAI 互換アプリは `gpt-5.4` をターゲット
### DDSHub Codex プリセット
- DDSHub の Codex 互換エンドポイントを追加(Claude サービスと同じホスト)
- ベース URL は `/v1` サフィックスを省略(ゲートウェイが OpenAI SDK パスを自動ルーティング)
---
## 変更
### 「Local Proxy Takeover」→「Local Routing」
- 三言語の UI 文言、README、ドキュメント全体で用語を統一リネーム
- 機能的な動作は変更なし
### Hermes `Auto` api_mode の削除
- ユーザーは明示的にプロトコルを選択する必要あり。新しいディープリンクはデフォルトで `chat_completions`
- URL ベースのヒューリスティックによる意外な挙動を排除
### Hermes プロバイダーフォーム
- API モードドロップダウンとプロバイダー単位のモデルエディターを追加
- アクティブなプロバイダーを切り替える際、プロバイダー単位のモデルをトップレベルの `model:` にバインド
### Hermes 深い設定の委譲
- 深い YAML 設定は CC Switch フォームで重複させず、「Hermes Web UI を起動」ボタン経由で Web UI に直接委譲
### Hermes ツールバーレイアウト
- Hermes Web UI ボタンのアイコンを `ExternalLink` から `LayoutDashboard` に変更(クリック時に単に URL を開くのではなく `hermes dashboard` を起動する場合があるため、パネル型アイコンのほうが意味的に正確)
- MCP をツールバーの末尾に移動し、Hermes のレイアウトを Claude / Codex / Gemini / OpenCode と揃える
### Claude Quick-Set から `ANTHROPIC_REASONING_MODEL` を削除
- 推論能力とモデル選択を分離。レガシーフィールドは Quick-Set フォームから除外
### プロバイダー単位のプロキシ設定を削除
- グローバルな Local Routing に統合
- プロバイダー単位のプロキシトグルと関連ストレージは削除済み
### ツールバーアイコンボタン幅の統一
- Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes パネルの間でアイコンボタン幅を正規化し、ヘッダーの見た目を統一
### Rust Toolchain を 1.95 にピン留め
- ワークスペース全体で clippy 1.95 の提案を採用し、nightly ドリフトを防ぐためツールチェーンをピン留め
### トレイメニュー ID 定数
- トレイ識別子をハードコーディング文字列 `"main"` から `TRAY_ID` 定数(`"cc-switch"`)に移行。すべての呼び出し箇所で同期 (#1978, 感謝 @lidaxian121)
### Copilot 交互消費の大幅最適化
Copilot リバースプロキシの premium 交互消費を削減するための系統的な最適化。以下の複数の改善をカバー:
- **転送前に thinking ブロックを主動削除**: Anthropic の `thinking` / `redacted_thinking` ブロックは OpenAI 互換エンドポイントに拒否される。従来は上流でリクエストが失敗して premium 交互を 1 回消費した後、`thinking_rectifier` によってリトライされていた。新しい主動削除ステップ(Copilot 最適化パイプラインの 3.5 ステップ目、`tool_result` マージ後)により、この無駄な premium 消費を直接解消
- **リクエスト分類の修正**: `tool_result` を含むメッセージをユーザー発起の新規リクエストではなく、エージェント継続として分類。ツール呼び出しが毎回 premium 交互としてカウントされる問題を防止
- **subagent 検出**: `__SUBAGENT_MARKER__``metadata._agent_` フォールバックで subagent を識別し、`x-interaction-type=conversation-subagent` を設定
- **決定論的 `x-interaction-id` による課金マージ**: セッション ID から `x-interaction-id` を導出し、同一セッション内の複数リクエストを 1 回の課金交互に統合
- **孤立 `tool_result` のサニタイズ**: 孤立した `tool_result` を整理し、上流エラーによるリトライおよび重複課金を防止
- **Warmup ダウングレードをデフォルトで有効化**: `gpt-5-mini` をデフォルトのダウングレードモデルとして使用
- **最適化パイプラインの並び替え**: classify → sanitize → merge → warmup の順序で、分類が生の `tool_result` セマンティクスを参照可能に
- `CopilotOptimizerConfig` のデフォルト値の不一致を修正(`gpt-5-mini` に統一)
### 用量スクリプトのイントラネットサポート
- 用量スクリプトからプライベート IP / 不審なホスト名のブロッキングを削除し、エンタープライズイントラネット、Docker、自己ホスト API エンドポイントを解放
- ビルトインテンプレートは引き続き HTTPS(localhost を除く)と同一オリジンチェックを強制。カスタムテンプレートはユーザー制御のまま、リクエスト URL のチェックをスキップ
### Failover キューの備考表示
- プロバイダーの備考が failover キューセレクターとキュー行に表示され、マルチプロバイダーキューでの識別が容易に (#2138, 感謝 @Coconut-Fish)
---
## バグ修正
### 最大化後のツールバー自動折り畳みラッチ
- ウィンドウの最大化 / 復元後、ツールバーが折り畳まれたままになる問題を修正。折り畳み判定はサイズ変更時に再評価される
### Hermes YAML 汚染と OAuth MCP `auth` 消失
- CC Switch 経由でラウンドトリップしても OAuth MCP `auth` ブロックが消失したり、無関係な YAML キーが汚染されたりしなくなった
- `tests/hermes_roundtrip.rs` をガードテストとして追加
### Hermes アクティブプロバイダー表示
- Hermes UI がアクティブプロバイダーを正しく表示するようになり、追加 / 有効化 / 削除アクションが正しく動作
### Hermes プロバイダーの永続化
- プロバイダーは `custom_providers:` の下に永続化され、`api_mode``model` が再起動 / 設定再読み込みを生き延びる
### Hermes ヘルスチェックが OpenClaw のスキーマを流用していた問題
- 以前 Hermes プロバイダーは `check_additive_app_stream`(OpenClaw のディスパッチャー)にルーティングされており、これは camelCase の `baseUrl` / `apiKey` / `api` を読むため、Hermes フィールドをすべて記入しても "OpenClaw provider is missing baseUrl" と表示されていた
- `check_hermes_stream` を導入し、Hermes 専用のエクストラクターで `api_mode``chat_completions` / `anthropic_messages` / `codex_responses`)を対応する `check_claude_stream``api_format` にマッピング。`bedrock_converse` は非対応として返す
- URL / API キーの抽出前に `api_mode` を解決することで、`bedrock_converse` を選んだユーザーには「missing base_url」という誤解を招くメッセージではなく実際の原因が表示される
### Hermes / OpenClaw 向け Usage クエリモーダル
- `getProviderCredentials` が Hermessnake_case の `base_url` / `api_key`)と OpenClawcamelCase の `baseUrl` / `apiKey`)のフラットな `settingsConfig` フィールドを読むようになり、SiliconFlow などマッチするプロバイダーで「official balance」テンプレートが自動選択される
- BALANCE と TOKEN_PLAN テストパスをリファクタリングし、`env.ANTHROPIC_*` を直接再読するのではなく、事前計算された `providerCredentials` を再利用するように変更。これにより非 Claude アプリでキーが設定されていても「empty key」エラーが出ていた問題を修正
### Codex `cache_control` 保持
- Codex フォーマット変換中に system prompt をマージする際の `cache_control` を保持 (#1946, 感謝 @yovinchen)
### Claude プロンプトキャッシュキーのリーク
- Claude chat 変換時にプロンプトキャッシュキーを送信しないように修正 (#2003, 感謝 @yovinchen)
### プロキシ Hop-by-Hop レスポンスヘッダーの削除
- RFC 7230 に従ってプロキシレスポンスの hop-by-hop ヘッダー(Connection、Keep-Alive、Transfer-Encoding など)を削除 (#2060, 感謝 @yovinchen)
### プロキシの寛容な CORS レイヤー削除
- プロキシの寛容な CORS レイヤーを削除 (#1915, 感謝 @zerone0x)
### プロキシトーストでのバックエンドエラー詳細表示
- プロキシ関連のトーストメッセージで、汎用的な失敗文字列ではなくバックエンドのエラーペイロードの詳細を表示
### Usage ログの重複排除
- プロキシとセッションログの用量レコードを重複排除し、同じリクエストが二重にカウントされないように修正
- リクエストログの時間範囲をダッシュボードの 1d / 7d / 30d セレクターと同期
### Common Config チェックボックスの永続化
- Claude / Codex / Gemini の common-config トグルのチェック状態が再オープンをまたいで正しく保持されるように修正 (#2191, 感謝 @zxZeng)
### Claude プラグイン `settings.json` 同期
- 現在のプロバイダーを編集すると、Claude プラグインパスの `settings.json` に同期されるように修正 (#1905, 感謝 @chengww5217)
### Google Official Gemini の env 保持
- Google Official Gemini プロバイダーを保存しても `env` ブロックが消えないように修正
### OpenCode の JSON5 による末尾カンマ解析
- OpenCode 設定読み取りが JSON5 パーサーにより末尾カンマを許容するように修正 (#2023, 感謝 @wwminger)
### プリセットの刷新
- DeepSeek と Claude 1M の古いコンテキストウィンドウを刷新
- 古いモデル ID を刷新。Hermes のモデルリストをバックフィル
- Nous エンドポイントを修正し、Hermes のプレースホルダーアイコンを Nous ブランドのアートワークに置き換え
- 未使用の公式 Hermes プリセットを整理
### 検索ヒット時の折り畳みメッセージの自動展開
- 隠されたコンテンツ内部で検索マッチが発生した場合、折り畳みメッセージを自動展開してマッチを示す
### 不明なサブスクリプション配額ティアの非表示
- プロバイダーカードは不明なサブスクリプション配額ティアを表示しないように変更
### weekly_limit ラベルの統一
- `weekly_limit` ティアラベルを公式の「7 日」命名にロケール間で揃えた
### ルートレベルの Skill リポジトリインストール
- リポジトリのルート自体が skill の場合のインストール失敗を修正
### Session ID 解析の clippy 警告
- session ID 解析内の冗長なクロージャを削除(clippy 警告)
### Stream Check デフォルトモデルの刷新
- Stream Check のデフォルト探索モデルを各ベンダーの現行ラインナップに合わせて更新
### Skills インポートの同期
- インポートされた Skills はデータベースに記録されるだけでなく、有効化されたアプリディレクトリにも即座に同期されるように変更 (#2101, 感謝 @yaoguohh)
- UI が「インストール済み」と表示しているのに対象アプリディレクトリに skill が存在しない状態を解消
### Ghostty セッション復元
- Ghostty セッション復元の起動を `--working-directory` 付きのシェル実行に変更 (#1976, 感謝 @Suda202)
- パスにスペースや特殊文字が含まれる場合の `cwd` エスケープ問題を回避
---
## ドキュメント
### README スポンサー更新
- SiliconFlow のサインアップボーナスを ¥16 に更新
- SSSAiCode のスポンサー文面を簡潔化
- パートナーロゴを更新
- 新しいスポンサーとして LemonData を追加
### グローバルプロキシヒントの明確化
- 三言語でグローバルプロキシと Local Routing の関係を明確化
### Takeover → Routing ドキュメントのリネーム
- テイクオーバー関連ドキュメントを三言語で routing にリネームし、アンカーを同期更新
### PIPELLM ウェブサイト URL
- PIPELLM スポンサーのウェブサイト URL を `code.pipellm.ai` に更新
---
## ⚠️ 重要な変更(Breaking
### Hermes は明示的な `api_mode` が必須
- `Auto` モードは廃止。インポートまたはディープリンクで取得したプロバイダーはデフォルトで `chat_completions`
- 既存の `Auto` 設定のユーザーはプロトコルを選択するよう促される
### Claude Quick-Set から `ANTHROPIC_REASONING_MODEL` を削除
- レガシーフィールドは公開されなくなった。既存の設定は自動的にクリーンアップされる
### プロバイダー単位のプロキシ設定を削除
- グローバル Local Routing 設定に移行
- 既存のプロバイダー単位のプロキシ値は無視される
### データベーススキーマ v9 → v10
- `mcp_servers``skills``enabled_hermes` カラムを追加
- `DEFAULT 0` で自動マイグレーション、データ損失なし
### Pricing テーブルの再シード(v8 → v9)
- 新しいモデルと修正済み価格を取り込むため、初回起動時に `model_pricing` テーブルがクリアされ再シードされる
### XCodeAPI プリセットの削除
- XCodeAPI プリセットを使用していたユーザーは別のプロバイダーに切り替える必要がある
---
## ⚠️ リスクに関する注意事項
本リリースは、リバースプロキシ型機能について v3.12.3 / v3.13.0 で提起された既存のリスク注意事項を継承します。
**GitHub Copilot リバースプロキシ**: Copilot のリバースプロキシパスを使用すると、GitHub / Microsoft の利用規約に違反する可能性があります。詳細は [v3.12.3 リリースノート](v3.12.3-ja.md#-リスクに関する注意事項) を参照してください。
**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションで Codex OAuth リバースプロキシを使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 リリースノート](v3.13.0-ja.md#-リスクに関する注意事項) を参照してください。
これらの機能を有効にすることで、ユーザーは**すべての関連リスクを自己責任で受諾**したものとみなされます。CC Switch はこれらの機能の使用に起因するアカウントの制限、警告、サービス停止について一切の責任を負いません。
---
## ダウンロード・インストール
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から対応バージョンをダウンロードしてください。
### システム要件
| OS | 最小バージョン | アーキテクチャ |
| ------- | ---------------------------- | ----------------------------------- |
| Windows | Windows 10 以降 | x64 |
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 下表参照 | x64 |
### Windows
| ファイル | 説明 |
| ---------------------------------------- | ------------------------------------------- |
| `CC-Switch-v3.14.0-Windows.msi` | **推奨** - MSI インストーラー、自動更新対応 |
| `CC-Switch-v3.14.0-Windows-Portable.zip` | ポータブル版、解凍して実行、レジストリ不要 |
### macOS
| ファイル | 説明 |
| -------------------------------- | -------------------------------------------------------- |
| `CC-Switch-v3.14.0-macOS.dmg` | **推奨** - DMG インストーラー、Applications にドラッグ |
| `CC-Switch-v3.14.0-macOS.zip` | 解凍して Applications にドラッグ、Universal Binary |
| `CC-Switch-v3.14.0-macOS.tar.gz` | Homebrew インストールと自動更新用 |
> macOS 版は Apple のコード署名および公証済みで、直接インストールして使用できます。
### HomebrewmacOS
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
| ディストリビューション | 推奨形式 | インストール方法 |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | 実行権限を付与して実行、または AUR を使用 |
| その他のディストリビューション / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
-468
View File
@@ -1,468 +0,0 @@
# CC Switch v3.14.0
> Hermes Agent 成为第 6 个受管应用、Claude Opus 4.7 全面接入、Gemini Native API 代理、Local Routing 统一重命名、应用级窗口控件
**[English →](v3.14.0-en.md) | [日本語版 →](v3.14.0-ja.md)**
---
## 概览
CC Switch v3.14.0 是一次大版本更新,核心焦点是把 **Hermes Agent 作为第 6 个一等受管应用**接入 CC Switch,并把 **Claude Opus 4.7** 铺设到全部聚合器与 Bedrock 预设矩阵。Hermes 支持覆盖数据库 v9 → v10 迁移、完整的 Rust 命令面、基于 YAML 的 `~/.hermes/config.yaml` 读写(含原子备份)、MCP 同步、Skills 同步、SQLite + JSONL 会话管理,以及专属的前端面板和 Memory 编辑面板;与 Hermes Agent 0.10.0 schema 对齐的四种协议(`chat_completions``anthropic_messages``codex_responses``bedrock_converse`)全部可选。用户自行维护的 `providers:` dict 条目以只读卡片形式呈现,深度 YAML 配置则直接委托给 Hermes Web UI。
除了 Hermes,本次还新增了 **Gemini Native API 代理**`api_format = "gemini_native"`),让代理可以把请求直接转发到 Google 的 `generateContent` 端点,完整支持流式、schema 转换和 shadow 请求;把老的 "Local Proxy Takeover" 在三语 UI / README / 文档中统一重命名为 **Local Routing**;新增 **应用级窗口控件**,在 Linux Wayland 等合成器绘制按钮失灵的场景下可选让 CC Switch 自绘最小化 / 最大化 / 关闭按钮;并在本版本发布前额外合入了从工具栏直接启动 `hermes dashboard`、LemonData 全应用预设、DDSHub Codex 端点以及若干 Hermes 健康检查与 Usage 模态框的修复。
会话侧通过 `@tanstack/react-virtual` **虚拟化会话列表**,让上千条记录的长会话也能流畅滚动,长消息默认折叠;Usage 面板新增**日期范围选择器**(今日 / 1d / 7d / 14d / 30d + 自定义日期时间)和翻页输入;**Stream Check 错误分类**以彩色 toast 呈现,默认探测模型重新梳理,"模型不存在"响应被单独识别;并新增在 Local Routing 激活时**阻止切换到官方供应商**的保护,以免官方流量被引入本地代理造成账号风险。Pricing 数据库 v8 → v9 重新种入约 50 个新模型条目(包括 Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1 等),并修正了多项陈旧价格。
**发布日期**2026-04-21
**更新规模**100 commits | 219 files changed | +20,548 / -3,569 lines
---
## 重点内容
- **Hermes Agent 支持(第 6 个受管应用)**:数据库 v9 → v10 迁移、完整 Rust 命令面、YAML 读写带原子备份、MCP 同步、Skills 同步、SQLite + JSONL 会话管理、专属前端面板、四种 API 协议(`chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`
- **Claude Opus 4.7 全面接入**:自适应思维白名单、按百万 token 定价种子、Bedrock SKU`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`,丢弃老 `-v1` 后缀),全部聚合器 / Bedrock 预设升级为默认 Opus 模型
- **Claude `max` 推理力度**:推理下拉从 `high` 升级到 `max`
- **Gemini Native API 代理**:新增 `api_format = "gemini_native"`,代理可直达 Google `generateContent`,完整流式 / schema 转换 / shadow 请求
- **GitHub Copilot 企业版**:为 Copilot 型 Claude 供应商新增 GHES 认证与端点配置
- **Copilot 次数消耗深度优化**:转发前主动剥离 thinking 块、`tool_result` 消息归类修正、subagent 检测、`x-interaction-id` 合并计费、orphan `tool_result` 清理、默认启用 warmup 降级 —— 系统性降低 premium 交互消耗
- **会话列表虚拟化**:长会话流畅滚动,长消息默认折叠降低文字布局成本
- **Codex / OpenClaw 会话标题提取**:自动抽取有意义标题,两行显示,剥离 OpenClaw `message_id` 尾噪声
- **Usage 日期范围选择器**Today / 1d / 7d / 14d / 30d 预设 + 自定义日期时间日历;分页列表支持页码跳转输入
- **Stream Check 错误分类**:错误按类别分色 toast;默认探测模型刷新;单独识别 "model not found"
- **Local Routing 激活时阻止官方供应商切换**:官方流量走本地代理有账号暂停风险,强制拦截并 toast 警告
- **Pricing 数据库刷新(v8 → v9)**:新增 ~50 条模型条目并修正陈旧价格
- **应用级窗口控件**:可选让 CC Switch 自绘 min/max/close,显著改善 Linux Wayland 体验
- **Hermes 接入统一 Skills 管理**Skills 安装 / 启用 / 过滤现覆盖 Hermes
- **Hermes / OpenClaw 配置目录自定义**:在设置里指定 `~/.hermes/config.yaml``openclaw.json` 的自定义位置
- **从工具栏启动 Hermes Dashboard**Web UI 探测失败时,点击可在用户首选终端中启动 `hermes dashboard`
- **新合作伙伴预设**:LemonData 覆盖全部 6 个应用;DDSHub 新增 Codex 端点;StepFun Step Plan
---
## 新功能
### Hermes Agent 支持(第 6 个受管应用)
CC Switch 首次支持 Hermes Agent 作为一等受管应用,与 Claude / Codex / Gemini / OpenCode / OpenClaw 并列。
- **数据库迁移 v9 → v10**:为 `mcp_servers``skills` 表新增 `enabled_hermes` 列(`DEFAULT 0` 自动迁移,无数据丢失)
- **YAML 配置读写**`~/.hermes/config.yaml` 读写带原子备份;`tests/hermes_roundtrip.rs` 守护不损坏不相关键和 OAuth MCP `auth`
- **四种 API 协议**:与 Hermes Agent 0.10.0 对齐的 `chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`;新 deeplink 默认为 `chat_completions`
- **用户 `providers:` dict 只读呈现**:用户在 YAML 里手写的 providers 条目在 CC Switch 中以只读卡片展示,深度配置跳转到 Hermes Web UI
- **累加式切换**:与 Claude / Codex 的"覆盖式"切换不同,Hermes 所有供应商共存于同一 YAML
### Hermes Memory 面板
- 新增 Memory 面板直接编辑 `MEMORY.md` / `USER.md`,带启用开关、字符数限制和保存流
- 替换 Hermes 的 Prompts 入口
### Hermes 供应商预设(约 50 个)
- 覆盖 Nous Research、胜算云、OpenRouter、DeepSeek、Together AI、StepFun、智谱 GLM、百炼、Kimi、MiniMax、豆包、百灵、魔搭、KAT-Coder、PackyCode、Cubence、AIGoCode、RightCode、AICodeMirror、AICoding、CrazyRouter、SSSAiCode、Micu、CTok.ai、DDSHub、E-FlowCode、LionCCAPI、PIPELLM、Compshare、SiliconFlow、AiHubMix、DMXAPI、TheRouter、Novita、Nvidia、小米 MiMo
### 从工具栏启动 Hermes Dashboard
- Hermes Web UI 探测失败时,工具栏按钮改为弹出确认框,提供在用户首选终端里运行 `hermes dashboard`
- 通过临时 bash / batch 脚本启动,`hermes dashboard` 就绪后自动打开浏览器,无需轮询
- Memory 面板和 Health banner 保留原有 toast 行为
- 顺便修正了离线 toast 里过时的 `hermes web` 提示(正确命令是 `hermes dashboard`
- Linux 终端探测改为先 `which` 后 stat,提升兼容性
### Claude Opus 4.7 支持
- 新增 Claude Opus 4.7 及其自适应思维白名单、按百万 token 定价种子、Bedrock SKU`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`,丢弃老 `-v1` 后缀)
- 全部聚合器 / Bedrock 预设升级为默认 Opus 模型
### Claude `max` 推理力度
- Claude 推理下拉从 `high` 升级到 `max`,解锁更强的思考容量
### Gemini Native API 代理
- 新增 `api_format = "gemini_native"`,代理可直接转发到 Google `generateContent` API (#1918, 感谢 @yovinchen)
- 完整支持流式、schema 转换、shadow 请求
- 在 proxy providers 模块下新增 `gemini_url.rs``gemini_schema.rs``gemini_shadow.rs``streaming_gemini.rs``transform_gemini.rs`
### GitHub Copilot 企业版(GHES
- 为 Copilot 型 Claude 供应商新增 GHES 认证与端点配置 (#2175, 感谢 @hotelbe)
### 会话列表虚拟化
- 通过 `@tanstack/react-virtual` 虚拟化会话列表,上千条记录流畅滚动
- 长会话消息默认折叠,减少文字布局开销
### Codex / OpenClaw 会话标题提取
- Codex 和 OpenClaw 会话自动抽取有意义的标题,两行显示
- 剥离 OpenClaw `message_id` 后缀噪声
### Usage 日期范围选择器
- Usage 面板新增日期范围选择器,预设 TabToday / 1d / 7d / 14d / 30d+ 自定义日期 + 时间日历 (#2002, 感谢 @yovinchen)
- 分页列表新增页码跳转输入
### 模型映射快速填入
- 供应商表单的模型映射字段旁新增快速填入按钮,加快编辑 (#2179, 感谢 @lispking)
### Stream Check 错误分类
- 按类别为 Stream Check 错误上色并以 toast 呈现
- 刷新所有厂商默认探测模型到当前主力机型
- 对 "model not found" 响应做单独识别
### Local Routing 激活时阻止官方供应商切换
- 在 Local Routing 激活状态下,切换到官方供应商会被强制拦截并弹出警告 toast
- 原因:官方 API 流量经由本地代理存在账号暂停风险
### Pricing 数据库刷新(v8 → v9
- 迁移时重新种入定价表
- 新增约 50 条模型条目,覆盖 Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1
- 修正 DeepSeek、Kimi K2.5 等陈旧价格
### 应用级窗口控件
- 新增可选设置,让 CC Switch 自绘最小化 / 切换最大化 / 关闭按钮,代替系统装饰 (#1119, 感谢 @git1677967754)
- 在合成器按钮可能失灵的 Linux Wayland 上显著改善体验
### Hermes 接入统一 Skills 管理
- 统一的 Skills 界面新增 Hermes
- Skills 安装 / 启用 / 过滤现覆盖 Hermes,与 Claude / Codex / Gemini / OpenCode / OpenClaw 并列
### OpenClaw 配置目录自定义
- 新增设置项,允许把 CC Switch 指向自定义的 `openclaw.json` 位置 (#1518, 感谢 @mrFranklin)
### Hermes 配置目录自定义
- 新增设置项,允许把 CC Switch 指向自定义的 `~/.hermes/config.yaml` 位置,底层通过数据驱动 dispatch
### StepFun Step Plan 预设
- 新增 StepFun Step PlanEN / ZH)供应商预设 (#2155, 感谢 @hengm3467)
### New API 用量脚本模板
- 为 New API 用量脚本模板新增 User-Agent 头,提升上游兼容性
### LemonData 全应用预设
- LemonData 作为第三方合作伙伴预设覆盖 Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes 全部 6 个应用
- 含图标资源和 zh / en / ja 三语合作伙伴推广文案
- Claude 预设使用 `ANTHROPIC_API_KEY` 认证,OpenAI 兼容应用目标为 `gpt-5.4`
### DDSHub Codex 预设
- 新增 DDSHub 的 Codex 兼容端点(与 Claude 服务同 host
- base URL 省略 `/v1` 后缀,由网关自动路由 OpenAI SDK 路径
---
## 变更
### "Local Proxy Takeover" → "Local Routing"
- 三语 UI 文案、README、文档中全部统一重命名
- 功能行为保持不变
### Hermes `Auto` api_mode 移除
- 用户必须显式选择协议;新 deeplink 默认为 `chat_completions`
- 消除了基于 URL 的启发式识别带来的意外
### Hermes 供应商表单
- 新增 API mode 下拉和按供应商的模型编辑器
- 切换激活供应商时,把按供应商的模型绑定到顶层 `model:`
### Hermes 深度配置委托
- 深度 YAML 配置不再在 CC Switch 表单里重复,直接通过"启动 Hermes Web UI"按钮交给 Web UI
### Hermes 工具栏布局
- Web UI 按钮图标从 `ExternalLink` 换成 `LayoutDashboard` —— 点击可能启动 `hermes dashboard` 而非仅仅打开 URL,面板式图标语义更准
- MCP 移到工具栏末尾,与 Claude / Codex / Gemini / OpenCode 的布局对齐
### Claude Quick-Set 移除 `ANTHROPIC_REASONING_MODEL`
- 把推理能力和模型选择解耦,quick-set 表单不再暴露该遗留字段
### 按供应商代理配置移除
- 统一到全局的 Local Routing
- 按供应商的代理开关和存储都已移除
### 统一工具栏图标按钮宽度
- 在 Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes 面板之间规格化图标按钮宽度,表头视觉一致
### Rust Toolchain 锁定 1.95
- 全仓库采纳 clippy 1.95 建议并锁定 toolchain,防止 nightly 漂移
### 托盘菜单 ID 常量
- 托盘标识符从硬编码字符串 `"main"` 改为 `TRAY_ID` 常量(`"cc-switch"`),所有调用点同步 (#1978, 感谢 @lidaxian121)
### Copilot 次数消耗深度优化
一次系统性优化专门降低 Copilot 反向代理的 premium 交互消耗,涵盖以下多项改进:
- **转发前主动剥离 thinking 块**Anthropic 的 `thinking` / `redacted_thinking` 块会被 OpenAI 兼容端点拒绝,过去一次请求先失败消耗一次 premium 交互、再由 `thinking_rectifier` 触发重试。新增主动剥离步骤(Copilot 优化管线第 3.5 步,位于 `tool_result` 合并之后),直接省掉那一次无谓的 premium 消耗
- **请求分类修正**:含 `tool_result` 的消息归类为代理继续,而不是用户发起的新请求 —— 避免每次工具调用都被错误计入 premium 次数
- **subagent 检测**:通过 `__SUBAGENT_MARKER__``metadata._agent_` 回退识别 subagent,设置 `x-interaction-type=conversation-subagent`
- **确定性 `x-interaction-id` 合并计费**:从 session ID 推导 `x-interaction-id`,把同一会话内的多次请求合并为一次计费交互
- **Orphan `tool_result` 清理**:清理孤立的 `tool_result`,避免触发上游错误导致重试和重复计费
- **Warmup 降级默认开启**:使用 `gpt-5-mini` 作为默认降级模型
- **优化管线重排**classify → sanitize → merge → warmup,让分类看到原始 `tool_result` 语义
- 修复 `CopilotOptimizerConfig` 默认值不一致(统一到 `gpt-5-mini`
### 用量脚本内网支持
- 移除 usage script 的私网 IP / 可疑主机名屏蔽,解锁企业内网、Docker、自建 API 端点
- 内置模板仍强制 HTTPS(localhost 除外)和同源检查;自定义模板仍由用户控制,这类请求 URL 检查跳过
### Failover 队列备注
- 供应商备注现在在 failover 队列选择器和队列行中显示,方便在多供应商队列里识别 (#2138, 感谢 @Coconut-Fish)
---
## Bug 修复
### 工具栏最大化后持续折叠
- 窗口最大化 / 还原后,工具栏不再卡在折叠状态;折叠判定会随尺寸变化重新计算
### Hermes YAML 污染与 OAuth MCP `auth` 丢失
- 经 CC Switch 往返写入不再丢失 OAuth MCP `auth` 块、也不污染不相关的 YAML 键
- 新增 `tests/hermes_roundtrip.rs` 作为守护测试
### Hermes 激活供应商展示
- Hermes UI 现在正确展示激活供应商,并连通添加 / 启用 / 移除动作
### Hermes 供应商持久化
- 供应商持久化到 `custom_providers:` 下,`api_mode``model` 可跨重启 / 配置重载存活
### Hermes 健康检查错借 OpenClaw schema
- 以前 Hermes 供应商被路由到 `check_additive_app_stream`(OpenClaw 的调度器),后者读 camelCase 的 `baseUrl` / `apiKey` / `api`,导致即便 Hermes 字段全填还是报 "OpenClaw provider is missing baseUrl"
- 新增 `check_hermes_stream`,用 Hermes 专用提取器把 `api_mode``chat_completions` / `anthropic_messages` / `codex_responses`)映射到对应的 `check_claude_stream` `api_format``bedrock_converse` 明确标记为不支持
- 先解析 `api_mode` 再抽 URL / API key,让 `bedrock_converse` 用户看到真实原因,而不是误导性的 "missing base_url"
### Usage 查询模态框支持 Hermes / OpenClaw
- `getProviderCredentials` 新增对 Hermessnake_case `base_url` / `api_key`)和 OpenClawcamelCase `baseUrl` / `apiKey`)的扁平 `settingsConfig` 字段读取,让 SiliconFlow 等匹配供应商自动选中 "official balance" 模板
- 重构 BALANCE 和 TOKEN_PLAN 测试路径复用 `providerCredentials`,不再直接读 `env.ANTHROPIC_*`,修正了非 Claude 应用即使配置了 key 也报 "empty key" 的问题
### Codex `cache_control` 保留
- 在 Codex 格式转换合并 system prompt 时保留 `cache_control` (#1946, 感谢 @yovinchen)
### Claude prompt cache key 泄漏
- Claude chat 转换时不再发送 prompt cache key (#2003, 感谢 @yovinchen)
### 代理逐跳响应头剥离
- 按 RFC 7230 剥离代理响应的 hop-by-hop 头(Connection、Keep-Alive、Transfer-Encoding 等) (#2060, 感谢 @yovinchen)
### 代理 CORS 层移除
- 移除代理中过于宽松的 CORS 层 (#1915, 感谢 @zerone0x)
### 代理 toast 显示后端错误详情
- 代理相关 toast 现在展示后端错误 payload 的详情,而不是一句笼统的失败
### Usage 日志去重
- 代理和会话日志的用量记录去重,相同请求不再被重复计数
- 请求日志时间范围与面板的 1d / 7d / 30d 选择器同步
### Common Config 勾选持久化
- Claude / Codex / Gemini common-config 勾选状态重开后正确保留 (#2191, 感谢 @zxZeng)
### Claude 插件 `settings.json` 同步
- 编辑当前供应商时,会同步回 Claude 插件路径下的 `settings.json` (#1905, 感谢 @chengww5217)
### Google Official Gemini env 保留
- 保存 Google Official Gemini 供应商时不再清空 `env`
### OpenCode JSON5 尾逗号解析
- OpenCode 配置读取容忍尾逗号(JSON5) (#2023, 感谢 @wwminger)
### 预设刷新
- 刷新 DeepSeek 和 Claude 1M 的陈旧 context 窗口
- 刷新陈旧模型 ID,回填 Hermes 模型列表
- 修正 Nous 端点,Hermes 占位图替换为 Nous 品牌图
- 移除未使用的官方 Hermes 预设
### 搜索命中时折叠消息自动展开
- 搜索匹配落在折叠内容内部时,消息自动展开以定位匹配
### 未知订阅配额等级隐藏
- 供应商卡片不再渲染未知订阅配额等级
### weekly_limit 标签统一
- 跨语言把 `weekly_limit` 等级标签对齐到官方的"7 天"命名
### 根级 Skill 仓库安装
- 修复当仓库根本身就是一个 skill 时的安装失败
### Session ID 解析 clippy
- 移除 session ID 解析里的冗余闭包(clippy 警告)
### Stream Check 默认探测模型刷新
- 默认探测模型更新到每家厂商当前主力
### Skills 导入同步
- 导入的 Skills 即时同步到启用应用目录,不再仅记录在数据库里导致 UI 显示"已安装"但目标目录空缺 (#2101, 感谢 @yaoguohh)
### Ghostty 会话恢复
- 改为通过 shell 执行 + `--working-directory` 启动 Ghostty 会话恢复 (#1976, 感谢 @Suda202)
- 避免路径含空格 / 特殊字符时 `cwd` 转义问题
---
## 文档
### README 赞助商更新
- SiliconFlow 注册赠送更新为 ¥16
- 精简 SSSAiCode 赞助文案
- 更新合作伙伴 logo
- 新增 LemonData 赞助商
### 全局代理提示澄清
- 三语澄清全局代理与 Local Routing 的关系
### Takeover → Routing 文档重命名
- 接管相关文档在三语下重命名为 routing,同步更新锚点
### PIPELLM 网站 URL
- PIPELLM 赞助商网站 URL 更新为 `code.pipellm.ai`
---
## ⚠️ 重要变更(Breaking
### Hermes 必须显式 `api_mode`
- `Auto` 模式移除;导入或 deeplink 得到的供应商默认落到 `chat_completions`
- 既有 `Auto` 配置的用户会被提示选择协议
### Claude Quick-Set 移除 `ANTHROPIC_REASONING_MODEL`
- 该遗留字段不再暴露;既有设置自动清理
### 按供应商代理配置移除
- 迁移到全局 Local Routing 设置
- 既有按供应商代理值被忽略
### 数据库 schema v9 → v10
-`mcp_servers``skills` 表新增 `enabled_hermes`
- 自动迁移,`DEFAULT 0`,无数据丢失
### Pricing 表 v8 → v9 重置
- 首次启动时 `model_pricing` 表被清空并重新种入,以应用新模型和修正后的价格
### XCodeAPI 预设移除
- 使用 XCodeAPI 预设的用户请迁移到其它供应商
---
## ⚠️ 风险提示
本版本在涉及反向代理类功能上沿用 v3.12.3 / v3.13.0 提出的风险提示。
**GitHub Copilot 反向代理**:使用 Copilot 的反代路径可能违反 GitHub / Microsoft 服务条款。详情见 [v3.12.3 release notes](v3.12.3-zh.md#-风险提示)。
**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#-风险提示)。
用户启用上述功能即表示**自行承担所有风险**。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
---
## 下载与安装
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
### 系统要求
| 系统 | 最低版本 | 架构 |
| ------- | -------------------------- | ----------------------------------- |
| Windows | Windows 10 及以上 | x64 |
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 见下表 | x64 |
### Windows
| 文件 | 说明 |
| ---------------------------------------- | ----------------------------------- |
| `CC-Switch-v3.14.0-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
| `CC-Switch-v3.14.0-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
### macOS
| 文件 | 说明 |
| -------------------------------- | --------------------------------------------- |
| `CC-Switch-v3.14.0-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
| `CC-Switch-v3.14.0-macOS.zip` | 解压后拖入 ApplicationsUniversal Binary |
| `CC-Switch-v3.14.0-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
> macOS 版本已通过 Apple 代码签名和公证,可直接安装使用。
### HomebrewmacOS
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
| 发行版 | 推荐格式 | 安装方式 |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb``sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm``sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+1 -1
View File
@@ -509,7 +509,7 @@ When editing Claude providers, a set of **quick toggles** is available above the
| **Hide Attribution** | Clears commit/PR attribution metadata | Sets `attribution: {commit: "", pr: ""}` |
| **Enable Teammates** | Enables the agent teams feature | Sets `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1"` |
| **Enable Tool Search** | Enables tool search functionality | Sets `env.ENABLE_TOOL_SEARCH = "true"` |
| **Max Effort** | Sets effort level to max | Sets `effortLevel = "max"` |
| **High Effort** | Sets effort level to high | Sets `effortLevel = "high"` |
| **Disable Auto Upgrade** | Prevents Claude Code auto-updates | Sets `env.DISABLE_AUTOUPDATER = "1"` |
When a toggle is unchecked, its corresponding config entry is removed entirely. Changes are reflected in the JSON editor in real-time.
+1 -1
View File
@@ -509,7 +509,7 @@ Claude プロバイダーの編集時、JSON エディタの上部に **クイ
| **帰属情報を非表示** | コミット/PR の帰属メタデータをクリア | `attribution: {commit: "", pr: ""}` を設定 |
| **チームメイトを有効化** | エージェントチーム機能を有効化 | `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1"` を設定 |
| **ツール検索を有効化** | ツール検索機能を有効化 | `env.ENABLE_TOOL_SEARCH = "true"` を設定 |
| **最大強度思考** | エフォートレベルを max に設定 | `effortLevel = "max"` を設定 |
| **高強度** | エフォートレベルをに設定 | `effortLevel = "high"` を設定 |
| **自動アップグレードを無効化** | Claude Code の自動更新を防止 | `env.DISABLE_AUTOUPDATER = "1"` を設定 |
トグルのチェックを外すと、対応する設定エントリが完全に削除されます。変更は JSON エディタにリアルタイムで反映されます。
+1 -1
View File
@@ -509,7 +509,7 @@ v3.13.0 起新增的高级选项。默认情况下,CC Switch 会把配置的 `
| **隐藏署名** | 清除提交/PR 的署名元数据 | 设置 `attribution: {commit: "", pr: ""}` |
| **启用 Teammates** | 启用 Agent 团队功能 | 设置 `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1"` |
| **启用工具搜索** | 启用工具搜索功能 | 设置 `env.ENABLE_TOOL_SEARCH = "true"` |
| **最大强度思考** | 将 effort 级别设为 max | 设置 `effortLevel = "max"` |
| **高效能模式** | 将 effort 级别设为 high | 设置 `effortLevel = "high"` |
| **禁用自动更新** | 阻止 Claude Code 自动更新 | 设置 `env.DISABLE_AUTOUPDATER = "1"` |
取消勾选开关时,对应的配置项会被完全移除。更改会实时反映在 JSON 编辑器中。
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cc-switch",
"version": "3.14.0",
"version": "3.13.0",
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
"type": "module",
"scripts": {
-4
View File
@@ -1,4 +0,0 @@
[toolchain]
channel = "1.95"
components = ["rustfmt", "clippy"]
profile = "minimal"
+1 -1
View File
@@ -735,7 +735,7 @@ dependencies = [
[[package]]
name = "cc-switch"
version = "3.14.0"
version = "3.13.0"
dependencies = [
"anyhow",
"arboard",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "cc-switch"
version = "3.14.0"
version = "3.13.0"
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
authors = ["Jason Young"]
license = "MIT"
+6 -46
View File
@@ -15,8 +15,6 @@ pub struct McpApps {
pub gemini: bool,
#[serde(default)]
pub opencode: bool,
#[serde(default)]
pub hermes: bool,
}
impl McpApps {
@@ -28,7 +26,6 @@ impl McpApps {
AppType::Gemini => self.gemini,
AppType::OpenCode => self.opencode,
AppType::OpenClaw => false, // OpenClaw doesn't support MCP
AppType::Hermes => self.hermes,
}
}
@@ -40,7 +37,6 @@ impl McpApps {
AppType::Gemini => self.gemini = enabled,
AppType::OpenCode => self.opencode = enabled,
AppType::OpenClaw => {} // OpenClaw doesn't support MCP, ignore
AppType::Hermes => self.hermes = enabled,
}
}
@@ -59,15 +55,12 @@ impl McpApps {
if self.opencode {
apps.push(AppType::OpenCode);
}
if self.hermes {
apps.push(AppType::Hermes);
}
apps
}
/// 检查是否所有应用都未启用
pub fn is_empty(&self) -> bool {
!self.claude && !self.codex && !self.gemini && !self.opencode && !self.hermes
!self.claude && !self.codex && !self.gemini && !self.opencode
}
}
@@ -82,8 +75,6 @@ pub struct SkillApps {
pub gemini: bool,
#[serde(default)]
pub opencode: bool,
#[serde(default)]
pub hermes: bool,
}
impl SkillApps {
@@ -94,7 +85,6 @@ impl SkillApps {
AppType::Codex => self.codex,
AppType::Gemini => self.gemini,
AppType::OpenCode => self.opencode,
AppType::Hermes => self.hermes,
AppType::OpenClaw => false, // OpenClaw doesn't support Skills
}
}
@@ -106,7 +96,6 @@ impl SkillApps {
AppType::Codex => self.codex = enabled,
AppType::Gemini => self.gemini = enabled,
AppType::OpenCode => self.opencode = enabled,
AppType::Hermes => self.hermes = enabled,
AppType::OpenClaw => {} // OpenClaw doesn't support Skills, ignore
}
}
@@ -126,15 +115,12 @@ impl SkillApps {
if self.opencode {
apps.push(AppType::OpenCode);
}
if self.hermes {
apps.push(AppType::Hermes);
}
apps
}
/// 检查是否所有应用都未启用
pub fn is_empty(&self) -> bool {
!self.claude && !self.codex && !self.gemini && !self.opencode && !self.hermes
!self.claude && !self.codex && !self.gemini && !self.opencode
}
/// 仅启用指定应用(其他应用设为禁用)
@@ -265,9 +251,6 @@ pub struct McpRoot {
/// OpenClaw MCP 配置(v4.1.0+,实际使用 openclaw.json
#[serde(default, skip_serializing_if = "McpConfig::is_empty")]
pub openclaw: McpConfig,
/// Hermes MCP 配置(实际使用 config.yaml
#[serde(default, skip_serializing_if = "McpConfig::is_empty")]
pub hermes: McpConfig,
}
impl Default for McpRoot {
@@ -281,7 +264,6 @@ impl Default for McpRoot {
gemini: McpConfig::default(),
opencode: McpConfig::default(),
openclaw: McpConfig::default(),
hermes: McpConfig::default(),
}
}
}
@@ -306,8 +288,6 @@ pub struct PromptRoot {
pub opencode: PromptConfig,
#[serde(default)]
pub openclaw: PromptConfig,
#[serde(default)]
pub hermes: PromptConfig,
}
use crate::config::{copy_file, get_app_config_dir, get_app_config_path, write_json_file};
@@ -324,7 +304,6 @@ pub enum AppType {
Gemini,
OpenCode,
OpenClaw,
Hermes,
}
impl AppType {
@@ -335,19 +314,15 @@ impl AppType {
AppType::Gemini => "gemini",
AppType::OpenCode => "opencode",
AppType::OpenClaw => "openclaw",
AppType::Hermes => "hermes",
}
}
/// Check if this app uses additive mode
///
/// - Switch mode (false): Only the current provider is written to live config (Claude, Codex, Gemini)
/// - Additive mode (true): All providers are written to live config (OpenCode, OpenClaw, Hermes)
/// - Additive mode (true): All providers are written to live config (OpenCode, OpenClaw)
pub fn is_additive_mode(&self) -> bool {
matches!(
self,
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes
)
matches!(self, AppType::OpenCode | AppType::OpenClaw)
}
/// Return an iterator over all app types
@@ -358,7 +333,6 @@ impl AppType {
AppType::Gemini,
AppType::OpenCode,
AppType::OpenClaw,
AppType::Hermes,
]
.into_iter()
}
@@ -375,11 +349,10 @@ impl FromStr for AppType {
"gemini" => Ok(AppType::Gemini),
"opencode" => Ok(AppType::OpenCode),
"openclaw" => Ok(AppType::OpenClaw),
"hermes" => Ok(AppType::Hermes),
other => Err(AppError::localized(
"unsupported_app",
format!("不支持的应用标识: '{other}'。可选值: claude, codex, gemini, opencode, openclaw, hermes"),
format!("Unsupported app id: '{other}'. Allowed: claude, codex, gemini, opencode, openclaw, hermes."),
format!("不支持的应用标识: '{other}'。可选值: claude, codex, gemini, opencode, openclaw。"),
format!("Unsupported app id: '{other}'. Allowed: claude, codex, gemini, opencode, openclaw."),
)),
}
}
@@ -402,9 +375,6 @@ pub struct CommonConfigSnippets {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub openclaw: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hermes: Option<String>,
}
impl CommonConfigSnippets {
@@ -416,7 +386,6 @@ impl CommonConfigSnippets {
AppType::Gemini => self.gemini.as_ref(),
AppType::OpenCode => self.opencode.as_ref(),
AppType::OpenClaw => self.openclaw.as_ref(),
AppType::Hermes => self.hermes.as_ref(),
}
}
@@ -428,7 +397,6 @@ impl CommonConfigSnippets {
AppType::Gemini => self.gemini = snippet,
AppType::OpenCode => self.opencode = snippet,
AppType::OpenClaw => self.openclaw = snippet,
AppType::Hermes => self.hermes = snippet,
}
}
}
@@ -470,7 +438,6 @@ impl Default for MultiAppConfig {
apps.insert("gemini".to_string(), ProviderManager::default());
apps.insert("opencode".to_string(), ProviderManager::default());
apps.insert("openclaw".to_string(), ProviderManager::default());
apps.insert("hermes".to_string(), ProviderManager::default());
Self {
version: 2,
@@ -631,7 +598,6 @@ impl MultiAppConfig {
AppType::Gemini => &self.mcp.gemini,
AppType::OpenCode => &self.mcp.opencode,
AppType::OpenClaw => &self.mcp.openclaw,
AppType::Hermes => &self.mcp.hermes,
}
}
@@ -643,7 +609,6 @@ impl MultiAppConfig {
AppType::Gemini => &mut self.mcp.gemini,
AppType::OpenCode => &mut self.mcp.opencode,
AppType::OpenClaw => &mut self.mcp.openclaw,
AppType::Hermes => &mut self.mcp.hermes,
}
}
@@ -659,7 +624,6 @@ impl MultiAppConfig {
Self::auto_import_prompt_if_exists(&mut config, AppType::Gemini)?;
Self::auto_import_prompt_if_exists(&mut config, AppType::OpenCode)?;
Self::auto_import_prompt_if_exists(&mut config, AppType::OpenClaw)?;
Self::auto_import_prompt_if_exists(&mut config, AppType::Hermes)?;
Ok(config)
}
@@ -681,7 +645,6 @@ impl MultiAppConfig {
|| !self.prompts.gemini.prompts.is_empty()
|| !self.prompts.opencode.prompts.is_empty()
|| !self.prompts.openclaw.prompts.is_empty()
|| !self.prompts.hermes.prompts.is_empty()
{
return Ok(false);
}
@@ -695,7 +658,6 @@ impl MultiAppConfig {
AppType::Gemini,
AppType::OpenCode,
AppType::OpenClaw,
AppType::Hermes,
] {
// 复用已有的单应用导入逻辑
if Self::auto_import_prompt_if_exists(self, app)? {
@@ -767,7 +729,6 @@ impl MultiAppConfig {
AppType::Gemini => &mut config.prompts.gemini.prompts,
AppType::OpenCode => &mut config.prompts.opencode.prompts,
AppType::OpenClaw => &mut config.prompts.openclaw.prompts,
AppType::Hermes => &mut config.prompts.hermes.prompts,
};
prompts.insert(id, prompt);
@@ -808,7 +769,6 @@ impl MultiAppConfig {
AppType::Gemini => &self.mcp.gemini.servers,
AppType::OpenCode => &self.mcp.opencode.servers,
AppType::OpenClaw => continue, // OpenClaw MCP is still in development, skip
AppType::Hermes => continue, // Hermes didn't exist in v3.6.x, skip
};
for (id, entry) in old_servers {
+2 -9
View File
@@ -18,7 +18,6 @@ pub struct ManagedAuthAccount {
pub avatar_url: Option<String>,
pub authenticated_at: i64,
pub is_default: bool,
pub github_domain: String,
}
#[derive(Debug, Clone, serde::Serialize)]
@@ -60,7 +59,6 @@ fn map_account(
login: account.login,
avatar_url: account.avatar_url,
authenticated_at: account.authenticated_at,
github_domain: account.github_domain,
}
}
@@ -81,7 +79,6 @@ fn map_device_code_response(
#[tauri::command(rename_all = "camelCase")]
pub async fn auth_start_login(
auth_provider: String,
github_domain: Option<String>,
copilot_state: State<'_, CopilotAuthState>,
codex_state: State<'_, CodexOAuthState>,
) -> Result<ManagedAuthDeviceCodeResponse, String> {
@@ -90,7 +87,7 @@ pub async fn auth_start_login(
AUTH_PROVIDER_GITHUB_COPILOT => {
let auth_manager = copilot_state.0.read().await;
let response = auth_manager
.start_device_flow(github_domain.as_deref())
.start_device_flow()
.await
.map_err(|e| e.to_string())?;
Ok(map_device_code_response(auth_provider, response))
@@ -111,7 +108,6 @@ pub async fn auth_start_login(
pub async fn auth_poll_for_account(
auth_provider: String,
device_code: String,
github_domain: Option<String>,
copilot_state: State<'_, CopilotAuthState>,
codex_state: State<'_, CodexOAuthState>,
) -> Result<Option<ManagedAuthAccount>, String> {
@@ -119,10 +115,7 @@ pub async fn auth_poll_for_account(
match auth_provider {
AUTH_PROVIDER_GITHUB_COPILOT => {
let auth_manager = copilot_state.0.write().await;
match auth_manager
.poll_for_token(&device_code, github_domain.as_deref())
.await
{
match auth_manager.poll_for_token(&device_code).await {
Ok(account) => {
let default_account_id = auth_manager.get_status().await.default_account_id;
Ok(account.map(|account| {
-11
View File
@@ -101,15 +101,6 @@ pub async fn get_config_status(app: String) -> Result<ConfigStatus, String> {
Ok(ConfigStatus { exists, path })
}
AppType::Hermes => {
let config_path = crate::hermes_config::get_hermes_config_path();
let exists = config_path.exists();
let path = crate::hermes_config::get_hermes_dir()
.to_string_lossy()
.to_string();
Ok(ConfigStatus { exists, path })
}
}
}
@@ -126,7 +117,6 @@ pub async fn get_config_dir(app: String) -> Result<String, String> {
AppType::Gemini => crate::gemini_config::get_gemini_dir(),
AppType::OpenCode => crate::opencode_config::get_opencode_dir(),
AppType::OpenClaw => crate::openclaw_config::get_openclaw_dir(),
AppType::Hermes => crate::hermes_config::get_hermes_dir(),
};
Ok(dir.to_string_lossy().to_string())
@@ -140,7 +130,6 @@ pub async fn open_config_folder(handle: AppHandle, app: String) -> Result<bool,
AppType::Gemini => crate::gemini_config::get_gemini_dir(),
AppType::OpenCode => crate::opencode_config::get_opencode_dir(),
AppType::OpenClaw => crate::openclaw_config::get_openclaw_dir(),
AppType::Hermes => crate::hermes_config::get_hermes_dir(),
};
if !config_dir.exists() {
+3 -12
View File
@@ -20,12 +20,11 @@ pub struct CopilotAuthState(pub Arc<RwLock<CopilotAuthManager>>);
/// 返回设备码和用户码,用于 OAuth 认证
#[tauri::command]
pub async fn copilot_start_device_flow(
github_domain: Option<String>,
state: State<'_, CopilotAuthState>,
) -> Result<GitHubDeviceCodeResponse, String> {
let auth_manager = state.0.read().await;
auth_manager
.start_device_flow(github_domain.as_deref())
.start_device_flow()
.await
.map_err(|e| e.to_string())
}
@@ -37,14 +36,10 @@ pub async fn copilot_start_device_flow(
#[tauri::command(rename_all = "camelCase")]
pub async fn copilot_poll_for_auth(
device_code: String,
github_domain: Option<String>,
state: State<'_, CopilotAuthState>,
) -> Result<bool, String> {
let auth_manager = state.0.write().await;
match auth_manager
.poll_for_token(&device_code, github_domain.as_deref())
.await
{
match auth_manager.poll_for_token(&device_code).await {
Ok(Some(_account)) => {
log::info!("[CopilotAuth] 用户已授权");
Ok(true)
@@ -66,14 +61,10 @@ pub async fn copilot_poll_for_auth(
#[tauri::command(rename_all = "camelCase")]
pub async fn copilot_poll_for_account(
device_code: String,
github_domain: Option<String>,
state: State<'_, CopilotAuthState>,
) -> Result<Option<GitHubAccount>, String> {
let auth_manager = state.0.write().await;
match auth_manager
.poll_for_token(&device_code, github_domain.as_deref())
.await
{
match auth_manager.poll_for_token(&device_code).await {
Ok(account) => Ok(account),
Err(crate::proxy::providers::copilot_auth::CopilotAuthError::AuthorizationPending) => {
Ok(None)
+1 -1
View File
@@ -162,7 +162,7 @@ pub async fn set_auto_failover_enabled(
// 刷新托盘菜单,确保状态同步
if let Ok(new_menu) = crate::tray::create_tray_menu(&app, &state) {
if let Some(tray) = app.tray_by_id(crate::tray::TRAY_ID) {
if let Some(tray) = app.tray_by_id("main") {
let _ = tray.set_menu(Some(new_menu));
}
}
-149
View File
@@ -1,149 +0,0 @@
use std::time::Duration;
use tauri::{AppHandle, State};
use tauri_plugin_opener::OpenerExt;
use crate::hermes_config;
use crate::store::AppState;
/// Error string returned when `open_hermes_web_ui` cannot reach the Hermes
/// FastAPI server. Kept in sync with the `HERMES_WEB_OFFLINE_ERROR` constant
/// in `src/hooks/useHermes.ts` so the frontend can branch on it.
const HERMES_WEB_OFFLINE_ERROR: &str = "hermes_web_offline";
// ============================================================================
// Hermes Provider Commands
// ============================================================================
/// Import providers from Hermes live config to database.
///
/// Hermes uses additive mode — users may already have providers
/// configured in config.yaml.
#[tauri::command]
pub fn import_hermes_providers_from_live(state: State<'_, AppState>) -> Result<usize, String> {
crate::services::provider::import_hermes_providers_from_live(state.inner())
.map_err(|e| e.to_string())
}
/// Get provider names in the Hermes live config.
#[tauri::command]
pub fn get_hermes_live_provider_ids() -> Result<Vec<String>, String> {
hermes_config::get_providers()
.map(|providers| providers.keys().cloned().collect())
.map_err(|e| e.to_string())
}
/// Get a single Hermes provider fragment from live config.
#[tauri::command]
pub fn get_hermes_live_provider(
#[allow(non_snake_case)] providerId: String,
) -> Result<Option<serde_json::Value>, String> {
hermes_config::get_provider(&providerId).map_err(|e| e.to_string())
}
/// Scan config.yaml for known configuration hazards.
#[tauri::command]
pub fn scan_hermes_config_health() -> Result<Vec<hermes_config::HermesHealthWarning>, String> {
hermes_config::scan_hermes_config_health().map_err(|e| e.to_string())
}
// ============================================================================
// Model Configuration Commands
// ============================================================================
/// Get Hermes model config (model section of config.yaml). Read-only — writes
/// happen implicitly through `apply_switch_defaults` when switching providers.
#[tauri::command]
pub fn get_hermes_model_config() -> Result<Option<hermes_config::HermesModelConfig>, String> {
hermes_config::get_model_config().map_err(|e| e.to_string())
}
// ============================================================================
// Memory Files Commands
// ============================================================================
#[tauri::command]
pub fn get_hermes_memory(kind: hermes_config::MemoryKind) -> Result<String, String> {
hermes_config::read_memory(kind).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn set_hermes_memory(kind: hermes_config::MemoryKind, content: String) -> Result<(), String> {
hermes_config::write_memory(kind, &content).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn get_hermes_memory_limits() -> Result<hermes_config::HermesMemoryLimits, String> {
hermes_config::read_memory_limits().map_err(|e| e.to_string())
}
#[tauri::command]
pub fn set_hermes_memory_enabled(
kind: hermes_config::MemoryKind,
enabled: bool,
) -> Result<hermes_config::HermesWriteOutcome, String> {
hermes_config::set_memory_enabled(kind, enabled).map_err(|e| e.to_string())
}
// ============================================================================
// Hermes Web UI launcher
// ============================================================================
/// Probe the local Hermes Web UI (FastAPI) and open it in the system browser.
///
/// Port discovery priority:
/// 1. `HERMES_WEB_PORT` environment variable
/// 2. Default 9119
///
/// Hermes wraps all `/api/*` routes in a Bearer-token middleware, so a GET
/// against `/api/status` returning **either 200 or 401** confirms the server
/// is live. The session token lives only in the Hermes process memory and is
/// injected into the returned HTML via `window.__HERMES_SESSION_TOKEN__`, so
/// there is no need (and no way) for CC Switch to inject it — we just open
/// the URL and let Hermes handle auth.
#[tauri::command]
pub async fn open_hermes_web_ui(app: AppHandle, path: Option<String>) -> Result<(), String> {
let port = std::env::var("HERMES_WEB_PORT")
.ok()
.and_then(|raw| raw.trim().parse::<u16>().ok())
.unwrap_or(9119);
let base = format!("http://127.0.0.1:{port}");
// Probe /api/status with a short timeout. Hermes returns 200 when open or
// 401 when the session token is required — either way the server is live.
// Only a connection error / timeout means the server isn't running.
let probe_url = format!("{base}/api/status");
let client = reqwest::Client::builder()
.timeout(Duration::from_millis(1200))
.no_proxy()
.build()
.map_err(|e| format!("failed to build probe client: {e}"))?;
match client.get(&probe_url).send().await {
Ok(_) => {}
Err(_) => return Err(HERMES_WEB_OFFLINE_ERROR.to_string()),
}
let target = match path.as_deref() {
Some(p) if p.starts_with('/') => format!("{base}{p}"),
Some(p) if !p.is_empty() => format!("{base}/{p}"),
_ => format!("{base}/"),
};
app.opener()
.open_url(&target, None::<String>)
.map_err(|e| format!("failed to open Hermes Web UI: {e}"))
}
/// Open the preferred terminal and run `hermes dashboard`. Non-blocking —
/// callers should reinvoke `open_hermes_web_ui` once the server is ready,
/// since Hermes startup can take several seconds and may fail outright if
/// the `hermes-agent[web]` extras are missing.
#[tauri::command]
pub async fn launch_hermes_dashboard() -> Result<(), String> {
tokio::task::spawn_blocking(|| {
crate::commands::misc::launch_terminal_running("hermes dashboard", "hermes_dashboard")
})
.await
.map_err(|e| format!("launch task join error: {e}"))?
}
-1
View File
@@ -202,6 +202,5 @@ pub async fn import_mcp_from_apps(state: State<'_, AppState>) -> Result<usize, S
total += McpService::import_from_codex(&state).unwrap_or(0);
total += McpService::import_from_gemini(&state).unwrap_or(0);
total += McpService::import_from_opencode(&state).unwrap_or(0);
total += McpService::import_from_hermes(&state).unwrap_or(0);
Ok(total)
}
-182
View File
@@ -1310,188 +1310,6 @@ fn run_windows_start_command(args: &[&str], terminal_name: &str) -> Result<(), S
Ok(())
}
/// 打开用户首选终端并在其中执行一条命令行。脚本尾部 `read -n 1` / `pause`
/// 是刻意设计的——让命令退出后窗口不要瞬间关闭,用户才看得到 `command
/// not found` / `ModuleNotFoundError` 这类诊断信息。
///
/// **Security**`command_line` 会被原样拼进 shell/batch 脚本,调用方必须
/// 保证它是可信字符串(当前只由后端硬编码调用)。
pub(crate) fn launch_terminal_running(command_line: &str, label: &str) -> Result<(), String> {
let temp_dir = std::env::temp_dir();
let pid = std::process::id();
#[cfg(any(target_os = "macos", target_os = "linux"))]
let (script_file, script_content) = {
let file = temp_dir.join(format!("cc_switch_{}_{}.sh", label, pid));
let content = format!(
r#"#!/bin/bash
trap 'rm -f "{script_path}"' EXIT
echo "[cc-switch] Starting: {cmd}"
echo ""
{cmd}
echo ""
echo "[cc-switch] Command exited. Press any key to close."
read -n 1 -s
"#,
script_path = file.display(),
cmd = command_line,
);
(file, content)
};
#[cfg(target_os = "macos")]
{
use std::os::unix::fs::PermissionsExt;
std::fs::write(&script_file, &script_content)
.map_err(|e| format!("写入启动脚本失败: {e}"))?;
std::fs::set_permissions(&script_file, std::fs::Permissions::from_mode(0o755))
.map_err(|e| format!("设置脚本权限失败: {e}"))?;
let preferred = crate::settings::get_preferred_terminal();
let terminal = preferred.as_deref().unwrap_or("terminal");
let result = match terminal {
"iterm2" => launch_macos_iterm2(&script_file),
"alacritty" => launch_macos_open_app("Alacritty", &script_file, true),
"kitty" => launch_macos_open_app("kitty", &script_file, false),
"ghostty" => launch_macos_open_app("Ghostty", &script_file, true),
"wezterm" => launch_macos_open_app("WezTerm", &script_file, true),
"kaku" => launch_macos_open_app("Kaku", &script_file, true),
_ => launch_macos_terminal_app(&script_file),
};
if result.is_err() && terminal != "terminal" {
log::warn!(
"首选终端 {} 启动失败,回退到 Terminal.app: {:?}",
terminal,
result.as_ref().err()
);
return launch_macos_terminal_app(&script_file);
}
result
}
#[cfg(target_os = "linux")]
{
use std::os::unix::fs::PermissionsExt;
use std::process::Command;
std::fs::write(&script_file, &script_content)
.map_err(|e| format!("写入启动脚本失败: {e}"))?;
std::fs::set_permissions(&script_file, std::fs::Permissions::from_mode(0o755))
.map_err(|e| format!("设置脚本权限失败: {e}"))?;
let preferred = crate::settings::get_preferred_terminal();
let default_terminals = [
("gnome-terminal", vec!["--"]),
("konsole", vec!["-e"]),
("xfce4-terminal", vec!["-e"]),
("mate-terminal", vec!["--"]),
("lxterminal", vec!["-e"]),
("alacritty", vec!["-e"]),
("kitty", vec!["-e"]),
("ghostty", vec!["-e"]),
];
let terminals_to_try: Vec<(&str, Vec<&str>)> = if let Some(ref pref) = preferred {
let pref_args = default_terminals
.iter()
.find(|(name, _)| *name == pref.as_str())
.map(|(_, args)| args.to_vec())
.unwrap_or_else(|| vec!["-e"]);
let mut list = vec![(pref.as_str(), pref_args)];
for (name, args) in &default_terminals {
if *name != pref.as_str() {
list.push((*name, args.to_vec()));
}
}
list
} else {
default_terminals
.iter()
.map(|(name, args)| (*name, args.to_vec()))
.collect()
};
let mut last_error = String::from("未找到可用的终端");
for (terminal, args) in terminals_to_try {
let terminal_exists = which_command(terminal)
|| ["/usr/bin", "/bin", "/usr/local/bin"]
.iter()
.any(|dir| std::path::Path::new(&format!("{}/{}", dir, terminal)).exists());
if terminal_exists {
let spawn_result = Command::new(terminal)
.args(&args)
.arg("bash")
.arg(script_file.to_string_lossy().as_ref())
.spawn();
match spawn_result {
Ok(_) => return Ok(()),
Err(e) => {
last_error = format!("执行 {} 失败: {}", terminal, e);
}
}
}
}
let _ = std::fs::remove_file(&script_file);
Err(last_error)
}
#[cfg(target_os = "windows")]
{
let preferred = crate::settings::get_preferred_terminal();
let terminal = preferred.as_deref().unwrap_or("cmd");
let bat_file = temp_dir.join(format!("cc_switch_{}_{}.bat", label, pid));
let content = format!(
"@echo off\r\necho [cc-switch] Starting: {cmd}\r\necho.\r\n{cmd}\r\necho.\r\necho [cc-switch] Command exited. Press any key to close.\r\npause >nul\r\ndel \"%~f0\" >nul 2>&1\r\n",
cmd = command_line,
);
std::fs::write(&bat_file, &content).map_err(|e| format!("写入批处理文件失败: {e}"))?;
let bat_path = bat_file.to_string_lossy();
let ps_cmd = format!("& '{}'", bat_path);
let result = match terminal {
"powershell" => run_windows_start_command(
&["powershell", "-NoExit", "-Command", &ps_cmd],
"PowerShell",
),
"wt" => run_windows_start_command(&["wt", "cmd", "/K", &bat_path], "Windows Terminal"),
_ => run_windows_start_command(&["cmd", "/K", &bat_path], "cmd"),
};
let final_result = if result.is_err() && terminal != "cmd" {
log::warn!(
"首选终端 {} 启动失败,回退到 cmd: {:?}",
terminal,
result.as_ref().err()
);
run_windows_start_command(&["cmd", "/K", &bat_path], "cmd")
} else {
result
};
// The .bat self-deletes (`del "%~f0"`) after it runs, but that only
// fires if *some* terminal actually launched it. If every attempt
// failed, sweep the temp file ourselves to avoid pollution.
if final_result.is_err() {
let _ = std::fs::remove_file(&bat_file);
}
final_result
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
{
let _ = (temp_dir, pid, command_line, label);
Err("不支持的操作系统".to_string())
}
}
/// 设置窗口主题(Windows/macOS 标题栏颜色)
/// theme: "dark" | "light" | "system"
#[tauri::command]
-2
View File
@@ -10,7 +10,6 @@ mod deeplink;
mod env;
mod failover;
mod global_proxy;
mod hermes;
mod import_export;
mod mcp;
mod misc;
@@ -43,7 +42,6 @@ pub use deeplink::*;
pub use env::*;
pub use failover::*;
pub use global_proxy::*;
pub use hermes::*;
pub use import_export::*;
pub use mcp::*;
pub use misc::*;
-1
View File
@@ -25,7 +25,6 @@ fn parse_app_type(app: &str) -> Result<AppType, String> {
"codex" => Ok(AppType::Codex),
"gemini" => Ok(AppType::Gemini),
"opencode" => Ok(AppType::OpenCode),
"hermes" => Ok(AppType::Hermes),
_ => Err(format!("不支持的 app 类型: {app}")),
}
}
+2 -10
View File
@@ -35,26 +35,18 @@ pub fn get_usage_trends(
#[tauri::command]
pub fn get_provider_stats(
state: State<'_, AppState>,
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<String>,
) -> Result<Vec<ProviderStats>, AppError> {
state
.db
.get_provider_stats(start_date, end_date, app_type.as_deref())
state.db.get_provider_stats(app_type.as_deref())
}
/// 获取模型统计
#[tauri::command]
pub fn get_model_stats(
state: State<'_, AppState>,
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<String>,
) -> Result<Vec<ModelStats>, AppError> {
state
.db
.get_model_stats(start_date, end_date, app_type.as_deref())
state.db.get_model_stats(app_type.as_deref())
}
/// 获取请求日志列表
+1 -4
View File
@@ -14,8 +14,6 @@ pub struct FailoverQueueItem {
pub provider_id: String,
pub provider_name: String,
pub sort_index: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_notes: Option<String>,
}
impl Database {
@@ -25,7 +23,7 @@ impl Database {
let mut stmt = conn
.prepare(
"SELECT id, name, sort_index, notes
"SELECT id, name, sort_index
FROM providers
WHERE app_type = ?1 AND in_failover_queue = 1
ORDER BY COALESCE(sort_index, 999999), id ASC",
@@ -38,7 +36,6 @@ impl Database {
provider_id: row.get(0)?,
provider_name: row.get(1)?,
sort_index: row.get(2)?,
provider_notes: row.get(3)?,
})
})
.map_err(|e| AppError::Database(e.to_string()))?
+3 -6
View File
@@ -13,7 +13,7 @@ impl Database {
pub fn get_all_mcp_servers(&self) -> Result<IndexMap<String, McpServer>, AppError> {
let conn = lock_conn!(self.conn);
let mut stmt = conn.prepare(
"SELECT id, name, server_config, description, homepage, docs, tags, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode, enabled_hermes
"SELECT id, name, server_config, description, homepage, docs, tags, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode
FROM mcp_servers
ORDER BY name ASC, id ASC"
).map_err(|e| AppError::Database(e.to_string()))?;
@@ -31,7 +31,6 @@ impl Database {
let enabled_codex: bool = row.get(8)?;
let enabled_gemini: bool = row.get(9)?;
let enabled_opencode: bool = row.get(10)?;
let enabled_hermes: bool = row.get(11)?;
let server = serde_json::from_str(&server_config_str).unwrap_or_default();
let tags = serde_json::from_str(&tags_str).unwrap_or_default();
@@ -47,7 +46,6 @@ impl Database {
codex: enabled_codex,
gemini: enabled_gemini,
opencode: enabled_opencode,
hermes: enabled_hermes,
},
description,
homepage,
@@ -72,8 +70,8 @@ impl Database {
conn.execute(
"INSERT OR REPLACE INTO mcp_servers (
id, name, server_config, description, homepage, docs, tags,
enabled_claude, enabled_codex, enabled_gemini, enabled_opencode, enabled_hermes
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
enabled_claude, enabled_codex, enabled_gemini, enabled_opencode
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
params![
server.id,
server.name,
@@ -89,7 +87,6 @@ impl Database {
server.apps.codex,
server.apps.gemini,
server.apps.opencode,
server.apps.hermes,
],
)
.map_err(|e| AppError::Database(e.to_string()))?;
+12 -15
View File
@@ -23,7 +23,7 @@ impl Database {
.prepare(
"SELECT id, name, description, directory, repo_owner, repo_name, repo_branch,
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode,
enabled_hermes, installed_at, content_hash, updated_at
installed_at, content_hash, updated_at
FROM skills ORDER BY name ASC",
)
.map_err(|e| AppError::Database(e.to_string()))?;
@@ -44,11 +44,10 @@ impl Database {
codex: row.get(9)?,
gemini: row.get(10)?,
opencode: row.get(11)?,
hermes: row.get(12)?,
},
installed_at: row.get(13)?,
content_hash: row.get(14)?,
updated_at: row.get::<_, i64>(15).unwrap_or(0),
installed_at: row.get(12)?,
content_hash: row.get(13)?,
updated_at: row.get::<_, i64>(14).unwrap_or(0),
})
})
.map_err(|e| AppError::Database(e.to_string()))?;
@@ -68,7 +67,7 @@ impl Database {
.prepare(
"SELECT id, name, description, directory, repo_owner, repo_name, repo_branch,
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode,
enabled_hermes, installed_at, content_hash, updated_at
installed_at, content_hash, updated_at
FROM skills WHERE id = ?1",
)
.map_err(|e| AppError::Database(e.to_string()))?;
@@ -88,11 +87,10 @@ impl Database {
codex: row.get(9)?,
gemini: row.get(10)?,
opencode: row.get(11)?,
hermes: row.get(12)?,
},
installed_at: row.get(13)?,
content_hash: row.get(14)?,
updated_at: row.get::<_, i64>(15).unwrap_or(0),
installed_at: row.get(12)?,
content_hash: row.get(13)?,
updated_at: row.get::<_, i64>(14).unwrap_or(0),
})
});
@@ -109,9 +107,9 @@ impl Database {
conn.execute(
"INSERT OR REPLACE INTO skills
(id, name, description, directory, repo_owner, repo_name, repo_branch,
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode, enabled_hermes,
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode,
installed_at, content_hash, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)",
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
params![
skill.id,
skill.name,
@@ -125,7 +123,6 @@ impl Database {
skill.apps.codex,
skill.apps.gemini,
skill.apps.opencode,
skill.apps.hermes,
skill.installed_at,
skill.content_hash,
skill.updated_at,
@@ -157,8 +154,8 @@ impl Database {
let conn = lock_conn!(self.conn);
let affected = conn
.execute(
"UPDATE skills SET enabled_claude = ?1, enabled_codex = ?2, enabled_gemini = ?3, enabled_opencode = ?4, enabled_hermes = ?5 WHERE id = ?6",
params![apps.claude, apps.codex, apps.gemini, apps.opencode, apps.hermes, id],
"UPDATE skills SET enabled_claude = ?1, enabled_codex = ?2, enabled_gemini = ?3, enabled_opencode = ?4 WHERE id = ?5",
params![apps.claude, apps.codex, apps.gemini, apps.opencode, id],
)
.map_err(|e| AppError::Database(e.to_string()))?;
Ok(affected > 0)
+1 -90
View File
@@ -4,61 +4,13 @@
use crate::database::{lock_conn, Database};
use crate::error::AppError;
use chrono::{Duration, Local, TimeZone};
/// Compute the rollup/prune cutoff aligned to a local-day boundary.
///
/// Anything strictly older than the returned timestamp will be aggregated into
/// `usage_daily_rollups` and deleted from `proxy_request_logs`. Aligning to the
/// next local midnight after `(now - retain_days)` guarantees that the youngest
/// rollup row always represents a *complete* local day. Without this alignment
/// the cutoff falls mid-day, leaving the day half-rolled-up and half-pruned —
/// which would silently under-count any range query that touches that day
/// after `compute_rollup_date_bounds` trims partial-coverage rollup days.
fn compute_local_midnight_cutoff(
now: chrono::DateTime<Local>,
retain_days: i64,
) -> Result<i64, AppError> {
let target_day = now
.checked_sub_signed(Duration::days(retain_days))
.ok_or_else(|| AppError::Database("rollup cutoff overflow".to_string()))?
.date_naive();
// Use the *next* day's midnight so anything before it has fully been bucketed.
let next_day = target_day
.succ_opt()
.ok_or_else(|| AppError::Database("rollup cutoff next-day overflow".to_string()))?;
let naive_midnight = next_day
.and_hms_opt(0, 0, 0)
.ok_or_else(|| AppError::Database("rollup cutoff midnight overflow".to_string()))?;
let local_dt = match Local.from_local_datetime(&naive_midnight) {
chrono::LocalResult::Single(dt) => dt,
chrono::LocalResult::Ambiguous(earliest, _) => earliest,
chrono::LocalResult::None => {
// DST gap: fall back to one hour later, which always exists.
let bumped = naive_midnight + Duration::hours(1);
match Local.from_local_datetime(&bumped) {
chrono::LocalResult::Single(dt) => dt,
chrono::LocalResult::Ambiguous(earliest, _) => earliest,
chrono::LocalResult::None => {
return Err(AppError::Database(
"rollup cutoff fell into DST gap".to_string(),
))
}
}
}
};
Ok(local_dt.timestamp())
}
impl Database {
/// Aggregate proxy_request_logs older than `retain_days` into usage_daily_rollups,
/// then delete the aggregated detail rows.
/// Returns the number of deleted detail rows.
pub fn rollup_and_prune(&self, retain_days: i64) -> Result<u64, AppError> {
let cutoff = compute_local_midnight_cutoff(Local::now(), retain_days)?;
let cutoff = chrono::Utc::now().timestamp() - retain_days * 86400;
let conn = lock_conn!(self.conn);
// Check if there are any rows to process
@@ -158,49 +110,8 @@ impl Database {
#[cfg(test)]
mod tests {
use super::compute_local_midnight_cutoff;
use crate::database::Database;
use crate::error::AppError;
use chrono::{Local, TimeZone};
fn local_dt(
year: i32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
) -> chrono::DateTime<Local> {
match Local.with_ymd_and_hms(year, month, day, hour, minute, second) {
chrono::LocalResult::Single(dt) => dt,
chrono::LocalResult::Ambiguous(earliest, _) => earliest,
chrono::LocalResult::None => panic!("invalid local datetime in test fixture"),
}
}
#[test]
fn cutoff_is_aligned_to_local_midnight_after_target_day() -> Result<(), AppError> {
// now = 2026-04-16 14:32:17 local; retain_days = 30
// target day = 2026-03-17; cutoff should be 2026-03-18 00:00 local.
let now = local_dt(2026, 4, 16, 14, 32, 17);
let cutoff_ts = compute_local_midnight_cutoff(now, 30)?;
let cutoff_dt = Local.timestamp_opt(cutoff_ts, 0).single().unwrap();
let expected = local_dt(2026, 3, 18, 0, 0, 0);
assert_eq!(cutoff_dt, expected);
Ok(())
}
#[test]
fn cutoff_at_local_midnight_now_still_lands_on_midnight() -> Result<(), AppError> {
// If `now` is itself local midnight, the math should not introduce drift.
let now = local_dt(2026, 4, 16, 0, 0, 0);
let cutoff_ts = compute_local_midnight_cutoff(now, 7)?;
let cutoff_dt = Local.timestamp_opt(cutoff_ts, 0).single().unwrap();
// (2026-04-16 - 7d) = 2026-04-09; cutoff = 2026-04-10 00:00 local.
let expected = local_dt(2026, 4, 10, 0, 0, 0);
assert_eq!(cutoff_dt, expected);
Ok(())
}
#[test]
fn test_rollup_and_prune() -> Result<(), AppError> {
+1 -1
View File
@@ -44,7 +44,7 @@ use std::sync::Mutex;
/// 当前 Schema 版本号
/// 每次修改表结构时递增,并在 schema.rs 中添加相应的迁移逻辑
pub(crate) const SCHEMA_VERSION: i32 = 10;
pub(crate) const SCHEMA_VERSION: i32 = 9;
/// 安全地序列化 JSON,避免 unwrap panic
pub(crate) fn to_json_string<T: Serialize>(value: &T) -> Result<String, AppError> {
+1 -41
View File
@@ -65,8 +65,7 @@ impl Database {
id TEXT PRIMARY KEY, name TEXT NOT NULL, server_config TEXT NOT NULL,
description TEXT, homepage TEXT, docs TEXT, tags TEXT NOT NULL DEFAULT '[]',
enabled_claude BOOLEAN NOT NULL DEFAULT 0, enabled_codex BOOLEAN NOT NULL DEFAULT 0,
enabled_gemini BOOLEAN NOT NULL DEFAULT 0, enabled_opencode BOOLEAN NOT NULL DEFAULT 0,
enabled_hermes BOOLEAN NOT NULL DEFAULT 0
enabled_gemini BOOLEAN NOT NULL DEFAULT 0, enabled_opencode BOOLEAN NOT NULL DEFAULT 0
)",
[],
)
@@ -94,7 +93,6 @@ impl Database {
enabled_codex BOOLEAN NOT NULL DEFAULT 0,
enabled_gemini BOOLEAN NOT NULL DEFAULT 0,
enabled_opencode BOOLEAN NOT NULL DEFAULT 0,
enabled_hermes BOOLEAN NOT NULL DEFAULT 0,
installed_at INTEGER NOT NULL DEFAULT 0,
content_hash TEXT,
updated_at INTEGER NOT NULL DEFAULT 0
@@ -425,11 +423,6 @@ impl Database {
Self::migrate_v8_to_v9(conn)?;
Self::set_user_version(conn, 9)?;
}
9 => {
log::info!("迁移数据库从 v9 到 v10(添加 Hermes Agent 支持)");
Self::migrate_v9_to_v10(conn)?;
Self::set_user_version(conn, 10)?;
}
_ => {
return Err(AppError::Database(format!(
"未知的数据库版本 {version},无法迁移到 {SCHEMA_VERSION}"
@@ -1175,43 +1168,11 @@ impl Database {
Ok(())
}
/// v9 -> v10 迁移:添加 Hermes Agent 支持
fn migrate_v9_to_v10(conn: &Connection) -> Result<(), AppError> {
Self::add_column_if_missing(
conn,
"mcp_servers",
"enabled_hermes",
"BOOLEAN NOT NULL DEFAULT 0",
)?;
// skills table may not exist in databases migrated from very old versions
if Self::table_exists(conn, "skills")? {
Self::add_column_if_missing(
conn,
"skills",
"enabled_hermes",
"BOOLEAN NOT NULL DEFAULT 0",
)?;
}
log::info!("v9 -> v10 迁移完成:已添加 Hermes Agent 支持");
Ok(())
}
/// 插入默认模型定价数据
/// 格式: (model_id, display_name, input, output, cache_read, cache_creation)
/// 注意: model_id 使用短横线格式(如 claude-haiku-4-5),与 API 返回的模型名称标准化后一致
fn seed_model_pricing(conn: &Connection) -> Result<(), AppError> {
let pricing_data = [
// Claude 4.7 系列
(
"claude-opus-4-7",
"Claude Opus 4.7",
"5",
"25",
"0.50",
"6.25",
),
// Claude 4.6 系列
(
"claude-opus-4-6-20260206",
@@ -1639,7 +1600,6 @@ impl Database {
"0",
),
("kimi-k2.5", "Kimi K2.5", "0.60", "2.50", "0.10", "0"),
("kimi-k2.6", "Kimi K2.6", "0.95", "4.00", "0.16", "0"),
// MiniMax 系列
("minimax-m2.1", "MiniMax M2.1", "0.27", "0.95", "0.03", "0"),
(
-2
View File
@@ -167,7 +167,6 @@ pub(crate) fn parse_mcp_apps(apps_str: &str) -> Result<McpApps, AppError> {
codex: false,
gemini: false,
opencode: false,
hermes: false,
};
for app in apps_str.split(',') {
@@ -180,7 +179,6 @@ pub(crate) fn parse_mcp_apps(apps_str: &str) -> Result<McpApps, AppError> {
// OpenClaw doesn't support MCP, ignore silently
log::debug!("OpenClaw doesn't support MCP, ignoring in apps parameter");
}
"hermes" => apps.hermes = true,
other => {
return Err(AppError::InvalidInput(format!(
"Invalid app in 'apps': {other}"
+1 -1
View File
@@ -31,7 +31,7 @@ pub use skill::import_skill_from_deeplink;
///
/// Represents a parsed ccswitch:// URL ready for processing.
/// This struct contains all possible fields for all resource types.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeepLinkImportRequest {
/// Protocol version (e.g., "v1")
+6 -6
View File
@@ -81,10 +81,10 @@ fn parse_provider_deeplink(
// Validate app type
if !matches!(
app.as_str(),
"claude" | "codex" | "gemini" | "opencode" | "openclaw" | "hermes"
"claude" | "codex" | "gemini" | "opencode" | "openclaw"
) {
return Err(AppError::InvalidInput(format!(
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', 'openclaw', or 'hermes', got '{app}'"
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', or 'openclaw', got '{app}'"
)));
}
@@ -190,10 +190,10 @@ fn parse_prompt_deeplink(
// Validate app type
if !matches!(
app.as_str(),
"claude" | "codex" | "gemini" | "opencode" | "openclaw" | "hermes"
"claude" | "codex" | "gemini" | "opencode" | "openclaw"
) {
return Err(AppError::InvalidInput(format!(
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', 'openclaw', or 'hermes', got '{app}'"
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', or 'openclaw', got '{app}'"
)));
}
@@ -262,10 +262,10 @@ fn parse_mcp_deeplink(
let trimmed = app.trim();
if !matches!(
trimmed,
"claude" | "codex" | "gemini" | "opencode" | "openclaw" | "hermes"
"claude" | "codex" | "gemini" | "opencode" | "openclaw"
) {
return Err(AppError::InvalidInput(format!(
"Invalid app in 'apps': must be 'claude', 'codex', 'gemini', 'opencode', 'openclaw', or 'hermes', got '{trimmed}'"
"Invalid app in 'apps': must be 'claude', 'codex', 'gemini', 'opencode', or 'openclaw', got '{trimmed}'"
)));
}
}
+7 -133
View File
@@ -146,8 +146,7 @@ pub(crate) fn build_provider_from_request(
AppType::Codex => build_codex_settings(request),
AppType::Gemini => build_gemini_settings(request),
AppType::OpenCode => build_opencode_settings(request),
AppType::OpenClaw => build_additive_app_settings(request),
AppType::Hermes => build_hermes_settings(request),
AppType::OpenClaw => build_openclaw_settings(request),
};
// Build usage script configuration if provided
@@ -394,11 +393,11 @@ fn build_opencode_settings(request: &DeepLinkImportRequest) -> serde_json::Value
})
}
/// Build settings for OpenClaw (camelCase live config).
/// Format: { baseUrl, apiKey, api, models }
fn build_additive_app_settings(request: &DeepLinkImportRequest) -> serde_json::Value {
fn build_openclaw_settings(request: &DeepLinkImportRequest) -> serde_json::Value {
let endpoint = get_primary_endpoint(request);
// Build OpenClaw provider config
// Format: { baseUrl, apiKey, api, models }
let mut config = serde_json::Map::new();
if !endpoint.is_empty() {
@@ -409,49 +408,10 @@ fn build_additive_app_settings(request: &DeepLinkImportRequest) -> serde_json::V
config.insert("apiKey".to_string(), json!(api_key));
}
// Default to OpenAI-compatible API
config.insert("api".to_string(), json!("openai-completions"));
if let Some(model) = &request.model {
config.insert(
"models".to_string(),
json!([{ "id": model, "name": model }]),
);
}
json!(config)
}
/// Build Hermes provider settings (snake_case YAML-native fields).
///
/// Hermes' `custom_providers:` entries use `base_url` / `api_key` / `api_mode`
/// (see `_VALID_CUSTOM_PROVIDER_FIELDS` in upstream `hermes_cli/config.py`).
/// Emitting camelCase here — as the OpenClaw path does — would poison the
/// YAML with unknown root fields the Hermes runtime ignores.
///
/// `api_mode` is always written explicitly. Deeplinks have no field to carry
/// it, so we default to `chat_completions` (the most widely compatible
/// protocol) and let the user adjust via the UI after import. We never rely
/// on Hermes' built-in URL heuristics, which only recognize a handful of
/// official endpoints.
fn build_hermes_settings(request: &DeepLinkImportRequest) -> serde_json::Value {
let endpoint = get_primary_endpoint(request);
let mut config = serde_json::Map::new();
if let Some(name) = request.name.as_deref().filter(|s| !s.is_empty()) {
config.insert("name".to_string(), json!(name));
}
if !endpoint.is_empty() {
config.insert("base_url".to_string(), json!(endpoint));
}
if let Some(api_key) = &request.api_key {
config.insert("api_key".to_string(), json!(api_key));
}
config.insert("api_mode".to_string(), json!("chat_completions"));
// Build models array
if let Some(model) = &request.model {
config.insert(
"models".to_string(),
@@ -524,7 +484,7 @@ pub fn parse_and_merge_config(
"codex" => merge_codex_config(&mut merged, &config_value)?,
"gemini" => merge_gemini_config(&mut merged, &config_value)?,
// Additive mode apps use JSON config directly; pass through as-is
"openclaw" | "opencode" | "hermes" => {
"openclaw" | "opencode" => {
merge_additive_config(&mut merged, &config_value)?;
}
"" => {
@@ -751,89 +711,3 @@ fn extract_codex_base_url(toml_value: &toml::Value) -> Option<String> {
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn hermes_request() -> DeepLinkImportRequest {
DeepLinkImportRequest {
resource: "provider".to_string(),
app: Some("hermes".to_string()),
name: Some("MyHermes".to_string()),
endpoint: Some("https://api.example.com/v1".to_string()),
api_key: Some("sk-test".to_string()),
model: Some("anthropic/claude-opus-4-7".to_string()),
..Default::default()
}
}
#[test]
fn build_hermes_settings_emits_snake_case() {
let settings = build_hermes_settings(&hermes_request());
let obj = settings.as_object().expect("settings must be object");
assert_eq!(obj.get("name").unwrap(), "MyHermes");
assert_eq!(obj.get("base_url").unwrap(), "https://api.example.com/v1");
assert_eq!(obj.get("api_key").unwrap(), "sk-test");
// camelCase and legacy fields must NOT be present
assert!(obj.get("baseUrl").is_none(), "no camelCase baseUrl");
assert!(obj.get("apiKey").is_none(), "no camelCase apiKey");
assert!(obj.get("api").is_none(), "no legacy 'api' field");
// models array with the deeplink model id
let models = obj.get("models").unwrap().as_array().unwrap();
assert_eq!(models.len(), 1);
assert_eq!(models[0]["id"], "anthropic/claude-opus-4-7");
}
#[test]
fn build_hermes_settings_writes_default_api_mode() {
let settings = build_hermes_settings(&hermes_request());
assert_eq!(
settings.as_object().unwrap().get("api_mode").unwrap(),
"chat_completions",
"api_mode must be written explicitly so Hermes never falls back to URL auto-detection"
);
}
#[test]
fn build_hermes_settings_skips_missing_optional_fields() {
let request = DeepLinkImportRequest {
resource: "provider".to_string(),
app: Some("hermes".to_string()),
name: Some("Minimal".to_string()),
endpoint: None,
api_key: None,
model: None,
..Default::default()
};
let settings = build_hermes_settings(&request);
let obj = settings.as_object().unwrap();
assert_eq!(obj.get("name").unwrap(), "Minimal");
assert!(obj.get("base_url").is_none());
assert!(obj.get("api_key").is_none());
assert!(obj.get("models").is_none());
assert_eq!(obj.get("api_mode").unwrap(), "chat_completions");
}
#[test]
fn openclaw_still_uses_camel_case() {
// OpenClaw's live config natively uses camelCase; guard against a
// refactor accidentally flipping it to snake_case.
let request = DeepLinkImportRequest {
resource: "provider".to_string(),
app: Some("openclaw".to_string()),
name: Some("c".to_string()),
endpoint: Some("https://api.example.com".to_string()),
api_key: Some("k".to_string()),
..Default::default()
};
let settings = build_additive_app_settings(&request);
let obj = settings.as_object().unwrap();
assert!(obj.contains_key("baseUrl"));
assert!(obj.contains_key("apiKey"));
}
}
File diff suppressed because it is too large Load Diff
+2 -31
View File
@@ -11,7 +11,6 @@ mod deeplink;
mod error;
mod gemini_config;
mod gemini_mcp;
pub mod hermes_config;
mod init_status;
mod lightweight;
#[cfg(target_os = "linux")]
@@ -169,7 +168,7 @@ async fn update_tray_menu(
) -> Result<bool, String> {
match tray::create_tray_menu(&app, state.inner()) {
Ok(new_menu) => {
if let Some(tray) = app.tray_by_id(tray::TRAY_ID) {
if let Some(tray) = app.tray_by_id("main") {
tray.set_menu(Some(new_menu))
.map_err(|e| format!("更新托盘菜单失败: {e}"))?;
return Ok(true);
@@ -541,13 +540,6 @@ pub fn run() {
Ok(_) => log::debug!("○ No new OpenClaw providers to import"),
Err(e) => log::warn!("✗ Failed to import OpenClaw providers: {e}"),
}
match crate::services::provider::import_hermes_providers_from_live(&app_state) {
Ok(count) if count > 0 => {
log::info!("✓ Imported {count} Hermes provider(s) from live config");
}
Ok(_) => log::debug!("○ No new Hermes providers to import"),
Err(e) => log::warn!("✗ Failed to import Hermes providers: {e}"),
}
// 2. OMO 配置导入(当数据库中无 OMO provider 时,从本地文件导入)
{
@@ -635,14 +627,6 @@ pub fn run() {
Ok(_) => log::debug!("○ No OpenCode MCP servers found to import"),
Err(e) => log::warn!("✗ Failed to import OpenCode MCP: {e}"),
}
match crate::services::mcp::McpService::import_from_hermes(&app_state) {
Ok(count) if count > 0 => {
log::info!("✓ Imported {count} MCP server(s) from Hermes");
}
Ok(_) => log::debug!("○ No Hermes MCP servers found to import"),
Err(e) => log::warn!("✗ Failed to import Hermes MCP: {e}"),
}
}
// 4. 导入提示词文件(表空时触发)
@@ -655,7 +639,6 @@ pub fn run() {
crate::app_config::AppType::Gemini,
crate::app_config::AppType::OpenCode,
crate::app_config::AppType::OpenClaw,
crate::app_config::AppType::Hermes,
] {
match crate::services::prompt::PromptService::import_from_file_on_first_launch(
&app_state,
@@ -745,7 +728,7 @@ pub fn run() {
let menu = tray::create_tray_menu(app.handle(), &app_state)?;
// 构建托盘
let mut tray_builder = TrayIconBuilder::with_id(tray::TRAY_ID)
let mut tray_builder = TrayIconBuilder::with_id("main")
.on_tray_icon_event(|_tray, event| match event {
// 左键点击已通过 show_menu_on_left_click(true) 打开菜单,这里不再额外处理
TrayIconEvent::Click { .. } => {}
@@ -1251,18 +1234,6 @@ pub fn run() {
commands::set_openclaw_env,
commands::get_openclaw_tools,
commands::set_openclaw_tools,
// Hermes specific
commands::import_hermes_providers_from_live,
commands::get_hermes_live_provider_ids,
commands::get_hermes_live_provider,
commands::scan_hermes_config_health,
commands::get_hermes_model_config,
commands::open_hermes_web_ui,
commands::launch_hermes_dashboard,
commands::get_hermes_memory,
commands::set_hermes_memory,
commands::get_hermes_memory_limits,
commands::set_hermes_memory_enabled,
// Global upstream proxy
commands::get_global_proxy_url,
commands::set_global_proxy_url,
-1
View File
@@ -92,7 +92,6 @@ pub fn import_from_claude(config: &mut MultiAppConfig) -> Result<usize, AppError
codex: false,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
-1
View File
@@ -236,7 +236,6 @@ pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, AppError>
codex: true,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
-1
View File
@@ -88,7 +88,6 @@ pub fn import_from_gemini(config: &mut MultiAppConfig) -> Result<usize, AppError
codex: false,
gemini: true,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
-574
View File
@@ -1,574 +0,0 @@
//! Hermes MCP sync and import module
//!
//! Handles conversion between CC Switch unified MCP format and Hermes config.yaml format.
//!
//! ## Format mapping
//!
//! | CC Switch unified (JSON) | Hermes config.yaml (YAML) |
//! |-------------------------------------------------|---------------------------------|
//! | `{"type":"stdio","command":"npx","args":[...],"env":{}}` | `command: npx`, `args: [...]`, `env: {}` |
//! | `{"type":"sse"/"http","url":"...","headers":{}}` | `url: "..."`, `headers: {}` |
//!
//! Key differences from Claude format:
//! - Hermes has NO explicit `type` field -- it infers stdio (has `command`) vs HTTP (has `url`)
//! - Hermes has extra fields: `enabled`, `timeout`, `connect_timeout`, `tools`, `sampling`
//! - These Hermes-specific fields are preserved on merge-on-write and stripped on import
use serde_json::{json, Value};
use std::collections::HashMap;
use crate::app_config::{McpApps, McpServer, MultiAppConfig};
use crate::error::AppError;
use crate::hermes_config;
use super::validation::validate_server_spec;
/// Hermes-specific fields preserved on merge-on-write, stripped on import.
/// Update this list when Hermes adds new per-server config fields.
///
/// `auth` ("oauth" / absent) is an OAuth-type declaration read by Hermes —
/// CC Switch has no OAuth UI, but losing the field on round-trip downgrades
/// the server to unauthenticated calls.
const HERMES_EXTRA_FIELDS: &[&str] = &[
"enabled",
"timeout",
"connect_timeout",
"tools",
"sampling",
"roots",
"auth",
];
// ============================================================================
// Helper Functions
// ============================================================================
/// Check if Hermes MCP sync should proceed
fn should_sync_hermes_mcp() -> bool {
hermes_config::get_hermes_dir().exists()
}
// ============================================================================
// Format Conversion: CC Switch -> Hermes
// ============================================================================
/// Convert CC Switch unified format to Hermes format
///
/// Conversion rules:
/// - `stdio`: output `command`, `args`, `env` (strip `type` field)
/// - `sse`/`http`: output `url`, `headers` (strip `type` field)
/// - Always add `enabled: true`
fn convert_to_hermes_format(spec: &Value) -> Result<Value, AppError> {
let obj = spec
.as_object()
.ok_or_else(|| AppError::McpValidation("MCP spec must be a JSON object".into()))?;
let typ = obj.get("type").and_then(|v| v.as_str()).unwrap_or("stdio");
let mut result = serde_json::Map::new();
match typ {
"stdio" => {
if let Some(command) = obj.get("command") {
result.insert("command".into(), command.clone());
}
if let Some(args) = obj.get("args") {
if args.is_array() && !args.as_array().map(|a| a.is_empty()).unwrap_or(true) {
result.insert("args".into(), args.clone());
}
}
if let Some(env) = obj.get("env") {
if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
result.insert("env".into(), env.clone());
}
}
}
"sse" | "http" => {
if let Some(url) = obj.get("url") {
result.insert("url".into(), url.clone());
}
if let Some(headers) = obj.get("headers") {
if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true)
{
result.insert("headers".into(), headers.clone());
}
}
}
_ => {
return Err(AppError::McpValidation(format!("Unknown MCP type: {typ}")));
}
}
result.insert("enabled".into(), json!(true));
Ok(Value::Object(result))
}
// ============================================================================
// Format Conversion: Hermes -> CC Switch
// ============================================================================
/// Convert Hermes format to CC Switch unified format
///
/// Conversion rules:
/// - If `command` exists: set `type: "stdio"`, extract `command`, `args`, `env`
/// - If `url` exists: set `type: "sse"`, extract `url`, `headers`
/// - Strip Hermes-specific fields: `enabled`, `timeout`, `connect_timeout`, `tools`, `sampling`
fn convert_from_hermes_format(id: &str, spec: &Value) -> Result<Value, AppError> {
let obj = spec
.as_object()
.ok_or_else(|| AppError::McpValidation("Hermes MCP spec must be a JSON object".into()))?;
let mut result = serde_json::Map::new();
if obj.contains_key("command") {
// stdio type
result.insert("type".into(), json!("stdio"));
if let Some(command) = obj.get("command") {
result.insert("command".into(), command.clone());
}
if let Some(args) = obj.get("args") {
if args.is_array() && !args.as_array().map(|a| a.is_empty()).unwrap_or(true) {
result.insert("args".into(), args.clone());
}
}
if let Some(env) = obj.get("env") {
if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
result.insert("env".into(), env.clone());
}
}
} else if obj.contains_key("url") {
// HTTP/SSE type
result.insert("type".into(), json!("sse"));
if let Some(url) = obj.get("url") {
result.insert("url".into(), url.clone());
}
if let Some(headers) = obj.get("headers") {
if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true) {
result.insert("headers".into(), headers.clone());
}
}
} else {
return Err(AppError::McpValidation(format!(
"Hermes MCP server '{id}' has neither 'command' nor 'url' field"
)));
}
// Note: Hermes-specific fields (enabled, timeout, connect_timeout, tools, sampling)
// are intentionally NOT copied -- they are stripped on import.
Ok(Value::Object(result))
}
// ============================================================================
// Public API: Sync Functions
// ============================================================================
/// Sync a single MCP server to Hermes live config (merge-on-write)
///
/// Strategy:
/// 1. Read existing mcp_servers from config.yaml
/// 2. If server already exists, merge: keep Hermes-specific fields, overwrite core fields
/// 3. Set `enabled: true`
/// 4. Write back
pub fn sync_single_server_to_hermes(
_config: &MultiAppConfig,
id: &str,
server_spec: &Value,
) -> Result<(), AppError> {
if !should_sync_hermes_mcp() {
return Ok(());
}
let hermes_spec = convert_to_hermes_format(server_spec)?;
let id_owned = id.to_string();
hermes_config::update_mcp_servers_yaml(|servers| {
let id_yaml = serde_yaml::Value::String(id_owned.clone());
let merged_json = if let Some(existing_yaml) = servers.get(&id_yaml) {
let existing_json = hermes_config::yaml_to_json(existing_yaml)?;
merge_hermes_spec(&existing_json, &hermes_spec)
} else {
hermes_spec.clone()
};
let merged_yaml_value = hermes_config::json_to_yaml(&merged_json)?;
servers.insert(id_yaml, merged_yaml_value);
Ok(())
})
}
/// Merge new spec into existing Hermes spec, preserving Hermes-specific fields.
///
/// Core fields (command, args, env, url, headers) come from `new_spec`.
/// Hermes-specific fields (enabled, tools, sampling, etc.) are kept from
/// `existing` — this prevents CC Switch from overwriting user customizations.
fn merge_hermes_spec(existing: &Value, new_spec: &Value) -> Value {
let mut result = serde_json::Map::new();
// Copy Hermes-specific fields from existing config
if let Some(existing_obj) = existing.as_object() {
for &field in HERMES_EXTRA_FIELDS {
if let Some(val) = existing_obj.get(field) {
result.insert(field.to_string(), val.clone());
}
}
}
// Overwrite with core fields from new spec; for Hermes-specific fields,
// only apply from new_spec if existing didn't already have them
if let Some(new_obj) = new_spec.as_object() {
for (key, val) in new_obj {
if HERMES_EXTRA_FIELDS.contains(&key.as_str()) && result.contains_key(key) {
continue; // Existing Hermes-specific field takes precedence
}
result.insert(key.clone(), val.clone());
}
}
Value::Object(result)
}
/// Remove a single MCP server from Hermes live config
pub fn remove_server_from_hermes(id: &str) -> Result<(), AppError> {
if !should_sync_hermes_mcp() {
return Ok(());
}
let id_owned = id.to_string();
hermes_config::update_mcp_servers_yaml(|servers| {
servers.remove(serde_yaml::Value::String(id_owned.clone()));
Ok(())
})
}
/// Import MCP servers from Hermes config to unified structure
///
/// Existing servers will have Hermes app enabled without overwriting other fields.
pub fn import_from_hermes(config: &mut MultiAppConfig) -> Result<usize, AppError> {
let yaml_map = hermes_config::get_mcp_servers_yaml()?;
if yaml_map.is_empty() {
return Ok(0);
}
// Ensure servers map exists
let servers = config.mcp.servers.get_or_insert_with(HashMap::new);
let mut changed = 0;
let mut errors = Vec::new();
for (key, spec_yaml) in &yaml_map {
let id = match key.as_str() {
Some(s) => s.to_string(),
None => {
log::warn!("Skip Hermes MCP server with non-string key");
continue;
}
};
// Convert YAML value to JSON
let spec_json = match hermes_config::yaml_to_json(spec_yaml) {
Ok(j) => j,
Err(e) => {
log::warn!("Skip Hermes MCP server '{id}': failed to convert YAML to JSON: {e}");
errors.push(format!("{id}: {e}"));
continue;
}
};
// Convert from Hermes format to unified format
let unified_spec = match convert_from_hermes_format(&id, &spec_json) {
Ok(s) => s,
Err(e) => {
log::warn!("Skip invalid Hermes MCP server '{id}': {e}");
errors.push(format!("{id}: {e}"));
continue;
}
};
// Validate the converted spec
if let Err(e) = validate_server_spec(&unified_spec) {
log::warn!("Skip invalid MCP server '{id}' after conversion: {e}");
errors.push(format!("{id}: {e}"));
continue;
}
if let Some(existing) = servers.get_mut(&id) {
// Existing server: just enable Hermes app
if !existing.apps.hermes {
existing.apps.hermes = true;
changed += 1;
log::info!("MCP server '{id}' enabled for Hermes");
}
} else {
// New server: default to only Hermes enabled
servers.insert(
id.clone(),
McpServer {
id: id.clone(),
name: id.clone(),
server: unified_spec,
apps: McpApps {
claude: false,
codex: false,
gemini: false,
opencode: false,
hermes: true,
},
description: None,
homepage: None,
docs: None,
tags: Vec::new(),
},
);
changed += 1;
log::info!("Imported new MCP server '{id}' from Hermes");
}
}
if !errors.is_empty() {
log::warn!(
"Import completed with {} failures: {:?}",
errors.len(),
errors
);
}
Ok(changed)
}
#[cfg(test)]
mod tests {
use super::*;
// ========================================================================
// convert_to_hermes_format tests
// ========================================================================
#[test]
fn test_convert_stdio_to_hermes() {
let spec = json!({
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem"],
"env": { "HOME": "/Users/test" }
});
let result = convert_to_hermes_format(&spec).unwrap();
// No type field in Hermes format
assert!(result.get("type").is_none());
assert_eq!(result["command"], "npx");
assert_eq!(result["args"][0], "-y");
assert_eq!(result["args"][1], "@modelcontextprotocol/server-filesystem");
assert_eq!(result["env"]["HOME"], "/Users/test");
assert_eq!(result["enabled"], true);
}
#[test]
fn test_convert_http_to_hermes() {
let spec = json!({
"type": "sse",
"url": "https://example.com/mcp",
"headers": { "Authorization": "Bearer xxx" }
});
let result = convert_to_hermes_format(&spec).unwrap();
assert!(result.get("type").is_none());
assert_eq!(result["url"], "https://example.com/mcp");
assert_eq!(result["headers"]["Authorization"], "Bearer xxx");
assert_eq!(result["enabled"], true);
}
#[test]
fn test_convert_http_type_to_hermes() {
let spec = json!({
"type": "http",
"url": "https://example.com/mcp"
});
let result = convert_to_hermes_format(&spec).unwrap();
assert!(result.get("type").is_none());
assert_eq!(result["url"], "https://example.com/mcp");
assert_eq!(result["enabled"], true);
}
#[test]
fn test_convert_stdio_empty_env_to_hermes() {
let spec = json!({
"type": "stdio",
"command": "node",
"args": [],
"env": {}
});
let result = convert_to_hermes_format(&spec).unwrap();
assert_eq!(result["command"], "node");
// Empty args and env should be omitted
assert!(result.get("args").is_none());
assert!(result.get("env").is_none());
assert_eq!(result["enabled"], true);
}
#[test]
fn test_convert_unknown_type_to_hermes_fails() {
let spec = json!({ "type": "grpc", "command": "foo" });
assert!(convert_to_hermes_format(&spec).is_err());
}
// ========================================================================
// convert_from_hermes_format tests
// ========================================================================
#[test]
fn test_convert_hermes_stdio_to_unified() {
let spec = json!({
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem"],
"env": { "HOME": "/Users/test" },
"enabled": true,
"timeout": 30,
"connect_timeout": 10,
"tools": { "include": ["read_file"] },
"sampling": { "enabled": true }
});
let result = convert_from_hermes_format("filesystem", &spec).unwrap();
assert_eq!(result["type"], "stdio");
assert_eq!(result["command"], "npx");
assert_eq!(result["args"][0], "-y");
assert_eq!(result["args"][1], "@modelcontextprotocol/server-filesystem");
assert_eq!(result["env"]["HOME"], "/Users/test");
// Hermes-specific fields should be stripped
assert!(result.get("enabled").is_none());
assert!(result.get("timeout").is_none());
assert!(result.get("connect_timeout").is_none());
assert!(result.get("tools").is_none());
assert!(result.get("sampling").is_none());
}
#[test]
fn test_convert_hermes_http_to_unified() {
let spec = json!({
"url": "https://example.com/mcp",
"headers": { "Authorization": "Bearer xxx" },
"enabled": true,
"timeout": 60
});
let result = convert_from_hermes_format("remote-server", &spec).unwrap();
assert_eq!(result["type"], "sse");
assert_eq!(result["url"], "https://example.com/mcp");
assert_eq!(result["headers"]["Authorization"], "Bearer xxx");
// Hermes-specific fields should be stripped
assert!(result.get("enabled").is_none());
assert!(result.get("timeout").is_none());
}
#[test]
fn test_convert_hermes_no_command_no_url_fails() {
let spec = json!({ "enabled": true, "timeout": 30 });
assert!(convert_from_hermes_format("bad-server", &spec).is_err());
}
// ========================================================================
// Merge-on-write tests
// ========================================================================
#[test]
fn test_merge_preserves_hermes_specific_fields() {
let existing = json!({
"command": "old-cmd",
"args": ["old-arg"],
"enabled": true,
"timeout": 30,
"connect_timeout": 10,
"tools": { "include": ["read_file"] },
"sampling": { "enabled": true }
});
let new_spec = json!({
"command": "new-cmd",
"args": ["new-arg"],
"env": { "KEY": "value" },
"enabled": true
});
let merged = merge_hermes_spec(&existing, &new_spec);
// Core fields should be overwritten
assert_eq!(merged["command"], "new-cmd");
assert_eq!(merged["args"][0], "new-arg");
assert_eq!(merged["env"]["KEY"], "value");
// Hermes-specific fields should be preserved from existing
assert_eq!(merged["timeout"], 30);
assert_eq!(merged["connect_timeout"], 10);
assert_eq!(merged["tools"]["include"][0], "read_file");
assert_eq!(merged["sampling"]["enabled"], true);
assert_eq!(merged["enabled"], true);
}
#[test]
fn test_merge_preserves_auth_field() {
let existing = json!({
"url": "https://mcp.example.com",
"auth": "oauth",
"enabled": true
});
let new_spec = json!({
"url": "https://mcp.example.com/updated",
"headers": { "X-Trace": "abc" },
"enabled": true
});
let merged = merge_hermes_spec(&existing, &new_spec);
assert_eq!(merged["url"], "https://mcp.example.com/updated");
assert_eq!(merged["headers"]["X-Trace"], "abc");
assert_eq!(
merged["auth"], "oauth",
"auth declaration must survive CC Switch round-trip"
);
}
#[test]
fn test_convert_hermes_strips_auth_on_import() {
let spec = json!({
"url": "https://mcp.example.com",
"auth": "oauth",
"enabled": true
});
let result = convert_from_hermes_format("remote", &spec).unwrap();
assert_eq!(result["type"], "sse");
assert_eq!(result["url"], "https://mcp.example.com");
assert!(
result.get("auth").is_none(),
"auth stays Hermes-specific; stripped from unified format"
);
}
#[test]
fn test_merge_new_server_no_existing_extra_fields() {
let existing = json!({
"command": "old-cmd"
});
let new_spec = json!({
"command": "new-cmd",
"args": ["arg1"],
"enabled": true
});
let merged = merge_hermes_spec(&existing, &new_spec);
assert_eq!(merged["command"], "new-cmd");
assert_eq!(merged["args"][0], "arg1");
assert_eq!(merged["enabled"], true);
// No extra fields to preserve
assert!(merged.get("timeout").is_none());
}
}
-3
View File
@@ -9,12 +9,10 @@
//! - `codex` - Codex MCP 同步和导入(含 TOML 转换)
//! - `gemini` - Gemini MCP 同步和导入
//! - `opencode` - OpenCode MCP 同步和导入(含 local/remote 格式转换)
//! - `hermes` - Hermes MCP 同步和导入
mod claude;
mod codex;
mod gemini;
mod hermes;
mod opencode;
mod validation;
@@ -30,7 +28,6 @@ pub use gemini::{
import_from_gemini, remove_server_from_gemini, sync_enabled_to_gemini,
sync_single_server_to_gemini,
};
pub use hermes::{import_from_hermes, remove_server_from_hermes, sync_single_server_to_hermes};
pub use opencode::{
import_from_opencode, remove_server_from_opencode, sync_single_server_to_opencode,
};
-1
View File
@@ -259,7 +259,6 @@ pub fn import_from_opencode(config: &mut MultiAppConfig) -> Result<usize, AppErr
codex: false,
gemini: false,
opencode: true,
hermes: false,
},
description: None,
homepage: None,
-5
View File
@@ -914,7 +914,6 @@ pub fn set_tools_config(tools: &OpenClawToolsConfig) -> Result<OpenClawWriteOutc
#[cfg(test)]
mod tests {
use super::*;
use serial_test::serial;
use std::sync::{Mutex, OnceLock};
fn test_guard() -> std::sync::MutexGuard<'static, ()> {
@@ -967,7 +966,6 @@ mod tests {
}
#[test]
#[serial]
fn default_model_write_preserves_top_level_comments() {
let source = r#"{
// top-level comment
@@ -996,7 +994,6 @@ mod tests {
}
#[test]
#[serial]
fn default_model_noop_write_skips_backup() {
let source = r#"{
models: {
@@ -1031,7 +1028,6 @@ mod tests {
}
#[test]
#[serial]
fn save_detects_external_conflict() {
let source = r#"{
models: {
@@ -1054,7 +1050,6 @@ mod tests {
}
#[test]
#[serial]
fn remove_last_provider_writes_empty_providers_without_panic() {
let source = r#"{
models: {
+2 -2
View File
@@ -16,14 +16,14 @@ pub fn prompt_file_path(app: &AppType) -> Result<PathBuf, AppError> {
AppType::Gemini => get_gemini_dir(),
AppType::OpenCode => get_opencode_dir(),
AppType::OpenClaw => get_openclaw_dir(),
AppType::Hermes => crate::hermes_config::get_hermes_dir(),
};
let filename = match app {
AppType::Claude => "CLAUDE.md",
AppType::Codex => "AGENTS.md",
AppType::Gemini => "GEMINI.md",
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => "AGENTS.md",
AppType::OpenCode => "AGENTS.md",
AppType::OpenClaw => "AGENTS.md", // OpenClaw uses AGENTS.md for agent instructions
};
Ok(base_dir.join(filename))
-169
View File
@@ -443,41 +443,6 @@ pub fn sanitize_orphan_tool_results(mut body: Value) -> Value {
body
}
/// 请求前主动剥离所有 assistant 消息里的 thinking / redacted_thinking block
///
/// Copilot 的三条目标端点(`/chat/completions`、`/v1/responses`、`/v1/chat/completions`
/// 均为 OpenAI 兼容格式,不识别 Anthropic 的 thinking block。若原样转发,上游会
/// 拒绝并返回 invalid_request_error —— 届时 `thinking_rectifier` 才做反应式清理并
/// 重试。那次已经失败的请求依旧消耗一次 premium quota,所以此处提前剥离。
///
/// 与 `thinking_rectifier::rectify_anthropic_request` 的区别:
/// - 本函数只剥 thinking / redacted_thinking 两类 block,不触碰 signature,也不
/// 移除顶层 thinking 字段——那些是错误路径上的激进整流,常规路径不需要。
/// - 保持与 `merge_tool_results` / `sanitize_orphan_tool_results` 一致的"消费 body、
/// 返回新 body"签名,便于接入 forwarder 管道。
pub fn strip_thinking_blocks(mut body: Value) -> Value {
let Some(messages) = body.get_mut("messages").and_then(|m| m.as_array_mut()) else {
return body;
};
for msg in messages.iter_mut() {
if msg.get("role").and_then(|r| r.as_str()) != Some("assistant") {
continue;
}
let Some(content) = msg.get_mut("content").and_then(|c| c.as_array_mut()) else {
continue;
};
content.retain(|block| {
!matches!(
block.get("type").and_then(|t| t.as_str()),
Some("thinking") | Some("redacted_thinking")
)
});
}
body
}
// ─── 内部辅助 ─────────────────────────────────
/// 从请求体的 `system` 字段提取文本(处理 string/array 两种格式)。
@@ -1406,138 +1371,4 @@ mod tests {
assert_eq!(content[0]["type"], "text");
assert_eq!(content[1]["type"], "text");
}
// === strip_thinking_blocks 测试 ===
#[test]
fn test_strip_thinking_removes_assistant_thinking_blocks() {
let body = serde_json::json!({
"messages": [
{"role": "user", "content": [{"type": "text", "text": "hi"}]},
{"role": "assistant", "content": [
{"type": "thinking", "thinking": "let me ponder", "signature": "sig"},
{"type": "redacted_thinking", "data": "opaque"},
{"type": "text", "text": "hello"},
{"type": "tool_use", "id": "t1", "name": "read", "input": {}}
]}
]
});
let result = strip_thinking_blocks(body);
let content = result["messages"][1]["content"].as_array().unwrap();
assert_eq!(content.len(), 2);
assert_eq!(content[0]["type"], "text");
assert_eq!(content[1]["type"], "tool_use");
}
#[test]
fn test_strip_thinking_leaves_user_messages_untouched() {
// 仅处理 assistantuser 的 thinking 块(极少见,但可能)不动
let body = serde_json::json!({
"messages": [
{"role": "user", "content": [
{"type": "thinking", "thinking": "x"},
{"type": "text", "text": "hi"}
]}
]
});
let result = strip_thinking_blocks(body);
let content = result["messages"][0]["content"].as_array().unwrap();
assert_eq!(content.len(), 2);
}
#[test]
fn test_strip_thinking_handles_missing_messages() {
let body = serde_json::json!({ "model": "claude-3-5-sonnet" });
let result = strip_thinking_blocks(body.clone());
assert_eq!(result, body);
}
#[test]
fn test_strip_thinking_leaves_empty_content_array() {
// 仅含 thinking 的 assistant 消息剥完后 content 为空——保留上游自处理
let body = serde_json::json!({
"messages": [
{"role": "assistant", "content": [
{"type": "thinking", "thinking": "solo"}
]}
]
});
let result = strip_thinking_blocks(body);
let content = result["messages"][0]["content"].as_array().unwrap();
assert_eq!(content.len(), 0);
}
#[test]
fn test_strip_thinking_preserves_signature_on_non_thinking_blocks() {
// signature 留给 thinking_rectifier 在错误路径处理,此处不动
let body = serde_json::json!({
"messages": [
{"role": "assistant", "content": [
{"type": "tool_use", "id": "t1", "name": "x", "input": {}, "signature": "s"}
]}
]
});
let result = strip_thinking_blocks(body);
let block = &result["messages"][0]["content"][0];
assert_eq!(block["signature"], "s");
}
#[test]
fn test_strip_thinking_multiple_assistant_turns() {
let body = serde_json::json!({
"messages": [
{"role": "user", "content": [{"type": "text", "text": "q1"}]},
{"role": "assistant", "content": [
{"type": "thinking", "thinking": "a"},
{"type": "text", "text": "r1"}
]},
{"role": "user", "content": [{"type": "text", "text": "q2"}]},
{"role": "assistant", "content": [
{"type": "redacted_thinking", "data": "x"},
{"type": "text", "text": "r2"}
]}
]
});
let result = strip_thinking_blocks(body);
let a1 = result["messages"][1]["content"].as_array().unwrap();
let a2 = result["messages"][3]["content"].as_array().unwrap();
assert_eq!(a1.len(), 1);
assert_eq!(a1[0]["text"], "r1");
assert_eq!(a2.len(), 1);
assert_eq!(a2[0]["text"], "r2");
}
#[test]
fn test_strip_thinking_ignores_string_content() {
// assistant.content 是字符串而非 block 数组 — 历史请求或极简客户端会这样
// 不应崩溃,也不应转换结构
let body = serde_json::json!({
"messages": [
{"role": "assistant", "content": "plain text response"}
]
});
let result = strip_thinking_blocks(body.clone());
assert_eq!(result, body);
}
#[test]
fn test_strip_thinking_preserves_block_order() {
let body = serde_json::json!({
"messages": [
{"role": "assistant", "content": [
{"type": "thinking", "thinking": "pre"},
{"type": "text", "text": "A"},
{"type": "tool_use", "id": "t1", "name": "x", "input": {}},
{"type": "redacted_thinking", "data": "mid"},
{"type": "text", "text": "B"}
]}
]
});
let result = strip_thinking_blocks(body);
let content = result["messages"][0]["content"].as_array().unwrap();
assert_eq!(content.len(), 3);
assert_eq!(content[0]["text"], "A");
assert_eq!(content[1]["type"], "tool_use");
assert_eq!(content[2]["text"], "B");
}
}
+1 -1
View File
@@ -111,7 +111,7 @@ impl FailoverSwitchManager {
}
if let Ok(new_menu) = crate::tray::create_tray_menu(app, app_state.inner()) {
if let Some(tray) = app.tray_by_id(crate::tray::TRAY_ID) {
if let Some(tray) = app.tray_by_id("main") {
if let Err(e) = tray.set_menu(Some(new_menu)) {
log::error!("[Failover] 更新托盘菜单失败: {e}");
}
-6
View File
@@ -821,12 +821,6 @@ impl RequestForwarder {
mapped_body = super::copilot_optimizer::merge_tool_results(mapped_body);
}
// 3.5. 主动剥离 thinking block — Copilot 走 OpenAI 兼容端点不识别该块
// 避免上游拒绝后由 rectifier 反应式重试(首次请求已消耗 quota)
if self.copilot_optimizer_config.strip_thinking {
mapped_body = super::copilot_optimizer::strip_thinking_blocks(mapped_body);
}
// 4. Warmup 小模型降级
if self.copilot_optimizer_config.warmup_downgrade && classification.is_warmup {
log::info!(
+107 -16
View File
@@ -11,6 +11,7 @@ pub struct ModelMapping {
pub sonnet_model: Option<String>,
pub opus_model: Option<String>,
pub default_model: Option<String>,
pub reasoning_model: Option<String>,
}
impl ModelMapping {
@@ -39,6 +40,11 @@ impl ModelMapping {
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(String::from),
reasoning_model: env
.and_then(|e| e.get("ANTHROPIC_REASONING_MODEL"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(String::from),
}
}
@@ -48,13 +54,21 @@ impl ModelMapping {
|| self.sonnet_model.is_some()
|| self.opus_model.is_some()
|| self.default_model.is_some()
|| self.reasoning_model.is_some()
}
/// 根据原始模型名称获取映射后的模型
pub fn map_model(&self, original_model: &str) -> String {
pub fn map_model(&self, original_model: &str, has_thinking: bool) -> String {
let model_lower = original_model.to_lowercase();
// 1. 按模型类型匹配
// 1. thinking 模式优先使用推理模型
if has_thinking {
if let Some(ref m) = self.reasoning_model {
return m.clone();
}
}
// 2. 按模型类型匹配
if model_lower.contains("haiku") {
if let Some(ref m) = self.haiku_model {
return m.clone();
@@ -71,16 +85,35 @@ impl ModelMapping {
}
}
// 2. 默认模型
// 3. 默认模型
if let Some(ref m) = self.default_model {
return m.clone();
}
// 3. 无映射,保持原样
// 4. 无映射,保持原样
original_model.to_string()
}
}
/// 检测请求是否启用了 thinking 模式
pub fn has_thinking_enabled(body: &Value) -> bool {
match body
.get("thinking")
.and_then(|v| v.as_object())
.and_then(|o| o.get("type"))
.and_then(|t| t.as_str())
{
Some("enabled") | Some("adaptive") => true,
Some("disabled") | None => false,
Some(other) => {
log::warn!(
"[ModelMapper] 未知 thinking.type='{other}',按 disabled 处理以避免误路由 reasoning 模型"
);
false
}
}
}
/// 对请求体应用模型映射
///
/// 返回 (映射后的请求体, 原始模型名, 映射后模型名)
@@ -100,7 +133,8 @@ pub fn apply_model_mapping(
let original_model = body.get("model").and_then(|m| m.as_str()).map(String::from);
if let Some(ref original) = original_model {
let mapped = mapping.map_model(original);
let has_thinking = has_thinking_enabled(&body);
let mapped = mapping.map_model(original, has_thinking);
if mapped != *original {
log::debug!("[ModelMapper] 模型映射: {original} → {mapped}");
@@ -126,7 +160,8 @@ mod tests {
"ANTHROPIC_MODEL": "default-model",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "haiku-mapped",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "sonnet-mapped",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped"
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped",
"ANTHROPIC_REASONING_MODEL": "reasoning-model"
}
}),
website_url: None,
@@ -158,6 +193,27 @@ mod tests {
}
}
fn create_provider_with_reasoning_only() -> Provider {
Provider {
id: "test".to_string(),
name: "Test".to_string(),
settings_config: json!({
"env": {
"ANTHROPIC_REASONING_MODEL": "reasoning-only-model"
}
}),
website_url: None,
category: None,
created_at: None,
sort_index: None,
notes: None,
meta: None,
icon: None,
icon_color: None,
in_failover_queue: false,
}
}
#[test]
fn test_sonnet_mapping() {
let provider = create_provider_with_mapping();
@@ -187,29 +243,40 @@ mod tests {
}
#[test]
fn test_thinking_does_not_affect_model_mapping() {
// Issue #2081: thinking 参数不应影响模型映射
fn test_thinking_mode() {
let provider = create_provider_with_mapping();
let body = json!({
"model": "claude-sonnet-4-5",
"thinking": {"type": "enabled"}
});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "sonnet-mapped");
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
assert_eq!(result["model"], "reasoning-model");
assert_eq!(mapped, Some("reasoning-model".to_string()));
}
#[test]
fn test_thinking_adaptive_does_not_affect_model_mapping() {
// Issue #2081: adaptive thinking 也不应影响模型映射
let provider = create_provider_with_mapping();
fn test_reasoning_only_mapping_in_thinking_mode() {
let provider = create_provider_with_reasoning_only();
let body = json!({
"model": "claude-sonnet-4-5",
"thinking": {"type": "adaptive"}
"thinking": {"type": "enabled"}
});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "sonnet-mapped");
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
assert_eq!(result["model"], "reasoning-only-model");
assert_eq!(mapped, Some("reasoning-only-model".to_string()));
}
#[test]
fn test_reasoning_only_mapping_does_not_affect_non_thinking() {
let provider = create_provider_with_reasoning_only();
let body = json!({
"model": "claude-sonnet-4-5",
"thinking": {"type": "disabled"}
});
let (result, original, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "claude-sonnet-4-5");
assert_eq!(original, Some("claude-sonnet-4-5".to_string()));
assert!(mapped.is_none());
}
#[test]
@@ -243,6 +310,30 @@ mod tests {
assert!(mapped.is_none());
}
#[test]
fn test_thinking_adaptive() {
let provider = create_provider_with_mapping();
let body = json!({
"model": "claude-sonnet-4-5",
"thinking": {"type": "adaptive"}
});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "reasoning-model");
assert_eq!(mapped, Some("reasoning-model".to_string()));
}
#[test]
fn test_thinking_unknown_type() {
let provider = create_provider_with_mapping();
let body = json!({
"model": "claude-sonnet-4-5",
"thinking": {"type": "some_future_type"}
});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "sonnet-mapped");
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
}
#[test]
fn test_case_insensitive() {
let provider = create_provider_with_mapping();
@@ -203,7 +203,6 @@ impl From<&CodexAccountData> for GitHubAccount {
.unwrap_or_else(|| format!("ChatGPT ({})", &data.account_id)),
avatar_url: None,
authenticated_at: data.authenticated_at,
github_domain: "github.com".to_string(),
}
}
}
+53 -327
View File
@@ -24,114 +24,26 @@ use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
/// GitHub OAuth 客户端 IDVS Code- 用于 github.com
/// GitHub OAuth 客户端 IDVS Code 使用的 ID
const GITHUB_CLIENT_ID: &str = "Iv1.b507a08c87ecfe98";
/// GitHub OAuth 客户端 ID(与 OpenCode 相同)- 在所有 GHES Copilot 实例上预注册
const GITHUB_CLIENT_ID_GHES: &str = "Ov23li8tweQw6odWQebz";
/// 默认 GitHub 域名
const DEFAULT_GITHUB_DOMAIN: &str = "github.com";
/// 根据域名选择 OAuth 客户端 ID
fn github_client_id(domain: &str) -> &'static str {
if domain == DEFAULT_GITHUB_DOMAIN {
GITHUB_CLIENT_ID
} else {
GITHUB_CLIENT_ID_GHES
}
}
fn default_github_domain() -> String {
DEFAULT_GITHUB_DOMAIN.to_string()
}
/// GitHub 设备码 URL
fn github_device_code_url(domain: &str) -> String {
format!("https://{domain}/login/device/code")
}
const GITHUB_DEVICE_CODE_URL: &str = "https://github.com/login/device/code";
/// GitHub OAuth Token URL
fn github_oauth_token_url(domain: &str) -> String {
format!("https://{domain}/login/oauth/access_token")
}
/// GitHub API 基础 URLgithub.com 用 api.github.comGHES 用 {domain}/api/v3
fn github_api_base(domain: &str) -> String {
if domain == DEFAULT_GITHUB_DOMAIN {
"https://api.github.com".to_string()
} else {
format!("https://{domain}/api/v3")
}
}
const GITHUB_OAUTH_TOKEN_URL: &str = "https://github.com/login/oauth/access_token";
/// Copilot Token URL
fn copilot_token_url(domain: &str) -> String {
format!("{}/copilot_internal/v2/token", github_api_base(domain))
}
const COPILOT_TOKEN_URL: &str = "https://api.github.com/copilot_internal/v2/token";
/// GitHub User API URL
fn github_user_url(domain: &str) -> String {
format!("{}/user", github_api_base(domain))
}
/// Copilot 使用量 API URL
fn copilot_usage_url(domain: &str) -> String {
format!("{}/copilot_internal/user", github_api_base(domain))
}
/// Copilot API 基础地址(github.com 用 api.githubcopilot.comGHES 用 copilot-api.{domain}
fn copilot_api_base(domain: &str) -> String {
if domain == DEFAULT_GITHUB_DOMAIN {
"https://api.githubcopilot.com".to_string()
} else {
format!("https://copilot-api.{domain}")
}
}
const GITHUB_USER_URL: &str = "https://api.github.com/user";
/// Token 刷新提前量(秒)
const TOKEN_REFRESH_BUFFER_SECONDS: i64 = 60;
/// 判断是否为 GitHub Enterprise Server(非 github.com
fn is_ghes(domain: &str) -> bool {
domain != DEFAULT_GITHUB_DOMAIN
}
/// 归一化 GitHub 域名(SSOT):
/// - 小写化
/// - 剥离协议(https:// http://
/// - 剥离尾斜杠、path、query、fragment
/// - 拒绝包含 userinfo@)的输入
/// - 保留端口号(如有)
fn normalize_github_domain(raw: &str) -> Result<String, CopilotAuthError> {
let s = raw.trim();
// 剥离协议
let s = s
.strip_prefix("https://")
.or_else(|| s.strip_prefix("http://"))
.unwrap_or(s);
// 取 host 部分(到第一个 / 或 ? 或 #)
let host = s.split(&['/', '?', '#'][..]).next().unwrap_or(s);
// 拒绝 userinfo
if host.contains('@') {
return Err(CopilotAuthError::InvalidDomain(raw.to_string()));
}
let normalized = host.to_lowercase();
if normalized.is_empty() {
return Err(CopilotAuthError::InvalidDomain(raw.to_string()));
}
Ok(normalized)
}
/// 生成复合账号 ID,确保不同 GHES 实例的 user ID 不会冲突。
/// github.com 账号保持原格式(向后兼容),GHES 账号使用 `domain:user_id` 格式。
fn composite_account_id(domain: &str, user_id: u64) -> String {
if domain == DEFAULT_GITHUB_DOMAIN {
user_id.to_string()
} else {
format!("{}:{}", domain, user_id)
}
}
/// Copilot API 端点
const COPILOT_MODELS_URL: &str = "https://api.githubcopilot.com/models";
/// Copilot API Header 常量
pub const COPILOT_EDITOR_VERSION: &str = "vscode/1.110.1";
@@ -140,6 +52,12 @@ pub const COPILOT_USER_AGENT: &str = "GitHubCopilotChat/0.38.2";
pub const COPILOT_API_VERSION: &str = "2025-10-01";
pub const COPILOT_INTEGRATION_ID: &str = "vscode-chat";
/// Copilot 使用量 API URL
const COPILOT_USAGE_URL: &str = "https://api.github.com/copilot_internal/user";
/// 默认 Copilot API 端点
const DEFAULT_COPILOT_API_ENDPOINT: &str = "https://api.githubcopilot.com";
/// Copilot 使用量响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CopilotUsageResponse {
@@ -251,9 +169,6 @@ pub enum CopilotAuthError {
#[error("账号不存在: {0}")]
AccountNotFound(String),
#[error("无效的 GitHub 域名: {0}")]
InvalidDomain(String),
}
impl From<reqwest::Error> for CopilotAuthError {
@@ -338,19 +253,15 @@ pub struct GitHubAccount {
pub avatar_url: Option<String>,
/// 认证时间戳
pub authenticated_at: i64,
/// GitHub 域名(github.com 或 GHES 域名)
#[serde(default = "default_github_domain")]
pub github_domain: String,
}
impl From<&GitHubAccountData> for GitHubAccount {
fn from(data: &GitHubAccountData) -> Self {
GitHubAccount {
id: composite_account_id(&data.github_domain, data.user.id),
id: data.user.id.to_string(),
login: data.user.login.clone(),
avatar_url: data.user.avatar_url.clone(),
authenticated_at: data.authenticated_at,
github_domain: data.github_domain.clone(),
}
}
}
@@ -384,9 +295,6 @@ struct GitHubAccountData {
pub user: GitHubUser,
/// 认证时间戳
pub authenticated_at: i64,
/// GitHub 域名(github.com 或 GHES 域名)
#[serde(default = "default_github_domain")]
pub github_domain: String,
}
/// 持久化存储结构(v3 多账号 + 默认账号格式)
@@ -529,16 +437,14 @@ impl CopilotAuthManager {
&self,
github_token: String,
user: GitHubUser,
github_domain: String,
) -> Result<GitHubAccount, CopilotAuthError> {
let account_id = composite_account_id(&github_domain, user.id);
let account_id = user.id.to_string();
let now = chrono::Utc::now().timestamp();
let account_data = GitHubAccountData {
github_token,
user: user.clone(),
authenticated_at: now,
github_domain: github_domain.clone(),
};
let account = GitHubAccount {
@@ -546,7 +452,6 @@ impl CopilotAuthManager {
login: user.login.clone(),
avatar_url: user.avatar_url.clone(),
authenticated_at: now,
github_domain,
};
{
@@ -592,25 +497,15 @@ impl CopilotAuthManager {
// ==================== 设备码流程 ====================
/// 启动设备码流程
pub async fn start_device_flow(
&self,
github_domain: Option<&str>,
) -> Result<GitHubDeviceCodeResponse, CopilotAuthError> {
let domain = match github_domain {
Some(d) => normalize_github_domain(d)?,
None => DEFAULT_GITHUB_DOMAIN.to_string(),
};
log::info!("[CopilotAuth] 启动设备码流程 (domain: {domain})");
pub async fn start_device_flow(&self) -> Result<GitHubDeviceCodeResponse, CopilotAuthError> {
log::info!("[CopilotAuth] 启动设备码流程");
let response = self
.http_client
.post(github_device_code_url(&domain))
.post(GITHUB_DEVICE_CODE_URL)
.header("Accept", "application/json")
.header("User-Agent", COPILOT_USER_AGENT)
.form(&[
("client_id", github_client_id(&domain)),
("scope", "read:user"),
])
.form(&[("client_id", GITHUB_CLIENT_ID), ("scope", "read:user")])
.send()
.await?;
@@ -639,21 +534,16 @@ impl CopilotAuthManager {
pub async fn poll_for_token(
&self,
device_code: &str,
github_domain: Option<&str>,
) -> Result<Option<GitHubAccount>, CopilotAuthError> {
let domain = match github_domain {
Some(d) => normalize_github_domain(d)?,
None => DEFAULT_GITHUB_DOMAIN.to_string(),
};
log::debug!("[CopilotAuth] 轮询 OAuth Token (domain: {domain})");
log::debug!("[CopilotAuth] 轮询 OAuth Token");
let response = self
.http_client
.post(github_oauth_token_url(&domain))
.post(GITHUB_OAUTH_TOKEN_URL)
.header("Accept", "application/json")
.header("User-Agent", COPILOT_USER_AGENT)
.form(&[
("client_id", github_client_id(&domain)),
("client_id", GITHUB_CLIENT_ID),
("device_code", device_code),
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
])
@@ -688,28 +578,14 @@ impl CopilotAuthManager {
log::info!("[CopilotAuth] OAuth Token 获取成功");
// 获取用户信息
let user = self
.fetch_user_info_with_token(&access_token, &domain)
.await?;
let user = self.fetch_user_info_with_token(&access_token).await?;
// GHES 无需换取 Copilot Token,直接使用 OAuth token 作为 Bearer
// 参考 OpenCode 的实现:GHE Copilot 直接用 OAuth token 调用 copilot-api.{domain}
if !is_ghes(&domain) {
// github.com:验证 Copilot 订阅(获取 Copilot Token
self.fetch_copilot_token_with_github_token(
&access_token,
&user.id.to_string(),
&domain,
)
// 验证 Copilot 订阅(获取 Copilot Token
self.fetch_copilot_token_with_github_token(&access_token, &user.id.to_string())
.await?;
} else {
log::info!("[CopilotAuth] GHES 账号,跳过 Copilot Token 兑换,直接使用 OAuth token");
}
// 添加账号
let account = self
.add_account_internal(access_token, user, domain)
.await?;
let account = self.add_account_internal(access_token, user).await?;
Ok(Some(account))
}
@@ -724,16 +600,6 @@ impl CopilotAuthManager {
// 确保迁移完成
self.ensure_migration_complete().await?;
// GHES 账号直接使用 GitHub OAuth token,无需 Copilot token 交换
let domain = self.get_account_domain(account_id).await;
if is_ghes(&domain) {
let accounts = self.accounts.read().await;
return accounts
.get(account_id)
.map(|a| a.github_token.clone())
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()));
}
// 检查缓存的 token
{
let tokens = self.copilot_tokens.read().await;
@@ -761,16 +627,16 @@ impl CopilotAuthManager {
}
// 获取账号的 GitHub token
let (github_token, domain) = {
let github_token = {
let accounts = self.accounts.read().await;
let account = accounts
accounts
.get(account_id)
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?;
(account.github_token.clone(), account.github_domain.clone())
.map(|a| a.github_token.clone())
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?
};
// 刷新 Copilot token
self.fetch_copilot_token_with_github_token(&github_token, account_id, &domain)
self.fetch_copilot_token_with_github_token(&github_token, account_id)
.await?;
// 返回新 token
@@ -821,19 +687,11 @@ impl CopilotAuthManager {
) -> Result<Vec<CopilotModel>, CopilotAuthError> {
let copilot_token = self.get_valid_token_for_account(account_id).await?;
// 使用 get_api_endpoint() 动态解析 Copilot API 基础 URL。
// 对于 github.com 账号,会查询 /copilot_internal/user 获取 endpoints.api 字段。
// 对于 GHES 账号,/copilot_internal/user 可能不返回 endpoints——此时
// get_api_endpoint() 会回退到 copilot_api_base(&domain),与之前的静态 URL
// 拼接结果一致。该回退行为是安全且符合预期的。
let api_base = self.get_api_endpoint(account_id).await;
let models_url = format!("{}/models", api_base);
log::info!("[CopilotAuth] 获取账号 {account_id} 的 Copilot 可用模型");
let response = self
.http_client
.get(&models_url)
.get(COPILOT_MODELS_URL)
.header("Authorization", format!("Bearer {copilot_token}"))
.header("Content-Type", "application/json")
.header("copilot-integration-id", "vscode-chat")
@@ -909,19 +767,19 @@ impl CopilotAuthManager {
&self,
account_id: &str,
) -> Result<CopilotUsageResponse, CopilotAuthError> {
let (github_token, domain) = {
let github_token = {
let accounts = self.accounts.read().await;
let account = accounts
accounts
.get(account_id)
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?;
(account.github_token.clone(), account.github_domain.clone())
.map(|a| a.github_token.clone())
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?
};
log::info!("[CopilotAuth] 获取账号 {account_id} 的 Copilot 使用量");
let response = self
.http_client
.get(copilot_usage_url(&domain))
.get(COPILOT_USAGE_URL)
.header("Authorization", format!("token {github_token}"))
.header("Content-Type", "application/json")
.header("editor-version", COPILOT_EDITOR_VERSION)
@@ -1004,8 +862,7 @@ impl CopilotAuthManager {
log::debug!(
"[CopilotAuth] 获取账号 {account_id} 动态 API 端点失败: {e},使用默认值"
);
let domain = self.get_account_domain(account_id).await;
copilot_api_base(&domain)
DEFAULT_COPILOT_API_ENDPOINT.to_string()
}
}
}
@@ -1016,27 +873,24 @@ impl CopilotAuthManager {
match self.resolve_default_account_id().await {
Some(id) => self.get_api_endpoint(&id).await,
None => {
// 无账号时回退到 github.com 的默认端点
copilot_api_base(DEFAULT_GITHUB_DOMAIN)
}
None => DEFAULT_COPILOT_API_ENDPOINT.to_string(),
}
}
async fn fetch_and_cache_endpoint(&self, account_id: &str) -> Result<String, CopilotAuthError> {
let (github_token, domain) = {
let github_token = {
let accounts = self.accounts.read().await;
let account = accounts
accounts
.get(account_id)
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?;
(account.github_token.clone(), account.github_domain.clone())
.map(|a| a.github_token.clone())
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?
};
log::debug!("[CopilotAuth] 为账号 {account_id} 惰性拉取动态 API 端点");
let response = self
.http_client
.get(copilot_usage_url(&domain))
.get(COPILOT_USAGE_URL)
.header("Authorization", format!("token {github_token}"))
.header("Content-Type", "application/json")
.header("editor-version", COPILOT_EDITOR_VERSION)
@@ -1064,7 +918,7 @@ impl CopilotAuthManager {
let endpoint = match usage.endpoints {
Some(endpoints) => endpoints.api.clone(),
None => copilot_api_base(&domain),
None => DEFAULT_COPILOT_API_ENDPOINT.to_string(),
};
// 缓存端点(包括默认值),避免重复请求
@@ -1221,15 +1075,6 @@ impl CopilotAuthManager {
Self::fallback_default_account_id(&accounts)
}
/// 获取指定账号的 GitHub 域名
async fn get_account_domain(&self, account_id: &str) -> String {
let accounts = self.accounts.read().await;
accounts
.get(account_id)
.map(|a| a.github_domain.clone())
.unwrap_or_else(|| DEFAULT_GITHUB_DOMAIN.to_string())
}
async fn get_refresh_lock(&self, account_id: &str) -> Arc<Mutex<()>> {
{
let refresh_locks = self.refresh_locks.read().await;
@@ -1310,11 +1155,10 @@ impl CopilotAuthManager {
async fn fetch_user_info_with_token(
&self,
github_token: &str,
domain: &str,
) -> Result<GitHubUser, CopilotAuthError> {
let response = self
.http_client
.get(github_user_url(domain))
.get(GITHUB_USER_URL)
.header("Authorization", format!("token {github_token}"))
.header("User-Agent", COPILOT_USER_AGENT)
.header("Editor-Version", COPILOT_EDITOR_VERSION)
@@ -1341,13 +1185,12 @@ impl CopilotAuthManager {
&self,
github_token: &str,
account_id: &str,
domain: &str,
) -> Result<(), CopilotAuthError> {
log::debug!("[CopilotAuth] 获取账号 {account_id} 的 Copilot Token (domain: {domain})");
log::debug!("[CopilotAuth] 获取账号 {account_id} 的 Copilot Token");
let response = self
.http_client
.get(copilot_token_url(domain))
.get(COPILOT_TOKEN_URL)
.header("Authorization", format!("token {github_token}"))
.header("User-Agent", COPILOT_USER_AGENT)
.header("Editor-Version", COPILOT_EDITOR_VERSION)
@@ -1441,32 +1284,20 @@ impl CopilotAuthManager {
log::info!("[CopilotAuth] 执行旧格式迁移");
// 获取用户信息
match self
.fetch_user_info_with_token(&legacy_token, DEFAULT_GITHUB_DOMAIN)
.await
{
match self.fetch_user_info_with_token(&legacy_token).await {
Ok(user) => {
let account_id = composite_account_id(DEFAULT_GITHUB_DOMAIN, user.id);
let account_id = user.id.to_string();
// 尝试获取 Copilot token 验证订阅
if let Err(e) = self
.fetch_copilot_token_with_github_token(
&legacy_token,
&account_id,
DEFAULT_GITHUB_DOMAIN,
)
.fetch_copilot_token_with_github_token(&legacy_token, &account_id)
.await
{
log::warn!("[CopilotAuth] 迁移时验证 Copilot 订阅失败: {e}");
}
// 添加账号
self.add_account_internal(
legacy_token,
user,
DEFAULT_GITHUB_DOMAIN.to_string(),
)
.await?;
self.add_account_internal(legacy_token, user).await?;
self.set_migration_error(None).await;
log::info!("[CopilotAuth] 旧格式迁移完成");
@@ -1556,7 +1387,6 @@ mod tests {
login: "testuser".to_string(),
avatar_url: Some("https://example.com/avatar.png".to_string()),
authenticated_at: 1234567890,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
}],
default_account_id: Some("12345".to_string()),
migration_error: None,
@@ -1590,7 +1420,6 @@ mod tests {
avatar_url: Some("https://example.com/alice.png".to_string()),
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
accounts.insert(
@@ -1603,7 +1432,6 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000001,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
@@ -1651,7 +1479,6 @@ mod tests {
avatar_url: Some("https://example.com/avatar.png".to_string()),
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
};
let account = GitHubAccount::from(&data);
@@ -1677,7 +1504,6 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
accounts.insert(
@@ -1690,7 +1516,6 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000001,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
@@ -1721,7 +1546,6 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
}
@@ -1806,7 +1630,6 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
}
@@ -1841,7 +1664,6 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
}
@@ -1924,7 +1746,6 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
}
@@ -1980,7 +1801,7 @@ mod tests {
let manager = CopilotAuthManager::new(temp_dir.path().to_path_buf());
let endpoint = manager.get_api_endpoint("12345").await;
assert_eq!(endpoint, copilot_api_base(DEFAULT_GITHUB_DOMAIN));
assert_eq!(endpoint, DEFAULT_COPILOT_API_ENDPOINT);
}
#[tokio::test]
@@ -1996,99 +1817,4 @@ mod tests {
other => panic!("期望 AccountNotFound 错误,实际: {other:?}"),
}
}
#[test]
fn test_normalize_github_domain() {
// 基本用法
assert_eq!(normalize_github_domain("github.com").unwrap(), "github.com");
assert_eq!(
normalize_github_domain("company.ghe.com").unwrap(),
"company.ghe.com"
);
// 剥离协议
assert_eq!(
normalize_github_domain("https://company.ghe.com").unwrap(),
"company.ghe.com"
);
assert_eq!(
normalize_github_domain("http://company.ghe.com").unwrap(),
"company.ghe.com"
);
// 小写化
assert_eq!(normalize_github_domain("GitHub.COM").unwrap(), "github.com");
assert_eq!(
normalize_github_domain("Company.GHE.Com").unwrap(),
"company.ghe.com"
);
// 剥离尾斜杠和 path
assert_eq!(
normalize_github_domain("company.ghe.com/").unwrap(),
"company.ghe.com"
);
assert_eq!(
normalize_github_domain("company.ghe.com/api/v3").unwrap(),
"company.ghe.com"
);
// 剥离 query 和 fragment
assert_eq!(
normalize_github_domain("company.ghe.com?foo=bar").unwrap(),
"company.ghe.com"
);
assert_eq!(
normalize_github_domain("company.ghe.com#section").unwrap(),
"company.ghe.com"
);
// 保留端口
assert_eq!(
normalize_github_domain("company.ghe.com:8443").unwrap(),
"company.ghe.com:8443"
);
// 拒绝 userinfo
assert!(normalize_github_domain("user@company.ghe.com").is_err());
// 拒绝空输入
assert!(normalize_github_domain("").is_err());
assert!(normalize_github_domain(" ").is_err());
}
#[test]
fn test_composite_account_id() {
// github.com 保持原格式(向后兼容)
assert_eq!(composite_account_id("github.com", 12345), "12345");
// GHES 使用复合格式
assert_eq!(
composite_account_id("company.ghe.com", 12345),
"company.ghe.com:12345"
);
// 不同 GHES 实例,相同 user ID,不冲突
assert_ne!(
composite_account_id("a.ghe.com", 1),
composite_account_id("b.ghe.com", 1)
);
}
#[test]
fn test_github_account_from_data_ghes_uses_composite_id() {
let data = GitHubAccountData {
github_token: "gho_test".to_string(),
user: GitHubUser {
login: "testuser".to_string(),
id: 99999,
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: "company.ghe.com".to_string(),
};
let account = GitHubAccount::from(&data);
assert_eq!(account.id, "company.ghe.com:99999");
}
}
+13 -5
View File
@@ -174,9 +174,13 @@ impl ProviderType {
}
ProviderType::Gemini
}
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy, fallback to Codex-like type
ProviderType::Codex
AppType::OpenCode => {
// OpenCode doesn't support proxy, but return a default type for completeness
ProviderType::Codex // Fallback to Codex-like type
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy, but return a default type for completeness
ProviderType::Codex // Fallback to Codex-like type
}
}
}
@@ -228,8 +232,12 @@ pub fn get_adapter(app_type: &AppType) -> Box<dyn ProviderAdapter> {
AppType::Claude => Box::new(ClaudeAdapter::new()),
AppType::Codex => Box::new(CodexAdapter::new()),
AppType::Gemini => Box::new(GeminiAdapter::new()),
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy, fallback to Codex adapter
AppType::OpenCode => {
// OpenCode doesn't support proxy, fallback to Codex adapter
Box::new(CodexAdapter::new())
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy, fallback to Codex adapter
Box::new(CodexAdapter::new())
}
}
@@ -203,7 +203,6 @@ pub(crate) fn map_responses_stop_reason(
{
"max_tokens"
}
"incomplete" => "end_turn",
_ => "end_turn",
})
}
+2 -2
View File
@@ -7,7 +7,7 @@ use serde_json::{json, Value};
///
/// 三路径分发:
/// - skip: haiku 模型直接跳过
/// - adaptive: opus-4-7 / opus-4-6 / sonnet-4-6 使用 adaptive thinking
/// - adaptive: opus-4-6 / sonnet-4-6 使用 adaptive thinking
/// - legacy: 其他模型注入 enabled thinking + budget_tokens
pub fn optimize(body: &mut Value, config: &OptimizerConfig) {
if !config.thinking_optimizer {
@@ -24,7 +24,7 @@ pub fn optimize(body: &mut Value, config: &OptimizerConfig) {
return;
}
if model.contains("opus-4-7") || model.contains("opus-4-6") || model.contains("sonnet-4-6") {
if model.contains("opus-4-6") || model.contains("sonnet-4-6") {
log::info!("[OPT] thinking: adaptive({model})");
body["thinking"] = json!({"type": "adaptive"});
body["output_config"] = json!({"effort": "max"});
+2 -9
View File
@@ -298,15 +298,9 @@ pub struct CopilotOptimizerConfig {
/// Warmup 小模型降级(默认开启 — 与参考实现对齐,避免探针请求消耗 premium quota
#[serde(default = "default_true")]
pub warmup_downgrade: bool,
/// Warmup 降级使用的模型(默认 "gpt-5-mini"
/// Warmup 降级使用的模型(默认 "gpt-4o-mini"
#[serde(default = "default_warmup_model")]
pub warmup_model: String,
/// 请求前主动剥离 assistant 消息里的 thinking / redacted_thinking block
///
/// Copilot 走 OpenAI 兼容端点,thinking block 会被上游拒绝并触发 rectifier 反应式
/// 重试,那时第一次请求已经消耗了一次 premium quota。主动剥离避免这次浪费。
#[serde(default = "default_true")]
pub strip_thinking: bool,
}
fn default_warmup_model() -> String {
@@ -323,8 +317,7 @@ impl Default for CopilotOptimizerConfig {
deterministic_request_id: true,
subagent_detection: true,
warmup_downgrade: true,
warmup_model: "gpt-5-mini".to_string(),
strip_thinking: true,
warmup_model: "gpt-4o-mini".to_string(),
}
}
}
-3
View File
@@ -130,9 +130,6 @@ impl ConfigService {
// OpenClaw uses additive mode, no live sync needed
// OpenClaw providers are managed directly in the config file
}
AppType::Hermes => {
// Hermes uses additive mode, no live sync needed
}
}
Ok(())
-47
View File
@@ -40,9 +40,6 @@ impl McpService {
if prev_apps.opencode && !server.apps.opencode {
Self::remove_server_from_app(state, &server.id, &AppType::OpenCode)?;
}
if prev_apps.hermes && !server.apps.hermes {
Self::remove_server_from_app(state, &server.id, &AppType::Hermes)?;
}
// 同步到各个启用的应用
Self::sync_server_to_apps(state, &server)?;
@@ -131,9 +128,6 @@ impl McpService {
// Skip for now
log::debug!("OpenClaw MCP support is still in development, skipping sync");
}
AppType::Hermes => {
mcp::sync_single_server_to_hermes(&Default::default(), &server.id, &server.server)?;
}
}
Ok(())
}
@@ -163,9 +157,6 @@ impl McpService {
// OpenClaw MCP support is still in development
log::debug!("OpenClaw MCP support is still in development, skipping remove");
}
AppType::Hermes => {
mcp::remove_server_from_hermes(id)?;
}
}
Ok(())
}
@@ -390,42 +381,4 @@ impl McpService {
Ok(new_count)
}
/// 从 Hermes 导入 MCP
pub fn import_from_hermes(state: &AppState) -> Result<usize, AppError> {
// 创建临时 MultiAppConfig 用于导入
let mut temp_config = crate::app_config::MultiAppConfig::default();
// 调用导入逻辑(从 mcp/hermes.rs
let count = crate::mcp::import_from_hermes(&mut temp_config)?;
let mut new_count = 0;
// 如果有导入的服务器,保存到数据库
if count > 0 {
if let Some(servers) = &temp_config.mcp.servers {
let mut existing = state.db.get_all_mcp_servers()?;
for server in servers.values() {
// 已存在:仅启用 Hermes,不覆盖其他字段(与导入模块语义保持一致)
let to_save = if let Some(existing_server) = existing.get(&server.id) {
let mut merged = existing_server.clone();
merged.apps.hermes = true;
merged
} else {
// 真正的新服务器
new_count += 1;
server.clone()
};
state.db.save_mcp_server(&to_save)?;
existing.insert(to_save.id.clone(), to_save.clone());
// 同步到对应应用 live 配置
Self::sync_server_to_apps(state, &to_save)?;
}
}
}
Ok(new_count)
}
}
+5 -92
View File
@@ -42,8 +42,6 @@ pub(crate) fn provider_exists_in_live_config(
.map(|providers| providers.contains_key(provider_id)),
AppType::OpenClaw => crate::openclaw_config::get_providers()
.map(|providers| providers.contains_key(provider_id)),
AppType::Hermes => crate::hermes_config::get_providers()
.map(|providers| providers.contains_key(provider_id)),
_ => Ok(false),
}
}
@@ -347,7 +345,7 @@ fn settings_contain_common_config(app_type: &AppType, settings: &Value, snippet:
}
_ => false,
},
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => false,
AppType::OpenCode | AppType::OpenClaw => false,
}
}
@@ -417,7 +415,7 @@ pub(crate) fn remove_common_config_from_settings(
}
Ok(result)
}
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => Ok(settings.clone()),
AppType::OpenCode | AppType::OpenClaw => Ok(settings.clone()),
}
}
@@ -472,7 +470,7 @@ fn apply_common_config_to_settings(
}
Ok(result)
}
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => Ok(settings.clone()),
AppType::OpenCode | AppType::OpenClaw => Ok(settings.clone()),
}
}
@@ -792,10 +790,6 @@ pub(crate) fn write_live_snapshot(app_type: &AppType, provider: &Provider) -> Re
}
}
}
AppType::Hermes => {
crate::hermes_config::set_provider(&provider.id, provider.settings_config.clone())?;
log::debug!("Hermes provider '{}' written to live config", provider.id);
}
}
Ok(())
}
@@ -991,19 +985,6 @@ pub fn read_live_settings(app_type: AppType) -> Result<Value, AppError> {
let config = read_openclaw_config()?;
Ok(config)
}
AppType::Hermes => {
let config_path = crate::hermes_config::get_hermes_config_path();
if !config_path.exists() {
return Err(AppError::localized(
"hermes.config.missing",
"Hermes 配置文件不存在",
"Hermes configuration file not found",
));
}
let yaml_config = crate::hermes_config::read_hermes_config()?;
let config = crate::hermes_config::yaml_to_json(&yaml_config)?;
Ok(config)
}
}
}
@@ -1086,8 +1067,8 @@ pub fn import_default_config(state: &AppState, app_type: AppType) -> Result<bool
"config": config_obj
})
}
// OpenCode, OpenClaw and Hermes use additive mode and are handled by early return above
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// OpenCode and OpenClaw use additive mode and are handled by early return above
AppType::OpenCode | AppType::OpenClaw => {
unreachable!("additive mode apps are handled by early return")
}
};
@@ -1335,74 +1316,6 @@ pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, Ap
Ok(imported)
}
/// Import all providers from Hermes live config to database
///
/// This imports existing providers from ~/.hermes/config.yaml
/// into the CC Switch database. Each provider found will be added to the
/// database with is_current set to false.
pub fn import_hermes_providers_from_live(state: &AppState) -> Result<usize, AppError> {
use crate::hermes_config;
let providers = hermes_config::get_providers()?;
if providers.is_empty() {
return Ok(0);
}
let mut imported = 0;
let existing_ids = state.db.get_provider_ids("hermes")?;
for (name, config) in providers {
// Validate: skip entries with empty name
if name.trim().is_empty() {
log::warn!("Skipping Hermes provider with empty name");
continue;
}
// Skip if already exists in database
if existing_ids.contains(&name) {
log::debug!("Hermes provider '{name}' already exists in database, skipping");
continue;
}
// Create provider
let mut provider = Provider::with_id(name.clone(), name.clone(), config, None);
provider.meta = Some(crate::provider::ProviderMeta {
live_config_managed: Some(true),
..Default::default()
});
// Save to database
if let Err(e) = state.db.save_provider("hermes", &provider) {
log::warn!("Failed to import Hermes provider '{name}': {e}");
continue;
}
imported += 1;
log::info!("Imported Hermes provider '{name}' from live config");
}
Ok(imported)
}
/// Remove a Hermes provider from live config
///
/// This removes a specific provider from ~/.hermes/config.yaml
/// without affecting other providers in the file.
pub fn remove_hermes_provider_from_live(provider_id: &str) -> Result<(), AppError> {
use crate::hermes_config;
// Check if Hermes config directory exists
if !hermes_config::get_hermes_dir().exists() {
log::debug!("Hermes config directory doesn't exist, skipping removal of '{provider_id}'");
return Ok(());
}
hermes_config::remove_provider(provider_id)?;
log::info!("Hermes provider '{provider_id}' removed from live config");
Ok(())
}
/// Remove an OpenClaw provider from live config
///
/// This removes a specific provider from ~/.openclaw/openclaw.json
+6 -43
View File
@@ -21,7 +21,7 @@ use crate::store::AppState;
// Re-export sub-module functions for external access
pub use live::{
import_default_config, import_hermes_providers_from_live, import_openclaw_providers_from_live,
import_default_config, import_openclaw_providers_from_live,
import_opencode_providers_from_live, read_live_settings, sync_current_to_live,
};
@@ -35,8 +35,7 @@ pub(crate) use live::{
// Internal re-exports
use live::{
remove_hermes_provider_from_live, remove_openclaw_provider_from_live,
remove_opencode_provider_from_live, write_gemini_live,
remove_openclaw_provider_from_live, remove_opencode_provider_from_live, write_gemini_live,
};
use usage::validate_usage_script;
@@ -1283,7 +1282,6 @@ impl ProviderService {
match app_type {
AppType::OpenCode => remove_opencode_provider_from_live(id)?,
AppType::OpenClaw => remove_openclaw_provider_from_live(id)?,
AppType::Hermes => remove_hermes_provider_from_live(id)?,
_ => {}
}
}
@@ -1346,9 +1344,6 @@ impl ProviderService {
AppType::OpenClaw => {
remove_openclaw_provider_from_live(id)?;
}
AppType::Hermes => {
remove_hermes_provider_from_live(id)?;
}
_ => {
return Err(AppError::Message(format!(
"App {} does not support remove from live config",
@@ -1523,25 +1518,6 @@ impl ProviderService {
// Sync to live (write_gemini_live handles security flag internally for Gemini)
write_live_with_common_config(state.db.as_ref(), &app_type, provider)?;
// Hermes is additive, so "switching" doesn't overwrite a live config file
// — we instead update the top-level `model:` section to point at this
// provider's first declared model. Without this, clicking "switch" would
// only shuffle entries in custom_providers[] while Hermes keeps using
// whatever `model.provider` was set before.
if matches!(app_type, AppType::Hermes) {
if let Err(e) =
crate::hermes_config::apply_switch_defaults(&provider.id, &provider.settings_config)
{
log::warn!(
"Failed to update Hermes model defaults after switching to '{}': {e}",
provider.id
);
result
.warnings
.push(format!("hermes_model_defaults_failed:{}", provider.id));
}
}
// For additive-mode providers that were DB-only (live_config_managed == Some(false)),
// flip the flag to true now that the provider has been successfully written to the live
// file. This ensures sync_all_providers_to_live() will include it on future syncs.
@@ -1556,7 +1532,6 @@ impl ProviderService {
let rollback_result = match app_type {
AppType::OpenCode => remove_opencode_provider_from_live(&provider.id),
AppType::OpenClaw => remove_openclaw_provider_from_live(&provider.id),
AppType::Hermes => remove_hermes_provider_from_live(&provider.id),
_ => Ok(()),
};
@@ -1733,7 +1708,6 @@ impl ProviderService {
AppType::Gemini => Self::extract_gemini_common_config(&provider.settings_config),
AppType::OpenCode => Self::extract_opencode_common_config(&provider.settings_config),
AppType::OpenClaw => Self::extract_openclaw_common_config(&provider.settings_config),
AppType::Hermes => Ok(String::new()), // Hermes doesn't use common config snippets
}
}
@@ -1748,7 +1722,6 @@ impl ProviderService {
AppType::Gemini => Self::extract_gemini_common_config(settings_config),
AppType::OpenCode => Self::extract_opencode_common_config(settings_config),
AppType::OpenClaw => Self::extract_openclaw_common_config(settings_config),
AppType::Hermes => Ok(String::new()), // Hermes doesn't use common config snippets
}
}
@@ -1761,9 +1734,9 @@ impl ProviderService {
// Auth
"ANTHROPIC_API_KEY",
"ANTHROPIC_AUTH_TOKEN",
// Models (4 fields + 1 legacy)
// Models (5 fields)
"ANTHROPIC_MODEL",
"ANTHROPIC_REASONING_MODEL", // legacy: 已废弃,但旧配置可能残留
"ANTHROPIC_REASONING_MODEL",
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
"ANTHROPIC_DEFAULT_OPUS_MODEL",
"ANTHROPIC_DEFAULT_SONNET_MODEL",
@@ -2114,16 +2087,6 @@ impl ProviderService {
));
}
}
AppType::Hermes => {
// Hermes: accept any JSON object for now
if !provider.settings_config.is_object() {
return Err(AppError::localized(
"provider.hermes.settings.not_object",
"Hermes 配置必须是 JSON 对象",
"Hermes configuration must be a JSON object",
));
}
}
}
// Validate and clean UsageScript configuration (common for all app types)
@@ -2295,8 +2258,8 @@ impl ProviderService {
Ok((api_key, base_url))
}
AppType::OpenClaw | AppType::Hermes => {
// OpenClaw/Hermes use apiKey and baseUrl directly on the object
AppType::OpenClaw => {
// OpenClaw uses apiKey and baseUrl directly on the object
let api_key = provider
.settings_config
.get("apiKey")
+57 -24
View File
@@ -27,7 +27,7 @@ const PROXY_TOKEN_PLACEHOLDER: &str = "PROXY_MANAGED";
/// Claude Code 会继续以旧模型名发起请求,导致新供应商不支持时失败。
const CLAUDE_MODEL_OVERRIDE_ENV_KEYS: [&str; 6] = [
"ANTHROPIC_MODEL",
"ANTHROPIC_REASONING_MODEL", // legacy: 已废弃,但旧配置可能残留
"ANTHROPIC_REASONING_MODEL",
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
"ANTHROPIC_DEFAULT_SONNET_MODEL",
"ANTHROPIC_DEFAULT_OPUS_MODEL",
@@ -466,9 +466,13 @@ impl ProxyService {
AppType::Claude => self.read_claude_live()?,
AppType::Codex => self.read_codex_live()?,
AppType::Gemini => self.read_gemini_live()?,
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features
return Err("该应用不支持代理功能".to_string());
AppType::OpenCode => {
// OpenCode doesn't support proxy features
return Err("OpenCode 不支持代理功能".to_string());
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features
return Err("OpenClaw 不支持代理功能".to_string());
}
};
@@ -683,8 +687,11 @@ impl ProxyService {
}
}
}
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features, skip silently
AppType::OpenCode => {
// OpenCode doesn't support proxy features, skip silently
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features, skip silently
}
}
@@ -864,9 +871,13 @@ impl ProxyService {
AppType::Claude => ("claude", self.read_claude_live()?),
AppType::Codex => ("codex", self.read_codex_live()?),
AppType::Gemini => ("gemini", self.read_gemini_live()?),
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features
return Err("该应用不支持代理功能".to_string());
AppType::OpenCode => {
// OpenCode doesn't support proxy features
return Err("OpenCode 不支持代理功能".to_string());
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features
return Err("OpenClaw 不支持代理功能".to_string());
}
};
@@ -1008,9 +1019,13 @@ impl ProxyService {
self.write_gemini_live(&live_config)?;
log::info!("Gemini Live 配置已接管,代理地址: {proxy_url}");
}
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features
return Err("该应用不支持代理功能".to_string());
AppType::OpenCode => {
// OpenCode doesn't support proxy features
return Err("OpenCode 不支持代理功能".to_string());
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features
return Err("OpenClaw 不支持代理功能".to_string());
}
}
@@ -1061,8 +1076,11 @@ impl ProxyService {
let _ = self.write_gemini_live(&live_config);
}
}
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features, skip silently
AppType::OpenCode => {
// OpenCode doesn't support proxy features, skip silently
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features, skip silently
}
}
@@ -1101,8 +1119,11 @@ impl ProxyService {
log::info!("Gemini Live 配置已恢复");
}
}
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features, skip silently
AppType::OpenCode => {
// OpenCode doesn't support proxy features, skip silently
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features, skip silently
}
}
@@ -1192,9 +1213,13 @@ impl ProxyService {
AppType::Claude => self.write_claude_live(config),
AppType::Codex => self.write_codex_live(config),
AppType::Gemini => self.write_gemini_live(config),
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features
Err("该应用不支持代理功能".to_string())
AppType::OpenCode => {
// OpenCode doesn't support proxy features
Err("OpenCode 不支持代理功能".to_string())
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features
Err("OpenClaw 不支持代理功能".to_string())
}
}
}
@@ -1213,8 +1238,12 @@ impl ProxyService {
Ok(config) => Self::is_gemini_live_taken_over(&config),
Err(_) => false,
},
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy takeover
AppType::OpenCode => {
// OpenCode doesn't support proxy takeover
false
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy takeover
false
}
}
@@ -1256,8 +1285,12 @@ impl ProxyService {
AppType::Claude => self.cleanup_claude_takeover_placeholders_in_live(),
AppType::Codex => self.cleanup_codex_takeover_placeholders_in_live(),
AppType::Gemini => self.cleanup_gemini_takeover_placeholders_in_live(),
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features
AppType::OpenCode => {
// OpenCode doesn't support proxy features
Ok(())
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features
Ok(())
}
}
@@ -1507,7 +1540,7 @@ impl ProxyService {
serde_json::to_string(&env_backup)
.map_err(|e| format!("序列化 Gemini 配置失败: {e}"))?
}
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
AppType::OpenCode | AppType::OpenClaw => {
return Err(format!("未知的应用类型: {app_type}"));
}
};
-20
View File
@@ -529,11 +529,6 @@ impl SkillService {
return Ok(custom.join("skills"));
}
}
AppType::Hermes => {
if let Some(custom) = crate::settings::get_hermes_override_dir() {
return Ok(custom.join("skills"));
}
}
}
// 默认路径:回退到用户主目录下的标准位置
@@ -549,7 +544,6 @@ impl SkillService {
AppType::Gemini => home.join(".gemini").join("skills"),
AppType::OpenCode => home.join(".config").join("opencode").join("skills"),
AppType::OpenClaw => home.join(".openclaw").join("skills"),
AppType::Hermes => crate::hermes_config::get_hermes_dir().join("skills"),
})
}
@@ -1555,20 +1549,6 @@ impl SkillService {
// 保存到数据库
db.save_skill(&skill)?;
// 同步到已启用的应用目录(创建 symlink 或复制文件)
for app in AppType::all() {
if skill.apps.is_enabled_for(&app) {
if let Err(e) = Self::sync_to_app_dir(&skill.directory, &app) {
log::warn!(
"导入后同步 Skill '{}' 到 {:?} 失败: {e:#}",
skill.directory,
app
);
}
}
}
imported.push(skill);
}
+16 -135
View File
@@ -207,10 +207,7 @@ impl StreamCheckService {
// OpenCode / OpenClaw 的 settings_config 结构与 Claude/Codex/Gemini 不同
// baseUrl / apiKey 直接作为根字段而非嵌套在 env),并且协议由 `api`
// 或 `npm` 字段显式指定。它们不走 get_adapter 路径,而是直接分发。
if matches!(
app_type,
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes
) {
if matches!(app_type, AppType::OpenCode | AppType::OpenClaw) {
return Self::check_once_without_adapter(app_type, provider, config, start).await;
}
@@ -273,9 +270,9 @@ impl StreamCheckService {
)
.await
}
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
AppType::OpenCode | AppType::OpenClaw => {
// Already handled via early dispatch above
unreachable!("OpenCode/OpenClaw/Hermes 已通过 check_once_without_adapter 处理")
unreachable!("OpenCode/OpenClaw 已通过 check_once_without_adapter 处理")
}
};
@@ -684,7 +681,7 @@ impl StreamCheckService {
let result = match app_type {
AppType::OpenClaw => {
Self::check_additive_app_stream(
Self::check_openclaw_stream(
&client,
provider,
&model_to_test,
@@ -703,17 +700,7 @@ impl StreamCheckService {
)
.await
}
AppType::Hermes => {
Self::check_hermes_stream(
&client,
provider,
&model_to_test,
test_prompt,
request_timeout,
)
.await
}
_ => unreachable!("check_once_without_adapter 只处理 OpenCode/OpenClaw/Hermes"),
_ => unreachable!("check_once_without_adapter 只处理 OpenCode/OpenClaw"),
};
let response_time = start.elapsed().as_millis() as u64;
@@ -818,7 +805,7 @@ impl StreamCheckService {
/// - `anthropic-messages` → check_claude_stream + api_format="anthropic" (ClaudeAuth 策略)
/// - `google-generative-ai` → check_gemini_stream (Google API Key 策略)
/// - `bedrock-converse-stream` → 不支持(需要 AWS SigV4 签名)
async fn check_additive_app_stream(
async fn check_openclaw_stream(
client: &Client,
provider: &Provider,
model: &str,
@@ -828,7 +815,7 @@ impl StreamCheckService {
// 自定义认证头(如 Longcat 的 `apikey` 头)不走标准 Bearer
// 具体头名由 OpenClaw 网关内部决定,cc-switch 无法准确构造,
// 因此直接返回友好错误而不是让用户看到一个误导性的 401。
if Self::additive_app_uses_auth_header(provider) {
if Self::openclaw_uses_auth_header(provider) {
return Err(AppError::localized(
"openclaw_auth_header_not_supported",
"该供应商使用自定义认证头,暂不支持流式健康检查。建议直接通过 OpenClaw 测试。",
@@ -921,8 +908,8 @@ impl StreamCheckService {
}
}
/// 判断 additive-mode 供应商是否使用自定义认证头(`authHeader: true`
fn additive_app_uses_auth_header(provider: &Provider) -> bool {
/// 判断 OpenClaw 供应商是否使用自定义认证头(`authHeader: true`
fn openclaw_uses_auth_header(provider: &Provider) -> bool {
provider
.settings_config
.get("authHeader")
@@ -982,112 +969,6 @@ impl StreamCheckService {
.filter(|s| !s.is_empty())
}
// Hermes 的 settings_config 用 snake_casebase_url / api_key / api_mode),
// 与 OpenClaw 的 camelCasebaseUrl / apiKey / api)是两套独立命名。
// 见 src/config/hermesProviderPresets.ts 的 HermesProviderSettingsConfig。
fn extract_hermes_base_url(provider: &Provider) -> Result<String, AppError> {
provider
.settings_config
.get("base_url")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.ok_or_else(|| {
AppError::localized(
"hermes_base_url_missing",
"Hermes 供应商缺少 base_url",
"Hermes provider is missing `base_url`",
)
})
}
fn extract_hermes_api_key(provider: &Provider) -> Result<String, AppError> {
provider
.settings_config
.get("api_key")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.ok_or_else(|| {
AppError::localized(
"hermes_api_key_missing",
"Hermes 供应商缺少 api_key",
"Hermes provider is missing `api_key`",
)
})
}
fn extract_hermes_api_mode(provider: &Provider) -> Option<String> {
provider
.settings_config
.get("api_mode")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
/// Hermes 流式检查分发器
///
/// Hermes 以 `api_mode` 字段显式指定协议,取值来自
/// `HermesApiMode`hermesProviderPresets.ts):
/// - `chat_completions` → check_claude_stream + api_format="openai_chat"Bearer
/// - `anthropic_messages` → check_claude_stream + api_format="anthropic"ClaudeAuth,与 OpenClaw 的 anthropic-messages 同策略)
/// - `codex_responses` → check_claude_stream + api_format="openai_responses"Bearer
/// - `bedrock_converse` → 不支持(需要 AWS SigV4 签名)
async fn check_hermes_stream(
client: &Client,
provider: &Provider,
model: &str,
test_prompt: &str,
timeout: std::time::Duration,
) -> Result<(u16, String), AppError> {
// 先把 api_mode 路由出协议格式与认证策略。
// 纯错误路径(bedrock / 未知 / 缺失)直接 return,避免在用户
// 选了 bedrock_converse 时被"缺 base_url"的二级错误盖住真正原因。
let (api_format, auth_strategy) = match Self::extract_hermes_api_mode(provider).as_deref() {
Some("chat_completions") => ("openai_chat", AuthStrategy::Bearer),
Some("anthropic_messages") => ("anthropic", AuthStrategy::ClaudeAuth),
Some("codex_responses") => ("openai_responses", AuthStrategy::Bearer),
Some("bedrock_converse") => {
return Err(AppError::localized(
"hermes_bedrock_not_supported",
"AWS Bedrock 需要 SigV4 签名,当前不支持健康检查。",
"AWS Bedrock requires SigV4 signing and is not supported by stream health check.",
));
}
Some(other) => {
return Err(AppError::localized(
"hermes_protocol_not_yet_supported",
format!("Hermes 暂不支持协议: {other}"),
format!("Hermes protocol not yet supported: {other}"),
));
}
None => {
return Err(AppError::localized(
"hermes_api_mode_missing",
"Hermes 供应商缺少 api_mode 字段",
"Hermes provider is missing the `api_mode` field",
));
}
};
let base_url = Self::extract_hermes_base_url(provider)?;
let api_key = Self::extract_hermes_api_key(provider)?;
let auth = AuthInfo::new(api_key, auth_strategy);
Self::check_claude_stream(
client,
&base_url,
&auth,
model,
test_prompt,
timeout,
provider,
Some(api_format),
None,
)
.await
}
/// OpenCode 流式检查分发器
///
/// OpenCode 用 `npm` 字段(AI SDK 包名)隐式指定协议。映射关系参见
@@ -1145,7 +1026,7 @@ impl StreamCheckService {
.await
}
Some("@ai-sdk/anthropic") => {
// 见 check_additive_app_stream 对 anthropic-messages 的处理
// 见 check_openclaw_stream 对 anthropic-messages 的注释
// 用 ClaudeAuthBearer-only)兼容中转服务。
let auth = AuthInfo::new(api_key, AuthStrategy::ClaudeAuth);
Self::check_claude_stream(
@@ -1360,8 +1241,8 @@ impl StreamCheckService {
// Try to extract first model from the models object
Self::extract_opencode_model(provider).unwrap_or_else(|| "gpt-4o".to_string())
}
AppType::OpenClaw | AppType::Hermes => {
// OpenClaw/Hermes use models array in settings_config
AppType::OpenClaw => {
// OpenClaw uses models array in settings_config
// Try to extract first model from the models array
Self::extract_openclaw_model(provider).unwrap_or_else(|| "gpt-4o".to_string())
}
@@ -1525,24 +1406,24 @@ mod tests {
}
#[test]
fn test_additive_app_uses_auth_header_true() {
fn test_openclaw_uses_auth_header_true() {
let p = make_provider(serde_json::json!({
"baseUrl": "https://api.longcat.chat/v1",
"apiKey": "k",
"api": "openai-completions",
"authHeader": true,
}));
assert!(StreamCheckService::additive_app_uses_auth_header(&p));
assert!(StreamCheckService::openclaw_uses_auth_header(&p));
}
#[test]
fn test_additive_app_uses_auth_header_default_false() {
fn test_openclaw_uses_auth_header_default_false() {
let p = make_provider(serde_json::json!({
"baseUrl": "https://api.deepseek.com/v1",
"apiKey": "k",
"api": "openai-completions",
}));
assert!(!StreamCheckService::additive_app_uses_auth_header(&p));
assert!(!StreamCheckService::openclaw_uses_auth_header(&p));
}
#[test]
File diff suppressed because it is too large Load Diff
+4 -16
View File
@@ -4,7 +4,7 @@ pub mod terminal;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use providers::{claude, codex, gemini, hermes, openclaw, opencode};
use providers::{claude, codex, gemini, openclaw, opencode};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -56,20 +56,18 @@ pub struct DeleteSessionOutcome {
}
pub fn scan_sessions() -> Vec<SessionMeta> {
let (r1, r2, r3, r4, r5, r6) = std::thread::scope(|s| {
let (r1, r2, r3, r4, r5) = std::thread::scope(|s| {
let h1 = s.spawn(codex::scan_sessions);
let h2 = s.spawn(claude::scan_sessions);
let h3 = s.spawn(opencode::scan_sessions);
let h4 = s.spawn(openclaw::scan_sessions);
let h5 = s.spawn(gemini::scan_sessions);
let h6 = s.spawn(hermes::scan_sessions);
(
h1.join().unwrap_or_default(),
h2.join().unwrap_or_default(),
h3.join().unwrap_or_default(),
h4.join().unwrap_or_default(),
h5.join().unwrap_or_default(),
h6.join().unwrap_or_default(),
)
});
@@ -79,7 +77,6 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
sessions.extend(r3);
sessions.extend(r4);
sessions.extend(r5);
sessions.extend(r6);
sessions.sort_by(|a, b| {
let a_ts = a.last_active_at.or(a.created_at).unwrap_or(0);
@@ -91,13 +88,10 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
}
pub fn load_messages(provider_id: &str, source_path: &str) -> Result<Vec<SessionMessage>, String> {
// SQLite sessions use a "sqlite:" prefixed source_path
// OpenCode SQLite sessions use a "sqlite:" prefixed source_path
if provider_id == "opencode" && source_path.starts_with("sqlite:") {
return opencode::load_messages_sqlite(source_path);
}
if provider_id == "hermes" && source_path.starts_with("sqlite:") {
return hermes::load_messages_sqlite(source_path);
}
let path = Path::new(source_path);
match provider_id {
@@ -106,7 +100,6 @@ pub fn load_messages(provider_id: &str, source_path: &str) -> Result<Vec<Session
"opencode" => opencode::load_messages(path),
"openclaw" => openclaw::load_messages(path),
"gemini" => gemini::load_messages(path),
"hermes" => hermes::load_messages(path),
_ => Err(format!("Unsupported provider: {provider_id}")),
}
}
@@ -116,13 +109,10 @@ pub fn delete_session(
session_id: &str,
source_path: &str,
) -> Result<bool, String> {
// SQLite sessions bypass the file-based deletion path
// OpenCode SQLite sessions bypass the file-based deletion path
if provider_id == "opencode" && source_path.starts_with("sqlite:") {
return opencode::delete_session_sqlite(session_id, source_path);
}
if provider_id == "hermes" && source_path.starts_with("sqlite:") {
return hermes::delete_session_sqlite(session_id, source_path);
}
let root = provider_root(provider_id)?;
delete_session_with_root(provider_id, session_id, Path::new(source_path), &root)
@@ -160,7 +150,6 @@ fn delete_session_with_root(
"opencode" => opencode::delete_session(&validated_root, &validated_source, session_id),
"openclaw" => openclaw::delete_session(&validated_root, &validated_source, session_id),
"gemini" => gemini::delete_session(&validated_root, &validated_source, session_id),
"hermes" => hermes::delete_session(&validated_root, &validated_source, session_id),
_ => Err(format!("Unsupported provider: {provider_id}")),
}
}
@@ -172,7 +161,6 @@ fn provider_root(provider_id: &str) -> Result<PathBuf, String> {
"opencode" => opencode::get_opencode_data_dir(),
"openclaw" => crate::openclaw_config::get_openclaw_dir().join("agents"),
"gemini" => crate::gemini_config::get_gemini_dir().join("tmp"),
"hermes" => crate::hermes_config::get_hermes_dir().join("sessions"),
_ => return Err(format!("Unsupported provider: {provider_id}")),
};
@@ -1,603 +0,0 @@
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use rusqlite::Connection;
use serde_json::Value;
use crate::hermes_config::get_hermes_dir;
use crate::session_manager::{SessionMessage, SessionMeta};
use super::utils::{
extract_text, parse_timestamp_to_ms, read_head_tail_lines, truncate_summary, TITLE_MAX_CHARS,
};
const PROVIDER_ID: &str = "hermes";
fn get_hermes_db_path() -> PathBuf {
get_hermes_dir().join("state.db")
}
fn get_hermes_sessions_dir() -> PathBuf {
get_hermes_dir().join("sessions")
}
/// Scan sessions from both SQLite database and JSONL transcript files,
/// with SQLite taking precedence on ID conflicts.
pub fn scan_sessions() -> Vec<SessionMeta> {
let sqlite_sessions = scan_sessions_sqlite();
let jsonl_sessions = scan_sessions_jsonl();
if sqlite_sessions.is_empty() {
return jsonl_sessions;
}
if jsonl_sessions.is_empty() {
return sqlite_sessions;
}
let sqlite_ids: std::collections::HashSet<String> = sqlite_sessions
.iter()
.map(|s| s.session_id.clone())
.collect();
let mut merged = sqlite_sessions;
for s in jsonl_sessions {
if !sqlite_ids.contains(&s.session_id) {
merged.push(s);
}
}
merged
}
// ── SQLite scanning ─────────────────────────────────────────────────
fn scan_sessions_sqlite() -> Vec<SessionMeta> {
let db_path = get_hermes_db_path();
if !db_path.exists() {
return Vec::new();
}
let conn = match Connection::open_with_flags(
&db_path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
) {
Ok(c) => c,
Err(_) => return Vec::new(),
};
// Check if sessions table exists
let has_sessions: bool = conn
.query_row(
"SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='sessions'",
[],
|row| row.get(0),
)
.unwrap_or(false);
if !has_sessions {
return Vec::new();
}
// Query sessions — use flexible column access via pragma
let columns = get_table_columns(&conn, "sessions");
let query = "SELECT * FROM sessions ORDER BY rowid DESC LIMIT 500";
let mut stmt = match conn.prepare(query) {
Ok(s) => s,
Err(_) => return Vec::new(),
};
let mut sessions = Vec::new();
let rows = match stmt.query_map([], |row| Ok(row_to_json(row, &columns))) {
Ok(r) => r,
Err(_) => return Vec::new(),
};
let db_source = format!("sqlite:{}", db_path.display());
for row_result in rows.flatten() {
if let Some(meta) = sqlite_row_to_session_meta(&row_result, &db_source) {
sessions.push(meta);
}
}
sessions
}
fn sqlite_row_to_session_meta(row: &Value, db_source: &str) -> Option<SessionMeta> {
let obj = row.as_object()?;
let session_id = obj.get("id").and_then(Value::as_str)?.to_string();
let title = obj
.get("title")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(|s| truncate_summary(s, TITLE_MAX_CHARS).to_string());
let cwd = obj
.get("cwd")
.or_else(|| obj.get("directory"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
let started_at = obj
.get("started_at")
.or_else(|| obj.get("created_at"))
.and_then(parse_timestamp_to_ms);
let ended_at = obj
.get("ended_at")
.or_else(|| obj.get("updated_at"))
.and_then(parse_timestamp_to_ms);
let source_path = format!("{}#{}", db_source, session_id);
Some(SessionMeta {
provider_id: PROVIDER_ID.to_string(),
session_id,
title,
summary: None,
project_dir: cwd,
created_at: started_at,
last_active_at: ended_at.or(started_at),
source_path: Some(source_path),
resume_command: None,
})
}
/// Get column names for a table.
fn get_table_columns(conn: &Connection, table: &str) -> Vec<String> {
let query = format!("PRAGMA table_info({table})");
let mut stmt = match conn.prepare(&query) {
Ok(s) => s,
Err(_) => return Vec::new(),
};
let rows = match stmt.query_map([], |row| {
let name: String = row.get(1)?;
Ok(name)
}) {
Ok(r) => r,
Err(_) => return Vec::new(),
};
rows.flatten().collect()
}
/// Convert a SQLite row to a JSON Value using known column names.
fn row_to_json(row: &rusqlite::Row, columns: &[String]) -> Value {
let mut map = serde_json::Map::new();
for (i, col) in columns.iter().enumerate() {
// Try string first, then integer, then float, then null
if let Ok(val) = row.get::<_, String>(i) {
map.insert(col.clone(), Value::String(val));
} else if let Ok(val) = row.get::<_, i64>(i) {
map.insert(col.clone(), Value::Number(val.into()));
} else if let Ok(val) = row.get::<_, f64>(i) {
if let Some(n) = serde_json::Number::from_f64(val) {
map.insert(col.clone(), Value::Number(n));
}
} else {
map.insert(col.clone(), Value::Null);
}
}
Value::Object(map)
}
/// Load messages from the Hermes SQLite database.
pub fn load_messages_sqlite(source: &str) -> Result<Vec<SessionMessage>, String> {
let (db_path, session_id) = parse_sqlite_source(source)
.ok_or_else(|| format!("Invalid SQLite source reference: {source}"))?;
let conn = Connection::open_with_flags(
&db_path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
.map_err(|e| format!("Failed to open Hermes database: {e}"))?;
// Try querying with common column names
let query =
"SELECT role, content, created_at FROM messages WHERE session_id = ?1 ORDER BY created_at ASC";
let mut stmt = conn
.prepare(query)
.map_err(|e| format!("Failed to prepare messages query: {e}"))?;
let rows = stmt
.query_map([session_id.as_str()], |row| {
let role: String = row.get(0)?;
let content: String = row.get(1)?;
let ts: Option<i64> = row.get(2).ok();
Ok((role, content, ts))
})
.map_err(|e| format!("Failed to query messages: {e}"))?;
let mut messages = Vec::new();
for row in rows.flatten() {
let (role, content, ts) = row;
if content.trim().is_empty() {
continue;
}
let ts_ms = ts.and_then(|v| parse_timestamp_to_ms(&Value::Number(v.into())));
messages.push(SessionMessage {
role,
content,
ts: ts_ms,
});
}
Ok(messages)
}
/// Delete a session from the Hermes SQLite database.
pub fn delete_session_sqlite(session_id: &str, source: &str) -> Result<bool, String> {
let (db_path, ref_session_id) = parse_sqlite_source(source)
.ok_or_else(|| format!("Invalid SQLite source reference: {source}"))?;
let db_path = db_path
.canonicalize()
.map_err(|e| format!("Failed to canonicalize Hermes database path: {e}"))?;
let expected_db_path = get_hermes_db_path()
.canonicalize()
.map_err(|e| format!("Failed to canonicalize expected Hermes database path: {e}"))?;
if ref_session_id != session_id {
return Err(format!(
"Hermes SQLite session ID mismatch: expected {session_id}, found {ref_session_id}"
));
}
if db_path != expected_db_path {
return Err("SQLite path does not match expected Hermes database".to_string());
}
let conn =
Connection::open(&db_path).map_err(|e| format!("Failed to open Hermes database: {e}"))?;
let tx = conn
.unchecked_transaction()
.map_err(|e| format!("Failed to begin transaction: {e}"))?;
// Delete messages first (child records)
let _ = tx.execute("DELETE FROM messages WHERE session_id = ?1", [session_id]);
let deleted = tx
.execute("DELETE FROM sessions WHERE id = ?1", [session_id])
.map_err(|e| format!("Failed to delete Hermes session: {e}"))?;
tx.commit()
.map_err(|e| format!("Failed to commit session deletion: {e}"))?;
Ok(deleted > 0)
}
fn parse_sqlite_source(source: &str) -> Option<(PathBuf, String)> {
let rest = source.strip_prefix("sqlite:")?;
let hash_pos = rest.rfind('#')?;
let db_path = PathBuf::from(&rest[..hash_pos]);
let session_id = rest[hash_pos + 1..].to_string();
if session_id.is_empty() {
return None;
}
Some((db_path, session_id))
}
// ── JSONL scanning ──────────────────────────────────────────────────
fn scan_sessions_jsonl() -> Vec<SessionMeta> {
let sessions_dir = get_hermes_sessions_dir();
if !sessions_dir.exists() {
return Vec::new();
}
let entries = match std::fs::read_dir(&sessions_dir) {
Ok(e) => e,
Err(_) => return Vec::new(),
};
let mut sessions = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
let ext = path.extension().and_then(|e| e.to_str());
if ext != Some("jsonl") && ext != Some("json") {
continue;
}
if let Some(meta) = parse_jsonl_session(&path) {
sessions.push(meta);
}
}
sessions
}
fn parse_jsonl_session(path: &Path) -> Option<SessionMeta> {
// Read head (metadata + first user message) and tail (last timestamp)
let (head, tail) = read_head_tail_lines(path, 30, 10).ok()?;
let mut first_user_msg: Option<String> = None;
let mut first_ts: Option<i64> = None;
let mut last_ts: Option<i64> = None;
let mut session_id: Option<String> = None;
let mut title: Option<String> = None;
let mut cwd: Option<String> = None;
// Process head lines for metadata and first user message
for line in &head {
if line.trim().is_empty() {
continue;
}
let value: Value = match serde_json::from_str(line) {
Ok(v) => v,
Err(_) => continue,
};
let ts = value
.get("timestamp")
.or_else(|| value.get("ts"))
.and_then(parse_timestamp_to_ms);
if first_ts.is_none() {
first_ts = ts;
}
last_ts = ts.or(last_ts);
let line_type = value.get("type").and_then(Value::as_str).unwrap_or("");
// Extract session metadata from session-type lines
if line_type == "session" || line_type == "init" {
if session_id.is_none() {
session_id = value
.get("id")
.or_else(|| value.get("sessionId"))
.and_then(Value::as_str)
.map(|s| s.to_string());
}
if title.is_none() {
title = value
.get("title")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
}
if cwd.is_none() {
cwd = value
.get("cwd")
.or_else(|| value.get("directory"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
}
}
if first_user_msg.is_none() {
let role = value
.get("role")
.or_else(|| value.get("message").and_then(|m| m.get("role")))
.and_then(Value::as_str);
if role == Some("user") {
let content = value
.get("content")
.or_else(|| value.get("message").and_then(|m| m.get("content")));
if let Some(c) = content {
let text = extract_text(c);
if !text.trim().is_empty() {
first_user_msg = Some(truncate_summary(&text, TITLE_MAX_CHARS).to_string());
}
}
}
}
}
// Process tail lines for the most recent timestamp
for line in tail.iter().rev() {
if line.trim().is_empty() {
continue;
}
let value: Value = match serde_json::from_str(line) {
Ok(v) => v,
Err(_) => continue,
};
let ts = value
.get("timestamp")
.or_else(|| value.get("ts"))
.and_then(parse_timestamp_to_ms);
if let Some(t) = ts {
last_ts = Some(t);
break;
}
}
// Fall back to filename as session ID
let session_id = session_id.unwrap_or_else(|| {
path.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown")
.to_string()
});
let source_path = path.to_string_lossy().to_string();
Some(SessionMeta {
provider_id: PROVIDER_ID.to_string(),
session_id,
title: title.or_else(|| first_user_msg.clone()),
summary: first_user_msg,
project_dir: cwd,
created_at: first_ts,
last_active_at: last_ts.or(first_ts),
source_path: Some(source_path),
resume_command: None,
})
}
/// Load messages from a Hermes JSONL transcript file.
pub fn load_messages(path: &Path) -> Result<Vec<SessionMessage>, String> {
let file = File::open(path).map_err(|e| format!("Failed to open session file: {e}"))?;
let reader = BufReader::new(file);
let mut messages = Vec::new();
for line in reader.lines() {
let line = match line {
Ok(l) => l,
Err(_) => continue,
};
if line.trim().is_empty() {
continue;
}
let value: Value = match serde_json::from_str(&line) {
Ok(v) => v,
Err(_) => continue,
};
// Support both flat messages and nested {type:"message", message:{...}} format
let (role_val, content_val, ts_val) =
if value.get("type").and_then(Value::as_str) == Some("message") {
let msg = match value.get("message") {
Some(m) => m,
None => continue,
};
(
msg.get("role"),
msg.get("content"),
value.get("timestamp").or_else(|| msg.get("ts")),
)
} else {
(
value.get("role"),
value.get("content"),
value.get("timestamp").or_else(|| value.get("ts")),
)
};
let role = match role_val.and_then(Value::as_str) {
Some(r) => r.to_string(),
None => continue,
};
let content = content_val.map(extract_text).unwrap_or_default();
if content.trim().is_empty() {
continue;
}
let ts = ts_val.and_then(parse_timestamp_to_ms);
messages.push(SessionMessage { role, content, ts });
}
Ok(messages)
}
/// Delete a Hermes JSONL session file.
pub fn delete_session(_root: &Path, path: &Path, _session_id: &str) -> Result<bool, String> {
std::fs::remove_file(path).map_err(|e| {
format!(
"Failed to delete Hermes session file {}: {e}",
path.display()
)
})?;
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::tempdir;
#[test]
fn parse_sqlite_source_valid() {
let (path, id) = parse_sqlite_source("sqlite:/home/user/.hermes/state.db#session-123")
.expect("should parse");
assert_eq!(path, PathBuf::from("/home/user/.hermes/state.db"));
assert_eq!(id, "session-123");
}
#[test]
fn parse_sqlite_source_invalid() {
assert!(parse_sqlite_source("not-sqlite").is_none());
assert!(parse_sqlite_source("sqlite:").is_none());
assert!(parse_sqlite_source("sqlite:/path#").is_none());
}
#[test]
fn parse_jsonl_session_extracts_metadata() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("test-session.jsonl");
let mut f = File::create(&path).expect("create");
writeln!(
f,
r#"{{"type":"session","id":"s1","title":"My Session","cwd":"/home/user/project"}}"#
)
.unwrap();
writeln!(f, r#"{{"type":"message","message":{{"role":"user","content":"Hello world"}},"timestamp":"2026-01-01T00:00:00Z"}}"#).unwrap();
writeln!(f, r#"{{"type":"message","message":{{"role":"assistant","content":"Hi there"}},"timestamp":"2026-01-01T00:01:00Z"}}"#).unwrap();
f.flush().unwrap();
let meta = parse_jsonl_session(&path).expect("should parse");
assert_eq!(meta.session_id, "s1");
assert_eq!(meta.title.as_deref(), Some("My Session"));
assert_eq!(meta.project_dir.as_deref(), Some("/home/user/project"));
assert!(meta.created_at.is_some());
assert!(meta.last_active_at.is_some());
}
#[test]
fn parse_jsonl_session_fallback_to_filename() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("my-session.jsonl");
let mut f = File::create(&path).expect("create");
writeln!(f, r#"{{"role":"user","content":"Hello","ts":1700000000}}"#).unwrap();
f.flush().unwrap();
let meta = parse_jsonl_session(&path).expect("should parse");
assert_eq!(meta.session_id, "my-session");
assert!(meta.title.is_some()); // Falls back to first user message
}
#[test]
fn load_messages_flat_format() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("session.jsonl");
let mut f = File::create(&path).expect("create");
writeln!(
f,
r#"{{"role":"user","content":"What is Rust?","ts":1700000000}}"#
)
.unwrap();
writeln!(
f,
r#"{{"role":"assistant","content":"A systems programming language.","ts":1700000001}}"#
)
.unwrap();
f.flush().unwrap();
let msgs = load_messages(&path).expect("should load");
assert_eq!(msgs.len(), 2);
assert_eq!(msgs[0].role, "user");
assert_eq!(msgs[1].role, "assistant");
}
#[test]
fn load_messages_nested_format() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("session.jsonl");
let mut f = File::create(&path).expect("create");
writeln!(f, r#"{{"type":"session","id":"s1"}}"#).unwrap();
writeln!(f, r#"{{"type":"message","message":{{"role":"user","content":"Hello"}},"timestamp":"2026-01-01T00:00:00Z"}}"#).unwrap();
writeln!(f, r#"{{"type":"message","message":{{"role":"assistant","content":"Hi"}},"timestamp":"2026-01-01T00:01:00Z"}}"#).unwrap();
f.flush().unwrap();
let msgs = load_messages(&path).expect("should load");
assert_eq!(msgs.len(), 2);
assert_eq!(msgs[0].role, "user");
assert!(msgs[0].ts.is_some());
}
#[test]
fn delete_session_removes_file() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("session.jsonl");
File::create(&path).expect("create");
assert!(path.exists());
delete_session(dir.path(), &path, "session").expect("should delete");
assert!(!path.exists());
}
}
@@ -1,7 +1,6 @@
pub mod claude;
pub mod codex;
pub mod gemini;
pub mod hermes;
pub mod openclaw;
pub mod opencode;
mod utils;
+66 -36
View File
@@ -78,7 +78,22 @@ end tell"#
}
fn launch_ghostty(command: &str, cwd: Option<&str>) -> Result<(), String> {
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".to_string());
let args = build_ghostty_args(command, cwd);
let status = Command::new("open")
.args(args.iter().map(String::as_str))
.status()
.map_err(|e| format!("Failed to launch Ghostty: {e}"))?;
if status.success() {
Ok(())
} else {
Err("Failed to launch Ghostty. Make sure it is installed.".to_string())
}
}
fn build_ghostty_args(command: &str, cwd: Option<&str>) -> Vec<String> {
let input = ghostty_raw_input(command);
let mut args = vec![
"-na".to_string(),
@@ -93,22 +108,22 @@ fn launch_ghostty(command: &str, cwd: Option<&str>) -> Result<(), String> {
}
}
args.push("-e".to_string());
args.push(shell);
args.push("-l".to_string());
args.push("-c".to_string());
args.push(command.to_string());
args.push(format!("--input={input}"));
args
}
let status = Command::new("open")
.args(&args)
.status()
.map_err(|e| format!("Failed to launch Ghostty: {e}"))?;
if status.success() {
Ok(())
} else {
Err("Failed to launch Ghostty. Make sure it is installed.".to_string())
fn ghostty_raw_input(command: &str) -> String {
let mut escaped = String::from("raw:");
for ch in command.chars() {
match ch {
'\\' => escaped.push_str("\\\\"),
'\n' => escaped.push_str("\\n"),
'\r' => escaped.push_str("\\r"),
_ => escaped.push(ch),
}
}
escaped.push_str("\\n");
escaped
}
fn launch_kitty(command: &str, cwd: Option<&str>) -> Result<(), String> {
@@ -285,10 +300,43 @@ mod tests {
use super::*;
#[test]
fn build_shell_command_keeps_command_without_cwd_prefix_when_not_provided() {
fn ghostty_uses_shell_mode_for_resume_commands() {
let args = build_ghostty_args("claude --resume abc-123", Some("/tmp/project dir"));
assert_eq!(
build_shell_command("claude --resume abc-123", None),
"claude --resume abc-123"
args,
vec![
"-na",
"Ghostty",
"--args",
"--quit-after-last-window-closed=true",
"--working-directory=/tmp/project dir",
"--input=raw:claude --resume abc-123\\n",
]
);
}
#[test]
fn ghostty_keeps_command_without_cwd_prefix_when_not_provided() {
let args = build_ghostty_args("claude --resume abc-123", None);
assert_eq!(
args,
vec![
"-na",
"Ghostty",
"--args",
"--quit-after-last-window-closed=true",
"--input=raw:claude --resume abc-123\\n",
]
);
}
#[test]
fn ghostty_escapes_newlines_and_backslashes_in_input() {
assert_eq!(
ghostty_raw_input("echo foo\\\\bar\npwd"),
"raw:echo foo\\\\\\\\bar\\npwd\\n"
);
}
@@ -317,22 +365,4 @@ mod tests {
]
);
}
#[test]
fn ghostty_uses_working_directory_arg_for_cwd() {
// cwd should be passed as --working-directory, not embedded in the shell command string
// This avoids shell expansion of special characters in directory paths
let cwd = "/tmp/project dir";
let command = "claude --resume abc-123";
// Verify build_shell_command does NOT include cwd when used in ghostty context
// (ghostty passes cwd via --working-directory flag instead)
assert_eq!(
build_shell_command(command, None),
"claude --resume abc-123"
);
// Verify shell_escape works correctly for paths with spaces
assert_eq!(shell_escape(cwd), "\"/tmp/project dir\"");
}
}
-28
View File
@@ -36,8 +36,6 @@ pub struct VisibleApps {
pub opencode: bool,
#[serde(default = "default_true")]
pub openclaw: bool,
#[serde(default)]
pub hermes: bool,
}
impl Default for VisibleApps {
@@ -48,7 +46,6 @@ impl Default for VisibleApps {
gemini: true,
opencode: true,
openclaw: true,
hermes: false, // 默认不显示,需用户手动启用
}
}
}
@@ -62,7 +59,6 @@ impl VisibleApps {
AppType::Gemini => self.gemini,
AppType::OpenCode => self.opencode,
AppType::OpenClaw => self.openclaw,
AppType::Hermes => self.hermes,
}
}
}
@@ -235,8 +231,6 @@ pub struct AppSettings {
pub opencode_config_dir: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub openclaw_config_dir: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hermes_config_dir: Option<String>,
// ===== 当前供应商 ID(设备级)=====
/// 当前 Claude 供应商 ID(本地存储,优先于数据库 is_current
@@ -254,9 +248,6 @@ pub struct AppSettings {
/// 当前 OpenClaw 供应商 ID(本地存储,对 OpenClaw 可能无意义,但保持结构一致)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub current_provider_openclaw: Option<String>,
/// 当前 Hermes 供应商 ID(本地存储,保持结构一致)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub current_provider_hermes: Option<String>,
// ===== Skill 同步设置 =====
/// Skill 同步方式:auto(默认,优先 symlink)、symlink、copy
@@ -324,13 +315,11 @@ impl Default for AppSettings {
gemini_config_dir: None,
opencode_config_dir: None,
openclaw_config_dir: None,
hermes_config_dir: None,
current_provider_claude: None,
current_provider_codex: None,
current_provider_gemini: None,
current_provider_opencode: None,
current_provider_openclaw: None,
current_provider_hermes: None,
skill_sync_method: SyncMethod::default(),
skill_storage_location: SkillStorageLocation::default(),
webdav_sync: None,
@@ -388,13 +377,6 @@ impl AppSettings {
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
self.hermes_config_dir = self
.hermes_config_dir
.as_ref()
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
self.language = self
.language
.as_ref()
@@ -595,14 +577,6 @@ pub fn get_openclaw_override_dir() -> Option<PathBuf> {
.map(|p| resolve_override_path(p))
}
pub fn get_hermes_override_dir() -> Option<PathBuf> {
let settings = settings_store().read().ok()?;
settings
.hermes_config_dir
.as_ref()
.map(|p| resolve_override_path(p))
}
// ===== 当前供应商管理函数 =====
/// 获取指定应用类型的当前供应商 ID(从本地 settings 读取)
@@ -617,7 +591,6 @@ pub fn get_current_provider(app_type: &AppType) -> Option<String> {
AppType::Gemini => settings.current_provider_gemini.clone(),
AppType::OpenCode => settings.current_provider_opencode.clone(),
AppType::OpenClaw => settings.current_provider_openclaw.clone(),
AppType::Hermes => settings.current_provider_hermes.clone(),
}
}
@@ -633,7 +606,6 @@ pub fn set_current_provider(app_type: &AppType, id: Option<&str>) -> Result<(),
AppType::Gemini => settings.current_provider_gemini = id_owned.clone(),
AppType::OpenCode => settings.current_provider_opencode = id_owned.clone(),
AppType::OpenClaw => settings.current_provider_openclaw = id_owned.clone(),
AppType::Hermes => settings.current_provider_hermes = id_owned.clone(),
})
}
+3 -15
View File
@@ -58,7 +58,6 @@ pub struct TrayAppSection {
/// Auto 菜单项后缀
pub const AUTO_SUFFIX: &str = "auto";
pub const TRAY_ID: &str = "cc-switch";
pub const TRAY_SECTIONS: [TrayAppSection; 3] = [
TrayAppSection {
@@ -208,7 +207,7 @@ fn handle_auto_click(app: &tauri::AppHandle, app_type: &AppType) -> Result<(), A
// 4) 更新托盘菜单
if let Ok(new_menu) = create_tray_menu(app, app_state.inner()) {
if let Some(tray) = app.tray_by_id(TRAY_ID) {
if let Some(tray) = app.tray_by_id("main") {
let _ = tray.set_menu(Some(new_menu));
}
}
@@ -256,7 +255,7 @@ fn handle_provider_click(
// 更新托盘菜单
if let Ok(new_menu) = create_tray_menu(app, app_state.inner()) {
if let Some(tray) = app.tray_by_id(TRAY_ID) {
if let Some(tray) = app.tray_by_id("main") {
let _ = tray.set_menu(Some(new_menu));
}
}
@@ -403,7 +402,7 @@ pub fn refresh_tray_menu(app: &tauri::AppHandle) {
if let Some(state) = app.try_state::<AppState>() {
if let Ok(new_menu) = create_tray_menu(app, state.inner()) {
if let Some(tray) = app.tray_by_id(TRAY_ID) {
if let Some(tray) = app.tray_by_id("main") {
if let Err(e) = tray.set_menu(Some(new_menu)) {
log::error!("刷新托盘菜单失败: {e}");
}
@@ -412,17 +411,6 @@ pub fn refresh_tray_menu(app: &tauri::AppHandle) {
}
}
#[cfg(test)]
mod tests {
use super::TRAY_ID;
#[test]
fn tray_id_is_unique_to_app() {
assert_eq!(TRAY_ID, "cc-switch");
assert_ne!(TRAY_ID, "main");
}
}
#[cfg(target_os = "macos")]
pub fn apply_tray_policy(app: &tauri::AppHandle, dock_visible: bool) {
use tauri::ActivationPolicy;
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "CC Switch",
"version": "3.14.0",
"version": "3.13.0",
"identifier": "com.ccswitch.desktop",
"build": {
"frontendDist": "../dist",
-124
View File
@@ -1,124 +0,0 @@
mod support;
use cc_switch_lib::{hermes_config, update_settings, AppSettings};
/// 读取并回写 Hermes provider 时,Hermes v12+ 新增或未来才会出现的字段
/// (例如 `rate_limit_delay`、`key_env`)必须透传,不能因为 UI 不感知就静默丢弃。
/// 否则用户在 Hermes Web UI 配置的高级字段会在 CC Switch 编辑后消失。
fn with_temp_hermes_dir<F: FnOnce(&std::path::Path)>(f: F) {
let guard = support::test_mutex().lock().expect("test mutex poisoned");
let home = support::ensure_test_home();
support::reset_test_fs();
let hermes_dir = home.join(".hermes-roundtrip");
let _ = std::fs::remove_dir_all(&hermes_dir);
std::fs::create_dir_all(&hermes_dir).expect("create temp hermes dir");
update_settings(AppSettings {
hermes_config_dir: Some(hermes_dir.to_string_lossy().into_owned()),
..AppSettings::default()
})
.expect("set hermes_config_dir override");
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&hermes_dir)));
// Always restore settings and drop fixture dir, even on test failure.
let _ = update_settings(AppSettings::default());
let _ = std::fs::remove_dir_all(&hermes_dir);
drop(guard);
if let Err(err) = result {
std::panic::resume_unwind(err);
}
}
#[test]
fn set_provider_preserves_unknown_and_future_fields() {
with_temp_hermes_dir(|dir| {
let yaml = r#"custom_providers:
- name: myhost
base_url: https://api.example.com/v1
api_key: sk-old
api_mode: chat_completions
rate_limit_delay: 0.5
key_env: MY_API_KEY
foo_bar: keep-me-around
models:
gpt-4:
context_length: 8192
"#;
let config_path = dir.join("config.yaml");
std::fs::write(&config_path, yaml).expect("seed config.yaml");
// Simulate the UI sending back only the fields it knows about.
let patch = serde_json::json!({
"name": "myhost",
"base_url": "https://api.example.com/v1",
"api_key": "sk-new",
"api_mode": "chat_completions",
"models": [
{ "id": "gpt-4", "context_length": 8192 }
]
});
hermes_config::set_provider("myhost", patch).expect("set_provider");
let written = std::fs::read_to_string(&config_path).expect("read written config");
assert!(
written.contains("rate_limit_delay"),
"rate_limit_delay stripped:\n{written}"
);
assert!(
written.contains("key_env"),
"key_env key stripped:\n{written}"
);
assert!(
written.contains("MY_API_KEY"),
"key_env value stripped:\n{written}"
);
assert!(
written.contains("foo_bar"),
"unknown forward-compat field stripped:\n{written}"
);
assert!(
written.contains("sk-new"),
"api_key was not updated to sk-new:\n{written}"
);
assert!(
!written.contains("sk-old"),
"old api_key still present:\n{written}"
);
});
}
#[test]
fn get_providers_surfaces_rate_limit_delay_and_key_env() {
with_temp_hermes_dir(|dir| {
let yaml = r#"custom_providers:
- name: myhost
base_url: https://api.example.com/v1
api_key: sk-xxx
api_mode: chat_completions
rate_limit_delay: 2.5
key_env: FOO_KEY
models:
m1: {}
"#;
std::fs::write(dir.join("config.yaml"), yaml).expect("seed config.yaml");
let providers = hermes_config::get_providers().expect("get_providers");
let entry = providers.get("myhost").expect("myhost missing");
assert_eq!(
entry.get("rate_limit_delay").and_then(|v| v.as_f64()),
Some(2.5),
"rate_limit_delay not surfaced to DAO payload"
);
assert_eq!(
entry.get("key_env").and_then(|v| v.as_str()),
Some("FOO_KEY"),
"key_env not surfaced to DAO payload"
);
});
}
-2
View File
@@ -554,7 +554,6 @@ command = "echo"
codex: false, // 初始未启用
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
@@ -683,7 +682,6 @@ fn import_from_claude_merges_into_config() {
codex: false,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
-8
View File
@@ -217,7 +217,6 @@ fn set_mcp_enabled_for_codex_writes_live_config() {
codex: false, // 初始未启用
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
@@ -282,7 +281,6 @@ fn enabling_codex_mcp_skips_when_codex_dir_missing() {
codex: false,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
@@ -327,7 +325,6 @@ fn upsert_mcp_server_disabling_app_removes_from_claude_live_config() {
codex: false,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
@@ -361,7 +358,6 @@ fn upsert_mcp_server_disabling_app_removes_from_claude_live_config() {
codex: false,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
@@ -494,7 +490,6 @@ fn enabling_gemini_mcp_skips_when_gemini_dir_missing() {
codex: false,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
@@ -549,7 +544,6 @@ fn enabling_claude_mcp_skips_when_claude_config_absent() {
codex: false,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
@@ -610,7 +604,6 @@ fn sync_all_enabled_removes_known_disabled_but_preserves_unknown_live_entries()
codex: false,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
@@ -632,7 +625,6 @@ fn sync_all_enabled_removes_known_disabled_but_preserves_unknown_live_entries()
codex: false,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
-1
View File
@@ -75,7 +75,6 @@ command = "say"
codex: true, // 启用 Codex
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
-1
View File
@@ -163,7 +163,6 @@ command = "say"
codex: true,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
+18 -5
View File
@@ -53,8 +53,10 @@ fn import_from_apps_respects_explicit_app_selection() {
vec![ImportSkillSelection {
directory: "shared-skill".to_string(),
apps: SkillApps {
claude: false,
codex: false,
gemini: false,
opencode: true,
..Default::default()
},
}],
)
@@ -101,7 +103,12 @@ fn sync_to_app_removes_disabled_and_orphaned_ssot_symlinks() {
repo_name: None,
repo_branch: None,
readme_url: None,
apps: SkillApps::default(),
apps: SkillApps {
claude: false,
codex: false,
gemini: false,
opencode: false,
},
installed_at: 0,
content_hash: None,
updated_at: 0,
@@ -144,7 +151,9 @@ fn uninstall_skill_creates_backup_before_removing_ssot() {
readme_url: None,
apps: SkillApps {
claude: true,
..Default::default()
codex: false,
gemini: false,
opencode: false,
},
installed_at: 123,
content_hash: None,
@@ -212,7 +221,9 @@ fn restore_skill_backup_restores_files_to_ssot_and_current_app() {
readme_url: None,
apps: SkillApps {
claude: true,
..Default::default()
codex: false,
gemini: false,
opencode: false,
},
installed_at: 456,
content_hash: None,
@@ -293,7 +304,9 @@ fn delete_skill_backup_removes_backup_directory() {
readme_url: None,
apps: SkillApps {
claude: true,
..Default::default()
codex: false,
gemini: false,
opencode: false,
},
installed_at: 789,
content_hash: None,
+20 -138
View File
@@ -14,7 +14,6 @@ import {
Minimize2,
X,
Book,
Brain,
Wrench,
RefreshCw,
History,
@@ -26,7 +25,6 @@ import {
KeyRound,
Shield,
Cpu,
LayoutDashboard,
} from "lucide-react";
import { getCurrentWindow } from "@tauri-apps/api/window";
import type { Provider, VisibleApps } from "@/types";
@@ -41,12 +39,6 @@ import {
import { checkAllEnvConflicts, checkEnvConflicts } from "@/lib/api/env";
import { useProviderActions } from "@/hooks/useProviderActions";
import { openclawKeys, useOpenClawHealth } from "@/hooks/useOpenClaw";
import {
hermesKeys,
useHermesHealth,
useOpenHermesWebUI,
} from "@/hooks/useHermes";
import { hermesApi } from "@/lib/api/hermes";
import { useProxyStatus } from "@/hooks/useProxyStatus";
import { useAutoCompact } from "@/hooks/useAutoCompact";
import { useLastValidValue } from "@/hooks/useLastValidValue";
@@ -90,8 +82,6 @@ import EnvPanel from "@/components/openclaw/EnvPanel";
import ToolsPanel from "@/components/openclaw/ToolsPanel";
import AgentsDefaultsPanel from "@/components/openclaw/AgentsDefaultsPanel";
import OpenClawHealthBanner from "@/components/openclaw/OpenClawHealthBanner";
import HermesHealthBanner from "@/components/hermes/HermesHealthBanner";
import HermesMemoryPanel from "@/components/hermes/HermesMemoryPanel";
type View =
| "providers"
@@ -106,8 +96,7 @@ type View =
| "workspace"
| "openclawEnv"
| "openclawTools"
| "openclawAgents"
| "hermesMemory";
| "openclawAgents";
interface WebDavSyncStatusUpdatedPayload {
source?: string;
@@ -125,7 +114,6 @@ const VALID_APPS: AppId[] = [
"gemini",
"opencode",
"openclaw",
"hermes",
];
const getInitialApp = (): AppId => {
@@ -151,7 +139,6 @@ const VALID_VIEWS: View[] = [
"openclawEnv",
"openclawTools",
"openclawAgents",
"hermesMemory",
];
const getInitialView = (): View => {
@@ -187,7 +174,6 @@ function App() {
gemini: true,
opencode: true,
openclaw: true,
hermes: true,
};
const getFirstVisibleApp = (): AppId => {
@@ -196,7 +182,6 @@ function App() {
if (visibleApps.gemini) return "gemini";
if (visibleApps.opencode) return "opencode";
if (visibleApps.openclaw) return "openclaw";
if (visibleApps.hermes) return "hermes";
return "claude"; // fallback
};
@@ -214,8 +199,7 @@ function App() {
activeApp !== "codex" &&
activeApp !== "opencode" &&
activeApp !== "openclaw" &&
activeApp !== "gemini" &&
activeApp !== "hermes"
activeApp !== "gemini"
) {
setCurrentView("providers");
}
@@ -271,16 +255,13 @@ function App() {
currentView === "openclawAgents");
const { data: openclawHealthWarnings = [] } =
useOpenClawHealth(isOpenClawView);
const isHermesView = activeApp === "hermes" && currentView === "providers";
const { data: hermesHealthWarnings = [] } = useHermesHealth(isHermesView);
const hasSkillsSupport = true;
const hasSessionSupport =
activeApp === "claude" ||
activeApp === "codex" ||
activeApp === "opencode" ||
activeApp === "openclaw" ||
activeApp === "gemini" ||
activeApp === "hermes";
activeApp === "gemini";
const {
addProvider,
@@ -629,11 +610,6 @@ function App() {
};
}, []);
const [launchDashboardOpen, setLaunchDashboardOpen] = useState(false);
const openHermesWebUI = useOpenHermesWebUI(() =>
setLaunchDashboardOpen(true),
);
const handleOpenWebsite = async (url: string) => {
try {
await settingsApi.openExternal(url);
@@ -678,13 +654,6 @@ function App() {
await queryClient.invalidateQueries({
queryKey: openclawKeys.health,
});
} else if (activeApp === "hermes") {
await queryClient.invalidateQueries({
queryKey: hermesKeys.liveProviderIds,
});
await queryClient.invalidateQueries({
queryKey: hermesKeys.health,
});
}
toast.success(
t("notifications.removeFromConfigSuccess", {
@@ -735,11 +704,7 @@ function App() {
iconColor: provider.iconColor,
};
if (
activeApp === "opencode" ||
activeApp === "openclaw" ||
activeApp === "hermes"
) {
if (activeApp === "opencode" || activeApp === "openclaw") {
let liveProviderIds: string[] = [];
try {
liveProviderIds =
@@ -748,15 +713,10 @@ function App() {
queryKey: ["opencodeLiveProviderIds"],
queryFn: () => providersApi.getOpenCodeLiveProviderIds(),
})
: activeApp === "openclaw"
? await queryClient.ensureQueryData({
queryKey: openclawKeys.liveProviderIds,
queryFn: () => providersApi.getOpenClawLiveProviderIds(),
})
: await queryClient.ensureQueryData({
queryKey: hermesKeys.liveProviderIds,
queryFn: () => providersApi.getHermesLiveProviderIds(),
});
: await queryClient.ensureQueryData({
queryKey: openclawKeys.liveProviderIds,
queryFn: () => providersApi.getOpenClawLiveProviderIds(),
});
} catch (error) {
console.error(
"[App] Failed to load live provider IDs for duplication",
@@ -917,8 +877,6 @@ function App() {
appId={activeApp}
/>
);
case "hermesMemory":
return <HermesMemoryPanel />;
case "skills":
return (
<UnifiedSkillsPanel
@@ -993,9 +951,7 @@ function App() {
setConfirmAction({ provider, action: "delete" })
}
onRemoveFromConfig={
activeApp === "opencode" ||
activeApp === "openclaw" ||
activeApp === "hermes"
activeApp === "opencode" || activeApp === "openclaw"
? (provider) =>
setConfirmAction({ provider, action: "remove" })
: undefined
@@ -1016,11 +972,7 @@ function App() {
}
onCreate={() => setIsAddOpen(true)}
onSetAsDefault={
activeApp === "openclaw"
? setAsDefaultModel
: activeApp === "hermes"
? switchProvider
: undefined
activeApp === "openclaw" ? setAsDefaultModel : undefined
}
/>
</motion.div>
@@ -1181,7 +1133,6 @@ function App() {
{currentView === "openclawTools" && t("openclaw.tools.title")}
{currentView === "openclawAgents" &&
t("openclaw.agents.title")}
{currentView === "hermesMemory" && t("hermes.memory.title")}
</h1>
</div>
) : (
@@ -1242,8 +1193,7 @@ function App() {
<div className="flex flex-1 min-w-0 items-center justify-end gap-1.5">
{currentView === "providers" &&
activeApp !== "opencode" &&
activeApp !== "openclaw" &&
activeApp !== "hermes" && (
activeApp !== "openclaw" && (
<div
className="flex shrink-0 items-center gap-1.5"
style={{ WebkitAppRegion: "no-drag" } as any}
@@ -1378,11 +1328,7 @@ function App() {
<AnimatePresence mode="wait">
<motion.div
key={
activeApp === "openclaw"
? "openclaw"
: activeApp === "hermes"
? "hermes"
: "default"
activeApp === "openclaw" ? "openclaw" : "default"
}
className="flex items-center gap-1"
initial={{ opacity: 0 }}
@@ -1390,52 +1336,13 @@ function App() {
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
{activeApp === "hermes" ? (
<>
<Button
variant="ghost"
size="sm"
onClick={() => setCurrentView("skills")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
title={t("skills.manage")}
>
<Wrench className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setCurrentView("hermesMemory")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
title={t("hermes.memory.title")}
>
<Brain className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => void openHermesWebUI()}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
title={t("hermes.webui.open")}
>
<LayoutDashboard className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setCurrentView("mcp")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
title={t("mcp.title")}
>
<McpIcon size={16} />
</Button>
</>
) : activeApp === "openclaw" ? (
{activeApp === "openclaw" ? (
<>
<Button
variant="ghost"
size="sm"
onClick={() => setCurrentView("workspace")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title={t("workspace.manage")}
>
<FolderOpen className="w-4 h-4" />
@@ -1444,7 +1351,7 @@ function App() {
variant="ghost"
size="sm"
onClick={() => setCurrentView("openclawEnv")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title={t("openclaw.env.title")}
>
<KeyRound className="w-4 h-4" />
@@ -1453,7 +1360,7 @@ function App() {
variant="ghost"
size="sm"
onClick={() => setCurrentView("openclawTools")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title={t("openclaw.tools.title")}
>
<Shield className="w-4 h-4" />
@@ -1462,7 +1369,7 @@ function App() {
variant="ghost"
size="sm"
onClick={() => setCurrentView("openclawAgents")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title={t("openclaw.agents.title")}
>
<Cpu className="w-4 h-4" />
@@ -1471,7 +1378,7 @@ function App() {
variant="ghost"
size="sm"
onClick={() => setCurrentView("sessions")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title={t("sessionManager.title")}
>
<History className="w-4 h-4" />
@@ -1498,7 +1405,7 @@ function App() {
variant="ghost"
size="sm"
onClick={() => setCurrentView("prompts")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title={t("prompts.manage")}
>
<Book className="w-4 h-4" />
@@ -1522,7 +1429,7 @@ function App() {
variant="ghost"
size="sm"
onClick={() => setCurrentView("mcp")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title={t("mcp.title")}
>
<McpIcon size={16} />
@@ -1552,9 +1459,6 @@ function App() {
{isOpenClawView && openclawHealthWarnings.length > 0 && (
<OpenClawHealthBanner warnings={openclawHealthWarnings} />
)}
{isHermesView && hermesHealthWarnings.length > 0 && (
<HermesHealthBanner warnings={hermesHealthWarnings} />
)}
{renderContent()}
</main>
@@ -1615,28 +1519,6 @@ function App() {
onCancel={() => setConfirmAction(null)}
/>
<ConfirmDialog
isOpen={launchDashboardOpen}
title={t("hermes.webui.launchConfirmTitle")}
message={t("hermes.webui.launchConfirmMessage")}
confirmText={t("hermes.webui.launchConfirmAction")}
variant="info"
onConfirm={() => {
setLaunchDashboardOpen(false);
void (async () => {
try {
await hermesApi.launchDashboard();
toast.success(t("hermes.webui.launching"));
} catch (error) {
toast.error(t("hermes.webui.launchFailed"), {
description: extractErrorMessage(error) || undefined,
});
}
})();
}}
onCancel={() => setLaunchDashboardOpen(false)}
/>
<DeepLinkImportDialog />
<FirstRunNoticeDialog />
</div>
+1 -10
View File
@@ -10,14 +10,7 @@ interface AppSwitcherProps {
compact?: boolean;
}
const ALL_APPS: AppId[] = [
"claude",
"codex",
"gemini",
"opencode",
"openclaw",
"hermes",
];
const ALL_APPS: AppId[] = ["claude", "codex", "gemini", "opencode", "openclaw"];
const STORAGE_KEY = "cc-switch-last-app";
export function AppSwitcher({
@@ -38,7 +31,6 @@ export function AppSwitcher({
gemini: "gemini",
opencode: "opencode",
openclaw: "openclaw",
hermes: "hermes",
};
const appDisplayName: Record<AppId, string> = {
claude: "Claude",
@@ -46,7 +38,6 @@ export function AppSwitcher({
gemini: "Gemini",
opencode: "OpenCode",
openclaw: "OpenClaw",
hermes: "Hermes",
};
// Filter apps based on visibility settings (default all visible)
+2 -4
View File
@@ -31,7 +31,7 @@ export const TIER_I18N_KEYS: Record<string, string> = {
gemini_flash: "subscription.geminiFlash",
gemini_flash_lite: "subscription.geminiFlashLite",
// Token Planfive_hour 已在上方官方映射中)
weekly_limit: "subscription.sevenDay",
weekly_limit: "subscription.weeklyLimit",
// GitHub Copilot
premium: "subscription.copilotPremium",
};
@@ -205,9 +205,7 @@ export const SubscriptionQuotaView: React.FC<SubscriptionQuotaViewProps> = ({
}
// 成功获取数据
const tiers = (quota.tiers || []).filter(
(tier) => tier.name in TIER_I18N_KEYS,
);
const tiers = quota.tiers || [];
if (tiers.length === 0) return null;
// ── inline 模式:紧凑两行显示 ──
+12 -17
View File
@@ -73,7 +73,6 @@ const generatePresetTemplates = (
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer {{accessToken}}",
"User-Agent": "cc-switch/1.0",
"New-Api-User": "{{userId}}"
},
},
@@ -204,18 +203,6 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
apiKey: env.GEMINI_API_KEY,
baseUrl: env.GOOGLE_GEMINI_BASE_URL,
};
} else if (appId === "hermes") {
// Hermes: settingsConfig 顶层扁平(snake_case,对应 config.yaml
return {
apiKey: (config as any).api_key,
baseUrl: (config as any).base_url,
};
} else if (appId === "openclaw") {
// OpenClaw: settingsConfig 顶层扁平(camelCase,对应 openclaw.json
return {
apiKey: (config as any).apiKey,
baseUrl: (config as any).baseUrl,
};
}
return { apiKey: undefined, baseUrl: undefined };
} catch (error) {
@@ -420,8 +407,12 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
try {
// 官方余额查询模板使用专用 API
if (selectedTemplate === TEMPLATE_TYPES.BALANCE) {
const baseUrl = providerCredentials.baseUrl ?? "";
const apiKey = providerCredentials.apiKey ?? "";
const config = provider.settingsConfig as Record<string, any>;
const baseUrl: string = config?.env?.ANTHROPIC_BASE_URL ?? "";
const apiKey: string =
config?.env?.ANTHROPIC_AUTH_TOKEN ??
config?.env?.ANTHROPIC_API_KEY ??
"";
const { subscriptionApi } = await import("@/lib/api/subscription");
const result = await subscriptionApi.getBalance(baseUrl, apiKey);
if (result.success && result.data && result.data.length > 0) {
@@ -447,8 +438,12 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
// Coding Plan 模板使用专用 API
if (selectedTemplate === TEMPLATE_TYPES.TOKEN_PLAN) {
const baseUrl = providerCredentials.baseUrl ?? "";
const apiKey = providerCredentials.apiKey ?? "";
const config = provider.settingsConfig as Record<string, any>;
const baseUrl: string = config?.env?.ANTHROPIC_BASE_URL ?? "";
const apiKey: string =
config?.env?.ANTHROPIC_AUTH_TOKEN ??
config?.env?.ANTHROPIC_API_KEY ??
"";
const { subscriptionApi } = await import("@/lib/api/subscription");
const quota = await subscriptionApi.getCodingPlanQuota(baseUrl, apiKey);
if (quota.success && quota.tiers.length > 0) {
@@ -1,127 +0,0 @@
import React, { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { ExternalLink, TriangleAlert } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { useOpenHermesWebUI } from "@/hooks/useHermes";
import type { HermesHealthWarning } from "@/types";
interface HermesHealthBannerProps {
warnings: HermesHealthWarning[];
}
function getWarningText(
code: string,
fallback: string,
t: ReturnType<typeof useTranslation>["t"],
) {
switch (code) {
case "config_parse_failed":
return t("hermes.health.parseFailed", {
defaultValue:
"config.yaml could not be parsed as valid YAML. Fix the file before editing it here.",
});
case "config_not_found":
return t("hermes.health.configNotFound", {
defaultValue:
"Hermes config.yaml not found. Create it at ~/.hermes/config.yaml or configure the path in settings.",
});
case "env_parse_failed":
return t("hermes.health.envParseFailed", {
defaultValue: "The .env file could not be parsed.",
});
case "model_no_default":
return t("hermes.health.modelNoDefault", {
defaultValue:
"No default model or provider is configured in the 'model' section.",
});
case "custom_providers_not_list":
return t("hermes.health.customProvidersNotList", {
defaultValue:
"custom_providers should be a YAML list (items prefixed with '-'), not a mapping.",
});
case "model_provider_unknown":
return t("hermes.health.modelProviderUnknown", {
defaultValue:
"model.provider references a provider that is not configured.",
});
case "model_default_not_in_provider":
return t("hermes.health.modelDefaultNotInProvider", {
defaultValue:
"model.default is not in the selected provider's models list.",
});
case "duplicate_provider_name":
return t("hermes.health.duplicateProviderName", {
defaultValue:
"custom_providers contains duplicate provider names — only one entry will be used.",
});
case "duplicate_provider_base_url":
return t("hermes.health.duplicateProviderBaseUrl", {
defaultValue:
"custom_providers contains duplicate base_urls — possible accidental copy.",
});
case "schema_migrated_v12":
return t("hermes.health.schemaMigratedV12", {
defaultValue:
"Hermes' newer schema moved some providers into the 'providers:' dict. They are shown read-only in CC Switch — edit or remove those entries via Hermes Web UI.",
});
default:
return fallback;
}
}
const HermesHealthBanner: React.FC<HermesHealthBannerProps> = ({
warnings,
}) => {
const { t } = useTranslation();
const openHermesWebUI = useOpenHermesWebUI();
const items = useMemo(
() =>
warnings.map((warning) => ({
...warning,
text: getWarningText(warning.code, warning.message, t),
})),
[t, warnings],
);
if (warnings.length === 0) {
return null;
}
return (
<div className="px-6 pt-4">
<Alert className="border-amber-500/30 bg-amber-500/5">
<TriangleAlert className="h-4 w-4" />
<AlertTitle className="flex items-center justify-between gap-2">
<span>
{t("hermes.health.title", {
defaultValue: "Hermes config warnings detected",
})}
</span>
<Button
variant="outline"
size="sm"
onClick={() => void openHermesWebUI("/config")}
className="shrink-0"
>
<ExternalLink className="w-3.5 h-3.5 mr-1" />
{t("hermes.webui.fixInWebUI")}
</Button>
</AlertTitle>
<AlertDescription>
<ul className="list-disc space-y-1 pl-5">
{items.map((warning) => (
<li key={`${warning.code}:${warning.path ?? warning.message}`}>
{warning.text}
{warning.path ? ` (${warning.path})` : ""}
</li>
))}
</ul>
</AlertDescription>
</Alert>
</div>
);
};
export default HermesHealthBanner;
-179
View File
@@ -1,179 +0,0 @@
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { ExternalLink } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import MarkdownEditor from "@/components/MarkdownEditor";
import {
useHermesMemory,
useHermesMemoryLimits,
useOpenHermesWebUI,
useSaveHermesMemory,
useToggleHermesMemoryEnabled,
} from "@/hooks/useHermes";
import { useDarkMode } from "@/hooks/useDarkMode";
import type { HermesMemoryKind } from "@/types";
import { cn } from "@/lib/utils";
interface MemoryTabPaneProps {
kind: HermesMemoryKind;
limit: number;
enabled: boolean;
}
const MemoryTabPane: React.FC<MemoryTabPaneProps> = ({
kind,
limit,
enabled,
}) => {
const { t } = useTranslation();
const darkMode = useDarkMode();
const { data, isLoading } = useHermesMemory(kind, true);
const saveMutation = useSaveHermesMemory();
const toggleMutation = useToggleHermesMemoryEnabled();
const [content, setContent] = useState("");
const [loaded, setLoaded] = useState(false);
// Hydrate local dirty buffer from query data only on first load. Later
// refetches (e.g. after a successful save) must not clobber in-flight user
// edits — the caller owns `content` until they click Save again.
useEffect(() => {
if (!loaded && data !== undefined) {
setContent(data);
setLoaded(true);
}
}, [data, loaded]);
const handleSave = async () => {
try {
await saveMutation.mutateAsync({ kind, content });
toast.success(t("hermes.memory.saveSuccess"));
} catch {
// useSaveHermesMemory already surfaces a localized error toast.
}
};
const charCount = content.length;
const isOver = charCount > limit;
return (
<div className="flex flex-col gap-3">
<div
className={cn(
"flex items-center justify-between px-3 py-2 rounded-md border",
enabled ? "bg-muted/30" : "bg-amber-500/10 border-amber-500/30",
)}
>
<div className="flex items-center gap-2">
<Switch
checked={enabled}
disabled={toggleMutation.isPending}
onCheckedChange={(next) =>
toggleMutation.mutate({ kind, enabled: next })
}
/>
<span className="text-sm">
{enabled
? t("hermes.memory.enableOn")
: t("hermes.memory.enableOff")}
</span>
</div>
{!enabled && (
<span className="text-xs text-amber-700 dark:text-amber-400">
{t("hermes.memory.disabledHint")}
</span>
)}
</div>
{isLoading && !loaded ? (
<div className="flex items-center justify-center h-64 text-muted-foreground">
{t("prompts.loading")}
</div>
) : (
<MarkdownEditor
value={content}
onChange={setContent}
darkMode={darkMode}
minHeight="calc(100vh - 320px)"
/>
)}
<div className="flex items-center justify-between gap-3 text-sm">
<span
className={cn(
"text-muted-foreground",
isOver && "text-red-600 dark:text-red-400 font-medium",
)}
>
{t("hermes.memory.usage", { current: charCount, limit })}
{isOver ? `${t("hermes.memory.overLimit")}` : ""}
</span>
<div className="flex items-center gap-3">
<span className="hidden md:inline text-xs text-muted-foreground">
{t("hermes.memory.runtimeNote")}
</span>
<Button
onClick={handleSave}
disabled={saveMutation.isPending || !loaded}
>
{saveMutation.isPending ? t("common.saving") : t("common.save")}
</Button>
</div>
</div>
</div>
);
};
const HermesMemoryPanel: React.FC = () => {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState<HermesMemoryKind>("memory");
const openHermesWebUI = useOpenHermesWebUI();
const { data: limits } = useHermesMemoryLimits(true);
const memoryLimit = limits?.memory ?? 2200;
const userLimit = limits?.user ?? 1375;
const memoryEnabled = limits?.memoryEnabled ?? true;
const userEnabled = limits?.userEnabled ?? true;
return (
<div className="flex flex-col h-full">
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as HermesMemoryKind)}
className="flex-1 flex flex-col"
>
<div className="px-6 pt-4 flex items-center justify-between gap-3 flex-wrap">
<TabsList>
<TabsTrigger value="memory">
{t("hermes.memory.agentTab")}
</TabsTrigger>
<TabsTrigger value="user">{t("hermes.memory.userTab")}</TabsTrigger>
</TabsList>
<Button
variant="outline"
size="sm"
onClick={() => void openHermesWebUI("/config")}
>
<ExternalLink className="w-3.5 h-3.5 mr-1" />
{t("hermes.memory.openConfig")}
</Button>
</div>
<TabsContent value="memory" className="flex-1 px-6 pb-4 mt-4">
<MemoryTabPane
kind="memory"
limit={memoryLimit}
enabled={memoryEnabled}
/>
</TabsContent>
<TabsContent value="user" className="flex-1 px-6 pb-4 mt-4">
<MemoryTabPane kind="user" limit={userLimit} enabled={userEnabled} />
</TabsContent>
</Tabs>
</div>
);
};
export default HermesMemoryPanel;
-18
View File
@@ -67,7 +67,6 @@ const McpFormModal: React.FC<McpFormModalProps> = ({
gemini: boolean;
opencode: boolean;
openclaw: boolean;
hermes: boolean;
}>(() => {
if (initialData?.apps) {
return { ...initialData.apps };
@@ -78,7 +77,6 @@ const McpFormModal: React.FC<McpFormModalProps> = ({
gemini: defaultEnabledApps.includes("gemini"),
opencode: defaultEnabledApps.includes("opencode"),
openclaw: defaultEnabledApps.includes("openclaw"),
hermes: defaultEnabledApps.includes("hermes"),
};
});
@@ -581,22 +579,6 @@ const McpFormModal: React.FC<McpFormModalProps> = ({
{t("mcp.unifiedPanel.apps.opencode")}
</label>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="enable-hermes"
checked={enabledApps.hermes}
onCheckedChange={(checked: boolean) =>
setEnabledApps({ ...enabledApps, hermes: checked })
}
/>
<label
htmlFor="enable-hermes"
className="text-sm text-foreground cursor-pointer select-none"
>
{t("mcp.unifiedPanel.apps.hermes")}
</label>
</div>
</div>
</div>
+5 -12
View File
@@ -17,7 +17,7 @@ import { Edit3, Trash2, ExternalLink } from "lucide-react";
import { settingsApi } from "@/lib/api";
import { mcpPresets } from "@/config/mcpPresets";
import { toast } from "sonner";
import { MCP_APP_IDS } from "@/config/appConfig";
import { MCP_SKILLS_APP_IDS } from "@/config/appConfig";
import { AppCountBar } from "@/components/common/AppCountBar";
import { AppToggleGroup } from "@/components/common/AppToggleGroup";
import { ListItemRow } from "@/components/common/ListItemRow";
@@ -56,16 +56,9 @@ const UnifiedMcpPanel = React.forwardRef<
}, [serversMap]);
const enabledCounts = useMemo(() => {
const counts = {
claude: 0,
codex: 0,
gemini: 0,
opencode: 0,
openclaw: 0,
hermes: 0,
};
const counts = { claude: 0, codex: 0, gemini: 0, opencode: 0, openclaw: 0 };
serverEntries.forEach(([_, server]) => {
for (const app of MCP_APP_IDS) {
for (const app of MCP_SKILLS_APP_IDS) {
if (server.apps[app]) counts[app]++;
}
});
@@ -143,7 +136,7 @@ const UnifiedMcpPanel = React.forwardRef<
<AppCountBar
totalLabel={t("mcp.serverCount", { count: serverEntries.length })}
counts={enabledCounts}
appIds={MCP_APP_IDS}
appIds={MCP_SKILLS_APP_IDS}
/>
<div className="flex-1 overflow-y-auto overflow-x-hidden pb-24">
@@ -285,7 +278,7 @@ const UnifiedMcpListItem: React.FC<UnifiedMcpListItemProps> = ({
<AppToggleGroup
apps={server.apps}
onToggle={(app, enabled) => onToggleApp(id, app, enabled)}
appIds={MCP_APP_IDS}
appIds={MCP_SKILLS_APP_IDS}
/>
<div className="flex items-center gap-0.5 flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
@@ -35,7 +35,6 @@ const PromptFormModal: React.FC<PromptFormModalProps> = ({
codex: "AGENTS.md",
gemini: "GEMINI.md",
opencode: "AGENTS.md",
hermes: "AGENTS.md",
};
const filename = filenameMap[appId as Exclude<AppId, "openclaw">];
const [name, setName] = useState("");
@@ -30,7 +30,6 @@ const PromptFormPanel: React.FC<PromptFormPanelProps> = ({
gemini: "GEMINI.md",
opencode: "AGENTS.md",
openclaw: "AGENTS.md",
hermes: "AGENTS.md",
};
const filename = filenameMap[appId];
const [name, setName] = useState("");
@@ -41,8 +41,7 @@ export function AddProviderDialog({
}: AddProviderDialogProps) {
const { t } = useTranslation();
// OpenCode and OpenClaw don't support universal providers
const showUniversalTab =
appId !== "opencode" && appId !== "openclaw" && appId !== "hermes";
const showUniversalTab = appId !== "opencode" && appId !== "openclaw";
const [activeTab, setActiveTab] = useState<"app-specific" | "universal">(
"app-specific",
);
@@ -107,7 +106,7 @@ export function AddProviderDialog({
// OpenCode/OpenClaw: pass providerKey for ID generation
if (
(appId === "opencode" || appId === "openclaw" || appId === "hermes") &&
(appId === "opencode" || appId === "openclaw") &&
values.providerKey
) {
providerData.providerKey = values.providerKey;
@@ -204,10 +203,6 @@ export function AddProviderDialog({
if (parsedConfig.baseUrl) {
addUrl(parsedConfig.baseUrl as string);
}
} else if (appId === "hermes") {
if (parsedConfig.base_url) {
addUrl(parsedConfig.base_url as string);
}
}
const urls = Array.from(urlSet);
+26 -50
View File
@@ -38,8 +38,6 @@ interface ProviderActionsProps {
isInFailoverQueue?: boolean;
onToggleFailover?: (enabled: boolean) => void;
isOfficialBlockedByProxy?: boolean;
// Hermes v12+ providers: dict overlay — edit/delete must go through Web UI
isReadOnly?: boolean;
// OpenClaw: default model
isDefaultModel?: boolean;
onSetAsDefault?: () => void;
@@ -65,7 +63,6 @@ export function ProviderActions({
isInFailoverQueue = false,
onToggleFailover,
isOfficialBlockedByProxy = false,
isReadOnly = false,
// OpenClaw: default model
isDefaultModel = false,
onSetAsDefault,
@@ -73,11 +70,9 @@ export function ProviderActions({
const { t } = useTranslation();
const iconButtonClass = "h-8 w-8 p-1";
// 累加模式应用(OpenCode 非 OMO / OpenClaw / Hermes
// 累加模式应用(OpenCode 非 OMO OpenClaw
const isAdditiveMode =
(appId === "opencode" && !isOmo) ||
appId === "openclaw" ||
appId === "hermes";
(appId === "opencode" && !isOmo) || appId === "openclaw";
// 故障转移模式下的按钮逻辑(累加模式和 OMO 应用不支持故障转移)
const isFailoverMode =
@@ -208,44 +203,29 @@ export function ProviderActions({
const buttonState = getMainButtonState();
const canDelete =
!isReadOnly && (isOmo || isAdditiveMode ? true : !isCurrent);
const readOnlyHint = t("provider.managedByHermesHint", {
defaultValue: "由 Hermes 管理,请在 Hermes Web UI 中编辑",
});
const canDelete = isOmo || isAdditiveMode ? true : !isCurrent;
return (
<div className="flex items-center gap-1.5">
{(appId === "openclaw" || appId === "hermes") &&
isInConfig &&
onSetAsDefault &&
(() => {
const activeLabel =
appId === "hermes"
? t("provider.inUse", { defaultValue: "已在用" })
: t("provider.isDefault", { defaultValue: "当前默认" });
const inactiveLabel =
appId === "hermes"
? t("provider.enable", { defaultValue: "启用" })
: t("provider.setAsDefault", { defaultValue: "设为默认" });
return (
<Button
size="sm"
variant={isDefaultModel ? "secondary" : "default"}
onClick={isDefaultModel ? undefined : onSetAsDefault}
disabled={isDefaultModel}
className={cn(
"w-fit px-2.5",
isDefaultModel
? "bg-gray-200 text-muted-foreground dark:bg-gray-700 opacity-60 cursor-not-allowed"
: "bg-blue-500 hover:bg-blue-600 dark:bg-blue-600 dark:hover:bg-blue-700",
)}
>
<Zap className="h-4 w-4" />
{isDefaultModel ? activeLabel : inactiveLabel}
</Button>
);
})()}
{appId === "openclaw" && isInConfig && onSetAsDefault && (
<Button
size="sm"
variant={isDefaultModel ? "secondary" : "default"}
onClick={isDefaultModel ? undefined : onSetAsDefault}
disabled={isDefaultModel}
className={cn(
"w-fit px-2.5",
isDefaultModel
? "bg-gray-200 text-muted-foreground dark:bg-gray-700 opacity-60 cursor-not-allowed"
: "bg-blue-500 hover:bg-blue-600 dark:bg-blue-600 dark:hover:bg-blue-700",
)}
>
<Zap className="h-4 w-4" />
{isDefaultModel
? t("provider.isDefault", { defaultValue: "当前默认" })
: t("provider.setAsDefault", { defaultValue: "设为默认" })}
</Button>
)}
<Button
size="sm"
@@ -262,13 +242,9 @@ export function ProviderActions({
<Button
size="icon"
variant="ghost"
onClick={isReadOnly ? undefined : onEdit}
disabled={isReadOnly}
title={isReadOnly ? readOnlyHint : t("common.edit")}
className={cn(
iconButtonClass,
isReadOnly && "opacity-40 cursor-not-allowed text-muted-foreground",
)}
onClick={onEdit}
title={t("common.edit")}
className={iconButtonClass}
>
<Edit className="h-4 w-4" />
</Button>
@@ -334,7 +310,7 @@ export function ProviderActions({
size="icon"
variant="ghost"
onClick={canDelete ? onDelete : undefined}
title={isReadOnly ? readOnlyHint : t("common.delete")}
title={t("common.delete")}
className={cn(
iconButtonClass,
canDelete && "hover:text-red-500 dark:hover:text-red-400",
+2 -23
View File
@@ -15,7 +15,6 @@ import SubscriptionQuotaFooter from "@/components/SubscriptionQuotaFooter";
import CopilotQuotaFooter from "@/components/CopilotQuotaFooter";
import CodexOauthQuotaFooter from "@/components/CodexOauthQuotaFooter";
import { PROVIDER_TYPES } from "@/config/constants";
import { isHermesReadOnlyProvider } from "@/config/hermesProviderPresets";
import { ProviderHealthBadge } from "@/components/providers/ProviderHealthBadge";
import { FailoverPriorityBadge } from "@/components/providers/FailoverPriorityBadge";
import { extractCodexBaseUrl } from "@/utils/providerConfigUtils";
@@ -181,19 +180,13 @@ export function ProviderCard({
const isCopilot =
provider.meta?.providerType === PROVIDER_TYPES.GITHUB_COPILOT ||
provider.meta?.usage_script?.templateType === "github_copilot";
// Hermes v12+ overlay entries live under the `providers:` dict and are
// read-only here — writes have to go through Hermes Web UI.
const isHermesReadOnly =
appId === "hermes" && isHermesReadOnlyProvider(provider.settingsConfig);
const isCodexOauth =
provider.meta?.providerType === PROVIDER_TYPES.CODEX_OAUTH;
// 获取用量数据以判断是否有多套餐
// 累加模式应用(OpenCode/OpenClaw/Hermes):使用 isInConfig 代替 isCurrent
// 累加模式应用(OpenCode/OpenClaw):使用 isInConfig 代替 isCurrent
const shouldAutoQuery =
appId === "opencode" || appId === "openclaw" || appId === "hermes"
? isInConfig
: isCurrent;
appId === "opencode" || appId === "openclaw" ? isInConfig : isCurrent;
const autoQueryInterval = shouldAutoQuery
? provider.meta?.usage_script?.autoQueryInterval || 0
: 0;
@@ -341,19 +334,6 @@ export function ProviderCard({
</span>
)}
{isHermesReadOnly && (
<span
className="inline-flex items-center rounded-md bg-slate-200 px-1.5 py-0.5 text-[10px] font-semibold text-slate-700 dark:bg-slate-700/60 dark:text-slate-200"
title={t("provider.managedByHermesHint", {
defaultValue: "由 Hermes 管理,请在 Hermes Web UI 中编辑",
})}
>
{t("provider.managedByHermes", {
defaultValue: "Hermes Managed",
})}
</span>
)}
</div>
{displayUrl && (
@@ -447,7 +427,6 @@ export function ProviderCard({
isTesting={isTesting}
isProxyTakeover={isProxyTakeover}
isOfficialBlockedByProxy={isOfficialBlockedByProxy}
isReadOnly={isHermesReadOnly}
isOmo={isAnyOmo}
onSwitch={() => onSwitch(provider)}
onEdit={() => onEdit(provider)}
+5 -31
View File
@@ -25,10 +25,6 @@ import {
useOpenClawLiveProviderIds,
useOpenClawDefaultModel,
} from "@/hooks/useOpenClaw";
import {
useHermesLiveProviderIds,
useHermesModelConfig,
} from "@/hooks/useHermes";
import { useStreamCheck } from "@/hooks/useStreamCheck";
import { ProviderCard } from "@/components/providers/ProviderCard";
import { ProviderEmptyState } from "@/components/providers/ProviderEmptyState";
@@ -109,14 +105,7 @@ export function ProviderList({
appId === "openclaw",
);
// Hermes: 查询 live 配置中的供应商 ID 列表,用于判断 isInConfig
const { data: hermesLiveIds } = useHermesLiveProviderIds(appId === "hermes");
// Hermes: 读取当前 model.provider,用于判断哪个供应商是"当前激活"(高亮)
const { data: hermesModelConfig } = useHermesModelConfig(appId === "hermes");
const hermesCurrentProviderId = hermesModelConfig?.provider;
// 判断供应商是否已添加到配置(累加模式应用:OpenCode/OpenClaw/Hermes
// 判断供应商是否已添加到配置(累加模式应用:OpenCode/OpenClaw
const isProviderInConfig = useCallback(
(providerId: string): boolean => {
if (appId === "opencode") {
@@ -125,12 +114,9 @@ export function ProviderList({
if (appId === "openclaw") {
return openclawLiveIds?.includes(providerId) ?? false;
}
if (appId === "hermes") {
return hermesLiveIds?.includes(providerId) ?? false;
}
return true; // 其他应用始终返回 true
},
[appId, opencodeLiveIds, openclawLiveIds, hermesLiveIds],
[appId, opencodeLiveIds, openclawLiveIds],
);
// OpenClaw: query default model to determine which provider is default
@@ -243,10 +229,6 @@ export function ProviderList({
const count = await providersApi.importOpenClawFromLive();
return count > 0;
}
if (appId === "hermes") {
const count = await providersApi.importHermesFromLive();
return count > 0;
}
return providersApi.importDefault(appId);
},
onSuccess: (imported) => {
@@ -341,8 +323,6 @@ export function ProviderList({
const isOmoCurrent = isOmo && provider.id === (currentOmoId || "");
const isOmoSlimCurrent =
isOmoSlim && provider.id === (currentOmoSlimId || "");
const isHermesCurrent =
appId === "hermes" && hermesCurrentProviderId === provider.id;
return (
<SortableProviderCard
key={provider.id}
@@ -352,9 +332,7 @@ export function ProviderList({
? isOmoCurrent
: isOmoSlim
? isOmoSlimCurrent
: appId === "hermes"
? isHermesCurrent
: provider.id === currentProviderId
: provider.id === currentProviderId
}
appId={appId}
isInConfig={isProviderInConfig(provider.id)}
@@ -381,12 +359,8 @@ export function ProviderList({
handleToggleFailover(provider.id, enabled)
}
activeProviderId={activeProviderId}
// OpenClaw: default model / Hermes: model.provider === provider.id
isDefaultModel={
appId === "hermes"
? isHermesCurrent
: isProviderDefaultModel(provider.id)
}
// OpenClaw: default model
isDefaultModel={isProviderDefaultModel(provider.id)}
onSetAsDefault={
onSetAsDefault ? () => onSetAsDefault(provider) : undefined
}
@@ -24,13 +24,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
ChevronDown,
ChevronRight,
Download,
Loader2,
Wand2,
} from "lucide-react";
import { ChevronDown, ChevronRight, Download, Loader2 } from "lucide-react";
import EndpointSpeedTest from "./EndpointSpeedTest";
import { ApiKeySection, EndpointField, ModelInputWithFetch } from "./shared";
import { CopilotAuthSection } from "./CopilotAuthSection";
@@ -102,12 +96,14 @@ interface ClaudeFormFieldsProps {
// Model Selector
shouldShowModelSelector: boolean;
claudeModel: string;
reasoningModel: string;
defaultHaikuModel: string;
defaultSonnetModel: string;
defaultOpusModel: string;
onModelChange: (
field:
| "ANTHROPIC_MODEL"
| "ANTHROPIC_REASONING_MODEL"
| "ANTHROPIC_DEFAULT_HAIKU_MODEL"
| "ANTHROPIC_DEFAULT_SONNET_MODEL"
| "ANTHROPIC_DEFAULT_OPUS_MODEL",
@@ -162,6 +158,7 @@ export function ClaudeFormFields({
onAutoSelectChange,
shouldShowModelSelector,
claudeModel,
reasoningModel,
defaultHaikuModel,
defaultSonnetModel,
defaultOpusModel,
@@ -177,6 +174,7 @@ export function ClaudeFormFields({
const { t } = useTranslation();
const hasAnyAdvancedValue = !!(
claudeModel ||
reasoningModel ||
defaultHaikuModel ||
defaultSonnetModel ||
defaultOpusModel ||
@@ -573,61 +571,23 @@ export function ClaudeFormFields({
<div className="space-y-1 pt-2 border-t">
<div className="flex items-center justify-between">
<FormLabel>{t("providerForm.modelMappingLabel")}</FormLabel>
<div className="flex gap-2">
{/* 一键设置按钮 */}
{!isCopilotPreset && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
const value =
claudeModel ||
defaultHaikuModel ||
defaultSonnetModel ||
defaultOpusModel;
if (value) {
onModelChange("ANTHROPIC_MODEL", value);
onModelChange("ANTHROPIC_DEFAULT_HAIKU_MODEL", value);
onModelChange("ANTHROPIC_DEFAULT_SONNET_MODEL", value);
onModelChange("ANTHROPIC_DEFAULT_OPUS_MODEL", value);
toast.success(
t("providerForm.quickSetSuccess", {
defaultValue: "已将模型名称应用到所有字段",
}),
);
}
}}
disabled={
!claudeModel &&
!defaultHaikuModel &&
!defaultSonnetModel &&
!defaultOpusModel
}
onClick={handleFetchModels}
disabled={isFetchingModels}
className="h-7 gap-1"
>
<Wand2 className="h-3.5 w-3.5" />
{t("providerForm.quickSetModels", {
defaultValue: "一键设置",
})}
{isFetchingModels ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Download className="h-3.5 w-3.5" />
)}
{t("providerForm.fetchModels")}
</Button>
{!isCopilotPreset && (
<Button
type="button"
variant="outline"
size="sm"
onClick={handleFetchModels}
disabled={isFetchingModels}
className="h-7 gap-1"
>
{isFetchingModels ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Download className="h-3.5 w-3.5" />
)}
{t("providerForm.fetchModels")}
</Button>
)}
</div>
)}
</div>
<p className="text-xs text-muted-foreground">
{t("providerForm.modelMappingHint")}
@@ -649,6 +609,18 @@ export function ClaudeFormFields({
)}
</div>
{/* 推理模型 */}
<div className="space-y-2">
<FormLabel htmlFor="reasoningModel">
{t("providerForm.anthropicReasoningModel")}
</FormLabel>
{renderModelInput(
"reasoningModel",
reasoningModel,
"ANTHROPIC_REASONING_MODEL",
)}
</div>
{/* 默认 Haiku */}
<div className="space-y-2">
<FormLabel htmlFor="claudeDefaultHaikuModel">
@@ -81,7 +81,7 @@ export function CommonConfigEditor({
enableToolSearch:
config?.env?.ENABLE_TOOL_SEARCH === "true" ||
config?.env?.ENABLE_TOOL_SEARCH === "1",
effortMax: config?.effortLevel === "max",
effortHigh: config?.effortLevel === "high",
disableAutoUpgrade:
config?.env?.DISABLE_AUTOUPDATER === "1" ||
config?.env?.DISABLE_AUTOUPDATER === 1,
@@ -91,7 +91,7 @@ export function CommonConfigEditor({
hideAttribution: false,
teammates: false,
enableToolSearch: false,
effortMax: false,
effortHigh: false,
disableAutoUpgrade: false,
};
}
@@ -128,9 +128,9 @@ export function CommonConfigEditor({
if (Object.keys(config.env).length === 0) delete config.env;
}
break;
case "effortMax":
case "effortHigh":
if (checked) {
config.effortLevel = "max";
config.effortLevel = "high";
} else {
delete config.effortLevel;
}
@@ -227,11 +227,11 @@ export function CommonConfigEditor({
<label className="inline-flex items-center gap-2 text-sm text-muted-foreground cursor-pointer">
<input
type="checkbox"
checked={toggleStates.effortMax}
onChange={(e) => handleToggle("effortMax", e.target.checked)}
checked={toggleStates.effortHigh}
onChange={(e) => handleToggle("effortHigh", e.target.checked)}
className="w-4 h-4 text-blue-500 bg-white dark:bg-gray-800 border-border-default rounded focus:ring-blue-500 dark:focus:ring-blue-400 focus:ring-2"
/>
<span>{t("claudeConfig.effortMax")}</span>
<span>{t("claudeConfig.effortHigh")}</span>
</label>
<label className="inline-flex items-center gap-2 text-sm text-muted-foreground cursor-pointer">
<input
@@ -3,7 +3,6 @@ import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
@@ -46,19 +45,6 @@ export const CopilotAuthSection: React.FC<CopilotAuthSectionProps> = ({
}) => {
const { t } = useTranslation();
const [copied, setCopied] = React.useState(false);
const [deploymentType, setDeploymentType] = React.useState<
"github.com" | "enterprise"
>("github.com");
const [enterpriseDomain, setEnterpriseDomain] = React.useState("");
// 根据部署类型计算实际的 GitHub 域名
const effectiveGithubDomain =
deploymentType === "enterprise" && enterpriseDomain.trim()
? enterpriseDomain
.trim()
.replace(/^https?:\/\//, "")
.replace(/\/$/, "")
: undefined;
const {
accounts,
@@ -77,7 +63,7 @@ export const CopilotAuthSection: React.FC<CopilotAuthSectionProps> = ({
setDefaultAccount,
cancelAuth,
logout,
} = useCopilotAuth(effectiveGithubDomain);
} = useCopilotAuth();
// 复制用户码
const copyUserCode = async () => {
@@ -127,41 +113,6 @@ export const CopilotAuthSection: React.FC<CopilotAuthSectionProps> = ({
</Badge>
</div>
{/* GitHub 部署类型选择 */}
<div className="space-y-2">
<Label className="text-sm text-muted-foreground">
{t("copilot.deploymentType", "GitHub 部署类型")}
</Label>
<Select
value={deploymentType}
onValueChange={(v) =>
setDeploymentType(v as "github.com" | "enterprise")
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="github.com">
{t("copilot.deploymentGitHubCom", "GitHub.com")}
</SelectItem>
<SelectItem value="enterprise">
{t("copilot.deploymentEnterprise", "GitHub Enterprise Server")}
</SelectItem>
</SelectContent>
</Select>
{deploymentType === "enterprise" && (
<Input
placeholder={t(
"copilot.enterpriseDomainPlaceholder",
"例如:company.ghe.com",
)}
value={enterpriseDomain}
onChange={(e) => setEnterpriseDomain(e.target.value)}
/>
)}
</div>
{migrationError && (
<p className="text-sm text-amber-600 dark:text-amber-400">
{t("copilot.migrationFailed", {
@@ -228,12 +179,6 @@ export const CopilotAuthSection: React.FC<CopilotAuthSectionProps> = ({
{t("copilot.defaultAccount", "默认")}
</Badge>
)}
{account.github_domain &&
account.github_domain !== "github.com" && (
<Badge variant="outline" className="text-xs">
{account.github_domain}
</Badge>
)}
{selectedAccountId === account.id && (
<Badge variant="outline" className="text-xs">
{t("copilot.selected", "已选中")}
@@ -278,7 +223,6 @@ export const CopilotAuthSection: React.FC<CopilotAuthSectionProps> = ({
onClick={addAccount}
className="w-full"
variant="outline"
disabled={deploymentType === "enterprise" && !enterpriseDomain.trim()}
>
<Github className="mr-2 h-4 w-4" />
{t("copilot.loginWithGitHub", "使用 GitHub 登录")}
@@ -292,10 +236,7 @@ export const CopilotAuthSection: React.FC<CopilotAuthSectionProps> = ({
onClick={addAccount}
className="w-full"
variant="outline"
disabled={
isAddingAccount ||
(deploymentType === "enterprise" && !enterpriseDomain.trim())
}
disabled={isAddingAccount}
>
<Plus className="mr-2 h-4 w-4" />
{t("copilot.addAnotherAccount", "添加其他账号")}
@@ -15,7 +15,6 @@ const ENDPOINT_TIMEOUT_SECS: Record<AppId, number> = {
gemini: 8,
opencode: 8,
openclaw: 8,
hermes: 8,
};
interface TestResult {
@@ -1,566 +0,0 @@
import { useTranslation } from "react-i18next";
import {
useState,
useRef,
useCallback,
useMemo,
useEffect,
type ReactNode,
} from "react";
import { FormLabel } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { toast } from "sonner";
import {
Download,
Plus,
Trash2,
ChevronDown,
ChevronRight,
Loader2,
} from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ApiKeySection } from "./shared";
import {
fetchModelsForConfig,
showFetchModelsError,
type FetchedModel,
} from "@/lib/api/model-fetch";
import {
hermesApiModes,
type HermesApiMode,
type HermesModel,
} from "@/config/hermesProviderPresets";
import type { ProviderCategory } from "@/types";
interface HermesFormFieldsProps {
baseUrl: string;
onBaseUrlChange: (value: string) => void;
apiKey: string;
onApiKeyChange: (value: string) => void;
category?: ProviderCategory;
shouldShowApiKeyLink: boolean;
websiteUrl: string;
isPartner?: boolean;
partnerPromotionKey?: string;
apiMode: HermesApiMode;
onApiModeChange: (mode: HermesApiMode) => void;
models: HermesModel[];
onModelsChange: (models: HermesModel[]) => void;
rateLimitDelay: number | undefined;
onRateLimitDelayChange: (delay: number | undefined) => void;
}
type BaseUrlErrorCode = "empty" | "invalid" | "scheme";
const BASE_URL_ERROR_I18N_KEY: Record<BaseUrlErrorCode, string> = {
empty: "hermes.form.baseUrlRequired",
scheme: "hermes.form.baseUrlScheme",
invalid: "hermes.form.baseUrlInvalid",
};
const TEMPLATE_TOKEN_RE = /\$\{[^}]+\}/g;
/**
* Hermes 0.10.0+ rejects `base_url` entries that don't parse as proper URLs
* (commit 2cdae233). Validate client-side so the error surfaces before the
* request ever reaches Hermes' startup.
*/
function validateBaseUrl(raw: string): BaseUrlErrorCode | null {
const trimmed = raw.trim();
if (!trimmed) return "empty";
// Presets like KAT-Coder embed `${VAR}` tokens — swap them before URL parse.
const candidate = trimmed.replace(TEMPLATE_TOKEN_RE, "placeholder");
let u: URL;
try {
u = new URL(candidate);
} catch {
return "invalid";
}
if (!u.protocol.startsWith("http")) return "scheme";
if (!u.hostname) return "invalid";
return null;
}
interface AdvancedSectionProps {
open: boolean;
onOpenChange: (next: boolean) => void;
labelKey: string;
children: ReactNode;
}
function AdvancedSection({
open,
onOpenChange,
labelKey,
children,
}: AdvancedSectionProps) {
const { t } = useTranslation();
return (
<Collapsible open={open} onOpenChange={onOpenChange}>
<CollapsibleTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 gap-1 text-xs text-muted-foreground hover:text-foreground"
>
{open ? (
<ChevronDown className="h-3.5 w-3.5" />
) : (
<ChevronRight className="h-3.5 w-3.5" />
)}
{t(labelKey)}
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="space-y-3 pt-2">
{children}
</CollapsibleContent>
</Collapsible>
);
}
export function HermesFormFields({
baseUrl,
onBaseUrlChange,
apiKey,
onApiKeyChange,
category,
shouldShowApiKeyLink,
websiteUrl,
isPartner,
partnerPromotionKey,
apiMode,
onApiModeChange,
models,
onModelsChange,
rateLimitDelay,
onRateLimitDelayChange,
}: HermesFormFieldsProps) {
const { t } = useTranslation();
const [expandedModels, setExpandedModels] = useState<Record<number, boolean>>(
{},
);
const [fetchedModels, setFetchedModels] = useState<FetchedModel[]>([]);
const [isFetchingModels, setIsFetchingModels] = useState(false);
const [baseUrlTouched, setBaseUrlTouched] = useState(false);
const [providerAdvancedOpen, setProviderAdvancedOpen] = useState(
rateLimitDelay !== undefined,
);
// Auto-expand when a preset switch brings in a value so the user sees it;
// don't force-collapse on clear, to avoid yanking the panel shut mid-edit.
useEffect(() => {
if (rateLimitDelay !== undefined) {
setProviderAdvancedOpen(true);
}
}, [rateLimitDelay]);
const baseUrlErrorCode = useMemo(() => validateBaseUrl(baseUrl), [baseUrl]);
const showBaseUrlError = baseUrlTouched && baseUrlErrorCode !== null;
const baseUrlErrorMessage = baseUrlErrorCode
? t(BASE_URL_ERROR_I18N_KEY[baseUrlErrorCode])
: "";
// Stable list keys: a manual ref rather than UUID-in-state so adding/removing
// rows doesn't re-mount unrelated inputs (would drop focus mid-typing).
const modelKeysRef = useRef<string[]>([]);
while (modelKeysRef.current.length < models.length) {
modelKeysRef.current.push(crypto.randomUUID());
}
if (modelKeysRef.current.length > models.length) {
modelKeysRef.current.length = models.length;
}
const modelKeys = modelKeysRef.current;
// Group fetched models by vendor once — Radix DropdownMenuContent doesn't
// lazy-mount, so computing this in JSX would re-run per model row per render.
const groupedFetchedModels = useMemo(
() =>
Object.entries(
fetchedModels.reduce(
(acc, m) => {
const v = m.ownedBy || "Other";
if (!acc[v]) acc[v] = [];
acc[v].push(m);
return acc;
},
{} as Record<string, FetchedModel[]>,
),
).sort(([a], [b]) => a.localeCompare(b)),
[fetchedModels],
);
const toggleModelAdvanced = (index: number) => {
setExpandedModels((prev) => ({ ...prev, [index]: !prev[index] }));
};
const handleAddModel = () => {
modelKeysRef.current.push(crypto.randomUUID());
onModelsChange([
...models,
{ id: "", name: "", context_length: undefined },
]);
};
const handleFetchModels = useCallback(() => {
if (!baseUrl || !apiKey) {
showFetchModelsError(null, t, {
hasApiKey: !!apiKey,
hasBaseUrl: !!baseUrl,
});
return;
}
setIsFetchingModels(true);
fetchModelsForConfig(baseUrl, apiKey)
.then((fetched) => {
setFetchedModels(fetched);
if (fetched.length === 0) {
toast.info(t("providerForm.fetchModelsEmpty"));
} else {
toast.success(
t("providerForm.fetchModelsSuccess", { count: fetched.length }),
);
}
})
.catch((err) => {
console.warn("[ModelFetch] Failed:", err);
showFetchModelsError(err, t);
})
.finally(() => setIsFetchingModels(false));
}, [baseUrl, apiKey, t]);
const handleRemoveModel = (index: number) => {
modelKeysRef.current.splice(index, 1);
const next = [...models];
next.splice(index, 1);
onModelsChange(next);
setExpandedModels((prev) => {
const updated = { ...prev };
delete updated[index];
return updated;
});
};
const handleModelChange = (
index: number,
field: keyof HermesModel,
value: unknown,
) => {
const next = [...models];
next[index] = { ...next[index], [field]: value };
onModelsChange(next);
};
return (
<>
<div className="space-y-2">
<FormLabel htmlFor="hermes-api-mode">
{t("hermes.form.apiMode", { defaultValue: "API 模式" })}
</FormLabel>
<Select
value={apiMode}
onValueChange={(v) => onApiModeChange(v as HermesApiMode)}
>
<SelectTrigger id="hermes-api-mode">
<SelectValue />
</SelectTrigger>
<SelectContent>
{hermesApiModes.map((mode) => (
<SelectItem key={mode.value} value={mode.value}>
{t(mode.labelKey)}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
{t("hermes.form.apiModeHint", {
defaultValue: "供应商 API 协议。请根据端点选择正确的协议。",
})}
</p>
</div>
<div className="space-y-2">
<FormLabel htmlFor="hermes-baseurl">
{t("hermes.form.baseUrl", { defaultValue: "API 端点" })}
</FormLabel>
<Input
id="hermes-baseurl"
value={baseUrl}
onChange={(e) => onBaseUrlChange(e.target.value)}
onBlur={() => setBaseUrlTouched(true)}
placeholder="https://api.example.com/v1"
aria-invalid={showBaseUrlError}
className={
showBaseUrlError
? "border-destructive focus-visible:ring-destructive"
: undefined
}
/>
{showBaseUrlError ? (
<p className="text-xs text-destructive">{baseUrlErrorMessage}</p>
) : (
<p className="text-xs text-muted-foreground">
{t("hermes.form.baseUrlHint", {
defaultValue: "供应商的 API 端点地址。",
})}
</p>
)}
</div>
<ApiKeySection
value={apiKey}
onChange={onApiKeyChange}
category={category}
shouldShowLink={shouldShowApiKeyLink}
websiteUrl={websiteUrl}
isPartner={isPartner}
partnerPromotionKey={partnerPromotionKey}
/>
<div className="space-y-3">
<div className="flex items-center justify-between">
<FormLabel>
{t("hermes.form.models", { defaultValue: "模型列表" })}
</FormLabel>
<div className="flex gap-1">
<Button
type="button"
variant="outline"
size="sm"
onClick={handleFetchModels}
disabled={isFetchingModels}
className="h-7 gap-1"
>
{isFetchingModels ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Download className="h-3.5 w-3.5" />
)}
{t("providerForm.fetchModels")}
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleAddModel}
className="h-7 gap-1"
>
<Plus className="h-3.5 w-3.5" />
{t("hermes.form.addModel", { defaultValue: "添加模型" })}
</Button>
</div>
</div>
{models.length === 0 ? (
<p className="text-sm text-muted-foreground py-2">
{t("hermes.form.noModels", {
defaultValue: "暂无模型配置。切换到此供应商时将无默认模型。",
})}
</p>
) : (
<div className="space-y-4">
{models.map((model, index) => (
<div
key={modelKeys[index]}
className="p-3 border border-border/50 rounded-lg space-y-3"
>
{/* Role badge — first entry is the default written to model.default on switch */}
<div className="flex items-center">
<span
className={`text-[10px] font-medium px-1.5 py-0.5 rounded ${
index === 0
? "bg-blue-500/15 text-blue-600 dark:text-blue-400"
: "bg-muted text-muted-foreground"
}`}
>
{index === 0
? t("hermes.form.primaryModel", {
defaultValue: "默认模型",
})
: t("hermes.form.fallbackModel", {
defaultValue: "备选模型",
})}
</span>
</div>
<div className="flex items-center gap-2">
<div className="flex-1 space-y-1">
<label className="text-xs text-muted-foreground">
{t("hermes.form.modelId", { defaultValue: "模型 ID" })}
</label>
<div className="flex gap-1">
<Input
value={model.id}
onChange={(e) =>
handleModelChange(index, "id", e.target.value)
}
placeholder={t("hermes.form.modelIdPlaceholder", {
defaultValue: "anthropic/claude-opus-4-7",
})}
className="flex-1"
/>
{fetchedModels.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
size="icon"
className="shrink-0"
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
className="max-h-64 overflow-y-auto z-[200]"
>
{groupedFetchedModels.map(
([vendor, vModels], vi) => (
<div key={vendor}>
{vi > 0 && <DropdownMenuSeparator />}
<DropdownMenuLabel>
{vendor}
</DropdownMenuLabel>
{vModels.map((m) => (
<DropdownMenuItem
key={m.id}
onSelect={() =>
handleModelChange(index, "id", m.id)
}
>
{m.id}
</DropdownMenuItem>
))}
</div>
),
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</div>
<div className="flex-1 space-y-1">
<label className="text-xs text-muted-foreground">
{t("hermes.form.modelName", {
defaultValue: "显示名称",
})}
</label>
<Input
value={model.name ?? ""}
onChange={(e) =>
handleModelChange(index, "name", e.target.value)
}
placeholder={t("hermes.form.modelNamePlaceholder", {
defaultValue: "Claude Opus 4.7",
})}
/>
</div>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => handleRemoveModel(index)}
className="h-9 w-9 mt-5 text-muted-foreground hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<AdvancedSection
open={expandedModels[index] ?? false}
onOpenChange={() => toggleModelAdvanced(index)}
labelKey="hermes.form.advancedOptions"
>
<div className="space-y-1">
<label className="text-xs text-muted-foreground">
{t("hermes.form.contextLength", {
defaultValue: "上下文长度",
})}
</label>
<Input
type="number"
value={model.context_length ?? ""}
onChange={(e) =>
handleModelChange(
index,
"context_length",
e.target.value ? parseInt(e.target.value) : undefined,
)
}
placeholder="200000"
/>
</div>
</AdvancedSection>
</div>
))}
</div>
)}
<p className="text-xs text-muted-foreground">
{t("hermes.form.modelsHint", {
defaultValue:
"切换到此供应商时,第一个模型会写入顶层 model.default。",
})}
</p>
</div>
<AdvancedSection
open={providerAdvancedOpen}
onOpenChange={setProviderAdvancedOpen}
labelKey="hermes.form.providerAdvanced"
>
<div className="space-y-1">
<label className="text-xs text-muted-foreground">
{t("hermes.form.rateLimitDelay", {
defaultValue: "请求间隔(秒)",
})}
</label>
<Input
type="number"
step="0.1"
min="0"
value={rateLimitDelay ?? ""}
onChange={(e) => {
const v = e.target.value;
if (v === "") {
onRateLimitDelayChange(undefined);
return;
}
const n = parseFloat(v);
onRateLimitDelayChange(
Number.isFinite(n) && n >= 0 ? n : undefined,
);
}}
placeholder="0.5"
/>
<p className="text-xs text-muted-foreground">
{t("hermes.form.rateLimitDelayHint", {
defaultValue:
"连续请求间的最小间隔秒数(可选)。留空表示无限制。",
})}
</p>
</div>
</AdvancedSection>
</>
);
}
+8 -223
View File
@@ -37,13 +37,8 @@ import {
type OpenClawProviderPreset,
type OpenClawSuggestedDefaults,
} from "@/config/openclawProviderPresets";
import {
hermesProviderPresets,
type HermesProviderPreset,
} from "@/config/hermesProviderPresets";
import { OpenCodeFormFields } from "./OpenCodeFormFields";
import { OpenClawFormFields } from "./OpenClawFormFields";
import { HermesFormFields } from "./HermesFormFields";
import type { UniversalProviderPreset } from "@/config/universalProviderPresets";
import {
applyTemplateValues,
@@ -85,7 +80,6 @@ import {
useOpencodeFormState,
useOmoDraftState,
useOpenclawFormState,
useHermesFormState,
useCopilotAuth,
useCodexOauth,
} from "./hooks";
@@ -99,10 +93,8 @@ import {
OPENCLAW_DEFAULT_CONFIG,
normalizePricingSource,
} from "./helpers/opencodeFormUtils";
import { HERMES_DEFAULT_CONFIG } from "./hooks/useHermesFormState";
import { resolveManagedAccountId } from "@/lib/authBinding";
import { useOpenClawLiveProviderIds } from "@/hooks/useOpenClaw";
import { useHermesLiveProviderIds } from "@/hooks/useHermes";
type PresetEntry = {
id: string;
@@ -111,8 +103,7 @@ type PresetEntry = {
| CodexProviderPreset
| GeminiProviderPreset
| OpenCodeProviderPreset
| OpenClawProviderPreset
| HermesProviderPreset;
| OpenClawProviderPreset;
};
interface ProviderFormProps {
@@ -262,9 +253,7 @@ export function ProviderForm({
? OPENCODE_DEFAULT_CONFIG
: appId === "openclaw"
? OPENCLAW_DEFAULT_CONFIG
: appId === "hermes"
? HERMES_DEFAULT_CONFIG
: CLAUDE_DEFAULT_CONFIG,
: CLAUDE_DEFAULT_CONFIG,
icon: initialData?.icon ?? "",
iconColor: initialData?.iconColor ?? "",
}),
@@ -325,6 +314,7 @@ export function ProviderForm({
const {
claudeModel,
reasoningModel,
defaultHaikuModel,
defaultSonnetModel,
defaultOpusModel,
@@ -460,11 +450,6 @@ export function ProviderForm({
id: `openclaw-${index}`,
preset,
}));
} else if (appId === "hermes") {
return hermesProviderPresets.map<PresetEntry>((preset, index) => ({
id: `hermes-${index}`,
preset,
}));
}
return providerPresets
.filter((p) => !p.hidden)
@@ -660,18 +645,6 @@ export function ProviderForm({
isLoading: isOpenclawLiveProviderIdsLoading,
} = useOpenClawLiveProviderIds(appId === "openclaw");
const hermesForm = useHermesFormState({
initialData,
appId,
providerId,
onSettingsConfigChange: (config) => form.setValue("settingsConfig", config),
getSettingsConfig: () => form.getValues("settingsConfig"),
});
const {
data: hermesLiveProviderIds = [],
isLoading: isHermesLiveProviderIdsLoading,
} = useHermesLiveProviderIds(appId === "hermes");
const additiveExistingProviderKeys = useMemo(() => {
if (appId === "opencode" && !isAnyOmoCategory) {
return Array.from(
@@ -694,22 +667,10 @@ export function ProviderForm({
);
}
if (appId === "hermes") {
return Array.from(
new Set(
[...hermesForm.existingHermesKeys, ...hermesLiveProviderIds].filter(
(key) => key !== providerId,
),
),
);
}
return [];
}, [
appId,
existingOpencodeKeys,
hermesForm.existingHermesKeys,
hermesLiveProviderIds,
isAnyOmoCategory,
openclawForm.existingOpenclawKeys,
openclawLiveProviderIds,
@@ -725,15 +686,11 @@ export function ProviderForm({
if (appId === "openclaw") {
return isOpenclawLiveProviderIdsLoading;
}
if (appId === "hermes") {
return isHermesLiveProviderIdsLoading;
}
return false;
}, [
appId,
isAnyOmoCategory,
isEditMode,
isHermesLiveProviderIdsLoading,
isOpenclawLiveProviderIdsLoading,
isOpencodeLiveProviderIdsLoading,
]);
@@ -746,13 +703,9 @@ export function ProviderForm({
if (appId === "openclaw") {
return openclawLiveProviderIds.includes(providerId);
}
if (appId === "hermes") {
return hermesLiveProviderIds.includes(providerId);
}
return false;
}, [
appId,
hermesLiveProviderIds,
isAnyOmoCategory,
isEditMode,
openclawLiveProviderIds,
@@ -844,34 +797,6 @@ export function ProviderForm({
}
}
// Hermes: validate provider key
if (appId === "hermes") {
const keyPattern = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (!hermesForm.hermesProviderKey.trim()) {
toast.error(t("hermes.form.providerKeyRequired"));
return;
}
if (!keyPattern.test(hermesForm.hermesProviderKey)) {
toast.error(t("hermes.form.providerKeyInvalid"));
return;
}
if (isProviderKeyLockStateLoading) {
toast.error(
t("providerForm.providerKeyStatusLoading", {
defaultValue: "正在加载供应商标识状态,请稍后再试",
}),
);
return;
}
if (
!isProviderKeyLocked &&
additiveExistingProviderKeys.includes(hermesForm.hermesProviderKey)
) {
toast.error(t("hermes.form.providerKeyDuplicate"));
return;
}
}
// 非官方供应商必填校验:端点和 API Key
// cloud_provider(如 Bedrock)通过模板变量处理认证,跳过通用校验
// GitHub Copilot 使用 OAuth 认证,不需要 API Key
@@ -1044,8 +969,6 @@ export function ProviderForm({
}
} else if (appId === "openclaw") {
payload.providerKey = openclawForm.openclawProviderKey;
} else if (appId === "hermes") {
payload.providerKey = hermesForm.hermesProviderKey;
}
if (isAnyOmoCategory && !payload.presetCategory) {
@@ -1259,20 +1182,6 @@ export function ProviderForm({
formWebsiteUrl: form.watch("websiteUrl") || "",
});
// 使用 API Key 链接 hook (Hermes)
const {
shouldShowApiKeyLink: shouldShowHermesApiKeyLink,
websiteUrl: hermesWebsiteUrl,
isPartner: isHermesPartner,
partnerPromotionKey: hermesPartnerPromotionKey,
} = useApiKeyLink({
appId: "hermes",
category,
selectedPresetId,
presetEntries,
formWebsiteUrl: form.watch("websiteUrl") || "",
});
// 使用端点测速候选 hook
const speedTestEndpoints = useSpeedTestEndpoints({
appId,
@@ -1304,9 +1213,6 @@ export function ProviderForm({
if (appId === "openclaw") {
openclawForm.resetOpenclawState();
}
if (appId === "hermes") {
hermesForm.resetHermesState();
}
return;
}
@@ -1411,23 +1317,6 @@ export function ProviderForm({
return;
}
// Hermes preset handling
if (appId === "hermes") {
const preset = entry.preset as HermesProviderPreset;
const config = preset.settingsConfig;
hermesForm.resetHermesState(config);
form.reset({
name: preset.nameKey ? t(preset.nameKey) : preset.name,
websiteUrl: preset.websiteUrl ?? "",
settingsConfig: JSON.stringify(config, null, 2),
icon: preset.icon ?? "",
iconColor: preset.iconColor ?? "",
});
return;
}
const preset = entry.preset as ProviderPreset;
const config = applyTemplateValues(
preset.settingsConfig,
@@ -1620,79 +1509,6 @@ export function ProviderForm({
</p>
)}
</div>
) : appId === "hermes" ? (
<div className="space-y-2">
<Label htmlFor="hermes-key">
{t("hermes.form.providerKey", {
defaultValue: "Provider Key",
})}
<span className="text-destructive ml-1">*</span>
</Label>
<Input
id="hermes-key"
value={hermesForm.hermesProviderKey}
onChange={(e) =>
hermesForm.setHermesProviderKey(
e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""),
)
}
placeholder={t("hermes.form.providerKeyPlaceholder", {
defaultValue: "my-provider",
})}
disabled={
isProviderKeyLocked || isProviderKeyLockStateLoading
}
className={
(additiveExistingProviderKeys.includes(
hermesForm.hermesProviderKey,
) &&
!isProviderKeyLocked) ||
(hermesForm.hermesProviderKey.trim() !== "" &&
!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(
hermesForm.hermesProviderKey,
))
? "border-destructive"
: ""
}
/>
{additiveExistingProviderKeys.includes(
hermesForm.hermesProviderKey,
) &&
!isProviderKeyLocked && (
<p className="text-xs text-destructive">
{t("hermes.form.providerKeyDuplicate")}
</p>
)}
{hermesForm.hermesProviderKey.trim() !== "" &&
!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(
hermesForm.hermesProviderKey,
) && (
<p className="text-xs text-destructive">
{t("hermes.form.providerKeyInvalid")}
</p>
)}
{!(
additiveExistingProviderKeys.includes(
hermesForm.hermesProviderKey,
) && !isProviderKeyLocked
) &&
(hermesForm.hermesProviderKey.trim() === "" ||
/^[a-z0-9]+(-[a-z0-9]+)*$/.test(
hermesForm.hermesProviderKey,
)) && (
<p className="text-xs text-muted-foreground">
{isProviderKeyLocked
? t("hermes.form.providerKeyLockedHint", {
defaultValue:
"This provider is in Hermes config; key is locked.",
})
: t("hermes.form.providerKeyHint", {
defaultValue:
"Lowercase letters, numbers, and hyphens only. Used as the provider name in config.yaml.",
})}
</p>
)}
</div>
) : undefined
}
/>
@@ -1751,6 +1567,7 @@ export function ProviderForm({
onAutoSelectChange={setEndpointAutoSelect}
shouldShowModelSelector={category !== "official"}
claudeModel={claudeModel}
reasoningModel={reasoningModel}
defaultHaikuModel={defaultHaikuModel}
defaultSonnetModel={defaultSonnetModel}
defaultOpusModel={defaultOpusModel}
@@ -1886,29 +1703,6 @@ export function ProviderForm({
/>
)}
{/* Hermes 专属字段 */}
{appId === "hermes" && (
<HermesFormFields
baseUrl={hermesForm.hermesBaseUrl}
onBaseUrlChange={hermesForm.handleHermesBaseUrlChange}
apiKey={hermesForm.hermesApiKey}
onApiKeyChange={hermesForm.handleHermesApiKeyChange}
category={category}
shouldShowApiKeyLink={shouldShowHermesApiKeyLink}
websiteUrl={hermesWebsiteUrl}
isPartner={isHermesPartner}
partnerPromotionKey={hermesPartnerPromotionKey}
apiMode={hermesForm.hermesApiMode}
onApiModeChange={hermesForm.handleHermesApiModeChange}
models={hermesForm.hermesModels}
onModelsChange={hermesForm.handleHermesModelsChange}
rateLimitDelay={hermesForm.hermesRateLimitDelay}
onRateLimitDelayChange={
hermesForm.handleHermesRateLimitDelayChange
}
/>
)}
{/* 配置编辑器:Codex、Claude、Gemini 分别使用不同的编辑器 */}
{appId === "codex" ? (
<>
@@ -1992,7 +1786,7 @@ export function ProviderForm({
</div>
{settingsConfigErrorField}
</>
) : appId === "openclaw" || appId === "hermes" ? (
) : appId === "openclaw" ? (
<>
<div className="space-y-2">
<Label htmlFor="settingsConfig">
@@ -2001,20 +1795,12 @@ export function ProviderForm({
<JsonEditor
value={form.getValues("settingsConfig")}
onChange={(config) => form.setValue("settingsConfig", config)}
placeholder={
appId === "hermes"
? `{
"name": "my-provider",
"base_url": "https://api.example.com/v1",
"api_key": ""
}`
: `{
placeholder={`{
"baseUrl": "https://api.example.com/v1",
"apiKey": "your-api-key-here",
"api": "openai-completions",
"models": []
}`
}
}`}
rows={14}
showValidation={true}
language="json"
@@ -2052,8 +1838,7 @@ export function ProviderForm({
{!isAnyOmoCategory &&
appId !== "opencode" &&
appId !== "openclaw" &&
appId !== "hermes" && (
appId !== "openclaw" && (
<ProviderAdvancedConfig
testConfig={testConfig}
pricingConfig={pricingConfig}
@@ -17,6 +17,5 @@ export { useOmoModelSource } from "./useOmoModelSource";
export { useOpencodeFormState } from "./useOpencodeFormState";
export { useOmoDraftState } from "./useOmoDraftState";
export { useOpenclawFormState } from "./useOpenclawFormState";
export { useHermesFormState } from "./useHermesFormState";
export { useCopilotAuth } from "./useCopilotAuth";
export { useCodexOauth } from "./useCodexOauth";
@@ -160,14 +160,9 @@ export function useCodexCommonConfig({
config,
commonConfigSnippet,
);
const hasCommon = initialEnabled ?? inferredHasCommon;
// 优先级:显式设置的 initialEnabled > 从配置推断的值
// 如果 initialEnabled 为 undefined,使用推断值
const hasCommon =
initialEnabled !== undefined ? initialEnabled : inferredHasCommon;
// 如果应该启用通用配置但配置中还没有,则自动添加
if (hasCommon && !inferredHasCommon && parsedSnippet.hasContent) {
if (hasCommon && !inferredHasCommon) {
const { updatedConfig, error } = updateTomlCommonConfigSnippet(
codexConfig,
commonConfigSnippet,
@@ -118,23 +118,17 @@ export function useCommonConfigSnippet({
// 初始化时检查通用配置片段(编辑模式)
useEffect(() => {
if (!enabled) return;
if (initialData && !isLoading && !hasInitializedEditMode.current) {
hasInitializedEditMode.current = true;
if (initialData && !isLoading) {
const configString = JSON.stringify(initialData.settingsConfig, null, 2);
const inferredHasCommon = hasCommonConfigSnippet(
configString,
commonConfigSnippet,
);
// 优先级:显式设置的 initialEnabled > 从配置推断的值
// 如果 initialEnabled 为 undefined,使用推断值
const hasCommon =
initialEnabled !== undefined ? initialEnabled : inferredHasCommon;
const hasCommon = initialEnabled ?? inferredHasCommon;
setUseCommonConfig(hasCommon);
// 如果应该启用通用配置但配置中还没有,则自动添加
if (hasCommon && !inferredHasCommon) {
if (hasCommon && !inferredHasCommon && !hasInitializedEditMode.current) {
hasInitializedEditMode.current = true;
const { updatedConfig, error } = updateCommonConfigSnippet(
settingsConfig,
commonConfigSnippet,
@@ -147,6 +141,8 @@ export function useCommonConfigSnippet({
isUpdatingFromCommonConfig.current = false;
}, 0);
}
} else {
hasInitializedEditMode.current = true;
}
}
}, [
@@ -1,8 +1,8 @@
import type { GitHubAccount } from "@/lib/api";
import { useManagedAuth } from "./useManagedAuth";
export function useCopilotAuth(githubDomain?: string) {
const managedAuth = useManagedAuth("github_copilot", githubDomain);
export function useCopilotAuth() {
const managedAuth = useManagedAuth("github_copilot");
const defaultAccount =
managedAuth.accounts.find(
(account) => account.id === managedAuth.defaultAccountId,

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