Compare commits
57 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e50fc0eb28 | |||
| f9547da930 | |||
| 844bbcf8c4 | |||
| 16922917fb | |||
| 88f1a78e3a | |||
| 90bc37449c | |||
| de386b297f | |||
| e6d40d0a93 | |||
| dd6a951c34 | |||
| 430ddf92bd | |||
| 8a91428b71 | |||
| 6180c4ba12 | |||
| f8768c5885 | |||
| 7d74d2449a | |||
| 273cc48c57 | |||
| f1328d89fc | |||
| a4eb5f3778 | |||
| 213f55a6d2 | |||
| fdf538e52d | |||
| 2e547c98b1 | |||
| 1a0e8c7a44 | |||
| 524b9d9825 | |||
| 6fd4e6f462 | |||
| edeee25fae | |||
| 55abd1822c | |||
| 9171ad752c | |||
| 2db3163cf2 | |||
| 169d58ac6f | |||
| 2781d40e82 | |||
| 2d478876fa | |||
| 895d7af3eb | |||
| 92930461b7 | |||
| c797b2a3fb | |||
| c4630b5c26 | |||
| a3b3a06f5e | |||
| e648b7425e | |||
| c26d867f79 | |||
| 26be9324dd | |||
| 142c8c1da7 | |||
| 6ec86cff46 | |||
| 455556380b | |||
| 510aa250c5 | |||
| d1b5df9a7b | |||
| dfa03b746a | |||
| 3d30dc03e8 | |||
| 95495ad19e | |||
| b724f5dde9 | |||
| 69341db284 | |||
| 0bb3b7515a | |||
| 81d6002ace | |||
| caa912e3a3 | |||
| 1042fb2a32 | |||
| de0a149df5 | |||
| 36b557b2e6 | |||
| 3e38889ccc | |||
| 12567b3229 | |||
| c548e7fcba |
@@ -16,9 +16,12 @@ jobs:
|
||||
release:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: windows-2022
|
||||
- os: windows-11-arm
|
||||
arch: arm64
|
||||
- os: ubuntu-22.04
|
||||
- os: ubuntu-22.04-arm
|
||||
arch: arm64
|
||||
@@ -36,6 +39,11 @@ jobs:
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Add Windows ARM64 target
|
||||
if: runner.os == 'Windows' && matrix.arch == 'arm64'
|
||||
shell: pwsh
|
||||
run: rustup target add aarch64-pc-windows-msvc
|
||||
|
||||
- name: Add macOS targets
|
||||
if: runner.os == 'macOS'
|
||||
run: |
|
||||
@@ -74,23 +82,50 @@ jobs:
|
||||
|| sudo apt-get install -y --no-install-recommends libsoup2.4-dev
|
||||
|
||||
- name: Setup pnpm
|
||||
if: runner.os != 'Windows' || matrix.arch != 'arm64'
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.12.3
|
||||
run_install: false
|
||||
|
||||
- name: Setup pnpm (Windows ARM64)
|
||||
if: runner.os == 'Windows' && matrix.arch == 'arm64'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
corepack enable
|
||||
corepack prepare pnpm@10.12.3 --activate
|
||||
node --version
|
||||
pnpm --version
|
||||
|
||||
- name: Get pnpm store directory
|
||||
if: runner.os != 'Windows' || matrix.arch != 'arm64'
|
||||
id: pnpm-store
|
||||
shell: bash
|
||||
run: echo "path=$(pnpm store path --silent)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Setup pnpm cache
|
||||
if: runner.os != 'Windows' || matrix.arch != 'arm64'
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ${{ steps.pnpm-store.outputs.path }}
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: ${{ runner.os }}-${{ runner.arch }}-pnpm-store-
|
||||
|
||||
- name: Setup LLVM for Windows ARM64
|
||||
if: runner.os == 'Windows' && matrix.arch == 'arm64'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$llvmRoot = 'C:\Program Files\LLVM'
|
||||
if (-not (Test-Path $llvmRoot)) {
|
||||
throw "LLVM not found at $llvmRoot"
|
||||
}
|
||||
$llvmBin = Join-Path $llvmRoot 'bin'
|
||||
"LIBCLANG_PATH=$llvmBin" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
|
||||
"CLANG_PATH=$(Join-Path $llvmBin 'clang.exe')" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
|
||||
$llvmBin | Out-File -FilePath $env:GITHUB_PATH -Append -Encoding utf8
|
||||
|
||||
- name: Install frontend deps
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
@@ -223,7 +258,16 @@ jobs:
|
||||
|
||||
- name: Build Tauri App (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
run: pnpm tauri build
|
||||
shell: pwsh
|
||||
env:
|
||||
WINDOWS_RELEASE_ARCH: ${{ matrix.arch || 'x86_64' }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($env:WINDOWS_RELEASE_ARCH -eq 'arm64') {
|
||||
pnpm tauri build --target aarch64-pc-windows-msvc --bundles msi
|
||||
} else {
|
||||
pnpm tauri build
|
||||
}
|
||||
|
||||
- name: Build Tauri App (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
@@ -394,50 +438,75 @@ jobs:
|
||||
- name: Prepare Windows Assets
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
env:
|
||||
WINDOWS_RELEASE_ARCH: ${{ matrix.arch || 'x86_64' }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
New-Item -ItemType Directory -Force -Path release-assets | Out-Null
|
||||
$VERSION = $env:GITHUB_REF_NAME # e.g., v3.5.0
|
||||
$isArm64 = $env:WINDOWS_RELEASE_ARCH -eq 'arm64'
|
||||
$targetRoot = if ($isArm64) { 'src-tauri/target/aarch64-pc-windows-msvc/release' } else { 'src-tauri/target/release' }
|
||||
$assetSuffix = if ($isArm64) { '-arm64' } else { '' }
|
||||
|
||||
# 仅打包 MSI 安装器 + .sig(用于 Updater)
|
||||
$msi = Get-ChildItem -Path 'src-tauri/target/release/bundle/msi' -Recurse -Include *.msi -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
$msi = Get-ChildItem -Path (Join-Path $targetRoot 'bundle/msi') -Recurse -Include *.msi -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($null -eq $msi) {
|
||||
# 兜底:全局搜索 .msi
|
||||
$msi = Get-ChildItem -Path 'src-tauri/target/release/bundle' -Recurse -Include *.msi -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
$msi = Get-ChildItem -Path (Join-Path $targetRoot 'bundle') -Recurse -Include *.msi -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
}
|
||||
if ($null -ne $msi) {
|
||||
$dest = "CC-Switch-$VERSION-Windows.msi"
|
||||
$dest = "CC-Switch-$VERSION-Windows$assetSuffix.msi"
|
||||
Copy-Item $msi.FullName (Join-Path release-assets $dest)
|
||||
Write-Host "Installer copied: $dest"
|
||||
$sigPath = "$($msi.FullName).sig"
|
||||
if (Test-Path $sigPath) {
|
||||
Copy-Item $sigPath (Join-Path release-assets ("$dest.sig"))
|
||||
Write-Host "Signature copied: $dest.sig"
|
||||
} elseif ($isArm64) {
|
||||
throw "Signature not found for $($msi.Name)"
|
||||
} else {
|
||||
Write-Warning "Signature not found for $($msi.Name)"
|
||||
}
|
||||
} elseif ($isArm64) {
|
||||
throw 'No Windows ARM64 MSI installer found'
|
||||
} else {
|
||||
Write-Warning 'No Windows MSI installer found'
|
||||
}
|
||||
|
||||
# 绿色版(portable):仅可执行文件打 zip(不参与 Updater)
|
||||
$exeCandidates = @(
|
||||
'src-tauri/target/release/cc-switch.exe',
|
||||
'src-tauri/target/x86_64-pc-windows-msvc/release/cc-switch.exe'
|
||||
)
|
||||
$exeCandidates = if ($isArm64) {
|
||||
@('src-tauri/target/aarch64-pc-windows-msvc/release/cc-switch.exe')
|
||||
} else {
|
||||
@(
|
||||
'src-tauri/target/release/cc-switch.exe',
|
||||
'src-tauri/target/x86_64-pc-windows-msvc/release/cc-switch.exe'
|
||||
)
|
||||
}
|
||||
$exePath = $exeCandidates | Where-Object { Test-Path $_ } | Select-Object -First 1
|
||||
if ($null -ne $exePath) {
|
||||
$portableDir = 'release-assets/CC-Switch-Portable'
|
||||
New-Item -ItemType Directory -Force -Path $portableDir | Out-Null
|
||||
Copy-Item $exePath $portableDir
|
||||
$portableIniPath = Join-Path $portableDir 'portable.ini'
|
||||
$portableContent = @(
|
||||
'# CC Switch portable build marker',
|
||||
'portable=true'
|
||||
)
|
||||
$portableContent = if ($isArm64) {
|
||||
@(
|
||||
'# CC Switch portable ARM64 build marker',
|
||||
'portable=true',
|
||||
'arch=arm64'
|
||||
)
|
||||
} else {
|
||||
@(
|
||||
'# CC Switch portable build marker',
|
||||
'portable=true'
|
||||
)
|
||||
}
|
||||
$portableContent | Set-Content -Path $portableIniPath -Encoding UTF8
|
||||
$portableZip = "release-assets/CC-Switch-$VERSION-Windows-Portable.zip"
|
||||
$portableZip = "release-assets/CC-Switch-$VERSION-Windows$assetSuffix-Portable.zip"
|
||||
Compress-Archive -Path "$portableDir/*" -DestinationPath $portableZip -Force
|
||||
Remove-Item -Recurse -Force $portableDir
|
||||
Write-Host "Windows portable zip created: CC-Switch-$VERSION-Windows-Portable.zip"
|
||||
Write-Host "Windows portable zip created: CC-Switch-$VERSION-Windows$assetSuffix-Portable.zip"
|
||||
} elseif ($isArm64) {
|
||||
throw 'Portable ARM64 exe not found'
|
||||
} else {
|
||||
Write-Warning 'Portable exe not found'
|
||||
}
|
||||
@@ -550,7 +619,8 @@ jobs:
|
||||
### 下载
|
||||
|
||||
- **macOS**: `CC-Switch-${{ github.ref_name }}-macOS.dmg`(推荐)或 `CC-Switch-${{ github.ref_name }}-macOS.zip`(解压即用)
|
||||
- **Windows**: `CC-Switch-${{ github.ref_name }}-Windows.msi`(安装版)或 `CC-Switch-${{ github.ref_name }}-Windows-Portable.zip`(绿色版)
|
||||
- **Windows (x86_64)**: `CC-Switch-${{ github.ref_name }}-Windows.msi`(安装版)或 `CC-Switch-${{ github.ref_name }}-Windows-Portable.zip`(绿色版)
|
||||
- **Windows (ARM64)**: `CC-Switch-${{ github.ref_name }}-Windows-arm64.msi`(安装版)或 `CC-Switch-${{ github.ref_name }}-Windows-arm64-Portable.zip`(绿色版)
|
||||
- **Linux (x86_64)**: `CC-Switch-${{ github.ref_name }}-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- **Linux (ARM64)**: `CC-Switch-${{ github.ref_name }}-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
@@ -594,7 +664,8 @@ jobs:
|
||||
base_url="https://github.com/$REPO/releases/download/$TAG"
|
||||
# 初始化空平台映射
|
||||
mac_url=""; mac_sig=""
|
||||
win_url=""; win_sig=""
|
||||
win_x64_url=""; win_x64_sig=""
|
||||
win_arm64_url=""; win_arm64_sig=""
|
||||
linux_x64_url=""; linux_x64_sig=""
|
||||
linux_arm64_url=""; linux_arm64_sig=""
|
||||
shopt -s nullglob
|
||||
@@ -607,12 +678,14 @@ jobs:
|
||||
*.tar.gz)
|
||||
# 视为 macOS updater artifact
|
||||
mac_url="$url"; mac_sig="$sig_content";;
|
||||
*-Windows-arm64.msi)
|
||||
win_arm64_url="$url"; win_arm64_sig="$sig_content";;
|
||||
*-Windows.msi)
|
||||
win_x64_url="$url"; win_x64_sig="$sig_content";;
|
||||
*-Linux-arm64.AppImage|*-Linux-arm64.appimage)
|
||||
linux_arm64_url="$url"; linux_arm64_sig="$sig_content";;
|
||||
*-Linux-x86_64.AppImage|*-Linux-x86_64.appimage)
|
||||
linux_x64_url="$url"; linux_x64_sig="$sig_content";;
|
||||
*.msi|*.exe)
|
||||
win_url="$url"; win_sig="$sig_content";;
|
||||
esac
|
||||
done
|
||||
# 构造 JSON(仅包含存在的目标)
|
||||
@@ -632,9 +705,14 @@ jobs:
|
||||
first=0
|
||||
done
|
||||
fi
|
||||
if [ -n "$win_url" ] && [ -n "$win_sig" ]; then
|
||||
if [ -n "$win_x64_url" ] && [ -n "$win_x64_sig" ]; then
|
||||
[ $first -eq 0 ] && echo ','
|
||||
echo " \"windows-x86_64\": {\"signature\": \"$win_sig\", \"url\": \"$win_url\"}"
|
||||
echo " \"windows-x86_64\": {\"signature\": \"$win_x64_sig\", \"url\": \"$win_x64_url\"}"
|
||||
first=0
|
||||
fi
|
||||
if [ -n "$win_arm64_url" ] && [ -n "$win_arm64_sig" ]; then
|
||||
[ $first -eq 0 ] && echo ','
|
||||
echo " \"windows-aarch64\": {\"signature\": \"$win_arm64_sig\", \"url\": \"$win_arm64_url\"}"
|
||||
first=0
|
||||
fi
|
||||
if [ -n "$linux_x64_url" ] && [ -n "$linux_x64_sig" ]; then
|
||||
|
||||
@@ -5,6 +5,65 @@ All notable changes to CC Switch will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [3.16.4] - 2026-06-27
|
||||
|
||||
Development since v3.16.3 focuses on tightening the Codex proxy path — native OpenAI Responses migration for the major Chinese providers, a decoupled upstream-format selector, zstd request/error-body decompression, and a run of tool-call and OAuth-over-proxy fixes — alongside richer usage and pricing tooling (models.dev pricing import, Volcengine Ark coding/agent-plan quotas, live-tracking date ranges, GLM-5.2/Doubao Seed 2.1 pricing), new proxy and resilience capabilities (custom request header/body overrides, an in-app recovery screen for too-new databases, native Windows ARM64 builds), and a broad wave of preset and branding updates (the SubRouter and OpenCode Go subscriptions, the CTok→ETok rename, Kimi rebranding and prime-partner badges, and a Kimi K2.7 Code sponsor banner).
|
||||
|
||||
**Stats**: 53 commits | 126 files changed | +8,149 insertions | -1,016 deletions
|
||||
|
||||
### Added
|
||||
|
||||
- **In-App Recovery Screen for a Too-New Database**: When the SQLite `user_version` is newer than the app supports (`SCHEMA_VERSION`) — e.g. after a downgrade or because a third-party client wrote the file — startup used to dead-end in a native Retry/Exit dialog where Retry just failed again. The app now boots a dedicated recovery screen offering an in-place "Upgrade app" button (download + install + restart with a progress bar) when an update is available, or a warning that even the latest build can't read the database when none is. The too-new check runs before any schema writes so the app never runs DDL against a database it can't understand, and native-close quits cleanly in recovery mode where no tray exists. (#4575)
|
||||
- **Local Proxy Request Overrides (Custom Headers and Body)**: Provider configs can now define custom request headers and request-body overrides that the local proxy applies when forwarding, exposed via a new field in the Claude and Codex provider forms. Inputs are validated, including a protected-header-name list that blocks overriding security-sensitive headers. (#4589)
|
||||
- **Volcengine Ark Coding/Agent Plan Usage Query**: Usage panels can now query coding-plan and agent-plan quota for Volcengine Ark. Because the Ark control-plane OpenAPI (`open.volcengineapi.com`) requires account-level AccessKey signing rather than the inference API key, the usage script gains a dedicated AK/SK input block, with a clickable link straight to the Volcengine IAM key-management console (`https://console.volcengine.com/iam/keymanage`), and the proxy implements Volcengine Signature V4 (an AWS SigV4 variant with fixed canonical header order, `HMAC-SHA256` algorithm, and `ark` service scope). It auto-detects the plan by probing `GetAFPUsage` (Agent Plan five-hour/weekly/monthly quotas) before falling back to `GetCodingPlanUsage`, parses the window label from the `Level` field (guarding `ResetTimestamp <= 0`), and adds a `monthly` tier label across the footer, tray menu, and all four locales.
|
||||
- **Import Model Pricing from models.dev**: The Add Pricing panel gains an "Import from models.dev" button that fetches `https://models.dev/api.json`, lets users full-text search the catalog, and imports the selected entry through the same `update_model_pricing` path as manual entry. Imported model IDs are normalized to match the backend's `clean_model_id_for_pricing` rules (strip vendor prefix, lowercase, drop `:` suffix, map `@` to `-`, drop the `[1m]` marker) so stored rows actually match cost-attribution lookups. A companion fix makes the scoped zero-cost backfill match raw model aliases (route prefixes, `:free` variants, date suffixes) in Rust instead of by exact SQL string, so newly priced alias rows get costed immediately rather than waiting for the next startup backfill (Fixes #4017). (#4079)
|
||||
- **Windows ARM64 Release Builds**: Releases now include native Windows ARM64 artifacts so ARM-based Windows devices get a matching build instead of relying on x64 emulation. The release matrix also runs each platform independently (fail-fast disabled) so a missing-secret failure on one job — e.g. macOS signing in forks — no longer cancels its siblings before they finish. (#3950)
|
||||
- **Live End Time for Custom Date Ranges**: The custom date-range picker gains an "End time follows current time" checkbox; when enabled the end time becomes read-only and tracks the current moment, so usage data always reflects up-to-the-second consumption from the chosen start. This is especially useful for watching real-time token use within a Coding Plan 5-hour quota window. `liveEndTime` is included in the React Query cache keys so a live range and a fixed range with the same stored endpoints no longer collide on a stale cache entry. (#4438)
|
||||
- **Source File Name in Session Detail Header**: The session detail header now shows the session log's file name (with the full path on hover and click-to-copy) alongside the project directory, so users can locate and open the underlying JSONL file directly from the UI. Long, space-less basenames such as ~70-char Codex rollout files are truncated at `max-w-[200px]` to keep them from overflowing into the action-button area on narrow windows. (#4113)
|
||||
- **Unmanaged-Skill Indicator on Import Button**: The top-bar Skills Import button now shows a green dot with a tooltip when local unmanaged skills are available to import, so you can tell at a glance that on-disk skills aren't tracked yet. The scan runs once on mount and is shared across navigations (30s `staleTime` + `keepPreviousData`) to avoid repeated disk IO.
|
||||
- **OpenCode Go Subscription Presets**: New OpenCode Go (`opencode.ai/zen/go`) presets for Claude, Codex, and OpenCode, authenticated with a plain pasteable API key (no OAuth). The Codex preset uses `openai_chat` conversion with a GLM/Kimi/DeepSeek/MiMo model catalog (and no static `codexChatReasoning`, so per-model capability is inferred), while OpenCode targets `/zen/go/v1` via `@ai-sdk/openai-compatible`. All four OpenCode Go presets — Claude, Claude Desktop, Codex, and OpenCode — carry a referral link and an in-app promo phrase; the promo banner is now gated on `partnerPromotionKey` alone rather than `isPartner`, so a preset can show a referral promo without earning the gold paid-partner star (this also re-surfaces the existing MiniMax promos).
|
||||
- **SubRouter Partner Provider**: Added SubRouter (`subrouter.ai`), an AI relay aggregator that exposes many models and providers behind a single key, as a preset across all seven managed apps — the Anthropic-format endpoint for Claude Code / Claude Desktop / OpenClaw / Hermes, the OpenAI-compatible `/v1` endpoint with `gpt-5.5` for Codex and OpenCode, and the Gemini-compatible `/v1beta` endpoint with `gemini-3.5-flash` for Gemini CLI — carrying its own brand icon, the gold partner star, four-locale promotion copy, and the affiliate registration link (`?aff=l3ri`) prefilled as the API-key signup URL. (#4522)
|
||||
- **Prime-Partner Preset Badge and Ordering**: First-party Moonshot Kimi presets (Kimi / Kimi For Coding / Kimi K2.7 Code) are now flagged as prime partners: instead of the gold star, they render a solid gold heart with no badge frame, and in the default (Original) sort they float to the top right after official-category presets, ahead of the rest. Grouping is a three-way partition so each group keeps its internal order and an official preset also flagged prime-partner stays only in the official group.
|
||||
- **Pricing for GLM-5.2 and Doubao Seed 2.1**: Seed model pricing now includes GLM-5.2 (#4385) and Doubao Seed 2.1 Pro/Turbo, so usage from these models is cost-attributed correctly instead of recording zero cost. Doubao prices use Volcengine's official list price (CNY converted at ~7.14); `cache_creation` is kept at 0 because Doubao bills cache storage by time rather than per-token writes, and the existing 2.0 rows are retained for historical accounting.
|
||||
- **Kimi For Coding Auto-Compact Window**: The Kimi For Coding preset now sets `CLAUDE_CODE_AUTO_COMPACT_WINDOW` to a default of 262144 to match the official Kimi docs, exposed via `templateValues` so users can customize the value for future models or performance tuning. (#4401)
|
||||
|
||||
### Changed
|
||||
|
||||
- **Native Responses API for CN Codex Providers**: Several Chinese providers (Qwen/DashScope Bailian, Xiaomi MiMo, Volcengine Doubao, Meituan LongCat, MiniMax CN/intl) now expose a native OpenAI Responses endpoint, so their Codex presets switch to `apiFormat: "openai_responses"` and reach the upstream directly instead of going through the Responses->Chat route-takeover conversion. Dropping the now-unused `codexChatReasoning` and `modelCatalog` also keeps the "local route mapping" toggle unchecked by default. SiliconFlow-hosted MiniMax stays `openai_chat` since it is a third-party endpoint rather than MiniMax's own base_url. Stale model ids on the remaining chat-only providers were refreshed as well (GLM 5.1->5.2, StepFun 3.5-flash-2603->3.7-flash, Ling 2.5-1T->2.6-1T).
|
||||
- **Decoupled Upstream Format Selector from Model-Mapping Toggle**: The Codex provider form used to tie Chat-format conversion and route takeover (model mapping) to a single toggle, so a provider serving a native Responses API could not use model mapping without forcing Chat Completions conversion. The upstream format (Chat Completions / Responses) is now an independent, always-visible selector, while the local-routing toggle solely gates the advanced sub-sections (model mapping catalog, plus reasoning capability when the format is Chat). Its initial state is derived from saved catalog presence with no new persisted field, and the `codexConfig` i18n strings were reworded across all four locales (zh/en/ja/zh-TW).
|
||||
- **Doubao Seed 2.1 Pro Preset**: The DouBaoSeed preset now targets `doubao-seed-2-1-pro` (replacing `doubao-seed-2-0-code-preview-latest`) across all six clients (claude, claude-desktop, codex, opencode, openclaw, hermes), with display names updated to "Doubao Seed 2.1 Pro" and the OpenClaw cost field corrected from 0.002/0.006 to 0.84/4.2 USD per 1M tokens to match the new model.
|
||||
- **CTok Rebranded to ETok**: Following the vendor's domain, endpoint, and trademark rename, all user-facing branding moves from CTok to ETok (`ctok.ai` -> `etok.ai`, `api.ctok.ai` -> `api.etok.ai`, internal id, display name, icons, and README partner banners) across every client preset. The Codex history-migration whitelist keeps `ctok` as a legacy id alongside the new `etok` so existing users' local session history stays correctly bucketed after the rename.
|
||||
- **Consistent Kimi Preset Naming**: The OpenCode and OpenClaw Kimi presets, previously labeled "Kimi K2.7 Code", are renamed to plain "Kimi" (along with the OpenCode provider display name) to match the other apps; the model label stays "Kimi K2.7 Code" since it describes the actual model.
|
||||
- **Dark Mode for JSON Editors**: The CodeMirror `JsonEditor` in the usage-script modal, provider form, and universal provider form now follows the app theme via `useDarkMode()`, switching to the `oneDark` editor theme instead of staying light while the rest of the app is dark. (#4556)
|
||||
- **Tighter Add Provider Header With Footer Hint**: The Add Provider dialog reduces the title-to-tabs and tabs-to-card vertical gaps from 24px to 12px and adds an always-visible pinned footer hint guiding users to fill in the fields below after choosing a preset. `FullScreenPanel` gains an optional `contentClassName` prop so the padding override is scoped to this panel without affecting others that share it.
|
||||
- **Theme-Adaptive Kimi Logo**: The inline Kimi placeholder mark is replaced with the vendor's refreshed logo. The K glyph uses `currentColor` so it follows the theme text color (dark in light mode, white in dark mode), while the brand accent dot is pinned to the new `#1783FF`, with the metadata fallback color aligned accordingly.
|
||||
- **Fable 5 Verified Banner Removed**: The Settings About page no longer shows the Fable 5 Verified commemorative banner that 3.16.3 added beside the app name to mark the special build; the banner image and its markup are dropped, returning the About panel to its standard version-badge layout.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Copilot/Codex OAuth Requests Now Honor the Global Proxy**: `CopilotAuthManager` and `CodexOAuthManager` hardcoded `Client::new()` at construction, so their auth flows (token exchange, `/models` listing, model-vendor checks, device-code and OAuth-refresh requests) ignored the configured global proxy and connected directly. With Copilot the direct connection returned zero Claude models, breaking live model resolution and causing the upstream to reject requests with `400 model_not_supported`. Both managers now fetch the shared client per request via `crate::proxy::http_client::get()`, so they follow the global proxy URL and pick up runtime proxy changes. Fixes #2016, #2931. (#4583)
|
||||
- **Compressed Request and Error Body Decompression**: Codex Desktop sends zstd-compressed request bodies when authenticated against the Codex backend, which broke local proxy routing because the handlers parsed the raw compressed bytes with `serde_json` directly. The proxy now decompresses request bodies (gzip/br/deflate plus new zstd support, including stacked codings like `gzip, zstd`) before JSON parsing across the three Codex handlers and strips the stale `content-encoding`/`content-length`/`transfer-encoding` headers so the forwarder regenerates them. Upstream non-2xx error bodies are decompressed the same way, so compressed rate-limit and auth details are no longer dropped and hidden from the client. Fixes #3764, #3696. (#3817)
|
||||
- **DeepSeek Endpoint `thinking: disabled` 400 Errors**: DeepSeek's Anthropic-compatible endpoint rejects requests where `thinking.type=disabled` coexists with effort parameters, returning HTTP 400, which broke Claude Code 2.1.166+ sub-agents (Workflow/Dynamic Workflow) that hardcode `thinking: disabled`. Rather than overriding the client's intent, the proxy now strips the conflicting `output_config.effort` / `reasoning_effort` parameters for the official DeepSeek endpoint, since sub-agents don't need to display reasoning. (#4239)
|
||||
- **Reverted Anthropic System-Message Hoisting**: Reverts #3775's hoisting of `role=system` messages out of `messages[]` into the top-level `system` field for Anthropic-compatible providers. DeepSeek's endpoint accepts inline system messages natively, and the rewrite altered the request prefix; leaving the messages in place preserves the prompt prefix and avoids a suspected cache hit-rate regression (refs #4297). The unrelated Windows test fixes and the tool-thinking-history normalization from #3775 are kept. (#3775)
|
||||
- **Chat Tool Calls with Missing Function Names**: Some upstreams send empty or absent function names in streaming tool-call deltas, which previously produced invalid Codex Chat output items (or an `unknown_tool` fallback). Accumulated tool-call state is no longer overwritten by empty deltas, and tool calls that never receive both a `call_id` and a valid name are skipped at finalization across the streaming, non-streaming, and legacy `function_call` paths. (#4159)
|
||||
- **Restored Cached Codex Tool Call Fields**: When Codex sends a follow-up Chat request referencing `previous_response_id`, its `function_call` items can arrive carrying only `call_id`. The history enrichment previously refilled only `reasoning`/`reasoning_content`, leaving the function `name`, `arguments`, `status`, and related fields empty; it now restores all cached tool-call fields from history so the call is reconstructed correctly for the Chat upstream. (#4160)
|
||||
- **Duplicate Codex base_url Entries in config.toml**: Writing the Codex `base_url` into `config.toml` only replaced or removed a single matching assignment per section, so a section that already contained multiple `base_url` lines kept the extras and accumulated duplicates. `setCodexBaseUrl` now collapses all matches in the target section or top level (replacing the first and removing the rest), and the TOML `base_url` regex handles escaped quotes. (#4316)
|
||||
- **CODEX_SQLITE_HOME State DB Probing for History Migration**: The Codex session-history migration only scanned `~/.codex/state_5.sqlite` and the `config.toml` `sqlite_home` location, so when Codex's SQLite state was relocated via the `CODEX_SQLITE_HOME` env var the state DB was never scanned and its threads kept their old provider bucket. The shared `codex_state_db_paths` helper used by both the third-party and unified-session migrations now falls back to `CODEX_SQLITE_HOME` (config `sqlite_home` still takes precedence).
|
||||
- **Provider Terminals Respect the User's Shell**: Launching a provider terminal on macOS/Linux hardcoded `bash`, so zsh/fish users' rc files never loaded. The launchers now detect the user's default shell from `$SHELL` (falling back to `/bin/zsh` on macOS, `/bin/bash` on Linux) and exec into it with clean-start flags, while the launch scripts themselves run through POSIX `sh` for portability (e.g. fish, NixOS where `/bin/sh` may not exist). (#4140, fixes #1546)
|
||||
- **Claude MCP Path Honors Custom Config Dir**: When a custom Claude config directory is configured, MCP server reads and writes now resolve to that directory's MCP file instead of the default location, keeping MCP state isolated per profile. The previous copy-on-access migration of the legacy file was removed in favor of resolving the override path directly. (#3431)
|
||||
- **Preset Search Results Clickable After Searching**: After searching in the Add Provider preset selector, results could no longer be clicked or selected. The `requestAnimationFrame` `select()` that raced with typing (and ate the first character, e.g. "gateway" -> "ateway") is removed, input autofocus is restored for the open-by-click path, and refocus is wired up for the Ctrl/Cmd+F shortcut while the box is open. The provider-list typing guard is also scoped to the Ctrl/Cmd+F branch so Escape still closes the search panel. (#4315)
|
||||
- **Skills Browser and Provider Card Display Fixes**: Fixed several display and interaction issues: the repo-manager action stays available while browsing skills.sh and Refresh stays available even when a repo returns no results; long provider names and website URLs on the provider card now truncate instead of overflowing; the OMO model-variant dropdown truncates its selected label with a full-text tooltip; and Select menu items show a checkmark on the active option. (#4323)
|
||||
- **Settings Scroll Resets on Tab Switch**: Switching tabs in the Settings dialog kept the previous tab's scroll position, sometimes landing partway down the new tab; the scroll container now resets to the top whenever the active tab changes. (#4165)
|
||||
|
||||
### Docs
|
||||
|
||||
- **Kimi Pinned Sponsor Banner**: The pinned sponsor banner at the top of all four README locales (en/zh/ja/de) now features Kimi K2.7 Code in place of the previous MiniMax M2.7 banner. The copy reflects the K2.7 Code release (a coding-focused agentic model that reduces thinking-token usage roughly 30% versus K2.6), the banner is served from in-repo assets (`assets/partners/banners/kimi-banner-en.png` / `kimi-banner-zh.png`) instead of the Moonshot CDN, and a clickable call-to-action links to the `aff=cc-switch` Moonshot console.
|
||||
- **Codex Unified Session-History Guide**: New trilingual (zh/en/ja) guide for the unified Codex session-history toggle, explaining what opt-in migration (on enable) and ledger-based restore (on disable) actually do, why session data is never truly deleted (tag-only rewrite plus automatic backups), and how to verify files on disk versus merely being filed under another provider drawer. It includes a symptom reference table for the common "my sessions are gone" misunderstanding plus on-disk verification commands for macOS/Linux/Windows, and is linked as the lead item in the v3.16.3 "Usage Guides" release notes.
|
||||
- **Simplified Homebrew Install Instructions**: The installation guide no longer instructs users to run `brew tap farion1231/ccswitch` before `brew install --cask cc-switch`; the deprecated tap step was removed from the en/ja/zh user manuals so the cask installs directly. (#4319)
|
||||
- **Star-History Global Rank Badge**: Added a star-history global rank badge next to the existing Trendshift badge in all four README locales, with light/dark theme variants.
|
||||
- **Volcengine Coding Plan Campaign Link**: The "中国大陆地区的开发者请点击这里" link in the ByteDance/Volcengine sponsor entry now points to the Volcengine `ai618` campaign page instead of the previous `codingplan` referral URL, updated across all four README locales.
|
||||
- **CCSub Sponsor Banner Vector Asset**: Replaced the low-res `ccsub.jpg` sponsor logo with a vector `ccsub.svg`, letterboxed from 2046x648 to 2046x850 (~2.406:1) so it matches the other sponsor-table banners and renders at the same 62px height. All four README locales point at the new asset.
|
||||
|
||||
## [3.16.3] - 2026-06-14
|
||||
|
||||
Development since v3.16.2 focuses on getting usage accounting right end-to-end — billing route-takeover and format-conversion traffic by the real upstream model and pricing basis (schema v11), counting Claude Code Workflow sub-agent sessions, folding Claude Desktop into the Claude view, refreshing the model pricing seed, and reworking the usage dashboard with global provider/model filters, brand-icon toolbars, and far more resilient quota queries — while hardening the proxy (mislabeled SSE bodies, Codex image rectification, OAuth token and takeover-residue recovery, Hermes duplicate YAML keys), reworking provider configuration (a custom User-Agent override, a unified Codex advanced section, searchable preset selection, a Fable 5 tier, and refreshed Kimi/Unity2/Volcengine/MiniMax presets), and smoothing the update, About-panel, and provider-health experiences.
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
|
||||
<a href="https://trendshift.io/repositories/15372" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15372" alt="farion1231%2Fcc-switch | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
<a href="https://www.star-history.com/#farion1231/cc-switch&Date"><picture><source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=farion1231/cc-switch&theme=dark" /><img alt="Star History Rank" src="https://api.star-history.com/badge?repo=farion1231/cc-switch" width="196" height="55" /></picture></a>
|
||||
|
||||
### 🌐 The Only Official Website: **[ccswitch.io](https://ccswitch.io)**
|
||||
|
||||
@@ -24,11 +25,9 @@ English | [中文](README_ZH.md) | [日本語](README_JA.md) | [Deutsch](README_
|
||||
<details open>
|
||||
<summary>Click to collapse</summary>
|
||||
|
||||
[](https://platform.minimax.io/subscribe/coding-plan?code=ClLhgxr2je&source=link)
|
||||
[](https://platform.moonshot.cn/console?aff=cc-switch)
|
||||
|
||||
MiniMax-M2.7 is a next-generation large language model designed for autonomous evolution and real-world productivity. Unlike traditional models, M2.7 actively participates in its own improvement through agent teams, dynamic tool use, and reinforcement learning loops. It delivers strong performance in software engineering (56.22% on SWE-Pro, 55.6% on VIBE-Pro, 57.0% on Terminal Bench 2) and excels in complex office workflows, achieving a leading 1495 ELO on GDPval-AA. With high-fidelity editing across Word, Excel, and PowerPoint, and a 97% adherence rate across 40+ complex skills, M2.7 sets a new standard for building AI-native workflows and organizations.
|
||||
|
||||
[Click](https://platform.minimax.io/subscribe/coding-plan?code=ClLhgxr2je&source=link) to get an exclusive 12% off the MiniMax Token Plan!
|
||||
Kimi K2.7 Code is an open-source, coding-focused agentic model developed by Moonshot AI. It delivers stronger coding and agent performance, with substantial improvements in real-world long-horizon coding tasks. These gains translate into higher end-to-end task success rates across complex software engineering workflows. K2.7 Code also improves reasoning efficiency, reducing thinking-token usage by approximately 30% compared with K2.6. **[Click here to start using Kimi](https://platform.moonshot.cn/console?aff=cc-switch)**
|
||||
|
||||
---
|
||||
|
||||
@@ -63,7 +62,7 @@ Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this lin
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
|
||||
<td>Thanks to Dola seed for sponsoring this project! Dola Seed 2.0 is a full‑modal general large model independently developed by ByteDance for the global market. Built on a unified multimodal architecture, it supports joint understanding and generation of text, images, audio, and video. It natively enables agent collaboration, with strong reasoning, long‑task execution, tool integration, and coding capabilities. It is widely applicable to smart cockpits, personal assistants, education, customer support, marketing, retail, and other scenarios. It excels in multimodal perception, end‑to‑end complex task delivery, stable interaction, and data security, and is readily accessible and deployable via the ModelArk platform.Register via <a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">this link</a> to get 500,000 tokens of free inference quota per model.<a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=6J6FV5N2&utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
|
||||
<td>Thanks to Dola seed for sponsoring this project! Dola Seed 2.0 is a full‑modal general large model independently developed by ByteDance for the global market. Built on a unified multimodal architecture, it supports joint understanding and generation of text, images, audio, and video. It natively enables agent collaboration, with strong reasoning, long‑task execution, tool integration, and coding capabilities. It is widely applicable to smart cockpits, personal assistants, education, customer support, marketing, retail, and other scenarios. It excels in multimodal perception, end‑to‑end complex task delivery, stable interaction, and data security, and is readily accessible and deployable via the ModelArk platform.Register via <a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">this link</a> to get 500,000 tokens of free inference quota per model.<a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -107,8 +106,8 @@ Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this lin
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
|
||||
<td>Thanks to CTok.ai for sponsoring this project! CTok.ai is dedicated to building a one-stop AI programming tool service platform. We offer professional Claude Code packages and technical community services, with support for Google Gemini and OpenAI Codex. Through carefully designed plans and a professional tech community, we provide developers with reliable service guarantees and continuous technical support, making AI-assisted programming a true productivity tool. Click <a href="https://ctok.ai">here</a> to register!</td>
|
||||
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
|
||||
<td>Thanks to ETok.ai for sponsoring this project! ETok.ai is dedicated to building a one-stop AI programming tool service platform. We offer professional Claude Code packages and technical community services, with support for Google Gemini and OpenAI Codex. Through carefully designed plans and a professional tech community, we provide developers with reliable service guarantees and continuous technical support, making AI-assisted programming a true productivity tool. Click <a href="https://etok.ai">here</a> to register!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -142,7 +141,7 @@ Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this lin
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.svg" alt="CCSub" width="150"></a></td>
|
||||
<td>Thanks to CCSub for sponsoring this project! CCSub is a stable, affordable AI API relay platform — your drop-in replacement for a Claude.ai subscription. One API key gives you access to Claude Opus 4.8, Sonnet, Haiku, GPT-5, Gemini, and DeepSeek at roughly 30% of direct API cost, with no VPN required from anywhere in the world. Compatible with Claude Code, Codex, Cursor, Cline, Continue, Windsurf, and all major AI coding tools. Register via <a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">this link</a> and get $5 free credit on sign-up.</td>
|
||||
</tr>
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
|
||||
<a href="https://trendshift.io/repositories/15372" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15372" alt="farion1231%2Fcc-switch | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
<a href="https://www.star-history.com/#farion1231/cc-switch&Date"><picture><source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=farion1231/cc-switch&theme=dark" /><img alt="Star History Rank" src="https://api.star-history.com/badge?repo=farion1231/cc-switch" width="196" height="55" /></picture></a>
|
||||
|
||||
### 🌐 Die einzige offizielle Website: **[ccswitch.io](https://ccswitch.io)**
|
||||
|
||||
@@ -24,11 +25,9 @@
|
||||
<details open>
|
||||
<summary>Zum Einklappen klicken</summary>
|
||||
|
||||
[](https://platform.minimax.io/subscribe/coding-plan?code=ClLhgxr2je&source=link)
|
||||
[](https://platform.moonshot.cn/console?aff=cc-switch)
|
||||
|
||||
MiniMax-M2.7 ist ein großes Sprachmodell der nächsten Generation, das auf autonome Weiterentwicklung und praxisnahe Produktivität ausgelegt ist. Anders als herkömmliche Modelle beteiligt sich M2.7 aktiv an seiner eigenen Verbesserung — durch Agententeams, dynamische Werkzeugnutzung und Reinforcement-Learning-Schleifen. Es liefert starke Leistung im Software-Engineering (56,22 % bei SWE-Pro, 55,6 % bei VIBE-Pro, 57,0 % bei Terminal Bench 2) und überzeugt bei komplexen Büro-Workflows mit einem führenden Wert von 1495 ELO bei GDPval-AA. Mit originalgetreuer Bearbeitung von Word-, Excel- und PowerPoint-Dateien sowie einer Befolgungsrate von 97 % über 40+ komplexe Skills hinweg setzt M2.7 einen neuen Standard für den Aufbau KI-nativer Workflows und Organisationen.
|
||||
|
||||
[Klicken Sie hier](https://platform.minimax.io/subscribe/coding-plan?code=ClLhgxr2je&source=link), um exklusive 12 % Rabatt auf den MiniMax Token Plan zu erhalten!
|
||||
Kimi K2.7 Code ist ein quelloffenes, auf Programmierung spezialisiertes Agenten-Modell von Moonshot AI. Es bietet eine stärkere Programmier- und Agentenleistung mit erheblichen Verbesserungen bei realen, langfristigen Programmieraufgaben. Diese Fortschritte führen zu höheren End-to-End-Erfolgsraten in komplexen Software-Engineering-Workflows. Zudem verbessert K2.7 Code die Reasoning-Effizienz und reduziert den Verbrauch an Thinking-Tokens um rund 30 % gegenüber K2.6. **[Hier klicken, um Kimi auszuprobieren](https://platform.moonshot.cn/console?aff=cc-switch)**
|
||||
|
||||
---
|
||||
|
||||
@@ -63,7 +62,7 @@ Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
|
||||
<td>Danke an Dola seed für die Unterstützung dieses Projekts! Dola Seed 2.0 ist ein voll-modales Allzweck-Großmodell, das von ByteDance eigenständig für den globalen Markt entwickelt wurde. Aufbauend auf einer einheitlichen multimodalen Architektur unterstützt es das gemeinsame Verstehen und Generieren von Text, Bildern, Audio und Video. Es ermöglicht von Haus aus die Zusammenarbeit von Agenten und verfügt über starke Fähigkeiten in den Bereichen Schlussfolgern, Ausführung langer Aufgaben, Werkzeugintegration und Programmierung. Es ist breit einsetzbar — etwa für intelligente Cockpits, persönliche Assistenten, Bildung, Kundensupport, Marketing, Einzelhandel und weitere Szenarien. Es überzeugt bei multimodaler Wahrnehmung, der Ende-zu-Ende-Bewältigung komplexer Aufgaben, stabiler Interaktion und Datensicherheit und ist über die ModelArk-Plattform einfach zugänglich und bereitstellbar. Registrieren Sie sich über <a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">diesen Link</a> und erhalten Sie pro Modell ein kostenloses Inferenzkontingent von 500.000 Token.<a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=6J6FV5N2&utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
|
||||
<td>Danke an Dola seed für die Unterstützung dieses Projekts! Dola Seed 2.0 ist ein voll-modales Allzweck-Großmodell, das von ByteDance eigenständig für den globalen Markt entwickelt wurde. Aufbauend auf einer einheitlichen multimodalen Architektur unterstützt es das gemeinsame Verstehen und Generieren von Text, Bildern, Audio und Video. Es ermöglicht von Haus aus die Zusammenarbeit von Agenten und verfügt über starke Fähigkeiten in den Bereichen Schlussfolgern, Ausführung langer Aufgaben, Werkzeugintegration und Programmierung. Es ist breit einsetzbar — etwa für intelligente Cockpits, persönliche Assistenten, Bildung, Kundensupport, Marketing, Einzelhandel und weitere Szenarien. Es überzeugt bei multimodaler Wahrnehmung, der Ende-zu-Ende-Bewältigung komplexer Aufgaben, stabiler Interaktion und Datensicherheit und ist über die ModelArk-Plattform einfach zugänglich und bereitstellbar. Registrieren Sie sich über <a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">diesen Link</a> und erhalten Sie pro Modell ein kostenloses Inferenzkontingent von 500.000 Token.<a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -107,8 +106,8 @@ Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
|
||||
<td>Danke an CTok.ai für die Unterstützung dieses Projekts! CTok.ai widmet sich dem Aufbau einer Komplettlösung für KI-Programmierwerkzeuge. Wir bieten professionelle Claude-Code-Pakete und Dienste einer technischen Community, mit Unterstützung für Google Gemini und OpenAI Codex. Durch sorgfältig gestaltete Pläne und eine professionelle Tech-Community geben wir Entwicklern verlässliche Servicegarantien und kontinuierlichen technischen Support an die Hand und machen KI-gestützte Programmierung zu einem echten Produktivitätswerkzeug. Klicken Sie <a href="https://ctok.ai">hier</a>, um sich zu registrieren!</td>
|
||||
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
|
||||
<td>Danke an ETok.ai für die Unterstützung dieses Projekts! ETok.ai widmet sich dem Aufbau einer Komplettlösung für KI-Programmierwerkzeuge. Wir bieten professionelle Claude-Code-Pakete und Dienste einer technischen Community, mit Unterstützung für Google Gemini und OpenAI Codex. Durch sorgfältig gestaltete Pläne und eine professionelle Tech-Community geben wir Entwicklern verlässliche Servicegarantien und kontinuierlichen technischen Support an die Hand und machen KI-gestützte Programmierung zu einem echten Produktivitätswerkzeug. Klicken Sie <a href="https://etok.ai">hier</a>, um sich zu registrieren!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -142,7 +141,7 @@ Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.svg" alt="CCSub" width="150"></a></td>
|
||||
<td>Danke an CCSub für die Unterstützung dieses Projekts! CCSub ist eine zuverlässige und kostengünstige AI-API-Relay-Plattform — Ihr direkter Ersatz für ein Claude.ai-Abonnement. Mit einem einzigen API-Schlüssel erhalten Sie Zugriff auf Claude Opus 4.8, Sonnet, Haiku, GPT-5, Gemini und DeepSeek zu etwa 30 % der Kosten der direkten API-Nutzung — ohne VPN, weltweit nutzbar. Kompatibel mit Claude Code, Codex, Cursor, Cline, Continue, Windsurf und allen gängigen AI-Coding-Tools. Registrieren Sie sich über <a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">diesen Link</a> und erhalten Sie $5 Startguthaben bei der Anmeldung.</td>
|
||||
</tr>
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
|
||||
<a href="https://trendshift.io/repositories/15372" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15372" alt="farion1231%2Fcc-switch | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
<a href="https://www.star-history.com/#farion1231/cc-switch&Date"><picture><source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=farion1231/cc-switch&theme=dark" /><img alt="Star History Rank" src="https://api.star-history.com/badge?repo=farion1231/cc-switch" width="196" height="55" /></picture></a>
|
||||
|
||||
### 🌐 唯一の公式サイト:**[ccswitch.io](https://ccswitch.io)**
|
||||
|
||||
@@ -24,11 +25,9 @@
|
||||
<details open>
|
||||
<summary>クリックで折りたたむ</summary>
|
||||
|
||||
[](https://platform.minimax.io/subscribe/coding-plan?code=ClLhgxr2je&source=link)
|
||||
[](https://platform.moonshot.cn/console?aff=cc-switch)
|
||||
|
||||
MiniMax-M2.7 は、自律的進化と実世界の生産性向上のために設計された次世代大規模言語モデルです。従来のモデルとは異なり、M2.7 はエージェントチーム、動的ツール使用、強化学習ループを通じて自身の改善に積極的に参加します。ソフトウェアエンジニアリングにおいて優れた性能を発揮し(SWE-Pro で 56.22%、VIBE-Pro で 55.6%、Terminal Bench 2 で 57.0%)、複雑なオフィスワークフローにも秀でており、GDPval-AA で 1495 ELO のリーディングスコアを達成しています。Word・Excel・PowerPoint の高忠実度編集と、40 以上の複雑なスキルにわたる 97% の遵守率により、M2.7 は AI ネイティブなワークフローと組織構築の新基準を打ち立てます。
|
||||
|
||||
[こちら](https://platform.minimax.io/subscribe/coding-plan?code=ClLhgxr2je&source=link)から MiniMax Token Plan の限定 12% オフを入手!
|
||||
Kimi K2.7 Code は Moonshot AI が開発した、コーディングに特化したオープンソースのエージェントモデルです。コーディング能力とエージェント性能が全面的に強化され、実世界の長程コーディングタスクで大幅な向上を実現し、複雑なソフトウェアエンジニアリングのワークフロー全体でエンドツーエンドのタスク成功率を高めます。さらに K2.7 Code は推論効率を改善し、K2.6 と比べて推論トークンの消費を約 30% 削減します。**[ここをクリックして Kimi を体験する](https://platform.moonshot.cn/console?aff=cc-switch)**
|
||||
|
||||
---
|
||||
|
||||
@@ -63,7 +62,7 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
|
||||
<td>Dola seed のご支援に感謝します!Dola Seed 2.0 は ByteDance がグローバル市場向けに独自開発したフルモーダル汎用大規模モデルです。統一されたマルチモーダルアーキテクチャを基盤に、テキスト・画像・音声・動画の統合的な理解と生成をサポートします。エージェント連携をネイティブに実現し、強力な推論、長時間タスクの実行、ツール統合、コーディング能力を備えています。スマートコックピット、パーソナルアシスタント、教育、カスタマーサポート、マーケティング、リテールなど幅広いシナリオに適用可能で、マルチモーダル認識、エンドツーエンドの複雑なタスク遂行、安定したインタラクション、データセキュリティに優れ、ModelArk プラットフォームを通じて手軽に利用・デプロイできます。<a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">このリンク</a>からご登録いただくと、モデルごとに 500,000 トークンの無料推論クォータを進呈します。<a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=6J6FV5N2&utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
|
||||
<td>Dola seed のご支援に感謝します!Dola Seed 2.0 は ByteDance がグローバル市場向けに独自開発したフルモーダル汎用大規模モデルです。統一されたマルチモーダルアーキテクチャを基盤に、テキスト・画像・音声・動画の統合的な理解と生成をサポートします。エージェント連携をネイティブに実現し、強力な推論、長時間タスクの実行、ツール統合、コーディング能力を備えています。スマートコックピット、パーソナルアシスタント、教育、カスタマーサポート、マーケティング、リテールなど幅広いシナリオに適用可能で、マルチモーダル認識、エンドツーエンドの複雑なタスク遂行、安定したインタラクション、データセキュリティに優れ、ModelArk プラットフォームを通じて手軽に利用・デプロイできます。<a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">このリンク</a>からご登録いただくと、モデルごとに 500,000 トークンの無料推論クォータを進呈します。<a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -107,8 +106,8 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
</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>
|
||||
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
|
||||
<td>ETok.ai のご支援に感謝します!ETok.ai はワンストップ AI プログラミングツールサービスプラットフォームの構築に取り組んでいます。Claude Code のプロフェッショナルプランと技術コミュニティサービスを提供し、Google Gemini や OpenAI Codex にも対応しています。丁寧に設計されたプランと専門的な技術コミュニティを通じて、開発者に安定したサービス保証と継続的な技術サポートを提供し、AI アシストプログラミングを真の生産性ツールにします。<a href="https://etok.ai">こちら</a>から登録してください!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -142,7 +141,7 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.svg" alt="CCSub" width="150"></a></td>
|
||||
<td>CCSub のご支援に感謝します!CCSub は安定した低価格の AI API リレープラットフォームで、Claude Code 公式サブスクリプションの強力な代替です。1 つの API キーで Claude Opus 4.8、Sonnet 4.6、Haiku 4.5、GPT-5、Gemini、DeepSeek の全モデルを公式直接利用の約 1/3 のコストでご利用いただけます。VPN 不要で世界中から直接接続可能。Claude Code、Codex、Cursor、Cline、Continue、Windsurf など主要な AI コーディングツールすべてに対応しています。<a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">こちらのリンク</a>から登録すると $5 の無料クレジットがもらえます。</td>
|
||||
</tr>
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
|
||||
<a href="https://trendshift.io/repositories/15372" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15372" alt="farion1231%2Fcc-switch | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
<a href="https://www.star-history.com/#farion1231/cc-switch&Date"><picture><source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=farion1231/cc-switch&theme=dark" /><img alt="Star History Rank" src="https://api.star-history.com/badge?repo=farion1231/cc-switch" width="196" height="55" /></picture></a>
|
||||
|
||||
### 🌐 唯一官方网站:**[ccswitch.io](https://ccswitch.io)**
|
||||
|
||||
@@ -24,11 +25,9 @@
|
||||
<details open>
|
||||
<summary>点击折叠</summary>
|
||||
|
||||
[](https://platform.minimaxi.com/subscribe/coding-plan?code=7kYF2VoaCn&source=link)
|
||||
[](https://platform.moonshot.cn/console?aff=cc-switch)
|
||||
|
||||
MiniMax M2.7 是 MiniMax 首个深度参与自我迭代的模型,可自主构建复杂 Agent Harness,并基于 Agent Teams、复杂 Skills、Tool Search Tool 等能力完成高复杂度生产力任务;其在软件工程、端到端项目交付及办公场景中表现优异,多项评测接近行业领先水平,同时具备稳定的复杂任务执行、环境交互能力以及良好的情商与身份保持能力。
|
||||
|
||||
[点击此处](https://platform.minimaxi.com/subscribe/coding-plan?code=7kYF2VoaCn&source=link)享 MiniMax Token Plan 专属 88 折优惠!
|
||||
Kimi K2.7 Code 是 Moonshot AI 开发的编程专用开源智能体模型。它在编程与智能体执行能力上全面增强,在真实长程编程任务中实现显著提升,带来复杂软件工程工作流中更高的端到端任务成功率。同时,K2.7 Code 优化了推理效率,相较 K2.6 平均减少约 30% 的推理 token 消耗。**[点击此处开启 Kimi 使用体验](https://platform.moonshot.cn/console?aff=cc-switch)**
|
||||
|
||||
---
|
||||
|
||||
@@ -62,8 +61,8 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=6J6FV5N2&utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/huoshan.png" alt="HuoShan" width="150"></a></td>
|
||||
<td>感谢火山方舟 Agent Plan 模型赞助了本项目!方舟 Agent Plan 模型订阅套餐集成了包含 Doubao-Seed、Doubao-Seedance、Doubao-Seedream 等在内的字节跳动自研 SOTA 级模型,覆盖文本、代码、图像、视频等多模态任务。最新支持 MiniMax-M3、DeepSeek-V4 系列、GLM-5.1、Doubao-Seed-2.0 系列、Kimi-K2.6 等模型,工具不限。超全模态模型与 Harness 升级一步到位,深度支持 Agent 框架与 AI 编程工具。一次订阅,可以为不同任务切换合适的 AI 引擎。方舟 Coding Plan 为 CC Switch 的用户提供了专属福利:通过<a href="https://www.volcengine.com/activity/codingplan?ac=MMAP8JTTCAQ2&rc=6J6FV5N2&utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">此链接</a>订阅方舟 Coding Plan,新客户首两个月享 2.5 折优惠,再用专属邀请码 6J6FV5N2 领取奖励叠加 9.5 折,低至 9.4 元/月!<a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">>>For developers outside Mainland China, please click here</a></td>
|
||||
<td width="180"><a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/huoshan.png" alt="HuoShan" width="150"></a></td>
|
||||
<td>感谢火山方舟 Agent Plan 模型赞助了本项目!方舟 Agent Plan 模型订阅套餐集成了包含 Doubao-Seed、Doubao-Seedance、Doubao-Seedream 等在内的字节跳动自研 SOTA 级模型,覆盖文本、代码、图像、视频等多模态任务。最新支持 MiniMax-M3、DeepSeek-V4 系列、GLM-5.1、Doubao-Seed-2.0 系列、Kimi-K2.6 等模型,工具不限。超全模态模型与 Harness 升级一步到位,深度支持 Agent 框架与 AI 编程工具。一次订阅,可以为不同任务切换合适的 AI 引擎。方舟 Coding Plan 为 CC Switch 的用户提供了专属福利:通过<a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">此链接</a>订阅方舟 Coding Plan,新客户首两个月享 2.5 折优惠,再用专属邀请码 6J6FV5N2 领取奖励叠加 9.5 折,低至 9.4 元/月!<a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">>>For developers outside Mainland China, please click here</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -108,8 +107,8 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
</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>
|
||||
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
|
||||
<td>感谢 ETok.ai 赞助了本项目!ETok.ai 致力于打造一站式 AI 编程工具服务平台。我们提供 Claude Code 专业套餐及技术社群服务,同时支持 Google Gemini 和 OpenAI Codex。通过精心设计的套餐方案和专业的技术社群,为开发者提供稳定的服务保障和持续的技术支持,让 AI 辅助编程真正成为开发者的生产力工具。点击<a href="https://etok.ai">这里</a>注册!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -143,7 +142,7 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.svg" alt="CCSub" width="150"></a></td>
|
||||
<td>感谢 CCSub 赞助本项目!CCSub 是稳定、实惠的 AI API 中转平台,是 Claude Code 官方订阅的超强平替。一个 API Key 即可调用 Claude Opus 4.8、Sonnet 4.6、Haiku 4.5、GPT-5、Gemini、DeepSeek 全系列模型,价格约为官方直连的 1/3,全球直连无需梯子。兼容 Claude Code、Codex、Cursor、Cline、Continue、Windsurf 等所有主流 AI 编程工具。通过<a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">此链接</a>注册即送 $5 体验额度!</td>
|
||||
</tr>
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 1.2 MiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 4.9 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 511 KiB |
|
After Width: | Height: | Size: 1.2 MiB |
@@ -0,0 +1,46 @@
|
||||
# Can't See Custom Models in the Codex Desktop App? (FAQ)
|
||||
|
||||
> Applies to CC Switch v3.16.1 and later. This article explains "why the Codex desktop app can't see custom models" and the available mitigation; for the detailed step-by-step setup with screenshots, see [Keep Codex Remote Control and Official Plugins While Using Third-Party APIs](./codex-official-auth-preservation-guide-en.md).
|
||||
|
||||
## Symptom
|
||||
|
||||
After you switch Codex to a third-party / custom model in CC Switch (DeepSeek, Kimi, GLM, MiniMax, an aggregator, etc.):
|
||||
|
||||
- The model picker in the **Codex desktop app** doesn't show these custom models — often only the official default model remains, and the reasoning level falls back to the official default;
|
||||
- but everything works fine in the **command-line `codex`** `/model` menu.
|
||||
|
||||
Many users have run into this. Here's why, and what you can do about it.
|
||||
|
||||
## Why this happens
|
||||
|
||||
This is **not a CC Switch local-config problem and not a CC Switch bug** — it is the **Codex desktop app's (the upstream closed-source client's) own model-gating behavior**.
|
||||
|
||||
The Codex desktop app's model picker decides which models to allow based on your **current login identity**: when it can't detect an official ChatGPT / Codex login state, it forces the picker back to the official default model and hides the custom models you configured through `config.toml` (the reasoning level falls back to the official default too). The upstream has marked "exposing custom-provider models in the desktop GUI" as not planned, so CC Switch cannot fully fix this at the desktop-GUI level.
|
||||
|
||||
The command-line `codex` `/model` menu and request routing both recognize the custom providers in `config.toml` correctly — **only the desktop GUI picker is constrained by this gating layer**.
|
||||
|
||||
## Mitigation: keep the official login
|
||||
|
||||
The workaround is to **keep the official login state** so the desktop app's gating allows your custom models through. The key points are below (the full step-by-step setup with screenshots is in the linked guide):
|
||||
|
||||
1. Log in once with an official ChatGPT / Codex account in Codex (a Free subscription is enough) to keep the official login state.
|
||||
2. In CC Switch, enable `Settings -> General -> Codex App Enhancements -> Keep official login when switching third-party providers` (**off by default**).
|
||||
3. Enable local routing and route Codex through it for this third-party provider (required for Chat Completions providers such as DeepSeek / Kimi / MiniMax).
|
||||
4. Fully quit and restart Codex.
|
||||
|
||||
Once enabled, CC Switch preserves the official login state in `~/.codex/auth.json` when switching to a third-party provider and writes the third-party key into `config.toml`, so the desktop app still recognizes the official login identity, the gating lets your models through, and the custom models you configured reappear in the picker. **The preserved official token is never sent to the third party** — third-party model requests still use the key you configured, forwarded through the local route.
|
||||
|
||||
> 📖 Detailed step-by-step setup: [Keep Codex Remote Control and Official Plugins While Using Third-Party APIs](./codex-official-auth-preservation-guide-en.md)
|
||||
|
||||
## Still can't see them?
|
||||
|
||||
- **Confirm the toggle is on**: this toggle is off by default, and many people overwrite the official login state the first time they switch to a third-party provider, which is exactly why the models disappear — enable it as above.
|
||||
- **The official login state expires**: if you haven't used the official login for several days, the picker may go empty again once the token expires — log in to the official account once more to restore it.
|
||||
- **Command-line fallback diagnosis**: run `codex debug models` to list the models actually available on the CLI side and confirm the model itself is configured correctly (the CLI is unaffected by this gating).
|
||||
- Individual Codex desktop versions may behave slightly differently; this is in the upstream client's domain, and no CC Switch version can fully fix it at the desktop-GUI level.
|
||||
|
||||
## References
|
||||
|
||||
- [Keep Codex Remote Control and Official Plugins While Using Third-Party APIs](./codex-official-auth-preservation-guide-en.md)
|
||||
- [Codex DeepSeek local routing hands-on guide](./codex-deepseek-routing-guide-en.md)
|
||||
- [Local Routing](../user-manual/en/4-proxy/4.2-routing.md)
|
||||
@@ -0,0 +1,47 @@
|
||||
# Codex デスクトップアプリでカスタムモデルが見えない?(よくある質問)
|
||||
|
||||
> 対象バージョン: CC Switch v3.16.1 以降。本記事は「なぜ Codex デスクトップアプリでカスタムモデルが見えないのか」と、使える緩和策を解説します。図入りの詳細な設定手順は [サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する](./codex-official-auth-preservation-guide-ja.md) を参照してください。
|
||||
|
||||
## 現象
|
||||
|
||||
CC Switch で Codex をサードパーティ / カスタムモデル(DeepSeek、Kimi、GLM、MiniMax、中継サービスなど)へ切り替えた後:
|
||||
|
||||
- **Codex デスクトップアプリ**のモデルセレクタにこれらのカスタムモデルが表示されず、多くの場合は公式の既定モデルだけが残り、思考レベルも公式の既定へ戻ってしまう。
|
||||
- 一方で**コマンドライン `codex`** の `/model` ではすべて正常に表示される。
|
||||
|
||||
多くのユーザーがこの現象に遭遇しています。以下で原因と対処を解説します。
|
||||
|
||||
## なぜこうなるのか
|
||||
|
||||
これは **CC Switch のローカル設定の問題でも、CC Switch のバグでもありません**。**Codex デスクトップアプリ(上流のクローズドソースクライアント)自身のモデルゲーティング挙動**です。
|
||||
|
||||
Codex デスクトップアプリのモデルセレクタは、あなたの**現在のログイン ID** に応じてどのモデルを通すかを決めます。公式 ChatGPT / Codex のログイン状態を検出できないとき、セレクタを公式の既定モデルへ強制的に戻し、`config.toml` で設定したカスタムモデルを隠します(思考レベルもあわせて公式の既定へ戻ります)。公式は「デスクトップ GUI でカスタムプロバイダーのモデルを公開する」ことを not planned としてマークしているため、CC Switch がデスクトップ GUI のレベルでこれを根本的に修正することはできません。
|
||||
|
||||
コマンドライン `codex` の `/model` とリクエストルーティングは `config.toml` 内のカスタムプロバイダーを正常に認識できます。**デスクトップ GUI のセレクタだけがこのゲーティングの制限を受けます**。
|
||||
|
||||
## 緩和策: 公式ログインを保持する
|
||||
|
||||
対処は**公式ログイン状態を保持する**ことで、デスクトップアプリのゲーティングにあなたのカスタムモデルを通させます。要点は次のとおりです(完全な図入り手順は下のリンク先のガイドを参照してください):
|
||||
|
||||
1. まず Codex で公式 ChatGPT / Codex に一度ログインし(Free サブスクリプションで構いません)、公式ログイン状態を保持する。
|
||||
2. CC Switch で `設定 → 一般 → Codex アプリ拡張 → サードパーティ切替時に公式ログインを保持` をオンにする(**デフォルトはオフ**)。
|
||||
3. そのサードパーティプロバイダーでローカルルーティングを有効化し、Codex のルーティングをオンにする(DeepSeek / Kimi / MiniMax など Chat Completions プロトコルのプロバイダーでは必須)。
|
||||
4. Codex を完全に終了して再起動する。
|
||||
|
||||
オンにすると、CC Switch はサードパーティプロバイダーへ切り替える際に `~/.codex/auth.json` 内の公式ログイン状態を保持し、サードパーティの Key を `config.toml` へ書き込みます。これにより、デスクトップアプリは引き続き公式ログイン ID を認識してゲーティングを通すため、設定したカスタムモデルがセレクタに再び表示されます。**保持された公式 Token がサードパーティへ送られることはありません**——サードパーティのモデルリクエストは引き続き、設定した Key でローカルルーティング経由で転送されます。
|
||||
|
||||
> 📖 詳細な図入り手順: [サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する](./codex-official-auth-preservation-guide-ja.md)
|
||||
|
||||
## それでも見えない場合は
|
||||
|
||||
- **スイッチがオンか確認する**: このスイッチはデフォルトでオフです。多くの人は初めてサードパーティへ切り替えたときに公式ログイン状態を上書きしてしまい、その結果見えなくなっています——上記の手順でオンにしてください。
|
||||
- **公式ログイン状態は期限切れになる**: 数日間公式ログインを使わないと、Token が失効した後にセレクタが再び空になることがあります——公式に一度ログインし直せば回復します。
|
||||
- **コマンドラインでの確認**: `codex debug models` を使うと CLI 側で実際に利用可能なモデルを一覧でき、モデル自体が正しく設定されていることを確認できます(CLI はこのゲーティングの影響を受けません)。
|
||||
- 個々の Codex デスクトップ版で挙動が多少異なる場合があります。これは上流クライアントの範疇であり、CC Switch のどのバージョンでもデスクトップ GUI のレベルで根本解決することはできません。
|
||||
|
||||
## 参考リンク
|
||||
|
||||
- [サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する](./codex-official-auth-preservation-guide-ja.md)
|
||||
- [Codex DeepSeek ローカルルーティング実践ガイド](./codex-deepseek-routing-guide-ja.md)
|
||||
- [ローカルルーティング](../user-manual/ja/4-proxy/4.2-routing.md)
|
||||
</content>
|
||||
@@ -0,0 +1,46 @@
|
||||
# Codex 桌面应用里看不到自定义模型?(常见问题)
|
||||
|
||||
> 适用版本:CC Switch v3.16.1 及以上。本文解释「为什么 Codex 桌面应用看不到自定义模型」以及可用的缓解办法;详细的图文配置步骤见 [使用第三方 API 时保留 Codex 远程操作和官方插件](./codex-official-auth-preservation-guide-zh.md)。
|
||||
|
||||
## 现象
|
||||
|
||||
在 CC Switch 里把 Codex 切换到第三方 / 自定义模型(DeepSeek、Kimi、GLM、MiniMax、中转站等)后:
|
||||
|
||||
- **Codex 桌面应用**的模型选择器里看不到这些自定义模型,往往只剩官方默认模型,思考等级也回落到官方默认;
|
||||
- 但**命令行 `codex`** 的 `/model` 里一切正常。
|
||||
|
||||
很多用户都遇到过这个现象,下面解释原因与办法。
|
||||
|
||||
## 为什么会这样
|
||||
|
||||
这**不是 CC Switch 的本地配置问题,也不是 CC Switch 的 bug**,而是 **Codex 桌面应用(上游闭源客户端)自身的模型门控行为**。
|
||||
|
||||
Codex 桌面应用的模型选择器会按你**当前的登录身份**来决定放行哪些模型:当它检测不到官方 ChatGPT / Codex 登录态时,会把选择器强制回落到官方默认模型,把你通过 `config.toml` 配置的自定义模型藏起来(思考等级也会一并回落到官方默认)。官方已把「在桌面 GUI 里暴露自定义供应商模型」标记为 not planned,因此 CC Switch 无法从桌面 GUI 层面彻底修复它。
|
||||
|
||||
命令行 `codex` 的 `/model` 与请求路由都能正常识别 `config.toml` 里的自定义供应商,**唯独桌面 GUI 的选择器受这层门控限制**。
|
||||
|
||||
## 怎么缓解:保留官方登录
|
||||
|
||||
办法是**保留官方登录态**,让桌面应用的门控放行你的自定义模型。要点如下(完整图文步骤见下方链接的攻略):
|
||||
|
||||
1. 先在 Codex 里登录一次官方 ChatGPT / Codex(Free 订阅即可),保留官方登录态。
|
||||
2. 在 CC Switch 开启 `设置 → 通用 → Codex 应用增强 → 切换第三方时保留官方登录`(**默认关闭**)。
|
||||
3. 为该第三方供应商开启本地路由并接管 Codex(Chat Completions 协议的供应商如 DeepSeek / Kimi / MiniMax 必须开启)。
|
||||
4. 完全退出并重启 Codex。
|
||||
|
||||
开启后,CC Switch 在切换第三方供应商时会保留 `~/.codex/auth.json` 里的官方登录态、把第三方 Key 写进 `config.toml`,于是桌面应用仍识别官方登录身份、门控放行,你配置的自定义模型就会重新出现在选择器里。**保留的官方 Token 不会被发往第三方**——第三方模型请求仍用你配置的 Key 经本地路由转发。
|
||||
|
||||
> 📖 详细图文步骤:[使用第三方 API 时保留 Codex 远程操作和官方插件](./codex-official-auth-preservation-guide-zh.md)
|
||||
|
||||
## 仍然看不到怎么办
|
||||
|
||||
- **确认开关已开**:该开关默认关闭,很多人第一次切到第三方就把官方登录态覆盖掉了,所以才看不到——按上面开启即可。
|
||||
- **官方登录态会过期**:如果连续几天没用过官方登录,Token 失效后选择器可能又变空——重新登录一次官方即可恢复。
|
||||
- **命令行兜底诊断**:用 `codex debug models` 可以列出 CLI 端实际可用的模型,确认模型本身已正确配置(CLI 不受此门控影响)。
|
||||
- 个别 Codex 桌面版本的行为可能略有差异;这属于上游客户端范畴,CC Switch 各版本都无法从桌面 GUI 层根治。
|
||||
|
||||
## 参考链接
|
||||
|
||||
- [使用第三方 API 时保留 Codex 远程操作和官方插件](./codex-official-auth-preservation-guide-zh.md)
|
||||
- [Codex DeepSeek 本地路由实战攻略](./codex-deepseek-routing-guide-zh.md)
|
||||
- [本地路由](../user-manual/zh/4-proxy/4.2-routing.md)
|
||||
@@ -202,6 +202,7 @@ Because Codex App Enhancements and routing takeover can create unnecessary troub
|
||||
|
||||
## References
|
||||
|
||||
- [Can't see custom models in the Codex desktop app? (FAQ)](./codex-desktop-custom-model-visibility-en.md)
|
||||
- [Codex DeepSeek local routing hands-on guide](./codex-deepseek-routing-guide-en.md)
|
||||
- [Add a Codex provider: Chat Completions routing and model mapping](../user-manual/en/2-providers/2.1-add.md)
|
||||
- [Local Proxy Service](../user-manual/en/4-proxy/4.1-service.md)
|
||||
|
||||
@@ -202,6 +202,7 @@ Codex アプリ拡張やルーティング管理は、必要ないユーザー
|
||||
|
||||
## 参考リンク
|
||||
|
||||
- [Codex デスクトップアプリでカスタムモデルが見えない?(よくある質問)](./codex-desktop-custom-model-visibility-ja.md)
|
||||
- [Codex DeepSeek ローカルルーティング実践ガイド](./codex-deepseek-routing-guide-ja.md)
|
||||
- [Codex プロバイダーの追加: Chat Completions ルーティングとモデルマッピング](../user-manual/ja/2-providers/2.1-add.md)
|
||||
- [ローカルプロキシサービス](../user-manual/ja/4-proxy/4.1-service.md)
|
||||
|
||||
@@ -202,6 +202,7 @@ Codex 的模型目录是启动时读取的。即使 CC Switch 已经生成了新
|
||||
|
||||
## 参考链接
|
||||
|
||||
- [Codex 桌面应用里看不到自定义模型?(常见问题)](./codex-desktop-custom-model-visibility-zh.md)
|
||||
- [Codex DeepSeek 本地路由实战攻略](./codex-deepseek-routing-guide-zh.md)
|
||||
- [添加 Codex 供应商:Chat Completions 路由与模型映射](../user-manual/zh/2-providers/2.1-add.md)
|
||||
- [本地代理服务](../user-manual/zh/4-proxy/4.1-service.md)
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
# Unified Codex Session History: Feature Overview and Usage Guide (CC Switch)
|
||||
|
||||
> Applies to CC Switch v3.16.x and later. This guide is based on the current code; every command and path can be verified by hand. Examples use de-identified data and contain no real session content or API keys.
|
||||
|
||||
## What this feature is
|
||||
|
||||
"Unified Codex session history" is a switch that CC Switch v3.16.x adds for Codex. You'll find it under **Settings -> General -> the "Codex App Enhancements" group** ("Codex App Enhancements" is the group title; the switch itself is called "Unified Codex session history"). Once enabled, **sessions from your official subscription (ChatGPT login / OpenAI API key) appear in the same history / resume list as sessions from every third-party provider CC Switch manages**—they are no longer split into two lists that can't see each other.
|
||||
|
||||
## What problem it solves
|
||||
|
||||
Codex classifies sessions by a "provider tag" (a field called `model_provider`), and **the resume / history list only shows sessions whose tag matches your currently active provider**. As a result, sessions are naturally sorted into two separate "drawers":
|
||||
|
||||
- Sessions from your official subscription go under Codex's built-in **`openai`** tag;
|
||||
- Every third-party provider CC Switch manages goes under the **`custom`** tag.
|
||||
|
||||
The two drawers can't see each other. If you **switch frequently between official and third-party**, you'll hit this kind of fragmentation: "the session I was just chatting in with the official account disappeared from the history list after I switched to a third-party provider"—it isn't actually gone, it's just been sorted into the other drawer. This split both makes it easy to believe a session was lost, and makes it inconvenient to review and resume all your sessions in one place.
|
||||
|
||||
**This switch exists to eliminate that fragmentation**: it makes the official subscription run under the `custom` tag too, so official and third-party sessions merge into one list and everything is easy to find and resume in a single place.
|
||||
|
||||
> ✅ **One important premise that runs through this whole guide, please remember it first**: this feature (unify / migrate / restore) **only ever rewrites that one classification tag `model_provider` in your session records, and it automatically makes a backup of the original file before every rewrite**. It never deletes, clears, or overwrites a single line of your conversations. So whenever this guide later mentions "some sessions are no longer visible," it almost always means "they've been sorted into the other drawer," not "the data is gone." If you're truly worried, jump straight to the [symptom reference table](#i-feel-like-my-sessions-are-gone-symptom-reference-table) and [verify the files are still there by hand](#verify-by-hand-your-session-files-are-still-on-disk-the-most-important-section).
|
||||
|
||||
## How it works (one-line version)
|
||||
|
||||
Think of it as **two drawers + automatic backup**:
|
||||
|
||||
- By default, official sessions live in the `openai` drawer and third-party sessions live in the `custom` drawer, invisible to each other;
|
||||
- The switch makes **the official side use the `custom` drawer too**, merging the two drawers into one shared list;
|
||||
- You can optionally choose to "move" your **existing official sessions** into the shared drawer as well (this step is called **migration**; it's optional and requires you to opt in by checking a box), and **before anything is moved a backup copy is made first**, so the whole process is **reversible**;
|
||||
- **Authentication is completely unaffected**—your official subscription still uses your ChatGPT login and still goes through the official backend; only the session's classification tag changes.
|
||||
|
||||
For the full mechanism (what gets injected, why it's reversible, how migration / restore guarantee no data loss) see [The core mental model](#the-core-mental-model-two-drawers--automatic-backup) and the [Advanced mechanism appendix](#advanced-mechanism-appendix-for-users-who-want-to-truly-understand-how-it-works) at the end.
|
||||
|
||||
## How to use it (at a glance)
|
||||
|
||||
1. **Enable**: Settings -> General -> Codex App Enhancements -> turn on "Unified Codex session history" -> in the dialog decide whether to check "Also migrate existing official session history" (check it if you want your **earlier** official sessions merged into the unified list too; leave it unchecked if you only want unification from now on) -> confirm. See [What happens when you enable it](#what-happens-when-you-enable-it-step-by-step).
|
||||
2. **Disable**: turn the same switch off -> in the dialog keep "restore exactly from backup" checked (it's checked by default) -> confirm, and the official sessions you migrated in will be precisely flipped back to the official list. See [What happens when you disable it](#what-happens-when-you-disable-it-step-by-step).
|
||||
3. **Feel like a session is gone?** Don't panic—jump to the [symptom reference table](#i-feel-like-my-sessions-are-gone-symptom-reference-table) to locate it by symptom, and use the commands in the [verify by hand](#verify-by-hand-your-session-files-are-still-on-disk-the-most-important-section) section to see for yourself that the files are all there.
|
||||
|
||||
---
|
||||
|
||||
## The core mental model: two drawers + automatic backup
|
||||
|
||||
To understand this feature, you only need to remember two things: **drawers** and **backups**.
|
||||
|
||||
### Drawers: how Codex classifies sessions
|
||||
|
||||
Every time you start a Codex session, Codex records a tag `model_provider` in the session file header, marking "which provider this session was chatted with." Codex's **resume / history list is filtered precisely by the currently active tag**—it only shows sessions whose tag matches "the provider you're on right now."
|
||||
|
||||
- Sessions from your official subscription (ChatGPT login / OpenAI API key) carry the built-in tag **`openai`**.
|
||||
- Every third-party provider CC Switch manages uses the tag **`custom`**.
|
||||
|
||||
So by default, official sessions and third-party sessions are inherently invisible to each other—they live in two different drawers. This is **Codex's own design**, not CC Switch losing anything.
|
||||
|
||||
```text
|
||||
Default state (unified switch off):
|
||||
┌───────────────────────┐ ┌──────────────────────────┐
|
||||
│ openai drawer │ │ custom drawer │
|
||||
│ (official sessions) │ │ (third-party sessions) │
|
||||
└───────────────────────┘ └──────────────────────────┘
|
||||
▲ ▲
|
||||
visible only while visible only while
|
||||
on the official provider on a third-party provider
|
||||
|
||||
The two drawers can't see each other.
|
||||
```
|
||||
|
||||
**What the "Unified Codex session history" switch does is make the official subscription run under the `custom` tag too, merging the two drawers into one**, so official and third-party sessions appear in the same resume list. Note: **authentication doesn't change**—your official subscription still uses your ChatGPT login and still goes through the official backend; only the session's "classification tag" changes from `openai` to `custom`.
|
||||
|
||||
```text
|
||||
After the unified switch is on:
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ custom shared drawer │
|
||||
│ official sessions + third-party sessions │
|
||||
│ (appear in the same history / resume list) │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Backups: a copy is made before every tag change
|
||||
|
||||
"Merging the drawers" requires changing the tag of some official sessions from `openai` to `custom` (this step is called **migration**, and it's **optional and requires you to opt in**). And **before any rewrite, CC Switch first copies the original file untouched** to here:
|
||||
|
||||
```text
|
||||
~/.cc-switch/backups/codex-official-history-unify-v1/<timestamp>/
|
||||
```
|
||||
|
||||
This backup is the sole basis for "restore exactly from backup" later. It makes the whole process **reversible**: at any time you can turn off the switch and precisely flip the official sessions you migrated in back to the `openai` drawer.
|
||||
|
||||
Remember these two words—**drawer** (a session just gets reclassified) and **backup** (a copy is always made before a change)—and everything that follows will be easy to understand.
|
||||
|
||||
---
|
||||
|
||||
## What happens when you enable it: step by step
|
||||
|
||||
### Step 1: Find the switch
|
||||
|
||||
```text
|
||||
Settings -> General -> Codex App Enhancements
|
||||
```
|
||||
|
||||
In the "Codex App Enhancements" block there are two rows of switches; the **second row** (the blue history icon) is the subject of this guide:
|
||||
|
||||
> **Unified Codex session history**
|
||||
|
||||
Below it is a line of description text (verbatim):
|
||||
|
||||
> When enabled, the official subscription runs under the shared "custom" provider id so official and third-party sessions appear in one history list, optionally migrating existing official sessions in (backed up first). When turning it off, the migrated sessions can be restored from backup. Note: resuming an old session across providers may fail because its encrypted_content reasoning can only be decrypted by the backend that created it.
|
||||
|
||||
> **Note**: this single line of description already previews three things—sessions will appear in one list, you can optionally migrate them in with an automatic backup, and resuming across providers "may fail." Here, "fail" means **you can't resume / can't generate a new turn**, not "the record is lost." This is exactly the core misunderstanding we'll dig into below.
|
||||
|
||||
### Step 2: Flip the switch from off to on -> a confirmation dialog pops up
|
||||
|
||||
The moment you flip the switch on, CC Switch **does not save immediately**; instead it first pops up a confirmation dialog. The dialog text reads as follows (verbatim):
|
||||
|
||||
- **Title**: Unified Codex session history
|
||||
- **Body**:
|
||||
|
||||
> When enabled, the official subscription and third-party providers share one session history list. Note: resuming an old session across providers may fail because its encrypted_content reasoning cannot be decrypted by another backend.
|
||||
>
|
||||
> You can also migrate your existing official session history into the shared list (originals are backed up to ~/.cc-switch/backups first and can be restored when you turn this off).
|
||||
|
||||
- **Checkbox**: Also migrate existing official session history
|
||||
- **Confirm button**: I understand, enable
|
||||
- **Cancel button**: Cancel
|
||||
|
||||
**This checkbox is unchecked by default.** This is an important fork in the road:
|
||||
|
||||
| Your choice | Effect | Where your data is right now |
|
||||
|---|---|---|
|
||||
| **Unchecked** (default) | Only switches the tag. **Only official sessions created after enabling** land in the `custom` shared drawer | Your official sessions from **before** enabling keep the `openai` tag, stay exactly where they were, still in `~/.codex/sessions/` |
|
||||
| **Checked** | In addition to switching the tag, also migrates your **existing official sessions** from the `openai` drawer into the `custom` drawer | After being **copied to backup**, the old sessions' tag is rewritten to `custom`; the original data is covered by the backup |
|
||||
|
||||
> **If you want "my earlier official sessions to appear in the unified list too," you must opt in by checking this box.** Otherwise you'll run into "scenario A" in the reference table below—the old sessions look "gone," when in fact they're just sitting in the original drawer.
|
||||
|
||||
Click "Cancel" or click outside the dialog: the switch flips straight back to off and nothing happens.
|
||||
Click "I understand, enable": the switch is saved as on, and CC Switch persists the configuration in the background (and runs the migration if you checked it).
|
||||
|
||||
### Step 3 (only if you checked migration): how migration runs + data safety
|
||||
|
||||
If you check "Also migrate existing official session history," CC Switch runs this procedure on your existing official sessions:
|
||||
|
||||
```text
|
||||
For each official (openai tag) session file:
|
||||
① First copy the original file untouched into the backup directory <- data now has its first safety net
|
||||
② Using "write a temp file -> replace the whole thing" atomic style,
|
||||
change only the model_provider in the session_meta line at the header
|
||||
from "openai" to "custom" <- not a single byte of the conversation body is touched
|
||||
③ Update the index database state_5.sqlite to switch the tag in the same transaction
|
||||
```
|
||||
|
||||
- **Backup location**: `~/.cc-switch/backups/codex-official-history-unify-v1/<timestamp>/`. Each migration produces one timestamped "generation directory," containing `jsonl/` (session copies), `state/` (index DB copy), and `meta.json` (recording which Codex directory this migration belongs to).
|
||||
- **What's changed**: only the value of the single field `model_provider`. Your conversation content, reasoning content, and all body text are **kept exactly as is**.
|
||||
- **What's deleted**: **nothing**. The backup is a "copy," the rewrite is an "atomic replacement of the same file," and at no point is any session or index deleted. The file is complete at every moment (either the old content or the new content, never empty or half-written).
|
||||
|
||||
After a successful migration, these existing official sessions show up in the unified list. **At this moment your data is**: ① the original copy in the backup directory; ② in the active file, only the classification tag changed, the content intact.
|
||||
|
||||
> **Note**: enabling and migration themselves **do not pop a success toast**. Migration runs as a side task on the backend during save; in the UI you'll only see the switch turn on. So "I didn't see a migration-success popup" is normal and does not mean failure.
|
||||
|
||||
---
|
||||
|
||||
## What happens when you disable it: step by step
|
||||
|
||||
### Step 1: Flip the switch from on to off -> probe for backups -> a confirmation dialog pops up
|
||||
|
||||
When disabling, CC Switch **first spends a moment probing whether there's a migration backup**, then pops up a confirmation dialog (so the disable dialog has a slight delay, which is normal). The text reads as follows (verbatim):
|
||||
|
||||
- **Title**: Turn off unified session history
|
||||
- **Body**:
|
||||
|
||||
> After turning this off, the official subscription and third-party providers return to separate history lists. Sessions created while it was on cannot be attributed to a provider, so they stay in the third-party history and the official subscription will not see them.
|
||||
|
||||
- **Checkbox** (shown conditionally): Restore the official sessions migrated at enable time back to the official history (exact restore from backup)
|
||||
- **Confirm button**: Turn off
|
||||
- **Cancel button**: Cancel
|
||||
|
||||
> **Key point**: the body says the official subscription **will not see them**—**won't see**, not **delete**. The new sessions you chatted during the unified period are still fully present in the `custom` drawer; after disabling, the official side simply won't see them.
|
||||
|
||||
**This restore checkbox is checked by default.** In other words, the default behavior is "restore the official sessions you migrated in back to the official history at the same time you disable." You only need to keep it checked and click "Turn off."
|
||||
|
||||
If the checkbox **doesn't appear**, the system has determined there's no backup that needs restoring (either you never checked migration, or no backup was found)—in that case your existing official sessions were never touched, and turning off the switch returns them to the `openai` drawer on their own.
|
||||
|
||||
### Step 2: How restore runs (precise flip-back per the backup ledger)
|
||||
|
||||
If you keep the box checked and click "Turn off," CC Switch's restore flow goes like this:
|
||||
|
||||
```text
|
||||
① First copy the current state once more into a separate restore-backup directory
|
||||
~/.cc-switch/backups/codex-official-history-unify-restore-v1/<timestamp>/
|
||||
(restore itself backs up first, so restore won't lose data either)
|
||||
② Comb through all migration backup generations, find the session ids "whose tag was originally openai," and assemble a "ledger"
|
||||
③ Only for sessions that are [both in the ledger AND currently still custom], change the tag back to "openai"
|
||||
```
|
||||
|
||||
Note the **dual condition** in step ③—it must be in the ledger (proving it really was migrated from the official side) AND currently still `custom` (showing you haven't manually changed it). Only when both conditions hold does it get flipped back. This guarantees the restore is both precise and free of collateral damage.
|
||||
|
||||
**At this moment your data is**: the migrated-back official sessions have their tag changed back to `openai` and reappear in the official list; meanwhile both the migration backup and the restore backup copies are still on disk.
|
||||
|
||||
### Step 3: Read the toast, confirm the result
|
||||
|
||||
Only the "disable + check restore" path pops a result toast. The toasts you may see (verbatim):
|
||||
|
||||
| Toast you see | Meaning |
|
||||
|---|---|
|
||||
| **Official session history restored from backup ({{files}} session files, {{rows}} index rows)** | Restore succeeded. `{{files}}` / `{{rows}}` show the actual numbers |
|
||||
| **No restorable migration backup for the current Codex directory** | Nothing to restore (**does not mean data is lost**, see scenario E in the reference table) |
|
||||
| **Unified session history was re-enabled; restore skipped** | You turned the switch back on while restore was queued, so the system deliberately abandoned the restore (see scenario F) |
|
||||
| **Failed to restore official session history, please try again** | The restore process errored; just retry, the data is not corrupted |
|
||||
| **Save failed, please try again** | The disable save itself failed; in this case **restore is never triggered** and the switch flips back to its original position |
|
||||
|
||||
> **A thoughtful safety design**: if the "disable the switch" save fails, CC Switch **never runs the restore**. Otherwise you'd end up in a torn state of "switch still on, but sessions flipped back to the openai bucket." When the save fails, the switch **automatically flips back to its original position**, so you won't be stuck in a fake state of "looks off but didn't actually save."
|
||||
|
||||
---
|
||||
|
||||
## "I feel like my sessions are gone?" symptom reference table
|
||||
|
||||
The six scenarios below are the situations where users most easily believe "sessions are gone." **The truth in every one is: the data is intact, it just moved drawers or is temporarily out of sight.** Use this table to locate your symptom first, then read the detailed explanation below.
|
||||
|
||||
| Scenario | What you see | The data truth | One-line fix |
|
||||
|---|---|---|---|
|
||||
| **A** Didn't check migration | Old official sessions not in the unified list | All present, still carry the `openai` tag | Re-enable and check migration, or turn off the switch |
|
||||
| **B** Cross-provider resume fails | Can't resume / errors out | Files intact, the ciphertext just can't be decrypted across backends | Resume on the original provider; to only read content, read the jsonl directly |
|
||||
| **C** Proxy takeover / injection refused | No migration and no restore | Migration was safely skipped, files untouched | Exit takeover -> restart and retry; or just turn off the switch |
|
||||
| **D** New sessions didn't return to official after restore | New sessions from the unified period aren't on the official side | They're in the `custom` drawer, untouched by design | Switch to a third-party provider to see them |
|
||||
| **E** Toast "no restorable backup" | Restore "failed" | Usually nothing was ever migrated, sessions are in the original drawer | Turn off the switch and the official sessions reappear automatically |
|
||||
| **F** Toast "switch was re-enabled, restore skipped" | Restore refused | Prevents a torn data state, nothing was changed | Fully turn off the switch first, then restore |
|
||||
|
||||
### Scenario A: You enabled the switch but didn't check migration -> old official sessions "disappear"
|
||||
|
||||
**Symptom**: you turned on the unified switch, but didn't check "Also migrate existing official session history" in the enable dialog (it's unchecked by default). After enabling, your earlier official sessions seem to be gone from the list.
|
||||
|
||||
**The truth**: 100% of your data is present, not a single line moved. The switch only takes effect on official sessions "created after enabling"; your official sessions from **before** enabling still carry the `openai` tag and sit untouched in `~/.codex/sessions/`. You're now on the `custom` drawer, so naturally you can't see the old sessions left in the `openai` drawer—that's the entire reason for the "apparent disappearance."
|
||||
|
||||
**What to do** (pick either):
|
||||
1. **Re-enable the switch and check "Also migrate existing official session history,"** which moves the old sessions to the `custom` drawer and they immediately appear in the unified list (automatic backup before the rewrite).
|
||||
2. **Or simply turn off the unified switch**, the official side runs on the `openai` drawer again, and the old sessions reappear right where they were.
|
||||
|
||||
### Scenario B: Cross-provider resume of an old session fails -> you think "this session is broken / gone"
|
||||
|
||||
**Symptom**: after unification, the list shows an old session chatted with "another provider." You switch to your current provider and click "Resume," but it errors out or can't connect.
|
||||
|
||||
**The truth**: the session file is intact; what's lost is not data, it's "cross-backend decryption ability." A Codex session stores an encrypted block of reasoning content `encrypted_content`, and **this ciphertext can only be decrypted by the backend that originally generated it**. Using provider B to resume a session generated by provider A means B can't decrypt A's ciphertext -> resume fails. This is **a design limitation of upstream Codex (by design)** and has nothing to do with whether CC Switch touched the file. The text content of the session is readable at any time.
|
||||
|
||||
> This is the **only "looks like a real problem" genuine exception** in this whole guide—but note: it just means **you can't resume (can't generate a new turn)**, and **the original file is still fully present**, the conversation text readable at any time.
|
||||
|
||||
**What to do**:
|
||||
- **Resume with "the provider that originally created this session,"** so it can decrypt normally and connect.
|
||||
- Just want to read the history without continuing? Read that session's `.jsonl` file directly (commands at the end).
|
||||
- Rule of thumb: **cross-provider is better suited to "starting a new session"; resume old sessions on their original provider whenever possible.**
|
||||
|
||||
### Scenario C: You enabled the switch and checked migration, but migration was silently skipped -> you think "migration lost the sessions"
|
||||
|
||||
**Symptom**: you enabled the switch and checked migration, but the old official sessions neither entered the unified list nor could be restored when you turned the switch off (or the restore checkbox didn't even appear in the disable dialog, see scenario E). You suspect migration lost the sessions during the process.
|
||||
|
||||
**The truth**: migration **never ran**, so it couldn't have lost anything—not a single character of your sessions was changed. CC Switch has a safety gate before migration: it checks whether Codex's live config (`~/.codex/config.toml`) is **actually** routed to the shared `custom` drawer right now, and only migrates if the routing truly went there. The following two situations are judged "not yet unified" (internal reason code `live_not_unified`), so CC Switch **deliberately skips the migration, preserves your switch and migration intent, and migrates later once the conditions are met**:
|
||||
|
||||
- **During proxy takeover**: CC Switch's proxy has taken over the live config, and the live config during takeover doesn't carry the unified routing marker.
|
||||
- **Injection refused**: your `config.toml` already has a manually specified `model_provider`, or there's already a differently-shaped `[model_providers.custom]` table (possibly with a third-party address). To avoid incorrectly routing official traffic to a third-party backend, CC Switch would rather not inject and not migrate.
|
||||
|
||||
Skipping migration = touching no session files. **No migration means nothing moved, so there's nothing to lose.** This is "safe deferral," not "failure with data loss."
|
||||
|
||||
**What to do**:
|
||||
- Exit proxy takeover -> **restart CC Switch**: on startup it automatically retries migration (your migration intent is preserved the whole time).
|
||||
- Check `~/.codex/config.toml`: if there's a conflicting route you wrote by hand, clean up the conflict before enabling the switch.
|
||||
- If you'd rather not bother: just turn off the switch, the official sessions still display normally on the `openai` drawer, completely intact.
|
||||
|
||||
### Scenario D: You turned off the switch and restored, but "the new sessions chatted during the unified period" didn't return to official -> you think "the new sessions are gone"
|
||||
|
||||
**Symptom**: during the unified period, you chatted a few more new sessions with the official account. Later you turned off the switch, checked restore, and after restoring you find those new sessions didn't return to the official drawer.
|
||||
|
||||
**The truth**: this is **intentional** design; the new sessions are perfectly fine in the `custom` drawer, visible and resumable. Restore is based on "the backup ledger from migration time"—**only sessions that were originally migrated in from the `openai` drawer** are recorded in the backup and get precisely flipped back to `openai`. The sessions you **created during the unified period** are in no backup ledger; and after unification both official and third-party use the `custom` tag, so **CC Switch can't tell whether a new session was chatted with the official account or a third-party**. To avoid wrongly stuffing third-party sessions into the official history, the product decision is: these new sessions all stay in the `custom` (third-party) history and are never moved automatically. The disable dialog's text says this explicitly too—"Sessions created while it was on cannot be attributed to a provider, so they stay in the third-party history."
|
||||
|
||||
**What to do**:
|
||||
- Switch to any third-party provider (the `custom` drawer) to see these sessions in the history list.
|
||||
- To read content, read the `.jsonl` directly; to resume, follow scenario B's rule (go back to the backend that originally generated it).
|
||||
- If you really want to manually return **one specific** session to official: there's currently no automatic button (deliberately omitted, to avoid misjudging the direction). Advanced users can, **after backing up** that file first, manually change `model_provider` in the `session_meta` of the first line of its `.jsonl` from `custom` back to `openai` (an advanced operation; always make a copy before editing).
|
||||
|
||||
### Scenario E: Restore toast "No restorable migration backup for the current Codex directory" -> you think "restore failed = data is gone"
|
||||
|
||||
**Symptom**: you checked restore when turning off the switch, and got the toast "No restorable migration backup for the current Codex directory." You panic: restore failed, is the data completely gone?
|
||||
|
||||
**The truth**: "nothing to restore" ≠ "data is lost." On the contrary, it's usually because **there was no migration that needed restoring**. Common reasons:
|
||||
|
||||
- **You never checked "migrate existing official sessions" in the first place**: with no migration, there's naturally no migration backup and no sessions to flip back. Your old official sessions have been in the `openai` drawer all along and reappear after you turn off the switch (same as scenario A). (In this case, the disable dialog may **not even show the restore checkbox**—because the system can't find any backup.)
|
||||
- **You've already restored once**: the session tags have all been flipped back to `openai`, so clicking again naturally finds "no targets still in custom to restore"—this is **idempotent protection, not failure**.
|
||||
- **You switched Codex directories**: restore only recognizes the backup ledger belonging to the **current** directory; switch directories and it can't find the old directory's ledger. Just switch the directory back.
|
||||
|
||||
In all three cases, no session was deleted.
|
||||
|
||||
**What to do**: use the end-of-guide commands to count the total session files in `~/.codex/sessions/` and confirm the files are all there; then check whether `~/.cc-switch/backups/` contains a `codex-official-history-unify-v1` directory—if even this directory is absent, you never triggered a migration and the sessions have been in their original drawer all along.
|
||||
|
||||
### Scenario F: Restore refused, toast "Unified session history was re-enabled; restore skipped"
|
||||
|
||||
**Symptom**: you turned off the switch -> checked restore -> but you were quick and immediately turned the switch back on, then saw the toast "Unified session history was re-enabled; restore skipped."
|
||||
|
||||
**The truth**: this is a safeguard against putting your data into a "torn" state, and again no sessions are lost. The restore action is "flip session tags from `custom` back to `openai`," but if the switch is on again at this moment, the live config is routing to `custom`—flipping history back to `openai` on one side while new sessions land in `custom` on the other would artificially tear sessions in two. So when CC Switch detects "the switch is on again," it **deliberately abandons this restore and changes nothing**. Sessions stay as they are, with no deletion or corruption.
|
||||
|
||||
**What to do**: to truly restore, **turn the switch off and keep it off** (don't immediately turn it back on), then do disable + check restore; to keep things unified, don't restore, and let the sessions stay in the `custom` shared drawer for normal use.
|
||||
|
||||
**The overriding principle: CC Switch's unify / migrate / restore only ever changes a single tag field in a session, and automatically backs up before every rewrite. It never deletes your conversations. Out of sight ≠ gone—look in the other drawer, or use the commands below to confirm with your own eyes.**
|
||||
|
||||
---
|
||||
|
||||
## Verify by hand: your session files are still on disk (the most important section)
|
||||
|
||||
No amount of text beats seeing it for yourself. Below are the **real paths** (taken from the CC Switch source) and how to view session files and backup directories on different systems. **The whole process is read-only and changes nothing; you're strongly encouraged to try it by hand.**
|
||||
|
||||
### The simplest way: open it directly in a file manager (no command line at all)
|
||||
|
||||
- **macOS (Finder)**: press `Cmd + Shift + G`, paste `~/.codex/sessions` and hit Enter to see a pile of `.jsonl` session files and their modification times; for the backup directory paste `~/.cc-switch/backups`.
|
||||
- **Windows (File Explorer)**: paste `%USERPROFILE%\.codex\sessions` into the address bar and hit Enter to see the session folders and the `.jsonl` files inside; for the backup directory paste `%USERPROFILE%\.cc-switch\backups`.
|
||||
|
||||
**As long as you can see a batch of `.jsonl` files here, that proves your session data is intact on disk.** The file count and modification times are more intuitive than any amount of text.
|
||||
|
||||
### Where exactly your session / history files live
|
||||
|
||||
| Content | Real path | Notes |
|
||||
|---|---|---|
|
||||
| **Session body (the core)** | `~/.codex/sessions/` (includes date-based subdirectories, recursive) | One `.jsonl` text file per session—**this is your conversation content** |
|
||||
| **Archived sessions** | `~/.codex/archived_sessions/` | Also `.jsonl` |
|
||||
| **Session index database** | `~/.codex/state_5.sqlite` | The `model_provider` column of the `threads` table is the "drawer tag"—**this is the actual classification source the resume list reads** |
|
||||
| **Migration backup** (auto-created when migration is enabled) | `~/.cc-switch/backups/codex-official-history-unify-v1/<timestamp>/` | Contains `jsonl/`, `state/`, `meta.json` |
|
||||
| **Restore backup** (auto-created when you restore) | `~/.cc-switch/backups/codex-official-history-unify-restore-v1/<timestamp>/` | A safety copy taken before restore |
|
||||
|
||||
> **Note**: if you've changed the Codex directory in CC Switch, or set `sqlite_home` in `config.toml`, replace `~/.codex` above with your actual directory. Below, `~` = your user home directory.
|
||||
|
||||
### macOS / Linux commands
|
||||
|
||||
**1. Count the total number of session files (this is the hard evidence of "nothing lost")**
|
||||
|
||||
```bash
|
||||
# Count the total number of session files -- as long as this number matches your expectation, the data is all there
|
||||
find ~/.codex/sessions ~/.codex/archived_sessions -name '*.jsonl' 2>/dev/null | wc -l
|
||||
|
||||
# Show the 10 most recently modified session files
|
||||
find ~/.codex/sessions -name '*.jsonl' 2>/dev/null -print0 \
|
||||
| xargs -0 ls -lt 2>/dev/null | head -10
|
||||
```
|
||||
|
||||
**2. (Auxiliary) See how many sessions are in each "drawer"**
|
||||
|
||||
```bash
|
||||
# Number of session files in the official drawer (openai)
|
||||
grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"openai"' ~/.codex/sessions 2>/dev/null | wc -l
|
||||
|
||||
# Number of session files in the unified drawer (custom)
|
||||
grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"custom"' ~/.codex/sessions 2>/dev/null | wc -l
|
||||
|
||||
# See the tag distribution at a glance
|
||||
grep -rhoE '"model_provider"[[:space:]]*:[[:space:]]*"[^"]*"' ~/.codex/sessions 2>/dev/null | sort | uniq -c
|
||||
```
|
||||
|
||||
> **Important note, don't let this step scare you**: **early versions of Codex did not write the `model_provider` field into the `.jsonl`**, so these old official sessions **can't be counted** by the grep above—but they're still classified as `openai` in the index database `state_5.sqlite` and still show up in the resume list. So **judge "nothing lost" by the total file count from step 1**—the per-drawer grep is only there to help you understand the classification, and counting fewer than the total file count is **completely normal** and never means "a batch was lost."
|
||||
|
||||
**3. (Advanced) Query the index database `state_5.sqlite`—the classification the resume list actually reads**
|
||||
|
||||
```bash
|
||||
# Requires sqlite3 to be installed; skip if you don't have it
|
||||
sqlite3 ~/.codex/state_5.sqlite \
|
||||
"SELECT COALESCE(model_provider,'<empty>'), COUNT(*) FROM threads GROUP BY 1;"
|
||||
```
|
||||
|
||||
> This `threads` table is the actual classification source Codex's resume list reads; the `openai` row count ≈ the number of sessions you can see in your official drawer. It may not match step 2's jsonl grep—the reason is exactly what's described above: "old sessions don't write the jsonl field, but they're still openai in the index database." A mismatch between the two is not an anomaly.
|
||||
|
||||
**4. Read the content of a specific session directly (confirm the conversation text is still there)**
|
||||
|
||||
```bash
|
||||
# Replace <filename> with one of the .jsonl paths listed by ls above
|
||||
python3 -m json.tool < "<filename>.jsonl" 2>/dev/null | head -50
|
||||
|
||||
# Or just open it in an editor (plain text)
|
||||
open -e "<filename>.jsonl" # macOS
|
||||
```
|
||||
|
||||
**5. Look at CC Switch's backup directory (proof that a copy was kept before migration / restore)**
|
||||
|
||||
```bash
|
||||
ls -la ~/.cc-switch/backups/codex-official-history-unify-v1/ 2>/dev/null
|
||||
ls -la ~/.cc-switch/backups/codex-official-history-unify-restore-v1/ 2>/dev/null
|
||||
```
|
||||
|
||||
### Windows commands (PowerShell)
|
||||
|
||||
The session directory is usually at `C:\Users\<your username>\.codex\`, and backups at `C:\Users\<your username>\.cc-switch\backups\`.
|
||||
|
||||
```powershell
|
||||
# 1. Total number of session files (hard evidence of "nothing lost")
|
||||
(Get-ChildItem "$env:USERPROFILE\.codex\sessions","$env:USERPROFILE\.codex\archived_sessions" -Recurse -Filter *.jsonl -ErrorAction SilentlyContinue).Count
|
||||
|
||||
# 2. The 10 most recently modified sessions
|
||||
Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
|
||||
Sort-Object LastWriteTime -Descending | Select-Object -First 10 FullName,LastWriteTime
|
||||
|
||||
# 3. (Auxiliary) How many session files in the official (openai) / unified (custom) drawers
|
||||
(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
|
||||
Select-String -Pattern 'model_provider"\s*:\s*"openai"' -List).Count
|
||||
(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
|
||||
Select-String -Pattern 'model_provider"\s*:\s*"custom"' -List).Count
|
||||
|
||||
# 4. Look at the backup directories
|
||||
Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-v1" -ErrorAction SilentlyContinue
|
||||
Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-restore-v1" -ErrorAction SilentlyContinue
|
||||
```
|
||||
|
||||
> Same reminder: the step-3 grep counting **fewer** than the total file count is normal (old sessions don't write that field); judge "nothing lost" by the **total file count** from step 1.
|
||||
|
||||
---
|
||||
|
||||
## Advanced mechanism appendix (for users who want to truly understand how it works)
|
||||
|
||||
### 1. The bucketing mechanism (the essence of the drawers)
|
||||
|
||||
Codex's resume / history list filters by the currently active `model_provider` id with **exact string matching**. The **first line** of a session's `.jsonl` file is a `type:"session_meta"` record whose `payload.model_provider` is the drawer that session belongs to (`grep -rl` counts a file as long as the tag appears once anywhere in it, so no line-by-line parsing is needed; sessions from old versions that didn't write the field can't be counted). What actually drives the resume list is the `threads.model_provider` column of the index database `state_5.sqlite`. When `config.toml` has no explicit `model_provider`, the official subscription falls into the built-in default id `openai`; all of CC Switch's third-party providers uniformly use `custom`.
|
||||
|
||||
### 2. What the switch does (injection, lives only in live)
|
||||
|
||||
When enabled, CC Switch injects the following into the official live `config.toml`:
|
||||
|
||||
```toml
|
||||
model_provider = "custom"
|
||||
|
||||
[model_providers.custom]
|
||||
name = "OpenAI"
|
||||
requires_openai_auth = true
|
||||
supports_websockets = true
|
||||
wire_api = "responses"
|
||||
```
|
||||
|
||||
Every field has a purpose: `requires_openai_auth = true` keeps authentication going through the ChatGPT login in `auth.json`, with the base_url defaulting back to the official Codex backend; `name = "OpenAI"` lets Codex's official feature gates (web search, remote compaction, etc.) keep matching; `supports_websockets = true` restores the capability that custom entries lose by default; `wire_api = "responses"` uses the official responses protocol. **The net effect is: authentication is unchanged, only the bucket name changed.**
|
||||
|
||||
**Key invariant: this injection can only exist in the live `config.toml`, and is never written into the database's stored configuration.** When you switch away from the official provider and write live back to the database, CC Switch strips this injection precisely (it strips only when the shape exactly matches the injected artifact; a third-party-customized `custom` table is kept as is). Precisely because of this, "turning off the switch + switching once" fully restores live, and the database always holds your original clean official configuration—this is the cornerstone of the whole switch's reversibility.
|
||||
|
||||
### 3. The two refusal gates for injection (corresponding to scenario C)
|
||||
|
||||
- `config.toml` already has an explicit `model_provider` -> don't override the user's route;
|
||||
- A differently-shaped `[model_providers.custom]` table already exists (possibly with a third-party `base_url`) -> refuse injection, otherwise ChatGPT OAuth traffic would be routed to the wrong backend.
|
||||
|
||||
When injection is refused, live is not unified, and the migration gate (checking whether live's `model_provider` equals `custom` after trim) judges `live_not_unified` -> skip migration, preserve intent, and do it later on the next startup retry. This is "safe deferral," not "failure with data loss."
|
||||
|
||||
### 4. The three session classes (which determine the migration / restore boundary)
|
||||
|
||||
- **Class A**: existing official sessions migrated in at enable time—the backup is the ledger, and they can be precisely restored back to `openai`;
|
||||
- **Class B**: created during the unified period—in no backup, and official / third-party can't be distinguished, so they're **never moved automatically** (stay `custom`);
|
||||
- **Class C**: pure third-party history from before enabling—never touched.
|
||||
|
||||
### 5. The safety of migration / restore (data is never truly deleted; where the guarantee comes from)
|
||||
|
||||
Four layers of design jointly guarantee that under **all paths, normal and abnormal**, the original session data is never truly deleted.
|
||||
|
||||
- **Only change the field, never the body**: migration / restore only switch the `model_provider` value in session metadata between `openai` and `custom`; conversation content, `response_item`, and `encrypted_content` are all kept exactly as is.
|
||||
- **Always copy a backup before a rewrite**: jsonl uses file copy, the state DB uses a full SQLite copy, both stored in a timestamped generation directory. Migration backups live in `codex-official-history-unify-v1/`, restore backups in the separate `codex-official-history-unify-restore-v1/`—the two are kept apart to keep the ledger clean.
|
||||
- **Only move, never delete + atomic writes**: all jsonl rewrites go through "temp file + whole-file replacement," and the state DB goes through a transactional `UPDATE`, with no deletion of any session or index at any point. The file is complete at every moment.
|
||||
- **Pessimistic skip + idempotent and retryable**: when buckets are inconsistent (`live_not_unified`), it would rather not migrate; a single process lock serializes migration and restore to avoid "startup retry / post-save background task / disable-time restore" concurrently rewriting the same batch of files in both directions; the completion marker is bound to the Codex directory and written conditionally to prevent missed migrations; restore uses the "in the ledger + currently still custom" dual condition to prevent wrong changes. Restore scans the union of all backup generations, so even after many switch cycles it can still restore early-migrated sessions; a repeated restore returns `nothing_to_restore`, which is idempotent protection rather than failure.
|
||||
|
||||
### 6. Cross-backend encrypted_content (corresponding to scenario B)
|
||||
|
||||
The reasoning ciphertext inside a session can only be decrypted by the backend that generated it; upstream Codex by design does not support cross-backend decryption. This is the root cause of "resume failure" and has nothing to do with file integrity—the session `.jsonl` sits fully on disk and `encrypted_content` is intact too. Switching back to the original provider to resume, or starting a new session, both work fine.
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
- [Keep Codex Remote Control and Official Plugins While Using Third-Party APIs: CC Switch Setup Guide](./codex-official-auth-preservation-guide-en.md)
|
||||
- [Using DeepSeek-Style Chat APIs in Codex: CC Switch Local Routing Guide](./codex-deepseek-routing-guide-en.md)
|
||||
- The "Codex App Enhancements" section in the CC Switch user manual
|
||||
|
||||
---
|
||||
|
||||
**One last word for you**: what you see as "sessions disappeared / resume failed" is essentially **the session being moved to another history list (drawer), or the other backend being unable to decrypt the old reasoning content**; the files always sit untouched in `~/.codex/sessions/` (and `state_5.sqlite`). Checking "restore from backup" when you turn off the switch precisely flips the official sessions you migrated in back to the official list; and even if you don't restore, both the original `.jsonl` files and the backup copies under `~/.cc-switch/backups/codex-official-history-unify-*/` are all still there—**the data is never truly lost.**
|
||||
@@ -0,0 +1,467 @@
|
||||
# Codex セッション履歴の統一: 機能紹介と利用ガイド(CC Switch)
|
||||
|
||||
> 対象バージョン: CC Switch v3.16.x 以降。本記事は現在のコードをもとに整理しており、コマンドとパスはご自身で検証できます。例示には匿名化したデータを使用しており、実際のセッション内容や API Key は含まれていません。
|
||||
|
||||
## この機能とは何か
|
||||
|
||||
「Codex セッション履歴を統一」は、CC Switch v3.16.x が Codex 向けに新しく追加したスイッチです。その場所は **設定 → 一般 → 「Codex アプリ拡張」グループ** の中にあります(「Codex アプリ拡張」はこのグループの見出しで、スイッチ自体は「Codex セッション履歴を統一」という名前です)。オンにすると、**公式サブスクリプション(ChatGPT ログイン / OpenAI API Key)のセッションが、CC Switch で管理するすべてのサードパーティプロバイダーのセッションと同じ履歴 / セッション再開リストに表示されます**——もう、互いに見えない 2 つのリストに分断されることはありません。
|
||||
|
||||
## どんな問題を解決するのか
|
||||
|
||||
Codex は「プロバイダーのラベル」(`model_provider` というフィールド)でセッションを分類しており、しかも **セッション再開 / 履歴リストには、現在アクティブなプロバイダーと同じラベルのセッションしか表示しません**。そのため、セッションは自然と 2 つの「引き出し」に分けられてしまいます。
|
||||
|
||||
- 公式サブスクリプションのセッションは、Codex 内蔵の **`openai`** ラベルに分類されます。
|
||||
- CC Switch が管理するすべてのサードパーティプロバイダーは、**`custom`** ラベルに分類されます。
|
||||
|
||||
2 つの引き出しは互いに見えません。**公式とサードパーティを頻繁に切り替えている** 場合、この分断に遭遇します——「さっき公式で話したセッションが、サードパーティに切り替えたら履歴リストから消えた」というように。実際にはなくなっておらず、別の引き出しに分けられただけです。この分断は、セッションが失われたと誤解させやすいうえに、すべてのセッションを 1 か所でまとめて振り返ったり再開したりするのにも不便です。
|
||||
|
||||
**このスイッチは、まさにこの分断を解消するためのものです**。公式サブスクリプションも `custom` ラベルで動作させることで、公式とサードパーティのセッションが同じリストに統合され、探すのも再開するのも 1 か所で済みます。
|
||||
|
||||
> ✅ **本記事全体を貫く重要な前提を、まず覚えておいてください**: この機能(統一 / 移行 / 復元)は **常にセッション記録内のあの分類ラベル `model_provider` 1 つだけを書き換え、しかも毎回書き換える前に自動で元ファイルをバックアップします**。あなたの会話を 1 文たりとも削除・消去・上書きすることはありません。ですので、本記事の後半で「あるセッションが見えなくなった」とあっても、そのほとんどは「別の引き出しに分けられた」だけであり、「データが消えた」わけではありません——本当に心配なときは、[症状対照表](#会話が消えた症状対照表) と [自分の目でファイルが残っていることを確認する](#自分の目で確認-セッションファイルはディスク上に残っている最重要セクション) を直接ご覧ください。
|
||||
|
||||
## 動作原理(一言版)
|
||||
|
||||
これを **2 つの引き出し + 自動バックアップ** と考えてください。
|
||||
|
||||
- デフォルトでは、公式セッションは `openai` の引き出しに、サードパーティのセッションは `custom` の引き出しにあり、互いに見えません。
|
||||
- スイッチは **公式も `custom` の引き出しを使うように** させ、2 つの引き出しを 1 つの共有リストに統合します。
|
||||
- **既存の公式の古いセッション** も一緒に共有の引き出しへ「移す」ことを選べます(この操作を **移行** と呼びます。任意で、能動的にチェックを入れる必要があります)。そして **いかなる移動の前にも、まずコピーをバックアップ** するので、プロセス全体が **可逆** です。
|
||||
- **認証はまったく影響を受けません**——公式サブスクリプションは引き続きあなたの ChatGPT ログインを使い、引き続き公式バックエンドを経由します。変わるのはセッションの分類ラベルだけです。
|
||||
|
||||
完全な仕組み(何が注入されるのか、なぜ可逆なのか、移行 / 復元がどうやってデータ消失を防ぐのか)は、後述の [コア・メンタルモデル](#コアメンタルモデル-2-つの引き出し--自動バックアップ) と巻末の [応用原理付録](#応用原理付録仕組みを本当に理解したい人向け) をご覧ください。
|
||||
|
||||
## 使い方(クイック)
|
||||
|
||||
1. **有効化**: 設定 → 一般 → Codex アプリ拡張 → 「Codex セッション履歴を統一」をオン → ダイアログで「既存の公式セッション履歴も移行する」にチェックを入れるか決める(**以前** の公式セッションも統一リストに合流させたいならチェックを入れる。今後だけ統一したいならチェックを入れない)→ 確定。詳しくは [有効化したとき何が起きるか](#有効化したとき何が起きるか-ステップ別解説) を参照。
|
||||
2. **無効化**: 同じスイッチをオフにする → ダイアログで「バックアップから正確に復元する」のチェックを保持(デフォルトでチェック済み)→ 確定すれば、移行した公式セッションを正確に公式リストへ戻せます。詳しくは [無効化したとき何が起きるか](#無効化したとき何が起きるか-ステップ別解説) を参照。
|
||||
3. **セッションが消えた気がする?** 慌てずに [症状対照表](#会話が消えた症状対照表) へ進んで症状から原因を特定し、[自分の目で確認](#自分の目で確認-セッションファイルはディスク上に残っている最重要セクション) セクションのコマンドで、ファイルがすべて残っていることを自分の目で確かめてください。
|
||||
|
||||
---
|
||||
|
||||
## コア・メンタルモデル: 2 つの引き出し + 自動バックアップ
|
||||
|
||||
この機能を理解するには、**引き出し** と **バックアップ** の 2 つだけ覚えれば十分です。
|
||||
|
||||
### 引き出し: Codex はどうやってセッションを分類するか
|
||||
|
||||
Codex セッションを 1 つ開くたびに、Codex はセッションファイルの先頭に `model_provider` というラベルを記録し、「このセッションはどのプロバイダーで話したか」を示します。Codex の **セッション再開 / 履歴リストは、現在アクティブなこのラベルで正確にフィルタリングされます**——「今あなたが使っているプロバイダー」と同じラベルのセッションだけが表示されます。
|
||||
|
||||
- 公式サブスクリプション(ChatGPT ログイン / OpenAI API Key)のセッションのラベルは、内蔵の **`openai`** です。
|
||||
- CC Switch が管理するすべてのサードパーティプロバイダーは、一律にラベル **`custom`** を使います。
|
||||
|
||||
そのためデフォルトでは、公式セッションとサードパーティセッションは生まれつき互いに見えません——2 つの異なる引き出しにあるからです。これは **Codex 自身の設計** であり、CC Switch が何かをなくしたわけではありません。
|
||||
|
||||
```text
|
||||
デフォルト状態(統一スイッチをオンにしていない):
|
||||
┌──────────────────────┐ ┌──────────────────────────────────┐
|
||||
│ openai の引き出し │ │ custom の引き出し │
|
||||
│ (公式セッション) │ │ (サードパーティのセッション) │
|
||||
└──────────────────────┘ └──────────────────────────────────┘
|
||||
▲ ▲
|
||||
公式のときは サードパーティのときは
|
||||
こちらだけ表示 こちらだけ表示
|
||||
|
||||
(2 つの引き出しは互いに見えない)
|
||||
```
|
||||
|
||||
**「Codex セッション履歴を統一」スイッチがすることは、公式サブスクリプションも `custom` ラベルで動作させ、2 つの引き出しを 1 つに統合することです**。その結果、公式セッションとサードパーティセッションが同じセッション再開リストに表示されます。注意してほしいのは、**認証は変わらない** ということです——あなたの公式サブスクリプションは引き続き ChatGPT ログインを使い、引き続き公式バックエンドを経由します。変わるのはセッションの「分類ラベル」が `openai` から `custom` になることだけです。
|
||||
|
||||
```text
|
||||
統一スイッチをオンにした後:
|
||||
┌────────────────────────────────────────────────┐
|
||||
│ custom 共有引き出し │
|
||||
│ 公式セッション + サードパーティのセッション │
|
||||
│ (同じ履歴 / 再開リストに表示される) │
|
||||
└────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### バックアップ: ラベルを変更する前に必ずコピーを取る
|
||||
|
||||
「引き出しの統合」では、一部の公式セッションのラベルを `openai` から `custom` に変更する必要があります(この操作を **移行** と呼び、これは **任意で、あなたが能動的にチェックを入れる必要があります**)。そして **どの書き換えの前にも、CC Switch はまず元ファイルをそのままコピー** して、ここに保存します。
|
||||
|
||||
```text
|
||||
~/.cc-switch/backups/codex-official-history-unify-v1/<時間スタンプ>/
|
||||
```
|
||||
|
||||
このバックアップが、後の「バックアップから正確に復元する」ための唯一の拠り所です。これによってプロセス全体が **可逆** になります——いつでもスイッチをオフにして、移行した公式セッションを正確に `openai` の引き出しへ戻せます。
|
||||
|
||||
この 2 つの言葉——**引き出し**(セッションは分類が変わるだけ)、**バックアップ**(変更前に必ずコピー)——を覚えておけば、以降の内容はすべて簡単に理解できます。
|
||||
|
||||
---
|
||||
|
||||
## 有効化したとき何が起きるか: ステップ別解説
|
||||
|
||||
### Step 1: スイッチを見つける
|
||||
|
||||
```text
|
||||
設定 → 一般 → Codex アプリ拡張
|
||||
```
|
||||
|
||||
「Codex アプリ拡張」のセクションには 2 行のスイッチがあり、**2 行目**(青い履歴アイコン)が本ガイドの主役です。
|
||||
|
||||
> **Codex セッション履歴を統一**
|
||||
|
||||
その下には説明文があります(逐語)。
|
||||
|
||||
> オンにすると、公式サブスクリプションも共有の custom プロバイダー ID で動作し、公式とサードパーティのセッションが同じ履歴リストに表示されます。既存の公式セッションの移行も選択できます(移行前に自動バックアップ)。オフにする際はバックアップから復元できます。注意:プロバイダーをまたいで古いセッションを再開すると、encrypted_content の推論内容を相手のバックエンドが復号できず、再開に失敗する場合があります。
|
||||
|
||||
> **注意**: この説明文には、すでに 3 つのことが予告されています——同じリストに表示される、移行を選べて自動バックアップされる、プロバイダーをまたいだ再開は「失敗する場合がある」。ここでの「再開に失敗する」は **続けられない、新しいターンを生成できない** という意味であり、「記録が消える」ではありません。これこそ、この後で重点的に解きほぐす核心的な誤解です。
|
||||
|
||||
### Step 2: スイッチをオフからオンに切り替える → 確認ダイアログが表示される
|
||||
|
||||
スイッチをオンに切り替えると、CC Switch は **すぐには保存せず**、まず確認ダイアログを表示します。ダイアログの文言は次のとおりです(逐語)。
|
||||
|
||||
- **タイトル**: Codex セッション履歴を統一
|
||||
- **本文**:
|
||||
|
||||
> オンにすると、公式サブスクリプションとサードパーティが同じセッション履歴リストを共有します。注意:プロバイダーをまたいで古いセッションを再開すると、encrypted_content を相手のバックエンドが復号できず失敗する場合があります。
|
||||
>
|
||||
> 既存の公式セッション履歴を共有リストへ移行することもできます(移行前に ~/.cc-switch/backups へ自動バックアップされ、オフにする際に復元を選択できます)。
|
||||
|
||||
- **チェックボックス**: 既存の公式セッション履歴も移行する
|
||||
- **確認ボタン**: 理解しました、オンにする
|
||||
- **キャンセルボタン**: キャンセル
|
||||
|
||||
**このチェックボックスはデフォルトでオフです。** これは重要な分岐点です。
|
||||
|
||||
| あなたの選択 | 効果 | この時点でデータはどこにあるか |
|
||||
|---|---|---|
|
||||
| **チェックしない**(デフォルト) | ラベルを切り替えるだけ。**オンにした後に新規作成された公式セッションだけ** が `custom` の共有引き出しに入る | あなたが **オンにする前** の公式の古いセッションは、ラベルが `openai` のまま、その場で動かず、引き続き `~/.codex/sessions/` にある |
|
||||
| **チェックする** | ラベルの切り替えに加えて、**既存の公式の古いセッション** も `openai` の引き出しから `custom` の引き出しへ移行する | 古いセッションは **コピーしてバックアップ** された後、ラベルが `custom` に書き換えられる。元データはバックアップで保護される |
|
||||
|
||||
> **「以前の公式セッションも統一リストに表示したい」なら、必ずこのチェックボックスを能動的にオンにしてください。** さもないと、下の対照表の「シナリオ A」に遭遇します——古いセッションが「消えた」ように見えますが、実際は元の引き出しに残っているだけです。
|
||||
|
||||
「キャンセル」を押すか、ダイアログの外側をクリックすると、スイッチはそのままオフ状態に戻り、何も起きません。
|
||||
「理解しました、オンにする」を押すと、スイッチはオンとして保存され、CC Switch はバックグラウンドで設定をディスクに書き込みます(移行にチェックを入れていれば、移行を実行します)。
|
||||
|
||||
### Step 3(移行にチェックを入れた場合のみ): 移行はどう実行されるか + データの安全性
|
||||
|
||||
「既存の公式セッション履歴も移行する」にチェックを入れた場合、CC Switch はあなたの公式の古いセッションに対して、次の一連の流れを実行します。
|
||||
|
||||
```text
|
||||
公式(openai ラベル)の各セッションファイルについて:
|
||||
① まず元ファイルをそのままバックアップディレクトリへコピー ← データの一次保険ができる
|
||||
② 「一時ファイルに書く → まるごと置換」という原子的な方法で、
|
||||
先頭行 session_meta 内の model_provider を
|
||||
"openai" から "custom" へ変更するだけ ← 会話本文は 1 バイトも触らない
|
||||
③ インデックス DB state_5.sqlite も同じトランザクション内でラベルを変更
|
||||
```
|
||||
|
||||
- **バックアップの場所**: `~/.cc-switch/backups/codex-official-history-unify-v1/<時間スタンプ>/`。移行のたびに、タイムスタンプ付きの「世代ディレクトリ」を生成し、その中に `jsonl/`(セッションのコピー)、`state/`(インデックス DB のコピー)、`meta.json`(この移行がどの Codex ディレクトリに属するかの記録)が含まれます。
|
||||
- **変更するもの**: `model_provider` というフィールドの値だけ。あなたの会話内容、推論内容、すべての本文は **そのまま保持** されます。
|
||||
- **削除するもの**: **何も削除しません**。バックアップは「コピー」、書き換えは「同一ファイルの原子的な置換」であり、全工程でセッションやインデックスを削除する操作は一切ありません。ファイルはいかなる時点でも完全です(古い内容か新しい内容かのどちらかであり、空や中途半端になることは決してありません)。
|
||||
|
||||
移行が成功すると、これらの公式の古いセッションが統一リストに表示されます。**この時点でのあなたのデータ**: ① 元のコピーがバックアップディレクトリにある。② アクティブファイルは分類ラベルが変わっただけで、内容は無傷。
|
||||
|
||||
> **注意**: 有効化と移行そのものは **成功通知を表示しません**。移行は保存時にバックエンドが付随的に実行するもので、UI 上ではスイッチがオン状態になったのが見えるだけです。ですので「移行成功のダイアログが見えなかった」のは正常であり、失敗を意味しません。
|
||||
|
||||
---
|
||||
|
||||
## 無効化したとき何が起きるか: ステップ別解説
|
||||
|
||||
### Step 1: スイッチをオンからオフに切り替える → バックアップを探索 → 確認ダイアログが表示される
|
||||
|
||||
無効化のとき、CC Switch はまず **一瞬かけて移行バックアップの有無を探索** し、それから確認ダイアログを表示します(そのため無効化のダイアログは少しだけ遅延しますが、これは正常です)。文言は次のとおりです(逐語)。
|
||||
|
||||
- **タイトル**: セッション履歴の統一をオフにする
|
||||
- **本文**:
|
||||
|
||||
> オフにすると、公式サブスクリプションとサードパーティはそれぞれ独立した履歴リストに戻ります。オン期間中に作成されたセッションは提供元を判別できないため、サードパーティの履歴に残り、公式サブスクリプションからは見えなくなります。
|
||||
|
||||
- **チェックボックス**(条件付き表示): オンにした際に移行した公式セッションを公式履歴へ復元する(バックアップから正確に復元)
|
||||
- **確認ボタン**: オフにする
|
||||
- **キャンセルボタン**: キャンセル
|
||||
|
||||
> **ポイント**: 本文が言っているのは「公式サブスクリプションからは **見えなくなる**」——**見えなくなる** であり、**削除される** ではありません。オン期間中に新たに話したセッションは、引き続き `custom` の引き出しに完全な形で残っており、オフにした後で公式側から見えなくなるだけです。
|
||||
|
||||
**この復元チェックボックスはデフォルトでオンです。** つまりデフォルトの動作は「オフにすると同時に、移行した公式セッションを公式履歴へ正確に復元する」です。チェックを保持したまま「オフにする」を押すだけで構いません。
|
||||
|
||||
チェックボックスが **表示されない** 場合は、復元が必要なバックアップがないとシステムが判断したことを意味します(移行に一度もチェックを入れていない、またはバックアップを探索できない)——この場合、あなたの公式の古いセッションは一度も変更されていないので、スイッチをオフにすれば自然と `openai` の引き出しに戻ります。
|
||||
|
||||
### Step 2: 復元はどう実行されるか(バックアップ台帳に従って正確に戻す)
|
||||
|
||||
チェックを保持して「オフにする」を押すと、CC Switch の復元フローは次のようになります。
|
||||
|
||||
```text
|
||||
① まず現在の状態を独立した復元バックアップディレクトリへもう一度コピー
|
||||
~/.cc-switch/backups/codex-official-history-unify-restore-v1/<時間スタンプ>/
|
||||
(復元自体もまずバックアップするので、復元でもデータは失われない)
|
||||
② すべての移行バックアップ世代を走査し、「当初のラベルが openai」のセッション id を集めて「台帳」を作る
|
||||
③ 【台帳に含まれ、かつ現在もまだ custom】のセッションだけ、ラベルを "openai" に戻す
|
||||
```
|
||||
|
||||
③ のステップの **二重条件** に注意してください——台帳に含まれていること(当初確かに公式から移行されたものだと証明できる)に加えて、現在もまだ `custom` であること(あなたが手動で変更していないことを示す)。両方の条件を満たして初めて戻します。これにより、復元は正確であり、かつ誤って手を加えることもありません。
|
||||
|
||||
**この時点でのあなたのデータ**: 戻された公式セッションはラベルが `openai` に変わり、再び公式リストに表示されます。同時に、移行バックアップと復元バックアップの 2 つのコピーがどちらもディスク上に残っています。
|
||||
|
||||
### Step 3: 通知を見て、結果を確認する
|
||||
|
||||
「オフにする + 復元にチェック」というパスだけが結果通知を表示します。表示され得る通知(逐語)。
|
||||
|
||||
| 表示される通知 | 意味 |
|
||||
|---|---|
|
||||
| **バックアップから公式セッション履歴を復元しました(セッションファイル {{files}} 件、インデックス {{rows}} 行)** | 復元成功。`{{files}}` / `{{rows}}` の部分には実際の数字が表示される |
|
||||
| **現在の Codex ディレクトリに復元可能な移行バックアップはありません** | 復元できる内容がない(**データが消えたわけではない**。対照表シナリオ E を参照) |
|
||||
| **統一セッション履歴が再度有効化されたため、復元をスキップしました** | 復元のキュー待ち中にスイッチを再びオンにしたため、システムが復元を自発的に取りやめた(対照表シナリオ F を参照) |
|
||||
| **公式セッション履歴の復元に失敗しました。もう一度お試しください** | 復元の途中でエラー。もう一度試せばよく、データは破壊されていない |
|
||||
| **保存に失敗しました。もう一度お試しください** | オフにするステップの保存そのものが失敗。この場合 **復元は決して起動されず**、スイッチは元の位置に戻る |
|
||||
|
||||
> **気の利いた安全設計**: 「スイッチをオフにする」ステップの保存が失敗した場合、CC Switch は **復元を決して実行しません**。さもないと「スイッチはまだオン、しかしセッションは `openai` バケットに戻された」という矛盾状態が生じてしまいます。保存失敗時、スイッチは **自動で元の位置に戻る** ので、「オフに見えるのに実は保存されていない」という偽の状態に取り残されることはありません。
|
||||
|
||||
---
|
||||
|
||||
## 「会話が消えた?」症状対照表
|
||||
|
||||
以下の 6 つのシナリオは、ユーザーが最も「セッションが消えた」と誤解しやすいケースです。**どれも真相は: データは無傷で、引き出しが変わったか一時的に見えないだけ。** まずこの表で症状から原因を特定し、その後で下の詳細説明を読んでください。
|
||||
|
||||
| シナリオ | あなたが見るもの | データの真相 | 一言での解決法 |
|
||||
|---|---|---|---|
|
||||
| **A** 移行にチェックなし | 公式の古いセッションが統一リストにない | すべて存在、`openai` ラベルのまま | 移行にチェックを入れて再度オンにする、またはスイッチをオフにする |
|
||||
| **B** プロバイダーをまたいだ再開が失敗 | 続けられない / エラー | ファイルは無傷、暗号文がバックエンドをまたいで復号できないだけ | 元のプロバイダーで再開する。内容だけ見るなら jsonl を直接読む |
|
||||
| **C** プロキシ接管 / 注入が拒否 | 移行も復元もされない | 移行が安全にスキップされ、ファイルは未変更 | 接管を終了 → 再起動して再試行。またはスイッチを直接オフにする |
|
||||
| **D** 復元後、新セッションが公式に戻らない | オン期間中の新セッションが公式にない | `custom` の引き出しにある、設計上動かさない | サードパーティプロバイダーに切り替えれば見える |
|
||||
| **E** 「復元可能なバックアップなし」と通知 | 復元が「失敗」 | 通常はそもそも移行していない、セッションは元の引き出しにある | スイッチをオフにすれば公式セッションが自動で再表示 |
|
||||
| **F** 「スイッチが再度有効化、復元スキップ」と通知 | 復元が拒否 | データの矛盾を防止、何も変更していない | まずスイッチを完全にオフにしてから復元する |
|
||||
|
||||
### シナリオ A: スイッチをオンにしたが移行にチェックを入れなかった → 公式の古いセッションが「消えた」
|
||||
|
||||
**現象**: 統一スイッチをオンにしたが、有効化ダイアログの「既存の公式セッション履歴も移行する」にチェックを入れなかった(デフォルトでチェックなし)。オンにした後で見ると、以前の公式の古いセッションがすべてリストにないように見える。
|
||||
|
||||
**真相**: データは 100% すべて存在し、1 行も動いていません。スイッチは「オンにした後に新規作成された」公式セッションにのみ効きます。あなたが **オンにする前** の公式の古いセッションはラベルが `openai` のままで、そっくりそのまま `~/.codex/sessions/` に横たわっています。今あなたがアクティブにしているのは `custom` の引き出しなので、`openai` の引き出しに残った古いセッションが見えないのは当然です——これが「消えたように見える」理由のすべてです。
|
||||
|
||||
**どうするか**(いずれか):
|
||||
1. **スイッチを再度オンにするときに「既存の公式セッション履歴も移行する」にチェックを入れ**、古いセッションを `custom` の引き出しへ移せば、すぐに統一リストに表示されます(書き換え前に自動バックアップ)。
|
||||
2. **または単に統一スイッチをオフにする** と、公式は再び `openai` の引き出しで動作し、古いセッションがその場で再表示されます。
|
||||
|
||||
### シナリオ B: プロバイダーをまたいで古いセッションを再開して失敗 → 「このセッションが壊れた / 消えた」と思う
|
||||
|
||||
**現象**: 統一した後、リストに「別のプロバイダー」で話した古いセッションが見える。今のプロバイダーに切り替えて「再開」を押すと、エラーになったり繋がらなかったりする。
|
||||
|
||||
**真相**: セッションファイルは完全に無傷で、失われたのはデータではなく「バックエンドをまたいだ復号能力」です。Codex セッションには暗号化された推論内容 `encrypted_content` が保存されており、**この暗号文は、それを生成したバックエンドだけが復号できます**。B プロバイダーで A プロバイダーが生成したセッションを再開しようとすると、B は A の暗号文を解けない → 再開失敗。これは **上流の Codex の設計上の制約(by design)** であり、CC Switch がファイルに手を加えたかどうかとは無関係です。セッション内の文字内容はいつでも読めます。
|
||||
|
||||
> これは本記事全体で **唯一「本当に問題が起きたように見える」実在の例外** です——ただし注意してください: これは **再開できない(新しいターンを生成できない)** だけであり、**元ファイルは依然として完全に存在し**、会話の文字はいつでも読めます。
|
||||
|
||||
**どうするか**:
|
||||
- **「このセッションを最初に作成したプロバイダー」で再開すれば**、正常に復号でき、繋がります。
|
||||
- 履歴の内容だけ見たくて、続ける必要がない場合は、そのセッションの `.jsonl` ファイルを直接読んでください(巻末にコマンドあり)。
|
||||
- 経験則: **プロバイダーをまたぐ場合は「新規セッションを始める」のが向いており、古いセッションはできるだけ元のプロバイダーで再開してください。**
|
||||
|
||||
### シナリオ C: スイッチをオンにし移行にもチェックを入れたが、移行が静かにスキップされた → 「移行がセッションをなくした」と思う
|
||||
|
||||
**現象**: オンにして移行にチェックを入れたのに、公式の古いセッションは統一リストに入らず、スイッチをオフにして復元しようとしても「復元できるものがない」と通知される(または無効化ダイアログに復元チェックボックスがそもそも現れない。シナリオ E を参照)。あなたは、移行の過程でセッションをなくしたのではと疑います。
|
||||
|
||||
**真相**: 移行はそもそも **実行されていない** ので、なくすことも不可能です——あなたのセッションは 1 文字も変更されていません。CC Switch には移行前に安全ゲートがあります: Codex の live 設定(`~/.codex/config.toml`)が、この時点で **本当に** 共有の `custom` 引き出しへルーティングされているかを確認し、本当にルーティングされている場合だけ移行します。以下の 2 つのケースでは「まだ統一されていない」と判定され(内部の理由コード `live_not_unified`)、**移行を自発的にスキップし、あなたのスイッチと移行の意思は保持し、条件が満たされてから移行します**。
|
||||
|
||||
- **プロキシ接管中**: CC Switch のプロキシが live 設定を接管しており、接管中の live には統一ルーティングのマークが付いていません。
|
||||
- **注入が拒否された**: あなたの `config.toml` にすでに手動指定の `model_provider` があるか、形態の異なる `[model_providers.custom]` テーブルが既に存在する(サードパーティのアドレスが付いている可能性がある)。公式トラフィックを誤ってサードパーティバックエンドへルーティングするのを避けるため、CC Switch は注入も移行もしないことを選びます。
|
||||
|
||||
移行のスキップ = どのセッションファイルにも触れない。**移行していない=動かしていない、消えようがない。** これは「安全な先送り」であり、「失敗してデータが消えた」ではありません。
|
||||
|
||||
**どうするか**:
|
||||
- プロキシ接管を終了 → **CC Switch を再起動**: 起動時に自動で移行を再試行します(あなたの移行の意思はずっと保持されています)。
|
||||
- `~/.codex/config.toml` を確認: 手動で書いた競合するルーティングがあれば、競合を整理してからスイッチをオンにします。
|
||||
- どうしても手間をかけたくない場合は、スイッチをオフにすれば、公式セッションは引き続き `openai` の引き出しで正常に表示され、まったく無傷です。
|
||||
|
||||
### シナリオ D: スイッチをオフにして復元したが、「オン期間中に新たに話したセッション」が公式に戻らない → 「新セッションが消えた」と思う
|
||||
|
||||
**現象**: 統一をオンにしている間、公式でさらにいくつかの新セッションを話した。後でスイッチをオフにし、復元にチェックを入れた。復元が終わると、その数本の新セッションが公式の引き出しに戻っていない。
|
||||
|
||||
**真相**: これは **意図的な** 設計で、新セッションはちゃんと `custom` の引き出しにあり、見えるし続けられます。復元の拠り所は「移行時のバックアップ台帳」です——**当初 `openai` の引き出しから移行されてきたセッションだけ** がバックアップに記録されており、正確に `openai` へ戻されます。あなたが **オン期間中に新規作成した** セッションはどのバックアップ台帳にもありません。しかも統一後は公式もサードパーティも `custom` ラベルを使うので、**CC Switch はこの新セッションが公式で話したものかサードパーティで話したものか判別できません**。サードパーティのセッションを公式履歴に誤って押し込まないため、プロダクトの決定として、これらの新セッションは一律に `custom`(サードパーティ)の履歴に残し、決して自動で動かしません。無効化ダイアログの文言もこれを明示しています——「オン期間中に作成されたセッションは提供元を判別できないため、サードパーティの履歴に残ります」。
|
||||
|
||||
**どうするか**:
|
||||
- 任意のサードパーティプロバイダー(`custom` の引き出し)に切り替えれば、履歴リストでこれらのセッションが見えます。
|
||||
- 内容を見たいなら `.jsonl` を直接読み、再開したいならシナリオ B のルール(それを生成した元のバックエンドに戻る)に従ってください。
|
||||
- もし **ある 1 本** を手動で公式に戻したい場合: 現在は自動ボタンはありません(方向を誤判定するのを避けるため、あえて作っていません)。上級ユーザーは、そのファイルを **先にバックアップ** したうえで、`.jsonl` の 1 行目 `session_meta` 内の `model_provider` を `custom` から `openai` に手動で戻せます(上級操作です。変更前に必ずコピーを取ってください)。
|
||||
|
||||
### シナリオ E: 復元時に「現在の Codex ディレクトリに復元可能な移行バックアップはありません」と通知 → 「復元失敗 = データが消えた」と思う
|
||||
|
||||
**現象**: スイッチをオフにするときに復元にチェックを入れたら、「現在の Codex ディレクトリに復元可能な移行バックアップはありません」と通知が出た。あなたは慌てます: 復元すら失敗した、データは完全に消えたのでは?
|
||||
|
||||
**真相**: 「復元できるものがない」≠「データが消えた」。むしろ逆で、通常は **そもそも復元すべき移行が存在しない** からです。よくある原因:
|
||||
|
||||
- **当初「既存の公式セッションを移行する」にチェックを入れていない**: 移行していない以上、移行バックアップもなく、戻すべきセッションもありません。あなたの公式の古いセッションはずっと `openai` の引き出しにあり、スイッチをオフにすれば直接再表示されます(シナリオ A と同じ)。(この場合、無効化ダイアログは復元チェックボックスを **そもそも表示しない** こともあります——システムがバックアップを一切探索できないためです。)
|
||||
- **すでに一度復元済み**: セッションラベルはすべて `openai` に戻っており、もう一度押しても「まだ `custom` の対象がない」のは当然です——これは **冪等保護であり、失敗ではありません**。
|
||||
- **Codex ディレクトリを切り替えた**: 復元は **現在の** ディレクトリに属するバックアップ台帳しか認識しないので、ディレクトリを変えると旧ディレクトリの台帳が見つかりません。ディレクトリを戻せば解決します。
|
||||
|
||||
この 3 つのケースでは、どのセッションも削除されていません。
|
||||
|
||||
**どうするか**: 巻末のコマンドで `~/.codex/sessions/` 内のセッションファイル総数を数え、ファイルがすべて残っていることを確認してください。次に `~/.cc-switch/backups/` に `codex-official-history-unify-v1` ディレクトリがあるかを見てください——もしこのディレクトリすらなければ、あなたは一度も移行を起動しておらず、セッションはずっと元の引き出しにある、ということです。
|
||||
|
||||
### シナリオ F: 復元が拒否され、「統一セッション履歴が再度有効化されたため、復元をスキップしました」と通知
|
||||
|
||||
**現象**: スイッチをオフにする → 復元にチェック → 手が速くて、すぐにスイッチを再びオンにした。すると「統一セッション履歴が再度有効化されたため、復元をスキップしました」と通知が出た。
|
||||
|
||||
**真相**: これはデータを「矛盾」状態にしてしまうのを防ぐ防護であり、セッションは同じく消えていません。復元の動作は「セッションラベルを `custom` から `openai` へ戻す」ことですが、この時点でスイッチが再びオンになっていると、live 設定は `custom` へルーティングしています——一方で履歴を `openai` へ戻し、一方で新セッションを `custom` に落とせば、セッションが人為的に 2 つに引き裂かれてしまいます。そのため CC Switch は「スイッチが再びオンになった」のを検知すると、**この復元を自発的に取りやめ、何も変更しません**。セッションは現状を維持し、削除も破壊もありません。
|
||||
|
||||
**どうするか**: 本当に復元したいなら、**まずスイッチを安定してオフにし**(すぐにオンにし直さない)、それから「オフにする + 復元にチェック」を実行してください。統一を保ちたいなら、復元せず、セッションを `custom` の共有引き出しに残して通常どおり使ってください。
|
||||
|
||||
**大原則: CC Switch の統一 / 移行 / 復元は、全工程でセッションの 1 つのラベルフィールドだけを変更し、しかも毎回書き換える前に自動でバックアップします。あなたの会話を削除することはありません。見えない ≠ 消えた——別の引き出しを見るか、下のコマンドで自分の目で確かめてください。**
|
||||
|
||||
---
|
||||
|
||||
## 自分の目で確認: セッションファイルはディスク上に残っている(最重要セクション)
|
||||
|
||||
文字をいくら重ねるより、自分の目で見るのが一番です。以下に **実際のパス**(CC Switch のソースコードから取得)と、異なる OS でセッションファイル・バックアップディレクトリを見る方法を示します。**全工程は読み取りのみで変更なし。ぜひ一度ご自身で試してみてください。**
|
||||
|
||||
### 最も簡単な方法: ファイルマネージャーで直接開く(コマンドライン完全不要)
|
||||
|
||||
- **macOS(Finder)**: `Cmd + Shift + G` を押して `~/.codex/sessions` を貼り付けて Enter すれば、たくさんの `.jsonl` セッションファイルとその更新時刻が見えます。バックアップディレクトリは `~/.cc-switch/backups` を貼り付けます。
|
||||
- **Windows(エクスプローラー)**: アドレスバーに `%USERPROFILE%\.codex\sessions` を貼り付けて Enter すれば、セッションフォルダとその中の `.jsonl` が見えます。バックアップディレクトリは `%USERPROFILE%\.cc-switch\backups` を貼り付けます。
|
||||
|
||||
**ここで一連の `.jsonl` ファイルが見えれば、それがセッションデータが無傷でディスク上にある証拠です。** ファイル数や更新時刻は、どんな文章よりも直感的です。
|
||||
|
||||
### あなたのセッション / 履歴ファイルはどこにあるのか
|
||||
|
||||
| 内容 | 実際のパス | 説明 |
|
||||
|---|---|---|
|
||||
| **セッション本文(コア)** | `~/.codex/sessions/`(日付別サブディレクトリを含む、再帰的) | セッション 1 つにつき 1 つの `.jsonl` テキストファイル。**これがあなたの会話内容** |
|
||||
| **アーカイブ済みセッション** | `~/.codex/archived_sessions/` | 同じく `.jsonl` |
|
||||
| **セッションインデックス DB** | `~/.codex/state_5.sqlite` | `threads` テーブルの `model_provider` 列が「引き出しラベル」。**これこそ、セッション再開リストが実際に読み取る分類のソース** |
|
||||
| **移行バックアップ**(移行をオンにすると自動生成) | `~/.cc-switch/backups/codex-official-history-unify-v1/<時間スタンプ>/` | `jsonl/`、`state/`、`meta.json` を含む |
|
||||
| **復元バックアップ**(復元を押すと自動生成) | `~/.cc-switch/backups/codex-official-history-unify-restore-v1/<時間スタンプ>/` | 復元前の安全なコピー |
|
||||
|
||||
> **注意**: CC Switch で Codex ディレクトリを変更した場合や、`config.toml` で `sqlite_home` を設定している場合は、上記の `~/.codex` をあなたの実際のディレクトリに置き換えてください。以下の `~` = あなたのユーザーホームディレクトリ。
|
||||
|
||||
### macOS / Linux コマンド
|
||||
|
||||
**1. セッションファイル総数を数える(これこそ「消えていない」確固たる証拠)**
|
||||
|
||||
```bash
|
||||
# セッションファイルの総数を数える —— この数が想定どおりなら、データはすべて残っている
|
||||
find ~/.codex/sessions ~/.codex/archived_sessions -name '*.jsonl' 2>/dev/null | wc -l
|
||||
|
||||
# 最近更新されたセッションファイル上位 10 件を見る
|
||||
find ~/.codex/sessions -name '*.jsonl' 2>/dev/null -print0 \
|
||||
| xargs -0 ls -lt 2>/dev/null | head -10
|
||||
```
|
||||
|
||||
**2. (補助)各「引き出し」にそれぞれ何個のセッションがあるか見る**
|
||||
|
||||
```bash
|
||||
# 公式の引き出し(openai)のセッションファイル数
|
||||
grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"openai"' ~/.codex/sessions 2>/dev/null | wc -l
|
||||
|
||||
# 統一の引き出し(custom)のセッションファイル数
|
||||
grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"custom"' ~/.codex/sessions 2>/dev/null | wc -l
|
||||
|
||||
# 各ラベルの分布をひと目で確認
|
||||
grep -rhoE '"model_provider"[[:space:]]*:[[:space:]]*"[^"]*"' ~/.codex/sessions 2>/dev/null | sort | uniq -c
|
||||
```
|
||||
|
||||
> **重要なヒント、このステップに驚かないでください**: **初期バージョンの Codex は `.jsonl` に `model_provider` フィールドを書き込みません**。これらの古い公式セッションは上記の grep では **数えられません** が、インデックス DB `state_5.sqlite` では依然として `openai` に分類されており、セッション再開リストではちゃんと見えます。ですので **「セッションが消えていない」かの判断はステップ 1 のファイル総数を基準にしてください**——バケット別 grep は分類を理解する補助に過ぎず、数えた結果がファイル総数より少ないのは **まったく正常** であり、決して「ひとまとまり消えた」ことを意味しません。
|
||||
|
||||
**3. (応用)インデックス DB `state_5.sqlite` を見る——セッション再開リストが実際に読む分類**
|
||||
|
||||
```bash
|
||||
# sqlite3 がインストール済みであること;未インストールならスキップ可
|
||||
sqlite3 ~/.codex/state_5.sqlite \
|
||||
"SELECT COALESCE(model_provider,'<空>'), COUNT(*) FROM threads GROUP BY 1;"
|
||||
```
|
||||
|
||||
> この `threads` テーブルこそ、Codex のセッション再開リストが実際に読み取る分類のソースであり、`openai` の行数 ≈ あなたの公式の引き出しで見えるセッション数です。ステップ 2 の jsonl grep とは数が合わないことがあります——その理由は、上述の「古いセッションは jsonl フィールドを書き込まないが、インデックス DB では依然として openai」だからです。両者が合わないのは異常ではありません。
|
||||
|
||||
**4. あるセッションの内容を直接読む(会話の文字が残っていることを確認)**
|
||||
|
||||
```bash
|
||||
# <ファイル名> を、上の ls で表示された .jsonl のパスに置き換える
|
||||
python3 -m json.tool < "<ファイル名>.jsonl" 2>/dev/null | head -50
|
||||
|
||||
# またはエディタで直接開いて見る(プレーンテキスト)
|
||||
open -e "<ファイル名>.jsonl" # macOS
|
||||
```
|
||||
|
||||
**5. CC Switch のバックアップディレクトリを見る(移行 / 復元の前に必ずコピーを残した証拠)**
|
||||
|
||||
```bash
|
||||
ls -la ~/.cc-switch/backups/codex-official-history-unify-v1/ 2>/dev/null
|
||||
ls -la ~/.cc-switch/backups/codex-official-history-unify-restore-v1/ 2>/dev/null
|
||||
```
|
||||
|
||||
### Windows コマンド(PowerShell)
|
||||
|
||||
セッションディレクトリは通常 `C:\Users\<あなたのユーザー名>\.codex\` にあり、バックアップは `C:\Users\<あなたのユーザー名>\.cc-switch\backups\` にあります。
|
||||
|
||||
```powershell
|
||||
# 1. セッションファイルの総数(「消えていない」ことの動かぬ証拠)
|
||||
(Get-ChildItem "$env:USERPROFILE\.codex\sessions","$env:USERPROFILE\.codex\archived_sessions" -Recurse -Filter *.jsonl -ErrorAction SilentlyContinue).Count
|
||||
|
||||
# 2. 最近更新されたセッション上位 10 件
|
||||
Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
|
||||
Sort-Object LastWriteTime -Descending | Select-Object -First 10 FullName,LastWriteTime
|
||||
|
||||
# 3. (補助)公式(openai) / 統一(custom) の引き出しにそれぞれ何件のセッションファイルがあるか
|
||||
(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
|
||||
Select-String -Pattern 'model_provider"\s*:\s*"openai"' -List).Count
|
||||
(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
|
||||
Select-String -Pattern 'model_provider"\s*:\s*"custom"' -List).Count
|
||||
|
||||
# 4. バックアップディレクトリを見る
|
||||
Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-v1" -ErrorAction SilentlyContinue
|
||||
Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-restore-v1" -ErrorAction SilentlyContinue
|
||||
```
|
||||
|
||||
> 同じく注意: ステップ 3 の grep の数がファイル総数より **少なくなる** のは正常です(古いセッションはこのフィールドを書き込まないため)。「セッションが消えていない」の判断は、ステップ 1 の **ファイル総数** を基準にしてください。
|
||||
|
||||
---
|
||||
|
||||
## 応用原理付録(仕組みを本当に理解したい人向け)
|
||||
|
||||
### 1. バケット分け機構(引き出しの本質)
|
||||
|
||||
Codex のセッション再開 / 履歴リストは、現在アクティブな `model_provider` id で **厳密な文字列フィルタリング** を行います。セッションファイル `.jsonl` の **1 行目** は `type:"session_meta"` のレコードで、その `payload.model_provider` がそのセッションの属する引き出しです(`grep -rl` はファイル内にそのラベルが 1 回でも出現すればそのファイルをカウントするので、行ごとに解析する必要はありません。旧バージョンでこのフィールドを書き込んでいないセッションは数えられません)。セッション再開リストを実際に駆動するのはインデックス DB `state_5.sqlite` の `threads.model_provider` 列です。公式サブスクリプションは `config.toml` に明示的な `model_provider` がないとき、内蔵のデフォルト id `openai` に入ります。CC Switch のすべてのサードパーティプロバイダーは一律に `custom` を使います。
|
||||
|
||||
### 2. スイッチがすること(注入、live にのみ存在)
|
||||
|
||||
オンにすると、CC Switch は公式 live `config.toml` に次の内容を注入します。
|
||||
|
||||
```toml
|
||||
model_provider = "custom"
|
||||
|
||||
[model_providers.custom]
|
||||
name = "OpenAI"
|
||||
requires_openai_auth = true
|
||||
supports_websockets = true
|
||||
wire_api = "responses"
|
||||
```
|
||||
|
||||
各フィールドには役割があります。`requires_openai_auth = true` は認証を引き続き `auth.json` 内の ChatGPT ログインで行わせ、base_url 未指定時は公式 Codex バックエンドへフォールバックさせます。`name = "OpenAI"` は Codex の公式機能ゲート(web search、リモート圧縮など)を引き続きヒットさせます。`supports_websockets = true` は custom エントリでデフォルトに失われる能力を補います。`wire_api = "responses"` は公式の responses プロトコルを使います。**正味の効果は: 認証は変わらず、バケット名が変わるだけ。**
|
||||
|
||||
**重要な不変条件: この注入は live `config.toml` にのみ存在でき、決してデータベースの保存設定には書き込まれません。** 公式プロバイダーから切り替えて離れ、live をデータベースへ書き戻すとき、CC Switch はこの注入を正確に剥離します(形態が注入物と完全に一致するときだけ剥離し、サードパーティがカスタムした `custom` テーブルはそのまま保持します)。だからこそ「スイッチをオフにする + 一度切り替える」だけで live を完全に復元でき、データベースには常にあなた本来のクリーンな公式設定が保たれます——これがスイッチ全体の可逆性の礎です。
|
||||
|
||||
### 3. 注入の 2 つの拒否ゲート(シナリオ C に対応)
|
||||
|
||||
- `config.toml` に明示的な `model_provider` がすでにある → ユーザーのルーティングを上書きしない。
|
||||
- 形態の異なる `[model_providers.custom]` テーブルがすでに存在する(サードパーティの `base_url` が付いている可能性がある)→ 注入を拒否、さもないと ChatGPT OAuth トラフィックを誤ったバックエンドへルーティングしてしまう。
|
||||
|
||||
注入を拒否したとき live は統一されず、移行ゲート(live の `model_provider` が trim 後に `custom` と等しいかを確認)が `live_not_unified` と判定 → 移行をスキップし、意思を保持し、次回起動の再試行時に行います。これは「安全な先送り」であり、「失敗してデータが消えた」ではありません。
|
||||
|
||||
### 4. セッションの三分類(移行 / 復元の境界を決める)
|
||||
|
||||
- **A 類**: オン時に移行した既存の公式セッション——バックアップが台帳であり、正確に `openai` へ復元可能。
|
||||
- **B 類**: オン期間中に新規作成——どのバックアップにもなく、公式 / サードパーティを判別不能、**決して自動で動かさない**(`custom` に残す)。
|
||||
- **C 類**: オン前の純粋なサードパーティ履歴——絶対に触れない。
|
||||
|
||||
### 5. 移行 / 復元の安全性(データが本当に削除されることはない、その保証はどこから来るか)
|
||||
|
||||
4 層の設計が共同で保証します: **正常・異常のあらゆるパス** において、元のセッションデータが本当に削除されることはありません。
|
||||
|
||||
- **フィールドだけ変更、本文には触れない**: 移行 / 復元はセッションメタデータ内の `model_provider` の値を `openai` と `custom` の間で切り替えるだけで、会話内容、`response_item`、`encrypted_content` はすべてそのまま保持します。
|
||||
- **書き換え前に必ずコピーをバックアップ**: jsonl はファイルコピー、state DB は SQLite の完全なコピーで、タイムスタンプ付きの世代ディレクトリに保存します。移行バックアップは `codex-official-history-unify-v1/` に、復元バックアップは独立した `codex-official-history-unify-restore-v1/` にあり、台帳を純粋に保つため両者は分けられています。
|
||||
- **移すだけ削除しない + 原子書き込み**: すべての jsonl 書き換えは「一時ファイル + 全体置換」を経由し、state DB はトランザクション化された `UPDATE` を経由し、全工程でセッションやインデックスを削除する操作は一切ありません。ファイルはいかなる時点でも完全です。
|
||||
- **悲観的スキップ + 冪等で再試行可能**: バケットが不一致のとき(`live_not_unified`)は移行しないことを選びます。一つのプロセスロックが移行と復元を直列化し、「起動時の再試行 / 保存後のバックグラウンドタスク / 無効化時の復元」が同じ一群のファイルを並行して双方向に書き換えるのを防ぎます。完了マークは Codex ディレクトリに紐づけて条件付きで書き込み、移行漏れを防ぎます。復元は「台帳にある + 現在もまだ custom」の二重条件を使い、誤変更を防ぎます。復元スキャンはすべてのバックアップ世代の和集合を取り、何度もスイッチを切り替えた後でも初期に移行したセッションを復元できます。重複した復元は `nothing_to_restore` を返しますが、これは冪等保護であり失敗ではありません。
|
||||
|
||||
### 6. バックエンドをまたいだ encrypted_content(シナリオ B に対応)
|
||||
|
||||
セッション内の推論暗号文は、それを生成したバックエンドだけが復号でき、上流の Codex は by design でバックエンドをまたいだ復号をサポートしません。これが「再開失敗」の根本原因であり、ファイルの完全性とは無関係です——セッション `.jsonl` は完全にディスク上に横たわり、`encrypted_content` も無傷です。元のプロバイダーに戻して再開するか、新規セッションを始めれば、どちらも正常です。
|
||||
|
||||
---
|
||||
|
||||
## 参考リンク
|
||||
|
||||
- [サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する: CC Switch 設定ガイド](./codex-official-auth-preservation-guide-ja.md)
|
||||
- [Codex で DeepSeek などの Chat 形式 API を使う: CC Switch ローカルルーティングガイド](./codex-deepseek-routing-guide-ja.md)
|
||||
- CC Switch ユーザーマニュアル内の「Codex アプリ拡張」関連の章
|
||||
|
||||
---
|
||||
|
||||
**最後に一言**: あなたが見た「セッションが消えた / 再開失敗」は、本質的には **セッションが別の履歴リスト(引き出し)に移されたか、相手のバックエンドが古い推論内容を復号できない** ことであり、ファイルは常にそっくりそのまま `~/.codex/sessions/`(および `state_5.sqlite`)に横たわっています。スイッチをオフにするとき「バックアップから復元する」にチェックを入れれば、移行した公式セッションを正確に公式リストへ戻せます。たとえ復元しなくても、元の `.jsonl` ファイルと `~/.cc-switch/backups/codex-official-history-unify-*/` 配下のバックアップコピーはどちらも残っています——**データが本当に失われることは決してありません。**
|
||||
@@ -0,0 +1,467 @@
|
||||
# 统一 Codex 会话历史:功能介绍与使用攻略(CC Switch)
|
||||
|
||||
> 适用版本:CC Switch v3.16.x 及以上。本文根据当前代码整理,命令与路径均可亲手验证;示例使用去敏数据,不包含真实会话内容或 API Key。
|
||||
|
||||
## 这个功能是什么
|
||||
|
||||
「统一 Codex 会话历史」是 CC Switch v3.16.x 为 Codex 新增的一个开关。它的位置在 **设置 → 通用 → 「Codex 应用增强」分组**里("Codex 应用增强"是这个分组的标题,开关本身叫"统一 Codex 会话历史")。开启后,**官方订阅(ChatGPT 登录 / OpenAI API Key)的会话,会和 CC Switch 管理的所有第三方供应商会话,出现在同一个历史 / 续聊列表里**——不再被分隔在两个互相看不见的列表中。
|
||||
|
||||
## 它解决什么问题
|
||||
|
||||
Codex 自己按"供应商标签"(一个叫 `model_provider` 的字段)给会话分类,而且**续聊 / 历史列表只显示和你当前激活的供应商同标签的会话**。于是会话天然被分进两个"抽屉":
|
||||
|
||||
- 官方订阅的会话,归在 Codex 内建的 **`openai`** 标签下;
|
||||
- CC Switch 管理的所有第三方供应商,归在 **`custom`** 标签下。
|
||||
|
||||
两个抽屉互相看不见。如果你**经常在官方与第三方之间切换**,就会遇到这种割裂:"刚才用官方聊的会话,切到第三方后在历史列表里找不到了"——它其实没丢,只是被分到了另一个抽屉。这种割裂既容易让人误以为会话丢失,也不方便把所有会话放在一处统一回顾、续聊。
|
||||
|
||||
**这个开关就是为了消除这种割裂**:让官方订阅也以 `custom` 标签运行,于是官方与第三方会话合并进同一个列表,找起来、续起来都在一处。
|
||||
|
||||
> ✅ **一个贯穿全文的重要前提,请先记住**:这个功能(统一 / 迁移 / 还原)**全程只改写会话记录里那一个归类标签 `model_provider`,而且每次改写前都会自动把原文件备份一份**。它不会删除、清空或覆盖你的任何一句对话。所以本文后面若提到"某些会话看不到了",几乎都是"被分到了另一个抽屉",而不是"数据没了"——真担心时,直接看 [症状对照表](#我感觉会话丢了症状对照表) 与 [亲手验证文件还在](#亲手验证你的会话文件还在硬盘上最重要的一节)。
|
||||
|
||||
## 工作原理(一句话版)
|
||||
|
||||
把它想成 **两个抽屉 + 自动备份**:
|
||||
|
||||
- 默认时,官方会话在 `openai` 抽屉、第三方会话在 `custom` 抽屉,互不可见;
|
||||
- 开关让**官方也改用 `custom` 抽屉**,于是两个抽屉合并成一个共享列表;
|
||||
- 你可以选择把**现有的官方老会话**也一并"搬"进共享抽屉(这一步叫**迁移**,可选、需主动勾选),而**任何搬动前都会先复制一份备份**,所以整个过程**可逆**;
|
||||
- **认证完全不受影响**——官方订阅照常用你的 ChatGPT 登录、照常走官方后端,变的只是会话的归类标签。
|
||||
|
||||
完整机制(注入了什么、为什么可逆、迁移/还原如何保证不丢数据)见下文 [核心心智模型](#核心心智模型两个抽屉--自动备份) 与文末 [进阶原理附录](#进阶原理附录给想真正搞懂机制的用户)。
|
||||
|
||||
## 如何使用(速览)
|
||||
|
||||
1. **开启**:设置 → 通用 → Codex 应用增强 → 打开「统一 Codex 会话历史」→ 在弹窗里决定是否勾选"同时迁入现有官方会话历史"(想让**以前**的官方会话也并进统一列表,就勾上;只想从现在起统一,就不勾)→ 确认。详见 [开启时会发生什么](#开启时会发生什么分步说明)。
|
||||
2. **关闭**:关掉同一开关 → 弹窗里保持勾选"按备份精确还原"(默认就勾着)→ 确认,即可把当初迁入的官方会话精确翻回官方列表。详见 [关闭时会发生什么](#关闭时会发生什么分步说明)。
|
||||
3. **感觉会话丢了?** 别慌,跳到 [症状对照表](#我感觉会话丢了症状对照表) 按症状定位,并用 [亲手验证](#亲手验证你的会话文件还在硬盘上最重要的一节) 一节的命令亲眼确认文件都在。
|
||||
|
||||
---
|
||||
|
||||
## 核心心智模型:两个抽屉 + 自动备份
|
||||
|
||||
要理解这个功能,你只需要记住两件事:**抽屉**和**备份**。
|
||||
|
||||
### 抽屉:Codex 怎么给会话分类
|
||||
|
||||
你每开一个 Codex 会话,Codex 会在会话文件头部记一个标签 `model_provider`,标记"这条会话是用哪个供应商聊的"。Codex 的**续聊 / 历史列表是按当前激活的这个标签精确过滤的**——只显示和"你现在这个供应商"同标签的会话。
|
||||
|
||||
- 官方订阅(ChatGPT 登录 / OpenAI API Key)的会话,标签是内建的 **`openai`**。
|
||||
- CC Switch 管理的所有第三方供应商,统一用标签 **`custom`**。
|
||||
|
||||
所以默认情况下,官方会话和第三方会话天生互相看不见——它们在两个不同的抽屉里。这是 **Codex 自身的设计**,不是 CC Switch 弄丢了什么。
|
||||
|
||||
```text
|
||||
默认状态(没开统一开关):
|
||||
|
||||
┌─────────────────┐ ┌─────────────────┐
|
||||
│ openai 抽屉 │ │ custom 抽屉 │
|
||||
│ (官方订阅会话) │ │ (第三方供应商会话)│
|
||||
└─────────────────┘ └─────────────────┘
|
||||
▲ ▲
|
||||
用官方时只看到这边 用第三方时只看到这边
|
||||
(两个抽屉互相看不见)
|
||||
```
|
||||
|
||||
**「统一 Codex 会话历史」开关做的事,就是让官方订阅也以 `custom` 标签运行,把两个抽屉合并成一个**,于是官方会话和第三方会话出现在同一个续聊列表里。注意:**认证没变**——你的官方订阅照常用你的 ChatGPT 登录、照常走官方后端,只是会话的"归类标签"从 `openai` 变成了 `custom`。
|
||||
|
||||
```text
|
||||
开启统一开关后:
|
||||
|
||||
┌─────────────────────────────────────────┐
|
||||
│ custom 共享抽屉 │
|
||||
│ 官方订阅会话 + 第三方供应商会话 │
|
||||
│ (出现在同一个历史 / 续聊列表里) │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 备份:每次改标签前都先复制一份
|
||||
|
||||
"合并抽屉"需要把一部分官方会话的标签从 `openai` 改成 `custom`(这一步叫**迁移**,且是**可选的、需要你主动勾选**)。而**任何一次改写之前,CC Switch 都会先把原文件原封不动地复制一份**到这里:
|
||||
|
||||
```text
|
||||
~/.cc-switch/backups/codex-official-history-unify-v1/<时间戳>/
|
||||
```
|
||||
|
||||
这份备份,就是日后"按备份精确还原"的唯一依据。它让整个过程变得**可逆**:你随时可以关掉开关,把当初迁进来的官方会话精确地翻回 `openai` 抽屉。
|
||||
|
||||
记住这两个词——**抽屉**(会话只是换了归类)、**备份**(改前必先复制)——后面所有内容你都能轻松理解。
|
||||
|
||||
---
|
||||
|
||||
## 开启时会发生什么:分步说明
|
||||
|
||||
### 第 1 步:找到开关
|
||||
|
||||
```text
|
||||
设置 → 通用 → Codex 应用增强
|
||||
```
|
||||
|
||||
在"Codex 应用增强"这个区块里有两行开关,**第二行**(蓝色历史图标)就是本攻略的主角:
|
||||
|
||||
> **统一 Codex 会话历史**
|
||||
|
||||
它下方有一段说明文字(逐字):
|
||||
|
||||
> 开启后,官方订阅将以共享的 custom 供应商标识运行,官方与第三方会话出现在同一历史列表中,并可选择把现有官方会话一并迁入(迁移前自动备份)。关闭开关时可按备份恢复迁入的会话。注意:跨供应商继续旧会话时,对方后端可能无法解密会话中的 encrypted_content 推理内容,导致继续失败
|
||||
|
||||
> **注意**:这一句说明里已经预告了三件事——会出现在同一列表、可选迁入并自动备份、跨供应商续聊"可能继续失败"。这里的"继续失败"指的是**续不上、生成不了新回合**,不是"记录丢失"。这正是后面要重点拆解的核心误解。
|
||||
|
||||
### 第 2 步:把开关从关拨到开 → 弹出确认窗
|
||||
|
||||
一旦你把开关拨到开,CC Switch **不会立刻保存**,而是先弹出一个确认窗口。窗口文案如下(逐字):
|
||||
|
||||
- **标题**:统一 Codex 会话历史
|
||||
- **正文**:
|
||||
|
||||
> 开启后,官方订阅与第三方将共用同一个会话历史列表。注意:跨供应商继续旧会话时,可能因对方后端无法解密 encrypted_content 推理内容而失败。
|
||||
>
|
||||
> 可选择同时把现有官方会话历史迁入共享列表(迁移前自动备份到 ~/.cc-switch/backups,关闭开关时可选择恢复)。
|
||||
|
||||
- **复选框**:同时迁入现有官方会话历史
|
||||
- **确认按钮**:我已了解,继续开启
|
||||
- **取消按钮**:取消
|
||||
|
||||
**这个复选框默认是不勾选的。** 这是一个重要的分岔点:
|
||||
|
||||
| 你的选择 | 效果 | 此刻你的数据在哪 |
|
||||
|---|---|---|
|
||||
| **不勾**(默认) | 只切换标识。**只有开启之后新建的官方会话**才会落进 `custom` 共享抽屉 | 你**开启前**的官方老会话,标签仍是 `openai`,原地未动,仍在 `~/.codex/sessions/` |
|
||||
| **勾上** | 除了切换标识,还会把**现有的官方老会话**也从 `openai` 抽屉迁进 `custom` 抽屉 | 老会话被**复制备份**后,标签改写为 `custom`;原始数据有备份兜底 |
|
||||
|
||||
> **如果你希望"以前的官方会话也出现在统一列表里",必须主动勾选这个复选框。** 否则你会遇到下面对照表里的"场景 A"——老会话看起来"不见了",其实只是留在原抽屉里。
|
||||
|
||||
点"取消"或点窗口外面:开关直接弹回关闭状态,什么都没发生。
|
||||
点"我已了解,继续开启":开关保存为开启,CC Switch 在后台落盘配置(如果勾了迁移,就执行迁移)。
|
||||
|
||||
### 第 3 步(仅当勾了迁移):迁移如何执行 + 数据安全
|
||||
|
||||
如果你勾了"同时迁入现有官方会话历史",CC Switch 会对你的官方老会话做这套流程:
|
||||
|
||||
```text
|
||||
对每个官方(openai 标签)会话文件:
|
||||
① 先把原文件原样复制一份到备份目录 ← 数据有了第一道保险
|
||||
② 用「写临时文件 → 整体替换」的原子方式,
|
||||
只把头部那行 session_meta 里的 model_provider
|
||||
从 "openai" 改成 "custom" ← 对话正文一个字节都不动
|
||||
③ 索引数据库 state_5.sqlite 同步在一个事务里把标签改过来
|
||||
```
|
||||
|
||||
- **备份位置**:`~/.cc-switch/backups/codex-official-history-unify-v1/<时间戳>/`,每次迁移生成一个带时间戳的"代际目录",内含 `jsonl/`(会话副本)、`state/`(索引库副本)、`meta.json`(记录这次迁移属于哪个 Codex 目录)。
|
||||
- **改的是什么**:只有 `model_provider` 这一个字段值。你的对话内容、推理内容、所有正文**原样保留**。
|
||||
- **删的是什么**:**什么都没删**。备份是"复制",改写是"原子替换同一个文件",全程没有任何删除会话或索引的动作。文件在任何时刻都是完整的(要么是旧内容、要么是新内容,绝不会是空或半截)。
|
||||
|
||||
迁移成功后,这些官方老会话就出现在统一列表里了。**此刻你的数据**:① 原始副本在备份目录;② 活动文件里只有归类标签变了,内容完好。
|
||||
|
||||
> **注意**:开启与迁移本身**不会弹成功提示**。迁移是后端在保存时顺带跑的,UI 上你只会看到开关变成了打开状态。所以"没看到迁移成功的弹窗"是正常的,不代表失败。
|
||||
|
||||
---
|
||||
|
||||
## 关闭时会发生什么:分步说明
|
||||
|
||||
### 第 1 步:把开关从开拨到关 → 探测备份 → 弹出确认窗
|
||||
|
||||
关闭时,CC Switch 会**先花一瞬间探测有没有迁移备份**,然后弹出确认窗口(所以关闭弹窗会有一点点延迟,属正常)。文案如下(逐字):
|
||||
|
||||
- **标题**:关闭统一会话历史
|
||||
- **正文**:
|
||||
|
||||
> 关闭后,官方订阅与第三方将恢复各自独立的会话历史列表。开启期间产生的会话因无法区分来源,将留在第三方历史中,官方订阅将看不到它们。
|
||||
|
||||
- **复选框**(条件显示):把开启时迁入的官方会话还原回官方历史(按备份精确还原)
|
||||
- **确认按钮**:关闭
|
||||
- **取消按钮**:取消
|
||||
|
||||
> **划重点**:正文说的是"官方订阅**将看不到它们**"——是**看不到**,不是**删除**。开启期间你新聊的会话仍然完整地在 `custom` 抽屉里,只是关闭后官方那一侧看不到而已。
|
||||
|
||||
**这个还原复选框默认是勾选的。** 也就是说,默认行为就是"关闭的同时,把当初迁入的官方会话精确还原回官方历史"。你只要保持勾选、点"关闭"即可。
|
||||
|
||||
如果复选框**没有出现**,说明系统判断当前没有需要还原的备份(要么你从没勾过迁移、要么探测不到备份)——这种情况下你的官方老会话从没被改动过,关掉开关它们自己就回到 `openai` 抽屉了。
|
||||
|
||||
### 第 2 步:还原如何执行(按备份账本精确翻回)
|
||||
|
||||
如果你保持勾选并点"关闭",CC Switch 的还原流程是这样的:
|
||||
|
||||
```text
|
||||
① 先把当前现场再复制一份到独立的还原备份目录
|
||||
~/.cc-switch/backups/codex-official-history-unify-restore-v1/<时间戳>/
|
||||
(还原本身也先备份,所以还原也不会丢数据)
|
||||
② 翻遍所有迁移备份代际,找出"当初标签是 openai"的会话 id,组成一份"账本"
|
||||
③ 只对【既在账本里、当前又仍是 custom】的会话,把标签改回 "openai"
|
||||
```
|
||||
|
||||
注意第 ③ 步的**双重条件**——既要在账本里(证明它当初确实是官方迁来的),又要当前仍是 `custom`(说明你没手动改过它)。两个条件都满足才翻回。这保证了还原既精确又不会误伤。
|
||||
|
||||
**此刻你的数据**:被迁回的官方会话标签改回 `openai`,重新出现在官方列表;同时迁移备份和还原备份两份副本都还在硬盘上。
|
||||
|
||||
### 第 3 步:看提示,确认结果
|
||||
|
||||
只有"关闭 + 勾选还原"这条路径会弹结果提示。可能看到的提示(逐字):
|
||||
|
||||
| 你看到的提示 | 含义 |
|
||||
|---|---|
|
||||
| **已按备份还原官方会话历史({{files}} 个会话文件、{{rows}} 条索引记录)** | 还原成功。`{{files}}` / `{{rows}}` 处会显示实际数字 |
|
||||
| **当前 Codex 目录没有可恢复的迁移备份** | 没有可还原的内容(**不等于数据丢了**,详见对照表场景 E) |
|
||||
| **统一会话历史开关已重新开启,已跳过还原** | 还原排队期间你又把开关打开了,系统主动放弃还原(详见对照表场景 F) |
|
||||
| **还原官方会话历史失败,请重试** | 还原过程报错,重试即可,数据未被破坏 |
|
||||
| **保存失败,请重试** | 关闭这一步保存本身就失败了;此时**绝不会触发还原**,开关弹回原位 |
|
||||
|
||||
> **一个贴心的安全设计**:如果"关闭开关"这一步保存失败,CC Switch **绝不会去执行还原**。否则就会出现"开关还开着、会话却被翻回 openai 桶"的撕裂状态。保存失败时开关会**自动弹回原来的位置**,你不会停留在一个"看起来已关、实则没保存"的假状态里。
|
||||
|
||||
---
|
||||
|
||||
## "我感觉会话丢了?"症状对照表
|
||||
|
||||
下面六个场景,是用户最容易误以为"会话丢了"的情形。**每一个的真相都是:数据完好,只是换了抽屉或暂时看不到。** 先用这张表按症状定位,再看下面的详细说明。
|
||||
|
||||
| 场景 | 你看到的 | 数据真相 | 一句话解法 |
|
||||
|---|---|---|---|
|
||||
| **A** 没勾迁移 | 官方老会话不在统一列表 | 全在,仍带 `openai` 标签 | 重开并勾迁移,或关开关 |
|
||||
| **B** 跨供应商续聊失败 | 续不上 / 报错 | 文件完好,只是密文跨后端解不开 | 回原供应商续;只看内容直接读 jsonl |
|
||||
| **C** 代理接管 / 注入被拒 | 没迁也没还原 | 迁移被安全跳过,文件没动 | 退出接管 → 重启重试;或直接关开关 |
|
||||
| **D** 还原后新会话没回官方 | 开启期间新会话不在官方 | 在 `custom` 抽屉,设计上不动 | 切第三方供应商即可见 |
|
||||
| **E** 提示"没有可恢复备份" | 还原"失败" | 通常压根没迁移过,会话在原抽屉 | 关开关官方会话自动复现 |
|
||||
| **F** 提示"开关已重新开启,跳过还原" | 还原被拒 | 防数据撕裂,啥也没改 | 先彻底关开关再还原 |
|
||||
|
||||
### 场景 A:开了开关但没勾迁移 → 官方老会话"不见了"
|
||||
|
||||
**现象**:你开了统一开关,但开启弹窗里那个"同时迁入现有官方会话历史"没勾(它默认就不勾)。开启后一看,以前的官方老会话好像都不在列表里了。
|
||||
|
||||
**真相**:数据 100% 都在,一行都没动。开关只对"开启之后新建"的官方会话生效,你**开启前**的官方老会话标签仍是 `openai`,原封不动地躺在 `~/.codex/sessions/` 里。你现在激活的是 `custom` 抽屉,自然看不到留在 `openai` 抽屉里的老会话——这就是"看起来消失"的全部原因。
|
||||
|
||||
**怎么办**(任选其一):
|
||||
1. **重新开启开关时勾上"同时迁入现有官方会话历史"**,把老会话换到 `custom` 抽屉,它们立刻出现在统一列表(改写前自动备份)。
|
||||
2. **或者干脆关掉统一开关**,官方重新以 `openai` 抽屉运行,老会话原地复现。
|
||||
|
||||
### 场景 B:跨供应商续聊旧会话失败 → 以为"这条会话坏了 / 没了"
|
||||
|
||||
**现象**:统一之后列表里能看到一条用"另一家供应商"聊出来的旧会话,你切到现在的供应商点"继续",结果报错或接不上。
|
||||
|
||||
**真相**:会话文件完好无损,丢的不是数据,是"跨后端解密能力"。Codex 会话里保存了一段加密的推理内容 `encrypted_content`,**这段密文只有当初生成它的那个后端能解密**。你用 B 供应商去续 A 供应商生成的会话,B 解不开 A 的密文 → 续聊失败。这是**上游 Codex 的设计限制(by design)**,与 CC Switch 是否动过文件无关。会话里的文字内容你随时能读到。
|
||||
|
||||
> 这是整篇攻略里**唯一一个"看起来真出了问题"的真实例外**——但请注意:它只是**无法续聊(生成不了新回合)**,**原始文件依然完整存在**,对话文字随时可读。
|
||||
|
||||
**怎么办**:
|
||||
- **用"当初创建这条会话的那个供应商"去续聊**,就能正常解密、接上。
|
||||
- 只想看历史内容、不必继续?直接读那条会话的 `.jsonl` 文件(文末有命令)。
|
||||
- 经验法则:**跨供应商更适合"开新会话",老会话尽量回原供应商续。**
|
||||
|
||||
### 场景 C:开了开关也勾了迁移,但迁移被静默跳过 → 以为"迁移把会话弄丢了"
|
||||
|
||||
**现象**:你开启并勾了迁移,但官方老会话既没进统一列表、关开关想还原也提示没东西可还原(或者关闭弹窗里压根没出现还原复选框,参见场景 E)。你怀疑迁移过程中把会话搞丢了。
|
||||
|
||||
**真相**:迁移根本**没执行**,所以也不可能弄丢——你的会话一个字都没被改。CC Switch 在迁移前有一道安全闸门:它会检查 Codex 的 live 配置(`~/.codex/config.toml`)此刻是否**真的**路由到了共享 `custom` 抽屉,只有真路由过去了才迁移。以下两种情况会判定"还没统一"(内部原因码 `live_not_unified`),于是**主动跳过迁移、保留你的开关和迁移意愿、等条件满足后再迁**:
|
||||
|
||||
- **代理接管期间**:CC Switch 的代理接管了 live 配置,接管期的 live 不带统一路由标记。
|
||||
- **注入被拒**:你的 `config.toml` 已有手工指定的 `model_provider`,或已存在一张形态不同的 `[model_providers.custom]` 表(可能带第三方地址)。为避免把官方流量错误路由到第三方后端,CC Switch 宁可不注入、不迁移。
|
||||
|
||||
跳过迁移 = 不碰任何会话文件。**没迁,等于没动,谈不上丢。** 这是"安全延后",不是"失败丢数据"。
|
||||
|
||||
**怎么办**:
|
||||
- 退出代理接管 → **重启 CC Switch**:启动时会自动重试迁移(你的迁移意愿一直保留着)。
|
||||
- 检查 `~/.codex/config.toml`:若有你手工写的冲突路由,整理掉冲突后再开开关。
|
||||
- 实在不想折腾:直接关开关,官方会话仍以 `openai` 抽屉正常显示,毫发无损。
|
||||
|
||||
### 场景 D:关了开关并还原,但"开启期间新聊的会话"没回官方 → 以为"新会话丢了"
|
||||
|
||||
**现象**:你开启统一期间,用官方又聊了几条新会话。后来关开关、勾了还原,还原完发现那几条新会话没回到官方抽屉。
|
||||
|
||||
**真相**:这是**有意为之**的设计,新会话好端端在 `custom` 抽屉里,能看见、能续。还原的依据是"迁移时的备份账本"——**只有当初从 `openai` 抽屉迁进来的会话**,备份里有据可查,才会被精确翻回 `openai`。你**开启期间新建**的会话不在任何备份账本里;而且统一之后官方和第三方都用 `custom` 标签,**CC Switch 无法分辨这条新会话到底是官方聊的还是第三方聊的**。为了不把第三方会话误塞进官方历史,产品决策是:这些新会话一律留在 `custom`(第三方)历史里,绝不自动搬动。关闭弹窗的文案也明示了这一点——"开启期间产生的会话因无法区分来源,将留在第三方历史中"。
|
||||
|
||||
**怎么办**:
|
||||
- 切到任意一个第三方供应商(`custom` 抽屉),就能在历史列表里看到这些会话。
|
||||
- 想看内容直接读 `.jsonl`;想续聊遵循场景 B 的规则(回到当初生成它的后端)。
|
||||
- 如果你确实想把**某一条**手动归回官方:目前没有自动按钮(刻意不做,避免误判方向)。进阶用户可在**先备份**该文件后,手动把它 `.jsonl` 第一行 `session_meta` 里的 `model_provider` 从 `custom` 改回 `openai`(属高阶操作,改前务必复制一份)。
|
||||
|
||||
### 场景 E:还原提示"当前 Codex 目录没有可恢复的迁移备份" → 以为"还原失败 = 数据没了"
|
||||
|
||||
**现象**:关开关时勾了还原,结果弹出提示"当前 Codex 目录没有可恢复的迁移备份"。你慌了:还原都失败了,是不是数据彻底没了?
|
||||
|
||||
**真相**:"没有可还原的东西"≠"数据丢了"。恰恰相反,通常是因为**根本没有需要还原的迁移**。常见原因:
|
||||
|
||||
- **你当初没勾过"迁入现有官方会话"**:既然没迁移,自然没有迁移备份、也没有需要翻回去的会话。你的官方老会话一直在 `openai` 抽屉,关开关后直接复现(同场景 A)。(这种情况下,关闭弹窗甚至可能**根本不显示还原复选框**——因为系统探测不到任何备份。)
|
||||
- **已经还原过一遍了**:会话标签已全部翻回 `openai`,再点一次自然"没有仍是 custom 的目标可还原"——这是**幂等保护,不是失败**。
|
||||
- **切换过 Codex 目录**:还原只认属于**当前**目录的备份账本,换了目录就找不到旧目录的账本,把目录切回去即可。
|
||||
|
||||
这三种情况下,没有任何会话被删除。
|
||||
|
||||
**怎么办**:用文末命令统计 `~/.codex/sessions/` 里的会话文件总数,确认文件都在;再看 `~/.cc-switch/backups/` 里有没有 `codex-official-history-unify-v1` 目录——如果连这个目录都没有,说明你从没触发过迁移,会话一直在原抽屉。
|
||||
|
||||
### 场景 F:还原被拒,提示"统一会话历史开关已重新开启,已跳过还原"
|
||||
|
||||
**现象**:关开关 → 勾还原 → 你手很快,紧接着又把开关重新打开了,然后看到提示"统一会话历史开关已重新开启,已跳过还原"。
|
||||
|
||||
**真相**:这是一道防护,防止把数据弄成"撕裂"状态,会话同样没丢。还原的动作是"把会话标签从 `custom` 翻回 `openai`",但如果此刻开关又开着,live 配置正路由到 `custom`——一边把历史翻回 `openai`、一边新会话往 `custom` 落,会话会被人为撕成两半。所以 CC Switch 检测到"开关又开了",**主动放弃这次还原、什么都不改**。会话维持现状,没有任何删除或破坏。
|
||||
|
||||
**怎么办**:想真正还原,就**先把开关稳定地关掉**(别再立刻打开),再执行关闭 + 勾还原;想保持统一,就别还原,让会话留在 `custom` 共享抽屉正常使用。
|
||||
|
||||
**总原则:CC Switch 的统一 / 迁移 / 还原全程只改会话的一个标签字段,并且每次改写前都自动备份。它不会删你的对话。看不见 ≠ 丢了——换个抽屉看,或用下面的命令亲眼确认。**
|
||||
|
||||
---
|
||||
|
||||
## 亲手验证:你的会话文件还在硬盘上(最重要的一节)
|
||||
|
||||
文字再多,不如亲眼看见。下面给出**真实路径**(取自 CC Switch 源码)和在不同系统下查看会话文件、备份目录的方法。**全程只读不改,强烈建议你亲手试一遍。**
|
||||
|
||||
### 最简单的方式:用文件管理器直接打开(完全不用命令行)
|
||||
|
||||
- **macOS(Finder)**:按 `Cmd + Shift + G`,粘贴 `~/.codex/sessions` 回车,就能看到一堆 `.jsonl` 会话文件和它们的修改时间;备份目录粘贴 `~/.cc-switch/backups`。
|
||||
- **Windows(文件资源管理器)**:在地址栏粘贴 `%USERPROFILE%\.codex\sessions` 回车,就能看到会话文件夹和里面的 `.jsonl`;备份目录粘贴 `%USERPROFILE%\.cc-switch\backups`。
|
||||
|
||||
**只要你能在这里看到一批 `.jsonl` 文件,就证明会话数据完好无损地在硬盘上。** 文件数量、修改时间,比任何文字都直观。
|
||||
|
||||
### 你的会话 / 历史文件到底在哪
|
||||
|
||||
| 内容 | 真实路径 | 说明 |
|
||||
|---|---|---|
|
||||
| **会话正文(核心)** | `~/.codex/sessions/`(含按日期分的子目录,递归) | 每个会话一个 `.jsonl` 文本文件,**这就是你的对话内容** |
|
||||
| **归档会话** | `~/.codex/archived_sessions/` | 同为 `.jsonl` |
|
||||
| **会话索引数据库** | `~/.codex/state_5.sqlite` | `threads` 表的 `model_provider` 列就是"抽屉标签",**它才是续聊列表真正读取的归类来源** |
|
||||
| **迁移备份**(开启迁移时自动产生) | `~/.cc-switch/backups/codex-official-history-unify-v1/<时间戳>/` | 内含 `jsonl/`、`state/`、`meta.json` |
|
||||
| **还原备份**(点还原时自动产生) | `~/.cc-switch/backups/codex-official-history-unify-restore-v1/<时间戳>/` | 还原前的安全副本 |
|
||||
|
||||
> **注意**:如果你在 CC Switch 里改过 Codex 目录,或在 `config.toml` 里设了 `sqlite_home`,请把上面的 `~/.codex` 换成你的实际目录。下文 `~` = 你的用户主目录。
|
||||
|
||||
### macOS / Linux 命令
|
||||
|
||||
**1. 数会话文件总数(这才是"没丢"的硬证据)**
|
||||
|
||||
```bash
|
||||
# 统计会话文件总数 —— 只要这个数字符合你的预期,数据就都在
|
||||
find ~/.codex/sessions ~/.codex/archived_sessions -name '*.jsonl' 2>/dev/null | wc -l
|
||||
|
||||
# 看最近修改的 10 个会话文件
|
||||
find ~/.codex/sessions -name '*.jsonl' 2>/dev/null -print0 \
|
||||
| xargs -0 ls -lt 2>/dev/null | head -10
|
||||
```
|
||||
|
||||
**2. (辅助)看每个"抽屉"各有多少会话**
|
||||
|
||||
```bash
|
||||
# 官方抽屉(openai)会话文件数
|
||||
grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"openai"' ~/.codex/sessions 2>/dev/null | wc -l
|
||||
|
||||
# 统一抽屉(custom)会话文件数
|
||||
grep -rlE '"model_provider"[[:space:]]*:[[:space:]]*"custom"' ~/.codex/sessions 2>/dev/null | wc -l
|
||||
|
||||
# 看各标签分布一目了然
|
||||
grep -rhoE '"model_provider"[[:space:]]*:[[:space:]]*"[^"]*"' ~/.codex/sessions 2>/dev/null | sort | uniq -c
|
||||
```
|
||||
|
||||
> **重要提示,别被这一步吓到**:**早期版本的 Codex 不在 `.jsonl` 里写 `model_provider` 字段**,这些旧官方会话用上面的 grep 是**数不到**的,但它们在索引库 `state_5.sqlite` 里仍然归类为 `openai`、续聊列表照样能看到。所以**判断"会话没丢"请以第 1 步的文件总数为准**——分桶 grep 只是帮你理解归类,数出来比文件总数少**完全正常**,绝不代表"丢了一批"。
|
||||
|
||||
**3. (进阶)查索引库 `state_5.sqlite`——续聊列表真正读的归类**
|
||||
|
||||
```bash
|
||||
# 需要已安装 sqlite3;没装可跳过
|
||||
sqlite3 ~/.codex/state_5.sqlite \
|
||||
"SELECT COALESCE(model_provider,'<空>'), COUNT(*) FROM threads GROUP BY 1;"
|
||||
```
|
||||
|
||||
> 这张 `threads` 表才是 Codex 续聊列表真正读取的归类来源,`openai` 行数 ≈ 你官方抽屉里能看到的会话数。它和第 2 步的 jsonl grep 可能对不上数——原因就是上面说的"旧会话不写 jsonl 字段,但索引库里仍是 openai"。两边对不上不是异常。
|
||||
|
||||
**4. 直接读某条会话的内容(确认对话文字还在)**
|
||||
|
||||
```bash
|
||||
# 把 <文件名> 换成上面 ls 列出的某个 .jsonl 路径
|
||||
python3 -m json.tool < "<文件名>.jsonl" 2>/dev/null | head -50
|
||||
|
||||
# 或者直接用编辑器打开看(纯文本)
|
||||
open -e "<文件名>.jsonl" # macOS
|
||||
```
|
||||
|
||||
**5. 看 CC Switch 的备份目录(证明迁移 / 还原前都留了副本)**
|
||||
|
||||
```bash
|
||||
ls -la ~/.cc-switch/backups/codex-official-history-unify-v1/ 2>/dev/null
|
||||
ls -la ~/.cc-switch/backups/codex-official-history-unify-restore-v1/ 2>/dev/null
|
||||
```
|
||||
|
||||
### Windows 命令(PowerShell)
|
||||
|
||||
会话目录通常在 `C:\Users\<你的用户名>\.codex\`,备份在 `C:\Users\<你的用户名>\.cc-switch\backups\`。
|
||||
|
||||
```powershell
|
||||
# 1. 会话文件总数("没丢"的硬证据)
|
||||
(Get-ChildItem "$env:USERPROFILE\.codex\sessions","$env:USERPROFILE\.codex\archived_sessions" -Recurse -Filter *.jsonl -ErrorAction SilentlyContinue).Count
|
||||
|
||||
# 2. 最近修改的 10 个会话
|
||||
Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
|
||||
Sort-Object LastWriteTime -Descending | Select-Object -First 10 FullName,LastWriteTime
|
||||
|
||||
# 3. (辅助)官方(openai) / 统一(custom) 抽屉各多少会话文件
|
||||
(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
|
||||
Select-String -Pattern 'model_provider"\s*:\s*"openai"' -List).Count
|
||||
(Get-ChildItem "$env:USERPROFILE\.codex\sessions" -Recurse -Filter *.jsonl |
|
||||
Select-String -Pattern 'model_provider"\s*:\s*"custom"' -List).Count
|
||||
|
||||
# 4. 看备份目录
|
||||
Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-v1" -ErrorAction SilentlyContinue
|
||||
Get-ChildItem "$env:USERPROFILE\.cc-switch\backups\codex-official-history-unify-restore-v1" -ErrorAction SilentlyContinue
|
||||
```
|
||||
|
||||
> 同样提醒:第 3 步的 grep 数会**少于**文件总数属正常(旧会话不写该字段),请以第 1 步的**文件总数**作为"会话没丢"的判断依据。
|
||||
|
||||
---
|
||||
|
||||
## 进阶原理附录(给想真正搞懂机制的用户)
|
||||
|
||||
### 1. 分桶机制(抽屉的本质)
|
||||
|
||||
Codex 的续聊 / 历史列表按当前激活的 `model_provider` id **精确字符串过滤**。会话文件 `.jsonl` 的**第一行**是一条 `type:"session_meta"` 记录,其 `payload.model_provider` 即该会话所属抽屉(`grep -rl` 只要文件里出现一次该标签就计入该文件,因此无需逐行解析;旧版本未写该字段的会话则数不到)。真正驱动续聊列表的是索引库 `state_5.sqlite` 的 `threads.model_provider` 列。官方订阅在 `config.toml` 没有显式 `model_provider` 时落进内建默认 id `openai`;CC Switch 的所有第三方供应商统一用 `custom`。
|
||||
|
||||
### 2. 开关做的事(注入,只活在 live)
|
||||
|
||||
开启后,CC Switch 对官方 live `config.toml` 注入如下内容:
|
||||
|
||||
```toml
|
||||
model_provider = "custom"
|
||||
|
||||
[model_providers.custom]
|
||||
name = "OpenAI"
|
||||
requires_openai_auth = true
|
||||
supports_websockets = true
|
||||
wire_api = "responses"
|
||||
```
|
||||
|
||||
每个字段都有作用:`requires_openai_auth = true` 让认证继续走 `auth.json` 里的 ChatGPT 登录、base_url 缺省回落官方 Codex 后端;`name = "OpenAI"` 让 Codex 的官方特性门控(web search、远程压缩等)继续命中;`supports_websockets = true` 补回 custom 条目默认丢失的能力;`wire_api = "responses"` 用官方 responses 协议。**净效果是:认证没变,只是桶名变了。**
|
||||
|
||||
**关键不变量:这段注入只能存在于 live `config.toml`,绝不写进数据库的存储配置。** 切换离开官方供应商、把 live 回写数据库时,CC Switch 会把这段注入精确剥离(只在形态与注入产物完全一致时才剥,第三方自定义的 `custom` 表原样保留)。正因如此,"关掉开关 + 切换一次"就能彻底还原 live,数据库里始终是你原本干净的官方配置——这是整个开关可逆性的基石。
|
||||
|
||||
### 3. 注入的两道拒绝闸(对应场景 C)
|
||||
|
||||
- `config.toml` 已有显式 `model_provider` → 不覆盖用户路由;
|
||||
- 已存在形态不同的 `[model_providers.custom]` 表(可能带第三方 `base_url`)→ 拒绝注入,否则会把 ChatGPT OAuth 流量路由到错误后端。
|
||||
|
||||
拒绝注入时 live 不统一,迁移闸门(检查 live 的 `model_provider` 是否 trim 后等于 `custom`)判定 `live_not_unified` → 跳过迁移、保留意愿、等下次启动重试时再做。这是"安全延后",不是"失败丢数据"。
|
||||
|
||||
### 4. 会话三分类(决定迁移 / 还原边界)
|
||||
|
||||
- **A 类**:开启时迁入的存量官方会话——备份即账本,可精确还原回 `openai`;
|
||||
- **B 类**:开启期间新建——不在任何备份、官方 / 第三方不可分,**永不自动搬动**(留 `custom`);
|
||||
- **C 类**:开启前的纯第三方历史——绝不触碰。
|
||||
|
||||
### 5. 迁移 / 还原的安全性(数据不会被真正删除,保障来自哪里)
|
||||
|
||||
四层设计共同保证:在**正常与异常的所有路径**下,原始会话数据都不会被真正删除。
|
||||
|
||||
- **只改字段,不动正文**:迁移 / 还原只把会话元数据里的 `model_provider` 值在 `openai` 与 `custom` 之间切换,对话内容、`response_item`、`encrypted_content` 一律原样保留。
|
||||
- **改写前必先复制备份**:jsonl 用文件复制、state DB 用 SQLite 完整副本,存进时间戳代际目录。迁移备份在 `codex-official-history-unify-v1/`,还原备份在独立的 `codex-official-history-unify-restore-v1/`,两者分开以保持账本纯净。
|
||||
- **只移不删 + 原子写**:所有 jsonl 改写走"临时文件 + 整体替换",state DB 走事务化 `UPDATE`,全程没有任何删除会话或索引的动作。文件在任一时刻都是完整的。
|
||||
- **悲观跳过 + 幂等可重试**:桶不一致时(`live_not_unified`)宁可不迁;一把进程锁串行化迁移与还原,避免"启动重试 / 保存后台任务 / 关闭还原"并发对同批文件双向改写;完成标记按 Codex 目录绑定、条件写入,防漏迁;还原用"在账本 + 当前仍 custom"双重条件,防误改。还原扫描全部备份代际取并集,多次开关循环后仍能还原早期迁入的会话;重复还原返回 `nothing_to_restore`,是幂等保护而非失败。
|
||||
|
||||
### 6. 跨后端 encrypted_content(对应场景 B)
|
||||
|
||||
会话内的推理密文只能被生成它的后端解密,上游 Codex by design 不支持跨后端解密。这是"续聊失败"的根因,与文件完整性无关——会话 `.jsonl` 完整躺在磁盘上、`encrypted_content` 也完好无损。换回原供应商续聊,或开新会话,都正常。
|
||||
|
||||
---
|
||||
|
||||
## 参考链接
|
||||
|
||||
- [使用第三方 API 时保留 Codex 远程操作和官方插件:CC Switch 配置攻略](./codex-official-auth-preservation-guide-zh.md)
|
||||
- [在 Codex 中使用 DeepSeek 这类 Chat 格式 API:CC Switch 路由攻略](./codex-deepseek-routing-guide-zh.md)
|
||||
- CC Switch 用户手册中「Codex 应用增强」相关章节
|
||||
|
||||
---
|
||||
|
||||
**给你的最后一句话**:你看到的"会话不见了 / 续聊失败",本质是**会话被换到了另一个历史列表(抽屉)里、或对方后端无法解密旧推理内容**,文件始终原封不动地躺在 `~/.codex/sessions/`(及 `state_5.sqlite`)里。关闭开关时勾选"按备份还原"即可把当初迁入的官方会话精确翻回官方列表;即便不还原,原始 `.jsonl` 文件和 `~/.cc-switch/backups/codex-official-history-unify-*/` 下的备份副本也都在——**数据绝不会真正丢失。**
|
||||
@@ -13,8 +13,9 @@
|
||||
|
||||
## Usage Guides
|
||||
|
||||
This release changes how usage is counted and reworks the dashboard quite a bit, so it is worth starting here:
|
||||
This release adds a **Codex unified session history** toggle — it migrates / restores sessions, and if used without care it can make you think sessions were "lost," so it is well worth reading its guide first. This release also changes how usage is counted and reworks the dashboard quite a bit, so both are worth starting with:
|
||||
|
||||
- **[Codex Unified Session History: Feature Overview and Usage Guide](../guides/codex-unified-session-history-guide-en.md)**: what "unify / migrate / restore" actually changes, why your data is never truly lost, and how to verify and precisely restore sessions when you can't see them. **If you used this toggle or worry a session is gone, read this first.**
|
||||
- **[Usage Statistics](../user-manual/en/4-proxy/4.4-usage.md)**: understand the Usage Dashboard's data sources (proxy logs, session sync) and how the statistics are counted. This release adds dashboard-wide provider / model filters and surfaces the real pricing model for route-takeover traffic.
|
||||
- **[Settings](../user-manual/en/1-getting-started/1.5-settings.md)**: the custom User-Agent override, the Codex unified session history toggle, and other switches live in the provider form's advanced options and on the settings page.
|
||||
|
||||
|
||||
@@ -13,8 +13,9 @@
|
||||
|
||||
## 利用ガイド
|
||||
|
||||
本リリースでは使用量統計の数え方とダッシュボードに多くの調整を加えたため、まず以下をご覧ください:
|
||||
本リリースでは **Codex 統一セッション履歴** のトグルを新設しました——セッションの移行 / 復元を伴い、操作を誤ると「セッションが消えた」と誤解しやすいため、まずこのガイドを読むことを強くおすすめします。また使用量統計の数え方とダッシュボードにも多くの調整を加えたので、あわせて以下をご覧ください:
|
||||
|
||||
- **[Codex セッション履歴の統一: 機能紹介と利用ガイド](../guides/codex-unified-session-history-guide-ja.md)**: 「統一 / 移行 / 復元」が実際に何を変えるのか、なぜデータが本当に失われないのか、そしてセッションが見えないときの自己点検と正確な復元の方法を解説します。**このトグルを使った、またはセッションが消えたと心配な方は、まずこちらをお読みください。**
|
||||
- **[使用量統計](../user-manual/ja/4-proxy/4.4-usage.md)**: 使用量ダッシュボードのデータソース(プロキシログ、セッション同期)と集計の仕組みを確認できます。本リリースで全体に効くプロバイダー / モデルフィルタを追加し、ルーティングテイクオーバー時の本物の課金モデルを表示するようにしました。
|
||||
- **[設定](../user-manual/ja/1-getting-started/1.5-settings.md)**: カスタム User-Agent オーバーライド、Codex 統一セッション履歴などのトグルは、プロバイダーフォームの高度なオプションと設定ページにあります。
|
||||
|
||||
|
||||
@@ -13,8 +13,9 @@
|
||||
|
||||
## 使用攻略
|
||||
|
||||
这一版用量统计的口径和看板做了较多调整,建议先看:
|
||||
本版新增了 **Codex 统一会话历史** 开关——它涉及会话的迁移 / 还原,操作不当时容易让人误以为"会话丢了",强烈建议先读这篇攻略;用量统计的口径和看板这一版也做了较多调整,一并附上:
|
||||
|
||||
- **[Codex 统一会话历史:功能介绍与使用攻略](../guides/codex-unified-session-history-guide-zh.md)**:讲清"统一 / 迁移 / 还原"到底改了什么、为什么数据不会真正丢失,以及看不到会话时如何自查与精确还原。**用过这个开关、或担心会话丢失,请务必先读。**
|
||||
- **[用量统计](../user-manual/zh/4-proxy/4.4-usage.md)**:了解用量看板的数据来源(代理日志、会话同步)与统计口径,本版新增了全局的供应商 / 模型筛选,并把路由接管的真实计价模型展示了出来。
|
||||
- **[设置](../user-manual/zh/1-getting-started/1.5-settings.md)**:自定义 User-Agent 覆盖、Codex 统一会话历史等开关都在供应商表单的高级选项与设置页里。
|
||||
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
# CC Switch v3.16.4
|
||||
|
||||
> After v3.16.3 made usage billing accurate, this release shifts the focus to polishing the Codex proxy chain and enriching the usage / pricing tooling — migrating Chinese providers to native Responses, decoupling the upstream-format selector from model mapping, decompressing zstd request / error bodies, and a batch of tool-call and OAuth-through-proxy fixes — while also adding local proxy request overrides, an in-app recovery screen when the database version is too new, native Windows ARM64 builds, and a wave of preset and branding updates (SubRouter, OpenCode Go, the CTok→ETok rename, the Kimi brand refresh, and a prime-partner badge).
|
||||
|
||||
**[中文版 →](v3.16.4-zh.md) | [日本語版 →](v3.16.4-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## Usage Guides
|
||||
|
||||
This release is mostly polish and expansion, with the new capabilities landing mainly in the usage dashboard and the provider form's advanced options. The following docs are worth reading alongside it:
|
||||
|
||||
- **[Can't see custom models in the Codex desktop app?](../guides/codex-desktop-custom-model-visibility-en.md)**: many users report that their configured third-party / custom models do not show up in the Codex desktop app's model picker. This is the Codex desktop app's **own upstream gating behavior** (it gates the model picker by official login state), not a CC Switch local-config problem, and **this release (v3.16.4) does not change it**. The doc explains the cause and the available mitigation (keep official login + route takeover).
|
||||
- **[Usage Statistics](../user-manual/en/4-proxy/4.4-usage.md)**: understand the Usage Dashboard's data sources and how the statistics are counted. This release adds bulk import of model pricing from models.dev, AK/SK usage queries for Volcengine Ark Coding / Agent Plan, and a live end time for custom date ranges.
|
||||
- **[Settings](../user-manual/en/1-getting-started/1.5-settings.md)**: local proxy request overrides (custom headers / request body), the Codex upstream-format selector, the local routing toggle, and more live in the provider form's advanced options.
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## Only Official Channels (Please Read)
|
||||
>
|
||||
> CC Switch is a **fully free and open-source** desktop app, and we **do not charge users any fees**. Please only obtain the software through the official channels listed below:
|
||||
>
|
||||
> | Channel | Only Official |
|
||||
> | ------------------ | ------------------------------------------------------------------------------ |
|
||||
> | Website | **[ccswitch.io](https://ccswitch.io)** |
|
||||
> | Source | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
|
||||
> | Downloads | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
|
||||
> | Author | **[@farion1231](https://github.com/farion1231)** |
|
||||
> | Report an Imposter | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
|
||||
>
|
||||
> **Any "CC Switch" website or client that asks you for payment, top-ups, or login credentials is fake.** If you have been tricked into paying, stop the transaction immediately and file a report through GitHub Issues.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CC Switch v3.16.4 is a maintenance update following v3.16.3. This release tightens the Codex proxy chain — switching several Chinese providers that have native OpenAI Responses endpoints to the native format (dropping the Responses→Chat route-takeover conversion), promoting "upstream format" out of the "local routing" toggle into its own control, adding decompression for zstd request and error response bodies, and fixing a string of tool-call and "OAuth module bypassing the global proxy" issues.
|
||||
|
||||
Alongside that, this release enriches the usage and pricing tooling (import pricing from models.dev, AK/SK usage queries for Volcengine Ark Coding / Agent Plan, a live end time for custom date ranges, GLM-5.2 and Doubao Seed 2.1 pricing), adds a batch of proxy and resilience capabilities (custom header / request-body overrides, an in-app recovery screen when the database version is too new, native Windows ARM64 builds), and brings a wave of preset and branding updates (SubRouter and OpenCode Go subscriptions, the CTok→ETok rename, the Kimi brand refresh and prime-partner badge, and a Kimi K2.7 Code sponsor banner).
|
||||
|
||||
**Release date**: 2026-06-27
|
||||
|
||||
**Stats**: 53 commits | 126 files changed | +8,149 / -1,016 lines
|
||||
|
||||
---
|
||||
|
||||
## Highlights
|
||||
|
||||
- **Native Responses for Chinese Codex providers**: Qwen / DashScope, Xiaomi MiMo, Volcengine Doubao, Meituan LongCat, and MiniMax (domestic / international) now connect directly to their native Responses endpoints instead of going through the Responses→Chat format-conversion takeover, for a shorter and more stable chain.
|
||||
- **Local proxy request overrides**: providers can configure custom header and request-body overrides, applied by the local proxy when forwarding, with interception validation that blocks protected security headers.
|
||||
- **In-app recovery screen for a too-new database**: when the SQLite version is newer than the current app supports, you no longer get stuck in a native dialog where "retry just fails again"; instead you are guided to a recovery screen that can upgrade the app in one click.
|
||||
- **Richer usage / pricing tooling**: bulk import of model pricing from models.dev, AK/SK usage queries for Volcengine Ark Coding / Agent Plan, a live end time for custom date ranges, and pricing for GLM-5.2 and Doubao Seed 2.1.
|
||||
- **New presets and branding updates**: added SubRouter and OpenCode Go subscription presets, renamed CTok to ETok, refreshed the Kimi brand mark, and added a prime-partner heart badge to the official Kimi presets.
|
||||
- **Native Windows ARM64 builds**: release artifacts now include native ARM64 builds, so ARM Windows devices no longer depend on x64 emulation.
|
||||
|
||||
---
|
||||
|
||||
## Added
|
||||
|
||||
### In-App Recovery Screen for a Too-New Database
|
||||
|
||||
When the SQLite `user_version` is newer than the current app's supported `SCHEMA_VERSION` (for example after downgrading to an older release, or because a third-party client wrote the file), startup used to die in a native "retry / quit" dialog — where "retry" just fails again. The app now routes to a dedicated recovery screen: when an update is available it offers a one-click "Upgrade App" button (download + install + restart, with a progress bar), and when none is available it explains that even the latest version cannot read this database. The "too new" check runs before any write to the database, so the app never runs DDL against a database it cannot understand; a native close in recovery mode exits cleanly (the tray has not been created yet). ([#4575](https://github.com/farion1231/cc-switch/pull/4575))
|
||||
|
||||
### Local Proxy Request Overrides (Custom Headers and Request Body)
|
||||
|
||||
Provider configs can now define custom header and request-body overrides that the local proxy applies when forwarding, exposed via new fields in the Claude and Codex provider forms. Input is validated against a protected-header list that blocks overriding security-sensitive headers. ([#4589](https://github.com/farion1231/cc-switch/pull/4589))
|
||||
|
||||
### Volcengine Ark Coding / Agent Plan Usage Queries
|
||||
|
||||
The usage panel can now query Volcengine Ark's Coding Plan and Agent Plan quotas. Because the Ark control-plane OpenAPI (`open.volcengineapi.com`) requires an account-level AccessKey signature rather than an inference API key, the usage script gains a dedicated AK/SK input area with a clickable link straight to the Volcengine IAM key-management console (`https://console.volcengine.com/iam/keymanage`); the proxy implements Volcengine Signature V4 (an AWS SigV4 variant: a fixed canonical-header order, the `HMAC-SHA256` algorithm, and the `ark` service scope). It first probes `GetAFPUsage` (the Agent Plan's 5-hour / weekly / monthly quotas) to auto-detect the plan and falls back to `GetCodingPlanUsage`, parsing the window label from the `Level` field (with a guard for `ResetTimestamp <= 0`), and adds the `monthly` tier label across the usage footer, the tray menu, and all four locales.
|
||||
|
||||
### Import Model Pricing from models.dev
|
||||
|
||||
The "Add Pricing" panel gains an "Import from models.dev" button: it fetches `https://models.dev/api.json`, supports full-text search across the entire catalog, and imports the selected entries through the same `update_model_pricing` path as manual entry. Imported model ids are normalized by the backend's `clean_model_id_for_pricing` rules (strip the provider prefix, lowercase, truncate the `:` suffix, map `@` to `-`, drop the `[1m]` marker) so the persisted rows actually match cost-attribution queries. A companion fix changes "backfill zero-cost over a range" to match in Rust by raw model alias (route prefixes, `:free` variants, date suffixes) rather than by exact SQL string match, so newly priced alias rows are priced immediately instead of waiting for the next startup backfill (fixes [#4017](https://github.com/farion1231/cc-switch/issues/4017)). ([#4079](https://github.com/farion1231/cc-switch/pull/4079))
|
||||
|
||||
### Native Windows ARM64 Builds
|
||||
|
||||
Release artifacts now include native Windows ARM64 builds, so ARM Windows devices can grab the matching native build instead of relying on x64 emulation. The release matrix now also runs each platform independently (fail-fast disabled), so a job that fails for a missing secret (e.g. macOS signing in a fork) no longer cancels its still-running siblings. ([#3950](https://github.com/farion1231/cc-switch/pull/3950))
|
||||
|
||||
### Live End Time for Custom Date Ranges
|
||||
|
||||
The custom date-range picker gains a "follow the current time as the end time" checkbox; when enabled, the end time becomes read-only and tracks now, so usage data always reflects the live consumption from the chosen start to the present moment. This is especially useful within the Coding Plan's 5-hour quota window. `liveEndTime` is now part of the React Query cache key, so a live range and a fixed range with the same endpoint no longer share the same stale cache entry. ([#4438](https://github.com/farion1231/cc-switch/pull/4438))
|
||||
|
||||
### Source File Name in the Session Detail Header
|
||||
|
||||
The session detail header now shows the session log's file name next to the project directory (hover for the full path, click to copy), so you can locate and open the underlying JSONL file directly from the UI. For long file names without spaces, such as the ~70-character Codex rollout names, it truncates at `max-w-[200px]` to avoid overflowing into the action buttons in a narrow window. ([#4113](https://github.com/farion1231/cc-switch/pull/4113))
|
||||
|
||||
### Unmanaged-Skill Hint on the Import Button
|
||||
|
||||
The Skills import button in the top bar now shows a green dot and a tooltip when there are unmanaged Skills on disk available to import, so you can tell at a glance that a Skill on disk hasn't been brought under management yet. The scan runs once on mount and is shared across navigations (30s `staleTime` + `keepPreviousData`) to avoid redundant disk IO.
|
||||
|
||||
### OpenCode Go Subscription Presets
|
||||
|
||||
Added the OpenCode Go (`opencode.ai/zen/go`) preset, covering Claude, Codex, and OpenCode, using a paste-ready bare API key (no OAuth). The Codex preset uses `openai_chat` conversion with a GLM / Kimi / DeepSeek / MiMo model catalog (and without a static `codexChatReasoning`, inferring each model's capabilities), while OpenCode points at `/zen/go/v1` via `@ai-sdk/openai-compatible`. All four OpenCode Go presets — Claude, Claude Desktop, Codex, and OpenCode — carry the referral link and in-app promotion copy; the promotion banner now shows on `partnerPromotionKey` alone (no longer bound to `isPartner`), so a preset can surface a referral promotion without earning the gold paid-partner star (which incidentally brings the existing MiniMax promotion back into view).
|
||||
|
||||
### Prime-Partner Preset Badge and Sorting
|
||||
|
||||
The first-party Moonshot Kimi presets (Kimi / Kimi For Coding / Kimi K2.7 Code) are now marked as prime partners: instead of the gold star they render a solid gold heart (no badge border) and, in the default (Original) sort, float to just after the official-category presets and before the rest. The grouping is done with a three-way partition that keeps each group's internal order, and an official preset that is also marked prime-partner stays only in the official group.
|
||||
|
||||
### GLM-5.2 and Doubao Seed 2.1 Pricing
|
||||
|
||||
The seed model pricing now includes GLM-5.2 ([#4385](https://github.com/farion1231/cc-switch/pull/4385)) and Doubao Seed 2.1 Pro / Turbo, so these models' usage is priced correctly instead of being recorded at zero cost. Doubao prices use Volcengine's official list pricing (converted at roughly 7.14); `cache_creation` stays at 0 because Doubao bills cache storage by time rather than by token writes, and the existing 2.0 rows are retained for historical accounting.
|
||||
|
||||
### Kimi For Coding Auto-Compact Window
|
||||
|
||||
The Kimi For Coding preset now defaults `CLAUDE_CODE_AUTO_COMPACT_WINDOW` to 262144, matching Kimi's official documentation, and exposes it via `templateValues` so users can customize the value for future models or performance tuning. ([#4401](https://github.com/farion1231/cc-switch/pull/4401))
|
||||
|
||||
### SubRouter Partner Provider
|
||||
|
||||
Added SubRouter (`subrouter.ai`, an AI relay aggregator that lets one key reach many models across many providers) as a preset covering all seven managed apps — an Anthropic-format endpoint for Claude Code / Claude Desktop / OpenClaw / Hermes, an OpenAI-compatible `/v1` endpoint (`gpt-5.5`) for Codex and OpenCode, and a Gemini-compatible `/v1beta` endpoint (`gemini-3.5-flash`) for Gemini CLI — with its own brand icon, a gold partner star, four-language promotion copy, and a referral signup link prefilled to the API-key registration page (`?aff=l3ri`). ([#4522](https://github.com/farion1231/cc-switch/pull/4522))
|
||||
|
||||
---
|
||||
|
||||
## Changed
|
||||
|
||||
### Chinese Codex Providers Use the Native Responses API
|
||||
|
||||
Several Chinese providers (Qwen / DashScope, Xiaomi MiMo, Volcengine Doubao, Meituan LongCat, MiniMax domestic / international) now expose native OpenAI Responses endpoints, so their Codex presets switch to `apiFormat: "openai_responses"`, connecting directly to the upstream instead of going through the Responses→Chat route-takeover conversion. Dropping the no-longer-needed `codexChatReasoning` and `modelCatalog` also keeps the "local routing mapping" toggle unchecked by default. SiliconFlow-hosted MiniMax stays on `openai_chat` because that is a third-party endpoint, not MiniMax's own base_url. The remaining chat-based providers also refreshed stale model ids (GLM 5.1→5.2, StepFun 3.5-flash-2603→3.7-flash, Ling 2.5-1T→2.6-1T).
|
||||
|
||||
### Upstream-Format Selector Decoupled from the Model-Mapping Toggle
|
||||
|
||||
The Codex provider form previously bound Chat format conversion and route takeover (model mapping) to the same toggle, which meant a provider offering a native Responses API couldn't use model mapping without forcing Chat Completions conversion. "Upstream format" (Chat Completions / Responses) is now a separate, always-visible selector, while the local routing toggle only controls the advanced subsection (the model-mapping catalog, plus reasoning capabilities when the format is Chat). Its initial state is derived from whether a saved catalog exists, adding no new persisted field; the four-language (zh / en / ja / zh-TW) `codexConfig` copy was rewritten to match.
|
||||
|
||||
### Doubao Seed 2.1 Pro Preset
|
||||
|
||||
The DouBaoSeed preset now points to `doubao-seed-2-1-pro` (replacing `doubao-seed-2-0-code-preview-latest`) across all six clients (claude, claude-desktop, codex, opencode, openclaw, hermes), updates the display name to "Doubao Seed 2.1 Pro", and corrects the OpenClaw cost fields from 0.002 / 0.006 to 0.84 / 4.2 USD per million tokens to match the new model.
|
||||
|
||||
### CTok Renamed to ETok
|
||||
|
||||
Following the vendor's domain, endpoint, and trademark rename, all user-facing branding migrates from CTok to ETok (`ctok.ai`→`etok.ai`, `api.ctok.ai`→`api.etok.ai`, plus the internal id, display name, icon, and README partner banner), across every client preset. The Codex history-migration whitelist still keeps `ctok` as a legacy id alongside the new `etok`, so existing users' local session history stays correctly bucketed after the rename.
|
||||
|
||||
### Kimi Preset Naming Unified
|
||||
|
||||
The Kimi presets that OpenCode and OpenClaw previously labeled "Kimi K2.7 Code" are renamed to "Kimi" to match the other apps (OpenCode's provider display name is renamed too); the model label still keeps "Kimi K2.7 Code" because it describes the actual model.
|
||||
|
||||
### JSON Editor Dark Mode
|
||||
|
||||
The CodeMirror `JsonEditor` in the usage-script dialog, the provider form, and the universal provider form now follows the app theme via `useDarkMode()`, switching to the `oneDark` editor theme instead of staying light while the rest of the app is already dark. ([#4556](https://github.com/farion1231/cc-switch/pull/4556))
|
||||
|
||||
### More Compact "Add Provider" Header and Footer Hint
|
||||
|
||||
The "Add Provider" dialog tightens the vertical spacing from the title to the tabs and from the tabs to the cards from 24px to 12px, and adds an always-visible fixed footer hint guiding users to fill in the fields below after choosing a preset. `FullScreenPanel` gains an optional `contentClassName` prop so the padding override applies only to this panel without affecting other panels that share it.
|
||||
|
||||
### Theme-Adaptive Kimi Mark
|
||||
|
||||
The inline Kimi placeholder mark is replaced with the vendor's refreshed mark. The K glyph uses `currentColor` so it follows the theme text color (dark in light mode, white in dark mode), while the brand accent color is fixed to the new `#1783FF`, with the metadata fallback color aligned accordingly.
|
||||
|
||||
### Removed the Fable 5 Verified Banner
|
||||
|
||||
The Settings About page no longer shows the Fable 5 Verified commemorative banner that 3.16.3 added beside the app name to mark a special build; the banner image and its marker are removed, and the About panel returns to the standard version-badge layout.
|
||||
|
||||
---
|
||||
|
||||
## Fixed
|
||||
|
||||
### Copilot / Codex OAuth Requests Now Honor the Global Proxy
|
||||
|
||||
`CopilotAuthManager` and `CodexOAuthManager` hardcoded `Client::new()` at construction, so their auth flows (token exchange, fetching the `/models` list, determining model vendor, device-code and OAuth refresh requests) ignored the configured global proxy and connected directly to the target services. On Copilot, a direct connection made `/models` return 0 Claude models, breaking live model resolution, and the upstream rejected requests with `400 model_not_supported`. Both managers now pull from the shared client on each request (`crate::proxy::http_client::get()`), honoring the global proxy URL and supporting runtime hot reload. Fixes [#2016](https://github.com/farion1231/cc-switch/issues/2016) and [#2931](https://github.com/farion1231/cc-switch/issues/2931). ([#4583](https://github.com/farion1231/cc-switch/pull/4583))
|
||||
|
||||
### Decompressing Compressed Request and Error Bodies
|
||||
|
||||
Codex Desktop sends zstd-compressed request bodies when authenticating to the Codex backend, which broke local proxy routing because the handlers parsed the raw compressed bytes directly with `serde_json`. The proxy now decompresses the request body before JSON parsing (gzip / br / deflate, plus the newly added zstd support, including stacked encodings like `gzip, zstd`), across three Codex handlers, and strips the stale `content-encoding` / `content-length` / `transfer-encoding` request headers so the forwarder regenerates them. Upstream non-2xx error bodies are decompressed the same way, so compressed rate-limit and auth details are no longer dropped and hidden from the client. Fixes [#3764](https://github.com/farion1231/cc-switch/issues/3764) and [#3696](https://github.com/farion1231/cc-switch/issues/3696). ([#3817](https://github.com/farion1231/cc-switch/pull/3817))
|
||||
|
||||
### DeepSeek Endpoint 400 with `thinking: disabled`
|
||||
|
||||
DeepSeek's Anthropic-compatible endpoint rejects requests where `thinking.type=disabled` coexists with an effort parameter, returning HTTP 400, which broke Claude Code 2.1.166+ sub-agents (Workflow / Dynamic Workflow) that hardcode `thinking: disabled`. Rather than overriding the client's intent, the proxy now strips the conflicting `output_config.effort` / `reasoning_effort` parameters for the official DeepSeek endpoint, since sub-agents don't need to surface reasoning anyway. ([#4239](https://github.com/farion1231/cc-switch/pull/4239))
|
||||
|
||||
### Reverted Hoisting Anthropic system Messages
|
||||
|
||||
Reverted the [#3775](https://github.com/farion1231/cc-switch/pull/3775) change that hoisted `role=system` messages on Anthropic-compatible providers from `messages[]` up to the top-level `system` field. The DeepSeek endpoint natively accepts inline system messages, and the rewrite changed the request prefix; keeping messages in place preserves the prompt prefix and avoids a suspected cache-hit-rate regression (see [#4297](https://github.com/farion1231/cc-switch/issues/4297)). The unrelated Windows test fix and the tool-thinking-history normalization from #3775 are retained.
|
||||
|
||||
### Chat Tool Calls Missing Function Names
|
||||
|
||||
Some upstreams send empty or missing function names in streaming tool-call deltas, which used to produce invalid Codex Chat output items (or an `unknown_tool` fallback). Accumulated tool-call state is no longer overwritten by an empty delta, and tool calls that never receive a `call_id` and a valid name are skipped at finalization, across the streaming, non-streaming, and legacy `function_call` paths. ([#4159](https://github.com/farion1231/cc-switch/pull/4159))
|
||||
|
||||
### Restore Cached Codex Tool-Call Fields
|
||||
|
||||
When Codex makes a follow-up Chat request that references a `previous_response_id`, its `function_call` items may carry only the `call_id`. History enhancement previously backfilled only `reasoning` / `reasoning_content`, leaving the function's `name`, `arguments`, `status`, and other fields empty; it now restores all cached tool-call fields from history so the call can be correctly reconstructed for the Chat upstream. ([#4160](https://github.com/farion1231/cc-switch/pull/4160))
|
||||
|
||||
### Duplicate Codex base_url Entries in config.toml
|
||||
|
||||
Writing Codex's `base_url` into `config.toml` previously replaced or removed only one matching assignment per section, so a section that already contained multiple `base_url` lines kept the extras and accumulated duplicates. `setCodexBaseUrl` now collapses all matches in the target section or at the top level (replacing the first, removing the rest), and the TOML `base_url` regex now handles escaped quotes. ([#4316](https://github.com/farion1231/cc-switch/pull/4316))
|
||||
|
||||
### History Migration Probes the CODEX_SQLITE_HOME State DB
|
||||
|
||||
Codex session-history migration previously scanned only `~/.codex/state_5.sqlite` and the `sqlite_home` location in `config.toml`, so when Codex's SQLite state was relocated via the `CODEX_SQLITE_HOME` environment variable, the state DB was never scanned and its threads stayed in the old provider bucket. The `codex_state_db_paths` helper shared by both the third-party and unified-session migrations now falls back to `CODEX_SQLITE_HOME` (the `sqlite_home` in `config` still takes precedence).
|
||||
|
||||
### Provider Terminal Honors the User Shell
|
||||
|
||||
Launching a provider terminal on macOS / Linux previously hardcoded `bash`, so zsh / fish users' rc files weren't loaded. The launcher now detects the user's default shell from `$SHELL` (falling back to `/bin/zsh` on macOS, `/bin/bash` on Linux) and execs into it with the clean-start flag, while the launch script itself now uses POSIX `sh` for portability (e.g. fish, and NixOS where `/bin/sh` may not exist). ([#4140](https://github.com/farion1231/cc-switch/pull/4140), fixes [#1546](https://github.com/farion1231/cc-switch/issues/1546))
|
||||
|
||||
### Claude MCP Paths Honor the Custom Config Directory
|
||||
|
||||
When a custom Claude config directory is configured, MCP server reads and writes now resolve to the MCP file under that directory instead of the default location, isolating MCP state per profile. The old "copy on access" migration of the legacy file was removed in favor of resolving the override path directly. ([#3431](https://github.com/farion1231/cc-switch/pull/3431))
|
||||
|
||||
### Preset Results Clickable After Search
|
||||
|
||||
After searching in the "Add Provider" preset selector, results briefly couldn't be clicked or selected. The `requestAnimationFrame` `select()` that fought the input and swallowed the first character (e.g. "gateway" → "ateway") was removed, input auto-focus on the open-and-click path was restored, and pressing Ctrl/Cmd+F while the search box is already open now refocuses it. The provider list's typing guard was also narrowed to the Ctrl/Cmd+F branch so Escape can still close the search panel. ([#4315](https://github.com/farion1231/cc-switch/pull/4315))
|
||||
|
||||
### Skills Browsing and Provider Card Display Fixes
|
||||
|
||||
Fixed several display and interaction issues: repository management actions stay available while browsing skills.sh, and refresh stays available when a repository returns empty results; overly long provider names and website URLs on provider cards now truncate instead of overflowing; the OMO model-variant dropdown truncates the selected label with a full-text tooltip; and Select menu items show a checkmark on the currently selected item. ([#4323](https://github.com/farion1231/cc-switch/pull/4323))
|
||||
|
||||
### Reset Scroll When Switching Settings Tabs
|
||||
|
||||
Switching tabs in the Settings dialog used to keep the previous tab's scroll position, sometimes landing halfway down the new tab; the scroll container now resets to the top whenever the active tab changes. ([#4165](https://github.com/farion1231/cc-switch/pull/4165))
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
### Kimi Pinned Sponsor Banner
|
||||
|
||||
The pinned sponsor banner at the top of all four README languages (en / zh / ja / de) is now Kimi K2.7 Code, replacing the previous MiniMax M2.7 banner. The copy reflects the K2.7 Code release (a coding-oriented agentic model with thinking-token usage down roughly 30% from K2.6), the banner is now served from in-repo assets (`assets/partners/banners/kimi-banner-en.png` / `kimi-banner-zh.png`) instead of the Moonshot CDN, and it carries a clickable call to action pointing at the `aff=cc-switch` Moonshot console.
|
||||
|
||||
### Codex Unified Session History Guide
|
||||
|
||||
Added a three-language (zh / en / ja) guide explaining what the unified Codex session history toggle's enable-time migration (when enabled) and ledger-based restore (when disabled) actually do, why session data is never truly deleted (only re-tagged + auto-backed-up), and how to verify whether files really are on disk or were just filed into another provider's drawer. It includes a symptom table for the common "my sessions are gone" misunderstanding and disk-verification commands for macOS / Linux / Windows, and is linked as the first item in the v3.16.3 release notes' "Usage Guides".
|
||||
|
||||
### Simplified Homebrew Install Instructions
|
||||
|
||||
The install guide no longer asks users to run `brew tap farion1231/ccswitch` before `brew install --cask cc-switch`; this deprecated tap step is removed from the en / ja / zh user manuals, and the cask now installs directly. ([#4319](https://github.com/farion1231/cc-switch/pull/4319))
|
||||
|
||||
### Star-History Global Ranking Badge
|
||||
|
||||
Added a star-history global ranking badge next to the existing Trendshift badge across all four README languages, with light / dark theme variants.
|
||||
|
||||
### Volcengine Ark Coding Plan Activity Link
|
||||
|
||||
The "developers in mainland China click here" link in the ByteDance / Volcengine Ark sponsor entry now points to Volcengine's `ai618` activity page, replacing the previous `codingplan` referral URL, across all four README languages.
|
||||
|
||||
### CCSub Sponsor Banner Vector Asset
|
||||
|
||||
Replaced the low-resolution `ccsub.jpg` sponsor logo with the vector `ccsub.svg`, letterboxed from 2046x648 to 2046x850 (roughly 2.406:1) so it matches the other sponsor-table banners and renders at the same 62px height. All four README languages point to the new asset.
|
||||
|
||||
---
|
||||
|
||||
## Upgrade Notes
|
||||
|
||||
### Chinese Codex Providers' Native Responses Migration
|
||||
|
||||
This release switches the Codex presets of several Chinese providers with native Responses endpoints (Qwen / DashScope, Xiaomi MiMo, Volcengine Doubao, Meituan LongCat, MiniMax domestic / international) to `openai_responses` and removes their `modelCatalog`. Existing providers already configured from these presets are unaffected and keep their configuration as-is; if you want to switch to native Responses (dropping the format-conversion takeover), re-pick the preset once and save. SiliconFlow-hosted MiniMax stays on `openai_chat` and is not part of this migration.
|
||||
|
||||
### Recovery from a Too-New Database
|
||||
|
||||
If you opened the database with a higher version of CC Switch and then switched back to an older version, the older version will enter the new "database version too new" recovery screen on startup and guide you to upgrade to a version that can read the database. This is expected behavior — upgrading to the latest version restores normal operation.
|
||||
|
||||
---
|
||||
|
||||
## Risk Notice
|
||||
|
||||
This release continues the risk notices from previous versions for reverse-proxy-style features.
|
||||
|
||||
**Codex OAuth reverse proxy**: using a ChatGPT subscription's Codex OAuth through a reverse proxy may violate OpenAI's terms of service. See the [v3.13.0 release notes](v3.13.0-en.md#️-risk-notice) for details.
|
||||
|
||||
**Codex third-party provider Chat routing**: when CC Switch local proxy converts and forwards Codex requests to third-party providers, each provider may have different requirements for billing, compliance, and data retention. Read the target provider's terms before use.
|
||||
|
||||
**Claude Desktop third-party provider proxy switching**: when CC Switch's built-in proxy gateway forwards Claude Desktop requests to third-party providers, you must also follow the target provider's billing, compliance, and data-retention terms.
|
||||
|
||||
By enabling these features, users accept the related risks. CC Switch is not responsible for account restrictions, warnings, or service suspensions caused by using these features.
|
||||
|
||||
---
|
||||
|
||||
## Thanks
|
||||
|
||||
Thanks to the following contributors for the features and fixes in v3.16.4:
|
||||
|
||||
- [#3817](https://github.com/farion1231/cc-switch/pull/3817): decompress the request body before forwarding and add zstd support, thanks @chenx-dust.
|
||||
- [#4583](https://github.com/farion1231/cc-switch/pull/4583): fix the Copilot / Codex OAuth modules bypassing the global proxy and causing Claude model 400s, thanks @zymouse.
|
||||
- [#4589](https://github.com/farion1231/cc-switch/pull/4589): add local proxy request overrides (custom headers and request body), thanks @mfzzf.
|
||||
- [#4575](https://github.com/farion1231/cc-switch/pull/4575): add an in-app recovery screen for a too-new database version, thanks @SaladDay.
|
||||
- [#4556](https://github.com/farion1231/cc-switch/pull/4556): wire dark mode into the JsonEditor in several places, thanks @TanKimzeg.
|
||||
- [#4438](https://github.com/farion1231/cc-switch/pull/4438): add a live end time for custom date ranges, thanks @arichyx.
|
||||
- [#3950](https://github.com/farion1231/cc-switch/pull/3950): add Windows ARM64 release support, thanks @MOON-DREAM-STARS.
|
||||
- [#4401](https://github.com/farion1231/cc-switch/pull/4401): add CLAUDE_CODE_AUTO_COMPACT_WINDOW to the Kimi For Coding preset, thanks @cyijun.
|
||||
- [#4323](https://github.com/farion1231/cc-switch/pull/4323): fix the Skills management and model-config interaction display, thanks @thisTom.
|
||||
- [#3431](https://github.com/farion1231/cc-switch/pull/3431): align Claude MCP paths to the custom config directory, thanks @makoMakoGo.
|
||||
- [#4159](https://github.com/farion1231/cc-switch/pull/4159): skip Chat tool calls missing function names, thanks @hueifeng.
|
||||
- [#4385](https://github.com/farion1231/cc-switch/pull/4385): add glm-5.2 pricing, thanks @arichyx.
|
||||
- [#4079](https://github.com/farion1231/cc-switch/pull/4079): support importing model pricing from models.dev, thanks @kingcanfish.
|
||||
- [#4315](https://github.com/farion1231/cc-switch/pull/4315): fix preset results not being clickable / selectable after search, thanks @RuixeWolf.
|
||||
- [#4316](https://github.com/farion1231/cc-switch/pull/4316): prevent duplicate Codex base_url entries, thanks @jeffwcx.
|
||||
- [#4140](https://github.com/farion1231/cc-switch/pull/4140): make the provider terminal honor the user shell, thanks @zkforge.
|
||||
- [#4113](https://github.com/farion1231/cc-switch/pull/4113): show the source file name in the session detail header, thanks @xu-song.
|
||||
- [#4160](https://github.com/farion1231/cc-switch/pull/4160): restore cached Codex tool-call fields, thanks @chen-985211.
|
||||
- [#4239](https://github.com/farion1231/cc-switch/pull/4239): strip the effort parameter when thinking:disabled on DeepSeek endpoints, thanks @maskshell.
|
||||
- [#4165](https://github.com/farion1231/cc-switch/pull/4165): reset scroll when switching settings tabs, thanks @Muleizhang.
|
||||
- [#4319](https://github.com/farion1231/cc-switch/pull/4319): remove the deprecated Homebrew tap step, thanks @tianpeng-dev.
|
||||
- [#4522](https://github.com/farion1231/cc-switch/pull/4522): add the SubRouter provider preset, thanks @abingyyds.
|
||||
|
||||
Thanks also to everyone who reported Codex proxy chain, usage billing, local proxy robustness, and platform compatibility issues after the v3.16.3 release. Many of these patches came directly from real-world reproduction clues.
|
||||
|
||||
---
|
||||
|
||||
## Download & Install
|
||||
|
||||
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) and download the build for your system.
|
||||
|
||||
### System Requirements
|
||||
|
||||
| System | Minimum Version | Architecture |
|
||||
| ------- | ------------------------ | ----------------------------------- |
|
||||
| Windows | Windows 10 and later | x64 / ARM64 |
|
||||
| macOS | macOS 12 (Monterey)+ | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | See table below | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| File | Description |
|
||||
| ---------------------------------------- | ------------------------------------------------ |
|
||||
| `CC-Switch-v3.16.4-Windows.msi` | **Recommended** - MSI installer with auto-update |
|
||||
| `CC-Switch-v3.16.4-Windows-Portable.zip` | Portable build, unzip and run |
|
||||
|
||||
Windows ARM64 devices should pick the artifact whose file name carries the `arm64` tag.
|
||||
|
||||
### macOS
|
||||
|
||||
| File | Description |
|
||||
| -------------------------------- | ----------------------------------------------------- |
|
||||
| `CC-Switch-v3.16.4-macOS.dmg` | **Recommended** - DMG installer, drag to Applications |
|
||||
| `CC-Switch-v3.16.4-macOS.zip` | Unzip and drag to Applications, Universal Binary |
|
||||
| `CC-Switch-v3.16.4-macOS.tar.gz` | For Homebrew install and auto-update |
|
||||
|
||||
Homebrew install:
|
||||
|
||||
```bash
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
Linux assets are available for both **x86_64** and **ARM64** (`aarch64`). Choose the file whose architecture tag matches your machine's `uname -m` output:
|
||||
|
||||
- `CC-Switch-v3.16.4-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.16.4-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
| Distribution | Recommended Format | Install Command |
|
||||
| --------------------------------------- | ------------------ | --------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | Make executable and run directly, or use AUR |
|
||||
| Other distributions / unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,353 @@
|
||||
# CC Switch v3.16.4
|
||||
|
||||
> v3.16.3 で「使用量の課金を正確にする」ことに取り組んだのに続き、本リリースは Codex プロキシ経路の磨き込みと、使用量 / 価格ツールの拡充に重きを置いています——国産プロバイダーのネイティブ Responses への移行、上流の形式セレクタとモデルマッピングの分離、zstd リクエスト / エラーボディの展開、そしてツール呼び出しと OAuth がプロキシを経由するようにする一連の修正です。あわせて、ローカルプロキシのリクエストオーバーライド、データベースのバージョンが新しすぎる場合のアプリ内リカバリ画面、ネイティブ Windows ARM64 ビルドを新設し、一連のプリセットとブランドの更新(SubRouter、OpenCode Go、CTok→ETok の改名、Kimi のブランド刷新と prime-partner バッジ)を届けます。
|
||||
|
||||
**[English →](v3.16.4-en.md) | [中文版 →](v3.16.4-zh.md)**
|
||||
|
||||
---
|
||||
|
||||
## 利用ガイド
|
||||
|
||||
本リリースは磨き込みと拡張が中心で、新しい機能の多くは使用量パネルとプロバイダーフォームの高度なオプションに収まっています。以下のドキュメントとあわせてご覧ください:
|
||||
|
||||
- **[Codex デスクトップでカスタムモデルが見えない?](../guides/codex-desktop-custom-model-visibility-ja.md)**: Codex デスクトップアプリで、設定したサードパーティ / カスタムモデルが見えないというフィードバックが少なくありません。これは Codex デスクトップアプリ**上流自身のゲーティング挙動**(公式ログイン状態に応じてモデルセレクタを通す)であり、CC Switch のローカル設定の問題ではありません。**本リリース(v3.16.4)でこの点に変更はありません**。ドキュメントでは原因と、使える緩和策(公式ログインの保持 + ルーティングテイクオーバー)を解説しています。
|
||||
- **[使用量統計](../user-manual/ja/4-proxy/4.4-usage.md)**: 使用量ダッシュボードのデータソースと集計の仕組みを確認できます。本リリースでは models.dev からのモデル価格一括インポート、火山方舟 Coding / Agent Plan の AK/SK 使用量照会、カスタム日付範囲の「リアルタイム終了時刻」を追加しました。
|
||||
- **[設定](../user-manual/ja/1-getting-started/1.5-settings.md)**: ローカルプロキシのリクエストオーバーライド(カスタムリクエストヘッダー / リクエストボディ)、Codex の上流形式セレクタやローカルルーティングのトグルは、いずれもプロバイダーフォームの高度なオプションにあります。
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## 唯一の公式チャネル(必ずお読みください)
|
||||
>
|
||||
> CC Switch は**完全に無料・オープンソース**のデスクトップアプリで、**ユーザーから料金を徴収することはありません**。本ソフトウェアは下記の公式チャネルからのみ入手してください:
|
||||
>
|
||||
> | チャネル | 唯一の公式 |
|
||||
> | ------------ | ------------------------------------------------------------------------------ |
|
||||
> | 公式サイト | **[ccswitch.io](https://ccswitch.io)** |
|
||||
> | ソースコード | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
|
||||
> | ダウンロード | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
|
||||
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
|
||||
> | 偽サイト通報 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
|
||||
>
|
||||
> **料金請求・チャージ・認証情報の提供を求める「CC Switch」サイトやクライアントはすべて偽物です。** 支払いを誘導された場合は直ちに操作を中止し、GitHub Issues からご報告ください。
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
CC Switch v3.16.4 は v3.16.3 に続くメンテナンスアップデートです。本リリースは Codex プロキシ経路まわりを一通り締め直しました——ネイティブの OpenAI Responses endpoint を備える複数の国産プロバイダーをネイティブ形式へ切り替え(Responses→Chat のルーティングテイクオーバー変換を省く)、「上流形式」を「ローカルルーティング」トグルから独立させ、zstd のリクエストとエラーレスポンスボディの展開を補い、ツール呼び出しと「OAuth モジュールがグローバルプロキシをバイパスする」一連の問題を修正しました。
|
||||
|
||||
あわせて本リリースでは使用量と価格のツールを拡充し(models.dev からの価格インポート、火山方舟 Coding / Agent Plan の AK/SK 使用量照会、カスタム日付範囲のリアルタイム終了時刻、GLM-5.2 と Doubao Seed 2.1 の価格)、一連のプロキシと堅牢性の機能を新設し(カスタムリクエストヘッダー / リクエストボディのオーバーライド、データベースのバージョンが新しすぎる場合のアプリ内リカバリ画面、ネイティブ Windows ARM64 ビルド)、一連のプリセットとブランドの更新(SubRouter と OpenCode Go のサブスクリプション、CTok→ETok の改名、Kimi のブランド刷新と prime-partner バッジ、Kimi K2.7 Code スポンサーバナー)を届けます。
|
||||
|
||||
**リリース日**: 2026-06-27
|
||||
|
||||
**Stats**: 53 commits | 126 files changed | +8,149 / -1,016 lines
|
||||
|
||||
---
|
||||
|
||||
## ハイライト
|
||||
|
||||
- **国産 Codex プロバイダーがネイティブ Responses を使用**: 千問 / 百炼、小米 MiMo、火山 Doubao、美団 LongCat、MiniMax(国内 / 国際)が、それぞれのネイティブ Responses endpoint に直結するようになり、Responses→Chat の形式変換テイクオーバーを経由しなくなりました。経路が短く、より安定します。
|
||||
- **ローカルプロキシのリクエストオーバーライド**: プロバイダーにカスタムリクエストヘッダーとリクエストボディのオーバーライドを設定でき、ローカルプロキシが転送時に適用します。保護対象のセキュリティ関連リクエストヘッダーにはブロック検証を行います。
|
||||
- **データベースのバージョンが新しすぎる場合のアプリ内リカバリ画面**: SQLite のバージョンが現在のアプリのサポート範囲より新しいとき、「再試行しても再び失敗するだけ」のネイティブダイアログで詰まらず、ワンクリックでアプリを更新できるリカバリ画面へ案内します。
|
||||
- **より充実した使用量 / 価格ツール**: models.dev からのモデル価格一括インポート、火山方舟 Coding / Agent Plan の AK/SK 使用量照会、カスタム日付範囲の「リアルタイム終了時刻」、そして GLM-5.2 と Doubao Seed 2.1 の価格。
|
||||
- **新しいプリセットとブランド更新**: SubRouter と OpenCode Go のサブスクリプションプリセットを追加し、CTok を ETok へ改名し、Kimi のブランドアイコンを刷新し、公式 Kimi プリセットに prime-partner のハートバッジを付けました。
|
||||
- **ネイティブ Windows ARM64 ビルド**: 配布物にネイティブ ARM64 版を追加し、ARM アーキテクチャの Windows デバイスは x64 エミュレーションに頼る必要がなくなりました。
|
||||
|
||||
---
|
||||
|
||||
## 追加機能
|
||||
|
||||
### データベースのバージョンが新しすぎる場合のアプリ内リカバリ画面
|
||||
|
||||
SQLite の `user_version` が現在のアプリのサポートする `SCHEMA_VERSION` より新しいとき(旧版へダウングレードした、あるいはサードパーティクライアントがこのファイルを書いた場合など)、これまでは起動時にネイティブの「再試行 / 終了」ダイアログで詰まっていました——しかし「再試行」は再び失敗するだけです。現在はアプリが専用のリカバリ画面へ案内します: 利用可能な更新があればワンクリックの「アプリを更新」ボタン(ダウンロード + インストール + 再起動、プログレスバー付き)を提供し、利用可能な更新がない場合は最新版であってもこのデータベースを読めない旨を案内します。この「バージョンが新しすぎる」チェックは、あらゆる書き込み動作の前に行われるため、アプリが読めないデータベースに対して DDL を実行することは決してありません。リカバリモードでのネイティブな終了はクリーンに終了します(この時点ではトレイがまだ作成されていません)。([#4575](https://github.com/farion1231/cc-switch/pull/4575))
|
||||
|
||||
### ローカルプロキシのリクエストオーバーライド(カスタムリクエストヘッダーとリクエストボディ)
|
||||
|
||||
プロバイダー設定で、カスタムリクエストヘッダーとリクエストボディのオーバーライドを定義できるようになり、ローカルプロキシが転送時に適用します。Claude と Codex のプロバイダーフォームの新しいフィールドから公開します。入力は検証を経て、その中にセキュリティに敏感なリクエストヘッダーの上書きを防ぐ保護対象リクエストヘッダーのリストを含みます。([#4589](https://github.com/farion1231/cc-switch/pull/4589))
|
||||
|
||||
### 火山方舟 Coding / Agent Plan 使用量照会
|
||||
|
||||
使用量パネルから火山方舟(Volcengine Ark)の Coding Plan と Agent Plan のクォータを照会できるようになりました。方舟のコントロールプレーン OpenAPI(`open.volcengineapi.com`)が要求するのは推論 API key ではなくアカウント単位の AccessKey 署名であるため、使用量スクリプトに独立した AK/SK 入力欄を新設し、火山 IAM のキー管理コンソール(`https://console.volcengine.com/iam/keymanage`)へ直接飛べるクリック可能なリンクを添えました。プロキシは火山署名 V4(AWS SigV4 の変種: 固定された canonical header 順、`HMAC-SHA256` アルゴリズム、`ark` サービス scope)を実装しています。まず `GetAFPUsage`(Agent Plan の 5 時間 / 週 / 月クォータ)をプローブしてプランを自動判定し、失敗した場合は `GetCodingPlanUsage` へフォールバックして `Level` フィールドからウィンドウラベルを解析し(`ResetTimestamp <= 0` にはガードを設けます)、あわせて使用量フッター、トレイメニュー、4 言語に `monthly` 階層のラベルを補いました。
|
||||
|
||||
### models.dev からのモデル価格インポート
|
||||
|
||||
「価格を追加」パネルに「models.dev からインポート」ボタンを新設しました: `https://models.dev/api.json` を取得し、カタログ全体の全文検索に対応し、選択した項目を手入力と同じ `update_model_pricing` 経路でインポートします。インポートされた model id は、バックエンドの `clean_model_id_for_pricing` ルール(プロバイダープレフィックスの除去、小文字化、`:` サフィックスの切り捨て、`@` を `-` へマッピング、`[1m]` マーカーの除去)で正規化されるため、保存される行がコスト帰属クエリと本当にマッチするようになります。あわせて、「範囲ごとのゼロコストバックフィル」を、精密な SQL 文字列マッチではなく Rust 側で元の model エイリアス(ルーティングプレフィックス、`:free` 変種、日付サフィックス)でマッチするように修正したため、新しい価格のエイリアス行が次回起動時のバックフィルを待たず即座に課金されるようになりました([#4017](https://github.com/farion1231/cc-switch/issues/4017) を修正)。([#4079](https://github.com/farion1231/cc-switch/pull/4079))
|
||||
|
||||
### ネイティブ Windows ARM64 ビルド
|
||||
|
||||
配布物にネイティブの Windows ARM64 制品が含まれるようになり、ARM アーキテクチャの Windows デバイスは対応するネイティブビルドを入手でき、x64 エミュレーションに頼る必要がなくなりました。リリースマトリクスも各プラットフォームが独立して走るように変更し(fail-fast を無効化)、あるジョブがキー欠如で失敗しても(fork での macOS 署名など)、まだ完了していない同列のジョブをまとめてキャンセルしないようにしました。([#3950](https://github.com/farion1231/cc-switch/pull/3950))
|
||||
|
||||
### カスタム日付範囲のリアルタイム終了時刻
|
||||
|
||||
カスタム日付範囲セレクタに「終了時刻を現在時刻に追従」チェックボックスを新設しました。有効にすると終了時刻は読み取り専用になり、今この瞬間に自動追従するため、使用量データは選択した起点から現在までのリアルタイムの消費を常に反映します。これは Coding Plan の 5 時間クォータウィンドウで特に有用です。`liveEndTime` は React Query のキャッシュキーに取り込んだため、リアルタイム範囲と終点が同じ固定範囲が同一の古いキャッシュ項目を共有することはなくなりました。([#4438](https://github.com/farion1231/cc-switch/pull/4438))
|
||||
|
||||
### セッション詳細ヘッダーにソースファイル名を表示
|
||||
|
||||
セッション詳細ヘッダーが、プロジェクトディレクトリの隣にセッションログのファイル名を表示するようになりました(ホバーで完全パスを確認、クリックでコピー)。これにより、画面から直接、基礎となる JSONL ファイルを特定して開けます。~70 文字の Codex rollout のような空白を含まない長いファイル名は `max-w-[200px]` で切り詰め、狭いウィンドウで操作ボタン領域へあふれ出るのを防ぎます。([#4113](https://github.com/farion1231/cc-switch/pull/4113))
|
||||
|
||||
### インポートボタンの未管理 Skill ヒント
|
||||
|
||||
トップバーの Skills インポートボタンが、ローカルにインポート可能な未管理の Skill が存在するとき、緑のドットとヒントを表示するようになり、ディスク上の Skill がまだ管理対象になっていないことが一目で分かります。このスキャンはマウント時に一度実行され、複数のナビゲーションをまたいで共有され(30s の `staleTime` + `keepPreviousData`)、ディスク IO の重複を避けます。
|
||||
|
||||
### OpenCode Go サブスクリプションプリセット
|
||||
|
||||
OpenCode Go(`opencode.ai/zen/go`)プリセットを追加し、Claude、Codex、OpenCode をカバーし、そのまま貼り付けられる素の API key(OAuth なし)を使用します。Codex プリセットは `openai_chat` 変換を使い、GLM / Kimi / DeepSeek / MiMo のモデルカタログを備え(静的な `codexChatReasoning` は付けず、モデルごとに能力を推論します)、OpenCode は `@ai-sdk/openai-compatible` 経由で `/zen/go/v1` を指します。4 つの OpenCode Go プリセット——Claude、Claude Desktop、Codex、OpenCode——にはいずれも紹介リンクとアプリ内宣伝文を付けました。宣伝バナーは `partnerPromotionKey` だけで表示できるようになり(`isPartner` への紐付けを解除)、あるプリセットが金色の有料パートナースターを得ずに紹介宣伝を表示できるようになりました(これにより既存の MiniMax 宣伝も再表示されます)。
|
||||
|
||||
### Prime-Partner プリセットバッジとソート
|
||||
|
||||
第一方 Moonshot Kimi プリセット(Kimi / Kimi For Coding / Kimi K2.7 Code)が prime partner としてマークされるようになりました: 金色のスターは表示せず、塗りつぶしの金色ハート(バッジ枠なし)を描画し、既定(Original)ソートでは公式カテゴリプリセットの後、その他より前に浮かびます。グルーピングは 3 方向の partition で実装し、各グループは内部順序を保ち、prime-partner としてもマークされた公式プリセットは公式グループにのみ残ります。
|
||||
|
||||
### GLM-5.2 と Doubao Seed 2.1 の価格
|
||||
|
||||
シードモデル価格に GLM-5.2([#4385](https://github.com/farion1231/cc-switch/pull/4385))と Doubao Seed 2.1 Pro / Turbo を追加し、これらのモデルの使用量がゼロコストではなく正しく課金されるようにしました。Doubao の価格は火山公式の定価を採用し(約 7.14 のレートで換算)、`cache_creation` は 0 のままです。Doubao はキャッシュストレージを token 書き込みではなく時間で課金するためで、既存の 2.0 行も過去の記帳のために残します。
|
||||
|
||||
### Kimi For Coding 自動圧縮ウィンドウ
|
||||
|
||||
Kimi For Coding プリセットが `CLAUDE_CODE_AUTO_COMPACT_WINDOW` を既定で 262144 に設定するようになり、Kimi 公式ドキュメントと一致させ、`templateValues` 経由で公開して、将来のモデルや性能チューニングのためにユーザーがこの値をカスタマイズできるようにしました。([#4401](https://github.com/farion1231/cc-switch/pull/4401))
|
||||
|
||||
### SubRouter パートナープロバイダー
|
||||
|
||||
SubRouter(`subrouter.ai`、1 つの key で複数モデル・複数プロバイダーにアクセスできる AI 中継アグリゲーター)をプリセットとして追加し、管理対象の 7 アプリすべてをカバーしました——Claude Code / Claude Desktop / OpenClaw / Hermes 向けには Anthropic 形式 endpoint、Codex と OpenCode 向けには OpenAI 互換の `/v1` endpoint(`gpt-5.5`)、Gemini CLI 向けには Gemini 互換の `/v1beta` endpoint(`gemini-3.5-flash`)——自前のブランドアイコン、金色のパートナースター、4 言語の宣伝文、そして API key の登録ページへ事前入力された紹介登録リンク(`?aff=l3ri`)を備えます。([#4522](https://github.com/farion1231/cc-switch/pull/4522))
|
||||
|
||||
---
|
||||
|
||||
## 変更
|
||||
|
||||
### 国産 Codex プロバイダーがネイティブ Responses API を使用
|
||||
|
||||
複数の国産プロバイダー(千問 / DashScope 百炼、小米 MiMo、火山 Doubao、美団 LongCat、MiniMax 国内 / 国際)がネイティブの OpenAI Responses endpoint を公開したため、それらの Codex プリセットを `apiFormat: "openai_responses"` へ切り替え、Responses→Chat のルーティングテイクオーバー変換を経由せず上流に直結するようにしました。不要になった `codexChatReasoning` と `modelCatalog` を外したことで、「ローカルルーティングマッピング」トグルも既定で未選択のままになります。SiliconFlow がホストする MiniMax は `openai_chat` のままです。これは MiniMax 自身の base_url ではなくサードパーティの endpoint だからです。引き続き chat を使う他のプロバイダーも、古くなった model id を更新しました(GLM 5.1→5.2、StepFun 3.5-flash-2603→3.7-flash、Ling 2.5-1T→2.6-1T)。
|
||||
|
||||
### 上流形式セレクタとモデルマッピングトグルの分離
|
||||
|
||||
Codex プロバイダーフォームは以前、Chat 形式変換とルーティングテイクオーバー(モデルマッピング)を同じトグルに束ねていたため、ネイティブ Responses API を提供するプロバイダーが Chat Completions 変換を強制せずにモデルマッピングを使うことができませんでした。現在は「上流形式」(Chat Completions / Responses)が独立して常に見えるセレクタになり、ローカルルーティングトグルは高度なサブ領域(モデルマッピングカタログ、および形式が Chat のときの推論能力)の制御だけを担います。その初期状態は保存済みカタログの有無から導かれ、永続化フィールドは増やしません。`codexConfig` の 4 言語(zh / en / ja / zh-TW)の文言もあわせて書き直しました。
|
||||
|
||||
### Doubao Seed 2.1 Pro プリセット
|
||||
|
||||
DouBaoSeed プリセットが、6 つのクライアントすべて(claude、claude-desktop、codex、opencode、openclaw、hermes)で `doubao-seed-2-1-pro` を指すようになり(`doubao-seed-2-0-code-preview-latest` を置き換え)、表示名を「Doubao Seed 2.1 Pro」に更新し、OpenClaw のコストフィールドを新モデルに合わせて 0.002 / 0.006 から 0.84 / 4.2 ドル毎 100 万 token へ訂正しました。
|
||||
|
||||
### CTok を ETok へ改名
|
||||
|
||||
ベンダーによるドメイン・endpoint・商標の改名に合わせ、ユーザーに見えるブランドをすべて CTok から ETok へ移行しました(`ctok.ai`→`etok.ai`、`api.ctok.ai`→`api.etok.ai`、および内部 id、表示名、アイコン、README パートナーバナー)。各クライアントプリセットを網羅します。Codex 履歴移行のホワイトリストでは、改名後も既存ユーザーのローカルセッション履歴が正しく分類されるよう、旧 id の `ctok` を新しい `etok` と並存させたまま残します。
|
||||
|
||||
### Kimi プリセットの命名統一
|
||||
|
||||
OpenCode と OpenClaw で以前「Kimi K2.7 Code」とマークされていた Kimi プリセットを、他のアプリと一致する「Kimi」へ改名しました(OpenCode のプロバイダー表示名もあわせて改名)。モデルラベルは引き続き「Kimi K2.7 Code」のままです。これは実際のモデルを表しているためです。
|
||||
|
||||
### JSON エディタのダークモード
|
||||
|
||||
使用量スクリプトのダイアログ、プロバイダーフォーム、ユニバーサルプロバイダーフォーム内の CodeMirror `JsonEditor` が、`useDarkMode()` を通じてアプリのテーマに追従し、`oneDark` エディタテーマへ切り替わるようになり、アプリの他の部分がすでにダークなのにライトのままになることがなくなりました。([#4556](https://github.com/farion1231/cc-switch/pull/4556))
|
||||
|
||||
### よりコンパクトな「プロバイダーを追加」のタイトルとフッターヒント
|
||||
|
||||
「プロバイダーを追加」ダイアログで、タイトルからタブ、タブからカードへの縦方向の間隔を 24px から 12px へ詰め、プリセットを選んだ後に下のフィールドを記入するよう案内する、常に見える固定フッターヒントを新設しました。`FullScreenPanel` には任意の `contentClassName` プロパティを追加し、パディングの上書きをこのパネルだけに作用させ、これを共有する他のパネルに影響しないようにしました。
|
||||
|
||||
### テーマ追従の Kimi アイコン
|
||||
|
||||
インラインの Kimi プレースホルダーマーカーを、ベンダーが刷新したアイコンへ置き換えました。K 字形は `currentColor` を使うため、テーマのテキスト色に追従し(ライトモードは濃く、ダークモードは白く)、ブランドのアクセント色は新しい `#1783FF` に固定し、メタデータのフォールバック色もそれに合わせました。
|
||||
|
||||
### Fable 5 Verified 記念バナーの削除
|
||||
|
||||
設定の「バージョン情報」ページが、3.16.3 で特別ビルドを示すためにアプリ名の隣に付けていた Fable 5 Verified 記念バナーを表示しなくなりました。バナー画像とそのマーカーを削除し、「バージョン情報」パネルは標準のバージョンバッジレイアウトに戻りました。
|
||||
|
||||
---
|
||||
|
||||
## 修正
|
||||
|
||||
### Copilot / Codex OAuth リクエストがグローバルプロキシに従うように
|
||||
|
||||
`CopilotAuthManager` と `CodexOAuthManager` は構築時に `Client::new()` をハードコードしていたため、それらの認証フロー(token の交換、`/models` リストの取得、model vendor の判定、device-code と OAuth のリフレッシュリクエスト)が設定済みのグローバルプロキシを無視し、対象サービスへ直結していました。Copilot では、直結により `/models` が Claude モデルを 0 個返し、live のモデル解決が失効し、上流が `400 model_not_supported` でリクエストを拒否していました。現在は両 manager が、リクエストのたびに共有クライアント(`crate::proxy::http_client::get()`)からその場で取得するように変更され、グローバルプロキシ URL に従い、ランタイムのホット更新にも対応します。[#2016](https://github.com/farion1231/cc-switch/issues/2016)、[#2931](https://github.com/farion1231/cc-switch/issues/2931) を修正。([#4583](https://github.com/farion1231/cc-switch/pull/4583))
|
||||
|
||||
### 圧縮されたリクエストボディとエラーボディの展開
|
||||
|
||||
Codex Desktop は Codex バックエンドへ認証するとき zstd 圧縮のリクエストボディを送ります。これがローカルプロキシのルーティングを壊していました。ハンドラーが生の圧縮バイトをそのまま `serde_json` で解析していたためです。プロキシは現在、JSON 解析の前にリクエストボディを展開し(gzip / br / deflate に加え、新たに zstd に対応、`gzip, zstd` のような積み重ねエンコーディングを含む)、3 つの Codex ハンドラーをカバーし、古くなった `content-encoding` / `content-length` / `transfer-encoding` リクエストヘッダーを剥がして転送器に再生成させます。上流の非 2xx のエラーボディも同様に展開されるため、圧縮されたレート制限や認証の詳細がクライアントに対して破棄・隠蔽されることがなくなりました。[#3764](https://github.com/farion1231/cc-switch/issues/3764)、[#3696](https://github.com/farion1231/cc-switch/issues/3696) を修正。([#3817](https://github.com/farion1231/cc-switch/pull/3817))
|
||||
|
||||
### DeepSeek endpoint で `thinking: disabled` のときの 400 エラー
|
||||
|
||||
DeepSeek の Anthropic 互換 endpoint は、`thinking.type=disabled` と effort パラメータが共存するリクエストを HTTP 400 で拒否します。これは Claude Code 2.1.166+ で `thinking: disabled` をハードコードするサブ agent(Workflow / Dynamic Workflow)を壊していました。プロキシは現在、クライアントの意図を上書きするのではなく、公式 DeepSeek endpoint に対しては競合する `output_config.effort` / `reasoning_effort` パラメータを剥がします。サブ agent はそもそも推論の表示を必要としないためです。([#4239](https://github.com/farion1231/cc-switch/pull/4239))
|
||||
|
||||
### Anthropic system メッセージの引き上げをロールバック
|
||||
|
||||
Anthropic 互換プロバイダーの `role=system` メッセージを `messages[]` からトップレベルの `system` フィールドへ引き上げる [#3775](https://github.com/farion1231/cc-switch/pull/3775) の変更をロールバックしました。DeepSeek endpoint はそもそもインラインの system メッセージをネイティブに受け付けますが、この書き換えはリクエストのプレフィックスを変えてしまいました。メッセージを元の位置に保つことで prompt プレフィックスを保持し、一見キャッシュヒット率の後退と思われる現象を回避します([#4297](https://github.com/farion1231/cc-switch/issues/4297) を参照)。#3775 由来の、無関係な Windows テスト修正と tool-thinking-history の正規化は残します。
|
||||
|
||||
### Chat ツール呼び出しの関数名欠落
|
||||
|
||||
一部の上流は、ストリーミングのツール呼び出し増分で空の、または欠落した関数名を送ります。これは以前、無効な Codex Chat の出力項(または `unknown_tool` フォールバック)を生んでいました。現在は累積したツール呼び出し状態が空の増分で上書きされることがなくなり、最後まで `call_id` と有効な名前を得られなかったツール呼び出しは最終化フェーズでスキップされます。ストリーミング、非ストリーミング、旧版 `function_call` の 3 経路をカバーします。([#4159](https://github.com/farion1231/cc-switch/pull/4159))
|
||||
|
||||
### Codex のキャッシュされたツール呼び出しフィールドの復元
|
||||
|
||||
Codex が `previous_response_id` を参照する後続の Chat リクエストを発行するとき、その `function_call` 項が `call_id` だけを携える場合があります。履歴拡張は以前 `reasoning` / `reasoning_content` だけをバックフィルし、関数の `name`、`arguments`、`status` などのフィールドを空のまま残していました。現在は履歴からキャッシュされたツール呼び出しフィールドをすべて復元し、その呼び出しを Chat 上流向けに正しく再構築できるようにします。([#4160](https://github.com/farion1231/cc-switch/pull/4160))
|
||||
|
||||
### config.toml 内の重複した Codex base_url 項
|
||||
|
||||
Codex の `base_url` を `config.toml` へ書き込むとき、以前は各セクションで一致する代入を 1 つだけ置換または削除していたため、すでに複数行の `base_url` を含むセクションでは余分な項が残り、重複が累積していました。`setCodexBaseUrl` は現在、対象セクションまたはトップレベルの一致をすべて折りたたみ(最初の 1 つを置換し、残りを削除)、TOML の `base_url` 正規表現もエスケープされた引用符を処理します。([#4316](https://github.com/farion1231/cc-switch/pull/4316))
|
||||
|
||||
### 履歴移行が CODEX_SQLITE_HOME の状態 DB をプローブ
|
||||
|
||||
Codex セッション履歴の移行は、以前 `~/.codex/state_5.sqlite` と `config.toml` の `sqlite_home` の場所だけをスキャンしていたため、Codex の SQLite 状態が `CODEX_SQLITE_HOME` 環境変数で再配置されたとき、状態 DB は一度もスキャンされず、その threads は古いプロバイダーバケットに残ったままでした。サードパーティ移行と統一セッション移行の両方が共有する `codex_state_db_paths` ヘルパーが、現在は `CODEX_SQLITE_HOME` へフォールバックします(`config` 内の `sqlite_home` は引き続き優先)。
|
||||
|
||||
### プロバイダーターミナルがユーザーの shell を尊重
|
||||
|
||||
macOS / Linux でプロバイダーターミナルを起動するとき、以前は `bash` をハードコードしていたため、zsh / fish ユーザーの rc ファイルが読み込まれませんでした。ランチャーは現在、`$SHELL` からユーザーの既定 shell を検出し(macOS は `/bin/zsh`、Linux は `/bin/bash` へフォールバック)、クリーンスタートのフラグ付きで exec します。一方、起動スクリプト自体は移植性のために POSIX `sh` を使うようにしました(fish や、`/bin/sh` が存在しないことのある NixOS など)。([#4140](https://github.com/farion1231/cc-switch/pull/4140)、[#1546](https://github.com/farion1231/cc-switch/issues/1546) を修正)
|
||||
|
||||
### Claude MCP のパスがカスタム設定ディレクトリを尊重
|
||||
|
||||
カスタムの Claude 設定ディレクトリが設定されているとき、MCP server の読み書きが、既定の場所ではなくそのディレクトリ配下の MCP ファイルへ解決されるようになり、MCP の状態が profile ごとに分離されます。旧ファイルに対する以前の「アクセス時コピー」移行は削除し、オーバーライドパスへ直接解決するようにしました。([#3431](https://github.com/farion1231/cc-switch/pull/3431))
|
||||
|
||||
### 検索後にプリセット結果をクリック可能に
|
||||
|
||||
「プロバイダーを追加」のプリセットセレクタで検索した後、結果がクリックも選択もできなくなることがありました。入力と競合して先頭文字を飲み込んでいた(「gateway」→「ateway」など)`requestAnimationFrame` の `select()` を削除し、すぐクリックできる経路の入力オートフォーカスを復元し、検索ボックスが開いているときに Ctrl/Cmd+F を押せば再フォーカスするようにもしました。プロバイダーリストのタイピングガードも Ctrl/Cmd+F 分岐に絞り込み、Escape で引き続き検索パネルを閉じられるようにしました。([#4315](https://github.com/farion1231/cc-switch/pull/4315))
|
||||
|
||||
### Skills ブラウズとプロバイダーカードの表示修正
|
||||
|
||||
いくつかの表示とインタラクションの問題を修正しました: skills.sh をブラウズ中もリポジトリ管理操作が引き続き使え、リポジトリが空の結果を返したときも更新が引き続き使え、プロバイダーカード上の長すぎるプロバイダー名やウェブサイト URL があふれずに切り詰められ、OMO のモデル変種ドロップダウンが選択ラベルを切り詰めて完全な内容をツールチップで示し、Select のメニュー項目が現在選択中の項目にチェックマークを表示します。([#4323](https://github.com/farion1231/cc-switch/pull/4323))
|
||||
|
||||
### 設定タブ切り替え時のスクロールリセット
|
||||
|
||||
設定ダイアログ内でタブを切り替えると前のタブのスクロール位置が引き継がれ、新しいタブの途中で止まることがありました。現在はアクティブなタブが変わるたびに、スクロールコンテナがトップへリセットされます。([#4165](https://github.com/farion1231/cc-switch/pull/4165))
|
||||
|
||||
---
|
||||
|
||||
## ドキュメント
|
||||
|
||||
### Kimi ピン留めスポンサーバナー
|
||||
|
||||
4 言語すべての README(en / zh / ja / de)の冒頭のピン留めスポンサーバナーが、これまでの MiniMax M2.7 バナーに代わって Kimi K2.7 Code になりました。文言は K2.7 Code のリリース(コーディング向けの agentic モデルで、思考 token の使用量が K2.6 比で約 30% 低減)を反映し、バナーは Moonshot CDN ではなくリポジトリ内のリソース(`assets/partners/banners/kimi-banner-en.png` / `kimi-banner-zh.png`)から提供し、`aff=cc-switch` の Moonshot コンソールを指すクリック可能な行動喚起を添えました。
|
||||
|
||||
### Codex 統一セッション履歴ガイド
|
||||
|
||||
3 言語(zh / en / ja)のガイドを新設し、Codex 統一セッション履歴トグルの有効化時の移行(有効化時)と台帳に基づく復元(無効化時)が実際に何をするのか、なぜセッションデータが本当に削除されないのか(マーカーの変更 + 自動バックアップのみ)、そしてファイルが本当にディスク上にあるのか、それとも別のプロバイダードロワーに分類されただけなのかを照合する方法を解説しました。「セッションが消えた」という、よくある誤解に対する症状の対照表と、macOS / Linux / Windows のディスク照合コマンドを含み、v3.16.3 の「利用ガイド」release notes の冒頭項としてリンクしました。
|
||||
|
||||
### Homebrew インストール手順の簡素化
|
||||
|
||||
インストールガイドが、`brew install --cask cc-switch` の前に `brew tap farion1231/ccswitch` を実行するようユーザーに求めなくなりました。この廃止された tap 手順を en / ja / zh のユーザーマニュアルから削除し、cask を直接インストールできるようにしました。([#4319](https://github.com/farion1231/cc-switch/pull/4319))
|
||||
|
||||
### Star-History 世界ランキングバッジ
|
||||
|
||||
4 言語すべての README で、既存の Trendshift バッジの隣に star-history の世界ランキングバッジを新設し、ライト / ダークテーマの変種を付けました。
|
||||
|
||||
### 火山方舟 Coding Plan キャンペーンリンク
|
||||
|
||||
ByteDance / 火山方舟スポンサー項目内の「中国本土の開発者はこちらをクリック」リンクが、これまでの `codingplan` 紹介 URL に代わって火山の `ai618` キャンペーンページを指すようになり、4 言語すべての README をカバーします。
|
||||
|
||||
### CCSub スポンサーバナーのベクター素材
|
||||
|
||||
低解像度の `ccsub.jpg` スポンサーロゴをベクターの `ccsub.svg` へ置き換え、2046x648 のレターボックスから 2046x850(約 2.406:1)へ拡げ、他のスポンサー表バナーと揃えて同じ 62px の高さで描画されるようにしました。4 言語すべての README が新しい素材を指します。
|
||||
|
||||
---
|
||||
|
||||
## アップグレード時の注意
|
||||
|
||||
### 国産 Codex プロバイダーのネイティブ Responses 移行
|
||||
|
||||
本リリースは、ネイティブ Responses endpoint を備える複数の国産プロバイダー(千問 / 百炼、小米 MiMo、火山 Doubao、美団 LongCat、MiniMax 国内 / 国際)の Codex プリセットを `openai_responses` へ切り替え、`modelCatalog` を削除しました。すでにこれらのプリセットをもとに設定済みの既存プロバイダーは影響を受けず、設定はそのまま保たれます。ネイティブ Responses(形式変換テイクオーバーを省く)へ切り替えたい場合は、プリセットからもう一度選び直して保存してください。SiliconFlow がホストする MiniMax は引き続き `openai_chat` を使い、今回の移行の対象外です。
|
||||
|
||||
### データベースのバージョンが新しすぎる場合の復旧
|
||||
|
||||
より高いバージョンの CC Switch でデータベースを開いた後、旧版へ戻した場合、旧版は起動時に新しい「データベースのバージョンが新しすぎる」リカバリ画面に入り、そのデータベースを読めるバージョンへのアップグレードへ案内します。これは期待される動作です——最新版へアップグレードすれば正常に戻ります。
|
||||
|
||||
---
|
||||
|
||||
## リスク通知
|
||||
|
||||
本リリースは、リバースプロキシ系機能に関する以前のリスク通知を引き続き適用します。
|
||||
|
||||
**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションの Codex OAuth をリバースプロキシ経由で使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 release notes](v3.13.0-ja.md#️-リスクに関する注意事項) を参照してください。
|
||||
|
||||
**Codex サードパーティプロバイダー Chat ルーティング**: CC Switch ローカルプロキシで Codex リクエストを変換し、サードパーティプロバイダーへ転送する場合、課金・コンプライアンス・データ保持に関する制約はプロバイダーごとに異なります。利用前に対象プロバイダーの利用規約を確認してください。
|
||||
|
||||
**Claude Desktop サードパーティプロバイダープロキシ切り替え**: CC Switch 内蔵のプロキシゲートウェイで Claude Desktop のリクエストをサードパーティプロバイダーへ転送する場合も、対象プロバイダーの課金・コンプライアンス・データ保持に関する規約に従う必要があります。
|
||||
|
||||
上記機能を有効化したユーザーは、関連するリスクを自ら負うものとします。CC Switch は、これらの機能の利用によって発生したアカウント制限、警告、サービス停止について責任を負いません。
|
||||
|
||||
---
|
||||
|
||||
## 謝辞
|
||||
|
||||
v3.16.4 で機能と修正を届けてくださった以下のコントリビューターに感謝します:
|
||||
|
||||
- [#3817](https://github.com/farion1231/cc-switch/pull/3817): 転送前にリクエストボディを展開し zstd に対応、@chenx-dust に感謝。
|
||||
- [#4583](https://github.com/farion1231/cc-switch/pull/4583): Copilot / Codex OAuth モジュールがグローバルプロキシをバイパスし Claude モデルが 400 になる問題を修正、@zymouse に感謝。
|
||||
- [#4589](https://github.com/farion1231/cc-switch/pull/4589): ローカルプロキシのリクエストオーバーライド(カスタムリクエストヘッダーとリクエストボディ)を追加、@mfzzf に感謝。
|
||||
- [#4575](https://github.com/farion1231/cc-switch/pull/4575): データベースのバージョンが新しすぎる場合のアプリ内リカバリ画面を追加、@SaladDay に感謝。
|
||||
- [#4556](https://github.com/farion1231/cc-switch/pull/4556): 複数箇所の JsonEditor にダークモードを導入、@TanKimzeg に感謝。
|
||||
- [#4438](https://github.com/farion1231/cc-switch/pull/4438): カスタム日付範囲のリアルタイム終了時刻を追加、@arichyx に感謝。
|
||||
- [#3950](https://github.com/farion1231/cc-switch/pull/3950): Windows ARM64 リリースのサポートを追加、@MOON-DREAM-STARS に感謝。
|
||||
- [#4401](https://github.com/farion1231/cc-switch/pull/4401): Kimi For Coding プリセットに CLAUDE_CODE_AUTO_COMPACT_WINDOW を追加、@cyijun に感謝。
|
||||
- [#4323](https://github.com/farion1231/cc-switch/pull/4323): Skills 管理とモデル設定のインタラクション表示を修正、@thisTom に感謝。
|
||||
- [#3431](https://github.com/farion1231/cc-switch/pull/3431): カスタム設定ディレクトリの Claude MCP パスを揃える、@makoMakoGo に感謝。
|
||||
- [#4159](https://github.com/farion1231/cc-switch/pull/4159): 関数名を欠く Chat ツール呼び出しをスキップ、@hueifeng に感謝。
|
||||
- [#4385](https://github.com/farion1231/cc-switch/pull/4385): glm-5.2 の価格を追加、@arichyx に感謝。
|
||||
- [#4079](https://github.com/farion1231/cc-switch/pull/4079): models.dev からのモデル価格インポートに対応、@kingcanfish に感謝。
|
||||
- [#4315](https://github.com/farion1231/cc-switch/pull/4315): プリセット検索後に結果をクリック選択できない問題を修正、@RuixeWolf に感謝。
|
||||
- [#4316](https://github.com/farion1231/cc-switch/pull/4316): 重複した Codex base_url 項を防止、@jeffwcx に感謝。
|
||||
- [#4140](https://github.com/farion1231/cc-switch/pull/4140): プロバイダーターミナルがユーザーの shell を尊重するように、@zkforge に感謝。
|
||||
- [#4113](https://github.com/farion1231/cc-switch/pull/4113): セッション詳細ヘッダーにソースファイル名を表示、@xu-song に感謝。
|
||||
- [#4160](https://github.com/farion1231/cc-switch/pull/4160): Codex のキャッシュされたツール呼び出しフィールドを復元、@chen-985211 に感謝。
|
||||
- [#4239](https://github.com/farion1231/cc-switch/pull/4239): DeepSeek endpoint で thinking:disabled のとき effort パラメータを剥がす、@maskshell に感謝。
|
||||
- [#4165](https://github.com/farion1231/cc-switch/pull/4165): 設定タブ切り替え時にスクロールをリセット、@Muleizhang に感謝。
|
||||
- [#4319](https://github.com/farion1231/cc-switch/pull/4319): 廃止された Homebrew tap 手順を削除、@tianpeng-dev に感謝。
|
||||
- [#4522](https://github.com/farion1231/cc-switch/pull/4522): SubRouter プロバイダープリセットを追加、@abingyyds に感謝。
|
||||
|
||||
v3.16.3 リリース後に Codex プロキシ経路、使用量の課金、ローカルプロキシの堅牢性、プラットフォーム互換性の問題を報告してくださったすべてのユーザーにも感謝します。今回の多くのパッチは、こうした実際の利用シーンから得られた再現の手がかりに基づいています。
|
||||
|
||||
---
|
||||
|
||||
## ダウンロードとインストール
|
||||
|
||||
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から、お使いのシステムに対応するビルドをダウンロードしてください。
|
||||
|
||||
### システム要件
|
||||
|
||||
| システム | 最低バージョン | アーキテクチャ |
|
||||
| -------- | ------------------------ | ----------------------------------- |
|
||||
| Windows | Windows 10 以降 | x64 / ARM64 |
|
||||
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 下表を参照 | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ---------------------------------------- | -------------------------------------------- |
|
||||
| `CC-Switch-v3.16.4-Windows.msi` | **推奨** - 自動更新対応の MSI インストーラー |
|
||||
| `CC-Switch-v3.16.4-Windows-Portable.zip` | ポータブル版、展開してそのまま実行できます |
|
||||
|
||||
Windows ARM64 デバイスをお使いの場合は、ファイル名に `arm64` 識別子が含まれる対応する制品を選択してください。
|
||||
|
||||
### macOS
|
||||
|
||||
| ファイル | 説明 |
|
||||
| -------------------------------- | ------------------------------------------------------ |
|
||||
| `CC-Switch-v3.16.4-macOS.dmg` | **推奨** - DMG インストーラー、Applications へドラッグ |
|
||||
| `CC-Switch-v3.16.4-macOS.zip` | 展開して Applications へドラッグ、Universal Binary |
|
||||
| `CC-Switch-v3.16.4-macOS.tar.gz` | Homebrew インストールと自動更新用 |
|
||||
|
||||
Homebrew インストール:
|
||||
|
||||
```bash
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
Linux アセットは **x86_64** と **ARM64**(`aarch64`)の両方を提供します。ファイル名にアーキテクチャ識別子が含まれているため、マシンの `uname -m` 出力に合わせて選択してください:
|
||||
|
||||
- `CC-Switch-v3.16.4-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.16.4-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
| ディストリビューション | 推奨形式 | インストール方法 |
|
||||
| --------------------------------------- | ----------- | ------------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 実行権限を付与して直接起動、または AUR を使用 |
|
||||
| その他 / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
</content>
|
||||
</invoke>
|
||||
@@ -0,0 +1,351 @@
|
||||
# CC Switch v3.16.4
|
||||
|
||||
> 继 v3.16.3 把「用量计费做准」之后,这一版把重心放在打磨 Codex 代理链路与丰富用量 / 定价工具上——国产供应商原生 Responses 迁移、上游格式选择器与模型映射解耦、zstd 请求 / 错误体解压,以及一批工具调用与 OAuth 走代理的修复;同时新增本地代理请求覆盖、数据库版本过新时的应用内恢复屏、原生 Windows ARM64 构建,并带来一波预设与品牌更新(SubRouter、OpenCode Go、CTok→ETok 改名、Kimi 品牌刷新与 prime-partner 徽标)。
|
||||
|
||||
**[English →](v3.16.4-en.md) | [日本語版 →](v3.16.4-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## 使用攻略
|
||||
|
||||
本版以打磨与扩展为主,新增的能力主要落在用量面板与供应商表单的高级选项里,建议结合以下文档了解:
|
||||
|
||||
- **[Codex 桌面看不到自定义模型?](../guides/codex-desktop-custom-model-visibility-zh.md)**:不少用户反馈在 Codex 桌面应用里看不到配置的第三方 / 自定义模型。这是 Codex 桌面应用**上游自身的门控行为**(按官方登录状态放行模型选择器),并非 CC Switch 的本地配置问题,**本版(v3.16.4)未对此做改动**;文档里说明了原因,以及可用的缓解办法(保留官方登录 + 路由接管)。
|
||||
- **[用量统计](../user-manual/zh/4-proxy/4.4-usage.md)**:了解用量看板的数据来源与统计口径。本版新增了从 models.dev 批量导入模型定价、火山方舟 Coding / Agent Plan 的 AK/SK 用量查询,以及自定义日期范围的「实时结束时间」。
|
||||
- **[设置](../user-manual/zh/1-getting-started/1.5-settings.md)**:本地代理请求覆盖(自定义请求头 / 请求体)、Codex 上游格式选择器与本地路由开关等都在供应商表单的高级选项里。
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## 唯一官方渠道声明(请务必阅读)
|
||||
>
|
||||
> CC Switch 是**完全免费、开源**的桌面应用,**不会向用户收取任何费用**。请仅通过下列官方渠道获取本软件:
|
||||
>
|
||||
> | 类别 | 唯一官方 |
|
||||
> | -------- | ------------------------------------------------------------------------------ |
|
||||
> | 官网 | **[ccswitch.io](https://ccswitch.io)** |
|
||||
> | 源码 | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
|
||||
> | 下载 | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
|
||||
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
|
||||
> | 举报山寨 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
|
||||
>
|
||||
> **任何向你收费、要求充值、或索取登录凭据的"CC Switch"网站或客户端均为假冒**。如果你被诱导支付了费用,请立即停止操作并通过 GitHub Issues 反馈。
|
||||
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
CC Switch v3.16.4 是 v3.16.3 之后的一版维护更新。这一版围绕 Codex 代理链路做了一轮收紧——为多家具备原生 OpenAI Responses 端点的国产供应商切换到原生格式(省去 Responses→Chat 的路由接管转换)、把「上游格式」从「本地路由」开关里独立出来、补上 zstd 请求与错误响应体的解压,并修了一串工具调用与「OAuth 模块绕过全局代理」的问题。
|
||||
|
||||
与此同时,本版还丰富了用量与定价工具(从 models.dev 导入定价、火山方舟 Coding / Agent Plan 的 AK/SK 用量查询、自定义日期范围的实时结束时间、GLM-5.2 与豆包 Seed 2.1 定价),新增了一批代理与韧性能力(自定义请求头 / 请求体覆盖、数据库版本过新时的应用内恢复屏、原生 Windows ARM64 构建),并带来一波预设与品牌更新(SubRouter 与 OpenCode Go 订阅、CTok→ETok 改名、Kimi 品牌刷新与 prime-partner 徽标、Kimi K2.7 Code 赞助横幅)。
|
||||
|
||||
**发布日期**:2026-06-27
|
||||
|
||||
**更新规模**:53 commits | 126 files changed | +8,149 / -1,016 lines
|
||||
|
||||
---
|
||||
|
||||
## 重点内容
|
||||
|
||||
- **国产 Codex 供应商走原生 Responses**:千问 / 百炼、小米 MiMo、火山豆包、美团 LongCat、MiniMax(国内 / 国际)现在直连各自的原生 Responses 端点,不再经过 Responses→Chat 的格式转换接管,链路更短、更稳。
|
||||
- **本地代理请求覆盖**:供应商可配置自定义请求头与请求体覆盖,由本地代理在转发时应用,并对受保护的安全请求头做了拦截校验。
|
||||
- **数据库版本过新的应用内恢复屏**:当 SQLite 版本比当前应用支持的更新时,不再死在「重试只会再次失败」的原生弹窗里,而是引导到一个可一键升级应用的恢复界面。
|
||||
- **更丰富的用量 / 定价工具**:从 models.dev 批量导入模型定价、火山方舟 Coding / Agent Plan 的 AK/SK 用量查询、自定义日期范围的「实时结束时间」,以及 GLM-5.2 与豆包 Seed 2.1 的定价。
|
||||
- **新预设与品牌更新**:新增 SubRouter 与 OpenCode Go 订阅预设,CTok 改名为 ETok,刷新 Kimi 品牌标识并为官方 Kimi 预设加上 prime-partner 心形徽标。
|
||||
- **原生 Windows ARM64 构建**:发布产物新增原生 ARM64 版本,ARM 架构的 Windows 设备不再依赖 x64 模拟。
|
||||
|
||||
---
|
||||
|
||||
## 新功能
|
||||
|
||||
### 数据库版本过新时的应用内恢复屏
|
||||
|
||||
当 SQLite 的 `user_version` 比当前应用支持的 `SCHEMA_VERSION` 更新时(例如降级回旧版、或被第三方客户端写过该文件),启动过去会死在一个原生的「重试 / 退出」弹窗里——而「重试」只会再次失败。现在应用会引导到一个专门的恢复界面:有可用更新时提供一键「升级应用」按钮(下载 + 安装 + 重启,带进度条),没有可用更新时则提示即便是最新版也读不了这个数据库。该「版本过新」检查在任何写库动作之前进行,因此应用永远不会对一个读不懂的数据库执行 DDL;恢复模式下的原生关闭会干净退出(此时托盘尚未创建)。([#4575](https://github.com/farion1231/cc-switch/pull/4575))
|
||||
|
||||
### 本地代理请求覆盖(自定义请求头与请求体)
|
||||
|
||||
供应商配置现在可以定义自定义请求头与请求体覆盖,由本地代理在转发时应用,并通过 Claude 与 Codex 供应商表单里的新字段暴露。输入会经过校验,其中包含一份受保护的请求头名单,用于阻止覆盖安全敏感的请求头。([#4589](https://github.com/farion1231/cc-switch/pull/4589))
|
||||
|
||||
### 火山方舟 Coding / Agent Plan 用量查询
|
||||
|
||||
用量面板现在可以查询火山方舟(Volcengine Ark)的 Coding Plan 与 Agent Plan 配额。由于方舟控制面 OpenAPI(`open.volcengineapi.com`)要求的是账号级 AccessKey 签名、而非推理 API key,用量脚本新增了独立的 AK/SK 输入区,并配有一个直达火山 IAM 密钥管理控制台(`https://console.volcengine.com/iam/keymanage`)的可点击链接;代理实现了火山签名 V4(一个 AWS SigV4 变体:固定的 canonical header 顺序、`HMAC-SHA256` 算法、`ark` 服务 scope)。它会先探测 `GetAFPUsage`(Agent Plan 的 5 小时 / 周 / 月配额)自动判定套餐,失败再回退到 `GetCodingPlanUsage`,从 `Level` 字段解析窗口标签(并对 `ResetTimestamp <= 0` 做守卫),同时在用量页脚、托盘菜单与四种语言里补上了 `monthly` 档标签。
|
||||
|
||||
### 从 models.dev 导入模型定价
|
||||
|
||||
「添加定价」面板新增了一个「从 models.dev 导入」按钮:拉取 `https://models.dev/api.json`,支持全文搜索整个目录,并通过与手动录入相同的 `update_model_pricing` 路径导入所选条目。导入的 model id 会按后端的 `clean_model_id_for_pricing` 规则归一化(剥供应商前缀、转小写、截断 `:` 后缀、把 `@` 映射为 `-`、丢掉 `[1m]` 标记),让落库的行真正能匹配成本归因查询。配套修复让「按范围回填零成本」改用 Rust 端按原始 model 别名(路由前缀、`:free` 变体、日期后缀)匹配,而不再用精确 SQL 字符串匹配,从而新定价的别名行能立刻被计价、而不必等下次启动回填(修复 [#4017](https://github.com/farion1231/cc-switch/issues/4017))。([#4079](https://github.com/farion1231/cc-switch/pull/4079))
|
||||
|
||||
### 原生 Windows ARM64 构建
|
||||
|
||||
发布产物现在包含原生的 Windows ARM64 制品,ARM 架构的 Windows 设备可以拿到对应的原生构建,不必再依赖 x64 模拟。发布矩阵也改为各平台独立运行(关闭 fail-fast),因此某个任务缺少密钥而失败(例如 fork 里的 macOS 签名)不会再把尚未完成的同级任务一并取消。([#3950](https://github.com/farion1231/cc-switch/pull/3950))
|
||||
|
||||
### 自定义日期范围的实时结束时间
|
||||
|
||||
自定义日期范围选择器新增了一个「结束时间跟随当前时间」勾选框;开启后结束时间变为只读并自动跟随此刻,因此用量数据始终反映从所选起点到当下的实时消耗。这在 Coding Plan 的 5 小时配额窗口里尤其有用。`liveEndTime` 已纳入 React Query 的缓存键,因此一个实时范围和一个端点相同的固定范围不会再共用同一个陈旧缓存项。([#4438](https://github.com/farion1231/cc-switch/pull/4438))
|
||||
|
||||
### 会话详情头显示源文件名
|
||||
|
||||
会话详情头现在会在项目目录旁显示会话日志的文件名(悬停看完整路径、可点击复制),方便用户直接从界面定位并打开底层的 JSONL 文件。对于像 ~70 字符的 Codex rollout 这类没有空格的长文件名,会截断到 `max-w-[200px]`,避免在窄窗口里溢出到操作按钮区。([#4113](https://github.com/farion1231/cc-switch/pull/4113))
|
||||
|
||||
### 导入按钮的未托管 Skill 提示
|
||||
|
||||
顶栏的 Skills 导入按钮现在会在本地存在未托管的 Skill 可导入时显示一个绿点与提示,让你一眼看出磁盘上的 Skill 还没被纳管。该扫描在挂载时执行一次,并在多次导航间共享(30s `staleTime` + `keepPreviousData`),避免重复磁盘 IO。
|
||||
|
||||
### OpenCode Go 订阅预设
|
||||
|
||||
新增 OpenCode Go(`opencode.ai/zen/go`)预设,覆盖 Claude、Codex 与 OpenCode,使用可直接粘贴的纯 API key(无 OAuth)。Codex 预设走 `openai_chat` 转换并带 GLM / Kimi / DeepSeek / MiMo 模型目录(且不带静态 `codexChatReasoning`,按每个模型推断能力),OpenCode 则通过 `@ai-sdk/openai-compatible` 指向 `/zen/go/v1`。四个 OpenCode Go 预设——Claude、Claude Desktop、Codex、OpenCode——都带上了推荐链接与应用内推广文案;推广横幅现在仅凭 `partnerPromotionKey` 即可展示(不再绑定 `isPartner`),因此一个预设可以展示推荐推广却不获得金色付费合作伙伴星标(这也顺带让既有的 MiniMax 推广重新显示出来)。
|
||||
|
||||
### Prime-Partner 预设徽标与排序
|
||||
|
||||
第一方 Moonshot Kimi 预设(Kimi / Kimi For Coding / Kimi K2.7 Code)现在被标记为 prime partner:不再显示金色星标,而是渲染一颗实心金色心形(无徽标边框),并在默认(Original)排序里浮到官方分类预设之后、其余之前。分组用三路 partition 实现,每组保持内部顺序,且一个同时被标为 prime-partner 的官方预设只会留在官方组里。
|
||||
|
||||
### GLM-5.2 与豆包 Seed 2.1 定价
|
||||
|
||||
种子模型定价现在包含 GLM-5.2([#4385](https://github.com/farion1231/cc-switch/pull/4385))与豆包 Seed 2.1 Pro / Turbo,让这些模型的用量被正确计价、而不是记成零成本。豆包价格采用火山官方 list 价(按约 7.14 的汇率折算);`cache_creation` 保持为 0,因为豆包按时间而非按 token 写入计费缓存存储,既有的 2.0 行也保留以供历史记账。
|
||||
|
||||
### Kimi For Coding 自动压缩窗口
|
||||
|
||||
Kimi For Coding 预设现在把 `CLAUDE_CODE_AUTO_COMPACT_WINDOW` 默认设为 262144,与 Kimi 官方文档一致,并通过 `templateValues` 暴露,方便用户为将来的模型或性能调优自定义该值。([#4401](https://github.com/farion1231/cc-switch/pull/4401))
|
||||
|
||||
### SubRouter 合作伙伴供应商
|
||||
|
||||
新增 SubRouter(`subrouter.ai`,一个让一把 key 访问多模型多供应商的 AI 中转聚合商)作为预设,覆盖全部 7 个受管应用——Anthropic 格式端点用于 Claude Code / Claude Desktop / OpenClaw / Hermes,OpenAI 兼容的 `/v1` 端点(`gpt-5.5`)用于 Codex 与 OpenCode,Gemini 兼容的 `/v1beta` 端点(`gemini-3.5-flash`)用于 Gemini CLI——带上自有品牌图标、金色合作伙伴星标、四语推广文案,以及预填为 API key 注册地址的推荐注册链接(`?aff=l3ri`)。([#4522](https://github.com/farion1231/cc-switch/pull/4522))
|
||||
|
||||
---
|
||||
|
||||
## 变更
|
||||
|
||||
### 国产 Codex 供应商走原生 Responses API
|
||||
|
||||
多家国产供应商(千问 / DashScope 百炼、小米 MiMo、火山豆包、美团 LongCat、MiniMax 国内 / 国际)现在暴露了原生的 OpenAI Responses 端点,因此它们的 Codex 预设切换到 `apiFormat: "openai_responses"`,直连上游而不再经过 Responses→Chat 的路由接管转换。丢掉不再需要的 `codexChatReasoning` 与 `modelCatalog` 也让「本地路由映射」开关默认保持未勾选。SiliconFlow 托管的 MiniMax 仍保持 `openai_chat`,因为那是第三方端点、并非 MiniMax 自家 base_url。其余仍走 chat 的供应商也刷新了过期的 model id(GLM 5.1→5.2、StepFun 3.5-flash-2603→3.7-flash、Ling 2.5-1T→2.6-1T)。
|
||||
|
||||
### 上游格式选择器与模型映射开关解耦
|
||||
|
||||
Codex 供应商表单此前把 Chat 格式转换与路由接管(模型映射)绑在同一个开关上,导致一个提供原生 Responses API 的供应商无法在不强制 Chat Completions 转换的情况下使用模型映射。现在「上游格式」(Chat Completions / Responses)成了一个独立、始终可见的选择器,而本地路由开关只负责控制高级子区(模型映射目录,以及格式为 Chat 时的推理能力)。它的初始状态由已保存目录是否存在派生,不新增持久化字段;`codexConfig` 的四语(zh / en / ja / zh-TW)文案也随之重写。
|
||||
|
||||
### 豆包 Seed 2.1 Pro 预设
|
||||
|
||||
DouBaoSeed 预设现在在全部 6 个客户端(claude、claude-desktop、codex、opencode、openclaw、hermes)指向 `doubao-seed-2-1-pro`(替换 `doubao-seed-2-0-code-preview-latest`),展示名更新为「Doubao Seed 2.1 Pro」,并把 OpenClaw 的成本字段从 0.002 / 0.006 订正为 0.84 / 4.2 美元每百万 token 以匹配新模型。
|
||||
|
||||
### CTok 改名为 ETok
|
||||
|
||||
随着厂商对域名、端点与商标的更名,所有面向用户的品牌从 CTok 迁移到 ETok(`ctok.ai`→`etok.ai`、`api.ctok.ai`→`api.etok.ai`,以及内部 id、展示名、图标和 README 合作伙伴横幅),覆盖每一个客户端预设。Codex 历史迁移白名单里仍保留 `ctok` 作为旧 id、与新 `etok` 并存,以保证改名后存量用户的本地会话历史仍被正确分桶。
|
||||
|
||||
### Kimi 预设命名统一
|
||||
|
||||
OpenCode 与 OpenClaw 此前被标为「Kimi K2.7 Code」的 Kimi 预设,更名为与其它应用一致的「Kimi」(OpenCode 的供应商展示名也一并更名);模型标签仍保留「Kimi K2.7 Code」,因为它描述的是实际模型。
|
||||
|
||||
### JSON 编辑器暗色模式
|
||||
|
||||
用量脚本弹窗、供应商表单与通用供应商表单里的 CodeMirror `JsonEditor` 现在会通过 `useDarkMode()` 跟随应用主题,切换到 `oneDark` 编辑器主题,而不再在应用其余部分已是暗色时仍停留在亮色。([#4556](https://github.com/farion1231/cc-switch/pull/4556))
|
||||
|
||||
### 更紧凑的「添加供应商」标题与底部提示
|
||||
|
||||
「添加供应商」对话框把标题到页签、页签到卡片的纵向间距从 24px 收到 12px,并新增一个始终可见的固定底部提示,引导用户在选好预设后填写下方字段。`FullScreenPanel` 新增可选的 `contentClassName` 属性,让内边距覆盖只作用于此面板、不影响其它共用它的面板。
|
||||
|
||||
### 主题自适应的 Kimi 标识
|
||||
|
||||
内联的 Kimi 占位标记替换为厂商刷新后的标识。K 字形使用 `currentColor`,因此会跟随主题文字色(亮色模式深、暗色模式白),而品牌点缀色固定为新的 `#1783FF`,元数据回退色也相应对齐。
|
||||
|
||||
### 移除 Fable 5 Verified 纪念横幅
|
||||
|
||||
设置「关于」页不再显示 3.16.3 为标明特别构建而加在应用名旁的 Fable 5 Verified 纪念横幅;横幅图片及其标记被移除,「关于」面板回到标准的版本徽标布局。
|
||||
|
||||
---
|
||||
|
||||
## 修复
|
||||
|
||||
### Copilot / Codex OAuth 请求现在遵循全局代理
|
||||
|
||||
`CopilotAuthManager` 与 `CodexOAuthManager` 在构造时写死了 `Client::new()`,导致它们的认证流程(换 token、拉 `/models` 列表、判定 model vendor、device-code 与 OAuth 刷新请求)无视配置的全局代理、直连目标服务。在 Copilot 上,直连会让 `/models` 返回 0 个 Claude 模型,使 live 模型解析失效,上游以 `400 model_not_supported` 拒绝请求。现在两个 manager 都改为每次请求从共享客户端现取(`crate::proxy::http_client::get()`),从而遵循全局代理 URL 并支持运行时热更新。修复 [#2016](https://github.com/farion1231/cc-switch/issues/2016)、[#2931](https://github.com/farion1231/cc-switch/issues/2931)。([#4583](https://github.com/farion1231/cc-switch/pull/4583))
|
||||
|
||||
### 压缩请求体与错误体的解压
|
||||
|
||||
Codex Desktop 在对 Codex 后端认证时会发送 zstd 压缩的请求体,这会破坏本地代理路由,因为处理器直接用 `serde_json` 解析原始压缩字节。代理现在会在 JSON 解析前对请求体解压(gzip / br / deflate,外加新增的 zstd 支持,包括 `gzip, zstd` 这类堆叠编码),覆盖三个 Codex 处理器,并剥掉过期的 `content-encoding` / `content-length` / `transfer-encoding` 请求头让转发器重新生成。上游非 2xx 的错误体也以同样方式解压,因此压缩过的限流与鉴权细节不再被丢弃、对客户端隐藏。修复 [#3764](https://github.com/farion1231/cc-switch/issues/3764)、[#3696](https://github.com/farion1231/cc-switch/issues/3696)。([#3817](https://github.com/farion1231/cc-switch/pull/3817))
|
||||
|
||||
### DeepSeek 端点 `thinking: disabled` 的 400 错误
|
||||
|
||||
DeepSeek 的 Anthropic 兼容端点会拒绝 `thinking.type=disabled` 与 effort 参数共存的请求、返回 HTTP 400,这会破坏 Claude Code 2.1.166+ 那些硬编码 `thinking: disabled` 的子 agent(Workflow / Dynamic Workflow)。代理现在不是去覆盖客户端的意图,而是对官方 DeepSeek 端点剥掉冲突的 `output_config.effort` / `reasoning_effort` 参数,因为子 agent 本就不需要展示推理。([#4239](https://github.com/farion1231/cc-switch/pull/4239))
|
||||
|
||||
### 回滚 Anthropic system 消息上提
|
||||
|
||||
回滚了 [#3775](https://github.com/farion1231/cc-switch/pull/3775) 把 Anthropic 兼容供应商的 `role=system` 消息从 `messages[]` 上提到顶层 `system` 字段的改动。DeepSeek 端点本就原生接受内联的 system 消息,而该重写改变了请求前缀;保持消息原位能保留 prompt 前缀,避免一处疑似的缓存命中率回退(参见 [#4297](https://github.com/farion1231/cc-switch/issues/4297))。来自 #3775 的、不相关的 Windows 测试修复以及 tool-thinking-history 归一化都保留。
|
||||
|
||||
### Chat 工具调用缺函数名
|
||||
|
||||
一些上游会在流式工具调用增量里发送空的或缺失的函数名,过去这会产生无效的 Codex Chat 输出项(或一个 `unknown_tool` 回退)。现在累积的工具调用状态不会再被空增量覆盖,而那些始终没拿到 `call_id` 与有效名字的工具调用会在最终化阶段被跳过,覆盖流式、非流式与旧版 `function_call` 三条路径。([#4159](https://github.com/farion1231/cc-switch/pull/4159))
|
||||
|
||||
### 恢复 Codex 缓存的工具调用字段
|
||||
|
||||
当 Codex 发起一个引用 `previous_response_id` 的后续 Chat 请求时,它的 `function_call` 项可能只携带 `call_id`。历史增强此前只回填 `reasoning` / `reasoning_content`,留空了函数的 `name`、`arguments`、`status` 等字段;现在它会从历史里恢复全部缓存的工具调用字段,让该调用能为 Chat 上游正确重建。([#4160](https://github.com/farion1231/cc-switch/pull/4160))
|
||||
|
||||
### config.toml 里重复的 Codex base_url 条目
|
||||
|
||||
把 Codex 的 `base_url` 写入 `config.toml` 时此前每个区段只替换或移除一个匹配的赋值,因此一个已经含多行 `base_url` 的区段会留下多余项、累积重复。`setCodexBaseUrl` 现在会折叠目标区段或顶层的所有匹配(替换第一处、移除其余),TOML 的 `base_url` 正则也处理了转义引号。([#4316](https://github.com/farion1231/cc-switch/pull/4316))
|
||||
|
||||
### 历史迁移探测 CODEX_SQLITE_HOME 的状态库
|
||||
|
||||
Codex 会话历史迁移此前只扫描 `~/.codex/state_5.sqlite` 与 `config.toml` 的 `sqlite_home` 位置,因此当 Codex 的 SQLite 状态通过 `CODEX_SQLITE_HOME` 环境变量被重定位时,状态库从未被扫描、其 threads 仍留在旧的供应商分桶里。第三方与统一会话两套迁移共用的 `codex_state_db_paths` 辅助函数现在会回退到 `CODEX_SQLITE_HOME`(`config` 里的 `sqlite_home` 仍优先)。
|
||||
|
||||
### 供应商终端尊重用户 shell
|
||||
|
||||
在 macOS / Linux 上启动供应商终端时此前硬编码了 `bash`,导致 zsh / fish 用户的 rc 文件不会加载。启动器现在会从 `$SHELL` 检测用户默认 shell(macOS 回退 `/bin/zsh`、Linux 回退 `/bin/bash`)并以干净启动的 flag exec 进去,而启动脚本本身改走 POSIX `sh` 以保证可移植性(例如 fish,以及 `/bin/sh` 可能不存在的 NixOS)。([#4140](https://github.com/farion1231/cc-switch/pull/4140),修复 [#1546](https://github.com/farion1231/cc-switch/issues/1546))
|
||||
|
||||
### Claude MCP 路径尊重自定义配置目录
|
||||
|
||||
当配置了自定义的 Claude 配置目录时,MCP server 的读写现在会解析到该目录下的 MCP 文件、而非默认位置,让 MCP 状态按 profile 隔离。此前对旧文件的「访问即拷贝」迁移被移除,改为直接解析覆盖路径。([#3431](https://github.com/farion1231/cc-switch/pull/3431))
|
||||
|
||||
### 搜索后预设结果可点击
|
||||
|
||||
在「添加供应商」预设选择器里搜索后,结果一度无法点击或选中。那个与输入打架、会吃掉首字符(如「gateway」→「ateway」)的 `requestAnimationFrame` `select()` 被移除,开箱即点路径的输入自动聚焦被恢复,当搜索框已打开时按 Ctrl/Cmd+F 也接上了重新聚焦。供应商列表的打字守卫也被收窄到 Ctrl/Cmd+F 分支,从而 Escape 仍能关闭搜索面板。([#4315](https://github.com/farion1231/cc-switch/pull/4315))
|
||||
|
||||
### Skills 浏览与供应商卡片显示修复
|
||||
|
||||
修复了若干显示与交互问题:浏览 skills.sh 时仓库管理操作保持可用,仓库返回空结果时刷新也保持可用;供应商卡片上过长的供应商名与网站 URL 现在会截断而非溢出;OMO 模型变体下拉会截断所选标签并配全文提示;Select 菜单项会在当前选中项上显示对勾。([#4323](https://github.com/farion1231/cc-switch/pull/4323))
|
||||
|
||||
### 切换设置页签时重置滚动
|
||||
|
||||
在设置对话框里切换页签会保留上一个页签的滚动位置,有时会停在新页签的中途;现在每当激活页签变化时,滚动容器都会重置到顶部。([#4165](https://github.com/farion1231/cc-switch/pull/4165))
|
||||
|
||||
---
|
||||
|
||||
## 文档
|
||||
|
||||
### Kimi 置顶赞助横幅
|
||||
|
||||
全部四种 README 语言(en / zh / ja / de)顶部的置顶赞助横幅现在换成了 Kimi K2.7 Code,取代此前的 MiniMax M2.7 横幅。文案反映 K2.7 Code 发布(一个面向编程的 agentic 模型,思考 token 用量较 K2.6 降低约 30%),横幅改由仓库内资源(`assets/partners/banners/kimi-banner-en.png` / `kimi-banner-zh.png`)提供、不再走 Moonshot CDN,并附一个指向 `aff=cc-switch` Moonshot 控制台的可点击行动号召。
|
||||
|
||||
### Codex 统一会话历史攻略
|
||||
|
||||
新增三语(zh / en / ja)攻略,讲清统一 Codex 会话历史开关的开启迁移(启用时)与按账本还原(禁用时)到底做了什么、为什么会话数据从不会真正删除(只改标记 + 自动备份),以及如何核对文件是真在磁盘上、还是只是被归到了另一个供应商抽屉里。它包含一张针对常见「我的会话不见了」误解的症状对照表,以及 macOS / Linux / Windows 的磁盘核对命令,并作为首项链入 v3.16.3 的「使用攻略」release notes。
|
||||
|
||||
### 简化 Homebrew 安装说明
|
||||
|
||||
安装指南不再要求用户在 `brew install --cask cc-switch` 之前先运行 `brew tap farion1231/ccswitch`;这个已废弃的 tap 步骤已从 en / ja / zh 用户手册里移除,cask 现在可直接安装。([#4319](https://github.com/farion1231/cc-switch/pull/4319))
|
||||
|
||||
### Star-History 全球排名徽标
|
||||
|
||||
在全部四种 README 语言里、既有的 Trendshift 徽标旁新增了一个 star-history 全球排名徽标,并带亮 / 暗主题变体。
|
||||
|
||||
### 火山方舟 Coding Plan 活动链接
|
||||
|
||||
ByteDance / 火山方舟赞助条目里的「中国大陆地区的开发者请点击这里」链接现在指向火山的 `ai618` 活动页,取代此前的 `codingplan` 推荐 URL,覆盖全部四种 README 语言。
|
||||
|
||||
### CCSub 赞助横幅矢量资源
|
||||
|
||||
把低分辨率的 `ccsub.jpg` 赞助 logo 替换为矢量的 `ccsub.svg`,并从 2046x648 letterbox 到 2046x850(约 2.406:1),使其与其它赞助表横幅匹配、以相同的 62px 高度渲染。全部四种 README 语言都指向新资源。
|
||||
|
||||
---
|
||||
|
||||
## 升级提醒
|
||||
|
||||
### 国产 Codex 供应商原生 Responses 迁移
|
||||
|
||||
本版把多家具备原生 Responses 端点的国产供应商(千问 / 百炼、小米 MiMo、火山豆包、美团 LongCat、MiniMax 国内 / 国际)的 Codex 预设切换为 `openai_responses` 并移除了 `modelCatalog`。已经基于这些预设配置过的存量供应商不受影响、配置保持原样;如果你希望改用原生 Responses(省去格式转换接管),可以重新从预设选择一次并保存。SiliconFlow 托管的 MiniMax 仍走 `openai_chat`,不在此次迁移之列。
|
||||
|
||||
### 数据库版本过新的恢复
|
||||
|
||||
如果你曾用更高版本的 CC Switch 打开过数据库、再切回旧版,旧版启动时会进入新的「数据库版本过新」恢复屏,并引导你升级到能读懂该数据库的版本。这是预期行为——升级到最新版即可恢复正常。
|
||||
|
||||
---
|
||||
|
||||
## 风险提示
|
||||
|
||||
本版本继续沿用此前版本对反向代理类功能的风险提示。
|
||||
|
||||
**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#️-风险提示)。
|
||||
|
||||
**Codex 第三方供应商 Chat 路由**:通过 CC Switch 本地代理把 Codex 请求转换并转发到第三方供应商时,各供应商对计费、合规与数据留存的约束不同,请在使用前阅读目标供应商的服务条款。
|
||||
|
||||
**Claude Desktop 第三方供应商代理切换**:通过 CC Switch 内置代理网关把 Claude Desktop 的请求转到第三方供应商时,同样需要遵守目标供应商的计费、合规与数据留存约束。
|
||||
|
||||
用户启用上述功能即表示自行承担相关风险。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
|
||||
|
||||
---
|
||||
|
||||
## 致谢
|
||||
|
||||
感谢以下贡献者在 v3.16.4 中提交的功能与修复:
|
||||
|
||||
- [#3817](https://github.com/farion1231/cc-switch/pull/3817):转发前解压请求体并支持 zstd,感谢 @chenx-dust。
|
||||
- [#4583](https://github.com/farion1231/cc-switch/pull/4583):修复 Copilot / Codex OAuth 模块绕过全局代理导致 Claude 模型 400,感谢 @zymouse。
|
||||
- [#4589](https://github.com/farion1231/cc-switch/pull/4589):新增本地代理请求覆盖(自定义请求头与请求体),感谢 @mfzzf。
|
||||
- [#4575](https://github.com/farion1231/cc-switch/pull/4575):新增数据库版本过新时的应用内恢复屏,感谢 @SaladDay。
|
||||
- [#4556](https://github.com/farion1231/cc-switch/pull/4556):为多处 JsonEditor 接入暗色模式,感谢 @TanKimzeg。
|
||||
- [#4438](https://github.com/farion1231/cc-switch/pull/4438):新增自定义日期范围的实时结束时间,感谢 @arichyx。
|
||||
- [#3950](https://github.com/farion1231/cc-switch/pull/3950):新增 Windows ARM64 发布支持,感谢 @MOON-DREAM-STARS。
|
||||
- [#4401](https://github.com/farion1231/cc-switch/pull/4401):为 Kimi For Coding 预设添加 CLAUDE_CODE_AUTO_COMPACT_WINDOW,感谢 @cyijun。
|
||||
- [#4323](https://github.com/farion1231/cc-switch/pull/4323):修复 Skills 管理与模型配置的交互展示,感谢 @thisTom。
|
||||
- [#3431](https://github.com/farion1231/cc-switch/pull/3431):对齐自定义配置目录的 Claude MCP 路径,感谢 @makoMakoGo。
|
||||
- [#4159](https://github.com/farion1231/cc-switch/pull/4159):跳过缺函数名的 Chat 工具调用,感谢 @hueifeng。
|
||||
- [#4385](https://github.com/farion1231/cc-switch/pull/4385):新增 glm-5.2 定价,感谢 @arichyx。
|
||||
- [#4079](https://github.com/farion1231/cc-switch/pull/4079):支持从 models.dev 导入模型定价,感谢 @kingcanfish。
|
||||
- [#4315](https://github.com/farion1231/cc-switch/pull/4315):修复搜索预设后结果无法点击选中,感谢 @RuixeWolf。
|
||||
- [#4316](https://github.com/farion1231/cc-switch/pull/4316):防止重复的 Codex base_url 条目,感谢 @jeffwcx。
|
||||
- [#4140](https://github.com/farion1231/cc-switch/pull/4140):让供应商终端尊重用户 shell,感谢 @zkforge。
|
||||
- [#4113](https://github.com/farion1231/cc-switch/pull/4113):在会话详情头显示源文件名,感谢 @xu-song。
|
||||
- [#4160](https://github.com/farion1231/cc-switch/pull/4160):恢复 Codex 缓存的工具调用字段,感谢 @chen-985211。
|
||||
- [#4239](https://github.com/farion1231/cc-switch/pull/4239):DeepSeek 端点 thinking:disabled 时剥掉 effort 参数,感谢 @maskshell。
|
||||
- [#4165](https://github.com/farion1231/cc-switch/pull/4165):切换设置页签时重置滚动,感谢 @Muleizhang。
|
||||
- [#4319](https://github.com/farion1231/cc-switch/pull/4319):移除已废弃的 Homebrew tap 步骤,感谢 @tianpeng-dev。
|
||||
- [#4522](https://github.com/farion1231/cc-switch/pull/4522):新增 SubRouter 供应商预设,感谢 @abingyyds。
|
||||
|
||||
也感谢所有在 v3.16.3 发布后反馈 Codex 代理链路、用量计费、本地代理稳健性与平台兼容性问题的用户,很多补丁都来自这些真实使用场景里的复现线索。
|
||||
|
||||
---
|
||||
|
||||
## 下载与安装
|
||||
|
||||
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
|
||||
|
||||
### 系统要求
|
||||
|
||||
| 系统 | 最低版本 | 架构 |
|
||||
| ------- | -------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 及以上 | x64 / ARM64 |
|
||||
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 见下表 | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ---------------------------------------- | ----------------------------------- |
|
||||
| `CC-Switch-v3.16.4-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
|
||||
| `CC-Switch-v3.16.4-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
|
||||
|
||||
Windows ARM64 设备请选择文件名中带 `arm64` 标识的对应制品。
|
||||
|
||||
### macOS
|
||||
|
||||
| 文件 | 说明 |
|
||||
| -------------------------------- | --------------------------------------------- |
|
||||
| `CC-Switch-v3.16.4-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
|
||||
| `CC-Switch-v3.16.4-macOS.zip` | 解压后拖入 Applications,Universal Binary |
|
||||
| `CC-Switch-v3.16.4-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
|
||||
|
||||
Homebrew 安装:
|
||||
|
||||
```bash
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
Linux 资产同时提供 **x86_64** 和 **ARM64**(`aarch64`)两种架构。资产文件名中包含架构标识,请按你机器的 `uname -m` 输出选择对应版本:
|
||||
|
||||
- `CC-Switch-v3.16.4-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.16.4-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
| 发行版 | 推荐格式 | 安装方式 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` 或 `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` 或 `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
|
||||
| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -122,9 +122,6 @@ npm install -g @google/gemini-cli
|
||||
### Option 1: Homebrew (Recommended)
|
||||
|
||||
```bash
|
||||
# Add tap
|
||||
brew tap farion1231/ccswitch
|
||||
|
||||
# Install
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
@@ -43,7 +43,7 @@ v3.13.0 provides **ready-to-use built-in templates** for the following categorie
|
||||
|
||||
| Category | Covered Providers | Template Type |
|
||||
| ------------------ | --------------------------------------------------------- | ------------------------------- |
|
||||
| Token Plan | Kimi / Zhipu GLM / MiniMax | Plan quota (with usage progress) |
|
||||
| Token Plan | Kimi / Zhipu GLM / MiniMax / Volcengine | Plan quota (with usage progress) |
|
||||
| Third-party balance| DeepSeek / StepFun / SiliconFlow / OpenRouter / Novita AI | Official balance query |
|
||||
|
||||
> **Tip**: Beyond these built-in templates, for uncovered providers you can use the **custom script** approach (see below) to write your own query logic.
|
||||
|
||||
@@ -122,9 +122,6 @@ npm install -g @google/gemini-cli
|
||||
### 方法 1:Homebrew(推奨)
|
||||
|
||||
```bash
|
||||
# tap を追加
|
||||
brew tap farion1231/ccswitch
|
||||
|
||||
# インストール
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
@@ -43,7 +43,7 @@ v3.13.0 では以下のカテゴリに **すぐに使える内蔵テンプレー
|
||||
|
||||
| カテゴリ | 対象プロバイダー | テンプレートタイプ |
|
||||
| --------------- | --------------------------------------------------------- | ------------------------- |
|
||||
| Token Plan | Kimi / Zhipu GLM / MiniMax | プランクォータ(使用進捗付き) |
|
||||
| Token Plan | Kimi / Zhipu GLM / MiniMax / Volcengine(火山方舟) | プランクォータ(使用進捗付き) |
|
||||
| 第三者残高 | DeepSeek / StepFun / SiliconFlow / OpenRouter / Novita AI | 公式残高クエリ |
|
||||
|
||||
> **ヒント**:上記の内蔵テンプレート以外で対象外のプロバイダーには、**カスタムスクリプト** 方式(下記参照)で独自のクエリロジックを記述できます。
|
||||
|
||||
@@ -138,9 +138,6 @@ npm install -g @google/gemini-cli --registry=https://registry.npmmirror.com
|
||||
### 方式一:Homebrew(推荐)
|
||||
|
||||
```bash
|
||||
# 添加 tap
|
||||
brew tap farion1231/ccswitch
|
||||
|
||||
# 安装
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
@@ -43,7 +43,7 @@ v3.13.0 为以下类别提供了**开箱即用的内置模板**,启用后无
|
||||
|
||||
| 类别 | 覆盖供应商 | 模板类型 |
|
||||
| ---------- | --------------------------------------------------------- | ----------------------- |
|
||||
| Token Plan | Kimi / Zhipu GLM / MiniMax | 套餐配额(带使用进度) |
|
||||
| Token Plan | Kimi / Zhipu GLM / MiniMax / 火山方舟 | 套餐配额(带使用进度) |
|
||||
| 第三方余额 | DeepSeek / StepFun / SiliconFlow / OpenRouter / Novita AI | 官方余额查询 |
|
||||
|
||||
> 💡 除了以上内置模板外,对未被覆盖的供应商,你可以使用**自定义脚本**方式(见下文)编写自己的查询逻辑。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cc-switch",
|
||||
"version": "3.16.3",
|
||||
"version": "3.16.4",
|
||||
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -184,7 +184,7 @@ dependencies = [
|
||||
"futures-lite",
|
||||
"parking",
|
||||
"polling",
|
||||
"rustix",
|
||||
"rustix 1.1.4",
|
||||
"slab",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -215,7 +215,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"event-listener",
|
||||
"futures-lite",
|
||||
"rustix",
|
||||
"rustix 1.1.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -241,7 +241,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"rustix",
|
||||
"rustix 1.1.4",
|
||||
"signal-hook-registry",
|
||||
"slab",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -421,6 +421,29 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bindgen"
|
||||
version = "0.69.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088"
|
||||
dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"cexpr",
|
||||
"clang-sys",
|
||||
"itertools",
|
||||
"lazy_static",
|
||||
"lazycell",
|
||||
"log",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
"rustc-hash 1.1.0",
|
||||
"shlex",
|
||||
"syn 2.0.117",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.8.0"
|
||||
@@ -735,7 +758,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc-switch"
|
||||
version = "3.16.3"
|
||||
version = "3.16.4"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arboard",
|
||||
@@ -802,6 +825,7 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"winreg 0.52.0",
|
||||
"zip 2.4.2",
|
||||
"zstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -810,6 +834,15 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
|
||||
|
||||
[[package]]
|
||||
name = "cexpr"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
|
||||
dependencies = [
|
||||
"nom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfb"
|
||||
version = "0.7.3"
|
||||
@@ -867,6 +900,17 @@ dependencies = [
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clang-sys"
|
||||
version = "1.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
|
||||
dependencies = [
|
||||
"glob",
|
||||
"libc",
|
||||
"libloading 0.8.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clipboard-win"
|
||||
version = "5.4.1"
|
||||
@@ -936,6 +980,15 @@ version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
|
||||
|
||||
[[package]]
|
||||
name = "convert_case"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"
|
||||
dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.1"
|
||||
@@ -1178,7 +1231,7 @@ version = "0.99.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"convert_case 0.4.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rustc_version",
|
||||
@@ -1385,6 +1438,12 @@ version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
|
||||
|
||||
[[package]]
|
||||
name = "embed-resource"
|
||||
version = "3.0.6"
|
||||
@@ -1914,7 +1973,7 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
|
||||
dependencies = [
|
||||
"rustix",
|
||||
"rustix 1.1.4",
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
@@ -2222,6 +2281,15 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "home"
|
||||
version = "0.5.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "html5ever"
|
||||
version = "0.29.1"
|
||||
@@ -2616,6 +2684,15 @@ dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.17"
|
||||
@@ -2753,6 +2830,18 @@ dependencies = [
|
||||
"selectors 0.24.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
|
||||
[[package]]
|
||||
name = "lazycell"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
version = "0.1.0"
|
||||
@@ -2779,7 +2868,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf"
|
||||
dependencies = [
|
||||
"gtk-sys",
|
||||
"libloading",
|
||||
"libloading 0.7.4",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
@@ -2799,6 +2888,16 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libloading"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libredox"
|
||||
version = "0.1.14"
|
||||
@@ -2822,6 +2921,12 @@ dependencies = [
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
@@ -2954,6 +3059,12 @@ version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
||||
|
||||
[[package]]
|
||||
name = "minisign-verify"
|
||||
version = "0.2.5"
|
||||
@@ -3071,6 +3182,16 @@ version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "7.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.0"
|
||||
@@ -3839,7 +3960,7 @@ dependencies = [
|
||||
"concurrent-queue",
|
||||
"hermit-abi",
|
||||
"pin-project-lite",
|
||||
"rustix",
|
||||
"rustix 1.1.4",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
@@ -4002,7 +4123,7 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
"quinn-proto",
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustc-hash 2.1.1",
|
||||
"rustls",
|
||||
"socket2",
|
||||
"thiserror 2.0.18",
|
||||
@@ -4022,7 +4143,7 @@ dependencies = [
|
||||
"lru-slab",
|
||||
"rand 0.9.2",
|
||||
"ring",
|
||||
"rustc-hash",
|
||||
"rustc-hash 2.1.1",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"slab",
|
||||
@@ -4278,6 +4399,12 @@ version = "0.8.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
||||
|
||||
[[package]]
|
||||
name = "relative-path"
|
||||
version = "1.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"
|
||||
|
||||
[[package]]
|
||||
name = "rend"
|
||||
version = "0.4.2"
|
||||
@@ -4447,6 +4574,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d16661bff09e9ed8e01094a188b463de45ec0693ade55b92ed54027d7ba7c40c"
|
||||
dependencies = [
|
||||
"rquickjs-core",
|
||||
"rquickjs-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4455,15 +4583,34 @@ version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c8db6379e204ef84c0811e90e7cc3e3e4d7688701db68a00d14a6db6849087b"
|
||||
dependencies = [
|
||||
"relative-path",
|
||||
"rquickjs-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rquickjs-macro"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6041104330c019fcd936026ae05e2446f5e8a2abef329d924f25424b7052a2f3"
|
||||
dependencies = [
|
||||
"convert_case 0.6.0",
|
||||
"fnv",
|
||||
"ident_case",
|
||||
"indexmap 2.13.0",
|
||||
"proc-macro-crate 1.3.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rquickjs-core",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rquickjs-sys"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4bc352c6b663604c3c186c000cfcc6c271f4b50bc135a285dd6d4f2a42f9790a"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"cc",
|
||||
]
|
||||
|
||||
@@ -4507,6 +4654,12 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.1"
|
||||
@@ -4522,6 +4675,19 @@ dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
|
||||
dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.4.15",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
@@ -4531,7 +4697,7 @@ dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
@@ -4775,7 +4941,7 @@ dependencies = [
|
||||
"phf 0.13.1",
|
||||
"phf_codegen 0.13.1",
|
||||
"precomputed-hash",
|
||||
"rustc-hash",
|
||||
"rustc-hash 2.1.1",
|
||||
"servo_arc 0.4.3",
|
||||
"smallvec",
|
||||
]
|
||||
@@ -5814,7 +5980,7 @@ dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.2",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"rustix 1.1.4",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
@@ -6783,6 +6949,18 @@ version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
|
||||
|
||||
[[package]]
|
||||
name = "which"
|
||||
version = "4.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7"
|
||||
dependencies = [
|
||||
"either",
|
||||
"home",
|
||||
"once_cell",
|
||||
"rustix 0.38.44",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
@@ -7527,7 +7705,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
|
||||
dependencies = [
|
||||
"gethostname",
|
||||
"rustix",
|
||||
"rustix 1.1.4",
|
||||
"x11rb-protocol",
|
||||
]
|
||||
|
||||
@@ -7544,7 +7722,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rustix",
|
||||
"rustix 1.1.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7601,7 +7779,7 @@ dependencies = [
|
||||
"hex",
|
||||
"libc",
|
||||
"ordered-stream",
|
||||
"rustix",
|
||||
"rustix 1.1.4",
|
||||
"serde",
|
||||
"serde_repr",
|
||||
"tracing",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cc-switch"
|
||||
version = "3.16.3"
|
||||
version = "3.16.4"
|
||||
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
|
||||
authors = ["Jason Young"]
|
||||
license = "MIT"
|
||||
@@ -43,6 +43,7 @@ reqwest = { version = "0.12", features = ["rustls-tls", "json", "stream", "socks
|
||||
arboard = "3.6"
|
||||
flate2 = "1"
|
||||
brotli = "7"
|
||||
zstd = "0.13"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "sync"] }
|
||||
futures = "0.3"
|
||||
async-stream = "0.3"
|
||||
@@ -91,6 +92,9 @@ webkit2gtk = { version = "2.0.1", features = ["v2_16"] }
|
||||
winreg = "0.52"
|
||||
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_UI_Shell"] }
|
||||
|
||||
[target.'cfg(all(target_os = "windows", target_arch = "aarch64"))'.dependencies]
|
||||
rquickjs = { version = "0.8", features = ["bindgen"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = "0.5"
|
||||
objc2-app-kit = { version = "0.2", features = ["NSColor"] }
|
||||
|
||||
@@ -1339,8 +1339,10 @@ mod tests {
|
||||
}
|
||||
|
||||
fn set_proxy_port(db: &Database, port: u16) {
|
||||
let mut config = crate::proxy::types::ProxyConfig::default();
|
||||
config.listen_port = port;
|
||||
let config = crate::proxy::types::ProxyConfig {
|
||||
listen_port: port,
|
||||
..Default::default()
|
||||
};
|
||||
futures::executor::block_on(db.update_proxy_config(config)).expect("update proxy config");
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::env;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::config::{atomic_write, get_claude_mcp_path, get_default_claude_mcp_path};
|
||||
use crate::config::{atomic_write, get_claude_mcp_path};
|
||||
use crate::error::AppError;
|
||||
|
||||
/// 需要在 Windows 上用 cmd /c 包装的命令
|
||||
@@ -98,51 +98,9 @@ pub struct McpStatus {
|
||||
}
|
||||
|
||||
fn user_config_path() -> PathBuf {
|
||||
ensure_mcp_override_migrated();
|
||||
get_claude_mcp_path()
|
||||
}
|
||||
|
||||
fn ensure_mcp_override_migrated() {
|
||||
if crate::settings::get_claude_override_dir().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let new_path = get_claude_mcp_path();
|
||||
if new_path.exists() {
|
||||
return;
|
||||
}
|
||||
|
||||
let legacy_path = get_default_claude_mcp_path();
|
||||
if !legacy_path.exists() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(parent) = new_path.parent() {
|
||||
if let Err(err) = fs::create_dir_all(parent) {
|
||||
log::warn!("创建 MCP 目录失败: {err}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
match fs::copy(&legacy_path, &new_path) {
|
||||
Ok(_) => {
|
||||
log::info!(
|
||||
"已根据覆盖目录复制 MCP 配置: {} -> {}",
|
||||
legacy_path.display(),
|
||||
new_path.display()
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"复制 MCP 配置失败: {} -> {}: {}",
|
||||
legacy_path.display(),
|
||||
new_path.display(),
|
||||
err
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_json_value(path: &Path) -> Result<Value, AppError> {
|
||||
if !path.exists() {
|
||||
return Ok(serde_json::json!({}));
|
||||
|
||||
@@ -67,6 +67,7 @@ const CC_SWITCH_LEGACY_CODEX_MODEL_PROVIDER_IDS: &[&str] = &[
|
||||
"dmxapi",
|
||||
"doubaoseed",
|
||||
"eflowcode",
|
||||
"etok",
|
||||
"kimi",
|
||||
"lemondata",
|
||||
"longcat",
|
||||
@@ -1116,16 +1117,23 @@ fn migrate_codex_state_dbs(
|
||||
}
|
||||
|
||||
fn codex_state_db_paths(codex_dir: &Path, config_text: &str) -> Vec<PathBuf> {
|
||||
let mut paths = vec![codex_dir.join(CODEX_STATE_DB_FILENAME)];
|
||||
let mut paths = Vec::new();
|
||||
push_unique_path(&mut paths, codex_dir.join(CODEX_STATE_DB_FILENAME));
|
||||
// Codex lets SQLite state move away from CODEX_HOME; config takes precedence.
|
||||
if let Some(sqlite_home) = sqlite_home_from_codex_config(config_text) {
|
||||
let db_path = sqlite_home.join(CODEX_STATE_DB_FILENAME);
|
||||
if !paths.contains(&db_path) {
|
||||
paths.push(db_path);
|
||||
}
|
||||
push_unique_path(&mut paths, sqlite_home.join(CODEX_STATE_DB_FILENAME));
|
||||
} else if let Some(sqlite_home) = sqlite_home_from_env() {
|
||||
push_unique_path(&mut paths, sqlite_home.join(CODEX_STATE_DB_FILENAME));
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
fn push_unique_path(paths: &mut Vec<PathBuf>, path: PathBuf) {
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
fn sqlite_home_from_codex_config(config_text: &str) -> Option<PathBuf> {
|
||||
let doc = config_text.parse::<DocumentMut>().ok()?;
|
||||
let raw = doc.get("sqlite_home")?.as_str()?.trim();
|
||||
@@ -1135,6 +1143,15 @@ fn sqlite_home_from_codex_config(config_text: &str) -> Option<PathBuf> {
|
||||
Some(resolve_user_path(raw))
|
||||
}
|
||||
|
||||
fn sqlite_home_from_env() -> Option<PathBuf> {
|
||||
let raw = std::env::var("CODEX_SQLITE_HOME").ok()?;
|
||||
let raw = raw.trim();
|
||||
if raw.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(resolve_user_path(raw))
|
||||
}
|
||||
|
||||
fn resolve_user_path(raw: &str) -> PathBuf {
|
||||
if raw == "~" {
|
||||
return crate::config::get_home_dir();
|
||||
@@ -1313,8 +1330,33 @@ fn relative_backup_path(path: &Path, root: &Path) -> PathBuf {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::provider::Provider;
|
||||
use serial_test::serial;
|
||||
use std::ffi::OsString;
|
||||
use tempfile::tempdir;
|
||||
|
||||
struct EnvVarGuard {
|
||||
key: &'static str,
|
||||
previous: Option<OsString>,
|
||||
}
|
||||
|
||||
impl EnvVarGuard {
|
||||
fn set(key: &'static str, value: &Path) -> Self {
|
||||
let previous = std::env::var_os(key);
|
||||
std::env::set_var(key, value);
|
||||
Self { key, previous }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EnvVarGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(previous) = &self.previous {
|
||||
std::env::set_var(self.key, previous);
|
||||
} else {
|
||||
std::env::remove_var(self.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn source_ids(values: &[&str]) -> BTreeSet<String> {
|
||||
values.iter().map(|value| value.to_string()).collect()
|
||||
}
|
||||
@@ -2116,6 +2158,46 @@ base_url = "https://proxy.example/v1"
|
||||
assert_eq!(backed_up_source_count, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn state_db_paths_include_codex_sqlite_home_env() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let codex_dir = dir.path().join(".codex");
|
||||
let sqlite_home = dir.path().join("sqlite-home");
|
||||
let _guard = EnvVarGuard::set("CODEX_SQLITE_HOME", &sqlite_home);
|
||||
|
||||
let paths = codex_state_db_paths(&codex_dir, "");
|
||||
|
||||
assert_eq!(
|
||||
paths,
|
||||
vec![
|
||||
codex_dir.join(CODEX_STATE_DB_FILENAME),
|
||||
sqlite_home.join(CODEX_STATE_DB_FILENAME),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn config_sqlite_home_takes_precedence_over_codex_sqlite_home_env() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let codex_dir = dir.path().join(".codex");
|
||||
let env_sqlite_home = dir.path().join("env-sqlite-home");
|
||||
let config_sqlite_home = dir.path().join("config-sqlite-home");
|
||||
let _guard = EnvVarGuard::set("CODEX_SQLITE_HOME", &env_sqlite_home);
|
||||
let config_text = format!("sqlite_home = \"{}\"\n", config_sqlite_home.display());
|
||||
|
||||
let paths = codex_state_db_paths(&codex_dir, &config_text);
|
||||
|
||||
assert_eq!(
|
||||
paths,
|
||||
vec![
|
||||
codex_dir.join(CODEX_STATE_DB_FILENAME),
|
||||
config_sqlite_home.join(CODEX_STATE_DB_FILENAME),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_third_party_provider_ids_from_codex_providers() {
|
||||
let db = Database::memory().expect("memory db");
|
||||
|
||||
@@ -4,6 +4,15 @@ use crate::services::subscription::SubscriptionQuota;
|
||||
pub async fn get_coding_plan_quota(
|
||||
base_url: String,
|
||||
api_key: String,
|
||||
// 火山方舟用控制面 AK/SK 签名查询用量;其他供应商不传,沿用 api_key。
|
||||
access_key_id: Option<String>,
|
||||
secret_access_key: Option<String>,
|
||||
) -> Result<SubscriptionQuota, String> {
|
||||
crate::services::coding_plan::get_coding_plan_quota(&base_url, &api_key).await
|
||||
crate::services::coding_plan::get_coding_plan_quota(
|
||||
&base_url,
|
||||
&api_key,
|
||||
access_key_id.as_deref(),
|
||||
secret_access_key.as_deref(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -1069,6 +1069,111 @@ fn default_flag_for_shell(shell: &str) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
fn fallback_user_shell() -> &'static str {
|
||||
if cfg!(target_os = "macos") {
|
||||
"/bin/zsh"
|
||||
} else {
|
||||
"/bin/bash"
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_user_shell_path(shell: &str) -> bool {
|
||||
if shell.is_empty()
|
||||
|| !shell.starts_with('/')
|
||||
|| !is_valid_shell(shell)
|
||||
|| shell.chars().any(char::is_control)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let path = std::path::Path::new(shell);
|
||||
path.is_file() && is_executable_file(path)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn is_executable_file(path: &std::path::Path) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
path.metadata()
|
||||
.map(|metadata| metadata.permissions().mode() & 0o111 != 0)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn is_executable_file(path: &std::path::Path) -> bool {
|
||||
path.is_file()
|
||||
}
|
||||
|
||||
/// 获取用户默认 shell 的完整路径;异常或被污染的 SHELL 回退到平台默认值。
|
||||
fn get_user_shell() -> String {
|
||||
std::env::var("SHELL")
|
||||
.ok()
|
||||
.filter(|shell| valid_user_shell_path(shell))
|
||||
.unwrap_or_else(|| fallback_user_shell().to_string())
|
||||
}
|
||||
|
||||
/// 构建 exec 行:引号保护 shell 路径,交还用户 shell 让其按默认规则加载 rc 配置。
|
||||
fn build_exec_line(shell: &str, cwd: Option<&Path>) -> String {
|
||||
let quoted_shell = shell_single_quote(shell);
|
||||
|
||||
match shell.rsplit('/').next().unwrap_or(shell) {
|
||||
"zsh" => cwd
|
||||
.map(|dir| {
|
||||
let command = format!(
|
||||
"cd {} || exit 1; exec {} -i",
|
||||
shell_single_quote(&dir.to_string_lossy()),
|
||||
quoted_shell
|
||||
);
|
||||
format!("exec {} -lc {}", quoted_shell, shell_single_quote(&command))
|
||||
})
|
||||
.unwrap_or_else(|| format!("exec {quoted_shell} -l")),
|
||||
_ => format!("exec {quoted_shell}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// 构建 provider 命令行:通过用户 shell 的交互模式执行,确保 GUI 启动的终端也加载用户 PATH。
|
||||
fn build_provider_command_line(shell: &str, config_path: &str, cwd: Option<&Path>) -> String {
|
||||
let claude_command = format!("claude --settings {}", shell_single_quote(config_path));
|
||||
let command = cwd
|
||||
.map(|dir| {
|
||||
format!(
|
||||
"cd {} && {}",
|
||||
shell_single_quote(&dir.to_string_lossy()),
|
||||
claude_command
|
||||
)
|
||||
})
|
||||
.unwrap_or(claude_command);
|
||||
|
||||
format!(
|
||||
"{} {} {}",
|
||||
shell_single_quote(shell),
|
||||
provider_command_flag_for_shell(shell),
|
||||
shell_single_quote(&command)
|
||||
)
|
||||
}
|
||||
|
||||
fn provider_command_flag_for_shell(shell: &str) -> &'static str {
|
||||
match shell.rsplit('/').next().unwrap_or(shell) {
|
||||
"dash" | "sh" => "-c",
|
||||
"zsh" => "-lic",
|
||||
_ => "-ic",
|
||||
}
|
||||
}
|
||||
|
||||
fn build_final_shell_cd_command(shell: &str, cwd: Option<&Path>) -> String {
|
||||
if matches!(shell.rsplit('/').next().unwrap_or(shell), "zsh") {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
cwd.map(|dir| {
|
||||
format!(
|
||||
"cd {} || exit 1\n",
|
||||
shell_single_quote(&dir.to_string_lossy())
|
||||
)
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn try_get_version_wsl(
|
||||
tool: &str,
|
||||
@@ -2642,24 +2747,31 @@ fn launch_macos_terminal(config_file: &std::path::Path, cwd: Option<&Path>) -> R
|
||||
let preferred = crate::settings::get_preferred_terminal();
|
||||
let terminal = preferred.as_deref().unwrap_or("terminal");
|
||||
|
||||
let shell = get_user_shell();
|
||||
let exec_line = build_exec_line(&shell, cwd);
|
||||
let final_cd_command = build_final_shell_cd_command(&shell, cwd);
|
||||
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let script_file = temp_dir.join(format!("cc_switch_launcher_{}.sh", std::process::id()));
|
||||
let config_path = config_file.to_string_lossy();
|
||||
let cd_command = build_shell_cd_command(cwd);
|
||||
let provider_command = build_provider_command_line(&shell, &config_path, cwd);
|
||||
|
||||
// Write the shell script to a temp file
|
||||
// 脚本使用 POSIX sh 语法确保可移植性,exec 行切换到用户交互式 shell
|
||||
let script_content = format!(
|
||||
r#"#!/bin/bash
|
||||
r#"#!/usr/bin/env sh
|
||||
trap 'rm -f "{config_path}" "{script_file}"' EXIT
|
||||
{cd_command}
|
||||
echo "Using provider-specific claude config:"
|
||||
echo "{config_path}"
|
||||
claude --settings "{config_path}"
|
||||
exec bash --norc --noprofile
|
||||
{provider_command}
|
||||
{final_cd_command}
|
||||
{exec_line}
|
||||
"#,
|
||||
config_path = config_path,
|
||||
script_file = script_file.display(),
|
||||
cd_command = cd_command,
|
||||
provider_command = provider_command,
|
||||
final_cd_command = final_cd_command,
|
||||
exec_line = exec_line,
|
||||
);
|
||||
|
||||
std::fs::write(&script_file, &script_content).map_err(|e| format!("写入启动脚本失败: {e}"))?;
|
||||
@@ -2678,7 +2790,7 @@ exec bash --norc --noprofile
|
||||
"ghostty" => launch_macos_ghostty(&script_file),
|
||||
"wezterm" => launch_macos_open_app("WezTerm", &script_file, true),
|
||||
"kaku" => launch_macos_open_app("Kaku", &script_file, true),
|
||||
_ => launch_macos_terminal_app(&script_file), // "terminal" or default
|
||||
_ => launch_macos_terminal_app(&script_file),
|
||||
};
|
||||
|
||||
// If preferred terminal fails and it's not the default, try Terminal.app as fallback
|
||||
@@ -2704,7 +2816,16 @@ fn applescript_string_literal(value: &str) -> String {
|
||||
#[cfg(target_os = "macos")]
|
||||
fn applescript_launcher_command(script_file: &std::path::Path) -> String {
|
||||
applescript_string_literal(&format!(
|
||||
"bash {}",
|
||||
"sh {}",
|
||||
shell_single_quote(&script_file.to_string_lossy())
|
||||
))
|
||||
}
|
||||
|
||||
/// Build a launcher command that replaces the terminal-created shell session.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn applescript_exec_launcher_command(script_file: &std::path::Path) -> String {
|
||||
applescript_string_literal(&format!(
|
||||
"exec sh {}",
|
||||
shell_single_quote(&script_file.to_string_lossy())
|
||||
))
|
||||
}
|
||||
@@ -2727,7 +2848,7 @@ tell application "Terminal"
|
||||
activate
|
||||
end if
|
||||
end tell"#,
|
||||
launcher = applescript_launcher_command(script_file)
|
||||
launcher = applescript_exec_launcher_command(script_file)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2795,7 +2916,7 @@ tell application "iTerm"
|
||||
write text launcher_script
|
||||
end tell
|
||||
end tell"#,
|
||||
launcher = applescript_launcher_command(script_file)
|
||||
launcher = applescript_exec_launcher_command(script_file)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2805,12 +2926,12 @@ fn launch_macos_iterm2(script_file: &std::path::Path) -> Result<(), String> {
|
||||
run_terminal_osascript(&build_macos_iterm2_applescript(script_file), "iTerm2")
|
||||
}
|
||||
|
||||
/// Keep the launcher path inside a `bash -c` string.
|
||||
/// Keep the launcher path inside a `sh -c` string.
|
||||
/// A bare `.sh` passed through `open --args` may also be opened as a document.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn build_macos_dash_c_command(script_file: &std::path::Path) -> String {
|
||||
format!(
|
||||
"exec bash {}",
|
||||
"exec sh {}",
|
||||
shell_single_quote(&script_file.to_string_lossy())
|
||||
)
|
||||
}
|
||||
@@ -2865,8 +2986,8 @@ fn launch_macos_open_app(
|
||||
if use_e_flag {
|
||||
cmd.arg("-e");
|
||||
}
|
||||
// Keep the script path inside `bash -c`; a trailing bare `.sh` can be opened as a document.
|
||||
cmd.arg("bash")
|
||||
// Keep the script path inside `sh -c`; a trailing bare `.sh` can be opened as a document.
|
||||
cmd.arg("sh")
|
||||
.arg("-c")
|
||||
.arg(build_macos_dash_c_command(script_file));
|
||||
|
||||
@@ -2912,9 +3033,9 @@ fn launch_macos_warp(script_file: &std::path::Path) -> Result<(), String> {
|
||||
|
||||
rm -- "$0"
|
||||
|
||||
exec bash {}
|
||||
exec sh {quoted_script}
|
||||
"#,
|
||||
script_file.display(),
|
||||
quoted_script = shell_single_quote(&script_file.to_string_lossy()),
|
||||
)
|
||||
.map_err(|e| format!("Failed to write to temporary script file for Warp: {e}"))?;
|
||||
|
||||
@@ -2946,6 +3067,10 @@ fn launch_linux_terminal(config_file: &std::path::Path, cwd: Option<&Path>) -> R
|
||||
|
||||
let preferred = crate::settings::get_preferred_terminal();
|
||||
|
||||
let shell = get_user_shell();
|
||||
let exec_line = build_exec_line(&shell, cwd);
|
||||
let final_cd_command = build_final_shell_cd_command(&shell, cwd);
|
||||
|
||||
// Default terminal list with their arguments
|
||||
let default_terminals = [
|
||||
("gnome-terminal", vec!["--"]),
|
||||
@@ -2962,20 +3087,22 @@ fn launch_linux_terminal(config_file: &std::path::Path, cwd: Option<&Path>) -> R
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let script_file = temp_dir.join(format!("cc_switch_launcher_{}.sh", std::process::id()));
|
||||
let config_path = config_file.to_string_lossy();
|
||||
let cd_command = build_shell_cd_command(cwd);
|
||||
let provider_command = build_provider_command_line(&shell, &config_path, cwd);
|
||||
|
||||
let script_content = format!(
|
||||
r#"#!/bin/bash
|
||||
r#"#!/usr/bin/env sh
|
||||
trap 'rm -f "{config_path}" "{script_file}"' EXIT
|
||||
{cd_command}
|
||||
echo "Using provider-specific claude config:"
|
||||
echo "{config_path}"
|
||||
claude --settings "{config_path}"
|
||||
exec bash --norc --noprofile
|
||||
{provider_command}
|
||||
{final_cd_command}
|
||||
{exec_line}
|
||||
"#,
|
||||
config_path = config_path,
|
||||
script_file = script_file.display(),
|
||||
cd_command = cd_command,
|
||||
provider_command = provider_command,
|
||||
final_cd_command = final_cd_command,
|
||||
exec_line = exec_line,
|
||||
);
|
||||
|
||||
std::fs::write(&script_file, &script_content).map_err(|e| format!("写入启动脚本失败: {e}"))?;
|
||||
@@ -3019,7 +3146,7 @@ exec bash --norc --noprofile
|
||||
if terminal_exists {
|
||||
let result = Command::new(terminal)
|
||||
.args(&args)
|
||||
.arg("bash")
|
||||
.arg("sh")
|
||||
.arg(script_file.to_string_lossy().as_ref())
|
||||
.spawn();
|
||||
|
||||
@@ -3106,16 +3233,6 @@ del \"%~f0\" >nul 2>&1
|
||||
result
|
||||
}
|
||||
|
||||
fn build_shell_cd_command(cwd: Option<&Path>) -> String {
|
||||
cwd.map(|dir| {
|
||||
format!(
|
||||
"cd {} || exit 1\n",
|
||||
shell_single_quote(&dir.to_string_lossy())
|
||||
)
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn shell_single_quote(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "'\"'\"'"))
|
||||
}
|
||||
@@ -3182,7 +3299,7 @@ fn run_windows_start_command(args: &[&str], terminal_name: &str) -> Result<(), S
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 打开用户首选终端并在其中执行一段可信命令脚本。脚本尾部 `read -n 1` / `pause`
|
||||
/// 打开用户首选终端并在其中执行一段可信命令脚本。脚本尾部 `read -r` / `pause`
|
||||
/// 是刻意设计的——让命令退出后窗口不要瞬间关闭,用户才看得到 `command
|
||||
/// not found` / `ModuleNotFoundError` 这类诊断信息。
|
||||
///
|
||||
@@ -3196,14 +3313,14 @@ pub(crate) fn launch_terminal_running(command_line: &str, label: &str) -> Result
|
||||
let (script_file, script_content) = {
|
||||
let file = temp_dir.join(format!("cc_switch_{}_{}.sh", label, pid));
|
||||
let content = format!(
|
||||
r#"#!/bin/bash
|
||||
r#"#!/usr/bin/env sh
|
||||
trap 'rm -f "{script_path}"' EXIT
|
||||
echo "[cc-switch] Starting: {label}"
|
||||
echo ""
|
||||
{cmd}
|
||||
echo ""
|
||||
echo "[cc-switch] Command exited. Press any key to close."
|
||||
read -n 1 -s
|
||||
echo "[cc-switch] Command exited. Press Enter to close."
|
||||
read -r _
|
||||
"#,
|
||||
script_path = file.display(),
|
||||
label = label,
|
||||
@@ -3299,7 +3416,7 @@ read -n 1 -s
|
||||
if terminal_exists {
|
||||
let spawn_result = Command::new(terminal)
|
||||
.args(&args)
|
||||
.arg("bash")
|
||||
.arg("sh")
|
||||
.arg(script_file.to_string_lossy().as_ref())
|
||||
.spawn();
|
||||
match spawn_result {
|
||||
@@ -3387,6 +3504,126 @@ mod tests {
|
||||
use super::*;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[cfg(unix)]
|
||||
fn set_test_executable(path: &Path, executable: bool) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let mode = if executable { 0o755 } else { 0o644 };
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
|
||||
.expect("fixture permissions should be set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_exec_line() {
|
||||
assert_eq!(build_exec_line("/bin/zsh", None), "exec '/bin/zsh' -l");
|
||||
assert_eq!(build_exec_line("/bin/bash", None), "exec '/bin/bash'");
|
||||
assert_eq!(
|
||||
build_exec_line("/opt/homebrew dir/bin/fish", None),
|
||||
"exec '/opt/homebrew dir/bin/fish'"
|
||||
);
|
||||
assert_eq!(build_exec_line("/bin/sh", None), "exec '/bin/sh'");
|
||||
assert_eq!(
|
||||
build_exec_line("/tmp/shell'quote/zsh", None),
|
||||
"exec '/tmp/shell'\"'\"'quote/zsh' -l"
|
||||
);
|
||||
assert_eq!(
|
||||
build_exec_line("/bin/zsh", Some(Path::new("/tmp/project"))),
|
||||
r#"exec '/bin/zsh' -lc 'cd '"'"'/tmp/project'"'"' || exit 1; exec '"'"'/bin/zsh'"'"' -i'"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_provider_command_line_uses_user_shell_environment() {
|
||||
assert_eq!(
|
||||
build_provider_command_line("/bin/zsh", "/tmp/claude config.json", None),
|
||||
"'/bin/zsh' -lic 'claude --settings '\"'\"'/tmp/claude config.json'\"'\"''"
|
||||
);
|
||||
assert_eq!(
|
||||
build_provider_command_line(
|
||||
"/bin/bash",
|
||||
"/tmp/claude config.json",
|
||||
Some(Path::new("/tmp/project"))
|
||||
),
|
||||
r#"'/bin/bash' -ic 'cd '"'"'/tmp/project'"'"' && claude --settings '"'"'/tmp/claude config.json'"'"''"#
|
||||
);
|
||||
assert_eq!(
|
||||
build_provider_command_line(
|
||||
"/bin/sh",
|
||||
"/tmp/claude config.json",
|
||||
Some(Path::new("/tmp/project O'Brien"))
|
||||
),
|
||||
r#"'/bin/sh' -c 'cd '"'"'/tmp/project O'"'"'"'"'"'"'"'"'Brien'"'"' && claude --settings '"'"'/tmp/claude config.json'"'"''"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_final_shell_cd_command() {
|
||||
assert_eq!(build_final_shell_cd_command("/bin/zsh", None), "");
|
||||
assert_eq!(
|
||||
build_final_shell_cd_command("/bin/zsh", Some(Path::new("/tmp/project"))),
|
||||
""
|
||||
);
|
||||
assert_eq!(
|
||||
build_final_shell_cd_command("/bin/bash", Some(Path::new("/tmp/project O'Brien"))),
|
||||
"cd '/tmp/project O'\"'\"'Brien' || exit 1\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn test_get_user_shell_fallback() {
|
||||
// $SHELL 未设置时应按平台 fallback
|
||||
// 此测试验证 fallback 逻辑,但不验证环境变量值(取决于运行环境)
|
||||
let shell = get_user_shell();
|
||||
// 至少应返回一个合法的绝对路径
|
||||
assert!(valid_user_shell_path(&shell));
|
||||
// basename 应为合法 shell 名
|
||||
let basename = shell.rsplit('/').next().unwrap_or("sh");
|
||||
assert!(["sh", "bash", "zsh", "fish", "dash"].contains(&basename));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn test_valid_user_shell_path() {
|
||||
let temp = tempfile::tempdir().expect("temp dir should be created");
|
||||
let executable_zsh = temp.path().join("zsh");
|
||||
std::fs::write(&executable_zsh, "#!/usr/bin/env sh\n")
|
||||
.expect("shell fixture should be written");
|
||||
set_test_executable(&executable_zsh, true);
|
||||
|
||||
let executable_fish_dir = temp.path().join("homebrew dir/bin");
|
||||
std::fs::create_dir_all(&executable_fish_dir)
|
||||
.expect("shell fixture directory should be created");
|
||||
let executable_fish = executable_fish_dir.join("fish");
|
||||
std::fs::write(&executable_fish, "#!/usr/bin/env sh\n")
|
||||
.expect("shell fixture should be written");
|
||||
set_test_executable(&executable_fish, true);
|
||||
|
||||
let non_executable_bash = temp.path().join("bash");
|
||||
std::fs::write(&non_executable_bash, "#!/usr/bin/env sh\n")
|
||||
.expect("shell fixture should be written");
|
||||
set_test_executable(&non_executable_bash, false);
|
||||
|
||||
assert!(valid_user_shell_path(&executable_zsh.to_string_lossy()));
|
||||
assert!(valid_user_shell_path(&executable_fish.to_string_lossy()));
|
||||
assert!(!valid_user_shell_path(""));
|
||||
assert!(!valid_user_shell_path("zsh"));
|
||||
assert!(!valid_user_shell_path(
|
||||
&temp.path().join("missing/zsh").to_string_lossy()
|
||||
));
|
||||
assert!(!valid_user_shell_path(
|
||||
&non_executable_bash.to_string_lossy()
|
||||
));
|
||||
assert!(!valid_user_shell_path(
|
||||
&temp.path().join("zsh; rm -rf /").to_string_lossy()
|
||||
));
|
||||
assert!(!valid_user_shell_path(&format!(
|
||||
"{}\n/bin/bash",
|
||||
executable_zsh.to_string_lossy()
|
||||
)));
|
||||
assert!(!valid_user_shell_path("/usr/bin/powershell"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_version() {
|
||||
assert_eq!(extract_version("claude 1.0.20"), "1.0.20");
|
||||
@@ -4850,13 +5087,6 @@ mod tests {
|
||||
assert!(error.contains("目录不存在"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_shell_cd_command_quotes_spaces_and_single_quotes() {
|
||||
let command = build_shell_cd_command(Some(Path::new("/tmp/project O'Brien")));
|
||||
|
||||
assert_eq!(command, "cd '/tmp/project O'\"'\"'Brien' || exit 1\n");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn iterm2_applescript_cold_start_avoids_current_window_before_one_exists() {
|
||||
@@ -4918,6 +5148,10 @@ mod tests {
|
||||
),
|
||||
"already-running branch should use bare do script:\n{script}"
|
||||
);
|
||||
assert!(
|
||||
script.contains(r#"set launcher_script to "exec sh '/tmp/cc_switch_launcher.sh'""#),
|
||||
"Terminal should replace the auto-created shell:\n{script}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Restored windows should not receive the launcher command.
|
||||
@@ -4943,7 +5177,7 @@ mod tests {
|
||||
|
||||
// Warm launches execute through the AppleScript command property, not `open -na ... -e`.
|
||||
assert!(
|
||||
script.contains(r#"set launcher_command to "bash '/tmp/cc_switch_launcher.sh'""#),
|
||||
script.contains(r#"set launcher_command to "sh '/tmp/cc_switch_launcher.sh'""#),
|
||||
"missing launcher_command:\n{script}"
|
||||
);
|
||||
assert!(script.contains("if was_running then"));
|
||||
@@ -4983,11 +5217,11 @@ mod tests {
|
||||
fn dash_c_command_wraps_script_path_inside_quoted_arg() {
|
||||
// The script path must stay inside the `-c` string, not as a bare argv.
|
||||
let s = build_macos_dash_c_command(Path::new("/tmp/cc_switch_launcher_1.sh"));
|
||||
assert_eq!(s, "exec bash '/tmp/cc_switch_launcher_1.sh'");
|
||||
assert_eq!(s, "exec sh '/tmp/cc_switch_launcher_1.sh'");
|
||||
|
||||
// Spaces and single quotes must stay shell-safe too.
|
||||
let s2 = build_macos_dash_c_command(Path::new("/Users/me/it's dir/x.sh"));
|
||||
assert_eq!(s2, r#"exec bash '/Users/me/it'"'"'s dir/x.sh'"#);
|
||||
assert_eq!(s2, r#"exec sh '/Users/me/it'"'"'s dir/x.sh'"#);
|
||||
}
|
||||
|
||||
/// AppleScript launchers need both shell-path quoting and AppleScript string quoting.
|
||||
@@ -4995,20 +5229,26 @@ mod tests {
|
||||
#[test]
|
||||
fn applescript_builders_safely_quote_special_paths() {
|
||||
// First shell-quote the path, then wrap the whole command as an AppleScript string.
|
||||
let expected = r#""bash '/Users/me/it'\"'\"'s dir/x.sh'""#;
|
||||
let expected = r#""sh '/Users/me/it'\"'\"'s dir/x.sh'""#;
|
||||
let p = Path::new("/Users/me/it's dir/x.sh");
|
||||
assert_eq!(applescript_launcher_command(p), expected);
|
||||
assert_eq!(
|
||||
applescript_exec_launcher_command(p),
|
||||
r#""exec sh '/Users/me/it'\"'\"'s dir/x.sh'""#
|
||||
);
|
||||
assert!(
|
||||
build_macos_terminal_applescript(p).contains(expected),
|
||||
build_macos_terminal_applescript(p)
|
||||
.contains(r#""exec sh '/Users/me/it'\"'\"'s dir/x.sh'""#),
|
||||
"Terminal did not quote safely"
|
||||
);
|
||||
assert!(
|
||||
build_macos_iterm2_applescript(p).contains(expected),
|
||||
build_macos_iterm2_applescript(p)
|
||||
.contains(r#""exec sh '/Users/me/it'\"'\"'s dir/x.sh'""#),
|
||||
"iTerm2 did not quote safely"
|
||||
);
|
||||
assert!(
|
||||
build_macos_ghostty_applescript(p).contains(expected),
|
||||
"Ghostty did not quote safely"
|
||||
"Ghostty did not keep the non-exec launcher"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -514,9 +514,19 @@ async fn query_provider_usage_inner(
|
||||
let (base_url, api_key) =
|
||||
resolve_coding_plan_credentials(&app_type, provider, usage_script);
|
||||
|
||||
let quota = crate::services::coding_plan::get_coding_plan_quota(&base_url, &api_key)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to query coding plan: {e}"))?;
|
||||
// 火山方舟用账号 AK/SK 签名查询用量(存于 usage_script,与推理 api_key 分离);
|
||||
// 其他供应商为 None,service 层沿用 api_key。
|
||||
let access_key_id = usage_script.and_then(|s| s.access_key_id.clone());
|
||||
let secret_access_key = usage_script.and_then(|s| s.secret_access_key.clone());
|
||||
|
||||
let quota = crate::services::coding_plan::get_coding_plan_quota(
|
||||
&base_url,
|
||||
&api_key,
|
||||
access_key_id.as_deref(),
|
||||
secret_access_key.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to query coding plan: {e}"))?;
|
||||
|
||||
// 将 SubscriptionQuota 转换为 UsageResult
|
||||
if !quota.success {
|
||||
@@ -1086,6 +1096,8 @@ mod native_query_credentials_tests {
|
||||
template_type: Some("token_plan".to_string()),
|
||||
auto_query_interval: None,
|
||||
coding_plan_provider: coding_plan_provider.map(str::to_string),
|
||||
access_key_id: None,
|
||||
secret_access_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use tauri::AppHandle;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tauri_plugin_updater::UpdaterExt;
|
||||
|
||||
/// 应用更新下载进度(通过 `update-download-progress` 事件发给前端)。
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
struct UpdateDownloadProgress {
|
||||
downloaded: u64,
|
||||
total: Option<u64>,
|
||||
}
|
||||
|
||||
fn merge_settings_for_save(
|
||||
mut incoming: crate::settings::AppSettings,
|
||||
existing: &crate::settings::AppSettings,
|
||||
@@ -203,8 +210,22 @@ pub async fn install_update_and_restart(app: AppHandle) -> Result<bool, String>
|
||||
};
|
||||
|
||||
log::info!("开始下载应用更新: {}", update.version);
|
||||
let progress_handle = app.clone();
|
||||
let mut downloaded: u64 = 0;
|
||||
let bytes = update
|
||||
.download(|_, _| {}, || {})
|
||||
.download(
|
||||
move |chunk_len, content_len| {
|
||||
downloaded = downloaded.saturating_add(chunk_len as u64);
|
||||
let _ = progress_handle.emit(
|
||||
"update-download-progress",
|
||||
UpdateDownloadProgress {
|
||||
downloaded,
|
||||
total: content_len,
|
||||
},
|
||||
);
|
||||
},
|
||||
|| {},
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("下载更新失败: {e}"))?;
|
||||
|
||||
@@ -245,6 +266,24 @@ pub async fn install_update_and_restart(app: AppHandle) -> Result<bool, String>
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查是否有可用的应用更新,返回可用的新版本号(无更新时返回 None)。
|
||||
///
|
||||
/// 数据库版本过新的恢复界面用它判断:升级应用能否解决问题。若返回 None,说明
|
||||
/// 已是最新版本,但数据库仍不兼容(通常由第三方客户端或更高版本创建),应提示用户
|
||||
/// 升级无法解决,而不是让其反复尝试。
|
||||
#[tauri::command]
|
||||
pub async fn check_app_update_available(app: AppHandle) -> Result<Option<String>, String> {
|
||||
let updater = app
|
||||
.updater_builder()
|
||||
.build()
|
||||
.map_err(|e| format!("初始化更新器失败: {e}"))?;
|
||||
let update = updater
|
||||
.check()
|
||||
.await
|
||||
.map_err(|e| format!("检查更新失败: {e}"))?;
|
||||
Ok(update.map(|u| u.version))
|
||||
}
|
||||
|
||||
/// 获取 app_config_dir 覆盖配置 (从 Store)
|
||||
#[tauri::command]
|
||||
pub async fn get_app_config_dir_override(app: AppHandle) -> Result<Option<String>, String> {
|
||||
|
||||
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
@@ -47,25 +47,118 @@ pub fn get_default_claude_mcp_path() -> PathBuf {
|
||||
get_home_dir().join(".claude.json")
|
||||
}
|
||||
|
||||
fn derive_mcp_path_from_override(dir: &Path) -> Option<PathBuf> {
|
||||
let file_name = dir
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())?
|
||||
.trim()
|
||||
.to_string();
|
||||
if file_name.is_empty() {
|
||||
return None;
|
||||
fn normalize_path_lexically(path: &Path) -> PathBuf {
|
||||
let mut normalized = PathBuf::new();
|
||||
|
||||
for component in path.components() {
|
||||
match component {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
if !normalized.pop() {
|
||||
normalized.push(component.as_os_str());
|
||||
}
|
||||
}
|
||||
Component::Normal(part) => normalized.push(part),
|
||||
Component::RootDir | Component::Prefix(_) => normalized.push(component.as_os_str()),
|
||||
}
|
||||
}
|
||||
let parent = dir.parent().unwrap_or_else(|| Path::new(""));
|
||||
Some(parent.join(format!("{file_name}.json")))
|
||||
|
||||
normalized
|
||||
}
|
||||
|
||||
/// 获取 Claude MCP 配置文件路径,若设置了目录覆盖则与覆盖目录同级
|
||||
fn comparable_path_key(path: &Path) -> String {
|
||||
let mut key = normalize_path_lexically(path).to_string_lossy().to_string();
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
key = key.replace('\\', "/");
|
||||
}
|
||||
|
||||
while key.len() > 1 && key.ends_with('/') {
|
||||
key.pop();
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
key.make_ascii_lowercase();
|
||||
}
|
||||
|
||||
key
|
||||
}
|
||||
|
||||
fn path_eq_lexical(left: &Path, right: &Path) -> bool {
|
||||
comparable_path_key(left) == comparable_path_key(right)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn derive_wsl_default_mcp_path(dir: &Path) -> Option<PathBuf> {
|
||||
use std::path::Prefix;
|
||||
|
||||
let normalized = normalize_path_lexically(dir);
|
||||
let mut components = normalized.components();
|
||||
let prefix = match components.next()? {
|
||||
Component::Prefix(prefix) => prefix,
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let server = match prefix.kind() {
|
||||
Prefix::UNC(server, _) | Prefix::VerbatimUNC(server, _) => server.to_string_lossy(),
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
if !server.eq_ignore_ascii_case("wsl$") && !server.eq_ignore_ascii_case("wsl.localhost") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut parts = Vec::new();
|
||||
for component in components {
|
||||
match component {
|
||||
Component::RootDir | Component::CurDir => {}
|
||||
Component::Normal(part) => parts.push(part.to_string_lossy().to_string()),
|
||||
Component::ParentDir | Component::Prefix(_) => return None,
|
||||
}
|
||||
}
|
||||
|
||||
let is_wsl_home_default =
|
||||
parts.len() == 3 && parts[0] == "home" && !parts[1].is_empty() && parts[2] == ".claude";
|
||||
let is_wsl_root_default = parts.len() == 2 && parts[0] == "root" && parts[1] == ".claude";
|
||||
|
||||
if is_wsl_home_default || is_wsl_root_default {
|
||||
return normalized
|
||||
.parent()
|
||||
.map(|parent| parent.join(".claude.json"));
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn default_mcp_path_for_config_dir(dir: &Path) -> Option<PathBuf> {
|
||||
let default_config_dir = get_home_dir().join(".claude");
|
||||
if path_eq_lexical(dir, &default_config_dir) {
|
||||
return Some(get_default_claude_mcp_path());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if let Some(path) = derive_wsl_default_mcp_path(dir) {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn derive_mcp_path_from_override(dir: &Path) -> PathBuf {
|
||||
dir.join(".claude.json")
|
||||
}
|
||||
|
||||
/// 获取 Claude MCP 配置文件路径
|
||||
pub fn get_claude_mcp_path() -> PathBuf {
|
||||
if let Some(custom_dir) = crate::settings::get_claude_override_dir() {
|
||||
if let Some(path) = derive_mcp_path_from_override(&custom_dir) {
|
||||
if let Some(path) = default_mcp_path_for_config_dir(&custom_dir) {
|
||||
return path;
|
||||
}
|
||||
return derive_mcp_path_from_override(&custom_dir);
|
||||
}
|
||||
get_default_claude_mcp_path()
|
||||
}
|
||||
@@ -263,33 +356,73 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn derive_mcp_path_from_override_preserves_folder_name() {
|
||||
fn derive_mcp_path_from_override_uses_config_dir_for_custom_path() {
|
||||
let override_dir = PathBuf::from("/tmp/profile/.claude");
|
||||
let derived = derive_mcp_path_from_override(&override_dir)
|
||||
.expect("should derive path for nested dir");
|
||||
assert_eq!(derived, PathBuf::from("/tmp/profile/.claude.json"));
|
||||
let derived = derive_mcp_path_from_override(&override_dir);
|
||||
assert_eq!(derived, PathBuf::from("/tmp/profile/.claude/.claude.json"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_mcp_path_from_override_handles_non_hidden_folder() {
|
||||
fn derive_mcp_path_from_override_uses_config_dir_for_non_hidden_folder() {
|
||||
let override_dir = PathBuf::from("/data/claude-config");
|
||||
let derived = derive_mcp_path_from_override(&override_dir)
|
||||
.expect("should derive path for standard dir");
|
||||
assert_eq!(derived, PathBuf::from("/data/claude-config.json"));
|
||||
let derived = derive_mcp_path_from_override(&override_dir);
|
||||
assert_eq!(derived, PathBuf::from("/data/claude-config/.claude.json"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_mcp_path_from_override_supports_relative_rootless_dir() {
|
||||
let override_dir = PathBuf::from("claude");
|
||||
let derived = derive_mcp_path_from_override(&override_dir)
|
||||
.expect("should derive path for single segment");
|
||||
assert_eq!(derived, PathBuf::from("claude.json"));
|
||||
let derived = derive_mcp_path_from_override(&override_dir);
|
||||
assert_eq!(derived, PathBuf::from("claude/.claude.json"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_mcp_path_from_root_like_dir_returns_none() {
|
||||
fn derive_mcp_path_from_root_like_dir_uses_root_file() {
|
||||
let override_dir = PathBuf::from("/");
|
||||
assert!(derive_mcp_path_from_override(&override_dir).is_none());
|
||||
let derived = derive_mcp_path_from_override(&override_dir);
|
||||
assert_eq!(derived, PathBuf::from("/.claude.json"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_mcp_path_from_override_preserves_leading_parent_dirs() {
|
||||
let override_dir = PathBuf::from("../../profiles/work/.claude");
|
||||
let derived = derive_mcp_path_from_override(&override_dir);
|
||||
assert_eq!(derived, override_dir.join(".claude.json"));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn wsl_unc_home_default_uses_split_mcp_path() {
|
||||
let override_dir = PathBuf::from(r"\\wsl$\Ubuntu\home\travis\.claude");
|
||||
let derived = default_mcp_path_for_config_dir(&override_dir)
|
||||
.expect("WSL home default should use split MCP path");
|
||||
assert_eq!(
|
||||
derived,
|
||||
PathBuf::from(r"\\wsl$\Ubuntu\home\travis\.claude.json")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn wsl_unc_root_default_uses_split_mcp_path() {
|
||||
let override_dir = PathBuf::from(r"\\wsl.localhost\Ubuntu\root\.claude");
|
||||
let derived = default_mcp_path_for_config_dir(&override_dir)
|
||||
.expect("WSL root default should use split MCP path");
|
||||
assert_eq!(
|
||||
derived,
|
||||
PathBuf::from(r"\\wsl.localhost\Ubuntu\root\.claude.json")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn wsl_unc_custom_dir_uses_nested_mcp_path() {
|
||||
let override_dir = PathBuf::from(r"\\wsl$\Ubuntu\opt\claude\.claude");
|
||||
assert!(default_mcp_path_for_config_dir(&override_dir).is_none());
|
||||
assert_eq!(
|
||||
derive_mcp_path_from_override(&override_dir),
|
||||
PathBuf::from(r"\\wsl$\Ubuntu\opt\claude\.claude\.claude.json")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -493,8 +493,10 @@ mod tests {
|
||||
|
||||
{
|
||||
let conn = crate::database::lock_conn!(db.conn);
|
||||
let date_str = chrono::DateTime::from_timestamp(old_ts, 0)
|
||||
.unwrap()
|
||||
let date_str = Local
|
||||
.timestamp_opt(old_ts, 0)
|
||||
.single()
|
||||
.expect("old timestamp should be a valid local datetime")
|
||||
.format("%Y-%m-%d")
|
||||
.to_string();
|
||||
conn.execute(
|
||||
|
||||
@@ -159,6 +159,22 @@ impl Database {
|
||||
Ok(db)
|
||||
}
|
||||
|
||||
/// 读取磁盘上数据库的 `user_version`;仅当它比应用支持的 [`SCHEMA_VERSION`]
|
||||
/// 更新时返回 `Some(version)`。
|
||||
///
|
||||
/// 用于初始化失败后判断是否为「数据库版本过新(应用过旧,需升级应用)」的可恢复
|
||||
/// 场景——此时不应反复弹出无效的重试对话框,而应引导用户在应用内升级。
|
||||
pub fn stored_user_version_exceeds_supported(
|
||||
db_path: &std::path::Path,
|
||||
) -> Result<Option<i32>, AppError> {
|
||||
if !db_path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let conn = Connection::open(db_path).map_err(|e| AppError::Database(e.to_string()))?;
|
||||
let version = Self::get_user_version(&conn)?;
|
||||
Ok((version > SCHEMA_VERSION).then_some(version))
|
||||
}
|
||||
|
||||
/// 创建内存数据库(用于测试)
|
||||
pub fn memory() -> Result<Self, AppError> {
|
||||
let conn = Connection::open_in_memory().map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
@@ -1684,6 +1684,26 @@ impl Database {
|
||||
),
|
||||
// ====== 国产模型 (USD/1M tokens) ======
|
||||
// Doubao (字节跳动)
|
||||
// Seed 2.1 系列(2026-06 火山引擎官方 list 价,CNY 按 ~7.14 折算):
|
||||
// pro 输入 6 元 / 输出 30 元 / 命中 1.2 元
|
||||
// turbo 输入 3 元 / 输出 15 元 / 命中 0.6 元
|
||||
// 「缓存存储 0.017 元/M/小时」是按时长计费的存储费,与本表 cache_creation(按 token 写入价)口径不同,置 0。
|
||||
(
|
||||
"doubao-seed-2-1-pro",
|
||||
"Doubao Seed 2.1 Pro",
|
||||
"0.84",
|
||||
"4.2",
|
||||
"0.17",
|
||||
"0",
|
||||
),
|
||||
(
|
||||
"doubao-seed-2-1-turbo",
|
||||
"Doubao Seed 2.1 Turbo",
|
||||
"0.42",
|
||||
"2.1",
|
||||
"0.08",
|
||||
"0",
|
||||
),
|
||||
(
|
||||
"doubao-seed-code",
|
||||
"Doubao Seed Code",
|
||||
@@ -1853,6 +1873,7 @@ impl Database {
|
||||
("glm-4.6", "GLM-4.6", "0.6", "2.2", "0.11", "0"),
|
||||
("glm-5", "GLM-5", "1", "3.2", "0.2", "0"),
|
||||
("glm-5.1", "GLM-5.1", "1.4", "4.4", "0.26", "0"),
|
||||
("glm-5.2", "GLM-5.2", "1.4", "4.4", "0.26", "0"),
|
||||
// MiMo (小米)
|
||||
(
|
||||
"mimo-v2-flash",
|
||||
|
||||
@@ -235,6 +235,8 @@ fn build_provider_meta(request: &DeepLinkImportRequest) -> Result<Option<Provide
|
||||
template_type: None, // Deeplink providers don't specify template type (will use backward compatibility logic)
|
||||
auto_query_interval: request.usage_auto_interval,
|
||||
coding_plan_provider: None,
|
||||
access_key_id: None,
|
||||
secret_access_key: None,
|
||||
};
|
||||
|
||||
Ok(Some(ProviderMeta {
|
||||
|
||||
@@ -5,6 +5,17 @@ use std::sync::{OnceLock, RwLock};
|
||||
pub struct InitErrorPayload {
|
||||
pub path: String,
|
||||
pub error: String,
|
||||
/// 错误类别。`Some("db_version_too_new")` 表示数据库版本过新(应用过旧),
|
||||
/// 前端据此展示「升级应用」恢复界面而非直接退出。
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub kind: Option<String>,
|
||||
/// 磁盘上数据库的 user_version(数据库版本过新时填充)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub db_version: Option<i32>,
|
||||
/// 当前应用支持的 SCHEMA_VERSION(数据库版本过新时填充)。
|
||||
/// 当升级到最新版后 db_version 仍 > supported_version,说明可能由第三方客户端创建。
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub supported_version: Option<i32>,
|
||||
}
|
||||
|
||||
static INIT_ERROR: OnceLock<RwLock<Option<InitErrorPayload>>> = OnceLock::new();
|
||||
@@ -13,7 +24,6 @@ fn cell() -> &'static RwLock<Option<InitErrorPayload>> {
|
||||
INIT_ERROR.get_or_init(|| RwLock::new(None))
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn set_init_error(payload: InitErrorPayload) {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
if let Ok(mut guard) = cell().write() {
|
||||
@@ -102,6 +112,9 @@ mod tests {
|
||||
let payload = InitErrorPayload {
|
||||
path: "/tmp/config.json".into(),
|
||||
error: "broken json".into(),
|
||||
kind: None,
|
||||
db_version: None,
|
||||
supported_version: None,
|
||||
};
|
||||
set_init_error(payload.clone());
|
||||
let got = get_init_error().expect("should get payload back");
|
||||
|
||||
@@ -270,6 +270,16 @@ pub fn run() {
|
||||
// 拦截窗口关闭:根据设置决定是否最小化到托盘
|
||||
.on_window_event(|window, event| {
|
||||
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
|
||||
// 数据库版本过新的恢复模式下没有托盘可唤回,关闭即退出,避免应用隐身后台
|
||||
let in_db_recovery = crate::init_status::get_init_error()
|
||||
.map(|p| p.kind.as_deref() == Some("db_version_too_new"))
|
||||
.unwrap_or(false);
|
||||
if in_db_recovery {
|
||||
api.prevent_close();
|
||||
window.app_handle().exit(0);
|
||||
return;
|
||||
}
|
||||
|
||||
let settings = crate::settings::get_settings();
|
||||
|
||||
if settings.minimize_to_tray_on_close {
|
||||
@@ -403,6 +413,35 @@ pub fn run() {
|
||||
// 说明:从 v3.8.* 升级的用户通常会走到这里的 SQLite schema 迁移,
|
||||
// 若迁移失败(数据库损坏/权限不足/user_version 过新等),需要给用户明确提示,
|
||||
// 否则表现可能只是“应用打不开/闪退”。
|
||||
//
|
||||
// 预检:数据库版本过新时,必须先于任何 schema 写操作(create_tables 内含
|
||||
// DROP/ALTER 等 DDL)进入恢复界面,避免旧应用对读不懂的更新版 DB 落写。
|
||||
match crate::database::Database::stored_user_version_exceeds_supported(&db_path) {
|
||||
Ok(Some(version)) => {
|
||||
log::warn!("数据库版本过新(v{version}),引导用户在应用内升级应用");
|
||||
crate::init_status::set_init_error(crate::init_status::InitErrorPayload {
|
||||
path: db_path.display().to_string(),
|
||||
error: format!(
|
||||
"数据库版本过新({version}),当前应用仅支持 {},请升级应用后再尝试。",
|
||||
crate::database::SCHEMA_VERSION
|
||||
),
|
||||
kind: Some("db_version_too_new".to_string()),
|
||||
db_version: Some(version),
|
||||
supported_version: Some(crate::database::SCHEMA_VERSION),
|
||||
});
|
||||
// 主窗口默认 visible:false,恢复界面必须强制显示
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
log::warn!("预检数据库版本失败,继续正常初始化流程: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
let db = loop {
|
||||
match crate::database::Database::init() {
|
||||
Ok(db) => break Arc::new(db),
|
||||
@@ -1187,6 +1226,7 @@ pub fn run() {
|
||||
commands::set_log_config,
|
||||
commands::restart_app,
|
||||
commands::install_update_and_restart,
|
||||
commands::check_app_update_available,
|
||||
commands::check_for_updates,
|
||||
commands::is_portable_mode,
|
||||
commands::copy_text_to_clipboard,
|
||||
|
||||
@@ -251,6 +251,14 @@ pub struct UsageScript {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "codingPlanProvider")]
|
||||
pub coding_plan_provider: Option<String>,
|
||||
/// 火山方舟控制面 OpenAPI 的 AccessKey ID(用量查询签名用,与推理 Key 是两套凭据)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "accessKeyId")]
|
||||
pub access_key_id: Option<String>,
|
||||
/// 火山方舟控制面 OpenAPI 的 SecretAccessKey(同上)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "secretAccessKey")]
|
||||
pub secret_access_key: Option<String>,
|
||||
}
|
||||
|
||||
/// 用量数据
|
||||
@@ -374,6 +382,21 @@ pub struct CodexChatReasoningConfig {
|
||||
pub output_format: Option<String>,
|
||||
}
|
||||
|
||||
/// Local proxy request overrides applied after route/protocol transforms.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct LocalProxyRequestOverrides {
|
||||
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
||||
pub headers: HashMap<String, String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub body: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl LocalProxyRequestOverrides {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.headers.is_empty() && self.body.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// 供应商元数据
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ProviderMeta {
|
||||
@@ -458,6 +481,12 @@ pub struct ProviderMeta {
|
||||
/// Custom User-Agent for local proxy routing.
|
||||
#[serde(rename = "customUserAgent", skip_serializing_if = "Option::is_none")]
|
||||
pub custom_user_agent: Option<String>,
|
||||
/// Local proxy request overrides applied to the transformed upstream request.
|
||||
#[serde(
|
||||
rename = "localProxyRequestOverrides",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub local_proxy_request_overrides: Option<LocalProxyRequestOverrides>,
|
||||
/// 累加模式应用中,该 provider 是否已写入 live config。
|
||||
/// `None` 表示旧数据/未知状态,`Some(false)` 表示明确仅存在于数据库中。
|
||||
#[serde(rename = "liveConfigManaged", skip_serializing_if = "Option::is_none")]
|
||||
@@ -924,10 +953,11 @@ pub struct OpenCodeModelLimit {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
ClaudeModelConfig, CodexModelConfig, GeminiModelConfig, OpenCodeProviderConfig, Provider,
|
||||
ProviderManager, ProviderMeta, UniversalProvider,
|
||||
ClaudeModelConfig, CodexModelConfig, GeminiModelConfig, LocalProxyRequestOverrides,
|
||||
OpenCodeProviderConfig, Provider, ProviderManager, ProviderMeta, UniversalProvider,
|
||||
};
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[test]
|
||||
fn provider_meta_serializes_pricing_model_source() {
|
||||
@@ -955,6 +985,33 @@ mod tests {
|
||||
assert!(value.get("pricingModelSource").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_meta_roundtrips_local_proxy_request_overrides() {
|
||||
let meta = ProviderMeta {
|
||||
local_proxy_request_overrides: Some(LocalProxyRequestOverrides {
|
||||
headers: HashMap::from([("X-Test".to_string(), "yes".to_string())]),
|
||||
body: Some(json!({ "temperature": 0.2 })),
|
||||
}),
|
||||
..ProviderMeta::default()
|
||||
};
|
||||
|
||||
let value = serde_json::to_value(&meta).expect("serialize ProviderMeta");
|
||||
assert_eq!(
|
||||
value["localProxyRequestOverrides"]["headers"]["X-Test"],
|
||||
"yes"
|
||||
);
|
||||
assert_eq!(
|
||||
value["localProxyRequestOverrides"]["body"]["temperature"],
|
||||
0.2
|
||||
);
|
||||
|
||||
let decoded: ProviderMeta =
|
||||
serde_json::from_value(value).expect("deserialize ProviderMeta");
|
||||
let overrides = decoded.local_proxy_request_overrides.unwrap();
|
||||
assert_eq!(overrides.headers.get("X-Test"), Some(&"yes".to_string()));
|
||||
assert_eq!(overrides.body.unwrap()["temperature"], 0.2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_with_id_populates_defaults() {
|
||||
let settings_config = json!({
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! HTTP content-encoding 工具。
|
||||
//!
|
||||
//! reqwest 的自动解压已禁用(为了透传 accept-encoding),需要手动解压。
|
||||
//! 请求侧(如 Codex Desktop 在登录态发压缩请求体)与响应侧(上游压缩响应体)
|
||||
//! 共用同一套解压逻辑。
|
||||
|
||||
use axum::http::header::HeaderMap;
|
||||
use std::io::Read;
|
||||
|
||||
/// 把 content-encoding 值拆成有序 coding 列表(去掉 identity 与空值)。
|
||||
///
|
||||
/// HTTP 允许堆叠编码(如 `gzip, zstd`),各 coding 以逗号分隔;亦允许重复
|
||||
/// content-encoding 头,语义等同逗号拼接(见 [`get_content_encoding`])。
|
||||
fn split_codings(content_encoding: &str) -> Vec<&str> {
|
||||
content_encoding
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|c| !c.is_empty() && *c != "identity")
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 单个 coding 是否可被解压。
|
||||
fn is_single_supported(coding: &str) -> bool {
|
||||
matches!(
|
||||
coding,
|
||||
"gzip" | "x-gzip" | "deflate" | "br" | "zstd" | "zst"
|
||||
)
|
||||
}
|
||||
|
||||
/// 解压单个 content-coding。未知编码返回 `Ok(None)`。
|
||||
fn decompress_single(coding: &str, body: &[u8]) -> Result<Option<Vec<u8>>, std::io::Error> {
|
||||
match coding {
|
||||
"gzip" | "x-gzip" => {
|
||||
let mut decoder = flate2::read::GzDecoder::new(body);
|
||||
let mut decompressed = Vec::new();
|
||||
decoder.read_to_end(&mut decompressed)?;
|
||||
Ok(Some(decompressed))
|
||||
}
|
||||
"deflate" => {
|
||||
// RFC 9110: deflate 指 zlib 包裹格式;但部分上游 / 客户端发 raw deflate 流。
|
||||
// 先按规范尝试 zlib,失败再回退 raw —— 否则合规来源必然解压失败,
|
||||
// 原始压缩字节会被 fail-open 透传给 JSON 解析(#2234 形态 C 之一)。
|
||||
let mut decompressed = Vec::new();
|
||||
let mut zlib = flate2::read::ZlibDecoder::new(body);
|
||||
match zlib.read_to_end(&mut decompressed) {
|
||||
Ok(_) => Ok(Some(decompressed)),
|
||||
Err(zlib_err) => {
|
||||
log::debug!("deflate 按 zlib 解压失败({zlib_err}),回退 raw deflate");
|
||||
let mut decompressed = Vec::new();
|
||||
let mut raw = flate2::read::DeflateDecoder::new(body);
|
||||
raw.read_to_end(&mut decompressed)?;
|
||||
Ok(Some(decompressed))
|
||||
}
|
||||
}
|
||||
}
|
||||
"br" => {
|
||||
let mut decompressed = Vec::new();
|
||||
brotli::BrotliDecompress(&mut std::io::Cursor::new(body), &mut decompressed)?;
|
||||
Ok(Some(decompressed))
|
||||
}
|
||||
"zstd" | "zst" => {
|
||||
// Codex 登录态对请求体启用 zstd(Compression::Zstd);上游也可能 zstd 压缩响应。
|
||||
let decompressed = zstd::stream::decode_all(std::io::Cursor::new(body))?;
|
||||
Ok(Some(decompressed))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// 根据 content-encoding 解压 body 字节,支持堆叠编码(如 `gzip, zstd`)。
|
||||
///
|
||||
/// RFC 9110 §8.4:codings 按**应用顺序**列出,故解压须**反向**(最后应用的先解)。
|
||||
/// 返回 `Ok(None)` 表示存在不受支持的编码、原样透传——此时调用方必须保留
|
||||
/// content-encoding 头,否则下游(诊断 / 客户端)会把压缩字节误当明文。
|
||||
pub(crate) fn decompress_body(
|
||||
content_encoding: &str,
|
||||
body: &[u8],
|
||||
) -> Result<Option<Vec<u8>>, std::io::Error> {
|
||||
let codings = split_codings(content_encoding);
|
||||
if codings.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
// 任一 coding 不支持就整体放弃解压、保头透传,避免半解码的脏数据。
|
||||
if !codings.iter().all(|c| is_single_supported(c)) {
|
||||
log::warn!("不支持的 content-encoding: {content_encoding},跳过解压");
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// 反向解码:列表末尾是最后应用的编码,须最先解。
|
||||
let mut data: Option<Vec<u8>> = None;
|
||||
for coding in codings.iter().rev() {
|
||||
let input = data.as_deref().unwrap_or(body);
|
||||
match decompress_single(coding, input)? {
|
||||
Some(decompressed) => data = Some(decompressed),
|
||||
// 上面 is_single_supported 已校验,理论不会发生;防御性兜底。
|
||||
None => return Ok(None),
|
||||
}
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// 该 content-encoding(含堆叠,如 `gzip, zstd`)是否全部可被解压。
|
||||
///
|
||||
/// 请求侧用它做闸门:无法解压的压缩体不能透传给 JSON 解析,需直接拒绝。
|
||||
pub(crate) fn is_supported_content_encoding(content_encoding: &str) -> bool {
|
||||
let codings = split_codings(content_encoding);
|
||||
!codings.is_empty() && codings.iter().all(|c| is_single_supported(c))
|
||||
}
|
||||
|
||||
/// 从 header 提取 content-encoding(合并重复头,忽略 identity 与空值)。
|
||||
///
|
||||
/// HTTP 允许重复 content-encoding 头,语义等同逗号拼接,故用 `get_all` 合并;
|
||||
/// 返回值可能含多个逗号分隔的 coding,交由 [`decompress_body`] 反向解码。
|
||||
pub(crate) fn get_content_encoding(headers: &HeaderMap) -> Option<String> {
|
||||
let combined = headers
|
||||
.get_all("content-encoding")
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
.to_lowercase();
|
||||
if split_codings(&combined).is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(combined)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::http::HeaderValue;
|
||||
|
||||
#[test]
|
||||
fn decompress_body_deflate_handles_zlib_wrapped_per_rfc9110() {
|
||||
// RFC 9110 规范的 deflate = zlib 包裹格式(合规来源发的就是这个)
|
||||
let payload = br#"{"ok":true}"#;
|
||||
let mut encoder =
|
||||
flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
std::io::Write::write_all(&mut encoder, payload).unwrap();
|
||||
let compressed = encoder.finish().unwrap();
|
||||
|
||||
let decompressed = decompress_body("deflate", &compressed).unwrap().unwrap();
|
||||
assert_eq!(decompressed, payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompress_body_deflate_falls_back_to_raw_stream() {
|
||||
// 部分来源违规发 raw deflate 流,保持兼容
|
||||
let payload = br#"{"ok":true}"#;
|
||||
let mut encoder =
|
||||
flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
std::io::Write::write_all(&mut encoder, payload).unwrap();
|
||||
let compressed = encoder.finish().unwrap();
|
||||
|
||||
let decompressed = decompress_body("deflate", &compressed).unwrap().unwrap();
|
||||
assert_eq!(decompressed, payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompress_body_zstd_roundtrip() {
|
||||
// Codex 登录态发的就是 zstd 压缩请求体
|
||||
let payload = br#"{"hello":"world","n":42}"#;
|
||||
let compressed = zstd::stream::encode_all(std::io::Cursor::new(&payload[..]), 0).unwrap();
|
||||
let decompressed = decompress_body("zstd", &compressed).unwrap().unwrap();
|
||||
assert_eq!(decompressed, payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompress_body_stacked_gzip_then_zstd_decodes_in_reverse() {
|
||||
// Content-Encoding: gzip, zstd 表示先 gzip 后 zstd,解压须反向(先 zstd 后 gzip)
|
||||
let payload = br#"{"stacked":true}"#;
|
||||
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
std::io::Write::write_all(&mut gz, payload).unwrap();
|
||||
let gzipped = gz.finish().unwrap();
|
||||
let stacked = zstd::stream::encode_all(std::io::Cursor::new(&gzipped[..]), 0).unwrap();
|
||||
|
||||
let decompressed = decompress_body("gzip, zstd", &stacked).unwrap().unwrap();
|
||||
assert_eq!(decompressed, payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompress_body_stacked_with_unsupported_returns_none() {
|
||||
// 堆叠里只要有一个不支持,就整体保头透传
|
||||
let result = decompress_body("snappy, zstd", b"\x00\x01\x02\x03").unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompress_body_unknown_encoding_returns_none_to_keep_headers() {
|
||||
// 未知编码必须返回 None(而非伪装成"已解码"),否则 content-encoding
|
||||
// 头被剥掉,下游诊断会把压缩字节误报成明文
|
||||
let result = decompress_body("snappy", b"\x00\x01\x02\x03").unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_supported_content_encoding_matches_decompressable() {
|
||||
for enc in [
|
||||
"gzip",
|
||||
"x-gzip",
|
||||
"deflate",
|
||||
"br",
|
||||
"zstd",
|
||||
"zst",
|
||||
"gzip, zstd",
|
||||
] {
|
||||
assert!(is_supported_content_encoding(enc), "{enc} 应受支持");
|
||||
}
|
||||
for enc in ["identity", "snappy", "compress", "", "gzip, snappy"] {
|
||||
assert!(!is_supported_content_encoding(enc), "{enc} 不应受支持");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_content_encoding_combines_repeated_headers() {
|
||||
// 重复的 content-encoding 头等同逗号拼接,须用 get_all 合并
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.append("content-encoding", HeaderValue::from_static("gzip"));
|
||||
headers.append("content-encoding", HeaderValue::from_static("zstd"));
|
||||
assert_eq!(
|
||||
get_content_encoding(&headers).as_deref(),
|
||||
Some("gzip, zstd")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_content_encoding_ignores_identity_only() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.append("content-encoding", HeaderValue::from_static("identity"));
|
||||
assert_eq!(get_content_encoding(&headers), None);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
use super::hyper_client::ProxyResponse;
|
||||
use super::{
|
||||
body_filter::filter_private_params_with_whitelist,
|
||||
content_encoding::{decompress_body, get_content_encoding},
|
||||
error::*,
|
||||
failover_switch::FailoverSwitchManager,
|
||||
json_canonical::{canonicalize_value, short_value_hash},
|
||||
@@ -24,7 +25,10 @@ use super::{
|
||||
use crate::commands::{CodexOAuthState, CopilotAuthState};
|
||||
use crate::proxy::providers::codex_oauth_auth::CodexOAuthManager;
|
||||
use crate::proxy::providers::copilot_auth::CopilotAuthManager;
|
||||
use crate::{app_config::AppType, provider::Provider};
|
||||
use crate::{
|
||||
app_config::AppType,
|
||||
provider::{LocalProxyRequestOverrides, Provider},
|
||||
};
|
||||
use futures::StreamExt;
|
||||
use http::Extensions;
|
||||
use serde_json::Value;
|
||||
@@ -1350,7 +1354,7 @@ impl RequestForwarder {
|
||||
.await;
|
||||
if restored > 0 {
|
||||
log::debug!(
|
||||
"[Codex] Restored {restored} cached function call(s) for Chat upstream"
|
||||
"[Codex] Restored or enriched {restored} cached function call item(s) for Chat upstream"
|
||||
);
|
||||
}
|
||||
super::providers::apply_codex_chat_upstream_model(provider, &mut mapped_body);
|
||||
@@ -1386,7 +1390,18 @@ impl RequestForwarder {
|
||||
|
||||
// 过滤私有参数(以 `_` 开头的字段),防止内部信息泄露到上游
|
||||
// 默认使用空白名单,过滤所有 _ 前缀字段
|
||||
let filtered_body = prepare_upstream_request_body(request_body);
|
||||
let mut filtered_body = prepare_upstream_request_body(request_body);
|
||||
if !is_copilot {
|
||||
if let Some(overrides) = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.local_proxy_request_overrides.as_ref())
|
||||
{
|
||||
if apply_local_proxy_body_overrides(&mut filtered_body, overrides) {
|
||||
filtered_body = prepare_upstream_request_body(filtered_body);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 出站 body 定稿后刷新真值(覆盖 Codex chat 上游模型覆写、转换层模型改写)
|
||||
if let Some(m) = filtered_body
|
||||
.get("model")
|
||||
@@ -1833,6 +1848,15 @@ impl RequestForwarder {
|
||||
);
|
||||
}
|
||||
|
||||
apply_local_proxy_header_overrides(
|
||||
&mut ordered_headers,
|
||||
provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.local_proxy_request_overrides.as_ref()),
|
||||
is_copilot,
|
||||
);
|
||||
|
||||
reject_proxy_placeholder_for_managed_account_upstream(&url, &ordered_headers)?;
|
||||
|
||||
// 输出请求信息日志
|
||||
@@ -1942,7 +1966,20 @@ impl RequestForwarder {
|
||||
Ok((response, resolved_claude_api_format, outbound_model))
|
||||
} else {
|
||||
let status_code = status.as_u16();
|
||||
let body_text = String::from_utf8(response.bytes().await?.to_vec()).ok();
|
||||
// 错误响应同样可能被上游压缩(content-encoding)。reqwest 未启用任何
|
||||
// 自动解压 feature,这里拿到的是原始字节;不解压的话,压缩过的错误体会
|
||||
// 在 from_utf8 处变成非 UTF-8 而被丢弃,隐藏掉上游的限流/鉴权等详情。
|
||||
let encoding = get_content_encoding(response.headers());
|
||||
let raw = response.bytes().await?;
|
||||
let decoded = match encoding {
|
||||
Some(encoding) => match decompress_body(&encoding, &raw) {
|
||||
Ok(Some(decompressed)) => decompressed,
|
||||
// 不支持的编码 / 解压失败:退回原始字节,尽量保留可读信息
|
||||
_ => raw.to_vec(),
|
||||
},
|
||||
None => raw.to_vec(),
|
||||
};
|
||||
let body_text = String::from_utf8(decoded).ok();
|
||||
|
||||
Err(ProxyError::UpstreamError {
|
||||
status: status_code,
|
||||
@@ -2544,6 +2581,154 @@ fn summarize_text_for_log(text: &str, max_chars: usize) -> String {
|
||||
format!("{truncated}...")
|
||||
}
|
||||
|
||||
fn apply_local_proxy_body_overrides(
|
||||
body: &mut Value,
|
||||
overrides: &LocalProxyRequestOverrides,
|
||||
) -> bool {
|
||||
let Some(override_body) = overrides.body.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if !override_body.is_object() {
|
||||
log::warn!("[LocalProxyOverrides] Ignoring body override because it is not an object");
|
||||
return false;
|
||||
}
|
||||
|
||||
merge_json_override(body, override_body)
|
||||
}
|
||||
|
||||
fn merge_json_override(target: &mut Value, patch: &Value) -> bool {
|
||||
merge_json_override_inner(target, patch, true)
|
||||
}
|
||||
|
||||
fn merge_json_override_inner(target: &mut Value, patch: &Value, is_top_level: bool) -> bool {
|
||||
match (target, patch) {
|
||||
(Value::Object(target_map), Value::Object(patch_map)) => {
|
||||
let mut changed = false;
|
||||
for (key, patch_value) in patch_map {
|
||||
if is_top_level && key == "stream" {
|
||||
log::warn!(
|
||||
"[LocalProxyOverrides] Ignoring body override for protected field: stream"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
match target_map.get_mut(key) {
|
||||
Some(target_value) => {
|
||||
changed |= merge_json_override_inner(target_value, patch_value, false);
|
||||
}
|
||||
None => {
|
||||
target_map.insert(key.clone(), patch_value.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
(target_value, patch_value) => {
|
||||
if target_value == patch_value {
|
||||
false
|
||||
} else {
|
||||
*target_value = patch_value.clone();
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_local_proxy_header_overrides(
|
||||
headers: &mut http::HeaderMap,
|
||||
overrides: Option<&LocalProxyRequestOverrides>,
|
||||
is_copilot: bool,
|
||||
) {
|
||||
if is_copilot {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(header_overrides) = overrides.map(|overrides| &overrides.headers) else {
|
||||
return;
|
||||
};
|
||||
|
||||
for (raw_name, raw_value) in header_overrides {
|
||||
let header_name = raw_name.trim().to_ascii_lowercase();
|
||||
if header_name.is_empty() {
|
||||
log::warn!("[LocalProxyOverrides] Ignoring header override with empty name");
|
||||
continue;
|
||||
}
|
||||
|
||||
let Ok(name) = http::HeaderName::from_bytes(header_name.as_bytes()) else {
|
||||
log::warn!("[LocalProxyOverrides] Ignoring invalid header override name: {raw_name}");
|
||||
continue;
|
||||
};
|
||||
|
||||
if is_protected_local_proxy_override_header(&name) {
|
||||
log::debug!(
|
||||
"[LocalProxyOverrides] Ignoring protected header override: {}",
|
||||
name.as_str()
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
let Ok(value) = http::HeaderValue::from_str(raw_value) else {
|
||||
log::warn!(
|
||||
"[LocalProxyOverrides] Ignoring invalid header override value for {}",
|
||||
name.as_str()
|
||||
);
|
||||
continue;
|
||||
};
|
||||
|
||||
headers.insert(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_protected_local_proxy_override_header(name: &http::HeaderName) -> bool {
|
||||
matches!(
|
||||
name.as_str(),
|
||||
"host"
|
||||
| "content-length"
|
||||
| "transfer-encoding"
|
||||
| "connection"
|
||||
| "proxy-authorization"
|
||||
| "proxy-authenticate"
|
||||
| "te"
|
||||
| "trailer"
|
||||
| "upgrade"
|
||||
| "accept-encoding"
|
||||
| "content-type"
|
||||
| "authorization"
|
||||
| "x-api-key"
|
||||
| "x-goog-api-key"
|
||||
| "chatgpt-account-id"
|
||||
| "session_id"
|
||||
| "x-client-request-id"
|
||||
| "x-codex-window-id"
|
||||
| "x-forwarded-host"
|
||||
| "x-forwarded-port"
|
||||
| "x-forwarded-proto"
|
||||
| "forwarded"
|
||||
| "cf-connecting-ip"
|
||||
| "cf-ipcountry"
|
||||
| "cf-ray"
|
||||
| "cf-visitor"
|
||||
| "true-client-ip"
|
||||
| "fastly-client-ip"
|
||||
| "x-azure-clientip"
|
||||
| "x-azure-fdid"
|
||||
| "x-azure-ref"
|
||||
| "akamai-origin-hop"
|
||||
| "x-akamai-config-log-detail"
|
||||
| "x-request-id"
|
||||
| "x-correlation-id"
|
||||
| "x-trace-id"
|
||||
| "x-amzn-trace-id"
|
||||
| "x-b3-traceid"
|
||||
| "x-b3-spanid"
|
||||
| "x-b3-parentspanid"
|
||||
| "x-b3-sampled"
|
||||
| "traceparent"
|
||||
| "tracestate"
|
||||
)
|
||||
}
|
||||
|
||||
fn prepare_upstream_request_body(request_body: Value) -> Value {
|
||||
canonicalize_value(filter_private_params_with_whitelist(request_body, &[]))
|
||||
}
|
||||
@@ -2607,6 +2792,7 @@ fn value_for_log(value: &Value) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::database::Database;
|
||||
use crate::provider::LocalProxyRequestOverrides;
|
||||
use axum::http::header::{HeaderValue, ACCEPT};
|
||||
use axum::http::HeaderMap;
|
||||
use bytes::Bytes;
|
||||
@@ -2806,6 +2992,116 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_proxy_body_overrides_deep_merge_final_body_without_stream() {
|
||||
let mut body = json!({
|
||||
"model": "before",
|
||||
"stream": false,
|
||||
"metadata": {
|
||||
"keep": true,
|
||||
"temperature": 1
|
||||
},
|
||||
"messages": [{ "role": "user", "content": "hello" }]
|
||||
});
|
||||
let overrides = LocalProxyRequestOverrides {
|
||||
headers: HashMap::new(),
|
||||
body: Some(json!({
|
||||
"model": "after",
|
||||
"stream": true,
|
||||
"metadata": {
|
||||
"temperature": 0.2,
|
||||
"top_p": 0.9
|
||||
},
|
||||
"messages": []
|
||||
})),
|
||||
};
|
||||
|
||||
assert!(apply_local_proxy_body_overrides(&mut body, &overrides));
|
||||
|
||||
assert_eq!(body["model"], "after");
|
||||
assert_eq!(body["stream"], false);
|
||||
assert_eq!(body["metadata"]["keep"], true);
|
||||
assert_eq!(body["metadata"]["temperature"], 0.2);
|
||||
assert_eq!(body["metadata"]["top_p"], 0.9);
|
||||
assert_eq!(body["messages"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_proxy_header_overrides_replace_allowed_headers_only() {
|
||||
let mut headers = http::HeaderMap::new();
|
||||
headers.insert(
|
||||
http::header::USER_AGENT,
|
||||
http::HeaderValue::from_static("original"),
|
||||
);
|
||||
headers.insert(
|
||||
http::header::AUTHORIZATION,
|
||||
http::HeaderValue::from_static("Bearer good"),
|
||||
);
|
||||
headers.insert(
|
||||
http::header::CONTENT_TYPE,
|
||||
http::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
|
||||
let overrides = LocalProxyRequestOverrides {
|
||||
headers: HashMap::from([
|
||||
("User-Agent".to_string(), "custom".to_string()),
|
||||
("X-Test".to_string(), "ok".to_string()),
|
||||
("Authorization".to_string(), "Bearer bad".to_string()),
|
||||
("Content-Type".to_string(), "text/plain".to_string()),
|
||||
("X-Bad".to_string(), "bad\nvalue".to_string()),
|
||||
]),
|
||||
body: None,
|
||||
};
|
||||
|
||||
apply_local_proxy_header_overrides(&mut headers, Some(&overrides), false);
|
||||
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(http::header::USER_AGENT)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("custom")
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("Bearer good")
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(http::header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("application/json")
|
||||
);
|
||||
assert_eq!(
|
||||
headers.get("x-test").and_then(|value| value.to_str().ok()),
|
||||
Some("ok")
|
||||
);
|
||||
assert!(headers.get("x-bad").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_proxy_header_overrides_are_skipped_for_copilot() {
|
||||
let mut headers = http::HeaderMap::new();
|
||||
headers.insert(
|
||||
http::header::USER_AGENT,
|
||||
http::HeaderValue::from_static("copilot"),
|
||||
);
|
||||
let overrides = LocalProxyRequestOverrides {
|
||||
headers: HashMap::from([("User-Agent".to_string(), "custom".to_string())]),
|
||||
body: None,
|
||||
};
|
||||
|
||||
apply_local_proxy_header_overrides(&mut headers, Some(&overrides), true);
|
||||
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(http::header::USER_AGENT)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("copilot")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn non_streaming_success_is_buffered_before_marking_provider_successful() {
|
||||
let forwarder = test_forwarder(Duration::from_secs(1), Duration::from_secs(1));
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
//! - Claude 的格式转换逻辑保留在此文件(用于 OpenRouter 旧接口回退)
|
||||
|
||||
use super::{
|
||||
content_encoding::{decompress_body, get_content_encoding, is_supported_content_encoding},
|
||||
error_mapper::{get_error_message, map_proxy_error_to_status},
|
||||
forwarder::ActiveConnectionGuard,
|
||||
handler_config::{
|
||||
@@ -568,6 +569,49 @@ fn endpoint_with_query(uri: &axum::http::Uri, endpoint: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Codex 客户端(尤其 Desktop 登录态)可能对请求体启用 zstd 压缩,使得后续
|
||||
/// `serde_json::from_slice` 直接解析失败。这里在解析前解压,并剥掉已失真的实体头
|
||||
/// (content-encoding / content-length / transfer-encoding)——转发层会基于解压后的
|
||||
/// 明文 JSON 重新生成正确的头。
|
||||
fn decode_codex_request_body(
|
||||
headers: &mut axum::http::HeaderMap,
|
||||
body_bytes: Bytes,
|
||||
) -> Result<Bytes, ProxyError> {
|
||||
let Some(encoding) = get_content_encoding(headers) else {
|
||||
return Ok(body_bytes);
|
||||
};
|
||||
|
||||
if !is_supported_content_encoding(&encoding) {
|
||||
return Err(ProxyError::InvalidRequest(format!(
|
||||
"Unsupported request content-encoding: {encoding}"
|
||||
)));
|
||||
}
|
||||
|
||||
log::debug!("[Codex] 解压请求体: content-encoding={encoding}");
|
||||
let decompressed = match decompress_body(&encoding, &body_bytes) {
|
||||
Ok(Some(decompressed)) => decompressed,
|
||||
// is_supported_content_encoding 已确保编码受支持,正常不会返回 None;
|
||||
// 防御性兜底:宁可报错,也不能把压缩字节当 JSON 透传下去。
|
||||
Ok(None) => {
|
||||
return Err(ProxyError::InvalidRequest(format!(
|
||||
"Unsupported request content-encoding: {encoding}"
|
||||
)));
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("[Codex] 请求体解压失败 ({encoding}): {e}");
|
||||
return Err(ProxyError::InvalidRequest(format!(
|
||||
"Failed to decompress request body ({encoding}): {e}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
headers.remove(axum::http::header::CONTENT_ENCODING);
|
||||
headers.remove(axum::http::header::CONTENT_LENGTH);
|
||||
headers.remove(axum::http::header::TRANSFER_ENCODING);
|
||||
|
||||
Ok(Bytes::from(decompressed))
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Codex API 处理器
|
||||
// ============================================================================
|
||||
@@ -580,13 +624,14 @@ pub async fn handle_chat_completions(
|
||||
let (parts, req_body) = request.into_parts();
|
||||
let method = parts.method.clone();
|
||||
let uri = parts.uri;
|
||||
let headers = parts.headers;
|
||||
let mut headers = parts.headers;
|
||||
let extensions = parts.extensions;
|
||||
let body_bytes = req_body
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to read request body: {e}")))?
|
||||
.to_bytes();
|
||||
let body_bytes = decode_codex_request_body(&mut headers, body_bytes)?;
|
||||
let body: Value = serde_json::from_slice(&body_bytes)
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to parse request body: {e}")))?;
|
||||
|
||||
@@ -645,13 +690,14 @@ pub async fn handle_responses(
|
||||
let (parts, req_body) = request.into_parts();
|
||||
let method = parts.method.clone();
|
||||
let uri = parts.uri;
|
||||
let headers = parts.headers;
|
||||
let mut headers = parts.headers;
|
||||
let extensions = parts.extensions;
|
||||
let body_bytes = req_body
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to read request body: {e}")))?
|
||||
.to_bytes();
|
||||
let body_bytes = decode_codex_request_body(&mut headers, body_bytes)?;
|
||||
let body: Value = serde_json::from_slice(&body_bytes)
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to parse request body: {e}")))?;
|
||||
|
||||
@@ -723,13 +769,14 @@ pub async fn handle_responses_compact(
|
||||
let (parts, req_body) = request.into_parts();
|
||||
let method = parts.method.clone();
|
||||
let uri = parts.uri;
|
||||
let headers = parts.headers;
|
||||
let mut headers = parts.headers;
|
||||
let extensions = parts.extensions;
|
||||
let body_bytes = req_body
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to read request body: {e}")))?
|
||||
.to_bytes();
|
||||
let body_bytes = decode_codex_request_body(&mut headers, body_bytes)?;
|
||||
let body: Value = serde_json::from_slice(&body_bytes)
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to parse request body: {e}")))?;
|
||||
|
||||
|
||||
@@ -223,7 +223,8 @@ fn build_client(proxy_url: Option<&str>) -> Result<Client, String> {
|
||||
// 响应解压由 response_processor 根据 content-encoding 手动处理。
|
||||
.no_gzip()
|
||||
.no_brotli()
|
||||
.no_deflate();
|
||||
.no_deflate()
|
||||
.no_zstd();
|
||||
|
||||
// 有代理地址则使用代理,否则跟随系统代理
|
||||
if let Some(url) = proxy_url {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
pub mod body_filter;
|
||||
pub mod cache_injector;
|
||||
pub mod circuit_breaker;
|
||||
pub(crate) mod content_encoding;
|
||||
pub mod copilot_optimizer;
|
||||
pub mod error;
|
||||
pub mod error_mapper;
|
||||
|
||||
@@ -145,6 +145,77 @@ pub fn normalize_anthropic_tool_thinking_history_for_provider(
|
||||
normalize_anthropic_tool_thinking_history(body)
|
||||
}
|
||||
|
||||
/// DeepSeek official Anthropic-compatible endpoint URL
|
||||
const DEEPSEEK_OFFICIAL_ANTHROPIC_URL: &str = "https://api.deepseek.com/anthropic";
|
||||
|
||||
/// Check whether the provider is configured to use DeepSeek's official
|
||||
/// Anthropic-compatible endpoint.
|
||||
fn is_deepseek_official_anthropic_endpoint(provider: &Provider) -> bool {
|
||||
let settings = &provider.settings_config;
|
||||
let base_url = settings
|
||||
.get("env")
|
||||
.and_then(|env| env.get("ANTHROPIC_BASE_URL"))
|
||||
.and_then(|v| v.as_str())
|
||||
.or_else(|| settings.get("base_url").and_then(|v| v.as_str()))
|
||||
.or_else(|| settings.get("baseURL").and_then(|v| v.as_str()))
|
||||
.or_else(|| settings.get("apiEndpoint").and_then(|v| v.as_str()));
|
||||
|
||||
base_url.map(|u| u.trim_end_matches('/')) == Some(DEEPSEEK_OFFICIAL_ANTHROPIC_URL)
|
||||
}
|
||||
|
||||
/// DeepSeek's official Anthropic-compatible endpoint treats
|
||||
/// `thinking: { type: "disabled" }` and effort parameters (`output_config.effort`
|
||||
/// or `reasoning_effort`) as mutually exclusive, returning HTTP 400:
|
||||
/// "thinking options type cannot be disabled when reasoning_effort is set".
|
||||
/// This breaks Claude Code 2.1.166+ Workflow/Dynamic Workflow features.
|
||||
///
|
||||
/// Rather than overriding Claude Code's intentional `thinking: disabled` for
|
||||
/// sub-agents, we respect that decision and remove the conflicting effort
|
||||
/// parameters instead. `thinking: disabled` means "don't output thinking
|
||||
/// blocks", which is the correct behavior for sub-agents that don't need
|
||||
/// to display reasoning to the user.
|
||||
///
|
||||
/// <https://github.com/deepseek-ai/DeepSeek-V3/issues/1397>
|
||||
pub fn normalize_deepseek_thinking_disabled_strip_effort(
|
||||
body: &mut Value,
|
||||
provider: &Provider,
|
||||
) -> bool {
|
||||
if !is_deepseek_official_anthropic_endpoint(provider) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let thinking_type = body
|
||||
.get("thinking")
|
||||
.and_then(|t| t.get("type"))
|
||||
.and_then(|t| t.as_str());
|
||||
|
||||
if thinking_type != Some("disabled") {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut changed = false;
|
||||
|
||||
// Remove output_config.effort (Anthropic format)
|
||||
if let Some(oc) = body
|
||||
.get_mut("output_config")
|
||||
.and_then(|v| v.as_object_mut())
|
||||
{
|
||||
changed |= oc.remove("effort").is_some();
|
||||
// Clean up empty output_config
|
||||
if oc.is_empty() {
|
||||
body.as_object_mut().unwrap().remove("output_config");
|
||||
}
|
||||
}
|
||||
|
||||
// Remove reasoning_effort (OpenAI format, may be present in passthrough)
|
||||
if body.get("reasoning_effort").is_some() {
|
||||
body.as_object_mut().unwrap().remove("reasoning_effort");
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
pub fn normalize_anthropic_messages_for_provider(
|
||||
body: &mut Value,
|
||||
provider: &Provider,
|
||||
@@ -154,77 +225,12 @@ pub fn normalize_anthropic_messages_for_provider(
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut changed = normalize_anthropic_system_role_messages(body);
|
||||
changed |= normalize_anthropic_tool_thinking_history_for_provider(body, provider, api_format);
|
||||
let mut changed =
|
||||
normalize_anthropic_tool_thinking_history_for_provider(body, provider, api_format);
|
||||
changed |= normalize_deepseek_thinking_disabled_strip_effort(body, provider);
|
||||
changed
|
||||
}
|
||||
|
||||
fn normalize_anthropic_system_role_messages(body: &mut Value) -> bool {
|
||||
let mut system_parts = Vec::new();
|
||||
let changed = {
|
||||
let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let original_len = messages.len();
|
||||
let mut kept_messages = Vec::with_capacity(messages.len());
|
||||
for message in std::mem::take(messages) {
|
||||
if message.get("role").and_then(Value::as_str) == Some("system") {
|
||||
if let Some(content) = message.get("content") {
|
||||
append_anthropic_system_parts(content, &mut system_parts);
|
||||
}
|
||||
} else {
|
||||
kept_messages.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
let changed = kept_messages.len() != original_len;
|
||||
*messages = kept_messages;
|
||||
changed
|
||||
};
|
||||
|
||||
if !changed || system_parts.is_empty() {
|
||||
return changed;
|
||||
}
|
||||
|
||||
let mut merged_parts = Vec::new();
|
||||
if let Some(existing) = body.get("system") {
|
||||
append_anthropic_system_parts(existing, &mut merged_parts);
|
||||
}
|
||||
merged_parts.extend(system_parts);
|
||||
|
||||
if !merged_parts.is_empty() {
|
||||
body["system"] = Value::Array(merged_parts);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn append_anthropic_system_parts(content: &Value, parts: &mut Vec<Value>) {
|
||||
match content {
|
||||
Value::String(text) if !text.trim().is_empty() => {
|
||||
parts.push(json!({
|
||||
"type": "text",
|
||||
"text": text
|
||||
}));
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for item in items {
|
||||
append_anthropic_system_parts(item, parts);
|
||||
}
|
||||
}
|
||||
Value::Object(obj)
|
||||
if obj
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|text| !text.trim().is_empty()) =>
|
||||
{
|
||||
parts.push(Value::Object(obj.clone()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_anthropic_tool_thinking_history(body: &mut Value) -> bool {
|
||||
let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
|
||||
return false;
|
||||
@@ -2117,7 +2123,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_system_role_messages_move_to_top_level_system() {
|
||||
fn test_anthropic_messages_no_longer_hoists_system_role_messages() {
|
||||
// After reverting #3775, role=system messages are left in `messages[]`
|
||||
// (DeepSeek's endpoint accepts them natively) and the top-level `system`
|
||||
// field is untouched, preserving the request prefix.
|
||||
let provider = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
|
||||
@@ -2139,15 +2148,13 @@ mod tests {
|
||||
|
||||
let changed = normalize_anthropic_messages_for_provider(&mut body, &provider, "anthropic");
|
||||
|
||||
assert!(changed);
|
||||
assert!(!changed);
|
||||
let messages = body["messages"].as_array().unwrap();
|
||||
assert_eq!(messages.len(), 1);
|
||||
assert_eq!(messages[0]["role"], "user");
|
||||
|
||||
let system = body["system"].as_array().unwrap();
|
||||
assert_eq!(system[0]["text"], "Existing top-level system.");
|
||||
assert_eq!(system[1]["text"], "Message system one.");
|
||||
assert_eq!(system[2]["text"], "Message system two.");
|
||||
assert_eq!(messages.len(), 3);
|
||||
assert_eq!(messages[0]["role"], "system");
|
||||
assert_eq!(messages[1]["role"], "user");
|
||||
assert_eq!(messages[2]["role"], "system");
|
||||
assert_eq!(body["system"], "Existing top-level system.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2300,4 +2307,245 @@ mod tests {
|
||||
assert!(!changed);
|
||||
assert_eq!(body, original);
|
||||
}
|
||||
|
||||
// ==================== normalize_deepseek_thinking_disabled_strip_effort 测试 ====================
|
||||
|
||||
fn deepseek_official_provider() -> Provider {
|
||||
create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
|
||||
"ANTHROPIC_API_KEY": "test-key"
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deepseek_official_strips_output_config_effort() {
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"thinking": { "type": "disabled" },
|
||||
"output_config": { "effort": "max" },
|
||||
"max_tokens": 100000
|
||||
});
|
||||
|
||||
let changed = normalize_deepseek_thinking_disabled_strip_effort(
|
||||
&mut body,
|
||||
&deepseek_official_provider(),
|
||||
);
|
||||
|
||||
assert!(changed);
|
||||
assert_eq!(body["thinking"]["type"], "disabled");
|
||||
assert!(body.get("output_config").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deepseek_official_strips_reasoning_effort() {
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"thinking": { "type": "disabled" },
|
||||
"reasoning_effort": "high",
|
||||
"max_tokens": 100000
|
||||
});
|
||||
|
||||
let changed = normalize_deepseek_thinking_disabled_strip_effort(
|
||||
&mut body,
|
||||
&deepseek_official_provider(),
|
||||
);
|
||||
|
||||
assert!(changed);
|
||||
assert_eq!(body["thinking"]["type"], "disabled");
|
||||
assert!(body.get("reasoning_effort").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deepseek_official_strips_both_effort_fields() {
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"thinking": { "type": "disabled" },
|
||||
"output_config": { "effort": "max" },
|
||||
"reasoning_effort": "high",
|
||||
"max_tokens": 100000
|
||||
});
|
||||
|
||||
let changed = normalize_deepseek_thinking_disabled_strip_effort(
|
||||
&mut body,
|
||||
&deepseek_official_provider(),
|
||||
);
|
||||
|
||||
assert!(changed);
|
||||
assert_eq!(body["thinking"]["type"], "disabled");
|
||||
assert!(body.get("output_config").is_none());
|
||||
assert!(body.get("reasoning_effort").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deepseek_official_no_effort_no_change() {
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"thinking": { "type": "disabled" },
|
||||
"max_tokens": 100000
|
||||
});
|
||||
let original = body.clone();
|
||||
|
||||
let changed = normalize_deepseek_thinking_disabled_strip_effort(
|
||||
&mut body,
|
||||
&deepseek_official_provider(),
|
||||
);
|
||||
|
||||
assert!(!changed);
|
||||
assert_eq!(body, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deepseek_official_preserves_output_config_other_fields() {
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"thinking": { "type": "disabled" },
|
||||
"output_config": { "effort": "max", "temperature": 0.5 },
|
||||
"max_tokens": 100000
|
||||
});
|
||||
|
||||
let changed = normalize_deepseek_thinking_disabled_strip_effort(
|
||||
&mut body,
|
||||
&deepseek_official_provider(),
|
||||
);
|
||||
|
||||
assert!(changed);
|
||||
assert_eq!(body["output_config"]["temperature"], 0.5);
|
||||
assert!(body["output_config"].get("effort").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deepseek_official_non_disabled_not_modified() {
|
||||
let cases = vec![
|
||||
(
|
||||
"enabled",
|
||||
json!({ "type": "enabled", "budget_tokens": 16000 }),
|
||||
),
|
||||
("adaptive", json!({ "type": "adaptive" })),
|
||||
];
|
||||
|
||||
for (label, thinking_value) in cases {
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"thinking": thinking_value,
|
||||
"output_config": { "effort": "max" },
|
||||
"max_tokens": 100000
|
||||
});
|
||||
let original = body.clone();
|
||||
|
||||
let changed = normalize_deepseek_thinking_disabled_strip_effort(
|
||||
&mut body,
|
||||
&deepseek_official_provider(),
|
||||
);
|
||||
|
||||
assert!(!changed, "should not modify thinking.type={label}");
|
||||
assert_eq!(body, original);
|
||||
}
|
||||
|
||||
// missing thinking field entirely
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"output_config": { "effort": "max" },
|
||||
"max_tokens": 100000
|
||||
});
|
||||
let original = body.clone();
|
||||
assert!(!normalize_deepseek_thinking_disabled_strip_effort(
|
||||
&mut body,
|
||||
&deepseek_official_provider()
|
||||
));
|
||||
assert_eq!(body, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deepseek_official_url_with_trailing_slash() {
|
||||
let provider = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic/",
|
||||
"ANTHROPIC_API_KEY": "test-key"
|
||||
}
|
||||
}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"thinking": { "type": "disabled" },
|
||||
"output_config": { "effort": "max" },
|
||||
"max_tokens": 100000
|
||||
});
|
||||
|
||||
let changed = normalize_deepseek_thinking_disabled_strip_effort(&mut body, &provider);
|
||||
|
||||
assert!(changed);
|
||||
assert!(body.get("output_config").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deepseek_official_detected_via_base_url_fallback() {
|
||||
let provider = create_provider(json!({
|
||||
"base_url": "https://api.deepseek.com/anthropic",
|
||||
"ANTHROPIC_API_KEY": "test-key"
|
||||
}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"thinking": { "type": "disabled" },
|
||||
"reasoning_effort": "high",
|
||||
"max_tokens": 100000
|
||||
});
|
||||
|
||||
let changed = normalize_deepseek_thinking_disabled_strip_effort(&mut body, &provider);
|
||||
|
||||
assert!(changed);
|
||||
assert!(body.get("reasoning_effort").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_non_deepseek_endpoint_not_modified() {
|
||||
let providers = vec![
|
||||
create_provider(json!({
|
||||
"env": { "ANTHROPIC_BASE_URL": "https://other-api.com/anthropic", "ANTHROPIC_API_KEY": "test-key" }
|
||||
})),
|
||||
create_provider(json!({
|
||||
"env": { "ANTHROPIC_BASE_URL": "https://api.anthropic.com", "ANTHROPIC_API_KEY": "test-key" }
|
||||
})),
|
||||
];
|
||||
|
||||
for provider in providers {
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"thinking": { "type": "disabled" },
|
||||
"output_config": { "effort": "max" },
|
||||
"max_tokens": 100000
|
||||
});
|
||||
let original = body.clone();
|
||||
|
||||
let changed = normalize_deepseek_thinking_disabled_strip_effort(&mut body, &provider);
|
||||
|
||||
assert!(
|
||||
!changed,
|
||||
"should not modify for {}",
|
||||
provider.settings_config["env"]["ANTHROPIC_BASE_URL"]
|
||||
);
|
||||
assert_eq!(body, original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_normalize_messages_pipeline_strips_effort_for_deepseek() {
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"thinking": { "type": "disabled" },
|
||||
"output_config": { "effort": "max" },
|
||||
"max_tokens": 100000,
|
||||
"messages": [{ "role": "user", "content": "hello" }]
|
||||
});
|
||||
|
||||
let changed = normalize_anthropic_messages_for_provider(
|
||||
&mut body,
|
||||
&deepseek_official_provider(),
|
||||
"anthropic",
|
||||
);
|
||||
|
||||
assert!(changed);
|
||||
assert_eq!(body["thinking"]["type"], "disabled");
|
||||
assert!(body.get("output_config").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ impl CodexChatHistoryStore {
|
||||
Some(item_type) if is_call_item_type(item_type) => {
|
||||
if let Some(call_id) = response_item_call_id(&item) {
|
||||
if let Some(cached) = lookup.call(&call_id) {
|
||||
if enrich_call_item_reasoning(&mut item, cached) {
|
||||
if enrich_call_item_from_cache(&mut item, cached) {
|
||||
enriched += 1;
|
||||
}
|
||||
}
|
||||
@@ -466,17 +466,26 @@ fn is_call_output_item_type(item_type: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
fn enrich_call_item_reasoning(item: &mut Value, cached: &Value) -> bool {
|
||||
fn enrich_call_item_from_cache(item: &mut Value, cached: &Value) -> bool {
|
||||
let mut changed = false;
|
||||
for key in ["reasoning_content", "reasoning"] {
|
||||
for key in [
|
||||
"name",
|
||||
"namespace",
|
||||
"arguments",
|
||||
"input",
|
||||
"status",
|
||||
"execution",
|
||||
"reasoning_content",
|
||||
"reasoning",
|
||||
] {
|
||||
if item.get(key).is_some_and(|value| !is_empty_value(value)) {
|
||||
continue;
|
||||
}
|
||||
let Some(reasoning) = cached.get(key).filter(|value| !is_empty_value(value)) else {
|
||||
let Some(value) = cached.get(key).filter(|value| !is_empty_value(value)) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(object) = item.as_object_mut() {
|
||||
object.insert(key.to_string(), reasoning.clone());
|
||||
object.insert(key.to_string(), value.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -675,6 +684,48 @@ mod tests {
|
||||
assert_eq!(input.len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enriches_existing_function_call_missing_name_and_arguments() {
|
||||
let history = CodexChatHistoryStore::default();
|
||||
history
|
||||
.record_response(&json!({
|
||||
"id": "resp_1",
|
||||
"output": [
|
||||
{
|
||||
"type": "function_call",
|
||||
"call_id": "call_1",
|
||||
"name": "read_file",
|
||||
"arguments": "{\"path\":\"README.md\"}",
|
||||
"reasoning_content": "Need to inspect the file."
|
||||
}
|
||||
]
|
||||
}))
|
||||
.await;
|
||||
|
||||
let mut request = json!({
|
||||
"previous_response_id": "resp_1",
|
||||
"input": [
|
||||
{
|
||||
"type": "function_call",
|
||||
"call_id": "call_1"
|
||||
},
|
||||
{
|
||||
"type": "function_call_output",
|
||||
"call_id": "call_1",
|
||||
"output": "ok"
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
assert_eq!(history.enrich_request(&mut request).await, 1);
|
||||
let input = request["input"].as_array().unwrap();
|
||||
assert_eq!(input[0]["type"], "function_call");
|
||||
assert_eq!(input[0]["name"], "read_file");
|
||||
assert_eq!(input[0]["arguments"], "{\"path\":\"README.md\"}");
|
||||
assert_eq!(input[0]["reasoning_content"], "Need to inspect the file.");
|
||||
assert_eq!(input[1]["type"], "function_call_output");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restores_parallel_tool_calls_as_one_assistant_group() {
|
||||
let history = CodexChatHistoryStore::default();
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
//! - 通过 JWT id_token 提取 chatgpt_account_id 作为账号唯一标识
|
||||
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||
use reqwest::Client;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
@@ -230,7 +230,6 @@ pub struct CodexOAuthManager {
|
||||
/// 进行中的 Device Code 流程:device_auth_id -> {user_code, expires_at_ms}
|
||||
/// 过期条目会在 start_device_flow 时被清理,防止放弃的登录流程导致无界增长
|
||||
pending_device_codes: Arc<RwLock<HashMap<String, PendingDeviceCode>>>,
|
||||
http_client: Client,
|
||||
storage_path: PathBuf,
|
||||
}
|
||||
|
||||
@@ -244,7 +243,6 @@ impl CodexOAuthManager {
|
||||
access_tokens: Arc::new(RwLock::new(HashMap::new())),
|
||||
refresh_locks: Arc::new(RwLock::new(HashMap::new())),
|
||||
pending_device_codes: Arc::new(RwLock::new(HashMap::new())),
|
||||
http_client: Client::new(),
|
||||
storage_path,
|
||||
};
|
||||
|
||||
@@ -266,8 +264,7 @@ impl CodexOAuthManager {
|
||||
pub async fn start_device_flow(&self) -> Result<GitHubDeviceCodeResponse, CodexOAuthError> {
|
||||
log::info!("[CodexOAuth] 启动 Device Code 流程");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
let response = crate::proxy::http_client::get()
|
||||
.post(DEVICE_AUTH_USERCODE_URL)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("User-Agent", CODEX_USER_AGENT)
|
||||
@@ -349,8 +346,7 @@ impl CodexOAuthManager {
|
||||
|
||||
log::debug!("[CodexOAuth] 轮询 Device Code");
|
||||
|
||||
let poll_response = self
|
||||
.http_client
|
||||
let poll_response = crate::proxy::http_client::get()
|
||||
.post(DEVICE_AUTH_TOKEN_URL)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("User-Agent", CODEX_USER_AGENT)
|
||||
@@ -431,8 +427,7 @@ impl CodexOAuthManager {
|
||||
code: &str,
|
||||
code_verifier: &str,
|
||||
) -> Result<OAuthTokenResponse, CodexOAuthError> {
|
||||
let response = self
|
||||
.http_client
|
||||
let response = crate::proxy::http_client::get()
|
||||
.post(OAUTH_TOKEN_URL)
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.header("User-Agent", CODEX_USER_AGENT)
|
||||
@@ -465,8 +460,7 @@ impl CodexOAuthManager {
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
) -> Result<OAuthTokenResponse, CodexOAuthError> {
|
||||
let response = self
|
||||
.http_client
|
||||
let response = crate::proxy::http_client::get()
|
||||
.post(OAUTH_TOKEN_URL)
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.header("User-Agent", CODEX_USER_AGENT)
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
//! - Provider 通过 meta.authBinding 关联账号
|
||||
//! - 自动迁移 v1 单账号格式到 v3 多账号 + 默认账号格式
|
||||
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
@@ -424,8 +423,6 @@ pub struct CopilotAuthManager {
|
||||
api_endpoints: Arc<RwLock<HashMap<String, String>>>,
|
||||
/// 每个账号的端点拉取锁,避免并发拉取重复打 GitHub API
|
||||
endpoint_locks: Arc<RwLock<HashMap<String, Arc<Mutex<()>>>>>,
|
||||
/// HTTP 客户端
|
||||
http_client: Client,
|
||||
/// 存储路径
|
||||
storage_path: PathBuf,
|
||||
/// 待迁移的旧格式 token
|
||||
@@ -447,7 +444,6 @@ impl CopilotAuthManager {
|
||||
copilot_models: Arc::new(RwLock::new(HashMap::new())),
|
||||
api_endpoints: Arc::new(RwLock::new(HashMap::new())),
|
||||
endpoint_locks: Arc::new(RwLock::new(HashMap::new())),
|
||||
http_client: Client::new(),
|
||||
storage_path,
|
||||
pending_migration: Arc::new(RwLock::new(None)),
|
||||
migration_error: Arc::new(RwLock::new(None)),
|
||||
@@ -602,8 +598,7 @@ impl CopilotAuthManager {
|
||||
};
|
||||
log::info!("[CopilotAuth] 启动设备码流程 (domain: {domain})");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
let response = crate::proxy::http_client::get()
|
||||
.post(github_device_code_url(&domain))
|
||||
.header("Accept", "application/json")
|
||||
.header("User-Agent", COPILOT_USER_AGENT)
|
||||
@@ -647,8 +642,7 @@ impl CopilotAuthManager {
|
||||
};
|
||||
log::debug!("[CopilotAuth] 轮询 OAuth Token (domain: {domain})");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
let response = crate::proxy::http_client::get()
|
||||
.post(github_oauth_token_url(&domain))
|
||||
.header("Accept", "application/json")
|
||||
.header("User-Agent", COPILOT_USER_AGENT)
|
||||
@@ -831,8 +825,7 @@ impl CopilotAuthManager {
|
||||
|
||||
log::info!("[CopilotAuth] 获取账号 {account_id} 的 Copilot 可用模型");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
let response = crate::proxy::http_client::get()
|
||||
.get(&models_url)
|
||||
.header("Authorization", format!("Bearer {copilot_token}"))
|
||||
.header("Content-Type", "application/json")
|
||||
@@ -919,8 +912,7 @@ impl CopilotAuthManager {
|
||||
|
||||
log::info!("[CopilotAuth] 获取账号 {account_id} 的 Copilot 使用量");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
let response = crate::proxy::http_client::get()
|
||||
.get(copilot_usage_url(&domain))
|
||||
.header("Authorization", format!("token {github_token}"))
|
||||
.header("Content-Type", "application/json")
|
||||
@@ -1034,8 +1026,7 @@ impl CopilotAuthManager {
|
||||
|
||||
log::debug!("[CopilotAuth] 为账号 {account_id} 惰性拉取动态 API 端点");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
let response = crate::proxy::http_client::get()
|
||||
.get(copilot_usage_url(&domain))
|
||||
.header("Authorization", format!("token {github_token}"))
|
||||
.header("Content-Type", "application/json")
|
||||
@@ -1312,8 +1303,7 @@ impl CopilotAuthManager {
|
||||
github_token: &str,
|
||||
domain: &str,
|
||||
) -> Result<GitHubUser, CopilotAuthError> {
|
||||
let response = self
|
||||
.http_client
|
||||
let response = crate::proxy::http_client::get()
|
||||
.get(github_user_url(domain))
|
||||
.header("Authorization", format!("token {github_token}"))
|
||||
.header("User-Agent", COPILOT_USER_AGENT)
|
||||
@@ -1345,8 +1335,7 @@ impl CopilotAuthManager {
|
||||
) -> Result<(), CopilotAuthError> {
|
||||
log::debug!("[CopilotAuth] 获取账号 {account_id} 的 Copilot Token (domain: {domain})");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
let response = crate::proxy::http_client::get()
|
||||
.get(copilot_token_url(domain))
|
||||
.header("Authorization", format!("token {github_token}"))
|
||||
.header("User-Agent", COPILOT_USER_AGENT)
|
||||
|
||||
@@ -429,8 +429,10 @@ impl ChatToResponsesState {
|
||||
if let Some(id) = id_delta {
|
||||
state.call_id = id;
|
||||
}
|
||||
if let Some(name) = name_delta {
|
||||
state.name = name;
|
||||
if let Some(ref name) = name_delta {
|
||||
if !name.is_empty() {
|
||||
state.name.clone_from(name);
|
||||
}
|
||||
}
|
||||
if !args_delta.is_empty() {
|
||||
state.arguments.push_str(&args_delta);
|
||||
@@ -442,7 +444,7 @@ impl ChatToResponsesState {
|
||||
}
|
||||
}
|
||||
|
||||
if !state.added && (!state.call_id.is_empty() || !state.name.is_empty()) {
|
||||
if !state.added && !state.call_id.is_empty() && !state.name.is_empty() {
|
||||
should_add = true;
|
||||
pending_arguments = state.arguments.clone();
|
||||
} else if state.added {
|
||||
@@ -464,9 +466,6 @@ impl ChatToResponsesState {
|
||||
if state.call_id.is_empty() {
|
||||
state.call_id = format!("call_{chat_index}");
|
||||
}
|
||||
if state.name.is_empty() {
|
||||
state.name = "unknown_tool".to_string();
|
||||
}
|
||||
state.output_index = Some(assigned);
|
||||
let is_custom_tool = self.tool_context.is_custom_tool_chat_name(&state.name);
|
||||
state.item_id = response_tool_call_item_id_from_chat_name(
|
||||
@@ -699,6 +698,21 @@ impl ChatToResponsesState {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip tool calls with missing names (defensive: some models generate
|
||||
// tool call deltas without providing a valid function name)
|
||||
let has_bad_name = self
|
||||
.tools
|
||||
.get(&key)
|
||||
.map(|state| state.name.is_empty())
|
||||
.unwrap_or(true);
|
||||
if has_bad_name {
|
||||
if let Some(state) = self.tools.get_mut(&key) {
|
||||
state.done = true;
|
||||
}
|
||||
log::warn!("[Codex] Skipping streaming tool call with missing name");
|
||||
continue;
|
||||
}
|
||||
|
||||
if self
|
||||
.tools
|
||||
.get(&key)
|
||||
@@ -713,9 +727,6 @@ impl ChatToResponsesState {
|
||||
if state.call_id.is_empty() {
|
||||
state.call_id = format!("call_{key}");
|
||||
}
|
||||
if state.name.is_empty() {
|
||||
state.name = "unknown_tool".to_string();
|
||||
}
|
||||
state.output_index = Some(assigned);
|
||||
state.item_id = response_tool_call_item_id_from_chat_name(
|
||||
&state.call_id,
|
||||
|
||||
@@ -1398,6 +1398,14 @@ fn chat_tool_calls_to_response_output_items(
|
||||
|
||||
if let Some(tool_calls) = message.get("tool_calls").and_then(|v| v.as_array()) {
|
||||
for (index, tool_call) in tool_calls.iter().enumerate() {
|
||||
// Skip tool calls with missing function names (defensive: some models
|
||||
// may generate tool calls without providing a valid name)
|
||||
let function = tool_call.get("function").unwrap_or(&Value::Null);
|
||||
let name = function.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if name.is_empty() {
|
||||
log::warn!("[Codex] Skipping tool call with missing name");
|
||||
continue;
|
||||
}
|
||||
output.push(chat_tool_call_to_response_item(
|
||||
tool_call,
|
||||
index,
|
||||
@@ -1406,11 +1414,11 @@ fn chat_tool_calls_to_response_output_items(
|
||||
));
|
||||
}
|
||||
} else if let Some(function_call) = message.get("function_call") {
|
||||
output.push(chat_legacy_function_call_to_response_item(
|
||||
function_call,
|
||||
reasoning,
|
||||
tool_context,
|
||||
));
|
||||
if let Some(item) =
|
||||
chat_legacy_function_call_to_response_item(function_call, reasoning, tool_context)
|
||||
{
|
||||
output.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
@@ -1448,7 +1456,7 @@ fn chat_legacy_function_call_to_response_item(
|
||||
function_call: &Value,
|
||||
reasoning: Option<&str>,
|
||||
tool_context: &CodexToolContext,
|
||||
) -> Value {
|
||||
) -> Option<Value> {
|
||||
let call_id = function_call
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -1458,10 +1466,18 @@ fn chat_legacy_function_call_to_response_item(
|
||||
.get("name")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
|
||||
// Skip legacy function calls with missing names (defensive: some models
|
||||
// may generate function_call without providing a valid name)
|
||||
if name.is_empty() {
|
||||
log::warn!("[Codex] Skipping legacy function_call with missing name");
|
||||
return None;
|
||||
}
|
||||
|
||||
let arguments = canonicalize_tool_arguments(function_call.get("arguments"));
|
||||
|
||||
let item_id = response_tool_call_item_id_from_chat_name(call_id, name, tool_context);
|
||||
response_tool_call_item_from_chat_name(
|
||||
Some(response_tool_call_item_from_chat_name(
|
||||
&item_id,
|
||||
"completed",
|
||||
call_id,
|
||||
@@ -1469,7 +1485,7 @@ fn chat_legacy_function_call_to_response_item(
|
||||
&arguments,
|
||||
reasoning,
|
||||
tool_context,
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn response_tool_call_item_id_from_chat_name(
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! 统一处理流式和非流式 API 响应
|
||||
|
||||
use super::{
|
||||
content_encoding::{decompress_body, get_content_encoding},
|
||||
forwarder::ActiveConnectionGuard,
|
||||
handler_config::{StreamUsageEventFilter, UsageParserConfig},
|
||||
handler_context::{RequestContext, StreamingTimeoutConfig},
|
||||
@@ -19,7 +20,6 @@ use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
io::Read,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
@@ -29,60 +29,9 @@ use std::{
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
// ============================================================================
|
||||
// 响应解压
|
||||
// 响应头处理
|
||||
// ============================================================================
|
||||
|
||||
/// 根据 content-encoding 解压响应体字节
|
||||
///
|
||||
/// reqwest 自动解压已禁用(为了透传 accept-encoding),需要手动解压。
|
||||
/// 返回 `Ok(None)` 表示编码不受支持、原样透传——此时调用方必须保留
|
||||
/// content-encoding 头,否则下游(诊断/客户端)会把压缩字节误当明文。
|
||||
fn decompress_body(content_encoding: &str, body: &[u8]) -> Result<Option<Vec<u8>>, std::io::Error> {
|
||||
match content_encoding {
|
||||
"gzip" | "x-gzip" => {
|
||||
let mut decoder = flate2::read::GzDecoder::new(body);
|
||||
let mut decompressed = Vec::new();
|
||||
decoder.read_to_end(&mut decompressed)?;
|
||||
Ok(Some(decompressed))
|
||||
}
|
||||
"deflate" => {
|
||||
// RFC 9110: deflate 指 zlib 包裹格式;但部分上游发 raw deflate 流。
|
||||
// 先按规范尝试 zlib,失败再回退 raw —— 否则合规上游必然解压失败,
|
||||
// 原始压缩字节会被 fail-open 透传给 JSON 解析(#2234 形态 C 之一)。
|
||||
let mut decompressed = Vec::new();
|
||||
let mut zlib = flate2::read::ZlibDecoder::new(body);
|
||||
match zlib.read_to_end(&mut decompressed) {
|
||||
Ok(_) => Ok(Some(decompressed)),
|
||||
Err(zlib_err) => {
|
||||
log::debug!("deflate 按 zlib 解压失败({zlib_err}),回退 raw deflate");
|
||||
let mut decompressed = Vec::new();
|
||||
let mut raw = flate2::read::DeflateDecoder::new(body);
|
||||
raw.read_to_end(&mut decompressed)?;
|
||||
Ok(Some(decompressed))
|
||||
}
|
||||
}
|
||||
}
|
||||
"br" => {
|
||||
let mut decompressed = Vec::new();
|
||||
brotli::BrotliDecompress(&mut std::io::Cursor::new(body), &mut decompressed)?;
|
||||
Ok(Some(decompressed))
|
||||
}
|
||||
_ => {
|
||||
log::warn!("未知的 content-encoding: {content_encoding},跳过解压");
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 从响应头提取 content-encoding(忽略 identity 和 chunked)
|
||||
fn get_content_encoding(headers: &HeaderMap) -> Option<String> {
|
||||
headers
|
||||
.get("content-encoding")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|s| s.trim().to_lowercase())
|
||||
.filter(|s| !s.is_empty() && s != "identity")
|
||||
}
|
||||
|
||||
/// RFC 2616 / RFC 7230 中定义的不应被代理继续转发的响应头。
|
||||
const HOP_BY_HOP_RESPONSE_HEADERS: &[&str] = &[
|
||||
"connection",
|
||||
@@ -878,40 +827,6 @@ mod tests {
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[test]
|
||||
fn decompress_body_deflate_handles_zlib_wrapped_per_rfc9110() {
|
||||
// RFC 9110 规范的 deflate = zlib 包裹格式(合规上游发的就是这个)
|
||||
let payload = br#"{"ok":true}"#;
|
||||
let mut encoder =
|
||||
flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
std::io::Write::write_all(&mut encoder, payload).unwrap();
|
||||
let compressed = encoder.finish().unwrap();
|
||||
|
||||
let decompressed = decompress_body("deflate", &compressed).unwrap().unwrap();
|
||||
assert_eq!(decompressed, payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompress_body_deflate_falls_back_to_raw_stream() {
|
||||
// 部分上游违规发 raw deflate 流,保持兼容
|
||||
let payload = br#"{"ok":true}"#;
|
||||
let mut encoder =
|
||||
flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
std::io::Write::write_all(&mut encoder, payload).unwrap();
|
||||
let compressed = encoder.finish().unwrap();
|
||||
|
||||
let decompressed = decompress_body("deflate", &compressed).unwrap().unwrap();
|
||||
assert_eq!(decompressed, payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompress_body_unknown_encoding_returns_none_to_keep_headers() {
|
||||
// 未知编码必须返回 None(而非伪装成"已解码"),否则 content-encoding
|
||||
// 头被剥掉,下游诊断会把压缩字节误报成明文
|
||||
let result = decompress_body("zstd", b"\x28\xb5\x2f\xfd").unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_sse_field_accepts_optional_space() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! 复用 subscription 模块的 SubscriptionQuota / QuotaTier 类型。
|
||||
|
||||
use super::subscription::{
|
||||
CredentialStatus, QuotaTier, SubscriptionQuota, TIER_FIVE_HOUR, TIER_WEEKLY_LIMIT,
|
||||
CredentialStatus, QuotaTier, SubscriptionQuota, TIER_FIVE_HOUR, TIER_MONTHLY, TIER_WEEKLY_LIMIT,
|
||||
};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -17,6 +17,9 @@ enum CodingPlanProvider {
|
||||
MiniMaxCn,
|
||||
MiniMaxEn,
|
||||
ZenMux,
|
||||
/// 火山方舟 Agent Plan / Coding Plan(base_url 形如
|
||||
/// `https://ark.cn-beijing.volces.com/api/coding[/v3]`)。
|
||||
Volcengine,
|
||||
}
|
||||
|
||||
fn detect_provider(base_url: &str) -> Option<CodingPlanProvider> {
|
||||
@@ -33,6 +36,10 @@ fn detect_provider(base_url: &str) -> Option<CodingPlanProvider> {
|
||||
Some(CodingPlanProvider::MiniMaxEn)
|
||||
} else if url.contains("zenmux") {
|
||||
Some(CodingPlanProvider::ZenMux)
|
||||
} else if url.contains("volces.com/api/coding") {
|
||||
// 仅匹配 Coding/Agent Plan 入口;DouBaoSeed 按量付费走 /api/v3 与
|
||||
// /api/compatible,没有套餐额度,不在此命中。
|
||||
Some(CodingPlanProvider::Volcengine)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -59,6 +66,10 @@ fn extract_reset_time(value: &serde_json::Value) -> Option<String> {
|
||||
return Some(s.to_string());
|
||||
}
|
||||
if let Some(n) = value.as_i64() {
|
||||
// 0/负时间戳(如火山 session 无活跃窗口回 -1)视为无重置时间
|
||||
if n <= 0 {
|
||||
return None;
|
||||
}
|
||||
// 区分秒和毫秒:秒级时间戳 < 1e12,毫秒 >= 1e12
|
||||
let ms = if n < 1_000_000_000_000 { n * 1000 } else { n };
|
||||
return millis_to_iso8601(ms);
|
||||
@@ -652,43 +663,517 @@ fn parse_minimax_tiers(body: &serde_json::Value) -> Vec<QuotaTier> {
|
||||
tiers
|
||||
}
|
||||
|
||||
// ── 火山方舟 Agent Plan / Coding Plan ───────────────────────
|
||||
//
|
||||
// 与 Kimi/MiniMax(数据面 Bearer 余额接口)不同,火山用量接口是**控制面
|
||||
// OpenAPI**:统一网关 `open.volcengineapi.com`(**不是**数据面推理域名
|
||||
// `ark.cn-beijing.volces.com`),形如
|
||||
// `POST https://open.volcengineapi.com/?Action=...&Version=2024-01-01&Region=cn-beijing`,
|
||||
// **强制火山引擎签名 V4(AK/SK)**——实测复用推理 Bearer Key 会被网关以
|
||||
// `400 InvalidAuthorization` 拒绝(格式层拒绝,非权限问题)。因此用户需在用量查询
|
||||
// 里另填火山账号的 AccessKey ID + Secret(与推理 Key 是两套凭据)。两个 plan 用
|
||||
// 同一份 AK/SK,故鉴权类错误直接停、不再试另一个 plan。
|
||||
//
|
||||
// 自动探测:先调 `GetAFPUsage`(Agent Plan,回绝对额度 Quota/Used),未订阅再调
|
||||
// `GetCodingPlanUsage`(Coding Plan,回百分比)。
|
||||
|
||||
/// 控制面 OpenAPI 统一网关(区别于数据面推理域名 ark.cn-beijing.volces.com)。
|
||||
const VOLCENGINE_OPENAPI_HOST: &str = "open.volcengineapi.com";
|
||||
const VOLCENGINE_API_VERSION: &str = "2024-01-01";
|
||||
/// ark 控制面 OpenAPI 的默认 Region(Agent/Coding Plan 目前在 cn-beijing)。
|
||||
const VOLCENGINE_DEFAULT_REGION: &str = "cn-beijing";
|
||||
|
||||
/// 单次 OpenAPI 调用的归类结果。
|
||||
enum VolcCall {
|
||||
/// 2xx 且 JSON 可解析、无 OpenAPI 级错误(业务 Result 仍可能为空=未订阅)。
|
||||
Body(serde_json::Value),
|
||||
/// 硬鉴权失败(HTTP 401/403 或 AccessDenied/Signature 等错误码)——两个 plan
|
||||
/// 共用凭据,命中即停。
|
||||
Auth(String),
|
||||
/// 网络 / 非鉴权 HTTP 错误 / 解析失败——记录后可继续尝试另一个 plan。
|
||||
Soft(String),
|
||||
}
|
||||
|
||||
/// 从数据面 base_url 提取控制面 OpenAPI 所需的 Region(如
|
||||
/// `ark.cn-beijing.volces.com` → `cn-beijing`);无法识别时回落 cn-beijing。
|
||||
/// 控制面 Host 是固定网关(`VOLCENGINE_OPENAPI_HOST`),不随 base_url 变化。
|
||||
fn volcengine_region(base_url: &str) -> String {
|
||||
let host = base_url
|
||||
.split_once("://")
|
||||
.map(|(_, rest)| rest)
|
||||
.unwrap_or(base_url)
|
||||
.split('/')
|
||||
.next()
|
||||
.unwrap_or("");
|
||||
host.split('.')
|
||||
.find(|p| p.starts_with("cn-") || p.starts_with("ap-"))
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or_else(|| VOLCENGINE_DEFAULT_REGION.to_string())
|
||||
}
|
||||
|
||||
/// 判断 OpenAPI 错误码是否属于鉴权类(需要硬停并提示换 AK/SK)。
|
||||
fn volcengine_is_auth_error_code(code: &str) -> bool {
|
||||
let c = code.to_lowercase();
|
||||
c.contains("auth")
|
||||
|| c.contains("signature")
|
||||
|| c.contains("accessdenied")
|
||||
|| c.contains("denied")
|
||||
|| c.contains("unauthorized")
|
||||
|| c.contains("forbidden")
|
||||
|| c.contains("credential")
|
||||
|| c.contains("token")
|
||||
}
|
||||
|
||||
/// 提取火山 OpenAPI 响应里的 `ResponseMetadata.Error`(或顶层 `Error`)。
|
||||
fn volcengine_response_error(body: &serde_json::Value) -> Option<(String, String)> {
|
||||
let err = body
|
||||
.get("ResponseMetadata")
|
||||
.and_then(|m| m.get("Error"))
|
||||
.or_else(|| body.get("Error"))?;
|
||||
let code = err
|
||||
.get("Code")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let msg = err
|
||||
.get("Message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if code.is_empty() && msg.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some((code, msg))
|
||||
}
|
||||
}
|
||||
|
||||
/// 鉴权失败时的引导文案,附加在错误后。
|
||||
const VOLCENGINE_AKSK_HINT: &str =
|
||||
"Check the AccessKey ID / Secret are correct and the account has Ark usage-query (OpenAPI) permission.";
|
||||
|
||||
// ── 火山引擎签名 V4(AK/SK)─────────────────────────────────
|
||||
//
|
||||
// 算法是 AWS SigV4 的火山变体(对照官方 volc-openapi-demos/signature/java/Sign.java)。
|
||||
// **两处致命差异,照搬 s3.rs 的标准 SigV4 会签名失败**:
|
||||
// 1. canonical headers 与 SignedHeaders 用**固定顺序**
|
||||
// `host;x-date;x-content-sha256;content-type`(**不按字母序**,s3.rs 是字母序);
|
||||
// 2. algorithm 串 `HMAC-SHA256`(无 `AWS4` 前缀)、credential scope 结尾 `request`
|
||||
// (非 `aws4_request`)、签名密钥 `kDate=HMAC(SK, date)`(SK 不加 `AWS4` 前缀)。
|
||||
// canonical query 仍按 key 字母序(与标准 SigV4 一致);service=`ark`、POST、空 body。
|
||||
|
||||
const VOLCENGINE_SERVICE: &str = "ark";
|
||||
const VOLCENGINE_CONTENT_TYPE: &str = "application/json; charset=utf-8";
|
||||
const VOLCENGINE_SIGNED_HEADERS: &str = "host;x-date;x-content-sha256;content-type";
|
||||
|
||||
fn volc_hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
|
||||
use hmac::{Hmac, Mac};
|
||||
type HmacSha256 = Hmac<sha2::Sha256>;
|
||||
let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts any key length");
|
||||
mac.update(data);
|
||||
mac.finalize().into_bytes().to_vec()
|
||||
}
|
||||
|
||||
fn volc_sha256_hex(data: &[u8]) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
format!("{:x}", Sha256::digest(data))
|
||||
}
|
||||
|
||||
/// RFC3986 unreserved 之外全部按 `%XX` 编码(用于 canonical query string)。
|
||||
fn volc_uri_encode(input: &str) -> String {
|
||||
let mut out = String::with_capacity(input.len());
|
||||
for byte in input.bytes() {
|
||||
match byte {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
out.push(byte as char)
|
||||
}
|
||||
_ => {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(out, "%{byte:02X}");
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 构造按 key 字母序排序、逐段 URL 编码的 canonical query string。
|
||||
/// 同一份字符串既用于签名也用于实际请求 URL,保证两者完全一致。
|
||||
fn volcengine_canonical_query(action: &str, region: &str) -> String {
|
||||
let mut pairs = [
|
||||
("Action", action),
|
||||
("Region", region),
|
||||
("Version", VOLCENGINE_API_VERSION),
|
||||
];
|
||||
pairs.sort_by(|a, b| a.0.cmp(b.0));
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{}={}", volc_uri_encode(k), volc_uri_encode(v)))
|
||||
.collect::<Vec<_>>()
|
||||
.join("&")
|
||||
}
|
||||
|
||||
/// 生成火山引擎签名 V4 的鉴权头,返回 `(Authorization, X-Date, X-Content-Sha256)`,
|
||||
/// 三者都要塞进请求头;`canonical_query` 必须与实际请求 URL 的 query 完全一致。
|
||||
/// `now` 作参数传入便于写确定性单测。
|
||||
fn volcengine_sign(
|
||||
access_key_id: &str,
|
||||
secret_access_key: &str,
|
||||
region: &str,
|
||||
canonical_query: &str,
|
||||
body: &[u8],
|
||||
now: chrono::DateTime<chrono::Utc>,
|
||||
) -> (String, String, String) {
|
||||
let x_date = now.format("%Y%m%dT%H%M%SZ").to_string();
|
||||
let short_date = now.format("%Y%m%d").to_string();
|
||||
let x_content_sha256 = volc_sha256_hex(body);
|
||||
|
||||
// 固定顺序 canonical headers(火山特有,**不排序**)。
|
||||
let canonical_headers = format!(
|
||||
"host:{VOLCENGINE_OPENAPI_HOST}\nx-date:{x_date}\nx-content-sha256:{x_content_sha256}\ncontent-type:{VOLCENGINE_CONTENT_TYPE}\n"
|
||||
);
|
||||
let canonical_request = format!(
|
||||
"POST\n/\n{canonical_query}\n{canonical_headers}\n{VOLCENGINE_SIGNED_HEADERS}\n{x_content_sha256}"
|
||||
);
|
||||
|
||||
let credential_scope = format!("{short_date}/{region}/{VOLCENGINE_SERVICE}/request");
|
||||
let string_to_sign = format!(
|
||||
"HMAC-SHA256\n{x_date}\n{credential_scope}\n{}",
|
||||
volc_sha256_hex(canonical_request.as_bytes())
|
||||
);
|
||||
|
||||
// 签名密钥派生:kDate=HMAC(SK, date)(SK **不加** AWS4 前缀),终止串 `request`。
|
||||
let k_date = volc_hmac_sha256(secret_access_key.as_bytes(), short_date.as_bytes());
|
||||
let k_region = volc_hmac_sha256(&k_date, region.as_bytes());
|
||||
let k_service = volc_hmac_sha256(&k_region, VOLCENGINE_SERVICE.as_bytes());
|
||||
let k_signing = volc_hmac_sha256(&k_service, b"request");
|
||||
let signature: String = volc_hmac_sha256(&k_signing, string_to_sign.as_bytes())
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect();
|
||||
|
||||
let authorization = format!(
|
||||
"HMAC-SHA256 Credential={access_key_id}/{credential_scope}, SignedHeaders={VOLCENGINE_SIGNED_HEADERS}, Signature={signature}"
|
||||
);
|
||||
(authorization, x_date, x_content_sha256)
|
||||
}
|
||||
|
||||
async fn volcengine_openapi_call(
|
||||
region: &str,
|
||||
access_key_id: &str,
|
||||
secret_access_key: &str,
|
||||
action: &str,
|
||||
) -> VolcCall {
|
||||
let client = crate::proxy::http_client::get();
|
||||
// canonical query 同时用于签名与实际 URL,确保两者逐字一致(否则签名不匹配)。
|
||||
let canonical_query = volcengine_canonical_query(action, region);
|
||||
let url = format!("https://{VOLCENGINE_OPENAPI_HOST}/?{canonical_query}");
|
||||
let body: &[u8] = b"";
|
||||
let (authorization, x_date, x_content_sha256) = volcengine_sign(
|
||||
access_key_id,
|
||||
secret_access_key,
|
||||
region,
|
||||
&canonical_query,
|
||||
body,
|
||||
chrono::Utc::now(),
|
||||
);
|
||||
|
||||
let resp = client
|
||||
.post(&url)
|
||||
.header("X-Date", x_date)
|
||||
.header("X-Content-Sha256", x_content_sha256)
|
||||
.header("Content-Type", VOLCENGINE_CONTENT_TYPE)
|
||||
.header("Authorization", authorization)
|
||||
.body(body.to_vec())
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.send()
|
||||
.await;
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return VolcCall::Soft(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return VolcCall::Auth(format!(
|
||||
"Authentication failed (HTTP {status}). {VOLCENGINE_AKSK_HINT}"
|
||||
));
|
||||
}
|
||||
if !status.is_success() {
|
||||
// 火山 OpenAPI 网关对签名/凭据类错误常返 4xx(多为 HTTP 400)并携带与 200
|
||||
// 路径相同的 ResponseMetadata.Error 信封,而非 401/403。这里也解析信封,让
|
||||
// Bearer 被拒时仍能给出 AK/SK 引导并标记凭据失效,而不是当成普通 API 错误。
|
||||
let raw = resp.text().await.unwrap_or_default();
|
||||
if let Ok(body) = serde_json::from_str::<serde_json::Value>(&raw) {
|
||||
if let Some((code, msg)) = volcengine_response_error(&body) {
|
||||
if volcengine_is_auth_error_code(&code) {
|
||||
return VolcCall::Auth(format!(
|
||||
"Authentication failed (HTTP {status}, {code}): {msg}. {VOLCENGINE_AKSK_HINT}"
|
||||
));
|
||||
}
|
||||
return VolcCall::Soft(format!("API error (HTTP {status}, {code}): {msg}"));
|
||||
}
|
||||
}
|
||||
return VolcCall::Soft(format!("API error (HTTP {status}): {raw}"));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
Ok(v) => v,
|
||||
Err(e) => return VolcCall::Soft(format!("Failed to parse response: {e}")),
|
||||
};
|
||||
|
||||
// 火山 OpenAPI 业务错误常以 200 + ResponseMetadata.Error 返回。
|
||||
if let Some((code, msg)) = volcengine_response_error(&body) {
|
||||
if volcengine_is_auth_error_code(&code) {
|
||||
return VolcCall::Auth(format!(
|
||||
"Authentication failed ({code}): {msg}. {VOLCENGINE_AKSK_HINT}"
|
||||
));
|
||||
}
|
||||
return VolcCall::Soft(format!("API error ({code}): {msg}"));
|
||||
}
|
||||
|
||||
VolcCall::Body(body)
|
||||
}
|
||||
|
||||
/// 解析 `GetAFPUsage` 的 `Result` 为 tier 列表。
|
||||
///
|
||||
/// 展示 5h / 周 / 月三个窗口(与控制台一致);`AFPDaily` 被官方控制台隐藏
|
||||
/// (其 Quota 常高于周上限,属历史默认值而非强制限额),故跳过。
|
||||
/// `Quota`/`Used` 是绝对 AFP 值,已用百分比 = Used/Quota×100;`Quota<=0` 视为
|
||||
/// 该窗口未订阅/未启用,跳过——也用于把"已鉴权但无 Agent Plan"识别为空结果,
|
||||
/// 从而回落到 Coding Plan 探测。
|
||||
fn parse_afp_tiers(result: &serde_json::Value) -> Vec<QuotaTier> {
|
||||
let mut tiers = Vec::new();
|
||||
for (key, name) in [
|
||||
("AFPFiveHour", TIER_FIVE_HOUR),
|
||||
("AFPWeekly", TIER_WEEKLY_LIMIT),
|
||||
("AFPMonthly", TIER_MONTHLY),
|
||||
] {
|
||||
let Some(win) = result.get(key) else { continue };
|
||||
let quota = win.get("Quota").and_then(parse_f64).unwrap_or(0.0);
|
||||
if quota <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let used = win.get("Used").and_then(parse_f64).unwrap_or(0.0);
|
||||
// 已用百分比;不做范围裁剪,与 parse_zhipu_token_tiers/parse_minimax_tiers
|
||||
// 的约定一致(下游渲染层负责显示策略)。
|
||||
let utilization = used / quota * 100.0;
|
||||
let resets_at = win.get("ResetTime").and_then(extract_reset_time);
|
||||
tiers.push(QuotaTier {
|
||||
name: name.to_string(),
|
||||
utilization,
|
||||
resets_at,
|
||||
used_value_usd: None,
|
||||
max_value_usd: None,
|
||||
});
|
||||
}
|
||||
tiers
|
||||
}
|
||||
|
||||
/// 把 `GetCodingPlanUsage` 的 window 标签归一到 tier 名。
|
||||
fn volcengine_coding_window(label: &str) -> Option<&'static str> {
|
||||
match label.to_lowercase().as_str() {
|
||||
"session" | "5h" | "fivehour" | "five_hour" | "rolling_5h" => Some(TIER_FIVE_HOUR),
|
||||
"weekly" | "week" | "7d" => Some(TIER_WEEKLY_LIMIT),
|
||||
"monthly" | "month" => Some(TIER_MONTHLY),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析 `GetCodingPlanUsage` 的 `Result` 为 tier 列表(防御式)。
|
||||
///
|
||||
/// 该接口官方文档未给出逐字段规格,依据官方 ark-cli 描述:回 session/weekly/
|
||||
/// monthly 窗口、**只给百分比**(已用)、重置时间是秒级。这里宽松匹配
|
||||
/// `QuotaUsage`/`Usages`/`Details` 数组及多种字段名,命中即用、未命中跳过。
|
||||
fn parse_coding_plan_tiers(result: &serde_json::Value) -> Vec<QuotaTier> {
|
||||
let mut tiers = Vec::new();
|
||||
let arr = result
|
||||
.get("QuotaUsage")
|
||||
.and_then(|v| v.as_array())
|
||||
.or_else(|| result.get("Usages").and_then(|v| v.as_array()))
|
||||
.or_else(|| result.get("Details").and_then(|v| v.as_array()));
|
||||
let Some(arr) = arr else { return tiers };
|
||||
|
||||
for item in arr {
|
||||
// 真实字段是 `Level`(实测 2026-06-21:session/weekly/monthly);其余作防御式 fallback。
|
||||
let label = item
|
||||
.get("Level")
|
||||
.and_then(|v| v.as_str())
|
||||
.or_else(|| item.get("Type").and_then(|v| v.as_str()))
|
||||
.or_else(|| item.get("Period").and_then(|v| v.as_str()))
|
||||
.or_else(|| item.get("Label").and_then(|v| v.as_str()))
|
||||
.or_else(|| item.get("Window").and_then(|v| v.as_str()))
|
||||
.unwrap_or("");
|
||||
let Some(name) = volcengine_coding_window(label) else {
|
||||
continue;
|
||||
};
|
||||
let utilization = item
|
||||
.get("Percent")
|
||||
.and_then(parse_f64)
|
||||
.or_else(|| item.get("UsedPercent").and_then(parse_f64))
|
||||
.or_else(|| item.get("UsagePercent").and_then(parse_f64))
|
||||
.unwrap_or(0.0);
|
||||
// 兼容秒/毫秒/字符串(extract_reset_time 内部已区分秒与毫秒)。
|
||||
let resets_at = item
|
||||
.get("ResetTime")
|
||||
.or_else(|| item.get("ResetTimestamp"))
|
||||
.and_then(extract_reset_time);
|
||||
tiers.push(QuotaTier {
|
||||
name: name.to_string(),
|
||||
utilization,
|
||||
resets_at,
|
||||
used_value_usd: None,
|
||||
max_value_usd: None,
|
||||
});
|
||||
}
|
||||
tiers
|
||||
}
|
||||
|
||||
fn volcengine_success(tiers: Vec<QuotaTier>, plan: Option<String>) -> SubscriptionQuota {
|
||||
SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Valid,
|
||||
credential_message: plan,
|
||||
success: true,
|
||||
tiers,
|
||||
extra_usage: None,
|
||||
error: None,
|
||||
queried_at: Some(now_millis()),
|
||||
}
|
||||
}
|
||||
|
||||
fn volcengine_auth_error(detail: String) -> SubscriptionQuota {
|
||||
SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Expired,
|
||||
credential_message: Some("Invalid API key".to_string()),
|
||||
success: false,
|
||||
tiers: vec![],
|
||||
extra_usage: None,
|
||||
error: Some(detail),
|
||||
queried_at: Some(now_millis()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn query_volcengine(
|
||||
base_url: &str,
|
||||
access_key_id: &str,
|
||||
secret_access_key: &str,
|
||||
) -> SubscriptionQuota {
|
||||
let region = volcengine_region(base_url);
|
||||
let mut soft_errors: Vec<String> = Vec::new();
|
||||
// 2xx + 无 Error 信封但解析不出额度时,截断原始响应用于诊断(区分"真没订阅"
|
||||
// 与"字段名/包裹层猜错")。签名若不通会走 Auth/Soft 分支,到不了这里。
|
||||
let mut empty_responses: Vec<String> = Vec::new();
|
||||
let summarize = |action: &str, body: &serde_json::Value| -> String {
|
||||
let raw: String = body.to_string().chars().take(700).collect();
|
||||
format!("{action}={raw}")
|
||||
};
|
||||
|
||||
// 1) Agent Plan:GetAFPUsage
|
||||
match volcengine_openapi_call(®ion, access_key_id, secret_access_key, "GetAFPUsage").await {
|
||||
VolcCall::Auth(detail) => return volcengine_auth_error(detail),
|
||||
VolcCall::Soft(detail) => soft_errors.push(format!("GetAFPUsage: {detail}")),
|
||||
VolcCall::Body(body) => {
|
||||
let result = body.get("Result").unwrap_or(&body);
|
||||
let tiers = parse_afp_tiers(result);
|
||||
if !tiers.is_empty() {
|
||||
let plan = result
|
||||
.get("PlanType")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| format!("Agent Plan {s}"));
|
||||
return volcengine_success(tiers, plan);
|
||||
}
|
||||
empty_responses.push(summarize("GetAFPUsage", &body));
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Coding Plan:GetCodingPlanUsage
|
||||
match volcengine_openapi_call(
|
||||
®ion,
|
||||
access_key_id,
|
||||
secret_access_key,
|
||||
"GetCodingPlanUsage",
|
||||
)
|
||||
.await
|
||||
{
|
||||
VolcCall::Auth(detail) => return volcengine_auth_error(detail),
|
||||
VolcCall::Soft(detail) => soft_errors.push(format!("GetCodingPlanUsage: {detail}")),
|
||||
VolcCall::Body(body) => {
|
||||
let result = body.get("Result").unwrap_or(&body);
|
||||
let tiers = parse_coding_plan_tiers(result);
|
||||
if !tiers.is_empty() {
|
||||
return volcengine_success(tiers, Some("Coding Plan".to_string()));
|
||||
}
|
||||
empty_responses.push(summarize("GetCodingPlanUsage", &body));
|
||||
}
|
||||
}
|
||||
|
||||
if !soft_errors.is_empty() {
|
||||
make_error(soft_errors.join("; "))
|
||||
} else if !empty_responses.is_empty() {
|
||||
// 签名已通过、请求到达业务层,但响应里没有可解析的额度。带上原始响应,
|
||||
// 便于核对真实字段名/包裹层,或确认确实未订阅。
|
||||
make_error(format!(
|
||||
"No active subscription found (signature OK). Raw: {}",
|
||||
empty_responses.join(" || ")
|
||||
))
|
||||
} else {
|
||||
make_error(
|
||||
"No active Agent Plan or Coding Plan subscription found for this credential"
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── 公开入口 ────────────────────────────────────────────────
|
||||
|
||||
/// 构造"凭据缺失 / 域名未命中"的失败结果(NotFound 状态 + 明确错误文案)。
|
||||
fn coding_plan_not_found(error: &str) -> SubscriptionQuota {
|
||||
SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::NotFound,
|
||||
credential_message: None,
|
||||
success: false,
|
||||
tiers: vec![],
|
||||
extra_usage: None,
|
||||
error: Some(error.to_string()),
|
||||
queried_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_coding_plan_quota(
|
||||
base_url: &str,
|
||||
api_key: &str,
|
||||
access_key_id: Option<&str>,
|
||||
secret_access_key: Option<&str>,
|
||||
) -> Result<SubscriptionQuota, String> {
|
||||
if api_key.trim().is_empty() {
|
||||
return Ok(SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::NotFound,
|
||||
credential_message: None,
|
||||
success: false,
|
||||
tiers: vec![],
|
||||
extra_usage: None,
|
||||
// 与 balance::get_balance 一致:给出明确错误,避免 footer 显示无信息的失败
|
||||
error: Some("API key is empty".to_string()),
|
||||
queried_at: None,
|
||||
});
|
||||
}
|
||||
|
||||
let provider = match detect_provider(base_url) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
return Ok(SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::NotFound,
|
||||
credential_message: None,
|
||||
success: false,
|
||||
tiers: vec![],
|
||||
extra_usage: None,
|
||||
// 域名未命中已知套餐供应商(如第三方中转站):给出明确错误而非静默失败
|
||||
error: Some("Unknown coding plan provider".to_string()),
|
||||
queried_at: None,
|
||||
});
|
||||
}
|
||||
// 域名未命中已知套餐供应商(如第三方中转站):给出明确错误而非静默失败
|
||||
None => return Ok(coding_plan_not_found("Unknown coding plan provider")),
|
||||
};
|
||||
|
||||
// 火山方舟走控制面 AK/SK 签名(区别于其他供应商的数据面 Bearer api_key),凭据
|
||||
// 校验与查询路径都不同,单独分支提前处理。
|
||||
if let CodingPlanProvider::Volcengine = provider {
|
||||
let ak = access_key_id.unwrap_or("").trim();
|
||||
let sk = secret_access_key.unwrap_or("").trim();
|
||||
if ak.is_empty() || sk.is_empty() {
|
||||
return Ok(coding_plan_not_found(
|
||||
"Volcengine usage query needs the account AccessKey ID + Secret (not the inference API key)",
|
||||
));
|
||||
}
|
||||
return Ok(query_volcengine(base_url, ak, sk).await);
|
||||
}
|
||||
|
||||
// 其余供应商:数据面 Bearer api_key。
|
||||
// 与 balance::get_balance 一致:给出明确错误,避免 footer 显示无信息的失败
|
||||
if api_key.trim().is_empty() {
|
||||
return Ok(coding_plan_not_found("API key is empty"));
|
||||
}
|
||||
|
||||
let quota = match provider {
|
||||
CodingPlanProvider::Kimi => query_kimi(api_key).await,
|
||||
CodingPlanProvider::ZhipuCn | CodingPlanProvider::ZhipuEn => {
|
||||
@@ -697,6 +1182,10 @@ pub async fn get_coding_plan_quota(
|
||||
CodingPlanProvider::MiniMaxCn => query_minimax(api_key, true).await,
|
||||
CodingPlanProvider::MiniMaxEn => query_minimax(api_key, false).await,
|
||||
CodingPlanProvider::ZenMux => query_zenmux(base_url, api_key).await,
|
||||
// 火山已在上面的 AK/SK 分支提前返回,此处不可达。
|
||||
CodingPlanProvider::Volcengine => {
|
||||
unreachable!("volcengine handled via AK/SK branch above")
|
||||
}
|
||||
};
|
||||
|
||||
Ok(quota)
|
||||
@@ -705,7 +1194,9 @@ pub async fn get_coding_plan_quota(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
parse_minimax_tiers, parse_zhipu_token_tiers, zhipu_quota_base, TIER_FIVE_HOUR,
|
||||
parse_afp_tiers, parse_coding_plan_tiers, parse_minimax_tiers, parse_zhipu_token_tiers,
|
||||
volcengine_canonical_query, volcengine_is_auth_error_code, volcengine_region,
|
||||
volcengine_response_error, volcengine_sign, zhipu_quota_base, TIER_FIVE_HOUR, TIER_MONTHLY,
|
||||
TIER_WEEKLY_LIMIT,
|
||||
};
|
||||
use serde_json::json;
|
||||
@@ -1135,4 +1626,184 @@ mod tests {
|
||||
"https://open.bigmodel.cn"
|
||||
);
|
||||
}
|
||||
|
||||
// ── 火山方舟 Agent Plan / Coding Plan ──
|
||||
|
||||
#[test]
|
||||
fn volcengine_afp_three_windows_from_official_example() {
|
||||
// 官方文档 GetAFPUsage 返回示例(逐字):5h 25% / weekly 30% / monthly
|
||||
// 42.525%;AFPDaily 被控制台隐藏,应跳过。
|
||||
let result = json!({
|
||||
"PlanType": "Large",
|
||||
"AFPFiveHour": { "Quota": 50.0, "Used": 12.5, "SubscribeTime": 1778788800000_i64, "ResetTime": 1778806800000_i64 },
|
||||
"AFPDaily": { "Quota": 100.0, "Used": 22.5, "SubscribeTime": 1778716800000_i64, "ResetTime": 1778803200000_i64 },
|
||||
"AFPWeekly": { "Quota": 500.0, "Used": 150.0, "SubscribeTime": 1778457600000_i64, "ResetTime": 1779062400000_i64 },
|
||||
"AFPMonthly": { "Quota": 2000.0, "Used": 850.5, "SubscribeTime": 1777939200000_i64, "ResetTime": 1780531200000_i64 }
|
||||
});
|
||||
let tiers = parse_afp_tiers(&result);
|
||||
assert_eq!(tiers.len(), 3, "daily 应被跳过,只剩 5h/周/月");
|
||||
assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
|
||||
assert!((tiers[0].utilization - 25.0).abs() < 1e-9);
|
||||
assert!(tiers[0].resets_at.is_some());
|
||||
assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
|
||||
assert!((tiers[1].utilization - 30.0).abs() < 1e-9);
|
||||
assert_eq!(tiers[2].name, TIER_MONTHLY);
|
||||
assert!((tiers[2].utilization - 42.525).abs() < 1e-9);
|
||||
assert!(tiers[2].resets_at.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volcengine_afp_zero_quota_windows_treated_as_unbound() {
|
||||
// 已鉴权但无 Agent Plan:窗口 Quota=0 → 空结果,调用方据此回落 Coding Plan。
|
||||
let result = json!({
|
||||
"PlanType": "",
|
||||
"AFPFiveHour": { "Quota": 0.0, "Used": 0.0 },
|
||||
"AFPWeekly": { "Quota": 0.0, "Used": 0.0 },
|
||||
"AFPMonthly": { "Quota": 0.0, "Used": 0.0 }
|
||||
});
|
||||
assert!(parse_afp_tiers(&result).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volcengine_afp_partial_windows_only_subscribed_ones() {
|
||||
// 仅 5h 窗口有额度(缺周/月)→ 只产出一个 tier。
|
||||
let result = json!({
|
||||
"AFPFiveHour": { "Quota": 40.0, "Used": 10.0, "ResetTime": 1778806800000_i64 },
|
||||
"AFPWeekly": { "Quota": 0.0, "Used": 0.0 }
|
||||
});
|
||||
let tiers = parse_afp_tiers(&result);
|
||||
assert_eq!(tiers.len(), 1);
|
||||
assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
|
||||
assert!((tiers[0].utilization - 25.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volcengine_coding_plan_real_response_levels() {
|
||||
// 真实 GetCodingPlanUsage 响应(用户实测 2026-06-21):字段名是 `Level`(非 `Type`),
|
||||
// 仅百分比,秒级 ResetTimestamp;session 无活跃窗口回 -1 → 无重置时间。
|
||||
let result = json!({
|
||||
"Status": "Running",
|
||||
"UpdateTimestamp": 1782053286_i64,
|
||||
"QuotaUsage": [
|
||||
{ "Level": "session", "Percent": 0.0, "ResetTimestamp": -1_i64 },
|
||||
{ "Level": "weekly", "Percent": 1.672568, "ResetTimestamp": 1782057600_i64 },
|
||||
{ "Level": "monthly", "Percent": 0.836284, "ResetTimestamp": 1784303999_i64 }
|
||||
]
|
||||
});
|
||||
let tiers = parse_coding_plan_tiers(&result);
|
||||
assert_eq!(tiers.len(), 3);
|
||||
assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
|
||||
assert!((tiers[0].utilization - 0.0).abs() < 1e-9);
|
||||
assert!(
|
||||
tiers[0].resets_at.is_none(),
|
||||
"session ResetTimestamp=-1 应无重置时间"
|
||||
);
|
||||
assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
|
||||
assert!((tiers[1].utilization - 1.672568).abs() < 1e-6);
|
||||
assert!(tiers[1].resets_at.is_some());
|
||||
assert_eq!(tiers[2].name, TIER_MONTHLY);
|
||||
assert!((tiers[2].utilization - 0.836284).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volcengine_coding_plan_unknown_window_skipped_and_missing_array_empty() {
|
||||
let result = json!({
|
||||
"QuotaUsage": [
|
||||
{ "Level": "daily", "Percent": 9.0 },
|
||||
{ "Level": "weekly", "Percent": 20.0 }
|
||||
]
|
||||
});
|
||||
let tiers = parse_coding_plan_tiers(&result);
|
||||
assert_eq!(tiers.len(), 1, "未知 daily 窗口跳过");
|
||||
assert_eq!(tiers[0].name, TIER_WEEKLY_LIMIT);
|
||||
|
||||
assert!(parse_coding_plan_tiers(&json!({})).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volcengine_region_derivation() {
|
||||
assert_eq!(
|
||||
volcengine_region("https://ark.cn-beijing.volces.com/api/coding"),
|
||||
"cn-beijing"
|
||||
);
|
||||
// 其他 region 的数据面域名按段提取。
|
||||
assert_eq!(
|
||||
volcengine_region("https://ark.cn-shanghai.volces.com/api/coding/v3"),
|
||||
"cn-shanghai"
|
||||
);
|
||||
// 无可识别 region 段时回落默认 cn-beijing。
|
||||
assert_eq!(
|
||||
volcengine_region("https://example.com/api/coding"),
|
||||
"cn-beijing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volcengine_canonical_query_is_sorted_and_encoded() {
|
||||
// 按 key 字母序:Action < Region < Version;值含 `-` 属 unreserved,不编码。
|
||||
assert_eq!(
|
||||
volcengine_canonical_query("GetAFPUsage", "cn-beijing"),
|
||||
"Action=GetAFPUsage&Region=cn-beijing&Version=2024-01-01"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volcengine_sign_structure_and_determinism() {
|
||||
// 没有服务端金标准向量时,锁定签名的结构契约 + 确定性(足以抓住 header 顺序、
|
||||
// scope 后缀、algorithm 前缀、空 body hash 等实现错误)。真实正确性靠用户实测。
|
||||
let now = chrono::DateTime::parse_from_rfc3339("2024-06-21T00:00:00Z")
|
||||
.unwrap()
|
||||
.with_timezone(&chrono::Utc);
|
||||
let region = "cn-beijing";
|
||||
let query = volcengine_canonical_query("GetAFPUsage", region);
|
||||
let (auth, x_date, x_content) =
|
||||
volcengine_sign("AKLTtest", "secretkey", region, &query, b"", now);
|
||||
|
||||
// 空 body 的 SHA-256(固定值),证明走的是空 body。
|
||||
assert_eq!(
|
||||
x_content,
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
);
|
||||
// X-Date 形如 20240621T000000Z。
|
||||
assert_eq!(x_date, "20240621T000000Z");
|
||||
// Authorization 结构:算法无 AWS4 前缀、scope 结尾 ark/request、固定 SignedHeaders。
|
||||
assert!(
|
||||
auth.starts_with("HMAC-SHA256 Credential=AKLTtest/20240621/cn-beijing/ark/request,"),
|
||||
"unexpected credential/scope: {auth}"
|
||||
);
|
||||
assert!(
|
||||
auth.contains("SignedHeaders=host;x-date;x-content-sha256;content-type,"),
|
||||
"unexpected signed headers: {auth}"
|
||||
);
|
||||
// Signature 是 64 位十六进制。
|
||||
let sig = auth.rsplit("Signature=").next().unwrap();
|
||||
assert_eq!(sig.len(), 64);
|
||||
assert!(sig.bytes().all(|b| b.is_ascii_hexdigit()));
|
||||
|
||||
// 确定性:同输入同输出。
|
||||
let (auth2, _, _) = volcengine_sign("AKLTtest", "secretkey", region, &query, b"", now);
|
||||
assert_eq!(auth, auth2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volcengine_auth_error_code_detection_and_extraction() {
|
||||
assert!(volcengine_is_auth_error_code("AccessDenied"));
|
||||
assert!(volcengine_is_auth_error_code("SignatureDoesNotMatch"));
|
||||
assert!(volcengine_is_auth_error_code("InvalidAuthorization"));
|
||||
assert!(volcengine_is_auth_error_code("Unauthorized"));
|
||||
assert!(!volcengine_is_auth_error_code("InvalidParameter.Action"));
|
||||
assert!(!volcengine_is_auth_error_code("InternalError"));
|
||||
|
||||
// ResponseMetadata.Error 抽取
|
||||
let body = json!({
|
||||
"ResponseMetadata": { "RequestId": "x", "Error": { "Code": "AccessDenied", "Message": "no permission" } }
|
||||
});
|
||||
let (code, msg) = volcengine_response_error(&body).expect("应抽到 Error");
|
||||
assert_eq!(code, "AccessDenied");
|
||||
assert_eq!(msg, "no permission");
|
||||
|
||||
// 无 Error 时返回 None
|
||||
let ok_body = json!({ "ResponseMetadata": { "RequestId": "x" }, "Result": {} });
|
||||
assert!(volcengine_response_error(&ok_body).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,6 +463,7 @@ base_url = "http://localhost:8080"
|
||||
|
||||
db.update_proxy_config(ProxyConfig {
|
||||
live_takeover_active: true,
|
||||
listen_port: 0,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
@@ -491,7 +492,7 @@ base_url = "http://localhost:8080"
|
||||
)
|
||||
.expect("seed taken-over live file");
|
||||
|
||||
state
|
||||
let proxy_info = state
|
||||
.proxy_service
|
||||
.start()
|
||||
.await
|
||||
@@ -544,7 +545,7 @@ base_url = "http://localhost:8080"
|
||||
live.get("env")
|
||||
.and_then(|env| env.get("ANTHROPIC_BASE_URL"))
|
||||
.and_then(|v| v.as_str()),
|
||||
Some("http://127.0.0.1:15721"),
|
||||
Some(format!("http://127.0.0.1:{}", proxy_info.port).as_str()),
|
||||
"proxy base URL should stay intact"
|
||||
);
|
||||
assert!(
|
||||
|
||||
@@ -5444,8 +5444,10 @@ command = "shared-command"
|
||||
)
|
||||
.expect("set common config snippet");
|
||||
|
||||
let mut proxy_config = ProxyConfig::default();
|
||||
proxy_config.listen_port = 0;
|
||||
let proxy_config = ProxyConfig {
|
||||
listen_port: 0,
|
||||
..Default::default()
|
||||
};
|
||||
db.update_proxy_config(proxy_config)
|
||||
.await
|
||||
.expect("set test proxy config");
|
||||
@@ -5582,8 +5584,10 @@ requires_openai_auth = true
|
||||
let db = Arc::new(Database::memory().expect("init db"));
|
||||
let state = crate::store::AppState::new(db.clone());
|
||||
|
||||
let mut proxy_config = ProxyConfig::default();
|
||||
proxy_config.listen_port = 0;
|
||||
let proxy_config = ProxyConfig {
|
||||
listen_port: 0,
|
||||
..Default::default()
|
||||
};
|
||||
db.update_proxy_config(proxy_config)
|
||||
.await
|
||||
.expect("set test proxy config");
|
||||
|
||||
@@ -307,6 +307,11 @@ pub const TIER_SEVEN_DAY_SONNET: &str = "seven_day_sonnet";
|
||||
/// 写入、tray 渲染、commands::provider 扁平化三处共用同一标识。
|
||||
pub const TIER_WEEKLY_LIMIT: &str = "weekly_limit";
|
||||
|
||||
/// 月窗口 tier 名。火山方舟 Agent Plan / Coding Plan 有 5h / 周 / 月 三个展示
|
||||
/// 窗口(Kimi / MiniMax 只有 5h + 周),月窗口共用此标识;前端 `TIER_I18N_KEYS`
|
||||
/// 映射到 `subscription.monthly`。
|
||||
pub const TIER_MONTHLY: &str = "monthly";
|
||||
|
||||
/// Gemini 用量分组名称(按模型而非时间窗口)。`classify_gemini_model` 输出。
|
||||
pub const TIER_GEMINI_PRO: &str = "gemini_pro";
|
||||
pub const TIER_GEMINI_FLASH: &str = "gemini_flash";
|
||||
|
||||
@@ -1732,23 +1732,20 @@ impl Database {
|
||||
OR cache_read_tokens > 0 OR cache_creation_tokens > 0)";
|
||||
|
||||
let mut logs = {
|
||||
match only_model_id {
|
||||
Some(model) => {
|
||||
let sql = format!(
|
||||
"{BASE_SQL} AND (model = ?1 OR request_model = ?1 OR pricing_model = ?1)"
|
||||
);
|
||||
let mut stmt = conn.prepare(&sql)?;
|
||||
let rows = stmt.query_map([model], row_to_request_log_detail)?;
|
||||
rows.collect::<Result<Vec<_>, _>>()?
|
||||
}
|
||||
None => {
|
||||
let mut stmt = conn.prepare(BASE_SQL)?;
|
||||
let rows = stmt.query_map([], row_to_request_log_detail)?;
|
||||
rows.collect::<Result<Vec<_>, _>>()?
|
||||
}
|
||||
}
|
||||
let mut stmt = conn.prepare(BASE_SQL)?;
|
||||
let rows = stmt.query_map([], row_to_request_log_detail)?;
|
||||
rows.collect::<Result<Vec<_>, _>>()?
|
||||
};
|
||||
|
||||
// 精准回填的行筛选必须与查价层共用 candidates 归一化:SQL 精确匹配会漏掉
|
||||
// 以原始别名落库的行(如 openrouter/anthropic/claude-sonnet-4.5:free),
|
||||
// 这些行查价时能归一化命中新定价,却在筛选层被挡掉,导致导入定价后
|
||||
// 历史成本要等下次全量回填才更新。误纳无害——查不到价的行会被跳过。
|
||||
if let Some(model_id) = only_model_id {
|
||||
let target = model_pricing_candidates(model_id);
|
||||
logs.retain(|log| log_pricing_scope_matches(log, &target));
|
||||
}
|
||||
|
||||
if logs.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
@@ -1966,6 +1963,30 @@ pub(crate) fn find_model_pricing_row(
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// 精准回填的行筛选:log 的任一模型字段归一化后与目标模型的 candidates 相交,
|
||||
/// 或可按查价层的前缀规则命中目标,即视为相关。镜像 find_model_pricing_row 的
|
||||
/// 匹配语义,宁可误纳(后续查价会兜底)不可漏筛。
|
||||
fn log_pricing_scope_matches(log: &RequestLogDetail, target_candidates: &[String]) -> bool {
|
||||
[
|
||||
Some(log.model.as_str()),
|
||||
log.request_model.as_deref(),
|
||||
log.pricing_model.as_deref(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|field| {
|
||||
model_pricing_candidates(field).iter().any(|candidate| {
|
||||
target_candidates.iter().any(|target| {
|
||||
target == candidate
|
||||
|| (should_try_pricing_prefix_match(candidate)
|
||||
&& target
|
||||
.strip_prefix(candidate.as_str())
|
||||
.is_some_and(|rest| rest.starts_with('-')))
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_placeholder_pricing_model(model_id: &str) -> bool {
|
||||
let normalized = model_id.trim().to_ascii_lowercase();
|
||||
normalized.is_empty() || matches!(normalized.as_str(), "unknown" | "null" | "none")
|
||||
@@ -2652,6 +2673,61 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scoped_backfill_matches_raw_alias_rows() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
|
||||
{
|
||||
let conn = lock_conn!(db.conn);
|
||||
// 代理日志按上游原文落库:带路由前缀和 :free 后缀的别名形式。
|
||||
// 精准回填的筛选必须归一化后匹配,否则这类行要等全量回填才更新。
|
||||
insert_usage_log(
|
||||
&conn,
|
||||
"openrouter-alias-zero-cost",
|
||||
"claude",
|
||||
"provider-1",
|
||||
"openrouter/moonshot/kimi-k2-novel:free",
|
||||
"proxy",
|
||||
1000,
|
||||
1_000_000,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
200,
|
||||
"0",
|
||||
)?;
|
||||
}
|
||||
|
||||
// 定价缺失时不应回填
|
||||
assert_eq!(db.backfill_missing_usage_costs()?, 0);
|
||||
|
||||
{
|
||||
let conn = lock_conn!(db.conn);
|
||||
conn.execute(
|
||||
"INSERT INTO model_pricing (model_id, display_name, input_cost_per_million, output_cost_per_million)
|
||||
VALUES ('kimi-k2-novel', 'Kimi K2 Novel', '0.6', '2.5')",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
|
||||
// 按归一化 ID 精准回填,应命中以原始别名落库的行
|
||||
assert_eq!(
|
||||
db.backfill_missing_usage_costs_for_model("kimi-k2-novel")?,
|
||||
1
|
||||
);
|
||||
|
||||
let conn = lock_conn!(db.conn);
|
||||
let total_cost: String = conn.query_row(
|
||||
"SELECT total_cost_usd
|
||||
FROM proxy_request_logs WHERE request_id = 'openrouter-alias-zero-cost'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
assert_eq!(total_cost, "0.600000");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_backfill_missing_usage_costs_keeps_claude_fresh_input() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
|
||||
@@ -19,6 +19,8 @@ const W_TIER_NAMES: &[&str] = &[
|
||||
crate::services::subscription::TIER_SEVEN_DAY_OPUS,
|
||||
crate::services::subscription::TIER_SEVEN_DAY_SONNET,
|
||||
];
|
||||
// 火山方舟 Agent/Coding Plan 的月窗口(5h/周/月 三档)。
|
||||
const M_TIER_NAMES: &[&str] = &[crate::services::subscription::TIER_MONTHLY];
|
||||
const GEMINI_PRO_TIER_NAMES: &[&str] = &[crate::services::subscription::TIER_GEMINI_PRO];
|
||||
const GEMINI_FLASH_TIER_NAMES: &[&str] = &[crate::services::subscription::TIER_GEMINI_FLASH];
|
||||
const GEMINI_FLASH_LITE_TIER_NAMES: &[&str] =
|
||||
@@ -26,6 +28,7 @@ const GEMINI_FLASH_LITE_TIER_NAMES: &[&str] =
|
||||
const TIER_LABEL_GROUPS: &[(&str, &[&str])] = &[
|
||||
("h", H_TIER_NAMES),
|
||||
("w", W_TIER_NAMES),
|
||||
("m", M_TIER_NAMES),
|
||||
("p", GEMINI_PRO_TIER_NAMES),
|
||||
("f", GEMINI_FLASH_TIER_NAMES),
|
||||
("l", GEMINI_FLASH_LITE_TIER_NAMES),
|
||||
@@ -878,7 +881,7 @@ mod tests {
|
||||
use crate::provider::{UsageData, UsageResult};
|
||||
use crate::services::subscription::{
|
||||
CredentialStatus, QuotaTier, SubscriptionQuota, TIER_FIVE_HOUR, TIER_GEMINI_FLASH,
|
||||
TIER_GEMINI_FLASH_LITE, TIER_GEMINI_PRO, TIER_SEVEN_DAY, TIER_SEVEN_DAY_OPUS,
|
||||
TIER_GEMINI_FLASH_LITE, TIER_GEMINI_PRO, TIER_MONTHLY, TIER_SEVEN_DAY, TIER_SEVEN_DAY_OPUS,
|
||||
TIER_SEVEN_DAY_SONNET, TIER_WEEKLY_LIMIT,
|
||||
};
|
||||
|
||||
@@ -1094,6 +1097,36 @@ mod tests {
|
||||
assert!(s.contains("w50%"), "expected w50% in {s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_summary_token_plan_volcengine_three_tiers_with_monthly() {
|
||||
// 火山方舟 Agent Plan 回 5h/周/月三档,托盘应包含 m(月)窗口,
|
||||
// 不再静默丢弃。
|
||||
let r = usage_result(
|
||||
true,
|
||||
vec![
|
||||
usage_data(Some(TIER_FIVE_HOUR), 25.0),
|
||||
usage_data(Some(TIER_WEEKLY_LIMIT), 30.0),
|
||||
usage_data(Some(TIER_MONTHLY), 42.0),
|
||||
],
|
||||
);
|
||||
let s = format_script_summary(&r).expect("should format");
|
||||
assert!(s.contains("h25%"), "expected h25% in {s}");
|
||||
assert!(s.contains("w30%"), "expected w30% in {s}");
|
||||
assert!(s.contains("m42%"), "expected m42% in {s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_summary_token_plan_monthly_only_renders_label_not_raw_name() {
|
||||
// 仅月窗口激活时不应回落到原始 "monthly" 机器名,而是走 m 标签。
|
||||
let r = usage_result(true, vec![usage_data(Some(TIER_MONTHLY), 60.0)]);
|
||||
let s = format_script_summary(&r).expect("should format");
|
||||
assert!(s.contains("m60%"), "expected m60% in {s}");
|
||||
assert!(
|
||||
!s.contains("monthly"),
|
||||
"raw tier name should not leak into label: {s}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_summary_official_subscription_claude_uses_h_and_w_labels() {
|
||||
let r = usage_result(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "CC Switch",
|
||||
"version": "3.16.3",
|
||||
"version": "3.16.4",
|
||||
"identifier": "com.ccswitch.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
||||
@@ -4,8 +4,9 @@ use std::fs;
|
||||
use serde_json::json;
|
||||
|
||||
use cc_switch_lib::{
|
||||
get_claude_mcp_path, get_claude_settings_path, import_default_config_test_hook, AppError,
|
||||
AppType, McpApps, McpServer, McpService, MultiAppConfig,
|
||||
get_claude_mcp_path, get_claude_mcp_status, get_claude_settings_path,
|
||||
import_default_config_test_hook, read_claude_mcp_config, update_settings, AppError,
|
||||
AppSettings, AppType, McpApps, McpServer, McpService, MultiAppConfig,
|
||||
};
|
||||
|
||||
#[path = "support.rs"]
|
||||
@@ -673,6 +674,274 @@ fn enabling_claude_mcp_skips_when_claude_config_absent() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_default_claude_dir_keeps_default_split_mcp_path() {
|
||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||
reset_test_fs();
|
||||
let home = ensure_test_home();
|
||||
let claude_dir = home.join(".claude");
|
||||
fs::create_dir_all(&claude_dir).expect("create explicit default claude dir");
|
||||
|
||||
update_settings(AppSettings {
|
||||
claude_config_dir: Some(claude_dir.to_string_lossy().to_string()),
|
||||
..AppSettings::default()
|
||||
})
|
||||
.expect("set explicit default claude config dir");
|
||||
|
||||
assert_eq!(
|
||||
get_claude_mcp_path(),
|
||||
home.join(".claude.json"),
|
||||
"explicit default Claude dir should keep Claude Code's split MCP path"
|
||||
);
|
||||
|
||||
let state = create_test_state().expect("create test state");
|
||||
McpService::upsert_server(
|
||||
&state,
|
||||
McpServer {
|
||||
id: "claude-default".to_string(),
|
||||
name: "Claude Default".to_string(),
|
||||
server: json!({
|
||||
"type": "stdio",
|
||||
"command": "echo"
|
||||
}),
|
||||
apps: McpApps {
|
||||
claude: true,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
docs: None,
|
||||
tags: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("sync default Claude MCP");
|
||||
|
||||
assert!(
|
||||
home.join(".claude.json").exists(),
|
||||
"default split MCP file should be written at home/.claude.json"
|
||||
);
|
||||
assert!(
|
||||
!claude_dir.join(".claude.json").exists(),
|
||||
"explicit default dir should not use nested .claude/.claude.json"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_claude_dir_writes_mcp_inside_config_dir() {
|
||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||
reset_test_fs();
|
||||
let home = ensure_test_home();
|
||||
let custom_dir = home.join("profiles").join(".claude");
|
||||
fs::create_dir_all(&custom_dir).expect("create custom claude dir");
|
||||
|
||||
update_settings(AppSettings {
|
||||
claude_config_dir: Some(custom_dir.to_string_lossy().to_string()),
|
||||
..AppSettings::default()
|
||||
})
|
||||
.expect("set custom claude config dir");
|
||||
|
||||
let expected_mcp_path = custom_dir.join(".claude.json");
|
||||
assert_eq!(
|
||||
get_claude_mcp_path(),
|
||||
expected_mcp_path,
|
||||
"custom Claude dir should keep MCP state inside the config dir"
|
||||
);
|
||||
|
||||
let state = create_test_state().expect("create test state");
|
||||
McpService::upsert_server(
|
||||
&state,
|
||||
McpServer {
|
||||
id: "claude-custom".to_string(),
|
||||
name: "Claude Custom".to_string(),
|
||||
server: json!({
|
||||
"type": "stdio",
|
||||
"command": "echo"
|
||||
}),
|
||||
apps: McpApps {
|
||||
claude: true,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
docs: None,
|
||||
tags: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("sync custom Claude MCP");
|
||||
|
||||
assert!(
|
||||
expected_mcp_path.exists(),
|
||||
"custom Claude MCP file should be written inside custom dir"
|
||||
);
|
||||
assert!(
|
||||
!home.join("profiles").join(".claude.json").exists(),
|
||||
"custom Claude dir should not write sibling .claude.json"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_claude_dir_sync_does_not_copy_default_profile() {
|
||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||
reset_test_fs();
|
||||
let home = ensure_test_home();
|
||||
let home_mcp_path = home.join(".claude.json");
|
||||
let default_profile = json!({
|
||||
"hasCompletedOnboarding": true,
|
||||
"projects": {
|
||||
"/home-project": {
|
||||
"hasTrustDialogAccepted": true
|
||||
}
|
||||
},
|
||||
"mcpServers": {
|
||||
"home-only": {
|
||||
"type": "stdio",
|
||||
"command": "home-command"
|
||||
}
|
||||
},
|
||||
"profileSentinel": "home-profile"
|
||||
});
|
||||
let default_profile_text =
|
||||
serde_json::to_string_pretty(&default_profile).expect("serialize default profile");
|
||||
fs::write(&home_mcp_path, &default_profile_text).expect("seed default Claude profile");
|
||||
|
||||
let custom_dir = home.join("profiles").join("work").join(".claude");
|
||||
fs::create_dir_all(&custom_dir).expect("create custom claude dir");
|
||||
update_settings(AppSettings {
|
||||
claude_config_dir: Some(custom_dir.to_string_lossy().to_string()),
|
||||
..AppSettings::default()
|
||||
})
|
||||
.expect("set custom claude config dir");
|
||||
|
||||
let expected_mcp_path = custom_dir.join(".claude.json");
|
||||
assert_eq!(
|
||||
get_claude_mcp_path(),
|
||||
expected_mcp_path,
|
||||
"custom Claude dir should use nested .claude.json"
|
||||
);
|
||||
assert!(
|
||||
!expected_mcp_path.exists(),
|
||||
"custom profile should start without a live MCP file"
|
||||
);
|
||||
|
||||
let state = create_test_state().expect("create test state");
|
||||
McpService::upsert_server(
|
||||
&state,
|
||||
McpServer {
|
||||
id: "custom-only".to_string(),
|
||||
name: "Custom Only".to_string(),
|
||||
server: json!({
|
||||
"type": "stdio",
|
||||
"command": "custom-command"
|
||||
}),
|
||||
apps: McpApps {
|
||||
claude: true,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
docs: None,
|
||||
tags: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("sync custom Claude MCP");
|
||||
|
||||
let text = fs::read_to_string(&expected_mcp_path).expect("read custom Claude MCP");
|
||||
let value: serde_json::Value = serde_json::from_str(&text).expect("parse custom Claude MCP");
|
||||
let servers = value
|
||||
.get("mcpServers")
|
||||
.and_then(|v| v.as_object())
|
||||
.expect("custom profile should contain mcpServers");
|
||||
assert!(
|
||||
servers.contains_key("custom-only"),
|
||||
"custom profile should contain DB-managed Claude server"
|
||||
);
|
||||
assert!(
|
||||
!servers.contains_key("home-only"),
|
||||
"custom profile should not inherit default profile MCP servers"
|
||||
);
|
||||
assert!(
|
||||
value.get("hasCompletedOnboarding").is_none(),
|
||||
"custom profile should not inherit onboarding state"
|
||||
);
|
||||
assert!(
|
||||
value.get("projects").is_none(),
|
||||
"custom profile should not inherit project trust state"
|
||||
);
|
||||
assert!(
|
||||
value.get("profileSentinel").is_none(),
|
||||
"custom profile should not inherit unrelated default profile fields"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(&home_mcp_path).expect("reread default Claude profile"),
|
||||
default_profile_text,
|
||||
"default Claude profile should remain unchanged"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_claude_dir_read_only_mcp_queries_do_not_create_profile() {
|
||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||
reset_test_fs();
|
||||
let home = ensure_test_home();
|
||||
let home_mcp_path = home.join(".claude.json");
|
||||
fs::write(
|
||||
&home_mcp_path,
|
||||
serde_json::to_string_pretty(&json!({
|
||||
"mcpServers": {
|
||||
"home-only": {
|
||||
"type": "stdio",
|
||||
"command": "home-command"
|
||||
}
|
||||
},
|
||||
"profileSentinel": "home-profile"
|
||||
}))
|
||||
.expect("serialize default profile"),
|
||||
)
|
||||
.expect("seed default Claude profile");
|
||||
|
||||
let custom_dir = home.join("profiles").join("work").join(".claude");
|
||||
fs::create_dir_all(&custom_dir).expect("create custom claude dir");
|
||||
update_settings(AppSettings {
|
||||
claude_config_dir: Some(custom_dir.to_string_lossy().to_string()),
|
||||
..AppSettings::default()
|
||||
})
|
||||
.expect("set custom claude config dir");
|
||||
|
||||
let expected_mcp_path = custom_dir.join(".claude.json");
|
||||
assert!(
|
||||
!expected_mcp_path.exists(),
|
||||
"custom profile should start without a live MCP file"
|
||||
);
|
||||
|
||||
let status =
|
||||
futures::executor::block_on(get_claude_mcp_status()).expect("get Claude MCP status");
|
||||
assert_eq!(
|
||||
status.user_config_path,
|
||||
expected_mcp_path.to_string_lossy(),
|
||||
"status should report the custom profile MCP path"
|
||||
);
|
||||
assert!(
|
||||
!status.user_config_exists,
|
||||
"status should report missing custom profile MCP file"
|
||||
);
|
||||
let text =
|
||||
futures::executor::block_on(read_claude_mcp_config()).expect("read Claude MCP config");
|
||||
assert_eq!(text, None, "missing custom profile should read as None");
|
||||
assert!(
|
||||
!expected_mcp_path.exists(),
|
||||
"read-only MCP queries should not copy or create the custom profile"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_all_enabled_removes_known_disabled_but_preserves_unknown_live_entries() {
|
||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||
|
||||
@@ -597,6 +597,14 @@ wire_api = "responses"
|
||||
|
||||
let state = create_test_state_with_config(&initial_config).expect("create test state");
|
||||
|
||||
let mut proxy_config = state.db.get_proxy_config().await.expect("get proxy config");
|
||||
proxy_config.listen_port = 0;
|
||||
state
|
||||
.db
|
||||
.update_proxy_config(proxy_config)
|
||||
.await
|
||||
.expect("use ephemeral proxy port");
|
||||
|
||||
ProviderService::switch(&state, AppType::Codex, "deepseek-provider")
|
||||
.expect("switch from official subscription to DeepSeek");
|
||||
|
||||
@@ -623,6 +631,12 @@ wire_api = "responses"
|
||||
.set_takeover_for_app("codex", true)
|
||||
.await
|
||||
.expect("enable Codex takeover");
|
||||
let proxy_status = state
|
||||
.proxy_service
|
||||
.get_status()
|
||||
.await
|
||||
.expect("read proxy status after takeover");
|
||||
let codex_proxy_base_url = format!("http://127.0.0.1:{}/v1", proxy_status.port);
|
||||
|
||||
let auth_after_takeover: serde_json::Value =
|
||||
read_json_file(&cc_switch_lib::get_codex_auth_path()).expect("read auth after takeover");
|
||||
@@ -634,7 +648,7 @@ wire_api = "responses"
|
||||
let config_after_takeover =
|
||||
std::fs::read_to_string(cc_switch_lib::get_codex_config_path()).expect("read config");
|
||||
assert!(
|
||||
config_after_takeover.contains("http://127.0.0.1:15721/v1"),
|
||||
config_after_takeover.contains(&codex_proxy_base_url),
|
||||
"enabling takeover should point Codex config.toml at the local proxy"
|
||||
);
|
||||
assert!(
|
||||
|
||||
@@ -33,6 +33,7 @@ pub fn reset_test_fs() {
|
||||
".gemini",
|
||||
".config",
|
||||
".openclaw",
|
||||
"profiles",
|
||||
] {
|
||||
let path = home.join(sub);
|
||||
if path.exists() {
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
Book,
|
||||
Brain,
|
||||
Wrench,
|
||||
RefreshCw,
|
||||
History,
|
||||
BarChart2,
|
||||
Download,
|
||||
@@ -47,6 +46,7 @@ import { useAutoCompact } from "@/hooks/useAutoCompact";
|
||||
import { useUsageCacheBridge } from "@/hooks/useUsageCacheBridge";
|
||||
import { useTauriEvent } from "@/hooks/useTauriEvent";
|
||||
import { useLastValidValue } from "@/hooks/useLastValidValue";
|
||||
import { useScanUnmanagedSkills } from "@/hooks/useSkills";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
import { isTextEditableTarget } from "@/utils/domUtils";
|
||||
import { deepClone } from "@/utils/deepClone";
|
||||
@@ -71,7 +71,11 @@ import { FailoverToggle } from "@/components/proxy/FailoverToggle";
|
||||
import UsageScriptModal from "@/components/UsageScriptModal";
|
||||
import UnifiedMcpPanel from "@/components/mcp/UnifiedMcpPanel";
|
||||
import PromptPanel from "@/components/prompts/PromptPanel";
|
||||
import { SkillsPage } from "@/components/skills/SkillsPage";
|
||||
import {
|
||||
SkillsPage,
|
||||
getSkillsPageHeaderActions,
|
||||
type SkillsPageSource,
|
||||
} from "@/components/skills/SkillsPage";
|
||||
import UnifiedSkillsPanel from "@/components/skills/UnifiedSkillsPanel";
|
||||
import { DeepLinkImportDialog } from "@/components/DeepLinkImportDialog";
|
||||
import { FirstRunNoticeDialog } from "@/components/FirstRunNoticeDialog";
|
||||
@@ -169,6 +173,8 @@ function App() {
|
||||
const sharedFeatureApp: AppId =
|
||||
activeApp === "claude-desktop" ? "claude" : activeApp;
|
||||
const [currentView, setCurrentView] = useState<View>(getInitialView);
|
||||
const [skillsDiscoverySource, setSkillsDiscoverySource] =
|
||||
useState<SkillsPageSource>("repos");
|
||||
const [settingsDefaultTab, setSettingsDefaultTab] = useState("general");
|
||||
const [isAddOpen, setIsAddOpen] = useState(false);
|
||||
const [isWindowMaximized, setIsWindowMaximized] = useState(false);
|
||||
@@ -245,6 +251,10 @@ function App() {
|
||||
const mcpPanelRef = useRef<any>(null);
|
||||
const skillsPageRef = useRef<any>(null);
|
||||
const unifiedSkillsPanelRef = useRef<any>(null);
|
||||
// 订阅未管理 Skill 的共享缓存(实际扫描由 UnifiedSkillsPanel 进入页面时触发)。
|
||||
// 这里 enabled 默认 false,仅用于「导入」按钮的绿点提示,不主动发起扫描。
|
||||
const { data: unmanagedSkills } = useScanUnmanagedSkills();
|
||||
const hasUnmanagedSkills = (unmanagedSkills?.length ?? 0) > 0;
|
||||
const addActionButtonClass =
|
||||
"bg-orange-500 hover:bg-orange-600 dark:bg-orange-500 dark:hover:bg-orange-600 text-white shadow-lg shadow-orange-500/30 dark:shadow-orange-500/40 rounded-full w-8 h-8";
|
||||
|
||||
@@ -857,6 +867,11 @@ function App() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenSkillsDiscovery = () => {
|
||||
setSkillsDiscoverySource("repos");
|
||||
setCurrentView("skillsDiscovery");
|
||||
};
|
||||
|
||||
const renderContent = () => {
|
||||
const content = (() => {
|
||||
switch (currentView) {
|
||||
@@ -884,7 +899,7 @@ function App() {
|
||||
return (
|
||||
<UnifiedSkillsPanel
|
||||
ref={unifiedSkillsPanelRef}
|
||||
onOpenDiscovery={() => setCurrentView("skillsDiscovery")}
|
||||
onOpenDiscovery={handleOpenSkillsDiscovery}
|
||||
currentApp={
|
||||
sharedFeatureApp === "openclaw" ? "claude" : sharedFeatureApp
|
||||
}
|
||||
@@ -897,6 +912,7 @@ function App() {
|
||||
initialApp={
|
||||
sharedFeatureApp === "openclaw" ? "claude" : sharedFeatureApp
|
||||
}
|
||||
onSourceChange={setSkillsDiscoverySource}
|
||||
/>
|
||||
);
|
||||
case "mcp":
|
||||
@@ -1304,15 +1320,26 @@ function App() {
|
||||
onClick={() =>
|
||||
unifiedSkillsPanelRef.current?.openImport()
|
||||
}
|
||||
className="hover:bg-black/5 dark:hover:bg-white/5"
|
||||
className="relative hover:bg-black/5 dark:hover:bg-white/5"
|
||||
title={
|
||||
hasUnmanagedSkills
|
||||
? t("skills.unmanagedAvailable")
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
{t("skills.import")}
|
||||
{hasUnmanagedSkills && (
|
||||
<span
|
||||
className="absolute top-1 right-1 h-2 w-2 rounded-full bg-green-500"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("skillsDiscovery")}
|
||||
onClick={handleOpenSkillsDiscovery}
|
||||
className="hover:bg-black/5 dark:hover:bg-white/5"
|
||||
>
|
||||
<Search className="w-4 h-4 mr-2" />
|
||||
@@ -1322,24 +1349,20 @@ function App() {
|
||||
)}
|
||||
{currentView === "skillsDiscovery" && (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => skillsPageRef.current?.refresh()}
|
||||
className="hover:bg-black/5 dark:hover:bg-white/5"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4 mr-2" />
|
||||
{t("skills.refresh")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => skillsPageRef.current?.openRepoManager()}
|
||||
className="hover:bg-black/5 dark:hover:bg-white/5"
|
||||
>
|
||||
<Settings className="w-4 h-4 mr-2" />
|
||||
{t("skills.repoManager")}
|
||||
</Button>
|
||||
{getSkillsPageHeaderActions(skillsDiscoverySource).map(
|
||||
({ key, labelKey, Icon, execute }) => (
|
||||
<Button
|
||||
key={key}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => execute(skillsPageRef.current)}
|
||||
className="hover:bg-black/5 dark:hover:bg-white/5"
|
||||
>
|
||||
<Icon className="w-4 h-4 mr-2" />
|
||||
{t(labelKey)}
|
||||
</Button>
|
||||
),
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{currentView === "providers" && (
|
||||
|
||||
|
Before Width: | Height: | Size: 1.2 MiB |
@@ -0,0 +1,303 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { exit } from "@tauri-apps/plugin-process";
|
||||
import {
|
||||
Database,
|
||||
Download,
|
||||
RefreshCw,
|
||||
ExternalLink,
|
||||
FolderOpen,
|
||||
Loader2,
|
||||
AlertTriangle,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
const RELEASES_URL = "https://github.com/farion1231/cc-switch/releases";
|
||||
|
||||
interface DatabaseUpgradeProps {
|
||||
payload: {
|
||||
path?: string;
|
||||
error?: string;
|
||||
kind?: string;
|
||||
db_version?: number;
|
||||
supported_version?: number;
|
||||
};
|
||||
}
|
||||
|
||||
// checking: 启动时检查是否有可用更新
|
||||
// upgradable: 有可用更新,升级应用即可解决
|
||||
// incompatible: 已是最新版本但数据库仍过新(可能来自第三方客户端),升级无法解决
|
||||
// updating: 正在下载/安装更新
|
||||
// error: 升级过程出错
|
||||
type Phase = "checking" | "upgradable" | "incompatible" | "updating" | "error";
|
||||
|
||||
interface DownloadProgress {
|
||||
downloaded: number;
|
||||
total: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库版本过新(应用过旧)时的应用内恢复界面。
|
||||
*
|
||||
* 启动时先检查是否有可用更新:
|
||||
* - 有 → 提供「升级应用」一键下载+安装+重启,并展示下载进度条。
|
||||
* - 无 → 说明当前已是最新版本但数据库仍不兼容(通常由第三方客户端或更高版本创建),
|
||||
* 升级无法解决,及时提醒用户备份后改用兼容客户端或等待官方支持。
|
||||
*/
|
||||
export function DatabaseUpgrade({ payload }: DatabaseUpgradeProps) {
|
||||
const { t } = useTranslation();
|
||||
const [phase, setPhase] = useState<Phase>("checking");
|
||||
const [availableVersion, setAvailableVersion] = useState<string | null>(null);
|
||||
const [progress, setProgress] = useState<DownloadProgress | null>(null);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
const unlistenRef = useRef<(() => void) | null>(null);
|
||||
|
||||
const dbVersion = payload.db_version;
|
||||
const supportedVersion = payload.supported_version;
|
||||
|
||||
// 启动时检查可用更新,决定 upgradable / incompatible
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const version = await invoke<string | null>(
|
||||
"check_app_update_available",
|
||||
);
|
||||
if (cancelled) return;
|
||||
if (version) {
|
||||
setAvailableVersion(version);
|
||||
setPhase("upgradable");
|
||||
} else {
|
||||
setPhase("incompatible");
|
||||
}
|
||||
} catch {
|
||||
// 检查失败(如离线):仍允许尝试升级,避免完全卡死
|
||||
if (!cancelled) setPhase("upgradable");
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
unlistenRef.current?.();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const startUpgrade = useCallback(async () => {
|
||||
setPhase("updating");
|
||||
setProgress(null);
|
||||
setErrorMsg(null);
|
||||
try {
|
||||
unlistenRef.current?.();
|
||||
unlistenRef.current = await listen<DownloadProgress>(
|
||||
"update-download-progress",
|
||||
(e) => setProgress(e.payload),
|
||||
);
|
||||
// 成功时后端会下载+安装+重启,不会返回;返回 false 表示无可用更新。
|
||||
const updating = await invoke<boolean>("install_update_and_restart");
|
||||
unlistenRef.current?.();
|
||||
unlistenRef.current = null;
|
||||
if (!updating) {
|
||||
// 竞态:检查时有更新、安装时已无 → 按不兼容处理
|
||||
setPhase("incompatible");
|
||||
}
|
||||
// updating === true:应用即将重启,保持 updating 态直到进程退出。
|
||||
} catch (e) {
|
||||
unlistenRef.current?.();
|
||||
unlistenRef.current = null;
|
||||
setErrorMsg(e instanceof Error ? e.message : String(e));
|
||||
setPhase("error");
|
||||
}
|
||||
}, []);
|
||||
|
||||
const percent =
|
||||
progress && progress.total && progress.total > 0
|
||||
? Math.min(100, Math.round((progress.downloaded / progress.total) * 100))
|
||||
: null;
|
||||
const fmtMB = (n: number) => (n / 1024 / 1024).toFixed(1);
|
||||
|
||||
const isIncompatible = phase === "incompatible";
|
||||
const accent = isIncompatible
|
||||
? {
|
||||
chip: "bg-red-100 text-red-600 dark:bg-red-950/50 dark:text-red-400",
|
||||
Icon: AlertTriangle,
|
||||
}
|
||||
: {
|
||||
chip: "bg-amber-100 text-amber-600 dark:bg-amber-950/50 dark:text-amber-400",
|
||||
Icon: Database,
|
||||
};
|
||||
const AccentIcon = accent.Icon;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background p-6 text-foreground">
|
||||
<div className="w-full max-w-lg space-y-5 rounded-2xl border border-border/60 bg-card/80 p-7 shadow-xl">
|
||||
<div className="flex items-start gap-4">
|
||||
<div
|
||||
className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-xl ${accent.chip}`}
|
||||
>
|
||||
<AccentIcon className="h-6 w-6" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-lg font-semibold">
|
||||
{t("dbUpgrade.title", "数据库版本过新")}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t(
|
||||
"dbUpgrade.description",
|
||||
"当前数据库由更新版本的 CC Switch 创建,需要升级应用后才能继续使用。升级不会删除你的数据。",
|
||||
)}
|
||||
</p>
|
||||
{dbVersion != null && supportedVersion != null && (
|
||||
<p className="pt-0.5 text-xs text-muted-foreground tabular-nums">
|
||||
{t("dbUpgrade.versionInfo", {
|
||||
db: dbVersion,
|
||||
supported: supportedVersion,
|
||||
defaultValue: "数据库版本 v{{db}} · 应用支持 v{{supported}}",
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 错误详情 / 数据库路径 */}
|
||||
<div className="space-y-1 rounded-lg border border-border/50 bg-muted/40 p-3 text-xs text-muted-foreground">
|
||||
{payload.error && (
|
||||
<p className="break-words font-mono">{payload.error}</p>
|
||||
)}
|
||||
{payload.path && (
|
||||
<p className="break-all">
|
||||
{t("dbUpgrade.dbPath", "数据库文件")}:{payload.path}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{phase === "checking" && (
|
||||
<p className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{t("dbUpgrade.checking", "正在检查可用更新…")}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{phase === "upgradable" && availableVersion && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("dbUpgrade.updateAvailable", {
|
||||
version: availableVersion,
|
||||
defaultValue: "发现新版本 v{{version}},升级后即可继续使用。",
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{phase === "incompatible" && (
|
||||
<div className="space-y-2 rounded-lg border border-red-300/60 bg-red-50 p-3 text-sm text-red-700 dark:border-red-500/40 dark:bg-red-950/40 dark:text-red-300">
|
||||
<p className="font-medium">
|
||||
{t("dbUpgrade.incompatibleTitle", "升级也无法解决")}
|
||||
</p>
|
||||
<p className="leading-relaxed">
|
||||
{t("dbUpgrade.incompatibleDescription", {
|
||||
db: dbVersion,
|
||||
supported: supportedVersion,
|
||||
defaultValue:
|
||||
"你已是最新版本,但数据库版本(v{{db}})仍高于本应用支持的版本(v{{supported}})。该数据库可能由第三方客户端或更高版本创建,升级当前官方应用也无法兼容。",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === "updating" && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="flex items-center gap-2 text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{percent === null
|
||||
? t("dbUpgrade.preparing", "正在准备更新…")
|
||||
: t("dbUpgrade.downloading", "正在下载更新…")}
|
||||
</span>
|
||||
{percent !== null && (
|
||||
<span className="tabular-nums text-muted-foreground">
|
||||
{percent}%
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="h-2 w-full overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className={`h-full rounded-full bg-amber-500 transition-all duration-200 ${
|
||||
percent === null ? "w-1/3 animate-pulse" : ""
|
||||
}`}
|
||||
style={percent === null ? undefined : { width: `${percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
{progress && (
|
||||
<p className="text-right text-xs tabular-nums text-muted-foreground">
|
||||
{fmtMB(progress.downloaded)} MB
|
||||
{progress.total ? ` / ${fmtMB(progress.total)} MB` : ""}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === "error" && errorMsg && (
|
||||
<p className="rounded-lg border border-red-300/60 bg-red-50 p-3 text-sm text-red-700 dark:border-red-500/40 dark:bg-red-950/40 dark:text-red-300">
|
||||
{errorMsg}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{(phase === "upgradable" || phase === "error") && (
|
||||
<Button
|
||||
onClick={startUpgrade}
|
||||
className="gap-2 bg-amber-500 text-white hover:bg-amber-600"
|
||||
>
|
||||
{phase === "error" ? (
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
) : (
|
||||
<Download className="h-4 w-4" />
|
||||
)}
|
||||
{phase === "error"
|
||||
? t("dbUpgrade.retry", "重试升级")
|
||||
: t("dbUpgrade.upgradeNow", "升级应用")}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{(phase === "incompatible" || phase === "error") && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
onClick={() =>
|
||||
void invoke("open_external", { url: RELEASES_URL })
|
||||
}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
{t("dbUpgrade.openReleases", "打开发布页")}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
onClick={() => void invoke("open_app_config_folder")}
|
||||
disabled={phase === "updating"}
|
||||
>
|
||||
<FolderOpen className="h-4 w-4" />
|
||||
{t("dbUpgrade.openConfigDir", "打开配置目录")}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="ml-auto text-muted-foreground"
|
||||
onClick={() => void exit(0)}
|
||||
disabled={phase === "updating"}
|
||||
>
|
||||
{t("dbUpgrade.quit", "退出")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default DatabaseUpgrade;
|
||||
@@ -33,6 +33,8 @@ export const TIER_I18N_KEYS: Record<string, string> = {
|
||||
gemini_flash_lite: "subscription.geminiFlashLite",
|
||||
// Token Plan(five_hour 已在上方官方映射中)
|
||||
weekly_limit: "subscription.sevenDay",
|
||||
// 火山方舟 Agent Plan / Coding Plan 的月窗口
|
||||
monthly: "subscription.monthly",
|
||||
// GitHub Copilot
|
||||
premium: "subscription.copilotPremium",
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState } from "react";
|
||||
import { Play, Wand2, Eye, EyeOff, Save } from "lucide-react";
|
||||
import { Play, Wand2, Eye, EyeOff, Save, ExternalLink } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
@@ -8,6 +8,7 @@ import { usageApi, settingsApi, type AppId } from "@/lib/api";
|
||||
import { copilotGetUsage, copilotGetUsageForAccount } from "@/lib/api/copilot";
|
||||
import { useSettingsQuery } from "@/lib/query";
|
||||
import { resolveManagedAccountId } from "@/lib/authBinding";
|
||||
import { useDarkMode } from "@/hooks/useDarkMode";
|
||||
import {
|
||||
extractCodexBaseUrl,
|
||||
extractCodexExperimentalBearerToken,
|
||||
@@ -30,6 +31,14 @@ import {
|
||||
} from "@/config/codingPlanProviders";
|
||||
import { formatUsageDataSummary } from "@/utils/usageDisplay";
|
||||
|
||||
/**
|
||||
* 火山引擎账号级 AccessKey 的密钥管理页(IAM)。
|
||||
* 用量查询走控制面 OpenAPI,需要 AK/SK 签名,与推理 API Key 是两套凭据,
|
||||
* 直接给用户一个可点击的直达地址,省得在控制台里翻菜单。
|
||||
*/
|
||||
const VOLCENGINE_KEY_CONSOLE_URL =
|
||||
"https://console.volcengine.com/iam/keymanage";
|
||||
|
||||
interface UsageScriptModalProps {
|
||||
provider: Provider;
|
||||
appId: AppId;
|
||||
@@ -196,6 +205,7 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
|
||||
const queryClient = useQueryClient();
|
||||
const { data: settingsData } = useSettingsQuery();
|
||||
const [showUsageConfirm, setShowUsageConfirm] = useState(false);
|
||||
const isDarkMode = useDarkMode();
|
||||
|
||||
// 生成带国际化的预设模板
|
||||
const PRESET_TEMPLATES = generatePresetTemplates(t);
|
||||
@@ -538,8 +548,10 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
|
||||
|
||||
// Coding Plan 模板使用专用 API
|
||||
if (selectedTemplate === TEMPLATE_TYPES.TOKEN_PLAN) {
|
||||
// ZenMux 使用用户在脚本配置中手动填入的 API Key 和 Base URL
|
||||
// ZenMux 手填 baseUrl/apiKey;火山是 native 供应商,baseUrl 走推理配置,
|
||||
// 另用账号 AK/SK 签名查询控制面用量。
|
||||
const isZenMux = script.codingPlanProvider === "zenmux";
|
||||
const isVolcengine = script.codingPlanProvider === "volcengine";
|
||||
const baseUrl = isZenMux
|
||||
? (script.baseUrl ?? "")
|
||||
: (providerCredentials.baseUrl ?? "");
|
||||
@@ -547,7 +559,12 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
|
||||
? (script.apiKey ?? "")
|
||||
: (providerCredentials.apiKey ?? "");
|
||||
const { subscriptionApi } = await import("@/lib/api/subscription");
|
||||
const quota = await subscriptionApi.getCodingPlanQuota(baseUrl, apiKey);
|
||||
const quota = await subscriptionApi.getCodingPlanQuota(
|
||||
baseUrl,
|
||||
apiKey,
|
||||
isVolcengine ? script.accessKeyId : undefined,
|
||||
isVolcengine ? script.secretAccessKey : undefined,
|
||||
);
|
||||
if (quota.success && quota.tiers.length > 0) {
|
||||
const summary = quota.tiers
|
||||
.map((tier) => `${tier.name}: ${Math.round(tier.utilization)}%`)
|
||||
@@ -726,8 +743,9 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
|
||||
providerCredentials.baseUrl,
|
||||
);
|
||||
const provider = script.codingPlanProvider || autoDetected || "kimi";
|
||||
// ZenMux 允许手动填写 API Key 和 Base URL,不清除
|
||||
// ZenMux 保留手填 baseUrl/apiKey;火山保留账号 AK/SK;其余清除。
|
||||
const isZenMux = provider === "zenmux";
|
||||
const isVolcengine = provider === "volcengine";
|
||||
setScript({
|
||||
...script,
|
||||
code: "",
|
||||
@@ -735,6 +753,8 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
|
||||
baseUrl: isZenMux ? script.baseUrl : undefined,
|
||||
accessToken: undefined,
|
||||
userId: undefined,
|
||||
accessKeyId: isVolcengine ? script.accessKeyId : undefined,
|
||||
secretAccessKey: isVolcengine ? script.secretAccessKey : undefined,
|
||||
codingPlanProvider: provider,
|
||||
});
|
||||
} else if (presetName === TEMPLATE_TYPES.BALANCE) {
|
||||
@@ -1246,6 +1266,96 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 火山方舟:控制面用量查询需账号 AK/SK(与推理 Key 是两套凭据) */}
|
||||
{selectedTemplate === TEMPLATE_TYPES.TOKEN_PLAN &&
|
||||
script.codingPlanProvider === "volcengine" && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-foreground">
|
||||
{t("usageScript.credentialsConfig")}
|
||||
</h4>
|
||||
<p className="text-xs text-muted-foreground mt-1 leading-relaxed">
|
||||
{t("usageScript.volcengineAkSkHint")}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1.5">
|
||||
{t("usageScript.volcengineKeyConsoleLink")}{" "}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
settingsApi.openExternal(VOLCENGINE_KEY_CONSOLE_URL)
|
||||
}
|
||||
className="inline-flex items-center gap-1 text-blue-400 dark:text-blue-500 hover:text-blue-500 dark:hover:text-blue-400 transition-colors break-all align-baseline underline-offset-2 hover:underline"
|
||||
>
|
||||
{VOLCENGINE_KEY_CONSOLE_URL}
|
||||
<ExternalLink size={12} className="shrink-0" />
|
||||
</button>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="usage-volcengine-ak">
|
||||
{t("usageScript.accessKeyId")}
|
||||
</Label>
|
||||
<Input
|
||||
id="usage-volcengine-ak"
|
||||
type="text"
|
||||
value={script.accessKeyId || ""}
|
||||
onChange={(e) =>
|
||||
setScript({
|
||||
...script,
|
||||
accessKeyId: e.target.value,
|
||||
})
|
||||
}
|
||||
placeholder="AKLT..."
|
||||
autoComplete="off"
|
||||
className="border-white/10"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="usage-volcengine-sk">
|
||||
{t("usageScript.secretAccessKey")}
|
||||
</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="usage-volcengine-sk"
|
||||
type={showApiKey ? "text" : "password"}
|
||||
value={script.secretAccessKey || ""}
|
||||
onChange={(e) =>
|
||||
setScript({
|
||||
...script,
|
||||
secretAccessKey: e.target.value,
|
||||
})
|
||||
}
|
||||
placeholder="••••••••"
|
||||
autoComplete="off"
|
||||
className="border-white/10"
|
||||
/>
|
||||
{script.secretAccessKey && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowApiKey(!showApiKey)}
|
||||
className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground hover:text-foreground transition-colors"
|
||||
aria-label={
|
||||
showApiKey
|
||||
? t("apiKeyInput.hide")
|
||||
: t("apiKeyInput.show")
|
||||
}
|
||||
>
|
||||
{showApiKey ? (
|
||||
<EyeOff size={16} />
|
||||
) : (
|
||||
<Eye size={16} />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 通用配置(始终显示) */}
|
||||
<div className="grid gap-4 md:grid-cols-2 pt-4 border-t border-white/10">
|
||||
{/* 超时时间 */}
|
||||
@@ -1333,6 +1443,7 @@ const UsageScriptModal: React.FC<UsageScriptModalProps> = ({
|
||||
height={480}
|
||||
language="javascript"
|
||||
showMinimap={false}
|
||||
darkMode={isDarkMode}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
DRAG_REGION_STYLE,
|
||||
} from "@/lib/platform";
|
||||
import { isTextEditableTarget } from "@/utils/domUtils";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface FullScreenPanelProps {
|
||||
isOpen: boolean;
|
||||
@@ -17,6 +18,11 @@ interface FullScreenPanelProps {
|
||||
onClose: () => void;
|
||||
children: React.ReactNode;
|
||||
footer?: React.ReactNode;
|
||||
/**
|
||||
* 覆盖内容区滚动容器的内边距/间距类。默认 `px-6 py-6 space-y-6`。
|
||||
* 通过 `cn`(twMerge) 合并,传入如 `pt-3` 只覆盖顶部内边距,其余保持默认。
|
||||
*/
|
||||
contentClassName?: string;
|
||||
}
|
||||
|
||||
const DRAG_BAR_HEIGHT = isWindows() || isLinux() ? 0 : 28; // px - match App.tsx
|
||||
@@ -33,6 +39,7 @@ export const FullScreenPanel: React.FC<FullScreenPanelProps> = ({
|
||||
onClose,
|
||||
children,
|
||||
footer,
|
||||
contentClassName,
|
||||
}) => {
|
||||
React.useEffect(() => {
|
||||
if (isOpen) {
|
||||
@@ -136,7 +143,9 @@ export const FullScreenPanel: React.FC<FullScreenPanelProps> = ({
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto scroll-overlay">
|
||||
<div className="px-6 py-6 space-y-6 w-full">{children}</div>
|
||||
<div className={cn("px-6 py-6 space-y-6 w-full", contentClassName)}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
|
||||
@@ -280,6 +280,9 @@ export function AddProviderDialog({
|
||||
const footer =
|
||||
!showUniversalTab || activeTab === "app-specific" ? (
|
||||
<>
|
||||
<span className="mr-auto min-w-0 text-xs text-muted-foreground truncate">
|
||||
{t("provider.addFooterHint")}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
@@ -322,6 +325,7 @@ export function AddProviderDialog({
|
||||
title={t("provider.addNewProvider")}
|
||||
onClose={() => onOpenChange(false)}
|
||||
footer={footer}
|
||||
contentClassName="pt-3"
|
||||
>
|
||||
{showUniversalTab ? (
|
||||
<Tabs
|
||||
|
||||
@@ -320,7 +320,7 @@ export function ProviderCard({
|
||||
)}
|
||||
/>
|
||||
<div className="relative flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
@@ -335,7 +335,7 @@ export function ProviderCard({
|
||||
<GripVertical className="h-4 w-4" />
|
||||
</button>
|
||||
|
||||
<div className="h-8 w-8 rounded-lg bg-muted flex items-center justify-center border border-border group-hover:scale-105 transition-transform duration-300">
|
||||
<div className="h-8 w-8 flex-shrink-0 rounded-lg bg-muted flex items-center justify-center border border-border group-hover:scale-105 transition-transform duration-300">
|
||||
<ProviderIcon
|
||||
icon={provider.icon}
|
||||
name={provider.name}
|
||||
@@ -344,7 +344,7 @@ export function ProviderCard({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<div className="flex flex-wrap items-center gap-2 min-h-7">
|
||||
<h3 className="text-base font-semibold leading-none">
|
||||
{provider.name}
|
||||
@@ -451,7 +451,7 @@ export function ProviderCard({
|
||||
type="button"
|
||||
onClick={handleOpenWebsite}
|
||||
className={cn(
|
||||
"inline-flex items-center text-sm max-w-[280px]",
|
||||
"inline-flex max-w-full items-center overflow-hidden text-left text-sm",
|
||||
isClickableUrl
|
||||
? "text-blue-500 transition-colors hover:underline dark:text-blue-400 cursor-pointer"
|
||||
: "text-muted-foreground cursor-default",
|
||||
@@ -459,7 +459,7 @@ export function ProviderCard({
|
||||
title={displayUrl}
|
||||
disabled={!isClickableUrl}
|
||||
>
|
||||
<span className="truncate">{displayUrl}</span>
|
||||
<span className="min-w-0 truncate">{displayUrl}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
import { useCallback } from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { isTextEditableTarget } from "@/utils/domUtils";
|
||||
|
||||
interface ProviderListProps {
|
||||
providers: Record<string, Provider>;
|
||||
@@ -245,8 +246,13 @@ export function ProviderList({
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
|
||||
const key = event.key.toLowerCase();
|
||||
if ((event.metaKey || event.ctrlKey) && key === "f") {
|
||||
// 正在输入框/可编辑区域中时不抢占 Ctrl+F(例如添加供应商表单里
|
||||
// ProviderPresetSelector 的搜索框),避免与其同名快捷键冲突。
|
||||
if (isTextEditableTarget(document.activeElement)) return;
|
||||
event.preventDefault();
|
||||
setIsSearchOpen(true);
|
||||
return;
|
||||
@@ -257,8 +263,8 @@ export function ProviderList({
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
globalThis.addEventListener("keydown", handleKeyDown);
|
||||
return () => globalThis.removeEventListener("keydown", handleKeyDown);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
type FetchedModel,
|
||||
} from "@/lib/api/model-fetch";
|
||||
import { CustomUserAgentField } from "./CustomUserAgentField";
|
||||
import { LocalProxyRequestOverridesField } from "./LocalProxyRequestOverridesField";
|
||||
import type {
|
||||
ProviderCategory,
|
||||
ClaudeApiFormat,
|
||||
@@ -145,6 +146,10 @@ interface ClaudeFormFieldsProps {
|
||||
// Local proxy User-Agent override
|
||||
customUserAgent: string;
|
||||
onCustomUserAgentChange: (value: string) => void;
|
||||
localProxyHeadersOverride: string;
|
||||
onLocalProxyHeadersOverrideChange: (value: string) => void;
|
||||
localProxyBodyOverride: string;
|
||||
onLocalProxyBodyOverrideChange: (value: string) => void;
|
||||
}
|
||||
|
||||
export function ClaudeFormFields({
|
||||
@@ -201,8 +206,15 @@ export function ClaudeFormFields({
|
||||
onFullUrlChange,
|
||||
customUserAgent,
|
||||
onCustomUserAgentChange,
|
||||
localProxyHeadersOverride,
|
||||
onLocalProxyHeadersOverrideChange,
|
||||
localProxyBodyOverride,
|
||||
onLocalProxyBodyOverrideChange,
|
||||
}: ClaudeFormFieldsProps) {
|
||||
const { t } = useTranslation();
|
||||
const hasRequestOverrides = Boolean(
|
||||
localProxyHeadersOverride.trim() || localProxyBodyOverride.trim(),
|
||||
);
|
||||
const hasAnyAdvancedValue = !!(
|
||||
claudeModel ||
|
||||
defaultHaikuModel ||
|
||||
@@ -211,7 +223,8 @@ export function ClaudeFormFields({
|
||||
defaultFableModel ||
|
||||
apiFormat !== "anthropic" ||
|
||||
apiKeyField !== "ANTHROPIC_AUTH_TOKEN" ||
|
||||
customUserAgent
|
||||
customUserAgent ||
|
||||
hasRequestOverrides
|
||||
);
|
||||
const [advancedExpanded, setAdvancedExpanded] = useState(hasAnyAdvancedValue);
|
||||
|
||||
@@ -963,6 +976,15 @@ export function ClaudeFormFields({
|
||||
value={customUserAgent}
|
||||
onChange={onCustomUserAgentChange}
|
||||
/>
|
||||
|
||||
<div className="border-t border-border-default pt-3">
|
||||
<LocalProxyRequestOverridesField
|
||||
headersJson={localProxyHeadersOverride}
|
||||
bodyJson={localProxyBodyOverride}
|
||||
onHeadersJsonChange={onLocalProxyHeadersOverrideChange}
|
||||
onBodyJsonChange={onLocalProxyBodyOverrideChange}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
|
||||
@@ -4,6 +4,13 @@ import { Button } from "@/components/ui/button";
|
||||
import { FormLabel } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
@@ -26,6 +33,7 @@ import {
|
||||
type FetchedModel,
|
||||
} from "@/lib/api/model-fetch";
|
||||
import { CustomUserAgentField } from "./CustomUserAgentField";
|
||||
import { LocalProxyRequestOverridesField } from "./LocalProxyRequestOverridesField";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type {
|
||||
CodexApiFormat,
|
||||
@@ -61,6 +69,13 @@ interface CodexFormFieldsProps {
|
||||
autoSelect: boolean;
|
||||
onAutoSelectChange: (checked: boolean) => void;
|
||||
|
||||
// Local routing / takeover
|
||||
// takeoverEnabled gates model mapping + reasoning visibility; it is decoupled
|
||||
// from the wire format so a native Responses provider can use model mapping
|
||||
// without Chat Completions conversion.
|
||||
takeoverEnabled: boolean;
|
||||
onTakeoverEnabledChange: (enabled: boolean) => void;
|
||||
|
||||
// API Format
|
||||
// Note: wire_api is always "responses" for Codex; apiFormat controls proxy-layer conversion
|
||||
apiFormat: CodexApiFormat;
|
||||
@@ -78,6 +93,10 @@ interface CodexFormFieldsProps {
|
||||
// Local proxy User-Agent override
|
||||
customUserAgent: string;
|
||||
onCustomUserAgentChange: (value: string) => void;
|
||||
localProxyHeadersOverride: string;
|
||||
onLocalProxyHeadersOverrideChange: (value: string) => void;
|
||||
localProxyBodyOverride: string;
|
||||
onLocalProxyBodyOverrideChange: (value: string) => void;
|
||||
}
|
||||
|
||||
type CodexCatalogRow = CodexCatalogModel & { rowId: string };
|
||||
@@ -127,6 +146,8 @@ export function CodexFormFields({
|
||||
onCustomEndpointsChange,
|
||||
autoSelect,
|
||||
onAutoSelectChange,
|
||||
takeoverEnabled,
|
||||
onTakeoverEnabledChange,
|
||||
apiFormat,
|
||||
onApiFormatChange,
|
||||
codexChatReasoning = {},
|
||||
@@ -136,12 +157,18 @@ export function CodexFormFields({
|
||||
speedTestEndpoints,
|
||||
customUserAgent,
|
||||
onCustomUserAgentChange,
|
||||
localProxyHeadersOverride,
|
||||
onLocalProxyHeadersOverrideChange,
|
||||
localProxyBodyOverride,
|
||||
onLocalProxyBodyOverrideChange,
|
||||
}: CodexFormFieldsProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [fetchedModels, setFetchedModels] = useState<FetchedModel[]>([]);
|
||||
const [isFetchingModels, setIsFetchingModels] = useState(false);
|
||||
const needsLocalRouting = apiFormat === "openai_chat";
|
||||
// takeoverEnabled 控制模型映射/思考能力的显示;isChatFormat 仅在选了
|
||||
// Chat Completions 上游格式时为真(思考能力是 Chat 专属)。
|
||||
const isChatFormat = apiFormat === "openai_chat";
|
||||
const canEditCatalog = Boolean(onCatalogModelsChange);
|
||||
const canEditReasoning = Boolean(onCodexChatReasoningChange);
|
||||
const supportsThinking =
|
||||
@@ -149,8 +176,13 @@ export function CodexFormFields({
|
||||
codexChatReasoning.supportsEffort === true;
|
||||
const supportsEffort = codexChatReasoning.supportsEffort === true;
|
||||
|
||||
// needsLocalRouting 非默认值说明预设/用户动过路由配置,需要让模型映射保持可见
|
||||
const hasAnyAdvancedValue = !!customUserAgent || needsLocalRouting;
|
||||
// takeoverEnabled 取代了旧的 needsLocalRouting:上游格式已与路由解耦。
|
||||
// takeoverEnabled 为真说明预设/用户启用了本地路由;请求头/请求体覆盖也算高级值。
|
||||
const hasRequestOverrides = Boolean(
|
||||
localProxyHeadersOverride.trim() || localProxyBodyOverride.trim(),
|
||||
);
|
||||
const hasAnyAdvancedValue =
|
||||
!!customUserAgent || hasRequestOverrides || takeoverEnabled;
|
||||
const [advancedExpanded, setAdvancedExpanded] = useState(hasAnyAdvancedValue);
|
||||
|
||||
// 预设/编辑加载填充高级值后自动展开(仅从折叠→展开,不会自动折叠)
|
||||
@@ -191,13 +223,6 @@ export function CodexFormFields({
|
||||
onCatalogModelsChange(next);
|
||||
}, [catalogRows, onCatalogModelsChange]);
|
||||
|
||||
const handleLocalRoutingChange = useCallback(
|
||||
(checked: boolean) => {
|
||||
onApiFormatChange(checked ? "openai_chat" : "openai_responses");
|
||||
},
|
||||
[onApiFormatChange],
|
||||
);
|
||||
|
||||
const handleReasoningThinkingChange = useCallback(
|
||||
(checked: boolean) => {
|
||||
if (!onCodexChatReasoningChange) return;
|
||||
@@ -378,38 +403,83 @@ export function CodexFormFields({
|
||||
</p>
|
||||
)}
|
||||
<CollapsibleContent className="space-y-3 pt-3">
|
||||
{/* 本地路由映射开关 —— 沿用 shouldShowSpeedTest 门控,cloud_provider 保持不可切换 */}
|
||||
{/* 上游格式 + 本地路由映射 —— 两个平级、相互独立的控件。
|
||||
格式不依赖路由:Responses 原生供应商无需开启路由即可直连;
|
||||
沿用 shouldShowSpeedTest 门控,cloud_provider 保持不可切换。 */}
|
||||
{shouldShowSpeedTest && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
<FormLabel>
|
||||
{t("codexConfig.localRoutingToggle", {
|
||||
defaultValue: "需要本地路由映射",
|
||||
<div className="space-y-3">
|
||||
{/* 上游格式 —— 顶层独立选择,与路由开关解耦 */}
|
||||
<div className="space-y-1.5">
|
||||
<FormLabel htmlFor="codex-upstream-format">
|
||||
{t("codexConfig.upstreamFormatLabel", {
|
||||
defaultValue: "上游格式",
|
||||
})}
|
||||
</FormLabel>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
{needsLocalRouting
|
||||
? t("codexConfig.localRoutingOnHint", {
|
||||
defaultValue:
|
||||
"Codex 目前仅原生支持 OpenAI Responses API 与 GPT 系列模型;如果您的供应商使用 Chat Completions 协议或非 GPT 模型(如 DeepSeek、Kimi),则需要打开本开关,并在使用过程中保持本地路由开启。",
|
||||
})
|
||||
: t("codexConfig.localRoutingOffHint", {
|
||||
defaultValue:
|
||||
"如果您的供应商不是原生 OpenAI Responses API,或者模型名不是 Codex 默认的 GPT 系列,请打开此开关。",
|
||||
<Select
|
||||
value={apiFormat}
|
||||
onValueChange={(value) =>
|
||||
onApiFormatChange(value as CodexApiFormat)
|
||||
}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="codex-upstream-format"
|
||||
className="w-full"
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="openai_chat">
|
||||
{t("codexConfig.upstreamFormatChat", {
|
||||
defaultValue: "Chat Completions(转换)",
|
||||
})}
|
||||
</SelectItem>
|
||||
<SelectItem value="openai_responses">
|
||||
{t("codexConfig.upstreamFormatResponses", {
|
||||
defaultValue: "Responses(原生)",
|
||||
})}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
{t("codexConfig.upstreamFormatHint", {
|
||||
defaultValue:
|
||||
"供应商原生是 Responses API 就选 Responses(直连,不转换格式);使用 Chat Completions 协议就选 Chat(转换为 Chat Completions)。",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={needsLocalRouting}
|
||||
onCheckedChange={handleLocalRoutingChange}
|
||||
aria-label={t("codexConfig.localRoutingToggle", {
|
||||
defaultValue: "需要本地路由映射",
|
||||
})}
|
||||
/>
|
||||
|
||||
{/* 需要本地路由映射 —— 纯模型映射门控,与上游格式无关 */}
|
||||
<div className="flex items-center justify-between gap-4 border-t border-border-default pt-3">
|
||||
<div className="space-y-1">
|
||||
<FormLabel>
|
||||
{t("codexConfig.localRoutingToggle", {
|
||||
defaultValue: "需要本地路由映射",
|
||||
})}
|
||||
</FormLabel>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
{takeoverEnabled
|
||||
? t("codexConfig.localRoutingOnHint", {
|
||||
defaultValue:
|
||||
"打开后可在下方配置模型映射:让 Codex 的 /model 菜单显示自定义模型名,并把请求映射到真实上游模型。",
|
||||
})
|
||||
: t("codexConfig.localRoutingOffHint", {
|
||||
defaultValue:
|
||||
"供应商模型名无需改写、也无需在 /model 菜单展示自定义名称时,可保持关闭;需要模型映射时打开。",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={takeoverEnabled}
|
||||
onCheckedChange={onTakeoverEnabledChange}
|
||||
aria-label={t("codexConfig.localRoutingToggle", {
|
||||
defaultValue: "需要本地路由映射",
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{needsLocalRouting && canEditReasoning && (
|
||||
{takeoverEnabled && isChatFormat && canEditReasoning && (
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-3",
|
||||
@@ -480,8 +550,9 @@ export function CodexFormFields({
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-3",
|
||||
(shouldShowSpeedTest ||
|
||||
(needsLocalRouting && canEditReasoning)) &&
|
||||
(takeoverEnabled && isChatFormat && canEditReasoning)) &&
|
||||
"border-t border-border-default pt-3",
|
||||
)}
|
||||
>
|
||||
@@ -490,10 +561,19 @@ export function CodexFormFields({
|
||||
value={customUserAgent}
|
||||
onChange={onCustomUserAgentChange}
|
||||
/>
|
||||
<div className="border-t border-border-default pt-3">
|
||||
<LocalProxyRequestOverridesField
|
||||
headersJson={localProxyHeadersOverride}
|
||||
bodyJson={localProxyBodyOverride}
|
||||
onHeadersJsonChange={onLocalProxyHeadersOverrideChange}
|
||||
onBodyJsonChange={onLocalProxyBodyOverrideChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 模型映射 —— 仅在本地路由 + 可编辑时显示;上方恒有 UA 字段,分隔线无需条件 */}
|
||||
{needsLocalRouting && canEditCatalog && (
|
||||
{/* 模型映射 —— 仅在本地路由开启 + 可编辑时显示(与上游格式解耦,
|
||||
Responses 原生供应商同样可配置);上方恒有 UA 字段,分隔线无需条件 */}
|
||||
{takeoverEnabled && canEditCatalog && (
|
||||
<div className="space-y-4 border-t border-border-default pt-3">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FormLabel } from "@/components/ui/form";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
parseBodyOverrideJson,
|
||||
parseHeaderOverrideJson,
|
||||
} from "@/lib/requestOverrides";
|
||||
|
||||
interface LocalProxyRequestOverridesFieldProps {
|
||||
headersJson: string;
|
||||
bodyJson: string;
|
||||
onHeadersJsonChange: (value: string) => void;
|
||||
onBodyJsonChange: (value: string) => void;
|
||||
}
|
||||
|
||||
export function LocalProxyRequestOverridesField({
|
||||
headersJson,
|
||||
bodyJson,
|
||||
onHeadersJsonChange,
|
||||
onBodyJsonChange,
|
||||
}: LocalProxyRequestOverridesFieldProps) {
|
||||
const { t } = useTranslation();
|
||||
const headerError = parseHeaderOverrideJson(headersJson).error;
|
||||
const bodyError = parseBodyOverrideJson(bodyJson).error;
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<FormLabel>
|
||||
{t("providerForm.localProxyRequestOverrides", {
|
||||
defaultValue: "本地代理请求覆盖",
|
||||
})}
|
||||
</FormLabel>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("providerForm.localProxyRequestOverridesHint", {
|
||||
defaultValue:
|
||||
"仅在本地路由/代理接管后生效,应用于协议转换后的上游请求。",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<FormLabel className="text-xs text-muted-foreground">
|
||||
{t("providerForm.localProxyHeaderOverrides", {
|
||||
defaultValue: "Header 覆盖",
|
||||
})}
|
||||
</FormLabel>
|
||||
<Textarea
|
||||
value={headersJson}
|
||||
onChange={(event) => onHeadersJsonChange(event.target.value)}
|
||||
placeholder={'{\n "X-Provider": "cc-switch"\n}'}
|
||||
className="min-h-[132px] resize-y font-mono text-xs"
|
||||
aria-invalid={Boolean(headerError)}
|
||||
/>
|
||||
{headerError && (
|
||||
<p className="text-xs text-destructive">
|
||||
{t("providerForm.localProxyHeaderOverridesInvalidDetail", {
|
||||
error: headerError,
|
||||
defaultValue: "Header 覆盖格式错误:{{error}}",
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<FormLabel className="text-xs text-muted-foreground">
|
||||
{t("providerForm.localProxyBodyOverrides", {
|
||||
defaultValue: "Body 覆盖",
|
||||
})}
|
||||
</FormLabel>
|
||||
<Textarea
|
||||
value={bodyJson}
|
||||
onChange={(event) => onBodyJsonChange(event.target.value)}
|
||||
placeholder={'{\n "temperature": 0.2\n}'}
|
||||
className="min-h-[132px] resize-y font-mono text-xs"
|
||||
aria-invalid={Boolean(bodyError)}
|
||||
/>
|
||||
{bodyError && (
|
||||
<p className="text-xs text-destructive">
|
||||
{t("providerForm.localProxyBodyOverridesInvalidDetail", {
|
||||
error: bodyError,
|
||||
defaultValue: "Body 覆盖格式错误:{{error}}",
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Popover,
|
||||
@@ -471,6 +470,19 @@ export function OmoFormFields({
|
||||
const firstIsUnavailable =
|
||||
Boolean(currentVariant) &&
|
||||
!(modelVariantsMap[currentModel] || []).includes(currentVariant);
|
||||
const defaultVariantLabel = t("omo.defaultWrapped", {
|
||||
defaultValue: "(Default)",
|
||||
});
|
||||
const getVariantLabel = (variant: string, index: number) =>
|
||||
firstIsUnavailable && index === 0
|
||||
? t("omo.currentValueUnavailable", {
|
||||
value: variant,
|
||||
defaultValue: "{{value}} (current value, unavailable)",
|
||||
})
|
||||
: variant;
|
||||
const selectedVariantLabel = currentVariant
|
||||
? getVariantLabel(currentVariant, 0)
|
||||
: defaultVariantLabel;
|
||||
|
||||
return (
|
||||
<Select
|
||||
@@ -479,25 +491,21 @@ export function OmoFormFields({
|
||||
onChange(value === EMPTY_VARIANT_VALUE ? "" : value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-28 h-8 text-xs shrink-0">
|
||||
<SelectValue
|
||||
placeholder={t("omo.variantPlaceholder", {
|
||||
defaultValue: "variant",
|
||||
})}
|
||||
/>
|
||||
<SelectTrigger
|
||||
className="w-28 min-w-0 h-8 overflow-hidden text-xs shrink-0"
|
||||
title={selectedVariantLabel}
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate text-left">
|
||||
{selectedVariantLabel}
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="max-h-72">
|
||||
<SelectItem value={EMPTY_VARIANT_VALUE}>
|
||||
{t("omo.defaultWrapped", { defaultValue: "(Default)" })}
|
||||
{defaultVariantLabel}
|
||||
</SelectItem>
|
||||
{variantOptions.map((variant, index) => (
|
||||
<SelectItem key={`${variant}-${index}`} value={variant}>
|
||||
{firstIsUnavailable && index === 0
|
||||
? t("omo.currentValueUnavailable", {
|
||||
value: variant,
|
||||
defaultValue: "{{value}} (current value, unavailable)",
|
||||
})
|
||||
: variant}
|
||||
{getVariantLabel(variant, index)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
|
||||
@@ -8,7 +8,12 @@ import { Button } from "@/components/ui/button";
|
||||
import { Form, FormField, FormItem, FormMessage } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { providerSchema, type ProviderFormData } from "@/lib/schemas/provider";
|
||||
import {
|
||||
buildLocalProxyRequestOverrides,
|
||||
formatRequestOverrideObject,
|
||||
} from "@/lib/requestOverrides";
|
||||
import { providersApi, settingsApi, type AppId } from "@/lib/api";
|
||||
import { useDarkMode } from "@/hooks/useDarkMode";
|
||||
import type {
|
||||
ProviderCategory,
|
||||
ProviderMeta,
|
||||
@@ -145,6 +150,16 @@ const codexApiFormatFromWireApi = (
|
||||
}
|
||||
};
|
||||
|
||||
// 从已保存的 settingsConfig 推断 Codex 模型映射条目数(用于决定本地路由初始开关)。
|
||||
const codexCatalogCountFromSettings = (settingsConfig: unknown): number => {
|
||||
if (settingsConfig && typeof settingsConfig === "object") {
|
||||
const models = (settingsConfig as { modelCatalog?: { models?: unknown } })
|
||||
.modelCatalog?.models;
|
||||
return Array.isArray(models) ? models.length : 0;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
export const normalizeCodexCatalogModelsForSave = (
|
||||
models: CodexCatalogModel[],
|
||||
): CodexCatalogModel[] => {
|
||||
@@ -210,6 +225,10 @@ const normalizeCodexChatReasoningForSave = (
|
||||
};
|
||||
};
|
||||
|
||||
type LocalProxyRequestOverridesBuildResult = ReturnType<
|
||||
typeof buildLocalProxyRequestOverrides
|
||||
>;
|
||||
|
||||
export interface ProviderFormProps {
|
||||
appId: AppId;
|
||||
providerId?: string;
|
||||
@@ -264,6 +283,7 @@ function ProviderFormFull({
|
||||
const { data: settingsData } = useSettingsQuery();
|
||||
const showCommonConfigNotice =
|
||||
settingsData != null && settingsData.commonConfigConfirmed !== true;
|
||||
const isDarkMode = useDarkMode();
|
||||
|
||||
const handleCommonConfigConfirm = async () => {
|
||||
try {
|
||||
@@ -356,6 +376,16 @@ function ProviderFormFull({
|
||||
});
|
||||
setCodexChatReasoning(initialData?.meta?.codexChatReasoning ?? {});
|
||||
setCustomUserAgent(initialData?.meta?.customUserAgent ?? "");
|
||||
setLocalProxyHeadersOverride(
|
||||
formatRequestOverrideObject(
|
||||
initialData?.meta?.localProxyRequestOverrides?.headers,
|
||||
),
|
||||
);
|
||||
setLocalProxyBodyOverride(
|
||||
formatRequestOverrideObject(
|
||||
initialData?.meta?.localProxyRequestOverrides?.body,
|
||||
),
|
||||
);
|
||||
}, [appId, initialData, supportsFullUrl]);
|
||||
|
||||
const defaultValues: ProviderFormData = useMemo(
|
||||
@@ -412,6 +442,10 @@ function ProviderFormFull({
|
||||
const [softIssues, setSoftIssues] = useState<string[] | null>(null);
|
||||
const [pendingFormValues, setPendingFormValues] =
|
||||
useState<ProviderFormData | null>(null);
|
||||
const [
|
||||
pendingLocalProxyRequestOverridesResult,
|
||||
setPendingLocalProxyRequestOverridesResult,
|
||||
] = useState<LocalProxyRequestOverridesBuildResult | null>(null);
|
||||
// 确认框走的提交路径绕过了 react-hook-form 的 isSubmitting,单独追踪
|
||||
const [isConfirmSubmitting, setIsConfirmSubmitting] = useState(false);
|
||||
|
||||
@@ -515,6 +549,18 @@ function ProviderFormFull({
|
||||
const [customUserAgent, setCustomUserAgent] = useState<string>(
|
||||
() => initialData?.meta?.customUserAgent ?? "",
|
||||
);
|
||||
const [localProxyHeadersOverride, setLocalProxyHeadersOverride] =
|
||||
useState<string>(() =>
|
||||
formatRequestOverrideObject(
|
||||
initialData?.meta?.localProxyRequestOverrides?.headers,
|
||||
),
|
||||
);
|
||||
const [localProxyBodyOverride, setLocalProxyBodyOverride] = useState<string>(
|
||||
() =>
|
||||
formatRequestOverrideObject(
|
||||
initialData?.meta?.localProxyRequestOverrides?.body,
|
||||
),
|
||||
);
|
||||
|
||||
const {
|
||||
codexAuth,
|
||||
@@ -532,24 +578,29 @@ function ProviderFormFull({
|
||||
resetCodexConfig,
|
||||
} = useCodexConfigState({ initialData });
|
||||
|
||||
const initialCodexApiFormat: CodexApiFormat =
|
||||
initialData?.meta?.apiFormat === "openai_chat"
|
||||
? "openai_chat"
|
||||
: initialData?.meta?.apiFormat === "openai_responses"
|
||||
? "openai_responses"
|
||||
: (codexApiFormatFromWireApi(
|
||||
extractCodexWireApi(
|
||||
typeof initialData?.settingsConfig?.config === "string"
|
||||
? initialData.settingsConfig.config
|
||||
: "",
|
||||
),
|
||||
) ?? "openai_responses");
|
||||
|
||||
const [localCodexApiFormat, setLocalCodexApiFormat] =
|
||||
useState<CodexApiFormat>(() => {
|
||||
if (initialData?.meta?.apiFormat === "openai_chat") {
|
||||
return "openai_chat";
|
||||
}
|
||||
if (initialData?.meta?.apiFormat === "openai_responses") {
|
||||
return "openai_responses";
|
||||
}
|
||||
return (
|
||||
codexApiFormatFromWireApi(
|
||||
extractCodexWireApi(
|
||||
typeof initialData?.settingsConfig?.config === "string"
|
||||
? initialData.settingsConfig.config
|
||||
: "",
|
||||
),
|
||||
) ?? "openai_responses"
|
||||
);
|
||||
});
|
||||
useState<CodexApiFormat>(initialCodexApiFormat);
|
||||
|
||||
// 本地路由(接管)开关 —— 纯模型映射门控,与上游格式完全独立。
|
||||
// 没有独立持久化字段,初值仅按「是否已配置模型映射」推断(有 catalog 即视为
|
||||
// 接管已开)。只在 useState 初始化与预设重置点设置,跟 localCodexApiFormat
|
||||
// 对称,避免漂移。
|
||||
const [codexTakeoverEnabled, setCodexTakeoverEnabled] = useState<boolean>(
|
||||
() => codexCatalogCountFromSettings(initialData?.settingsConfig) > 0,
|
||||
);
|
||||
|
||||
const { configError: codexConfigError, debouncedValidate } =
|
||||
useCodexTomlValidation();
|
||||
@@ -580,6 +631,7 @@ function ProviderFormFull({
|
||||
const template = getCodexCustomTemplate();
|
||||
resetCodexConfig(template.auth, template.config);
|
||||
setCodexChatReasoning({});
|
||||
setCodexTakeoverEnabled(false);
|
||||
}
|
||||
}, [appId, initialData, selectedPresetId, resetCodexConfig]);
|
||||
|
||||
@@ -929,7 +981,26 @@ function ProviderFormFull({
|
||||
|
||||
const [isCommonConfigModalOpen, setIsCommonConfigModalOpen] = useState(false);
|
||||
|
||||
const shouldApplyLocalProxyRequestOverrides =
|
||||
(appId === "claude" || appId === "codex") && category !== "official";
|
||||
|
||||
const handleSubmit = async (values: ProviderFormData) => {
|
||||
const overridesResult = shouldApplyLocalProxyRequestOverrides
|
||||
? buildLocalProxyRequestOverrides(
|
||||
localProxyHeadersOverride,
|
||||
localProxyBodyOverride,
|
||||
)
|
||||
: {};
|
||||
if (overridesResult.error) {
|
||||
toast.error(
|
||||
t("providerForm.localProxyRequestOverridesInvalid", {
|
||||
defaultValue: `本地代理请求覆盖格式错误:${overridesResult.error}`,
|
||||
error: overridesResult.error,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 软性问题(业务约束,用户可选择仍要保存)
|
||||
const issues: string[] = [];
|
||||
|
||||
@@ -1167,13 +1238,27 @@ function ProviderFormFull({
|
||||
// 弹确认框让用户决定是否仍要保存
|
||||
setSoftIssues(issues);
|
||||
setPendingFormValues(values);
|
||||
setPendingLocalProxyRequestOverridesResult(overridesResult);
|
||||
return;
|
||||
}
|
||||
|
||||
await performSubmit(values);
|
||||
await performSubmit(values, overridesResult);
|
||||
};
|
||||
|
||||
const performSubmit = async (values: ProviderFormData) => {
|
||||
const performSubmit = async (
|
||||
values: ProviderFormData,
|
||||
overridesResult: LocalProxyRequestOverridesBuildResult,
|
||||
) => {
|
||||
if (overridesResult.error) {
|
||||
toast.error(
|
||||
t("providerForm.localProxyRequestOverridesInvalid", {
|
||||
defaultValue: `本地代理请求覆盖格式错误:${overridesResult.error}`,
|
||||
error: overridesResult.error,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// OAuth / 其它身份识别(与 handleSubmit 保持一致)
|
||||
const isCopilotProvider =
|
||||
templatePreset?.providerType === "github_copilot" ||
|
||||
@@ -1193,7 +1278,7 @@ function ProviderFormFull({
|
||||
? setCodexWireApi(codexConfig ?? "", "responses")
|
||||
: (codexConfig ?? "");
|
||||
const normalizedCatalogModels =
|
||||
category !== "official" && localCodexApiFormat === "openai_chat"
|
||||
category !== "official" && codexTakeoverEnabled
|
||||
? normalizeCodexCatalogModelsForSave(codexCatalogModels)
|
||||
: [];
|
||||
// Sync first catalog row's model into config.toml so Codex uses it as default
|
||||
@@ -1389,6 +1474,7 @@ function ProviderFormFull({
|
||||
codexChatReasoning:
|
||||
appId === "codex" &&
|
||||
category !== "official" &&
|
||||
codexTakeoverEnabled &&
|
||||
localCodexApiFormat === "openai_chat"
|
||||
? normalizeCodexChatReasoningForSave(codexChatReasoning)
|
||||
: undefined,
|
||||
@@ -1396,6 +1482,9 @@ function ProviderFormFull({
|
||||
(appId === "claude" || appId === "codex") && category !== "official"
|
||||
? customUserAgent.trim() || undefined
|
||||
: undefined,
|
||||
localProxyRequestOverrides: shouldApplyLocalProxyRequestOverrides
|
||||
? overridesResult.overrides
|
||||
: undefined,
|
||||
testConfig: testConfig.enabled ? testConfig : undefined,
|
||||
costMultiplier: pricingConfig.enabled
|
||||
? pricingConfig.costMultiplier
|
||||
@@ -1538,6 +1627,8 @@ function ProviderFormFull({
|
||||
codexApiFormatFromWireApi(extractCodexWireApi(template.config)) ??
|
||||
"openai_responses",
|
||||
);
|
||||
// 自定义模板无模型映射,路由默认关闭
|
||||
setCodexTakeoverEnabled(false);
|
||||
}
|
||||
if (appId === "gemini") {
|
||||
resetGeminiConfig({}, {});
|
||||
@@ -1580,6 +1671,8 @@ function ProviderFormFull({
|
||||
codexApiFormatFromWireApi(extractCodexWireApi(config)) ??
|
||||
"openai_responses",
|
||||
);
|
||||
// 路由开关与格式无关,仅按预设是否带模型映射决定
|
||||
setCodexTakeoverEnabled((preset.modelCatalog?.length ?? 0) > 0);
|
||||
|
||||
form.reset({
|
||||
name: preset.nameKey ? t(preset.nameKey) : preset.name,
|
||||
@@ -2023,6 +2116,10 @@ function ProviderFormFull({
|
||||
onFullUrlChange={setLocalIsFullUrl}
|
||||
customUserAgent={customUserAgent}
|
||||
onCustomUserAgentChange={setCustomUserAgent}
|
||||
localProxyHeadersOverride={localProxyHeadersOverride}
|
||||
onLocalProxyHeadersOverrideChange={setLocalProxyHeadersOverride}
|
||||
localProxyBodyOverride={localProxyBodyOverride}
|
||||
onLocalProxyBodyOverrideChange={setLocalProxyBodyOverride}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -2048,6 +2145,8 @@ function ProviderFormFull({
|
||||
}
|
||||
autoSelect={endpointAutoSelect}
|
||||
onAutoSelectChange={setEndpointAutoSelect}
|
||||
takeoverEnabled={codexTakeoverEnabled}
|
||||
onTakeoverEnabledChange={setCodexTakeoverEnabled}
|
||||
apiFormat={localCodexApiFormat}
|
||||
onApiFormatChange={handleCodexApiFormatChange}
|
||||
codexChatReasoning={codexChatReasoning}
|
||||
@@ -2057,6 +2156,10 @@ function ProviderFormFull({
|
||||
speedTestEndpoints={speedTestEndpoints}
|
||||
customUserAgent={customUserAgent}
|
||||
onCustomUserAgentChange={setCustomUserAgent}
|
||||
localProxyHeadersOverride={localProxyHeadersOverride}
|
||||
onLocalProxyHeadersOverrideChange={setLocalProxyHeadersOverride}
|
||||
localProxyBodyOverride={localProxyBodyOverride}
|
||||
onLocalProxyBodyOverrideChange={setLocalProxyBodyOverride}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -2233,6 +2336,7 @@ function ProviderFormFull({
|
||||
rows={14}
|
||||
showValidation={false}
|
||||
language="json"
|
||||
darkMode={isDarkMode}
|
||||
/>
|
||||
</div>
|
||||
) : appId === "opencode" &&
|
||||
@@ -2257,6 +2361,7 @@ function ProviderFormFull({
|
||||
rows={14}
|
||||
showValidation={true}
|
||||
language="json"
|
||||
darkMode={isDarkMode}
|
||||
/>
|
||||
</div>
|
||||
{settingsConfigErrorField}
|
||||
@@ -2287,6 +2392,7 @@ function ProviderFormFull({
|
||||
rows={14}
|
||||
showValidation={true}
|
||||
language="json"
|
||||
darkMode={isDarkMode}
|
||||
/>
|
||||
</div>
|
||||
<FormField
|
||||
@@ -2378,15 +2484,19 @@ function ProviderFormFull({
|
||||
onConfirm={async () => {
|
||||
if (isConfirmSubmitting) return;
|
||||
const values = pendingFormValues;
|
||||
if (!values) {
|
||||
const overridesResult = pendingLocalProxyRequestOverridesResult;
|
||||
if (!values || !overridesResult) {
|
||||
setSoftIssues(null);
|
||||
setPendingFormValues(null);
|
||||
setPendingLocalProxyRequestOverridesResult(null);
|
||||
return;
|
||||
}
|
||||
setIsConfirmSubmitting(true);
|
||||
try {
|
||||
await performSubmit(values);
|
||||
await performSubmit(values, overridesResult);
|
||||
setSoftIssues(null);
|
||||
setPendingFormValues(null);
|
||||
setPendingLocalProxyRequestOverridesResult(null);
|
||||
} catch (error) {
|
||||
console.error("[ProviderForm] soft-confirm submit failed:", error);
|
||||
// 保留确认框和 pending values,让用户可以重试或取消
|
||||
@@ -2398,6 +2508,7 @@ function ProviderFormFull({
|
||||
if (isConfirmSubmitting) return;
|
||||
setSoftIssues(null);
|
||||
setPendingFormValues(null);
|
||||
setPendingLocalProxyRequestOverridesResult(null);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -4,7 +4,15 @@ import { FormLabel } from "@/components/ui/form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ClaudeIcon, CodexIcon, GeminiIcon } from "@/components/BrandIcons";
|
||||
import { ArrowUpAZ, Search, Zap, Star, Layers, Settings2 } from "lucide-react";
|
||||
import {
|
||||
ArrowUpAZ,
|
||||
Search,
|
||||
Zap,
|
||||
Star,
|
||||
Heart,
|
||||
Layers,
|
||||
Settings2,
|
||||
} from "lucide-react";
|
||||
import type { ProviderPreset } from "@/config/claudeProviderPresets";
|
||||
import type { CodexProviderPreset } from "@/config/codexProviderPresets";
|
||||
import type { GeminiProviderPreset } from "@/config/geminiProviderPresets";
|
||||
@@ -80,7 +88,21 @@ export function sortPresetEntries(
|
||||
t: PresetTranslator,
|
||||
): PresetEntry[] {
|
||||
if (sortMode === PresetSortMode.Original) {
|
||||
return [...entries];
|
||||
// 置顶优先级:官方分类 > 尊享合作伙伴(Kimi)> 其余原顺序。
|
||||
// 用分区拼接而非排序,确保每组内部各自的相对顺序都不变;
|
||||
// 排他条件保证「既是官方又是 prime」的预设只归入官方组、不被重复。
|
||||
const official = entries.filter(
|
||||
(entry) => entry.preset.category === "official",
|
||||
);
|
||||
const prime = entries.filter(
|
||||
(entry) =>
|
||||
entry.preset.category !== "official" && entry.preset.primePartner,
|
||||
);
|
||||
const rest = entries.filter(
|
||||
(entry) =>
|
||||
entry.preset.category !== "official" && !entry.preset.primePartner,
|
||||
);
|
||||
return [...official, ...prime, ...rest];
|
||||
}
|
||||
|
||||
return [...entries].sort((a, b) =>
|
||||
@@ -123,7 +145,7 @@ export function ProviderPresetSelector({
|
||||
onUniversalPresetSelect,
|
||||
onManageUniversalProviders,
|
||||
category,
|
||||
}: ProviderPresetSelectorProps) {
|
||||
}: Readonly<ProviderPresetSelectorProps>) {
|
||||
const { t } = useTranslation();
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
@@ -131,6 +153,7 @@ export function ProviderPresetSelector({
|
||||
PresetSortMode.Original,
|
||||
);
|
||||
const searchContainerRef = useRef<HTMLDivElement>(null);
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// 点击搜索区域外时收起并清空,对齐旧 Popover 的「点击外部关闭」行为
|
||||
useEffect(() => {
|
||||
@@ -150,6 +173,25 @@ export function ProviderPresetSelector({
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, [searchOpen]);
|
||||
|
||||
// 键盘快捷键: Ctrl/Cmd+F 打开搜索并聚焦输入框。
|
||||
// 使用捕获阶段并阻止冒泡,避免背后 ProviderList 的同名快捷键被意外触发。
|
||||
// 首次打开靠 Input 的 autoFocus 聚焦;若搜索已打开(例如点击 preset 后焦点
|
||||
// 停在按钮上),setSearchOpen(true) 同值不会重渲染、autoFocus 不重触发,
|
||||
// 这里用 rAF 命令式地把焦点移回搜索框(不 select,避免吞掉随后输入的首字符)。
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "f") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setSearchOpen(true);
|
||||
requestAnimationFrame(() => searchInputRef.current?.focus());
|
||||
}
|
||||
};
|
||||
|
||||
globalThis.addEventListener("keydown", handleKeyDown, true);
|
||||
return () => globalThis.removeEventListener("keydown", handleKeyDown, true);
|
||||
}, []);
|
||||
|
||||
const visiblePresetEntries = useMemo(
|
||||
() =>
|
||||
getVisiblePresetEntries(presetEntries, {
|
||||
@@ -258,12 +300,13 @@ export function ProviderPresetSelector({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div ref={searchContainerRef} className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<FormLabel>{t("providerPreset.label")}</FormLabel>
|
||||
<div ref={searchContainerRef} className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
{searchOpen && (
|
||||
<Input
|
||||
ref={searchInputRef}
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
@@ -278,7 +321,7 @@ export function ProviderPresetSelector({
|
||||
aria-label={t("providerPreset.searchAriaLabel", {
|
||||
defaultValue: "Search provider presets",
|
||||
})}
|
||||
className="w-48 h-8"
|
||||
className="w-60 h-8"
|
||||
autoFocus
|
||||
/>
|
||||
)}
|
||||
@@ -359,6 +402,7 @@ export function ProviderPresetSelector({
|
||||
{visiblePresetEntries.map((entry) => {
|
||||
const isSelected = selectedPresetId === entry.id;
|
||||
const isPartner = entry.preset.isPartner;
|
||||
const isPrimePartner = entry.preset.primePartner;
|
||||
const presetCategory = entry.preset.category ?? "others";
|
||||
return (
|
||||
<button
|
||||
@@ -376,10 +420,18 @@ export function ProviderPresetSelector({
|
||||
<span className="truncate">
|
||||
{getPresetDisplayName(entry.preset, t)}
|
||||
</span>
|
||||
{isPartner && (
|
||||
<span className="absolute -top-1 -right-1 flex items-center gap-0.5 rounded-full bg-gradient-to-r from-amber-500 to-yellow-500 px-1.5 py-0.5 text-[10px] font-bold text-white shadow-md">
|
||||
<Star className="h-2.5 w-2.5 fill-current" />
|
||||
</span>
|
||||
{isPrimePartner ? (
|
||||
<Heart
|
||||
className="absolute -top-1 -right-1 h-5 w-5 fill-amber-500 text-amber-500 drop-shadow-sm"
|
||||
strokeWidth={0}
|
||||
aria-hidden
|
||||
/>
|
||||
) : (
|
||||
isPartner && (
|
||||
<span className="absolute -top-1 -right-1 flex items-center gap-0.5 rounded-full bg-gradient-to-r from-amber-500 to-yellow-500 px-1.5 py-0.5 text-[10px] font-bold text-white shadow-md">
|
||||
<Star className="h-2.5 w-2.5 fill-current" />
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
@@ -387,50 +439,47 @@ export function ProviderPresetSelector({
|
||||
</div>
|
||||
|
||||
{onUniversalPresetSelect && universalProviderPresets.length > 0 && (
|
||||
<>
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(150px,1fr))] gap-2">
|
||||
{universalProviderPresets.map((preset) => (
|
||||
<button
|
||||
key={`universal-${preset.providerType}`}
|
||||
type="button"
|
||||
onClick={() => onUniversalPresetSelect(preset)}
|
||||
className="inline-flex items-center justify-start gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors bg-accent text-muted-foreground hover:bg-accent/80 relative w-full"
|
||||
title={t("universalProvider.hint", {
|
||||
defaultValue:
|
||||
"跨应用统一配置,自动同步到 Claude/Codex/Gemini",
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(150px,1fr))] gap-2">
|
||||
{universalProviderPresets.map((preset) => (
|
||||
<button
|
||||
key={`universal-${preset.providerType}`}
|
||||
type="button"
|
||||
onClick={() => onUniversalPresetSelect(preset)}
|
||||
className="inline-flex items-center justify-start gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors bg-accent text-muted-foreground hover:bg-accent/80 relative w-full"
|
||||
title={t("universalProvider.hint", {
|
||||
defaultValue: "跨应用统一配置,自动同步到 Claude/Codex/Gemini",
|
||||
})}
|
||||
>
|
||||
<ProviderIcon
|
||||
icon={preset.icon}
|
||||
name={preset.name}
|
||||
size={14}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
<span className="truncate">{preset.name}</span>
|
||||
<span className="absolute -top-1 -right-1 flex items-center gap-0.5 rounded-full bg-gradient-to-r from-indigo-500 to-purple-500 px-1.5 py-0.5 text-[10px] font-bold text-white shadow-md">
|
||||
<Layers className="h-2.5 w-2.5" />
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
{onManageUniversalProviders && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onManageUniversalProviders}
|
||||
className="inline-flex items-center justify-start gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors bg-accent text-muted-foreground hover:bg-accent/80 w-full"
|
||||
title={t("universalProvider.manage", {
|
||||
defaultValue: "管理统一供应商",
|
||||
})}
|
||||
>
|
||||
<Settings2 className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="truncate">
|
||||
{t("universalProvider.manage", {
|
||||
defaultValue: "管理",
|
||||
})}
|
||||
>
|
||||
<ProviderIcon
|
||||
icon={preset.icon}
|
||||
name={preset.name}
|
||||
size={14}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
<span className="truncate">{preset.name}</span>
|
||||
<span className="absolute -top-1 -right-1 flex items-center gap-0.5 rounded-full bg-gradient-to-r from-indigo-500 to-purple-500 px-1.5 py-0.5 text-[10px] font-bold text-white shadow-md">
|
||||
<Layers className="h-2.5 w-2.5" />
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
{onManageUniversalProviders && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onManageUniversalProviders}
|
||||
className="inline-flex items-center justify-start gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors bg-accent text-muted-foreground hover:bg-accent/80 w-full"
|
||||
title={t("universalProvider.manage", {
|
||||
defaultValue: "管理统一供应商",
|
||||
})}
|
||||
>
|
||||
<Settings2 className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="truncate">
|
||||
{t("universalProvider.manage", {
|
||||
defaultValue: "管理",
|
||||
})}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground">{getCategoryHint()}</p>
|
||||
|
||||
@@ -29,7 +29,6 @@ export function ApiKeySection({
|
||||
websiteUrl,
|
||||
placeholder,
|
||||
disabled,
|
||||
isPartner,
|
||||
partnerPromotionKey,
|
||||
}: ApiKeySectionProps) {
|
||||
const { t } = useTranslation();
|
||||
@@ -73,8 +72,8 @@ export function ApiKeySection({
|
||||
})}
|
||||
</a>
|
||||
|
||||
{/* 合作伙伴促销信息 */}
|
||||
{isPartner && partnerPromotionKey && (
|
||||
{/* 促销信息(与 isPartner 解耦:仅凭 partnerPromotionKey 即可展示,星标仍由 isPartner 控制) */}
|
||||
{partnerPromotionKey && (
|
||||
<div className="rounded-md bg-blue-50 dark:bg-blue-950/30 p-2.5 border border-blue-200 dark:border-blue-800">
|
||||
<p className="text-xs leading-relaxed text-blue-700 dark:text-blue-300">
|
||||
💡{" "}
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
MessageSquare,
|
||||
Clock,
|
||||
FolderOpen,
|
||||
FileText,
|
||||
X,
|
||||
CheckSquare,
|
||||
} from "lucide-react";
|
||||
@@ -897,6 +898,38 @@ export function SessionManagerPage({ appId }: { appId: string }) {
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{selectedSession.sourcePath && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
void handleCopy(
|
||||
selectedSession.sourcePath!,
|
||||
t("sessionManager.sourcePathCopied"),
|
||||
)
|
||||
}
|
||||
className="flex items-center gap-1 hover:text-foreground transition-colors"
|
||||
>
|
||||
<FileText className="size-3 shrink-0" />
|
||||
<span className="font-mono truncate max-w-[200px]">
|
||||
{getBaseName(selectedSession.sourcePath)}
|
||||
</span>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="bottom"
|
||||
className="max-w-xs"
|
||||
>
|
||||
<p className="font-mono text-xs break-all">
|
||||
{selectedSession.sourcePath}
|
||||
</p>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{t("sessionManager.clickToCopyPath")}
|
||||
</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -35,7 +35,6 @@ import { useUpdate } from "@/contexts/UpdateContext";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { motion } from "framer-motion";
|
||||
import appIcon from "@/assets/icons/app-icon.png";
|
||||
import fable5VerifiedBanner from "@/assets/fable5-verified.png";
|
||||
import { APP_ICON_MAP } from "@/config/appConfig";
|
||||
import type { AppId } from "@/lib/api/types";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
@@ -854,12 +853,6 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<img
|
||||
src={fable5VerifiedBanner}
|
||||
alt="Fable 5 Verified"
|
||||
className="h-16 w-auto shrink-0 select-none"
|
||||
draggable={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { motion } from "framer-motion";
|
||||
import {
|
||||
Loader2,
|
||||
@@ -102,6 +109,7 @@ export function SettingsPage({
|
||||
|
||||
const [activeTab, setActiveTab] = useState<string>("general");
|
||||
const [showRestartPrompt, setShowRestartPrompt] = useState(false);
|
||||
const tabScrollContainerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
@@ -116,6 +124,12 @@ export function SettingsPage({
|
||||
}
|
||||
}, [requiresRestart]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (tabScrollContainerRef.current) {
|
||||
tabScrollContainerRef.current.scrollTop = 0;
|
||||
}
|
||||
}, [activeTab]);
|
||||
|
||||
const closeAfterSave = useCallback(() => {
|
||||
// 保存成功后关闭:不再重置语言,避免需要“保存两次”才生效
|
||||
acknowledgeRestart();
|
||||
@@ -226,7 +240,10 @@ export function SettingsPage({
|
||||
</TabsList>
|
||||
|
||||
<div className="flex-1 min-h-0 flex flex-col">
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden pr-2">
|
||||
<div
|
||||
ref={tabScrollContainerRef}
|
||||
className="flex-1 overflow-y-auto overflow-x-hidden pr-2"
|
||||
>
|
||||
<TabsContent value="general" className="space-y-6 mt-0">
|
||||
{settings ? (
|
||||
<motion.div
|
||||
|
||||
@@ -15,7 +15,13 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { RefreshCw, Search, Loader2 } from "lucide-react";
|
||||
import {
|
||||
RefreshCw,
|
||||
Search,
|
||||
Loader2,
|
||||
Settings,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { SkillCard } from "./SkillCard";
|
||||
import { RepoManagerPanel } from "./RepoManagerPanel";
|
||||
@@ -36,8 +42,11 @@ import type {
|
||||
} from "@/lib/api/skills";
|
||||
import { formatSkillError } from "@/lib/errors/skillErrorParser";
|
||||
|
||||
export type SkillsPageSource = "repos" | "skillssh";
|
||||
|
||||
interface SkillsPageProps {
|
||||
initialApp?: AppId;
|
||||
onSourceChange?: (source: SkillsPageSource) => void;
|
||||
}
|
||||
|
||||
export interface SkillsPageHandle {
|
||||
@@ -45,7 +54,35 @@ export interface SkillsPageHandle {
|
||||
openRepoManager: () => void;
|
||||
}
|
||||
|
||||
type SearchSource = "repos" | "skillssh";
|
||||
type SkillsPageHeaderAction = {
|
||||
key: string;
|
||||
sources: readonly SkillsPageSource[];
|
||||
labelKey: string;
|
||||
Icon: LucideIcon;
|
||||
execute: (page: SkillsPageHandle | null) => void;
|
||||
};
|
||||
|
||||
const SKILLS_PAGE_HEADER_ACTIONS: readonly SkillsPageHeaderAction[] = [
|
||||
{
|
||||
key: "refresh-repos",
|
||||
sources: ["repos"],
|
||||
labelKey: "skills.refresh",
|
||||
Icon: RefreshCw,
|
||||
execute: (page) => page?.refresh(),
|
||||
},
|
||||
{
|
||||
key: "manage-repos",
|
||||
sources: ["repos", "skillssh"],
|
||||
labelKey: "skills.repoManager",
|
||||
Icon: Settings,
|
||||
execute: (page) => page?.openRepoManager(),
|
||||
},
|
||||
];
|
||||
|
||||
export const getSkillsPageHeaderActions = (source: SkillsPageSource) =>
|
||||
SKILLS_PAGE_HEADER_ACTIONS.filter((action) =>
|
||||
action.sources.includes(source),
|
||||
);
|
||||
|
||||
const SKILLSSH_PAGE_SIZE = 20;
|
||||
|
||||
@@ -54,7 +91,7 @@ const SKILLSSH_PAGE_SIZE = 20;
|
||||
* 用于浏览和安装来自仓库或 skills.sh 的 Skills
|
||||
*/
|
||||
export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
({ initialApp = "claude" }, ref) => {
|
||||
({ initialApp = "claude", onSourceChange }, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [repoManagerOpen, setRepoManagerOpen] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
@@ -64,7 +101,7 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
>("all");
|
||||
|
||||
// skills.sh 搜索状态
|
||||
const [searchSource, setSearchSource] = useState<SearchSource>("repos");
|
||||
const [searchSource, setSearchSource] = useState<SkillsPageSource>("repos");
|
||||
const [skillsShInput, setSkillsShInput] = useState("");
|
||||
const [skillsShQuery, setSkillsShQuery] = useState("");
|
||||
const [skillsShOffset, setSkillsShOffset] = useState(0);
|
||||
@@ -90,23 +127,25 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
data: skillsShResult,
|
||||
isLoading: loadingSkillsSh,
|
||||
isFetching: fetchingSkillsSh,
|
||||
isPlaceholderData: placeholderSkillsSh,
|
||||
} = useSearchSkillsSh(skillsShQuery, SKILLSSH_PAGE_SIZE, skillsShOffset);
|
||||
|
||||
// 当搜索结果返回时累积
|
||||
useEffect(() => {
|
||||
if (skillsShResult) {
|
||||
if (skillsShResult && !placeholderSkillsSh) {
|
||||
if (skillsShOffset === 0) {
|
||||
setAccumulatedResults(skillsShResult.skills);
|
||||
} else {
|
||||
setAccumulatedResults((prev) => [...prev, ...skillsShResult.skills]);
|
||||
}
|
||||
}
|
||||
}, [skillsShResult, skillsShOffset]);
|
||||
}, [skillsShResult, skillsShOffset, placeholderSkillsSh]);
|
||||
|
||||
// 手动提交搜索
|
||||
const handleSkillsShSearch = () => {
|
||||
const trimmed = skillsShInput.trim();
|
||||
if (trimmed.length < 2) return;
|
||||
if (trimmed === skillsShQuery && skillsShOffset === 0) return;
|
||||
setSkillsShOffset(0);
|
||||
setAccumulatedResults([]);
|
||||
setSkillsShQuery(trimmed);
|
||||
@@ -314,13 +353,19 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
// 是否有更多 skills.sh 结果
|
||||
const hasMoreSkillsSh =
|
||||
skillsShResult && accumulatedResults.length < skillsShResult.totalCount;
|
||||
const searchingSkillsSh =
|
||||
(loadingSkillsSh || fetchingSkillsSh) && accumulatedResults.length === 0;
|
||||
|
||||
// 无仓库时默认切换到 skills.sh
|
||||
// 无仓库配置时默认切换到 skills.sh;仓库发现结果为空时仍保留仓库视图,方便手动刷新重试。
|
||||
const effectiveSource =
|
||||
searchSource === "repos" && skills.length === 0 && !loading
|
||||
searchSource === "repos" && repos.length === 0 && !loading
|
||||
? "skillssh"
|
||||
: searchSource;
|
||||
|
||||
useEffect(() => {
|
||||
onSourceChange?.(effectiveSource);
|
||||
}, [effectiveSource, onSourceChange]);
|
||||
|
||||
return (
|
||||
<div className="px-6 flex flex-col flex-1 min-h-0 overflow-hidden bg-background/50">
|
||||
{/* 技能网格(可滚动详情区域) */}
|
||||
@@ -528,7 +573,7 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
) : (
|
||||
/* ===== skills.sh 模式 ===== */
|
||||
<>
|
||||
{loadingSkillsSh && accumulatedResults.length === 0 ? (
|
||||
{searchingSkillsSh ? (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
<span className="ml-3 text-sm text-muted-foreground">
|
||||
@@ -542,7 +587,7 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
{t("skills.skillssh.searchPlaceholder")}
|
||||
</p>
|
||||
</div>
|
||||
) : accumulatedResults.length === 0 && !loadingSkillsSh ? (
|
||||
) : accumulatedResults.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-48 text-center">
|
||||
<p className="text-lg font-medium text-foreground">
|
||||
{t("skills.skillssh.noResults", {
|
||||
|
||||
@@ -90,8 +90,9 @@ const UnifiedSkillsPanel = React.forwardRef<
|
||||
const toggleAppMutation = useToggleSkillApp();
|
||||
const uninstallMutation = useUninstallSkill();
|
||||
const restoreBackupMutation = useRestoreSkillBackup();
|
||||
// enabled: true —— 进入 Skill 页面时自动静默扫描一次(绿点提示来源)
|
||||
const { data: unmanagedSkills, refetch: scanUnmanaged } =
|
||||
useScanUnmanagedSkills();
|
||||
useScanUnmanagedSkills({ enabled: true });
|
||||
const importMutation = useImportSkillsFromApps();
|
||||
const installFromZipMutation = useInstallSkillsFromZip();
|
||||
const {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as React from "react";
|
||||
import * as SelectPrimitive from "@radix-ui/react-select";
|
||||
import { ChevronDown, ChevronUp } from "lucide-react";
|
||||
import { Check, ChevronDown, ChevronUp } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Select = SelectPrimitive.Root;
|
||||
@@ -87,6 +87,11 @@ const SelectItem = React.forwardRef<
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from "react";
|
||||
import { useDarkMode } from "@/hooks/useDarkMode";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Eye, EyeOff, RefreshCw } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -34,6 +35,7 @@ export function UniversalProviderFormModal({
|
||||
editingProvider,
|
||||
initialPreset,
|
||||
}: UniversalProviderFormModalProps) {
|
||||
const isDarkMode = useDarkMode();
|
||||
const { t } = useTranslation();
|
||||
const isEditMode = !!editingProvider;
|
||||
|
||||
@@ -658,6 +660,7 @@ requires_openai_auth = true`;
|
||||
value={JSON.stringify(claudeConfigJson, null, 2)}
|
||||
onChange={() => {}}
|
||||
height={180}
|
||||
darkMode={isDarkMode}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -673,6 +676,7 @@ requires_openai_auth = true`;
|
||||
value={JSON.stringify(codexConfigJson, null, 2)}
|
||||
onChange={() => {}}
|
||||
height={280}
|
||||
darkMode={isDarkMode}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -688,6 +692,7 @@ requires_openai_auth = true`;
|
||||
value={JSON.stringify(geminiConfigJson, null, 2)}
|
||||
onChange={() => {}}
|
||||
height={140}
|
||||
darkMode={isDarkMode}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { Check, Loader2, Search } from "lucide-react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { useUpdateModelPricing } from "@/lib/query/usage";
|
||||
import { isTextEditableTarget } from "@/utils/domUtils";
|
||||
|
||||
const MODELS_DEV_API_URL = "https://models.dev/api.json";
|
||||
// 全量约 5000 条:默认只展示最新发布的一批,搜索时才做全量匹配
|
||||
const DEFAULT_VISIBLE_ROWS = 50;
|
||||
const MAX_VISIBLE_ROWS = 200;
|
||||
|
||||
interface ModelsDevCost {
|
||||
input?: number;
|
||||
output?: number;
|
||||
cache_read?: number;
|
||||
cache_write?: number;
|
||||
}
|
||||
|
||||
interface ModelsDevModel {
|
||||
id?: string;
|
||||
name?: string;
|
||||
release_date?: string;
|
||||
cost?: ModelsDevCost;
|
||||
}
|
||||
|
||||
interface ModelsDevProvider {
|
||||
id?: string;
|
||||
name?: string;
|
||||
models?: Record<string, ModelsDevModel>;
|
||||
}
|
||||
|
||||
type ModelsDevResponse = Record<string, ModelsDevProvider>;
|
||||
|
||||
interface ModelsDevEntry {
|
||||
/** providerId/modelId,同一模型可能出现在多个供应商下 */
|
||||
key: string;
|
||||
providerId: string;
|
||||
providerName: string;
|
||||
modelId: string;
|
||||
/** 实际入库的 ID,与后端 clean_model_id_for_pricing 的归一化规则一致 */
|
||||
normalizedId: string;
|
||||
modelName: string;
|
||||
/** YYYY-MM-DD 或 YYYY-MM,缺失时为空串 */
|
||||
releaseDate: string;
|
||||
input: number;
|
||||
output: number;
|
||||
cacheRead: number;
|
||||
cacheWrite: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 与后端 clean_model_id_for_pricing(usage_stats.rs)保持一致:
|
||||
* 取最后一个 '/' 之后的段、去掉 ':' 后缀、'@' 换成 '-'、转小写、去掉 [1m] 标记。
|
||||
* 成本归因查询用的就是这种归一化形式,原样入库的 ID 永远匹配不上。
|
||||
*/
|
||||
export function normalizeModelIdForPricing(modelId: string): string {
|
||||
const afterSlash = modelId.slice(modelId.lastIndexOf("/") + 1);
|
||||
const beforeColon = afterSlash.split(":")[0] ?? "";
|
||||
let normalized = beforeColon.trim().replace(/@/g, "-").toLowerCase();
|
||||
if (normalized.endsWith("[1m]")) {
|
||||
normalized = normalized.slice(0, -"[1m]".length).trim();
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/** 转成后端可解析的非负十进制字符串(不能用 String(),小数可能变成科学计数法) */
|
||||
export function formatPrice(value: number): string {
|
||||
if (!Number.isFinite(value) || value <= 0) return "0";
|
||||
// toFixed 对 >=1e21 会退化成科学计数法;这种量级的"价格"只可能是脏数据,按 0 处理
|
||||
if (value >= 1e12) return "0";
|
||||
const trimmed = value.toFixed(6).replace(/0+$/, "").replace(/\.$/, "");
|
||||
return trimmed || "0";
|
||||
}
|
||||
|
||||
export function flattenModels(data: ModelsDevResponse): ModelsDevEntry[] {
|
||||
const entries: ModelsDevEntry[] = [];
|
||||
for (const [providerId, provider] of Object.entries(data)) {
|
||||
if (!provider || typeof provider !== "object") continue;
|
||||
const providerName = provider.name || providerId;
|
||||
for (const [modelId, model] of Object.entries(provider.models ?? {})) {
|
||||
const cost = model?.cost;
|
||||
const input = typeof cost?.input === "number" ? cost.input : null;
|
||||
const output = typeof cost?.output === "number" ? cost.output : null;
|
||||
if (input === null && output === null) continue;
|
||||
const normalizedId = normalizeModelIdForPricing(modelId);
|
||||
if (!normalizedId) continue;
|
||||
entries.push({
|
||||
key: `${providerId}/${modelId}`,
|
||||
providerId,
|
||||
providerName,
|
||||
modelId,
|
||||
normalizedId,
|
||||
modelName: model?.name || modelId,
|
||||
releaseDate:
|
||||
typeof model?.release_date === "string" ? model.release_date : "",
|
||||
input: input ?? 0,
|
||||
output: output ?? 0,
|
||||
cacheRead: typeof cost?.cache_read === "number" ? cost.cache_read : 0,
|
||||
cacheWrite:
|
||||
typeof cost?.cache_write === "number" ? cost.cache_write : 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
// 最新发布的排在前面
|
||||
entries.sort(
|
||||
(a, b) =>
|
||||
b.releaseDate.localeCompare(a.releaseDate) ||
|
||||
a.modelName.localeCompare(b.modelName),
|
||||
);
|
||||
return entries;
|
||||
}
|
||||
|
||||
interface ModelsDevPickerDialogProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
/** 导入成功后调用(此时定价列表已刷新) */
|
||||
onImported: () => void;
|
||||
}
|
||||
|
||||
export function ModelsDevPickerDialog({
|
||||
open,
|
||||
onClose,
|
||||
onImported,
|
||||
}: ModelsDevPickerDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const updatePricing = useUpdateModelPricing();
|
||||
|
||||
const [search, setSearch] = useState("");
|
||||
const [providerFilter, setProviderFilter] = useState("all");
|
||||
const [selected, setSelected] = useState<ModelsDevEntry | null>(null);
|
||||
|
||||
// 每次打开时重置选择与过滤条件
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSearch("");
|
||||
setProviderFilter("all");
|
||||
setSelected(null);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const { data, isLoading, error, refetch } = useQuery({
|
||||
queryKey: ["models-dev-pricing"],
|
||||
queryFn: async (): Promise<ModelsDevResponse> => {
|
||||
const res = await fetch(MODELS_DEV_API_URL);
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
},
|
||||
enabled: open,
|
||||
staleTime: 60 * 60 * 1000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const entries = useMemo(() => (data ? flattenModels(data) : []), [data]);
|
||||
|
||||
const providers = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
for (const entry of entries) {
|
||||
if (!map.has(entry.providerId)) {
|
||||
map.set(entry.providerId, entry.providerName);
|
||||
}
|
||||
}
|
||||
return Array.from(map, ([id, name]) => ({ id, name })).sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
);
|
||||
}, [entries]);
|
||||
|
||||
const isFiltering = search.trim() !== "" || providerFilter !== "all";
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const query = search.trim().toLowerCase();
|
||||
return entries.filter(
|
||||
(entry) =>
|
||||
(providerFilter === "all" || entry.providerId === providerFilter) &&
|
||||
(!query ||
|
||||
entry.modelId.toLowerCase().includes(query) ||
|
||||
entry.normalizedId.includes(query) ||
|
||||
entry.modelName.toLowerCase().includes(query) ||
|
||||
entry.providerName.toLowerCase().includes(query)),
|
||||
);
|
||||
}, [entries, search, providerFilter]);
|
||||
|
||||
// 默认只展示最新发布的一批,搜索/筛选时展示全量匹配(设上限防卡顿)
|
||||
const visible = useMemo(
|
||||
() =>
|
||||
filtered.slice(0, isFiltering ? MAX_VISIBLE_ROWS : DEFAULT_VISIBLE_ROWS),
|
||||
[filtered, isFiltering],
|
||||
);
|
||||
|
||||
// 单选:点击未选中的行替换选择,点击已选中的行取消选择。
|
||||
// 限制单选是为了避免批量导入时每条都触发一次全量零成本回填扫描(见 update_model_pricing)。
|
||||
const toggleEntry = (entry: ModelsDevEntry) => {
|
||||
setSelected((prev) => (prev?.key === entry.key ? null : entry));
|
||||
};
|
||||
|
||||
const handleImport = async () => {
|
||||
if (!selected) return;
|
||||
|
||||
try {
|
||||
await updatePricing.mutateAsync({
|
||||
modelId: selected.normalizedId,
|
||||
displayName: selected.modelName,
|
||||
inputCost: formatPrice(selected.input),
|
||||
outputCost: formatPrice(selected.output),
|
||||
cacheReadCost: formatPrice(selected.cacheRead),
|
||||
cacheCreationCost: formatPrice(selected.cacheWrite),
|
||||
});
|
||||
|
||||
toast.success(
|
||||
t("usage.modelsDevImported", {
|
||||
name: selected.modelName,
|
||||
defaultValue: "已导入 {{name}} 的定价",
|
||||
}),
|
||||
{ closeButton: true },
|
||||
);
|
||||
onImported();
|
||||
} catch (error) {
|
||||
toast.error(String(error));
|
||||
}
|
||||
};
|
||||
|
||||
const priceColumns = (entry: ModelsDevEntry) =>
|
||||
[
|
||||
{ label: t("usage.inputCost", "输入成本"), value: entry.input },
|
||||
{ label: t("usage.outputCost", "输出成本"), value: entry.output },
|
||||
{ label: t("usage.cacheReadCost", "缓存命中"), value: entry.cacheRead },
|
||||
{
|
||||
label: t("usage.cacheWriteCost", "缓存创建"),
|
||||
value: entry.cacheWrite,
|
||||
},
|
||||
] as const;
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen && !updatePricing.isPending) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
zIndex="top"
|
||||
className="max-w-3xl h-[80vh]"
|
||||
onEscapeKeyDown={(e) => {
|
||||
// 在搜索框里按 ESC 不应关闭弹窗丢掉已选模型(与 FullScreenPanel 的约定一致)
|
||||
if (isTextEditableTarget(e.target)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{t("usage.modelsDevPickerTitle", "从 models.dev 导入定价")}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t(
|
||||
"usage.modelsDevPickerDesc",
|
||||
"选择要导入的模型(价格单位:USD / 百万 tokens),每次导入一个",
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-1 min-h-0 flex-col gap-3 px-6 py-4">
|
||||
{isLoading ? (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription className="flex items-center justify-between gap-3">
|
||||
<span>
|
||||
{t("usage.modelsDevLoadError", "加载 models.dev 数据失败")}:{" "}
|
||||
{error instanceof Error ? error.message : String(error)}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => refetch()}
|
||||
className="shrink-0"
|
||||
>
|
||||
{t("usage.modelsDevRetry", "重试")}
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<Select
|
||||
value={providerFilter}
|
||||
onValueChange={setProviderFilter}
|
||||
>
|
||||
<SelectTrigger className="w-44 shrink-0">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="z-[120] max-h-[min(24rem,var(--radix-select-content-available-height))]">
|
||||
<SelectItem value="all">
|
||||
{t("usage.modelsDevAllProviders", "全部供应商")}
|
||||
</SelectItem>
|
||||
{providers.map((provider) => (
|
||||
<SelectItem key={provider.id} value={provider.id}>
|
||||
{provider.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={t(
|
||||
"usage.modelsDevSearchPlaceholder",
|
||||
"搜索模型或供应商(全量搜索)...",
|
||||
)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto rounded-md border border-border/50">
|
||||
{filtered.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center py-8 text-sm text-muted-foreground">
|
||||
{t("usage.modelsDevNoResults", "没有匹配的模型")}
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-border/30">
|
||||
{visible.map((entry) => (
|
||||
<div
|
||||
key={entry.key}
|
||||
role="button"
|
||||
aria-pressed={selected?.key === entry.key}
|
||||
onClick={() => toggleEntry(entry)}
|
||||
className={`flex cursor-pointer items-center gap-3 px-3 py-2 ${
|
||||
selected?.key === entry.key
|
||||
? "bg-accent/50"
|
||||
: "hover:bg-muted/40"
|
||||
}`}
|
||||
>
|
||||
<Check
|
||||
className={`h-4 w-4 shrink-0 text-primary ${
|
||||
selected?.key === entry.key
|
||||
? "visible"
|
||||
: "invisible"
|
||||
}`}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-medium">
|
||||
{entry.modelName}
|
||||
</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{entry.providerName}
|
||||
</span>
|
||||
{entry.releaseDate && (
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/70">
|
||||
{entry.releaseDate}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className="truncate font-mono text-xs text-muted-foreground"
|
||||
title={entry.modelId}
|
||||
>
|
||||
{entry.normalizedId}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-3 text-right">
|
||||
{priceColumns(entry).map((column) => (
|
||||
<div key={column.label} className="w-16">
|
||||
<div className="text-[10px] text-muted-foreground">
|
||||
{column.label}
|
||||
</div>
|
||||
<div className="font-mono text-xs">
|
||||
${formatPrice(column.value)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{filtered.length > visible.length && (
|
||||
<div className="px-3 py-2 text-center text-xs text-muted-foreground">
|
||||
{isFiltering
|
||||
? t("usage.modelsDevTruncated", {
|
||||
shown: visible.length,
|
||||
total: filtered.length,
|
||||
defaultValue:
|
||||
"仅显示前 {{shown}} 条,共 {{total}} 条结果,请缩小搜索范围",
|
||||
})
|
||||
: t("usage.modelsDevDefaultHint", {
|
||||
shown: visible.length,
|
||||
total: filtered.length,
|
||||
defaultValue:
|
||||
"默认展示最新发布的 {{shown}} 个模型(共 {{total}} 个),输入关键字可全量搜索",
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
disabled={updatePricing.isPending}
|
||||
>
|
||||
{t("common.cancel", "取消")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleImport}
|
||||
disabled={!selected || updatePricing.isPending}
|
||||
>
|
||||
{updatePricing.isPending ? (
|
||||
<>
|
||||
<Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
|
||||
{t("usage.modelsDevImporting", "导入中...")}
|
||||
</>
|
||||
) : (
|
||||
t("usage.modelsDevImportButton", "导入")
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { Save, Plus } from "lucide-react";
|
||||
import { Save, Plus, Globe } from "lucide-react";
|
||||
import { FullScreenPanel } from "@/components/common/FullScreenPanel";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { useUpdateModelPricing } from "@/lib/query/usage";
|
||||
import { isNonNegativeDecimalString, type ModelPricing } from "@/types/usage";
|
||||
import { ModelsDevPickerDialog } from "./ModelsDevPickerDialog";
|
||||
|
||||
interface PricingEditModalProps {
|
||||
open: boolean;
|
||||
@@ -26,6 +27,7 @@ export function PricingEditModal({
|
||||
}: PricingEditModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const updatePricing = useUpdateModelPricing();
|
||||
const [isPickerOpen, setIsPickerOpen] = useState(false);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
modelId: model.modelId,
|
||||
@@ -111,6 +113,27 @@ export function PricingEditModal({
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{isNew && (
|
||||
<div className="mb-6 flex items-center justify-between gap-3 rounded-md border border-border/50 bg-muted/20 px-3 py-2.5">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"usage.modelsDevHint",
|
||||
"无需手动填写,可从 models.dev 选择模型定价",
|
||||
)}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setIsPickerOpen(true)}
|
||||
className="shrink-0"
|
||||
>
|
||||
<Globe className="mr-1.5 h-4 w-4" />
|
||||
{t("usage.importFromModelsDev", "从 models.dev 导入")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form id="pricing-form" onSubmit={handleSubmit} className="space-y-6">
|
||||
{isNew && (
|
||||
<div className="space-y-2">
|
||||
@@ -220,6 +243,17 @@ export function PricingEditModal({
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{isNew && isPickerOpen && (
|
||||
<ModelsDevPickerDialog
|
||||
open={isPickerOpen}
|
||||
onClose={() => setIsPickerOpen(false)}
|
||||
onImported={() => {
|
||||
setIsPickerOpen(false);
|
||||
onClose();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FullScreenPanel>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -108,9 +108,18 @@ export function UsageDashboard() {
|
||||
return getUsageRangePresetLabel(range.preset, t);
|
||||
}
|
||||
|
||||
return `${new Date(resolvedRange.startDate * 1000).toLocaleString(locale)} - ${new Date(
|
||||
resolvedRange.endDate * 1000,
|
||||
).toLocaleString(locale)}`;
|
||||
const startStr = new Date(resolvedRange.startDate * 1000).toLocaleString(
|
||||
locale,
|
||||
);
|
||||
|
||||
if (range.liveEndTime) {
|
||||
return `${startStr} → ${t("usage.liveEndTimeNow", "现在")}`;
|
||||
}
|
||||
|
||||
const endStr = new Date(resolvedRange.endDate * 1000).toLocaleString(
|
||||
locale,
|
||||
);
|
||||
return `${startStr} - ${endStr}`;
|
||||
}, [locale, range, resolvedRange.endDate, resolvedRange.startDate, t]);
|
||||
|
||||
// 顶栏下拉的选项池:Provider 列表只跟应用/时间范围走(不受自身选中值影响),
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
ChevronRight,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Popover,
|
||||
@@ -117,6 +118,9 @@ export function UsageDateRangePicker({
|
||||
);
|
||||
const [draftStart, setDraftStart] = useState(resolvedRange.startDate);
|
||||
const [draftEnd, setDraftEnd] = useState(resolvedRange.endDate);
|
||||
const [draftLiveEnd, setDraftLiveEnd] = useState(
|
||||
selection.preset === "custom" ? (selection.liveEndTime ?? false) : false,
|
||||
);
|
||||
const [displayMonth, setDisplayMonth] = useState(
|
||||
() =>
|
||||
new Date(
|
||||
@@ -136,6 +140,9 @@ export function UsageDateRangePicker({
|
||||
const r = resolveUsageRange(selection);
|
||||
setDraftStart(r.startDate);
|
||||
setDraftEnd(r.endDate);
|
||||
setDraftLiveEnd(
|
||||
selection.preset === "custom" ? (selection.liveEndTime ?? false) : false,
|
||||
);
|
||||
setDisplayMonth(
|
||||
new Date(
|
||||
fromTs(r.startDate).getFullYear(),
|
||||
@@ -147,6 +154,15 @@ export function UsageDateRangePicker({
|
||||
setError(null);
|
||||
}, [open, selection]);
|
||||
|
||||
// Keep draftEnd ticking when live mode is active and popover is open
|
||||
useEffect(() => {
|
||||
if (!open || !draftLiveEnd) return;
|
||||
const tick = () => setDraftEnd(Math.floor(Date.now() / 1000));
|
||||
tick();
|
||||
const id = setInterval(tick, 1000);
|
||||
return () => clearInterval(id);
|
||||
}, [open, draftLiveEnd]);
|
||||
|
||||
const calendarDays = useMemo(
|
||||
() => getCalendarDays(displayMonth),
|
||||
[displayMonth],
|
||||
@@ -169,6 +185,14 @@ export function UsageDateRangePicker({
|
||||
/* Pick a date from the calendar */
|
||||
const handleDatePick = (day: Date) => {
|
||||
setError(null);
|
||||
|
||||
// When live end time is active, calendar only controls start date
|
||||
if (draftLiveEnd) {
|
||||
const nextTs = setDateKeepTime(draftStart, day);
|
||||
setDraftStart(nextTs);
|
||||
return;
|
||||
}
|
||||
|
||||
const nextTs = setDateKeepTime(
|
||||
activeField === "start" ? draftStart : draftEnd,
|
||||
day,
|
||||
@@ -211,6 +235,7 @@ export function UsageDateRangePicker({
|
||||
preset: "custom",
|
||||
customStartDate: draftStart,
|
||||
customEndDate: draftEnd,
|
||||
liveEndTime: draftLiveEnd,
|
||||
});
|
||||
setOpen(false);
|
||||
};
|
||||
@@ -222,6 +247,7 @@ export function UsageDateRangePicker({
|
||||
/* ── Field card (start / end) ── */
|
||||
const renderField = (field: DraftField) => {
|
||||
const isActive = activeField === field;
|
||||
const isEndLive = field === "end" && draftLiveEnd;
|
||||
const ts = field === "start" ? draftStart : draftEnd;
|
||||
const setTs = field === "start" ? setDraftStart : setDraftEnd;
|
||||
const label =
|
||||
@@ -232,12 +258,16 @@ export function UsageDateRangePicker({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-lg border px-3 py-2 cursor-pointer transition-all",
|
||||
isActive
|
||||
? "border-primary ring-1 ring-primary/30 bg-primary/5"
|
||||
: "border-border/50 hover:border-border",
|
||||
"rounded-lg border px-3 py-2 transition-all",
|
||||
isEndLive
|
||||
? "border-border/30 bg-muted/30 cursor-not-allowed opacity-50"
|
||||
: isActive
|
||||
? "border-primary ring-1 ring-primary/30 bg-primary/5 cursor-pointer"
|
||||
: "border-border/50 hover:border-border cursor-pointer",
|
||||
)}
|
||||
onClick={() => setActiveField(field)}
|
||||
onClick={() => {
|
||||
if (!isEndLive) setActiveField(field);
|
||||
}}
|
||||
>
|
||||
<div className="mb-1.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{label}
|
||||
@@ -245,27 +275,41 @@ export function UsageDateRangePicker({
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Input
|
||||
type="date"
|
||||
className="h-7 flex-1 border-0 bg-transparent p-0 text-sm shadow-none focus-visible:ring-0"
|
||||
className={cn(
|
||||
"h-7 flex-1 border-0 bg-transparent p-0 text-sm shadow-none focus-visible:ring-0",
|
||||
isEndLive && "pointer-events-none",
|
||||
)}
|
||||
value={fmtDate(ts)}
|
||||
onChange={(e) => {
|
||||
if (isEndLive) return;
|
||||
const next = parseDateInput(ts, e.target.value);
|
||||
setTs(next);
|
||||
const d = fromTs(next);
|
||||
setDisplayMonth(new Date(d.getFullYear(), d.getMonth(), 1));
|
||||
setError(null);
|
||||
}}
|
||||
onFocus={() => setActiveField(field)}
|
||||
onFocus={() => {
|
||||
if (!isEndLive) setActiveField(field);
|
||||
}}
|
||||
readOnly={isEndLive}
|
||||
/>
|
||||
<Input
|
||||
type="time"
|
||||
step={60}
|
||||
className="h-7 w-[90px] flex-none border-0 bg-transparent p-0 text-sm shadow-none focus-visible:ring-0"
|
||||
className={cn(
|
||||
"h-7 w-[90px] flex-none border-0 bg-transparent p-0 text-sm shadow-none focus-visible:ring-0",
|
||||
isEndLive && "pointer-events-none",
|
||||
)}
|
||||
value={fmtTime(ts)}
|
||||
onChange={(e) => {
|
||||
if (isEndLive) return;
|
||||
setTs(parseTimeInput(ts, e.target.value));
|
||||
setError(null);
|
||||
}}
|
||||
onFocus={() => setActiveField(field)}
|
||||
onFocus={() => {
|
||||
if (!isEndLive) setActiveField(field);
|
||||
}}
|
||||
readOnly={isEndLive}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -318,6 +362,23 @@ export function UsageDateRangePicker({
|
||||
{renderField("start")}
|
||||
{renderField("end")}
|
||||
|
||||
<label className="flex items-center gap-2 cursor-pointer select-none">
|
||||
<Checkbox
|
||||
checked={draftLiveEnd}
|
||||
onCheckedChange={(checked) => {
|
||||
const live = checked === true;
|
||||
setDraftLiveEnd(live);
|
||||
if (live) {
|
||||
setDraftEnd(Math.floor(Date.now() / 1000));
|
||||
setActiveField("start");
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("usage.liveEndTime", "结束时间跟随当前时刻")}
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
|
||||
<div className="flex gap-2 pt-1">
|
||||
|
||||